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>
105 #include <QScrollBar>
107 #define EXPORT_in_THREAD 1
109 // QtConcurrent was introduced in Qt 4.4
110 #if (QT_VERSION >= 0x040400)
112 #include <QFutureWatcher>
113 #include <QtConcurrentRun>
116 #include <boost/bind.hpp>
120 #ifdef HAVE_SYS_TIME_H
121 # include <sys/time.h>
128 using namespace lyx::support;
135 class BackgroundWidget : public QWidget
140 LYXERR(Debug::GUI, "show banner: " << lyxrc.show_banner);
141 /// The text to be written on top of the pixmap
142 QString const text = lyx_version ?
143 qt_("version ") + lyx_version : qt_("unknown version");
144 splash_ = getPixmap("images/", "banner", "png");
146 QPainter pain(&splash_);
147 pain.setPen(QColor(0, 0, 0));
149 // The font used to display the version info
150 font.setStyleHint(QFont::SansSerif);
151 font.setWeight(QFont::Bold);
152 font.setPointSize(int(toqstr(lyxrc.font_sizes[FONT_SIZE_LARGE]).toDouble()));
154 pain.drawText(260, 15, text);
157 void paintEvent(QPaintEvent *)
159 int x = (width() - splash_.width()) / 2;
160 int y = (height() - splash_.height()) / 2;
162 pain.drawPixmap(x, y, splash_);
170 /// Toolbar store providing access to individual toolbars by name.
171 typedef map<string, GuiToolbar *> ToolbarMap;
173 typedef boost::shared_ptr<Dialog> DialogPtr;
178 struct GuiView::GuiViewPrivate
180 GuiViewPrivate(GuiView * gv)
181 : gv_(gv), current_work_area_(0), current_main_work_area_(0),
182 layout_(0), autosave_timeout_(5000),
185 // hardcode here the platform specific icon size
186 smallIconSize = 14; // scaling problems
187 normalIconSize = 20; // ok, default
188 bigIconSize = 26; // better for some math icons
190 splitter_ = new QSplitter;
191 bg_widget_ = new BackgroundWidget;
192 stack_widget_ = new QStackedWidget;
193 stack_widget_->addWidget(bg_widget_);
194 stack_widget_->addWidget(splitter_);
196 progress_ = new GuiProgress(gv);
203 delete stack_widget_;
207 QMenu * toolBarPopup(GuiView * parent)
209 // FIXME: translation
210 QMenu * menu = new QMenu(parent);
211 QActionGroup * iconSizeGroup = new QActionGroup(parent);
213 QAction * smallIcons = new QAction(iconSizeGroup);
214 smallIcons->setText(qt_("Small-sized icons"));
215 smallIcons->setCheckable(true);
216 QObject::connect(smallIcons, SIGNAL(triggered()),
217 parent, SLOT(smallSizedIcons()));
218 menu->addAction(smallIcons);
220 QAction * normalIcons = new QAction(iconSizeGroup);
221 normalIcons->setText(qt_("Normal-sized icons"));
222 normalIcons->setCheckable(true);
223 QObject::connect(normalIcons, SIGNAL(triggered()),
224 parent, SLOT(normalSizedIcons()));
225 menu->addAction(normalIcons);
227 QAction * bigIcons = new QAction(iconSizeGroup);
228 bigIcons->setText(qt_("Big-sized icons"));
229 bigIcons->setCheckable(true);
230 QObject::connect(bigIcons, SIGNAL(triggered()),
231 parent, SLOT(bigSizedIcons()));
232 menu->addAction(bigIcons);
234 unsigned int cur = parent->iconSize().width();
235 if ( cur == parent->d.smallIconSize)
236 smallIcons->setChecked(true);
237 else if (cur == parent->d.normalIconSize)
238 normalIcons->setChecked(true);
239 else if (cur == parent->d.bigIconSize)
240 bigIcons->setChecked(true);
247 stack_widget_->setCurrentWidget(bg_widget_);
248 bg_widget_->setUpdatesEnabled(true);
251 TabWorkArea * tabWorkArea(int i)
253 return dynamic_cast<TabWorkArea *>(splitter_->widget(i));
256 TabWorkArea * currentTabWorkArea()
258 if (splitter_->count() == 1)
259 // The first TabWorkArea is always the first one, if any.
260 return tabWorkArea(0);
262 for (int i = 0; i != splitter_->count(); ++i) {
263 TabWorkArea * twa = tabWorkArea(i);
264 if (current_main_work_area_ == twa->currentWorkArea())
268 // None has the focus so we just take the first one.
269 return tabWorkArea(0);
272 void setPreviewFuture(QFuture<docstring> const & f)
274 if (preview_watcher_.isRunning())
275 preview_watcher_.waitForFinished();
276 preview_watcher_.setFuture(f);
277 connect(&preview_watcher_, SIGNAL(finished()), gv_,
278 SLOT(threadFinished()));
283 GuiWorkArea * current_work_area_;
284 GuiWorkArea * current_main_work_area_;
285 QSplitter * splitter_;
286 QStackedWidget * stack_widget_;
287 BackgroundWidget * bg_widget_;
289 ToolbarMap toolbars_;
290 ProgressInterface* progress_;
291 /// The main layout box.
293 * \warning Don't Delete! The layout box is actually owned by
294 * whichever toolbar contains it. All the GuiView class needs is a
295 * means of accessing it.
297 * FIXME: replace that with a proper model so that we are not limited
298 * to only one dialog.
303 map<string, DialogPtr> dialogs_;
305 unsigned int smallIconSize;
306 unsigned int normalIconSize;
307 unsigned int bigIconSize;
309 QTimer statusbar_timer_;
310 /// auto-saving of buffers
311 Timeout autosave_timeout_;
312 /// flag against a race condition due to multiclicks, see bug #1119
316 TocModels toc_models_;
318 #if (QT_VERSION >= 0x040400)
320 QFutureWatcher<docstring> autosave_watcher_;
321 QFutureWatcher<docstring> preview_watcher_;
326 GuiView::GuiView(int id)
327 : d(*new GuiViewPrivate(this)), id_(id), closing_(false)
329 // GuiToolbars *must* be initialised before the menu bar.
330 normalSizedIcons(); // at least on Mac the default is 32 otherwise, which is huge
333 // set ourself as the current view. This is needed for the menu bar
334 // filling, at least for the static special menu item on Mac. Otherwise
335 // they are greyed out.
336 guiApp->setCurrentView(this);
338 // Fill up the menu bar.
339 guiApp->menus().fillMenuBar(menuBar(), this, true);
341 setCentralWidget(d.stack_widget_);
343 // Start autosave timer
344 if (lyxrc.autosave) {
345 d.autosave_timeout_.timeout.connect(boost::bind(&GuiView::autoSave, this));
346 d.autosave_timeout_.setTimeout(lyxrc.autosave * 1000);
347 d.autosave_timeout_.start();
349 connect(&d.statusbar_timer_, SIGNAL(timeout()),
350 this, SLOT(clearMessage()));
352 // We don't want to keep the window in memory if it is closed.
353 setAttribute(Qt::WA_DeleteOnClose, true);
355 #if (!defined(Q_WS_WIN) && !defined(Q_WS_MACX))
356 // assign an icon to main form. We do not do it under Qt/Win or Qt/Mac,
357 // since the icon is provided in the application bundle.
358 setWindowIcon(getPixmap("images/", "lyx", "png"));
362 setAcceptDrops(true);
364 statusBar()->setSizeGripEnabled(true);
366 // Forbid too small unresizable window because it can happen
367 // with some window manager under X11.
368 setMinimumSize(300, 200);
370 if (lyxrc.allow_geometry_session) {
371 // Now take care of session management.
376 // no session handling, default to a sane size.
377 setGeometry(50, 50, 690, 510);
380 // clear session data if any.
382 settings.remove("views");
384 #if (QT_VERSION >= 0x040400)
385 connect(&d.autosave_watcher_, SIGNAL(finished()), this,
386 SLOT(threadFinished()));
389 connect(this, SIGNAL(triggerShowDialog(QString const &, QString const &, Inset *)),
390 SLOT(doShowDialog(QString const &, QString const &, Inset *)));
400 void GuiView::threadFinished()
402 #if (QT_VERSION >= 0x040400)
403 QFutureWatcher<docstring> const * watcher =
404 static_cast<QFutureWatcher<docstring> const *>(sender());
405 message(watcher->result());
410 void GuiView::saveLayout() const
413 settings.beginGroup("views");
414 settings.beginGroup(QString::number(id_));
416 settings.setValue("pos", pos());
417 settings.setValue("size", size());
419 settings.setValue("geometry", saveGeometry());
421 settings.setValue("layout", saveState(0));
422 settings.setValue("icon_size", iconSize());
426 bool GuiView::restoreLayout()
429 settings.beginGroup("views");
430 settings.beginGroup(QString::number(id_));
431 QString const icon_key = "icon_size";
432 if (!settings.contains(icon_key))
435 //code below is skipped when when ~/.config/LyX is (re)created
436 setIconSize(settings.value(icon_key).toSize());
438 QPoint pos = settings.value("pos", QPoint(50, 50)).toPoint();
439 QSize size = settings.value("size", QSize(690, 510)).toSize();
443 // Work-around for bug #6034: the window ends up in an undetermined
444 // state when trying to restore a maximized window when it is
445 // already maximized.
446 if (!(windowState() & Qt::WindowMaximized))
447 if (!restoreGeometry(settings.value("geometry").toByteArray()))
448 setGeometry(50, 50, 690, 510);
450 // Make sure layout is correctly oriented.
451 setLayoutDirection(qApp->layoutDirection());
453 // Allow the toc and view-source dock widget to be restored if needed.
455 if ((dialog = findOrBuild("toc", true)))
456 // see bug 5082. At least setup title and enabled state.
457 // Visibility will be adjusted by restoreState below.
458 dialog->prepareView();
459 if ((dialog = findOrBuild("view-source", true)))
460 dialog->prepareView();
462 if (!restoreState(settings.value("layout").toByteArray(), 0))
469 GuiToolbar * GuiView::toolbar(string const & name)
471 ToolbarMap::iterator it = d.toolbars_.find(name);
472 if (it != d.toolbars_.end())
475 LYXERR(Debug::GUI, "Toolbar::display: no toolbar named " << name);
476 message(bformat(_("Unknown toolbar \"%1$s\""), from_utf8(name)));
481 void GuiView::constructToolbars()
483 ToolbarMap::iterator it = d.toolbars_.begin();
484 for (; it != d.toolbars_.end(); ++it)
488 // I don't like doing this here, but the standard toolbar
489 // destroys this object when it's destroyed itself (vfr)
490 d.layout_ = new LayoutBox(*this);
491 d.stack_widget_->addWidget(d.layout_);
492 d.layout_->move(0,0);
494 // extracts the toolbars from the backend
495 Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
496 Toolbars::Infos::iterator end = guiApp->toolbars().end();
497 for (; cit != end; ++cit)
498 d.toolbars_[cit->name] = new GuiToolbar(*cit, *this);
502 void GuiView::initToolbars()
504 // extracts the toolbars from the backend
505 Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
506 Toolbars::Infos::iterator end = guiApp->toolbars().end();
507 for (; cit != end; ++cit) {
508 GuiToolbar * tb = toolbar(cit->name);
511 int const visibility = guiApp->toolbars().defaultVisibility(cit->name);
513 tb->setVisible(false);
514 tb->setVisibility(visibility);
516 if (visibility & Toolbars::TOP) {
518 addToolBarBreak(Qt::TopToolBarArea);
519 addToolBar(Qt::TopToolBarArea, tb);
522 if (visibility & Toolbars::BOTTOM) {
523 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
524 #if (QT_VERSION >= 0x040202)
525 addToolBarBreak(Qt::BottomToolBarArea);
527 addToolBar(Qt::BottomToolBarArea, tb);
530 if (visibility & Toolbars::LEFT) {
531 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
532 #if (QT_VERSION >= 0x040202)
533 addToolBarBreak(Qt::LeftToolBarArea);
535 addToolBar(Qt::LeftToolBarArea, tb);
538 if (visibility & Toolbars::RIGHT) {
539 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
540 #if (QT_VERSION >= 0x040202)
541 addToolBarBreak(Qt::RightToolBarArea);
543 addToolBar(Qt::RightToolBarArea, tb);
546 if (visibility & Toolbars::ON)
547 tb->setVisible(true);
552 TocModels & GuiView::tocModels()
554 return d.toc_models_;
558 void GuiView::setFocus()
560 LYXERR(Debug::DEBUG, "GuiView::setFocus()" << this);
561 // Make sure LyXFunc points to the correct view.
562 guiApp->setCurrentView(this);
563 QMainWindow::setFocus();
564 if (d.current_work_area_)
565 d.current_work_area_->setFocus();
569 QMenu * GuiView::createPopupMenu()
571 return d.toolBarPopup(this);
575 void GuiView::showEvent(QShowEvent * e)
577 LYXERR(Debug::GUI, "Passed Geometry "
578 << size().height() << "x" << size().width()
579 << "+" << pos().x() << "+" << pos().y());
581 if (d.splitter_->count() == 0)
582 // No work area, switch to the background widget.
585 QMainWindow::showEvent(e);
589 /** Destroy only all tabbed WorkAreas. Destruction of other WorkAreas
590 ** is responsibility of the container (e.g., dialog)
592 void GuiView::closeEvent(QCloseEvent * close_event)
594 LYXERR(Debug::DEBUG, "GuiView::closeEvent()");
599 // it can happen that this event arrives without selecting the view,
600 // e.g. when clicking the close button on a background window.
602 if (!closeWorkAreaAll()) {
604 close_event->ignore();
608 // Make sure that nothing will use this to be closed View.
609 guiApp->unregisterView(this);
611 if (isFullScreen()) {
612 // Switch off fullscreen before closing.
617 // Make sure the timer time out will not trigger a statusbar update.
618 d.statusbar_timer_.stop();
620 // Saving fullscreen requires additional tweaks in the toolbar code.
621 // It wouldn't also work under linux natively.
622 if (lyxrc.allow_geometry_session) {
623 // Save this window geometry and layout.
625 // Then the toolbar private states.
626 ToolbarMap::iterator end = d.toolbars_.end();
627 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
628 it->second->saveSession();
629 // Now take care of all other dialogs:
630 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
631 for (; it!= d.dialogs_.end(); ++it)
632 it->second->saveSession();
635 close_event->accept();
639 void GuiView::dragEnterEvent(QDragEnterEvent * event)
641 if (event->mimeData()->hasUrls())
643 /// \todo Ask lyx-devel is this is enough:
644 /// if (event->mimeData()->hasFormat("text/plain"))
645 /// event->acceptProposedAction();
649 void GuiView::dropEvent(QDropEvent * event)
651 QList<QUrl> files = event->mimeData()->urls();
655 LYXERR(Debug::GUI, "GuiView::dropEvent: got URLs!");
656 for (int i = 0; i != files.size(); ++i) {
657 string const file = os::internal_path(fromqstr(
658 files.at(i).toLocalFile()));
662 string const ext = support::getExtension(file);
663 vector<const Format *> found_formats;
665 // Find all formats that have the correct extension.
666 vector<const Format *> const & import_formats
667 = theConverters().importableFormats();
668 vector<const Format *>::const_iterator it = import_formats.begin();
669 for (; it != import_formats.end(); ++it)
670 if ((*it)->extension() == ext)
671 found_formats.push_back(*it);
674 if (found_formats.size() >= 1) {
675 if (found_formats.size() > 1) {
676 //FIXME: show a dialog to choose the correct importable format
678 "Multiple importable formats found, selecting first");
680 string const arg = found_formats[0]->name() + " " + file;
681 cmd = FuncRequest(LFUN_BUFFER_IMPORT, arg);
684 //FIXME: do we have to explicitly check whether it's a lyx file?
686 "No formats found, trying to open it as a lyx file");
687 cmd = FuncRequest(LFUN_FILE_OPEN, file);
690 // Asynchronously post the event. DropEvent usually come
691 // from the BufferView. But reloading a file might close
692 // the BufferView from within its own event handler.
693 guiApp->dispatchDelayed(cmd);
699 void GuiView::message(docstring const & str)
701 if (ForkedProcess::iAmAChild())
704 // call is moved to GUI-thread by GuiProgress
705 d.progress_->appendMessage(toqstr(str));
709 void GuiView::updateMessage(QString const & str)
711 statusBar()->showMessage(str);
712 d.statusbar_timer_.stop();
713 d.statusbar_timer_.start(3000);
717 void GuiView::smallSizedIcons()
719 setIconSize(QSize(d.smallIconSize, d.smallIconSize));
723 void GuiView::normalSizedIcons()
725 setIconSize(QSize(d.normalIconSize, d.normalIconSize));
729 void GuiView::bigSizedIcons()
731 setIconSize(QSize(d.bigIconSize, d.bigIconSize));
735 void GuiView::clearMessage()
740 d.statusbar_timer_.stop();
744 void GuiView::updateWindowTitle(GuiWorkArea * wa)
746 if (wa != d.current_work_area_)
748 setWindowTitle(qt_("LyX: ") + wa->windowTitle());
749 setWindowIconText(wa->windowIconText());
753 void GuiView::on_currentWorkAreaChanged(GuiWorkArea * wa)
756 disconnectBufferView();
757 connectBufferView(wa->bufferView());
758 connectBuffer(wa->bufferView().buffer());
759 d.current_work_area_ = wa;
760 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
761 this, SLOT(updateWindowTitle(GuiWorkArea *)));
762 updateWindowTitle(wa);
766 // The document settings needs to be reinitialised.
767 updateDialog("document", "");
769 // Buffer-dependent dialogs must be updated. This is done here because
770 // some dialogs require buffer()->text.
775 void GuiView::on_lastWorkAreaRemoved()
778 // We already are in a close event. Nothing more to do.
781 if (d.splitter_->count() > 1)
782 // We have a splitter so don't close anything.
785 // Reset and updates the dialogs.
786 d.toc_models_.reset(0);
787 updateDialog("document", "");
790 resetWindowTitleAndIconText();
792 if (lyxrc.open_buffers_in_tabs)
793 // Nothing more to do, the window should stay open.
796 if (guiApp->viewIds().size() > 1) {
802 // On Mac we also close the last window because the application stay
803 // resident in memory. On other platforms we don't close the last
804 // window because this would quit the application.
810 void GuiView::updateStatusBar()
812 // let the user see the explicit message
813 if (d.statusbar_timer_.isActive())
820 void GuiView::showMessage()
822 QString msg = toqstr(theGuiApp()->viewStatusMessage());
824 BufferView const * bv = currentBufferView();
826 msg = toqstr(bv->cursor().currentState());
828 msg = qt_("Welcome to LyX!");
830 statusBar()->showMessage(msg);
834 bool GuiView::event(QEvent * e)
838 // Useful debug code:
839 //case QEvent::ActivationChange:
840 //case QEvent::WindowDeactivate:
841 //case QEvent::Paint:
842 //case QEvent::Enter:
843 //case QEvent::Leave:
844 //case QEvent::HoverEnter:
845 //case QEvent::HoverLeave:
846 //case QEvent::HoverMove:
847 //case QEvent::StatusTip:
848 //case QEvent::DragEnter:
849 //case QEvent::DragLeave:
853 case QEvent::WindowActivate: {
854 GuiView * old_view = guiApp->currentView();
855 if (this == old_view) {
857 return QMainWindow::event(e);
859 if (old_view && old_view->currentBufferView()) {
860 // save current selection to the selection buffer to allow
861 // middle-button paste in this window.
862 cap::saveSelection(old_view->currentBufferView()->cursor());
864 guiApp->setCurrentView(this);
865 if (d.current_work_area_) {
866 BufferView & bv = d.current_work_area_->bufferView();
867 connectBufferView(bv);
868 connectBuffer(bv.buffer());
869 // The document structure, name and dialogs might have
870 // changed in another view.
872 // The document settings needs to be reinitialised.
873 updateDialog("document", "");
876 resetWindowTitleAndIconText();
879 return QMainWindow::event(e);
882 case QEvent::ShortcutOverride: {
885 #if (!defined Q_WS_X11) || (QT_VERSION >= 0x040500)
886 if (isFullScreen() && menuBar()->isHidden()) {
887 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
888 // FIXME: we should also try to detect special LyX shortcut such as
889 // Alt-P and Alt-M. Right now there is a hack in
890 // GuiWorkArea::processKeySym() that hides again the menubar for
892 if (ke->modifiers() & Qt::AltModifier && ke->key() != Qt::Key_Alt) {
894 return QMainWindow::event(e);
899 if (d.current_work_area_)
900 // Nothing special to do.
901 return QMainWindow::event(e);
903 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
904 // Let Qt handle menu access and the Tab keys to navigate keys to navigate
906 if (ke->modifiers() & Qt::AltModifier || ke->key() == Qt::Key_Tab
907 || ke->key() == Qt::Key_Backtab)
908 return QMainWindow::event(e);
910 // Allow processing of shortcuts that are allowed even when no Buffer
913 setKeySymbol(&sym, ke);
914 guiApp->processKeySym(sym, q_key_state(ke->modifiers()));
920 return QMainWindow::event(e);
924 void GuiView::resetWindowTitleAndIconText()
926 setWindowTitle(qt_("LyX"));
927 setWindowIconText(qt_("LyX"));
930 bool GuiView::focusNextPrevChild(bool /*next*/)
937 void GuiView::setBusy(bool busy)
939 if (d.current_work_area_) {
940 d.current_work_area_->setUpdatesEnabled(!busy);
942 d.current_work_area_->stopBlinkingCursor();
944 d.current_work_area_->startBlinkingCursor();
948 QApplication::setOverrideCursor(Qt::WaitCursor);
950 QApplication::restoreOverrideCursor();
954 GuiWorkArea * GuiView::workArea(Buffer & buffer)
956 if (currentWorkArea()
957 && ¤tWorkArea()->bufferView().buffer() == &buffer)
958 return (GuiWorkArea *) currentWorkArea();
959 if (TabWorkArea * twa = d.currentTabWorkArea())
960 return twa->workArea(buffer);
965 GuiWorkArea * GuiView::addWorkArea(Buffer & buffer)
967 // Automatically create a TabWorkArea if there are none yet.
968 TabWorkArea * tab_widget = d.splitter_->count()
969 ? d.currentTabWorkArea() : addTabWorkArea();
970 return tab_widget->addWorkArea(buffer, *this);
974 TabWorkArea * GuiView::addTabWorkArea()
976 TabWorkArea * twa = new TabWorkArea;
977 QObject::connect(twa, SIGNAL(currentWorkAreaChanged(GuiWorkArea *)),
978 this, SLOT(on_currentWorkAreaChanged(GuiWorkArea *)));
979 QObject::connect(twa, SIGNAL(lastWorkAreaRemoved()),
980 this, SLOT(on_lastWorkAreaRemoved()));
982 d.splitter_->addWidget(twa);
983 d.stack_widget_->setCurrentWidget(d.splitter_);
988 GuiWorkArea const * GuiView::currentWorkArea() const
990 return d.current_work_area_;
994 GuiWorkArea * GuiView::currentWorkArea()
996 return d.current_work_area_;
1000 GuiWorkArea const * GuiView::currentMainWorkArea() const
1002 if (d.currentTabWorkArea() == NULL)
1004 return d.currentTabWorkArea()->currentWorkArea();
1008 GuiWorkArea * GuiView::currentMainWorkArea()
1010 if (d.currentTabWorkArea() == NULL)
1012 return d.currentTabWorkArea()->currentWorkArea();
1016 void GuiView::setCurrentWorkArea(GuiWorkArea * wa)
1018 LYXERR(Debug::DEBUG, "Setting current wa: " << wa << endl);
1020 d.current_work_area_ = NULL;
1024 GuiWorkArea * old_gwa = theGuiApp()->currentView()->currentWorkArea();
1028 if (currentBufferView())
1029 cap::saveSelection(currentBufferView()->cursor());
1031 theGuiApp()->setCurrentView(this);
1032 d.current_work_area_ = wa;
1033 for (int i = 0; i != d.splitter_->count(); ++i) {
1034 if (d.tabWorkArea(i)->setCurrentWorkArea(wa)) {
1035 //if (d.current_main_work_area_)
1036 // d.current_main_work_area_->setFrameStyle(QFrame::NoFrame);
1037 d.current_main_work_area_ = wa;
1038 //d.current_main_work_area_->setFrameStyle(QFrame::Box | QFrame::Plain);
1039 //d.current_main_work_area_->setLineWidth(2);
1040 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() << ", Current main wa: " << currentMainWorkArea());
1044 LYXERR(Debug::DEBUG, "This is not a tabbed wa");
1045 on_currentWorkAreaChanged(wa);
1046 BufferView & bv = wa->bufferView();
1047 bv.cursor().fixIfBroken();
1049 wa->setUpdatesEnabled(true);
1050 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() << ", Current main wa: " << currentMainWorkArea());
1054 void GuiView::removeWorkArea(GuiWorkArea * wa)
1056 LASSERT(wa, return);
1057 if (wa == d.current_work_area_) {
1059 disconnectBufferView();
1060 d.current_work_area_ = 0;
1061 d.current_main_work_area_ = 0;
1064 bool found_twa = false;
1065 for (int i = 0; i != d.splitter_->count(); ++i) {
1066 TabWorkArea * twa = d.tabWorkArea(i);
1067 if (twa->removeWorkArea(wa)) {
1068 // Found in this tab group, and deleted the GuiWorkArea.
1070 if (twa->count() != 0) {
1071 if (d.current_work_area_ == 0)
1072 // This means that we are closing the current GuiWorkArea, so
1073 // switch to the next GuiWorkArea in the found TabWorkArea.
1074 setCurrentWorkArea(twa->currentWorkArea());
1076 // No more WorkAreas in this tab group, so delete it.
1083 // It is not a tabbed work area (i.e., the search work area), so it
1084 // should be deleted by other means.
1085 LASSERT(found_twa, /* */);
1087 if (d.current_work_area_ == 0) {
1088 if (d.splitter_->count() != 0) {
1089 TabWorkArea * twa = d.currentTabWorkArea();
1090 setCurrentWorkArea(twa->currentWorkArea());
1092 // No more work areas, switch to the background widget.
1093 setCurrentWorkArea(0);
1099 LayoutBox * GuiView::getLayoutDialog() const
1105 void GuiView::updateLayoutList()
1108 d.layout_->updateContents(false);
1112 void GuiView::updateToolbars()
1114 ToolbarMap::iterator end = d.toolbars_.end();
1115 if (d.current_work_area_) {
1117 d.current_work_area_->bufferView().cursor().inMathed();
1119 lyx::getStatus(FuncRequest(LFUN_LAYOUT_TABULAR)).enabled();
1121 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).enabled() &&
1122 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).onoff(true);
1123 bool const mathmacrotemplate =
1124 lyx::getStatus(FuncRequest(LFUN_IN_MATHMACROTEMPLATE)).enabled();
1126 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1127 it->second->update(math, table, review, mathmacrotemplate);
1129 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1130 it->second->update(false, false, false, false);
1134 void GuiView::setBuffer(Buffer * newBuffer)
1136 LYXERR(Debug::DEBUG, "Setting buffer: " << newBuffer << endl);
1137 LASSERT(newBuffer, return);
1140 GuiWorkArea * wa = workArea(*newBuffer);
1142 newBuffer->masterBuffer()->updateLabels();
1143 wa = addWorkArea(*newBuffer);
1145 //Disconnect the old buffer...there's no new one.
1148 connectBuffer(*newBuffer);
1149 connectBufferView(wa->bufferView());
1150 setCurrentWorkArea(wa);
1156 void GuiView::connectBuffer(Buffer & buf)
1158 buf.setGuiDelegate(this);
1162 void GuiView::disconnectBuffer()
1164 if (d.current_work_area_)
1165 d.current_work_area_->bufferView().buffer().setGuiDelegate(0);
1169 void GuiView::connectBufferView(BufferView & bv)
1171 bv.setGuiDelegate(this);
1175 void GuiView::disconnectBufferView()
1177 if (d.current_work_area_)
1178 d.current_work_area_->bufferView().setGuiDelegate(0);
1182 void GuiView::errors(string const & error_type, bool from_master)
1184 ErrorList & el = from_master ?
1185 documentBufferView()->buffer().masterBuffer()->errorList(error_type)
1186 : documentBufferView()->buffer().errorList(error_type);
1187 string data = error_type;
1189 data = "from_master|" + error_type;
1191 showDialog("errorlist", data);
1195 void GuiView::updateTocItem(string const & type, DocIterator const & dit)
1197 d.toc_models_.updateItem(toqstr(type), dit);
1201 void GuiView::structureChanged()
1203 d.toc_models_.reset(documentBufferView());
1204 // Navigator needs more than a simple update in this case. It needs to be
1206 updateDialog("toc", "");
1210 void GuiView::updateDialog(string const & name, string const & data)
1212 if (!isDialogVisible(name))
1215 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
1216 if (it == d.dialogs_.end())
1219 Dialog * const dialog = it->second.get();
1220 if (dialog->isVisibleView())
1221 dialog->initialiseParams(data);
1225 BufferView * GuiView::documentBufferView()
1227 return currentMainWorkArea()
1228 ? ¤tMainWorkArea()->bufferView()
1233 BufferView const * GuiView::documentBufferView() const
1235 return currentMainWorkArea()
1236 ? ¤tMainWorkArea()->bufferView()
1241 BufferView * GuiView::currentBufferView()
1243 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1247 BufferView const * GuiView::currentBufferView() const
1249 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1253 static docstring saveAndDestroyBuffer(Buffer * buffer, FileName const & fname)
1256 FileName const tmp_ret = FileName::tempName("lyxauto");
1257 if (!tmp_ret.empty()) {
1258 if (buffer->writeFile(tmp_ret))
1259 failed = !tmp_ret.moveTo(fname);
1262 // failed to write/rename tmp_ret so try writing direct
1263 failed = buffer->writeFile(fname);
1267 ? _("Automatic save failed!")
1268 : _("Automatic save done.");
1272 void GuiView::autoSave()
1274 LYXERR(Debug::INFO, "Running autoSave()");
1276 Buffer * buffer = documentBufferView()
1277 ? &documentBufferView()->buffer() : 0;
1281 #if (QT_VERSION >= 0x040400)
1282 QFuture<docstring> f = QtConcurrent::run(saveAndDestroyBuffer, buffer->clone(),
1283 buffer->getAutosaveFilename());
1284 d.autosave_watcher_.setFuture(f);
1291 void GuiView::resetAutosaveTimers()
1294 d.autosave_timeout_.restart();
1298 bool GuiView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1301 Buffer * buf = currentBufferView()
1302 ? ¤tBufferView()->buffer() : 0;
1303 Buffer * doc_buffer = documentBufferView()
1304 ? &(documentBufferView()->buffer()) : 0;
1306 // Check whether we need a buffer
1307 if (!lyxaction.funcHasFlag(cmd.action, LyXAction::NoBuffer) && !buf) {
1308 // no, exit directly
1309 flag.message(from_utf8(N_("Command not allowed with"
1310 "out any document open")));
1311 flag.setEnabled(false);
1315 if (cmd.origin == FuncRequest::TOC) {
1316 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
1318 if (toc->getStatus(documentBufferView()->cursor(), cmd, fs))
1321 flag.setEnabled(false);
1325 switch(cmd.action) {
1326 case LFUN_BUFFER_IMPORT:
1329 case LFUN_MASTER_BUFFER_UPDATE:
1330 case LFUN_MASTER_BUFFER_VIEW:
1331 enable = doc_buffer && doc_buffer->parent() != 0
1332 && !d.preview_watcher_.isRunning();
1335 case LFUN_BUFFER_UPDATE:
1336 case LFUN_BUFFER_VIEW: {
1337 if (!doc_buffer || d.preview_watcher_.isRunning()) {
1341 string format = to_utf8(cmd.argument());
1342 if (cmd.argument().empty())
1343 format = doc_buffer->getDefaultOutputFormat();
1344 enable = doc_buffer->isExportableFormat(format);
1348 case LFUN_BUFFER_RELOAD:
1349 enable = doc_buffer && !doc_buffer->isUnnamed()
1350 && doc_buffer->fileName().exists()
1351 && (!doc_buffer->isClean()
1352 || doc_buffer->isExternallyModified(Buffer::timestamp_method));
1355 case LFUN_BUFFER_CHILD_OPEN:
1356 enable = doc_buffer;
1359 case LFUN_BUFFER_WRITE:
1360 enable = doc_buffer && (doc_buffer->isUnnamed() || !doc_buffer->isClean());
1363 //FIXME: This LFUN should be moved to GuiApplication.
1364 case LFUN_BUFFER_WRITE_ALL: {
1365 // We enable the command only if there are some modified buffers
1366 Buffer * first = theBufferList().first();
1371 // We cannot use a for loop as the buffer list is a cycle.
1373 if (!b->isClean()) {
1377 b = theBufferList().next(b);
1378 } while (b != first);
1382 case LFUN_BUFFER_WRITE_AS:
1383 enable = doc_buffer;
1386 case LFUN_BUFFER_CLOSE:
1387 enable = doc_buffer;
1390 case LFUN_BUFFER_CLOSE_ALL:
1391 enable = theBufferList().last() != theBufferList().first();
1394 case LFUN_SPLIT_VIEW:
1395 if (cmd.getArg(0) == "vertical")
1396 enable = doc_buffer && (d.splitter_->count() == 1 ||
1397 d.splitter_->orientation() == Qt::Vertical);
1399 enable = doc_buffer && (d.splitter_->count() == 1 ||
1400 d.splitter_->orientation() == Qt::Horizontal);
1403 case LFUN_CLOSE_TAB_GROUP:
1404 enable = d.currentTabWorkArea();
1407 case LFUN_TOOLBAR_TOGGLE:
1408 if (GuiToolbar * t = toolbar(cmd.getArg(0)))
1409 flag.setOnOff(t->isVisible());
1412 case LFUN_DROP_LAYOUTS_CHOICE:
1416 case LFUN_UI_TOGGLE:
1417 flag.setOnOff(isFullScreen());
1420 case LFUN_DIALOG_DISCONNECT_INSET:
1423 case LFUN_DIALOG_HIDE:
1424 // FIXME: should we check if the dialog is shown?
1427 case LFUN_DIALOG_TOGGLE:
1428 flag.setOnOff(isDialogVisible(cmd.getArg(0)));
1429 // fall through to set "enable"
1430 case LFUN_DIALOG_SHOW: {
1431 string const name = cmd.getArg(0);
1433 enable = name == "aboutlyx"
1434 || name == "file" //FIXME: should be removed.
1436 || name == "texinfo"
1437 || name == "compare";
1438 else if (name == "print")
1439 enable = doc_buffer->isExportable("dvi")
1440 && lyxrc.print_command != "none";
1441 else if (name == "character" || name == "symbols") {
1442 if (!buf || buf->isReadonly()
1443 || !currentBufferView()->cursor().inTexted())
1446 // FIXME we should consider passthru
1448 Inset const & in = currentBufferView()->cursor().inset();
1449 enable = !in.getLayout().isPassThru();
1452 else if (name == "latexlog")
1453 enable = FileName(doc_buffer->logName()).isReadableFile();
1454 else if (name == "spellchecker")
1455 enable = theSpellChecker() && !doc_buffer->isReadonly();
1456 else if (name == "vclog")
1457 enable = doc_buffer->lyxvc().inUse();
1461 case LFUN_DIALOG_UPDATE: {
1462 string const name = cmd.getArg(0);
1464 enable = name == "prefs";
1468 case LFUN_COMMAND_EXECUTE:
1470 case LFUN_MENU_OPEN:
1471 // Nothing to check.
1474 case LFUN_COMPLETION_INLINE:
1475 if (!d.current_work_area_
1476 || !d.current_work_area_->completer().inlinePossible(
1477 currentBufferView()->cursor()))
1481 case LFUN_COMPLETION_POPUP:
1482 if (!d.current_work_area_
1483 || !d.current_work_area_->completer().popupPossible(
1484 currentBufferView()->cursor()))
1488 case LFUN_COMPLETION_COMPLETE:
1489 if (!d.current_work_area_
1490 || !d.current_work_area_->completer().inlinePossible(
1491 currentBufferView()->cursor()))
1495 case LFUN_COMPLETION_ACCEPT:
1496 if (!d.current_work_area_
1497 || (!d.current_work_area_->completer().popupVisible()
1498 && !d.current_work_area_->completer().inlineVisible()
1499 && !d.current_work_area_->completer().completionAvailable()))
1503 case LFUN_COMPLETION_CANCEL:
1504 if (!d.current_work_area_
1505 || (!d.current_work_area_->completer().popupVisible()
1506 && !d.current_work_area_->completer().inlineVisible()))
1510 case LFUN_BUFFER_ZOOM_OUT:
1511 enable = doc_buffer && lyxrc.zoom > 10;
1514 case LFUN_BUFFER_ZOOM_IN:
1515 enable = doc_buffer;
1518 case LFUN_BUFFER_NEXT:
1519 case LFUN_BUFFER_PREVIOUS:
1520 // FIXME: should we check is there is an previous or next buffer?
1522 case LFUN_BUFFER_SWITCH:
1523 // toggle on the current buffer, but do not toggle off
1524 // the other ones (is that a good idea?)
1526 && to_utf8(cmd.argument()) == doc_buffer->absFileName())
1527 flag.setOnOff(true);
1530 case LFUN_VC_REGISTER:
1531 enable = doc_buffer && !doc_buffer->lyxvc().inUse();
1533 case LFUN_VC_CHECK_IN:
1534 enable = doc_buffer && doc_buffer->lyxvc().checkInEnabled();
1536 case LFUN_VC_CHECK_OUT:
1537 enable = doc_buffer && doc_buffer->lyxvc().checkOutEnabled();
1539 case LFUN_VC_LOCKING_TOGGLE:
1540 enable = doc_buffer && !doc_buffer->isReadonly()
1541 && doc_buffer->lyxvc().lockingToggleEnabled();
1542 flag.setOnOff(enable && !doc_buffer->lyxvc().locker().empty());
1544 case LFUN_VC_REVERT:
1545 enable = doc_buffer && doc_buffer->lyxvc().inUse();
1547 case LFUN_VC_UNDO_LAST:
1548 enable = doc_buffer && doc_buffer->lyxvc().undoLastEnabled();
1550 case LFUN_VC_REPO_UPDATE:
1551 enable = doc_buffer && doc_buffer->lyxvc().inUse();
1553 case LFUN_VC_COMMAND: {
1554 if (cmd.argument().empty())
1556 if (!doc_buffer && contains(cmd.getArg(0), 'D'))
1561 case LFUN_SERVER_GOTO_FILE_ROW:
1569 flag.setEnabled(false);
1575 static FileName selectTemplateFile()
1577 FileDialog dlg(qt_("Select template file"));
1578 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1579 dlg.setButton1(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
1581 FileDialog::Result result = dlg.open(toqstr(lyxrc.template_path),
1582 QStringList(qt_("LyX Documents (*.lyx)")));
1584 if (result.first == FileDialog::Later)
1586 if (result.second.isEmpty())
1588 return FileName(fromqstr(result.second));
1592 Buffer * GuiView::loadDocument(FileName const & filename, bool tolastfiles)
1596 Buffer * newBuffer = checkAndLoadLyXFile(filename);
1599 message(_("Document not loaded."));
1604 setBuffer(newBuffer);
1606 // scroll to the position when the file was last closed
1607 if (lyxrc.use_lastfilepos) {
1608 LastFilePosSection::FilePos filepos =
1609 theSession().lastFilePos().load(filename);
1610 documentBufferView()->moveToPosition(filepos.pit, filepos.pos, 0, 0);
1614 theSession().lastFiles().add(filename);
1621 void GuiView::openDocument(string const & fname)
1623 string initpath = lyxrc.document_path;
1625 if (documentBufferView()) {
1626 string const trypath = documentBufferView()->buffer().filePath();
1627 // If directory is writeable, use this as default.
1628 if (FileName(trypath).isDirWritable())
1634 if (fname.empty()) {
1635 FileDialog dlg(qt_("Select document to open"), LFUN_FILE_OPEN);
1636 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1637 dlg.setButton2(qt_("Examples|#E#e"),
1638 toqstr(addPath(package().system_support().absFilename(), "examples")));
1640 QStringList filter(qt_("LyX Documents (*.lyx)"));
1641 filter << qt_("LyX-1.3.x Documents (*.lyx13)")
1642 << qt_("LyX-1.4.x Documents (*.lyx14)")
1643 << qt_("LyX-1.5.x Documents (*.lyx15)")
1644 << qt_("LyX-1.6.x Documents (*.lyx16)");
1645 FileDialog::Result result =
1646 dlg.open(toqstr(initpath), filter);
1648 if (result.first == FileDialog::Later)
1651 filename = fromqstr(result.second);
1653 // check selected filename
1654 if (filename.empty()) {
1655 message(_("Canceled."));
1661 // get absolute path of file and add ".lyx" to the filename if
1663 FileName const fullname =
1664 fileSearch(string(), filename, "lyx", support::may_not_exist);
1665 if (!fullname.empty())
1666 filename = fullname.absFilename();
1668 if (!fullname.onlyPath().isDirectory()) {
1669 Alert::warning(_("Invalid filename"),
1670 bformat(_("The directory in the given path\n%1$s\ndoes not exist."),
1671 from_utf8(fullname.absFilename())));
1674 // if the file doesn't exist, let the user create one
1675 if (!fullname.exists()) {
1676 // the user specifically chose this name. Believe him.
1677 Buffer * const b = newFile(filename, string(), true);
1683 docstring const disp_fn = makeDisplayPath(filename);
1684 message(bformat(_("Opening document %1$s..."), disp_fn));
1687 Buffer * buf = loadDocument(fullname);
1689 buf->updateLabels();
1691 buf->errors("Parse");
1692 str2 = bformat(_("Document %1$s opened."), disp_fn);
1693 if (buf->lyxvc().inUse())
1694 str2 += " " + from_utf8(buf->lyxvc().versionString()) +
1695 " " + _("Version control detected.");
1697 str2 = bformat(_("Could not open document %1$s"), disp_fn);
1702 // FIXME: clean that
1703 static bool import(GuiView * lv, FileName const & filename,
1704 string const & format, ErrorList & errorList)
1706 FileName const lyxfile(support::changeExtension(filename.absFilename(), ".lyx"));
1708 string loader_format;
1709 vector<string> loaders = theConverters().loaders();
1710 if (find(loaders.begin(), loaders.end(), format) == loaders.end()) {
1711 for (vector<string>::const_iterator it = loaders.begin();
1712 it != loaders.end(); ++it) {
1713 if (!theConverters().isReachable(format, *it))
1716 string const tofile =
1717 support::changeExtension(filename.absFilename(),
1718 formats.extension(*it));
1719 if (!theConverters().convert(0, filename, FileName(tofile),
1720 filename, format, *it, errorList))
1722 loader_format = *it;
1725 if (loader_format.empty()) {
1726 frontend::Alert::error(_("Couldn't import file"),
1727 bformat(_("No information for importing the format %1$s."),
1728 formats.prettyName(format)));
1732 loader_format = format;
1734 if (loader_format == "lyx") {
1735 Buffer * buf = lv->loadDocument(lyxfile);
1738 buf->updateLabels();
1740 buf->errors("Parse");
1742 Buffer * const b = newFile(lyxfile.absFilename(), string(), true);
1746 bool as_paragraphs = loader_format == "textparagraph";
1747 string filename2 = (loader_format == format) ? filename.absFilename()
1748 : support::changeExtension(filename.absFilename(),
1749 formats.extension(loader_format));
1750 lv->currentBufferView()->insertPlaintextFile(FileName(filename2),
1752 guiApp->setCurrentView(lv);
1753 lyx::dispatch(FuncRequest(LFUN_MARK_OFF));
1760 void GuiView::importDocument(string const & argument)
1763 string filename = split(argument, format, ' ');
1765 LYXERR(Debug::INFO, format << " file: " << filename);
1767 // need user interaction
1768 if (filename.empty()) {
1769 string initpath = lyxrc.document_path;
1770 if (documentBufferView()) {
1771 string const trypath = documentBufferView()->buffer().filePath();
1772 // If directory is writeable, use this as default.
1773 if (FileName(trypath).isDirWritable())
1777 docstring const text = bformat(_("Select %1$s file to import"),
1778 formats.prettyName(format));
1780 FileDialog dlg(toqstr(text), LFUN_BUFFER_IMPORT);
1781 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1782 dlg.setButton2(qt_("Examples|#E#e"),
1783 toqstr(addPath(package().system_support().absFilename(), "examples")));
1785 docstring filter = formats.prettyName(format);
1788 filter += from_utf8(formats.extension(format));
1791 FileDialog::Result result =
1792 dlg.open(toqstr(initpath), fileFilters(toqstr(filter)));
1794 if (result.first == FileDialog::Later)
1797 filename = fromqstr(result.second);
1799 // check selected filename
1800 if (filename.empty())
1801 message(_("Canceled."));
1804 if (filename.empty())
1807 // get absolute path of file
1808 FileName const fullname(support::makeAbsPath(filename));
1810 FileName const lyxfile(support::changeExtension(fullname.absFilename(), ".lyx"));
1812 // Check if the document already is open
1813 Buffer * buf = theBufferList().getBuffer(lyxfile);
1816 if (!closeBuffer()) {
1817 message(_("Canceled."));
1822 docstring const displaypath = makeDisplayPath(lyxfile.absFilename(), 30);
1824 // if the file exists already, and we didn't do
1825 // -i lyx thefile.lyx, warn
1826 if (lyxfile.exists() && fullname != lyxfile) {
1828 docstring text = bformat(_("The document %1$s already exists.\n\n"
1829 "Do you want to overwrite that document?"), displaypath);
1830 int const ret = Alert::prompt(_("Overwrite document?"),
1831 text, 0, 1, _("&Overwrite"), _("&Cancel"));
1834 message(_("Canceled."));
1839 message(bformat(_("Importing %1$s..."), displaypath));
1840 ErrorList errorList;
1841 if (import(this, fullname, format, errorList))
1842 message(_("imported."));
1844 message(_("file not imported!"));
1846 // FIXME (Abdel 12/08/06): Is there a need to display the error list here?
1850 void GuiView::newDocument(string const & filename, bool from_template)
1852 FileName initpath(lyxrc.document_path);
1853 if (documentBufferView()) {
1854 FileName const trypath(documentBufferView()->buffer().filePath());
1855 // If directory is writeable, use this as default.
1856 if (trypath.isDirWritable())
1860 string templatefile;
1861 if (from_template) {
1862 templatefile = selectTemplateFile().absFilename();
1863 if (templatefile.empty())
1868 if (filename.empty())
1869 b = newUnnamedFile(initpath, to_utf8(_("newfile")), templatefile);
1871 b = newFile(filename, templatefile, true);
1876 // If no new document could be created, it is unsure
1877 // whether there is a valid BufferView.
1878 if (currentBufferView())
1879 // Ensure the cursor is correctly positioned on screen.
1880 currentBufferView()->showCursor();
1884 void GuiView::insertLyXFile(docstring const & fname)
1886 BufferView * bv = documentBufferView();
1891 FileName filename(to_utf8(fname));
1893 if (!filename.empty()) {
1894 bv->insertLyXFile(filename);
1898 // Launch a file browser
1900 string initpath = lyxrc.document_path;
1901 string const trypath = bv->buffer().filePath();
1902 // If directory is writeable, use this as default.
1903 if (FileName(trypath).isDirWritable())
1907 FileDialog dlg(qt_("Select LyX document to insert"), LFUN_FILE_INSERT);
1908 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1909 dlg.setButton2(qt_("Examples|#E#e"),
1910 toqstr(addPath(package().system_support().absFilename(),
1913 FileDialog::Result result = dlg.open(toqstr(initpath),
1914 QStringList(qt_("LyX Documents (*.lyx)")));
1916 if (result.first == FileDialog::Later)
1920 filename.set(fromqstr(result.second));
1922 // check selected filename
1923 if (filename.empty()) {
1924 // emit message signal.
1925 message(_("Canceled."));
1929 bv->insertLyXFile(filename);
1933 void GuiView::insertPlaintextFile(docstring const & fname,
1936 BufferView * bv = documentBufferView();
1940 if (!fname.empty() && !FileName::isAbsolute(to_utf8(fname))) {
1941 message(_("Absolute filename expected."));
1946 FileName filename(to_utf8(fname));
1948 if (!filename.empty()) {
1949 bv->insertPlaintextFile(filename, asParagraph);
1953 FileDialog dlg(qt_("Select file to insert"), (asParagraph ?
1954 LFUN_FILE_INSERT_PLAINTEXT_PARA : LFUN_FILE_INSERT_PLAINTEXT));
1956 FileDialog::Result result = dlg.open(toqstr(bv->buffer().filePath()),
1957 QStringList(qt_("All Files (*)")));
1959 if (result.first == FileDialog::Later)
1963 filename.set(fromqstr(result.second));
1965 // check selected filename
1966 if (filename.empty()) {
1967 // emit message signal.
1968 message(_("Canceled."));
1972 bv->insertPlaintextFile(filename, asParagraph);
1976 bool GuiView::renameBuffer(Buffer & b, docstring const & newname)
1978 FileName fname = b.fileName();
1979 FileName const oldname = fname;
1981 if (!newname.empty()) {
1983 fname = support::makeAbsPath(to_utf8(newname), oldname.onlyPath().absFilename());
1985 // Switch to this Buffer.
1988 // No argument? Ask user through dialog.
1990 FileDialog dlg(qt_("Choose a filename to save document as"),
1991 LFUN_BUFFER_WRITE_AS);
1992 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1993 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
1995 if (!isLyXFilename(fname.absFilename()))
1996 fname.changeExtension(".lyx");
1998 FileDialog::Result result =
1999 dlg.save(toqstr(fname.onlyPath().absFilename()),
2000 QStringList(qt_("LyX Documents (*.lyx)")),
2001 toqstr(fname.onlyFileName()));
2003 if (result.first == FileDialog::Later)
2006 fname.set(fromqstr(result.second));
2011 if (!isLyXFilename(fname.absFilename()))
2012 fname.changeExtension(".lyx");
2015 if (FileName(fname).exists()) {
2016 docstring const file = makeDisplayPath(fname.absFilename(), 30);
2017 docstring text = bformat(_("The document %1$s already "
2018 "exists.\n\nDo you want to "
2019 "overwrite that document?"),
2021 int const ret = Alert::prompt(_("Overwrite document?"),
2022 text, 0, 2, _("&Overwrite"), _("&Rename"), _("&Cancel"));
2025 case 1: return renameBuffer(b, docstring());
2026 case 2: return false;
2030 FileName oldauto = b.getAutosaveFilename();
2032 // Ok, change the name of the buffer
2033 b.setFileName(fname.absFilename());
2035 bool unnamed = b.isUnnamed();
2036 b.setUnnamed(false);
2037 b.saveCheckSum(fname);
2039 // bring the autosave file with us, just in case.
2040 b.moveAutosaveFile(oldauto);
2042 if (!saveBuffer(b)) {
2043 oldauto = b.getAutosaveFilename();
2044 b.setFileName(oldname.absFilename());
2045 b.setUnnamed(unnamed);
2046 b.saveCheckSum(oldname);
2047 b.moveAutosaveFile(oldauto);
2055 bool GuiView::saveBuffer(Buffer & b)
2057 if (workArea(b) && workArea(b)->inDialogMode())
2061 return renameBuffer(b, docstring());
2064 theSession().lastFiles().add(b.fileName());
2068 // Switch to this Buffer.
2071 // FIXME: we don't tell the user *WHY* the save failed !!
2072 docstring const file = makeDisplayPath(b.absFileName(), 30);
2073 docstring text = bformat(_("The document %1$s could not be saved.\n\n"
2074 "Do you want to rename the document and "
2075 "try again?"), file);
2076 int const ret = Alert::prompt(_("Rename and save?"),
2077 text, 0, 2, _("&Rename"), _("&Retry"), _("&Cancel"));
2080 if (!renameBuffer(b, docstring()))
2089 return saveBuffer(b);
2093 bool GuiView::hideWorkArea(GuiWorkArea * wa)
2095 return closeWorkArea(wa, false);
2099 bool GuiView::closeWorkArea(GuiWorkArea * wa)
2101 Buffer & buf = wa->bufferView().buffer();
2102 return closeWorkArea(wa, !buf.parent());
2106 bool GuiView::closeBuffer()
2108 GuiWorkArea * wa = currentMainWorkArea();
2109 Buffer & buf = wa->bufferView().buffer();
2110 return wa && closeWorkArea(wa, !buf.parent());
2114 void GuiView::writeSession() const {
2115 GuiWorkArea const * active_wa = currentMainWorkArea();
2116 for (int i = 0; i < d.splitter_->count(); ++i) {
2117 TabWorkArea * twa = d.tabWorkArea(i);
2118 for (int j = 0; j < twa->count(); ++j) {
2119 GuiWorkArea * wa = static_cast<GuiWorkArea *>(twa->widget(j));
2120 Buffer & buf = wa->bufferView().buffer();
2121 theSession().lastOpened().add(buf.fileName(), wa == active_wa);
2127 bool GuiView::closeBufferAll()
2129 // Close the workareas in all other views
2130 QList<int> const ids = guiApp->viewIds();
2131 for (int i = 0; i != ids.size(); ++i) {
2132 if (id_ != ids[i] && !guiApp->view(ids[i]).closeWorkAreaAll())
2136 // Close our own workareas
2137 if (!closeWorkAreaAll())
2140 // Now close the hidden buffers. We prevent hidden buffers from being
2141 // dirty, so we can just close them.
2142 theBufferList().closeAll();
2147 bool GuiView::closeWorkAreaAll()
2149 setCurrentWorkArea(currentMainWorkArea());
2151 // We might be in a situation that there is still a tabWorkArea, but
2152 // there are no tabs anymore. This can happen when we get here after a
2153 // TabWorkArea::lastWorkAreaRemoved() signal. Therefore we count how
2154 // many TabWorkArea's have no documents anymore.
2157 // We have to call count() each time, because it can happen that
2158 // more than one splitter will disappear in one iteration (bug 5998).
2159 for (; d.splitter_->count() > empty_twa; ) {
2160 TabWorkArea * twa = d.tabWorkArea(empty_twa);
2162 if (twa->count() == 0)
2165 setCurrentWorkArea(twa->currentWorkArea());
2166 if (!closeTabWorkArea(twa))
2174 bool GuiView::closeWorkArea(GuiWorkArea * wa, bool close_buffer)
2179 Buffer & buf = wa->bufferView().buffer();
2182 return closeBuffer(buf);
2184 if (!inMultiTabs(wa))
2185 if (!saveBufferIfNeeded(buf, true))
2193 bool GuiView::closeBuffer(Buffer & buf)
2195 // If we are in a close_event all children will be closed in some time,
2196 // so no need to do it here. This will ensure that the children end up
2197 // in the session file in the correct order. If we close the master
2198 // buffer, we can close or release the child buffers here too.
2200 vector<Buffer *> clist = buf.getChildren(false);
2201 for (vector<Buffer *>::const_iterator it = clist.begin();
2202 it != clist.end(); ++it) {
2203 // If a child is dirty, do not close
2204 // without user intervention
2205 //FIXME: should we look in other tabworkareas?
2206 Buffer * child_buf = *it;
2207 GuiWorkArea * child_wa = workArea(*child_buf);
2209 if (!closeWorkArea(child_wa, true))
2212 theBufferList().releaseChild(&buf, child_buf);
2215 // goto bookmark to update bookmark pit.
2216 //FIXME: we should update only the bookmarks related to this buffer!
2217 LYXERR(Debug::DEBUG, "GuiView::closeBuffer()");
2218 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
2219 theLyXFunc().gotoBookmark(i+1, false, false);
2221 if (saveBufferIfNeeded(buf, false)) {
2222 theBufferList().release(&buf);
2229 bool GuiView::closeTabWorkArea(TabWorkArea * twa)
2231 while (twa == d.currentTabWorkArea()) {
2232 twa->setCurrentIndex(twa->count()-1);
2234 GuiWorkArea * wa = twa->currentWorkArea();
2235 Buffer & b = wa->bufferView().buffer();
2237 // We only want to close the buffer if the same buffer is not visible
2238 // in another view, and if this is not a child and if we are closing
2239 // a view (not a tabgroup).
2240 bool const close_buffer =
2241 !inMultiViews(wa) && !b.parent() && closing_;
2243 if (!closeWorkArea(wa, close_buffer))
2250 bool GuiView::saveBufferIfNeeded(Buffer & buf, bool hiding)
2252 if (buf.isClean() || buf.paragraphs().empty())
2255 // Switch to this Buffer.
2260 if (buf.isUnnamed())
2261 file = from_utf8(buf.fileName().onlyFileName());
2263 file = buf.fileName().displayName(30);
2265 // Bring this window to top before asking questions.
2270 if (hiding && buf.isUnnamed()) {
2271 docstring const text = bformat(_("The document %1$s has not been "
2272 "saved yet.\n\nDo you want to save "
2273 "the document?"), file);
2274 ret = Alert::prompt(_("Save new document?"),
2275 text, 0, 1, _("&Save"), _("&Cancel"));
2279 docstring const text = bformat(_("The document %1$s has unsaved changes."
2280 "\n\nDo you want to save the document or discard the changes?"), file);
2281 ret = Alert::prompt(_("Save changed document?"),
2282 text, 0, 2, _("&Save"), _("&Discard"), _("&Cancel"));
2287 if (!saveBuffer(buf))
2291 // if we crash after this we could
2292 // have no autosave file but I guess
2293 // this is really improbable (Jug)
2294 buf.removeAutosaveFile();
2296 // revert all changes
2297 buf.loadLyXFile(buf.fileName());
2307 bool GuiView::inMultiTabs(GuiWorkArea * wa)
2309 Buffer & buf = wa->bufferView().buffer();
2311 for (int i = 0; i != d.splitter_->count(); ++i) {
2312 GuiWorkArea * wa_ = d.tabWorkArea(i)->workArea(buf);
2313 if (wa_ && wa_ != wa)
2316 return inMultiViews(wa);
2320 bool GuiView::inMultiViews(GuiWorkArea * wa)
2322 QList<int> const ids = guiApp->viewIds();
2323 Buffer & buf = wa->bufferView().buffer();
2326 for (int i = 0; i != ids.size() && found_twa <= 1; ++i) {
2330 if (guiApp->view(ids[i]).workArea(buf))
2337 void GuiView::gotoNextOrPreviousBuffer(NextOrPrevious np)
2339 Buffer * const curbuf = documentBufferView()
2340 ? &documentBufferView()->buffer() : 0;
2341 Buffer * nextbuf = curbuf;
2343 if (np == NEXTBUFFER)
2344 nextbuf = theBufferList().next(nextbuf);
2346 nextbuf = theBufferList().previous(nextbuf);
2347 if (nextbuf == curbuf)
2353 if (workArea(*nextbuf))
2360 /// make sure the document is saved
2361 static bool ensureBufferClean(Buffer * buffer)
2363 LASSERT(buffer, return false);
2364 if (buffer->isClean() && !buffer->isUnnamed())
2367 docstring const file = buffer->fileName().displayName(30);
2370 if (!buffer->isUnnamed()) {
2371 text = bformat(_("The document %1$s has unsaved "
2372 "changes.\n\nDo you want to save "
2373 "the document?"), file);
2374 title = _("Save changed document?");
2377 text = bformat(_("The document %1$s has not been "
2378 "saved yet.\n\nDo you want to save "
2379 "the document?"), file);
2380 title = _("Save new document?");
2382 int const ret = Alert::prompt(title, text, 0, 1, _("&Save"), _("&Cancel"));
2385 dispatch(FuncRequest(LFUN_BUFFER_WRITE));
2387 return buffer->isClean() && !buffer->isUnnamed();
2391 void GuiView::reloadBuffer()
2393 Buffer * buf = &documentBufferView()->buffer();
2398 void GuiView::reloadBuffer(Buffer * buf)
2400 FileName filename = buf->fileName();
2401 Buffer const * master = buf->masterBuffer();
2402 bool const is_child = master != buf;
2403 // The user has already confirmed that the changes, if any, should
2404 // be discarded. So we just release the Buffer and don't call closeBuffer();
2405 theBufferList().release(buf);
2406 buf = loadDocument(filename);
2407 docstring const disp_fn = makeDisplayPath(filename.absFilename());
2410 // re-allocate master if necessary
2411 if (is_child && theBufferList().isLoaded(master)
2412 && buf->masterBuffer() != master)
2413 buf->setParent(master);
2414 buf->updateLabels();
2416 buf->errors("Parse");
2417 str = bformat(_("Document %1$s reloaded."), disp_fn);
2419 str = bformat(_("Could not reload document %1$s"), disp_fn);
2425 void GuiView::checkExternallyModifiedBuffers()
2427 BufferList::iterator bit = theBufferList().begin();
2428 BufferList::iterator const bend = theBufferList().end();
2429 for (; bit != bend; ++bit) {
2430 if ((*bit)->isExternallyModified(Buffer::checksum_method)) {
2431 docstring text = bformat(_("Document \n%1$s\n has been externally modified."
2432 " Reload now? Any local changes will be lost."),
2433 from_utf8((*bit)->absFileName()));
2434 int const ret = Alert::prompt(_("Reload externally changed document?"),
2435 text, 0, 1, _("&Reload"), _("&Cancel"));
2443 void GuiView::dispatchVC(FuncRequest const & cmd)
2445 Buffer * buffer = documentBufferView()
2446 ? &(documentBufferView()->buffer()) : 0;
2448 switch (cmd.action) {
2449 case LFUN_VC_REGISTER:
2450 if (!buffer || !ensureBufferClean(buffer))
2452 if (!buffer->lyxvc().inUse()) {
2453 if (buffer->lyxvc().registrer())
2458 case LFUN_VC_CHECK_IN:
2459 if (!buffer || !ensureBufferClean(buffer))
2461 if (buffer->lyxvc().inUse() && !buffer->isReadonly()) {
2462 message(from_utf8(buffer->lyxvc().checkIn()));
2467 case LFUN_VC_CHECK_OUT:
2468 if (!buffer || !ensureBufferClean(buffer))
2470 if (buffer->lyxvc().inUse()) {
2471 message(from_utf8(buffer->lyxvc().checkOut()));
2476 case LFUN_VC_LOCKING_TOGGLE:
2477 LASSERT(buffer, return);
2478 if (!ensureBufferClean(buffer) || buffer->isReadonly())
2480 if (buffer->lyxvc().inUse()) {
2481 string res = buffer->lyxvc().lockingToggle();
2483 frontend::Alert::error(_("Revision control error."),
2484 _("Error when setting the locking property."));
2486 message(from_utf8(res));
2492 case LFUN_VC_REVERT:
2493 LASSERT(buffer, return);
2494 buffer->lyxvc().revert();
2498 case LFUN_VC_UNDO_LAST:
2499 LASSERT(buffer, return);
2500 buffer->lyxvc().undoLast();
2504 case LFUN_VC_REPO_UPDATE:
2505 LASSERT(buffer, return);
2506 if (ensureBufferClean(buffer)) {
2507 string res = buffer->lyxvc().repoUpdate();
2508 message(from_utf8(res));
2509 checkExternallyModifiedBuffers();
2513 case LFUN_VC_COMMAND: {
2514 string flag = cmd.getArg(0);
2515 if (buffer && contains(flag, 'R') && !ensureBufferClean(buffer))
2518 if (contains(flag, 'M')) {
2519 if (!Alert::askForText(message, _("LyX VC: Log Message")))
2522 string path = cmd.getArg(1);
2523 if (contains(path, "$$p") && buffer)
2524 path = subst(path, "$$p", buffer->filePath());
2525 LYXERR(Debug::LYXVC, "Directory: " << path);
2527 if (!pp.isReadableDirectory()) {
2528 lyxerr << _("Directory is not accessible.") << endl;
2531 support::PathChanger p(pp);
2533 string command = cmd.getArg(2);
2534 if (command.empty())
2537 command = subst(command, "$$i", buffer->absFileName());
2538 command = subst(command, "$$p", buffer->filePath());
2540 command = subst(command, "$$m", to_utf8(message));
2541 LYXERR(Debug::LYXVC, "Command: " << command);
2543 one.startscript(Systemcall::Wait, command);
2547 if (contains(flag, 'I'))
2548 buffer->markDirty();
2549 if (contains(flag, 'R'))
2560 void GuiView::openChildDocument(string const & fname)
2562 LASSERT(documentBufferView(), return);
2563 Buffer & buffer = documentBufferView()->buffer();
2564 FileName const filename = support::makeAbsPath(fname, buffer.filePath());
2565 documentBufferView()->saveBookmark(false);
2567 bool parsed = false;
2568 if (theBufferList().exists(filename)) {
2569 child = theBufferList().getBuffer(filename);
2571 message(bformat(_("Opening child document %1$s..."),
2572 makeDisplayPath(filename.absFilename())));
2573 child = loadDocument(filename, false);
2579 // Set the parent name of the child document.
2580 // This makes insertion of citations and references in the child work,
2581 // when the target is in the parent or another child document.
2582 child->setParent(&buffer);
2583 child->masterBuffer()->updateLabels();
2586 child->errors("Parse");
2590 bool GuiView::goToFileRow(string const & argument)
2594 istringstream is(argument);
2595 is >> file_name >> row;
2596 file_name = os::internal_path(file_name);
2598 string const abstmp = package().temp_dir().absFilename();
2599 string const realtmp = package().temp_dir().realPath();
2600 // We have to use os::path_prefix_is() here, instead of
2601 // simply prefixIs(), because the file name comes from
2602 // an external application and may need case adjustment.
2603 if (os::path_prefix_is(file_name, abstmp, os::CASE_ADJUSTED)
2604 || os::path_prefix_is(file_name, realtmp, os::CASE_ADJUSTED)) {
2605 // Needed by inverse dvi search. If it is a file
2606 // in tmpdir, call the apropriated function.
2607 // If tmpdir is a symlink, we may have the real
2608 // path passed back, so we correct for that.
2609 if (!prefixIs(file_name, abstmp))
2610 file_name = subst(file_name, realtmp, abstmp);
2611 buf = theBufferList().getBufferFromTmp(file_name);
2613 // Must replace extension of the file to be .lyx
2614 // and get full path
2615 FileName const s = fileSearch(string(),
2616 support::changeExtension(file_name, ".lyx"), "lyx");
2617 // Either change buffer or load the file
2618 if (theBufferList().exists(s))
2619 buf = theBufferList().getBuffer(s);
2620 else if (s.exists()) {
2621 buf = loadDocument(s);
2622 buf->updateLabels();
2623 buf->errors("Parse");
2626 _("File does not exist: %1$s"),
2627 makeDisplayPath(file_name)));
2632 documentBufferView()->setCursorFromRow(row);
2637 static docstring exportAndDestroy(Buffer * buffer, string const & format)
2639 bool const success = buffer->doExport(format, true);
2642 ? bformat(_("Successful export to format: %1$s"), from_utf8(format))
2643 : bformat(_("Error exporting to format: %1$s"), from_utf8(format));
2647 static docstring previewAndDestroy(Buffer * buffer, string const & format)
2649 bool const success = buffer->preview(format);
2652 ? bformat(_("Successful preview of format: %1$s"), from_utf8(format))
2653 : bformat(_("Error previewing format: %1$s"), from_utf8(format));
2657 bool GuiView::dispatch(FuncRequest const & cmd)
2659 BufferView * bv = currentBufferView();
2660 // By default we won't need any update.
2662 bv->cursor().updateFlags(Update::None);
2664 Buffer * doc_buffer = documentBufferView()
2665 ? &(documentBufferView()->buffer()) : 0;
2667 bool dispatched = true;
2669 if (cmd.origin == FuncRequest::TOC) {
2670 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
2671 toc->doDispatch(bv->cursor(), cmd);
2675 string const argument = to_utf8(cmd.argument());
2677 switch(cmd.action) {
2678 case LFUN_BUFFER_CHILD_OPEN:
2679 openChildDocument(to_utf8(cmd.argument()));
2682 case LFUN_BUFFER_IMPORT:
2683 importDocument(to_utf8(cmd.argument()));
2686 case LFUN_BUFFER_EXPORT: {
2689 if (cmd.argument() == "custom") {
2690 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "sendto"));
2693 if (doc_buffer->doExport(argument, false)) {
2694 message(bformat(_("Error exporting to format: %1$s."),
2700 case LFUN_BUFFER_UPDATE: {
2703 string format = argument;
2704 if (argument.empty())
2705 format = doc_buffer->getDefaultOutputFormat();
2706 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
2707 ProgressInterface::instance()->clearMessages();
2708 QString time = QTime::currentTime().toString(Qt::SystemLocaleShortDate);
2709 ProgressInterface::instance()->appendMessage(time + ": Exporting ...\n");
2710 QFuture<docstring> f = QtConcurrent::run(exportAndDestroy,
2711 doc_buffer->clone(), format);
2712 d.setPreviewFuture(f);
2714 doc_buffer->doExport(format, true);
2718 case LFUN_BUFFER_VIEW: {
2721 string format = argument;
2722 if (argument.empty())
2723 format = doc_buffer->getDefaultOutputFormat();
2724 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
2725 ProgressInterface::instance()->clearMessages();
2726 QString time = QTime::currentTime().toString(Qt::SystemLocaleShortDate);
2727 ProgressInterface::instance()->appendMessage(time + ": Previewing ...\n");
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"};
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);
3408 Dialog * GuiView::build(string const & name)
3410 LASSERT(isValidName(name), return 0);
3412 if (name == "aboutlyx")
3413 return createGuiAbout(*this);
3414 if (name == "bibitem")
3415 return createGuiBibitem(*this);
3416 if (name == "bibtex")
3417 return createGuiBibtex(*this);
3419 return createGuiBox(*this);
3420 if (name == "branch")
3421 return createGuiBranch(*this);
3422 if (name == "changes")
3423 return createGuiChanges(*this);
3424 if (name == "character")
3425 return createGuiCharacter(*this);
3426 if (name == "citation")
3427 return createGuiCitation(*this);
3428 if (name == "compare")
3429 return createGuiCompare(*this);
3430 if (name == "document")
3431 return createGuiDocument(*this);
3432 if (name == "errorlist")
3433 return createGuiErrorList(*this);
3435 return createGuiERT(*this);
3436 if (name == "external")
3437 return createGuiExternal(*this);
3439 return createGuiShowFile(*this);
3440 if (name == "findreplace")
3441 return createGuiSearch(*this);
3442 if (name == "findreplaceadv")
3443 return createGuiSearchAdv(*this);
3444 if (name == "float")
3445 return createGuiFloat(*this);
3446 if (name == "graphics")
3447 return createGuiGraphics(*this);
3449 return createGuiHyperlink(*this);
3450 if (name == "include")
3451 return createGuiInclude(*this);
3452 if (name == "index")
3453 return createGuiIndex(*this);
3454 if (name == "index_print")
3455 return createGuiPrintindex(*this);
3457 return createGuiInfo(*this);
3458 if (name == "label")
3459 return createGuiLabel(*this);
3460 if (name == "listings")
3461 return createGuiListings(*this);
3463 return createGuiLog(*this);
3464 if (name == "mathdelimiter")
3465 return createGuiDelimiter(*this);
3466 if (name == "mathspace")
3467 return createGuiMathHSpace(*this);
3468 if (name == "mathmatrix")
3469 return createGuiMathMatrix(*this);
3470 if (name == "nomenclature")
3471 return createGuiNomenclature(*this);
3472 if (name == "nomencl_print")
3473 return createGuiPrintNomencl(*this);
3475 return createGuiNote(*this);
3476 if (name == "paragraph")
3477 return createGuiParagraph(*this);
3478 if (name == "phantom")
3479 return createGuiPhantom(*this);
3480 if (name == "prefs")
3481 return createGuiPreferences(*this);
3482 if (name == "print")
3483 return createGuiPrint(*this);
3485 return createGuiRef(*this);
3486 if (name == "sendto")
3487 return createGuiSendTo(*this);
3488 if (name == "space")
3489 return createGuiTextHSpace(*this);
3490 if (name == "spellchecker")
3491 return createGuiSpellchecker(*this);
3492 if (name == "symbols")
3493 return createGuiSymbols(*this);
3494 if (name == "tabular")
3495 return createGuiTabular(*this);
3496 if (name == "tabularcreate")
3497 return createGuiTabularCreate(*this);
3498 if (name == "texinfo")
3499 return createGuiTexInfo(*this);
3500 if (name == "thesaurus")
3501 return createGuiThesaurus(*this);
3503 return createGuiToc(*this);
3504 if (name == "view-source")
3505 return createGuiViewSource(*this);
3506 if (name == "vspace")
3507 return createGuiVSpace(*this);
3509 return createGuiWrap(*this);
3515 } // namespace frontend
3518 #include "moc_GuiView.cpp"