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>
100 #include <QPixmapCache>
102 #include <QPushButton>
103 #include <QScrollBar>
105 #include <QShowEvent>
107 #include <QStackedWidget>
108 #include <QStatusBar>
109 #include <QtConcurrentRun>
117 #define EXPORT_in_THREAD 1
120 #include "support/bind.h"
124 #ifdef HAVE_SYS_TIME_H
125 # include <sys/time.h>
133 using namespace lyx::support;
137 using support::addExtension;
138 using support::changeExtension;
139 using support::removeExtension;
145 class BackgroundWidget : public QWidget
150 LYXERR(Debug::GUI, "show banner: " << lyxrc.show_banner);
151 if (!lyxrc.show_banner)
153 /// The text to be written on top of the pixmap
154 QString const text = lyx_version ?
155 qt_("version ") + lyx_version : qt_("unknown version");
156 splash_ = getPixmap("images/", "banner", "png");
158 QPainter pain(&splash_);
159 pain.setPen(QColor(0, 0, 0));
161 // The font used to display the version info
162 font.setStyleHint(QFont::SansSerif);
163 font.setWeight(QFont::Bold);
164 font.setPointSize(int(toqstr(lyxrc.font_sizes[FONT_SIZE_LARGE]).toDouble()));
166 pain.drawText(190, 225, text);
167 setFocusPolicy(Qt::StrongFocus);
170 void paintEvent(QPaintEvent *)
172 int x = (width() - splash_.width()) / 2;
173 int y = (height() - splash_.height()) / 2;
175 pain.drawPixmap(x, y, splash_);
178 void keyPressEvent(QKeyEvent * ev)
181 setKeySymbol(&sym, ev);
183 guiApp->processKeySym(sym, q_key_state(ev->modifiers()));
195 /// Toolbar store providing access to individual toolbars by name.
196 typedef map<string, GuiToolbar *> ToolbarMap;
198 typedef shared_ptr<Dialog> DialogPtr;
203 struct GuiView::GuiViewPrivate
205 GuiViewPrivate(GuiView * gv)
206 : gv_(gv), current_work_area_(0), current_main_work_area_(0),
207 layout_(0), autosave_timeout_(5000),
210 // hardcode here the platform specific icon size
211 smallIconSize = 16; // scaling problems
212 normalIconSize = 20; // ok, default if iconsize.png is missing
213 bigIconSize = 26; // better for some math icons
215 // if it exists, use width of iconsize.png as normal size
216 QString const dir = toqstr(addPath("images", lyxrc.icon_set));
217 FileName const fn = lyx::libFileSearch(dir, "iconsize.png");
219 QImage image(toqstr(fn.absFileName()));
220 if (image.width() < int(smallIconSize))
221 normalIconSize = smallIconSize;
222 else if (image.width() > int(bigIconSize))
223 normalIconSize = bigIconSize;
225 normalIconSize = image.width();
228 splitter_ = new QSplitter;
229 bg_widget_ = new BackgroundWidget;
230 stack_widget_ = new QStackedWidget;
231 stack_widget_->addWidget(bg_widget_);
232 stack_widget_->addWidget(splitter_);
235 // TODO cleanup, remove the singleton, handle multiple Windows?
236 progress_ = ProgressInterface::instance();
237 if (!dynamic_cast<GuiProgress*>(progress_)) {
238 progress_ = new GuiProgress; // TODO who deletes it
239 ProgressInterface::setInstance(progress_);
242 dynamic_cast<GuiProgress*>(progress_),
243 SIGNAL(updateStatusBarMessage(QString const&)),
244 gv, SLOT(updateStatusBarMessage(QString const&)));
246 dynamic_cast<GuiProgress*>(progress_),
247 SIGNAL(clearMessageText()),
248 gv, SLOT(clearMessageText()));
255 delete stack_widget_;
258 QMenu * toolBarPopup(GuiView * parent)
260 // FIXME: translation
261 QMenu * menu = new QMenu(parent);
262 QActionGroup * iconSizeGroup = new QActionGroup(parent);
264 QAction * smallIcons = new QAction(iconSizeGroup);
265 smallIcons->setText(qt_("Small-sized icons"));
266 smallIcons->setCheckable(true);
267 QObject::connect(smallIcons, SIGNAL(triggered()),
268 parent, SLOT(smallSizedIcons()));
269 menu->addAction(smallIcons);
271 QAction * normalIcons = new QAction(iconSizeGroup);
272 normalIcons->setText(qt_("Normal-sized icons"));
273 normalIcons->setCheckable(true);
274 QObject::connect(normalIcons, SIGNAL(triggered()),
275 parent, SLOT(normalSizedIcons()));
276 menu->addAction(normalIcons);
278 QAction * bigIcons = new QAction(iconSizeGroup);
279 bigIcons->setText(qt_("Big-sized icons"));
280 bigIcons->setCheckable(true);
281 QObject::connect(bigIcons, SIGNAL(triggered()),
282 parent, SLOT(bigSizedIcons()));
283 menu->addAction(bigIcons);
285 unsigned int cur = parent->iconSize().width();
286 if ( cur == parent->d.smallIconSize)
287 smallIcons->setChecked(true);
288 else if (cur == parent->d.normalIconSize)
289 normalIcons->setChecked(true);
290 else if (cur == parent->d.bigIconSize)
291 bigIcons->setChecked(true);
298 stack_widget_->setCurrentWidget(bg_widget_);
299 bg_widget_->setUpdatesEnabled(true);
300 bg_widget_->setFocus();
303 int tabWorkAreaCount()
305 return splitter_->count();
308 TabWorkArea * tabWorkArea(int i)
310 return dynamic_cast<TabWorkArea *>(splitter_->widget(i));
313 TabWorkArea * currentTabWorkArea()
315 int areas = tabWorkAreaCount();
317 // The first TabWorkArea is always the first one, if any.
318 return tabWorkArea(0);
320 for (int i = 0; i != areas; ++i) {
321 TabWorkArea * twa = tabWorkArea(i);
322 if (current_main_work_area_ == twa->currentWorkArea())
326 // None has the focus so we just take the first one.
327 return tabWorkArea(0);
330 int countWorkAreasOf(Buffer & buf)
332 int areas = tabWorkAreaCount();
334 for (int i = 0; i != areas; ++i) {
335 TabWorkArea * twa = tabWorkArea(i);
336 if (twa->workArea(buf))
342 void setPreviewFuture(QFuture<Buffer::ExportStatus> const & f)
344 if (processing_thread_watcher_.isRunning()) {
345 // we prefer to cancel this preview in order to keep a snappy
349 processing_thread_watcher_.setFuture(f);
354 GuiWorkArea * current_work_area_;
355 GuiWorkArea * current_main_work_area_;
356 QSplitter * splitter_;
357 QStackedWidget * stack_widget_;
358 BackgroundWidget * bg_widget_;
360 ToolbarMap toolbars_;
361 ProgressInterface* progress_;
362 /// The main layout box.
364 * \warning Don't Delete! The layout box is actually owned by
365 * whichever toolbar contains it. All the GuiView class needs is a
366 * means of accessing it.
368 * FIXME: replace that with a proper model so that we are not limited
369 * to only one dialog.
374 map<string, DialogPtr> dialogs_;
376 unsigned int smallIconSize;
377 unsigned int normalIconSize;
378 unsigned int bigIconSize;
380 QTimer statusbar_timer_;
381 /// auto-saving of buffers
382 Timeout autosave_timeout_;
383 /// flag against a race condition due to multiclicks, see bug #1119
387 TocModels toc_models_;
390 QFutureWatcher<docstring> autosave_watcher_;
391 QFutureWatcher<Buffer::ExportStatus> processing_thread_watcher_;
393 string last_export_format;
394 string processing_format;
396 static QSet<Buffer const *> busyBuffers;
397 static Buffer::ExportStatus previewAndDestroy(Buffer const * orig, Buffer * buffer, string const & format);
398 static Buffer::ExportStatus exportAndDestroy(Buffer const * orig, Buffer * buffer, string const & format);
399 static Buffer::ExportStatus compileAndDestroy(Buffer const * orig, Buffer * buffer, string const & format);
400 static docstring autosaveAndDestroy(Buffer const * orig, Buffer * buffer);
403 static Buffer::ExportStatus runAndDestroy(const T& func, Buffer const * orig, Buffer * buffer, string const & format);
405 // TODO syncFunc/previewFunc: use bind
406 bool asyncBufferProcessing(string const & argument,
407 Buffer const * used_buffer,
408 docstring const & msg,
409 Buffer::ExportStatus (*asyncFunc)(Buffer const *, Buffer *, string const &),
410 Buffer::ExportStatus (Buffer::*syncFunc)(string const &, bool) const,
411 Buffer::ExportStatus (Buffer::*previewFunc)(string const &) const);
413 QVector<GuiWorkArea*> guiWorkAreas();
416 QSet<Buffer const *> GuiView::GuiViewPrivate::busyBuffers;
419 GuiView::GuiView(int id)
420 : d(*new GuiViewPrivate(this)), id_(id), closing_(false), busy_(0)
422 // GuiToolbars *must* be initialised before the menu bar.
423 normalSizedIcons(); // at least on Mac the default is 32 otherwise, which is huge
426 // set ourself as the current view. This is needed for the menu bar
427 // filling, at least for the static special menu item on Mac. Otherwise
428 // they are greyed out.
429 guiApp->setCurrentView(this);
431 // Fill up the menu bar.
432 guiApp->menus().fillMenuBar(menuBar(), this, true);
434 setCentralWidget(d.stack_widget_);
436 // Start autosave timer
437 if (lyxrc.autosave) {
438 d.autosave_timeout_.timeout.connect(bind(&GuiView::autoSave, this));
439 d.autosave_timeout_.setTimeout(lyxrc.autosave * 1000);
440 d.autosave_timeout_.start();
442 connect(&d.statusbar_timer_, SIGNAL(timeout()),
443 this, SLOT(clearMessage()));
445 // We don't want to keep the window in memory if it is closed.
446 setAttribute(Qt::WA_DeleteOnClose, true);
448 #if (!defined(Q_WS_WIN) && !defined(Q_WS_MACX))
449 // QIcon::fromTheme was introduced in Qt 4.6
450 #if (QT_VERSION >= 0x040600)
451 // assign an icon to main form. We do not do it under Qt/Win or Qt/Mac,
452 // since the icon is provided in the application bundle. We use a themed
453 // version when available and use the bundled one as fallback.
454 setWindowIcon(QIcon::fromTheme("lyx", getPixmap("images/", "lyx", "png")));
456 setWindowIcon(getPixmap("images/", "lyx", "png"));
460 resetWindowTitleAndIconText();
462 // use tabbed dock area for multiple docks
463 // (such as "source" and "messages")
464 setDockOptions(QMainWindow::ForceTabbedDocks);
467 setAcceptDrops(true);
469 // add busy indicator to statusbar
470 QLabel * busylabel = new QLabel(statusBar());
471 statusBar()->addPermanentWidget(busylabel);
472 QString fn = toqstr(lyx::libFileSearch("images", "busy.gif").absFileName());
473 QMovie * busyanim = new QMovie(fn, QByteArray(), busylabel);
474 busylabel->setMovie(busyanim);
478 connect(&d.processing_thread_watcher_, SIGNAL(started()),
479 busylabel, SLOT(show()));
480 connect(&d.processing_thread_watcher_, SIGNAL(finished()),
481 busylabel, SLOT(hide()));
483 statusBar()->setSizeGripEnabled(true);
486 connect(&d.autosave_watcher_, SIGNAL(finished()), this,
487 SLOT(autoSaveThreadFinished()));
489 connect(&d.processing_thread_watcher_, SIGNAL(started()), this,
490 SLOT(processingThreadStarted()));
491 connect(&d.processing_thread_watcher_, SIGNAL(finished()), this,
492 SLOT(processingThreadFinished()));
494 connect(this, SIGNAL(triggerShowDialog(QString const &, QString const &, Inset *)),
495 SLOT(doShowDialog(QString const &, QString const &, Inset *)));
497 // Forbid too small unresizable window because it can happen
498 // with some window manager under X11.
499 setMinimumSize(300, 200);
501 if (lyxrc.allow_geometry_session) {
502 // Now take care of session management.
507 // no session handling, default to a sane size.
508 setGeometry(50, 50, 690, 510);
511 // clear session data if any.
513 settings.remove("views");
523 QVector<GuiWorkArea*> GuiView::GuiViewPrivate::guiWorkAreas()
525 QVector<GuiWorkArea*> areas;
526 for (int i = 0; i < tabWorkAreaCount(); i++) {
527 TabWorkArea* ta = tabWorkArea(i);
528 for (int u = 0; u < ta->count(); u++) {
529 areas << ta->workArea(u);
535 static void handleExportStatus(GuiView * view, Buffer::ExportStatus status,
536 string const & format)
538 docstring const fmt = formats.prettyName(format);
541 case Buffer::ExportSuccess:
542 msg = bformat(_("Successful export to format: %1$s"), fmt);
544 case Buffer::ExportCancel:
545 msg = _("Document export cancelled.");
547 case Buffer::ExportError:
548 case Buffer::ExportNoPathToFormat:
549 case Buffer::ExportTexPathHasSpaces:
550 case Buffer::ExportConverterError:
551 msg = bformat(_("Error while exporting format: %1$s"), fmt);
553 case Buffer::PreviewSuccess:
554 msg = bformat(_("Successful preview of format: %1$s"), fmt);
556 case Buffer::PreviewError:
557 msg = bformat(_("Error while previewing format: %1$s"), fmt);
564 void GuiView::processingThreadStarted()
569 void GuiView::processingThreadFinished()
571 QFutureWatcher<Buffer::ExportStatus> const * watcher =
572 static_cast<QFutureWatcher<Buffer::ExportStatus> const *>(sender());
574 Buffer::ExportStatus const status = watcher->result();
575 handleExportStatus(this, status, d.processing_format);
578 BufferView const * const bv = currentBufferView();
579 if (bv && !bv->buffer().errorList("Export").empty()) {
583 errors(d.last_export_format);
587 void GuiView::autoSaveThreadFinished()
589 QFutureWatcher<docstring> const * watcher =
590 static_cast<QFutureWatcher<docstring> const *>(sender());
591 message(watcher->result());
596 void GuiView::saveLayout() const
599 settings.beginGroup("views");
600 settings.beginGroup(QString::number(id_));
602 settings.setValue("pos", pos());
603 settings.setValue("size", size());
605 settings.setValue("geometry", saveGeometry());
607 settings.setValue("layout", saveState(0));
608 settings.setValue("icon_size", iconSize());
612 void GuiView::saveUISettings() const
614 // Save the toolbar private states
615 ToolbarMap::iterator end = d.toolbars_.end();
616 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
617 it->second->saveSession();
618 // Now take care of all other dialogs
619 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
620 for (; it!= d.dialogs_.end(); ++it)
621 it->second->saveSession();
625 bool GuiView::restoreLayout()
628 settings.beginGroup("views");
629 settings.beginGroup(QString::number(id_));
630 QString const icon_key = "icon_size";
631 if (!settings.contains(icon_key))
634 //code below is skipped when when ~/.config/LyX is (re)created
635 QSize icon_size = settings.value(icon_key).toSize();
636 // Check whether session size changed.
637 if (icon_size.width() != int(d.smallIconSize) &&
638 icon_size.width() != int(d.normalIconSize) &&
639 icon_size.width() != int(d.bigIconSize)) {
640 icon_size.setWidth(d.normalIconSize);
641 icon_size.setHeight(d.normalIconSize);
643 setIconSize(icon_size);
646 QPoint pos = settings.value("pos", QPoint(50, 50)).toPoint();
647 QSize size = settings.value("size", QSize(690, 510)).toSize();
651 // Work-around for bug #6034: the window ends up in an undetermined
652 // state when trying to restore a maximized window when it is
653 // already maximized.
654 if (!(windowState() & Qt::WindowMaximized))
655 if (!restoreGeometry(settings.value("geometry").toByteArray()))
656 setGeometry(50, 50, 690, 510);
658 // Make sure layout is correctly oriented.
659 setLayoutDirection(qApp->layoutDirection());
661 // Allow the toc and view-source dock widget to be restored if needed.
663 if ((dialog = findOrBuild("toc", true)))
664 // see bug 5082. At least setup title and enabled state.
665 // Visibility will be adjusted by restoreState below.
666 dialog->prepareView();
667 if ((dialog = findOrBuild("view-source", true)))
668 dialog->prepareView();
669 if ((dialog = findOrBuild("progress", true)))
670 dialog->prepareView();
671 if ((dialog = findOrBuild("findreplaceadv", true)))
672 dialog->prepareView();
674 if (!restoreState(settings.value("layout").toByteArray(), 0))
681 GuiToolbar * GuiView::toolbar(string const & name)
683 ToolbarMap::iterator it = d.toolbars_.find(name);
684 if (it != d.toolbars_.end())
687 LYXERR(Debug::GUI, "Toolbar::display: no toolbar named " << name);
692 void GuiView::constructToolbars()
694 ToolbarMap::iterator it = d.toolbars_.begin();
695 for (; it != d.toolbars_.end(); ++it)
699 // I don't like doing this here, but the standard toolbar
700 // destroys this object when it's destroyed itself (vfr)
701 d.layout_ = new LayoutBox(*this);
702 d.stack_widget_->addWidget(d.layout_);
703 d.layout_->move(0,0);
705 // extracts the toolbars from the backend
706 Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
707 Toolbars::Infos::iterator end = guiApp->toolbars().end();
708 for (; cit != end; ++cit)
709 d.toolbars_[cit->name] = new GuiToolbar(*cit, *this);
713 void GuiView::initToolbars()
715 // extracts the toolbars from the backend
716 Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
717 Toolbars::Infos::iterator end = guiApp->toolbars().end();
718 for (; cit != end; ++cit) {
719 GuiToolbar * tb = toolbar(cit->name);
722 int const visibility = guiApp->toolbars().defaultVisibility(cit->name);
723 bool newline = !(visibility & Toolbars::SAMEROW);
724 tb->setVisible(false);
725 tb->setVisibility(visibility);
727 if (visibility & Toolbars::TOP) {
729 addToolBarBreak(Qt::TopToolBarArea);
730 addToolBar(Qt::TopToolBarArea, tb);
733 if (visibility & Toolbars::BOTTOM) {
735 addToolBarBreak(Qt::BottomToolBarArea);
736 addToolBar(Qt::BottomToolBarArea, tb);
739 if (visibility & Toolbars::LEFT) {
741 addToolBarBreak(Qt::LeftToolBarArea);
742 addToolBar(Qt::LeftToolBarArea, tb);
745 if (visibility & Toolbars::RIGHT) {
747 addToolBarBreak(Qt::RightToolBarArea);
748 addToolBar(Qt::RightToolBarArea, tb);
751 if (visibility & Toolbars::ON)
752 tb->setVisible(true);
757 TocModels & GuiView::tocModels()
759 return d.toc_models_;
763 void GuiView::setFocus()
765 LYXERR(Debug::DEBUG, "GuiView::setFocus()" << this);
766 QMainWindow::setFocus();
770 void GuiView::focusInEvent(QFocusEvent * e)
772 LYXERR(Debug::DEBUG, "GuiView::focusInEvent()" << this);
773 QMainWindow::focusInEvent(e);
774 // Make sure guiApp points to the correct view.
775 guiApp->setCurrentView(this);
776 if (currentWorkArea())
777 currentWorkArea()->setFocus();
778 else if (currentMainWorkArea())
779 currentMainWorkArea()->setFocus();
781 d.bg_widget_->setFocus();
785 QMenu * GuiView::createPopupMenu()
787 return d.toolBarPopup(this);
791 void GuiView::showEvent(QShowEvent * e)
793 LYXERR(Debug::GUI, "Passed Geometry "
794 << size().height() << "x" << size().width()
795 << "+" << pos().x() << "+" << pos().y());
797 if (d.splitter_->count() == 0)
798 // No work area, switch to the background widget.
802 QMainWindow::showEvent(e);
806 bool GuiView::closeScheduled()
813 /** Destroy only all tabbed WorkAreas. Destruction of other WorkAreas
814 ** is responsibility of the container (e.g., dialog)
816 void GuiView::closeEvent(QCloseEvent * close_event)
818 LYXERR(Debug::DEBUG, "GuiView::closeEvent()");
820 if (!GuiViewPrivate::busyBuffers.isEmpty()) {
821 Alert::warning(_("Exit LyX"),
822 _("LyX could not be closed because documents are being processed by LyX."));
823 close_event->setAccepted(false);
827 // If the user pressed the x (so we didn't call closeView
828 // programmatically), we want to clear all existing entries.
830 theSession().lastOpened().clear();
835 // it can happen that this event arrives without selecting the view,
836 // e.g. when clicking the close button on a background window.
838 if (!closeWorkAreaAll()) {
840 close_event->ignore();
844 // Make sure that nothing will use this to be closed View.
845 guiApp->unregisterView(this);
847 if (isFullScreen()) {
848 // Switch off fullscreen before closing.
853 // Make sure the timer time out will not trigger a statusbar update.
854 d.statusbar_timer_.stop();
856 // Saving fullscreen requires additional tweaks in the toolbar code.
857 // It wouldn't also work under linux natively.
858 if (lyxrc.allow_geometry_session) {
863 close_event->accept();
867 void GuiView::dragEnterEvent(QDragEnterEvent * event)
869 if (event->mimeData()->hasUrls())
871 /// \todo Ask lyx-devel is this is enough:
872 /// if (event->mimeData()->hasFormat("text/plain"))
873 /// event->acceptProposedAction();
877 void GuiView::dropEvent(QDropEvent * event)
879 QList<QUrl> files = event->mimeData()->urls();
883 LYXERR(Debug::GUI, "GuiView::dropEvent: got URLs!");
884 for (int i = 0; i != files.size(); ++i) {
885 string const file = os::internal_path(fromqstr(
886 files.at(i).toLocalFile()));
890 string const ext = support::getExtension(file);
891 vector<const Format *> found_formats;
893 // Find all formats that have the correct extension.
894 vector<const Format *> const & import_formats
895 = theConverters().importableFormats();
896 vector<const Format *>::const_iterator it = import_formats.begin();
897 for (; it != import_formats.end(); ++it)
898 if ((*it)->hasExtension(ext))
899 found_formats.push_back(*it);
902 if (found_formats.size() >= 1) {
903 if (found_formats.size() > 1) {
904 //FIXME: show a dialog to choose the correct importable format
906 "Multiple importable formats found, selecting first");
908 string const arg = found_formats[0]->name() + " " + file;
909 cmd = FuncRequest(LFUN_BUFFER_IMPORT, arg);
912 //FIXME: do we have to explicitly check whether it's a lyx file?
914 "No formats found, trying to open it as a lyx file");
915 cmd = FuncRequest(LFUN_FILE_OPEN, file);
917 // add the functions to the queue
918 guiApp->addToFuncRequestQueue(cmd);
921 // now process the collected functions. We perform the events
922 // asynchronously. This prevents potential problems in case the
923 // BufferView is closed within an event.
924 guiApp->processFuncRequestQueueAsync();
928 void GuiView::message(docstring const & str)
930 if (ForkedProcess::iAmAChild())
933 // call is moved to GUI-thread by GuiProgress
934 d.progress_->appendMessage(toqstr(str));
938 void GuiView::clearMessageText()
940 message(docstring());
944 void GuiView::updateStatusBarMessage(QString const & str)
946 statusBar()->showMessage(str);
947 d.statusbar_timer_.stop();
948 d.statusbar_timer_.start(3000);
952 void GuiView::smallSizedIcons()
954 setIconSize(QSize(d.smallIconSize, d.smallIconSize));
958 void GuiView::normalSizedIcons()
960 setIconSize(QSize(d.normalIconSize, d.normalIconSize));
964 void GuiView::bigSizedIcons()
966 setIconSize(QSize(d.bigIconSize, d.bigIconSize));
970 void GuiView::clearMessage()
972 // FIXME: This code was introduced in r19643 to fix bug #4123. However,
973 // the hasFocus function mostly returns false, even if the focus is on
974 // a workarea in this view.
978 d.statusbar_timer_.stop();
982 void GuiView::updateWindowTitle(GuiWorkArea * wa)
984 if (wa != d.current_work_area_
985 || wa->bufferView().buffer().isInternal())
987 setWindowTitle(qt_("LyX: ") + wa->windowTitle());
988 setWindowIconText(wa->windowIconText());
992 void GuiView::on_currentWorkAreaChanged(GuiWorkArea * wa)
994 if (d.current_work_area_)
995 QObject::disconnect(d.current_work_area_, SIGNAL(busy(bool)),
996 this, SLOT(setBusy(bool)));
998 disconnectBufferView();
999 connectBufferView(wa->bufferView());
1000 connectBuffer(wa->bufferView().buffer());
1001 d.current_work_area_ = wa;
1002 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
1003 this, SLOT(updateWindowTitle(GuiWorkArea *)));
1004 QObject::connect(wa, SIGNAL(busy(bool)), this, SLOT(setBusy(bool)));
1005 updateWindowTitle(wa);
1009 // The document settings needs to be reinitialised.
1010 updateDialog("document", "");
1012 // Buffer-dependent dialogs must be updated. This is done here because
1013 // some dialogs require buffer()->text.
1018 void GuiView::on_lastWorkAreaRemoved()
1021 // We already are in a close event. Nothing more to do.
1024 if (d.splitter_->count() > 1)
1025 // We have a splitter so don't close anything.
1028 // Reset and updates the dialogs.
1029 d.toc_models_.reset(0);
1030 updateDialog("document", "");
1033 resetWindowTitleAndIconText();
1036 if (lyxrc.open_buffers_in_tabs)
1037 // Nothing more to do, the window should stay open.
1040 if (guiApp->viewIds().size() > 1) {
1046 // On Mac we also close the last window because the application stay
1047 // resident in memory. On other platforms we don't close the last
1048 // window because this would quit the application.
1054 void GuiView::updateStatusBar()
1056 // let the user see the explicit message
1057 if (d.statusbar_timer_.isActive())
1064 void GuiView::showMessage()
1066 QString msg = toqstr(theGuiApp()->viewStatusMessage());
1067 if (msg.isEmpty()) {
1068 BufferView const * bv = currentBufferView();
1070 msg = toqstr(bv->cursor().currentState());
1072 msg = qt_("Welcome to LyX!");
1074 statusBar()->showMessage(msg);
1078 bool GuiView::event(QEvent * e)
1082 // Useful debug code:
1083 //case QEvent::ActivationChange:
1084 //case QEvent::WindowDeactivate:
1085 //case QEvent::Paint:
1086 //case QEvent::Enter:
1087 //case QEvent::Leave:
1088 //case QEvent::HoverEnter:
1089 //case QEvent::HoverLeave:
1090 //case QEvent::HoverMove:
1091 //case QEvent::StatusTip:
1092 //case QEvent::DragEnter:
1093 //case QEvent::DragLeave:
1094 //case QEvent::Drop:
1097 case QEvent::WindowActivate: {
1098 GuiView * old_view = guiApp->currentView();
1099 if (this == old_view) {
1101 return QMainWindow::event(e);
1103 if (old_view && old_view->currentBufferView()) {
1104 // save current selection to the selection buffer to allow
1105 // middle-button paste in this window.
1106 cap::saveSelection(old_view->currentBufferView()->cursor());
1108 guiApp->setCurrentView(this);
1109 if (d.current_work_area_) {
1110 BufferView & bv = d.current_work_area_->bufferView();
1111 connectBufferView(bv);
1112 connectBuffer(bv.buffer());
1113 // The document structure, name and dialogs might have
1114 // changed in another view.
1116 // The document settings needs to be reinitialised.
1117 updateDialog("document", "");
1120 resetWindowTitleAndIconText();
1123 return QMainWindow::event(e);
1126 case QEvent::ShortcutOverride: {
1128 if (isFullScreen() && menuBar()->isHidden()) {
1129 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
1130 // FIXME: we should also try to detect special LyX shortcut such as
1131 // Alt-P and Alt-M. Right now there is a hack in
1132 // GuiWorkArea::processKeySym() that hides again the menubar for
1134 if (ke->modifiers() & Qt::AltModifier && ke->key() != Qt::Key_Alt) {
1136 return QMainWindow::event(e);
1139 return QMainWindow::event(e);
1143 return QMainWindow::event(e);
1147 void GuiView::resetWindowTitleAndIconText()
1149 setWindowTitle(qt_("LyX"));
1150 setWindowIconText(qt_("LyX"));
1153 bool GuiView::focusNextPrevChild(bool /*next*/)
1160 bool GuiView::busy() const
1166 void GuiView::setBusy(bool busy)
1168 bool const busy_before = busy_ > 0;
1169 busy ? ++busy_ : --busy_;
1170 if ((busy_ > 0) == busy_before)
1171 // busy state didn't change
1175 QApplication::setOverrideCursor(Qt::WaitCursor);
1178 QApplication::restoreOverrideCursor();
1183 GuiWorkArea * GuiView::workArea(int index)
1185 if (TabWorkArea * twa = d.currentTabWorkArea())
1186 if (index < twa->count())
1187 return dynamic_cast<GuiWorkArea *>(twa->widget(index));
1192 GuiWorkArea * GuiView::workArea(Buffer & buffer)
1194 if (currentWorkArea()
1195 && ¤tWorkArea()->bufferView().buffer() == &buffer)
1196 return (GuiWorkArea *) currentWorkArea();
1197 if (TabWorkArea * twa = d.currentTabWorkArea())
1198 return twa->workArea(buffer);
1203 GuiWorkArea * GuiView::addWorkArea(Buffer & buffer)
1205 // Automatically create a TabWorkArea if there are none yet.
1206 TabWorkArea * tab_widget = d.splitter_->count()
1207 ? d.currentTabWorkArea() : addTabWorkArea();
1208 return tab_widget->addWorkArea(buffer, *this);
1212 TabWorkArea * GuiView::addTabWorkArea()
1214 TabWorkArea * twa = new TabWorkArea;
1215 QObject::connect(twa, SIGNAL(currentWorkAreaChanged(GuiWorkArea *)),
1216 this, SLOT(on_currentWorkAreaChanged(GuiWorkArea *)));
1217 QObject::connect(twa, SIGNAL(lastWorkAreaRemoved()),
1218 this, SLOT(on_lastWorkAreaRemoved()));
1220 d.splitter_->addWidget(twa);
1221 d.stack_widget_->setCurrentWidget(d.splitter_);
1226 GuiWorkArea const * GuiView::currentWorkArea() const
1228 return d.current_work_area_;
1232 GuiWorkArea * GuiView::currentWorkArea()
1234 return d.current_work_area_;
1238 GuiWorkArea const * GuiView::currentMainWorkArea() const
1240 if (!d.currentTabWorkArea())
1242 return d.currentTabWorkArea()->currentWorkArea();
1246 GuiWorkArea * GuiView::currentMainWorkArea()
1248 if (!d.currentTabWorkArea())
1250 return d.currentTabWorkArea()->currentWorkArea();
1254 void GuiView::setCurrentWorkArea(GuiWorkArea * wa)
1256 LYXERR(Debug::DEBUG, "Setting current wa: " << wa << endl);
1258 d.current_work_area_ = 0;
1263 // FIXME: I've no clue why this is here and why it accesses
1264 // theGuiApp()->currentView, which might be 0 (bug 6464).
1265 // See also 27525 (vfr).
1266 if (theGuiApp()->currentView() == this
1267 && theGuiApp()->currentView()->currentWorkArea() == wa)
1270 if (currentBufferView())
1271 cap::saveSelection(currentBufferView()->cursor());
1273 theGuiApp()->setCurrentView(this);
1274 d.current_work_area_ = wa;
1276 // We need to reset this now, because it will need to be
1277 // right if the tabWorkArea gets reset in the for loop. We
1278 // will change it back if we aren't in that case.
1279 GuiWorkArea * const old_cmwa = d.current_main_work_area_;
1280 d.current_main_work_area_ = wa;
1282 for (int i = 0; i != d.splitter_->count(); ++i) {
1283 if (d.tabWorkArea(i)->setCurrentWorkArea(wa)) {
1284 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea()
1285 << ", Current main wa: " << currentMainWorkArea());
1290 d.current_main_work_area_ = old_cmwa;
1292 LYXERR(Debug::DEBUG, "This is not a tabbed wa");
1293 on_currentWorkAreaChanged(wa);
1294 BufferView & bv = wa->bufferView();
1295 bv.cursor().fixIfBroken();
1297 wa->setUpdatesEnabled(true);
1298 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() << ", Current main wa: " << currentMainWorkArea());
1302 void GuiView::removeWorkArea(GuiWorkArea * wa)
1304 LASSERT(wa, return);
1305 if (wa == d.current_work_area_) {
1307 disconnectBufferView();
1308 d.current_work_area_ = 0;
1309 d.current_main_work_area_ = 0;
1312 bool found_twa = false;
1313 for (int i = 0; i != d.splitter_->count(); ++i) {
1314 TabWorkArea * twa = d.tabWorkArea(i);
1315 if (twa->removeWorkArea(wa)) {
1316 // Found in this tab group, and deleted the GuiWorkArea.
1318 if (twa->count() != 0) {
1319 if (d.current_work_area_ == 0)
1320 // This means that we are closing the current GuiWorkArea, so
1321 // switch to the next GuiWorkArea in the found TabWorkArea.
1322 setCurrentWorkArea(twa->currentWorkArea());
1324 // No more WorkAreas in this tab group, so delete it.
1331 // It is not a tabbed work area (i.e., the search work area), so it
1332 // should be deleted by other means.
1333 LASSERT(found_twa, /* */);
1335 if (d.current_work_area_ == 0) {
1336 if (d.splitter_->count() != 0) {
1337 TabWorkArea * twa = d.currentTabWorkArea();
1338 setCurrentWorkArea(twa->currentWorkArea());
1340 // No more work areas, switch to the background widget.
1341 setCurrentWorkArea(0);
1347 LayoutBox * GuiView::getLayoutDialog() const
1353 void GuiView::updateLayoutList()
1356 d.layout_->updateContents(false);
1360 void GuiView::updateToolbars()
1362 ToolbarMap::iterator end = d.toolbars_.end();
1363 if (d.current_work_area_) {
1365 d.current_work_area_->bufferView().cursor().inMathed()
1366 && !d.current_work_area_->bufferView().cursor().inRegexped();
1368 lyx::getStatus(FuncRequest(LFUN_LAYOUT_TABULAR)).enabled();
1370 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).enabled() &&
1371 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).onOff(true);
1372 bool const mathmacrotemplate =
1373 lyx::getStatus(FuncRequest(LFUN_IN_MATHMACROTEMPLATE)).enabled();
1375 lyx::getStatus(FuncRequest(LFUN_IN_IPA)).enabled();
1377 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1378 it->second->update(math, table, review, mathmacrotemplate, ipa);
1380 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1381 it->second->update(false, false, false, false, false);
1385 void GuiView::setBuffer(Buffer * newBuffer)
1387 LYXERR(Debug::DEBUG, "Setting buffer: " << newBuffer << endl);
1388 LASSERT(newBuffer, return);
1390 GuiWorkArea * wa = workArea(*newBuffer);
1393 newBuffer->masterBuffer()->updateBuffer();
1395 wa = addWorkArea(*newBuffer);
1396 // scroll to the position when the BufferView was last closed
1397 if (lyxrc.use_lastfilepos) {
1398 LastFilePosSection::FilePos filepos =
1399 theSession().lastFilePos().load(newBuffer->fileName());
1400 wa->bufferView().moveToPosition(filepos.pit, filepos.pos, 0, 0);
1403 //Disconnect the old buffer...there's no new one.
1406 connectBuffer(*newBuffer);
1407 connectBufferView(wa->bufferView());
1408 setCurrentWorkArea(wa);
1412 void GuiView::connectBuffer(Buffer & buf)
1414 buf.setGuiDelegate(this);
1418 void GuiView::disconnectBuffer()
1420 if (d.current_work_area_)
1421 d.current_work_area_->bufferView().buffer().setGuiDelegate(0);
1425 void GuiView::connectBufferView(BufferView & bv)
1427 bv.setGuiDelegate(this);
1431 void GuiView::disconnectBufferView()
1433 if (d.current_work_area_)
1434 d.current_work_area_->bufferView().setGuiDelegate(0);
1438 void GuiView::errors(string const & error_type, bool from_master)
1440 BufferView const * const bv = currentBufferView();
1444 #if EXPORT_in_THREAD
1445 // We are called with from_master == false by default, so we
1446 // have to figure out whether that is the case or not.
1447 ErrorList & el = bv->buffer().errorList(error_type);
1449 el = bv->buffer().masterBuffer()->errorList(error_type);
1453 ErrorList const & el = from_master ?
1454 bv->buffer().masterBuffer()->errorList(error_type) :
1455 bv->buffer().errorList(error_type);
1461 string data = error_type;
1463 data = "from_master|" + error_type;
1464 showDialog("errorlist", data);
1468 void GuiView::updateTocItem(string const & type, DocIterator const & dit)
1470 d.toc_models_.updateItem(toqstr(type), dit);
1474 void GuiView::structureChanged()
1476 d.toc_models_.reset(documentBufferView());
1477 // Navigator needs more than a simple update in this case. It needs to be
1479 updateDialog("toc", "");
1483 void GuiView::updateDialog(string const & name, string const & data)
1485 if (!isDialogVisible(name))
1488 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
1489 if (it == d.dialogs_.end())
1492 Dialog * const dialog = it->second.get();
1493 if (dialog->isVisibleView())
1494 dialog->initialiseParams(data);
1498 BufferView * GuiView::documentBufferView()
1500 return currentMainWorkArea()
1501 ? ¤tMainWorkArea()->bufferView()
1506 BufferView const * GuiView::documentBufferView() const
1508 return currentMainWorkArea()
1509 ? ¤tMainWorkArea()->bufferView()
1514 BufferView * GuiView::currentBufferView()
1516 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1520 BufferView const * GuiView::currentBufferView() const
1522 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1526 docstring GuiView::GuiViewPrivate::autosaveAndDestroy(
1527 Buffer const * orig, Buffer * clone)
1529 bool const success = clone->autoSave();
1531 busyBuffers.remove(orig);
1533 ? _("Automatic save done.")
1534 : _("Automatic save failed!");
1538 void GuiView::autoSave()
1540 LYXERR(Debug::INFO, "Running autoSave()");
1542 Buffer * buffer = documentBufferView()
1543 ? &documentBufferView()->buffer() : 0;
1545 resetAutosaveTimers();
1549 GuiViewPrivate::busyBuffers.insert(buffer);
1550 QFuture<docstring> f = QtConcurrent::run(GuiViewPrivate::autosaveAndDestroy,
1551 buffer, buffer->cloneBufferOnly());
1552 d.autosave_watcher_.setFuture(f);
1553 resetAutosaveTimers();
1557 void GuiView::resetAutosaveTimers()
1560 d.autosave_timeout_.restart();
1564 bool GuiView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1567 Buffer * buf = currentBufferView()
1568 ? ¤tBufferView()->buffer() : 0;
1569 Buffer * doc_buffer = documentBufferView()
1570 ? &(documentBufferView()->buffer()) : 0;
1572 // Check whether we need a buffer
1573 if (!lyxaction.funcHasFlag(cmd.action(), LyXAction::NoBuffer) && !buf) {
1574 // no, exit directly
1575 flag.message(from_utf8(N_("Command not allowed with"
1576 "out any document open")));
1577 flag.setEnabled(false);
1581 if (cmd.origin() == FuncRequest::TOC) {
1582 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
1583 if (!toc || !toc->getStatus(documentBufferView()->cursor(), cmd, flag))
1584 flag.setEnabled(false);
1588 switch(cmd.action()) {
1589 case LFUN_BUFFER_IMPORT:
1592 case LFUN_MASTER_BUFFER_UPDATE:
1593 case LFUN_MASTER_BUFFER_VIEW:
1594 enable = doc_buffer && doc_buffer->parent() != 0
1595 && !d.processing_thread_watcher_.isRunning();
1598 case LFUN_BUFFER_UPDATE:
1599 case LFUN_BUFFER_VIEW: {
1600 if (!doc_buffer || d.processing_thread_watcher_.isRunning()) {
1604 string format = to_utf8(cmd.argument());
1605 if (cmd.argument().empty())
1606 format = doc_buffer->params().getDefaultOutputFormat();
1607 enable = doc_buffer->params().isExportableFormat(format);
1611 case LFUN_BUFFER_RELOAD:
1612 enable = doc_buffer && !doc_buffer->isUnnamed()
1613 && doc_buffer->fileName().exists()
1614 && (!doc_buffer->isClean()
1615 || doc_buffer->isExternallyModified(Buffer::timestamp_method));
1618 case LFUN_BUFFER_CHILD_OPEN:
1619 enable = doc_buffer;
1622 case LFUN_BUFFER_WRITE:
1623 enable = doc_buffer && (doc_buffer->isUnnamed() || !doc_buffer->isClean());
1626 //FIXME: This LFUN should be moved to GuiApplication.
1627 case LFUN_BUFFER_WRITE_ALL: {
1628 // We enable the command only if there are some modified buffers
1629 Buffer * first = theBufferList().first();
1634 // We cannot use a for loop as the buffer list is a cycle.
1636 if (!b->isClean()) {
1640 b = theBufferList().next(b);
1641 } while (b != first);
1645 case LFUN_BUFFER_WRITE_AS:
1646 case LFUN_BUFFER_EXPORT_AS:
1647 enable = doc_buffer;
1650 case LFUN_BUFFER_CLOSE:
1651 case LFUN_VIEW_CLOSE:
1652 enable = doc_buffer;
1655 case LFUN_BUFFER_CLOSE_ALL:
1656 enable = theBufferList().last() != theBufferList().first();
1659 case LFUN_VIEW_SPLIT:
1660 if (cmd.getArg(0) == "vertical")
1661 enable = doc_buffer && (d.splitter_->count() == 1 ||
1662 d.splitter_->orientation() == Qt::Vertical);
1664 enable = doc_buffer && (d.splitter_->count() == 1 ||
1665 d.splitter_->orientation() == Qt::Horizontal);
1668 case LFUN_TAB_GROUP_CLOSE:
1669 enable = d.tabWorkAreaCount() > 1;
1672 case LFUN_TOOLBAR_TOGGLE: {
1673 string const name = cmd.getArg(0);
1674 if (GuiToolbar * t = toolbar(name))
1675 flag.setOnOff(t->isVisible());
1678 docstring const msg =
1679 bformat(_("Unknown toolbar \"%1$s\""), from_utf8(name));
1685 case LFUN_DROP_LAYOUTS_CHOICE:
1689 case LFUN_UI_TOGGLE:
1690 flag.setOnOff(isFullScreen());
1693 case LFUN_DIALOG_DISCONNECT_INSET:
1696 case LFUN_DIALOG_HIDE:
1697 // FIXME: should we check if the dialog is shown?
1700 case LFUN_DIALOG_TOGGLE:
1701 flag.setOnOff(isDialogVisible(cmd.getArg(0)));
1702 // fall through to set "enable"
1703 case LFUN_DIALOG_SHOW: {
1704 string const name = cmd.getArg(0);
1706 enable = name == "aboutlyx"
1707 || name == "file" //FIXME: should be removed.
1709 || name == "texinfo"
1710 || name == "progress"
1711 || name == "compare";
1712 else if (name == "print")
1713 enable = doc_buffer->params().isExportable("dvi")
1714 && lyxrc.print_command != "none";
1715 else if (name == "character" || name == "symbols") {
1716 if (!buf || buf->isReadonly())
1719 Cursor const & cur = currentBufferView()->cursor();
1720 enable = !(cur.inTexted() && cur.paragraph().isPassThru());
1723 else if (name == "latexlog")
1724 enable = FileName(doc_buffer->logName()).isReadableFile();
1725 else if (name == "spellchecker")
1726 enable = theSpellChecker()
1727 && !doc_buffer->isReadonly()
1728 && !doc_buffer->text().empty();
1729 else if (name == "vclog")
1730 enable = doc_buffer->lyxvc().inUse();
1734 case LFUN_DIALOG_UPDATE: {
1735 string const name = cmd.getArg(0);
1737 enable = name == "prefs";
1741 case LFUN_COMMAND_EXECUTE:
1743 case LFUN_MENU_OPEN:
1744 // Nothing to check.
1747 case LFUN_COMPLETION_INLINE:
1748 if (!d.current_work_area_
1749 || !d.current_work_area_->completer().inlinePossible(
1750 currentBufferView()->cursor()))
1754 case LFUN_COMPLETION_POPUP:
1755 if (!d.current_work_area_
1756 || !d.current_work_area_->completer().popupPossible(
1757 currentBufferView()->cursor()))
1761 case LFUN_COMPLETION_COMPLETE:
1762 if (!d.current_work_area_
1763 || !d.current_work_area_->completer().inlinePossible(
1764 currentBufferView()->cursor()))
1768 case LFUN_COMPLETION_ACCEPT:
1769 if (!d.current_work_area_
1770 || (!d.current_work_area_->completer().popupVisible()
1771 && !d.current_work_area_->completer().inlineVisible()
1772 && !d.current_work_area_->completer().completionAvailable()))
1776 case LFUN_COMPLETION_CANCEL:
1777 if (!d.current_work_area_
1778 || (!d.current_work_area_->completer().popupVisible()
1779 && !d.current_work_area_->completer().inlineVisible()))
1783 case LFUN_BUFFER_ZOOM_OUT:
1784 enable = doc_buffer && lyxrc.zoom > 10;
1787 case LFUN_BUFFER_ZOOM_IN:
1788 enable = doc_buffer;
1791 case LFUN_BUFFER_NEXT:
1792 case LFUN_BUFFER_PREVIOUS:
1793 // FIXME: should we check is there is an previous or next buffer?
1795 case LFUN_BUFFER_SWITCH:
1796 // toggle on the current buffer, but do not toggle off
1797 // the other ones (is that a good idea?)
1799 && to_utf8(cmd.argument()) == doc_buffer->absFileName())
1800 flag.setOnOff(true);
1803 case LFUN_VC_REGISTER:
1804 enable = doc_buffer && !doc_buffer->lyxvc().inUse();
1806 case LFUN_VC_CHECK_IN:
1807 enable = doc_buffer && doc_buffer->lyxvc().checkInEnabled();
1809 case LFUN_VC_CHECK_OUT:
1810 enable = doc_buffer && doc_buffer->lyxvc().checkOutEnabled();
1812 case LFUN_VC_LOCKING_TOGGLE:
1813 enable = doc_buffer && !doc_buffer->isReadonly()
1814 && doc_buffer->lyxvc().lockingToggleEnabled();
1815 flag.setOnOff(enable && doc_buffer->lyxvc().locking());
1817 case LFUN_VC_REVERT:
1818 enable = doc_buffer && doc_buffer->lyxvc().inUse() && !doc_buffer->isReadonly();
1820 case LFUN_VC_UNDO_LAST:
1821 enable = doc_buffer && doc_buffer->lyxvc().undoLastEnabled();
1823 case LFUN_VC_REPO_UPDATE:
1824 enable = doc_buffer && doc_buffer->lyxvc().repoUpdateEnabled();
1826 case LFUN_VC_COMMAND: {
1827 if (cmd.argument().empty())
1829 if (!doc_buffer && contains(cmd.getArg(0), 'D'))
1833 case LFUN_VC_COMPARE:
1834 enable = doc_buffer && doc_buffer->lyxvc().prepareFileRevisionEnabled();
1837 case LFUN_SERVER_GOTO_FILE_ROW:
1839 case LFUN_FORWARD_SEARCH:
1840 enable = !(lyxrc.forward_search_dvi.empty() && lyxrc.forward_search_pdf.empty());
1843 case LFUN_FILE_INSERT_PLAINTEXT:
1844 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
1845 enable = documentBufferView() && documentBufferView()->cursor().inTexted();
1853 flag.setEnabled(false);
1859 static FileName selectTemplateFile()
1861 FileDialog dlg(qt_("Select template file"));
1862 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1863 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
1865 FileDialog::Result result = dlg.open(toqstr(lyxrc.template_path),
1866 QStringList(qt_("LyX Documents (*.lyx)")));
1868 if (result.first == FileDialog::Later)
1870 if (result.second.isEmpty())
1872 return FileName(fromqstr(result.second));
1876 Buffer * GuiView::loadDocument(FileName const & filename, bool tolastfiles)
1880 Buffer * newBuffer = 0;
1882 newBuffer = checkAndLoadLyXFile(filename);
1883 } catch (ExceptionMessage const & e) {
1890 message(_("Document not loaded."));
1894 setBuffer(newBuffer);
1895 newBuffer->errors("Parse");
1898 theSession().lastFiles().add(filename);
1904 void GuiView::openDocument(string const & fname)
1906 string initpath = lyxrc.document_path;
1908 if (documentBufferView()) {
1909 string const trypath = documentBufferView()->buffer().filePath();
1910 // If directory is writeable, use this as default.
1911 if (FileName(trypath).isDirWritable())
1917 if (fname.empty()) {
1918 FileDialog dlg(qt_("Select document to open"), LFUN_FILE_OPEN);
1919 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1920 dlg.setButton2(qt_("Examples|#E#e"),
1921 toqstr(addPath(package().system_support().absFileName(), "examples")));
1923 QStringList filter(qt_("LyX Documents (*.lyx)"));
1924 filter << qt_("LyX-1.3.x Documents (*.lyx13)")
1925 << qt_("LyX-1.4.x Documents (*.lyx14)")
1926 << qt_("LyX-1.5.x Documents (*.lyx15)")
1927 << qt_("LyX-1.6.x Documents (*.lyx16)");
1928 FileDialog::Result result =
1929 dlg.open(toqstr(initpath), filter);
1931 if (result.first == FileDialog::Later)
1934 filename = fromqstr(result.second);
1936 // check selected filename
1937 if (filename.empty()) {
1938 message(_("Canceled."));
1944 // get absolute path of file and add ".lyx" to the filename if
1946 FileName const fullname =
1947 fileSearch(string(), filename, "lyx", support::may_not_exist);
1948 if (!fullname.empty())
1949 filename = fullname.absFileName();
1951 if (!fullname.onlyPath().isDirectory()) {
1952 Alert::warning(_("Invalid filename"),
1953 bformat(_("The directory in the given path\n%1$s\ndoes not exist."),
1954 from_utf8(fullname.absFileName())));
1958 // if the file doesn't exist and isn't already open (bug 6645),
1959 // let the user create one
1960 if (!fullname.exists() && !theBufferList().exists(fullname) &&
1961 !LyXVC::file_not_found_hook(fullname)) {
1962 // the user specifically chose this name. Believe him.
1963 Buffer * const b = newFile(filename, string(), true);
1969 docstring const disp_fn = makeDisplayPath(filename);
1970 message(bformat(_("Opening document %1$s..."), disp_fn));
1973 Buffer * buf = loadDocument(fullname);
1975 str2 = bformat(_("Document %1$s opened."), disp_fn);
1976 if (buf->lyxvc().inUse())
1977 str2 += " " + from_utf8(buf->lyxvc().versionString()) +
1978 " " + _("Version control detected.");
1980 str2 = bformat(_("Could not open document %1$s"), disp_fn);
1985 // FIXME: clean that
1986 static bool import(GuiView * lv, FileName const & filename,
1987 string const & format, ErrorList & errorList)
1989 FileName const lyxfile(support::changeExtension(filename.absFileName(), ".lyx"));
1991 string loader_format;
1992 vector<string> loaders = theConverters().loaders();
1993 if (find(loaders.begin(), loaders.end(), format) == loaders.end()) {
1994 vector<string>::const_iterator it = loaders.begin();
1995 vector<string>::const_iterator en = loaders.end();
1996 for (; it != en; ++it) {
1997 if (!theConverters().isReachable(format, *it))
2000 string const tofile =
2001 support::changeExtension(filename.absFileName(),
2002 formats.extension(*it));
2003 if (!theConverters().convert(0, filename, FileName(tofile),
2004 filename, format, *it, errorList))
2006 loader_format = *it;
2009 if (loader_format.empty()) {
2010 frontend::Alert::error(_("Couldn't import file"),
2011 bformat(_("No information for importing the format %1$s."),
2012 formats.prettyName(format)));
2016 loader_format = format;
2018 if (loader_format == "lyx") {
2019 Buffer * buf = lv->loadDocument(lyxfile);
2023 Buffer * const b = newFile(lyxfile.absFileName(), string(), true);
2027 bool as_paragraphs = loader_format == "textparagraph";
2028 string filename2 = (loader_format == format) ? filename.absFileName()
2029 : support::changeExtension(filename.absFileName(),
2030 formats.extension(loader_format));
2031 lv->currentBufferView()->insertPlaintextFile(FileName(filename2),
2033 guiApp->setCurrentView(lv);
2034 lyx::dispatch(FuncRequest(LFUN_MARK_OFF));
2041 void GuiView::importDocument(string const & argument)
2044 string filename = split(argument, format, ' ');
2046 LYXERR(Debug::INFO, format << " file: " << filename);
2048 // need user interaction
2049 if (filename.empty()) {
2050 string initpath = lyxrc.document_path;
2051 if (documentBufferView()) {
2052 string const trypath = documentBufferView()->buffer().filePath();
2053 // If directory is writeable, use this as default.
2054 if (FileName(trypath).isDirWritable())
2058 docstring const text = bformat(_("Select %1$s file to import"),
2059 formats.prettyName(format));
2061 FileDialog dlg(toqstr(text), LFUN_BUFFER_IMPORT);
2062 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2063 dlg.setButton2(qt_("Examples|#E#e"),
2064 toqstr(addPath(package().system_support().absFileName(), "examples")));
2066 docstring filter = formats.prettyName(format);
2069 filter += from_utf8(formats.extensions(format));
2072 FileDialog::Result result =
2073 dlg.open(toqstr(initpath), fileFilters(toqstr(filter)));
2075 if (result.first == FileDialog::Later)
2078 filename = fromqstr(result.second);
2080 // check selected filename
2081 if (filename.empty())
2082 message(_("Canceled."));
2085 if (filename.empty())
2088 // get absolute path of file
2089 FileName const fullname(support::makeAbsPath(filename));
2091 FileName const lyxfile(support::changeExtension(fullname.absFileName(), ".lyx"));
2093 // Check if the document already is open
2094 Buffer * buf = theBufferList().getBuffer(lyxfile);
2097 if (!closeBuffer()) {
2098 message(_("Canceled."));
2103 docstring const displaypath = makeDisplayPath(lyxfile.absFileName(), 30);
2105 // if the file exists already, and we didn't do
2106 // -i lyx thefile.lyx, warn
2107 if (lyxfile.exists() && fullname != lyxfile) {
2109 docstring text = bformat(_("The document %1$s already exists.\n\n"
2110 "Do you want to overwrite that document?"), displaypath);
2111 int const ret = Alert::prompt(_("Overwrite document?"),
2112 text, 0, 1, _("&Overwrite"), _("&Cancel"));
2115 message(_("Canceled."));
2120 message(bformat(_("Importing %1$s..."), displaypath));
2121 ErrorList errorList;
2122 if (import(this, fullname, format, errorList))
2123 message(_("imported."));
2125 message(_("file not imported!"));
2127 // FIXME (Abdel 12/08/06): Is there a need to display the error list here?
2131 void GuiView::newDocument(string const & filename, bool from_template)
2133 FileName initpath(lyxrc.document_path);
2134 if (documentBufferView()) {
2135 FileName const trypath(documentBufferView()->buffer().filePath());
2136 // If directory is writeable, use this as default.
2137 if (trypath.isDirWritable())
2141 string templatefile;
2142 if (from_template) {
2143 templatefile = selectTemplateFile().absFileName();
2144 if (templatefile.empty())
2149 if (filename.empty())
2150 b = newUnnamedFile(initpath, to_utf8(_("newfile")), templatefile);
2152 b = newFile(filename, templatefile, true);
2157 // If no new document could be created, it is unsure
2158 // whether there is a valid BufferView.
2159 if (currentBufferView())
2160 // Ensure the cursor is correctly positioned on screen.
2161 currentBufferView()->showCursor();
2165 void GuiView::insertLyXFile(docstring const & fname)
2167 BufferView * bv = documentBufferView();
2172 FileName filename(to_utf8(fname));
2173 if (filename.empty()) {
2174 // Launch a file browser
2176 string initpath = lyxrc.document_path;
2177 string const trypath = bv->buffer().filePath();
2178 // If directory is writeable, use this as default.
2179 if (FileName(trypath).isDirWritable())
2183 FileDialog dlg(qt_("Select LyX document to insert"), LFUN_FILE_INSERT);
2184 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2185 dlg.setButton2(qt_("Examples|#E#e"),
2186 toqstr(addPath(package().system_support().absFileName(),
2189 FileDialog::Result result = dlg.open(toqstr(initpath),
2190 QStringList(qt_("LyX Documents (*.lyx)")));
2192 if (result.first == FileDialog::Later)
2196 filename.set(fromqstr(result.second));
2198 // check selected filename
2199 if (filename.empty()) {
2200 // emit message signal.
2201 message(_("Canceled."));
2206 bv->insertLyXFile(filename);
2207 bv->buffer().errors("Parse");
2211 bool GuiView::renameBuffer(Buffer & b, docstring const & newname)
2213 FileName fname = b.fileName();
2214 FileName const oldname = fname;
2216 if (!newname.empty()) {
2218 fname = support::makeAbsPath(to_utf8(newname), oldname.onlyPath().absFileName());
2220 // Switch to this Buffer.
2223 // No argument? Ask user through dialog.
2225 FileDialog dlg(qt_("Choose a filename to save document as"),
2226 LFUN_BUFFER_WRITE_AS);
2227 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2228 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
2230 if (!isLyXFileName(fname.absFileName()))
2231 fname.changeExtension(".lyx");
2233 FileDialog::Result result =
2234 dlg.save(toqstr(fname.onlyPath().absFileName()),
2235 QStringList(qt_("LyX Documents (*.lyx)")),
2236 toqstr(fname.onlyFileName()));
2238 if (result.first == FileDialog::Later)
2241 fname.set(fromqstr(result.second));
2246 if (!isLyXFileName(fname.absFileName()))
2247 fname.changeExtension(".lyx");
2250 // fname is now the new Buffer location.
2252 // if there is already a Buffer open with this name, we do not want
2253 // to have another one. (the second test makes sure we're not just
2254 // trying to overwrite ourselves, which is fine.)
2255 if (theBufferList().exists(fname) && fname != oldname
2256 && theBufferList().getBuffer(fname) != &b) {
2257 docstring const text =
2258 bformat(_("The file\n%1$s\nis already open in your current session.\n"
2259 "Please close it before attempting to overwrite it.\n"
2260 "Do you want to choose a new filename?"),
2261 from_utf8(fname.absFileName()));
2262 int const ret = Alert::prompt(_("Chosen File Already Open"),
2263 text, 0, 1, _("&Rename"), _("&Cancel"));
2265 case 0: return renameBuffer(b, docstring());
2266 case 1: return false;
2271 if (FileName(fname).exists()) {
2272 docstring const file = makeDisplayPath(fname.absFileName(), 30);
2273 docstring const text = bformat(_("The document %1$s already "
2274 "exists.\n\nDo you want to "
2275 "overwrite that document?"),
2277 int const ret = Alert::prompt(_("Overwrite document?"),
2278 text, 0, 2, _("&Overwrite"), _("&Rename"), _("&Cancel"));
2281 case 1: return renameBuffer(b, docstring());
2282 case 2: return false;
2286 bool const saved = saveBuffer(b, fname);
2293 struct PrettyNameComparator
2295 bool operator()(Format const *first, Format const *second) const {
2296 return compare_ascii_no_case(first->prettyname(), second->prettyname()) <= 0;
2301 bool GuiView::exportBufferAs(Buffer & b)
2303 FileName fname = b.fileName();
2305 FileDialog dlg(qt_("Choose a filename to export the document as"));
2306 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2309 types << "Any supported format (*.*)";
2310 Formats::const_iterator it = formats.begin();
2311 vector<Format const *> export_formats;
2312 for (; it != formats.end(); ++it)
2313 if (it->documentFormat() && it->inExportMenu())
2314 export_formats.push_back(&(*it));
2315 PrettyNameComparator cmp;
2316 sort(export_formats.begin(), export_formats.end(), cmp);
2317 vector<Format const *>::const_iterator fit = export_formats.begin();
2318 for (; fit != export_formats.end(); ++fit)
2319 types << toqstr((*fit)->prettyname() + " (*." + (*fit)->extension() + ")");
2321 FileDialog::Result result =
2322 dlg.save(toqstr(fname.onlyPath().absFileName()),
2324 toqstr(fname.onlyFileName()),
2326 if (result.first != FileDialog::Chosen)
2329 string s = fromqstr(filter);
2330 size_t pos = s.find(" (*.");
2331 LASSERT(pos != string::npos, /**/);
2332 string fmt_prettyname = s.substr(0, pos);
2334 fname.set(fromqstr(result.second));
2335 if (fmt_prettyname == "Any supported format")
2336 fmt_name = formats.getFormatFromExtension(fname.extension());
2338 fmt_name = formats.getFormatFromPrettyName(fmt_prettyname);
2339 LYXERR(Debug::FILES, "fmt_prettyname=" << fmt_prettyname
2340 << ", fmt_name=" << fmt_name << ", fname=" << fname.absFileName());
2342 if (fmt_name.empty() || fname.empty())
2345 // fname is now the new Buffer location.
2346 if (FileName(fname).exists()) {
2347 docstring const file = makeDisplayPath(fname.absFileName(), 30);
2348 docstring text = bformat(_("The document %1$s already "
2349 "exists.\n\nDo you want to "
2350 "overwrite that document?"),
2352 int const ret = Alert::prompt(_("Overwrite document?"),
2353 text, 0, 2, _("&Overwrite"), _("&Rename"), _("&Cancel"));
2356 case 1: return exportBufferAs(b);
2357 case 2: return false;
2361 FuncRequest cmd(LFUN_BUFFER_EXPORT, fmt_name + " " + fname.absFileName());
2364 return dr.dispatched();
2368 bool GuiView::saveBuffer(Buffer & b) {
2369 return saveBuffer(b, FileName());
2373 bool GuiView::saveBuffer(Buffer & b, FileName const & fn)
2375 if (workArea(b) && workArea(b)->inDialogMode())
2378 if (fn.empty() && b.isUnnamed())
2379 return renameBuffer(b, docstring());
2385 success = b.saveAs(fn);
2388 theSession().lastFiles().add(b.fileName());
2392 // Switch to this Buffer.
2395 // FIXME: we don't tell the user *WHY* the save failed !!
2396 docstring const file = makeDisplayPath(b.absFileName(), 30);
2397 docstring text = bformat(_("The document %1$s could not be saved.\n\n"
2398 "Do you want to rename the document and "
2399 "try again?"), file);
2400 int const ret = Alert::prompt(_("Rename and save?"),
2401 text, 0, 2, _("&Rename"), _("&Retry"), _("&Cancel"));
2404 if (!renameBuffer(b, docstring()))
2413 return saveBuffer(b);
2417 bool GuiView::hideWorkArea(GuiWorkArea * wa)
2419 return closeWorkArea(wa, false);
2423 // We only want to close the buffer if it is not visible in other workareas
2424 // of the same view, nor in other views, and if this is not a child
2425 bool GuiView::closeWorkArea(GuiWorkArea * wa)
2427 Buffer & buf = wa->bufferView().buffer();
2429 bool last_wa = d.countWorkAreasOf(buf) == 1
2430 && !inOtherView(buf) && !buf.parent();
2432 bool close_buffer = last_wa;
2435 if (lyxrc.close_buffer_with_last_view == "yes")
2437 else if (lyxrc.close_buffer_with_last_view == "no")
2438 close_buffer = false;
2441 if (buf.isUnnamed())
2442 file = from_utf8(buf.fileName().onlyFileName());
2444 file = buf.fileName().displayName(30);
2445 docstring const text = bformat(
2446 _("Last view on document %1$s is being closed.\n"
2447 "Would you like to close or hide the document?\n"
2449 "Hidden documents can be displayed back through\n"
2450 "the menu: View->Hidden->...\n"
2452 "To remove this question, set your preference in:\n"
2453 " Tools->Preferences->Look&Feel->UserInterface\n"
2455 int ret = Alert::prompt(_("Close or hide document?"),
2456 text, 0, 1, _("&Close"), _("&Hide"));
2457 close_buffer = (ret == 0);
2461 return closeWorkArea(wa, close_buffer);
2465 bool GuiView::closeBuffer()
2467 GuiWorkArea * wa = currentMainWorkArea();
2468 setCurrentWorkArea(wa);
2469 Buffer & buf = wa->bufferView().buffer();
2470 return wa && closeWorkArea(wa, !buf.parent());
2474 void GuiView::writeSession() const {
2475 GuiWorkArea const * active_wa = currentMainWorkArea();
2476 for (int i = 0; i < d.splitter_->count(); ++i) {
2477 TabWorkArea * twa = d.tabWorkArea(i);
2478 for (int j = 0; j < twa->count(); ++j) {
2479 GuiWorkArea * wa = static_cast<GuiWorkArea *>(twa->widget(j));
2480 Buffer & buf = wa->bufferView().buffer();
2481 theSession().lastOpened().add(buf.fileName(), wa == active_wa);
2487 bool GuiView::closeBufferAll()
2489 // Close the workareas in all other views
2490 QList<int> const ids = guiApp->viewIds();
2491 for (int i = 0; i != ids.size(); ++i) {
2492 if (id_ != ids[i] && !guiApp->view(ids[i]).closeWorkAreaAll())
2496 // Close our own workareas
2497 if (!closeWorkAreaAll())
2500 // Now close the hidden buffers. We prevent hidden buffers from being
2501 // dirty, so we can just close them.
2502 theBufferList().closeAll();
2507 bool GuiView::closeWorkAreaAll()
2509 setCurrentWorkArea(currentMainWorkArea());
2511 // We might be in a situation that there is still a tabWorkArea, but
2512 // there are no tabs anymore. This can happen when we get here after a
2513 // TabWorkArea::lastWorkAreaRemoved() signal. Therefore we count how
2514 // many TabWorkArea's have no documents anymore.
2517 // We have to call count() each time, because it can happen that
2518 // more than one splitter will disappear in one iteration (bug 5998).
2519 for (; d.splitter_->count() > empty_twa; ) {
2520 TabWorkArea * twa = d.tabWorkArea(empty_twa);
2522 if (twa->count() == 0)
2525 setCurrentWorkArea(twa->currentWorkArea());
2526 if (!closeTabWorkArea(twa))
2534 bool GuiView::closeWorkArea(GuiWorkArea * wa, bool close_buffer)
2539 Buffer & buf = wa->bufferView().buffer();
2541 if (close_buffer && GuiViewPrivate::busyBuffers.contains(&buf)) {
2542 Alert::warning(_("Close document"),
2543 _("Document could not be closed because it is being processed by LyX."));
2548 return closeBuffer(buf);
2550 if (!inMultiTabs(wa))
2551 if (!saveBufferIfNeeded(buf, true))
2559 bool GuiView::closeBuffer(Buffer & buf)
2561 // If we are in a close_event all children will be closed in some time,
2562 // so no need to do it here. This will ensure that the children end up
2563 // in the session file in the correct order. If we close the master
2564 // buffer, we can close or release the child buffers here too.
2565 bool success = true;
2567 ListOfBuffers clist = buf.getChildren();
2568 ListOfBuffers::const_iterator it = clist.begin();
2569 ListOfBuffers::const_iterator const bend = clist.end();
2570 for (; it != bend; ++it) {
2571 // If a child is dirty, do not close
2572 // without user intervention
2573 //FIXME: should we look in other tabworkareas?
2574 Buffer * child_buf = *it;
2575 GuiWorkArea * child_wa = workArea(*child_buf);
2577 if (!closeWorkArea(child_wa, true)) {
2582 theBufferList().releaseChild(&buf, child_buf);
2586 // goto bookmark to update bookmark pit.
2587 //FIXME: we should update only the bookmarks related to this buffer!
2588 LYXERR(Debug::DEBUG, "GuiView::closeBuffer()");
2589 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
2590 guiApp->gotoBookmark(i+1, false, false);
2592 if (saveBufferIfNeeded(buf, false)) {
2593 buf.removeAutosaveFile();
2594 theBufferList().release(&buf);
2598 // open all children again to avoid a crash because of dangling
2599 // pointers (bug 6603)
2605 bool GuiView::closeTabWorkArea(TabWorkArea * twa)
2607 while (twa == d.currentTabWorkArea()) {
2608 twa->setCurrentIndex(twa->count()-1);
2610 GuiWorkArea * wa = twa->currentWorkArea();
2611 Buffer & b = wa->bufferView().buffer();
2613 // We only want to close the buffer if the same buffer is not visible
2614 // in another view, and if this is not a child and if we are closing
2615 // a view (not a tabgroup).
2616 bool const close_buffer =
2617 !inOtherView(b) && !b.parent() && closing_;
2619 if (!closeWorkArea(wa, close_buffer))
2626 bool GuiView::saveBufferIfNeeded(Buffer & buf, bool hiding)
2628 if (buf.isClean() || buf.paragraphs().empty())
2631 // Switch to this Buffer.
2636 if (buf.isUnnamed())
2637 file = from_utf8(buf.fileName().onlyFileName());
2639 file = buf.fileName().displayName(30);
2641 // Bring this window to top before asking questions.
2646 if (hiding && buf.isUnnamed()) {
2647 docstring const text = bformat(_("The document %1$s has not been "
2648 "saved yet.\n\nDo you want to save "
2649 "the document?"), file);
2650 ret = Alert::prompt(_("Save new document?"),
2651 text, 0, 1, _("&Save"), _("&Cancel"));
2655 docstring const text = bformat(_("The document %1$s has unsaved changes."
2656 "\n\nDo you want to save the document or discard the changes?"), file);
2657 ret = Alert::prompt(_("Save changed document?"),
2658 text, 0, 2, _("&Save"), _("&Discard"), _("&Cancel"));
2663 if (!saveBuffer(buf))
2667 // If we crash after this we could have no autosave file
2668 // but I guess this is really improbable (Jug).
2669 // Sometimes improbable things happen:
2670 // - see bug http://www.lyx.org/trac/ticket/6587 (ps)
2671 // buf.removeAutosaveFile();
2673 // revert all changes
2684 bool GuiView::inMultiTabs(GuiWorkArea * wa)
2686 Buffer & buf = wa->bufferView().buffer();
2688 for (int i = 0; i != d.splitter_->count(); ++i) {
2689 GuiWorkArea * wa_ = d.tabWorkArea(i)->workArea(buf);
2690 if (wa_ && wa_ != wa)
2693 return inOtherView(buf);
2697 bool GuiView::inOtherView(Buffer & buf)
2699 QList<int> const ids = guiApp->viewIds();
2701 for (int i = 0; i != ids.size(); ++i) {
2705 if (guiApp->view(ids[i]).workArea(buf))
2712 void GuiView::gotoNextOrPreviousBuffer(NextOrPrevious np)
2714 if (!documentBufferView())
2717 if (TabWorkArea * twa = d.currentTabWorkArea()) {
2718 Buffer * const curbuf = &documentBufferView()->buffer();
2719 int nwa = twa->count();
2720 for (int i = 0; i < nwa; ++i) {
2721 if (&workArea(i)->bufferView().buffer() == curbuf) {
2723 if (np == NEXTBUFFER)
2724 next_index = (i == nwa - 1 ? 0 : i + 1);
2726 next_index = (i == 0 ? nwa - 1 : i - 1);
2727 setBuffer(&workArea(next_index)->bufferView().buffer());
2735 /// make sure the document is saved
2736 static bool ensureBufferClean(Buffer * buffer)
2738 LASSERT(buffer, return false);
2739 if (buffer->isClean() && !buffer->isUnnamed())
2742 docstring const file = buffer->fileName().displayName(30);
2745 if (!buffer->isUnnamed()) {
2746 text = bformat(_("The document %1$s has unsaved "
2747 "changes.\n\nDo you want to save "
2748 "the document?"), file);
2749 title = _("Save changed document?");
2752 text = bformat(_("The document %1$s has not been "
2753 "saved yet.\n\nDo you want to save "
2754 "the document?"), file);
2755 title = _("Save new document?");
2757 int const ret = Alert::prompt(title, text, 0, 1, _("&Save"), _("&Cancel"));
2760 dispatch(FuncRequest(LFUN_BUFFER_WRITE));
2762 return buffer->isClean() && !buffer->isUnnamed();
2766 bool GuiView::reloadBuffer(Buffer & buf)
2768 Buffer::ReadStatus status = buf.reload();
2769 return status == Buffer::ReadSuccess;
2773 void GuiView::checkExternallyModifiedBuffers()
2775 BufferList::iterator bit = theBufferList().begin();
2776 BufferList::iterator const bend = theBufferList().end();
2777 for (; bit != bend; ++bit) {
2778 Buffer * buf = *bit;
2779 if (buf->fileName().exists()
2780 && buf->isExternallyModified(Buffer::checksum_method)) {
2781 docstring text = bformat(_("Document \n%1$s\n has been externally modified."
2782 " Reload now? Any local changes will be lost."),
2783 from_utf8(buf->absFileName()));
2784 int const ret = Alert::prompt(_("Reload externally changed document?"),
2785 text, 0, 1, _("&Reload"), _("&Cancel"));
2793 void GuiView::dispatchVC(FuncRequest const & cmd, DispatchResult & dr)
2795 Buffer * buffer = documentBufferView()
2796 ? &(documentBufferView()->buffer()) : 0;
2798 switch (cmd.action()) {
2799 case LFUN_VC_REGISTER:
2800 if (!buffer || !ensureBufferClean(buffer))
2802 if (!buffer->lyxvc().inUse()) {
2803 if (buffer->lyxvc().registrer()) {
2804 reloadBuffer(*buffer);
2805 dr.suppressMessageUpdate();
2810 case LFUN_VC_CHECK_IN:
2811 if (!buffer || !ensureBufferClean(buffer))
2813 if (buffer->lyxvc().inUse() && !buffer->isReadonly()) {
2814 dr.setMessage(buffer->lyxvc().checkIn());
2815 if (!dr.message().empty())
2816 reloadBuffer(*buffer);
2820 case LFUN_VC_CHECK_OUT:
2821 if (!buffer || !ensureBufferClean(buffer))
2823 if (buffer->lyxvc().inUse()) {
2824 dr.setMessage(buffer->lyxvc().checkOut());
2825 reloadBuffer(*buffer);
2829 case LFUN_VC_LOCKING_TOGGLE:
2830 LASSERT(buffer, return);
2831 if (!ensureBufferClean(buffer) || buffer->isReadonly())
2833 if (buffer->lyxvc().inUse()) {
2834 string res = buffer->lyxvc().lockingToggle();
2836 frontend::Alert::error(_("Revision control error."),
2837 _("Error when setting the locking property."));
2840 reloadBuffer(*buffer);
2845 case LFUN_VC_REVERT:
2846 LASSERT(buffer, return);
2847 if (buffer->lyxvc().revert()) {
2848 reloadBuffer(*buffer);
2849 dr.suppressMessageUpdate();
2853 case LFUN_VC_UNDO_LAST:
2854 LASSERT(buffer, return);
2855 buffer->lyxvc().undoLast();
2856 reloadBuffer(*buffer);
2857 dr.suppressMessageUpdate();
2860 case LFUN_VC_REPO_UPDATE:
2861 LASSERT(buffer, return);
2862 if (ensureBufferClean(buffer)) {
2863 dr.setMessage(buffer->lyxvc().repoUpdate());
2864 checkExternallyModifiedBuffers();
2868 case LFUN_VC_COMMAND: {
2869 string flag = cmd.getArg(0);
2870 if (buffer && contains(flag, 'R') && !ensureBufferClean(buffer))
2873 if (contains(flag, 'M')) {
2874 if (!Alert::askForText(message, _("LyX VC: Log Message")))
2877 string path = cmd.getArg(1);
2878 if (contains(path, "$$p") && buffer)
2879 path = subst(path, "$$p", buffer->filePath());
2880 LYXERR(Debug::LYXVC, "Directory: " << path);
2882 if (!pp.isReadableDirectory()) {
2883 lyxerr << _("Directory is not accessible.") << endl;
2886 support::PathChanger p(pp);
2888 string command = cmd.getArg(2);
2889 if (command.empty())
2892 command = subst(command, "$$i", buffer->absFileName());
2893 command = subst(command, "$$p", buffer->filePath());
2895 command = subst(command, "$$m", to_utf8(message));
2896 LYXERR(Debug::LYXVC, "Command: " << command);
2898 one.startscript(Systemcall::Wait, command);
2902 if (contains(flag, 'I'))
2903 buffer->markDirty();
2904 if (contains(flag, 'R'))
2905 reloadBuffer(*buffer);
2910 case LFUN_VC_COMPARE: {
2912 if (cmd.argument().empty()) {
2913 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "comparehistory"));
2917 string rev1 = cmd.getArg(0);
2921 if (!buffer->lyxvc().prepareFileRevision(rev1, f1))
2924 if (isStrInt(rev1) && convert<int>(rev1) <= 0) {
2925 f2 = buffer->absFileName();
2927 string rev2 = cmd.getArg(1);
2931 if (!buffer->lyxvc().prepareFileRevision(rev2, f2))
2935 LYXERR(Debug::LYXVC, "Launching comparison for fetched revisions:\n" <<
2936 f1 << "\n" << f2 << "\n" );
2937 string par = "compare run " + quoteName(f1) + " " + quoteName(f2);
2938 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, par));
2948 void GuiView::openChildDocument(string const & fname)
2950 LASSERT(documentBufferView(), return);
2951 Buffer & buffer = documentBufferView()->buffer();
2952 FileName const filename = support::makeAbsPath(fname, buffer.filePath());
2953 documentBufferView()->saveBookmark(false);
2955 if (theBufferList().exists(filename)) {
2956 child = theBufferList().getBuffer(filename);
2959 message(bformat(_("Opening child document %1$s..."),
2960 makeDisplayPath(filename.absFileName())));
2961 child = loadDocument(filename, false);
2963 // Set the parent name of the child document.
2964 // This makes insertion of citations and references in the child work,
2965 // when the target is in the parent or another child document.
2967 child->setParent(&buffer);
2971 bool GuiView::goToFileRow(string const & argument)
2975 size_t i = argument.find_last_of(' ');
2976 if (i != string::npos) {
2977 file_name = os::internal_path(trim(argument.substr(0, i)));
2978 istringstream is(argument.substr(i + 1));
2983 if (i == string::npos) {
2984 LYXERR0("Wrong argument: " << argument);
2988 string const abstmp = package().temp_dir().absFileName();
2989 string const realtmp = package().temp_dir().realPath();
2990 // We have to use os::path_prefix_is() here, instead of
2991 // simply prefixIs(), because the file name comes from
2992 // an external application and may need case adjustment.
2993 if (os::path_prefix_is(file_name, abstmp, os::CASE_ADJUSTED)
2994 || os::path_prefix_is(file_name, realtmp, os::CASE_ADJUSTED)) {
2995 // Needed by inverse dvi search. If it is a file
2996 // in tmpdir, call the apropriated function.
2997 // If tmpdir is a symlink, we may have the real
2998 // path passed back, so we correct for that.
2999 if (!prefixIs(file_name, abstmp))
3000 file_name = subst(file_name, realtmp, abstmp);
3001 buf = theBufferList().getBufferFromTmp(file_name);
3003 // Must replace extension of the file to be .lyx
3004 // and get full path
3005 FileName const s = fileSearch(string(),
3006 support::changeExtension(file_name, ".lyx"), "lyx");
3007 // Either change buffer or load the file
3008 if (theBufferList().exists(s))
3009 buf = theBufferList().getBuffer(s);
3010 else if (s.exists()) {
3011 buf = loadDocument(s);
3016 _("File does not exist: %1$s"),
3017 makeDisplayPath(file_name)));
3023 _("No buffer for file: %1$s."),
3024 makeDisplayPath(file_name))
3029 documentBufferView()->setCursorFromRow(row);
3035 Buffer::ExportStatus GuiView::GuiViewPrivate::runAndDestroy(const T& func, Buffer const * orig, Buffer * clone, string const & format)
3037 Buffer::ExportStatus const status = func(format);
3039 // the cloning operation will have produced a clone of the entire set of
3040 // documents, starting from the master. so we must delete those.
3041 Buffer * mbuf = const_cast<Buffer *>(clone->masterBuffer());
3043 busyBuffers.remove(orig);
3048 Buffer::ExportStatus GuiView::GuiViewPrivate::compileAndDestroy(Buffer const * orig, Buffer * clone, string const & format)
3050 Buffer::ExportStatus (Buffer::* mem_func)(std::string const &, bool) const = &Buffer::doExport;
3051 return runAndDestroy(lyx::bind(mem_func, clone, _1, true), orig, clone, format);
3055 Buffer::ExportStatus GuiView::GuiViewPrivate::exportAndDestroy(Buffer const * orig, Buffer * clone, string const & format)
3057 Buffer::ExportStatus (Buffer::* mem_func)(std::string const &, bool) const = &Buffer::doExport;
3058 return runAndDestroy(lyx::bind(mem_func, clone, _1, false), orig, clone, format);
3062 Buffer::ExportStatus GuiView::GuiViewPrivate::previewAndDestroy(Buffer const * orig, Buffer * clone, string const & format)
3064 Buffer::ExportStatus (Buffer::* mem_func)(std::string const &) const = &Buffer::preview;
3065 return runAndDestroy(lyx::bind(mem_func, clone, _1), orig, clone, format);
3069 bool GuiView::GuiViewPrivate::asyncBufferProcessing(
3070 string const & argument,
3071 Buffer const * used_buffer,
3072 docstring const & msg,
3073 Buffer::ExportStatus (*asyncFunc)(Buffer const *, Buffer *, string const &),
3074 Buffer::ExportStatus (Buffer::*syncFunc)(string const &, bool) const,
3075 Buffer::ExportStatus (Buffer::*previewFunc)(string const &) const)
3080 string format = argument;
3082 format = used_buffer->params().getDefaultOutputFormat();
3083 processing_format = format;
3084 #if EXPORT_in_THREAD
3086 progress_->clearMessages();
3089 GuiViewPrivate::busyBuffers.insert(used_buffer);
3090 Buffer * cloned_buffer = used_buffer->cloneFromMaster();
3091 if (!cloned_buffer) {
3092 Alert::error(_("Export Error"),
3093 _("Error cloning the Buffer."));
3096 QFuture<Buffer::ExportStatus> f = QtConcurrent::run(
3101 setPreviewFuture(f);
3102 last_export_format = used_buffer->params().bufferFormat();
3105 // We are asynchronous, so we don't know here anything about the success
3108 Buffer::ExportStatus status;
3110 // TODO check here if it breaks exporting with Qt < 4.4
3111 status = (used_buffer->*syncFunc)(format, true);
3112 } else if (previewFunc) {
3113 status = (used_buffer->*previewFunc)(format);
3116 handleExportStatus(gv_, status, format);
3118 return (status == Buffer::ExportSuccess
3119 || status == Buffer::PreviewSuccess);
3123 void GuiView::dispatchToBufferView(FuncRequest const & cmd, DispatchResult & dr)
3125 BufferView * bv = currentBufferView();
3128 // Let the current BufferView dispatch its own actions.
3129 bv->dispatch(cmd, dr);
3130 if (dr.dispatched())
3133 // Try with the document BufferView dispatch if any.
3134 BufferView * doc_bv = documentBufferView();
3135 if (doc_bv && doc_bv != bv) {
3136 doc_bv->dispatch(cmd, dr);
3137 if (dr.dispatched())
3141 // Then let the current Cursor dispatch its own actions.
3142 bv->cursor().dispatch(cmd);
3144 // update completion. We do it here and not in
3145 // processKeySym to avoid another redraw just for a
3146 // changed inline completion
3147 if (cmd.origin() == FuncRequest::KEYBOARD) {
3148 if (cmd.action() == LFUN_SELF_INSERT
3149 || (cmd.action() == LFUN_ERT_INSERT && bv->cursor().inMathed()))
3150 updateCompletion(bv->cursor(), true, true);
3151 else if (cmd.action() == LFUN_CHAR_DELETE_BACKWARD)
3152 updateCompletion(bv->cursor(), false, true);
3154 updateCompletion(bv->cursor(), false, false);
3157 dr = bv->cursor().result();
3161 void GuiView::dispatch(FuncRequest const & cmd, DispatchResult & dr)
3163 BufferView * bv = currentBufferView();
3164 // By default we won't need any update.
3165 dr.screenUpdate(Update::None);
3166 // assume cmd will be dispatched
3167 dr.dispatched(true);
3169 Buffer * doc_buffer = documentBufferView()
3170 ? &(documentBufferView()->buffer()) : 0;
3172 if (cmd.origin() == FuncRequest::TOC) {
3173 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
3174 // FIXME: do we need to pass a DispatchResult object here?
3175 toc->doDispatch(bv->cursor(), cmd);
3179 string const argument = to_utf8(cmd.argument());
3181 switch(cmd.action()) {
3182 case LFUN_BUFFER_CHILD_OPEN:
3183 openChildDocument(to_utf8(cmd.argument()));
3186 case LFUN_BUFFER_IMPORT:
3187 importDocument(to_utf8(cmd.argument()));
3190 case LFUN_BUFFER_EXPORT: {
3193 // GCC only sees strfwd.h when building merged
3194 if (::lyx::operator==(cmd.argument(), "custom")) {
3195 dispatch(FuncRequest(LFUN_DIALOG_SHOW, "sendto"), dr);
3198 /* TODO/Review: Is it a problem to also export the children?
3199 See the update_unincluded flag */
3200 d.asyncBufferProcessing(argument,
3203 &GuiViewPrivate::exportAndDestroy,
3206 // TODO Inform user about success
3210 case LFUN_BUFFER_EXPORT_AS:
3211 LASSERT(doc_buffer, break);
3212 exportBufferAs(*doc_buffer);
3215 case LFUN_BUFFER_UPDATE: {
3216 d.asyncBufferProcessing(argument,
3219 &GuiViewPrivate::compileAndDestroy,
3224 case LFUN_BUFFER_VIEW: {
3225 d.asyncBufferProcessing(argument,
3227 _("Previewing ..."),
3228 &GuiViewPrivate::previewAndDestroy,
3233 case LFUN_MASTER_BUFFER_UPDATE: {
3234 d.asyncBufferProcessing(argument,
3235 (doc_buffer ? doc_buffer->masterBuffer() : 0),
3237 &GuiViewPrivate::compileAndDestroy,
3242 case LFUN_MASTER_BUFFER_VIEW: {
3243 d.asyncBufferProcessing(argument,
3244 (doc_buffer ? doc_buffer->masterBuffer() : 0),
3246 &GuiViewPrivate::previewAndDestroy,
3247 0, &Buffer::preview);
3250 case LFUN_BUFFER_SWITCH: {
3251 string const file_name = to_utf8(cmd.argument());
3252 if (!FileName::isAbsolute(file_name)) {
3254 dr.setMessage(_("Absolute filename expected."));
3258 Buffer * buffer = theBufferList().getBuffer(FileName(file_name));
3261 dr.setMessage(_("Document not loaded"));
3265 // Do we open or switch to the buffer in this view ?
3266 if (workArea(*buffer)
3267 || lyxrc.open_buffers_in_tabs || !documentBufferView()) {
3272 // Look for the buffer in other views
3273 QList<int> const ids = guiApp->viewIds();
3275 for (; i != ids.size(); ++i) {
3276 GuiView & gv = guiApp->view(ids[i]);
3277 if (gv.workArea(*buffer)) {
3278 gv.activateWindow();
3279 gv.setBuffer(buffer);
3284 // If necessary, open a new window as a last resort
3285 if (i == ids.size()) {
3286 lyx::dispatch(FuncRequest(LFUN_WINDOW_NEW));
3292 case LFUN_BUFFER_NEXT:
3293 gotoNextOrPreviousBuffer(NEXTBUFFER);
3296 case LFUN_BUFFER_PREVIOUS:
3297 gotoNextOrPreviousBuffer(PREVBUFFER);
3300 case LFUN_COMMAND_EXECUTE: {
3301 bool const show_it = cmd.argument() != "off";
3302 // FIXME: this is a hack, "minibuffer" should not be
3304 if (GuiToolbar * t = toolbar("minibuffer")) {
3305 t->setVisible(show_it);
3306 if (show_it && t->commandBuffer())
3307 t->commandBuffer()->setFocus();
3311 case LFUN_DROP_LAYOUTS_CHOICE:
3312 d.layout_->showPopup();
3315 case LFUN_MENU_OPEN:
3316 if (QMenu * menu = guiApp->menus().menu(toqstr(cmd.argument()), *this))
3317 menu->exec(QCursor::pos());
3320 case LFUN_FILE_INSERT:
3321 insertLyXFile(cmd.argument());
3324 case LFUN_FILE_INSERT_PLAINTEXT:
3325 case LFUN_FILE_INSERT_PLAINTEXT_PARA: {
3326 bool const as_paragraph = (cmd.action() == LFUN_FILE_INSERT_PLAINTEXT_PARA);
3327 string const fname = to_utf8(cmd.argument());
3328 if (!fname.empty() && !FileName::isAbsolute(fname)) {
3329 dr.setMessage(_("Absolute filename expected."));
3333 FileName filename(fname);
3334 if (fname.empty()) {
3335 FileDialog dlg(qt_("Select file to insert"), (as_paragraph ?
3336 LFUN_FILE_INSERT_PLAINTEXT_PARA : LFUN_FILE_INSERT_PLAINTEXT));
3338 FileDialog::Result result = dlg.open(toqstr(bv->buffer().filePath()),
3339 QStringList(qt_("All Files (*)")));
3341 if (result.first == FileDialog::Later || result.second.isEmpty()) {
3342 dr.setMessage(_("Canceled."));
3346 filename.set(fromqstr(result.second));
3350 FuncRequest const new_cmd(cmd, filename.absoluteFilePath());
3351 bv->dispatch(new_cmd, dr);
3356 case LFUN_BUFFER_RELOAD: {
3357 LASSERT(doc_buffer, break);
3360 if (!doc_buffer->isClean()) {
3361 docstring const file =
3362 makeDisplayPath(doc_buffer->absFileName(), 20);
3363 docstring text = bformat(_("Any changes will be lost. "
3364 "Are you sure you want to revert to the saved version "
3365 "of the document %1$s?"), file);
3366 ret = Alert::prompt(_("Revert to saved document?"),
3367 text, 1, 1, _("&Revert"), _("&Cancel"));
3371 doc_buffer->markClean();
3372 reloadBuffer(*doc_buffer);
3373 dr.forceBufferUpdate();
3378 case LFUN_BUFFER_WRITE:
3379 LASSERT(doc_buffer, break);
3380 saveBuffer(*doc_buffer);
3383 case LFUN_BUFFER_WRITE_AS:
3384 LASSERT(doc_buffer, break);
3385 renameBuffer(*doc_buffer, cmd.argument());
3388 case LFUN_BUFFER_WRITE_ALL: {
3389 Buffer * first = theBufferList().first();
3392 message(_("Saving all documents..."));
3393 // We cannot use a for loop as the buffer list cycles.
3396 if (!b->isClean()) {
3398 LYXERR(Debug::ACTION, "Saved " << b->absFileName());
3400 b = theBufferList().next(b);
3401 } while (b != first);
3402 dr.setMessage(_("All documents saved."));
3406 case LFUN_BUFFER_CLOSE:
3410 case LFUN_BUFFER_CLOSE_ALL:
3414 case LFUN_TOOLBAR_TOGGLE: {
3415 string const name = cmd.getArg(0);
3416 if (GuiToolbar * t = toolbar(name))
3421 case LFUN_DIALOG_UPDATE: {
3422 string const name = to_utf8(cmd.argument());
3423 if (name == "prefs" || name == "document")
3424 updateDialog(name, string());
3425 else if (name == "paragraph")
3426 lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
3427 else if (currentBufferView()) {
3428 Inset * inset = currentBufferView()->editedInset(name);
3429 // Can only update a dialog connected to an existing inset
3431 // FIXME: get rid of this indirection; GuiView ask the inset
3432 // if he is kind enough to update itself...
3433 FuncRequest fr(LFUN_INSET_DIALOG_UPDATE, cmd.argument());
3434 //FIXME: pass DispatchResult here?
3435 inset->dispatch(currentBufferView()->cursor(), fr);
3441 case LFUN_DIALOG_TOGGLE: {
3442 FuncCode const func_code = isDialogVisible(cmd.getArg(0))
3443 ? LFUN_DIALOG_HIDE : LFUN_DIALOG_SHOW;
3444 dispatch(FuncRequest(func_code, cmd.argument()), dr);
3448 case LFUN_DIALOG_DISCONNECT_INSET:
3449 disconnectDialog(to_utf8(cmd.argument()));
3452 case LFUN_DIALOG_HIDE: {
3453 guiApp->hideDialogs(to_utf8(cmd.argument()), 0);
3457 case LFUN_DIALOG_SHOW: {
3458 string const name = cmd.getArg(0);
3459 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
3461 if (name == "character") {
3462 data = freefont2string();
3464 showDialog("character", data);
3465 } else if (name == "latexlog") {
3466 Buffer::LogType type;
3467 string const logfile = doc_buffer->logName(&type);
3469 case Buffer::latexlog:
3472 case Buffer::buildlog:
3476 data += Lexer::quoteString(logfile);
3477 showDialog("log", data);
3478 } else if (name == "vclog") {
3479 string const data = "vc " +
3480 Lexer::quoteString(doc_buffer->lyxvc().getLogFile());
3481 showDialog("log", data);
3482 } else if (name == "symbols") {
3483 data = bv->cursor().getEncoding()->name();
3485 showDialog("symbols", data);
3487 } else if (name == "prefs" && isFullScreen()) {
3488 lfunUiToggle("fullscreen");
3489 showDialog("prefs", data);
3491 showDialog(name, data);
3496 dr.setMessage(cmd.argument());
3499 case LFUN_UI_TOGGLE: {
3500 string arg = cmd.getArg(0);
3501 if (!lfunUiToggle(arg)) {
3502 docstring const msg = "ui-toggle " + _("%1$s unknown command!");
3503 dr.setMessage(bformat(msg, from_utf8(arg)));
3505 // Make sure the keyboard focus stays in the work area.
3510 case LFUN_VIEW_SPLIT: {
3511 LASSERT(doc_buffer, break);
3512 string const orientation = cmd.getArg(0);
3513 d.splitter_->setOrientation(orientation == "vertical"
3514 ? Qt::Vertical : Qt::Horizontal);
3515 TabWorkArea * twa = addTabWorkArea();
3516 GuiWorkArea * wa = twa->addWorkArea(*doc_buffer, *this);
3517 setCurrentWorkArea(wa);
3520 case LFUN_TAB_GROUP_CLOSE:
3521 if (TabWorkArea * twa = d.currentTabWorkArea()) {
3522 closeTabWorkArea(twa);
3523 d.current_work_area_ = 0;
3524 twa = d.currentTabWorkArea();
3525 // Switch to the next GuiWorkArea in the found TabWorkArea.
3527 // Make sure the work area is up to date.
3528 setCurrentWorkArea(twa->currentWorkArea());
3530 setCurrentWorkArea(0);
3535 case LFUN_VIEW_CLOSE:
3536 if (TabWorkArea * twa = d.currentTabWorkArea()) {
3537 closeWorkArea(twa->currentWorkArea());
3538 d.current_work_area_ = 0;
3539 twa = d.currentTabWorkArea();
3540 // Switch to the next GuiWorkArea in the found TabWorkArea.
3542 // Make sure the work area is up to date.
3543 setCurrentWorkArea(twa->currentWorkArea());
3545 setCurrentWorkArea(0);
3550 case LFUN_COMPLETION_INLINE:
3551 if (d.current_work_area_)
3552 d.current_work_area_->completer().showInline();
3555 case LFUN_COMPLETION_POPUP:
3556 if (d.current_work_area_)
3557 d.current_work_area_->completer().showPopup();
3561 case LFUN_COMPLETION_COMPLETE:
3562 if (d.current_work_area_)
3563 d.current_work_area_->completer().tab();
3566 case LFUN_COMPLETION_CANCEL:
3567 if (d.current_work_area_) {
3568 if (d.current_work_area_->completer().popupVisible())
3569 d.current_work_area_->completer().hidePopup();
3571 d.current_work_area_->completer().hideInline();
3575 case LFUN_COMPLETION_ACCEPT:
3576 if (d.current_work_area_)
3577 d.current_work_area_->completer().activate();
3580 case LFUN_BUFFER_ZOOM_IN:
3581 case LFUN_BUFFER_ZOOM_OUT:
3582 if (cmd.argument().empty()) {
3583 if (cmd.action() == LFUN_BUFFER_ZOOM_IN)
3588 lyxrc.zoom += convert<int>(cmd.argument());
3590 if (lyxrc.zoom < 10)
3593 // The global QPixmapCache is used in GuiPainter to cache text
3594 // painting so we must reset it.
3595 QPixmapCache::clear();
3596 guiApp->fontLoader().update();
3597 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
3600 case LFUN_VC_REGISTER:
3601 case LFUN_VC_CHECK_IN:
3602 case LFUN_VC_CHECK_OUT:
3603 case LFUN_VC_REPO_UPDATE:
3604 case LFUN_VC_LOCKING_TOGGLE:
3605 case LFUN_VC_REVERT:
3606 case LFUN_VC_UNDO_LAST:
3607 case LFUN_VC_COMMAND:
3608 case LFUN_VC_COMPARE:
3609 dispatchVC(cmd, dr);
3612 case LFUN_SERVER_GOTO_FILE_ROW:
3613 goToFileRow(to_utf8(cmd.argument()));
3616 case LFUN_FORWARD_SEARCH: {
3617 Buffer const * doc_master = doc_buffer->masterBuffer();
3618 FileName const path(doc_master->temppath());
3619 string const texname = doc_master->isChild(doc_buffer)
3620 ? DocFileName(changeExtension(
3621 doc_buffer->absFileName(),
3622 "tex")).mangledFileName()
3623 : doc_buffer->latexName();
3624 string const fulltexname =
3625 support::makeAbsPath(texname, doc_master->temppath()).absFileName();
3626 string const mastername =
3627 removeExtension(doc_master->latexName());
3628 FileName const dviname(addName(path.absFileName(),
3629 addExtension(mastername, "dvi")));
3630 FileName const pdfname(addName(path.absFileName(),
3631 addExtension(mastername, "pdf")));
3632 bool const have_dvi = dviname.exists();
3633 bool const have_pdf = pdfname.exists();
3634 if (!have_dvi && !have_pdf) {
3635 dr.setMessage(_("Please, preview the document first."));
3638 string outname = dviname.onlyFileName();
3639 string command = lyxrc.forward_search_dvi;
3640 if (!have_dvi || (have_pdf &&
3641 pdfname.lastModified() > dviname.lastModified())) {
3642 outname = pdfname.onlyFileName();
3643 command = lyxrc.forward_search_pdf;
3646 DocIterator tmpcur = bv->cursor();
3648 while (tmpcur.inMathed())
3650 int row = tmpcur.inMathed() ? 0 : doc_buffer->texrow().getRowFromIdPos(
3651 tmpcur.paragraph().id(), tmpcur.pos());
3652 LYXERR(Debug::ACTION, "Forward search: row:" << row
3653 << " id:" << tmpcur.paragraph().id());
3654 if (!row || command.empty()) {
3655 dr.setMessage(_("Couldn't proceed."));
3658 string texrow = convert<string>(row);
3660 command = subst(command, "$$n", texrow);
3661 command = subst(command, "$$f", fulltexname);
3662 command = subst(command, "$$t", texname);
3663 command = subst(command, "$$o", outname);
3665 PathChanger p(path);
3667 one.startscript(Systemcall::DontWait, command);
3671 // The LFUN must be for one of BufferView, Buffer or Cursor;
3673 dispatchToBufferView(cmd, dr);
3677 // Part of automatic menu appearance feature.
3678 if (isFullScreen()) {
3679 if (menuBar()->isVisible() && lyxrc.full_screen_menubar)
3681 if (statusBar()->isVisible())
3682 statusBar()->hide();
3687 bool GuiView::lfunUiToggle(string const & ui_component)
3689 if (ui_component == "scrollbar") {
3690 // hide() is of no help
3691 if (d.current_work_area_->verticalScrollBarPolicy() ==
3692 Qt::ScrollBarAlwaysOff)
3694 d.current_work_area_->setVerticalScrollBarPolicy(
3695 Qt::ScrollBarAsNeeded);
3697 d.current_work_area_->setVerticalScrollBarPolicy(
3698 Qt::ScrollBarAlwaysOff);
3699 } else if (ui_component == "statusbar") {
3700 statusBar()->setVisible(!statusBar()->isVisible());
3701 } else if (ui_component == "menubar") {
3702 menuBar()->setVisible(!menuBar()->isVisible());
3704 if (ui_component == "frame") {
3706 getContentsMargins(&l, &t, &r, &b);
3707 //are the frames in default state?
3708 d.current_work_area_->setFrameStyle(QFrame::NoFrame);
3710 setContentsMargins(-2, -2, -2, -2);
3712 setContentsMargins(0, 0, 0, 0);
3715 if (ui_component == "fullscreen") {
3723 void GuiView::toggleFullScreen()
3725 if (isFullScreen()) {
3726 for (int i = 0; i != d.splitter_->count(); ++i)
3727 d.tabWorkArea(i)->setFullScreen(false);
3728 setContentsMargins(0, 0, 0, 0);
3729 setWindowState(windowState() ^ Qt::WindowFullScreen);
3732 statusBar()->show();
3735 hideDialogs("prefs", 0);
3736 for (int i = 0; i != d.splitter_->count(); ++i)
3737 d.tabWorkArea(i)->setFullScreen(true);
3738 setContentsMargins(-2, -2, -2, -2);
3740 setWindowState(windowState() ^ Qt::WindowFullScreen);
3741 statusBar()->hide();
3742 if (lyxrc.full_screen_menubar)
3744 if (lyxrc.full_screen_toolbars) {
3745 ToolbarMap::iterator end = d.toolbars_.end();
3746 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
3751 // give dialogs like the TOC a chance to adapt
3756 Buffer const * GuiView::updateInset(Inset const * inset)
3761 Buffer const * inset_buffer = &(inset->buffer());
3763 for (int i = 0; i != d.splitter_->count(); ++i) {
3764 GuiWorkArea * wa = d.tabWorkArea(i)->currentWorkArea();
3767 Buffer const * buffer = &(wa->bufferView().buffer());
3768 if (inset_buffer == buffer)
3769 wa->scheduleRedraw();
3771 return inset_buffer;
3775 void GuiView::restartCursor()
3777 /* When we move around, or type, it's nice to be able to see
3778 * the cursor immediately after the keypress.
3780 if (d.current_work_area_)
3781 d.current_work_area_->startBlinkingCursor();
3783 // Take this occasion to update the other GUI elements.
3789 void GuiView::updateCompletion(Cursor & cur, bool start, bool keep)
3791 if (d.current_work_area_)
3792 d.current_work_area_->completer().updateVisibility(cur, start, keep);
3797 // This list should be kept in sync with the list of insets in
3798 // src/insets/Inset.cpp. I.e., if a dialog goes with an inset, the
3799 // dialog should have the same name as the inset.
3800 // Changes should be also recorded in LFUN_DIALOG_SHOW doxygen
3801 // docs in LyXAction.cpp.
3803 char const * const dialognames[] = {
3805 "aboutlyx", "bibitem", "bibtex", "box", "branch", "changes", "character",
3806 "citation", "compare", "comparehistory", "document", "errorlist", "ert",
3807 "external", "file", "findreplace", "findreplaceadv", "float", "graphics",
3808 "href", "include", "index", "index_print", "info", "listings", "label", "line",
3809 "log", "mathdelimiter", "mathmatrix", "mathspace", "nomenclature",
3810 "nomencl_print", "note", "paragraph", "phantom", "prefs", "print", "ref",
3811 "sendto", "space", "spellchecker", "symbols", "tabular", "tabularcreate",
3812 "thesaurus", "texinfo", "toc", "view-source", "vspace", "wrap", "progress"};
3814 char const * const * const end_dialognames =
3815 dialognames + (sizeof(dialognames) / sizeof(char *));
3819 cmpCStr(char const * name) : name_(name) {}
3820 bool operator()(char const * other) {
3821 return strcmp(other, name_) == 0;
3828 bool isValidName(string const & name)
3830 return find_if(dialognames, end_dialognames,
3831 cmpCStr(name.c_str())) != end_dialognames;
3837 void GuiView::resetDialogs()
3839 // Make sure that no LFUN uses any GuiView.
3840 guiApp->setCurrentView(0);
3844 constructToolbars();
3845 guiApp->menus().fillMenuBar(menuBar(), this, false);
3846 d.layout_->updateContents(true);
3847 // Now update controls with current buffer.
3848 guiApp->setCurrentView(this);
3854 Dialog * GuiView::findOrBuild(string const & name, bool hide_it)
3856 if (!isValidName(name))
3859 map<string, DialogPtr>::iterator it = d.dialogs_.find(name);
3861 if (it != d.dialogs_.end()) {
3863 it->second->hideView();
3864 return it->second.get();
3867 Dialog * dialog = build(name);
3868 d.dialogs_[name].reset(dialog);
3869 if (lyxrc.allow_geometry_session)
3870 dialog->restoreSession();
3877 void GuiView::showDialog(string const & name, string const & data,
3880 triggerShowDialog(toqstr(name), toqstr(data), inset);
3884 void GuiView::doShowDialog(QString const & qname, QString const & qdata,
3890 const string name = fromqstr(qname);
3891 const string data = fromqstr(qdata);
3895 Dialog * dialog = findOrBuild(name, false);
3897 bool const visible = dialog->isVisibleView();
3898 dialog->showData(data);
3899 if (inset && currentBufferView())
3900 currentBufferView()->editInset(name, inset);
3901 // We only set the focus to the new dialog if it was not yet
3902 // visible in order not to change the existing previous behaviour
3904 // activateWindow is needed for floating dockviews
3905 dialog->asQWidget()->raise();
3906 dialog->asQWidget()->activateWindow();
3907 dialog->asQWidget()->setFocus();
3911 catch (ExceptionMessage const & ex) {
3919 bool GuiView::isDialogVisible(string const & name) const
3921 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3922 if (it == d.dialogs_.end())
3924 return it->second.get()->isVisibleView() && !it->second.get()->isClosing();
3928 void GuiView::hideDialog(string const & name, Inset * inset)
3930 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3931 if (it == d.dialogs_.end())
3935 if (!currentBufferView())
3937 if (inset != currentBufferView()->editedInset(name))
3941 Dialog * const dialog = it->second.get();
3942 if (dialog->isVisibleView())
3944 if (currentBufferView())
3945 currentBufferView()->editInset(name, 0);
3949 void GuiView::disconnectDialog(string const & name)
3951 if (!isValidName(name))
3953 if (currentBufferView())
3954 currentBufferView()->editInset(name, 0);
3958 void GuiView::hideAll() const
3960 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
3961 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3963 for(; it != end; ++it)
3964 it->second->hideView();
3968 void GuiView::updateDialogs()
3970 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
3971 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3973 for(; it != end; ++it) {
3974 Dialog * dialog = it->second.get();
3976 if (dialog->needBufferOpen() && !documentBufferView())
3977 hideDialog(fromqstr(dialog->name()), 0);
3978 else if (dialog->isVisibleView())
3979 dialog->checkStatus();
3986 Dialog * createDialog(GuiView & lv, string const & name);
3988 // will be replaced by a proper factory...
3989 Dialog * createGuiAbout(GuiView & lv);
3990 Dialog * createGuiBibtex(GuiView & lv);
3991 Dialog * createGuiChanges(GuiView & lv);
3992 Dialog * createGuiCharacter(GuiView & lv);
3993 Dialog * createGuiCitation(GuiView & lv);
3994 Dialog * createGuiCompare(GuiView & lv);
3995 Dialog * createGuiCompareHistory(GuiView & lv);
3996 Dialog * createGuiDelimiter(GuiView & lv);
3997 Dialog * createGuiDocument(GuiView & lv);
3998 Dialog * createGuiErrorList(GuiView & lv);
3999 Dialog * createGuiExternal(GuiView & lv);
4000 Dialog * createGuiGraphics(GuiView & lv);
4001 Dialog * createGuiInclude(GuiView & lv);
4002 Dialog * createGuiIndex(GuiView & lv);
4003 Dialog * createGuiListings(GuiView & lv);
4004 Dialog * createGuiLog(GuiView & lv);
4005 Dialog * createGuiMathMatrix(GuiView & lv);
4006 Dialog * createGuiNote(GuiView & lv);
4007 Dialog * createGuiParagraph(GuiView & lv);
4008 Dialog * createGuiPhantom(GuiView & lv);
4009 Dialog * createGuiPreferences(GuiView & lv);
4010 Dialog * createGuiPrint(GuiView & lv);
4011 Dialog * createGuiPrintindex(GuiView & lv);
4012 Dialog * createGuiRef(GuiView & lv);
4013 Dialog * createGuiSearch(GuiView & lv);
4014 Dialog * createGuiSearchAdv(GuiView & lv);
4015 Dialog * createGuiSendTo(GuiView & lv);
4016 Dialog * createGuiShowFile(GuiView & lv);
4017 Dialog * createGuiSpellchecker(GuiView & lv);
4018 Dialog * createGuiSymbols(GuiView & lv);
4019 Dialog * createGuiTabularCreate(GuiView & lv);
4020 Dialog * createGuiTexInfo(GuiView & lv);
4021 Dialog * createGuiToc(GuiView & lv);
4022 Dialog * createGuiThesaurus(GuiView & lv);
4023 Dialog * createGuiViewSource(GuiView & lv);
4024 Dialog * createGuiWrap(GuiView & lv);
4025 Dialog * createGuiProgressView(GuiView & lv);
4029 Dialog * GuiView::build(string const & name)
4031 LASSERT(isValidName(name), return 0);
4033 Dialog * dialog = createDialog(*this, name);
4037 if (name == "aboutlyx")
4038 return createGuiAbout(*this);
4039 if (name == "bibtex")
4040 return createGuiBibtex(*this);
4041 if (name == "changes")
4042 return createGuiChanges(*this);
4043 if (name == "character")
4044 return createGuiCharacter(*this);
4045 if (name == "citation")
4046 return createGuiCitation(*this);
4047 if (name == "compare")
4048 return createGuiCompare(*this);
4049 if (name == "comparehistory")
4050 return createGuiCompareHistory(*this);
4051 if (name == "document")
4052 return createGuiDocument(*this);
4053 if (name == "errorlist")
4054 return createGuiErrorList(*this);
4055 if (name == "external")
4056 return createGuiExternal(*this);
4058 return createGuiShowFile(*this);
4059 if (name == "findreplace")
4060 return createGuiSearch(*this);
4061 if (name == "findreplaceadv")
4062 return createGuiSearchAdv(*this);
4063 if (name == "graphics")
4064 return createGuiGraphics(*this);
4065 if (name == "include")
4066 return createGuiInclude(*this);
4067 if (name == "index")
4068 return createGuiIndex(*this);
4069 if (name == "index_print")
4070 return createGuiPrintindex(*this);
4071 if (name == "listings")
4072 return createGuiListings(*this);
4074 return createGuiLog(*this);
4075 if (name == "mathdelimiter")
4076 return createGuiDelimiter(*this);
4077 if (name == "mathmatrix")
4078 return createGuiMathMatrix(*this);
4080 return createGuiNote(*this);
4081 if (name == "paragraph")
4082 return createGuiParagraph(*this);
4083 if (name == "phantom")
4084 return createGuiPhantom(*this);
4085 if (name == "prefs")
4086 return createGuiPreferences(*this);
4087 if (name == "print")
4088 return createGuiPrint(*this);
4090 return createGuiRef(*this);
4091 if (name == "sendto")
4092 return createGuiSendTo(*this);
4093 if (name == "spellchecker")
4094 return createGuiSpellchecker(*this);
4095 if (name == "symbols")
4096 return createGuiSymbols(*this);
4097 if (name == "tabularcreate")
4098 return createGuiTabularCreate(*this);
4099 if (name == "texinfo")
4100 return createGuiTexInfo(*this);
4101 if (name == "thesaurus")
4102 return createGuiThesaurus(*this);
4104 return createGuiToc(*this);
4105 if (name == "view-source")
4106 return createGuiViewSource(*this);
4108 return createGuiWrap(*this);
4109 if (name == "progress")
4110 return createGuiProgressView(*this);
4116 } // namespace frontend
4119 #include "moc_GuiView.cpp"