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>
98 #include <QPixmapCache>
100 #include <QPushButton>
102 #include <QShowEvent>
104 #include <QStackedWidget>
105 #include <QStatusBar>
110 #include <QScrollBar>
114 #define EXPORT_in_THREAD 1
116 // QtConcurrent was introduced in Qt 4.4
117 #if (QT_VERSION >= 0x040400)
119 #include <QFutureWatcher>
120 #include <QtConcurrentRun>
123 #include "support/bind.h"
127 #ifdef HAVE_SYS_TIME_H
128 # include <sys/time.h>
136 using namespace lyx::support;
140 using support::addExtension;
141 using support::changeExtension;
142 using support::removeExtension;
148 class BackgroundWidget : public QWidget
153 LYXERR(Debug::GUI, "show banner: " << lyxrc.show_banner);
154 if (!lyxrc.show_banner)
156 /// The text to be written on top of the pixmap
157 QString const text = lyx_version ?
158 qt_("version ") + lyx_version : qt_("unknown version");
159 splash_ = getPixmap("images/", "banner", "png");
161 QPainter pain(&splash_);
162 pain.setPen(QColor(0, 0, 0));
164 // The font used to display the version info
165 font.setStyleHint(QFont::SansSerif);
166 font.setWeight(QFont::Bold);
167 font.setPointSize(int(toqstr(lyxrc.font_sizes[FONT_SIZE_LARGE]).toDouble()));
169 pain.drawText(190, 225, text);
170 setFocusPolicy(Qt::StrongFocus);
173 void paintEvent(QPaintEvent *)
175 int x = (width() - splash_.width()) / 2;
176 int y = (height() - splash_.height()) / 2;
178 pain.drawPixmap(x, y, splash_);
181 void keyPressEvent(QKeyEvent * ev)
184 setKeySymbol(&sym, ev);
186 guiApp->processKeySym(sym, q_key_state(ev->modifiers()));
198 /// Toolbar store providing access to individual toolbars by name.
199 typedef map<string, GuiToolbar *> ToolbarMap;
201 typedef shared_ptr<Dialog> DialogPtr;
206 struct GuiView::GuiViewPrivate
208 GuiViewPrivate(GuiView * gv)
209 : gv_(gv), current_work_area_(0), current_main_work_area_(0),
210 layout_(0), autosave_timeout_(5000),
213 // hardcode here the platform specific icon size
214 smallIconSize = 16; // scaling problems
215 normalIconSize = 20; // ok, default if iconsize.png is missing
216 bigIconSize = 26; // better for some math icons
218 // if it exists, use width of iconsize.png as normal size
219 QString const dir = toqstr(addPath("images", lyxrc.icon_set));
220 FileName const fn = lyx::libFileSearch(dir, "iconsize.png");
222 QImage image(toqstr(fn.absFileName()));
223 if (image.width() < int(smallIconSize))
224 normalIconSize = smallIconSize;
225 else if (image.width() > int(bigIconSize))
226 normalIconSize = bigIconSize;
228 normalIconSize = image.width();
231 splitter_ = new QSplitter;
232 bg_widget_ = new BackgroundWidget;
233 stack_widget_ = new QStackedWidget;
234 stack_widget_->addWidget(bg_widget_);
235 stack_widget_->addWidget(splitter_);
238 // TODO cleanup, remove the singleton, handle multiple Windows?
239 progress_ = ProgressInterface::instance();
240 if (!dynamic_cast<GuiProgress*>(progress_)) {
241 progress_ = new GuiProgress(); // TODO who deletes it
242 ProgressInterface::setInstance(progress_);
245 dynamic_cast<GuiProgress*>(progress_),
246 SIGNAL(updateStatusBarMessage(QString const&)),
247 gv, SLOT(updateStatusBarMessage(QString const&)));
249 dynamic_cast<GuiProgress*>(progress_),
250 SIGNAL(clearMessageText()),
251 gv, SLOT(clearMessageText()));
258 delete stack_widget_;
261 QMenu * toolBarPopup(GuiView * parent)
263 // FIXME: translation
264 QMenu * menu = new QMenu(parent);
265 QActionGroup * iconSizeGroup = new QActionGroup(parent);
267 QAction * smallIcons = new QAction(iconSizeGroup);
268 smallIcons->setText(qt_("Small-sized icons"));
269 smallIcons->setCheckable(true);
270 QObject::connect(smallIcons, SIGNAL(triggered()),
271 parent, SLOT(smallSizedIcons()));
272 menu->addAction(smallIcons);
274 QAction * normalIcons = new QAction(iconSizeGroup);
275 normalIcons->setText(qt_("Normal-sized icons"));
276 normalIcons->setCheckable(true);
277 QObject::connect(normalIcons, SIGNAL(triggered()),
278 parent, SLOT(normalSizedIcons()));
279 menu->addAction(normalIcons);
281 QAction * bigIcons = new QAction(iconSizeGroup);
282 bigIcons->setText(qt_("Big-sized icons"));
283 bigIcons->setCheckable(true);
284 QObject::connect(bigIcons, SIGNAL(triggered()),
285 parent, SLOT(bigSizedIcons()));
286 menu->addAction(bigIcons);
288 unsigned int cur = parent->iconSize().width();
289 if ( cur == parent->d.smallIconSize)
290 smallIcons->setChecked(true);
291 else if (cur == parent->d.normalIconSize)
292 normalIcons->setChecked(true);
293 else if (cur == parent->d.bigIconSize)
294 bigIcons->setChecked(true);
301 stack_widget_->setCurrentWidget(bg_widget_);
302 bg_widget_->setUpdatesEnabled(true);
303 bg_widget_->setFocus();
306 int tabWorkAreaCount()
308 return splitter_->count();
311 TabWorkArea * tabWorkArea(int i)
313 return dynamic_cast<TabWorkArea *>(splitter_->widget(i));
316 TabWorkArea * currentTabWorkArea()
318 int areas = tabWorkAreaCount();
320 // The first TabWorkArea is always the first one, if any.
321 return tabWorkArea(0);
323 for (int i = 0; i != areas; ++i) {
324 TabWorkArea * twa = tabWorkArea(i);
325 if (current_main_work_area_ == twa->currentWorkArea())
329 // None has the focus so we just take the first one.
330 return tabWorkArea(0);
333 #if (QT_VERSION >= 0x040400)
334 void setPreviewFuture(QFuture<Buffer::ExportStatus> const & f)
336 if (processing_thread_watcher_.isRunning()) {
337 // we prefer to cancel this preview in order to keep a snappy
341 processing_thread_watcher_.setFuture(f);
347 GuiWorkArea * current_work_area_;
348 GuiWorkArea * current_main_work_area_;
349 QSplitter * splitter_;
350 QStackedWidget * stack_widget_;
351 BackgroundWidget * bg_widget_;
353 ToolbarMap toolbars_;
354 ProgressInterface* progress_;
355 /// The main layout box.
357 * \warning Don't Delete! The layout box is actually owned by
358 * whichever toolbar contains it. All the GuiView class needs is a
359 * means of accessing it.
361 * FIXME: replace that with a proper model so that we are not limited
362 * to only one dialog.
367 map<string, DialogPtr> dialogs_;
369 unsigned int smallIconSize;
370 unsigned int normalIconSize;
371 unsigned int bigIconSize;
373 QTimer statusbar_timer_;
374 /// auto-saving of buffers
375 Timeout autosave_timeout_;
376 /// flag against a race condition due to multiclicks, see bug #1119
380 TocModels toc_models_;
382 #if (QT_VERSION >= 0x040400)
384 QFutureWatcher<docstring> autosave_watcher_;
385 QFutureWatcher<Buffer::ExportStatus> processing_thread_watcher_;
387 string last_export_format;
388 string processing_format;
390 struct DummyWatcher { bool isRunning(){return false;} };
391 DummyWatcher processing_thread_watcher_;
394 static QSet<Buffer const *> busyBuffers;
395 static Buffer::ExportStatus previewAndDestroy(Buffer const * orig, Buffer * buffer, string const & format);
396 static Buffer::ExportStatus exportAndDestroy(Buffer const * orig, Buffer * buffer, string const & format);
397 static Buffer::ExportStatus compileAndDestroy(Buffer const * orig, Buffer * buffer, string const & format);
398 static docstring autosaveAndDestroy(Buffer const * orig, Buffer * buffer);
401 static Buffer::ExportStatus runAndDestroy(const T& func, Buffer const * orig, Buffer * buffer, string const & format);
403 // TODO syncFunc/previewFunc: use bind
404 bool asyncBufferProcessing(string const & argument,
405 Buffer const * used_buffer,
406 docstring const & msg,
407 Buffer::ExportStatus (*asyncFunc)(Buffer const *, Buffer *, string const &),
408 Buffer::ExportStatus (Buffer::*syncFunc)(string const &, bool) const,
409 Buffer::ExportStatus (Buffer::*previewFunc)(string const &) const);
411 QVector<GuiWorkArea*> guiWorkAreas();
414 QSet<Buffer const *> GuiView::GuiViewPrivate::busyBuffers;
417 GuiView::GuiView(int id)
418 : d(*new GuiViewPrivate(this)), id_(id), closing_(false), busy_(0)
420 // GuiToolbars *must* be initialised before the menu bar.
421 normalSizedIcons(); // at least on Mac the default is 32 otherwise, which is huge
424 // set ourself as the current view. This is needed for the menu bar
425 // filling, at least for the static special menu item on Mac. Otherwise
426 // they are greyed out.
427 guiApp->setCurrentView(this);
429 // Fill up the menu bar.
430 guiApp->menus().fillMenuBar(menuBar(), this, true);
432 setCentralWidget(d.stack_widget_);
434 // Start autosave timer
435 if (lyxrc.autosave) {
436 d.autosave_timeout_.timeout.connect(bind(&GuiView::autoSave, this));
437 d.autosave_timeout_.setTimeout(lyxrc.autosave * 1000);
438 d.autosave_timeout_.start();
440 connect(&d.statusbar_timer_, SIGNAL(timeout()),
441 this, SLOT(clearMessage()));
443 // We don't want to keep the window in memory if it is closed.
444 setAttribute(Qt::WA_DeleteOnClose, true);
446 #if (!defined(Q_WS_WIN) && !defined(Q_WS_MACX))
447 // assign an icon to main form. We do not do it under Qt/Win or Qt/Mac,
448 // since the icon is provided in the application bundle.
449 setWindowIcon(getPixmap("images/", "lyx", "png"));
452 #if (QT_VERSION >= 0x040300)
453 // use tabbed dock area for multiple docks
454 // (such as "source" and "messages")
455 setDockOptions(QMainWindow::ForceTabbedDocks);
459 setAcceptDrops(true);
461 #if (QT_VERSION >= 0x040400)
463 // add busy indicator to statusbar
464 QLabel * busylabel = new QLabel(statusBar());
465 statusBar()->addPermanentWidget(busylabel);
466 QString fn = toqstr(lyx::libFileSearch("images", "busy.gif").absFileName());
467 QMovie * busyanim = new QMovie(fn, QByteArray(), busylabel);
468 busylabel->setMovie(busyanim);
472 connect(&d.processing_thread_watcher_, SIGNAL(started()),
473 busylabel, SLOT(show()));
474 connect(&d.processing_thread_watcher_, SIGNAL(finished()),
475 busylabel, SLOT(hide()));
477 statusBar()->setSizeGripEnabled(true);
480 connect(&d.autosave_watcher_, SIGNAL(finished()), this,
481 SLOT(autoSaveThreadFinished()));
483 connect(&d.processing_thread_watcher_, SIGNAL(started()), this,
484 SLOT(processingThreadStarted()));
485 connect(&d.processing_thread_watcher_, SIGNAL(finished()), this,
486 SLOT(processingThreadFinished()));
490 connect(this, SIGNAL(triggerShowDialog(QString const &, QString const &, Inset *)),
491 SLOT(doShowDialog(QString const &, QString const &, Inset *)));
493 // Forbid too small unresizable window because it can happen
494 // with some window manager under X11.
495 setMinimumSize(300, 200);
497 if (lyxrc.allow_geometry_session) {
498 // Now take care of session management.
503 // no session handling, default to a sane size.
504 setGeometry(50, 50, 690, 510);
507 // clear session data if any.
509 settings.remove("views");
519 QVector<GuiWorkArea*> GuiView::GuiViewPrivate::guiWorkAreas()
521 QVector<GuiWorkArea*> areas;
522 for (int i = 0; i < tabWorkAreaCount(); i++) {
523 TabWorkArea* ta = tabWorkArea(i);
524 for (int u = 0; u < ta->count(); u++) {
525 areas << ta->workArea(u);
531 static void handleExportStatus(GuiView * view, Buffer::ExportStatus status,
532 string const & format)
534 docstring const fmt = formats.prettyName(format);
537 case Buffer::ExportSuccess:
538 msg = bformat(_("Successful export to format: %1$s"), fmt);
540 case Buffer::ExportCancel:
541 msg = _("Document export cancelled.");
543 case Buffer::ExportError:
544 case Buffer::ExportNoPathToFormat:
545 case Buffer::ExportTexPathHasSpaces:
546 case Buffer::ExportConverterError:
547 msg = bformat(_("Error while exporting format: %1$s"), fmt);
549 case Buffer::PreviewSuccess:
550 msg = bformat(_("Successful preview of format: %1$s"), fmt);
552 case Buffer::PreviewError:
553 msg = bformat(_("Error while previewing format: %1$s"), fmt);
560 #if QT_VERSION >= 0x040400
562 void GuiView::processingThreadStarted()
567 void GuiView::processingThreadFinished()
569 QFutureWatcher<Buffer::ExportStatus> const * watcher =
570 static_cast<QFutureWatcher<Buffer::ExportStatus> const *>(sender());
572 Buffer::ExportStatus const status = watcher->result();
573 handleExportStatus(this, status, d.processing_format);
576 BufferView const * const bv = currentBufferView();
577 if (bv && !bv->buffer().errorList("Export").empty()) {
581 errors(d.last_export_format);
585 void GuiView::autoSaveThreadFinished()
587 QFutureWatcher<docstring> const * watcher =
588 static_cast<QFutureWatcher<docstring> const *>(sender());
589 message(watcher->result());
595 void GuiView::processingThreadStarted()
600 void GuiView::processingThreadFinished()
605 void GuiView::autoSaveThreadFinished()
611 void GuiView::saveLayout() const
614 settings.beginGroup("views");
615 settings.beginGroup(QString::number(id_));
617 settings.setValue("pos", pos());
618 settings.setValue("size", size());
620 settings.setValue("geometry", saveGeometry());
622 settings.setValue("layout", saveState(0));
623 settings.setValue("icon_size", iconSize());
627 void GuiView::saveUISettings() const
629 // Save the toolbar private states
630 ToolbarMap::iterator end = d.toolbars_.end();
631 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
632 it->second->saveSession();
633 // Now take care of all other dialogs
634 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
635 for (; it!= d.dialogs_.end(); ++it)
636 it->second->saveSession();
640 bool GuiView::restoreLayout()
643 settings.beginGroup("views");
644 settings.beginGroup(QString::number(id_));
645 QString const icon_key = "icon_size";
646 if (!settings.contains(icon_key))
649 //code below is skipped when when ~/.config/LyX is (re)created
650 QSize icon_size = settings.value(icon_key).toSize();
651 // Check whether session size changed.
652 if (icon_size.width() != int(d.smallIconSize) &&
653 icon_size.width() != int(d.normalIconSize) &&
654 icon_size.width() != int(d.bigIconSize)) {
655 icon_size.setWidth(d.normalIconSize);
656 icon_size.setHeight(d.normalIconSize);
658 setIconSize(icon_size);
661 QPoint pos = settings.value("pos", QPoint(50, 50)).toPoint();
662 QSize size = settings.value("size", QSize(690, 510)).toSize();
666 // Work-around for bug #6034: the window ends up in an undetermined
667 // state when trying to restore a maximized window when it is
668 // already maximized.
669 if (!(windowState() & Qt::WindowMaximized))
670 if (!restoreGeometry(settings.value("geometry").toByteArray()))
671 setGeometry(50, 50, 690, 510);
673 // Make sure layout is correctly oriented.
674 setLayoutDirection(qApp->layoutDirection());
676 // Allow the toc and view-source dock widget to be restored if needed.
678 if ((dialog = findOrBuild("toc", true)))
679 // see bug 5082. At least setup title and enabled state.
680 // Visibility will be adjusted by restoreState below.
681 dialog->prepareView();
682 if ((dialog = findOrBuild("view-source", true)))
683 dialog->prepareView();
684 if ((dialog = findOrBuild("progress", true)))
685 dialog->prepareView();
686 if ((dialog = findOrBuild("findreplaceadv", true)))
687 dialog->prepareView();
689 if (!restoreState(settings.value("layout").toByteArray(), 0))
696 GuiToolbar * GuiView::toolbar(string const & name)
698 ToolbarMap::iterator it = d.toolbars_.find(name);
699 if (it != d.toolbars_.end())
702 LYXERR(Debug::GUI, "Toolbar::display: no toolbar named " << name);
707 void GuiView::constructToolbars()
709 ToolbarMap::iterator it = d.toolbars_.begin();
710 for (; it != d.toolbars_.end(); ++it)
714 // I don't like doing this here, but the standard toolbar
715 // destroys this object when it's destroyed itself (vfr)
716 d.layout_ = new LayoutBox(*this);
717 d.stack_widget_->addWidget(d.layout_);
718 d.layout_->move(0,0);
720 // extracts the toolbars from the backend
721 Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
722 Toolbars::Infos::iterator end = guiApp->toolbars().end();
723 for (; cit != end; ++cit)
724 d.toolbars_[cit->name] = new GuiToolbar(*cit, *this);
728 void GuiView::initToolbars()
730 // extracts the toolbars from the backend
731 Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
732 Toolbars::Infos::iterator end = guiApp->toolbars().end();
733 for (; cit != end; ++cit) {
734 GuiToolbar * tb = toolbar(cit->name);
737 int const visibility = guiApp->toolbars().defaultVisibility(cit->name);
738 bool newline = !(visibility & Toolbars::SAMEROW);
739 tb->setVisible(false);
740 tb->setVisibility(visibility);
742 if (visibility & Toolbars::TOP) {
744 addToolBarBreak(Qt::TopToolBarArea);
745 addToolBar(Qt::TopToolBarArea, tb);
748 if (visibility & Toolbars::BOTTOM) {
749 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
750 #if (QT_VERSION >= 0x040202)
752 addToolBarBreak(Qt::BottomToolBarArea);
754 addToolBar(Qt::BottomToolBarArea, tb);
757 if (visibility & Toolbars::LEFT) {
758 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
759 #if (QT_VERSION >= 0x040202)
761 addToolBarBreak(Qt::LeftToolBarArea);
763 addToolBar(Qt::LeftToolBarArea, tb);
766 if (visibility & Toolbars::RIGHT) {
767 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
768 #if (QT_VERSION >= 0x040202)
770 addToolBarBreak(Qt::RightToolBarArea);
772 addToolBar(Qt::RightToolBarArea, tb);
775 if (visibility & Toolbars::ON)
776 tb->setVisible(true);
781 TocModels & GuiView::tocModels()
783 return d.toc_models_;
787 void GuiView::setFocus()
789 LYXERR(Debug::DEBUG, "GuiView::setFocus()" << this);
790 QMainWindow::setFocus();
794 void GuiView::focusInEvent(QFocusEvent * e)
796 LYXERR(Debug::DEBUG, "GuiView::focusInEvent()" << this);
797 QMainWindow::focusInEvent(e);
798 // Make sure guiApp points to the correct view.
799 guiApp->setCurrentView(this);
800 if (currentWorkArea())
801 currentWorkArea()->setFocus();
802 else if (currentMainWorkArea())
803 currentMainWorkArea()->setFocus();
805 d.bg_widget_->setFocus();
809 QMenu * GuiView::createPopupMenu()
811 return d.toolBarPopup(this);
815 void GuiView::showEvent(QShowEvent * e)
817 LYXERR(Debug::GUI, "Passed Geometry "
818 << size().height() << "x" << size().width()
819 << "+" << pos().x() << "+" << pos().y());
821 if (d.splitter_->count() == 0)
822 // No work area, switch to the background widget.
826 QMainWindow::showEvent(e);
830 bool GuiView::closeScheduled()
837 /** Destroy only all tabbed WorkAreas. Destruction of other WorkAreas
838 ** is responsibility of the container (e.g., dialog)
840 void GuiView::closeEvent(QCloseEvent * close_event)
842 LYXERR(Debug::DEBUG, "GuiView::closeEvent()");
844 if (!GuiViewPrivate::busyBuffers.isEmpty()) {
845 Alert::warning(_("Exit LyX"),
846 _("LyX could not be closed because documents are being processed by LyX."));
847 close_event->setAccepted(false);
851 // If the user pressed the x (so we didn't call closeView
852 // programmatically), we want to clear all existing entries.
854 theSession().lastOpened().clear();
859 // it can happen that this event arrives without selecting the view,
860 // e.g. when clicking the close button on a background window.
862 if (!closeWorkAreaAll()) {
864 close_event->ignore();
868 // Make sure that nothing will use this to be closed View.
869 guiApp->unregisterView(this);
871 if (isFullScreen()) {
872 // Switch off fullscreen before closing.
877 // Make sure the timer time out will not trigger a statusbar update.
878 d.statusbar_timer_.stop();
880 // Saving fullscreen requires additional tweaks in the toolbar code.
881 // It wouldn't also work under linux natively.
882 if (lyxrc.allow_geometry_session) {
887 close_event->accept();
891 void GuiView::dragEnterEvent(QDragEnterEvent * event)
893 if (event->mimeData()->hasUrls())
895 /// \todo Ask lyx-devel is this is enough:
896 /// if (event->mimeData()->hasFormat("text/plain"))
897 /// event->acceptProposedAction();
901 void GuiView::dropEvent(QDropEvent * event)
903 QList<QUrl> files = event->mimeData()->urls();
907 LYXERR(Debug::GUI, "GuiView::dropEvent: got URLs!");
908 for (int i = 0; i != files.size(); ++i) {
909 string const file = os::internal_path(fromqstr(
910 files.at(i).toLocalFile()));
914 string const ext = support::getExtension(file);
915 vector<const Format *> found_formats;
917 // Find all formats that have the correct extension.
918 vector<const Format *> const & import_formats
919 = theConverters().importableFormats();
920 vector<const Format *>::const_iterator it = import_formats.begin();
921 for (; it != import_formats.end(); ++it)
922 if ((*it)->hasExtension(ext))
923 found_formats.push_back(*it);
926 if (found_formats.size() >= 1) {
927 if (found_formats.size() > 1) {
928 //FIXME: show a dialog to choose the correct importable format
930 "Multiple importable formats found, selecting first");
932 string const arg = found_formats[0]->name() + " " + file;
933 cmd = FuncRequest(LFUN_BUFFER_IMPORT, arg);
936 //FIXME: do we have to explicitly check whether it's a lyx file?
938 "No formats found, trying to open it as a lyx file");
939 cmd = FuncRequest(LFUN_FILE_OPEN, file);
941 // add the functions to the queue
942 guiApp->addToFuncRequestQueue(cmd);
945 // now process the collected functions. We perform the events
946 // asynchronously. This prevents potential problems in case the
947 // BufferView is closed within an event.
948 guiApp->processFuncRequestQueueAsync();
952 void GuiView::message(docstring const & str)
954 if (ForkedProcess::iAmAChild())
957 // call is moved to GUI-thread by GuiProgress
958 d.progress_->appendMessage(toqstr(str));
962 void GuiView::clearMessageText()
964 message(docstring());
968 void GuiView::updateStatusBarMessage(QString const & str)
970 statusBar()->showMessage(str);
971 d.statusbar_timer_.stop();
972 d.statusbar_timer_.start(3000);
976 void GuiView::smallSizedIcons()
978 setIconSize(QSize(d.smallIconSize, d.smallIconSize));
982 void GuiView::normalSizedIcons()
984 setIconSize(QSize(d.normalIconSize, d.normalIconSize));
988 void GuiView::bigSizedIcons()
990 setIconSize(QSize(d.bigIconSize, d.bigIconSize));
994 void GuiView::clearMessage()
996 // FIXME: This code was introduced in r19643 to fix bug #4123. However,
997 // the hasFocus function mostly returns false, even if the focus is on
998 // a workarea in this view.
1002 d.statusbar_timer_.stop();
1006 void GuiView::updateWindowTitle(GuiWorkArea * wa)
1008 if (wa != d.current_work_area_
1009 || wa->bufferView().buffer().isInternal())
1011 setWindowTitle(qt_("LyX: ") + wa->windowTitle());
1012 setWindowIconText(wa->windowIconText());
1016 void GuiView::on_currentWorkAreaChanged(GuiWorkArea * wa)
1018 QObject::disconnect(d.current_work_area_, SIGNAL(busy(bool)),
1019 this, SLOT(setBusy(bool)));
1021 disconnectBufferView();
1022 connectBufferView(wa->bufferView());
1023 connectBuffer(wa->bufferView().buffer());
1024 d.current_work_area_ = wa;
1025 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
1026 this, SLOT(updateWindowTitle(GuiWorkArea *)));
1027 QObject::connect(wa, SIGNAL(busy(bool)), this, SLOT(setBusy(bool)));
1028 updateWindowTitle(wa);
1032 // The document settings needs to be reinitialised.
1033 updateDialog("document", "");
1035 // Buffer-dependent dialogs must be updated. This is done here because
1036 // some dialogs require buffer()->text.
1041 void GuiView::on_lastWorkAreaRemoved()
1044 // We already are in a close event. Nothing more to do.
1047 if (d.splitter_->count() > 1)
1048 // We have a splitter so don't close anything.
1051 // Reset and updates the dialogs.
1052 d.toc_models_.reset(0);
1053 updateDialog("document", "");
1056 resetWindowTitleAndIconText();
1059 if (lyxrc.open_buffers_in_tabs)
1060 // Nothing more to do, the window should stay open.
1063 if (guiApp->viewIds().size() > 1) {
1069 // On Mac we also close the last window because the application stay
1070 // resident in memory. On other platforms we don't close the last
1071 // window because this would quit the application.
1077 void GuiView::updateStatusBar()
1079 // let the user see the explicit message
1080 if (d.statusbar_timer_.isActive())
1087 void GuiView::showMessage()
1089 QString msg = toqstr(theGuiApp()->viewStatusMessage());
1090 if (msg.isEmpty()) {
1091 BufferView const * bv = currentBufferView();
1093 msg = toqstr(bv->cursor().currentState());
1095 msg = qt_("Welcome to LyX!");
1097 statusBar()->showMessage(msg);
1101 bool GuiView::event(QEvent * e)
1105 // Useful debug code:
1106 //case QEvent::ActivationChange:
1107 //case QEvent::WindowDeactivate:
1108 //case QEvent::Paint:
1109 //case QEvent::Enter:
1110 //case QEvent::Leave:
1111 //case QEvent::HoverEnter:
1112 //case QEvent::HoverLeave:
1113 //case QEvent::HoverMove:
1114 //case QEvent::StatusTip:
1115 //case QEvent::DragEnter:
1116 //case QEvent::DragLeave:
1117 //case QEvent::Drop:
1120 case QEvent::WindowActivate: {
1121 GuiView * old_view = guiApp->currentView();
1122 if (this == old_view) {
1124 return QMainWindow::event(e);
1126 if (old_view && old_view->currentBufferView()) {
1127 // save current selection to the selection buffer to allow
1128 // middle-button paste in this window.
1129 cap::saveSelection(old_view->currentBufferView()->cursor());
1131 guiApp->setCurrentView(this);
1132 if (d.current_work_area_) {
1133 BufferView & bv = d.current_work_area_->bufferView();
1134 connectBufferView(bv);
1135 connectBuffer(bv.buffer());
1136 // The document structure, name and dialogs might have
1137 // changed in another view.
1139 // The document settings needs to be reinitialised.
1140 updateDialog("document", "");
1143 resetWindowTitleAndIconText();
1146 return QMainWindow::event(e);
1149 case QEvent::ShortcutOverride: {
1152 #if (!defined Q_WS_X11) || (QT_VERSION >= 0x040500)
1153 if (isFullScreen() && menuBar()->isHidden()) {
1154 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
1155 // FIXME: we should also try to detect special LyX shortcut such as
1156 // Alt-P and Alt-M. Right now there is a hack in
1157 // GuiWorkArea::processKeySym() that hides again the menubar for
1159 if (ke->modifiers() & Qt::AltModifier && ke->key() != Qt::Key_Alt) {
1161 return QMainWindow::event(e);
1165 return QMainWindow::event(e);
1169 return QMainWindow::event(e);
1173 void GuiView::resetWindowTitleAndIconText()
1175 setWindowTitle(qt_("LyX"));
1176 setWindowIconText(qt_("LyX"));
1179 bool GuiView::focusNextPrevChild(bool /*next*/)
1186 bool GuiView::busy() const
1192 void GuiView::setBusy(bool busy)
1194 bool const busy_before = busy_ > 0;
1195 busy ? ++busy_ : --busy_;
1196 if ((busy_ > 0) == busy_before)
1197 // busy state didn't change
1201 QApplication::setOverrideCursor(Qt::WaitCursor);
1204 QApplication::restoreOverrideCursor();
1209 GuiWorkArea * GuiView::workArea(int index)
1211 if (TabWorkArea * twa = d.currentTabWorkArea())
1212 if (index < twa->count())
1213 return dynamic_cast<GuiWorkArea *>(twa->widget(index));
1218 GuiWorkArea * GuiView::workArea(Buffer & buffer)
1220 if (currentWorkArea()
1221 && ¤tWorkArea()->bufferView().buffer() == &buffer)
1222 return (GuiWorkArea *) currentWorkArea();
1223 if (TabWorkArea * twa = d.currentTabWorkArea())
1224 return twa->workArea(buffer);
1229 GuiWorkArea * GuiView::addWorkArea(Buffer & buffer)
1231 // Automatically create a TabWorkArea if there are none yet.
1232 TabWorkArea * tab_widget = d.splitter_->count()
1233 ? d.currentTabWorkArea() : addTabWorkArea();
1234 return tab_widget->addWorkArea(buffer, *this);
1238 TabWorkArea * GuiView::addTabWorkArea()
1240 TabWorkArea * twa = new TabWorkArea;
1241 QObject::connect(twa, SIGNAL(currentWorkAreaChanged(GuiWorkArea *)),
1242 this, SLOT(on_currentWorkAreaChanged(GuiWorkArea *)));
1243 QObject::connect(twa, SIGNAL(lastWorkAreaRemoved()),
1244 this, SLOT(on_lastWorkAreaRemoved()));
1246 d.splitter_->addWidget(twa);
1247 d.stack_widget_->setCurrentWidget(d.splitter_);
1252 GuiWorkArea const * GuiView::currentWorkArea() const
1254 return d.current_work_area_;
1258 GuiWorkArea * GuiView::currentWorkArea()
1260 return d.current_work_area_;
1264 GuiWorkArea const * GuiView::currentMainWorkArea() const
1266 if (!d.currentTabWorkArea())
1268 return d.currentTabWorkArea()->currentWorkArea();
1272 GuiWorkArea * GuiView::currentMainWorkArea()
1274 if (!d.currentTabWorkArea())
1276 return d.currentTabWorkArea()->currentWorkArea();
1280 void GuiView::setCurrentWorkArea(GuiWorkArea * wa)
1282 LYXERR(Debug::DEBUG, "Setting current wa: " << wa << endl);
1284 d.current_work_area_ = 0;
1289 // FIXME: I've no clue why this is here and why it accesses
1290 // theGuiApp()->currentView, which might be 0 (bug 6464).
1291 // See also 27525 (vfr).
1292 if (theGuiApp()->currentView() == this
1293 && theGuiApp()->currentView()->currentWorkArea() == wa)
1296 if (currentBufferView())
1297 cap::saveSelection(currentBufferView()->cursor());
1299 theGuiApp()->setCurrentView(this);
1300 d.current_work_area_ = wa;
1302 // We need to reset this now, because it will need to be
1303 // right if the tabWorkArea gets reset in the for loop. We
1304 // will change it back if we aren't in that case.
1305 GuiWorkArea * const old_cmwa = d.current_main_work_area_;
1306 d.current_main_work_area_ = wa;
1308 for (int i = 0; i != d.splitter_->count(); ++i) {
1309 if (d.tabWorkArea(i)->setCurrentWorkArea(wa)) {
1310 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea()
1311 << ", Current main wa: " << currentMainWorkArea());
1316 d.current_main_work_area_ = old_cmwa;
1318 LYXERR(Debug::DEBUG, "This is not a tabbed wa");
1319 on_currentWorkAreaChanged(wa);
1320 BufferView & bv = wa->bufferView();
1321 bv.cursor().fixIfBroken();
1323 wa->setUpdatesEnabled(true);
1324 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() << ", Current main wa: " << currentMainWorkArea());
1328 void GuiView::removeWorkArea(GuiWorkArea * wa)
1330 LASSERT(wa, return);
1331 if (wa == d.current_work_area_) {
1333 disconnectBufferView();
1334 d.current_work_area_ = 0;
1335 d.current_main_work_area_ = 0;
1338 bool found_twa = false;
1339 for (int i = 0; i != d.splitter_->count(); ++i) {
1340 TabWorkArea * twa = d.tabWorkArea(i);
1341 if (twa->removeWorkArea(wa)) {
1342 // Found in this tab group, and deleted the GuiWorkArea.
1344 if (twa->count() != 0) {
1345 if (d.current_work_area_ == 0)
1346 // This means that we are closing the current GuiWorkArea, so
1347 // switch to the next GuiWorkArea in the found TabWorkArea.
1348 setCurrentWorkArea(twa->currentWorkArea());
1350 // No more WorkAreas in this tab group, so delete it.
1357 // It is not a tabbed work area (i.e., the search work area), so it
1358 // should be deleted by other means.
1359 LASSERT(found_twa, /* */);
1361 if (d.current_work_area_ == 0) {
1362 if (d.splitter_->count() != 0) {
1363 TabWorkArea * twa = d.currentTabWorkArea();
1364 setCurrentWorkArea(twa->currentWorkArea());
1366 // No more work areas, switch to the background widget.
1367 setCurrentWorkArea(0);
1373 LayoutBox * GuiView::getLayoutDialog() const
1379 void GuiView::updateLayoutList()
1382 d.layout_->updateContents(false);
1386 void GuiView::updateToolbars()
1388 ToolbarMap::iterator end = d.toolbars_.end();
1389 if (d.current_work_area_) {
1391 d.current_work_area_->bufferView().cursor().inMathed()
1392 && !d.current_work_area_->bufferView().cursor().inRegexped();
1394 lyx::getStatus(FuncRequest(LFUN_LAYOUT_TABULAR)).enabled();
1396 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).enabled() &&
1397 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).onOff(true);
1398 bool const mathmacrotemplate =
1399 lyx::getStatus(FuncRequest(LFUN_IN_MATHMACROTEMPLATE)).enabled();
1401 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1402 it->second->update(math, table, review, mathmacrotemplate);
1404 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1405 it->second->update(false, false, false, false);
1409 void GuiView::setBuffer(Buffer * newBuffer)
1411 LYXERR(Debug::DEBUG, "Setting buffer: " << newBuffer << endl);
1412 LASSERT(newBuffer, return);
1414 GuiWorkArea * wa = workArea(*newBuffer);
1417 newBuffer->masterBuffer()->updateBuffer();
1419 wa = addWorkArea(*newBuffer);
1420 // scroll to the position when the BufferView was last closed
1421 if (lyxrc.use_lastfilepos) {
1422 LastFilePosSection::FilePos filepos =
1423 theSession().lastFilePos().load(newBuffer->fileName());
1424 wa->bufferView().moveToPosition(filepos.pit, filepos.pos, 0, 0);
1427 //Disconnect the old buffer...there's no new one.
1430 connectBuffer(*newBuffer);
1431 connectBufferView(wa->bufferView());
1432 setCurrentWorkArea(wa);
1436 void GuiView::connectBuffer(Buffer & buf)
1438 buf.setGuiDelegate(this);
1442 void GuiView::disconnectBuffer()
1444 if (d.current_work_area_)
1445 d.current_work_area_->bufferView().buffer().setGuiDelegate(0);
1449 void GuiView::connectBufferView(BufferView & bv)
1451 bv.setGuiDelegate(this);
1455 void GuiView::disconnectBufferView()
1457 if (d.current_work_area_)
1458 d.current_work_area_->bufferView().setGuiDelegate(0);
1462 void GuiView::errors(string const & error_type, bool from_master)
1464 BufferView const * const bv = currentBufferView();
1468 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
1469 // We are called with from_master == false by default, so we
1470 // have to figure out whether that is the case or not.
1471 ErrorList & el = bv->buffer().errorList(error_type);
1473 el = bv->buffer().masterBuffer()->errorList(error_type);
1477 ErrorList const & el = from_master ?
1478 bv->buffer().masterBuffer()->errorList(error_type) :
1479 bv->buffer().errorList(error_type);
1485 string data = error_type;
1487 data = "from_master|" + error_type;
1488 showDialog("errorlist", data);
1492 void GuiView::updateTocItem(string const & type, DocIterator const & dit)
1494 d.toc_models_.updateItem(toqstr(type), dit);
1498 void GuiView::structureChanged()
1500 d.toc_models_.reset(documentBufferView());
1501 // Navigator needs more than a simple update in this case. It needs to be
1503 updateDialog("toc", "");
1507 void GuiView::updateDialog(string const & name, string const & data)
1509 if (!isDialogVisible(name))
1512 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
1513 if (it == d.dialogs_.end())
1516 Dialog * const dialog = it->second.get();
1517 if (dialog->isVisibleView())
1518 dialog->initialiseParams(data);
1522 BufferView * GuiView::documentBufferView()
1524 return currentMainWorkArea()
1525 ? ¤tMainWorkArea()->bufferView()
1530 BufferView const * GuiView::documentBufferView() const
1532 return currentMainWorkArea()
1533 ? ¤tMainWorkArea()->bufferView()
1538 BufferView * GuiView::currentBufferView()
1540 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1544 BufferView const * GuiView::currentBufferView() const
1546 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1550 #if (QT_VERSION >= 0x040400)
1551 docstring GuiView::GuiViewPrivate::autosaveAndDestroy(
1552 Buffer const * orig, Buffer * buffer)
1554 bool const success = buffer->autoSave();
1556 busyBuffers.remove(orig);
1558 ? _("Automatic save done.")
1559 : _("Automatic save failed!");
1564 void GuiView::autoSave()
1566 LYXERR(Debug::INFO, "Running autoSave()");
1568 Buffer * buffer = documentBufferView()
1569 ? &documentBufferView()->buffer() : 0;
1571 resetAutosaveTimers();
1575 #if (QT_VERSION >= 0x040400)
1576 GuiViewPrivate::busyBuffers.insert(buffer);
1577 QFuture<docstring> f = QtConcurrent::run(GuiViewPrivate::autosaveAndDestroy,
1578 buffer, buffer->clone());
1579 d.autosave_watcher_.setFuture(f);
1583 resetAutosaveTimers();
1587 void GuiView::resetAutosaveTimers()
1590 d.autosave_timeout_.restart();
1594 bool GuiView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1597 Buffer * buf = currentBufferView()
1598 ? ¤tBufferView()->buffer() : 0;
1599 Buffer * doc_buffer = documentBufferView()
1600 ? &(documentBufferView()->buffer()) : 0;
1602 // Check whether we need a buffer
1603 if (!lyxaction.funcHasFlag(cmd.action(), LyXAction::NoBuffer) && !buf) {
1604 // no, exit directly
1605 flag.message(from_utf8(N_("Command not allowed with"
1606 "out any document open")));
1607 flag.setEnabled(false);
1611 if (cmd.origin() == FuncRequest::TOC) {
1612 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
1613 if (!toc || !toc->getStatus(documentBufferView()->cursor(), cmd, flag))
1614 flag.setEnabled(false);
1618 switch(cmd.action()) {
1619 case LFUN_BUFFER_IMPORT:
1622 case LFUN_MASTER_BUFFER_UPDATE:
1623 case LFUN_MASTER_BUFFER_VIEW:
1624 enable = doc_buffer && doc_buffer->parent() != 0
1625 && !d.processing_thread_watcher_.isRunning();
1628 case LFUN_BUFFER_UPDATE:
1629 case LFUN_BUFFER_VIEW: {
1630 if (!doc_buffer || d.processing_thread_watcher_.isRunning()) {
1634 string format = to_utf8(cmd.argument());
1635 if (cmd.argument().empty())
1636 format = doc_buffer->params().getDefaultOutputFormat();
1637 enable = doc_buffer->params().isExportableFormat(format);
1641 case LFUN_BUFFER_RELOAD:
1642 enable = doc_buffer && !doc_buffer->isUnnamed()
1643 && doc_buffer->fileName().exists()
1644 && (!doc_buffer->isClean()
1645 || doc_buffer->isExternallyModified(Buffer::timestamp_method));
1648 case LFUN_BUFFER_CHILD_OPEN:
1649 enable = doc_buffer;
1652 case LFUN_BUFFER_WRITE:
1653 enable = doc_buffer && (doc_buffer->isUnnamed() || !doc_buffer->isClean());
1656 //FIXME: This LFUN should be moved to GuiApplication.
1657 case LFUN_BUFFER_WRITE_ALL: {
1658 // We enable the command only if there are some modified buffers
1659 Buffer * first = theBufferList().first();
1664 // We cannot use a for loop as the buffer list is a cycle.
1666 if (!b->isClean()) {
1670 b = theBufferList().next(b);
1671 } while (b != first);
1675 case LFUN_BUFFER_WRITE_AS:
1676 case LFUN_BUFFER_EXPORT_AS:
1677 enable = doc_buffer;
1680 case LFUN_BUFFER_CLOSE:
1681 enable = doc_buffer;
1684 case LFUN_BUFFER_CLOSE_ALL:
1685 enable = theBufferList().last() != theBufferList().first();
1688 case LFUN_SPLIT_VIEW:
1689 if (cmd.getArg(0) == "vertical")
1690 enable = doc_buffer && (d.splitter_->count() == 1 ||
1691 d.splitter_->orientation() == Qt::Vertical);
1693 enable = doc_buffer && (d.splitter_->count() == 1 ||
1694 d.splitter_->orientation() == Qt::Horizontal);
1697 case LFUN_CLOSE_TAB_GROUP:
1698 enable = d.currentTabWorkArea();
1701 case LFUN_TOOLBAR_TOGGLE: {
1702 string const name = cmd.getArg(0);
1703 if (GuiToolbar * t = toolbar(name))
1704 flag.setOnOff(t->isVisible());
1707 docstring const msg =
1708 bformat(_("Unknown toolbar \"%1$s\""), from_utf8(name));
1714 case LFUN_DROP_LAYOUTS_CHOICE:
1718 case LFUN_UI_TOGGLE:
1719 flag.setOnOff(isFullScreen());
1722 case LFUN_DIALOG_DISCONNECT_INSET:
1725 case LFUN_DIALOG_HIDE:
1726 // FIXME: should we check if the dialog is shown?
1729 case LFUN_DIALOG_TOGGLE:
1730 flag.setOnOff(isDialogVisible(cmd.getArg(0)));
1731 // fall through to set "enable"
1732 case LFUN_DIALOG_SHOW: {
1733 string const name = cmd.getArg(0);
1735 enable = name == "aboutlyx"
1736 || name == "file" //FIXME: should be removed.
1738 || name == "texinfo"
1739 || name == "progress"
1740 || name == "compare";
1741 else if (name == "print")
1742 enable = doc_buffer->params().isExportable("dvi")
1743 && lyxrc.print_command != "none";
1744 else if (name == "character" || name == "symbols") {
1745 if (!buf || buf->isReadonly())
1748 Cursor const & cur = currentBufferView()->cursor();
1749 enable = !(cur.inTexted() && cur.paragraph().isPassThru());
1752 else if (name == "latexlog")
1753 enable = FileName(doc_buffer->logName()).isReadableFile();
1754 else if (name == "spellchecker")
1755 enable = theSpellChecker() && !doc_buffer->isReadonly();
1756 else if (name == "vclog")
1757 enable = doc_buffer->lyxvc().inUse();
1761 case LFUN_DIALOG_UPDATE: {
1762 string const name = cmd.getArg(0);
1764 enable = name == "prefs";
1768 case LFUN_COMMAND_EXECUTE:
1770 case LFUN_MENU_OPEN:
1771 // Nothing to check.
1774 case LFUN_COMPLETION_INLINE:
1775 if (!d.current_work_area_
1776 || !d.current_work_area_->completer().inlinePossible(
1777 currentBufferView()->cursor()))
1781 case LFUN_COMPLETION_POPUP:
1782 if (!d.current_work_area_
1783 || !d.current_work_area_->completer().popupPossible(
1784 currentBufferView()->cursor()))
1788 case LFUN_COMPLETION_COMPLETE:
1789 if (!d.current_work_area_
1790 || !d.current_work_area_->completer().inlinePossible(
1791 currentBufferView()->cursor()))
1795 case LFUN_COMPLETION_ACCEPT:
1796 if (!d.current_work_area_
1797 || (!d.current_work_area_->completer().popupVisible()
1798 && !d.current_work_area_->completer().inlineVisible()
1799 && !d.current_work_area_->completer().completionAvailable()))
1803 case LFUN_COMPLETION_CANCEL:
1804 if (!d.current_work_area_
1805 || (!d.current_work_area_->completer().popupVisible()
1806 && !d.current_work_area_->completer().inlineVisible()))
1810 case LFUN_BUFFER_ZOOM_OUT:
1811 enable = doc_buffer && lyxrc.zoom > 10;
1814 case LFUN_BUFFER_ZOOM_IN:
1815 enable = doc_buffer;
1818 case LFUN_BUFFER_NEXT:
1819 case LFUN_BUFFER_PREVIOUS:
1820 // FIXME: should we check is there is an previous or next buffer?
1822 case LFUN_BUFFER_SWITCH:
1823 // toggle on the current buffer, but do not toggle off
1824 // the other ones (is that a good idea?)
1826 && to_utf8(cmd.argument()) == doc_buffer->absFileName())
1827 flag.setOnOff(true);
1830 case LFUN_VC_REGISTER:
1831 enable = doc_buffer && !doc_buffer->lyxvc().inUse();
1833 case LFUN_VC_CHECK_IN:
1834 enable = doc_buffer && doc_buffer->lyxvc().checkInEnabled();
1836 case LFUN_VC_CHECK_OUT:
1837 enable = doc_buffer && doc_buffer->lyxvc().checkOutEnabled();
1839 case LFUN_VC_LOCKING_TOGGLE:
1840 enable = doc_buffer && !doc_buffer->isReadonly()
1841 && doc_buffer->lyxvc().lockingToggleEnabled();
1842 flag.setOnOff(enable && doc_buffer->lyxvc().locking());
1844 case LFUN_VC_REVERT:
1845 enable = doc_buffer && doc_buffer->lyxvc().inUse() && !doc_buffer->isReadonly();
1847 case LFUN_VC_UNDO_LAST:
1848 enable = doc_buffer && doc_buffer->lyxvc().undoLastEnabled();
1850 case LFUN_VC_REPO_UPDATE:
1851 enable = doc_buffer && doc_buffer->lyxvc().repoUpdateEnabled();
1853 case LFUN_VC_COMMAND: {
1854 if (cmd.argument().empty())
1856 if (!doc_buffer && contains(cmd.getArg(0), 'D'))
1860 case LFUN_VC_COMPARE:
1861 enable = doc_buffer && doc_buffer->lyxvc().prepareFileRevisionEnabled();
1864 case LFUN_SERVER_GOTO_FILE_ROW:
1866 case LFUN_FORWARD_SEARCH:
1867 enable = !(lyxrc.forward_search_dvi.empty() && lyxrc.forward_search_pdf.empty());
1875 flag.setEnabled(false);
1881 static FileName selectTemplateFile()
1883 FileDialog dlg(qt_("Select template file"));
1884 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1885 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
1887 FileDialog::Result result = dlg.open(toqstr(lyxrc.template_path),
1888 QStringList(qt_("LyX Documents (*.lyx)")));
1890 if (result.first == FileDialog::Later)
1892 if (result.second.isEmpty())
1894 return FileName(fromqstr(result.second));
1898 Buffer * GuiView::loadDocument(FileName const & filename, bool tolastfiles)
1902 Buffer * newBuffer = 0;
1904 newBuffer = checkAndLoadLyXFile(filename);
1905 } catch (ExceptionMessage const & e) {
1912 message(_("Document not loaded."));
1916 setBuffer(newBuffer);
1917 newBuffer->errors("Parse");
1920 theSession().lastFiles().add(filename);
1926 void GuiView::openDocument(string const & fname)
1928 string initpath = lyxrc.document_path;
1930 if (documentBufferView()) {
1931 string const trypath = documentBufferView()->buffer().filePath();
1932 // If directory is writeable, use this as default.
1933 if (FileName(trypath).isDirWritable())
1939 if (fname.empty()) {
1940 FileDialog dlg(qt_("Select document to open"), LFUN_FILE_OPEN);
1941 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1942 dlg.setButton2(qt_("Examples|#E#e"),
1943 toqstr(addPath(package().system_support().absFileName(), "examples")));
1945 QStringList filter(qt_("LyX Documents (*.lyx)"));
1946 filter << qt_("LyX-1.3.x Documents (*.lyx13)")
1947 << qt_("LyX-1.4.x Documents (*.lyx14)")
1948 << qt_("LyX-1.5.x Documents (*.lyx15)")
1949 << qt_("LyX-1.6.x Documents (*.lyx16)");
1950 FileDialog::Result result =
1951 dlg.open(toqstr(initpath), filter);
1953 if (result.first == FileDialog::Later)
1956 filename = fromqstr(result.second);
1958 // check selected filename
1959 if (filename.empty()) {
1960 message(_("Canceled."));
1966 // get absolute path of file and add ".lyx" to the filename if
1968 FileName const fullname =
1969 fileSearch(string(), filename, "lyx", support::may_not_exist);
1970 if (!fullname.empty())
1971 filename = fullname.absFileName();
1973 if (!fullname.onlyPath().isDirectory()) {
1974 Alert::warning(_("Invalid filename"),
1975 bformat(_("The directory in the given path\n%1$s\ndoes not exist."),
1976 from_utf8(fullname.absFileName())));
1980 // if the file doesn't exist and isn't already open (bug 6645),
1981 // let the user create one
1982 if (!fullname.exists() && !theBufferList().exists(fullname)) {
1983 // the user specifically chose this name. Believe him.
1984 Buffer * const b = newFile(filename, string(), true);
1990 docstring const disp_fn = makeDisplayPath(filename);
1991 message(bformat(_("Opening document %1$s..."), disp_fn));
1994 Buffer * buf = loadDocument(fullname);
1996 str2 = bformat(_("Document %1$s opened."), disp_fn);
1997 if (buf->lyxvc().inUse())
1998 str2 += " " + from_utf8(buf->lyxvc().versionString()) +
1999 " " + _("Version control detected.");
2001 str2 = bformat(_("Could not open document %1$s"), disp_fn);
2006 // FIXME: clean that
2007 static bool import(GuiView * lv, FileName const & filename,
2008 string const & format, ErrorList & errorList)
2010 FileName const lyxfile(support::changeExtension(filename.absFileName(), ".lyx"));
2012 string loader_format;
2013 vector<string> loaders = theConverters().loaders();
2014 if (find(loaders.begin(), loaders.end(), format) == loaders.end()) {
2015 for (vector<string>::const_iterator it = loaders.begin();
2016 it != loaders.end(); ++it) {
2017 if (!theConverters().isReachable(format, *it))
2020 string const tofile =
2021 support::changeExtension(filename.absFileName(),
2022 formats.extension(*it));
2023 if (!theConverters().convert(0, filename, FileName(tofile),
2024 filename, format, *it, errorList))
2026 loader_format = *it;
2029 if (loader_format.empty()) {
2030 frontend::Alert::error(_("Couldn't import file"),
2031 bformat(_("No information for importing the format %1$s."),
2032 formats.prettyName(format)));
2036 loader_format = format;
2038 if (loader_format == "lyx") {
2039 Buffer * buf = lv->loadDocument(lyxfile);
2043 Buffer * const b = newFile(lyxfile.absFileName(), string(), true);
2047 bool as_paragraphs = loader_format == "textparagraph";
2048 string filename2 = (loader_format == format) ? filename.absFileName()
2049 : support::changeExtension(filename.absFileName(),
2050 formats.extension(loader_format));
2051 lv->currentBufferView()->insertPlaintextFile(FileName(filename2),
2053 guiApp->setCurrentView(lv);
2054 lyx::dispatch(FuncRequest(LFUN_MARK_OFF));
2061 void GuiView::importDocument(string const & argument)
2064 string filename = split(argument, format, ' ');
2066 LYXERR(Debug::INFO, format << " file: " << filename);
2068 // need user interaction
2069 if (filename.empty()) {
2070 string initpath = lyxrc.document_path;
2071 if (documentBufferView()) {
2072 string const trypath = documentBufferView()->buffer().filePath();
2073 // If directory is writeable, use this as default.
2074 if (FileName(trypath).isDirWritable())
2078 docstring const text = bformat(_("Select %1$s file to import"),
2079 formats.prettyName(format));
2081 FileDialog dlg(toqstr(text), LFUN_BUFFER_IMPORT);
2082 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2083 dlg.setButton2(qt_("Examples|#E#e"),
2084 toqstr(addPath(package().system_support().absFileName(), "examples")));
2086 docstring filter = formats.prettyName(format);
2089 filter += from_utf8(formats.extensions(format));
2092 FileDialog::Result result =
2093 dlg.open(toqstr(initpath), fileFilters(toqstr(filter)));
2095 if (result.first == FileDialog::Later)
2098 filename = fromqstr(result.second);
2100 // check selected filename
2101 if (filename.empty())
2102 message(_("Canceled."));
2105 if (filename.empty())
2108 // get absolute path of file
2109 FileName const fullname(support::makeAbsPath(filename));
2111 FileName const lyxfile(support::changeExtension(fullname.absFileName(), ".lyx"));
2113 // Check if the document already is open
2114 Buffer * buf = theBufferList().getBuffer(lyxfile);
2117 if (!closeBuffer()) {
2118 message(_("Canceled."));
2123 docstring const displaypath = makeDisplayPath(lyxfile.absFileName(), 30);
2125 // if the file exists already, and we didn't do
2126 // -i lyx thefile.lyx, warn
2127 if (lyxfile.exists() && fullname != lyxfile) {
2129 docstring text = bformat(_("The document %1$s already exists.\n\n"
2130 "Do you want to overwrite that document?"), displaypath);
2131 int const ret = Alert::prompt(_("Overwrite document?"),
2132 text, 0, 1, _("&Overwrite"), _("&Cancel"));
2135 message(_("Canceled."));
2140 message(bformat(_("Importing %1$s..."), displaypath));
2141 ErrorList errorList;
2142 if (import(this, fullname, format, errorList))
2143 message(_("imported."));
2145 message(_("file not imported!"));
2147 // FIXME (Abdel 12/08/06): Is there a need to display the error list here?
2151 void GuiView::newDocument(string const & filename, bool from_template)
2153 FileName initpath(lyxrc.document_path);
2154 if (documentBufferView()) {
2155 FileName const trypath(documentBufferView()->buffer().filePath());
2156 // If directory is writeable, use this as default.
2157 if (trypath.isDirWritable())
2161 string templatefile;
2162 if (from_template) {
2163 templatefile = selectTemplateFile().absFileName();
2164 if (templatefile.empty())
2169 if (filename.empty())
2170 b = newUnnamedFile(initpath, to_utf8(_("newfile")), templatefile);
2172 b = newFile(filename, templatefile, true);
2177 // If no new document could be created, it is unsure
2178 // whether there is a valid BufferView.
2179 if (currentBufferView())
2180 // Ensure the cursor is correctly positioned on screen.
2181 currentBufferView()->showCursor();
2185 void GuiView::insertLyXFile(docstring const & fname)
2187 BufferView * bv = documentBufferView();
2192 FileName filename(to_utf8(fname));
2193 if (filename.empty()) {
2194 // Launch a file browser
2196 string initpath = lyxrc.document_path;
2197 string const trypath = bv->buffer().filePath();
2198 // If directory is writeable, use this as default.
2199 if (FileName(trypath).isDirWritable())
2203 FileDialog dlg(qt_("Select LyX document to insert"), LFUN_FILE_INSERT);
2204 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2205 dlg.setButton2(qt_("Examples|#E#e"),
2206 toqstr(addPath(package().system_support().absFileName(),
2209 FileDialog::Result result = dlg.open(toqstr(initpath),
2210 QStringList(qt_("LyX Documents (*.lyx)")));
2212 if (result.first == FileDialog::Later)
2216 filename.set(fromqstr(result.second));
2218 // check selected filename
2219 if (filename.empty()) {
2220 // emit message signal.
2221 message(_("Canceled."));
2226 bv->insertLyXFile(filename);
2227 bv->buffer().errors("Parse");
2231 void GuiView::insertPlaintextFile(docstring const & fname,
2234 BufferView * bv = documentBufferView();
2238 if (!fname.empty() && !FileName::isAbsolute(to_utf8(fname))) {
2239 message(_("Absolute filename expected."));
2244 FileName filename(to_utf8(fname));
2246 if (!filename.empty()) {
2247 bv->insertPlaintextFile(filename, asParagraph);
2251 FileDialog dlg(qt_("Select file to insert"), (asParagraph ?
2252 LFUN_FILE_INSERT_PLAINTEXT_PARA : LFUN_FILE_INSERT_PLAINTEXT));
2254 FileDialog::Result result = dlg.open(toqstr(bv->buffer().filePath()),
2255 QStringList(qt_("All Files (*)")));
2257 if (result.first == FileDialog::Later)
2261 filename.set(fromqstr(result.second));
2263 // check selected filename
2264 if (filename.empty()) {
2265 // emit message signal.
2266 message(_("Canceled."));
2270 bv->insertPlaintextFile(filename, asParagraph);
2274 bool GuiView::renameBuffer(Buffer & b, docstring const & newname)
2276 FileName fname = b.fileName();
2277 FileName const oldname = fname;
2279 if (!newname.empty()) {
2281 fname = support::makeAbsPath(to_utf8(newname), oldname.onlyPath().absFileName());
2283 // Switch to this Buffer.
2286 // No argument? Ask user through dialog.
2288 FileDialog dlg(qt_("Choose a filename to save document as"),
2289 LFUN_BUFFER_WRITE_AS);
2290 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2291 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
2293 if (!isLyXFileName(fname.absFileName()))
2294 fname.changeExtension(".lyx");
2296 FileDialog::Result result =
2297 dlg.save(toqstr(fname.onlyPath().absFileName()),
2298 QStringList(qt_("LyX Documents (*.lyx)")),
2299 toqstr(fname.onlyFileName()));
2301 if (result.first == FileDialog::Later)
2304 fname.set(fromqstr(result.second));
2309 if (!isLyXFileName(fname.absFileName()))
2310 fname.changeExtension(".lyx");
2313 // fname is now the new Buffer location.
2314 if (FileName(fname).exists()) {
2315 docstring const file = makeDisplayPath(fname.absFileName(), 30);
2316 docstring text = bformat(_("The document %1$s already "
2317 "exists.\n\nDo you want to "
2318 "overwrite that document?"),
2320 int const ret = Alert::prompt(_("Overwrite document?"),
2321 text, 0, 2, _("&Overwrite"), _("&Rename"), _("&Cancel"));
2324 case 1: return renameBuffer(b, docstring());
2325 case 2: return false;
2329 return saveBuffer(b, fname);
2333 struct PrettyNameComparator
2335 bool operator()(Format const *first, Format const *second) const {
2336 return compare_ascii_no_case(first->prettyname(), second->prettyname()) <= 0;
2341 bool GuiView::exportBufferAs(Buffer & b)
2343 FileName fname = b.fileName();
2345 FileDialog dlg(qt_("Choose a filename to export the document as"));
2346 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2349 types << "Any supported format (*.*)";
2350 Formats::const_iterator it = formats.begin();
2351 vector<Format const *> export_formats;
2352 for (; it != formats.end(); ++it)
2353 if (it->documentFormat() && it->inExportMenu())
2354 export_formats.push_back(&(*it));
2355 PrettyNameComparator cmp;
2356 sort(export_formats.begin(), export_formats.end(), cmp);
2357 vector<Format const *>::const_iterator fit = export_formats.begin();
2358 for (; fit != export_formats.end(); ++fit)
2359 types << toqstr((*fit)->prettyname() + " (*." + (*fit)->extension() + ")");
2361 FileDialog::Result result =
2362 dlg.save(toqstr(fname.onlyPath().absFileName()),
2364 toqstr(fname.onlyFileName()),
2366 if (result.first != FileDialog::Chosen)
2369 string s = fromqstr(filter);
2370 size_t pos = s.find(" (*.");
2371 LASSERT(pos != string::npos, /**/);
2372 string fmt_prettyname = s.substr(0, pos);
2374 fname.set(fromqstr(result.second));
2375 if (fmt_prettyname == "Any supported format")
2376 fmt_name = formats.getFormatFromExtension(fname.extension());
2378 fmt_name = formats.getFormatFromPrettyName(fmt_prettyname);
2379 LYXERR(Debug::FILES, "fmt_prettyname=" << fmt_prettyname
2380 << ", fmt_name=" << fmt_name << ", fname=" << fname.absFileName());
2382 if (fmt_name.empty() || fname.empty())
2385 // fname is now the new Buffer location.
2386 if (FileName(fname).exists()) {
2387 docstring const file = makeDisplayPath(fname.absFileName(), 30);
2388 docstring text = bformat(_("The document %1$s already "
2389 "exists.\n\nDo you want to "
2390 "overwrite that document?"),
2392 int const ret = Alert::prompt(_("Overwrite document?"),
2393 text, 0, 2, _("&Overwrite"), _("&Rename"), _("&Cancel"));
2396 case 1: return exportBufferAs(b);
2397 case 2: return false;
2401 FuncRequest cmd(LFUN_BUFFER_EXPORT, fmt_name + " " + fname.absFileName());
2404 return dr.dispatched();
2408 bool GuiView::saveBuffer(Buffer & b) {
2409 return saveBuffer(b, FileName());
2413 bool GuiView::saveBuffer(Buffer & b, FileName const & fn)
2415 if (workArea(b) && workArea(b)->inDialogMode())
2418 if (fn.empty() && b.isUnnamed())
2419 return renameBuffer(b, docstring());
2425 success = b.saveAs(fn);
2428 theSession().lastFiles().add(b.fileName());
2432 // Switch to this Buffer.
2435 // FIXME: we don't tell the user *WHY* the save failed !!
2436 docstring const file = makeDisplayPath(b.absFileName(), 30);
2437 docstring text = bformat(_("The document %1$s could not be saved.\n\n"
2438 "Do you want to rename the document and "
2439 "try again?"), file);
2440 int const ret = Alert::prompt(_("Rename and save?"),
2441 text, 0, 2, _("&Rename"), _("&Retry"), _("&Cancel"));
2444 if (!renameBuffer(b, docstring()))
2453 return saveBuffer(b);
2457 bool GuiView::hideWorkArea(GuiWorkArea * wa)
2459 return closeWorkArea(wa, false);
2463 bool GuiView::closeWorkArea(GuiWorkArea * wa)
2465 Buffer & buf = wa->bufferView().buffer();
2466 return closeWorkArea(wa, !buf.parent());
2470 bool GuiView::closeBuffer()
2472 GuiWorkArea * wa = currentMainWorkArea();
2473 setCurrentWorkArea(wa);
2474 Buffer & buf = wa->bufferView().buffer();
2475 return wa && closeWorkArea(wa, !buf.parent());
2479 void GuiView::writeSession() const {
2480 GuiWorkArea const * active_wa = currentMainWorkArea();
2481 for (int i = 0; i < d.splitter_->count(); ++i) {
2482 TabWorkArea * twa = d.tabWorkArea(i);
2483 for (int j = 0; j < twa->count(); ++j) {
2484 GuiWorkArea * wa = static_cast<GuiWorkArea *>(twa->widget(j));
2485 Buffer & buf = wa->bufferView().buffer();
2486 theSession().lastOpened().add(buf.fileName(), wa == active_wa);
2492 bool GuiView::closeBufferAll()
2494 // Close the workareas in all other views
2495 QList<int> const ids = guiApp->viewIds();
2496 for (int i = 0; i != ids.size(); ++i) {
2497 if (id_ != ids[i] && !guiApp->view(ids[i]).closeWorkAreaAll())
2501 // Close our own workareas
2502 if (!closeWorkAreaAll())
2505 // Now close the hidden buffers. We prevent hidden buffers from being
2506 // dirty, so we can just close them.
2507 theBufferList().closeAll();
2512 bool GuiView::closeWorkAreaAll()
2514 setCurrentWorkArea(currentMainWorkArea());
2516 // We might be in a situation that there is still a tabWorkArea, but
2517 // there are no tabs anymore. This can happen when we get here after a
2518 // TabWorkArea::lastWorkAreaRemoved() signal. Therefore we count how
2519 // many TabWorkArea's have no documents anymore.
2522 // We have to call count() each time, because it can happen that
2523 // more than one splitter will disappear in one iteration (bug 5998).
2524 for (; d.splitter_->count() > empty_twa; ) {
2525 TabWorkArea * twa = d.tabWorkArea(empty_twa);
2527 if (twa->count() == 0)
2530 setCurrentWorkArea(twa->currentWorkArea());
2531 if (!closeTabWorkArea(twa))
2539 bool GuiView::closeWorkArea(GuiWorkArea * wa, bool close_buffer)
2544 Buffer & buf = wa->bufferView().buffer();
2546 if (close_buffer && GuiViewPrivate::busyBuffers.contains(&buf)) {
2547 Alert::warning(_("Close document"),
2548 _("Document could not be closed because it is being processed by LyX."));
2553 return closeBuffer(buf);
2555 if (!inMultiTabs(wa))
2556 if (!saveBufferIfNeeded(buf, true))
2564 bool GuiView::closeBuffer(Buffer & buf)
2566 // If we are in a close_event all children will be closed in some time,
2567 // so no need to do it here. This will ensure that the children end up
2568 // in the session file in the correct order. If we close the master
2569 // buffer, we can close or release the child buffers here too.
2570 bool success = true;
2572 ListOfBuffers clist = buf.getChildren();
2573 ListOfBuffers::const_iterator it = clist.begin();
2574 ListOfBuffers::const_iterator const bend = clist.end();
2575 for (; it != bend; ++it) {
2576 // If a child is dirty, do not close
2577 // without user intervention
2578 //FIXME: should we look in other tabworkareas?
2579 Buffer * child_buf = *it;
2580 GuiWorkArea * child_wa = workArea(*child_buf);
2582 if (!closeWorkArea(child_wa, true)) {
2587 theBufferList().releaseChild(&buf, child_buf);
2591 // goto bookmark to update bookmark pit.
2592 //FIXME: we should update only the bookmarks related to this buffer!
2593 LYXERR(Debug::DEBUG, "GuiView::closeBuffer()");
2594 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
2595 guiApp->gotoBookmark(i+1, false, false);
2597 if (saveBufferIfNeeded(buf, false)) {
2598 buf.removeAutosaveFile();
2599 theBufferList().release(&buf);
2603 // open all children again to avoid a crash because of dangling
2604 // pointers (bug 6603)
2610 bool GuiView::closeTabWorkArea(TabWorkArea * twa)
2612 while (twa == d.currentTabWorkArea()) {
2613 twa->setCurrentIndex(twa->count()-1);
2615 GuiWorkArea * wa = twa->currentWorkArea();
2616 Buffer & b = wa->bufferView().buffer();
2618 // We only want to close the buffer if the same buffer is not visible
2619 // in another view, and if this is not a child and if we are closing
2620 // a view (not a tabgroup).
2621 bool const close_buffer =
2622 !inOtherView(b) && !b.parent() && closing_;
2624 if (!closeWorkArea(wa, close_buffer))
2631 bool GuiView::saveBufferIfNeeded(Buffer & buf, bool hiding)
2633 if (buf.isClean() || buf.paragraphs().empty())
2636 // Switch to this Buffer.
2641 if (buf.isUnnamed())
2642 file = from_utf8(buf.fileName().onlyFileName());
2644 file = buf.fileName().displayName(30);
2646 // Bring this window to top before asking questions.
2651 if (hiding && buf.isUnnamed()) {
2652 docstring const text = bformat(_("The document %1$s has not been "
2653 "saved yet.\n\nDo you want to save "
2654 "the document?"), file);
2655 ret = Alert::prompt(_("Save new document?"),
2656 text, 0, 1, _("&Save"), _("&Cancel"));
2660 docstring const text = bformat(_("The document %1$s has unsaved changes."
2661 "\n\nDo you want to save the document or discard the changes?"), file);
2662 ret = Alert::prompt(_("Save changed document?"),
2663 text, 0, 2, _("&Save"), _("&Discard"), _("&Cancel"));
2668 if (!saveBuffer(buf))
2672 // If we crash after this we could have no autosave file
2673 // but I guess this is really improbable (Jug).
2674 // Sometimes improbable things happen:
2675 // - see bug http://www.lyx.org/trac/ticket/6587 (ps)
2676 // buf.removeAutosaveFile();
2678 // revert all changes
2689 bool GuiView::inMultiTabs(GuiWorkArea * wa)
2691 Buffer & buf = wa->bufferView().buffer();
2693 for (int i = 0; i != d.splitter_->count(); ++i) {
2694 GuiWorkArea * wa_ = d.tabWorkArea(i)->workArea(buf);
2695 if (wa_ && wa_ != wa)
2698 return inOtherView(buf);
2702 bool GuiView::inOtherView(Buffer & buf)
2704 QList<int> const ids = guiApp->viewIds();
2706 for (int i = 0; i != ids.size(); ++i) {
2710 if (guiApp->view(ids[i]).workArea(buf))
2717 void GuiView::gotoNextOrPreviousBuffer(NextOrPrevious np)
2719 if (!documentBufferView())
2722 if (TabWorkArea * twa = d.currentTabWorkArea()) {
2723 Buffer * const curbuf = &documentBufferView()->buffer();
2724 int nwa = twa->count();
2725 for (int i = 0; i < nwa; ++i) {
2726 if (&workArea(i)->bufferView().buffer() == curbuf) {
2728 if (np == NEXTBUFFER)
2729 next_index = (i == nwa - 1 ? 0 : i + 1);
2731 next_index = (i == 0 ? nwa - 1 : i - 1);
2732 setBuffer(&workArea(next_index)->bufferView().buffer());
2740 /// make sure the document is saved
2741 static bool ensureBufferClean(Buffer * buffer)
2743 LASSERT(buffer, return false);
2744 if (buffer->isClean() && !buffer->isUnnamed())
2747 docstring const file = buffer->fileName().displayName(30);
2750 if (!buffer->isUnnamed()) {
2751 text = bformat(_("The document %1$s has unsaved "
2752 "changes.\n\nDo you want to save "
2753 "the document?"), file);
2754 title = _("Save changed document?");
2757 text = bformat(_("The document %1$s has not been "
2758 "saved yet.\n\nDo you want to save "
2759 "the document?"), file);
2760 title = _("Save new document?");
2762 int const ret = Alert::prompt(title, text, 0, 1, _("&Save"), _("&Cancel"));
2765 dispatch(FuncRequest(LFUN_BUFFER_WRITE));
2767 return buffer->isClean() && !buffer->isUnnamed();
2771 bool GuiView::reloadBuffer(Buffer & buf)
2773 Buffer::ReadStatus status = buf.reload();
2774 return status == Buffer::ReadSuccess;
2778 void GuiView::checkExternallyModifiedBuffers()
2780 BufferList::iterator bit = theBufferList().begin();
2781 BufferList::iterator const bend = theBufferList().end();
2782 for (; bit != bend; ++bit) {
2783 Buffer * buf = *bit;
2784 if (buf->fileName().exists()
2785 && buf->isExternallyModified(Buffer::checksum_method)) {
2786 docstring text = bformat(_("Document \n%1$s\n has been externally modified."
2787 " Reload now? Any local changes will be lost."),
2788 from_utf8(buf->absFileName()));
2789 int const ret = Alert::prompt(_("Reload externally changed document?"),
2790 text, 0, 1, _("&Reload"), _("&Cancel"));
2798 void GuiView::dispatchVC(FuncRequest const & cmd, DispatchResult & dr)
2800 Buffer * buffer = documentBufferView()
2801 ? &(documentBufferView()->buffer()) : 0;
2803 switch (cmd.action()) {
2804 case LFUN_VC_REGISTER:
2805 if (!buffer || !ensureBufferClean(buffer))
2807 if (!buffer->lyxvc().inUse()) {
2808 if (buffer->lyxvc().registrer()) {
2809 reloadBuffer(*buffer);
2810 dr.suppressMessageUpdate();
2815 case LFUN_VC_CHECK_IN:
2816 if (!buffer || !ensureBufferClean(buffer))
2818 if (buffer->lyxvc().inUse() && !buffer->isReadonly()) {
2819 dr.setMessage(buffer->lyxvc().checkIn());
2820 if (!dr.message().empty())
2821 reloadBuffer(*buffer);
2825 case LFUN_VC_CHECK_OUT:
2826 if (!buffer || !ensureBufferClean(buffer))
2828 if (buffer->lyxvc().inUse()) {
2829 dr.setMessage(buffer->lyxvc().checkOut());
2830 reloadBuffer(*buffer);
2834 case LFUN_VC_LOCKING_TOGGLE:
2835 LASSERT(buffer, return);
2836 if (!ensureBufferClean(buffer) || buffer->isReadonly())
2838 if (buffer->lyxvc().inUse()) {
2839 string res = buffer->lyxvc().lockingToggle();
2841 frontend::Alert::error(_("Revision control error."),
2842 _("Error when setting the locking property."));
2845 reloadBuffer(*buffer);
2850 case LFUN_VC_REVERT:
2851 LASSERT(buffer, return);
2852 if (buffer->lyxvc().revert()) {
2853 reloadBuffer(*buffer);
2854 dr.suppressMessageUpdate();
2858 case LFUN_VC_UNDO_LAST:
2859 LASSERT(buffer, return);
2860 buffer->lyxvc().undoLast();
2861 reloadBuffer(*buffer);
2862 dr.suppressMessageUpdate();
2865 case LFUN_VC_REPO_UPDATE:
2866 LASSERT(buffer, return);
2867 if (ensureBufferClean(buffer)) {
2868 dr.setMessage(buffer->lyxvc().repoUpdate());
2869 checkExternallyModifiedBuffers();
2873 case LFUN_VC_COMMAND: {
2874 string flag = cmd.getArg(0);
2875 if (buffer && contains(flag, 'R') && !ensureBufferClean(buffer))
2878 if (contains(flag, 'M')) {
2879 if (!Alert::askForText(message, _("LyX VC: Log Message")))
2882 string path = cmd.getArg(1);
2883 if (contains(path, "$$p") && buffer)
2884 path = subst(path, "$$p", buffer->filePath());
2885 LYXERR(Debug::LYXVC, "Directory: " << path);
2887 if (!pp.isReadableDirectory()) {
2888 lyxerr << _("Directory is not accessible.") << endl;
2891 support::PathChanger p(pp);
2893 string command = cmd.getArg(2);
2894 if (command.empty())
2897 command = subst(command, "$$i", buffer->absFileName());
2898 command = subst(command, "$$p", buffer->filePath());
2900 command = subst(command, "$$m", to_utf8(message));
2901 LYXERR(Debug::LYXVC, "Command: " << command);
2903 one.startscript(Systemcall::Wait, command);
2907 if (contains(flag, 'I'))
2908 buffer->markDirty();
2909 if (contains(flag, 'R'))
2910 reloadBuffer(*buffer);
2915 case LFUN_VC_COMPARE: {
2917 if (cmd.argument().empty()) {
2918 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "comparehistory"));
2922 string rev1 = cmd.getArg(0);
2926 if (!buffer->lyxvc().prepareFileRevision(rev1, f1))
2929 if (isStrInt(rev1) && convert<int>(rev1) <= 0) {
2930 f2 = buffer->absFileName();
2932 string rev2 = cmd.getArg(1);
2936 if (!buffer->lyxvc().prepareFileRevision(rev2, f2))
2940 LYXERR(Debug::LYXVC, "Launching comparison for fetched revisions:\n" <<
2941 f1 << "\n" << f2 << "\n" );
2942 string par = "compare run " + quoteName(f1) + " " + quoteName(f2);
2943 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, par));
2953 void GuiView::openChildDocument(string const & fname)
2955 LASSERT(documentBufferView(), return);
2956 Buffer & buffer = documentBufferView()->buffer();
2957 FileName const filename = support::makeAbsPath(fname, buffer.filePath());
2958 documentBufferView()->saveBookmark(false);
2960 if (theBufferList().exists(filename)) {
2961 child = theBufferList().getBuffer(filename);
2964 message(bformat(_("Opening child document %1$s..."),
2965 makeDisplayPath(filename.absFileName())));
2966 child = loadDocument(filename, false);
2968 // Set the parent name of the child document.
2969 // This makes insertion of citations and references in the child work,
2970 // when the target is in the parent or another child document.
2972 child->setParent(&buffer);
2976 bool GuiView::goToFileRow(string const & argument)
2980 size_t i = argument.find_last_of(' ');
2981 if (i != string::npos) {
2982 file_name = os::internal_path(trim(argument.substr(0, i)));
2983 istringstream is(argument.substr(i + 1));
2988 if (i == string::npos) {
2989 LYXERR0("Wrong argument: " << argument);
2993 string const abstmp = package().temp_dir().absFileName();
2994 string const realtmp = package().temp_dir().realPath();
2995 // We have to use os::path_prefix_is() here, instead of
2996 // simply prefixIs(), because the file name comes from
2997 // an external application and may need case adjustment.
2998 if (os::path_prefix_is(file_name, abstmp, os::CASE_ADJUSTED)
2999 || os::path_prefix_is(file_name, realtmp, os::CASE_ADJUSTED)) {
3000 // Needed by inverse dvi search. If it is a file
3001 // in tmpdir, call the apropriated function.
3002 // If tmpdir is a symlink, we may have the real
3003 // path passed back, so we correct for that.
3004 if (!prefixIs(file_name, abstmp))
3005 file_name = subst(file_name, realtmp, abstmp);
3006 buf = theBufferList().getBufferFromTmp(file_name);
3008 // Must replace extension of the file to be .lyx
3009 // and get full path
3010 FileName const s = fileSearch(string(),
3011 support::changeExtension(file_name, ".lyx"), "lyx");
3012 // Either change buffer or load the file
3013 if (theBufferList().exists(s))
3014 buf = theBufferList().getBuffer(s);
3015 else if (s.exists()) {
3016 buf = loadDocument(s);
3021 _("File does not exist: %1$s"),
3022 makeDisplayPath(file_name)));
3028 _("No buffer for file: %1$s."),
3029 makeDisplayPath(file_name))
3034 documentBufferView()->setCursorFromRow(row);
3039 #if (QT_VERSION >= 0x040400)
3041 Buffer::ExportStatus GuiView::GuiViewPrivate::runAndDestroy(const T& func, Buffer const * orig, Buffer * buffer, string const & format)
3043 Buffer::ExportStatus const status = func(format);
3045 // the cloning operation will have produced a clone of the entire set of
3046 // documents, starting from the master. so we must delete those.
3047 Buffer * mbuf = const_cast<Buffer *>(buffer->masterBuffer());
3049 busyBuffers.remove(orig);
3054 Buffer::ExportStatus GuiView::GuiViewPrivate::compileAndDestroy(Buffer const * orig, Buffer * buffer, string const & format)
3056 Buffer::ExportStatus (Buffer::* mem_func)(std::string const &, bool) const = &Buffer::doExport;
3057 return runAndDestroy(bind(mem_func, buffer, _1, true), orig, buffer, format);
3061 Buffer::ExportStatus GuiView::GuiViewPrivate::exportAndDestroy(Buffer const * orig, Buffer * buffer, string const & format)
3063 Buffer::ExportStatus (Buffer::* mem_func)(std::string const &, bool) const = &Buffer::doExport;
3064 return runAndDestroy(bind(mem_func, buffer, _1, false), orig, buffer, format);
3068 Buffer::ExportStatus GuiView::GuiViewPrivate::previewAndDestroy(Buffer const * orig, Buffer * buffer, string const & format)
3070 Buffer::ExportStatus (Buffer::* mem_func)(std::string const &) const = &Buffer::preview;
3071 return runAndDestroy(bind(mem_func, buffer, _1), orig, buffer, format);
3076 // not used, but the linker needs them
3078 Buffer::ExportStatus GuiView::GuiViewPrivate::compileAndDestroy(
3079 Buffer const *, Buffer *, string const &)
3081 return Buffer::ExportSuccess;
3085 Buffer::ExportStatus GuiView::GuiViewPrivate::exportAndDestroy(
3086 Buffer const *, Buffer *, string const &)
3088 return Buffer::ExportSuccess;
3092 Buffer::ExportStatus GuiView::GuiViewPrivate::previewAndDestroy(
3093 Buffer const *, Buffer *, string const &)
3095 return Buffer::ExportSuccess;
3101 bool GuiView::GuiViewPrivate::asyncBufferProcessing(
3102 string const & argument,
3103 Buffer const * used_buffer,
3104 docstring const & msg,
3105 Buffer::ExportStatus (*asyncFunc)(Buffer const *, Buffer *, string const &),
3106 Buffer::ExportStatus (Buffer::*syncFunc)(string const &, bool) const,
3107 Buffer::ExportStatus (Buffer::*previewFunc)(string const &) const)
3112 string format = argument;
3114 format = used_buffer->params().getDefaultOutputFormat();
3115 processing_format = format;
3116 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
3118 progress_->clearMessages();
3121 GuiViewPrivate::busyBuffers.insert(used_buffer);
3122 QFuture<Buffer::ExportStatus> f = QtConcurrent::run(
3125 used_buffer->clone(),
3127 setPreviewFuture(f);
3128 last_export_format = used_buffer->params().bufferFormat();
3131 // We are asynchronous, so we don't know here anything about the success
3134 Buffer::ExportStatus status;
3136 // TODO check here if it breaks exporting with Qt < 4.4
3137 status = (used_buffer->*syncFunc)(format, true);
3138 } else if (previewFunc) {
3139 status = (used_buffer->*previewFunc)(format);
3142 handleExportStatus(gv_, status, format);
3144 return (status == Buffer::ExportSuccess
3145 || status == Buffer::PreviewSuccess);
3149 void GuiView::dispatchToBufferView(FuncRequest const & cmd, DispatchResult & dr)
3151 BufferView * bv = currentBufferView();
3154 // Let the current BufferView dispatch its own actions.
3155 bv->dispatch(cmd, dr);
3156 if (dr.dispatched())
3159 // Try with the document BufferView dispatch if any.
3160 BufferView * doc_bv = documentBufferView();
3161 if (doc_bv && doc_bv != bv) {
3162 doc_bv->dispatch(cmd, dr);
3163 if (dr.dispatched())
3167 // Then let the current Cursor dispatch its own actions.
3168 bv->cursor().dispatch(cmd);
3170 // update completion. We do it here and not in
3171 // processKeySym to avoid another redraw just for a
3172 // changed inline completion
3173 if (cmd.origin() == FuncRequest::KEYBOARD) {
3174 if (cmd.action() == LFUN_SELF_INSERT
3175 || (cmd.action() == LFUN_ERT_INSERT && bv->cursor().inMathed()))
3176 updateCompletion(bv->cursor(), true, true);
3177 else if (cmd.action() == LFUN_CHAR_DELETE_BACKWARD)
3178 updateCompletion(bv->cursor(), false, true);
3180 updateCompletion(bv->cursor(), false, false);
3183 dr = bv->cursor().result();
3187 void GuiView::dispatch(FuncRequest const & cmd, DispatchResult & dr)
3189 BufferView * bv = currentBufferView();
3190 // By default we won't need any update.
3191 dr.screenUpdate(Update::None);
3192 // assume cmd will be dispatched
3193 dr.dispatched(true);
3195 Buffer * doc_buffer = documentBufferView()
3196 ? &(documentBufferView()->buffer()) : 0;
3198 if (cmd.origin() == FuncRequest::TOC) {
3199 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
3200 // FIXME: do we need to pass a DispatchResult object here?
3201 toc->doDispatch(bv->cursor(), cmd);
3205 string const argument = to_utf8(cmd.argument());
3207 switch(cmd.action()) {
3208 case LFUN_BUFFER_CHILD_OPEN:
3209 openChildDocument(to_utf8(cmd.argument()));
3212 case LFUN_BUFFER_IMPORT:
3213 importDocument(to_utf8(cmd.argument()));
3216 case LFUN_BUFFER_EXPORT: {
3219 // GCC only sees strfwd.h when building merged
3220 if (::lyx::operator==(cmd.argument(), "custom")) {
3221 dispatch(FuncRequest(LFUN_DIALOG_SHOW, "sendto"), dr);
3224 #if QT_VERSION < 0x040400
3225 if (!doc_buffer->doExport(argument, false)) {
3227 dr.setMessage(bformat(_("Error exporting to format: %1$s"),
3231 /* TODO/Review: Is it a problem to also export the children?
3232 See the update_unincluded flag */
3233 d.asyncBufferProcessing(argument,
3236 &GuiViewPrivate::exportAndDestroy,
3239 // TODO Inform user about success
3244 case LFUN_BUFFER_EXPORT_AS:
3245 LASSERT(doc_buffer, break);
3246 exportBufferAs(*doc_buffer);
3249 case LFUN_BUFFER_UPDATE: {
3250 d.asyncBufferProcessing(argument,
3253 &GuiViewPrivate::compileAndDestroy,
3258 case LFUN_BUFFER_VIEW: {
3259 d.asyncBufferProcessing(argument,
3261 _("Previewing ..."),
3262 &GuiViewPrivate::previewAndDestroy,
3267 case LFUN_MASTER_BUFFER_UPDATE: {
3268 d.asyncBufferProcessing(argument,
3269 (doc_buffer ? doc_buffer->masterBuffer() : 0),
3271 &GuiViewPrivate::compileAndDestroy,
3276 case LFUN_MASTER_BUFFER_VIEW: {
3277 d.asyncBufferProcessing(argument,
3278 (doc_buffer ? doc_buffer->masterBuffer() : 0),
3280 &GuiViewPrivate::previewAndDestroy,
3281 0, &Buffer::preview);
3284 case LFUN_BUFFER_SWITCH: {
3285 string const file_name = to_utf8(cmd.argument());
3286 if (!FileName::isAbsolute(file_name)) {
3288 dr.setMessage(_("Absolute filename expected."));
3292 Buffer * buffer = theBufferList().getBuffer(FileName(file_name));
3295 dr.setMessage(_("Document not loaded"));
3299 // Do we open or switch to the buffer in this view ?
3300 if (workArea(*buffer)
3301 || lyxrc.open_buffers_in_tabs || !documentBufferView()) {
3306 // Look for the buffer in other views
3307 QList<int> const ids = guiApp->viewIds();
3309 for (; i != ids.size(); ++i) {
3310 GuiView & gv = guiApp->view(ids[i]);
3311 if (gv.workArea(*buffer)) {
3312 gv.activateWindow();
3313 gv.setBuffer(buffer);
3318 // If necessary, open a new window as a last resort
3319 if (i == ids.size()) {
3320 lyx::dispatch(FuncRequest(LFUN_WINDOW_NEW));
3326 case LFUN_BUFFER_NEXT:
3327 gotoNextOrPreviousBuffer(NEXTBUFFER);
3330 case LFUN_BUFFER_PREVIOUS:
3331 gotoNextOrPreviousBuffer(PREVBUFFER);
3334 case LFUN_COMMAND_EXECUTE: {
3335 bool const show_it = cmd.argument() != "off";
3336 // FIXME: this is a hack, "minibuffer" should not be
3338 if (GuiToolbar * t = toolbar("minibuffer")) {
3339 t->setVisible(show_it);
3340 if (show_it && t->commandBuffer())
3341 t->commandBuffer()->setFocus();
3345 case LFUN_DROP_LAYOUTS_CHOICE:
3346 d.layout_->showPopup();
3349 case LFUN_MENU_OPEN:
3350 if (QMenu * menu = guiApp->menus().menu(toqstr(cmd.argument()), *this))
3351 menu->exec(QCursor::pos());
3354 case LFUN_FILE_INSERT:
3355 insertLyXFile(cmd.argument());
3358 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
3359 insertPlaintextFile(cmd.argument(), true);
3362 case LFUN_FILE_INSERT_PLAINTEXT:
3363 insertPlaintextFile(cmd.argument(), false);
3366 case LFUN_BUFFER_RELOAD: {
3367 LASSERT(doc_buffer, break);
3370 if (!doc_buffer->isClean()) {
3371 docstring const file =
3372 makeDisplayPath(doc_buffer->absFileName(), 20);
3373 docstring text = bformat(_("Any changes will be lost. "
3374 "Are you sure you want to revert to the saved version "
3375 "of the document %1$s?"), file);
3376 ret = Alert::prompt(_("Revert to saved document?"),
3377 text, 1, 1, _("&Revert"), _("&Cancel"));
3381 doc_buffer->markClean();
3382 reloadBuffer(*doc_buffer);
3383 dr.forceBufferUpdate();
3388 case LFUN_BUFFER_WRITE:
3389 LASSERT(doc_buffer, break);
3390 saveBuffer(*doc_buffer);
3393 case LFUN_BUFFER_WRITE_AS:
3394 LASSERT(doc_buffer, break);
3395 renameBuffer(*doc_buffer, cmd.argument());
3398 case LFUN_BUFFER_WRITE_ALL: {
3399 Buffer * first = theBufferList().first();
3402 message(_("Saving all documents..."));
3403 // We cannot use a for loop as the buffer list cycles.
3406 if (!b->isClean()) {
3408 LYXERR(Debug::ACTION, "Saved " << b->absFileName());
3410 b = theBufferList().next(b);
3411 } while (b != first);
3412 dr.setMessage(_("All documents saved."));
3416 case LFUN_BUFFER_CLOSE:
3420 case LFUN_BUFFER_CLOSE_ALL:
3424 case LFUN_TOOLBAR_TOGGLE: {
3425 string const name = cmd.getArg(0);
3426 if (GuiToolbar * t = toolbar(name))
3431 case LFUN_DIALOG_UPDATE: {
3432 string const name = to_utf8(cmd.argument());
3433 if (name == "prefs" || name == "document")
3434 updateDialog(name, string());
3435 else if (name == "paragraph")
3436 lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
3437 else if (currentBufferView()) {
3438 Inset * inset = currentBufferView()->editedInset(name);
3439 // Can only update a dialog connected to an existing inset
3441 // FIXME: get rid of this indirection; GuiView ask the inset
3442 // if he is kind enough to update itself...
3443 FuncRequest fr(LFUN_INSET_DIALOG_UPDATE, cmd.argument());
3444 //FIXME: pass DispatchResult here?
3445 inset->dispatch(currentBufferView()->cursor(), fr);
3451 case LFUN_DIALOG_TOGGLE: {
3452 FuncCode const func_code = isDialogVisible(cmd.getArg(0))
3453 ? LFUN_DIALOG_HIDE : LFUN_DIALOG_SHOW;
3454 dispatch(FuncRequest(func_code, cmd.argument()), dr);
3458 case LFUN_DIALOG_DISCONNECT_INSET:
3459 disconnectDialog(to_utf8(cmd.argument()));
3462 case LFUN_DIALOG_HIDE: {
3463 guiApp->hideDialogs(to_utf8(cmd.argument()), 0);
3467 case LFUN_DIALOG_SHOW: {
3468 string const name = cmd.getArg(0);
3469 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
3471 if (name == "character") {
3472 data = freefont2string();
3474 showDialog("character", data);
3475 } else if (name == "latexlog") {
3476 Buffer::LogType type;
3477 string const logfile = doc_buffer->logName(&type);
3479 case Buffer::latexlog:
3482 case Buffer::buildlog:
3486 data += Lexer::quoteString(logfile);
3487 showDialog("log", data);
3488 } else if (name == "vclog") {
3489 string const data = "vc " +
3490 Lexer::quoteString(doc_buffer->lyxvc().getLogFile());
3491 showDialog("log", data);
3492 } else if (name == "symbols") {
3493 data = bv->cursor().getEncoding()->name();
3495 showDialog("symbols", data);
3497 } else if (name == "prefs" && isFullScreen()) {
3498 lfunUiToggle("fullscreen");
3499 showDialog("prefs", data);
3501 showDialog(name, data);
3506 dr.setMessage(cmd.argument());
3509 case LFUN_UI_TOGGLE: {
3510 string arg = cmd.getArg(0);
3511 if (!lfunUiToggle(arg)) {
3512 docstring const msg = "ui-toggle " + _("%1$s unknown command!");
3513 dr.setMessage(bformat(msg, from_utf8(arg)));
3515 // Make sure the keyboard focus stays in the work area.
3520 case LFUN_SPLIT_VIEW: {
3521 LASSERT(doc_buffer, break);
3522 string const orientation = cmd.getArg(0);
3523 d.splitter_->setOrientation(orientation == "vertical"
3524 ? Qt::Vertical : Qt::Horizontal);
3525 TabWorkArea * twa = addTabWorkArea();
3526 GuiWorkArea * wa = twa->addWorkArea(*doc_buffer, *this);
3527 setCurrentWorkArea(wa);
3530 case LFUN_CLOSE_TAB_GROUP:
3531 if (TabWorkArea * twa = d.currentTabWorkArea()) {
3532 closeTabWorkArea(twa);
3533 d.current_work_area_ = 0;
3534 twa = d.currentTabWorkArea();
3535 // Switch to the next GuiWorkArea in the found TabWorkArea.
3537 // Make sure the work area is up to date.
3538 setCurrentWorkArea(twa->currentWorkArea());
3540 setCurrentWorkArea(0);
3545 case LFUN_COMPLETION_INLINE:
3546 if (d.current_work_area_)
3547 d.current_work_area_->completer().showInline();
3550 case LFUN_COMPLETION_POPUP:
3551 if (d.current_work_area_)
3552 d.current_work_area_->completer().showPopup();
3556 case LFUN_COMPLETION_COMPLETE:
3557 if (d.current_work_area_)
3558 d.current_work_area_->completer().tab();
3561 case LFUN_COMPLETION_CANCEL:
3562 if (d.current_work_area_) {
3563 if (d.current_work_area_->completer().popupVisible())
3564 d.current_work_area_->completer().hidePopup();
3566 d.current_work_area_->completer().hideInline();
3570 case LFUN_COMPLETION_ACCEPT:
3571 if (d.current_work_area_)
3572 d.current_work_area_->completer().activate();
3575 case LFUN_BUFFER_ZOOM_IN:
3576 case LFUN_BUFFER_ZOOM_OUT:
3577 if (cmd.argument().empty()) {
3578 if (cmd.action() == LFUN_BUFFER_ZOOM_IN)
3583 lyxrc.zoom += convert<int>(cmd.argument());
3585 if (lyxrc.zoom < 10)
3588 // The global QPixmapCache is used in GuiPainter to cache text
3589 // painting so we must reset it.
3590 QPixmapCache::clear();
3591 guiApp->fontLoader().update();
3592 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
3595 case LFUN_VC_REGISTER:
3596 case LFUN_VC_CHECK_IN:
3597 case LFUN_VC_CHECK_OUT:
3598 case LFUN_VC_REPO_UPDATE:
3599 case LFUN_VC_LOCKING_TOGGLE:
3600 case LFUN_VC_REVERT:
3601 case LFUN_VC_UNDO_LAST:
3602 case LFUN_VC_COMMAND:
3603 case LFUN_VC_COMPARE:
3604 dispatchVC(cmd, dr);
3607 case LFUN_SERVER_GOTO_FILE_ROW:
3608 goToFileRow(to_utf8(cmd.argument()));
3611 case LFUN_FORWARD_SEARCH: {
3612 Buffer const * doc_master = doc_buffer->masterBuffer();
3613 FileName const path(doc_master->temppath());
3614 string const texname = doc_master->isChild(doc_buffer)
3615 ? DocFileName(changeExtension(
3616 doc_buffer->absFileName(),
3617 "tex")).mangledFileName()
3618 : doc_buffer->latexName();
3619 string const mastername =
3620 removeExtension(doc_master->latexName());
3621 FileName const dviname(addName(path.absFileName(),
3622 addExtension(mastername, "dvi")));
3623 FileName const pdfname(addName(path.absFileName(),
3624 addExtension(mastername, "pdf")));
3625 bool const have_dvi = dviname.exists();
3626 bool const have_pdf = pdfname.exists();
3627 if (!have_dvi && !have_pdf) {
3628 dr.setMessage(_("Please, preview the document first."));
3631 string outname = dviname.onlyFileName();
3632 string command = lyxrc.forward_search_dvi;
3633 if (!have_dvi || (have_pdf &&
3634 pdfname.lastModified() > dviname.lastModified())) {
3635 outname = pdfname.onlyFileName();
3636 command = lyxrc.forward_search_pdf;
3639 int row = doc_buffer->texrow().getRowFromIdPos(bv->cursor().paragraph().id(), bv->cursor().pos());
3640 LYXERR(Debug::ACTION, "Forward search: row:" << row
3641 << " id:" << bv->cursor().paragraph().id());
3642 if (!row || command.empty()) {
3643 dr.setMessage(_("Couldn't proceed."));
3646 string texrow = convert<string>(row);
3648 command = subst(command, "$$n", texrow);
3649 command = subst(command, "$$t", texname);
3650 command = subst(command, "$$o", outname);
3652 PathChanger p(path);
3654 one.startscript(Systemcall::DontWait, command);
3658 // The LFUN must be for one of BufferView, Buffer or Cursor;
3660 dispatchToBufferView(cmd, dr);
3664 // Part of automatic menu appearance feature.
3665 if (isFullScreen()) {
3666 if (menuBar()->isVisible() && lyxrc.full_screen_menubar)
3668 if (statusBar()->isVisible())
3669 statusBar()->hide();
3674 bool GuiView::lfunUiToggle(string const & ui_component)
3676 if (ui_component == "scrollbar") {
3677 // hide() is of no help
3678 if (d.current_work_area_->verticalScrollBarPolicy() ==
3679 Qt::ScrollBarAlwaysOff)
3681 d.current_work_area_->setVerticalScrollBarPolicy(
3682 Qt::ScrollBarAsNeeded);
3684 d.current_work_area_->setVerticalScrollBarPolicy(
3685 Qt::ScrollBarAlwaysOff);
3686 } else if (ui_component == "statusbar") {
3687 statusBar()->setVisible(!statusBar()->isVisible());
3688 } else if (ui_component == "menubar") {
3689 menuBar()->setVisible(!menuBar()->isVisible());
3691 #if QT_VERSION >= 0x040300
3692 if (ui_component == "frame") {
3694 getContentsMargins(&l, &t, &r, &b);
3695 //are the frames in default state?
3696 d.current_work_area_->setFrameStyle(QFrame::NoFrame);
3698 setContentsMargins(-2, -2, -2, -2);
3700 setContentsMargins(0, 0, 0, 0);
3704 if (ui_component == "fullscreen") {
3712 void GuiView::toggleFullScreen()
3714 if (isFullScreen()) {
3715 for (int i = 0; i != d.splitter_->count(); ++i)
3716 d.tabWorkArea(i)->setFullScreen(false);
3717 #if QT_VERSION >= 0x040300
3718 setContentsMargins(0, 0, 0, 0);
3720 setWindowState(windowState() ^ Qt::WindowFullScreen);
3723 statusBar()->show();
3726 hideDialogs("prefs", 0);
3727 for (int i = 0; i != d.splitter_->count(); ++i)
3728 d.tabWorkArea(i)->setFullScreen(true);
3729 #if QT_VERSION >= 0x040300
3730 setContentsMargins(-2, -2, -2, -2);
3733 setWindowState(windowState() ^ Qt::WindowFullScreen);
3734 statusBar()->hide();
3735 if (lyxrc.full_screen_menubar)
3737 if (lyxrc.full_screen_toolbars) {
3738 ToolbarMap::iterator end = d.toolbars_.end();
3739 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
3744 // give dialogs like the TOC a chance to adapt
3749 Buffer const * GuiView::updateInset(Inset const * inset)
3754 Buffer const * inset_buffer = &(inset->buffer());
3756 for (int i = 0; i != d.splitter_->count(); ++i) {
3757 GuiWorkArea * wa = d.tabWorkArea(i)->currentWorkArea();
3760 Buffer const * buffer = &(wa->bufferView().buffer());
3761 if (inset_buffer == buffer)
3762 wa->scheduleRedraw();
3764 return inset_buffer;
3768 void GuiView::restartCursor()
3770 /* When we move around, or type, it's nice to be able to see
3771 * the cursor immediately after the keypress.
3773 if (d.current_work_area_)
3774 d.current_work_area_->startBlinkingCursor();
3776 // Take this occasion to update the other GUI elements.
3782 void GuiView::updateCompletion(Cursor & cur, bool start, bool keep)
3784 if (d.current_work_area_)
3785 d.current_work_area_->completer().updateVisibility(cur, start, keep);
3790 // This list should be kept in sync with the list of insets in
3791 // src/insets/Inset.cpp. I.e., if a dialog goes with an inset, the
3792 // dialog should have the same name as the inset.
3793 // Changes should be also recorded in LFUN_DIALOG_SHOW doxygen
3794 // docs in LyXAction.cpp.
3796 char const * const dialognames[] = {
3798 "aboutlyx", "bibitem", "bibtex", "box", "branch", "changes", "character",
3799 "citation", "compare", "comparehistory", "document", "errorlist", "ert",
3800 "external", "file", "findreplace", "findreplaceadv", "float", "graphics",
3801 "href", "include", "index", "index_print", "info", "listings", "label", "line",
3802 "log", "mathdelimiter", "mathmatrix", "mathspace", "nomenclature",
3803 "nomencl_print", "note", "paragraph", "phantom", "prefs", "print", "ref",
3804 "sendto", "space", "spellchecker", "symbols", "tabular", "tabularcreate",
3805 "thesaurus", "texinfo", "toc", "view-source", "vspace", "wrap", "progress"};
3807 char const * const * const end_dialognames =
3808 dialognames + (sizeof(dialognames) / sizeof(char *));
3812 cmpCStr(char const * name) : name_(name) {}
3813 bool operator()(char const * other) {
3814 return strcmp(other, name_) == 0;
3821 bool isValidName(string const & name)
3823 return find_if(dialognames, end_dialognames,
3824 cmpCStr(name.c_str())) != end_dialognames;
3830 void GuiView::resetDialogs()
3832 // Make sure that no LFUN uses any GuiView.
3833 guiApp->setCurrentView(0);
3837 constructToolbars();
3838 guiApp->menus().fillMenuBar(menuBar(), this, false);
3839 d.layout_->updateContents(true);
3840 // Now update controls with current buffer.
3841 guiApp->setCurrentView(this);
3847 Dialog * GuiView::findOrBuild(string const & name, bool hide_it)
3849 if (!isValidName(name))
3852 map<string, DialogPtr>::iterator it = d.dialogs_.find(name);
3854 if (it != d.dialogs_.end()) {
3856 it->second->hideView();
3857 return it->second.get();
3860 Dialog * dialog = build(name);
3861 d.dialogs_[name].reset(dialog);
3862 if (lyxrc.allow_geometry_session)
3863 dialog->restoreSession();
3870 void GuiView::showDialog(string const & name, string const & data,
3873 triggerShowDialog(toqstr(name), toqstr(data), inset);
3877 void GuiView::doShowDialog(QString const & qname, QString const & qdata,
3883 const string name = fromqstr(qname);
3884 const string data = fromqstr(qdata);
3888 Dialog * dialog = findOrBuild(name, false);
3890 bool const visible = dialog->isVisibleView();
3891 dialog->showData(data);
3892 if (inset && currentBufferView())
3893 currentBufferView()->editInset(name, inset);
3894 // We only set the focus to the new dialog if it was not yet
3895 // visible in order not to change the existing previous behaviour
3897 // activateWindow is needed for floating dockviews
3898 dialog->asQWidget()->raise();
3899 dialog->asQWidget()->activateWindow();
3900 dialog->asQWidget()->setFocus();
3904 catch (ExceptionMessage const & ex) {
3912 bool GuiView::isDialogVisible(string const & name) const
3914 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3915 if (it == d.dialogs_.end())
3917 return it->second.get()->isVisibleView() && !it->second.get()->isClosing();
3921 void GuiView::hideDialog(string const & name, Inset * inset)
3923 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3924 if (it == d.dialogs_.end())
3928 if (!currentBufferView())
3930 if (inset != currentBufferView()->editedInset(name))
3934 Dialog * const dialog = it->second.get();
3935 if (dialog->isVisibleView())
3937 if (currentBufferView())
3938 currentBufferView()->editInset(name, 0);
3942 void GuiView::disconnectDialog(string const & name)
3944 if (!isValidName(name))
3946 if (currentBufferView())
3947 currentBufferView()->editInset(name, 0);
3951 void GuiView::hideAll() const
3953 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
3954 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3956 for(; it != end; ++it)
3957 it->second->hideView();
3961 void GuiView::updateDialogs()
3963 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
3964 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3966 for(; it != end; ++it) {
3967 Dialog * dialog = it->second.get();
3969 if (dialog->needBufferOpen() && !documentBufferView())
3970 hideDialog(fromqstr(dialog->name()), 0);
3971 else if (dialog->isVisibleView())
3972 dialog->checkStatus();
3979 Dialog * createDialog(GuiView & lv, string const & name);
3981 // will be replaced by a proper factory...
3982 Dialog * createGuiAbout(GuiView & lv);
3983 Dialog * createGuiBibtex(GuiView & lv);
3984 Dialog * createGuiChanges(GuiView & lv);
3985 Dialog * createGuiCharacter(GuiView & lv);
3986 Dialog * createGuiCitation(GuiView & lv);
3987 Dialog * createGuiCompare(GuiView & lv);
3988 Dialog * createGuiCompareHistory(GuiView & lv);
3989 Dialog * createGuiDelimiter(GuiView & lv);
3990 Dialog * createGuiDocument(GuiView & lv);
3991 Dialog * createGuiErrorList(GuiView & lv);
3992 Dialog * createGuiExternal(GuiView & lv);
3993 Dialog * createGuiGraphics(GuiView & lv);
3994 Dialog * createGuiInclude(GuiView & lv);
3995 Dialog * createGuiIndex(GuiView & lv);
3996 Dialog * createGuiListings(GuiView & lv);
3997 Dialog * createGuiLog(GuiView & lv);
3998 Dialog * createGuiMathMatrix(GuiView & lv);
3999 Dialog * createGuiNote(GuiView & lv);
4000 Dialog * createGuiParagraph(GuiView & lv);
4001 Dialog * createGuiPhantom(GuiView & lv);
4002 Dialog * createGuiPreferences(GuiView & lv);
4003 Dialog * createGuiPrint(GuiView & lv);
4004 Dialog * createGuiPrintindex(GuiView & lv);
4005 Dialog * createGuiRef(GuiView & lv);
4006 Dialog * createGuiSearch(GuiView & lv);
4007 Dialog * createGuiSearchAdv(GuiView & lv);
4008 Dialog * createGuiSendTo(GuiView & lv);
4009 Dialog * createGuiShowFile(GuiView & lv);
4010 Dialog * createGuiSpellchecker(GuiView & lv);
4011 Dialog * createGuiSymbols(GuiView & lv);
4012 Dialog * createGuiTabularCreate(GuiView & lv);
4013 Dialog * createGuiTexInfo(GuiView & lv);
4014 Dialog * createGuiToc(GuiView & lv);
4015 Dialog * createGuiThesaurus(GuiView & lv);
4016 Dialog * createGuiViewSource(GuiView & lv);
4017 Dialog * createGuiWrap(GuiView & lv);
4018 Dialog * createGuiProgressView(GuiView & lv);
4022 Dialog * GuiView::build(string const & name)
4024 LASSERT(isValidName(name), return 0);
4026 Dialog * dialog = createDialog(*this, name);
4030 if (name == "aboutlyx")
4031 return createGuiAbout(*this);
4032 if (name == "bibtex")
4033 return createGuiBibtex(*this);
4034 if (name == "changes")
4035 return createGuiChanges(*this);
4036 if (name == "character")
4037 return createGuiCharacter(*this);
4038 if (name == "citation")
4039 return createGuiCitation(*this);
4040 if (name == "compare")
4041 return createGuiCompare(*this);
4042 if (name == "comparehistory")
4043 return createGuiCompareHistory(*this);
4044 if (name == "document")
4045 return createGuiDocument(*this);
4046 if (name == "errorlist")
4047 return createGuiErrorList(*this);
4048 if (name == "external")
4049 return createGuiExternal(*this);
4051 return createGuiShowFile(*this);
4052 if (name == "findreplace")
4053 return createGuiSearch(*this);
4054 if (name == "findreplaceadv")
4055 return createGuiSearchAdv(*this);
4056 if (name == "graphics")
4057 return createGuiGraphics(*this);
4058 if (name == "include")
4059 return createGuiInclude(*this);
4060 if (name == "index")
4061 return createGuiIndex(*this);
4062 if (name == "index_print")
4063 return createGuiPrintindex(*this);
4064 if (name == "listings")
4065 return createGuiListings(*this);
4067 return createGuiLog(*this);
4068 if (name == "mathdelimiter")
4069 return createGuiDelimiter(*this);
4070 if (name == "mathmatrix")
4071 return createGuiMathMatrix(*this);
4073 return createGuiNote(*this);
4074 if (name == "paragraph")
4075 return createGuiParagraph(*this);
4076 if (name == "phantom")
4077 return createGuiPhantom(*this);
4078 if (name == "prefs")
4079 return createGuiPreferences(*this);
4080 if (name == "print")
4081 return createGuiPrint(*this);
4083 return createGuiRef(*this);
4084 if (name == "sendto")
4085 return createGuiSendTo(*this);
4086 if (name == "spellchecker")
4087 return createGuiSpellchecker(*this);
4088 if (name == "symbols")
4089 return createGuiSymbols(*this);
4090 if (name == "tabularcreate")
4091 return createGuiTabularCreate(*this);
4092 if (name == "texinfo")
4093 return createGuiTexInfo(*this);
4094 if (name == "thesaurus")
4095 return createGuiThesaurus(*this);
4097 return createGuiToc(*this);
4098 if (name == "view-source")
4099 return createGuiViewSource(*this);
4101 return createGuiWrap(*this);
4102 if (name == "progress")
4103 return createGuiProgressView(*this);
4109 } // namespace frontend
4112 #include "moc_GuiView.cpp"