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"
63 #include "TextClass.h"
68 #include "support/convert.h"
69 #include "support/debug.h"
70 #include "support/ExceptionMessage.h"
71 #include "support/FileName.h"
72 #include "support/filetools.h"
73 #include "support/gettext.h"
74 #include "support/filetools.h"
75 #include "support/ForkedCalls.h"
76 #include "support/lassert.h"
77 #include "support/lstrings.h"
78 #include "support/os.h"
79 #include "support/Package.h"
80 #include "support/PathChanger.h"
81 #include "support/Systemcall.h"
82 #include "support/Timeout.h"
83 #include "support/ProgressInterface.h"
86 #include <QApplication>
87 #include <QCloseEvent>
89 #include <QDesktopWidget>
90 #include <QDragEnterEvent>
93 #include <QFutureWatcher>
102 #include <QPixmapCache>
104 #include <QPushButton>
105 #include <QScrollBar>
107 #include <QShowEvent>
109 #include <QStackedWidget>
110 #include <QStatusBar>
111 #include <QtConcurrentRun>
119 #define EXPORT_in_THREAD 1
122 #include "support/bind.h"
126 #ifdef HAVE_SYS_TIME_H
127 # include <sys/time.h>
135 using namespace lyx::support;
139 using support::addExtension;
140 using support::changeExtension;
141 using support::removeExtension;
147 class BackgroundWidget : public QWidget
152 LYXERR(Debug::GUI, "show banner: " << lyxrc.show_banner);
153 if (!lyxrc.show_banner)
155 /// The text to be written on top of the pixmap
156 QString const text = lyx_version ?
157 qt_("version ") + lyx_version : qt_("unknown version");
158 splash_ = getPixmap("images/", "banner", "png");
160 QPainter pain(&splash_);
161 pain.setPen(QColor(0, 0, 0));
163 // The font used to display the version info
164 font.setStyleHint(QFont::SansSerif);
165 font.setWeight(QFont::Bold);
166 font.setPointSize(int(toqstr(lyxrc.font_sizes[FONT_SIZE_LARGE]).toDouble()));
168 pain.drawText(190, 225, text);
169 setFocusPolicy(Qt::StrongFocus);
172 void paintEvent(QPaintEvent *)
174 int x = (width() - splash_.width()) / 2;
175 int y = (height() - splash_.height()) / 2;
177 pain.drawPixmap(x, y, splash_);
180 void keyPressEvent(QKeyEvent * ev)
183 setKeySymbol(&sym, ev);
185 guiApp->processKeySym(sym, q_key_state(ev->modifiers()));
197 /// Toolbar store providing access to individual toolbars by name.
198 typedef map<string, GuiToolbar *> ToolbarMap;
200 typedef shared_ptr<Dialog> DialogPtr;
205 struct GuiView::GuiViewPrivate
207 GuiViewPrivate(GuiView * gv)
208 : gv_(gv), current_work_area_(0), current_main_work_area_(0),
209 layout_(0), autosave_timeout_(5000),
212 // hardcode here the platform specific icon size
213 smallIconSize = 16; // scaling problems
214 normalIconSize = 20; // ok, default if iconsize.png is missing
215 bigIconSize = 26; // better for some math icons
217 // if it exists, use width of iconsize.png as normal size
218 QString const dir = toqstr(addPath("images", lyxrc.icon_set));
219 FileName const fn = lyx::libFileSearch(dir, "iconsize.png");
221 QImage image(toqstr(fn.absFileName()));
222 if (image.width() < int(smallIconSize))
223 normalIconSize = smallIconSize;
224 else if (image.width() > int(bigIconSize))
225 normalIconSize = bigIconSize;
227 normalIconSize = image.width();
230 splitter_ = new QSplitter;
231 bg_widget_ = new BackgroundWidget;
232 stack_widget_ = new QStackedWidget;
233 stack_widget_->addWidget(bg_widget_);
234 stack_widget_->addWidget(splitter_);
237 // TODO cleanup, remove the singleton, handle multiple Windows?
238 progress_ = ProgressInterface::instance();
239 if (!dynamic_cast<GuiProgress*>(progress_)) {
240 progress_ = new GuiProgress; // TODO who deletes it
241 ProgressInterface::setInstance(progress_);
244 dynamic_cast<GuiProgress*>(progress_),
245 SIGNAL(updateStatusBarMessage(QString const&)),
246 gv, SLOT(updateStatusBarMessage(QString const&)));
248 dynamic_cast<GuiProgress*>(progress_),
249 SIGNAL(clearMessageText()),
250 gv, SLOT(clearMessageText()));
257 delete stack_widget_;
260 QMenu * toolBarPopup(GuiView * parent)
262 // FIXME: translation
263 QMenu * menu = new QMenu(parent);
264 QActionGroup * iconSizeGroup = new QActionGroup(parent);
266 QAction * smallIcons = new QAction(iconSizeGroup);
267 smallIcons->setText(qt_("Small-sized icons"));
268 smallIcons->setCheckable(true);
269 QObject::connect(smallIcons, SIGNAL(triggered()),
270 parent, SLOT(smallSizedIcons()));
271 menu->addAction(smallIcons);
273 QAction * normalIcons = new QAction(iconSizeGroup);
274 normalIcons->setText(qt_("Normal-sized icons"));
275 normalIcons->setCheckable(true);
276 QObject::connect(normalIcons, SIGNAL(triggered()),
277 parent, SLOT(normalSizedIcons()));
278 menu->addAction(normalIcons);
280 QAction * bigIcons = new QAction(iconSizeGroup);
281 bigIcons->setText(qt_("Big-sized icons"));
282 bigIcons->setCheckable(true);
283 QObject::connect(bigIcons, SIGNAL(triggered()),
284 parent, SLOT(bigSizedIcons()));
285 menu->addAction(bigIcons);
287 unsigned int cur = parent->iconSize().width();
288 if ( cur == parent->d.smallIconSize)
289 smallIcons->setChecked(true);
290 else if (cur == parent->d.normalIconSize)
291 normalIcons->setChecked(true);
292 else if (cur == parent->d.bigIconSize)
293 bigIcons->setChecked(true);
300 stack_widget_->setCurrentWidget(bg_widget_);
301 bg_widget_->setUpdatesEnabled(true);
302 bg_widget_->setFocus();
305 int tabWorkAreaCount()
307 return splitter_->count();
310 TabWorkArea * tabWorkArea(int i)
312 return dynamic_cast<TabWorkArea *>(splitter_->widget(i));
315 TabWorkArea * currentTabWorkArea()
317 int areas = tabWorkAreaCount();
319 // The first TabWorkArea is always the first one, if any.
320 return tabWorkArea(0);
322 for (int i = 0; i != areas; ++i) {
323 TabWorkArea * twa = tabWorkArea(i);
324 if (current_main_work_area_ == twa->currentWorkArea())
328 // None has the focus so we just take the first one.
329 return tabWorkArea(0);
332 int countWorkAreasOf(Buffer & buf)
334 int areas = tabWorkAreaCount();
336 for (int i = 0; i != areas; ++i) {
337 TabWorkArea * twa = tabWorkArea(i);
338 if (twa->workArea(buf))
344 void setPreviewFuture(QFuture<Buffer::ExportStatus> const & f)
346 if (processing_thread_watcher_.isRunning()) {
347 // we prefer to cancel this preview in order to keep a snappy
351 processing_thread_watcher_.setFuture(f);
356 GuiWorkArea * current_work_area_;
357 GuiWorkArea * current_main_work_area_;
358 QSplitter * splitter_;
359 QStackedWidget * stack_widget_;
360 BackgroundWidget * bg_widget_;
362 ToolbarMap toolbars_;
363 ProgressInterface* progress_;
364 /// The main layout box.
366 * \warning Don't Delete! The layout box is actually owned by
367 * whichever toolbar contains it. All the GuiView class needs is a
368 * means of accessing it.
370 * FIXME: replace that with a proper model so that we are not limited
371 * to only one dialog.
376 map<string, DialogPtr> dialogs_;
378 unsigned int smallIconSize;
379 unsigned int normalIconSize;
380 unsigned int bigIconSize;
382 QTimer statusbar_timer_;
383 /// auto-saving of buffers
384 Timeout autosave_timeout_;
385 /// flag against a race condition due to multiclicks, see bug #1119
389 TocModels toc_models_;
392 QFutureWatcher<docstring> autosave_watcher_;
393 QFutureWatcher<Buffer::ExportStatus> processing_thread_watcher_;
395 string last_export_format;
396 string processing_format;
398 static QSet<Buffer const *> busyBuffers;
399 static Buffer::ExportStatus previewAndDestroy(Buffer const * orig, Buffer * buffer, string const & format);
400 static Buffer::ExportStatus exportAndDestroy(Buffer const * orig, Buffer * buffer, string const & format);
401 static Buffer::ExportStatus compileAndDestroy(Buffer const * orig, Buffer * buffer, string const & format);
402 static docstring autosaveAndDestroy(Buffer const * orig, Buffer * buffer);
405 static Buffer::ExportStatus runAndDestroy(const T& func, Buffer const * orig, Buffer * buffer, string const & format);
407 // TODO syncFunc/previewFunc: use bind
408 bool asyncBufferProcessing(string const & argument,
409 Buffer const * used_buffer,
410 docstring const & msg,
411 Buffer::ExportStatus (*asyncFunc)(Buffer const *, Buffer *, string const &),
412 Buffer::ExportStatus (Buffer::*syncFunc)(string const &, bool) const,
413 Buffer::ExportStatus (Buffer::*previewFunc)(string const &) const);
415 QVector<GuiWorkArea*> guiWorkAreas();
418 QSet<Buffer const *> GuiView::GuiViewPrivate::busyBuffers;
421 GuiView::GuiView(int id)
422 : d(*new GuiViewPrivate(this)), id_(id), closing_(false), busy_(0)
424 // GuiToolbars *must* be initialised before the menu bar.
425 normalSizedIcons(); // at least on Mac the default is 32 otherwise, which is huge
428 // set ourself as the current view. This is needed for the menu bar
429 // filling, at least for the static special menu item on Mac. Otherwise
430 // they are greyed out.
431 guiApp->setCurrentView(this);
433 // Fill up the menu bar.
434 guiApp->menus().fillMenuBar(menuBar(), this, true);
436 setCentralWidget(d.stack_widget_);
438 // Start autosave timer
439 if (lyxrc.autosave) {
440 d.autosave_timeout_.timeout.connect(bind(&GuiView::autoSave, this));
441 d.autosave_timeout_.setTimeout(lyxrc.autosave * 1000);
442 d.autosave_timeout_.start();
444 connect(&d.statusbar_timer_, SIGNAL(timeout()),
445 this, SLOT(clearMessage()));
447 // We don't want to keep the window in memory if it is closed.
448 setAttribute(Qt::WA_DeleteOnClose, true);
450 #if (!defined(Q_WS_WIN) && !defined(Q_WS_MACX))
451 // QIcon::fromTheme was introduced in Qt 4.6
452 #if (QT_VERSION >= 0x040600)
453 // assign an icon to main form. We do not do it under Qt/Win or Qt/Mac,
454 // since the icon is provided in the application bundle. We use a themed
455 // version when available and use the bundled one as fallback.
456 setWindowIcon(QIcon::fromTheme("lyx", getPixmap("images/", "lyx", "png")));
458 setWindowIcon(getPixmap("images/", "lyx", "png"));
462 resetWindowTitleAndIconText();
464 // use tabbed dock area for multiple docks
465 // (such as "source" and "messages")
466 setDockOptions(QMainWindow::ForceTabbedDocks);
469 setAcceptDrops(true);
471 // add busy indicator to statusbar
472 QLabel * busylabel = new QLabel(statusBar());
473 statusBar()->addPermanentWidget(busylabel);
474 QString fn = toqstr(lyx::libFileSearch("images", "busy.gif").absFileName());
475 QMovie * busyanim = new QMovie(fn, QByteArray(), busylabel);
476 busylabel->setMovie(busyanim);
480 connect(&d.processing_thread_watcher_, SIGNAL(started()),
481 busylabel, SLOT(show()));
482 connect(&d.processing_thread_watcher_, SIGNAL(finished()),
483 busylabel, SLOT(hide()));
485 statusBar()->setSizeGripEnabled(true);
488 connect(&d.autosave_watcher_, SIGNAL(finished()), this,
489 SLOT(autoSaveThreadFinished()));
491 connect(&d.processing_thread_watcher_, SIGNAL(started()), this,
492 SLOT(processingThreadStarted()));
493 connect(&d.processing_thread_watcher_, SIGNAL(finished()), this,
494 SLOT(processingThreadFinished()));
496 connect(this, SIGNAL(triggerShowDialog(QString const &, QString const &, Inset *)),
497 SLOT(doShowDialog(QString const &, QString const &, Inset *)));
499 // Forbid too small unresizable window because it can happen
500 // with some window manager under X11.
501 setMinimumSize(300, 200);
503 if (lyxrc.allow_geometry_session) {
504 // Now take care of session management.
509 // no session handling, default to a sane size.
510 setGeometry(50, 50, 690, 510);
513 // clear session data if any.
515 settings.remove("views");
525 QVector<GuiWorkArea*> GuiView::GuiViewPrivate::guiWorkAreas()
527 QVector<GuiWorkArea*> areas;
528 for (int i = 0; i < tabWorkAreaCount(); i++) {
529 TabWorkArea* ta = tabWorkArea(i);
530 for (int u = 0; u < ta->count(); u++) {
531 areas << ta->workArea(u);
537 static void handleExportStatus(GuiView * view, Buffer::ExportStatus status,
538 string const & format)
540 docstring const fmt = formats.prettyName(format);
543 case Buffer::ExportSuccess:
544 msg = bformat(_("Successful export to format: %1$s"), fmt);
546 case Buffer::ExportCancel:
547 msg = _("Document export cancelled.");
549 case Buffer::ExportError:
550 case Buffer::ExportNoPathToFormat:
551 case Buffer::ExportTexPathHasSpaces:
552 case Buffer::ExportConverterError:
553 msg = bformat(_("Error while exporting format: %1$s"), fmt);
555 case Buffer::PreviewSuccess:
556 msg = bformat(_("Successful preview of format: %1$s"), fmt);
558 case Buffer::PreviewError:
559 msg = bformat(_("Error while previewing format: %1$s"), fmt);
566 void GuiView::processingThreadStarted()
571 void GuiView::processingThreadFinished()
573 QFutureWatcher<Buffer::ExportStatus> const * watcher =
574 static_cast<QFutureWatcher<Buffer::ExportStatus> const *>(sender());
576 Buffer::ExportStatus const status = watcher->result();
577 handleExportStatus(this, status, d.processing_format);
580 BufferView const * const bv = currentBufferView();
581 if (bv && !bv->buffer().errorList("Export").empty()) {
585 errors(d.last_export_format);
589 void GuiView::autoSaveThreadFinished()
591 QFutureWatcher<docstring> const * watcher =
592 static_cast<QFutureWatcher<docstring> const *>(sender());
593 message(watcher->result());
598 void GuiView::saveLayout() const
601 settings.beginGroup("views");
602 settings.beginGroup(QString::number(id_));
604 settings.setValue("pos", pos());
605 settings.setValue("size", size());
607 settings.setValue("geometry", saveGeometry());
609 settings.setValue("layout", saveState(0));
610 settings.setValue("icon_size", iconSize());
614 void GuiView::saveUISettings() const
616 // Save the toolbar private states
617 ToolbarMap::iterator end = d.toolbars_.end();
618 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
619 it->second->saveSession();
620 // Now take care of all other dialogs
621 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
622 for (; it!= d.dialogs_.end(); ++it)
623 it->second->saveSession();
627 bool GuiView::restoreLayout()
630 settings.beginGroup("views");
631 settings.beginGroup(QString::number(id_));
632 QString const icon_key = "icon_size";
633 if (!settings.contains(icon_key))
636 //code below is skipped when when ~/.config/LyX is (re)created
637 QSize icon_size = settings.value(icon_key).toSize();
638 // Check whether session size changed.
639 if (icon_size.width() != int(d.smallIconSize) &&
640 icon_size.width() != int(d.normalIconSize) &&
641 icon_size.width() != int(d.bigIconSize)) {
642 icon_size.setWidth(d.normalIconSize);
643 icon_size.setHeight(d.normalIconSize);
645 setIconSize(icon_size);
648 QPoint pos = settings.value("pos", QPoint(50, 50)).toPoint();
649 QSize size = settings.value("size", QSize(690, 510)).toSize();
653 // Work-around for bug #6034: the window ends up in an undetermined
654 // state when trying to restore a maximized window when it is
655 // already maximized.
656 if (!(windowState() & Qt::WindowMaximized))
657 if (!restoreGeometry(settings.value("geometry").toByteArray()))
658 setGeometry(50, 50, 690, 510);
660 // Make sure layout is correctly oriented.
661 setLayoutDirection(qApp->layoutDirection());
663 // Allow the toc and view-source dock widget to be restored if needed.
665 if ((dialog = findOrBuild("toc", true)))
666 // see bug 5082. At least setup title and enabled state.
667 // Visibility will be adjusted by restoreState below.
668 dialog->prepareView();
669 if ((dialog = findOrBuild("view-source", true)))
670 dialog->prepareView();
671 if ((dialog = findOrBuild("progress", true)))
672 dialog->prepareView();
673 if ((dialog = findOrBuild("findreplaceadv", true)))
674 dialog->prepareView();
676 if (!restoreState(settings.value("layout").toByteArray(), 0))
679 // init the toolbars that have not been restored
680 Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
681 Toolbars::Infos::iterator end = guiApp->toolbars().end();
682 for (; cit != end; ++cit) {
683 GuiToolbar * tb = toolbar(cit->name);
684 if (tb && !tb->isRestored())
685 initToolbar(cit->name);
693 GuiToolbar * GuiView::toolbar(string const & name)
695 ToolbarMap::iterator it = d.toolbars_.find(name);
696 if (it != d.toolbars_.end())
699 LYXERR(Debug::GUI, "Toolbar::display: no toolbar named " << name);
704 void GuiView::constructToolbars()
706 ToolbarMap::iterator it = d.toolbars_.begin();
707 for (; it != d.toolbars_.end(); ++it)
711 // I don't like doing this here, but the standard toolbar
712 // destroys this object when it's destroyed itself (vfr)
713 d.layout_ = new LayoutBox(*this);
714 d.stack_widget_->addWidget(d.layout_);
715 d.layout_->move(0,0);
717 // extracts the toolbars from the backend
718 Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
719 Toolbars::Infos::iterator end = guiApp->toolbars().end();
720 for (; cit != end; ++cit)
721 d.toolbars_[cit->name] = new GuiToolbar(*cit, *this);
725 void GuiView::initToolbars()
727 // extracts the toolbars from the backend
728 Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
729 Toolbars::Infos::iterator end = guiApp->toolbars().end();
730 for (; cit != end; ++cit)
731 initToolbar(cit->name);
735 void GuiView::initToolbar(string const & name)
737 GuiToolbar * tb = toolbar(name);
740 int const visibility = guiApp->toolbars().defaultVisibility(name);
741 bool newline = !(visibility & Toolbars::SAMEROW);
742 tb->setVisible(false);
743 tb->setVisibility(visibility);
745 if (visibility & Toolbars::TOP) {
747 addToolBarBreak(Qt::TopToolBarArea);
748 addToolBar(Qt::TopToolBarArea, tb);
751 if (visibility & Toolbars::BOTTOM) {
753 addToolBarBreak(Qt::BottomToolBarArea);
754 addToolBar(Qt::BottomToolBarArea, tb);
757 if (visibility & Toolbars::LEFT) {
759 addToolBarBreak(Qt::LeftToolBarArea);
760 addToolBar(Qt::LeftToolBarArea, tb);
763 if (visibility & Toolbars::RIGHT) {
765 addToolBarBreak(Qt::RightToolBarArea);
766 addToolBar(Qt::RightToolBarArea, tb);
769 if (visibility & Toolbars::ON)
770 tb->setVisible(true);
774 TocModels & GuiView::tocModels()
776 return d.toc_models_;
780 void GuiView::setFocus()
782 LYXERR(Debug::DEBUG, "GuiView::setFocus()" << this);
783 QMainWindow::setFocus();
787 void GuiView::focusInEvent(QFocusEvent * e)
789 LYXERR(Debug::DEBUG, "GuiView::focusInEvent()" << this);
790 QMainWindow::focusInEvent(e);
791 // Make sure guiApp points to the correct view.
792 guiApp->setCurrentView(this);
793 if (currentWorkArea())
794 currentWorkArea()->setFocus();
795 else if (currentMainWorkArea())
796 currentMainWorkArea()->setFocus();
798 d.bg_widget_->setFocus();
802 QMenu * GuiView::createPopupMenu()
804 return d.toolBarPopup(this);
808 void GuiView::showEvent(QShowEvent * e)
810 LYXERR(Debug::GUI, "Passed Geometry "
811 << size().height() << "x" << size().width()
812 << "+" << pos().x() << "+" << pos().y());
814 if (d.splitter_->count() == 0)
815 // No work area, switch to the background widget.
819 QMainWindow::showEvent(e);
823 bool GuiView::closeScheduled()
830 /** Destroy only all tabbed WorkAreas. Destruction of other WorkAreas
831 ** is responsibility of the container (e.g., dialog)
833 void GuiView::closeEvent(QCloseEvent * close_event)
835 LYXERR(Debug::DEBUG, "GuiView::closeEvent()");
837 if (!GuiViewPrivate::busyBuffers.isEmpty()) {
838 Alert::warning(_("Exit LyX"),
839 _("LyX could not be closed because documents are being processed by LyX."));
840 close_event->setAccepted(false);
844 // If the user pressed the x (so we didn't call closeView
845 // programmatically), we want to clear all existing entries.
847 theSession().lastOpened().clear();
852 // it can happen that this event arrives without selecting the view,
853 // e.g. when clicking the close button on a background window.
855 if (!closeWorkAreaAll()) {
857 close_event->ignore();
861 // Make sure that nothing will use this to be closed View.
862 guiApp->unregisterView(this);
864 if (isFullScreen()) {
865 // Switch off fullscreen before closing.
870 // Make sure the timer time out will not trigger a statusbar update.
871 d.statusbar_timer_.stop();
873 // Saving fullscreen requires additional tweaks in the toolbar code.
874 // It wouldn't also work under linux natively.
875 if (lyxrc.allow_geometry_session) {
880 close_event->accept();
884 void GuiView::dragEnterEvent(QDragEnterEvent * event)
886 if (event->mimeData()->hasUrls())
888 /// \todo Ask lyx-devel is this is enough:
889 /// if (event->mimeData()->hasFormat("text/plain"))
890 /// event->acceptProposedAction();
894 void GuiView::dropEvent(QDropEvent * event)
896 QList<QUrl> files = event->mimeData()->urls();
900 LYXERR(Debug::GUI, "GuiView::dropEvent: got URLs!");
901 for (int i = 0; i != files.size(); ++i) {
902 string const file = os::internal_path(fromqstr(
903 files.at(i).toLocalFile()));
907 string const ext = support::getExtension(file);
908 vector<const Format *> found_formats;
910 // Find all formats that have the correct extension.
911 vector<const Format *> const & import_formats
912 = theConverters().importableFormats();
913 vector<const Format *>::const_iterator it = import_formats.begin();
914 for (; it != import_formats.end(); ++it)
915 if ((*it)->hasExtension(ext))
916 found_formats.push_back(*it);
919 if (found_formats.size() >= 1) {
920 if (found_formats.size() > 1) {
921 //FIXME: show a dialog to choose the correct importable format
923 "Multiple importable formats found, selecting first");
925 string const arg = found_formats[0]->name() + " " + file;
926 cmd = FuncRequest(LFUN_BUFFER_IMPORT, arg);
929 //FIXME: do we have to explicitly check whether it's a lyx file?
931 "No formats found, trying to open it as a lyx file");
932 cmd = FuncRequest(LFUN_FILE_OPEN, file);
934 // add the functions to the queue
935 guiApp->addToFuncRequestQueue(cmd);
938 // now process the collected functions. We perform the events
939 // asynchronously. This prevents potential problems in case the
940 // BufferView is closed within an event.
941 guiApp->processFuncRequestQueueAsync();
945 void GuiView::message(docstring const & str)
947 if (ForkedProcess::iAmAChild())
950 // call is moved to GUI-thread by GuiProgress
951 d.progress_->appendMessage(toqstr(str));
955 void GuiView::clearMessageText()
957 message(docstring());
961 void GuiView::updateStatusBarMessage(QString const & str)
963 statusBar()->showMessage(str);
964 d.statusbar_timer_.stop();
965 d.statusbar_timer_.start(3000);
969 void GuiView::smallSizedIcons()
971 setIconSize(QSize(d.smallIconSize, d.smallIconSize));
975 void GuiView::normalSizedIcons()
977 setIconSize(QSize(d.normalIconSize, d.normalIconSize));
981 void GuiView::bigSizedIcons()
983 setIconSize(QSize(d.bigIconSize, d.bigIconSize));
987 void GuiView::clearMessage()
989 // FIXME: This code was introduced in r19643 to fix bug #4123. However,
990 // the hasFocus function mostly returns false, even if the focus is on
991 // a workarea in this view.
995 d.statusbar_timer_.stop();
999 void GuiView::updateWindowTitle(GuiWorkArea * wa)
1001 if (wa != d.current_work_area_
1002 || wa->bufferView().buffer().isInternal())
1004 setWindowTitle(qt_("LyX: ") + wa->windowTitle());
1005 setWindowIconText(wa->windowIconText());
1009 void GuiView::on_currentWorkAreaChanged(GuiWorkArea * wa)
1011 if (d.current_work_area_)
1012 QObject::disconnect(d.current_work_area_, SIGNAL(busy(bool)),
1013 this, SLOT(setBusy(bool)));
1015 disconnectBufferView();
1016 connectBufferView(wa->bufferView());
1017 connectBuffer(wa->bufferView().buffer());
1018 d.current_work_area_ = wa;
1019 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
1020 this, SLOT(updateWindowTitle(GuiWorkArea *)));
1021 QObject::connect(wa, SIGNAL(busy(bool)), this, SLOT(setBusy(bool)));
1022 updateWindowTitle(wa);
1026 // The document settings needs to be reinitialised.
1027 updateDialog("document", "");
1029 // Buffer-dependent dialogs must be updated. This is done here because
1030 // some dialogs require buffer()->text.
1035 void GuiView::on_lastWorkAreaRemoved()
1038 // We already are in a close event. Nothing more to do.
1041 if (d.splitter_->count() > 1)
1042 // We have a splitter so don't close anything.
1045 // Reset and updates the dialogs.
1046 d.toc_models_.reset(0);
1047 updateDialog("document", "");
1050 resetWindowTitleAndIconText();
1053 if (lyxrc.open_buffers_in_tabs)
1054 // Nothing more to do, the window should stay open.
1057 if (guiApp->viewIds().size() > 1) {
1063 // On Mac we also close the last window because the application stay
1064 // resident in memory. On other platforms we don't close the last
1065 // window because this would quit the application.
1071 void GuiView::updateStatusBar()
1073 // let the user see the explicit message
1074 if (d.statusbar_timer_.isActive())
1081 void GuiView::showMessage()
1085 QString msg = toqstr(theGuiApp()->viewStatusMessage());
1086 if (msg.isEmpty()) {
1087 BufferView const * bv = currentBufferView();
1089 msg = toqstr(bv->cursor().currentState());
1091 msg = qt_("Welcome to LyX!");
1093 statusBar()->showMessage(msg);
1097 bool GuiView::event(QEvent * e)
1101 // Useful debug code:
1102 //case QEvent::ActivationChange:
1103 //case QEvent::WindowDeactivate:
1104 //case QEvent::Paint:
1105 //case QEvent::Enter:
1106 //case QEvent::Leave:
1107 //case QEvent::HoverEnter:
1108 //case QEvent::HoverLeave:
1109 //case QEvent::HoverMove:
1110 //case QEvent::StatusTip:
1111 //case QEvent::DragEnter:
1112 //case QEvent::DragLeave:
1113 //case QEvent::Drop:
1116 case QEvent::WindowActivate: {
1117 GuiView * old_view = guiApp->currentView();
1118 if (this == old_view) {
1120 return QMainWindow::event(e);
1122 if (old_view && old_view->currentBufferView()) {
1123 // save current selection to the selection buffer to allow
1124 // middle-button paste in this window.
1125 cap::saveSelection(old_view->currentBufferView()->cursor());
1127 guiApp->setCurrentView(this);
1128 if (d.current_work_area_) {
1129 BufferView & bv = d.current_work_area_->bufferView();
1130 connectBufferView(bv);
1131 connectBuffer(bv.buffer());
1132 // The document structure, name and dialogs might have
1133 // changed in another view.
1135 // The document settings needs to be reinitialised.
1136 updateDialog("document", "");
1139 resetWindowTitleAndIconText();
1142 return QMainWindow::event(e);
1145 case QEvent::ShortcutOverride: {
1147 if (isFullScreen() && menuBar()->isHidden()) {
1148 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
1149 // FIXME: we should also try to detect special LyX shortcut such as
1150 // Alt-P and Alt-M. Right now there is a hack in
1151 // GuiWorkArea::processKeySym() that hides again the menubar for
1153 if (ke->modifiers() & Qt::AltModifier && ke->key() != Qt::Key_Alt) {
1155 return QMainWindow::event(e);
1158 return QMainWindow::event(e);
1162 return QMainWindow::event(e);
1166 void GuiView::resetWindowTitleAndIconText()
1168 setWindowTitle(qt_("LyX"));
1169 setWindowIconText(qt_("LyX"));
1172 bool GuiView::focusNextPrevChild(bool /*next*/)
1179 bool GuiView::busy() const
1185 void GuiView::setBusy(bool busy)
1187 bool const busy_before = busy_ > 0;
1188 busy ? ++busy_ : --busy_;
1189 if ((busy_ > 0) == busy_before)
1190 // busy state didn't change
1194 QApplication::setOverrideCursor(Qt::WaitCursor);
1197 QApplication::restoreOverrideCursor();
1202 GuiWorkArea * GuiView::workArea(int index)
1204 if (TabWorkArea * twa = d.currentTabWorkArea())
1205 if (index < twa->count())
1206 return dynamic_cast<GuiWorkArea *>(twa->widget(index));
1211 GuiWorkArea * GuiView::workArea(Buffer & buffer)
1213 if (currentWorkArea()
1214 && ¤tWorkArea()->bufferView().buffer() == &buffer)
1215 return (GuiWorkArea *) currentWorkArea();
1216 if (TabWorkArea * twa = d.currentTabWorkArea())
1217 return twa->workArea(buffer);
1222 GuiWorkArea * GuiView::addWorkArea(Buffer & buffer)
1224 // Automatically create a TabWorkArea if there are none yet.
1225 TabWorkArea * tab_widget = d.splitter_->count()
1226 ? d.currentTabWorkArea() : addTabWorkArea();
1227 return tab_widget->addWorkArea(buffer, *this);
1231 TabWorkArea * GuiView::addTabWorkArea()
1233 TabWorkArea * twa = new TabWorkArea;
1234 QObject::connect(twa, SIGNAL(currentWorkAreaChanged(GuiWorkArea *)),
1235 this, SLOT(on_currentWorkAreaChanged(GuiWorkArea *)));
1236 QObject::connect(twa, SIGNAL(lastWorkAreaRemoved()),
1237 this, SLOT(on_lastWorkAreaRemoved()));
1239 d.splitter_->addWidget(twa);
1240 d.stack_widget_->setCurrentWidget(d.splitter_);
1245 GuiWorkArea const * GuiView::currentWorkArea() const
1247 return d.current_work_area_;
1251 GuiWorkArea * GuiView::currentWorkArea()
1253 return d.current_work_area_;
1257 GuiWorkArea const * GuiView::currentMainWorkArea() const
1259 if (!d.currentTabWorkArea())
1261 return d.currentTabWorkArea()->currentWorkArea();
1265 GuiWorkArea * GuiView::currentMainWorkArea()
1267 if (!d.currentTabWorkArea())
1269 return d.currentTabWorkArea()->currentWorkArea();
1273 void GuiView::setCurrentWorkArea(GuiWorkArea * wa)
1275 LYXERR(Debug::DEBUG, "Setting current wa: " << wa << endl);
1277 d.current_work_area_ = 0;
1282 // FIXME: I've no clue why this is here and why it accesses
1283 // theGuiApp()->currentView, which might be 0 (bug 6464).
1284 // See also 27525 (vfr).
1285 if (theGuiApp()->currentView() == this
1286 && theGuiApp()->currentView()->currentWorkArea() == wa)
1289 if (currentBufferView())
1290 cap::saveSelection(currentBufferView()->cursor());
1292 theGuiApp()->setCurrentView(this);
1293 d.current_work_area_ = wa;
1295 // We need to reset this now, because it will need to be
1296 // right if the tabWorkArea gets reset in the for loop. We
1297 // will change it back if we aren't in that case.
1298 GuiWorkArea * const old_cmwa = d.current_main_work_area_;
1299 d.current_main_work_area_ = wa;
1301 for (int i = 0; i != d.splitter_->count(); ++i) {
1302 if (d.tabWorkArea(i)->setCurrentWorkArea(wa)) {
1303 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea()
1304 << ", Current main wa: " << currentMainWorkArea());
1309 d.current_main_work_area_ = old_cmwa;
1311 LYXERR(Debug::DEBUG, "This is not a tabbed wa");
1312 on_currentWorkAreaChanged(wa);
1313 BufferView & bv = wa->bufferView();
1314 bv.cursor().fixIfBroken();
1316 wa->setUpdatesEnabled(true);
1317 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() << ", Current main wa: " << currentMainWorkArea());
1321 void GuiView::removeWorkArea(GuiWorkArea * wa)
1323 LASSERT(wa, return);
1324 if (wa == d.current_work_area_) {
1326 disconnectBufferView();
1327 d.current_work_area_ = 0;
1328 d.current_main_work_area_ = 0;
1331 bool found_twa = false;
1332 for (int i = 0; i != d.splitter_->count(); ++i) {
1333 TabWorkArea * twa = d.tabWorkArea(i);
1334 if (twa->removeWorkArea(wa)) {
1335 // Found in this tab group, and deleted the GuiWorkArea.
1337 if (twa->count() != 0) {
1338 if (d.current_work_area_ == 0)
1339 // This means that we are closing the current GuiWorkArea, so
1340 // switch to the next GuiWorkArea in the found TabWorkArea.
1341 setCurrentWorkArea(twa->currentWorkArea());
1343 // No more WorkAreas in this tab group, so delete it.
1350 // It is not a tabbed work area (i.e., the search work area), so it
1351 // should be deleted by other means.
1352 LASSERT(found_twa, return);
1354 if (d.current_work_area_ == 0) {
1355 if (d.splitter_->count() != 0) {
1356 TabWorkArea * twa = d.currentTabWorkArea();
1357 setCurrentWorkArea(twa->currentWorkArea());
1359 // No more work areas, switch to the background widget.
1360 setCurrentWorkArea(0);
1366 LayoutBox * GuiView::getLayoutDialog() const
1372 void GuiView::updateLayoutList()
1375 d.layout_->updateContents(false);
1379 void GuiView::updateToolbars()
1381 ToolbarMap::iterator end = d.toolbars_.end();
1382 if (d.current_work_area_) {
1384 d.current_work_area_->bufferView().cursor().inMathed()
1385 && !d.current_work_area_->bufferView().cursor().inRegexped();
1387 lyx::getStatus(FuncRequest(LFUN_LAYOUT_TABULAR)).enabled();
1389 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).enabled() &&
1390 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).onOff(true);
1391 bool const mathmacrotemplate =
1392 lyx::getStatus(FuncRequest(LFUN_IN_MATHMACROTEMPLATE)).enabled();
1394 lyx::getStatus(FuncRequest(LFUN_IN_IPA)).enabled();
1396 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1397 it->second->update(math, table, review, mathmacrotemplate, ipa);
1399 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1400 it->second->update(false, false, false, false, false);
1404 void GuiView::setBuffer(Buffer * newBuffer)
1406 LYXERR(Debug::DEBUG, "Setting buffer: " << newBuffer << endl);
1407 LASSERT(newBuffer, return);
1409 GuiWorkArea * wa = workArea(*newBuffer);
1412 newBuffer->masterBuffer()->updateBuffer();
1414 wa = addWorkArea(*newBuffer);
1415 // scroll to the position when the BufferView was last closed
1416 if (lyxrc.use_lastfilepos) {
1417 LastFilePosSection::FilePos filepos =
1418 theSession().lastFilePos().load(newBuffer->fileName());
1419 wa->bufferView().moveToPosition(filepos.pit, filepos.pos, 0, 0);
1422 //Disconnect the old buffer...there's no new one.
1425 connectBuffer(*newBuffer);
1426 connectBufferView(wa->bufferView());
1427 setCurrentWorkArea(wa);
1431 void GuiView::connectBuffer(Buffer & buf)
1433 buf.setGuiDelegate(this);
1437 void GuiView::disconnectBuffer()
1439 if (d.current_work_area_)
1440 d.current_work_area_->bufferView().buffer().setGuiDelegate(0);
1444 void GuiView::connectBufferView(BufferView & bv)
1446 bv.setGuiDelegate(this);
1450 void GuiView::disconnectBufferView()
1452 if (d.current_work_area_)
1453 d.current_work_area_->bufferView().setGuiDelegate(0);
1457 void GuiView::errors(string const & error_type, bool from_master)
1459 BufferView const * const bv = currentBufferView();
1463 #if EXPORT_in_THREAD
1464 // We are called with from_master == false by default, so we
1465 // have to figure out whether that is the case or not.
1466 ErrorList & el = bv->buffer().errorList(error_type);
1468 el = bv->buffer().masterBuffer()->errorList(error_type);
1472 ErrorList const & el = from_master ?
1473 bv->buffer().masterBuffer()->errorList(error_type) :
1474 bv->buffer().errorList(error_type);
1480 string data = error_type;
1482 data = "from_master|" + error_type;
1483 showDialog("errorlist", data);
1487 void GuiView::updateTocItem(string const & type, DocIterator const & dit)
1489 d.toc_models_.updateItem(toqstr(type), dit);
1493 void GuiView::structureChanged()
1495 d.toc_models_.reset(documentBufferView());
1496 // Navigator needs more than a simple update in this case. It needs to be
1498 updateDialog("toc", "");
1502 void GuiView::updateDialog(string const & name, string const & data)
1504 if (!isDialogVisible(name))
1507 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
1508 if (it == d.dialogs_.end())
1511 Dialog * const dialog = it->second.get();
1512 if (dialog->isVisibleView())
1513 dialog->initialiseParams(data);
1517 BufferView * GuiView::documentBufferView()
1519 return currentMainWorkArea()
1520 ? ¤tMainWorkArea()->bufferView()
1525 BufferView const * GuiView::documentBufferView() const
1527 return currentMainWorkArea()
1528 ? ¤tMainWorkArea()->bufferView()
1533 BufferView * GuiView::currentBufferView()
1535 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1539 BufferView const * GuiView::currentBufferView() const
1541 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1545 docstring GuiView::GuiViewPrivate::autosaveAndDestroy(
1546 Buffer const * orig, Buffer * clone)
1548 bool const success = clone->autoSave();
1550 busyBuffers.remove(orig);
1552 ? _("Automatic save done.")
1553 : _("Automatic save failed!");
1557 void GuiView::autoSave()
1559 LYXERR(Debug::INFO, "Running autoSave()");
1561 Buffer * buffer = documentBufferView()
1562 ? &documentBufferView()->buffer() : 0;
1564 resetAutosaveTimers();
1568 GuiViewPrivate::busyBuffers.insert(buffer);
1569 QFuture<docstring> f = QtConcurrent::run(GuiViewPrivate::autosaveAndDestroy,
1570 buffer, buffer->cloneBufferOnly());
1571 d.autosave_watcher_.setFuture(f);
1572 resetAutosaveTimers();
1576 void GuiView::resetAutosaveTimers()
1579 d.autosave_timeout_.restart();
1583 bool GuiView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1586 Buffer * buf = currentBufferView()
1587 ? ¤tBufferView()->buffer() : 0;
1588 Buffer * doc_buffer = documentBufferView()
1589 ? &(documentBufferView()->buffer()) : 0;
1591 // Check whether we need a buffer
1592 if (!lyxaction.funcHasFlag(cmd.action(), LyXAction::NoBuffer) && !buf) {
1593 // no, exit directly
1594 flag.message(from_utf8(N_("Command not allowed with"
1595 "out any document open")));
1596 flag.setEnabled(false);
1600 if (cmd.origin() == FuncRequest::TOC) {
1601 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
1602 if (!toc || !toc->getStatus(documentBufferView()->cursor(), cmd, flag))
1603 flag.setEnabled(false);
1607 switch(cmd.action()) {
1608 case LFUN_BUFFER_IMPORT:
1611 case LFUN_MASTER_BUFFER_UPDATE:
1612 case LFUN_MASTER_BUFFER_VIEW:
1613 enable = doc_buffer && doc_buffer->parent() != 0
1614 && !d.processing_thread_watcher_.isRunning();
1617 case LFUN_BUFFER_UPDATE:
1618 case LFUN_BUFFER_VIEW: {
1619 if (!doc_buffer || d.processing_thread_watcher_.isRunning()) {
1623 string format = to_utf8(cmd.argument());
1624 if (cmd.argument().empty())
1625 format = doc_buffer->params().getDefaultOutputFormat();
1626 enable = doc_buffer->params().isExportableFormat(format);
1630 case LFUN_BUFFER_RELOAD:
1631 enable = doc_buffer && !doc_buffer->isUnnamed()
1632 && doc_buffer->fileName().exists()
1633 && (!doc_buffer->isClean()
1634 || doc_buffer->isExternallyModified(Buffer::timestamp_method));
1637 case LFUN_BUFFER_CHILD_OPEN:
1638 enable = doc_buffer;
1641 case LFUN_BUFFER_WRITE:
1642 enable = doc_buffer && (doc_buffer->isUnnamed() || !doc_buffer->isClean());
1645 //FIXME: This LFUN should be moved to GuiApplication.
1646 case LFUN_BUFFER_WRITE_ALL: {
1647 // We enable the command only if there are some modified buffers
1648 Buffer * first = theBufferList().first();
1653 // We cannot use a for loop as the buffer list is a cycle.
1655 if (!b->isClean()) {
1659 b = theBufferList().next(b);
1660 } while (b != first);
1664 case LFUN_BUFFER_WRITE_AS:
1665 case LFUN_BUFFER_EXPORT_AS:
1666 enable = doc_buffer;
1669 case LFUN_BUFFER_CLOSE:
1670 case LFUN_VIEW_CLOSE:
1671 enable = doc_buffer;
1674 case LFUN_BUFFER_CLOSE_ALL:
1675 enable = theBufferList().last() != theBufferList().first();
1678 case LFUN_VIEW_SPLIT:
1679 if (cmd.getArg(0) == "vertical")
1680 enable = doc_buffer && (d.splitter_->count() == 1 ||
1681 d.splitter_->orientation() == Qt::Vertical);
1683 enable = doc_buffer && (d.splitter_->count() == 1 ||
1684 d.splitter_->orientation() == Qt::Horizontal);
1687 case LFUN_TAB_GROUP_CLOSE:
1688 enable = d.tabWorkAreaCount() > 1;
1691 case LFUN_TOOLBAR_TOGGLE: {
1692 string const name = cmd.getArg(0);
1693 if (GuiToolbar * t = toolbar(name))
1694 flag.setOnOff(t->isVisible());
1697 docstring const msg =
1698 bformat(_("Unknown toolbar \"%1$s\""), from_utf8(name));
1704 case LFUN_DROP_LAYOUTS_CHOICE:
1708 case LFUN_UI_TOGGLE:
1709 flag.setOnOff(isFullScreen());
1712 case LFUN_DIALOG_DISCONNECT_INSET:
1715 case LFUN_DIALOG_HIDE:
1716 // FIXME: should we check if the dialog is shown?
1719 case LFUN_DIALOG_TOGGLE:
1720 flag.setOnOff(isDialogVisible(cmd.getArg(0)));
1721 // fall through to set "enable"
1722 case LFUN_DIALOG_SHOW: {
1723 string const name = cmd.getArg(0);
1725 enable = name == "aboutlyx"
1726 || name == "file" //FIXME: should be removed.
1728 || name == "texinfo"
1729 || name == "progress"
1730 || name == "compare";
1731 else if (name == "print")
1732 enable = doc_buffer->params().isExportable("dvi")
1733 && lyxrc.print_command != "none";
1734 else if (name == "character" || name == "symbols") {
1735 if (!buf || buf->isReadonly())
1738 Cursor const & cur = currentBufferView()->cursor();
1739 enable = !(cur.inTexted() && cur.paragraph().isPassThru());
1742 else if (name == "latexlog")
1743 enable = FileName(doc_buffer->logName()).isReadableFile();
1744 else if (name == "spellchecker")
1745 enable = theSpellChecker()
1746 && !doc_buffer->isReadonly()
1747 && !doc_buffer->text().empty();
1748 else if (name == "vclog")
1749 enable = doc_buffer->lyxvc().inUse();
1753 case LFUN_DIALOG_UPDATE: {
1754 string const name = cmd.getArg(0);
1756 enable = name == "prefs";
1760 case LFUN_COMMAND_EXECUTE:
1762 case LFUN_MENU_OPEN:
1763 // Nothing to check.
1766 case LFUN_COMPLETION_INLINE:
1767 if (!d.current_work_area_
1768 || !d.current_work_area_->completer().inlinePossible(
1769 currentBufferView()->cursor()))
1773 case LFUN_COMPLETION_POPUP:
1774 if (!d.current_work_area_
1775 || !d.current_work_area_->completer().popupPossible(
1776 currentBufferView()->cursor()))
1780 case LFUN_COMPLETION_COMPLETE:
1781 if (!d.current_work_area_
1782 || !d.current_work_area_->completer().inlinePossible(
1783 currentBufferView()->cursor()))
1787 case LFUN_COMPLETION_ACCEPT:
1788 if (!d.current_work_area_
1789 || (!d.current_work_area_->completer().popupVisible()
1790 && !d.current_work_area_->completer().inlineVisible()
1791 && !d.current_work_area_->completer().completionAvailable()))
1795 case LFUN_COMPLETION_CANCEL:
1796 if (!d.current_work_area_
1797 || (!d.current_work_area_->completer().popupVisible()
1798 && !d.current_work_area_->completer().inlineVisible()))
1802 case LFUN_BUFFER_ZOOM_OUT:
1803 enable = doc_buffer && lyxrc.zoom > 10;
1806 case LFUN_BUFFER_ZOOM_IN:
1807 enable = doc_buffer;
1810 case LFUN_BUFFER_NEXT:
1811 case LFUN_BUFFER_PREVIOUS:
1812 // FIXME: should we check is there is an previous or next buffer?
1814 case LFUN_BUFFER_SWITCH:
1815 // toggle on the current buffer, but do not toggle off
1816 // the other ones (is that a good idea?)
1818 && to_utf8(cmd.argument()) == doc_buffer->absFileName())
1819 flag.setOnOff(true);
1822 case LFUN_VC_REGISTER:
1823 enable = doc_buffer && !doc_buffer->lyxvc().inUse();
1825 case LFUN_VC_RENAME:
1826 enable = doc_buffer && doc_buffer->lyxvc().renameEnabled();
1829 enable = doc_buffer && doc_buffer->lyxvc().copyEnabled();
1831 case LFUN_VC_CHECK_IN:
1832 enable = doc_buffer && doc_buffer->lyxvc().checkInEnabled();
1834 case LFUN_VC_CHECK_OUT:
1835 enable = doc_buffer && doc_buffer->lyxvc().checkOutEnabled();
1837 case LFUN_VC_LOCKING_TOGGLE:
1838 enable = doc_buffer && !doc_buffer->isReadonly()
1839 && doc_buffer->lyxvc().lockingToggleEnabled();
1840 flag.setOnOff(enable && doc_buffer->lyxvc().locking());
1842 case LFUN_VC_REVERT:
1843 enable = doc_buffer && doc_buffer->lyxvc().inUse() && !doc_buffer->isReadonly();
1845 case LFUN_VC_UNDO_LAST:
1846 enable = doc_buffer && doc_buffer->lyxvc().undoLastEnabled();
1848 case LFUN_VC_REPO_UPDATE:
1849 enable = doc_buffer && doc_buffer->lyxvc().repoUpdateEnabled();
1851 case LFUN_VC_COMMAND: {
1852 if (cmd.argument().empty())
1854 if (!doc_buffer && contains(cmd.getArg(0), 'D'))
1858 case LFUN_VC_COMPARE:
1859 enable = doc_buffer && doc_buffer->lyxvc().prepareFileRevisionEnabled();
1862 case LFUN_SERVER_GOTO_FILE_ROW:
1864 case LFUN_FORWARD_SEARCH:
1865 enable = !(lyxrc.forward_search_dvi.empty() && lyxrc.forward_search_pdf.empty());
1868 case LFUN_FILE_INSERT_PLAINTEXT:
1869 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
1870 enable = documentBufferView() && documentBufferView()->cursor().inTexted();
1873 case LFUN_SPELLING_CONTINUOUSLY:
1874 flag.setOnOff(lyxrc.spellcheck_continuously);
1882 flag.setEnabled(false);
1888 static FileName selectTemplateFile()
1890 FileDialog dlg(qt_("Select template file"));
1891 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1892 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
1894 FileDialog::Result result = dlg.open(toqstr(lyxrc.template_path),
1895 QStringList(qt_("LyX Documents (*.lyx)")));
1897 if (result.first == FileDialog::Later)
1899 if (result.second.isEmpty())
1901 return FileName(fromqstr(result.second));
1905 Buffer * GuiView::loadDocument(FileName const & filename, bool tolastfiles)
1909 Buffer * newBuffer = 0;
1911 newBuffer = checkAndLoadLyXFile(filename);
1912 } catch (ExceptionMessage const & e) {
1919 message(_("Document not loaded."));
1923 setBuffer(newBuffer);
1924 newBuffer->errors("Parse");
1927 theSession().lastFiles().add(filename);
1933 void GuiView::openDocument(string const & fname)
1935 string initpath = lyxrc.document_path;
1937 if (documentBufferView()) {
1938 string const trypath = documentBufferView()->buffer().filePath();
1939 // If directory is writeable, use this as default.
1940 if (FileName(trypath).isDirWritable())
1946 if (fname.empty()) {
1947 FileDialog dlg(qt_("Select document to open"), LFUN_FILE_OPEN);
1948 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1949 dlg.setButton2(qt_("Examples|#E#e"),
1950 toqstr(addPath(package().system_support().absFileName(), "examples")));
1952 QStringList filter(qt_("LyX Documents (*.lyx)"));
1953 filter << qt_("LyX-1.3.x Documents (*.lyx13)")
1954 << qt_("LyX-1.4.x Documents (*.lyx14)")
1955 << qt_("LyX-1.5.x Documents (*.lyx15)")
1956 << qt_("LyX-1.6.x Documents (*.lyx16)");
1957 FileDialog::Result result =
1958 dlg.open(toqstr(initpath), filter);
1960 if (result.first == FileDialog::Later)
1963 filename = fromqstr(result.second);
1965 // check selected filename
1966 if (filename.empty()) {
1967 message(_("Canceled."));
1973 // get absolute path of file and add ".lyx" to the filename if
1975 FileName const fullname =
1976 fileSearch(string(), filename, "lyx", support::may_not_exist);
1977 if (!fullname.empty())
1978 filename = fullname.absFileName();
1980 if (!fullname.onlyPath().isDirectory()) {
1981 Alert::warning(_("Invalid filename"),
1982 bformat(_("The directory in the given path\n%1$s\ndoes not exist."),
1983 from_utf8(fullname.absFileName())));
1987 // if the file doesn't exist and isn't already open (bug 6645),
1988 // let the user create one
1989 if (!fullname.exists() && !theBufferList().exists(fullname) &&
1990 !LyXVC::file_not_found_hook(fullname)) {
1991 // the user specifically chose this name. Believe him.
1992 Buffer * const b = newFile(filename, string(), true);
1998 docstring const disp_fn = makeDisplayPath(filename);
1999 message(bformat(_("Opening document %1$s..."), disp_fn));
2002 Buffer * buf = loadDocument(fullname);
2004 str2 = bformat(_("Document %1$s opened."), disp_fn);
2005 if (buf->lyxvc().inUse())
2006 str2 += " " + from_utf8(buf->lyxvc().versionString()) +
2007 " " + _("Version control detected.");
2009 str2 = bformat(_("Could not open document %1$s"), disp_fn);
2014 // FIXME: clean that
2015 static bool import(GuiView * lv, FileName const & filename,
2016 string const & format, ErrorList & errorList)
2018 FileName const lyxfile(support::changeExtension(filename.absFileName(), ".lyx"));
2020 string loader_format;
2021 vector<string> loaders = theConverters().loaders();
2022 if (find(loaders.begin(), loaders.end(), format) == loaders.end()) {
2023 vector<string>::const_iterator it = loaders.begin();
2024 vector<string>::const_iterator en = loaders.end();
2025 for (; it != en; ++it) {
2026 if (!theConverters().isReachable(format, *it))
2029 string const tofile =
2030 support::changeExtension(filename.absFileName(),
2031 formats.extension(*it));
2032 if (!theConverters().convert(0, filename, FileName(tofile),
2033 filename, format, *it, errorList))
2035 loader_format = *it;
2038 if (loader_format.empty()) {
2039 frontend::Alert::error(_("Couldn't import file"),
2040 bformat(_("No information for importing the format %1$s."),
2041 formats.prettyName(format)));
2045 loader_format = format;
2047 if (loader_format == "lyx") {
2048 Buffer * buf = lv->loadDocument(lyxfile);
2052 Buffer * const b = newFile(lyxfile.absFileName(), string(), true);
2056 bool as_paragraphs = loader_format == "textparagraph";
2057 string filename2 = (loader_format == format) ? filename.absFileName()
2058 : support::changeExtension(filename.absFileName(),
2059 formats.extension(loader_format));
2060 lv->currentBufferView()->insertPlaintextFile(FileName(filename2),
2062 guiApp->setCurrentView(lv);
2063 lyx::dispatch(FuncRequest(LFUN_MARK_OFF));
2070 void GuiView::importDocument(string const & argument)
2073 string filename = split(argument, format, ' ');
2075 LYXERR(Debug::INFO, format << " file: " << filename);
2077 // need user interaction
2078 if (filename.empty()) {
2079 string initpath = lyxrc.document_path;
2080 if (documentBufferView()) {
2081 string const trypath = documentBufferView()->buffer().filePath();
2082 // If directory is writeable, use this as default.
2083 if (FileName(trypath).isDirWritable())
2087 docstring const text = bformat(_("Select %1$s file to import"),
2088 formats.prettyName(format));
2090 FileDialog dlg(toqstr(text), LFUN_BUFFER_IMPORT);
2091 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2092 dlg.setButton2(qt_("Examples|#E#e"),
2093 toqstr(addPath(package().system_support().absFileName(), "examples")));
2095 docstring filter = formats.prettyName(format);
2098 filter += from_utf8(formats.extensions(format));
2101 FileDialog::Result result =
2102 dlg.open(toqstr(initpath), fileFilters(toqstr(filter)));
2104 if (result.first == FileDialog::Later)
2107 filename = fromqstr(result.second);
2109 // check selected filename
2110 if (filename.empty())
2111 message(_("Canceled."));
2114 if (filename.empty())
2117 // get absolute path of file
2118 FileName const fullname(support::makeAbsPath(filename));
2120 FileName const lyxfile(support::changeExtension(fullname.absFileName(), ".lyx"));
2122 // Check if the document already is open
2123 Buffer * buf = theBufferList().getBuffer(lyxfile);
2126 if (!closeBuffer()) {
2127 message(_("Canceled."));
2132 docstring const displaypath = makeDisplayPath(lyxfile.absFileName(), 30);
2134 // if the file exists already, and we didn't do
2135 // -i lyx thefile.lyx, warn
2136 if (lyxfile.exists() && fullname != lyxfile) {
2138 docstring text = bformat(_("The document %1$s already exists.\n\n"
2139 "Do you want to overwrite that document?"), displaypath);
2140 int const ret = Alert::prompt(_("Overwrite document?"),
2141 text, 0, 1, _("&Overwrite"), _("&Cancel"));
2144 message(_("Canceled."));
2149 message(bformat(_("Importing %1$s..."), displaypath));
2150 ErrorList errorList;
2151 if (import(this, fullname, format, errorList))
2152 message(_("imported."));
2154 message(_("file not imported!"));
2156 // FIXME (Abdel 12/08/06): Is there a need to display the error list here?
2160 void GuiView::newDocument(string const & filename, bool from_template)
2162 FileName initpath(lyxrc.document_path);
2163 if (documentBufferView()) {
2164 FileName const trypath(documentBufferView()->buffer().filePath());
2165 // If directory is writeable, use this as default.
2166 if (trypath.isDirWritable())
2170 string templatefile;
2171 if (from_template) {
2172 templatefile = selectTemplateFile().absFileName();
2173 if (templatefile.empty())
2178 if (filename.empty())
2179 b = newUnnamedFile(initpath, to_utf8(_("newfile")), templatefile);
2181 b = newFile(filename, templatefile, true);
2186 // If no new document could be created, it is unsure
2187 // whether there is a valid BufferView.
2188 if (currentBufferView())
2189 // Ensure the cursor is correctly positioned on screen.
2190 currentBufferView()->showCursor();
2194 void GuiView::insertLyXFile(docstring const & fname)
2196 BufferView * bv = documentBufferView();
2201 FileName filename(to_utf8(fname));
2202 if (filename.empty()) {
2203 // Launch a file browser
2205 string initpath = lyxrc.document_path;
2206 string const trypath = bv->buffer().filePath();
2207 // If directory is writeable, use this as default.
2208 if (FileName(trypath).isDirWritable())
2212 FileDialog dlg(qt_("Select LyX document to insert"), LFUN_FILE_INSERT);
2213 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2214 dlg.setButton2(qt_("Examples|#E#e"),
2215 toqstr(addPath(package().system_support().absFileName(),
2218 FileDialog::Result result = dlg.open(toqstr(initpath),
2219 QStringList(qt_("LyX Documents (*.lyx)")));
2221 if (result.first == FileDialog::Later)
2225 filename.set(fromqstr(result.second));
2227 // check selected filename
2228 if (filename.empty()) {
2229 // emit message signal.
2230 message(_("Canceled."));
2235 bv->insertLyXFile(filename);
2236 bv->buffer().errors("Parse");
2240 bool GuiView::renameBuffer(Buffer & b, docstring const & newname, RenameKind kind)
2242 FileName fname = b.fileName();
2243 FileName const oldname = fname;
2245 if (!newname.empty()) {
2247 fname = support::makeAbsPath(to_utf8(newname), oldname.onlyPath().absFileName());
2249 // Switch to this Buffer.
2252 // No argument? Ask user through dialog.
2254 FileDialog dlg(qt_("Choose a filename to save document as"),
2255 LFUN_BUFFER_WRITE_AS);
2256 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2257 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
2259 if (!isLyXFileName(fname.absFileName()))
2260 fname.changeExtension(".lyx");
2262 FileDialog::Result result =
2263 dlg.save(toqstr(fname.onlyPath().absFileName()),
2264 QStringList(qt_("LyX Documents (*.lyx)")),
2265 toqstr(fname.onlyFileName()));
2267 if (result.first == FileDialog::Later)
2270 fname.set(fromqstr(result.second));
2275 if (!isLyXFileName(fname.absFileName()))
2276 fname.changeExtension(".lyx");
2279 // fname is now the new Buffer location.
2281 // if there is already a Buffer open with this name, we do not want
2282 // to have another one. (the second test makes sure we're not just
2283 // trying to overwrite ourselves, which is fine.)
2284 if (theBufferList().exists(fname) && fname != oldname
2285 && theBufferList().getBuffer(fname) != &b) {
2286 docstring const text =
2287 bformat(_("The file\n%1$s\nis already open in your current session.\n"
2288 "Please close it before attempting to overwrite it.\n"
2289 "Do you want to choose a new filename?"),
2290 from_utf8(fname.absFileName()));
2291 int const ret = Alert::prompt(_("Chosen File Already Open"),
2292 text, 0, 1, _("&Rename"), _("&Cancel"));
2294 case 0: return renameBuffer(b, docstring(), kind);
2295 case 1: return false;
2300 bool const existsLocal = fname.exists();
2301 bool const existsInVC = LyXVC::fileInVC(fname);
2302 if (existsLocal || existsInVC) {
2303 docstring const file = makeDisplayPath(fname.absFileName(), 30);
2304 if (kind != LV_WRITE_AS && existsInVC) {
2305 // renaming to a name that is already in VC
2307 docstring text = bformat(_("The document %1$s "
2308 "is already registered.\n\n"
2309 "Do you want to choose a new name?"),
2311 docstring const title = (kind == LV_VC_RENAME) ?
2312 _("Rename document?") : _("Copy document?");
2313 docstring const button = (kind == LV_VC_RENAME) ?
2314 _("&Rename") : _("&Copy");
2315 int const ret = Alert::prompt(title, text, 0, 1,
2316 button, _("&Cancel"));
2318 case 0: return renameBuffer(b, docstring(), kind);
2319 case 1: return false;
2324 docstring text = bformat(_("The document %1$s "
2325 "already exists.\n\n"
2326 "Do you want to overwrite that document?"),
2328 int const ret = Alert::prompt(_("Overwrite document?"),
2329 text, 0, 2, _("&Overwrite"),
2330 _("&Rename"), _("&Cancel"));
2333 case 1: return renameBuffer(b, docstring(), kind);
2334 case 2: return false;
2340 case LV_VC_RENAME: {
2341 string msg = b.lyxvc().rename(fname);
2344 message(from_utf8(msg));
2348 string msg = b.lyxvc().copy(fname);
2351 message(from_utf8(msg));
2357 // LyXVC created the file already in case of LV_VC_RENAME or
2358 // LV_VC_COPY, but call saveBuffer() nevertheless to get
2359 // relative paths of included stuff right if we moved e.g. from
2360 // /a/b.lyx to /a/c/b.lyx.
2362 bool const saved = saveBuffer(b, fname);
2369 struct PrettyNameComparator
2371 bool operator()(Format const *first, Format const *second) const {
2372 return compare_ascii_no_case(first->prettyname(), second->prettyname()) <= 0;
2377 bool GuiView::exportBufferAs(Buffer & b)
2379 FileName fname = b.fileName();
2381 FileDialog dlg(qt_("Choose a filename to export the document as"));
2382 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2385 types << "Any supported format (*.*)";
2386 Formats::const_iterator it = formats.begin();
2387 vector<Format const *> export_formats;
2388 for (; it != formats.end(); ++it)
2389 if (it->documentFormat() && it->inExportMenu())
2390 export_formats.push_back(&(*it));
2391 PrettyNameComparator cmp;
2392 sort(export_formats.begin(), export_formats.end(), cmp);
2393 vector<Format const *>::const_iterator fit = export_formats.begin();
2394 for (; fit != export_formats.end(); ++fit)
2395 types << toqstr((*fit)->prettyname() + " (*." + (*fit)->extension() + ")");
2397 FileDialog::Result result =
2398 dlg.save(toqstr(fname.onlyPath().absFileName()),
2400 toqstr(fname.onlyFileName()),
2402 if (result.first != FileDialog::Chosen)
2405 string s = fromqstr(filter);
2406 size_t pos = s.find(" (*.");
2407 LATTEST(pos != string::npos);
2408 string fmt_prettyname = s.substr(0, pos);
2410 fname.set(fromqstr(result.second));
2411 if (fmt_prettyname == "Any supported format")
2412 fmt_name = formats.getFormatFromExtension(fname.extension());
2414 fmt_name = formats.getFormatFromPrettyName(fmt_prettyname);
2415 LYXERR(Debug::FILES, "fmt_prettyname=" << fmt_prettyname
2416 << ", fmt_name=" << fmt_name << ", fname=" << fname.absFileName());
2418 if (fmt_name.empty() || fname.empty())
2421 // fname is now the new Buffer location.
2422 if (FileName(fname).exists()) {
2423 docstring const file = makeDisplayPath(fname.absFileName(), 30);
2424 docstring text = bformat(_("The document %1$s already "
2425 "exists.\n\nDo you want to "
2426 "overwrite that document?"),
2428 int const ret = Alert::prompt(_("Overwrite document?"),
2429 text, 0, 2, _("&Overwrite"), _("&Rename"), _("&Cancel"));
2432 case 1: return exportBufferAs(b);
2433 case 2: return false;
2437 FuncRequest cmd(LFUN_BUFFER_EXPORT, fmt_name + " " + fname.absFileName());
2440 return dr.dispatched();
2444 bool GuiView::saveBuffer(Buffer & b)
2446 return saveBuffer(b, FileName());
2450 bool GuiView::saveBuffer(Buffer & b, FileName const & fn)
2452 if (workArea(b) && workArea(b)->inDialogMode())
2455 if (fn.empty() && b.isUnnamed())
2456 return renameBuffer(b, docstring());
2458 bool const success = (fn.empty() ? b.save() : b.saveAs(fn));
2460 theSession().lastFiles().add(b.fileName());
2464 // Switch to this Buffer.
2467 // FIXME: we don't tell the user *WHY* the save failed !!
2468 docstring const file = makeDisplayPath(b.absFileName(), 30);
2469 docstring text = bformat(_("The document %1$s could not be saved.\n\n"
2470 "Do you want to rename the document and "
2471 "try again?"), file);
2472 int const ret = Alert::prompt(_("Rename and save?"),
2473 text, 0, 2, _("&Rename"), _("&Retry"), _("&Cancel"));
2476 if (!renameBuffer(b, docstring()))
2485 return saveBuffer(b, fn);
2489 bool GuiView::hideWorkArea(GuiWorkArea * wa)
2491 return closeWorkArea(wa, false);
2495 // We only want to close the buffer if it is not visible in other workareas
2496 // of the same view, nor in other views, and if this is not a child
2497 bool GuiView::closeWorkArea(GuiWorkArea * wa)
2499 Buffer & buf = wa->bufferView().buffer();
2501 bool last_wa = d.countWorkAreasOf(buf) == 1
2502 && !inOtherView(buf) && !buf.parent();
2504 bool close_buffer = last_wa;
2507 if (lyxrc.close_buffer_with_last_view == "yes")
2509 else if (lyxrc.close_buffer_with_last_view == "no")
2510 close_buffer = false;
2513 if (buf.isUnnamed())
2514 file = from_utf8(buf.fileName().onlyFileName());
2516 file = buf.fileName().displayName(30);
2517 docstring const text = bformat(
2518 _("Last view on document %1$s is being closed.\n"
2519 "Would you like to close or hide the document?\n"
2521 "Hidden documents can be displayed back through\n"
2522 "the menu: View->Hidden->...\n"
2524 "To remove this question, set your preference in:\n"
2525 " Tools->Preferences->Look&Feel->UserInterface\n"
2527 int ret = Alert::prompt(_("Close or hide document?"),
2528 text, 0, 1, _("&Close"), _("&Hide"));
2529 close_buffer = (ret == 0);
2533 return closeWorkArea(wa, close_buffer);
2537 bool GuiView::closeBuffer()
2539 GuiWorkArea * wa = currentMainWorkArea();
2540 setCurrentWorkArea(wa);
2541 Buffer & buf = wa->bufferView().buffer();
2542 return wa && closeWorkArea(wa, !buf.parent());
2546 void GuiView::writeSession() const {
2547 GuiWorkArea const * active_wa = currentMainWorkArea();
2548 for (int i = 0; i < d.splitter_->count(); ++i) {
2549 TabWorkArea * twa = d.tabWorkArea(i);
2550 for (int j = 0; j < twa->count(); ++j) {
2551 GuiWorkArea * wa = static_cast<GuiWorkArea *>(twa->widget(j));
2552 Buffer & buf = wa->bufferView().buffer();
2553 theSession().lastOpened().add(buf.fileName(), wa == active_wa);
2559 bool GuiView::closeBufferAll()
2561 // Close the workareas in all other views
2562 QList<int> const ids = guiApp->viewIds();
2563 for (int i = 0; i != ids.size(); ++i) {
2564 if (id_ != ids[i] && !guiApp->view(ids[i]).closeWorkAreaAll())
2568 // Close our own workareas
2569 if (!closeWorkAreaAll())
2572 // Now close the hidden buffers. We prevent hidden buffers from being
2573 // dirty, so we can just close them.
2574 theBufferList().closeAll();
2579 bool GuiView::closeWorkAreaAll()
2581 setCurrentWorkArea(currentMainWorkArea());
2583 // We might be in a situation that there is still a tabWorkArea, but
2584 // there are no tabs anymore. This can happen when we get here after a
2585 // TabWorkArea::lastWorkAreaRemoved() signal. Therefore we count how
2586 // many TabWorkArea's have no documents anymore.
2589 // We have to call count() each time, because it can happen that
2590 // more than one splitter will disappear in one iteration (bug 5998).
2591 for (; d.splitter_->count() > empty_twa; ) {
2592 TabWorkArea * twa = d.tabWorkArea(empty_twa);
2594 if (twa->count() == 0)
2597 setCurrentWorkArea(twa->currentWorkArea());
2598 if (!closeTabWorkArea(twa))
2606 bool GuiView::closeWorkArea(GuiWorkArea * wa, bool close_buffer)
2611 Buffer & buf = wa->bufferView().buffer();
2613 if (close_buffer && GuiViewPrivate::busyBuffers.contains(&buf)) {
2614 Alert::warning(_("Close document"),
2615 _("Document could not be closed because it is being processed by LyX."));
2620 return closeBuffer(buf);
2622 if (!inMultiTabs(wa))
2623 if (!saveBufferIfNeeded(buf, true))
2631 bool GuiView::closeBuffer(Buffer & buf)
2633 // If we are in a close_event all children will be closed in some time,
2634 // so no need to do it here. This will ensure that the children end up
2635 // in the session file in the correct order. If we close the master
2636 // buffer, we can close or release the child buffers here too.
2637 bool success = true;
2639 ListOfBuffers clist = buf.getChildren();
2640 ListOfBuffers::const_iterator it = clist.begin();
2641 ListOfBuffers::const_iterator const bend = clist.end();
2642 for (; it != bend; ++it) {
2643 // If a child is dirty, do not close
2644 // without user intervention
2645 //FIXME: should we look in other tabworkareas?
2646 Buffer * child_buf = *it;
2647 GuiWorkArea * child_wa = workArea(*child_buf);
2649 if (!closeWorkArea(child_wa, true)) {
2654 theBufferList().releaseChild(&buf, child_buf);
2658 // goto bookmark to update bookmark pit.
2659 //FIXME: we should update only the bookmarks related to this buffer!
2660 LYXERR(Debug::DEBUG, "GuiView::closeBuffer()");
2661 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
2662 guiApp->gotoBookmark(i+1, false, false);
2664 if (saveBufferIfNeeded(buf, false)) {
2665 buf.removeAutosaveFile();
2666 theBufferList().release(&buf);
2670 // open all children again to avoid a crash because of dangling
2671 // pointers (bug 6603)
2677 bool GuiView::closeTabWorkArea(TabWorkArea * twa)
2679 while (twa == d.currentTabWorkArea()) {
2680 twa->setCurrentIndex(twa->count()-1);
2682 GuiWorkArea * wa = twa->currentWorkArea();
2683 Buffer & b = wa->bufferView().buffer();
2685 // We only want to close the buffer if the same buffer is not visible
2686 // in another view, and if this is not a child and if we are closing
2687 // a view (not a tabgroup).
2688 bool const close_buffer =
2689 !inOtherView(b) && !b.parent() && closing_;
2691 if (!closeWorkArea(wa, close_buffer))
2698 bool GuiView::saveBufferIfNeeded(Buffer & buf, bool hiding)
2700 if (buf.isClean() || buf.paragraphs().empty())
2703 // Switch to this Buffer.
2708 if (buf.isUnnamed())
2709 file = from_utf8(buf.fileName().onlyFileName());
2711 file = buf.fileName().displayName(30);
2713 // Bring this window to top before asking questions.
2718 if (hiding && buf.isUnnamed()) {
2719 docstring const text = bformat(_("The document %1$s has not been "
2720 "saved yet.\n\nDo you want to save "
2721 "the document?"), file);
2722 ret = Alert::prompt(_("Save new document?"),
2723 text, 0, 1, _("&Save"), _("&Cancel"));
2727 docstring const text = bformat(_("The document %1$s has unsaved changes."
2728 "\n\nDo you want to save the document or discard the changes?"), file);
2729 ret = Alert::prompt(_("Save changed document?"),
2730 text, 0, 2, _("&Save"), _("&Discard"), _("&Cancel"));
2735 if (!saveBuffer(buf))
2739 // If we crash after this we could have no autosave file
2740 // but I guess this is really improbable (Jug).
2741 // Sometimes improbable things happen:
2742 // - see bug http://www.lyx.org/trac/ticket/6587 (ps)
2743 // buf.removeAutosaveFile();
2745 // revert all changes
2756 bool GuiView::inMultiTabs(GuiWorkArea * wa)
2758 Buffer & buf = wa->bufferView().buffer();
2760 for (int i = 0; i != d.splitter_->count(); ++i) {
2761 GuiWorkArea * wa_ = d.tabWorkArea(i)->workArea(buf);
2762 if (wa_ && wa_ != wa)
2765 return inOtherView(buf);
2769 bool GuiView::inOtherView(Buffer & buf)
2771 QList<int> const ids = guiApp->viewIds();
2773 for (int i = 0; i != ids.size(); ++i) {
2777 if (guiApp->view(ids[i]).workArea(buf))
2784 void GuiView::gotoNextOrPreviousBuffer(NextOrPrevious np)
2786 if (!documentBufferView())
2789 if (TabWorkArea * twa = d.currentTabWorkArea()) {
2790 Buffer * const curbuf = &documentBufferView()->buffer();
2791 int nwa = twa->count();
2792 for (int i = 0; i < nwa; ++i) {
2793 if (&workArea(i)->bufferView().buffer() == curbuf) {
2795 if (np == NEXTBUFFER)
2796 next_index = (i == nwa - 1 ? 0 : i + 1);
2798 next_index = (i == 0 ? nwa - 1 : i - 1);
2799 setBuffer(&workArea(next_index)->bufferView().buffer());
2807 /// make sure the document is saved
2808 static bool ensureBufferClean(Buffer * buffer)
2810 LASSERT(buffer, return false);
2811 if (buffer->isClean() && !buffer->isUnnamed())
2814 docstring const file = buffer->fileName().displayName(30);
2817 if (!buffer->isUnnamed()) {
2818 text = bformat(_("The document %1$s has unsaved "
2819 "changes.\n\nDo you want to save "
2820 "the document?"), file);
2821 title = _("Save changed document?");
2824 text = bformat(_("The document %1$s has not been "
2825 "saved yet.\n\nDo you want to save "
2826 "the document?"), file);
2827 title = _("Save new document?");
2829 int const ret = Alert::prompt(title, text, 0, 1, _("&Save"), _("&Cancel"));
2832 dispatch(FuncRequest(LFUN_BUFFER_WRITE));
2834 return buffer->isClean() && !buffer->isUnnamed();
2838 bool GuiView::reloadBuffer(Buffer & buf)
2840 Buffer::ReadStatus status = buf.reload();
2841 return status == Buffer::ReadSuccess;
2845 void GuiView::checkExternallyModifiedBuffers()
2847 BufferList::iterator bit = theBufferList().begin();
2848 BufferList::iterator const bend = theBufferList().end();
2849 for (; bit != bend; ++bit) {
2850 Buffer * buf = *bit;
2851 if (buf->fileName().exists()
2852 && buf->isExternallyModified(Buffer::checksum_method)) {
2853 docstring text = bformat(_("Document \n%1$s\n has been externally modified."
2854 " Reload now? Any local changes will be lost."),
2855 from_utf8(buf->absFileName()));
2856 int const ret = Alert::prompt(_("Reload externally changed document?"),
2857 text, 0, 1, _("&Reload"), _("&Cancel"));
2865 void GuiView::dispatchVC(FuncRequest const & cmd, DispatchResult & dr)
2867 Buffer * buffer = documentBufferView()
2868 ? &(documentBufferView()->buffer()) : 0;
2870 switch (cmd.action()) {
2871 case LFUN_VC_REGISTER:
2872 if (!buffer || !ensureBufferClean(buffer))
2874 if (!buffer->lyxvc().inUse()) {
2875 if (buffer->lyxvc().registrer()) {
2876 reloadBuffer(*buffer);
2877 dr.suppressMessageUpdate();
2882 case LFUN_VC_RENAME:
2883 case LFUN_VC_COPY: {
2884 if (!buffer || !ensureBufferClean(buffer))
2886 if (buffer->lyxvc().inUse() && !buffer->isReadonly()) {
2887 if (buffer->lyxvc().isCheckInWithConfirmation()) {
2888 // Some changes are not yet committed.
2889 // We test here and not in getStatus(), since
2890 // this test is expensive.
2892 LyXVC::CommandResult ret =
2893 buffer->lyxvc().checkIn(log);
2895 if (ret == LyXVC::ErrorCommand ||
2896 ret == LyXVC::VCSuccess)
2897 reloadBuffer(*buffer);
2898 if (buffer->lyxvc().isCheckInWithConfirmation()) {
2899 frontend::Alert::error(
2900 _("Revision control error."),
2901 _("Document could not be checked in."));
2905 RenameKind const kind = (cmd.action() == LFUN_VC_RENAME) ?
2906 LV_VC_RENAME : LV_VC_COPY;
2907 renameBuffer(*buffer, cmd.argument(), kind);
2912 case LFUN_VC_CHECK_IN:
2913 if (!buffer || !ensureBufferClean(buffer))
2915 if (buffer->lyxvc().inUse() && !buffer->isReadonly()) {
2917 LyXVC::CommandResult ret = buffer->lyxvc().checkIn(log);
2919 // Only skip reloading if the checkin was cancelled or
2920 // an error occured before the real checkin VCS command
2921 // was executed, since the VCS might have changed the
2922 // file even if it could not checkin successfully.
2923 if (ret == LyXVC::ErrorCommand || ret == LyXVC::VCSuccess)
2924 reloadBuffer(*buffer);
2928 case LFUN_VC_CHECK_OUT:
2929 if (!buffer || !ensureBufferClean(buffer))
2931 if (buffer->lyxvc().inUse()) {
2932 dr.setMessage(buffer->lyxvc().checkOut());
2933 reloadBuffer(*buffer);
2937 case LFUN_VC_LOCKING_TOGGLE:
2938 LASSERT(buffer, return);
2939 if (!ensureBufferClean(buffer) || buffer->isReadonly())
2941 if (buffer->lyxvc().inUse()) {
2942 string res = buffer->lyxvc().lockingToggle();
2944 frontend::Alert::error(_("Revision control error."),
2945 _("Error when setting the locking property."));
2948 reloadBuffer(*buffer);
2953 case LFUN_VC_REVERT:
2954 LASSERT(buffer, return);
2955 if (buffer->lyxvc().revert()) {
2956 reloadBuffer(*buffer);
2957 dr.suppressMessageUpdate();
2961 case LFUN_VC_UNDO_LAST:
2962 LASSERT(buffer, return);
2963 buffer->lyxvc().undoLast();
2964 reloadBuffer(*buffer);
2965 dr.suppressMessageUpdate();
2968 case LFUN_VC_REPO_UPDATE:
2969 LASSERT(buffer, return);
2970 if (ensureBufferClean(buffer)) {
2971 dr.setMessage(buffer->lyxvc().repoUpdate());
2972 checkExternallyModifiedBuffers();
2976 case LFUN_VC_COMMAND: {
2977 string flag = cmd.getArg(0);
2978 if (buffer && contains(flag, 'R') && !ensureBufferClean(buffer))
2981 if (contains(flag, 'M')) {
2982 if (!Alert::askForText(message, _("LyX VC: Log Message")))
2985 string path = cmd.getArg(1);
2986 if (contains(path, "$$p") && buffer)
2987 path = subst(path, "$$p", buffer->filePath());
2988 LYXERR(Debug::LYXVC, "Directory: " << path);
2990 if (!pp.isReadableDirectory()) {
2991 lyxerr << _("Directory is not accessible.") << endl;
2994 support::PathChanger p(pp);
2996 string command = cmd.getArg(2);
2997 if (command.empty())
3000 command = subst(command, "$$i", buffer->absFileName());
3001 command = subst(command, "$$p", buffer->filePath());
3003 command = subst(command, "$$m", to_utf8(message));
3004 LYXERR(Debug::LYXVC, "Command: " << command);
3006 one.startscript(Systemcall::Wait, command);
3010 if (contains(flag, 'I'))
3011 buffer->markDirty();
3012 if (contains(flag, 'R'))
3013 reloadBuffer(*buffer);
3018 case LFUN_VC_COMPARE: {
3020 if (cmd.argument().empty()) {
3021 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "comparehistory"));
3025 string rev1 = cmd.getArg(0);
3029 if (!buffer->lyxvc().prepareFileRevision(rev1, f1))
3032 if (isStrInt(rev1) && convert<int>(rev1) <= 0) {
3033 f2 = buffer->absFileName();
3035 string rev2 = cmd.getArg(1);
3039 if (!buffer->lyxvc().prepareFileRevision(rev2, f2))
3043 LYXERR(Debug::LYXVC, "Launching comparison for fetched revisions:\n" <<
3044 f1 << "\n" << f2 << "\n" );
3045 string par = "compare run " + quoteName(f1) + " " + quoteName(f2);
3046 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, par));
3056 void GuiView::openChildDocument(string const & fname)
3058 LASSERT(documentBufferView(), return);
3059 Buffer & buffer = documentBufferView()->buffer();
3060 FileName const filename = support::makeAbsPath(fname, buffer.filePath());
3061 documentBufferView()->saveBookmark(false);
3063 if (theBufferList().exists(filename)) {
3064 child = theBufferList().getBuffer(filename);
3067 message(bformat(_("Opening child document %1$s..."),
3068 makeDisplayPath(filename.absFileName())));
3069 child = loadDocument(filename, false);
3071 // Set the parent name of the child document.
3072 // This makes insertion of citations and references in the child work,
3073 // when the target is in the parent or another child document.
3075 child->setParent(&buffer);
3079 bool GuiView::goToFileRow(string const & argument)
3083 size_t i = argument.find_last_of(' ');
3084 if (i != string::npos) {
3085 file_name = os::internal_path(trim(argument.substr(0, i)));
3086 istringstream is(argument.substr(i + 1));
3091 if (i == string::npos) {
3092 LYXERR0("Wrong argument: " << argument);
3096 string const abstmp = package().temp_dir().absFileName();
3097 string const realtmp = package().temp_dir().realPath();
3098 // We have to use os::path_prefix_is() here, instead of
3099 // simply prefixIs(), because the file name comes from
3100 // an external application and may need case adjustment.
3101 if (os::path_prefix_is(file_name, abstmp, os::CASE_ADJUSTED)
3102 || os::path_prefix_is(file_name, realtmp, os::CASE_ADJUSTED)) {
3103 // Needed by inverse dvi search. If it is a file
3104 // in tmpdir, call the apropriated function.
3105 // If tmpdir is a symlink, we may have the real
3106 // path passed back, so we correct for that.
3107 if (!prefixIs(file_name, abstmp))
3108 file_name = subst(file_name, realtmp, abstmp);
3109 buf = theBufferList().getBufferFromTmp(file_name);
3111 // Must replace extension of the file to be .lyx
3112 // and get full path
3113 FileName const s = fileSearch(string(),
3114 support::changeExtension(file_name, ".lyx"), "lyx");
3115 // Either change buffer or load the file
3116 if (theBufferList().exists(s))
3117 buf = theBufferList().getBuffer(s);
3118 else if (s.exists()) {
3119 buf = loadDocument(s);
3124 _("File does not exist: %1$s"),
3125 makeDisplayPath(file_name)));
3131 _("No buffer for file: %1$s."),
3132 makeDisplayPath(file_name))
3137 documentBufferView()->setCursorFromRow(row);
3143 Buffer::ExportStatus GuiView::GuiViewPrivate::runAndDestroy(const T& func, Buffer const * orig, Buffer * clone, string const & format)
3145 Buffer::ExportStatus const status = func(format);
3147 // the cloning operation will have produced a clone of the entire set of
3148 // documents, starting from the master. so we must delete those.
3149 Buffer * mbuf = const_cast<Buffer *>(clone->masterBuffer());
3151 busyBuffers.remove(orig);
3156 Buffer::ExportStatus GuiView::GuiViewPrivate::compileAndDestroy(Buffer const * orig, Buffer * clone, string const & format)
3158 Buffer::ExportStatus (Buffer::* mem_func)(std::string const &, bool) const = &Buffer::doExport;
3159 return runAndDestroy(lyx::bind(mem_func, clone, _1, true), orig, clone, format);
3163 Buffer::ExportStatus GuiView::GuiViewPrivate::exportAndDestroy(Buffer const * orig, Buffer * clone, string const & format)
3165 Buffer::ExportStatus (Buffer::* mem_func)(std::string const &, bool) const = &Buffer::doExport;
3166 return runAndDestroy(lyx::bind(mem_func, clone, _1, false), orig, clone, format);
3170 Buffer::ExportStatus GuiView::GuiViewPrivate::previewAndDestroy(Buffer const * orig, Buffer * clone, string const & format)
3172 Buffer::ExportStatus (Buffer::* mem_func)(std::string const &) const = &Buffer::preview;
3173 return runAndDestroy(lyx::bind(mem_func, clone, _1), orig, clone, format);
3177 bool GuiView::GuiViewPrivate::asyncBufferProcessing(
3178 string const & argument,
3179 Buffer const * used_buffer,
3180 docstring const & msg,
3181 Buffer::ExportStatus (*asyncFunc)(Buffer const *, Buffer *, string const &),
3182 Buffer::ExportStatus (Buffer::*syncFunc)(string const &, bool) const,
3183 Buffer::ExportStatus (Buffer::*previewFunc)(string const &) const)
3188 string format = argument;
3190 format = used_buffer->params().getDefaultOutputFormat();
3191 processing_format = format;
3192 #if EXPORT_in_THREAD
3194 progress_->clearMessages();
3197 GuiViewPrivate::busyBuffers.insert(used_buffer);
3198 Buffer * cloned_buffer = used_buffer->cloneFromMaster();
3199 if (!cloned_buffer) {
3200 Alert::error(_("Export Error"),
3201 _("Error cloning the Buffer."));
3204 QFuture<Buffer::ExportStatus> f = QtConcurrent::run(
3209 setPreviewFuture(f);
3210 last_export_format = used_buffer->params().bufferFormat();
3213 // We are asynchronous, so we don't know here anything about the success
3216 Buffer::ExportStatus status;
3218 // TODO check here if it breaks exporting with Qt < 4.4
3219 status = (used_buffer->*syncFunc)(format, true);
3220 } else if (previewFunc) {
3221 status = (used_buffer->*previewFunc)(format);
3224 handleExportStatus(gv_, status, format);
3226 return (status == Buffer::ExportSuccess
3227 || status == Buffer::PreviewSuccess);
3231 void GuiView::dispatchToBufferView(FuncRequest const & cmd, DispatchResult & dr)
3233 BufferView * bv = currentBufferView();
3234 LASSERT(bv, return);
3236 // Let the current BufferView dispatch its own actions.
3237 bv->dispatch(cmd, dr);
3238 if (dr.dispatched())
3241 // Try with the document BufferView dispatch if any.
3242 BufferView * doc_bv = documentBufferView();
3243 if (doc_bv && doc_bv != bv) {
3244 doc_bv->dispatch(cmd, dr);
3245 if (dr.dispatched())
3249 // Then let the current Cursor dispatch its own actions.
3250 bv->cursor().dispatch(cmd);
3252 // update completion. We do it here and not in
3253 // processKeySym to avoid another redraw just for a
3254 // changed inline completion
3255 if (cmd.origin() == FuncRequest::KEYBOARD) {
3256 if (cmd.action() == LFUN_SELF_INSERT
3257 || (cmd.action() == LFUN_ERT_INSERT && bv->cursor().inMathed()))
3258 updateCompletion(bv->cursor(), true, true);
3259 else if (cmd.action() == LFUN_CHAR_DELETE_BACKWARD)
3260 updateCompletion(bv->cursor(), false, true);
3262 updateCompletion(bv->cursor(), false, false);
3265 dr = bv->cursor().result();
3269 void GuiView::dispatch(FuncRequest const & cmd, DispatchResult & dr)
3271 BufferView * bv = currentBufferView();
3272 // By default we won't need any update.
3273 dr.screenUpdate(Update::None);
3274 // assume cmd will be dispatched
3275 dr.dispatched(true);
3277 Buffer * doc_buffer = documentBufferView()
3278 ? &(documentBufferView()->buffer()) : 0;
3280 if (cmd.origin() == FuncRequest::TOC) {
3281 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
3282 // FIXME: do we need to pass a DispatchResult object here?
3283 toc->doDispatch(bv->cursor(), cmd);
3287 string const argument = to_utf8(cmd.argument());
3289 switch(cmd.action()) {
3290 case LFUN_BUFFER_CHILD_OPEN:
3291 openChildDocument(to_utf8(cmd.argument()));
3294 case LFUN_BUFFER_IMPORT:
3295 importDocument(to_utf8(cmd.argument()));
3298 case LFUN_BUFFER_EXPORT: {
3301 // GCC only sees strfwd.h when building merged
3302 if (::lyx::operator==(cmd.argument(), "custom")) {
3303 dispatch(FuncRequest(LFUN_DIALOG_SHOW, "sendto"), dr);
3306 /* TODO/Review: Is it a problem to also export the children?
3307 See the update_unincluded flag */
3308 d.asyncBufferProcessing(argument,
3311 &GuiViewPrivate::exportAndDestroy,
3314 // TODO Inform user about success
3318 case LFUN_BUFFER_EXPORT_AS:
3319 LASSERT(doc_buffer, break);
3320 exportBufferAs(*doc_buffer);
3323 case LFUN_BUFFER_UPDATE: {
3324 d.asyncBufferProcessing(argument,
3327 &GuiViewPrivate::compileAndDestroy,
3332 case LFUN_BUFFER_VIEW: {
3333 d.asyncBufferProcessing(argument,
3335 _("Previewing ..."),
3336 &GuiViewPrivate::previewAndDestroy,
3341 case LFUN_MASTER_BUFFER_UPDATE: {
3342 d.asyncBufferProcessing(argument,
3343 (doc_buffer ? doc_buffer->masterBuffer() : 0),
3345 &GuiViewPrivate::compileAndDestroy,
3350 case LFUN_MASTER_BUFFER_VIEW: {
3351 d.asyncBufferProcessing(argument,
3352 (doc_buffer ? doc_buffer->masterBuffer() : 0),
3354 &GuiViewPrivate::previewAndDestroy,
3355 0, &Buffer::preview);
3358 case LFUN_BUFFER_SWITCH: {
3359 string const file_name = to_utf8(cmd.argument());
3360 if (!FileName::isAbsolute(file_name)) {
3362 dr.setMessage(_("Absolute filename expected."));
3366 Buffer * buffer = theBufferList().getBuffer(FileName(file_name));
3369 dr.setMessage(_("Document not loaded"));
3373 // Do we open or switch to the buffer in this view ?
3374 if (workArea(*buffer)
3375 || lyxrc.open_buffers_in_tabs || !documentBufferView()) {
3380 // Look for the buffer in other views
3381 QList<int> const ids = guiApp->viewIds();
3383 for (; i != ids.size(); ++i) {
3384 GuiView & gv = guiApp->view(ids[i]);
3385 if (gv.workArea(*buffer)) {
3386 gv.activateWindow();
3387 gv.setBuffer(buffer);
3392 // If necessary, open a new window as a last resort
3393 if (i == ids.size()) {
3394 lyx::dispatch(FuncRequest(LFUN_WINDOW_NEW));
3400 case LFUN_BUFFER_NEXT:
3401 gotoNextOrPreviousBuffer(NEXTBUFFER);
3404 case LFUN_BUFFER_PREVIOUS:
3405 gotoNextOrPreviousBuffer(PREVBUFFER);
3408 case LFUN_COMMAND_EXECUTE: {
3409 bool const show_it = cmd.argument() != "off";
3410 // FIXME: this is a hack, "minibuffer" should not be
3412 if (GuiToolbar * t = toolbar("minibuffer")) {
3413 t->setVisible(show_it);
3414 if (show_it && t->commandBuffer())
3415 t->commandBuffer()->setFocus();
3419 case LFUN_DROP_LAYOUTS_CHOICE:
3420 d.layout_->showPopup();
3423 case LFUN_MENU_OPEN:
3424 if (QMenu * menu = guiApp->menus().menu(toqstr(cmd.argument()), *this))
3425 menu->exec(QCursor::pos());
3428 case LFUN_FILE_INSERT:
3429 insertLyXFile(cmd.argument());
3432 case LFUN_FILE_INSERT_PLAINTEXT:
3433 case LFUN_FILE_INSERT_PLAINTEXT_PARA: {
3434 bool const as_paragraph = (cmd.action() == LFUN_FILE_INSERT_PLAINTEXT_PARA);
3435 string const fname = to_utf8(cmd.argument());
3436 if (!fname.empty() && !FileName::isAbsolute(fname)) {
3437 dr.setMessage(_("Absolute filename expected."));
3441 FileName filename(fname);
3442 if (fname.empty()) {
3443 FileDialog dlg(qt_("Select file to insert"), (as_paragraph ?
3444 LFUN_FILE_INSERT_PLAINTEXT_PARA : LFUN_FILE_INSERT_PLAINTEXT));
3446 FileDialog::Result result = dlg.open(toqstr(bv->buffer().filePath()),
3447 QStringList(qt_("All Files (*)")));
3449 if (result.first == FileDialog::Later || result.second.isEmpty()) {
3450 dr.setMessage(_("Canceled."));
3454 filename.set(fromqstr(result.second));
3458 FuncRequest const new_cmd(cmd, filename.absoluteFilePath());
3459 bv->dispatch(new_cmd, dr);
3464 case LFUN_BUFFER_RELOAD: {
3465 LASSERT(doc_buffer, break);
3468 if (!doc_buffer->isClean()) {
3469 docstring const file =
3470 makeDisplayPath(doc_buffer->absFileName(), 20);
3471 docstring text = bformat(_("Any changes will be lost. "
3472 "Are you sure you want to revert to the saved version "
3473 "of the document %1$s?"), file);
3474 ret = Alert::prompt(_("Revert to saved document?"),
3475 text, 1, 1, _("&Revert"), _("&Cancel"));
3479 doc_buffer->markClean();
3480 reloadBuffer(*doc_buffer);
3481 dr.forceBufferUpdate();
3486 case LFUN_BUFFER_WRITE:
3487 LASSERT(doc_buffer, break);
3488 saveBuffer(*doc_buffer);
3491 case LFUN_BUFFER_WRITE_AS:
3492 LASSERT(doc_buffer, break);
3493 renameBuffer(*doc_buffer, cmd.argument());
3496 case LFUN_BUFFER_WRITE_ALL: {
3497 Buffer * first = theBufferList().first();
3500 message(_("Saving all documents..."));
3501 // We cannot use a for loop as the buffer list cycles.
3504 if (!b->isClean()) {
3506 LYXERR(Debug::ACTION, "Saved " << b->absFileName());
3508 b = theBufferList().next(b);
3509 } while (b != first);
3510 dr.setMessage(_("All documents saved."));
3514 case LFUN_BUFFER_CLOSE:
3518 case LFUN_BUFFER_CLOSE_ALL:
3522 case LFUN_TOOLBAR_TOGGLE: {
3523 string const name = cmd.getArg(0);
3524 if (GuiToolbar * t = toolbar(name))
3529 case LFUN_DIALOG_UPDATE: {
3530 string const name = to_utf8(cmd.argument());
3531 if (name == "prefs" || name == "document")
3532 updateDialog(name, string());
3533 else if (name == "paragraph")
3534 lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
3535 else if (currentBufferView()) {
3536 Inset * inset = currentBufferView()->editedInset(name);
3537 // Can only update a dialog connected to an existing inset
3539 // FIXME: get rid of this indirection; GuiView ask the inset
3540 // if he is kind enough to update itself...
3541 FuncRequest fr(LFUN_INSET_DIALOG_UPDATE, cmd.argument());
3542 //FIXME: pass DispatchResult here?
3543 inset->dispatch(currentBufferView()->cursor(), fr);
3549 case LFUN_DIALOG_TOGGLE: {
3550 FuncCode const func_code = isDialogVisible(cmd.getArg(0))
3551 ? LFUN_DIALOG_HIDE : LFUN_DIALOG_SHOW;
3552 dispatch(FuncRequest(func_code, cmd.argument()), dr);
3556 case LFUN_DIALOG_DISCONNECT_INSET:
3557 disconnectDialog(to_utf8(cmd.argument()));
3560 case LFUN_DIALOG_HIDE: {
3561 guiApp->hideDialogs(to_utf8(cmd.argument()), 0);
3565 case LFUN_DIALOG_SHOW: {
3566 string const name = cmd.getArg(0);
3567 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
3569 if (name == "character") {
3570 data = freefont2string();
3572 showDialog("character", data);
3573 } else if (name == "latexlog") {
3574 Buffer::LogType type;
3575 string const logfile = doc_buffer->logName(&type);
3577 case Buffer::latexlog:
3580 case Buffer::buildlog:
3584 data += Lexer::quoteString(logfile);
3585 showDialog("log", data);
3586 } else if (name == "vclog") {
3587 string const data = "vc " +
3588 Lexer::quoteString(doc_buffer->lyxvc().getLogFile());
3589 showDialog("log", data);
3590 } else if (name == "symbols") {
3591 data = bv->cursor().getEncoding()->name();
3593 showDialog("symbols", data);
3595 } else if (name == "prefs" && isFullScreen()) {
3596 lfunUiToggle("fullscreen");
3597 showDialog("prefs", data);
3599 showDialog(name, data);
3604 dr.setMessage(cmd.argument());
3607 case LFUN_UI_TOGGLE: {
3608 string arg = cmd.getArg(0);
3609 if (!lfunUiToggle(arg)) {
3610 docstring const msg = "ui-toggle " + _("%1$s unknown command!");
3611 dr.setMessage(bformat(msg, from_utf8(arg)));
3613 // Make sure the keyboard focus stays in the work area.
3618 case LFUN_VIEW_SPLIT: {
3619 LASSERT(doc_buffer, break);
3620 string const orientation = cmd.getArg(0);
3621 d.splitter_->setOrientation(orientation == "vertical"
3622 ? Qt::Vertical : Qt::Horizontal);
3623 TabWorkArea * twa = addTabWorkArea();
3624 GuiWorkArea * wa = twa->addWorkArea(*doc_buffer, *this);
3625 setCurrentWorkArea(wa);
3628 case LFUN_TAB_GROUP_CLOSE:
3629 if (TabWorkArea * twa = d.currentTabWorkArea()) {
3630 closeTabWorkArea(twa);
3631 d.current_work_area_ = 0;
3632 twa = d.currentTabWorkArea();
3633 // Switch to the next GuiWorkArea in the found TabWorkArea.
3635 // Make sure the work area is up to date.
3636 setCurrentWorkArea(twa->currentWorkArea());
3638 setCurrentWorkArea(0);
3643 case LFUN_VIEW_CLOSE:
3644 if (TabWorkArea * twa = d.currentTabWorkArea()) {
3645 closeWorkArea(twa->currentWorkArea());
3646 d.current_work_area_ = 0;
3647 twa = d.currentTabWorkArea();
3648 // Switch to the next GuiWorkArea in the found TabWorkArea.
3650 // Make sure the work area is up to date.
3651 setCurrentWorkArea(twa->currentWorkArea());
3653 setCurrentWorkArea(0);
3658 case LFUN_COMPLETION_INLINE:
3659 if (d.current_work_area_)
3660 d.current_work_area_->completer().showInline();
3663 case LFUN_COMPLETION_POPUP:
3664 if (d.current_work_area_)
3665 d.current_work_area_->completer().showPopup();
3669 case LFUN_COMPLETION_COMPLETE:
3670 if (d.current_work_area_)
3671 d.current_work_area_->completer().tab();
3674 case LFUN_COMPLETION_CANCEL:
3675 if (d.current_work_area_) {
3676 if (d.current_work_area_->completer().popupVisible())
3677 d.current_work_area_->completer().hidePopup();
3679 d.current_work_area_->completer().hideInline();
3683 case LFUN_COMPLETION_ACCEPT:
3684 if (d.current_work_area_)
3685 d.current_work_area_->completer().activate();
3688 case LFUN_BUFFER_ZOOM_IN:
3689 case LFUN_BUFFER_ZOOM_OUT:
3690 if (cmd.argument().empty()) {
3691 if (cmd.action() == LFUN_BUFFER_ZOOM_IN)
3696 lyxrc.zoom += convert<int>(cmd.argument());
3698 if (lyxrc.zoom < 10)
3701 // The global QPixmapCache is used in GuiPainter to cache text
3702 // painting so we must reset it.
3703 QPixmapCache::clear();
3704 guiApp->fontLoader().update();
3705 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
3708 case LFUN_VC_REGISTER:
3709 case LFUN_VC_RENAME:
3711 case LFUN_VC_CHECK_IN:
3712 case LFUN_VC_CHECK_OUT:
3713 case LFUN_VC_REPO_UPDATE:
3714 case LFUN_VC_LOCKING_TOGGLE:
3715 case LFUN_VC_REVERT:
3716 case LFUN_VC_UNDO_LAST:
3717 case LFUN_VC_COMMAND:
3718 case LFUN_VC_COMPARE:
3719 dispatchVC(cmd, dr);
3722 case LFUN_SERVER_GOTO_FILE_ROW:
3723 goToFileRow(to_utf8(cmd.argument()));
3726 case LFUN_FORWARD_SEARCH: {
3727 Buffer const * doc_master = doc_buffer->masterBuffer();
3728 FileName const path(doc_master->temppath());
3729 string const texname = doc_master->isChild(doc_buffer)
3730 ? DocFileName(changeExtension(
3731 doc_buffer->absFileName(),
3732 "tex")).mangledFileName()
3733 : doc_buffer->latexName();
3734 string const fulltexname =
3735 support::makeAbsPath(texname, doc_master->temppath()).absFileName();
3736 string const mastername =
3737 removeExtension(doc_master->latexName());
3738 FileName const dviname(addName(path.absFileName(),
3739 addExtension(mastername, "dvi")));
3740 FileName const pdfname(addName(path.absFileName(),
3741 addExtension(mastername, "pdf")));
3742 bool const have_dvi = dviname.exists();
3743 bool const have_pdf = pdfname.exists();
3744 if (!have_dvi && !have_pdf) {
3745 dr.setMessage(_("Please, preview the document first."));
3748 string outname = dviname.onlyFileName();
3749 string command = lyxrc.forward_search_dvi;
3750 if (!have_dvi || (have_pdf &&
3751 pdfname.lastModified() > dviname.lastModified())) {
3752 outname = pdfname.onlyFileName();
3753 command = lyxrc.forward_search_pdf;
3756 DocIterator tmpcur = bv->cursor();
3758 while (tmpcur.inMathed())
3760 int row = tmpcur.inMathed() ? 0 : doc_buffer->texrow().getRowFromIdPos(
3761 tmpcur.paragraph().id(), tmpcur.pos());
3762 LYXERR(Debug::ACTION, "Forward search: row:" << row
3763 << " id:" << tmpcur.paragraph().id());
3764 if (!row || command.empty()) {
3765 dr.setMessage(_("Couldn't proceed."));
3768 string texrow = convert<string>(row);
3770 command = subst(command, "$$n", texrow);
3771 command = subst(command, "$$f", fulltexname);
3772 command = subst(command, "$$t", texname);
3773 command = subst(command, "$$o", outname);
3775 PathChanger p(path);
3777 one.startscript(Systemcall::DontWait, command);
3781 case LFUN_SPELLING_CONTINUOUSLY:
3782 lyxrc.spellcheck_continuously = !lyxrc.spellcheck_continuously;
3783 dr.screenUpdate(Update::Force | Update::FitCursor);
3787 // The LFUN must be for one of BufferView, Buffer or Cursor;
3789 dispatchToBufferView(cmd, dr);
3793 // Part of automatic menu appearance feature.
3794 if (isFullScreen()) {
3795 if (menuBar()->isVisible() && lyxrc.full_screen_menubar)
3797 if (statusBar()->isVisible())
3798 statusBar()->hide();
3803 bool GuiView::lfunUiToggle(string const & ui_component)
3805 if (ui_component == "scrollbar") {
3806 // hide() is of no help
3807 if (d.current_work_area_->verticalScrollBarPolicy() ==
3808 Qt::ScrollBarAlwaysOff)
3810 d.current_work_area_->setVerticalScrollBarPolicy(
3811 Qt::ScrollBarAsNeeded);
3813 d.current_work_area_->setVerticalScrollBarPolicy(
3814 Qt::ScrollBarAlwaysOff);
3815 } else if (ui_component == "statusbar") {
3816 statusBar()->setVisible(!statusBar()->isVisible());
3817 } else if (ui_component == "menubar") {
3818 menuBar()->setVisible(!menuBar()->isVisible());
3820 if (ui_component == "frame") {
3822 getContentsMargins(&l, &t, &r, &b);
3823 //are the frames in default state?
3824 d.current_work_area_->setFrameStyle(QFrame::NoFrame);
3826 setContentsMargins(-2, -2, -2, -2);
3828 setContentsMargins(0, 0, 0, 0);
3831 if (ui_component == "fullscreen") {
3839 void GuiView::toggleFullScreen()
3841 if (isFullScreen()) {
3842 for (int i = 0; i != d.splitter_->count(); ++i)
3843 d.tabWorkArea(i)->setFullScreen(false);
3844 setContentsMargins(0, 0, 0, 0);
3845 setWindowState(windowState() ^ Qt::WindowFullScreen);
3848 statusBar()->show();
3851 hideDialogs("prefs", 0);
3852 for (int i = 0; i != d.splitter_->count(); ++i)
3853 d.tabWorkArea(i)->setFullScreen(true);
3854 setContentsMargins(-2, -2, -2, -2);
3856 setWindowState(windowState() ^ Qt::WindowFullScreen);
3857 statusBar()->hide();
3858 if (lyxrc.full_screen_menubar)
3860 if (lyxrc.full_screen_toolbars) {
3861 ToolbarMap::iterator end = d.toolbars_.end();
3862 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
3867 // give dialogs like the TOC a chance to adapt
3872 Buffer const * GuiView::updateInset(Inset const * inset)
3877 Buffer const * inset_buffer = &(inset->buffer());
3879 for (int i = 0; i != d.splitter_->count(); ++i) {
3880 GuiWorkArea * wa = d.tabWorkArea(i)->currentWorkArea();
3883 Buffer const * buffer = &(wa->bufferView().buffer());
3884 if (inset_buffer == buffer)
3885 wa->scheduleRedraw();
3887 return inset_buffer;
3891 void GuiView::restartCursor()
3893 /* When we move around, or type, it's nice to be able to see
3894 * the cursor immediately after the keypress.
3896 if (d.current_work_area_)
3897 d.current_work_area_->startBlinkingCursor();
3899 // Take this occasion to update the other GUI elements.
3905 void GuiView::updateCompletion(Cursor & cur, bool start, bool keep)
3907 if (d.current_work_area_)
3908 d.current_work_area_->completer().updateVisibility(cur, start, keep);
3913 // This list should be kept in sync with the list of insets in
3914 // src/insets/Inset.cpp. I.e., if a dialog goes with an inset, the
3915 // dialog should have the same name as the inset.
3916 // Changes should be also recorded in LFUN_DIALOG_SHOW doxygen
3917 // docs in LyXAction.cpp.
3919 char const * const dialognames[] = {
3921 "aboutlyx", "bibitem", "bibtex", "box", "branch", "changes", "character",
3922 "citation", "compare", "comparehistory", "document", "errorlist", "ert",
3923 "external", "file", "findreplace", "findreplaceadv", "float", "graphics",
3924 "href", "include", "index", "index_print", "info", "listings", "label", "line",
3925 "log", "mathdelimiter", "mathmatrix", "mathspace", "nomenclature",
3926 "nomencl_print", "note", "paragraph", "phantom", "prefs", "print", "ref",
3927 "sendto", "space", "spellchecker", "symbols", "tabular", "tabularcreate",
3928 "thesaurus", "texinfo", "toc", "view-source", "vspace", "wrap", "progress"};
3930 char const * const * const end_dialognames =
3931 dialognames + (sizeof(dialognames) / sizeof(char *));
3935 cmpCStr(char const * name) : name_(name) {}
3936 bool operator()(char const * other) {
3937 return strcmp(other, name_) == 0;
3944 bool isValidName(string const & name)
3946 return find_if(dialognames, end_dialognames,
3947 cmpCStr(name.c_str())) != end_dialognames;
3953 void GuiView::resetDialogs()
3955 // Make sure that no LFUN uses any GuiView.
3956 guiApp->setCurrentView(0);
3960 constructToolbars();
3961 guiApp->menus().fillMenuBar(menuBar(), this, false);
3962 d.layout_->updateContents(true);
3963 // Now update controls with current buffer.
3964 guiApp->setCurrentView(this);
3970 Dialog * GuiView::findOrBuild(string const & name, bool hide_it)
3972 if (!isValidName(name))
3975 map<string, DialogPtr>::iterator it = d.dialogs_.find(name);
3977 if (it != d.dialogs_.end()) {
3979 it->second->hideView();
3980 return it->second.get();
3983 Dialog * dialog = build(name);
3984 d.dialogs_[name].reset(dialog);
3985 if (lyxrc.allow_geometry_session)
3986 dialog->restoreSession();
3993 void GuiView::showDialog(string const & name, string const & data,
3996 triggerShowDialog(toqstr(name), toqstr(data), inset);
4000 void GuiView::doShowDialog(QString const & qname, QString const & qdata,
4006 const string name = fromqstr(qname);
4007 const string data = fromqstr(qdata);
4011 Dialog * dialog = findOrBuild(name, false);
4013 bool const visible = dialog->isVisibleView();
4014 dialog->showData(data);
4015 if (inset && currentBufferView())
4016 currentBufferView()->editInset(name, inset);
4017 // We only set the focus to the new dialog if it was not yet
4018 // visible in order not to change the existing previous behaviour
4020 // activateWindow is needed for floating dockviews
4021 dialog->asQWidget()->raise();
4022 dialog->asQWidget()->activateWindow();
4023 dialog->asQWidget()->setFocus();
4027 catch (ExceptionMessage const & ex) {
4035 bool GuiView::isDialogVisible(string const & name) const
4037 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
4038 if (it == d.dialogs_.end())
4040 return it->second.get()->isVisibleView() && !it->second.get()->isClosing();
4044 void GuiView::hideDialog(string const & name, Inset * inset)
4046 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
4047 if (it == d.dialogs_.end())
4051 if (!currentBufferView())
4053 if (inset != currentBufferView()->editedInset(name))
4057 Dialog * const dialog = it->second.get();
4058 if (dialog->isVisibleView())
4060 if (currentBufferView())
4061 currentBufferView()->editInset(name, 0);
4065 void GuiView::disconnectDialog(string const & name)
4067 if (!isValidName(name))
4069 if (currentBufferView())
4070 currentBufferView()->editInset(name, 0);
4074 void GuiView::hideAll() const
4076 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
4077 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
4079 for(; it != end; ++it)
4080 it->second->hideView();
4084 void GuiView::updateDialogs()
4086 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
4087 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
4089 for(; it != end; ++it) {
4090 Dialog * dialog = it->second.get();
4092 if (dialog->needBufferOpen() && !documentBufferView())
4093 hideDialog(fromqstr(dialog->name()), 0);
4094 else if (dialog->isVisibleView())
4095 dialog->checkStatus();
4102 Dialog * createDialog(GuiView & lv, string const & name);
4104 // will be replaced by a proper factory...
4105 Dialog * createGuiAbout(GuiView & lv);
4106 Dialog * createGuiBibtex(GuiView & lv);
4107 Dialog * createGuiChanges(GuiView & lv);
4108 Dialog * createGuiCharacter(GuiView & lv);
4109 Dialog * createGuiCitation(GuiView & lv);
4110 Dialog * createGuiCompare(GuiView & lv);
4111 Dialog * createGuiCompareHistory(GuiView & lv);
4112 Dialog * createGuiDelimiter(GuiView & lv);
4113 Dialog * createGuiDocument(GuiView & lv);
4114 Dialog * createGuiErrorList(GuiView & lv);
4115 Dialog * createGuiExternal(GuiView & lv);
4116 Dialog * createGuiGraphics(GuiView & lv);
4117 Dialog * createGuiInclude(GuiView & lv);
4118 Dialog * createGuiIndex(GuiView & lv);
4119 Dialog * createGuiListings(GuiView & lv);
4120 Dialog * createGuiLog(GuiView & lv);
4121 Dialog * createGuiMathMatrix(GuiView & lv);
4122 Dialog * createGuiNote(GuiView & lv);
4123 Dialog * createGuiParagraph(GuiView & lv);
4124 Dialog * createGuiPhantom(GuiView & lv);
4125 Dialog * createGuiPreferences(GuiView & lv);
4126 Dialog * createGuiPrint(GuiView & lv);
4127 Dialog * createGuiPrintindex(GuiView & lv);
4128 Dialog * createGuiRef(GuiView & lv);
4129 Dialog * createGuiSearch(GuiView & lv);
4130 Dialog * createGuiSearchAdv(GuiView & lv);
4131 Dialog * createGuiSendTo(GuiView & lv);
4132 Dialog * createGuiShowFile(GuiView & lv);
4133 Dialog * createGuiSpellchecker(GuiView & lv);
4134 Dialog * createGuiSymbols(GuiView & lv);
4135 Dialog * createGuiTabularCreate(GuiView & lv);
4136 Dialog * createGuiTexInfo(GuiView & lv);
4137 Dialog * createGuiToc(GuiView & lv);
4138 Dialog * createGuiThesaurus(GuiView & lv);
4139 Dialog * createGuiViewSource(GuiView & lv);
4140 Dialog * createGuiWrap(GuiView & lv);
4141 Dialog * createGuiProgressView(GuiView & lv);
4145 Dialog * GuiView::build(string const & name)
4147 LASSERT(isValidName(name), return 0);
4149 Dialog * dialog = createDialog(*this, name);
4153 if (name == "aboutlyx")
4154 return createGuiAbout(*this);
4155 if (name == "bibtex")
4156 return createGuiBibtex(*this);
4157 if (name == "changes")
4158 return createGuiChanges(*this);
4159 if (name == "character")
4160 return createGuiCharacter(*this);
4161 if (name == "citation")
4162 return createGuiCitation(*this);
4163 if (name == "compare")
4164 return createGuiCompare(*this);
4165 if (name == "comparehistory")
4166 return createGuiCompareHistory(*this);
4167 if (name == "document")
4168 return createGuiDocument(*this);
4169 if (name == "errorlist")
4170 return createGuiErrorList(*this);
4171 if (name == "external")
4172 return createGuiExternal(*this);
4174 return createGuiShowFile(*this);
4175 if (name == "findreplace")
4176 return createGuiSearch(*this);
4177 if (name == "findreplaceadv")
4178 return createGuiSearchAdv(*this);
4179 if (name == "graphics")
4180 return createGuiGraphics(*this);
4181 if (name == "include")
4182 return createGuiInclude(*this);
4183 if (name == "index")
4184 return createGuiIndex(*this);
4185 if (name == "index_print")
4186 return createGuiPrintindex(*this);
4187 if (name == "listings")
4188 return createGuiListings(*this);
4190 return createGuiLog(*this);
4191 if (name == "mathdelimiter")
4192 return createGuiDelimiter(*this);
4193 if (name == "mathmatrix")
4194 return createGuiMathMatrix(*this);
4196 return createGuiNote(*this);
4197 if (name == "paragraph")
4198 return createGuiParagraph(*this);
4199 if (name == "phantom")
4200 return createGuiPhantom(*this);
4201 if (name == "prefs")
4202 return createGuiPreferences(*this);
4203 if (name == "print")
4204 return createGuiPrint(*this);
4206 return createGuiRef(*this);
4207 if (name == "sendto")
4208 return createGuiSendTo(*this);
4209 if (name == "spellchecker")
4210 return createGuiSpellchecker(*this);
4211 if (name == "symbols")
4212 return createGuiSymbols(*this);
4213 if (name == "tabularcreate")
4214 return createGuiTabularCreate(*this);
4215 if (name == "texinfo")
4216 return createGuiTexInfo(*this);
4217 if (name == "thesaurus")
4218 return createGuiThesaurus(*this);
4220 return createGuiToc(*this);
4221 if (name == "view-source")
4222 return createGuiViewSource(*this);
4224 return createGuiWrap(*this);
4225 if (name == "progress")
4226 return createGuiProgressView(*this);
4232 } // namespace frontend
4235 #include "moc_GuiView.cpp"