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 "FileDialog.h"
20 #include "FontLoader.h"
21 #include "GuiApplication.h"
22 #include "GuiCommandBuffer.h"
23 #include "GuiCompleter.h"
24 #include "GuiWorkArea.h"
25 #include "GuiKeySymbol.h"
27 #include "GuiToolbar.h"
28 #include "LayoutBox.h"
32 #include "qt_helpers.h"
34 #include "frontends/alert.h"
36 #include "buffer_funcs.h"
38 #include "BufferList.h"
39 #include "BufferParams.h"
40 #include "BufferView.h"
41 #include "Converter.h"
43 #include "CutAndPaste.h"
45 #include "ErrorList.h"
47 #include "FuncStatus.h"
48 #include "FuncRequest.h"
52 #include "LyXAction.h"
57 #include "Paragraph.h"
58 #include "SpellChecker.h"
59 #include "TextClass.h"
64 #include "support/convert.h"
65 #include "support/debug.h"
66 #include "support/ExceptionMessage.h"
67 #include "support/FileName.h"
68 #include "support/filetools.h"
69 #include "support/gettext.h"
70 #include "support/filetools.h"
71 #include "support/ForkedCalls.h"
72 #include "support/lassert.h"
73 #include "support/lstrings.h"
74 #include "support/os.h"
75 #include "support/Package.h"
76 #include "support/Path.h"
77 #include "support/Systemcall.h"
78 #include "support/Timeout.h"
79 #include "support/ProgressInterface.h"
80 #include "GuiProgress.h"
83 #include <QApplication>
84 #include <QCloseEvent>
86 #include <QDesktopWidget>
87 #include <QDragEnterEvent>
94 #include <QPixmapCache>
96 #include <QPushButton>
100 #include <QStackedWidget>
101 #include <QStatusBar>
106 #include <QScrollBar>
108 #define EXPORT_in_THREAD 1
110 // QtConcurrent was introduced in Qt 4.4
111 #if (QT_VERSION >= 0x040400)
113 #include <QFutureWatcher>
114 #include <QtConcurrentRun>
117 #include <boost/bind.hpp>
121 #ifdef HAVE_SYS_TIME_H
122 # include <sys/time.h>
129 using namespace lyx::support;
136 class BackgroundWidget : public QWidget
141 LYXERR(Debug::GUI, "show banner: " << lyxrc.show_banner);
142 /// The text to be written on top of the pixmap
143 QString const text = lyx_version ?
144 qt_("version ") + lyx_version : qt_("unknown version");
145 splash_ = getPixmap("images/", "banner", "png");
147 QPainter pain(&splash_);
148 pain.setPen(QColor(0, 0, 0));
150 // The font used to display the version info
151 font.setStyleHint(QFont::SansSerif);
152 font.setWeight(QFont::Bold);
153 font.setPointSize(int(toqstr(lyxrc.font_sizes[FONT_SIZE_LARGE]).toDouble()));
155 pain.drawText(260, 15, text);
158 void paintEvent(QPaintEvent *)
160 int x = (width() - splash_.width()) / 2;
161 int y = (height() - splash_.height()) / 2;
163 pain.drawPixmap(x, y, splash_);
171 /// Toolbar store providing access to individual toolbars by name.
172 typedef map<string, GuiToolbar *> ToolbarMap;
174 typedef boost::shared_ptr<Dialog> DialogPtr;
179 struct GuiView::GuiViewPrivate
181 GuiViewPrivate(GuiView * gv)
182 : gv_(gv), current_work_area_(0), current_main_work_area_(0),
183 layout_(0), autosave_timeout_(5000),
186 // hardcode here the platform specific icon size
187 smallIconSize = 14; // scaling problems
188 normalIconSize = 20; // ok, default
189 bigIconSize = 26; // better for some math icons
191 splitter_ = new QSplitter;
192 bg_widget_ = new BackgroundWidget;
193 stack_widget_ = new QStackedWidget;
194 stack_widget_->addWidget(bg_widget_);
195 stack_widget_->addWidget(splitter_);
197 progress_ = new GuiProgress(gv);
204 delete stack_widget_;
208 QMenu * toolBarPopup(GuiView * parent)
210 // FIXME: translation
211 QMenu * menu = new QMenu(parent);
212 QActionGroup * iconSizeGroup = new QActionGroup(parent);
214 QAction * smallIcons = new QAction(iconSizeGroup);
215 smallIcons->setText(qt_("Small-sized icons"));
216 smallIcons->setCheckable(true);
217 QObject::connect(smallIcons, SIGNAL(triggered()),
218 parent, SLOT(smallSizedIcons()));
219 menu->addAction(smallIcons);
221 QAction * normalIcons = new QAction(iconSizeGroup);
222 normalIcons->setText(qt_("Normal-sized icons"));
223 normalIcons->setCheckable(true);
224 QObject::connect(normalIcons, SIGNAL(triggered()),
225 parent, SLOT(normalSizedIcons()));
226 menu->addAction(normalIcons);
228 QAction * bigIcons = new QAction(iconSizeGroup);
229 bigIcons->setText(qt_("Big-sized icons"));
230 bigIcons->setCheckable(true);
231 QObject::connect(bigIcons, SIGNAL(triggered()),
232 parent, SLOT(bigSizedIcons()));
233 menu->addAction(bigIcons);
235 unsigned int cur = parent->iconSize().width();
236 if ( cur == parent->d.smallIconSize)
237 smallIcons->setChecked(true);
238 else if (cur == parent->d.normalIconSize)
239 normalIcons->setChecked(true);
240 else if (cur == parent->d.bigIconSize)
241 bigIcons->setChecked(true);
248 stack_widget_->setCurrentWidget(bg_widget_);
249 bg_widget_->setUpdatesEnabled(true);
252 TabWorkArea * tabWorkArea(int i)
254 return dynamic_cast<TabWorkArea *>(splitter_->widget(i));
257 TabWorkArea * currentTabWorkArea()
259 if (splitter_->count() == 1)
260 // The first TabWorkArea is always the first one, if any.
261 return tabWorkArea(0);
263 for (int i = 0; i != splitter_->count(); ++i) {
264 TabWorkArea * twa = tabWorkArea(i);
265 if (current_main_work_area_ == twa->currentWorkArea())
269 // None has the focus so we just take the first one.
270 return tabWorkArea(0);
273 void setPreviewFuture(QFuture<docstring> const & f)
275 if (preview_watcher_.isRunning())
276 preview_watcher_.waitForFinished();
277 preview_watcher_.setFuture(f);
278 connect(&preview_watcher_, SIGNAL(finished()), gv_,
279 SLOT(threadFinished()));
284 GuiWorkArea * current_work_area_;
285 GuiWorkArea * current_main_work_area_;
286 QSplitter * splitter_;
287 QStackedWidget * stack_widget_;
288 BackgroundWidget * bg_widget_;
290 ToolbarMap toolbars_;
291 ProgressInterface* progress_;
292 /// The main layout box.
294 * \warning Don't Delete! The layout box is actually owned by
295 * whichever toolbar contains it. All the GuiView class needs is a
296 * means of accessing it.
298 * FIXME: replace that with a proper model so that we are not limited
299 * to only one dialog.
304 map<string, DialogPtr> dialogs_;
306 unsigned int smallIconSize;
307 unsigned int normalIconSize;
308 unsigned int bigIconSize;
310 QTimer statusbar_timer_;
311 /// auto-saving of buffers
312 Timeout autosave_timeout_;
313 /// flag against a race condition due to multiclicks, see bug #1119
317 TocModels toc_models_;
319 #if (QT_VERSION >= 0x040400)
321 QFutureWatcher<docstring> autosave_watcher_;
322 QFutureWatcher<docstring> preview_watcher_;
327 GuiView::GuiView(int id)
328 : d(*new GuiViewPrivate(this)), id_(id), closing_(false)
330 // GuiToolbars *must* be initialised before the menu bar.
331 normalSizedIcons(); // at least on Mac the default is 32 otherwise, which is huge
334 // set ourself as the current view. This is needed for the menu bar
335 // filling, at least for the static special menu item on Mac. Otherwise
336 // they are greyed out.
337 guiApp->setCurrentView(this);
339 // Fill up the menu bar.
340 guiApp->menus().fillMenuBar(menuBar(), this, true);
342 setCentralWidget(d.stack_widget_);
344 // Start autosave timer
345 if (lyxrc.autosave) {
346 d.autosave_timeout_.timeout.connect(boost::bind(&GuiView::autoSave, this));
347 d.autosave_timeout_.setTimeout(lyxrc.autosave * 1000);
348 d.autosave_timeout_.start();
350 connect(&d.statusbar_timer_, SIGNAL(timeout()),
351 this, SLOT(clearMessage()));
353 // We don't want to keep the window in memory if it is closed.
354 setAttribute(Qt::WA_DeleteOnClose, true);
356 #if (!defined(Q_WS_WIN) && !defined(Q_WS_MACX))
357 // assign an icon to main form. We do not do it under Qt/Win or Qt/Mac,
358 // since the icon is provided in the application bundle.
359 setWindowIcon(getPixmap("images/", "lyx", "png"));
363 setAcceptDrops(true);
365 statusBar()->setSizeGripEnabled(true);
367 // Forbid too small unresizable window because it can happen
368 // with some window manager under X11.
369 setMinimumSize(300, 200);
371 if (lyxrc.allow_geometry_session) {
372 // Now take care of session management.
377 // no session handling, default to a sane size.
378 setGeometry(50, 50, 690, 510);
381 // clear session data if any.
383 settings.remove("views");
385 #if (QT_VERSION >= 0x040400)
386 connect(&d.autosave_watcher_, SIGNAL(finished()), this,
387 SLOT(threadFinished()));
390 connect(this, SIGNAL(triggerShowDialog(QString const &, QString const &, Inset *)),
391 SLOT(doShowDialog(QString const &, QString const &, Inset *)));
401 void GuiView::threadFinished()
403 #if (QT_VERSION >= 0x040400)
404 QFutureWatcher<docstring> const * watcher =
405 static_cast<QFutureWatcher<docstring> const *>(sender());
406 message(watcher->result());
411 void GuiView::saveLayout() const
414 settings.beginGroup("views");
415 settings.beginGroup(QString::number(id_));
417 settings.setValue("pos", pos());
418 settings.setValue("size", size());
420 settings.setValue("geometry", saveGeometry());
422 settings.setValue("layout", saveState(0));
423 settings.setValue("icon_size", iconSize());
427 bool GuiView::restoreLayout()
430 settings.beginGroup("views");
431 settings.beginGroup(QString::number(id_));
432 QString const icon_key = "icon_size";
433 if (!settings.contains(icon_key))
436 //code below is skipped when when ~/.config/LyX is (re)created
437 setIconSize(settings.value(icon_key).toSize());
439 QPoint pos = settings.value("pos", QPoint(50, 50)).toPoint();
440 QSize size = settings.value("size", QSize(690, 510)).toSize();
444 // Work-around for bug #6034: the window ends up in an undetermined
445 // state when trying to restore a maximized window when it is
446 // already maximized.
447 if (!(windowState() & Qt::WindowMaximized))
448 if (!restoreGeometry(settings.value("geometry").toByteArray()))
449 setGeometry(50, 50, 690, 510);
451 // Make sure layout is correctly oriented.
452 setLayoutDirection(qApp->layoutDirection());
454 // Allow the toc and view-source dock widget to be restored if needed.
456 if ((dialog = findOrBuild("toc", true)))
457 // see bug 5082. At least setup title and enabled state.
458 // Visibility will be adjusted by restoreState below.
459 dialog->prepareView();
460 if ((dialog = findOrBuild("view-source", true)))
461 dialog->prepareView();
463 if (!restoreState(settings.value("layout").toByteArray(), 0))
470 GuiToolbar * GuiView::toolbar(string const & name)
472 ToolbarMap::iterator it = d.toolbars_.find(name);
473 if (it != d.toolbars_.end())
476 LYXERR(Debug::GUI, "Toolbar::display: no toolbar named " << name);
477 message(bformat(_("Unknown toolbar \"%1$s\""), from_utf8(name)));
482 void GuiView::constructToolbars()
484 ToolbarMap::iterator it = d.toolbars_.begin();
485 for (; it != d.toolbars_.end(); ++it)
489 // I don't like doing this here, but the standard toolbar
490 // destroys this object when it's destroyed itself (vfr)
491 d.layout_ = new LayoutBox(*this);
492 d.stack_widget_->addWidget(d.layout_);
493 d.layout_->move(0,0);
495 // extracts the toolbars from the backend
496 Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
497 Toolbars::Infos::iterator end = guiApp->toolbars().end();
498 for (; cit != end; ++cit)
499 d.toolbars_[cit->name] = new GuiToolbar(*cit, *this);
503 void GuiView::initToolbars()
505 // extracts the toolbars from the backend
506 Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
507 Toolbars::Infos::iterator end = guiApp->toolbars().end();
508 for (; cit != end; ++cit) {
509 GuiToolbar * tb = toolbar(cit->name);
512 int const visibility = guiApp->toolbars().defaultVisibility(cit->name);
514 tb->setVisible(false);
515 tb->setVisibility(visibility);
517 if (visibility & Toolbars::TOP) {
519 addToolBarBreak(Qt::TopToolBarArea);
520 addToolBar(Qt::TopToolBarArea, tb);
523 if (visibility & Toolbars::BOTTOM) {
524 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
525 #if (QT_VERSION >= 0x040202)
526 addToolBarBreak(Qt::BottomToolBarArea);
528 addToolBar(Qt::BottomToolBarArea, tb);
531 if (visibility & Toolbars::LEFT) {
532 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
533 #if (QT_VERSION >= 0x040202)
534 addToolBarBreak(Qt::LeftToolBarArea);
536 addToolBar(Qt::LeftToolBarArea, tb);
539 if (visibility & Toolbars::RIGHT) {
540 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
541 #if (QT_VERSION >= 0x040202)
542 addToolBarBreak(Qt::RightToolBarArea);
544 addToolBar(Qt::RightToolBarArea, tb);
547 if (visibility & Toolbars::ON)
548 tb->setVisible(true);
553 TocModels & GuiView::tocModels()
555 return d.toc_models_;
559 void GuiView::setFocus()
561 LYXERR(Debug::DEBUG, "GuiView::setFocus()" << this);
562 // Make sure LyXFunc points to the correct view.
563 guiApp->setCurrentView(this);
564 QMainWindow::setFocus();
565 if (d.current_work_area_)
566 d.current_work_area_->setFocus();
570 QMenu * GuiView::createPopupMenu()
572 return d.toolBarPopup(this);
576 void GuiView::showEvent(QShowEvent * e)
578 LYXERR(Debug::GUI, "Passed Geometry "
579 << size().height() << "x" << size().width()
580 << "+" << pos().x() << "+" << pos().y());
582 if (d.splitter_->count() == 0)
583 // No work area, switch to the background widget.
586 QMainWindow::showEvent(e);
590 /** Destroy only all tabbed WorkAreas. Destruction of other WorkAreas
591 ** is responsibility of the container (e.g., dialog)
593 void GuiView::closeEvent(QCloseEvent * close_event)
595 LYXERR(Debug::DEBUG, "GuiView::closeEvent()");
600 // it can happen that this event arrives without selecting the view,
601 // e.g. when clicking the close button on a background window.
603 if (!closeWorkAreaAll()) {
605 close_event->ignore();
609 // Make sure that nothing will use this to be closed View.
610 guiApp->unregisterView(this);
612 if (isFullScreen()) {
613 // Switch off fullscreen before closing.
618 // Make sure the timer time out will not trigger a statusbar update.
619 d.statusbar_timer_.stop();
621 // Saving fullscreen requires additional tweaks in the toolbar code.
622 // It wouldn't also work under linux natively.
623 if (lyxrc.allow_geometry_session) {
624 // Save this window geometry and layout.
626 // Then the toolbar private states.
627 ToolbarMap::iterator end = d.toolbars_.end();
628 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
629 it->second->saveSession();
630 // Now take care of all other dialogs:
631 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
632 for (; it!= d.dialogs_.end(); ++it)
633 it->second->saveSession();
636 close_event->accept();
640 void GuiView::dragEnterEvent(QDragEnterEvent * event)
642 if (event->mimeData()->hasUrls())
644 /// \todo Ask lyx-devel is this is enough:
645 /// if (event->mimeData()->hasFormat("text/plain"))
646 /// event->acceptProposedAction();
650 void GuiView::dropEvent(QDropEvent * event)
652 QList<QUrl> files = event->mimeData()->urls();
656 LYXERR(Debug::GUI, "GuiView::dropEvent: got URLs!");
657 for (int i = 0; i != files.size(); ++i) {
658 string const file = os::internal_path(fromqstr(
659 files.at(i).toLocalFile()));
663 string const ext = support::getExtension(file);
664 vector<const Format *> found_formats;
666 // Find all formats that have the correct extension.
667 vector<const Format *> const & import_formats
668 = theConverters().importableFormats();
669 vector<const Format *>::const_iterator it = import_formats.begin();
670 for (; it != import_formats.end(); ++it)
671 if ((*it)->extension() == ext)
672 found_formats.push_back(*it);
675 if (found_formats.size() >= 1) {
676 if (found_formats.size() > 1) {
677 //FIXME: show a dialog to choose the correct importable format
679 "Multiple importable formats found, selecting first");
681 string const arg = found_formats[0]->name() + " " + file;
682 cmd = FuncRequest(LFUN_BUFFER_IMPORT, arg);
685 //FIXME: do we have to explicitly check whether it's a lyx file?
687 "No formats found, trying to open it as a lyx file");
688 cmd = FuncRequest(LFUN_FILE_OPEN, file);
691 // Asynchronously post the event. DropEvent usually come
692 // from the BufferView. But reloading a file might close
693 // the BufferView from within its own event handler.
694 guiApp->dispatchDelayed(cmd);
700 void GuiView::message(docstring const & str)
702 if (ForkedProcess::iAmAChild())
705 // call is moved to GUI-thread by GuiProgress
706 d.progress_->appendMessage(toqstr(str));
710 void GuiView::updateMessage(QString const & str)
712 statusBar()->showMessage(str);
713 d.statusbar_timer_.stop();
714 d.statusbar_timer_.start(3000);
718 void GuiView::smallSizedIcons()
720 setIconSize(QSize(d.smallIconSize, d.smallIconSize));
724 void GuiView::normalSizedIcons()
726 setIconSize(QSize(d.normalIconSize, d.normalIconSize));
730 void GuiView::bigSizedIcons()
732 setIconSize(QSize(d.bigIconSize, d.bigIconSize));
736 void GuiView::clearMessage()
741 d.statusbar_timer_.stop();
745 void GuiView::updateWindowTitle(GuiWorkArea * wa)
747 if (wa != d.current_work_area_)
749 setWindowTitle(qt_("LyX: ") + wa->windowTitle());
750 setWindowIconText(wa->windowIconText());
754 void GuiView::on_currentWorkAreaChanged(GuiWorkArea * wa)
757 disconnectBufferView();
758 connectBufferView(wa->bufferView());
759 connectBuffer(wa->bufferView().buffer());
760 d.current_work_area_ = wa;
761 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
762 this, SLOT(updateWindowTitle(GuiWorkArea *)));
763 updateWindowTitle(wa);
767 // The document settings needs to be reinitialised.
768 updateDialog("document", "");
770 // Buffer-dependent dialogs must be updated. This is done here because
771 // some dialogs require buffer()->text.
776 void GuiView::on_lastWorkAreaRemoved()
779 // We already are in a close event. Nothing more to do.
782 if (d.splitter_->count() > 1)
783 // We have a splitter so don't close anything.
786 // Reset and updates the dialogs.
787 d.toc_models_.reset(0);
788 updateDialog("document", "");
791 resetWindowTitleAndIconText();
793 if (lyxrc.open_buffers_in_tabs)
794 // Nothing more to do, the window should stay open.
797 if (guiApp->viewIds().size() > 1) {
803 // On Mac we also close the last window because the application stay
804 // resident in memory. On other platforms we don't close the last
805 // window because this would quit the application.
811 void GuiView::updateStatusBar()
813 // let the user see the explicit message
814 if (d.statusbar_timer_.isActive())
821 void GuiView::showMessage()
823 QString msg = toqstr(theGuiApp()->viewStatusMessage());
825 BufferView const * bv = currentBufferView();
827 msg = toqstr(bv->cursor().currentState());
829 msg = qt_("Welcome to LyX!");
831 statusBar()->showMessage(msg);
835 bool GuiView::event(QEvent * e)
839 // Useful debug code:
840 //case QEvent::ActivationChange:
841 //case QEvent::WindowDeactivate:
842 //case QEvent::Paint:
843 //case QEvent::Enter:
844 //case QEvent::Leave:
845 //case QEvent::HoverEnter:
846 //case QEvent::HoverLeave:
847 //case QEvent::HoverMove:
848 //case QEvent::StatusTip:
849 //case QEvent::DragEnter:
850 //case QEvent::DragLeave:
854 case QEvent::WindowActivate: {
855 GuiView * old_view = guiApp->currentView();
856 if (this == old_view) {
858 return QMainWindow::event(e);
860 if (old_view && old_view->currentBufferView()) {
861 // save current selection to the selection buffer to allow
862 // middle-button paste in this window.
863 cap::saveSelection(old_view->currentBufferView()->cursor());
865 guiApp->setCurrentView(this);
866 if (d.current_work_area_) {
867 BufferView & bv = d.current_work_area_->bufferView();
868 connectBufferView(bv);
869 connectBuffer(bv.buffer());
870 // The document structure, name and dialogs might have
871 // changed in another view.
873 // The document settings needs to be reinitialised.
874 updateDialog("document", "");
877 resetWindowTitleAndIconText();
880 return QMainWindow::event(e);
883 case QEvent::ShortcutOverride: {
886 #if (!defined Q_WS_X11) || (QT_VERSION >= 0x040500)
887 if (isFullScreen() && menuBar()->isHidden()) {
888 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
889 // FIXME: we should also try to detect special LyX shortcut such as
890 // Alt-P and Alt-M. Right now there is a hack in
891 // GuiWorkArea::processKeySym() that hides again the menubar for
893 if (ke->modifiers() & Qt::AltModifier && ke->key() != Qt::Key_Alt) {
895 return QMainWindow::event(e);
900 if (d.current_work_area_)
901 // Nothing special to do.
902 return QMainWindow::event(e);
904 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
905 // Let Qt handle menu access and the Tab keys to navigate keys to navigate
907 if (ke->modifiers() & Qt::AltModifier || ke->key() == Qt::Key_Tab
908 || ke->key() == Qt::Key_Backtab)
909 return QMainWindow::event(e);
911 // Allow processing of shortcuts that are allowed even when no Buffer
914 setKeySymbol(&sym, ke);
915 guiApp->processKeySym(sym, q_key_state(ke->modifiers()));
921 return QMainWindow::event(e);
925 void GuiView::resetWindowTitleAndIconText()
927 setWindowTitle(qt_("LyX"));
928 setWindowIconText(qt_("LyX"));
931 bool GuiView::focusNextPrevChild(bool /*next*/)
938 void GuiView::setBusy(bool busy)
940 if (d.current_work_area_) {
941 d.current_work_area_->setUpdatesEnabled(!busy);
943 d.current_work_area_->stopBlinkingCursor();
945 d.current_work_area_->startBlinkingCursor();
949 QApplication::setOverrideCursor(Qt::WaitCursor);
951 QApplication::restoreOverrideCursor();
955 GuiWorkArea * GuiView::workArea(Buffer & buffer)
957 if (currentWorkArea()
958 && ¤tWorkArea()->bufferView().buffer() == &buffer)
959 return (GuiWorkArea *) currentWorkArea();
960 if (TabWorkArea * twa = d.currentTabWorkArea())
961 return twa->workArea(buffer);
966 GuiWorkArea * GuiView::addWorkArea(Buffer & buffer)
968 // Automatically create a TabWorkArea if there are none yet.
969 TabWorkArea * tab_widget = d.splitter_->count()
970 ? d.currentTabWorkArea() : addTabWorkArea();
971 return tab_widget->addWorkArea(buffer, *this);
975 TabWorkArea * GuiView::addTabWorkArea()
977 TabWorkArea * twa = new TabWorkArea;
978 QObject::connect(twa, SIGNAL(currentWorkAreaChanged(GuiWorkArea *)),
979 this, SLOT(on_currentWorkAreaChanged(GuiWorkArea *)));
980 QObject::connect(twa, SIGNAL(lastWorkAreaRemoved()),
981 this, SLOT(on_lastWorkAreaRemoved()));
983 d.splitter_->addWidget(twa);
984 d.stack_widget_->setCurrentWidget(d.splitter_);
989 GuiWorkArea const * GuiView::currentWorkArea() const
991 return d.current_work_area_;
995 GuiWorkArea * GuiView::currentWorkArea()
997 return d.current_work_area_;
1001 GuiWorkArea const * GuiView::currentMainWorkArea() const
1003 if (d.currentTabWorkArea() == NULL)
1005 return d.currentTabWorkArea()->currentWorkArea();
1009 GuiWorkArea * GuiView::currentMainWorkArea()
1011 if (d.currentTabWorkArea() == NULL)
1013 return d.currentTabWorkArea()->currentWorkArea();
1017 void GuiView::setCurrentWorkArea(GuiWorkArea * wa)
1019 LYXERR(Debug::DEBUG, "Setting current wa: " << wa << endl);
1021 d.current_work_area_ = NULL;
1025 GuiWorkArea * old_gwa = theGuiApp()->currentView()->currentWorkArea();
1029 if (currentBufferView())
1030 cap::saveSelection(currentBufferView()->cursor());
1032 theGuiApp()->setCurrentView(this);
1033 d.current_work_area_ = wa;
1034 for (int i = 0; i != d.splitter_->count(); ++i) {
1035 if (d.tabWorkArea(i)->setCurrentWorkArea(wa)) {
1036 //if (d.current_main_work_area_)
1037 // d.current_main_work_area_->setFrameStyle(QFrame::NoFrame);
1038 d.current_main_work_area_ = wa;
1039 //d.current_main_work_area_->setFrameStyle(QFrame::Box | QFrame::Plain);
1040 //d.current_main_work_area_->setLineWidth(2);
1041 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() << ", Current main wa: " << currentMainWorkArea());
1045 LYXERR(Debug::DEBUG, "This is not a tabbed wa");
1046 on_currentWorkAreaChanged(wa);
1047 BufferView & bv = wa->bufferView();
1048 bv.cursor().fixIfBroken();
1050 wa->setUpdatesEnabled(true);
1051 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() << ", Current main wa: " << currentMainWorkArea());
1055 void GuiView::removeWorkArea(GuiWorkArea * wa)
1057 LASSERT(wa, return);
1058 if (wa == d.current_work_area_) {
1060 disconnectBufferView();
1061 d.current_work_area_ = 0;
1062 d.current_main_work_area_ = 0;
1065 bool found_twa = false;
1066 for (int i = 0; i != d.splitter_->count(); ++i) {
1067 TabWorkArea * twa = d.tabWorkArea(i);
1068 if (twa->removeWorkArea(wa)) {
1069 // Found in this tab group, and deleted the GuiWorkArea.
1071 if (twa->count() != 0) {
1072 if (d.current_work_area_ == 0)
1073 // This means that we are closing the current GuiWorkArea, so
1074 // switch to the next GuiWorkArea in the found TabWorkArea.
1075 setCurrentWorkArea(twa->currentWorkArea());
1077 // No more WorkAreas in this tab group, so delete it.
1084 // It is not a tabbed work area (i.e., the search work area), so it
1085 // should be deleted by other means.
1086 LASSERT(found_twa, /* */);
1088 if (d.current_work_area_ == 0) {
1089 if (d.splitter_->count() != 0) {
1090 TabWorkArea * twa = d.currentTabWorkArea();
1091 setCurrentWorkArea(twa->currentWorkArea());
1093 // No more work areas, switch to the background widget.
1094 setCurrentWorkArea(0);
1100 LayoutBox * GuiView::getLayoutDialog() const
1106 void GuiView::updateLayoutList()
1109 d.layout_->updateContents(false);
1113 void GuiView::updateToolbars()
1115 ToolbarMap::iterator end = d.toolbars_.end();
1116 if (d.current_work_area_) {
1118 d.current_work_area_->bufferView().cursor().inMathed();
1120 lyx::getStatus(FuncRequest(LFUN_LAYOUT_TABULAR)).enabled();
1122 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).enabled() &&
1123 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).onoff(true);
1124 bool const mathmacrotemplate =
1125 lyx::getStatus(FuncRequest(LFUN_IN_MATHMACROTEMPLATE)).enabled();
1127 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1128 it->second->update(math, table, review, mathmacrotemplate);
1130 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1131 it->second->update(false, false, false, false);
1135 void GuiView::setBuffer(Buffer * newBuffer)
1137 LYXERR(Debug::DEBUG, "Setting buffer: " << newBuffer << endl);
1138 LASSERT(newBuffer, return);
1141 GuiWorkArea * wa = workArea(*newBuffer);
1143 newBuffer->masterBuffer()->updateLabels();
1144 wa = addWorkArea(*newBuffer);
1146 //Disconnect the old buffer...there's no new one.
1149 connectBuffer(*newBuffer);
1150 connectBufferView(wa->bufferView());
1151 setCurrentWorkArea(wa);
1157 void GuiView::connectBuffer(Buffer & buf)
1159 buf.setGuiDelegate(this);
1163 void GuiView::disconnectBuffer()
1165 if (d.current_work_area_)
1166 d.current_work_area_->bufferView().buffer().setGuiDelegate(0);
1170 void GuiView::connectBufferView(BufferView & bv)
1172 bv.setGuiDelegate(this);
1176 void GuiView::disconnectBufferView()
1178 if (d.current_work_area_)
1179 d.current_work_area_->bufferView().setGuiDelegate(0);
1183 void GuiView::errors(string const & error_type, bool from_master)
1185 ErrorList & el = from_master ?
1186 documentBufferView()->buffer().masterBuffer()->errorList(error_type)
1187 : documentBufferView()->buffer().errorList(error_type);
1188 string data = error_type;
1190 data = "from_master|" + error_type;
1192 showDialog("errorlist", data);
1196 void GuiView::updateTocItem(string const & type, DocIterator const & dit)
1198 d.toc_models_.updateItem(toqstr(type), dit);
1202 void GuiView::structureChanged()
1204 d.toc_models_.reset(documentBufferView());
1205 // Navigator needs more than a simple update in this case. It needs to be
1207 updateDialog("toc", "");
1211 void GuiView::updateDialog(string const & name, string const & data)
1213 if (!isDialogVisible(name))
1216 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
1217 if (it == d.dialogs_.end())
1220 Dialog * const dialog = it->second.get();
1221 if (dialog->isVisibleView())
1222 dialog->initialiseParams(data);
1226 BufferView * GuiView::documentBufferView()
1228 return currentMainWorkArea()
1229 ? ¤tMainWorkArea()->bufferView()
1234 BufferView const * GuiView::documentBufferView() const
1236 return currentMainWorkArea()
1237 ? ¤tMainWorkArea()->bufferView()
1242 BufferView * GuiView::currentBufferView()
1244 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1248 BufferView const * GuiView::currentBufferView() const
1250 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1254 static docstring saveAndDestroyBuffer(Buffer * buffer, FileName const & fname)
1257 FileName const tmp_ret = FileName::tempName("lyxauto");
1258 if (!tmp_ret.empty()) {
1259 if (buffer->writeFile(tmp_ret))
1260 failed = !tmp_ret.moveTo(fname);
1263 // failed to write/rename tmp_ret so try writing direct
1264 failed = buffer->writeFile(fname);
1268 ? _("Automatic save failed!")
1269 : _("Automatic save done.");
1273 void GuiView::autoSave()
1275 LYXERR(Debug::INFO, "Running autoSave()");
1277 Buffer * buffer = documentBufferView()
1278 ? &documentBufferView()->buffer() : 0;
1282 #if (QT_VERSION >= 0x040400)
1283 QFuture<docstring> f = QtConcurrent::run(saveAndDestroyBuffer, buffer->clone(),
1284 buffer->getAutosaveFilename());
1285 d.autosave_watcher_.setFuture(f);
1292 void GuiView::resetAutosaveTimers()
1295 d.autosave_timeout_.restart();
1299 bool GuiView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1302 Buffer * buf = currentBufferView()
1303 ? ¤tBufferView()->buffer() : 0;
1304 Buffer * doc_buffer = documentBufferView()
1305 ? &(documentBufferView()->buffer()) : 0;
1307 // Check whether we need a buffer
1308 if (!lyxaction.funcHasFlag(cmd.action, LyXAction::NoBuffer) && !buf) {
1309 // no, exit directly
1310 flag.message(from_utf8(N_("Command not allowed with"
1311 "out any document open")));
1312 flag.setEnabled(false);
1316 if (cmd.origin == FuncRequest::TOC) {
1317 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
1319 if (toc->getStatus(documentBufferView()->cursor(), cmd, fs))
1322 flag.setEnabled(false);
1326 switch(cmd.action) {
1327 case LFUN_BUFFER_IMPORT:
1330 case LFUN_MASTER_BUFFER_UPDATE:
1331 case LFUN_MASTER_BUFFER_VIEW:
1332 enable = doc_buffer && doc_buffer->parent() != 0
1333 && !d.preview_watcher_.isRunning();
1336 case LFUN_BUFFER_UPDATE:
1337 case LFUN_BUFFER_VIEW: {
1338 if (!doc_buffer || d.preview_watcher_.isRunning()) {
1342 string format = to_utf8(cmd.argument());
1343 if (cmd.argument().empty())
1344 format = doc_buffer->getDefaultOutputFormat();
1345 enable = doc_buffer->isExportableFormat(format);
1349 case LFUN_BUFFER_RELOAD:
1350 enable = doc_buffer && !doc_buffer->isUnnamed()
1351 && doc_buffer->fileName().exists()
1352 && (!doc_buffer->isClean()
1353 || doc_buffer->isExternallyModified(Buffer::timestamp_method));
1356 case LFUN_BUFFER_CHILD_OPEN:
1357 enable = doc_buffer;
1360 case LFUN_BUFFER_WRITE:
1361 enable = doc_buffer && (doc_buffer->isUnnamed() || !doc_buffer->isClean());
1364 //FIXME: This LFUN should be moved to GuiApplication.
1365 case LFUN_BUFFER_WRITE_ALL: {
1366 // We enable the command only if there are some modified buffers
1367 Buffer * first = theBufferList().first();
1372 // We cannot use a for loop as the buffer list is a cycle.
1374 if (!b->isClean()) {
1378 b = theBufferList().next(b);
1379 } while (b != first);
1383 case LFUN_BUFFER_WRITE_AS:
1384 enable = doc_buffer;
1387 case LFUN_BUFFER_CLOSE:
1388 enable = doc_buffer;
1391 case LFUN_BUFFER_CLOSE_ALL:
1392 enable = theBufferList().last() != theBufferList().first();
1395 case LFUN_SPLIT_VIEW:
1396 if (cmd.getArg(0) == "vertical")
1397 enable = doc_buffer && (d.splitter_->count() == 1 ||
1398 d.splitter_->orientation() == Qt::Vertical);
1400 enable = doc_buffer && (d.splitter_->count() == 1 ||
1401 d.splitter_->orientation() == Qt::Horizontal);
1404 case LFUN_CLOSE_TAB_GROUP:
1405 enable = d.currentTabWorkArea();
1408 case LFUN_TOOLBAR_TOGGLE:
1409 if (GuiToolbar * t = toolbar(cmd.getArg(0)))
1410 flag.setOnOff(t->isVisible());
1413 case LFUN_DROP_LAYOUTS_CHOICE:
1417 case LFUN_UI_TOGGLE:
1418 flag.setOnOff(isFullScreen());
1421 case LFUN_DIALOG_DISCONNECT_INSET:
1424 case LFUN_DIALOG_HIDE:
1425 // FIXME: should we check if the dialog is shown?
1428 case LFUN_DIALOG_TOGGLE:
1429 flag.setOnOff(isDialogVisible(cmd.getArg(0)));
1430 // fall through to set "enable"
1431 case LFUN_DIALOG_SHOW: {
1432 string const name = cmd.getArg(0);
1434 enable = name == "aboutlyx"
1435 || name == "file" //FIXME: should be removed.
1437 || name == "texinfo"
1438 || name == "compare";
1439 else if (name == "print")
1440 enable = doc_buffer->isExportable("dvi")
1441 && lyxrc.print_command != "none";
1442 else if (name == "character" || name == "symbols") {
1443 if (!buf || buf->isReadonly()
1444 || !currentBufferView()->cursor().inTexted())
1447 // FIXME we should consider passthru
1449 Inset const & in = currentBufferView()->cursor().inset();
1450 enable = !in.getLayout().isPassThru();
1453 else if (name == "latexlog")
1454 enable = FileName(doc_buffer->logName()).isReadableFile();
1455 else if (name == "spellchecker")
1456 enable = theSpellChecker() && !doc_buffer->isReadonly();
1457 else if (name == "vclog")
1458 enable = doc_buffer->lyxvc().inUse();
1462 case LFUN_DIALOG_UPDATE: {
1463 string const name = cmd.getArg(0);
1465 enable = name == "prefs";
1469 case LFUN_COMMAND_EXECUTE:
1471 case LFUN_MENU_OPEN:
1472 // Nothing to check.
1475 case LFUN_COMPLETION_INLINE:
1476 if (!d.current_work_area_
1477 || !d.current_work_area_->completer().inlinePossible(
1478 currentBufferView()->cursor()))
1482 case LFUN_COMPLETION_POPUP:
1483 if (!d.current_work_area_
1484 || !d.current_work_area_->completer().popupPossible(
1485 currentBufferView()->cursor()))
1489 case LFUN_COMPLETION_COMPLETE:
1490 if (!d.current_work_area_
1491 || !d.current_work_area_->completer().inlinePossible(
1492 currentBufferView()->cursor()))
1496 case LFUN_COMPLETION_ACCEPT:
1497 if (!d.current_work_area_
1498 || (!d.current_work_area_->completer().popupVisible()
1499 && !d.current_work_area_->completer().inlineVisible()
1500 && !d.current_work_area_->completer().completionAvailable()))
1504 case LFUN_COMPLETION_CANCEL:
1505 if (!d.current_work_area_
1506 || (!d.current_work_area_->completer().popupVisible()
1507 && !d.current_work_area_->completer().inlineVisible()))
1511 case LFUN_BUFFER_ZOOM_OUT:
1512 enable = doc_buffer && lyxrc.zoom > 10;
1515 case LFUN_BUFFER_ZOOM_IN:
1516 enable = doc_buffer;
1519 case LFUN_BUFFER_NEXT:
1520 case LFUN_BUFFER_PREVIOUS:
1521 // FIXME: should we check is there is an previous or next buffer?
1523 case LFUN_BUFFER_SWITCH:
1524 // toggle on the current buffer, but do not toggle off
1525 // the other ones (is that a good idea?)
1527 && to_utf8(cmd.argument()) == doc_buffer->absFileName())
1528 flag.setOnOff(true);
1531 case LFUN_VC_REGISTER:
1532 enable = doc_buffer && !doc_buffer->lyxvc().inUse();
1534 case LFUN_VC_CHECK_IN:
1535 enable = doc_buffer && doc_buffer->lyxvc().checkInEnabled();
1537 case LFUN_VC_CHECK_OUT:
1538 enable = doc_buffer && doc_buffer->lyxvc().checkOutEnabled();
1540 case LFUN_VC_LOCKING_TOGGLE:
1541 enable = doc_buffer && !doc_buffer->isReadonly()
1542 && doc_buffer->lyxvc().lockingToggleEnabled();
1543 flag.setOnOff(enable && !doc_buffer->lyxvc().locker().empty());
1545 case LFUN_VC_REVERT:
1546 enable = doc_buffer && doc_buffer->lyxvc().inUse();
1548 case LFUN_VC_UNDO_LAST:
1549 enable = doc_buffer && doc_buffer->lyxvc().undoLastEnabled();
1551 case LFUN_VC_REPO_UPDATE:
1552 enable = doc_buffer && doc_buffer->lyxvc().inUse();
1554 case LFUN_VC_COMMAND: {
1555 if (cmd.argument().empty())
1557 if (!doc_buffer && contains(cmd.getArg(0), 'D'))
1562 case LFUN_SERVER_GOTO_FILE_ROW:
1570 flag.setEnabled(false);
1576 static FileName selectTemplateFile()
1578 FileDialog dlg(qt_("Select template file"));
1579 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1580 dlg.setButton1(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
1582 FileDialog::Result result = dlg.open(toqstr(lyxrc.template_path),
1583 QStringList(qt_("LyX Documents (*.lyx)")));
1585 if (result.first == FileDialog::Later)
1587 if (result.second.isEmpty())
1589 return FileName(fromqstr(result.second));
1593 Buffer * GuiView::loadDocument(FileName const & filename, bool tolastfiles)
1597 Buffer * newBuffer = checkAndLoadLyXFile(filename);
1600 message(_("Document not loaded."));
1605 setBuffer(newBuffer);
1607 // scroll to the position when the file was last closed
1608 if (lyxrc.use_lastfilepos) {
1609 LastFilePosSection::FilePos filepos =
1610 theSession().lastFilePos().load(filename);
1611 documentBufferView()->moveToPosition(filepos.pit, filepos.pos, 0, 0);
1615 theSession().lastFiles().add(filename);
1622 void GuiView::openDocument(string const & fname)
1624 string initpath = lyxrc.document_path;
1626 if (documentBufferView()) {
1627 string const trypath = documentBufferView()->buffer().filePath();
1628 // If directory is writeable, use this as default.
1629 if (FileName(trypath).isDirWritable())
1635 if (fname.empty()) {
1636 FileDialog dlg(qt_("Select document to open"), LFUN_FILE_OPEN);
1637 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1638 dlg.setButton2(qt_("Examples|#E#e"),
1639 toqstr(addPath(package().system_support().absFilename(), "examples")));
1641 QStringList filter(qt_("LyX Documents (*.lyx)"));
1642 filter << qt_("LyX-1.3.x Documents (*.lyx13)")
1643 << qt_("LyX-1.4.x Documents (*.lyx14)")
1644 << qt_("LyX-1.5.x Documents (*.lyx15)")
1645 << qt_("LyX-1.6.x Documents (*.lyx16)");
1646 FileDialog::Result result =
1647 dlg.open(toqstr(initpath), filter);
1649 if (result.first == FileDialog::Later)
1652 filename = fromqstr(result.second);
1654 // check selected filename
1655 if (filename.empty()) {
1656 message(_("Canceled."));
1662 // get absolute path of file and add ".lyx" to the filename if
1664 FileName const fullname =
1665 fileSearch(string(), filename, "lyx", support::may_not_exist);
1666 if (!fullname.empty())
1667 filename = fullname.absFilename();
1669 if (!fullname.onlyPath().isDirectory()) {
1670 Alert::warning(_("Invalid filename"),
1671 bformat(_("The directory in the given path\n%1$s\ndoes not exist."),
1672 from_utf8(fullname.absFilename())));
1675 // if the file doesn't exist, let the user create one
1676 if (!fullname.exists()) {
1677 // the user specifically chose this name. Believe him.
1678 Buffer * const b = newFile(filename, string(), true);
1684 docstring const disp_fn = makeDisplayPath(filename);
1685 message(bformat(_("Opening document %1$s..."), disp_fn));
1688 Buffer * buf = loadDocument(fullname);
1690 buf->updateLabels();
1692 buf->errors("Parse");
1693 str2 = bformat(_("Document %1$s opened."), disp_fn);
1694 if (buf->lyxvc().inUse())
1695 str2 += " " + from_utf8(buf->lyxvc().versionString()) +
1696 " " + _("Version control detected.");
1698 str2 = bformat(_("Could not open document %1$s"), disp_fn);
1703 // FIXME: clean that
1704 static bool import(GuiView * lv, FileName const & filename,
1705 string const & format, ErrorList & errorList)
1707 FileName const lyxfile(support::changeExtension(filename.absFilename(), ".lyx"));
1709 string loader_format;
1710 vector<string> loaders = theConverters().loaders();
1711 if (find(loaders.begin(), loaders.end(), format) == loaders.end()) {
1712 for (vector<string>::const_iterator it = loaders.begin();
1713 it != loaders.end(); ++it) {
1714 if (!theConverters().isReachable(format, *it))
1717 string const tofile =
1718 support::changeExtension(filename.absFilename(),
1719 formats.extension(*it));
1720 if (!theConverters().convert(0, filename, FileName(tofile),
1721 filename, format, *it, errorList))
1723 loader_format = *it;
1726 if (loader_format.empty()) {
1727 frontend::Alert::error(_("Couldn't import file"),
1728 bformat(_("No information for importing the format %1$s."),
1729 formats.prettyName(format)));
1733 loader_format = format;
1735 if (loader_format == "lyx") {
1736 Buffer * buf = lv->loadDocument(lyxfile);
1739 buf->updateLabels();
1741 buf->errors("Parse");
1743 Buffer * const b = newFile(lyxfile.absFilename(), string(), true);
1747 bool as_paragraphs = loader_format == "textparagraph";
1748 string filename2 = (loader_format == format) ? filename.absFilename()
1749 : support::changeExtension(filename.absFilename(),
1750 formats.extension(loader_format));
1751 lv->currentBufferView()->insertPlaintextFile(FileName(filename2),
1753 guiApp->setCurrentView(lv);
1754 lyx::dispatch(FuncRequest(LFUN_MARK_OFF));
1761 void GuiView::importDocument(string const & argument)
1764 string filename = split(argument, format, ' ');
1766 LYXERR(Debug::INFO, format << " file: " << filename);
1768 // need user interaction
1769 if (filename.empty()) {
1770 string initpath = lyxrc.document_path;
1771 if (documentBufferView()) {
1772 string const trypath = documentBufferView()->buffer().filePath();
1773 // If directory is writeable, use this as default.
1774 if (FileName(trypath).isDirWritable())
1778 docstring const text = bformat(_("Select %1$s file to import"),
1779 formats.prettyName(format));
1781 FileDialog dlg(toqstr(text), LFUN_BUFFER_IMPORT);
1782 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1783 dlg.setButton2(qt_("Examples|#E#e"),
1784 toqstr(addPath(package().system_support().absFilename(), "examples")));
1786 docstring filter = formats.prettyName(format);
1789 filter += from_utf8(formats.extension(format));
1792 FileDialog::Result result =
1793 dlg.open(toqstr(initpath), fileFilters(toqstr(filter)));
1795 if (result.first == FileDialog::Later)
1798 filename = fromqstr(result.second);
1800 // check selected filename
1801 if (filename.empty())
1802 message(_("Canceled."));
1805 if (filename.empty())
1808 // get absolute path of file
1809 FileName const fullname(support::makeAbsPath(filename));
1811 FileName const lyxfile(support::changeExtension(fullname.absFilename(), ".lyx"));
1813 // Check if the document already is open
1814 Buffer * buf = theBufferList().getBuffer(lyxfile);
1817 if (!closeBuffer()) {
1818 message(_("Canceled."));
1823 docstring const displaypath = makeDisplayPath(lyxfile.absFilename(), 30);
1825 // if the file exists already, and we didn't do
1826 // -i lyx thefile.lyx, warn
1827 if (lyxfile.exists() && fullname != lyxfile) {
1829 docstring text = bformat(_("The document %1$s already exists.\n\n"
1830 "Do you want to overwrite that document?"), displaypath);
1831 int const ret = Alert::prompt(_("Overwrite document?"),
1832 text, 0, 1, _("&Overwrite"), _("&Cancel"));
1835 message(_("Canceled."));
1840 message(bformat(_("Importing %1$s..."), displaypath));
1841 ErrorList errorList;
1842 if (import(this, fullname, format, errorList))
1843 message(_("imported."));
1845 message(_("file not imported!"));
1847 // FIXME (Abdel 12/08/06): Is there a need to display the error list here?
1851 void GuiView::newDocument(string const & filename, bool from_template)
1853 FileName initpath(lyxrc.document_path);
1854 if (documentBufferView()) {
1855 FileName const trypath(documentBufferView()->buffer().filePath());
1856 // If directory is writeable, use this as default.
1857 if (trypath.isDirWritable())
1861 string templatefile;
1862 if (from_template) {
1863 templatefile = selectTemplateFile().absFilename();
1864 if (templatefile.empty())
1869 if (filename.empty())
1870 b = newUnnamedFile(initpath, to_utf8(_("newfile")), templatefile);
1872 b = newFile(filename, templatefile, true);
1877 // If no new document could be created, it is unsure
1878 // whether there is a valid BufferView.
1879 if (currentBufferView())
1880 // Ensure the cursor is correctly positioned on screen.
1881 currentBufferView()->showCursor();
1885 void GuiView::insertLyXFile(docstring const & fname)
1887 BufferView * bv = documentBufferView();
1892 FileName filename(to_utf8(fname));
1894 if (!filename.empty()) {
1895 bv->insertLyXFile(filename);
1899 // Launch a file browser
1901 string initpath = lyxrc.document_path;
1902 string const trypath = bv->buffer().filePath();
1903 // If directory is writeable, use this as default.
1904 if (FileName(trypath).isDirWritable())
1908 FileDialog dlg(qt_("Select LyX document to insert"), LFUN_FILE_INSERT);
1909 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1910 dlg.setButton2(qt_("Examples|#E#e"),
1911 toqstr(addPath(package().system_support().absFilename(),
1914 FileDialog::Result result = dlg.open(toqstr(initpath),
1915 QStringList(qt_("LyX Documents (*.lyx)")));
1917 if (result.first == FileDialog::Later)
1921 filename.set(fromqstr(result.second));
1923 // check selected filename
1924 if (filename.empty()) {
1925 // emit message signal.
1926 message(_("Canceled."));
1930 bv->insertLyXFile(filename);
1934 void GuiView::insertPlaintextFile(docstring const & fname,
1937 BufferView * bv = documentBufferView();
1941 if (!fname.empty() && !FileName::isAbsolute(to_utf8(fname))) {
1942 message(_("Absolute filename expected."));
1947 FileName filename(to_utf8(fname));
1949 if (!filename.empty()) {
1950 bv->insertPlaintextFile(filename, asParagraph);
1954 FileDialog dlg(qt_("Select file to insert"), (asParagraph ?
1955 LFUN_FILE_INSERT_PLAINTEXT_PARA : LFUN_FILE_INSERT_PLAINTEXT));
1957 FileDialog::Result result = dlg.open(toqstr(bv->buffer().filePath()),
1958 QStringList(qt_("All Files (*)")));
1960 if (result.first == FileDialog::Later)
1964 filename.set(fromqstr(result.second));
1966 // check selected filename
1967 if (filename.empty()) {
1968 // emit message signal.
1969 message(_("Canceled."));
1973 bv->insertPlaintextFile(filename, asParagraph);
1977 bool GuiView::renameBuffer(Buffer & b, docstring const & newname)
1979 FileName fname = b.fileName();
1980 FileName const oldname = fname;
1982 if (!newname.empty()) {
1984 fname = support::makeAbsPath(to_utf8(newname), oldname.onlyPath().absFilename());
1986 // Switch to this Buffer.
1989 // No argument? Ask user through dialog.
1991 FileDialog dlg(qt_("Choose a filename to save document as"),
1992 LFUN_BUFFER_WRITE_AS);
1993 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1994 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
1996 if (!isLyXFilename(fname.absFilename()))
1997 fname.changeExtension(".lyx");
1999 FileDialog::Result result =
2000 dlg.save(toqstr(fname.onlyPath().absFilename()),
2001 QStringList(qt_("LyX Documents (*.lyx)")),
2002 toqstr(fname.onlyFileName()));
2004 if (result.first == FileDialog::Later)
2007 fname.set(fromqstr(result.second));
2012 if (!isLyXFilename(fname.absFilename()))
2013 fname.changeExtension(".lyx");
2016 if (FileName(fname).exists()) {
2017 docstring const file = makeDisplayPath(fname.absFilename(), 30);
2018 docstring text = bformat(_("The document %1$s already "
2019 "exists.\n\nDo you want to "
2020 "overwrite that document?"),
2022 int const ret = Alert::prompt(_("Overwrite document?"),
2023 text, 0, 2, _("&Overwrite"), _("&Rename"), _("&Cancel"));
2026 case 1: return renameBuffer(b, docstring());
2027 case 2: return false;
2031 FileName oldauto = b.getAutosaveFilename();
2033 // Ok, change the name of the buffer
2034 b.setFileName(fname.absFilename());
2036 bool unnamed = b.isUnnamed();
2037 b.setUnnamed(false);
2038 b.saveCheckSum(fname);
2040 // bring the autosave file with us, just in case.
2041 b.moveAutosaveFile(oldauto);
2043 if (!saveBuffer(b)) {
2044 oldauto = b.getAutosaveFilename();
2045 b.setFileName(oldname.absFilename());
2046 b.setUnnamed(unnamed);
2047 b.saveCheckSum(oldname);
2048 b.moveAutosaveFile(oldauto);
2056 bool GuiView::saveBuffer(Buffer & b)
2058 if (workArea(b) && workArea(b)->inDialogMode())
2062 return renameBuffer(b, docstring());
2065 theSession().lastFiles().add(b.fileName());
2069 // Switch to this Buffer.
2072 // FIXME: we don't tell the user *WHY* the save failed !!
2073 docstring const file = makeDisplayPath(b.absFileName(), 30);
2074 docstring text = bformat(_("The document %1$s could not be saved.\n\n"
2075 "Do you want to rename the document and "
2076 "try again?"), file);
2077 int const ret = Alert::prompt(_("Rename and save?"),
2078 text, 0, 2, _("&Rename"), _("&Retry"), _("&Cancel"));
2081 if (!renameBuffer(b, docstring()))
2090 return saveBuffer(b);
2094 bool GuiView::hideWorkArea(GuiWorkArea * wa)
2096 return closeWorkArea(wa, false);
2100 bool GuiView::closeWorkArea(GuiWorkArea * wa)
2102 Buffer & buf = wa->bufferView().buffer();
2103 return closeWorkArea(wa, !buf.parent());
2107 bool GuiView::closeBuffer()
2109 GuiWorkArea * wa = currentMainWorkArea();
2110 Buffer & buf = wa->bufferView().buffer();
2111 return wa && closeWorkArea(wa, !buf.parent());
2115 void GuiView::writeSession() const {
2116 GuiWorkArea const * active_wa = currentMainWorkArea();
2117 for (int i = 0; i < d.splitter_->count(); ++i) {
2118 TabWorkArea * twa = d.tabWorkArea(i);
2119 for (int j = 0; j < twa->count(); ++j) {
2120 GuiWorkArea * wa = static_cast<GuiWorkArea *>(twa->widget(j));
2121 Buffer & buf = wa->bufferView().buffer();
2122 theSession().lastOpened().add(buf.fileName(), wa == active_wa);
2128 bool GuiView::closeBufferAll()
2130 // Close the workareas in all other views
2131 QList<int> const ids = guiApp->viewIds();
2132 for (int i = 0; i != ids.size(); ++i) {
2133 if (id_ != ids[i] && !guiApp->view(ids[i]).closeWorkAreaAll())
2137 // Close our own workareas
2138 if (!closeWorkAreaAll())
2141 // Now close the hidden buffers. We prevent hidden buffers from being
2142 // dirty, so we can just close them.
2143 theBufferList().closeAll();
2148 bool GuiView::closeWorkAreaAll()
2150 setCurrentWorkArea(currentMainWorkArea());
2152 // We might be in a situation that there is still a tabWorkArea, but
2153 // there are no tabs anymore. This can happen when we get here after a
2154 // TabWorkArea::lastWorkAreaRemoved() signal. Therefore we count how
2155 // many TabWorkArea's have no documents anymore.
2158 // We have to call count() each time, because it can happen that
2159 // more than one splitter will disappear in one iteration (bug 5998).
2160 for (; d.splitter_->count() > empty_twa; ) {
2161 TabWorkArea * twa = d.tabWorkArea(empty_twa);
2163 if (twa->count() == 0)
2166 setCurrentWorkArea(twa->currentWorkArea());
2167 if (!closeTabWorkArea(twa))
2175 bool GuiView::closeWorkArea(GuiWorkArea * wa, bool close_buffer)
2180 Buffer & buf = wa->bufferView().buffer();
2183 return closeBuffer(buf);
2185 if (!inMultiTabs(wa))
2186 if (!saveBufferIfNeeded(buf, true))
2194 bool GuiView::closeBuffer(Buffer & buf)
2196 // If we are in a close_event all children will be closed in some time,
2197 // so no need to do it here. This will ensure that the children end up
2198 // in the session file in the correct order. If we close the master
2199 // buffer, we can close or release the child buffers here too.
2201 vector<Buffer *> clist = buf.getChildren(false);
2202 for (vector<Buffer *>::const_iterator it = clist.begin();
2203 it != clist.end(); ++it) {
2204 // If a child is dirty, do not close
2205 // without user intervention
2206 //FIXME: should we look in other tabworkareas?
2207 Buffer * child_buf = *it;
2208 GuiWorkArea * child_wa = workArea(*child_buf);
2210 if (!closeWorkArea(child_wa, true))
2213 theBufferList().releaseChild(&buf, child_buf);
2216 // goto bookmark to update bookmark pit.
2217 //FIXME: we should update only the bookmarks related to this buffer!
2218 LYXERR(Debug::DEBUG, "GuiView::closeBuffer()");
2219 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
2220 theLyXFunc().gotoBookmark(i+1, false, false);
2222 if (saveBufferIfNeeded(buf, false)) {
2223 theBufferList().release(&buf);
2230 bool GuiView::closeTabWorkArea(TabWorkArea * twa)
2232 while (twa == d.currentTabWorkArea()) {
2233 twa->setCurrentIndex(twa->count()-1);
2235 GuiWorkArea * wa = twa->currentWorkArea();
2236 Buffer & b = wa->bufferView().buffer();
2238 // We only want to close the buffer if the same buffer is not visible
2239 // in another view, and if this is not a child and if we are closing
2240 // a view (not a tabgroup).
2241 bool const close_buffer =
2242 !inMultiViews(wa) && !b.parent() && closing_;
2244 if (!closeWorkArea(wa, close_buffer))
2251 bool GuiView::saveBufferIfNeeded(Buffer & buf, bool hiding)
2253 if (buf.isClean() || buf.paragraphs().empty())
2256 // Switch to this Buffer.
2261 if (buf.isUnnamed())
2262 file = from_utf8(buf.fileName().onlyFileName());
2264 file = buf.fileName().displayName(30);
2266 // Bring this window to top before asking questions.
2271 if (hiding && buf.isUnnamed()) {
2272 docstring const text = bformat(_("The document %1$s has not been "
2273 "saved yet.\n\nDo you want to save "
2274 "the document?"), file);
2275 ret = Alert::prompt(_("Save new document?"),
2276 text, 0, 1, _("&Save"), _("&Cancel"));
2280 docstring const text = bformat(_("The document %1$s has unsaved changes."
2281 "\n\nDo you want to save the document or discard the changes?"), file);
2282 ret = Alert::prompt(_("Save changed document?"),
2283 text, 0, 2, _("&Save"), _("&Discard"), _("&Cancel"));
2288 if (!saveBuffer(buf))
2292 // if we crash after this we could
2293 // have no autosave file but I guess
2294 // this is really improbable (Jug)
2295 buf.removeAutosaveFile();
2297 // revert all changes
2298 buf.loadLyXFile(buf.fileName());
2308 bool GuiView::inMultiTabs(GuiWorkArea * wa)
2310 Buffer & buf = wa->bufferView().buffer();
2312 for (int i = 0; i != d.splitter_->count(); ++i) {
2313 GuiWorkArea * wa_ = d.tabWorkArea(i)->workArea(buf);
2314 if (wa_ && wa_ != wa)
2317 return inMultiViews(wa);
2321 bool GuiView::inMultiViews(GuiWorkArea * wa)
2323 QList<int> const ids = guiApp->viewIds();
2324 Buffer & buf = wa->bufferView().buffer();
2327 for (int i = 0; i != ids.size() && found_twa <= 1; ++i) {
2331 if (guiApp->view(ids[i]).workArea(buf))
2338 void GuiView::gotoNextOrPreviousBuffer(NextOrPrevious np)
2340 Buffer * const curbuf = documentBufferView()
2341 ? &documentBufferView()->buffer() : 0;
2342 Buffer * nextbuf = curbuf;
2344 if (np == NEXTBUFFER)
2345 nextbuf = theBufferList().next(nextbuf);
2347 nextbuf = theBufferList().previous(nextbuf);
2348 if (nextbuf == curbuf)
2354 if (workArea(*nextbuf))
2361 /// make sure the document is saved
2362 static bool ensureBufferClean(Buffer * buffer)
2364 LASSERT(buffer, return false);
2365 if (buffer->isClean() && !buffer->isUnnamed())
2368 docstring const file = buffer->fileName().displayName(30);
2371 if (!buffer->isUnnamed()) {
2372 text = bformat(_("The document %1$s has unsaved "
2373 "changes.\n\nDo you want to save "
2374 "the document?"), file);
2375 title = _("Save changed document?");
2378 text = bformat(_("The document %1$s has not been "
2379 "saved yet.\n\nDo you want to save "
2380 "the document?"), file);
2381 title = _("Save new document?");
2383 int const ret = Alert::prompt(title, text, 0, 1, _("&Save"), _("&Cancel"));
2386 dispatch(FuncRequest(LFUN_BUFFER_WRITE));
2388 return buffer->isClean() && !buffer->isUnnamed();
2392 void GuiView::reloadBuffer()
2394 Buffer * buf = &documentBufferView()->buffer();
2399 void GuiView::reloadBuffer(Buffer * buf)
2401 FileName filename = buf->fileName();
2402 Buffer const * master = buf->masterBuffer();
2403 bool const is_child = master != buf;
2404 // The user has already confirmed that the changes, if any, should
2405 // be discarded. So we just release the Buffer and don't call closeBuffer();
2406 theBufferList().release(buf);
2407 buf = loadDocument(filename);
2408 docstring const disp_fn = makeDisplayPath(filename.absFilename());
2411 // re-allocate master if necessary
2412 if (is_child && theBufferList().isLoaded(master)
2413 && buf->masterBuffer() != master)
2414 buf->setParent(master);
2415 buf->updateLabels();
2417 buf->errors("Parse");
2418 str = bformat(_("Document %1$s reloaded."), disp_fn);
2420 str = bformat(_("Could not reload document %1$s"), disp_fn);
2426 void GuiView::checkExternallyModifiedBuffers()
2428 BufferList::iterator bit = theBufferList().begin();
2429 BufferList::iterator const bend = theBufferList().end();
2430 for (; bit != bend; ++bit) {
2431 if ((*bit)->isExternallyModified(Buffer::checksum_method)) {
2432 docstring text = bformat(_("Document \n%1$s\n has been externally modified."
2433 " Reload now? Any local changes will be lost."),
2434 from_utf8((*bit)->absFileName()));
2435 int const ret = Alert::prompt(_("Reload externally changed document?"),
2436 text, 0, 1, _("&Reload"), _("&Cancel"));
2444 void GuiView::dispatchVC(FuncRequest const & cmd)
2446 Buffer * buffer = documentBufferView()
2447 ? &(documentBufferView()->buffer()) : 0;
2449 switch (cmd.action) {
2450 case LFUN_VC_REGISTER:
2451 if (!buffer || !ensureBufferClean(buffer))
2453 if (!buffer->lyxvc().inUse()) {
2454 if (buffer->lyxvc().registrer())
2459 case LFUN_VC_CHECK_IN:
2460 if (!buffer || !ensureBufferClean(buffer))
2462 if (buffer->lyxvc().inUse() && !buffer->isReadonly()) {
2463 message(from_utf8(buffer->lyxvc().checkIn()));
2468 case LFUN_VC_CHECK_OUT:
2469 if (!buffer || !ensureBufferClean(buffer))
2471 if (buffer->lyxvc().inUse()) {
2472 message(from_utf8(buffer->lyxvc().checkOut()));
2477 case LFUN_VC_LOCKING_TOGGLE:
2478 LASSERT(buffer, return);
2479 if (!ensureBufferClean(buffer) || buffer->isReadonly())
2481 if (buffer->lyxvc().inUse()) {
2482 string res = buffer->lyxvc().lockingToggle();
2484 frontend::Alert::error(_("Revision control error."),
2485 _("Error when setting the locking property."));
2487 message(from_utf8(res));
2493 case LFUN_VC_REVERT:
2494 LASSERT(buffer, return);
2495 buffer->lyxvc().revert();
2499 case LFUN_VC_UNDO_LAST:
2500 LASSERT(buffer, return);
2501 buffer->lyxvc().undoLast();
2505 case LFUN_VC_REPO_UPDATE:
2506 LASSERT(buffer, return);
2507 if (ensureBufferClean(buffer)) {
2508 string res = buffer->lyxvc().repoUpdate();
2509 message(from_utf8(res));
2510 checkExternallyModifiedBuffers();
2514 case LFUN_VC_COMMAND: {
2515 string flag = cmd.getArg(0);
2516 if (buffer && contains(flag, 'R') && !ensureBufferClean(buffer))
2519 if (contains(flag, 'M')) {
2520 if (!Alert::askForText(message, _("LyX VC: Log Message")))
2523 string path = cmd.getArg(1);
2524 if (contains(path, "$$p") && buffer)
2525 path = subst(path, "$$p", buffer->filePath());
2526 LYXERR(Debug::LYXVC, "Directory: " << path);
2528 if (!pp.isReadableDirectory()) {
2529 lyxerr << _("Directory is not accessible.") << endl;
2532 support::PathChanger p(pp);
2534 string command = cmd.getArg(2);
2535 if (command.empty())
2538 command = subst(command, "$$i", buffer->absFileName());
2539 command = subst(command, "$$p", buffer->filePath());
2541 command = subst(command, "$$m", to_utf8(message));
2542 LYXERR(Debug::LYXVC, "Command: " << command);
2544 one.startscript(Systemcall::Wait, command);
2548 if (contains(flag, 'I'))
2549 buffer->markDirty();
2550 if (contains(flag, 'R'))
2561 void GuiView::openChildDocument(string const & fname)
2563 LASSERT(documentBufferView(), return);
2564 Buffer & buffer = documentBufferView()->buffer();
2565 FileName const filename = support::makeAbsPath(fname, buffer.filePath());
2566 documentBufferView()->saveBookmark(false);
2568 bool parsed = false;
2569 if (theBufferList().exists(filename)) {
2570 child = theBufferList().getBuffer(filename);
2572 message(bformat(_("Opening child document %1$s..."),
2573 makeDisplayPath(filename.absFilename())));
2574 child = loadDocument(filename, false);
2580 // Set the parent name of the child document.
2581 // This makes insertion of citations and references in the child work,
2582 // when the target is in the parent or another child document.
2583 child->setParent(&buffer);
2584 child->masterBuffer()->updateLabels();
2587 child->errors("Parse");
2591 bool GuiView::goToFileRow(string const & argument)
2595 istringstream is(argument);
2596 is >> file_name >> row;
2597 file_name = os::internal_path(file_name);
2599 string const abstmp = package().temp_dir().absFilename();
2600 string const realtmp = package().temp_dir().realPath();
2601 // We have to use os::path_prefix_is() here, instead of
2602 // simply prefixIs(), because the file name comes from
2603 // an external application and may need case adjustment.
2604 if (os::path_prefix_is(file_name, abstmp, os::CASE_ADJUSTED)
2605 || os::path_prefix_is(file_name, realtmp, os::CASE_ADJUSTED)) {
2606 // Needed by inverse dvi search. If it is a file
2607 // in tmpdir, call the apropriated function.
2608 // If tmpdir is a symlink, we may have the real
2609 // path passed back, so we correct for that.
2610 if (!prefixIs(file_name, abstmp))
2611 file_name = subst(file_name, realtmp, abstmp);
2612 buf = theBufferList().getBufferFromTmp(file_name);
2614 // Must replace extension of the file to be .lyx
2615 // and get full path
2616 FileName const s = fileSearch(string(),
2617 support::changeExtension(file_name, ".lyx"), "lyx");
2618 // Either change buffer or load the file
2619 if (theBufferList().exists(s))
2620 buf = theBufferList().getBuffer(s);
2621 else if (s.exists()) {
2622 buf = loadDocument(s);
2623 buf->updateLabels();
2624 buf->errors("Parse");
2627 _("File does not exist: %1$s"),
2628 makeDisplayPath(file_name)));
2633 documentBufferView()->setCursorFromRow(row);
2638 static docstring exportAndDestroy(Buffer * buffer, string const & format)
2640 bool const success = buffer->doExport(format, true);
2643 ? bformat(_("Successful export to format: %1$s"), from_utf8(format))
2644 : bformat(_("Error exporting to format: %1$s"), from_utf8(format));
2648 static docstring previewAndDestroy(Buffer * buffer, string const & format)
2650 bool const success = buffer->preview(format);
2653 ? bformat(_("Successful preview of format: %1$s"), from_utf8(format))
2654 : bformat(_("Error previewing format: %1$s"), from_utf8(format));
2658 bool GuiView::dispatch(FuncRequest const & cmd)
2660 BufferView * bv = currentBufferView();
2661 // By default we won't need any update.
2663 bv->cursor().updateFlags(Update::None);
2665 Buffer * doc_buffer = documentBufferView()
2666 ? &(documentBufferView()->buffer()) : 0;
2668 bool dispatched = true;
2670 if (cmd.origin == FuncRequest::TOC) {
2671 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
2672 toc->doDispatch(bv->cursor(), cmd);
2676 string const argument = to_utf8(cmd.argument());
2678 switch(cmd.action) {
2679 case LFUN_BUFFER_CHILD_OPEN:
2680 openChildDocument(to_utf8(cmd.argument()));
2683 case LFUN_BUFFER_IMPORT:
2684 importDocument(to_utf8(cmd.argument()));
2687 case LFUN_BUFFER_EXPORT: {
2690 if (cmd.argument() == "custom") {
2691 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "sendto"));
2694 if (doc_buffer->doExport(argument, false)) {
2695 message(bformat(_("Error exporting to format: %1$s."),
2701 case LFUN_BUFFER_UPDATE: {
2704 string format = argument;
2705 if (argument.empty())
2706 format = doc_buffer->getDefaultOutputFormat();
2707 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
2708 ProgressInterface::instance()->clearMessages();
2709 QString time = QTime::currentTime().toString(Qt::SystemLocaleShortDate);
2710 ProgressInterface::instance()->appendMessage(time + ": Exporting ...\n");
2711 QFuture<docstring> f = QtConcurrent::run(exportAndDestroy,
2712 doc_buffer->clone(), format);
2713 d.setPreviewFuture(f);
2715 doc_buffer->doExport(format, true);
2719 case LFUN_BUFFER_VIEW: {
2722 string format = argument;
2723 if (argument.empty())
2724 format = doc_buffer->getDefaultOutputFormat();
2725 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
2726 ProgressInterface::instance()->clearMessages();
2727 QString time = QTime::currentTime().toString(Qt::SystemLocaleShortDate);
2728 ProgressInterface::instance()->appendMessage(time + ": Previewing ...\n");
2729 QFuture<docstring> f = QtConcurrent::run(previewAndDestroy,
2730 doc_buffer->clone(), format);
2731 d.setPreviewFuture(f);
2733 doc_buffer->preview(format);
2737 case LFUN_MASTER_BUFFER_UPDATE: {
2740 string format = argument;
2741 Buffer const * master = doc_buffer->masterBuffer();
2742 if (argument.empty())
2743 format = master->getDefaultOutputFormat();
2744 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
2745 QFuture<docstring> f = QtConcurrent::run(exportAndDestroy,
2746 master->clone(), format);
2747 d.setPreviewFuture(f);
2749 master->doExport(format, true);
2753 case LFUN_MASTER_BUFFER_VIEW: {
2754 string format = argument;
2755 Buffer const * master = doc_buffer->masterBuffer();
2756 if (argument.empty())
2757 format = master->getDefaultOutputFormat();
2758 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
2759 QFuture<docstring> f = QtConcurrent::run(previewAndDestroy,
2760 master->clone(), format);
2761 d.setPreviewFuture(f);
2763 master->preview(format);
2767 case LFUN_BUFFER_SWITCH:
2768 if (FileName::isAbsolute(to_utf8(cmd.argument()))) {
2770 theBufferList().getBuffer(FileName(to_utf8(cmd.argument())));
2774 message(_("Document not loaded"));
2778 case LFUN_BUFFER_NEXT:
2779 gotoNextOrPreviousBuffer(NEXTBUFFER);
2782 case LFUN_BUFFER_PREVIOUS:
2783 gotoNextOrPreviousBuffer(PREVBUFFER);
2786 case LFUN_COMMAND_EXECUTE: {
2787 bool const show_it = cmd.argument() != "off";
2788 // FIXME: this is a hack, "minibuffer" should not be
2790 if (GuiToolbar * t = toolbar("minibuffer")) {
2791 t->setVisible(show_it);
2792 if (show_it && t->commandBuffer())
2793 t->commandBuffer()->setFocus();
2797 case LFUN_DROP_LAYOUTS_CHOICE:
2798 d.layout_->showPopup();
2801 case LFUN_MENU_OPEN:
2802 if (QMenu * menu = guiApp->menus().menu(toqstr(cmd.argument()), *this))
2803 menu->exec(QCursor::pos());
2806 case LFUN_FILE_INSERT:
2807 insertLyXFile(cmd.argument());
2809 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
2810 insertPlaintextFile(cmd.argument(), true);
2813 case LFUN_FILE_INSERT_PLAINTEXT:
2814 insertPlaintextFile(cmd.argument(), false);
2817 case LFUN_BUFFER_RELOAD: {
2818 LASSERT(doc_buffer, break);
2819 docstring const file = makeDisplayPath(doc_buffer->absFileName(), 20);
2820 docstring text = bformat(_("Any changes will be lost. Are you sure "
2821 "you want to revert to the saved version of the document %1$s?"), file);
2822 int const ret = Alert::prompt(_("Revert to saved document?"),
2823 text, 1, 1, _("&Revert"), _("&Cancel"));
2826 doc_buffer->markClean();
2832 case LFUN_BUFFER_WRITE:
2833 LASSERT(doc_buffer, break);
2834 saveBuffer(*doc_buffer);
2837 case LFUN_BUFFER_WRITE_AS:
2838 LASSERT(doc_buffer, break);
2839 renameBuffer(*doc_buffer, cmd.argument());
2842 case LFUN_BUFFER_WRITE_ALL: {
2843 Buffer * first = theBufferList().first();
2846 message(_("Saving all documents..."));
2847 // We cannot use a for loop as the buffer list cycles.
2850 if (!b->isClean()) {
2852 LYXERR(Debug::ACTION, "Saved " << b->absFileName());
2854 b = theBufferList().next(b);
2855 } while (b != first);
2856 message(_("All documents saved."));
2860 case LFUN_BUFFER_CLOSE:
2864 case LFUN_BUFFER_CLOSE_ALL:
2868 case LFUN_TOOLBAR_TOGGLE: {
2869 string const name = cmd.getArg(0);
2870 if (GuiToolbar * t = toolbar(name))
2875 case LFUN_DIALOG_UPDATE: {
2876 string const name = to_utf8(cmd.argument());
2877 if (currentBufferView()) {
2878 Inset * inset = currentBufferView()->editedInset(name);
2879 // Can only update a dialog connected to an existing inset
2882 // FIXME: get rid of this indirection; GuiView ask the inset
2883 // if he is kind enough to update itself...
2884 FuncRequest fr(LFUN_INSET_DIALOG_UPDATE, cmd.argument());
2885 inset->dispatch(currentBufferView()->cursor(), fr);
2886 } else if (name == "paragraph") {
2887 lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
2888 } else if (name == "prefs" || name == "document") {
2889 updateDialog(name, string());
2894 case LFUN_DIALOG_TOGGLE: {
2895 if (isDialogVisible(cmd.getArg(0)))
2896 dispatch(FuncRequest(LFUN_DIALOG_HIDE, cmd.argument()));
2898 dispatch(FuncRequest(LFUN_DIALOG_SHOW, cmd.argument()));
2902 case LFUN_DIALOG_DISCONNECT_INSET:
2903 disconnectDialog(to_utf8(cmd.argument()));
2906 case LFUN_DIALOG_HIDE: {
2907 guiApp->hideDialogs(to_utf8(cmd.argument()), 0);
2911 case LFUN_DIALOG_SHOW: {
2912 string const name = cmd.getArg(0);
2913 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
2915 if (name == "character") {
2916 data = freefont2string();
2918 showDialog("character", data);
2919 } else if (name == "latexlog") {
2920 Buffer::LogType type;
2921 string const logfile = doc_buffer->logName(&type);
2923 case Buffer::latexlog:
2926 case Buffer::buildlog:
2930 data += Lexer::quoteString(logfile);
2931 showDialog("log", data);
2932 } else if (name == "vclog") {
2933 string const data = "vc " +
2934 Lexer::quoteString(doc_buffer->lyxvc().getLogFile());
2935 showDialog("log", data);
2936 } else if (name == "symbols") {
2937 data = bv->cursor().getEncoding()->name();
2939 showDialog("symbols", data);
2941 } else if (name == "prefs" && isFullScreen()) {
2942 FuncRequest fr(LFUN_INSET_INSERT, "fullscreen");
2944 showDialog("prefs", data);
2946 showDialog(name, data);
2951 message(cmd.argument());
2954 case LFUN_UI_TOGGLE:
2956 // Make sure the keyboard focus stays in the work area.
2960 case LFUN_SPLIT_VIEW: {
2961 LASSERT(doc_buffer, break);
2962 string const orientation = cmd.getArg(0);
2963 d.splitter_->setOrientation(orientation == "vertical"
2964 ? Qt::Vertical : Qt::Horizontal);
2965 TabWorkArea * twa = addTabWorkArea();
2966 GuiWorkArea * wa = twa->addWorkArea(*doc_buffer, *this);
2967 setCurrentWorkArea(wa);
2970 case LFUN_CLOSE_TAB_GROUP:
2971 if (TabWorkArea * twa = d.currentTabWorkArea()) {
2972 closeTabWorkArea(twa);
2973 d.current_work_area_ = 0;
2974 twa = d.currentTabWorkArea();
2975 // Switch to the next GuiWorkArea in the found TabWorkArea.
2977 // Make sure the work area is up to date.
2978 setCurrentWorkArea(twa->currentWorkArea());
2980 setCurrentWorkArea(0);
2985 case LFUN_COMPLETION_INLINE:
2986 if (d.current_work_area_)
2987 d.current_work_area_->completer().showInline();
2990 case LFUN_COMPLETION_POPUP:
2991 if (d.current_work_area_)
2992 d.current_work_area_->completer().showPopup();
2996 case LFUN_COMPLETION_COMPLETE:
2997 if (d.current_work_area_)
2998 d.current_work_area_->completer().tab();
3001 case LFUN_COMPLETION_CANCEL:
3002 if (d.current_work_area_) {
3003 if (d.current_work_area_->completer().popupVisible())
3004 d.current_work_area_->completer().hidePopup();
3006 d.current_work_area_->completer().hideInline();
3010 case LFUN_COMPLETION_ACCEPT:
3011 if (d.current_work_area_)
3012 d.current_work_area_->completer().activate();
3015 case LFUN_BUFFER_ZOOM_IN:
3016 case LFUN_BUFFER_ZOOM_OUT:
3017 if (cmd.argument().empty()) {
3018 if (cmd.action == LFUN_BUFFER_ZOOM_IN)
3023 lyxrc.zoom += convert<int>(cmd.argument());
3025 if (lyxrc.zoom < 10)
3028 // The global QPixmapCache is used in GuiPainter to cache text
3029 // painting so we must reset it.
3030 QPixmapCache::clear();
3031 guiApp->fontLoader().update();
3032 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
3035 case LFUN_VC_REGISTER:
3036 case LFUN_VC_CHECK_IN:
3037 case LFUN_VC_CHECK_OUT:
3038 case LFUN_VC_REPO_UPDATE:
3039 case LFUN_VC_LOCKING_TOGGLE:
3040 case LFUN_VC_REVERT:
3041 case LFUN_VC_UNDO_LAST:
3042 case LFUN_VC_COMMAND:
3046 case LFUN_SERVER_GOTO_FILE_ROW:
3047 goToFileRow(to_utf8(cmd.argument()));
3055 // Part of automatic menu appearance feature.
3056 if (isFullScreen()) {
3057 if (menuBar()->isVisible() && lyxrc.full_screen_menubar)
3059 if (statusBar()->isVisible())
3060 statusBar()->hide();
3067 void GuiView::lfunUiToggle(FuncRequest const & cmd)
3069 string const arg = cmd.getArg(0);
3070 if (arg == "scrollbar") {
3071 // hide() is of no help
3072 if (d.current_work_area_->verticalScrollBarPolicy() ==
3073 Qt::ScrollBarAlwaysOff)
3075 d.current_work_area_->setVerticalScrollBarPolicy(
3076 Qt::ScrollBarAsNeeded);
3078 d.current_work_area_->setVerticalScrollBarPolicy(
3079 Qt::ScrollBarAlwaysOff);
3082 if (arg == "statusbar") {
3083 statusBar()->setVisible(!statusBar()->isVisible());
3086 if (arg == "menubar") {
3087 menuBar()->setVisible(!menuBar()->isVisible());
3090 #if QT_VERSION >= 0x040300
3091 if (arg == "frame") {
3093 getContentsMargins(&l, &t, &r, &b);
3094 //are the frames in default state?
3095 d.current_work_area_->setFrameStyle(QFrame::NoFrame);
3097 setContentsMargins(-2, -2, -2, -2);
3099 setContentsMargins(0, 0, 0, 0);
3104 if (arg == "fullscreen") {
3109 message(bformat("LFUN_UI_TOGGLE " + _("%1$s unknown command!"), from_utf8(arg)));
3113 void GuiView::toggleFullScreen()
3115 if (isFullScreen()) {
3116 for (int i = 0; i != d.splitter_->count(); ++i)
3117 d.tabWorkArea(i)->setFullScreen(false);
3118 #if QT_VERSION >= 0x040300
3119 setContentsMargins(0, 0, 0, 0);
3121 setWindowState(windowState() ^ Qt::WindowFullScreen);
3124 statusBar()->show();
3127 hideDialogs("prefs", 0);
3128 for (int i = 0; i != d.splitter_->count(); ++i)
3129 d.tabWorkArea(i)->setFullScreen(true);
3130 #if QT_VERSION >= 0x040300
3131 setContentsMargins(-2, -2, -2, -2);
3134 setWindowState(windowState() ^ Qt::WindowFullScreen);
3135 statusBar()->hide();
3136 if (lyxrc.full_screen_menubar)
3138 if (lyxrc.full_screen_toolbars) {
3139 ToolbarMap::iterator end = d.toolbars_.end();
3140 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
3145 // give dialogs like the TOC a chance to adapt
3150 Buffer const * GuiView::updateInset(Inset const * inset)
3152 if (!d.current_work_area_)
3156 d.current_work_area_->scheduleRedraw();
3158 return &d.current_work_area_->bufferView().buffer();
3162 void GuiView::restartCursor()
3164 /* When we move around, or type, it's nice to be able to see
3165 * the cursor immediately after the keypress.
3167 if (d.current_work_area_)
3168 d.current_work_area_->startBlinkingCursor();
3170 // Take this occasion to update the other GUI elements.
3176 void GuiView::updateCompletion(Cursor & cur, bool start, bool keep)
3178 if (d.current_work_area_)
3179 d.current_work_area_->completer().updateVisibility(cur, start, keep);
3184 // This list should be kept in sync with the list of insets in
3185 // src/insets/Inset.cpp. I.e., if a dialog goes with an inset, the
3186 // dialog should have the same name as the inset.
3187 // Changes should be also recorded in LFUN_DIALOG_SHOW doxygen
3188 // docs in LyXAction.cpp.
3190 char const * const dialognames[] = {
3191 "aboutlyx", "bibitem", "bibtex", "box", "branch", "changes", "character",
3192 "citation", "compare", "document", "errorlist", "ert", "external", "file",
3193 "findreplace", "findreplaceadv", "float", "graphics", "href", "include",
3194 "index", "index_print", "info", "listings", "label", "log", "mathdelimiter",
3195 "mathmatrix", "mathspace", "nomenclature", "nomencl_print", "note",
3196 "paragraph", "phantom", "prefs", "print", "ref", "sendto", "space",
3197 "spellchecker", "symbols", "tabular", "tabularcreate", "thesaurus", "texinfo",
3198 "toc", "view-source", "vspace", "wrap"};
3200 char const * const * const end_dialognames =
3201 dialognames + (sizeof(dialognames) / sizeof(char *));
3205 cmpCStr(char const * name) : name_(name) {}
3206 bool operator()(char const * other) {
3207 return strcmp(other, name_) == 0;
3214 bool isValidName(string const & name)
3216 return find_if(dialognames, end_dialognames,
3217 cmpCStr(name.c_str())) != end_dialognames;
3223 void GuiView::resetDialogs()
3225 // Make sure that no LFUN uses any LyXView.
3226 guiApp->setCurrentView(0);
3229 constructToolbars();
3230 guiApp->menus().fillMenuBar(menuBar(), this, false);
3231 d.layout_->updateContents(true);
3232 // Now update controls with current buffer.
3233 guiApp->setCurrentView(this);
3239 Dialog * GuiView::findOrBuild(string const & name, bool hide_it)
3241 if (!isValidName(name))
3244 map<string, DialogPtr>::iterator it = d.dialogs_.find(name);
3246 if (it != d.dialogs_.end()) {
3248 it->second->hideView();
3249 return it->second.get();
3252 Dialog * dialog = build(name);
3253 d.dialogs_[name].reset(dialog);
3254 if (lyxrc.allow_geometry_session)
3255 dialog->restoreSession();
3262 void GuiView::showDialog(string const & name, string const & data,
3265 triggerShowDialog(toqstr(name), toqstr(data), inset);
3269 void GuiView::doShowDialog(QString const & qname, QString const & qdata,
3275 const string name = fromqstr(qname);
3276 const string data = fromqstr(qdata);
3280 Dialog * dialog = findOrBuild(name, false);
3282 dialog->showData(data);
3283 if (inset && currentBufferView())
3284 currentBufferView()->editInset(name, inset);
3287 catch (ExceptionMessage const & ex) {
3295 bool GuiView::isDialogVisible(string const & name) const
3297 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3298 if (it == d.dialogs_.end())
3300 return it->second.get()->isVisibleView() && !it->second.get()->isClosing();
3304 void GuiView::hideDialog(string const & name, Inset * inset)
3306 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3307 if (it == d.dialogs_.end())
3310 if (inset && currentBufferView()
3311 && inset != currentBufferView()->editedInset(name))
3314 Dialog * const dialog = it->second.get();
3315 if (dialog->isVisibleView())
3317 if (currentBufferView())
3318 currentBufferView()->editInset(name, 0);
3322 void GuiView::disconnectDialog(string const & name)
3324 if (!isValidName(name))
3326 if (currentBufferView())
3327 currentBufferView()->editInset(name, 0);
3331 void GuiView::hideAll() const
3333 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
3334 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3336 for(; it != end; ++it)
3337 it->second->hideView();
3341 void GuiView::updateDialogs()
3343 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
3344 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3346 for(; it != end; ++it) {
3347 Dialog * dialog = it->second.get();
3348 if (dialog && dialog->isVisibleView())
3349 dialog->checkStatus();
3356 // will be replaced by a proper factory...
3357 Dialog * createGuiAbout(GuiView & lv);
3358 Dialog * createGuiBibitem(GuiView & lv);
3359 Dialog * createGuiBibtex(GuiView & lv);
3360 Dialog * createGuiBox(GuiView & lv);
3361 Dialog * createGuiBranch(GuiView & lv);
3362 Dialog * createGuiChanges(GuiView & lv);
3363 Dialog * createGuiCharacter(GuiView & lv);
3364 Dialog * createGuiCitation(GuiView & lv);
3365 Dialog * createGuiCompare(GuiView & lv);
3366 Dialog * createGuiDelimiter(GuiView & lv);
3367 Dialog * createGuiDocument(GuiView & lv);
3368 Dialog * createGuiErrorList(GuiView & lv);
3369 Dialog * createGuiERT(GuiView & lv);
3370 Dialog * createGuiExternal(GuiView & lv);
3371 Dialog * createGuiFloat(GuiView & lv);
3372 Dialog * createGuiGraphics(GuiView & lv);
3373 Dialog * createGuiInclude(GuiView & lv);
3374 Dialog * createGuiIndex(GuiView & lv);
3375 Dialog * createGuiInfo(GuiView & lv);
3376 Dialog * createGuiLabel(GuiView & lv);
3377 Dialog * createGuiListings(GuiView & lv);
3378 Dialog * createGuiLog(GuiView & lv);
3379 Dialog * createGuiMathHSpace(GuiView & lv);
3380 Dialog * createGuiMathMatrix(GuiView & lv);
3381 Dialog * createGuiNomenclature(GuiView & lv);
3382 Dialog * createGuiNote(GuiView & lv);
3383 Dialog * createGuiParagraph(GuiView & lv);
3384 Dialog * createGuiPhantom(GuiView & lv);
3385 Dialog * createGuiPreferences(GuiView & lv);
3386 Dialog * createGuiPrint(GuiView & lv);
3387 Dialog * createGuiPrintindex(GuiView & lv);
3388 Dialog * createGuiPrintNomencl(GuiView & lv);
3389 Dialog * createGuiRef(GuiView & lv);
3390 Dialog * createGuiSearch(GuiView & lv);
3391 Dialog * createGuiSearchAdv(GuiView & lv);
3392 Dialog * createGuiSendTo(GuiView & lv);
3393 Dialog * createGuiShowFile(GuiView & lv);
3394 Dialog * createGuiSpellchecker(GuiView & lv);
3395 Dialog * createGuiSymbols(GuiView & lv);
3396 Dialog * createGuiTabularCreate(GuiView & lv);
3397 Dialog * createGuiTabular(GuiView & lv);
3398 Dialog * createGuiTexInfo(GuiView & lv);
3399 Dialog * createGuiTextHSpace(GuiView & lv);
3400 Dialog * createGuiToc(GuiView & lv);
3401 Dialog * createGuiThesaurus(GuiView & lv);
3402 Dialog * createGuiHyperlink(GuiView & lv);
3403 Dialog * createGuiVSpace(GuiView & lv);
3404 Dialog * createGuiViewSource(GuiView & lv);
3405 Dialog * createGuiWrap(GuiView & lv);
3409 Dialog * GuiView::build(string const & name)
3411 LASSERT(isValidName(name), return 0);
3413 if (name == "aboutlyx")
3414 return createGuiAbout(*this);
3415 if (name == "bibitem")
3416 return createGuiBibitem(*this);
3417 if (name == "bibtex")
3418 return createGuiBibtex(*this);
3420 return createGuiBox(*this);
3421 if (name == "branch")
3422 return createGuiBranch(*this);
3423 if (name == "changes")
3424 return createGuiChanges(*this);
3425 if (name == "character")
3426 return createGuiCharacter(*this);
3427 if (name == "citation")
3428 return createGuiCitation(*this);
3429 if (name == "compare")
3430 return createGuiCompare(*this);
3431 if (name == "document")
3432 return createGuiDocument(*this);
3433 if (name == "errorlist")
3434 return createGuiErrorList(*this);
3436 return createGuiERT(*this);
3437 if (name == "external")
3438 return createGuiExternal(*this);
3440 return createGuiShowFile(*this);
3441 if (name == "findreplace")
3442 return createGuiSearch(*this);
3443 if (name == "findreplaceadv")
3444 return createGuiSearchAdv(*this);
3445 if (name == "float")
3446 return createGuiFloat(*this);
3447 if (name == "graphics")
3448 return createGuiGraphics(*this);
3450 return createGuiHyperlink(*this);
3451 if (name == "include")
3452 return createGuiInclude(*this);
3453 if (name == "index")
3454 return createGuiIndex(*this);
3455 if (name == "index_print")
3456 return createGuiPrintindex(*this);
3458 return createGuiInfo(*this);
3459 if (name == "label")
3460 return createGuiLabel(*this);
3461 if (name == "listings")
3462 return createGuiListings(*this);
3464 return createGuiLog(*this);
3465 if (name == "mathdelimiter")
3466 return createGuiDelimiter(*this);
3467 if (name == "mathspace")
3468 return createGuiMathHSpace(*this);
3469 if (name == "mathmatrix")
3470 return createGuiMathMatrix(*this);
3471 if (name == "nomenclature")
3472 return createGuiNomenclature(*this);
3473 if (name == "nomencl_print")
3474 return createGuiPrintNomencl(*this);
3476 return createGuiNote(*this);
3477 if (name == "paragraph")
3478 return createGuiParagraph(*this);
3479 if (name == "phantom")
3480 return createGuiPhantom(*this);
3481 if (name == "prefs")
3482 return createGuiPreferences(*this);
3483 if (name == "print")
3484 return createGuiPrint(*this);
3486 return createGuiRef(*this);
3487 if (name == "sendto")
3488 return createGuiSendTo(*this);
3489 if (name == "space")
3490 return createGuiTextHSpace(*this);
3491 if (name == "spellchecker")
3492 return createGuiSpellchecker(*this);
3493 if (name == "symbols")
3494 return createGuiSymbols(*this);
3495 if (name == "tabular")
3496 return createGuiTabular(*this);
3497 if (name == "tabularcreate")
3498 return createGuiTabularCreate(*this);
3499 if (name == "texinfo")
3500 return createGuiTexInfo(*this);
3501 if (name == "thesaurus")
3502 return createGuiThesaurus(*this);
3504 return createGuiToc(*this);
3505 if (name == "view-source")
3506 return createGuiViewSource(*this);
3507 if (name == "vspace")
3508 return createGuiVSpace(*this);
3510 return createGuiWrap(*this);
3516 } // namespace frontend
3519 #include "moc_GuiView.cpp"