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>
92 #include <QFutureWatcher>
100 #include <QPixmapCache>
102 #include <QPushButton>
103 #include <QScrollBar>
105 #include <QShowEvent>
107 #include <QStackedWidget>
108 #include <QStatusBar>
109 #include <QtConcurrentRun>
117 #define EXPORT_in_THREAD 1
120 #include "support/bind.h"
124 #ifdef HAVE_SYS_TIME_H
125 # include <sys/time.h>
133 using namespace lyx::support;
137 using support::addExtension;
138 using support::changeExtension;
139 using support::removeExtension;
145 class BackgroundWidget : public QWidget
150 LYXERR(Debug::GUI, "show banner: " << lyxrc.show_banner);
151 if (!lyxrc.show_banner)
153 /// The text to be written on top of the pixmap
154 QString const text = lyx_version ?
155 qt_("version ") + lyx_version : qt_("unknown version");
156 splash_ = getPixmap("images/", "banner", "png");
158 QPainter pain(&splash_);
159 pain.setPen(QColor(0, 0, 0));
161 // The font used to display the version info
162 font.setStyleHint(QFont::SansSerif);
163 font.setWeight(QFont::Bold);
164 font.setPointSize(int(toqstr(lyxrc.font_sizes[FONT_SIZE_LARGE]).toDouble()));
166 pain.drawText(190, 225, text);
167 setFocusPolicy(Qt::StrongFocus);
170 void paintEvent(QPaintEvent *)
172 int x = (width() - splash_.width()) / 2;
173 int y = (height() - splash_.height()) / 2;
175 pain.drawPixmap(x, y, splash_);
178 void keyPressEvent(QKeyEvent * ev)
181 setKeySymbol(&sym, ev);
183 guiApp->processKeySym(sym, q_key_state(ev->modifiers()));
195 /// Toolbar store providing access to individual toolbars by name.
196 typedef map<string, GuiToolbar *> ToolbarMap;
198 typedef shared_ptr<Dialog> DialogPtr;
203 struct GuiView::GuiViewPrivate
205 GuiViewPrivate(GuiView * gv)
206 : gv_(gv), current_work_area_(0), current_main_work_area_(0),
207 layout_(0), autosave_timeout_(5000),
210 // hardcode here the platform specific icon size
211 smallIconSize = 16; // scaling problems
212 normalIconSize = 20; // ok, default if iconsize.png is missing
213 bigIconSize = 26; // better for some math icons
215 // if it exists, use width of iconsize.png as normal size
216 QString const dir = toqstr(addPath("images", lyxrc.icon_set));
217 FileName const fn = lyx::libFileSearch(dir, "iconsize.png");
219 QImage image(toqstr(fn.absFileName()));
220 if (image.width() < int(smallIconSize))
221 normalIconSize = smallIconSize;
222 else if (image.width() > int(bigIconSize))
223 normalIconSize = bigIconSize;
225 normalIconSize = image.width();
228 splitter_ = new QSplitter;
229 bg_widget_ = new BackgroundWidget;
230 stack_widget_ = new QStackedWidget;
231 stack_widget_->addWidget(bg_widget_);
232 stack_widget_->addWidget(splitter_);
235 // TODO cleanup, remove the singleton, handle multiple Windows?
236 progress_ = ProgressInterface::instance();
237 if (!dynamic_cast<GuiProgress*>(progress_)) {
238 progress_ = new GuiProgress; // TODO who deletes it
239 ProgressInterface::setInstance(progress_);
242 dynamic_cast<GuiProgress*>(progress_),
243 SIGNAL(updateStatusBarMessage(QString const&)),
244 gv, SLOT(updateStatusBarMessage(QString const&)));
246 dynamic_cast<GuiProgress*>(progress_),
247 SIGNAL(clearMessageText()),
248 gv, SLOT(clearMessageText()));
255 delete stack_widget_;
258 QMenu * toolBarPopup(GuiView * parent)
260 // FIXME: translation
261 QMenu * menu = new QMenu(parent);
262 QActionGroup * iconSizeGroup = new QActionGroup(parent);
264 QAction * smallIcons = new QAction(iconSizeGroup);
265 smallIcons->setText(qt_("Small-sized icons"));
266 smallIcons->setCheckable(true);
267 QObject::connect(smallIcons, SIGNAL(triggered()),
268 parent, SLOT(smallSizedIcons()));
269 menu->addAction(smallIcons);
271 QAction * normalIcons = new QAction(iconSizeGroup);
272 normalIcons->setText(qt_("Normal-sized icons"));
273 normalIcons->setCheckable(true);
274 QObject::connect(normalIcons, SIGNAL(triggered()),
275 parent, SLOT(normalSizedIcons()));
276 menu->addAction(normalIcons);
278 QAction * bigIcons = new QAction(iconSizeGroup);
279 bigIcons->setText(qt_("Big-sized icons"));
280 bigIcons->setCheckable(true);
281 QObject::connect(bigIcons, SIGNAL(triggered()),
282 parent, SLOT(bigSizedIcons()));
283 menu->addAction(bigIcons);
285 unsigned int cur = parent->iconSize().width();
286 if ( cur == parent->d.smallIconSize)
287 smallIcons->setChecked(true);
288 else if (cur == parent->d.normalIconSize)
289 normalIcons->setChecked(true);
290 else if (cur == parent->d.bigIconSize)
291 bigIcons->setChecked(true);
298 stack_widget_->setCurrentWidget(bg_widget_);
299 bg_widget_->setUpdatesEnabled(true);
300 bg_widget_->setFocus();
303 int tabWorkAreaCount()
305 return splitter_->count();
308 TabWorkArea * tabWorkArea(int i)
310 return dynamic_cast<TabWorkArea *>(splitter_->widget(i));
313 TabWorkArea * currentTabWorkArea()
315 int areas = tabWorkAreaCount();
317 // The first TabWorkArea is always the first one, if any.
318 return tabWorkArea(0);
320 for (int i = 0; i != areas; ++i) {
321 TabWorkArea * twa = tabWorkArea(i);
322 if (current_main_work_area_ == twa->currentWorkArea())
326 // None has the focus so we just take the first one.
327 return tabWorkArea(0);
330 int countWorkAreasOf(Buffer & buf)
332 int areas = tabWorkAreaCount();
334 for (int i = 0; i != areas; ++i) {
335 TabWorkArea * twa = tabWorkArea(i);
336 if (twa->workArea(buf))
342 void setPreviewFuture(QFuture<Buffer::ExportStatus> const & f)
344 if (processing_thread_watcher_.isRunning()) {
345 // we prefer to cancel this preview in order to keep a snappy
349 processing_thread_watcher_.setFuture(f);
354 GuiWorkArea * current_work_area_;
355 GuiWorkArea * current_main_work_area_;
356 QSplitter * splitter_;
357 QStackedWidget * stack_widget_;
358 BackgroundWidget * bg_widget_;
360 ToolbarMap toolbars_;
361 ProgressInterface* progress_;
362 /// The main layout box.
364 * \warning Don't Delete! The layout box is actually owned by
365 * whichever toolbar contains it. All the GuiView class needs is a
366 * means of accessing it.
368 * FIXME: replace that with a proper model so that we are not limited
369 * to only one dialog.
374 map<string, DialogPtr> dialogs_;
376 unsigned int smallIconSize;
377 unsigned int normalIconSize;
378 unsigned int bigIconSize;
380 QTimer statusbar_timer_;
381 /// auto-saving of buffers
382 Timeout autosave_timeout_;
383 /// flag against a race condition due to multiclicks, see bug #1119
387 TocModels toc_models_;
390 QFutureWatcher<docstring> autosave_watcher_;
391 QFutureWatcher<Buffer::ExportStatus> processing_thread_watcher_;
393 string last_export_format;
394 string processing_format;
396 static QSet<Buffer const *> busyBuffers;
397 static Buffer::ExportStatus previewAndDestroy(Buffer const * orig, Buffer * buffer, string const & format);
398 static Buffer::ExportStatus exportAndDestroy(Buffer const * orig, Buffer * buffer, string const & format);
399 static Buffer::ExportStatus compileAndDestroy(Buffer const * orig, Buffer * buffer, string const & format);
400 static docstring autosaveAndDestroy(Buffer const * orig, Buffer * buffer);
403 static Buffer::ExportStatus runAndDestroy(const T& func, Buffer const * orig, Buffer * buffer, string const & format);
405 // TODO syncFunc/previewFunc: use bind
406 bool asyncBufferProcessing(string const & argument,
407 Buffer const * used_buffer,
408 docstring const & msg,
409 Buffer::ExportStatus (*asyncFunc)(Buffer const *, Buffer *, string const &),
410 Buffer::ExportStatus (Buffer::*syncFunc)(string const &, bool) const,
411 Buffer::ExportStatus (Buffer::*previewFunc)(string const &) const);
413 QVector<GuiWorkArea*> guiWorkAreas();
416 QSet<Buffer const *> GuiView::GuiViewPrivate::busyBuffers;
419 GuiView::GuiView(int id)
420 : d(*new GuiViewPrivate(this)), id_(id), closing_(false), busy_(0)
422 // GuiToolbars *must* be initialised before the menu bar.
423 normalSizedIcons(); // at least on Mac the default is 32 otherwise, which is huge
426 // set ourself as the current view. This is needed for the menu bar
427 // filling, at least for the static special menu item on Mac. Otherwise
428 // they are greyed out.
429 guiApp->setCurrentView(this);
431 // Fill up the menu bar.
432 guiApp->menus().fillMenuBar(menuBar(), this, true);
434 setCentralWidget(d.stack_widget_);
436 // Start autosave timer
437 if (lyxrc.autosave) {
438 d.autosave_timeout_.timeout.connect(bind(&GuiView::autoSave, this));
439 d.autosave_timeout_.setTimeout(lyxrc.autosave * 1000);
440 d.autosave_timeout_.start();
442 connect(&d.statusbar_timer_, SIGNAL(timeout()),
443 this, SLOT(clearMessage()));
445 // We don't want to keep the window in memory if it is closed.
446 setAttribute(Qt::WA_DeleteOnClose, true);
448 #if (!defined(Q_WS_WIN) && !defined(Q_WS_MACX))
449 // QIcon::fromTheme was introduced in Qt 4.6
450 #if (QT_VERSION >= 0x040600)
451 // assign an icon to main form. We do not do it under Qt/Win or Qt/Mac,
452 // since the icon is provided in the application bundle. We use a themed
453 // version when available and use the bundled one as fallback.
454 setWindowIcon(QIcon::fromTheme("lyx", getPixmap("images/", "lyx", "png")));
456 setWindowIcon(getPixmap("images/", "lyx", "png"));
461 // use tabbed dock area for multiple docks
462 // (such as "source" and "messages")
463 setDockOptions(QMainWindow::ForceTabbedDocks);
466 setAcceptDrops(true);
468 // add busy indicator to statusbar
469 QLabel * busylabel = new QLabel(statusBar());
470 statusBar()->addPermanentWidget(busylabel);
471 QString fn = toqstr(lyx::libFileSearch("images", "busy.gif").absFileName());
472 QMovie * busyanim = new QMovie(fn, QByteArray(), busylabel);
473 busylabel->setMovie(busyanim);
477 connect(&d.processing_thread_watcher_, SIGNAL(started()),
478 busylabel, SLOT(show()));
479 connect(&d.processing_thread_watcher_, SIGNAL(finished()),
480 busylabel, SLOT(hide()));
482 statusBar()->setSizeGripEnabled(true);
485 connect(&d.autosave_watcher_, SIGNAL(finished()), this,
486 SLOT(autoSaveThreadFinished()));
488 connect(&d.processing_thread_watcher_, SIGNAL(started()), this,
489 SLOT(processingThreadStarted()));
490 connect(&d.processing_thread_watcher_, SIGNAL(finished()), this,
491 SLOT(processingThreadFinished()));
493 connect(this, SIGNAL(triggerShowDialog(QString const &, QString const &, Inset *)),
494 SLOT(doShowDialog(QString const &, QString const &, Inset *)));
496 // Forbid too small unresizable window because it can happen
497 // with some window manager under X11.
498 setMinimumSize(300, 200);
500 if (lyxrc.allow_geometry_session) {
501 // Now take care of session management.
506 // no session handling, default to a sane size.
507 setGeometry(50, 50, 690, 510);
510 // clear session data if any.
512 settings.remove("views");
522 QVector<GuiWorkArea*> GuiView::GuiViewPrivate::guiWorkAreas()
524 QVector<GuiWorkArea*> areas;
525 for (int i = 0; i < tabWorkAreaCount(); i++) {
526 TabWorkArea* ta = tabWorkArea(i);
527 for (int u = 0; u < ta->count(); u++) {
528 areas << ta->workArea(u);
534 static void handleExportStatus(GuiView * view, Buffer::ExportStatus status,
535 string const & format)
537 docstring const fmt = formats.prettyName(format);
540 case Buffer::ExportSuccess:
541 msg = bformat(_("Successful export to format: %1$s"), fmt);
543 case Buffer::ExportCancel:
544 msg = _("Document export cancelled.");
546 case Buffer::ExportError:
547 case Buffer::ExportNoPathToFormat:
548 case Buffer::ExportTexPathHasSpaces:
549 case Buffer::ExportConverterError:
550 msg = bformat(_("Error while exporting format: %1$s"), fmt);
552 case Buffer::PreviewSuccess:
553 msg = bformat(_("Successful preview of format: %1$s"), fmt);
555 case Buffer::PreviewError:
556 msg = bformat(_("Error while previewing format: %1$s"), fmt);
563 void GuiView::processingThreadStarted()
568 void GuiView::processingThreadFinished()
570 QFutureWatcher<Buffer::ExportStatus> const * watcher =
571 static_cast<QFutureWatcher<Buffer::ExportStatus> const *>(sender());
573 Buffer::ExportStatus const status = watcher->result();
574 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);
586 void GuiView::autoSaveThreadFinished()
588 QFutureWatcher<docstring> const * watcher =
589 static_cast<QFutureWatcher<docstring> const *>(sender());
590 message(watcher->result());
595 void GuiView::saveLayout() const
598 settings.beginGroup("views");
599 settings.beginGroup(QString::number(id_));
601 settings.setValue("pos", pos());
602 settings.setValue("size", size());
604 settings.setValue("geometry", saveGeometry());
606 settings.setValue("layout", saveState(0));
607 settings.setValue("icon_size", iconSize());
611 void GuiView::saveUISettings() const
613 // Save the toolbar private states
614 ToolbarMap::iterator end = d.toolbars_.end();
615 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
616 it->second->saveSession();
617 // Now take care of all other dialogs
618 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
619 for (; it!= d.dialogs_.end(); ++it)
620 it->second->saveSession();
624 bool GuiView::restoreLayout()
627 settings.beginGroup("views");
628 settings.beginGroup(QString::number(id_));
629 QString const icon_key = "icon_size";
630 if (!settings.contains(icon_key))
633 //code below is skipped when when ~/.config/LyX is (re)created
634 QSize icon_size = settings.value(icon_key).toSize();
635 // Check whether session size changed.
636 if (icon_size.width() != int(d.smallIconSize) &&
637 icon_size.width() != int(d.normalIconSize) &&
638 icon_size.width() != int(d.bigIconSize)) {
639 icon_size.setWidth(d.normalIconSize);
640 icon_size.setHeight(d.normalIconSize);
642 setIconSize(icon_size);
645 QPoint pos = settings.value("pos", QPoint(50, 50)).toPoint();
646 QSize size = settings.value("size", QSize(690, 510)).toSize();
650 // Work-around for bug #6034: the window ends up in an undetermined
651 // state when trying to restore a maximized window when it is
652 // already maximized.
653 if (!(windowState() & Qt::WindowMaximized))
654 if (!restoreGeometry(settings.value("geometry").toByteArray()))
655 setGeometry(50, 50, 690, 510);
657 // Make sure layout is correctly oriented.
658 setLayoutDirection(qApp->layoutDirection());
660 // Allow the toc and view-source dock widget to be restored if needed.
662 if ((dialog = findOrBuild("toc", true)))
663 // see bug 5082. At least setup title and enabled state.
664 // Visibility will be adjusted by restoreState below.
665 dialog->prepareView();
666 if ((dialog = findOrBuild("view-source", true)))
667 dialog->prepareView();
668 if ((dialog = findOrBuild("progress", true)))
669 dialog->prepareView();
670 if ((dialog = findOrBuild("findreplaceadv", true)))
671 dialog->prepareView();
673 if (!restoreState(settings.value("layout").toByteArray(), 0))
680 GuiToolbar * GuiView::toolbar(string const & name)
682 ToolbarMap::iterator it = d.toolbars_.find(name);
683 if (it != d.toolbars_.end())
686 LYXERR(Debug::GUI, "Toolbar::display: no toolbar named " << name);
691 void GuiView::constructToolbars()
693 ToolbarMap::iterator it = d.toolbars_.begin();
694 for (; it != d.toolbars_.end(); ++it)
698 // I don't like doing this here, but the standard toolbar
699 // destroys this object when it's destroyed itself (vfr)
700 d.layout_ = new LayoutBox(*this);
701 d.stack_widget_->addWidget(d.layout_);
702 d.layout_->move(0,0);
704 // extracts the toolbars from the backend
705 Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
706 Toolbars::Infos::iterator end = guiApp->toolbars().end();
707 for (; cit != end; ++cit)
708 d.toolbars_[cit->name] = new GuiToolbar(*cit, *this);
712 void GuiView::initToolbars()
714 // extracts the toolbars from the backend
715 Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
716 Toolbars::Infos::iterator end = guiApp->toolbars().end();
717 for (; cit != end; ++cit) {
718 GuiToolbar * tb = toolbar(cit->name);
721 int const visibility = guiApp->toolbars().defaultVisibility(cit->name);
722 bool newline = !(visibility & Toolbars::SAMEROW);
723 tb->setVisible(false);
724 tb->setVisibility(visibility);
726 if (visibility & Toolbars::TOP) {
728 addToolBarBreak(Qt::TopToolBarArea);
729 addToolBar(Qt::TopToolBarArea, tb);
732 if (visibility & Toolbars::BOTTOM) {
734 addToolBarBreak(Qt::BottomToolBarArea);
735 addToolBar(Qt::BottomToolBarArea, tb);
738 if (visibility & Toolbars::LEFT) {
740 addToolBarBreak(Qt::LeftToolBarArea);
741 addToolBar(Qt::LeftToolBarArea, tb);
744 if (visibility & Toolbars::RIGHT) {
746 addToolBarBreak(Qt::RightToolBarArea);
747 addToolBar(Qt::RightToolBarArea, tb);
750 if (visibility & Toolbars::ON)
751 tb->setVisible(true);
756 TocModels & GuiView::tocModels()
758 return d.toc_models_;
762 void GuiView::setFocus()
764 LYXERR(Debug::DEBUG, "GuiView::setFocus()" << this);
765 QMainWindow::setFocus();
769 void GuiView::focusInEvent(QFocusEvent * e)
771 LYXERR(Debug::DEBUG, "GuiView::focusInEvent()" << this);
772 QMainWindow::focusInEvent(e);
773 // Make sure guiApp points to the correct view.
774 guiApp->setCurrentView(this);
775 if (currentWorkArea())
776 currentWorkArea()->setFocus();
777 else if (currentMainWorkArea())
778 currentMainWorkArea()->setFocus();
780 d.bg_widget_->setFocus();
784 QMenu * GuiView::createPopupMenu()
786 return d.toolBarPopup(this);
790 void GuiView::showEvent(QShowEvent * e)
792 LYXERR(Debug::GUI, "Passed Geometry "
793 << size().height() << "x" << size().width()
794 << "+" << pos().x() << "+" << pos().y());
796 if (d.splitter_->count() == 0)
797 // No work area, switch to the background widget.
801 QMainWindow::showEvent(e);
805 bool GuiView::closeScheduled()
812 /** Destroy only all tabbed WorkAreas. Destruction of other WorkAreas
813 ** is responsibility of the container (e.g., dialog)
815 void GuiView::closeEvent(QCloseEvent * close_event)
817 LYXERR(Debug::DEBUG, "GuiView::closeEvent()");
819 if (!GuiViewPrivate::busyBuffers.isEmpty()) {
820 Alert::warning(_("Exit LyX"),
821 _("LyX could not be closed because documents are being processed by LyX."));
822 close_event->setAccepted(false);
826 // If the user pressed the x (so we didn't call closeView
827 // programmatically), we want to clear all existing entries.
829 theSession().lastOpened().clear();
834 // it can happen that this event arrives without selecting the view,
835 // e.g. when clicking the close button on a background window.
837 if (!closeWorkAreaAll()) {
839 close_event->ignore();
843 // Make sure that nothing will use this to be closed View.
844 guiApp->unregisterView(this);
846 if (isFullScreen()) {
847 // Switch off fullscreen before closing.
852 // Make sure the timer time out will not trigger a statusbar update.
853 d.statusbar_timer_.stop();
855 // Saving fullscreen requires additional tweaks in the toolbar code.
856 // It wouldn't also work under linux natively.
857 if (lyxrc.allow_geometry_session) {
862 close_event->accept();
866 void GuiView::dragEnterEvent(QDragEnterEvent * event)
868 if (event->mimeData()->hasUrls())
870 /// \todo Ask lyx-devel is this is enough:
871 /// if (event->mimeData()->hasFormat("text/plain"))
872 /// event->acceptProposedAction();
876 void GuiView::dropEvent(QDropEvent * event)
878 QList<QUrl> files = event->mimeData()->urls();
882 LYXERR(Debug::GUI, "GuiView::dropEvent: got URLs!");
883 for (int i = 0; i != files.size(); ++i) {
884 string const file = os::internal_path(fromqstr(
885 files.at(i).toLocalFile()));
889 string const ext = support::getExtension(file);
890 vector<const Format *> found_formats;
892 // Find all formats that have the correct extension.
893 vector<const Format *> const & import_formats
894 = theConverters().importableFormats();
895 vector<const Format *>::const_iterator it = import_formats.begin();
896 for (; it != import_formats.end(); ++it)
897 if ((*it)->hasExtension(ext))
898 found_formats.push_back(*it);
901 if (found_formats.size() >= 1) {
902 if (found_formats.size() > 1) {
903 //FIXME: show a dialog to choose the correct importable format
905 "Multiple importable formats found, selecting first");
907 string const arg = found_formats[0]->name() + " " + file;
908 cmd = FuncRequest(LFUN_BUFFER_IMPORT, arg);
911 //FIXME: do we have to explicitly check whether it's a lyx file?
913 "No formats found, trying to open it as a lyx file");
914 cmd = FuncRequest(LFUN_FILE_OPEN, file);
916 // add the functions to the queue
917 guiApp->addToFuncRequestQueue(cmd);
920 // now process the collected functions. We perform the events
921 // asynchronously. This prevents potential problems in case the
922 // BufferView is closed within an event.
923 guiApp->processFuncRequestQueueAsync();
927 void GuiView::message(docstring const & str)
929 if (ForkedProcess::iAmAChild())
932 // call is moved to GUI-thread by GuiProgress
933 d.progress_->appendMessage(toqstr(str));
937 void GuiView::clearMessageText()
939 message(docstring());
943 void GuiView::updateStatusBarMessage(QString const & str)
945 statusBar()->showMessage(str);
946 d.statusbar_timer_.stop();
947 d.statusbar_timer_.start(3000);
951 void GuiView::smallSizedIcons()
953 setIconSize(QSize(d.smallIconSize, d.smallIconSize));
957 void GuiView::normalSizedIcons()
959 setIconSize(QSize(d.normalIconSize, d.normalIconSize));
963 void GuiView::bigSizedIcons()
965 setIconSize(QSize(d.bigIconSize, d.bigIconSize));
969 void GuiView::clearMessage()
971 // FIXME: This code was introduced in r19643 to fix bug #4123. However,
972 // the hasFocus function mostly returns false, even if the focus is on
973 // a workarea in this view.
977 d.statusbar_timer_.stop();
981 void GuiView::updateWindowTitle(GuiWorkArea * wa)
983 if (wa != d.current_work_area_
984 || wa->bufferView().buffer().isInternal())
986 setWindowTitle(qt_("LyX: ") + wa->windowTitle());
987 setWindowIconText(wa->windowIconText());
991 void GuiView::on_currentWorkAreaChanged(GuiWorkArea * wa)
993 if (d.current_work_area_)
994 QObject::disconnect(d.current_work_area_, SIGNAL(busy(bool)),
995 this, SLOT(setBusy(bool)));
997 disconnectBufferView();
998 connectBufferView(wa->bufferView());
999 connectBuffer(wa->bufferView().buffer());
1000 d.current_work_area_ = wa;
1001 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
1002 this, SLOT(updateWindowTitle(GuiWorkArea *)));
1003 QObject::connect(wa, SIGNAL(busy(bool)), this, SLOT(setBusy(bool)));
1004 updateWindowTitle(wa);
1008 // The document settings needs to be reinitialised.
1009 updateDialog("document", "");
1011 // Buffer-dependent dialogs must be updated. This is done here because
1012 // some dialogs require buffer()->text.
1017 void GuiView::on_lastWorkAreaRemoved()
1020 // We already are in a close event. Nothing more to do.
1023 if (d.splitter_->count() > 1)
1024 // We have a splitter so don't close anything.
1027 // Reset and updates the dialogs.
1028 d.toc_models_.reset(0);
1029 updateDialog("document", "");
1032 resetWindowTitleAndIconText();
1035 if (lyxrc.open_buffers_in_tabs)
1036 // Nothing more to do, the window should stay open.
1039 if (guiApp->viewIds().size() > 1) {
1045 // On Mac we also close the last window because the application stay
1046 // resident in memory. On other platforms we don't close the last
1047 // window because this would quit the application.
1053 void GuiView::updateStatusBar()
1055 // let the user see the explicit message
1056 if (d.statusbar_timer_.isActive())
1063 void GuiView::showMessage()
1065 QString msg = toqstr(theGuiApp()->viewStatusMessage());
1066 if (msg.isEmpty()) {
1067 BufferView const * bv = currentBufferView();
1069 msg = toqstr(bv->cursor().currentState());
1071 msg = qt_("Welcome to LyX!");
1073 statusBar()->showMessage(msg);
1077 bool GuiView::event(QEvent * e)
1081 // Useful debug code:
1082 //case QEvent::ActivationChange:
1083 //case QEvent::WindowDeactivate:
1084 //case QEvent::Paint:
1085 //case QEvent::Enter:
1086 //case QEvent::Leave:
1087 //case QEvent::HoverEnter:
1088 //case QEvent::HoverLeave:
1089 //case QEvent::HoverMove:
1090 //case QEvent::StatusTip:
1091 //case QEvent::DragEnter:
1092 //case QEvent::DragLeave:
1093 //case QEvent::Drop:
1096 case QEvent::WindowActivate: {
1097 GuiView * old_view = guiApp->currentView();
1098 if (this == old_view) {
1100 return QMainWindow::event(e);
1102 if (old_view && old_view->currentBufferView()) {
1103 // save current selection to the selection buffer to allow
1104 // middle-button paste in this window.
1105 cap::saveSelection(old_view->currentBufferView()->cursor());
1107 guiApp->setCurrentView(this);
1108 if (d.current_work_area_) {
1109 BufferView & bv = d.current_work_area_->bufferView();
1110 connectBufferView(bv);
1111 connectBuffer(bv.buffer());
1112 // The document structure, name and dialogs might have
1113 // changed in another view.
1115 // The document settings needs to be reinitialised.
1116 updateDialog("document", "");
1119 resetWindowTitleAndIconText();
1122 return QMainWindow::event(e);
1125 case QEvent::ShortcutOverride: {
1127 if (isFullScreen() && menuBar()->isHidden()) {
1128 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
1129 // FIXME: we should also try to detect special LyX shortcut such as
1130 // Alt-P and Alt-M. Right now there is a hack in
1131 // GuiWorkArea::processKeySym() that hides again the menubar for
1133 if (ke->modifiers() & Qt::AltModifier && ke->key() != Qt::Key_Alt) {
1135 return QMainWindow::event(e);
1138 return QMainWindow::event(e);
1142 return QMainWindow::event(e);
1146 void GuiView::resetWindowTitleAndIconText()
1148 setWindowTitle(qt_("LyX"));
1149 setWindowIconText(qt_("LyX"));
1152 bool GuiView::focusNextPrevChild(bool /*next*/)
1159 bool GuiView::busy() const
1165 void GuiView::setBusy(bool busy)
1167 bool const busy_before = busy_ > 0;
1168 busy ? ++busy_ : --busy_;
1169 if ((busy_ > 0) == busy_before)
1170 // busy state didn't change
1174 QApplication::setOverrideCursor(Qt::WaitCursor);
1177 QApplication::restoreOverrideCursor();
1182 GuiWorkArea * GuiView::workArea(int index)
1184 if (TabWorkArea * twa = d.currentTabWorkArea())
1185 if (index < twa->count())
1186 return dynamic_cast<GuiWorkArea *>(twa->widget(index));
1191 GuiWorkArea * GuiView::workArea(Buffer & buffer)
1193 if (currentWorkArea()
1194 && ¤tWorkArea()->bufferView().buffer() == &buffer)
1195 return (GuiWorkArea *) currentWorkArea();
1196 if (TabWorkArea * twa = d.currentTabWorkArea())
1197 return twa->workArea(buffer);
1202 GuiWorkArea * GuiView::addWorkArea(Buffer & buffer)
1204 // Automatically create a TabWorkArea if there are none yet.
1205 TabWorkArea * tab_widget = d.splitter_->count()
1206 ? d.currentTabWorkArea() : addTabWorkArea();
1207 return tab_widget->addWorkArea(buffer, *this);
1211 TabWorkArea * GuiView::addTabWorkArea()
1213 TabWorkArea * twa = new TabWorkArea;
1214 QObject::connect(twa, SIGNAL(currentWorkAreaChanged(GuiWorkArea *)),
1215 this, SLOT(on_currentWorkAreaChanged(GuiWorkArea *)));
1216 QObject::connect(twa, SIGNAL(lastWorkAreaRemoved()),
1217 this, SLOT(on_lastWorkAreaRemoved()));
1219 d.splitter_->addWidget(twa);
1220 d.stack_widget_->setCurrentWidget(d.splitter_);
1225 GuiWorkArea const * GuiView::currentWorkArea() const
1227 return d.current_work_area_;
1231 GuiWorkArea * GuiView::currentWorkArea()
1233 return d.current_work_area_;
1237 GuiWorkArea const * GuiView::currentMainWorkArea() const
1239 if (!d.currentTabWorkArea())
1241 return d.currentTabWorkArea()->currentWorkArea();
1245 GuiWorkArea * GuiView::currentMainWorkArea()
1247 if (!d.currentTabWorkArea())
1249 return d.currentTabWorkArea()->currentWorkArea();
1253 void GuiView::setCurrentWorkArea(GuiWorkArea * wa)
1255 LYXERR(Debug::DEBUG, "Setting current wa: " << wa << endl);
1257 d.current_work_area_ = 0;
1262 // FIXME: I've no clue why this is here and why it accesses
1263 // theGuiApp()->currentView, which might be 0 (bug 6464).
1264 // See also 27525 (vfr).
1265 if (theGuiApp()->currentView() == this
1266 && theGuiApp()->currentView()->currentWorkArea() == wa)
1269 if (currentBufferView())
1270 cap::saveSelection(currentBufferView()->cursor());
1272 theGuiApp()->setCurrentView(this);
1273 d.current_work_area_ = wa;
1275 // We need to reset this now, because it will need to be
1276 // right if the tabWorkArea gets reset in the for loop. We
1277 // will change it back if we aren't in that case.
1278 GuiWorkArea * const old_cmwa = d.current_main_work_area_;
1279 d.current_main_work_area_ = wa;
1281 for (int i = 0; i != d.splitter_->count(); ++i) {
1282 if (d.tabWorkArea(i)->setCurrentWorkArea(wa)) {
1283 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea()
1284 << ", Current main wa: " << currentMainWorkArea());
1289 d.current_main_work_area_ = old_cmwa;
1291 LYXERR(Debug::DEBUG, "This is not a tabbed wa");
1292 on_currentWorkAreaChanged(wa);
1293 BufferView & bv = wa->bufferView();
1294 bv.cursor().fixIfBroken();
1296 wa->setUpdatesEnabled(true);
1297 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() << ", Current main wa: " << currentMainWorkArea());
1301 void GuiView::removeWorkArea(GuiWorkArea * wa)
1303 LASSERT(wa, return);
1304 if (wa == d.current_work_area_) {
1306 disconnectBufferView();
1307 d.current_work_area_ = 0;
1308 d.current_main_work_area_ = 0;
1311 bool found_twa = false;
1312 for (int i = 0; i != d.splitter_->count(); ++i) {
1313 TabWorkArea * twa = d.tabWorkArea(i);
1314 if (twa->removeWorkArea(wa)) {
1315 // Found in this tab group, and deleted the GuiWorkArea.
1317 if (twa->count() != 0) {
1318 if (d.current_work_area_ == 0)
1319 // This means that we are closing the current GuiWorkArea, so
1320 // switch to the next GuiWorkArea in the found TabWorkArea.
1321 setCurrentWorkArea(twa->currentWorkArea());
1323 // No more WorkAreas in this tab group, so delete it.
1330 // It is not a tabbed work area (i.e., the search work area), so it
1331 // should be deleted by other means.
1332 LASSERT(found_twa, /* */);
1334 if (d.current_work_area_ == 0) {
1335 if (d.splitter_->count() != 0) {
1336 TabWorkArea * twa = d.currentTabWorkArea();
1337 setCurrentWorkArea(twa->currentWorkArea());
1339 // No more work areas, switch to the background widget.
1340 setCurrentWorkArea(0);
1346 LayoutBox * GuiView::getLayoutDialog() const
1352 void GuiView::updateLayoutList()
1355 d.layout_->updateContents(false);
1359 void GuiView::updateToolbars()
1361 ToolbarMap::iterator end = d.toolbars_.end();
1362 if (d.current_work_area_) {
1364 d.current_work_area_->bufferView().cursor().inMathed()
1365 && !d.current_work_area_->bufferView().cursor().inRegexped();
1367 lyx::getStatus(FuncRequest(LFUN_LAYOUT_TABULAR)).enabled();
1369 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).enabled() &&
1370 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).onOff(true);
1371 bool const mathmacrotemplate =
1372 lyx::getStatus(FuncRequest(LFUN_IN_MATHMACROTEMPLATE)).enabled();
1374 lyx::getStatus(FuncRequest(LFUN_IN_IPA)).enabled();
1376 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1377 it->second->update(math, table, review, mathmacrotemplate, ipa);
1379 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1380 it->second->update(false, false, false, false, false);
1384 void GuiView::setBuffer(Buffer * newBuffer)
1386 LYXERR(Debug::DEBUG, "Setting buffer: " << newBuffer << endl);
1387 LASSERT(newBuffer, return);
1389 GuiWorkArea * wa = workArea(*newBuffer);
1392 newBuffer->masterBuffer()->updateBuffer();
1394 wa = addWorkArea(*newBuffer);
1395 // scroll to the position when the BufferView was last closed
1396 if (lyxrc.use_lastfilepos) {
1397 LastFilePosSection::FilePos filepos =
1398 theSession().lastFilePos().load(newBuffer->fileName());
1399 wa->bufferView().moveToPosition(filepos.pit, filepos.pos, 0, 0);
1402 //Disconnect the old buffer...there's no new one.
1405 connectBuffer(*newBuffer);
1406 connectBufferView(wa->bufferView());
1407 setCurrentWorkArea(wa);
1411 void GuiView::connectBuffer(Buffer & buf)
1413 buf.setGuiDelegate(this);
1417 void GuiView::disconnectBuffer()
1419 if (d.current_work_area_)
1420 d.current_work_area_->bufferView().buffer().setGuiDelegate(0);
1424 void GuiView::connectBufferView(BufferView & bv)
1426 bv.setGuiDelegate(this);
1430 void GuiView::disconnectBufferView()
1432 if (d.current_work_area_)
1433 d.current_work_area_->bufferView().setGuiDelegate(0);
1437 void GuiView::errors(string const & error_type, bool from_master)
1439 BufferView const * const bv = currentBufferView();
1443 #if EXPORT_in_THREAD
1444 // We are called with from_master == false by default, so we
1445 // have to figure out whether that is the case or not.
1446 ErrorList & el = bv->buffer().errorList(error_type);
1448 el = bv->buffer().masterBuffer()->errorList(error_type);
1452 ErrorList const & el = from_master ?
1453 bv->buffer().masterBuffer()->errorList(error_type) :
1454 bv->buffer().errorList(error_type);
1460 string data = error_type;
1462 data = "from_master|" + error_type;
1463 showDialog("errorlist", data);
1467 void GuiView::updateTocItem(string const & type, DocIterator const & dit)
1469 d.toc_models_.updateItem(toqstr(type), dit);
1473 void GuiView::structureChanged()
1475 d.toc_models_.reset(documentBufferView());
1476 // Navigator needs more than a simple update in this case. It needs to be
1478 updateDialog("toc", "");
1482 void GuiView::updateDialog(string const & name, string const & data)
1484 if (!isDialogVisible(name))
1487 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
1488 if (it == d.dialogs_.end())
1491 Dialog * const dialog = it->second.get();
1492 if (dialog->isVisibleView())
1493 dialog->initialiseParams(data);
1497 BufferView * GuiView::documentBufferView()
1499 return currentMainWorkArea()
1500 ? ¤tMainWorkArea()->bufferView()
1505 BufferView const * GuiView::documentBufferView() const
1507 return currentMainWorkArea()
1508 ? ¤tMainWorkArea()->bufferView()
1513 BufferView * GuiView::currentBufferView()
1515 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1519 BufferView const * GuiView::currentBufferView() const
1521 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1525 docstring GuiView::GuiViewPrivate::autosaveAndDestroy(
1526 Buffer const * orig, Buffer * clone)
1528 bool const success = clone->autoSave();
1530 busyBuffers.remove(orig);
1532 ? _("Automatic save done.")
1533 : _("Automatic save failed!");
1537 void GuiView::autoSave()
1539 LYXERR(Debug::INFO, "Running autoSave()");
1541 Buffer * buffer = documentBufferView()
1542 ? &documentBufferView()->buffer() : 0;
1544 resetAutosaveTimers();
1548 GuiViewPrivate::busyBuffers.insert(buffer);
1549 QFuture<docstring> f = QtConcurrent::run(GuiViewPrivate::autosaveAndDestroy,
1550 buffer, buffer->cloneBufferOnly());
1551 d.autosave_watcher_.setFuture(f);
1552 resetAutosaveTimers();
1556 void GuiView::resetAutosaveTimers()
1559 d.autosave_timeout_.restart();
1563 bool GuiView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1566 Buffer * buf = currentBufferView()
1567 ? ¤tBufferView()->buffer() : 0;
1568 Buffer * doc_buffer = documentBufferView()
1569 ? &(documentBufferView()->buffer()) : 0;
1571 // Check whether we need a buffer
1572 if (!lyxaction.funcHasFlag(cmd.action(), LyXAction::NoBuffer) && !buf) {
1573 // no, exit directly
1574 flag.message(from_utf8(N_("Command not allowed with"
1575 "out any document open")));
1576 flag.setEnabled(false);
1580 if (cmd.origin() == FuncRequest::TOC) {
1581 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
1582 if (!toc || !toc->getStatus(documentBufferView()->cursor(), cmd, flag))
1583 flag.setEnabled(false);
1587 switch(cmd.action()) {
1588 case LFUN_BUFFER_IMPORT:
1591 case LFUN_MASTER_BUFFER_UPDATE:
1592 case LFUN_MASTER_BUFFER_VIEW:
1593 enable = doc_buffer && doc_buffer->parent() != 0
1594 && !d.processing_thread_watcher_.isRunning();
1597 case LFUN_BUFFER_UPDATE:
1598 case LFUN_BUFFER_VIEW: {
1599 if (!doc_buffer || d.processing_thread_watcher_.isRunning()) {
1603 string format = to_utf8(cmd.argument());
1604 if (cmd.argument().empty())
1605 format = doc_buffer->params().getDefaultOutputFormat();
1606 enable = doc_buffer->params().isExportableFormat(format);
1610 case LFUN_BUFFER_RELOAD:
1611 enable = doc_buffer && !doc_buffer->isUnnamed()
1612 && doc_buffer->fileName().exists()
1613 && (!doc_buffer->isClean()
1614 || doc_buffer->isExternallyModified(Buffer::timestamp_method));
1617 case LFUN_BUFFER_CHILD_OPEN:
1618 enable = doc_buffer;
1621 case LFUN_BUFFER_WRITE:
1622 enable = doc_buffer && (doc_buffer->isUnnamed() || !doc_buffer->isClean());
1625 //FIXME: This LFUN should be moved to GuiApplication.
1626 case LFUN_BUFFER_WRITE_ALL: {
1627 // We enable the command only if there are some modified buffers
1628 Buffer * first = theBufferList().first();
1633 // We cannot use a for loop as the buffer list is a cycle.
1635 if (!b->isClean()) {
1639 b = theBufferList().next(b);
1640 } while (b != first);
1644 case LFUN_BUFFER_WRITE_AS:
1645 case LFUN_BUFFER_EXPORT_AS:
1646 enable = doc_buffer;
1649 case LFUN_BUFFER_CLOSE:
1650 case LFUN_VIEW_CLOSE:
1651 enable = doc_buffer;
1654 case LFUN_BUFFER_CLOSE_ALL:
1655 enable = theBufferList().last() != theBufferList().first();
1658 case LFUN_VIEW_SPLIT:
1659 if (cmd.getArg(0) == "vertical")
1660 enable = doc_buffer && (d.splitter_->count() == 1 ||
1661 d.splitter_->orientation() == Qt::Vertical);
1663 enable = doc_buffer && (d.splitter_->count() == 1 ||
1664 d.splitter_->orientation() == Qt::Horizontal);
1667 case LFUN_TAB_GROUP_CLOSE:
1668 enable = d.tabWorkAreaCount() > 1;
1671 case LFUN_TOOLBAR_TOGGLE: {
1672 string const name = cmd.getArg(0);
1673 if (GuiToolbar * t = toolbar(name))
1674 flag.setOnOff(t->isVisible());
1677 docstring const msg =
1678 bformat(_("Unknown toolbar \"%1$s\""), from_utf8(name));
1684 case LFUN_DROP_LAYOUTS_CHOICE:
1688 case LFUN_UI_TOGGLE:
1689 flag.setOnOff(isFullScreen());
1692 case LFUN_DIALOG_DISCONNECT_INSET:
1695 case LFUN_DIALOG_HIDE:
1696 // FIXME: should we check if the dialog is shown?
1699 case LFUN_DIALOG_TOGGLE:
1700 flag.setOnOff(isDialogVisible(cmd.getArg(0)));
1701 // fall through to set "enable"
1702 case LFUN_DIALOG_SHOW: {
1703 string const name = cmd.getArg(0);
1705 enable = name == "aboutlyx"
1706 || name == "file" //FIXME: should be removed.
1708 || name == "texinfo"
1709 || name == "progress"
1710 || name == "compare";
1711 else if (name == "print")
1712 enable = doc_buffer->params().isExportable("dvi")
1713 && lyxrc.print_command != "none";
1714 else if (name == "character" || name == "symbols") {
1715 if (!buf || buf->isReadonly())
1718 Cursor const & cur = currentBufferView()->cursor();
1719 enable = !(cur.inTexted() && cur.paragraph().isPassThru());
1722 else if (name == "latexlog")
1723 enable = FileName(doc_buffer->logName()).isReadableFile();
1724 else if (name == "spellchecker")
1725 enable = theSpellChecker()
1726 && !doc_buffer->isReadonly()
1727 && !doc_buffer->text().empty();
1728 else if (name == "vclog")
1729 enable = doc_buffer->lyxvc().inUse();
1733 case LFUN_DIALOG_UPDATE: {
1734 string const name = cmd.getArg(0);
1736 enable = name == "prefs";
1740 case LFUN_COMMAND_EXECUTE:
1742 case LFUN_MENU_OPEN:
1743 // Nothing to check.
1746 case LFUN_COMPLETION_INLINE:
1747 if (!d.current_work_area_
1748 || !d.current_work_area_->completer().inlinePossible(
1749 currentBufferView()->cursor()))
1753 case LFUN_COMPLETION_POPUP:
1754 if (!d.current_work_area_
1755 || !d.current_work_area_->completer().popupPossible(
1756 currentBufferView()->cursor()))
1760 case LFUN_COMPLETION_COMPLETE:
1761 if (!d.current_work_area_
1762 || !d.current_work_area_->completer().inlinePossible(
1763 currentBufferView()->cursor()))
1767 case LFUN_COMPLETION_ACCEPT:
1768 if (!d.current_work_area_
1769 || (!d.current_work_area_->completer().popupVisible()
1770 && !d.current_work_area_->completer().inlineVisible()
1771 && !d.current_work_area_->completer().completionAvailable()))
1775 case LFUN_COMPLETION_CANCEL:
1776 if (!d.current_work_area_
1777 || (!d.current_work_area_->completer().popupVisible()
1778 && !d.current_work_area_->completer().inlineVisible()))
1782 case LFUN_BUFFER_ZOOM_OUT:
1783 enable = doc_buffer && lyxrc.zoom > 10;
1786 case LFUN_BUFFER_ZOOM_IN:
1787 enable = doc_buffer;
1790 case LFUN_BUFFER_NEXT:
1791 case LFUN_BUFFER_PREVIOUS:
1792 // FIXME: should we check is there is an previous or next buffer?
1794 case LFUN_BUFFER_SWITCH:
1795 // toggle on the current buffer, but do not toggle off
1796 // the other ones (is that a good idea?)
1798 && to_utf8(cmd.argument()) == doc_buffer->absFileName())
1799 flag.setOnOff(true);
1802 case LFUN_VC_REGISTER:
1803 enable = doc_buffer && !doc_buffer->lyxvc().inUse();
1805 case LFUN_VC_CHECK_IN:
1806 enable = doc_buffer && doc_buffer->lyxvc().checkInEnabled();
1808 case LFUN_VC_CHECK_OUT:
1809 enable = doc_buffer && doc_buffer->lyxvc().checkOutEnabled();
1811 case LFUN_VC_LOCKING_TOGGLE:
1812 enable = doc_buffer && !doc_buffer->isReadonly()
1813 && doc_buffer->lyxvc().lockingToggleEnabled();
1814 flag.setOnOff(enable && doc_buffer->lyxvc().locking());
1816 case LFUN_VC_REVERT:
1817 enable = doc_buffer && doc_buffer->lyxvc().inUse() && !doc_buffer->isReadonly();
1819 case LFUN_VC_UNDO_LAST:
1820 enable = doc_buffer && doc_buffer->lyxvc().undoLastEnabled();
1822 case LFUN_VC_REPO_UPDATE:
1823 enable = doc_buffer && doc_buffer->lyxvc().repoUpdateEnabled();
1825 case LFUN_VC_COMMAND: {
1826 if (cmd.argument().empty())
1828 if (!doc_buffer && contains(cmd.getArg(0), 'D'))
1832 case LFUN_VC_COMPARE:
1833 enable = doc_buffer && doc_buffer->lyxvc().prepareFileRevisionEnabled();
1836 case LFUN_SERVER_GOTO_FILE_ROW:
1838 case LFUN_FORWARD_SEARCH:
1839 enable = !(lyxrc.forward_search_dvi.empty() && lyxrc.forward_search_pdf.empty());
1842 case LFUN_FILE_INSERT_PLAINTEXT:
1843 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
1844 enable = documentBufferView() && documentBufferView()->cursor().inTexted();
1852 flag.setEnabled(false);
1858 static FileName selectTemplateFile()
1860 FileDialog dlg(qt_("Select template file"));
1861 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1862 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
1864 FileDialog::Result result = dlg.open(toqstr(lyxrc.template_path),
1865 QStringList(qt_("LyX Documents (*.lyx)")));
1867 if (result.first == FileDialog::Later)
1869 if (result.second.isEmpty())
1871 return FileName(fromqstr(result.second));
1875 Buffer * GuiView::loadDocument(FileName const & filename, bool tolastfiles)
1879 Buffer * newBuffer = 0;
1881 newBuffer = checkAndLoadLyXFile(filename);
1882 } catch (ExceptionMessage const & e) {
1889 message(_("Document not loaded."));
1893 setBuffer(newBuffer);
1894 newBuffer->errors("Parse");
1897 theSession().lastFiles().add(filename);
1903 void GuiView::openDocument(string const & fname)
1905 string initpath = lyxrc.document_path;
1907 if (documentBufferView()) {
1908 string const trypath = documentBufferView()->buffer().filePath();
1909 // If directory is writeable, use this as default.
1910 if (FileName(trypath).isDirWritable())
1916 if (fname.empty()) {
1917 FileDialog dlg(qt_("Select document to open"), LFUN_FILE_OPEN);
1918 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1919 dlg.setButton2(qt_("Examples|#E#e"),
1920 toqstr(addPath(package().system_support().absFileName(), "examples")));
1922 QStringList filter(qt_("LyX Documents (*.lyx)"));
1923 filter << qt_("LyX-1.3.x Documents (*.lyx13)")
1924 << qt_("LyX-1.4.x Documents (*.lyx14)")
1925 << qt_("LyX-1.5.x Documents (*.lyx15)")
1926 << qt_("LyX-1.6.x Documents (*.lyx16)");
1927 FileDialog::Result result =
1928 dlg.open(toqstr(initpath), filter);
1930 if (result.first == FileDialog::Later)
1933 filename = fromqstr(result.second);
1935 // check selected filename
1936 if (filename.empty()) {
1937 message(_("Canceled."));
1943 // get absolute path of file and add ".lyx" to the filename if
1945 FileName const fullname =
1946 fileSearch(string(), filename, "lyx", support::may_not_exist);
1947 if (!fullname.empty())
1948 filename = fullname.absFileName();
1950 if (!fullname.onlyPath().isDirectory()) {
1951 Alert::warning(_("Invalid filename"),
1952 bformat(_("The directory in the given path\n%1$s\ndoes not exist."),
1953 from_utf8(fullname.absFileName())));
1957 // if the file doesn't exist and isn't already open (bug 6645),
1958 // let the user create one
1959 if (!fullname.exists() && !theBufferList().exists(fullname) &&
1960 !LyXVC::file_not_found_hook(fullname)) {
1961 // the user specifically chose this name. Believe him.
1962 Buffer * const b = newFile(filename, string(), true);
1968 docstring const disp_fn = makeDisplayPath(filename);
1969 message(bformat(_("Opening document %1$s..."), disp_fn));
1972 Buffer * buf = loadDocument(fullname);
1974 str2 = bformat(_("Document %1$s opened."), disp_fn);
1975 if (buf->lyxvc().inUse())
1976 str2 += " " + from_utf8(buf->lyxvc().versionString()) +
1977 " " + _("Version control detected.");
1979 str2 = bformat(_("Could not open document %1$s"), disp_fn);
1984 // FIXME: clean that
1985 static bool import(GuiView * lv, FileName const & filename,
1986 string const & format, ErrorList & errorList)
1988 FileName const lyxfile(support::changeExtension(filename.absFileName(), ".lyx"));
1990 string loader_format;
1991 vector<string> loaders = theConverters().loaders();
1992 if (find(loaders.begin(), loaders.end(), format) == loaders.end()) {
1993 vector<string>::const_iterator it = loaders.begin();
1994 vector<string>::const_iterator en = loaders.end();
1995 for (; it != en; ++it) {
1996 if (!theConverters().isReachable(format, *it))
1999 string const tofile =
2000 support::changeExtension(filename.absFileName(),
2001 formats.extension(*it));
2002 if (!theConverters().convert(0, filename, FileName(tofile),
2003 filename, format, *it, errorList))
2005 loader_format = *it;
2008 if (loader_format.empty()) {
2009 frontend::Alert::error(_("Couldn't import file"),
2010 bformat(_("No information for importing the format %1$s."),
2011 formats.prettyName(format)));
2015 loader_format = format;
2017 if (loader_format == "lyx") {
2018 Buffer * buf = lv->loadDocument(lyxfile);
2022 Buffer * const b = newFile(lyxfile.absFileName(), string(), true);
2026 bool as_paragraphs = loader_format == "textparagraph";
2027 string filename2 = (loader_format == format) ? filename.absFileName()
2028 : support::changeExtension(filename.absFileName(),
2029 formats.extension(loader_format));
2030 lv->currentBufferView()->insertPlaintextFile(FileName(filename2),
2032 guiApp->setCurrentView(lv);
2033 lyx::dispatch(FuncRequest(LFUN_MARK_OFF));
2040 void GuiView::importDocument(string const & argument)
2043 string filename = split(argument, format, ' ');
2045 LYXERR(Debug::INFO, format << " file: " << filename);
2047 // need user interaction
2048 if (filename.empty()) {
2049 string initpath = lyxrc.document_path;
2050 if (documentBufferView()) {
2051 string const trypath = documentBufferView()->buffer().filePath();
2052 // If directory is writeable, use this as default.
2053 if (FileName(trypath).isDirWritable())
2057 docstring const text = bformat(_("Select %1$s file to import"),
2058 formats.prettyName(format));
2060 FileDialog dlg(toqstr(text), LFUN_BUFFER_IMPORT);
2061 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2062 dlg.setButton2(qt_("Examples|#E#e"),
2063 toqstr(addPath(package().system_support().absFileName(), "examples")));
2065 docstring filter = formats.prettyName(format);
2068 filter += from_utf8(formats.extensions(format));
2071 FileDialog::Result result =
2072 dlg.open(toqstr(initpath), fileFilters(toqstr(filter)));
2074 if (result.first == FileDialog::Later)
2077 filename = fromqstr(result.second);
2079 // check selected filename
2080 if (filename.empty())
2081 message(_("Canceled."));
2084 if (filename.empty())
2087 // get absolute path of file
2088 FileName const fullname(support::makeAbsPath(filename));
2090 FileName const lyxfile(support::changeExtension(fullname.absFileName(), ".lyx"));
2092 // Check if the document already is open
2093 Buffer * buf = theBufferList().getBuffer(lyxfile);
2096 if (!closeBuffer()) {
2097 message(_("Canceled."));
2102 docstring const displaypath = makeDisplayPath(lyxfile.absFileName(), 30);
2104 // if the file exists already, and we didn't do
2105 // -i lyx thefile.lyx, warn
2106 if (lyxfile.exists() && fullname != lyxfile) {
2108 docstring text = bformat(_("The document %1$s already exists.\n\n"
2109 "Do you want to overwrite that document?"), displaypath);
2110 int const ret = Alert::prompt(_("Overwrite document?"),
2111 text, 0, 1, _("&Overwrite"), _("&Cancel"));
2114 message(_("Canceled."));
2119 message(bformat(_("Importing %1$s..."), displaypath));
2120 ErrorList errorList;
2121 if (import(this, fullname, format, errorList))
2122 message(_("imported."));
2124 message(_("file not imported!"));
2126 // FIXME (Abdel 12/08/06): Is there a need to display the error list here?
2130 void GuiView::newDocument(string const & filename, bool from_template)
2132 FileName initpath(lyxrc.document_path);
2133 if (documentBufferView()) {
2134 FileName const trypath(documentBufferView()->buffer().filePath());
2135 // If directory is writeable, use this as default.
2136 if (trypath.isDirWritable())
2140 string templatefile;
2141 if (from_template) {
2142 templatefile = selectTemplateFile().absFileName();
2143 if (templatefile.empty())
2148 if (filename.empty())
2149 b = newUnnamedFile(initpath, to_utf8(_("newfile")), templatefile);
2151 b = newFile(filename, templatefile, true);
2156 // If no new document could be created, it is unsure
2157 // whether there is a valid BufferView.
2158 if (currentBufferView())
2159 // Ensure the cursor is correctly positioned on screen.
2160 currentBufferView()->showCursor();
2164 void GuiView::insertLyXFile(docstring const & fname)
2166 BufferView * bv = documentBufferView();
2171 FileName filename(to_utf8(fname));
2172 if (filename.empty()) {
2173 // Launch a file browser
2175 string initpath = lyxrc.document_path;
2176 string const trypath = bv->buffer().filePath();
2177 // If directory is writeable, use this as default.
2178 if (FileName(trypath).isDirWritable())
2182 FileDialog dlg(qt_("Select LyX document to insert"), LFUN_FILE_INSERT);
2183 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2184 dlg.setButton2(qt_("Examples|#E#e"),
2185 toqstr(addPath(package().system_support().absFileName(),
2188 FileDialog::Result result = dlg.open(toqstr(initpath),
2189 QStringList(qt_("LyX Documents (*.lyx)")));
2191 if (result.first == FileDialog::Later)
2195 filename.set(fromqstr(result.second));
2197 // check selected filename
2198 if (filename.empty()) {
2199 // emit message signal.
2200 message(_("Canceled."));
2205 bv->insertLyXFile(filename);
2206 bv->buffer().errors("Parse");
2210 bool GuiView::renameBuffer(Buffer & b, docstring const & newname)
2212 FileName fname = b.fileName();
2213 FileName const oldname = fname;
2215 if (!newname.empty()) {
2217 fname = support::makeAbsPath(to_utf8(newname), oldname.onlyPath().absFileName());
2219 // Switch to this Buffer.
2222 // No argument? Ask user through dialog.
2224 FileDialog dlg(qt_("Choose a filename to save document as"),
2225 LFUN_BUFFER_WRITE_AS);
2226 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2227 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
2229 if (!isLyXFileName(fname.absFileName()))
2230 fname.changeExtension(".lyx");
2232 FileDialog::Result result =
2233 dlg.save(toqstr(fname.onlyPath().absFileName()),
2234 QStringList(qt_("LyX Documents (*.lyx)")),
2235 toqstr(fname.onlyFileName()));
2237 if (result.first == FileDialog::Later)
2240 fname.set(fromqstr(result.second));
2245 if (!isLyXFileName(fname.absFileName()))
2246 fname.changeExtension(".lyx");
2249 // fname is now the new Buffer location.
2251 // if there is already a Buffer open with this name, we do not want
2252 // to have another one. (the second test makes sure we're not just
2253 // trying to overwrite ourselves, which is fine.)
2254 if (theBufferList().exists(fname) && fname != oldname
2255 && theBufferList().getBuffer(fname) != &b) {
2256 docstring const text =
2257 bformat(_("The file\n%1$s\nis already open in your current session.\n"
2258 "Please close it before attempting to overwrite it.\n"
2259 "Do you want to choose a new filename?"),
2260 from_utf8(fname.absFileName()));
2261 int const ret = Alert::prompt(_("Chosen File Already Open"),
2262 text, 0, 1, _("&Rename"), _("&Cancel"));
2264 case 0: return renameBuffer(b, docstring());
2265 case 1: return false;
2270 if (FileName(fname).exists()) {
2271 docstring const file = makeDisplayPath(fname.absFileName(), 30);
2272 docstring const text = bformat(_("The document %1$s already "
2273 "exists.\n\nDo you want to "
2274 "overwrite that document?"),
2276 int const ret = Alert::prompt(_("Overwrite document?"),
2277 text, 0, 2, _("&Overwrite"), _("&Rename"), _("&Cancel"));
2280 case 1: return renameBuffer(b, docstring());
2281 case 2: return false;
2285 bool const saved = saveBuffer(b, fname);
2292 struct PrettyNameComparator
2294 bool operator()(Format const *first, Format const *second) const {
2295 return compare_ascii_no_case(first->prettyname(), second->prettyname()) <= 0;
2300 bool GuiView::exportBufferAs(Buffer & b)
2302 FileName fname = b.fileName();
2304 FileDialog dlg(qt_("Choose a filename to export the document as"));
2305 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2308 types << "Any supported format (*.*)";
2309 Formats::const_iterator it = formats.begin();
2310 vector<Format const *> export_formats;
2311 for (; it != formats.end(); ++it)
2312 if (it->documentFormat() && it->inExportMenu())
2313 export_formats.push_back(&(*it));
2314 PrettyNameComparator cmp;
2315 sort(export_formats.begin(), export_formats.end(), cmp);
2316 vector<Format const *>::const_iterator fit = export_formats.begin();
2317 for (; fit != export_formats.end(); ++fit)
2318 types << toqstr((*fit)->prettyname() + " (*." + (*fit)->extension() + ")");
2320 FileDialog::Result result =
2321 dlg.save(toqstr(fname.onlyPath().absFileName()),
2323 toqstr(fname.onlyFileName()),
2325 if (result.first != FileDialog::Chosen)
2328 string s = fromqstr(filter);
2329 size_t pos = s.find(" (*.");
2330 LASSERT(pos != string::npos, /**/);
2331 string fmt_prettyname = s.substr(0, pos);
2333 fname.set(fromqstr(result.second));
2334 if (fmt_prettyname == "Any supported format")
2335 fmt_name = formats.getFormatFromExtension(fname.extension());
2337 fmt_name = formats.getFormatFromPrettyName(fmt_prettyname);
2338 LYXERR(Debug::FILES, "fmt_prettyname=" << fmt_prettyname
2339 << ", fmt_name=" << fmt_name << ", fname=" << fname.absFileName());
2341 if (fmt_name.empty() || fname.empty())
2344 // fname is now the new Buffer location.
2345 if (FileName(fname).exists()) {
2346 docstring const file = makeDisplayPath(fname.absFileName(), 30);
2347 docstring text = bformat(_("The document %1$s already "
2348 "exists.\n\nDo you want to "
2349 "overwrite that document?"),
2351 int const ret = Alert::prompt(_("Overwrite document?"),
2352 text, 0, 2, _("&Overwrite"), _("&Rename"), _("&Cancel"));
2355 case 1: return exportBufferAs(b);
2356 case 2: return false;
2360 FuncRequest cmd(LFUN_BUFFER_EXPORT, fmt_name + " " + fname.absFileName());
2363 return dr.dispatched();
2367 bool GuiView::saveBuffer(Buffer & b) {
2368 return saveBuffer(b, FileName());
2372 bool GuiView::saveBuffer(Buffer & b, FileName const & fn)
2374 if (workArea(b) && workArea(b)->inDialogMode())
2377 if (fn.empty() && b.isUnnamed())
2378 return renameBuffer(b, docstring());
2384 success = b.saveAs(fn);
2387 theSession().lastFiles().add(b.fileName());
2391 // Switch to this Buffer.
2394 // FIXME: we don't tell the user *WHY* the save failed !!
2395 docstring const file = makeDisplayPath(b.absFileName(), 30);
2396 docstring text = bformat(_("The document %1$s could not be saved.\n\n"
2397 "Do you want to rename the document and "
2398 "try again?"), file);
2399 int const ret = Alert::prompt(_("Rename and save?"),
2400 text, 0, 2, _("&Rename"), _("&Retry"), _("&Cancel"));
2403 if (!renameBuffer(b, docstring()))
2412 return saveBuffer(b);
2416 bool GuiView::hideWorkArea(GuiWorkArea * wa)
2418 return closeWorkArea(wa, false);
2422 // We only want to close the buffer if it is not visible in other workareas
2423 // of the same view, nor in other views, and if this is not a child
2424 bool GuiView::closeWorkArea(GuiWorkArea * wa)
2426 Buffer & buf = wa->bufferView().buffer();
2428 bool last_wa = d.countWorkAreasOf(buf) == 1
2429 && !inOtherView(buf) && !buf.parent();
2431 bool close_buffer = last_wa;
2434 if (lyxrc.close_buffer_with_last_view == "yes")
2436 else if (lyxrc.close_buffer_with_last_view == "no")
2437 close_buffer = false;
2440 if (buf.isUnnamed())
2441 file = from_utf8(buf.fileName().onlyFileName());
2443 file = buf.fileName().displayName(30);
2444 docstring const text = bformat(
2445 _("Last view on document %1$s is being closed.\n"
2446 "Would you like to close or hide the document?\n"
2448 "Hidden documents can be displayed back through\n"
2449 "the menu: View->Hidden->...\n"
2451 "To remove this question, set your preference in:\n"
2452 " Tools->Preferences->Look&Feel->UserInterface\n"
2454 int ret = Alert::prompt(_("Close or hide document?"),
2455 text, 0, 1, _("&Close"), _("&Hide"));
2456 close_buffer = (ret == 0);
2460 return closeWorkArea(wa, close_buffer);
2464 bool GuiView::closeBuffer()
2466 GuiWorkArea * wa = currentMainWorkArea();
2467 setCurrentWorkArea(wa);
2468 Buffer & buf = wa->bufferView().buffer();
2469 return wa && closeWorkArea(wa, !buf.parent());
2473 void GuiView::writeSession() const {
2474 GuiWorkArea const * active_wa = currentMainWorkArea();
2475 for (int i = 0; i < d.splitter_->count(); ++i) {
2476 TabWorkArea * twa = d.tabWorkArea(i);
2477 for (int j = 0; j < twa->count(); ++j) {
2478 GuiWorkArea * wa = static_cast<GuiWorkArea *>(twa->widget(j));
2479 Buffer & buf = wa->bufferView().buffer();
2480 theSession().lastOpened().add(buf.fileName(), wa == active_wa);
2486 bool GuiView::closeBufferAll()
2488 // Close the workareas in all other views
2489 QList<int> const ids = guiApp->viewIds();
2490 for (int i = 0; i != ids.size(); ++i) {
2491 if (id_ != ids[i] && !guiApp->view(ids[i]).closeWorkAreaAll())
2495 // Close our own workareas
2496 if (!closeWorkAreaAll())
2499 // Now close the hidden buffers. We prevent hidden buffers from being
2500 // dirty, so we can just close them.
2501 theBufferList().closeAll();
2506 bool GuiView::closeWorkAreaAll()
2508 setCurrentWorkArea(currentMainWorkArea());
2510 // We might be in a situation that there is still a tabWorkArea, but
2511 // there are no tabs anymore. This can happen when we get here after a
2512 // TabWorkArea::lastWorkAreaRemoved() signal. Therefore we count how
2513 // many TabWorkArea's have no documents anymore.
2516 // We have to call count() each time, because it can happen that
2517 // more than one splitter will disappear in one iteration (bug 5998).
2518 for (; d.splitter_->count() > empty_twa; ) {
2519 TabWorkArea * twa = d.tabWorkArea(empty_twa);
2521 if (twa->count() == 0)
2524 setCurrentWorkArea(twa->currentWorkArea());
2525 if (!closeTabWorkArea(twa))
2533 bool GuiView::closeWorkArea(GuiWorkArea * wa, bool close_buffer)
2538 Buffer & buf = wa->bufferView().buffer();
2540 if (close_buffer && GuiViewPrivate::busyBuffers.contains(&buf)) {
2541 Alert::warning(_("Close document"),
2542 _("Document could not be closed because it is being processed by LyX."));
2547 return closeBuffer(buf);
2549 if (!inMultiTabs(wa))
2550 if (!saveBufferIfNeeded(buf, true))
2558 bool GuiView::closeBuffer(Buffer & buf)
2560 // If we are in a close_event all children will be closed in some time,
2561 // so no need to do it here. This will ensure that the children end up
2562 // in the session file in the correct order. If we close the master
2563 // buffer, we can close or release the child buffers here too.
2564 bool success = true;
2566 ListOfBuffers clist = buf.getChildren();
2567 ListOfBuffers::const_iterator it = clist.begin();
2568 ListOfBuffers::const_iterator const bend = clist.end();
2569 for (; it != bend; ++it) {
2570 // If a child is dirty, do not close
2571 // without user intervention
2572 //FIXME: should we look in other tabworkareas?
2573 Buffer * child_buf = *it;
2574 GuiWorkArea * child_wa = workArea(*child_buf);
2576 if (!closeWorkArea(child_wa, true)) {
2581 theBufferList().releaseChild(&buf, child_buf);
2585 // goto bookmark to update bookmark pit.
2586 //FIXME: we should update only the bookmarks related to this buffer!
2587 LYXERR(Debug::DEBUG, "GuiView::closeBuffer()");
2588 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
2589 guiApp->gotoBookmark(i+1, false, false);
2591 if (saveBufferIfNeeded(buf, false)) {
2592 buf.removeAutosaveFile();
2593 theBufferList().release(&buf);
2597 // open all children again to avoid a crash because of dangling
2598 // pointers (bug 6603)
2604 bool GuiView::closeTabWorkArea(TabWorkArea * twa)
2606 while (twa == d.currentTabWorkArea()) {
2607 twa->setCurrentIndex(twa->count()-1);
2609 GuiWorkArea * wa = twa->currentWorkArea();
2610 Buffer & b = wa->bufferView().buffer();
2612 // We only want to close the buffer if the same buffer is not visible
2613 // in another view, and if this is not a child and if we are closing
2614 // a view (not a tabgroup).
2615 bool const close_buffer =
2616 !inOtherView(b) && !b.parent() && closing_;
2618 if (!closeWorkArea(wa, close_buffer))
2625 bool GuiView::saveBufferIfNeeded(Buffer & buf, bool hiding)
2627 if (buf.isClean() || buf.paragraphs().empty())
2630 // Switch to this Buffer.
2635 if (buf.isUnnamed())
2636 file = from_utf8(buf.fileName().onlyFileName());
2638 file = buf.fileName().displayName(30);
2640 // Bring this window to top before asking questions.
2645 if (hiding && buf.isUnnamed()) {
2646 docstring const text = bformat(_("The document %1$s has not been "
2647 "saved yet.\n\nDo you want to save "
2648 "the document?"), file);
2649 ret = Alert::prompt(_("Save new document?"),
2650 text, 0, 1, _("&Save"), _("&Cancel"));
2654 docstring const text = bformat(_("The document %1$s has unsaved changes."
2655 "\n\nDo you want to save the document or discard the changes?"), file);
2656 ret = Alert::prompt(_("Save changed document?"),
2657 text, 0, 2, _("&Save"), _("&Discard"), _("&Cancel"));
2662 if (!saveBuffer(buf))
2666 // If we crash after this we could have no autosave file
2667 // but I guess this is really improbable (Jug).
2668 // Sometimes improbable things happen:
2669 // - see bug http://www.lyx.org/trac/ticket/6587 (ps)
2670 // buf.removeAutosaveFile();
2672 // revert all changes
2683 bool GuiView::inMultiTabs(GuiWorkArea * wa)
2685 Buffer & buf = wa->bufferView().buffer();
2687 for (int i = 0; i != d.splitter_->count(); ++i) {
2688 GuiWorkArea * wa_ = d.tabWorkArea(i)->workArea(buf);
2689 if (wa_ && wa_ != wa)
2692 return inOtherView(buf);
2696 bool GuiView::inOtherView(Buffer & buf)
2698 QList<int> const ids = guiApp->viewIds();
2700 for (int i = 0; i != ids.size(); ++i) {
2704 if (guiApp->view(ids[i]).workArea(buf))
2711 void GuiView::gotoNextOrPreviousBuffer(NextOrPrevious np)
2713 if (!documentBufferView())
2716 if (TabWorkArea * twa = d.currentTabWorkArea()) {
2717 Buffer * const curbuf = &documentBufferView()->buffer();
2718 int nwa = twa->count();
2719 for (int i = 0; i < nwa; ++i) {
2720 if (&workArea(i)->bufferView().buffer() == curbuf) {
2722 if (np == NEXTBUFFER)
2723 next_index = (i == nwa - 1 ? 0 : i + 1);
2725 next_index = (i == 0 ? nwa - 1 : i - 1);
2726 setBuffer(&workArea(next_index)->bufferView().buffer());
2734 /// make sure the document is saved
2735 static bool ensureBufferClean(Buffer * buffer)
2737 LASSERT(buffer, return false);
2738 if (buffer->isClean() && !buffer->isUnnamed())
2741 docstring const file = buffer->fileName().displayName(30);
2744 if (!buffer->isUnnamed()) {
2745 text = bformat(_("The document %1$s has unsaved "
2746 "changes.\n\nDo you want to save "
2747 "the document?"), file);
2748 title = _("Save changed document?");
2751 text = bformat(_("The document %1$s has not been "
2752 "saved yet.\n\nDo you want to save "
2753 "the document?"), file);
2754 title = _("Save new document?");
2756 int const ret = Alert::prompt(title, text, 0, 1, _("&Save"), _("&Cancel"));
2759 dispatch(FuncRequest(LFUN_BUFFER_WRITE));
2761 return buffer->isClean() && !buffer->isUnnamed();
2765 bool GuiView::reloadBuffer(Buffer & buf)
2767 Buffer::ReadStatus status = buf.reload();
2768 return status == Buffer::ReadSuccess;
2772 void GuiView::checkExternallyModifiedBuffers()
2774 BufferList::iterator bit = theBufferList().begin();
2775 BufferList::iterator const bend = theBufferList().end();
2776 for (; bit != bend; ++bit) {
2777 Buffer * buf = *bit;
2778 if (buf->fileName().exists()
2779 && buf->isExternallyModified(Buffer::checksum_method)) {
2780 docstring text = bformat(_("Document \n%1$s\n has been externally modified."
2781 " Reload now? Any local changes will be lost."),
2782 from_utf8(buf->absFileName()));
2783 int const ret = Alert::prompt(_("Reload externally changed document?"),
2784 text, 0, 1, _("&Reload"), _("&Cancel"));
2792 void GuiView::dispatchVC(FuncRequest const & cmd, DispatchResult & dr)
2794 Buffer * buffer = documentBufferView()
2795 ? &(documentBufferView()->buffer()) : 0;
2797 switch (cmd.action()) {
2798 case LFUN_VC_REGISTER:
2799 if (!buffer || !ensureBufferClean(buffer))
2801 if (!buffer->lyxvc().inUse()) {
2802 if (buffer->lyxvc().registrer()) {
2803 reloadBuffer(*buffer);
2804 dr.suppressMessageUpdate();
2809 case LFUN_VC_CHECK_IN:
2810 if (!buffer || !ensureBufferClean(buffer))
2812 if (buffer->lyxvc().inUse() && !buffer->isReadonly()) {
2813 dr.setMessage(buffer->lyxvc().checkIn());
2814 if (!dr.message().empty())
2815 reloadBuffer(*buffer);
2819 case LFUN_VC_CHECK_OUT:
2820 if (!buffer || !ensureBufferClean(buffer))
2822 if (buffer->lyxvc().inUse()) {
2823 dr.setMessage(buffer->lyxvc().checkOut());
2824 reloadBuffer(*buffer);
2828 case LFUN_VC_LOCKING_TOGGLE:
2829 LASSERT(buffer, return);
2830 if (!ensureBufferClean(buffer) || buffer->isReadonly())
2832 if (buffer->lyxvc().inUse()) {
2833 string res = buffer->lyxvc().lockingToggle();
2835 frontend::Alert::error(_("Revision control error."),
2836 _("Error when setting the locking property."));
2839 reloadBuffer(*buffer);
2844 case LFUN_VC_REVERT:
2845 LASSERT(buffer, return);
2846 if (buffer->lyxvc().revert()) {
2847 reloadBuffer(*buffer);
2848 dr.suppressMessageUpdate();
2852 case LFUN_VC_UNDO_LAST:
2853 LASSERT(buffer, return);
2854 buffer->lyxvc().undoLast();
2855 reloadBuffer(*buffer);
2856 dr.suppressMessageUpdate();
2859 case LFUN_VC_REPO_UPDATE:
2860 LASSERT(buffer, return);
2861 if (ensureBufferClean(buffer)) {
2862 dr.setMessage(buffer->lyxvc().repoUpdate());
2863 checkExternallyModifiedBuffers();
2867 case LFUN_VC_COMMAND: {
2868 string flag = cmd.getArg(0);
2869 if (buffer && contains(flag, 'R') && !ensureBufferClean(buffer))
2872 if (contains(flag, 'M')) {
2873 if (!Alert::askForText(message, _("LyX VC: Log Message")))
2876 string path = cmd.getArg(1);
2877 if (contains(path, "$$p") && buffer)
2878 path = subst(path, "$$p", buffer->filePath());
2879 LYXERR(Debug::LYXVC, "Directory: " << path);
2881 if (!pp.isReadableDirectory()) {
2882 lyxerr << _("Directory is not accessible.") << endl;
2885 support::PathChanger p(pp);
2887 string command = cmd.getArg(2);
2888 if (command.empty())
2891 command = subst(command, "$$i", buffer->absFileName());
2892 command = subst(command, "$$p", buffer->filePath());
2894 command = subst(command, "$$m", to_utf8(message));
2895 LYXERR(Debug::LYXVC, "Command: " << command);
2897 one.startscript(Systemcall::Wait, command);
2901 if (contains(flag, 'I'))
2902 buffer->markDirty();
2903 if (contains(flag, 'R'))
2904 reloadBuffer(*buffer);
2909 case LFUN_VC_COMPARE: {
2911 if (cmd.argument().empty()) {
2912 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "comparehistory"));
2916 string rev1 = cmd.getArg(0);
2920 if (!buffer->lyxvc().prepareFileRevision(rev1, f1))
2923 if (isStrInt(rev1) && convert<int>(rev1) <= 0) {
2924 f2 = buffer->absFileName();
2926 string rev2 = cmd.getArg(1);
2930 if (!buffer->lyxvc().prepareFileRevision(rev2, f2))
2934 LYXERR(Debug::LYXVC, "Launching comparison for fetched revisions:\n" <<
2935 f1 << "\n" << f2 << "\n" );
2936 string par = "compare run " + quoteName(f1) + " " + quoteName(f2);
2937 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, par));
2947 void GuiView::openChildDocument(string const & fname)
2949 LASSERT(documentBufferView(), return);
2950 Buffer & buffer = documentBufferView()->buffer();
2951 FileName const filename = support::makeAbsPath(fname, buffer.filePath());
2952 documentBufferView()->saveBookmark(false);
2954 if (theBufferList().exists(filename)) {
2955 child = theBufferList().getBuffer(filename);
2958 message(bformat(_("Opening child document %1$s..."),
2959 makeDisplayPath(filename.absFileName())));
2960 child = loadDocument(filename, false);
2962 // Set the parent name of the child document.
2963 // This makes insertion of citations and references in the child work,
2964 // when the target is in the parent or another child document.
2966 child->setParent(&buffer);
2970 bool GuiView::goToFileRow(string const & argument)
2974 size_t i = argument.find_last_of(' ');
2975 if (i != string::npos) {
2976 file_name = os::internal_path(trim(argument.substr(0, i)));
2977 istringstream is(argument.substr(i + 1));
2982 if (i == string::npos) {
2983 LYXERR0("Wrong argument: " << argument);
2987 string const abstmp = package().temp_dir().absFileName();
2988 string const realtmp = package().temp_dir().realPath();
2989 // We have to use os::path_prefix_is() here, instead of
2990 // simply prefixIs(), because the file name comes from
2991 // an external application and may need case adjustment.
2992 if (os::path_prefix_is(file_name, abstmp, os::CASE_ADJUSTED)
2993 || os::path_prefix_is(file_name, realtmp, os::CASE_ADJUSTED)) {
2994 // Needed by inverse dvi search. If it is a file
2995 // in tmpdir, call the apropriated function.
2996 // If tmpdir is a symlink, we may have the real
2997 // path passed back, so we correct for that.
2998 if (!prefixIs(file_name, abstmp))
2999 file_name = subst(file_name, realtmp, abstmp);
3000 buf = theBufferList().getBufferFromTmp(file_name);
3002 // Must replace extension of the file to be .lyx
3003 // and get full path
3004 FileName const s = fileSearch(string(),
3005 support::changeExtension(file_name, ".lyx"), "lyx");
3006 // Either change buffer or load the file
3007 if (theBufferList().exists(s))
3008 buf = theBufferList().getBuffer(s);
3009 else if (s.exists()) {
3010 buf = loadDocument(s);
3015 _("File does not exist: %1$s"),
3016 makeDisplayPath(file_name)));
3022 _("No buffer for file: %1$s."),
3023 makeDisplayPath(file_name))
3028 documentBufferView()->setCursorFromRow(row);
3034 Buffer::ExportStatus GuiView::GuiViewPrivate::runAndDestroy(const T& func, Buffer const * orig, Buffer * clone, string const & format)
3036 Buffer::ExportStatus const status = func(format);
3038 // the cloning operation will have produced a clone of the entire set of
3039 // documents, starting from the master. so we must delete those.
3040 Buffer * mbuf = const_cast<Buffer *>(clone->masterBuffer());
3042 busyBuffers.remove(orig);
3047 Buffer::ExportStatus GuiView::GuiViewPrivate::compileAndDestroy(Buffer const * orig, Buffer * clone, string const & format)
3049 Buffer::ExportStatus (Buffer::* mem_func)(std::string const &, bool) const = &Buffer::doExport;
3050 return runAndDestroy(lyx::bind(mem_func, clone, _1, true), orig, clone, format);
3054 Buffer::ExportStatus GuiView::GuiViewPrivate::exportAndDestroy(Buffer const * orig, Buffer * clone, string const & format)
3056 Buffer::ExportStatus (Buffer::* mem_func)(std::string const &, bool) const = &Buffer::doExport;
3057 return runAndDestroy(lyx::bind(mem_func, clone, _1, false), orig, clone, format);
3061 Buffer::ExportStatus GuiView::GuiViewPrivate::previewAndDestroy(Buffer const * orig, Buffer * clone, string const & format)
3063 Buffer::ExportStatus (Buffer::* mem_func)(std::string const &) const = &Buffer::preview;
3064 return runAndDestroy(lyx::bind(mem_func, clone, _1), orig, clone, format);
3068 bool GuiView::GuiViewPrivate::asyncBufferProcessing(
3069 string const & argument,
3070 Buffer const * used_buffer,
3071 docstring const & msg,
3072 Buffer::ExportStatus (*asyncFunc)(Buffer const *, Buffer *, string const &),
3073 Buffer::ExportStatus (Buffer::*syncFunc)(string const &, bool) const,
3074 Buffer::ExportStatus (Buffer::*previewFunc)(string const &) const)
3079 string format = argument;
3081 format = used_buffer->params().getDefaultOutputFormat();
3082 processing_format = format;
3083 #if EXPORT_in_THREAD
3085 progress_->clearMessages();
3088 GuiViewPrivate::busyBuffers.insert(used_buffer);
3089 Buffer * cloned_buffer = used_buffer->cloneFromMaster();
3090 if (!cloned_buffer) {
3091 Alert::error(_("Export Error"),
3092 _("Error cloning the Buffer."));
3095 QFuture<Buffer::ExportStatus> f = QtConcurrent::run(
3100 setPreviewFuture(f);
3101 last_export_format = used_buffer->params().bufferFormat();
3104 // We are asynchronous, so we don't know here anything about the success
3107 Buffer::ExportStatus status;
3109 // TODO check here if it breaks exporting with Qt < 4.4
3110 status = (used_buffer->*syncFunc)(format, true);
3111 } else if (previewFunc) {
3112 status = (used_buffer->*previewFunc)(format);
3115 handleExportStatus(gv_, status, format);
3117 return (status == Buffer::ExportSuccess
3118 || status == Buffer::PreviewSuccess);
3122 void GuiView::dispatchToBufferView(FuncRequest const & cmd, DispatchResult & dr)
3124 BufferView * bv = currentBufferView();
3127 // Let the current BufferView dispatch its own actions.
3128 bv->dispatch(cmd, dr);
3129 if (dr.dispatched())
3132 // Try with the document BufferView dispatch if any.
3133 BufferView * doc_bv = documentBufferView();
3134 if (doc_bv && doc_bv != bv) {
3135 doc_bv->dispatch(cmd, dr);
3136 if (dr.dispatched())
3140 // Then let the current Cursor dispatch its own actions.
3141 bv->cursor().dispatch(cmd);
3143 // update completion. We do it here and not in
3144 // processKeySym to avoid another redraw just for a
3145 // changed inline completion
3146 if (cmd.origin() == FuncRequest::KEYBOARD) {
3147 if (cmd.action() == LFUN_SELF_INSERT
3148 || (cmd.action() == LFUN_ERT_INSERT && bv->cursor().inMathed()))
3149 updateCompletion(bv->cursor(), true, true);
3150 else if (cmd.action() == LFUN_CHAR_DELETE_BACKWARD)
3151 updateCompletion(bv->cursor(), false, true);
3153 updateCompletion(bv->cursor(), false, false);
3156 dr = bv->cursor().result();
3160 void GuiView::dispatch(FuncRequest const & cmd, DispatchResult & dr)
3162 BufferView * bv = currentBufferView();
3163 // By default we won't need any update.
3164 dr.screenUpdate(Update::None);
3165 // assume cmd will be dispatched
3166 dr.dispatched(true);
3168 Buffer * doc_buffer = documentBufferView()
3169 ? &(documentBufferView()->buffer()) : 0;
3171 if (cmd.origin() == FuncRequest::TOC) {
3172 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
3173 // FIXME: do we need to pass a DispatchResult object here?
3174 toc->doDispatch(bv->cursor(), cmd);
3178 string const argument = to_utf8(cmd.argument());
3180 switch(cmd.action()) {
3181 case LFUN_BUFFER_CHILD_OPEN:
3182 openChildDocument(to_utf8(cmd.argument()));
3185 case LFUN_BUFFER_IMPORT:
3186 importDocument(to_utf8(cmd.argument()));
3189 case LFUN_BUFFER_EXPORT: {
3192 // GCC only sees strfwd.h when building merged
3193 if (::lyx::operator==(cmd.argument(), "custom")) {
3194 dispatch(FuncRequest(LFUN_DIALOG_SHOW, "sendto"), dr);
3197 /* TODO/Review: Is it a problem to also export the children?
3198 See the update_unincluded flag */
3199 d.asyncBufferProcessing(argument,
3202 &GuiViewPrivate::exportAndDestroy,
3205 // TODO Inform user about success
3209 case LFUN_BUFFER_EXPORT_AS:
3210 LASSERT(doc_buffer, break);
3211 exportBufferAs(*doc_buffer);
3214 case LFUN_BUFFER_UPDATE: {
3215 d.asyncBufferProcessing(argument,
3218 &GuiViewPrivate::compileAndDestroy,
3223 case LFUN_BUFFER_VIEW: {
3224 d.asyncBufferProcessing(argument,
3226 _("Previewing ..."),
3227 &GuiViewPrivate::previewAndDestroy,
3232 case LFUN_MASTER_BUFFER_UPDATE: {
3233 d.asyncBufferProcessing(argument,
3234 (doc_buffer ? doc_buffer->masterBuffer() : 0),
3236 &GuiViewPrivate::compileAndDestroy,
3241 case LFUN_MASTER_BUFFER_VIEW: {
3242 d.asyncBufferProcessing(argument,
3243 (doc_buffer ? doc_buffer->masterBuffer() : 0),
3245 &GuiViewPrivate::previewAndDestroy,
3246 0, &Buffer::preview);
3249 case LFUN_BUFFER_SWITCH: {
3250 string const file_name = to_utf8(cmd.argument());
3251 if (!FileName::isAbsolute(file_name)) {
3253 dr.setMessage(_("Absolute filename expected."));
3257 Buffer * buffer = theBufferList().getBuffer(FileName(file_name));
3260 dr.setMessage(_("Document not loaded"));
3264 // Do we open or switch to the buffer in this view ?
3265 if (workArea(*buffer)
3266 || lyxrc.open_buffers_in_tabs || !documentBufferView()) {
3271 // Look for the buffer in other views
3272 QList<int> const ids = guiApp->viewIds();
3274 for (; i != ids.size(); ++i) {
3275 GuiView & gv = guiApp->view(ids[i]);
3276 if (gv.workArea(*buffer)) {
3277 gv.activateWindow();
3278 gv.setBuffer(buffer);
3283 // If necessary, open a new window as a last resort
3284 if (i == ids.size()) {
3285 lyx::dispatch(FuncRequest(LFUN_WINDOW_NEW));
3291 case LFUN_BUFFER_NEXT:
3292 gotoNextOrPreviousBuffer(NEXTBUFFER);
3295 case LFUN_BUFFER_PREVIOUS:
3296 gotoNextOrPreviousBuffer(PREVBUFFER);
3299 case LFUN_COMMAND_EXECUTE: {
3300 bool const show_it = cmd.argument() != "off";
3301 // FIXME: this is a hack, "minibuffer" should not be
3303 if (GuiToolbar * t = toolbar("minibuffer")) {
3304 t->setVisible(show_it);
3305 if (show_it && t->commandBuffer())
3306 t->commandBuffer()->setFocus();
3310 case LFUN_DROP_LAYOUTS_CHOICE:
3311 d.layout_->showPopup();
3314 case LFUN_MENU_OPEN:
3315 if (QMenu * menu = guiApp->menus().menu(toqstr(cmd.argument()), *this))
3316 menu->exec(QCursor::pos());
3319 case LFUN_FILE_INSERT:
3320 insertLyXFile(cmd.argument());
3323 case LFUN_FILE_INSERT_PLAINTEXT:
3324 case LFUN_FILE_INSERT_PLAINTEXT_PARA: {
3325 bool const as_paragraph = (cmd.action() == LFUN_FILE_INSERT_PLAINTEXT_PARA);
3326 string const fname = to_utf8(cmd.argument());
3327 if (!fname.empty() && !FileName::isAbsolute(fname)) {
3328 dr.setMessage(_("Absolute filename expected."));
3332 FileName filename(fname);
3333 if (fname.empty()) {
3334 FileDialog dlg(qt_("Select file to insert"), (as_paragraph ?
3335 LFUN_FILE_INSERT_PLAINTEXT_PARA : LFUN_FILE_INSERT_PLAINTEXT));
3337 FileDialog::Result result = dlg.open(toqstr(bv->buffer().filePath()),
3338 QStringList(qt_("All Files (*)")));
3340 if (result.first == FileDialog::Later || result.second.isEmpty()) {
3341 dr.setMessage(_("Canceled."));
3345 filename.set(fromqstr(result.second));
3349 FuncRequest const new_cmd(cmd, filename.absoluteFilePath());
3350 bv->dispatch(new_cmd, dr);
3355 case LFUN_BUFFER_RELOAD: {
3356 LASSERT(doc_buffer, break);
3359 if (!doc_buffer->isClean()) {
3360 docstring const file =
3361 makeDisplayPath(doc_buffer->absFileName(), 20);
3362 docstring text = bformat(_("Any changes will be lost. "
3363 "Are you sure you want to revert to the saved version "
3364 "of the document %1$s?"), file);
3365 ret = Alert::prompt(_("Revert to saved document?"),
3366 text, 1, 1, _("&Revert"), _("&Cancel"));
3370 doc_buffer->markClean();
3371 reloadBuffer(*doc_buffer);
3372 dr.forceBufferUpdate();
3377 case LFUN_BUFFER_WRITE:
3378 LASSERT(doc_buffer, break);
3379 saveBuffer(*doc_buffer);
3382 case LFUN_BUFFER_WRITE_AS:
3383 LASSERT(doc_buffer, break);
3384 renameBuffer(*doc_buffer, cmd.argument());
3387 case LFUN_BUFFER_WRITE_ALL: {
3388 Buffer * first = theBufferList().first();
3391 message(_("Saving all documents..."));
3392 // We cannot use a for loop as the buffer list cycles.
3395 if (!b->isClean()) {
3397 LYXERR(Debug::ACTION, "Saved " << b->absFileName());
3399 b = theBufferList().next(b);
3400 } while (b != first);
3401 dr.setMessage(_("All documents saved."));
3405 case LFUN_BUFFER_CLOSE:
3409 case LFUN_BUFFER_CLOSE_ALL:
3413 case LFUN_TOOLBAR_TOGGLE: {
3414 string const name = cmd.getArg(0);
3415 if (GuiToolbar * t = toolbar(name))
3420 case LFUN_DIALOG_UPDATE: {
3421 string const name = to_utf8(cmd.argument());
3422 if (name == "prefs" || name == "document")
3423 updateDialog(name, string());
3424 else if (name == "paragraph")
3425 lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
3426 else if (currentBufferView()) {
3427 Inset * inset = currentBufferView()->editedInset(name);
3428 // Can only update a dialog connected to an existing inset
3430 // FIXME: get rid of this indirection; GuiView ask the inset
3431 // if he is kind enough to update itself...
3432 FuncRequest fr(LFUN_INSET_DIALOG_UPDATE, cmd.argument());
3433 //FIXME: pass DispatchResult here?
3434 inset->dispatch(currentBufferView()->cursor(), fr);
3440 case LFUN_DIALOG_TOGGLE: {
3441 FuncCode const func_code = isDialogVisible(cmd.getArg(0))
3442 ? LFUN_DIALOG_HIDE : LFUN_DIALOG_SHOW;
3443 dispatch(FuncRequest(func_code, cmd.argument()), dr);
3447 case LFUN_DIALOG_DISCONNECT_INSET:
3448 disconnectDialog(to_utf8(cmd.argument()));
3451 case LFUN_DIALOG_HIDE: {
3452 guiApp->hideDialogs(to_utf8(cmd.argument()), 0);
3456 case LFUN_DIALOG_SHOW: {
3457 string const name = cmd.getArg(0);
3458 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
3460 if (name == "character") {
3461 data = freefont2string();
3463 showDialog("character", data);
3464 } else if (name == "latexlog") {
3465 Buffer::LogType type;
3466 string const logfile = doc_buffer->logName(&type);
3468 case Buffer::latexlog:
3471 case Buffer::buildlog:
3475 data += Lexer::quoteString(logfile);
3476 showDialog("log", data);
3477 } else if (name == "vclog") {
3478 string const data = "vc " +
3479 Lexer::quoteString(doc_buffer->lyxvc().getLogFile());
3480 showDialog("log", data);
3481 } else if (name == "symbols") {
3482 data = bv->cursor().getEncoding()->name();
3484 showDialog("symbols", data);
3486 } else if (name == "prefs" && isFullScreen()) {
3487 lfunUiToggle("fullscreen");
3488 showDialog("prefs", data);
3490 showDialog(name, data);
3495 dr.setMessage(cmd.argument());
3498 case LFUN_UI_TOGGLE: {
3499 string arg = cmd.getArg(0);
3500 if (!lfunUiToggle(arg)) {
3501 docstring const msg = "ui-toggle " + _("%1$s unknown command!");
3502 dr.setMessage(bformat(msg, from_utf8(arg)));
3504 // Make sure the keyboard focus stays in the work area.
3509 case LFUN_VIEW_SPLIT: {
3510 LASSERT(doc_buffer, break);
3511 string const orientation = cmd.getArg(0);
3512 d.splitter_->setOrientation(orientation == "vertical"
3513 ? Qt::Vertical : Qt::Horizontal);
3514 TabWorkArea * twa = addTabWorkArea();
3515 GuiWorkArea * wa = twa->addWorkArea(*doc_buffer, *this);
3516 setCurrentWorkArea(wa);
3519 case LFUN_TAB_GROUP_CLOSE:
3520 if (TabWorkArea * twa = d.currentTabWorkArea()) {
3521 closeTabWorkArea(twa);
3522 d.current_work_area_ = 0;
3523 twa = d.currentTabWorkArea();
3524 // Switch to the next GuiWorkArea in the found TabWorkArea.
3526 // Make sure the work area is up to date.
3527 setCurrentWorkArea(twa->currentWorkArea());
3529 setCurrentWorkArea(0);
3534 case LFUN_VIEW_CLOSE:
3535 if (TabWorkArea * twa = d.currentTabWorkArea()) {
3536 closeWorkArea(twa->currentWorkArea());
3537 d.current_work_area_ = 0;
3538 twa = d.currentTabWorkArea();
3539 // Switch to the next GuiWorkArea in the found TabWorkArea.
3541 // Make sure the work area is up to date.
3542 setCurrentWorkArea(twa->currentWorkArea());
3544 setCurrentWorkArea(0);
3549 case LFUN_COMPLETION_INLINE:
3550 if (d.current_work_area_)
3551 d.current_work_area_->completer().showInline();
3554 case LFUN_COMPLETION_POPUP:
3555 if (d.current_work_area_)
3556 d.current_work_area_->completer().showPopup();
3560 case LFUN_COMPLETION_COMPLETE:
3561 if (d.current_work_area_)
3562 d.current_work_area_->completer().tab();
3565 case LFUN_COMPLETION_CANCEL:
3566 if (d.current_work_area_) {
3567 if (d.current_work_area_->completer().popupVisible())
3568 d.current_work_area_->completer().hidePopup();
3570 d.current_work_area_->completer().hideInline();
3574 case LFUN_COMPLETION_ACCEPT:
3575 if (d.current_work_area_)
3576 d.current_work_area_->completer().activate();
3579 case LFUN_BUFFER_ZOOM_IN:
3580 case LFUN_BUFFER_ZOOM_OUT:
3581 if (cmd.argument().empty()) {
3582 if (cmd.action() == LFUN_BUFFER_ZOOM_IN)
3587 lyxrc.zoom += convert<int>(cmd.argument());
3589 if (lyxrc.zoom < 10)
3592 // The global QPixmapCache is used in GuiPainter to cache text
3593 // painting so we must reset it.
3594 QPixmapCache::clear();
3595 guiApp->fontLoader().update();
3596 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
3599 case LFUN_VC_REGISTER:
3600 case LFUN_VC_CHECK_IN:
3601 case LFUN_VC_CHECK_OUT:
3602 case LFUN_VC_REPO_UPDATE:
3603 case LFUN_VC_LOCKING_TOGGLE:
3604 case LFUN_VC_REVERT:
3605 case LFUN_VC_UNDO_LAST:
3606 case LFUN_VC_COMMAND:
3607 case LFUN_VC_COMPARE:
3608 dispatchVC(cmd, dr);
3611 case LFUN_SERVER_GOTO_FILE_ROW:
3612 goToFileRow(to_utf8(cmd.argument()));
3615 case LFUN_FORWARD_SEARCH: {
3616 Buffer const * doc_master = doc_buffer->masterBuffer();
3617 FileName const path(doc_master->temppath());
3618 string const texname = doc_master->isChild(doc_buffer)
3619 ? DocFileName(changeExtension(
3620 doc_buffer->absFileName(),
3621 "tex")).mangledFileName()
3622 : doc_buffer->latexName();
3623 string const fulltexname =
3624 support::makeAbsPath(texname, doc_master->temppath()).absFileName();
3625 string const mastername =
3626 removeExtension(doc_master->latexName());
3627 FileName const dviname(addName(path.absFileName(),
3628 addExtension(mastername, "dvi")));
3629 FileName const pdfname(addName(path.absFileName(),
3630 addExtension(mastername, "pdf")));
3631 bool const have_dvi = dviname.exists();
3632 bool const have_pdf = pdfname.exists();
3633 if (!have_dvi && !have_pdf) {
3634 dr.setMessage(_("Please, preview the document first."));
3637 string outname = dviname.onlyFileName();
3638 string command = lyxrc.forward_search_dvi;
3639 if (!have_dvi || (have_pdf &&
3640 pdfname.lastModified() > dviname.lastModified())) {
3641 outname = pdfname.onlyFileName();
3642 command = lyxrc.forward_search_pdf;
3645 DocIterator tmpcur = bv->cursor();
3647 while (tmpcur.inMathed())
3649 int row = tmpcur.inMathed() ? 0 : doc_buffer->texrow().getRowFromIdPos(
3650 tmpcur.paragraph().id(), tmpcur.pos());
3651 LYXERR(Debug::ACTION, "Forward search: row:" << row
3652 << " id:" << tmpcur.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, "$$f", fulltexname);
3661 command = subst(command, "$$t", texname);
3662 command = subst(command, "$$o", outname);
3664 PathChanger p(path);
3666 one.startscript(Systemcall::DontWait, command);
3670 // The LFUN must be for one of BufferView, Buffer or Cursor;
3672 dispatchToBufferView(cmd, dr);
3676 // Part of automatic menu appearance feature.
3677 if (isFullScreen()) {
3678 if (menuBar()->isVisible() && lyxrc.full_screen_menubar)
3680 if (statusBar()->isVisible())
3681 statusBar()->hide();
3686 bool GuiView::lfunUiToggle(string const & ui_component)
3688 if (ui_component == "scrollbar") {
3689 // hide() is of no help
3690 if (d.current_work_area_->verticalScrollBarPolicy() ==
3691 Qt::ScrollBarAlwaysOff)
3693 d.current_work_area_->setVerticalScrollBarPolicy(
3694 Qt::ScrollBarAsNeeded);
3696 d.current_work_area_->setVerticalScrollBarPolicy(
3697 Qt::ScrollBarAlwaysOff);
3698 } else if (ui_component == "statusbar") {
3699 statusBar()->setVisible(!statusBar()->isVisible());
3700 } else if (ui_component == "menubar") {
3701 menuBar()->setVisible(!menuBar()->isVisible());
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);
3714 if (ui_component == "fullscreen") {
3722 void GuiView::toggleFullScreen()
3724 if (isFullScreen()) {
3725 for (int i = 0; i != d.splitter_->count(); ++i)
3726 d.tabWorkArea(i)->setFullScreen(false);
3727 setContentsMargins(0, 0, 0, 0);
3728 setWindowState(windowState() ^ Qt::WindowFullScreen);
3731 statusBar()->show();
3734 hideDialogs("prefs", 0);
3735 for (int i = 0; i != d.splitter_->count(); ++i)
3736 d.tabWorkArea(i)->setFullScreen(true);
3737 setContentsMargins(-2, -2, -2, -2);
3739 setWindowState(windowState() ^ Qt::WindowFullScreen);
3740 statusBar()->hide();
3741 if (lyxrc.full_screen_menubar)
3743 if (lyxrc.full_screen_toolbars) {
3744 ToolbarMap::iterator end = d.toolbars_.end();
3745 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
3750 // give dialogs like the TOC a chance to adapt
3755 Buffer const * GuiView::updateInset(Inset const * inset)
3760 Buffer const * inset_buffer = &(inset->buffer());
3762 for (int i = 0; i != d.splitter_->count(); ++i) {
3763 GuiWorkArea * wa = d.tabWorkArea(i)->currentWorkArea();
3766 Buffer const * buffer = &(wa->bufferView().buffer());
3767 if (inset_buffer == buffer)
3768 wa->scheduleRedraw();
3770 return inset_buffer;
3774 void GuiView::restartCursor()
3776 /* When we move around, or type, it's nice to be able to see
3777 * the cursor immediately after the keypress.
3779 if (d.current_work_area_)
3780 d.current_work_area_->startBlinkingCursor();
3782 // Take this occasion to update the other GUI elements.
3788 void GuiView::updateCompletion(Cursor & cur, bool start, bool keep)
3790 if (d.current_work_area_)
3791 d.current_work_area_->completer().updateVisibility(cur, start, keep);
3796 // This list should be kept in sync with the list of insets in
3797 // src/insets/Inset.cpp. I.e., if a dialog goes with an inset, the
3798 // dialog should have the same name as the inset.
3799 // Changes should be also recorded in LFUN_DIALOG_SHOW doxygen
3800 // docs in LyXAction.cpp.
3802 char const * const dialognames[] = {
3804 "aboutlyx", "bibitem", "bibtex", "box", "branch", "changes", "character",
3805 "citation", "compare", "comparehistory", "document", "errorlist", "ert",
3806 "external", "file", "findreplace", "findreplaceadv", "float", "graphics",
3807 "href", "include", "index", "index_print", "info", "listings", "label", "line",
3808 "log", "mathdelimiter", "mathmatrix", "mathspace", "nomenclature",
3809 "nomencl_print", "note", "paragraph", "phantom", "prefs", "print", "ref",
3810 "sendto", "space", "spellchecker", "symbols", "tabular", "tabularcreate",
3811 "thesaurus", "texinfo", "toc", "view-source", "vspace", "wrap", "progress"};
3813 char const * const * const end_dialognames =
3814 dialognames + (sizeof(dialognames) / sizeof(char *));
3818 cmpCStr(char const * name) : name_(name) {}
3819 bool operator()(char const * other) {
3820 return strcmp(other, name_) == 0;
3827 bool isValidName(string const & name)
3829 return find_if(dialognames, end_dialognames,
3830 cmpCStr(name.c_str())) != end_dialognames;
3836 void GuiView::resetDialogs()
3838 // Make sure that no LFUN uses any GuiView.
3839 guiApp->setCurrentView(0);
3843 constructToolbars();
3844 guiApp->menus().fillMenuBar(menuBar(), this, false);
3845 d.layout_->updateContents(true);
3846 // Now update controls with current buffer.
3847 guiApp->setCurrentView(this);
3853 Dialog * GuiView::findOrBuild(string const & name, bool hide_it)
3855 if (!isValidName(name))
3858 map<string, DialogPtr>::iterator it = d.dialogs_.find(name);
3860 if (it != d.dialogs_.end()) {
3862 it->second->hideView();
3863 return it->second.get();
3866 Dialog * dialog = build(name);
3867 d.dialogs_[name].reset(dialog);
3868 if (lyxrc.allow_geometry_session)
3869 dialog->restoreSession();
3876 void GuiView::showDialog(string const & name, string const & data,
3879 triggerShowDialog(toqstr(name), toqstr(data), inset);
3883 void GuiView::doShowDialog(QString const & qname, QString const & qdata,
3889 const string name = fromqstr(qname);
3890 const string data = fromqstr(qdata);
3894 Dialog * dialog = findOrBuild(name, false);
3896 bool const visible = dialog->isVisibleView();
3897 dialog->showData(data);
3898 if (inset && currentBufferView())
3899 currentBufferView()->editInset(name, inset);
3900 // We only set the focus to the new dialog if it was not yet
3901 // visible in order not to change the existing previous behaviour
3903 // activateWindow is needed for floating dockviews
3904 dialog->asQWidget()->raise();
3905 dialog->asQWidget()->activateWindow();
3906 dialog->asQWidget()->setFocus();
3910 catch (ExceptionMessage const & ex) {
3918 bool GuiView::isDialogVisible(string const & name) const
3920 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3921 if (it == d.dialogs_.end())
3923 return it->second.get()->isVisibleView() && !it->second.get()->isClosing();
3927 void GuiView::hideDialog(string const & name, Inset * inset)
3929 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3930 if (it == d.dialogs_.end())
3934 if (!currentBufferView())
3936 if (inset != currentBufferView()->editedInset(name))
3940 Dialog * const dialog = it->second.get();
3941 if (dialog->isVisibleView())
3943 if (currentBufferView())
3944 currentBufferView()->editInset(name, 0);
3948 void GuiView::disconnectDialog(string const & name)
3950 if (!isValidName(name))
3952 if (currentBufferView())
3953 currentBufferView()->editInset(name, 0);
3957 void GuiView::hideAll() const
3959 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
3960 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3962 for(; it != end; ++it)
3963 it->second->hideView();
3967 void GuiView::updateDialogs()
3969 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
3970 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3972 for(; it != end; ++it) {
3973 Dialog * dialog = it->second.get();
3975 if (dialog->needBufferOpen() && !documentBufferView())
3976 hideDialog(fromqstr(dialog->name()), 0);
3977 else if (dialog->isVisibleView())
3978 dialog->checkStatus();
3985 Dialog * createDialog(GuiView & lv, string const & name);
3987 // will be replaced by a proper factory...
3988 Dialog * createGuiAbout(GuiView & lv);
3989 Dialog * createGuiBibtex(GuiView & lv);
3990 Dialog * createGuiChanges(GuiView & lv);
3991 Dialog * createGuiCharacter(GuiView & lv);
3992 Dialog * createGuiCitation(GuiView & lv);
3993 Dialog * createGuiCompare(GuiView & lv);
3994 Dialog * createGuiCompareHistory(GuiView & lv);
3995 Dialog * createGuiDelimiter(GuiView & lv);
3996 Dialog * createGuiDocument(GuiView & lv);
3997 Dialog * createGuiErrorList(GuiView & lv);
3998 Dialog * createGuiExternal(GuiView & lv);
3999 Dialog * createGuiGraphics(GuiView & lv);
4000 Dialog * createGuiInclude(GuiView & lv);
4001 Dialog * createGuiIndex(GuiView & lv);
4002 Dialog * createGuiListings(GuiView & lv);
4003 Dialog * createGuiLog(GuiView & lv);
4004 Dialog * createGuiMathMatrix(GuiView & lv);
4005 Dialog * createGuiNote(GuiView & lv);
4006 Dialog * createGuiParagraph(GuiView & lv);
4007 Dialog * createGuiPhantom(GuiView & lv);
4008 Dialog * createGuiPreferences(GuiView & lv);
4009 Dialog * createGuiPrint(GuiView & lv);
4010 Dialog * createGuiPrintindex(GuiView & lv);
4011 Dialog * createGuiRef(GuiView & lv);
4012 Dialog * createGuiSearch(GuiView & lv);
4013 Dialog * createGuiSearchAdv(GuiView & lv);
4014 Dialog * createGuiSendTo(GuiView & lv);
4015 Dialog * createGuiShowFile(GuiView & lv);
4016 Dialog * createGuiSpellchecker(GuiView & lv);
4017 Dialog * createGuiSymbols(GuiView & lv);
4018 Dialog * createGuiTabularCreate(GuiView & lv);
4019 Dialog * createGuiTexInfo(GuiView & lv);
4020 Dialog * createGuiToc(GuiView & lv);
4021 Dialog * createGuiThesaurus(GuiView & lv);
4022 Dialog * createGuiViewSource(GuiView & lv);
4023 Dialog * createGuiWrap(GuiView & lv);
4024 Dialog * createGuiProgressView(GuiView & lv);
4028 Dialog * GuiView::build(string const & name)
4030 LASSERT(isValidName(name), return 0);
4032 Dialog * dialog = createDialog(*this, name);
4036 if (name == "aboutlyx")
4037 return createGuiAbout(*this);
4038 if (name == "bibtex")
4039 return createGuiBibtex(*this);
4040 if (name == "changes")
4041 return createGuiChanges(*this);
4042 if (name == "character")
4043 return createGuiCharacter(*this);
4044 if (name == "citation")
4045 return createGuiCitation(*this);
4046 if (name == "compare")
4047 return createGuiCompare(*this);
4048 if (name == "comparehistory")
4049 return createGuiCompareHistory(*this);
4050 if (name == "document")
4051 return createGuiDocument(*this);
4052 if (name == "errorlist")
4053 return createGuiErrorList(*this);
4054 if (name == "external")
4055 return createGuiExternal(*this);
4057 return createGuiShowFile(*this);
4058 if (name == "findreplace")
4059 return createGuiSearch(*this);
4060 if (name == "findreplaceadv")
4061 return createGuiSearchAdv(*this);
4062 if (name == "graphics")
4063 return createGuiGraphics(*this);
4064 if (name == "include")
4065 return createGuiInclude(*this);
4066 if (name == "index")
4067 return createGuiIndex(*this);
4068 if (name == "index_print")
4069 return createGuiPrintindex(*this);
4070 if (name == "listings")
4071 return createGuiListings(*this);
4073 return createGuiLog(*this);
4074 if (name == "mathdelimiter")
4075 return createGuiDelimiter(*this);
4076 if (name == "mathmatrix")
4077 return createGuiMathMatrix(*this);
4079 return createGuiNote(*this);
4080 if (name == "paragraph")
4081 return createGuiParagraph(*this);
4082 if (name == "phantom")
4083 return createGuiPhantom(*this);
4084 if (name == "prefs")
4085 return createGuiPreferences(*this);
4086 if (name == "print")
4087 return createGuiPrint(*this);
4089 return createGuiRef(*this);
4090 if (name == "sendto")
4091 return createGuiSendTo(*this);
4092 if (name == "spellchecker")
4093 return createGuiSpellchecker(*this);
4094 if (name == "symbols")
4095 return createGuiSymbols(*this);
4096 if (name == "tabularcreate")
4097 return createGuiTabularCreate(*this);
4098 if (name == "texinfo")
4099 return createGuiTexInfo(*this);
4100 if (name == "thesaurus")
4101 return createGuiThesaurus(*this);
4103 return createGuiToc(*this);
4104 if (name == "view-source")
4105 return createGuiViewSource(*this);
4107 return createGuiWrap(*this);
4108 if (name == "progress")
4109 return createGuiProgressView(*this);
4115 } // namespace frontend
4118 #include "moc_GuiView.cpp"