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<docstring> 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<docstring> processing_thread_watcher_;
387 string last_export_format;
389 struct DummyWatcher { bool isRunning(){return false;} };
390 DummyWatcher processing_thread_watcher_;
393 static QSet<Buffer const *> busyBuffers;
394 static docstring previewAndDestroy(Buffer const * orig, Buffer * buffer, string const & format);
395 static docstring exportAndDestroy(Buffer const * orig, Buffer * buffer, string const & format);
396 static docstring compileAndDestroy(Buffer const * orig, Buffer * buffer, string const & format);
397 static docstring autosaveAndDestroy(Buffer const * orig, Buffer * buffer);
400 static docstring runAndDestroy(const T& func, Buffer const * orig, Buffer * buffer, string const & format, string const & msg);
402 // TODO syncFunc/previewFunc: use bind
403 bool asyncBufferProcessing(string const & argument,
404 Buffer const * used_buffer,
405 docstring const & msg,
406 docstring (*asyncFunc)(Buffer const *, Buffer *, string const &),
407 bool (Buffer::*syncFunc)(string const &, bool) const,
408 bool (Buffer::*previewFunc)(string const &) const);
410 QVector<GuiWorkArea*> guiWorkAreas();
413 QSet<Buffer const *> GuiView::GuiViewPrivate::busyBuffers;
416 GuiView::GuiView(int id)
417 : d(*new GuiViewPrivate(this)), id_(id), closing_(false), busy_(0)
419 // GuiToolbars *must* be initialised before the menu bar.
420 normalSizedIcons(); // at least on Mac the default is 32 otherwise, which is huge
423 // set ourself as the current view. This is needed for the menu bar
424 // filling, at least for the static special menu item on Mac. Otherwise
425 // they are greyed out.
426 guiApp->setCurrentView(this);
428 // Fill up the menu bar.
429 guiApp->menus().fillMenuBar(menuBar(), this, true);
431 setCentralWidget(d.stack_widget_);
433 // Start autosave timer
434 if (lyxrc.autosave) {
435 d.autosave_timeout_.timeout.connect(bind(&GuiView::autoSave, this));
436 d.autosave_timeout_.setTimeout(lyxrc.autosave * 1000);
437 d.autosave_timeout_.start();
439 connect(&d.statusbar_timer_, SIGNAL(timeout()),
440 this, SLOT(clearMessage()));
442 // We don't want to keep the window in memory if it is closed.
443 setAttribute(Qt::WA_DeleteOnClose, true);
445 #if (!defined(Q_WS_WIN) && !defined(Q_WS_MACX))
446 // assign an icon to main form. We do not do it under Qt/Win or Qt/Mac,
447 // since the icon is provided in the application bundle.
448 setWindowIcon(getPixmap("images/", "lyx", "png"));
451 #if (QT_VERSION >= 0x040300)
452 // use tabbed dock area for multiple docks
453 // (such as "source" and "messages")
454 setDockOptions(QMainWindow::ForceTabbedDocks);
458 setAcceptDrops(true);
460 #if (QT_VERSION >= 0x040400)
462 // add busy indicator to statusbar
463 QLabel * busylabel = new QLabel(statusBar());
464 statusBar()->addPermanentWidget(busylabel);
465 QString fn = toqstr(lyx::libFileSearch("images", "busy.gif").absFileName());
466 QMovie * busyanim = new QMovie(fn, QByteArray(), busylabel);
467 busylabel->setMovie(busyanim);
471 connect(&d.processing_thread_watcher_, SIGNAL(started()),
472 busylabel, SLOT(show()));
473 connect(&d.processing_thread_watcher_, SIGNAL(finished()),
474 busylabel, SLOT(hide()));
476 statusBar()->setSizeGripEnabled(true);
479 connect(&d.autosave_watcher_, SIGNAL(finished()), this,
480 SLOT(autoSaveThreadFinished()));
482 connect(&d.processing_thread_watcher_, SIGNAL(started()), this,
483 SLOT(processingThreadStarted()));
484 connect(&d.processing_thread_watcher_, SIGNAL(finished()), this,
485 SLOT(processingThreadFinished()));
489 connect(this, SIGNAL(triggerShowDialog(QString const &, QString const &, Inset *)),
490 SLOT(doShowDialog(QString const &, QString const &, Inset *)));
492 // Forbid too small unresizable window because it can happen
493 // with some window manager under X11.
494 setMinimumSize(300, 200);
496 if (lyxrc.allow_geometry_session) {
497 // Now take care of session management.
502 // no session handling, default to a sane size.
503 setGeometry(50, 50, 690, 510);
506 // clear session data if any.
508 settings.remove("views");
518 QVector<GuiWorkArea*> GuiView::GuiViewPrivate::guiWorkAreas()
520 QVector<GuiWorkArea*> areas;
521 for (int i = 0; i < tabWorkAreaCount(); i++) {
522 TabWorkArea* ta = tabWorkArea(i);
523 for (int u = 0; u < ta->count(); u++) {
524 areas << ta->workArea(u);
531 #if QT_VERSION >= 0x040400
533 void GuiView::processingThreadStarted()
538 void GuiView::processingThreadFinished(bool show_errors)
540 QFutureWatcher<docstring> const * watcher =
541 static_cast<QFutureWatcher<docstring> const *>(sender());
542 message(watcher->result());
545 BufferView const * const bv = currentBufferView();
546 if (bv && !bv->buffer().errorList("Export").empty()) {
550 errors(d.last_export_format);
555 void GuiView::processingThreadFinished()
557 processingThreadFinished(true);
561 void GuiView::autoSaveThreadFinished()
563 processingThreadFinished(false);
569 void GuiView::processingThreadStarted()
574 void GuiView::processingThreadFinished(bool)
579 void GuiView::processingThreadFinished()
584 void GuiView::autoSaveThreadFinished()
590 void GuiView::saveLayout() const
593 settings.beginGroup("views");
594 settings.beginGroup(QString::number(id_));
596 settings.setValue("pos", pos());
597 settings.setValue("size", size());
599 settings.setValue("geometry", saveGeometry());
601 settings.setValue("layout", saveState(0));
602 settings.setValue("icon_size", iconSize());
606 void GuiView::saveUISettings() const
608 // Save the toolbar private states
609 ToolbarMap::iterator end = d.toolbars_.end();
610 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
611 it->second->saveSession();
612 // Now take care of all other dialogs
613 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
614 for (; it!= d.dialogs_.end(); ++it)
615 it->second->saveSession();
619 bool GuiView::restoreLayout()
622 settings.beginGroup("views");
623 settings.beginGroup(QString::number(id_));
624 QString const icon_key = "icon_size";
625 if (!settings.contains(icon_key))
628 //code below is skipped when when ~/.config/LyX is (re)created
629 QSize icon_size = settings.value(icon_key).toSize();
630 // Check whether session size changed.
631 if (icon_size.width() != int(d.smallIconSize) &&
632 icon_size.width() != int(d.normalIconSize) &&
633 icon_size.width() != int(d.bigIconSize)) {
634 icon_size.setWidth(d.normalIconSize);
635 icon_size.setHeight(d.normalIconSize);
637 setIconSize(icon_size);
640 QPoint pos = settings.value("pos", QPoint(50, 50)).toPoint();
641 QSize size = settings.value("size", QSize(690, 510)).toSize();
645 // Work-around for bug #6034: the window ends up in an undetermined
646 // state when trying to restore a maximized window when it is
647 // already maximized.
648 if (!(windowState() & Qt::WindowMaximized))
649 if (!restoreGeometry(settings.value("geometry").toByteArray()))
650 setGeometry(50, 50, 690, 510);
652 // Make sure layout is correctly oriented.
653 setLayoutDirection(qApp->layoutDirection());
655 // Allow the toc and view-source dock widget to be restored if needed.
657 if ((dialog = findOrBuild("toc", true)))
658 // see bug 5082. At least setup title and enabled state.
659 // Visibility will be adjusted by restoreState below.
660 dialog->prepareView();
661 if ((dialog = findOrBuild("view-source", true)))
662 dialog->prepareView();
663 if ((dialog = findOrBuild("progress", true)))
664 dialog->prepareView();
665 if ((dialog = findOrBuild("findreplaceadv", true)))
666 dialog->prepareView();
668 if (!restoreState(settings.value("layout").toByteArray(), 0))
675 GuiToolbar * GuiView::toolbar(string const & name)
677 ToolbarMap::iterator it = d.toolbars_.find(name);
678 if (it != d.toolbars_.end())
681 LYXERR(Debug::GUI, "Toolbar::display: no toolbar named " << name);
686 void GuiView::constructToolbars()
688 ToolbarMap::iterator it = d.toolbars_.begin();
689 for (; it != d.toolbars_.end(); ++it)
693 // I don't like doing this here, but the standard toolbar
694 // destroys this object when it's destroyed itself (vfr)
695 d.layout_ = new LayoutBox(*this);
696 d.stack_widget_->addWidget(d.layout_);
697 d.layout_->move(0,0);
699 // extracts the toolbars from the backend
700 Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
701 Toolbars::Infos::iterator end = guiApp->toolbars().end();
702 for (; cit != end; ++cit)
703 d.toolbars_[cit->name] = new GuiToolbar(*cit, *this);
707 void GuiView::initToolbars()
709 // extracts the toolbars from the backend
710 Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
711 Toolbars::Infos::iterator end = guiApp->toolbars().end();
712 for (; cit != end; ++cit) {
713 GuiToolbar * tb = toolbar(cit->name);
716 int const visibility = guiApp->toolbars().defaultVisibility(cit->name);
717 bool newline = !(visibility & Toolbars::SAMEROW);
718 tb->setVisible(false);
719 tb->setVisibility(visibility);
721 if (visibility & Toolbars::TOP) {
723 addToolBarBreak(Qt::TopToolBarArea);
724 addToolBar(Qt::TopToolBarArea, tb);
727 if (visibility & Toolbars::BOTTOM) {
728 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
729 #if (QT_VERSION >= 0x040202)
731 addToolBarBreak(Qt::BottomToolBarArea);
733 addToolBar(Qt::BottomToolBarArea, tb);
736 if (visibility & Toolbars::LEFT) {
737 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
738 #if (QT_VERSION >= 0x040202)
740 addToolBarBreak(Qt::LeftToolBarArea);
742 addToolBar(Qt::LeftToolBarArea, tb);
745 if (visibility & Toolbars::RIGHT) {
746 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
747 #if (QT_VERSION >= 0x040202)
749 addToolBarBreak(Qt::RightToolBarArea);
751 addToolBar(Qt::RightToolBarArea, tb);
754 if (visibility & Toolbars::ON)
755 tb->setVisible(true);
760 TocModels & GuiView::tocModels()
762 return d.toc_models_;
766 void GuiView::setFocus()
768 LYXERR(Debug::DEBUG, "GuiView::setFocus()" << this);
769 QMainWindow::setFocus();
773 void GuiView::focusInEvent(QFocusEvent * e)
775 LYXERR(Debug::DEBUG, "GuiView::focusInEvent()" << this);
776 QMainWindow::focusInEvent(e);
777 // Make sure guiApp points to the correct view.
778 guiApp->setCurrentView(this);
779 if (currentWorkArea())
780 currentWorkArea()->setFocus();
781 else if (currentMainWorkArea())
782 currentMainWorkArea()->setFocus();
784 d.bg_widget_->setFocus();
788 QMenu * GuiView::createPopupMenu()
790 return d.toolBarPopup(this);
794 void GuiView::showEvent(QShowEvent * e)
796 LYXERR(Debug::GUI, "Passed Geometry "
797 << size().height() << "x" << size().width()
798 << "+" << pos().x() << "+" << pos().y());
800 if (d.splitter_->count() == 0)
801 // No work area, switch to the background widget.
805 QMainWindow::showEvent(e);
809 bool GuiView::closeScheduled()
816 /** Destroy only all tabbed WorkAreas. Destruction of other WorkAreas
817 ** is responsibility of the container (e.g., dialog)
819 void GuiView::closeEvent(QCloseEvent * close_event)
821 LYXERR(Debug::DEBUG, "GuiView::closeEvent()");
823 if (!GuiViewPrivate::busyBuffers.isEmpty()) {
824 Alert::warning(_("Exit LyX"),
825 _("LyX could not be closed because documents are being processed by LyX."));
826 close_event->setAccepted(false);
830 // If the user pressed the x (so we didn't call closeView
831 // programmatically), we want to clear all existing entries.
833 theSession().lastOpened().clear();
838 // it can happen that this event arrives without selecting the view,
839 // e.g. when clicking the close button on a background window.
841 if (!closeWorkAreaAll()) {
843 close_event->ignore();
847 // Make sure that nothing will use this to be closed View.
848 guiApp->unregisterView(this);
850 if (isFullScreen()) {
851 // Switch off fullscreen before closing.
856 // Make sure the timer time out will not trigger a statusbar update.
857 d.statusbar_timer_.stop();
859 // Saving fullscreen requires additional tweaks in the toolbar code.
860 // It wouldn't also work under linux natively.
861 if (lyxrc.allow_geometry_session) {
866 close_event->accept();
870 void GuiView::dragEnterEvent(QDragEnterEvent * event)
872 if (event->mimeData()->hasUrls())
874 /// \todo Ask lyx-devel is this is enough:
875 /// if (event->mimeData()->hasFormat("text/plain"))
876 /// event->acceptProposedAction();
880 void GuiView::dropEvent(QDropEvent * event)
882 QList<QUrl> files = event->mimeData()->urls();
886 LYXERR(Debug::GUI, "GuiView::dropEvent: got URLs!");
887 for (int i = 0; i != files.size(); ++i) {
888 string const file = os::internal_path(fromqstr(
889 files.at(i).toLocalFile()));
893 string const ext = support::getExtension(file);
894 vector<const Format *> found_formats;
896 // Find all formats that have the correct extension.
897 vector<const Format *> const & import_formats
898 = theConverters().importableFormats();
899 vector<const Format *>::const_iterator it = import_formats.begin();
900 for (; it != import_formats.end(); ++it)
901 if ((*it)->hasExtension(ext))
902 found_formats.push_back(*it);
905 if (found_formats.size() >= 1) {
906 if (found_formats.size() > 1) {
907 //FIXME: show a dialog to choose the correct importable format
909 "Multiple importable formats found, selecting first");
911 string const arg = found_formats[0]->name() + " " + file;
912 cmd = FuncRequest(LFUN_BUFFER_IMPORT, arg);
915 //FIXME: do we have to explicitly check whether it's a lyx file?
917 "No formats found, trying to open it as a lyx file");
918 cmd = FuncRequest(LFUN_FILE_OPEN, file);
920 // add the functions to the queue
921 guiApp->addToFuncRequestQueue(cmd);
924 // now process the collected functions. We perform the events
925 // asynchronously. This prevents potential problems in case the
926 // BufferView is closed within an event.
927 guiApp->processFuncRequestQueueAsync();
931 void GuiView::message(docstring const & str)
933 if (ForkedProcess::iAmAChild())
936 // call is moved to GUI-thread by GuiProgress
937 d.progress_->appendMessage(toqstr(str));
941 void GuiView::clearMessageText()
943 message(docstring());
947 void GuiView::updateStatusBarMessage(QString const & str)
949 statusBar()->showMessage(str);
950 d.statusbar_timer_.stop();
951 d.statusbar_timer_.start(3000);
955 void GuiView::smallSizedIcons()
957 setIconSize(QSize(d.smallIconSize, d.smallIconSize));
961 void GuiView::normalSizedIcons()
963 setIconSize(QSize(d.normalIconSize, d.normalIconSize));
967 void GuiView::bigSizedIcons()
969 setIconSize(QSize(d.bigIconSize, d.bigIconSize));
973 void GuiView::clearMessage()
975 // FIXME: This code was introduced in r19643 to fix bug #4123. However,
976 // the hasFocus function mostly returns false, even if the focus is on
977 // a workarea in this view.
981 d.statusbar_timer_.stop();
985 void GuiView::updateWindowTitle(GuiWorkArea * wa)
987 if (wa != d.current_work_area_
988 || wa->bufferView().buffer().isInternal())
990 setWindowTitle(qt_("LyX: ") + wa->windowTitle());
991 setWindowIconText(wa->windowIconText());
995 void GuiView::on_currentWorkAreaChanged(GuiWorkArea * wa)
997 QObject::disconnect(d.current_work_area_, SIGNAL(busy(bool)),
998 this, SLOT(setBusy(bool)));
1000 disconnectBufferView();
1001 connectBufferView(wa->bufferView());
1002 connectBuffer(wa->bufferView().buffer());
1003 d.current_work_area_ = wa;
1004 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
1005 this, SLOT(updateWindowTitle(GuiWorkArea *)));
1006 QObject::connect(wa, SIGNAL(busy(bool)), this, SLOT(setBusy(bool)));
1007 updateWindowTitle(wa);
1011 // The document settings needs to be reinitialised.
1012 updateDialog("document", "");
1014 // Buffer-dependent dialogs must be updated. This is done here because
1015 // some dialogs require buffer()->text.
1020 void GuiView::on_lastWorkAreaRemoved()
1023 // We already are in a close event. Nothing more to do.
1026 if (d.splitter_->count() > 1)
1027 // We have a splitter so don't close anything.
1030 // Reset and updates the dialogs.
1031 d.toc_models_.reset(0);
1032 updateDialog("document", "");
1035 resetWindowTitleAndIconText();
1038 if (lyxrc.open_buffers_in_tabs)
1039 // Nothing more to do, the window should stay open.
1042 if (guiApp->viewIds().size() > 1) {
1048 // On Mac we also close the last window because the application stay
1049 // resident in memory. On other platforms we don't close the last
1050 // window because this would quit the application.
1056 void GuiView::updateStatusBar()
1058 // let the user see the explicit message
1059 if (d.statusbar_timer_.isActive())
1066 void GuiView::showMessage()
1068 QString msg = toqstr(theGuiApp()->viewStatusMessage());
1069 if (msg.isEmpty()) {
1070 BufferView const * bv = currentBufferView();
1072 msg = toqstr(bv->cursor().currentState());
1074 msg = qt_("Welcome to LyX!");
1076 statusBar()->showMessage(msg);
1080 bool GuiView::event(QEvent * e)
1084 // Useful debug code:
1085 //case QEvent::ActivationChange:
1086 //case QEvent::WindowDeactivate:
1087 //case QEvent::Paint:
1088 //case QEvent::Enter:
1089 //case QEvent::Leave:
1090 //case QEvent::HoverEnter:
1091 //case QEvent::HoverLeave:
1092 //case QEvent::HoverMove:
1093 //case QEvent::StatusTip:
1094 //case QEvent::DragEnter:
1095 //case QEvent::DragLeave:
1096 //case QEvent::Drop:
1099 case QEvent::WindowActivate: {
1100 GuiView * old_view = guiApp->currentView();
1101 if (this == old_view) {
1103 return QMainWindow::event(e);
1105 if (old_view && old_view->currentBufferView()) {
1106 // save current selection to the selection buffer to allow
1107 // middle-button paste in this window.
1108 cap::saveSelection(old_view->currentBufferView()->cursor());
1110 guiApp->setCurrentView(this);
1111 if (d.current_work_area_) {
1112 BufferView & bv = d.current_work_area_->bufferView();
1113 connectBufferView(bv);
1114 connectBuffer(bv.buffer());
1115 // The document structure, name and dialogs might have
1116 // changed in another view.
1118 // The document settings needs to be reinitialised.
1119 updateDialog("document", "");
1122 resetWindowTitleAndIconText();
1125 return QMainWindow::event(e);
1128 case QEvent::ShortcutOverride: {
1131 #if (!defined Q_WS_X11) || (QT_VERSION >= 0x040500)
1132 if (isFullScreen() && menuBar()->isHidden()) {
1133 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
1134 // FIXME: we should also try to detect special LyX shortcut such as
1135 // Alt-P and Alt-M. Right now there is a hack in
1136 // GuiWorkArea::processKeySym() that hides again the menubar for
1138 if (ke->modifiers() & Qt::AltModifier && ke->key() != Qt::Key_Alt) {
1140 return QMainWindow::event(e);
1144 return QMainWindow::event(e);
1148 return QMainWindow::event(e);
1152 void GuiView::resetWindowTitleAndIconText()
1154 setWindowTitle(qt_("LyX"));
1155 setWindowIconText(qt_("LyX"));
1158 bool GuiView::focusNextPrevChild(bool /*next*/)
1165 bool GuiView::busy() const
1171 void GuiView::setBusy(bool busy)
1173 bool const busy_before = busy_ > 0;
1174 busy ? ++busy_ : --busy_;
1175 if ((busy_ > 0) == busy_before)
1176 // busy state didn't change
1180 QApplication::setOverrideCursor(Qt::WaitCursor);
1183 QApplication::restoreOverrideCursor();
1188 GuiWorkArea * GuiView::workArea(int index)
1190 if (TabWorkArea * twa = d.currentTabWorkArea())
1191 if (index < twa->count())
1192 return dynamic_cast<GuiWorkArea *>(twa->widget(index));
1197 GuiWorkArea * GuiView::workArea(Buffer & buffer)
1199 if (currentWorkArea()
1200 && ¤tWorkArea()->bufferView().buffer() == &buffer)
1201 return (GuiWorkArea *) currentWorkArea();
1202 if (TabWorkArea * twa = d.currentTabWorkArea())
1203 return twa->workArea(buffer);
1208 GuiWorkArea * GuiView::addWorkArea(Buffer & buffer)
1210 // Automatically create a TabWorkArea if there are none yet.
1211 TabWorkArea * tab_widget = d.splitter_->count()
1212 ? d.currentTabWorkArea() : addTabWorkArea();
1213 return tab_widget->addWorkArea(buffer, *this);
1217 TabWorkArea * GuiView::addTabWorkArea()
1219 TabWorkArea * twa = new TabWorkArea;
1220 QObject::connect(twa, SIGNAL(currentWorkAreaChanged(GuiWorkArea *)),
1221 this, SLOT(on_currentWorkAreaChanged(GuiWorkArea *)));
1222 QObject::connect(twa, SIGNAL(lastWorkAreaRemoved()),
1223 this, SLOT(on_lastWorkAreaRemoved()));
1225 d.splitter_->addWidget(twa);
1226 d.stack_widget_->setCurrentWidget(d.splitter_);
1231 GuiWorkArea const * GuiView::currentWorkArea() const
1233 return d.current_work_area_;
1237 GuiWorkArea * GuiView::currentWorkArea()
1239 return d.current_work_area_;
1243 GuiWorkArea const * GuiView::currentMainWorkArea() const
1245 if (!d.currentTabWorkArea())
1247 return d.currentTabWorkArea()->currentWorkArea();
1251 GuiWorkArea * GuiView::currentMainWorkArea()
1253 if (!d.currentTabWorkArea())
1255 return d.currentTabWorkArea()->currentWorkArea();
1259 void GuiView::setCurrentWorkArea(GuiWorkArea * wa)
1261 LYXERR(Debug::DEBUG, "Setting current wa: " << wa << endl);
1263 d.current_work_area_ = 0;
1268 // FIXME: I've no clue why this is here and why it accesses
1269 // theGuiApp()->currentView, which might be 0 (bug 6464).
1270 // See also 27525 (vfr).
1271 if (theGuiApp()->currentView() == this
1272 && theGuiApp()->currentView()->currentWorkArea() == wa)
1275 if (currentBufferView())
1276 cap::saveSelection(currentBufferView()->cursor());
1278 theGuiApp()->setCurrentView(this);
1279 d.current_work_area_ = wa;
1281 // We need to reset this now, because it will need to be
1282 // right if the tabWorkArea gets reset in the for loop. We
1283 // will change it back if we aren't in that case.
1284 GuiWorkArea * const old_cmwa = d.current_main_work_area_;
1285 d.current_main_work_area_ = wa;
1287 for (int i = 0; i != d.splitter_->count(); ++i) {
1288 if (d.tabWorkArea(i)->setCurrentWorkArea(wa)) {
1289 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea()
1290 << ", Current main wa: " << currentMainWorkArea());
1295 d.current_main_work_area_ = old_cmwa;
1297 LYXERR(Debug::DEBUG, "This is not a tabbed wa");
1298 on_currentWorkAreaChanged(wa);
1299 BufferView & bv = wa->bufferView();
1300 bv.cursor().fixIfBroken();
1302 wa->setUpdatesEnabled(true);
1303 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() << ", Current main wa: " << currentMainWorkArea());
1307 void GuiView::removeWorkArea(GuiWorkArea * wa)
1309 LASSERT(wa, return);
1310 if (wa == d.current_work_area_) {
1312 disconnectBufferView();
1313 d.current_work_area_ = 0;
1314 d.current_main_work_area_ = 0;
1317 bool found_twa = false;
1318 for (int i = 0; i != d.splitter_->count(); ++i) {
1319 TabWorkArea * twa = d.tabWorkArea(i);
1320 if (twa->removeWorkArea(wa)) {
1321 // Found in this tab group, and deleted the GuiWorkArea.
1323 if (twa->count() != 0) {
1324 if (d.current_work_area_ == 0)
1325 // This means that we are closing the current GuiWorkArea, so
1326 // switch to the next GuiWorkArea in the found TabWorkArea.
1327 setCurrentWorkArea(twa->currentWorkArea());
1329 // No more WorkAreas in this tab group, so delete it.
1336 // It is not a tabbed work area (i.e., the search work area), so it
1337 // should be deleted by other means.
1338 LASSERT(found_twa, /* */);
1340 if (d.current_work_area_ == 0) {
1341 if (d.splitter_->count() != 0) {
1342 TabWorkArea * twa = d.currentTabWorkArea();
1343 setCurrentWorkArea(twa->currentWorkArea());
1345 // No more work areas, switch to the background widget.
1346 setCurrentWorkArea(0);
1352 LayoutBox * GuiView::getLayoutDialog() const
1358 void GuiView::updateLayoutList()
1361 d.layout_->updateContents(false);
1365 void GuiView::updateToolbars()
1367 ToolbarMap::iterator end = d.toolbars_.end();
1368 if (d.current_work_area_) {
1370 d.current_work_area_->bufferView().cursor().inMathed()
1371 && !d.current_work_area_->bufferView().cursor().inRegexped();
1373 lyx::getStatus(FuncRequest(LFUN_LAYOUT_TABULAR)).enabled();
1375 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).enabled() &&
1376 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).onOff(true);
1377 bool const mathmacrotemplate =
1378 lyx::getStatus(FuncRequest(LFUN_IN_MATHMACROTEMPLATE)).enabled();
1380 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1381 it->second->update(math, table, review, mathmacrotemplate);
1383 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1384 it->second->update(false, false, false, false);
1388 void GuiView::setBuffer(Buffer * newBuffer)
1390 LYXERR(Debug::DEBUG, "Setting buffer: " << newBuffer << endl);
1391 LASSERT(newBuffer, return);
1393 GuiWorkArea * wa = workArea(*newBuffer);
1396 newBuffer->masterBuffer()->updateBuffer();
1398 wa = addWorkArea(*newBuffer);
1399 // scroll to the position when the BufferView was last closed
1400 if (lyxrc.use_lastfilepos) {
1401 LastFilePosSection::FilePos filepos =
1402 theSession().lastFilePos().load(newBuffer->fileName());
1403 wa->bufferView().moveToPosition(filepos.pit, filepos.pos, 0, 0);
1406 //Disconnect the old buffer...there's no new one.
1409 connectBuffer(*newBuffer);
1410 connectBufferView(wa->bufferView());
1411 setCurrentWorkArea(wa);
1415 void GuiView::connectBuffer(Buffer & buf)
1417 buf.setGuiDelegate(this);
1421 void GuiView::disconnectBuffer()
1423 if (d.current_work_area_)
1424 d.current_work_area_->bufferView().buffer().setGuiDelegate(0);
1428 void GuiView::connectBufferView(BufferView & bv)
1430 bv.setGuiDelegate(this);
1434 void GuiView::disconnectBufferView()
1436 if (d.current_work_area_)
1437 d.current_work_area_->bufferView().setGuiDelegate(0);
1441 void GuiView::errors(string const & error_type, bool from_master)
1443 BufferView const * const bv = currentBufferView();
1447 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
1448 // We are called with from_master == false by default, so we
1449 // have to figure out whether that is the case or not.
1450 ErrorList & el = bv->buffer().errorList(error_type);
1452 el = bv->buffer().masterBuffer()->errorList(error_type);
1456 ErrorList const & el = from_master ?
1457 bv->buffer().masterBuffer()->errorList(error_type) :
1458 bv->buffer().errorList(error_type);
1464 string data = error_type;
1466 data = "from_master|" + error_type;
1467 showDialog("errorlist", data);
1471 void GuiView::updateTocItem(string const & type, DocIterator const & dit)
1473 d.toc_models_.updateItem(toqstr(type), dit);
1477 void GuiView::structureChanged()
1479 d.toc_models_.reset(documentBufferView());
1480 // Navigator needs more than a simple update in this case. It needs to be
1482 updateDialog("toc", "");
1486 void GuiView::updateDialog(string const & name, string const & data)
1488 if (!isDialogVisible(name))
1491 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
1492 if (it == d.dialogs_.end())
1495 Dialog * const dialog = it->second.get();
1496 if (dialog->isVisibleView())
1497 dialog->initialiseParams(data);
1501 BufferView * GuiView::documentBufferView()
1503 return currentMainWorkArea()
1504 ? ¤tMainWorkArea()->bufferView()
1509 BufferView const * GuiView::documentBufferView() const
1511 return currentMainWorkArea()
1512 ? ¤tMainWorkArea()->bufferView()
1517 BufferView * GuiView::currentBufferView()
1519 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1523 BufferView const * GuiView::currentBufferView() const
1525 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1529 #if (QT_VERSION >= 0x040400)
1530 docstring GuiView::GuiViewPrivate::autosaveAndDestroy(
1531 Buffer const * orig, Buffer * buffer)
1533 bool const success = buffer->autoSave();
1535 busyBuffers.remove(orig);
1537 ? _("Automatic save done.")
1538 : _("Automatic save failed!");
1543 void GuiView::autoSave()
1545 LYXERR(Debug::INFO, "Running autoSave()");
1547 Buffer * buffer = documentBufferView()
1548 ? &documentBufferView()->buffer() : 0;
1550 resetAutosaveTimers();
1554 #if (QT_VERSION >= 0x040400)
1555 GuiViewPrivate::busyBuffers.insert(buffer);
1556 QFuture<docstring> f = QtConcurrent::run(GuiViewPrivate::autosaveAndDestroy,
1557 buffer, buffer->clone());
1558 d.autosave_watcher_.setFuture(f);
1562 resetAutosaveTimers();
1566 void GuiView::resetAutosaveTimers()
1569 d.autosave_timeout_.restart();
1573 bool GuiView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1576 Buffer * buf = currentBufferView()
1577 ? ¤tBufferView()->buffer() : 0;
1578 Buffer * doc_buffer = documentBufferView()
1579 ? &(documentBufferView()->buffer()) : 0;
1581 // Check whether we need a buffer
1582 if (!lyxaction.funcHasFlag(cmd.action(), LyXAction::NoBuffer) && !buf) {
1583 // no, exit directly
1584 flag.message(from_utf8(N_("Command not allowed with"
1585 "out any document open")));
1586 flag.setEnabled(false);
1590 if (cmd.origin() == FuncRequest::TOC) {
1591 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
1592 if (!toc || !toc->getStatus(documentBufferView()->cursor(), cmd, flag))
1593 flag.setEnabled(false);
1597 switch(cmd.action()) {
1598 case LFUN_BUFFER_IMPORT:
1601 case LFUN_MASTER_BUFFER_UPDATE:
1602 case LFUN_MASTER_BUFFER_VIEW:
1603 enable = doc_buffer && doc_buffer->parent() != 0
1604 && !d.processing_thread_watcher_.isRunning();
1607 case LFUN_BUFFER_UPDATE:
1608 case LFUN_BUFFER_VIEW: {
1609 if (!doc_buffer || d.processing_thread_watcher_.isRunning()) {
1613 string format = to_utf8(cmd.argument());
1614 if (cmd.argument().empty())
1615 format = doc_buffer->params().getDefaultOutputFormat();
1616 enable = doc_buffer->params().isExportableFormat(format);
1620 case LFUN_BUFFER_RELOAD:
1621 enable = doc_buffer && !doc_buffer->isUnnamed()
1622 && doc_buffer->fileName().exists()
1623 && (!doc_buffer->isClean()
1624 || doc_buffer->isExternallyModified(Buffer::timestamp_method));
1627 case LFUN_BUFFER_CHILD_OPEN:
1628 enable = doc_buffer;
1631 case LFUN_BUFFER_WRITE:
1632 enable = doc_buffer && (doc_buffer->isUnnamed() || !doc_buffer->isClean());
1635 //FIXME: This LFUN should be moved to GuiApplication.
1636 case LFUN_BUFFER_WRITE_ALL: {
1637 // We enable the command only if there are some modified buffers
1638 Buffer * first = theBufferList().first();
1643 // We cannot use a for loop as the buffer list is a cycle.
1645 if (!b->isClean()) {
1649 b = theBufferList().next(b);
1650 } while (b != first);
1654 case LFUN_BUFFER_WRITE_AS:
1655 case LFUN_BUFFER_EXPORT_AS:
1656 enable = doc_buffer;
1659 case LFUN_BUFFER_CLOSE:
1660 enable = doc_buffer;
1663 case LFUN_BUFFER_CLOSE_ALL:
1664 enable = theBufferList().last() != theBufferList().first();
1667 case LFUN_SPLIT_VIEW:
1668 if (cmd.getArg(0) == "vertical")
1669 enable = doc_buffer && (d.splitter_->count() == 1 ||
1670 d.splitter_->orientation() == Qt::Vertical);
1672 enable = doc_buffer && (d.splitter_->count() == 1 ||
1673 d.splitter_->orientation() == Qt::Horizontal);
1676 case LFUN_CLOSE_TAB_GROUP:
1677 enable = d.currentTabWorkArea();
1680 case LFUN_TOOLBAR_TOGGLE: {
1681 string const name = cmd.getArg(0);
1682 if (GuiToolbar * t = toolbar(name))
1683 flag.setOnOff(t->isVisible());
1686 docstring const msg =
1687 bformat(_("Unknown toolbar \"%1$s\""), from_utf8(name));
1693 case LFUN_DROP_LAYOUTS_CHOICE:
1697 case LFUN_UI_TOGGLE:
1698 flag.setOnOff(isFullScreen());
1701 case LFUN_DIALOG_DISCONNECT_INSET:
1704 case LFUN_DIALOG_HIDE:
1705 // FIXME: should we check if the dialog is shown?
1708 case LFUN_DIALOG_TOGGLE:
1709 flag.setOnOff(isDialogVisible(cmd.getArg(0)));
1710 // fall through to set "enable"
1711 case LFUN_DIALOG_SHOW: {
1712 string const name = cmd.getArg(0);
1714 enable = name == "aboutlyx"
1715 || name == "file" //FIXME: should be removed.
1717 || name == "texinfo"
1718 || name == "progress"
1719 || name == "compare";
1720 else if (name == "print")
1721 enable = doc_buffer->params().isExportable("dvi")
1722 && lyxrc.print_command != "none";
1723 else if (name == "character" || name == "symbols") {
1724 if (!buf || buf->isReadonly())
1727 Cursor const & cur = currentBufferView()->cursor();
1728 enable = !(cur.inTexted() && cur.paragraph().isPassThru());
1731 else if (name == "latexlog")
1732 enable = FileName(doc_buffer->logName()).isReadableFile();
1733 else if (name == "spellchecker")
1734 enable = theSpellChecker() && !doc_buffer->isReadonly();
1735 else if (name == "vclog")
1736 enable = doc_buffer->lyxvc().inUse();
1740 case LFUN_DIALOG_UPDATE: {
1741 string const name = cmd.getArg(0);
1743 enable = name == "prefs";
1747 case LFUN_COMMAND_EXECUTE:
1749 case LFUN_MENU_OPEN:
1750 // Nothing to check.
1753 case LFUN_COMPLETION_INLINE:
1754 if (!d.current_work_area_
1755 || !d.current_work_area_->completer().inlinePossible(
1756 currentBufferView()->cursor()))
1760 case LFUN_COMPLETION_POPUP:
1761 if (!d.current_work_area_
1762 || !d.current_work_area_->completer().popupPossible(
1763 currentBufferView()->cursor()))
1767 case LFUN_COMPLETION_COMPLETE:
1768 if (!d.current_work_area_
1769 || !d.current_work_area_->completer().inlinePossible(
1770 currentBufferView()->cursor()))
1774 case LFUN_COMPLETION_ACCEPT:
1775 if (!d.current_work_area_
1776 || (!d.current_work_area_->completer().popupVisible()
1777 && !d.current_work_area_->completer().inlineVisible()
1778 && !d.current_work_area_->completer().completionAvailable()))
1782 case LFUN_COMPLETION_CANCEL:
1783 if (!d.current_work_area_
1784 || (!d.current_work_area_->completer().popupVisible()
1785 && !d.current_work_area_->completer().inlineVisible()))
1789 case LFUN_BUFFER_ZOOM_OUT:
1790 enable = doc_buffer && lyxrc.zoom > 10;
1793 case LFUN_BUFFER_ZOOM_IN:
1794 enable = doc_buffer;
1797 case LFUN_BUFFER_NEXT:
1798 case LFUN_BUFFER_PREVIOUS:
1799 // FIXME: should we check is there is an previous or next buffer?
1801 case LFUN_BUFFER_SWITCH:
1802 // toggle on the current buffer, but do not toggle off
1803 // the other ones (is that a good idea?)
1805 && to_utf8(cmd.argument()) == doc_buffer->absFileName())
1806 flag.setOnOff(true);
1809 case LFUN_VC_REGISTER:
1810 enable = doc_buffer && !doc_buffer->lyxvc().inUse();
1812 case LFUN_VC_CHECK_IN:
1813 enable = doc_buffer && doc_buffer->lyxvc().checkInEnabled();
1815 case LFUN_VC_CHECK_OUT:
1816 enable = doc_buffer && doc_buffer->lyxvc().checkOutEnabled();
1818 case LFUN_VC_LOCKING_TOGGLE:
1819 enable = doc_buffer && !doc_buffer->isReadonly()
1820 && doc_buffer->lyxvc().lockingToggleEnabled();
1821 flag.setOnOff(enable && doc_buffer->lyxvc().locking());
1823 case LFUN_VC_REVERT:
1824 enable = doc_buffer && doc_buffer->lyxvc().inUse() && !doc_buffer->isReadonly();
1826 case LFUN_VC_UNDO_LAST:
1827 enable = doc_buffer && doc_buffer->lyxvc().undoLastEnabled();
1829 case LFUN_VC_REPO_UPDATE:
1830 enable = doc_buffer && doc_buffer->lyxvc().repoUpdateEnabled();
1832 case LFUN_VC_COMMAND: {
1833 if (cmd.argument().empty())
1835 if (!doc_buffer && contains(cmd.getArg(0), 'D'))
1839 case LFUN_VC_COMPARE:
1840 enable = doc_buffer && doc_buffer->lyxvc().prepareFileRevisionEnabled();
1843 case LFUN_SERVER_GOTO_FILE_ROW:
1845 case LFUN_FORWARD_SEARCH:
1846 enable = !(lyxrc.forward_search_dvi.empty() && lyxrc.forward_search_pdf.empty());
1854 flag.setEnabled(false);
1860 static FileName selectTemplateFile()
1862 FileDialog dlg(qt_("Select template file"));
1863 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1864 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
1866 FileDialog::Result result = dlg.open(toqstr(lyxrc.template_path),
1867 QStringList(qt_("LyX Documents (*.lyx)")));
1869 if (result.first == FileDialog::Later)
1871 if (result.second.isEmpty())
1873 return FileName(fromqstr(result.second));
1877 Buffer * GuiView::loadDocument(FileName const & filename, bool tolastfiles)
1881 Buffer * newBuffer = 0;
1883 newBuffer = checkAndLoadLyXFile(filename);
1884 } catch (ExceptionMessage const & e) {
1891 message(_("Document not loaded."));
1895 setBuffer(newBuffer);
1896 newBuffer->errors("Parse");
1899 theSession().lastFiles().add(filename);
1905 void GuiView::openDocument(string const & fname)
1907 string initpath = lyxrc.document_path;
1909 if (documentBufferView()) {
1910 string const trypath = documentBufferView()->buffer().filePath();
1911 // If directory is writeable, use this as default.
1912 if (FileName(trypath).isDirWritable())
1918 if (fname.empty()) {
1919 FileDialog dlg(qt_("Select document to open"), LFUN_FILE_OPEN);
1920 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1921 dlg.setButton2(qt_("Examples|#E#e"),
1922 toqstr(addPath(package().system_support().absFileName(), "examples")));
1924 QStringList filter(qt_("LyX Documents (*.lyx)"));
1925 filter << qt_("LyX-1.3.x Documents (*.lyx13)")
1926 << qt_("LyX-1.4.x Documents (*.lyx14)")
1927 << qt_("LyX-1.5.x Documents (*.lyx15)")
1928 << qt_("LyX-1.6.x Documents (*.lyx16)");
1929 FileDialog::Result result =
1930 dlg.open(toqstr(initpath), filter);
1932 if (result.first == FileDialog::Later)
1935 filename = fromqstr(result.second);
1937 // check selected filename
1938 if (filename.empty()) {
1939 message(_("Canceled."));
1945 // get absolute path of file and add ".lyx" to the filename if
1947 FileName const fullname =
1948 fileSearch(string(), filename, "lyx", support::may_not_exist);
1949 if (!fullname.empty())
1950 filename = fullname.absFileName();
1952 if (!fullname.onlyPath().isDirectory()) {
1953 Alert::warning(_("Invalid filename"),
1954 bformat(_("The directory in the given path\n%1$s\ndoes not exist."),
1955 from_utf8(fullname.absFileName())));
1959 // if the file doesn't exist and isn't already open (bug 6645),
1960 // let the user create one
1961 if (!fullname.exists() && !theBufferList().exists(fullname)) {
1962 // the user specifically chose this name. Believe him.
1963 Buffer * const b = newFile(filename, string(), true);
1969 docstring const disp_fn = makeDisplayPath(filename);
1970 message(bformat(_("Opening document %1$s..."), disp_fn));
1973 Buffer * buf = loadDocument(fullname);
1975 str2 = bformat(_("Document %1$s opened."), disp_fn);
1976 if (buf->lyxvc().inUse())
1977 str2 += " " + from_utf8(buf->lyxvc().versionString()) +
1978 " " + _("Version control detected.");
1980 str2 = bformat(_("Could not open document %1$s"), disp_fn);
1985 // FIXME: clean that
1986 static bool import(GuiView * lv, FileName const & filename,
1987 string const & format, ErrorList & errorList)
1989 FileName const lyxfile(support::changeExtension(filename.absFileName(), ".lyx"));
1991 string loader_format;
1992 vector<string> loaders = theConverters().loaders();
1993 if (find(loaders.begin(), loaders.end(), format) == loaders.end()) {
1994 for (vector<string>::const_iterator it = loaders.begin();
1995 it != loaders.end(); ++it) {
1996 if (!theConverters().isReachable(format, *it))
1999 string const tofile =
2000 support::changeExtension(filename.absFileName(),
2001 formats.extension(*it));
2002 if (!theConverters().convert(0, filename, FileName(tofile),
2003 filename, format, *it, errorList))
2005 loader_format = *it;
2008 if (loader_format.empty()) {
2009 frontend::Alert::error(_("Couldn't import file"),
2010 bformat(_("No information for importing the format %1$s."),
2011 formats.prettyName(format)));
2015 loader_format = format;
2017 if (loader_format == "lyx") {
2018 Buffer * buf = lv->loadDocument(lyxfile);
2022 Buffer * const b = newFile(lyxfile.absFileName(), string(), true);
2026 bool as_paragraphs = loader_format == "textparagraph";
2027 string filename2 = (loader_format == format) ? filename.absFileName()
2028 : support::changeExtension(filename.absFileName(),
2029 formats.extension(loader_format));
2030 lv->currentBufferView()->insertPlaintextFile(FileName(filename2),
2032 guiApp->setCurrentView(lv);
2033 lyx::dispatch(FuncRequest(LFUN_MARK_OFF));
2040 void GuiView::importDocument(string const & argument)
2043 string filename = split(argument, format, ' ');
2045 LYXERR(Debug::INFO, format << " file: " << filename);
2047 // need user interaction
2048 if (filename.empty()) {
2049 string initpath = lyxrc.document_path;
2050 if (documentBufferView()) {
2051 string const trypath = documentBufferView()->buffer().filePath();
2052 // If directory is writeable, use this as default.
2053 if (FileName(trypath).isDirWritable())
2057 docstring const text = bformat(_("Select %1$s file to import"),
2058 formats.prettyName(format));
2060 FileDialog dlg(toqstr(text), LFUN_BUFFER_IMPORT);
2061 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2062 dlg.setButton2(qt_("Examples|#E#e"),
2063 toqstr(addPath(package().system_support().absFileName(), "examples")));
2065 docstring filter = formats.prettyName(format);
2068 filter += from_utf8(formats.extensions(format));
2071 FileDialog::Result result =
2072 dlg.open(toqstr(initpath), fileFilters(toqstr(filter)));
2074 if (result.first == FileDialog::Later)
2077 filename = fromqstr(result.second);
2079 // check selected filename
2080 if (filename.empty())
2081 message(_("Canceled."));
2084 if (filename.empty())
2087 // get absolute path of file
2088 FileName const fullname(support::makeAbsPath(filename));
2090 FileName const lyxfile(support::changeExtension(fullname.absFileName(), ".lyx"));
2092 // Check if the document already is open
2093 Buffer * buf = theBufferList().getBuffer(lyxfile);
2096 if (!closeBuffer()) {
2097 message(_("Canceled."));
2102 docstring const displaypath = makeDisplayPath(lyxfile.absFileName(), 30);
2104 // if the file exists already, and we didn't do
2105 // -i lyx thefile.lyx, warn
2106 if (lyxfile.exists() && fullname != lyxfile) {
2108 docstring text = bformat(_("The document %1$s already exists.\n\n"
2109 "Do you want to overwrite that document?"), displaypath);
2110 int const ret = Alert::prompt(_("Overwrite document?"),
2111 text, 0, 1, _("&Overwrite"), _("&Cancel"));
2114 message(_("Canceled."));
2119 message(bformat(_("Importing %1$s..."), displaypath));
2120 ErrorList errorList;
2121 if (import(this, fullname, format, errorList))
2122 message(_("imported."));
2124 message(_("file not imported!"));
2126 // FIXME (Abdel 12/08/06): Is there a need to display the error list here?
2130 void GuiView::newDocument(string const & filename, bool from_template)
2132 FileName initpath(lyxrc.document_path);
2133 if (documentBufferView()) {
2134 FileName const trypath(documentBufferView()->buffer().filePath());
2135 // If directory is writeable, use this as default.
2136 if (trypath.isDirWritable())
2140 string templatefile;
2141 if (from_template) {
2142 templatefile = selectTemplateFile().absFileName();
2143 if (templatefile.empty())
2148 if (filename.empty())
2149 b = newUnnamedFile(initpath, to_utf8(_("newfile")), templatefile);
2151 b = newFile(filename, templatefile, true);
2156 // If no new document could be created, it is unsure
2157 // whether there is a valid BufferView.
2158 if (currentBufferView())
2159 // Ensure the cursor is correctly positioned on screen.
2160 currentBufferView()->showCursor();
2164 void GuiView::insertLyXFile(docstring const & fname)
2166 BufferView * bv = documentBufferView();
2171 FileName filename(to_utf8(fname));
2172 if (filename.empty()) {
2173 // Launch a file browser
2175 string initpath = lyxrc.document_path;
2176 string const trypath = bv->buffer().filePath();
2177 // If directory is writeable, use this as default.
2178 if (FileName(trypath).isDirWritable())
2182 FileDialog dlg(qt_("Select LyX document to insert"), LFUN_FILE_INSERT);
2183 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2184 dlg.setButton2(qt_("Examples|#E#e"),
2185 toqstr(addPath(package().system_support().absFileName(),
2188 FileDialog::Result result = dlg.open(toqstr(initpath),
2189 QStringList(qt_("LyX Documents (*.lyx)")));
2191 if (result.first == FileDialog::Later)
2195 filename.set(fromqstr(result.second));
2197 // check selected filename
2198 if (filename.empty()) {
2199 // emit message signal.
2200 message(_("Canceled."));
2205 bv->insertLyXFile(filename);
2206 bv->buffer().errors("Parse");
2210 void GuiView::insertPlaintextFile(docstring const & fname,
2213 BufferView * bv = documentBufferView();
2217 if (!fname.empty() && !FileName::isAbsolute(to_utf8(fname))) {
2218 message(_("Absolute filename expected."));
2223 FileName filename(to_utf8(fname));
2225 if (!filename.empty()) {
2226 bv->insertPlaintextFile(filename, asParagraph);
2230 FileDialog dlg(qt_("Select file to insert"), (asParagraph ?
2231 LFUN_FILE_INSERT_PLAINTEXT_PARA : LFUN_FILE_INSERT_PLAINTEXT));
2233 FileDialog::Result result = dlg.open(toqstr(bv->buffer().filePath()),
2234 QStringList(qt_("All Files (*)")));
2236 if (result.first == FileDialog::Later)
2240 filename.set(fromqstr(result.second));
2242 // check selected filename
2243 if (filename.empty()) {
2244 // emit message signal.
2245 message(_("Canceled."));
2249 bv->insertPlaintextFile(filename, asParagraph);
2253 bool GuiView::renameBuffer(Buffer & b, docstring const & newname)
2255 FileName fname = b.fileName();
2256 FileName const oldname = fname;
2258 if (!newname.empty()) {
2260 fname = support::makeAbsPath(to_utf8(newname), oldname.onlyPath().absFileName());
2262 // Switch to this Buffer.
2265 // No argument? Ask user through dialog.
2267 FileDialog dlg(qt_("Choose a filename to save document as"),
2268 LFUN_BUFFER_WRITE_AS);
2269 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2270 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
2272 if (!isLyXFileName(fname.absFileName()))
2273 fname.changeExtension(".lyx");
2275 FileDialog::Result result =
2276 dlg.save(toqstr(fname.onlyPath().absFileName()),
2277 QStringList(qt_("LyX Documents (*.lyx)")),
2278 toqstr(fname.onlyFileName()));
2280 if (result.first == FileDialog::Later)
2283 fname.set(fromqstr(result.second));
2288 if (!isLyXFileName(fname.absFileName()))
2289 fname.changeExtension(".lyx");
2292 // fname is now the new Buffer location.
2293 if (FileName(fname).exists()) {
2294 docstring const file = makeDisplayPath(fname.absFileName(), 30);
2295 docstring text = bformat(_("The document %1$s already "
2296 "exists.\n\nDo you want to "
2297 "overwrite that document?"),
2299 int const ret = Alert::prompt(_("Overwrite document?"),
2300 text, 0, 2, _("&Overwrite"), _("&Rename"), _("&Cancel"));
2303 case 1: return renameBuffer(b, docstring());
2304 case 2: return false;
2308 return saveBuffer(b, fname);
2312 struct PrettyNameComparator
2314 bool operator()(Format const *first, Format const *second) const {
2315 return compare_ascii_no_case(first->prettyname(), second->prettyname()) <= 0;
2320 bool GuiView::exportBufferAs(Buffer & b)
2322 FileName fname = b.fileName();
2324 FileDialog dlg(qt_("Choose a filename to export the document as"));
2325 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2328 types << "Any supported format (*.*)";
2329 Formats::const_iterator it = formats.begin();
2330 vector<Format const *> export_formats;
2331 for (; it != formats.end(); ++it)
2332 if (it->documentFormat() && it->inExportMenu())
2333 export_formats.push_back(&(*it));
2334 PrettyNameComparator cmp;
2335 sort(export_formats.begin(), export_formats.end(), cmp);
2336 vector<Format const *>::const_iterator fit = export_formats.begin();
2337 for (; fit != export_formats.end(); ++fit)
2338 types << toqstr((*fit)->prettyname() + " (*." + (*fit)->extension() + ")");
2340 FileDialog::Result result =
2341 dlg.save(toqstr(fname.onlyPath().absFileName()),
2343 toqstr(fname.onlyFileName()),
2345 if (result.first != FileDialog::Chosen)
2348 string s = fromqstr(filter);
2349 size_t pos = s.find(" (*.");
2350 LASSERT(pos != string::npos, /**/);
2351 string fmt_prettyname = s.substr(0, pos);
2353 fname.set(fromqstr(result.second));
2354 if (fmt_prettyname == "Any supported format")
2355 fmt_name = formats.getFormatFromExtension(fname.extension());
2357 fmt_name = formats.getFormatFromPrettyName(fmt_prettyname);
2358 LYXERR(Debug::FILES, "fmt_prettyname=" << fmt_prettyname
2359 << ", fmt_name=" << fmt_name << ", fname=" << fname.absFileName());
2361 if (fmt_name.empty() || fname.empty())
2364 // fname is now the new Buffer location.
2365 if (FileName(fname).exists()) {
2366 docstring const file = makeDisplayPath(fname.absFileName(), 30);
2367 docstring text = bformat(_("The document %1$s already "
2368 "exists.\n\nDo you want to "
2369 "overwrite that document?"),
2371 int const ret = Alert::prompt(_("Overwrite document?"),
2372 text, 0, 2, _("&Overwrite"), _("&Rename"), _("&Cancel"));
2375 case 1: return exportBufferAs(b);
2376 case 2: return false;
2380 FuncRequest cmd(LFUN_BUFFER_EXPORT, fmt_name + " " + fname.absFileName());
2383 return dr.dispatched();
2387 bool GuiView::saveBuffer(Buffer & b) {
2388 return saveBuffer(b, FileName());
2392 bool GuiView::saveBuffer(Buffer & b, FileName const & fn)
2394 if (workArea(b) && workArea(b)->inDialogMode())
2397 if (fn.empty() && b.isUnnamed())
2398 return renameBuffer(b, docstring());
2404 success = b.saveAs(fn);
2407 theSession().lastFiles().add(b.fileName());
2411 // Switch to this Buffer.
2414 // FIXME: we don't tell the user *WHY* the save failed !!
2415 docstring const file = makeDisplayPath(b.absFileName(), 30);
2416 docstring text = bformat(_("The document %1$s could not be saved.\n\n"
2417 "Do you want to rename the document and "
2418 "try again?"), file);
2419 int const ret = Alert::prompt(_("Rename and save?"),
2420 text, 0, 2, _("&Rename"), _("&Retry"), _("&Cancel"));
2423 if (!renameBuffer(b, docstring()))
2432 return saveBuffer(b);
2436 bool GuiView::hideWorkArea(GuiWorkArea * wa)
2438 return closeWorkArea(wa, false);
2442 bool GuiView::closeWorkArea(GuiWorkArea * wa)
2444 Buffer & buf = wa->bufferView().buffer();
2445 return closeWorkArea(wa, !buf.parent());
2449 bool GuiView::closeBuffer()
2451 GuiWorkArea * wa = currentMainWorkArea();
2452 setCurrentWorkArea(wa);
2453 Buffer & buf = wa->bufferView().buffer();
2454 return wa && closeWorkArea(wa, !buf.parent());
2458 void GuiView::writeSession() const {
2459 GuiWorkArea const * active_wa = currentMainWorkArea();
2460 for (int i = 0; i < d.splitter_->count(); ++i) {
2461 TabWorkArea * twa = d.tabWorkArea(i);
2462 for (int j = 0; j < twa->count(); ++j) {
2463 GuiWorkArea * wa = static_cast<GuiWorkArea *>(twa->widget(j));
2464 Buffer & buf = wa->bufferView().buffer();
2465 theSession().lastOpened().add(buf.fileName(), wa == active_wa);
2471 bool GuiView::closeBufferAll()
2473 // Close the workareas in all other views
2474 QList<int> const ids = guiApp->viewIds();
2475 for (int i = 0; i != ids.size(); ++i) {
2476 if (id_ != ids[i] && !guiApp->view(ids[i]).closeWorkAreaAll())
2480 // Close our own workareas
2481 if (!closeWorkAreaAll())
2484 // Now close the hidden buffers. We prevent hidden buffers from being
2485 // dirty, so we can just close them.
2486 theBufferList().closeAll();
2491 bool GuiView::closeWorkAreaAll()
2493 setCurrentWorkArea(currentMainWorkArea());
2495 // We might be in a situation that there is still a tabWorkArea, but
2496 // there are no tabs anymore. This can happen when we get here after a
2497 // TabWorkArea::lastWorkAreaRemoved() signal. Therefore we count how
2498 // many TabWorkArea's have no documents anymore.
2501 // We have to call count() each time, because it can happen that
2502 // more than one splitter will disappear in one iteration (bug 5998).
2503 for (; d.splitter_->count() > empty_twa; ) {
2504 TabWorkArea * twa = d.tabWorkArea(empty_twa);
2506 if (twa->count() == 0)
2509 setCurrentWorkArea(twa->currentWorkArea());
2510 if (!closeTabWorkArea(twa))
2518 bool GuiView::closeWorkArea(GuiWorkArea * wa, bool close_buffer)
2523 Buffer & buf = wa->bufferView().buffer();
2525 if (close_buffer && GuiViewPrivate::busyBuffers.contains(&buf)) {
2526 Alert::warning(_("Close document"),
2527 _("Document could not be closed because it is being processed by LyX."));
2532 return closeBuffer(buf);
2534 if (!inMultiTabs(wa))
2535 if (!saveBufferIfNeeded(buf, true))
2543 bool GuiView::closeBuffer(Buffer & buf)
2545 // If we are in a close_event all children will be closed in some time,
2546 // so no need to do it here. This will ensure that the children end up
2547 // in the session file in the correct order. If we close the master
2548 // buffer, we can close or release the child buffers here too.
2549 bool success = true;
2551 ListOfBuffers clist = buf.getChildren();
2552 ListOfBuffers::const_iterator it = clist.begin();
2553 ListOfBuffers::const_iterator const bend = clist.end();
2554 for (; it != bend; ++it) {
2555 // If a child is dirty, do not close
2556 // without user intervention
2557 //FIXME: should we look in other tabworkareas?
2558 Buffer * child_buf = *it;
2559 GuiWorkArea * child_wa = workArea(*child_buf);
2561 if (!closeWorkArea(child_wa, true)) {
2566 theBufferList().releaseChild(&buf, child_buf);
2570 // goto bookmark to update bookmark pit.
2571 //FIXME: we should update only the bookmarks related to this buffer!
2572 LYXERR(Debug::DEBUG, "GuiView::closeBuffer()");
2573 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
2574 guiApp->gotoBookmark(i+1, false, false);
2576 if (saveBufferIfNeeded(buf, false)) {
2577 buf.removeAutosaveFile();
2578 theBufferList().release(&buf);
2582 // open all children again to avoid a crash because of dangling
2583 // pointers (bug 6603)
2589 bool GuiView::closeTabWorkArea(TabWorkArea * twa)
2591 while (twa == d.currentTabWorkArea()) {
2592 twa->setCurrentIndex(twa->count()-1);
2594 GuiWorkArea * wa = twa->currentWorkArea();
2595 Buffer & b = wa->bufferView().buffer();
2597 // We only want to close the buffer if the same buffer is not visible
2598 // in another view, and if this is not a child and if we are closing
2599 // a view (not a tabgroup).
2600 bool const close_buffer =
2601 !inOtherView(b) && !b.parent() && closing_;
2603 if (!closeWorkArea(wa, close_buffer))
2610 bool GuiView::saveBufferIfNeeded(Buffer & buf, bool hiding)
2612 if (buf.isClean() || buf.paragraphs().empty())
2615 // Switch to this Buffer.
2620 if (buf.isUnnamed())
2621 file = from_utf8(buf.fileName().onlyFileName());
2623 file = buf.fileName().displayName(30);
2625 // Bring this window to top before asking questions.
2630 if (hiding && buf.isUnnamed()) {
2631 docstring const text = bformat(_("The document %1$s has not been "
2632 "saved yet.\n\nDo you want to save "
2633 "the document?"), file);
2634 ret = Alert::prompt(_("Save new document?"),
2635 text, 0, 1, _("&Save"), _("&Cancel"));
2639 docstring const text = bformat(_("The document %1$s has unsaved changes."
2640 "\n\nDo you want to save the document or discard the changes?"), file);
2641 ret = Alert::prompt(_("Save changed document?"),
2642 text, 0, 2, _("&Save"), _("&Discard"), _("&Cancel"));
2647 if (!saveBuffer(buf))
2651 // If we crash after this we could have no autosave file
2652 // but I guess this is really improbable (Jug).
2653 // Sometimes improbable things happen:
2654 // - see bug http://www.lyx.org/trac/ticket/6587 (ps)
2655 // buf.removeAutosaveFile();
2657 // revert all changes
2668 bool GuiView::inMultiTabs(GuiWorkArea * wa)
2670 Buffer & buf = wa->bufferView().buffer();
2672 for (int i = 0; i != d.splitter_->count(); ++i) {
2673 GuiWorkArea * wa_ = d.tabWorkArea(i)->workArea(buf);
2674 if (wa_ && wa_ != wa)
2677 return inOtherView(buf);
2681 bool GuiView::inOtherView(Buffer & buf)
2683 QList<int> const ids = guiApp->viewIds();
2685 for (int i = 0; i != ids.size(); ++i) {
2689 if (guiApp->view(ids[i]).workArea(buf))
2696 void GuiView::gotoNextOrPreviousBuffer(NextOrPrevious np)
2698 if (!documentBufferView())
2701 if (TabWorkArea * twa = d.currentTabWorkArea()) {
2702 Buffer * const curbuf = &documentBufferView()->buffer();
2703 int nwa = twa->count();
2704 for (int i = 0; i < nwa; ++i) {
2705 if (&workArea(i)->bufferView().buffer() == curbuf) {
2707 if (np == NEXTBUFFER)
2708 next_index = (i == nwa - 1 ? 0 : i + 1);
2710 next_index = (i == 0 ? nwa - 1 : i - 1);
2711 setBuffer(&workArea(next_index)->bufferView().buffer());
2719 /// make sure the document is saved
2720 static bool ensureBufferClean(Buffer * buffer)
2722 LASSERT(buffer, return false);
2723 if (buffer->isClean() && !buffer->isUnnamed())
2726 docstring const file = buffer->fileName().displayName(30);
2729 if (!buffer->isUnnamed()) {
2730 text = bformat(_("The document %1$s has unsaved "
2731 "changes.\n\nDo you want to save "
2732 "the document?"), file);
2733 title = _("Save changed document?");
2736 text = bformat(_("The document %1$s has not been "
2737 "saved yet.\n\nDo you want to save "
2738 "the document?"), file);
2739 title = _("Save new document?");
2741 int const ret = Alert::prompt(title, text, 0, 1, _("&Save"), _("&Cancel"));
2744 dispatch(FuncRequest(LFUN_BUFFER_WRITE));
2746 return buffer->isClean() && !buffer->isUnnamed();
2750 bool GuiView::reloadBuffer(Buffer & buf)
2752 Buffer::ReadStatus status = buf.reload();
2753 return status == Buffer::ReadSuccess;
2757 void GuiView::checkExternallyModifiedBuffers()
2759 BufferList::iterator bit = theBufferList().begin();
2760 BufferList::iterator const bend = theBufferList().end();
2761 for (; bit != bend; ++bit) {
2762 Buffer * buf = *bit;
2763 if (buf->fileName().exists()
2764 && buf->isExternallyModified(Buffer::checksum_method)) {
2765 docstring text = bformat(_("Document \n%1$s\n has been externally modified."
2766 " Reload now? Any local changes will be lost."),
2767 from_utf8(buf->absFileName()));
2768 int const ret = Alert::prompt(_("Reload externally changed document?"),
2769 text, 0, 1, _("&Reload"), _("&Cancel"));
2777 void GuiView::dispatchVC(FuncRequest const & cmd, DispatchResult & dr)
2779 Buffer * buffer = documentBufferView()
2780 ? &(documentBufferView()->buffer()) : 0;
2782 switch (cmd.action()) {
2783 case LFUN_VC_REGISTER:
2784 if (!buffer || !ensureBufferClean(buffer))
2786 if (!buffer->lyxvc().inUse()) {
2787 if (buffer->lyxvc().registrer()) {
2788 reloadBuffer(*buffer);
2789 dr.suppressMessageUpdate();
2794 case LFUN_VC_CHECK_IN:
2795 if (!buffer || !ensureBufferClean(buffer))
2797 if (buffer->lyxvc().inUse() && !buffer->isReadonly()) {
2798 dr.setMessage(buffer->lyxvc().checkIn());
2799 if (!dr.message().empty())
2800 reloadBuffer(*buffer);
2804 case LFUN_VC_CHECK_OUT:
2805 if (!buffer || !ensureBufferClean(buffer))
2807 if (buffer->lyxvc().inUse()) {
2808 dr.setMessage(buffer->lyxvc().checkOut());
2809 reloadBuffer(*buffer);
2813 case LFUN_VC_LOCKING_TOGGLE:
2814 LASSERT(buffer, return);
2815 if (!ensureBufferClean(buffer) || buffer->isReadonly())
2817 if (buffer->lyxvc().inUse()) {
2818 string res = buffer->lyxvc().lockingToggle();
2820 frontend::Alert::error(_("Revision control error."),
2821 _("Error when setting the locking property."));
2824 reloadBuffer(*buffer);
2829 case LFUN_VC_REVERT:
2830 LASSERT(buffer, return);
2831 if (buffer->lyxvc().revert()) {
2832 reloadBuffer(*buffer);
2833 dr.suppressMessageUpdate();
2837 case LFUN_VC_UNDO_LAST:
2838 LASSERT(buffer, return);
2839 buffer->lyxvc().undoLast();
2840 reloadBuffer(*buffer);
2841 dr.suppressMessageUpdate();
2844 case LFUN_VC_REPO_UPDATE:
2845 LASSERT(buffer, return);
2846 if (ensureBufferClean(buffer)) {
2847 dr.setMessage(buffer->lyxvc().repoUpdate());
2848 checkExternallyModifiedBuffers();
2852 case LFUN_VC_COMMAND: {
2853 string flag = cmd.getArg(0);
2854 if (buffer && contains(flag, 'R') && !ensureBufferClean(buffer))
2857 if (contains(flag, 'M')) {
2858 if (!Alert::askForText(message, _("LyX VC: Log Message")))
2861 string path = cmd.getArg(1);
2862 if (contains(path, "$$p") && buffer)
2863 path = subst(path, "$$p", buffer->filePath());
2864 LYXERR(Debug::LYXVC, "Directory: " << path);
2866 if (!pp.isReadableDirectory()) {
2867 lyxerr << _("Directory is not accessible.") << endl;
2870 support::PathChanger p(pp);
2872 string command = cmd.getArg(2);
2873 if (command.empty())
2876 command = subst(command, "$$i", buffer->absFileName());
2877 command = subst(command, "$$p", buffer->filePath());
2879 command = subst(command, "$$m", to_utf8(message));
2880 LYXERR(Debug::LYXVC, "Command: " << command);
2882 one.startscript(Systemcall::Wait, command);
2886 if (contains(flag, 'I'))
2887 buffer->markDirty();
2888 if (contains(flag, 'R'))
2889 reloadBuffer(*buffer);
2894 case LFUN_VC_COMPARE: {
2896 if (cmd.argument().empty()) {
2897 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "comparehistory"));
2901 string rev1 = cmd.getArg(0);
2905 if (!buffer->lyxvc().prepareFileRevision(rev1, f1))
2908 if (isStrInt(rev1) && convert<int>(rev1) <= 0) {
2909 f2 = buffer->absFileName();
2911 string rev2 = cmd.getArg(1);
2915 if (!buffer->lyxvc().prepareFileRevision(rev2, f2))
2919 LYXERR(Debug::LYXVC, "Launching comparison for fetched revisions:\n" <<
2920 f1 << "\n" << f2 << "\n" );
2921 string par = "compare run " + quoteName(f1) + " " + quoteName(f2);
2922 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, par));
2932 void GuiView::openChildDocument(string const & fname)
2934 LASSERT(documentBufferView(), return);
2935 Buffer & buffer = documentBufferView()->buffer();
2936 FileName const filename = support::makeAbsPath(fname, buffer.filePath());
2937 documentBufferView()->saveBookmark(false);
2939 if (theBufferList().exists(filename)) {
2940 child = theBufferList().getBuffer(filename);
2943 message(bformat(_("Opening child document %1$s..."),
2944 makeDisplayPath(filename.absFileName())));
2945 child = loadDocument(filename, false);
2947 // Set the parent name of the child document.
2948 // This makes insertion of citations and references in the child work,
2949 // when the target is in the parent or another child document.
2951 child->setParent(&buffer);
2955 bool GuiView::goToFileRow(string const & argument)
2959 size_t i = argument.find_last_of(' ');
2960 if (i != string::npos) {
2961 file_name = os::internal_path(trim(argument.substr(0, i)));
2962 istringstream is(argument.substr(i + 1));
2967 if (i == string::npos) {
2968 LYXERR0("Wrong argument: " << argument);
2972 string const abstmp = package().temp_dir().absFileName();
2973 string const realtmp = package().temp_dir().realPath();
2974 // We have to use os::path_prefix_is() here, instead of
2975 // simply prefixIs(), because the file name comes from
2976 // an external application and may need case adjustment.
2977 if (os::path_prefix_is(file_name, abstmp, os::CASE_ADJUSTED)
2978 || os::path_prefix_is(file_name, realtmp, os::CASE_ADJUSTED)) {
2979 // Needed by inverse dvi search. If it is a file
2980 // in tmpdir, call the apropriated function.
2981 // If tmpdir is a symlink, we may have the real
2982 // path passed back, so we correct for that.
2983 if (!prefixIs(file_name, abstmp))
2984 file_name = subst(file_name, realtmp, abstmp);
2985 buf = theBufferList().getBufferFromTmp(file_name);
2987 // Must replace extension of the file to be .lyx
2988 // and get full path
2989 FileName const s = fileSearch(string(),
2990 support::changeExtension(file_name, ".lyx"), "lyx");
2991 // Either change buffer or load the file
2992 if (theBufferList().exists(s))
2993 buf = theBufferList().getBuffer(s);
2994 else if (s.exists()) {
2995 buf = loadDocument(s);
3000 _("File does not exist: %1$s"),
3001 makeDisplayPath(file_name)));
3007 _("No buffer for file: %1$s."),
3008 makeDisplayPath(file_name))
3013 documentBufferView()->setCursorFromRow(row);
3018 #if (QT_VERSION >= 0x040400)
3020 docstring GuiView::GuiViewPrivate::runAndDestroy(const T& func, Buffer const * orig, Buffer * buffer, string const & format, string const & msg)
3022 bool const success = func(format);
3024 // the cloning operation will have produced a clone of the entire set of
3025 // documents, starting from the master. so we must delete those.
3026 Buffer * mbuf = const_cast<Buffer *>(buffer->masterBuffer());
3028 busyBuffers.remove(orig);
3029 if (msg == "preview") {
3031 ? bformat(_("Successful preview of format: %1$s"), from_utf8(format))
3032 : bformat(_("Error while previewing format: %1$s"), from_utf8(format));
3035 ? bformat(_("Successful export to format: %1$s"), from_utf8(format))
3036 : bformat(_("Error while exporting format: %1$s"), from_utf8(format));
3040 docstring GuiView::GuiViewPrivate::compileAndDestroy(Buffer const * orig, Buffer * buffer, string const & format)
3042 bool (Buffer::* mem_func)(std::string const &, bool) const = &Buffer::doExport;
3043 return runAndDestroy(bind(mem_func, buffer, _1, true), orig, buffer, format, "export");
3047 docstring GuiView::GuiViewPrivate::exportAndDestroy(Buffer const * orig, Buffer * buffer, string const & format)
3049 bool (Buffer::* mem_func)(std::string const &, bool) const = &Buffer::doExport;
3050 return runAndDestroy(bind(mem_func, buffer, _1, false), orig, buffer, format, "export");
3054 docstring GuiView::GuiViewPrivate::previewAndDestroy(Buffer const * orig, Buffer * buffer, string const & format)
3056 bool(Buffer::* mem_func)(std::string const &) const = &Buffer::preview;
3057 return runAndDestroy(bind(mem_func, buffer, _1), orig, buffer, format, "preview");
3062 // not used, but the linker needs them
3064 docstring GuiView::GuiViewPrivate::compileAndDestroy(
3065 Buffer const *, Buffer *, string const &)
3071 docstring GuiView::GuiViewPrivate::exportAndDestroy(
3072 Buffer const *, Buffer *, string const &)
3078 docstring GuiView::GuiViewPrivate::previewAndDestroy(
3079 Buffer const *, Buffer *, string const &)
3087 bool GuiView::GuiViewPrivate::asyncBufferProcessing(
3088 string const & argument,
3089 Buffer const * used_buffer,
3090 docstring const & msg,
3091 docstring (*asyncFunc)(Buffer const *, Buffer *, string const &),
3092 bool (Buffer::*syncFunc)(string const &, bool) const,
3093 bool (Buffer::*previewFunc)(string const &) const)
3098 string format = argument;
3100 format = used_buffer->params().getDefaultOutputFormat();
3102 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
3104 progress_->clearMessages();
3107 GuiViewPrivate::busyBuffers.insert(used_buffer);
3108 QFuture<docstring> f = QtConcurrent::run(
3111 used_buffer->clone(),
3113 setPreviewFuture(f);
3114 last_export_format = used_buffer->params().bufferFormat();
3117 // We are asynchronous, so we don't know here anything about the success
3121 // TODO check here if it breaks exporting with Qt < 4.4
3122 return (used_buffer->*syncFunc)(format, true);
3123 } else if (previewFunc) {
3124 return (used_buffer->*previewFunc)(format, false);
3131 void GuiView::dispatchToBufferView(FuncRequest const & cmd, DispatchResult & dr)
3133 BufferView * bv = currentBufferView();
3136 // Let the current BufferView dispatch its own actions.
3137 bv->dispatch(cmd, dr);
3138 if (dr.dispatched())
3141 // Try with the document BufferView dispatch if any.
3142 BufferView * doc_bv = documentBufferView();
3143 if (doc_bv && doc_bv != bv) {
3144 doc_bv->dispatch(cmd, dr);
3145 if (dr.dispatched())
3149 // Then let the current Cursor dispatch its own actions.
3150 bv->cursor().dispatch(cmd);
3152 // update completion. We do it here and not in
3153 // processKeySym to avoid another redraw just for a
3154 // changed inline completion
3155 if (cmd.origin() == FuncRequest::KEYBOARD) {
3156 if (cmd.action() == LFUN_SELF_INSERT
3157 || (cmd.action() == LFUN_ERT_INSERT && bv->cursor().inMathed()))
3158 updateCompletion(bv->cursor(), true, true);
3159 else if (cmd.action() == LFUN_CHAR_DELETE_BACKWARD)
3160 updateCompletion(bv->cursor(), false, true);
3162 updateCompletion(bv->cursor(), false, false);
3165 dr = bv->cursor().result();
3169 void GuiView::dispatch(FuncRequest const & cmd, DispatchResult & dr)
3171 BufferView * bv = currentBufferView();
3172 // By default we won't need any update.
3173 dr.screenUpdate(Update::None);
3174 // assume cmd will be dispatched
3175 dr.dispatched(true);
3177 Buffer * doc_buffer = documentBufferView()
3178 ? &(documentBufferView()->buffer()) : 0;
3180 if (cmd.origin() == FuncRequest::TOC) {
3181 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
3182 // FIXME: do we need to pass a DispatchResult object here?
3183 toc->doDispatch(bv->cursor(), cmd);
3187 string const argument = to_utf8(cmd.argument());
3189 switch(cmd.action()) {
3190 case LFUN_BUFFER_CHILD_OPEN:
3191 openChildDocument(to_utf8(cmd.argument()));
3194 case LFUN_BUFFER_IMPORT:
3195 importDocument(to_utf8(cmd.argument()));
3198 case LFUN_BUFFER_EXPORT: {
3201 // GCC only sees strfwd.h when building merged
3202 if (::lyx::operator==(cmd.argument(), "custom")) {
3203 dispatch(FuncRequest(LFUN_DIALOG_SHOW, "sendto"), dr);
3206 #if QT_VERSION < 0x040400
3207 if (!doc_buffer->doExport(argument, false)) {
3209 dr.setMessage(bformat(_("Error exporting to format: %1$s"),
3213 /* TODO/Review: Is it a problem to also export the children?
3214 See the update_unincluded flag */
3215 d.asyncBufferProcessing(argument,
3218 &GuiViewPrivate::exportAndDestroy,
3221 // TODO Inform user about success
3226 case LFUN_BUFFER_EXPORT_AS:
3227 LASSERT(doc_buffer, break);
3228 exportBufferAs(*doc_buffer);
3231 case LFUN_BUFFER_UPDATE: {
3232 d.asyncBufferProcessing(argument,
3235 &GuiViewPrivate::compileAndDestroy,
3240 case LFUN_BUFFER_VIEW: {
3241 d.asyncBufferProcessing(argument,
3243 _("Previewing ..."),
3244 &GuiViewPrivate::previewAndDestroy,
3249 case LFUN_MASTER_BUFFER_UPDATE: {
3250 d.asyncBufferProcessing(argument,
3251 (doc_buffer ? doc_buffer->masterBuffer() : 0),
3253 &GuiViewPrivate::compileAndDestroy,
3258 case LFUN_MASTER_BUFFER_VIEW: {
3259 d.asyncBufferProcessing(argument,
3260 (doc_buffer ? doc_buffer->masterBuffer() : 0),
3262 &GuiViewPrivate::previewAndDestroy,
3263 0, &Buffer::preview);
3266 case LFUN_BUFFER_SWITCH: {
3267 string const file_name = to_utf8(cmd.argument());
3268 if (!FileName::isAbsolute(file_name)) {
3270 dr.setMessage(_("Absolute filename expected."));
3274 Buffer * buffer = theBufferList().getBuffer(FileName(file_name));
3277 dr.setMessage(_("Document not loaded"));
3281 // Do we open or switch to the buffer in this view ?
3282 if (workArea(*buffer)
3283 || lyxrc.open_buffers_in_tabs || !documentBufferView()) {
3288 // Look for the buffer in other views
3289 QList<int> const ids = guiApp->viewIds();
3291 for (; i != ids.size(); ++i) {
3292 GuiView & gv = guiApp->view(ids[i]);
3293 if (gv.workArea(*buffer)) {
3294 gv.activateWindow();
3295 gv.setBuffer(buffer);
3300 // If necessary, open a new window as a last resort
3301 if (i == ids.size()) {
3302 lyx::dispatch(FuncRequest(LFUN_WINDOW_NEW));
3308 case LFUN_BUFFER_NEXT:
3309 gotoNextOrPreviousBuffer(NEXTBUFFER);
3312 case LFUN_BUFFER_PREVIOUS:
3313 gotoNextOrPreviousBuffer(PREVBUFFER);
3316 case LFUN_COMMAND_EXECUTE: {
3317 bool const show_it = cmd.argument() != "off";
3318 // FIXME: this is a hack, "minibuffer" should not be
3320 if (GuiToolbar * t = toolbar("minibuffer")) {
3321 t->setVisible(show_it);
3322 if (show_it && t->commandBuffer())
3323 t->commandBuffer()->setFocus();
3327 case LFUN_DROP_LAYOUTS_CHOICE:
3328 d.layout_->showPopup();
3331 case LFUN_MENU_OPEN:
3332 if (QMenu * menu = guiApp->menus().menu(toqstr(cmd.argument()), *this))
3333 menu->exec(QCursor::pos());
3336 case LFUN_FILE_INSERT:
3337 insertLyXFile(cmd.argument());
3340 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
3341 insertPlaintextFile(cmd.argument(), true);
3344 case LFUN_FILE_INSERT_PLAINTEXT:
3345 insertPlaintextFile(cmd.argument(), false);
3348 case LFUN_BUFFER_RELOAD: {
3349 LASSERT(doc_buffer, break);
3352 if (!doc_buffer->isClean()) {
3353 docstring const file =
3354 makeDisplayPath(doc_buffer->absFileName(), 20);
3355 docstring text = bformat(_("Any changes will be lost. "
3356 "Are you sure you want to revert to the saved version "
3357 "of the document %1$s?"), file);
3358 ret = Alert::prompt(_("Revert to saved document?"),
3359 text, 1, 1, _("&Revert"), _("&Cancel"));
3363 doc_buffer->markClean();
3364 reloadBuffer(*doc_buffer);
3365 dr.forceBufferUpdate();
3370 case LFUN_BUFFER_WRITE:
3371 LASSERT(doc_buffer, break);
3372 saveBuffer(*doc_buffer);
3375 case LFUN_BUFFER_WRITE_AS:
3376 LASSERT(doc_buffer, break);
3377 renameBuffer(*doc_buffer, cmd.argument());
3380 case LFUN_BUFFER_WRITE_ALL: {
3381 Buffer * first = theBufferList().first();
3384 message(_("Saving all documents..."));
3385 // We cannot use a for loop as the buffer list cycles.
3388 if (!b->isClean()) {
3390 LYXERR(Debug::ACTION, "Saved " << b->absFileName());
3392 b = theBufferList().next(b);
3393 } while (b != first);
3394 dr.setMessage(_("All documents saved."));
3398 case LFUN_BUFFER_CLOSE:
3402 case LFUN_BUFFER_CLOSE_ALL:
3406 case LFUN_TOOLBAR_TOGGLE: {
3407 string const name = cmd.getArg(0);
3408 if (GuiToolbar * t = toolbar(name))
3413 case LFUN_DIALOG_UPDATE: {
3414 string const name = to_utf8(cmd.argument());
3415 if (name == "prefs" || name == "document")
3416 updateDialog(name, string());
3417 else if (name == "paragraph")
3418 lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
3419 else if (currentBufferView()) {
3420 Inset * inset = currentBufferView()->editedInset(name);
3421 // Can only update a dialog connected to an existing inset
3423 // FIXME: get rid of this indirection; GuiView ask the inset
3424 // if he is kind enough to update itself...
3425 FuncRequest fr(LFUN_INSET_DIALOG_UPDATE, cmd.argument());
3426 //FIXME: pass DispatchResult here?
3427 inset->dispatch(currentBufferView()->cursor(), fr);
3433 case LFUN_DIALOG_TOGGLE: {
3434 FuncCode const func_code = isDialogVisible(cmd.getArg(0))
3435 ? LFUN_DIALOG_HIDE : LFUN_DIALOG_SHOW;
3436 dispatch(FuncRequest(func_code, cmd.argument()), dr);
3440 case LFUN_DIALOG_DISCONNECT_INSET:
3441 disconnectDialog(to_utf8(cmd.argument()));
3444 case LFUN_DIALOG_HIDE: {
3445 guiApp->hideDialogs(to_utf8(cmd.argument()), 0);
3449 case LFUN_DIALOG_SHOW: {
3450 string const name = cmd.getArg(0);
3451 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
3453 if (name == "character") {
3454 data = freefont2string();
3456 showDialog("character", data);
3457 } else if (name == "latexlog") {
3458 Buffer::LogType type;
3459 string const logfile = doc_buffer->logName(&type);
3461 case Buffer::latexlog:
3464 case Buffer::buildlog:
3468 data += Lexer::quoteString(logfile);
3469 showDialog("log", data);
3470 } else if (name == "vclog") {
3471 string const data = "vc " +
3472 Lexer::quoteString(doc_buffer->lyxvc().getLogFile());
3473 showDialog("log", data);
3474 } else if (name == "symbols") {
3475 data = bv->cursor().getEncoding()->name();
3477 showDialog("symbols", data);
3479 } else if (name == "prefs" && isFullScreen()) {
3480 lfunUiToggle("fullscreen");
3481 showDialog("prefs", data);
3483 showDialog(name, data);
3488 dr.setMessage(cmd.argument());
3491 case LFUN_UI_TOGGLE: {
3492 string arg = cmd.getArg(0);
3493 if (!lfunUiToggle(arg)) {
3494 docstring const msg = "ui-toggle " + _("%1$s unknown command!");
3495 dr.setMessage(bformat(msg, from_utf8(arg)));
3497 // Make sure the keyboard focus stays in the work area.
3502 case LFUN_SPLIT_VIEW: {
3503 LASSERT(doc_buffer, break);
3504 string const orientation = cmd.getArg(0);
3505 d.splitter_->setOrientation(orientation == "vertical"
3506 ? Qt::Vertical : Qt::Horizontal);
3507 TabWorkArea * twa = addTabWorkArea();
3508 GuiWorkArea * wa = twa->addWorkArea(*doc_buffer, *this);
3509 setCurrentWorkArea(wa);
3512 case LFUN_CLOSE_TAB_GROUP:
3513 if (TabWorkArea * twa = d.currentTabWorkArea()) {
3514 closeTabWorkArea(twa);
3515 d.current_work_area_ = 0;
3516 twa = d.currentTabWorkArea();
3517 // Switch to the next GuiWorkArea in the found TabWorkArea.
3519 // Make sure the work area is up to date.
3520 setCurrentWorkArea(twa->currentWorkArea());
3522 setCurrentWorkArea(0);
3527 case LFUN_COMPLETION_INLINE:
3528 if (d.current_work_area_)
3529 d.current_work_area_->completer().showInline();
3532 case LFUN_COMPLETION_POPUP:
3533 if (d.current_work_area_)
3534 d.current_work_area_->completer().showPopup();
3538 case LFUN_COMPLETION_COMPLETE:
3539 if (d.current_work_area_)
3540 d.current_work_area_->completer().tab();
3543 case LFUN_COMPLETION_CANCEL:
3544 if (d.current_work_area_) {
3545 if (d.current_work_area_->completer().popupVisible())
3546 d.current_work_area_->completer().hidePopup();
3548 d.current_work_area_->completer().hideInline();
3552 case LFUN_COMPLETION_ACCEPT:
3553 if (d.current_work_area_)
3554 d.current_work_area_->completer().activate();
3557 case LFUN_BUFFER_ZOOM_IN:
3558 case LFUN_BUFFER_ZOOM_OUT:
3559 if (cmd.argument().empty()) {
3560 if (cmd.action() == LFUN_BUFFER_ZOOM_IN)
3565 lyxrc.zoom += convert<int>(cmd.argument());
3567 if (lyxrc.zoom < 10)
3570 // The global QPixmapCache is used in GuiPainter to cache text
3571 // painting so we must reset it.
3572 QPixmapCache::clear();
3573 guiApp->fontLoader().update();
3574 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
3577 case LFUN_VC_REGISTER:
3578 case LFUN_VC_CHECK_IN:
3579 case LFUN_VC_CHECK_OUT:
3580 case LFUN_VC_REPO_UPDATE:
3581 case LFUN_VC_LOCKING_TOGGLE:
3582 case LFUN_VC_REVERT:
3583 case LFUN_VC_UNDO_LAST:
3584 case LFUN_VC_COMMAND:
3585 case LFUN_VC_COMPARE:
3586 dispatchVC(cmd, dr);
3589 case LFUN_SERVER_GOTO_FILE_ROW:
3590 goToFileRow(to_utf8(cmd.argument()));
3593 case LFUN_FORWARD_SEARCH: {
3594 Buffer const * doc_master = doc_buffer->masterBuffer();
3595 FileName const path(doc_master->temppath());
3596 string const texname = doc_master->isChild(doc_buffer)
3597 ? DocFileName(changeExtension(
3598 doc_buffer->absFileName(),
3599 "tex")).mangledFileName()
3600 : doc_buffer->latexName();
3601 string const mastername =
3602 removeExtension(doc_master->latexName());
3603 FileName const dviname(addName(path.absFileName(),
3604 addExtension(mastername, "dvi")));
3605 FileName const pdfname(addName(path.absFileName(),
3606 addExtension(mastername, "pdf")));
3607 bool const have_dvi = dviname.exists();
3608 bool const have_pdf = pdfname.exists();
3609 if (!have_dvi && !have_pdf) {
3610 dr.setMessage(_("Please, preview the document first."));
3613 string outname = dviname.onlyFileName();
3614 string command = lyxrc.forward_search_dvi;
3615 if (!have_dvi || (have_pdf &&
3616 pdfname.lastModified() > dviname.lastModified())) {
3617 outname = pdfname.onlyFileName();
3618 command = lyxrc.forward_search_pdf;
3621 int row = doc_buffer->texrow().getRowFromIdPos(bv->cursor().paragraph().id(), bv->cursor().pos());
3622 LYXERR(Debug::ACTION, "Forward search: row:" << row
3623 << " id:" << bv->cursor().paragraph().id());
3624 if (!row || command.empty()) {
3625 dr.setMessage(_("Couldn't proceed."));
3628 string texrow = convert<string>(row);
3630 command = subst(command, "$$n", texrow);
3631 command = subst(command, "$$t", texname);
3632 command = subst(command, "$$o", outname);
3634 PathChanger p(path);
3636 one.startscript(Systemcall::DontWait, command);
3640 // The LFUN must be for one of BufferView, Buffer or Cursor;
3642 dispatchToBufferView(cmd, dr);
3646 // Part of automatic menu appearance feature.
3647 if (isFullScreen()) {
3648 if (menuBar()->isVisible() && lyxrc.full_screen_menubar)
3650 if (statusBar()->isVisible())
3651 statusBar()->hide();
3656 bool GuiView::lfunUiToggle(string const & ui_component)
3658 if (ui_component == "scrollbar") {
3659 // hide() is of no help
3660 if (d.current_work_area_->verticalScrollBarPolicy() ==
3661 Qt::ScrollBarAlwaysOff)
3663 d.current_work_area_->setVerticalScrollBarPolicy(
3664 Qt::ScrollBarAsNeeded);
3666 d.current_work_area_->setVerticalScrollBarPolicy(
3667 Qt::ScrollBarAlwaysOff);
3668 } else if (ui_component == "statusbar") {
3669 statusBar()->setVisible(!statusBar()->isVisible());
3670 } else if (ui_component == "menubar") {
3671 menuBar()->setVisible(!menuBar()->isVisible());
3673 #if QT_VERSION >= 0x040300
3674 if (ui_component == "frame") {
3676 getContentsMargins(&l, &t, &r, &b);
3677 //are the frames in default state?
3678 d.current_work_area_->setFrameStyle(QFrame::NoFrame);
3680 setContentsMargins(-2, -2, -2, -2);
3682 setContentsMargins(0, 0, 0, 0);
3686 if (ui_component == "fullscreen") {
3694 void GuiView::toggleFullScreen()
3696 if (isFullScreen()) {
3697 for (int i = 0; i != d.splitter_->count(); ++i)
3698 d.tabWorkArea(i)->setFullScreen(false);
3699 #if QT_VERSION >= 0x040300
3700 setContentsMargins(0, 0, 0, 0);
3702 setWindowState(windowState() ^ Qt::WindowFullScreen);
3705 statusBar()->show();
3708 hideDialogs("prefs", 0);
3709 for (int i = 0; i != d.splitter_->count(); ++i)
3710 d.tabWorkArea(i)->setFullScreen(true);
3711 #if QT_VERSION >= 0x040300
3712 setContentsMargins(-2, -2, -2, -2);
3715 setWindowState(windowState() ^ Qt::WindowFullScreen);
3716 statusBar()->hide();
3717 if (lyxrc.full_screen_menubar)
3719 if (lyxrc.full_screen_toolbars) {
3720 ToolbarMap::iterator end = d.toolbars_.end();
3721 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
3726 // give dialogs like the TOC a chance to adapt
3731 Buffer const * GuiView::updateInset(Inset const * inset)
3736 Buffer const * inset_buffer = &(inset->buffer());
3738 for (int i = 0; i != d.splitter_->count(); ++i) {
3739 GuiWorkArea * wa = d.tabWorkArea(i)->currentWorkArea();
3742 Buffer const * buffer = &(wa->bufferView().buffer());
3743 if (inset_buffer == buffer)
3744 wa->scheduleRedraw();
3746 return inset_buffer;
3750 void GuiView::restartCursor()
3752 /* When we move around, or type, it's nice to be able to see
3753 * the cursor immediately after the keypress.
3755 if (d.current_work_area_)
3756 d.current_work_area_->startBlinkingCursor();
3758 // Take this occasion to update the other GUI elements.
3764 void GuiView::updateCompletion(Cursor & cur, bool start, bool keep)
3766 if (d.current_work_area_)
3767 d.current_work_area_->completer().updateVisibility(cur, start, keep);
3772 // This list should be kept in sync with the list of insets in
3773 // src/insets/Inset.cpp. I.e., if a dialog goes with an inset, the
3774 // dialog should have the same name as the inset.
3775 // Changes should be also recorded in LFUN_DIALOG_SHOW doxygen
3776 // docs in LyXAction.cpp.
3778 char const * const dialognames[] = {
3780 "aboutlyx", "bibitem", "bibtex", "box", "branch", "changes", "character",
3781 "citation", "compare", "comparehistory", "document", "errorlist", "ert",
3782 "external", "file", "findreplace", "findreplaceadv", "float", "graphics",
3783 "href", "include", "index", "index_print", "info", "listings", "label", "line",
3784 "log", "mathdelimiter", "mathmatrix", "mathspace", "nomenclature",
3785 "nomencl_print", "note", "paragraph", "phantom", "prefs", "print", "ref",
3786 "sendto", "space", "spellchecker", "symbols", "tabular", "tabularcreate",
3787 "thesaurus", "texinfo", "toc", "view-source", "vspace", "wrap", "progress"};
3789 char const * const * const end_dialognames =
3790 dialognames + (sizeof(dialognames) / sizeof(char *));
3794 cmpCStr(char const * name) : name_(name) {}
3795 bool operator()(char const * other) {
3796 return strcmp(other, name_) == 0;
3803 bool isValidName(string const & name)
3805 return find_if(dialognames, end_dialognames,
3806 cmpCStr(name.c_str())) != end_dialognames;
3812 void GuiView::resetDialogs()
3814 // Make sure that no LFUN uses any GuiView.
3815 guiApp->setCurrentView(0);
3819 constructToolbars();
3820 guiApp->menus().fillMenuBar(menuBar(), this, false);
3821 d.layout_->updateContents(true);
3822 // Now update controls with current buffer.
3823 guiApp->setCurrentView(this);
3829 Dialog * GuiView::findOrBuild(string const & name, bool hide_it)
3831 if (!isValidName(name))
3834 map<string, DialogPtr>::iterator it = d.dialogs_.find(name);
3836 if (it != d.dialogs_.end()) {
3838 it->second->hideView();
3839 return it->second.get();
3842 Dialog * dialog = build(name);
3843 d.dialogs_[name].reset(dialog);
3844 if (lyxrc.allow_geometry_session)
3845 dialog->restoreSession();
3852 void GuiView::showDialog(string const & name, string const & data,
3855 triggerShowDialog(toqstr(name), toqstr(data), inset);
3859 void GuiView::doShowDialog(QString const & qname, QString const & qdata,
3865 const string name = fromqstr(qname);
3866 const string data = fromqstr(qdata);
3870 Dialog * dialog = findOrBuild(name, false);
3872 bool const visible = dialog->isVisibleView();
3873 dialog->showData(data);
3874 if (inset && currentBufferView())
3875 currentBufferView()->editInset(name, inset);
3876 // We only set the focus to the new dialog if it was not yet
3877 // visible in order not to change the existing previous behaviour
3879 // activateWindow is needed for floating dockviews
3880 dialog->asQWidget()->raise();
3881 dialog->asQWidget()->activateWindow();
3882 dialog->asQWidget()->setFocus();
3886 catch (ExceptionMessage const & ex) {
3894 bool GuiView::isDialogVisible(string const & name) const
3896 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3897 if (it == d.dialogs_.end())
3899 return it->second.get()->isVisibleView() && !it->second.get()->isClosing();
3903 void GuiView::hideDialog(string const & name, Inset * inset)
3905 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3906 if (it == d.dialogs_.end())
3910 if (!currentBufferView())
3912 if (inset != currentBufferView()->editedInset(name))
3916 Dialog * const dialog = it->second.get();
3917 if (dialog->isVisibleView())
3919 if (currentBufferView())
3920 currentBufferView()->editInset(name, 0);
3924 void GuiView::disconnectDialog(string const & name)
3926 if (!isValidName(name))
3928 if (currentBufferView())
3929 currentBufferView()->editInset(name, 0);
3933 void GuiView::hideAll() const
3935 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
3936 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3938 for(; it != end; ++it)
3939 it->second->hideView();
3943 void GuiView::updateDialogs()
3945 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
3946 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3948 for(; it != end; ++it) {
3949 Dialog * dialog = it->second.get();
3951 if (dialog->needBufferOpen() && !documentBufferView())
3952 hideDialog(fromqstr(dialog->name()), 0);
3953 else if (dialog->isVisibleView())
3954 dialog->checkStatus();
3961 Dialog * createDialog(GuiView & lv, string const & name);
3963 // will be replaced by a proper factory...
3964 Dialog * createGuiAbout(GuiView & lv);
3965 Dialog * createGuiBibtex(GuiView & lv);
3966 Dialog * createGuiChanges(GuiView & lv);
3967 Dialog * createGuiCharacter(GuiView & lv);
3968 Dialog * createGuiCitation(GuiView & lv);
3969 Dialog * createGuiCompare(GuiView & lv);
3970 Dialog * createGuiCompareHistory(GuiView & lv);
3971 Dialog * createGuiDelimiter(GuiView & lv);
3972 Dialog * createGuiDocument(GuiView & lv);
3973 Dialog * createGuiErrorList(GuiView & lv);
3974 Dialog * createGuiExternal(GuiView & lv);
3975 Dialog * createGuiGraphics(GuiView & lv);
3976 Dialog * createGuiInclude(GuiView & lv);
3977 Dialog * createGuiIndex(GuiView & lv);
3978 Dialog * createGuiListings(GuiView & lv);
3979 Dialog * createGuiLog(GuiView & lv);
3980 Dialog * createGuiMathMatrix(GuiView & lv);
3981 Dialog * createGuiNote(GuiView & lv);
3982 Dialog * createGuiParagraph(GuiView & lv);
3983 Dialog * createGuiPhantom(GuiView & lv);
3984 Dialog * createGuiPreferences(GuiView & lv);
3985 Dialog * createGuiPrint(GuiView & lv);
3986 Dialog * createGuiPrintindex(GuiView & lv);
3987 Dialog * createGuiRef(GuiView & lv);
3988 Dialog * createGuiSearch(GuiView & lv);
3989 Dialog * createGuiSearchAdv(GuiView & lv);
3990 Dialog * createGuiSendTo(GuiView & lv);
3991 Dialog * createGuiShowFile(GuiView & lv);
3992 Dialog * createGuiSpellchecker(GuiView & lv);
3993 Dialog * createGuiSymbols(GuiView & lv);
3994 Dialog * createGuiTabularCreate(GuiView & lv);
3995 Dialog * createGuiTexInfo(GuiView & lv);
3996 Dialog * createGuiToc(GuiView & lv);
3997 Dialog * createGuiThesaurus(GuiView & lv);
3998 Dialog * createGuiViewSource(GuiView & lv);
3999 Dialog * createGuiWrap(GuiView & lv);
4000 Dialog * createGuiProgressView(GuiView & lv);
4004 Dialog * GuiView::build(string const & name)
4006 LASSERT(isValidName(name), return 0);
4008 Dialog * dialog = createDialog(*this, name);
4012 if (name == "aboutlyx")
4013 return createGuiAbout(*this);
4014 if (name == "bibtex")
4015 return createGuiBibtex(*this);
4016 if (name == "changes")
4017 return createGuiChanges(*this);
4018 if (name == "character")
4019 return createGuiCharacter(*this);
4020 if (name == "citation")
4021 return createGuiCitation(*this);
4022 if (name == "compare")
4023 return createGuiCompare(*this);
4024 if (name == "comparehistory")
4025 return createGuiCompareHistory(*this);
4026 if (name == "document")
4027 return createGuiDocument(*this);
4028 if (name == "errorlist")
4029 return createGuiErrorList(*this);
4030 if (name == "external")
4031 return createGuiExternal(*this);
4033 return createGuiShowFile(*this);
4034 if (name == "findreplace")
4035 return createGuiSearch(*this);
4036 if (name == "findreplaceadv")
4037 return createGuiSearchAdv(*this);
4038 if (name == "graphics")
4039 return createGuiGraphics(*this);
4040 if (name == "include")
4041 return createGuiInclude(*this);
4042 if (name == "index")
4043 return createGuiIndex(*this);
4044 if (name == "index_print")
4045 return createGuiPrintindex(*this);
4046 if (name == "listings")
4047 return createGuiListings(*this);
4049 return createGuiLog(*this);
4050 if (name == "mathdelimiter")
4051 return createGuiDelimiter(*this);
4052 if (name == "mathmatrix")
4053 return createGuiMathMatrix(*this);
4055 return createGuiNote(*this);
4056 if (name == "paragraph")
4057 return createGuiParagraph(*this);
4058 if (name == "phantom")
4059 return createGuiPhantom(*this);
4060 if (name == "prefs")
4061 return createGuiPreferences(*this);
4062 if (name == "print")
4063 return createGuiPrint(*this);
4065 return createGuiRef(*this);
4066 if (name == "sendto")
4067 return createGuiSendTo(*this);
4068 if (name == "spellchecker")
4069 return createGuiSpellchecker(*this);
4070 if (name == "symbols")
4071 return createGuiSymbols(*this);
4072 if (name == "tabularcreate")
4073 return createGuiTabularCreate(*this);
4074 if (name == "texinfo")
4075 return createGuiTexInfo(*this);
4076 if (name == "thesaurus")
4077 return createGuiThesaurus(*this);
4079 return createGuiToc(*this);
4080 if (name == "view-source")
4081 return createGuiViewSource(*this);
4083 return createGuiWrap(*this);
4084 if (name == "progress")
4085 return createGuiProgressView(*this);
4091 } // namespace frontend
4094 #include "moc_GuiView.cpp"