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 // assign an icon to main form. We do not do it under Qt/Win or Qt/Mac,
448 // since the icon is provided in the application bundle.
449 setWindowIcon(getPixmap("images/", "lyx", "png"));
452 #if (QT_VERSION >= 0x040300)
453 // use tabbed dock area for multiple docks
454 // (such as "source" and "messages")
455 setDockOptions(QMainWindow::ForceTabbedDocks);
459 setAcceptDrops(true);
461 #if (QT_VERSION >= 0x040400)
463 // add busy indicator to statusbar
464 QLabel * busylabel = new QLabel(statusBar());
465 statusBar()->addPermanentWidget(busylabel);
466 QString fn = toqstr(lyx::libFileSearch("images", "busy.gif").absFileName());
467 QMovie * busyanim = new QMovie(fn, QByteArray(), busylabel);
468 busylabel->setMovie(busyanim);
472 connect(&d.processing_thread_watcher_, SIGNAL(started()),
473 busylabel, SLOT(show()));
474 connect(&d.processing_thread_watcher_, SIGNAL(finished()),
475 busylabel, SLOT(hide()));
477 statusBar()->setSizeGripEnabled(true);
480 connect(&d.autosave_watcher_, SIGNAL(finished()), this,
481 SLOT(autoSaveThreadFinished()));
483 connect(&d.processing_thread_watcher_, SIGNAL(started()), this,
484 SLOT(processingThreadStarted()));
485 connect(&d.processing_thread_watcher_, SIGNAL(finished()), this,
486 SLOT(processingThreadFinished()));
490 connect(this, SIGNAL(triggerShowDialog(QString const &, QString const &, Inset *)),
491 SLOT(doShowDialog(QString const &, QString const &, Inset *)));
493 // Forbid too small unresizable window because it can happen
494 // with some window manager under X11.
495 setMinimumSize(300, 200);
497 if (lyxrc.allow_geometry_session) {
498 // Now take care of session management.
503 // no session handling, default to a sane size.
504 setGeometry(50, 50, 690, 510);
507 // clear session data if any.
509 settings.remove("views");
519 QVector<GuiWorkArea*> GuiView::GuiViewPrivate::guiWorkAreas()
521 QVector<GuiWorkArea*> areas;
522 for (int i = 0; i < tabWorkAreaCount(); i++) {
523 TabWorkArea* ta = tabWorkArea(i);
524 for (int u = 0; u < ta->count(); u++) {
525 areas << ta->workArea(u);
531 static void handleExportStatus(GuiView * view, Buffer::ExportStatus status,
532 string const & format)
534 docstring const fmt = formats.prettyName(format);
537 case Buffer::ExportSuccess:
538 msg = bformat(_("Successful export to format: %1$s"), fmt);
540 case Buffer::ExportCancel:
541 msg = _("Document export cancelled.");
543 case Buffer::ExportError:
544 case Buffer::ExportNoPathToFormat:
545 case Buffer::ExportTexPathHasSpaces:
546 case Buffer::ExportConverterError:
547 msg = bformat(_("Error while exporting format: %1$s"), fmt);
549 case Buffer::PreviewSuccess:
550 msg = bformat(_("Successful preview of format: %1$s"), fmt);
552 case Buffer::PreviewError:
553 msg = bformat(_("Error while previewing format: %1$s"), fmt);
560 #if QT_VERSION >= 0x040400
562 void GuiView::processingThreadStarted()
567 void GuiView::processingThreadFinished(bool show_errors)
569 QFutureWatcher<Buffer::ExportStatus> const * watcher =
570 static_cast<QFutureWatcher<Buffer::ExportStatus> const *>(sender());
572 Buffer::ExportStatus const status = watcher->result();
573 handleExportStatus(this, status, d.processing_format);
577 BufferView const * const bv = currentBufferView();
578 if (bv && !bv->buffer().errorList("Export").empty()) {
582 errors(d.last_export_format);
587 void GuiView::processingThreadFinished()
589 processingThreadFinished(true);
593 void GuiView::autoSaveThreadFinished()
595 processingThreadFinished(false);
601 void GuiView::processingThreadStarted()
606 void GuiView::processingThreadFinished(bool)
611 void GuiView::processingThreadFinished()
616 void GuiView::autoSaveThreadFinished()
622 void GuiView::saveLayout() const
625 settings.beginGroup("views");
626 settings.beginGroup(QString::number(id_));
628 settings.setValue("pos", pos());
629 settings.setValue("size", size());
631 settings.setValue("geometry", saveGeometry());
633 settings.setValue("layout", saveState(0));
634 settings.setValue("icon_size", iconSize());
638 void GuiView::saveUISettings() const
640 // Save the toolbar private states
641 ToolbarMap::iterator end = d.toolbars_.end();
642 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
643 it->second->saveSession();
644 // Now take care of all other dialogs
645 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
646 for (; it!= d.dialogs_.end(); ++it)
647 it->second->saveSession();
651 bool GuiView::restoreLayout()
654 settings.beginGroup("views");
655 settings.beginGroup(QString::number(id_));
656 QString const icon_key = "icon_size";
657 if (!settings.contains(icon_key))
660 //code below is skipped when when ~/.config/LyX is (re)created
661 QSize icon_size = settings.value(icon_key).toSize();
662 // Check whether session size changed.
663 if (icon_size.width() != int(d.smallIconSize) &&
664 icon_size.width() != int(d.normalIconSize) &&
665 icon_size.width() != int(d.bigIconSize)) {
666 icon_size.setWidth(d.normalIconSize);
667 icon_size.setHeight(d.normalIconSize);
669 setIconSize(icon_size);
672 QPoint pos = settings.value("pos", QPoint(50, 50)).toPoint();
673 QSize size = settings.value("size", QSize(690, 510)).toSize();
677 // Work-around for bug #6034: the window ends up in an undetermined
678 // state when trying to restore a maximized window when it is
679 // already maximized.
680 if (!(windowState() & Qt::WindowMaximized))
681 if (!restoreGeometry(settings.value("geometry").toByteArray()))
682 setGeometry(50, 50, 690, 510);
684 // Make sure layout is correctly oriented.
685 setLayoutDirection(qApp->layoutDirection());
687 // Allow the toc and view-source dock widget to be restored if needed.
689 if ((dialog = findOrBuild("toc", true)))
690 // see bug 5082. At least setup title and enabled state.
691 // Visibility will be adjusted by restoreState below.
692 dialog->prepareView();
693 if ((dialog = findOrBuild("view-source", true)))
694 dialog->prepareView();
695 if ((dialog = findOrBuild("progress", true)))
696 dialog->prepareView();
697 if ((dialog = findOrBuild("findreplaceadv", true)))
698 dialog->prepareView();
700 if (!restoreState(settings.value("layout").toByteArray(), 0))
707 GuiToolbar * GuiView::toolbar(string const & name)
709 ToolbarMap::iterator it = d.toolbars_.find(name);
710 if (it != d.toolbars_.end())
713 LYXERR(Debug::GUI, "Toolbar::display: no toolbar named " << name);
718 void GuiView::constructToolbars()
720 ToolbarMap::iterator it = d.toolbars_.begin();
721 for (; it != d.toolbars_.end(); ++it)
725 // I don't like doing this here, but the standard toolbar
726 // destroys this object when it's destroyed itself (vfr)
727 d.layout_ = new LayoutBox(*this);
728 d.stack_widget_->addWidget(d.layout_);
729 d.layout_->move(0,0);
731 // extracts the toolbars from the backend
732 Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
733 Toolbars::Infos::iterator end = guiApp->toolbars().end();
734 for (; cit != end; ++cit)
735 d.toolbars_[cit->name] = new GuiToolbar(*cit, *this);
739 void GuiView::initToolbars()
741 // extracts the toolbars from the backend
742 Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
743 Toolbars::Infos::iterator end = guiApp->toolbars().end();
744 for (; cit != end; ++cit) {
745 GuiToolbar * tb = toolbar(cit->name);
748 int const visibility = guiApp->toolbars().defaultVisibility(cit->name);
749 bool newline = !(visibility & Toolbars::SAMEROW);
750 tb->setVisible(false);
751 tb->setVisibility(visibility);
753 if (visibility & Toolbars::TOP) {
755 addToolBarBreak(Qt::TopToolBarArea);
756 addToolBar(Qt::TopToolBarArea, tb);
759 if (visibility & Toolbars::BOTTOM) {
760 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
761 #if (QT_VERSION >= 0x040202)
763 addToolBarBreak(Qt::BottomToolBarArea);
765 addToolBar(Qt::BottomToolBarArea, tb);
768 if (visibility & Toolbars::LEFT) {
769 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
770 #if (QT_VERSION >= 0x040202)
772 addToolBarBreak(Qt::LeftToolBarArea);
774 addToolBar(Qt::LeftToolBarArea, tb);
777 if (visibility & Toolbars::RIGHT) {
778 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
779 #if (QT_VERSION >= 0x040202)
781 addToolBarBreak(Qt::RightToolBarArea);
783 addToolBar(Qt::RightToolBarArea, tb);
786 if (visibility & Toolbars::ON)
787 tb->setVisible(true);
792 TocModels & GuiView::tocModels()
794 return d.toc_models_;
798 void GuiView::setFocus()
800 LYXERR(Debug::DEBUG, "GuiView::setFocus()" << this);
801 QMainWindow::setFocus();
805 void GuiView::focusInEvent(QFocusEvent * e)
807 LYXERR(Debug::DEBUG, "GuiView::focusInEvent()" << this);
808 QMainWindow::focusInEvent(e);
809 // Make sure guiApp points to the correct view.
810 guiApp->setCurrentView(this);
811 if (currentWorkArea())
812 currentWorkArea()->setFocus();
813 else if (currentMainWorkArea())
814 currentMainWorkArea()->setFocus();
816 d.bg_widget_->setFocus();
820 QMenu * GuiView::createPopupMenu()
822 return d.toolBarPopup(this);
826 void GuiView::showEvent(QShowEvent * e)
828 LYXERR(Debug::GUI, "Passed Geometry "
829 << size().height() << "x" << size().width()
830 << "+" << pos().x() << "+" << pos().y());
832 if (d.splitter_->count() == 0)
833 // No work area, switch to the background widget.
837 QMainWindow::showEvent(e);
841 bool GuiView::closeScheduled()
848 /** Destroy only all tabbed WorkAreas. Destruction of other WorkAreas
849 ** is responsibility of the container (e.g., dialog)
851 void GuiView::closeEvent(QCloseEvent * close_event)
853 LYXERR(Debug::DEBUG, "GuiView::closeEvent()");
855 if (!GuiViewPrivate::busyBuffers.isEmpty()) {
856 Alert::warning(_("Exit LyX"),
857 _("LyX could not be closed because documents are being processed by LyX."));
858 close_event->setAccepted(false);
862 // If the user pressed the x (so we didn't call closeView
863 // programmatically), we want to clear all existing entries.
865 theSession().lastOpened().clear();
870 // it can happen that this event arrives without selecting the view,
871 // e.g. when clicking the close button on a background window.
873 if (!closeWorkAreaAll()) {
875 close_event->ignore();
879 // Make sure that nothing will use this to be closed View.
880 guiApp->unregisterView(this);
882 if (isFullScreen()) {
883 // Switch off fullscreen before closing.
888 // Make sure the timer time out will not trigger a statusbar update.
889 d.statusbar_timer_.stop();
891 // Saving fullscreen requires additional tweaks in the toolbar code.
892 // It wouldn't also work under linux natively.
893 if (lyxrc.allow_geometry_session) {
898 close_event->accept();
902 void GuiView::dragEnterEvent(QDragEnterEvent * event)
904 if (event->mimeData()->hasUrls())
906 /// \todo Ask lyx-devel is this is enough:
907 /// if (event->mimeData()->hasFormat("text/plain"))
908 /// event->acceptProposedAction();
912 void GuiView::dropEvent(QDropEvent * event)
914 QList<QUrl> files = event->mimeData()->urls();
918 LYXERR(Debug::GUI, "GuiView::dropEvent: got URLs!");
919 for (int i = 0; i != files.size(); ++i) {
920 string const file = os::internal_path(fromqstr(
921 files.at(i).toLocalFile()));
925 string const ext = support::getExtension(file);
926 vector<const Format *> found_formats;
928 // Find all formats that have the correct extension.
929 vector<const Format *> const & import_formats
930 = theConverters().importableFormats();
931 vector<const Format *>::const_iterator it = import_formats.begin();
932 for (; it != import_formats.end(); ++it)
933 if ((*it)->hasExtension(ext))
934 found_formats.push_back(*it);
937 if (found_formats.size() >= 1) {
938 if (found_formats.size() > 1) {
939 //FIXME: show a dialog to choose the correct importable format
941 "Multiple importable formats found, selecting first");
943 string const arg = found_formats[0]->name() + " " + file;
944 cmd = FuncRequest(LFUN_BUFFER_IMPORT, arg);
947 //FIXME: do we have to explicitly check whether it's a lyx file?
949 "No formats found, trying to open it as a lyx file");
950 cmd = FuncRequest(LFUN_FILE_OPEN, file);
952 // add the functions to the queue
953 guiApp->addToFuncRequestQueue(cmd);
956 // now process the collected functions. We perform the events
957 // asynchronously. This prevents potential problems in case the
958 // BufferView is closed within an event.
959 guiApp->processFuncRequestQueueAsync();
963 void GuiView::message(docstring const & str)
965 if (ForkedProcess::iAmAChild())
968 // call is moved to GUI-thread by GuiProgress
969 d.progress_->appendMessage(toqstr(str));
973 void GuiView::clearMessageText()
975 message(docstring());
979 void GuiView::updateStatusBarMessage(QString const & str)
981 statusBar()->showMessage(str);
982 d.statusbar_timer_.stop();
983 d.statusbar_timer_.start(3000);
987 void GuiView::smallSizedIcons()
989 setIconSize(QSize(d.smallIconSize, d.smallIconSize));
993 void GuiView::normalSizedIcons()
995 setIconSize(QSize(d.normalIconSize, d.normalIconSize));
999 void GuiView::bigSizedIcons()
1001 setIconSize(QSize(d.bigIconSize, d.bigIconSize));
1005 void GuiView::clearMessage()
1007 // FIXME: This code was introduced in r19643 to fix bug #4123. However,
1008 // the hasFocus function mostly returns false, even if the focus is on
1009 // a workarea in this view.
1013 d.statusbar_timer_.stop();
1017 void GuiView::updateWindowTitle(GuiWorkArea * wa)
1019 if (wa != d.current_work_area_
1020 || wa->bufferView().buffer().isInternal())
1022 setWindowTitle(qt_("LyX: ") + wa->windowTitle());
1023 setWindowIconText(wa->windowIconText());
1027 void GuiView::on_currentWorkAreaChanged(GuiWorkArea * wa)
1029 QObject::disconnect(d.current_work_area_, SIGNAL(busy(bool)),
1030 this, SLOT(setBusy(bool)));
1032 disconnectBufferView();
1033 connectBufferView(wa->bufferView());
1034 connectBuffer(wa->bufferView().buffer());
1035 d.current_work_area_ = wa;
1036 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
1037 this, SLOT(updateWindowTitle(GuiWorkArea *)));
1038 QObject::connect(wa, SIGNAL(busy(bool)), this, SLOT(setBusy(bool)));
1039 updateWindowTitle(wa);
1043 // The document settings needs to be reinitialised.
1044 updateDialog("document", "");
1046 // Buffer-dependent dialogs must be updated. This is done here because
1047 // some dialogs require buffer()->text.
1052 void GuiView::on_lastWorkAreaRemoved()
1055 // We already are in a close event. Nothing more to do.
1058 if (d.splitter_->count() > 1)
1059 // We have a splitter so don't close anything.
1062 // Reset and updates the dialogs.
1063 d.toc_models_.reset(0);
1064 updateDialog("document", "");
1067 resetWindowTitleAndIconText();
1070 if (lyxrc.open_buffers_in_tabs)
1071 // Nothing more to do, the window should stay open.
1074 if (guiApp->viewIds().size() > 1) {
1080 // On Mac we also close the last window because the application stay
1081 // resident in memory. On other platforms we don't close the last
1082 // window because this would quit the application.
1088 void GuiView::updateStatusBar()
1090 // let the user see the explicit message
1091 if (d.statusbar_timer_.isActive())
1098 void GuiView::showMessage()
1100 QString msg = toqstr(theGuiApp()->viewStatusMessage());
1101 if (msg.isEmpty()) {
1102 BufferView const * bv = currentBufferView();
1104 msg = toqstr(bv->cursor().currentState());
1106 msg = qt_("Welcome to LyX!");
1108 statusBar()->showMessage(msg);
1112 bool GuiView::event(QEvent * e)
1116 // Useful debug code:
1117 //case QEvent::ActivationChange:
1118 //case QEvent::WindowDeactivate:
1119 //case QEvent::Paint:
1120 //case QEvent::Enter:
1121 //case QEvent::Leave:
1122 //case QEvent::HoverEnter:
1123 //case QEvent::HoverLeave:
1124 //case QEvent::HoverMove:
1125 //case QEvent::StatusTip:
1126 //case QEvent::DragEnter:
1127 //case QEvent::DragLeave:
1128 //case QEvent::Drop:
1131 case QEvent::WindowActivate: {
1132 GuiView * old_view = guiApp->currentView();
1133 if (this == old_view) {
1135 return QMainWindow::event(e);
1137 if (old_view && old_view->currentBufferView()) {
1138 // save current selection to the selection buffer to allow
1139 // middle-button paste in this window.
1140 cap::saveSelection(old_view->currentBufferView()->cursor());
1142 guiApp->setCurrentView(this);
1143 if (d.current_work_area_) {
1144 BufferView & bv = d.current_work_area_->bufferView();
1145 connectBufferView(bv);
1146 connectBuffer(bv.buffer());
1147 // The document structure, name and dialogs might have
1148 // changed in another view.
1150 // The document settings needs to be reinitialised.
1151 updateDialog("document", "");
1154 resetWindowTitleAndIconText();
1157 return QMainWindow::event(e);
1160 case QEvent::ShortcutOverride: {
1163 #if (!defined Q_WS_X11) || (QT_VERSION >= 0x040500)
1164 if (isFullScreen() && menuBar()->isHidden()) {
1165 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
1166 // FIXME: we should also try to detect special LyX shortcut such as
1167 // Alt-P and Alt-M. Right now there is a hack in
1168 // GuiWorkArea::processKeySym() that hides again the menubar for
1170 if (ke->modifiers() & Qt::AltModifier && ke->key() != Qt::Key_Alt) {
1172 return QMainWindow::event(e);
1176 return QMainWindow::event(e);
1180 return QMainWindow::event(e);
1184 void GuiView::resetWindowTitleAndIconText()
1186 setWindowTitle(qt_("LyX"));
1187 setWindowIconText(qt_("LyX"));
1190 bool GuiView::focusNextPrevChild(bool /*next*/)
1197 bool GuiView::busy() const
1203 void GuiView::setBusy(bool busy)
1205 bool const busy_before = busy_ > 0;
1206 busy ? ++busy_ : --busy_;
1207 if ((busy_ > 0) == busy_before)
1208 // busy state didn't change
1212 QApplication::setOverrideCursor(Qt::WaitCursor);
1215 QApplication::restoreOverrideCursor();
1220 GuiWorkArea * GuiView::workArea(int index)
1222 if (TabWorkArea * twa = d.currentTabWorkArea())
1223 if (index < twa->count())
1224 return dynamic_cast<GuiWorkArea *>(twa->widget(index));
1229 GuiWorkArea * GuiView::workArea(Buffer & buffer)
1231 if (currentWorkArea()
1232 && ¤tWorkArea()->bufferView().buffer() == &buffer)
1233 return (GuiWorkArea *) currentWorkArea();
1234 if (TabWorkArea * twa = d.currentTabWorkArea())
1235 return twa->workArea(buffer);
1240 GuiWorkArea * GuiView::addWorkArea(Buffer & buffer)
1242 // Automatically create a TabWorkArea if there are none yet.
1243 TabWorkArea * tab_widget = d.splitter_->count()
1244 ? d.currentTabWorkArea() : addTabWorkArea();
1245 return tab_widget->addWorkArea(buffer, *this);
1249 TabWorkArea * GuiView::addTabWorkArea()
1251 TabWorkArea * twa = new TabWorkArea;
1252 QObject::connect(twa, SIGNAL(currentWorkAreaChanged(GuiWorkArea *)),
1253 this, SLOT(on_currentWorkAreaChanged(GuiWorkArea *)));
1254 QObject::connect(twa, SIGNAL(lastWorkAreaRemoved()),
1255 this, SLOT(on_lastWorkAreaRemoved()));
1257 d.splitter_->addWidget(twa);
1258 d.stack_widget_->setCurrentWidget(d.splitter_);
1263 GuiWorkArea const * GuiView::currentWorkArea() const
1265 return d.current_work_area_;
1269 GuiWorkArea * GuiView::currentWorkArea()
1271 return d.current_work_area_;
1275 GuiWorkArea const * GuiView::currentMainWorkArea() const
1277 if (!d.currentTabWorkArea())
1279 return d.currentTabWorkArea()->currentWorkArea();
1283 GuiWorkArea * GuiView::currentMainWorkArea()
1285 if (!d.currentTabWorkArea())
1287 return d.currentTabWorkArea()->currentWorkArea();
1291 void GuiView::setCurrentWorkArea(GuiWorkArea * wa)
1293 LYXERR(Debug::DEBUG, "Setting current wa: " << wa << endl);
1295 d.current_work_area_ = 0;
1300 // FIXME: I've no clue why this is here and why it accesses
1301 // theGuiApp()->currentView, which might be 0 (bug 6464).
1302 // See also 27525 (vfr).
1303 if (theGuiApp()->currentView() == this
1304 && theGuiApp()->currentView()->currentWorkArea() == wa)
1307 if (currentBufferView())
1308 cap::saveSelection(currentBufferView()->cursor());
1310 theGuiApp()->setCurrentView(this);
1311 d.current_work_area_ = wa;
1313 // We need to reset this now, because it will need to be
1314 // right if the tabWorkArea gets reset in the for loop. We
1315 // will change it back if we aren't in that case.
1316 GuiWorkArea * const old_cmwa = d.current_main_work_area_;
1317 d.current_main_work_area_ = wa;
1319 for (int i = 0; i != d.splitter_->count(); ++i) {
1320 if (d.tabWorkArea(i)->setCurrentWorkArea(wa)) {
1321 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea()
1322 << ", Current main wa: " << currentMainWorkArea());
1327 d.current_main_work_area_ = old_cmwa;
1329 LYXERR(Debug::DEBUG, "This is not a tabbed wa");
1330 on_currentWorkAreaChanged(wa);
1331 BufferView & bv = wa->bufferView();
1332 bv.cursor().fixIfBroken();
1334 wa->setUpdatesEnabled(true);
1335 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() << ", Current main wa: " << currentMainWorkArea());
1339 void GuiView::removeWorkArea(GuiWorkArea * wa)
1341 LASSERT(wa, return);
1342 if (wa == d.current_work_area_) {
1344 disconnectBufferView();
1345 d.current_work_area_ = 0;
1346 d.current_main_work_area_ = 0;
1349 bool found_twa = false;
1350 for (int i = 0; i != d.splitter_->count(); ++i) {
1351 TabWorkArea * twa = d.tabWorkArea(i);
1352 if (twa->removeWorkArea(wa)) {
1353 // Found in this tab group, and deleted the GuiWorkArea.
1355 if (twa->count() != 0) {
1356 if (d.current_work_area_ == 0)
1357 // This means that we are closing the current GuiWorkArea, so
1358 // switch to the next GuiWorkArea in the found TabWorkArea.
1359 setCurrentWorkArea(twa->currentWorkArea());
1361 // No more WorkAreas in this tab group, so delete it.
1368 // It is not a tabbed work area (i.e., the search work area), so it
1369 // should be deleted by other means.
1370 LASSERT(found_twa, /* */);
1372 if (d.current_work_area_ == 0) {
1373 if (d.splitter_->count() != 0) {
1374 TabWorkArea * twa = d.currentTabWorkArea();
1375 setCurrentWorkArea(twa->currentWorkArea());
1377 // No more work areas, switch to the background widget.
1378 setCurrentWorkArea(0);
1384 LayoutBox * GuiView::getLayoutDialog() const
1390 void GuiView::updateLayoutList()
1393 d.layout_->updateContents(false);
1397 void GuiView::updateToolbars()
1399 ToolbarMap::iterator end = d.toolbars_.end();
1400 if (d.current_work_area_) {
1402 d.current_work_area_->bufferView().cursor().inMathed()
1403 && !d.current_work_area_->bufferView().cursor().inRegexped();
1405 lyx::getStatus(FuncRequest(LFUN_LAYOUT_TABULAR)).enabled();
1407 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).enabled() &&
1408 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).onOff(true);
1409 bool const mathmacrotemplate =
1410 lyx::getStatus(FuncRequest(LFUN_IN_MATHMACROTEMPLATE)).enabled();
1412 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1413 it->second->update(math, table, review, mathmacrotemplate);
1415 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1416 it->second->update(false, false, false, false);
1420 void GuiView::setBuffer(Buffer * newBuffer)
1422 LYXERR(Debug::DEBUG, "Setting buffer: " << newBuffer << endl);
1423 LASSERT(newBuffer, return);
1425 GuiWorkArea * wa = workArea(*newBuffer);
1428 newBuffer->masterBuffer()->updateBuffer();
1430 wa = addWorkArea(*newBuffer);
1431 // scroll to the position when the BufferView was last closed
1432 if (lyxrc.use_lastfilepos) {
1433 LastFilePosSection::FilePos filepos =
1434 theSession().lastFilePos().load(newBuffer->fileName());
1435 wa->bufferView().moveToPosition(filepos.pit, filepos.pos, 0, 0);
1438 //Disconnect the old buffer...there's no new one.
1441 connectBuffer(*newBuffer);
1442 connectBufferView(wa->bufferView());
1443 setCurrentWorkArea(wa);
1447 void GuiView::connectBuffer(Buffer & buf)
1449 buf.setGuiDelegate(this);
1453 void GuiView::disconnectBuffer()
1455 if (d.current_work_area_)
1456 d.current_work_area_->bufferView().buffer().setGuiDelegate(0);
1460 void GuiView::connectBufferView(BufferView & bv)
1462 bv.setGuiDelegate(this);
1466 void GuiView::disconnectBufferView()
1468 if (d.current_work_area_)
1469 d.current_work_area_->bufferView().setGuiDelegate(0);
1473 void GuiView::errors(string const & error_type, bool from_master)
1475 BufferView const * const bv = currentBufferView();
1479 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
1480 // We are called with from_master == false by default, so we
1481 // have to figure out whether that is the case or not.
1482 ErrorList & el = bv->buffer().errorList(error_type);
1484 el = bv->buffer().masterBuffer()->errorList(error_type);
1488 ErrorList const & el = from_master ?
1489 bv->buffer().masterBuffer()->errorList(error_type) :
1490 bv->buffer().errorList(error_type);
1496 string data = error_type;
1498 data = "from_master|" + error_type;
1499 showDialog("errorlist", data);
1503 void GuiView::updateTocItem(string const & type, DocIterator const & dit)
1505 d.toc_models_.updateItem(toqstr(type), dit);
1509 void GuiView::structureChanged()
1511 d.toc_models_.reset(documentBufferView());
1512 // Navigator needs more than a simple update in this case. It needs to be
1514 updateDialog("toc", "");
1518 void GuiView::updateDialog(string const & name, string const & data)
1520 if (!isDialogVisible(name))
1523 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
1524 if (it == d.dialogs_.end())
1527 Dialog * const dialog = it->second.get();
1528 if (dialog->isVisibleView())
1529 dialog->initialiseParams(data);
1533 BufferView * GuiView::documentBufferView()
1535 return currentMainWorkArea()
1536 ? ¤tMainWorkArea()->bufferView()
1541 BufferView const * GuiView::documentBufferView() const
1543 return currentMainWorkArea()
1544 ? ¤tMainWorkArea()->bufferView()
1549 BufferView * GuiView::currentBufferView()
1551 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1555 BufferView const * GuiView::currentBufferView() const
1557 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1561 #if (QT_VERSION >= 0x040400)
1562 docstring GuiView::GuiViewPrivate::autosaveAndDestroy(
1563 Buffer const * orig, Buffer * buffer)
1565 bool const success = buffer->autoSave();
1567 busyBuffers.remove(orig);
1569 ? _("Automatic save done.")
1570 : _("Automatic save failed!");
1575 void GuiView::autoSave()
1577 LYXERR(Debug::INFO, "Running autoSave()");
1579 Buffer * buffer = documentBufferView()
1580 ? &documentBufferView()->buffer() : 0;
1582 resetAutosaveTimers();
1586 #if (QT_VERSION >= 0x040400)
1587 GuiViewPrivate::busyBuffers.insert(buffer);
1588 QFuture<docstring> f = QtConcurrent::run(GuiViewPrivate::autosaveAndDestroy,
1589 buffer, buffer->clone());
1590 d.autosave_watcher_.setFuture(f);
1594 resetAutosaveTimers();
1598 void GuiView::resetAutosaveTimers()
1601 d.autosave_timeout_.restart();
1605 bool GuiView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1608 Buffer * buf = currentBufferView()
1609 ? ¤tBufferView()->buffer() : 0;
1610 Buffer * doc_buffer = documentBufferView()
1611 ? &(documentBufferView()->buffer()) : 0;
1613 // Check whether we need a buffer
1614 if (!lyxaction.funcHasFlag(cmd.action(), LyXAction::NoBuffer) && !buf) {
1615 // no, exit directly
1616 flag.message(from_utf8(N_("Command not allowed with"
1617 "out any document open")));
1618 flag.setEnabled(false);
1622 if (cmd.origin() == FuncRequest::TOC) {
1623 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
1624 if (!toc || !toc->getStatus(documentBufferView()->cursor(), cmd, flag))
1625 flag.setEnabled(false);
1629 switch(cmd.action()) {
1630 case LFUN_BUFFER_IMPORT:
1633 case LFUN_MASTER_BUFFER_UPDATE:
1634 case LFUN_MASTER_BUFFER_VIEW:
1635 enable = doc_buffer && doc_buffer->parent() != 0
1636 && !d.processing_thread_watcher_.isRunning();
1639 case LFUN_BUFFER_UPDATE:
1640 case LFUN_BUFFER_VIEW: {
1641 if (!doc_buffer || d.processing_thread_watcher_.isRunning()) {
1645 string format = to_utf8(cmd.argument());
1646 if (cmd.argument().empty())
1647 format = doc_buffer->params().getDefaultOutputFormat();
1648 enable = doc_buffer->params().isExportableFormat(format);
1652 case LFUN_BUFFER_RELOAD:
1653 enable = doc_buffer && !doc_buffer->isUnnamed()
1654 && doc_buffer->fileName().exists()
1655 && (!doc_buffer->isClean()
1656 || doc_buffer->isExternallyModified(Buffer::timestamp_method));
1659 case LFUN_BUFFER_CHILD_OPEN:
1660 enable = doc_buffer;
1663 case LFUN_BUFFER_WRITE:
1664 enable = doc_buffer && (doc_buffer->isUnnamed() || !doc_buffer->isClean());
1667 //FIXME: This LFUN should be moved to GuiApplication.
1668 case LFUN_BUFFER_WRITE_ALL: {
1669 // We enable the command only if there are some modified buffers
1670 Buffer * first = theBufferList().first();
1675 // We cannot use a for loop as the buffer list is a cycle.
1677 if (!b->isClean()) {
1681 b = theBufferList().next(b);
1682 } while (b != first);
1686 case LFUN_BUFFER_WRITE_AS:
1687 case LFUN_BUFFER_EXPORT_AS:
1688 enable = doc_buffer;
1691 case LFUN_BUFFER_CLOSE:
1692 enable = doc_buffer;
1695 case LFUN_BUFFER_CLOSE_ALL:
1696 enable = theBufferList().last() != theBufferList().first();
1699 case LFUN_SPLIT_VIEW:
1700 if (cmd.getArg(0) == "vertical")
1701 enable = doc_buffer && (d.splitter_->count() == 1 ||
1702 d.splitter_->orientation() == Qt::Vertical);
1704 enable = doc_buffer && (d.splitter_->count() == 1 ||
1705 d.splitter_->orientation() == Qt::Horizontal);
1708 case LFUN_CLOSE_TAB_GROUP:
1709 enable = d.currentTabWorkArea();
1712 case LFUN_TOOLBAR_TOGGLE: {
1713 string const name = cmd.getArg(0);
1714 if (GuiToolbar * t = toolbar(name))
1715 flag.setOnOff(t->isVisible());
1718 docstring const msg =
1719 bformat(_("Unknown toolbar \"%1$s\""), from_utf8(name));
1725 case LFUN_DROP_LAYOUTS_CHOICE:
1729 case LFUN_UI_TOGGLE:
1730 flag.setOnOff(isFullScreen());
1733 case LFUN_DIALOG_DISCONNECT_INSET:
1736 case LFUN_DIALOG_HIDE:
1737 // FIXME: should we check if the dialog is shown?
1740 case LFUN_DIALOG_TOGGLE:
1741 flag.setOnOff(isDialogVisible(cmd.getArg(0)));
1742 // fall through to set "enable"
1743 case LFUN_DIALOG_SHOW: {
1744 string const name = cmd.getArg(0);
1746 enable = name == "aboutlyx"
1747 || name == "file" //FIXME: should be removed.
1749 || name == "texinfo"
1750 || name == "progress"
1751 || name == "compare";
1752 else if (name == "print")
1753 enable = doc_buffer->params().isExportable("dvi")
1754 && lyxrc.print_command != "none";
1755 else if (name == "character" || name == "symbols") {
1756 if (!buf || buf->isReadonly())
1759 Cursor const & cur = currentBufferView()->cursor();
1760 enable = !(cur.inTexted() && cur.paragraph().isPassThru());
1763 else if (name == "latexlog")
1764 enable = FileName(doc_buffer->logName()).isReadableFile();
1765 else if (name == "spellchecker")
1766 enable = theSpellChecker() && !doc_buffer->isReadonly();
1767 else if (name == "vclog")
1768 enable = doc_buffer->lyxvc().inUse();
1772 case LFUN_DIALOG_UPDATE: {
1773 string const name = cmd.getArg(0);
1775 enable = name == "prefs";
1779 case LFUN_COMMAND_EXECUTE:
1781 case LFUN_MENU_OPEN:
1782 // Nothing to check.
1785 case LFUN_COMPLETION_INLINE:
1786 if (!d.current_work_area_
1787 || !d.current_work_area_->completer().inlinePossible(
1788 currentBufferView()->cursor()))
1792 case LFUN_COMPLETION_POPUP:
1793 if (!d.current_work_area_
1794 || !d.current_work_area_->completer().popupPossible(
1795 currentBufferView()->cursor()))
1799 case LFUN_COMPLETION_COMPLETE:
1800 if (!d.current_work_area_
1801 || !d.current_work_area_->completer().inlinePossible(
1802 currentBufferView()->cursor()))
1806 case LFUN_COMPLETION_ACCEPT:
1807 if (!d.current_work_area_
1808 || (!d.current_work_area_->completer().popupVisible()
1809 && !d.current_work_area_->completer().inlineVisible()
1810 && !d.current_work_area_->completer().completionAvailable()))
1814 case LFUN_COMPLETION_CANCEL:
1815 if (!d.current_work_area_
1816 || (!d.current_work_area_->completer().popupVisible()
1817 && !d.current_work_area_->completer().inlineVisible()))
1821 case LFUN_BUFFER_ZOOM_OUT:
1822 enable = doc_buffer && lyxrc.zoom > 10;
1825 case LFUN_BUFFER_ZOOM_IN:
1826 enable = doc_buffer;
1829 case LFUN_BUFFER_NEXT:
1830 case LFUN_BUFFER_PREVIOUS:
1831 // FIXME: should we check is there is an previous or next buffer?
1833 case LFUN_BUFFER_SWITCH:
1834 // toggle on the current buffer, but do not toggle off
1835 // the other ones (is that a good idea?)
1837 && to_utf8(cmd.argument()) == doc_buffer->absFileName())
1838 flag.setOnOff(true);
1841 case LFUN_VC_REGISTER:
1842 enable = doc_buffer && !doc_buffer->lyxvc().inUse();
1844 case LFUN_VC_CHECK_IN:
1845 enable = doc_buffer && doc_buffer->lyxvc().checkInEnabled();
1847 case LFUN_VC_CHECK_OUT:
1848 enable = doc_buffer && doc_buffer->lyxvc().checkOutEnabled();
1850 case LFUN_VC_LOCKING_TOGGLE:
1851 enable = doc_buffer && !doc_buffer->isReadonly()
1852 && doc_buffer->lyxvc().lockingToggleEnabled();
1853 flag.setOnOff(enable && doc_buffer->lyxvc().locking());
1855 case LFUN_VC_REVERT:
1856 enable = doc_buffer && doc_buffer->lyxvc().inUse() && !doc_buffer->isReadonly();
1858 case LFUN_VC_UNDO_LAST:
1859 enable = doc_buffer && doc_buffer->lyxvc().undoLastEnabled();
1861 case LFUN_VC_REPO_UPDATE:
1862 enable = doc_buffer && doc_buffer->lyxvc().repoUpdateEnabled();
1864 case LFUN_VC_COMMAND: {
1865 if (cmd.argument().empty())
1867 if (!doc_buffer && contains(cmd.getArg(0), 'D'))
1871 case LFUN_VC_COMPARE:
1872 enable = doc_buffer && doc_buffer->lyxvc().prepareFileRevisionEnabled();
1875 case LFUN_SERVER_GOTO_FILE_ROW:
1877 case LFUN_FORWARD_SEARCH:
1878 enable = !(lyxrc.forward_search_dvi.empty() && lyxrc.forward_search_pdf.empty());
1886 flag.setEnabled(false);
1892 static FileName selectTemplateFile()
1894 FileDialog dlg(qt_("Select template file"));
1895 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1896 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
1898 FileDialog::Result result = dlg.open(toqstr(lyxrc.template_path),
1899 QStringList(qt_("LyX Documents (*.lyx)")));
1901 if (result.first == FileDialog::Later)
1903 if (result.second.isEmpty())
1905 return FileName(fromqstr(result.second));
1909 Buffer * GuiView::loadDocument(FileName const & filename, bool tolastfiles)
1913 Buffer * newBuffer = 0;
1915 newBuffer = checkAndLoadLyXFile(filename);
1916 } catch (ExceptionMessage const & e) {
1923 message(_("Document not loaded."));
1927 setBuffer(newBuffer);
1928 newBuffer->errors("Parse");
1931 theSession().lastFiles().add(filename);
1937 void GuiView::openDocument(string const & fname)
1939 string initpath = lyxrc.document_path;
1941 if (documentBufferView()) {
1942 string const trypath = documentBufferView()->buffer().filePath();
1943 // If directory is writeable, use this as default.
1944 if (FileName(trypath).isDirWritable())
1950 if (fname.empty()) {
1951 FileDialog dlg(qt_("Select document to open"), LFUN_FILE_OPEN);
1952 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1953 dlg.setButton2(qt_("Examples|#E#e"),
1954 toqstr(addPath(package().system_support().absFileName(), "examples")));
1956 QStringList filter(qt_("LyX Documents (*.lyx)"));
1957 filter << qt_("LyX-1.3.x Documents (*.lyx13)")
1958 << qt_("LyX-1.4.x Documents (*.lyx14)")
1959 << qt_("LyX-1.5.x Documents (*.lyx15)")
1960 << qt_("LyX-1.6.x Documents (*.lyx16)");
1961 FileDialog::Result result =
1962 dlg.open(toqstr(initpath), filter);
1964 if (result.first == FileDialog::Later)
1967 filename = fromqstr(result.second);
1969 // check selected filename
1970 if (filename.empty()) {
1971 message(_("Canceled."));
1977 // get absolute path of file and add ".lyx" to the filename if
1979 FileName const fullname =
1980 fileSearch(string(), filename, "lyx", support::may_not_exist);
1981 if (!fullname.empty())
1982 filename = fullname.absFileName();
1984 if (!fullname.onlyPath().isDirectory()) {
1985 Alert::warning(_("Invalid filename"),
1986 bformat(_("The directory in the given path\n%1$s\ndoes not exist."),
1987 from_utf8(fullname.absFileName())));
1991 // if the file doesn't exist and isn't already open (bug 6645),
1992 // let the user create one
1993 if (!fullname.exists() && !theBufferList().exists(fullname)) {
1994 // the user specifically chose this name. Believe him.
1995 Buffer * const b = newFile(filename, string(), true);
2001 docstring const disp_fn = makeDisplayPath(filename);
2002 message(bformat(_("Opening document %1$s..."), disp_fn));
2005 Buffer * buf = loadDocument(fullname);
2007 str2 = bformat(_("Document %1$s opened."), disp_fn);
2008 if (buf->lyxvc().inUse())
2009 str2 += " " + from_utf8(buf->lyxvc().versionString()) +
2010 " " + _("Version control detected.");
2012 str2 = bformat(_("Could not open document %1$s"), disp_fn);
2017 // FIXME: clean that
2018 static bool import(GuiView * lv, FileName const & filename,
2019 string const & format, ErrorList & errorList)
2021 FileName const lyxfile(support::changeExtension(filename.absFileName(), ".lyx"));
2023 string loader_format;
2024 vector<string> loaders = theConverters().loaders();
2025 if (find(loaders.begin(), loaders.end(), format) == loaders.end()) {
2026 for (vector<string>::const_iterator it = loaders.begin();
2027 it != loaders.end(); ++it) {
2028 if (!theConverters().isReachable(format, *it))
2031 string const tofile =
2032 support::changeExtension(filename.absFileName(),
2033 formats.extension(*it));
2034 if (!theConverters().convert(0, filename, FileName(tofile),
2035 filename, format, *it, errorList))
2037 loader_format = *it;
2040 if (loader_format.empty()) {
2041 frontend::Alert::error(_("Couldn't import file"),
2042 bformat(_("No information for importing the format %1$s."),
2043 formats.prettyName(format)));
2047 loader_format = format;
2049 if (loader_format == "lyx") {
2050 Buffer * buf = lv->loadDocument(lyxfile);
2054 Buffer * const b = newFile(lyxfile.absFileName(), string(), true);
2058 bool as_paragraphs = loader_format == "textparagraph";
2059 string filename2 = (loader_format == format) ? filename.absFileName()
2060 : support::changeExtension(filename.absFileName(),
2061 formats.extension(loader_format));
2062 lv->currentBufferView()->insertPlaintextFile(FileName(filename2),
2064 guiApp->setCurrentView(lv);
2065 lyx::dispatch(FuncRequest(LFUN_MARK_OFF));
2072 void GuiView::importDocument(string const & argument)
2075 string filename = split(argument, format, ' ');
2077 LYXERR(Debug::INFO, format << " file: " << filename);
2079 // need user interaction
2080 if (filename.empty()) {
2081 string initpath = lyxrc.document_path;
2082 if (documentBufferView()) {
2083 string const trypath = documentBufferView()->buffer().filePath();
2084 // If directory is writeable, use this as default.
2085 if (FileName(trypath).isDirWritable())
2089 docstring const text = bformat(_("Select %1$s file to import"),
2090 formats.prettyName(format));
2092 FileDialog dlg(toqstr(text), LFUN_BUFFER_IMPORT);
2093 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2094 dlg.setButton2(qt_("Examples|#E#e"),
2095 toqstr(addPath(package().system_support().absFileName(), "examples")));
2097 docstring filter = formats.prettyName(format);
2100 filter += from_utf8(formats.extensions(format));
2103 FileDialog::Result result =
2104 dlg.open(toqstr(initpath), fileFilters(toqstr(filter)));
2106 if (result.first == FileDialog::Later)
2109 filename = fromqstr(result.second);
2111 // check selected filename
2112 if (filename.empty())
2113 message(_("Canceled."));
2116 if (filename.empty())
2119 // get absolute path of file
2120 FileName const fullname(support::makeAbsPath(filename));
2122 FileName const lyxfile(support::changeExtension(fullname.absFileName(), ".lyx"));
2124 // Check if the document already is open
2125 Buffer * buf = theBufferList().getBuffer(lyxfile);
2128 if (!closeBuffer()) {
2129 message(_("Canceled."));
2134 docstring const displaypath = makeDisplayPath(lyxfile.absFileName(), 30);
2136 // if the file exists already, and we didn't do
2137 // -i lyx thefile.lyx, warn
2138 if (lyxfile.exists() && fullname != lyxfile) {
2140 docstring text = bformat(_("The document %1$s already exists.\n\n"
2141 "Do you want to overwrite that document?"), displaypath);
2142 int const ret = Alert::prompt(_("Overwrite document?"),
2143 text, 0, 1, _("&Overwrite"), _("&Cancel"));
2146 message(_("Canceled."));
2151 message(bformat(_("Importing %1$s..."), displaypath));
2152 ErrorList errorList;
2153 if (import(this, fullname, format, errorList))
2154 message(_("imported."));
2156 message(_("file not imported!"));
2158 // FIXME (Abdel 12/08/06): Is there a need to display the error list here?
2162 void GuiView::newDocument(string const & filename, bool from_template)
2164 FileName initpath(lyxrc.document_path);
2165 if (documentBufferView()) {
2166 FileName const trypath(documentBufferView()->buffer().filePath());
2167 // If directory is writeable, use this as default.
2168 if (trypath.isDirWritable())
2172 string templatefile;
2173 if (from_template) {
2174 templatefile = selectTemplateFile().absFileName();
2175 if (templatefile.empty())
2180 if (filename.empty())
2181 b = newUnnamedFile(initpath, to_utf8(_("newfile")), templatefile);
2183 b = newFile(filename, templatefile, true);
2188 // If no new document could be created, it is unsure
2189 // whether there is a valid BufferView.
2190 if (currentBufferView())
2191 // Ensure the cursor is correctly positioned on screen.
2192 currentBufferView()->showCursor();
2196 void GuiView::insertLyXFile(docstring const & fname)
2198 BufferView * bv = documentBufferView();
2203 FileName filename(to_utf8(fname));
2204 if (filename.empty()) {
2205 // Launch a file browser
2207 string initpath = lyxrc.document_path;
2208 string const trypath = bv->buffer().filePath();
2209 // If directory is writeable, use this as default.
2210 if (FileName(trypath).isDirWritable())
2214 FileDialog dlg(qt_("Select LyX document to insert"), LFUN_FILE_INSERT);
2215 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2216 dlg.setButton2(qt_("Examples|#E#e"),
2217 toqstr(addPath(package().system_support().absFileName(),
2220 FileDialog::Result result = dlg.open(toqstr(initpath),
2221 QStringList(qt_("LyX Documents (*.lyx)")));
2223 if (result.first == FileDialog::Later)
2227 filename.set(fromqstr(result.second));
2229 // check selected filename
2230 if (filename.empty()) {
2231 // emit message signal.
2232 message(_("Canceled."));
2237 bv->insertLyXFile(filename);
2238 bv->buffer().errors("Parse");
2242 void GuiView::insertPlaintextFile(docstring const & fname,
2245 BufferView * bv = documentBufferView();
2249 if (!fname.empty() && !FileName::isAbsolute(to_utf8(fname))) {
2250 message(_("Absolute filename expected."));
2255 FileName filename(to_utf8(fname));
2257 if (!filename.empty()) {
2258 bv->insertPlaintextFile(filename, asParagraph);
2262 FileDialog dlg(qt_("Select file to insert"), (asParagraph ?
2263 LFUN_FILE_INSERT_PLAINTEXT_PARA : LFUN_FILE_INSERT_PLAINTEXT));
2265 FileDialog::Result result = dlg.open(toqstr(bv->buffer().filePath()),
2266 QStringList(qt_("All Files (*)")));
2268 if (result.first == FileDialog::Later)
2272 filename.set(fromqstr(result.second));
2274 // check selected filename
2275 if (filename.empty()) {
2276 // emit message signal.
2277 message(_("Canceled."));
2281 bv->insertPlaintextFile(filename, asParagraph);
2285 bool GuiView::renameBuffer(Buffer & b, docstring const & newname)
2287 FileName fname = b.fileName();
2288 FileName const oldname = fname;
2290 if (!newname.empty()) {
2292 fname = support::makeAbsPath(to_utf8(newname), oldname.onlyPath().absFileName());
2294 // Switch to this Buffer.
2297 // No argument? Ask user through dialog.
2299 FileDialog dlg(qt_("Choose a filename to save document as"),
2300 LFUN_BUFFER_WRITE_AS);
2301 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2302 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
2304 if (!isLyXFileName(fname.absFileName()))
2305 fname.changeExtension(".lyx");
2307 FileDialog::Result result =
2308 dlg.save(toqstr(fname.onlyPath().absFileName()),
2309 QStringList(qt_("LyX Documents (*.lyx)")),
2310 toqstr(fname.onlyFileName()));
2312 if (result.first == FileDialog::Later)
2315 fname.set(fromqstr(result.second));
2320 if (!isLyXFileName(fname.absFileName()))
2321 fname.changeExtension(".lyx");
2324 // fname is now the new Buffer location.
2325 if (FileName(fname).exists()) {
2326 docstring const file = makeDisplayPath(fname.absFileName(), 30);
2327 docstring text = bformat(_("The document %1$s already "
2328 "exists.\n\nDo you want to "
2329 "overwrite that document?"),
2331 int const ret = Alert::prompt(_("Overwrite document?"),
2332 text, 0, 2, _("&Overwrite"), _("&Rename"), _("&Cancel"));
2335 case 1: return renameBuffer(b, docstring());
2336 case 2: return false;
2340 return saveBuffer(b, fname);
2344 struct PrettyNameComparator
2346 bool operator()(Format const *first, Format const *second) const {
2347 return compare_ascii_no_case(first->prettyname(), second->prettyname()) <= 0;
2352 bool GuiView::exportBufferAs(Buffer & b)
2354 FileName fname = b.fileName();
2356 FileDialog dlg(qt_("Choose a filename to export the document as"));
2357 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2360 types << "Any supported format (*.*)";
2361 Formats::const_iterator it = formats.begin();
2362 vector<Format const *> export_formats;
2363 for (; it != formats.end(); ++it)
2364 if (it->documentFormat() && it->inExportMenu())
2365 export_formats.push_back(&(*it));
2366 PrettyNameComparator cmp;
2367 sort(export_formats.begin(), export_formats.end(), cmp);
2368 vector<Format const *>::const_iterator fit = export_formats.begin();
2369 for (; fit != export_formats.end(); ++fit)
2370 types << toqstr((*fit)->prettyname() + " (*." + (*fit)->extension() + ")");
2372 FileDialog::Result result =
2373 dlg.save(toqstr(fname.onlyPath().absFileName()),
2375 toqstr(fname.onlyFileName()),
2377 if (result.first != FileDialog::Chosen)
2380 string s = fromqstr(filter);
2381 size_t pos = s.find(" (*.");
2382 LASSERT(pos != string::npos, /**/);
2383 string fmt_prettyname = s.substr(0, pos);
2385 fname.set(fromqstr(result.second));
2386 if (fmt_prettyname == "Any supported format")
2387 fmt_name = formats.getFormatFromExtension(fname.extension());
2389 fmt_name = formats.getFormatFromPrettyName(fmt_prettyname);
2390 LYXERR(Debug::FILES, "fmt_prettyname=" << fmt_prettyname
2391 << ", fmt_name=" << fmt_name << ", fname=" << fname.absFileName());
2393 if (fmt_name.empty() || fname.empty())
2396 // fname is now the new Buffer location.
2397 if (FileName(fname).exists()) {
2398 docstring const file = makeDisplayPath(fname.absFileName(), 30);
2399 docstring text = bformat(_("The document %1$s already "
2400 "exists.\n\nDo you want to "
2401 "overwrite that document?"),
2403 int const ret = Alert::prompt(_("Overwrite document?"),
2404 text, 0, 2, _("&Overwrite"), _("&Rename"), _("&Cancel"));
2407 case 1: return exportBufferAs(b);
2408 case 2: return false;
2412 FuncRequest cmd(LFUN_BUFFER_EXPORT, fmt_name + " " + fname.absFileName());
2415 return dr.dispatched();
2419 bool GuiView::saveBuffer(Buffer & b) {
2420 return saveBuffer(b, FileName());
2424 bool GuiView::saveBuffer(Buffer & b, FileName const & fn)
2426 if (workArea(b) && workArea(b)->inDialogMode())
2429 if (fn.empty() && b.isUnnamed())
2430 return renameBuffer(b, docstring());
2436 success = b.saveAs(fn);
2439 theSession().lastFiles().add(b.fileName());
2443 // Switch to this Buffer.
2446 // FIXME: we don't tell the user *WHY* the save failed !!
2447 docstring const file = makeDisplayPath(b.absFileName(), 30);
2448 docstring text = bformat(_("The document %1$s could not be saved.\n\n"
2449 "Do you want to rename the document and "
2450 "try again?"), file);
2451 int const ret = Alert::prompt(_("Rename and save?"),
2452 text, 0, 2, _("&Rename"), _("&Retry"), _("&Cancel"));
2455 if (!renameBuffer(b, docstring()))
2464 return saveBuffer(b);
2468 bool GuiView::hideWorkArea(GuiWorkArea * wa)
2470 return closeWorkArea(wa, false);
2474 bool GuiView::closeWorkArea(GuiWorkArea * wa)
2476 Buffer & buf = wa->bufferView().buffer();
2477 return closeWorkArea(wa, !buf.parent());
2481 bool GuiView::closeBuffer()
2483 GuiWorkArea * wa = currentMainWorkArea();
2484 setCurrentWorkArea(wa);
2485 Buffer & buf = wa->bufferView().buffer();
2486 return wa && closeWorkArea(wa, !buf.parent());
2490 void GuiView::writeSession() const {
2491 GuiWorkArea const * active_wa = currentMainWorkArea();
2492 for (int i = 0; i < d.splitter_->count(); ++i) {
2493 TabWorkArea * twa = d.tabWorkArea(i);
2494 for (int j = 0; j < twa->count(); ++j) {
2495 GuiWorkArea * wa = static_cast<GuiWorkArea *>(twa->widget(j));
2496 Buffer & buf = wa->bufferView().buffer();
2497 theSession().lastOpened().add(buf.fileName(), wa == active_wa);
2503 bool GuiView::closeBufferAll()
2505 // Close the workareas in all other views
2506 QList<int> const ids = guiApp->viewIds();
2507 for (int i = 0; i != ids.size(); ++i) {
2508 if (id_ != ids[i] && !guiApp->view(ids[i]).closeWorkAreaAll())
2512 // Close our own workareas
2513 if (!closeWorkAreaAll())
2516 // Now close the hidden buffers. We prevent hidden buffers from being
2517 // dirty, so we can just close them.
2518 theBufferList().closeAll();
2523 bool GuiView::closeWorkAreaAll()
2525 setCurrentWorkArea(currentMainWorkArea());
2527 // We might be in a situation that there is still a tabWorkArea, but
2528 // there are no tabs anymore. This can happen when we get here after a
2529 // TabWorkArea::lastWorkAreaRemoved() signal. Therefore we count how
2530 // many TabWorkArea's have no documents anymore.
2533 // We have to call count() each time, because it can happen that
2534 // more than one splitter will disappear in one iteration (bug 5998).
2535 for (; d.splitter_->count() > empty_twa; ) {
2536 TabWorkArea * twa = d.tabWorkArea(empty_twa);
2538 if (twa->count() == 0)
2541 setCurrentWorkArea(twa->currentWorkArea());
2542 if (!closeTabWorkArea(twa))
2550 bool GuiView::closeWorkArea(GuiWorkArea * wa, bool close_buffer)
2555 Buffer & buf = wa->bufferView().buffer();
2557 if (close_buffer && GuiViewPrivate::busyBuffers.contains(&buf)) {
2558 Alert::warning(_("Close document"),
2559 _("Document could not be closed because it is being processed by LyX."));
2564 return closeBuffer(buf);
2566 if (!inMultiTabs(wa))
2567 if (!saveBufferIfNeeded(buf, true))
2575 bool GuiView::closeBuffer(Buffer & buf)
2577 // If we are in a close_event all children will be closed in some time,
2578 // so no need to do it here. This will ensure that the children end up
2579 // in the session file in the correct order. If we close the master
2580 // buffer, we can close or release the child buffers here too.
2581 bool success = true;
2583 ListOfBuffers clist = buf.getChildren();
2584 ListOfBuffers::const_iterator it = clist.begin();
2585 ListOfBuffers::const_iterator const bend = clist.end();
2586 for (; it != bend; ++it) {
2587 // If a child is dirty, do not close
2588 // without user intervention
2589 //FIXME: should we look in other tabworkareas?
2590 Buffer * child_buf = *it;
2591 GuiWorkArea * child_wa = workArea(*child_buf);
2593 if (!closeWorkArea(child_wa, true)) {
2598 theBufferList().releaseChild(&buf, child_buf);
2602 // goto bookmark to update bookmark pit.
2603 //FIXME: we should update only the bookmarks related to this buffer!
2604 LYXERR(Debug::DEBUG, "GuiView::closeBuffer()");
2605 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
2606 guiApp->gotoBookmark(i+1, false, false);
2608 if (saveBufferIfNeeded(buf, false)) {
2609 buf.removeAutosaveFile();
2610 theBufferList().release(&buf);
2614 // open all children again to avoid a crash because of dangling
2615 // pointers (bug 6603)
2621 bool GuiView::closeTabWorkArea(TabWorkArea * twa)
2623 while (twa == d.currentTabWorkArea()) {
2624 twa->setCurrentIndex(twa->count()-1);
2626 GuiWorkArea * wa = twa->currentWorkArea();
2627 Buffer & b = wa->bufferView().buffer();
2629 // We only want to close the buffer if the same buffer is not visible
2630 // in another view, and if this is not a child and if we are closing
2631 // a view (not a tabgroup).
2632 bool const close_buffer =
2633 !inOtherView(b) && !b.parent() && closing_;
2635 if (!closeWorkArea(wa, close_buffer))
2642 bool GuiView::saveBufferIfNeeded(Buffer & buf, bool hiding)
2644 if (buf.isClean() || buf.paragraphs().empty())
2647 // Switch to this Buffer.
2652 if (buf.isUnnamed())
2653 file = from_utf8(buf.fileName().onlyFileName());
2655 file = buf.fileName().displayName(30);
2657 // Bring this window to top before asking questions.
2662 if (hiding && buf.isUnnamed()) {
2663 docstring const text = bformat(_("The document %1$s has not been "
2664 "saved yet.\n\nDo you want to save "
2665 "the document?"), file);
2666 ret = Alert::prompt(_("Save new document?"),
2667 text, 0, 1, _("&Save"), _("&Cancel"));
2671 docstring const text = bformat(_("The document %1$s has unsaved changes."
2672 "\n\nDo you want to save the document or discard the changes?"), file);
2673 ret = Alert::prompt(_("Save changed document?"),
2674 text, 0, 2, _("&Save"), _("&Discard"), _("&Cancel"));
2679 if (!saveBuffer(buf))
2683 // If we crash after this we could have no autosave file
2684 // but I guess this is really improbable (Jug).
2685 // Sometimes improbable things happen:
2686 // - see bug http://www.lyx.org/trac/ticket/6587 (ps)
2687 // buf.removeAutosaveFile();
2689 // revert all changes
2700 bool GuiView::inMultiTabs(GuiWorkArea * wa)
2702 Buffer & buf = wa->bufferView().buffer();
2704 for (int i = 0; i != d.splitter_->count(); ++i) {
2705 GuiWorkArea * wa_ = d.tabWorkArea(i)->workArea(buf);
2706 if (wa_ && wa_ != wa)
2709 return inOtherView(buf);
2713 bool GuiView::inOtherView(Buffer & buf)
2715 QList<int> const ids = guiApp->viewIds();
2717 for (int i = 0; i != ids.size(); ++i) {
2721 if (guiApp->view(ids[i]).workArea(buf))
2728 void GuiView::gotoNextOrPreviousBuffer(NextOrPrevious np)
2730 if (!documentBufferView())
2733 if (TabWorkArea * twa = d.currentTabWorkArea()) {
2734 Buffer * const curbuf = &documentBufferView()->buffer();
2735 int nwa = twa->count();
2736 for (int i = 0; i < nwa; ++i) {
2737 if (&workArea(i)->bufferView().buffer() == curbuf) {
2739 if (np == NEXTBUFFER)
2740 next_index = (i == nwa - 1 ? 0 : i + 1);
2742 next_index = (i == 0 ? nwa - 1 : i - 1);
2743 setBuffer(&workArea(next_index)->bufferView().buffer());
2751 /// make sure the document is saved
2752 static bool ensureBufferClean(Buffer * buffer)
2754 LASSERT(buffer, return false);
2755 if (buffer->isClean() && !buffer->isUnnamed())
2758 docstring const file = buffer->fileName().displayName(30);
2761 if (!buffer->isUnnamed()) {
2762 text = bformat(_("The document %1$s has unsaved "
2763 "changes.\n\nDo you want to save "
2764 "the document?"), file);
2765 title = _("Save changed document?");
2768 text = bformat(_("The document %1$s has not been "
2769 "saved yet.\n\nDo you want to save "
2770 "the document?"), file);
2771 title = _("Save new document?");
2773 int const ret = Alert::prompt(title, text, 0, 1, _("&Save"), _("&Cancel"));
2776 dispatch(FuncRequest(LFUN_BUFFER_WRITE));
2778 return buffer->isClean() && !buffer->isUnnamed();
2782 bool GuiView::reloadBuffer(Buffer & buf)
2784 Buffer::ReadStatus status = buf.reload();
2785 return status == Buffer::ReadSuccess;
2789 void GuiView::checkExternallyModifiedBuffers()
2791 BufferList::iterator bit = theBufferList().begin();
2792 BufferList::iterator const bend = theBufferList().end();
2793 for (; bit != bend; ++bit) {
2794 Buffer * buf = *bit;
2795 if (buf->fileName().exists()
2796 && buf->isExternallyModified(Buffer::checksum_method)) {
2797 docstring text = bformat(_("Document \n%1$s\n has been externally modified."
2798 " Reload now? Any local changes will be lost."),
2799 from_utf8(buf->absFileName()));
2800 int const ret = Alert::prompt(_("Reload externally changed document?"),
2801 text, 0, 1, _("&Reload"), _("&Cancel"));
2809 void GuiView::dispatchVC(FuncRequest const & cmd, DispatchResult & dr)
2811 Buffer * buffer = documentBufferView()
2812 ? &(documentBufferView()->buffer()) : 0;
2814 switch (cmd.action()) {
2815 case LFUN_VC_REGISTER:
2816 if (!buffer || !ensureBufferClean(buffer))
2818 if (!buffer->lyxvc().inUse()) {
2819 if (buffer->lyxvc().registrer()) {
2820 reloadBuffer(*buffer);
2821 dr.suppressMessageUpdate();
2826 case LFUN_VC_CHECK_IN:
2827 if (!buffer || !ensureBufferClean(buffer))
2829 if (buffer->lyxvc().inUse() && !buffer->isReadonly()) {
2830 dr.setMessage(buffer->lyxvc().checkIn());
2831 if (!dr.message().empty())
2832 reloadBuffer(*buffer);
2836 case LFUN_VC_CHECK_OUT:
2837 if (!buffer || !ensureBufferClean(buffer))
2839 if (buffer->lyxvc().inUse()) {
2840 dr.setMessage(buffer->lyxvc().checkOut());
2841 reloadBuffer(*buffer);
2845 case LFUN_VC_LOCKING_TOGGLE:
2846 LASSERT(buffer, return);
2847 if (!ensureBufferClean(buffer) || buffer->isReadonly())
2849 if (buffer->lyxvc().inUse()) {
2850 string res = buffer->lyxvc().lockingToggle();
2852 frontend::Alert::error(_("Revision control error."),
2853 _("Error when setting the locking property."));
2856 reloadBuffer(*buffer);
2861 case LFUN_VC_REVERT:
2862 LASSERT(buffer, return);
2863 if (buffer->lyxvc().revert()) {
2864 reloadBuffer(*buffer);
2865 dr.suppressMessageUpdate();
2869 case LFUN_VC_UNDO_LAST:
2870 LASSERT(buffer, return);
2871 buffer->lyxvc().undoLast();
2872 reloadBuffer(*buffer);
2873 dr.suppressMessageUpdate();
2876 case LFUN_VC_REPO_UPDATE:
2877 LASSERT(buffer, return);
2878 if (ensureBufferClean(buffer)) {
2879 dr.setMessage(buffer->lyxvc().repoUpdate());
2880 checkExternallyModifiedBuffers();
2884 case LFUN_VC_COMMAND: {
2885 string flag = cmd.getArg(0);
2886 if (buffer && contains(flag, 'R') && !ensureBufferClean(buffer))
2889 if (contains(flag, 'M')) {
2890 if (!Alert::askForText(message, _("LyX VC: Log Message")))
2893 string path = cmd.getArg(1);
2894 if (contains(path, "$$p") && buffer)
2895 path = subst(path, "$$p", buffer->filePath());
2896 LYXERR(Debug::LYXVC, "Directory: " << path);
2898 if (!pp.isReadableDirectory()) {
2899 lyxerr << _("Directory is not accessible.") << endl;
2902 support::PathChanger p(pp);
2904 string command = cmd.getArg(2);
2905 if (command.empty())
2908 command = subst(command, "$$i", buffer->absFileName());
2909 command = subst(command, "$$p", buffer->filePath());
2911 command = subst(command, "$$m", to_utf8(message));
2912 LYXERR(Debug::LYXVC, "Command: " << command);
2914 one.startscript(Systemcall::Wait, command);
2918 if (contains(flag, 'I'))
2919 buffer->markDirty();
2920 if (contains(flag, 'R'))
2921 reloadBuffer(*buffer);
2926 case LFUN_VC_COMPARE: {
2928 if (cmd.argument().empty()) {
2929 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "comparehistory"));
2933 string rev1 = cmd.getArg(0);
2937 if (!buffer->lyxvc().prepareFileRevision(rev1, f1))
2940 if (isStrInt(rev1) && convert<int>(rev1) <= 0) {
2941 f2 = buffer->absFileName();
2943 string rev2 = cmd.getArg(1);
2947 if (!buffer->lyxvc().prepareFileRevision(rev2, f2))
2951 LYXERR(Debug::LYXVC, "Launching comparison for fetched revisions:\n" <<
2952 f1 << "\n" << f2 << "\n" );
2953 string par = "compare run " + quoteName(f1) + " " + quoteName(f2);
2954 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, par));
2964 void GuiView::openChildDocument(string const & fname)
2966 LASSERT(documentBufferView(), return);
2967 Buffer & buffer = documentBufferView()->buffer();
2968 FileName const filename = support::makeAbsPath(fname, buffer.filePath());
2969 documentBufferView()->saveBookmark(false);
2971 if (theBufferList().exists(filename)) {
2972 child = theBufferList().getBuffer(filename);
2975 message(bformat(_("Opening child document %1$s..."),
2976 makeDisplayPath(filename.absFileName())));
2977 child = loadDocument(filename, false);
2979 // Set the parent name of the child document.
2980 // This makes insertion of citations and references in the child work,
2981 // when the target is in the parent or another child document.
2983 child->setParent(&buffer);
2987 bool GuiView::goToFileRow(string const & argument)
2991 size_t i = argument.find_last_of(' ');
2992 if (i != string::npos) {
2993 file_name = os::internal_path(trim(argument.substr(0, i)));
2994 istringstream is(argument.substr(i + 1));
2999 if (i == string::npos) {
3000 LYXERR0("Wrong argument: " << argument);
3004 string const abstmp = package().temp_dir().absFileName();
3005 string const realtmp = package().temp_dir().realPath();
3006 // We have to use os::path_prefix_is() here, instead of
3007 // simply prefixIs(), because the file name comes from
3008 // an external application and may need case adjustment.
3009 if (os::path_prefix_is(file_name, abstmp, os::CASE_ADJUSTED)
3010 || os::path_prefix_is(file_name, realtmp, os::CASE_ADJUSTED)) {
3011 // Needed by inverse dvi search. If it is a file
3012 // in tmpdir, call the apropriated function.
3013 // If tmpdir is a symlink, we may have the real
3014 // path passed back, so we correct for that.
3015 if (!prefixIs(file_name, abstmp))
3016 file_name = subst(file_name, realtmp, abstmp);
3017 buf = theBufferList().getBufferFromTmp(file_name);
3019 // Must replace extension of the file to be .lyx
3020 // and get full path
3021 FileName const s = fileSearch(string(),
3022 support::changeExtension(file_name, ".lyx"), "lyx");
3023 // Either change buffer or load the file
3024 if (theBufferList().exists(s))
3025 buf = theBufferList().getBuffer(s);
3026 else if (s.exists()) {
3027 buf = loadDocument(s);
3032 _("File does not exist: %1$s"),
3033 makeDisplayPath(file_name)));
3039 _("No buffer for file: %1$s."),
3040 makeDisplayPath(file_name))
3045 documentBufferView()->setCursorFromRow(row);
3050 #if (QT_VERSION >= 0x040400)
3052 Buffer::ExportStatus GuiView::GuiViewPrivate::runAndDestroy(const T& func, Buffer const * orig, Buffer * buffer, string const & format)
3054 Buffer::ExportStatus const status = func(format);
3056 // the cloning operation will have produced a clone of the entire set of
3057 // documents, starting from the master. so we must delete those.
3058 Buffer * mbuf = const_cast<Buffer *>(buffer->masterBuffer());
3060 busyBuffers.remove(orig);
3065 Buffer::ExportStatus GuiView::GuiViewPrivate::compileAndDestroy(Buffer const * orig, Buffer * buffer, string const & format)
3067 Buffer::ExportStatus (Buffer::* mem_func)(std::string const &, bool) const = &Buffer::doExport;
3068 return runAndDestroy(bind(mem_func, buffer, _1, true), orig, buffer, format);
3072 Buffer::ExportStatus GuiView::GuiViewPrivate::exportAndDestroy(Buffer const * orig, Buffer * buffer, string const & format)
3074 Buffer::ExportStatus (Buffer::* mem_func)(std::string const &, bool) const = &Buffer::doExport;
3075 return runAndDestroy(bind(mem_func, buffer, _1, false), orig, buffer, format);
3079 Buffer::ExportStatus GuiView::GuiViewPrivate::previewAndDestroy(Buffer const * orig, Buffer * buffer, string const & format)
3081 Buffer::ExportStatus (Buffer::* mem_func)(std::string const &) const = &Buffer::preview;
3082 return runAndDestroy(bind(mem_func, buffer, _1), orig, buffer, format);
3087 // not used, but the linker needs them
3089 Buffer::ExportStatus GuiView::GuiViewPrivate::compileAndDestroy(
3090 Buffer const *, Buffer *, string const &)
3092 return Buffer::ExportSuccess;
3096 Buffer::ExportStatus GuiView::GuiViewPrivate::exportAndDestroy(
3097 Buffer const *, Buffer *, string const &)
3099 return Buffer::ExportSuccess;
3103 Buffer::ExportStatus GuiView::GuiViewPrivate::previewAndDestroy(
3104 Buffer const *, Buffer *, string const &)
3106 return Buffer::ExportSuccess;
3112 bool GuiView::GuiViewPrivate::asyncBufferProcessing(
3113 string const & argument,
3114 Buffer const * used_buffer,
3115 docstring const & msg,
3116 Buffer::ExportStatus (*asyncFunc)(Buffer const *, Buffer *, string const &),
3117 Buffer::ExportStatus (Buffer::*syncFunc)(string const &, bool) const,
3118 Buffer::ExportStatus (Buffer::*previewFunc)(string const &) const)
3123 string format = argument;
3125 format = used_buffer->params().getDefaultOutputFormat();
3126 processing_format = format;
3127 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
3129 progress_->clearMessages();
3132 GuiViewPrivate::busyBuffers.insert(used_buffer);
3133 QFuture<Buffer::ExportStatus> f = QtConcurrent::run(
3136 used_buffer->clone(),
3138 setPreviewFuture(f);
3139 last_export_format = used_buffer->params().bufferFormat();
3142 // We are asynchronous, so we don't know here anything about the success
3145 Buffer::ExportStatus status;
3147 // TODO check here if it breaks exporting with Qt < 4.4
3148 status = (used_buffer->*syncFunc)(format, true);
3149 } else if (previewFunc) {
3150 status = (used_buffer->*previewFunc)(format);
3153 handleExportStatus(gv_, status, format);
3155 return (status == Buffer::ExportSuccess
3156 || status == Buffer::PreviewSuccess);
3160 void GuiView::dispatchToBufferView(FuncRequest const & cmd, DispatchResult & dr)
3162 BufferView * bv = currentBufferView();
3165 // Let the current BufferView dispatch its own actions.
3166 bv->dispatch(cmd, dr);
3167 if (dr.dispatched())
3170 // Try with the document BufferView dispatch if any.
3171 BufferView * doc_bv = documentBufferView();
3172 if (doc_bv && doc_bv != bv) {
3173 doc_bv->dispatch(cmd, dr);
3174 if (dr.dispatched())
3178 // Then let the current Cursor dispatch its own actions.
3179 bv->cursor().dispatch(cmd);
3181 // update completion. We do it here and not in
3182 // processKeySym to avoid another redraw just for a
3183 // changed inline completion
3184 if (cmd.origin() == FuncRequest::KEYBOARD) {
3185 if (cmd.action() == LFUN_SELF_INSERT
3186 || (cmd.action() == LFUN_ERT_INSERT && bv->cursor().inMathed()))
3187 updateCompletion(bv->cursor(), true, true);
3188 else if (cmd.action() == LFUN_CHAR_DELETE_BACKWARD)
3189 updateCompletion(bv->cursor(), false, true);
3191 updateCompletion(bv->cursor(), false, false);
3194 dr = bv->cursor().result();
3198 void GuiView::dispatch(FuncRequest const & cmd, DispatchResult & dr)
3200 BufferView * bv = currentBufferView();
3201 // By default we won't need any update.
3202 dr.screenUpdate(Update::None);
3203 // assume cmd will be dispatched
3204 dr.dispatched(true);
3206 Buffer * doc_buffer = documentBufferView()
3207 ? &(documentBufferView()->buffer()) : 0;
3209 if (cmd.origin() == FuncRequest::TOC) {
3210 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
3211 // FIXME: do we need to pass a DispatchResult object here?
3212 toc->doDispatch(bv->cursor(), cmd);
3216 string const argument = to_utf8(cmd.argument());
3218 switch(cmd.action()) {
3219 case LFUN_BUFFER_CHILD_OPEN:
3220 openChildDocument(to_utf8(cmd.argument()));
3223 case LFUN_BUFFER_IMPORT:
3224 importDocument(to_utf8(cmd.argument()));
3227 case LFUN_BUFFER_EXPORT: {
3230 // GCC only sees strfwd.h when building merged
3231 if (::lyx::operator==(cmd.argument(), "custom")) {
3232 dispatch(FuncRequest(LFUN_DIALOG_SHOW, "sendto"), dr);
3235 #if QT_VERSION < 0x040400
3236 if (!doc_buffer->doExport(argument, false)) {
3238 dr.setMessage(bformat(_("Error exporting to format: %1$s"),
3242 /* TODO/Review: Is it a problem to also export the children?
3243 See the update_unincluded flag */
3244 d.asyncBufferProcessing(argument,
3247 &GuiViewPrivate::exportAndDestroy,
3250 // TODO Inform user about success
3255 case LFUN_BUFFER_EXPORT_AS:
3256 LASSERT(doc_buffer, break);
3257 exportBufferAs(*doc_buffer);
3260 case LFUN_BUFFER_UPDATE: {
3261 d.asyncBufferProcessing(argument,
3264 &GuiViewPrivate::compileAndDestroy,
3269 case LFUN_BUFFER_VIEW: {
3270 d.asyncBufferProcessing(argument,
3272 _("Previewing ..."),
3273 &GuiViewPrivate::previewAndDestroy,
3278 case LFUN_MASTER_BUFFER_UPDATE: {
3279 d.asyncBufferProcessing(argument,
3280 (doc_buffer ? doc_buffer->masterBuffer() : 0),
3282 &GuiViewPrivate::compileAndDestroy,
3287 case LFUN_MASTER_BUFFER_VIEW: {
3288 d.asyncBufferProcessing(argument,
3289 (doc_buffer ? doc_buffer->masterBuffer() : 0),
3291 &GuiViewPrivate::previewAndDestroy,
3292 0, &Buffer::preview);
3295 case LFUN_BUFFER_SWITCH: {
3296 string const file_name = to_utf8(cmd.argument());
3297 if (!FileName::isAbsolute(file_name)) {
3299 dr.setMessage(_("Absolute filename expected."));
3303 Buffer * buffer = theBufferList().getBuffer(FileName(file_name));
3306 dr.setMessage(_("Document not loaded"));
3310 // Do we open or switch to the buffer in this view ?
3311 if (workArea(*buffer)
3312 || lyxrc.open_buffers_in_tabs || !documentBufferView()) {
3317 // Look for the buffer in other views
3318 QList<int> const ids = guiApp->viewIds();
3320 for (; i != ids.size(); ++i) {
3321 GuiView & gv = guiApp->view(ids[i]);
3322 if (gv.workArea(*buffer)) {
3323 gv.activateWindow();
3324 gv.setBuffer(buffer);
3329 // If necessary, open a new window as a last resort
3330 if (i == ids.size()) {
3331 lyx::dispatch(FuncRequest(LFUN_WINDOW_NEW));
3337 case LFUN_BUFFER_NEXT:
3338 gotoNextOrPreviousBuffer(NEXTBUFFER);
3341 case LFUN_BUFFER_PREVIOUS:
3342 gotoNextOrPreviousBuffer(PREVBUFFER);
3345 case LFUN_COMMAND_EXECUTE: {
3346 bool const show_it = cmd.argument() != "off";
3347 // FIXME: this is a hack, "minibuffer" should not be
3349 if (GuiToolbar * t = toolbar("minibuffer")) {
3350 t->setVisible(show_it);
3351 if (show_it && t->commandBuffer())
3352 t->commandBuffer()->setFocus();
3356 case LFUN_DROP_LAYOUTS_CHOICE:
3357 d.layout_->showPopup();
3360 case LFUN_MENU_OPEN:
3361 if (QMenu * menu = guiApp->menus().menu(toqstr(cmd.argument()), *this))
3362 menu->exec(QCursor::pos());
3365 case LFUN_FILE_INSERT:
3366 insertLyXFile(cmd.argument());
3369 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
3370 insertPlaintextFile(cmd.argument(), true);
3373 case LFUN_FILE_INSERT_PLAINTEXT:
3374 insertPlaintextFile(cmd.argument(), false);
3377 case LFUN_BUFFER_RELOAD: {
3378 LASSERT(doc_buffer, break);
3381 if (!doc_buffer->isClean()) {
3382 docstring const file =
3383 makeDisplayPath(doc_buffer->absFileName(), 20);
3384 docstring text = bformat(_("Any changes will be lost. "
3385 "Are you sure you want to revert to the saved version "
3386 "of the document %1$s?"), file);
3387 ret = Alert::prompt(_("Revert to saved document?"),
3388 text, 1, 1, _("&Revert"), _("&Cancel"));
3392 doc_buffer->markClean();
3393 reloadBuffer(*doc_buffer);
3394 dr.forceBufferUpdate();
3399 case LFUN_BUFFER_WRITE:
3400 LASSERT(doc_buffer, break);
3401 saveBuffer(*doc_buffer);
3404 case LFUN_BUFFER_WRITE_AS:
3405 LASSERT(doc_buffer, break);
3406 renameBuffer(*doc_buffer, cmd.argument());
3409 case LFUN_BUFFER_WRITE_ALL: {
3410 Buffer * first = theBufferList().first();
3413 message(_("Saving all documents..."));
3414 // We cannot use a for loop as the buffer list cycles.
3417 if (!b->isClean()) {
3419 LYXERR(Debug::ACTION, "Saved " << b->absFileName());
3421 b = theBufferList().next(b);
3422 } while (b != first);
3423 dr.setMessage(_("All documents saved."));
3427 case LFUN_BUFFER_CLOSE:
3431 case LFUN_BUFFER_CLOSE_ALL:
3435 case LFUN_TOOLBAR_TOGGLE: {
3436 string const name = cmd.getArg(0);
3437 if (GuiToolbar * t = toolbar(name))
3442 case LFUN_DIALOG_UPDATE: {
3443 string const name = to_utf8(cmd.argument());
3444 if (name == "prefs" || name == "document")
3445 updateDialog(name, string());
3446 else if (name == "paragraph")
3447 lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
3448 else if (currentBufferView()) {
3449 Inset * inset = currentBufferView()->editedInset(name);
3450 // Can only update a dialog connected to an existing inset
3452 // FIXME: get rid of this indirection; GuiView ask the inset
3453 // if he is kind enough to update itself...
3454 FuncRequest fr(LFUN_INSET_DIALOG_UPDATE, cmd.argument());
3455 //FIXME: pass DispatchResult here?
3456 inset->dispatch(currentBufferView()->cursor(), fr);
3462 case LFUN_DIALOG_TOGGLE: {
3463 FuncCode const func_code = isDialogVisible(cmd.getArg(0))
3464 ? LFUN_DIALOG_HIDE : LFUN_DIALOG_SHOW;
3465 dispatch(FuncRequest(func_code, cmd.argument()), dr);
3469 case LFUN_DIALOG_DISCONNECT_INSET:
3470 disconnectDialog(to_utf8(cmd.argument()));
3473 case LFUN_DIALOG_HIDE: {
3474 guiApp->hideDialogs(to_utf8(cmd.argument()), 0);
3478 case LFUN_DIALOG_SHOW: {
3479 string const name = cmd.getArg(0);
3480 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
3482 if (name == "character") {
3483 data = freefont2string();
3485 showDialog("character", data);
3486 } else if (name == "latexlog") {
3487 Buffer::LogType type;
3488 string const logfile = doc_buffer->logName(&type);
3490 case Buffer::latexlog:
3493 case Buffer::buildlog:
3497 data += Lexer::quoteString(logfile);
3498 showDialog("log", data);
3499 } else if (name == "vclog") {
3500 string const data = "vc " +
3501 Lexer::quoteString(doc_buffer->lyxvc().getLogFile());
3502 showDialog("log", data);
3503 } else if (name == "symbols") {
3504 data = bv->cursor().getEncoding()->name();
3506 showDialog("symbols", data);
3508 } else if (name == "prefs" && isFullScreen()) {
3509 lfunUiToggle("fullscreen");
3510 showDialog("prefs", data);
3512 showDialog(name, data);
3517 dr.setMessage(cmd.argument());
3520 case LFUN_UI_TOGGLE: {
3521 string arg = cmd.getArg(0);
3522 if (!lfunUiToggle(arg)) {
3523 docstring const msg = "ui-toggle " + _("%1$s unknown command!");
3524 dr.setMessage(bformat(msg, from_utf8(arg)));
3526 // Make sure the keyboard focus stays in the work area.
3531 case LFUN_SPLIT_VIEW: {
3532 LASSERT(doc_buffer, break);
3533 string const orientation = cmd.getArg(0);
3534 d.splitter_->setOrientation(orientation == "vertical"
3535 ? Qt::Vertical : Qt::Horizontal);
3536 TabWorkArea * twa = addTabWorkArea();
3537 GuiWorkArea * wa = twa->addWorkArea(*doc_buffer, *this);
3538 setCurrentWorkArea(wa);
3541 case LFUN_CLOSE_TAB_GROUP:
3542 if (TabWorkArea * twa = d.currentTabWorkArea()) {
3543 closeTabWorkArea(twa);
3544 d.current_work_area_ = 0;
3545 twa = d.currentTabWorkArea();
3546 // Switch to the next GuiWorkArea in the found TabWorkArea.
3548 // Make sure the work area is up to date.
3549 setCurrentWorkArea(twa->currentWorkArea());
3551 setCurrentWorkArea(0);
3556 case LFUN_COMPLETION_INLINE:
3557 if (d.current_work_area_)
3558 d.current_work_area_->completer().showInline();
3561 case LFUN_COMPLETION_POPUP:
3562 if (d.current_work_area_)
3563 d.current_work_area_->completer().showPopup();
3567 case LFUN_COMPLETION_COMPLETE:
3568 if (d.current_work_area_)
3569 d.current_work_area_->completer().tab();
3572 case LFUN_COMPLETION_CANCEL:
3573 if (d.current_work_area_) {
3574 if (d.current_work_area_->completer().popupVisible())
3575 d.current_work_area_->completer().hidePopup();
3577 d.current_work_area_->completer().hideInline();
3581 case LFUN_COMPLETION_ACCEPT:
3582 if (d.current_work_area_)
3583 d.current_work_area_->completer().activate();
3586 case LFUN_BUFFER_ZOOM_IN:
3587 case LFUN_BUFFER_ZOOM_OUT:
3588 if (cmd.argument().empty()) {
3589 if (cmd.action() == LFUN_BUFFER_ZOOM_IN)
3594 lyxrc.zoom += convert<int>(cmd.argument());
3596 if (lyxrc.zoom < 10)
3599 // The global QPixmapCache is used in GuiPainter to cache text
3600 // painting so we must reset it.
3601 QPixmapCache::clear();
3602 guiApp->fontLoader().update();
3603 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
3606 case LFUN_VC_REGISTER:
3607 case LFUN_VC_CHECK_IN:
3608 case LFUN_VC_CHECK_OUT:
3609 case LFUN_VC_REPO_UPDATE:
3610 case LFUN_VC_LOCKING_TOGGLE:
3611 case LFUN_VC_REVERT:
3612 case LFUN_VC_UNDO_LAST:
3613 case LFUN_VC_COMMAND:
3614 case LFUN_VC_COMPARE:
3615 dispatchVC(cmd, dr);
3618 case LFUN_SERVER_GOTO_FILE_ROW:
3619 goToFileRow(to_utf8(cmd.argument()));
3622 case LFUN_FORWARD_SEARCH: {
3623 Buffer const * doc_master = doc_buffer->masterBuffer();
3624 FileName const path(doc_master->temppath());
3625 string const texname = doc_master->isChild(doc_buffer)
3626 ? DocFileName(changeExtension(
3627 doc_buffer->absFileName(),
3628 "tex")).mangledFileName()
3629 : doc_buffer->latexName();
3630 string const mastername =
3631 removeExtension(doc_master->latexName());
3632 FileName const dviname(addName(path.absFileName(),
3633 addExtension(mastername, "dvi")));
3634 FileName const pdfname(addName(path.absFileName(),
3635 addExtension(mastername, "pdf")));
3636 bool const have_dvi = dviname.exists();
3637 bool const have_pdf = pdfname.exists();
3638 if (!have_dvi && !have_pdf) {
3639 dr.setMessage(_("Please, preview the document first."));
3642 string outname = dviname.onlyFileName();
3643 string command = lyxrc.forward_search_dvi;
3644 if (!have_dvi || (have_pdf &&
3645 pdfname.lastModified() > dviname.lastModified())) {
3646 outname = pdfname.onlyFileName();
3647 command = lyxrc.forward_search_pdf;
3650 int row = doc_buffer->texrow().getRowFromIdPos(bv->cursor().paragraph().id(), bv->cursor().pos());
3651 LYXERR(Debug::ACTION, "Forward search: row:" << row
3652 << " id:" << bv->cursor().paragraph().id());
3653 if (!row || command.empty()) {
3654 dr.setMessage(_("Couldn't proceed."));
3657 string texrow = convert<string>(row);
3659 command = subst(command, "$$n", texrow);
3660 command = subst(command, "$$t", texname);
3661 command = subst(command, "$$o", outname);
3663 PathChanger p(path);
3665 one.startscript(Systemcall::DontWait, command);
3669 // The LFUN must be for one of BufferView, Buffer or Cursor;
3671 dispatchToBufferView(cmd, dr);
3675 // Part of automatic menu appearance feature.
3676 if (isFullScreen()) {
3677 if (menuBar()->isVisible() && lyxrc.full_screen_menubar)
3679 if (statusBar()->isVisible())
3680 statusBar()->hide();
3685 bool GuiView::lfunUiToggle(string const & ui_component)
3687 if (ui_component == "scrollbar") {
3688 // hide() is of no help
3689 if (d.current_work_area_->verticalScrollBarPolicy() ==
3690 Qt::ScrollBarAlwaysOff)
3692 d.current_work_area_->setVerticalScrollBarPolicy(
3693 Qt::ScrollBarAsNeeded);
3695 d.current_work_area_->setVerticalScrollBarPolicy(
3696 Qt::ScrollBarAlwaysOff);
3697 } else if (ui_component == "statusbar") {
3698 statusBar()->setVisible(!statusBar()->isVisible());
3699 } else if (ui_component == "menubar") {
3700 menuBar()->setVisible(!menuBar()->isVisible());
3702 #if QT_VERSION >= 0x040300
3703 if (ui_component == "frame") {
3705 getContentsMargins(&l, &t, &r, &b);
3706 //are the frames in default state?
3707 d.current_work_area_->setFrameStyle(QFrame::NoFrame);
3709 setContentsMargins(-2, -2, -2, -2);
3711 setContentsMargins(0, 0, 0, 0);
3715 if (ui_component == "fullscreen") {
3723 void GuiView::toggleFullScreen()
3725 if (isFullScreen()) {
3726 for (int i = 0; i != d.splitter_->count(); ++i)
3727 d.tabWorkArea(i)->setFullScreen(false);
3728 #if QT_VERSION >= 0x040300
3729 setContentsMargins(0, 0, 0, 0);
3731 setWindowState(windowState() ^ Qt::WindowFullScreen);
3734 statusBar()->show();
3737 hideDialogs("prefs", 0);
3738 for (int i = 0; i != d.splitter_->count(); ++i)
3739 d.tabWorkArea(i)->setFullScreen(true);
3740 #if QT_VERSION >= 0x040300
3741 setContentsMargins(-2, -2, -2, -2);
3744 setWindowState(windowState() ^ Qt::WindowFullScreen);
3745 statusBar()->hide();
3746 if (lyxrc.full_screen_menubar)
3748 if (lyxrc.full_screen_toolbars) {
3749 ToolbarMap::iterator end = d.toolbars_.end();
3750 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
3755 // give dialogs like the TOC a chance to adapt
3760 Buffer const * GuiView::updateInset(Inset const * inset)
3765 Buffer const * inset_buffer = &(inset->buffer());
3767 for (int i = 0; i != d.splitter_->count(); ++i) {
3768 GuiWorkArea * wa = d.tabWorkArea(i)->currentWorkArea();
3771 Buffer const * buffer = &(wa->bufferView().buffer());
3772 if (inset_buffer == buffer)
3773 wa->scheduleRedraw();
3775 return inset_buffer;
3779 void GuiView::restartCursor()
3781 /* When we move around, or type, it's nice to be able to see
3782 * the cursor immediately after the keypress.
3784 if (d.current_work_area_)
3785 d.current_work_area_->startBlinkingCursor();
3787 // Take this occasion to update the other GUI elements.
3793 void GuiView::updateCompletion(Cursor & cur, bool start, bool keep)
3795 if (d.current_work_area_)
3796 d.current_work_area_->completer().updateVisibility(cur, start, keep);
3801 // This list should be kept in sync with the list of insets in
3802 // src/insets/Inset.cpp. I.e., if a dialog goes with an inset, the
3803 // dialog should have the same name as the inset.
3804 // Changes should be also recorded in LFUN_DIALOG_SHOW doxygen
3805 // docs in LyXAction.cpp.
3807 char const * const dialognames[] = {
3809 "aboutlyx", "bibitem", "bibtex", "box", "branch", "changes", "character",
3810 "citation", "compare", "comparehistory", "document", "errorlist", "ert",
3811 "external", "file", "findreplace", "findreplaceadv", "float", "graphics",
3812 "href", "include", "index", "index_print", "info", "listings", "label", "line",
3813 "log", "mathdelimiter", "mathmatrix", "mathspace", "nomenclature",
3814 "nomencl_print", "note", "paragraph", "phantom", "prefs", "print", "ref",
3815 "sendto", "space", "spellchecker", "symbols", "tabular", "tabularcreate",
3816 "thesaurus", "texinfo", "toc", "view-source", "vspace", "wrap", "progress"};
3818 char const * const * const end_dialognames =
3819 dialognames + (sizeof(dialognames) / sizeof(char *));
3823 cmpCStr(char const * name) : name_(name) {}
3824 bool operator()(char const * other) {
3825 return strcmp(other, name_) == 0;
3832 bool isValidName(string const & name)
3834 return find_if(dialognames, end_dialognames,
3835 cmpCStr(name.c_str())) != end_dialognames;
3841 void GuiView::resetDialogs()
3843 // Make sure that no LFUN uses any GuiView.
3844 guiApp->setCurrentView(0);
3848 constructToolbars();
3849 guiApp->menus().fillMenuBar(menuBar(), this, false);
3850 d.layout_->updateContents(true);
3851 // Now update controls with current buffer.
3852 guiApp->setCurrentView(this);
3858 Dialog * GuiView::findOrBuild(string const & name, bool hide_it)
3860 if (!isValidName(name))
3863 map<string, DialogPtr>::iterator it = d.dialogs_.find(name);
3865 if (it != d.dialogs_.end()) {
3867 it->second->hideView();
3868 return it->second.get();
3871 Dialog * dialog = build(name);
3872 d.dialogs_[name].reset(dialog);
3873 if (lyxrc.allow_geometry_session)
3874 dialog->restoreSession();
3881 void GuiView::showDialog(string const & name, string const & data,
3884 triggerShowDialog(toqstr(name), toqstr(data), inset);
3888 void GuiView::doShowDialog(QString const & qname, QString const & qdata,
3894 const string name = fromqstr(qname);
3895 const string data = fromqstr(qdata);
3899 Dialog * dialog = findOrBuild(name, false);
3901 bool const visible = dialog->isVisibleView();
3902 dialog->showData(data);
3903 if (inset && currentBufferView())
3904 currentBufferView()->editInset(name, inset);
3905 // We only set the focus to the new dialog if it was not yet
3906 // visible in order not to change the existing previous behaviour
3908 // activateWindow is needed for floating dockviews
3909 dialog->asQWidget()->raise();
3910 dialog->asQWidget()->activateWindow();
3911 dialog->asQWidget()->setFocus();
3915 catch (ExceptionMessage const & ex) {
3923 bool GuiView::isDialogVisible(string const & name) const
3925 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3926 if (it == d.dialogs_.end())
3928 return it->second.get()->isVisibleView() && !it->second.get()->isClosing();
3932 void GuiView::hideDialog(string const & name, Inset * inset)
3934 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3935 if (it == d.dialogs_.end())
3939 if (!currentBufferView())
3941 if (inset != currentBufferView()->editedInset(name))
3945 Dialog * const dialog = it->second.get();
3946 if (dialog->isVisibleView())
3948 if (currentBufferView())
3949 currentBufferView()->editInset(name, 0);
3953 void GuiView::disconnectDialog(string const & name)
3955 if (!isValidName(name))
3957 if (currentBufferView())
3958 currentBufferView()->editInset(name, 0);
3962 void GuiView::hideAll() const
3964 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
3965 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3967 for(; it != end; ++it)
3968 it->second->hideView();
3972 void GuiView::updateDialogs()
3974 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
3975 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3977 for(; it != end; ++it) {
3978 Dialog * dialog = it->second.get();
3980 if (dialog->needBufferOpen() && !documentBufferView())
3981 hideDialog(fromqstr(dialog->name()), 0);
3982 else if (dialog->isVisibleView())
3983 dialog->checkStatus();
3990 Dialog * createDialog(GuiView & lv, string const & name);
3992 // will be replaced by a proper factory...
3993 Dialog * createGuiAbout(GuiView & lv);
3994 Dialog * createGuiBibtex(GuiView & lv);
3995 Dialog * createGuiChanges(GuiView & lv);
3996 Dialog * createGuiCharacter(GuiView & lv);
3997 Dialog * createGuiCitation(GuiView & lv);
3998 Dialog * createGuiCompare(GuiView & lv);
3999 Dialog * createGuiCompareHistory(GuiView & lv);
4000 Dialog * createGuiDelimiter(GuiView & lv);
4001 Dialog * createGuiDocument(GuiView & lv);
4002 Dialog * createGuiErrorList(GuiView & lv);
4003 Dialog * createGuiExternal(GuiView & lv);
4004 Dialog * createGuiGraphics(GuiView & lv);
4005 Dialog * createGuiInclude(GuiView & lv);
4006 Dialog * createGuiIndex(GuiView & lv);
4007 Dialog * createGuiListings(GuiView & lv);
4008 Dialog * createGuiLog(GuiView & lv);
4009 Dialog * createGuiMathMatrix(GuiView & lv);
4010 Dialog * createGuiNote(GuiView & lv);
4011 Dialog * createGuiParagraph(GuiView & lv);
4012 Dialog * createGuiPhantom(GuiView & lv);
4013 Dialog * createGuiPreferences(GuiView & lv);
4014 Dialog * createGuiPrint(GuiView & lv);
4015 Dialog * createGuiPrintindex(GuiView & lv);
4016 Dialog * createGuiRef(GuiView & lv);
4017 Dialog * createGuiSearch(GuiView & lv);
4018 Dialog * createGuiSearchAdv(GuiView & lv);
4019 Dialog * createGuiSendTo(GuiView & lv);
4020 Dialog * createGuiShowFile(GuiView & lv);
4021 Dialog * createGuiSpellchecker(GuiView & lv);
4022 Dialog * createGuiSymbols(GuiView & lv);
4023 Dialog * createGuiTabularCreate(GuiView & lv);
4024 Dialog * createGuiTexInfo(GuiView & lv);
4025 Dialog * createGuiToc(GuiView & lv);
4026 Dialog * createGuiThesaurus(GuiView & lv);
4027 Dialog * createGuiViewSource(GuiView & lv);
4028 Dialog * createGuiWrap(GuiView & lv);
4029 Dialog * createGuiProgressView(GuiView & lv);
4033 Dialog * GuiView::build(string const & name)
4035 LASSERT(isValidName(name), return 0);
4037 Dialog * dialog = createDialog(*this, name);
4041 if (name == "aboutlyx")
4042 return createGuiAbout(*this);
4043 if (name == "bibtex")
4044 return createGuiBibtex(*this);
4045 if (name == "changes")
4046 return createGuiChanges(*this);
4047 if (name == "character")
4048 return createGuiCharacter(*this);
4049 if (name == "citation")
4050 return createGuiCitation(*this);
4051 if (name == "compare")
4052 return createGuiCompare(*this);
4053 if (name == "comparehistory")
4054 return createGuiCompareHistory(*this);
4055 if (name == "document")
4056 return createGuiDocument(*this);
4057 if (name == "errorlist")
4058 return createGuiErrorList(*this);
4059 if (name == "external")
4060 return createGuiExternal(*this);
4062 return createGuiShowFile(*this);
4063 if (name == "findreplace")
4064 return createGuiSearch(*this);
4065 if (name == "findreplaceadv")
4066 return createGuiSearchAdv(*this);
4067 if (name == "graphics")
4068 return createGuiGraphics(*this);
4069 if (name == "include")
4070 return createGuiInclude(*this);
4071 if (name == "index")
4072 return createGuiIndex(*this);
4073 if (name == "index_print")
4074 return createGuiPrintindex(*this);
4075 if (name == "listings")
4076 return createGuiListings(*this);
4078 return createGuiLog(*this);
4079 if (name == "mathdelimiter")
4080 return createGuiDelimiter(*this);
4081 if (name == "mathmatrix")
4082 return createGuiMathMatrix(*this);
4084 return createGuiNote(*this);
4085 if (name == "paragraph")
4086 return createGuiParagraph(*this);
4087 if (name == "phantom")
4088 return createGuiPhantom(*this);
4089 if (name == "prefs")
4090 return createGuiPreferences(*this);
4091 if (name == "print")
4092 return createGuiPrint(*this);
4094 return createGuiRef(*this);
4095 if (name == "sendto")
4096 return createGuiSendTo(*this);
4097 if (name == "spellchecker")
4098 return createGuiSpellchecker(*this);
4099 if (name == "symbols")
4100 return createGuiSymbols(*this);
4101 if (name == "tabularcreate")
4102 return createGuiTabularCreate(*this);
4103 if (name == "texinfo")
4104 return createGuiTexInfo(*this);
4105 if (name == "thesaurus")
4106 return createGuiThesaurus(*this);
4108 return createGuiToc(*this);
4109 if (name == "view-source")
4110 return createGuiViewSource(*this);
4112 return createGuiWrap(*this);
4113 if (name == "progress")
4114 return createGuiProgressView(*this);
4120 } // namespace frontend
4123 #include "moc_GuiView.cpp"