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"
37 #include "frontends/KeySymbol.h"
39 #include "buffer_funcs.h"
41 #include "BufferList.h"
42 #include "BufferParams.h"
43 #include "BufferView.h"
45 #include "Converter.h"
47 #include "CutAndPaste.h"
49 #include "ErrorList.h"
51 #include "FuncStatus.h"
52 #include "FuncRequest.h"
56 #include "LyXAction.h"
60 #include "Paragraph.h"
61 #include "SpellChecker.h"
64 #include "TextClass.h"
69 #include "support/convert.h"
70 #include "support/debug.h"
71 #include "support/ExceptionMessage.h"
72 #include "support/FileName.h"
73 #include "support/filetools.h"
74 #include "support/gettext.h"
75 #include "support/filetools.h"
76 #include "support/ForkedCalls.h"
77 #include "support/lassert.h"
78 #include "support/lstrings.h"
79 #include "support/os.h"
80 #include "support/Package.h"
81 #include "support/PathChanger.h"
82 #include "support/Systemcall.h"
83 #include "support/Timeout.h"
84 #include "support/ProgressInterface.h"
87 #include <QApplication>
88 #include <QCloseEvent>
90 #include <QDesktopWidget>
91 #include <QDragEnterEvent>
94 #include <QFutureWatcher>
103 #include <QPixmapCache>
105 #include <QPushButton>
106 #include <QScrollBar>
108 #include <QShowEvent>
110 #include <QStackedWidget>
111 #include <QStatusBar>
112 #include <QtConcurrentRun>
120 #define EXPORT_in_THREAD 1
123 #include "support/bind.h"
127 #ifdef HAVE_SYS_TIME_H
128 # include <sys/time.h>
136 using namespace lyx::support;
140 using support::addExtension;
141 using support::changeExtension;
142 using support::removeExtension;
148 class BackgroundWidget : public QWidget
153 LYXERR(Debug::GUI, "show banner: " << lyxrc.show_banner);
154 if (!lyxrc.show_banner)
156 /// The text to be written on top of the pixmap
157 QString const text = lyx_version ?
158 qt_("version ") + lyx_version : qt_("unknown version");
159 splash_ = getPixmap("images/", "banner", "png");
161 QPainter pain(&splash_);
162 pain.setPen(QColor(0, 0, 0));
164 // The font used to display the version info
165 font.setStyleHint(QFont::SansSerif);
166 font.setWeight(QFont::Bold);
167 font.setPointSize(int(toqstr(lyxrc.font_sizes[FONT_SIZE_LARGE]).toDouble()));
169 pain.drawText(190, 225, text);
170 setFocusPolicy(Qt::StrongFocus);
173 void paintEvent(QPaintEvent *)
175 QRectF r = splash_.rect();
176 #if QT_VERSION >= 0x050000
177 r.setWidth(r.width() / splash_.devicePixelRatio());
178 r.setHeight(r.height() / splash_.devicePixelRatio());
180 int x = (width() - r.width()) / 2;
181 int y = (height() - r.height()) / 2;
183 pain.drawPixmap(x, y, splash_);
186 void keyPressEvent(QKeyEvent * ev)
189 setKeySymbol(&sym, ev);
191 guiApp->processKeySym(sym, q_key_state(ev->modifiers()));
203 /// Toolbar store providing access to individual toolbars by name.
204 typedef map<string, GuiToolbar *> ToolbarMap;
206 typedef shared_ptr<Dialog> DialogPtr;
211 struct GuiView::GuiViewPrivate
213 GuiViewPrivate(GuiView * gv)
214 : gv_(gv), current_work_area_(0), current_main_work_area_(0),
215 layout_(0), autosave_timeout_(5000),
218 // hardcode here the platform specific icon size
219 smallIconSize = 16; // scaling problems
220 normalIconSize = 20; // ok, default if iconsize.png is missing
221 bigIconSize = 26; // better for some math icons
223 // if it exists, use width of iconsize.png as normal size
224 QString const dir = toqstr(addPath("images", lyxrc.icon_set));
225 FileName const fn = lyx::libFileSearch(dir, "iconsize.png");
227 QImage image(toqstr(fn.absFileName()));
228 if (image.width() < int(smallIconSize))
229 normalIconSize = smallIconSize;
230 else if (image.width() > int(bigIconSize))
231 normalIconSize = bigIconSize;
233 normalIconSize = image.width();
236 splitter_ = new QSplitter;
237 bg_widget_ = new BackgroundWidget;
238 stack_widget_ = new QStackedWidget;
239 stack_widget_->addWidget(bg_widget_);
240 stack_widget_->addWidget(splitter_);
243 // TODO cleanup, remove the singleton, handle multiple Windows?
244 progress_ = ProgressInterface::instance();
245 if (!dynamic_cast<GuiProgress*>(progress_)) {
246 progress_ = new GuiProgress; // TODO who deletes it
247 ProgressInterface::setInstance(progress_);
250 dynamic_cast<GuiProgress*>(progress_),
251 SIGNAL(updateStatusBarMessage(QString const&)),
252 gv, SLOT(updateStatusBarMessage(QString const&)));
254 dynamic_cast<GuiProgress*>(progress_),
255 SIGNAL(clearMessageText()),
256 gv, SLOT(clearMessageText()));
263 delete stack_widget_;
266 QMenu * toolBarPopup(GuiView * parent)
268 // FIXME: translation
269 QMenu * menu = new QMenu(parent);
270 QActionGroup * iconSizeGroup = new QActionGroup(parent);
272 QAction * smallIcons = new QAction(iconSizeGroup);
273 smallIcons->setText(qt_("Small-sized icons"));
274 smallIcons->setCheckable(true);
275 QObject::connect(smallIcons, SIGNAL(triggered()),
276 parent, SLOT(smallSizedIcons()));
277 menu->addAction(smallIcons);
279 QAction * normalIcons = new QAction(iconSizeGroup);
280 normalIcons->setText(qt_("Normal-sized icons"));
281 normalIcons->setCheckable(true);
282 QObject::connect(normalIcons, SIGNAL(triggered()),
283 parent, SLOT(normalSizedIcons()));
284 menu->addAction(normalIcons);
286 QAction * bigIcons = new QAction(iconSizeGroup);
287 bigIcons->setText(qt_("Big-sized icons"));
288 bigIcons->setCheckable(true);
289 QObject::connect(bigIcons, SIGNAL(triggered()),
290 parent, SLOT(bigSizedIcons()));
291 menu->addAction(bigIcons);
293 unsigned int cur = parent->iconSize().width();
294 if ( cur == parent->d.smallIconSize)
295 smallIcons->setChecked(true);
296 else if (cur == parent->d.normalIconSize)
297 normalIcons->setChecked(true);
298 else if (cur == parent->d.bigIconSize)
299 bigIcons->setChecked(true);
306 stack_widget_->setCurrentWidget(bg_widget_);
307 bg_widget_->setUpdatesEnabled(true);
308 bg_widget_->setFocus();
311 int tabWorkAreaCount()
313 return splitter_->count();
316 TabWorkArea * tabWorkArea(int i)
318 return dynamic_cast<TabWorkArea *>(splitter_->widget(i));
321 TabWorkArea * currentTabWorkArea()
323 int areas = tabWorkAreaCount();
325 // The first TabWorkArea is always the first one, if any.
326 return tabWorkArea(0);
328 for (int i = 0; i != areas; ++i) {
329 TabWorkArea * twa = tabWorkArea(i);
330 if (current_main_work_area_ == twa->currentWorkArea())
334 // None has the focus so we just take the first one.
335 return tabWorkArea(0);
338 int countWorkAreasOf(Buffer & buf)
340 int areas = tabWorkAreaCount();
342 for (int i = 0; i != areas; ++i) {
343 TabWorkArea * twa = tabWorkArea(i);
344 if (twa->workArea(buf))
350 void setPreviewFuture(QFuture<Buffer::ExportStatus> const & f)
352 if (processing_thread_watcher_.isRunning()) {
353 // we prefer to cancel this preview in order to keep a snappy
357 processing_thread_watcher_.setFuture(f);
362 GuiWorkArea * current_work_area_;
363 GuiWorkArea * current_main_work_area_;
364 QSplitter * splitter_;
365 QStackedWidget * stack_widget_;
366 BackgroundWidget * bg_widget_;
368 ToolbarMap toolbars_;
369 ProgressInterface* progress_;
370 /// The main layout box.
372 * \warning Don't Delete! The layout box is actually owned by
373 * whichever toolbar contains it. All the GuiView class needs is a
374 * means of accessing it.
376 * FIXME: replace that with a proper model so that we are not limited
377 * to only one dialog.
382 map<string, DialogPtr> dialogs_;
384 unsigned int smallIconSize;
385 unsigned int normalIconSize;
386 unsigned int bigIconSize;
388 QTimer statusbar_timer_;
389 /// auto-saving of buffers
390 Timeout autosave_timeout_;
391 /// flag against a race condition due to multiclicks, see bug #1119
395 TocModels toc_models_;
398 QFutureWatcher<docstring> autosave_watcher_;
399 QFutureWatcher<Buffer::ExportStatus> processing_thread_watcher_;
401 string last_export_format;
402 string processing_format;
404 static QSet<Buffer const *> busyBuffers;
405 static Buffer::ExportStatus previewAndDestroy(Buffer const * orig, Buffer * buffer, string const & format);
406 static Buffer::ExportStatus exportAndDestroy(Buffer const * orig, Buffer * buffer, string const & format);
407 static Buffer::ExportStatus compileAndDestroy(Buffer const * orig, Buffer * buffer, string const & format);
408 static docstring autosaveAndDestroy(Buffer const * orig, Buffer * buffer);
411 static Buffer::ExportStatus runAndDestroy(const T& func, Buffer const * orig, Buffer * buffer, string const & format);
413 // TODO syncFunc/previewFunc: use bind
414 bool asyncBufferProcessing(string const & argument,
415 Buffer const * used_buffer,
416 docstring const & msg,
417 Buffer::ExportStatus (*asyncFunc)(Buffer const *, Buffer *, string const &),
418 Buffer::ExportStatus (Buffer::*syncFunc)(string const &, bool) const,
419 Buffer::ExportStatus (Buffer::*previewFunc)(string const &) const);
421 QVector<GuiWorkArea*> guiWorkAreas();
424 QSet<Buffer const *> GuiView::GuiViewPrivate::busyBuffers;
427 GuiView::GuiView(int id)
428 : d(*new GuiViewPrivate(this)), id_(id), closing_(false), busy_(0)
430 // GuiToolbars *must* be initialised before the menu bar.
431 normalSizedIcons(); // at least on Mac the default is 32 otherwise, which is huge
434 // set ourself as the current view. This is needed for the menu bar
435 // filling, at least for the static special menu item on Mac. Otherwise
436 // they are greyed out.
437 guiApp->setCurrentView(this);
439 // Fill up the menu bar.
440 guiApp->menus().fillMenuBar(menuBar(), this, true);
442 setCentralWidget(d.stack_widget_);
444 // Start autosave timer
445 if (lyxrc.autosave) {
446 d.autosave_timeout_.timeout.connect(bind(&GuiView::autoSave, this));
447 d.autosave_timeout_.setTimeout(lyxrc.autosave * 1000);
448 d.autosave_timeout_.start();
450 connect(&d.statusbar_timer_, SIGNAL(timeout()),
451 this, SLOT(clearMessage()));
453 // We don't want to keep the window in memory if it is closed.
454 setAttribute(Qt::WA_DeleteOnClose, true);
456 #if !(defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)) && !defined(Q_OS_MAC)
457 // QIcon::fromTheme was introduced in Qt 4.6
458 #if (QT_VERSION >= 0x040600)
459 // assign an icon to main form. We do not do it under Qt/Win or Qt/Mac,
460 // since the icon is provided in the application bundle. We use a themed
461 // version when available and use the bundled one as fallback.
462 setWindowIcon(QIcon::fromTheme("lyx", getPixmap("images/", "lyx", "png")));
464 setWindowIcon(getPixmap("images/", "lyx", "png"));
468 resetWindowTitleAndIconText();
470 // use tabbed dock area for multiple docks
471 // (such as "source" and "messages")
472 setDockOptions(QMainWindow::ForceTabbedDocks);
475 setAcceptDrops(true);
477 // add busy indicator to statusbar
478 QLabel * busylabel = new QLabel(statusBar());
479 statusBar()->addPermanentWidget(busylabel);
480 search_mode mode = theGuiApp()->imageSearchMode();
481 QString fn = toqstr(lyx::libFileSearch("images", "busy", "gif", mode).absFileName());
482 QMovie * busyanim = new QMovie(fn, QByteArray(), busylabel);
483 busylabel->setMovie(busyanim);
487 connect(&d.processing_thread_watcher_, SIGNAL(started()),
488 busylabel, SLOT(show()));
489 connect(&d.processing_thread_watcher_, SIGNAL(finished()),
490 busylabel, SLOT(hide()));
492 statusBar()->setSizeGripEnabled(true);
495 connect(&d.autosave_watcher_, SIGNAL(finished()), this,
496 SLOT(autoSaveThreadFinished()));
498 connect(&d.processing_thread_watcher_, SIGNAL(started()), this,
499 SLOT(processingThreadStarted()));
500 connect(&d.processing_thread_watcher_, SIGNAL(finished()), this,
501 SLOT(processingThreadFinished()));
503 connect(this, SIGNAL(triggerShowDialog(QString const &, QString const &, Inset *)),
504 SLOT(doShowDialog(QString const &, QString const &, Inset *)));
506 // Forbid too small unresizable window because it can happen
507 // with some window manager under X11.
508 setMinimumSize(300, 200);
510 if (lyxrc.allow_geometry_session) {
511 // Now take care of session management.
516 // no session handling, default to a sane size.
517 setGeometry(50, 50, 690, 510);
520 // clear session data if any.
522 settings.remove("views");
532 QVector<GuiWorkArea*> GuiView::GuiViewPrivate::guiWorkAreas()
534 QVector<GuiWorkArea*> areas;
535 for (int i = 0; i < tabWorkAreaCount(); i++) {
536 TabWorkArea* ta = tabWorkArea(i);
537 for (int u = 0; u < ta->count(); u++) {
538 areas << ta->workArea(u);
544 static void handleExportStatus(GuiView * view, Buffer::ExportStatus status,
545 string const & format)
547 docstring const fmt = formats.prettyName(format);
550 case Buffer::ExportSuccess:
551 msg = bformat(_("Successful export to format: %1$s"), fmt);
553 case Buffer::ExportCancel:
554 msg = _("Document export cancelled.");
556 case Buffer::ExportError:
557 case Buffer::ExportNoPathToFormat:
558 case Buffer::ExportTexPathHasSpaces:
559 case Buffer::ExportConverterError:
560 msg = bformat(_("Error while exporting format: %1$s"), fmt);
562 case Buffer::PreviewSuccess:
563 msg = bformat(_("Successful preview of format: %1$s"), fmt);
565 case Buffer::PreviewError:
566 msg = bformat(_("Error while previewing format: %1$s"), fmt);
573 void GuiView::processingThreadStarted()
578 void GuiView::processingThreadFinished()
580 QFutureWatcher<Buffer::ExportStatus> const * watcher =
581 static_cast<QFutureWatcher<Buffer::ExportStatus> const *>(sender());
583 Buffer::ExportStatus const status = watcher->result();
584 handleExportStatus(this, status, d.processing_format);
587 BufferView const * const bv = currentBufferView();
588 if (bv && !bv->buffer().errorList("Export").empty()) {
592 errors(d.last_export_format);
596 void GuiView::autoSaveThreadFinished()
598 QFutureWatcher<docstring> const * watcher =
599 static_cast<QFutureWatcher<docstring> const *>(sender());
600 message(watcher->result());
605 void GuiView::saveLayout() const
608 settings.beginGroup("views");
609 settings.beginGroup(QString::number(id_));
611 settings.setValue("pos", pos());
612 settings.setValue("size", size());
614 settings.setValue("geometry", saveGeometry());
616 settings.setValue("layout", saveState(0));
617 settings.setValue("icon_size", iconSize());
621 void GuiView::saveUISettings() const
623 // Save the toolbar private states
624 ToolbarMap::iterator end = d.toolbars_.end();
625 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
626 it->second->saveSession();
627 // Now take care of all other dialogs
628 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
629 for (; it!= d.dialogs_.end(); ++it)
630 it->second->saveSession();
634 bool GuiView::restoreLayout()
637 settings.beginGroup("views");
638 settings.beginGroup(QString::number(id_));
639 QString const icon_key = "icon_size";
640 if (!settings.contains(icon_key))
643 //code below is skipped when when ~/.config/LyX is (re)created
644 QSize icon_size = settings.value(icon_key).toSize();
645 // Check whether session size changed.
646 if (icon_size.width() != int(d.smallIconSize) &&
647 icon_size.width() != int(d.normalIconSize) &&
648 icon_size.width() != int(d.bigIconSize)) {
649 icon_size.setWidth(d.normalIconSize);
650 icon_size.setHeight(d.normalIconSize);
652 setIconSize(icon_size);
655 QPoint pos = settings.value("pos", QPoint(50, 50)).toPoint();
656 QSize size = settings.value("size", QSize(690, 510)).toSize();
660 // Work-around for bug #6034: the window ends up in an undetermined
661 // state when trying to restore a maximized window when it is
662 // already maximized.
663 if (!(windowState() & Qt::WindowMaximized))
664 if (!restoreGeometry(settings.value("geometry").toByteArray()))
665 setGeometry(50, 50, 690, 510);
667 // Make sure layout is correctly oriented.
668 setLayoutDirection(qApp->layoutDirection());
670 // Allow the toc and view-source dock widget to be restored if needed.
672 if ((dialog = findOrBuild("toc", true)))
673 // see bug 5082. At least setup title and enabled state.
674 // Visibility will be adjusted by restoreState below.
675 dialog->prepareView();
676 if ((dialog = findOrBuild("view-source", true)))
677 dialog->prepareView();
678 if ((dialog = findOrBuild("progress", true)))
679 dialog->prepareView();
681 if (!restoreState(settings.value("layout").toByteArray(), 0))
684 // init the toolbars that have not been restored
685 Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
686 Toolbars::Infos::iterator end = guiApp->toolbars().end();
687 for (; cit != end; ++cit) {
688 GuiToolbar * tb = toolbar(cit->name);
689 if (tb && !tb->isRestored())
690 initToolbar(cit->name);
698 GuiToolbar * GuiView::toolbar(string const & name)
700 ToolbarMap::iterator it = d.toolbars_.find(name);
701 if (it != d.toolbars_.end())
704 LYXERR(Debug::GUI, "Toolbar::display: no toolbar named " << name);
709 void GuiView::constructToolbars()
711 ToolbarMap::iterator it = d.toolbars_.begin();
712 for (; it != d.toolbars_.end(); ++it)
716 // I don't like doing this here, but the standard toolbar
717 // destroys this object when it's destroyed itself (vfr)
718 d.layout_ = new LayoutBox(*this);
719 d.stack_widget_->addWidget(d.layout_);
720 d.layout_->move(0,0);
722 // extracts the toolbars from the backend
723 Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
724 Toolbars::Infos::iterator end = guiApp->toolbars().end();
725 for (; cit != end; ++cit)
726 d.toolbars_[cit->name] = new GuiToolbar(*cit, *this);
730 void GuiView::initToolbars()
732 // extracts the toolbars from the backend
733 Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
734 Toolbars::Infos::iterator end = guiApp->toolbars().end();
735 for (; cit != end; ++cit)
736 initToolbar(cit->name);
740 void GuiView::initToolbar(string const & name)
742 GuiToolbar * tb = toolbar(name);
745 int const visibility = guiApp->toolbars().defaultVisibility(name);
746 bool newline = !(visibility & Toolbars::SAMEROW);
747 tb->setVisible(false);
748 tb->setVisibility(visibility);
750 if (visibility & Toolbars::TOP) {
752 addToolBarBreak(Qt::TopToolBarArea);
753 addToolBar(Qt::TopToolBarArea, tb);
756 if (visibility & Toolbars::BOTTOM) {
758 addToolBarBreak(Qt::BottomToolBarArea);
759 addToolBar(Qt::BottomToolBarArea, tb);
762 if (visibility & Toolbars::LEFT) {
764 addToolBarBreak(Qt::LeftToolBarArea);
765 addToolBar(Qt::LeftToolBarArea, tb);
768 if (visibility & Toolbars::RIGHT) {
770 addToolBarBreak(Qt::RightToolBarArea);
771 addToolBar(Qt::RightToolBarArea, tb);
774 if (visibility & Toolbars::ON)
775 tb->setVisible(true);
779 TocModels & GuiView::tocModels()
781 return d.toc_models_;
785 void GuiView::setFocus()
787 LYXERR(Debug::DEBUG, "GuiView::setFocus()" << this);
788 QMainWindow::setFocus();
792 void GuiView::focusInEvent(QFocusEvent * e)
794 LYXERR(Debug::DEBUG, "GuiView::focusInEvent()" << this);
795 QMainWindow::focusInEvent(e);
796 // Make sure guiApp points to the correct view.
797 guiApp->setCurrentView(this);
798 if (currentWorkArea())
799 currentWorkArea()->setFocus();
800 else if (currentMainWorkArea())
801 currentMainWorkArea()->setFocus();
803 d.bg_widget_->setFocus();
807 QMenu * GuiView::createPopupMenu()
809 return d.toolBarPopup(this);
813 void GuiView::showEvent(QShowEvent * e)
815 LYXERR(Debug::GUI, "Passed Geometry "
816 << size().height() << "x" << size().width()
817 << "+" << pos().x() << "+" << pos().y());
819 if (d.splitter_->count() == 0)
820 // No work area, switch to the background widget.
824 QMainWindow::showEvent(e);
828 bool GuiView::closeScheduled()
835 /** Destroy only all tabbed WorkAreas. Destruction of other WorkAreas
836 ** is responsibility of the container (e.g., dialog)
838 void GuiView::closeEvent(QCloseEvent * close_event)
840 LYXERR(Debug::DEBUG, "GuiView::closeEvent()");
842 if (!GuiViewPrivate::busyBuffers.isEmpty()) {
843 Alert::warning(_("Exit LyX"),
844 _("LyX could not be closed because documents are being processed by LyX."));
845 close_event->setAccepted(false);
849 // If the user pressed the x (so we didn't call closeView
850 // programmatically), we want to clear all existing entries.
852 theSession().lastOpened().clear();
857 // it can happen that this event arrives without selecting the view,
858 // e.g. when clicking the close button on a background window.
860 if (!closeWorkAreaAll()) {
862 close_event->ignore();
866 // Make sure that nothing will use this to be closed View.
867 guiApp->unregisterView(this);
869 if (isFullScreen()) {
870 // Switch off fullscreen before closing.
875 // Make sure the timer time out will not trigger a statusbar update.
876 d.statusbar_timer_.stop();
878 // Saving fullscreen requires additional tweaks in the toolbar code.
879 // It wouldn't also work under linux natively.
880 if (lyxrc.allow_geometry_session) {
885 close_event->accept();
889 void GuiView::dragEnterEvent(QDragEnterEvent * event)
891 if (event->mimeData()->hasUrls())
893 /// \todo Ask lyx-devel is this is enough:
894 /// if (event->mimeData()->hasFormat("text/plain"))
895 /// event->acceptProposedAction();
899 void GuiView::dropEvent(QDropEvent * event)
901 QList<QUrl> files = event->mimeData()->urls();
905 LYXERR(Debug::GUI, "GuiView::dropEvent: got URLs!");
906 for (int i = 0; i != files.size(); ++i) {
907 string const file = os::internal_path(fromqstr(
908 files.at(i).toLocalFile()));
912 string const ext = support::getExtension(file);
913 vector<const Format *> found_formats;
915 // Find all formats that have the correct extension.
916 vector<const Format *> const & import_formats
917 = theConverters().importableFormats();
918 vector<const Format *>::const_iterator it = import_formats.begin();
919 for (; it != import_formats.end(); ++it)
920 if ((*it)->hasExtension(ext))
921 found_formats.push_back(*it);
924 if (found_formats.size() >= 1) {
925 if (found_formats.size() > 1) {
926 //FIXME: show a dialog to choose the correct importable format
928 "Multiple importable formats found, selecting first");
930 string const arg = found_formats[0]->name() + " " + file;
931 cmd = FuncRequest(LFUN_BUFFER_IMPORT, arg);
934 //FIXME: do we have to explicitly check whether it's a lyx file?
936 "No formats found, trying to open it as a lyx file");
937 cmd = FuncRequest(LFUN_FILE_OPEN, file);
939 // add the functions to the queue
940 guiApp->addToFuncRequestQueue(cmd);
943 // now process the collected functions. We perform the events
944 // asynchronously. This prevents potential problems in case the
945 // BufferView is closed within an event.
946 guiApp->processFuncRequestQueueAsync();
950 void GuiView::message(docstring const & str)
952 if (ForkedProcess::iAmAChild())
955 // call is moved to GUI-thread by GuiProgress
956 d.progress_->appendMessage(toqstr(str));
960 void GuiView::clearMessageText()
962 message(docstring());
966 void GuiView::updateStatusBarMessage(QString const & str)
968 statusBar()->showMessage(str);
969 d.statusbar_timer_.stop();
970 d.statusbar_timer_.start(3000);
974 void GuiView::smallSizedIcons()
976 setIconSize(QSize(d.smallIconSize, d.smallIconSize));
980 void GuiView::normalSizedIcons()
982 setIconSize(QSize(d.normalIconSize, d.normalIconSize));
986 void GuiView::bigSizedIcons()
988 setIconSize(QSize(d.bigIconSize, d.bigIconSize));
992 void GuiView::clearMessage()
994 // FIXME: This code was introduced in r19643 to fix bug #4123. However,
995 // the hasFocus function mostly returns false, even if the focus is on
996 // a workarea in this view.
1000 d.statusbar_timer_.stop();
1004 void GuiView::updateWindowTitle(GuiWorkArea * wa)
1006 if (wa != d.current_work_area_
1007 || wa->bufferView().buffer().isInternal())
1009 setWindowTitle(qt_("LyX: ") + wa->windowTitle());
1010 setWindowIconText(wa->windowIconText());
1011 #if (QT_VERSION >= 0x040400)
1012 // Sets the path for the window: this is used by OSX to
1013 // allow a context click on the title bar showing a menu
1014 // with the path up to the file
1015 setWindowFilePath(toqstr(wa->bufferView().buffer().absFileName()));
1020 void GuiView::on_currentWorkAreaChanged(GuiWorkArea * wa)
1022 if (d.current_work_area_)
1023 QObject::disconnect(d.current_work_area_, SIGNAL(busy(bool)),
1024 this, SLOT(setBusy(bool)));
1026 disconnectBufferView();
1027 connectBufferView(wa->bufferView());
1028 connectBuffer(wa->bufferView().buffer());
1029 d.current_work_area_ = wa;
1030 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
1031 this, SLOT(updateWindowTitle(GuiWorkArea *)));
1032 QObject::connect(wa, SIGNAL(busy(bool)), this, SLOT(setBusy(bool)));
1033 updateWindowTitle(wa);
1037 // The document settings needs to be reinitialised.
1038 updateDialog("document", "");
1040 // Buffer-dependent dialogs must be updated. This is done here because
1041 // some dialogs require buffer()->text.
1046 void GuiView::on_lastWorkAreaRemoved()
1049 // We already are in a close event. Nothing more to do.
1052 if (d.splitter_->count() > 1)
1053 // We have a splitter so don't close anything.
1056 // Reset and updates the dialogs.
1057 d.toc_models_.reset(0);
1058 updateDialog("document", "");
1061 resetWindowTitleAndIconText();
1064 if (lyxrc.open_buffers_in_tabs)
1065 // Nothing more to do, the window should stay open.
1068 if (guiApp->viewIds().size() > 1) {
1074 // On Mac we also close the last window because the application stay
1075 // resident in memory. On other platforms we don't close the last
1076 // window because this would quit the application.
1082 void GuiView::updateStatusBar()
1084 // let the user see the explicit message
1085 if (d.statusbar_timer_.isActive())
1092 void GuiView::showMessage()
1096 QString msg = toqstr(theGuiApp()->viewStatusMessage());
1097 if (msg.isEmpty()) {
1098 BufferView const * bv = currentBufferView();
1100 msg = toqstr(bv->cursor().currentState());
1102 msg = qt_("Welcome to LyX!");
1104 statusBar()->showMessage(msg);
1108 bool GuiView::event(QEvent * e)
1112 // Useful debug code:
1113 //case QEvent::ActivationChange:
1114 //case QEvent::WindowDeactivate:
1115 //case QEvent::Paint:
1116 //case QEvent::Enter:
1117 //case QEvent::Leave:
1118 //case QEvent::HoverEnter:
1119 //case QEvent::HoverLeave:
1120 //case QEvent::HoverMove:
1121 //case QEvent::StatusTip:
1122 //case QEvent::DragEnter:
1123 //case QEvent::DragLeave:
1124 //case QEvent::Drop:
1127 case QEvent::WindowActivate: {
1128 GuiView * old_view = guiApp->currentView();
1129 if (this == old_view) {
1131 return QMainWindow::event(e);
1133 if (old_view && old_view->currentBufferView()) {
1134 // save current selection to the selection buffer to allow
1135 // middle-button paste in this window.
1136 cap::saveSelection(old_view->currentBufferView()->cursor());
1138 guiApp->setCurrentView(this);
1139 if (d.current_work_area_) {
1140 BufferView & bv = d.current_work_area_->bufferView();
1141 connectBufferView(bv);
1142 connectBuffer(bv.buffer());
1143 // The document structure, name and dialogs might have
1144 // changed in another view.
1146 // The document settings needs to be reinitialised.
1147 updateDialog("document", "");
1150 resetWindowTitleAndIconText();
1153 return QMainWindow::event(e);
1156 case QEvent::ShortcutOverride: {
1158 if (isFullScreen() && menuBar()->isHidden()) {
1159 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
1160 // FIXME: we should also try to detect special LyX shortcut such as
1161 // Alt-P and Alt-M. Right now there is a hack in
1162 // GuiWorkArea::processKeySym() that hides again the menubar for
1164 if (ke->modifiers() & Qt::AltModifier && ke->key() != Qt::Key_Alt) {
1166 return QMainWindow::event(e);
1169 return QMainWindow::event(e);
1173 return QMainWindow::event(e);
1177 void GuiView::resetWindowTitleAndIconText()
1179 setWindowTitle(qt_("LyX"));
1180 setWindowIconText(qt_("LyX"));
1183 bool GuiView::focusNextPrevChild(bool /*next*/)
1190 bool GuiView::busy() const
1196 void GuiView::setBusy(bool busy)
1198 bool const busy_before = busy_ > 0;
1199 busy ? ++busy_ : --busy_;
1200 if ((busy_ > 0) == busy_before)
1201 // busy state didn't change
1205 QApplication::setOverrideCursor(Qt::WaitCursor);
1208 QApplication::restoreOverrideCursor();
1213 double GuiView::pixelRatio() const
1215 #if QT_VERSION >= 0x050000
1216 return devicePixelRatio();
1223 GuiWorkArea * GuiView::workArea(int index)
1225 if (TabWorkArea * twa = d.currentTabWorkArea())
1226 if (index < twa->count())
1227 return dynamic_cast<GuiWorkArea *>(twa->widget(index));
1232 GuiWorkArea * GuiView::workArea(Buffer & buffer)
1234 if (currentWorkArea()
1235 && ¤tWorkArea()->bufferView().buffer() == &buffer)
1236 return (GuiWorkArea *) currentWorkArea();
1237 if (TabWorkArea * twa = d.currentTabWorkArea())
1238 return twa->workArea(buffer);
1243 GuiWorkArea * GuiView::addWorkArea(Buffer & buffer)
1245 // Automatically create a TabWorkArea if there are none yet.
1246 TabWorkArea * tab_widget = d.splitter_->count()
1247 ? d.currentTabWorkArea() : addTabWorkArea();
1248 return tab_widget->addWorkArea(buffer, *this);
1252 TabWorkArea * GuiView::addTabWorkArea()
1254 TabWorkArea * twa = new TabWorkArea;
1255 QObject::connect(twa, SIGNAL(currentWorkAreaChanged(GuiWorkArea *)),
1256 this, SLOT(on_currentWorkAreaChanged(GuiWorkArea *)));
1257 QObject::connect(twa, SIGNAL(lastWorkAreaRemoved()),
1258 this, SLOT(on_lastWorkAreaRemoved()));
1260 d.splitter_->addWidget(twa);
1261 d.stack_widget_->setCurrentWidget(d.splitter_);
1266 GuiWorkArea const * GuiView::currentWorkArea() const
1268 return d.current_work_area_;
1272 GuiWorkArea * GuiView::currentWorkArea()
1274 return d.current_work_area_;
1278 GuiWorkArea const * GuiView::currentMainWorkArea() const
1280 if (!d.currentTabWorkArea())
1282 return d.currentTabWorkArea()->currentWorkArea();
1286 GuiWorkArea * GuiView::currentMainWorkArea()
1288 if (!d.currentTabWorkArea())
1290 return d.currentTabWorkArea()->currentWorkArea();
1294 void GuiView::setCurrentWorkArea(GuiWorkArea * wa)
1296 LYXERR(Debug::DEBUG, "Setting current wa: " << wa << endl);
1298 d.current_work_area_ = 0;
1303 // FIXME: I've no clue why this is here and why it accesses
1304 // theGuiApp()->currentView, which might be 0 (bug 6464).
1305 // See also 27525 (vfr).
1306 if (theGuiApp()->currentView() == this
1307 && theGuiApp()->currentView()->currentWorkArea() == wa)
1310 if (currentBufferView())
1311 cap::saveSelection(currentBufferView()->cursor());
1313 theGuiApp()->setCurrentView(this);
1314 d.current_work_area_ = wa;
1316 // We need to reset this now, because it will need to be
1317 // right if the tabWorkArea gets reset in the for loop. We
1318 // will change it back if we aren't in that case.
1319 GuiWorkArea * const old_cmwa = d.current_main_work_area_;
1320 d.current_main_work_area_ = wa;
1322 for (int i = 0; i != d.splitter_->count(); ++i) {
1323 if (d.tabWorkArea(i)->setCurrentWorkArea(wa)) {
1324 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea()
1325 << ", Current main wa: " << currentMainWorkArea());
1330 d.current_main_work_area_ = old_cmwa;
1332 LYXERR(Debug::DEBUG, "This is not a tabbed wa");
1333 on_currentWorkAreaChanged(wa);
1334 BufferView & bv = wa->bufferView();
1335 bv.cursor().fixIfBroken();
1337 wa->setUpdatesEnabled(true);
1338 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() << ", Current main wa: " << currentMainWorkArea());
1342 void GuiView::removeWorkArea(GuiWorkArea * wa)
1344 LASSERT(wa, return);
1345 if (wa == d.current_work_area_) {
1347 disconnectBufferView();
1348 d.current_work_area_ = 0;
1349 d.current_main_work_area_ = 0;
1352 bool found_twa = false;
1353 for (int i = 0; i != d.splitter_->count(); ++i) {
1354 TabWorkArea * twa = d.tabWorkArea(i);
1355 if (twa->removeWorkArea(wa)) {
1356 // Found in this tab group, and deleted the GuiWorkArea.
1358 if (twa->count() != 0) {
1359 if (d.current_work_area_ == 0)
1360 // This means that we are closing the current GuiWorkArea, so
1361 // switch to the next GuiWorkArea in the found TabWorkArea.
1362 setCurrentWorkArea(twa->currentWorkArea());
1364 // No more WorkAreas in this tab group, so delete it.
1371 // It is not a tabbed work area (i.e., the search work area), so it
1372 // should be deleted by other means.
1373 LASSERT(found_twa, return);
1375 if (d.current_work_area_ == 0) {
1376 if (d.splitter_->count() != 0) {
1377 TabWorkArea * twa = d.currentTabWorkArea();
1378 setCurrentWorkArea(twa->currentWorkArea());
1380 // No more work areas, switch to the background widget.
1381 setCurrentWorkArea(0);
1387 LayoutBox * GuiView::getLayoutDialog() const
1393 void GuiView::updateLayoutList()
1396 d.layout_->updateContents(false);
1400 void GuiView::updateToolbars()
1402 ToolbarMap::iterator end = d.toolbars_.end();
1403 if (d.current_work_area_) {
1405 d.current_work_area_->bufferView().cursor().inMathed()
1406 && !d.current_work_area_->bufferView().cursor().inRegexped();
1408 lyx::getStatus(FuncRequest(LFUN_LAYOUT_TABULAR)).enabled();
1410 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).enabled() &&
1411 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).onOff(true);
1412 bool const mathmacrotemplate =
1413 lyx::getStatus(FuncRequest(LFUN_IN_MATHMACROTEMPLATE)).enabled();
1415 lyx::getStatus(FuncRequest(LFUN_IN_IPA)).enabled();
1417 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1418 it->second->update(math, table, review, mathmacrotemplate, ipa);
1420 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1421 it->second->update(false, false, false, false, false);
1425 void GuiView::setBuffer(Buffer * newBuffer)
1427 LYXERR(Debug::DEBUG, "Setting buffer: " << newBuffer << endl);
1428 LASSERT(newBuffer, return);
1430 GuiWorkArea * wa = workArea(*newBuffer);
1433 newBuffer->masterBuffer()->updateBuffer();
1435 wa = addWorkArea(*newBuffer);
1436 // scroll to the position when the BufferView was last closed
1437 if (lyxrc.use_lastfilepos) {
1438 LastFilePosSection::FilePos filepos =
1439 theSession().lastFilePos().load(newBuffer->fileName());
1440 wa->bufferView().moveToPosition(filepos.pit, filepos.pos, 0, 0);
1443 //Disconnect the old buffer...there's no new one.
1446 connectBuffer(*newBuffer);
1447 connectBufferView(wa->bufferView());
1448 setCurrentWorkArea(wa);
1452 void GuiView::connectBuffer(Buffer & buf)
1454 buf.setGuiDelegate(this);
1458 void GuiView::disconnectBuffer()
1460 if (d.current_work_area_)
1461 d.current_work_area_->bufferView().buffer().setGuiDelegate(0);
1465 void GuiView::connectBufferView(BufferView & bv)
1467 bv.setGuiDelegate(this);
1471 void GuiView::disconnectBufferView()
1473 if (d.current_work_area_)
1474 d.current_work_area_->bufferView().setGuiDelegate(0);
1478 void GuiView::errors(string const & error_type, bool from_master)
1480 BufferView const * const bv = currentBufferView();
1484 #if EXPORT_in_THREAD
1485 // We are called with from_master == false by default, so we
1486 // have to figure out whether that is the case or not.
1487 ErrorList & el = bv->buffer().errorList(error_type);
1489 el = bv->buffer().masterBuffer()->errorList(error_type);
1493 ErrorList const & el = from_master ?
1494 bv->buffer().masterBuffer()->errorList(error_type) :
1495 bv->buffer().errorList(error_type);
1501 string data = error_type;
1503 data = "from_master|" + error_type;
1504 showDialog("errorlist", data);
1508 void GuiView::updateTocItem(string const & type, DocIterator const & dit)
1510 d.toc_models_.updateItem(toqstr(type), dit);
1514 void GuiView::structureChanged()
1516 d.toc_models_.reset(documentBufferView());
1517 // Navigator needs more than a simple update in this case. It needs to be
1519 updateDialog("toc", "");
1523 void GuiView::updateDialog(string const & name, string const & data)
1525 if (!isDialogVisible(name))
1528 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
1529 if (it == d.dialogs_.end())
1532 Dialog * const dialog = it->second.get();
1533 if (dialog->isVisibleView())
1534 dialog->initialiseParams(data);
1538 BufferView * GuiView::documentBufferView()
1540 return currentMainWorkArea()
1541 ? ¤tMainWorkArea()->bufferView()
1546 BufferView const * GuiView::documentBufferView() const
1548 return currentMainWorkArea()
1549 ? ¤tMainWorkArea()->bufferView()
1554 BufferView * GuiView::currentBufferView()
1556 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1560 BufferView const * GuiView::currentBufferView() const
1562 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1566 docstring GuiView::GuiViewPrivate::autosaveAndDestroy(
1567 Buffer const * orig, Buffer * clone)
1569 bool const success = clone->autoSave();
1571 busyBuffers.remove(orig);
1573 ? _("Automatic save done.")
1574 : _("Automatic save failed!");
1578 void GuiView::autoSave()
1580 LYXERR(Debug::INFO, "Running autoSave()");
1582 Buffer * buffer = documentBufferView()
1583 ? &documentBufferView()->buffer() : 0;
1585 resetAutosaveTimers();
1589 GuiViewPrivate::busyBuffers.insert(buffer);
1590 QFuture<docstring> f = QtConcurrent::run(GuiViewPrivate::autosaveAndDestroy,
1591 buffer, buffer->cloneBufferOnly());
1592 d.autosave_watcher_.setFuture(f);
1593 resetAutosaveTimers();
1597 void GuiView::resetAutosaveTimers()
1600 d.autosave_timeout_.restart();
1604 bool GuiView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1607 Buffer * buf = currentBufferView()
1608 ? ¤tBufferView()->buffer() : 0;
1609 Buffer * doc_buffer = documentBufferView()
1610 ? &(documentBufferView()->buffer()) : 0;
1612 // Check whether we need a buffer
1613 if (!lyxaction.funcHasFlag(cmd.action(), LyXAction::NoBuffer) && !buf) {
1614 // no, exit directly
1615 flag.message(from_utf8(N_("Command not allowed with"
1616 "out any document open")));
1617 flag.setEnabled(false);
1621 if (cmd.origin() == FuncRequest::TOC) {
1622 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
1623 if (!toc || !toc->getStatus(documentBufferView()->cursor(), cmd, flag))
1624 flag.setEnabled(false);
1628 switch(cmd.action()) {
1629 case LFUN_BUFFER_IMPORT:
1632 case LFUN_MASTER_BUFFER_UPDATE:
1633 case LFUN_MASTER_BUFFER_VIEW:
1635 && (doc_buffer->parent() != 0
1636 || doc_buffer->hasChildren())
1637 && !d.processing_thread_watcher_.isRunning();
1640 case LFUN_BUFFER_UPDATE:
1641 case LFUN_BUFFER_VIEW: {
1642 if (!doc_buffer || d.processing_thread_watcher_.isRunning()) {
1646 string format = to_utf8(cmd.argument());
1647 if (cmd.argument().empty())
1648 format = doc_buffer->params().getDefaultOutputFormat();
1649 enable = doc_buffer->params().isExportableFormat(format);
1653 case LFUN_BUFFER_RELOAD:
1654 enable = doc_buffer && !doc_buffer->isUnnamed()
1655 && doc_buffer->fileName().exists()
1656 && (!doc_buffer->isClean()
1657 || doc_buffer->isExternallyModified(Buffer::timestamp_method));
1660 case LFUN_BUFFER_CHILD_OPEN:
1661 enable = doc_buffer;
1664 case LFUN_BUFFER_WRITE:
1665 enable = doc_buffer && (doc_buffer->isUnnamed() || !doc_buffer->isClean());
1668 //FIXME: This LFUN should be moved to GuiApplication.
1669 case LFUN_BUFFER_WRITE_ALL: {
1670 // We enable the command only if there are some modified buffers
1671 Buffer * first = theBufferList().first();
1676 // We cannot use a for loop as the buffer list is a cycle.
1678 if (!b->isClean()) {
1682 b = theBufferList().next(b);
1683 } while (b != first);
1687 case LFUN_BUFFER_WRITE_AS:
1688 case LFUN_BUFFER_EXPORT_AS:
1689 enable = doc_buffer;
1692 case LFUN_BUFFER_CLOSE:
1693 case LFUN_VIEW_CLOSE:
1694 enable = doc_buffer;
1697 case LFUN_BUFFER_CLOSE_ALL:
1698 enable = theBufferList().last() != theBufferList().first();
1701 case LFUN_VIEW_SPLIT:
1702 if (cmd.getArg(0) == "vertical")
1703 enable = doc_buffer && (d.splitter_->count() == 1 ||
1704 d.splitter_->orientation() == Qt::Vertical);
1706 enable = doc_buffer && (d.splitter_->count() == 1 ||
1707 d.splitter_->orientation() == Qt::Horizontal);
1710 case LFUN_TAB_GROUP_CLOSE:
1711 enable = d.tabWorkAreaCount() > 1;
1714 case LFUN_TOOLBAR_TOGGLE: {
1715 string const name = cmd.getArg(0);
1716 if (GuiToolbar * t = toolbar(name))
1717 flag.setOnOff(t->isVisible());
1720 docstring const msg =
1721 bformat(_("Unknown toolbar \"%1$s\""), from_utf8(name));
1727 case LFUN_DROP_LAYOUTS_CHOICE:
1731 case LFUN_UI_TOGGLE:
1732 flag.setOnOff(isFullScreen());
1735 case LFUN_DIALOG_DISCONNECT_INSET:
1738 case LFUN_DIALOG_HIDE:
1739 // FIXME: should we check if the dialog is shown?
1742 case LFUN_DIALOG_TOGGLE:
1743 flag.setOnOff(isDialogVisible(cmd.getArg(0)));
1744 // fall through to set "enable"
1745 case LFUN_DIALOG_SHOW: {
1746 string const name = cmd.getArg(0);
1748 enable = name == "aboutlyx"
1749 || name == "file" //FIXME: should be removed.
1751 || name == "texinfo"
1752 || name == "progress"
1753 || name == "compare";
1754 else if (name == "print")
1755 enable = doc_buffer->params().isExportable("dvi")
1756 && lyxrc.print_command != "none";
1757 else if (name == "character" || name == "symbols"
1758 || name == "mathdelimiter" || name == "mathmatrix") {
1759 if (!buf || buf->isReadonly())
1762 Cursor const & cur = currentBufferView()->cursor();
1763 enable = !(cur.inTexted() && cur.paragraph().isPassThru());
1766 else if (name == "latexlog")
1767 enable = FileName(doc_buffer->logName()).isReadableFile();
1768 else if (name == "spellchecker")
1769 enable = theSpellChecker()
1770 && !doc_buffer->isReadonly()
1771 && !doc_buffer->text().empty();
1772 else if (name == "vclog")
1773 enable = doc_buffer->lyxvc().inUse();
1777 case LFUN_DIALOG_UPDATE: {
1778 string const name = cmd.getArg(0);
1780 enable = name == "prefs";
1784 case LFUN_COMMAND_EXECUTE:
1786 case LFUN_MENU_OPEN:
1787 // Nothing to check.
1790 case LFUN_COMPLETION_INLINE:
1791 if (!d.current_work_area_
1792 || !d.current_work_area_->completer().inlinePossible(
1793 currentBufferView()->cursor()))
1797 case LFUN_COMPLETION_POPUP:
1798 if (!d.current_work_area_
1799 || !d.current_work_area_->completer().popupPossible(
1800 currentBufferView()->cursor()))
1805 if (!d.current_work_area_
1806 || !d.current_work_area_->completer().inlinePossible(
1807 currentBufferView()->cursor()))
1811 case LFUN_COMPLETION_ACCEPT:
1812 if (!d.current_work_area_
1813 || (!d.current_work_area_->completer().popupVisible()
1814 && !d.current_work_area_->completer().inlineVisible()
1815 && !d.current_work_area_->completer().completionAvailable()))
1819 case LFUN_COMPLETION_CANCEL:
1820 if (!d.current_work_area_
1821 || (!d.current_work_area_->completer().popupVisible()
1822 && !d.current_work_area_->completer().inlineVisible()))
1826 case LFUN_BUFFER_ZOOM_OUT:
1827 enable = doc_buffer && lyxrc.zoom > 10;
1830 case LFUN_BUFFER_ZOOM_IN:
1831 enable = doc_buffer;
1834 case LFUN_BUFFER_NEXT:
1835 case LFUN_BUFFER_PREVIOUS:
1836 // FIXME: should we check is there is an previous or next buffer?
1838 case LFUN_BUFFER_SWITCH:
1839 // toggle on the current buffer, but do not toggle off
1840 // the other ones (is that a good idea?)
1842 && to_utf8(cmd.argument()) == doc_buffer->absFileName())
1843 flag.setOnOff(true);
1846 case LFUN_VC_REGISTER:
1847 enable = doc_buffer && !doc_buffer->lyxvc().inUse();
1849 case LFUN_VC_RENAME:
1850 enable = doc_buffer && doc_buffer->lyxvc().renameEnabled();
1853 enable = doc_buffer && doc_buffer->lyxvc().copyEnabled();
1855 case LFUN_VC_CHECK_IN:
1856 enable = doc_buffer && doc_buffer->lyxvc().checkInEnabled();
1858 case LFUN_VC_CHECK_OUT:
1859 enable = doc_buffer && doc_buffer->lyxvc().checkOutEnabled();
1861 case LFUN_VC_LOCKING_TOGGLE:
1862 enable = doc_buffer && !doc_buffer->isReadonly()
1863 && doc_buffer->lyxvc().lockingToggleEnabled();
1864 flag.setOnOff(enable && doc_buffer->lyxvc().locking());
1866 case LFUN_VC_REVERT:
1867 enable = doc_buffer && doc_buffer->lyxvc().inUse() && !doc_buffer->isReadonly();
1869 case LFUN_VC_UNDO_LAST:
1870 enable = doc_buffer && doc_buffer->lyxvc().undoLastEnabled();
1872 case LFUN_VC_REPO_UPDATE:
1873 enable = doc_buffer && doc_buffer->lyxvc().repoUpdateEnabled();
1875 case LFUN_VC_COMMAND: {
1876 if (cmd.argument().empty())
1878 if (!doc_buffer && contains(cmd.getArg(0), 'D'))
1882 case LFUN_VC_COMPARE:
1883 enable = doc_buffer && doc_buffer->lyxvc().prepareFileRevisionEnabled();
1886 case LFUN_SERVER_GOTO_FILE_ROW:
1888 case LFUN_FORWARD_SEARCH:
1889 enable = !(lyxrc.forward_search_dvi.empty() && lyxrc.forward_search_pdf.empty());
1892 case LFUN_FILE_INSERT_PLAINTEXT:
1893 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
1894 enable = documentBufferView() && documentBufferView()->cursor().inTexted();
1897 case LFUN_SPELLING_CONTINUOUSLY:
1898 flag.setOnOff(lyxrc.spellcheck_continuously);
1906 flag.setEnabled(false);
1912 static FileName selectTemplateFile()
1914 FileDialog dlg(qt_("Select template file"));
1915 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1916 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
1918 FileDialog::Result result = dlg.open(toqstr(lyxrc.template_path),
1919 QStringList(qt_("LyX Documents (*.lyx)")));
1921 if (result.first == FileDialog::Later)
1923 if (result.second.isEmpty())
1925 return FileName(fromqstr(result.second));
1929 Buffer * GuiView::loadDocument(FileName const & filename, bool tolastfiles)
1933 Buffer * newBuffer = 0;
1935 newBuffer = checkAndLoadLyXFile(filename);
1936 } catch (ExceptionMessage const & e) {
1943 message(_("Document not loaded."));
1947 setBuffer(newBuffer);
1948 newBuffer->errors("Parse");
1951 theSession().lastFiles().add(filename);
1957 void GuiView::openDocument(string const & fname)
1959 string initpath = lyxrc.document_path;
1961 if (documentBufferView()) {
1962 string const trypath = documentBufferView()->buffer().filePath();
1963 // If directory is writeable, use this as default.
1964 if (FileName(trypath).isDirWritable())
1970 if (fname.empty()) {
1971 FileDialog dlg(qt_("Select document to open"));
1972 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1973 dlg.setButton2(qt_("Examples|#E#e"),
1974 toqstr(addPath(package().system_support().absFileName(), "examples")));
1976 QStringList const filter(qt_("LyX Documents (*.lyx)"));
1977 FileDialog::Result result =
1978 dlg.open(toqstr(initpath), filter);
1980 if (result.first == FileDialog::Later)
1983 filename = fromqstr(result.second);
1985 // check selected filename
1986 if (filename.empty()) {
1987 message(_("Canceled."));
1993 // get absolute path of file and add ".lyx" to the filename if
1995 FileName const fullname =
1996 fileSearch(string(), filename, "lyx", support::may_not_exist);
1997 if (!fullname.empty())
1998 filename = fullname.absFileName();
2000 if (!fullname.onlyPath().isDirectory()) {
2001 Alert::warning(_("Invalid filename"),
2002 bformat(_("The directory in the given path\n%1$s\ndoes not exist."),
2003 from_utf8(fullname.absFileName())));
2007 // if the file doesn't exist and isn't already open (bug 6645),
2008 // let the user create one
2009 if (!fullname.exists() && !theBufferList().exists(fullname) &&
2010 !LyXVC::file_not_found_hook(fullname)) {
2011 // the user specifically chose this name. Believe him.
2012 Buffer * const b = newFile(filename, string(), true);
2018 docstring const disp_fn = makeDisplayPath(filename);
2019 message(bformat(_("Opening document %1$s..."), disp_fn));
2022 Buffer * buf = loadDocument(fullname);
2024 str2 = bformat(_("Document %1$s opened."), disp_fn);
2025 if (buf->lyxvc().inUse())
2026 str2 += " " + from_utf8(buf->lyxvc().versionString()) +
2027 " " + _("Version control detected.");
2029 str2 = bformat(_("Could not open document %1$s"), disp_fn);
2034 // FIXME: clean that
2035 static bool import(GuiView * lv, FileName const & filename,
2036 string const & format, ErrorList & errorList)
2038 FileName const lyxfile(support::changeExtension(filename.absFileName(), ".lyx"));
2040 string loader_format;
2041 vector<string> loaders = theConverters().loaders();
2042 if (find(loaders.begin(), loaders.end(), format) == loaders.end()) {
2043 vector<string>::const_iterator it = loaders.begin();
2044 vector<string>::const_iterator en = loaders.end();
2045 for (; it != en; ++it) {
2046 if (!theConverters().isReachable(format, *it))
2049 string const tofile =
2050 support::changeExtension(filename.absFileName(),
2051 formats.extension(*it));
2052 if (!theConverters().convert(0, filename, FileName(tofile),
2053 filename, format, *it, errorList))
2055 loader_format = *it;
2058 if (loader_format.empty()) {
2059 frontend::Alert::error(_("Couldn't import file"),
2060 bformat(_("No information for importing the format %1$s."),
2061 formats.prettyName(format)));
2065 loader_format = format;
2067 if (loader_format == "lyx") {
2068 Buffer * buf = lv->loadDocument(lyxfile);
2072 Buffer * const b = newFile(lyxfile.absFileName(), string(), true);
2076 bool as_paragraphs = loader_format == "textparagraph";
2077 string filename2 = (loader_format == format) ? filename.absFileName()
2078 : support::changeExtension(filename.absFileName(),
2079 formats.extension(loader_format));
2080 lv->currentBufferView()->insertPlaintextFile(FileName(filename2),
2082 guiApp->setCurrentView(lv);
2083 lyx::dispatch(FuncRequest(LFUN_MARK_OFF));
2090 void GuiView::importDocument(string const & argument)
2093 string filename = split(argument, format, ' ');
2095 LYXERR(Debug::INFO, format << " file: " << filename);
2097 // need user interaction
2098 if (filename.empty()) {
2099 string initpath = lyxrc.document_path;
2100 if (documentBufferView()) {
2101 string const trypath = documentBufferView()->buffer().filePath();
2102 // If directory is writeable, use this as default.
2103 if (FileName(trypath).isDirWritable())
2107 docstring const text = bformat(_("Select %1$s file to import"),
2108 formats.prettyName(format));
2110 FileDialog dlg(toqstr(text));
2111 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2112 dlg.setButton2(qt_("Examples|#E#e"),
2113 toqstr(addPath(package().system_support().absFileName(), "examples")));
2115 docstring filter = formats.prettyName(format);
2118 filter += from_utf8(formats.extensions(format));
2121 FileDialog::Result result =
2122 dlg.open(toqstr(initpath), fileFilters(toqstr(filter)));
2124 if (result.first == FileDialog::Later)
2127 filename = fromqstr(result.second);
2129 // check selected filename
2130 if (filename.empty())
2131 message(_("Canceled."));
2134 if (filename.empty())
2137 // get absolute path of file
2138 FileName const fullname(support::makeAbsPath(filename));
2140 // Can happen if the user entered a path into the dialog
2142 if (fullname.onlyFileName().empty()) {
2143 docstring msg = bformat(_("The file name '%1$s' is invalid!\n"
2144 "Aborting import."),
2145 from_utf8(fullname.absFileName()));
2146 frontend::Alert::error(_("File name error"), msg);
2147 message(_("Canceled."));
2152 FileName const lyxfile(support::changeExtension(fullname.absFileName(), ".lyx"));
2154 // Check if the document already is open
2155 Buffer * buf = theBufferList().getBuffer(lyxfile);
2158 if (!closeBuffer()) {
2159 message(_("Canceled."));
2164 docstring const displaypath = makeDisplayPath(lyxfile.absFileName(), 30);
2166 // if the file exists already, and we didn't do
2167 // -i lyx thefile.lyx, warn
2168 if (lyxfile.exists() && fullname != lyxfile) {
2170 docstring text = bformat(_("The document %1$s already exists.\n\n"
2171 "Do you want to overwrite that document?"), displaypath);
2172 int const ret = Alert::prompt(_("Overwrite document?"),
2173 text, 0, 1, _("&Overwrite"), _("&Cancel"));
2176 message(_("Canceled."));
2181 message(bformat(_("Importing %1$s..."), displaypath));
2182 ErrorList errorList;
2183 if (import(this, fullname, format, errorList))
2184 message(_("imported."));
2186 message(_("file not imported!"));
2188 // FIXME (Abdel 12/08/06): Is there a need to display the error list here?
2192 void GuiView::newDocument(string const & filename, bool from_template)
2194 FileName initpath(lyxrc.document_path);
2195 if (documentBufferView()) {
2196 FileName const trypath(documentBufferView()->buffer().filePath());
2197 // If directory is writeable, use this as default.
2198 if (trypath.isDirWritable())
2202 string templatefile;
2203 if (from_template) {
2204 templatefile = selectTemplateFile().absFileName();
2205 if (templatefile.empty())
2210 if (filename.empty())
2211 b = newUnnamedFile(initpath, to_utf8(_("newfile")), templatefile);
2213 b = newFile(filename, templatefile, true);
2218 // If no new document could be created, it is unsure
2219 // whether there is a valid BufferView.
2220 if (currentBufferView())
2221 // Ensure the cursor is correctly positioned on screen.
2222 currentBufferView()->showCursor();
2226 void GuiView::insertLyXFile(docstring const & fname)
2228 BufferView * bv = documentBufferView();
2233 FileName filename(to_utf8(fname));
2234 if (filename.empty()) {
2235 // Launch a file browser
2237 string initpath = lyxrc.document_path;
2238 string const trypath = bv->buffer().filePath();
2239 // If directory is writeable, use this as default.
2240 if (FileName(trypath).isDirWritable())
2244 FileDialog dlg(qt_("Select LyX document to insert"));
2245 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2246 dlg.setButton2(qt_("Examples|#E#e"),
2247 toqstr(addPath(package().system_support().absFileName(),
2250 FileDialog::Result result = dlg.open(toqstr(initpath),
2251 QStringList(qt_("LyX Documents (*.lyx)")));
2253 if (result.first == FileDialog::Later)
2257 filename.set(fromqstr(result.second));
2259 // check selected filename
2260 if (filename.empty()) {
2261 // emit message signal.
2262 message(_("Canceled."));
2267 bv->insertLyXFile(filename);
2268 bv->buffer().errors("Parse");
2272 bool GuiView::renameBuffer(Buffer & b, docstring const & newname, RenameKind kind)
2274 FileName fname = b.fileName();
2275 FileName const oldname = fname;
2277 if (!newname.empty()) {
2279 fname = support::makeAbsPath(to_utf8(newname), oldname.onlyPath().absFileName());
2281 // Switch to this Buffer.
2284 // No argument? Ask user through dialog.
2286 FileDialog dlg(qt_("Choose a filename to save document as"));
2287 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2288 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
2290 if (!isLyXFileName(fname.absFileName()))
2291 fname.changeExtension(".lyx");
2293 FileDialog::Result result =
2294 dlg.save(toqstr(fname.onlyPath().absFileName()),
2295 QStringList(qt_("LyX Documents (*.lyx)")),
2296 toqstr(fname.onlyFileName()));
2298 if (result.first == FileDialog::Later)
2301 fname.set(fromqstr(result.second));
2306 if (!isLyXFileName(fname.absFileName()))
2307 fname.changeExtension(".lyx");
2310 // fname is now the new Buffer location.
2312 // if there is already a Buffer open with this name, we do not want
2313 // to have another one. (the second test makes sure we're not just
2314 // trying to overwrite ourselves, which is fine.)
2315 if (theBufferList().exists(fname) && fname != oldname
2316 && theBufferList().getBuffer(fname) != &b) {
2317 docstring const text =
2318 bformat(_("The file\n%1$s\nis already open in your current session.\n"
2319 "Please close it before attempting to overwrite it.\n"
2320 "Do you want to choose a new filename?"),
2321 from_utf8(fname.absFileName()));
2322 int const ret = Alert::prompt(_("Chosen File Already Open"),
2323 text, 0, 1, _("&Rename"), _("&Cancel"));
2325 case 0: return renameBuffer(b, docstring(), kind);
2326 case 1: return false;
2331 bool const existsLocal = fname.exists();
2332 bool const existsInVC = LyXVC::fileInVC(fname);
2333 if (existsLocal || existsInVC) {
2334 docstring const file = makeDisplayPath(fname.absFileName(), 30);
2335 if (kind != LV_WRITE_AS && existsInVC) {
2336 // renaming to a name that is already in VC
2338 docstring text = bformat(_("The document %1$s "
2339 "is already registered.\n\n"
2340 "Do you want to choose a new name?"),
2342 docstring const title = (kind == LV_VC_RENAME) ?
2343 _("Rename document?") : _("Copy document?");
2344 docstring const button = (kind == LV_VC_RENAME) ?
2345 _("&Rename") : _("&Copy");
2346 int const ret = Alert::prompt(title, text, 0, 1,
2347 button, _("&Cancel"));
2349 case 0: return renameBuffer(b, docstring(), kind);
2350 case 1: return false;
2355 docstring text = bformat(_("The document %1$s "
2356 "already exists.\n\n"
2357 "Do you want to overwrite that document?"),
2359 int const ret = Alert::prompt(_("Overwrite document?"),
2360 text, 0, 2, _("&Overwrite"),
2361 _("&Rename"), _("&Cancel"));
2364 case 1: return renameBuffer(b, docstring(), kind);
2365 case 2: return false;
2371 case LV_VC_RENAME: {
2372 string msg = b.lyxvc().rename(fname);
2375 message(from_utf8(msg));
2379 string msg = b.lyxvc().copy(fname);
2382 message(from_utf8(msg));
2388 // LyXVC created the file already in case of LV_VC_RENAME or
2389 // LV_VC_COPY, but call saveBuffer() nevertheless to get
2390 // relative paths of included stuff right if we moved e.g. from
2391 // /a/b.lyx to /a/c/b.lyx.
2393 bool const saved = saveBuffer(b, fname);
2400 struct PrettyNameComparator
2402 bool operator()(Format const *first, Format const *second) const {
2403 return compare_no_case(translateIfPossible(from_ascii(first->prettyname())),
2404 translateIfPossible(from_ascii(second->prettyname()))) <= 0;
2409 bool GuiView::exportBufferAs(Buffer & b, docstring const & iformat)
2411 FileName fname = b.fileName();
2413 FileDialog dlg(qt_("Choose a filename to export the document as"));
2414 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2417 QString const anyformat = qt_("Guess from extension (*.*)");
2419 Formats::const_iterator it = formats.begin();
2420 vector<Format const *> export_formats;
2421 for (; it != formats.end(); ++it)
2422 if (it->documentFormat())
2423 export_formats.push_back(&(*it));
2424 PrettyNameComparator cmp;
2425 sort(export_formats.begin(), export_formats.end(), cmp);
2426 vector<Format const *>::const_iterator fit = export_formats.begin();
2427 map<QString, string> fmap;
2430 for (; fit != export_formats.end(); ++fit) {
2431 docstring const loc_prettyname =
2432 translateIfPossible(from_utf8((*fit)->prettyname()));
2433 QString const loc_filter = toqstr(bformat(from_ascii("%1$s (*.%2$s)"),
2435 from_ascii((*fit)->extension())));
2436 types << loc_filter;
2437 fmap[loc_filter] = (*fit)->name();
2438 if (from_ascii((*fit)->name()) == iformat) {
2439 filter = loc_filter;
2440 ext = (*fit)->extension();
2443 string ofname = fname.onlyFileName();
2445 ofname = support::changeExtension(ofname, ext);
2446 FileDialog::Result result =
2447 dlg.save(toqstr(fname.onlyPath().absFileName()),
2451 if (result.first != FileDialog::Chosen)
2455 fname.set(fromqstr(result.second));
2456 if (filter == anyformat)
2457 fmt_name = formats.getFormatFromExtension(fname.extension());
2459 fmt_name = fmap[filter];
2460 LYXERR(Debug::FILES, "filter=" << fromqstr(filter)
2461 << ", fmt_name=" << fmt_name << ", fname=" << fname.absFileName());
2463 if (fmt_name.empty() || fname.empty())
2466 // fname is now the new Buffer location.
2467 if (FileName(fname).exists()) {
2468 docstring const file = makeDisplayPath(fname.absFileName(), 30);
2469 docstring text = bformat(_("The document %1$s already "
2470 "exists.\n\nDo you want to "
2471 "overwrite that document?"),
2473 int const ret = Alert::prompt(_("Overwrite document?"),
2474 text, 0, 2, _("&Overwrite"), _("&Rename"), _("&Cancel"));
2477 case 1: return exportBufferAs(b, from_ascii(fmt_name));
2478 case 2: return false;
2482 FuncRequest cmd(LFUN_BUFFER_EXPORT, fmt_name + " " + fname.absFileName());
2485 return dr.dispatched();
2489 bool GuiView::saveBuffer(Buffer & b)
2491 return saveBuffer(b, FileName());
2495 bool GuiView::saveBuffer(Buffer & b, FileName const & fn)
2497 if (workArea(b) && workArea(b)->inDialogMode())
2500 if (fn.empty() && b.isUnnamed())
2501 return renameBuffer(b, docstring());
2503 bool const success = (fn.empty() ? b.save() : b.saveAs(fn));
2505 theSession().lastFiles().add(b.fileName());
2509 // Switch to this Buffer.
2512 // FIXME: we don't tell the user *WHY* the save failed !!
2513 docstring const file = makeDisplayPath(b.absFileName(), 30);
2514 docstring text = bformat(_("The document %1$s could not be saved.\n\n"
2515 "Do you want to rename the document and "
2516 "try again?"), file);
2517 int const ret = Alert::prompt(_("Rename and save?"),
2518 text, 0, 2, _("&Rename"), _("&Retry"), _("&Cancel"));
2521 if (!renameBuffer(b, docstring()))
2530 return saveBuffer(b, fn);
2534 bool GuiView::hideWorkArea(GuiWorkArea * wa)
2536 return closeWorkArea(wa, false);
2540 // We only want to close the buffer if it is not visible in other workareas
2541 // of the same view, nor in other views, and if this is not a child
2542 bool GuiView::closeWorkArea(GuiWorkArea * wa)
2544 Buffer & buf = wa->bufferView().buffer();
2546 bool last_wa = d.countWorkAreasOf(buf) == 1
2547 && !inOtherView(buf) && !buf.parent();
2549 bool close_buffer = last_wa;
2552 if (lyxrc.close_buffer_with_last_view == "yes")
2554 else if (lyxrc.close_buffer_with_last_view == "no")
2555 close_buffer = false;
2558 if (buf.isUnnamed())
2559 file = from_utf8(buf.fileName().onlyFileName());
2561 file = buf.fileName().displayName(30);
2562 docstring const text = bformat(
2563 _("Last view on document %1$s is being closed.\n"
2564 "Would you like to close or hide the document?\n"
2566 "Hidden documents can be displayed back through\n"
2567 "the menu: View->Hidden->...\n"
2569 "To remove this question, set your preference in:\n"
2570 " Tools->Preferences->Look&Feel->UserInterface\n"
2572 int ret = Alert::prompt(_("Close or hide document?"),
2573 text, 0, 1, _("&Close"), _("&Hide"));
2574 close_buffer = (ret == 0);
2578 return closeWorkArea(wa, close_buffer);
2582 bool GuiView::closeBuffer()
2584 GuiWorkArea * wa = currentMainWorkArea();
2585 setCurrentWorkArea(wa);
2586 Buffer & buf = wa->bufferView().buffer();
2587 return wa && closeWorkArea(wa, !buf.parent());
2591 void GuiView::writeSession() const {
2592 GuiWorkArea const * active_wa = currentMainWorkArea();
2593 for (int i = 0; i < d.splitter_->count(); ++i) {
2594 TabWorkArea * twa = d.tabWorkArea(i);
2595 for (int j = 0; j < twa->count(); ++j) {
2596 GuiWorkArea * wa = static_cast<GuiWorkArea *>(twa->widget(j));
2597 Buffer & buf = wa->bufferView().buffer();
2598 theSession().lastOpened().add(buf.fileName(), wa == active_wa);
2604 bool GuiView::closeBufferAll()
2606 // Close the workareas in all other views
2607 QList<int> const ids = guiApp->viewIds();
2608 for (int i = 0; i != ids.size(); ++i) {
2609 if (id_ != ids[i] && !guiApp->view(ids[i]).closeWorkAreaAll())
2613 // Close our own workareas
2614 if (!closeWorkAreaAll())
2617 // Now close the hidden buffers. We prevent hidden buffers from being
2618 // dirty, so we can just close them.
2619 theBufferList().closeAll();
2624 bool GuiView::closeWorkAreaAll()
2626 setCurrentWorkArea(currentMainWorkArea());
2628 // We might be in a situation that there is still a tabWorkArea, but
2629 // there are no tabs anymore. This can happen when we get here after a
2630 // TabWorkArea::lastWorkAreaRemoved() signal. Therefore we count how
2631 // many TabWorkArea's have no documents anymore.
2634 // We have to call count() each time, because it can happen that
2635 // more than one splitter will disappear in one iteration (bug 5998).
2636 for (; d.splitter_->count() > empty_twa; ) {
2637 TabWorkArea * twa = d.tabWorkArea(empty_twa);
2639 if (twa->count() == 0)
2642 setCurrentWorkArea(twa->currentWorkArea());
2643 if (!closeTabWorkArea(twa))
2651 bool GuiView::closeWorkArea(GuiWorkArea * wa, bool close_buffer)
2656 Buffer & buf = wa->bufferView().buffer();
2658 if (close_buffer && GuiViewPrivate::busyBuffers.contains(&buf)) {
2659 Alert::warning(_("Close document"),
2660 _("Document could not be closed because it is being processed by LyX."));
2665 return closeBuffer(buf);
2667 if (!inMultiTabs(wa))
2668 if (!saveBufferIfNeeded(buf, true))
2676 bool GuiView::closeBuffer(Buffer & buf)
2678 // If we are in a close_event all children will be closed in some time,
2679 // so no need to do it here. This will ensure that the children end up
2680 // in the session file in the correct order. If we close the master
2681 // buffer, we can close or release the child buffers here too.
2682 bool success = true;
2684 ListOfBuffers clist = buf.getChildren();
2685 ListOfBuffers::const_iterator it = clist.begin();
2686 ListOfBuffers::const_iterator const bend = clist.end();
2687 for (; it != bend; ++it) {
2688 // If a child is dirty, do not close
2689 // without user intervention
2690 //FIXME: should we look in other tabworkareas?
2691 Buffer * child_buf = *it;
2692 GuiWorkArea * child_wa = workArea(*child_buf);
2694 if (!closeWorkArea(child_wa, true)) {
2699 theBufferList().releaseChild(&buf, child_buf);
2703 // goto bookmark to update bookmark pit.
2704 //FIXME: we should update only the bookmarks related to this buffer!
2705 LYXERR(Debug::DEBUG, "GuiView::closeBuffer()");
2706 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
2707 guiApp->gotoBookmark(i+1, false, false);
2709 if (saveBufferIfNeeded(buf, false)) {
2710 buf.removeAutosaveFile();
2711 theBufferList().release(&buf);
2715 // open all children again to avoid a crash because of dangling
2716 // pointers (bug 6603)
2722 bool GuiView::closeTabWorkArea(TabWorkArea * twa)
2724 while (twa == d.currentTabWorkArea()) {
2725 twa->setCurrentIndex(twa->count()-1);
2727 GuiWorkArea * wa = twa->currentWorkArea();
2728 Buffer & b = wa->bufferView().buffer();
2730 // We only want to close the buffer if the same buffer is not visible
2731 // in another view, and if this is not a child and if we are closing
2732 // a view (not a tabgroup).
2733 bool const close_buffer =
2734 !inOtherView(b) && !b.parent() && closing_;
2736 if (!closeWorkArea(wa, close_buffer))
2743 bool GuiView::saveBufferIfNeeded(Buffer & buf, bool hiding)
2745 if (buf.isClean() || buf.paragraphs().empty())
2748 // Switch to this Buffer.
2753 if (buf.isUnnamed())
2754 file = from_utf8(buf.fileName().onlyFileName());
2756 file = buf.fileName().displayName(30);
2758 // Bring this window to top before asking questions.
2763 if (hiding && buf.isUnnamed()) {
2764 docstring const text = bformat(_("The document %1$s has not been "
2765 "saved yet.\n\nDo you want to save "
2766 "the document?"), file);
2767 ret = Alert::prompt(_("Save new document?"),
2768 text, 0, 1, _("&Save"), _("&Cancel"));
2772 docstring const text = bformat(_("The document %1$s has unsaved changes."
2773 "\n\nDo you want to save the document or discard the changes?"), file);
2774 ret = Alert::prompt(_("Save changed document?"),
2775 text, 0, 2, _("&Save"), _("&Discard"), _("&Cancel"));
2780 if (!saveBuffer(buf))
2784 // If we crash after this we could have no autosave file
2785 // but I guess this is really improbable (Jug).
2786 // Sometimes improbable things happen:
2787 // - see bug http://www.lyx.org/trac/ticket/6587 (ps)
2788 // buf.removeAutosaveFile();
2790 // revert all changes
2801 bool GuiView::inMultiTabs(GuiWorkArea * wa)
2803 Buffer & buf = wa->bufferView().buffer();
2805 for (int i = 0; i != d.splitter_->count(); ++i) {
2806 GuiWorkArea * wa_ = d.tabWorkArea(i)->workArea(buf);
2807 if (wa_ && wa_ != wa)
2810 return inOtherView(buf);
2814 bool GuiView::inOtherView(Buffer & buf)
2816 QList<int> const ids = guiApp->viewIds();
2818 for (int i = 0; i != ids.size(); ++i) {
2822 if (guiApp->view(ids[i]).workArea(buf))
2829 void GuiView::gotoNextOrPreviousBuffer(NextOrPrevious np)
2831 if (!documentBufferView())
2834 if (TabWorkArea * twa = d.currentTabWorkArea()) {
2835 Buffer * const curbuf = &documentBufferView()->buffer();
2836 int nwa = twa->count();
2837 for (int i = 0; i < nwa; ++i) {
2838 if (&workArea(i)->bufferView().buffer() == curbuf) {
2840 if (np == NEXTBUFFER)
2841 next_index = (i == nwa - 1 ? 0 : i + 1);
2843 next_index = (i == 0 ? nwa - 1 : i - 1);
2844 setBuffer(&workArea(next_index)->bufferView().buffer());
2852 /// make sure the document is saved
2853 static bool ensureBufferClean(Buffer * buffer)
2855 LASSERT(buffer, return false);
2856 if (buffer->isClean() && !buffer->isUnnamed())
2859 docstring const file = buffer->fileName().displayName(30);
2862 if (!buffer->isUnnamed()) {
2863 text = bformat(_("The document %1$s has unsaved "
2864 "changes.\n\nDo you want to save "
2865 "the document?"), file);
2866 title = _("Save changed document?");
2869 text = bformat(_("The document %1$s has not been "
2870 "saved yet.\n\nDo you want to save "
2871 "the document?"), file);
2872 title = _("Save new document?");
2874 int const ret = Alert::prompt(title, text, 0, 1, _("&Save"), _("&Cancel"));
2877 dispatch(FuncRequest(LFUN_BUFFER_WRITE));
2879 return buffer->isClean() && !buffer->isUnnamed();
2883 bool GuiView::reloadBuffer(Buffer & buf)
2885 Buffer::ReadStatus status = buf.reload();
2886 return status == Buffer::ReadSuccess;
2890 void GuiView::checkExternallyModifiedBuffers()
2892 BufferList::iterator bit = theBufferList().begin();
2893 BufferList::iterator const bend = theBufferList().end();
2894 for (; bit != bend; ++bit) {
2895 Buffer * buf = *bit;
2896 if (buf->fileName().exists()
2897 && buf->isExternallyModified(Buffer::checksum_method)) {
2898 docstring text = bformat(_("Document \n%1$s\n has been externally modified."
2899 " Reload now? Any local changes will be lost."),
2900 from_utf8(buf->absFileName()));
2901 int const ret = Alert::prompt(_("Reload externally changed document?"),
2902 text, 0, 1, _("&Reload"), _("&Cancel"));
2910 void GuiView::dispatchVC(FuncRequest const & cmd, DispatchResult & dr)
2912 Buffer * buffer = documentBufferView()
2913 ? &(documentBufferView()->buffer()) : 0;
2915 switch (cmd.action()) {
2916 case LFUN_VC_REGISTER:
2917 if (!buffer || !ensureBufferClean(buffer))
2919 if (!buffer->lyxvc().inUse()) {
2920 if (buffer->lyxvc().registrer()) {
2921 reloadBuffer(*buffer);
2922 dr.clearMessageUpdate();
2927 case LFUN_VC_RENAME:
2928 case LFUN_VC_COPY: {
2929 if (!buffer || !ensureBufferClean(buffer))
2931 if (buffer->lyxvc().inUse() && !buffer->isReadonly()) {
2932 if (buffer->lyxvc().isCheckInWithConfirmation()) {
2933 // Some changes are not yet committed.
2934 // We test here and not in getStatus(), since
2935 // this test is expensive.
2937 LyXVC::CommandResult ret =
2938 buffer->lyxvc().checkIn(log);
2940 if (ret == LyXVC::ErrorCommand ||
2941 ret == LyXVC::VCSuccess)
2942 reloadBuffer(*buffer);
2943 if (buffer->lyxvc().isCheckInWithConfirmation()) {
2944 frontend::Alert::error(
2945 _("Revision control error."),
2946 _("Document could not be checked in."));
2950 RenameKind const kind = (cmd.action() == LFUN_VC_RENAME) ?
2951 LV_VC_RENAME : LV_VC_COPY;
2952 renameBuffer(*buffer, cmd.argument(), kind);
2957 case LFUN_VC_CHECK_IN:
2958 if (!buffer || !ensureBufferClean(buffer))
2960 if (buffer->lyxvc().inUse() && !buffer->isReadonly()) {
2962 LyXVC::CommandResult ret = buffer->lyxvc().checkIn(log);
2964 // Only skip reloading if the checkin was cancelled or
2965 // an error occured before the real checkin VCS command
2966 // was executed, since the VCS might have changed the
2967 // file even if it could not checkin successfully.
2968 if (ret == LyXVC::ErrorCommand || ret == LyXVC::VCSuccess)
2969 reloadBuffer(*buffer);
2973 case LFUN_VC_CHECK_OUT:
2974 if (!buffer || !ensureBufferClean(buffer))
2976 if (buffer->lyxvc().inUse()) {
2977 dr.setMessage(buffer->lyxvc().checkOut());
2978 reloadBuffer(*buffer);
2982 case LFUN_VC_LOCKING_TOGGLE:
2983 LASSERT(buffer, return);
2984 if (!ensureBufferClean(buffer) || buffer->isReadonly())
2986 if (buffer->lyxvc().inUse()) {
2987 string res = buffer->lyxvc().lockingToggle();
2989 frontend::Alert::error(_("Revision control error."),
2990 _("Error when setting the locking property."));
2993 reloadBuffer(*buffer);
2998 case LFUN_VC_REVERT:
2999 LASSERT(buffer, return);
3000 if (buffer->lyxvc().revert()) {
3001 reloadBuffer(*buffer);
3002 dr.clearMessageUpdate();
3006 case LFUN_VC_UNDO_LAST:
3007 LASSERT(buffer, return);
3008 buffer->lyxvc().undoLast();
3009 reloadBuffer(*buffer);
3010 dr.clearMessageUpdate();
3013 case LFUN_VC_REPO_UPDATE:
3014 LASSERT(buffer, return);
3015 if (ensureBufferClean(buffer)) {
3016 dr.setMessage(buffer->lyxvc().repoUpdate());
3017 checkExternallyModifiedBuffers();
3021 case LFUN_VC_COMMAND: {
3022 string flag = cmd.getArg(0);
3023 if (buffer && contains(flag, 'R') && !ensureBufferClean(buffer))
3026 if (contains(flag, 'M')) {
3027 if (!Alert::askForText(message, _("LyX VC: Log Message")))
3030 string path = cmd.getArg(1);
3031 if (contains(path, "$$p") && buffer)
3032 path = subst(path, "$$p", buffer->filePath());
3033 LYXERR(Debug::LYXVC, "Directory: " << path);
3035 if (!pp.isReadableDirectory()) {
3036 lyxerr << _("Directory is not accessible.") << endl;
3039 support::PathChanger p(pp);
3041 string command = cmd.getArg(2);
3042 if (command.empty())
3045 command = subst(command, "$$i", buffer->absFileName());
3046 command = subst(command, "$$p", buffer->filePath());
3048 command = subst(command, "$$m", to_utf8(message));
3049 LYXERR(Debug::LYXVC, "Command: " << command);
3051 one.startscript(Systemcall::Wait, command);
3055 if (contains(flag, 'I'))
3056 buffer->markDirty();
3057 if (contains(flag, 'R'))
3058 reloadBuffer(*buffer);
3063 case LFUN_VC_COMPARE: {
3065 if (cmd.argument().empty()) {
3066 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "comparehistory"));
3070 string rev1 = cmd.getArg(0);
3074 if (!buffer->lyxvc().prepareFileRevision(rev1, f1))
3077 if (isStrInt(rev1) && convert<int>(rev1) <= 0) {
3078 f2 = buffer->absFileName();
3080 string rev2 = cmd.getArg(1);
3084 if (!buffer->lyxvc().prepareFileRevision(rev2, f2))
3088 LYXERR(Debug::LYXVC, "Launching comparison for fetched revisions:\n" <<
3089 f1 << "\n" << f2 << "\n" );
3090 string par = "compare run " + quoteName(f1) + " " + quoteName(f2);
3091 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, par));
3101 void GuiView::openChildDocument(string const & fname)
3103 LASSERT(documentBufferView(), return);
3104 Buffer & buffer = documentBufferView()->buffer();
3105 FileName const filename = support::makeAbsPath(fname, buffer.filePath());
3106 documentBufferView()->saveBookmark(false);
3108 if (theBufferList().exists(filename)) {
3109 child = theBufferList().getBuffer(filename);
3112 message(bformat(_("Opening child document %1$s..."),
3113 makeDisplayPath(filename.absFileName())));
3114 child = loadDocument(filename, false);
3116 // Set the parent name of the child document.
3117 // This makes insertion of citations and references in the child work,
3118 // when the target is in the parent or another child document.
3120 child->setParent(&buffer);
3124 bool GuiView::goToFileRow(string const & argument)
3128 size_t i = argument.find_last_of(' ');
3129 if (i != string::npos) {
3130 file_name = os::internal_path(trim(argument.substr(0, i)));
3131 istringstream is(argument.substr(i + 1));
3136 if (i == string::npos) {
3137 LYXERR0("Wrong argument: " << argument);
3141 string const abstmp = package().temp_dir().absFileName();
3142 string const realtmp = package().temp_dir().realPath();
3143 // We have to use os::path_prefix_is() here, instead of
3144 // simply prefixIs(), because the file name comes from
3145 // an external application and may need case adjustment.
3146 if (os::path_prefix_is(file_name, abstmp, os::CASE_ADJUSTED)
3147 || os::path_prefix_is(file_name, realtmp, os::CASE_ADJUSTED)) {
3148 // Needed by inverse dvi search. If it is a file
3149 // in tmpdir, call the apropriated function.
3150 // If tmpdir is a symlink, we may have the real
3151 // path passed back, so we correct for that.
3152 if (!prefixIs(file_name, abstmp))
3153 file_name = subst(file_name, realtmp, abstmp);
3154 buf = theBufferList().getBufferFromTmp(file_name);
3156 // Must replace extension of the file to be .lyx
3157 // and get full path
3158 FileName const s = fileSearch(string(),
3159 support::changeExtension(file_name, ".lyx"), "lyx");
3160 // Either change buffer or load the file
3161 if (theBufferList().exists(s))
3162 buf = theBufferList().getBuffer(s);
3163 else if (s.exists()) {
3164 buf = loadDocument(s);
3169 _("File does not exist: %1$s"),
3170 makeDisplayPath(file_name)));
3176 _("No buffer for file: %1$s."),
3177 makeDisplayPath(file_name))
3182 documentBufferView()->setCursorFromRow(row);
3188 Buffer::ExportStatus GuiView::GuiViewPrivate::runAndDestroy(const T& func, Buffer const * orig, Buffer * clone, string const & format)
3190 Buffer::ExportStatus const status = func(format);
3192 // the cloning operation will have produced a clone of the entire set of
3193 // documents, starting from the master. so we must delete those.
3194 Buffer * mbuf = const_cast<Buffer *>(clone->masterBuffer());
3196 busyBuffers.remove(orig);
3201 Buffer::ExportStatus GuiView::GuiViewPrivate::compileAndDestroy(Buffer const * orig, Buffer * clone, string const & format)
3203 Buffer::ExportStatus (Buffer::* mem_func)(std::string const &, bool) const = &Buffer::doExport;
3204 return runAndDestroy(lyx::bind(mem_func, clone, _1, true), orig, clone, format);
3208 Buffer::ExportStatus GuiView::GuiViewPrivate::exportAndDestroy(Buffer const * orig, Buffer * clone, string const & format)
3210 Buffer::ExportStatus (Buffer::* mem_func)(std::string const &, bool) const = &Buffer::doExport;
3211 return runAndDestroy(lyx::bind(mem_func, clone, _1, false), orig, clone, format);
3215 Buffer::ExportStatus GuiView::GuiViewPrivate::previewAndDestroy(Buffer const * orig, Buffer * clone, string const & format)
3217 Buffer::ExportStatus (Buffer::* mem_func)(std::string const &) const = &Buffer::preview;
3218 return runAndDestroy(lyx::bind(mem_func, clone, _1), orig, clone, format);
3222 bool GuiView::GuiViewPrivate::asyncBufferProcessing(
3223 string const & argument,
3224 Buffer const * used_buffer,
3225 docstring const & msg,
3226 Buffer::ExportStatus (*asyncFunc)(Buffer const *, Buffer *, string const &),
3227 Buffer::ExportStatus (Buffer::*syncFunc)(string const &, bool) const,
3228 Buffer::ExportStatus (Buffer::*previewFunc)(string const &) const)
3233 string format = argument;
3235 format = used_buffer->params().getDefaultOutputFormat();
3236 processing_format = format;
3237 #if EXPORT_in_THREAD
3239 progress_->clearMessages();
3242 GuiViewPrivate::busyBuffers.insert(used_buffer);
3243 Buffer * cloned_buffer = used_buffer->cloneFromMaster();
3244 if (!cloned_buffer) {
3245 Alert::error(_("Export Error"),
3246 _("Error cloning the Buffer."));
3249 QFuture<Buffer::ExportStatus> f = QtConcurrent::run(
3254 setPreviewFuture(f);
3255 last_export_format = used_buffer->params().bufferFormat();
3258 // We are asynchronous, so we don't know here anything about the success
3261 Buffer::ExportStatus status;
3263 // TODO check here if it breaks exporting with Qt < 4.4
3264 status = (used_buffer->*syncFunc)(format, true);
3265 } else if (previewFunc) {
3266 status = (used_buffer->*previewFunc)(format);
3269 handleExportStatus(gv_, status, format);
3271 return (status == Buffer::ExportSuccess
3272 || status == Buffer::PreviewSuccess);
3276 void GuiView::dispatchToBufferView(FuncRequest const & cmd, DispatchResult & dr)
3278 BufferView * bv = currentBufferView();
3279 LASSERT(bv, return);
3281 // Let the current BufferView dispatch its own actions.
3282 bv->dispatch(cmd, dr);
3283 if (dr.dispatched())
3286 // Try with the document BufferView dispatch if any.
3287 BufferView * doc_bv = documentBufferView();
3288 if (doc_bv && doc_bv != bv) {
3289 doc_bv->dispatch(cmd, dr);
3290 if (dr.dispatched())
3294 // Then let the current Cursor dispatch its own actions.
3295 bv->cursor().dispatch(cmd);
3297 // update completion. We do it here and not in
3298 // processKeySym to avoid another redraw just for a
3299 // changed inline completion
3300 if (cmd.origin() == FuncRequest::KEYBOARD) {
3301 if (cmd.action() == LFUN_SELF_INSERT
3302 || (cmd.action() == LFUN_ERT_INSERT && bv->cursor().inMathed()))
3303 updateCompletion(bv->cursor(), true, true);
3304 else if (cmd.action() == LFUN_CHAR_DELETE_BACKWARD)
3305 updateCompletion(bv->cursor(), false, true);
3307 updateCompletion(bv->cursor(), false, false);
3310 dr = bv->cursor().result();
3314 void GuiView::dispatch(FuncRequest const & cmd, DispatchResult & dr)
3316 BufferView * bv = currentBufferView();
3317 // By default we won't need any update.
3318 dr.screenUpdate(Update::None);
3319 // assume cmd will be dispatched
3320 dr.dispatched(true);
3322 Buffer * doc_buffer = documentBufferView()
3323 ? &(documentBufferView()->buffer()) : 0;
3325 if (cmd.origin() == FuncRequest::TOC) {
3326 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
3327 // FIXME: do we need to pass a DispatchResult object here?
3328 toc->doDispatch(bv->cursor(), cmd);
3332 string const argument = to_utf8(cmd.argument());
3334 switch(cmd.action()) {
3335 case LFUN_BUFFER_CHILD_OPEN:
3336 openChildDocument(to_utf8(cmd.argument()));
3339 case LFUN_BUFFER_IMPORT:
3340 importDocument(to_utf8(cmd.argument()));
3343 case LFUN_BUFFER_EXPORT: {
3346 FileName target_dir = doc_buffer->fileName().onlyPath();
3347 string const dest = cmd.getArg(1);
3348 if (!dest.empty() && FileName::isAbsolute(dest))
3349 target_dir = FileName(support::onlyPath(dest));
3350 // GCC only sees strfwd.h when building merged
3351 if (::lyx::operator==(cmd.argument(), "custom")) {
3352 dispatch(FuncRequest(LFUN_DIALOG_SHOW, "sendto"), dr);
3355 if (!target_dir.isDirWritable()) {
3356 exportBufferAs(*doc_buffer, cmd.argument());
3359 /* TODO/Review: Is it a problem to also export the children?
3360 See the update_unincluded flag */
3361 d.asyncBufferProcessing(argument,
3364 &GuiViewPrivate::exportAndDestroy,
3367 // TODO Inform user about success
3371 case LFUN_BUFFER_EXPORT_AS: {
3372 LASSERT(doc_buffer, break);
3373 docstring f = cmd.argument();
3375 f = from_ascii(doc_buffer->params().getDefaultOutputFormat());
3376 exportBufferAs(*doc_buffer, f);
3380 case LFUN_BUFFER_UPDATE: {
3381 d.asyncBufferProcessing(argument,
3384 &GuiViewPrivate::compileAndDestroy,
3389 case LFUN_BUFFER_VIEW: {
3390 d.asyncBufferProcessing(argument,
3392 _("Previewing ..."),
3393 &GuiViewPrivate::previewAndDestroy,
3398 case LFUN_MASTER_BUFFER_UPDATE: {
3399 d.asyncBufferProcessing(argument,
3400 (doc_buffer ? doc_buffer->masterBuffer() : 0),
3402 &GuiViewPrivate::compileAndDestroy,
3407 case LFUN_MASTER_BUFFER_VIEW: {
3408 d.asyncBufferProcessing(argument,
3409 (doc_buffer ? doc_buffer->masterBuffer() : 0),
3411 &GuiViewPrivate::previewAndDestroy,
3412 0, &Buffer::preview);
3415 case LFUN_BUFFER_SWITCH: {
3416 string const file_name = to_utf8(cmd.argument());
3417 if (!FileName::isAbsolute(file_name)) {
3419 dr.setMessage(_("Absolute filename expected."));
3423 Buffer * buffer = theBufferList().getBuffer(FileName(file_name));
3426 dr.setMessage(_("Document not loaded"));
3430 // Do we open or switch to the buffer in this view ?
3431 if (workArea(*buffer)
3432 || lyxrc.open_buffers_in_tabs || !documentBufferView()) {
3437 // Look for the buffer in other views
3438 QList<int> const ids = guiApp->viewIds();
3440 for (; i != ids.size(); ++i) {
3441 GuiView & gv = guiApp->view(ids[i]);
3442 if (gv.workArea(*buffer)) {
3443 gv.activateWindow();
3444 gv.setBuffer(buffer);
3449 // If necessary, open a new window as a last resort
3450 if (i == ids.size()) {
3451 lyx::dispatch(FuncRequest(LFUN_WINDOW_NEW));
3457 case LFUN_BUFFER_NEXT:
3458 gotoNextOrPreviousBuffer(NEXTBUFFER);
3461 case LFUN_BUFFER_PREVIOUS:
3462 gotoNextOrPreviousBuffer(PREVBUFFER);
3465 case LFUN_COMMAND_EXECUTE: {
3466 bool const show_it = cmd.argument() != "off";
3467 // FIXME: this is a hack, "minibuffer" should not be
3469 if (GuiToolbar * t = toolbar("minibuffer")) {
3470 t->setVisible(show_it);
3471 if (show_it && t->commandBuffer())
3472 t->commandBuffer()->setFocus();
3476 case LFUN_DROP_LAYOUTS_CHOICE:
3477 d.layout_->showPopup();
3480 case LFUN_MENU_OPEN:
3481 if (QMenu * menu = guiApp->menus().menu(toqstr(cmd.argument()), *this))
3482 menu->exec(QCursor::pos());
3485 case LFUN_FILE_INSERT:
3486 insertLyXFile(cmd.argument());
3489 case LFUN_FILE_INSERT_PLAINTEXT:
3490 case LFUN_FILE_INSERT_PLAINTEXT_PARA: {
3491 string const fname = to_utf8(cmd.argument());
3492 if (!fname.empty() && !FileName::isAbsolute(fname)) {
3493 dr.setMessage(_("Absolute filename expected."));
3497 FileName filename(fname);
3498 if (fname.empty()) {
3499 FileDialog dlg(qt_("Select file to insert"));
3501 FileDialog::Result result = dlg.open(toqstr(bv->buffer().filePath()),
3502 QStringList(qt_("All Files (*)")));
3504 if (result.first == FileDialog::Later || result.second.isEmpty()) {
3505 dr.setMessage(_("Canceled."));
3509 filename.set(fromqstr(result.second));
3513 FuncRequest const new_cmd(cmd, filename.absoluteFilePath());
3514 bv->dispatch(new_cmd, dr);
3519 case LFUN_BUFFER_RELOAD: {
3520 LASSERT(doc_buffer, break);
3523 if (!doc_buffer->isClean()) {
3524 docstring const file =
3525 makeDisplayPath(doc_buffer->absFileName(), 20);
3526 docstring text = bformat(_("Any changes will be lost. "
3527 "Are you sure you want to revert to the saved version "
3528 "of the document %1$s?"), file);
3529 ret = Alert::prompt(_("Revert to saved document?"),
3530 text, 1, 1, _("&Revert"), _("&Cancel"));
3534 doc_buffer->markClean();
3535 reloadBuffer(*doc_buffer);
3536 dr.forceBufferUpdate();
3541 case LFUN_BUFFER_WRITE:
3542 LASSERT(doc_buffer, break);
3543 saveBuffer(*doc_buffer);
3546 case LFUN_BUFFER_WRITE_AS:
3547 LASSERT(doc_buffer, break);
3548 renameBuffer(*doc_buffer, cmd.argument());
3551 case LFUN_BUFFER_WRITE_ALL: {
3552 Buffer * first = theBufferList().first();
3555 message(_("Saving all documents..."));
3556 // We cannot use a for loop as the buffer list cycles.
3559 if (!b->isClean()) {
3561 LYXERR(Debug::ACTION, "Saved " << b->absFileName());
3563 b = theBufferList().next(b);
3564 } while (b != first);
3565 dr.setMessage(_("All documents saved."));
3569 case LFUN_BUFFER_CLOSE:
3573 case LFUN_BUFFER_CLOSE_ALL:
3577 case LFUN_TOOLBAR_TOGGLE: {
3578 string const name = cmd.getArg(0);
3579 if (GuiToolbar * t = toolbar(name))
3584 case LFUN_DIALOG_UPDATE: {
3585 string const name = to_utf8(cmd.argument());
3586 if (name == "prefs" || name == "document")
3587 updateDialog(name, string());
3588 else if (name == "paragraph")
3589 lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
3590 else if (currentBufferView()) {
3591 Inset * inset = currentBufferView()->editedInset(name);
3592 // Can only update a dialog connected to an existing inset
3594 // FIXME: get rid of this indirection; GuiView ask the inset
3595 // if he is kind enough to update itself...
3596 FuncRequest fr(LFUN_INSET_DIALOG_UPDATE, cmd.argument());
3597 //FIXME: pass DispatchResult here?
3598 inset->dispatch(currentBufferView()->cursor(), fr);
3604 case LFUN_DIALOG_TOGGLE: {
3605 FuncCode const func_code = isDialogVisible(cmd.getArg(0))
3606 ? LFUN_DIALOG_HIDE : LFUN_DIALOG_SHOW;
3607 dispatch(FuncRequest(func_code, cmd.argument()), dr);
3611 case LFUN_DIALOG_DISCONNECT_INSET:
3612 disconnectDialog(to_utf8(cmd.argument()));
3615 case LFUN_DIALOG_HIDE: {
3616 guiApp->hideDialogs(to_utf8(cmd.argument()), 0);
3620 case LFUN_DIALOG_SHOW: {
3621 string const name = cmd.getArg(0);
3622 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
3624 if (name == "character") {
3625 data = freefont2string();
3627 showDialog("character", data);
3628 } else if (name == "latexlog") {
3629 Buffer::LogType type;
3630 string const logfile = doc_buffer->logName(&type);
3632 case Buffer::latexlog:
3635 case Buffer::buildlog:
3639 data += Lexer::quoteString(logfile);
3640 showDialog("log", data);
3641 } else if (name == "vclog") {
3642 string const data = "vc " +
3643 Lexer::quoteString(doc_buffer->lyxvc().getLogFile());
3644 showDialog("log", data);
3645 } else if (name == "symbols") {
3646 data = bv->cursor().getEncoding()->name();
3648 showDialog("symbols", data);
3650 } else if (name == "prefs" && isFullScreen()) {
3651 lfunUiToggle("fullscreen");
3652 showDialog("prefs", data);
3654 showDialog(name, data);
3659 dr.setMessage(cmd.argument());
3662 case LFUN_UI_TOGGLE: {
3663 string arg = cmd.getArg(0);
3664 if (!lfunUiToggle(arg)) {
3665 docstring const msg = "ui-toggle " + _("%1$s unknown command!");
3666 dr.setMessage(bformat(msg, from_utf8(arg)));
3668 // Make sure the keyboard focus stays in the work area.
3673 case LFUN_VIEW_SPLIT: {
3674 LASSERT(doc_buffer, break);
3675 string const orientation = cmd.getArg(0);
3676 d.splitter_->setOrientation(orientation == "vertical"
3677 ? Qt::Vertical : Qt::Horizontal);
3678 TabWorkArea * twa = addTabWorkArea();
3679 GuiWorkArea * wa = twa->addWorkArea(*doc_buffer, *this);
3680 setCurrentWorkArea(wa);
3683 case LFUN_TAB_GROUP_CLOSE:
3684 if (TabWorkArea * twa = d.currentTabWorkArea()) {
3685 closeTabWorkArea(twa);
3686 d.current_work_area_ = 0;
3687 twa = d.currentTabWorkArea();
3688 // Switch to the next GuiWorkArea in the found TabWorkArea.
3690 // Make sure the work area is up to date.
3691 setCurrentWorkArea(twa->currentWorkArea());
3693 setCurrentWorkArea(0);
3698 case LFUN_VIEW_CLOSE:
3699 if (TabWorkArea * twa = d.currentTabWorkArea()) {
3700 closeWorkArea(twa->currentWorkArea());
3701 d.current_work_area_ = 0;
3702 twa = d.currentTabWorkArea();
3703 // Switch to the next GuiWorkArea in the found TabWorkArea.
3705 // Make sure the work area is up to date.
3706 setCurrentWorkArea(twa->currentWorkArea());
3708 setCurrentWorkArea(0);
3713 case LFUN_COMPLETION_INLINE:
3714 if (d.current_work_area_)
3715 d.current_work_area_->completer().showInline();
3718 case LFUN_COMPLETION_POPUP:
3719 if (d.current_work_area_)
3720 d.current_work_area_->completer().showPopup();
3725 if (d.current_work_area_)
3726 d.current_work_area_->completer().tab();
3729 case LFUN_COMPLETION_CANCEL:
3730 if (d.current_work_area_) {
3731 if (d.current_work_area_->completer().popupVisible())
3732 d.current_work_area_->completer().hidePopup();
3734 d.current_work_area_->completer().hideInline();
3738 case LFUN_COMPLETION_ACCEPT:
3739 if (d.current_work_area_)
3740 d.current_work_area_->completer().activate();
3743 case LFUN_BUFFER_ZOOM_IN:
3744 case LFUN_BUFFER_ZOOM_OUT:
3745 if (cmd.argument().empty()) {
3746 if (cmd.action() == LFUN_BUFFER_ZOOM_IN)
3751 lyxrc.zoom += convert<int>(cmd.argument());
3753 if (lyxrc.zoom < 10)
3756 // The global QPixmapCache is used in GuiPainter to cache text
3757 // painting so we must reset it.
3758 QPixmapCache::clear();
3759 guiApp->fontLoader().update();
3760 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
3763 case LFUN_VC_REGISTER:
3764 case LFUN_VC_RENAME:
3766 case LFUN_VC_CHECK_IN:
3767 case LFUN_VC_CHECK_OUT:
3768 case LFUN_VC_REPO_UPDATE:
3769 case LFUN_VC_LOCKING_TOGGLE:
3770 case LFUN_VC_REVERT:
3771 case LFUN_VC_UNDO_LAST:
3772 case LFUN_VC_COMMAND:
3773 case LFUN_VC_COMPARE:
3774 dispatchVC(cmd, dr);
3777 case LFUN_SERVER_GOTO_FILE_ROW:
3778 goToFileRow(to_utf8(cmd.argument()));
3781 case LFUN_FORWARD_SEARCH: {
3782 Buffer const * doc_master = doc_buffer->masterBuffer();
3783 FileName const path(doc_master->temppath());
3784 string const texname = doc_master->isChild(doc_buffer)
3785 ? DocFileName(changeExtension(
3786 doc_buffer->absFileName(),
3787 "tex")).mangledFileName()
3788 : doc_buffer->latexName();
3789 string const fulltexname =
3790 support::makeAbsPath(texname, doc_master->temppath()).absFileName();
3791 string const mastername =
3792 removeExtension(doc_master->latexName());
3793 FileName const dviname(addName(path.absFileName(),
3794 addExtension(mastername, "dvi")));
3795 FileName const pdfname(addName(path.absFileName(),
3796 addExtension(mastername, "pdf")));
3797 bool const have_dvi = dviname.exists();
3798 bool const have_pdf = pdfname.exists();
3799 if (!have_dvi && !have_pdf) {
3800 dr.setMessage(_("Please, preview the document first."));
3803 string outname = dviname.onlyFileName();
3804 string command = lyxrc.forward_search_dvi;
3805 if (!have_dvi || (have_pdf &&
3806 pdfname.lastModified() > dviname.lastModified())) {
3807 outname = pdfname.onlyFileName();
3808 command = lyxrc.forward_search_pdf;
3811 DocIterator tmpcur = bv->cursor();
3813 while (tmpcur.inMathed())
3815 int row = tmpcur.inMathed() ? 0 : doc_buffer->texrow().getRowFromIdPos(
3816 tmpcur.paragraph().id(), tmpcur.pos());
3817 LYXERR(Debug::ACTION, "Forward search: row:" << row
3818 << " id:" << tmpcur.paragraph().id());
3819 if (!row || command.empty()) {
3820 dr.setMessage(_("Couldn't proceed."));
3823 string texrow = convert<string>(row);
3825 command = subst(command, "$$n", texrow);
3826 command = subst(command, "$$f", fulltexname);
3827 command = subst(command, "$$t", texname);
3828 command = subst(command, "$$o", outname);
3830 PathChanger p(path);
3832 one.startscript(Systemcall::DontWait, command);
3836 case LFUN_SPELLING_CONTINUOUSLY:
3837 lyxrc.spellcheck_continuously = !lyxrc.spellcheck_continuously;
3838 dr.screenUpdate(Update::Force | Update::FitCursor);
3842 // The LFUN must be for one of BufferView, Buffer or Cursor;
3844 dispatchToBufferView(cmd, dr);
3848 // Part of automatic menu appearance feature.
3849 if (isFullScreen()) {
3850 if (menuBar()->isVisible() && lyxrc.full_screen_menubar)
3856 bool GuiView::lfunUiToggle(string const & ui_component)
3858 if (ui_component == "scrollbar") {
3859 // hide() is of no help
3860 if (d.current_work_area_->verticalScrollBarPolicy() ==
3861 Qt::ScrollBarAlwaysOff)
3863 d.current_work_area_->setVerticalScrollBarPolicy(
3864 Qt::ScrollBarAsNeeded);
3866 d.current_work_area_->setVerticalScrollBarPolicy(
3867 Qt::ScrollBarAlwaysOff);
3868 } else if (ui_component == "statusbar") {
3869 statusBar()->setVisible(!statusBar()->isVisible());
3870 } else if (ui_component == "menubar") {
3871 menuBar()->setVisible(!menuBar()->isVisible());
3873 if (ui_component == "frame") {
3875 getContentsMargins(&l, &t, &r, &b);
3876 //are the frames in default state?
3877 d.current_work_area_->setFrameStyle(QFrame::NoFrame);
3879 setContentsMargins(-2, -2, -2, -2);
3881 setContentsMargins(0, 0, 0, 0);
3884 if (ui_component == "fullscreen") {
3892 void GuiView::toggleFullScreen()
3894 if (isFullScreen()) {
3895 for (int i = 0; i != d.splitter_->count(); ++i)
3896 d.tabWorkArea(i)->setFullScreen(false);
3897 setContentsMargins(0, 0, 0, 0);
3898 setWindowState(windowState() ^ Qt::WindowFullScreen);
3901 statusBar()->show();
3904 hideDialogs("prefs", 0);
3905 for (int i = 0; i != d.splitter_->count(); ++i)
3906 d.tabWorkArea(i)->setFullScreen(true);
3907 setContentsMargins(-2, -2, -2, -2);
3909 setWindowState(windowState() ^ Qt::WindowFullScreen);
3910 if (lyxrc.full_screen_statusbar)
3911 statusBar()->hide();
3912 if (lyxrc.full_screen_menubar)
3914 if (lyxrc.full_screen_toolbars) {
3915 ToolbarMap::iterator end = d.toolbars_.end();
3916 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
3921 // give dialogs like the TOC a chance to adapt
3926 Buffer const * GuiView::updateInset(Inset const * inset)
3931 Buffer const * inset_buffer = &(inset->buffer());
3933 for (int i = 0; i != d.splitter_->count(); ++i) {
3934 GuiWorkArea * wa = d.tabWorkArea(i)->currentWorkArea();
3937 Buffer const * buffer = &(wa->bufferView().buffer());
3938 if (inset_buffer == buffer)
3939 wa->scheduleRedraw();
3941 return inset_buffer;
3945 void GuiView::restartCursor()
3947 /* When we move around, or type, it's nice to be able to see
3948 * the cursor immediately after the keypress.
3950 if (d.current_work_area_)
3951 d.current_work_area_->startBlinkingCursor();
3953 // Take this occasion to update the other GUI elements.
3959 void GuiView::updateCompletion(Cursor & cur, bool start, bool keep)
3961 if (d.current_work_area_)
3962 d.current_work_area_->completer().updateVisibility(cur, start, keep);
3967 // This list should be kept in sync with the list of insets in
3968 // src/insets/Inset.cpp. I.e., if a dialog goes with an inset, the
3969 // dialog should have the same name as the inset.
3970 // Changes should be also recorded in LFUN_DIALOG_SHOW doxygen
3971 // docs in LyXAction.cpp.
3973 char const * const dialognames[] = {
3975 "aboutlyx", "bibitem", "bibtex", "box", "branch", "changes", "character",
3976 "citation", "compare", "comparehistory", "document", "errorlist", "ert",
3977 "external", "file", "findreplace", "findreplaceadv", "float", "graphics",
3978 "href", "include", "index", "index_print", "info", "listings", "label", "line",
3979 "log", "mathdelimiter", "mathmatrix", "mathspace", "nomenclature",
3980 "nomencl_print", "note", "paragraph", "phantom", "prefs", "print", "ref",
3981 "sendto", "space", "spellchecker", "symbols", "tabular", "tabularcreate",
3982 "thesaurus", "texinfo", "toc", "view-source", "vspace", "wrap", "progress"};
3984 char const * const * const end_dialognames =
3985 dialognames + (sizeof(dialognames) / sizeof(char *));
3989 cmpCStr(char const * name) : name_(name) {}
3990 bool operator()(char const * other) {
3991 return strcmp(other, name_) == 0;
3998 bool isValidName(string const & name)
4000 return find_if(dialognames, end_dialognames,
4001 cmpCStr(name.c_str())) != end_dialognames;
4007 void GuiView::resetDialogs()
4009 // Make sure that no LFUN uses any GuiView.
4010 guiApp->setCurrentView(0);
4014 constructToolbars();
4015 guiApp->menus().fillMenuBar(menuBar(), this, false);
4016 d.layout_->updateContents(true);
4017 // Now update controls with current buffer.
4018 guiApp->setCurrentView(this);
4024 Dialog * GuiView::findOrBuild(string const & name, bool hide_it)
4026 if (!isValidName(name))
4029 map<string, DialogPtr>::iterator it = d.dialogs_.find(name);
4031 if (it != d.dialogs_.end()) {
4033 it->second->hideView();
4034 return it->second.get();
4037 Dialog * dialog = build(name);
4038 d.dialogs_[name].reset(dialog);
4039 if (lyxrc.allow_geometry_session)
4040 dialog->restoreSession();
4047 void GuiView::showDialog(string const & name, string const & data,
4050 triggerShowDialog(toqstr(name), toqstr(data), inset);
4054 void GuiView::doShowDialog(QString const & qname, QString const & qdata,
4060 const string name = fromqstr(qname);
4061 const string data = fromqstr(qdata);
4065 Dialog * dialog = findOrBuild(name, false);
4067 bool const visible = dialog->isVisibleView();
4068 dialog->showData(data);
4069 if (inset && currentBufferView())
4070 currentBufferView()->editInset(name, inset);
4071 // We only set the focus to the new dialog if it was not yet
4072 // visible in order not to change the existing previous behaviour
4074 // activateWindow is needed for floating dockviews
4075 dialog->asQWidget()->raise();
4076 dialog->asQWidget()->activateWindow();
4077 dialog->asQWidget()->setFocus();
4081 catch (ExceptionMessage const & ex) {
4089 bool GuiView::isDialogVisible(string const & name) const
4091 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
4092 if (it == d.dialogs_.end())
4094 return it->second.get()->isVisibleView() && !it->second.get()->isClosing();
4098 void GuiView::hideDialog(string const & name, Inset * inset)
4100 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
4101 if (it == d.dialogs_.end())
4105 if (!currentBufferView())
4107 if (inset != currentBufferView()->editedInset(name))
4111 Dialog * const dialog = it->second.get();
4112 if (dialog->isVisibleView())
4114 if (currentBufferView())
4115 currentBufferView()->editInset(name, 0);
4119 void GuiView::disconnectDialog(string const & name)
4121 if (!isValidName(name))
4123 if (currentBufferView())
4124 currentBufferView()->editInset(name, 0);
4128 void GuiView::hideAll() const
4130 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
4131 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
4133 for(; it != end; ++it)
4134 it->second->hideView();
4138 void GuiView::updateDialogs()
4140 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
4141 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
4143 for(; it != end; ++it) {
4144 Dialog * dialog = it->second.get();
4146 if (dialog->needBufferOpen() && !documentBufferView())
4147 hideDialog(fromqstr(dialog->name()), 0);
4148 else if (dialog->isVisibleView())
4149 dialog->checkStatus();
4156 Dialog * createDialog(GuiView & lv, string const & name);
4158 // will be replaced by a proper factory...
4159 Dialog * createGuiAbout(GuiView & lv);
4160 Dialog * createGuiBibtex(GuiView & lv);
4161 Dialog * createGuiChanges(GuiView & lv);
4162 Dialog * createGuiCharacter(GuiView & lv);
4163 Dialog * createGuiCitation(GuiView & lv);
4164 Dialog * createGuiCompare(GuiView & lv);
4165 Dialog * createGuiCompareHistory(GuiView & lv);
4166 Dialog * createGuiDelimiter(GuiView & lv);
4167 Dialog * createGuiDocument(GuiView & lv);
4168 Dialog * createGuiErrorList(GuiView & lv);
4169 Dialog * createGuiExternal(GuiView & lv);
4170 Dialog * createGuiGraphics(GuiView & lv);
4171 Dialog * createGuiInclude(GuiView & lv);
4172 Dialog * createGuiIndex(GuiView & lv);
4173 Dialog * createGuiListings(GuiView & lv);
4174 Dialog * createGuiLog(GuiView & lv);
4175 Dialog * createGuiMathMatrix(GuiView & lv);
4176 Dialog * createGuiNote(GuiView & lv);
4177 Dialog * createGuiParagraph(GuiView & lv);
4178 Dialog * createGuiPhantom(GuiView & lv);
4179 Dialog * createGuiPreferences(GuiView & lv);
4180 Dialog * createGuiPrint(GuiView & lv);
4181 Dialog * createGuiPrintindex(GuiView & lv);
4182 Dialog * createGuiRef(GuiView & lv);
4183 Dialog * createGuiSearch(GuiView & lv);
4184 Dialog * createGuiSearchAdv(GuiView & lv);
4185 Dialog * createGuiSendTo(GuiView & lv);
4186 Dialog * createGuiShowFile(GuiView & lv);
4187 Dialog * createGuiSpellchecker(GuiView & lv);
4188 Dialog * createGuiSymbols(GuiView & lv);
4189 Dialog * createGuiTabularCreate(GuiView & lv);
4190 Dialog * createGuiTexInfo(GuiView & lv);
4191 Dialog * createGuiToc(GuiView & lv);
4192 Dialog * createGuiThesaurus(GuiView & lv);
4193 Dialog * createGuiViewSource(GuiView & lv);
4194 Dialog * createGuiWrap(GuiView & lv);
4195 Dialog * createGuiProgressView(GuiView & lv);
4199 Dialog * GuiView::build(string const & name)
4201 LASSERT(isValidName(name), return 0);
4203 Dialog * dialog = createDialog(*this, name);
4207 if (name == "aboutlyx")
4208 return createGuiAbout(*this);
4209 if (name == "bibtex")
4210 return createGuiBibtex(*this);
4211 if (name == "changes")
4212 return createGuiChanges(*this);
4213 if (name == "character")
4214 return createGuiCharacter(*this);
4215 if (name == "citation")
4216 return createGuiCitation(*this);
4217 if (name == "compare")
4218 return createGuiCompare(*this);
4219 if (name == "comparehistory")
4220 return createGuiCompareHistory(*this);
4221 if (name == "document")
4222 return createGuiDocument(*this);
4223 if (name == "errorlist")
4224 return createGuiErrorList(*this);
4225 if (name == "external")
4226 return createGuiExternal(*this);
4228 return createGuiShowFile(*this);
4229 if (name == "findreplace")
4230 return createGuiSearch(*this);
4231 if (name == "findreplaceadv")
4232 return createGuiSearchAdv(*this);
4233 if (name == "graphics")
4234 return createGuiGraphics(*this);
4235 if (name == "include")
4236 return createGuiInclude(*this);
4237 if (name == "index")
4238 return createGuiIndex(*this);
4239 if (name == "index_print")
4240 return createGuiPrintindex(*this);
4241 if (name == "listings")
4242 return createGuiListings(*this);
4244 return createGuiLog(*this);
4245 if (name == "mathdelimiter")
4246 return createGuiDelimiter(*this);
4247 if (name == "mathmatrix")
4248 return createGuiMathMatrix(*this);
4250 return createGuiNote(*this);
4251 if (name == "paragraph")
4252 return createGuiParagraph(*this);
4253 if (name == "phantom")
4254 return createGuiPhantom(*this);
4255 if (name == "prefs")
4256 return createGuiPreferences(*this);
4257 if (name == "print")
4258 return createGuiPrint(*this);
4260 return createGuiRef(*this);
4261 if (name == "sendto")
4262 return createGuiSendTo(*this);
4263 if (name == "spellchecker")
4264 return createGuiSpellchecker(*this);
4265 if (name == "symbols")
4266 return createGuiSymbols(*this);
4267 if (name == "tabularcreate")
4268 return createGuiTabularCreate(*this);
4269 if (name == "texinfo")
4270 return createGuiTexInfo(*this);
4271 if (name == "thesaurus")
4272 return createGuiThesaurus(*this);
4274 return createGuiToc(*this);
4275 if (name == "view-source")
4276 return createGuiViewSource(*this);
4278 return createGuiWrap(*this);
4279 if (name == "progress")
4280 return createGuiProgressView(*this);
4286 } // namespace frontend
4289 #include "moc_GuiView.cpp"