3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Lars Gullik Bjønnes
8 * \author Abdelrazak Younes
11 * Full author contact details are available in file CREDITS.
19 #include "DispatchResult.h"
20 #include "FileDialog.h"
21 #include "FontLoader.h"
22 #include "GuiApplication.h"
23 #include "GuiCommandBuffer.h"
24 #include "GuiCompleter.h"
25 #include "GuiKeySymbol.h"
27 #include "GuiToolbar.h"
28 #include "GuiWorkArea.h"
29 #include "GuiProgress.h"
30 #include "LayoutBox.h"
34 #include "qt_helpers.h"
36 #include "frontends/alert.h"
37 #include "frontends/KeySymbol.h"
39 #include "buffer_funcs.h"
41 #include "BufferList.h"
42 #include "BufferParams.h"
43 #include "BufferView.h"
45 #include "Converter.h"
47 #include "CutAndPaste.h"
49 #include "ErrorList.h"
51 #include "FuncStatus.h"
52 #include "FuncRequest.h"
56 #include "LyXAction.h"
60 #include "Paragraph.h"
61 #include "SpellChecker.h"
64 #include "TextClass.h"
69 #include "support/convert.h"
70 #include "support/debug.h"
71 #include "support/ExceptionMessage.h"
72 #include "support/FileName.h"
73 #include "support/filetools.h"
74 #include "support/gettext.h"
75 #include "support/filetools.h"
76 #include "support/ForkedCalls.h"
77 #include "support/lassert.h"
78 #include "support/lstrings.h"
79 #include "support/os.h"
80 #include "support/Package.h"
81 #include "support/PathChanger.h"
82 #include "support/Systemcall.h"
83 #include "support/Timeout.h"
84 #include "support/ProgressInterface.h"
87 #include <QApplication>
88 #include <QCloseEvent>
90 #include <QDesktopWidget>
91 #include <QDragEnterEvent>
94 #include <QFutureWatcher>
103 #include <QPixmapCache>
105 #include <QPushButton>
106 #include <QScrollBar>
108 #include <QShowEvent>
110 #include <QStackedWidget>
111 #include <QStatusBar>
112 #include <QtConcurrentRun>
120 #define EXPORT_in_THREAD 1
123 #include "support/bind.h"
127 #ifdef HAVE_SYS_TIME_H
128 # include <sys/time.h>
136 using namespace lyx::support;
140 using support::addExtension;
141 using support::changeExtension;
142 using support::removeExtension;
148 class BackgroundWidget : public QWidget
153 LYXERR(Debug::GUI, "show banner: " << lyxrc.show_banner);
154 if (!lyxrc.show_banner)
156 /// The text to be written on top of the pixmap
157 QString const text = lyx_version ?
158 qt_("version ") + lyx_version : qt_("unknown version");
159 splash_ = getPixmap("images/", "banner", "png");
161 QPainter pain(&splash_);
162 pain.setPen(QColor(0, 0, 0));
164 // The font used to display the version info
165 font.setStyleHint(QFont::SansSerif);
166 font.setWeight(QFont::Bold);
167 font.setPointSize(int(toqstr(lyxrc.font_sizes[FONT_SIZE_LARGE]).toDouble()));
169 pain.drawText(190, 225, text);
170 setFocusPolicy(Qt::StrongFocus);
173 void paintEvent(QPaintEvent *)
175 int x = (width() - splash_.width()) / 2;
176 int y = (height() - splash_.height()) / 2;
178 pain.drawPixmap(x, y, splash_);
181 void keyPressEvent(QKeyEvent * ev)
184 setKeySymbol(&sym, ev);
186 guiApp->processKeySym(sym, q_key_state(ev->modifiers()));
198 /// Toolbar store providing access to individual toolbars by name.
199 typedef map<string, GuiToolbar *> ToolbarMap;
201 typedef shared_ptr<Dialog> DialogPtr;
206 struct GuiView::GuiViewPrivate
208 GuiViewPrivate(GuiView * gv)
209 : gv_(gv), current_work_area_(0), current_main_work_area_(0),
210 layout_(0), autosave_timeout_(5000),
213 // hardcode here the platform specific icon size
214 smallIconSize = 16; // scaling problems
215 normalIconSize = 20; // ok, default if iconsize.png is missing
216 bigIconSize = 26; // better for some math icons
218 // if it exists, use width of iconsize.png as normal size
219 QString const dir = toqstr(addPath("images", lyxrc.icon_set));
220 FileName const fn = lyx::libFileSearch(dir, "iconsize.png");
222 QImage image(toqstr(fn.absFileName()));
223 if (image.width() < int(smallIconSize))
224 normalIconSize = smallIconSize;
225 else if (image.width() > int(bigIconSize))
226 normalIconSize = bigIconSize;
228 normalIconSize = image.width();
231 splitter_ = new QSplitter;
232 bg_widget_ = new BackgroundWidget;
233 stack_widget_ = new QStackedWidget;
234 stack_widget_->addWidget(bg_widget_);
235 stack_widget_->addWidget(splitter_);
238 // TODO cleanup, remove the singleton, handle multiple Windows?
239 progress_ = ProgressInterface::instance();
240 if (!dynamic_cast<GuiProgress*>(progress_)) {
241 progress_ = new GuiProgress; // TODO who deletes it
242 ProgressInterface::setInstance(progress_);
245 dynamic_cast<GuiProgress*>(progress_),
246 SIGNAL(updateStatusBarMessage(QString const&)),
247 gv, SLOT(updateStatusBarMessage(QString const&)));
249 dynamic_cast<GuiProgress*>(progress_),
250 SIGNAL(clearMessageText()),
251 gv, SLOT(clearMessageText()));
258 delete stack_widget_;
261 QMenu * toolBarPopup(GuiView * parent)
263 // FIXME: translation
264 QMenu * menu = new QMenu(parent);
265 QActionGroup * iconSizeGroup = new QActionGroup(parent);
267 QAction * smallIcons = new QAction(iconSizeGroup);
268 smallIcons->setText(qt_("Small-sized icons"));
269 smallIcons->setCheckable(true);
270 QObject::connect(smallIcons, SIGNAL(triggered()),
271 parent, SLOT(smallSizedIcons()));
272 menu->addAction(smallIcons);
274 QAction * normalIcons = new QAction(iconSizeGroup);
275 normalIcons->setText(qt_("Normal-sized icons"));
276 normalIcons->setCheckable(true);
277 QObject::connect(normalIcons, SIGNAL(triggered()),
278 parent, SLOT(normalSizedIcons()));
279 menu->addAction(normalIcons);
281 QAction * bigIcons = new QAction(iconSizeGroup);
282 bigIcons->setText(qt_("Big-sized icons"));
283 bigIcons->setCheckable(true);
284 QObject::connect(bigIcons, SIGNAL(triggered()),
285 parent, SLOT(bigSizedIcons()));
286 menu->addAction(bigIcons);
288 unsigned int cur = parent->iconSize().width();
289 if ( cur == parent->d.smallIconSize)
290 smallIcons->setChecked(true);
291 else if (cur == parent->d.normalIconSize)
292 normalIcons->setChecked(true);
293 else if (cur == parent->d.bigIconSize)
294 bigIcons->setChecked(true);
301 stack_widget_->setCurrentWidget(bg_widget_);
302 bg_widget_->setUpdatesEnabled(true);
303 bg_widget_->setFocus();
306 int tabWorkAreaCount()
308 return splitter_->count();
311 TabWorkArea * tabWorkArea(int i)
313 return dynamic_cast<TabWorkArea *>(splitter_->widget(i));
316 TabWorkArea * currentTabWorkArea()
318 int areas = tabWorkAreaCount();
320 // The first TabWorkArea is always the first one, if any.
321 return tabWorkArea(0);
323 for (int i = 0; i != areas; ++i) {
324 TabWorkArea * twa = tabWorkArea(i);
325 if (current_main_work_area_ == twa->currentWorkArea())
329 // None has the focus so we just take the first one.
330 return tabWorkArea(0);
333 int countWorkAreasOf(Buffer & buf)
335 int areas = tabWorkAreaCount();
337 for (int i = 0; i != areas; ++i) {
338 TabWorkArea * twa = tabWorkArea(i);
339 if (twa->workArea(buf))
345 void setPreviewFuture(QFuture<Buffer::ExportStatus> const & f)
347 if (processing_thread_watcher_.isRunning()) {
348 // we prefer to cancel this preview in order to keep a snappy
352 processing_thread_watcher_.setFuture(f);
357 GuiWorkArea * current_work_area_;
358 GuiWorkArea * current_main_work_area_;
359 QSplitter * splitter_;
360 QStackedWidget * stack_widget_;
361 BackgroundWidget * bg_widget_;
363 ToolbarMap toolbars_;
364 ProgressInterface* progress_;
365 /// The main layout box.
367 * \warning Don't Delete! The layout box is actually owned by
368 * whichever toolbar contains it. All the GuiView class needs is a
369 * means of accessing it.
371 * FIXME: replace that with a proper model so that we are not limited
372 * to only one dialog.
377 map<string, DialogPtr> dialogs_;
379 unsigned int smallIconSize;
380 unsigned int normalIconSize;
381 unsigned int bigIconSize;
383 QTimer statusbar_timer_;
384 /// auto-saving of buffers
385 Timeout autosave_timeout_;
386 /// flag against a race condition due to multiclicks, see bug #1119
390 TocModels toc_models_;
393 QFutureWatcher<docstring> autosave_watcher_;
394 QFutureWatcher<Buffer::ExportStatus> processing_thread_watcher_;
396 string last_export_format;
397 string processing_format;
399 static QSet<Buffer const *> busyBuffers;
400 static Buffer::ExportStatus previewAndDestroy(Buffer const * orig, Buffer * buffer, string const & format);
401 static Buffer::ExportStatus exportAndDestroy(Buffer const * orig, Buffer * buffer, string const & format);
402 static Buffer::ExportStatus compileAndDestroy(Buffer const * orig, Buffer * buffer, string const & format);
403 static docstring autosaveAndDestroy(Buffer const * orig, Buffer * buffer);
406 static Buffer::ExportStatus runAndDestroy(const T& func, Buffer const * orig, Buffer * buffer, string const & format);
408 // TODO syncFunc/previewFunc: use bind
409 bool asyncBufferProcessing(string const & argument,
410 Buffer const * used_buffer,
411 docstring const & msg,
412 Buffer::ExportStatus (*asyncFunc)(Buffer const *, Buffer *, string const &),
413 Buffer::ExportStatus (Buffer::*syncFunc)(string const &, bool) const,
414 Buffer::ExportStatus (Buffer::*previewFunc)(string const &) const);
416 QVector<GuiWorkArea*> guiWorkAreas();
419 QSet<Buffer const *> GuiView::GuiViewPrivate::busyBuffers;
422 GuiView::GuiView(int id)
423 : d(*new GuiViewPrivate(this)), id_(id), closing_(false), busy_(0)
425 // GuiToolbars *must* be initialised before the menu bar.
426 normalSizedIcons(); // at least on Mac the default is 32 otherwise, which is huge
429 // set ourself as the current view. This is needed for the menu bar
430 // filling, at least for the static special menu item on Mac. Otherwise
431 // they are greyed out.
432 guiApp->setCurrentView(this);
434 // Fill up the menu bar.
435 guiApp->menus().fillMenuBar(menuBar(), this, true);
437 setCentralWidget(d.stack_widget_);
439 // Start autosave timer
440 if (lyxrc.autosave) {
441 d.autosave_timeout_.timeout.connect(bind(&GuiView::autoSave, this));
442 d.autosave_timeout_.setTimeout(lyxrc.autosave * 1000);
443 d.autosave_timeout_.start();
445 connect(&d.statusbar_timer_, SIGNAL(timeout()),
446 this, SLOT(clearMessage()));
448 // We don't want to keep the window in memory if it is closed.
449 setAttribute(Qt::WA_DeleteOnClose, true);
451 #if (!defined(Q_WS_WIN) && !defined(Q_WS_MACX))
452 // QIcon::fromTheme was introduced in Qt 4.6
453 #if (QT_VERSION >= 0x040600)
454 // assign an icon to main form. We do not do it under Qt/Win or Qt/Mac,
455 // since the icon is provided in the application bundle. We use a themed
456 // version when available and use the bundled one as fallback.
457 setWindowIcon(QIcon::fromTheme("lyx", getPixmap("images/", "lyx", "png")));
459 setWindowIcon(getPixmap("images/", "lyx", "png"));
463 resetWindowTitleAndIconText();
465 // use tabbed dock area for multiple docks
466 // (such as "source" and "messages")
467 setDockOptions(QMainWindow::ForceTabbedDocks);
470 setAcceptDrops(true);
472 // add busy indicator to statusbar
473 QLabel * busylabel = new QLabel(statusBar());
474 statusBar()->addPermanentWidget(busylabel);
475 QString fn = toqstr(lyx::libFileSearch("images", "busy.gif").absFileName());
476 QMovie * busyanim = new QMovie(fn, QByteArray(), busylabel);
477 busylabel->setMovie(busyanim);
481 connect(&d.processing_thread_watcher_, SIGNAL(started()),
482 busylabel, SLOT(show()));
483 connect(&d.processing_thread_watcher_, SIGNAL(finished()),
484 busylabel, SLOT(hide()));
486 statusBar()->setSizeGripEnabled(true);
489 connect(&d.autosave_watcher_, SIGNAL(finished()), this,
490 SLOT(autoSaveThreadFinished()));
492 connect(&d.processing_thread_watcher_, SIGNAL(started()), this,
493 SLOT(processingThreadStarted()));
494 connect(&d.processing_thread_watcher_, SIGNAL(finished()), this,
495 SLOT(processingThreadFinished()));
497 connect(this, SIGNAL(triggerShowDialog(QString const &, QString const &, Inset *)),
498 SLOT(doShowDialog(QString const &, QString const &, Inset *)));
500 // Forbid too small unresizable window because it can happen
501 // with some window manager under X11.
502 setMinimumSize(300, 200);
504 if (lyxrc.allow_geometry_session) {
505 // Now take care of session management.
510 // no session handling, default to a sane size.
511 setGeometry(50, 50, 690, 510);
514 // clear session data if any.
516 settings.remove("views");
526 QVector<GuiWorkArea*> GuiView::GuiViewPrivate::guiWorkAreas()
528 QVector<GuiWorkArea*> areas;
529 for (int i = 0; i < tabWorkAreaCount(); i++) {
530 TabWorkArea* ta = tabWorkArea(i);
531 for (int u = 0; u < ta->count(); u++) {
532 areas << ta->workArea(u);
538 static void handleExportStatus(GuiView * view, Buffer::ExportStatus status,
539 string const & format)
541 docstring const fmt = formats.prettyName(format);
544 case Buffer::ExportSuccess:
545 msg = bformat(_("Successful export to format: %1$s"), fmt);
547 case Buffer::ExportCancel:
548 msg = _("Document export cancelled.");
550 case Buffer::ExportError:
551 case Buffer::ExportNoPathToFormat:
552 case Buffer::ExportTexPathHasSpaces:
553 case Buffer::ExportConverterError:
554 msg = bformat(_("Error while exporting format: %1$s"), fmt);
556 case Buffer::PreviewSuccess:
557 msg = bformat(_("Successful preview of format: %1$s"), fmt);
559 case Buffer::PreviewError:
560 msg = bformat(_("Error while previewing format: %1$s"), fmt);
567 void GuiView::processingThreadStarted()
572 void GuiView::processingThreadFinished()
574 QFutureWatcher<Buffer::ExportStatus> const * watcher =
575 static_cast<QFutureWatcher<Buffer::ExportStatus> const *>(sender());
577 Buffer::ExportStatus const status = watcher->result();
578 handleExportStatus(this, status, d.processing_format);
581 BufferView const * const bv = currentBufferView();
582 if (bv && !bv->buffer().errorList("Export").empty()) {
586 errors(d.last_export_format);
590 void GuiView::autoSaveThreadFinished()
592 QFutureWatcher<docstring> const * watcher =
593 static_cast<QFutureWatcher<docstring> const *>(sender());
594 message(watcher->result());
599 void GuiView::saveLayout() const
602 settings.beginGroup("views");
603 settings.beginGroup(QString::number(id_));
605 settings.setValue("pos", pos());
606 settings.setValue("size", size());
608 settings.setValue("geometry", saveGeometry());
610 settings.setValue("layout", saveState(0));
611 settings.setValue("icon_size", iconSize());
615 void GuiView::saveUISettings() const
617 // Save the toolbar private states
618 ToolbarMap::iterator end = d.toolbars_.end();
619 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
620 it->second->saveSession();
621 // Now take care of all other dialogs
622 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
623 for (; it!= d.dialogs_.end(); ++it)
624 it->second->saveSession();
628 bool GuiView::restoreLayout()
631 settings.beginGroup("views");
632 settings.beginGroup(QString::number(id_));
633 QString const icon_key = "icon_size";
634 if (!settings.contains(icon_key))
637 //code below is skipped when when ~/.config/LyX is (re)created
638 QSize icon_size = settings.value(icon_key).toSize();
639 // Check whether session size changed.
640 if (icon_size.width() != int(d.smallIconSize) &&
641 icon_size.width() != int(d.normalIconSize) &&
642 icon_size.width() != int(d.bigIconSize)) {
643 icon_size.setWidth(d.normalIconSize);
644 icon_size.setHeight(d.normalIconSize);
646 setIconSize(icon_size);
649 QPoint pos = settings.value("pos", QPoint(50, 50)).toPoint();
650 QSize size = settings.value("size", QSize(690, 510)).toSize();
654 // Work-around for bug #6034: the window ends up in an undetermined
655 // state when trying to restore a maximized window when it is
656 // already maximized.
657 if (!(windowState() & Qt::WindowMaximized))
658 if (!restoreGeometry(settings.value("geometry").toByteArray()))
659 setGeometry(50, 50, 690, 510);
661 // Make sure layout is correctly oriented.
662 setLayoutDirection(qApp->layoutDirection());
664 // Allow the toc and view-source dock widget to be restored if needed.
666 if ((dialog = findOrBuild("toc", true)))
667 // see bug 5082. At least setup title and enabled state.
668 // Visibility will be adjusted by restoreState below.
669 dialog->prepareView();
670 if ((dialog = findOrBuild("view-source", true)))
671 dialog->prepareView();
672 if ((dialog = findOrBuild("progress", true)))
673 dialog->prepareView();
675 if (!restoreState(settings.value("layout").toByteArray(), 0))
678 // init the toolbars that have not been restored
679 Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
680 Toolbars::Infos::iterator end = guiApp->toolbars().end();
681 for (; cit != end; ++cit) {
682 GuiToolbar * tb = toolbar(cit->name);
683 if (tb && !tb->isRestored())
684 initToolbar(cit->name);
692 GuiToolbar * GuiView::toolbar(string const & name)
694 ToolbarMap::iterator it = d.toolbars_.find(name);
695 if (it != d.toolbars_.end())
698 LYXERR(Debug::GUI, "Toolbar::display: no toolbar named " << name);
703 void GuiView::constructToolbars()
705 ToolbarMap::iterator it = d.toolbars_.begin();
706 for (; it != d.toolbars_.end(); ++it)
710 // I don't like doing this here, but the standard toolbar
711 // destroys this object when it's destroyed itself (vfr)
712 d.layout_ = new LayoutBox(*this);
713 d.stack_widget_->addWidget(d.layout_);
714 d.layout_->move(0,0);
716 // extracts the toolbars from the backend
717 Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
718 Toolbars::Infos::iterator end = guiApp->toolbars().end();
719 for (; cit != end; ++cit)
720 d.toolbars_[cit->name] = new GuiToolbar(*cit, *this);
724 void GuiView::initToolbars()
726 // extracts the toolbars from the backend
727 Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
728 Toolbars::Infos::iterator end = guiApp->toolbars().end();
729 for (; cit != end; ++cit)
730 initToolbar(cit->name);
734 void GuiView::initToolbar(string const & name)
736 GuiToolbar * tb = toolbar(name);
739 int const visibility = guiApp->toolbars().defaultVisibility(name);
740 bool newline = !(visibility & Toolbars::SAMEROW);
741 tb->setVisible(false);
742 tb->setVisibility(visibility);
744 if (visibility & Toolbars::TOP) {
746 addToolBarBreak(Qt::TopToolBarArea);
747 addToolBar(Qt::TopToolBarArea, tb);
750 if (visibility & Toolbars::BOTTOM) {
752 addToolBarBreak(Qt::BottomToolBarArea);
753 addToolBar(Qt::BottomToolBarArea, tb);
756 if (visibility & Toolbars::LEFT) {
758 addToolBarBreak(Qt::LeftToolBarArea);
759 addToolBar(Qt::LeftToolBarArea, tb);
762 if (visibility & Toolbars::RIGHT) {
764 addToolBarBreak(Qt::RightToolBarArea);
765 addToolBar(Qt::RightToolBarArea, tb);
768 if (visibility & Toolbars::ON)
769 tb->setVisible(true);
773 TocModels & GuiView::tocModels()
775 return d.toc_models_;
779 void GuiView::setFocus()
781 LYXERR(Debug::DEBUG, "GuiView::setFocus()" << this);
782 QMainWindow::setFocus();
786 void GuiView::focusInEvent(QFocusEvent * e)
788 LYXERR(Debug::DEBUG, "GuiView::focusInEvent()" << this);
789 QMainWindow::focusInEvent(e);
790 // Make sure guiApp points to the correct view.
791 guiApp->setCurrentView(this);
792 if (currentWorkArea())
793 currentWorkArea()->setFocus();
794 else if (currentMainWorkArea())
795 currentMainWorkArea()->setFocus();
797 d.bg_widget_->setFocus();
801 QMenu * GuiView::createPopupMenu()
803 return d.toolBarPopup(this);
807 void GuiView::showEvent(QShowEvent * e)
809 LYXERR(Debug::GUI, "Passed Geometry "
810 << size().height() << "x" << size().width()
811 << "+" << pos().x() << "+" << pos().y());
813 if (d.splitter_->count() == 0)
814 // No work area, switch to the background widget.
818 QMainWindow::showEvent(e);
822 bool GuiView::closeScheduled()
829 /** Destroy only all tabbed WorkAreas. Destruction of other WorkAreas
830 ** is responsibility of the container (e.g., dialog)
832 void GuiView::closeEvent(QCloseEvent * close_event)
834 LYXERR(Debug::DEBUG, "GuiView::closeEvent()");
836 if (!GuiViewPrivate::busyBuffers.isEmpty()) {
837 Alert::warning(_("Exit LyX"),
838 _("LyX could not be closed because documents are being processed by LyX."));
839 close_event->setAccepted(false);
843 // If the user pressed the x (so we didn't call closeView
844 // programmatically), we want to clear all existing entries.
846 theSession().lastOpened().clear();
851 // it can happen that this event arrives without selecting the view,
852 // e.g. when clicking the close button on a background window.
854 if (!closeWorkAreaAll()) {
856 close_event->ignore();
860 // Make sure that nothing will use this to be closed View.
861 guiApp->unregisterView(this);
863 if (isFullScreen()) {
864 // Switch off fullscreen before closing.
869 // Make sure the timer time out will not trigger a statusbar update.
870 d.statusbar_timer_.stop();
872 // Saving fullscreen requires additional tweaks in the toolbar code.
873 // It wouldn't also work under linux natively.
874 if (lyxrc.allow_geometry_session) {
879 close_event->accept();
883 void GuiView::dragEnterEvent(QDragEnterEvent * event)
885 if (event->mimeData()->hasUrls())
887 /// \todo Ask lyx-devel is this is enough:
888 /// if (event->mimeData()->hasFormat("text/plain"))
889 /// event->acceptProposedAction();
893 void GuiView::dropEvent(QDropEvent * event)
895 QList<QUrl> files = event->mimeData()->urls();
899 LYXERR(Debug::GUI, "GuiView::dropEvent: got URLs!");
900 for (int i = 0; i != files.size(); ++i) {
901 string const file = os::internal_path(fromqstr(
902 files.at(i).toLocalFile()));
906 string const ext = support::getExtension(file);
907 vector<const Format *> found_formats;
909 // Find all formats that have the correct extension.
910 vector<const Format *> const & import_formats
911 = theConverters().importableFormats();
912 vector<const Format *>::const_iterator it = import_formats.begin();
913 for (; it != import_formats.end(); ++it)
914 if ((*it)->hasExtension(ext))
915 found_formats.push_back(*it);
918 if (found_formats.size() >= 1) {
919 if (found_formats.size() > 1) {
920 //FIXME: show a dialog to choose the correct importable format
922 "Multiple importable formats found, selecting first");
924 string const arg = found_formats[0]->name() + " " + file;
925 cmd = FuncRequest(LFUN_BUFFER_IMPORT, arg);
928 //FIXME: do we have to explicitly check whether it's a lyx file?
930 "No formats found, trying to open it as a lyx file");
931 cmd = FuncRequest(LFUN_FILE_OPEN, file);
933 // add the functions to the queue
934 guiApp->addToFuncRequestQueue(cmd);
937 // now process the collected functions. We perform the events
938 // asynchronously. This prevents potential problems in case the
939 // BufferView is closed within an event.
940 guiApp->processFuncRequestQueueAsync();
944 void GuiView::message(docstring const & str)
946 if (ForkedProcess::iAmAChild())
949 // call is moved to GUI-thread by GuiProgress
950 d.progress_->appendMessage(toqstr(str));
954 void GuiView::clearMessageText()
956 message(docstring());
960 void GuiView::updateStatusBarMessage(QString const & str)
962 statusBar()->showMessage(str);
963 d.statusbar_timer_.stop();
964 d.statusbar_timer_.start(3000);
968 void GuiView::smallSizedIcons()
970 setIconSize(QSize(d.smallIconSize, d.smallIconSize));
974 void GuiView::normalSizedIcons()
976 setIconSize(QSize(d.normalIconSize, d.normalIconSize));
980 void GuiView::bigSizedIcons()
982 setIconSize(QSize(d.bigIconSize, d.bigIconSize));
986 void GuiView::clearMessage()
988 // FIXME: This code was introduced in r19643 to fix bug #4123. However,
989 // the hasFocus function mostly returns false, even if the focus is on
990 // a workarea in this view.
994 d.statusbar_timer_.stop();
998 void GuiView::updateWindowTitle(GuiWorkArea * wa)
1000 if (wa != d.current_work_area_
1001 || wa->bufferView().buffer().isInternal())
1003 setWindowTitle(qt_("LyX: ") + wa->windowTitle());
1004 setWindowIconText(wa->windowIconText());
1005 #if (QT_VERSION >= 0x040400)
1006 setWindowFilePath(wa->bufferView().buffer().absFileName().c_str());
1011 void GuiView::on_currentWorkAreaChanged(GuiWorkArea * wa)
1013 if (d.current_work_area_)
1014 QObject::disconnect(d.current_work_area_, SIGNAL(busy(bool)),
1015 this, SLOT(setBusy(bool)));
1017 disconnectBufferView();
1018 connectBufferView(wa->bufferView());
1019 connectBuffer(wa->bufferView().buffer());
1020 d.current_work_area_ = wa;
1021 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
1022 this, SLOT(updateWindowTitle(GuiWorkArea *)));
1023 QObject::connect(wa, SIGNAL(busy(bool)), this, SLOT(setBusy(bool)));
1024 updateWindowTitle(wa);
1028 // The document settings needs to be reinitialised.
1029 updateDialog("document", "");
1031 // Buffer-dependent dialogs must be updated. This is done here because
1032 // some dialogs require buffer()->text.
1037 void GuiView::on_lastWorkAreaRemoved()
1040 // We already are in a close event. Nothing more to do.
1043 if (d.splitter_->count() > 1)
1044 // We have a splitter so don't close anything.
1047 // Reset and updates the dialogs.
1048 d.toc_models_.reset(0);
1049 updateDialog("document", "");
1052 resetWindowTitleAndIconText();
1055 if (lyxrc.open_buffers_in_tabs)
1056 // Nothing more to do, the window should stay open.
1059 if (guiApp->viewIds().size() > 1) {
1065 // On Mac we also close the last window because the application stay
1066 // resident in memory. On other platforms we don't close the last
1067 // window because this would quit the application.
1073 void GuiView::updateStatusBar()
1075 // let the user see the explicit message
1076 if (d.statusbar_timer_.isActive())
1083 void GuiView::showMessage()
1087 QString msg = toqstr(theGuiApp()->viewStatusMessage());
1088 if (msg.isEmpty()) {
1089 BufferView const * bv = currentBufferView();
1091 msg = toqstr(bv->cursor().currentState());
1093 msg = qt_("Welcome to LyX!");
1095 statusBar()->showMessage(msg);
1099 bool GuiView::event(QEvent * e)
1103 // Useful debug code:
1104 //case QEvent::ActivationChange:
1105 //case QEvent::WindowDeactivate:
1106 //case QEvent::Paint:
1107 //case QEvent::Enter:
1108 //case QEvent::Leave:
1109 //case QEvent::HoverEnter:
1110 //case QEvent::HoverLeave:
1111 //case QEvent::HoverMove:
1112 //case QEvent::StatusTip:
1113 //case QEvent::DragEnter:
1114 //case QEvent::DragLeave:
1115 //case QEvent::Drop:
1118 case QEvent::WindowActivate: {
1119 GuiView * old_view = guiApp->currentView();
1120 if (this == old_view) {
1122 return QMainWindow::event(e);
1124 if (old_view && old_view->currentBufferView()) {
1125 // save current selection to the selection buffer to allow
1126 // middle-button paste in this window.
1127 cap::saveSelection(old_view->currentBufferView()->cursor());
1129 guiApp->setCurrentView(this);
1130 if (d.current_work_area_) {
1131 BufferView & bv = d.current_work_area_->bufferView();
1132 connectBufferView(bv);
1133 connectBuffer(bv.buffer());
1134 // The document structure, name and dialogs might have
1135 // changed in another view.
1137 // The document settings needs to be reinitialised.
1138 updateDialog("document", "");
1141 resetWindowTitleAndIconText();
1144 return QMainWindow::event(e);
1147 case QEvent::ShortcutOverride: {
1149 if (isFullScreen() && menuBar()->isHidden()) {
1150 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
1151 // FIXME: we should also try to detect special LyX shortcut such as
1152 // Alt-P and Alt-M. Right now there is a hack in
1153 // GuiWorkArea::processKeySym() that hides again the menubar for
1155 if (ke->modifiers() & Qt::AltModifier && ke->key() != Qt::Key_Alt) {
1157 return QMainWindow::event(e);
1160 return QMainWindow::event(e);
1164 return QMainWindow::event(e);
1168 void GuiView::resetWindowTitleAndIconText()
1170 setWindowTitle(qt_("LyX"));
1171 setWindowIconText(qt_("LyX"));
1174 bool GuiView::focusNextPrevChild(bool /*next*/)
1181 bool GuiView::busy() const
1187 void GuiView::setBusy(bool busy)
1189 bool const busy_before = busy_ > 0;
1190 busy ? ++busy_ : --busy_;
1191 if ((busy_ > 0) == busy_before)
1192 // busy state didn't change
1196 QApplication::setOverrideCursor(Qt::WaitCursor);
1199 QApplication::restoreOverrideCursor();
1204 GuiWorkArea * GuiView::workArea(int index)
1206 if (TabWorkArea * twa = d.currentTabWorkArea())
1207 if (index < twa->count())
1208 return dynamic_cast<GuiWorkArea *>(twa->widget(index));
1213 GuiWorkArea * GuiView::workArea(Buffer & buffer)
1215 if (currentWorkArea()
1216 && ¤tWorkArea()->bufferView().buffer() == &buffer)
1217 return (GuiWorkArea *) currentWorkArea();
1218 if (TabWorkArea * twa = d.currentTabWorkArea())
1219 return twa->workArea(buffer);
1224 GuiWorkArea * GuiView::addWorkArea(Buffer & buffer)
1226 // Automatically create a TabWorkArea if there are none yet.
1227 TabWorkArea * tab_widget = d.splitter_->count()
1228 ? d.currentTabWorkArea() : addTabWorkArea();
1229 return tab_widget->addWorkArea(buffer, *this);
1233 TabWorkArea * GuiView::addTabWorkArea()
1235 TabWorkArea * twa = new TabWorkArea;
1236 QObject::connect(twa, SIGNAL(currentWorkAreaChanged(GuiWorkArea *)),
1237 this, SLOT(on_currentWorkAreaChanged(GuiWorkArea *)));
1238 QObject::connect(twa, SIGNAL(lastWorkAreaRemoved()),
1239 this, SLOT(on_lastWorkAreaRemoved()));
1241 d.splitter_->addWidget(twa);
1242 d.stack_widget_->setCurrentWidget(d.splitter_);
1247 GuiWorkArea const * GuiView::currentWorkArea() const
1249 return d.current_work_area_;
1253 GuiWorkArea * GuiView::currentWorkArea()
1255 return d.current_work_area_;
1259 GuiWorkArea const * GuiView::currentMainWorkArea() const
1261 if (!d.currentTabWorkArea())
1263 return d.currentTabWorkArea()->currentWorkArea();
1267 GuiWorkArea * GuiView::currentMainWorkArea()
1269 if (!d.currentTabWorkArea())
1271 return d.currentTabWorkArea()->currentWorkArea();
1275 void GuiView::setCurrentWorkArea(GuiWorkArea * wa)
1277 LYXERR(Debug::DEBUG, "Setting current wa: " << wa << endl);
1279 d.current_work_area_ = 0;
1284 // FIXME: I've no clue why this is here and why it accesses
1285 // theGuiApp()->currentView, which might be 0 (bug 6464).
1286 // See also 27525 (vfr).
1287 if (theGuiApp()->currentView() == this
1288 && theGuiApp()->currentView()->currentWorkArea() == wa)
1291 if (currentBufferView())
1292 cap::saveSelection(currentBufferView()->cursor());
1294 theGuiApp()->setCurrentView(this);
1295 d.current_work_area_ = wa;
1297 // We need to reset this now, because it will need to be
1298 // right if the tabWorkArea gets reset in the for loop. We
1299 // will change it back if we aren't in that case.
1300 GuiWorkArea * const old_cmwa = d.current_main_work_area_;
1301 d.current_main_work_area_ = wa;
1303 for (int i = 0; i != d.splitter_->count(); ++i) {
1304 if (d.tabWorkArea(i)->setCurrentWorkArea(wa)) {
1305 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea()
1306 << ", Current main wa: " << currentMainWorkArea());
1311 d.current_main_work_area_ = old_cmwa;
1313 LYXERR(Debug::DEBUG, "This is not a tabbed wa");
1314 on_currentWorkAreaChanged(wa);
1315 BufferView & bv = wa->bufferView();
1316 bv.cursor().fixIfBroken();
1318 wa->setUpdatesEnabled(true);
1319 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() << ", Current main wa: " << currentMainWorkArea());
1323 void GuiView::removeWorkArea(GuiWorkArea * wa)
1325 LASSERT(wa, return);
1326 if (wa == d.current_work_area_) {
1328 disconnectBufferView();
1329 d.current_work_area_ = 0;
1330 d.current_main_work_area_ = 0;
1333 bool found_twa = false;
1334 for (int i = 0; i != d.splitter_->count(); ++i) {
1335 TabWorkArea * twa = d.tabWorkArea(i);
1336 if (twa->removeWorkArea(wa)) {
1337 // Found in this tab group, and deleted the GuiWorkArea.
1339 if (twa->count() != 0) {
1340 if (d.current_work_area_ == 0)
1341 // This means that we are closing the current GuiWorkArea, so
1342 // switch to the next GuiWorkArea in the found TabWorkArea.
1343 setCurrentWorkArea(twa->currentWorkArea());
1345 // No more WorkAreas in this tab group, so delete it.
1352 // It is not a tabbed work area (i.e., the search work area), so it
1353 // should be deleted by other means.
1354 LASSERT(found_twa, return);
1356 if (d.current_work_area_ == 0) {
1357 if (d.splitter_->count() != 0) {
1358 TabWorkArea * twa = d.currentTabWorkArea();
1359 setCurrentWorkArea(twa->currentWorkArea());
1361 // No more work areas, switch to the background widget.
1362 setCurrentWorkArea(0);
1368 LayoutBox * GuiView::getLayoutDialog() const
1374 void GuiView::updateLayoutList()
1377 d.layout_->updateContents(false);
1381 void GuiView::updateToolbars()
1383 ToolbarMap::iterator end = d.toolbars_.end();
1384 if (d.current_work_area_) {
1386 d.current_work_area_->bufferView().cursor().inMathed()
1387 && !d.current_work_area_->bufferView().cursor().inRegexped();
1389 lyx::getStatus(FuncRequest(LFUN_LAYOUT_TABULAR)).enabled();
1391 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).enabled() &&
1392 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).onOff(true);
1393 bool const mathmacrotemplate =
1394 lyx::getStatus(FuncRequest(LFUN_IN_MATHMACROTEMPLATE)).enabled();
1396 lyx::getStatus(FuncRequest(LFUN_IN_IPA)).enabled();
1398 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1399 it->second->update(math, table, review, mathmacrotemplate, ipa);
1401 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1402 it->second->update(false, false, false, false, false);
1406 void GuiView::setBuffer(Buffer * newBuffer)
1408 LYXERR(Debug::DEBUG, "Setting buffer: " << newBuffer << endl);
1409 LASSERT(newBuffer, return);
1411 GuiWorkArea * wa = workArea(*newBuffer);
1414 newBuffer->masterBuffer()->updateBuffer();
1416 wa = addWorkArea(*newBuffer);
1417 // scroll to the position when the BufferView was last closed
1418 if (lyxrc.use_lastfilepos) {
1419 LastFilePosSection::FilePos filepos =
1420 theSession().lastFilePos().load(newBuffer->fileName());
1421 wa->bufferView().moveToPosition(filepos.pit, filepos.pos, 0, 0);
1424 //Disconnect the old buffer...there's no new one.
1427 connectBuffer(*newBuffer);
1428 connectBufferView(wa->bufferView());
1429 setCurrentWorkArea(wa);
1433 void GuiView::connectBuffer(Buffer & buf)
1435 buf.setGuiDelegate(this);
1439 void GuiView::disconnectBuffer()
1441 if (d.current_work_area_)
1442 d.current_work_area_->bufferView().buffer().setGuiDelegate(0);
1446 void GuiView::connectBufferView(BufferView & bv)
1448 bv.setGuiDelegate(this);
1452 void GuiView::disconnectBufferView()
1454 if (d.current_work_area_)
1455 d.current_work_area_->bufferView().setGuiDelegate(0);
1459 void GuiView::errors(string const & error_type, bool from_master)
1461 BufferView const * const bv = currentBufferView();
1465 #if EXPORT_in_THREAD
1466 // We are called with from_master == false by default, so we
1467 // have to figure out whether that is the case or not.
1468 ErrorList & el = bv->buffer().errorList(error_type);
1470 el = bv->buffer().masterBuffer()->errorList(error_type);
1474 ErrorList const & el = from_master ?
1475 bv->buffer().masterBuffer()->errorList(error_type) :
1476 bv->buffer().errorList(error_type);
1482 string data = error_type;
1484 data = "from_master|" + error_type;
1485 showDialog("errorlist", data);
1489 void GuiView::updateTocItem(string const & type, DocIterator const & dit)
1491 d.toc_models_.updateItem(toqstr(type), dit);
1495 void GuiView::structureChanged()
1497 d.toc_models_.reset(documentBufferView());
1498 // Navigator needs more than a simple update in this case. It needs to be
1500 updateDialog("toc", "");
1504 void GuiView::updateDialog(string const & name, string const & data)
1506 if (!isDialogVisible(name))
1509 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
1510 if (it == d.dialogs_.end())
1513 Dialog * const dialog = it->second.get();
1514 if (dialog->isVisibleView())
1515 dialog->initialiseParams(data);
1519 BufferView * GuiView::documentBufferView()
1521 return currentMainWorkArea()
1522 ? ¤tMainWorkArea()->bufferView()
1527 BufferView const * GuiView::documentBufferView() const
1529 return currentMainWorkArea()
1530 ? ¤tMainWorkArea()->bufferView()
1535 BufferView * GuiView::currentBufferView()
1537 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1541 BufferView const * GuiView::currentBufferView() const
1543 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1547 docstring GuiView::GuiViewPrivate::autosaveAndDestroy(
1548 Buffer const * orig, Buffer * clone)
1550 bool const success = clone->autoSave();
1552 busyBuffers.remove(orig);
1554 ? _("Automatic save done.")
1555 : _("Automatic save failed!");
1559 void GuiView::autoSave()
1561 LYXERR(Debug::INFO, "Running autoSave()");
1563 Buffer * buffer = documentBufferView()
1564 ? &documentBufferView()->buffer() : 0;
1566 resetAutosaveTimers();
1570 GuiViewPrivate::busyBuffers.insert(buffer);
1571 QFuture<docstring> f = QtConcurrent::run(GuiViewPrivate::autosaveAndDestroy,
1572 buffer, buffer->cloneBufferOnly());
1573 d.autosave_watcher_.setFuture(f);
1574 resetAutosaveTimers();
1578 void GuiView::resetAutosaveTimers()
1581 d.autosave_timeout_.restart();
1585 bool GuiView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1588 Buffer * buf = currentBufferView()
1589 ? ¤tBufferView()->buffer() : 0;
1590 Buffer * doc_buffer = documentBufferView()
1591 ? &(documentBufferView()->buffer()) : 0;
1593 // Check whether we need a buffer
1594 if (!lyxaction.funcHasFlag(cmd.action(), LyXAction::NoBuffer) && !buf) {
1595 // no, exit directly
1596 flag.message(from_utf8(N_("Command not allowed with"
1597 "out any document open")));
1598 flag.setEnabled(false);
1602 if (cmd.origin() == FuncRequest::TOC) {
1603 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
1604 if (!toc || !toc->getStatus(documentBufferView()->cursor(), cmd, flag))
1605 flag.setEnabled(false);
1609 switch(cmd.action()) {
1610 case LFUN_BUFFER_IMPORT:
1613 case LFUN_MASTER_BUFFER_UPDATE:
1614 case LFUN_MASTER_BUFFER_VIEW:
1616 && (doc_buffer->parent() != 0
1617 || doc_buffer->hasChildren())
1618 && !d.processing_thread_watcher_.isRunning();
1621 case LFUN_BUFFER_UPDATE:
1622 case LFUN_BUFFER_VIEW: {
1623 if (!doc_buffer || d.processing_thread_watcher_.isRunning()) {
1627 string format = to_utf8(cmd.argument());
1628 if (cmd.argument().empty())
1629 format = doc_buffer->params().getDefaultOutputFormat();
1630 enable = doc_buffer->params().isExportableFormat(format);
1634 case LFUN_BUFFER_RELOAD:
1635 enable = doc_buffer && !doc_buffer->isUnnamed()
1636 && doc_buffer->fileName().exists()
1637 && (!doc_buffer->isClean()
1638 || doc_buffer->isExternallyModified(Buffer::timestamp_method));
1641 case LFUN_BUFFER_CHILD_OPEN:
1642 enable = doc_buffer;
1645 case LFUN_BUFFER_WRITE:
1646 enable = doc_buffer && (doc_buffer->isUnnamed() || !doc_buffer->isClean());
1649 //FIXME: This LFUN should be moved to GuiApplication.
1650 case LFUN_BUFFER_WRITE_ALL: {
1651 // We enable the command only if there are some modified buffers
1652 Buffer * first = theBufferList().first();
1657 // We cannot use a for loop as the buffer list is a cycle.
1659 if (!b->isClean()) {
1663 b = theBufferList().next(b);
1664 } while (b != first);
1668 case LFUN_BUFFER_WRITE_AS:
1669 case LFUN_BUFFER_EXPORT_AS:
1670 enable = doc_buffer;
1673 case LFUN_BUFFER_CLOSE:
1674 case LFUN_VIEW_CLOSE:
1675 enable = doc_buffer;
1678 case LFUN_BUFFER_CLOSE_ALL:
1679 enable = theBufferList().last() != theBufferList().first();
1682 case LFUN_VIEW_SPLIT:
1683 if (cmd.getArg(0) == "vertical")
1684 enable = doc_buffer && (d.splitter_->count() == 1 ||
1685 d.splitter_->orientation() == Qt::Vertical);
1687 enable = doc_buffer && (d.splitter_->count() == 1 ||
1688 d.splitter_->orientation() == Qt::Horizontal);
1691 case LFUN_TAB_GROUP_CLOSE:
1692 enable = d.tabWorkAreaCount() > 1;
1695 case LFUN_TOOLBAR_TOGGLE: {
1696 string const name = cmd.getArg(0);
1697 if (GuiToolbar * t = toolbar(name))
1698 flag.setOnOff(t->isVisible());
1701 docstring const msg =
1702 bformat(_("Unknown toolbar \"%1$s\""), from_utf8(name));
1708 case LFUN_DROP_LAYOUTS_CHOICE:
1712 case LFUN_UI_TOGGLE:
1713 flag.setOnOff(isFullScreen());
1716 case LFUN_DIALOG_DISCONNECT_INSET:
1719 case LFUN_DIALOG_HIDE:
1720 // FIXME: should we check if the dialog is shown?
1723 case LFUN_DIALOG_TOGGLE:
1724 flag.setOnOff(isDialogVisible(cmd.getArg(0)));
1725 // fall through to set "enable"
1726 case LFUN_DIALOG_SHOW: {
1727 string const name = cmd.getArg(0);
1729 enable = name == "aboutlyx"
1730 || name == "file" //FIXME: should be removed.
1732 || name == "texinfo"
1733 || name == "progress"
1734 || name == "compare";
1735 else if (name == "print")
1736 enable = doc_buffer->params().isExportable("dvi")
1737 && lyxrc.print_command != "none";
1738 else if (name == "character" || name == "symbols"
1739 || name == "mathdelimiter" || name == "mathmatrix") {
1740 if (!buf || buf->isReadonly())
1743 Cursor const & cur = currentBufferView()->cursor();
1744 enable = !(cur.inTexted() && cur.paragraph().isPassThru());
1747 else if (name == "latexlog")
1748 enable = FileName(doc_buffer->logName()).isReadableFile();
1749 else if (name == "spellchecker")
1750 enable = theSpellChecker()
1751 && !doc_buffer->isReadonly()
1752 && !doc_buffer->text().empty();
1753 else if (name == "vclog")
1754 enable = doc_buffer->lyxvc().inUse();
1758 case LFUN_DIALOG_UPDATE: {
1759 string const name = cmd.getArg(0);
1761 enable = name == "prefs";
1765 case LFUN_COMMAND_EXECUTE:
1767 case LFUN_MENU_OPEN:
1768 // Nothing to check.
1771 case LFUN_COMPLETION_INLINE:
1772 if (!d.current_work_area_
1773 || !d.current_work_area_->completer().inlinePossible(
1774 currentBufferView()->cursor()))
1778 case LFUN_COMPLETION_POPUP:
1779 if (!d.current_work_area_
1780 || !d.current_work_area_->completer().popupPossible(
1781 currentBufferView()->cursor()))
1786 if (!d.current_work_area_
1787 || !d.current_work_area_->completer().inlinePossible(
1788 currentBufferView()->cursor()))
1792 case LFUN_COMPLETION_ACCEPT:
1793 if (!d.current_work_area_
1794 || (!d.current_work_area_->completer().popupVisible()
1795 && !d.current_work_area_->completer().inlineVisible()
1796 && !d.current_work_area_->completer().completionAvailable()))
1800 case LFUN_COMPLETION_CANCEL:
1801 if (!d.current_work_area_
1802 || (!d.current_work_area_->completer().popupVisible()
1803 && !d.current_work_area_->completer().inlineVisible()))
1807 case LFUN_BUFFER_ZOOM_OUT:
1808 enable = doc_buffer && lyxrc.zoom > 10;
1811 case LFUN_BUFFER_ZOOM_IN:
1812 enable = doc_buffer;
1815 case LFUN_BUFFER_NEXT:
1816 case LFUN_BUFFER_PREVIOUS:
1817 // FIXME: should we check is there is an previous or next buffer?
1819 case LFUN_BUFFER_SWITCH:
1820 // toggle on the current buffer, but do not toggle off
1821 // the other ones (is that a good idea?)
1823 && to_utf8(cmd.argument()) == doc_buffer->absFileName())
1824 flag.setOnOff(true);
1827 case LFUN_VC_REGISTER:
1828 enable = doc_buffer && !doc_buffer->lyxvc().inUse();
1830 case LFUN_VC_RENAME:
1831 enable = doc_buffer && doc_buffer->lyxvc().renameEnabled();
1834 enable = doc_buffer && doc_buffer->lyxvc().copyEnabled();
1836 case LFUN_VC_CHECK_IN:
1837 enable = doc_buffer && doc_buffer->lyxvc().checkInEnabled();
1839 case LFUN_VC_CHECK_OUT:
1840 enable = doc_buffer && doc_buffer->lyxvc().checkOutEnabled();
1842 case LFUN_VC_LOCKING_TOGGLE:
1843 enable = doc_buffer && !doc_buffer->isReadonly()
1844 && doc_buffer->lyxvc().lockingToggleEnabled();
1845 flag.setOnOff(enable && doc_buffer->lyxvc().locking());
1847 case LFUN_VC_REVERT:
1848 enable = doc_buffer && doc_buffer->lyxvc().inUse() && !doc_buffer->isReadonly();
1850 case LFUN_VC_UNDO_LAST:
1851 enable = doc_buffer && doc_buffer->lyxvc().undoLastEnabled();
1853 case LFUN_VC_REPO_UPDATE:
1854 enable = doc_buffer && doc_buffer->lyxvc().repoUpdateEnabled();
1856 case LFUN_VC_COMMAND: {
1857 if (cmd.argument().empty())
1859 if (!doc_buffer && contains(cmd.getArg(0), 'D'))
1863 case LFUN_VC_COMPARE:
1864 enable = doc_buffer && doc_buffer->lyxvc().prepareFileRevisionEnabled();
1867 case LFUN_SERVER_GOTO_FILE_ROW:
1869 case LFUN_FORWARD_SEARCH:
1870 enable = !(lyxrc.forward_search_dvi.empty() && lyxrc.forward_search_pdf.empty());
1873 case LFUN_FILE_INSERT_PLAINTEXT:
1874 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
1875 enable = documentBufferView() && documentBufferView()->cursor().inTexted();
1878 case LFUN_SPELLING_CONTINUOUSLY:
1879 flag.setOnOff(lyxrc.spellcheck_continuously);
1887 flag.setEnabled(false);
1893 static FileName selectTemplateFile()
1895 FileDialog dlg(qt_("Select template file"));
1896 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1897 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
1899 FileDialog::Result result = dlg.open(toqstr(lyxrc.template_path),
1900 QStringList(qt_("LyX Documents (*.lyx)")));
1902 if (result.first == FileDialog::Later)
1904 if (result.second.isEmpty())
1906 return FileName(fromqstr(result.second));
1910 Buffer * GuiView::loadDocument(FileName const & filename, bool tolastfiles)
1914 Buffer * newBuffer = 0;
1916 newBuffer = checkAndLoadLyXFile(filename);
1917 } catch (ExceptionMessage const & e) {
1924 message(_("Document not loaded."));
1928 setBuffer(newBuffer);
1929 newBuffer->errors("Parse");
1932 theSession().lastFiles().add(filename);
1938 void GuiView::openDocument(string const & fname)
1940 string initpath = lyxrc.document_path;
1942 if (documentBufferView()) {
1943 string const trypath = documentBufferView()->buffer().filePath();
1944 // If directory is writeable, use this as default.
1945 if (FileName(trypath).isDirWritable())
1951 if (fname.empty()) {
1952 FileDialog dlg(qt_("Select document to open"), LFUN_FILE_OPEN);
1953 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1954 dlg.setButton2(qt_("Examples|#E#e"),
1955 toqstr(addPath(package().system_support().absFileName(), "examples")));
1957 QStringList const filter(qt_("LyX Documents (*.lyx)"));
1958 FileDialog::Result result =
1959 dlg.open(toqstr(initpath), filter);
1961 if (result.first == FileDialog::Later)
1964 filename = fromqstr(result.second);
1966 // check selected filename
1967 if (filename.empty()) {
1968 message(_("Canceled."));
1974 // get absolute path of file and add ".lyx" to the filename if
1976 FileName const fullname =
1977 fileSearch(string(), filename, "lyx", support::may_not_exist);
1978 if (!fullname.empty())
1979 filename = fullname.absFileName();
1981 if (!fullname.onlyPath().isDirectory()) {
1982 Alert::warning(_("Invalid filename"),
1983 bformat(_("The directory in the given path\n%1$s\ndoes not exist."),
1984 from_utf8(fullname.absFileName())));
1988 // if the file doesn't exist and isn't already open (bug 6645),
1989 // let the user create one
1990 if (!fullname.exists() && !theBufferList().exists(fullname) &&
1991 !LyXVC::file_not_found_hook(fullname)) {
1992 // the user specifically chose this name. Believe him.
1993 Buffer * const b = newFile(filename, string(), true);
1999 docstring const disp_fn = makeDisplayPath(filename);
2000 message(bformat(_("Opening document %1$s..."), disp_fn));
2003 Buffer * buf = loadDocument(fullname);
2005 str2 = bformat(_("Document %1$s opened."), disp_fn);
2006 if (buf->lyxvc().inUse())
2007 str2 += " " + from_utf8(buf->lyxvc().versionString()) +
2008 " " + _("Version control detected.");
2010 str2 = bformat(_("Could not open document %1$s"), disp_fn);
2015 // FIXME: clean that
2016 static bool import(GuiView * lv, FileName const & filename,
2017 string const & format, ErrorList & errorList)
2019 FileName const lyxfile(support::changeExtension(filename.absFileName(), ".lyx"));
2021 string loader_format;
2022 vector<string> loaders = theConverters().loaders();
2023 if (find(loaders.begin(), loaders.end(), format) == loaders.end()) {
2024 vector<string>::const_iterator it = loaders.begin();
2025 vector<string>::const_iterator en = loaders.end();
2026 for (; it != en; ++it) {
2027 if (!theConverters().isReachable(format, *it))
2030 string const tofile =
2031 support::changeExtension(filename.absFileName(),
2032 formats.extension(*it));
2033 if (!theConverters().convert(0, filename, FileName(tofile),
2034 filename, format, *it, errorList))
2036 loader_format = *it;
2039 if (loader_format.empty()) {
2040 frontend::Alert::error(_("Couldn't import file"),
2041 bformat(_("No information for importing the format %1$s."),
2042 formats.prettyName(format)));
2046 loader_format = format;
2048 if (loader_format == "lyx") {
2049 Buffer * buf = lv->loadDocument(lyxfile);
2053 Buffer * const b = newFile(lyxfile.absFileName(), string(), true);
2057 bool as_paragraphs = loader_format == "textparagraph";
2058 string filename2 = (loader_format == format) ? filename.absFileName()
2059 : support::changeExtension(filename.absFileName(),
2060 formats.extension(loader_format));
2061 lv->currentBufferView()->insertPlaintextFile(FileName(filename2),
2063 guiApp->setCurrentView(lv);
2064 lyx::dispatch(FuncRequest(LFUN_MARK_OFF));
2071 void GuiView::importDocument(string const & argument)
2074 string filename = split(argument, format, ' ');
2076 LYXERR(Debug::INFO, format << " file: " << filename);
2078 // need user interaction
2079 if (filename.empty()) {
2080 string initpath = lyxrc.document_path;
2081 if (documentBufferView()) {
2082 string const trypath = documentBufferView()->buffer().filePath();
2083 // If directory is writeable, use this as default.
2084 if (FileName(trypath).isDirWritable())
2088 docstring const text = bformat(_("Select %1$s file to import"),
2089 formats.prettyName(format));
2091 FileDialog dlg(toqstr(text), LFUN_BUFFER_IMPORT);
2092 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2093 dlg.setButton2(qt_("Examples|#E#e"),
2094 toqstr(addPath(package().system_support().absFileName(), "examples")));
2096 docstring filter = formats.prettyName(format);
2099 filter += from_utf8(formats.extensions(format));
2102 FileDialog::Result result =
2103 dlg.open(toqstr(initpath), fileFilters(toqstr(filter)));
2105 if (result.first == FileDialog::Later)
2108 filename = fromqstr(result.second);
2110 // check selected filename
2111 if (filename.empty())
2112 message(_("Canceled."));
2115 if (filename.empty())
2118 // get absolute path of file
2119 FileName const fullname(support::makeAbsPath(filename));
2121 FileName const lyxfile(support::changeExtension(fullname.absFileName(), ".lyx"));
2123 // Check if the document already is open
2124 Buffer * buf = theBufferList().getBuffer(lyxfile);
2127 if (!closeBuffer()) {
2128 message(_("Canceled."));
2133 docstring const displaypath = makeDisplayPath(lyxfile.absFileName(), 30);
2135 // if the file exists already, and we didn't do
2136 // -i lyx thefile.lyx, warn
2137 if (lyxfile.exists() && fullname != lyxfile) {
2139 docstring text = bformat(_("The document %1$s already exists.\n\n"
2140 "Do you want to overwrite that document?"), displaypath);
2141 int const ret = Alert::prompt(_("Overwrite document?"),
2142 text, 0, 1, _("&Overwrite"), _("&Cancel"));
2145 message(_("Canceled."));
2150 message(bformat(_("Importing %1$s..."), displaypath));
2151 ErrorList errorList;
2152 if (import(this, fullname, format, errorList))
2153 message(_("imported."));
2155 message(_("file not imported!"));
2157 // FIXME (Abdel 12/08/06): Is there a need to display the error list here?
2161 void GuiView::newDocument(string const & filename, bool from_template)
2163 FileName initpath(lyxrc.document_path);
2164 if (documentBufferView()) {
2165 FileName const trypath(documentBufferView()->buffer().filePath());
2166 // If directory is writeable, use this as default.
2167 if (trypath.isDirWritable())
2171 string templatefile;
2172 if (from_template) {
2173 templatefile = selectTemplateFile().absFileName();
2174 if (templatefile.empty())
2179 if (filename.empty())
2180 b = newUnnamedFile(initpath, to_utf8(_("newfile")), templatefile);
2182 b = newFile(filename, templatefile, true);
2187 // If no new document could be created, it is unsure
2188 // whether there is a valid BufferView.
2189 if (currentBufferView())
2190 // Ensure the cursor is correctly positioned on screen.
2191 currentBufferView()->showCursor();
2195 void GuiView::insertLyXFile(docstring const & fname)
2197 BufferView * bv = documentBufferView();
2202 FileName filename(to_utf8(fname));
2203 if (filename.empty()) {
2204 // Launch a file browser
2206 string initpath = lyxrc.document_path;
2207 string const trypath = bv->buffer().filePath();
2208 // If directory is writeable, use this as default.
2209 if (FileName(trypath).isDirWritable())
2213 FileDialog dlg(qt_("Select LyX document to insert"), LFUN_FILE_INSERT);
2214 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2215 dlg.setButton2(qt_("Examples|#E#e"),
2216 toqstr(addPath(package().system_support().absFileName(),
2219 FileDialog::Result result = dlg.open(toqstr(initpath),
2220 QStringList(qt_("LyX Documents (*.lyx)")));
2222 if (result.first == FileDialog::Later)
2226 filename.set(fromqstr(result.second));
2228 // check selected filename
2229 if (filename.empty()) {
2230 // emit message signal.
2231 message(_("Canceled."));
2236 bv->insertLyXFile(filename);
2237 bv->buffer().errors("Parse");
2241 bool GuiView::renameBuffer(Buffer & b, docstring const & newname, RenameKind kind)
2243 FileName fname = b.fileName();
2244 FileName const oldname = fname;
2246 if (!newname.empty()) {
2248 fname = support::makeAbsPath(to_utf8(newname), oldname.onlyPath().absFileName());
2250 // Switch to this Buffer.
2253 // No argument? Ask user through dialog.
2255 FileDialog dlg(qt_("Choose a filename to save document as"),
2256 LFUN_BUFFER_WRITE_AS);
2257 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2258 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
2260 if (!isLyXFileName(fname.absFileName()))
2261 fname.changeExtension(".lyx");
2263 FileDialog::Result result =
2264 dlg.save(toqstr(fname.onlyPath().absFileName()),
2265 QStringList(qt_("LyX Documents (*.lyx)")),
2266 toqstr(fname.onlyFileName()));
2268 if (result.first == FileDialog::Later)
2271 fname.set(fromqstr(result.second));
2276 if (!isLyXFileName(fname.absFileName()))
2277 fname.changeExtension(".lyx");
2280 // fname is now the new Buffer location.
2282 // if there is already a Buffer open with this name, we do not want
2283 // to have another one. (the second test makes sure we're not just
2284 // trying to overwrite ourselves, which is fine.)
2285 if (theBufferList().exists(fname) && fname != oldname
2286 && theBufferList().getBuffer(fname) != &b) {
2287 docstring const text =
2288 bformat(_("The file\n%1$s\nis already open in your current session.\n"
2289 "Please close it before attempting to overwrite it.\n"
2290 "Do you want to choose a new filename?"),
2291 from_utf8(fname.absFileName()));
2292 int const ret = Alert::prompt(_("Chosen File Already Open"),
2293 text, 0, 1, _("&Rename"), _("&Cancel"));
2295 case 0: return renameBuffer(b, docstring(), kind);
2296 case 1: return false;
2301 bool const existsLocal = fname.exists();
2302 bool const existsInVC = LyXVC::fileInVC(fname);
2303 if (existsLocal || existsInVC) {
2304 docstring const file = makeDisplayPath(fname.absFileName(), 30);
2305 if (kind != LV_WRITE_AS && existsInVC) {
2306 // renaming to a name that is already in VC
2308 docstring text = bformat(_("The document %1$s "
2309 "is already registered.\n\n"
2310 "Do you want to choose a new name?"),
2312 docstring const title = (kind == LV_VC_RENAME) ?
2313 _("Rename document?") : _("Copy document?");
2314 docstring const button = (kind == LV_VC_RENAME) ?
2315 _("&Rename") : _("&Copy");
2316 int const ret = Alert::prompt(title, text, 0, 1,
2317 button, _("&Cancel"));
2319 case 0: return renameBuffer(b, docstring(), kind);
2320 case 1: return false;
2325 docstring text = bformat(_("The document %1$s "
2326 "already exists.\n\n"
2327 "Do you want to overwrite that document?"),
2329 int const ret = Alert::prompt(_("Overwrite document?"),
2330 text, 0, 2, _("&Overwrite"),
2331 _("&Rename"), _("&Cancel"));
2334 case 1: return renameBuffer(b, docstring(), kind);
2335 case 2: return false;
2341 case LV_VC_RENAME: {
2342 string msg = b.lyxvc().rename(fname);
2345 message(from_utf8(msg));
2349 string msg = b.lyxvc().copy(fname);
2352 message(from_utf8(msg));
2358 // LyXVC created the file already in case of LV_VC_RENAME or
2359 // LV_VC_COPY, but call saveBuffer() nevertheless to get
2360 // relative paths of included stuff right if we moved e.g. from
2361 // /a/b.lyx to /a/c/b.lyx.
2363 bool const saved = saveBuffer(b, fname);
2370 struct PrettyNameComparator
2372 bool operator()(Format const *first, Format const *second) const {
2373 return compare_no_case(translateIfPossible(from_ascii(first->prettyname())),
2374 translateIfPossible(from_ascii(second->prettyname()))) <= 0;
2379 bool GuiView::exportBufferAs(Buffer & b, docstring const & iformat)
2381 FileName fname = b.fileName();
2383 FileDialog dlg(qt_("Choose a filename to export the document as"));
2384 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2387 QString const anyformat = qt_("Guess from extension (*.*)");
2389 Formats::const_iterator it = formats.begin();
2390 vector<Format const *> export_formats;
2391 for (; it != formats.end(); ++it)
2392 if (it->documentFormat())
2393 export_formats.push_back(&(*it));
2394 PrettyNameComparator cmp;
2395 sort(export_formats.begin(), export_formats.end(), cmp);
2396 vector<Format const *>::const_iterator fit = export_formats.begin();
2397 map<QString, string> fmap;
2400 for (; fit != export_formats.end(); ++fit) {
2401 docstring const loc_prettyname =
2402 translateIfPossible(from_utf8((*fit)->prettyname()));
2403 QString const loc_filter = toqstr(bformat(from_ascii("%1$s (*.%2$s)"),
2405 from_ascii((*fit)->extension())));
2406 types << loc_filter;
2407 fmap[loc_filter] = (*fit)->name();
2408 if (from_ascii((*fit)->name()) == iformat) {
2409 filter = loc_filter;
2410 ext = (*fit)->extension();
2413 string ofname = fname.onlyFileName();
2415 ofname = support::changeExtension(ofname, ext);
2416 FileDialog::Result result =
2417 dlg.save(toqstr(fname.onlyPath().absFileName()),
2421 if (result.first != FileDialog::Chosen)
2425 fname.set(fromqstr(result.second));
2426 if (filter == anyformat)
2427 fmt_name = formats.getFormatFromExtension(fname.extension());
2429 fmt_name = fmap[filter];
2430 LYXERR(Debug::FILES, "filter=" << fromqstr(filter)
2431 << ", fmt_name=" << fmt_name << ", fname=" << fname.absFileName());
2433 if (fmt_name.empty() || fname.empty())
2436 // fname is now the new Buffer location.
2437 if (FileName(fname).exists()) {
2438 docstring const file = makeDisplayPath(fname.absFileName(), 30);
2439 docstring text = bformat(_("The document %1$s already "
2440 "exists.\n\nDo you want to "
2441 "overwrite that document?"),
2443 int const ret = Alert::prompt(_("Overwrite document?"),
2444 text, 0, 2, _("&Overwrite"), _("&Rename"), _("&Cancel"));
2447 case 1: return exportBufferAs(b, from_ascii(fmt_name));
2448 case 2: return false;
2452 FuncRequest cmd(LFUN_BUFFER_EXPORT, fmt_name + " " + fname.absFileName());
2455 return dr.dispatched();
2459 bool GuiView::saveBuffer(Buffer & b)
2461 return saveBuffer(b, FileName());
2465 bool GuiView::saveBuffer(Buffer & b, FileName const & fn)
2467 if (workArea(b) && workArea(b)->inDialogMode())
2470 if (fn.empty() && b.isUnnamed())
2471 return renameBuffer(b, docstring());
2473 bool const success = (fn.empty() ? b.save() : b.saveAs(fn));
2475 theSession().lastFiles().add(b.fileName());
2479 // Switch to this Buffer.
2482 // FIXME: we don't tell the user *WHY* the save failed !!
2483 docstring const file = makeDisplayPath(b.absFileName(), 30);
2484 docstring text = bformat(_("The document %1$s could not be saved.\n\n"
2485 "Do you want to rename the document and "
2486 "try again?"), file);
2487 int const ret = Alert::prompt(_("Rename and save?"),
2488 text, 0, 2, _("&Rename"), _("&Retry"), _("&Cancel"));
2491 if (!renameBuffer(b, docstring()))
2500 return saveBuffer(b, fn);
2504 bool GuiView::hideWorkArea(GuiWorkArea * wa)
2506 return closeWorkArea(wa, false);
2510 // We only want to close the buffer if it is not visible in other workareas
2511 // of the same view, nor in other views, and if this is not a child
2512 bool GuiView::closeWorkArea(GuiWorkArea * wa)
2514 Buffer & buf = wa->bufferView().buffer();
2516 bool last_wa = d.countWorkAreasOf(buf) == 1
2517 && !inOtherView(buf) && !buf.parent();
2519 bool close_buffer = last_wa;
2522 if (lyxrc.close_buffer_with_last_view == "yes")
2524 else if (lyxrc.close_buffer_with_last_view == "no")
2525 close_buffer = false;
2528 if (buf.isUnnamed())
2529 file = from_utf8(buf.fileName().onlyFileName());
2531 file = buf.fileName().displayName(30);
2532 docstring const text = bformat(
2533 _("Last view on document %1$s is being closed.\n"
2534 "Would you like to close or hide the document?\n"
2536 "Hidden documents can be displayed back through\n"
2537 "the menu: View->Hidden->...\n"
2539 "To remove this question, set your preference in:\n"
2540 " Tools->Preferences->Look&Feel->UserInterface\n"
2542 int ret = Alert::prompt(_("Close or hide document?"),
2543 text, 0, 1, _("&Close"), _("&Hide"));
2544 close_buffer = (ret == 0);
2548 return closeWorkArea(wa, close_buffer);
2552 bool GuiView::closeBuffer()
2554 GuiWorkArea * wa = currentMainWorkArea();
2555 setCurrentWorkArea(wa);
2556 Buffer & buf = wa->bufferView().buffer();
2557 return wa && closeWorkArea(wa, !buf.parent());
2561 void GuiView::writeSession() const {
2562 GuiWorkArea const * active_wa = currentMainWorkArea();
2563 for (int i = 0; i < d.splitter_->count(); ++i) {
2564 TabWorkArea * twa = d.tabWorkArea(i);
2565 for (int j = 0; j < twa->count(); ++j) {
2566 GuiWorkArea * wa = static_cast<GuiWorkArea *>(twa->widget(j));
2567 Buffer & buf = wa->bufferView().buffer();
2568 theSession().lastOpened().add(buf.fileName(), wa == active_wa);
2574 bool GuiView::closeBufferAll()
2576 // Close the workareas in all other views
2577 QList<int> const ids = guiApp->viewIds();
2578 for (int i = 0; i != ids.size(); ++i) {
2579 if (id_ != ids[i] && !guiApp->view(ids[i]).closeWorkAreaAll())
2583 // Close our own workareas
2584 if (!closeWorkAreaAll())
2587 // Now close the hidden buffers. We prevent hidden buffers from being
2588 // dirty, so we can just close them.
2589 theBufferList().closeAll();
2594 bool GuiView::closeWorkAreaAll()
2596 setCurrentWorkArea(currentMainWorkArea());
2598 // We might be in a situation that there is still a tabWorkArea, but
2599 // there are no tabs anymore. This can happen when we get here after a
2600 // TabWorkArea::lastWorkAreaRemoved() signal. Therefore we count how
2601 // many TabWorkArea's have no documents anymore.
2604 // We have to call count() each time, because it can happen that
2605 // more than one splitter will disappear in one iteration (bug 5998).
2606 for (; d.splitter_->count() > empty_twa; ) {
2607 TabWorkArea * twa = d.tabWorkArea(empty_twa);
2609 if (twa->count() == 0)
2612 setCurrentWorkArea(twa->currentWorkArea());
2613 if (!closeTabWorkArea(twa))
2621 bool GuiView::closeWorkArea(GuiWorkArea * wa, bool close_buffer)
2626 Buffer & buf = wa->bufferView().buffer();
2628 if (close_buffer && GuiViewPrivate::busyBuffers.contains(&buf)) {
2629 Alert::warning(_("Close document"),
2630 _("Document could not be closed because it is being processed by LyX."));
2635 return closeBuffer(buf);
2637 if (!inMultiTabs(wa))
2638 if (!saveBufferIfNeeded(buf, true))
2646 bool GuiView::closeBuffer(Buffer & buf)
2648 // If we are in a close_event all children will be closed in some time,
2649 // so no need to do it here. This will ensure that the children end up
2650 // in the session file in the correct order. If we close the master
2651 // buffer, we can close or release the child buffers here too.
2652 bool success = true;
2654 ListOfBuffers clist = buf.getChildren();
2655 ListOfBuffers::const_iterator it = clist.begin();
2656 ListOfBuffers::const_iterator const bend = clist.end();
2657 for (; it != bend; ++it) {
2658 // If a child is dirty, do not close
2659 // without user intervention
2660 //FIXME: should we look in other tabworkareas?
2661 Buffer * child_buf = *it;
2662 GuiWorkArea * child_wa = workArea(*child_buf);
2664 if (!closeWorkArea(child_wa, true)) {
2669 theBufferList().releaseChild(&buf, child_buf);
2673 // goto bookmark to update bookmark pit.
2674 //FIXME: we should update only the bookmarks related to this buffer!
2675 LYXERR(Debug::DEBUG, "GuiView::closeBuffer()");
2676 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
2677 guiApp->gotoBookmark(i+1, false, false);
2679 if (saveBufferIfNeeded(buf, false)) {
2680 buf.removeAutosaveFile();
2681 theBufferList().release(&buf);
2685 // open all children again to avoid a crash because of dangling
2686 // pointers (bug 6603)
2692 bool GuiView::closeTabWorkArea(TabWorkArea * twa)
2694 while (twa == d.currentTabWorkArea()) {
2695 twa->setCurrentIndex(twa->count()-1);
2697 GuiWorkArea * wa = twa->currentWorkArea();
2698 Buffer & b = wa->bufferView().buffer();
2700 // We only want to close the buffer if the same buffer is not visible
2701 // in another view, and if this is not a child and if we are closing
2702 // a view (not a tabgroup).
2703 bool const close_buffer =
2704 !inOtherView(b) && !b.parent() && closing_;
2706 if (!closeWorkArea(wa, close_buffer))
2713 bool GuiView::saveBufferIfNeeded(Buffer & buf, bool hiding)
2715 if (buf.isClean() || buf.paragraphs().empty())
2718 // Switch to this Buffer.
2723 if (buf.isUnnamed())
2724 file = from_utf8(buf.fileName().onlyFileName());
2726 file = buf.fileName().displayName(30);
2728 // Bring this window to top before asking questions.
2733 if (hiding && buf.isUnnamed()) {
2734 docstring const text = bformat(_("The document %1$s has not been "
2735 "saved yet.\n\nDo you want to save "
2736 "the document?"), file);
2737 ret = Alert::prompt(_("Save new document?"),
2738 text, 0, 1, _("&Save"), _("&Cancel"));
2742 docstring const text = bformat(_("The document %1$s has unsaved changes."
2743 "\n\nDo you want to save the document or discard the changes?"), file);
2744 ret = Alert::prompt(_("Save changed document?"),
2745 text, 0, 2, _("&Save"), _("&Discard"), _("&Cancel"));
2750 if (!saveBuffer(buf))
2754 // If we crash after this we could have no autosave file
2755 // but I guess this is really improbable (Jug).
2756 // Sometimes improbable things happen:
2757 // - see bug http://www.lyx.org/trac/ticket/6587 (ps)
2758 // buf.removeAutosaveFile();
2760 // revert all changes
2771 bool GuiView::inMultiTabs(GuiWorkArea * wa)
2773 Buffer & buf = wa->bufferView().buffer();
2775 for (int i = 0; i != d.splitter_->count(); ++i) {
2776 GuiWorkArea * wa_ = d.tabWorkArea(i)->workArea(buf);
2777 if (wa_ && wa_ != wa)
2780 return inOtherView(buf);
2784 bool GuiView::inOtherView(Buffer & buf)
2786 QList<int> const ids = guiApp->viewIds();
2788 for (int i = 0; i != ids.size(); ++i) {
2792 if (guiApp->view(ids[i]).workArea(buf))
2799 void GuiView::gotoNextOrPreviousBuffer(NextOrPrevious np)
2801 if (!documentBufferView())
2804 if (TabWorkArea * twa = d.currentTabWorkArea()) {
2805 Buffer * const curbuf = &documentBufferView()->buffer();
2806 int nwa = twa->count();
2807 for (int i = 0; i < nwa; ++i) {
2808 if (&workArea(i)->bufferView().buffer() == curbuf) {
2810 if (np == NEXTBUFFER)
2811 next_index = (i == nwa - 1 ? 0 : i + 1);
2813 next_index = (i == 0 ? nwa - 1 : i - 1);
2814 setBuffer(&workArea(next_index)->bufferView().buffer());
2822 /// make sure the document is saved
2823 static bool ensureBufferClean(Buffer * buffer)
2825 LASSERT(buffer, return false);
2826 if (buffer->isClean() && !buffer->isUnnamed())
2829 docstring const file = buffer->fileName().displayName(30);
2832 if (!buffer->isUnnamed()) {
2833 text = bformat(_("The document %1$s has unsaved "
2834 "changes.\n\nDo you want to save "
2835 "the document?"), file);
2836 title = _("Save changed document?");
2839 text = bformat(_("The document %1$s has not been "
2840 "saved yet.\n\nDo you want to save "
2841 "the document?"), file);
2842 title = _("Save new document?");
2844 int const ret = Alert::prompt(title, text, 0, 1, _("&Save"), _("&Cancel"));
2847 dispatch(FuncRequest(LFUN_BUFFER_WRITE));
2849 return buffer->isClean() && !buffer->isUnnamed();
2853 bool GuiView::reloadBuffer(Buffer & buf)
2855 Buffer::ReadStatus status = buf.reload();
2856 return status == Buffer::ReadSuccess;
2860 void GuiView::checkExternallyModifiedBuffers()
2862 BufferList::iterator bit = theBufferList().begin();
2863 BufferList::iterator const bend = theBufferList().end();
2864 for (; bit != bend; ++bit) {
2865 Buffer * buf = *bit;
2866 if (buf->fileName().exists()
2867 && buf->isExternallyModified(Buffer::checksum_method)) {
2868 docstring text = bformat(_("Document \n%1$s\n has been externally modified."
2869 " Reload now? Any local changes will be lost."),
2870 from_utf8(buf->absFileName()));
2871 int const ret = Alert::prompt(_("Reload externally changed document?"),
2872 text, 0, 1, _("&Reload"), _("&Cancel"));
2880 void GuiView::dispatchVC(FuncRequest const & cmd, DispatchResult & dr)
2882 Buffer * buffer = documentBufferView()
2883 ? &(documentBufferView()->buffer()) : 0;
2885 switch (cmd.action()) {
2886 case LFUN_VC_REGISTER:
2887 if (!buffer || !ensureBufferClean(buffer))
2889 if (!buffer->lyxvc().inUse()) {
2890 if (buffer->lyxvc().registrer()) {
2891 reloadBuffer(*buffer);
2892 dr.clearMessageUpdate();
2897 case LFUN_VC_RENAME:
2898 case LFUN_VC_COPY: {
2899 if (!buffer || !ensureBufferClean(buffer))
2901 if (buffer->lyxvc().inUse() && !buffer->isReadonly()) {
2902 if (buffer->lyxvc().isCheckInWithConfirmation()) {
2903 // Some changes are not yet committed.
2904 // We test here and not in getStatus(), since
2905 // this test is expensive.
2907 LyXVC::CommandResult ret =
2908 buffer->lyxvc().checkIn(log);
2910 if (ret == LyXVC::ErrorCommand ||
2911 ret == LyXVC::VCSuccess)
2912 reloadBuffer(*buffer);
2913 if (buffer->lyxvc().isCheckInWithConfirmation()) {
2914 frontend::Alert::error(
2915 _("Revision control error."),
2916 _("Document could not be checked in."));
2920 RenameKind const kind = (cmd.action() == LFUN_VC_RENAME) ?
2921 LV_VC_RENAME : LV_VC_COPY;
2922 renameBuffer(*buffer, cmd.argument(), kind);
2927 case LFUN_VC_CHECK_IN:
2928 if (!buffer || !ensureBufferClean(buffer))
2930 if (buffer->lyxvc().inUse() && !buffer->isReadonly()) {
2932 LyXVC::CommandResult ret = buffer->lyxvc().checkIn(log);
2934 // Only skip reloading if the checkin was cancelled or
2935 // an error occured before the real checkin VCS command
2936 // was executed, since the VCS might have changed the
2937 // file even if it could not checkin successfully.
2938 if (ret == LyXVC::ErrorCommand || ret == LyXVC::VCSuccess)
2939 reloadBuffer(*buffer);
2943 case LFUN_VC_CHECK_OUT:
2944 if (!buffer || !ensureBufferClean(buffer))
2946 if (buffer->lyxvc().inUse()) {
2947 dr.setMessage(buffer->lyxvc().checkOut());
2948 reloadBuffer(*buffer);
2952 case LFUN_VC_LOCKING_TOGGLE:
2953 LASSERT(buffer, return);
2954 if (!ensureBufferClean(buffer) || buffer->isReadonly())
2956 if (buffer->lyxvc().inUse()) {
2957 string res = buffer->lyxvc().lockingToggle();
2959 frontend::Alert::error(_("Revision control error."),
2960 _("Error when setting the locking property."));
2963 reloadBuffer(*buffer);
2968 case LFUN_VC_REVERT:
2969 LASSERT(buffer, return);
2970 if (buffer->lyxvc().revert()) {
2971 reloadBuffer(*buffer);
2972 dr.clearMessageUpdate();
2976 case LFUN_VC_UNDO_LAST:
2977 LASSERT(buffer, return);
2978 buffer->lyxvc().undoLast();
2979 reloadBuffer(*buffer);
2980 dr.clearMessageUpdate();
2983 case LFUN_VC_REPO_UPDATE:
2984 LASSERT(buffer, return);
2985 if (ensureBufferClean(buffer)) {
2986 dr.setMessage(buffer->lyxvc().repoUpdate());
2987 checkExternallyModifiedBuffers();
2991 case LFUN_VC_COMMAND: {
2992 string flag = cmd.getArg(0);
2993 if (buffer && contains(flag, 'R') && !ensureBufferClean(buffer))
2996 if (contains(flag, 'M')) {
2997 if (!Alert::askForText(message, _("LyX VC: Log Message")))
3000 string path = cmd.getArg(1);
3001 if (contains(path, "$$p") && buffer)
3002 path = subst(path, "$$p", buffer->filePath());
3003 LYXERR(Debug::LYXVC, "Directory: " << path);
3005 if (!pp.isReadableDirectory()) {
3006 lyxerr << _("Directory is not accessible.") << endl;
3009 support::PathChanger p(pp);
3011 string command = cmd.getArg(2);
3012 if (command.empty())
3015 command = subst(command, "$$i", buffer->absFileName());
3016 command = subst(command, "$$p", buffer->filePath());
3018 command = subst(command, "$$m", to_utf8(message));
3019 LYXERR(Debug::LYXVC, "Command: " << command);
3021 one.startscript(Systemcall::Wait, command);
3025 if (contains(flag, 'I'))
3026 buffer->markDirty();
3027 if (contains(flag, 'R'))
3028 reloadBuffer(*buffer);
3033 case LFUN_VC_COMPARE: {
3035 if (cmd.argument().empty()) {
3036 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "comparehistory"));
3040 string rev1 = cmd.getArg(0);
3044 if (!buffer->lyxvc().prepareFileRevision(rev1, f1))
3047 if (isStrInt(rev1) && convert<int>(rev1) <= 0) {
3048 f2 = buffer->absFileName();
3050 string rev2 = cmd.getArg(1);
3054 if (!buffer->lyxvc().prepareFileRevision(rev2, f2))
3058 LYXERR(Debug::LYXVC, "Launching comparison for fetched revisions:\n" <<
3059 f1 << "\n" << f2 << "\n" );
3060 string par = "compare run " + quoteName(f1) + " " + quoteName(f2);
3061 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, par));
3071 void GuiView::openChildDocument(string const & fname)
3073 LASSERT(documentBufferView(), return);
3074 Buffer & buffer = documentBufferView()->buffer();
3075 FileName const filename = support::makeAbsPath(fname, buffer.filePath());
3076 documentBufferView()->saveBookmark(false);
3078 if (theBufferList().exists(filename)) {
3079 child = theBufferList().getBuffer(filename);
3082 message(bformat(_("Opening child document %1$s..."),
3083 makeDisplayPath(filename.absFileName())));
3084 child = loadDocument(filename, false);
3086 // Set the parent name of the child document.
3087 // This makes insertion of citations and references in the child work,
3088 // when the target is in the parent or another child document.
3090 child->setParent(&buffer);
3094 bool GuiView::goToFileRow(string const & argument)
3098 size_t i = argument.find_last_of(' ');
3099 if (i != string::npos) {
3100 file_name = os::internal_path(trim(argument.substr(0, i)));
3101 istringstream is(argument.substr(i + 1));
3106 if (i == string::npos) {
3107 LYXERR0("Wrong argument: " << argument);
3111 string const abstmp = package().temp_dir().absFileName();
3112 string const realtmp = package().temp_dir().realPath();
3113 // We have to use os::path_prefix_is() here, instead of
3114 // simply prefixIs(), because the file name comes from
3115 // an external application and may need case adjustment.
3116 if (os::path_prefix_is(file_name, abstmp, os::CASE_ADJUSTED)
3117 || os::path_prefix_is(file_name, realtmp, os::CASE_ADJUSTED)) {
3118 // Needed by inverse dvi search. If it is a file
3119 // in tmpdir, call the apropriated function.
3120 // If tmpdir is a symlink, we may have the real
3121 // path passed back, so we correct for that.
3122 if (!prefixIs(file_name, abstmp))
3123 file_name = subst(file_name, realtmp, abstmp);
3124 buf = theBufferList().getBufferFromTmp(file_name);
3126 // Must replace extension of the file to be .lyx
3127 // and get full path
3128 FileName const s = fileSearch(string(),
3129 support::changeExtension(file_name, ".lyx"), "lyx");
3130 // Either change buffer or load the file
3131 if (theBufferList().exists(s))
3132 buf = theBufferList().getBuffer(s);
3133 else if (s.exists()) {
3134 buf = loadDocument(s);
3139 _("File does not exist: %1$s"),
3140 makeDisplayPath(file_name)));
3146 _("No buffer for file: %1$s."),
3147 makeDisplayPath(file_name))
3152 documentBufferView()->setCursorFromRow(row);
3158 Buffer::ExportStatus GuiView::GuiViewPrivate::runAndDestroy(const T& func, Buffer const * orig, Buffer * clone, string const & format)
3160 Buffer::ExportStatus const status = func(format);
3162 // the cloning operation will have produced a clone of the entire set of
3163 // documents, starting from the master. so we must delete those.
3164 Buffer * mbuf = const_cast<Buffer *>(clone->masterBuffer());
3166 busyBuffers.remove(orig);
3171 Buffer::ExportStatus GuiView::GuiViewPrivate::compileAndDestroy(Buffer const * orig, Buffer * clone, string const & format)
3173 Buffer::ExportStatus (Buffer::* mem_func)(std::string const &, bool) const = &Buffer::doExport;
3174 return runAndDestroy(lyx::bind(mem_func, clone, _1, true), orig, clone, format);
3178 Buffer::ExportStatus GuiView::GuiViewPrivate::exportAndDestroy(Buffer const * orig, Buffer * clone, string const & format)
3180 Buffer::ExportStatus (Buffer::* mem_func)(std::string const &, bool) const = &Buffer::doExport;
3181 return runAndDestroy(lyx::bind(mem_func, clone, _1, false), orig, clone, format);
3185 Buffer::ExportStatus GuiView::GuiViewPrivate::previewAndDestroy(Buffer const * orig, Buffer * clone, string const & format)
3187 Buffer::ExportStatus (Buffer::* mem_func)(std::string const &) const = &Buffer::preview;
3188 return runAndDestroy(lyx::bind(mem_func, clone, _1), orig, clone, format);
3192 bool GuiView::GuiViewPrivate::asyncBufferProcessing(
3193 string const & argument,
3194 Buffer const * used_buffer,
3195 docstring const & msg,
3196 Buffer::ExportStatus (*asyncFunc)(Buffer const *, Buffer *, string const &),
3197 Buffer::ExportStatus (Buffer::*syncFunc)(string const &, bool) const,
3198 Buffer::ExportStatus (Buffer::*previewFunc)(string const &) const)
3203 string format = argument;
3205 format = used_buffer->params().getDefaultOutputFormat();
3206 processing_format = format;
3207 #if EXPORT_in_THREAD
3209 progress_->clearMessages();
3212 GuiViewPrivate::busyBuffers.insert(used_buffer);
3213 Buffer * cloned_buffer = used_buffer->cloneFromMaster();
3214 if (!cloned_buffer) {
3215 Alert::error(_("Export Error"),
3216 _("Error cloning the Buffer."));
3219 QFuture<Buffer::ExportStatus> f = QtConcurrent::run(
3224 setPreviewFuture(f);
3225 last_export_format = used_buffer->params().bufferFormat();
3228 // We are asynchronous, so we don't know here anything about the success
3231 Buffer::ExportStatus status;
3233 // TODO check here if it breaks exporting with Qt < 4.4
3234 status = (used_buffer->*syncFunc)(format, true);
3235 } else if (previewFunc) {
3236 status = (used_buffer->*previewFunc)(format);
3239 handleExportStatus(gv_, status, format);
3241 return (status == Buffer::ExportSuccess
3242 || status == Buffer::PreviewSuccess);
3246 void GuiView::dispatchToBufferView(FuncRequest const & cmd, DispatchResult & dr)
3248 BufferView * bv = currentBufferView();
3249 LASSERT(bv, return);
3251 // Let the current BufferView dispatch its own actions.
3252 bv->dispatch(cmd, dr);
3253 if (dr.dispatched())
3256 // Try with the document BufferView dispatch if any.
3257 BufferView * doc_bv = documentBufferView();
3258 if (doc_bv && doc_bv != bv) {
3259 doc_bv->dispatch(cmd, dr);
3260 if (dr.dispatched())
3264 // Then let the current Cursor dispatch its own actions.
3265 bv->cursor().dispatch(cmd);
3267 // update completion. We do it here and not in
3268 // processKeySym to avoid another redraw just for a
3269 // changed inline completion
3270 if (cmd.origin() == FuncRequest::KEYBOARD) {
3271 if (cmd.action() == LFUN_SELF_INSERT
3272 || (cmd.action() == LFUN_ERT_INSERT && bv->cursor().inMathed()))
3273 updateCompletion(bv->cursor(), true, true);
3274 else if (cmd.action() == LFUN_CHAR_DELETE_BACKWARD)
3275 updateCompletion(bv->cursor(), false, true);
3277 updateCompletion(bv->cursor(), false, false);
3280 dr = bv->cursor().result();
3284 void GuiView::dispatch(FuncRequest const & cmd, DispatchResult & dr)
3286 BufferView * bv = currentBufferView();
3287 // By default we won't need any update.
3288 dr.screenUpdate(Update::None);
3289 // assume cmd will be dispatched
3290 dr.dispatched(true);
3292 Buffer * doc_buffer = documentBufferView()
3293 ? &(documentBufferView()->buffer()) : 0;
3295 if (cmd.origin() == FuncRequest::TOC) {
3296 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
3297 // FIXME: do we need to pass a DispatchResult object here?
3298 toc->doDispatch(bv->cursor(), cmd);
3302 string const argument = to_utf8(cmd.argument());
3304 switch(cmd.action()) {
3305 case LFUN_BUFFER_CHILD_OPEN:
3306 openChildDocument(to_utf8(cmd.argument()));
3309 case LFUN_BUFFER_IMPORT:
3310 importDocument(to_utf8(cmd.argument()));
3313 case LFUN_BUFFER_EXPORT: {
3316 FileName target_dir = doc_buffer->fileName().onlyPath();
3317 string const dest = cmd.getArg(1);
3318 if (!dest.empty() && FileName::isAbsolute(dest))
3319 target_dir = FileName(support::onlyPath(dest));
3320 // GCC only sees strfwd.h when building merged
3321 if (::lyx::operator==(cmd.argument(), "custom")) {
3322 dispatch(FuncRequest(LFUN_DIALOG_SHOW, "sendto"), dr);
3325 if (!target_dir.isDirWritable()) {
3326 exportBufferAs(*doc_buffer, cmd.argument());
3329 /* TODO/Review: Is it a problem to also export the children?
3330 See the update_unincluded flag */
3331 d.asyncBufferProcessing(argument,
3334 &GuiViewPrivate::exportAndDestroy,
3337 // TODO Inform user about success
3341 case LFUN_BUFFER_EXPORT_AS: {
3342 LASSERT(doc_buffer, break);
3343 docstring f = cmd.argument();
3345 f = from_ascii(doc_buffer->params().getDefaultOutputFormat());
3346 exportBufferAs(*doc_buffer, f);
3350 case LFUN_BUFFER_UPDATE: {
3351 d.asyncBufferProcessing(argument,
3354 &GuiViewPrivate::compileAndDestroy,
3359 case LFUN_BUFFER_VIEW: {
3360 d.asyncBufferProcessing(argument,
3362 _("Previewing ..."),
3363 &GuiViewPrivate::previewAndDestroy,
3368 case LFUN_MASTER_BUFFER_UPDATE: {
3369 d.asyncBufferProcessing(argument,
3370 (doc_buffer ? doc_buffer->masterBuffer() : 0),
3372 &GuiViewPrivate::compileAndDestroy,
3377 case LFUN_MASTER_BUFFER_VIEW: {
3378 d.asyncBufferProcessing(argument,
3379 (doc_buffer ? doc_buffer->masterBuffer() : 0),
3381 &GuiViewPrivate::previewAndDestroy,
3382 0, &Buffer::preview);
3385 case LFUN_BUFFER_SWITCH: {
3386 string const file_name = to_utf8(cmd.argument());
3387 if (!FileName::isAbsolute(file_name)) {
3389 dr.setMessage(_("Absolute filename expected."));
3393 Buffer * buffer = theBufferList().getBuffer(FileName(file_name));
3396 dr.setMessage(_("Document not loaded"));
3400 // Do we open or switch to the buffer in this view ?
3401 if (workArea(*buffer)
3402 || lyxrc.open_buffers_in_tabs || !documentBufferView()) {
3407 // Look for the buffer in other views
3408 QList<int> const ids = guiApp->viewIds();
3410 for (; i != ids.size(); ++i) {
3411 GuiView & gv = guiApp->view(ids[i]);
3412 if (gv.workArea(*buffer)) {
3413 gv.activateWindow();
3414 gv.setBuffer(buffer);
3419 // If necessary, open a new window as a last resort
3420 if (i == ids.size()) {
3421 lyx::dispatch(FuncRequest(LFUN_WINDOW_NEW));
3427 case LFUN_BUFFER_NEXT:
3428 gotoNextOrPreviousBuffer(NEXTBUFFER);
3431 case LFUN_BUFFER_PREVIOUS:
3432 gotoNextOrPreviousBuffer(PREVBUFFER);
3435 case LFUN_COMMAND_EXECUTE: {
3436 bool const show_it = cmd.argument() != "off";
3437 // FIXME: this is a hack, "minibuffer" should not be
3439 if (GuiToolbar * t = toolbar("minibuffer")) {
3440 t->setVisible(show_it);
3441 if (show_it && t->commandBuffer())
3442 t->commandBuffer()->setFocus();
3446 case LFUN_DROP_LAYOUTS_CHOICE:
3447 d.layout_->showPopup();
3450 case LFUN_MENU_OPEN:
3451 if (QMenu * menu = guiApp->menus().menu(toqstr(cmd.argument()), *this))
3452 menu->exec(QCursor::pos());
3455 case LFUN_FILE_INSERT:
3456 insertLyXFile(cmd.argument());
3459 case LFUN_FILE_INSERT_PLAINTEXT:
3460 case LFUN_FILE_INSERT_PLAINTEXT_PARA: {
3461 bool const as_paragraph = (cmd.action() == LFUN_FILE_INSERT_PLAINTEXT_PARA);
3462 string const fname = to_utf8(cmd.argument());
3463 if (!fname.empty() && !FileName::isAbsolute(fname)) {
3464 dr.setMessage(_("Absolute filename expected."));
3468 FileName filename(fname);
3469 if (fname.empty()) {
3470 FileDialog dlg(qt_("Select file to insert"), (as_paragraph ?
3471 LFUN_FILE_INSERT_PLAINTEXT_PARA : LFUN_FILE_INSERT_PLAINTEXT));
3473 FileDialog::Result result = dlg.open(toqstr(bv->buffer().filePath()),
3474 QStringList(qt_("All Files (*)")));
3476 if (result.first == FileDialog::Later || result.second.isEmpty()) {
3477 dr.setMessage(_("Canceled."));
3481 filename.set(fromqstr(result.second));
3485 FuncRequest const new_cmd(cmd, filename.absoluteFilePath());
3486 bv->dispatch(new_cmd, dr);
3491 case LFUN_BUFFER_RELOAD: {
3492 LASSERT(doc_buffer, break);
3495 if (!doc_buffer->isClean()) {
3496 docstring const file =
3497 makeDisplayPath(doc_buffer->absFileName(), 20);
3498 docstring text = bformat(_("Any changes will be lost. "
3499 "Are you sure you want to revert to the saved version "
3500 "of the document %1$s?"), file);
3501 ret = Alert::prompt(_("Revert to saved document?"),
3502 text, 1, 1, _("&Revert"), _("&Cancel"));
3506 doc_buffer->markClean();
3507 reloadBuffer(*doc_buffer);
3508 dr.forceBufferUpdate();
3513 case LFUN_BUFFER_WRITE:
3514 LASSERT(doc_buffer, break);
3515 saveBuffer(*doc_buffer);
3518 case LFUN_BUFFER_WRITE_AS:
3519 LASSERT(doc_buffer, break);
3520 renameBuffer(*doc_buffer, cmd.argument());
3523 case LFUN_BUFFER_WRITE_ALL: {
3524 Buffer * first = theBufferList().first();
3527 message(_("Saving all documents..."));
3528 // We cannot use a for loop as the buffer list cycles.
3531 if (!b->isClean()) {
3533 LYXERR(Debug::ACTION, "Saved " << b->absFileName());
3535 b = theBufferList().next(b);
3536 } while (b != first);
3537 dr.setMessage(_("All documents saved."));
3541 case LFUN_BUFFER_CLOSE:
3545 case LFUN_BUFFER_CLOSE_ALL:
3549 case LFUN_TOOLBAR_TOGGLE: {
3550 string const name = cmd.getArg(0);
3551 if (GuiToolbar * t = toolbar(name))
3556 case LFUN_DIALOG_UPDATE: {
3557 string const name = to_utf8(cmd.argument());
3558 if (name == "prefs" || name == "document")
3559 updateDialog(name, string());
3560 else if (name == "paragraph")
3561 lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
3562 else if (currentBufferView()) {
3563 Inset * inset = currentBufferView()->editedInset(name);
3564 // Can only update a dialog connected to an existing inset
3566 // FIXME: get rid of this indirection; GuiView ask the inset
3567 // if he is kind enough to update itself...
3568 FuncRequest fr(LFUN_INSET_DIALOG_UPDATE, cmd.argument());
3569 //FIXME: pass DispatchResult here?
3570 inset->dispatch(currentBufferView()->cursor(), fr);
3576 case LFUN_DIALOG_TOGGLE: {
3577 FuncCode const func_code = isDialogVisible(cmd.getArg(0))
3578 ? LFUN_DIALOG_HIDE : LFUN_DIALOG_SHOW;
3579 dispatch(FuncRequest(func_code, cmd.argument()), dr);
3583 case LFUN_DIALOG_DISCONNECT_INSET:
3584 disconnectDialog(to_utf8(cmd.argument()));
3587 case LFUN_DIALOG_HIDE: {
3588 guiApp->hideDialogs(to_utf8(cmd.argument()), 0);
3592 case LFUN_DIALOG_SHOW: {
3593 string const name = cmd.getArg(0);
3594 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
3596 if (name == "character") {
3597 data = freefont2string();
3599 showDialog("character", data);
3600 } else if (name == "latexlog") {
3601 Buffer::LogType type;
3602 string const logfile = doc_buffer->logName(&type);
3604 case Buffer::latexlog:
3607 case Buffer::buildlog:
3611 data += Lexer::quoteString(logfile);
3612 showDialog("log", data);
3613 } else if (name == "vclog") {
3614 string const data = "vc " +
3615 Lexer::quoteString(doc_buffer->lyxvc().getLogFile());
3616 showDialog("log", data);
3617 } else if (name == "symbols") {
3618 data = bv->cursor().getEncoding()->name();
3620 showDialog("symbols", data);
3622 } else if (name == "prefs" && isFullScreen()) {
3623 lfunUiToggle("fullscreen");
3624 showDialog("prefs", data);
3626 showDialog(name, data);
3631 dr.setMessage(cmd.argument());
3634 case LFUN_UI_TOGGLE: {
3635 string arg = cmd.getArg(0);
3636 if (!lfunUiToggle(arg)) {
3637 docstring const msg = "ui-toggle " + _("%1$s unknown command!");
3638 dr.setMessage(bformat(msg, from_utf8(arg)));
3640 // Make sure the keyboard focus stays in the work area.
3645 case LFUN_VIEW_SPLIT: {
3646 LASSERT(doc_buffer, break);
3647 string const orientation = cmd.getArg(0);
3648 d.splitter_->setOrientation(orientation == "vertical"
3649 ? Qt::Vertical : Qt::Horizontal);
3650 TabWorkArea * twa = addTabWorkArea();
3651 GuiWorkArea * wa = twa->addWorkArea(*doc_buffer, *this);
3652 setCurrentWorkArea(wa);
3655 case LFUN_TAB_GROUP_CLOSE:
3656 if (TabWorkArea * twa = d.currentTabWorkArea()) {
3657 closeTabWorkArea(twa);
3658 d.current_work_area_ = 0;
3659 twa = d.currentTabWorkArea();
3660 // Switch to the next GuiWorkArea in the found TabWorkArea.
3662 // Make sure the work area is up to date.
3663 setCurrentWorkArea(twa->currentWorkArea());
3665 setCurrentWorkArea(0);
3670 case LFUN_VIEW_CLOSE:
3671 if (TabWorkArea * twa = d.currentTabWorkArea()) {
3672 closeWorkArea(twa->currentWorkArea());
3673 d.current_work_area_ = 0;
3674 twa = d.currentTabWorkArea();
3675 // Switch to the next GuiWorkArea in the found TabWorkArea.
3677 // Make sure the work area is up to date.
3678 setCurrentWorkArea(twa->currentWorkArea());
3680 setCurrentWorkArea(0);
3685 case LFUN_COMPLETION_INLINE:
3686 if (d.current_work_area_)
3687 d.current_work_area_->completer().showInline();
3690 case LFUN_COMPLETION_POPUP:
3691 if (d.current_work_area_)
3692 d.current_work_area_->completer().showPopup();
3697 if (d.current_work_area_)
3698 d.current_work_area_->completer().tab();
3701 case LFUN_COMPLETION_CANCEL:
3702 if (d.current_work_area_) {
3703 if (d.current_work_area_->completer().popupVisible())
3704 d.current_work_area_->completer().hidePopup();
3706 d.current_work_area_->completer().hideInline();
3710 case LFUN_COMPLETION_ACCEPT:
3711 if (d.current_work_area_)
3712 d.current_work_area_->completer().activate();
3715 case LFUN_BUFFER_ZOOM_IN:
3716 case LFUN_BUFFER_ZOOM_OUT:
3717 if (cmd.argument().empty()) {
3718 if (cmd.action() == LFUN_BUFFER_ZOOM_IN)
3723 lyxrc.zoom += convert<int>(cmd.argument());
3725 if (lyxrc.zoom < 10)
3728 // The global QPixmapCache is used in GuiPainter to cache text
3729 // painting so we must reset it.
3730 QPixmapCache::clear();
3731 guiApp->fontLoader().update();
3732 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
3735 case LFUN_VC_REGISTER:
3736 case LFUN_VC_RENAME:
3738 case LFUN_VC_CHECK_IN:
3739 case LFUN_VC_CHECK_OUT:
3740 case LFUN_VC_REPO_UPDATE:
3741 case LFUN_VC_LOCKING_TOGGLE:
3742 case LFUN_VC_REVERT:
3743 case LFUN_VC_UNDO_LAST:
3744 case LFUN_VC_COMMAND:
3745 case LFUN_VC_COMPARE:
3746 dispatchVC(cmd, dr);
3749 case LFUN_SERVER_GOTO_FILE_ROW:
3750 goToFileRow(to_utf8(cmd.argument()));
3753 case LFUN_FORWARD_SEARCH: {
3754 Buffer const * doc_master = doc_buffer->masterBuffer();
3755 FileName const path(doc_master->temppath());
3756 string const texname = doc_master->isChild(doc_buffer)
3757 ? DocFileName(changeExtension(
3758 doc_buffer->absFileName(),
3759 "tex")).mangledFileName()
3760 : doc_buffer->latexName();
3761 string const fulltexname =
3762 support::makeAbsPath(texname, doc_master->temppath()).absFileName();
3763 string const mastername =
3764 removeExtension(doc_master->latexName());
3765 FileName const dviname(addName(path.absFileName(),
3766 addExtension(mastername, "dvi")));
3767 FileName const pdfname(addName(path.absFileName(),
3768 addExtension(mastername, "pdf")));
3769 bool const have_dvi = dviname.exists();
3770 bool const have_pdf = pdfname.exists();
3771 if (!have_dvi && !have_pdf) {
3772 dr.setMessage(_("Please, preview the document first."));
3775 string outname = dviname.onlyFileName();
3776 string command = lyxrc.forward_search_dvi;
3777 if (!have_dvi || (have_pdf &&
3778 pdfname.lastModified() > dviname.lastModified())) {
3779 outname = pdfname.onlyFileName();
3780 command = lyxrc.forward_search_pdf;
3783 DocIterator tmpcur = bv->cursor();
3785 while (tmpcur.inMathed())
3787 int row = tmpcur.inMathed() ? 0 : doc_buffer->texrow().getRowFromIdPos(
3788 tmpcur.paragraph().id(), tmpcur.pos());
3789 LYXERR(Debug::ACTION, "Forward search: row:" << row
3790 << " id:" << tmpcur.paragraph().id());
3791 if (!row || command.empty()) {
3792 dr.setMessage(_("Couldn't proceed."));
3795 string texrow = convert<string>(row);
3797 command = subst(command, "$$n", texrow);
3798 command = subst(command, "$$f", fulltexname);
3799 command = subst(command, "$$t", texname);
3800 command = subst(command, "$$o", outname);
3802 PathChanger p(path);
3804 one.startscript(Systemcall::DontWait, command);
3808 case LFUN_SPELLING_CONTINUOUSLY:
3809 lyxrc.spellcheck_continuously = !lyxrc.spellcheck_continuously;
3810 dr.screenUpdate(Update::Force | Update::FitCursor);
3814 // The LFUN must be for one of BufferView, Buffer or Cursor;
3816 dispatchToBufferView(cmd, dr);
3820 // Part of automatic menu appearance feature.
3821 if (isFullScreen()) {
3822 if (menuBar()->isVisible() && lyxrc.full_screen_menubar)
3828 bool GuiView::lfunUiToggle(string const & ui_component)
3830 if (ui_component == "scrollbar") {
3831 // hide() is of no help
3832 if (d.current_work_area_->verticalScrollBarPolicy() ==
3833 Qt::ScrollBarAlwaysOff)
3835 d.current_work_area_->setVerticalScrollBarPolicy(
3836 Qt::ScrollBarAsNeeded);
3838 d.current_work_area_->setVerticalScrollBarPolicy(
3839 Qt::ScrollBarAlwaysOff);
3840 } else if (ui_component == "statusbar") {
3841 statusBar()->setVisible(!statusBar()->isVisible());
3842 } else if (ui_component == "menubar") {
3843 menuBar()->setVisible(!menuBar()->isVisible());
3845 if (ui_component == "frame") {
3847 getContentsMargins(&l, &t, &r, &b);
3848 //are the frames in default state?
3849 d.current_work_area_->setFrameStyle(QFrame::NoFrame);
3851 setContentsMargins(-2, -2, -2, -2);
3853 setContentsMargins(0, 0, 0, 0);
3856 if (ui_component == "fullscreen") {
3864 void GuiView::toggleFullScreen()
3866 if (isFullScreen()) {
3867 for (int i = 0; i != d.splitter_->count(); ++i)
3868 d.tabWorkArea(i)->setFullScreen(false);
3869 setContentsMargins(0, 0, 0, 0);
3870 setWindowState(windowState() ^ Qt::WindowFullScreen);
3873 statusBar()->show();
3876 hideDialogs("prefs", 0);
3877 for (int i = 0; i != d.splitter_->count(); ++i)
3878 d.tabWorkArea(i)->setFullScreen(true);
3879 setContentsMargins(-2, -2, -2, -2);
3881 setWindowState(windowState() ^ Qt::WindowFullScreen);
3882 if (lyxrc.full_screen_statusbar)
3883 statusBar()->hide();
3884 if (lyxrc.full_screen_menubar)
3886 if (lyxrc.full_screen_toolbars) {
3887 ToolbarMap::iterator end = d.toolbars_.end();
3888 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
3893 // give dialogs like the TOC a chance to adapt
3898 Buffer const * GuiView::updateInset(Inset const * inset)
3903 Buffer const * inset_buffer = &(inset->buffer());
3905 for (int i = 0; i != d.splitter_->count(); ++i) {
3906 GuiWorkArea * wa = d.tabWorkArea(i)->currentWorkArea();
3909 Buffer const * buffer = &(wa->bufferView().buffer());
3910 if (inset_buffer == buffer)
3911 wa->scheduleRedraw();
3913 return inset_buffer;
3917 void GuiView::restartCursor()
3919 /* When we move around, or type, it's nice to be able to see
3920 * the cursor immediately after the keypress.
3922 if (d.current_work_area_)
3923 d.current_work_area_->startBlinkingCursor();
3925 // Take this occasion to update the other GUI elements.
3931 void GuiView::updateCompletion(Cursor & cur, bool start, bool keep)
3933 if (d.current_work_area_)
3934 d.current_work_area_->completer().updateVisibility(cur, start, keep);
3939 // This list should be kept in sync with the list of insets in
3940 // src/insets/Inset.cpp. I.e., if a dialog goes with an inset, the
3941 // dialog should have the same name as the inset.
3942 // Changes should be also recorded in LFUN_DIALOG_SHOW doxygen
3943 // docs in LyXAction.cpp.
3945 char const * const dialognames[] = {
3947 "aboutlyx", "bibitem", "bibtex", "box", "branch", "changes", "character",
3948 "citation", "compare", "comparehistory", "document", "errorlist", "ert",
3949 "external", "file", "findreplace", "findreplaceadv", "float", "graphics",
3950 "href", "include", "index", "index_print", "info", "listings", "label", "line",
3951 "log", "mathdelimiter", "mathmatrix", "mathspace", "nomenclature",
3952 "nomencl_print", "note", "paragraph", "phantom", "prefs", "print", "ref",
3953 "sendto", "space", "spellchecker", "symbols", "tabular", "tabularcreate",
3954 "thesaurus", "texinfo", "toc", "view-source", "vspace", "wrap", "progress"};
3956 char const * const * const end_dialognames =
3957 dialognames + (sizeof(dialognames) / sizeof(char *));
3961 cmpCStr(char const * name) : name_(name) {}
3962 bool operator()(char const * other) {
3963 return strcmp(other, name_) == 0;
3970 bool isValidName(string const & name)
3972 return find_if(dialognames, end_dialognames,
3973 cmpCStr(name.c_str())) != end_dialognames;
3979 void GuiView::resetDialogs()
3981 // Make sure that no LFUN uses any GuiView.
3982 guiApp->setCurrentView(0);
3986 constructToolbars();
3987 guiApp->menus().fillMenuBar(menuBar(), this, false);
3988 d.layout_->updateContents(true);
3989 // Now update controls with current buffer.
3990 guiApp->setCurrentView(this);
3996 Dialog * GuiView::findOrBuild(string const & name, bool hide_it)
3998 if (!isValidName(name))
4001 map<string, DialogPtr>::iterator it = d.dialogs_.find(name);
4003 if (it != d.dialogs_.end()) {
4005 it->second->hideView();
4006 return it->second.get();
4009 Dialog * dialog = build(name);
4010 d.dialogs_[name].reset(dialog);
4011 if (lyxrc.allow_geometry_session)
4012 dialog->restoreSession();
4019 void GuiView::showDialog(string const & name, string const & data,
4022 triggerShowDialog(toqstr(name), toqstr(data), inset);
4026 void GuiView::doShowDialog(QString const & qname, QString const & qdata,
4032 const string name = fromqstr(qname);
4033 const string data = fromqstr(qdata);
4037 Dialog * dialog = findOrBuild(name, false);
4039 bool const visible = dialog->isVisibleView();
4040 dialog->showData(data);
4041 if (inset && currentBufferView())
4042 currentBufferView()->editInset(name, inset);
4043 // We only set the focus to the new dialog if it was not yet
4044 // visible in order not to change the existing previous behaviour
4046 // activateWindow is needed for floating dockviews
4047 dialog->asQWidget()->raise();
4048 dialog->asQWidget()->activateWindow();
4049 dialog->asQWidget()->setFocus();
4053 catch (ExceptionMessage const & ex) {
4061 bool GuiView::isDialogVisible(string const & name) const
4063 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
4064 if (it == d.dialogs_.end())
4066 return it->second.get()->isVisibleView() && !it->second.get()->isClosing();
4070 void GuiView::hideDialog(string const & name, Inset * inset)
4072 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
4073 if (it == d.dialogs_.end())
4077 if (!currentBufferView())
4079 if (inset != currentBufferView()->editedInset(name))
4083 Dialog * const dialog = it->second.get();
4084 if (dialog->isVisibleView())
4086 if (currentBufferView())
4087 currentBufferView()->editInset(name, 0);
4091 void GuiView::disconnectDialog(string const & name)
4093 if (!isValidName(name))
4095 if (currentBufferView())
4096 currentBufferView()->editInset(name, 0);
4100 void GuiView::hideAll() const
4102 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
4103 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
4105 for(; it != end; ++it)
4106 it->second->hideView();
4110 void GuiView::updateDialogs()
4112 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
4113 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
4115 for(; it != end; ++it) {
4116 Dialog * dialog = it->second.get();
4118 if (dialog->needBufferOpen() && !documentBufferView())
4119 hideDialog(fromqstr(dialog->name()), 0);
4120 else if (dialog->isVisibleView())
4121 dialog->checkStatus();
4128 Dialog * createDialog(GuiView & lv, string const & name);
4130 // will be replaced by a proper factory...
4131 Dialog * createGuiAbout(GuiView & lv);
4132 Dialog * createGuiBibtex(GuiView & lv);
4133 Dialog * createGuiChanges(GuiView & lv);
4134 Dialog * createGuiCharacter(GuiView & lv);
4135 Dialog * createGuiCitation(GuiView & lv);
4136 Dialog * createGuiCompare(GuiView & lv);
4137 Dialog * createGuiCompareHistory(GuiView & lv);
4138 Dialog * createGuiDelimiter(GuiView & lv);
4139 Dialog * createGuiDocument(GuiView & lv);
4140 Dialog * createGuiErrorList(GuiView & lv);
4141 Dialog * createGuiExternal(GuiView & lv);
4142 Dialog * createGuiGraphics(GuiView & lv);
4143 Dialog * createGuiInclude(GuiView & lv);
4144 Dialog * createGuiIndex(GuiView & lv);
4145 Dialog * createGuiListings(GuiView & lv);
4146 Dialog * createGuiLog(GuiView & lv);
4147 Dialog * createGuiMathMatrix(GuiView & lv);
4148 Dialog * createGuiNote(GuiView & lv);
4149 Dialog * createGuiParagraph(GuiView & lv);
4150 Dialog * createGuiPhantom(GuiView & lv);
4151 Dialog * createGuiPreferences(GuiView & lv);
4152 Dialog * createGuiPrint(GuiView & lv);
4153 Dialog * createGuiPrintindex(GuiView & lv);
4154 Dialog * createGuiRef(GuiView & lv);
4155 Dialog * createGuiSearch(GuiView & lv);
4156 Dialog * createGuiSearchAdv(GuiView & lv);
4157 Dialog * createGuiSendTo(GuiView & lv);
4158 Dialog * createGuiShowFile(GuiView & lv);
4159 Dialog * createGuiSpellchecker(GuiView & lv);
4160 Dialog * createGuiSymbols(GuiView & lv);
4161 Dialog * createGuiTabularCreate(GuiView & lv);
4162 Dialog * createGuiTexInfo(GuiView & lv);
4163 Dialog * createGuiToc(GuiView & lv);
4164 Dialog * createGuiThesaurus(GuiView & lv);
4165 Dialog * createGuiViewSource(GuiView & lv);
4166 Dialog * createGuiWrap(GuiView & lv);
4167 Dialog * createGuiProgressView(GuiView & lv);
4171 Dialog * GuiView::build(string const & name)
4173 LASSERT(isValidName(name), return 0);
4175 Dialog * dialog = createDialog(*this, name);
4179 if (name == "aboutlyx")
4180 return createGuiAbout(*this);
4181 if (name == "bibtex")
4182 return createGuiBibtex(*this);
4183 if (name == "changes")
4184 return createGuiChanges(*this);
4185 if (name == "character")
4186 return createGuiCharacter(*this);
4187 if (name == "citation")
4188 return createGuiCitation(*this);
4189 if (name == "compare")
4190 return createGuiCompare(*this);
4191 if (name == "comparehistory")
4192 return createGuiCompareHistory(*this);
4193 if (name == "document")
4194 return createGuiDocument(*this);
4195 if (name == "errorlist")
4196 return createGuiErrorList(*this);
4197 if (name == "external")
4198 return createGuiExternal(*this);
4200 return createGuiShowFile(*this);
4201 if (name == "findreplace")
4202 return createGuiSearch(*this);
4203 if (name == "findreplaceadv")
4204 return createGuiSearchAdv(*this);
4205 if (name == "graphics")
4206 return createGuiGraphics(*this);
4207 if (name == "include")
4208 return createGuiInclude(*this);
4209 if (name == "index")
4210 return createGuiIndex(*this);
4211 if (name == "index_print")
4212 return createGuiPrintindex(*this);
4213 if (name == "listings")
4214 return createGuiListings(*this);
4216 return createGuiLog(*this);
4217 if (name == "mathdelimiter")
4218 return createGuiDelimiter(*this);
4219 if (name == "mathmatrix")
4220 return createGuiMathMatrix(*this);
4222 return createGuiNote(*this);
4223 if (name == "paragraph")
4224 return createGuiParagraph(*this);
4225 if (name == "phantom")
4226 return createGuiPhantom(*this);
4227 if (name == "prefs")
4228 return createGuiPreferences(*this);
4229 if (name == "print")
4230 return createGuiPrint(*this);
4232 return createGuiRef(*this);
4233 if (name == "sendto")
4234 return createGuiSendTo(*this);
4235 if (name == "spellchecker")
4236 return createGuiSpellchecker(*this);
4237 if (name == "symbols")
4238 return createGuiSymbols(*this);
4239 if (name == "tabularcreate")
4240 return createGuiTabularCreate(*this);
4241 if (name == "texinfo")
4242 return createGuiTexInfo(*this);
4243 if (name == "thesaurus")
4244 return createGuiThesaurus(*this);
4246 return createGuiToc(*this);
4247 if (name == "view-source")
4248 return createGuiViewSource(*this);
4250 return createGuiWrap(*this);
4251 if (name == "progress")
4252 return createGuiProgressView(*this);
4258 } // namespace frontend
4261 #include "moc_GuiView.cpp"