3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Lars Gullik Bjønnes
8 * \author Abdelrazak Younes
11 * Full author contact details are available in file CREDITS.
19 #include "DispatchResult.h"
20 #include "FileDialog.h"
21 #include "FontLoader.h"
22 #include "GuiApplication.h"
23 #include "GuiCommandBuffer.h"
24 #include "GuiCompleter.h"
25 #include "GuiKeySymbol.h"
27 #include "GuiToolbar.h"
28 #include "GuiWorkArea.h"
29 #include "GuiProgress.h"
30 #include "LayoutBox.h"
34 #include "qt_helpers.h"
36 #include "frontends/alert.h"
38 #include "buffer_funcs.h"
40 #include "BufferList.h"
41 #include "BufferParams.h"
42 #include "BufferView.h"
44 #include "Converter.h"
46 #include "CutAndPaste.h"
48 #include "ErrorList.h"
50 #include "FuncStatus.h"
51 #include "FuncRequest.h"
55 #include "LyXAction.h"
59 #include "Paragraph.h"
60 #include "SpellChecker.h"
62 #include "TextClass.h"
67 #include "support/convert.h"
68 #include "support/debug.h"
69 #include "support/ExceptionMessage.h"
70 #include "support/FileName.h"
71 #include "support/filetools.h"
72 #include "support/gettext.h"
73 #include "support/filetools.h"
74 #include "support/ForkedCalls.h"
75 #include "support/lassert.h"
76 #include "support/lstrings.h"
77 #include "support/os.h"
78 #include "support/Package.h"
79 #include "support/Path.h"
80 #include "support/Systemcall.h"
81 #include "support/Timeout.h"
82 #include "support/ProgressInterface.h"
85 #include <QApplication>
86 #include <QCloseEvent>
88 #include <QDesktopWidget>
89 #include <QDragEnterEvent>
92 #include <QFutureWatcher>
101 #include <QPixmapCache>
103 #include <QPushButton>
104 #include <QScrollBar>
106 #include <QShowEvent>
108 #include <QStackedWidget>
109 #include <QStatusBar>
110 #include <QtConcurrentRun>
118 #define EXPORT_in_THREAD 1
121 #include "support/bind.h"
125 #ifdef HAVE_SYS_TIME_H
126 # include <sys/time.h>
134 using namespace lyx::support;
138 using support::addExtension;
139 using support::changeExtension;
140 using support::removeExtension;
146 class BackgroundWidget : public QWidget
151 LYXERR(Debug::GUI, "show banner: " << lyxrc.show_banner);
152 if (!lyxrc.show_banner)
154 /// The text to be written on top of the pixmap
155 QString const text = lyx_version ?
156 qt_("version ") + lyx_version : qt_("unknown version");
157 splash_ = getPixmap("images/", "banner", "png");
159 QPainter pain(&splash_);
160 pain.setPen(QColor(0, 0, 0));
162 // The font used to display the version info
163 font.setStyleHint(QFont::SansSerif);
164 font.setWeight(QFont::Bold);
165 font.setPointSize(int(toqstr(lyxrc.font_sizes[FONT_SIZE_LARGE]).toDouble()));
167 pain.drawText(190, 225, text);
168 setFocusPolicy(Qt::StrongFocus);
171 void paintEvent(QPaintEvent *)
173 int x = (width() - splash_.width()) / 2;
174 int y = (height() - splash_.height()) / 2;
176 pain.drawPixmap(x, y, splash_);
179 void keyPressEvent(QKeyEvent * ev)
182 setKeySymbol(&sym, ev);
184 guiApp->processKeySym(sym, q_key_state(ev->modifiers()));
196 /// Toolbar store providing access to individual toolbars by name.
197 typedef map<string, GuiToolbar *> ToolbarMap;
199 typedef shared_ptr<Dialog> DialogPtr;
204 struct GuiView::GuiViewPrivate
206 GuiViewPrivate(GuiView * gv)
207 : gv_(gv), current_work_area_(0), current_main_work_area_(0),
208 layout_(0), autosave_timeout_(5000),
211 // hardcode here the platform specific icon size
212 smallIconSize = 16; // scaling problems
213 normalIconSize = 20; // ok, default if iconsize.png is missing
214 bigIconSize = 26; // better for some math icons
216 // if it exists, use width of iconsize.png as normal size
217 QString const dir = toqstr(addPath("images", lyxrc.icon_set));
218 FileName const fn = lyx::libFileSearch(dir, "iconsize.png");
220 QImage image(toqstr(fn.absFileName()));
221 if (image.width() < int(smallIconSize))
222 normalIconSize = smallIconSize;
223 else if (image.width() > int(bigIconSize))
224 normalIconSize = bigIconSize;
226 normalIconSize = image.width();
229 splitter_ = new QSplitter;
230 bg_widget_ = new BackgroundWidget;
231 stack_widget_ = new QStackedWidget;
232 stack_widget_->addWidget(bg_widget_);
233 stack_widget_->addWidget(splitter_);
236 // TODO cleanup, remove the singleton, handle multiple Windows?
237 progress_ = ProgressInterface::instance();
238 if (!dynamic_cast<GuiProgress*>(progress_)) {
239 progress_ = new GuiProgress; // TODO who deletes it
240 ProgressInterface::setInstance(progress_);
243 dynamic_cast<GuiProgress*>(progress_),
244 SIGNAL(updateStatusBarMessage(QString const&)),
245 gv, SLOT(updateStatusBarMessage(QString const&)));
247 dynamic_cast<GuiProgress*>(progress_),
248 SIGNAL(clearMessageText()),
249 gv, SLOT(clearMessageText()));
256 delete stack_widget_;
259 QMenu * toolBarPopup(GuiView * parent)
261 // FIXME: translation
262 QMenu * menu = new QMenu(parent);
263 QActionGroup * iconSizeGroup = new QActionGroup(parent);
265 QAction * smallIcons = new QAction(iconSizeGroup);
266 smallIcons->setText(qt_("Small-sized icons"));
267 smallIcons->setCheckable(true);
268 QObject::connect(smallIcons, SIGNAL(triggered()),
269 parent, SLOT(smallSizedIcons()));
270 menu->addAction(smallIcons);
272 QAction * normalIcons = new QAction(iconSizeGroup);
273 normalIcons->setText(qt_("Normal-sized icons"));
274 normalIcons->setCheckable(true);
275 QObject::connect(normalIcons, SIGNAL(triggered()),
276 parent, SLOT(normalSizedIcons()));
277 menu->addAction(normalIcons);
279 QAction * bigIcons = new QAction(iconSizeGroup);
280 bigIcons->setText(qt_("Big-sized icons"));
281 bigIcons->setCheckable(true);
282 QObject::connect(bigIcons, SIGNAL(triggered()),
283 parent, SLOT(bigSizedIcons()));
284 menu->addAction(bigIcons);
286 unsigned int cur = parent->iconSize().width();
287 if ( cur == parent->d.smallIconSize)
288 smallIcons->setChecked(true);
289 else if (cur == parent->d.normalIconSize)
290 normalIcons->setChecked(true);
291 else if (cur == parent->d.bigIconSize)
292 bigIcons->setChecked(true);
299 stack_widget_->setCurrentWidget(bg_widget_);
300 bg_widget_->setUpdatesEnabled(true);
301 bg_widget_->setFocus();
304 int tabWorkAreaCount()
306 return splitter_->count();
309 TabWorkArea * tabWorkArea(int i)
311 return dynamic_cast<TabWorkArea *>(splitter_->widget(i));
314 TabWorkArea * currentTabWorkArea()
316 int areas = tabWorkAreaCount();
318 // The first TabWorkArea is always the first one, if any.
319 return tabWorkArea(0);
321 for (int i = 0; i != areas; ++i) {
322 TabWorkArea * twa = tabWorkArea(i);
323 if (current_main_work_area_ == twa->currentWorkArea())
327 // None has the focus so we just take the first one.
328 return tabWorkArea(0);
331 int countWorkAreasOf(Buffer & buf)
333 int areas = tabWorkAreaCount();
335 for (int i = 0; i != areas; ++i) {
336 TabWorkArea * twa = tabWorkArea(i);
337 if (twa->workArea(buf))
343 void setPreviewFuture(QFuture<Buffer::ExportStatus> const & f)
345 if (processing_thread_watcher_.isRunning()) {
346 // we prefer to cancel this preview in order to keep a snappy
350 processing_thread_watcher_.setFuture(f);
355 GuiWorkArea * current_work_area_;
356 GuiWorkArea * current_main_work_area_;
357 QSplitter * splitter_;
358 QStackedWidget * stack_widget_;
359 BackgroundWidget * bg_widget_;
361 ToolbarMap toolbars_;
362 ProgressInterface* progress_;
363 /// The main layout box.
365 * \warning Don't Delete! The layout box is actually owned by
366 * whichever toolbar contains it. All the GuiView class needs is a
367 * means of accessing it.
369 * FIXME: replace that with a proper model so that we are not limited
370 * to only one dialog.
375 map<string, DialogPtr> dialogs_;
377 unsigned int smallIconSize;
378 unsigned int normalIconSize;
379 unsigned int bigIconSize;
381 QTimer statusbar_timer_;
382 /// auto-saving of buffers
383 Timeout autosave_timeout_;
384 /// flag against a race condition due to multiclicks, see bug #1119
388 TocModels toc_models_;
391 QFutureWatcher<docstring> autosave_watcher_;
392 QFutureWatcher<Buffer::ExportStatus> processing_thread_watcher_;
394 string last_export_format;
395 string processing_format;
397 static QSet<Buffer const *> busyBuffers;
398 static Buffer::ExportStatus previewAndDestroy(Buffer const * orig, Buffer * buffer, string const & format);
399 static Buffer::ExportStatus exportAndDestroy(Buffer const * orig, Buffer * buffer, string const & format);
400 static Buffer::ExportStatus compileAndDestroy(Buffer const * orig, Buffer * buffer, string const & format);
401 static docstring autosaveAndDestroy(Buffer const * orig, Buffer * buffer);
404 static Buffer::ExportStatus runAndDestroy(const T& func, Buffer const * orig, Buffer * buffer, string const & format);
406 // TODO syncFunc/previewFunc: use bind
407 bool asyncBufferProcessing(string const & argument,
408 Buffer const * used_buffer,
409 docstring const & msg,
410 Buffer::ExportStatus (*asyncFunc)(Buffer const *, Buffer *, string const &),
411 Buffer::ExportStatus (Buffer::*syncFunc)(string const &, bool) const,
412 Buffer::ExportStatus (Buffer::*previewFunc)(string const &) const);
414 QVector<GuiWorkArea*> guiWorkAreas();
417 QSet<Buffer const *> GuiView::GuiViewPrivate::busyBuffers;
420 GuiView::GuiView(int id)
421 : d(*new GuiViewPrivate(this)), id_(id), closing_(false), busy_(0)
423 // GuiToolbars *must* be initialised before the menu bar.
424 normalSizedIcons(); // at least on Mac the default is 32 otherwise, which is huge
427 // set ourself as the current view. This is needed for the menu bar
428 // filling, at least for the static special menu item on Mac. Otherwise
429 // they are greyed out.
430 guiApp->setCurrentView(this);
432 // Fill up the menu bar.
433 guiApp->menus().fillMenuBar(menuBar(), this, true);
435 setCentralWidget(d.stack_widget_);
437 // Start autosave timer
438 if (lyxrc.autosave) {
439 d.autosave_timeout_.timeout.connect(bind(&GuiView::autoSave, this));
440 d.autosave_timeout_.setTimeout(lyxrc.autosave * 1000);
441 d.autosave_timeout_.start();
443 connect(&d.statusbar_timer_, SIGNAL(timeout()),
444 this, SLOT(clearMessage()));
446 // We don't want to keep the window in memory if it is closed.
447 setAttribute(Qt::WA_DeleteOnClose, true);
449 #if (!defined(Q_WS_WIN) && !defined(Q_WS_MACX))
450 // QIcon::fromTheme was introduced in Qt 4.6
451 #if (QT_VERSION >= 0x040600)
452 // assign an icon to main form. We do not do it under Qt/Win or Qt/Mac,
453 // since the icon is provided in the application bundle. We use a themed
454 // version when available and use the bundled one as fallback.
455 setWindowIcon(QIcon::fromTheme("lyx", getPixmap("images/", "lyx", "png")));
457 setWindowIcon(getPixmap("images/", "lyx", "png"));
461 resetWindowTitleAndIconText();
463 // use tabbed dock area for multiple docks
464 // (such as "source" and "messages")
465 setDockOptions(QMainWindow::ForceTabbedDocks);
468 setAcceptDrops(true);
470 // add busy indicator to statusbar
471 QLabel * busylabel = new QLabel(statusBar());
472 statusBar()->addPermanentWidget(busylabel);
473 QString fn = toqstr(lyx::libFileSearch("images", "busy.gif").absFileName());
474 QMovie * busyanim = new QMovie(fn, QByteArray(), busylabel);
475 busylabel->setMovie(busyanim);
479 connect(&d.processing_thread_watcher_, SIGNAL(started()),
480 busylabel, SLOT(show()));
481 connect(&d.processing_thread_watcher_, SIGNAL(finished()),
482 busylabel, SLOT(hide()));
484 statusBar()->setSizeGripEnabled(true);
487 connect(&d.autosave_watcher_, SIGNAL(finished()), this,
488 SLOT(autoSaveThreadFinished()));
490 connect(&d.processing_thread_watcher_, SIGNAL(started()), this,
491 SLOT(processingThreadStarted()));
492 connect(&d.processing_thread_watcher_, SIGNAL(finished()), this,
493 SLOT(processingThreadFinished()));
495 connect(this, SIGNAL(triggerShowDialog(QString const &, QString const &, Inset *)),
496 SLOT(doShowDialog(QString const &, QString const &, Inset *)));
498 // Forbid too small unresizable window because it can happen
499 // with some window manager under X11.
500 setMinimumSize(300, 200);
502 if (lyxrc.allow_geometry_session) {
503 // Now take care of session management.
508 // no session handling, default to a sane size.
509 setGeometry(50, 50, 690, 510);
512 // clear session data if any.
514 settings.remove("views");
524 QVector<GuiWorkArea*> GuiView::GuiViewPrivate::guiWorkAreas()
526 QVector<GuiWorkArea*> areas;
527 for (int i = 0; i < tabWorkAreaCount(); i++) {
528 TabWorkArea* ta = tabWorkArea(i);
529 for (int u = 0; u < ta->count(); u++) {
530 areas << ta->workArea(u);
536 static void handleExportStatus(GuiView * view, Buffer::ExportStatus status,
537 string const & format)
539 docstring const fmt = formats.prettyName(format);
542 case Buffer::ExportSuccess:
543 msg = bformat(_("Successful export to format: %1$s"), fmt);
545 case Buffer::ExportCancel:
546 msg = _("Document export cancelled.");
548 case Buffer::ExportError:
549 case Buffer::ExportNoPathToFormat:
550 case Buffer::ExportTexPathHasSpaces:
551 case Buffer::ExportConverterError:
552 msg = bformat(_("Error while exporting format: %1$s"), fmt);
554 case Buffer::PreviewSuccess:
555 msg = bformat(_("Successful preview of format: %1$s"), fmt);
557 case Buffer::PreviewError:
558 msg = bformat(_("Error while previewing format: %1$s"), fmt);
565 void GuiView::processingThreadStarted()
570 void GuiView::processingThreadFinished()
572 QFutureWatcher<Buffer::ExportStatus> const * watcher =
573 static_cast<QFutureWatcher<Buffer::ExportStatus> const *>(sender());
575 Buffer::ExportStatus const status = watcher->result();
576 handleExportStatus(this, status, d.processing_format);
579 BufferView const * const bv = currentBufferView();
580 if (bv && !bv->buffer().errorList("Export").empty()) {
584 errors(d.last_export_format);
588 void GuiView::autoSaveThreadFinished()
590 QFutureWatcher<docstring> const * watcher =
591 static_cast<QFutureWatcher<docstring> const *>(sender());
592 message(watcher->result());
597 void GuiView::saveLayout() const
600 settings.beginGroup("views");
601 settings.beginGroup(QString::number(id_));
603 settings.setValue("pos", pos());
604 settings.setValue("size", size());
606 settings.setValue("geometry", saveGeometry());
608 settings.setValue("layout", saveState(0));
609 settings.setValue("icon_size", iconSize());
613 void GuiView::saveUISettings() const
615 // Save the toolbar private states
616 ToolbarMap::iterator end = d.toolbars_.end();
617 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
618 it->second->saveSession();
619 // Now take care of all other dialogs
620 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
621 for (; it!= d.dialogs_.end(); ++it)
622 it->second->saveSession();
626 bool GuiView::restoreLayout()
629 settings.beginGroup("views");
630 settings.beginGroup(QString::number(id_));
631 QString const icon_key = "icon_size";
632 if (!settings.contains(icon_key))
635 //code below is skipped when when ~/.config/LyX is (re)created
636 QSize icon_size = settings.value(icon_key).toSize();
637 // Check whether session size changed.
638 if (icon_size.width() != int(d.smallIconSize) &&
639 icon_size.width() != int(d.normalIconSize) &&
640 icon_size.width() != int(d.bigIconSize)) {
641 icon_size.setWidth(d.normalIconSize);
642 icon_size.setHeight(d.normalIconSize);
644 setIconSize(icon_size);
647 QPoint pos = settings.value("pos", QPoint(50, 50)).toPoint();
648 QSize size = settings.value("size", QSize(690, 510)).toSize();
652 // Work-around for bug #6034: the window ends up in an undetermined
653 // state when trying to restore a maximized window when it is
654 // already maximized.
655 if (!(windowState() & Qt::WindowMaximized))
656 if (!restoreGeometry(settings.value("geometry").toByteArray()))
657 setGeometry(50, 50, 690, 510);
659 // Make sure layout is correctly oriented.
660 setLayoutDirection(qApp->layoutDirection());
662 // Allow the toc and view-source dock widget to be restored if needed.
664 if ((dialog = findOrBuild("toc", true)))
665 // see bug 5082. At least setup title and enabled state.
666 // Visibility will be adjusted by restoreState below.
667 dialog->prepareView();
668 if ((dialog = findOrBuild("view-source", true)))
669 dialog->prepareView();
670 if ((dialog = findOrBuild("progress", true)))
671 dialog->prepareView();
672 if ((dialog = findOrBuild("findreplaceadv", true)))
673 dialog->prepareView();
675 if (!restoreState(settings.value("layout").toByteArray(), 0))
682 GuiToolbar * GuiView::toolbar(string const & name)
684 ToolbarMap::iterator it = d.toolbars_.find(name);
685 if (it != d.toolbars_.end())
688 LYXERR(Debug::GUI, "Toolbar::display: no toolbar named " << name);
693 void GuiView::constructToolbars()
695 ToolbarMap::iterator it = d.toolbars_.begin();
696 for (; it != d.toolbars_.end(); ++it)
700 // I don't like doing this here, but the standard toolbar
701 // destroys this object when it's destroyed itself (vfr)
702 d.layout_ = new LayoutBox(*this);
703 d.stack_widget_->addWidget(d.layout_);
704 d.layout_->move(0,0);
706 // extracts the toolbars from the backend
707 Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
708 Toolbars::Infos::iterator end = guiApp->toolbars().end();
709 for (; cit != end; ++cit)
710 d.toolbars_[cit->name] = new GuiToolbar(*cit, *this);
714 void GuiView::initToolbars()
716 // extracts the toolbars from the backend
717 Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
718 Toolbars::Infos::iterator end = guiApp->toolbars().end();
719 for (; cit != end; ++cit) {
720 GuiToolbar * tb = toolbar(cit->name);
723 int const visibility = guiApp->toolbars().defaultVisibility(cit->name);
724 bool newline = !(visibility & Toolbars::SAMEROW);
725 tb->setVisible(false);
726 tb->setVisibility(visibility);
728 if (visibility & Toolbars::TOP) {
730 addToolBarBreak(Qt::TopToolBarArea);
731 addToolBar(Qt::TopToolBarArea, tb);
734 if (visibility & Toolbars::BOTTOM) {
736 addToolBarBreak(Qt::BottomToolBarArea);
737 addToolBar(Qt::BottomToolBarArea, tb);
740 if (visibility & Toolbars::LEFT) {
742 addToolBarBreak(Qt::LeftToolBarArea);
743 addToolBar(Qt::LeftToolBarArea, tb);
746 if (visibility & Toolbars::RIGHT) {
748 addToolBarBreak(Qt::RightToolBarArea);
749 addToolBar(Qt::RightToolBarArea, tb);
752 if (visibility & Toolbars::ON)
753 tb->setVisible(true);
758 TocModels & GuiView::tocModels()
760 return d.toc_models_;
764 void GuiView::setFocus()
766 LYXERR(Debug::DEBUG, "GuiView::setFocus()" << this);
767 QMainWindow::setFocus();
771 void GuiView::focusInEvent(QFocusEvent * e)
773 LYXERR(Debug::DEBUG, "GuiView::focusInEvent()" << this);
774 QMainWindow::focusInEvent(e);
775 // Make sure guiApp points to the correct view.
776 guiApp->setCurrentView(this);
777 if (currentWorkArea())
778 currentWorkArea()->setFocus();
779 else if (currentMainWorkArea())
780 currentMainWorkArea()->setFocus();
782 d.bg_widget_->setFocus();
786 QMenu * GuiView::createPopupMenu()
788 return d.toolBarPopup(this);
792 void GuiView::showEvent(QShowEvent * e)
794 LYXERR(Debug::GUI, "Passed Geometry "
795 << size().height() << "x" << size().width()
796 << "+" << pos().x() << "+" << pos().y());
798 if (d.splitter_->count() == 0)
799 // No work area, switch to the background widget.
803 QMainWindow::showEvent(e);
807 bool GuiView::closeScheduled()
814 /** Destroy only all tabbed WorkAreas. Destruction of other WorkAreas
815 ** is responsibility of the container (e.g., dialog)
817 void GuiView::closeEvent(QCloseEvent * close_event)
819 LYXERR(Debug::DEBUG, "GuiView::closeEvent()");
821 if (!GuiViewPrivate::busyBuffers.isEmpty()) {
822 Alert::warning(_("Exit LyX"),
823 _("LyX could not be closed because documents are being processed by LyX."));
824 close_event->setAccepted(false);
828 // If the user pressed the x (so we didn't call closeView
829 // programmatically), we want to clear all existing entries.
831 theSession().lastOpened().clear();
836 // it can happen that this event arrives without selecting the view,
837 // e.g. when clicking the close button on a background window.
839 if (!closeWorkAreaAll()) {
841 close_event->ignore();
845 // Make sure that nothing will use this to be closed View.
846 guiApp->unregisterView(this);
848 if (isFullScreen()) {
849 // Switch off fullscreen before closing.
854 // Make sure the timer time out will not trigger a statusbar update.
855 d.statusbar_timer_.stop();
857 // Saving fullscreen requires additional tweaks in the toolbar code.
858 // It wouldn't also work under linux natively.
859 if (lyxrc.allow_geometry_session) {
864 close_event->accept();
868 void GuiView::dragEnterEvent(QDragEnterEvent * event)
870 if (event->mimeData()->hasUrls())
872 /// \todo Ask lyx-devel is this is enough:
873 /// if (event->mimeData()->hasFormat("text/plain"))
874 /// event->acceptProposedAction();
878 void GuiView::dropEvent(QDropEvent * event)
880 QList<QUrl> files = event->mimeData()->urls();
884 LYXERR(Debug::GUI, "GuiView::dropEvent: got URLs!");
885 for (int i = 0; i != files.size(); ++i) {
886 string const file = os::internal_path(fromqstr(
887 files.at(i).toLocalFile()));
891 string const ext = support::getExtension(file);
892 vector<const Format *> found_formats;
894 // Find all formats that have the correct extension.
895 vector<const Format *> const & import_formats
896 = theConverters().importableFormats();
897 vector<const Format *>::const_iterator it = import_formats.begin();
898 for (; it != import_formats.end(); ++it)
899 if ((*it)->hasExtension(ext))
900 found_formats.push_back(*it);
903 if (found_formats.size() >= 1) {
904 if (found_formats.size() > 1) {
905 //FIXME: show a dialog to choose the correct importable format
907 "Multiple importable formats found, selecting first");
909 string const arg = found_formats[0]->name() + " " + file;
910 cmd = FuncRequest(LFUN_BUFFER_IMPORT, arg);
913 //FIXME: do we have to explicitly check whether it's a lyx file?
915 "No formats found, trying to open it as a lyx file");
916 cmd = FuncRequest(LFUN_FILE_OPEN, file);
918 // add the functions to the queue
919 guiApp->addToFuncRequestQueue(cmd);
922 // now process the collected functions. We perform the events
923 // asynchronously. This prevents potential problems in case the
924 // BufferView is closed within an event.
925 guiApp->processFuncRequestQueueAsync();
929 void GuiView::message(docstring const & str)
931 if (ForkedProcess::iAmAChild())
934 // call is moved to GUI-thread by GuiProgress
935 d.progress_->appendMessage(toqstr(str));
939 void GuiView::clearMessageText()
941 message(docstring());
945 void GuiView::updateStatusBarMessage(QString const & str)
947 statusBar()->showMessage(str);
948 d.statusbar_timer_.stop();
949 d.statusbar_timer_.start(3000);
953 void GuiView::smallSizedIcons()
955 setIconSize(QSize(d.smallIconSize, d.smallIconSize));
959 void GuiView::normalSizedIcons()
961 setIconSize(QSize(d.normalIconSize, d.normalIconSize));
965 void GuiView::bigSizedIcons()
967 setIconSize(QSize(d.bigIconSize, d.bigIconSize));
971 void GuiView::clearMessage()
973 // FIXME: This code was introduced in r19643 to fix bug #4123. However,
974 // the hasFocus function mostly returns false, even if the focus is on
975 // a workarea in this view.
979 d.statusbar_timer_.stop();
983 void GuiView::updateWindowTitle(GuiWorkArea * wa)
985 if (wa != d.current_work_area_
986 || wa->bufferView().buffer().isInternal())
988 setWindowTitle(qt_("LyX: ") + wa->windowTitle());
989 setWindowIconText(wa->windowIconText());
993 void GuiView::on_currentWorkAreaChanged(GuiWorkArea * wa)
995 if (d.current_work_area_)
996 QObject::disconnect(d.current_work_area_, SIGNAL(busy(bool)),
997 this, SLOT(setBusy(bool)));
999 disconnectBufferView();
1000 connectBufferView(wa->bufferView());
1001 connectBuffer(wa->bufferView().buffer());
1002 d.current_work_area_ = wa;
1003 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
1004 this, SLOT(updateWindowTitle(GuiWorkArea *)));
1005 QObject::connect(wa, SIGNAL(busy(bool)), this, SLOT(setBusy(bool)));
1006 updateWindowTitle(wa);
1010 // The document settings needs to be reinitialised.
1011 updateDialog("document", "");
1013 // Buffer-dependent dialogs must be updated. This is done here because
1014 // some dialogs require buffer()->text.
1019 void GuiView::on_lastWorkAreaRemoved()
1022 // We already are in a close event. Nothing more to do.
1025 if (d.splitter_->count() > 1)
1026 // We have a splitter so don't close anything.
1029 // Reset and updates the dialogs.
1030 d.toc_models_.reset(0);
1031 updateDialog("document", "");
1034 resetWindowTitleAndIconText();
1037 if (lyxrc.open_buffers_in_tabs)
1038 // Nothing more to do, the window should stay open.
1041 if (guiApp->viewIds().size() > 1) {
1047 // On Mac we also close the last window because the application stay
1048 // resident in memory. On other platforms we don't close the last
1049 // window because this would quit the application.
1055 void GuiView::updateStatusBar()
1057 // let the user see the explicit message
1058 if (d.statusbar_timer_.isActive())
1065 void GuiView::showMessage()
1067 QString msg = toqstr(theGuiApp()->viewStatusMessage());
1068 if (msg.isEmpty()) {
1069 BufferView const * bv = currentBufferView();
1071 msg = toqstr(bv->cursor().currentState());
1073 msg = qt_("Welcome to LyX!");
1075 statusBar()->showMessage(msg);
1079 bool GuiView::event(QEvent * e)
1083 // Useful debug code:
1084 //case QEvent::ActivationChange:
1085 //case QEvent::WindowDeactivate:
1086 //case QEvent::Paint:
1087 //case QEvent::Enter:
1088 //case QEvent::Leave:
1089 //case QEvent::HoverEnter:
1090 //case QEvent::HoverLeave:
1091 //case QEvent::HoverMove:
1092 //case QEvent::StatusTip:
1093 //case QEvent::DragEnter:
1094 //case QEvent::DragLeave:
1095 //case QEvent::Drop:
1098 case QEvent::WindowActivate: {
1099 GuiView * old_view = guiApp->currentView();
1100 if (this == old_view) {
1102 return QMainWindow::event(e);
1104 if (old_view && old_view->currentBufferView()) {
1105 // save current selection to the selection buffer to allow
1106 // middle-button paste in this window.
1107 cap::saveSelection(old_view->currentBufferView()->cursor());
1109 guiApp->setCurrentView(this);
1110 if (d.current_work_area_) {
1111 BufferView & bv = d.current_work_area_->bufferView();
1112 connectBufferView(bv);
1113 connectBuffer(bv.buffer());
1114 // The document structure, name and dialogs might have
1115 // changed in another view.
1117 // The document settings needs to be reinitialised.
1118 updateDialog("document", "");
1121 resetWindowTitleAndIconText();
1124 return QMainWindow::event(e);
1127 case QEvent::ShortcutOverride: {
1129 if (isFullScreen() && menuBar()->isHidden()) {
1130 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
1131 // FIXME: we should also try to detect special LyX shortcut such as
1132 // Alt-P and Alt-M. Right now there is a hack in
1133 // GuiWorkArea::processKeySym() that hides again the menubar for
1135 if (ke->modifiers() & Qt::AltModifier && ke->key() != Qt::Key_Alt) {
1137 return QMainWindow::event(e);
1140 return QMainWindow::event(e);
1144 return QMainWindow::event(e);
1148 void GuiView::resetWindowTitleAndIconText()
1150 setWindowTitle(qt_("LyX"));
1151 setWindowIconText(qt_("LyX"));
1154 bool GuiView::focusNextPrevChild(bool /*next*/)
1161 bool GuiView::busy() const
1167 void GuiView::setBusy(bool busy)
1169 bool const busy_before = busy_ > 0;
1170 busy ? ++busy_ : --busy_;
1171 if ((busy_ > 0) == busy_before)
1172 // busy state didn't change
1176 QApplication::setOverrideCursor(Qt::WaitCursor);
1179 QApplication::restoreOverrideCursor();
1184 GuiWorkArea * GuiView::workArea(int index)
1186 if (TabWorkArea * twa = d.currentTabWorkArea())
1187 if (index < twa->count())
1188 return dynamic_cast<GuiWorkArea *>(twa->widget(index));
1193 GuiWorkArea * GuiView::workArea(Buffer & buffer)
1195 if (currentWorkArea()
1196 && ¤tWorkArea()->bufferView().buffer() == &buffer)
1197 return (GuiWorkArea *) currentWorkArea();
1198 if (TabWorkArea * twa = d.currentTabWorkArea())
1199 return twa->workArea(buffer);
1204 GuiWorkArea * GuiView::addWorkArea(Buffer & buffer)
1206 // Automatically create a TabWorkArea if there are none yet.
1207 TabWorkArea * tab_widget = d.splitter_->count()
1208 ? d.currentTabWorkArea() : addTabWorkArea();
1209 return tab_widget->addWorkArea(buffer, *this);
1213 TabWorkArea * GuiView::addTabWorkArea()
1215 TabWorkArea * twa = new TabWorkArea;
1216 QObject::connect(twa, SIGNAL(currentWorkAreaChanged(GuiWorkArea *)),
1217 this, SLOT(on_currentWorkAreaChanged(GuiWorkArea *)));
1218 QObject::connect(twa, SIGNAL(lastWorkAreaRemoved()),
1219 this, SLOT(on_lastWorkAreaRemoved()));
1221 d.splitter_->addWidget(twa);
1222 d.stack_widget_->setCurrentWidget(d.splitter_);
1227 GuiWorkArea const * GuiView::currentWorkArea() const
1229 return d.current_work_area_;
1233 GuiWorkArea * GuiView::currentWorkArea()
1235 return d.current_work_area_;
1239 GuiWorkArea const * GuiView::currentMainWorkArea() const
1241 if (!d.currentTabWorkArea())
1243 return d.currentTabWorkArea()->currentWorkArea();
1247 GuiWorkArea * GuiView::currentMainWorkArea()
1249 if (!d.currentTabWorkArea())
1251 return d.currentTabWorkArea()->currentWorkArea();
1255 void GuiView::setCurrentWorkArea(GuiWorkArea * wa)
1257 LYXERR(Debug::DEBUG, "Setting current wa: " << wa << endl);
1259 d.current_work_area_ = 0;
1264 // FIXME: I've no clue why this is here and why it accesses
1265 // theGuiApp()->currentView, which might be 0 (bug 6464).
1266 // See also 27525 (vfr).
1267 if (theGuiApp()->currentView() == this
1268 && theGuiApp()->currentView()->currentWorkArea() == wa)
1271 if (currentBufferView())
1272 cap::saveSelection(currentBufferView()->cursor());
1274 theGuiApp()->setCurrentView(this);
1275 d.current_work_area_ = wa;
1277 // We need to reset this now, because it will need to be
1278 // right if the tabWorkArea gets reset in the for loop. We
1279 // will change it back if we aren't in that case.
1280 GuiWorkArea * const old_cmwa = d.current_main_work_area_;
1281 d.current_main_work_area_ = wa;
1283 for (int i = 0; i != d.splitter_->count(); ++i) {
1284 if (d.tabWorkArea(i)->setCurrentWorkArea(wa)) {
1285 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea()
1286 << ", Current main wa: " << currentMainWorkArea());
1291 d.current_main_work_area_ = old_cmwa;
1293 LYXERR(Debug::DEBUG, "This is not a tabbed wa");
1294 on_currentWorkAreaChanged(wa);
1295 BufferView & bv = wa->bufferView();
1296 bv.cursor().fixIfBroken();
1298 wa->setUpdatesEnabled(true);
1299 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() << ", Current main wa: " << currentMainWorkArea());
1303 void GuiView::removeWorkArea(GuiWorkArea * wa)
1305 LASSERT(wa, return);
1306 if (wa == d.current_work_area_) {
1308 disconnectBufferView();
1309 d.current_work_area_ = 0;
1310 d.current_main_work_area_ = 0;
1313 bool found_twa = false;
1314 for (int i = 0; i != d.splitter_->count(); ++i) {
1315 TabWorkArea * twa = d.tabWorkArea(i);
1316 if (twa->removeWorkArea(wa)) {
1317 // Found in this tab group, and deleted the GuiWorkArea.
1319 if (twa->count() != 0) {
1320 if (d.current_work_area_ == 0)
1321 // This means that we are closing the current GuiWorkArea, so
1322 // switch to the next GuiWorkArea in the found TabWorkArea.
1323 setCurrentWorkArea(twa->currentWorkArea());
1325 // No more WorkAreas in this tab group, so delete it.
1332 // It is not a tabbed work area (i.e., the search work area), so it
1333 // should be deleted by other means.
1334 LASSERT(found_twa, /* */);
1336 if (d.current_work_area_ == 0) {
1337 if (d.splitter_->count() != 0) {
1338 TabWorkArea * twa = d.currentTabWorkArea();
1339 setCurrentWorkArea(twa->currentWorkArea());
1341 // No more work areas, switch to the background widget.
1342 setCurrentWorkArea(0);
1348 LayoutBox * GuiView::getLayoutDialog() const
1354 void GuiView::updateLayoutList()
1357 d.layout_->updateContents(false);
1361 void GuiView::updateToolbars()
1363 ToolbarMap::iterator end = d.toolbars_.end();
1364 if (d.current_work_area_) {
1366 d.current_work_area_->bufferView().cursor().inMathed()
1367 && !d.current_work_area_->bufferView().cursor().inRegexped();
1369 lyx::getStatus(FuncRequest(LFUN_LAYOUT_TABULAR)).enabled();
1371 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).enabled() &&
1372 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).onOff(true);
1373 bool const mathmacrotemplate =
1374 lyx::getStatus(FuncRequest(LFUN_IN_MATHMACROTEMPLATE)).enabled();
1376 lyx::getStatus(FuncRequest(LFUN_IN_IPA)).enabled();
1378 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1379 it->second->update(math, table, review, mathmacrotemplate, ipa);
1381 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1382 it->second->update(false, false, false, false, false);
1386 void GuiView::setBuffer(Buffer * newBuffer)
1388 LYXERR(Debug::DEBUG, "Setting buffer: " << newBuffer << endl);
1389 LASSERT(newBuffer, return);
1391 GuiWorkArea * wa = workArea(*newBuffer);
1394 newBuffer->masterBuffer()->updateBuffer();
1396 wa = addWorkArea(*newBuffer);
1397 // scroll to the position when the BufferView was last closed
1398 if (lyxrc.use_lastfilepos) {
1399 LastFilePosSection::FilePos filepos =
1400 theSession().lastFilePos().load(newBuffer->fileName());
1401 wa->bufferView().moveToPosition(filepos.pit, filepos.pos, 0, 0);
1404 //Disconnect the old buffer...there's no new one.
1407 connectBuffer(*newBuffer);
1408 connectBufferView(wa->bufferView());
1409 setCurrentWorkArea(wa);
1413 void GuiView::connectBuffer(Buffer & buf)
1415 buf.setGuiDelegate(this);
1419 void GuiView::disconnectBuffer()
1421 if (d.current_work_area_)
1422 d.current_work_area_->bufferView().buffer().setGuiDelegate(0);
1426 void GuiView::connectBufferView(BufferView & bv)
1428 bv.setGuiDelegate(this);
1432 void GuiView::disconnectBufferView()
1434 if (d.current_work_area_)
1435 d.current_work_area_->bufferView().setGuiDelegate(0);
1439 void GuiView::errors(string const & error_type, bool from_master)
1441 BufferView const * const bv = currentBufferView();
1445 #if EXPORT_in_THREAD
1446 // We are called with from_master == false by default, so we
1447 // have to figure out whether that is the case or not.
1448 ErrorList & el = bv->buffer().errorList(error_type);
1450 el = bv->buffer().masterBuffer()->errorList(error_type);
1454 ErrorList const & el = from_master ?
1455 bv->buffer().masterBuffer()->errorList(error_type) :
1456 bv->buffer().errorList(error_type);
1462 string data = error_type;
1464 data = "from_master|" + error_type;
1465 showDialog("errorlist", data);
1469 void GuiView::updateTocItem(string const & type, DocIterator const & dit)
1471 d.toc_models_.updateItem(toqstr(type), dit);
1475 void GuiView::structureChanged()
1477 d.toc_models_.reset(documentBufferView());
1478 // Navigator needs more than a simple update in this case. It needs to be
1480 updateDialog("toc", "");
1484 void GuiView::updateDialog(string const & name, string const & data)
1486 if (!isDialogVisible(name))
1489 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
1490 if (it == d.dialogs_.end())
1493 Dialog * const dialog = it->second.get();
1494 if (dialog->isVisibleView())
1495 dialog->initialiseParams(data);
1499 BufferView * GuiView::documentBufferView()
1501 return currentMainWorkArea()
1502 ? ¤tMainWorkArea()->bufferView()
1507 BufferView const * GuiView::documentBufferView() const
1509 return currentMainWorkArea()
1510 ? ¤tMainWorkArea()->bufferView()
1515 BufferView * GuiView::currentBufferView()
1517 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1521 BufferView const * GuiView::currentBufferView() const
1523 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1527 docstring GuiView::GuiViewPrivate::autosaveAndDestroy(
1528 Buffer const * orig, Buffer * clone)
1530 bool const success = clone->autoSave();
1532 busyBuffers.remove(orig);
1534 ? _("Automatic save done.")
1535 : _("Automatic save failed!");
1539 void GuiView::autoSave()
1541 LYXERR(Debug::INFO, "Running autoSave()");
1543 Buffer * buffer = documentBufferView()
1544 ? &documentBufferView()->buffer() : 0;
1546 resetAutosaveTimers();
1550 GuiViewPrivate::busyBuffers.insert(buffer);
1551 QFuture<docstring> f = QtConcurrent::run(GuiViewPrivate::autosaveAndDestroy,
1552 buffer, buffer->cloneBufferOnly());
1553 d.autosave_watcher_.setFuture(f);
1554 resetAutosaveTimers();
1558 void GuiView::resetAutosaveTimers()
1561 d.autosave_timeout_.restart();
1565 bool GuiView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1568 Buffer * buf = currentBufferView()
1569 ? ¤tBufferView()->buffer() : 0;
1570 Buffer * doc_buffer = documentBufferView()
1571 ? &(documentBufferView()->buffer()) : 0;
1573 // Check whether we need a buffer
1574 if (!lyxaction.funcHasFlag(cmd.action(), LyXAction::NoBuffer) && !buf) {
1575 // no, exit directly
1576 flag.message(from_utf8(N_("Command not allowed with"
1577 "out any document open")));
1578 flag.setEnabled(false);
1582 if (cmd.origin() == FuncRequest::TOC) {
1583 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
1584 if (!toc || !toc->getStatus(documentBufferView()->cursor(), cmd, flag))
1585 flag.setEnabled(false);
1589 switch(cmd.action()) {
1590 case LFUN_BUFFER_IMPORT:
1593 case LFUN_MASTER_BUFFER_UPDATE:
1594 case LFUN_MASTER_BUFFER_VIEW:
1595 enable = doc_buffer && doc_buffer->parent() != 0
1596 && !d.processing_thread_watcher_.isRunning();
1599 case LFUN_BUFFER_UPDATE:
1600 case LFUN_BUFFER_VIEW: {
1601 if (!doc_buffer || d.processing_thread_watcher_.isRunning()) {
1605 string format = to_utf8(cmd.argument());
1606 if (cmd.argument().empty())
1607 format = doc_buffer->params().getDefaultOutputFormat();
1608 enable = doc_buffer->params().isExportableFormat(format);
1612 case LFUN_BUFFER_RELOAD:
1613 enable = doc_buffer && !doc_buffer->isUnnamed()
1614 && doc_buffer->fileName().exists()
1615 && (!doc_buffer->isClean()
1616 || doc_buffer->isExternallyModified(Buffer::timestamp_method));
1619 case LFUN_BUFFER_CHILD_OPEN:
1620 enable = doc_buffer;
1623 case LFUN_BUFFER_WRITE:
1624 enable = doc_buffer && (doc_buffer->isUnnamed() || !doc_buffer->isClean());
1627 //FIXME: This LFUN should be moved to GuiApplication.
1628 case LFUN_BUFFER_WRITE_ALL: {
1629 // We enable the command only if there are some modified buffers
1630 Buffer * first = theBufferList().first();
1635 // We cannot use a for loop as the buffer list is a cycle.
1637 if (!b->isClean()) {
1641 b = theBufferList().next(b);
1642 } while (b != first);
1646 case LFUN_BUFFER_WRITE_AS:
1647 case LFUN_BUFFER_EXPORT_AS:
1648 enable = doc_buffer;
1651 case LFUN_BUFFER_CLOSE:
1652 case LFUN_VIEW_CLOSE:
1653 enable = doc_buffer;
1656 case LFUN_BUFFER_CLOSE_ALL:
1657 enable = theBufferList().last() != theBufferList().first();
1660 case LFUN_VIEW_SPLIT:
1661 if (cmd.getArg(0) == "vertical")
1662 enable = doc_buffer && (d.splitter_->count() == 1 ||
1663 d.splitter_->orientation() == Qt::Vertical);
1665 enable = doc_buffer && (d.splitter_->count() == 1 ||
1666 d.splitter_->orientation() == Qt::Horizontal);
1669 case LFUN_TAB_GROUP_CLOSE:
1670 enable = d.tabWorkAreaCount() > 1;
1673 case LFUN_TOOLBAR_TOGGLE: {
1674 string const name = cmd.getArg(0);
1675 if (GuiToolbar * t = toolbar(name))
1676 flag.setOnOff(t->isVisible());
1679 docstring const msg =
1680 bformat(_("Unknown toolbar \"%1$s\""), from_utf8(name));
1686 case LFUN_DROP_LAYOUTS_CHOICE:
1690 case LFUN_UI_TOGGLE:
1691 flag.setOnOff(isFullScreen());
1694 case LFUN_DIALOG_DISCONNECT_INSET:
1697 case LFUN_DIALOG_HIDE:
1698 // FIXME: should we check if the dialog is shown?
1701 case LFUN_DIALOG_TOGGLE:
1702 flag.setOnOff(isDialogVisible(cmd.getArg(0)));
1703 // fall through to set "enable"
1704 case LFUN_DIALOG_SHOW: {
1705 string const name = cmd.getArg(0);
1707 enable = name == "aboutlyx"
1708 || name == "file" //FIXME: should be removed.
1710 || name == "texinfo"
1711 || name == "progress"
1712 || name == "compare";
1713 else if (name == "print")
1714 enable = doc_buffer->params().isExportable("dvi")
1715 && lyxrc.print_command != "none";
1716 else if (name == "character" || name == "symbols") {
1717 if (!buf || buf->isReadonly())
1720 Cursor const & cur = currentBufferView()->cursor();
1721 enable = !(cur.inTexted() && cur.paragraph().isPassThru());
1724 else if (name == "latexlog")
1725 enable = FileName(doc_buffer->logName()).isReadableFile();
1726 else if (name == "spellchecker")
1727 enable = theSpellChecker()
1728 && !doc_buffer->isReadonly()
1729 && !doc_buffer->text().empty();
1730 else if (name == "vclog")
1731 enable = doc_buffer->lyxvc().inUse();
1735 case LFUN_DIALOG_UPDATE: {
1736 string const name = cmd.getArg(0);
1738 enable = name == "prefs";
1742 case LFUN_COMMAND_EXECUTE:
1744 case LFUN_MENU_OPEN:
1745 // Nothing to check.
1748 case LFUN_COMPLETION_INLINE:
1749 if (!d.current_work_area_
1750 || !d.current_work_area_->completer().inlinePossible(
1751 currentBufferView()->cursor()))
1755 case LFUN_COMPLETION_POPUP:
1756 if (!d.current_work_area_
1757 || !d.current_work_area_->completer().popupPossible(
1758 currentBufferView()->cursor()))
1762 case LFUN_COMPLETION_COMPLETE:
1763 if (!d.current_work_area_
1764 || !d.current_work_area_->completer().inlinePossible(
1765 currentBufferView()->cursor()))
1769 case LFUN_COMPLETION_ACCEPT:
1770 if (!d.current_work_area_
1771 || (!d.current_work_area_->completer().popupVisible()
1772 && !d.current_work_area_->completer().inlineVisible()
1773 && !d.current_work_area_->completer().completionAvailable()))
1777 case LFUN_COMPLETION_CANCEL:
1778 if (!d.current_work_area_
1779 || (!d.current_work_area_->completer().popupVisible()
1780 && !d.current_work_area_->completer().inlineVisible()))
1784 case LFUN_BUFFER_ZOOM_OUT:
1785 enable = doc_buffer && lyxrc.zoom > 10;
1788 case LFUN_BUFFER_ZOOM_IN:
1789 enable = doc_buffer;
1792 case LFUN_BUFFER_NEXT:
1793 case LFUN_BUFFER_PREVIOUS:
1794 // FIXME: should we check is there is an previous or next buffer?
1796 case LFUN_BUFFER_SWITCH:
1797 // toggle on the current buffer, but do not toggle off
1798 // the other ones (is that a good idea?)
1800 && to_utf8(cmd.argument()) == doc_buffer->absFileName())
1801 flag.setOnOff(true);
1804 case LFUN_VC_REGISTER:
1805 enable = doc_buffer && !doc_buffer->lyxvc().inUse();
1807 case LFUN_VC_CHECK_IN:
1808 enable = doc_buffer && doc_buffer->lyxvc().checkInEnabled();
1810 case LFUN_VC_CHECK_OUT:
1811 enable = doc_buffer && doc_buffer->lyxvc().checkOutEnabled();
1813 case LFUN_VC_LOCKING_TOGGLE:
1814 enable = doc_buffer && !doc_buffer->isReadonly()
1815 && doc_buffer->lyxvc().lockingToggleEnabled();
1816 flag.setOnOff(enable && doc_buffer->lyxvc().locking());
1818 case LFUN_VC_REVERT:
1819 enable = doc_buffer && doc_buffer->lyxvc().inUse() && !doc_buffer->isReadonly();
1821 case LFUN_VC_UNDO_LAST:
1822 enable = doc_buffer && doc_buffer->lyxvc().undoLastEnabled();
1824 case LFUN_VC_REPO_UPDATE:
1825 enable = doc_buffer && doc_buffer->lyxvc().repoUpdateEnabled();
1827 case LFUN_VC_COMMAND: {
1828 if (cmd.argument().empty())
1830 if (!doc_buffer && contains(cmd.getArg(0), 'D'))
1834 case LFUN_VC_COMPARE:
1835 enable = doc_buffer && doc_buffer->lyxvc().prepareFileRevisionEnabled();
1838 case LFUN_SERVER_GOTO_FILE_ROW:
1840 case LFUN_FORWARD_SEARCH:
1841 enable = !(lyxrc.forward_search_dvi.empty() && lyxrc.forward_search_pdf.empty());
1844 case LFUN_FILE_INSERT_PLAINTEXT:
1845 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
1846 enable = documentBufferView() && documentBufferView()->cursor().inTexted();
1854 flag.setEnabled(false);
1860 static FileName selectTemplateFile()
1862 FileDialog dlg(qt_("Select template file"));
1863 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1864 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
1866 FileDialog::Result result = dlg.open(toqstr(lyxrc.template_path),
1867 QStringList(qt_("LyX Documents (*.lyx)")));
1869 if (result.first == FileDialog::Later)
1871 if (result.second.isEmpty())
1873 return FileName(fromqstr(result.second));
1877 Buffer * GuiView::loadDocument(FileName const & filename, bool tolastfiles)
1881 Buffer * newBuffer = 0;
1883 newBuffer = checkAndLoadLyXFile(filename);
1884 } catch (ExceptionMessage const & e) {
1891 message(_("Document not loaded."));
1895 setBuffer(newBuffer);
1896 newBuffer->errors("Parse");
1899 theSession().lastFiles().add(filename);
1905 void GuiView::openDocument(string const & fname)
1907 string initpath = lyxrc.document_path;
1909 if (documentBufferView()) {
1910 string const trypath = documentBufferView()->buffer().filePath();
1911 // If directory is writeable, use this as default.
1912 if (FileName(trypath).isDirWritable())
1918 if (fname.empty()) {
1919 FileDialog dlg(qt_("Select document to open"), LFUN_FILE_OPEN);
1920 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1921 dlg.setButton2(qt_("Examples|#E#e"),
1922 toqstr(addPath(package().system_support().absFileName(), "examples")));
1924 QStringList filter(qt_("LyX Documents (*.lyx)"));
1925 filter << qt_("LyX-1.3.x Documents (*.lyx13)")
1926 << qt_("LyX-1.4.x Documents (*.lyx14)")
1927 << qt_("LyX-1.5.x Documents (*.lyx15)")
1928 << qt_("LyX-1.6.x Documents (*.lyx16)");
1929 FileDialog::Result result =
1930 dlg.open(toqstr(initpath), filter);
1932 if (result.first == FileDialog::Later)
1935 filename = fromqstr(result.second);
1937 // check selected filename
1938 if (filename.empty()) {
1939 message(_("Canceled."));
1945 // get absolute path of file and add ".lyx" to the filename if
1947 FileName const fullname =
1948 fileSearch(string(), filename, "lyx", support::may_not_exist);
1949 if (!fullname.empty())
1950 filename = fullname.absFileName();
1952 if (!fullname.onlyPath().isDirectory()) {
1953 Alert::warning(_("Invalid filename"),
1954 bformat(_("The directory in the given path\n%1$s\ndoes not exist."),
1955 from_utf8(fullname.absFileName())));
1959 // if the file doesn't exist and isn't already open (bug 6645),
1960 // let the user create one
1961 if (!fullname.exists() && !theBufferList().exists(fullname) &&
1962 !LyXVC::file_not_found_hook(fullname)) {
1963 // the user specifically chose this name. Believe him.
1964 Buffer * const b = newFile(filename, string(), true);
1970 docstring const disp_fn = makeDisplayPath(filename);
1971 message(bformat(_("Opening document %1$s..."), disp_fn));
1974 Buffer * buf = loadDocument(fullname);
1976 str2 = bformat(_("Document %1$s opened."), disp_fn);
1977 if (buf->lyxvc().inUse())
1978 str2 += " " + from_utf8(buf->lyxvc().versionString()) +
1979 " " + _("Version control detected.");
1981 str2 = bformat(_("Could not open document %1$s"), disp_fn);
1986 // FIXME: clean that
1987 static bool import(GuiView * lv, FileName const & filename,
1988 string const & format, ErrorList & errorList)
1990 FileName const lyxfile(support::changeExtension(filename.absFileName(), ".lyx"));
1992 string loader_format;
1993 vector<string> loaders = theConverters().loaders();
1994 if (find(loaders.begin(), loaders.end(), format) == loaders.end()) {
1995 vector<string>::const_iterator it = loaders.begin();
1996 vector<string>::const_iterator en = loaders.end();
1997 for (; it != en; ++it) {
1998 if (!theConverters().isReachable(format, *it))
2001 string const tofile =
2002 support::changeExtension(filename.absFileName(),
2003 formats.extension(*it));
2004 if (!theConverters().convert(0, filename, FileName(tofile),
2005 filename, format, *it, errorList))
2007 loader_format = *it;
2010 if (loader_format.empty()) {
2011 frontend::Alert::error(_("Couldn't import file"),
2012 bformat(_("No information for importing the format %1$s."),
2013 formats.prettyName(format)));
2017 loader_format = format;
2019 if (loader_format == "lyx") {
2020 Buffer * buf = lv->loadDocument(lyxfile);
2024 Buffer * const b = newFile(lyxfile.absFileName(), string(), true);
2028 bool as_paragraphs = loader_format == "textparagraph";
2029 string filename2 = (loader_format == format) ? filename.absFileName()
2030 : support::changeExtension(filename.absFileName(),
2031 formats.extension(loader_format));
2032 lv->currentBufferView()->insertPlaintextFile(FileName(filename2),
2034 guiApp->setCurrentView(lv);
2035 lyx::dispatch(FuncRequest(LFUN_MARK_OFF));
2042 void GuiView::importDocument(string const & argument)
2045 string filename = split(argument, format, ' ');
2047 LYXERR(Debug::INFO, format << " file: " << filename);
2049 // need user interaction
2050 if (filename.empty()) {
2051 string initpath = lyxrc.document_path;
2052 if (documentBufferView()) {
2053 string const trypath = documentBufferView()->buffer().filePath();
2054 // If directory is writeable, use this as default.
2055 if (FileName(trypath).isDirWritable())
2059 docstring const text = bformat(_("Select %1$s file to import"),
2060 formats.prettyName(format));
2062 FileDialog dlg(toqstr(text), LFUN_BUFFER_IMPORT);
2063 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2064 dlg.setButton2(qt_("Examples|#E#e"),
2065 toqstr(addPath(package().system_support().absFileName(), "examples")));
2067 docstring filter = formats.prettyName(format);
2070 filter += from_utf8(formats.extensions(format));
2073 FileDialog::Result result =
2074 dlg.open(toqstr(initpath), fileFilters(toqstr(filter)));
2076 if (result.first == FileDialog::Later)
2079 filename = fromqstr(result.second);
2081 // check selected filename
2082 if (filename.empty())
2083 message(_("Canceled."));
2086 if (filename.empty())
2089 // get absolute path of file
2090 FileName const fullname(support::makeAbsPath(filename));
2092 FileName const lyxfile(support::changeExtension(fullname.absFileName(), ".lyx"));
2094 // Check if the document already is open
2095 Buffer * buf = theBufferList().getBuffer(lyxfile);
2098 if (!closeBuffer()) {
2099 message(_("Canceled."));
2104 docstring const displaypath = makeDisplayPath(lyxfile.absFileName(), 30);
2106 // if the file exists already, and we didn't do
2107 // -i lyx thefile.lyx, warn
2108 if (lyxfile.exists() && fullname != lyxfile) {
2110 docstring text = bformat(_("The document %1$s already exists.\n\n"
2111 "Do you want to overwrite that document?"), displaypath);
2112 int const ret = Alert::prompt(_("Overwrite document?"),
2113 text, 0, 1, _("&Overwrite"), _("&Cancel"));
2116 message(_("Canceled."));
2121 message(bformat(_("Importing %1$s..."), displaypath));
2122 ErrorList errorList;
2123 if (import(this, fullname, format, errorList))
2124 message(_("imported."));
2126 message(_("file not imported!"));
2128 // FIXME (Abdel 12/08/06): Is there a need to display the error list here?
2132 void GuiView::newDocument(string const & filename, bool from_template)
2134 FileName initpath(lyxrc.document_path);
2135 if (documentBufferView()) {
2136 FileName const trypath(documentBufferView()->buffer().filePath());
2137 // If directory is writeable, use this as default.
2138 if (trypath.isDirWritable())
2142 string templatefile;
2143 if (from_template) {
2144 templatefile = selectTemplateFile().absFileName();
2145 if (templatefile.empty())
2150 if (filename.empty())
2151 b = newUnnamedFile(initpath, to_utf8(_("newfile")), templatefile);
2153 b = newFile(filename, templatefile, true);
2158 // If no new document could be created, it is unsure
2159 // whether there is a valid BufferView.
2160 if (currentBufferView())
2161 // Ensure the cursor is correctly positioned on screen.
2162 currentBufferView()->showCursor();
2166 void GuiView::insertLyXFile(docstring const & fname)
2168 BufferView * bv = documentBufferView();
2173 FileName filename(to_utf8(fname));
2174 if (filename.empty()) {
2175 // Launch a file browser
2177 string initpath = lyxrc.document_path;
2178 string const trypath = bv->buffer().filePath();
2179 // If directory is writeable, use this as default.
2180 if (FileName(trypath).isDirWritable())
2184 FileDialog dlg(qt_("Select LyX document to insert"), LFUN_FILE_INSERT);
2185 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2186 dlg.setButton2(qt_("Examples|#E#e"),
2187 toqstr(addPath(package().system_support().absFileName(),
2190 FileDialog::Result result = dlg.open(toqstr(initpath),
2191 QStringList(qt_("LyX Documents (*.lyx)")));
2193 if (result.first == FileDialog::Later)
2197 filename.set(fromqstr(result.second));
2199 // check selected filename
2200 if (filename.empty()) {
2201 // emit message signal.
2202 message(_("Canceled."));
2207 bv->insertLyXFile(filename);
2208 bv->buffer().errors("Parse");
2212 bool GuiView::renameBuffer(Buffer & b, docstring const & newname)
2214 FileName fname = b.fileName();
2215 FileName const oldname = fname;
2217 if (!newname.empty()) {
2219 fname = support::makeAbsPath(to_utf8(newname), oldname.onlyPath().absFileName());
2221 // Switch to this Buffer.
2224 // No argument? Ask user through dialog.
2226 FileDialog dlg(qt_("Choose a filename to save document as"),
2227 LFUN_BUFFER_WRITE_AS);
2228 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2229 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
2231 if (!isLyXFileName(fname.absFileName()))
2232 fname.changeExtension(".lyx");
2234 FileDialog::Result result =
2235 dlg.save(toqstr(fname.onlyPath().absFileName()),
2236 QStringList(qt_("LyX Documents (*.lyx)")),
2237 toqstr(fname.onlyFileName()));
2239 if (result.first == FileDialog::Later)
2242 fname.set(fromqstr(result.second));
2247 if (!isLyXFileName(fname.absFileName()))
2248 fname.changeExtension(".lyx");
2251 // fname is now the new Buffer location.
2253 // if there is already a Buffer open with this name, we do not want
2254 // to have another one. (the second test makes sure we're not just
2255 // trying to overwrite ourselves, which is fine.)
2256 if (theBufferList().exists(fname) && fname != oldname
2257 && theBufferList().getBuffer(fname) != &b) {
2258 docstring const text =
2259 bformat(_("The file\n%1$s\nis already open in your current session.\n"
2260 "Please close it before attempting to overwrite it.\n"
2261 "Do you want to choose a new filename?"),
2262 from_utf8(fname.absFileName()));
2263 int const ret = Alert::prompt(_("Chosen File Already Open"),
2264 text, 0, 1, _("&Rename"), _("&Cancel"));
2266 case 0: return renameBuffer(b, docstring());
2267 case 1: return false;
2272 if (FileName(fname).exists()) {
2273 docstring const file = makeDisplayPath(fname.absFileName(), 30);
2274 docstring const text = bformat(_("The document %1$s already "
2275 "exists.\n\nDo you want to "
2276 "overwrite that document?"),
2278 int const ret = Alert::prompt(_("Overwrite document?"),
2279 text, 0, 2, _("&Overwrite"), _("&Rename"), _("&Cancel"));
2282 case 1: return renameBuffer(b, docstring());
2283 case 2: return false;
2287 bool const saved = saveBuffer(b, fname);
2294 struct PrettyNameComparator
2296 bool operator()(Format const *first, Format const *second) const {
2297 return compare_ascii_no_case(first->prettyname(), second->prettyname()) <= 0;
2302 bool GuiView::exportBufferAs(Buffer & b)
2304 FileName fname = b.fileName();
2306 FileDialog dlg(qt_("Choose a filename to export the document as"));
2307 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2310 types << "Any supported format (*.*)";
2311 Formats::const_iterator it = formats.begin();
2312 vector<Format const *> export_formats;
2313 for (; it != formats.end(); ++it)
2314 if (it->documentFormat() && it->inExportMenu())
2315 export_formats.push_back(&(*it));
2316 PrettyNameComparator cmp;
2317 sort(export_formats.begin(), export_formats.end(), cmp);
2318 vector<Format const *>::const_iterator fit = export_formats.begin();
2319 for (; fit != export_formats.end(); ++fit)
2320 types << toqstr((*fit)->prettyname() + " (*." + (*fit)->extension() + ")");
2322 FileDialog::Result result =
2323 dlg.save(toqstr(fname.onlyPath().absFileName()),
2325 toqstr(fname.onlyFileName()),
2327 if (result.first != FileDialog::Chosen)
2330 string s = fromqstr(filter);
2331 size_t pos = s.find(" (*.");
2332 LASSERT(pos != string::npos, /**/);
2333 string fmt_prettyname = s.substr(0, pos);
2335 fname.set(fromqstr(result.second));
2336 if (fmt_prettyname == "Any supported format")
2337 fmt_name = formats.getFormatFromExtension(fname.extension());
2339 fmt_name = formats.getFormatFromPrettyName(fmt_prettyname);
2340 LYXERR(Debug::FILES, "fmt_prettyname=" << fmt_prettyname
2341 << ", fmt_name=" << fmt_name << ", fname=" << fname.absFileName());
2343 if (fmt_name.empty() || fname.empty())
2346 // fname is now the new Buffer location.
2347 if (FileName(fname).exists()) {
2348 docstring const file = makeDisplayPath(fname.absFileName(), 30);
2349 docstring text = bformat(_("The document %1$s already "
2350 "exists.\n\nDo you want to "
2351 "overwrite that document?"),
2353 int const ret = Alert::prompt(_("Overwrite document?"),
2354 text, 0, 2, _("&Overwrite"), _("&Rename"), _("&Cancel"));
2357 case 1: return exportBufferAs(b);
2358 case 2: return false;
2362 FuncRequest cmd(LFUN_BUFFER_EXPORT, fmt_name + " " + fname.absFileName());
2365 return dr.dispatched();
2369 bool GuiView::saveBuffer(Buffer & b) {
2370 return saveBuffer(b, FileName());
2374 bool GuiView::saveBuffer(Buffer & b, FileName const & fn)
2376 if (workArea(b) && workArea(b)->inDialogMode())
2379 if (fn.empty() && b.isUnnamed())
2380 return renameBuffer(b, docstring());
2386 success = b.saveAs(fn);
2389 theSession().lastFiles().add(b.fileName());
2393 // Switch to this Buffer.
2396 // FIXME: we don't tell the user *WHY* the save failed !!
2397 docstring const file = makeDisplayPath(b.absFileName(), 30);
2398 docstring text = bformat(_("The document %1$s could not be saved.\n\n"
2399 "Do you want to rename the document and "
2400 "try again?"), file);
2401 int const ret = Alert::prompt(_("Rename and save?"),
2402 text, 0, 2, _("&Rename"), _("&Retry"), _("&Cancel"));
2405 if (!renameBuffer(b, docstring()))
2414 return saveBuffer(b);
2418 bool GuiView::hideWorkArea(GuiWorkArea * wa)
2420 return closeWorkArea(wa, false);
2424 // We only want to close the buffer if it is not visible in other workareas
2425 // of the same view, nor in other views, and if this is not a child
2426 bool GuiView::closeWorkArea(GuiWorkArea * wa)
2428 Buffer & buf = wa->bufferView().buffer();
2430 bool last_wa = d.countWorkAreasOf(buf) == 1
2431 && !inOtherView(buf) && !buf.parent();
2433 bool close_buffer = last_wa;
2436 if (lyxrc.close_buffer_with_last_view == "yes")
2438 else if (lyxrc.close_buffer_with_last_view == "no")
2439 close_buffer = false;
2442 if (buf.isUnnamed())
2443 file = from_utf8(buf.fileName().onlyFileName());
2445 file = buf.fileName().displayName(30);
2446 docstring const text = bformat(
2447 _("Last view on document %1$s is being closed.\n"
2448 "Would you like to close or hide the document?\n"
2450 "Hidden documents can be displayed back through\n"
2451 "the menu: View->Hidden->...\n"
2453 "To remove this question, set your preference in:\n"
2454 " Tools->Preferences->Look&Feel->UserInterface\n"
2456 int ret = Alert::prompt(_("Close or hide document?"),
2457 text, 0, 1, _("&Close"), _("&Hide"));
2458 close_buffer = (ret == 0);
2462 return closeWorkArea(wa, close_buffer);
2466 bool GuiView::closeBuffer()
2468 GuiWorkArea * wa = currentMainWorkArea();
2469 setCurrentWorkArea(wa);
2470 Buffer & buf = wa->bufferView().buffer();
2471 return wa && closeWorkArea(wa, !buf.parent());
2475 void GuiView::writeSession() const {
2476 GuiWorkArea const * active_wa = currentMainWorkArea();
2477 for (int i = 0; i < d.splitter_->count(); ++i) {
2478 TabWorkArea * twa = d.tabWorkArea(i);
2479 for (int j = 0; j < twa->count(); ++j) {
2480 GuiWorkArea * wa = static_cast<GuiWorkArea *>(twa->widget(j));
2481 Buffer & buf = wa->bufferView().buffer();
2482 theSession().lastOpened().add(buf.fileName(), wa == active_wa);
2488 bool GuiView::closeBufferAll()
2490 // Close the workareas in all other views
2491 QList<int> const ids = guiApp->viewIds();
2492 for (int i = 0; i != ids.size(); ++i) {
2493 if (id_ != ids[i] && !guiApp->view(ids[i]).closeWorkAreaAll())
2497 // Close our own workareas
2498 if (!closeWorkAreaAll())
2501 // Now close the hidden buffers. We prevent hidden buffers from being
2502 // dirty, so we can just close them.
2503 theBufferList().closeAll();
2508 bool GuiView::closeWorkAreaAll()
2510 setCurrentWorkArea(currentMainWorkArea());
2512 // We might be in a situation that there is still a tabWorkArea, but
2513 // there are no tabs anymore. This can happen when we get here after a
2514 // TabWorkArea::lastWorkAreaRemoved() signal. Therefore we count how
2515 // many TabWorkArea's have no documents anymore.
2518 // We have to call count() each time, because it can happen that
2519 // more than one splitter will disappear in one iteration (bug 5998).
2520 for (; d.splitter_->count() > empty_twa; ) {
2521 TabWorkArea * twa = d.tabWorkArea(empty_twa);
2523 if (twa->count() == 0)
2526 setCurrentWorkArea(twa->currentWorkArea());
2527 if (!closeTabWorkArea(twa))
2535 bool GuiView::closeWorkArea(GuiWorkArea * wa, bool close_buffer)
2540 Buffer & buf = wa->bufferView().buffer();
2542 if (close_buffer && GuiViewPrivate::busyBuffers.contains(&buf)) {
2543 Alert::warning(_("Close document"),
2544 _("Document could not be closed because it is being processed by LyX."));
2549 return closeBuffer(buf);
2551 if (!inMultiTabs(wa))
2552 if (!saveBufferIfNeeded(buf, true))
2560 bool GuiView::closeBuffer(Buffer & buf)
2562 // If we are in a close_event all children will be closed in some time,
2563 // so no need to do it here. This will ensure that the children end up
2564 // in the session file in the correct order. If we close the master
2565 // buffer, we can close or release the child buffers here too.
2566 bool success = true;
2568 ListOfBuffers clist = buf.getChildren();
2569 ListOfBuffers::const_iterator it = clist.begin();
2570 ListOfBuffers::const_iterator const bend = clist.end();
2571 for (; it != bend; ++it) {
2572 // If a child is dirty, do not close
2573 // without user intervention
2574 //FIXME: should we look in other tabworkareas?
2575 Buffer * child_buf = *it;
2576 GuiWorkArea * child_wa = workArea(*child_buf);
2578 if (!closeWorkArea(child_wa, true)) {
2583 theBufferList().releaseChild(&buf, child_buf);
2587 // goto bookmark to update bookmark pit.
2588 //FIXME: we should update only the bookmarks related to this buffer!
2589 LYXERR(Debug::DEBUG, "GuiView::closeBuffer()");
2590 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
2591 guiApp->gotoBookmark(i+1, false, false);
2593 if (saveBufferIfNeeded(buf, false)) {
2594 buf.removeAutosaveFile();
2595 theBufferList().release(&buf);
2599 // open all children again to avoid a crash because of dangling
2600 // pointers (bug 6603)
2606 bool GuiView::closeTabWorkArea(TabWorkArea * twa)
2608 while (twa == d.currentTabWorkArea()) {
2609 twa->setCurrentIndex(twa->count()-1);
2611 GuiWorkArea * wa = twa->currentWorkArea();
2612 Buffer & b = wa->bufferView().buffer();
2614 // We only want to close the buffer if the same buffer is not visible
2615 // in another view, and if this is not a child and if we are closing
2616 // a view (not a tabgroup).
2617 bool const close_buffer =
2618 !inOtherView(b) && !b.parent() && closing_;
2620 if (!closeWorkArea(wa, close_buffer))
2627 bool GuiView::saveBufferIfNeeded(Buffer & buf, bool hiding)
2629 if (buf.isClean() || buf.paragraphs().empty())
2632 // Switch to this Buffer.
2637 if (buf.isUnnamed())
2638 file = from_utf8(buf.fileName().onlyFileName());
2640 file = buf.fileName().displayName(30);
2642 // Bring this window to top before asking questions.
2647 if (hiding && buf.isUnnamed()) {
2648 docstring const text = bformat(_("The document %1$s has not been "
2649 "saved yet.\n\nDo you want to save "
2650 "the document?"), file);
2651 ret = Alert::prompt(_("Save new document?"),
2652 text, 0, 1, _("&Save"), _("&Cancel"));
2656 docstring const text = bformat(_("The document %1$s has unsaved changes."
2657 "\n\nDo you want to save the document or discard the changes?"), file);
2658 ret = Alert::prompt(_("Save changed document?"),
2659 text, 0, 2, _("&Save"), _("&Discard"), _("&Cancel"));
2664 if (!saveBuffer(buf))
2668 // If we crash after this we could have no autosave file
2669 // but I guess this is really improbable (Jug).
2670 // Sometimes improbable things happen:
2671 // - see bug http://www.lyx.org/trac/ticket/6587 (ps)
2672 // buf.removeAutosaveFile();
2674 // revert all changes
2685 bool GuiView::inMultiTabs(GuiWorkArea * wa)
2687 Buffer & buf = wa->bufferView().buffer();
2689 for (int i = 0; i != d.splitter_->count(); ++i) {
2690 GuiWorkArea * wa_ = d.tabWorkArea(i)->workArea(buf);
2691 if (wa_ && wa_ != wa)
2694 return inOtherView(buf);
2698 bool GuiView::inOtherView(Buffer & buf)
2700 QList<int> const ids = guiApp->viewIds();
2702 for (int i = 0; i != ids.size(); ++i) {
2706 if (guiApp->view(ids[i]).workArea(buf))
2713 void GuiView::gotoNextOrPreviousBuffer(NextOrPrevious np)
2715 if (!documentBufferView())
2718 if (TabWorkArea * twa = d.currentTabWorkArea()) {
2719 Buffer * const curbuf = &documentBufferView()->buffer();
2720 int nwa = twa->count();
2721 for (int i = 0; i < nwa; ++i) {
2722 if (&workArea(i)->bufferView().buffer() == curbuf) {
2724 if (np == NEXTBUFFER)
2725 next_index = (i == nwa - 1 ? 0 : i + 1);
2727 next_index = (i == 0 ? nwa - 1 : i - 1);
2728 setBuffer(&workArea(next_index)->bufferView().buffer());
2736 /// make sure the document is saved
2737 static bool ensureBufferClean(Buffer * buffer)
2739 LASSERT(buffer, return false);
2740 if (buffer->isClean() && !buffer->isUnnamed())
2743 docstring const file = buffer->fileName().displayName(30);
2746 if (!buffer->isUnnamed()) {
2747 text = bformat(_("The document %1$s has unsaved "
2748 "changes.\n\nDo you want to save "
2749 "the document?"), file);
2750 title = _("Save changed document?");
2753 text = bformat(_("The document %1$s has not been "
2754 "saved yet.\n\nDo you want to save "
2755 "the document?"), file);
2756 title = _("Save new document?");
2758 int const ret = Alert::prompt(title, text, 0, 1, _("&Save"), _("&Cancel"));
2761 dispatch(FuncRequest(LFUN_BUFFER_WRITE));
2763 return buffer->isClean() && !buffer->isUnnamed();
2767 bool GuiView::reloadBuffer(Buffer & buf)
2769 Buffer::ReadStatus status = buf.reload();
2770 return status == Buffer::ReadSuccess;
2774 void GuiView::checkExternallyModifiedBuffers()
2776 BufferList::iterator bit = theBufferList().begin();
2777 BufferList::iterator const bend = theBufferList().end();
2778 for (; bit != bend; ++bit) {
2779 Buffer * buf = *bit;
2780 if (buf->fileName().exists()
2781 && buf->isExternallyModified(Buffer::checksum_method)) {
2782 docstring text = bformat(_("Document \n%1$s\n has been externally modified."
2783 " Reload now? Any local changes will be lost."),
2784 from_utf8(buf->absFileName()));
2785 int const ret = Alert::prompt(_("Reload externally changed document?"),
2786 text, 0, 1, _("&Reload"), _("&Cancel"));
2794 void GuiView::dispatchVC(FuncRequest const & cmd, DispatchResult & dr)
2796 Buffer * buffer = documentBufferView()
2797 ? &(documentBufferView()->buffer()) : 0;
2799 switch (cmd.action()) {
2800 case LFUN_VC_REGISTER:
2801 if (!buffer || !ensureBufferClean(buffer))
2803 if (!buffer->lyxvc().inUse()) {
2804 if (buffer->lyxvc().registrer()) {
2805 reloadBuffer(*buffer);
2806 dr.suppressMessageUpdate();
2811 case LFUN_VC_CHECK_IN:
2812 if (!buffer || !ensureBufferClean(buffer))
2814 if (buffer->lyxvc().inUse() && !buffer->isReadonly()) {
2815 dr.setMessage(buffer->lyxvc().checkIn());
2816 if (!dr.message().empty())
2817 reloadBuffer(*buffer);
2821 case LFUN_VC_CHECK_OUT:
2822 if (!buffer || !ensureBufferClean(buffer))
2824 if (buffer->lyxvc().inUse()) {
2825 dr.setMessage(buffer->lyxvc().checkOut());
2826 reloadBuffer(*buffer);
2830 case LFUN_VC_LOCKING_TOGGLE:
2831 LASSERT(buffer, return);
2832 if (!ensureBufferClean(buffer) || buffer->isReadonly())
2834 if (buffer->lyxvc().inUse()) {
2835 string res = buffer->lyxvc().lockingToggle();
2837 frontend::Alert::error(_("Revision control error."),
2838 _("Error when setting the locking property."));
2841 reloadBuffer(*buffer);
2846 case LFUN_VC_REVERT:
2847 LASSERT(buffer, return);
2848 if (buffer->lyxvc().revert()) {
2849 reloadBuffer(*buffer);
2850 dr.suppressMessageUpdate();
2854 case LFUN_VC_UNDO_LAST:
2855 LASSERT(buffer, return);
2856 buffer->lyxvc().undoLast();
2857 reloadBuffer(*buffer);
2858 dr.suppressMessageUpdate();
2861 case LFUN_VC_REPO_UPDATE:
2862 LASSERT(buffer, return);
2863 if (ensureBufferClean(buffer)) {
2864 dr.setMessage(buffer->lyxvc().repoUpdate());
2865 checkExternallyModifiedBuffers();
2869 case LFUN_VC_COMMAND: {
2870 string flag = cmd.getArg(0);
2871 if (buffer && contains(flag, 'R') && !ensureBufferClean(buffer))
2874 if (contains(flag, 'M')) {
2875 if (!Alert::askForText(message, _("LyX VC: Log Message")))
2878 string path = cmd.getArg(1);
2879 if (contains(path, "$$p") && buffer)
2880 path = subst(path, "$$p", buffer->filePath());
2881 LYXERR(Debug::LYXVC, "Directory: " << path);
2883 if (!pp.isReadableDirectory()) {
2884 lyxerr << _("Directory is not accessible.") << endl;
2887 support::PathChanger p(pp);
2889 string command = cmd.getArg(2);
2890 if (command.empty())
2893 command = subst(command, "$$i", buffer->absFileName());
2894 command = subst(command, "$$p", buffer->filePath());
2896 command = subst(command, "$$m", to_utf8(message));
2897 LYXERR(Debug::LYXVC, "Command: " << command);
2899 one.startscript(Systemcall::Wait, command);
2903 if (contains(flag, 'I'))
2904 buffer->markDirty();
2905 if (contains(flag, 'R'))
2906 reloadBuffer(*buffer);
2911 case LFUN_VC_COMPARE: {
2913 if (cmd.argument().empty()) {
2914 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "comparehistory"));
2918 string rev1 = cmd.getArg(0);
2922 if (!buffer->lyxvc().prepareFileRevision(rev1, f1))
2925 if (isStrInt(rev1) && convert<int>(rev1) <= 0) {
2926 f2 = buffer->absFileName();
2928 string rev2 = cmd.getArg(1);
2932 if (!buffer->lyxvc().prepareFileRevision(rev2, f2))
2936 LYXERR(Debug::LYXVC, "Launching comparison for fetched revisions:\n" <<
2937 f1 << "\n" << f2 << "\n" );
2938 string par = "compare run " + quoteName(f1) + " " + quoteName(f2);
2939 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, par));
2949 void GuiView::openChildDocument(string const & fname)
2951 LASSERT(documentBufferView(), return);
2952 Buffer & buffer = documentBufferView()->buffer();
2953 FileName const filename = support::makeAbsPath(fname, buffer.filePath());
2954 documentBufferView()->saveBookmark(false);
2956 if (theBufferList().exists(filename)) {
2957 child = theBufferList().getBuffer(filename);
2960 message(bformat(_("Opening child document %1$s..."),
2961 makeDisplayPath(filename.absFileName())));
2962 child = loadDocument(filename, false);
2964 // Set the parent name of the child document.
2965 // This makes insertion of citations and references in the child work,
2966 // when the target is in the parent or another child document.
2968 child->setParent(&buffer);
2972 bool GuiView::goToFileRow(string const & argument)
2976 size_t i = argument.find_last_of(' ');
2977 if (i != string::npos) {
2978 file_name = os::internal_path(trim(argument.substr(0, i)));
2979 istringstream is(argument.substr(i + 1));
2984 if (i == string::npos) {
2985 LYXERR0("Wrong argument: " << argument);
2989 string const abstmp = package().temp_dir().absFileName();
2990 string const realtmp = package().temp_dir().realPath();
2991 // We have to use os::path_prefix_is() here, instead of
2992 // simply prefixIs(), because the file name comes from
2993 // an external application and may need case adjustment.
2994 if (os::path_prefix_is(file_name, abstmp, os::CASE_ADJUSTED)
2995 || os::path_prefix_is(file_name, realtmp, os::CASE_ADJUSTED)) {
2996 // Needed by inverse dvi search. If it is a file
2997 // in tmpdir, call the apropriated function.
2998 // If tmpdir is a symlink, we may have the real
2999 // path passed back, so we correct for that.
3000 if (!prefixIs(file_name, abstmp))
3001 file_name = subst(file_name, realtmp, abstmp);
3002 buf = theBufferList().getBufferFromTmp(file_name);
3004 // Must replace extension of the file to be .lyx
3005 // and get full path
3006 FileName const s = fileSearch(string(),
3007 support::changeExtension(file_name, ".lyx"), "lyx");
3008 // Either change buffer or load the file
3009 if (theBufferList().exists(s))
3010 buf = theBufferList().getBuffer(s);
3011 else if (s.exists()) {
3012 buf = loadDocument(s);
3017 _("File does not exist: %1$s"),
3018 makeDisplayPath(file_name)));
3024 _("No buffer for file: %1$s."),
3025 makeDisplayPath(file_name))
3030 documentBufferView()->setCursorFromRow(row);
3036 Buffer::ExportStatus GuiView::GuiViewPrivate::runAndDestroy(const T& func, Buffer const * orig, Buffer * clone, string const & format)
3038 Buffer::ExportStatus const status = func(format);
3040 // the cloning operation will have produced a clone of the entire set of
3041 // documents, starting from the master. so we must delete those.
3042 Buffer * mbuf = const_cast<Buffer *>(clone->masterBuffer());
3044 busyBuffers.remove(orig);
3049 Buffer::ExportStatus GuiView::GuiViewPrivate::compileAndDestroy(Buffer const * orig, Buffer * clone, string const & format)
3051 Buffer::ExportStatus (Buffer::* mem_func)(std::string const &, bool) const = &Buffer::doExport;
3052 return runAndDestroy(lyx::bind(mem_func, clone, _1, true), orig, clone, format);
3056 Buffer::ExportStatus GuiView::GuiViewPrivate::exportAndDestroy(Buffer const * orig, Buffer * clone, string const & format)
3058 Buffer::ExportStatus (Buffer::* mem_func)(std::string const &, bool) const = &Buffer::doExport;
3059 return runAndDestroy(lyx::bind(mem_func, clone, _1, false), orig, clone, format);
3063 Buffer::ExportStatus GuiView::GuiViewPrivate::previewAndDestroy(Buffer const * orig, Buffer * clone, string const & format)
3065 Buffer::ExportStatus (Buffer::* mem_func)(std::string const &) const = &Buffer::preview;
3066 return runAndDestroy(lyx::bind(mem_func, clone, _1), orig, clone, format);
3070 bool GuiView::GuiViewPrivate::asyncBufferProcessing(
3071 string const & argument,
3072 Buffer const * used_buffer,
3073 docstring const & msg,
3074 Buffer::ExportStatus (*asyncFunc)(Buffer const *, Buffer *, string const &),
3075 Buffer::ExportStatus (Buffer::*syncFunc)(string const &, bool) const,
3076 Buffer::ExportStatus (Buffer::*previewFunc)(string const &) const)
3081 string format = argument;
3083 format = used_buffer->params().getDefaultOutputFormat();
3084 processing_format = format;
3085 #if EXPORT_in_THREAD
3087 progress_->clearMessages();
3090 GuiViewPrivate::busyBuffers.insert(used_buffer);
3091 Buffer * cloned_buffer = used_buffer->cloneFromMaster();
3092 if (!cloned_buffer) {
3093 Alert::error(_("Export Error"),
3094 _("Error cloning the Buffer."));
3097 QFuture<Buffer::ExportStatus> f = QtConcurrent::run(
3102 setPreviewFuture(f);
3103 last_export_format = used_buffer->params().bufferFormat();
3106 // We are asynchronous, so we don't know here anything about the success
3109 Buffer::ExportStatus status;
3111 // TODO check here if it breaks exporting with Qt < 4.4
3112 status = (used_buffer->*syncFunc)(format, true);
3113 } else if (previewFunc) {
3114 status = (used_buffer->*previewFunc)(format);
3117 handleExportStatus(gv_, status, format);
3119 return (status == Buffer::ExportSuccess
3120 || status == Buffer::PreviewSuccess);
3124 void GuiView::dispatchToBufferView(FuncRequest const & cmd, DispatchResult & dr)
3126 BufferView * bv = currentBufferView();
3129 // Let the current BufferView dispatch its own actions.
3130 bv->dispatch(cmd, dr);
3131 if (dr.dispatched())
3134 // Try with the document BufferView dispatch if any.
3135 BufferView * doc_bv = documentBufferView();
3136 if (doc_bv && doc_bv != bv) {
3137 doc_bv->dispatch(cmd, dr);
3138 if (dr.dispatched())
3142 // Then let the current Cursor dispatch its own actions.
3143 bv->cursor().dispatch(cmd);
3145 // update completion. We do it here and not in
3146 // processKeySym to avoid another redraw just for a
3147 // changed inline completion
3148 if (cmd.origin() == FuncRequest::KEYBOARD) {
3149 if (cmd.action() == LFUN_SELF_INSERT
3150 || (cmd.action() == LFUN_ERT_INSERT && bv->cursor().inMathed()))
3151 updateCompletion(bv->cursor(), true, true);
3152 else if (cmd.action() == LFUN_CHAR_DELETE_BACKWARD)
3153 updateCompletion(bv->cursor(), false, true);
3155 updateCompletion(bv->cursor(), false, false);
3158 dr = bv->cursor().result();
3162 void GuiView::dispatch(FuncRequest const & cmd, DispatchResult & dr)
3164 BufferView * bv = currentBufferView();
3165 // By default we won't need any update.
3166 dr.screenUpdate(Update::None);
3167 // assume cmd will be dispatched
3168 dr.dispatched(true);
3170 Buffer * doc_buffer = documentBufferView()
3171 ? &(documentBufferView()->buffer()) : 0;
3173 if (cmd.origin() == FuncRequest::TOC) {
3174 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
3175 // FIXME: do we need to pass a DispatchResult object here?
3176 toc->doDispatch(bv->cursor(), cmd);
3180 string const argument = to_utf8(cmd.argument());
3182 switch(cmd.action()) {
3183 case LFUN_BUFFER_CHILD_OPEN:
3184 openChildDocument(to_utf8(cmd.argument()));
3187 case LFUN_BUFFER_IMPORT:
3188 importDocument(to_utf8(cmd.argument()));
3191 case LFUN_BUFFER_EXPORT: {
3194 // GCC only sees strfwd.h when building merged
3195 if (::lyx::operator==(cmd.argument(), "custom")) {
3196 dispatch(FuncRequest(LFUN_DIALOG_SHOW, "sendto"), dr);
3199 /* TODO/Review: Is it a problem to also export the children?
3200 See the update_unincluded flag */
3201 d.asyncBufferProcessing(argument,
3204 &GuiViewPrivate::exportAndDestroy,
3207 // TODO Inform user about success
3211 case LFUN_BUFFER_EXPORT_AS:
3212 LASSERT(doc_buffer, break);
3213 exportBufferAs(*doc_buffer);
3216 case LFUN_BUFFER_UPDATE: {
3217 d.asyncBufferProcessing(argument,
3220 &GuiViewPrivate::compileAndDestroy,
3225 case LFUN_BUFFER_VIEW: {
3226 d.asyncBufferProcessing(argument,
3228 _("Previewing ..."),
3229 &GuiViewPrivate::previewAndDestroy,
3234 case LFUN_MASTER_BUFFER_UPDATE: {
3235 d.asyncBufferProcessing(argument,
3236 (doc_buffer ? doc_buffer->masterBuffer() : 0),
3238 &GuiViewPrivate::compileAndDestroy,
3243 case LFUN_MASTER_BUFFER_VIEW: {
3244 d.asyncBufferProcessing(argument,
3245 (doc_buffer ? doc_buffer->masterBuffer() : 0),
3247 &GuiViewPrivate::previewAndDestroy,
3248 0, &Buffer::preview);
3251 case LFUN_BUFFER_SWITCH: {
3252 string const file_name = to_utf8(cmd.argument());
3253 if (!FileName::isAbsolute(file_name)) {
3255 dr.setMessage(_("Absolute filename expected."));
3259 Buffer * buffer = theBufferList().getBuffer(FileName(file_name));
3262 dr.setMessage(_("Document not loaded"));
3266 // Do we open or switch to the buffer in this view ?
3267 if (workArea(*buffer)
3268 || lyxrc.open_buffers_in_tabs || !documentBufferView()) {
3273 // Look for the buffer in other views
3274 QList<int> const ids = guiApp->viewIds();
3276 for (; i != ids.size(); ++i) {
3277 GuiView & gv = guiApp->view(ids[i]);
3278 if (gv.workArea(*buffer)) {
3279 gv.activateWindow();
3280 gv.setBuffer(buffer);
3285 // If necessary, open a new window as a last resort
3286 if (i == ids.size()) {
3287 lyx::dispatch(FuncRequest(LFUN_WINDOW_NEW));
3293 case LFUN_BUFFER_NEXT:
3294 gotoNextOrPreviousBuffer(NEXTBUFFER);
3297 case LFUN_BUFFER_PREVIOUS:
3298 gotoNextOrPreviousBuffer(PREVBUFFER);
3301 case LFUN_COMMAND_EXECUTE: {
3302 bool const show_it = cmd.argument() != "off";
3303 // FIXME: this is a hack, "minibuffer" should not be
3305 if (GuiToolbar * t = toolbar("minibuffer")) {
3306 t->setVisible(show_it);
3307 if (show_it && t->commandBuffer())
3308 t->commandBuffer()->setFocus();
3312 case LFUN_DROP_LAYOUTS_CHOICE:
3313 d.layout_->showPopup();
3316 case LFUN_MENU_OPEN:
3317 if (QMenu * menu = guiApp->menus().menu(toqstr(cmd.argument()), *this))
3318 menu->exec(QCursor::pos());
3321 case LFUN_FILE_INSERT:
3322 insertLyXFile(cmd.argument());
3325 case LFUN_FILE_INSERT_PLAINTEXT:
3326 case LFUN_FILE_INSERT_PLAINTEXT_PARA: {
3327 bool const as_paragraph = (cmd.action() == LFUN_FILE_INSERT_PLAINTEXT_PARA);
3328 string const fname = to_utf8(cmd.argument());
3329 if (!fname.empty() && !FileName::isAbsolute(fname)) {
3330 dr.setMessage(_("Absolute filename expected."));
3334 FileName filename(fname);
3335 if (fname.empty()) {
3336 FileDialog dlg(qt_("Select file to insert"), (as_paragraph ?
3337 LFUN_FILE_INSERT_PLAINTEXT_PARA : LFUN_FILE_INSERT_PLAINTEXT));
3339 FileDialog::Result result = dlg.open(toqstr(bv->buffer().filePath()),
3340 QStringList(qt_("All Files (*)")));
3342 if (result.first == FileDialog::Later || result.second.isEmpty()) {
3343 dr.setMessage(_("Canceled."));
3347 filename.set(fromqstr(result.second));
3351 FuncRequest const new_cmd(cmd, filename.absoluteFilePath());
3352 bv->dispatch(new_cmd, dr);
3357 case LFUN_BUFFER_RELOAD: {
3358 LASSERT(doc_buffer, break);
3361 if (!doc_buffer->isClean()) {
3362 docstring const file =
3363 makeDisplayPath(doc_buffer->absFileName(), 20);
3364 docstring text = bformat(_("Any changes will be lost. "
3365 "Are you sure you want to revert to the saved version "
3366 "of the document %1$s?"), file);
3367 ret = Alert::prompt(_("Revert to saved document?"),
3368 text, 1, 1, _("&Revert"), _("&Cancel"));
3372 doc_buffer->markClean();
3373 reloadBuffer(*doc_buffer);
3374 dr.forceBufferUpdate();
3379 case LFUN_BUFFER_WRITE:
3380 LASSERT(doc_buffer, break);
3381 saveBuffer(*doc_buffer);
3384 case LFUN_BUFFER_WRITE_AS:
3385 LASSERT(doc_buffer, break);
3386 renameBuffer(*doc_buffer, cmd.argument());
3389 case LFUN_BUFFER_WRITE_ALL: {
3390 Buffer * first = theBufferList().first();
3393 message(_("Saving all documents..."));
3394 // We cannot use a for loop as the buffer list cycles.
3397 if (!b->isClean()) {
3399 LYXERR(Debug::ACTION, "Saved " << b->absFileName());
3401 b = theBufferList().next(b);
3402 } while (b != first);
3403 dr.setMessage(_("All documents saved."));
3407 case LFUN_BUFFER_CLOSE:
3411 case LFUN_BUFFER_CLOSE_ALL:
3415 case LFUN_TOOLBAR_TOGGLE: {
3416 string const name = cmd.getArg(0);
3417 if (GuiToolbar * t = toolbar(name))
3422 case LFUN_DIALOG_UPDATE: {
3423 string const name = to_utf8(cmd.argument());
3424 if (name == "prefs" || name == "document")
3425 updateDialog(name, string());
3426 else if (name == "paragraph")
3427 lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
3428 else if (currentBufferView()) {
3429 Inset * inset = currentBufferView()->editedInset(name);
3430 // Can only update a dialog connected to an existing inset
3432 // FIXME: get rid of this indirection; GuiView ask the inset
3433 // if he is kind enough to update itself...
3434 FuncRequest fr(LFUN_INSET_DIALOG_UPDATE, cmd.argument());
3435 //FIXME: pass DispatchResult here?
3436 inset->dispatch(currentBufferView()->cursor(), fr);
3442 case LFUN_DIALOG_TOGGLE: {
3443 FuncCode const func_code = isDialogVisible(cmd.getArg(0))
3444 ? LFUN_DIALOG_HIDE : LFUN_DIALOG_SHOW;
3445 dispatch(FuncRequest(func_code, cmd.argument()), dr);
3449 case LFUN_DIALOG_DISCONNECT_INSET:
3450 disconnectDialog(to_utf8(cmd.argument()));
3453 case LFUN_DIALOG_HIDE: {
3454 guiApp->hideDialogs(to_utf8(cmd.argument()), 0);
3458 case LFUN_DIALOG_SHOW: {
3459 string const name = cmd.getArg(0);
3460 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
3462 if (name == "character") {
3463 data = freefont2string();
3465 showDialog("character", data);
3466 } else if (name == "latexlog") {
3467 Buffer::LogType type;
3468 string const logfile = doc_buffer->logName(&type);
3470 case Buffer::latexlog:
3473 case Buffer::buildlog:
3477 data += Lexer::quoteString(logfile);
3478 showDialog("log", data);
3479 } else if (name == "vclog") {
3480 string const data = "vc " +
3481 Lexer::quoteString(doc_buffer->lyxvc().getLogFile());
3482 showDialog("log", data);
3483 } else if (name == "symbols") {
3484 data = bv->cursor().getEncoding()->name();
3486 showDialog("symbols", data);
3488 } else if (name == "prefs" && isFullScreen()) {
3489 lfunUiToggle("fullscreen");
3490 showDialog("prefs", data);
3492 showDialog(name, data);
3497 dr.setMessage(cmd.argument());
3500 case LFUN_UI_TOGGLE: {
3501 string arg = cmd.getArg(0);
3502 if (!lfunUiToggle(arg)) {
3503 docstring const msg = "ui-toggle " + _("%1$s unknown command!");
3504 dr.setMessage(bformat(msg, from_utf8(arg)));
3506 // Make sure the keyboard focus stays in the work area.
3511 case LFUN_VIEW_SPLIT: {
3512 LASSERT(doc_buffer, break);
3513 string const orientation = cmd.getArg(0);
3514 d.splitter_->setOrientation(orientation == "vertical"
3515 ? Qt::Vertical : Qt::Horizontal);
3516 TabWorkArea * twa = addTabWorkArea();
3517 GuiWorkArea * wa = twa->addWorkArea(*doc_buffer, *this);
3518 setCurrentWorkArea(wa);
3521 case LFUN_TAB_GROUP_CLOSE:
3522 if (TabWorkArea * twa = d.currentTabWorkArea()) {
3523 closeTabWorkArea(twa);
3524 d.current_work_area_ = 0;
3525 twa = d.currentTabWorkArea();
3526 // Switch to the next GuiWorkArea in the found TabWorkArea.
3528 // Make sure the work area is up to date.
3529 setCurrentWorkArea(twa->currentWorkArea());
3531 setCurrentWorkArea(0);
3536 case LFUN_VIEW_CLOSE:
3537 if (TabWorkArea * twa = d.currentTabWorkArea()) {
3538 closeWorkArea(twa->currentWorkArea());
3539 d.current_work_area_ = 0;
3540 twa = d.currentTabWorkArea();
3541 // Switch to the next GuiWorkArea in the found TabWorkArea.
3543 // Make sure the work area is up to date.
3544 setCurrentWorkArea(twa->currentWorkArea());
3546 setCurrentWorkArea(0);
3551 case LFUN_COMPLETION_INLINE:
3552 if (d.current_work_area_)
3553 d.current_work_area_->completer().showInline();
3556 case LFUN_COMPLETION_POPUP:
3557 if (d.current_work_area_)
3558 d.current_work_area_->completer().showPopup();
3562 case LFUN_COMPLETION_COMPLETE:
3563 if (d.current_work_area_)
3564 d.current_work_area_->completer().tab();
3567 case LFUN_COMPLETION_CANCEL:
3568 if (d.current_work_area_) {
3569 if (d.current_work_area_->completer().popupVisible())
3570 d.current_work_area_->completer().hidePopup();
3572 d.current_work_area_->completer().hideInline();
3576 case LFUN_COMPLETION_ACCEPT:
3577 if (d.current_work_area_)
3578 d.current_work_area_->completer().activate();
3581 case LFUN_BUFFER_ZOOM_IN:
3582 case LFUN_BUFFER_ZOOM_OUT:
3583 if (cmd.argument().empty()) {
3584 if (cmd.action() == LFUN_BUFFER_ZOOM_IN)
3589 lyxrc.zoom += convert<int>(cmd.argument());
3591 if (lyxrc.zoom < 10)
3594 // The global QPixmapCache is used in GuiPainter to cache text
3595 // painting so we must reset it.
3596 QPixmapCache::clear();
3597 guiApp->fontLoader().update();
3598 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
3601 case LFUN_VC_REGISTER:
3602 case LFUN_VC_CHECK_IN:
3603 case LFUN_VC_CHECK_OUT:
3604 case LFUN_VC_REPO_UPDATE:
3605 case LFUN_VC_LOCKING_TOGGLE:
3606 case LFUN_VC_REVERT:
3607 case LFUN_VC_UNDO_LAST:
3608 case LFUN_VC_COMMAND:
3609 case LFUN_VC_COMPARE:
3610 dispatchVC(cmd, dr);
3613 case LFUN_SERVER_GOTO_FILE_ROW:
3614 goToFileRow(to_utf8(cmd.argument()));
3617 case LFUN_FORWARD_SEARCH: {
3618 Buffer const * doc_master = doc_buffer->masterBuffer();
3619 FileName const path(doc_master->temppath());
3620 string const texname = doc_master->isChild(doc_buffer)
3621 ? DocFileName(changeExtension(
3622 doc_buffer->absFileName(),
3623 "tex")).mangledFileName()
3624 : doc_buffer->latexName();
3625 string const fulltexname =
3626 support::makeAbsPath(texname, doc_master->temppath()).absFileName();
3627 string const mastername =
3628 removeExtension(doc_master->latexName());
3629 FileName const dviname(addName(path.absFileName(),
3630 addExtension(mastername, "dvi")));
3631 FileName const pdfname(addName(path.absFileName(),
3632 addExtension(mastername, "pdf")));
3633 bool const have_dvi = dviname.exists();
3634 bool const have_pdf = pdfname.exists();
3635 if (!have_dvi && !have_pdf) {
3636 dr.setMessage(_("Please, preview the document first."));
3639 string outname = dviname.onlyFileName();
3640 string command = lyxrc.forward_search_dvi;
3641 if (!have_dvi || (have_pdf &&
3642 pdfname.lastModified() > dviname.lastModified())) {
3643 outname = pdfname.onlyFileName();
3644 command = lyxrc.forward_search_pdf;
3647 DocIterator tmpcur = bv->cursor();
3649 while (tmpcur.inMathed())
3651 int row = tmpcur.inMathed() ? 0 : doc_buffer->texrow().getRowFromIdPos(
3652 tmpcur.paragraph().id(), tmpcur.pos());
3653 LYXERR(Debug::ACTION, "Forward search: row:" << row
3654 << " id:" << tmpcur.paragraph().id());
3655 if (!row || command.empty()) {
3656 dr.setMessage(_("Couldn't proceed."));
3659 string texrow = convert<string>(row);
3661 command = subst(command, "$$n", texrow);
3662 command = subst(command, "$$f", fulltexname);
3663 command = subst(command, "$$t", texname);
3664 command = subst(command, "$$o", outname);
3666 PathChanger p(path);
3668 one.startscript(Systemcall::DontWait, command);
3672 // The LFUN must be for one of BufferView, Buffer or Cursor;
3674 dispatchToBufferView(cmd, dr);
3678 // Part of automatic menu appearance feature.
3679 if (isFullScreen()) {
3680 if (menuBar()->isVisible() && lyxrc.full_screen_menubar)
3682 if (statusBar()->isVisible())
3683 statusBar()->hide();
3688 bool GuiView::lfunUiToggle(string const & ui_component)
3690 if (ui_component == "scrollbar") {
3691 // hide() is of no help
3692 if (d.current_work_area_->verticalScrollBarPolicy() ==
3693 Qt::ScrollBarAlwaysOff)
3695 d.current_work_area_->setVerticalScrollBarPolicy(
3696 Qt::ScrollBarAsNeeded);
3698 d.current_work_area_->setVerticalScrollBarPolicy(
3699 Qt::ScrollBarAlwaysOff);
3700 } else if (ui_component == "statusbar") {
3701 statusBar()->setVisible(!statusBar()->isVisible());
3702 } else if (ui_component == "menubar") {
3703 menuBar()->setVisible(!menuBar()->isVisible());
3705 if (ui_component == "frame") {
3707 getContentsMargins(&l, &t, &r, &b);
3708 //are the frames in default state?
3709 d.current_work_area_->setFrameStyle(QFrame::NoFrame);
3711 setContentsMargins(-2, -2, -2, -2);
3713 setContentsMargins(0, 0, 0, 0);
3716 if (ui_component == "fullscreen") {
3724 void GuiView::toggleFullScreen()
3726 if (isFullScreen()) {
3727 for (int i = 0; i != d.splitter_->count(); ++i)
3728 d.tabWorkArea(i)->setFullScreen(false);
3729 setContentsMargins(0, 0, 0, 0);
3730 setWindowState(windowState() ^ Qt::WindowFullScreen);
3733 statusBar()->show();
3736 hideDialogs("prefs", 0);
3737 for (int i = 0; i != d.splitter_->count(); ++i)
3738 d.tabWorkArea(i)->setFullScreen(true);
3739 setContentsMargins(-2, -2, -2, -2);
3741 setWindowState(windowState() ^ Qt::WindowFullScreen);
3742 statusBar()->hide();
3743 if (lyxrc.full_screen_menubar)
3745 if (lyxrc.full_screen_toolbars) {
3746 ToolbarMap::iterator end = d.toolbars_.end();
3747 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
3752 // give dialogs like the TOC a chance to adapt
3757 Buffer const * GuiView::updateInset(Inset const * inset)
3762 Buffer const * inset_buffer = &(inset->buffer());
3764 for (int i = 0; i != d.splitter_->count(); ++i) {
3765 GuiWorkArea * wa = d.tabWorkArea(i)->currentWorkArea();
3768 Buffer const * buffer = &(wa->bufferView().buffer());
3769 if (inset_buffer == buffer)
3770 wa->scheduleRedraw();
3772 return inset_buffer;
3776 void GuiView::restartCursor()
3778 /* When we move around, or type, it's nice to be able to see
3779 * the cursor immediately after the keypress.
3781 if (d.current_work_area_)
3782 d.current_work_area_->startBlinkingCursor();
3784 // Take this occasion to update the other GUI elements.
3790 void GuiView::updateCompletion(Cursor & cur, bool start, bool keep)
3792 if (d.current_work_area_)
3793 d.current_work_area_->completer().updateVisibility(cur, start, keep);
3798 // This list should be kept in sync with the list of insets in
3799 // src/insets/Inset.cpp. I.e., if a dialog goes with an inset, the
3800 // dialog should have the same name as the inset.
3801 // Changes should be also recorded in LFUN_DIALOG_SHOW doxygen
3802 // docs in LyXAction.cpp.
3804 char const * const dialognames[] = {
3806 "aboutlyx", "bibitem", "bibtex", "box", "branch", "changes", "character",
3807 "citation", "compare", "comparehistory", "document", "errorlist", "ert",
3808 "external", "file", "findreplace", "findreplaceadv", "float", "graphics",
3809 "href", "include", "index", "index_print", "info", "listings", "label", "line",
3810 "log", "mathdelimiter", "mathmatrix", "mathspace", "nomenclature",
3811 "nomencl_print", "note", "paragraph", "phantom", "prefs", "print", "ref",
3812 "sendto", "space", "spellchecker", "symbols", "tabular", "tabularcreate",
3813 "thesaurus", "texinfo", "toc", "view-source", "vspace", "wrap", "progress"};
3815 char const * const * const end_dialognames =
3816 dialognames + (sizeof(dialognames) / sizeof(char *));
3820 cmpCStr(char const * name) : name_(name) {}
3821 bool operator()(char const * other) {
3822 return strcmp(other, name_) == 0;
3829 bool isValidName(string const & name)
3831 return find_if(dialognames, end_dialognames,
3832 cmpCStr(name.c_str())) != end_dialognames;
3838 void GuiView::resetDialogs()
3840 // Make sure that no LFUN uses any GuiView.
3841 guiApp->setCurrentView(0);
3845 constructToolbars();
3846 guiApp->menus().fillMenuBar(menuBar(), this, false);
3847 d.layout_->updateContents(true);
3848 // Now update controls with current buffer.
3849 guiApp->setCurrentView(this);
3855 Dialog * GuiView::findOrBuild(string const & name, bool hide_it)
3857 if (!isValidName(name))
3860 map<string, DialogPtr>::iterator it = d.dialogs_.find(name);
3862 if (it != d.dialogs_.end()) {
3864 it->second->hideView();
3865 return it->second.get();
3868 Dialog * dialog = build(name);
3869 d.dialogs_[name].reset(dialog);
3870 if (lyxrc.allow_geometry_session)
3871 dialog->restoreSession();
3878 void GuiView::showDialog(string const & name, string const & data,
3881 triggerShowDialog(toqstr(name), toqstr(data), inset);
3885 void GuiView::doShowDialog(QString const & qname, QString const & qdata,
3891 const string name = fromqstr(qname);
3892 const string data = fromqstr(qdata);
3896 Dialog * dialog = findOrBuild(name, false);
3898 bool const visible = dialog->isVisibleView();
3899 dialog->showData(data);
3900 if (inset && currentBufferView())
3901 currentBufferView()->editInset(name, inset);
3902 // We only set the focus to the new dialog if it was not yet
3903 // visible in order not to change the existing previous behaviour
3905 // activateWindow is needed for floating dockviews
3906 dialog->asQWidget()->raise();
3907 dialog->asQWidget()->activateWindow();
3908 dialog->asQWidget()->setFocus();
3912 catch (ExceptionMessage const & ex) {
3920 bool GuiView::isDialogVisible(string const & name) const
3922 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3923 if (it == d.dialogs_.end())
3925 return it->second.get()->isVisibleView() && !it->second.get()->isClosing();
3929 void GuiView::hideDialog(string const & name, Inset * inset)
3931 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3932 if (it == d.dialogs_.end())
3936 if (!currentBufferView())
3938 if (inset != currentBufferView()->editedInset(name))
3942 Dialog * const dialog = it->second.get();
3943 if (dialog->isVisibleView())
3945 if (currentBufferView())
3946 currentBufferView()->editInset(name, 0);
3950 void GuiView::disconnectDialog(string const & name)
3952 if (!isValidName(name))
3954 if (currentBufferView())
3955 currentBufferView()->editInset(name, 0);
3959 void GuiView::hideAll() const
3961 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
3962 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3964 for(; it != end; ++it)
3965 it->second->hideView();
3969 void GuiView::updateDialogs()
3971 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
3972 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3974 for(; it != end; ++it) {
3975 Dialog * dialog = it->second.get();
3977 if (dialog->needBufferOpen() && !documentBufferView())
3978 hideDialog(fromqstr(dialog->name()), 0);
3979 else if (dialog->isVisibleView())
3980 dialog->checkStatus();
3987 Dialog * createDialog(GuiView & lv, string const & name);
3989 // will be replaced by a proper factory...
3990 Dialog * createGuiAbout(GuiView & lv);
3991 Dialog * createGuiBibtex(GuiView & lv);
3992 Dialog * createGuiChanges(GuiView & lv);
3993 Dialog * createGuiCharacter(GuiView & lv);
3994 Dialog * createGuiCitation(GuiView & lv);
3995 Dialog * createGuiCompare(GuiView & lv);
3996 Dialog * createGuiCompareHistory(GuiView & lv);
3997 Dialog * createGuiDelimiter(GuiView & lv);
3998 Dialog * createGuiDocument(GuiView & lv);
3999 Dialog * createGuiErrorList(GuiView & lv);
4000 Dialog * createGuiExternal(GuiView & lv);
4001 Dialog * createGuiGraphics(GuiView & lv);
4002 Dialog * createGuiInclude(GuiView & lv);
4003 Dialog * createGuiIndex(GuiView & lv);
4004 Dialog * createGuiListings(GuiView & lv);
4005 Dialog * createGuiLog(GuiView & lv);
4006 Dialog * createGuiMathMatrix(GuiView & lv);
4007 Dialog * createGuiNote(GuiView & lv);
4008 Dialog * createGuiParagraph(GuiView & lv);
4009 Dialog * createGuiPhantom(GuiView & lv);
4010 Dialog * createGuiPreferences(GuiView & lv);
4011 Dialog * createGuiPrint(GuiView & lv);
4012 Dialog * createGuiPrintindex(GuiView & lv);
4013 Dialog * createGuiRef(GuiView & lv);
4014 Dialog * createGuiSearch(GuiView & lv);
4015 Dialog * createGuiSearchAdv(GuiView & lv);
4016 Dialog * createGuiSendTo(GuiView & lv);
4017 Dialog * createGuiShowFile(GuiView & lv);
4018 Dialog * createGuiSpellchecker(GuiView & lv);
4019 Dialog * createGuiSymbols(GuiView & lv);
4020 Dialog * createGuiTabularCreate(GuiView & lv);
4021 Dialog * createGuiTexInfo(GuiView & lv);
4022 Dialog * createGuiToc(GuiView & lv);
4023 Dialog * createGuiThesaurus(GuiView & lv);
4024 Dialog * createGuiViewSource(GuiView & lv);
4025 Dialog * createGuiWrap(GuiView & lv);
4026 Dialog * createGuiProgressView(GuiView & lv);
4030 Dialog * GuiView::build(string const & name)
4032 LASSERT(isValidName(name), return 0);
4034 Dialog * dialog = createDialog(*this, name);
4038 if (name == "aboutlyx")
4039 return createGuiAbout(*this);
4040 if (name == "bibtex")
4041 return createGuiBibtex(*this);
4042 if (name == "changes")
4043 return createGuiChanges(*this);
4044 if (name == "character")
4045 return createGuiCharacter(*this);
4046 if (name == "citation")
4047 return createGuiCitation(*this);
4048 if (name == "compare")
4049 return createGuiCompare(*this);
4050 if (name == "comparehistory")
4051 return createGuiCompareHistory(*this);
4052 if (name == "document")
4053 return createGuiDocument(*this);
4054 if (name == "errorlist")
4055 return createGuiErrorList(*this);
4056 if (name == "external")
4057 return createGuiExternal(*this);
4059 return createGuiShowFile(*this);
4060 if (name == "findreplace")
4061 return createGuiSearch(*this);
4062 if (name == "findreplaceadv")
4063 return createGuiSearchAdv(*this);
4064 if (name == "graphics")
4065 return createGuiGraphics(*this);
4066 if (name == "include")
4067 return createGuiInclude(*this);
4068 if (name == "index")
4069 return createGuiIndex(*this);
4070 if (name == "index_print")
4071 return createGuiPrintindex(*this);
4072 if (name == "listings")
4073 return createGuiListings(*this);
4075 return createGuiLog(*this);
4076 if (name == "mathdelimiter")
4077 return createGuiDelimiter(*this);
4078 if (name == "mathmatrix")
4079 return createGuiMathMatrix(*this);
4081 return createGuiNote(*this);
4082 if (name == "paragraph")
4083 return createGuiParagraph(*this);
4084 if (name == "phantom")
4085 return createGuiPhantom(*this);
4086 if (name == "prefs")
4087 return createGuiPreferences(*this);
4088 if (name == "print")
4089 return createGuiPrint(*this);
4091 return createGuiRef(*this);
4092 if (name == "sendto")
4093 return createGuiSendTo(*this);
4094 if (name == "spellchecker")
4095 return createGuiSpellchecker(*this);
4096 if (name == "symbols")
4097 return createGuiSymbols(*this);
4098 if (name == "tabularcreate")
4099 return createGuiTabularCreate(*this);
4100 if (name == "texinfo")
4101 return createGuiTexInfo(*this);
4102 if (name == "thesaurus")
4103 return createGuiThesaurus(*this);
4105 return createGuiToc(*this);
4106 if (name == "view-source")
4107 return createGuiViewSource(*this);
4109 return createGuiWrap(*this);
4110 if (name == "progress")
4111 return createGuiProgressView(*this);
4117 } // namespace frontend
4120 #include "moc_GuiView.cpp"