3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Lars Gullik Bjønnes
8 * \author Abdelrazak Younes
11 * Full author contact details are available in file CREDITS.
19 #include "DispatchResult.h"
20 #include "FileDialog.h"
21 #include "FontLoader.h"
22 #include "GuiApplication.h"
23 #include "GuiCommandBuffer.h"
24 #include "GuiCompleter.h"
25 #include "GuiKeySymbol.h"
27 #include "GuiToolbar.h"
28 #include "GuiWorkArea.h"
29 #include "GuiProgress.h"
30 #include "LayoutBox.h"
34 #include "qt_helpers.h"
36 #include "frontends/alert.h"
38 #include "buffer_funcs.h"
40 #include "BufferList.h"
41 #include "BufferParams.h"
42 #include "BufferView.h"
44 #include "Converter.h"
46 #include "CutAndPaste.h"
48 #include "ErrorList.h"
50 #include "FuncStatus.h"
51 #include "FuncRequest.h"
55 #include "LyXAction.h"
59 #include "Paragraph.h"
60 #include "SpellChecker.h"
62 #include "TextClass.h"
67 #include "support/convert.h"
68 #include "support/debug.h"
69 #include "support/ExceptionMessage.h"
70 #include "support/FileName.h"
71 #include "support/filetools.h"
72 #include "support/gettext.h"
73 #include "support/filetools.h"
74 #include "support/ForkedCalls.h"
75 #include "support/lassert.h"
76 #include "support/lstrings.h"
77 #include "support/os.h"
78 #include "support/Package.h"
79 #include "support/Path.h"
80 #include "support/Systemcall.h"
81 #include "support/Timeout.h"
82 #include "support/ProgressInterface.h"
85 #include <QApplication>
86 #include <QCloseEvent>
88 #include <QDesktopWidget>
89 #include <QDragEnterEvent>
98 #include <QPixmapCache>
100 #include <QPushButton>
102 #include <QShowEvent>
104 #include <QStackedWidget>
105 #include <QStatusBar>
110 #include <QScrollBar>
114 #define EXPORT_in_THREAD 1
116 // QtConcurrent was introduced in Qt 4.4
117 #if (QT_VERSION >= 0x040400)
119 #include <QFutureWatcher>
120 #include <QtConcurrentRun>
123 #include "support/bind.h"
127 #ifdef HAVE_SYS_TIME_H
128 # include <sys/time.h>
136 using namespace lyx::support;
140 using support::addExtension;
141 using support::changeExtension;
142 using support::removeExtension;
148 class BackgroundWidget : public QWidget
153 LYXERR(Debug::GUI, "show banner: " << lyxrc.show_banner);
154 if (!lyxrc.show_banner)
156 /// The text to be written on top of the pixmap
157 QString const text = lyx_version ?
158 qt_("version ") + lyx_version : qt_("unknown version");
159 splash_ = getPixmap("images/", "banner", "png");
161 QPainter pain(&splash_);
162 pain.setPen(QColor(0, 0, 0));
164 // The font used to display the version info
165 font.setStyleHint(QFont::SansSerif);
166 font.setWeight(QFont::Bold);
167 font.setPointSize(int(toqstr(lyxrc.font_sizes[FONT_SIZE_LARGE]).toDouble()));
169 pain.drawText(190, 225, text);
170 setFocusPolicy(Qt::StrongFocus);
173 void paintEvent(QPaintEvent *)
175 int x = (width() - splash_.width()) / 2;
176 int y = (height() - splash_.height()) / 2;
178 pain.drawPixmap(x, y, splash_);
181 void keyPressEvent(QKeyEvent * ev)
184 setKeySymbol(&sym, ev);
186 guiApp->processKeySym(sym, q_key_state(ev->modifiers()));
198 /// Toolbar store providing access to individual toolbars by name.
199 typedef map<string, GuiToolbar *> ToolbarMap;
201 typedef shared_ptr<Dialog> DialogPtr;
206 struct GuiView::GuiViewPrivate
208 GuiViewPrivate(GuiView * gv)
209 : gv_(gv), current_work_area_(0), current_main_work_area_(0),
210 layout_(0), autosave_timeout_(5000),
213 // hardcode here the platform specific icon size
214 smallIconSize = 16; // scaling problems
215 normalIconSize = 20; // ok, default if iconsize.png is missing
216 bigIconSize = 26; // better for some math icons
218 // if it exists, use width of iconsize.png as normal size
219 QString const dir = toqstr(addPath("images", lyxrc.icon_set));
220 FileName const fn = lyx::libFileSearch(dir, "iconsize.png");
222 QImage image(toqstr(fn.absFileName()));
223 if (image.width() < int(smallIconSize))
224 normalIconSize = smallIconSize;
225 else if (image.width() > int(bigIconSize))
226 normalIconSize = bigIconSize;
228 normalIconSize = image.width();
231 splitter_ = new QSplitter;
232 bg_widget_ = new BackgroundWidget;
233 stack_widget_ = new QStackedWidget;
234 stack_widget_->addWidget(bg_widget_);
235 stack_widget_->addWidget(splitter_);
238 // TODO cleanup, remove the singleton, handle multiple Windows?
239 progress_ = ProgressInterface::instance();
240 if (!dynamic_cast<GuiProgress*>(progress_)) {
241 progress_ = new GuiProgress(); // TODO who deletes it
242 ProgressInterface::setInstance(progress_);
245 dynamic_cast<GuiProgress*>(progress_),
246 SIGNAL(updateStatusBarMessage(QString const&)),
247 gv, SLOT(updateStatusBarMessage(QString const&)));
249 dynamic_cast<GuiProgress*>(progress_),
250 SIGNAL(clearMessageText()),
251 gv, SLOT(clearMessageText()));
258 delete stack_widget_;
261 QMenu * toolBarPopup(GuiView * parent)
263 // FIXME: translation
264 QMenu * menu = new QMenu(parent);
265 QActionGroup * iconSizeGroup = new QActionGroup(parent);
267 QAction * smallIcons = new QAction(iconSizeGroup);
268 smallIcons->setText(qt_("Small-sized icons"));
269 smallIcons->setCheckable(true);
270 QObject::connect(smallIcons, SIGNAL(triggered()),
271 parent, SLOT(smallSizedIcons()));
272 menu->addAction(smallIcons);
274 QAction * normalIcons = new QAction(iconSizeGroup);
275 normalIcons->setText(qt_("Normal-sized icons"));
276 normalIcons->setCheckable(true);
277 QObject::connect(normalIcons, SIGNAL(triggered()),
278 parent, SLOT(normalSizedIcons()));
279 menu->addAction(normalIcons);
281 QAction * bigIcons = new QAction(iconSizeGroup);
282 bigIcons->setText(qt_("Big-sized icons"));
283 bigIcons->setCheckable(true);
284 QObject::connect(bigIcons, SIGNAL(triggered()),
285 parent, SLOT(bigSizedIcons()));
286 menu->addAction(bigIcons);
288 unsigned int cur = parent->iconSize().width();
289 if ( cur == parent->d.smallIconSize)
290 smallIcons->setChecked(true);
291 else if (cur == parent->d.normalIconSize)
292 normalIcons->setChecked(true);
293 else if (cur == parent->d.bigIconSize)
294 bigIcons->setChecked(true);
301 stack_widget_->setCurrentWidget(bg_widget_);
302 bg_widget_->setUpdatesEnabled(true);
303 bg_widget_->setFocus();
306 int tabWorkAreaCount()
308 return splitter_->count();
311 TabWorkArea * tabWorkArea(int i)
313 return dynamic_cast<TabWorkArea *>(splitter_->widget(i));
316 TabWorkArea * currentTabWorkArea()
318 int areas = tabWorkAreaCount();
320 // The first TabWorkArea is always the first one, if any.
321 return tabWorkArea(0);
323 for (int i = 0; i != areas; ++i) {
324 TabWorkArea * twa = tabWorkArea(i);
325 if (current_main_work_area_ == twa->currentWorkArea())
329 // None has the focus so we just take the first one.
330 return tabWorkArea(0);
333 #if (QT_VERSION >= 0x040400)
334 void setPreviewFuture(QFuture<Buffer::ExportStatus> const & f)
336 if (processing_thread_watcher_.isRunning()) {
337 // we prefer to cancel this preview in order to keep a snappy
341 processing_thread_watcher_.setFuture(f);
347 GuiWorkArea * current_work_area_;
348 GuiWorkArea * current_main_work_area_;
349 QSplitter * splitter_;
350 QStackedWidget * stack_widget_;
351 BackgroundWidget * bg_widget_;
353 ToolbarMap toolbars_;
354 ProgressInterface* progress_;
355 /// The main layout box.
357 * \warning Don't Delete! The layout box is actually owned by
358 * whichever toolbar contains it. All the GuiView class needs is a
359 * means of accessing it.
361 * FIXME: replace that with a proper model so that we are not limited
362 * to only one dialog.
367 map<string, DialogPtr> dialogs_;
369 unsigned int smallIconSize;
370 unsigned int normalIconSize;
371 unsigned int bigIconSize;
373 QTimer statusbar_timer_;
374 /// auto-saving of buffers
375 Timeout autosave_timeout_;
376 /// flag against a race condition due to multiclicks, see bug #1119
380 TocModels toc_models_;
382 #if (QT_VERSION >= 0x040400)
384 QFutureWatcher<docstring> autosave_watcher_;
385 QFutureWatcher<Buffer::ExportStatus> processing_thread_watcher_;
387 string last_export_format;
388 string processing_format;
390 struct DummyWatcher { bool isRunning(){return false;} };
391 DummyWatcher processing_thread_watcher_;
394 static QSet<Buffer const *> busyBuffers;
395 static Buffer::ExportStatus previewAndDestroy(Buffer const * orig, Buffer * buffer, string const & format);
396 static Buffer::ExportStatus exportAndDestroy(Buffer const * orig, Buffer * buffer, string const & format);
397 static Buffer::ExportStatus compileAndDestroy(Buffer const * orig, Buffer * buffer, string const & format);
398 static docstring autosaveAndDestroy(Buffer const * orig, Buffer * buffer);
401 static Buffer::ExportStatus runAndDestroy(const T& func, Buffer const * orig, Buffer * buffer, string const & format, string const & msg);
403 // TODO syncFunc/previewFunc: use bind
404 bool asyncBufferProcessing(string const & argument,
405 Buffer const * used_buffer,
406 docstring const & msg,
407 Buffer::ExportStatus (*asyncFunc)(Buffer const *, Buffer *, string const &),
408 Buffer::ExportStatus (Buffer::*syncFunc)(string const &, bool) const,
409 Buffer::ExportStatus (Buffer::*previewFunc)(string const &) const);
411 QVector<GuiWorkArea*> guiWorkAreas();
414 QSet<Buffer const *> GuiView::GuiViewPrivate::busyBuffers;
417 GuiView::GuiView(int id)
418 : d(*new GuiViewPrivate(this)), id_(id), closing_(false), busy_(0)
420 // GuiToolbars *must* be initialised before the menu bar.
421 normalSizedIcons(); // at least on Mac the default is 32 otherwise, which is huge
424 // set ourself as the current view. This is needed for the menu bar
425 // filling, at least for the static special menu item on Mac. Otherwise
426 // they are greyed out.
427 guiApp->setCurrentView(this);
429 // Fill up the menu bar.
430 guiApp->menus().fillMenuBar(menuBar(), this, true);
432 setCentralWidget(d.stack_widget_);
434 // Start autosave timer
435 if (lyxrc.autosave) {
436 d.autosave_timeout_.timeout.connect(bind(&GuiView::autoSave, this));
437 d.autosave_timeout_.setTimeout(lyxrc.autosave * 1000);
438 d.autosave_timeout_.start();
440 connect(&d.statusbar_timer_, SIGNAL(timeout()),
441 this, SLOT(clearMessage()));
443 // We don't want to keep the window in memory if it is closed.
444 setAttribute(Qt::WA_DeleteOnClose, true);
446 #if (!defined(Q_WS_WIN) && !defined(Q_WS_MACX))
447 // assign an icon to main form. We do not do it under Qt/Win or Qt/Mac,
448 // since the icon is provided in the application bundle.
449 setWindowIcon(getPixmap("images/", "lyx", "png"));
452 #if (QT_VERSION >= 0x040300)
453 // use tabbed dock area for multiple docks
454 // (such as "source" and "messages")
455 setDockOptions(QMainWindow::ForceTabbedDocks);
459 setAcceptDrops(true);
461 #if (QT_VERSION >= 0x040400)
463 // add busy indicator to statusbar
464 QLabel * busylabel = new QLabel(statusBar());
465 statusBar()->addPermanentWidget(busylabel);
466 QString fn = toqstr(lyx::libFileSearch("images", "busy.gif").absFileName());
467 QMovie * busyanim = new QMovie(fn, QByteArray(), busylabel);
468 busylabel->setMovie(busyanim);
472 connect(&d.processing_thread_watcher_, SIGNAL(started()),
473 busylabel, SLOT(show()));
474 connect(&d.processing_thread_watcher_, SIGNAL(finished()),
475 busylabel, SLOT(hide()));
477 statusBar()->setSizeGripEnabled(true);
480 connect(&d.autosave_watcher_, SIGNAL(finished()), this,
481 SLOT(autoSaveThreadFinished()));
483 connect(&d.processing_thread_watcher_, SIGNAL(started()), this,
484 SLOT(processingThreadStarted()));
485 connect(&d.processing_thread_watcher_, SIGNAL(finished()), this,
486 SLOT(processingThreadFinished()));
490 connect(this, SIGNAL(triggerShowDialog(QString const &, QString const &, Inset *)),
491 SLOT(doShowDialog(QString const &, QString const &, Inset *)));
493 // Forbid too small unresizable window because it can happen
494 // with some window manager under X11.
495 setMinimumSize(300, 200);
497 if (lyxrc.allow_geometry_session) {
498 // Now take care of session management.
503 // no session handling, default to a sane size.
504 setGeometry(50, 50, 690, 510);
507 // clear session data if any.
509 settings.remove("views");
519 QVector<GuiWorkArea*> GuiView::GuiViewPrivate::guiWorkAreas()
521 QVector<GuiWorkArea*> areas;
522 for (int i = 0; i < tabWorkAreaCount(); i++) {
523 TabWorkArea* ta = tabWorkArea(i);
524 for (int u = 0; u < ta->count(); u++) {
525 areas << ta->workArea(u);
532 #if QT_VERSION >= 0x040400
534 void GuiView::processingThreadStarted()
539 void GuiView::processingThreadFinished(bool show_errors)
541 QFutureWatcher<Buffer::ExportStatus> const * watcher =
542 static_cast<QFutureWatcher<Buffer::ExportStatus> const *>(sender());
544 Buffer::ExportStatus const status = watcher->result();
547 case Buffer::ExportSuccess:
548 msg = _("Successful export to format: %1$s");
550 case Buffer::ExportError:
551 case Buffer::ExportNoPathToFormat:
552 case Buffer::ExportTexPathHasSpaces:
553 case Buffer::ExportConverterError:
554 msg = _("Error while exporting format: %1$s");
556 case Buffer::PreviewSuccess:
557 msg = _("Successful preview of format: %1$s");
559 case Buffer::PreviewError:
560 msg = _("Error while previewing format: %1$s");
563 message(bformat(msg, from_utf8(d.processing_format)));
567 BufferView const * const bv = currentBufferView();
568 if (bv && !bv->buffer().errorList("Export").empty()) {
572 errors(d.last_export_format);
577 void GuiView::processingThreadFinished()
579 processingThreadFinished(true);
583 void GuiView::autoSaveThreadFinished()
585 processingThreadFinished(false);
591 void GuiView::processingThreadStarted()
596 void GuiView::processingThreadFinished(bool)
601 void GuiView::processingThreadFinished()
606 void GuiView::autoSaveThreadFinished()
612 void GuiView::saveLayout() const
615 settings.beginGroup("views");
616 settings.beginGroup(QString::number(id_));
618 settings.setValue("pos", pos());
619 settings.setValue("size", size());
621 settings.setValue("geometry", saveGeometry());
623 settings.setValue("layout", saveState(0));
624 settings.setValue("icon_size", iconSize());
628 void GuiView::saveUISettings() const
630 // Save the toolbar private states
631 ToolbarMap::iterator end = d.toolbars_.end();
632 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
633 it->second->saveSession();
634 // Now take care of all other dialogs
635 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
636 for (; it!= d.dialogs_.end(); ++it)
637 it->second->saveSession();
641 bool GuiView::restoreLayout()
644 settings.beginGroup("views");
645 settings.beginGroup(QString::number(id_));
646 QString const icon_key = "icon_size";
647 if (!settings.contains(icon_key))
650 //code below is skipped when when ~/.config/LyX is (re)created
651 QSize icon_size = settings.value(icon_key).toSize();
652 // Check whether session size changed.
653 if (icon_size.width() != int(d.smallIconSize) &&
654 icon_size.width() != int(d.normalIconSize) &&
655 icon_size.width() != int(d.bigIconSize)) {
656 icon_size.setWidth(d.normalIconSize);
657 icon_size.setHeight(d.normalIconSize);
659 setIconSize(icon_size);
662 QPoint pos = settings.value("pos", QPoint(50, 50)).toPoint();
663 QSize size = settings.value("size", QSize(690, 510)).toSize();
667 // Work-around for bug #6034: the window ends up in an undetermined
668 // state when trying to restore a maximized window when it is
669 // already maximized.
670 if (!(windowState() & Qt::WindowMaximized))
671 if (!restoreGeometry(settings.value("geometry").toByteArray()))
672 setGeometry(50, 50, 690, 510);
674 // Make sure layout is correctly oriented.
675 setLayoutDirection(qApp->layoutDirection());
677 // Allow the toc and view-source dock widget to be restored if needed.
679 if ((dialog = findOrBuild("toc", true)))
680 // see bug 5082. At least setup title and enabled state.
681 // Visibility will be adjusted by restoreState below.
682 dialog->prepareView();
683 if ((dialog = findOrBuild("view-source", true)))
684 dialog->prepareView();
685 if ((dialog = findOrBuild("progress", true)))
686 dialog->prepareView();
687 if ((dialog = findOrBuild("findreplaceadv", true)))
688 dialog->prepareView();
690 if (!restoreState(settings.value("layout").toByteArray(), 0))
697 GuiToolbar * GuiView::toolbar(string const & name)
699 ToolbarMap::iterator it = d.toolbars_.find(name);
700 if (it != d.toolbars_.end())
703 LYXERR(Debug::GUI, "Toolbar::display: no toolbar named " << name);
708 void GuiView::constructToolbars()
710 ToolbarMap::iterator it = d.toolbars_.begin();
711 for (; it != d.toolbars_.end(); ++it)
715 // I don't like doing this here, but the standard toolbar
716 // destroys this object when it's destroyed itself (vfr)
717 d.layout_ = new LayoutBox(*this);
718 d.stack_widget_->addWidget(d.layout_);
719 d.layout_->move(0,0);
721 // extracts the toolbars from the backend
722 Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
723 Toolbars::Infos::iterator end = guiApp->toolbars().end();
724 for (; cit != end; ++cit)
725 d.toolbars_[cit->name] = new GuiToolbar(*cit, *this);
729 void GuiView::initToolbars()
731 // extracts the toolbars from the backend
732 Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
733 Toolbars::Infos::iterator end = guiApp->toolbars().end();
734 for (; cit != end; ++cit) {
735 GuiToolbar * tb = toolbar(cit->name);
738 int const visibility = guiApp->toolbars().defaultVisibility(cit->name);
739 bool newline = !(visibility & Toolbars::SAMEROW);
740 tb->setVisible(false);
741 tb->setVisibility(visibility);
743 if (visibility & Toolbars::TOP) {
745 addToolBarBreak(Qt::TopToolBarArea);
746 addToolBar(Qt::TopToolBarArea, tb);
749 if (visibility & Toolbars::BOTTOM) {
750 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
751 #if (QT_VERSION >= 0x040202)
753 addToolBarBreak(Qt::BottomToolBarArea);
755 addToolBar(Qt::BottomToolBarArea, tb);
758 if (visibility & Toolbars::LEFT) {
759 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
760 #if (QT_VERSION >= 0x040202)
762 addToolBarBreak(Qt::LeftToolBarArea);
764 addToolBar(Qt::LeftToolBarArea, tb);
767 if (visibility & Toolbars::RIGHT) {
768 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
769 #if (QT_VERSION >= 0x040202)
771 addToolBarBreak(Qt::RightToolBarArea);
773 addToolBar(Qt::RightToolBarArea, tb);
776 if (visibility & Toolbars::ON)
777 tb->setVisible(true);
782 TocModels & GuiView::tocModels()
784 return d.toc_models_;
788 void GuiView::setFocus()
790 LYXERR(Debug::DEBUG, "GuiView::setFocus()" << this);
791 QMainWindow::setFocus();
795 void GuiView::focusInEvent(QFocusEvent * e)
797 LYXERR(Debug::DEBUG, "GuiView::focusInEvent()" << this);
798 QMainWindow::focusInEvent(e);
799 // Make sure guiApp points to the correct view.
800 guiApp->setCurrentView(this);
801 if (currentWorkArea())
802 currentWorkArea()->setFocus();
803 else if (currentMainWorkArea())
804 currentMainWorkArea()->setFocus();
806 d.bg_widget_->setFocus();
810 QMenu * GuiView::createPopupMenu()
812 return d.toolBarPopup(this);
816 void GuiView::showEvent(QShowEvent * e)
818 LYXERR(Debug::GUI, "Passed Geometry "
819 << size().height() << "x" << size().width()
820 << "+" << pos().x() << "+" << pos().y());
822 if (d.splitter_->count() == 0)
823 // No work area, switch to the background widget.
827 QMainWindow::showEvent(e);
831 bool GuiView::closeScheduled()
838 /** Destroy only all tabbed WorkAreas. Destruction of other WorkAreas
839 ** is responsibility of the container (e.g., dialog)
841 void GuiView::closeEvent(QCloseEvent * close_event)
843 LYXERR(Debug::DEBUG, "GuiView::closeEvent()");
845 if (!GuiViewPrivate::busyBuffers.isEmpty()) {
846 Alert::warning(_("Exit LyX"),
847 _("LyX could not be closed because documents are being processed by LyX."));
848 close_event->setAccepted(false);
852 // If the user pressed the x (so we didn't call closeView
853 // programmatically), we want to clear all existing entries.
855 theSession().lastOpened().clear();
860 // it can happen that this event arrives without selecting the view,
861 // e.g. when clicking the close button on a background window.
863 if (!closeWorkAreaAll()) {
865 close_event->ignore();
869 // Make sure that nothing will use this to be closed View.
870 guiApp->unregisterView(this);
872 if (isFullScreen()) {
873 // Switch off fullscreen before closing.
878 // Make sure the timer time out will not trigger a statusbar update.
879 d.statusbar_timer_.stop();
881 // Saving fullscreen requires additional tweaks in the toolbar code.
882 // It wouldn't also work under linux natively.
883 if (lyxrc.allow_geometry_session) {
888 close_event->accept();
892 void GuiView::dragEnterEvent(QDragEnterEvent * event)
894 if (event->mimeData()->hasUrls())
896 /// \todo Ask lyx-devel is this is enough:
897 /// if (event->mimeData()->hasFormat("text/plain"))
898 /// event->acceptProposedAction();
902 void GuiView::dropEvent(QDropEvent * event)
904 QList<QUrl> files = event->mimeData()->urls();
908 LYXERR(Debug::GUI, "GuiView::dropEvent: got URLs!");
909 for (int i = 0; i != files.size(); ++i) {
910 string const file = os::internal_path(fromqstr(
911 files.at(i).toLocalFile()));
915 string const ext = support::getExtension(file);
916 vector<const Format *> found_formats;
918 // Find all formats that have the correct extension.
919 vector<const Format *> const & import_formats
920 = theConverters().importableFormats();
921 vector<const Format *>::const_iterator it = import_formats.begin();
922 for (; it != import_formats.end(); ++it)
923 if ((*it)->hasExtension(ext))
924 found_formats.push_back(*it);
927 if (found_formats.size() >= 1) {
928 if (found_formats.size() > 1) {
929 //FIXME: show a dialog to choose the correct importable format
931 "Multiple importable formats found, selecting first");
933 string const arg = found_formats[0]->name() + " " + file;
934 cmd = FuncRequest(LFUN_BUFFER_IMPORT, arg);
937 //FIXME: do we have to explicitly check whether it's a lyx file?
939 "No formats found, trying to open it as a lyx file");
940 cmd = FuncRequest(LFUN_FILE_OPEN, file);
942 // add the functions to the queue
943 guiApp->addToFuncRequestQueue(cmd);
946 // now process the collected functions. We perform the events
947 // asynchronously. This prevents potential problems in case the
948 // BufferView is closed within an event.
949 guiApp->processFuncRequestQueueAsync();
953 void GuiView::message(docstring const & str)
955 if (ForkedProcess::iAmAChild())
958 // call is moved to GUI-thread by GuiProgress
959 d.progress_->appendMessage(toqstr(str));
963 void GuiView::clearMessageText()
965 message(docstring());
969 void GuiView::updateStatusBarMessage(QString const & str)
971 statusBar()->showMessage(str);
972 d.statusbar_timer_.stop();
973 d.statusbar_timer_.start(3000);
977 void GuiView::smallSizedIcons()
979 setIconSize(QSize(d.smallIconSize, d.smallIconSize));
983 void GuiView::normalSizedIcons()
985 setIconSize(QSize(d.normalIconSize, d.normalIconSize));
989 void GuiView::bigSizedIcons()
991 setIconSize(QSize(d.bigIconSize, d.bigIconSize));
995 void GuiView::clearMessage()
997 // FIXME: This code was introduced in r19643 to fix bug #4123. However,
998 // the hasFocus function mostly returns false, even if the focus is on
999 // a workarea in this view.
1003 d.statusbar_timer_.stop();
1007 void GuiView::updateWindowTitle(GuiWorkArea * wa)
1009 if (wa != d.current_work_area_
1010 || wa->bufferView().buffer().isInternal())
1012 setWindowTitle(qt_("LyX: ") + wa->windowTitle());
1013 setWindowIconText(wa->windowIconText());
1017 void GuiView::on_currentWorkAreaChanged(GuiWorkArea * wa)
1019 QObject::disconnect(d.current_work_area_, SIGNAL(busy(bool)),
1020 this, SLOT(setBusy(bool)));
1022 disconnectBufferView();
1023 connectBufferView(wa->bufferView());
1024 connectBuffer(wa->bufferView().buffer());
1025 d.current_work_area_ = wa;
1026 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
1027 this, SLOT(updateWindowTitle(GuiWorkArea *)));
1028 QObject::connect(wa, SIGNAL(busy(bool)), this, SLOT(setBusy(bool)));
1029 updateWindowTitle(wa);
1033 // The document settings needs to be reinitialised.
1034 updateDialog("document", "");
1036 // Buffer-dependent dialogs must be updated. This is done here because
1037 // some dialogs require buffer()->text.
1042 void GuiView::on_lastWorkAreaRemoved()
1045 // We already are in a close event. Nothing more to do.
1048 if (d.splitter_->count() > 1)
1049 // We have a splitter so don't close anything.
1052 // Reset and updates the dialogs.
1053 d.toc_models_.reset(0);
1054 updateDialog("document", "");
1057 resetWindowTitleAndIconText();
1060 if (lyxrc.open_buffers_in_tabs)
1061 // Nothing more to do, the window should stay open.
1064 if (guiApp->viewIds().size() > 1) {
1070 // On Mac we also close the last window because the application stay
1071 // resident in memory. On other platforms we don't close the last
1072 // window because this would quit the application.
1078 void GuiView::updateStatusBar()
1080 // let the user see the explicit message
1081 if (d.statusbar_timer_.isActive())
1088 void GuiView::showMessage()
1090 QString msg = toqstr(theGuiApp()->viewStatusMessage());
1091 if (msg.isEmpty()) {
1092 BufferView const * bv = currentBufferView();
1094 msg = toqstr(bv->cursor().currentState());
1096 msg = qt_("Welcome to LyX!");
1098 statusBar()->showMessage(msg);
1102 bool GuiView::event(QEvent * e)
1106 // Useful debug code:
1107 //case QEvent::ActivationChange:
1108 //case QEvent::WindowDeactivate:
1109 //case QEvent::Paint:
1110 //case QEvent::Enter:
1111 //case QEvent::Leave:
1112 //case QEvent::HoverEnter:
1113 //case QEvent::HoverLeave:
1114 //case QEvent::HoverMove:
1115 //case QEvent::StatusTip:
1116 //case QEvent::DragEnter:
1117 //case QEvent::DragLeave:
1118 //case QEvent::Drop:
1121 case QEvent::WindowActivate: {
1122 GuiView * old_view = guiApp->currentView();
1123 if (this == old_view) {
1125 return QMainWindow::event(e);
1127 if (old_view && old_view->currentBufferView()) {
1128 // save current selection to the selection buffer to allow
1129 // middle-button paste in this window.
1130 cap::saveSelection(old_view->currentBufferView()->cursor());
1132 guiApp->setCurrentView(this);
1133 if (d.current_work_area_) {
1134 BufferView & bv = d.current_work_area_->bufferView();
1135 connectBufferView(bv);
1136 connectBuffer(bv.buffer());
1137 // The document structure, name and dialogs might have
1138 // changed in another view.
1140 // The document settings needs to be reinitialised.
1141 updateDialog("document", "");
1144 resetWindowTitleAndIconText();
1147 return QMainWindow::event(e);
1150 case QEvent::ShortcutOverride: {
1153 #if (!defined Q_WS_X11) || (QT_VERSION >= 0x040500)
1154 if (isFullScreen() && menuBar()->isHidden()) {
1155 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
1156 // FIXME: we should also try to detect special LyX shortcut such as
1157 // Alt-P and Alt-M. Right now there is a hack in
1158 // GuiWorkArea::processKeySym() that hides again the menubar for
1160 if (ke->modifiers() & Qt::AltModifier && ke->key() != Qt::Key_Alt) {
1162 return QMainWindow::event(e);
1166 return QMainWindow::event(e);
1170 return QMainWindow::event(e);
1174 void GuiView::resetWindowTitleAndIconText()
1176 setWindowTitle(qt_("LyX"));
1177 setWindowIconText(qt_("LyX"));
1180 bool GuiView::focusNextPrevChild(bool /*next*/)
1187 bool GuiView::busy() const
1193 void GuiView::setBusy(bool busy)
1195 bool const busy_before = busy_ > 0;
1196 busy ? ++busy_ : --busy_;
1197 if ((busy_ > 0) == busy_before)
1198 // busy state didn't change
1202 QApplication::setOverrideCursor(Qt::WaitCursor);
1205 QApplication::restoreOverrideCursor();
1210 GuiWorkArea * GuiView::workArea(int index)
1212 if (TabWorkArea * twa = d.currentTabWorkArea())
1213 if (index < twa->count())
1214 return dynamic_cast<GuiWorkArea *>(twa->widget(index));
1219 GuiWorkArea * GuiView::workArea(Buffer & buffer)
1221 if (currentWorkArea()
1222 && ¤tWorkArea()->bufferView().buffer() == &buffer)
1223 return (GuiWorkArea *) currentWorkArea();
1224 if (TabWorkArea * twa = d.currentTabWorkArea())
1225 return twa->workArea(buffer);
1230 GuiWorkArea * GuiView::addWorkArea(Buffer & buffer)
1232 // Automatically create a TabWorkArea if there are none yet.
1233 TabWorkArea * tab_widget = d.splitter_->count()
1234 ? d.currentTabWorkArea() : addTabWorkArea();
1235 return tab_widget->addWorkArea(buffer, *this);
1239 TabWorkArea * GuiView::addTabWorkArea()
1241 TabWorkArea * twa = new TabWorkArea;
1242 QObject::connect(twa, SIGNAL(currentWorkAreaChanged(GuiWorkArea *)),
1243 this, SLOT(on_currentWorkAreaChanged(GuiWorkArea *)));
1244 QObject::connect(twa, SIGNAL(lastWorkAreaRemoved()),
1245 this, SLOT(on_lastWorkAreaRemoved()));
1247 d.splitter_->addWidget(twa);
1248 d.stack_widget_->setCurrentWidget(d.splitter_);
1253 GuiWorkArea const * GuiView::currentWorkArea() const
1255 return d.current_work_area_;
1259 GuiWorkArea * GuiView::currentWorkArea()
1261 return d.current_work_area_;
1265 GuiWorkArea const * GuiView::currentMainWorkArea() const
1267 if (!d.currentTabWorkArea())
1269 return d.currentTabWorkArea()->currentWorkArea();
1273 GuiWorkArea * GuiView::currentMainWorkArea()
1275 if (!d.currentTabWorkArea())
1277 return d.currentTabWorkArea()->currentWorkArea();
1281 void GuiView::setCurrentWorkArea(GuiWorkArea * wa)
1283 LYXERR(Debug::DEBUG, "Setting current wa: " << wa << endl);
1285 d.current_work_area_ = 0;
1290 // FIXME: I've no clue why this is here and why it accesses
1291 // theGuiApp()->currentView, which might be 0 (bug 6464).
1292 // See also 27525 (vfr).
1293 if (theGuiApp()->currentView() == this
1294 && theGuiApp()->currentView()->currentWorkArea() == wa)
1297 if (currentBufferView())
1298 cap::saveSelection(currentBufferView()->cursor());
1300 theGuiApp()->setCurrentView(this);
1301 d.current_work_area_ = wa;
1303 // We need to reset this now, because it will need to be
1304 // right if the tabWorkArea gets reset in the for loop. We
1305 // will change it back if we aren't in that case.
1306 GuiWorkArea * const old_cmwa = d.current_main_work_area_;
1307 d.current_main_work_area_ = wa;
1309 for (int i = 0; i != d.splitter_->count(); ++i) {
1310 if (d.tabWorkArea(i)->setCurrentWorkArea(wa)) {
1311 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea()
1312 << ", Current main wa: " << currentMainWorkArea());
1317 d.current_main_work_area_ = old_cmwa;
1319 LYXERR(Debug::DEBUG, "This is not a tabbed wa");
1320 on_currentWorkAreaChanged(wa);
1321 BufferView & bv = wa->bufferView();
1322 bv.cursor().fixIfBroken();
1324 wa->setUpdatesEnabled(true);
1325 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() << ", Current main wa: " << currentMainWorkArea());
1329 void GuiView::removeWorkArea(GuiWorkArea * wa)
1331 LASSERT(wa, return);
1332 if (wa == d.current_work_area_) {
1334 disconnectBufferView();
1335 d.current_work_area_ = 0;
1336 d.current_main_work_area_ = 0;
1339 bool found_twa = false;
1340 for (int i = 0; i != d.splitter_->count(); ++i) {
1341 TabWorkArea * twa = d.tabWorkArea(i);
1342 if (twa->removeWorkArea(wa)) {
1343 // Found in this tab group, and deleted the GuiWorkArea.
1345 if (twa->count() != 0) {
1346 if (d.current_work_area_ == 0)
1347 // This means that we are closing the current GuiWorkArea, so
1348 // switch to the next GuiWorkArea in the found TabWorkArea.
1349 setCurrentWorkArea(twa->currentWorkArea());
1351 // No more WorkAreas in this tab group, so delete it.
1358 // It is not a tabbed work area (i.e., the search work area), so it
1359 // should be deleted by other means.
1360 LASSERT(found_twa, /* */);
1362 if (d.current_work_area_ == 0) {
1363 if (d.splitter_->count() != 0) {
1364 TabWorkArea * twa = d.currentTabWorkArea();
1365 setCurrentWorkArea(twa->currentWorkArea());
1367 // No more work areas, switch to the background widget.
1368 setCurrentWorkArea(0);
1374 LayoutBox * GuiView::getLayoutDialog() const
1380 void GuiView::updateLayoutList()
1383 d.layout_->updateContents(false);
1387 void GuiView::updateToolbars()
1389 ToolbarMap::iterator end = d.toolbars_.end();
1390 if (d.current_work_area_) {
1392 d.current_work_area_->bufferView().cursor().inMathed()
1393 && !d.current_work_area_->bufferView().cursor().inRegexped();
1395 lyx::getStatus(FuncRequest(LFUN_LAYOUT_TABULAR)).enabled();
1397 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).enabled() &&
1398 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).onOff(true);
1399 bool const mathmacrotemplate =
1400 lyx::getStatus(FuncRequest(LFUN_IN_MATHMACROTEMPLATE)).enabled();
1402 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1403 it->second->update(math, table, review, mathmacrotemplate);
1405 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1406 it->second->update(false, false, false, false);
1410 void GuiView::setBuffer(Buffer * newBuffer)
1412 LYXERR(Debug::DEBUG, "Setting buffer: " << newBuffer << endl);
1413 LASSERT(newBuffer, return);
1415 GuiWorkArea * wa = workArea(*newBuffer);
1418 newBuffer->masterBuffer()->updateBuffer();
1420 wa = addWorkArea(*newBuffer);
1421 // scroll to the position when the BufferView was last closed
1422 if (lyxrc.use_lastfilepos) {
1423 LastFilePosSection::FilePos filepos =
1424 theSession().lastFilePos().load(newBuffer->fileName());
1425 wa->bufferView().moveToPosition(filepos.pit, filepos.pos, 0, 0);
1428 //Disconnect the old buffer...there's no new one.
1431 connectBuffer(*newBuffer);
1432 connectBufferView(wa->bufferView());
1433 setCurrentWorkArea(wa);
1437 void GuiView::connectBuffer(Buffer & buf)
1439 buf.setGuiDelegate(this);
1443 void GuiView::disconnectBuffer()
1445 if (d.current_work_area_)
1446 d.current_work_area_->bufferView().buffer().setGuiDelegate(0);
1450 void GuiView::connectBufferView(BufferView & bv)
1452 bv.setGuiDelegate(this);
1456 void GuiView::disconnectBufferView()
1458 if (d.current_work_area_)
1459 d.current_work_area_->bufferView().setGuiDelegate(0);
1463 void GuiView::errors(string const & error_type, bool from_master)
1465 BufferView const * const bv = currentBufferView();
1469 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
1470 // We are called with from_master == false by default, so we
1471 // have to figure out whether that is the case or not.
1472 ErrorList & el = bv->buffer().errorList(error_type);
1474 el = bv->buffer().masterBuffer()->errorList(error_type);
1478 ErrorList const & el = from_master ?
1479 bv->buffer().masterBuffer()->errorList(error_type) :
1480 bv->buffer().errorList(error_type);
1486 string data = error_type;
1488 data = "from_master|" + error_type;
1489 showDialog("errorlist", data);
1493 void GuiView::updateTocItem(string const & type, DocIterator const & dit)
1495 d.toc_models_.updateItem(toqstr(type), dit);
1499 void GuiView::structureChanged()
1501 d.toc_models_.reset(documentBufferView());
1502 // Navigator needs more than a simple update in this case. It needs to be
1504 updateDialog("toc", "");
1508 void GuiView::updateDialog(string const & name, string const & data)
1510 if (!isDialogVisible(name))
1513 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
1514 if (it == d.dialogs_.end())
1517 Dialog * const dialog = it->second.get();
1518 if (dialog->isVisibleView())
1519 dialog->initialiseParams(data);
1523 BufferView * GuiView::documentBufferView()
1525 return currentMainWorkArea()
1526 ? ¤tMainWorkArea()->bufferView()
1531 BufferView const * GuiView::documentBufferView() const
1533 return currentMainWorkArea()
1534 ? ¤tMainWorkArea()->bufferView()
1539 BufferView * GuiView::currentBufferView()
1541 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1545 BufferView const * GuiView::currentBufferView() const
1547 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1551 #if (QT_VERSION >= 0x040400)
1552 docstring GuiView::GuiViewPrivate::autosaveAndDestroy(
1553 Buffer const * orig, Buffer * buffer)
1555 bool const success = buffer->autoSave();
1557 busyBuffers.remove(orig);
1559 ? _("Automatic save done.")
1560 : _("Automatic save failed!");
1565 void GuiView::autoSave()
1567 LYXERR(Debug::INFO, "Running autoSave()");
1569 Buffer * buffer = documentBufferView()
1570 ? &documentBufferView()->buffer() : 0;
1572 resetAutosaveTimers();
1576 #if (QT_VERSION >= 0x040400)
1577 GuiViewPrivate::busyBuffers.insert(buffer);
1578 QFuture<docstring> f = QtConcurrent::run(GuiViewPrivate::autosaveAndDestroy,
1579 buffer, buffer->clone());
1580 d.autosave_watcher_.setFuture(f);
1584 resetAutosaveTimers();
1588 void GuiView::resetAutosaveTimers()
1591 d.autosave_timeout_.restart();
1595 bool GuiView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1598 Buffer * buf = currentBufferView()
1599 ? ¤tBufferView()->buffer() : 0;
1600 Buffer * doc_buffer = documentBufferView()
1601 ? &(documentBufferView()->buffer()) : 0;
1603 // Check whether we need a buffer
1604 if (!lyxaction.funcHasFlag(cmd.action(), LyXAction::NoBuffer) && !buf) {
1605 // no, exit directly
1606 flag.message(from_utf8(N_("Command not allowed with"
1607 "out any document open")));
1608 flag.setEnabled(false);
1612 if (cmd.origin() == FuncRequest::TOC) {
1613 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
1614 if (!toc || !toc->getStatus(documentBufferView()->cursor(), cmd, flag))
1615 flag.setEnabled(false);
1619 switch(cmd.action()) {
1620 case LFUN_BUFFER_IMPORT:
1623 case LFUN_MASTER_BUFFER_UPDATE:
1624 case LFUN_MASTER_BUFFER_VIEW:
1625 enable = doc_buffer && doc_buffer->parent() != 0
1626 && !d.processing_thread_watcher_.isRunning();
1629 case LFUN_BUFFER_UPDATE:
1630 case LFUN_BUFFER_VIEW: {
1631 if (!doc_buffer || d.processing_thread_watcher_.isRunning()) {
1635 string format = to_utf8(cmd.argument());
1636 if (cmd.argument().empty())
1637 format = doc_buffer->params().getDefaultOutputFormat();
1638 enable = doc_buffer->params().isExportableFormat(format);
1642 case LFUN_BUFFER_RELOAD:
1643 enable = doc_buffer && !doc_buffer->isUnnamed()
1644 && doc_buffer->fileName().exists()
1645 && (!doc_buffer->isClean()
1646 || doc_buffer->isExternallyModified(Buffer::timestamp_method));
1649 case LFUN_BUFFER_CHILD_OPEN:
1650 enable = doc_buffer;
1653 case LFUN_BUFFER_WRITE:
1654 enable = doc_buffer && (doc_buffer->isUnnamed() || !doc_buffer->isClean());
1657 //FIXME: This LFUN should be moved to GuiApplication.
1658 case LFUN_BUFFER_WRITE_ALL: {
1659 // We enable the command only if there are some modified buffers
1660 Buffer * first = theBufferList().first();
1665 // We cannot use a for loop as the buffer list is a cycle.
1667 if (!b->isClean()) {
1671 b = theBufferList().next(b);
1672 } while (b != first);
1676 case LFUN_BUFFER_WRITE_AS:
1677 case LFUN_BUFFER_EXPORT_AS:
1678 enable = doc_buffer;
1681 case LFUN_BUFFER_CLOSE:
1682 enable = doc_buffer;
1685 case LFUN_BUFFER_CLOSE_ALL:
1686 enable = theBufferList().last() != theBufferList().first();
1689 case LFUN_SPLIT_VIEW:
1690 if (cmd.getArg(0) == "vertical")
1691 enable = doc_buffer && (d.splitter_->count() == 1 ||
1692 d.splitter_->orientation() == Qt::Vertical);
1694 enable = doc_buffer && (d.splitter_->count() == 1 ||
1695 d.splitter_->orientation() == Qt::Horizontal);
1698 case LFUN_CLOSE_TAB_GROUP:
1699 enable = d.currentTabWorkArea();
1702 case LFUN_TOOLBAR_TOGGLE: {
1703 string const name = cmd.getArg(0);
1704 if (GuiToolbar * t = toolbar(name))
1705 flag.setOnOff(t->isVisible());
1708 docstring const msg =
1709 bformat(_("Unknown toolbar \"%1$s\""), from_utf8(name));
1715 case LFUN_DROP_LAYOUTS_CHOICE:
1719 case LFUN_UI_TOGGLE:
1720 flag.setOnOff(isFullScreen());
1723 case LFUN_DIALOG_DISCONNECT_INSET:
1726 case LFUN_DIALOG_HIDE:
1727 // FIXME: should we check if the dialog is shown?
1730 case LFUN_DIALOG_TOGGLE:
1731 flag.setOnOff(isDialogVisible(cmd.getArg(0)));
1732 // fall through to set "enable"
1733 case LFUN_DIALOG_SHOW: {
1734 string const name = cmd.getArg(0);
1736 enable = name == "aboutlyx"
1737 || name == "file" //FIXME: should be removed.
1739 || name == "texinfo"
1740 || name == "progress"
1741 || name == "compare";
1742 else if (name == "print")
1743 enable = doc_buffer->params().isExportable("dvi")
1744 && lyxrc.print_command != "none";
1745 else if (name == "character" || name == "symbols") {
1746 if (!buf || buf->isReadonly())
1749 Cursor const & cur = currentBufferView()->cursor();
1750 enable = !(cur.inTexted() && cur.paragraph().isPassThru());
1753 else if (name == "latexlog")
1754 enable = FileName(doc_buffer->logName()).isReadableFile();
1755 else if (name == "spellchecker")
1756 enable = theSpellChecker() && !doc_buffer->isReadonly();
1757 else if (name == "vclog")
1758 enable = doc_buffer->lyxvc().inUse();
1762 case LFUN_DIALOG_UPDATE: {
1763 string const name = cmd.getArg(0);
1765 enable = name == "prefs";
1769 case LFUN_COMMAND_EXECUTE:
1771 case LFUN_MENU_OPEN:
1772 // Nothing to check.
1775 case LFUN_COMPLETION_INLINE:
1776 if (!d.current_work_area_
1777 || !d.current_work_area_->completer().inlinePossible(
1778 currentBufferView()->cursor()))
1782 case LFUN_COMPLETION_POPUP:
1783 if (!d.current_work_area_
1784 || !d.current_work_area_->completer().popupPossible(
1785 currentBufferView()->cursor()))
1789 case LFUN_COMPLETION_COMPLETE:
1790 if (!d.current_work_area_
1791 || !d.current_work_area_->completer().inlinePossible(
1792 currentBufferView()->cursor()))
1796 case LFUN_COMPLETION_ACCEPT:
1797 if (!d.current_work_area_
1798 || (!d.current_work_area_->completer().popupVisible()
1799 && !d.current_work_area_->completer().inlineVisible()
1800 && !d.current_work_area_->completer().completionAvailable()))
1804 case LFUN_COMPLETION_CANCEL:
1805 if (!d.current_work_area_
1806 || (!d.current_work_area_->completer().popupVisible()
1807 && !d.current_work_area_->completer().inlineVisible()))
1811 case LFUN_BUFFER_ZOOM_OUT:
1812 enable = doc_buffer && lyxrc.zoom > 10;
1815 case LFUN_BUFFER_ZOOM_IN:
1816 enable = doc_buffer;
1819 case LFUN_BUFFER_NEXT:
1820 case LFUN_BUFFER_PREVIOUS:
1821 // FIXME: should we check is there is an previous or next buffer?
1823 case LFUN_BUFFER_SWITCH:
1824 // toggle on the current buffer, but do not toggle off
1825 // the other ones (is that a good idea?)
1827 && to_utf8(cmd.argument()) == doc_buffer->absFileName())
1828 flag.setOnOff(true);
1831 case LFUN_VC_REGISTER:
1832 enable = doc_buffer && !doc_buffer->lyxvc().inUse();
1834 case LFUN_VC_CHECK_IN:
1835 enable = doc_buffer && doc_buffer->lyxvc().checkInEnabled();
1837 case LFUN_VC_CHECK_OUT:
1838 enable = doc_buffer && doc_buffer->lyxvc().checkOutEnabled();
1840 case LFUN_VC_LOCKING_TOGGLE:
1841 enable = doc_buffer && !doc_buffer->isReadonly()
1842 && doc_buffer->lyxvc().lockingToggleEnabled();
1843 flag.setOnOff(enable && doc_buffer->lyxvc().locking());
1845 case LFUN_VC_REVERT:
1846 enable = doc_buffer && doc_buffer->lyxvc().inUse() && !doc_buffer->isReadonly();
1848 case LFUN_VC_UNDO_LAST:
1849 enable = doc_buffer && doc_buffer->lyxvc().undoLastEnabled();
1851 case LFUN_VC_REPO_UPDATE:
1852 enable = doc_buffer && doc_buffer->lyxvc().repoUpdateEnabled();
1854 case LFUN_VC_COMMAND: {
1855 if (cmd.argument().empty())
1857 if (!doc_buffer && contains(cmd.getArg(0), 'D'))
1861 case LFUN_VC_COMPARE:
1862 enable = doc_buffer && doc_buffer->lyxvc().prepareFileRevisionEnabled();
1865 case LFUN_SERVER_GOTO_FILE_ROW:
1867 case LFUN_FORWARD_SEARCH:
1868 enable = !(lyxrc.forward_search_dvi.empty() && lyxrc.forward_search_pdf.empty());
1876 flag.setEnabled(false);
1882 static FileName selectTemplateFile()
1884 FileDialog dlg(qt_("Select template file"));
1885 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1886 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
1888 FileDialog::Result result = dlg.open(toqstr(lyxrc.template_path),
1889 QStringList(qt_("LyX Documents (*.lyx)")));
1891 if (result.first == FileDialog::Later)
1893 if (result.second.isEmpty())
1895 return FileName(fromqstr(result.second));
1899 Buffer * GuiView::loadDocument(FileName const & filename, bool tolastfiles)
1903 Buffer * newBuffer = 0;
1905 newBuffer = checkAndLoadLyXFile(filename);
1906 } catch (ExceptionMessage const & e) {
1913 message(_("Document not loaded."));
1917 setBuffer(newBuffer);
1918 newBuffer->errors("Parse");
1921 theSession().lastFiles().add(filename);
1927 void GuiView::openDocument(string const & fname)
1929 string initpath = lyxrc.document_path;
1931 if (documentBufferView()) {
1932 string const trypath = documentBufferView()->buffer().filePath();
1933 // If directory is writeable, use this as default.
1934 if (FileName(trypath).isDirWritable())
1940 if (fname.empty()) {
1941 FileDialog dlg(qt_("Select document to open"), LFUN_FILE_OPEN);
1942 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1943 dlg.setButton2(qt_("Examples|#E#e"),
1944 toqstr(addPath(package().system_support().absFileName(), "examples")));
1946 QStringList filter(qt_("LyX Documents (*.lyx)"));
1947 filter << qt_("LyX-1.3.x Documents (*.lyx13)")
1948 << qt_("LyX-1.4.x Documents (*.lyx14)")
1949 << qt_("LyX-1.5.x Documents (*.lyx15)")
1950 << qt_("LyX-1.6.x Documents (*.lyx16)");
1951 FileDialog::Result result =
1952 dlg.open(toqstr(initpath), filter);
1954 if (result.first == FileDialog::Later)
1957 filename = fromqstr(result.second);
1959 // check selected filename
1960 if (filename.empty()) {
1961 message(_("Canceled."));
1967 // get absolute path of file and add ".lyx" to the filename if
1969 FileName const fullname =
1970 fileSearch(string(), filename, "lyx", support::may_not_exist);
1971 if (!fullname.empty())
1972 filename = fullname.absFileName();
1974 if (!fullname.onlyPath().isDirectory()) {
1975 Alert::warning(_("Invalid filename"),
1976 bformat(_("The directory in the given path\n%1$s\ndoes not exist."),
1977 from_utf8(fullname.absFileName())));
1981 // if the file doesn't exist and isn't already open (bug 6645),
1982 // let the user create one
1983 if (!fullname.exists() && !theBufferList().exists(fullname)) {
1984 // the user specifically chose this name. Believe him.
1985 Buffer * const b = newFile(filename, string(), true);
1991 docstring const disp_fn = makeDisplayPath(filename);
1992 message(bformat(_("Opening document %1$s..."), disp_fn));
1995 Buffer * buf = loadDocument(fullname);
1997 str2 = bformat(_("Document %1$s opened."), disp_fn);
1998 if (buf->lyxvc().inUse())
1999 str2 += " " + from_utf8(buf->lyxvc().versionString()) +
2000 " " + _("Version control detected.");
2002 str2 = bformat(_("Could not open document %1$s"), disp_fn);
2007 // FIXME: clean that
2008 static bool import(GuiView * lv, FileName const & filename,
2009 string const & format, ErrorList & errorList)
2011 FileName const lyxfile(support::changeExtension(filename.absFileName(), ".lyx"));
2013 string loader_format;
2014 vector<string> loaders = theConverters().loaders();
2015 if (find(loaders.begin(), loaders.end(), format) == loaders.end()) {
2016 for (vector<string>::const_iterator it = loaders.begin();
2017 it != loaders.end(); ++it) {
2018 if (!theConverters().isReachable(format, *it))
2021 string const tofile =
2022 support::changeExtension(filename.absFileName(),
2023 formats.extension(*it));
2024 if (!theConverters().convert(0, filename, FileName(tofile),
2025 filename, format, *it, errorList))
2027 loader_format = *it;
2030 if (loader_format.empty()) {
2031 frontend::Alert::error(_("Couldn't import file"),
2032 bformat(_("No information for importing the format %1$s."),
2033 formats.prettyName(format)));
2037 loader_format = format;
2039 if (loader_format == "lyx") {
2040 Buffer * buf = lv->loadDocument(lyxfile);
2044 Buffer * const b = newFile(lyxfile.absFileName(), string(), true);
2048 bool as_paragraphs = loader_format == "textparagraph";
2049 string filename2 = (loader_format == format) ? filename.absFileName()
2050 : support::changeExtension(filename.absFileName(),
2051 formats.extension(loader_format));
2052 lv->currentBufferView()->insertPlaintextFile(FileName(filename2),
2054 guiApp->setCurrentView(lv);
2055 lyx::dispatch(FuncRequest(LFUN_MARK_OFF));
2062 void GuiView::importDocument(string const & argument)
2065 string filename = split(argument, format, ' ');
2067 LYXERR(Debug::INFO, format << " file: " << filename);
2069 // need user interaction
2070 if (filename.empty()) {
2071 string initpath = lyxrc.document_path;
2072 if (documentBufferView()) {
2073 string const trypath = documentBufferView()->buffer().filePath();
2074 // If directory is writeable, use this as default.
2075 if (FileName(trypath).isDirWritable())
2079 docstring const text = bformat(_("Select %1$s file to import"),
2080 formats.prettyName(format));
2082 FileDialog dlg(toqstr(text), LFUN_BUFFER_IMPORT);
2083 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2084 dlg.setButton2(qt_("Examples|#E#e"),
2085 toqstr(addPath(package().system_support().absFileName(), "examples")));
2087 docstring filter = formats.prettyName(format);
2090 filter += from_utf8(formats.extensions(format));
2093 FileDialog::Result result =
2094 dlg.open(toqstr(initpath), fileFilters(toqstr(filter)));
2096 if (result.first == FileDialog::Later)
2099 filename = fromqstr(result.second);
2101 // check selected filename
2102 if (filename.empty())
2103 message(_("Canceled."));
2106 if (filename.empty())
2109 // get absolute path of file
2110 FileName const fullname(support::makeAbsPath(filename));
2112 FileName const lyxfile(support::changeExtension(fullname.absFileName(), ".lyx"));
2114 // Check if the document already is open
2115 Buffer * buf = theBufferList().getBuffer(lyxfile);
2118 if (!closeBuffer()) {
2119 message(_("Canceled."));
2124 docstring const displaypath = makeDisplayPath(lyxfile.absFileName(), 30);
2126 // if the file exists already, and we didn't do
2127 // -i lyx thefile.lyx, warn
2128 if (lyxfile.exists() && fullname != lyxfile) {
2130 docstring text = bformat(_("The document %1$s already exists.\n\n"
2131 "Do you want to overwrite that document?"), displaypath);
2132 int const ret = Alert::prompt(_("Overwrite document?"),
2133 text, 0, 1, _("&Overwrite"), _("&Cancel"));
2136 message(_("Canceled."));
2141 message(bformat(_("Importing %1$s..."), displaypath));
2142 ErrorList errorList;
2143 if (import(this, fullname, format, errorList))
2144 message(_("imported."));
2146 message(_("file not imported!"));
2148 // FIXME (Abdel 12/08/06): Is there a need to display the error list here?
2152 void GuiView::newDocument(string const & filename, bool from_template)
2154 FileName initpath(lyxrc.document_path);
2155 if (documentBufferView()) {
2156 FileName const trypath(documentBufferView()->buffer().filePath());
2157 // If directory is writeable, use this as default.
2158 if (trypath.isDirWritable())
2162 string templatefile;
2163 if (from_template) {
2164 templatefile = selectTemplateFile().absFileName();
2165 if (templatefile.empty())
2170 if (filename.empty())
2171 b = newUnnamedFile(initpath, to_utf8(_("newfile")), templatefile);
2173 b = newFile(filename, templatefile, true);
2178 // If no new document could be created, it is unsure
2179 // whether there is a valid BufferView.
2180 if (currentBufferView())
2181 // Ensure the cursor is correctly positioned on screen.
2182 currentBufferView()->showCursor();
2186 void GuiView::insertLyXFile(docstring const & fname)
2188 BufferView * bv = documentBufferView();
2193 FileName filename(to_utf8(fname));
2194 if (filename.empty()) {
2195 // Launch a file browser
2197 string initpath = lyxrc.document_path;
2198 string const trypath = bv->buffer().filePath();
2199 // If directory is writeable, use this as default.
2200 if (FileName(trypath).isDirWritable())
2204 FileDialog dlg(qt_("Select LyX document to insert"), LFUN_FILE_INSERT);
2205 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2206 dlg.setButton2(qt_("Examples|#E#e"),
2207 toqstr(addPath(package().system_support().absFileName(),
2210 FileDialog::Result result = dlg.open(toqstr(initpath),
2211 QStringList(qt_("LyX Documents (*.lyx)")));
2213 if (result.first == FileDialog::Later)
2217 filename.set(fromqstr(result.second));
2219 // check selected filename
2220 if (filename.empty()) {
2221 // emit message signal.
2222 message(_("Canceled."));
2227 bv->insertLyXFile(filename);
2228 bv->buffer().errors("Parse");
2232 void GuiView::insertPlaintextFile(docstring const & fname,
2235 BufferView * bv = documentBufferView();
2239 if (!fname.empty() && !FileName::isAbsolute(to_utf8(fname))) {
2240 message(_("Absolute filename expected."));
2245 FileName filename(to_utf8(fname));
2247 if (!filename.empty()) {
2248 bv->insertPlaintextFile(filename, asParagraph);
2252 FileDialog dlg(qt_("Select file to insert"), (asParagraph ?
2253 LFUN_FILE_INSERT_PLAINTEXT_PARA : LFUN_FILE_INSERT_PLAINTEXT));
2255 FileDialog::Result result = dlg.open(toqstr(bv->buffer().filePath()),
2256 QStringList(qt_("All Files (*)")));
2258 if (result.first == FileDialog::Later)
2262 filename.set(fromqstr(result.second));
2264 // check selected filename
2265 if (filename.empty()) {
2266 // emit message signal.
2267 message(_("Canceled."));
2271 bv->insertPlaintextFile(filename, asParagraph);
2275 bool GuiView::renameBuffer(Buffer & b, docstring const & newname)
2277 FileName fname = b.fileName();
2278 FileName const oldname = fname;
2280 if (!newname.empty()) {
2282 fname = support::makeAbsPath(to_utf8(newname), oldname.onlyPath().absFileName());
2284 // Switch to this Buffer.
2287 // No argument? Ask user through dialog.
2289 FileDialog dlg(qt_("Choose a filename to save document as"),
2290 LFUN_BUFFER_WRITE_AS);
2291 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2292 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
2294 if (!isLyXFileName(fname.absFileName()))
2295 fname.changeExtension(".lyx");
2297 FileDialog::Result result =
2298 dlg.save(toqstr(fname.onlyPath().absFileName()),
2299 QStringList(qt_("LyX Documents (*.lyx)")),
2300 toqstr(fname.onlyFileName()));
2302 if (result.first == FileDialog::Later)
2305 fname.set(fromqstr(result.second));
2310 if (!isLyXFileName(fname.absFileName()))
2311 fname.changeExtension(".lyx");
2314 // fname is now the new Buffer location.
2315 if (FileName(fname).exists()) {
2316 docstring const file = makeDisplayPath(fname.absFileName(), 30);
2317 docstring text = bformat(_("The document %1$s already "
2318 "exists.\n\nDo you want to "
2319 "overwrite that document?"),
2321 int const ret = Alert::prompt(_("Overwrite document?"),
2322 text, 0, 2, _("&Overwrite"), _("&Rename"), _("&Cancel"));
2325 case 1: return renameBuffer(b, docstring());
2326 case 2: return false;
2330 return saveBuffer(b, fname);
2334 struct PrettyNameComparator
2336 bool operator()(Format const *first, Format const *second) const {
2337 return compare_ascii_no_case(first->prettyname(), second->prettyname()) <= 0;
2342 bool GuiView::exportBufferAs(Buffer & b)
2344 FileName fname = b.fileName();
2346 FileDialog dlg(qt_("Choose a filename to export the document as"));
2347 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2350 types << "Any supported format (*.*)";
2351 Formats::const_iterator it = formats.begin();
2352 vector<Format const *> export_formats;
2353 for (; it != formats.end(); ++it)
2354 if (it->documentFormat() && it->inExportMenu())
2355 export_formats.push_back(&(*it));
2356 PrettyNameComparator cmp;
2357 sort(export_formats.begin(), export_formats.end(), cmp);
2358 vector<Format const *>::const_iterator fit = export_formats.begin();
2359 for (; fit != export_formats.end(); ++fit)
2360 types << toqstr((*fit)->prettyname() + " (*." + (*fit)->extension() + ")");
2362 FileDialog::Result result =
2363 dlg.save(toqstr(fname.onlyPath().absFileName()),
2365 toqstr(fname.onlyFileName()),
2367 if (result.first != FileDialog::Chosen)
2370 string s = fromqstr(filter);
2371 size_t pos = s.find(" (*.");
2372 LASSERT(pos != string::npos, /**/);
2373 string fmt_prettyname = s.substr(0, pos);
2375 fname.set(fromqstr(result.second));
2376 if (fmt_prettyname == "Any supported format")
2377 fmt_name = formats.getFormatFromExtension(fname.extension());
2379 fmt_name = formats.getFormatFromPrettyName(fmt_prettyname);
2380 LYXERR(Debug::FILES, "fmt_prettyname=" << fmt_prettyname
2381 << ", fmt_name=" << fmt_name << ", fname=" << fname.absFileName());
2383 if (fmt_name.empty() || fname.empty())
2386 // fname is now the new Buffer location.
2387 if (FileName(fname).exists()) {
2388 docstring const file = makeDisplayPath(fname.absFileName(), 30);
2389 docstring text = bformat(_("The document %1$s already "
2390 "exists.\n\nDo you want to "
2391 "overwrite that document?"),
2393 int const ret = Alert::prompt(_("Overwrite document?"),
2394 text, 0, 2, _("&Overwrite"), _("&Rename"), _("&Cancel"));
2397 case 1: return exportBufferAs(b);
2398 case 2: return false;
2402 FuncRequest cmd(LFUN_BUFFER_EXPORT, fmt_name + " " + fname.absFileName());
2405 return dr.dispatched();
2409 bool GuiView::saveBuffer(Buffer & b) {
2410 return saveBuffer(b, FileName());
2414 bool GuiView::saveBuffer(Buffer & b, FileName const & fn)
2416 if (workArea(b) && workArea(b)->inDialogMode())
2419 if (fn.empty() && b.isUnnamed())
2420 return renameBuffer(b, docstring());
2426 success = b.saveAs(fn);
2429 theSession().lastFiles().add(b.fileName());
2433 // Switch to this Buffer.
2436 // FIXME: we don't tell the user *WHY* the save failed !!
2437 docstring const file = makeDisplayPath(b.absFileName(), 30);
2438 docstring text = bformat(_("The document %1$s could not be saved.\n\n"
2439 "Do you want to rename the document and "
2440 "try again?"), file);
2441 int const ret = Alert::prompt(_("Rename and save?"),
2442 text, 0, 2, _("&Rename"), _("&Retry"), _("&Cancel"));
2445 if (!renameBuffer(b, docstring()))
2454 return saveBuffer(b);
2458 bool GuiView::hideWorkArea(GuiWorkArea * wa)
2460 return closeWorkArea(wa, false);
2464 bool GuiView::closeWorkArea(GuiWorkArea * wa)
2466 Buffer & buf = wa->bufferView().buffer();
2467 return closeWorkArea(wa, !buf.parent());
2471 bool GuiView::closeBuffer()
2473 GuiWorkArea * wa = currentMainWorkArea();
2474 setCurrentWorkArea(wa);
2475 Buffer & buf = wa->bufferView().buffer();
2476 return wa && closeWorkArea(wa, !buf.parent());
2480 void GuiView::writeSession() const {
2481 GuiWorkArea const * active_wa = currentMainWorkArea();
2482 for (int i = 0; i < d.splitter_->count(); ++i) {
2483 TabWorkArea * twa = d.tabWorkArea(i);
2484 for (int j = 0; j < twa->count(); ++j) {
2485 GuiWorkArea * wa = static_cast<GuiWorkArea *>(twa->widget(j));
2486 Buffer & buf = wa->bufferView().buffer();
2487 theSession().lastOpened().add(buf.fileName(), wa == active_wa);
2493 bool GuiView::closeBufferAll()
2495 // Close the workareas in all other views
2496 QList<int> const ids = guiApp->viewIds();
2497 for (int i = 0; i != ids.size(); ++i) {
2498 if (id_ != ids[i] && !guiApp->view(ids[i]).closeWorkAreaAll())
2502 // Close our own workareas
2503 if (!closeWorkAreaAll())
2506 // Now close the hidden buffers. We prevent hidden buffers from being
2507 // dirty, so we can just close them.
2508 theBufferList().closeAll();
2513 bool GuiView::closeWorkAreaAll()
2515 setCurrentWorkArea(currentMainWorkArea());
2517 // We might be in a situation that there is still a tabWorkArea, but
2518 // there are no tabs anymore. This can happen when we get here after a
2519 // TabWorkArea::lastWorkAreaRemoved() signal. Therefore we count how
2520 // many TabWorkArea's have no documents anymore.
2523 // We have to call count() each time, because it can happen that
2524 // more than one splitter will disappear in one iteration (bug 5998).
2525 for (; d.splitter_->count() > empty_twa; ) {
2526 TabWorkArea * twa = d.tabWorkArea(empty_twa);
2528 if (twa->count() == 0)
2531 setCurrentWorkArea(twa->currentWorkArea());
2532 if (!closeTabWorkArea(twa))
2540 bool GuiView::closeWorkArea(GuiWorkArea * wa, bool close_buffer)
2545 Buffer & buf = wa->bufferView().buffer();
2547 if (close_buffer && GuiViewPrivate::busyBuffers.contains(&buf)) {
2548 Alert::warning(_("Close document"),
2549 _("Document could not be closed because it is being processed by LyX."));
2554 return closeBuffer(buf);
2556 if (!inMultiTabs(wa))
2557 if (!saveBufferIfNeeded(buf, true))
2565 bool GuiView::closeBuffer(Buffer & buf)
2567 // If we are in a close_event all children will be closed in some time,
2568 // so no need to do it here. This will ensure that the children end up
2569 // in the session file in the correct order. If we close the master
2570 // buffer, we can close or release the child buffers here too.
2571 bool success = true;
2573 ListOfBuffers clist = buf.getChildren();
2574 ListOfBuffers::const_iterator it = clist.begin();
2575 ListOfBuffers::const_iterator const bend = clist.end();
2576 for (; it != bend; ++it) {
2577 // If a child is dirty, do not close
2578 // without user intervention
2579 //FIXME: should we look in other tabworkareas?
2580 Buffer * child_buf = *it;
2581 GuiWorkArea * child_wa = workArea(*child_buf);
2583 if (!closeWorkArea(child_wa, true)) {
2588 theBufferList().releaseChild(&buf, child_buf);
2592 // goto bookmark to update bookmark pit.
2593 //FIXME: we should update only the bookmarks related to this buffer!
2594 LYXERR(Debug::DEBUG, "GuiView::closeBuffer()");
2595 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
2596 guiApp->gotoBookmark(i+1, false, false);
2598 if (saveBufferIfNeeded(buf, false)) {
2599 buf.removeAutosaveFile();
2600 theBufferList().release(&buf);
2604 // open all children again to avoid a crash because of dangling
2605 // pointers (bug 6603)
2611 bool GuiView::closeTabWorkArea(TabWorkArea * twa)
2613 while (twa == d.currentTabWorkArea()) {
2614 twa->setCurrentIndex(twa->count()-1);
2616 GuiWorkArea * wa = twa->currentWorkArea();
2617 Buffer & b = wa->bufferView().buffer();
2619 // We only want to close the buffer if the same buffer is not visible
2620 // in another view, and if this is not a child and if we are closing
2621 // a view (not a tabgroup).
2622 bool const close_buffer =
2623 !inOtherView(b) && !b.parent() && closing_;
2625 if (!closeWorkArea(wa, close_buffer))
2632 bool GuiView::saveBufferIfNeeded(Buffer & buf, bool hiding)
2634 if (buf.isClean() || buf.paragraphs().empty())
2637 // Switch to this Buffer.
2642 if (buf.isUnnamed())
2643 file = from_utf8(buf.fileName().onlyFileName());
2645 file = buf.fileName().displayName(30);
2647 // Bring this window to top before asking questions.
2652 if (hiding && buf.isUnnamed()) {
2653 docstring const text = bformat(_("The document %1$s has not been "
2654 "saved yet.\n\nDo you want to save "
2655 "the document?"), file);
2656 ret = Alert::prompt(_("Save new document?"),
2657 text, 0, 1, _("&Save"), _("&Cancel"));
2661 docstring const text = bformat(_("The document %1$s has unsaved changes."
2662 "\n\nDo you want to save the document or discard the changes?"), file);
2663 ret = Alert::prompt(_("Save changed document?"),
2664 text, 0, 2, _("&Save"), _("&Discard"), _("&Cancel"));
2669 if (!saveBuffer(buf))
2673 // If we crash after this we could have no autosave file
2674 // but I guess this is really improbable (Jug).
2675 // Sometimes improbable things happen:
2676 // - see bug http://www.lyx.org/trac/ticket/6587 (ps)
2677 // buf.removeAutosaveFile();
2679 // revert all changes
2690 bool GuiView::inMultiTabs(GuiWorkArea * wa)
2692 Buffer & buf = wa->bufferView().buffer();
2694 for (int i = 0; i != d.splitter_->count(); ++i) {
2695 GuiWorkArea * wa_ = d.tabWorkArea(i)->workArea(buf);
2696 if (wa_ && wa_ != wa)
2699 return inOtherView(buf);
2703 bool GuiView::inOtherView(Buffer & buf)
2705 QList<int> const ids = guiApp->viewIds();
2707 for (int i = 0; i != ids.size(); ++i) {
2711 if (guiApp->view(ids[i]).workArea(buf))
2718 void GuiView::gotoNextOrPreviousBuffer(NextOrPrevious np)
2720 if (!documentBufferView())
2723 if (TabWorkArea * twa = d.currentTabWorkArea()) {
2724 Buffer * const curbuf = &documentBufferView()->buffer();
2725 int nwa = twa->count();
2726 for (int i = 0; i < nwa; ++i) {
2727 if (&workArea(i)->bufferView().buffer() == curbuf) {
2729 if (np == NEXTBUFFER)
2730 next_index = (i == nwa - 1 ? 0 : i + 1);
2732 next_index = (i == 0 ? nwa - 1 : i - 1);
2733 setBuffer(&workArea(next_index)->bufferView().buffer());
2741 /// make sure the document is saved
2742 static bool ensureBufferClean(Buffer * buffer)
2744 LASSERT(buffer, return false);
2745 if (buffer->isClean() && !buffer->isUnnamed())
2748 docstring const file = buffer->fileName().displayName(30);
2751 if (!buffer->isUnnamed()) {
2752 text = bformat(_("The document %1$s has unsaved "
2753 "changes.\n\nDo you want to save "
2754 "the document?"), file);
2755 title = _("Save changed document?");
2758 text = bformat(_("The document %1$s has not been "
2759 "saved yet.\n\nDo you want to save "
2760 "the document?"), file);
2761 title = _("Save new document?");
2763 int const ret = Alert::prompt(title, text, 0, 1, _("&Save"), _("&Cancel"));
2766 dispatch(FuncRequest(LFUN_BUFFER_WRITE));
2768 return buffer->isClean() && !buffer->isUnnamed();
2772 bool GuiView::reloadBuffer(Buffer & buf)
2774 Buffer::ReadStatus status = buf.reload();
2775 return status == Buffer::ReadSuccess;
2779 void GuiView::checkExternallyModifiedBuffers()
2781 BufferList::iterator bit = theBufferList().begin();
2782 BufferList::iterator const bend = theBufferList().end();
2783 for (; bit != bend; ++bit) {
2784 Buffer * buf = *bit;
2785 if (buf->fileName().exists()
2786 && buf->isExternallyModified(Buffer::checksum_method)) {
2787 docstring text = bformat(_("Document \n%1$s\n has been externally modified."
2788 " Reload now? Any local changes will be lost."),
2789 from_utf8(buf->absFileName()));
2790 int const ret = Alert::prompt(_("Reload externally changed document?"),
2791 text, 0, 1, _("&Reload"), _("&Cancel"));
2799 void GuiView::dispatchVC(FuncRequest const & cmd, DispatchResult & dr)
2801 Buffer * buffer = documentBufferView()
2802 ? &(documentBufferView()->buffer()) : 0;
2804 switch (cmd.action()) {
2805 case LFUN_VC_REGISTER:
2806 if (!buffer || !ensureBufferClean(buffer))
2808 if (!buffer->lyxvc().inUse()) {
2809 if (buffer->lyxvc().registrer()) {
2810 reloadBuffer(*buffer);
2811 dr.suppressMessageUpdate();
2816 case LFUN_VC_CHECK_IN:
2817 if (!buffer || !ensureBufferClean(buffer))
2819 if (buffer->lyxvc().inUse() && !buffer->isReadonly()) {
2820 dr.setMessage(buffer->lyxvc().checkIn());
2821 if (!dr.message().empty())
2822 reloadBuffer(*buffer);
2826 case LFUN_VC_CHECK_OUT:
2827 if (!buffer || !ensureBufferClean(buffer))
2829 if (buffer->lyxvc().inUse()) {
2830 dr.setMessage(buffer->lyxvc().checkOut());
2831 reloadBuffer(*buffer);
2835 case LFUN_VC_LOCKING_TOGGLE:
2836 LASSERT(buffer, return);
2837 if (!ensureBufferClean(buffer) || buffer->isReadonly())
2839 if (buffer->lyxvc().inUse()) {
2840 string res = buffer->lyxvc().lockingToggle();
2842 frontend::Alert::error(_("Revision control error."),
2843 _("Error when setting the locking property."));
2846 reloadBuffer(*buffer);
2851 case LFUN_VC_REVERT:
2852 LASSERT(buffer, return);
2853 if (buffer->lyxvc().revert()) {
2854 reloadBuffer(*buffer);
2855 dr.suppressMessageUpdate();
2859 case LFUN_VC_UNDO_LAST:
2860 LASSERT(buffer, return);
2861 buffer->lyxvc().undoLast();
2862 reloadBuffer(*buffer);
2863 dr.suppressMessageUpdate();
2866 case LFUN_VC_REPO_UPDATE:
2867 LASSERT(buffer, return);
2868 if (ensureBufferClean(buffer)) {
2869 dr.setMessage(buffer->lyxvc().repoUpdate());
2870 checkExternallyModifiedBuffers();
2874 case LFUN_VC_COMMAND: {
2875 string flag = cmd.getArg(0);
2876 if (buffer && contains(flag, 'R') && !ensureBufferClean(buffer))
2879 if (contains(flag, 'M')) {
2880 if (!Alert::askForText(message, _("LyX VC: Log Message")))
2883 string path = cmd.getArg(1);
2884 if (contains(path, "$$p") && buffer)
2885 path = subst(path, "$$p", buffer->filePath());
2886 LYXERR(Debug::LYXVC, "Directory: " << path);
2888 if (!pp.isReadableDirectory()) {
2889 lyxerr << _("Directory is not accessible.") << endl;
2892 support::PathChanger p(pp);
2894 string command = cmd.getArg(2);
2895 if (command.empty())
2898 command = subst(command, "$$i", buffer->absFileName());
2899 command = subst(command, "$$p", buffer->filePath());
2901 command = subst(command, "$$m", to_utf8(message));
2902 LYXERR(Debug::LYXVC, "Command: " << command);
2904 one.startscript(Systemcall::Wait, command);
2908 if (contains(flag, 'I'))
2909 buffer->markDirty();
2910 if (contains(flag, 'R'))
2911 reloadBuffer(*buffer);
2916 case LFUN_VC_COMPARE: {
2918 if (cmd.argument().empty()) {
2919 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "comparehistory"));
2923 string rev1 = cmd.getArg(0);
2927 if (!buffer->lyxvc().prepareFileRevision(rev1, f1))
2930 if (isStrInt(rev1) && convert<int>(rev1) <= 0) {
2931 f2 = buffer->absFileName();
2933 string rev2 = cmd.getArg(1);
2937 if (!buffer->lyxvc().prepareFileRevision(rev2, f2))
2941 LYXERR(Debug::LYXVC, "Launching comparison for fetched revisions:\n" <<
2942 f1 << "\n" << f2 << "\n" );
2943 string par = "compare run " + quoteName(f1) + " " + quoteName(f2);
2944 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, par));
2954 void GuiView::openChildDocument(string const & fname)
2956 LASSERT(documentBufferView(), return);
2957 Buffer & buffer = documentBufferView()->buffer();
2958 FileName const filename = support::makeAbsPath(fname, buffer.filePath());
2959 documentBufferView()->saveBookmark(false);
2961 if (theBufferList().exists(filename)) {
2962 child = theBufferList().getBuffer(filename);
2965 message(bformat(_("Opening child document %1$s..."),
2966 makeDisplayPath(filename.absFileName())));
2967 child = loadDocument(filename, false);
2969 // Set the parent name of the child document.
2970 // This makes insertion of citations and references in the child work,
2971 // when the target is in the parent or another child document.
2973 child->setParent(&buffer);
2977 bool GuiView::goToFileRow(string const & argument)
2981 size_t i = argument.find_last_of(' ');
2982 if (i != string::npos) {
2983 file_name = os::internal_path(trim(argument.substr(0, i)));
2984 istringstream is(argument.substr(i + 1));
2989 if (i == string::npos) {
2990 LYXERR0("Wrong argument: " << argument);
2994 string const abstmp = package().temp_dir().absFileName();
2995 string const realtmp = package().temp_dir().realPath();
2996 // We have to use os::path_prefix_is() here, instead of
2997 // simply prefixIs(), because the file name comes from
2998 // an external application and may need case adjustment.
2999 if (os::path_prefix_is(file_name, abstmp, os::CASE_ADJUSTED)
3000 || os::path_prefix_is(file_name, realtmp, os::CASE_ADJUSTED)) {
3001 // Needed by inverse dvi search. If it is a file
3002 // in tmpdir, call the apropriated function.
3003 // If tmpdir is a symlink, we may have the real
3004 // path passed back, so we correct for that.
3005 if (!prefixIs(file_name, abstmp))
3006 file_name = subst(file_name, realtmp, abstmp);
3007 buf = theBufferList().getBufferFromTmp(file_name);
3009 // Must replace extension of the file to be .lyx
3010 // and get full path
3011 FileName const s = fileSearch(string(),
3012 support::changeExtension(file_name, ".lyx"), "lyx");
3013 // Either change buffer or load the file
3014 if (theBufferList().exists(s))
3015 buf = theBufferList().getBuffer(s);
3016 else if (s.exists()) {
3017 buf = loadDocument(s);
3022 _("File does not exist: %1$s"),
3023 makeDisplayPath(file_name)));
3029 _("No buffer for file: %1$s."),
3030 makeDisplayPath(file_name))
3035 documentBufferView()->setCursorFromRow(row);
3040 #if (QT_VERSION >= 0x040400)
3042 Buffer::ExportStatus GuiView::GuiViewPrivate::runAndDestroy(const T& func, Buffer const * orig, Buffer * buffer, string const & format, string const & msg)
3044 Buffer::ExportStatus const status = func(format);
3046 // the cloning operation will have produced a clone of the entire set of
3047 // documents, starting from the master. so we must delete those.
3048 Buffer * mbuf = const_cast<Buffer *>(buffer->masterBuffer());
3050 busyBuffers.remove(orig);
3055 Buffer::ExportStatus GuiView::GuiViewPrivate::compileAndDestroy(Buffer const * orig, Buffer * buffer, string const & format)
3057 Buffer::ExportStatus (Buffer::* mem_func)(std::string const &, bool) const = &Buffer::doExport;
3058 return runAndDestroy(bind(mem_func, buffer, _1, true), orig, buffer, format, "export");
3062 Buffer::ExportStatus GuiView::GuiViewPrivate::exportAndDestroy(Buffer const * orig, Buffer * buffer, string const & format)
3064 Buffer::ExportStatus (Buffer::* mem_func)(std::string const &, bool) const = &Buffer::doExport;
3065 return runAndDestroy(bind(mem_func, buffer, _1, false), orig, buffer, format, "export");
3069 Buffer::ExportStatus GuiView::GuiViewPrivate::previewAndDestroy(Buffer const * orig, Buffer * buffer, string const & format)
3071 Buffer::ExportStatus (Buffer::* mem_func)(std::string const &) const = &Buffer::preview;
3072 return runAndDestroy(bind(mem_func, buffer, _1), orig, buffer, format, "preview");
3077 // not used, but the linker needs them
3079 Buffer::ExportStatus GuiView::GuiViewPrivate::compileAndDestroy(
3080 Buffer const *, Buffer *, string const &)
3082 return Buffer::ExportSuccess;
3086 Buffer::ExportStatus GuiView::GuiViewPrivate::exportAndDestroy(
3087 Buffer const *, Buffer *, string const &)
3089 return Buffer::ExportSuccess;
3093 Buffer::ExportStatus GuiView::GuiViewPrivate::previewAndDestroy(
3094 Buffer const *, Buffer *, string const &)
3096 return Buffer::ExportSuccess;
3102 bool GuiView::GuiViewPrivate::asyncBufferProcessing(
3103 string const & argument,
3104 Buffer const * used_buffer,
3105 docstring const & msg,
3106 Buffer::ExportStatus (*asyncFunc)(Buffer const *, Buffer *, string const &),
3107 Buffer::ExportStatus (Buffer::*syncFunc)(string const &, bool) const,
3108 Buffer::ExportStatus (Buffer::*previewFunc)(string const &) const)
3113 string format = argument;
3115 format = used_buffer->params().getDefaultOutputFormat();
3117 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
3119 progress_->clearMessages();
3122 GuiViewPrivate::busyBuffers.insert(used_buffer);
3123 QFuture<Buffer::ExportStatus> f = QtConcurrent::run(
3126 used_buffer->clone(),
3128 setPreviewFuture(f);
3129 processing_format = format;
3130 last_export_format = used_buffer->params().bufferFormat();
3133 // We are asynchronous, so we don't know here anything about the success
3137 // TODO check here if it breaks exporting with Qt < 4.4
3138 return (used_buffer->*syncFunc)(format, true);
3139 } else if (previewFunc) {
3140 return (used_buffer->*previewFunc)(format, false);
3147 void GuiView::dispatchToBufferView(FuncRequest const & cmd, DispatchResult & dr)
3149 BufferView * bv = currentBufferView();
3152 // Let the current BufferView dispatch its own actions.
3153 bv->dispatch(cmd, dr);
3154 if (dr.dispatched())
3157 // Try with the document BufferView dispatch if any.
3158 BufferView * doc_bv = documentBufferView();
3159 if (doc_bv && doc_bv != bv) {
3160 doc_bv->dispatch(cmd, dr);
3161 if (dr.dispatched())
3165 // Then let the current Cursor dispatch its own actions.
3166 bv->cursor().dispatch(cmd);
3168 // update completion. We do it here and not in
3169 // processKeySym to avoid another redraw just for a
3170 // changed inline completion
3171 if (cmd.origin() == FuncRequest::KEYBOARD) {
3172 if (cmd.action() == LFUN_SELF_INSERT
3173 || (cmd.action() == LFUN_ERT_INSERT && bv->cursor().inMathed()))
3174 updateCompletion(bv->cursor(), true, true);
3175 else if (cmd.action() == LFUN_CHAR_DELETE_BACKWARD)
3176 updateCompletion(bv->cursor(), false, true);
3178 updateCompletion(bv->cursor(), false, false);
3181 dr = bv->cursor().result();
3185 void GuiView::dispatch(FuncRequest const & cmd, DispatchResult & dr)
3187 BufferView * bv = currentBufferView();
3188 // By default we won't need any update.
3189 dr.screenUpdate(Update::None);
3190 // assume cmd will be dispatched
3191 dr.dispatched(true);
3193 Buffer * doc_buffer = documentBufferView()
3194 ? &(documentBufferView()->buffer()) : 0;
3196 if (cmd.origin() == FuncRequest::TOC) {
3197 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
3198 // FIXME: do we need to pass a DispatchResult object here?
3199 toc->doDispatch(bv->cursor(), cmd);
3203 string const argument = to_utf8(cmd.argument());
3205 switch(cmd.action()) {
3206 case LFUN_BUFFER_CHILD_OPEN:
3207 openChildDocument(to_utf8(cmd.argument()));
3210 case LFUN_BUFFER_IMPORT:
3211 importDocument(to_utf8(cmd.argument()));
3214 case LFUN_BUFFER_EXPORT: {
3217 // GCC only sees strfwd.h when building merged
3218 if (::lyx::operator==(cmd.argument(), "custom")) {
3219 dispatch(FuncRequest(LFUN_DIALOG_SHOW, "sendto"), dr);
3222 #if QT_VERSION < 0x040400
3223 if (!doc_buffer->doExport(argument, false)) {
3225 dr.setMessage(bformat(_("Error exporting to format: %1$s"),
3229 /* TODO/Review: Is it a problem to also export the children?
3230 See the update_unincluded flag */
3231 d.asyncBufferProcessing(argument,
3234 &GuiViewPrivate::exportAndDestroy,
3237 // TODO Inform user about success
3242 case LFUN_BUFFER_EXPORT_AS:
3243 LASSERT(doc_buffer, break);
3244 exportBufferAs(*doc_buffer);
3247 case LFUN_BUFFER_UPDATE: {
3248 d.asyncBufferProcessing(argument,
3251 &GuiViewPrivate::compileAndDestroy,
3256 case LFUN_BUFFER_VIEW: {
3257 d.asyncBufferProcessing(argument,
3259 _("Previewing ..."),
3260 &GuiViewPrivate::previewAndDestroy,
3265 case LFUN_MASTER_BUFFER_UPDATE: {
3266 d.asyncBufferProcessing(argument,
3267 (doc_buffer ? doc_buffer->masterBuffer() : 0),
3269 &GuiViewPrivate::compileAndDestroy,
3274 case LFUN_MASTER_BUFFER_VIEW: {
3275 d.asyncBufferProcessing(argument,
3276 (doc_buffer ? doc_buffer->masterBuffer() : 0),
3278 &GuiViewPrivate::previewAndDestroy,
3279 0, &Buffer::preview);
3282 case LFUN_BUFFER_SWITCH: {
3283 string const file_name = to_utf8(cmd.argument());
3284 if (!FileName::isAbsolute(file_name)) {
3286 dr.setMessage(_("Absolute filename expected."));
3290 Buffer * buffer = theBufferList().getBuffer(FileName(file_name));
3293 dr.setMessage(_("Document not loaded"));
3297 // Do we open or switch to the buffer in this view ?
3298 if (workArea(*buffer)
3299 || lyxrc.open_buffers_in_tabs || !documentBufferView()) {
3304 // Look for the buffer in other views
3305 QList<int> const ids = guiApp->viewIds();
3307 for (; i != ids.size(); ++i) {
3308 GuiView & gv = guiApp->view(ids[i]);
3309 if (gv.workArea(*buffer)) {
3310 gv.activateWindow();
3311 gv.setBuffer(buffer);
3316 // If necessary, open a new window as a last resort
3317 if (i == ids.size()) {
3318 lyx::dispatch(FuncRequest(LFUN_WINDOW_NEW));
3324 case LFUN_BUFFER_NEXT:
3325 gotoNextOrPreviousBuffer(NEXTBUFFER);
3328 case LFUN_BUFFER_PREVIOUS:
3329 gotoNextOrPreviousBuffer(PREVBUFFER);
3332 case LFUN_COMMAND_EXECUTE: {
3333 bool const show_it = cmd.argument() != "off";
3334 // FIXME: this is a hack, "minibuffer" should not be
3336 if (GuiToolbar * t = toolbar("minibuffer")) {
3337 t->setVisible(show_it);
3338 if (show_it && t->commandBuffer())
3339 t->commandBuffer()->setFocus();
3343 case LFUN_DROP_LAYOUTS_CHOICE:
3344 d.layout_->showPopup();
3347 case LFUN_MENU_OPEN:
3348 if (QMenu * menu = guiApp->menus().menu(toqstr(cmd.argument()), *this))
3349 menu->exec(QCursor::pos());
3352 case LFUN_FILE_INSERT:
3353 insertLyXFile(cmd.argument());
3356 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
3357 insertPlaintextFile(cmd.argument(), true);
3360 case LFUN_FILE_INSERT_PLAINTEXT:
3361 insertPlaintextFile(cmd.argument(), false);
3364 case LFUN_BUFFER_RELOAD: {
3365 LASSERT(doc_buffer, break);
3368 if (!doc_buffer->isClean()) {
3369 docstring const file =
3370 makeDisplayPath(doc_buffer->absFileName(), 20);
3371 docstring text = bformat(_("Any changes will be lost. "
3372 "Are you sure you want to revert to the saved version "
3373 "of the document %1$s?"), file);
3374 ret = Alert::prompt(_("Revert to saved document?"),
3375 text, 1, 1, _("&Revert"), _("&Cancel"));
3379 doc_buffer->markClean();
3380 reloadBuffer(*doc_buffer);
3381 dr.forceBufferUpdate();
3386 case LFUN_BUFFER_WRITE:
3387 LASSERT(doc_buffer, break);
3388 saveBuffer(*doc_buffer);
3391 case LFUN_BUFFER_WRITE_AS:
3392 LASSERT(doc_buffer, break);
3393 renameBuffer(*doc_buffer, cmd.argument());
3396 case LFUN_BUFFER_WRITE_ALL: {
3397 Buffer * first = theBufferList().first();
3400 message(_("Saving all documents..."));
3401 // We cannot use a for loop as the buffer list cycles.
3404 if (!b->isClean()) {
3406 LYXERR(Debug::ACTION, "Saved " << b->absFileName());
3408 b = theBufferList().next(b);
3409 } while (b != first);
3410 dr.setMessage(_("All documents saved."));
3414 case LFUN_BUFFER_CLOSE:
3418 case LFUN_BUFFER_CLOSE_ALL:
3422 case LFUN_TOOLBAR_TOGGLE: {
3423 string const name = cmd.getArg(0);
3424 if (GuiToolbar * t = toolbar(name))
3429 case LFUN_DIALOG_UPDATE: {
3430 string const name = to_utf8(cmd.argument());
3431 if (name == "prefs" || name == "document")
3432 updateDialog(name, string());
3433 else if (name == "paragraph")
3434 lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
3435 else if (currentBufferView()) {
3436 Inset * inset = currentBufferView()->editedInset(name);
3437 // Can only update a dialog connected to an existing inset
3439 // FIXME: get rid of this indirection; GuiView ask the inset
3440 // if he is kind enough to update itself...
3441 FuncRequest fr(LFUN_INSET_DIALOG_UPDATE, cmd.argument());
3442 //FIXME: pass DispatchResult here?
3443 inset->dispatch(currentBufferView()->cursor(), fr);
3449 case LFUN_DIALOG_TOGGLE: {
3450 FuncCode const func_code = isDialogVisible(cmd.getArg(0))
3451 ? LFUN_DIALOG_HIDE : LFUN_DIALOG_SHOW;
3452 dispatch(FuncRequest(func_code, cmd.argument()), dr);
3456 case LFUN_DIALOG_DISCONNECT_INSET:
3457 disconnectDialog(to_utf8(cmd.argument()));
3460 case LFUN_DIALOG_HIDE: {
3461 guiApp->hideDialogs(to_utf8(cmd.argument()), 0);
3465 case LFUN_DIALOG_SHOW: {
3466 string const name = cmd.getArg(0);
3467 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
3469 if (name == "character") {
3470 data = freefont2string();
3472 showDialog("character", data);
3473 } else if (name == "latexlog") {
3474 Buffer::LogType type;
3475 string const logfile = doc_buffer->logName(&type);
3477 case Buffer::latexlog:
3480 case Buffer::buildlog:
3484 data += Lexer::quoteString(logfile);
3485 showDialog("log", data);
3486 } else if (name == "vclog") {
3487 string const data = "vc " +
3488 Lexer::quoteString(doc_buffer->lyxvc().getLogFile());
3489 showDialog("log", data);
3490 } else if (name == "symbols") {
3491 data = bv->cursor().getEncoding()->name();
3493 showDialog("symbols", data);
3495 } else if (name == "prefs" && isFullScreen()) {
3496 lfunUiToggle("fullscreen");
3497 showDialog("prefs", data);
3499 showDialog(name, data);
3504 dr.setMessage(cmd.argument());
3507 case LFUN_UI_TOGGLE: {
3508 string arg = cmd.getArg(0);
3509 if (!lfunUiToggle(arg)) {
3510 docstring const msg = "ui-toggle " + _("%1$s unknown command!");
3511 dr.setMessage(bformat(msg, from_utf8(arg)));
3513 // Make sure the keyboard focus stays in the work area.
3518 case LFUN_SPLIT_VIEW: {
3519 LASSERT(doc_buffer, break);
3520 string const orientation = cmd.getArg(0);
3521 d.splitter_->setOrientation(orientation == "vertical"
3522 ? Qt::Vertical : Qt::Horizontal);
3523 TabWorkArea * twa = addTabWorkArea();
3524 GuiWorkArea * wa = twa->addWorkArea(*doc_buffer, *this);
3525 setCurrentWorkArea(wa);
3528 case LFUN_CLOSE_TAB_GROUP:
3529 if (TabWorkArea * twa = d.currentTabWorkArea()) {
3530 closeTabWorkArea(twa);
3531 d.current_work_area_ = 0;
3532 twa = d.currentTabWorkArea();
3533 // Switch to the next GuiWorkArea in the found TabWorkArea.
3535 // Make sure the work area is up to date.
3536 setCurrentWorkArea(twa->currentWorkArea());
3538 setCurrentWorkArea(0);
3543 case LFUN_COMPLETION_INLINE:
3544 if (d.current_work_area_)
3545 d.current_work_area_->completer().showInline();
3548 case LFUN_COMPLETION_POPUP:
3549 if (d.current_work_area_)
3550 d.current_work_area_->completer().showPopup();
3554 case LFUN_COMPLETION_COMPLETE:
3555 if (d.current_work_area_)
3556 d.current_work_area_->completer().tab();
3559 case LFUN_COMPLETION_CANCEL:
3560 if (d.current_work_area_) {
3561 if (d.current_work_area_->completer().popupVisible())
3562 d.current_work_area_->completer().hidePopup();
3564 d.current_work_area_->completer().hideInline();
3568 case LFUN_COMPLETION_ACCEPT:
3569 if (d.current_work_area_)
3570 d.current_work_area_->completer().activate();
3573 case LFUN_BUFFER_ZOOM_IN:
3574 case LFUN_BUFFER_ZOOM_OUT:
3575 if (cmd.argument().empty()) {
3576 if (cmd.action() == LFUN_BUFFER_ZOOM_IN)
3581 lyxrc.zoom += convert<int>(cmd.argument());
3583 if (lyxrc.zoom < 10)
3586 // The global QPixmapCache is used in GuiPainter to cache text
3587 // painting so we must reset it.
3588 QPixmapCache::clear();
3589 guiApp->fontLoader().update();
3590 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
3593 case LFUN_VC_REGISTER:
3594 case LFUN_VC_CHECK_IN:
3595 case LFUN_VC_CHECK_OUT:
3596 case LFUN_VC_REPO_UPDATE:
3597 case LFUN_VC_LOCKING_TOGGLE:
3598 case LFUN_VC_REVERT:
3599 case LFUN_VC_UNDO_LAST:
3600 case LFUN_VC_COMMAND:
3601 case LFUN_VC_COMPARE:
3602 dispatchVC(cmd, dr);
3605 case LFUN_SERVER_GOTO_FILE_ROW:
3606 goToFileRow(to_utf8(cmd.argument()));
3609 case LFUN_FORWARD_SEARCH: {
3610 Buffer const * doc_master = doc_buffer->masterBuffer();
3611 FileName const path(doc_master->temppath());
3612 string const texname = doc_master->isChild(doc_buffer)
3613 ? DocFileName(changeExtension(
3614 doc_buffer->absFileName(),
3615 "tex")).mangledFileName()
3616 : doc_buffer->latexName();
3617 string const mastername =
3618 removeExtension(doc_master->latexName());
3619 FileName const dviname(addName(path.absFileName(),
3620 addExtension(mastername, "dvi")));
3621 FileName const pdfname(addName(path.absFileName(),
3622 addExtension(mastername, "pdf")));
3623 bool const have_dvi = dviname.exists();
3624 bool const have_pdf = pdfname.exists();
3625 if (!have_dvi && !have_pdf) {
3626 dr.setMessage(_("Please, preview the document first."));
3629 string outname = dviname.onlyFileName();
3630 string command = lyxrc.forward_search_dvi;
3631 if (!have_dvi || (have_pdf &&
3632 pdfname.lastModified() > dviname.lastModified())) {
3633 outname = pdfname.onlyFileName();
3634 command = lyxrc.forward_search_pdf;
3637 int row = doc_buffer->texrow().getRowFromIdPos(bv->cursor().paragraph().id(), bv->cursor().pos());
3638 LYXERR(Debug::ACTION, "Forward search: row:" << row
3639 << " id:" << bv->cursor().paragraph().id());
3640 if (!row || command.empty()) {
3641 dr.setMessage(_("Couldn't proceed."));
3644 string texrow = convert<string>(row);
3646 command = subst(command, "$$n", texrow);
3647 command = subst(command, "$$t", texname);
3648 command = subst(command, "$$o", outname);
3650 PathChanger p(path);
3652 one.startscript(Systemcall::DontWait, command);
3656 // The LFUN must be for one of BufferView, Buffer or Cursor;
3658 dispatchToBufferView(cmd, dr);
3662 // Part of automatic menu appearance feature.
3663 if (isFullScreen()) {
3664 if (menuBar()->isVisible() && lyxrc.full_screen_menubar)
3666 if (statusBar()->isVisible())
3667 statusBar()->hide();
3672 bool GuiView::lfunUiToggle(string const & ui_component)
3674 if (ui_component == "scrollbar") {
3675 // hide() is of no help
3676 if (d.current_work_area_->verticalScrollBarPolicy() ==
3677 Qt::ScrollBarAlwaysOff)
3679 d.current_work_area_->setVerticalScrollBarPolicy(
3680 Qt::ScrollBarAsNeeded);
3682 d.current_work_area_->setVerticalScrollBarPolicy(
3683 Qt::ScrollBarAlwaysOff);
3684 } else if (ui_component == "statusbar") {
3685 statusBar()->setVisible(!statusBar()->isVisible());
3686 } else if (ui_component == "menubar") {
3687 menuBar()->setVisible(!menuBar()->isVisible());
3689 #if QT_VERSION >= 0x040300
3690 if (ui_component == "frame") {
3692 getContentsMargins(&l, &t, &r, &b);
3693 //are the frames in default state?
3694 d.current_work_area_->setFrameStyle(QFrame::NoFrame);
3696 setContentsMargins(-2, -2, -2, -2);
3698 setContentsMargins(0, 0, 0, 0);
3702 if (ui_component == "fullscreen") {
3710 void GuiView::toggleFullScreen()
3712 if (isFullScreen()) {
3713 for (int i = 0; i != d.splitter_->count(); ++i)
3714 d.tabWorkArea(i)->setFullScreen(false);
3715 #if QT_VERSION >= 0x040300
3716 setContentsMargins(0, 0, 0, 0);
3718 setWindowState(windowState() ^ Qt::WindowFullScreen);
3721 statusBar()->show();
3724 hideDialogs("prefs", 0);
3725 for (int i = 0; i != d.splitter_->count(); ++i)
3726 d.tabWorkArea(i)->setFullScreen(true);
3727 #if QT_VERSION >= 0x040300
3728 setContentsMargins(-2, -2, -2, -2);
3731 setWindowState(windowState() ^ Qt::WindowFullScreen);
3732 statusBar()->hide();
3733 if (lyxrc.full_screen_menubar)
3735 if (lyxrc.full_screen_toolbars) {
3736 ToolbarMap::iterator end = d.toolbars_.end();
3737 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
3742 // give dialogs like the TOC a chance to adapt
3747 Buffer const * GuiView::updateInset(Inset const * inset)
3752 Buffer const * inset_buffer = &(inset->buffer());
3754 for (int i = 0; i != d.splitter_->count(); ++i) {
3755 GuiWorkArea * wa = d.tabWorkArea(i)->currentWorkArea();
3758 Buffer const * buffer = &(wa->bufferView().buffer());
3759 if (inset_buffer == buffer)
3760 wa->scheduleRedraw();
3762 return inset_buffer;
3766 void GuiView::restartCursor()
3768 /* When we move around, or type, it's nice to be able to see
3769 * the cursor immediately after the keypress.
3771 if (d.current_work_area_)
3772 d.current_work_area_->startBlinkingCursor();
3774 // Take this occasion to update the other GUI elements.
3780 void GuiView::updateCompletion(Cursor & cur, bool start, bool keep)
3782 if (d.current_work_area_)
3783 d.current_work_area_->completer().updateVisibility(cur, start, keep);
3788 // This list should be kept in sync with the list of insets in
3789 // src/insets/Inset.cpp. I.e., if a dialog goes with an inset, the
3790 // dialog should have the same name as the inset.
3791 // Changes should be also recorded in LFUN_DIALOG_SHOW doxygen
3792 // docs in LyXAction.cpp.
3794 char const * const dialognames[] = {
3796 "aboutlyx", "bibitem", "bibtex", "box", "branch", "changes", "character",
3797 "citation", "compare", "comparehistory", "document", "errorlist", "ert",
3798 "external", "file", "findreplace", "findreplaceadv", "float", "graphics",
3799 "href", "include", "index", "index_print", "info", "listings", "label", "line",
3800 "log", "mathdelimiter", "mathmatrix", "mathspace", "nomenclature",
3801 "nomencl_print", "note", "paragraph", "phantom", "prefs", "print", "ref",
3802 "sendto", "space", "spellchecker", "symbols", "tabular", "tabularcreate",
3803 "thesaurus", "texinfo", "toc", "view-source", "vspace", "wrap", "progress"};
3805 char const * const * const end_dialognames =
3806 dialognames + (sizeof(dialognames) / sizeof(char *));
3810 cmpCStr(char const * name) : name_(name) {}
3811 bool operator()(char const * other) {
3812 return strcmp(other, name_) == 0;
3819 bool isValidName(string const & name)
3821 return find_if(dialognames, end_dialognames,
3822 cmpCStr(name.c_str())) != end_dialognames;
3828 void GuiView::resetDialogs()
3830 // Make sure that no LFUN uses any GuiView.
3831 guiApp->setCurrentView(0);
3835 constructToolbars();
3836 guiApp->menus().fillMenuBar(menuBar(), this, false);
3837 d.layout_->updateContents(true);
3838 // Now update controls with current buffer.
3839 guiApp->setCurrentView(this);
3845 Dialog * GuiView::findOrBuild(string const & name, bool hide_it)
3847 if (!isValidName(name))
3850 map<string, DialogPtr>::iterator it = d.dialogs_.find(name);
3852 if (it != d.dialogs_.end()) {
3854 it->second->hideView();
3855 return it->second.get();
3858 Dialog * dialog = build(name);
3859 d.dialogs_[name].reset(dialog);
3860 if (lyxrc.allow_geometry_session)
3861 dialog->restoreSession();
3868 void GuiView::showDialog(string const & name, string const & data,
3871 triggerShowDialog(toqstr(name), toqstr(data), inset);
3875 void GuiView::doShowDialog(QString const & qname, QString const & qdata,
3881 const string name = fromqstr(qname);
3882 const string data = fromqstr(qdata);
3886 Dialog * dialog = findOrBuild(name, false);
3888 bool const visible = dialog->isVisibleView();
3889 dialog->showData(data);
3890 if (inset && currentBufferView())
3891 currentBufferView()->editInset(name, inset);
3892 // We only set the focus to the new dialog if it was not yet
3893 // visible in order not to change the existing previous behaviour
3895 // activateWindow is needed for floating dockviews
3896 dialog->asQWidget()->raise();
3897 dialog->asQWidget()->activateWindow();
3898 dialog->asQWidget()->setFocus();
3902 catch (ExceptionMessage const & ex) {
3910 bool GuiView::isDialogVisible(string const & name) const
3912 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3913 if (it == d.dialogs_.end())
3915 return it->second.get()->isVisibleView() && !it->second.get()->isClosing();
3919 void GuiView::hideDialog(string const & name, Inset * inset)
3921 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3922 if (it == d.dialogs_.end())
3926 if (!currentBufferView())
3928 if (inset != currentBufferView()->editedInset(name))
3932 Dialog * const dialog = it->second.get();
3933 if (dialog->isVisibleView())
3935 if (currentBufferView())
3936 currentBufferView()->editInset(name, 0);
3940 void GuiView::disconnectDialog(string const & name)
3942 if (!isValidName(name))
3944 if (currentBufferView())
3945 currentBufferView()->editInset(name, 0);
3949 void GuiView::hideAll() const
3951 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
3952 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3954 for(; it != end; ++it)
3955 it->second->hideView();
3959 void GuiView::updateDialogs()
3961 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
3962 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3964 for(; it != end; ++it) {
3965 Dialog * dialog = it->second.get();
3967 if (dialog->needBufferOpen() && !documentBufferView())
3968 hideDialog(fromqstr(dialog->name()), 0);
3969 else if (dialog->isVisibleView())
3970 dialog->checkStatus();
3977 Dialog * createDialog(GuiView & lv, string const & name);
3979 // will be replaced by a proper factory...
3980 Dialog * createGuiAbout(GuiView & lv);
3981 Dialog * createGuiBibtex(GuiView & lv);
3982 Dialog * createGuiChanges(GuiView & lv);
3983 Dialog * createGuiCharacter(GuiView & lv);
3984 Dialog * createGuiCitation(GuiView & lv);
3985 Dialog * createGuiCompare(GuiView & lv);
3986 Dialog * createGuiCompareHistory(GuiView & lv);
3987 Dialog * createGuiDelimiter(GuiView & lv);
3988 Dialog * createGuiDocument(GuiView & lv);
3989 Dialog * createGuiErrorList(GuiView & lv);
3990 Dialog * createGuiExternal(GuiView & lv);
3991 Dialog * createGuiGraphics(GuiView & lv);
3992 Dialog * createGuiInclude(GuiView & lv);
3993 Dialog * createGuiIndex(GuiView & lv);
3994 Dialog * createGuiListings(GuiView & lv);
3995 Dialog * createGuiLog(GuiView & lv);
3996 Dialog * createGuiMathMatrix(GuiView & lv);
3997 Dialog * createGuiNote(GuiView & lv);
3998 Dialog * createGuiParagraph(GuiView & lv);
3999 Dialog * createGuiPhantom(GuiView & lv);
4000 Dialog * createGuiPreferences(GuiView & lv);
4001 Dialog * createGuiPrint(GuiView & lv);
4002 Dialog * createGuiPrintindex(GuiView & lv);
4003 Dialog * createGuiRef(GuiView & lv);
4004 Dialog * createGuiSearch(GuiView & lv);
4005 Dialog * createGuiSearchAdv(GuiView & lv);
4006 Dialog * createGuiSendTo(GuiView & lv);
4007 Dialog * createGuiShowFile(GuiView & lv);
4008 Dialog * createGuiSpellchecker(GuiView & lv);
4009 Dialog * createGuiSymbols(GuiView & lv);
4010 Dialog * createGuiTabularCreate(GuiView & lv);
4011 Dialog * createGuiTexInfo(GuiView & lv);
4012 Dialog * createGuiToc(GuiView & lv);
4013 Dialog * createGuiThesaurus(GuiView & lv);
4014 Dialog * createGuiViewSource(GuiView & lv);
4015 Dialog * createGuiWrap(GuiView & lv);
4016 Dialog * createGuiProgressView(GuiView & lv);
4020 Dialog * GuiView::build(string const & name)
4022 LASSERT(isValidName(name), return 0);
4024 Dialog * dialog = createDialog(*this, name);
4028 if (name == "aboutlyx")
4029 return createGuiAbout(*this);
4030 if (name == "bibtex")
4031 return createGuiBibtex(*this);
4032 if (name == "changes")
4033 return createGuiChanges(*this);
4034 if (name == "character")
4035 return createGuiCharacter(*this);
4036 if (name == "citation")
4037 return createGuiCitation(*this);
4038 if (name == "compare")
4039 return createGuiCompare(*this);
4040 if (name == "comparehistory")
4041 return createGuiCompareHistory(*this);
4042 if (name == "document")
4043 return createGuiDocument(*this);
4044 if (name == "errorlist")
4045 return createGuiErrorList(*this);
4046 if (name == "external")
4047 return createGuiExternal(*this);
4049 return createGuiShowFile(*this);
4050 if (name == "findreplace")
4051 return createGuiSearch(*this);
4052 if (name == "findreplaceadv")
4053 return createGuiSearchAdv(*this);
4054 if (name == "graphics")
4055 return createGuiGraphics(*this);
4056 if (name == "include")
4057 return createGuiInclude(*this);
4058 if (name == "index")
4059 return createGuiIndex(*this);
4060 if (name == "index_print")
4061 return createGuiPrintindex(*this);
4062 if (name == "listings")
4063 return createGuiListings(*this);
4065 return createGuiLog(*this);
4066 if (name == "mathdelimiter")
4067 return createGuiDelimiter(*this);
4068 if (name == "mathmatrix")
4069 return createGuiMathMatrix(*this);
4071 return createGuiNote(*this);
4072 if (name == "paragraph")
4073 return createGuiParagraph(*this);
4074 if (name == "phantom")
4075 return createGuiPhantom(*this);
4076 if (name == "prefs")
4077 return createGuiPreferences(*this);
4078 if (name == "print")
4079 return createGuiPrint(*this);
4081 return createGuiRef(*this);
4082 if (name == "sendto")
4083 return createGuiSendTo(*this);
4084 if (name == "spellchecker")
4085 return createGuiSpellchecker(*this);
4086 if (name == "symbols")
4087 return createGuiSymbols(*this);
4088 if (name == "tabularcreate")
4089 return createGuiTabularCreate(*this);
4090 if (name == "texinfo")
4091 return createGuiTexInfo(*this);
4092 if (name == "thesaurus")
4093 return createGuiThesaurus(*this);
4095 return createGuiToc(*this);
4096 if (name == "view-source")
4097 return createGuiViewSource(*this);
4099 return createGuiWrap(*this);
4100 if (name == "progress")
4101 return createGuiProgressView(*this);
4107 } // namespace frontend
4110 #include "moc_GuiView.cpp"