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 QString fn = toqstr(lyx::libFileSearch("images", "busy.gif").absFileName());
481 QMovie * busyanim = new QMovie(fn, QByteArray(), busylabel);
482 busylabel->setMovie(busyanim);
486 connect(&d.processing_thread_watcher_, SIGNAL(started()),
487 busylabel, SLOT(show()));
488 connect(&d.processing_thread_watcher_, SIGNAL(finished()),
489 busylabel, SLOT(hide()));
491 statusBar()->setSizeGripEnabled(true);
494 connect(&d.autosave_watcher_, SIGNAL(finished()), this,
495 SLOT(autoSaveThreadFinished()));
497 connect(&d.processing_thread_watcher_, SIGNAL(started()), this,
498 SLOT(processingThreadStarted()));
499 connect(&d.processing_thread_watcher_, SIGNAL(finished()), this,
500 SLOT(processingThreadFinished()));
502 connect(this, SIGNAL(triggerShowDialog(QString const &, QString const &, Inset *)),
503 SLOT(doShowDialog(QString const &, QString const &, Inset *)));
505 // Forbid too small unresizable window because it can happen
506 // with some window manager under X11.
507 setMinimumSize(300, 200);
509 if (lyxrc.allow_geometry_session) {
510 // Now take care of session management.
515 // no session handling, default to a sane size.
516 setGeometry(50, 50, 690, 510);
519 // clear session data if any.
521 settings.remove("views");
531 QVector<GuiWorkArea*> GuiView::GuiViewPrivate::guiWorkAreas()
533 QVector<GuiWorkArea*> areas;
534 for (int i = 0; i < tabWorkAreaCount(); i++) {
535 TabWorkArea* ta = tabWorkArea(i);
536 for (int u = 0; u < ta->count(); u++) {
537 areas << ta->workArea(u);
543 static void handleExportStatus(GuiView * view, Buffer::ExportStatus status,
544 string const & format)
546 docstring const fmt = formats.prettyName(format);
549 case Buffer::ExportSuccess:
550 msg = bformat(_("Successful export to format: %1$s"), fmt);
552 case Buffer::ExportCancel:
553 msg = _("Document export cancelled.");
555 case Buffer::ExportError:
556 case Buffer::ExportNoPathToFormat:
557 case Buffer::ExportTexPathHasSpaces:
558 case Buffer::ExportConverterError:
559 msg = bformat(_("Error while exporting format: %1$s"), fmt);
561 case Buffer::PreviewSuccess:
562 msg = bformat(_("Successful preview of format: %1$s"), fmt);
564 case Buffer::PreviewError:
565 msg = bformat(_("Error while previewing format: %1$s"), fmt);
572 void GuiView::processingThreadStarted()
577 void GuiView::processingThreadFinished()
579 QFutureWatcher<Buffer::ExportStatus> const * watcher =
580 static_cast<QFutureWatcher<Buffer::ExportStatus> const *>(sender());
582 Buffer::ExportStatus const status = watcher->result();
583 handleExportStatus(this, status, d.processing_format);
586 BufferView const * const bv = currentBufferView();
587 if (bv && !bv->buffer().errorList("Export").empty()) {
591 errors(d.last_export_format);
595 void GuiView::autoSaveThreadFinished()
597 QFutureWatcher<docstring> const * watcher =
598 static_cast<QFutureWatcher<docstring> const *>(sender());
599 message(watcher->result());
604 void GuiView::saveLayout() const
607 settings.beginGroup("views");
608 settings.beginGroup(QString::number(id_));
610 settings.setValue("pos", pos());
611 settings.setValue("size", size());
613 settings.setValue("geometry", saveGeometry());
615 settings.setValue("layout", saveState(0));
616 settings.setValue("icon_size", iconSize());
620 void GuiView::saveUISettings() const
622 // Save the toolbar private states
623 ToolbarMap::iterator end = d.toolbars_.end();
624 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
625 it->second->saveSession();
626 // Now take care of all other dialogs
627 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
628 for (; it!= d.dialogs_.end(); ++it)
629 it->second->saveSession();
633 bool GuiView::restoreLayout()
636 settings.beginGroup("views");
637 settings.beginGroup(QString::number(id_));
638 QString const icon_key = "icon_size";
639 if (!settings.contains(icon_key))
642 //code below is skipped when when ~/.config/LyX is (re)created
643 QSize icon_size = settings.value(icon_key).toSize();
644 // Check whether session size changed.
645 if (icon_size.width() != int(d.smallIconSize) &&
646 icon_size.width() != int(d.normalIconSize) &&
647 icon_size.width() != int(d.bigIconSize)) {
648 icon_size.setWidth(d.normalIconSize);
649 icon_size.setHeight(d.normalIconSize);
651 setIconSize(icon_size);
654 QPoint pos = settings.value("pos", QPoint(50, 50)).toPoint();
655 QSize size = settings.value("size", QSize(690, 510)).toSize();
659 // Work-around for bug #6034: the window ends up in an undetermined
660 // state when trying to restore a maximized window when it is
661 // already maximized.
662 if (!(windowState() & Qt::WindowMaximized))
663 if (!restoreGeometry(settings.value("geometry").toByteArray()))
664 setGeometry(50, 50, 690, 510);
666 // Make sure layout is correctly oriented.
667 setLayoutDirection(qApp->layoutDirection());
669 // Allow the toc and view-source dock widget to be restored if needed.
671 if ((dialog = findOrBuild("toc", true)))
672 // see bug 5082. At least setup title and enabled state.
673 // Visibility will be adjusted by restoreState below.
674 dialog->prepareView();
675 if ((dialog = findOrBuild("view-source", true)))
676 dialog->prepareView();
677 if ((dialog = findOrBuild("progress", true)))
678 dialog->prepareView();
680 if (!restoreState(settings.value("layout").toByteArray(), 0))
683 // init the toolbars that have not been restored
684 Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
685 Toolbars::Infos::iterator end = guiApp->toolbars().end();
686 for (; cit != end; ++cit) {
687 GuiToolbar * tb = toolbar(cit->name);
688 if (tb && !tb->isRestored())
689 initToolbar(cit->name);
697 GuiToolbar * GuiView::toolbar(string const & name)
699 ToolbarMap::iterator it = d.toolbars_.find(name);
700 if (it != d.toolbars_.end())
703 LYXERR(Debug::GUI, "Toolbar::display: no toolbar named " << name);
708 void GuiView::constructToolbars()
710 ToolbarMap::iterator it = d.toolbars_.begin();
711 for (; it != d.toolbars_.end(); ++it)
715 // I don't like doing this here, but the standard toolbar
716 // destroys this object when it's destroyed itself (vfr)
717 d.layout_ = new LayoutBox(*this);
718 d.stack_widget_->addWidget(d.layout_);
719 d.layout_->move(0,0);
721 // extracts the toolbars from the backend
722 Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
723 Toolbars::Infos::iterator end = guiApp->toolbars().end();
724 for (; cit != end; ++cit)
725 d.toolbars_[cit->name] = new GuiToolbar(*cit, *this);
729 void GuiView::initToolbars()
731 // extracts the toolbars from the backend
732 Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
733 Toolbars::Infos::iterator end = guiApp->toolbars().end();
734 for (; cit != end; ++cit)
735 initToolbar(cit->name);
739 void GuiView::initToolbar(string const & name)
741 GuiToolbar * tb = toolbar(name);
744 int const visibility = guiApp->toolbars().defaultVisibility(name);
745 bool newline = !(visibility & Toolbars::SAMEROW);
746 tb->setVisible(false);
747 tb->setVisibility(visibility);
749 if (visibility & Toolbars::TOP) {
751 addToolBarBreak(Qt::TopToolBarArea);
752 addToolBar(Qt::TopToolBarArea, tb);
755 if (visibility & Toolbars::BOTTOM) {
757 addToolBarBreak(Qt::BottomToolBarArea);
758 addToolBar(Qt::BottomToolBarArea, tb);
761 if (visibility & Toolbars::LEFT) {
763 addToolBarBreak(Qt::LeftToolBarArea);
764 addToolBar(Qt::LeftToolBarArea, tb);
767 if (visibility & Toolbars::RIGHT) {
769 addToolBarBreak(Qt::RightToolBarArea);
770 addToolBar(Qt::RightToolBarArea, tb);
773 if (visibility & Toolbars::ON)
774 tb->setVisible(true);
778 TocModels & GuiView::tocModels()
780 return d.toc_models_;
784 void GuiView::setFocus()
786 LYXERR(Debug::DEBUG, "GuiView::setFocus()" << this);
787 QMainWindow::setFocus();
791 void GuiView::focusInEvent(QFocusEvent * e)
793 LYXERR(Debug::DEBUG, "GuiView::focusInEvent()" << this);
794 QMainWindow::focusInEvent(e);
795 // Make sure guiApp points to the correct view.
796 guiApp->setCurrentView(this);
797 if (currentWorkArea())
798 currentWorkArea()->setFocus();
799 else if (currentMainWorkArea())
800 currentMainWorkArea()->setFocus();
802 d.bg_widget_->setFocus();
806 QMenu * GuiView::createPopupMenu()
808 return d.toolBarPopup(this);
812 void GuiView::showEvent(QShowEvent * e)
814 LYXERR(Debug::GUI, "Passed Geometry "
815 << size().height() << "x" << size().width()
816 << "+" << pos().x() << "+" << pos().y());
818 if (d.splitter_->count() == 0)
819 // No work area, switch to the background widget.
823 QMainWindow::showEvent(e);
827 bool GuiView::closeScheduled()
834 /** Destroy only all tabbed WorkAreas. Destruction of other WorkAreas
835 ** is responsibility of the container (e.g., dialog)
837 void GuiView::closeEvent(QCloseEvent * close_event)
839 LYXERR(Debug::DEBUG, "GuiView::closeEvent()");
841 if (!GuiViewPrivate::busyBuffers.isEmpty()) {
842 Alert::warning(_("Exit LyX"),
843 _("LyX could not be closed because documents are being processed by LyX."));
844 close_event->setAccepted(false);
848 // If the user pressed the x (so we didn't call closeView
849 // programmatically), we want to clear all existing entries.
851 theSession().lastOpened().clear();
856 // it can happen that this event arrives without selecting the view,
857 // e.g. when clicking the close button on a background window.
859 if (!closeWorkAreaAll()) {
861 close_event->ignore();
865 // Make sure that nothing will use this to be closed View.
866 guiApp->unregisterView(this);
868 if (isFullScreen()) {
869 // Switch off fullscreen before closing.
874 // Make sure the timer time out will not trigger a statusbar update.
875 d.statusbar_timer_.stop();
877 // Saving fullscreen requires additional tweaks in the toolbar code.
878 // It wouldn't also work under linux natively.
879 if (lyxrc.allow_geometry_session) {
884 close_event->accept();
888 void GuiView::dragEnterEvent(QDragEnterEvent * event)
890 if (event->mimeData()->hasUrls())
892 /// \todo Ask lyx-devel is this is enough:
893 /// if (event->mimeData()->hasFormat("text/plain"))
894 /// event->acceptProposedAction();
898 void GuiView::dropEvent(QDropEvent * event)
900 QList<QUrl> files = event->mimeData()->urls();
904 LYXERR(Debug::GUI, "GuiView::dropEvent: got URLs!");
905 for (int i = 0; i != files.size(); ++i) {
906 string const file = os::internal_path(fromqstr(
907 files.at(i).toLocalFile()));
911 string const ext = support::getExtension(file);
912 vector<const Format *> found_formats;
914 // Find all formats that have the correct extension.
915 vector<const Format *> const & import_formats
916 = theConverters().importableFormats();
917 vector<const Format *>::const_iterator it = import_formats.begin();
918 for (; it != import_formats.end(); ++it)
919 if ((*it)->hasExtension(ext))
920 found_formats.push_back(*it);
923 if (found_formats.size() >= 1) {
924 if (found_formats.size() > 1) {
925 //FIXME: show a dialog to choose the correct importable format
927 "Multiple importable formats found, selecting first");
929 string const arg = found_formats[0]->name() + " " + file;
930 cmd = FuncRequest(LFUN_BUFFER_IMPORT, arg);
933 //FIXME: do we have to explicitly check whether it's a lyx file?
935 "No formats found, trying to open it as a lyx file");
936 cmd = FuncRequest(LFUN_FILE_OPEN, file);
938 // add the functions to the queue
939 guiApp->addToFuncRequestQueue(cmd);
942 // now process the collected functions. We perform the events
943 // asynchronously. This prevents potential problems in case the
944 // BufferView is closed within an event.
945 guiApp->processFuncRequestQueueAsync();
949 void GuiView::message(docstring const & str)
951 if (ForkedProcess::iAmAChild())
954 // call is moved to GUI-thread by GuiProgress
955 d.progress_->appendMessage(toqstr(str));
959 void GuiView::clearMessageText()
961 message(docstring());
965 void GuiView::updateStatusBarMessage(QString const & str)
967 statusBar()->showMessage(str);
968 d.statusbar_timer_.stop();
969 d.statusbar_timer_.start(3000);
973 void GuiView::smallSizedIcons()
975 setIconSize(QSize(d.smallIconSize, d.smallIconSize));
979 void GuiView::normalSizedIcons()
981 setIconSize(QSize(d.normalIconSize, d.normalIconSize));
985 void GuiView::bigSizedIcons()
987 setIconSize(QSize(d.bigIconSize, d.bigIconSize));
991 void GuiView::clearMessage()
993 // FIXME: This code was introduced in r19643 to fix bug #4123. However,
994 // the hasFocus function mostly returns false, even if the focus is on
995 // a workarea in this view.
999 d.statusbar_timer_.stop();
1003 void GuiView::updateWindowTitle(GuiWorkArea * wa)
1005 if (wa != d.current_work_area_
1006 || wa->bufferView().buffer().isInternal())
1008 setWindowTitle(qt_("LyX: ") + wa->windowTitle());
1009 setWindowIconText(wa->windowIconText());
1010 #if (QT_VERSION >= 0x040400)
1011 // Sets the path for the window: this is used by OSX to
1012 // allow a context click on the title bar showing a menu
1013 // with the path up to the file
1014 setWindowFilePath(toqstr(wa->bufferView().buffer().absFileName()));
1019 void GuiView::on_currentWorkAreaChanged(GuiWorkArea * wa)
1021 if (d.current_work_area_)
1022 QObject::disconnect(d.current_work_area_, SIGNAL(busy(bool)),
1023 this, SLOT(setBusy(bool)));
1025 disconnectBufferView();
1026 connectBufferView(wa->bufferView());
1027 connectBuffer(wa->bufferView().buffer());
1028 d.current_work_area_ = wa;
1029 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
1030 this, SLOT(updateWindowTitle(GuiWorkArea *)));
1031 QObject::connect(wa, SIGNAL(busy(bool)), this, SLOT(setBusy(bool)));
1032 updateWindowTitle(wa);
1036 // The document settings needs to be reinitialised.
1037 updateDialog("document", "");
1039 // Buffer-dependent dialogs must be updated. This is done here because
1040 // some dialogs require buffer()->text.
1045 void GuiView::on_lastWorkAreaRemoved()
1048 // We already are in a close event. Nothing more to do.
1051 if (d.splitter_->count() > 1)
1052 // We have a splitter so don't close anything.
1055 // Reset and updates the dialogs.
1056 d.toc_models_.reset(0);
1057 updateDialog("document", "");
1060 resetWindowTitleAndIconText();
1063 if (lyxrc.open_buffers_in_tabs)
1064 // Nothing more to do, the window should stay open.
1067 if (guiApp->viewIds().size() > 1) {
1073 // On Mac we also close the last window because the application stay
1074 // resident in memory. On other platforms we don't close the last
1075 // window because this would quit the application.
1081 void GuiView::updateStatusBar()
1083 // let the user see the explicit message
1084 if (d.statusbar_timer_.isActive())
1091 void GuiView::showMessage()
1095 QString msg = toqstr(theGuiApp()->viewStatusMessage());
1096 if (msg.isEmpty()) {
1097 BufferView const * bv = currentBufferView();
1099 msg = toqstr(bv->cursor().currentState());
1101 msg = qt_("Welcome to LyX!");
1103 statusBar()->showMessage(msg);
1107 bool GuiView::event(QEvent * e)
1111 // Useful debug code:
1112 //case QEvent::ActivationChange:
1113 //case QEvent::WindowDeactivate:
1114 //case QEvent::Paint:
1115 //case QEvent::Enter:
1116 //case QEvent::Leave:
1117 //case QEvent::HoverEnter:
1118 //case QEvent::HoverLeave:
1119 //case QEvent::HoverMove:
1120 //case QEvent::StatusTip:
1121 //case QEvent::DragEnter:
1122 //case QEvent::DragLeave:
1123 //case QEvent::Drop:
1126 case QEvent::WindowActivate: {
1127 GuiView * old_view = guiApp->currentView();
1128 if (this == old_view) {
1130 return QMainWindow::event(e);
1132 if (old_view && old_view->currentBufferView()) {
1133 // save current selection to the selection buffer to allow
1134 // middle-button paste in this window.
1135 cap::saveSelection(old_view->currentBufferView()->cursor());
1137 guiApp->setCurrentView(this);
1138 if (d.current_work_area_) {
1139 BufferView & bv = d.current_work_area_->bufferView();
1140 connectBufferView(bv);
1141 connectBuffer(bv.buffer());
1142 // The document structure, name and dialogs might have
1143 // changed in another view.
1145 // The document settings needs to be reinitialised.
1146 updateDialog("document", "");
1149 resetWindowTitleAndIconText();
1152 return QMainWindow::event(e);
1155 case QEvent::ShortcutOverride: {
1157 if (isFullScreen() && menuBar()->isHidden()) {
1158 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
1159 // FIXME: we should also try to detect special LyX shortcut such as
1160 // Alt-P and Alt-M. Right now there is a hack in
1161 // GuiWorkArea::processKeySym() that hides again the menubar for
1163 if (ke->modifiers() & Qt::AltModifier && ke->key() != Qt::Key_Alt) {
1165 return QMainWindow::event(e);
1168 return QMainWindow::event(e);
1172 return QMainWindow::event(e);
1176 void GuiView::resetWindowTitleAndIconText()
1178 setWindowTitle(qt_("LyX"));
1179 setWindowIconText(qt_("LyX"));
1182 bool GuiView::focusNextPrevChild(bool /*next*/)
1189 bool GuiView::busy() const
1195 void GuiView::setBusy(bool busy)
1197 bool const busy_before = busy_ > 0;
1198 busy ? ++busy_ : --busy_;
1199 if ((busy_ > 0) == busy_before)
1200 // busy state didn't change
1204 QApplication::setOverrideCursor(Qt::WaitCursor);
1207 QApplication::restoreOverrideCursor();
1212 double GuiView::pixelRatio() const
1214 #if QT_VERSION > 0x050000
1215 return devicePixelRatio();
1222 GuiWorkArea * GuiView::workArea(int index)
1224 if (TabWorkArea * twa = d.currentTabWorkArea())
1225 if (index < twa->count())
1226 return dynamic_cast<GuiWorkArea *>(twa->widget(index));
1231 GuiWorkArea * GuiView::workArea(Buffer & buffer)
1233 if (currentWorkArea()
1234 && ¤tWorkArea()->bufferView().buffer() == &buffer)
1235 return (GuiWorkArea *) currentWorkArea();
1236 if (TabWorkArea * twa = d.currentTabWorkArea())
1237 return twa->workArea(buffer);
1242 GuiWorkArea * GuiView::addWorkArea(Buffer & buffer)
1244 // Automatically create a TabWorkArea if there are none yet.
1245 TabWorkArea * tab_widget = d.splitter_->count()
1246 ? d.currentTabWorkArea() : addTabWorkArea();
1247 return tab_widget->addWorkArea(buffer, *this);
1251 TabWorkArea * GuiView::addTabWorkArea()
1253 TabWorkArea * twa = new TabWorkArea;
1254 QObject::connect(twa, SIGNAL(currentWorkAreaChanged(GuiWorkArea *)),
1255 this, SLOT(on_currentWorkAreaChanged(GuiWorkArea *)));
1256 QObject::connect(twa, SIGNAL(lastWorkAreaRemoved()),
1257 this, SLOT(on_lastWorkAreaRemoved()));
1259 d.splitter_->addWidget(twa);
1260 d.stack_widget_->setCurrentWidget(d.splitter_);
1265 GuiWorkArea const * GuiView::currentWorkArea() const
1267 return d.current_work_area_;
1271 GuiWorkArea * GuiView::currentWorkArea()
1273 return d.current_work_area_;
1277 GuiWorkArea const * GuiView::currentMainWorkArea() const
1279 if (!d.currentTabWorkArea())
1281 return d.currentTabWorkArea()->currentWorkArea();
1285 GuiWorkArea * GuiView::currentMainWorkArea()
1287 if (!d.currentTabWorkArea())
1289 return d.currentTabWorkArea()->currentWorkArea();
1293 void GuiView::setCurrentWorkArea(GuiWorkArea * wa)
1295 LYXERR(Debug::DEBUG, "Setting current wa: " << wa << endl);
1297 d.current_work_area_ = 0;
1302 // FIXME: I've no clue why this is here and why it accesses
1303 // theGuiApp()->currentView, which might be 0 (bug 6464).
1304 // See also 27525 (vfr).
1305 if (theGuiApp()->currentView() == this
1306 && theGuiApp()->currentView()->currentWorkArea() == wa)
1309 if (currentBufferView())
1310 cap::saveSelection(currentBufferView()->cursor());
1312 theGuiApp()->setCurrentView(this);
1313 d.current_work_area_ = wa;
1315 // We need to reset this now, because it will need to be
1316 // right if the tabWorkArea gets reset in the for loop. We
1317 // will change it back if we aren't in that case.
1318 GuiWorkArea * const old_cmwa = d.current_main_work_area_;
1319 d.current_main_work_area_ = wa;
1321 for (int i = 0; i != d.splitter_->count(); ++i) {
1322 if (d.tabWorkArea(i)->setCurrentWorkArea(wa)) {
1323 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea()
1324 << ", Current main wa: " << currentMainWorkArea());
1329 d.current_main_work_area_ = old_cmwa;
1331 LYXERR(Debug::DEBUG, "This is not a tabbed wa");
1332 on_currentWorkAreaChanged(wa);
1333 BufferView & bv = wa->bufferView();
1334 bv.cursor().fixIfBroken();
1336 wa->setUpdatesEnabled(true);
1337 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() << ", Current main wa: " << currentMainWorkArea());
1341 void GuiView::removeWorkArea(GuiWorkArea * wa)
1343 LASSERT(wa, return);
1344 if (wa == d.current_work_area_) {
1346 disconnectBufferView();
1347 d.current_work_area_ = 0;
1348 d.current_main_work_area_ = 0;
1351 bool found_twa = false;
1352 for (int i = 0; i != d.splitter_->count(); ++i) {
1353 TabWorkArea * twa = d.tabWorkArea(i);
1354 if (twa->removeWorkArea(wa)) {
1355 // Found in this tab group, and deleted the GuiWorkArea.
1357 if (twa->count() != 0) {
1358 if (d.current_work_area_ == 0)
1359 // This means that we are closing the current GuiWorkArea, so
1360 // switch to the next GuiWorkArea in the found TabWorkArea.
1361 setCurrentWorkArea(twa->currentWorkArea());
1363 // No more WorkAreas in this tab group, so delete it.
1370 // It is not a tabbed work area (i.e., the search work area), so it
1371 // should be deleted by other means.
1372 LASSERT(found_twa, return);
1374 if (d.current_work_area_ == 0) {
1375 if (d.splitter_->count() != 0) {
1376 TabWorkArea * twa = d.currentTabWorkArea();
1377 setCurrentWorkArea(twa->currentWorkArea());
1379 // No more work areas, switch to the background widget.
1380 setCurrentWorkArea(0);
1386 LayoutBox * GuiView::getLayoutDialog() const
1392 void GuiView::updateLayoutList()
1395 d.layout_->updateContents(false);
1399 void GuiView::updateToolbars()
1401 ToolbarMap::iterator end = d.toolbars_.end();
1402 if (d.current_work_area_) {
1404 d.current_work_area_->bufferView().cursor().inMathed()
1405 && !d.current_work_area_->bufferView().cursor().inRegexped();
1407 lyx::getStatus(FuncRequest(LFUN_LAYOUT_TABULAR)).enabled();
1409 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).enabled() &&
1410 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).onOff(true);
1411 bool const mathmacrotemplate =
1412 lyx::getStatus(FuncRequest(LFUN_IN_MATHMACROTEMPLATE)).enabled();
1414 lyx::getStatus(FuncRequest(LFUN_IN_IPA)).enabled();
1416 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1417 it->second->update(math, table, review, mathmacrotemplate, ipa);
1419 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1420 it->second->update(false, false, false, false, false);
1424 void GuiView::setBuffer(Buffer * newBuffer)
1426 LYXERR(Debug::DEBUG, "Setting buffer: " << newBuffer << endl);
1427 LASSERT(newBuffer, return);
1429 GuiWorkArea * wa = workArea(*newBuffer);
1432 newBuffer->masterBuffer()->updateBuffer();
1434 wa = addWorkArea(*newBuffer);
1435 // scroll to the position when the BufferView was last closed
1436 if (lyxrc.use_lastfilepos) {
1437 LastFilePosSection::FilePos filepos =
1438 theSession().lastFilePos().load(newBuffer->fileName());
1439 wa->bufferView().moveToPosition(filepos.pit, filepos.pos, 0, 0);
1442 //Disconnect the old buffer...there's no new one.
1445 connectBuffer(*newBuffer);
1446 connectBufferView(wa->bufferView());
1447 setCurrentWorkArea(wa);
1451 void GuiView::connectBuffer(Buffer & buf)
1453 buf.setGuiDelegate(this);
1457 void GuiView::disconnectBuffer()
1459 if (d.current_work_area_)
1460 d.current_work_area_->bufferView().buffer().setGuiDelegate(0);
1464 void GuiView::connectBufferView(BufferView & bv)
1466 bv.setGuiDelegate(this);
1470 void GuiView::disconnectBufferView()
1472 if (d.current_work_area_)
1473 d.current_work_area_->bufferView().setGuiDelegate(0);
1477 void GuiView::errors(string const & error_type, bool from_master)
1479 BufferView const * const bv = currentBufferView();
1483 #if EXPORT_in_THREAD
1484 // We are called with from_master == false by default, so we
1485 // have to figure out whether that is the case or not.
1486 ErrorList & el = bv->buffer().errorList(error_type);
1488 el = bv->buffer().masterBuffer()->errorList(error_type);
1492 ErrorList const & el = from_master ?
1493 bv->buffer().masterBuffer()->errorList(error_type) :
1494 bv->buffer().errorList(error_type);
1500 string data = error_type;
1502 data = "from_master|" + error_type;
1503 showDialog("errorlist", data);
1507 void GuiView::updateTocItem(string const & type, DocIterator const & dit)
1509 d.toc_models_.updateItem(toqstr(type), dit);
1513 void GuiView::structureChanged()
1515 d.toc_models_.reset(documentBufferView());
1516 // Navigator needs more than a simple update in this case. It needs to be
1518 updateDialog("toc", "");
1522 void GuiView::updateDialog(string const & name, string const & data)
1524 if (!isDialogVisible(name))
1527 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
1528 if (it == d.dialogs_.end())
1531 Dialog * const dialog = it->second.get();
1532 if (dialog->isVisibleView())
1533 dialog->initialiseParams(data);
1537 BufferView * GuiView::documentBufferView()
1539 return currentMainWorkArea()
1540 ? ¤tMainWorkArea()->bufferView()
1545 BufferView const * GuiView::documentBufferView() const
1547 return currentMainWorkArea()
1548 ? ¤tMainWorkArea()->bufferView()
1553 BufferView * GuiView::currentBufferView()
1555 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1559 BufferView const * GuiView::currentBufferView() const
1561 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1565 docstring GuiView::GuiViewPrivate::autosaveAndDestroy(
1566 Buffer const * orig, Buffer * clone)
1568 bool const success = clone->autoSave();
1570 busyBuffers.remove(orig);
1572 ? _("Automatic save done.")
1573 : _("Automatic save failed!");
1577 void GuiView::autoSave()
1579 LYXERR(Debug::INFO, "Running autoSave()");
1581 Buffer * buffer = documentBufferView()
1582 ? &documentBufferView()->buffer() : 0;
1584 resetAutosaveTimers();
1588 GuiViewPrivate::busyBuffers.insert(buffer);
1589 QFuture<docstring> f = QtConcurrent::run(GuiViewPrivate::autosaveAndDestroy,
1590 buffer, buffer->cloneBufferOnly());
1591 d.autosave_watcher_.setFuture(f);
1592 resetAutosaveTimers();
1596 void GuiView::resetAutosaveTimers()
1599 d.autosave_timeout_.restart();
1603 bool GuiView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1606 Buffer * buf = currentBufferView()
1607 ? ¤tBufferView()->buffer() : 0;
1608 Buffer * doc_buffer = documentBufferView()
1609 ? &(documentBufferView()->buffer()) : 0;
1611 // Check whether we need a buffer
1612 if (!lyxaction.funcHasFlag(cmd.action(), LyXAction::NoBuffer) && !buf) {
1613 // no, exit directly
1614 flag.message(from_utf8(N_("Command not allowed with"
1615 "out any document open")));
1616 flag.setEnabled(false);
1620 if (cmd.origin() == FuncRequest::TOC) {
1621 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
1622 if (!toc || !toc->getStatus(documentBufferView()->cursor(), cmd, flag))
1623 flag.setEnabled(false);
1627 switch(cmd.action()) {
1628 case LFUN_BUFFER_IMPORT:
1631 case LFUN_MASTER_BUFFER_UPDATE:
1632 case LFUN_MASTER_BUFFER_VIEW:
1634 && (doc_buffer->parent() != 0
1635 || doc_buffer->hasChildren())
1636 && !d.processing_thread_watcher_.isRunning();
1639 case LFUN_BUFFER_UPDATE:
1640 case LFUN_BUFFER_VIEW: {
1641 if (!doc_buffer || d.processing_thread_watcher_.isRunning()) {
1645 string format = to_utf8(cmd.argument());
1646 if (cmd.argument().empty())
1647 format = doc_buffer->params().getDefaultOutputFormat();
1648 enable = doc_buffer->params().isExportableFormat(format);
1652 case LFUN_BUFFER_RELOAD:
1653 enable = doc_buffer && !doc_buffer->isUnnamed()
1654 && doc_buffer->fileName().exists()
1655 && (!doc_buffer->isClean()
1656 || doc_buffer->isExternallyModified(Buffer::timestamp_method));
1659 case LFUN_BUFFER_CHILD_OPEN:
1660 enable = doc_buffer;
1663 case LFUN_BUFFER_WRITE:
1664 enable = doc_buffer && (doc_buffer->isUnnamed() || !doc_buffer->isClean());
1667 //FIXME: This LFUN should be moved to GuiApplication.
1668 case LFUN_BUFFER_WRITE_ALL: {
1669 // We enable the command only if there are some modified buffers
1670 Buffer * first = theBufferList().first();
1675 // We cannot use a for loop as the buffer list is a cycle.
1677 if (!b->isClean()) {
1681 b = theBufferList().next(b);
1682 } while (b != first);
1686 case LFUN_BUFFER_WRITE_AS:
1687 case LFUN_BUFFER_EXPORT_AS:
1688 enable = doc_buffer;
1691 case LFUN_BUFFER_CLOSE:
1692 case LFUN_VIEW_CLOSE:
1693 enable = doc_buffer;
1696 case LFUN_BUFFER_CLOSE_ALL:
1697 enable = theBufferList().last() != theBufferList().first();
1700 case LFUN_VIEW_SPLIT:
1701 if (cmd.getArg(0) == "vertical")
1702 enable = doc_buffer && (d.splitter_->count() == 1 ||
1703 d.splitter_->orientation() == Qt::Vertical);
1705 enable = doc_buffer && (d.splitter_->count() == 1 ||
1706 d.splitter_->orientation() == Qt::Horizontal);
1709 case LFUN_TAB_GROUP_CLOSE:
1710 enable = d.tabWorkAreaCount() > 1;
1713 case LFUN_TOOLBAR_TOGGLE: {
1714 string const name = cmd.getArg(0);
1715 if (GuiToolbar * t = toolbar(name))
1716 flag.setOnOff(t->isVisible());
1719 docstring const msg =
1720 bformat(_("Unknown toolbar \"%1$s\""), from_utf8(name));
1726 case LFUN_DROP_LAYOUTS_CHOICE:
1730 case LFUN_UI_TOGGLE:
1731 flag.setOnOff(isFullScreen());
1734 case LFUN_DIALOG_DISCONNECT_INSET:
1737 case LFUN_DIALOG_HIDE:
1738 // FIXME: should we check if the dialog is shown?
1741 case LFUN_DIALOG_TOGGLE:
1742 flag.setOnOff(isDialogVisible(cmd.getArg(0)));
1743 // fall through to set "enable"
1744 case LFUN_DIALOG_SHOW: {
1745 string const name = cmd.getArg(0);
1747 enable = name == "aboutlyx"
1748 || name == "file" //FIXME: should be removed.
1750 || name == "texinfo"
1751 || name == "progress"
1752 || name == "compare";
1753 else if (name == "print")
1754 enable = doc_buffer->params().isExportable("dvi")
1755 && lyxrc.print_command != "none";
1756 else if (name == "character" || name == "symbols"
1757 || name == "mathdelimiter" || name == "mathmatrix") {
1758 if (!buf || buf->isReadonly())
1761 Cursor const & cur = currentBufferView()->cursor();
1762 enable = !(cur.inTexted() && cur.paragraph().isPassThru());
1765 else if (name == "latexlog")
1766 enable = FileName(doc_buffer->logName()).isReadableFile();
1767 else if (name == "spellchecker")
1768 enable = theSpellChecker()
1769 && !doc_buffer->isReadonly()
1770 && !doc_buffer->text().empty();
1771 else if (name == "vclog")
1772 enable = doc_buffer->lyxvc().inUse();
1776 case LFUN_DIALOG_UPDATE: {
1777 string const name = cmd.getArg(0);
1779 enable = name == "prefs";
1783 case LFUN_COMMAND_EXECUTE:
1785 case LFUN_MENU_OPEN:
1786 // Nothing to check.
1789 case LFUN_COMPLETION_INLINE:
1790 if (!d.current_work_area_
1791 || !d.current_work_area_->completer().inlinePossible(
1792 currentBufferView()->cursor()))
1796 case LFUN_COMPLETION_POPUP:
1797 if (!d.current_work_area_
1798 || !d.current_work_area_->completer().popupPossible(
1799 currentBufferView()->cursor()))
1804 if (!d.current_work_area_
1805 || !d.current_work_area_->completer().inlinePossible(
1806 currentBufferView()->cursor()))
1810 case LFUN_COMPLETION_ACCEPT:
1811 if (!d.current_work_area_
1812 || (!d.current_work_area_->completer().popupVisible()
1813 && !d.current_work_area_->completer().inlineVisible()
1814 && !d.current_work_area_->completer().completionAvailable()))
1818 case LFUN_COMPLETION_CANCEL:
1819 if (!d.current_work_area_
1820 || (!d.current_work_area_->completer().popupVisible()
1821 && !d.current_work_area_->completer().inlineVisible()))
1825 case LFUN_BUFFER_ZOOM_OUT:
1826 enable = doc_buffer && lyxrc.zoom > 10;
1829 case LFUN_BUFFER_ZOOM_IN:
1830 enable = doc_buffer;
1833 case LFUN_BUFFER_NEXT:
1834 case LFUN_BUFFER_PREVIOUS:
1835 // FIXME: should we check is there is an previous or next buffer?
1837 case LFUN_BUFFER_SWITCH:
1838 // toggle on the current buffer, but do not toggle off
1839 // the other ones (is that a good idea?)
1841 && to_utf8(cmd.argument()) == doc_buffer->absFileName())
1842 flag.setOnOff(true);
1845 case LFUN_VC_REGISTER:
1846 enable = doc_buffer && !doc_buffer->lyxvc().inUse();
1848 case LFUN_VC_RENAME:
1849 enable = doc_buffer && doc_buffer->lyxvc().renameEnabled();
1852 enable = doc_buffer && doc_buffer->lyxvc().copyEnabled();
1854 case LFUN_VC_CHECK_IN:
1855 enable = doc_buffer && doc_buffer->lyxvc().checkInEnabled();
1857 case LFUN_VC_CHECK_OUT:
1858 enable = doc_buffer && doc_buffer->lyxvc().checkOutEnabled();
1860 case LFUN_VC_LOCKING_TOGGLE:
1861 enable = doc_buffer && !doc_buffer->isReadonly()
1862 && doc_buffer->lyxvc().lockingToggleEnabled();
1863 flag.setOnOff(enable && doc_buffer->lyxvc().locking());
1865 case LFUN_VC_REVERT:
1866 enable = doc_buffer && doc_buffer->lyxvc().inUse() && !doc_buffer->isReadonly();
1868 case LFUN_VC_UNDO_LAST:
1869 enable = doc_buffer && doc_buffer->lyxvc().undoLastEnabled();
1871 case LFUN_VC_REPO_UPDATE:
1872 enable = doc_buffer && doc_buffer->lyxvc().repoUpdateEnabled();
1874 case LFUN_VC_COMMAND: {
1875 if (cmd.argument().empty())
1877 if (!doc_buffer && contains(cmd.getArg(0), 'D'))
1881 case LFUN_VC_COMPARE:
1882 enable = doc_buffer && doc_buffer->lyxvc().prepareFileRevisionEnabled();
1885 case LFUN_SERVER_GOTO_FILE_ROW:
1887 case LFUN_FORWARD_SEARCH:
1888 enable = !(lyxrc.forward_search_dvi.empty() && lyxrc.forward_search_pdf.empty());
1891 case LFUN_FILE_INSERT_PLAINTEXT:
1892 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
1893 enable = documentBufferView() && documentBufferView()->cursor().inTexted();
1896 case LFUN_SPELLING_CONTINUOUSLY:
1897 flag.setOnOff(lyxrc.spellcheck_continuously);
1905 flag.setEnabled(false);
1911 static FileName selectTemplateFile()
1913 FileDialog dlg(qt_("Select template file"));
1914 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1915 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
1917 FileDialog::Result result = dlg.open(toqstr(lyxrc.template_path),
1918 QStringList(qt_("LyX Documents (*.lyx)")));
1920 if (result.first == FileDialog::Later)
1922 if (result.second.isEmpty())
1924 return FileName(fromqstr(result.second));
1928 Buffer * GuiView::loadDocument(FileName const & filename, bool tolastfiles)
1932 Buffer * newBuffer = 0;
1934 newBuffer = checkAndLoadLyXFile(filename);
1935 } catch (ExceptionMessage const & e) {
1942 message(_("Document not loaded."));
1946 setBuffer(newBuffer);
1947 newBuffer->errors("Parse");
1950 theSession().lastFiles().add(filename);
1956 void GuiView::openDocument(string const & fname)
1958 string initpath = lyxrc.document_path;
1960 if (documentBufferView()) {
1961 string const trypath = documentBufferView()->buffer().filePath();
1962 // If directory is writeable, use this as default.
1963 if (FileName(trypath).isDirWritable())
1969 if (fname.empty()) {
1970 FileDialog dlg(qt_("Select document to open"));
1971 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1972 dlg.setButton2(qt_("Examples|#E#e"),
1973 toqstr(addPath(package().system_support().absFileName(), "examples")));
1975 QStringList const filter(qt_("LyX Documents (*.lyx)"));
1976 FileDialog::Result result =
1977 dlg.open(toqstr(initpath), filter);
1979 if (result.first == FileDialog::Later)
1982 filename = fromqstr(result.second);
1984 // check selected filename
1985 if (filename.empty()) {
1986 message(_("Canceled."));
1992 // get absolute path of file and add ".lyx" to the filename if
1994 FileName const fullname =
1995 fileSearch(string(), filename, "lyx", support::may_not_exist);
1996 if (!fullname.empty())
1997 filename = fullname.absFileName();
1999 if (!fullname.onlyPath().isDirectory()) {
2000 Alert::warning(_("Invalid filename"),
2001 bformat(_("The directory in the given path\n%1$s\ndoes not exist."),
2002 from_utf8(fullname.absFileName())));
2006 // if the file doesn't exist and isn't already open (bug 6645),
2007 // let the user create one
2008 if (!fullname.exists() && !theBufferList().exists(fullname) &&
2009 !LyXVC::file_not_found_hook(fullname)) {
2010 // the user specifically chose this name. Believe him.
2011 Buffer * const b = newFile(filename, string(), true);
2017 docstring const disp_fn = makeDisplayPath(filename);
2018 message(bformat(_("Opening document %1$s..."), disp_fn));
2021 Buffer * buf = loadDocument(fullname);
2023 str2 = bformat(_("Document %1$s opened."), disp_fn);
2024 if (buf->lyxvc().inUse())
2025 str2 += " " + from_utf8(buf->lyxvc().versionString()) +
2026 " " + _("Version control detected.");
2028 str2 = bformat(_("Could not open document %1$s"), disp_fn);
2033 // FIXME: clean that
2034 static bool import(GuiView * lv, FileName const & filename,
2035 string const & format, ErrorList & errorList)
2037 FileName const lyxfile(support::changeExtension(filename.absFileName(), ".lyx"));
2039 string loader_format;
2040 vector<string> loaders = theConverters().loaders();
2041 if (find(loaders.begin(), loaders.end(), format) == loaders.end()) {
2042 vector<string>::const_iterator it = loaders.begin();
2043 vector<string>::const_iterator en = loaders.end();
2044 for (; it != en; ++it) {
2045 if (!theConverters().isReachable(format, *it))
2048 string const tofile =
2049 support::changeExtension(filename.absFileName(),
2050 formats.extension(*it));
2051 if (!theConverters().convert(0, filename, FileName(tofile),
2052 filename, format, *it, errorList))
2054 loader_format = *it;
2057 if (loader_format.empty()) {
2058 frontend::Alert::error(_("Couldn't import file"),
2059 bformat(_("No information for importing the format %1$s."),
2060 formats.prettyName(format)));
2064 loader_format = format;
2066 if (loader_format == "lyx") {
2067 Buffer * buf = lv->loadDocument(lyxfile);
2071 Buffer * const b = newFile(lyxfile.absFileName(), string(), true);
2075 bool as_paragraphs = loader_format == "textparagraph";
2076 string filename2 = (loader_format == format) ? filename.absFileName()
2077 : support::changeExtension(filename.absFileName(),
2078 formats.extension(loader_format));
2079 lv->currentBufferView()->insertPlaintextFile(FileName(filename2),
2081 guiApp->setCurrentView(lv);
2082 lyx::dispatch(FuncRequest(LFUN_MARK_OFF));
2089 void GuiView::importDocument(string const & argument)
2092 string filename = split(argument, format, ' ');
2094 LYXERR(Debug::INFO, format << " file: " << filename);
2096 // need user interaction
2097 if (filename.empty()) {
2098 string initpath = lyxrc.document_path;
2099 if (documentBufferView()) {
2100 string const trypath = documentBufferView()->buffer().filePath();
2101 // If directory is writeable, use this as default.
2102 if (FileName(trypath).isDirWritable())
2106 docstring const text = bformat(_("Select %1$s file to import"),
2107 formats.prettyName(format));
2109 FileDialog dlg(toqstr(text));
2110 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2111 dlg.setButton2(qt_("Examples|#E#e"),
2112 toqstr(addPath(package().system_support().absFileName(), "examples")));
2114 docstring filter = formats.prettyName(format);
2117 filter += from_utf8(formats.extensions(format));
2120 FileDialog::Result result =
2121 dlg.open(toqstr(initpath), fileFilters(toqstr(filter)));
2123 if (result.first == FileDialog::Later)
2126 filename = fromqstr(result.second);
2128 // check selected filename
2129 if (filename.empty())
2130 message(_("Canceled."));
2133 if (filename.empty())
2136 // get absolute path of file
2137 FileName const fullname(support::makeAbsPath(filename));
2139 // Can happen if the user entered a path into the dialog
2141 if (fullname.onlyFileName().empty()) {
2142 docstring msg = bformat(_("The file name '%1$s' is invalid!\n"
2143 "Aborting import."),
2144 from_utf8(fullname.absFileName()));
2145 frontend::Alert::error(_("File name error"), msg);
2146 message(_("Canceled."));
2151 FileName const lyxfile(support::changeExtension(fullname.absFileName(), ".lyx"));
2153 // Check if the document already is open
2154 Buffer * buf = theBufferList().getBuffer(lyxfile);
2157 if (!closeBuffer()) {
2158 message(_("Canceled."));
2163 docstring const displaypath = makeDisplayPath(lyxfile.absFileName(), 30);
2165 // if the file exists already, and we didn't do
2166 // -i lyx thefile.lyx, warn
2167 if (lyxfile.exists() && fullname != lyxfile) {
2169 docstring text = bformat(_("The document %1$s already exists.\n\n"
2170 "Do you want to overwrite that document?"), displaypath);
2171 int const ret = Alert::prompt(_("Overwrite document?"),
2172 text, 0, 1, _("&Overwrite"), _("&Cancel"));
2175 message(_("Canceled."));
2180 message(bformat(_("Importing %1$s..."), displaypath));
2181 ErrorList errorList;
2182 if (import(this, fullname, format, errorList))
2183 message(_("imported."));
2185 message(_("file not imported!"));
2187 // FIXME (Abdel 12/08/06): Is there a need to display the error list here?
2191 void GuiView::newDocument(string const & filename, bool from_template)
2193 FileName initpath(lyxrc.document_path);
2194 if (documentBufferView()) {
2195 FileName const trypath(documentBufferView()->buffer().filePath());
2196 // If directory is writeable, use this as default.
2197 if (trypath.isDirWritable())
2201 string templatefile;
2202 if (from_template) {
2203 templatefile = selectTemplateFile().absFileName();
2204 if (templatefile.empty())
2209 if (filename.empty())
2210 b = newUnnamedFile(initpath, to_utf8(_("newfile")), templatefile);
2212 b = newFile(filename, templatefile, true);
2217 // If no new document could be created, it is unsure
2218 // whether there is a valid BufferView.
2219 if (currentBufferView())
2220 // Ensure the cursor is correctly positioned on screen.
2221 currentBufferView()->showCursor();
2225 void GuiView::insertLyXFile(docstring const & fname)
2227 BufferView * bv = documentBufferView();
2232 FileName filename(to_utf8(fname));
2233 if (filename.empty()) {
2234 // Launch a file browser
2236 string initpath = lyxrc.document_path;
2237 string const trypath = bv->buffer().filePath();
2238 // If directory is writeable, use this as default.
2239 if (FileName(trypath).isDirWritable())
2243 FileDialog dlg(qt_("Select LyX document to insert"));
2244 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2245 dlg.setButton2(qt_("Examples|#E#e"),
2246 toqstr(addPath(package().system_support().absFileName(),
2249 FileDialog::Result result = dlg.open(toqstr(initpath),
2250 QStringList(qt_("LyX Documents (*.lyx)")));
2252 if (result.first == FileDialog::Later)
2256 filename.set(fromqstr(result.second));
2258 // check selected filename
2259 if (filename.empty()) {
2260 // emit message signal.
2261 message(_("Canceled."));
2266 bv->insertLyXFile(filename);
2267 bv->buffer().errors("Parse");
2271 bool GuiView::renameBuffer(Buffer & b, docstring const & newname, RenameKind kind)
2273 FileName fname = b.fileName();
2274 FileName const oldname = fname;
2276 if (!newname.empty()) {
2278 fname = support::makeAbsPath(to_utf8(newname), oldname.onlyPath().absFileName());
2280 // Switch to this Buffer.
2283 // No argument? Ask user through dialog.
2285 FileDialog dlg(qt_("Choose a filename to save document as"));
2286 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2287 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
2289 if (!isLyXFileName(fname.absFileName()))
2290 fname.changeExtension(".lyx");
2292 FileDialog::Result result =
2293 dlg.save(toqstr(fname.onlyPath().absFileName()),
2294 QStringList(qt_("LyX Documents (*.lyx)")),
2295 toqstr(fname.onlyFileName()));
2297 if (result.first == FileDialog::Later)
2300 fname.set(fromqstr(result.second));
2305 if (!isLyXFileName(fname.absFileName()))
2306 fname.changeExtension(".lyx");
2309 // fname is now the new Buffer location.
2311 // if there is already a Buffer open with this name, we do not want
2312 // to have another one. (the second test makes sure we're not just
2313 // trying to overwrite ourselves, which is fine.)
2314 if (theBufferList().exists(fname) && fname != oldname
2315 && theBufferList().getBuffer(fname) != &b) {
2316 docstring const text =
2317 bformat(_("The file\n%1$s\nis already open in your current session.\n"
2318 "Please close it before attempting to overwrite it.\n"
2319 "Do you want to choose a new filename?"),
2320 from_utf8(fname.absFileName()));
2321 int const ret = Alert::prompt(_("Chosen File Already Open"),
2322 text, 0, 1, _("&Rename"), _("&Cancel"));
2324 case 0: return renameBuffer(b, docstring(), kind);
2325 case 1: return false;
2330 bool const existsLocal = fname.exists();
2331 bool const existsInVC = LyXVC::fileInVC(fname);
2332 if (existsLocal || existsInVC) {
2333 docstring const file = makeDisplayPath(fname.absFileName(), 30);
2334 if (kind != LV_WRITE_AS && existsInVC) {
2335 // renaming to a name that is already in VC
2337 docstring text = bformat(_("The document %1$s "
2338 "is already registered.\n\n"
2339 "Do you want to choose a new name?"),
2341 docstring const title = (kind == LV_VC_RENAME) ?
2342 _("Rename document?") : _("Copy document?");
2343 docstring const button = (kind == LV_VC_RENAME) ?
2344 _("&Rename") : _("&Copy");
2345 int const ret = Alert::prompt(title, text, 0, 1,
2346 button, _("&Cancel"));
2348 case 0: return renameBuffer(b, docstring(), kind);
2349 case 1: return false;
2354 docstring text = bformat(_("The document %1$s "
2355 "already exists.\n\n"
2356 "Do you want to overwrite that document?"),
2358 int const ret = Alert::prompt(_("Overwrite document?"),
2359 text, 0, 2, _("&Overwrite"),
2360 _("&Rename"), _("&Cancel"));
2363 case 1: return renameBuffer(b, docstring(), kind);
2364 case 2: return false;
2370 case LV_VC_RENAME: {
2371 string msg = b.lyxvc().rename(fname);
2374 message(from_utf8(msg));
2378 string msg = b.lyxvc().copy(fname);
2381 message(from_utf8(msg));
2387 // LyXVC created the file already in case of LV_VC_RENAME or
2388 // LV_VC_COPY, but call saveBuffer() nevertheless to get
2389 // relative paths of included stuff right if we moved e.g. from
2390 // /a/b.lyx to /a/c/b.lyx.
2392 bool const saved = saveBuffer(b, fname);
2399 struct PrettyNameComparator
2401 bool operator()(Format const *first, Format const *second) const {
2402 return compare_no_case(translateIfPossible(from_ascii(first->prettyname())),
2403 translateIfPossible(from_ascii(second->prettyname()))) <= 0;
2408 bool GuiView::exportBufferAs(Buffer & b, docstring const & iformat)
2410 FileName fname = b.fileName();
2412 FileDialog dlg(qt_("Choose a filename to export the document as"));
2413 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2416 QString const anyformat = qt_("Guess from extension (*.*)");
2418 Formats::const_iterator it = formats.begin();
2419 vector<Format const *> export_formats;
2420 for (; it != formats.end(); ++it)
2421 if (it->documentFormat())
2422 export_formats.push_back(&(*it));
2423 PrettyNameComparator cmp;
2424 sort(export_formats.begin(), export_formats.end(), cmp);
2425 vector<Format const *>::const_iterator fit = export_formats.begin();
2426 map<QString, string> fmap;
2429 for (; fit != export_formats.end(); ++fit) {
2430 docstring const loc_prettyname =
2431 translateIfPossible(from_utf8((*fit)->prettyname()));
2432 QString const loc_filter = toqstr(bformat(from_ascii("%1$s (*.%2$s)"),
2434 from_ascii((*fit)->extension())));
2435 types << loc_filter;
2436 fmap[loc_filter] = (*fit)->name();
2437 if (from_ascii((*fit)->name()) == iformat) {
2438 filter = loc_filter;
2439 ext = (*fit)->extension();
2442 string ofname = fname.onlyFileName();
2444 ofname = support::changeExtension(ofname, ext);
2445 FileDialog::Result result =
2446 dlg.save(toqstr(fname.onlyPath().absFileName()),
2450 if (result.first != FileDialog::Chosen)
2454 fname.set(fromqstr(result.second));
2455 if (filter == anyformat)
2456 fmt_name = formats.getFormatFromExtension(fname.extension());
2458 fmt_name = fmap[filter];
2459 LYXERR(Debug::FILES, "filter=" << fromqstr(filter)
2460 << ", fmt_name=" << fmt_name << ", fname=" << fname.absFileName());
2462 if (fmt_name.empty() || fname.empty())
2465 // fname is now the new Buffer location.
2466 if (FileName(fname).exists()) {
2467 docstring const file = makeDisplayPath(fname.absFileName(), 30);
2468 docstring text = bformat(_("The document %1$s already "
2469 "exists.\n\nDo you want to "
2470 "overwrite that document?"),
2472 int const ret = Alert::prompt(_("Overwrite document?"),
2473 text, 0, 2, _("&Overwrite"), _("&Rename"), _("&Cancel"));
2476 case 1: return exportBufferAs(b, from_ascii(fmt_name));
2477 case 2: return false;
2481 FuncRequest cmd(LFUN_BUFFER_EXPORT, fmt_name + " " + fname.absFileName());
2484 return dr.dispatched();
2488 bool GuiView::saveBuffer(Buffer & b)
2490 return saveBuffer(b, FileName());
2494 bool GuiView::saveBuffer(Buffer & b, FileName const & fn)
2496 if (workArea(b) && workArea(b)->inDialogMode())
2499 if (fn.empty() && b.isUnnamed())
2500 return renameBuffer(b, docstring());
2502 bool const success = (fn.empty() ? b.save() : b.saveAs(fn));
2504 theSession().lastFiles().add(b.fileName());
2508 // Switch to this Buffer.
2511 // FIXME: we don't tell the user *WHY* the save failed !!
2512 docstring const file = makeDisplayPath(b.absFileName(), 30);
2513 docstring text = bformat(_("The document %1$s could not be saved.\n\n"
2514 "Do you want to rename the document and "
2515 "try again?"), file);
2516 int const ret = Alert::prompt(_("Rename and save?"),
2517 text, 0, 2, _("&Rename"), _("&Retry"), _("&Cancel"));
2520 if (!renameBuffer(b, docstring()))
2529 return saveBuffer(b, fn);
2533 bool GuiView::hideWorkArea(GuiWorkArea * wa)
2535 return closeWorkArea(wa, false);
2539 // We only want to close the buffer if it is not visible in other workareas
2540 // of the same view, nor in other views, and if this is not a child
2541 bool GuiView::closeWorkArea(GuiWorkArea * wa)
2543 Buffer & buf = wa->bufferView().buffer();
2545 bool last_wa = d.countWorkAreasOf(buf) == 1
2546 && !inOtherView(buf) && !buf.parent();
2548 bool close_buffer = last_wa;
2551 if (lyxrc.close_buffer_with_last_view == "yes")
2553 else if (lyxrc.close_buffer_with_last_view == "no")
2554 close_buffer = false;
2557 if (buf.isUnnamed())
2558 file = from_utf8(buf.fileName().onlyFileName());
2560 file = buf.fileName().displayName(30);
2561 docstring const text = bformat(
2562 _("Last view on document %1$s is being closed.\n"
2563 "Would you like to close or hide the document?\n"
2565 "Hidden documents can be displayed back through\n"
2566 "the menu: View->Hidden->...\n"
2568 "To remove this question, set your preference in:\n"
2569 " Tools->Preferences->Look&Feel->UserInterface\n"
2571 int ret = Alert::prompt(_("Close or hide document?"),
2572 text, 0, 1, _("&Close"), _("&Hide"));
2573 close_buffer = (ret == 0);
2577 return closeWorkArea(wa, close_buffer);
2581 bool GuiView::closeBuffer()
2583 GuiWorkArea * wa = currentMainWorkArea();
2584 setCurrentWorkArea(wa);
2585 Buffer & buf = wa->bufferView().buffer();
2586 return wa && closeWorkArea(wa, !buf.parent());
2590 void GuiView::writeSession() const {
2591 GuiWorkArea const * active_wa = currentMainWorkArea();
2592 for (int i = 0; i < d.splitter_->count(); ++i) {
2593 TabWorkArea * twa = d.tabWorkArea(i);
2594 for (int j = 0; j < twa->count(); ++j) {
2595 GuiWorkArea * wa = static_cast<GuiWorkArea *>(twa->widget(j));
2596 Buffer & buf = wa->bufferView().buffer();
2597 theSession().lastOpened().add(buf.fileName(), wa == active_wa);
2603 bool GuiView::closeBufferAll()
2605 // Close the workareas in all other views
2606 QList<int> const ids = guiApp->viewIds();
2607 for (int i = 0; i != ids.size(); ++i) {
2608 if (id_ != ids[i] && !guiApp->view(ids[i]).closeWorkAreaAll())
2612 // Close our own workareas
2613 if (!closeWorkAreaAll())
2616 // Now close the hidden buffers. We prevent hidden buffers from being
2617 // dirty, so we can just close them.
2618 theBufferList().closeAll();
2623 bool GuiView::closeWorkAreaAll()
2625 setCurrentWorkArea(currentMainWorkArea());
2627 // We might be in a situation that there is still a tabWorkArea, but
2628 // there are no tabs anymore. This can happen when we get here after a
2629 // TabWorkArea::lastWorkAreaRemoved() signal. Therefore we count how
2630 // many TabWorkArea's have no documents anymore.
2633 // We have to call count() each time, because it can happen that
2634 // more than one splitter will disappear in one iteration (bug 5998).
2635 for (; d.splitter_->count() > empty_twa; ) {
2636 TabWorkArea * twa = d.tabWorkArea(empty_twa);
2638 if (twa->count() == 0)
2641 setCurrentWorkArea(twa->currentWorkArea());
2642 if (!closeTabWorkArea(twa))
2650 bool GuiView::closeWorkArea(GuiWorkArea * wa, bool close_buffer)
2655 Buffer & buf = wa->bufferView().buffer();
2657 if (close_buffer && GuiViewPrivate::busyBuffers.contains(&buf)) {
2658 Alert::warning(_("Close document"),
2659 _("Document could not be closed because it is being processed by LyX."));
2664 return closeBuffer(buf);
2666 if (!inMultiTabs(wa))
2667 if (!saveBufferIfNeeded(buf, true))
2675 bool GuiView::closeBuffer(Buffer & buf)
2677 // If we are in a close_event all children will be closed in some time,
2678 // so no need to do it here. This will ensure that the children end up
2679 // in the session file in the correct order. If we close the master
2680 // buffer, we can close or release the child buffers here too.
2681 bool success = true;
2683 ListOfBuffers clist = buf.getChildren();
2684 ListOfBuffers::const_iterator it = clist.begin();
2685 ListOfBuffers::const_iterator const bend = clist.end();
2686 for (; it != bend; ++it) {
2687 // If a child is dirty, do not close
2688 // without user intervention
2689 //FIXME: should we look in other tabworkareas?
2690 Buffer * child_buf = *it;
2691 GuiWorkArea * child_wa = workArea(*child_buf);
2693 if (!closeWorkArea(child_wa, true)) {
2698 theBufferList().releaseChild(&buf, child_buf);
2702 // goto bookmark to update bookmark pit.
2703 //FIXME: we should update only the bookmarks related to this buffer!
2704 LYXERR(Debug::DEBUG, "GuiView::closeBuffer()");
2705 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
2706 guiApp->gotoBookmark(i+1, false, false);
2708 if (saveBufferIfNeeded(buf, false)) {
2709 buf.removeAutosaveFile();
2710 theBufferList().release(&buf);
2714 // open all children again to avoid a crash because of dangling
2715 // pointers (bug 6603)
2721 bool GuiView::closeTabWorkArea(TabWorkArea * twa)
2723 while (twa == d.currentTabWorkArea()) {
2724 twa->setCurrentIndex(twa->count()-1);
2726 GuiWorkArea * wa = twa->currentWorkArea();
2727 Buffer & b = wa->bufferView().buffer();
2729 // We only want to close the buffer if the same buffer is not visible
2730 // in another view, and if this is not a child and if we are closing
2731 // a view (not a tabgroup).
2732 bool const close_buffer =
2733 !inOtherView(b) && !b.parent() && closing_;
2735 if (!closeWorkArea(wa, close_buffer))
2742 bool GuiView::saveBufferIfNeeded(Buffer & buf, bool hiding)
2744 if (buf.isClean() || buf.paragraphs().empty())
2747 // Switch to this Buffer.
2752 if (buf.isUnnamed())
2753 file = from_utf8(buf.fileName().onlyFileName());
2755 file = buf.fileName().displayName(30);
2757 // Bring this window to top before asking questions.
2762 if (hiding && buf.isUnnamed()) {
2763 docstring const text = bformat(_("The document %1$s has not been "
2764 "saved yet.\n\nDo you want to save "
2765 "the document?"), file);
2766 ret = Alert::prompt(_("Save new document?"),
2767 text, 0, 1, _("&Save"), _("&Cancel"));
2771 docstring const text = bformat(_("The document %1$s has unsaved changes."
2772 "\n\nDo you want to save the document or discard the changes?"), file);
2773 ret = Alert::prompt(_("Save changed document?"),
2774 text, 0, 2, _("&Save"), _("&Discard"), _("&Cancel"));
2779 if (!saveBuffer(buf))
2783 // If we crash after this we could have no autosave file
2784 // but I guess this is really improbable (Jug).
2785 // Sometimes improbable things happen:
2786 // - see bug http://www.lyx.org/trac/ticket/6587 (ps)
2787 // buf.removeAutosaveFile();
2789 // revert all changes
2800 bool GuiView::inMultiTabs(GuiWorkArea * wa)
2802 Buffer & buf = wa->bufferView().buffer();
2804 for (int i = 0; i != d.splitter_->count(); ++i) {
2805 GuiWorkArea * wa_ = d.tabWorkArea(i)->workArea(buf);
2806 if (wa_ && wa_ != wa)
2809 return inOtherView(buf);
2813 bool GuiView::inOtherView(Buffer & buf)
2815 QList<int> const ids = guiApp->viewIds();
2817 for (int i = 0; i != ids.size(); ++i) {
2821 if (guiApp->view(ids[i]).workArea(buf))
2828 void GuiView::gotoNextOrPreviousBuffer(NextOrPrevious np)
2830 if (!documentBufferView())
2833 if (TabWorkArea * twa = d.currentTabWorkArea()) {
2834 Buffer * const curbuf = &documentBufferView()->buffer();
2835 int nwa = twa->count();
2836 for (int i = 0; i < nwa; ++i) {
2837 if (&workArea(i)->bufferView().buffer() == curbuf) {
2839 if (np == NEXTBUFFER)
2840 next_index = (i == nwa - 1 ? 0 : i + 1);
2842 next_index = (i == 0 ? nwa - 1 : i - 1);
2843 setBuffer(&workArea(next_index)->bufferView().buffer());
2851 /// make sure the document is saved
2852 static bool ensureBufferClean(Buffer * buffer)
2854 LASSERT(buffer, return false);
2855 if (buffer->isClean() && !buffer->isUnnamed())
2858 docstring const file = buffer->fileName().displayName(30);
2861 if (!buffer->isUnnamed()) {
2862 text = bformat(_("The document %1$s has unsaved "
2863 "changes.\n\nDo you want to save "
2864 "the document?"), file);
2865 title = _("Save changed document?");
2868 text = bformat(_("The document %1$s has not been "
2869 "saved yet.\n\nDo you want to save "
2870 "the document?"), file);
2871 title = _("Save new document?");
2873 int const ret = Alert::prompt(title, text, 0, 1, _("&Save"), _("&Cancel"));
2876 dispatch(FuncRequest(LFUN_BUFFER_WRITE));
2878 return buffer->isClean() && !buffer->isUnnamed();
2882 bool GuiView::reloadBuffer(Buffer & buf)
2884 Buffer::ReadStatus status = buf.reload();
2885 return status == Buffer::ReadSuccess;
2889 void GuiView::checkExternallyModifiedBuffers()
2891 BufferList::iterator bit = theBufferList().begin();
2892 BufferList::iterator const bend = theBufferList().end();
2893 for (; bit != bend; ++bit) {
2894 Buffer * buf = *bit;
2895 if (buf->fileName().exists()
2896 && buf->isExternallyModified(Buffer::checksum_method)) {
2897 docstring text = bformat(_("Document \n%1$s\n has been externally modified."
2898 " Reload now? Any local changes will be lost."),
2899 from_utf8(buf->absFileName()));
2900 int const ret = Alert::prompt(_("Reload externally changed document?"),
2901 text, 0, 1, _("&Reload"), _("&Cancel"));
2909 void GuiView::dispatchVC(FuncRequest const & cmd, DispatchResult & dr)
2911 Buffer * buffer = documentBufferView()
2912 ? &(documentBufferView()->buffer()) : 0;
2914 switch (cmd.action()) {
2915 case LFUN_VC_REGISTER:
2916 if (!buffer || !ensureBufferClean(buffer))
2918 if (!buffer->lyxvc().inUse()) {
2919 if (buffer->lyxvc().registrer()) {
2920 reloadBuffer(*buffer);
2921 dr.clearMessageUpdate();
2926 case LFUN_VC_RENAME:
2927 case LFUN_VC_COPY: {
2928 if (!buffer || !ensureBufferClean(buffer))
2930 if (buffer->lyxvc().inUse() && !buffer->isReadonly()) {
2931 if (buffer->lyxvc().isCheckInWithConfirmation()) {
2932 // Some changes are not yet committed.
2933 // We test here and not in getStatus(), since
2934 // this test is expensive.
2936 LyXVC::CommandResult ret =
2937 buffer->lyxvc().checkIn(log);
2939 if (ret == LyXVC::ErrorCommand ||
2940 ret == LyXVC::VCSuccess)
2941 reloadBuffer(*buffer);
2942 if (buffer->lyxvc().isCheckInWithConfirmation()) {
2943 frontend::Alert::error(
2944 _("Revision control error."),
2945 _("Document could not be checked in."));
2949 RenameKind const kind = (cmd.action() == LFUN_VC_RENAME) ?
2950 LV_VC_RENAME : LV_VC_COPY;
2951 renameBuffer(*buffer, cmd.argument(), kind);
2956 case LFUN_VC_CHECK_IN:
2957 if (!buffer || !ensureBufferClean(buffer))
2959 if (buffer->lyxvc().inUse() && !buffer->isReadonly()) {
2961 LyXVC::CommandResult ret = buffer->lyxvc().checkIn(log);
2963 // Only skip reloading if the checkin was cancelled or
2964 // an error occured before the real checkin VCS command
2965 // was executed, since the VCS might have changed the
2966 // file even if it could not checkin successfully.
2967 if (ret == LyXVC::ErrorCommand || ret == LyXVC::VCSuccess)
2968 reloadBuffer(*buffer);
2972 case LFUN_VC_CHECK_OUT:
2973 if (!buffer || !ensureBufferClean(buffer))
2975 if (buffer->lyxvc().inUse()) {
2976 dr.setMessage(buffer->lyxvc().checkOut());
2977 reloadBuffer(*buffer);
2981 case LFUN_VC_LOCKING_TOGGLE:
2982 LASSERT(buffer, return);
2983 if (!ensureBufferClean(buffer) || buffer->isReadonly())
2985 if (buffer->lyxvc().inUse()) {
2986 string res = buffer->lyxvc().lockingToggle();
2988 frontend::Alert::error(_("Revision control error."),
2989 _("Error when setting the locking property."));
2992 reloadBuffer(*buffer);
2997 case LFUN_VC_REVERT:
2998 LASSERT(buffer, return);
2999 if (buffer->lyxvc().revert()) {
3000 reloadBuffer(*buffer);
3001 dr.clearMessageUpdate();
3005 case LFUN_VC_UNDO_LAST:
3006 LASSERT(buffer, return);
3007 buffer->lyxvc().undoLast();
3008 reloadBuffer(*buffer);
3009 dr.clearMessageUpdate();
3012 case LFUN_VC_REPO_UPDATE:
3013 LASSERT(buffer, return);
3014 if (ensureBufferClean(buffer)) {
3015 dr.setMessage(buffer->lyxvc().repoUpdate());
3016 checkExternallyModifiedBuffers();
3020 case LFUN_VC_COMMAND: {
3021 string flag = cmd.getArg(0);
3022 if (buffer && contains(flag, 'R') && !ensureBufferClean(buffer))
3025 if (contains(flag, 'M')) {
3026 if (!Alert::askForText(message, _("LyX VC: Log Message")))
3029 string path = cmd.getArg(1);
3030 if (contains(path, "$$p") && buffer)
3031 path = subst(path, "$$p", buffer->filePath());
3032 LYXERR(Debug::LYXVC, "Directory: " << path);
3034 if (!pp.isReadableDirectory()) {
3035 lyxerr << _("Directory is not accessible.") << endl;
3038 support::PathChanger p(pp);
3040 string command = cmd.getArg(2);
3041 if (command.empty())
3044 command = subst(command, "$$i", buffer->absFileName());
3045 command = subst(command, "$$p", buffer->filePath());
3047 command = subst(command, "$$m", to_utf8(message));
3048 LYXERR(Debug::LYXVC, "Command: " << command);
3050 one.startscript(Systemcall::Wait, command);
3054 if (contains(flag, 'I'))
3055 buffer->markDirty();
3056 if (contains(flag, 'R'))
3057 reloadBuffer(*buffer);
3062 case LFUN_VC_COMPARE: {
3064 if (cmd.argument().empty()) {
3065 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "comparehistory"));
3069 string rev1 = cmd.getArg(0);
3073 if (!buffer->lyxvc().prepareFileRevision(rev1, f1))
3076 if (isStrInt(rev1) && convert<int>(rev1) <= 0) {
3077 f2 = buffer->absFileName();
3079 string rev2 = cmd.getArg(1);
3083 if (!buffer->lyxvc().prepareFileRevision(rev2, f2))
3087 LYXERR(Debug::LYXVC, "Launching comparison for fetched revisions:\n" <<
3088 f1 << "\n" << f2 << "\n" );
3089 string par = "compare run " + quoteName(f1) + " " + quoteName(f2);
3090 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, par));
3100 void GuiView::openChildDocument(string const & fname)
3102 LASSERT(documentBufferView(), return);
3103 Buffer & buffer = documentBufferView()->buffer();
3104 FileName const filename = support::makeAbsPath(fname, buffer.filePath());
3105 documentBufferView()->saveBookmark(false);
3107 if (theBufferList().exists(filename)) {
3108 child = theBufferList().getBuffer(filename);
3111 message(bformat(_("Opening child document %1$s..."),
3112 makeDisplayPath(filename.absFileName())));
3113 child = loadDocument(filename, false);
3115 // Set the parent name of the child document.
3116 // This makes insertion of citations and references in the child work,
3117 // when the target is in the parent or another child document.
3119 child->setParent(&buffer);
3123 bool GuiView::goToFileRow(string const & argument)
3127 size_t i = argument.find_last_of(' ');
3128 if (i != string::npos) {
3129 file_name = os::internal_path(trim(argument.substr(0, i)));
3130 istringstream is(argument.substr(i + 1));
3135 if (i == string::npos) {
3136 LYXERR0("Wrong argument: " << argument);
3140 string const abstmp = package().temp_dir().absFileName();
3141 string const realtmp = package().temp_dir().realPath();
3142 // We have to use os::path_prefix_is() here, instead of
3143 // simply prefixIs(), because the file name comes from
3144 // an external application and may need case adjustment.
3145 if (os::path_prefix_is(file_name, abstmp, os::CASE_ADJUSTED)
3146 || os::path_prefix_is(file_name, realtmp, os::CASE_ADJUSTED)) {
3147 // Needed by inverse dvi search. If it is a file
3148 // in tmpdir, call the apropriated function.
3149 // If tmpdir is a symlink, we may have the real
3150 // path passed back, so we correct for that.
3151 if (!prefixIs(file_name, abstmp))
3152 file_name = subst(file_name, realtmp, abstmp);
3153 buf = theBufferList().getBufferFromTmp(file_name);
3155 // Must replace extension of the file to be .lyx
3156 // and get full path
3157 FileName const s = fileSearch(string(),
3158 support::changeExtension(file_name, ".lyx"), "lyx");
3159 // Either change buffer or load the file
3160 if (theBufferList().exists(s))
3161 buf = theBufferList().getBuffer(s);
3162 else if (s.exists()) {
3163 buf = loadDocument(s);
3168 _("File does not exist: %1$s"),
3169 makeDisplayPath(file_name)));
3175 _("No buffer for file: %1$s."),
3176 makeDisplayPath(file_name))
3181 documentBufferView()->setCursorFromRow(row);
3187 Buffer::ExportStatus GuiView::GuiViewPrivate::runAndDestroy(const T& func, Buffer const * orig, Buffer * clone, string const & format)
3189 Buffer::ExportStatus const status = func(format);
3191 // the cloning operation will have produced a clone of the entire set of
3192 // documents, starting from the master. so we must delete those.
3193 Buffer * mbuf = const_cast<Buffer *>(clone->masterBuffer());
3195 busyBuffers.remove(orig);
3200 Buffer::ExportStatus GuiView::GuiViewPrivate::compileAndDestroy(Buffer const * orig, Buffer * clone, string const & format)
3202 Buffer::ExportStatus (Buffer::* mem_func)(std::string const &, bool) const = &Buffer::doExport;
3203 return runAndDestroy(lyx::bind(mem_func, clone, _1, true), orig, clone, format);
3207 Buffer::ExportStatus GuiView::GuiViewPrivate::exportAndDestroy(Buffer const * orig, Buffer * clone, string const & format)
3209 Buffer::ExportStatus (Buffer::* mem_func)(std::string const &, bool) const = &Buffer::doExport;
3210 return runAndDestroy(lyx::bind(mem_func, clone, _1, false), orig, clone, format);
3214 Buffer::ExportStatus GuiView::GuiViewPrivate::previewAndDestroy(Buffer const * orig, Buffer * clone, string const & format)
3216 Buffer::ExportStatus (Buffer::* mem_func)(std::string const &) const = &Buffer::preview;
3217 return runAndDestroy(lyx::bind(mem_func, clone, _1), orig, clone, format);
3221 bool GuiView::GuiViewPrivate::asyncBufferProcessing(
3222 string const & argument,
3223 Buffer const * used_buffer,
3224 docstring const & msg,
3225 Buffer::ExportStatus (*asyncFunc)(Buffer const *, Buffer *, string const &),
3226 Buffer::ExportStatus (Buffer::*syncFunc)(string const &, bool) const,
3227 Buffer::ExportStatus (Buffer::*previewFunc)(string const &) const)
3232 string format = argument;
3234 format = used_buffer->params().getDefaultOutputFormat();
3235 processing_format = format;
3236 #if EXPORT_in_THREAD
3238 progress_->clearMessages();
3241 GuiViewPrivate::busyBuffers.insert(used_buffer);
3242 Buffer * cloned_buffer = used_buffer->cloneFromMaster();
3243 if (!cloned_buffer) {
3244 Alert::error(_("Export Error"),
3245 _("Error cloning the Buffer."));
3248 QFuture<Buffer::ExportStatus> f = QtConcurrent::run(
3253 setPreviewFuture(f);
3254 last_export_format = used_buffer->params().bufferFormat();
3257 // We are asynchronous, so we don't know here anything about the success
3260 Buffer::ExportStatus status;
3262 // TODO check here if it breaks exporting with Qt < 4.4
3263 status = (used_buffer->*syncFunc)(format, true);
3264 } else if (previewFunc) {
3265 status = (used_buffer->*previewFunc)(format);
3268 handleExportStatus(gv_, status, format);
3270 return (status == Buffer::ExportSuccess
3271 || status == Buffer::PreviewSuccess);
3275 void GuiView::dispatchToBufferView(FuncRequest const & cmd, DispatchResult & dr)
3277 BufferView * bv = currentBufferView();
3278 LASSERT(bv, return);
3280 // Let the current BufferView dispatch its own actions.
3281 bv->dispatch(cmd, dr);
3282 if (dr.dispatched())
3285 // Try with the document BufferView dispatch if any.
3286 BufferView * doc_bv = documentBufferView();
3287 if (doc_bv && doc_bv != bv) {
3288 doc_bv->dispatch(cmd, dr);
3289 if (dr.dispatched())
3293 // Then let the current Cursor dispatch its own actions.
3294 bv->cursor().dispatch(cmd);
3296 // update completion. We do it here and not in
3297 // processKeySym to avoid another redraw just for a
3298 // changed inline completion
3299 if (cmd.origin() == FuncRequest::KEYBOARD) {
3300 if (cmd.action() == LFUN_SELF_INSERT
3301 || (cmd.action() == LFUN_ERT_INSERT && bv->cursor().inMathed()))
3302 updateCompletion(bv->cursor(), true, true);
3303 else if (cmd.action() == LFUN_CHAR_DELETE_BACKWARD)
3304 updateCompletion(bv->cursor(), false, true);
3306 updateCompletion(bv->cursor(), false, false);
3309 dr = bv->cursor().result();
3313 void GuiView::dispatch(FuncRequest const & cmd, DispatchResult & dr)
3315 BufferView * bv = currentBufferView();
3316 // By default we won't need any update.
3317 dr.screenUpdate(Update::None);
3318 // assume cmd will be dispatched
3319 dr.dispatched(true);
3321 Buffer * doc_buffer = documentBufferView()
3322 ? &(documentBufferView()->buffer()) : 0;
3324 if (cmd.origin() == FuncRequest::TOC) {
3325 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
3326 // FIXME: do we need to pass a DispatchResult object here?
3327 toc->doDispatch(bv->cursor(), cmd);
3331 string const argument = to_utf8(cmd.argument());
3333 switch(cmd.action()) {
3334 case LFUN_BUFFER_CHILD_OPEN:
3335 openChildDocument(to_utf8(cmd.argument()));
3338 case LFUN_BUFFER_IMPORT:
3339 importDocument(to_utf8(cmd.argument()));
3342 case LFUN_BUFFER_EXPORT: {
3345 FileName target_dir = doc_buffer->fileName().onlyPath();
3346 string const dest = cmd.getArg(1);
3347 if (!dest.empty() && FileName::isAbsolute(dest))
3348 target_dir = FileName(support::onlyPath(dest));
3349 // GCC only sees strfwd.h when building merged
3350 if (::lyx::operator==(cmd.argument(), "custom")) {
3351 dispatch(FuncRequest(LFUN_DIALOG_SHOW, "sendto"), dr);
3354 if (!target_dir.isDirWritable()) {
3355 exportBufferAs(*doc_buffer, cmd.argument());
3358 /* TODO/Review: Is it a problem to also export the children?
3359 See the update_unincluded flag */
3360 d.asyncBufferProcessing(argument,
3363 &GuiViewPrivate::exportAndDestroy,
3366 // TODO Inform user about success
3370 case LFUN_BUFFER_EXPORT_AS: {
3371 LASSERT(doc_buffer, break);
3372 docstring f = cmd.argument();
3374 f = from_ascii(doc_buffer->params().getDefaultOutputFormat());
3375 exportBufferAs(*doc_buffer, f);
3379 case LFUN_BUFFER_UPDATE: {
3380 d.asyncBufferProcessing(argument,
3383 &GuiViewPrivate::compileAndDestroy,
3388 case LFUN_BUFFER_VIEW: {
3389 d.asyncBufferProcessing(argument,
3391 _("Previewing ..."),
3392 &GuiViewPrivate::previewAndDestroy,
3397 case LFUN_MASTER_BUFFER_UPDATE: {
3398 d.asyncBufferProcessing(argument,
3399 (doc_buffer ? doc_buffer->masterBuffer() : 0),
3401 &GuiViewPrivate::compileAndDestroy,
3406 case LFUN_MASTER_BUFFER_VIEW: {
3407 d.asyncBufferProcessing(argument,
3408 (doc_buffer ? doc_buffer->masterBuffer() : 0),
3410 &GuiViewPrivate::previewAndDestroy,
3411 0, &Buffer::preview);
3414 case LFUN_BUFFER_SWITCH: {
3415 string const file_name = to_utf8(cmd.argument());
3416 if (!FileName::isAbsolute(file_name)) {
3418 dr.setMessage(_("Absolute filename expected."));
3422 Buffer * buffer = theBufferList().getBuffer(FileName(file_name));
3425 dr.setMessage(_("Document not loaded"));
3429 // Do we open or switch to the buffer in this view ?
3430 if (workArea(*buffer)
3431 || lyxrc.open_buffers_in_tabs || !documentBufferView()) {
3436 // Look for the buffer in other views
3437 QList<int> const ids = guiApp->viewIds();
3439 for (; i != ids.size(); ++i) {
3440 GuiView & gv = guiApp->view(ids[i]);
3441 if (gv.workArea(*buffer)) {
3442 gv.activateWindow();
3443 gv.setBuffer(buffer);
3448 // If necessary, open a new window as a last resort
3449 if (i == ids.size()) {
3450 lyx::dispatch(FuncRequest(LFUN_WINDOW_NEW));
3456 case LFUN_BUFFER_NEXT:
3457 gotoNextOrPreviousBuffer(NEXTBUFFER);
3460 case LFUN_BUFFER_PREVIOUS:
3461 gotoNextOrPreviousBuffer(PREVBUFFER);
3464 case LFUN_COMMAND_EXECUTE: {
3465 bool const show_it = cmd.argument() != "off";
3466 // FIXME: this is a hack, "minibuffer" should not be
3468 if (GuiToolbar * t = toolbar("minibuffer")) {
3469 t->setVisible(show_it);
3470 if (show_it && t->commandBuffer())
3471 t->commandBuffer()->setFocus();
3475 case LFUN_DROP_LAYOUTS_CHOICE:
3476 d.layout_->showPopup();
3479 case LFUN_MENU_OPEN:
3480 if (QMenu * menu = guiApp->menus().menu(toqstr(cmd.argument()), *this))
3481 menu->exec(QCursor::pos());
3484 case LFUN_FILE_INSERT:
3485 insertLyXFile(cmd.argument());
3488 case LFUN_FILE_INSERT_PLAINTEXT:
3489 case LFUN_FILE_INSERT_PLAINTEXT_PARA: {
3490 string const fname = to_utf8(cmd.argument());
3491 if (!fname.empty() && !FileName::isAbsolute(fname)) {
3492 dr.setMessage(_("Absolute filename expected."));
3496 FileName filename(fname);
3497 if (fname.empty()) {
3498 FileDialog dlg(qt_("Select file to insert"));
3500 FileDialog::Result result = dlg.open(toqstr(bv->buffer().filePath()),
3501 QStringList(qt_("All Files (*)")));
3503 if (result.first == FileDialog::Later || result.second.isEmpty()) {
3504 dr.setMessage(_("Canceled."));
3508 filename.set(fromqstr(result.second));
3512 FuncRequest const new_cmd(cmd, filename.absoluteFilePath());
3513 bv->dispatch(new_cmd, dr);
3518 case LFUN_BUFFER_RELOAD: {
3519 LASSERT(doc_buffer, break);
3522 if (!doc_buffer->isClean()) {
3523 docstring const file =
3524 makeDisplayPath(doc_buffer->absFileName(), 20);
3525 docstring text = bformat(_("Any changes will be lost. "
3526 "Are you sure you want to revert to the saved version "
3527 "of the document %1$s?"), file);
3528 ret = Alert::prompt(_("Revert to saved document?"),
3529 text, 1, 1, _("&Revert"), _("&Cancel"));
3533 doc_buffer->markClean();
3534 reloadBuffer(*doc_buffer);
3535 dr.forceBufferUpdate();
3540 case LFUN_BUFFER_WRITE:
3541 LASSERT(doc_buffer, break);
3542 saveBuffer(*doc_buffer);
3545 case LFUN_BUFFER_WRITE_AS:
3546 LASSERT(doc_buffer, break);
3547 renameBuffer(*doc_buffer, cmd.argument());
3550 case LFUN_BUFFER_WRITE_ALL: {
3551 Buffer * first = theBufferList().first();
3554 message(_("Saving all documents..."));
3555 // We cannot use a for loop as the buffer list cycles.
3558 if (!b->isClean()) {
3560 LYXERR(Debug::ACTION, "Saved " << b->absFileName());
3562 b = theBufferList().next(b);
3563 } while (b != first);
3564 dr.setMessage(_("All documents saved."));
3568 case LFUN_BUFFER_CLOSE:
3572 case LFUN_BUFFER_CLOSE_ALL:
3576 case LFUN_TOOLBAR_TOGGLE: {
3577 string const name = cmd.getArg(0);
3578 if (GuiToolbar * t = toolbar(name))
3583 case LFUN_DIALOG_UPDATE: {
3584 string const name = to_utf8(cmd.argument());
3585 if (name == "prefs" || name == "document")
3586 updateDialog(name, string());
3587 else if (name == "paragraph")
3588 lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
3589 else if (currentBufferView()) {
3590 Inset * inset = currentBufferView()->editedInset(name);
3591 // Can only update a dialog connected to an existing inset
3593 // FIXME: get rid of this indirection; GuiView ask the inset
3594 // if he is kind enough to update itself...
3595 FuncRequest fr(LFUN_INSET_DIALOG_UPDATE, cmd.argument());
3596 //FIXME: pass DispatchResult here?
3597 inset->dispatch(currentBufferView()->cursor(), fr);
3603 case LFUN_DIALOG_TOGGLE: {
3604 FuncCode const func_code = isDialogVisible(cmd.getArg(0))
3605 ? LFUN_DIALOG_HIDE : LFUN_DIALOG_SHOW;
3606 dispatch(FuncRequest(func_code, cmd.argument()), dr);
3610 case LFUN_DIALOG_DISCONNECT_INSET:
3611 disconnectDialog(to_utf8(cmd.argument()));
3614 case LFUN_DIALOG_HIDE: {
3615 guiApp->hideDialogs(to_utf8(cmd.argument()), 0);
3619 case LFUN_DIALOG_SHOW: {
3620 string const name = cmd.getArg(0);
3621 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
3623 if (name == "character") {
3624 data = freefont2string();
3626 showDialog("character", data);
3627 } else if (name == "latexlog") {
3628 Buffer::LogType type;
3629 string const logfile = doc_buffer->logName(&type);
3631 case Buffer::latexlog:
3634 case Buffer::buildlog:
3638 data += Lexer::quoteString(logfile);
3639 showDialog("log", data);
3640 } else if (name == "vclog") {
3641 string const data = "vc " +
3642 Lexer::quoteString(doc_buffer->lyxvc().getLogFile());
3643 showDialog("log", data);
3644 } else if (name == "symbols") {
3645 data = bv->cursor().getEncoding()->name();
3647 showDialog("symbols", data);
3649 } else if (name == "prefs" && isFullScreen()) {
3650 lfunUiToggle("fullscreen");
3651 showDialog("prefs", data);
3653 showDialog(name, data);
3658 dr.setMessage(cmd.argument());
3661 case LFUN_UI_TOGGLE: {
3662 string arg = cmd.getArg(0);
3663 if (!lfunUiToggle(arg)) {
3664 docstring const msg = "ui-toggle " + _("%1$s unknown command!");
3665 dr.setMessage(bformat(msg, from_utf8(arg)));
3667 // Make sure the keyboard focus stays in the work area.
3672 case LFUN_VIEW_SPLIT: {
3673 LASSERT(doc_buffer, break);
3674 string const orientation = cmd.getArg(0);
3675 d.splitter_->setOrientation(orientation == "vertical"
3676 ? Qt::Vertical : Qt::Horizontal);
3677 TabWorkArea * twa = addTabWorkArea();
3678 GuiWorkArea * wa = twa->addWorkArea(*doc_buffer, *this);
3679 setCurrentWorkArea(wa);
3682 case LFUN_TAB_GROUP_CLOSE:
3683 if (TabWorkArea * twa = d.currentTabWorkArea()) {
3684 closeTabWorkArea(twa);
3685 d.current_work_area_ = 0;
3686 twa = d.currentTabWorkArea();
3687 // Switch to the next GuiWorkArea in the found TabWorkArea.
3689 // Make sure the work area is up to date.
3690 setCurrentWorkArea(twa->currentWorkArea());
3692 setCurrentWorkArea(0);
3697 case LFUN_VIEW_CLOSE:
3698 if (TabWorkArea * twa = d.currentTabWorkArea()) {
3699 closeWorkArea(twa->currentWorkArea());
3700 d.current_work_area_ = 0;
3701 twa = d.currentTabWorkArea();
3702 // Switch to the next GuiWorkArea in the found TabWorkArea.
3704 // Make sure the work area is up to date.
3705 setCurrentWorkArea(twa->currentWorkArea());
3707 setCurrentWorkArea(0);
3712 case LFUN_COMPLETION_INLINE:
3713 if (d.current_work_area_)
3714 d.current_work_area_->completer().showInline();
3717 case LFUN_COMPLETION_POPUP:
3718 if (d.current_work_area_)
3719 d.current_work_area_->completer().showPopup();
3724 if (d.current_work_area_)
3725 d.current_work_area_->completer().tab();
3728 case LFUN_COMPLETION_CANCEL:
3729 if (d.current_work_area_) {
3730 if (d.current_work_area_->completer().popupVisible())
3731 d.current_work_area_->completer().hidePopup();
3733 d.current_work_area_->completer().hideInline();
3737 case LFUN_COMPLETION_ACCEPT:
3738 if (d.current_work_area_)
3739 d.current_work_area_->completer().activate();
3742 case LFUN_BUFFER_ZOOM_IN:
3743 case LFUN_BUFFER_ZOOM_OUT:
3744 if (cmd.argument().empty()) {
3745 if (cmd.action() == LFUN_BUFFER_ZOOM_IN)
3750 lyxrc.zoom += convert<int>(cmd.argument());
3752 if (lyxrc.zoom < 10)
3755 // The global QPixmapCache is used in GuiPainter to cache text
3756 // painting so we must reset it.
3757 QPixmapCache::clear();
3758 guiApp->fontLoader().update();
3759 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
3762 case LFUN_VC_REGISTER:
3763 case LFUN_VC_RENAME:
3765 case LFUN_VC_CHECK_IN:
3766 case LFUN_VC_CHECK_OUT:
3767 case LFUN_VC_REPO_UPDATE:
3768 case LFUN_VC_LOCKING_TOGGLE:
3769 case LFUN_VC_REVERT:
3770 case LFUN_VC_UNDO_LAST:
3771 case LFUN_VC_COMMAND:
3772 case LFUN_VC_COMPARE:
3773 dispatchVC(cmd, dr);
3776 case LFUN_SERVER_GOTO_FILE_ROW:
3777 goToFileRow(to_utf8(cmd.argument()));
3780 case LFUN_FORWARD_SEARCH: {
3781 Buffer const * doc_master = doc_buffer->masterBuffer();
3782 FileName const path(doc_master->temppath());
3783 string const texname = doc_master->isChild(doc_buffer)
3784 ? DocFileName(changeExtension(
3785 doc_buffer->absFileName(),
3786 "tex")).mangledFileName()
3787 : doc_buffer->latexName();
3788 string const fulltexname =
3789 support::makeAbsPath(texname, doc_master->temppath()).absFileName();
3790 string const mastername =
3791 removeExtension(doc_master->latexName());
3792 FileName const dviname(addName(path.absFileName(),
3793 addExtension(mastername, "dvi")));
3794 FileName const pdfname(addName(path.absFileName(),
3795 addExtension(mastername, "pdf")));
3796 bool const have_dvi = dviname.exists();
3797 bool const have_pdf = pdfname.exists();
3798 if (!have_dvi && !have_pdf) {
3799 dr.setMessage(_("Please, preview the document first."));
3802 string outname = dviname.onlyFileName();
3803 string command = lyxrc.forward_search_dvi;
3804 if (!have_dvi || (have_pdf &&
3805 pdfname.lastModified() > dviname.lastModified())) {
3806 outname = pdfname.onlyFileName();
3807 command = lyxrc.forward_search_pdf;
3810 DocIterator tmpcur = bv->cursor();
3812 while (tmpcur.inMathed())
3814 int row = tmpcur.inMathed() ? 0 : doc_buffer->texrow().getRowFromIdPos(
3815 tmpcur.paragraph().id(), tmpcur.pos());
3816 LYXERR(Debug::ACTION, "Forward search: row:" << row
3817 << " id:" << tmpcur.paragraph().id());
3818 if (!row || command.empty()) {
3819 dr.setMessage(_("Couldn't proceed."));
3822 string texrow = convert<string>(row);
3824 command = subst(command, "$$n", texrow);
3825 command = subst(command, "$$f", fulltexname);
3826 command = subst(command, "$$t", texname);
3827 command = subst(command, "$$o", outname);
3829 PathChanger p(path);
3831 one.startscript(Systemcall::DontWait, command);
3835 case LFUN_SPELLING_CONTINUOUSLY:
3836 lyxrc.spellcheck_continuously = !lyxrc.spellcheck_continuously;
3837 dr.screenUpdate(Update::Force | Update::FitCursor);
3841 // The LFUN must be for one of BufferView, Buffer or Cursor;
3843 dispatchToBufferView(cmd, dr);
3847 // Part of automatic menu appearance feature.
3848 if (isFullScreen()) {
3849 if (menuBar()->isVisible() && lyxrc.full_screen_menubar)
3855 bool GuiView::lfunUiToggle(string const & ui_component)
3857 if (ui_component == "scrollbar") {
3858 // hide() is of no help
3859 if (d.current_work_area_->verticalScrollBarPolicy() ==
3860 Qt::ScrollBarAlwaysOff)
3862 d.current_work_area_->setVerticalScrollBarPolicy(
3863 Qt::ScrollBarAsNeeded);
3865 d.current_work_area_->setVerticalScrollBarPolicy(
3866 Qt::ScrollBarAlwaysOff);
3867 } else if (ui_component == "statusbar") {
3868 statusBar()->setVisible(!statusBar()->isVisible());
3869 } else if (ui_component == "menubar") {
3870 menuBar()->setVisible(!menuBar()->isVisible());
3872 if (ui_component == "frame") {
3874 getContentsMargins(&l, &t, &r, &b);
3875 //are the frames in default state?
3876 d.current_work_area_->setFrameStyle(QFrame::NoFrame);
3878 setContentsMargins(-2, -2, -2, -2);
3880 setContentsMargins(0, 0, 0, 0);
3883 if (ui_component == "fullscreen") {
3891 void GuiView::toggleFullScreen()
3893 if (isFullScreen()) {
3894 for (int i = 0; i != d.splitter_->count(); ++i)
3895 d.tabWorkArea(i)->setFullScreen(false);
3896 setContentsMargins(0, 0, 0, 0);
3897 setWindowState(windowState() ^ Qt::WindowFullScreen);
3900 statusBar()->show();
3903 hideDialogs("prefs", 0);
3904 for (int i = 0; i != d.splitter_->count(); ++i)
3905 d.tabWorkArea(i)->setFullScreen(true);
3906 setContentsMargins(-2, -2, -2, -2);
3908 setWindowState(windowState() ^ Qt::WindowFullScreen);
3909 if (lyxrc.full_screen_statusbar)
3910 statusBar()->hide();
3911 if (lyxrc.full_screen_menubar)
3913 if (lyxrc.full_screen_toolbars) {
3914 ToolbarMap::iterator end = d.toolbars_.end();
3915 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
3920 // give dialogs like the TOC a chance to adapt
3925 Buffer const * GuiView::updateInset(Inset const * inset)
3930 Buffer const * inset_buffer = &(inset->buffer());
3932 for (int i = 0; i != d.splitter_->count(); ++i) {
3933 GuiWorkArea * wa = d.tabWorkArea(i)->currentWorkArea();
3936 Buffer const * buffer = &(wa->bufferView().buffer());
3937 if (inset_buffer == buffer)
3938 wa->scheduleRedraw();
3940 return inset_buffer;
3944 void GuiView::restartCursor()
3946 /* When we move around, or type, it's nice to be able to see
3947 * the cursor immediately after the keypress.
3949 if (d.current_work_area_)
3950 d.current_work_area_->startBlinkingCursor();
3952 // Take this occasion to update the other GUI elements.
3958 void GuiView::updateCompletion(Cursor & cur, bool start, bool keep)
3960 if (d.current_work_area_)
3961 d.current_work_area_->completer().updateVisibility(cur, start, keep);
3966 // This list should be kept in sync with the list of insets in
3967 // src/insets/Inset.cpp. I.e., if a dialog goes with an inset, the
3968 // dialog should have the same name as the inset.
3969 // Changes should be also recorded in LFUN_DIALOG_SHOW doxygen
3970 // docs in LyXAction.cpp.
3972 char const * const dialognames[] = {
3974 "aboutlyx", "bibitem", "bibtex", "box", "branch", "changes", "character",
3975 "citation", "compare", "comparehistory", "document", "errorlist", "ert",
3976 "external", "file", "findreplace", "findreplaceadv", "float", "graphics",
3977 "href", "include", "index", "index_print", "info", "listings", "label", "line",
3978 "log", "mathdelimiter", "mathmatrix", "mathspace", "nomenclature",
3979 "nomencl_print", "note", "paragraph", "phantom", "prefs", "print", "ref",
3980 "sendto", "space", "spellchecker", "symbols", "tabular", "tabularcreate",
3981 "thesaurus", "texinfo", "toc", "view-source", "vspace", "wrap", "progress"};
3983 char const * const * const end_dialognames =
3984 dialognames + (sizeof(dialognames) / sizeof(char *));
3988 cmpCStr(char const * name) : name_(name) {}
3989 bool operator()(char const * other) {
3990 return strcmp(other, name_) == 0;
3997 bool isValidName(string const & name)
3999 return find_if(dialognames, end_dialognames,
4000 cmpCStr(name.c_str())) != end_dialognames;
4006 void GuiView::resetDialogs()
4008 // Make sure that no LFUN uses any GuiView.
4009 guiApp->setCurrentView(0);
4013 constructToolbars();
4014 guiApp->menus().fillMenuBar(menuBar(), this, false);
4015 d.layout_->updateContents(true);
4016 // Now update controls with current buffer.
4017 guiApp->setCurrentView(this);
4023 Dialog * GuiView::findOrBuild(string const & name, bool hide_it)
4025 if (!isValidName(name))
4028 map<string, DialogPtr>::iterator it = d.dialogs_.find(name);
4030 if (it != d.dialogs_.end()) {
4032 it->second->hideView();
4033 return it->second.get();
4036 Dialog * dialog = build(name);
4037 d.dialogs_[name].reset(dialog);
4038 if (lyxrc.allow_geometry_session)
4039 dialog->restoreSession();
4046 void GuiView::showDialog(string const & name, string const & data,
4049 triggerShowDialog(toqstr(name), toqstr(data), inset);
4053 void GuiView::doShowDialog(QString const & qname, QString const & qdata,
4059 const string name = fromqstr(qname);
4060 const string data = fromqstr(qdata);
4064 Dialog * dialog = findOrBuild(name, false);
4066 bool const visible = dialog->isVisibleView();
4067 dialog->showData(data);
4068 if (inset && currentBufferView())
4069 currentBufferView()->editInset(name, inset);
4070 // We only set the focus to the new dialog if it was not yet
4071 // visible in order not to change the existing previous behaviour
4073 // activateWindow is needed for floating dockviews
4074 dialog->asQWidget()->raise();
4075 dialog->asQWidget()->activateWindow();
4076 dialog->asQWidget()->setFocus();
4080 catch (ExceptionMessage const & ex) {
4088 bool GuiView::isDialogVisible(string const & name) const
4090 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
4091 if (it == d.dialogs_.end())
4093 return it->second.get()->isVisibleView() && !it->second.get()->isClosing();
4097 void GuiView::hideDialog(string const & name, Inset * inset)
4099 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
4100 if (it == d.dialogs_.end())
4104 if (!currentBufferView())
4106 if (inset != currentBufferView()->editedInset(name))
4110 Dialog * const dialog = it->second.get();
4111 if (dialog->isVisibleView())
4113 if (currentBufferView())
4114 currentBufferView()->editInset(name, 0);
4118 void GuiView::disconnectDialog(string const & name)
4120 if (!isValidName(name))
4122 if (currentBufferView())
4123 currentBufferView()->editInset(name, 0);
4127 void GuiView::hideAll() const
4129 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
4130 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
4132 for(; it != end; ++it)
4133 it->second->hideView();
4137 void GuiView::updateDialogs()
4139 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
4140 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
4142 for(; it != end; ++it) {
4143 Dialog * dialog = it->second.get();
4145 if (dialog->needBufferOpen() && !documentBufferView())
4146 hideDialog(fromqstr(dialog->name()), 0);
4147 else if (dialog->isVisibleView())
4148 dialog->checkStatus();
4155 Dialog * createDialog(GuiView & lv, string const & name);
4157 // will be replaced by a proper factory...
4158 Dialog * createGuiAbout(GuiView & lv);
4159 Dialog * createGuiBibtex(GuiView & lv);
4160 Dialog * createGuiChanges(GuiView & lv);
4161 Dialog * createGuiCharacter(GuiView & lv);
4162 Dialog * createGuiCitation(GuiView & lv);
4163 Dialog * createGuiCompare(GuiView & lv);
4164 Dialog * createGuiCompareHistory(GuiView & lv);
4165 Dialog * createGuiDelimiter(GuiView & lv);
4166 Dialog * createGuiDocument(GuiView & lv);
4167 Dialog * createGuiErrorList(GuiView & lv);
4168 Dialog * createGuiExternal(GuiView & lv);
4169 Dialog * createGuiGraphics(GuiView & lv);
4170 Dialog * createGuiInclude(GuiView & lv);
4171 Dialog * createGuiIndex(GuiView & lv);
4172 Dialog * createGuiListings(GuiView & lv);
4173 Dialog * createGuiLog(GuiView & lv);
4174 Dialog * createGuiMathMatrix(GuiView & lv);
4175 Dialog * createGuiNote(GuiView & lv);
4176 Dialog * createGuiParagraph(GuiView & lv);
4177 Dialog * createGuiPhantom(GuiView & lv);
4178 Dialog * createGuiPreferences(GuiView & lv);
4179 Dialog * createGuiPrint(GuiView & lv);
4180 Dialog * createGuiPrintindex(GuiView & lv);
4181 Dialog * createGuiRef(GuiView & lv);
4182 Dialog * createGuiSearch(GuiView & lv);
4183 Dialog * createGuiSearchAdv(GuiView & lv);
4184 Dialog * createGuiSendTo(GuiView & lv);
4185 Dialog * createGuiShowFile(GuiView & lv);
4186 Dialog * createGuiSpellchecker(GuiView & lv);
4187 Dialog * createGuiSymbols(GuiView & lv);
4188 Dialog * createGuiTabularCreate(GuiView & lv);
4189 Dialog * createGuiTexInfo(GuiView & lv);
4190 Dialog * createGuiToc(GuiView & lv);
4191 Dialog * createGuiThesaurus(GuiView & lv);
4192 Dialog * createGuiViewSource(GuiView & lv);
4193 Dialog * createGuiWrap(GuiView & lv);
4194 Dialog * createGuiProgressView(GuiView & lv);
4198 Dialog * GuiView::build(string const & name)
4200 LASSERT(isValidName(name), return 0);
4202 Dialog * dialog = createDialog(*this, name);
4206 if (name == "aboutlyx")
4207 return createGuiAbout(*this);
4208 if (name == "bibtex")
4209 return createGuiBibtex(*this);
4210 if (name == "changes")
4211 return createGuiChanges(*this);
4212 if (name == "character")
4213 return createGuiCharacter(*this);
4214 if (name == "citation")
4215 return createGuiCitation(*this);
4216 if (name == "compare")
4217 return createGuiCompare(*this);
4218 if (name == "comparehistory")
4219 return createGuiCompareHistory(*this);
4220 if (name == "document")
4221 return createGuiDocument(*this);
4222 if (name == "errorlist")
4223 return createGuiErrorList(*this);
4224 if (name == "external")
4225 return createGuiExternal(*this);
4227 return createGuiShowFile(*this);
4228 if (name == "findreplace")
4229 return createGuiSearch(*this);
4230 if (name == "findreplaceadv")
4231 return createGuiSearchAdv(*this);
4232 if (name == "graphics")
4233 return createGuiGraphics(*this);
4234 if (name == "include")
4235 return createGuiInclude(*this);
4236 if (name == "index")
4237 return createGuiIndex(*this);
4238 if (name == "index_print")
4239 return createGuiPrintindex(*this);
4240 if (name == "listings")
4241 return createGuiListings(*this);
4243 return createGuiLog(*this);
4244 if (name == "mathdelimiter")
4245 return createGuiDelimiter(*this);
4246 if (name == "mathmatrix")
4247 return createGuiMathMatrix(*this);
4249 return createGuiNote(*this);
4250 if (name == "paragraph")
4251 return createGuiParagraph(*this);
4252 if (name == "phantom")
4253 return createGuiPhantom(*this);
4254 if (name == "prefs")
4255 return createGuiPreferences(*this);
4256 if (name == "print")
4257 return createGuiPrint(*this);
4259 return createGuiRef(*this);
4260 if (name == "sendto")
4261 return createGuiSendTo(*this);
4262 if (name == "spellchecker")
4263 return createGuiSpellchecker(*this);
4264 if (name == "symbols")
4265 return createGuiSymbols(*this);
4266 if (name == "tabularcreate")
4267 return createGuiTabularCreate(*this);
4268 if (name == "texinfo")
4269 return createGuiTexInfo(*this);
4270 if (name == "thesaurus")
4271 return createGuiThesaurus(*this);
4273 return createGuiToc(*this);
4274 if (name == "view-source")
4275 return createGuiViewSource(*this);
4277 return createGuiWrap(*this);
4278 if (name == "progress")
4279 return createGuiProgressView(*this);
4285 } // namespace frontend
4288 #include "moc_GuiView.cpp"