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 int x = (width() - splash_.width()) / 2;
176 int y = (height() - splash_.height()) / 2;
178 pain.drawPixmap(x, y, splash_);
181 void keyPressEvent(QKeyEvent * ev)
184 setKeySymbol(&sym, ev);
186 guiApp->processKeySym(sym, q_key_state(ev->modifiers()));
198 /// Toolbar store providing access to individual toolbars by name.
199 typedef map<string, GuiToolbar *> ToolbarMap;
201 typedef shared_ptr<Dialog> DialogPtr;
206 struct GuiView::GuiViewPrivate
208 GuiViewPrivate(GuiView * gv)
209 : gv_(gv), current_work_area_(0), current_main_work_area_(0),
210 layout_(0), autosave_timeout_(5000),
213 // hardcode here the platform specific icon size
214 smallIconSize = 16; // scaling problems
215 normalIconSize = 20; // ok, default if iconsize.png is missing
216 bigIconSize = 26; // better for some math icons
218 // if it exists, use width of iconsize.png as normal size
219 QString const dir = toqstr(addPath("images", lyxrc.icon_set));
220 FileName const fn = lyx::libFileSearch(dir, "iconsize.png");
222 QImage image(toqstr(fn.absFileName()));
223 if (image.width() < int(smallIconSize))
224 normalIconSize = smallIconSize;
225 else if (image.width() > int(bigIconSize))
226 normalIconSize = bigIconSize;
228 normalIconSize = image.width();
231 splitter_ = new QSplitter;
232 bg_widget_ = new BackgroundWidget;
233 stack_widget_ = new QStackedWidget;
234 stack_widget_->addWidget(bg_widget_);
235 stack_widget_->addWidget(splitter_);
238 // TODO cleanup, remove the singleton, handle multiple Windows?
239 progress_ = ProgressInterface::instance();
240 if (!dynamic_cast<GuiProgress*>(progress_)) {
241 progress_ = new GuiProgress; // TODO who deletes it
242 ProgressInterface::setInstance(progress_);
245 dynamic_cast<GuiProgress*>(progress_),
246 SIGNAL(updateStatusBarMessage(QString const&)),
247 gv, SLOT(updateStatusBarMessage(QString const&)));
249 dynamic_cast<GuiProgress*>(progress_),
250 SIGNAL(clearMessageText()),
251 gv, SLOT(clearMessageText()));
258 delete stack_widget_;
261 QMenu * toolBarPopup(GuiView * parent)
263 // FIXME: translation
264 QMenu * menu = new QMenu(parent);
265 QActionGroup * iconSizeGroup = new QActionGroup(parent);
267 QAction * smallIcons = new QAction(iconSizeGroup);
268 smallIcons->setText(qt_("Small-sized icons"));
269 smallIcons->setCheckable(true);
270 QObject::connect(smallIcons, SIGNAL(triggered()),
271 parent, SLOT(smallSizedIcons()));
272 menu->addAction(smallIcons);
274 QAction * normalIcons = new QAction(iconSizeGroup);
275 normalIcons->setText(qt_("Normal-sized icons"));
276 normalIcons->setCheckable(true);
277 QObject::connect(normalIcons, SIGNAL(triggered()),
278 parent, SLOT(normalSizedIcons()));
279 menu->addAction(normalIcons);
281 QAction * bigIcons = new QAction(iconSizeGroup);
282 bigIcons->setText(qt_("Big-sized icons"));
283 bigIcons->setCheckable(true);
284 QObject::connect(bigIcons, SIGNAL(triggered()),
285 parent, SLOT(bigSizedIcons()));
286 menu->addAction(bigIcons);
288 unsigned int cur = parent->iconSize().width();
289 if ( cur == parent->d.smallIconSize)
290 smallIcons->setChecked(true);
291 else if (cur == parent->d.normalIconSize)
292 normalIcons->setChecked(true);
293 else if (cur == parent->d.bigIconSize)
294 bigIcons->setChecked(true);
301 stack_widget_->setCurrentWidget(bg_widget_);
302 bg_widget_->setUpdatesEnabled(true);
303 bg_widget_->setFocus();
306 int tabWorkAreaCount()
308 return splitter_->count();
311 TabWorkArea * tabWorkArea(int i)
313 return dynamic_cast<TabWorkArea *>(splitter_->widget(i));
316 TabWorkArea * currentTabWorkArea()
318 int areas = tabWorkAreaCount();
320 // The first TabWorkArea is always the first one, if any.
321 return tabWorkArea(0);
323 for (int i = 0; i != areas; ++i) {
324 TabWorkArea * twa = tabWorkArea(i);
325 if (current_main_work_area_ == twa->currentWorkArea())
329 // None has the focus so we just take the first one.
330 return tabWorkArea(0);
333 int countWorkAreasOf(Buffer & buf)
335 int areas = tabWorkAreaCount();
337 for (int i = 0; i != areas; ++i) {
338 TabWorkArea * twa = tabWorkArea(i);
339 if (twa->workArea(buf))
345 void setPreviewFuture(QFuture<Buffer::ExportStatus> const & f)
347 if (processing_thread_watcher_.isRunning()) {
348 // we prefer to cancel this preview in order to keep a snappy
352 processing_thread_watcher_.setFuture(f);
357 GuiWorkArea * current_work_area_;
358 GuiWorkArea * current_main_work_area_;
359 QSplitter * splitter_;
360 QStackedWidget * stack_widget_;
361 BackgroundWidget * bg_widget_;
363 ToolbarMap toolbars_;
364 ProgressInterface* progress_;
365 /// The main layout box.
367 * \warning Don't Delete! The layout box is actually owned by
368 * whichever toolbar contains it. All the GuiView class needs is a
369 * means of accessing it.
371 * FIXME: replace that with a proper model so that we are not limited
372 * to only one dialog.
377 map<string, DialogPtr> dialogs_;
379 unsigned int smallIconSize;
380 unsigned int normalIconSize;
381 unsigned int bigIconSize;
383 QTimer statusbar_timer_;
384 /// auto-saving of buffers
385 Timeout autosave_timeout_;
386 /// flag against a race condition due to multiclicks, see bug #1119
390 TocModels toc_models_;
393 QFutureWatcher<docstring> autosave_watcher_;
394 QFutureWatcher<Buffer::ExportStatus> processing_thread_watcher_;
396 string last_export_format;
397 string processing_format;
399 static QSet<Buffer const *> busyBuffers;
400 static Buffer::ExportStatus previewAndDestroy(Buffer const * orig, Buffer * buffer, string const & format);
401 static Buffer::ExportStatus exportAndDestroy(Buffer const * orig, Buffer * buffer, string const & format);
402 static Buffer::ExportStatus compileAndDestroy(Buffer const * orig, Buffer * buffer, string const & format);
403 static docstring autosaveAndDestroy(Buffer const * orig, Buffer * buffer);
406 static Buffer::ExportStatus runAndDestroy(const T& func, Buffer const * orig, Buffer * buffer, string const & format);
408 // TODO syncFunc/previewFunc: use bind
409 bool asyncBufferProcessing(string const & argument,
410 Buffer const * used_buffer,
411 docstring const & msg,
412 Buffer::ExportStatus (*asyncFunc)(Buffer const *, Buffer *, string const &),
413 Buffer::ExportStatus (Buffer::*syncFunc)(string const &, bool) const,
414 Buffer::ExportStatus (Buffer::*previewFunc)(string const &) const);
416 QVector<GuiWorkArea*> guiWorkAreas();
419 QSet<Buffer const *> GuiView::GuiViewPrivate::busyBuffers;
422 GuiView::GuiView(int id)
423 : d(*new GuiViewPrivate(this)), id_(id), closing_(false), busy_(0)
425 // GuiToolbars *must* be initialised before the menu bar.
426 normalSizedIcons(); // at least on Mac the default is 32 otherwise, which is huge
429 // set ourself as the current view. This is needed for the menu bar
430 // filling, at least for the static special menu item on Mac. Otherwise
431 // they are greyed out.
432 guiApp->setCurrentView(this);
434 // Fill up the menu bar.
435 guiApp->menus().fillMenuBar(menuBar(), this, true);
437 setCentralWidget(d.stack_widget_);
439 // Start autosave timer
440 if (lyxrc.autosave) {
441 d.autosave_timeout_.timeout.connect(bind(&GuiView::autoSave, this));
442 d.autosave_timeout_.setTimeout(lyxrc.autosave * 1000);
443 d.autosave_timeout_.start();
445 connect(&d.statusbar_timer_, SIGNAL(timeout()),
446 this, SLOT(clearMessage()));
448 // We don't want to keep the window in memory if it is closed.
449 setAttribute(Qt::WA_DeleteOnClose, true);
451 #if (!defined(Q_WS_WIN) && !defined(Q_WS_MACX))
452 // QIcon::fromTheme was introduced in Qt 4.6
453 #if (QT_VERSION >= 0x040600)
454 // assign an icon to main form. We do not do it under Qt/Win or Qt/Mac,
455 // since the icon is provided in the application bundle. We use a themed
456 // version when available and use the bundled one as fallback.
457 setWindowIcon(QIcon::fromTheme("lyx", getPixmap("images/", "lyx", "png")));
459 setWindowIcon(getPixmap("images/", "lyx", "png"));
463 resetWindowTitleAndIconText();
465 // use tabbed dock area for multiple docks
466 // (such as "source" and "messages")
467 setDockOptions(QMainWindow::ForceTabbedDocks);
470 setAcceptDrops(true);
472 // add busy indicator to statusbar
473 QLabel * busylabel = new QLabel(statusBar());
474 statusBar()->addPermanentWidget(busylabel);
475 QString fn = toqstr(lyx::libFileSearch("images", "busy.gif").absFileName());
476 QMovie * busyanim = new QMovie(fn, QByteArray(), busylabel);
477 busylabel->setMovie(busyanim);
481 connect(&d.processing_thread_watcher_, SIGNAL(started()),
482 busylabel, SLOT(show()));
483 connect(&d.processing_thread_watcher_, SIGNAL(finished()),
484 busylabel, SLOT(hide()));
486 statusBar()->setSizeGripEnabled(true);
489 connect(&d.autosave_watcher_, SIGNAL(finished()), this,
490 SLOT(autoSaveThreadFinished()));
492 connect(&d.processing_thread_watcher_, SIGNAL(started()), this,
493 SLOT(processingThreadStarted()));
494 connect(&d.processing_thread_watcher_, SIGNAL(finished()), this,
495 SLOT(processingThreadFinished()));
497 connect(this, SIGNAL(triggerShowDialog(QString const &, QString const &, Inset *)),
498 SLOT(doShowDialog(QString const &, QString const &, Inset *)));
500 // Forbid too small unresizable window because it can happen
501 // with some window manager under X11.
502 setMinimumSize(300, 200);
504 if (lyxrc.allow_geometry_session) {
505 // Now take care of session management.
510 // no session handling, default to a sane size.
511 setGeometry(50, 50, 690, 510);
514 // clear session data if any.
516 settings.remove("views");
526 QVector<GuiWorkArea*> GuiView::GuiViewPrivate::guiWorkAreas()
528 QVector<GuiWorkArea*> areas;
529 for (int i = 0; i < tabWorkAreaCount(); i++) {
530 TabWorkArea* ta = tabWorkArea(i);
531 for (int u = 0; u < ta->count(); u++) {
532 areas << ta->workArea(u);
538 static void handleExportStatus(GuiView * view, Buffer::ExportStatus status,
539 string const & format)
541 docstring const fmt = formats.prettyName(format);
544 case Buffer::ExportSuccess:
545 msg = bformat(_("Successful export to format: %1$s"), fmt);
547 case Buffer::ExportCancel:
548 msg = _("Document export cancelled.");
550 case Buffer::ExportError:
551 case Buffer::ExportNoPathToFormat:
552 case Buffer::ExportTexPathHasSpaces:
553 case Buffer::ExportConverterError:
554 msg = bformat(_("Error while exporting format: %1$s"), fmt);
556 case Buffer::PreviewSuccess:
557 msg = bformat(_("Successful preview of format: %1$s"), fmt);
559 case Buffer::PreviewError:
560 msg = bformat(_("Error while previewing format: %1$s"), fmt);
567 void GuiView::processingThreadStarted()
572 void GuiView::processingThreadFinished()
574 QFutureWatcher<Buffer::ExportStatus> const * watcher =
575 static_cast<QFutureWatcher<Buffer::ExportStatus> const *>(sender());
577 Buffer::ExportStatus const status = watcher->result();
578 handleExportStatus(this, status, d.processing_format);
581 BufferView const * const bv = currentBufferView();
582 if (bv && !bv->buffer().errorList("Export").empty()) {
586 errors(d.last_export_format);
590 void GuiView::autoSaveThreadFinished()
592 QFutureWatcher<docstring> const * watcher =
593 static_cast<QFutureWatcher<docstring> const *>(sender());
594 message(watcher->result());
599 void GuiView::saveLayout() const
602 settings.beginGroup("views");
603 settings.beginGroup(QString::number(id_));
605 settings.setValue("pos", pos());
606 settings.setValue("size", size());
608 settings.setValue("geometry", saveGeometry());
610 settings.setValue("layout", saveState(0));
611 settings.setValue("icon_size", iconSize());
615 void GuiView::saveUISettings() const
617 // Save the toolbar private states
618 ToolbarMap::iterator end = d.toolbars_.end();
619 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
620 it->second->saveSession();
621 // Now take care of all other dialogs
622 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
623 for (; it!= d.dialogs_.end(); ++it)
624 it->second->saveSession();
628 bool GuiView::restoreLayout()
631 settings.beginGroup("views");
632 settings.beginGroup(QString::number(id_));
633 QString const icon_key = "icon_size";
634 if (!settings.contains(icon_key))
637 //code below is skipped when when ~/.config/LyX is (re)created
638 QSize icon_size = settings.value(icon_key).toSize();
639 // Check whether session size changed.
640 if (icon_size.width() != int(d.smallIconSize) &&
641 icon_size.width() != int(d.normalIconSize) &&
642 icon_size.width() != int(d.bigIconSize)) {
643 icon_size.setWidth(d.normalIconSize);
644 icon_size.setHeight(d.normalIconSize);
646 setIconSize(icon_size);
649 QPoint pos = settings.value("pos", QPoint(50, 50)).toPoint();
650 QSize size = settings.value("size", QSize(690, 510)).toSize();
654 // Work-around for bug #6034: the window ends up in an undetermined
655 // state when trying to restore a maximized window when it is
656 // already maximized.
657 if (!(windowState() & Qt::WindowMaximized))
658 if (!restoreGeometry(settings.value("geometry").toByteArray()))
659 setGeometry(50, 50, 690, 510);
661 // Make sure layout is correctly oriented.
662 setLayoutDirection(qApp->layoutDirection());
664 // Allow the toc and view-source dock widget to be restored if needed.
666 if ((dialog = findOrBuild("toc", true)))
667 // see bug 5082. At least setup title and enabled state.
668 // Visibility will be adjusted by restoreState below.
669 dialog->prepareView();
670 if ((dialog = findOrBuild("view-source", true)))
671 dialog->prepareView();
672 if ((dialog = findOrBuild("progress", true)))
673 dialog->prepareView();
675 if (!restoreState(settings.value("layout").toByteArray(), 0))
678 // init the toolbars that have not been restored
679 Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
680 Toolbars::Infos::iterator end = guiApp->toolbars().end();
681 for (; cit != end; ++cit) {
682 GuiToolbar * tb = toolbar(cit->name);
683 if (tb && !tb->isRestored())
684 initToolbar(cit->name);
692 GuiToolbar * GuiView::toolbar(string const & name)
694 ToolbarMap::iterator it = d.toolbars_.find(name);
695 if (it != d.toolbars_.end())
698 LYXERR(Debug::GUI, "Toolbar::display: no toolbar named " << name);
703 void GuiView::constructToolbars()
705 ToolbarMap::iterator it = d.toolbars_.begin();
706 for (; it != d.toolbars_.end(); ++it)
710 // I don't like doing this here, but the standard toolbar
711 // destroys this object when it's destroyed itself (vfr)
712 d.layout_ = new LayoutBox(*this);
713 d.stack_widget_->addWidget(d.layout_);
714 d.layout_->move(0,0);
716 // extracts the toolbars from the backend
717 Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
718 Toolbars::Infos::iterator end = guiApp->toolbars().end();
719 for (; cit != end; ++cit)
720 d.toolbars_[cit->name] = new GuiToolbar(*cit, *this);
724 void GuiView::initToolbars()
726 // extracts the toolbars from the backend
727 Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
728 Toolbars::Infos::iterator end = guiApp->toolbars().end();
729 for (; cit != end; ++cit)
730 initToolbar(cit->name);
734 void GuiView::initToolbar(string const & name)
736 GuiToolbar * tb = toolbar(name);
739 int const visibility = guiApp->toolbars().defaultVisibility(name);
740 bool newline = !(visibility & Toolbars::SAMEROW);
741 tb->setVisible(false);
742 tb->setVisibility(visibility);
744 if (visibility & Toolbars::TOP) {
746 addToolBarBreak(Qt::TopToolBarArea);
747 addToolBar(Qt::TopToolBarArea, tb);
750 if (visibility & Toolbars::BOTTOM) {
752 addToolBarBreak(Qt::BottomToolBarArea);
753 addToolBar(Qt::BottomToolBarArea, tb);
756 if (visibility & Toolbars::LEFT) {
758 addToolBarBreak(Qt::LeftToolBarArea);
759 addToolBar(Qt::LeftToolBarArea, tb);
762 if (visibility & Toolbars::RIGHT) {
764 addToolBarBreak(Qt::RightToolBarArea);
765 addToolBar(Qt::RightToolBarArea, tb);
768 if (visibility & Toolbars::ON)
769 tb->setVisible(true);
773 TocModels & GuiView::tocModels()
775 return d.toc_models_;
779 void GuiView::setFocus()
781 LYXERR(Debug::DEBUG, "GuiView::setFocus()" << this);
782 QMainWindow::setFocus();
786 void GuiView::focusInEvent(QFocusEvent * e)
788 LYXERR(Debug::DEBUG, "GuiView::focusInEvent()" << this);
789 QMainWindow::focusInEvent(e);
790 // Make sure guiApp points to the correct view.
791 guiApp->setCurrentView(this);
792 if (currentWorkArea())
793 currentWorkArea()->setFocus();
794 else if (currentMainWorkArea())
795 currentMainWorkArea()->setFocus();
797 d.bg_widget_->setFocus();
801 QMenu * GuiView::createPopupMenu()
803 return d.toolBarPopup(this);
807 void GuiView::showEvent(QShowEvent * e)
809 LYXERR(Debug::GUI, "Passed Geometry "
810 << size().height() << "x" << size().width()
811 << "+" << pos().x() << "+" << pos().y());
813 if (d.splitter_->count() == 0)
814 // No work area, switch to the background widget.
818 QMainWindow::showEvent(e);
822 bool GuiView::closeScheduled()
829 /** Destroy only all tabbed WorkAreas. Destruction of other WorkAreas
830 ** is responsibility of the container (e.g., dialog)
832 void GuiView::closeEvent(QCloseEvent * close_event)
834 LYXERR(Debug::DEBUG, "GuiView::closeEvent()");
836 if (!GuiViewPrivate::busyBuffers.isEmpty()) {
837 Alert::warning(_("Exit LyX"),
838 _("LyX could not be closed because documents are being processed by LyX."));
839 close_event->setAccepted(false);
843 // If the user pressed the x (so we didn't call closeView
844 // programmatically), we want to clear all existing entries.
846 theSession().lastOpened().clear();
851 // it can happen that this event arrives without selecting the view,
852 // e.g. when clicking the close button on a background window.
854 if (!closeWorkAreaAll()) {
856 close_event->ignore();
860 // Make sure that nothing will use this to be closed View.
861 guiApp->unregisterView(this);
863 if (isFullScreen()) {
864 // Switch off fullscreen before closing.
869 // Make sure the timer time out will not trigger a statusbar update.
870 d.statusbar_timer_.stop();
872 // Saving fullscreen requires additional tweaks in the toolbar code.
873 // It wouldn't also work under linux natively.
874 if (lyxrc.allow_geometry_session) {
879 close_event->accept();
883 void GuiView::dragEnterEvent(QDragEnterEvent * event)
885 if (event->mimeData()->hasUrls())
887 /// \todo Ask lyx-devel is this is enough:
888 /// if (event->mimeData()->hasFormat("text/plain"))
889 /// event->acceptProposedAction();
893 void GuiView::dropEvent(QDropEvent * event)
895 QList<QUrl> files = event->mimeData()->urls();
899 LYXERR(Debug::GUI, "GuiView::dropEvent: got URLs!");
900 for (int i = 0; i != files.size(); ++i) {
901 string const file = os::internal_path(fromqstr(
902 files.at(i).toLocalFile()));
906 string const ext = support::getExtension(file);
907 vector<const Format *> found_formats;
909 // Find all formats that have the correct extension.
910 vector<const Format *> const & import_formats
911 = theConverters().importableFormats();
912 vector<const Format *>::const_iterator it = import_formats.begin();
913 for (; it != import_formats.end(); ++it)
914 if ((*it)->hasExtension(ext))
915 found_formats.push_back(*it);
918 if (found_formats.size() >= 1) {
919 if (found_formats.size() > 1) {
920 //FIXME: show a dialog to choose the correct importable format
922 "Multiple importable formats found, selecting first");
924 string const arg = found_formats[0]->name() + " " + file;
925 cmd = FuncRequest(LFUN_BUFFER_IMPORT, arg);
928 //FIXME: do we have to explicitly check whether it's a lyx file?
930 "No formats found, trying to open it as a lyx file");
931 cmd = FuncRequest(LFUN_FILE_OPEN, file);
933 // add the functions to the queue
934 guiApp->addToFuncRequestQueue(cmd);
937 // now process the collected functions. We perform the events
938 // asynchronously. This prevents potential problems in case the
939 // BufferView is closed within an event.
940 guiApp->processFuncRequestQueueAsync();
944 void GuiView::message(docstring const & str)
946 if (ForkedProcess::iAmAChild())
949 // call is moved to GUI-thread by GuiProgress
950 d.progress_->appendMessage(toqstr(str));
954 void GuiView::clearMessageText()
956 message(docstring());
960 void GuiView::updateStatusBarMessage(QString const & str)
962 statusBar()->showMessage(str);
963 d.statusbar_timer_.stop();
964 d.statusbar_timer_.start(3000);
968 void GuiView::smallSizedIcons()
970 setIconSize(QSize(d.smallIconSize, d.smallIconSize));
974 void GuiView::normalSizedIcons()
976 setIconSize(QSize(d.normalIconSize, d.normalIconSize));
980 void GuiView::bigSizedIcons()
982 setIconSize(QSize(d.bigIconSize, d.bigIconSize));
986 void GuiView::clearMessage()
988 // FIXME: This code was introduced in r19643 to fix bug #4123. However,
989 // the hasFocus function mostly returns false, even if the focus is on
990 // a workarea in this view.
994 d.statusbar_timer_.stop();
998 void GuiView::updateWindowTitle(GuiWorkArea * wa)
1000 if (wa != d.current_work_area_
1001 || wa->bufferView().buffer().isInternal())
1003 setWindowTitle(qt_("LyX: ") + wa->windowTitle());
1004 setWindowIconText(wa->windowIconText());
1005 #if (QT_VERSION >= 0x040400)
1006 // Sets the path for the window: this is used by OSX to
1007 // allow a context click on the title bar showing a menu
1008 // with the path up to the file
1009 setWindowFilePath(toqstr(wa->bufferView().buffer().absFileName()));
1014 void GuiView::on_currentWorkAreaChanged(GuiWorkArea * wa)
1016 if (d.current_work_area_)
1017 QObject::disconnect(d.current_work_area_, SIGNAL(busy(bool)),
1018 this, SLOT(setBusy(bool)));
1020 disconnectBufferView();
1021 connectBufferView(wa->bufferView());
1022 connectBuffer(wa->bufferView().buffer());
1023 d.current_work_area_ = wa;
1024 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
1025 this, SLOT(updateWindowTitle(GuiWorkArea *)));
1026 QObject::connect(wa, SIGNAL(busy(bool)), this, SLOT(setBusy(bool)));
1027 updateWindowTitle(wa);
1031 // The document settings needs to be reinitialised.
1032 updateDialog("document", "");
1034 // Buffer-dependent dialogs must be updated. This is done here because
1035 // some dialogs require buffer()->text.
1040 void GuiView::on_lastWorkAreaRemoved()
1043 // We already are in a close event. Nothing more to do.
1046 if (d.splitter_->count() > 1)
1047 // We have a splitter so don't close anything.
1050 // Reset and updates the dialogs.
1051 d.toc_models_.reset(0);
1052 updateDialog("document", "");
1055 resetWindowTitleAndIconText();
1058 if (lyxrc.open_buffers_in_tabs)
1059 // Nothing more to do, the window should stay open.
1062 if (guiApp->viewIds().size() > 1) {
1068 // On Mac we also close the last window because the application stay
1069 // resident in memory. On other platforms we don't close the last
1070 // window because this would quit the application.
1076 void GuiView::updateStatusBar()
1078 // let the user see the explicit message
1079 if (d.statusbar_timer_.isActive())
1086 void GuiView::showMessage()
1090 QString msg = toqstr(theGuiApp()->viewStatusMessage());
1091 if (msg.isEmpty()) {
1092 BufferView const * bv = currentBufferView();
1094 msg = toqstr(bv->cursor().currentState());
1096 msg = qt_("Welcome to LyX!");
1098 statusBar()->showMessage(msg);
1102 bool GuiView::event(QEvent * e)
1106 // Useful debug code:
1107 //case QEvent::ActivationChange:
1108 //case QEvent::WindowDeactivate:
1109 //case QEvent::Paint:
1110 //case QEvent::Enter:
1111 //case QEvent::Leave:
1112 //case QEvent::HoverEnter:
1113 //case QEvent::HoverLeave:
1114 //case QEvent::HoverMove:
1115 //case QEvent::StatusTip:
1116 //case QEvent::DragEnter:
1117 //case QEvent::DragLeave:
1118 //case QEvent::Drop:
1121 case QEvent::WindowActivate: {
1122 GuiView * old_view = guiApp->currentView();
1123 if (this == old_view) {
1125 return QMainWindow::event(e);
1127 if (old_view && old_view->currentBufferView()) {
1128 // save current selection to the selection buffer to allow
1129 // middle-button paste in this window.
1130 cap::saveSelection(old_view->currentBufferView()->cursor());
1132 guiApp->setCurrentView(this);
1133 if (d.current_work_area_) {
1134 BufferView & bv = d.current_work_area_->bufferView();
1135 connectBufferView(bv);
1136 connectBuffer(bv.buffer());
1137 // The document structure, name and dialogs might have
1138 // changed in another view.
1140 // The document settings needs to be reinitialised.
1141 updateDialog("document", "");
1144 resetWindowTitleAndIconText();
1147 return QMainWindow::event(e);
1150 case QEvent::ShortcutOverride: {
1152 if (isFullScreen() && menuBar()->isHidden()) {
1153 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
1154 // FIXME: we should also try to detect special LyX shortcut such as
1155 // Alt-P and Alt-M. Right now there is a hack in
1156 // GuiWorkArea::processKeySym() that hides again the menubar for
1158 if (ke->modifiers() & Qt::AltModifier && ke->key() != Qt::Key_Alt) {
1160 return QMainWindow::event(e);
1163 return QMainWindow::event(e);
1167 return QMainWindow::event(e);
1171 void GuiView::resetWindowTitleAndIconText()
1173 setWindowTitle(qt_("LyX"));
1174 setWindowIconText(qt_("LyX"));
1177 bool GuiView::focusNextPrevChild(bool /*next*/)
1184 bool GuiView::busy() const
1190 void GuiView::setBusy(bool busy)
1192 bool const busy_before = busy_ > 0;
1193 busy ? ++busy_ : --busy_;
1194 if ((busy_ > 0) == busy_before)
1195 // busy state didn't change
1199 QApplication::setOverrideCursor(Qt::WaitCursor);
1202 QApplication::restoreOverrideCursor();
1207 GuiWorkArea * GuiView::workArea(int index)
1209 if (TabWorkArea * twa = d.currentTabWorkArea())
1210 if (index < twa->count())
1211 return dynamic_cast<GuiWorkArea *>(twa->widget(index));
1216 GuiWorkArea * GuiView::workArea(Buffer & buffer)
1218 if (currentWorkArea()
1219 && ¤tWorkArea()->bufferView().buffer() == &buffer)
1220 return (GuiWorkArea *) currentWorkArea();
1221 if (TabWorkArea * twa = d.currentTabWorkArea())
1222 return twa->workArea(buffer);
1227 GuiWorkArea * GuiView::addWorkArea(Buffer & buffer)
1229 // Automatically create a TabWorkArea if there are none yet.
1230 TabWorkArea * tab_widget = d.splitter_->count()
1231 ? d.currentTabWorkArea() : addTabWorkArea();
1232 return tab_widget->addWorkArea(buffer, *this);
1236 TabWorkArea * GuiView::addTabWorkArea()
1238 TabWorkArea * twa = new TabWorkArea;
1239 QObject::connect(twa, SIGNAL(currentWorkAreaChanged(GuiWorkArea *)),
1240 this, SLOT(on_currentWorkAreaChanged(GuiWorkArea *)));
1241 QObject::connect(twa, SIGNAL(lastWorkAreaRemoved()),
1242 this, SLOT(on_lastWorkAreaRemoved()));
1244 d.splitter_->addWidget(twa);
1245 d.stack_widget_->setCurrentWidget(d.splitter_);
1250 GuiWorkArea const * GuiView::currentWorkArea() const
1252 return d.current_work_area_;
1256 GuiWorkArea * GuiView::currentWorkArea()
1258 return d.current_work_area_;
1262 GuiWorkArea const * GuiView::currentMainWorkArea() const
1264 if (!d.currentTabWorkArea())
1266 return d.currentTabWorkArea()->currentWorkArea();
1270 GuiWorkArea * GuiView::currentMainWorkArea()
1272 if (!d.currentTabWorkArea())
1274 return d.currentTabWorkArea()->currentWorkArea();
1278 void GuiView::setCurrentWorkArea(GuiWorkArea * wa)
1280 LYXERR(Debug::DEBUG, "Setting current wa: " << wa << endl);
1282 d.current_work_area_ = 0;
1287 // FIXME: I've no clue why this is here and why it accesses
1288 // theGuiApp()->currentView, which might be 0 (bug 6464).
1289 // See also 27525 (vfr).
1290 if (theGuiApp()->currentView() == this
1291 && theGuiApp()->currentView()->currentWorkArea() == wa)
1294 if (currentBufferView())
1295 cap::saveSelection(currentBufferView()->cursor());
1297 theGuiApp()->setCurrentView(this);
1298 d.current_work_area_ = wa;
1300 // We need to reset this now, because it will need to be
1301 // right if the tabWorkArea gets reset in the for loop. We
1302 // will change it back if we aren't in that case.
1303 GuiWorkArea * const old_cmwa = d.current_main_work_area_;
1304 d.current_main_work_area_ = wa;
1306 for (int i = 0; i != d.splitter_->count(); ++i) {
1307 if (d.tabWorkArea(i)->setCurrentWorkArea(wa)) {
1308 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea()
1309 << ", Current main wa: " << currentMainWorkArea());
1314 d.current_main_work_area_ = old_cmwa;
1316 LYXERR(Debug::DEBUG, "This is not a tabbed wa");
1317 on_currentWorkAreaChanged(wa);
1318 BufferView & bv = wa->bufferView();
1319 bv.cursor().fixIfBroken();
1321 wa->setUpdatesEnabled(true);
1322 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() << ", Current main wa: " << currentMainWorkArea());
1326 void GuiView::removeWorkArea(GuiWorkArea * wa)
1328 LASSERT(wa, return);
1329 if (wa == d.current_work_area_) {
1331 disconnectBufferView();
1332 d.current_work_area_ = 0;
1333 d.current_main_work_area_ = 0;
1336 bool found_twa = false;
1337 for (int i = 0; i != d.splitter_->count(); ++i) {
1338 TabWorkArea * twa = d.tabWorkArea(i);
1339 if (twa->removeWorkArea(wa)) {
1340 // Found in this tab group, and deleted the GuiWorkArea.
1342 if (twa->count() != 0) {
1343 if (d.current_work_area_ == 0)
1344 // This means that we are closing the current GuiWorkArea, so
1345 // switch to the next GuiWorkArea in the found TabWorkArea.
1346 setCurrentWorkArea(twa->currentWorkArea());
1348 // No more WorkAreas in this tab group, so delete it.
1355 // It is not a tabbed work area (i.e., the search work area), so it
1356 // should be deleted by other means.
1357 LASSERT(found_twa, return);
1359 if (d.current_work_area_ == 0) {
1360 if (d.splitter_->count() != 0) {
1361 TabWorkArea * twa = d.currentTabWorkArea();
1362 setCurrentWorkArea(twa->currentWorkArea());
1364 // No more work areas, switch to the background widget.
1365 setCurrentWorkArea(0);
1371 LayoutBox * GuiView::getLayoutDialog() const
1377 void GuiView::updateLayoutList()
1380 d.layout_->updateContents(false);
1384 void GuiView::updateToolbars()
1386 ToolbarMap::iterator end = d.toolbars_.end();
1387 if (d.current_work_area_) {
1389 d.current_work_area_->bufferView().cursor().inMathed()
1390 && !d.current_work_area_->bufferView().cursor().inRegexped();
1392 lyx::getStatus(FuncRequest(LFUN_LAYOUT_TABULAR)).enabled();
1394 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).enabled() &&
1395 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).onOff(true);
1396 bool const mathmacrotemplate =
1397 lyx::getStatus(FuncRequest(LFUN_IN_MATHMACROTEMPLATE)).enabled();
1399 lyx::getStatus(FuncRequest(LFUN_IN_IPA)).enabled();
1401 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1402 it->second->update(math, table, review, mathmacrotemplate, ipa);
1404 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1405 it->second->update(false, false, false, false, false);
1409 void GuiView::setBuffer(Buffer * newBuffer)
1411 LYXERR(Debug::DEBUG, "Setting buffer: " << newBuffer << endl);
1412 LASSERT(newBuffer, return);
1414 GuiWorkArea * wa = workArea(*newBuffer);
1417 newBuffer->masterBuffer()->updateBuffer();
1419 wa = addWorkArea(*newBuffer);
1420 // scroll to the position when the BufferView was last closed
1421 if (lyxrc.use_lastfilepos) {
1422 LastFilePosSection::FilePos filepos =
1423 theSession().lastFilePos().load(newBuffer->fileName());
1424 wa->bufferView().moveToPosition(filepos.pit, filepos.pos, 0, 0);
1427 //Disconnect the old buffer...there's no new one.
1430 connectBuffer(*newBuffer);
1431 connectBufferView(wa->bufferView());
1432 setCurrentWorkArea(wa);
1436 void GuiView::connectBuffer(Buffer & buf)
1438 buf.setGuiDelegate(this);
1442 void GuiView::disconnectBuffer()
1444 if (d.current_work_area_)
1445 d.current_work_area_->bufferView().buffer().setGuiDelegate(0);
1449 void GuiView::connectBufferView(BufferView & bv)
1451 bv.setGuiDelegate(this);
1455 void GuiView::disconnectBufferView()
1457 if (d.current_work_area_)
1458 d.current_work_area_->bufferView().setGuiDelegate(0);
1462 void GuiView::errors(string const & error_type, bool from_master)
1464 BufferView const * const bv = currentBufferView();
1468 #if EXPORT_in_THREAD
1469 // We are called with from_master == false by default, so we
1470 // have to figure out whether that is the case or not.
1471 ErrorList & el = bv->buffer().errorList(error_type);
1473 el = bv->buffer().masterBuffer()->errorList(error_type);
1477 ErrorList const & el = from_master ?
1478 bv->buffer().masterBuffer()->errorList(error_type) :
1479 bv->buffer().errorList(error_type);
1485 string data = error_type;
1487 data = "from_master|" + error_type;
1488 showDialog("errorlist", data);
1492 void GuiView::updateTocItem(string const & type, DocIterator const & dit)
1494 d.toc_models_.updateItem(toqstr(type), dit);
1498 void GuiView::structureChanged()
1500 d.toc_models_.reset(documentBufferView());
1501 // Navigator needs more than a simple update in this case. It needs to be
1503 updateDialog("toc", "");
1507 void GuiView::updateDialog(string const & name, string const & data)
1509 if (!isDialogVisible(name))
1512 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
1513 if (it == d.dialogs_.end())
1516 Dialog * const dialog = it->second.get();
1517 if (dialog->isVisibleView())
1518 dialog->initialiseParams(data);
1522 BufferView * GuiView::documentBufferView()
1524 return currentMainWorkArea()
1525 ? ¤tMainWorkArea()->bufferView()
1530 BufferView const * GuiView::documentBufferView() const
1532 return currentMainWorkArea()
1533 ? ¤tMainWorkArea()->bufferView()
1538 BufferView * GuiView::currentBufferView()
1540 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1544 BufferView const * GuiView::currentBufferView() const
1546 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1550 docstring GuiView::GuiViewPrivate::autosaveAndDestroy(
1551 Buffer const * orig, Buffer * clone)
1553 bool const success = clone->autoSave();
1555 busyBuffers.remove(orig);
1557 ? _("Automatic save done.")
1558 : _("Automatic save failed!");
1562 void GuiView::autoSave()
1564 LYXERR(Debug::INFO, "Running autoSave()");
1566 Buffer * buffer = documentBufferView()
1567 ? &documentBufferView()->buffer() : 0;
1569 resetAutosaveTimers();
1573 GuiViewPrivate::busyBuffers.insert(buffer);
1574 QFuture<docstring> f = QtConcurrent::run(GuiViewPrivate::autosaveAndDestroy,
1575 buffer, buffer->cloneBufferOnly());
1576 d.autosave_watcher_.setFuture(f);
1577 resetAutosaveTimers();
1581 void GuiView::resetAutosaveTimers()
1584 d.autosave_timeout_.restart();
1588 bool GuiView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1591 Buffer * buf = currentBufferView()
1592 ? ¤tBufferView()->buffer() : 0;
1593 Buffer * doc_buffer = documentBufferView()
1594 ? &(documentBufferView()->buffer()) : 0;
1596 // Check whether we need a buffer
1597 if (!lyxaction.funcHasFlag(cmd.action(), LyXAction::NoBuffer) && !buf) {
1598 // no, exit directly
1599 flag.message(from_utf8(N_("Command not allowed with"
1600 "out any document open")));
1601 flag.setEnabled(false);
1605 if (cmd.origin() == FuncRequest::TOC) {
1606 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
1607 if (!toc || !toc->getStatus(documentBufferView()->cursor(), cmd, flag))
1608 flag.setEnabled(false);
1612 switch(cmd.action()) {
1613 case LFUN_BUFFER_IMPORT:
1616 case LFUN_MASTER_BUFFER_UPDATE:
1617 case LFUN_MASTER_BUFFER_VIEW:
1619 && (doc_buffer->parent() != 0
1620 || doc_buffer->hasChildren())
1621 && !d.processing_thread_watcher_.isRunning();
1624 case LFUN_BUFFER_UPDATE:
1625 case LFUN_BUFFER_VIEW: {
1626 if (!doc_buffer || d.processing_thread_watcher_.isRunning()) {
1630 string format = to_utf8(cmd.argument());
1631 if (cmd.argument().empty())
1632 format = doc_buffer->params().getDefaultOutputFormat();
1633 enable = doc_buffer->params().isExportableFormat(format);
1637 case LFUN_BUFFER_RELOAD:
1638 enable = doc_buffer && !doc_buffer->isUnnamed()
1639 && doc_buffer->fileName().exists()
1640 && (!doc_buffer->isClean()
1641 || doc_buffer->isExternallyModified(Buffer::timestamp_method));
1644 case LFUN_BUFFER_CHILD_OPEN:
1645 enable = doc_buffer;
1648 case LFUN_BUFFER_WRITE:
1649 enable = doc_buffer && (doc_buffer->isUnnamed() || !doc_buffer->isClean());
1652 //FIXME: This LFUN should be moved to GuiApplication.
1653 case LFUN_BUFFER_WRITE_ALL: {
1654 // We enable the command only if there are some modified buffers
1655 Buffer * first = theBufferList().first();
1660 // We cannot use a for loop as the buffer list is a cycle.
1662 if (!b->isClean()) {
1666 b = theBufferList().next(b);
1667 } while (b != first);
1671 case LFUN_BUFFER_WRITE_AS:
1672 case LFUN_BUFFER_EXPORT_AS:
1673 enable = doc_buffer;
1676 case LFUN_BUFFER_CLOSE:
1677 case LFUN_VIEW_CLOSE:
1678 enable = doc_buffer;
1681 case LFUN_BUFFER_CLOSE_ALL:
1682 enable = theBufferList().last() != theBufferList().first();
1685 case LFUN_VIEW_SPLIT:
1686 if (cmd.getArg(0) == "vertical")
1687 enable = doc_buffer && (d.splitter_->count() == 1 ||
1688 d.splitter_->orientation() == Qt::Vertical);
1690 enable = doc_buffer && (d.splitter_->count() == 1 ||
1691 d.splitter_->orientation() == Qt::Horizontal);
1694 case LFUN_TAB_GROUP_CLOSE:
1695 enable = d.tabWorkAreaCount() > 1;
1698 case LFUN_TOOLBAR_TOGGLE: {
1699 string const name = cmd.getArg(0);
1700 if (GuiToolbar * t = toolbar(name))
1701 flag.setOnOff(t->isVisible());
1704 docstring const msg =
1705 bformat(_("Unknown toolbar \"%1$s\""), from_utf8(name));
1711 case LFUN_DROP_LAYOUTS_CHOICE:
1715 case LFUN_UI_TOGGLE:
1716 flag.setOnOff(isFullScreen());
1719 case LFUN_DIALOG_DISCONNECT_INSET:
1722 case LFUN_DIALOG_HIDE:
1723 // FIXME: should we check if the dialog is shown?
1726 case LFUN_DIALOG_TOGGLE:
1727 flag.setOnOff(isDialogVisible(cmd.getArg(0)));
1728 // fall through to set "enable"
1729 case LFUN_DIALOG_SHOW: {
1730 string const name = cmd.getArg(0);
1732 enable = name == "aboutlyx"
1733 || name == "file" //FIXME: should be removed.
1735 || name == "texinfo"
1736 || name == "progress"
1737 || name == "compare";
1738 else if (name == "print")
1739 enable = doc_buffer->params().isExportable("dvi")
1740 && lyxrc.print_command != "none";
1741 else if (name == "character" || name == "symbols"
1742 || name == "mathdelimiter" || name == "mathmatrix") {
1743 if (!buf || buf->isReadonly())
1746 Cursor const & cur = currentBufferView()->cursor();
1747 enable = !(cur.inTexted() && cur.paragraph().isPassThru());
1750 else if (name == "latexlog")
1751 enable = FileName(doc_buffer->logName()).isReadableFile();
1752 else if (name == "spellchecker")
1753 enable = theSpellChecker()
1754 && !doc_buffer->isReadonly()
1755 && !doc_buffer->text().empty();
1756 else if (name == "vclog")
1757 enable = doc_buffer->lyxvc().inUse();
1761 case LFUN_DIALOG_UPDATE: {
1762 string const name = cmd.getArg(0);
1764 enable = name == "prefs";
1768 case LFUN_COMMAND_EXECUTE:
1770 case LFUN_MENU_OPEN:
1771 // Nothing to check.
1774 case LFUN_COMPLETION_INLINE:
1775 if (!d.current_work_area_
1776 || !d.current_work_area_->completer().inlinePossible(
1777 currentBufferView()->cursor()))
1781 case LFUN_COMPLETION_POPUP:
1782 if (!d.current_work_area_
1783 || !d.current_work_area_->completer().popupPossible(
1784 currentBufferView()->cursor()))
1789 if (!d.current_work_area_
1790 || !d.current_work_area_->completer().inlinePossible(
1791 currentBufferView()->cursor()))
1795 case LFUN_COMPLETION_ACCEPT:
1796 if (!d.current_work_area_
1797 || (!d.current_work_area_->completer().popupVisible()
1798 && !d.current_work_area_->completer().inlineVisible()
1799 && !d.current_work_area_->completer().completionAvailable()))
1803 case LFUN_COMPLETION_CANCEL:
1804 if (!d.current_work_area_
1805 || (!d.current_work_area_->completer().popupVisible()
1806 && !d.current_work_area_->completer().inlineVisible()))
1810 case LFUN_BUFFER_ZOOM_OUT:
1811 enable = doc_buffer && lyxrc.zoom > 10;
1814 case LFUN_BUFFER_ZOOM_IN:
1815 enable = doc_buffer;
1818 case LFUN_BUFFER_NEXT:
1819 case LFUN_BUFFER_PREVIOUS:
1820 // FIXME: should we check is there is an previous or next buffer?
1822 case LFUN_BUFFER_SWITCH:
1823 // toggle on the current buffer, but do not toggle off
1824 // the other ones (is that a good idea?)
1826 && to_utf8(cmd.argument()) == doc_buffer->absFileName())
1827 flag.setOnOff(true);
1830 case LFUN_VC_REGISTER:
1831 enable = doc_buffer && !doc_buffer->lyxvc().inUse();
1833 case LFUN_VC_RENAME:
1834 enable = doc_buffer && doc_buffer->lyxvc().renameEnabled();
1837 enable = doc_buffer && doc_buffer->lyxvc().copyEnabled();
1839 case LFUN_VC_CHECK_IN:
1840 enable = doc_buffer && doc_buffer->lyxvc().checkInEnabled();
1842 case LFUN_VC_CHECK_OUT:
1843 enable = doc_buffer && doc_buffer->lyxvc().checkOutEnabled();
1845 case LFUN_VC_LOCKING_TOGGLE:
1846 enable = doc_buffer && !doc_buffer->isReadonly()
1847 && doc_buffer->lyxvc().lockingToggleEnabled();
1848 flag.setOnOff(enable && doc_buffer->lyxvc().locking());
1850 case LFUN_VC_REVERT:
1851 enable = doc_buffer && doc_buffer->lyxvc().inUse() && !doc_buffer->isReadonly();
1853 case LFUN_VC_UNDO_LAST:
1854 enable = doc_buffer && doc_buffer->lyxvc().undoLastEnabled();
1856 case LFUN_VC_REPO_UPDATE:
1857 enable = doc_buffer && doc_buffer->lyxvc().repoUpdateEnabled();
1859 case LFUN_VC_COMMAND: {
1860 if (cmd.argument().empty())
1862 if (!doc_buffer && contains(cmd.getArg(0), 'D'))
1866 case LFUN_VC_COMPARE:
1867 enable = doc_buffer && doc_buffer->lyxvc().prepareFileRevisionEnabled();
1870 case LFUN_SERVER_GOTO_FILE_ROW:
1872 case LFUN_FORWARD_SEARCH:
1873 enable = !(lyxrc.forward_search_dvi.empty() && lyxrc.forward_search_pdf.empty());
1876 case LFUN_FILE_INSERT_PLAINTEXT:
1877 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
1878 enable = documentBufferView() && documentBufferView()->cursor().inTexted();
1881 case LFUN_SPELLING_CONTINUOUSLY:
1882 flag.setOnOff(lyxrc.spellcheck_continuously);
1890 flag.setEnabled(false);
1896 static FileName selectTemplateFile()
1898 FileDialog dlg(qt_("Select template file"));
1899 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1900 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
1902 FileDialog::Result result = dlg.open(toqstr(lyxrc.template_path),
1903 QStringList(qt_("LyX Documents (*.lyx)")));
1905 if (result.first == FileDialog::Later)
1907 if (result.second.isEmpty())
1909 return FileName(fromqstr(result.second));
1913 Buffer * GuiView::loadDocument(FileName const & filename, bool tolastfiles)
1917 Buffer * newBuffer = 0;
1919 newBuffer = checkAndLoadLyXFile(filename);
1920 } catch (ExceptionMessage const & e) {
1927 message(_("Document not loaded."));
1931 setBuffer(newBuffer);
1932 newBuffer->errors("Parse");
1935 theSession().lastFiles().add(filename);
1941 void GuiView::openDocument(string const & fname)
1943 string initpath = lyxrc.document_path;
1945 if (documentBufferView()) {
1946 string const trypath = documentBufferView()->buffer().filePath();
1947 // If directory is writeable, use this as default.
1948 if (FileName(trypath).isDirWritable())
1954 if (fname.empty()) {
1955 FileDialog dlg(qt_("Select document to open"), LFUN_FILE_OPEN);
1956 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1957 dlg.setButton2(qt_("Examples|#E#e"),
1958 toqstr(addPath(package().system_support().absFileName(), "examples")));
1960 QStringList const filter(qt_("LyX Documents (*.lyx)"));
1961 FileDialog::Result result =
1962 dlg.open(toqstr(initpath), filter);
1964 if (result.first == FileDialog::Later)
1967 filename = fromqstr(result.second);
1969 // check selected filename
1970 if (filename.empty()) {
1971 message(_("Canceled."));
1977 // get absolute path of file and add ".lyx" to the filename if
1979 FileName const fullname =
1980 fileSearch(string(), filename, "lyx", support::may_not_exist);
1981 if (!fullname.empty())
1982 filename = fullname.absFileName();
1984 if (!fullname.onlyPath().isDirectory()) {
1985 Alert::warning(_("Invalid filename"),
1986 bformat(_("The directory in the given path\n%1$s\ndoes not exist."),
1987 from_utf8(fullname.absFileName())));
1991 // if the file doesn't exist and isn't already open (bug 6645),
1992 // let the user create one
1993 if (!fullname.exists() && !theBufferList().exists(fullname) &&
1994 !LyXVC::file_not_found_hook(fullname)) {
1995 // the user specifically chose this name. Believe him.
1996 Buffer * const b = newFile(filename, string(), true);
2002 docstring const disp_fn = makeDisplayPath(filename);
2003 message(bformat(_("Opening document %1$s..."), disp_fn));
2006 Buffer * buf = loadDocument(fullname);
2008 str2 = bformat(_("Document %1$s opened."), disp_fn);
2009 if (buf->lyxvc().inUse())
2010 str2 += " " + from_utf8(buf->lyxvc().versionString()) +
2011 " " + _("Version control detected.");
2013 str2 = bformat(_("Could not open document %1$s"), disp_fn);
2018 // FIXME: clean that
2019 static bool import(GuiView * lv, FileName const & filename,
2020 string const & format, ErrorList & errorList)
2022 FileName const lyxfile(support::changeExtension(filename.absFileName(), ".lyx"));
2024 string loader_format;
2025 vector<string> loaders = theConverters().loaders();
2026 if (find(loaders.begin(), loaders.end(), format) == loaders.end()) {
2027 vector<string>::const_iterator it = loaders.begin();
2028 vector<string>::const_iterator en = loaders.end();
2029 for (; it != en; ++it) {
2030 if (!theConverters().isReachable(format, *it))
2033 string const tofile =
2034 support::changeExtension(filename.absFileName(),
2035 formats.extension(*it));
2036 if (!theConverters().convert(0, filename, FileName(tofile),
2037 filename, format, *it, errorList))
2039 loader_format = *it;
2042 if (loader_format.empty()) {
2043 frontend::Alert::error(_("Couldn't import file"),
2044 bformat(_("No information for importing the format %1$s."),
2045 formats.prettyName(format)));
2049 loader_format = format;
2051 if (loader_format == "lyx") {
2052 Buffer * buf = lv->loadDocument(lyxfile);
2056 Buffer * const b = newFile(lyxfile.absFileName(), string(), true);
2060 bool as_paragraphs = loader_format == "textparagraph";
2061 string filename2 = (loader_format == format) ? filename.absFileName()
2062 : support::changeExtension(filename.absFileName(),
2063 formats.extension(loader_format));
2064 lv->currentBufferView()->insertPlaintextFile(FileName(filename2),
2066 guiApp->setCurrentView(lv);
2067 lyx::dispatch(FuncRequest(LFUN_MARK_OFF));
2074 void GuiView::importDocument(string const & argument)
2077 string filename = split(argument, format, ' ');
2079 LYXERR(Debug::INFO, format << " file: " << filename);
2081 // need user interaction
2082 if (filename.empty()) {
2083 string initpath = lyxrc.document_path;
2084 if (documentBufferView()) {
2085 string const trypath = documentBufferView()->buffer().filePath();
2086 // If directory is writeable, use this as default.
2087 if (FileName(trypath).isDirWritable())
2091 docstring const text = bformat(_("Select %1$s file to import"),
2092 formats.prettyName(format));
2094 FileDialog dlg(toqstr(text), LFUN_BUFFER_IMPORT);
2095 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2096 dlg.setButton2(qt_("Examples|#E#e"),
2097 toqstr(addPath(package().system_support().absFileName(), "examples")));
2099 docstring filter = formats.prettyName(format);
2102 filter += from_utf8(formats.extensions(format));
2105 FileDialog::Result result =
2106 dlg.open(toqstr(initpath), fileFilters(toqstr(filter)));
2108 if (result.first == FileDialog::Later)
2111 filename = fromqstr(result.second);
2113 // check selected filename
2114 if (filename.empty())
2115 message(_("Canceled."));
2118 if (filename.empty())
2121 // get absolute path of file
2122 FileName const fullname(support::makeAbsPath(filename));
2124 FileName const lyxfile(support::changeExtension(fullname.absFileName(), ".lyx"));
2126 // Check if the document already is open
2127 Buffer * buf = theBufferList().getBuffer(lyxfile);
2130 if (!closeBuffer()) {
2131 message(_("Canceled."));
2136 docstring const displaypath = makeDisplayPath(lyxfile.absFileName(), 30);
2138 // if the file exists already, and we didn't do
2139 // -i lyx thefile.lyx, warn
2140 if (lyxfile.exists() && fullname != lyxfile) {
2142 docstring text = bformat(_("The document %1$s already exists.\n\n"
2143 "Do you want to overwrite that document?"), displaypath);
2144 int const ret = Alert::prompt(_("Overwrite document?"),
2145 text, 0, 1, _("&Overwrite"), _("&Cancel"));
2148 message(_("Canceled."));
2153 message(bformat(_("Importing %1$s..."), displaypath));
2154 ErrorList errorList;
2155 if (import(this, fullname, format, errorList))
2156 message(_("imported."));
2158 message(_("file not imported!"));
2160 // FIXME (Abdel 12/08/06): Is there a need to display the error list here?
2164 void GuiView::newDocument(string const & filename, bool from_template)
2166 FileName initpath(lyxrc.document_path);
2167 if (documentBufferView()) {
2168 FileName const trypath(documentBufferView()->buffer().filePath());
2169 // If directory is writeable, use this as default.
2170 if (trypath.isDirWritable())
2174 string templatefile;
2175 if (from_template) {
2176 templatefile = selectTemplateFile().absFileName();
2177 if (templatefile.empty())
2182 if (filename.empty())
2183 b = newUnnamedFile(initpath, to_utf8(_("newfile")), templatefile);
2185 b = newFile(filename, templatefile, true);
2190 // If no new document could be created, it is unsure
2191 // whether there is a valid BufferView.
2192 if (currentBufferView())
2193 // Ensure the cursor is correctly positioned on screen.
2194 currentBufferView()->showCursor();
2198 void GuiView::insertLyXFile(docstring const & fname)
2200 BufferView * bv = documentBufferView();
2205 FileName filename(to_utf8(fname));
2206 if (filename.empty()) {
2207 // Launch a file browser
2209 string initpath = lyxrc.document_path;
2210 string const trypath = bv->buffer().filePath();
2211 // If directory is writeable, use this as default.
2212 if (FileName(trypath).isDirWritable())
2216 FileDialog dlg(qt_("Select LyX document to insert"), LFUN_FILE_INSERT);
2217 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2218 dlg.setButton2(qt_("Examples|#E#e"),
2219 toqstr(addPath(package().system_support().absFileName(),
2222 FileDialog::Result result = dlg.open(toqstr(initpath),
2223 QStringList(qt_("LyX Documents (*.lyx)")));
2225 if (result.first == FileDialog::Later)
2229 filename.set(fromqstr(result.second));
2231 // check selected filename
2232 if (filename.empty()) {
2233 // emit message signal.
2234 message(_("Canceled."));
2239 bv->insertLyXFile(filename);
2240 bv->buffer().errors("Parse");
2244 bool GuiView::renameBuffer(Buffer & b, docstring const & newname, RenameKind kind)
2246 FileName fname = b.fileName();
2247 FileName const oldname = fname;
2249 if (!newname.empty()) {
2251 fname = support::makeAbsPath(to_utf8(newname), oldname.onlyPath().absFileName());
2253 // Switch to this Buffer.
2256 // No argument? Ask user through dialog.
2258 FileDialog dlg(qt_("Choose a filename to save document as"),
2259 LFUN_BUFFER_WRITE_AS);
2260 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2261 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
2263 if (!isLyXFileName(fname.absFileName()))
2264 fname.changeExtension(".lyx");
2266 FileDialog::Result result =
2267 dlg.save(toqstr(fname.onlyPath().absFileName()),
2268 QStringList(qt_("LyX Documents (*.lyx)")),
2269 toqstr(fname.onlyFileName()));
2271 if (result.first == FileDialog::Later)
2274 fname.set(fromqstr(result.second));
2279 if (!isLyXFileName(fname.absFileName()))
2280 fname.changeExtension(".lyx");
2283 // fname is now the new Buffer location.
2285 // if there is already a Buffer open with this name, we do not want
2286 // to have another one. (the second test makes sure we're not just
2287 // trying to overwrite ourselves, which is fine.)
2288 if (theBufferList().exists(fname) && fname != oldname
2289 && theBufferList().getBuffer(fname) != &b) {
2290 docstring const text =
2291 bformat(_("The file\n%1$s\nis already open in your current session.\n"
2292 "Please close it before attempting to overwrite it.\n"
2293 "Do you want to choose a new filename?"),
2294 from_utf8(fname.absFileName()));
2295 int const ret = Alert::prompt(_("Chosen File Already Open"),
2296 text, 0, 1, _("&Rename"), _("&Cancel"));
2298 case 0: return renameBuffer(b, docstring(), kind);
2299 case 1: return false;
2304 bool const existsLocal = fname.exists();
2305 bool const existsInVC = LyXVC::fileInVC(fname);
2306 if (existsLocal || existsInVC) {
2307 docstring const file = makeDisplayPath(fname.absFileName(), 30);
2308 if (kind != LV_WRITE_AS && existsInVC) {
2309 // renaming to a name that is already in VC
2311 docstring text = bformat(_("The document %1$s "
2312 "is already registered.\n\n"
2313 "Do you want to choose a new name?"),
2315 docstring const title = (kind == LV_VC_RENAME) ?
2316 _("Rename document?") : _("Copy document?");
2317 docstring const button = (kind == LV_VC_RENAME) ?
2318 _("&Rename") : _("&Copy");
2319 int const ret = Alert::prompt(title, text, 0, 1,
2320 button, _("&Cancel"));
2322 case 0: return renameBuffer(b, docstring(), kind);
2323 case 1: return false;
2328 docstring text = bformat(_("The document %1$s "
2329 "already exists.\n\n"
2330 "Do you want to overwrite that document?"),
2332 int const ret = Alert::prompt(_("Overwrite document?"),
2333 text, 0, 2, _("&Overwrite"),
2334 _("&Rename"), _("&Cancel"));
2337 case 1: return renameBuffer(b, docstring(), kind);
2338 case 2: return false;
2344 case LV_VC_RENAME: {
2345 string msg = b.lyxvc().rename(fname);
2348 message(from_utf8(msg));
2352 string msg = b.lyxvc().copy(fname);
2355 message(from_utf8(msg));
2361 // LyXVC created the file already in case of LV_VC_RENAME or
2362 // LV_VC_COPY, but call saveBuffer() nevertheless to get
2363 // relative paths of included stuff right if we moved e.g. from
2364 // /a/b.lyx to /a/c/b.lyx.
2366 bool const saved = saveBuffer(b, fname);
2373 struct PrettyNameComparator
2375 bool operator()(Format const *first, Format const *second) const {
2376 return compare_no_case(translateIfPossible(from_ascii(first->prettyname())),
2377 translateIfPossible(from_ascii(second->prettyname()))) <= 0;
2382 bool GuiView::exportBufferAs(Buffer & b, docstring const & iformat)
2384 FileName fname = b.fileName();
2386 FileDialog dlg(qt_("Choose a filename to export the document as"));
2387 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2390 QString const anyformat = qt_("Guess from extension (*.*)");
2392 Formats::const_iterator it = formats.begin();
2393 vector<Format const *> export_formats;
2394 for (; it != formats.end(); ++it)
2395 if (it->documentFormat())
2396 export_formats.push_back(&(*it));
2397 PrettyNameComparator cmp;
2398 sort(export_formats.begin(), export_formats.end(), cmp);
2399 vector<Format const *>::const_iterator fit = export_formats.begin();
2400 map<QString, string> fmap;
2403 for (; fit != export_formats.end(); ++fit) {
2404 docstring const loc_prettyname =
2405 translateIfPossible(from_utf8((*fit)->prettyname()));
2406 QString const loc_filter = toqstr(bformat(from_ascii("%1$s (*.%2$s)"),
2408 from_ascii((*fit)->extension())));
2409 types << loc_filter;
2410 fmap[loc_filter] = (*fit)->name();
2411 if (from_ascii((*fit)->name()) == iformat) {
2412 filter = loc_filter;
2413 ext = (*fit)->extension();
2416 string ofname = fname.onlyFileName();
2418 ofname = support::changeExtension(ofname, ext);
2419 FileDialog::Result result =
2420 dlg.save(toqstr(fname.onlyPath().absFileName()),
2424 if (result.first != FileDialog::Chosen)
2428 fname.set(fromqstr(result.second));
2429 if (filter == anyformat)
2430 fmt_name = formats.getFormatFromExtension(fname.extension());
2432 fmt_name = fmap[filter];
2433 LYXERR(Debug::FILES, "filter=" << fromqstr(filter)
2434 << ", fmt_name=" << fmt_name << ", fname=" << fname.absFileName());
2436 if (fmt_name.empty() || fname.empty())
2439 // fname is now the new Buffer location.
2440 if (FileName(fname).exists()) {
2441 docstring const file = makeDisplayPath(fname.absFileName(), 30);
2442 docstring text = bformat(_("The document %1$s already "
2443 "exists.\n\nDo you want to "
2444 "overwrite that document?"),
2446 int const ret = Alert::prompt(_("Overwrite document?"),
2447 text, 0, 2, _("&Overwrite"), _("&Rename"), _("&Cancel"));
2450 case 1: return exportBufferAs(b, from_ascii(fmt_name));
2451 case 2: return false;
2455 FuncRequest cmd(LFUN_BUFFER_EXPORT, fmt_name + " " + fname.absFileName());
2458 return dr.dispatched();
2462 bool GuiView::saveBuffer(Buffer & b)
2464 return saveBuffer(b, FileName());
2468 bool GuiView::saveBuffer(Buffer & b, FileName const & fn)
2470 if (workArea(b) && workArea(b)->inDialogMode())
2473 if (fn.empty() && b.isUnnamed())
2474 return renameBuffer(b, docstring());
2476 bool const success = (fn.empty() ? b.save() : b.saveAs(fn));
2478 theSession().lastFiles().add(b.fileName());
2482 // Switch to this Buffer.
2485 // FIXME: we don't tell the user *WHY* the save failed !!
2486 docstring const file = makeDisplayPath(b.absFileName(), 30);
2487 docstring text = bformat(_("The document %1$s could not be saved.\n\n"
2488 "Do you want to rename the document and "
2489 "try again?"), file);
2490 int const ret = Alert::prompt(_("Rename and save?"),
2491 text, 0, 2, _("&Rename"), _("&Retry"), _("&Cancel"));
2494 if (!renameBuffer(b, docstring()))
2503 return saveBuffer(b, fn);
2507 bool GuiView::hideWorkArea(GuiWorkArea * wa)
2509 return closeWorkArea(wa, false);
2513 // We only want to close the buffer if it is not visible in other workareas
2514 // of the same view, nor in other views, and if this is not a child
2515 bool GuiView::closeWorkArea(GuiWorkArea * wa)
2517 Buffer & buf = wa->bufferView().buffer();
2519 bool last_wa = d.countWorkAreasOf(buf) == 1
2520 && !inOtherView(buf) && !buf.parent();
2522 bool close_buffer = last_wa;
2525 if (lyxrc.close_buffer_with_last_view == "yes")
2527 else if (lyxrc.close_buffer_with_last_view == "no")
2528 close_buffer = false;
2531 if (buf.isUnnamed())
2532 file = from_utf8(buf.fileName().onlyFileName());
2534 file = buf.fileName().displayName(30);
2535 docstring const text = bformat(
2536 _("Last view on document %1$s is being closed.\n"
2537 "Would you like to close or hide the document?\n"
2539 "Hidden documents can be displayed back through\n"
2540 "the menu: View->Hidden->...\n"
2542 "To remove this question, set your preference in:\n"
2543 " Tools->Preferences->Look&Feel->UserInterface\n"
2545 int ret = Alert::prompt(_("Close or hide document?"),
2546 text, 0, 1, _("&Close"), _("&Hide"));
2547 close_buffer = (ret == 0);
2551 return closeWorkArea(wa, close_buffer);
2555 bool GuiView::closeBuffer()
2557 GuiWorkArea * wa = currentMainWorkArea();
2558 setCurrentWorkArea(wa);
2559 Buffer & buf = wa->bufferView().buffer();
2560 return wa && closeWorkArea(wa, !buf.parent());
2564 void GuiView::writeSession() const {
2565 GuiWorkArea const * active_wa = currentMainWorkArea();
2566 for (int i = 0; i < d.splitter_->count(); ++i) {
2567 TabWorkArea * twa = d.tabWorkArea(i);
2568 for (int j = 0; j < twa->count(); ++j) {
2569 GuiWorkArea * wa = static_cast<GuiWorkArea *>(twa->widget(j));
2570 Buffer & buf = wa->bufferView().buffer();
2571 theSession().lastOpened().add(buf.fileName(), wa == active_wa);
2577 bool GuiView::closeBufferAll()
2579 // Close the workareas in all other views
2580 QList<int> const ids = guiApp->viewIds();
2581 for (int i = 0; i != ids.size(); ++i) {
2582 if (id_ != ids[i] && !guiApp->view(ids[i]).closeWorkAreaAll())
2586 // Close our own workareas
2587 if (!closeWorkAreaAll())
2590 // Now close the hidden buffers. We prevent hidden buffers from being
2591 // dirty, so we can just close them.
2592 theBufferList().closeAll();
2597 bool GuiView::closeWorkAreaAll()
2599 setCurrentWorkArea(currentMainWorkArea());
2601 // We might be in a situation that there is still a tabWorkArea, but
2602 // there are no tabs anymore. This can happen when we get here after a
2603 // TabWorkArea::lastWorkAreaRemoved() signal. Therefore we count how
2604 // many TabWorkArea's have no documents anymore.
2607 // We have to call count() each time, because it can happen that
2608 // more than one splitter will disappear in one iteration (bug 5998).
2609 for (; d.splitter_->count() > empty_twa; ) {
2610 TabWorkArea * twa = d.tabWorkArea(empty_twa);
2612 if (twa->count() == 0)
2615 setCurrentWorkArea(twa->currentWorkArea());
2616 if (!closeTabWorkArea(twa))
2624 bool GuiView::closeWorkArea(GuiWorkArea * wa, bool close_buffer)
2629 Buffer & buf = wa->bufferView().buffer();
2631 if (close_buffer && GuiViewPrivate::busyBuffers.contains(&buf)) {
2632 Alert::warning(_("Close document"),
2633 _("Document could not be closed because it is being processed by LyX."));
2638 return closeBuffer(buf);
2640 if (!inMultiTabs(wa))
2641 if (!saveBufferIfNeeded(buf, true))
2649 bool GuiView::closeBuffer(Buffer & buf)
2651 // If we are in a close_event all children will be closed in some time,
2652 // so no need to do it here. This will ensure that the children end up
2653 // in the session file in the correct order. If we close the master
2654 // buffer, we can close or release the child buffers here too.
2655 bool success = true;
2657 ListOfBuffers clist = buf.getChildren();
2658 ListOfBuffers::const_iterator it = clist.begin();
2659 ListOfBuffers::const_iterator const bend = clist.end();
2660 for (; it != bend; ++it) {
2661 // If a child is dirty, do not close
2662 // without user intervention
2663 //FIXME: should we look in other tabworkareas?
2664 Buffer * child_buf = *it;
2665 GuiWorkArea * child_wa = workArea(*child_buf);
2667 if (!closeWorkArea(child_wa, true)) {
2672 theBufferList().releaseChild(&buf, child_buf);
2676 // goto bookmark to update bookmark pit.
2677 //FIXME: we should update only the bookmarks related to this buffer!
2678 LYXERR(Debug::DEBUG, "GuiView::closeBuffer()");
2679 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
2680 guiApp->gotoBookmark(i+1, false, false);
2682 if (saveBufferIfNeeded(buf, false)) {
2683 buf.removeAutosaveFile();
2684 theBufferList().release(&buf);
2688 // open all children again to avoid a crash because of dangling
2689 // pointers (bug 6603)
2695 bool GuiView::closeTabWorkArea(TabWorkArea * twa)
2697 while (twa == d.currentTabWorkArea()) {
2698 twa->setCurrentIndex(twa->count()-1);
2700 GuiWorkArea * wa = twa->currentWorkArea();
2701 Buffer & b = wa->bufferView().buffer();
2703 // We only want to close the buffer if the same buffer is not visible
2704 // in another view, and if this is not a child and if we are closing
2705 // a view (not a tabgroup).
2706 bool const close_buffer =
2707 !inOtherView(b) && !b.parent() && closing_;
2709 if (!closeWorkArea(wa, close_buffer))
2716 bool GuiView::saveBufferIfNeeded(Buffer & buf, bool hiding)
2718 if (buf.isClean() || buf.paragraphs().empty())
2721 // Switch to this Buffer.
2726 if (buf.isUnnamed())
2727 file = from_utf8(buf.fileName().onlyFileName());
2729 file = buf.fileName().displayName(30);
2731 // Bring this window to top before asking questions.
2736 if (hiding && buf.isUnnamed()) {
2737 docstring const text = bformat(_("The document %1$s has not been "
2738 "saved yet.\n\nDo you want to save "
2739 "the document?"), file);
2740 ret = Alert::prompt(_("Save new document?"),
2741 text, 0, 1, _("&Save"), _("&Cancel"));
2745 docstring const text = bformat(_("The document %1$s has unsaved changes."
2746 "\n\nDo you want to save the document or discard the changes?"), file);
2747 ret = Alert::prompt(_("Save changed document?"),
2748 text, 0, 2, _("&Save"), _("&Discard"), _("&Cancel"));
2753 if (!saveBuffer(buf))
2757 // If we crash after this we could have no autosave file
2758 // but I guess this is really improbable (Jug).
2759 // Sometimes improbable things happen:
2760 // - see bug http://www.lyx.org/trac/ticket/6587 (ps)
2761 // buf.removeAutosaveFile();
2763 // revert all changes
2774 bool GuiView::inMultiTabs(GuiWorkArea * wa)
2776 Buffer & buf = wa->bufferView().buffer();
2778 for (int i = 0; i != d.splitter_->count(); ++i) {
2779 GuiWorkArea * wa_ = d.tabWorkArea(i)->workArea(buf);
2780 if (wa_ && wa_ != wa)
2783 return inOtherView(buf);
2787 bool GuiView::inOtherView(Buffer & buf)
2789 QList<int> const ids = guiApp->viewIds();
2791 for (int i = 0; i != ids.size(); ++i) {
2795 if (guiApp->view(ids[i]).workArea(buf))
2802 void GuiView::gotoNextOrPreviousBuffer(NextOrPrevious np)
2804 if (!documentBufferView())
2807 if (TabWorkArea * twa = d.currentTabWorkArea()) {
2808 Buffer * const curbuf = &documentBufferView()->buffer();
2809 int nwa = twa->count();
2810 for (int i = 0; i < nwa; ++i) {
2811 if (&workArea(i)->bufferView().buffer() == curbuf) {
2813 if (np == NEXTBUFFER)
2814 next_index = (i == nwa - 1 ? 0 : i + 1);
2816 next_index = (i == 0 ? nwa - 1 : i - 1);
2817 setBuffer(&workArea(next_index)->bufferView().buffer());
2825 /// make sure the document is saved
2826 static bool ensureBufferClean(Buffer * buffer)
2828 LASSERT(buffer, return false);
2829 if (buffer->isClean() && !buffer->isUnnamed())
2832 docstring const file = buffer->fileName().displayName(30);
2835 if (!buffer->isUnnamed()) {
2836 text = bformat(_("The document %1$s has unsaved "
2837 "changes.\n\nDo you want to save "
2838 "the document?"), file);
2839 title = _("Save changed document?");
2842 text = bformat(_("The document %1$s has not been "
2843 "saved yet.\n\nDo you want to save "
2844 "the document?"), file);
2845 title = _("Save new document?");
2847 int const ret = Alert::prompt(title, text, 0, 1, _("&Save"), _("&Cancel"));
2850 dispatch(FuncRequest(LFUN_BUFFER_WRITE));
2852 return buffer->isClean() && !buffer->isUnnamed();
2856 bool GuiView::reloadBuffer(Buffer & buf)
2858 Buffer::ReadStatus status = buf.reload();
2859 return status == Buffer::ReadSuccess;
2863 void GuiView::checkExternallyModifiedBuffers()
2865 BufferList::iterator bit = theBufferList().begin();
2866 BufferList::iterator const bend = theBufferList().end();
2867 for (; bit != bend; ++bit) {
2868 Buffer * buf = *bit;
2869 if (buf->fileName().exists()
2870 && buf->isExternallyModified(Buffer::checksum_method)) {
2871 docstring text = bformat(_("Document \n%1$s\n has been externally modified."
2872 " Reload now? Any local changes will be lost."),
2873 from_utf8(buf->absFileName()));
2874 int const ret = Alert::prompt(_("Reload externally changed document?"),
2875 text, 0, 1, _("&Reload"), _("&Cancel"));
2883 void GuiView::dispatchVC(FuncRequest const & cmd, DispatchResult & dr)
2885 Buffer * buffer = documentBufferView()
2886 ? &(documentBufferView()->buffer()) : 0;
2888 switch (cmd.action()) {
2889 case LFUN_VC_REGISTER:
2890 if (!buffer || !ensureBufferClean(buffer))
2892 if (!buffer->lyxvc().inUse()) {
2893 if (buffer->lyxvc().registrer()) {
2894 reloadBuffer(*buffer);
2895 dr.clearMessageUpdate();
2900 case LFUN_VC_RENAME:
2901 case LFUN_VC_COPY: {
2902 if (!buffer || !ensureBufferClean(buffer))
2904 if (buffer->lyxvc().inUse() && !buffer->isReadonly()) {
2905 if (buffer->lyxvc().isCheckInWithConfirmation()) {
2906 // Some changes are not yet committed.
2907 // We test here and not in getStatus(), since
2908 // this test is expensive.
2910 LyXVC::CommandResult ret =
2911 buffer->lyxvc().checkIn(log);
2913 if (ret == LyXVC::ErrorCommand ||
2914 ret == LyXVC::VCSuccess)
2915 reloadBuffer(*buffer);
2916 if (buffer->lyxvc().isCheckInWithConfirmation()) {
2917 frontend::Alert::error(
2918 _("Revision control error."),
2919 _("Document could not be checked in."));
2923 RenameKind const kind = (cmd.action() == LFUN_VC_RENAME) ?
2924 LV_VC_RENAME : LV_VC_COPY;
2925 renameBuffer(*buffer, cmd.argument(), kind);
2930 case LFUN_VC_CHECK_IN:
2931 if (!buffer || !ensureBufferClean(buffer))
2933 if (buffer->lyxvc().inUse() && !buffer->isReadonly()) {
2935 LyXVC::CommandResult ret = buffer->lyxvc().checkIn(log);
2937 // Only skip reloading if the checkin was cancelled or
2938 // an error occured before the real checkin VCS command
2939 // was executed, since the VCS might have changed the
2940 // file even if it could not checkin successfully.
2941 if (ret == LyXVC::ErrorCommand || ret == LyXVC::VCSuccess)
2942 reloadBuffer(*buffer);
2946 case LFUN_VC_CHECK_OUT:
2947 if (!buffer || !ensureBufferClean(buffer))
2949 if (buffer->lyxvc().inUse()) {
2950 dr.setMessage(buffer->lyxvc().checkOut());
2951 reloadBuffer(*buffer);
2955 case LFUN_VC_LOCKING_TOGGLE:
2956 LASSERT(buffer, return);
2957 if (!ensureBufferClean(buffer) || buffer->isReadonly())
2959 if (buffer->lyxvc().inUse()) {
2960 string res = buffer->lyxvc().lockingToggle();
2962 frontend::Alert::error(_("Revision control error."),
2963 _("Error when setting the locking property."));
2966 reloadBuffer(*buffer);
2971 case LFUN_VC_REVERT:
2972 LASSERT(buffer, return);
2973 if (buffer->lyxvc().revert()) {
2974 reloadBuffer(*buffer);
2975 dr.clearMessageUpdate();
2979 case LFUN_VC_UNDO_LAST:
2980 LASSERT(buffer, return);
2981 buffer->lyxvc().undoLast();
2982 reloadBuffer(*buffer);
2983 dr.clearMessageUpdate();
2986 case LFUN_VC_REPO_UPDATE:
2987 LASSERT(buffer, return);
2988 if (ensureBufferClean(buffer)) {
2989 dr.setMessage(buffer->lyxvc().repoUpdate());
2990 checkExternallyModifiedBuffers();
2994 case LFUN_VC_COMMAND: {
2995 string flag = cmd.getArg(0);
2996 if (buffer && contains(flag, 'R') && !ensureBufferClean(buffer))
2999 if (contains(flag, 'M')) {
3000 if (!Alert::askForText(message, _("LyX VC: Log Message")))
3003 string path = cmd.getArg(1);
3004 if (contains(path, "$$p") && buffer)
3005 path = subst(path, "$$p", buffer->filePath());
3006 LYXERR(Debug::LYXVC, "Directory: " << path);
3008 if (!pp.isReadableDirectory()) {
3009 lyxerr << _("Directory is not accessible.") << endl;
3012 support::PathChanger p(pp);
3014 string command = cmd.getArg(2);
3015 if (command.empty())
3018 command = subst(command, "$$i", buffer->absFileName());
3019 command = subst(command, "$$p", buffer->filePath());
3021 command = subst(command, "$$m", to_utf8(message));
3022 LYXERR(Debug::LYXVC, "Command: " << command);
3024 one.startscript(Systemcall::Wait, command);
3028 if (contains(flag, 'I'))
3029 buffer->markDirty();
3030 if (contains(flag, 'R'))
3031 reloadBuffer(*buffer);
3036 case LFUN_VC_COMPARE: {
3038 if (cmd.argument().empty()) {
3039 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "comparehistory"));
3043 string rev1 = cmd.getArg(0);
3047 if (!buffer->lyxvc().prepareFileRevision(rev1, f1))
3050 if (isStrInt(rev1) && convert<int>(rev1) <= 0) {
3051 f2 = buffer->absFileName();
3053 string rev2 = cmd.getArg(1);
3057 if (!buffer->lyxvc().prepareFileRevision(rev2, f2))
3061 LYXERR(Debug::LYXVC, "Launching comparison for fetched revisions:\n" <<
3062 f1 << "\n" << f2 << "\n" );
3063 string par = "compare run " + quoteName(f1) + " " + quoteName(f2);
3064 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, par));
3074 void GuiView::openChildDocument(string const & fname)
3076 LASSERT(documentBufferView(), return);
3077 Buffer & buffer = documentBufferView()->buffer();
3078 FileName const filename = support::makeAbsPath(fname, buffer.filePath());
3079 documentBufferView()->saveBookmark(false);
3081 if (theBufferList().exists(filename)) {
3082 child = theBufferList().getBuffer(filename);
3085 message(bformat(_("Opening child document %1$s..."),
3086 makeDisplayPath(filename.absFileName())));
3087 child = loadDocument(filename, false);
3089 // Set the parent name of the child document.
3090 // This makes insertion of citations and references in the child work,
3091 // when the target is in the parent or another child document.
3093 child->setParent(&buffer);
3097 bool GuiView::goToFileRow(string const & argument)
3101 size_t i = argument.find_last_of(' ');
3102 if (i != string::npos) {
3103 file_name = os::internal_path(trim(argument.substr(0, i)));
3104 istringstream is(argument.substr(i + 1));
3109 if (i == string::npos) {
3110 LYXERR0("Wrong argument: " << argument);
3114 string const abstmp = package().temp_dir().absFileName();
3115 string const realtmp = package().temp_dir().realPath();
3116 // We have to use os::path_prefix_is() here, instead of
3117 // simply prefixIs(), because the file name comes from
3118 // an external application and may need case adjustment.
3119 if (os::path_prefix_is(file_name, abstmp, os::CASE_ADJUSTED)
3120 || os::path_prefix_is(file_name, realtmp, os::CASE_ADJUSTED)) {
3121 // Needed by inverse dvi search. If it is a file
3122 // in tmpdir, call the apropriated function.
3123 // If tmpdir is a symlink, we may have the real
3124 // path passed back, so we correct for that.
3125 if (!prefixIs(file_name, abstmp))
3126 file_name = subst(file_name, realtmp, abstmp);
3127 buf = theBufferList().getBufferFromTmp(file_name);
3129 // Must replace extension of the file to be .lyx
3130 // and get full path
3131 FileName const s = fileSearch(string(),
3132 support::changeExtension(file_name, ".lyx"), "lyx");
3133 // Either change buffer or load the file
3134 if (theBufferList().exists(s))
3135 buf = theBufferList().getBuffer(s);
3136 else if (s.exists()) {
3137 buf = loadDocument(s);
3142 _("File does not exist: %1$s"),
3143 makeDisplayPath(file_name)));
3149 _("No buffer for file: %1$s."),
3150 makeDisplayPath(file_name))
3155 documentBufferView()->setCursorFromRow(row);
3161 Buffer::ExportStatus GuiView::GuiViewPrivate::runAndDestroy(const T& func, Buffer const * orig, Buffer * clone, string const & format)
3163 Buffer::ExportStatus const status = func(format);
3165 // the cloning operation will have produced a clone of the entire set of
3166 // documents, starting from the master. so we must delete those.
3167 Buffer * mbuf = const_cast<Buffer *>(clone->masterBuffer());
3169 busyBuffers.remove(orig);
3174 Buffer::ExportStatus GuiView::GuiViewPrivate::compileAndDestroy(Buffer const * orig, Buffer * clone, string const & format)
3176 Buffer::ExportStatus (Buffer::* mem_func)(std::string const &, bool) const = &Buffer::doExport;
3177 return runAndDestroy(lyx::bind(mem_func, clone, _1, true), orig, clone, format);
3181 Buffer::ExportStatus GuiView::GuiViewPrivate::exportAndDestroy(Buffer const * orig, Buffer * clone, string const & format)
3183 Buffer::ExportStatus (Buffer::* mem_func)(std::string const &, bool) const = &Buffer::doExport;
3184 return runAndDestroy(lyx::bind(mem_func, clone, _1, false), orig, clone, format);
3188 Buffer::ExportStatus GuiView::GuiViewPrivate::previewAndDestroy(Buffer const * orig, Buffer * clone, string const & format)
3190 Buffer::ExportStatus (Buffer::* mem_func)(std::string const &) const = &Buffer::preview;
3191 return runAndDestroy(lyx::bind(mem_func, clone, _1), orig, clone, format);
3195 bool GuiView::GuiViewPrivate::asyncBufferProcessing(
3196 string const & argument,
3197 Buffer const * used_buffer,
3198 docstring const & msg,
3199 Buffer::ExportStatus (*asyncFunc)(Buffer const *, Buffer *, string const &),
3200 Buffer::ExportStatus (Buffer::*syncFunc)(string const &, bool) const,
3201 Buffer::ExportStatus (Buffer::*previewFunc)(string const &) const)
3206 string format = argument;
3208 format = used_buffer->params().getDefaultOutputFormat();
3209 processing_format = format;
3210 #if EXPORT_in_THREAD
3212 progress_->clearMessages();
3215 GuiViewPrivate::busyBuffers.insert(used_buffer);
3216 Buffer * cloned_buffer = used_buffer->cloneFromMaster();
3217 if (!cloned_buffer) {
3218 Alert::error(_("Export Error"),
3219 _("Error cloning the Buffer."));
3222 QFuture<Buffer::ExportStatus> f = QtConcurrent::run(
3227 setPreviewFuture(f);
3228 last_export_format = used_buffer->params().bufferFormat();
3231 // We are asynchronous, so we don't know here anything about the success
3234 Buffer::ExportStatus status;
3236 // TODO check here if it breaks exporting with Qt < 4.4
3237 status = (used_buffer->*syncFunc)(format, true);
3238 } else if (previewFunc) {
3239 status = (used_buffer->*previewFunc)(format);
3242 handleExportStatus(gv_, status, format);
3244 return (status == Buffer::ExportSuccess
3245 || status == Buffer::PreviewSuccess);
3249 void GuiView::dispatchToBufferView(FuncRequest const & cmd, DispatchResult & dr)
3251 BufferView * bv = currentBufferView();
3252 LASSERT(bv, return);
3254 // Let the current BufferView dispatch its own actions.
3255 bv->dispatch(cmd, dr);
3256 if (dr.dispatched())
3259 // Try with the document BufferView dispatch if any.
3260 BufferView * doc_bv = documentBufferView();
3261 if (doc_bv && doc_bv != bv) {
3262 doc_bv->dispatch(cmd, dr);
3263 if (dr.dispatched())
3267 // Then let the current Cursor dispatch its own actions.
3268 bv->cursor().dispatch(cmd);
3270 // update completion. We do it here and not in
3271 // processKeySym to avoid another redraw just for a
3272 // changed inline completion
3273 if (cmd.origin() == FuncRequest::KEYBOARD) {
3274 if (cmd.action() == LFUN_SELF_INSERT
3275 || (cmd.action() == LFUN_ERT_INSERT && bv->cursor().inMathed()))
3276 updateCompletion(bv->cursor(), true, true);
3277 else if (cmd.action() == LFUN_CHAR_DELETE_BACKWARD)
3278 updateCompletion(bv->cursor(), false, true);
3280 updateCompletion(bv->cursor(), false, false);
3283 dr = bv->cursor().result();
3287 void GuiView::dispatch(FuncRequest const & cmd, DispatchResult & dr)
3289 BufferView * bv = currentBufferView();
3290 // By default we won't need any update.
3291 dr.screenUpdate(Update::None);
3292 // assume cmd will be dispatched
3293 dr.dispatched(true);
3295 Buffer * doc_buffer = documentBufferView()
3296 ? &(documentBufferView()->buffer()) : 0;
3298 if (cmd.origin() == FuncRequest::TOC) {
3299 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
3300 // FIXME: do we need to pass a DispatchResult object here?
3301 toc->doDispatch(bv->cursor(), cmd);
3305 string const argument = to_utf8(cmd.argument());
3307 switch(cmd.action()) {
3308 case LFUN_BUFFER_CHILD_OPEN:
3309 openChildDocument(to_utf8(cmd.argument()));
3312 case LFUN_BUFFER_IMPORT:
3313 importDocument(to_utf8(cmd.argument()));
3316 case LFUN_BUFFER_EXPORT: {
3319 FileName target_dir = doc_buffer->fileName().onlyPath();
3320 string const dest = cmd.getArg(1);
3321 if (!dest.empty() && FileName::isAbsolute(dest))
3322 target_dir = FileName(support::onlyPath(dest));
3323 // GCC only sees strfwd.h when building merged
3324 if (::lyx::operator==(cmd.argument(), "custom")) {
3325 dispatch(FuncRequest(LFUN_DIALOG_SHOW, "sendto"), dr);
3328 if (!target_dir.isDirWritable()) {
3329 exportBufferAs(*doc_buffer, cmd.argument());
3332 /* TODO/Review: Is it a problem to also export the children?
3333 See the update_unincluded flag */
3334 d.asyncBufferProcessing(argument,
3337 &GuiViewPrivate::exportAndDestroy,
3340 // TODO Inform user about success
3344 case LFUN_BUFFER_EXPORT_AS: {
3345 LASSERT(doc_buffer, break);
3346 docstring f = cmd.argument();
3348 f = from_ascii(doc_buffer->params().getDefaultOutputFormat());
3349 exportBufferAs(*doc_buffer, f);
3353 case LFUN_BUFFER_UPDATE: {
3354 d.asyncBufferProcessing(argument,
3357 &GuiViewPrivate::compileAndDestroy,
3362 case LFUN_BUFFER_VIEW: {
3363 d.asyncBufferProcessing(argument,
3365 _("Previewing ..."),
3366 &GuiViewPrivate::previewAndDestroy,
3371 case LFUN_MASTER_BUFFER_UPDATE: {
3372 d.asyncBufferProcessing(argument,
3373 (doc_buffer ? doc_buffer->masterBuffer() : 0),
3375 &GuiViewPrivate::compileAndDestroy,
3380 case LFUN_MASTER_BUFFER_VIEW: {
3381 d.asyncBufferProcessing(argument,
3382 (doc_buffer ? doc_buffer->masterBuffer() : 0),
3384 &GuiViewPrivate::previewAndDestroy,
3385 0, &Buffer::preview);
3388 case LFUN_BUFFER_SWITCH: {
3389 string const file_name = to_utf8(cmd.argument());
3390 if (!FileName::isAbsolute(file_name)) {
3392 dr.setMessage(_("Absolute filename expected."));
3396 Buffer * buffer = theBufferList().getBuffer(FileName(file_name));
3399 dr.setMessage(_("Document not loaded"));
3403 // Do we open or switch to the buffer in this view ?
3404 if (workArea(*buffer)
3405 || lyxrc.open_buffers_in_tabs || !documentBufferView()) {
3410 // Look for the buffer in other views
3411 QList<int> const ids = guiApp->viewIds();
3413 for (; i != ids.size(); ++i) {
3414 GuiView & gv = guiApp->view(ids[i]);
3415 if (gv.workArea(*buffer)) {
3416 gv.activateWindow();
3417 gv.setBuffer(buffer);
3422 // If necessary, open a new window as a last resort
3423 if (i == ids.size()) {
3424 lyx::dispatch(FuncRequest(LFUN_WINDOW_NEW));
3430 case LFUN_BUFFER_NEXT:
3431 gotoNextOrPreviousBuffer(NEXTBUFFER);
3434 case LFUN_BUFFER_PREVIOUS:
3435 gotoNextOrPreviousBuffer(PREVBUFFER);
3438 case LFUN_COMMAND_EXECUTE: {
3439 bool const show_it = cmd.argument() != "off";
3440 // FIXME: this is a hack, "minibuffer" should not be
3442 if (GuiToolbar * t = toolbar("minibuffer")) {
3443 t->setVisible(show_it);
3444 if (show_it && t->commandBuffer())
3445 t->commandBuffer()->setFocus();
3449 case LFUN_DROP_LAYOUTS_CHOICE:
3450 d.layout_->showPopup();
3453 case LFUN_MENU_OPEN:
3454 if (QMenu * menu = guiApp->menus().menu(toqstr(cmd.argument()), *this))
3455 menu->exec(QCursor::pos());
3458 case LFUN_FILE_INSERT:
3459 insertLyXFile(cmd.argument());
3462 case LFUN_FILE_INSERT_PLAINTEXT:
3463 case LFUN_FILE_INSERT_PLAINTEXT_PARA: {
3464 bool const as_paragraph = (cmd.action() == LFUN_FILE_INSERT_PLAINTEXT_PARA);
3465 string const fname = to_utf8(cmd.argument());
3466 if (!fname.empty() && !FileName::isAbsolute(fname)) {
3467 dr.setMessage(_("Absolute filename expected."));
3471 FileName filename(fname);
3472 if (fname.empty()) {
3473 FileDialog dlg(qt_("Select file to insert"), (as_paragraph ?
3474 LFUN_FILE_INSERT_PLAINTEXT_PARA : LFUN_FILE_INSERT_PLAINTEXT));
3476 FileDialog::Result result = dlg.open(toqstr(bv->buffer().filePath()),
3477 QStringList(qt_("All Files (*)")));
3479 if (result.first == FileDialog::Later || result.second.isEmpty()) {
3480 dr.setMessage(_("Canceled."));
3484 filename.set(fromqstr(result.second));
3488 FuncRequest const new_cmd(cmd, filename.absoluteFilePath());
3489 bv->dispatch(new_cmd, dr);
3494 case LFUN_BUFFER_RELOAD: {
3495 LASSERT(doc_buffer, break);
3498 if (!doc_buffer->isClean()) {
3499 docstring const file =
3500 makeDisplayPath(doc_buffer->absFileName(), 20);
3501 docstring text = bformat(_("Any changes will be lost. "
3502 "Are you sure you want to revert to the saved version "
3503 "of the document %1$s?"), file);
3504 ret = Alert::prompt(_("Revert to saved document?"),
3505 text, 1, 1, _("&Revert"), _("&Cancel"));
3509 doc_buffer->markClean();
3510 reloadBuffer(*doc_buffer);
3511 dr.forceBufferUpdate();
3516 case LFUN_BUFFER_WRITE:
3517 LASSERT(doc_buffer, break);
3518 saveBuffer(*doc_buffer);
3521 case LFUN_BUFFER_WRITE_AS:
3522 LASSERT(doc_buffer, break);
3523 renameBuffer(*doc_buffer, cmd.argument());
3526 case LFUN_BUFFER_WRITE_ALL: {
3527 Buffer * first = theBufferList().first();
3530 message(_("Saving all documents..."));
3531 // We cannot use a for loop as the buffer list cycles.
3534 if (!b->isClean()) {
3536 LYXERR(Debug::ACTION, "Saved " << b->absFileName());
3538 b = theBufferList().next(b);
3539 } while (b != first);
3540 dr.setMessage(_("All documents saved."));
3544 case LFUN_BUFFER_CLOSE:
3548 case LFUN_BUFFER_CLOSE_ALL:
3552 case LFUN_TOOLBAR_TOGGLE: {
3553 string const name = cmd.getArg(0);
3554 if (GuiToolbar * t = toolbar(name))
3559 case LFUN_DIALOG_UPDATE: {
3560 string const name = to_utf8(cmd.argument());
3561 if (name == "prefs" || name == "document")
3562 updateDialog(name, string());
3563 else if (name == "paragraph")
3564 lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
3565 else if (currentBufferView()) {
3566 Inset * inset = currentBufferView()->editedInset(name);
3567 // Can only update a dialog connected to an existing inset
3569 // FIXME: get rid of this indirection; GuiView ask the inset
3570 // if he is kind enough to update itself...
3571 FuncRequest fr(LFUN_INSET_DIALOG_UPDATE, cmd.argument());
3572 //FIXME: pass DispatchResult here?
3573 inset->dispatch(currentBufferView()->cursor(), fr);
3579 case LFUN_DIALOG_TOGGLE: {
3580 FuncCode const func_code = isDialogVisible(cmd.getArg(0))
3581 ? LFUN_DIALOG_HIDE : LFUN_DIALOG_SHOW;
3582 dispatch(FuncRequest(func_code, cmd.argument()), dr);
3586 case LFUN_DIALOG_DISCONNECT_INSET:
3587 disconnectDialog(to_utf8(cmd.argument()));
3590 case LFUN_DIALOG_HIDE: {
3591 guiApp->hideDialogs(to_utf8(cmd.argument()), 0);
3595 case LFUN_DIALOG_SHOW: {
3596 string const name = cmd.getArg(0);
3597 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
3599 if (name == "character") {
3600 data = freefont2string();
3602 showDialog("character", data);
3603 } else if (name == "latexlog") {
3604 Buffer::LogType type;
3605 string const logfile = doc_buffer->logName(&type);
3607 case Buffer::latexlog:
3610 case Buffer::buildlog:
3614 data += Lexer::quoteString(logfile);
3615 showDialog("log", data);
3616 } else if (name == "vclog") {
3617 string const data = "vc " +
3618 Lexer::quoteString(doc_buffer->lyxvc().getLogFile());
3619 showDialog("log", data);
3620 } else if (name == "symbols") {
3621 data = bv->cursor().getEncoding()->name();
3623 showDialog("symbols", data);
3625 } else if (name == "prefs" && isFullScreen()) {
3626 lfunUiToggle("fullscreen");
3627 showDialog("prefs", data);
3629 showDialog(name, data);
3634 dr.setMessage(cmd.argument());
3637 case LFUN_UI_TOGGLE: {
3638 string arg = cmd.getArg(0);
3639 if (!lfunUiToggle(arg)) {
3640 docstring const msg = "ui-toggle " + _("%1$s unknown command!");
3641 dr.setMessage(bformat(msg, from_utf8(arg)));
3643 // Make sure the keyboard focus stays in the work area.
3648 case LFUN_VIEW_SPLIT: {
3649 LASSERT(doc_buffer, break);
3650 string const orientation = cmd.getArg(0);
3651 d.splitter_->setOrientation(orientation == "vertical"
3652 ? Qt::Vertical : Qt::Horizontal);
3653 TabWorkArea * twa = addTabWorkArea();
3654 GuiWorkArea * wa = twa->addWorkArea(*doc_buffer, *this);
3655 setCurrentWorkArea(wa);
3658 case LFUN_TAB_GROUP_CLOSE:
3659 if (TabWorkArea * twa = d.currentTabWorkArea()) {
3660 closeTabWorkArea(twa);
3661 d.current_work_area_ = 0;
3662 twa = d.currentTabWorkArea();
3663 // Switch to the next GuiWorkArea in the found TabWorkArea.
3665 // Make sure the work area is up to date.
3666 setCurrentWorkArea(twa->currentWorkArea());
3668 setCurrentWorkArea(0);
3673 case LFUN_VIEW_CLOSE:
3674 if (TabWorkArea * twa = d.currentTabWorkArea()) {
3675 closeWorkArea(twa->currentWorkArea());
3676 d.current_work_area_ = 0;
3677 twa = d.currentTabWorkArea();
3678 // Switch to the next GuiWorkArea in the found TabWorkArea.
3680 // Make sure the work area is up to date.
3681 setCurrentWorkArea(twa->currentWorkArea());
3683 setCurrentWorkArea(0);
3688 case LFUN_COMPLETION_INLINE:
3689 if (d.current_work_area_)
3690 d.current_work_area_->completer().showInline();
3693 case LFUN_COMPLETION_POPUP:
3694 if (d.current_work_area_)
3695 d.current_work_area_->completer().showPopup();
3700 if (d.current_work_area_)
3701 d.current_work_area_->completer().tab();
3704 case LFUN_COMPLETION_CANCEL:
3705 if (d.current_work_area_) {
3706 if (d.current_work_area_->completer().popupVisible())
3707 d.current_work_area_->completer().hidePopup();
3709 d.current_work_area_->completer().hideInline();
3713 case LFUN_COMPLETION_ACCEPT:
3714 if (d.current_work_area_)
3715 d.current_work_area_->completer().activate();
3718 case LFUN_BUFFER_ZOOM_IN:
3719 case LFUN_BUFFER_ZOOM_OUT:
3720 if (cmd.argument().empty()) {
3721 if (cmd.action() == LFUN_BUFFER_ZOOM_IN)
3726 lyxrc.zoom += convert<int>(cmd.argument());
3728 if (lyxrc.zoom < 10)
3731 // The global QPixmapCache is used in GuiPainter to cache text
3732 // painting so we must reset it.
3733 QPixmapCache::clear();
3734 guiApp->fontLoader().update();
3735 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
3738 case LFUN_VC_REGISTER:
3739 case LFUN_VC_RENAME:
3741 case LFUN_VC_CHECK_IN:
3742 case LFUN_VC_CHECK_OUT:
3743 case LFUN_VC_REPO_UPDATE:
3744 case LFUN_VC_LOCKING_TOGGLE:
3745 case LFUN_VC_REVERT:
3746 case LFUN_VC_UNDO_LAST:
3747 case LFUN_VC_COMMAND:
3748 case LFUN_VC_COMPARE:
3749 dispatchVC(cmd, dr);
3752 case LFUN_SERVER_GOTO_FILE_ROW:
3753 goToFileRow(to_utf8(cmd.argument()));
3756 case LFUN_FORWARD_SEARCH: {
3757 Buffer const * doc_master = doc_buffer->masterBuffer();
3758 FileName const path(doc_master->temppath());
3759 string const texname = doc_master->isChild(doc_buffer)
3760 ? DocFileName(changeExtension(
3761 doc_buffer->absFileName(),
3762 "tex")).mangledFileName()
3763 : doc_buffer->latexName();
3764 string const fulltexname =
3765 support::makeAbsPath(texname, doc_master->temppath()).absFileName();
3766 string const mastername =
3767 removeExtension(doc_master->latexName());
3768 FileName const dviname(addName(path.absFileName(),
3769 addExtension(mastername, "dvi")));
3770 FileName const pdfname(addName(path.absFileName(),
3771 addExtension(mastername, "pdf")));
3772 bool const have_dvi = dviname.exists();
3773 bool const have_pdf = pdfname.exists();
3774 if (!have_dvi && !have_pdf) {
3775 dr.setMessage(_("Please, preview the document first."));
3778 string outname = dviname.onlyFileName();
3779 string command = lyxrc.forward_search_dvi;
3780 if (!have_dvi || (have_pdf &&
3781 pdfname.lastModified() > dviname.lastModified())) {
3782 outname = pdfname.onlyFileName();
3783 command = lyxrc.forward_search_pdf;
3786 DocIterator tmpcur = bv->cursor();
3788 while (tmpcur.inMathed())
3790 int row = tmpcur.inMathed() ? 0 : doc_buffer->texrow().getRowFromIdPos(
3791 tmpcur.paragraph().id(), tmpcur.pos());
3792 LYXERR(Debug::ACTION, "Forward search: row:" << row
3793 << " id:" << tmpcur.paragraph().id());
3794 if (!row || command.empty()) {
3795 dr.setMessage(_("Couldn't proceed."));
3798 string texrow = convert<string>(row);
3800 command = subst(command, "$$n", texrow);
3801 command = subst(command, "$$f", fulltexname);
3802 command = subst(command, "$$t", texname);
3803 command = subst(command, "$$o", outname);
3805 PathChanger p(path);
3807 one.startscript(Systemcall::DontWait, command);
3811 case LFUN_SPELLING_CONTINUOUSLY:
3812 lyxrc.spellcheck_continuously = !lyxrc.spellcheck_continuously;
3813 dr.screenUpdate(Update::Force | Update::FitCursor);
3817 // The LFUN must be for one of BufferView, Buffer or Cursor;
3819 dispatchToBufferView(cmd, dr);
3823 // Part of automatic menu appearance feature.
3824 if (isFullScreen()) {
3825 if (menuBar()->isVisible() && lyxrc.full_screen_menubar)
3831 bool GuiView::lfunUiToggle(string const & ui_component)
3833 if (ui_component == "scrollbar") {
3834 // hide() is of no help
3835 if (d.current_work_area_->verticalScrollBarPolicy() ==
3836 Qt::ScrollBarAlwaysOff)
3838 d.current_work_area_->setVerticalScrollBarPolicy(
3839 Qt::ScrollBarAsNeeded);
3841 d.current_work_area_->setVerticalScrollBarPolicy(
3842 Qt::ScrollBarAlwaysOff);
3843 } else if (ui_component == "statusbar") {
3844 statusBar()->setVisible(!statusBar()->isVisible());
3845 } else if (ui_component == "menubar") {
3846 menuBar()->setVisible(!menuBar()->isVisible());
3848 if (ui_component == "frame") {
3850 getContentsMargins(&l, &t, &r, &b);
3851 //are the frames in default state?
3852 d.current_work_area_->setFrameStyle(QFrame::NoFrame);
3854 setContentsMargins(-2, -2, -2, -2);
3856 setContentsMargins(0, 0, 0, 0);
3859 if (ui_component == "fullscreen") {
3867 void GuiView::toggleFullScreen()
3869 if (isFullScreen()) {
3870 for (int i = 0; i != d.splitter_->count(); ++i)
3871 d.tabWorkArea(i)->setFullScreen(false);
3872 setContentsMargins(0, 0, 0, 0);
3873 setWindowState(windowState() ^ Qt::WindowFullScreen);
3876 statusBar()->show();
3879 hideDialogs("prefs", 0);
3880 for (int i = 0; i != d.splitter_->count(); ++i)
3881 d.tabWorkArea(i)->setFullScreen(true);
3882 setContentsMargins(-2, -2, -2, -2);
3884 setWindowState(windowState() ^ Qt::WindowFullScreen);
3885 if (lyxrc.full_screen_statusbar)
3886 statusBar()->hide();
3887 if (lyxrc.full_screen_menubar)
3889 if (lyxrc.full_screen_toolbars) {
3890 ToolbarMap::iterator end = d.toolbars_.end();
3891 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
3896 // give dialogs like the TOC a chance to adapt
3901 Buffer const * GuiView::updateInset(Inset const * inset)
3906 Buffer const * inset_buffer = &(inset->buffer());
3908 for (int i = 0; i != d.splitter_->count(); ++i) {
3909 GuiWorkArea * wa = d.tabWorkArea(i)->currentWorkArea();
3912 Buffer const * buffer = &(wa->bufferView().buffer());
3913 if (inset_buffer == buffer)
3914 wa->scheduleRedraw();
3916 return inset_buffer;
3920 void GuiView::restartCursor()
3922 /* When we move around, or type, it's nice to be able to see
3923 * the cursor immediately after the keypress.
3925 if (d.current_work_area_)
3926 d.current_work_area_->startBlinkingCursor();
3928 // Take this occasion to update the other GUI elements.
3934 void GuiView::updateCompletion(Cursor & cur, bool start, bool keep)
3936 if (d.current_work_area_)
3937 d.current_work_area_->completer().updateVisibility(cur, start, keep);
3942 // This list should be kept in sync with the list of insets in
3943 // src/insets/Inset.cpp. I.e., if a dialog goes with an inset, the
3944 // dialog should have the same name as the inset.
3945 // Changes should be also recorded in LFUN_DIALOG_SHOW doxygen
3946 // docs in LyXAction.cpp.
3948 char const * const dialognames[] = {
3950 "aboutlyx", "bibitem", "bibtex", "box", "branch", "changes", "character",
3951 "citation", "compare", "comparehistory", "document", "errorlist", "ert",
3952 "external", "file", "findreplace", "findreplaceadv", "float", "graphics",
3953 "href", "include", "index", "index_print", "info", "listings", "label", "line",
3954 "log", "mathdelimiter", "mathmatrix", "mathspace", "nomenclature",
3955 "nomencl_print", "note", "paragraph", "phantom", "prefs", "print", "ref",
3956 "sendto", "space", "spellchecker", "symbols", "tabular", "tabularcreate",
3957 "thesaurus", "texinfo", "toc", "view-source", "vspace", "wrap", "progress"};
3959 char const * const * const end_dialognames =
3960 dialognames + (sizeof(dialognames) / sizeof(char *));
3964 cmpCStr(char const * name) : name_(name) {}
3965 bool operator()(char const * other) {
3966 return strcmp(other, name_) == 0;
3973 bool isValidName(string const & name)
3975 return find_if(dialognames, end_dialognames,
3976 cmpCStr(name.c_str())) != end_dialognames;
3982 void GuiView::resetDialogs()
3984 // Make sure that no LFUN uses any GuiView.
3985 guiApp->setCurrentView(0);
3989 constructToolbars();
3990 guiApp->menus().fillMenuBar(menuBar(), this, false);
3991 d.layout_->updateContents(true);
3992 // Now update controls with current buffer.
3993 guiApp->setCurrentView(this);
3999 Dialog * GuiView::findOrBuild(string const & name, bool hide_it)
4001 if (!isValidName(name))
4004 map<string, DialogPtr>::iterator it = d.dialogs_.find(name);
4006 if (it != d.dialogs_.end()) {
4008 it->second->hideView();
4009 return it->second.get();
4012 Dialog * dialog = build(name);
4013 d.dialogs_[name].reset(dialog);
4014 if (lyxrc.allow_geometry_session)
4015 dialog->restoreSession();
4022 void GuiView::showDialog(string const & name, string const & data,
4025 triggerShowDialog(toqstr(name), toqstr(data), inset);
4029 void GuiView::doShowDialog(QString const & qname, QString const & qdata,
4035 const string name = fromqstr(qname);
4036 const string data = fromqstr(qdata);
4040 Dialog * dialog = findOrBuild(name, false);
4042 bool const visible = dialog->isVisibleView();
4043 dialog->showData(data);
4044 if (inset && currentBufferView())
4045 currentBufferView()->editInset(name, inset);
4046 // We only set the focus to the new dialog if it was not yet
4047 // visible in order not to change the existing previous behaviour
4049 // activateWindow is needed for floating dockviews
4050 dialog->asQWidget()->raise();
4051 dialog->asQWidget()->activateWindow();
4052 dialog->asQWidget()->setFocus();
4056 catch (ExceptionMessage const & ex) {
4064 bool GuiView::isDialogVisible(string const & name) const
4066 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
4067 if (it == d.dialogs_.end())
4069 return it->second.get()->isVisibleView() && !it->second.get()->isClosing();
4073 void GuiView::hideDialog(string const & name, Inset * inset)
4075 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
4076 if (it == d.dialogs_.end())
4080 if (!currentBufferView())
4082 if (inset != currentBufferView()->editedInset(name))
4086 Dialog * const dialog = it->second.get();
4087 if (dialog->isVisibleView())
4089 if (currentBufferView())
4090 currentBufferView()->editInset(name, 0);
4094 void GuiView::disconnectDialog(string const & name)
4096 if (!isValidName(name))
4098 if (currentBufferView())
4099 currentBufferView()->editInset(name, 0);
4103 void GuiView::hideAll() const
4105 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
4106 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
4108 for(; it != end; ++it)
4109 it->second->hideView();
4113 void GuiView::updateDialogs()
4115 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
4116 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
4118 for(; it != end; ++it) {
4119 Dialog * dialog = it->second.get();
4121 if (dialog->needBufferOpen() && !documentBufferView())
4122 hideDialog(fromqstr(dialog->name()), 0);
4123 else if (dialog->isVisibleView())
4124 dialog->checkStatus();
4131 Dialog * createDialog(GuiView & lv, string const & name);
4133 // will be replaced by a proper factory...
4134 Dialog * createGuiAbout(GuiView & lv);
4135 Dialog * createGuiBibtex(GuiView & lv);
4136 Dialog * createGuiChanges(GuiView & lv);
4137 Dialog * createGuiCharacter(GuiView & lv);
4138 Dialog * createGuiCitation(GuiView & lv);
4139 Dialog * createGuiCompare(GuiView & lv);
4140 Dialog * createGuiCompareHistory(GuiView & lv);
4141 Dialog * createGuiDelimiter(GuiView & lv);
4142 Dialog * createGuiDocument(GuiView & lv);
4143 Dialog * createGuiErrorList(GuiView & lv);
4144 Dialog * createGuiExternal(GuiView & lv);
4145 Dialog * createGuiGraphics(GuiView & lv);
4146 Dialog * createGuiInclude(GuiView & lv);
4147 Dialog * createGuiIndex(GuiView & lv);
4148 Dialog * createGuiListings(GuiView & lv);
4149 Dialog * createGuiLog(GuiView & lv);
4150 Dialog * createGuiMathMatrix(GuiView & lv);
4151 Dialog * createGuiNote(GuiView & lv);
4152 Dialog * createGuiParagraph(GuiView & lv);
4153 Dialog * createGuiPhantom(GuiView & lv);
4154 Dialog * createGuiPreferences(GuiView & lv);
4155 Dialog * createGuiPrint(GuiView & lv);
4156 Dialog * createGuiPrintindex(GuiView & lv);
4157 Dialog * createGuiRef(GuiView & lv);
4158 Dialog * createGuiSearch(GuiView & lv);
4159 Dialog * createGuiSearchAdv(GuiView & lv);
4160 Dialog * createGuiSendTo(GuiView & lv);
4161 Dialog * createGuiShowFile(GuiView & lv);
4162 Dialog * createGuiSpellchecker(GuiView & lv);
4163 Dialog * createGuiSymbols(GuiView & lv);
4164 Dialog * createGuiTabularCreate(GuiView & lv);
4165 Dialog * createGuiTexInfo(GuiView & lv);
4166 Dialog * createGuiToc(GuiView & lv);
4167 Dialog * createGuiThesaurus(GuiView & lv);
4168 Dialog * createGuiViewSource(GuiView & lv);
4169 Dialog * createGuiWrap(GuiView & lv);
4170 Dialog * createGuiProgressView(GuiView & lv);
4174 Dialog * GuiView::build(string const & name)
4176 LASSERT(isValidName(name), return 0);
4178 Dialog * dialog = createDialog(*this, name);
4182 if (name == "aboutlyx")
4183 return createGuiAbout(*this);
4184 if (name == "bibtex")
4185 return createGuiBibtex(*this);
4186 if (name == "changes")
4187 return createGuiChanges(*this);
4188 if (name == "character")
4189 return createGuiCharacter(*this);
4190 if (name == "citation")
4191 return createGuiCitation(*this);
4192 if (name == "compare")
4193 return createGuiCompare(*this);
4194 if (name == "comparehistory")
4195 return createGuiCompareHistory(*this);
4196 if (name == "document")
4197 return createGuiDocument(*this);
4198 if (name == "errorlist")
4199 return createGuiErrorList(*this);
4200 if (name == "external")
4201 return createGuiExternal(*this);
4203 return createGuiShowFile(*this);
4204 if (name == "findreplace")
4205 return createGuiSearch(*this);
4206 if (name == "findreplaceadv")
4207 return createGuiSearchAdv(*this);
4208 if (name == "graphics")
4209 return createGuiGraphics(*this);
4210 if (name == "include")
4211 return createGuiInclude(*this);
4212 if (name == "index")
4213 return createGuiIndex(*this);
4214 if (name == "index_print")
4215 return createGuiPrintindex(*this);
4216 if (name == "listings")
4217 return createGuiListings(*this);
4219 return createGuiLog(*this);
4220 if (name == "mathdelimiter")
4221 return createGuiDelimiter(*this);
4222 if (name == "mathmatrix")
4223 return createGuiMathMatrix(*this);
4225 return createGuiNote(*this);
4226 if (name == "paragraph")
4227 return createGuiParagraph(*this);
4228 if (name == "phantom")
4229 return createGuiPhantom(*this);
4230 if (name == "prefs")
4231 return createGuiPreferences(*this);
4232 if (name == "print")
4233 return createGuiPrint(*this);
4235 return createGuiRef(*this);
4236 if (name == "sendto")
4237 return createGuiSendTo(*this);
4238 if (name == "spellchecker")
4239 return createGuiSpellchecker(*this);
4240 if (name == "symbols")
4241 return createGuiSymbols(*this);
4242 if (name == "tabularcreate")
4243 return createGuiTabularCreate(*this);
4244 if (name == "texinfo")
4245 return createGuiTexInfo(*this);
4246 if (name == "thesaurus")
4247 return createGuiThesaurus(*this);
4249 return createGuiToc(*this);
4250 if (name == "view-source")
4251 return createGuiViewSource(*this);
4253 return createGuiWrap(*this);
4254 if (name == "progress")
4255 return createGuiProgressView(*this);
4261 } // namespace frontend
4264 #include "moc_GuiView.cpp"