3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Lars Gullik Bjønnes
8 * \author Abdelrazak Younes
11 * Full author contact details are available in file CREDITS.
19 #include "FileDialog.h"
20 #include "FontLoader.h"
21 #include "GuiApplication.h"
22 #include "GuiCommandBuffer.h"
23 #include "GuiCompleter.h"
24 #include "GuiWorkArea.h"
25 #include "GuiKeySymbol.h"
27 #include "GuiToolbar.h"
28 #include "LayoutBox.h"
32 #include "qt_helpers.h"
34 #include "frontends/alert.h"
36 #include "buffer_funcs.h"
38 #include "BufferList.h"
39 #include "BufferParams.h"
40 #include "BufferView.h"
41 #include "Converter.h"
43 #include "CutAndPaste.h"
45 #include "ErrorList.h"
47 #include "FuncStatus.h"
48 #include "FuncRequest.h"
52 #include "LyXAction.h"
57 #include "Paragraph.h"
58 #include "SpellChecker.h"
59 #include "TextClass.h"
64 #include "support/convert.h"
65 #include "support/debug.h"
66 #include "support/ExceptionMessage.h"
67 #include "support/FileName.h"
68 #include "support/filetools.h"
69 #include "support/gettext.h"
70 #include "support/filetools.h"
71 #include "support/ForkedCalls.h"
72 #include "support/lassert.h"
73 #include "support/lstrings.h"
74 #include "support/os.h"
75 #include "support/Package.h"
76 #include "support/Path.h"
77 #include "support/Systemcall.h"
78 #include "support/Timeout.h"
79 #include "support/ProgressInterface.h"
80 #include "GuiProgress.h"
83 #include <QApplication>
84 #include <QCloseEvent>
86 #include <QDesktopWidget>
87 #include <QDragEnterEvent>
94 #include <QPixmapCache>
96 #include <QPushButton>
100 #include <QStackedWidget>
101 #include <QStatusBar>
106 #include <QScrollBar>
108 #define EXPORT_in_THREAD 1
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 static docstring saveAndDestroyBuffer(Buffer * buffer, FileName const & fname)
1273 FileName const tmp_ret = FileName::tempName("lyxauto");
1274 if (!tmp_ret.empty()) {
1275 if (buffer->writeFile(tmp_ret))
1276 failed = !tmp_ret.moveTo(fname);
1279 // failed to write/rename tmp_ret so try writing direct
1280 failed = buffer->writeFile(fname);
1284 ? _("Automatic save failed!")
1285 : _("Automatic save done.");
1289 void GuiView::autoSave()
1291 LYXERR(Debug::INFO, "Running autoSave()");
1293 Buffer * buffer = documentBufferView()
1294 ? &documentBufferView()->buffer() : 0;
1298 #if (QT_VERSION >= 0x040400)
1299 QFuture<docstring> f = QtConcurrent::run(saveAndDestroyBuffer, buffer->clone(),
1300 buffer->getAutosaveFilename());
1301 d.autosave_watcher_.setFuture(f);
1308 void GuiView::resetAutosaveTimers()
1311 d.autosave_timeout_.restart();
1315 bool GuiView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1318 Buffer * buf = currentBufferView()
1319 ? ¤tBufferView()->buffer() : 0;
1320 Buffer * doc_buffer = documentBufferView()
1321 ? &(documentBufferView()->buffer()) : 0;
1323 // Check whether we need a buffer
1324 if (!lyxaction.funcHasFlag(cmd.action, LyXAction::NoBuffer) && !buf) {
1325 // no, exit directly
1326 flag.message(from_utf8(N_("Command not allowed with"
1327 "out any document open")));
1328 flag.setEnabled(false);
1332 if (cmd.origin == FuncRequest::TOC) {
1333 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
1335 if (toc->getStatus(documentBufferView()->cursor(), cmd, fs))
1338 flag.setEnabled(false);
1342 switch(cmd.action) {
1343 case LFUN_BUFFER_IMPORT:
1346 case LFUN_MASTER_BUFFER_UPDATE:
1347 case LFUN_MASTER_BUFFER_VIEW:
1348 enable = doc_buffer && doc_buffer->parent() != 0
1349 && !d.preview_watcher_.isRunning();
1352 case LFUN_BUFFER_UPDATE:
1353 case LFUN_BUFFER_VIEW: {
1354 if (!doc_buffer || d.preview_watcher_.isRunning()) {
1358 string format = to_utf8(cmd.argument());
1359 if (cmd.argument().empty())
1360 format = doc_buffer->getDefaultOutputFormat();
1361 enable = doc_buffer->isExportableFormat(format);
1365 case LFUN_BUFFER_RELOAD:
1366 enable = doc_buffer && !doc_buffer->isUnnamed()
1367 && doc_buffer->fileName().exists()
1368 && (!doc_buffer->isClean()
1369 || doc_buffer->isExternallyModified(Buffer::timestamp_method));
1372 case LFUN_BUFFER_CHILD_OPEN:
1373 enable = doc_buffer;
1376 case LFUN_BUFFER_WRITE:
1377 enable = doc_buffer && (doc_buffer->isUnnamed() || !doc_buffer->isClean());
1380 //FIXME: This LFUN should be moved to GuiApplication.
1381 case LFUN_BUFFER_WRITE_ALL: {
1382 // We enable the command only if there are some modified buffers
1383 Buffer * first = theBufferList().first();
1388 // We cannot use a for loop as the buffer list is a cycle.
1390 if (!b->isClean()) {
1394 b = theBufferList().next(b);
1395 } while (b != first);
1399 case LFUN_BUFFER_WRITE_AS:
1400 enable = doc_buffer;
1403 case LFUN_BUFFER_CLOSE:
1404 enable = doc_buffer;
1407 case LFUN_BUFFER_CLOSE_ALL:
1408 enable = theBufferList().last() != theBufferList().first();
1411 case LFUN_SPLIT_VIEW:
1412 if (cmd.getArg(0) == "vertical")
1413 enable = doc_buffer && (d.splitter_->count() == 1 ||
1414 d.splitter_->orientation() == Qt::Vertical);
1416 enable = doc_buffer && (d.splitter_->count() == 1 ||
1417 d.splitter_->orientation() == Qt::Horizontal);
1420 case LFUN_CLOSE_TAB_GROUP:
1421 enable = d.currentTabWorkArea();
1424 case LFUN_TOOLBAR_TOGGLE:
1425 if (GuiToolbar * t = toolbar(cmd.getArg(0)))
1426 flag.setOnOff(t->isVisible());
1429 case LFUN_DROP_LAYOUTS_CHOICE:
1433 case LFUN_UI_TOGGLE:
1434 flag.setOnOff(isFullScreen());
1437 case LFUN_DIALOG_DISCONNECT_INSET:
1440 case LFUN_DIALOG_HIDE:
1441 // FIXME: should we check if the dialog is shown?
1444 case LFUN_DIALOG_TOGGLE:
1445 flag.setOnOff(isDialogVisible(cmd.getArg(0)));
1446 // fall through to set "enable"
1447 case LFUN_DIALOG_SHOW: {
1448 string const name = cmd.getArg(0);
1450 enable = name == "aboutlyx"
1451 || name == "file" //FIXME: should be removed.
1453 || name == "texinfo"
1454 || name == "progress"
1455 || name == "compare";
1456 else if (name == "print")
1457 enable = doc_buffer->isExportable("dvi")
1458 && lyxrc.print_command != "none";
1459 else if (name == "character" || name == "symbols") {
1460 if (!buf || buf->isReadonly()
1461 || !currentBufferView()->cursor().inTexted())
1464 // FIXME we should consider passthru
1466 Inset const & in = currentBufferView()->cursor().inset();
1467 enable = !in.getLayout().isPassThru();
1470 else if (name == "latexlog")
1471 enable = FileName(doc_buffer->logName()).isReadableFile();
1472 else if (name == "spellchecker")
1473 enable = theSpellChecker() && !doc_buffer->isReadonly();
1474 else if (name == "vclog")
1475 enable = doc_buffer->lyxvc().inUse();
1479 case LFUN_DIALOG_UPDATE: {
1480 string const name = cmd.getArg(0);
1482 enable = name == "prefs";
1486 case LFUN_COMMAND_EXECUTE:
1488 case LFUN_MENU_OPEN:
1489 // Nothing to check.
1492 case LFUN_COMPLETION_INLINE:
1493 if (!d.current_work_area_
1494 || !d.current_work_area_->completer().inlinePossible(
1495 currentBufferView()->cursor()))
1499 case LFUN_COMPLETION_POPUP:
1500 if (!d.current_work_area_
1501 || !d.current_work_area_->completer().popupPossible(
1502 currentBufferView()->cursor()))
1506 case LFUN_COMPLETION_COMPLETE:
1507 if (!d.current_work_area_
1508 || !d.current_work_area_->completer().inlinePossible(
1509 currentBufferView()->cursor()))
1513 case LFUN_COMPLETION_ACCEPT:
1514 if (!d.current_work_area_
1515 || (!d.current_work_area_->completer().popupVisible()
1516 && !d.current_work_area_->completer().inlineVisible()
1517 && !d.current_work_area_->completer().completionAvailable()))
1521 case LFUN_COMPLETION_CANCEL:
1522 if (!d.current_work_area_
1523 || (!d.current_work_area_->completer().popupVisible()
1524 && !d.current_work_area_->completer().inlineVisible()))
1528 case LFUN_BUFFER_ZOOM_OUT:
1529 enable = doc_buffer && lyxrc.zoom > 10;
1532 case LFUN_BUFFER_ZOOM_IN:
1533 enable = doc_buffer;
1536 case LFUN_BUFFER_NEXT:
1537 case LFUN_BUFFER_PREVIOUS:
1538 // FIXME: should we check is there is an previous or next buffer?
1540 case LFUN_BUFFER_SWITCH:
1541 // toggle on the current buffer, but do not toggle off
1542 // the other ones (is that a good idea?)
1544 && to_utf8(cmd.argument()) == doc_buffer->absFileName())
1545 flag.setOnOff(true);
1548 case LFUN_VC_REGISTER:
1549 enable = doc_buffer && !doc_buffer->lyxvc().inUse();
1551 case LFUN_VC_CHECK_IN:
1552 enable = doc_buffer && doc_buffer->lyxvc().checkInEnabled();
1554 case LFUN_VC_CHECK_OUT:
1555 enable = doc_buffer && doc_buffer->lyxvc().checkOutEnabled();
1557 case LFUN_VC_LOCKING_TOGGLE:
1558 enable = doc_buffer && !doc_buffer->isReadonly()
1559 && doc_buffer->lyxvc().lockingToggleEnabled();
1560 flag.setOnOff(enable && !doc_buffer->lyxvc().locker().empty());
1562 case LFUN_VC_REVERT:
1563 enable = doc_buffer && doc_buffer->lyxvc().inUse();
1565 case LFUN_VC_UNDO_LAST:
1566 enable = doc_buffer && doc_buffer->lyxvc().undoLastEnabled();
1568 case LFUN_VC_REPO_UPDATE:
1569 enable = doc_buffer && doc_buffer->lyxvc().inUse();
1571 case LFUN_VC_COMMAND: {
1572 if (cmd.argument().empty())
1574 if (!doc_buffer && contains(cmd.getArg(0), 'D'))
1579 case LFUN_SERVER_GOTO_FILE_ROW:
1587 flag.setEnabled(false);
1593 static FileName selectTemplateFile()
1595 FileDialog dlg(qt_("Select template file"));
1596 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1597 dlg.setButton1(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
1599 FileDialog::Result result = dlg.open(toqstr(lyxrc.template_path),
1600 QStringList(qt_("LyX Documents (*.lyx)")));
1602 if (result.first == FileDialog::Later)
1604 if (result.second.isEmpty())
1606 return FileName(fromqstr(result.second));
1610 Buffer * GuiView::loadDocument(FileName const & filename, bool tolastfiles)
1614 Buffer * newBuffer = checkAndLoadLyXFile(filename);
1617 message(_("Document not loaded."));
1622 setBuffer(newBuffer);
1624 // scroll to the position when the file was last closed
1625 if (lyxrc.use_lastfilepos) {
1626 LastFilePosSection::FilePos filepos =
1627 theSession().lastFilePos().load(filename);
1628 documentBufferView()->moveToPosition(filepos.pit, filepos.pos, 0, 0);
1632 theSession().lastFiles().add(filename);
1639 void GuiView::openDocument(string const & fname)
1641 string initpath = lyxrc.document_path;
1643 if (documentBufferView()) {
1644 string const trypath = documentBufferView()->buffer().filePath();
1645 // If directory is writeable, use this as default.
1646 if (FileName(trypath).isDirWritable())
1652 if (fname.empty()) {
1653 FileDialog dlg(qt_("Select document to open"), LFUN_FILE_OPEN);
1654 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1655 dlg.setButton2(qt_("Examples|#E#e"),
1656 toqstr(addPath(package().system_support().absFilename(), "examples")));
1658 QStringList filter(qt_("LyX Documents (*.lyx)"));
1659 filter << qt_("LyX-1.3.x Documents (*.lyx13)")
1660 << qt_("LyX-1.4.x Documents (*.lyx14)")
1661 << qt_("LyX-1.5.x Documents (*.lyx15)")
1662 << qt_("LyX-1.6.x Documents (*.lyx16)");
1663 FileDialog::Result result =
1664 dlg.open(toqstr(initpath), filter);
1666 if (result.first == FileDialog::Later)
1669 filename = fromqstr(result.second);
1671 // check selected filename
1672 if (filename.empty()) {
1673 message(_("Canceled."));
1679 // get absolute path of file and add ".lyx" to the filename if
1681 FileName const fullname =
1682 fileSearch(string(), filename, "lyx", support::may_not_exist);
1683 if (!fullname.empty())
1684 filename = fullname.absFilename();
1686 if (!fullname.onlyPath().isDirectory()) {
1687 Alert::warning(_("Invalid filename"),
1688 bformat(_("The directory in the given path\n%1$s\ndoes not exist."),
1689 from_utf8(fullname.absFilename())));
1692 // if the file doesn't exist, let the user create one
1693 if (!fullname.exists()) {
1694 // the user specifically chose this name. Believe him.
1695 Buffer * const b = newFile(filename, string(), true);
1701 docstring const disp_fn = makeDisplayPath(filename);
1702 message(bformat(_("Opening document %1$s..."), disp_fn));
1705 Buffer * buf = loadDocument(fullname);
1707 buf->updateLabels();
1709 buf->errors("Parse");
1710 str2 = bformat(_("Document %1$s opened."), disp_fn);
1711 if (buf->lyxvc().inUse())
1712 str2 += " " + from_utf8(buf->lyxvc().versionString()) +
1713 " " + _("Version control detected.");
1715 str2 = bformat(_("Could not open document %1$s"), disp_fn);
1720 // FIXME: clean that
1721 static bool import(GuiView * lv, FileName const & filename,
1722 string const & format, ErrorList & errorList)
1724 FileName const lyxfile(support::changeExtension(filename.absFilename(), ".lyx"));
1726 string loader_format;
1727 vector<string> loaders = theConverters().loaders();
1728 if (find(loaders.begin(), loaders.end(), format) == loaders.end()) {
1729 for (vector<string>::const_iterator it = loaders.begin();
1730 it != loaders.end(); ++it) {
1731 if (!theConverters().isReachable(format, *it))
1734 string const tofile =
1735 support::changeExtension(filename.absFilename(),
1736 formats.extension(*it));
1737 if (!theConverters().convert(0, filename, FileName(tofile),
1738 filename, format, *it, errorList))
1740 loader_format = *it;
1743 if (loader_format.empty()) {
1744 frontend::Alert::error(_("Couldn't import file"),
1745 bformat(_("No information for importing the format %1$s."),
1746 formats.prettyName(format)));
1750 loader_format = format;
1752 if (loader_format == "lyx") {
1753 Buffer * buf = lv->loadDocument(lyxfile);
1756 buf->updateLabels();
1758 buf->errors("Parse");
1760 Buffer * const b = newFile(lyxfile.absFilename(), string(), true);
1764 bool as_paragraphs = loader_format == "textparagraph";
1765 string filename2 = (loader_format == format) ? filename.absFilename()
1766 : support::changeExtension(filename.absFilename(),
1767 formats.extension(loader_format));
1768 lv->currentBufferView()->insertPlaintextFile(FileName(filename2),
1770 guiApp->setCurrentView(lv);
1771 lyx::dispatch(FuncRequest(LFUN_MARK_OFF));
1778 void GuiView::importDocument(string const & argument)
1781 string filename = split(argument, format, ' ');
1783 LYXERR(Debug::INFO, format << " file: " << filename);
1785 // need user interaction
1786 if (filename.empty()) {
1787 string initpath = lyxrc.document_path;
1788 if (documentBufferView()) {
1789 string const trypath = documentBufferView()->buffer().filePath();
1790 // If directory is writeable, use this as default.
1791 if (FileName(trypath).isDirWritable())
1795 docstring const text = bformat(_("Select %1$s file to import"),
1796 formats.prettyName(format));
1798 FileDialog dlg(toqstr(text), LFUN_BUFFER_IMPORT);
1799 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1800 dlg.setButton2(qt_("Examples|#E#e"),
1801 toqstr(addPath(package().system_support().absFilename(), "examples")));
1803 docstring filter = formats.prettyName(format);
1806 filter += from_utf8(formats.extension(format));
1809 FileDialog::Result result =
1810 dlg.open(toqstr(initpath), fileFilters(toqstr(filter)));
1812 if (result.first == FileDialog::Later)
1815 filename = fromqstr(result.second);
1817 // check selected filename
1818 if (filename.empty())
1819 message(_("Canceled."));
1822 if (filename.empty())
1825 // get absolute path of file
1826 FileName const fullname(support::makeAbsPath(filename));
1828 FileName const lyxfile(support::changeExtension(fullname.absFilename(), ".lyx"));
1830 // Check if the document already is open
1831 Buffer * buf = theBufferList().getBuffer(lyxfile);
1834 if (!closeBuffer()) {
1835 message(_("Canceled."));
1840 docstring const displaypath = makeDisplayPath(lyxfile.absFilename(), 30);
1842 // if the file exists already, and we didn't do
1843 // -i lyx thefile.lyx, warn
1844 if (lyxfile.exists() && fullname != lyxfile) {
1846 docstring text = bformat(_("The document %1$s already exists.\n\n"
1847 "Do you want to overwrite that document?"), displaypath);
1848 int const ret = Alert::prompt(_("Overwrite document?"),
1849 text, 0, 1, _("&Overwrite"), _("&Cancel"));
1852 message(_("Canceled."));
1857 message(bformat(_("Importing %1$s..."), displaypath));
1858 ErrorList errorList;
1859 if (import(this, fullname, format, errorList))
1860 message(_("imported."));
1862 message(_("file not imported!"));
1864 // FIXME (Abdel 12/08/06): Is there a need to display the error list here?
1868 void GuiView::newDocument(string const & filename, bool from_template)
1870 FileName initpath(lyxrc.document_path);
1871 if (documentBufferView()) {
1872 FileName const trypath(documentBufferView()->buffer().filePath());
1873 // If directory is writeable, use this as default.
1874 if (trypath.isDirWritable())
1878 string templatefile;
1879 if (from_template) {
1880 templatefile = selectTemplateFile().absFilename();
1881 if (templatefile.empty())
1886 if (filename.empty())
1887 b = newUnnamedFile(initpath, to_utf8(_("newfile")), templatefile);
1889 b = newFile(filename, templatefile, true);
1894 // If no new document could be created, it is unsure
1895 // whether there is a valid BufferView.
1896 if (currentBufferView())
1897 // Ensure the cursor is correctly positioned on screen.
1898 currentBufferView()->showCursor();
1902 void GuiView::insertLyXFile(docstring const & fname)
1904 BufferView * bv = documentBufferView();
1909 FileName filename(to_utf8(fname));
1911 if (!filename.empty()) {
1912 bv->insertLyXFile(filename);
1916 // Launch a file browser
1918 string initpath = lyxrc.document_path;
1919 string const trypath = bv->buffer().filePath();
1920 // If directory is writeable, use this as default.
1921 if (FileName(trypath).isDirWritable())
1925 FileDialog dlg(qt_("Select LyX document to insert"), LFUN_FILE_INSERT);
1926 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1927 dlg.setButton2(qt_("Examples|#E#e"),
1928 toqstr(addPath(package().system_support().absFilename(),
1931 FileDialog::Result result = dlg.open(toqstr(initpath),
1932 QStringList(qt_("LyX Documents (*.lyx)")));
1934 if (result.first == FileDialog::Later)
1938 filename.set(fromqstr(result.second));
1940 // check selected filename
1941 if (filename.empty()) {
1942 // emit message signal.
1943 message(_("Canceled."));
1947 bv->insertLyXFile(filename);
1951 void GuiView::insertPlaintextFile(docstring const & fname,
1954 BufferView * bv = documentBufferView();
1958 if (!fname.empty() && !FileName::isAbsolute(to_utf8(fname))) {
1959 message(_("Absolute filename expected."));
1964 FileName filename(to_utf8(fname));
1966 if (!filename.empty()) {
1967 bv->insertPlaintextFile(filename, asParagraph);
1971 FileDialog dlg(qt_("Select file to insert"), (asParagraph ?
1972 LFUN_FILE_INSERT_PLAINTEXT_PARA : LFUN_FILE_INSERT_PLAINTEXT));
1974 FileDialog::Result result = dlg.open(toqstr(bv->buffer().filePath()),
1975 QStringList(qt_("All Files (*)")));
1977 if (result.first == FileDialog::Later)
1981 filename.set(fromqstr(result.second));
1983 // check selected filename
1984 if (filename.empty()) {
1985 // emit message signal.
1986 message(_("Canceled."));
1990 bv->insertPlaintextFile(filename, asParagraph);
1994 bool GuiView::renameBuffer(Buffer & b, docstring const & newname)
1996 FileName fname = b.fileName();
1997 FileName const oldname = fname;
1999 if (!newname.empty()) {
2001 fname = support::makeAbsPath(to_utf8(newname), oldname.onlyPath().absFilename());
2003 // Switch to this Buffer.
2006 // No argument? Ask user through dialog.
2008 FileDialog dlg(qt_("Choose a filename to save document as"),
2009 LFUN_BUFFER_WRITE_AS);
2010 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2011 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
2013 if (!isLyXFilename(fname.absFilename()))
2014 fname.changeExtension(".lyx");
2016 FileDialog::Result result =
2017 dlg.save(toqstr(fname.onlyPath().absFilename()),
2018 QStringList(qt_("LyX Documents (*.lyx)")),
2019 toqstr(fname.onlyFileName()));
2021 if (result.first == FileDialog::Later)
2024 fname.set(fromqstr(result.second));
2029 if (!isLyXFilename(fname.absFilename()))
2030 fname.changeExtension(".lyx");
2033 if (FileName(fname).exists()) {
2034 docstring const file = makeDisplayPath(fname.absFilename(), 30);
2035 docstring text = bformat(_("The document %1$s already "
2036 "exists.\n\nDo you want to "
2037 "overwrite that document?"),
2039 int const ret = Alert::prompt(_("Overwrite document?"),
2040 text, 0, 2, _("&Overwrite"), _("&Rename"), _("&Cancel"));
2043 case 1: return renameBuffer(b, docstring());
2044 case 2: return false;
2048 FileName oldauto = b.getAutosaveFilename();
2050 // Ok, change the name of the buffer
2051 b.setFileName(fname.absFilename());
2053 bool unnamed = b.isUnnamed();
2054 b.setUnnamed(false);
2055 b.saveCheckSum(fname);
2057 // bring the autosave file with us, just in case.
2058 b.moveAutosaveFile(oldauto);
2060 if (!saveBuffer(b)) {
2061 oldauto = b.getAutosaveFilename();
2062 b.setFileName(oldname.absFilename());
2063 b.setUnnamed(unnamed);
2064 b.saveCheckSum(oldname);
2065 b.moveAutosaveFile(oldauto);
2073 bool GuiView::saveBuffer(Buffer & b)
2075 if (workArea(b) && workArea(b)->inDialogMode())
2079 return renameBuffer(b, docstring());
2082 theSession().lastFiles().add(b.fileName());
2086 // Switch to this Buffer.
2089 // FIXME: we don't tell the user *WHY* the save failed !!
2090 docstring const file = makeDisplayPath(b.absFileName(), 30);
2091 docstring text = bformat(_("The document %1$s could not be saved.\n\n"
2092 "Do you want to rename the document and "
2093 "try again?"), file);
2094 int const ret = Alert::prompt(_("Rename and save?"),
2095 text, 0, 2, _("&Rename"), _("&Retry"), _("&Cancel"));
2098 if (!renameBuffer(b, docstring()))
2107 return saveBuffer(b);
2111 bool GuiView::hideWorkArea(GuiWorkArea * wa)
2113 return closeWorkArea(wa, false);
2117 bool GuiView::closeWorkArea(GuiWorkArea * wa)
2119 Buffer & buf = wa->bufferView().buffer();
2120 return closeWorkArea(wa, !buf.parent());
2124 bool GuiView::closeBuffer()
2126 GuiWorkArea * wa = currentMainWorkArea();
2127 Buffer & buf = wa->bufferView().buffer();
2128 return wa && closeWorkArea(wa, !buf.parent());
2132 void GuiView::writeSession() const {
2133 GuiWorkArea const * active_wa = currentMainWorkArea();
2134 for (int i = 0; i < d.splitter_->count(); ++i) {
2135 TabWorkArea * twa = d.tabWorkArea(i);
2136 for (int j = 0; j < twa->count(); ++j) {
2137 GuiWorkArea * wa = static_cast<GuiWorkArea *>(twa->widget(j));
2138 Buffer & buf = wa->bufferView().buffer();
2139 theSession().lastOpened().add(buf.fileName(), wa == active_wa);
2145 bool GuiView::closeBufferAll()
2147 // Close the workareas in all other views
2148 QList<int> const ids = guiApp->viewIds();
2149 for (int i = 0; i != ids.size(); ++i) {
2150 if (id_ != ids[i] && !guiApp->view(ids[i]).closeWorkAreaAll())
2154 // Close our own workareas
2155 if (!closeWorkAreaAll())
2158 // Now close the hidden buffers. We prevent hidden buffers from being
2159 // dirty, so we can just close them.
2160 theBufferList().closeAll();
2165 bool GuiView::closeWorkAreaAll()
2167 setCurrentWorkArea(currentMainWorkArea());
2169 // We might be in a situation that there is still a tabWorkArea, but
2170 // there are no tabs anymore. This can happen when we get here after a
2171 // TabWorkArea::lastWorkAreaRemoved() signal. Therefore we count how
2172 // many TabWorkArea's have no documents anymore.
2175 // We have to call count() each time, because it can happen that
2176 // more than one splitter will disappear in one iteration (bug 5998).
2177 for (; d.splitter_->count() > empty_twa; ) {
2178 TabWorkArea * twa = d.tabWorkArea(empty_twa);
2180 if (twa->count() == 0)
2183 setCurrentWorkArea(twa->currentWorkArea());
2184 if (!closeTabWorkArea(twa))
2192 bool GuiView::closeWorkArea(GuiWorkArea * wa, bool close_buffer)
2197 Buffer & buf = wa->bufferView().buffer();
2200 return closeBuffer(buf);
2202 if (!inMultiTabs(wa))
2203 if (!saveBufferIfNeeded(buf, true))
2211 bool GuiView::closeBuffer(Buffer & buf)
2213 // If we are in a close_event all children will be closed in some time,
2214 // so no need to do it here. This will ensure that the children end up
2215 // in the session file in the correct order. If we close the master
2216 // buffer, we can close or release the child buffers here too.
2218 vector<Buffer *> clist = buf.getChildren(false);
2219 for (vector<Buffer *>::const_iterator it = clist.begin();
2220 it != clist.end(); ++it) {
2221 // If a child is dirty, do not close
2222 // without user intervention
2223 //FIXME: should we look in other tabworkareas?
2224 Buffer * child_buf = *it;
2225 GuiWorkArea * child_wa = workArea(*child_buf);
2227 if (!closeWorkArea(child_wa, true))
2230 theBufferList().releaseChild(&buf, child_buf);
2233 // goto bookmark to update bookmark pit.
2234 //FIXME: we should update only the bookmarks related to this buffer!
2235 LYXERR(Debug::DEBUG, "GuiView::closeBuffer()");
2236 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
2237 theLyXFunc().gotoBookmark(i+1, false, false);
2239 if (saveBufferIfNeeded(buf, false)) {
2240 theBufferList().release(&buf);
2247 bool GuiView::closeTabWorkArea(TabWorkArea * twa)
2249 while (twa == d.currentTabWorkArea()) {
2250 twa->setCurrentIndex(twa->count()-1);
2252 GuiWorkArea * wa = twa->currentWorkArea();
2253 Buffer & b = wa->bufferView().buffer();
2255 // We only want to close the buffer if the same buffer is not visible
2256 // in another view, and if this is not a child and if we are closing
2257 // a view (not a tabgroup).
2258 bool const close_buffer =
2259 !inMultiViews(wa) && !b.parent() && closing_;
2261 if (!closeWorkArea(wa, close_buffer))
2268 bool GuiView::saveBufferIfNeeded(Buffer & buf, bool hiding)
2270 if (buf.isClean() || buf.paragraphs().empty())
2273 // Switch to this Buffer.
2278 if (buf.isUnnamed())
2279 file = from_utf8(buf.fileName().onlyFileName());
2281 file = buf.fileName().displayName(30);
2283 // Bring this window to top before asking questions.
2288 if (hiding && buf.isUnnamed()) {
2289 docstring const text = bformat(_("The document %1$s has not been "
2290 "saved yet.\n\nDo you want to save "
2291 "the document?"), file);
2292 ret = Alert::prompt(_("Save new document?"),
2293 text, 0, 1, _("&Save"), _("&Cancel"));
2297 docstring const text = bformat(_("The document %1$s has unsaved changes."
2298 "\n\nDo you want to save the document or discard the changes?"), file);
2299 ret = Alert::prompt(_("Save changed document?"),
2300 text, 0, 2, _("&Save"), _("&Discard"), _("&Cancel"));
2305 if (!saveBuffer(buf))
2309 // if we crash after this we could
2310 // have no autosave file but I guess
2311 // this is really improbable (Jug)
2312 buf.removeAutosaveFile();
2314 // revert all changes
2315 buf.loadLyXFile(buf.fileName());
2325 bool GuiView::inMultiTabs(GuiWorkArea * wa)
2327 Buffer & buf = wa->bufferView().buffer();
2329 for (int i = 0; i != d.splitter_->count(); ++i) {
2330 GuiWorkArea * wa_ = d.tabWorkArea(i)->workArea(buf);
2331 if (wa_ && wa_ != wa)
2334 return inMultiViews(wa);
2338 bool GuiView::inMultiViews(GuiWorkArea * wa)
2340 QList<int> const ids = guiApp->viewIds();
2341 Buffer & buf = wa->bufferView().buffer();
2344 for (int i = 0; i != ids.size() && found_twa <= 1; ++i) {
2348 if (guiApp->view(ids[i]).workArea(buf))
2355 void GuiView::gotoNextOrPreviousBuffer(NextOrPrevious np)
2357 Buffer * const curbuf = documentBufferView()
2358 ? &documentBufferView()->buffer() : 0;
2359 Buffer * nextbuf = curbuf;
2361 if (np == NEXTBUFFER)
2362 nextbuf = theBufferList().next(nextbuf);
2364 nextbuf = theBufferList().previous(nextbuf);
2365 if (nextbuf == curbuf)
2371 if (workArea(*nextbuf))
2378 /// make sure the document is saved
2379 static bool ensureBufferClean(Buffer * buffer)
2381 LASSERT(buffer, return false);
2382 if (buffer->isClean() && !buffer->isUnnamed())
2385 docstring const file = buffer->fileName().displayName(30);
2388 if (!buffer->isUnnamed()) {
2389 text = bformat(_("The document %1$s has unsaved "
2390 "changes.\n\nDo you want to save "
2391 "the document?"), file);
2392 title = _("Save changed document?");
2395 text = bformat(_("The document %1$s has not been "
2396 "saved yet.\n\nDo you want to save "
2397 "the document?"), file);
2398 title = _("Save new document?");
2400 int const ret = Alert::prompt(title, text, 0, 1, _("&Save"), _("&Cancel"));
2403 dispatch(FuncRequest(LFUN_BUFFER_WRITE));
2405 return buffer->isClean() && !buffer->isUnnamed();
2409 void GuiView::reloadBuffer()
2411 Buffer * buf = &documentBufferView()->buffer();
2416 void GuiView::reloadBuffer(Buffer * buf)
2418 FileName filename = buf->fileName();
2419 // e.g., read-only status could have changed due to version control
2421 Buffer const * parent = buf->parent();
2422 bool const is_child = parent != buf;
2423 // The user has already confirmed that the changes, if any, should
2424 // be discarded. So we just release the Buffer and don't call closeBuffer();
2425 theBufferList().release(buf);
2426 buf = loadDocument(filename);
2427 docstring const disp_fn = makeDisplayPath(filename.absFilename());
2430 // re-allocate master if necessary
2431 if (is_child && theBufferList().isLoaded(parent)
2432 && buf->parent() != parent)
2433 buf->setParent(parent);
2434 buf->updateLabels();
2436 buf->errors("Parse");
2437 str = bformat(_("Document %1$s reloaded."), disp_fn);
2439 str = bformat(_("Could not reload document %1$s"), disp_fn);
2445 void GuiView::checkExternallyModifiedBuffers()
2447 BufferList::iterator bit = theBufferList().begin();
2448 BufferList::iterator const bend = theBufferList().end();
2449 for (; bit != bend; ++bit) {
2450 if ((*bit)->fileName().exists()
2451 && (*bit)->isExternallyModified(Buffer::checksum_method)) {
2452 docstring text = bformat(_("Document \n%1$s\n has been externally modified."
2453 " Reload now? Any local changes will be lost."),
2454 from_utf8((*bit)->absFileName()));
2455 int const ret = Alert::prompt(_("Reload externally changed document?"),
2456 text, 0, 1, _("&Reload"), _("&Cancel"));
2464 void GuiView::dispatchVC(FuncRequest const & cmd)
2466 // message for statusbar
2468 Buffer * buffer = documentBufferView()
2469 ? &(documentBufferView()->buffer()) : 0;
2471 switch (cmd.action) {
2472 case LFUN_VC_REGISTER:
2473 if (!buffer || !ensureBufferClean(buffer))
2475 if (!buffer->lyxvc().inUse()) {
2476 if (buffer->lyxvc().registrer())
2481 case LFUN_VC_CHECK_IN:
2482 if (!buffer || !ensureBufferClean(buffer))
2484 if (buffer->lyxvc().inUse() && !buffer->isReadonly()) {
2485 msg = buffer->lyxvc().checkIn();
2490 case LFUN_VC_CHECK_OUT:
2491 if (!buffer || !ensureBufferClean(buffer))
2493 if (buffer->lyxvc().inUse()) {
2494 msg = buffer->lyxvc().checkOut();
2499 case LFUN_VC_LOCKING_TOGGLE:
2500 LASSERT(buffer, return);
2501 if (!ensureBufferClean(buffer) || buffer->isReadonly())
2503 if (buffer->lyxvc().inUse()) {
2504 string res = buffer->lyxvc().lockingToggle();
2506 frontend::Alert::error(_("Revision control error."),
2507 _("Error when setting the locking property."));
2515 case LFUN_VC_REVERT:
2516 LASSERT(buffer, return);
2517 buffer->lyxvc().revert();
2521 case LFUN_VC_UNDO_LAST:
2522 LASSERT(buffer, return);
2523 buffer->lyxvc().undoLast();
2527 case LFUN_VC_REPO_UPDATE:
2528 LASSERT(buffer, return);
2529 if (ensureBufferClean(buffer)) {
2530 msg = buffer->lyxvc().repoUpdate();
2531 checkExternallyModifiedBuffers();
2535 case LFUN_VC_COMMAND: {
2536 string flag = cmd.getArg(0);
2537 if (buffer && contains(flag, 'R') && !ensureBufferClean(buffer))
2540 if (contains(flag, 'M')) {
2541 if (!Alert::askForText(message, _("LyX VC: Log Message")))
2544 string path = cmd.getArg(1);
2545 if (contains(path, "$$p") && buffer)
2546 path = subst(path, "$$p", buffer->filePath());
2547 LYXERR(Debug::LYXVC, "Directory: " << path);
2549 if (!pp.isReadableDirectory()) {
2550 lyxerr << _("Directory is not accessible.") << endl;
2553 support::PathChanger p(pp);
2555 string command = cmd.getArg(2);
2556 if (command.empty())
2559 command = subst(command, "$$i", buffer->absFileName());
2560 command = subst(command, "$$p", buffer->filePath());
2562 command = subst(command, "$$m", to_utf8(message));
2563 LYXERR(Debug::LYXVC, "Command: " << command);
2565 one.startscript(Systemcall::Wait, command);
2569 if (contains(flag, 'I'))
2570 buffer->markDirty();
2571 if (contains(flag, 'R'))
2581 message(from_utf8(msg));
2585 void GuiView::openChildDocument(string const & fname)
2587 LASSERT(documentBufferView(), return);
2588 Buffer & buffer = documentBufferView()->buffer();
2589 FileName const filename = support::makeAbsPath(fname, buffer.filePath());
2590 documentBufferView()->saveBookmark(false);
2592 bool parsed = false;
2593 if (theBufferList().exists(filename)) {
2594 child = theBufferList().getBuffer(filename);
2596 message(bformat(_("Opening child document %1$s..."),
2597 makeDisplayPath(filename.absFilename())));
2598 child = loadDocument(filename, false);
2604 // Set the parent name of the child document.
2605 // This makes insertion of citations and references in the child work,
2606 // when the target is in the parent or another child document.
2607 child->setParent(&buffer);
2608 child->masterBuffer()->updateLabels();
2611 child->errors("Parse");
2615 bool GuiView::goToFileRow(string const & argument)
2619 size_t i = argument.find_last_of(' ');
2620 if (i != string::npos) {
2621 file_name = os::internal_path(trim(argument.substr(0, i)));
2622 istringstream is(argument.substr(i + 1));
2627 if (i == string::npos) {
2628 LYXERR0("Wrong argument: " << argument);
2632 string const abstmp = package().temp_dir().absFilename();
2633 string const realtmp = package().temp_dir().realPath();
2634 // We have to use os::path_prefix_is() here, instead of
2635 // simply prefixIs(), because the file name comes from
2636 // an external application and may need case adjustment.
2637 if (os::path_prefix_is(file_name, abstmp, os::CASE_ADJUSTED)
2638 || os::path_prefix_is(file_name, realtmp, os::CASE_ADJUSTED)) {
2639 // Needed by inverse dvi search. If it is a file
2640 // in tmpdir, call the apropriated function.
2641 // If tmpdir is a symlink, we may have the real
2642 // path passed back, so we correct for that.
2643 if (!prefixIs(file_name, abstmp))
2644 file_name = subst(file_name, realtmp, abstmp);
2645 buf = theBufferList().getBufferFromTmp(file_name);
2647 // Must replace extension of the file to be .lyx
2648 // and get full path
2649 FileName const s = fileSearch(string(),
2650 support::changeExtension(file_name, ".lyx"), "lyx");
2651 // Either change buffer or load the file
2652 if (theBufferList().exists(s))
2653 buf = theBufferList().getBuffer(s);
2654 else if (s.exists()) {
2655 buf = loadDocument(s);
2656 buf->updateLabels();
2657 buf->errors("Parse");
2660 _("File does not exist: %1$s"),
2661 makeDisplayPath(file_name)));
2666 documentBufferView()->setCursorFromRow(row);
2671 static docstring exportAndDestroy(Buffer * buffer, string const & format)
2673 bool const success = buffer->doExport(format, true);
2676 ? bformat(_("Successful export to format: %1$s"), from_utf8(format))
2677 : bformat(_("Error exporting to format: %1$s"), from_utf8(format));
2681 static docstring previewAndDestroy(Buffer * buffer, string const & format)
2683 bool const success = buffer->preview(format);
2686 ? bformat(_("Successful preview of format: %1$s"), from_utf8(format))
2687 : bformat(_("Error previewing format: %1$s"), from_utf8(format));
2691 bool GuiView::dispatch(FuncRequest const & cmd)
2693 BufferView * bv = currentBufferView();
2694 // By default we won't need any update.
2696 bv->cursor().updateFlags(Update::None);
2698 Buffer * doc_buffer = documentBufferView()
2699 ? &(documentBufferView()->buffer()) : 0;
2701 bool dispatched = true;
2703 if (cmd.origin == FuncRequest::TOC) {
2704 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
2705 toc->doDispatch(bv->cursor(), cmd);
2709 string const argument = to_utf8(cmd.argument());
2711 switch(cmd.action) {
2712 case LFUN_BUFFER_CHILD_OPEN:
2713 openChildDocument(to_utf8(cmd.argument()));
2716 case LFUN_BUFFER_IMPORT:
2717 importDocument(to_utf8(cmd.argument()));
2720 case LFUN_BUFFER_EXPORT: {
2723 if (cmd.argument() == "custom") {
2724 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "sendto"));
2727 if (doc_buffer->doExport(argument, false)) {
2728 message(bformat(_("Error exporting to format: %1$s."),
2734 case LFUN_BUFFER_UPDATE: {
2737 string format = argument;
2738 if (argument.empty())
2739 format = doc_buffer->getDefaultOutputFormat();
2740 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
2741 d.progress_->clearMessages();
2742 message(_("Exporting ..."));
2743 QFuture<docstring> f = QtConcurrent::run(exportAndDestroy,
2744 doc_buffer->clone(), format);
2745 d.setPreviewFuture(f);
2747 doc_buffer->doExport(format, true);
2751 case LFUN_BUFFER_VIEW: {
2754 string format = argument;
2755 if (argument.empty())
2756 format = doc_buffer->getDefaultOutputFormat();
2757 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
2758 d.progress_->clearMessages();
2759 message(_("Previewing ..."));
2760 QFuture<docstring> f = QtConcurrent::run(previewAndDestroy,
2761 doc_buffer->clone(), format);
2762 d.setPreviewFuture(f);
2764 doc_buffer->preview(format);
2768 case LFUN_MASTER_BUFFER_UPDATE: {
2771 string format = argument;
2772 Buffer const * master = doc_buffer->masterBuffer();
2773 if (argument.empty())
2774 format = master->getDefaultOutputFormat();
2775 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
2776 QFuture<docstring> f = QtConcurrent::run(exportAndDestroy,
2777 master->clone(), format);
2778 d.setPreviewFuture(f);
2780 master->doExport(format, true);
2784 case LFUN_MASTER_BUFFER_VIEW: {
2785 string format = argument;
2786 Buffer const * master = doc_buffer->masterBuffer();
2787 if (argument.empty())
2788 format = master->getDefaultOutputFormat();
2789 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
2790 QFuture<docstring> f = QtConcurrent::run(previewAndDestroy,
2791 master->clone(), format);
2792 d.setPreviewFuture(f);
2794 master->preview(format);
2798 case LFUN_BUFFER_SWITCH:
2799 if (FileName::isAbsolute(to_utf8(cmd.argument()))) {
2801 theBufferList().getBuffer(FileName(to_utf8(cmd.argument())));
2805 message(_("Document not loaded"));
2809 case LFUN_BUFFER_NEXT:
2810 gotoNextOrPreviousBuffer(NEXTBUFFER);
2813 case LFUN_BUFFER_PREVIOUS:
2814 gotoNextOrPreviousBuffer(PREVBUFFER);
2817 case LFUN_COMMAND_EXECUTE: {
2818 bool const show_it = cmd.argument() != "off";
2819 // FIXME: this is a hack, "minibuffer" should not be
2821 if (GuiToolbar * t = toolbar("minibuffer")) {
2822 t->setVisible(show_it);
2823 if (show_it && t->commandBuffer())
2824 t->commandBuffer()->setFocus();
2828 case LFUN_DROP_LAYOUTS_CHOICE:
2829 d.layout_->showPopup();
2832 case LFUN_MENU_OPEN:
2833 if (QMenu * menu = guiApp->menus().menu(toqstr(cmd.argument()), *this))
2834 menu->exec(QCursor::pos());
2837 case LFUN_FILE_INSERT:
2838 insertLyXFile(cmd.argument());
2840 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
2841 insertPlaintextFile(cmd.argument(), true);
2844 case LFUN_FILE_INSERT_PLAINTEXT:
2845 insertPlaintextFile(cmd.argument(), false);
2848 case LFUN_BUFFER_RELOAD: {
2849 LASSERT(doc_buffer, break);
2850 docstring const file = makeDisplayPath(doc_buffer->absFileName(), 20);
2851 docstring text = bformat(_("Any changes will be lost. Are you sure "
2852 "you want to revert to the saved version of the document %1$s?"), file);
2853 int const ret = Alert::prompt(_("Revert to saved document?"),
2854 text, 1, 1, _("&Revert"), _("&Cancel"));
2857 doc_buffer->markClean();
2863 case LFUN_BUFFER_WRITE:
2864 LASSERT(doc_buffer, break);
2865 saveBuffer(*doc_buffer);
2868 case LFUN_BUFFER_WRITE_AS:
2869 LASSERT(doc_buffer, break);
2870 renameBuffer(*doc_buffer, cmd.argument());
2873 case LFUN_BUFFER_WRITE_ALL: {
2874 Buffer * first = theBufferList().first();
2877 message(_("Saving all documents..."));
2878 // We cannot use a for loop as the buffer list cycles.
2881 if (!b->isClean()) {
2883 LYXERR(Debug::ACTION, "Saved " << b->absFileName());
2885 b = theBufferList().next(b);
2886 } while (b != first);
2887 message(_("All documents saved."));
2891 case LFUN_BUFFER_CLOSE:
2895 case LFUN_BUFFER_CLOSE_ALL:
2899 case LFUN_TOOLBAR_TOGGLE: {
2900 string const name = cmd.getArg(0);
2901 if (GuiToolbar * t = toolbar(name))
2906 case LFUN_DIALOG_UPDATE: {
2907 string const name = to_utf8(cmd.argument());
2908 if (currentBufferView()) {
2909 Inset * inset = currentBufferView()->editedInset(name);
2910 // Can only update a dialog connected to an existing inset
2913 // FIXME: get rid of this indirection; GuiView ask the inset
2914 // if he is kind enough to update itself...
2915 FuncRequest fr(LFUN_INSET_DIALOG_UPDATE, cmd.argument());
2916 inset->dispatch(currentBufferView()->cursor(), fr);
2917 } else if (name == "paragraph") {
2918 lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
2919 } else if (name == "prefs" || name == "document") {
2920 updateDialog(name, string());
2925 case LFUN_DIALOG_TOGGLE: {
2926 if (isDialogVisible(cmd.getArg(0)))
2927 dispatch(FuncRequest(LFUN_DIALOG_HIDE, cmd.argument()));
2929 dispatch(FuncRequest(LFUN_DIALOG_SHOW, cmd.argument()));
2933 case LFUN_DIALOG_DISCONNECT_INSET:
2934 disconnectDialog(to_utf8(cmd.argument()));
2937 case LFUN_DIALOG_HIDE: {
2938 guiApp->hideDialogs(to_utf8(cmd.argument()), 0);
2942 case LFUN_DIALOG_SHOW: {
2943 string const name = cmd.getArg(0);
2944 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
2946 if (name == "character") {
2947 data = freefont2string();
2949 showDialog("character", data);
2950 } else if (name == "latexlog") {
2951 Buffer::LogType type;
2952 string const logfile = doc_buffer->logName(&type);
2954 case Buffer::latexlog:
2957 case Buffer::buildlog:
2961 data += Lexer::quoteString(logfile);
2962 showDialog("log", data);
2963 } else if (name == "vclog") {
2964 string const data = "vc " +
2965 Lexer::quoteString(doc_buffer->lyxvc().getLogFile());
2966 showDialog("log", data);
2967 } else if (name == "symbols") {
2968 data = bv->cursor().getEncoding()->name();
2970 showDialog("symbols", data);
2972 } else if (name == "prefs" && isFullScreen()) {
2973 FuncRequest fr(LFUN_INSET_INSERT, "fullscreen");
2975 showDialog("prefs", data);
2977 showDialog(name, data);
2982 message(cmd.argument());
2985 case LFUN_UI_TOGGLE:
2987 // Make sure the keyboard focus stays in the work area.
2991 case LFUN_SPLIT_VIEW: {
2992 LASSERT(doc_buffer, break);
2993 string const orientation = cmd.getArg(0);
2994 d.splitter_->setOrientation(orientation == "vertical"
2995 ? Qt::Vertical : Qt::Horizontal);
2996 TabWorkArea * twa = addTabWorkArea();
2997 GuiWorkArea * wa = twa->addWorkArea(*doc_buffer, *this);
2998 setCurrentWorkArea(wa);
3001 case LFUN_CLOSE_TAB_GROUP:
3002 if (TabWorkArea * twa = d.currentTabWorkArea()) {
3003 closeTabWorkArea(twa);
3004 d.current_work_area_ = 0;
3005 twa = d.currentTabWorkArea();
3006 // Switch to the next GuiWorkArea in the found TabWorkArea.
3008 // Make sure the work area is up to date.
3009 setCurrentWorkArea(twa->currentWorkArea());
3011 setCurrentWorkArea(0);
3016 case LFUN_COMPLETION_INLINE:
3017 if (d.current_work_area_)
3018 d.current_work_area_->completer().showInline();
3021 case LFUN_COMPLETION_POPUP:
3022 if (d.current_work_area_)
3023 d.current_work_area_->completer().showPopup();
3027 case LFUN_COMPLETION_COMPLETE:
3028 if (d.current_work_area_)
3029 d.current_work_area_->completer().tab();
3032 case LFUN_COMPLETION_CANCEL:
3033 if (d.current_work_area_) {
3034 if (d.current_work_area_->completer().popupVisible())
3035 d.current_work_area_->completer().hidePopup();
3037 d.current_work_area_->completer().hideInline();
3041 case LFUN_COMPLETION_ACCEPT:
3042 if (d.current_work_area_)
3043 d.current_work_area_->completer().activate();
3046 case LFUN_BUFFER_ZOOM_IN:
3047 case LFUN_BUFFER_ZOOM_OUT:
3048 if (cmd.argument().empty()) {
3049 if (cmd.action == LFUN_BUFFER_ZOOM_IN)
3054 lyxrc.zoom += convert<int>(cmd.argument());
3056 if (lyxrc.zoom < 10)
3059 // The global QPixmapCache is used in GuiPainter to cache text
3060 // painting so we must reset it.
3061 QPixmapCache::clear();
3062 guiApp->fontLoader().update();
3063 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
3066 case LFUN_VC_REGISTER:
3067 case LFUN_VC_CHECK_IN:
3068 case LFUN_VC_CHECK_OUT:
3069 case LFUN_VC_REPO_UPDATE:
3070 case LFUN_VC_LOCKING_TOGGLE:
3071 case LFUN_VC_REVERT:
3072 case LFUN_VC_UNDO_LAST:
3073 case LFUN_VC_COMMAND:
3077 case LFUN_SERVER_GOTO_FILE_ROW:
3078 goToFileRow(to_utf8(cmd.argument()));
3086 // Part of automatic menu appearance feature.
3087 if (isFullScreen()) {
3088 if (menuBar()->isVisible() && lyxrc.full_screen_menubar)
3090 if (statusBar()->isVisible())
3091 statusBar()->hide();
3098 void GuiView::lfunUiToggle(FuncRequest const & cmd)
3100 string const arg = cmd.getArg(0);
3101 if (arg == "scrollbar") {
3102 // hide() is of no help
3103 if (d.current_work_area_->verticalScrollBarPolicy() ==
3104 Qt::ScrollBarAlwaysOff)
3106 d.current_work_area_->setVerticalScrollBarPolicy(
3107 Qt::ScrollBarAsNeeded);
3109 d.current_work_area_->setVerticalScrollBarPolicy(
3110 Qt::ScrollBarAlwaysOff);
3113 if (arg == "statusbar") {
3114 statusBar()->setVisible(!statusBar()->isVisible());
3117 if (arg == "menubar") {
3118 menuBar()->setVisible(!menuBar()->isVisible());
3121 #if QT_VERSION >= 0x040300
3122 if (arg == "frame") {
3124 getContentsMargins(&l, &t, &r, &b);
3125 //are the frames in default state?
3126 d.current_work_area_->setFrameStyle(QFrame::NoFrame);
3128 setContentsMargins(-2, -2, -2, -2);
3130 setContentsMargins(0, 0, 0, 0);
3135 if (arg == "fullscreen") {
3140 message(bformat("LFUN_UI_TOGGLE " + _("%1$s unknown command!"), from_utf8(arg)));
3144 void GuiView::toggleFullScreen()
3146 if (isFullScreen()) {
3147 for (int i = 0; i != d.splitter_->count(); ++i)
3148 d.tabWorkArea(i)->setFullScreen(false);
3149 #if QT_VERSION >= 0x040300
3150 setContentsMargins(0, 0, 0, 0);
3152 setWindowState(windowState() ^ Qt::WindowFullScreen);
3155 statusBar()->show();
3158 hideDialogs("prefs", 0);
3159 for (int i = 0; i != d.splitter_->count(); ++i)
3160 d.tabWorkArea(i)->setFullScreen(true);
3161 #if QT_VERSION >= 0x040300
3162 setContentsMargins(-2, -2, -2, -2);
3165 setWindowState(windowState() ^ Qt::WindowFullScreen);
3166 statusBar()->hide();
3167 if (lyxrc.full_screen_menubar)
3169 if (lyxrc.full_screen_toolbars) {
3170 ToolbarMap::iterator end = d.toolbars_.end();
3171 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
3176 // give dialogs like the TOC a chance to adapt
3181 Buffer const * GuiView::updateInset(Inset const * inset)
3183 if (!d.current_work_area_)
3187 d.current_work_area_->scheduleRedraw();
3189 return &d.current_work_area_->bufferView().buffer();
3193 void GuiView::restartCursor()
3195 /* When we move around, or type, it's nice to be able to see
3196 * the cursor immediately after the keypress.
3198 if (d.current_work_area_)
3199 d.current_work_area_->startBlinkingCursor();
3201 // Take this occasion to update the other GUI elements.
3207 void GuiView::updateCompletion(Cursor & cur, bool start, bool keep)
3209 if (d.current_work_area_)
3210 d.current_work_area_->completer().updateVisibility(cur, start, keep);
3215 // This list should be kept in sync with the list of insets in
3216 // src/insets/Inset.cpp. I.e., if a dialog goes with an inset, the
3217 // dialog should have the same name as the inset.
3218 // Changes should be also recorded in LFUN_DIALOG_SHOW doxygen
3219 // docs in LyXAction.cpp.
3221 char const * const dialognames[] = {
3222 "aboutlyx", "bibitem", "bibtex", "box", "branch", "changes", "character",
3223 "citation", "compare", "document", "errorlist", "ert", "external", "file",
3224 "findreplace", "findreplaceadv", "float", "graphics", "href", "include",
3225 "index", "index_print", "info", "listings", "label", "log", "mathdelimiter",
3226 "mathmatrix", "mathspace", "nomenclature", "nomencl_print", "note",
3227 "paragraph", "phantom", "prefs", "print", "ref", "sendto", "space",
3228 "spellchecker", "symbols", "tabular", "tabularcreate", "thesaurus", "texinfo",
3229 "toc", "view-source", "vspace", "wrap", "progress"};
3231 char const * const * const end_dialognames =
3232 dialognames + (sizeof(dialognames) / sizeof(char *));
3236 cmpCStr(char const * name) : name_(name) {}
3237 bool operator()(char const * other) {
3238 return strcmp(other, name_) == 0;
3245 bool isValidName(string const & name)
3247 return find_if(dialognames, end_dialognames,
3248 cmpCStr(name.c_str())) != end_dialognames;
3254 void GuiView::resetDialogs()
3256 // Make sure that no LFUN uses any LyXView.
3257 guiApp->setCurrentView(0);
3260 constructToolbars();
3261 guiApp->menus().fillMenuBar(menuBar(), this, false);
3262 d.layout_->updateContents(true);
3263 // Now update controls with current buffer.
3264 guiApp->setCurrentView(this);
3270 Dialog * GuiView::findOrBuild(string const & name, bool hide_it)
3272 if (!isValidName(name))
3275 map<string, DialogPtr>::iterator it = d.dialogs_.find(name);
3277 if (it != d.dialogs_.end()) {
3279 it->second->hideView();
3280 return it->second.get();
3283 Dialog * dialog = build(name);
3284 d.dialogs_[name].reset(dialog);
3285 if (lyxrc.allow_geometry_session)
3286 dialog->restoreSession();
3293 void GuiView::showDialog(string const & name, string const & data,
3296 triggerShowDialog(toqstr(name), toqstr(data), inset);
3300 void GuiView::doShowDialog(QString const & qname, QString const & qdata,
3306 const string name = fromqstr(qname);
3307 const string data = fromqstr(qdata);
3311 Dialog * dialog = findOrBuild(name, false);
3313 dialog->showData(data);
3314 if (inset && currentBufferView())
3315 currentBufferView()->editInset(name, inset);
3318 catch (ExceptionMessage const & ex) {
3326 bool GuiView::isDialogVisible(string const & name) const
3328 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3329 if (it == d.dialogs_.end())
3331 return it->second.get()->isVisibleView() && !it->second.get()->isClosing();
3335 void GuiView::hideDialog(string const & name, Inset * inset)
3337 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3338 if (it == d.dialogs_.end())
3341 if (inset && currentBufferView()
3342 && inset != currentBufferView()->editedInset(name))
3345 Dialog * const dialog = it->second.get();
3346 if (dialog->isVisibleView())
3348 if (currentBufferView())
3349 currentBufferView()->editInset(name, 0);
3353 void GuiView::disconnectDialog(string const & name)
3355 if (!isValidName(name))
3357 if (currentBufferView())
3358 currentBufferView()->editInset(name, 0);
3362 void GuiView::hideAll() const
3364 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
3365 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3367 for(; it != end; ++it)
3368 it->second->hideView();
3372 void GuiView::updateDialogs()
3374 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
3375 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3377 for(; it != end; ++it) {
3378 Dialog * dialog = it->second.get();
3379 if (dialog && dialog->isVisibleView())
3380 dialog->checkStatus();
3387 // will be replaced by a proper factory...
3388 Dialog * createGuiAbout(GuiView & lv);
3389 Dialog * createGuiBibitem(GuiView & lv);
3390 Dialog * createGuiBibtex(GuiView & lv);
3391 Dialog * createGuiBox(GuiView & lv);
3392 Dialog * createGuiBranch(GuiView & lv);
3393 Dialog * createGuiChanges(GuiView & lv);
3394 Dialog * createGuiCharacter(GuiView & lv);
3395 Dialog * createGuiCitation(GuiView & lv);
3396 Dialog * createGuiCompare(GuiView & lv);
3397 Dialog * createGuiDelimiter(GuiView & lv);
3398 Dialog * createGuiDocument(GuiView & lv);
3399 Dialog * createGuiErrorList(GuiView & lv);
3400 Dialog * createGuiERT(GuiView & lv);
3401 Dialog * createGuiExternal(GuiView & lv);
3402 Dialog * createGuiFloat(GuiView & lv);
3403 Dialog * createGuiGraphics(GuiView & lv);
3404 Dialog * createGuiInclude(GuiView & lv);
3405 Dialog * createGuiIndex(GuiView & lv);
3406 Dialog * createGuiInfo(GuiView & lv);
3407 Dialog * createGuiLabel(GuiView & lv);
3408 Dialog * createGuiListings(GuiView & lv);
3409 Dialog * createGuiLog(GuiView & lv);
3410 Dialog * createGuiMathHSpace(GuiView & lv);
3411 Dialog * createGuiMathMatrix(GuiView & lv);
3412 Dialog * createGuiNomenclature(GuiView & lv);
3413 Dialog * createGuiNote(GuiView & lv);
3414 Dialog * createGuiParagraph(GuiView & lv);
3415 Dialog * createGuiPhantom(GuiView & lv);
3416 Dialog * createGuiPreferences(GuiView & lv);
3417 Dialog * createGuiPrint(GuiView & lv);
3418 Dialog * createGuiPrintindex(GuiView & lv);
3419 Dialog * createGuiPrintNomencl(GuiView & lv);
3420 Dialog * createGuiRef(GuiView & lv);
3421 Dialog * createGuiSearch(GuiView & lv);
3422 Dialog * createGuiSearchAdv(GuiView & lv);
3423 Dialog * createGuiSendTo(GuiView & lv);
3424 Dialog * createGuiShowFile(GuiView & lv);
3425 Dialog * createGuiSpellchecker(GuiView & lv);
3426 Dialog * createGuiSymbols(GuiView & lv);
3427 Dialog * createGuiTabularCreate(GuiView & lv);
3428 Dialog * createGuiTabular(GuiView & lv);
3429 Dialog * createGuiTexInfo(GuiView & lv);
3430 Dialog * createGuiTextHSpace(GuiView & lv);
3431 Dialog * createGuiToc(GuiView & lv);
3432 Dialog * createGuiThesaurus(GuiView & lv);
3433 Dialog * createGuiHyperlink(GuiView & lv);
3434 Dialog * createGuiVSpace(GuiView & lv);
3435 Dialog * createGuiViewSource(GuiView & lv);
3436 Dialog * createGuiWrap(GuiView & lv);
3437 Dialog * createGuiProgressView(GuiView & lv);
3441 Dialog * GuiView::build(string const & name)
3443 LASSERT(isValidName(name), return 0);
3445 if (name == "aboutlyx")
3446 return createGuiAbout(*this);
3447 if (name == "bibitem")
3448 return createGuiBibitem(*this);
3449 if (name == "bibtex")
3450 return createGuiBibtex(*this);
3452 return createGuiBox(*this);
3453 if (name == "branch")
3454 return createGuiBranch(*this);
3455 if (name == "changes")
3456 return createGuiChanges(*this);
3457 if (name == "character")
3458 return createGuiCharacter(*this);
3459 if (name == "citation")
3460 return createGuiCitation(*this);
3461 if (name == "compare")
3462 return createGuiCompare(*this);
3463 if (name == "document")
3464 return createGuiDocument(*this);
3465 if (name == "errorlist")
3466 return createGuiErrorList(*this);
3468 return createGuiERT(*this);
3469 if (name == "external")
3470 return createGuiExternal(*this);
3472 return createGuiShowFile(*this);
3473 if (name == "findreplace")
3474 return createGuiSearch(*this);
3475 if (name == "findreplaceadv")
3476 return createGuiSearchAdv(*this);
3477 if (name == "float")
3478 return createGuiFloat(*this);
3479 if (name == "graphics")
3480 return createGuiGraphics(*this);
3482 return createGuiHyperlink(*this);
3483 if (name == "include")
3484 return createGuiInclude(*this);
3485 if (name == "index")
3486 return createGuiIndex(*this);
3487 if (name == "index_print")
3488 return createGuiPrintindex(*this);
3490 return createGuiInfo(*this);
3491 if (name == "label")
3492 return createGuiLabel(*this);
3493 if (name == "listings")
3494 return createGuiListings(*this);
3496 return createGuiLog(*this);
3497 if (name == "mathdelimiter")
3498 return createGuiDelimiter(*this);
3499 if (name == "mathspace")
3500 return createGuiMathHSpace(*this);
3501 if (name == "mathmatrix")
3502 return createGuiMathMatrix(*this);
3503 if (name == "nomenclature")
3504 return createGuiNomenclature(*this);
3505 if (name == "nomencl_print")
3506 return createGuiPrintNomencl(*this);
3508 return createGuiNote(*this);
3509 if (name == "paragraph")
3510 return createGuiParagraph(*this);
3511 if (name == "phantom")
3512 return createGuiPhantom(*this);
3513 if (name == "prefs")
3514 return createGuiPreferences(*this);
3515 if (name == "print")
3516 return createGuiPrint(*this);
3518 return createGuiRef(*this);
3519 if (name == "sendto")
3520 return createGuiSendTo(*this);
3521 if (name == "space")
3522 return createGuiTextHSpace(*this);
3523 if (name == "spellchecker")
3524 return createGuiSpellchecker(*this);
3525 if (name == "symbols")
3526 return createGuiSymbols(*this);
3527 if (name == "tabular")
3528 return createGuiTabular(*this);
3529 if (name == "tabularcreate")
3530 return createGuiTabularCreate(*this);
3531 if (name == "texinfo")
3532 return createGuiTexInfo(*this);
3533 if (name == "thesaurus")
3534 return createGuiThesaurus(*this);
3536 return createGuiToc(*this);
3537 if (name == "view-source")
3538 return createGuiViewSource(*this);
3539 if (name == "vspace")
3540 return createGuiVSpace(*this);
3542 return createGuiWrap(*this);
3543 if (name == "progress")
3544 return createGuiProgressView(*this);
3550 } // namespace frontend
3553 #include "moc_GuiView.cpp"