3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Lars Gullik Bjønnes
8 * \author Abdelrazak Younes
11 * Full author contact details are available in file CREDITS.
19 #include "DispatchResult.h"
20 #include "FileDialog.h"
21 #include "FontLoader.h"
22 #include "GuiApplication.h"
23 #include "GuiCommandBuffer.h"
24 #include "GuiCompleter.h"
25 #include "GuiKeySymbol.h"
27 #include "GuiToolbar.h"
28 #include "GuiWorkArea.h"
29 #include "GuiProgress.h"
30 #include "LayoutBox.h"
34 #include "qt_helpers.h"
36 #include "frontends/alert.h"
38 #include "buffer_funcs.h"
40 #include "BufferList.h"
41 #include "BufferParams.h"
42 #include "BufferView.h"
44 #include "Converter.h"
46 #include "CutAndPaste.h"
48 #include "ErrorList.h"
50 #include "FuncStatus.h"
51 #include "FuncRequest.h"
55 #include "LyXAction.h"
59 #include "Paragraph.h"
60 #include "SpellChecker.h"
62 #include "TextClass.h"
67 #include "support/convert.h"
68 #include "support/debug.h"
69 #include "support/ExceptionMessage.h"
70 #include "support/FileName.h"
71 #include "support/filetools.h"
72 #include "support/gettext.h"
73 #include "support/filetools.h"
74 #include "support/ForkedCalls.h"
75 #include "support/lassert.h"
76 #include "support/lstrings.h"
77 #include "support/os.h"
78 #include "support/Package.h"
79 #include "support/PathChanger.h"
80 #include "support/Systemcall.h"
81 #include "support/Timeout.h"
82 #include "support/ProgressInterface.h"
85 #include <QApplication>
86 #include <QCloseEvent>
88 #include <QDesktopWidget>
89 #include <QDragEnterEvent>
92 #include <QFutureWatcher>
101 #include <QPixmapCache>
103 #include <QPushButton>
104 #include <QScrollBar>
106 #include <QShowEvent>
108 #include <QStackedWidget>
109 #include <QStatusBar>
110 #include <QtConcurrentRun>
118 #define EXPORT_in_THREAD 1
121 #include "support/bind.h"
125 #ifdef HAVE_SYS_TIME_H
126 # include <sys/time.h>
134 using namespace lyx::support;
138 using support::addExtension;
139 using support::changeExtension;
140 using support::removeExtension;
146 class BackgroundWidget : public QWidget
151 LYXERR(Debug::GUI, "show banner: " << lyxrc.show_banner);
152 if (!lyxrc.show_banner)
154 /// The text to be written on top of the pixmap
155 QString const text = lyx_version ?
156 qt_("version ") + lyx_version : qt_("unknown version");
157 splash_ = getPixmap("images/", "banner", "png");
159 QPainter pain(&splash_);
160 pain.setPen(QColor(0, 0, 0));
162 // The font used to display the version info
163 font.setStyleHint(QFont::SansSerif);
164 font.setWeight(QFont::Bold);
165 font.setPointSize(int(toqstr(lyxrc.font_sizes[FONT_SIZE_LARGE]).toDouble()));
167 pain.drawText(190, 225, text);
168 setFocusPolicy(Qt::StrongFocus);
171 void paintEvent(QPaintEvent *)
173 int x = (width() - splash_.width()) / 2;
174 int y = (height() - splash_.height()) / 2;
176 pain.drawPixmap(x, y, splash_);
179 void keyPressEvent(QKeyEvent * ev)
182 setKeySymbol(&sym, ev);
184 guiApp->processKeySym(sym, q_key_state(ev->modifiers()));
196 /// Toolbar store providing access to individual toolbars by name.
197 typedef map<string, GuiToolbar *> ToolbarMap;
199 typedef shared_ptr<Dialog> DialogPtr;
204 struct GuiView::GuiViewPrivate
206 GuiViewPrivate(GuiView * gv)
207 : gv_(gv), current_work_area_(0), current_main_work_area_(0),
208 layout_(0), autosave_timeout_(5000),
211 // hardcode here the platform specific icon size
212 smallIconSize = 16; // scaling problems
213 normalIconSize = 20; // ok, default if iconsize.png is missing
214 bigIconSize = 26; // better for some math icons
216 // if it exists, use width of iconsize.png as normal size
217 QString const dir = toqstr(addPath("images", lyxrc.icon_set));
218 FileName const fn = lyx::libFileSearch(dir, "iconsize.png");
220 QImage image(toqstr(fn.absFileName()));
221 if (image.width() < int(smallIconSize))
222 normalIconSize = smallIconSize;
223 else if (image.width() > int(bigIconSize))
224 normalIconSize = bigIconSize;
226 normalIconSize = image.width();
229 splitter_ = new QSplitter;
230 bg_widget_ = new BackgroundWidget;
231 stack_widget_ = new QStackedWidget;
232 stack_widget_->addWidget(bg_widget_);
233 stack_widget_->addWidget(splitter_);
236 // TODO cleanup, remove the singleton, handle multiple Windows?
237 progress_ = ProgressInterface::instance();
238 if (!dynamic_cast<GuiProgress*>(progress_)) {
239 progress_ = new GuiProgress; // TODO who deletes it
240 ProgressInterface::setInstance(progress_);
243 dynamic_cast<GuiProgress*>(progress_),
244 SIGNAL(updateStatusBarMessage(QString const&)),
245 gv, SLOT(updateStatusBarMessage(QString const&)));
247 dynamic_cast<GuiProgress*>(progress_),
248 SIGNAL(clearMessageText()),
249 gv, SLOT(clearMessageText()));
256 delete stack_widget_;
259 QMenu * toolBarPopup(GuiView * parent)
261 // FIXME: translation
262 QMenu * menu = new QMenu(parent);
263 QActionGroup * iconSizeGroup = new QActionGroup(parent);
265 QAction * smallIcons = new QAction(iconSizeGroup);
266 smallIcons->setText(qt_("Small-sized icons"));
267 smallIcons->setCheckable(true);
268 QObject::connect(smallIcons, SIGNAL(triggered()),
269 parent, SLOT(smallSizedIcons()));
270 menu->addAction(smallIcons);
272 QAction * normalIcons = new QAction(iconSizeGroup);
273 normalIcons->setText(qt_("Normal-sized icons"));
274 normalIcons->setCheckable(true);
275 QObject::connect(normalIcons, SIGNAL(triggered()),
276 parent, SLOT(normalSizedIcons()));
277 menu->addAction(normalIcons);
279 QAction * bigIcons = new QAction(iconSizeGroup);
280 bigIcons->setText(qt_("Big-sized icons"));
281 bigIcons->setCheckable(true);
282 QObject::connect(bigIcons, SIGNAL(triggered()),
283 parent, SLOT(bigSizedIcons()));
284 menu->addAction(bigIcons);
286 unsigned int cur = parent->iconSize().width();
287 if ( cur == parent->d.smallIconSize)
288 smallIcons->setChecked(true);
289 else if (cur == parent->d.normalIconSize)
290 normalIcons->setChecked(true);
291 else if (cur == parent->d.bigIconSize)
292 bigIcons->setChecked(true);
299 stack_widget_->setCurrentWidget(bg_widget_);
300 bg_widget_->setUpdatesEnabled(true);
301 bg_widget_->setFocus();
304 int tabWorkAreaCount()
306 return splitter_->count();
309 TabWorkArea * tabWorkArea(int i)
311 return dynamic_cast<TabWorkArea *>(splitter_->widget(i));
314 TabWorkArea * currentTabWorkArea()
316 int areas = tabWorkAreaCount();
318 // The first TabWorkArea is always the first one, if any.
319 return tabWorkArea(0);
321 for (int i = 0; i != areas; ++i) {
322 TabWorkArea * twa = tabWorkArea(i);
323 if (current_main_work_area_ == twa->currentWorkArea())
327 // None has the focus so we just take the first one.
328 return tabWorkArea(0);
331 int countWorkAreasOf(Buffer & buf)
333 int areas = tabWorkAreaCount();
335 for (int i = 0; i != areas; ++i) {
336 TabWorkArea * twa = tabWorkArea(i);
337 if (twa->workArea(buf))
343 void setPreviewFuture(QFuture<Buffer::ExportStatus> const & f)
345 if (processing_thread_watcher_.isRunning()) {
346 // we prefer to cancel this preview in order to keep a snappy
350 processing_thread_watcher_.setFuture(f);
355 GuiWorkArea * current_work_area_;
356 GuiWorkArea * current_main_work_area_;
357 QSplitter * splitter_;
358 QStackedWidget * stack_widget_;
359 BackgroundWidget * bg_widget_;
361 ToolbarMap toolbars_;
362 ProgressInterface* progress_;
363 /// The main layout box.
365 * \warning Don't Delete! The layout box is actually owned by
366 * whichever toolbar contains it. All the GuiView class needs is a
367 * means of accessing it.
369 * FIXME: replace that with a proper model so that we are not limited
370 * to only one dialog.
375 map<string, DialogPtr> dialogs_;
377 unsigned int smallIconSize;
378 unsigned int normalIconSize;
379 unsigned int bigIconSize;
381 QTimer statusbar_timer_;
382 /// auto-saving of buffers
383 Timeout autosave_timeout_;
384 /// flag against a race condition due to multiclicks, see bug #1119
388 TocModels toc_models_;
391 QFutureWatcher<docstring> autosave_watcher_;
392 QFutureWatcher<Buffer::ExportStatus> processing_thread_watcher_;
394 string last_export_format;
395 string processing_format;
397 static QSet<Buffer const *> busyBuffers;
398 static Buffer::ExportStatus previewAndDestroy(Buffer const * orig, Buffer * buffer, string const & format);
399 static Buffer::ExportStatus exportAndDestroy(Buffer const * orig, Buffer * buffer, string const & format);
400 static Buffer::ExportStatus compileAndDestroy(Buffer const * orig, Buffer * buffer, string const & format);
401 static docstring autosaveAndDestroy(Buffer const * orig, Buffer * buffer);
404 static Buffer::ExportStatus runAndDestroy(const T& func, Buffer const * orig, Buffer * buffer, string const & format);
406 // TODO syncFunc/previewFunc: use bind
407 bool asyncBufferProcessing(string const & argument,
408 Buffer const * used_buffer,
409 docstring const & msg,
410 Buffer::ExportStatus (*asyncFunc)(Buffer const *, Buffer *, string const &),
411 Buffer::ExportStatus (Buffer::*syncFunc)(string const &, bool) const,
412 Buffer::ExportStatus (Buffer::*previewFunc)(string const &) const);
414 QVector<GuiWorkArea*> guiWorkAreas();
417 QSet<Buffer const *> GuiView::GuiViewPrivate::busyBuffers;
420 GuiView::GuiView(int id)
421 : d(*new GuiViewPrivate(this)), id_(id), closing_(false), busy_(0)
423 // GuiToolbars *must* be initialised before the menu bar.
424 normalSizedIcons(); // at least on Mac the default is 32 otherwise, which is huge
427 // set ourself as the current view. This is needed for the menu bar
428 // filling, at least for the static special menu item on Mac. Otherwise
429 // they are greyed out.
430 guiApp->setCurrentView(this);
432 // Fill up the menu bar.
433 guiApp->menus().fillMenuBar(menuBar(), this, true);
435 setCentralWidget(d.stack_widget_);
437 // Start autosave timer
438 if (lyxrc.autosave) {
439 d.autosave_timeout_.timeout.connect(bind(&GuiView::autoSave, this));
440 d.autosave_timeout_.setTimeout(lyxrc.autosave * 1000);
441 d.autosave_timeout_.start();
443 connect(&d.statusbar_timer_, SIGNAL(timeout()),
444 this, SLOT(clearMessage()));
446 // We don't want to keep the window in memory if it is closed.
447 setAttribute(Qt::WA_DeleteOnClose, true);
449 #if (!defined(Q_WS_WIN) && !defined(Q_WS_MACX))
450 // QIcon::fromTheme was introduced in Qt 4.6
451 #if (QT_VERSION >= 0x040600)
452 // assign an icon to main form. We do not do it under Qt/Win or Qt/Mac,
453 // since the icon is provided in the application bundle. We use a themed
454 // version when available and use the bundled one as fallback.
455 setWindowIcon(QIcon::fromTheme("lyx", getPixmap("images/", "lyx", "png")));
457 setWindowIcon(getPixmap("images/", "lyx", "png"));
461 resetWindowTitleAndIconText();
463 // use tabbed dock area for multiple docks
464 // (such as "source" and "messages")
465 setDockOptions(QMainWindow::ForceTabbedDocks);
468 setAcceptDrops(true);
470 // add busy indicator to statusbar
471 QLabel * busylabel = new QLabel(statusBar());
472 statusBar()->addPermanentWidget(busylabel);
473 QString fn = toqstr(lyx::libFileSearch("images", "busy.gif").absFileName());
474 QMovie * busyanim = new QMovie(fn, QByteArray(), busylabel);
475 busylabel->setMovie(busyanim);
479 connect(&d.processing_thread_watcher_, SIGNAL(started()),
480 busylabel, SLOT(show()));
481 connect(&d.processing_thread_watcher_, SIGNAL(finished()),
482 busylabel, SLOT(hide()));
484 statusBar()->setSizeGripEnabled(true);
487 connect(&d.autosave_watcher_, SIGNAL(finished()), this,
488 SLOT(autoSaveThreadFinished()));
490 connect(&d.processing_thread_watcher_, SIGNAL(started()), this,
491 SLOT(processingThreadStarted()));
492 connect(&d.processing_thread_watcher_, SIGNAL(finished()), this,
493 SLOT(processingThreadFinished()));
495 connect(this, SIGNAL(triggerShowDialog(QString const &, QString const &, Inset *)),
496 SLOT(doShowDialog(QString const &, QString const &, Inset *)));
498 // Forbid too small unresizable window because it can happen
499 // with some window manager under X11.
500 setMinimumSize(300, 200);
502 if (lyxrc.allow_geometry_session) {
503 // Now take care of session management.
508 // no session handling, default to a sane size.
509 setGeometry(50, 50, 690, 510);
512 // clear session data if any.
514 settings.remove("views");
524 QVector<GuiWorkArea*> GuiView::GuiViewPrivate::guiWorkAreas()
526 QVector<GuiWorkArea*> areas;
527 for (int i = 0; i < tabWorkAreaCount(); i++) {
528 TabWorkArea* ta = tabWorkArea(i);
529 for (int u = 0; u < ta->count(); u++) {
530 areas << ta->workArea(u);
536 static void handleExportStatus(GuiView * view, Buffer::ExportStatus status,
537 string const & format)
539 docstring const fmt = formats.prettyName(format);
542 case Buffer::ExportSuccess:
543 msg = bformat(_("Successful export to format: %1$s"), fmt);
545 case Buffer::ExportCancel:
546 msg = _("Document export cancelled.");
548 case Buffer::ExportError:
549 case Buffer::ExportNoPathToFormat:
550 case Buffer::ExportTexPathHasSpaces:
551 case Buffer::ExportConverterError:
552 msg = bformat(_("Error while exporting format: %1$s"), fmt);
554 case Buffer::PreviewSuccess:
555 msg = bformat(_("Successful preview of format: %1$s"), fmt);
557 case Buffer::PreviewError:
558 msg = bformat(_("Error while previewing format: %1$s"), fmt);
565 void GuiView::processingThreadStarted()
570 void GuiView::processingThreadFinished()
572 QFutureWatcher<Buffer::ExportStatus> const * watcher =
573 static_cast<QFutureWatcher<Buffer::ExportStatus> const *>(sender());
575 Buffer::ExportStatus const status = watcher->result();
576 handleExportStatus(this, status, d.processing_format);
579 BufferView const * const bv = currentBufferView();
580 if (bv && !bv->buffer().errorList("Export").empty()) {
584 errors(d.last_export_format);
588 void GuiView::autoSaveThreadFinished()
590 QFutureWatcher<docstring> const * watcher =
591 static_cast<QFutureWatcher<docstring> const *>(sender());
592 message(watcher->result());
597 void GuiView::saveLayout() const
600 settings.beginGroup("views");
601 settings.beginGroup(QString::number(id_));
603 settings.setValue("pos", pos());
604 settings.setValue("size", size());
606 settings.setValue("geometry", saveGeometry());
608 settings.setValue("layout", saveState(0));
609 settings.setValue("icon_size", iconSize());
613 void GuiView::saveUISettings() const
615 // Save the toolbar private states
616 ToolbarMap::iterator end = d.toolbars_.end();
617 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
618 it->second->saveSession();
619 // Now take care of all other dialogs
620 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
621 for (; it!= d.dialogs_.end(); ++it)
622 it->second->saveSession();
626 bool GuiView::restoreLayout()
629 settings.beginGroup("views");
630 settings.beginGroup(QString::number(id_));
631 QString const icon_key = "icon_size";
632 if (!settings.contains(icon_key))
635 //code below is skipped when when ~/.config/LyX is (re)created
636 QSize icon_size = settings.value(icon_key).toSize();
637 // Check whether session size changed.
638 if (icon_size.width() != int(d.smallIconSize) &&
639 icon_size.width() != int(d.normalIconSize) &&
640 icon_size.width() != int(d.bigIconSize)) {
641 icon_size.setWidth(d.normalIconSize);
642 icon_size.setHeight(d.normalIconSize);
644 setIconSize(icon_size);
647 QPoint pos = settings.value("pos", QPoint(50, 50)).toPoint();
648 QSize size = settings.value("size", QSize(690, 510)).toSize();
652 // Work-around for bug #6034: the window ends up in an undetermined
653 // state when trying to restore a maximized window when it is
654 // already maximized.
655 if (!(windowState() & Qt::WindowMaximized))
656 if (!restoreGeometry(settings.value("geometry").toByteArray()))
657 setGeometry(50, 50, 690, 510);
659 // Make sure layout is correctly oriented.
660 setLayoutDirection(qApp->layoutDirection());
662 // Allow the toc and view-source dock widget to be restored if needed.
664 if ((dialog = findOrBuild("toc", true)))
665 // see bug 5082. At least setup title and enabled state.
666 // Visibility will be adjusted by restoreState below.
667 dialog->prepareView();
668 if ((dialog = findOrBuild("view-source", true)))
669 dialog->prepareView();
670 if ((dialog = findOrBuild("progress", true)))
671 dialog->prepareView();
672 if ((dialog = findOrBuild("findreplaceadv", 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());
1008 void GuiView::on_currentWorkAreaChanged(GuiWorkArea * wa)
1010 if (d.current_work_area_)
1011 QObject::disconnect(d.current_work_area_, SIGNAL(busy(bool)),
1012 this, SLOT(setBusy(bool)));
1014 disconnectBufferView();
1015 connectBufferView(wa->bufferView());
1016 connectBuffer(wa->bufferView().buffer());
1017 d.current_work_area_ = wa;
1018 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
1019 this, SLOT(updateWindowTitle(GuiWorkArea *)));
1020 QObject::connect(wa, SIGNAL(busy(bool)), this, SLOT(setBusy(bool)));
1021 updateWindowTitle(wa);
1025 // The document settings needs to be reinitialised.
1026 updateDialog("document", "");
1028 // Buffer-dependent dialogs must be updated. This is done here because
1029 // some dialogs require buffer()->text.
1034 void GuiView::on_lastWorkAreaRemoved()
1037 // We already are in a close event. Nothing more to do.
1040 if (d.splitter_->count() > 1)
1041 // We have a splitter so don't close anything.
1044 // Reset and updates the dialogs.
1045 d.toc_models_.reset(0);
1046 updateDialog("document", "");
1049 resetWindowTitleAndIconText();
1052 if (lyxrc.open_buffers_in_tabs)
1053 // Nothing more to do, the window should stay open.
1056 if (guiApp->viewIds().size() > 1) {
1062 // On Mac we also close the last window because the application stay
1063 // resident in memory. On other platforms we don't close the last
1064 // window because this would quit the application.
1070 void GuiView::updateStatusBar()
1072 // let the user see the explicit message
1073 if (d.statusbar_timer_.isActive())
1080 void GuiView::showMessage()
1084 QString msg = toqstr(theGuiApp()->viewStatusMessage());
1085 if (msg.isEmpty()) {
1086 BufferView const * bv = currentBufferView();
1088 msg = toqstr(bv->cursor().currentState());
1090 msg = qt_("Welcome to LyX!");
1092 statusBar()->showMessage(msg);
1096 bool GuiView::event(QEvent * e)
1100 // Useful debug code:
1101 //case QEvent::ActivationChange:
1102 //case QEvent::WindowDeactivate:
1103 //case QEvent::Paint:
1104 //case QEvent::Enter:
1105 //case QEvent::Leave:
1106 //case QEvent::HoverEnter:
1107 //case QEvent::HoverLeave:
1108 //case QEvent::HoverMove:
1109 //case QEvent::StatusTip:
1110 //case QEvent::DragEnter:
1111 //case QEvent::DragLeave:
1112 //case QEvent::Drop:
1115 case QEvent::WindowActivate: {
1116 GuiView * old_view = guiApp->currentView();
1117 if (this == old_view) {
1119 return QMainWindow::event(e);
1121 if (old_view && old_view->currentBufferView()) {
1122 // save current selection to the selection buffer to allow
1123 // middle-button paste in this window.
1124 cap::saveSelection(old_view->currentBufferView()->cursor());
1126 guiApp->setCurrentView(this);
1127 if (d.current_work_area_) {
1128 BufferView & bv = d.current_work_area_->bufferView();
1129 connectBufferView(bv);
1130 connectBuffer(bv.buffer());
1131 // The document structure, name and dialogs might have
1132 // changed in another view.
1134 // The document settings needs to be reinitialised.
1135 updateDialog("document", "");
1138 resetWindowTitleAndIconText();
1141 return QMainWindow::event(e);
1144 case QEvent::ShortcutOverride: {
1146 if (isFullScreen() && menuBar()->isHidden()) {
1147 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
1148 // FIXME: we should also try to detect special LyX shortcut such as
1149 // Alt-P and Alt-M. Right now there is a hack in
1150 // GuiWorkArea::processKeySym() that hides again the menubar for
1152 if (ke->modifiers() & Qt::AltModifier && ke->key() != Qt::Key_Alt) {
1154 return QMainWindow::event(e);
1157 return QMainWindow::event(e);
1161 return QMainWindow::event(e);
1165 void GuiView::resetWindowTitleAndIconText()
1167 setWindowTitle(qt_("LyX"));
1168 setWindowIconText(qt_("LyX"));
1171 bool GuiView::focusNextPrevChild(bool /*next*/)
1178 bool GuiView::busy() const
1184 void GuiView::setBusy(bool busy)
1186 bool const busy_before = busy_ > 0;
1187 busy ? ++busy_ : --busy_;
1188 if ((busy_ > 0) == busy_before)
1189 // busy state didn't change
1193 QApplication::setOverrideCursor(Qt::WaitCursor);
1196 QApplication::restoreOverrideCursor();
1201 GuiWorkArea * GuiView::workArea(int index)
1203 if (TabWorkArea * twa = d.currentTabWorkArea())
1204 if (index < twa->count())
1205 return dynamic_cast<GuiWorkArea *>(twa->widget(index));
1210 GuiWorkArea * GuiView::workArea(Buffer & buffer)
1212 if (currentWorkArea()
1213 && ¤tWorkArea()->bufferView().buffer() == &buffer)
1214 return (GuiWorkArea *) currentWorkArea();
1215 if (TabWorkArea * twa = d.currentTabWorkArea())
1216 return twa->workArea(buffer);
1221 GuiWorkArea * GuiView::addWorkArea(Buffer & buffer)
1223 // Automatically create a TabWorkArea if there are none yet.
1224 TabWorkArea * tab_widget = d.splitter_->count()
1225 ? d.currentTabWorkArea() : addTabWorkArea();
1226 return tab_widget->addWorkArea(buffer, *this);
1230 TabWorkArea * GuiView::addTabWorkArea()
1232 TabWorkArea * twa = new TabWorkArea;
1233 QObject::connect(twa, SIGNAL(currentWorkAreaChanged(GuiWorkArea *)),
1234 this, SLOT(on_currentWorkAreaChanged(GuiWorkArea *)));
1235 QObject::connect(twa, SIGNAL(lastWorkAreaRemoved()),
1236 this, SLOT(on_lastWorkAreaRemoved()));
1238 d.splitter_->addWidget(twa);
1239 d.stack_widget_->setCurrentWidget(d.splitter_);
1244 GuiWorkArea const * GuiView::currentWorkArea() const
1246 return d.current_work_area_;
1250 GuiWorkArea * GuiView::currentWorkArea()
1252 return d.current_work_area_;
1256 GuiWorkArea const * GuiView::currentMainWorkArea() const
1258 if (!d.currentTabWorkArea())
1260 return d.currentTabWorkArea()->currentWorkArea();
1264 GuiWorkArea * GuiView::currentMainWorkArea()
1266 if (!d.currentTabWorkArea())
1268 return d.currentTabWorkArea()->currentWorkArea();
1272 void GuiView::setCurrentWorkArea(GuiWorkArea * wa)
1274 LYXERR(Debug::DEBUG, "Setting current wa: " << wa << endl);
1276 d.current_work_area_ = 0;
1281 // FIXME: I've no clue why this is here and why it accesses
1282 // theGuiApp()->currentView, which might be 0 (bug 6464).
1283 // See also 27525 (vfr).
1284 if (theGuiApp()->currentView() == this
1285 && theGuiApp()->currentView()->currentWorkArea() == wa)
1288 if (currentBufferView())
1289 cap::saveSelection(currentBufferView()->cursor());
1291 theGuiApp()->setCurrentView(this);
1292 d.current_work_area_ = wa;
1294 // We need to reset this now, because it will need to be
1295 // right if the tabWorkArea gets reset in the for loop. We
1296 // will change it back if we aren't in that case.
1297 GuiWorkArea * const old_cmwa = d.current_main_work_area_;
1298 d.current_main_work_area_ = wa;
1300 for (int i = 0; i != d.splitter_->count(); ++i) {
1301 if (d.tabWorkArea(i)->setCurrentWorkArea(wa)) {
1302 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea()
1303 << ", Current main wa: " << currentMainWorkArea());
1308 d.current_main_work_area_ = old_cmwa;
1310 LYXERR(Debug::DEBUG, "This is not a tabbed wa");
1311 on_currentWorkAreaChanged(wa);
1312 BufferView & bv = wa->bufferView();
1313 bv.cursor().fixIfBroken();
1315 wa->setUpdatesEnabled(true);
1316 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() << ", Current main wa: " << currentMainWorkArea());
1320 void GuiView::removeWorkArea(GuiWorkArea * wa)
1322 LASSERT(wa, return);
1323 if (wa == d.current_work_area_) {
1325 disconnectBufferView();
1326 d.current_work_area_ = 0;
1327 d.current_main_work_area_ = 0;
1330 bool found_twa = false;
1331 for (int i = 0; i != d.splitter_->count(); ++i) {
1332 TabWorkArea * twa = d.tabWorkArea(i);
1333 if (twa->removeWorkArea(wa)) {
1334 // Found in this tab group, and deleted the GuiWorkArea.
1336 if (twa->count() != 0) {
1337 if (d.current_work_area_ == 0)
1338 // This means that we are closing the current GuiWorkArea, so
1339 // switch to the next GuiWorkArea in the found TabWorkArea.
1340 setCurrentWorkArea(twa->currentWorkArea());
1342 // No more WorkAreas in this tab group, so delete it.
1349 // It is not a tabbed work area (i.e., the search work area), so it
1350 // should be deleted by other means.
1351 LASSERT(found_twa, return);
1353 if (d.current_work_area_ == 0) {
1354 if (d.splitter_->count() != 0) {
1355 TabWorkArea * twa = d.currentTabWorkArea();
1356 setCurrentWorkArea(twa->currentWorkArea());
1358 // No more work areas, switch to the background widget.
1359 setCurrentWorkArea(0);
1365 LayoutBox * GuiView::getLayoutDialog() const
1371 void GuiView::updateLayoutList()
1374 d.layout_->updateContents(false);
1378 void GuiView::updateToolbars()
1380 ToolbarMap::iterator end = d.toolbars_.end();
1381 if (d.current_work_area_) {
1383 d.current_work_area_->bufferView().cursor().inMathed()
1384 && !d.current_work_area_->bufferView().cursor().inRegexped();
1386 lyx::getStatus(FuncRequest(LFUN_LAYOUT_TABULAR)).enabled();
1388 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).enabled() &&
1389 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).onOff(true);
1390 bool const mathmacrotemplate =
1391 lyx::getStatus(FuncRequest(LFUN_IN_MATHMACROTEMPLATE)).enabled();
1393 lyx::getStatus(FuncRequest(LFUN_IN_IPA)).enabled();
1395 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1396 it->second->update(math, table, review, mathmacrotemplate, ipa);
1398 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1399 it->second->update(false, false, false, false, false);
1403 void GuiView::setBuffer(Buffer * newBuffer)
1405 LYXERR(Debug::DEBUG, "Setting buffer: " << newBuffer << endl);
1406 LASSERT(newBuffer, return);
1408 GuiWorkArea * wa = workArea(*newBuffer);
1411 newBuffer->masterBuffer()->updateBuffer();
1413 wa = addWorkArea(*newBuffer);
1414 // scroll to the position when the BufferView was last closed
1415 if (lyxrc.use_lastfilepos) {
1416 LastFilePosSection::FilePos filepos =
1417 theSession().lastFilePos().load(newBuffer->fileName());
1418 wa->bufferView().moveToPosition(filepos.pit, filepos.pos, 0, 0);
1421 //Disconnect the old buffer...there's no new one.
1424 connectBuffer(*newBuffer);
1425 connectBufferView(wa->bufferView());
1426 setCurrentWorkArea(wa);
1430 void GuiView::connectBuffer(Buffer & buf)
1432 buf.setGuiDelegate(this);
1436 void GuiView::disconnectBuffer()
1438 if (d.current_work_area_)
1439 d.current_work_area_->bufferView().buffer().setGuiDelegate(0);
1443 void GuiView::connectBufferView(BufferView & bv)
1445 bv.setGuiDelegate(this);
1449 void GuiView::disconnectBufferView()
1451 if (d.current_work_area_)
1452 d.current_work_area_->bufferView().setGuiDelegate(0);
1456 void GuiView::errors(string const & error_type, bool from_master)
1458 BufferView const * const bv = currentBufferView();
1462 #if EXPORT_in_THREAD
1463 // We are called with from_master == false by default, so we
1464 // have to figure out whether that is the case or not.
1465 ErrorList & el = bv->buffer().errorList(error_type);
1467 el = bv->buffer().masterBuffer()->errorList(error_type);
1471 ErrorList const & el = from_master ?
1472 bv->buffer().masterBuffer()->errorList(error_type) :
1473 bv->buffer().errorList(error_type);
1479 string data = error_type;
1481 data = "from_master|" + error_type;
1482 showDialog("errorlist", data);
1486 void GuiView::updateTocItem(string const & type, DocIterator const & dit)
1488 d.toc_models_.updateItem(toqstr(type), dit);
1492 void GuiView::structureChanged()
1494 d.toc_models_.reset(documentBufferView());
1495 // Navigator needs more than a simple update in this case. It needs to be
1497 updateDialog("toc", "");
1501 void GuiView::updateDialog(string const & name, string const & data)
1503 if (!isDialogVisible(name))
1506 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
1507 if (it == d.dialogs_.end())
1510 Dialog * const dialog = it->second.get();
1511 if (dialog->isVisibleView())
1512 dialog->initialiseParams(data);
1516 BufferView * GuiView::documentBufferView()
1518 return currentMainWorkArea()
1519 ? ¤tMainWorkArea()->bufferView()
1524 BufferView const * GuiView::documentBufferView() const
1526 return currentMainWorkArea()
1527 ? ¤tMainWorkArea()->bufferView()
1532 BufferView * GuiView::currentBufferView()
1534 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1538 BufferView const * GuiView::currentBufferView() const
1540 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1544 docstring GuiView::GuiViewPrivate::autosaveAndDestroy(
1545 Buffer const * orig, Buffer * clone)
1547 bool const success = clone->autoSave();
1549 busyBuffers.remove(orig);
1551 ? _("Automatic save done.")
1552 : _("Automatic save failed!");
1556 void GuiView::autoSave()
1558 LYXERR(Debug::INFO, "Running autoSave()");
1560 Buffer * buffer = documentBufferView()
1561 ? &documentBufferView()->buffer() : 0;
1563 resetAutosaveTimers();
1567 GuiViewPrivate::busyBuffers.insert(buffer);
1568 QFuture<docstring> f = QtConcurrent::run(GuiViewPrivate::autosaveAndDestroy,
1569 buffer, buffer->cloneBufferOnly());
1570 d.autosave_watcher_.setFuture(f);
1571 resetAutosaveTimers();
1575 void GuiView::resetAutosaveTimers()
1578 d.autosave_timeout_.restart();
1582 bool GuiView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1585 Buffer * buf = currentBufferView()
1586 ? ¤tBufferView()->buffer() : 0;
1587 Buffer * doc_buffer = documentBufferView()
1588 ? &(documentBufferView()->buffer()) : 0;
1590 // Check whether we need a buffer
1591 if (!lyxaction.funcHasFlag(cmd.action(), LyXAction::NoBuffer) && !buf) {
1592 // no, exit directly
1593 flag.message(from_utf8(N_("Command not allowed with"
1594 "out any document open")));
1595 flag.setEnabled(false);
1599 if (cmd.origin() == FuncRequest::TOC) {
1600 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
1601 if (!toc || !toc->getStatus(documentBufferView()->cursor(), cmd, flag))
1602 flag.setEnabled(false);
1606 switch(cmd.action()) {
1607 case LFUN_BUFFER_IMPORT:
1610 case LFUN_MASTER_BUFFER_UPDATE:
1611 case LFUN_MASTER_BUFFER_VIEW:
1612 enable = doc_buffer && doc_buffer->parent() != 0
1613 && !d.processing_thread_watcher_.isRunning();
1616 case LFUN_BUFFER_UPDATE:
1617 case LFUN_BUFFER_VIEW: {
1618 if (!doc_buffer || d.processing_thread_watcher_.isRunning()) {
1622 string format = to_utf8(cmd.argument());
1623 if (cmd.argument().empty())
1624 format = doc_buffer->params().getDefaultOutputFormat();
1625 enable = doc_buffer->params().isExportableFormat(format);
1629 case LFUN_BUFFER_RELOAD:
1630 enable = doc_buffer && !doc_buffer->isUnnamed()
1631 && doc_buffer->fileName().exists()
1632 && (!doc_buffer->isClean()
1633 || doc_buffer->isExternallyModified(Buffer::timestamp_method));
1636 case LFUN_BUFFER_CHILD_OPEN:
1637 enable = doc_buffer;
1640 case LFUN_BUFFER_WRITE:
1641 enable = doc_buffer && (doc_buffer->isUnnamed() || !doc_buffer->isClean());
1644 //FIXME: This LFUN should be moved to GuiApplication.
1645 case LFUN_BUFFER_WRITE_ALL: {
1646 // We enable the command only if there are some modified buffers
1647 Buffer * first = theBufferList().first();
1652 // We cannot use a for loop as the buffer list is a cycle.
1654 if (!b->isClean()) {
1658 b = theBufferList().next(b);
1659 } while (b != first);
1663 case LFUN_BUFFER_WRITE_AS:
1664 case LFUN_BUFFER_EXPORT_AS:
1665 enable = doc_buffer;
1668 case LFUN_BUFFER_CLOSE:
1669 case LFUN_VIEW_CLOSE:
1670 enable = doc_buffer;
1673 case LFUN_BUFFER_CLOSE_ALL:
1674 enable = theBufferList().last() != theBufferList().first();
1677 case LFUN_VIEW_SPLIT:
1678 if (cmd.getArg(0) == "vertical")
1679 enable = doc_buffer && (d.splitter_->count() == 1 ||
1680 d.splitter_->orientation() == Qt::Vertical);
1682 enable = doc_buffer && (d.splitter_->count() == 1 ||
1683 d.splitter_->orientation() == Qt::Horizontal);
1686 case LFUN_TAB_GROUP_CLOSE:
1687 enable = d.tabWorkAreaCount() > 1;
1690 case LFUN_TOOLBAR_TOGGLE: {
1691 string const name = cmd.getArg(0);
1692 if (GuiToolbar * t = toolbar(name))
1693 flag.setOnOff(t->isVisible());
1696 docstring const msg =
1697 bformat(_("Unknown toolbar \"%1$s\""), from_utf8(name));
1703 case LFUN_DROP_LAYOUTS_CHOICE:
1707 case LFUN_UI_TOGGLE:
1708 flag.setOnOff(isFullScreen());
1711 case LFUN_DIALOG_DISCONNECT_INSET:
1714 case LFUN_DIALOG_HIDE:
1715 // FIXME: should we check if the dialog is shown?
1718 case LFUN_DIALOG_TOGGLE:
1719 flag.setOnOff(isDialogVisible(cmd.getArg(0)));
1720 // fall through to set "enable"
1721 case LFUN_DIALOG_SHOW: {
1722 string const name = cmd.getArg(0);
1724 enable = name == "aboutlyx"
1725 || name == "file" //FIXME: should be removed.
1727 || name == "texinfo"
1728 || name == "progress"
1729 || name == "compare";
1730 else if (name == "print")
1731 enable = doc_buffer->params().isExportable("dvi")
1732 && lyxrc.print_command != "none";
1733 else if (name == "character" || name == "symbols") {
1734 if (!buf || buf->isReadonly())
1737 Cursor const & cur = currentBufferView()->cursor();
1738 enable = !(cur.inTexted() && cur.paragraph().isPassThru());
1741 else if (name == "latexlog")
1742 enable = FileName(doc_buffer->logName()).isReadableFile();
1743 else if (name == "spellchecker")
1744 enable = theSpellChecker()
1745 && !doc_buffer->isReadonly()
1746 && !doc_buffer->text().empty();
1747 else if (name == "vclog")
1748 enable = doc_buffer->lyxvc().inUse();
1752 case LFUN_DIALOG_UPDATE: {
1753 string const name = cmd.getArg(0);
1755 enable = name == "prefs";
1759 case LFUN_COMMAND_EXECUTE:
1761 case LFUN_MENU_OPEN:
1762 // Nothing to check.
1765 case LFUN_COMPLETION_INLINE:
1766 if (!d.current_work_area_
1767 || !d.current_work_area_->completer().inlinePossible(
1768 currentBufferView()->cursor()))
1772 case LFUN_COMPLETION_POPUP:
1773 if (!d.current_work_area_
1774 || !d.current_work_area_->completer().popupPossible(
1775 currentBufferView()->cursor()))
1779 case LFUN_COMPLETION_COMPLETE:
1780 if (!d.current_work_area_
1781 || !d.current_work_area_->completer().inlinePossible(
1782 currentBufferView()->cursor()))
1786 case LFUN_COMPLETION_ACCEPT:
1787 if (!d.current_work_area_
1788 || (!d.current_work_area_->completer().popupVisible()
1789 && !d.current_work_area_->completer().inlineVisible()
1790 && !d.current_work_area_->completer().completionAvailable()))
1794 case LFUN_COMPLETION_CANCEL:
1795 if (!d.current_work_area_
1796 || (!d.current_work_area_->completer().popupVisible()
1797 && !d.current_work_area_->completer().inlineVisible()))
1801 case LFUN_BUFFER_ZOOM_OUT:
1802 enable = doc_buffer && lyxrc.zoom > 10;
1805 case LFUN_BUFFER_ZOOM_IN:
1806 enable = doc_buffer;
1809 case LFUN_BUFFER_NEXT:
1810 case LFUN_BUFFER_PREVIOUS:
1811 // FIXME: should we check is there is an previous or next buffer?
1813 case LFUN_BUFFER_SWITCH:
1814 // toggle on the current buffer, but do not toggle off
1815 // the other ones (is that a good idea?)
1817 && to_utf8(cmd.argument()) == doc_buffer->absFileName())
1818 flag.setOnOff(true);
1821 case LFUN_VC_REGISTER:
1822 enable = doc_buffer && !doc_buffer->lyxvc().inUse();
1824 case LFUN_VC_RENAME:
1825 enable = doc_buffer && doc_buffer->lyxvc().renameEnabled();
1828 enable = doc_buffer && doc_buffer->lyxvc().copyEnabled();
1830 case LFUN_VC_CHECK_IN:
1831 enable = doc_buffer && doc_buffer->lyxvc().checkInEnabled();
1833 case LFUN_VC_CHECK_OUT:
1834 enable = doc_buffer && doc_buffer->lyxvc().checkOutEnabled();
1836 case LFUN_VC_LOCKING_TOGGLE:
1837 enable = doc_buffer && !doc_buffer->isReadonly()
1838 && doc_buffer->lyxvc().lockingToggleEnabled();
1839 flag.setOnOff(enable && doc_buffer->lyxvc().locking());
1841 case LFUN_VC_REVERT:
1842 enable = doc_buffer && doc_buffer->lyxvc().inUse() && !doc_buffer->isReadonly();
1844 case LFUN_VC_UNDO_LAST:
1845 enable = doc_buffer && doc_buffer->lyxvc().undoLastEnabled();
1847 case LFUN_VC_REPO_UPDATE:
1848 enable = doc_buffer && doc_buffer->lyxvc().repoUpdateEnabled();
1850 case LFUN_VC_COMMAND: {
1851 if (cmd.argument().empty())
1853 if (!doc_buffer && contains(cmd.getArg(0), 'D'))
1857 case LFUN_VC_COMPARE:
1858 enable = doc_buffer && doc_buffer->lyxvc().prepareFileRevisionEnabled();
1861 case LFUN_SERVER_GOTO_FILE_ROW:
1863 case LFUN_FORWARD_SEARCH:
1864 enable = !(lyxrc.forward_search_dvi.empty() && lyxrc.forward_search_pdf.empty());
1867 case LFUN_FILE_INSERT_PLAINTEXT:
1868 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
1869 enable = documentBufferView() && documentBufferView()->cursor().inTexted();
1872 case LFUN_SPELLING_CONTINUOUSLY:
1873 flag.setOnOff(lyxrc.spellcheck_continuously);
1881 flag.setEnabled(false);
1887 static FileName selectTemplateFile()
1889 FileDialog dlg(qt_("Select template file"));
1890 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1891 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
1893 FileDialog::Result result = dlg.open(toqstr(lyxrc.template_path),
1894 QStringList(qt_("LyX Documents (*.lyx)")));
1896 if (result.first == FileDialog::Later)
1898 if (result.second.isEmpty())
1900 return FileName(fromqstr(result.second));
1904 Buffer * GuiView::loadDocument(FileName const & filename, bool tolastfiles)
1908 Buffer * newBuffer = 0;
1910 newBuffer = checkAndLoadLyXFile(filename);
1911 } catch (ExceptionMessage const & e) {
1918 message(_("Document not loaded."));
1922 setBuffer(newBuffer);
1923 newBuffer->errors("Parse");
1926 theSession().lastFiles().add(filename);
1932 void GuiView::openDocument(string const & fname)
1934 string initpath = lyxrc.document_path;
1936 if (documentBufferView()) {
1937 string const trypath = documentBufferView()->buffer().filePath();
1938 // If directory is writeable, use this as default.
1939 if (FileName(trypath).isDirWritable())
1945 if (fname.empty()) {
1946 FileDialog dlg(qt_("Select document to open"), LFUN_FILE_OPEN);
1947 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1948 dlg.setButton2(qt_("Examples|#E#e"),
1949 toqstr(addPath(package().system_support().absFileName(), "examples")));
1951 QStringList filter(qt_("LyX Documents (*.lyx)"));
1952 filter << qt_("LyX-1.3.x Documents (*.lyx13)")
1953 << qt_("LyX-1.4.x Documents (*.lyx14)")
1954 << qt_("LyX-1.5.x Documents (*.lyx15)")
1955 << qt_("LyX-1.6.x Documents (*.lyx16)");
1956 FileDialog::Result result =
1957 dlg.open(toqstr(initpath), filter);
1959 if (result.first == FileDialog::Later)
1962 filename = fromqstr(result.second);
1964 // check selected filename
1965 if (filename.empty()) {
1966 message(_("Canceled."));
1972 // get absolute path of file and add ".lyx" to the filename if
1974 FileName const fullname =
1975 fileSearch(string(), filename, "lyx", support::may_not_exist);
1976 if (!fullname.empty())
1977 filename = fullname.absFileName();
1979 if (!fullname.onlyPath().isDirectory()) {
1980 Alert::warning(_("Invalid filename"),
1981 bformat(_("The directory in the given path\n%1$s\ndoes not exist."),
1982 from_utf8(fullname.absFileName())));
1986 // if the file doesn't exist and isn't already open (bug 6645),
1987 // let the user create one
1988 if (!fullname.exists() && !theBufferList().exists(fullname) &&
1989 !LyXVC::file_not_found_hook(fullname)) {
1990 // the user specifically chose this name. Believe him.
1991 Buffer * const b = newFile(filename, string(), true);
1997 docstring const disp_fn = makeDisplayPath(filename);
1998 message(bformat(_("Opening document %1$s..."), disp_fn));
2001 Buffer * buf = loadDocument(fullname);
2003 str2 = bformat(_("Document %1$s opened."), disp_fn);
2004 if (buf->lyxvc().inUse())
2005 str2 += " " + from_utf8(buf->lyxvc().versionString()) +
2006 " " + _("Version control detected.");
2008 str2 = bformat(_("Could not open document %1$s"), disp_fn);
2013 // FIXME: clean that
2014 static bool import(GuiView * lv, FileName const & filename,
2015 string const & format, ErrorList & errorList)
2017 FileName const lyxfile(support::changeExtension(filename.absFileName(), ".lyx"));
2019 string loader_format;
2020 vector<string> loaders = theConverters().loaders();
2021 if (find(loaders.begin(), loaders.end(), format) == loaders.end()) {
2022 vector<string>::const_iterator it = loaders.begin();
2023 vector<string>::const_iterator en = loaders.end();
2024 for (; it != en; ++it) {
2025 if (!theConverters().isReachable(format, *it))
2028 string const tofile =
2029 support::changeExtension(filename.absFileName(),
2030 formats.extension(*it));
2031 if (!theConverters().convert(0, filename, FileName(tofile),
2032 filename, format, *it, errorList))
2034 loader_format = *it;
2037 if (loader_format.empty()) {
2038 frontend::Alert::error(_("Couldn't import file"),
2039 bformat(_("No information for importing the format %1$s."),
2040 formats.prettyName(format)));
2044 loader_format = format;
2046 if (loader_format == "lyx") {
2047 Buffer * buf = lv->loadDocument(lyxfile);
2051 Buffer * const b = newFile(lyxfile.absFileName(), string(), true);
2055 bool as_paragraphs = loader_format == "textparagraph";
2056 string filename2 = (loader_format == format) ? filename.absFileName()
2057 : support::changeExtension(filename.absFileName(),
2058 formats.extension(loader_format));
2059 lv->currentBufferView()->insertPlaintextFile(FileName(filename2),
2061 guiApp->setCurrentView(lv);
2062 lyx::dispatch(FuncRequest(LFUN_MARK_OFF));
2069 void GuiView::importDocument(string const & argument)
2072 string filename = split(argument, format, ' ');
2074 LYXERR(Debug::INFO, format << " file: " << filename);
2076 // need user interaction
2077 if (filename.empty()) {
2078 string initpath = lyxrc.document_path;
2079 if (documentBufferView()) {
2080 string const trypath = documentBufferView()->buffer().filePath();
2081 // If directory is writeable, use this as default.
2082 if (FileName(trypath).isDirWritable())
2086 docstring const text = bformat(_("Select %1$s file to import"),
2087 formats.prettyName(format));
2089 FileDialog dlg(toqstr(text), LFUN_BUFFER_IMPORT);
2090 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2091 dlg.setButton2(qt_("Examples|#E#e"),
2092 toqstr(addPath(package().system_support().absFileName(), "examples")));
2094 docstring filter = formats.prettyName(format);
2097 filter += from_utf8(formats.extensions(format));
2100 FileDialog::Result result =
2101 dlg.open(toqstr(initpath), fileFilters(toqstr(filter)));
2103 if (result.first == FileDialog::Later)
2106 filename = fromqstr(result.second);
2108 // check selected filename
2109 if (filename.empty())
2110 message(_("Canceled."));
2113 if (filename.empty())
2116 // get absolute path of file
2117 FileName const fullname(support::makeAbsPath(filename));
2119 FileName const lyxfile(support::changeExtension(fullname.absFileName(), ".lyx"));
2121 // Check if the document already is open
2122 Buffer * buf = theBufferList().getBuffer(lyxfile);
2125 if (!closeBuffer()) {
2126 message(_("Canceled."));
2131 docstring const displaypath = makeDisplayPath(lyxfile.absFileName(), 30);
2133 // if the file exists already, and we didn't do
2134 // -i lyx thefile.lyx, warn
2135 if (lyxfile.exists() && fullname != lyxfile) {
2137 docstring text = bformat(_("The document %1$s already exists.\n\n"
2138 "Do you want to overwrite that document?"), displaypath);
2139 int const ret = Alert::prompt(_("Overwrite document?"),
2140 text, 0, 1, _("&Overwrite"), _("&Cancel"));
2143 message(_("Canceled."));
2148 message(bformat(_("Importing %1$s..."), displaypath));
2149 ErrorList errorList;
2150 if (import(this, fullname, format, errorList))
2151 message(_("imported."));
2153 message(_("file not imported!"));
2155 // FIXME (Abdel 12/08/06): Is there a need to display the error list here?
2159 void GuiView::newDocument(string const & filename, bool from_template)
2161 FileName initpath(lyxrc.document_path);
2162 if (documentBufferView()) {
2163 FileName const trypath(documentBufferView()->buffer().filePath());
2164 // If directory is writeable, use this as default.
2165 if (trypath.isDirWritable())
2169 string templatefile;
2170 if (from_template) {
2171 templatefile = selectTemplateFile().absFileName();
2172 if (templatefile.empty())
2177 if (filename.empty())
2178 b = newUnnamedFile(initpath, to_utf8(_("newfile")), templatefile);
2180 b = newFile(filename, templatefile, true);
2185 // If no new document could be created, it is unsure
2186 // whether there is a valid BufferView.
2187 if (currentBufferView())
2188 // Ensure the cursor is correctly positioned on screen.
2189 currentBufferView()->showCursor();
2193 void GuiView::insertLyXFile(docstring const & fname)
2195 BufferView * bv = documentBufferView();
2200 FileName filename(to_utf8(fname));
2201 if (filename.empty()) {
2202 // Launch a file browser
2204 string initpath = lyxrc.document_path;
2205 string const trypath = bv->buffer().filePath();
2206 // If directory is writeable, use this as default.
2207 if (FileName(trypath).isDirWritable())
2211 FileDialog dlg(qt_("Select LyX document to insert"), LFUN_FILE_INSERT);
2212 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2213 dlg.setButton2(qt_("Examples|#E#e"),
2214 toqstr(addPath(package().system_support().absFileName(),
2217 FileDialog::Result result = dlg.open(toqstr(initpath),
2218 QStringList(qt_("LyX Documents (*.lyx)")));
2220 if (result.first == FileDialog::Later)
2224 filename.set(fromqstr(result.second));
2226 // check selected filename
2227 if (filename.empty()) {
2228 // emit message signal.
2229 message(_("Canceled."));
2234 bv->insertLyXFile(filename);
2235 bv->buffer().errors("Parse");
2239 bool GuiView::renameBuffer(Buffer & b, docstring const & newname, RenameKind kind)
2241 FileName fname = b.fileName();
2242 FileName const oldname = fname;
2244 if (!newname.empty()) {
2246 fname = support::makeAbsPath(to_utf8(newname), oldname.onlyPath().absFileName());
2248 // Switch to this Buffer.
2251 // No argument? Ask user through dialog.
2253 FileDialog dlg(qt_("Choose a filename to save document as"),
2254 LFUN_BUFFER_WRITE_AS);
2255 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2256 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
2258 if (!isLyXFileName(fname.absFileName()))
2259 fname.changeExtension(".lyx");
2261 FileDialog::Result result =
2262 dlg.save(toqstr(fname.onlyPath().absFileName()),
2263 QStringList(qt_("LyX Documents (*.lyx)")),
2264 toqstr(fname.onlyFileName()));
2266 if (result.first == FileDialog::Later)
2269 fname.set(fromqstr(result.second));
2274 if (!isLyXFileName(fname.absFileName()))
2275 fname.changeExtension(".lyx");
2278 // fname is now the new Buffer location.
2280 // if there is already a Buffer open with this name, we do not want
2281 // to have another one. (the second test makes sure we're not just
2282 // trying to overwrite ourselves, which is fine.)
2283 if (theBufferList().exists(fname) && fname != oldname
2284 && theBufferList().getBuffer(fname) != &b) {
2285 docstring const text =
2286 bformat(_("The file\n%1$s\nis already open in your current session.\n"
2287 "Please close it before attempting to overwrite it.\n"
2288 "Do you want to choose a new filename?"),
2289 from_utf8(fname.absFileName()));
2290 int const ret = Alert::prompt(_("Chosen File Already Open"),
2291 text, 0, 1, _("&Rename"), _("&Cancel"));
2293 case 0: return renameBuffer(b, docstring(), kind);
2294 case 1: return false;
2299 bool const existsLocal = fname.exists();
2300 bool const existsInVC = LyXVC::fileInVC(fname);
2301 if (existsLocal || existsInVC) {
2302 docstring const file = makeDisplayPath(fname.absFileName(), 30);
2303 if (kind != LV_WRITE_AS && existsInVC) {
2304 // renaming to a name that is already in VC
2306 docstring text = bformat(_("The document %1$s "
2307 "is already registered.\n\n"
2308 "Do you want to choose a new name?"),
2310 docstring const title = (kind == LV_VC_RENAME) ?
2311 _("Rename document?") : _("Copy document?");
2312 docstring const button = (kind == LV_VC_RENAME) ?
2313 _("&Rename") : _("&Copy");
2314 int const ret = Alert::prompt(title, text, 0, 1,
2315 button, _("&Cancel"));
2317 case 0: return renameBuffer(b, docstring(), kind);
2318 case 1: return false;
2323 docstring text = bformat(_("The document %1$s "
2324 "already exists.\n\n"
2325 "Do you want to overwrite that document?"),
2327 int const ret = Alert::prompt(_("Overwrite document?"),
2328 text, 0, 2, _("&Overwrite"),
2329 _("&Rename"), _("&Cancel"));
2332 case 1: return renameBuffer(b, docstring(), kind);
2333 case 2: return false;
2339 case LV_VC_RENAME: {
2340 string msg = b.lyxvc().rename(fname);
2343 message(from_utf8(msg));
2347 string msg = b.lyxvc().copy(fname);
2350 message(from_utf8(msg));
2356 // LyXVC created the file already in case of LV_VC_RENAME or
2357 // LV_VC_COPY, but call saveBuffer() nevertheless to get
2358 // relative paths of included stuff right if we moved e.g. from
2359 // /a/b.lyx to /a/c/b.lyx.
2361 bool const saved = saveBuffer(b, fname);
2368 struct PrettyNameComparator
2370 bool operator()(Format const *first, Format const *second) const {
2371 return compare_ascii_no_case(first->prettyname(), second->prettyname()) <= 0;
2376 bool GuiView::exportBufferAs(Buffer & b)
2378 FileName fname = b.fileName();
2380 FileDialog dlg(qt_("Choose a filename to export the document as"));
2381 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2384 types << "Any supported format (*.*)";
2385 Formats::const_iterator it = formats.begin();
2386 vector<Format const *> export_formats;
2387 for (; it != formats.end(); ++it)
2388 if (it->documentFormat() && it->inExportMenu())
2389 export_formats.push_back(&(*it));
2390 PrettyNameComparator cmp;
2391 sort(export_formats.begin(), export_formats.end(), cmp);
2392 vector<Format const *>::const_iterator fit = export_formats.begin();
2393 for (; fit != export_formats.end(); ++fit)
2394 types << toqstr((*fit)->prettyname() + " (*." + (*fit)->extension() + ")");
2396 FileDialog::Result result =
2397 dlg.save(toqstr(fname.onlyPath().absFileName()),
2399 toqstr(fname.onlyFileName()),
2401 if (result.first != FileDialog::Chosen)
2404 string s = fromqstr(filter);
2405 size_t pos = s.find(" (*.");
2406 LATTEST(pos != string::npos);
2407 string fmt_prettyname = s.substr(0, pos);
2409 fname.set(fromqstr(result.second));
2410 if (fmt_prettyname == "Any supported format")
2411 fmt_name = formats.getFormatFromExtension(fname.extension());
2413 fmt_name = formats.getFormatFromPrettyName(fmt_prettyname);
2414 LYXERR(Debug::FILES, "fmt_prettyname=" << fmt_prettyname
2415 << ", fmt_name=" << fmt_name << ", fname=" << fname.absFileName());
2417 if (fmt_name.empty() || fname.empty())
2420 // fname is now the new Buffer location.
2421 if (FileName(fname).exists()) {
2422 docstring const file = makeDisplayPath(fname.absFileName(), 30);
2423 docstring text = bformat(_("The document %1$s already "
2424 "exists.\n\nDo you want to "
2425 "overwrite that document?"),
2427 int const ret = Alert::prompt(_("Overwrite document?"),
2428 text, 0, 2, _("&Overwrite"), _("&Rename"), _("&Cancel"));
2431 case 1: return exportBufferAs(b);
2432 case 2: return false;
2436 FuncRequest cmd(LFUN_BUFFER_EXPORT, fmt_name + " " + fname.absFileName());
2439 return dr.dispatched();
2443 bool GuiView::saveBuffer(Buffer & b)
2445 return saveBuffer(b, FileName());
2449 bool GuiView::saveBuffer(Buffer & b, FileName const & fn)
2451 if (workArea(b) && workArea(b)->inDialogMode())
2454 if (fn.empty() && b.isUnnamed())
2455 return renameBuffer(b, docstring());
2457 bool const success = (fn.empty() ? b.save() : b.saveAs(fn));
2459 theSession().lastFiles().add(b.fileName());
2463 // Switch to this Buffer.
2466 // FIXME: we don't tell the user *WHY* the save failed !!
2467 docstring const file = makeDisplayPath(b.absFileName(), 30);
2468 docstring text = bformat(_("The document %1$s could not be saved.\n\n"
2469 "Do you want to rename the document and "
2470 "try again?"), file);
2471 int const ret = Alert::prompt(_("Rename and save?"),
2472 text, 0, 2, _("&Rename"), _("&Retry"), _("&Cancel"));
2475 if (!renameBuffer(b, docstring()))
2484 return saveBuffer(b, fn);
2488 bool GuiView::hideWorkArea(GuiWorkArea * wa)
2490 return closeWorkArea(wa, false);
2494 // We only want to close the buffer if it is not visible in other workareas
2495 // of the same view, nor in other views, and if this is not a child
2496 bool GuiView::closeWorkArea(GuiWorkArea * wa)
2498 Buffer & buf = wa->bufferView().buffer();
2500 bool last_wa = d.countWorkAreasOf(buf) == 1
2501 && !inOtherView(buf) && !buf.parent();
2503 bool close_buffer = last_wa;
2506 if (lyxrc.close_buffer_with_last_view == "yes")
2508 else if (lyxrc.close_buffer_with_last_view == "no")
2509 close_buffer = false;
2512 if (buf.isUnnamed())
2513 file = from_utf8(buf.fileName().onlyFileName());
2515 file = buf.fileName().displayName(30);
2516 docstring const text = bformat(
2517 _("Last view on document %1$s is being closed.\n"
2518 "Would you like to close or hide the document?\n"
2520 "Hidden documents can be displayed back through\n"
2521 "the menu: View->Hidden->...\n"
2523 "To remove this question, set your preference in:\n"
2524 " Tools->Preferences->Look&Feel->UserInterface\n"
2526 int ret = Alert::prompt(_("Close or hide document?"),
2527 text, 0, 1, _("&Close"), _("&Hide"));
2528 close_buffer = (ret == 0);
2532 return closeWorkArea(wa, close_buffer);
2536 bool GuiView::closeBuffer()
2538 GuiWorkArea * wa = currentMainWorkArea();
2539 setCurrentWorkArea(wa);
2540 Buffer & buf = wa->bufferView().buffer();
2541 return wa && closeWorkArea(wa, !buf.parent());
2545 void GuiView::writeSession() const {
2546 GuiWorkArea const * active_wa = currentMainWorkArea();
2547 for (int i = 0; i < d.splitter_->count(); ++i) {
2548 TabWorkArea * twa = d.tabWorkArea(i);
2549 for (int j = 0; j < twa->count(); ++j) {
2550 GuiWorkArea * wa = static_cast<GuiWorkArea *>(twa->widget(j));
2551 Buffer & buf = wa->bufferView().buffer();
2552 theSession().lastOpened().add(buf.fileName(), wa == active_wa);
2558 bool GuiView::closeBufferAll()
2560 // Close the workareas in all other views
2561 QList<int> const ids = guiApp->viewIds();
2562 for (int i = 0; i != ids.size(); ++i) {
2563 if (id_ != ids[i] && !guiApp->view(ids[i]).closeWorkAreaAll())
2567 // Close our own workareas
2568 if (!closeWorkAreaAll())
2571 // Now close the hidden buffers. We prevent hidden buffers from being
2572 // dirty, so we can just close them.
2573 theBufferList().closeAll();
2578 bool GuiView::closeWorkAreaAll()
2580 setCurrentWorkArea(currentMainWorkArea());
2582 // We might be in a situation that there is still a tabWorkArea, but
2583 // there are no tabs anymore. This can happen when we get here after a
2584 // TabWorkArea::lastWorkAreaRemoved() signal. Therefore we count how
2585 // many TabWorkArea's have no documents anymore.
2588 // We have to call count() each time, because it can happen that
2589 // more than one splitter will disappear in one iteration (bug 5998).
2590 for (; d.splitter_->count() > empty_twa; ) {
2591 TabWorkArea * twa = d.tabWorkArea(empty_twa);
2593 if (twa->count() == 0)
2596 setCurrentWorkArea(twa->currentWorkArea());
2597 if (!closeTabWorkArea(twa))
2605 bool GuiView::closeWorkArea(GuiWorkArea * wa, bool close_buffer)
2610 Buffer & buf = wa->bufferView().buffer();
2612 if (close_buffer && GuiViewPrivate::busyBuffers.contains(&buf)) {
2613 Alert::warning(_("Close document"),
2614 _("Document could not be closed because it is being processed by LyX."));
2619 return closeBuffer(buf);
2621 if (!inMultiTabs(wa))
2622 if (!saveBufferIfNeeded(buf, true))
2630 bool GuiView::closeBuffer(Buffer & buf)
2632 // If we are in a close_event all children will be closed in some time,
2633 // so no need to do it here. This will ensure that the children end up
2634 // in the session file in the correct order. If we close the master
2635 // buffer, we can close or release the child buffers here too.
2636 bool success = true;
2638 ListOfBuffers clist = buf.getChildren();
2639 ListOfBuffers::const_iterator it = clist.begin();
2640 ListOfBuffers::const_iterator const bend = clist.end();
2641 for (; it != bend; ++it) {
2642 // If a child is dirty, do not close
2643 // without user intervention
2644 //FIXME: should we look in other tabworkareas?
2645 Buffer * child_buf = *it;
2646 GuiWorkArea * child_wa = workArea(*child_buf);
2648 if (!closeWorkArea(child_wa, true)) {
2653 theBufferList().releaseChild(&buf, child_buf);
2657 // goto bookmark to update bookmark pit.
2658 //FIXME: we should update only the bookmarks related to this buffer!
2659 LYXERR(Debug::DEBUG, "GuiView::closeBuffer()");
2660 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
2661 guiApp->gotoBookmark(i+1, false, false);
2663 if (saveBufferIfNeeded(buf, false)) {
2664 buf.removeAutosaveFile();
2665 theBufferList().release(&buf);
2669 // open all children again to avoid a crash because of dangling
2670 // pointers (bug 6603)
2676 bool GuiView::closeTabWorkArea(TabWorkArea * twa)
2678 while (twa == d.currentTabWorkArea()) {
2679 twa->setCurrentIndex(twa->count()-1);
2681 GuiWorkArea * wa = twa->currentWorkArea();
2682 Buffer & b = wa->bufferView().buffer();
2684 // We only want to close the buffer if the same buffer is not visible
2685 // in another view, and if this is not a child and if we are closing
2686 // a view (not a tabgroup).
2687 bool const close_buffer =
2688 !inOtherView(b) && !b.parent() && closing_;
2690 if (!closeWorkArea(wa, close_buffer))
2697 bool GuiView::saveBufferIfNeeded(Buffer & buf, bool hiding)
2699 if (buf.isClean() || buf.paragraphs().empty())
2702 // Switch to this Buffer.
2707 if (buf.isUnnamed())
2708 file = from_utf8(buf.fileName().onlyFileName());
2710 file = buf.fileName().displayName(30);
2712 // Bring this window to top before asking questions.
2717 if (hiding && buf.isUnnamed()) {
2718 docstring const text = bformat(_("The document %1$s has not been "
2719 "saved yet.\n\nDo you want to save "
2720 "the document?"), file);
2721 ret = Alert::prompt(_("Save new document?"),
2722 text, 0, 1, _("&Save"), _("&Cancel"));
2726 docstring const text = bformat(_("The document %1$s has unsaved changes."
2727 "\n\nDo you want to save the document or discard the changes?"), file);
2728 ret = Alert::prompt(_("Save changed document?"),
2729 text, 0, 2, _("&Save"), _("&Discard"), _("&Cancel"));
2734 if (!saveBuffer(buf))
2738 // If we crash after this we could have no autosave file
2739 // but I guess this is really improbable (Jug).
2740 // Sometimes improbable things happen:
2741 // - see bug http://www.lyx.org/trac/ticket/6587 (ps)
2742 // buf.removeAutosaveFile();
2744 // revert all changes
2755 bool GuiView::inMultiTabs(GuiWorkArea * wa)
2757 Buffer & buf = wa->bufferView().buffer();
2759 for (int i = 0; i != d.splitter_->count(); ++i) {
2760 GuiWorkArea * wa_ = d.tabWorkArea(i)->workArea(buf);
2761 if (wa_ && wa_ != wa)
2764 return inOtherView(buf);
2768 bool GuiView::inOtherView(Buffer & buf)
2770 QList<int> const ids = guiApp->viewIds();
2772 for (int i = 0; i != ids.size(); ++i) {
2776 if (guiApp->view(ids[i]).workArea(buf))
2783 void GuiView::gotoNextOrPreviousBuffer(NextOrPrevious np)
2785 if (!documentBufferView())
2788 if (TabWorkArea * twa = d.currentTabWorkArea()) {
2789 Buffer * const curbuf = &documentBufferView()->buffer();
2790 int nwa = twa->count();
2791 for (int i = 0; i < nwa; ++i) {
2792 if (&workArea(i)->bufferView().buffer() == curbuf) {
2794 if (np == NEXTBUFFER)
2795 next_index = (i == nwa - 1 ? 0 : i + 1);
2797 next_index = (i == 0 ? nwa - 1 : i - 1);
2798 setBuffer(&workArea(next_index)->bufferView().buffer());
2806 /// make sure the document is saved
2807 static bool ensureBufferClean(Buffer * buffer)
2809 LASSERT(buffer, return false);
2810 if (buffer->isClean() && !buffer->isUnnamed())
2813 docstring const file = buffer->fileName().displayName(30);
2816 if (!buffer->isUnnamed()) {
2817 text = bformat(_("The document %1$s has unsaved "
2818 "changes.\n\nDo you want to save "
2819 "the document?"), file);
2820 title = _("Save changed document?");
2823 text = bformat(_("The document %1$s has not been "
2824 "saved yet.\n\nDo you want to save "
2825 "the document?"), file);
2826 title = _("Save new document?");
2828 int const ret = Alert::prompt(title, text, 0, 1, _("&Save"), _("&Cancel"));
2831 dispatch(FuncRequest(LFUN_BUFFER_WRITE));
2833 return buffer->isClean() && !buffer->isUnnamed();
2837 bool GuiView::reloadBuffer(Buffer & buf)
2839 Buffer::ReadStatus status = buf.reload();
2840 return status == Buffer::ReadSuccess;
2844 void GuiView::checkExternallyModifiedBuffers()
2846 BufferList::iterator bit = theBufferList().begin();
2847 BufferList::iterator const bend = theBufferList().end();
2848 for (; bit != bend; ++bit) {
2849 Buffer * buf = *bit;
2850 if (buf->fileName().exists()
2851 && buf->isExternallyModified(Buffer::checksum_method)) {
2852 docstring text = bformat(_("Document \n%1$s\n has been externally modified."
2853 " Reload now? Any local changes will be lost."),
2854 from_utf8(buf->absFileName()));
2855 int const ret = Alert::prompt(_("Reload externally changed document?"),
2856 text, 0, 1, _("&Reload"), _("&Cancel"));
2864 void GuiView::dispatchVC(FuncRequest const & cmd, DispatchResult & dr)
2866 Buffer * buffer = documentBufferView()
2867 ? &(documentBufferView()->buffer()) : 0;
2869 switch (cmd.action()) {
2870 case LFUN_VC_REGISTER:
2871 if (!buffer || !ensureBufferClean(buffer))
2873 if (!buffer->lyxvc().inUse()) {
2874 if (buffer->lyxvc().registrer()) {
2875 reloadBuffer(*buffer);
2876 dr.suppressMessageUpdate();
2881 case LFUN_VC_RENAME:
2882 case LFUN_VC_COPY: {
2883 if (!buffer || !ensureBufferClean(buffer))
2885 if (buffer->lyxvc().inUse() && !buffer->isReadonly()) {
2886 if (buffer->lyxvc().isCheckInWithConfirmation()) {
2887 // Some changes are not yet committed.
2888 // We test here and not in getStatus(), since
2889 // this test is expensive.
2891 LyXVC::CommandResult ret =
2892 buffer->lyxvc().checkIn(log);
2894 if (ret == LyXVC::ErrorCommand ||
2895 ret == LyXVC::VCSuccess)
2896 reloadBuffer(*buffer);
2897 if (buffer->lyxvc().isCheckInWithConfirmation()) {
2898 frontend::Alert::error(
2899 _("Revision control error."),
2900 _("Document could not be checked in."));
2904 RenameKind const kind = (cmd.action() == LFUN_VC_RENAME) ?
2905 LV_VC_RENAME : LV_VC_COPY;
2906 renameBuffer(*buffer, cmd.argument(), kind);
2911 case LFUN_VC_CHECK_IN:
2912 if (!buffer || !ensureBufferClean(buffer))
2914 if (buffer->lyxvc().inUse() && !buffer->isReadonly()) {
2916 LyXVC::CommandResult ret = buffer->lyxvc().checkIn(log);
2918 // Only skip reloading if the checkin was cancelled or
2919 // an error occured before the real checkin VCS command
2920 // was executed, since the VCS might have changed the
2921 // file even if it could not checkin successfully.
2922 if (ret == LyXVC::ErrorCommand || ret == LyXVC::VCSuccess)
2923 reloadBuffer(*buffer);
2927 case LFUN_VC_CHECK_OUT:
2928 if (!buffer || !ensureBufferClean(buffer))
2930 if (buffer->lyxvc().inUse()) {
2931 dr.setMessage(buffer->lyxvc().checkOut());
2932 reloadBuffer(*buffer);
2936 case LFUN_VC_LOCKING_TOGGLE:
2937 LASSERT(buffer, return);
2938 if (!ensureBufferClean(buffer) || buffer->isReadonly())
2940 if (buffer->lyxvc().inUse()) {
2941 string res = buffer->lyxvc().lockingToggle();
2943 frontend::Alert::error(_("Revision control error."),
2944 _("Error when setting the locking property."));
2947 reloadBuffer(*buffer);
2952 case LFUN_VC_REVERT:
2953 LASSERT(buffer, return);
2954 if (buffer->lyxvc().revert()) {
2955 reloadBuffer(*buffer);
2956 dr.suppressMessageUpdate();
2960 case LFUN_VC_UNDO_LAST:
2961 LASSERT(buffer, return);
2962 buffer->lyxvc().undoLast();
2963 reloadBuffer(*buffer);
2964 dr.suppressMessageUpdate();
2967 case LFUN_VC_REPO_UPDATE:
2968 LASSERT(buffer, return);
2969 if (ensureBufferClean(buffer)) {
2970 dr.setMessage(buffer->lyxvc().repoUpdate());
2971 checkExternallyModifiedBuffers();
2975 case LFUN_VC_COMMAND: {
2976 string flag = cmd.getArg(0);
2977 if (buffer && contains(flag, 'R') && !ensureBufferClean(buffer))
2980 if (contains(flag, 'M')) {
2981 if (!Alert::askForText(message, _("LyX VC: Log Message")))
2984 string path = cmd.getArg(1);
2985 if (contains(path, "$$p") && buffer)
2986 path = subst(path, "$$p", buffer->filePath());
2987 LYXERR(Debug::LYXVC, "Directory: " << path);
2989 if (!pp.isReadableDirectory()) {
2990 lyxerr << _("Directory is not accessible.") << endl;
2993 support::PathChanger p(pp);
2995 string command = cmd.getArg(2);
2996 if (command.empty())
2999 command = subst(command, "$$i", buffer->absFileName());
3000 command = subst(command, "$$p", buffer->filePath());
3002 command = subst(command, "$$m", to_utf8(message));
3003 LYXERR(Debug::LYXVC, "Command: " << command);
3005 one.startscript(Systemcall::Wait, command);
3009 if (contains(flag, 'I'))
3010 buffer->markDirty();
3011 if (contains(flag, 'R'))
3012 reloadBuffer(*buffer);
3017 case LFUN_VC_COMPARE: {
3019 if (cmd.argument().empty()) {
3020 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "comparehistory"));
3024 string rev1 = cmd.getArg(0);
3028 if (!buffer->lyxvc().prepareFileRevision(rev1, f1))
3031 if (isStrInt(rev1) && convert<int>(rev1) <= 0) {
3032 f2 = buffer->absFileName();
3034 string rev2 = cmd.getArg(1);
3038 if (!buffer->lyxvc().prepareFileRevision(rev2, f2))
3042 LYXERR(Debug::LYXVC, "Launching comparison for fetched revisions:\n" <<
3043 f1 << "\n" << f2 << "\n" );
3044 string par = "compare run " + quoteName(f1) + " " + quoteName(f2);
3045 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, par));
3055 void GuiView::openChildDocument(string const & fname)
3057 LASSERT(documentBufferView(), return);
3058 Buffer & buffer = documentBufferView()->buffer();
3059 FileName const filename = support::makeAbsPath(fname, buffer.filePath());
3060 documentBufferView()->saveBookmark(false);
3062 if (theBufferList().exists(filename)) {
3063 child = theBufferList().getBuffer(filename);
3066 message(bformat(_("Opening child document %1$s..."),
3067 makeDisplayPath(filename.absFileName())));
3068 child = loadDocument(filename, false);
3070 // Set the parent name of the child document.
3071 // This makes insertion of citations and references in the child work,
3072 // when the target is in the parent or another child document.
3074 child->setParent(&buffer);
3078 bool GuiView::goToFileRow(string const & argument)
3082 size_t i = argument.find_last_of(' ');
3083 if (i != string::npos) {
3084 file_name = os::internal_path(trim(argument.substr(0, i)));
3085 istringstream is(argument.substr(i + 1));
3090 if (i == string::npos) {
3091 LYXERR0("Wrong argument: " << argument);
3095 string const abstmp = package().temp_dir().absFileName();
3096 string const realtmp = package().temp_dir().realPath();
3097 // We have to use os::path_prefix_is() here, instead of
3098 // simply prefixIs(), because the file name comes from
3099 // an external application and may need case adjustment.
3100 if (os::path_prefix_is(file_name, abstmp, os::CASE_ADJUSTED)
3101 || os::path_prefix_is(file_name, realtmp, os::CASE_ADJUSTED)) {
3102 // Needed by inverse dvi search. If it is a file
3103 // in tmpdir, call the apropriated function.
3104 // If tmpdir is a symlink, we may have the real
3105 // path passed back, so we correct for that.
3106 if (!prefixIs(file_name, abstmp))
3107 file_name = subst(file_name, realtmp, abstmp);
3108 buf = theBufferList().getBufferFromTmp(file_name);
3110 // Must replace extension of the file to be .lyx
3111 // and get full path
3112 FileName const s = fileSearch(string(),
3113 support::changeExtension(file_name, ".lyx"), "lyx");
3114 // Either change buffer or load the file
3115 if (theBufferList().exists(s))
3116 buf = theBufferList().getBuffer(s);
3117 else if (s.exists()) {
3118 buf = loadDocument(s);
3123 _("File does not exist: %1$s"),
3124 makeDisplayPath(file_name)));
3130 _("No buffer for file: %1$s."),
3131 makeDisplayPath(file_name))
3136 documentBufferView()->setCursorFromRow(row);
3142 Buffer::ExportStatus GuiView::GuiViewPrivate::runAndDestroy(const T& func, Buffer const * orig, Buffer * clone, string const & format)
3144 Buffer::ExportStatus const status = func(format);
3146 // the cloning operation will have produced a clone of the entire set of
3147 // documents, starting from the master. so we must delete those.
3148 Buffer * mbuf = const_cast<Buffer *>(clone->masterBuffer());
3150 busyBuffers.remove(orig);
3155 Buffer::ExportStatus GuiView::GuiViewPrivate::compileAndDestroy(Buffer const * orig, Buffer * clone, string const & format)
3157 Buffer::ExportStatus (Buffer::* mem_func)(std::string const &, bool) const = &Buffer::doExport;
3158 return runAndDestroy(lyx::bind(mem_func, clone, _1, true), orig, clone, format);
3162 Buffer::ExportStatus GuiView::GuiViewPrivate::exportAndDestroy(Buffer const * orig, Buffer * clone, string const & format)
3164 Buffer::ExportStatus (Buffer::* mem_func)(std::string const &, bool) const = &Buffer::doExport;
3165 return runAndDestroy(lyx::bind(mem_func, clone, _1, false), orig, clone, format);
3169 Buffer::ExportStatus GuiView::GuiViewPrivate::previewAndDestroy(Buffer const * orig, Buffer * clone, string const & format)
3171 Buffer::ExportStatus (Buffer::* mem_func)(std::string const &) const = &Buffer::preview;
3172 return runAndDestroy(lyx::bind(mem_func, clone, _1), orig, clone, format);
3176 bool GuiView::GuiViewPrivate::asyncBufferProcessing(
3177 string const & argument,
3178 Buffer const * used_buffer,
3179 docstring const & msg,
3180 Buffer::ExportStatus (*asyncFunc)(Buffer const *, Buffer *, string const &),
3181 Buffer::ExportStatus (Buffer::*syncFunc)(string const &, bool) const,
3182 Buffer::ExportStatus (Buffer::*previewFunc)(string const &) const)
3187 string format = argument;
3189 format = used_buffer->params().getDefaultOutputFormat();
3190 processing_format = format;
3191 #if EXPORT_in_THREAD
3193 progress_->clearMessages();
3196 GuiViewPrivate::busyBuffers.insert(used_buffer);
3197 Buffer * cloned_buffer = used_buffer->cloneFromMaster();
3198 if (!cloned_buffer) {
3199 Alert::error(_("Export Error"),
3200 _("Error cloning the Buffer."));
3203 QFuture<Buffer::ExportStatus> f = QtConcurrent::run(
3208 setPreviewFuture(f);
3209 last_export_format = used_buffer->params().bufferFormat();
3212 // We are asynchronous, so we don't know here anything about the success
3215 Buffer::ExportStatus status;
3217 // TODO check here if it breaks exporting with Qt < 4.4
3218 status = (used_buffer->*syncFunc)(format, true);
3219 } else if (previewFunc) {
3220 status = (used_buffer->*previewFunc)(format);
3223 handleExportStatus(gv_, status, format);
3225 return (status == Buffer::ExportSuccess
3226 || status == Buffer::PreviewSuccess);
3230 void GuiView::dispatchToBufferView(FuncRequest const & cmd, DispatchResult & dr)
3232 BufferView * bv = currentBufferView();
3233 LASSERT(bv, return);
3235 // Let the current BufferView dispatch its own actions.
3236 bv->dispatch(cmd, dr);
3237 if (dr.dispatched())
3240 // Try with the document BufferView dispatch if any.
3241 BufferView * doc_bv = documentBufferView();
3242 if (doc_bv && doc_bv != bv) {
3243 doc_bv->dispatch(cmd, dr);
3244 if (dr.dispatched())
3248 // Then let the current Cursor dispatch its own actions.
3249 bv->cursor().dispatch(cmd);
3251 // update completion. We do it here and not in
3252 // processKeySym to avoid another redraw just for a
3253 // changed inline completion
3254 if (cmd.origin() == FuncRequest::KEYBOARD) {
3255 if (cmd.action() == LFUN_SELF_INSERT
3256 || (cmd.action() == LFUN_ERT_INSERT && bv->cursor().inMathed()))
3257 updateCompletion(bv->cursor(), true, true);
3258 else if (cmd.action() == LFUN_CHAR_DELETE_BACKWARD)
3259 updateCompletion(bv->cursor(), false, true);
3261 updateCompletion(bv->cursor(), false, false);
3264 dr = bv->cursor().result();
3268 void GuiView::dispatch(FuncRequest const & cmd, DispatchResult & dr)
3270 BufferView * bv = currentBufferView();
3271 // By default we won't need any update.
3272 dr.screenUpdate(Update::None);
3273 // assume cmd will be dispatched
3274 dr.dispatched(true);
3276 Buffer * doc_buffer = documentBufferView()
3277 ? &(documentBufferView()->buffer()) : 0;
3279 if (cmd.origin() == FuncRequest::TOC) {
3280 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
3281 // FIXME: do we need to pass a DispatchResult object here?
3282 toc->doDispatch(bv->cursor(), cmd);
3286 string const argument = to_utf8(cmd.argument());
3288 switch(cmd.action()) {
3289 case LFUN_BUFFER_CHILD_OPEN:
3290 openChildDocument(to_utf8(cmd.argument()));
3293 case LFUN_BUFFER_IMPORT:
3294 importDocument(to_utf8(cmd.argument()));
3297 case LFUN_BUFFER_EXPORT: {
3300 // GCC only sees strfwd.h when building merged
3301 if (::lyx::operator==(cmd.argument(), "custom")) {
3302 dispatch(FuncRequest(LFUN_DIALOG_SHOW, "sendto"), dr);
3305 /* TODO/Review: Is it a problem to also export the children?
3306 See the update_unincluded flag */
3307 d.asyncBufferProcessing(argument,
3310 &GuiViewPrivate::exportAndDestroy,
3313 // TODO Inform user about success
3317 case LFUN_BUFFER_EXPORT_AS:
3318 LASSERT(doc_buffer, break);
3319 exportBufferAs(*doc_buffer);
3322 case LFUN_BUFFER_UPDATE: {
3323 d.asyncBufferProcessing(argument,
3326 &GuiViewPrivate::compileAndDestroy,
3331 case LFUN_BUFFER_VIEW: {
3332 d.asyncBufferProcessing(argument,
3334 _("Previewing ..."),
3335 &GuiViewPrivate::previewAndDestroy,
3340 case LFUN_MASTER_BUFFER_UPDATE: {
3341 d.asyncBufferProcessing(argument,
3342 (doc_buffer ? doc_buffer->masterBuffer() : 0),
3344 &GuiViewPrivate::compileAndDestroy,
3349 case LFUN_MASTER_BUFFER_VIEW: {
3350 d.asyncBufferProcessing(argument,
3351 (doc_buffer ? doc_buffer->masterBuffer() : 0),
3353 &GuiViewPrivate::previewAndDestroy,
3354 0, &Buffer::preview);
3357 case LFUN_BUFFER_SWITCH: {
3358 string const file_name = to_utf8(cmd.argument());
3359 if (!FileName::isAbsolute(file_name)) {
3361 dr.setMessage(_("Absolute filename expected."));
3365 Buffer * buffer = theBufferList().getBuffer(FileName(file_name));
3368 dr.setMessage(_("Document not loaded"));
3372 // Do we open or switch to the buffer in this view ?
3373 if (workArea(*buffer)
3374 || lyxrc.open_buffers_in_tabs || !documentBufferView()) {
3379 // Look for the buffer in other views
3380 QList<int> const ids = guiApp->viewIds();
3382 for (; i != ids.size(); ++i) {
3383 GuiView & gv = guiApp->view(ids[i]);
3384 if (gv.workArea(*buffer)) {
3385 gv.activateWindow();
3386 gv.setBuffer(buffer);
3391 // If necessary, open a new window as a last resort
3392 if (i == ids.size()) {
3393 lyx::dispatch(FuncRequest(LFUN_WINDOW_NEW));
3399 case LFUN_BUFFER_NEXT:
3400 gotoNextOrPreviousBuffer(NEXTBUFFER);
3403 case LFUN_BUFFER_PREVIOUS:
3404 gotoNextOrPreviousBuffer(PREVBUFFER);
3407 case LFUN_COMMAND_EXECUTE: {
3408 bool const show_it = cmd.argument() != "off";
3409 // FIXME: this is a hack, "minibuffer" should not be
3411 if (GuiToolbar * t = toolbar("minibuffer")) {
3412 t->setVisible(show_it);
3413 if (show_it && t->commandBuffer())
3414 t->commandBuffer()->setFocus();
3418 case LFUN_DROP_LAYOUTS_CHOICE:
3419 d.layout_->showPopup();
3422 case LFUN_MENU_OPEN:
3423 if (QMenu * menu = guiApp->menus().menu(toqstr(cmd.argument()), *this))
3424 menu->exec(QCursor::pos());
3427 case LFUN_FILE_INSERT:
3428 insertLyXFile(cmd.argument());
3431 case LFUN_FILE_INSERT_PLAINTEXT:
3432 case LFUN_FILE_INSERT_PLAINTEXT_PARA: {
3433 bool const as_paragraph = (cmd.action() == LFUN_FILE_INSERT_PLAINTEXT_PARA);
3434 string const fname = to_utf8(cmd.argument());
3435 if (!fname.empty() && !FileName::isAbsolute(fname)) {
3436 dr.setMessage(_("Absolute filename expected."));
3440 FileName filename(fname);
3441 if (fname.empty()) {
3442 FileDialog dlg(qt_("Select file to insert"), (as_paragraph ?
3443 LFUN_FILE_INSERT_PLAINTEXT_PARA : LFUN_FILE_INSERT_PLAINTEXT));
3445 FileDialog::Result result = dlg.open(toqstr(bv->buffer().filePath()),
3446 QStringList(qt_("All Files (*)")));
3448 if (result.first == FileDialog::Later || result.second.isEmpty()) {
3449 dr.setMessage(_("Canceled."));
3453 filename.set(fromqstr(result.second));
3457 FuncRequest const new_cmd(cmd, filename.absoluteFilePath());
3458 bv->dispatch(new_cmd, dr);
3463 case LFUN_BUFFER_RELOAD: {
3464 LASSERT(doc_buffer, break);
3467 if (!doc_buffer->isClean()) {
3468 docstring const file =
3469 makeDisplayPath(doc_buffer->absFileName(), 20);
3470 docstring text = bformat(_("Any changes will be lost. "
3471 "Are you sure you want to revert to the saved version "
3472 "of the document %1$s?"), file);
3473 ret = Alert::prompt(_("Revert to saved document?"),
3474 text, 1, 1, _("&Revert"), _("&Cancel"));
3478 doc_buffer->markClean();
3479 reloadBuffer(*doc_buffer);
3480 dr.forceBufferUpdate();
3485 case LFUN_BUFFER_WRITE:
3486 LASSERT(doc_buffer, break);
3487 saveBuffer(*doc_buffer);
3490 case LFUN_BUFFER_WRITE_AS:
3491 LASSERT(doc_buffer, break);
3492 renameBuffer(*doc_buffer, cmd.argument());
3495 case LFUN_BUFFER_WRITE_ALL: {
3496 Buffer * first = theBufferList().first();
3499 message(_("Saving all documents..."));
3500 // We cannot use a for loop as the buffer list cycles.
3503 if (!b->isClean()) {
3505 LYXERR(Debug::ACTION, "Saved " << b->absFileName());
3507 b = theBufferList().next(b);
3508 } while (b != first);
3509 dr.setMessage(_("All documents saved."));
3513 case LFUN_BUFFER_CLOSE:
3517 case LFUN_BUFFER_CLOSE_ALL:
3521 case LFUN_TOOLBAR_TOGGLE: {
3522 string const name = cmd.getArg(0);
3523 if (GuiToolbar * t = toolbar(name))
3528 case LFUN_DIALOG_UPDATE: {
3529 string const name = to_utf8(cmd.argument());
3530 if (name == "prefs" || name == "document")
3531 updateDialog(name, string());
3532 else if (name == "paragraph")
3533 lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
3534 else if (currentBufferView()) {
3535 Inset * inset = currentBufferView()->editedInset(name);
3536 // Can only update a dialog connected to an existing inset
3538 // FIXME: get rid of this indirection; GuiView ask the inset
3539 // if he is kind enough to update itself...
3540 FuncRequest fr(LFUN_INSET_DIALOG_UPDATE, cmd.argument());
3541 //FIXME: pass DispatchResult here?
3542 inset->dispatch(currentBufferView()->cursor(), fr);
3548 case LFUN_DIALOG_TOGGLE: {
3549 FuncCode const func_code = isDialogVisible(cmd.getArg(0))
3550 ? LFUN_DIALOG_HIDE : LFUN_DIALOG_SHOW;
3551 dispatch(FuncRequest(func_code, cmd.argument()), dr);
3555 case LFUN_DIALOG_DISCONNECT_INSET:
3556 disconnectDialog(to_utf8(cmd.argument()));
3559 case LFUN_DIALOG_HIDE: {
3560 guiApp->hideDialogs(to_utf8(cmd.argument()), 0);
3564 case LFUN_DIALOG_SHOW: {
3565 string const name = cmd.getArg(0);
3566 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
3568 if (name == "character") {
3569 data = freefont2string();
3571 showDialog("character", data);
3572 } else if (name == "latexlog") {
3573 Buffer::LogType type;
3574 string const logfile = doc_buffer->logName(&type);
3576 case Buffer::latexlog:
3579 case Buffer::buildlog:
3583 data += Lexer::quoteString(logfile);
3584 showDialog("log", data);
3585 } else if (name == "vclog") {
3586 string const data = "vc " +
3587 Lexer::quoteString(doc_buffer->lyxvc().getLogFile());
3588 showDialog("log", data);
3589 } else if (name == "symbols") {
3590 data = bv->cursor().getEncoding()->name();
3592 showDialog("symbols", data);
3594 } else if (name == "prefs" && isFullScreen()) {
3595 lfunUiToggle("fullscreen");
3596 showDialog("prefs", data);
3598 showDialog(name, data);
3603 dr.setMessage(cmd.argument());
3606 case LFUN_UI_TOGGLE: {
3607 string arg = cmd.getArg(0);
3608 if (!lfunUiToggle(arg)) {
3609 docstring const msg = "ui-toggle " + _("%1$s unknown command!");
3610 dr.setMessage(bformat(msg, from_utf8(arg)));
3612 // Make sure the keyboard focus stays in the work area.
3617 case LFUN_VIEW_SPLIT: {
3618 LASSERT(doc_buffer, break);
3619 string const orientation = cmd.getArg(0);
3620 d.splitter_->setOrientation(orientation == "vertical"
3621 ? Qt::Vertical : Qt::Horizontal);
3622 TabWorkArea * twa = addTabWorkArea();
3623 GuiWorkArea * wa = twa->addWorkArea(*doc_buffer, *this);
3624 setCurrentWorkArea(wa);
3627 case LFUN_TAB_GROUP_CLOSE:
3628 if (TabWorkArea * twa = d.currentTabWorkArea()) {
3629 closeTabWorkArea(twa);
3630 d.current_work_area_ = 0;
3631 twa = d.currentTabWorkArea();
3632 // Switch to the next GuiWorkArea in the found TabWorkArea.
3634 // Make sure the work area is up to date.
3635 setCurrentWorkArea(twa->currentWorkArea());
3637 setCurrentWorkArea(0);
3642 case LFUN_VIEW_CLOSE:
3643 if (TabWorkArea * twa = d.currentTabWorkArea()) {
3644 closeWorkArea(twa->currentWorkArea());
3645 d.current_work_area_ = 0;
3646 twa = d.currentTabWorkArea();
3647 // Switch to the next GuiWorkArea in the found TabWorkArea.
3649 // Make sure the work area is up to date.
3650 setCurrentWorkArea(twa->currentWorkArea());
3652 setCurrentWorkArea(0);
3657 case LFUN_COMPLETION_INLINE:
3658 if (d.current_work_area_)
3659 d.current_work_area_->completer().showInline();
3662 case LFUN_COMPLETION_POPUP:
3663 if (d.current_work_area_)
3664 d.current_work_area_->completer().showPopup();
3668 case LFUN_COMPLETION_COMPLETE:
3669 if (d.current_work_area_)
3670 d.current_work_area_->completer().tab();
3673 case LFUN_COMPLETION_CANCEL:
3674 if (d.current_work_area_) {
3675 if (d.current_work_area_->completer().popupVisible())
3676 d.current_work_area_->completer().hidePopup();
3678 d.current_work_area_->completer().hideInline();
3682 case LFUN_COMPLETION_ACCEPT:
3683 if (d.current_work_area_)
3684 d.current_work_area_->completer().activate();
3687 case LFUN_BUFFER_ZOOM_IN:
3688 case LFUN_BUFFER_ZOOM_OUT:
3689 if (cmd.argument().empty()) {
3690 if (cmd.action() == LFUN_BUFFER_ZOOM_IN)
3695 lyxrc.zoom += convert<int>(cmd.argument());
3697 if (lyxrc.zoom < 10)
3700 // The global QPixmapCache is used in GuiPainter to cache text
3701 // painting so we must reset it.
3702 QPixmapCache::clear();
3703 guiApp->fontLoader().update();
3704 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
3707 case LFUN_VC_REGISTER:
3708 case LFUN_VC_RENAME:
3710 case LFUN_VC_CHECK_IN:
3711 case LFUN_VC_CHECK_OUT:
3712 case LFUN_VC_REPO_UPDATE:
3713 case LFUN_VC_LOCKING_TOGGLE:
3714 case LFUN_VC_REVERT:
3715 case LFUN_VC_UNDO_LAST:
3716 case LFUN_VC_COMMAND:
3717 case LFUN_VC_COMPARE:
3718 dispatchVC(cmd, dr);
3721 case LFUN_SERVER_GOTO_FILE_ROW:
3722 goToFileRow(to_utf8(cmd.argument()));
3725 case LFUN_FORWARD_SEARCH: {
3726 Buffer const * doc_master = doc_buffer->masterBuffer();
3727 FileName const path(doc_master->temppath());
3728 string const texname = doc_master->isChild(doc_buffer)
3729 ? DocFileName(changeExtension(
3730 doc_buffer->absFileName(),
3731 "tex")).mangledFileName()
3732 : doc_buffer->latexName();
3733 string const fulltexname =
3734 support::makeAbsPath(texname, doc_master->temppath()).absFileName();
3735 string const mastername =
3736 removeExtension(doc_master->latexName());
3737 FileName const dviname(addName(path.absFileName(),
3738 addExtension(mastername, "dvi")));
3739 FileName const pdfname(addName(path.absFileName(),
3740 addExtension(mastername, "pdf")));
3741 bool const have_dvi = dviname.exists();
3742 bool const have_pdf = pdfname.exists();
3743 if (!have_dvi && !have_pdf) {
3744 dr.setMessage(_("Please, preview the document first."));
3747 string outname = dviname.onlyFileName();
3748 string command = lyxrc.forward_search_dvi;
3749 if (!have_dvi || (have_pdf &&
3750 pdfname.lastModified() > dviname.lastModified())) {
3751 outname = pdfname.onlyFileName();
3752 command = lyxrc.forward_search_pdf;
3755 DocIterator tmpcur = bv->cursor();
3757 while (tmpcur.inMathed())
3759 int row = tmpcur.inMathed() ? 0 : doc_buffer->texrow().getRowFromIdPos(
3760 tmpcur.paragraph().id(), tmpcur.pos());
3761 LYXERR(Debug::ACTION, "Forward search: row:" << row
3762 << " id:" << tmpcur.paragraph().id());
3763 if (!row || command.empty()) {
3764 dr.setMessage(_("Couldn't proceed."));
3767 string texrow = convert<string>(row);
3769 command = subst(command, "$$n", texrow);
3770 command = subst(command, "$$f", fulltexname);
3771 command = subst(command, "$$t", texname);
3772 command = subst(command, "$$o", outname);
3774 PathChanger p(path);
3776 one.startscript(Systemcall::DontWait, command);
3780 case LFUN_SPELLING_CONTINUOUSLY:
3781 lyxrc.spellcheck_continuously = !lyxrc.spellcheck_continuously;
3782 dr.screenUpdate(Update::Force | Update::FitCursor);
3786 // The LFUN must be for one of BufferView, Buffer or Cursor;
3788 dispatchToBufferView(cmd, dr);
3792 // Part of automatic menu appearance feature.
3793 if (isFullScreen()) {
3794 if (menuBar()->isVisible() && lyxrc.full_screen_menubar)
3796 if (statusBar()->isVisible())
3797 statusBar()->hide();
3802 bool GuiView::lfunUiToggle(string const & ui_component)
3804 if (ui_component == "scrollbar") {
3805 // hide() is of no help
3806 if (d.current_work_area_->verticalScrollBarPolicy() ==
3807 Qt::ScrollBarAlwaysOff)
3809 d.current_work_area_->setVerticalScrollBarPolicy(
3810 Qt::ScrollBarAsNeeded);
3812 d.current_work_area_->setVerticalScrollBarPolicy(
3813 Qt::ScrollBarAlwaysOff);
3814 } else if (ui_component == "statusbar") {
3815 statusBar()->setVisible(!statusBar()->isVisible());
3816 } else if (ui_component == "menubar") {
3817 menuBar()->setVisible(!menuBar()->isVisible());
3819 if (ui_component == "frame") {
3821 getContentsMargins(&l, &t, &r, &b);
3822 //are the frames in default state?
3823 d.current_work_area_->setFrameStyle(QFrame::NoFrame);
3825 setContentsMargins(-2, -2, -2, -2);
3827 setContentsMargins(0, 0, 0, 0);
3830 if (ui_component == "fullscreen") {
3838 void GuiView::toggleFullScreen()
3840 if (isFullScreen()) {
3841 for (int i = 0; i != d.splitter_->count(); ++i)
3842 d.tabWorkArea(i)->setFullScreen(false);
3843 setContentsMargins(0, 0, 0, 0);
3844 setWindowState(windowState() ^ Qt::WindowFullScreen);
3847 statusBar()->show();
3850 hideDialogs("prefs", 0);
3851 for (int i = 0; i != d.splitter_->count(); ++i)
3852 d.tabWorkArea(i)->setFullScreen(true);
3853 setContentsMargins(-2, -2, -2, -2);
3855 setWindowState(windowState() ^ Qt::WindowFullScreen);
3856 statusBar()->hide();
3857 if (lyxrc.full_screen_menubar)
3859 if (lyxrc.full_screen_toolbars) {
3860 ToolbarMap::iterator end = d.toolbars_.end();
3861 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
3866 // give dialogs like the TOC a chance to adapt
3871 Buffer const * GuiView::updateInset(Inset const * inset)
3876 Buffer const * inset_buffer = &(inset->buffer());
3878 for (int i = 0; i != d.splitter_->count(); ++i) {
3879 GuiWorkArea * wa = d.tabWorkArea(i)->currentWorkArea();
3882 Buffer const * buffer = &(wa->bufferView().buffer());
3883 if (inset_buffer == buffer)
3884 wa->scheduleRedraw();
3886 return inset_buffer;
3890 void GuiView::restartCursor()
3892 /* When we move around, or type, it's nice to be able to see
3893 * the cursor immediately after the keypress.
3895 if (d.current_work_area_)
3896 d.current_work_area_->startBlinkingCursor();
3898 // Take this occasion to update the other GUI elements.
3904 void GuiView::updateCompletion(Cursor & cur, bool start, bool keep)
3906 if (d.current_work_area_)
3907 d.current_work_area_->completer().updateVisibility(cur, start, keep);
3912 // This list should be kept in sync with the list of insets in
3913 // src/insets/Inset.cpp. I.e., if a dialog goes with an inset, the
3914 // dialog should have the same name as the inset.
3915 // Changes should be also recorded in LFUN_DIALOG_SHOW doxygen
3916 // docs in LyXAction.cpp.
3918 char const * const dialognames[] = {
3920 "aboutlyx", "bibitem", "bibtex", "box", "branch", "changes", "character",
3921 "citation", "compare", "comparehistory", "document", "errorlist", "ert",
3922 "external", "file", "findreplace", "findreplaceadv", "float", "graphics",
3923 "href", "include", "index", "index_print", "info", "listings", "label", "line",
3924 "log", "mathdelimiter", "mathmatrix", "mathspace", "nomenclature",
3925 "nomencl_print", "note", "paragraph", "phantom", "prefs", "print", "ref",
3926 "sendto", "space", "spellchecker", "symbols", "tabular", "tabularcreate",
3927 "thesaurus", "texinfo", "toc", "view-source", "vspace", "wrap", "progress"};
3929 char const * const * const end_dialognames =
3930 dialognames + (sizeof(dialognames) / sizeof(char *));
3934 cmpCStr(char const * name) : name_(name) {}
3935 bool operator()(char const * other) {
3936 return strcmp(other, name_) == 0;
3943 bool isValidName(string const & name)
3945 return find_if(dialognames, end_dialognames,
3946 cmpCStr(name.c_str())) != end_dialognames;
3952 void GuiView::resetDialogs()
3954 // Make sure that no LFUN uses any GuiView.
3955 guiApp->setCurrentView(0);
3959 constructToolbars();
3960 guiApp->menus().fillMenuBar(menuBar(), this, false);
3961 d.layout_->updateContents(true);
3962 // Now update controls with current buffer.
3963 guiApp->setCurrentView(this);
3969 Dialog * GuiView::findOrBuild(string const & name, bool hide_it)
3971 if (!isValidName(name))
3974 map<string, DialogPtr>::iterator it = d.dialogs_.find(name);
3976 if (it != d.dialogs_.end()) {
3978 it->second->hideView();
3979 return it->second.get();
3982 Dialog * dialog = build(name);
3983 d.dialogs_[name].reset(dialog);
3984 if (lyxrc.allow_geometry_session)
3985 dialog->restoreSession();
3992 void GuiView::showDialog(string const & name, string const & data,
3995 triggerShowDialog(toqstr(name), toqstr(data), inset);
3999 void GuiView::doShowDialog(QString const & qname, QString const & qdata,
4005 const string name = fromqstr(qname);
4006 const string data = fromqstr(qdata);
4010 Dialog * dialog = findOrBuild(name, false);
4012 bool const visible = dialog->isVisibleView();
4013 dialog->showData(data);
4014 if (inset && currentBufferView())
4015 currentBufferView()->editInset(name, inset);
4016 // We only set the focus to the new dialog if it was not yet
4017 // visible in order not to change the existing previous behaviour
4019 // activateWindow is needed for floating dockviews
4020 dialog->asQWidget()->raise();
4021 dialog->asQWidget()->activateWindow();
4022 dialog->asQWidget()->setFocus();
4026 catch (ExceptionMessage const & ex) {
4034 bool GuiView::isDialogVisible(string const & name) const
4036 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
4037 if (it == d.dialogs_.end())
4039 return it->second.get()->isVisibleView() && !it->second.get()->isClosing();
4043 void GuiView::hideDialog(string const & name, Inset * inset)
4045 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
4046 if (it == d.dialogs_.end())
4050 if (!currentBufferView())
4052 if (inset != currentBufferView()->editedInset(name))
4056 Dialog * const dialog = it->second.get();
4057 if (dialog->isVisibleView())
4059 if (currentBufferView())
4060 currentBufferView()->editInset(name, 0);
4064 void GuiView::disconnectDialog(string const & name)
4066 if (!isValidName(name))
4068 if (currentBufferView())
4069 currentBufferView()->editInset(name, 0);
4073 void GuiView::hideAll() const
4075 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
4076 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
4078 for(; it != end; ++it)
4079 it->second->hideView();
4083 void GuiView::updateDialogs()
4085 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
4086 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
4088 for(; it != end; ++it) {
4089 Dialog * dialog = it->second.get();
4091 if (dialog->needBufferOpen() && !documentBufferView())
4092 hideDialog(fromqstr(dialog->name()), 0);
4093 else if (dialog->isVisibleView())
4094 dialog->checkStatus();
4101 Dialog * createDialog(GuiView & lv, string const & name);
4103 // will be replaced by a proper factory...
4104 Dialog * createGuiAbout(GuiView & lv);
4105 Dialog * createGuiBibtex(GuiView & lv);
4106 Dialog * createGuiChanges(GuiView & lv);
4107 Dialog * createGuiCharacter(GuiView & lv);
4108 Dialog * createGuiCitation(GuiView & lv);
4109 Dialog * createGuiCompare(GuiView & lv);
4110 Dialog * createGuiCompareHistory(GuiView & lv);
4111 Dialog * createGuiDelimiter(GuiView & lv);
4112 Dialog * createGuiDocument(GuiView & lv);
4113 Dialog * createGuiErrorList(GuiView & lv);
4114 Dialog * createGuiExternal(GuiView & lv);
4115 Dialog * createGuiGraphics(GuiView & lv);
4116 Dialog * createGuiInclude(GuiView & lv);
4117 Dialog * createGuiIndex(GuiView & lv);
4118 Dialog * createGuiListings(GuiView & lv);
4119 Dialog * createGuiLog(GuiView & lv);
4120 Dialog * createGuiMathMatrix(GuiView & lv);
4121 Dialog * createGuiNote(GuiView & lv);
4122 Dialog * createGuiParagraph(GuiView & lv);
4123 Dialog * createGuiPhantom(GuiView & lv);
4124 Dialog * createGuiPreferences(GuiView & lv);
4125 Dialog * createGuiPrint(GuiView & lv);
4126 Dialog * createGuiPrintindex(GuiView & lv);
4127 Dialog * createGuiRef(GuiView & lv);
4128 Dialog * createGuiSearch(GuiView & lv);
4129 Dialog * createGuiSearchAdv(GuiView & lv);
4130 Dialog * createGuiSendTo(GuiView & lv);
4131 Dialog * createGuiShowFile(GuiView & lv);
4132 Dialog * createGuiSpellchecker(GuiView & lv);
4133 Dialog * createGuiSymbols(GuiView & lv);
4134 Dialog * createGuiTabularCreate(GuiView & lv);
4135 Dialog * createGuiTexInfo(GuiView & lv);
4136 Dialog * createGuiToc(GuiView & lv);
4137 Dialog * createGuiThesaurus(GuiView & lv);
4138 Dialog * createGuiViewSource(GuiView & lv);
4139 Dialog * createGuiWrap(GuiView & lv);
4140 Dialog * createGuiProgressView(GuiView & lv);
4144 Dialog * GuiView::build(string const & name)
4146 LASSERT(isValidName(name), return 0);
4148 Dialog * dialog = createDialog(*this, name);
4152 if (name == "aboutlyx")
4153 return createGuiAbout(*this);
4154 if (name == "bibtex")
4155 return createGuiBibtex(*this);
4156 if (name == "changes")
4157 return createGuiChanges(*this);
4158 if (name == "character")
4159 return createGuiCharacter(*this);
4160 if (name == "citation")
4161 return createGuiCitation(*this);
4162 if (name == "compare")
4163 return createGuiCompare(*this);
4164 if (name == "comparehistory")
4165 return createGuiCompareHistory(*this);
4166 if (name == "document")
4167 return createGuiDocument(*this);
4168 if (name == "errorlist")
4169 return createGuiErrorList(*this);
4170 if (name == "external")
4171 return createGuiExternal(*this);
4173 return createGuiShowFile(*this);
4174 if (name == "findreplace")
4175 return createGuiSearch(*this);
4176 if (name == "findreplaceadv")
4177 return createGuiSearchAdv(*this);
4178 if (name == "graphics")
4179 return createGuiGraphics(*this);
4180 if (name == "include")
4181 return createGuiInclude(*this);
4182 if (name == "index")
4183 return createGuiIndex(*this);
4184 if (name == "index_print")
4185 return createGuiPrintindex(*this);
4186 if (name == "listings")
4187 return createGuiListings(*this);
4189 return createGuiLog(*this);
4190 if (name == "mathdelimiter")
4191 return createGuiDelimiter(*this);
4192 if (name == "mathmatrix")
4193 return createGuiMathMatrix(*this);
4195 return createGuiNote(*this);
4196 if (name == "paragraph")
4197 return createGuiParagraph(*this);
4198 if (name == "phantom")
4199 return createGuiPhantom(*this);
4200 if (name == "prefs")
4201 return createGuiPreferences(*this);
4202 if (name == "print")
4203 return createGuiPrint(*this);
4205 return createGuiRef(*this);
4206 if (name == "sendto")
4207 return createGuiSendTo(*this);
4208 if (name == "spellchecker")
4209 return createGuiSpellchecker(*this);
4210 if (name == "symbols")
4211 return createGuiSymbols(*this);
4212 if (name == "tabularcreate")
4213 return createGuiTabularCreate(*this);
4214 if (name == "texinfo")
4215 return createGuiTexInfo(*this);
4216 if (name == "thesaurus")
4217 return createGuiThesaurus(*this);
4219 return createGuiToc(*this);
4220 if (name == "view-source")
4221 return createGuiViewSource(*this);
4223 return createGuiWrap(*this);
4224 if (name == "progress")
4225 return createGuiProgressView(*this);
4231 } // namespace frontend
4234 #include "moc_GuiView.cpp"