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 preview_watcher_.waitForFinished();
279 preview_watcher_.setFuture(f);
280 connect(&preview_watcher_, SIGNAL(finished()), gv_,
281 SLOT(threadFinished()));
287 GuiWorkArea * current_work_area_;
288 GuiWorkArea * current_main_work_area_;
289 QSplitter * splitter_;
290 QStackedWidget * stack_widget_;
291 BackgroundWidget * bg_widget_;
293 ToolbarMap toolbars_;
294 ProgressInterface* progress_;
295 /// The main layout box.
297 * \warning Don't Delete! The layout box is actually owned by
298 * whichever toolbar contains it. All the GuiView class needs is a
299 * means of accessing it.
301 * FIXME: replace that with a proper model so that we are not limited
302 * to only one dialog.
307 map<string, DialogPtr> dialogs_;
309 unsigned int smallIconSize;
310 unsigned int normalIconSize;
311 unsigned int bigIconSize;
313 QTimer statusbar_timer_;
314 /// auto-saving of buffers
315 Timeout autosave_timeout_;
316 /// flag against a race condition due to multiclicks, see bug #1119
320 TocModels toc_models_;
322 #if (QT_VERSION >= 0x040400)
324 QFutureWatcher<docstring> autosave_watcher_;
325 QFutureWatcher<docstring> preview_watcher_;
327 struct DummyWatcher { bool isRunning(){return false;} };
328 DummyWatcher preview_watcher_;
333 GuiView::GuiView(int id)
334 : d(*new GuiViewPrivate(this)), id_(id), closing_(false)
336 // GuiToolbars *must* be initialised before the menu bar.
337 normalSizedIcons(); // at least on Mac the default is 32 otherwise, which is huge
340 // set ourself as the current view. This is needed for the menu bar
341 // filling, at least for the static special menu item on Mac. Otherwise
342 // they are greyed out.
343 guiApp->setCurrentView(this);
345 // Fill up the menu bar.
346 guiApp->menus().fillMenuBar(menuBar(), this, true);
348 setCentralWidget(d.stack_widget_);
350 // Start autosave timer
351 if (lyxrc.autosave) {
352 d.autosave_timeout_.timeout.connect(boost::bind(&GuiView::autoSave, this));
353 d.autosave_timeout_.setTimeout(lyxrc.autosave * 1000);
354 d.autosave_timeout_.start();
356 connect(&d.statusbar_timer_, SIGNAL(timeout()),
357 this, SLOT(clearMessage()));
359 // We don't want to keep the window in memory if it is closed.
360 setAttribute(Qt::WA_DeleteOnClose, true);
362 #if (!defined(Q_WS_WIN) && !defined(Q_WS_MACX))
363 // assign an icon to main form. We do not do it under Qt/Win or Qt/Mac,
364 // since the icon is provided in the application bundle.
365 setWindowIcon(getPixmap("images/", "lyx", "png"));
369 setAcceptDrops(true);
371 statusBar()->setSizeGripEnabled(true);
373 #if (QT_VERSION >= 0x040400)
374 connect(&d.autosave_watcher_, SIGNAL(finished()), this,
375 SLOT(threadFinished()));
378 connect(this, SIGNAL(triggerShowDialog(QString const &, QString const &, Inset *)),
379 SLOT(doShowDialog(QString const &, QString const &, Inset *)));
381 // Forbid too small unresizable window because it can happen
382 // with some window manager under X11.
383 setMinimumSize(300, 200);
385 if (lyxrc.allow_geometry_session) {
386 // Now take care of session management.
391 // no session handling, default to a sane size.
392 setGeometry(50, 50, 690, 510);
395 // clear session data if any.
397 settings.remove("views");
407 void GuiView::threadFinished()
409 #if (QT_VERSION >= 0x040400)
410 QFutureWatcher<docstring> const * watcher =
411 static_cast<QFutureWatcher<docstring> const *>(sender());
412 message(watcher->result());
417 void GuiView::saveLayout() const
420 settings.beginGroup("views");
421 settings.beginGroup(QString::number(id_));
423 settings.setValue("pos", pos());
424 settings.setValue("size", size());
426 settings.setValue("geometry", saveGeometry());
428 settings.setValue("layout", saveState(0));
429 settings.setValue("icon_size", iconSize());
433 bool GuiView::restoreLayout()
436 settings.beginGroup("views");
437 settings.beginGroup(QString::number(id_));
438 QString const icon_key = "icon_size";
439 if (!settings.contains(icon_key))
442 //code below is skipped when when ~/.config/LyX is (re)created
443 setIconSize(settings.value(icon_key).toSize());
445 QPoint pos = settings.value("pos", QPoint(50, 50)).toPoint();
446 QSize size = settings.value("size", QSize(690, 510)).toSize();
450 // Work-around for bug #6034: the window ends up in an undetermined
451 // state when trying to restore a maximized window when it is
452 // already maximized.
453 if (!(windowState() & Qt::WindowMaximized))
454 if (!restoreGeometry(settings.value("geometry").toByteArray()))
455 setGeometry(50, 50, 690, 510);
457 // Make sure layout is correctly oriented.
458 setLayoutDirection(qApp->layoutDirection());
460 // Allow the toc and view-source dock widget to be restored if needed.
462 if ((dialog = findOrBuild("toc", true)))
463 // see bug 5082. At least setup title and enabled state.
464 // Visibility will be adjusted by restoreState below.
465 dialog->prepareView();
466 if ((dialog = findOrBuild("view-source", true)))
467 dialog->prepareView();
469 if (!restoreState(settings.value("layout").toByteArray(), 0))
476 GuiToolbar * GuiView::toolbar(string const & name)
478 ToolbarMap::iterator it = d.toolbars_.find(name);
479 if (it != d.toolbars_.end())
482 LYXERR(Debug::GUI, "Toolbar::display: no toolbar named " << name);
483 message(bformat(_("Unknown toolbar \"%1$s\""), from_utf8(name)));
488 void GuiView::constructToolbars()
490 ToolbarMap::iterator it = d.toolbars_.begin();
491 for (; it != d.toolbars_.end(); ++it)
495 // I don't like doing this here, but the standard toolbar
496 // destroys this object when it's destroyed itself (vfr)
497 d.layout_ = new LayoutBox(*this);
498 d.stack_widget_->addWidget(d.layout_);
499 d.layout_->move(0,0);
501 // extracts the toolbars from the backend
502 Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
503 Toolbars::Infos::iterator end = guiApp->toolbars().end();
504 for (; cit != end; ++cit)
505 d.toolbars_[cit->name] = new GuiToolbar(*cit, *this);
509 void GuiView::initToolbars()
511 // extracts the toolbars from the backend
512 Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
513 Toolbars::Infos::iterator end = guiApp->toolbars().end();
514 for (; cit != end; ++cit) {
515 GuiToolbar * tb = toolbar(cit->name);
518 int const visibility = guiApp->toolbars().defaultVisibility(cit->name);
520 tb->setVisible(false);
521 tb->setVisibility(visibility);
523 if (visibility & Toolbars::TOP) {
525 addToolBarBreak(Qt::TopToolBarArea);
526 addToolBar(Qt::TopToolBarArea, tb);
529 if (visibility & Toolbars::BOTTOM) {
530 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
531 #if (QT_VERSION >= 0x040202)
532 addToolBarBreak(Qt::BottomToolBarArea);
534 addToolBar(Qt::BottomToolBarArea, tb);
537 if (visibility & Toolbars::LEFT) {
538 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
539 #if (QT_VERSION >= 0x040202)
540 addToolBarBreak(Qt::LeftToolBarArea);
542 addToolBar(Qt::LeftToolBarArea, tb);
545 if (visibility & Toolbars::RIGHT) {
546 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
547 #if (QT_VERSION >= 0x040202)
548 addToolBarBreak(Qt::RightToolBarArea);
550 addToolBar(Qt::RightToolBarArea, tb);
553 if (visibility & Toolbars::ON)
554 tb->setVisible(true);
559 TocModels & GuiView::tocModels()
561 return d.toc_models_;
565 void GuiView::setFocus()
567 LYXERR(Debug::DEBUG, "GuiView::setFocus()" << this);
568 // Make sure LyXFunc points to the correct view.
569 guiApp->setCurrentView(this);
570 QMainWindow::setFocus();
571 if (d.current_work_area_)
572 d.current_work_area_->setFocus();
576 QMenu * GuiView::createPopupMenu()
578 return d.toolBarPopup(this);
582 void GuiView::showEvent(QShowEvent * e)
584 LYXERR(Debug::GUI, "Passed Geometry "
585 << size().height() << "x" << size().width()
586 << "+" << pos().x() << "+" << pos().y());
588 if (d.splitter_->count() == 0)
589 // No work area, switch to the background widget.
592 QMainWindow::showEvent(e);
596 /** Destroy only all tabbed WorkAreas. Destruction of other WorkAreas
597 ** is responsibility of the container (e.g., dialog)
599 void GuiView::closeEvent(QCloseEvent * close_event)
601 LYXERR(Debug::DEBUG, "GuiView::closeEvent()");
606 // it can happen that this event arrives without selecting the view,
607 // e.g. when clicking the close button on a background window.
609 if (!closeWorkAreaAll()) {
611 close_event->ignore();
615 // Make sure that nothing will use this to be closed View.
616 guiApp->unregisterView(this);
618 if (isFullScreen()) {
619 // Switch off fullscreen before closing.
624 // Make sure the timer time out will not trigger a statusbar update.
625 d.statusbar_timer_.stop();
627 // Saving fullscreen requires additional tweaks in the toolbar code.
628 // It wouldn't also work under linux natively.
629 if (lyxrc.allow_geometry_session) {
630 // Save this window geometry and layout.
632 // Then the toolbar private states.
633 ToolbarMap::iterator end = d.toolbars_.end();
634 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
635 it->second->saveSession();
636 // Now take care of all other dialogs:
637 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
638 for (; it!= d.dialogs_.end(); ++it)
639 it->second->saveSession();
642 close_event->accept();
646 void GuiView::dragEnterEvent(QDragEnterEvent * event)
648 if (event->mimeData()->hasUrls())
650 /// \todo Ask lyx-devel is this is enough:
651 /// if (event->mimeData()->hasFormat("text/plain"))
652 /// event->acceptProposedAction();
656 void GuiView::dropEvent(QDropEvent * event)
658 QList<QUrl> files = event->mimeData()->urls();
662 LYXERR(Debug::GUI, "GuiView::dropEvent: got URLs!");
663 for (int i = 0; i != files.size(); ++i) {
664 string const file = os::internal_path(fromqstr(
665 files.at(i).toLocalFile()));
669 string const ext = support::getExtension(file);
670 vector<const Format *> found_formats;
672 // Find all formats that have the correct extension.
673 vector<const Format *> const & import_formats
674 = theConverters().importableFormats();
675 vector<const Format *>::const_iterator it = import_formats.begin();
676 for (; it != import_formats.end(); ++it)
677 if ((*it)->extension() == ext)
678 found_formats.push_back(*it);
681 if (found_formats.size() >= 1) {
682 if (found_formats.size() > 1) {
683 //FIXME: show a dialog to choose the correct importable format
685 "Multiple importable formats found, selecting first");
687 string const arg = found_formats[0]->name() + " " + file;
688 cmd = FuncRequest(LFUN_BUFFER_IMPORT, arg);
691 //FIXME: do we have to explicitly check whether it's a lyx file?
693 "No formats found, trying to open it as a lyx file");
694 cmd = FuncRequest(LFUN_FILE_OPEN, file);
697 // Asynchronously post the event. DropEvent usually come
698 // from the BufferView. But reloading a file might close
699 // the BufferView from within its own event handler.
700 guiApp->dispatchDelayed(cmd);
706 void GuiView::message(docstring const & str)
708 if (ForkedProcess::iAmAChild())
711 // call is moved to GUI-thread by GuiProgress
712 d.progress_->appendMessage(toqstr(str));
716 void GuiView::updateMessage(QString const & str)
718 statusBar()->showMessage(str);
719 d.statusbar_timer_.stop();
720 d.statusbar_timer_.start(3000);
724 void GuiView::smallSizedIcons()
726 setIconSize(QSize(d.smallIconSize, d.smallIconSize));
730 void GuiView::normalSizedIcons()
732 setIconSize(QSize(d.normalIconSize, d.normalIconSize));
736 void GuiView::bigSizedIcons()
738 setIconSize(QSize(d.bigIconSize, d.bigIconSize));
742 void GuiView::clearMessage()
744 // FIXME: This code was introduced in r19643 to fix bug #4123. However,
745 // the hasFocus function mostly returns false, even if the focus is on
746 // a workarea in this view.
750 d.statusbar_timer_.stop();
754 void GuiView::updateWindowTitle(GuiWorkArea * wa)
756 if (wa != d.current_work_area_)
758 setWindowTitle(qt_("LyX: ") + wa->windowTitle());
759 setWindowIconText(wa->windowIconText());
763 void GuiView::on_currentWorkAreaChanged(GuiWorkArea * wa)
766 disconnectBufferView();
767 connectBufferView(wa->bufferView());
768 connectBuffer(wa->bufferView().buffer());
769 d.current_work_area_ = wa;
770 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
771 this, SLOT(updateWindowTitle(GuiWorkArea *)));
772 updateWindowTitle(wa);
776 // The document settings needs to be reinitialised.
777 updateDialog("document", "");
779 // Buffer-dependent dialogs must be updated. This is done here because
780 // some dialogs require buffer()->text.
785 void GuiView::on_lastWorkAreaRemoved()
788 // We already are in a close event. Nothing more to do.
791 if (d.splitter_->count() > 1)
792 // We have a splitter so don't close anything.
795 // Reset and updates the dialogs.
796 d.toc_models_.reset(0);
797 updateDialog("document", "");
800 resetWindowTitleAndIconText();
802 if (lyxrc.open_buffers_in_tabs)
803 // Nothing more to do, the window should stay open.
806 if (guiApp->viewIds().size() > 1) {
812 // On Mac we also close the last window because the application stay
813 // resident in memory. On other platforms we don't close the last
814 // window because this would quit the application.
820 void GuiView::updateStatusBar()
822 // let the user see the explicit message
823 if (d.statusbar_timer_.isActive())
830 void GuiView::showMessage()
832 QString msg = toqstr(theGuiApp()->viewStatusMessage());
834 BufferView const * bv = currentBufferView();
836 msg = toqstr(bv->cursor().currentState());
838 msg = qt_("Welcome to LyX!");
840 statusBar()->showMessage(msg);
844 bool GuiView::event(QEvent * e)
848 // Useful debug code:
849 //case QEvent::ActivationChange:
850 //case QEvent::WindowDeactivate:
851 //case QEvent::Paint:
852 //case QEvent::Enter:
853 //case QEvent::Leave:
854 //case QEvent::HoverEnter:
855 //case QEvent::HoverLeave:
856 //case QEvent::HoverMove:
857 //case QEvent::StatusTip:
858 //case QEvent::DragEnter:
859 //case QEvent::DragLeave:
863 case QEvent::WindowActivate: {
864 GuiView * old_view = guiApp->currentView();
865 if (this == old_view) {
867 return QMainWindow::event(e);
869 if (old_view && old_view->currentBufferView()) {
870 // save current selection to the selection buffer to allow
871 // middle-button paste in this window.
872 cap::saveSelection(old_view->currentBufferView()->cursor());
874 guiApp->setCurrentView(this);
875 if (d.current_work_area_) {
876 BufferView & bv = d.current_work_area_->bufferView();
877 connectBufferView(bv);
878 connectBuffer(bv.buffer());
879 // The document structure, name and dialogs might have
880 // changed in another view.
882 // The document settings needs to be reinitialised.
883 updateDialog("document", "");
886 resetWindowTitleAndIconText();
889 return QMainWindow::event(e);
892 case QEvent::ShortcutOverride: {
895 #if (!defined Q_WS_X11) || (QT_VERSION >= 0x040500)
896 if (isFullScreen() && menuBar()->isHidden()) {
897 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
898 // FIXME: we should also try to detect special LyX shortcut such as
899 // Alt-P and Alt-M. Right now there is a hack in
900 // GuiWorkArea::processKeySym() that hides again the menubar for
902 if (ke->modifiers() & Qt::AltModifier && ke->key() != Qt::Key_Alt) {
904 return QMainWindow::event(e);
909 if (d.current_work_area_)
910 // Nothing special to do.
911 return QMainWindow::event(e);
913 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
914 // Let Qt handle menu access and the Tab keys to navigate keys to navigate
916 if (ke->modifiers() & Qt::AltModifier || ke->key() == Qt::Key_Tab
917 || ke->key() == Qt::Key_Backtab)
918 return QMainWindow::event(e);
920 // Allow processing of shortcuts that are allowed even when no Buffer
923 setKeySymbol(&sym, ke);
924 guiApp->processKeySym(sym, q_key_state(ke->modifiers()));
930 return QMainWindow::event(e);
934 void GuiView::resetWindowTitleAndIconText()
936 setWindowTitle(qt_("LyX"));
937 setWindowIconText(qt_("LyX"));
940 bool GuiView::focusNextPrevChild(bool /*next*/)
947 void GuiView::setBusy(bool busy)
949 if (d.current_work_area_) {
950 d.current_work_area_->setUpdatesEnabled(!busy);
952 d.current_work_area_->stopBlinkingCursor();
954 d.current_work_area_->startBlinkingCursor();
958 QApplication::setOverrideCursor(Qt::WaitCursor);
960 QApplication::restoreOverrideCursor();
964 GuiWorkArea * GuiView::workArea(Buffer & buffer)
966 if (currentWorkArea()
967 && ¤tWorkArea()->bufferView().buffer() == &buffer)
968 return (GuiWorkArea *) currentWorkArea();
969 if (TabWorkArea * twa = d.currentTabWorkArea())
970 return twa->workArea(buffer);
975 GuiWorkArea * GuiView::addWorkArea(Buffer & buffer)
977 // Automatically create a TabWorkArea if there are none yet.
978 TabWorkArea * tab_widget = d.splitter_->count()
979 ? d.currentTabWorkArea() : addTabWorkArea();
980 return tab_widget->addWorkArea(buffer, *this);
984 TabWorkArea * GuiView::addTabWorkArea()
986 TabWorkArea * twa = new TabWorkArea;
987 QObject::connect(twa, SIGNAL(currentWorkAreaChanged(GuiWorkArea *)),
988 this, SLOT(on_currentWorkAreaChanged(GuiWorkArea *)));
989 QObject::connect(twa, SIGNAL(lastWorkAreaRemoved()),
990 this, SLOT(on_lastWorkAreaRemoved()));
992 d.splitter_->addWidget(twa);
993 d.stack_widget_->setCurrentWidget(d.splitter_);
998 GuiWorkArea const * GuiView::currentWorkArea() const
1000 return d.current_work_area_;
1004 GuiWorkArea * GuiView::currentWorkArea()
1006 return d.current_work_area_;
1010 GuiWorkArea const * GuiView::currentMainWorkArea() const
1012 if (d.currentTabWorkArea() == NULL)
1014 return d.currentTabWorkArea()->currentWorkArea();
1018 GuiWorkArea * GuiView::currentMainWorkArea()
1020 if (d.currentTabWorkArea() == NULL)
1022 return d.currentTabWorkArea()->currentWorkArea();
1026 void GuiView::setCurrentWorkArea(GuiWorkArea * wa)
1028 LYXERR(Debug::DEBUG, "Setting current wa: " << wa << endl);
1030 d.current_work_area_ = NULL;
1034 GuiWorkArea * old_gwa = theGuiApp()->currentView()->currentWorkArea();
1038 if (currentBufferView())
1039 cap::saveSelection(currentBufferView()->cursor());
1041 theGuiApp()->setCurrentView(this);
1042 d.current_work_area_ = wa;
1043 for (int i = 0; i != d.splitter_->count(); ++i) {
1044 if (d.tabWorkArea(i)->setCurrentWorkArea(wa)) {
1045 //if (d.current_main_work_area_)
1046 // d.current_main_work_area_->setFrameStyle(QFrame::NoFrame);
1047 d.current_main_work_area_ = wa;
1048 //d.current_main_work_area_->setFrameStyle(QFrame::Box | QFrame::Plain);
1049 //d.current_main_work_area_->setLineWidth(2);
1050 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() << ", Current main wa: " << currentMainWorkArea());
1054 LYXERR(Debug::DEBUG, "This is not a tabbed wa");
1055 on_currentWorkAreaChanged(wa);
1056 BufferView & bv = wa->bufferView();
1057 bv.cursor().fixIfBroken();
1059 wa->setUpdatesEnabled(true);
1060 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() << ", Current main wa: " << currentMainWorkArea());
1064 void GuiView::removeWorkArea(GuiWorkArea * wa)
1066 LASSERT(wa, return);
1067 if (wa == d.current_work_area_) {
1069 disconnectBufferView();
1070 d.current_work_area_ = 0;
1071 d.current_main_work_area_ = 0;
1074 bool found_twa = false;
1075 for (int i = 0; i != d.splitter_->count(); ++i) {
1076 TabWorkArea * twa = d.tabWorkArea(i);
1077 if (twa->removeWorkArea(wa)) {
1078 // Found in this tab group, and deleted the GuiWorkArea.
1080 if (twa->count() != 0) {
1081 if (d.current_work_area_ == 0)
1082 // This means that we are closing the current GuiWorkArea, so
1083 // switch to the next GuiWorkArea in the found TabWorkArea.
1084 setCurrentWorkArea(twa->currentWorkArea());
1086 // No more WorkAreas in this tab group, so delete it.
1093 // It is not a tabbed work area (i.e., the search work area), so it
1094 // should be deleted by other means.
1095 LASSERT(found_twa, /* */);
1097 if (d.current_work_area_ == 0) {
1098 if (d.splitter_->count() != 0) {
1099 TabWorkArea * twa = d.currentTabWorkArea();
1100 setCurrentWorkArea(twa->currentWorkArea());
1102 // No more work areas, switch to the background widget.
1103 setCurrentWorkArea(0);
1109 LayoutBox * GuiView::getLayoutDialog() const
1115 void GuiView::updateLayoutList()
1118 d.layout_->updateContents(false);
1122 void GuiView::updateToolbars()
1124 ToolbarMap::iterator end = d.toolbars_.end();
1125 if (d.current_work_area_) {
1127 d.current_work_area_->bufferView().cursor().inMathed();
1129 lyx::getStatus(FuncRequest(LFUN_LAYOUT_TABULAR)).enabled();
1131 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).enabled() &&
1132 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).onoff(true);
1133 bool const mathmacrotemplate =
1134 lyx::getStatus(FuncRequest(LFUN_IN_MATHMACROTEMPLATE)).enabled();
1136 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1137 it->second->update(math, table, review, mathmacrotemplate);
1139 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1140 it->second->update(false, false, false, false);
1144 void GuiView::setBuffer(Buffer * newBuffer)
1146 LYXERR(Debug::DEBUG, "Setting buffer: " << newBuffer << endl);
1147 LASSERT(newBuffer, return);
1150 GuiWorkArea * wa = workArea(*newBuffer);
1152 newBuffer->masterBuffer()->updateLabels();
1153 wa = addWorkArea(*newBuffer);
1155 //Disconnect the old buffer...there's no new one.
1158 connectBuffer(*newBuffer);
1159 connectBufferView(wa->bufferView());
1160 setCurrentWorkArea(wa);
1166 void GuiView::connectBuffer(Buffer & buf)
1168 buf.setGuiDelegate(this);
1172 void GuiView::disconnectBuffer()
1174 if (d.current_work_area_)
1175 d.current_work_area_->bufferView().buffer().setGuiDelegate(0);
1179 void GuiView::connectBufferView(BufferView & bv)
1181 bv.setGuiDelegate(this);
1185 void GuiView::disconnectBufferView()
1187 if (d.current_work_area_)
1188 d.current_work_area_->bufferView().setGuiDelegate(0);
1192 void GuiView::errors(string const & error_type, bool from_master)
1194 ErrorList & el = from_master ?
1195 documentBufferView()->buffer().masterBuffer()->errorList(error_type)
1196 : documentBufferView()->buffer().errorList(error_type);
1197 string data = error_type;
1199 data = "from_master|" + error_type;
1201 showDialog("errorlist", data);
1205 void GuiView::updateTocItem(string const & type, DocIterator const & dit)
1207 d.toc_models_.updateItem(toqstr(type), dit);
1211 void GuiView::structureChanged()
1213 d.toc_models_.reset(documentBufferView());
1214 // Navigator needs more than a simple update in this case. It needs to be
1216 updateDialog("toc", "");
1220 void GuiView::updateDialog(string const & name, string const & data)
1222 if (!isDialogVisible(name))
1225 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
1226 if (it == d.dialogs_.end())
1229 Dialog * const dialog = it->second.get();
1230 if (dialog->isVisibleView())
1231 dialog->initialiseParams(data);
1235 BufferView * GuiView::documentBufferView()
1237 return currentMainWorkArea()
1238 ? ¤tMainWorkArea()->bufferView()
1243 BufferView const * GuiView::documentBufferView() const
1245 return currentMainWorkArea()
1246 ? ¤tMainWorkArea()->bufferView()
1251 BufferView * GuiView::currentBufferView()
1253 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1257 BufferView const * GuiView::currentBufferView() const
1259 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1263 static docstring saveAndDestroyBuffer(Buffer * buffer, FileName const & fname)
1266 FileName const tmp_ret = FileName::tempName("lyxauto");
1267 if (!tmp_ret.empty()) {
1268 if (buffer->writeFile(tmp_ret))
1269 failed = !tmp_ret.moveTo(fname);
1272 // failed to write/rename tmp_ret so try writing direct
1273 failed = buffer->writeFile(fname);
1277 ? _("Automatic save failed!")
1278 : _("Automatic save done.");
1282 void GuiView::autoSave()
1284 LYXERR(Debug::INFO, "Running autoSave()");
1286 Buffer * buffer = documentBufferView()
1287 ? &documentBufferView()->buffer() : 0;
1291 #if (QT_VERSION >= 0x040400)
1292 QFuture<docstring> f = QtConcurrent::run(saveAndDestroyBuffer, buffer->clone(),
1293 buffer->getAutosaveFilename());
1294 d.autosave_watcher_.setFuture(f);
1301 void GuiView::resetAutosaveTimers()
1304 d.autosave_timeout_.restart();
1308 bool GuiView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1311 Buffer * buf = currentBufferView()
1312 ? ¤tBufferView()->buffer() : 0;
1313 Buffer * doc_buffer = documentBufferView()
1314 ? &(documentBufferView()->buffer()) : 0;
1316 // Check whether we need a buffer
1317 if (!lyxaction.funcHasFlag(cmd.action, LyXAction::NoBuffer) && !buf) {
1318 // no, exit directly
1319 flag.message(from_utf8(N_("Command not allowed with"
1320 "out any document open")));
1321 flag.setEnabled(false);
1325 if (cmd.origin == FuncRequest::TOC) {
1326 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
1328 if (toc->getStatus(documentBufferView()->cursor(), cmd, fs))
1331 flag.setEnabled(false);
1335 switch(cmd.action) {
1336 case LFUN_BUFFER_IMPORT:
1339 case LFUN_MASTER_BUFFER_UPDATE:
1340 case LFUN_MASTER_BUFFER_VIEW:
1341 enable = doc_buffer && doc_buffer->parent() != 0
1342 && !d.preview_watcher_.isRunning();
1345 case LFUN_BUFFER_UPDATE:
1346 case LFUN_BUFFER_VIEW: {
1347 if (!doc_buffer || d.preview_watcher_.isRunning()) {
1351 string format = to_utf8(cmd.argument());
1352 if (cmd.argument().empty())
1353 format = doc_buffer->getDefaultOutputFormat();
1354 enable = doc_buffer->isExportableFormat(format);
1358 case LFUN_BUFFER_RELOAD:
1359 enable = doc_buffer && !doc_buffer->isUnnamed()
1360 && doc_buffer->fileName().exists()
1361 && (!doc_buffer->isClean()
1362 || doc_buffer->isExternallyModified(Buffer::timestamp_method));
1365 case LFUN_BUFFER_CHILD_OPEN:
1366 enable = doc_buffer;
1369 case LFUN_BUFFER_WRITE:
1370 enable = doc_buffer && (doc_buffer->isUnnamed() || !doc_buffer->isClean());
1373 //FIXME: This LFUN should be moved to GuiApplication.
1374 case LFUN_BUFFER_WRITE_ALL: {
1375 // We enable the command only if there are some modified buffers
1376 Buffer * first = theBufferList().first();
1381 // We cannot use a for loop as the buffer list is a cycle.
1383 if (!b->isClean()) {
1387 b = theBufferList().next(b);
1388 } while (b != first);
1392 case LFUN_BUFFER_WRITE_AS:
1393 enable = doc_buffer;
1396 case LFUN_BUFFER_CLOSE:
1397 enable = doc_buffer;
1400 case LFUN_BUFFER_CLOSE_ALL:
1401 enable = theBufferList().last() != theBufferList().first();
1404 case LFUN_SPLIT_VIEW:
1405 if (cmd.getArg(0) == "vertical")
1406 enable = doc_buffer && (d.splitter_->count() == 1 ||
1407 d.splitter_->orientation() == Qt::Vertical);
1409 enable = doc_buffer && (d.splitter_->count() == 1 ||
1410 d.splitter_->orientation() == Qt::Horizontal);
1413 case LFUN_CLOSE_TAB_GROUP:
1414 enable = d.currentTabWorkArea();
1417 case LFUN_TOOLBAR_TOGGLE:
1418 if (GuiToolbar * t = toolbar(cmd.getArg(0)))
1419 flag.setOnOff(t->isVisible());
1422 case LFUN_DROP_LAYOUTS_CHOICE:
1426 case LFUN_UI_TOGGLE:
1427 flag.setOnOff(isFullScreen());
1430 case LFUN_DIALOG_DISCONNECT_INSET:
1433 case LFUN_DIALOG_HIDE:
1434 // FIXME: should we check if the dialog is shown?
1437 case LFUN_DIALOG_TOGGLE:
1438 flag.setOnOff(isDialogVisible(cmd.getArg(0)));
1439 // fall through to set "enable"
1440 case LFUN_DIALOG_SHOW: {
1441 string const name = cmd.getArg(0);
1443 enable = name == "aboutlyx"
1444 || name == "file" //FIXME: should be removed.
1446 || name == "texinfo"
1447 || name == "progress"
1448 || name == "compare";
1449 else if (name == "print")
1450 enable = doc_buffer->isExportable("dvi")
1451 && lyxrc.print_command != "none";
1452 else if (name == "character" || name == "symbols") {
1453 if (!buf || buf->isReadonly()
1454 || !currentBufferView()->cursor().inTexted())
1457 // FIXME we should consider passthru
1459 Inset const & in = currentBufferView()->cursor().inset();
1460 enable = !in.getLayout().isPassThru();
1463 else if (name == "latexlog")
1464 enable = FileName(doc_buffer->logName()).isReadableFile();
1465 else if (name == "spellchecker")
1466 enable = theSpellChecker() && !doc_buffer->isReadonly();
1467 else if (name == "vclog")
1468 enable = doc_buffer->lyxvc().inUse();
1472 case LFUN_DIALOG_UPDATE: {
1473 string const name = cmd.getArg(0);
1475 enable = name == "prefs";
1479 case LFUN_COMMAND_EXECUTE:
1481 case LFUN_MENU_OPEN:
1482 // Nothing to check.
1485 case LFUN_COMPLETION_INLINE:
1486 if (!d.current_work_area_
1487 || !d.current_work_area_->completer().inlinePossible(
1488 currentBufferView()->cursor()))
1492 case LFUN_COMPLETION_POPUP:
1493 if (!d.current_work_area_
1494 || !d.current_work_area_->completer().popupPossible(
1495 currentBufferView()->cursor()))
1499 case LFUN_COMPLETION_COMPLETE:
1500 if (!d.current_work_area_
1501 || !d.current_work_area_->completer().inlinePossible(
1502 currentBufferView()->cursor()))
1506 case LFUN_COMPLETION_ACCEPT:
1507 if (!d.current_work_area_
1508 || (!d.current_work_area_->completer().popupVisible()
1509 && !d.current_work_area_->completer().inlineVisible()
1510 && !d.current_work_area_->completer().completionAvailable()))
1514 case LFUN_COMPLETION_CANCEL:
1515 if (!d.current_work_area_
1516 || (!d.current_work_area_->completer().popupVisible()
1517 && !d.current_work_area_->completer().inlineVisible()))
1521 case LFUN_BUFFER_ZOOM_OUT:
1522 enable = doc_buffer && lyxrc.zoom > 10;
1525 case LFUN_BUFFER_ZOOM_IN:
1526 enable = doc_buffer;
1529 case LFUN_BUFFER_NEXT:
1530 case LFUN_BUFFER_PREVIOUS:
1531 // FIXME: should we check is there is an previous or next buffer?
1533 case LFUN_BUFFER_SWITCH:
1534 // toggle on the current buffer, but do not toggle off
1535 // the other ones (is that a good idea?)
1537 && to_utf8(cmd.argument()) == doc_buffer->absFileName())
1538 flag.setOnOff(true);
1541 case LFUN_VC_REGISTER:
1542 enable = doc_buffer && !doc_buffer->lyxvc().inUse();
1544 case LFUN_VC_CHECK_IN:
1545 enable = doc_buffer && doc_buffer->lyxvc().checkInEnabled();
1547 case LFUN_VC_CHECK_OUT:
1548 enable = doc_buffer && doc_buffer->lyxvc().checkOutEnabled();
1550 case LFUN_VC_LOCKING_TOGGLE:
1551 enable = doc_buffer && !doc_buffer->isReadonly()
1552 && doc_buffer->lyxvc().lockingToggleEnabled();
1553 flag.setOnOff(enable && !doc_buffer->lyxvc().locker().empty());
1555 case LFUN_VC_REVERT:
1556 enable = doc_buffer && doc_buffer->lyxvc().inUse();
1558 case LFUN_VC_UNDO_LAST:
1559 enable = doc_buffer && doc_buffer->lyxvc().undoLastEnabled();
1561 case LFUN_VC_REPO_UPDATE:
1562 enable = doc_buffer && doc_buffer->lyxvc().inUse();
1564 case LFUN_VC_COMMAND: {
1565 if (cmd.argument().empty())
1567 if (!doc_buffer && contains(cmd.getArg(0), 'D'))
1572 case LFUN_SERVER_GOTO_FILE_ROW:
1580 flag.setEnabled(false);
1586 static FileName selectTemplateFile()
1588 FileDialog dlg(qt_("Select template file"));
1589 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1590 dlg.setButton1(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
1592 FileDialog::Result result = dlg.open(toqstr(lyxrc.template_path),
1593 QStringList(qt_("LyX Documents (*.lyx)")));
1595 if (result.first == FileDialog::Later)
1597 if (result.second.isEmpty())
1599 return FileName(fromqstr(result.second));
1603 Buffer * GuiView::loadDocument(FileName const & filename, bool tolastfiles)
1607 Buffer * newBuffer = checkAndLoadLyXFile(filename);
1610 message(_("Document not loaded."));
1615 setBuffer(newBuffer);
1617 // scroll to the position when the file was last closed
1618 if (lyxrc.use_lastfilepos) {
1619 LastFilePosSection::FilePos filepos =
1620 theSession().lastFilePos().load(filename);
1621 documentBufferView()->moveToPosition(filepos.pit, filepos.pos, 0, 0);
1625 theSession().lastFiles().add(filename);
1632 void GuiView::openDocument(string const & fname)
1634 string initpath = lyxrc.document_path;
1636 if (documentBufferView()) {
1637 string const trypath = documentBufferView()->buffer().filePath();
1638 // If directory is writeable, use this as default.
1639 if (FileName(trypath).isDirWritable())
1645 if (fname.empty()) {
1646 FileDialog dlg(qt_("Select document to open"), LFUN_FILE_OPEN);
1647 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1648 dlg.setButton2(qt_("Examples|#E#e"),
1649 toqstr(addPath(package().system_support().absFilename(), "examples")));
1651 QStringList filter(qt_("LyX Documents (*.lyx)"));
1652 filter << qt_("LyX-1.3.x Documents (*.lyx13)")
1653 << qt_("LyX-1.4.x Documents (*.lyx14)")
1654 << qt_("LyX-1.5.x Documents (*.lyx15)")
1655 << qt_("LyX-1.6.x Documents (*.lyx16)");
1656 FileDialog::Result result =
1657 dlg.open(toqstr(initpath), filter);
1659 if (result.first == FileDialog::Later)
1662 filename = fromqstr(result.second);
1664 // check selected filename
1665 if (filename.empty()) {
1666 message(_("Canceled."));
1672 // get absolute path of file and add ".lyx" to the filename if
1674 FileName const fullname =
1675 fileSearch(string(), filename, "lyx", support::may_not_exist);
1676 if (!fullname.empty())
1677 filename = fullname.absFilename();
1679 if (!fullname.onlyPath().isDirectory()) {
1680 Alert::warning(_("Invalid filename"),
1681 bformat(_("The directory in the given path\n%1$s\ndoes not exist."),
1682 from_utf8(fullname.absFilename())));
1685 // if the file doesn't exist, let the user create one
1686 if (!fullname.exists()) {
1687 // the user specifically chose this name. Believe him.
1688 Buffer * const b = newFile(filename, string(), true);
1694 docstring const disp_fn = makeDisplayPath(filename);
1695 message(bformat(_("Opening document %1$s..."), disp_fn));
1698 Buffer * buf = loadDocument(fullname);
1700 buf->updateLabels();
1702 buf->errors("Parse");
1703 str2 = bformat(_("Document %1$s opened."), disp_fn);
1704 if (buf->lyxvc().inUse())
1705 str2 += " " + from_utf8(buf->lyxvc().versionString()) +
1706 " " + _("Version control detected.");
1708 str2 = bformat(_("Could not open document %1$s"), disp_fn);
1713 // FIXME: clean that
1714 static bool import(GuiView * lv, FileName const & filename,
1715 string const & format, ErrorList & errorList)
1717 FileName const lyxfile(support::changeExtension(filename.absFilename(), ".lyx"));
1719 string loader_format;
1720 vector<string> loaders = theConverters().loaders();
1721 if (find(loaders.begin(), loaders.end(), format) == loaders.end()) {
1722 for (vector<string>::const_iterator it = loaders.begin();
1723 it != loaders.end(); ++it) {
1724 if (!theConverters().isReachable(format, *it))
1727 string const tofile =
1728 support::changeExtension(filename.absFilename(),
1729 formats.extension(*it));
1730 if (!theConverters().convert(0, filename, FileName(tofile),
1731 filename, format, *it, errorList))
1733 loader_format = *it;
1736 if (loader_format.empty()) {
1737 frontend::Alert::error(_("Couldn't import file"),
1738 bformat(_("No information for importing the format %1$s."),
1739 formats.prettyName(format)));
1743 loader_format = format;
1745 if (loader_format == "lyx") {
1746 Buffer * buf = lv->loadDocument(lyxfile);
1749 buf->updateLabels();
1751 buf->errors("Parse");
1753 Buffer * const b = newFile(lyxfile.absFilename(), string(), true);
1757 bool as_paragraphs = loader_format == "textparagraph";
1758 string filename2 = (loader_format == format) ? filename.absFilename()
1759 : support::changeExtension(filename.absFilename(),
1760 formats.extension(loader_format));
1761 lv->currentBufferView()->insertPlaintextFile(FileName(filename2),
1763 guiApp->setCurrentView(lv);
1764 lyx::dispatch(FuncRequest(LFUN_MARK_OFF));
1771 void GuiView::importDocument(string const & argument)
1774 string filename = split(argument, format, ' ');
1776 LYXERR(Debug::INFO, format << " file: " << filename);
1778 // need user interaction
1779 if (filename.empty()) {
1780 string initpath = lyxrc.document_path;
1781 if (documentBufferView()) {
1782 string const trypath = documentBufferView()->buffer().filePath();
1783 // If directory is writeable, use this as default.
1784 if (FileName(trypath).isDirWritable())
1788 docstring const text = bformat(_("Select %1$s file to import"),
1789 formats.prettyName(format));
1791 FileDialog dlg(toqstr(text), LFUN_BUFFER_IMPORT);
1792 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1793 dlg.setButton2(qt_("Examples|#E#e"),
1794 toqstr(addPath(package().system_support().absFilename(), "examples")));
1796 docstring filter = formats.prettyName(format);
1799 filter += from_utf8(formats.extension(format));
1802 FileDialog::Result result =
1803 dlg.open(toqstr(initpath), fileFilters(toqstr(filter)));
1805 if (result.first == FileDialog::Later)
1808 filename = fromqstr(result.second);
1810 // check selected filename
1811 if (filename.empty())
1812 message(_("Canceled."));
1815 if (filename.empty())
1818 // get absolute path of file
1819 FileName const fullname(support::makeAbsPath(filename));
1821 FileName const lyxfile(support::changeExtension(fullname.absFilename(), ".lyx"));
1823 // Check if the document already is open
1824 Buffer * buf = theBufferList().getBuffer(lyxfile);
1827 if (!closeBuffer()) {
1828 message(_("Canceled."));
1833 docstring const displaypath = makeDisplayPath(lyxfile.absFilename(), 30);
1835 // if the file exists already, and we didn't do
1836 // -i lyx thefile.lyx, warn
1837 if (lyxfile.exists() && fullname != lyxfile) {
1839 docstring text = bformat(_("The document %1$s already exists.\n\n"
1840 "Do you want to overwrite that document?"), displaypath);
1841 int const ret = Alert::prompt(_("Overwrite document?"),
1842 text, 0, 1, _("&Overwrite"), _("&Cancel"));
1845 message(_("Canceled."));
1850 message(bformat(_("Importing %1$s..."), displaypath));
1851 ErrorList errorList;
1852 if (import(this, fullname, format, errorList))
1853 message(_("imported."));
1855 message(_("file not imported!"));
1857 // FIXME (Abdel 12/08/06): Is there a need to display the error list here?
1861 void GuiView::newDocument(string const & filename, bool from_template)
1863 FileName initpath(lyxrc.document_path);
1864 if (documentBufferView()) {
1865 FileName const trypath(documentBufferView()->buffer().filePath());
1866 // If directory is writeable, use this as default.
1867 if (trypath.isDirWritable())
1871 string templatefile;
1872 if (from_template) {
1873 templatefile = selectTemplateFile().absFilename();
1874 if (templatefile.empty())
1879 if (filename.empty())
1880 b = newUnnamedFile(initpath, to_utf8(_("newfile")), templatefile);
1882 b = newFile(filename, templatefile, true);
1887 // If no new document could be created, it is unsure
1888 // whether there is a valid BufferView.
1889 if (currentBufferView())
1890 // Ensure the cursor is correctly positioned on screen.
1891 currentBufferView()->showCursor();
1895 void GuiView::insertLyXFile(docstring const & fname)
1897 BufferView * bv = documentBufferView();
1902 FileName filename(to_utf8(fname));
1904 if (!filename.empty()) {
1905 bv->insertLyXFile(filename);
1909 // Launch a file browser
1911 string initpath = lyxrc.document_path;
1912 string const trypath = bv->buffer().filePath();
1913 // If directory is writeable, use this as default.
1914 if (FileName(trypath).isDirWritable())
1918 FileDialog dlg(qt_("Select LyX document to insert"), LFUN_FILE_INSERT);
1919 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1920 dlg.setButton2(qt_("Examples|#E#e"),
1921 toqstr(addPath(package().system_support().absFilename(),
1924 FileDialog::Result result = dlg.open(toqstr(initpath),
1925 QStringList(qt_("LyX Documents (*.lyx)")));
1927 if (result.first == FileDialog::Later)
1931 filename.set(fromqstr(result.second));
1933 // check selected filename
1934 if (filename.empty()) {
1935 // emit message signal.
1936 message(_("Canceled."));
1940 bv->insertLyXFile(filename);
1944 void GuiView::insertPlaintextFile(docstring const & fname,
1947 BufferView * bv = documentBufferView();
1951 if (!fname.empty() && !FileName::isAbsolute(to_utf8(fname))) {
1952 message(_("Absolute filename expected."));
1957 FileName filename(to_utf8(fname));
1959 if (!filename.empty()) {
1960 bv->insertPlaintextFile(filename, asParagraph);
1964 FileDialog dlg(qt_("Select file to insert"), (asParagraph ?
1965 LFUN_FILE_INSERT_PLAINTEXT_PARA : LFUN_FILE_INSERT_PLAINTEXT));
1967 FileDialog::Result result = dlg.open(toqstr(bv->buffer().filePath()),
1968 QStringList(qt_("All Files (*)")));
1970 if (result.first == FileDialog::Later)
1974 filename.set(fromqstr(result.second));
1976 // check selected filename
1977 if (filename.empty()) {
1978 // emit message signal.
1979 message(_("Canceled."));
1983 bv->insertPlaintextFile(filename, asParagraph);
1987 bool GuiView::renameBuffer(Buffer & b, docstring const & newname)
1989 FileName fname = b.fileName();
1990 FileName const oldname = fname;
1992 if (!newname.empty()) {
1994 fname = support::makeAbsPath(to_utf8(newname), oldname.onlyPath().absFilename());
1996 // Switch to this Buffer.
1999 // No argument? Ask user through dialog.
2001 FileDialog dlg(qt_("Choose a filename to save document as"),
2002 LFUN_BUFFER_WRITE_AS);
2003 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2004 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
2006 if (!isLyXFilename(fname.absFilename()))
2007 fname.changeExtension(".lyx");
2009 FileDialog::Result result =
2010 dlg.save(toqstr(fname.onlyPath().absFilename()),
2011 QStringList(qt_("LyX Documents (*.lyx)")),
2012 toqstr(fname.onlyFileName()));
2014 if (result.first == FileDialog::Later)
2017 fname.set(fromqstr(result.second));
2022 if (!isLyXFilename(fname.absFilename()))
2023 fname.changeExtension(".lyx");
2026 if (FileName(fname).exists()) {
2027 docstring const file = makeDisplayPath(fname.absFilename(), 30);
2028 docstring text = bformat(_("The document %1$s already "
2029 "exists.\n\nDo you want to "
2030 "overwrite that document?"),
2032 int const ret = Alert::prompt(_("Overwrite document?"),
2033 text, 0, 2, _("&Overwrite"), _("&Rename"), _("&Cancel"));
2036 case 1: return renameBuffer(b, docstring());
2037 case 2: return false;
2041 FileName oldauto = b.getAutosaveFilename();
2043 // Ok, change the name of the buffer
2044 b.setFileName(fname.absFilename());
2046 bool unnamed = b.isUnnamed();
2047 b.setUnnamed(false);
2048 b.saveCheckSum(fname);
2050 // bring the autosave file with us, just in case.
2051 b.moveAutosaveFile(oldauto);
2053 if (!saveBuffer(b)) {
2054 oldauto = b.getAutosaveFilename();
2055 b.setFileName(oldname.absFilename());
2056 b.setUnnamed(unnamed);
2057 b.saveCheckSum(oldname);
2058 b.moveAutosaveFile(oldauto);
2066 bool GuiView::saveBuffer(Buffer & b)
2068 if (workArea(b) && workArea(b)->inDialogMode())
2072 return renameBuffer(b, docstring());
2075 theSession().lastFiles().add(b.fileName());
2079 // Switch to this Buffer.
2082 // FIXME: we don't tell the user *WHY* the save failed !!
2083 docstring const file = makeDisplayPath(b.absFileName(), 30);
2084 docstring text = bformat(_("The document %1$s could not be saved.\n\n"
2085 "Do you want to rename the document and "
2086 "try again?"), file);
2087 int const ret = Alert::prompt(_("Rename and save?"),
2088 text, 0, 2, _("&Rename"), _("&Retry"), _("&Cancel"));
2091 if (!renameBuffer(b, docstring()))
2100 return saveBuffer(b);
2104 bool GuiView::hideWorkArea(GuiWorkArea * wa)
2106 return closeWorkArea(wa, false);
2110 bool GuiView::closeWorkArea(GuiWorkArea * wa)
2112 Buffer & buf = wa->bufferView().buffer();
2113 return closeWorkArea(wa, !buf.parent());
2117 bool GuiView::closeBuffer()
2119 GuiWorkArea * wa = currentMainWorkArea();
2120 Buffer & buf = wa->bufferView().buffer();
2121 return wa && closeWorkArea(wa, !buf.parent());
2125 void GuiView::writeSession() const {
2126 GuiWorkArea const * active_wa = currentMainWorkArea();
2127 for (int i = 0; i < d.splitter_->count(); ++i) {
2128 TabWorkArea * twa = d.tabWorkArea(i);
2129 for (int j = 0; j < twa->count(); ++j) {
2130 GuiWorkArea * wa = static_cast<GuiWorkArea *>(twa->widget(j));
2131 Buffer & buf = wa->bufferView().buffer();
2132 theSession().lastOpened().add(buf.fileName(), wa == active_wa);
2138 bool GuiView::closeBufferAll()
2140 // Close the workareas in all other views
2141 QList<int> const ids = guiApp->viewIds();
2142 for (int i = 0; i != ids.size(); ++i) {
2143 if (id_ != ids[i] && !guiApp->view(ids[i]).closeWorkAreaAll())
2147 // Close our own workareas
2148 if (!closeWorkAreaAll())
2151 // Now close the hidden buffers. We prevent hidden buffers from being
2152 // dirty, so we can just close them.
2153 theBufferList().closeAll();
2158 bool GuiView::closeWorkAreaAll()
2160 setCurrentWorkArea(currentMainWorkArea());
2162 // We might be in a situation that there is still a tabWorkArea, but
2163 // there are no tabs anymore. This can happen when we get here after a
2164 // TabWorkArea::lastWorkAreaRemoved() signal. Therefore we count how
2165 // many TabWorkArea's have no documents anymore.
2168 // We have to call count() each time, because it can happen that
2169 // more than one splitter will disappear in one iteration (bug 5998).
2170 for (; d.splitter_->count() > empty_twa; ) {
2171 TabWorkArea * twa = d.tabWorkArea(empty_twa);
2173 if (twa->count() == 0)
2176 setCurrentWorkArea(twa->currentWorkArea());
2177 if (!closeTabWorkArea(twa))
2185 bool GuiView::closeWorkArea(GuiWorkArea * wa, bool close_buffer)
2190 Buffer & buf = wa->bufferView().buffer();
2193 return closeBuffer(buf);
2195 if (!inMultiTabs(wa))
2196 if (!saveBufferIfNeeded(buf, true))
2204 bool GuiView::closeBuffer(Buffer & buf)
2206 // If we are in a close_event all children will be closed in some time,
2207 // so no need to do it here. This will ensure that the children end up
2208 // in the session file in the correct order. If we close the master
2209 // buffer, we can close or release the child buffers here too.
2211 vector<Buffer *> clist = buf.getChildren(false);
2212 for (vector<Buffer *>::const_iterator it = clist.begin();
2213 it != clist.end(); ++it) {
2214 // If a child is dirty, do not close
2215 // without user intervention
2216 //FIXME: should we look in other tabworkareas?
2217 Buffer * child_buf = *it;
2218 GuiWorkArea * child_wa = workArea(*child_buf);
2220 if (!closeWorkArea(child_wa, true))
2223 theBufferList().releaseChild(&buf, child_buf);
2226 // goto bookmark to update bookmark pit.
2227 //FIXME: we should update only the bookmarks related to this buffer!
2228 LYXERR(Debug::DEBUG, "GuiView::closeBuffer()");
2229 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
2230 theLyXFunc().gotoBookmark(i+1, false, false);
2232 if (saveBufferIfNeeded(buf, false)) {
2233 theBufferList().release(&buf);
2240 bool GuiView::closeTabWorkArea(TabWorkArea * twa)
2242 while (twa == d.currentTabWorkArea()) {
2243 twa->setCurrentIndex(twa->count()-1);
2245 GuiWorkArea * wa = twa->currentWorkArea();
2246 Buffer & b = wa->bufferView().buffer();
2248 // We only want to close the buffer if the same buffer is not visible
2249 // in another view, and if this is not a child and if we are closing
2250 // a view (not a tabgroup).
2251 bool const close_buffer =
2252 !inMultiViews(wa) && !b.parent() && closing_;
2254 if (!closeWorkArea(wa, close_buffer))
2261 bool GuiView::saveBufferIfNeeded(Buffer & buf, bool hiding)
2263 if (buf.isClean() || buf.paragraphs().empty())
2266 // Switch to this Buffer.
2271 if (buf.isUnnamed())
2272 file = from_utf8(buf.fileName().onlyFileName());
2274 file = buf.fileName().displayName(30);
2276 // Bring this window to top before asking questions.
2281 if (hiding && buf.isUnnamed()) {
2282 docstring const text = bformat(_("The document %1$s has not been "
2283 "saved yet.\n\nDo you want to save "
2284 "the document?"), file);
2285 ret = Alert::prompt(_("Save new document?"),
2286 text, 0, 1, _("&Save"), _("&Cancel"));
2290 docstring const text = bformat(_("The document %1$s has unsaved changes."
2291 "\n\nDo you want to save the document or discard the changes?"), file);
2292 ret = Alert::prompt(_("Save changed document?"),
2293 text, 0, 2, _("&Save"), _("&Discard"), _("&Cancel"));
2298 if (!saveBuffer(buf))
2302 // if we crash after this we could
2303 // have no autosave file but I guess
2304 // this is really improbable (Jug)
2305 buf.removeAutosaveFile();
2307 // revert all changes
2308 buf.loadLyXFile(buf.fileName());
2318 bool GuiView::inMultiTabs(GuiWorkArea * wa)
2320 Buffer & buf = wa->bufferView().buffer();
2322 for (int i = 0; i != d.splitter_->count(); ++i) {
2323 GuiWorkArea * wa_ = d.tabWorkArea(i)->workArea(buf);
2324 if (wa_ && wa_ != wa)
2327 return inMultiViews(wa);
2331 bool GuiView::inMultiViews(GuiWorkArea * wa)
2333 QList<int> const ids = guiApp->viewIds();
2334 Buffer & buf = wa->bufferView().buffer();
2337 for (int i = 0; i != ids.size() && found_twa <= 1; ++i) {
2341 if (guiApp->view(ids[i]).workArea(buf))
2348 void GuiView::gotoNextOrPreviousBuffer(NextOrPrevious np)
2350 Buffer * const curbuf = documentBufferView()
2351 ? &documentBufferView()->buffer() : 0;
2352 Buffer * nextbuf = curbuf;
2354 if (np == NEXTBUFFER)
2355 nextbuf = theBufferList().next(nextbuf);
2357 nextbuf = theBufferList().previous(nextbuf);
2358 if (nextbuf == curbuf)
2364 if (workArea(*nextbuf))
2371 /// make sure the document is saved
2372 static bool ensureBufferClean(Buffer * buffer)
2374 LASSERT(buffer, return false);
2375 if (buffer->isClean() && !buffer->isUnnamed())
2378 docstring const file = buffer->fileName().displayName(30);
2381 if (!buffer->isUnnamed()) {
2382 text = bformat(_("The document %1$s has unsaved "
2383 "changes.\n\nDo you want to save "
2384 "the document?"), file);
2385 title = _("Save changed document?");
2388 text = bformat(_("The document %1$s has not been "
2389 "saved yet.\n\nDo you want to save "
2390 "the document?"), file);
2391 title = _("Save new document?");
2393 int const ret = Alert::prompt(title, text, 0, 1, _("&Save"), _("&Cancel"));
2396 dispatch(FuncRequest(LFUN_BUFFER_WRITE));
2398 return buffer->isClean() && !buffer->isUnnamed();
2402 void GuiView::reloadBuffer()
2404 Buffer * buf = &documentBufferView()->buffer();
2409 void GuiView::reloadBuffer(Buffer * buf)
2411 FileName filename = buf->fileName();
2412 Buffer const * master = buf->masterBuffer();
2413 bool const is_child = master != buf;
2414 // The user has already confirmed that the changes, if any, should
2415 // be discarded. So we just release the Buffer and don't call closeBuffer();
2416 theBufferList().release(buf);
2417 buf = loadDocument(filename);
2418 docstring const disp_fn = makeDisplayPath(filename.absFilename());
2421 // re-allocate master if necessary
2422 if (is_child && theBufferList().isLoaded(master)
2423 && buf->masterBuffer() != master)
2424 buf->setParent(master);
2425 buf->updateLabels();
2427 buf->errors("Parse");
2428 str = bformat(_("Document %1$s reloaded."), disp_fn);
2430 str = bformat(_("Could not reload document %1$s"), disp_fn);
2436 void GuiView::checkExternallyModifiedBuffers()
2438 BufferList::iterator bit = theBufferList().begin();
2439 BufferList::iterator const bend = theBufferList().end();
2440 for (; bit != bend; ++bit) {
2441 if ((*bit)->fileName().exists()
2442 && (*bit)->isExternallyModified(Buffer::checksum_method)) {
2443 docstring text = bformat(_("Document \n%1$s\n has been externally modified."
2444 " Reload now? Any local changes will be lost."),
2445 from_utf8((*bit)->absFileName()));
2446 int const ret = Alert::prompt(_("Reload externally changed document?"),
2447 text, 0, 1, _("&Reload"), _("&Cancel"));
2455 void GuiView::dispatchVC(FuncRequest const & cmd)
2457 // message for statusbar
2459 Buffer * buffer = documentBufferView()
2460 ? &(documentBufferView()->buffer()) : 0;
2462 switch (cmd.action) {
2463 case LFUN_VC_REGISTER:
2464 if (!buffer || !ensureBufferClean(buffer))
2466 if (!buffer->lyxvc().inUse()) {
2467 if (buffer->lyxvc().registrer())
2472 case LFUN_VC_CHECK_IN:
2473 if (!buffer || !ensureBufferClean(buffer))
2475 if (buffer->lyxvc().inUse() && !buffer->isReadonly()) {
2476 msg = buffer->lyxvc().checkIn();
2481 case LFUN_VC_CHECK_OUT:
2482 if (!buffer || !ensureBufferClean(buffer))
2484 if (buffer->lyxvc().inUse()) {
2485 msg = buffer->lyxvc().checkOut();
2490 case LFUN_VC_LOCKING_TOGGLE:
2491 LASSERT(buffer, return);
2492 if (!ensureBufferClean(buffer) || buffer->isReadonly())
2494 if (buffer->lyxvc().inUse()) {
2495 string res = buffer->lyxvc().lockingToggle();
2497 frontend::Alert::error(_("Revision control error."),
2498 _("Error when setting the locking property."));
2506 case LFUN_VC_REVERT:
2507 LASSERT(buffer, return);
2508 buffer->lyxvc().revert();
2512 case LFUN_VC_UNDO_LAST:
2513 LASSERT(buffer, return);
2514 buffer->lyxvc().undoLast();
2518 case LFUN_VC_REPO_UPDATE:
2519 LASSERT(buffer, return);
2520 if (ensureBufferClean(buffer)) {
2521 msg = buffer->lyxvc().repoUpdate();
2522 checkExternallyModifiedBuffers();
2526 case LFUN_VC_COMMAND: {
2527 string flag = cmd.getArg(0);
2528 if (buffer && contains(flag, 'R') && !ensureBufferClean(buffer))
2531 if (contains(flag, 'M')) {
2532 if (!Alert::askForText(message, _("LyX VC: Log Message")))
2535 string path = cmd.getArg(1);
2536 if (contains(path, "$$p") && buffer)
2537 path = subst(path, "$$p", buffer->filePath());
2538 LYXERR(Debug::LYXVC, "Directory: " << path);
2540 if (!pp.isReadableDirectory()) {
2541 lyxerr << _("Directory is not accessible.") << endl;
2544 support::PathChanger p(pp);
2546 string command = cmd.getArg(2);
2547 if (command.empty())
2550 command = subst(command, "$$i", buffer->absFileName());
2551 command = subst(command, "$$p", buffer->filePath());
2553 command = subst(command, "$$m", to_utf8(message));
2554 LYXERR(Debug::LYXVC, "Command: " << command);
2556 one.startscript(Systemcall::Wait, command);
2560 if (contains(flag, 'I'))
2561 buffer->markDirty();
2562 if (contains(flag, 'R'))
2572 message(from_utf8(msg));
2576 void GuiView::openChildDocument(string const & fname)
2578 LASSERT(documentBufferView(), return);
2579 Buffer & buffer = documentBufferView()->buffer();
2580 FileName const filename = support::makeAbsPath(fname, buffer.filePath());
2581 documentBufferView()->saveBookmark(false);
2583 bool parsed = false;
2584 if (theBufferList().exists(filename)) {
2585 child = theBufferList().getBuffer(filename);
2587 message(bformat(_("Opening child document %1$s..."),
2588 makeDisplayPath(filename.absFilename())));
2589 child = loadDocument(filename, false);
2595 // Set the parent name of the child document.
2596 // This makes insertion of citations and references in the child work,
2597 // when the target is in the parent or another child document.
2598 child->setParent(&buffer);
2599 child->masterBuffer()->updateLabels();
2602 child->errors("Parse");
2606 bool GuiView::goToFileRow(string const & argument)
2610 size_t i = argument.find_last_of(' ');
2611 if (i != string::npos) {
2612 file_name = os::internal_path(trim(argument.substr(0, i)));
2613 istringstream is(argument.substr(i + 1));
2618 if (i == string::npos) {
2619 LYXERR0("Wrong argument: " << argument);
2623 string const abstmp = package().temp_dir().absFilename();
2624 string const realtmp = package().temp_dir().realPath();
2625 // We have to use os::path_prefix_is() here, instead of
2626 // simply prefixIs(), because the file name comes from
2627 // an external application and may need case adjustment.
2628 if (os::path_prefix_is(file_name, abstmp, os::CASE_ADJUSTED)
2629 || os::path_prefix_is(file_name, realtmp, os::CASE_ADJUSTED)) {
2630 // Needed by inverse dvi search. If it is a file
2631 // in tmpdir, call the apropriated function.
2632 // If tmpdir is a symlink, we may have the real
2633 // path passed back, so we correct for that.
2634 if (!prefixIs(file_name, abstmp))
2635 file_name = subst(file_name, realtmp, abstmp);
2636 buf = theBufferList().getBufferFromTmp(file_name);
2638 // Must replace extension of the file to be .lyx
2639 // and get full path
2640 FileName const s = fileSearch(string(),
2641 support::changeExtension(file_name, ".lyx"), "lyx");
2642 // Either change buffer or load the file
2643 if (theBufferList().exists(s))
2644 buf = theBufferList().getBuffer(s);
2645 else if (s.exists()) {
2646 buf = loadDocument(s);
2647 buf->updateLabels();
2648 buf->errors("Parse");
2651 _("File does not exist: %1$s"),
2652 makeDisplayPath(file_name)));
2657 documentBufferView()->setCursorFromRow(row);
2662 static docstring exportAndDestroy(Buffer * buffer, string const & format)
2664 bool const success = buffer->doExport(format, true);
2667 ? bformat(_("Successful export to format: %1$s"), from_utf8(format))
2668 : bformat(_("Error exporting to format: %1$s"), from_utf8(format));
2672 static docstring previewAndDestroy(Buffer * buffer, string const & format)
2674 bool const success = buffer->preview(format);
2677 ? bformat(_("Successful preview of format: %1$s"), from_utf8(format))
2678 : bformat(_("Error previewing format: %1$s"), from_utf8(format));
2682 bool GuiView::dispatch(FuncRequest const & cmd)
2684 BufferView * bv = currentBufferView();
2685 // By default we won't need any update.
2687 bv->cursor().updateFlags(Update::None);
2689 Buffer * doc_buffer = documentBufferView()
2690 ? &(documentBufferView()->buffer()) : 0;
2692 bool dispatched = true;
2694 if (cmd.origin == FuncRequest::TOC) {
2695 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
2696 toc->doDispatch(bv->cursor(), cmd);
2700 string const argument = to_utf8(cmd.argument());
2702 switch(cmd.action) {
2703 case LFUN_BUFFER_CHILD_OPEN:
2704 openChildDocument(to_utf8(cmd.argument()));
2707 case LFUN_BUFFER_IMPORT:
2708 importDocument(to_utf8(cmd.argument()));
2711 case LFUN_BUFFER_EXPORT: {
2714 if (cmd.argument() == "custom") {
2715 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "sendto"));
2718 if (doc_buffer->doExport(argument, false)) {
2719 message(bformat(_("Error exporting to format: %1$s."),
2725 case LFUN_BUFFER_UPDATE: {
2728 string format = argument;
2729 if (argument.empty())
2730 format = doc_buffer->getDefaultOutputFormat();
2731 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
2732 ProgressInterface::instance()->clearMessages();
2733 ProgressInterface::instance()->appendMessage("Exporting ...");
2734 QFuture<docstring> f = QtConcurrent::run(exportAndDestroy,
2735 doc_buffer->clone(), format);
2736 d.setPreviewFuture(f);
2738 doc_buffer->doExport(format, true);
2742 case LFUN_BUFFER_VIEW: {
2745 string format = argument;
2746 if (argument.empty())
2747 format = doc_buffer->getDefaultOutputFormat();
2748 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
2749 ProgressInterface::instance()->clearMessages();
2750 ProgressInterface::instance()->appendMessage("Previewing ...");
2751 QFuture<docstring> f = QtConcurrent::run(previewAndDestroy,
2752 doc_buffer->clone(), format);
2753 d.setPreviewFuture(f);
2755 doc_buffer->preview(format);
2759 case LFUN_MASTER_BUFFER_UPDATE: {
2762 string format = argument;
2763 Buffer const * master = doc_buffer->masterBuffer();
2764 if (argument.empty())
2765 format = master->getDefaultOutputFormat();
2766 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
2767 QFuture<docstring> f = QtConcurrent::run(exportAndDestroy,
2768 master->clone(), format);
2769 d.setPreviewFuture(f);
2771 master->doExport(format, true);
2775 case LFUN_MASTER_BUFFER_VIEW: {
2776 string format = argument;
2777 Buffer const * master = doc_buffer->masterBuffer();
2778 if (argument.empty())
2779 format = master->getDefaultOutputFormat();
2780 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
2781 QFuture<docstring> f = QtConcurrent::run(previewAndDestroy,
2782 master->clone(), format);
2783 d.setPreviewFuture(f);
2785 master->preview(format);
2789 case LFUN_BUFFER_SWITCH:
2790 if (FileName::isAbsolute(to_utf8(cmd.argument()))) {
2792 theBufferList().getBuffer(FileName(to_utf8(cmd.argument())));
2796 message(_("Document not loaded"));
2800 case LFUN_BUFFER_NEXT:
2801 gotoNextOrPreviousBuffer(NEXTBUFFER);
2804 case LFUN_BUFFER_PREVIOUS:
2805 gotoNextOrPreviousBuffer(PREVBUFFER);
2808 case LFUN_COMMAND_EXECUTE: {
2809 bool const show_it = cmd.argument() != "off";
2810 // FIXME: this is a hack, "minibuffer" should not be
2812 if (GuiToolbar * t = toolbar("minibuffer")) {
2813 t->setVisible(show_it);
2814 if (show_it && t->commandBuffer())
2815 t->commandBuffer()->setFocus();
2819 case LFUN_DROP_LAYOUTS_CHOICE:
2820 d.layout_->showPopup();
2823 case LFUN_MENU_OPEN:
2824 if (QMenu * menu = guiApp->menus().menu(toqstr(cmd.argument()), *this))
2825 menu->exec(QCursor::pos());
2828 case LFUN_FILE_INSERT:
2829 insertLyXFile(cmd.argument());
2831 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
2832 insertPlaintextFile(cmd.argument(), true);
2835 case LFUN_FILE_INSERT_PLAINTEXT:
2836 insertPlaintextFile(cmd.argument(), false);
2839 case LFUN_BUFFER_RELOAD: {
2840 LASSERT(doc_buffer, break);
2841 docstring const file = makeDisplayPath(doc_buffer->absFileName(), 20);
2842 docstring text = bformat(_("Any changes will be lost. Are you sure "
2843 "you want to revert to the saved version of the document %1$s?"), file);
2844 int const ret = Alert::prompt(_("Revert to saved document?"),
2845 text, 1, 1, _("&Revert"), _("&Cancel"));
2848 doc_buffer->markClean();
2854 case LFUN_BUFFER_WRITE:
2855 LASSERT(doc_buffer, break);
2856 saveBuffer(*doc_buffer);
2859 case LFUN_BUFFER_WRITE_AS:
2860 LASSERT(doc_buffer, break);
2861 renameBuffer(*doc_buffer, cmd.argument());
2864 case LFUN_BUFFER_WRITE_ALL: {
2865 Buffer * first = theBufferList().first();
2868 message(_("Saving all documents..."));
2869 // We cannot use a for loop as the buffer list cycles.
2872 if (!b->isClean()) {
2874 LYXERR(Debug::ACTION, "Saved " << b->absFileName());
2876 b = theBufferList().next(b);
2877 } while (b != first);
2878 message(_("All documents saved."));
2882 case LFUN_BUFFER_CLOSE:
2886 case LFUN_BUFFER_CLOSE_ALL:
2890 case LFUN_TOOLBAR_TOGGLE: {
2891 string const name = cmd.getArg(0);
2892 if (GuiToolbar * t = toolbar(name))
2897 case LFUN_DIALOG_UPDATE: {
2898 string const name = to_utf8(cmd.argument());
2899 if (currentBufferView()) {
2900 Inset * inset = currentBufferView()->editedInset(name);
2901 // Can only update a dialog connected to an existing inset
2904 // FIXME: get rid of this indirection; GuiView ask the inset
2905 // if he is kind enough to update itself...
2906 FuncRequest fr(LFUN_INSET_DIALOG_UPDATE, cmd.argument());
2907 inset->dispatch(currentBufferView()->cursor(), fr);
2908 } else if (name == "paragraph") {
2909 lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
2910 } else if (name == "prefs" || name == "document") {
2911 updateDialog(name, string());
2916 case LFUN_DIALOG_TOGGLE: {
2917 if (isDialogVisible(cmd.getArg(0)))
2918 dispatch(FuncRequest(LFUN_DIALOG_HIDE, cmd.argument()));
2920 dispatch(FuncRequest(LFUN_DIALOG_SHOW, cmd.argument()));
2924 case LFUN_DIALOG_DISCONNECT_INSET:
2925 disconnectDialog(to_utf8(cmd.argument()));
2928 case LFUN_DIALOG_HIDE: {
2929 guiApp->hideDialogs(to_utf8(cmd.argument()), 0);
2933 case LFUN_DIALOG_SHOW: {
2934 string const name = cmd.getArg(0);
2935 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
2937 if (name == "character") {
2938 data = freefont2string();
2940 showDialog("character", data);
2941 } else if (name == "latexlog") {
2942 Buffer::LogType type;
2943 string const logfile = doc_buffer->logName(&type);
2945 case Buffer::latexlog:
2948 case Buffer::buildlog:
2952 data += Lexer::quoteString(logfile);
2953 showDialog("log", data);
2954 } else if (name == "vclog") {
2955 string const data = "vc " +
2956 Lexer::quoteString(doc_buffer->lyxvc().getLogFile());
2957 showDialog("log", data);
2958 } else if (name == "symbols") {
2959 data = bv->cursor().getEncoding()->name();
2961 showDialog("symbols", data);
2963 } else if (name == "prefs" && isFullScreen()) {
2964 FuncRequest fr(LFUN_INSET_INSERT, "fullscreen");
2966 showDialog("prefs", data);
2968 showDialog(name, data);
2973 message(cmd.argument());
2976 case LFUN_UI_TOGGLE:
2978 // Make sure the keyboard focus stays in the work area.
2982 case LFUN_SPLIT_VIEW: {
2983 LASSERT(doc_buffer, break);
2984 string const orientation = cmd.getArg(0);
2985 d.splitter_->setOrientation(orientation == "vertical"
2986 ? Qt::Vertical : Qt::Horizontal);
2987 TabWorkArea * twa = addTabWorkArea();
2988 GuiWorkArea * wa = twa->addWorkArea(*doc_buffer, *this);
2989 setCurrentWorkArea(wa);
2992 case LFUN_CLOSE_TAB_GROUP:
2993 if (TabWorkArea * twa = d.currentTabWorkArea()) {
2994 closeTabWorkArea(twa);
2995 d.current_work_area_ = 0;
2996 twa = d.currentTabWorkArea();
2997 // Switch to the next GuiWorkArea in the found TabWorkArea.
2999 // Make sure the work area is up to date.
3000 setCurrentWorkArea(twa->currentWorkArea());
3002 setCurrentWorkArea(0);
3007 case LFUN_COMPLETION_INLINE:
3008 if (d.current_work_area_)
3009 d.current_work_area_->completer().showInline();
3012 case LFUN_COMPLETION_POPUP:
3013 if (d.current_work_area_)
3014 d.current_work_area_->completer().showPopup();
3018 case LFUN_COMPLETION_COMPLETE:
3019 if (d.current_work_area_)
3020 d.current_work_area_->completer().tab();
3023 case LFUN_COMPLETION_CANCEL:
3024 if (d.current_work_area_) {
3025 if (d.current_work_area_->completer().popupVisible())
3026 d.current_work_area_->completer().hidePopup();
3028 d.current_work_area_->completer().hideInline();
3032 case LFUN_COMPLETION_ACCEPT:
3033 if (d.current_work_area_)
3034 d.current_work_area_->completer().activate();
3037 case LFUN_BUFFER_ZOOM_IN:
3038 case LFUN_BUFFER_ZOOM_OUT:
3039 if (cmd.argument().empty()) {
3040 if (cmd.action == LFUN_BUFFER_ZOOM_IN)
3045 lyxrc.zoom += convert<int>(cmd.argument());
3047 if (lyxrc.zoom < 10)
3050 // The global QPixmapCache is used in GuiPainter to cache text
3051 // painting so we must reset it.
3052 QPixmapCache::clear();
3053 guiApp->fontLoader().update();
3054 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
3057 case LFUN_VC_REGISTER:
3058 case LFUN_VC_CHECK_IN:
3059 case LFUN_VC_CHECK_OUT:
3060 case LFUN_VC_REPO_UPDATE:
3061 case LFUN_VC_LOCKING_TOGGLE:
3062 case LFUN_VC_REVERT:
3063 case LFUN_VC_UNDO_LAST:
3064 case LFUN_VC_COMMAND:
3068 case LFUN_SERVER_GOTO_FILE_ROW:
3069 goToFileRow(to_utf8(cmd.argument()));
3077 // Part of automatic menu appearance feature.
3078 if (isFullScreen()) {
3079 if (menuBar()->isVisible() && lyxrc.full_screen_menubar)
3081 if (statusBar()->isVisible())
3082 statusBar()->hide();
3089 void GuiView::lfunUiToggle(FuncRequest const & cmd)
3091 string const arg = cmd.getArg(0);
3092 if (arg == "scrollbar") {
3093 // hide() is of no help
3094 if (d.current_work_area_->verticalScrollBarPolicy() ==
3095 Qt::ScrollBarAlwaysOff)
3097 d.current_work_area_->setVerticalScrollBarPolicy(
3098 Qt::ScrollBarAsNeeded);
3100 d.current_work_area_->setVerticalScrollBarPolicy(
3101 Qt::ScrollBarAlwaysOff);
3104 if (arg == "statusbar") {
3105 statusBar()->setVisible(!statusBar()->isVisible());
3108 if (arg == "menubar") {
3109 menuBar()->setVisible(!menuBar()->isVisible());
3112 #if QT_VERSION >= 0x040300
3113 if (arg == "frame") {
3115 getContentsMargins(&l, &t, &r, &b);
3116 //are the frames in default state?
3117 d.current_work_area_->setFrameStyle(QFrame::NoFrame);
3119 setContentsMargins(-2, -2, -2, -2);
3121 setContentsMargins(0, 0, 0, 0);
3126 if (arg == "fullscreen") {
3131 message(bformat("LFUN_UI_TOGGLE " + _("%1$s unknown command!"), from_utf8(arg)));
3135 void GuiView::toggleFullScreen()
3137 if (isFullScreen()) {
3138 for (int i = 0; i != d.splitter_->count(); ++i)
3139 d.tabWorkArea(i)->setFullScreen(false);
3140 #if QT_VERSION >= 0x040300
3141 setContentsMargins(0, 0, 0, 0);
3143 setWindowState(windowState() ^ Qt::WindowFullScreen);
3146 statusBar()->show();
3149 hideDialogs("prefs", 0);
3150 for (int i = 0; i != d.splitter_->count(); ++i)
3151 d.tabWorkArea(i)->setFullScreen(true);
3152 #if QT_VERSION >= 0x040300
3153 setContentsMargins(-2, -2, -2, -2);
3156 setWindowState(windowState() ^ Qt::WindowFullScreen);
3157 statusBar()->hide();
3158 if (lyxrc.full_screen_menubar)
3160 if (lyxrc.full_screen_toolbars) {
3161 ToolbarMap::iterator end = d.toolbars_.end();
3162 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
3167 // give dialogs like the TOC a chance to adapt
3172 Buffer const * GuiView::updateInset(Inset const * inset)
3174 if (!d.current_work_area_)
3178 d.current_work_area_->scheduleRedraw();
3180 return &d.current_work_area_->bufferView().buffer();
3184 void GuiView::restartCursor()
3186 /* When we move around, or type, it's nice to be able to see
3187 * the cursor immediately after the keypress.
3189 if (d.current_work_area_)
3190 d.current_work_area_->startBlinkingCursor();
3192 // Take this occasion to update the other GUI elements.
3198 void GuiView::updateCompletion(Cursor & cur, bool start, bool keep)
3200 if (d.current_work_area_)
3201 d.current_work_area_->completer().updateVisibility(cur, start, keep);
3206 // This list should be kept in sync with the list of insets in
3207 // src/insets/Inset.cpp. I.e., if a dialog goes with an inset, the
3208 // dialog should have the same name as the inset.
3209 // Changes should be also recorded in LFUN_DIALOG_SHOW doxygen
3210 // docs in LyXAction.cpp.
3212 char const * const dialognames[] = {
3213 "aboutlyx", "bibitem", "bibtex", "box", "branch", "changes", "character",
3214 "citation", "compare", "document", "errorlist", "ert", "external", "file",
3215 "findreplace", "findreplaceadv", "float", "graphics", "href", "include",
3216 "index", "index_print", "info", "listings", "label", "log", "mathdelimiter",
3217 "mathmatrix", "mathspace", "nomenclature", "nomencl_print", "note",
3218 "paragraph", "phantom", "prefs", "print", "ref", "sendto", "space",
3219 "spellchecker", "symbols", "tabular", "tabularcreate", "thesaurus", "texinfo",
3220 "toc", "view-source", "vspace", "wrap", "progress"};
3222 char const * const * const end_dialognames =
3223 dialognames + (sizeof(dialognames) / sizeof(char *));
3227 cmpCStr(char const * name) : name_(name) {}
3228 bool operator()(char const * other) {
3229 return strcmp(other, name_) == 0;
3236 bool isValidName(string const & name)
3238 return find_if(dialognames, end_dialognames,
3239 cmpCStr(name.c_str())) != end_dialognames;
3245 void GuiView::resetDialogs()
3247 // Make sure that no LFUN uses any LyXView.
3248 guiApp->setCurrentView(0);
3251 constructToolbars();
3252 guiApp->menus().fillMenuBar(menuBar(), this, false);
3253 d.layout_->updateContents(true);
3254 // Now update controls with current buffer.
3255 guiApp->setCurrentView(this);
3261 Dialog * GuiView::findOrBuild(string const & name, bool hide_it)
3263 if (!isValidName(name))
3266 map<string, DialogPtr>::iterator it = d.dialogs_.find(name);
3268 if (it != d.dialogs_.end()) {
3270 it->second->hideView();
3271 return it->second.get();
3274 Dialog * dialog = build(name);
3275 d.dialogs_[name].reset(dialog);
3276 if (lyxrc.allow_geometry_session)
3277 dialog->restoreSession();
3284 void GuiView::showDialog(string const & name, string const & data,
3287 triggerShowDialog(toqstr(name), toqstr(data), inset);
3291 void GuiView::doShowDialog(QString const & qname, QString const & qdata,
3297 const string name = fromqstr(qname);
3298 const string data = fromqstr(qdata);
3302 Dialog * dialog = findOrBuild(name, false);
3304 dialog->showData(data);
3305 if (inset && currentBufferView())
3306 currentBufferView()->editInset(name, inset);
3309 catch (ExceptionMessage const & ex) {
3317 bool GuiView::isDialogVisible(string const & name) const
3319 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3320 if (it == d.dialogs_.end())
3322 return it->second.get()->isVisibleView() && !it->second.get()->isClosing();
3326 void GuiView::hideDialog(string const & name, Inset * inset)
3328 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3329 if (it == d.dialogs_.end())
3332 if (inset && currentBufferView()
3333 && inset != currentBufferView()->editedInset(name))
3336 Dialog * const dialog = it->second.get();
3337 if (dialog->isVisibleView())
3339 if (currentBufferView())
3340 currentBufferView()->editInset(name, 0);
3344 void GuiView::disconnectDialog(string const & name)
3346 if (!isValidName(name))
3348 if (currentBufferView())
3349 currentBufferView()->editInset(name, 0);
3353 void GuiView::hideAll() const
3355 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
3356 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3358 for(; it != end; ++it)
3359 it->second->hideView();
3363 void GuiView::updateDialogs()
3365 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
3366 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3368 for(; it != end; ++it) {
3369 Dialog * dialog = it->second.get();
3370 if (dialog && dialog->isVisibleView())
3371 dialog->checkStatus();
3378 // will be replaced by a proper factory...
3379 Dialog * createGuiAbout(GuiView & lv);
3380 Dialog * createGuiBibitem(GuiView & lv);
3381 Dialog * createGuiBibtex(GuiView & lv);
3382 Dialog * createGuiBox(GuiView & lv);
3383 Dialog * createGuiBranch(GuiView & lv);
3384 Dialog * createGuiChanges(GuiView & lv);
3385 Dialog * createGuiCharacter(GuiView & lv);
3386 Dialog * createGuiCitation(GuiView & lv);
3387 Dialog * createGuiCompare(GuiView & lv);
3388 Dialog * createGuiDelimiter(GuiView & lv);
3389 Dialog * createGuiDocument(GuiView & lv);
3390 Dialog * createGuiErrorList(GuiView & lv);
3391 Dialog * createGuiERT(GuiView & lv);
3392 Dialog * createGuiExternal(GuiView & lv);
3393 Dialog * createGuiFloat(GuiView & lv);
3394 Dialog * createGuiGraphics(GuiView & lv);
3395 Dialog * createGuiInclude(GuiView & lv);
3396 Dialog * createGuiIndex(GuiView & lv);
3397 Dialog * createGuiInfo(GuiView & lv);
3398 Dialog * createGuiLabel(GuiView & lv);
3399 Dialog * createGuiListings(GuiView & lv);
3400 Dialog * createGuiLog(GuiView & lv);
3401 Dialog * createGuiMathHSpace(GuiView & lv);
3402 Dialog * createGuiMathMatrix(GuiView & lv);
3403 Dialog * createGuiNomenclature(GuiView & lv);
3404 Dialog * createGuiNote(GuiView & lv);
3405 Dialog * createGuiParagraph(GuiView & lv);
3406 Dialog * createGuiPhantom(GuiView & lv);
3407 Dialog * createGuiPreferences(GuiView & lv);
3408 Dialog * createGuiPrint(GuiView & lv);
3409 Dialog * createGuiPrintindex(GuiView & lv);
3410 Dialog * createGuiPrintNomencl(GuiView & lv);
3411 Dialog * createGuiRef(GuiView & lv);
3412 Dialog * createGuiSearch(GuiView & lv);
3413 Dialog * createGuiSearchAdv(GuiView & lv);
3414 Dialog * createGuiSendTo(GuiView & lv);
3415 Dialog * createGuiShowFile(GuiView & lv);
3416 Dialog * createGuiSpellchecker(GuiView & lv);
3417 Dialog * createGuiSymbols(GuiView & lv);
3418 Dialog * createGuiTabularCreate(GuiView & lv);
3419 Dialog * createGuiTabular(GuiView & lv);
3420 Dialog * createGuiTexInfo(GuiView & lv);
3421 Dialog * createGuiTextHSpace(GuiView & lv);
3422 Dialog * createGuiToc(GuiView & lv);
3423 Dialog * createGuiThesaurus(GuiView & lv);
3424 Dialog * createGuiHyperlink(GuiView & lv);
3425 Dialog * createGuiVSpace(GuiView & lv);
3426 Dialog * createGuiViewSource(GuiView & lv);
3427 Dialog * createGuiWrap(GuiView & lv);
3428 Dialog * createGuiProgressView(GuiView & lv);
3432 Dialog * GuiView::build(string const & name)
3434 LASSERT(isValidName(name), return 0);
3436 if (name == "aboutlyx")
3437 return createGuiAbout(*this);
3438 if (name == "bibitem")
3439 return createGuiBibitem(*this);
3440 if (name == "bibtex")
3441 return createGuiBibtex(*this);
3443 return createGuiBox(*this);
3444 if (name == "branch")
3445 return createGuiBranch(*this);
3446 if (name == "changes")
3447 return createGuiChanges(*this);
3448 if (name == "character")
3449 return createGuiCharacter(*this);
3450 if (name == "citation")
3451 return createGuiCitation(*this);
3452 if (name == "compare")
3453 return createGuiCompare(*this);
3454 if (name == "document")
3455 return createGuiDocument(*this);
3456 if (name == "errorlist")
3457 return createGuiErrorList(*this);
3459 return createGuiERT(*this);
3460 if (name == "external")
3461 return createGuiExternal(*this);
3463 return createGuiShowFile(*this);
3464 if (name == "findreplace")
3465 return createGuiSearch(*this);
3466 if (name == "findreplaceadv")
3467 return createGuiSearchAdv(*this);
3468 if (name == "float")
3469 return createGuiFloat(*this);
3470 if (name == "graphics")
3471 return createGuiGraphics(*this);
3473 return createGuiHyperlink(*this);
3474 if (name == "include")
3475 return createGuiInclude(*this);
3476 if (name == "index")
3477 return createGuiIndex(*this);
3478 if (name == "index_print")
3479 return createGuiPrintindex(*this);
3481 return createGuiInfo(*this);
3482 if (name == "label")
3483 return createGuiLabel(*this);
3484 if (name == "listings")
3485 return createGuiListings(*this);
3487 return createGuiLog(*this);
3488 if (name == "mathdelimiter")
3489 return createGuiDelimiter(*this);
3490 if (name == "mathspace")
3491 return createGuiMathHSpace(*this);
3492 if (name == "mathmatrix")
3493 return createGuiMathMatrix(*this);
3494 if (name == "nomenclature")
3495 return createGuiNomenclature(*this);
3496 if (name == "nomencl_print")
3497 return createGuiPrintNomencl(*this);
3499 return createGuiNote(*this);
3500 if (name == "paragraph")
3501 return createGuiParagraph(*this);
3502 if (name == "phantom")
3503 return createGuiPhantom(*this);
3504 if (name == "prefs")
3505 return createGuiPreferences(*this);
3506 if (name == "print")
3507 return createGuiPrint(*this);
3509 return createGuiRef(*this);
3510 if (name == "sendto")
3511 return createGuiSendTo(*this);
3512 if (name == "space")
3513 return createGuiTextHSpace(*this);
3514 if (name == "spellchecker")
3515 return createGuiSpellchecker(*this);
3516 if (name == "symbols")
3517 return createGuiSymbols(*this);
3518 if (name == "tabular")
3519 return createGuiTabular(*this);
3520 if (name == "tabularcreate")
3521 return createGuiTabularCreate(*this);
3522 if (name == "texinfo")
3523 return createGuiTexInfo(*this);
3524 if (name == "thesaurus")
3525 return createGuiThesaurus(*this);
3527 return createGuiToc(*this);
3528 if (name == "view-source")
3529 return createGuiViewSource(*this);
3530 if (name == "vspace")
3531 return createGuiVSpace(*this);
3533 return createGuiWrap(*this);
3534 if (name == "progress")
3535 return createGuiProgressView(*this);
3541 } // namespace frontend
3544 #include "moc_GuiView.cpp"