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 "GuiKeySymbol.h"
26 #include "GuiToolbar.h"
27 #include "GuiWorkArea.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
111 // QtConcurrent was introduced in Qt 4.4
112 #if (QT_VERSION >= 0x040400)
114 #include <QFutureWatcher>
115 #include <QtConcurrentRun>
118 #include <boost/bind.hpp>
122 #ifdef HAVE_SYS_TIME_H
123 # include <sys/time.h>
130 using namespace lyx::support;
137 class BackgroundWidget : public QWidget
142 LYXERR(Debug::GUI, "show banner: " << lyxrc.show_banner);
143 /// The text to be written on top of the pixmap
144 QString const text = lyx_version ?
145 qt_("version ") + lyx_version : qt_("unknown version");
146 splash_ = getPixmap("images/", "banner", "png");
148 QPainter pain(&splash_);
149 pain.setPen(QColor(0, 0, 0));
151 // The font used to display the version info
152 font.setStyleHint(QFont::SansSerif);
153 font.setWeight(QFont::Bold);
154 font.setPointSize(int(toqstr(lyxrc.font_sizes[FONT_SIZE_LARGE]).toDouble()));
156 pain.drawText(260, 15, text);
159 void paintEvent(QPaintEvent *)
161 int x = (width() - splash_.width()) / 2;
162 int y = (height() - splash_.height()) / 2;
164 pain.drawPixmap(x, y, splash_);
172 /// Toolbar store providing access to individual toolbars by name.
173 typedef map<string, GuiToolbar *> ToolbarMap;
175 typedef boost::shared_ptr<Dialog> DialogPtr;
180 struct GuiView::GuiViewPrivate
182 GuiViewPrivate(GuiView * gv)
183 : gv_(gv), current_work_area_(0), current_main_work_area_(0),
184 layout_(0), autosave_timeout_(5000),
187 // hardcode here the platform specific icon size
188 smallIconSize = 14; // scaling problems
189 normalIconSize = 20; // ok, default
190 bigIconSize = 26; // better for some math icons
192 splitter_ = new QSplitter;
193 bg_widget_ = new BackgroundWidget;
194 stack_widget_ = new QStackedWidget;
195 stack_widget_->addWidget(bg_widget_);
196 stack_widget_->addWidget(splitter_);
198 progress_ = new GuiProgress(gv);
205 delete stack_widget_;
209 QMenu * toolBarPopup(GuiView * parent)
211 // FIXME: translation
212 QMenu * menu = new QMenu(parent);
213 QActionGroup * iconSizeGroup = new QActionGroup(parent);
215 QAction * smallIcons = new QAction(iconSizeGroup);
216 smallIcons->setText(qt_("Small-sized icons"));
217 smallIcons->setCheckable(true);
218 QObject::connect(smallIcons, SIGNAL(triggered()),
219 parent, SLOT(smallSizedIcons()));
220 menu->addAction(smallIcons);
222 QAction * normalIcons = new QAction(iconSizeGroup);
223 normalIcons->setText(qt_("Normal-sized icons"));
224 normalIcons->setCheckable(true);
225 QObject::connect(normalIcons, SIGNAL(triggered()),
226 parent, SLOT(normalSizedIcons()));
227 menu->addAction(normalIcons);
229 QAction * bigIcons = new QAction(iconSizeGroup);
230 bigIcons->setText(qt_("Big-sized icons"));
231 bigIcons->setCheckable(true);
232 QObject::connect(bigIcons, SIGNAL(triggered()),
233 parent, SLOT(bigSizedIcons()));
234 menu->addAction(bigIcons);
236 unsigned int cur = parent->iconSize().width();
237 if ( cur == parent->d.smallIconSize)
238 smallIcons->setChecked(true);
239 else if (cur == parent->d.normalIconSize)
240 normalIcons->setChecked(true);
241 else if (cur == parent->d.bigIconSize)
242 bigIcons->setChecked(true);
249 stack_widget_->setCurrentWidget(bg_widget_);
250 bg_widget_->setUpdatesEnabled(true);
253 TabWorkArea * tabWorkArea(int i)
255 return dynamic_cast<TabWorkArea *>(splitter_->widget(i));
258 TabWorkArea * currentTabWorkArea()
260 if (splitter_->count() == 1)
261 // The first TabWorkArea is always the first one, if any.
262 return tabWorkArea(0);
264 for (int i = 0; i != splitter_->count(); ++i) {
265 TabWorkArea * twa = tabWorkArea(i);
266 if (current_main_work_area_ == twa->currentWorkArea())
270 // None has the focus so we just take the first one.
271 return tabWorkArea(0);
274 #if (QT_VERSION >= 0x040400)
275 void setPreviewFuture(QFuture<docstring> const & f)
277 if (preview_watcher_.isRunning()) {
278 // we prefer to cancel this preview in order to keep a snappy
282 preview_watcher_.setFuture(f);
288 GuiWorkArea * current_work_area_;
289 GuiWorkArea * current_main_work_area_;
290 QSplitter * splitter_;
291 QStackedWidget * stack_widget_;
292 BackgroundWidget * bg_widget_;
294 ToolbarMap toolbars_;
295 ProgressInterface* progress_;
296 /// The main layout box.
298 * \warning Don't Delete! The layout box is actually owned by
299 * whichever toolbar contains it. All the GuiView class needs is a
300 * means of accessing it.
302 * FIXME: replace that with a proper model so that we are not limited
303 * to only one dialog.
308 map<string, DialogPtr> dialogs_;
310 unsigned int smallIconSize;
311 unsigned int normalIconSize;
312 unsigned int bigIconSize;
314 QTimer statusbar_timer_;
315 /// auto-saving of buffers
316 Timeout autosave_timeout_;
317 /// flag against a race condition due to multiclicks, see bug #1119
321 TocModels toc_models_;
323 #if (QT_VERSION >= 0x040400)
325 QFutureWatcher<docstring> autosave_watcher_;
326 QFutureWatcher<docstring> preview_watcher_;
328 struct DummyWatcher { bool isRunning(){return false;} };
329 DummyWatcher preview_watcher_;
334 GuiView::GuiView(int id)
335 : d(*new GuiViewPrivate(this)), id_(id), closing_(false)
337 // GuiToolbars *must* be initialised before the menu bar.
338 normalSizedIcons(); // at least on Mac the default is 32 otherwise, which is huge
341 // set ourself as the current view. This is needed for the menu bar
342 // filling, at least for the static special menu item on Mac. Otherwise
343 // they are greyed out.
344 guiApp->setCurrentView(this);
346 // Fill up the menu bar.
347 guiApp->menus().fillMenuBar(menuBar(), this, true);
349 setCentralWidget(d.stack_widget_);
351 // Start autosave timer
352 if (lyxrc.autosave) {
353 d.autosave_timeout_.timeout.connect(boost::bind(&GuiView::autoSave, this));
354 d.autosave_timeout_.setTimeout(lyxrc.autosave * 1000);
355 d.autosave_timeout_.start();
357 connect(&d.statusbar_timer_, SIGNAL(timeout()),
358 this, SLOT(clearMessage()));
360 // We don't want to keep the window in memory if it is closed.
361 setAttribute(Qt::WA_DeleteOnClose, true);
363 #if (!defined(Q_WS_WIN) && !defined(Q_WS_MACX))
364 // assign an icon to main form. We do not do it under Qt/Win or Qt/Mac,
365 // since the icon is provided in the application bundle.
366 setWindowIcon(getPixmap("images/", "lyx", "png"));
370 setAcceptDrops(true);
372 statusBar()->setSizeGripEnabled(true);
375 #if (QT_VERSION >= 0x040400)
376 connect(&d.autosave_watcher_, SIGNAL(finished()), this,
377 SLOT(threadFinished()));
378 connect(&d.preview_watcher_, SIGNAL(finished()), this,
379 SLOT(threadFinished()));
382 connect(this, SIGNAL(triggerShowDialog(QString const &, QString const &, Inset *)),
383 SLOT(doShowDialog(QString const &, QString const &, Inset *)));
385 // Forbid too small unresizable window because it can happen
386 // with some window manager under X11.
387 setMinimumSize(300, 200);
389 if (lyxrc.allow_geometry_session) {
390 // Now take care of session management.
395 // no session handling, default to a sane size.
396 setGeometry(50, 50, 690, 510);
399 // clear session data if any.
401 settings.remove("views");
411 void GuiView::threadFinished()
413 #if (QT_VERSION >= 0x040400)
414 QFutureWatcher<docstring> const * watcher =
415 static_cast<QFutureWatcher<docstring> const *>(sender());
416 message(watcher->result());
421 void GuiView::saveLayout() const
424 settings.beginGroup("views");
425 settings.beginGroup(QString::number(id_));
427 settings.setValue("pos", pos());
428 settings.setValue("size", size());
430 settings.setValue("geometry", saveGeometry());
432 settings.setValue("layout", saveState(0));
433 settings.setValue("icon_size", iconSize());
437 bool GuiView::restoreLayout()
440 settings.beginGroup("views");
441 settings.beginGroup(QString::number(id_));
442 QString const icon_key = "icon_size";
443 if (!settings.contains(icon_key))
446 //code below is skipped when when ~/.config/LyX is (re)created
447 setIconSize(settings.value(icon_key).toSize());
449 QPoint pos = settings.value("pos", QPoint(50, 50)).toPoint();
450 QSize size = settings.value("size", QSize(690, 510)).toSize();
454 // Work-around for bug #6034: the window ends up in an undetermined
455 // state when trying to restore a maximized window when it is
456 // already maximized.
457 if (!(windowState() & Qt::WindowMaximized))
458 if (!restoreGeometry(settings.value("geometry").toByteArray()))
459 setGeometry(50, 50, 690, 510);
461 // Make sure layout is correctly oriented.
462 setLayoutDirection(qApp->layoutDirection());
464 // Allow the toc and view-source dock widget to be restored if needed.
466 if ((dialog = findOrBuild("toc", true)))
467 // see bug 5082. At least setup title and enabled state.
468 // Visibility will be adjusted by restoreState below.
469 dialog->prepareView();
470 if ((dialog = findOrBuild("view-source", true)))
471 dialog->prepareView();
472 if ((dialog = findOrBuild("progress", true)))
473 dialog->prepareView();
475 if (!restoreState(settings.value("layout").toByteArray(), 0))
482 GuiToolbar * GuiView::toolbar(string const & name)
484 ToolbarMap::iterator it = d.toolbars_.find(name);
485 if (it != d.toolbars_.end())
488 LYXERR(Debug::GUI, "Toolbar::display: no toolbar named " << name);
489 message(bformat(_("Unknown toolbar \"%1$s\""), from_utf8(name)));
494 void GuiView::constructToolbars()
496 ToolbarMap::iterator it = d.toolbars_.begin();
497 for (; it != d.toolbars_.end(); ++it)
501 // I don't like doing this here, but the standard toolbar
502 // destroys this object when it's destroyed itself (vfr)
503 d.layout_ = new LayoutBox(*this);
504 d.stack_widget_->addWidget(d.layout_);
505 d.layout_->move(0,0);
507 // extracts the toolbars from the backend
508 Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
509 Toolbars::Infos::iterator end = guiApp->toolbars().end();
510 for (; cit != end; ++cit)
511 d.toolbars_[cit->name] = new GuiToolbar(*cit, *this);
515 void GuiView::initToolbars()
517 // extracts the toolbars from the backend
518 Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
519 Toolbars::Infos::iterator end = guiApp->toolbars().end();
520 for (; cit != end; ++cit) {
521 GuiToolbar * tb = toolbar(cit->name);
524 int const visibility = guiApp->toolbars().defaultVisibility(cit->name);
526 tb->setVisible(false);
527 tb->setVisibility(visibility);
529 if (visibility & Toolbars::TOP) {
531 addToolBarBreak(Qt::TopToolBarArea);
532 addToolBar(Qt::TopToolBarArea, tb);
535 if (visibility & Toolbars::BOTTOM) {
536 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
537 #if (QT_VERSION >= 0x040202)
538 addToolBarBreak(Qt::BottomToolBarArea);
540 addToolBar(Qt::BottomToolBarArea, tb);
543 if (visibility & Toolbars::LEFT) {
544 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
545 #if (QT_VERSION >= 0x040202)
546 addToolBarBreak(Qt::LeftToolBarArea);
548 addToolBar(Qt::LeftToolBarArea, tb);
551 if (visibility & Toolbars::RIGHT) {
552 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
553 #if (QT_VERSION >= 0x040202)
554 addToolBarBreak(Qt::RightToolBarArea);
556 addToolBar(Qt::RightToolBarArea, tb);
559 if (visibility & Toolbars::ON)
560 tb->setVisible(true);
565 TocModels & GuiView::tocModels()
567 return d.toc_models_;
571 void GuiView::setFocus()
573 LYXERR(Debug::DEBUG, "GuiView::setFocus()" << this);
574 // Make sure LyXFunc points to the correct view.
575 guiApp->setCurrentView(this);
576 QMainWindow::setFocus();
577 if (d.current_work_area_)
578 d.current_work_area_->setFocus();
582 QMenu * GuiView::createPopupMenu()
584 return d.toolBarPopup(this);
588 void GuiView::showEvent(QShowEvent * e)
590 LYXERR(Debug::GUI, "Passed Geometry "
591 << size().height() << "x" << size().width()
592 << "+" << pos().x() << "+" << pos().y());
594 if (d.splitter_->count() == 0)
595 // No work area, switch to the background widget.
598 QMainWindow::showEvent(e);
602 /** Destroy only all tabbed WorkAreas. Destruction of other WorkAreas
603 ** is responsibility of the container (e.g., dialog)
605 void GuiView::closeEvent(QCloseEvent * close_event)
607 LYXERR(Debug::DEBUG, "GuiView::closeEvent()");
612 // it can happen that this event arrives without selecting the view,
613 // e.g. when clicking the close button on a background window.
615 if (!closeWorkAreaAll()) {
617 close_event->ignore();
621 // Make sure that nothing will use this to be closed View.
622 guiApp->unregisterView(this);
624 if (isFullScreen()) {
625 // Switch off fullscreen before closing.
630 // Make sure the timer time out will not trigger a statusbar update.
631 d.statusbar_timer_.stop();
633 // Saving fullscreen requires additional tweaks in the toolbar code.
634 // It wouldn't also work under linux natively.
635 if (lyxrc.allow_geometry_session) {
636 // Save this window geometry and layout.
638 // Then the toolbar private states.
639 ToolbarMap::iterator end = d.toolbars_.end();
640 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
641 it->second->saveSession();
642 // Now take care of all other dialogs:
643 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
644 for (; it!= d.dialogs_.end(); ++it)
645 it->second->saveSession();
648 close_event->accept();
652 void GuiView::dragEnterEvent(QDragEnterEvent * event)
654 if (event->mimeData()->hasUrls())
656 /// \todo Ask lyx-devel is this is enough:
657 /// if (event->mimeData()->hasFormat("text/plain"))
658 /// event->acceptProposedAction();
662 void GuiView::dropEvent(QDropEvent * event)
664 QList<QUrl> files = event->mimeData()->urls();
668 LYXERR(Debug::GUI, "GuiView::dropEvent: got URLs!");
669 for (int i = 0; i != files.size(); ++i) {
670 string const file = os::internal_path(fromqstr(
671 files.at(i).toLocalFile()));
675 string const ext = support::getExtension(file);
676 vector<const Format *> found_formats;
678 // Find all formats that have the correct extension.
679 vector<const Format *> const & import_formats
680 = theConverters().importableFormats();
681 vector<const Format *>::const_iterator it = import_formats.begin();
682 for (; it != import_formats.end(); ++it)
683 if ((*it)->extension() == ext)
684 found_formats.push_back(*it);
687 if (found_formats.size() >= 1) {
688 if (found_formats.size() > 1) {
689 //FIXME: show a dialog to choose the correct importable format
691 "Multiple importable formats found, selecting first");
693 string const arg = found_formats[0]->name() + " " + file;
694 cmd = FuncRequest(LFUN_BUFFER_IMPORT, arg);
697 //FIXME: do we have to explicitly check whether it's a lyx file?
699 "No formats found, trying to open it as a lyx file");
700 cmd = FuncRequest(LFUN_FILE_OPEN, file);
703 // Asynchronously post the event. DropEvent usually comes
704 // from the BufferView. But reloading a file might close
705 // the BufferView from within its own event handler.
706 guiApp->dispatchDelayed(cmd);
712 void GuiView::message(docstring const & str)
714 if (ForkedProcess::iAmAChild())
717 // call is moved to GUI-thread by GuiProgress
718 d.progress_->appendMessage(toqstr(str));
722 void GuiView::updateMessage(QString const & str)
724 statusBar()->showMessage(str);
725 d.statusbar_timer_.stop();
726 d.statusbar_timer_.start(3000);
730 void GuiView::smallSizedIcons()
732 setIconSize(QSize(d.smallIconSize, d.smallIconSize));
736 void GuiView::normalSizedIcons()
738 setIconSize(QSize(d.normalIconSize, d.normalIconSize));
742 void GuiView::bigSizedIcons()
744 setIconSize(QSize(d.bigIconSize, d.bigIconSize));
748 void GuiView::clearMessage()
750 // FIXME: This code was introduced in r19643 to fix bug #4123. However,
751 // the hasFocus function mostly returns false, even if the focus is on
752 // a workarea in this view.
756 d.statusbar_timer_.stop();
760 void GuiView::updateWindowTitle(GuiWorkArea * wa)
762 if (wa != d.current_work_area_)
764 setWindowTitle(qt_("LyX: ") + wa->windowTitle());
765 setWindowIconText(wa->windowIconText());
769 void GuiView::on_currentWorkAreaChanged(GuiWorkArea * wa)
772 disconnectBufferView();
773 connectBufferView(wa->bufferView());
774 connectBuffer(wa->bufferView().buffer());
775 d.current_work_area_ = wa;
776 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
777 this, SLOT(updateWindowTitle(GuiWorkArea *)));
778 updateWindowTitle(wa);
782 // The document settings needs to be reinitialised.
783 updateDialog("document", "");
785 // Buffer-dependent dialogs must be updated. This is done here because
786 // some dialogs require buffer()->text.
791 void GuiView::on_lastWorkAreaRemoved()
794 // We already are in a close event. Nothing more to do.
797 if (d.splitter_->count() > 1)
798 // We have a splitter so don't close anything.
801 // Reset and updates the dialogs.
802 d.toc_models_.reset(0);
803 updateDialog("document", "");
806 resetWindowTitleAndIconText();
809 if (lyxrc.open_buffers_in_tabs)
810 // Nothing more to do, the window should stay open.
813 if (guiApp->viewIds().size() > 1) {
819 // On Mac we also close the last window because the application stay
820 // resident in memory. On other platforms we don't close the last
821 // window because this would quit the application.
827 void GuiView::updateStatusBar()
829 // let the user see the explicit message
830 if (d.statusbar_timer_.isActive())
837 void GuiView::showMessage()
839 QString msg = toqstr(theGuiApp()->viewStatusMessage());
841 BufferView const * bv = currentBufferView();
843 msg = toqstr(bv->cursor().currentState());
845 msg = qt_("Welcome to LyX!");
847 statusBar()->showMessage(msg);
851 bool GuiView::event(QEvent * e)
855 // Useful debug code:
856 //case QEvent::ActivationChange:
857 //case QEvent::WindowDeactivate:
858 //case QEvent::Paint:
859 //case QEvent::Enter:
860 //case QEvent::Leave:
861 //case QEvent::HoverEnter:
862 //case QEvent::HoverLeave:
863 //case QEvent::HoverMove:
864 //case QEvent::StatusTip:
865 //case QEvent::DragEnter:
866 //case QEvent::DragLeave:
870 case QEvent::WindowActivate: {
871 GuiView * old_view = guiApp->currentView();
872 if (this == old_view) {
874 return QMainWindow::event(e);
876 if (old_view && old_view->currentBufferView()) {
877 // save current selection to the selection buffer to allow
878 // middle-button paste in this window.
879 cap::saveSelection(old_view->currentBufferView()->cursor());
881 guiApp->setCurrentView(this);
882 if (d.current_work_area_) {
883 BufferView & bv = d.current_work_area_->bufferView();
884 connectBufferView(bv);
885 connectBuffer(bv.buffer());
886 // The document structure, name and dialogs might have
887 // changed in another view.
889 // The document settings needs to be reinitialised.
890 updateDialog("document", "");
893 resetWindowTitleAndIconText();
896 return QMainWindow::event(e);
899 case QEvent::ShortcutOverride: {
902 #if (!defined Q_WS_X11) || (QT_VERSION >= 0x040500)
903 if (isFullScreen() && menuBar()->isHidden()) {
904 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
905 // FIXME: we should also try to detect special LyX shortcut such as
906 // Alt-P and Alt-M. Right now there is a hack in
907 // GuiWorkArea::processKeySym() that hides again the menubar for
909 if (ke->modifiers() & Qt::AltModifier && ke->key() != Qt::Key_Alt) {
911 return QMainWindow::event(e);
916 if (d.current_work_area_)
917 // Nothing special to do.
918 return QMainWindow::event(e);
920 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
921 // Let Qt handle menu access and the Tab keys to navigate keys to navigate
923 if (ke->modifiers() & Qt::AltModifier || ke->key() == Qt::Key_Tab
924 || ke->key() == Qt::Key_Backtab)
925 return QMainWindow::event(e);
927 // Allow processing of shortcuts that are allowed even when no Buffer
930 setKeySymbol(&sym, ke);
931 guiApp->processKeySym(sym, q_key_state(ke->modifiers()));
937 return QMainWindow::event(e);
941 void GuiView::resetWindowTitleAndIconText()
943 setWindowTitle(qt_("LyX"));
944 setWindowIconText(qt_("LyX"));
947 bool GuiView::focusNextPrevChild(bool /*next*/)
954 void GuiView::setBusy(bool busy)
956 if (d.current_work_area_) {
957 d.current_work_area_->setUpdatesEnabled(!busy);
959 d.current_work_area_->stopBlinkingCursor();
961 d.current_work_area_->startBlinkingCursor();
965 QApplication::setOverrideCursor(Qt::WaitCursor);
967 QApplication::restoreOverrideCursor();
971 GuiWorkArea * GuiView::workArea(Buffer & buffer)
973 if (currentWorkArea()
974 && ¤tWorkArea()->bufferView().buffer() == &buffer)
975 return (GuiWorkArea *) currentWorkArea();
976 if (TabWorkArea * twa = d.currentTabWorkArea())
977 return twa->workArea(buffer);
982 GuiWorkArea * GuiView::addWorkArea(Buffer & buffer)
984 // Automatically create a TabWorkArea if there are none yet.
985 TabWorkArea * tab_widget = d.splitter_->count()
986 ? d.currentTabWorkArea() : addTabWorkArea();
987 return tab_widget->addWorkArea(buffer, *this);
991 TabWorkArea * GuiView::addTabWorkArea()
993 TabWorkArea * twa = new TabWorkArea;
994 QObject::connect(twa, SIGNAL(currentWorkAreaChanged(GuiWorkArea *)),
995 this, SLOT(on_currentWorkAreaChanged(GuiWorkArea *)));
996 QObject::connect(twa, SIGNAL(lastWorkAreaRemoved()),
997 this, SLOT(on_lastWorkAreaRemoved()));
999 d.splitter_->addWidget(twa);
1000 d.stack_widget_->setCurrentWidget(d.splitter_);
1005 GuiWorkArea const * GuiView::currentWorkArea() const
1007 return d.current_work_area_;
1011 GuiWorkArea * GuiView::currentWorkArea()
1013 return d.current_work_area_;
1017 GuiWorkArea const * GuiView::currentMainWorkArea() const
1019 if (d.currentTabWorkArea() == NULL)
1021 return d.currentTabWorkArea()->currentWorkArea();
1025 GuiWorkArea * GuiView::currentMainWorkArea()
1027 if (d.currentTabWorkArea() == NULL)
1029 return d.currentTabWorkArea()->currentWorkArea();
1033 void GuiView::setCurrentWorkArea(GuiWorkArea * wa)
1035 LYXERR(Debug::DEBUG, "Setting current wa: " << wa << endl);
1037 d.current_work_area_ = NULL;
1041 GuiWorkArea * old_gwa = theGuiApp()->currentView()->currentWorkArea();
1045 if (currentBufferView())
1046 cap::saveSelection(currentBufferView()->cursor());
1048 theGuiApp()->setCurrentView(this);
1049 d.current_work_area_ = wa;
1050 for (int i = 0; i != d.splitter_->count(); ++i) {
1051 if (d.tabWorkArea(i)->setCurrentWorkArea(wa)) {
1052 //if (d.current_main_work_area_)
1053 // d.current_main_work_area_->setFrameStyle(QFrame::NoFrame);
1054 d.current_main_work_area_ = wa;
1055 //d.current_main_work_area_->setFrameStyle(QFrame::Box | QFrame::Plain);
1056 //d.current_main_work_area_->setLineWidth(2);
1057 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() << ", Current main wa: " << currentMainWorkArea());
1061 LYXERR(Debug::DEBUG, "This is not a tabbed wa");
1062 on_currentWorkAreaChanged(wa);
1063 BufferView & bv = wa->bufferView();
1064 bv.cursor().fixIfBroken();
1066 wa->setUpdatesEnabled(true);
1067 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() << ", Current main wa: " << currentMainWorkArea());
1071 void GuiView::removeWorkArea(GuiWorkArea * wa)
1073 LASSERT(wa, return);
1074 if (wa == d.current_work_area_) {
1076 disconnectBufferView();
1077 d.current_work_area_ = 0;
1078 d.current_main_work_area_ = 0;
1081 bool found_twa = false;
1082 for (int i = 0; i != d.splitter_->count(); ++i) {
1083 TabWorkArea * twa = d.tabWorkArea(i);
1084 if (twa->removeWorkArea(wa)) {
1085 // Found in this tab group, and deleted the GuiWorkArea.
1087 if (twa->count() != 0) {
1088 if (d.current_work_area_ == 0)
1089 // This means that we are closing the current GuiWorkArea, so
1090 // switch to the next GuiWorkArea in the found TabWorkArea.
1091 setCurrentWorkArea(twa->currentWorkArea());
1093 // No more WorkAreas in this tab group, so delete it.
1100 // It is not a tabbed work area (i.e., the search work area), so it
1101 // should be deleted by other means.
1102 LASSERT(found_twa, /* */);
1104 if (d.current_work_area_ == 0) {
1105 if (d.splitter_->count() != 0) {
1106 TabWorkArea * twa = d.currentTabWorkArea();
1107 setCurrentWorkArea(twa->currentWorkArea());
1109 // No more work areas, switch to the background widget.
1110 setCurrentWorkArea(0);
1116 LayoutBox * GuiView::getLayoutDialog() const
1122 void GuiView::updateLayoutList()
1125 d.layout_->updateContents(false);
1129 void GuiView::updateToolbars()
1131 ToolbarMap::iterator end = d.toolbars_.end();
1132 if (d.current_work_area_) {
1134 d.current_work_area_->bufferView().cursor().inMathed();
1136 lyx::getStatus(FuncRequest(LFUN_LAYOUT_TABULAR)).enabled();
1138 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).enabled() &&
1139 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).onoff(true);
1140 bool const mathmacrotemplate =
1141 lyx::getStatus(FuncRequest(LFUN_IN_MATHMACROTEMPLATE)).enabled();
1143 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1144 it->second->update(math, table, review, mathmacrotemplate);
1146 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1147 it->second->update(false, false, false, false);
1151 void GuiView::setBuffer(Buffer * newBuffer)
1153 LYXERR(Debug::DEBUG, "Setting buffer: " << newBuffer << endl);
1154 LASSERT(newBuffer, return);
1157 GuiWorkArea * wa = workArea(*newBuffer);
1159 newBuffer->masterBuffer()->updateLabels();
1160 wa = addWorkArea(*newBuffer);
1162 //Disconnect the old buffer...there's no new one.
1165 connectBuffer(*newBuffer);
1166 connectBufferView(wa->bufferView());
1167 setCurrentWorkArea(wa);
1173 void GuiView::connectBuffer(Buffer & buf)
1175 buf.setGuiDelegate(this);
1179 void GuiView::disconnectBuffer()
1181 if (d.current_work_area_)
1182 d.current_work_area_->bufferView().buffer().setGuiDelegate(0);
1186 void GuiView::connectBufferView(BufferView & bv)
1188 bv.setGuiDelegate(this);
1192 void GuiView::disconnectBufferView()
1194 if (d.current_work_area_)
1195 d.current_work_area_->bufferView().setGuiDelegate(0);
1199 void GuiView::errors(string const & error_type, bool from_master)
1201 ErrorList & el = from_master ?
1202 documentBufferView()->buffer().masterBuffer()->errorList(error_type)
1203 : documentBufferView()->buffer().errorList(error_type);
1204 string data = error_type;
1206 data = "from_master|" + error_type;
1208 showDialog("errorlist", data);
1212 void GuiView::updateTocItem(string const & type, DocIterator const & dit)
1214 d.toc_models_.updateItem(toqstr(type), dit);
1218 void GuiView::structureChanged()
1220 d.toc_models_.reset(documentBufferView());
1221 // Navigator needs more than a simple update in this case. It needs to be
1223 updateDialog("toc", "");
1227 void GuiView::updateDialog(string const & name, string const & data)
1229 if (!isDialogVisible(name))
1232 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
1233 if (it == d.dialogs_.end())
1236 Dialog * const dialog = it->second.get();
1237 if (dialog->isVisibleView())
1238 dialog->initialiseParams(data);
1242 BufferView * GuiView::documentBufferView()
1244 return currentMainWorkArea()
1245 ? ¤tMainWorkArea()->bufferView()
1250 BufferView const * GuiView::documentBufferView() const
1252 return currentMainWorkArea()
1253 ? ¤tMainWorkArea()->bufferView()
1258 BufferView * GuiView::currentBufferView()
1260 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1264 BufferView const * GuiView::currentBufferView() const
1266 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1270 #if (QT_VERSION >= 0x040400)
1271 static docstring saveAndDestroyBuffer(Buffer * buffer, FileName const & fname)
1274 FileName const tmp_ret = FileName::tempName("lyxauto");
1275 if (!tmp_ret.empty()) {
1276 if (buffer->writeFile(tmp_ret))
1277 failed = !tmp_ret.moveTo(fname);
1280 // failed to write/rename tmp_ret so try writing direct
1281 failed = buffer->writeFile(fname);
1285 ? _("Automatic save failed!")
1286 : _("Automatic save done.");
1291 void GuiView::autoSave()
1293 LYXERR(Debug::INFO, "Running autoSave()");
1295 Buffer * buffer = documentBufferView()
1296 ? &documentBufferView()->buffer() : 0;
1300 #if (QT_VERSION >= 0x040400)
1301 QFuture<docstring> f = QtConcurrent::run(saveAndDestroyBuffer, buffer->clone(),
1302 buffer->getAutosaveFilename());
1303 d.autosave_watcher_.setFuture(f);
1310 void GuiView::resetAutosaveTimers()
1313 d.autosave_timeout_.restart();
1317 bool GuiView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1320 Buffer * buf = currentBufferView()
1321 ? ¤tBufferView()->buffer() : 0;
1322 Buffer * doc_buffer = documentBufferView()
1323 ? &(documentBufferView()->buffer()) : 0;
1325 // Check whether we need a buffer
1326 if (!lyxaction.funcHasFlag(cmd.action, LyXAction::NoBuffer) && !buf) {
1327 // no, exit directly
1328 flag.message(from_utf8(N_("Command not allowed with"
1329 "out any document open")));
1330 flag.setEnabled(false);
1334 if (cmd.origin == FuncRequest::TOC) {
1335 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
1337 if (toc->getStatus(documentBufferView()->cursor(), cmd, fs))
1340 flag.setEnabled(false);
1344 switch(cmd.action) {
1345 case LFUN_BUFFER_IMPORT:
1348 case LFUN_MASTER_BUFFER_UPDATE:
1349 case LFUN_MASTER_BUFFER_VIEW:
1350 enable = doc_buffer && doc_buffer->parent() != 0
1351 && !d.preview_watcher_.isRunning();
1354 case LFUN_BUFFER_UPDATE:
1355 case LFUN_BUFFER_VIEW: {
1356 if (!doc_buffer || d.preview_watcher_.isRunning()) {
1360 string format = to_utf8(cmd.argument());
1361 if (cmd.argument().empty())
1362 format = doc_buffer->getDefaultOutputFormat();
1363 enable = doc_buffer->isExportableFormat(format);
1367 case LFUN_BUFFER_RELOAD:
1368 enable = doc_buffer && !doc_buffer->isUnnamed()
1369 && doc_buffer->fileName().exists()
1370 && (!doc_buffer->isClean()
1371 || doc_buffer->isExternallyModified(Buffer::timestamp_method));
1374 case LFUN_BUFFER_CHILD_OPEN:
1375 enable = doc_buffer;
1378 case LFUN_BUFFER_WRITE:
1379 enable = doc_buffer && (doc_buffer->isUnnamed() || !doc_buffer->isClean());
1382 //FIXME: This LFUN should be moved to GuiApplication.
1383 case LFUN_BUFFER_WRITE_ALL: {
1384 // We enable the command only if there are some modified buffers
1385 Buffer * first = theBufferList().first();
1390 // We cannot use a for loop as the buffer list is a cycle.
1392 if (!b->isClean()) {
1396 b = theBufferList().next(b);
1397 } while (b != first);
1401 case LFUN_BUFFER_WRITE_AS:
1402 enable = doc_buffer;
1405 case LFUN_BUFFER_CLOSE:
1406 enable = doc_buffer;
1409 case LFUN_BUFFER_CLOSE_ALL:
1410 enable = theBufferList().last() != theBufferList().first();
1413 case LFUN_SPLIT_VIEW:
1414 if (cmd.getArg(0) == "vertical")
1415 enable = doc_buffer && (d.splitter_->count() == 1 ||
1416 d.splitter_->orientation() == Qt::Vertical);
1418 enable = doc_buffer && (d.splitter_->count() == 1 ||
1419 d.splitter_->orientation() == Qt::Horizontal);
1422 case LFUN_CLOSE_TAB_GROUP:
1423 enable = d.currentTabWorkArea();
1426 case LFUN_TOOLBAR_TOGGLE:
1427 if (GuiToolbar * t = toolbar(cmd.getArg(0)))
1428 flag.setOnOff(t->isVisible());
1431 case LFUN_DROP_LAYOUTS_CHOICE:
1435 case LFUN_UI_TOGGLE:
1436 flag.setOnOff(isFullScreen());
1439 case LFUN_DIALOG_DISCONNECT_INSET:
1442 case LFUN_DIALOG_HIDE:
1443 // FIXME: should we check if the dialog is shown?
1446 case LFUN_DIALOG_TOGGLE:
1447 flag.setOnOff(isDialogVisible(cmd.getArg(0)));
1448 // fall through to set "enable"
1449 case LFUN_DIALOG_SHOW: {
1450 string const name = cmd.getArg(0);
1452 enable = name == "aboutlyx"
1453 || name == "file" //FIXME: should be removed.
1455 || name == "texinfo"
1456 || name == "progress"
1457 || name == "compare";
1458 else if (name == "print")
1459 enable = doc_buffer->isExportable("dvi")
1460 && lyxrc.print_command != "none";
1461 else if (name == "character" || name == "symbols") {
1462 if (!buf || buf->isReadonly()
1463 || !currentBufferView()->cursor().inTexted())
1466 // FIXME we should consider passthru
1468 Inset const & in = currentBufferView()->cursor().inset();
1469 enable = !in.getLayout().isPassThru();
1472 else if (name == "latexlog")
1473 enable = FileName(doc_buffer->logName()).isReadableFile();
1474 else if (name == "spellchecker")
1475 enable = theSpellChecker() && !doc_buffer->isReadonly();
1476 else if (name == "vclog")
1477 enable = doc_buffer->lyxvc().inUse();
1481 case LFUN_DIALOG_UPDATE: {
1482 string const name = cmd.getArg(0);
1484 enable = name == "prefs";
1488 case LFUN_COMMAND_EXECUTE:
1490 case LFUN_MENU_OPEN:
1491 // Nothing to check.
1494 case LFUN_COMPLETION_INLINE:
1495 if (!d.current_work_area_
1496 || !d.current_work_area_->completer().inlinePossible(
1497 currentBufferView()->cursor()))
1501 case LFUN_COMPLETION_POPUP:
1502 if (!d.current_work_area_
1503 || !d.current_work_area_->completer().popupPossible(
1504 currentBufferView()->cursor()))
1508 case LFUN_COMPLETION_COMPLETE:
1509 if (!d.current_work_area_
1510 || !d.current_work_area_->completer().inlinePossible(
1511 currentBufferView()->cursor()))
1515 case LFUN_COMPLETION_ACCEPT:
1516 if (!d.current_work_area_
1517 || (!d.current_work_area_->completer().popupVisible()
1518 && !d.current_work_area_->completer().inlineVisible()
1519 && !d.current_work_area_->completer().completionAvailable()))
1523 case LFUN_COMPLETION_CANCEL:
1524 if (!d.current_work_area_
1525 || (!d.current_work_area_->completer().popupVisible()
1526 && !d.current_work_area_->completer().inlineVisible()))
1530 case LFUN_BUFFER_ZOOM_OUT:
1531 enable = doc_buffer && lyxrc.zoom > 10;
1534 case LFUN_BUFFER_ZOOM_IN:
1535 enable = doc_buffer;
1538 case LFUN_BUFFER_NEXT:
1539 case LFUN_BUFFER_PREVIOUS:
1540 // FIXME: should we check is there is an previous or next buffer?
1542 case LFUN_BUFFER_SWITCH:
1543 // toggle on the current buffer, but do not toggle off
1544 // the other ones (is that a good idea?)
1546 && to_utf8(cmd.argument()) == doc_buffer->absFileName())
1547 flag.setOnOff(true);
1550 case LFUN_VC_REGISTER:
1551 enable = doc_buffer && !doc_buffer->lyxvc().inUse();
1553 case LFUN_VC_CHECK_IN:
1554 enable = doc_buffer && doc_buffer->lyxvc().checkInEnabled();
1556 case LFUN_VC_CHECK_OUT:
1557 enable = doc_buffer && doc_buffer->lyxvc().checkOutEnabled();
1559 case LFUN_VC_LOCKING_TOGGLE:
1560 enable = doc_buffer && !doc_buffer->isReadonly()
1561 && doc_buffer->lyxvc().lockingToggleEnabled();
1562 flag.setOnOff(enable && !doc_buffer->lyxvc().locker().empty());
1564 case LFUN_VC_REVERT:
1565 enable = doc_buffer && doc_buffer->lyxvc().inUse();
1567 case LFUN_VC_UNDO_LAST:
1568 enable = doc_buffer && doc_buffer->lyxvc().undoLastEnabled();
1570 case LFUN_VC_REPO_UPDATE:
1571 enable = doc_buffer && doc_buffer->lyxvc().inUse();
1573 case LFUN_VC_COMMAND: {
1574 if (cmd.argument().empty())
1576 if (!doc_buffer && contains(cmd.getArg(0), 'D'))
1581 case LFUN_SERVER_GOTO_FILE_ROW:
1589 flag.setEnabled(false);
1595 static FileName selectTemplateFile()
1597 FileDialog dlg(qt_("Select template file"));
1598 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1599 dlg.setButton1(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
1601 FileDialog::Result result = dlg.open(toqstr(lyxrc.template_path),
1602 QStringList(qt_("LyX Documents (*.lyx)")));
1604 if (result.first == FileDialog::Later)
1606 if (result.second.isEmpty())
1608 return FileName(fromqstr(result.second));
1612 Buffer * GuiView::loadDocument(FileName const & filename, bool tolastfiles)
1616 Buffer * newBuffer = checkAndLoadLyXFile(filename);
1619 message(_("Document not loaded."));
1624 setBuffer(newBuffer);
1626 // scroll to the position when the file was last closed
1627 if (lyxrc.use_lastfilepos) {
1628 LastFilePosSection::FilePos filepos =
1629 theSession().lastFilePos().load(filename);
1630 documentBufferView()->moveToPosition(filepos.pit, filepos.pos, 0, 0);
1634 theSession().lastFiles().add(filename);
1641 void GuiView::openDocument(string const & fname)
1643 string initpath = lyxrc.document_path;
1645 if (documentBufferView()) {
1646 string const trypath = documentBufferView()->buffer().filePath();
1647 // If directory is writeable, use this as default.
1648 if (FileName(trypath).isDirWritable())
1654 if (fname.empty()) {
1655 FileDialog dlg(qt_("Select document to open"), LFUN_FILE_OPEN);
1656 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1657 dlg.setButton2(qt_("Examples|#E#e"),
1658 toqstr(addPath(package().system_support().absFilename(), "examples")));
1660 QStringList filter(qt_("LyX Documents (*.lyx)"));
1661 filter << qt_("LyX-1.3.x Documents (*.lyx13)")
1662 << qt_("LyX-1.4.x Documents (*.lyx14)")
1663 << qt_("LyX-1.5.x Documents (*.lyx15)")
1664 << qt_("LyX-1.6.x Documents (*.lyx16)");
1665 FileDialog::Result result =
1666 dlg.open(toqstr(initpath), filter);
1668 if (result.first == FileDialog::Later)
1671 filename = fromqstr(result.second);
1673 // check selected filename
1674 if (filename.empty()) {
1675 message(_("Canceled."));
1681 // get absolute path of file and add ".lyx" to the filename if
1683 FileName const fullname =
1684 fileSearch(string(), filename, "lyx", support::may_not_exist);
1685 if (!fullname.empty())
1686 filename = fullname.absFilename();
1688 if (!fullname.onlyPath().isDirectory()) {
1689 Alert::warning(_("Invalid filename"),
1690 bformat(_("The directory in the given path\n%1$s\ndoes not exist."),
1691 from_utf8(fullname.absFilename())));
1694 // if the file doesn't exist, let the user create one
1695 if (!fullname.exists()) {
1696 // the user specifically chose this name. Believe him.
1697 Buffer * const b = newFile(filename, string(), true);
1703 docstring const disp_fn = makeDisplayPath(filename);
1704 message(bformat(_("Opening document %1$s..."), disp_fn));
1707 Buffer * buf = loadDocument(fullname);
1709 buf->updateLabels();
1711 buf->errors("Parse");
1712 str2 = bformat(_("Document %1$s opened."), disp_fn);
1713 if (buf->lyxvc().inUse())
1714 str2 += " " + from_utf8(buf->lyxvc().versionString()) +
1715 " " + _("Version control detected.");
1717 str2 = bformat(_("Could not open document %1$s"), disp_fn);
1722 // FIXME: clean that
1723 static bool import(GuiView * lv, FileName const & filename,
1724 string const & format, ErrorList & errorList)
1726 FileName const lyxfile(support::changeExtension(filename.absFilename(), ".lyx"));
1728 string loader_format;
1729 vector<string> loaders = theConverters().loaders();
1730 if (find(loaders.begin(), loaders.end(), format) == loaders.end()) {
1731 for (vector<string>::const_iterator it = loaders.begin();
1732 it != loaders.end(); ++it) {
1733 if (!theConverters().isReachable(format, *it))
1736 string const tofile =
1737 support::changeExtension(filename.absFilename(),
1738 formats.extension(*it));
1739 if (!theConverters().convert(0, filename, FileName(tofile),
1740 filename, format, *it, errorList))
1742 loader_format = *it;
1745 if (loader_format.empty()) {
1746 frontend::Alert::error(_("Couldn't import file"),
1747 bformat(_("No information for importing the format %1$s."),
1748 formats.prettyName(format)));
1752 loader_format = format;
1754 if (loader_format == "lyx") {
1755 Buffer * buf = lv->loadDocument(lyxfile);
1758 buf->updateLabels();
1760 buf->errors("Parse");
1762 Buffer * const b = newFile(lyxfile.absFilename(), string(), true);
1766 bool as_paragraphs = loader_format == "textparagraph";
1767 string filename2 = (loader_format == format) ? filename.absFilename()
1768 : support::changeExtension(filename.absFilename(),
1769 formats.extension(loader_format));
1770 lv->currentBufferView()->insertPlaintextFile(FileName(filename2),
1772 guiApp->setCurrentView(lv);
1773 lyx::dispatch(FuncRequest(LFUN_MARK_OFF));
1780 void GuiView::importDocument(string const & argument)
1783 string filename = split(argument, format, ' ');
1785 LYXERR(Debug::INFO, format << " file: " << filename);
1787 // need user interaction
1788 if (filename.empty()) {
1789 string initpath = lyxrc.document_path;
1790 if (documentBufferView()) {
1791 string const trypath = documentBufferView()->buffer().filePath();
1792 // If directory is writeable, use this as default.
1793 if (FileName(trypath).isDirWritable())
1797 docstring const text = bformat(_("Select %1$s file to import"),
1798 formats.prettyName(format));
1800 FileDialog dlg(toqstr(text), LFUN_BUFFER_IMPORT);
1801 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1802 dlg.setButton2(qt_("Examples|#E#e"),
1803 toqstr(addPath(package().system_support().absFilename(), "examples")));
1805 docstring filter = formats.prettyName(format);
1808 filter += from_utf8(formats.extension(format));
1811 FileDialog::Result result =
1812 dlg.open(toqstr(initpath), fileFilters(toqstr(filter)));
1814 if (result.first == FileDialog::Later)
1817 filename = fromqstr(result.second);
1819 // check selected filename
1820 if (filename.empty())
1821 message(_("Canceled."));
1824 if (filename.empty())
1827 // get absolute path of file
1828 FileName const fullname(support::makeAbsPath(filename));
1830 FileName const lyxfile(support::changeExtension(fullname.absFilename(), ".lyx"));
1832 // Check if the document already is open
1833 Buffer * buf = theBufferList().getBuffer(lyxfile);
1836 if (!closeBuffer()) {
1837 message(_("Canceled."));
1842 docstring const displaypath = makeDisplayPath(lyxfile.absFilename(), 30);
1844 // if the file exists already, and we didn't do
1845 // -i lyx thefile.lyx, warn
1846 if (lyxfile.exists() && fullname != lyxfile) {
1848 docstring text = bformat(_("The document %1$s already exists.\n\n"
1849 "Do you want to overwrite that document?"), displaypath);
1850 int const ret = Alert::prompt(_("Overwrite document?"),
1851 text, 0, 1, _("&Overwrite"), _("&Cancel"));
1854 message(_("Canceled."));
1859 message(bformat(_("Importing %1$s..."), displaypath));
1860 ErrorList errorList;
1861 if (import(this, fullname, format, errorList))
1862 message(_("imported."));
1864 message(_("file not imported!"));
1866 // FIXME (Abdel 12/08/06): Is there a need to display the error list here?
1870 void GuiView::newDocument(string const & filename, bool from_template)
1872 FileName initpath(lyxrc.document_path);
1873 if (documentBufferView()) {
1874 FileName const trypath(documentBufferView()->buffer().filePath());
1875 // If directory is writeable, use this as default.
1876 if (trypath.isDirWritable())
1880 string templatefile;
1881 if (from_template) {
1882 templatefile = selectTemplateFile().absFilename();
1883 if (templatefile.empty())
1888 if (filename.empty())
1889 b = newUnnamedFile(initpath, to_utf8(_("newfile")), templatefile);
1891 b = newFile(filename, templatefile, true);
1896 // If no new document could be created, it is unsure
1897 // whether there is a valid BufferView.
1898 if (currentBufferView())
1899 // Ensure the cursor is correctly positioned on screen.
1900 currentBufferView()->showCursor();
1904 void GuiView::insertLyXFile(docstring const & fname)
1906 BufferView * bv = documentBufferView();
1911 FileName filename(to_utf8(fname));
1913 if (!filename.empty()) {
1914 bv->insertLyXFile(filename);
1918 // Launch a file browser
1920 string initpath = lyxrc.document_path;
1921 string const trypath = bv->buffer().filePath();
1922 // If directory is writeable, use this as default.
1923 if (FileName(trypath).isDirWritable())
1927 FileDialog dlg(qt_("Select LyX document to insert"), LFUN_FILE_INSERT);
1928 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1929 dlg.setButton2(qt_("Examples|#E#e"),
1930 toqstr(addPath(package().system_support().absFilename(),
1933 FileDialog::Result result = dlg.open(toqstr(initpath),
1934 QStringList(qt_("LyX Documents (*.lyx)")));
1936 if (result.first == FileDialog::Later)
1940 filename.set(fromqstr(result.second));
1942 // check selected filename
1943 if (filename.empty()) {
1944 // emit message signal.
1945 message(_("Canceled."));
1949 bv->insertLyXFile(filename);
1953 void GuiView::insertPlaintextFile(docstring const & fname,
1956 BufferView * bv = documentBufferView();
1960 if (!fname.empty() && !FileName::isAbsolute(to_utf8(fname))) {
1961 message(_("Absolute filename expected."));
1966 FileName filename(to_utf8(fname));
1968 if (!filename.empty()) {
1969 bv->insertPlaintextFile(filename, asParagraph);
1973 FileDialog dlg(qt_("Select file to insert"), (asParagraph ?
1974 LFUN_FILE_INSERT_PLAINTEXT_PARA : LFUN_FILE_INSERT_PLAINTEXT));
1976 FileDialog::Result result = dlg.open(toqstr(bv->buffer().filePath()),
1977 QStringList(qt_("All Files (*)")));
1979 if (result.first == FileDialog::Later)
1983 filename.set(fromqstr(result.second));
1985 // check selected filename
1986 if (filename.empty()) {
1987 // emit message signal.
1988 message(_("Canceled."));
1992 bv->insertPlaintextFile(filename, asParagraph);
1996 bool GuiView::renameBuffer(Buffer & b, docstring const & newname)
1998 FileName fname = b.fileName();
1999 FileName const oldname = fname;
2001 if (!newname.empty()) {
2003 fname = support::makeAbsPath(to_utf8(newname), oldname.onlyPath().absFilename());
2005 // Switch to this Buffer.
2008 // No argument? Ask user through dialog.
2010 FileDialog dlg(qt_("Choose a filename to save document as"),
2011 LFUN_BUFFER_WRITE_AS);
2012 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2013 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
2015 if (!isLyXFilename(fname.absFilename()))
2016 fname.changeExtension(".lyx");
2018 FileDialog::Result result =
2019 dlg.save(toqstr(fname.onlyPath().absFilename()),
2020 QStringList(qt_("LyX Documents (*.lyx)")),
2021 toqstr(fname.onlyFileName()));
2023 if (result.first == FileDialog::Later)
2026 fname.set(fromqstr(result.second));
2031 if (!isLyXFilename(fname.absFilename()))
2032 fname.changeExtension(".lyx");
2035 if (FileName(fname).exists()) {
2036 docstring const file = makeDisplayPath(fname.absFilename(), 30);
2037 docstring text = bformat(_("The document %1$s already "
2038 "exists.\n\nDo you want to "
2039 "overwrite that document?"),
2041 int const ret = Alert::prompt(_("Overwrite document?"),
2042 text, 0, 2, _("&Overwrite"), _("&Rename"), _("&Cancel"));
2045 case 1: return renameBuffer(b, docstring());
2046 case 2: return false;
2050 FileName oldauto = b.getAutosaveFilename();
2052 // Ok, change the name of the buffer
2053 b.setFileName(fname.absFilename());
2055 bool unnamed = b.isUnnamed();
2056 b.setUnnamed(false);
2057 b.saveCheckSum(fname);
2059 // bring the autosave file with us, just in case.
2060 b.moveAutosaveFile(oldauto);
2062 if (!saveBuffer(b)) {
2063 oldauto = b.getAutosaveFilename();
2064 b.setFileName(oldname.absFilename());
2065 b.setUnnamed(unnamed);
2066 b.saveCheckSum(oldname);
2067 b.moveAutosaveFile(oldauto);
2075 bool GuiView::saveBuffer(Buffer & b)
2077 if (workArea(b) && workArea(b)->inDialogMode())
2081 return renameBuffer(b, docstring());
2084 theSession().lastFiles().add(b.fileName());
2088 // Switch to this Buffer.
2091 // FIXME: we don't tell the user *WHY* the save failed !!
2092 docstring const file = makeDisplayPath(b.absFileName(), 30);
2093 docstring text = bformat(_("The document %1$s could not be saved.\n\n"
2094 "Do you want to rename the document and "
2095 "try again?"), file);
2096 int const ret = Alert::prompt(_("Rename and save?"),
2097 text, 0, 2, _("&Rename"), _("&Retry"), _("&Cancel"));
2100 if (!renameBuffer(b, docstring()))
2109 return saveBuffer(b);
2113 bool GuiView::hideWorkArea(GuiWorkArea * wa)
2115 return closeWorkArea(wa, false);
2119 bool GuiView::closeWorkArea(GuiWorkArea * wa)
2121 Buffer & buf = wa->bufferView().buffer();
2122 return closeWorkArea(wa, !buf.parent());
2126 bool GuiView::closeBuffer()
2128 GuiWorkArea * wa = currentMainWorkArea();
2129 Buffer & buf = wa->bufferView().buffer();
2130 return wa && closeWorkArea(wa, !buf.parent());
2134 void GuiView::writeSession() const {
2135 GuiWorkArea const * active_wa = currentMainWorkArea();
2136 for (int i = 0; i < d.splitter_->count(); ++i) {
2137 TabWorkArea * twa = d.tabWorkArea(i);
2138 for (int j = 0; j < twa->count(); ++j) {
2139 GuiWorkArea * wa = static_cast<GuiWorkArea *>(twa->widget(j));
2140 Buffer & buf = wa->bufferView().buffer();
2141 theSession().lastOpened().add(buf.fileName(), wa == active_wa);
2147 bool GuiView::closeBufferAll()
2149 // Close the workareas in all other views
2150 QList<int> const ids = guiApp->viewIds();
2151 for (int i = 0; i != ids.size(); ++i) {
2152 if (id_ != ids[i] && !guiApp->view(ids[i]).closeWorkAreaAll())
2156 // Close our own workareas
2157 if (!closeWorkAreaAll())
2160 // Now close the hidden buffers. We prevent hidden buffers from being
2161 // dirty, so we can just close them.
2162 theBufferList().closeAll();
2167 bool GuiView::closeWorkAreaAll()
2169 setCurrentWorkArea(currentMainWorkArea());
2171 // We might be in a situation that there is still a tabWorkArea, but
2172 // there are no tabs anymore. This can happen when we get here after a
2173 // TabWorkArea::lastWorkAreaRemoved() signal. Therefore we count how
2174 // many TabWorkArea's have no documents anymore.
2177 // We have to call count() each time, because it can happen that
2178 // more than one splitter will disappear in one iteration (bug 5998).
2179 for (; d.splitter_->count() > empty_twa; ) {
2180 TabWorkArea * twa = d.tabWorkArea(empty_twa);
2182 if (twa->count() == 0)
2185 setCurrentWorkArea(twa->currentWorkArea());
2186 if (!closeTabWorkArea(twa))
2194 bool GuiView::closeWorkArea(GuiWorkArea * wa, bool close_buffer)
2199 Buffer & buf = wa->bufferView().buffer();
2202 return closeBuffer(buf);
2204 if (!inMultiTabs(wa))
2205 if (!saveBufferIfNeeded(buf, true))
2213 bool GuiView::closeBuffer(Buffer & buf)
2215 // If we are in a close_event all children will be closed in some time,
2216 // so no need to do it here. This will ensure that the children end up
2217 // in the session file in the correct order. If we close the master
2218 // buffer, we can close or release the child buffers here too.
2220 vector<Buffer *> clist = buf.getChildren(false);
2221 for (vector<Buffer *>::const_iterator it = clist.begin();
2222 it != clist.end(); ++it) {
2223 // If a child is dirty, do not close
2224 // without user intervention
2225 //FIXME: should we look in other tabworkareas?
2226 Buffer * child_buf = *it;
2227 GuiWorkArea * child_wa = workArea(*child_buf);
2229 if (!closeWorkArea(child_wa, true))
2232 theBufferList().releaseChild(&buf, child_buf);
2235 // goto bookmark to update bookmark pit.
2236 //FIXME: we should update only the bookmarks related to this buffer!
2237 LYXERR(Debug::DEBUG, "GuiView::closeBuffer()");
2238 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
2239 theLyXFunc().gotoBookmark(i+1, false, false);
2241 if (saveBufferIfNeeded(buf, false)) {
2242 theBufferList().release(&buf);
2249 bool GuiView::closeTabWorkArea(TabWorkArea * twa)
2251 while (twa == d.currentTabWorkArea()) {
2252 twa->setCurrentIndex(twa->count()-1);
2254 GuiWorkArea * wa = twa->currentWorkArea();
2255 Buffer & b = wa->bufferView().buffer();
2257 // We only want to close the buffer if the same buffer is not visible
2258 // in another view, and if this is not a child and if we are closing
2259 // a view (not a tabgroup).
2260 bool const close_buffer =
2261 !inMultiViews(wa) && !b.parent() && closing_;
2263 if (!closeWorkArea(wa, close_buffer))
2270 bool GuiView::saveBufferIfNeeded(Buffer & buf, bool hiding)
2272 if (buf.isClean() || buf.paragraphs().empty())
2275 // Switch to this Buffer.
2280 if (buf.isUnnamed())
2281 file = from_utf8(buf.fileName().onlyFileName());
2283 file = buf.fileName().displayName(30);
2285 // Bring this window to top before asking questions.
2290 if (hiding && buf.isUnnamed()) {
2291 docstring const text = bformat(_("The document %1$s has not been "
2292 "saved yet.\n\nDo you want to save "
2293 "the document?"), file);
2294 ret = Alert::prompt(_("Save new document?"),
2295 text, 0, 1, _("&Save"), _("&Cancel"));
2299 docstring const text = bformat(_("The document %1$s has unsaved changes."
2300 "\n\nDo you want to save the document or discard the changes?"), file);
2301 ret = Alert::prompt(_("Save changed document?"),
2302 text, 0, 2, _("&Save"), _("&Discard"), _("&Cancel"));
2307 if (!saveBuffer(buf))
2311 // if we crash after this we could
2312 // have no autosave file but I guess
2313 // this is really improbable (Jug)
2314 buf.removeAutosaveFile();
2316 // revert all changes
2317 buf.loadLyXFile(buf.fileName());
2327 bool GuiView::inMultiTabs(GuiWorkArea * wa)
2329 Buffer & buf = wa->bufferView().buffer();
2331 for (int i = 0; i != d.splitter_->count(); ++i) {
2332 GuiWorkArea * wa_ = d.tabWorkArea(i)->workArea(buf);
2333 if (wa_ && wa_ != wa)
2336 return inMultiViews(wa);
2340 bool GuiView::inMultiViews(GuiWorkArea * wa)
2342 QList<int> const ids = guiApp->viewIds();
2343 Buffer & buf = wa->bufferView().buffer();
2346 for (int i = 0; i != ids.size() && found_twa <= 1; ++i) {
2350 if (guiApp->view(ids[i]).workArea(buf))
2357 void GuiView::gotoNextOrPreviousBuffer(NextOrPrevious np)
2359 Buffer * const curbuf = documentBufferView()
2360 ? &documentBufferView()->buffer() : 0;
2361 Buffer * nextbuf = curbuf;
2363 if (np == NEXTBUFFER)
2364 nextbuf = theBufferList().next(nextbuf);
2366 nextbuf = theBufferList().previous(nextbuf);
2367 if (nextbuf == curbuf)
2373 if (workArea(*nextbuf))
2380 /// make sure the document is saved
2381 static bool ensureBufferClean(Buffer * buffer)
2383 LASSERT(buffer, return false);
2384 if (buffer->isClean() && !buffer->isUnnamed())
2387 docstring const file = buffer->fileName().displayName(30);
2390 if (!buffer->isUnnamed()) {
2391 text = bformat(_("The document %1$s has unsaved "
2392 "changes.\n\nDo you want to save "
2393 "the document?"), file);
2394 title = _("Save changed document?");
2397 text = bformat(_("The document %1$s has not been "
2398 "saved yet.\n\nDo you want to save "
2399 "the document?"), file);
2400 title = _("Save new document?");
2402 int const ret = Alert::prompt(title, text, 0, 1, _("&Save"), _("&Cancel"));
2405 dispatch(FuncRequest(LFUN_BUFFER_WRITE));
2407 return buffer->isClean() && !buffer->isUnnamed();
2411 void GuiView::reloadBuffer()
2413 Buffer * buf = &documentBufferView()->buffer();
2418 void GuiView::reloadBuffer(Buffer * buf)
2420 FileName filename = buf->fileName();
2421 // e.g., read-only status could have changed due to version control
2423 Buffer const * parent = buf->parent();
2424 // The user has already confirmed that the changes, if any, should
2425 // be discarded. So we just release the Buffer and don't call closeBuffer();
2426 theBufferList().release(buf);
2427 buf = loadDocument(filename);
2428 docstring const disp_fn = makeDisplayPath(filename.absFilename());
2431 // re-allocate master if necessary
2432 if (parent && theBufferList().isLoaded(parent)
2433 && buf->parent() != parent)
2434 buf->setParent(parent);
2435 buf->updateLabels();
2437 buf->errors("Parse");
2438 str = bformat(_("Document %1$s reloaded."), disp_fn);
2440 str = bformat(_("Could not reload document %1$s"), disp_fn);
2446 void GuiView::checkExternallyModifiedBuffers()
2448 BufferList::iterator bit = theBufferList().begin();
2449 BufferList::iterator const bend = theBufferList().end();
2450 for (; bit != bend; ++bit) {
2451 if ((*bit)->fileName().exists()
2452 && (*bit)->isExternallyModified(Buffer::checksum_method)) {
2453 docstring text = bformat(_("Document \n%1$s\n has been externally modified."
2454 " Reload now? Any local changes will be lost."),
2455 from_utf8((*bit)->absFileName()));
2456 int const ret = Alert::prompt(_("Reload externally changed document?"),
2457 text, 0, 1, _("&Reload"), _("&Cancel"));
2465 void GuiView::dispatchVC(FuncRequest const & cmd)
2467 // message for statusbar
2469 Buffer * buffer = documentBufferView()
2470 ? &(documentBufferView()->buffer()) : 0;
2472 switch (cmd.action) {
2473 case LFUN_VC_REGISTER:
2474 if (!buffer || !ensureBufferClean(buffer))
2476 if (!buffer->lyxvc().inUse()) {
2477 if (buffer->lyxvc().registrer())
2482 case LFUN_VC_CHECK_IN:
2483 if (!buffer || !ensureBufferClean(buffer))
2485 if (buffer->lyxvc().inUse() && !buffer->isReadonly()) {
2486 msg = buffer->lyxvc().checkIn();
2491 case LFUN_VC_CHECK_OUT:
2492 if (!buffer || !ensureBufferClean(buffer))
2494 if (buffer->lyxvc().inUse()) {
2495 msg = buffer->lyxvc().checkOut();
2500 case LFUN_VC_LOCKING_TOGGLE:
2501 LASSERT(buffer, return);
2502 if (!ensureBufferClean(buffer) || buffer->isReadonly())
2504 if (buffer->lyxvc().inUse()) {
2505 string res = buffer->lyxvc().lockingToggle();
2507 frontend::Alert::error(_("Revision control error."),
2508 _("Error when setting the locking property."));
2516 case LFUN_VC_REVERT:
2517 LASSERT(buffer, return);
2518 buffer->lyxvc().revert();
2522 case LFUN_VC_UNDO_LAST:
2523 LASSERT(buffer, return);
2524 buffer->lyxvc().undoLast();
2528 case LFUN_VC_REPO_UPDATE:
2529 LASSERT(buffer, return);
2530 if (ensureBufferClean(buffer)) {
2531 msg = buffer->lyxvc().repoUpdate();
2532 checkExternallyModifiedBuffers();
2536 case LFUN_VC_COMMAND: {
2537 string flag = cmd.getArg(0);
2538 if (buffer && contains(flag, 'R') && !ensureBufferClean(buffer))
2541 if (contains(flag, 'M')) {
2542 if (!Alert::askForText(message, _("LyX VC: Log Message")))
2545 string path = cmd.getArg(1);
2546 if (contains(path, "$$p") && buffer)
2547 path = subst(path, "$$p", buffer->filePath());
2548 LYXERR(Debug::LYXVC, "Directory: " << path);
2550 if (!pp.isReadableDirectory()) {
2551 lyxerr << _("Directory is not accessible.") << endl;
2554 support::PathChanger p(pp);
2556 string command = cmd.getArg(2);
2557 if (command.empty())
2560 command = subst(command, "$$i", buffer->absFileName());
2561 command = subst(command, "$$p", buffer->filePath());
2563 command = subst(command, "$$m", to_utf8(message));
2564 LYXERR(Debug::LYXVC, "Command: " << command);
2566 one.startscript(Systemcall::Wait, command);
2570 if (contains(flag, 'I'))
2571 buffer->markDirty();
2572 if (contains(flag, 'R'))
2582 message(from_utf8(msg));
2586 void GuiView::openChildDocument(string const & fname)
2588 LASSERT(documentBufferView(), return);
2589 Buffer & buffer = documentBufferView()->buffer();
2590 FileName const filename = support::makeAbsPath(fname, buffer.filePath());
2591 documentBufferView()->saveBookmark(false);
2593 bool parsed = false;
2594 if (theBufferList().exists(filename)) {
2595 child = theBufferList().getBuffer(filename);
2597 message(bformat(_("Opening child document %1$s..."),
2598 makeDisplayPath(filename.absFilename())));
2599 child = loadDocument(filename, false);
2605 // Set the parent name of the child document.
2606 // This makes insertion of citations and references in the child work,
2607 // when the target is in the parent or another child document.
2608 child->setParent(&buffer);
2609 child->masterBuffer()->updateLabels();
2612 child->errors("Parse");
2616 bool GuiView::goToFileRow(string const & argument)
2620 size_t i = argument.find_last_of(' ');
2621 if (i != string::npos) {
2622 file_name = os::internal_path(trim(argument.substr(0, i)));
2623 istringstream is(argument.substr(i + 1));
2628 if (i == string::npos) {
2629 LYXERR0("Wrong argument: " << argument);
2633 string const abstmp = package().temp_dir().absFilename();
2634 string const realtmp = package().temp_dir().realPath();
2635 // We have to use os::path_prefix_is() here, instead of
2636 // simply prefixIs(), because the file name comes from
2637 // an external application and may need case adjustment.
2638 if (os::path_prefix_is(file_name, abstmp, os::CASE_ADJUSTED)
2639 || os::path_prefix_is(file_name, realtmp, os::CASE_ADJUSTED)) {
2640 // Needed by inverse dvi search. If it is a file
2641 // in tmpdir, call the apropriated function.
2642 // If tmpdir is a symlink, we may have the real
2643 // path passed back, so we correct for that.
2644 if (!prefixIs(file_name, abstmp))
2645 file_name = subst(file_name, realtmp, abstmp);
2646 buf = theBufferList().getBufferFromTmp(file_name);
2648 // Must replace extension of the file to be .lyx
2649 // and get full path
2650 FileName const s = fileSearch(string(),
2651 support::changeExtension(file_name, ".lyx"), "lyx");
2652 // Either change buffer or load the file
2653 if (theBufferList().exists(s))
2654 buf = theBufferList().getBuffer(s);
2655 else if (s.exists()) {
2656 buf = loadDocument(s);
2657 buf->updateLabels();
2658 buf->errors("Parse");
2661 _("File does not exist: %1$s"),
2662 makeDisplayPath(file_name)));
2667 documentBufferView()->setCursorFromRow(row);
2672 #if (QT_VERSION >= 0x040400)
2673 static docstring exportAndDestroy(Buffer * buffer, string const & format)
2675 bool const success = buffer->doExport(format, true);
2678 ? bformat(_("Successful export to format: %1$s"), from_utf8(format))
2679 : bformat(_("Error exporting to format: %1$s"), from_utf8(format));
2683 static docstring previewAndDestroy(Buffer * buffer, string const & format)
2685 bool const success = buffer->preview(format);
2688 ? bformat(_("Successful preview of format: %1$s"), from_utf8(format))
2689 : bformat(_("Error previewing format: %1$s"), from_utf8(format));
2694 bool GuiView::dispatch(FuncRequest const & cmd)
2696 BufferView * bv = currentBufferView();
2697 // By default we won't need any update.
2699 bv->cursor().updateFlags(Update::None);
2701 Buffer * doc_buffer = documentBufferView()
2702 ? &(documentBufferView()->buffer()) : 0;
2704 bool dispatched = true;
2706 if (cmd.origin == FuncRequest::TOC) {
2707 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
2708 toc->doDispatch(bv->cursor(), cmd);
2712 string const argument = to_utf8(cmd.argument());
2714 switch(cmd.action) {
2715 case LFUN_BUFFER_CHILD_OPEN:
2716 openChildDocument(to_utf8(cmd.argument()));
2719 case LFUN_BUFFER_IMPORT:
2720 importDocument(to_utf8(cmd.argument()));
2723 case LFUN_BUFFER_EXPORT: {
2726 if (cmd.argument() == "custom") {
2727 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "sendto"));
2730 if (doc_buffer->doExport(argument, false)) {
2731 message(bformat(_("Error exporting to format: %1$s."),
2737 case LFUN_BUFFER_UPDATE: {
2740 string format = argument;
2741 if (argument.empty())
2742 format = doc_buffer->getDefaultOutputFormat();
2743 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
2744 d.progress_->clearMessages();
2745 message(_("Exporting ..."));
2746 QFuture<docstring> f = QtConcurrent::run(exportAndDestroy,
2747 doc_buffer->clone(), format);
2748 d.setPreviewFuture(f);
2750 doc_buffer->doExport(format, true);
2754 case LFUN_BUFFER_VIEW: {
2757 string format = argument;
2758 if (argument.empty())
2759 format = doc_buffer->getDefaultOutputFormat();
2760 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
2761 d.progress_->clearMessages();
2762 message(_("Previewing ..."));
2763 QFuture<docstring> f = QtConcurrent::run(previewAndDestroy,
2764 doc_buffer->clone(), format);
2765 d.setPreviewFuture(f);
2767 doc_buffer->preview(format);
2771 case LFUN_MASTER_BUFFER_UPDATE: {
2774 string format = argument;
2775 Buffer const * master = doc_buffer->masterBuffer();
2776 if (argument.empty())
2777 format = master->getDefaultOutputFormat();
2778 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
2779 QFuture<docstring> f = QtConcurrent::run(exportAndDestroy,
2780 master->clone(), format);
2781 d.setPreviewFuture(f);
2783 master->doExport(format, true);
2787 case LFUN_MASTER_BUFFER_VIEW: {
2788 string format = argument;
2789 Buffer const * master = doc_buffer->masterBuffer();
2790 if (argument.empty())
2791 format = master->getDefaultOutputFormat();
2792 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
2793 QFuture<docstring> f = QtConcurrent::run(previewAndDestroy,
2794 master->clone(), format);
2795 d.setPreviewFuture(f);
2797 master->preview(format);
2801 case LFUN_BUFFER_SWITCH:
2802 if (FileName::isAbsolute(to_utf8(cmd.argument()))) {
2804 theBufferList().getBuffer(FileName(to_utf8(cmd.argument())));
2808 message(_("Document not loaded"));
2812 case LFUN_BUFFER_NEXT:
2813 gotoNextOrPreviousBuffer(NEXTBUFFER);
2816 case LFUN_BUFFER_PREVIOUS:
2817 gotoNextOrPreviousBuffer(PREVBUFFER);
2820 case LFUN_COMMAND_EXECUTE: {
2821 bool const show_it = cmd.argument() != "off";
2822 // FIXME: this is a hack, "minibuffer" should not be
2824 if (GuiToolbar * t = toolbar("minibuffer")) {
2825 t->setVisible(show_it);
2826 if (show_it && t->commandBuffer())
2827 t->commandBuffer()->setFocus();
2831 case LFUN_DROP_LAYOUTS_CHOICE:
2832 d.layout_->showPopup();
2835 case LFUN_MENU_OPEN:
2836 if (QMenu * menu = guiApp->menus().menu(toqstr(cmd.argument()), *this))
2837 menu->exec(QCursor::pos());
2840 case LFUN_FILE_INSERT:
2841 insertLyXFile(cmd.argument());
2843 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
2844 insertPlaintextFile(cmd.argument(), true);
2847 case LFUN_FILE_INSERT_PLAINTEXT:
2848 insertPlaintextFile(cmd.argument(), false);
2851 case LFUN_BUFFER_RELOAD: {
2852 LASSERT(doc_buffer, break);
2853 docstring const file = makeDisplayPath(doc_buffer->absFileName(), 20);
2854 docstring text = bformat(_("Any changes will be lost. Are you sure "
2855 "you want to revert to the saved version of the document %1$s?"), file);
2856 int const ret = Alert::prompt(_("Revert to saved document?"),
2857 text, 1, 1, _("&Revert"), _("&Cancel"));
2860 doc_buffer->markClean();
2866 case LFUN_BUFFER_WRITE:
2867 LASSERT(doc_buffer, break);
2868 saveBuffer(*doc_buffer);
2871 case LFUN_BUFFER_WRITE_AS:
2872 LASSERT(doc_buffer, break);
2873 renameBuffer(*doc_buffer, cmd.argument());
2876 case LFUN_BUFFER_WRITE_ALL: {
2877 Buffer * first = theBufferList().first();
2880 message(_("Saving all documents..."));
2881 // We cannot use a for loop as the buffer list cycles.
2884 if (!b->isClean()) {
2886 LYXERR(Debug::ACTION, "Saved " << b->absFileName());
2888 b = theBufferList().next(b);
2889 } while (b != first);
2890 message(_("All documents saved."));
2894 case LFUN_BUFFER_CLOSE:
2898 case LFUN_BUFFER_CLOSE_ALL:
2902 case LFUN_TOOLBAR_TOGGLE: {
2903 string const name = cmd.getArg(0);
2904 if (GuiToolbar * t = toolbar(name))
2909 case LFUN_DIALOG_UPDATE: {
2910 string const name = to_utf8(cmd.argument());
2911 if (currentBufferView()) {
2912 Inset * inset = currentBufferView()->editedInset(name);
2913 // Can only update a dialog connected to an existing inset
2916 // FIXME: get rid of this indirection; GuiView ask the inset
2917 // if he is kind enough to update itself...
2918 FuncRequest fr(LFUN_INSET_DIALOG_UPDATE, cmd.argument());
2919 inset->dispatch(currentBufferView()->cursor(), fr);
2920 } else if (name == "paragraph") {
2921 lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
2922 } else if (name == "prefs" || name == "document") {
2923 updateDialog(name, string());
2928 case LFUN_DIALOG_TOGGLE: {
2929 if (isDialogVisible(cmd.getArg(0)))
2930 dispatch(FuncRequest(LFUN_DIALOG_HIDE, cmd.argument()));
2932 dispatch(FuncRequest(LFUN_DIALOG_SHOW, cmd.argument()));
2936 case LFUN_DIALOG_DISCONNECT_INSET:
2937 disconnectDialog(to_utf8(cmd.argument()));
2940 case LFUN_DIALOG_HIDE: {
2941 guiApp->hideDialogs(to_utf8(cmd.argument()), 0);
2945 case LFUN_DIALOG_SHOW: {
2946 string const name = cmd.getArg(0);
2947 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
2949 if (name == "character") {
2950 data = freefont2string();
2952 showDialog("character", data);
2953 } else if (name == "latexlog") {
2954 Buffer::LogType type;
2955 string const logfile = doc_buffer->logName(&type);
2957 case Buffer::latexlog:
2960 case Buffer::buildlog:
2964 data += Lexer::quoteString(logfile);
2965 showDialog("log", data);
2966 } else if (name == "vclog") {
2967 string const data = "vc " +
2968 Lexer::quoteString(doc_buffer->lyxvc().getLogFile());
2969 showDialog("log", data);
2970 } else if (name == "symbols") {
2971 data = bv->cursor().getEncoding()->name();
2973 showDialog("symbols", data);
2975 } else if (name == "prefs" && isFullScreen()) {
2976 FuncRequest fr(LFUN_INSET_INSERT, "fullscreen");
2978 showDialog("prefs", data);
2980 showDialog(name, data);
2985 message(cmd.argument());
2988 case LFUN_UI_TOGGLE:
2990 // Make sure the keyboard focus stays in the work area.
2994 case LFUN_SPLIT_VIEW: {
2995 LASSERT(doc_buffer, break);
2996 string const orientation = cmd.getArg(0);
2997 d.splitter_->setOrientation(orientation == "vertical"
2998 ? Qt::Vertical : Qt::Horizontal);
2999 TabWorkArea * twa = addTabWorkArea();
3000 GuiWorkArea * wa = twa->addWorkArea(*doc_buffer, *this);
3001 setCurrentWorkArea(wa);
3004 case LFUN_CLOSE_TAB_GROUP:
3005 if (TabWorkArea * twa = d.currentTabWorkArea()) {
3006 closeTabWorkArea(twa);
3007 d.current_work_area_ = 0;
3008 twa = d.currentTabWorkArea();
3009 // Switch to the next GuiWorkArea in the found TabWorkArea.
3011 // Make sure the work area is up to date.
3012 setCurrentWorkArea(twa->currentWorkArea());
3014 setCurrentWorkArea(0);
3019 case LFUN_COMPLETION_INLINE:
3020 if (d.current_work_area_)
3021 d.current_work_area_->completer().showInline();
3024 case LFUN_COMPLETION_POPUP:
3025 if (d.current_work_area_)
3026 d.current_work_area_->completer().showPopup();
3030 case LFUN_COMPLETION_COMPLETE:
3031 if (d.current_work_area_)
3032 d.current_work_area_->completer().tab();
3035 case LFUN_COMPLETION_CANCEL:
3036 if (d.current_work_area_) {
3037 if (d.current_work_area_->completer().popupVisible())
3038 d.current_work_area_->completer().hidePopup();
3040 d.current_work_area_->completer().hideInline();
3044 case LFUN_COMPLETION_ACCEPT:
3045 if (d.current_work_area_)
3046 d.current_work_area_->completer().activate();
3049 case LFUN_BUFFER_ZOOM_IN:
3050 case LFUN_BUFFER_ZOOM_OUT:
3051 if (cmd.argument().empty()) {
3052 if (cmd.action == LFUN_BUFFER_ZOOM_IN)
3057 lyxrc.zoom += convert<int>(cmd.argument());
3059 if (lyxrc.zoom < 10)
3062 // The global QPixmapCache is used in GuiPainter to cache text
3063 // painting so we must reset it.
3064 QPixmapCache::clear();
3065 guiApp->fontLoader().update();
3066 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
3069 case LFUN_VC_REGISTER:
3070 case LFUN_VC_CHECK_IN:
3071 case LFUN_VC_CHECK_OUT:
3072 case LFUN_VC_REPO_UPDATE:
3073 case LFUN_VC_LOCKING_TOGGLE:
3074 case LFUN_VC_REVERT:
3075 case LFUN_VC_UNDO_LAST:
3076 case LFUN_VC_COMMAND:
3080 case LFUN_SERVER_GOTO_FILE_ROW:
3081 goToFileRow(to_utf8(cmd.argument()));
3089 // Part of automatic menu appearance feature.
3090 if (isFullScreen()) {
3091 if (menuBar()->isVisible() && lyxrc.full_screen_menubar)
3093 if (statusBar()->isVisible())
3094 statusBar()->hide();
3101 void GuiView::lfunUiToggle(FuncRequest const & cmd)
3103 string const arg = cmd.getArg(0);
3104 if (arg == "scrollbar") {
3105 // hide() is of no help
3106 if (d.current_work_area_->verticalScrollBarPolicy() ==
3107 Qt::ScrollBarAlwaysOff)
3109 d.current_work_area_->setVerticalScrollBarPolicy(
3110 Qt::ScrollBarAsNeeded);
3112 d.current_work_area_->setVerticalScrollBarPolicy(
3113 Qt::ScrollBarAlwaysOff);
3116 if (arg == "statusbar") {
3117 statusBar()->setVisible(!statusBar()->isVisible());
3120 if (arg == "menubar") {
3121 menuBar()->setVisible(!menuBar()->isVisible());
3124 #if QT_VERSION >= 0x040300
3125 if (arg == "frame") {
3127 getContentsMargins(&l, &t, &r, &b);
3128 //are the frames in default state?
3129 d.current_work_area_->setFrameStyle(QFrame::NoFrame);
3131 setContentsMargins(-2, -2, -2, -2);
3133 setContentsMargins(0, 0, 0, 0);
3138 if (arg == "fullscreen") {
3143 message(bformat("LFUN_UI_TOGGLE " + _("%1$s unknown command!"), from_utf8(arg)));
3147 void GuiView::toggleFullScreen()
3149 if (isFullScreen()) {
3150 for (int i = 0; i != d.splitter_->count(); ++i)
3151 d.tabWorkArea(i)->setFullScreen(false);
3152 #if QT_VERSION >= 0x040300
3153 setContentsMargins(0, 0, 0, 0);
3155 setWindowState(windowState() ^ Qt::WindowFullScreen);
3158 statusBar()->show();
3161 hideDialogs("prefs", 0);
3162 for (int i = 0; i != d.splitter_->count(); ++i)
3163 d.tabWorkArea(i)->setFullScreen(true);
3164 #if QT_VERSION >= 0x040300
3165 setContentsMargins(-2, -2, -2, -2);
3168 setWindowState(windowState() ^ Qt::WindowFullScreen);
3169 statusBar()->hide();
3170 if (lyxrc.full_screen_menubar)
3172 if (lyxrc.full_screen_toolbars) {
3173 ToolbarMap::iterator end = d.toolbars_.end();
3174 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
3179 // give dialogs like the TOC a chance to adapt
3184 Buffer const * GuiView::updateInset(Inset const * inset)
3186 if (!d.current_work_area_)
3190 d.current_work_area_->scheduleRedraw();
3192 return &d.current_work_area_->bufferView().buffer();
3196 void GuiView::restartCursor()
3198 /* When we move around, or type, it's nice to be able to see
3199 * the cursor immediately after the keypress.
3201 if (d.current_work_area_)
3202 d.current_work_area_->startBlinkingCursor();
3204 // Take this occasion to update the other GUI elements.
3210 void GuiView::updateCompletion(Cursor & cur, bool start, bool keep)
3212 if (d.current_work_area_)
3213 d.current_work_area_->completer().updateVisibility(cur, start, keep);
3218 // This list should be kept in sync with the list of insets in
3219 // src/insets/Inset.cpp. I.e., if a dialog goes with an inset, the
3220 // dialog should have the same name as the inset.
3221 // Changes should be also recorded in LFUN_DIALOG_SHOW doxygen
3222 // docs in LyXAction.cpp.
3224 char const * const dialognames[] = {
3225 "aboutlyx", "bibitem", "bibtex", "box", "branch", "changes", "character",
3226 "citation", "compare", "document", "errorlist", "ert", "external", "file",
3227 "findreplace", "findreplaceadv", "float", "graphics", "href", "include",
3228 "index", "index_print", "info", "listings", "label", "log", "mathdelimiter",
3229 "mathmatrix", "mathspace", "nomenclature", "nomencl_print", "note",
3230 "paragraph", "phantom", "prefs", "print", "ref", "sendto", "space",
3231 "spellchecker", "symbols", "tabular", "tabularcreate", "thesaurus", "texinfo",
3232 "toc", "view-source", "vspace", "wrap", "progress"};
3234 char const * const * const end_dialognames =
3235 dialognames + (sizeof(dialognames) / sizeof(char *));
3239 cmpCStr(char const * name) : name_(name) {}
3240 bool operator()(char const * other) {
3241 return strcmp(other, name_) == 0;
3248 bool isValidName(string const & name)
3250 return find_if(dialognames, end_dialognames,
3251 cmpCStr(name.c_str())) != end_dialognames;
3257 void GuiView::resetDialogs()
3259 // Make sure that no LFUN uses any LyXView.
3260 guiApp->setCurrentView(0);
3263 constructToolbars();
3264 guiApp->menus().fillMenuBar(menuBar(), this, false);
3265 d.layout_->updateContents(true);
3266 // Now update controls with current buffer.
3267 guiApp->setCurrentView(this);
3273 Dialog * GuiView::findOrBuild(string const & name, bool hide_it)
3275 if (!isValidName(name))
3278 map<string, DialogPtr>::iterator it = d.dialogs_.find(name);
3280 if (it != d.dialogs_.end()) {
3282 it->second->hideView();
3283 return it->second.get();
3286 Dialog * dialog = build(name);
3287 d.dialogs_[name].reset(dialog);
3288 if (lyxrc.allow_geometry_session)
3289 dialog->restoreSession();
3296 void GuiView::showDialog(string const & name, string const & data,
3299 triggerShowDialog(toqstr(name), toqstr(data), inset);
3303 void GuiView::doShowDialog(QString const & qname, QString const & qdata,
3309 const string name = fromqstr(qname);
3310 const string data = fromqstr(qdata);
3314 Dialog * dialog = findOrBuild(name, false);
3316 dialog->showData(data);
3317 if (inset && currentBufferView())
3318 currentBufferView()->editInset(name, inset);
3321 catch (ExceptionMessage const & ex) {
3329 bool GuiView::isDialogVisible(string const & name) const
3331 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3332 if (it == d.dialogs_.end())
3334 return it->second.get()->isVisibleView() && !it->second.get()->isClosing();
3338 void GuiView::hideDialog(string const & name, Inset * inset)
3340 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3341 if (it == d.dialogs_.end())
3344 if (inset && currentBufferView()
3345 && inset != currentBufferView()->editedInset(name))
3348 Dialog * const dialog = it->second.get();
3349 if (dialog->isVisibleView())
3351 if (currentBufferView())
3352 currentBufferView()->editInset(name, 0);
3356 void GuiView::disconnectDialog(string const & name)
3358 if (!isValidName(name))
3360 if (currentBufferView())
3361 currentBufferView()->editInset(name, 0);
3365 void GuiView::hideAll() const
3367 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
3368 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3370 for(; it != end; ++it)
3371 it->second->hideView();
3375 void GuiView::updateDialogs()
3377 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
3378 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3380 for(; it != end; ++it) {
3381 Dialog * dialog = it->second.get();
3382 if (dialog && dialog->isVisibleView())
3383 dialog->checkStatus();
3390 // will be replaced by a proper factory...
3391 Dialog * createGuiAbout(GuiView & lv);
3392 Dialog * createGuiBibitem(GuiView & lv);
3393 Dialog * createGuiBibtex(GuiView & lv);
3394 Dialog * createGuiBox(GuiView & lv);
3395 Dialog * createGuiBranch(GuiView & lv);
3396 Dialog * createGuiChanges(GuiView & lv);
3397 Dialog * createGuiCharacter(GuiView & lv);
3398 Dialog * createGuiCitation(GuiView & lv);
3399 Dialog * createGuiCompare(GuiView & lv);
3400 Dialog * createGuiDelimiter(GuiView & lv);
3401 Dialog * createGuiDocument(GuiView & lv);
3402 Dialog * createGuiErrorList(GuiView & lv);
3403 Dialog * createGuiERT(GuiView & lv);
3404 Dialog * createGuiExternal(GuiView & lv);
3405 Dialog * createGuiFloat(GuiView & lv);
3406 Dialog * createGuiGraphics(GuiView & lv);
3407 Dialog * createGuiInclude(GuiView & lv);
3408 Dialog * createGuiIndex(GuiView & lv);
3409 Dialog * createGuiInfo(GuiView & lv);
3410 Dialog * createGuiLabel(GuiView & lv);
3411 Dialog * createGuiListings(GuiView & lv);
3412 Dialog * createGuiLog(GuiView & lv);
3413 Dialog * createGuiMathHSpace(GuiView & lv);
3414 Dialog * createGuiMathMatrix(GuiView & lv);
3415 Dialog * createGuiNomenclature(GuiView & lv);
3416 Dialog * createGuiNote(GuiView & lv);
3417 Dialog * createGuiParagraph(GuiView & lv);
3418 Dialog * createGuiPhantom(GuiView & lv);
3419 Dialog * createGuiPreferences(GuiView & lv);
3420 Dialog * createGuiPrint(GuiView & lv);
3421 Dialog * createGuiPrintindex(GuiView & lv);
3422 Dialog * createGuiPrintNomencl(GuiView & lv);
3423 Dialog * createGuiRef(GuiView & lv);
3424 Dialog * createGuiSearch(GuiView & lv);
3425 Dialog * createGuiSearchAdv(GuiView & lv);
3426 Dialog * createGuiSendTo(GuiView & lv);
3427 Dialog * createGuiShowFile(GuiView & lv);
3428 Dialog * createGuiSpellchecker(GuiView & lv);
3429 Dialog * createGuiSymbols(GuiView & lv);
3430 Dialog * createGuiTabularCreate(GuiView & lv);
3431 Dialog * createGuiTabular(GuiView & lv);
3432 Dialog * createGuiTexInfo(GuiView & lv);
3433 Dialog * createGuiTextHSpace(GuiView & lv);
3434 Dialog * createGuiToc(GuiView & lv);
3435 Dialog * createGuiThesaurus(GuiView & lv);
3436 Dialog * createGuiHyperlink(GuiView & lv);
3437 Dialog * createGuiVSpace(GuiView & lv);
3438 Dialog * createGuiViewSource(GuiView & lv);
3439 Dialog * createGuiWrap(GuiView & lv);
3440 Dialog * createGuiProgressView(GuiView & lv);
3444 Dialog * GuiView::build(string const & name)
3446 LASSERT(isValidName(name), return 0);
3448 if (name == "aboutlyx")
3449 return createGuiAbout(*this);
3450 if (name == "bibitem")
3451 return createGuiBibitem(*this);
3452 if (name == "bibtex")
3453 return createGuiBibtex(*this);
3455 return createGuiBox(*this);
3456 if (name == "branch")
3457 return createGuiBranch(*this);
3458 if (name == "changes")
3459 return createGuiChanges(*this);
3460 if (name == "character")
3461 return createGuiCharacter(*this);
3462 if (name == "citation")
3463 return createGuiCitation(*this);
3464 if (name == "compare")
3465 return createGuiCompare(*this);
3466 if (name == "document")
3467 return createGuiDocument(*this);
3468 if (name == "errorlist")
3469 return createGuiErrorList(*this);
3471 return createGuiERT(*this);
3472 if (name == "external")
3473 return createGuiExternal(*this);
3475 return createGuiShowFile(*this);
3476 if (name == "findreplace")
3477 return createGuiSearch(*this);
3478 if (name == "findreplaceadv")
3479 return createGuiSearchAdv(*this);
3480 if (name == "float")
3481 return createGuiFloat(*this);
3482 if (name == "graphics")
3483 return createGuiGraphics(*this);
3485 return createGuiHyperlink(*this);
3486 if (name == "include")
3487 return createGuiInclude(*this);
3488 if (name == "index")
3489 return createGuiIndex(*this);
3490 if (name == "index_print")
3491 return createGuiPrintindex(*this);
3493 return createGuiInfo(*this);
3494 if (name == "label")
3495 return createGuiLabel(*this);
3496 if (name == "listings")
3497 return createGuiListings(*this);
3499 return createGuiLog(*this);
3500 if (name == "mathdelimiter")
3501 return createGuiDelimiter(*this);
3502 if (name == "mathspace")
3503 return createGuiMathHSpace(*this);
3504 if (name == "mathmatrix")
3505 return createGuiMathMatrix(*this);
3506 if (name == "nomenclature")
3507 return createGuiNomenclature(*this);
3508 if (name == "nomencl_print")
3509 return createGuiPrintNomencl(*this);
3511 return createGuiNote(*this);
3512 if (name == "paragraph")
3513 return createGuiParagraph(*this);
3514 if (name == "phantom")
3515 return createGuiPhantom(*this);
3516 if (name == "prefs")
3517 return createGuiPreferences(*this);
3518 if (name == "print")
3519 return createGuiPrint(*this);
3521 return createGuiRef(*this);
3522 if (name == "sendto")
3523 return createGuiSendTo(*this);
3524 if (name == "space")
3525 return createGuiTextHSpace(*this);
3526 if (name == "spellchecker")
3527 return createGuiSpellchecker(*this);
3528 if (name == "symbols")
3529 return createGuiSymbols(*this);
3530 if (name == "tabular")
3531 return createGuiTabular(*this);
3532 if (name == "tabularcreate")
3533 return createGuiTabularCreate(*this);
3534 if (name == "texinfo")
3535 return createGuiTexInfo(*this);
3536 if (name == "thesaurus")
3537 return createGuiThesaurus(*this);
3539 return createGuiToc(*this);
3540 if (name == "view-source")
3541 return createGuiViewSource(*this);
3542 if (name == "vspace")
3543 return createGuiVSpace(*this);
3545 return createGuiWrap(*this);
3546 if (name == "progress")
3547 return createGuiProgressView(*this);
3553 } // namespace frontend
3556 #include "moc_GuiView.cpp"