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 #if (QT_VERSION >= 0x040400)
368 connect(&d.autosave_watcher_, SIGNAL(finished()), this,
369 SLOT(threadFinished()));
372 connect(this, SIGNAL(triggerShowDialog(QString const &, QString const &, Inset *)),
373 SLOT(doShowDialog(QString const &, QString const &, Inset *)));
375 // Forbid too small unresizable window because it can happen
376 // with some window manager under X11.
377 setMinimumSize(300, 200);
379 if (lyxrc.allow_geometry_session) {
380 // Now take care of session management.
385 // no session handling, default to a sane size.
386 setGeometry(50, 50, 690, 510);
389 // clear session data if any.
391 settings.remove("views");
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 == "progress"
1439 || name == "compare";
1440 else if (name == "print")
1441 enable = doc_buffer->isExportable("dvi")
1442 && lyxrc.print_command != "none";
1443 else if (name == "character" || name == "symbols") {
1444 if (!buf || buf->isReadonly()
1445 || !currentBufferView()->cursor().inTexted())
1448 // FIXME we should consider passthru
1450 Inset const & in = currentBufferView()->cursor().inset();
1451 enable = !in.getLayout().isPassThru();
1454 else if (name == "latexlog")
1455 enable = FileName(doc_buffer->logName()).isReadableFile();
1456 else if (name == "spellchecker")
1457 enable = theSpellChecker() && !doc_buffer->isReadonly();
1458 else if (name == "vclog")
1459 enable = doc_buffer->lyxvc().inUse();
1463 case LFUN_DIALOG_UPDATE: {
1464 string const name = cmd.getArg(0);
1466 enable = name == "prefs";
1470 case LFUN_COMMAND_EXECUTE:
1472 case LFUN_MENU_OPEN:
1473 // Nothing to check.
1476 case LFUN_COMPLETION_INLINE:
1477 if (!d.current_work_area_
1478 || !d.current_work_area_->completer().inlinePossible(
1479 currentBufferView()->cursor()))
1483 case LFUN_COMPLETION_POPUP:
1484 if (!d.current_work_area_
1485 || !d.current_work_area_->completer().popupPossible(
1486 currentBufferView()->cursor()))
1490 case LFUN_COMPLETION_COMPLETE:
1491 if (!d.current_work_area_
1492 || !d.current_work_area_->completer().inlinePossible(
1493 currentBufferView()->cursor()))
1497 case LFUN_COMPLETION_ACCEPT:
1498 if (!d.current_work_area_
1499 || (!d.current_work_area_->completer().popupVisible()
1500 && !d.current_work_area_->completer().inlineVisible()
1501 && !d.current_work_area_->completer().completionAvailable()))
1505 case LFUN_COMPLETION_CANCEL:
1506 if (!d.current_work_area_
1507 || (!d.current_work_area_->completer().popupVisible()
1508 && !d.current_work_area_->completer().inlineVisible()))
1512 case LFUN_BUFFER_ZOOM_OUT:
1513 enable = doc_buffer && lyxrc.zoom > 10;
1516 case LFUN_BUFFER_ZOOM_IN:
1517 enable = doc_buffer;
1520 case LFUN_BUFFER_NEXT:
1521 case LFUN_BUFFER_PREVIOUS:
1522 // FIXME: should we check is there is an previous or next buffer?
1524 case LFUN_BUFFER_SWITCH:
1525 // toggle on the current buffer, but do not toggle off
1526 // the other ones (is that a good idea?)
1528 && to_utf8(cmd.argument()) == doc_buffer->absFileName())
1529 flag.setOnOff(true);
1532 case LFUN_VC_REGISTER:
1533 enable = doc_buffer && !doc_buffer->lyxvc().inUse();
1535 case LFUN_VC_CHECK_IN:
1536 enable = doc_buffer && doc_buffer->lyxvc().checkInEnabled();
1538 case LFUN_VC_CHECK_OUT:
1539 enable = doc_buffer && doc_buffer->lyxvc().checkOutEnabled();
1541 case LFUN_VC_LOCKING_TOGGLE:
1542 enable = doc_buffer && !doc_buffer->isReadonly()
1543 && doc_buffer->lyxvc().lockingToggleEnabled();
1544 flag.setOnOff(enable && !doc_buffer->lyxvc().locker().empty());
1546 case LFUN_VC_REVERT:
1547 enable = doc_buffer && doc_buffer->lyxvc().inUse();
1549 case LFUN_VC_UNDO_LAST:
1550 enable = doc_buffer && doc_buffer->lyxvc().undoLastEnabled();
1552 case LFUN_VC_REPO_UPDATE:
1553 enable = doc_buffer && doc_buffer->lyxvc().inUse();
1555 case LFUN_VC_COMMAND: {
1556 if (cmd.argument().empty())
1558 if (!doc_buffer && contains(cmd.getArg(0), 'D'))
1563 case LFUN_SERVER_GOTO_FILE_ROW:
1571 flag.setEnabled(false);
1577 static FileName selectTemplateFile()
1579 FileDialog dlg(qt_("Select template file"));
1580 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1581 dlg.setButton1(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
1583 FileDialog::Result result = dlg.open(toqstr(lyxrc.template_path),
1584 QStringList(qt_("LyX Documents (*.lyx)")));
1586 if (result.first == FileDialog::Later)
1588 if (result.second.isEmpty())
1590 return FileName(fromqstr(result.second));
1594 Buffer * GuiView::loadDocument(FileName const & filename, bool tolastfiles)
1598 Buffer * newBuffer = checkAndLoadLyXFile(filename);
1601 message(_("Document not loaded."));
1606 setBuffer(newBuffer);
1608 // scroll to the position when the file was last closed
1609 if (lyxrc.use_lastfilepos) {
1610 LastFilePosSection::FilePos filepos =
1611 theSession().lastFilePos().load(filename);
1612 documentBufferView()->moveToPosition(filepos.pit, filepos.pos, 0, 0);
1616 theSession().lastFiles().add(filename);
1623 void GuiView::openDocument(string const & fname)
1625 string initpath = lyxrc.document_path;
1627 if (documentBufferView()) {
1628 string const trypath = documentBufferView()->buffer().filePath();
1629 // If directory is writeable, use this as default.
1630 if (FileName(trypath).isDirWritable())
1636 if (fname.empty()) {
1637 FileDialog dlg(qt_("Select document to open"), LFUN_FILE_OPEN);
1638 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1639 dlg.setButton2(qt_("Examples|#E#e"),
1640 toqstr(addPath(package().system_support().absFilename(), "examples")));
1642 QStringList filter(qt_("LyX Documents (*.lyx)"));
1643 filter << qt_("LyX-1.3.x Documents (*.lyx13)")
1644 << qt_("LyX-1.4.x Documents (*.lyx14)")
1645 << qt_("LyX-1.5.x Documents (*.lyx15)")
1646 << qt_("LyX-1.6.x Documents (*.lyx16)");
1647 FileDialog::Result result =
1648 dlg.open(toqstr(initpath), filter);
1650 if (result.first == FileDialog::Later)
1653 filename = fromqstr(result.second);
1655 // check selected filename
1656 if (filename.empty()) {
1657 message(_("Canceled."));
1663 // get absolute path of file and add ".lyx" to the filename if
1665 FileName const fullname =
1666 fileSearch(string(), filename, "lyx", support::may_not_exist);
1667 if (!fullname.empty())
1668 filename = fullname.absFilename();
1670 if (!fullname.onlyPath().isDirectory()) {
1671 Alert::warning(_("Invalid filename"),
1672 bformat(_("The directory in the given path\n%1$s\ndoes not exist."),
1673 from_utf8(fullname.absFilename())));
1676 // if the file doesn't exist, let the user create one
1677 if (!fullname.exists()) {
1678 // the user specifically chose this name. Believe him.
1679 Buffer * const b = newFile(filename, string(), true);
1685 docstring const disp_fn = makeDisplayPath(filename);
1686 message(bformat(_("Opening document %1$s..."), disp_fn));
1689 Buffer * buf = loadDocument(fullname);
1691 buf->updateLabels();
1693 buf->errors("Parse");
1694 str2 = bformat(_("Document %1$s opened."), disp_fn);
1695 if (buf->lyxvc().inUse())
1696 str2 += " " + from_utf8(buf->lyxvc().versionString()) +
1697 " " + _("Version control detected.");
1699 str2 = bformat(_("Could not open document %1$s"), disp_fn);
1704 // FIXME: clean that
1705 static bool import(GuiView * lv, FileName const & filename,
1706 string const & format, ErrorList & errorList)
1708 FileName const lyxfile(support::changeExtension(filename.absFilename(), ".lyx"));
1710 string loader_format;
1711 vector<string> loaders = theConverters().loaders();
1712 if (find(loaders.begin(), loaders.end(), format) == loaders.end()) {
1713 for (vector<string>::const_iterator it = loaders.begin();
1714 it != loaders.end(); ++it) {
1715 if (!theConverters().isReachable(format, *it))
1718 string const tofile =
1719 support::changeExtension(filename.absFilename(),
1720 formats.extension(*it));
1721 if (!theConverters().convert(0, filename, FileName(tofile),
1722 filename, format, *it, errorList))
1724 loader_format = *it;
1727 if (loader_format.empty()) {
1728 frontend::Alert::error(_("Couldn't import file"),
1729 bformat(_("No information for importing the format %1$s."),
1730 formats.prettyName(format)));
1734 loader_format = format;
1736 if (loader_format == "lyx") {
1737 Buffer * buf = lv->loadDocument(lyxfile);
1740 buf->updateLabels();
1742 buf->errors("Parse");
1744 Buffer * const b = newFile(lyxfile.absFilename(), string(), true);
1748 bool as_paragraphs = loader_format == "textparagraph";
1749 string filename2 = (loader_format == format) ? filename.absFilename()
1750 : support::changeExtension(filename.absFilename(),
1751 formats.extension(loader_format));
1752 lv->currentBufferView()->insertPlaintextFile(FileName(filename2),
1754 guiApp->setCurrentView(lv);
1755 lyx::dispatch(FuncRequest(LFUN_MARK_OFF));
1762 void GuiView::importDocument(string const & argument)
1765 string filename = split(argument, format, ' ');
1767 LYXERR(Debug::INFO, format << " file: " << filename);
1769 // need user interaction
1770 if (filename.empty()) {
1771 string initpath = lyxrc.document_path;
1772 if (documentBufferView()) {
1773 string const trypath = documentBufferView()->buffer().filePath();
1774 // If directory is writeable, use this as default.
1775 if (FileName(trypath).isDirWritable())
1779 docstring const text = bformat(_("Select %1$s file to import"),
1780 formats.prettyName(format));
1782 FileDialog dlg(toqstr(text), LFUN_BUFFER_IMPORT);
1783 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1784 dlg.setButton2(qt_("Examples|#E#e"),
1785 toqstr(addPath(package().system_support().absFilename(), "examples")));
1787 docstring filter = formats.prettyName(format);
1790 filter += from_utf8(formats.extension(format));
1793 FileDialog::Result result =
1794 dlg.open(toqstr(initpath), fileFilters(toqstr(filter)));
1796 if (result.first == FileDialog::Later)
1799 filename = fromqstr(result.second);
1801 // check selected filename
1802 if (filename.empty())
1803 message(_("Canceled."));
1806 if (filename.empty())
1809 // get absolute path of file
1810 FileName const fullname(support::makeAbsPath(filename));
1812 FileName const lyxfile(support::changeExtension(fullname.absFilename(), ".lyx"));
1814 // Check if the document already is open
1815 Buffer * buf = theBufferList().getBuffer(lyxfile);
1818 if (!closeBuffer()) {
1819 message(_("Canceled."));
1824 docstring const displaypath = makeDisplayPath(lyxfile.absFilename(), 30);
1826 // if the file exists already, and we didn't do
1827 // -i lyx thefile.lyx, warn
1828 if (lyxfile.exists() && fullname != lyxfile) {
1830 docstring text = bformat(_("The document %1$s already exists.\n\n"
1831 "Do you want to overwrite that document?"), displaypath);
1832 int const ret = Alert::prompt(_("Overwrite document?"),
1833 text, 0, 1, _("&Overwrite"), _("&Cancel"));
1836 message(_("Canceled."));
1841 message(bformat(_("Importing %1$s..."), displaypath));
1842 ErrorList errorList;
1843 if (import(this, fullname, format, errorList))
1844 message(_("imported."));
1846 message(_("file not imported!"));
1848 // FIXME (Abdel 12/08/06): Is there a need to display the error list here?
1852 void GuiView::newDocument(string const & filename, bool from_template)
1854 FileName initpath(lyxrc.document_path);
1855 if (documentBufferView()) {
1856 FileName const trypath(documentBufferView()->buffer().filePath());
1857 // If directory is writeable, use this as default.
1858 if (trypath.isDirWritable())
1862 string templatefile;
1863 if (from_template) {
1864 templatefile = selectTemplateFile().absFilename();
1865 if (templatefile.empty())
1870 if (filename.empty())
1871 b = newUnnamedFile(initpath, to_utf8(_("newfile")), templatefile);
1873 b = newFile(filename, templatefile, true);
1878 // If no new document could be created, it is unsure
1879 // whether there is a valid BufferView.
1880 if (currentBufferView())
1881 // Ensure the cursor is correctly positioned on screen.
1882 currentBufferView()->showCursor();
1886 void GuiView::insertLyXFile(docstring const & fname)
1888 BufferView * bv = documentBufferView();
1893 FileName filename(to_utf8(fname));
1895 if (!filename.empty()) {
1896 bv->insertLyXFile(filename);
1900 // Launch a file browser
1902 string initpath = lyxrc.document_path;
1903 string const trypath = bv->buffer().filePath();
1904 // If directory is writeable, use this as default.
1905 if (FileName(trypath).isDirWritable())
1909 FileDialog dlg(qt_("Select LyX document to insert"), LFUN_FILE_INSERT);
1910 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1911 dlg.setButton2(qt_("Examples|#E#e"),
1912 toqstr(addPath(package().system_support().absFilename(),
1915 FileDialog::Result result = dlg.open(toqstr(initpath),
1916 QStringList(qt_("LyX Documents (*.lyx)")));
1918 if (result.first == FileDialog::Later)
1922 filename.set(fromqstr(result.second));
1924 // check selected filename
1925 if (filename.empty()) {
1926 // emit message signal.
1927 message(_("Canceled."));
1931 bv->insertLyXFile(filename);
1935 void GuiView::insertPlaintextFile(docstring const & fname,
1938 BufferView * bv = documentBufferView();
1942 if (!fname.empty() && !FileName::isAbsolute(to_utf8(fname))) {
1943 message(_("Absolute filename expected."));
1948 FileName filename(to_utf8(fname));
1950 if (!filename.empty()) {
1951 bv->insertPlaintextFile(filename, asParagraph);
1955 FileDialog dlg(qt_("Select file to insert"), (asParagraph ?
1956 LFUN_FILE_INSERT_PLAINTEXT_PARA : LFUN_FILE_INSERT_PLAINTEXT));
1958 FileDialog::Result result = dlg.open(toqstr(bv->buffer().filePath()),
1959 QStringList(qt_("All Files (*)")));
1961 if (result.first == FileDialog::Later)
1965 filename.set(fromqstr(result.second));
1967 // check selected filename
1968 if (filename.empty()) {
1969 // emit message signal.
1970 message(_("Canceled."));
1974 bv->insertPlaintextFile(filename, asParagraph);
1978 bool GuiView::renameBuffer(Buffer & b, docstring const & newname)
1980 FileName fname = b.fileName();
1981 FileName const oldname = fname;
1983 if (!newname.empty()) {
1985 fname = support::makeAbsPath(to_utf8(newname), oldname.onlyPath().absFilename());
1987 // Switch to this Buffer.
1990 // No argument? Ask user through dialog.
1992 FileDialog dlg(qt_("Choose a filename to save document as"),
1993 LFUN_BUFFER_WRITE_AS);
1994 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1995 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
1997 if (!isLyXFilename(fname.absFilename()))
1998 fname.changeExtension(".lyx");
2000 FileDialog::Result result =
2001 dlg.save(toqstr(fname.onlyPath().absFilename()),
2002 QStringList(qt_("LyX Documents (*.lyx)")),
2003 toqstr(fname.onlyFileName()));
2005 if (result.first == FileDialog::Later)
2008 fname.set(fromqstr(result.second));
2013 if (!isLyXFilename(fname.absFilename()))
2014 fname.changeExtension(".lyx");
2017 if (FileName(fname).exists()) {
2018 docstring const file = makeDisplayPath(fname.absFilename(), 30);
2019 docstring text = bformat(_("The document %1$s already "
2020 "exists.\n\nDo you want to "
2021 "overwrite that document?"),
2023 int const ret = Alert::prompt(_("Overwrite document?"),
2024 text, 0, 2, _("&Overwrite"), _("&Rename"), _("&Cancel"));
2027 case 1: return renameBuffer(b, docstring());
2028 case 2: return false;
2032 FileName oldauto = b.getAutosaveFilename();
2034 // Ok, change the name of the buffer
2035 b.setFileName(fname.absFilename());
2037 bool unnamed = b.isUnnamed();
2038 b.setUnnamed(false);
2039 b.saveCheckSum(fname);
2041 // bring the autosave file with us, just in case.
2042 b.moveAutosaveFile(oldauto);
2044 if (!saveBuffer(b)) {
2045 oldauto = b.getAutosaveFilename();
2046 b.setFileName(oldname.absFilename());
2047 b.setUnnamed(unnamed);
2048 b.saveCheckSum(oldname);
2049 b.moveAutosaveFile(oldauto);
2057 bool GuiView::saveBuffer(Buffer & b)
2059 if (workArea(b) && workArea(b)->inDialogMode())
2063 return renameBuffer(b, docstring());
2066 theSession().lastFiles().add(b.fileName());
2070 // Switch to this Buffer.
2073 // FIXME: we don't tell the user *WHY* the save failed !!
2074 docstring const file = makeDisplayPath(b.absFileName(), 30);
2075 docstring text = bformat(_("The document %1$s could not be saved.\n\n"
2076 "Do you want to rename the document and "
2077 "try again?"), file);
2078 int const ret = Alert::prompt(_("Rename and save?"),
2079 text, 0, 2, _("&Rename"), _("&Retry"), _("&Cancel"));
2082 if (!renameBuffer(b, docstring()))
2091 return saveBuffer(b);
2095 bool GuiView::hideWorkArea(GuiWorkArea * wa)
2097 return closeWorkArea(wa, false);
2101 bool GuiView::closeWorkArea(GuiWorkArea * wa)
2103 Buffer & buf = wa->bufferView().buffer();
2104 return closeWorkArea(wa, !buf.parent());
2108 bool GuiView::closeBuffer()
2110 GuiWorkArea * wa = currentMainWorkArea();
2111 Buffer & buf = wa->bufferView().buffer();
2112 return wa && closeWorkArea(wa, !buf.parent());
2116 void GuiView::writeSession() const {
2117 GuiWorkArea const * active_wa = currentMainWorkArea();
2118 for (int i = 0; i < d.splitter_->count(); ++i) {
2119 TabWorkArea * twa = d.tabWorkArea(i);
2120 for (int j = 0; j < twa->count(); ++j) {
2121 GuiWorkArea * wa = static_cast<GuiWorkArea *>(twa->widget(j));
2122 Buffer & buf = wa->bufferView().buffer();
2123 theSession().lastOpened().add(buf.fileName(), wa == active_wa);
2129 bool GuiView::closeBufferAll()
2131 // Close the workareas in all other views
2132 QList<int> const ids = guiApp->viewIds();
2133 for (int i = 0; i != ids.size(); ++i) {
2134 if (id_ != ids[i] && !guiApp->view(ids[i]).closeWorkAreaAll())
2138 // Close our own workareas
2139 if (!closeWorkAreaAll())
2142 // Now close the hidden buffers. We prevent hidden buffers from being
2143 // dirty, so we can just close them.
2144 theBufferList().closeAll();
2149 bool GuiView::closeWorkAreaAll()
2151 setCurrentWorkArea(currentMainWorkArea());
2153 // We might be in a situation that there is still a tabWorkArea, but
2154 // there are no tabs anymore. This can happen when we get here after a
2155 // TabWorkArea::lastWorkAreaRemoved() signal. Therefore we count how
2156 // many TabWorkArea's have no documents anymore.
2159 // We have to call count() each time, because it can happen that
2160 // more than one splitter will disappear in one iteration (bug 5998).
2161 for (; d.splitter_->count() > empty_twa; ) {
2162 TabWorkArea * twa = d.tabWorkArea(empty_twa);
2164 if (twa->count() == 0)
2167 setCurrentWorkArea(twa->currentWorkArea());
2168 if (!closeTabWorkArea(twa))
2176 bool GuiView::closeWorkArea(GuiWorkArea * wa, bool close_buffer)
2181 Buffer & buf = wa->bufferView().buffer();
2184 return closeBuffer(buf);
2186 if (!inMultiTabs(wa))
2187 if (!saveBufferIfNeeded(buf, true))
2195 bool GuiView::closeBuffer(Buffer & buf)
2197 // If we are in a close_event all children will be closed in some time,
2198 // so no need to do it here. This will ensure that the children end up
2199 // in the session file in the correct order. If we close the master
2200 // buffer, we can close or release the child buffers here too.
2202 vector<Buffer *> clist = buf.getChildren(false);
2203 for (vector<Buffer *>::const_iterator it = clist.begin();
2204 it != clist.end(); ++it) {
2205 // If a child is dirty, do not close
2206 // without user intervention
2207 //FIXME: should we look in other tabworkareas?
2208 Buffer * child_buf = *it;
2209 GuiWorkArea * child_wa = workArea(*child_buf);
2211 if (!closeWorkArea(child_wa, true))
2214 theBufferList().releaseChild(&buf, child_buf);
2217 // goto bookmark to update bookmark pit.
2218 //FIXME: we should update only the bookmarks related to this buffer!
2219 LYXERR(Debug::DEBUG, "GuiView::closeBuffer()");
2220 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
2221 theLyXFunc().gotoBookmark(i+1, false, false);
2223 if (saveBufferIfNeeded(buf, false)) {
2224 theBufferList().release(&buf);
2231 bool GuiView::closeTabWorkArea(TabWorkArea * twa)
2233 while (twa == d.currentTabWorkArea()) {
2234 twa->setCurrentIndex(twa->count()-1);
2236 GuiWorkArea * wa = twa->currentWorkArea();
2237 Buffer & b = wa->bufferView().buffer();
2239 // We only want to close the buffer if the same buffer is not visible
2240 // in another view, and if this is not a child and if we are closing
2241 // a view (not a tabgroup).
2242 bool const close_buffer =
2243 !inMultiViews(wa) && !b.parent() && closing_;
2245 if (!closeWorkArea(wa, close_buffer))
2252 bool GuiView::saveBufferIfNeeded(Buffer & buf, bool hiding)
2254 if (buf.isClean() || buf.paragraphs().empty())
2257 // Switch to this Buffer.
2262 if (buf.isUnnamed())
2263 file = from_utf8(buf.fileName().onlyFileName());
2265 file = buf.fileName().displayName(30);
2267 // Bring this window to top before asking questions.
2272 if (hiding && buf.isUnnamed()) {
2273 docstring const text = bformat(_("The document %1$s has not been "
2274 "saved yet.\n\nDo you want to save "
2275 "the document?"), file);
2276 ret = Alert::prompt(_("Save new document?"),
2277 text, 0, 1, _("&Save"), _("&Cancel"));
2281 docstring const text = bformat(_("The document %1$s has unsaved changes."
2282 "\n\nDo you want to save the document or discard the changes?"), file);
2283 ret = Alert::prompt(_("Save changed document?"),
2284 text, 0, 2, _("&Save"), _("&Discard"), _("&Cancel"));
2289 if (!saveBuffer(buf))
2293 // if we crash after this we could
2294 // have no autosave file but I guess
2295 // this is really improbable (Jug)
2296 buf.removeAutosaveFile();
2298 // revert all changes
2299 buf.loadLyXFile(buf.fileName());
2309 bool GuiView::inMultiTabs(GuiWorkArea * wa)
2311 Buffer & buf = wa->bufferView().buffer();
2313 for (int i = 0; i != d.splitter_->count(); ++i) {
2314 GuiWorkArea * wa_ = d.tabWorkArea(i)->workArea(buf);
2315 if (wa_ && wa_ != wa)
2318 return inMultiViews(wa);
2322 bool GuiView::inMultiViews(GuiWorkArea * wa)
2324 QList<int> const ids = guiApp->viewIds();
2325 Buffer & buf = wa->bufferView().buffer();
2328 for (int i = 0; i != ids.size() && found_twa <= 1; ++i) {
2332 if (guiApp->view(ids[i]).workArea(buf))
2339 void GuiView::gotoNextOrPreviousBuffer(NextOrPrevious np)
2341 Buffer * const curbuf = documentBufferView()
2342 ? &documentBufferView()->buffer() : 0;
2343 Buffer * nextbuf = curbuf;
2345 if (np == NEXTBUFFER)
2346 nextbuf = theBufferList().next(nextbuf);
2348 nextbuf = theBufferList().previous(nextbuf);
2349 if (nextbuf == curbuf)
2355 if (workArea(*nextbuf))
2362 /// make sure the document is saved
2363 static bool ensureBufferClean(Buffer * buffer)
2365 LASSERT(buffer, return false);
2366 if (buffer->isClean() && !buffer->isUnnamed())
2369 docstring const file = buffer->fileName().displayName(30);
2372 if (!buffer->isUnnamed()) {
2373 text = bformat(_("The document %1$s has unsaved "
2374 "changes.\n\nDo you want to save "
2375 "the document?"), file);
2376 title = _("Save changed document?");
2379 text = bformat(_("The document %1$s has not been "
2380 "saved yet.\n\nDo you want to save "
2381 "the document?"), file);
2382 title = _("Save new document?");
2384 int const ret = Alert::prompt(title, text, 0, 1, _("&Save"), _("&Cancel"));
2387 dispatch(FuncRequest(LFUN_BUFFER_WRITE));
2389 return buffer->isClean() && !buffer->isUnnamed();
2393 void GuiView::reloadBuffer()
2395 Buffer * buf = &documentBufferView()->buffer();
2400 void GuiView::reloadBuffer(Buffer * buf)
2402 FileName filename = buf->fileName();
2403 Buffer const * master = buf->masterBuffer();
2404 bool const is_child = master != buf;
2405 // The user has already confirmed that the changes, if any, should
2406 // be discarded. So we just release the Buffer and don't call closeBuffer();
2407 theBufferList().release(buf);
2408 buf = loadDocument(filename);
2409 docstring const disp_fn = makeDisplayPath(filename.absFilename());
2412 // re-allocate master if necessary
2413 if (is_child && theBufferList().isLoaded(master)
2414 && buf->masterBuffer() != master)
2415 buf->setParent(master);
2416 buf->updateLabels();
2418 buf->errors("Parse");
2419 str = bformat(_("Document %1$s reloaded."), disp_fn);
2421 str = bformat(_("Could not reload document %1$s"), disp_fn);
2427 void GuiView::checkExternallyModifiedBuffers()
2429 BufferList::iterator bit = theBufferList().begin();
2430 BufferList::iterator const bend = theBufferList().end();
2431 for (; bit != bend; ++bit) {
2432 if ((*bit)->isExternallyModified(Buffer::checksum_method)) {
2433 docstring text = bformat(_("Document \n%1$s\n has been externally modified."
2434 " Reload now? Any local changes will be lost."),
2435 from_utf8((*bit)->absFileName()));
2436 int const ret = Alert::prompt(_("Reload externally changed document?"),
2437 text, 0, 1, _("&Reload"), _("&Cancel"));
2445 void GuiView::dispatchVC(FuncRequest const & cmd)
2447 Buffer * buffer = documentBufferView()
2448 ? &(documentBufferView()->buffer()) : 0;
2450 switch (cmd.action) {
2451 case LFUN_VC_REGISTER:
2452 if (!buffer || !ensureBufferClean(buffer))
2454 if (!buffer->lyxvc().inUse()) {
2455 if (buffer->lyxvc().registrer())
2460 case LFUN_VC_CHECK_IN:
2461 if (!buffer || !ensureBufferClean(buffer))
2463 if (buffer->lyxvc().inUse() && !buffer->isReadonly()) {
2464 message(from_utf8(buffer->lyxvc().checkIn()));
2469 case LFUN_VC_CHECK_OUT:
2470 if (!buffer || !ensureBufferClean(buffer))
2472 if (buffer->lyxvc().inUse()) {
2473 message(from_utf8(buffer->lyxvc().checkOut()));
2478 case LFUN_VC_LOCKING_TOGGLE:
2479 LASSERT(buffer, return);
2480 if (!ensureBufferClean(buffer) || buffer->isReadonly())
2482 if (buffer->lyxvc().inUse()) {
2483 string res = buffer->lyxvc().lockingToggle();
2485 frontend::Alert::error(_("Revision control error."),
2486 _("Error when setting the locking property."));
2488 message(from_utf8(res));
2494 case LFUN_VC_REVERT:
2495 LASSERT(buffer, return);
2496 buffer->lyxvc().revert();
2500 case LFUN_VC_UNDO_LAST:
2501 LASSERT(buffer, return);
2502 buffer->lyxvc().undoLast();
2506 case LFUN_VC_REPO_UPDATE:
2507 LASSERT(buffer, return);
2508 if (ensureBufferClean(buffer)) {
2509 string res = buffer->lyxvc().repoUpdate();
2510 message(from_utf8(res));
2511 checkExternallyModifiedBuffers();
2515 case LFUN_VC_COMMAND: {
2516 string flag = cmd.getArg(0);
2517 if (buffer && contains(flag, 'R') && !ensureBufferClean(buffer))
2520 if (contains(flag, 'M')) {
2521 if (!Alert::askForText(message, _("LyX VC: Log Message")))
2524 string path = cmd.getArg(1);
2525 if (contains(path, "$$p") && buffer)
2526 path = subst(path, "$$p", buffer->filePath());
2527 LYXERR(Debug::LYXVC, "Directory: " << path);
2529 if (!pp.isReadableDirectory()) {
2530 lyxerr << _("Directory is not accessible.") << endl;
2533 support::PathChanger p(pp);
2535 string command = cmd.getArg(2);
2536 if (command.empty())
2539 command = subst(command, "$$i", buffer->absFileName());
2540 command = subst(command, "$$p", buffer->filePath());
2542 command = subst(command, "$$m", to_utf8(message));
2543 LYXERR(Debug::LYXVC, "Command: " << command);
2545 one.startscript(Systemcall::Wait, command);
2549 if (contains(flag, 'I'))
2550 buffer->markDirty();
2551 if (contains(flag, 'R'))
2562 void GuiView::openChildDocument(string const & fname)
2564 LASSERT(documentBufferView(), return);
2565 Buffer & buffer = documentBufferView()->buffer();
2566 FileName const filename = support::makeAbsPath(fname, buffer.filePath());
2567 documentBufferView()->saveBookmark(false);
2569 bool parsed = false;
2570 if (theBufferList().exists(filename)) {
2571 child = theBufferList().getBuffer(filename);
2573 message(bformat(_("Opening child document %1$s..."),
2574 makeDisplayPath(filename.absFilename())));
2575 child = loadDocument(filename, false);
2581 // Set the parent name of the child document.
2582 // This makes insertion of citations and references in the child work,
2583 // when the target is in the parent or another child document.
2584 child->setParent(&buffer);
2585 child->masterBuffer()->updateLabels();
2588 child->errors("Parse");
2592 bool GuiView::goToFileRow(string const & argument)
2596 istringstream is(argument);
2597 is >> file_name >> row;
2598 file_name = os::internal_path(file_name);
2600 string const abstmp = package().temp_dir().absFilename();
2601 string const realtmp = package().temp_dir().realPath();
2602 // We have to use os::path_prefix_is() here, instead of
2603 // simply prefixIs(), because the file name comes from
2604 // an external application and may need case adjustment.
2605 if (os::path_prefix_is(file_name, abstmp, os::CASE_ADJUSTED)
2606 || os::path_prefix_is(file_name, realtmp, os::CASE_ADJUSTED)) {
2607 // Needed by inverse dvi search. If it is a file
2608 // in tmpdir, call the apropriated function.
2609 // If tmpdir is a symlink, we may have the real
2610 // path passed back, so we correct for that.
2611 if (!prefixIs(file_name, abstmp))
2612 file_name = subst(file_name, realtmp, abstmp);
2613 buf = theBufferList().getBufferFromTmp(file_name);
2615 // Must replace extension of the file to be .lyx
2616 // and get full path
2617 FileName const s = fileSearch(string(),
2618 support::changeExtension(file_name, ".lyx"), "lyx");
2619 // Either change buffer or load the file
2620 if (theBufferList().exists(s))
2621 buf = theBufferList().getBuffer(s);
2622 else if (s.exists()) {
2623 buf = loadDocument(s);
2624 buf->updateLabels();
2625 buf->errors("Parse");
2628 _("File does not exist: %1$s"),
2629 makeDisplayPath(file_name)));
2634 documentBufferView()->setCursorFromRow(row);
2639 static docstring exportAndDestroy(Buffer * buffer, string const & format)
2641 bool const success = buffer->doExport(format, true);
2644 ? bformat(_("Successful export to format: %1$s"), from_utf8(format))
2645 : bformat(_("Error exporting to format: %1$s"), from_utf8(format));
2649 static docstring previewAndDestroy(Buffer * buffer, string const & format)
2651 bool const success = buffer->preview(format);
2654 ? bformat(_("Successful preview of format: %1$s"), from_utf8(format))
2655 : bformat(_("Error previewing format: %1$s"), from_utf8(format));
2659 bool GuiView::dispatch(FuncRequest const & cmd)
2661 BufferView * bv = currentBufferView();
2662 // By default we won't need any update.
2664 bv->cursor().updateFlags(Update::None);
2666 Buffer * doc_buffer = documentBufferView()
2667 ? &(documentBufferView()->buffer()) : 0;
2669 bool dispatched = true;
2671 if (cmd.origin == FuncRequest::TOC) {
2672 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
2673 toc->doDispatch(bv->cursor(), cmd);
2677 string const argument = to_utf8(cmd.argument());
2679 switch(cmd.action) {
2680 case LFUN_BUFFER_CHILD_OPEN:
2681 openChildDocument(to_utf8(cmd.argument()));
2684 case LFUN_BUFFER_IMPORT:
2685 importDocument(to_utf8(cmd.argument()));
2688 case LFUN_BUFFER_EXPORT: {
2691 if (cmd.argument() == "custom") {
2692 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "sendto"));
2695 if (doc_buffer->doExport(argument, false)) {
2696 message(bformat(_("Error exporting to format: %1$s."),
2702 case LFUN_BUFFER_UPDATE: {
2705 string format = argument;
2706 if (argument.empty())
2707 format = doc_buffer->getDefaultOutputFormat();
2708 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
2709 ProgressInterface::instance()->clearMessages();
2710 ProgressInterface::instance()->appendMessage("Exporting ...");
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 ProgressInterface::instance()->appendMessage("Previewing ...");
2728 QFuture<docstring> f = QtConcurrent::run(previewAndDestroy,
2729 doc_buffer->clone(), format);
2730 d.setPreviewFuture(f);
2732 doc_buffer->preview(format);
2736 case LFUN_MASTER_BUFFER_UPDATE: {
2739 string format = argument;
2740 Buffer const * master = doc_buffer->masterBuffer();
2741 if (argument.empty())
2742 format = master->getDefaultOutputFormat();
2743 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
2744 QFuture<docstring> f = QtConcurrent::run(exportAndDestroy,
2745 master->clone(), format);
2746 d.setPreviewFuture(f);
2748 master->doExport(format, true);
2752 case LFUN_MASTER_BUFFER_VIEW: {
2753 string format = argument;
2754 Buffer const * master = doc_buffer->masterBuffer();
2755 if (argument.empty())
2756 format = master->getDefaultOutputFormat();
2757 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
2758 QFuture<docstring> f = QtConcurrent::run(previewAndDestroy,
2759 master->clone(), format);
2760 d.setPreviewFuture(f);
2762 master->preview(format);
2766 case LFUN_BUFFER_SWITCH:
2767 if (FileName::isAbsolute(to_utf8(cmd.argument()))) {
2769 theBufferList().getBuffer(FileName(to_utf8(cmd.argument())));
2773 message(_("Document not loaded"));
2777 case LFUN_BUFFER_NEXT:
2778 gotoNextOrPreviousBuffer(NEXTBUFFER);
2781 case LFUN_BUFFER_PREVIOUS:
2782 gotoNextOrPreviousBuffer(PREVBUFFER);
2785 case LFUN_COMMAND_EXECUTE: {
2786 bool const show_it = cmd.argument() != "off";
2787 // FIXME: this is a hack, "minibuffer" should not be
2789 if (GuiToolbar * t = toolbar("minibuffer")) {
2790 t->setVisible(show_it);
2791 if (show_it && t->commandBuffer())
2792 t->commandBuffer()->setFocus();
2796 case LFUN_DROP_LAYOUTS_CHOICE:
2797 d.layout_->showPopup();
2800 case LFUN_MENU_OPEN:
2801 if (QMenu * menu = guiApp->menus().menu(toqstr(cmd.argument()), *this))
2802 menu->exec(QCursor::pos());
2805 case LFUN_FILE_INSERT:
2806 insertLyXFile(cmd.argument());
2808 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
2809 insertPlaintextFile(cmd.argument(), true);
2812 case LFUN_FILE_INSERT_PLAINTEXT:
2813 insertPlaintextFile(cmd.argument(), false);
2816 case LFUN_BUFFER_RELOAD: {
2817 LASSERT(doc_buffer, break);
2818 docstring const file = makeDisplayPath(doc_buffer->absFileName(), 20);
2819 docstring text = bformat(_("Any changes will be lost. Are you sure "
2820 "you want to revert to the saved version of the document %1$s?"), file);
2821 int const ret = Alert::prompt(_("Revert to saved document?"),
2822 text, 1, 1, _("&Revert"), _("&Cancel"));
2825 doc_buffer->markClean();
2831 case LFUN_BUFFER_WRITE:
2832 LASSERT(doc_buffer, break);
2833 saveBuffer(*doc_buffer);
2836 case LFUN_BUFFER_WRITE_AS:
2837 LASSERT(doc_buffer, break);
2838 renameBuffer(*doc_buffer, cmd.argument());
2841 case LFUN_BUFFER_WRITE_ALL: {
2842 Buffer * first = theBufferList().first();
2845 message(_("Saving all documents..."));
2846 // We cannot use a for loop as the buffer list cycles.
2849 if (!b->isClean()) {
2851 LYXERR(Debug::ACTION, "Saved " << b->absFileName());
2853 b = theBufferList().next(b);
2854 } while (b != first);
2855 message(_("All documents saved."));
2859 case LFUN_BUFFER_CLOSE:
2863 case LFUN_BUFFER_CLOSE_ALL:
2867 case LFUN_TOOLBAR_TOGGLE: {
2868 string const name = cmd.getArg(0);
2869 if (GuiToolbar * t = toolbar(name))
2874 case LFUN_DIALOG_UPDATE: {
2875 string const name = to_utf8(cmd.argument());
2876 if (currentBufferView()) {
2877 Inset * inset = currentBufferView()->editedInset(name);
2878 // Can only update a dialog connected to an existing inset
2881 // FIXME: get rid of this indirection; GuiView ask the inset
2882 // if he is kind enough to update itself...
2883 FuncRequest fr(LFUN_INSET_DIALOG_UPDATE, cmd.argument());
2884 inset->dispatch(currentBufferView()->cursor(), fr);
2885 } else if (name == "paragraph") {
2886 lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
2887 } else if (name == "prefs" || name == "document") {
2888 updateDialog(name, string());
2893 case LFUN_DIALOG_TOGGLE: {
2894 if (isDialogVisible(cmd.getArg(0)))
2895 dispatch(FuncRequest(LFUN_DIALOG_HIDE, cmd.argument()));
2897 dispatch(FuncRequest(LFUN_DIALOG_SHOW, cmd.argument()));
2901 case LFUN_DIALOG_DISCONNECT_INSET:
2902 disconnectDialog(to_utf8(cmd.argument()));
2905 case LFUN_DIALOG_HIDE: {
2906 guiApp->hideDialogs(to_utf8(cmd.argument()), 0);
2910 case LFUN_DIALOG_SHOW: {
2911 string const name = cmd.getArg(0);
2912 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
2914 if (name == "character") {
2915 data = freefont2string();
2917 showDialog("character", data);
2918 } else if (name == "latexlog") {
2919 Buffer::LogType type;
2920 string const logfile = doc_buffer->logName(&type);
2922 case Buffer::latexlog:
2925 case Buffer::buildlog:
2929 data += Lexer::quoteString(logfile);
2930 showDialog("log", data);
2931 } else if (name == "vclog") {
2932 string const data = "vc " +
2933 Lexer::quoteString(doc_buffer->lyxvc().getLogFile());
2934 showDialog("log", data);
2935 } else if (name == "symbols") {
2936 data = bv->cursor().getEncoding()->name();
2938 showDialog("symbols", data);
2940 } else if (name == "prefs" && isFullScreen()) {
2941 FuncRequest fr(LFUN_INSET_INSERT, "fullscreen");
2943 showDialog("prefs", data);
2945 showDialog(name, data);
2950 message(cmd.argument());
2953 case LFUN_UI_TOGGLE:
2955 // Make sure the keyboard focus stays in the work area.
2959 case LFUN_SPLIT_VIEW: {
2960 LASSERT(doc_buffer, break);
2961 string const orientation = cmd.getArg(0);
2962 d.splitter_->setOrientation(orientation == "vertical"
2963 ? Qt::Vertical : Qt::Horizontal);
2964 TabWorkArea * twa = addTabWorkArea();
2965 GuiWorkArea * wa = twa->addWorkArea(*doc_buffer, *this);
2966 setCurrentWorkArea(wa);
2969 case LFUN_CLOSE_TAB_GROUP:
2970 if (TabWorkArea * twa = d.currentTabWorkArea()) {
2971 closeTabWorkArea(twa);
2972 d.current_work_area_ = 0;
2973 twa = d.currentTabWorkArea();
2974 // Switch to the next GuiWorkArea in the found TabWorkArea.
2976 // Make sure the work area is up to date.
2977 setCurrentWorkArea(twa->currentWorkArea());
2979 setCurrentWorkArea(0);
2984 case LFUN_COMPLETION_INLINE:
2985 if (d.current_work_area_)
2986 d.current_work_area_->completer().showInline();
2989 case LFUN_COMPLETION_POPUP:
2990 if (d.current_work_area_)
2991 d.current_work_area_->completer().showPopup();
2995 case LFUN_COMPLETION_COMPLETE:
2996 if (d.current_work_area_)
2997 d.current_work_area_->completer().tab();
3000 case LFUN_COMPLETION_CANCEL:
3001 if (d.current_work_area_) {
3002 if (d.current_work_area_->completer().popupVisible())
3003 d.current_work_area_->completer().hidePopup();
3005 d.current_work_area_->completer().hideInline();
3009 case LFUN_COMPLETION_ACCEPT:
3010 if (d.current_work_area_)
3011 d.current_work_area_->completer().activate();
3014 case LFUN_BUFFER_ZOOM_IN:
3015 case LFUN_BUFFER_ZOOM_OUT:
3016 if (cmd.argument().empty()) {
3017 if (cmd.action == LFUN_BUFFER_ZOOM_IN)
3022 lyxrc.zoom += convert<int>(cmd.argument());
3024 if (lyxrc.zoom < 10)
3027 // The global QPixmapCache is used in GuiPainter to cache text
3028 // painting so we must reset it.
3029 QPixmapCache::clear();
3030 guiApp->fontLoader().update();
3031 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
3034 case LFUN_VC_REGISTER:
3035 case LFUN_VC_CHECK_IN:
3036 case LFUN_VC_CHECK_OUT:
3037 case LFUN_VC_REPO_UPDATE:
3038 case LFUN_VC_LOCKING_TOGGLE:
3039 case LFUN_VC_REVERT:
3040 case LFUN_VC_UNDO_LAST:
3041 case LFUN_VC_COMMAND:
3045 case LFUN_SERVER_GOTO_FILE_ROW:
3046 goToFileRow(to_utf8(cmd.argument()));
3054 // Part of automatic menu appearance feature.
3055 if (isFullScreen()) {
3056 if (menuBar()->isVisible() && lyxrc.full_screen_menubar)
3058 if (statusBar()->isVisible())
3059 statusBar()->hide();
3066 void GuiView::lfunUiToggle(FuncRequest const & cmd)
3068 string const arg = cmd.getArg(0);
3069 if (arg == "scrollbar") {
3070 // hide() is of no help
3071 if (d.current_work_area_->verticalScrollBarPolicy() ==
3072 Qt::ScrollBarAlwaysOff)
3074 d.current_work_area_->setVerticalScrollBarPolicy(
3075 Qt::ScrollBarAsNeeded);
3077 d.current_work_area_->setVerticalScrollBarPolicy(
3078 Qt::ScrollBarAlwaysOff);
3081 if (arg == "statusbar") {
3082 statusBar()->setVisible(!statusBar()->isVisible());
3085 if (arg == "menubar") {
3086 menuBar()->setVisible(!menuBar()->isVisible());
3089 #if QT_VERSION >= 0x040300
3090 if (arg == "frame") {
3092 getContentsMargins(&l, &t, &r, &b);
3093 //are the frames in default state?
3094 d.current_work_area_->setFrameStyle(QFrame::NoFrame);
3096 setContentsMargins(-2, -2, -2, -2);
3098 setContentsMargins(0, 0, 0, 0);
3103 if (arg == "fullscreen") {
3108 message(bformat("LFUN_UI_TOGGLE " + _("%1$s unknown command!"), from_utf8(arg)));
3112 void GuiView::toggleFullScreen()
3114 if (isFullScreen()) {
3115 for (int i = 0; i != d.splitter_->count(); ++i)
3116 d.tabWorkArea(i)->setFullScreen(false);
3117 #if QT_VERSION >= 0x040300
3118 setContentsMargins(0, 0, 0, 0);
3120 setWindowState(windowState() ^ Qt::WindowFullScreen);
3123 statusBar()->show();
3126 hideDialogs("prefs", 0);
3127 for (int i = 0; i != d.splitter_->count(); ++i)
3128 d.tabWorkArea(i)->setFullScreen(true);
3129 #if QT_VERSION >= 0x040300
3130 setContentsMargins(-2, -2, -2, -2);
3133 setWindowState(windowState() ^ Qt::WindowFullScreen);
3134 statusBar()->hide();
3135 if (lyxrc.full_screen_menubar)
3137 if (lyxrc.full_screen_toolbars) {
3138 ToolbarMap::iterator end = d.toolbars_.end();
3139 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
3144 // give dialogs like the TOC a chance to adapt
3149 Buffer const * GuiView::updateInset(Inset const * inset)
3151 if (!d.current_work_area_)
3155 d.current_work_area_->scheduleRedraw();
3157 return &d.current_work_area_->bufferView().buffer();
3161 void GuiView::restartCursor()
3163 /* When we move around, or type, it's nice to be able to see
3164 * the cursor immediately after the keypress.
3166 if (d.current_work_area_)
3167 d.current_work_area_->startBlinkingCursor();
3169 // Take this occasion to update the other GUI elements.
3175 void GuiView::updateCompletion(Cursor & cur, bool start, bool keep)
3177 if (d.current_work_area_)
3178 d.current_work_area_->completer().updateVisibility(cur, start, keep);
3183 // This list should be kept in sync with the list of insets in
3184 // src/insets/Inset.cpp. I.e., if a dialog goes with an inset, the
3185 // dialog should have the same name as the inset.
3186 // Changes should be also recorded in LFUN_DIALOG_SHOW doxygen
3187 // docs in LyXAction.cpp.
3189 char const * const dialognames[] = {
3190 "aboutlyx", "bibitem", "bibtex", "box", "branch", "changes", "character",
3191 "citation", "compare", "document", "errorlist", "ert", "external", "file",
3192 "findreplace", "findreplaceadv", "float", "graphics", "href", "include",
3193 "index", "index_print", "info", "listings", "label", "log", "mathdelimiter",
3194 "mathmatrix", "mathspace", "nomenclature", "nomencl_print", "note",
3195 "paragraph", "phantom", "prefs", "print", "ref", "sendto", "space",
3196 "spellchecker", "symbols", "tabular", "tabularcreate", "thesaurus", "texinfo",
3197 "toc", "view-source", "vspace", "wrap", "progress"};
3199 char const * const * const end_dialognames =
3200 dialognames + (sizeof(dialognames) / sizeof(char *));
3204 cmpCStr(char const * name) : name_(name) {}
3205 bool operator()(char const * other) {
3206 return strcmp(other, name_) == 0;
3213 bool isValidName(string const & name)
3215 return find_if(dialognames, end_dialognames,
3216 cmpCStr(name.c_str())) != end_dialognames;
3222 void GuiView::resetDialogs()
3224 // Make sure that no LFUN uses any LyXView.
3225 guiApp->setCurrentView(0);
3228 constructToolbars();
3229 guiApp->menus().fillMenuBar(menuBar(), this, false);
3230 d.layout_->updateContents(true);
3231 // Now update controls with current buffer.
3232 guiApp->setCurrentView(this);
3238 Dialog * GuiView::findOrBuild(string const & name, bool hide_it)
3240 if (!isValidName(name))
3243 map<string, DialogPtr>::iterator it = d.dialogs_.find(name);
3245 if (it != d.dialogs_.end()) {
3247 it->second->hideView();
3248 return it->second.get();
3251 Dialog * dialog = build(name);
3252 d.dialogs_[name].reset(dialog);
3253 if (lyxrc.allow_geometry_session)
3254 dialog->restoreSession();
3261 void GuiView::showDialog(string const & name, string const & data,
3264 triggerShowDialog(toqstr(name), toqstr(data), inset);
3268 void GuiView::doShowDialog(QString const & qname, QString const & qdata,
3274 const string name = fromqstr(qname);
3275 const string data = fromqstr(qdata);
3279 Dialog * dialog = findOrBuild(name, false);
3281 dialog->showData(data);
3282 if (inset && currentBufferView())
3283 currentBufferView()->editInset(name, inset);
3286 catch (ExceptionMessage const & ex) {
3294 bool GuiView::isDialogVisible(string const & name) const
3296 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3297 if (it == d.dialogs_.end())
3299 return it->second.get()->isVisibleView() && !it->second.get()->isClosing();
3303 void GuiView::hideDialog(string const & name, Inset * inset)
3305 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3306 if (it == d.dialogs_.end())
3309 if (inset && currentBufferView()
3310 && inset != currentBufferView()->editedInset(name))
3313 Dialog * const dialog = it->second.get();
3314 if (dialog->isVisibleView())
3316 if (currentBufferView())
3317 currentBufferView()->editInset(name, 0);
3321 void GuiView::disconnectDialog(string const & name)
3323 if (!isValidName(name))
3325 if (currentBufferView())
3326 currentBufferView()->editInset(name, 0);
3330 void GuiView::hideAll() const
3332 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
3333 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3335 for(; it != end; ++it)
3336 it->second->hideView();
3340 void GuiView::updateDialogs()
3342 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
3343 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3345 for(; it != end; ++it) {
3346 Dialog * dialog = it->second.get();
3347 if (dialog && dialog->isVisibleView())
3348 dialog->checkStatus();
3355 // will be replaced by a proper factory...
3356 Dialog * createGuiAbout(GuiView & lv);
3357 Dialog * createGuiBibitem(GuiView & lv);
3358 Dialog * createGuiBibtex(GuiView & lv);
3359 Dialog * createGuiBox(GuiView & lv);
3360 Dialog * createGuiBranch(GuiView & lv);
3361 Dialog * createGuiChanges(GuiView & lv);
3362 Dialog * createGuiCharacter(GuiView & lv);
3363 Dialog * createGuiCitation(GuiView & lv);
3364 Dialog * createGuiCompare(GuiView & lv);
3365 Dialog * createGuiDelimiter(GuiView & lv);
3366 Dialog * createGuiDocument(GuiView & lv);
3367 Dialog * createGuiErrorList(GuiView & lv);
3368 Dialog * createGuiERT(GuiView & lv);
3369 Dialog * createGuiExternal(GuiView & lv);
3370 Dialog * createGuiFloat(GuiView & lv);
3371 Dialog * createGuiGraphics(GuiView & lv);
3372 Dialog * createGuiInclude(GuiView & lv);
3373 Dialog * createGuiIndex(GuiView & lv);
3374 Dialog * createGuiInfo(GuiView & lv);
3375 Dialog * createGuiLabel(GuiView & lv);
3376 Dialog * createGuiListings(GuiView & lv);
3377 Dialog * createGuiLog(GuiView & lv);
3378 Dialog * createGuiMathHSpace(GuiView & lv);
3379 Dialog * createGuiMathMatrix(GuiView & lv);
3380 Dialog * createGuiNomenclature(GuiView & lv);
3381 Dialog * createGuiNote(GuiView & lv);
3382 Dialog * createGuiParagraph(GuiView & lv);
3383 Dialog * createGuiPhantom(GuiView & lv);
3384 Dialog * createGuiPreferences(GuiView & lv);
3385 Dialog * createGuiPrint(GuiView & lv);
3386 Dialog * createGuiPrintindex(GuiView & lv);
3387 Dialog * createGuiPrintNomencl(GuiView & lv);
3388 Dialog * createGuiRef(GuiView & lv);
3389 Dialog * createGuiSearch(GuiView & lv);
3390 Dialog * createGuiSearchAdv(GuiView & lv);
3391 Dialog * createGuiSendTo(GuiView & lv);
3392 Dialog * createGuiShowFile(GuiView & lv);
3393 Dialog * createGuiSpellchecker(GuiView & lv);
3394 Dialog * createGuiSymbols(GuiView & lv);
3395 Dialog * createGuiTabularCreate(GuiView & lv);
3396 Dialog * createGuiTabular(GuiView & lv);
3397 Dialog * createGuiTexInfo(GuiView & lv);
3398 Dialog * createGuiTextHSpace(GuiView & lv);
3399 Dialog * createGuiToc(GuiView & lv);
3400 Dialog * createGuiThesaurus(GuiView & lv);
3401 Dialog * createGuiHyperlink(GuiView & lv);
3402 Dialog * createGuiVSpace(GuiView & lv);
3403 Dialog * createGuiViewSource(GuiView & lv);
3404 Dialog * createGuiWrap(GuiView & lv);
3405 Dialog * createGuiProgressView(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);
3511 if (name == "progress")
3512 return createGuiProgressView(*this);
3518 } // namespace frontend
3521 #include "moc_GuiView.cpp"