3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Lars Gullik Bjønnes
8 * \author Abdelrazak Younes
11 * Full author contact details are available in file CREDITS.
19 #include "DispatchResult.h"
20 #include "FileDialog.h"
21 #include "FontLoader.h"
22 #include "GuiApplication.h"
23 #include "GuiCommandBuffer.h"
24 #include "GuiCompleter.h"
25 #include "GuiKeySymbol.h"
27 #include "GuiToolbar.h"
28 #include "GuiWorkArea.h"
29 #include "GuiProgress.h"
30 #include "LayoutBox.h"
34 #include "qt_helpers.h"
36 #include "frontends/alert.h"
38 #include "buffer_funcs.h"
40 #include "BufferList.h"
41 #include "BufferParams.h"
42 #include "BufferView.h"
44 #include "Converter.h"
46 #include "CutAndPaste.h"
48 #include "ErrorList.h"
50 #include "FuncStatus.h"
51 #include "FuncRequest.h"
55 #include "LyXAction.h"
59 #include "Paragraph.h"
60 #include "SpellChecker.h"
62 #include "TextClass.h"
67 #include "support/convert.h"
68 #include "support/debug.h"
69 #include "support/ExceptionMessage.h"
70 #include "support/FileName.h"
71 #include "support/filetools.h"
72 #include "support/gettext.h"
73 #include "support/filetools.h"
74 #include "support/ForkedCalls.h"
75 #include "support/lassert.h"
76 #include "support/lstrings.h"
77 #include "support/os.h"
78 #include "support/Package.h"
79 #include "support/Path.h"
80 #include "support/Systemcall.h"
81 #include "support/Timeout.h"
82 #include "support/ProgressInterface.h"
85 #include <QApplication>
86 #include <QCloseEvent>
88 #include <QDesktopWidget>
89 #include <QDragEnterEvent>
98 #include <QPixmapCache>
100 #include <QPushButton>
102 #include <QShowEvent>
104 #include <QStackedWidget>
105 #include <QStatusBar>
110 #include <QScrollBar>
114 #define EXPORT_in_THREAD 1
116 // QtConcurrent was introduced in Qt 4.4
117 #if (QT_VERSION >= 0x040400)
119 #include <QFutureWatcher>
120 #include <QtConcurrentRun>
123 #include "support/bind.h"
127 #ifdef HAVE_SYS_TIME_H
128 # include <sys/time.h>
136 using namespace lyx::support;
140 using support::addExtension;
141 using support::changeExtension;
142 using support::removeExtension;
148 class BackgroundWidget : public QWidget
153 LYXERR(Debug::GUI, "show banner: " << lyxrc.show_banner);
154 if (!lyxrc.show_banner)
156 /// The text to be written on top of the pixmap
157 QString const text = lyx_version ?
158 qt_("version ") + lyx_version : qt_("unknown version");
159 splash_ = getPixmap("images/", "banner", "png");
161 QPainter pain(&splash_);
162 pain.setPen(QColor(0, 0, 0));
164 // The font used to display the version info
165 font.setStyleHint(QFont::SansSerif);
166 font.setWeight(QFont::Bold);
167 font.setPointSize(int(toqstr(lyxrc.font_sizes[FONT_SIZE_LARGE]).toDouble()));
169 pain.drawText(190, 225, text);
170 setFocusPolicy(Qt::StrongFocus);
173 void paintEvent(QPaintEvent *)
175 int x = (width() - splash_.width()) / 2;
176 int y = (height() - splash_.height()) / 2;
178 pain.drawPixmap(x, y, splash_);
181 void keyPressEvent(QKeyEvent * ev)
184 setKeySymbol(&sym, ev);
186 guiApp->processKeySym(sym, q_key_state(ev->modifiers()));
198 /// Toolbar store providing access to individual toolbars by name.
199 typedef map<string, GuiToolbar *> ToolbarMap;
201 typedef shared_ptr<Dialog> DialogPtr;
206 struct GuiView::GuiViewPrivate
208 GuiViewPrivate(GuiView * gv)
209 : gv_(gv), current_work_area_(0), current_main_work_area_(0),
210 layout_(0), autosave_timeout_(5000),
213 // hardcode here the platform specific icon size
214 smallIconSize = 16; // scaling problems
215 normalIconSize = 20; // ok, default if iconsize.png is missing
216 bigIconSize = 26; // better for some math icons
218 // if it exists, use width of iconsize.png as normal size
219 QString const dir = toqstr(addPath("images", lyxrc.icon_set));
220 FileName const fn = lyx::libFileSearch(dir, "iconsize.png");
222 QImage image(toqstr(fn.absFileName()));
223 if (image.width() < int(smallIconSize))
224 normalIconSize = smallIconSize;
225 else if (image.width() > int(bigIconSize))
226 normalIconSize = bigIconSize;
228 normalIconSize = image.width();
231 splitter_ = new QSplitter;
232 bg_widget_ = new BackgroundWidget;
233 stack_widget_ = new QStackedWidget;
234 stack_widget_->addWidget(bg_widget_);
235 stack_widget_->addWidget(splitter_);
238 // TODO cleanup, remove the singleton, handle multiple Windows?
239 progress_ = ProgressInterface::instance();
240 if (!dynamic_cast<GuiProgress*>(progress_)) {
241 progress_ = new GuiProgress(); // TODO who deletes it
242 ProgressInterface::setInstance(progress_);
245 dynamic_cast<GuiProgress*>(progress_),
246 SIGNAL(updateStatusBarMessage(QString const&)),
247 gv, SLOT(updateStatusBarMessage(QString const&)));
249 dynamic_cast<GuiProgress*>(progress_),
250 SIGNAL(clearMessageText()),
251 gv, SLOT(clearMessageText()));
258 delete stack_widget_;
261 QMenu * toolBarPopup(GuiView * parent)
263 // FIXME: translation
264 QMenu * menu = new QMenu(parent);
265 QActionGroup * iconSizeGroup = new QActionGroup(parent);
267 QAction * smallIcons = new QAction(iconSizeGroup);
268 smallIcons->setText(qt_("Small-sized icons"));
269 smallIcons->setCheckable(true);
270 QObject::connect(smallIcons, SIGNAL(triggered()),
271 parent, SLOT(smallSizedIcons()));
272 menu->addAction(smallIcons);
274 QAction * normalIcons = new QAction(iconSizeGroup);
275 normalIcons->setText(qt_("Normal-sized icons"));
276 normalIcons->setCheckable(true);
277 QObject::connect(normalIcons, SIGNAL(triggered()),
278 parent, SLOT(normalSizedIcons()));
279 menu->addAction(normalIcons);
281 QAction * bigIcons = new QAction(iconSizeGroup);
282 bigIcons->setText(qt_("Big-sized icons"));
283 bigIcons->setCheckable(true);
284 QObject::connect(bigIcons, SIGNAL(triggered()),
285 parent, SLOT(bigSizedIcons()));
286 menu->addAction(bigIcons);
288 unsigned int cur = parent->iconSize().width();
289 if ( cur == parent->d.smallIconSize)
290 smallIcons->setChecked(true);
291 else if (cur == parent->d.normalIconSize)
292 normalIcons->setChecked(true);
293 else if (cur == parent->d.bigIconSize)
294 bigIcons->setChecked(true);
301 stack_widget_->setCurrentWidget(bg_widget_);
302 bg_widget_->setUpdatesEnabled(true);
303 bg_widget_->setFocus();
306 int tabWorkAreaCount()
308 return splitter_->count();
311 TabWorkArea * tabWorkArea(int i)
313 return dynamic_cast<TabWorkArea *>(splitter_->widget(i));
316 TabWorkArea * currentTabWorkArea()
318 int areas = tabWorkAreaCount();
320 // The first TabWorkArea is always the first one, if any.
321 return tabWorkArea(0);
323 for (int i = 0; i != areas; ++i) {
324 TabWorkArea * twa = tabWorkArea(i);
325 if (current_main_work_area_ == twa->currentWorkArea())
329 // None has the focus so we just take the first one.
330 return tabWorkArea(0);
333 #if (QT_VERSION >= 0x040400)
334 void setPreviewFuture(QFuture<Buffer::ExportStatus> const & f)
336 if (processing_thread_watcher_.isRunning()) {
337 // we prefer to cancel this preview in order to keep a snappy
341 processing_thread_watcher_.setFuture(f);
347 GuiWorkArea * current_work_area_;
348 GuiWorkArea * current_main_work_area_;
349 QSplitter * splitter_;
350 QStackedWidget * stack_widget_;
351 BackgroundWidget * bg_widget_;
353 ToolbarMap toolbars_;
354 ProgressInterface* progress_;
355 /// The main layout box.
357 * \warning Don't Delete! The layout box is actually owned by
358 * whichever toolbar contains it. All the GuiView class needs is a
359 * means of accessing it.
361 * FIXME: replace that with a proper model so that we are not limited
362 * to only one dialog.
367 map<string, DialogPtr> dialogs_;
369 unsigned int smallIconSize;
370 unsigned int normalIconSize;
371 unsigned int bigIconSize;
373 QTimer statusbar_timer_;
374 /// auto-saving of buffers
375 Timeout autosave_timeout_;
376 /// flag against a race condition due to multiclicks, see bug #1119
380 TocModels toc_models_;
382 #if (QT_VERSION >= 0x040400)
384 QFutureWatcher<docstring> autosave_watcher_;
385 QFutureWatcher<Buffer::ExportStatus> processing_thread_watcher_;
387 string last_export_format;
388 string processing_format;
390 struct DummyWatcher { bool isRunning(){return false;} };
391 DummyWatcher processing_thread_watcher_;
394 static QSet<Buffer const *> busyBuffers;
395 static Buffer::ExportStatus previewAndDestroy(Buffer const * orig, Buffer * buffer, string const & format);
396 static Buffer::ExportStatus exportAndDestroy(Buffer const * orig, Buffer * buffer, string const & format);
397 static Buffer::ExportStatus compileAndDestroy(Buffer const * orig, Buffer * buffer, string const & format);
398 static docstring autosaveAndDestroy(Buffer const * orig, Buffer * buffer);
401 static Buffer::ExportStatus runAndDestroy(const T& func, Buffer const * orig, Buffer * buffer, string const & format);
403 // TODO syncFunc/previewFunc: use bind
404 bool asyncBufferProcessing(string const & argument,
405 Buffer const * used_buffer,
406 docstring const & msg,
407 Buffer::ExportStatus (*asyncFunc)(Buffer const *, Buffer *, string const &),
408 Buffer::ExportStatus (Buffer::*syncFunc)(string const &, bool) const,
409 Buffer::ExportStatus (Buffer::*previewFunc)(string const &) const);
411 QVector<GuiWorkArea*> guiWorkAreas();
414 QSet<Buffer const *> GuiView::GuiViewPrivate::busyBuffers;
417 GuiView::GuiView(int id)
418 : d(*new GuiViewPrivate(this)), id_(id), closing_(false), busy_(0)
420 // GuiToolbars *must* be initialised before the menu bar.
421 normalSizedIcons(); // at least on Mac the default is 32 otherwise, which is huge
424 // set ourself as the current view. This is needed for the menu bar
425 // filling, at least for the static special menu item on Mac. Otherwise
426 // they are greyed out.
427 guiApp->setCurrentView(this);
429 // Fill up the menu bar.
430 guiApp->menus().fillMenuBar(menuBar(), this, true);
432 setCentralWidget(d.stack_widget_);
434 // Start autosave timer
435 if (lyxrc.autosave) {
436 d.autosave_timeout_.timeout.connect(bind(&GuiView::autoSave, this));
437 d.autosave_timeout_.setTimeout(lyxrc.autosave * 1000);
438 d.autosave_timeout_.start();
440 connect(&d.statusbar_timer_, SIGNAL(timeout()),
441 this, SLOT(clearMessage()));
443 // We don't want to keep the window in memory if it is closed.
444 setAttribute(Qt::WA_DeleteOnClose, true);
446 #if (!defined(Q_WS_WIN) && !defined(Q_WS_MACX))
447 // QIcon::fromTheme was introduced in Qt 4.6
448 #if (QT_VERSION >= 0x040600)
449 // assign an icon to main form. We do not do it under Qt/Win or Qt/Mac,
450 // since the icon is provided in the application bundle. We use a themed
451 // version when available and use the bundled one as fallback.
452 setWindowIcon(QIcon::fromTheme("lyx", getPixmap("images/", "lyx", "png")));
454 setWindowIcon(getPixmap("images/", "lyx", "png"));
459 #if (QT_VERSION >= 0x040300)
460 // use tabbed dock area for multiple docks
461 // (such as "source" and "messages")
462 setDockOptions(QMainWindow::ForceTabbedDocks);
466 setAcceptDrops(true);
468 #if (QT_VERSION >= 0x040400)
470 // add busy indicator to statusbar
471 QLabel * busylabel = new QLabel(statusBar());
472 statusBar()->addPermanentWidget(busylabel);
473 QString fn = toqstr(lyx::libFileSearch("images", "busy.gif").absFileName());
474 QMovie * busyanim = new QMovie(fn, QByteArray(), busylabel);
475 busylabel->setMovie(busyanim);
479 connect(&d.processing_thread_watcher_, SIGNAL(started()),
480 busylabel, SLOT(show()));
481 connect(&d.processing_thread_watcher_, SIGNAL(finished()),
482 busylabel, SLOT(hide()));
484 statusBar()->setSizeGripEnabled(true);
487 connect(&d.autosave_watcher_, SIGNAL(finished()), this,
488 SLOT(autoSaveThreadFinished()));
490 connect(&d.processing_thread_watcher_, SIGNAL(started()), this,
491 SLOT(processingThreadStarted()));
492 connect(&d.processing_thread_watcher_, SIGNAL(finished()), this,
493 SLOT(processingThreadFinished()));
497 connect(this, SIGNAL(triggerShowDialog(QString const &, QString const &, Inset *)),
498 SLOT(doShowDialog(QString const &, QString const &, Inset *)));
500 // Forbid too small unresizable window because it can happen
501 // with some window manager under X11.
502 setMinimumSize(300, 200);
504 if (lyxrc.allow_geometry_session) {
505 // Now take care of session management.
510 // no session handling, default to a sane size.
511 setGeometry(50, 50, 690, 510);
514 // clear session data if any.
516 settings.remove("views");
526 QVector<GuiWorkArea*> GuiView::GuiViewPrivate::guiWorkAreas()
528 QVector<GuiWorkArea*> areas;
529 for (int i = 0; i < tabWorkAreaCount(); i++) {
530 TabWorkArea* ta = tabWorkArea(i);
531 for (int u = 0; u < ta->count(); u++) {
532 areas << ta->workArea(u);
538 static void handleExportStatus(GuiView * view, Buffer::ExportStatus status,
539 string const & format)
541 docstring const fmt = formats.prettyName(format);
544 case Buffer::ExportSuccess:
545 msg = bformat(_("Successful export to format: %1$s"), fmt);
547 case Buffer::ExportCancel:
548 msg = _("Document export cancelled.");
550 case Buffer::ExportError:
551 case Buffer::ExportNoPathToFormat:
552 case Buffer::ExportTexPathHasSpaces:
553 case Buffer::ExportConverterError:
554 msg = bformat(_("Error while exporting format: %1$s"), fmt);
556 case Buffer::PreviewSuccess:
557 msg = bformat(_("Successful preview of format: %1$s"), fmt);
559 case Buffer::PreviewError:
560 msg = bformat(_("Error while previewing format: %1$s"), fmt);
567 #if QT_VERSION >= 0x040400
569 void GuiView::processingThreadStarted()
574 void GuiView::processingThreadFinished()
576 QFutureWatcher<Buffer::ExportStatus> const * watcher =
577 static_cast<QFutureWatcher<Buffer::ExportStatus> const *>(sender());
579 Buffer::ExportStatus const status = watcher->result();
580 handleExportStatus(this, status, d.processing_format);
583 BufferView const * const bv = currentBufferView();
584 if (bv && !bv->buffer().errorList("Export").empty()) {
588 errors(d.last_export_format);
592 void GuiView::autoSaveThreadFinished()
594 QFutureWatcher<docstring> const * watcher =
595 static_cast<QFutureWatcher<docstring> const *>(sender());
596 message(watcher->result());
602 void GuiView::processingThreadStarted()
607 void GuiView::processingThreadFinished()
612 void GuiView::autoSaveThreadFinished()
618 void GuiView::saveLayout() const
621 settings.beginGroup("views");
622 settings.beginGroup(QString::number(id_));
624 settings.setValue("pos", pos());
625 settings.setValue("size", size());
627 settings.setValue("geometry", saveGeometry());
629 settings.setValue("layout", saveState(0));
630 settings.setValue("icon_size", iconSize());
634 void GuiView::saveUISettings() const
636 // Save the toolbar private states
637 ToolbarMap::iterator end = d.toolbars_.end();
638 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
639 it->second->saveSession();
640 // Now take care of all other dialogs
641 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
642 for (; it!= d.dialogs_.end(); ++it)
643 it->second->saveSession();
647 bool GuiView::restoreLayout()
650 settings.beginGroup("views");
651 settings.beginGroup(QString::number(id_));
652 QString const icon_key = "icon_size";
653 if (!settings.contains(icon_key))
656 //code below is skipped when when ~/.config/LyX is (re)created
657 QSize icon_size = settings.value(icon_key).toSize();
658 // Check whether session size changed.
659 if (icon_size.width() != int(d.smallIconSize) &&
660 icon_size.width() != int(d.normalIconSize) &&
661 icon_size.width() != int(d.bigIconSize)) {
662 icon_size.setWidth(d.normalIconSize);
663 icon_size.setHeight(d.normalIconSize);
665 setIconSize(icon_size);
668 QPoint pos = settings.value("pos", QPoint(50, 50)).toPoint();
669 QSize size = settings.value("size", QSize(690, 510)).toSize();
673 // Work-around for bug #6034: the window ends up in an undetermined
674 // state when trying to restore a maximized window when it is
675 // already maximized.
676 if (!(windowState() & Qt::WindowMaximized))
677 if (!restoreGeometry(settings.value("geometry").toByteArray()))
678 setGeometry(50, 50, 690, 510);
680 // Make sure layout is correctly oriented.
681 setLayoutDirection(qApp->layoutDirection());
683 // Allow the toc and view-source dock widget to be restored if needed.
685 if ((dialog = findOrBuild("toc", true)))
686 // see bug 5082. At least setup title and enabled state.
687 // Visibility will be adjusted by restoreState below.
688 dialog->prepareView();
689 if ((dialog = findOrBuild("view-source", true)))
690 dialog->prepareView();
691 if ((dialog = findOrBuild("progress", true)))
692 dialog->prepareView();
693 if ((dialog = findOrBuild("findreplaceadv", true)))
694 dialog->prepareView();
696 if (!restoreState(settings.value("layout").toByteArray(), 0))
703 GuiToolbar * GuiView::toolbar(string const & name)
705 ToolbarMap::iterator it = d.toolbars_.find(name);
706 if (it != d.toolbars_.end())
709 LYXERR(Debug::GUI, "Toolbar::display: no toolbar named " << name);
714 void GuiView::constructToolbars()
716 ToolbarMap::iterator it = d.toolbars_.begin();
717 for (; it != d.toolbars_.end(); ++it)
721 // I don't like doing this here, but the standard toolbar
722 // destroys this object when it's destroyed itself (vfr)
723 d.layout_ = new LayoutBox(*this);
724 d.stack_widget_->addWidget(d.layout_);
725 d.layout_->move(0,0);
727 // extracts the toolbars from the backend
728 Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
729 Toolbars::Infos::iterator end = guiApp->toolbars().end();
730 for (; cit != end; ++cit)
731 d.toolbars_[cit->name] = new GuiToolbar(*cit, *this);
735 void GuiView::initToolbars()
737 // extracts the toolbars from the backend
738 Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
739 Toolbars::Infos::iterator end = guiApp->toolbars().end();
740 for (; cit != end; ++cit) {
741 GuiToolbar * tb = toolbar(cit->name);
744 int const visibility = guiApp->toolbars().defaultVisibility(cit->name);
745 bool newline = !(visibility & Toolbars::SAMEROW);
746 tb->setVisible(false);
747 tb->setVisibility(visibility);
749 if (visibility & Toolbars::TOP) {
751 addToolBarBreak(Qt::TopToolBarArea);
752 addToolBar(Qt::TopToolBarArea, tb);
755 if (visibility & Toolbars::BOTTOM) {
756 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
757 #if (QT_VERSION >= 0x040202)
759 addToolBarBreak(Qt::BottomToolBarArea);
761 addToolBar(Qt::BottomToolBarArea, tb);
764 if (visibility & Toolbars::LEFT) {
765 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
766 #if (QT_VERSION >= 0x040202)
768 addToolBarBreak(Qt::LeftToolBarArea);
770 addToolBar(Qt::LeftToolBarArea, tb);
773 if (visibility & Toolbars::RIGHT) {
774 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
775 #if (QT_VERSION >= 0x040202)
777 addToolBarBreak(Qt::RightToolBarArea);
779 addToolBar(Qt::RightToolBarArea, tb);
782 if (visibility & Toolbars::ON)
783 tb->setVisible(true);
788 TocModels & GuiView::tocModels()
790 return d.toc_models_;
794 void GuiView::setFocus()
796 LYXERR(Debug::DEBUG, "GuiView::setFocus()" << this);
797 QMainWindow::setFocus();
801 void GuiView::focusInEvent(QFocusEvent * e)
803 LYXERR(Debug::DEBUG, "GuiView::focusInEvent()" << this);
804 QMainWindow::focusInEvent(e);
805 // Make sure guiApp points to the correct view.
806 guiApp->setCurrentView(this);
807 if (currentWorkArea())
808 currentWorkArea()->setFocus();
809 else if (currentMainWorkArea())
810 currentMainWorkArea()->setFocus();
812 d.bg_widget_->setFocus();
816 QMenu * GuiView::createPopupMenu()
818 return d.toolBarPopup(this);
822 void GuiView::showEvent(QShowEvent * e)
824 LYXERR(Debug::GUI, "Passed Geometry "
825 << size().height() << "x" << size().width()
826 << "+" << pos().x() << "+" << pos().y());
828 if (d.splitter_->count() == 0)
829 // No work area, switch to the background widget.
833 QMainWindow::showEvent(e);
837 bool GuiView::closeScheduled()
844 /** Destroy only all tabbed WorkAreas. Destruction of other WorkAreas
845 ** is responsibility of the container (e.g., dialog)
847 void GuiView::closeEvent(QCloseEvent * close_event)
849 LYXERR(Debug::DEBUG, "GuiView::closeEvent()");
851 if (!GuiViewPrivate::busyBuffers.isEmpty()) {
852 Alert::warning(_("Exit LyX"),
853 _("LyX could not be closed because documents are being processed by LyX."));
854 close_event->setAccepted(false);
858 // If the user pressed the x (so we didn't call closeView
859 // programmatically), we want to clear all existing entries.
861 theSession().lastOpened().clear();
866 // it can happen that this event arrives without selecting the view,
867 // e.g. when clicking the close button on a background window.
869 if (!closeWorkAreaAll()) {
871 close_event->ignore();
875 // Make sure that nothing will use this to be closed View.
876 guiApp->unregisterView(this);
878 if (isFullScreen()) {
879 // Switch off fullscreen before closing.
884 // Make sure the timer time out will not trigger a statusbar update.
885 d.statusbar_timer_.stop();
887 // Saving fullscreen requires additional tweaks in the toolbar code.
888 // It wouldn't also work under linux natively.
889 if (lyxrc.allow_geometry_session) {
894 close_event->accept();
898 void GuiView::dragEnterEvent(QDragEnterEvent * event)
900 if (event->mimeData()->hasUrls())
902 /// \todo Ask lyx-devel is this is enough:
903 /// if (event->mimeData()->hasFormat("text/plain"))
904 /// event->acceptProposedAction();
908 void GuiView::dropEvent(QDropEvent * event)
910 QList<QUrl> files = event->mimeData()->urls();
914 LYXERR(Debug::GUI, "GuiView::dropEvent: got URLs!");
915 for (int i = 0; i != files.size(); ++i) {
916 string const file = os::internal_path(fromqstr(
917 files.at(i).toLocalFile()));
921 string const ext = support::getExtension(file);
922 vector<const Format *> found_formats;
924 // Find all formats that have the correct extension.
925 vector<const Format *> const & import_formats
926 = theConverters().importableFormats();
927 vector<const Format *>::const_iterator it = import_formats.begin();
928 for (; it != import_formats.end(); ++it)
929 if ((*it)->hasExtension(ext))
930 found_formats.push_back(*it);
933 if (found_formats.size() >= 1) {
934 if (found_formats.size() > 1) {
935 //FIXME: show a dialog to choose the correct importable format
937 "Multiple importable formats found, selecting first");
939 string const arg = found_formats[0]->name() + " " + file;
940 cmd = FuncRequest(LFUN_BUFFER_IMPORT, arg);
943 //FIXME: do we have to explicitly check whether it's a lyx file?
945 "No formats found, trying to open it as a lyx file");
946 cmd = FuncRequest(LFUN_FILE_OPEN, file);
948 // add the functions to the queue
949 guiApp->addToFuncRequestQueue(cmd);
952 // now process the collected functions. We perform the events
953 // asynchronously. This prevents potential problems in case the
954 // BufferView is closed within an event.
955 guiApp->processFuncRequestQueueAsync();
959 void GuiView::message(docstring const & str)
961 if (ForkedProcess::iAmAChild())
964 // call is moved to GUI-thread by GuiProgress
965 d.progress_->appendMessage(toqstr(str));
969 void GuiView::clearMessageText()
971 message(docstring());
975 void GuiView::updateStatusBarMessage(QString const & str)
977 statusBar()->showMessage(str);
978 d.statusbar_timer_.stop();
979 d.statusbar_timer_.start(3000);
983 void GuiView::smallSizedIcons()
985 setIconSize(QSize(d.smallIconSize, d.smallIconSize));
989 void GuiView::normalSizedIcons()
991 setIconSize(QSize(d.normalIconSize, d.normalIconSize));
995 void GuiView::bigSizedIcons()
997 setIconSize(QSize(d.bigIconSize, d.bigIconSize));
1001 void GuiView::clearMessage()
1003 // FIXME: This code was introduced in r19643 to fix bug #4123. However,
1004 // the hasFocus function mostly returns false, even if the focus is on
1005 // a workarea in this view.
1009 d.statusbar_timer_.stop();
1013 void GuiView::updateWindowTitle(GuiWorkArea * wa)
1015 if (wa != d.current_work_area_
1016 || wa->bufferView().buffer().isInternal())
1018 setWindowTitle(qt_("LyX: ") + wa->windowTitle());
1019 setWindowIconText(wa->windowIconText());
1023 void GuiView::on_currentWorkAreaChanged(GuiWorkArea * wa)
1025 QObject::disconnect(d.current_work_area_, SIGNAL(busy(bool)),
1026 this, SLOT(setBusy(bool)));
1028 disconnectBufferView();
1029 connectBufferView(wa->bufferView());
1030 connectBuffer(wa->bufferView().buffer());
1031 d.current_work_area_ = wa;
1032 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
1033 this, SLOT(updateWindowTitle(GuiWorkArea *)));
1034 QObject::connect(wa, SIGNAL(busy(bool)), this, SLOT(setBusy(bool)));
1035 updateWindowTitle(wa);
1039 // The document settings needs to be reinitialised.
1040 updateDialog("document", "");
1042 // Buffer-dependent dialogs must be updated. This is done here because
1043 // some dialogs require buffer()->text.
1048 void GuiView::on_lastWorkAreaRemoved()
1051 // We already are in a close event. Nothing more to do.
1054 if (d.splitter_->count() > 1)
1055 // We have a splitter so don't close anything.
1058 // Reset and updates the dialogs.
1059 d.toc_models_.reset(0);
1060 updateDialog("document", "");
1063 resetWindowTitleAndIconText();
1066 if (lyxrc.open_buffers_in_tabs)
1067 // Nothing more to do, the window should stay open.
1070 if (guiApp->viewIds().size() > 1) {
1076 // On Mac we also close the last window because the application stay
1077 // resident in memory. On other platforms we don't close the last
1078 // window because this would quit the application.
1084 void GuiView::updateStatusBar()
1086 // let the user see the explicit message
1087 if (d.statusbar_timer_.isActive())
1094 void GuiView::showMessage()
1096 QString msg = toqstr(theGuiApp()->viewStatusMessage());
1097 if (msg.isEmpty()) {
1098 BufferView const * bv = currentBufferView();
1100 msg = toqstr(bv->cursor().currentState());
1102 msg = qt_("Welcome to LyX!");
1104 statusBar()->showMessage(msg);
1108 bool GuiView::event(QEvent * e)
1112 // Useful debug code:
1113 //case QEvent::ActivationChange:
1114 //case QEvent::WindowDeactivate:
1115 //case QEvent::Paint:
1116 //case QEvent::Enter:
1117 //case QEvent::Leave:
1118 //case QEvent::HoverEnter:
1119 //case QEvent::HoverLeave:
1120 //case QEvent::HoverMove:
1121 //case QEvent::StatusTip:
1122 //case QEvent::DragEnter:
1123 //case QEvent::DragLeave:
1124 //case QEvent::Drop:
1127 case QEvent::WindowActivate: {
1128 GuiView * old_view = guiApp->currentView();
1129 if (this == old_view) {
1131 return QMainWindow::event(e);
1133 if (old_view && old_view->currentBufferView()) {
1134 // save current selection to the selection buffer to allow
1135 // middle-button paste in this window.
1136 cap::saveSelection(old_view->currentBufferView()->cursor());
1138 guiApp->setCurrentView(this);
1139 if (d.current_work_area_) {
1140 BufferView & bv = d.current_work_area_->bufferView();
1141 connectBufferView(bv);
1142 connectBuffer(bv.buffer());
1143 // The document structure, name and dialogs might have
1144 // changed in another view.
1146 // The document settings needs to be reinitialised.
1147 updateDialog("document", "");
1150 resetWindowTitleAndIconText();
1153 return QMainWindow::event(e);
1156 case QEvent::ShortcutOverride: {
1159 #if (!defined Q_WS_X11) || (QT_VERSION >= 0x040500)
1160 if (isFullScreen() && menuBar()->isHidden()) {
1161 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
1162 // FIXME: we should also try to detect special LyX shortcut such as
1163 // Alt-P and Alt-M. Right now there is a hack in
1164 // GuiWorkArea::processKeySym() that hides again the menubar for
1166 if (ke->modifiers() & Qt::AltModifier && ke->key() != Qt::Key_Alt) {
1168 return QMainWindow::event(e);
1172 return QMainWindow::event(e);
1176 return QMainWindow::event(e);
1180 void GuiView::resetWindowTitleAndIconText()
1182 setWindowTitle(qt_("LyX"));
1183 setWindowIconText(qt_("LyX"));
1186 bool GuiView::focusNextPrevChild(bool /*next*/)
1193 bool GuiView::busy() const
1199 void GuiView::setBusy(bool busy)
1201 bool const busy_before = busy_ > 0;
1202 busy ? ++busy_ : --busy_;
1203 if ((busy_ > 0) == busy_before)
1204 // busy state didn't change
1208 QApplication::setOverrideCursor(Qt::WaitCursor);
1211 QApplication::restoreOverrideCursor();
1216 GuiWorkArea * GuiView::workArea(int index)
1218 if (TabWorkArea * twa = d.currentTabWorkArea())
1219 if (index < twa->count())
1220 return dynamic_cast<GuiWorkArea *>(twa->widget(index));
1225 GuiWorkArea * GuiView::workArea(Buffer & buffer)
1227 if (currentWorkArea()
1228 && ¤tWorkArea()->bufferView().buffer() == &buffer)
1229 return (GuiWorkArea *) currentWorkArea();
1230 if (TabWorkArea * twa = d.currentTabWorkArea())
1231 return twa->workArea(buffer);
1236 GuiWorkArea * GuiView::addWorkArea(Buffer & buffer)
1238 // Automatically create a TabWorkArea if there are none yet.
1239 TabWorkArea * tab_widget = d.splitter_->count()
1240 ? d.currentTabWorkArea() : addTabWorkArea();
1241 return tab_widget->addWorkArea(buffer, *this);
1245 TabWorkArea * GuiView::addTabWorkArea()
1247 TabWorkArea * twa = new TabWorkArea;
1248 QObject::connect(twa, SIGNAL(currentWorkAreaChanged(GuiWorkArea *)),
1249 this, SLOT(on_currentWorkAreaChanged(GuiWorkArea *)));
1250 QObject::connect(twa, SIGNAL(lastWorkAreaRemoved()),
1251 this, SLOT(on_lastWorkAreaRemoved()));
1253 d.splitter_->addWidget(twa);
1254 d.stack_widget_->setCurrentWidget(d.splitter_);
1259 GuiWorkArea const * GuiView::currentWorkArea() const
1261 return d.current_work_area_;
1265 GuiWorkArea * GuiView::currentWorkArea()
1267 return d.current_work_area_;
1271 GuiWorkArea const * GuiView::currentMainWorkArea() const
1273 if (!d.currentTabWorkArea())
1275 return d.currentTabWorkArea()->currentWorkArea();
1279 GuiWorkArea * GuiView::currentMainWorkArea()
1281 if (!d.currentTabWorkArea())
1283 return d.currentTabWorkArea()->currentWorkArea();
1287 void GuiView::setCurrentWorkArea(GuiWorkArea * wa)
1289 LYXERR(Debug::DEBUG, "Setting current wa: " << wa << endl);
1291 d.current_work_area_ = 0;
1296 // FIXME: I've no clue why this is here and why it accesses
1297 // theGuiApp()->currentView, which might be 0 (bug 6464).
1298 // See also 27525 (vfr).
1299 if (theGuiApp()->currentView() == this
1300 && theGuiApp()->currentView()->currentWorkArea() == wa)
1303 if (currentBufferView())
1304 cap::saveSelection(currentBufferView()->cursor());
1306 theGuiApp()->setCurrentView(this);
1307 d.current_work_area_ = wa;
1309 // We need to reset this now, because it will need to be
1310 // right if the tabWorkArea gets reset in the for loop. We
1311 // will change it back if we aren't in that case.
1312 GuiWorkArea * const old_cmwa = d.current_main_work_area_;
1313 d.current_main_work_area_ = wa;
1315 for (int i = 0; i != d.splitter_->count(); ++i) {
1316 if (d.tabWorkArea(i)->setCurrentWorkArea(wa)) {
1317 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea()
1318 << ", Current main wa: " << currentMainWorkArea());
1323 d.current_main_work_area_ = old_cmwa;
1325 LYXERR(Debug::DEBUG, "This is not a tabbed wa");
1326 on_currentWorkAreaChanged(wa);
1327 BufferView & bv = wa->bufferView();
1328 bv.cursor().fixIfBroken();
1330 wa->setUpdatesEnabled(true);
1331 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() << ", Current main wa: " << currentMainWorkArea());
1335 void GuiView::removeWorkArea(GuiWorkArea * wa)
1337 LASSERT(wa, return);
1338 if (wa == d.current_work_area_) {
1340 disconnectBufferView();
1341 d.current_work_area_ = 0;
1342 d.current_main_work_area_ = 0;
1345 bool found_twa = false;
1346 for (int i = 0; i != d.splitter_->count(); ++i) {
1347 TabWorkArea * twa = d.tabWorkArea(i);
1348 if (twa->removeWorkArea(wa)) {
1349 // Found in this tab group, and deleted the GuiWorkArea.
1351 if (twa->count() != 0) {
1352 if (d.current_work_area_ == 0)
1353 // This means that we are closing the current GuiWorkArea, so
1354 // switch to the next GuiWorkArea in the found TabWorkArea.
1355 setCurrentWorkArea(twa->currentWorkArea());
1357 // No more WorkAreas in this tab group, so delete it.
1364 // It is not a tabbed work area (i.e., the search work area), so it
1365 // should be deleted by other means.
1366 LASSERT(found_twa, /* */);
1368 if (d.current_work_area_ == 0) {
1369 if (d.splitter_->count() != 0) {
1370 TabWorkArea * twa = d.currentTabWorkArea();
1371 setCurrentWorkArea(twa->currentWorkArea());
1373 // No more work areas, switch to the background widget.
1374 setCurrentWorkArea(0);
1380 LayoutBox * GuiView::getLayoutDialog() const
1386 void GuiView::updateLayoutList()
1389 d.layout_->updateContents(false);
1393 void GuiView::updateToolbars()
1395 ToolbarMap::iterator end = d.toolbars_.end();
1396 if (d.current_work_area_) {
1398 d.current_work_area_->bufferView().cursor().inMathed()
1399 && !d.current_work_area_->bufferView().cursor().inRegexped();
1401 lyx::getStatus(FuncRequest(LFUN_LAYOUT_TABULAR)).enabled();
1403 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).enabled() &&
1404 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).onOff(true);
1405 bool const mathmacrotemplate =
1406 lyx::getStatus(FuncRequest(LFUN_IN_MATHMACROTEMPLATE)).enabled();
1408 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1409 it->second->update(math, table, review, mathmacrotemplate);
1411 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1412 it->second->update(false, false, false, false);
1416 void GuiView::setBuffer(Buffer * newBuffer)
1418 LYXERR(Debug::DEBUG, "Setting buffer: " << newBuffer << endl);
1419 LASSERT(newBuffer, return);
1421 GuiWorkArea * wa = workArea(*newBuffer);
1424 newBuffer->masterBuffer()->updateBuffer();
1426 wa = addWorkArea(*newBuffer);
1427 // scroll to the position when the BufferView was last closed
1428 if (lyxrc.use_lastfilepos) {
1429 LastFilePosSection::FilePos filepos =
1430 theSession().lastFilePos().load(newBuffer->fileName());
1431 wa->bufferView().moveToPosition(filepos.pit, filepos.pos, 0, 0);
1434 //Disconnect the old buffer...there's no new one.
1437 connectBuffer(*newBuffer);
1438 connectBufferView(wa->bufferView());
1439 setCurrentWorkArea(wa);
1443 void GuiView::connectBuffer(Buffer & buf)
1445 buf.setGuiDelegate(this);
1449 void GuiView::disconnectBuffer()
1451 if (d.current_work_area_)
1452 d.current_work_area_->bufferView().buffer().setGuiDelegate(0);
1456 void GuiView::connectBufferView(BufferView & bv)
1458 bv.setGuiDelegate(this);
1462 void GuiView::disconnectBufferView()
1464 if (d.current_work_area_)
1465 d.current_work_area_->bufferView().setGuiDelegate(0);
1469 void GuiView::errors(string const & error_type, bool from_master)
1471 BufferView const * const bv = currentBufferView();
1475 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
1476 // We are called with from_master == false by default, so we
1477 // have to figure out whether that is the case or not.
1478 ErrorList & el = bv->buffer().errorList(error_type);
1480 el = bv->buffer().masterBuffer()->errorList(error_type);
1484 ErrorList const & el = from_master ?
1485 bv->buffer().masterBuffer()->errorList(error_type) :
1486 bv->buffer().errorList(error_type);
1492 string data = error_type;
1494 data = "from_master|" + error_type;
1495 showDialog("errorlist", data);
1499 void GuiView::updateTocItem(string const & type, DocIterator const & dit)
1501 d.toc_models_.updateItem(toqstr(type), dit);
1505 void GuiView::structureChanged()
1507 d.toc_models_.reset(documentBufferView());
1508 // Navigator needs more than a simple update in this case. It needs to be
1510 updateDialog("toc", "");
1514 void GuiView::updateDialog(string const & name, string const & data)
1516 if (!isDialogVisible(name))
1519 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
1520 if (it == d.dialogs_.end())
1523 Dialog * const dialog = it->second.get();
1524 if (dialog->isVisibleView())
1525 dialog->initialiseParams(data);
1529 BufferView * GuiView::documentBufferView()
1531 return currentMainWorkArea()
1532 ? ¤tMainWorkArea()->bufferView()
1537 BufferView const * GuiView::documentBufferView() const
1539 return currentMainWorkArea()
1540 ? ¤tMainWorkArea()->bufferView()
1545 BufferView * GuiView::currentBufferView()
1547 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1551 BufferView const * GuiView::currentBufferView() const
1553 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1557 #if (QT_VERSION >= 0x040400)
1558 docstring GuiView::GuiViewPrivate::autosaveAndDestroy(
1559 Buffer const * orig, Buffer * clone)
1561 bool const success = clone->autoSave();
1563 busyBuffers.remove(orig);
1565 ? _("Automatic save done.")
1566 : _("Automatic save failed!");
1571 void GuiView::autoSave()
1573 LYXERR(Debug::INFO, "Running autoSave()");
1575 Buffer * buffer = documentBufferView()
1576 ? &documentBufferView()->buffer() : 0;
1578 resetAutosaveTimers();
1582 #if (QT_VERSION >= 0x040400)
1583 GuiViewPrivate::busyBuffers.insert(buffer);
1584 QFuture<docstring> f = QtConcurrent::run(GuiViewPrivate::autosaveAndDestroy,
1585 buffer, buffer->cloneBufferOnly());
1586 d.autosave_watcher_.setFuture(f);
1590 resetAutosaveTimers();
1594 void GuiView::resetAutosaveTimers()
1597 d.autosave_timeout_.restart();
1601 bool GuiView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1604 Buffer * buf = currentBufferView()
1605 ? ¤tBufferView()->buffer() : 0;
1606 Buffer * doc_buffer = documentBufferView()
1607 ? &(documentBufferView()->buffer()) : 0;
1609 // Check whether we need a buffer
1610 if (!lyxaction.funcHasFlag(cmd.action(), LyXAction::NoBuffer) && !buf) {
1611 // no, exit directly
1612 flag.message(from_utf8(N_("Command not allowed with"
1613 "out any document open")));
1614 flag.setEnabled(false);
1618 if (cmd.origin() == FuncRequest::TOC) {
1619 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
1620 if (!toc || !toc->getStatus(documentBufferView()->cursor(), cmd, flag))
1621 flag.setEnabled(false);
1625 switch(cmd.action()) {
1626 case LFUN_BUFFER_IMPORT:
1629 case LFUN_MASTER_BUFFER_UPDATE:
1630 case LFUN_MASTER_BUFFER_VIEW:
1631 enable = doc_buffer && doc_buffer->parent() != 0
1632 && !d.processing_thread_watcher_.isRunning();
1635 case LFUN_BUFFER_UPDATE:
1636 case LFUN_BUFFER_VIEW: {
1637 if (!doc_buffer || d.processing_thread_watcher_.isRunning()) {
1641 string format = to_utf8(cmd.argument());
1642 if (cmd.argument().empty())
1643 format = doc_buffer->params().getDefaultOutputFormat();
1644 enable = doc_buffer->params().isExportableFormat(format);
1648 case LFUN_BUFFER_RELOAD:
1649 enable = doc_buffer && !doc_buffer->isUnnamed()
1650 && doc_buffer->fileName().exists()
1651 && (!doc_buffer->isClean()
1652 || doc_buffer->isExternallyModified(Buffer::timestamp_method));
1655 case LFUN_BUFFER_CHILD_OPEN:
1656 enable = doc_buffer;
1659 case LFUN_BUFFER_WRITE:
1660 enable = doc_buffer && (doc_buffer->isUnnamed() || !doc_buffer->isClean());
1663 //FIXME: This LFUN should be moved to GuiApplication.
1664 case LFUN_BUFFER_WRITE_ALL: {
1665 // We enable the command only if there are some modified buffers
1666 Buffer * first = theBufferList().first();
1671 // We cannot use a for loop as the buffer list is a cycle.
1673 if (!b->isClean()) {
1677 b = theBufferList().next(b);
1678 } while (b != first);
1682 case LFUN_BUFFER_WRITE_AS:
1683 case LFUN_BUFFER_EXPORT_AS:
1684 enable = doc_buffer;
1687 case LFUN_BUFFER_CLOSE:
1688 enable = doc_buffer;
1691 case LFUN_BUFFER_CLOSE_ALL:
1692 enable = theBufferList().last() != theBufferList().first();
1695 case LFUN_SPLIT_VIEW:
1696 if (cmd.getArg(0) == "vertical")
1697 enable = doc_buffer && (d.splitter_->count() == 1 ||
1698 d.splitter_->orientation() == Qt::Vertical);
1700 enable = doc_buffer && (d.splitter_->count() == 1 ||
1701 d.splitter_->orientation() == Qt::Horizontal);
1704 case LFUN_CLOSE_TAB_GROUP:
1705 enable = d.currentTabWorkArea();
1708 case LFUN_TOOLBAR_TOGGLE: {
1709 string const name = cmd.getArg(0);
1710 if (GuiToolbar * t = toolbar(name))
1711 flag.setOnOff(t->isVisible());
1714 docstring const msg =
1715 bformat(_("Unknown toolbar \"%1$s\""), from_utf8(name));
1721 case LFUN_DROP_LAYOUTS_CHOICE:
1725 case LFUN_UI_TOGGLE:
1726 flag.setOnOff(isFullScreen());
1729 case LFUN_DIALOG_DISCONNECT_INSET:
1732 case LFUN_DIALOG_HIDE:
1733 // FIXME: should we check if the dialog is shown?
1736 case LFUN_DIALOG_TOGGLE:
1737 flag.setOnOff(isDialogVisible(cmd.getArg(0)));
1738 // fall through to set "enable"
1739 case LFUN_DIALOG_SHOW: {
1740 string const name = cmd.getArg(0);
1742 enable = name == "aboutlyx"
1743 || name == "file" //FIXME: should be removed.
1745 || name == "texinfo"
1746 || name == "progress"
1747 || name == "compare";
1748 else if (name == "print")
1749 enable = doc_buffer->params().isExportable("dvi")
1750 && lyxrc.print_command != "none";
1751 else if (name == "character" || name == "symbols") {
1752 if (!buf || buf->isReadonly())
1755 Cursor const & cur = currentBufferView()->cursor();
1756 enable = !(cur.inTexted() && cur.paragraph().isPassThru());
1759 else if (name == "latexlog")
1760 enable = FileName(doc_buffer->logName()).isReadableFile();
1761 else if (name == "spellchecker")
1762 enable = theSpellChecker()
1763 && !doc_buffer->isReadonly()
1764 && !doc_buffer->text().empty();
1765 else if (name == "vclog")
1766 enable = doc_buffer->lyxvc().inUse();
1770 case LFUN_DIALOG_UPDATE: {
1771 string const name = cmd.getArg(0);
1773 enable = name == "prefs";
1777 case LFUN_COMMAND_EXECUTE:
1779 case LFUN_MENU_OPEN:
1780 // Nothing to check.
1783 case LFUN_COMPLETION_INLINE:
1784 if (!d.current_work_area_
1785 || !d.current_work_area_->completer().inlinePossible(
1786 currentBufferView()->cursor()))
1790 case LFUN_COMPLETION_POPUP:
1791 if (!d.current_work_area_
1792 || !d.current_work_area_->completer().popupPossible(
1793 currentBufferView()->cursor()))
1797 case LFUN_COMPLETION_COMPLETE:
1798 if (!d.current_work_area_
1799 || !d.current_work_area_->completer().inlinePossible(
1800 currentBufferView()->cursor()))
1804 case LFUN_COMPLETION_ACCEPT:
1805 if (!d.current_work_area_
1806 || (!d.current_work_area_->completer().popupVisible()
1807 && !d.current_work_area_->completer().inlineVisible()
1808 && !d.current_work_area_->completer().completionAvailable()))
1812 case LFUN_COMPLETION_CANCEL:
1813 if (!d.current_work_area_
1814 || (!d.current_work_area_->completer().popupVisible()
1815 && !d.current_work_area_->completer().inlineVisible()))
1819 case LFUN_BUFFER_ZOOM_OUT:
1820 enable = doc_buffer && lyxrc.zoom > 10;
1823 case LFUN_BUFFER_ZOOM_IN:
1824 enable = doc_buffer;
1827 case LFUN_BUFFER_NEXT:
1828 case LFUN_BUFFER_PREVIOUS:
1829 // FIXME: should we check is there is an previous or next buffer?
1831 case LFUN_BUFFER_SWITCH:
1832 // toggle on the current buffer, but do not toggle off
1833 // the other ones (is that a good idea?)
1835 && to_utf8(cmd.argument()) == doc_buffer->absFileName())
1836 flag.setOnOff(true);
1839 case LFUN_VC_REGISTER:
1840 enable = doc_buffer && !doc_buffer->lyxvc().inUse();
1842 case LFUN_VC_CHECK_IN:
1843 enable = doc_buffer && doc_buffer->lyxvc().checkInEnabled();
1845 case LFUN_VC_CHECK_OUT:
1846 enable = doc_buffer && doc_buffer->lyxvc().checkOutEnabled();
1848 case LFUN_VC_LOCKING_TOGGLE:
1849 enable = doc_buffer && !doc_buffer->isReadonly()
1850 && doc_buffer->lyxvc().lockingToggleEnabled();
1851 flag.setOnOff(enable && doc_buffer->lyxvc().locking());
1853 case LFUN_VC_REVERT:
1854 enable = doc_buffer && doc_buffer->lyxvc().inUse() && !doc_buffer->isReadonly();
1856 case LFUN_VC_UNDO_LAST:
1857 enable = doc_buffer && doc_buffer->lyxvc().undoLastEnabled();
1859 case LFUN_VC_REPO_UPDATE:
1860 enable = doc_buffer && doc_buffer->lyxvc().repoUpdateEnabled();
1862 case LFUN_VC_COMMAND: {
1863 if (cmd.argument().empty())
1865 if (!doc_buffer && contains(cmd.getArg(0), 'D'))
1869 case LFUN_VC_COMPARE:
1870 enable = doc_buffer && doc_buffer->lyxvc().prepareFileRevisionEnabled();
1873 case LFUN_SERVER_GOTO_FILE_ROW:
1875 case LFUN_FORWARD_SEARCH:
1876 enable = !(lyxrc.forward_search_dvi.empty() && lyxrc.forward_search_pdf.empty());
1879 case LFUN_FILE_INSERT_PLAINTEXT:
1880 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
1881 enable = documentBufferView() && documentBufferView()->cursor().inTexted();
1889 flag.setEnabled(false);
1895 static FileName selectTemplateFile()
1897 FileDialog dlg(qt_("Select template file"));
1898 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1899 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
1901 FileDialog::Result result = dlg.open(toqstr(lyxrc.template_path),
1902 QStringList(qt_("LyX Documents (*.lyx)")));
1904 if (result.first == FileDialog::Later)
1906 if (result.second.isEmpty())
1908 return FileName(fromqstr(result.second));
1912 Buffer * GuiView::loadDocument(FileName const & filename, bool tolastfiles)
1916 Buffer * newBuffer = 0;
1918 newBuffer = checkAndLoadLyXFile(filename);
1919 } catch (ExceptionMessage const & e) {
1926 message(_("Document not loaded."));
1930 setBuffer(newBuffer);
1931 newBuffer->errors("Parse");
1934 theSession().lastFiles().add(filename);
1940 void GuiView::openDocument(string const & fname)
1942 string initpath = lyxrc.document_path;
1944 if (documentBufferView()) {
1945 string const trypath = documentBufferView()->buffer().filePath();
1946 // If directory is writeable, use this as default.
1947 if (FileName(trypath).isDirWritable())
1953 if (fname.empty()) {
1954 FileDialog dlg(qt_("Select document to open"), LFUN_FILE_OPEN);
1955 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1956 dlg.setButton2(qt_("Examples|#E#e"),
1957 toqstr(addPath(package().system_support().absFileName(), "examples")));
1959 QStringList filter(qt_("LyX Documents (*.lyx)"));
1960 filter << qt_("LyX-1.3.x Documents (*.lyx13)")
1961 << qt_("LyX-1.4.x Documents (*.lyx14)")
1962 << qt_("LyX-1.5.x Documents (*.lyx15)")
1963 << qt_("LyX-1.6.x Documents (*.lyx16)");
1964 FileDialog::Result result =
1965 dlg.open(toqstr(initpath), filter);
1967 if (result.first == FileDialog::Later)
1970 filename = fromqstr(result.second);
1972 // check selected filename
1973 if (filename.empty()) {
1974 message(_("Canceled."));
1980 // get absolute path of file and add ".lyx" to the filename if
1982 FileName const fullname =
1983 fileSearch(string(), filename, "lyx", support::may_not_exist);
1984 if (!fullname.empty())
1985 filename = fullname.absFileName();
1987 if (!fullname.onlyPath().isDirectory()) {
1988 Alert::warning(_("Invalid filename"),
1989 bformat(_("The directory in the given path\n%1$s\ndoes not exist."),
1990 from_utf8(fullname.absFileName())));
1994 // if the file doesn't exist and isn't already open (bug 6645),
1995 // let the user create one
1996 if (!fullname.exists() && !theBufferList().exists(fullname)) {
1997 // the user specifically chose this name. Believe him.
1998 Buffer * const b = newFile(filename, string(), true);
2004 docstring const disp_fn = makeDisplayPath(filename);
2005 message(bformat(_("Opening document %1$s..."), disp_fn));
2008 Buffer * buf = loadDocument(fullname);
2010 str2 = bformat(_("Document %1$s opened."), disp_fn);
2011 if (buf->lyxvc().inUse())
2012 str2 += " " + from_utf8(buf->lyxvc().versionString()) +
2013 " " + _("Version control detected.");
2015 str2 = bformat(_("Could not open document %1$s"), disp_fn);
2020 // FIXME: clean that
2021 static bool import(GuiView * lv, FileName const & filename,
2022 string const & format, ErrorList & errorList)
2024 FileName const lyxfile(support::changeExtension(filename.absFileName(), ".lyx"));
2026 string loader_format;
2027 vector<string> loaders = theConverters().loaders();
2028 if (find(loaders.begin(), loaders.end(), format) == loaders.end()) {
2029 for (vector<string>::const_iterator it = loaders.begin();
2030 it != loaders.end(); ++it) {
2031 if (!theConverters().isReachable(format, *it))
2034 string const tofile =
2035 support::changeExtension(filename.absFileName(),
2036 formats.extension(*it));
2037 if (!theConverters().convert(0, filename, FileName(tofile),
2038 filename, format, *it, errorList))
2040 loader_format = *it;
2043 if (loader_format.empty()) {
2044 frontend::Alert::error(_("Couldn't import file"),
2045 bformat(_("No information for importing the format %1$s."),
2046 formats.prettyName(format)));
2050 loader_format = format;
2052 if (loader_format == "lyx") {
2053 Buffer * buf = lv->loadDocument(lyxfile);
2057 Buffer * const b = newFile(lyxfile.absFileName(), string(), true);
2061 bool as_paragraphs = loader_format == "textparagraph";
2062 string filename2 = (loader_format == format) ? filename.absFileName()
2063 : support::changeExtension(filename.absFileName(),
2064 formats.extension(loader_format));
2065 lv->currentBufferView()->insertPlaintextFile(FileName(filename2),
2067 guiApp->setCurrentView(lv);
2068 lyx::dispatch(FuncRequest(LFUN_MARK_OFF));
2075 void GuiView::importDocument(string const & argument)
2078 string filename = split(argument, format, ' ');
2080 LYXERR(Debug::INFO, format << " file: " << filename);
2082 // need user interaction
2083 if (filename.empty()) {
2084 string initpath = lyxrc.document_path;
2085 if (documentBufferView()) {
2086 string const trypath = documentBufferView()->buffer().filePath();
2087 // If directory is writeable, use this as default.
2088 if (FileName(trypath).isDirWritable())
2092 docstring const text = bformat(_("Select %1$s file to import"),
2093 formats.prettyName(format));
2095 FileDialog dlg(toqstr(text), LFUN_BUFFER_IMPORT);
2096 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2097 dlg.setButton2(qt_("Examples|#E#e"),
2098 toqstr(addPath(package().system_support().absFileName(), "examples")));
2100 docstring filter = formats.prettyName(format);
2103 filter += from_utf8(formats.extensions(format));
2106 FileDialog::Result result =
2107 dlg.open(toqstr(initpath), fileFilters(toqstr(filter)));
2109 if (result.first == FileDialog::Later)
2112 filename = fromqstr(result.second);
2114 // check selected filename
2115 if (filename.empty())
2116 message(_("Canceled."));
2119 if (filename.empty())
2122 // get absolute path of file
2123 FileName const fullname(support::makeAbsPath(filename));
2125 FileName const lyxfile(support::changeExtension(fullname.absFileName(), ".lyx"));
2127 // Check if the document already is open
2128 Buffer * buf = theBufferList().getBuffer(lyxfile);
2131 if (!closeBuffer()) {
2132 message(_("Canceled."));
2137 docstring const displaypath = makeDisplayPath(lyxfile.absFileName(), 30);
2139 // if the file exists already, and we didn't do
2140 // -i lyx thefile.lyx, warn
2141 if (lyxfile.exists() && fullname != lyxfile) {
2143 docstring text = bformat(_("The document %1$s already exists.\n\n"
2144 "Do you want to overwrite that document?"), displaypath);
2145 int const ret = Alert::prompt(_("Overwrite document?"),
2146 text, 0, 1, _("&Overwrite"), _("&Cancel"));
2149 message(_("Canceled."));
2154 message(bformat(_("Importing %1$s..."), displaypath));
2155 ErrorList errorList;
2156 if (import(this, fullname, format, errorList))
2157 message(_("imported."));
2159 message(_("file not imported!"));
2161 // FIXME (Abdel 12/08/06): Is there a need to display the error list here?
2165 void GuiView::newDocument(string const & filename, bool from_template)
2167 FileName initpath(lyxrc.document_path);
2168 if (documentBufferView()) {
2169 FileName const trypath(documentBufferView()->buffer().filePath());
2170 // If directory is writeable, use this as default.
2171 if (trypath.isDirWritable())
2175 string templatefile;
2176 if (from_template) {
2177 templatefile = selectTemplateFile().absFileName();
2178 if (templatefile.empty())
2183 if (filename.empty())
2184 b = newUnnamedFile(initpath, to_utf8(_("newfile")), templatefile);
2186 b = newFile(filename, templatefile, true);
2191 // If no new document could be created, it is unsure
2192 // whether there is a valid BufferView.
2193 if (currentBufferView())
2194 // Ensure the cursor is correctly positioned on screen.
2195 currentBufferView()->showCursor();
2199 void GuiView::insertLyXFile(docstring const & fname)
2201 BufferView * bv = documentBufferView();
2206 FileName filename(to_utf8(fname));
2207 if (filename.empty()) {
2208 // Launch a file browser
2210 string initpath = lyxrc.document_path;
2211 string const trypath = bv->buffer().filePath();
2212 // If directory is writeable, use this as default.
2213 if (FileName(trypath).isDirWritable())
2217 FileDialog dlg(qt_("Select LyX document to insert"), LFUN_FILE_INSERT);
2218 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2219 dlg.setButton2(qt_("Examples|#E#e"),
2220 toqstr(addPath(package().system_support().absFileName(),
2223 FileDialog::Result result = dlg.open(toqstr(initpath),
2224 QStringList(qt_("LyX Documents (*.lyx)")));
2226 if (result.first == FileDialog::Later)
2230 filename.set(fromqstr(result.second));
2232 // check selected filename
2233 if (filename.empty()) {
2234 // emit message signal.
2235 message(_("Canceled."));
2240 bv->insertLyXFile(filename);
2241 bv->buffer().errors("Parse");
2245 bool GuiView::renameBuffer(Buffer & b, docstring const & newname)
2247 FileName fname = b.fileName();
2248 FileName const oldname = fname;
2250 if (!newname.empty()) {
2252 fname = support::makeAbsPath(to_utf8(newname), oldname.onlyPath().absFileName());
2254 // Switch to this Buffer.
2257 // No argument? Ask user through dialog.
2259 FileDialog dlg(qt_("Choose a filename to save document as"),
2260 LFUN_BUFFER_WRITE_AS);
2261 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2262 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
2264 if (!isLyXFileName(fname.absFileName()))
2265 fname.changeExtension(".lyx");
2267 FileDialog::Result result =
2268 dlg.save(toqstr(fname.onlyPath().absFileName()),
2269 QStringList(qt_("LyX Documents (*.lyx)")),
2270 toqstr(fname.onlyFileName()));
2272 if (result.first == FileDialog::Later)
2275 fname.set(fromqstr(result.second));
2280 if (!isLyXFileName(fname.absFileName()))
2281 fname.changeExtension(".lyx");
2284 // fname is now the new Buffer location.
2286 // if there is already a Buffer open with this name, we do not want
2287 // to have another one. (the second test makes sure we're not just
2288 // trying to overwrite ourselves, which is fine.)
2289 if (theBufferList().exists(fname) && fname != oldname) {
2290 docstring const text =
2291 bformat(_("The file\n%1$s\nis already open in your current session.\n"
2292 "Please close it before attempting to overwrite it.\n"
2293 "Do you want to choose a new filename?"),
2294 from_utf8(fname.absFileName()));
2295 int const ret = Alert::prompt(_("Chosen File Already Open"),
2296 text, 0, 1, _("&Rename"), _("&Cancel"));
2298 case 0: return renameBuffer(b, docstring());
2299 case 1: return false;
2304 if (FileName(fname).exists()) {
2305 docstring const file = makeDisplayPath(fname.absFileName(), 30);
2306 docstring const text = bformat(_("The document %1$s already "
2307 "exists.\n\nDo you want to "
2308 "overwrite that document?"),
2310 int const ret = Alert::prompt(_("Overwrite document?"),
2311 text, 0, 2, _("&Overwrite"), _("&Rename"), _("&Cancel"));
2314 case 1: return renameBuffer(b, docstring());
2315 case 2: return false;
2319 return saveBuffer(b, fname);
2323 struct PrettyNameComparator
2325 bool operator()(Format const *first, Format const *second) const {
2326 return compare_ascii_no_case(first->prettyname(), second->prettyname()) <= 0;
2331 bool GuiView::exportBufferAs(Buffer & b)
2333 FileName fname = b.fileName();
2335 FileDialog dlg(qt_("Choose a filename to export the document as"));
2336 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2339 types << "Any supported format (*.*)";
2340 Formats::const_iterator it = formats.begin();
2341 vector<Format const *> export_formats;
2342 for (; it != formats.end(); ++it)
2343 if (it->documentFormat() && it->inExportMenu())
2344 export_formats.push_back(&(*it));
2345 PrettyNameComparator cmp;
2346 sort(export_formats.begin(), export_formats.end(), cmp);
2347 vector<Format const *>::const_iterator fit = export_formats.begin();
2348 for (; fit != export_formats.end(); ++fit)
2349 types << toqstr((*fit)->prettyname() + " (*." + (*fit)->extension() + ")");
2351 FileDialog::Result result =
2352 dlg.save(toqstr(fname.onlyPath().absFileName()),
2354 toqstr(fname.onlyFileName()),
2356 if (result.first != FileDialog::Chosen)
2359 string s = fromqstr(filter);
2360 size_t pos = s.find(" (*.");
2361 LASSERT(pos != string::npos, /**/);
2362 string fmt_prettyname = s.substr(0, pos);
2364 fname.set(fromqstr(result.second));
2365 if (fmt_prettyname == "Any supported format")
2366 fmt_name = formats.getFormatFromExtension(fname.extension());
2368 fmt_name = formats.getFormatFromPrettyName(fmt_prettyname);
2369 LYXERR(Debug::FILES, "fmt_prettyname=" << fmt_prettyname
2370 << ", fmt_name=" << fmt_name << ", fname=" << fname.absFileName());
2372 if (fmt_name.empty() || fname.empty())
2375 // fname is now the new Buffer location.
2376 if (FileName(fname).exists()) {
2377 docstring const file = makeDisplayPath(fname.absFileName(), 30);
2378 docstring text = bformat(_("The document %1$s already "
2379 "exists.\n\nDo you want to "
2380 "overwrite that document?"),
2382 int const ret = Alert::prompt(_("Overwrite document?"),
2383 text, 0, 2, _("&Overwrite"), _("&Rename"), _("&Cancel"));
2386 case 1: return exportBufferAs(b);
2387 case 2: return false;
2391 FuncRequest cmd(LFUN_BUFFER_EXPORT, fmt_name + " " + fname.absFileName());
2394 return dr.dispatched();
2398 bool GuiView::saveBuffer(Buffer & b) {
2399 return saveBuffer(b, FileName());
2403 bool GuiView::saveBuffer(Buffer & b, FileName const & fn)
2405 if (workArea(b) && workArea(b)->inDialogMode())
2408 if (fn.empty() && b.isUnnamed())
2409 return renameBuffer(b, docstring());
2415 success = b.saveAs(fn);
2418 theSession().lastFiles().add(b.fileName());
2422 // Switch to this Buffer.
2425 // FIXME: we don't tell the user *WHY* the save failed !!
2426 docstring const file = makeDisplayPath(b.absFileName(), 30);
2427 docstring text = bformat(_("The document %1$s could not be saved.\n\n"
2428 "Do you want to rename the document and "
2429 "try again?"), file);
2430 int const ret = Alert::prompt(_("Rename and save?"),
2431 text, 0, 2, _("&Rename"), _("&Retry"), _("&Cancel"));
2434 if (!renameBuffer(b, docstring()))
2443 return saveBuffer(b);
2447 bool GuiView::hideWorkArea(GuiWorkArea * wa)
2449 return closeWorkArea(wa, false);
2453 bool GuiView::closeWorkArea(GuiWorkArea * wa)
2455 Buffer & buf = wa->bufferView().buffer();
2456 return closeWorkArea(wa, !buf.parent());
2460 bool GuiView::closeBuffer()
2462 GuiWorkArea * wa = currentMainWorkArea();
2463 setCurrentWorkArea(wa);
2464 Buffer & buf = wa->bufferView().buffer();
2465 return wa && closeWorkArea(wa, !buf.parent());
2469 void GuiView::writeSession() const {
2470 GuiWorkArea const * active_wa = currentMainWorkArea();
2471 for (int i = 0; i < d.splitter_->count(); ++i) {
2472 TabWorkArea * twa = d.tabWorkArea(i);
2473 for (int j = 0; j < twa->count(); ++j) {
2474 GuiWorkArea * wa = static_cast<GuiWorkArea *>(twa->widget(j));
2475 Buffer & buf = wa->bufferView().buffer();
2476 theSession().lastOpened().add(buf.fileName(), wa == active_wa);
2482 bool GuiView::closeBufferAll()
2484 // Close the workareas in all other views
2485 QList<int> const ids = guiApp->viewIds();
2486 for (int i = 0; i != ids.size(); ++i) {
2487 if (id_ != ids[i] && !guiApp->view(ids[i]).closeWorkAreaAll())
2491 // Close our own workareas
2492 if (!closeWorkAreaAll())
2495 // Now close the hidden buffers. We prevent hidden buffers from being
2496 // dirty, so we can just close them.
2497 theBufferList().closeAll();
2502 bool GuiView::closeWorkAreaAll()
2504 setCurrentWorkArea(currentMainWorkArea());
2506 // We might be in a situation that there is still a tabWorkArea, but
2507 // there are no tabs anymore. This can happen when we get here after a
2508 // TabWorkArea::lastWorkAreaRemoved() signal. Therefore we count how
2509 // many TabWorkArea's have no documents anymore.
2512 // We have to call count() each time, because it can happen that
2513 // more than one splitter will disappear in one iteration (bug 5998).
2514 for (; d.splitter_->count() > empty_twa; ) {
2515 TabWorkArea * twa = d.tabWorkArea(empty_twa);
2517 if (twa->count() == 0)
2520 setCurrentWorkArea(twa->currentWorkArea());
2521 if (!closeTabWorkArea(twa))
2529 bool GuiView::closeWorkArea(GuiWorkArea * wa, bool close_buffer)
2534 Buffer & buf = wa->bufferView().buffer();
2536 if (close_buffer && GuiViewPrivate::busyBuffers.contains(&buf)) {
2537 Alert::warning(_("Close document"),
2538 _("Document could not be closed because it is being processed by LyX."));
2543 return closeBuffer(buf);
2545 if (!inMultiTabs(wa))
2546 if (!saveBufferIfNeeded(buf, true))
2554 bool GuiView::closeBuffer(Buffer & buf)
2556 // If we are in a close_event all children will be closed in some time,
2557 // so no need to do it here. This will ensure that the children end up
2558 // in the session file in the correct order. If we close the master
2559 // buffer, we can close or release the child buffers here too.
2560 bool success = true;
2562 ListOfBuffers clist = buf.getChildren();
2563 ListOfBuffers::const_iterator it = clist.begin();
2564 ListOfBuffers::const_iterator const bend = clist.end();
2565 for (; it != bend; ++it) {
2566 // If a child is dirty, do not close
2567 // without user intervention
2568 //FIXME: should we look in other tabworkareas?
2569 Buffer * child_buf = *it;
2570 GuiWorkArea * child_wa = workArea(*child_buf);
2572 if (!closeWorkArea(child_wa, true)) {
2577 theBufferList().releaseChild(&buf, child_buf);
2581 // goto bookmark to update bookmark pit.
2582 //FIXME: we should update only the bookmarks related to this buffer!
2583 LYXERR(Debug::DEBUG, "GuiView::closeBuffer()");
2584 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
2585 guiApp->gotoBookmark(i+1, false, false);
2587 if (saveBufferIfNeeded(buf, false)) {
2588 buf.removeAutosaveFile();
2589 theBufferList().release(&buf);
2593 // open all children again to avoid a crash because of dangling
2594 // pointers (bug 6603)
2600 bool GuiView::closeTabWorkArea(TabWorkArea * twa)
2602 while (twa == d.currentTabWorkArea()) {
2603 twa->setCurrentIndex(twa->count()-1);
2605 GuiWorkArea * wa = twa->currentWorkArea();
2606 Buffer & b = wa->bufferView().buffer();
2608 // We only want to close the buffer if the same buffer is not visible
2609 // in another view, and if this is not a child and if we are closing
2610 // a view (not a tabgroup).
2611 bool const close_buffer =
2612 !inOtherView(b) && !b.parent() && closing_;
2614 if (!closeWorkArea(wa, close_buffer))
2621 bool GuiView::saveBufferIfNeeded(Buffer & buf, bool hiding)
2623 if (buf.isClean() || buf.paragraphs().empty())
2626 // Switch to this Buffer.
2631 if (buf.isUnnamed())
2632 file = from_utf8(buf.fileName().onlyFileName());
2634 file = buf.fileName().displayName(30);
2636 // Bring this window to top before asking questions.
2641 if (hiding && buf.isUnnamed()) {
2642 docstring const text = bformat(_("The document %1$s has not been "
2643 "saved yet.\n\nDo you want to save "
2644 "the document?"), file);
2645 ret = Alert::prompt(_("Save new document?"),
2646 text, 0, 1, _("&Save"), _("&Cancel"));
2650 docstring const text = bformat(_("The document %1$s has unsaved changes."
2651 "\n\nDo you want to save the document or discard the changes?"), file);
2652 ret = Alert::prompt(_("Save changed document?"),
2653 text, 0, 2, _("&Save"), _("&Discard"), _("&Cancel"));
2658 if (!saveBuffer(buf))
2662 // If we crash after this we could have no autosave file
2663 // but I guess this is really improbable (Jug).
2664 // Sometimes improbable things happen:
2665 // - see bug http://www.lyx.org/trac/ticket/6587 (ps)
2666 // buf.removeAutosaveFile();
2668 // revert all changes
2679 bool GuiView::inMultiTabs(GuiWorkArea * wa)
2681 Buffer & buf = wa->bufferView().buffer();
2683 for (int i = 0; i != d.splitter_->count(); ++i) {
2684 GuiWorkArea * wa_ = d.tabWorkArea(i)->workArea(buf);
2685 if (wa_ && wa_ != wa)
2688 return inOtherView(buf);
2692 bool GuiView::inOtherView(Buffer & buf)
2694 QList<int> const ids = guiApp->viewIds();
2696 for (int i = 0; i != ids.size(); ++i) {
2700 if (guiApp->view(ids[i]).workArea(buf))
2707 void GuiView::gotoNextOrPreviousBuffer(NextOrPrevious np)
2709 if (!documentBufferView())
2712 if (TabWorkArea * twa = d.currentTabWorkArea()) {
2713 Buffer * const curbuf = &documentBufferView()->buffer();
2714 int nwa = twa->count();
2715 for (int i = 0; i < nwa; ++i) {
2716 if (&workArea(i)->bufferView().buffer() == curbuf) {
2718 if (np == NEXTBUFFER)
2719 next_index = (i == nwa - 1 ? 0 : i + 1);
2721 next_index = (i == 0 ? nwa - 1 : i - 1);
2722 setBuffer(&workArea(next_index)->bufferView().buffer());
2730 /// make sure the document is saved
2731 static bool ensureBufferClean(Buffer * buffer)
2733 LASSERT(buffer, return false);
2734 if (buffer->isClean() && !buffer->isUnnamed())
2737 docstring const file = buffer->fileName().displayName(30);
2740 if (!buffer->isUnnamed()) {
2741 text = bformat(_("The document %1$s has unsaved "
2742 "changes.\n\nDo you want to save "
2743 "the document?"), file);
2744 title = _("Save changed document?");
2747 text = bformat(_("The document %1$s has not been "
2748 "saved yet.\n\nDo you want to save "
2749 "the document?"), file);
2750 title = _("Save new document?");
2752 int const ret = Alert::prompt(title, text, 0, 1, _("&Save"), _("&Cancel"));
2755 dispatch(FuncRequest(LFUN_BUFFER_WRITE));
2757 return buffer->isClean() && !buffer->isUnnamed();
2761 bool GuiView::reloadBuffer(Buffer & buf)
2763 Buffer::ReadStatus status = buf.reload();
2764 return status == Buffer::ReadSuccess;
2768 void GuiView::checkExternallyModifiedBuffers()
2770 BufferList::iterator bit = theBufferList().begin();
2771 BufferList::iterator const bend = theBufferList().end();
2772 for (; bit != bend; ++bit) {
2773 Buffer * buf = *bit;
2774 if (buf->fileName().exists()
2775 && buf->isExternallyModified(Buffer::checksum_method)) {
2776 docstring text = bformat(_("Document \n%1$s\n has been externally modified."
2777 " Reload now? Any local changes will be lost."),
2778 from_utf8(buf->absFileName()));
2779 int const ret = Alert::prompt(_("Reload externally changed document?"),
2780 text, 0, 1, _("&Reload"), _("&Cancel"));
2788 void GuiView::dispatchVC(FuncRequest const & cmd, DispatchResult & dr)
2790 Buffer * buffer = documentBufferView()
2791 ? &(documentBufferView()->buffer()) : 0;
2793 switch (cmd.action()) {
2794 case LFUN_VC_REGISTER:
2795 if (!buffer || !ensureBufferClean(buffer))
2797 if (!buffer->lyxvc().inUse()) {
2798 if (buffer->lyxvc().registrer()) {
2799 reloadBuffer(*buffer);
2800 dr.suppressMessageUpdate();
2805 case LFUN_VC_CHECK_IN:
2806 if (!buffer || !ensureBufferClean(buffer))
2808 if (buffer->lyxvc().inUse() && !buffer->isReadonly()) {
2809 dr.setMessage(buffer->lyxvc().checkIn());
2810 if (!dr.message().empty())
2811 reloadBuffer(*buffer);
2815 case LFUN_VC_CHECK_OUT:
2816 if (!buffer || !ensureBufferClean(buffer))
2818 if (buffer->lyxvc().inUse()) {
2819 dr.setMessage(buffer->lyxvc().checkOut());
2820 reloadBuffer(*buffer);
2824 case LFUN_VC_LOCKING_TOGGLE:
2825 LASSERT(buffer, return);
2826 if (!ensureBufferClean(buffer) || buffer->isReadonly())
2828 if (buffer->lyxvc().inUse()) {
2829 string res = buffer->lyxvc().lockingToggle();
2831 frontend::Alert::error(_("Revision control error."),
2832 _("Error when setting the locking property."));
2835 reloadBuffer(*buffer);
2840 case LFUN_VC_REVERT:
2841 LASSERT(buffer, return);
2842 if (buffer->lyxvc().revert()) {
2843 reloadBuffer(*buffer);
2844 dr.suppressMessageUpdate();
2848 case LFUN_VC_UNDO_LAST:
2849 LASSERT(buffer, return);
2850 buffer->lyxvc().undoLast();
2851 reloadBuffer(*buffer);
2852 dr.suppressMessageUpdate();
2855 case LFUN_VC_REPO_UPDATE:
2856 LASSERT(buffer, return);
2857 if (ensureBufferClean(buffer)) {
2858 dr.setMessage(buffer->lyxvc().repoUpdate());
2859 checkExternallyModifiedBuffers();
2863 case LFUN_VC_COMMAND: {
2864 string flag = cmd.getArg(0);
2865 if (buffer && contains(flag, 'R') && !ensureBufferClean(buffer))
2868 if (contains(flag, 'M')) {
2869 if (!Alert::askForText(message, _("LyX VC: Log Message")))
2872 string path = cmd.getArg(1);
2873 if (contains(path, "$$p") && buffer)
2874 path = subst(path, "$$p", buffer->filePath());
2875 LYXERR(Debug::LYXVC, "Directory: " << path);
2877 if (!pp.isReadableDirectory()) {
2878 lyxerr << _("Directory is not accessible.") << endl;
2881 support::PathChanger p(pp);
2883 string command = cmd.getArg(2);
2884 if (command.empty())
2887 command = subst(command, "$$i", buffer->absFileName());
2888 command = subst(command, "$$p", buffer->filePath());
2890 command = subst(command, "$$m", to_utf8(message));
2891 LYXERR(Debug::LYXVC, "Command: " << command);
2893 one.startscript(Systemcall::Wait, command);
2897 if (contains(flag, 'I'))
2898 buffer->markDirty();
2899 if (contains(flag, 'R'))
2900 reloadBuffer(*buffer);
2905 case LFUN_VC_COMPARE: {
2907 if (cmd.argument().empty()) {
2908 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "comparehistory"));
2912 string rev1 = cmd.getArg(0);
2916 if (!buffer->lyxvc().prepareFileRevision(rev1, f1))
2919 if (isStrInt(rev1) && convert<int>(rev1) <= 0) {
2920 f2 = buffer->absFileName();
2922 string rev2 = cmd.getArg(1);
2926 if (!buffer->lyxvc().prepareFileRevision(rev2, f2))
2930 LYXERR(Debug::LYXVC, "Launching comparison for fetched revisions:\n" <<
2931 f1 << "\n" << f2 << "\n" );
2932 string par = "compare run " + quoteName(f1) + " " + quoteName(f2);
2933 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, par));
2943 void GuiView::openChildDocument(string const & fname)
2945 LASSERT(documentBufferView(), return);
2946 Buffer & buffer = documentBufferView()->buffer();
2947 FileName const filename = support::makeAbsPath(fname, buffer.filePath());
2948 documentBufferView()->saveBookmark(false);
2950 if (theBufferList().exists(filename)) {
2951 child = theBufferList().getBuffer(filename);
2954 message(bformat(_("Opening child document %1$s..."),
2955 makeDisplayPath(filename.absFileName())));
2956 child = loadDocument(filename, false);
2958 // Set the parent name of the child document.
2959 // This makes insertion of citations and references in the child work,
2960 // when the target is in the parent or another child document.
2962 child->setParent(&buffer);
2966 bool GuiView::goToFileRow(string const & argument)
2970 size_t i = argument.find_last_of(' ');
2971 if (i != string::npos) {
2972 file_name = os::internal_path(trim(argument.substr(0, i)));
2973 istringstream is(argument.substr(i + 1));
2978 if (i == string::npos) {
2979 LYXERR0("Wrong argument: " << argument);
2983 string const abstmp = package().temp_dir().absFileName();
2984 string const realtmp = package().temp_dir().realPath();
2985 // We have to use os::path_prefix_is() here, instead of
2986 // simply prefixIs(), because the file name comes from
2987 // an external application and may need case adjustment.
2988 if (os::path_prefix_is(file_name, abstmp, os::CASE_ADJUSTED)
2989 || os::path_prefix_is(file_name, realtmp, os::CASE_ADJUSTED)) {
2990 // Needed by inverse dvi search. If it is a file
2991 // in tmpdir, call the apropriated function.
2992 // If tmpdir is a symlink, we may have the real
2993 // path passed back, so we correct for that.
2994 if (!prefixIs(file_name, abstmp))
2995 file_name = subst(file_name, realtmp, abstmp);
2996 buf = theBufferList().getBufferFromTmp(file_name);
2998 // Must replace extension of the file to be .lyx
2999 // and get full path
3000 FileName const s = fileSearch(string(),
3001 support::changeExtension(file_name, ".lyx"), "lyx");
3002 // Either change buffer or load the file
3003 if (theBufferList().exists(s))
3004 buf = theBufferList().getBuffer(s);
3005 else if (s.exists()) {
3006 buf = loadDocument(s);
3011 _("File does not exist: %1$s"),
3012 makeDisplayPath(file_name)));
3018 _("No buffer for file: %1$s."),
3019 makeDisplayPath(file_name))
3024 documentBufferView()->setCursorFromRow(row);
3029 #if (QT_VERSION >= 0x040400)
3031 Buffer::ExportStatus GuiView::GuiViewPrivate::runAndDestroy(const T& func, Buffer const * orig, Buffer * clone, string const & format)
3033 Buffer::ExportStatus const status = func(format);
3035 // the cloning operation will have produced a clone of the entire set of
3036 // documents, starting from the master. so we must delete those.
3037 Buffer * mbuf = const_cast<Buffer *>(clone->masterBuffer());
3039 busyBuffers.remove(orig);
3044 Buffer::ExportStatus GuiView::GuiViewPrivate::compileAndDestroy(Buffer const * orig, Buffer * clone, string const & format)
3046 Buffer::ExportStatus (Buffer::* mem_func)(std::string const &, bool) const = &Buffer::doExport;
3047 return runAndDestroy(bind(mem_func, clone, _1, true), orig, clone, format);
3051 Buffer::ExportStatus GuiView::GuiViewPrivate::exportAndDestroy(Buffer const * orig, Buffer * clone, string const & format)
3053 Buffer::ExportStatus (Buffer::* mem_func)(std::string const &, bool) const = &Buffer::doExport;
3054 return runAndDestroy(bind(mem_func, clone, _1, false), orig, clone, format);
3058 Buffer::ExportStatus GuiView::GuiViewPrivate::previewAndDestroy(Buffer const * orig, Buffer * clone, string const & format)
3060 Buffer::ExportStatus (Buffer::* mem_func)(std::string const &) const = &Buffer::preview;
3061 return runAndDestroy(bind(mem_func, clone, _1), orig, clone, format);
3066 // not used, but the linker needs them
3068 Buffer::ExportStatus GuiView::GuiViewPrivate::compileAndDestroy(
3069 Buffer const *, Buffer *, string const &)
3071 return Buffer::ExportSuccess;
3075 Buffer::ExportStatus GuiView::GuiViewPrivate::exportAndDestroy(
3076 Buffer const *, Buffer *, string const &)
3078 return Buffer::ExportSuccess;
3082 Buffer::ExportStatus GuiView::GuiViewPrivate::previewAndDestroy(
3083 Buffer const *, Buffer *, string const &)
3085 return Buffer::ExportSuccess;
3091 bool GuiView::GuiViewPrivate::asyncBufferProcessing(
3092 string const & argument,
3093 Buffer const * used_buffer,
3094 docstring const & msg,
3095 Buffer::ExportStatus (*asyncFunc)(Buffer const *, Buffer *, string const &),
3096 Buffer::ExportStatus (Buffer::*syncFunc)(string const &, bool) const,
3097 Buffer::ExportStatus (Buffer::*previewFunc)(string const &) const)
3102 string format = argument;
3104 format = used_buffer->params().getDefaultOutputFormat();
3105 processing_format = format;
3106 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
3108 progress_->clearMessages();
3111 GuiViewPrivate::busyBuffers.insert(used_buffer);
3112 Buffer * cloned_buffer = used_buffer->cloneFromMaster();
3113 if (!cloned_buffer) {
3114 Alert::error(_("Export Error"),
3115 _("Error cloning the Buffer."));
3118 QFuture<Buffer::ExportStatus> f = QtConcurrent::run(
3123 setPreviewFuture(f);
3124 last_export_format = used_buffer->params().bufferFormat();
3127 // We are asynchronous, so we don't know here anything about the success
3130 Buffer::ExportStatus status;
3132 // TODO check here if it breaks exporting with Qt < 4.4
3133 status = (used_buffer->*syncFunc)(format, true);
3134 } else if (previewFunc) {
3135 status = (used_buffer->*previewFunc)(format);
3138 handleExportStatus(gv_, status, format);
3140 return (status == Buffer::ExportSuccess
3141 || status == Buffer::PreviewSuccess);
3145 void GuiView::dispatchToBufferView(FuncRequest const & cmd, DispatchResult & dr)
3147 BufferView * bv = currentBufferView();
3150 // Let the current BufferView dispatch its own actions.
3151 bv->dispatch(cmd, dr);
3152 if (dr.dispatched())
3155 // Try with the document BufferView dispatch if any.
3156 BufferView * doc_bv = documentBufferView();
3157 if (doc_bv && doc_bv != bv) {
3158 doc_bv->dispatch(cmd, dr);
3159 if (dr.dispatched())
3163 // Then let the current Cursor dispatch its own actions.
3164 bv->cursor().dispatch(cmd);
3166 // update completion. We do it here and not in
3167 // processKeySym to avoid another redraw just for a
3168 // changed inline completion
3169 if (cmd.origin() == FuncRequest::KEYBOARD) {
3170 if (cmd.action() == LFUN_SELF_INSERT
3171 || (cmd.action() == LFUN_ERT_INSERT && bv->cursor().inMathed()))
3172 updateCompletion(bv->cursor(), true, true);
3173 else if (cmd.action() == LFUN_CHAR_DELETE_BACKWARD)
3174 updateCompletion(bv->cursor(), false, true);
3176 updateCompletion(bv->cursor(), false, false);
3179 dr = bv->cursor().result();
3183 void GuiView::dispatch(FuncRequest const & cmd, DispatchResult & dr)
3185 BufferView * bv = currentBufferView();
3186 // By default we won't need any update.
3187 dr.screenUpdate(Update::None);
3188 // assume cmd will be dispatched
3189 dr.dispatched(true);
3191 Buffer * doc_buffer = documentBufferView()
3192 ? &(documentBufferView()->buffer()) : 0;
3194 if (cmd.origin() == FuncRequest::TOC) {
3195 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
3196 // FIXME: do we need to pass a DispatchResult object here?
3197 toc->doDispatch(bv->cursor(), cmd);
3201 string const argument = to_utf8(cmd.argument());
3203 switch(cmd.action()) {
3204 case LFUN_BUFFER_CHILD_OPEN:
3205 openChildDocument(to_utf8(cmd.argument()));
3208 case LFUN_BUFFER_IMPORT:
3209 importDocument(to_utf8(cmd.argument()));
3212 case LFUN_BUFFER_EXPORT: {
3215 // GCC only sees strfwd.h when building merged
3216 if (::lyx::operator==(cmd.argument(), "custom")) {
3217 dispatch(FuncRequest(LFUN_DIALOG_SHOW, "sendto"), dr);
3220 #if QT_VERSION < 0x040400
3221 if (!doc_buffer->doExport(argument, false)) {
3223 dr.setMessage(bformat(_("Error exporting to format: %1$s"),
3227 /* TODO/Review: Is it a problem to also export the children?
3228 See the update_unincluded flag */
3229 d.asyncBufferProcessing(argument,
3232 &GuiViewPrivate::exportAndDestroy,
3235 // TODO Inform user about success
3240 case LFUN_BUFFER_EXPORT_AS:
3241 LASSERT(doc_buffer, break);
3242 exportBufferAs(*doc_buffer);
3245 case LFUN_BUFFER_UPDATE: {
3246 d.asyncBufferProcessing(argument,
3249 &GuiViewPrivate::compileAndDestroy,
3254 case LFUN_BUFFER_VIEW: {
3255 d.asyncBufferProcessing(argument,
3257 _("Previewing ..."),
3258 &GuiViewPrivate::previewAndDestroy,
3263 case LFUN_MASTER_BUFFER_UPDATE: {
3264 d.asyncBufferProcessing(argument,
3265 (doc_buffer ? doc_buffer->masterBuffer() : 0),
3267 &GuiViewPrivate::compileAndDestroy,
3272 case LFUN_MASTER_BUFFER_VIEW: {
3273 d.asyncBufferProcessing(argument,
3274 (doc_buffer ? doc_buffer->masterBuffer() : 0),
3276 &GuiViewPrivate::previewAndDestroy,
3277 0, &Buffer::preview);
3280 case LFUN_BUFFER_SWITCH: {
3281 string const file_name = to_utf8(cmd.argument());
3282 if (!FileName::isAbsolute(file_name)) {
3284 dr.setMessage(_("Absolute filename expected."));
3288 Buffer * buffer = theBufferList().getBuffer(FileName(file_name));
3291 dr.setMessage(_("Document not loaded"));
3295 // Do we open or switch to the buffer in this view ?
3296 if (workArea(*buffer)
3297 || lyxrc.open_buffers_in_tabs || !documentBufferView()) {
3302 // Look for the buffer in other views
3303 QList<int> const ids = guiApp->viewIds();
3305 for (; i != ids.size(); ++i) {
3306 GuiView & gv = guiApp->view(ids[i]);
3307 if (gv.workArea(*buffer)) {
3308 gv.activateWindow();
3309 gv.setBuffer(buffer);
3314 // If necessary, open a new window as a last resort
3315 if (i == ids.size()) {
3316 lyx::dispatch(FuncRequest(LFUN_WINDOW_NEW));
3322 case LFUN_BUFFER_NEXT:
3323 gotoNextOrPreviousBuffer(NEXTBUFFER);
3326 case LFUN_BUFFER_PREVIOUS:
3327 gotoNextOrPreviousBuffer(PREVBUFFER);
3330 case LFUN_COMMAND_EXECUTE: {
3331 bool const show_it = cmd.argument() != "off";
3332 // FIXME: this is a hack, "minibuffer" should not be
3334 if (GuiToolbar * t = toolbar("minibuffer")) {
3335 t->setVisible(show_it);
3336 if (show_it && t->commandBuffer())
3337 t->commandBuffer()->setFocus();
3341 case LFUN_DROP_LAYOUTS_CHOICE:
3342 d.layout_->showPopup();
3345 case LFUN_MENU_OPEN:
3346 if (QMenu * menu = guiApp->menus().menu(toqstr(cmd.argument()), *this))
3347 menu->exec(QCursor::pos());
3350 case LFUN_FILE_INSERT:
3351 insertLyXFile(cmd.argument());
3354 case LFUN_FILE_INSERT_PLAINTEXT:
3355 case LFUN_FILE_INSERT_PLAINTEXT_PARA: {
3356 bool const as_paragraph = (cmd.action() == LFUN_FILE_INSERT_PLAINTEXT_PARA);
3357 string const fname = to_utf8(cmd.argument());
3358 if (!fname.empty() && !FileName::isAbsolute(fname)) {
3359 dr.setMessage(_("Absolute filename expected."));
3363 FileName filename(fname);
3364 if (fname.empty()) {
3365 FileDialog dlg(qt_("Select file to insert"), (as_paragraph ?
3366 LFUN_FILE_INSERT_PLAINTEXT_PARA : LFUN_FILE_INSERT_PLAINTEXT));
3368 FileDialog::Result result = dlg.open(toqstr(bv->buffer().filePath()),
3369 QStringList(qt_("All Files (*)")));
3371 if (result.first == FileDialog::Later || result.second.isEmpty()) {
3372 dr.setMessage(_("Canceled."));
3376 filename.set(fromqstr(result.second));
3380 FuncRequest const new_cmd(cmd, filename.absoluteFilePath());
3381 bv->dispatch(new_cmd, dr);
3386 case LFUN_BUFFER_RELOAD: {
3387 LASSERT(doc_buffer, break);
3390 if (!doc_buffer->isClean()) {
3391 docstring const file =
3392 makeDisplayPath(doc_buffer->absFileName(), 20);
3393 docstring text = bformat(_("Any changes will be lost. "
3394 "Are you sure you want to revert to the saved version "
3395 "of the document %1$s?"), file);
3396 ret = Alert::prompt(_("Revert to saved document?"),
3397 text, 1, 1, _("&Revert"), _("&Cancel"));
3401 doc_buffer->markClean();
3402 reloadBuffer(*doc_buffer);
3403 dr.forceBufferUpdate();
3408 case LFUN_BUFFER_WRITE:
3409 LASSERT(doc_buffer, break);
3410 saveBuffer(*doc_buffer);
3413 case LFUN_BUFFER_WRITE_AS:
3414 LASSERT(doc_buffer, break);
3415 renameBuffer(*doc_buffer, cmd.argument());
3418 case LFUN_BUFFER_WRITE_ALL: {
3419 Buffer * first = theBufferList().first();
3422 message(_("Saving all documents..."));
3423 // We cannot use a for loop as the buffer list cycles.
3426 if (!b->isClean()) {
3428 LYXERR(Debug::ACTION, "Saved " << b->absFileName());
3430 b = theBufferList().next(b);
3431 } while (b != first);
3432 dr.setMessage(_("All documents saved."));
3436 case LFUN_BUFFER_CLOSE:
3440 case LFUN_BUFFER_CLOSE_ALL:
3444 case LFUN_TOOLBAR_TOGGLE: {
3445 string const name = cmd.getArg(0);
3446 if (GuiToolbar * t = toolbar(name))
3451 case LFUN_DIALOG_UPDATE: {
3452 string const name = to_utf8(cmd.argument());
3453 if (name == "prefs" || name == "document")
3454 updateDialog(name, string());
3455 else if (name == "paragraph")
3456 lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
3457 else if (currentBufferView()) {
3458 Inset * inset = currentBufferView()->editedInset(name);
3459 // Can only update a dialog connected to an existing inset
3461 // FIXME: get rid of this indirection; GuiView ask the inset
3462 // if he is kind enough to update itself...
3463 FuncRequest fr(LFUN_INSET_DIALOG_UPDATE, cmd.argument());
3464 //FIXME: pass DispatchResult here?
3465 inset->dispatch(currentBufferView()->cursor(), fr);
3471 case LFUN_DIALOG_TOGGLE: {
3472 FuncCode const func_code = isDialogVisible(cmd.getArg(0))
3473 ? LFUN_DIALOG_HIDE : LFUN_DIALOG_SHOW;
3474 dispatch(FuncRequest(func_code, cmd.argument()), dr);
3478 case LFUN_DIALOG_DISCONNECT_INSET:
3479 disconnectDialog(to_utf8(cmd.argument()));
3482 case LFUN_DIALOG_HIDE: {
3483 guiApp->hideDialogs(to_utf8(cmd.argument()), 0);
3487 case LFUN_DIALOG_SHOW: {
3488 string const name = cmd.getArg(0);
3489 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
3491 if (name == "character") {
3492 data = freefont2string();
3494 showDialog("character", data);
3495 } else if (name == "latexlog") {
3496 Buffer::LogType type;
3497 string const logfile = doc_buffer->logName(&type);
3499 case Buffer::latexlog:
3502 case Buffer::buildlog:
3506 data += Lexer::quoteString(logfile);
3507 showDialog("log", data);
3508 } else if (name == "vclog") {
3509 string const data = "vc " +
3510 Lexer::quoteString(doc_buffer->lyxvc().getLogFile());
3511 showDialog("log", data);
3512 } else if (name == "symbols") {
3513 data = bv->cursor().getEncoding()->name();
3515 showDialog("symbols", data);
3517 } else if (name == "prefs" && isFullScreen()) {
3518 lfunUiToggle("fullscreen");
3519 showDialog("prefs", data);
3521 showDialog(name, data);
3526 dr.setMessage(cmd.argument());
3529 case LFUN_UI_TOGGLE: {
3530 string arg = cmd.getArg(0);
3531 if (!lfunUiToggle(arg)) {
3532 docstring const msg = "ui-toggle " + _("%1$s unknown command!");
3533 dr.setMessage(bformat(msg, from_utf8(arg)));
3535 // Make sure the keyboard focus stays in the work area.
3540 case LFUN_SPLIT_VIEW: {
3541 LASSERT(doc_buffer, break);
3542 string const orientation = cmd.getArg(0);
3543 d.splitter_->setOrientation(orientation == "vertical"
3544 ? Qt::Vertical : Qt::Horizontal);
3545 TabWorkArea * twa = addTabWorkArea();
3546 GuiWorkArea * wa = twa->addWorkArea(*doc_buffer, *this);
3547 setCurrentWorkArea(wa);
3550 case LFUN_CLOSE_TAB_GROUP:
3551 if (TabWorkArea * twa = d.currentTabWorkArea()) {
3552 closeTabWorkArea(twa);
3553 d.current_work_area_ = 0;
3554 twa = d.currentTabWorkArea();
3555 // Switch to the next GuiWorkArea in the found TabWorkArea.
3557 // Make sure the work area is up to date.
3558 setCurrentWorkArea(twa->currentWorkArea());
3560 setCurrentWorkArea(0);
3565 case LFUN_COMPLETION_INLINE:
3566 if (d.current_work_area_)
3567 d.current_work_area_->completer().showInline();
3570 case LFUN_COMPLETION_POPUP:
3571 if (d.current_work_area_)
3572 d.current_work_area_->completer().showPopup();
3576 case LFUN_COMPLETION_COMPLETE:
3577 if (d.current_work_area_)
3578 d.current_work_area_->completer().tab();
3581 case LFUN_COMPLETION_CANCEL:
3582 if (d.current_work_area_) {
3583 if (d.current_work_area_->completer().popupVisible())
3584 d.current_work_area_->completer().hidePopup();
3586 d.current_work_area_->completer().hideInline();
3590 case LFUN_COMPLETION_ACCEPT:
3591 if (d.current_work_area_)
3592 d.current_work_area_->completer().activate();
3595 case LFUN_BUFFER_ZOOM_IN:
3596 case LFUN_BUFFER_ZOOM_OUT:
3597 if (cmd.argument().empty()) {
3598 if (cmd.action() == LFUN_BUFFER_ZOOM_IN)
3603 lyxrc.zoom += convert<int>(cmd.argument());
3605 if (lyxrc.zoom < 10)
3608 // The global QPixmapCache is used in GuiPainter to cache text
3609 // painting so we must reset it.
3610 QPixmapCache::clear();
3611 guiApp->fontLoader().update();
3612 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
3615 case LFUN_VC_REGISTER:
3616 case LFUN_VC_CHECK_IN:
3617 case LFUN_VC_CHECK_OUT:
3618 case LFUN_VC_REPO_UPDATE:
3619 case LFUN_VC_LOCKING_TOGGLE:
3620 case LFUN_VC_REVERT:
3621 case LFUN_VC_UNDO_LAST:
3622 case LFUN_VC_COMMAND:
3623 case LFUN_VC_COMPARE:
3624 dispatchVC(cmd, dr);
3627 case LFUN_SERVER_GOTO_FILE_ROW:
3628 goToFileRow(to_utf8(cmd.argument()));
3631 case LFUN_FORWARD_SEARCH: {
3632 Buffer const * doc_master = doc_buffer->masterBuffer();
3633 FileName const path(doc_master->temppath());
3634 string const texname = doc_master->isChild(doc_buffer)
3635 ? DocFileName(changeExtension(
3636 doc_buffer->absFileName(),
3637 "tex")).mangledFileName()
3638 : doc_buffer->latexName();
3639 string const mastername =
3640 removeExtension(doc_master->latexName());
3641 FileName const dviname(addName(path.absFileName(),
3642 addExtension(mastername, "dvi")));
3643 FileName const pdfname(addName(path.absFileName(),
3644 addExtension(mastername, "pdf")));
3645 bool const have_dvi = dviname.exists();
3646 bool const have_pdf = pdfname.exists();
3647 if (!have_dvi && !have_pdf) {
3648 dr.setMessage(_("Please, preview the document first."));
3651 string outname = dviname.onlyFileName();
3652 string command = lyxrc.forward_search_dvi;
3653 if (!have_dvi || (have_pdf &&
3654 pdfname.lastModified() > dviname.lastModified())) {
3655 outname = pdfname.onlyFileName();
3656 command = lyxrc.forward_search_pdf;
3659 int row = doc_buffer->texrow().getRowFromIdPos(bv->cursor().paragraph().id(), bv->cursor().pos());
3660 LYXERR(Debug::ACTION, "Forward search: row:" << row
3661 << " id:" << bv->cursor().paragraph().id());
3662 if (!row || command.empty()) {
3663 dr.setMessage(_("Couldn't proceed."));
3666 string texrow = convert<string>(row);
3668 command = subst(command, "$$n", texrow);
3669 command = subst(command, "$$t", texname);
3670 command = subst(command, "$$o", outname);
3672 PathChanger p(path);
3674 one.startscript(Systemcall::DontWait, command);
3678 // The LFUN must be for one of BufferView, Buffer or Cursor;
3680 dispatchToBufferView(cmd, dr);
3684 // Part of automatic menu appearance feature.
3685 if (isFullScreen()) {
3686 if (menuBar()->isVisible() && lyxrc.full_screen_menubar)
3688 if (statusBar()->isVisible())
3689 statusBar()->hide();
3694 bool GuiView::lfunUiToggle(string const & ui_component)
3696 if (ui_component == "scrollbar") {
3697 // hide() is of no help
3698 if (d.current_work_area_->verticalScrollBarPolicy() ==
3699 Qt::ScrollBarAlwaysOff)
3701 d.current_work_area_->setVerticalScrollBarPolicy(
3702 Qt::ScrollBarAsNeeded);
3704 d.current_work_area_->setVerticalScrollBarPolicy(
3705 Qt::ScrollBarAlwaysOff);
3706 } else if (ui_component == "statusbar") {
3707 statusBar()->setVisible(!statusBar()->isVisible());
3708 } else if (ui_component == "menubar") {
3709 menuBar()->setVisible(!menuBar()->isVisible());
3711 #if QT_VERSION >= 0x040300
3712 if (ui_component == "frame") {
3714 getContentsMargins(&l, &t, &r, &b);
3715 //are the frames in default state?
3716 d.current_work_area_->setFrameStyle(QFrame::NoFrame);
3718 setContentsMargins(-2, -2, -2, -2);
3720 setContentsMargins(0, 0, 0, 0);
3724 if (ui_component == "fullscreen") {
3732 void GuiView::toggleFullScreen()
3734 if (isFullScreen()) {
3735 for (int i = 0; i != d.splitter_->count(); ++i)
3736 d.tabWorkArea(i)->setFullScreen(false);
3737 #if QT_VERSION >= 0x040300
3738 setContentsMargins(0, 0, 0, 0);
3740 setWindowState(windowState() ^ Qt::WindowFullScreen);
3743 statusBar()->show();
3746 hideDialogs("prefs", 0);
3747 for (int i = 0; i != d.splitter_->count(); ++i)
3748 d.tabWorkArea(i)->setFullScreen(true);
3749 #if QT_VERSION >= 0x040300
3750 setContentsMargins(-2, -2, -2, -2);
3753 setWindowState(windowState() ^ Qt::WindowFullScreen);
3754 statusBar()->hide();
3755 if (lyxrc.full_screen_menubar)
3757 if (lyxrc.full_screen_toolbars) {
3758 ToolbarMap::iterator end = d.toolbars_.end();
3759 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
3764 // give dialogs like the TOC a chance to adapt
3769 Buffer const * GuiView::updateInset(Inset const * inset)
3774 Buffer const * inset_buffer = &(inset->buffer());
3776 for (int i = 0; i != d.splitter_->count(); ++i) {
3777 GuiWorkArea * wa = d.tabWorkArea(i)->currentWorkArea();
3780 Buffer const * buffer = &(wa->bufferView().buffer());
3781 if (inset_buffer == buffer)
3782 wa->scheduleRedraw();
3784 return inset_buffer;
3788 void GuiView::restartCursor()
3790 /* When we move around, or type, it's nice to be able to see
3791 * the cursor immediately after the keypress.
3793 if (d.current_work_area_)
3794 d.current_work_area_->startBlinkingCursor();
3796 // Take this occasion to update the other GUI elements.
3802 void GuiView::updateCompletion(Cursor & cur, bool start, bool keep)
3804 if (d.current_work_area_)
3805 d.current_work_area_->completer().updateVisibility(cur, start, keep);
3810 // This list should be kept in sync with the list of insets in
3811 // src/insets/Inset.cpp. I.e., if a dialog goes with an inset, the
3812 // dialog should have the same name as the inset.
3813 // Changes should be also recorded in LFUN_DIALOG_SHOW doxygen
3814 // docs in LyXAction.cpp.
3816 char const * const dialognames[] = {
3818 "aboutlyx", "bibitem", "bibtex", "box", "branch", "changes", "character",
3819 "citation", "compare", "comparehistory", "document", "errorlist", "ert",
3820 "external", "file", "findreplace", "findreplaceadv", "float", "graphics",
3821 "href", "include", "index", "index_print", "info", "listings", "label", "line",
3822 "log", "mathdelimiter", "mathmatrix", "mathspace", "nomenclature",
3823 "nomencl_print", "note", "paragraph", "phantom", "prefs", "print", "ref",
3824 "sendto", "space", "spellchecker", "symbols", "tabular", "tabularcreate",
3825 "thesaurus", "texinfo", "toc", "view-source", "vspace", "wrap", "progress"};
3827 char const * const * const end_dialognames =
3828 dialognames + (sizeof(dialognames) / sizeof(char *));
3832 cmpCStr(char const * name) : name_(name) {}
3833 bool operator()(char const * other) {
3834 return strcmp(other, name_) == 0;
3841 bool isValidName(string const & name)
3843 return find_if(dialognames, end_dialognames,
3844 cmpCStr(name.c_str())) != end_dialognames;
3850 void GuiView::resetDialogs()
3852 // Make sure that no LFUN uses any GuiView.
3853 guiApp->setCurrentView(0);
3857 constructToolbars();
3858 guiApp->menus().fillMenuBar(menuBar(), this, false);
3859 d.layout_->updateContents(true);
3860 // Now update controls with current buffer.
3861 guiApp->setCurrentView(this);
3867 Dialog * GuiView::findOrBuild(string const & name, bool hide_it)
3869 if (!isValidName(name))
3872 map<string, DialogPtr>::iterator it = d.dialogs_.find(name);
3874 if (it != d.dialogs_.end()) {
3876 it->second->hideView();
3877 return it->second.get();
3880 Dialog * dialog = build(name);
3881 d.dialogs_[name].reset(dialog);
3882 if (lyxrc.allow_geometry_session)
3883 dialog->restoreSession();
3890 void GuiView::showDialog(string const & name, string const & data,
3893 triggerShowDialog(toqstr(name), toqstr(data), inset);
3897 void GuiView::doShowDialog(QString const & qname, QString const & qdata,
3903 const string name = fromqstr(qname);
3904 const string data = fromqstr(qdata);
3908 Dialog * dialog = findOrBuild(name, false);
3910 bool const visible = dialog->isVisibleView();
3911 dialog->showData(data);
3912 if (inset && currentBufferView())
3913 currentBufferView()->editInset(name, inset);
3914 // We only set the focus to the new dialog if it was not yet
3915 // visible in order not to change the existing previous behaviour
3917 // activateWindow is needed for floating dockviews
3918 dialog->asQWidget()->raise();
3919 dialog->asQWidget()->activateWindow();
3920 dialog->asQWidget()->setFocus();
3924 catch (ExceptionMessage const & ex) {
3932 bool GuiView::isDialogVisible(string const & name) const
3934 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3935 if (it == d.dialogs_.end())
3937 return it->second.get()->isVisibleView() && !it->second.get()->isClosing();
3941 void GuiView::hideDialog(string const & name, Inset * inset)
3943 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3944 if (it == d.dialogs_.end())
3948 if (!currentBufferView())
3950 if (inset != currentBufferView()->editedInset(name))
3954 Dialog * const dialog = it->second.get();
3955 if (dialog->isVisibleView())
3957 if (currentBufferView())
3958 currentBufferView()->editInset(name, 0);
3962 void GuiView::disconnectDialog(string const & name)
3964 if (!isValidName(name))
3966 if (currentBufferView())
3967 currentBufferView()->editInset(name, 0);
3971 void GuiView::hideAll() const
3973 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
3974 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3976 for(; it != end; ++it)
3977 it->second->hideView();
3981 void GuiView::updateDialogs()
3983 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
3984 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3986 for(; it != end; ++it) {
3987 Dialog * dialog = it->second.get();
3989 if (dialog->needBufferOpen() && !documentBufferView())
3990 hideDialog(fromqstr(dialog->name()), 0);
3991 else if (dialog->isVisibleView())
3992 dialog->checkStatus();
3999 Dialog * createDialog(GuiView & lv, string const & name);
4001 // will be replaced by a proper factory...
4002 Dialog * createGuiAbout(GuiView & lv);
4003 Dialog * createGuiBibtex(GuiView & lv);
4004 Dialog * createGuiChanges(GuiView & lv);
4005 Dialog * createGuiCharacter(GuiView & lv);
4006 Dialog * createGuiCitation(GuiView & lv);
4007 Dialog * createGuiCompare(GuiView & lv);
4008 Dialog * createGuiCompareHistory(GuiView & lv);
4009 Dialog * createGuiDelimiter(GuiView & lv);
4010 Dialog * createGuiDocument(GuiView & lv);
4011 Dialog * createGuiErrorList(GuiView & lv);
4012 Dialog * createGuiExternal(GuiView & lv);
4013 Dialog * createGuiGraphics(GuiView & lv);
4014 Dialog * createGuiInclude(GuiView & lv);
4015 Dialog * createGuiIndex(GuiView & lv);
4016 Dialog * createGuiListings(GuiView & lv);
4017 Dialog * createGuiLog(GuiView & lv);
4018 Dialog * createGuiMathMatrix(GuiView & lv);
4019 Dialog * createGuiNote(GuiView & lv);
4020 Dialog * createGuiParagraph(GuiView & lv);
4021 Dialog * createGuiPhantom(GuiView & lv);
4022 Dialog * createGuiPreferences(GuiView & lv);
4023 Dialog * createGuiPrint(GuiView & lv);
4024 Dialog * createGuiPrintindex(GuiView & lv);
4025 Dialog * createGuiRef(GuiView & lv);
4026 Dialog * createGuiSearch(GuiView & lv);
4027 Dialog * createGuiSearchAdv(GuiView & lv);
4028 Dialog * createGuiSendTo(GuiView & lv);
4029 Dialog * createGuiShowFile(GuiView & lv);
4030 Dialog * createGuiSpellchecker(GuiView & lv);
4031 Dialog * createGuiSymbols(GuiView & lv);
4032 Dialog * createGuiTabularCreate(GuiView & lv);
4033 Dialog * createGuiTexInfo(GuiView & lv);
4034 Dialog * createGuiToc(GuiView & lv);
4035 Dialog * createGuiThesaurus(GuiView & lv);
4036 Dialog * createGuiViewSource(GuiView & lv);
4037 Dialog * createGuiWrap(GuiView & lv);
4038 Dialog * createGuiProgressView(GuiView & lv);
4042 Dialog * GuiView::build(string const & name)
4044 LASSERT(isValidName(name), return 0);
4046 Dialog * dialog = createDialog(*this, name);
4050 if (name == "aboutlyx")
4051 return createGuiAbout(*this);
4052 if (name == "bibtex")
4053 return createGuiBibtex(*this);
4054 if (name == "changes")
4055 return createGuiChanges(*this);
4056 if (name == "character")
4057 return createGuiCharacter(*this);
4058 if (name == "citation")
4059 return createGuiCitation(*this);
4060 if (name == "compare")
4061 return createGuiCompare(*this);
4062 if (name == "comparehistory")
4063 return createGuiCompareHistory(*this);
4064 if (name == "document")
4065 return createGuiDocument(*this);
4066 if (name == "errorlist")
4067 return createGuiErrorList(*this);
4068 if (name == "external")
4069 return createGuiExternal(*this);
4071 return createGuiShowFile(*this);
4072 if (name == "findreplace")
4073 return createGuiSearch(*this);
4074 if (name == "findreplaceadv")
4075 return createGuiSearchAdv(*this);
4076 if (name == "graphics")
4077 return createGuiGraphics(*this);
4078 if (name == "include")
4079 return createGuiInclude(*this);
4080 if (name == "index")
4081 return createGuiIndex(*this);
4082 if (name == "index_print")
4083 return createGuiPrintindex(*this);
4084 if (name == "listings")
4085 return createGuiListings(*this);
4087 return createGuiLog(*this);
4088 if (name == "mathdelimiter")
4089 return createGuiDelimiter(*this);
4090 if (name == "mathmatrix")
4091 return createGuiMathMatrix(*this);
4093 return createGuiNote(*this);
4094 if (name == "paragraph")
4095 return createGuiParagraph(*this);
4096 if (name == "phantom")
4097 return createGuiPhantom(*this);
4098 if (name == "prefs")
4099 return createGuiPreferences(*this);
4100 if (name == "print")
4101 return createGuiPrint(*this);
4103 return createGuiRef(*this);
4104 if (name == "sendto")
4105 return createGuiSendTo(*this);
4106 if (name == "spellchecker")
4107 return createGuiSpellchecker(*this);
4108 if (name == "symbols")
4109 return createGuiSymbols(*this);
4110 if (name == "tabularcreate")
4111 return createGuiTabularCreate(*this);
4112 if (name == "texinfo")
4113 return createGuiTexInfo(*this);
4114 if (name == "thesaurus")
4115 return createGuiThesaurus(*this);
4117 return createGuiToc(*this);
4118 if (name == "view-source")
4119 return createGuiViewSource(*this);
4121 return createGuiWrap(*this);
4122 if (name == "progress")
4123 return createGuiProgressView(*this);
4129 } // namespace frontend
4132 #include "moc_GuiView.cpp"