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()
747 d.statusbar_timer_.stop();
751 void GuiView::updateWindowTitle(GuiWorkArea * wa)
753 if (wa != d.current_work_area_)
755 setWindowTitle(qt_("LyX: ") + wa->windowTitle());
756 setWindowIconText(wa->windowIconText());
760 void GuiView::on_currentWorkAreaChanged(GuiWorkArea * wa)
763 disconnectBufferView();
764 connectBufferView(wa->bufferView());
765 connectBuffer(wa->bufferView().buffer());
766 d.current_work_area_ = wa;
767 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
768 this, SLOT(updateWindowTitle(GuiWorkArea *)));
769 updateWindowTitle(wa);
773 // The document settings needs to be reinitialised.
774 updateDialog("document", "");
776 // Buffer-dependent dialogs must be updated. This is done here because
777 // some dialogs require buffer()->text.
782 void GuiView::on_lastWorkAreaRemoved()
785 // We already are in a close event. Nothing more to do.
788 if (d.splitter_->count() > 1)
789 // We have a splitter so don't close anything.
792 // Reset and updates the dialogs.
793 d.toc_models_.reset(0);
794 updateDialog("document", "");
797 resetWindowTitleAndIconText();
799 if (lyxrc.open_buffers_in_tabs)
800 // Nothing more to do, the window should stay open.
803 if (guiApp->viewIds().size() > 1) {
809 // On Mac we also close the last window because the application stay
810 // resident in memory. On other platforms we don't close the last
811 // window because this would quit the application.
817 void GuiView::updateStatusBar()
819 // let the user see the explicit message
820 if (d.statusbar_timer_.isActive())
827 void GuiView::showMessage()
829 QString msg = toqstr(theGuiApp()->viewStatusMessage());
831 BufferView const * bv = currentBufferView();
833 msg = toqstr(bv->cursor().currentState());
835 msg = qt_("Welcome to LyX!");
837 statusBar()->showMessage(msg);
841 bool GuiView::event(QEvent * e)
845 // Useful debug code:
846 //case QEvent::ActivationChange:
847 //case QEvent::WindowDeactivate:
848 //case QEvent::Paint:
849 //case QEvent::Enter:
850 //case QEvent::Leave:
851 //case QEvent::HoverEnter:
852 //case QEvent::HoverLeave:
853 //case QEvent::HoverMove:
854 //case QEvent::StatusTip:
855 //case QEvent::DragEnter:
856 //case QEvent::DragLeave:
860 case QEvent::WindowActivate: {
861 GuiView * old_view = guiApp->currentView();
862 if (this == old_view) {
864 return QMainWindow::event(e);
866 if (old_view && old_view->currentBufferView()) {
867 // save current selection to the selection buffer to allow
868 // middle-button paste in this window.
869 cap::saveSelection(old_view->currentBufferView()->cursor());
871 guiApp->setCurrentView(this);
872 if (d.current_work_area_) {
873 BufferView & bv = d.current_work_area_->bufferView();
874 connectBufferView(bv);
875 connectBuffer(bv.buffer());
876 // The document structure, name and dialogs might have
877 // changed in another view.
879 // The document settings needs to be reinitialised.
880 updateDialog("document", "");
883 resetWindowTitleAndIconText();
886 return QMainWindow::event(e);
889 case QEvent::ShortcutOverride: {
892 #if (!defined Q_WS_X11) || (QT_VERSION >= 0x040500)
893 if (isFullScreen() && menuBar()->isHidden()) {
894 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
895 // FIXME: we should also try to detect special LyX shortcut such as
896 // Alt-P and Alt-M. Right now there is a hack in
897 // GuiWorkArea::processKeySym() that hides again the menubar for
899 if (ke->modifiers() & Qt::AltModifier && ke->key() != Qt::Key_Alt) {
901 return QMainWindow::event(e);
906 if (d.current_work_area_)
907 // Nothing special to do.
908 return QMainWindow::event(e);
910 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
911 // Let Qt handle menu access and the Tab keys to navigate keys to navigate
913 if (ke->modifiers() & Qt::AltModifier || ke->key() == Qt::Key_Tab
914 || ke->key() == Qt::Key_Backtab)
915 return QMainWindow::event(e);
917 // Allow processing of shortcuts that are allowed even when no Buffer
920 setKeySymbol(&sym, ke);
921 guiApp->processKeySym(sym, q_key_state(ke->modifiers()));
927 return QMainWindow::event(e);
931 void GuiView::resetWindowTitleAndIconText()
933 setWindowTitle(qt_("LyX"));
934 setWindowIconText(qt_("LyX"));
937 bool GuiView::focusNextPrevChild(bool /*next*/)
944 void GuiView::setBusy(bool busy)
946 if (d.current_work_area_) {
947 d.current_work_area_->setUpdatesEnabled(!busy);
949 d.current_work_area_->stopBlinkingCursor();
951 d.current_work_area_->startBlinkingCursor();
955 QApplication::setOverrideCursor(Qt::WaitCursor);
957 QApplication::restoreOverrideCursor();
961 GuiWorkArea * GuiView::workArea(Buffer & buffer)
963 if (currentWorkArea()
964 && ¤tWorkArea()->bufferView().buffer() == &buffer)
965 return (GuiWorkArea *) currentWorkArea();
966 if (TabWorkArea * twa = d.currentTabWorkArea())
967 return twa->workArea(buffer);
972 GuiWorkArea * GuiView::addWorkArea(Buffer & buffer)
974 // Automatically create a TabWorkArea if there are none yet.
975 TabWorkArea * tab_widget = d.splitter_->count()
976 ? d.currentTabWorkArea() : addTabWorkArea();
977 return tab_widget->addWorkArea(buffer, *this);
981 TabWorkArea * GuiView::addTabWorkArea()
983 TabWorkArea * twa = new TabWorkArea;
984 QObject::connect(twa, SIGNAL(currentWorkAreaChanged(GuiWorkArea *)),
985 this, SLOT(on_currentWorkAreaChanged(GuiWorkArea *)));
986 QObject::connect(twa, SIGNAL(lastWorkAreaRemoved()),
987 this, SLOT(on_lastWorkAreaRemoved()));
989 d.splitter_->addWidget(twa);
990 d.stack_widget_->setCurrentWidget(d.splitter_);
995 GuiWorkArea const * GuiView::currentWorkArea() const
997 return d.current_work_area_;
1001 GuiWorkArea * GuiView::currentWorkArea()
1003 return d.current_work_area_;
1007 GuiWorkArea const * GuiView::currentMainWorkArea() const
1009 if (d.currentTabWorkArea() == NULL)
1011 return d.currentTabWorkArea()->currentWorkArea();
1015 GuiWorkArea * GuiView::currentMainWorkArea()
1017 if (d.currentTabWorkArea() == NULL)
1019 return d.currentTabWorkArea()->currentWorkArea();
1023 void GuiView::setCurrentWorkArea(GuiWorkArea * wa)
1025 LYXERR(Debug::DEBUG, "Setting current wa: " << wa << endl);
1027 d.current_work_area_ = NULL;
1031 GuiWorkArea * old_gwa = theGuiApp()->currentView()->currentWorkArea();
1035 if (currentBufferView())
1036 cap::saveSelection(currentBufferView()->cursor());
1038 theGuiApp()->setCurrentView(this);
1039 d.current_work_area_ = wa;
1040 for (int i = 0; i != d.splitter_->count(); ++i) {
1041 if (d.tabWorkArea(i)->setCurrentWorkArea(wa)) {
1042 //if (d.current_main_work_area_)
1043 // d.current_main_work_area_->setFrameStyle(QFrame::NoFrame);
1044 d.current_main_work_area_ = wa;
1045 //d.current_main_work_area_->setFrameStyle(QFrame::Box | QFrame::Plain);
1046 //d.current_main_work_area_->setLineWidth(2);
1047 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() << ", Current main wa: " << currentMainWorkArea());
1051 LYXERR(Debug::DEBUG, "This is not a tabbed wa");
1052 on_currentWorkAreaChanged(wa);
1053 BufferView & bv = wa->bufferView();
1054 bv.cursor().fixIfBroken();
1056 wa->setUpdatesEnabled(true);
1057 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() << ", Current main wa: " << currentMainWorkArea());
1061 void GuiView::removeWorkArea(GuiWorkArea * wa)
1063 LASSERT(wa, return);
1064 if (wa == d.current_work_area_) {
1066 disconnectBufferView();
1067 d.current_work_area_ = 0;
1068 d.current_main_work_area_ = 0;
1071 bool found_twa = false;
1072 for (int i = 0; i != d.splitter_->count(); ++i) {
1073 TabWorkArea * twa = d.tabWorkArea(i);
1074 if (twa->removeWorkArea(wa)) {
1075 // Found in this tab group, and deleted the GuiWorkArea.
1077 if (twa->count() != 0) {
1078 if (d.current_work_area_ == 0)
1079 // This means that we are closing the current GuiWorkArea, so
1080 // switch to the next GuiWorkArea in the found TabWorkArea.
1081 setCurrentWorkArea(twa->currentWorkArea());
1083 // No more WorkAreas in this tab group, so delete it.
1090 // It is not a tabbed work area (i.e., the search work area), so it
1091 // should be deleted by other means.
1092 LASSERT(found_twa, /* */);
1094 if (d.current_work_area_ == 0) {
1095 if (d.splitter_->count() != 0) {
1096 TabWorkArea * twa = d.currentTabWorkArea();
1097 setCurrentWorkArea(twa->currentWorkArea());
1099 // No more work areas, switch to the background widget.
1100 setCurrentWorkArea(0);
1106 LayoutBox * GuiView::getLayoutDialog() const
1112 void GuiView::updateLayoutList()
1115 d.layout_->updateContents(false);
1119 void GuiView::updateToolbars()
1121 ToolbarMap::iterator end = d.toolbars_.end();
1122 if (d.current_work_area_) {
1124 d.current_work_area_->bufferView().cursor().inMathed();
1126 lyx::getStatus(FuncRequest(LFUN_LAYOUT_TABULAR)).enabled();
1128 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).enabled() &&
1129 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).onoff(true);
1130 bool const mathmacrotemplate =
1131 lyx::getStatus(FuncRequest(LFUN_IN_MATHMACROTEMPLATE)).enabled();
1133 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1134 it->second->update(math, table, review, mathmacrotemplate);
1136 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1137 it->second->update(false, false, false, false);
1141 void GuiView::setBuffer(Buffer * newBuffer)
1143 LYXERR(Debug::DEBUG, "Setting buffer: " << newBuffer << endl);
1144 LASSERT(newBuffer, return);
1147 GuiWorkArea * wa = workArea(*newBuffer);
1149 newBuffer->masterBuffer()->updateLabels();
1150 wa = addWorkArea(*newBuffer);
1152 //Disconnect the old buffer...there's no new one.
1155 connectBuffer(*newBuffer);
1156 connectBufferView(wa->bufferView());
1157 setCurrentWorkArea(wa);
1163 void GuiView::connectBuffer(Buffer & buf)
1165 buf.setGuiDelegate(this);
1169 void GuiView::disconnectBuffer()
1171 if (d.current_work_area_)
1172 d.current_work_area_->bufferView().buffer().setGuiDelegate(0);
1176 void GuiView::connectBufferView(BufferView & bv)
1178 bv.setGuiDelegate(this);
1182 void GuiView::disconnectBufferView()
1184 if (d.current_work_area_)
1185 d.current_work_area_->bufferView().setGuiDelegate(0);
1189 void GuiView::errors(string const & error_type, bool from_master)
1191 ErrorList & el = from_master ?
1192 documentBufferView()->buffer().masterBuffer()->errorList(error_type)
1193 : documentBufferView()->buffer().errorList(error_type);
1194 string data = error_type;
1196 data = "from_master|" + error_type;
1198 showDialog("errorlist", data);
1202 void GuiView::updateTocItem(string const & type, DocIterator const & dit)
1204 d.toc_models_.updateItem(toqstr(type), dit);
1208 void GuiView::structureChanged()
1210 d.toc_models_.reset(documentBufferView());
1211 // Navigator needs more than a simple update in this case. It needs to be
1213 updateDialog("toc", "");
1217 void GuiView::updateDialog(string const & name, string const & data)
1219 if (!isDialogVisible(name))
1222 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
1223 if (it == d.dialogs_.end())
1226 Dialog * const dialog = it->second.get();
1227 if (dialog->isVisibleView())
1228 dialog->initialiseParams(data);
1232 BufferView * GuiView::documentBufferView()
1234 return currentMainWorkArea()
1235 ? ¤tMainWorkArea()->bufferView()
1240 BufferView const * GuiView::documentBufferView() const
1242 return currentMainWorkArea()
1243 ? ¤tMainWorkArea()->bufferView()
1248 BufferView * GuiView::currentBufferView()
1250 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1254 BufferView const * GuiView::currentBufferView() const
1256 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1260 static docstring saveAndDestroyBuffer(Buffer * buffer, FileName const & fname)
1263 FileName const tmp_ret = FileName::tempName("lyxauto");
1264 if (!tmp_ret.empty()) {
1265 if (buffer->writeFile(tmp_ret))
1266 failed = !tmp_ret.moveTo(fname);
1269 // failed to write/rename tmp_ret so try writing direct
1270 failed = buffer->writeFile(fname);
1274 ? _("Automatic save failed!")
1275 : _("Automatic save done.");
1279 void GuiView::autoSave()
1281 LYXERR(Debug::INFO, "Running autoSave()");
1283 Buffer * buffer = documentBufferView()
1284 ? &documentBufferView()->buffer() : 0;
1288 #if (QT_VERSION >= 0x040400)
1289 QFuture<docstring> f = QtConcurrent::run(saveAndDestroyBuffer, buffer->clone(),
1290 buffer->getAutosaveFilename());
1291 d.autosave_watcher_.setFuture(f);
1298 void GuiView::resetAutosaveTimers()
1301 d.autosave_timeout_.restart();
1305 bool GuiView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1308 Buffer * buf = currentBufferView()
1309 ? ¤tBufferView()->buffer() : 0;
1310 Buffer * doc_buffer = documentBufferView()
1311 ? &(documentBufferView()->buffer()) : 0;
1313 // Check whether we need a buffer
1314 if (!lyxaction.funcHasFlag(cmd.action, LyXAction::NoBuffer) && !buf) {
1315 // no, exit directly
1316 flag.message(from_utf8(N_("Command not allowed with"
1317 "out any document open")));
1318 flag.setEnabled(false);
1322 if (cmd.origin == FuncRequest::TOC) {
1323 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
1325 if (toc->getStatus(documentBufferView()->cursor(), cmd, fs))
1328 flag.setEnabled(false);
1332 switch(cmd.action) {
1333 case LFUN_BUFFER_IMPORT:
1336 case LFUN_MASTER_BUFFER_UPDATE:
1337 case LFUN_MASTER_BUFFER_VIEW:
1338 enable = doc_buffer && doc_buffer->parent() != 0
1339 && !d.preview_watcher_.isRunning();
1342 case LFUN_BUFFER_UPDATE:
1343 case LFUN_BUFFER_VIEW: {
1344 if (!doc_buffer || d.preview_watcher_.isRunning()) {
1348 string format = to_utf8(cmd.argument());
1349 if (cmd.argument().empty())
1350 format = doc_buffer->getDefaultOutputFormat();
1351 enable = doc_buffer->isExportableFormat(format);
1355 case LFUN_BUFFER_RELOAD:
1356 enable = doc_buffer && !doc_buffer->isUnnamed()
1357 && doc_buffer->fileName().exists()
1358 && (!doc_buffer->isClean()
1359 || doc_buffer->isExternallyModified(Buffer::timestamp_method));
1362 case LFUN_BUFFER_CHILD_OPEN:
1363 enable = doc_buffer;
1366 case LFUN_BUFFER_WRITE:
1367 enable = doc_buffer && (doc_buffer->isUnnamed() || !doc_buffer->isClean());
1370 //FIXME: This LFUN should be moved to GuiApplication.
1371 case LFUN_BUFFER_WRITE_ALL: {
1372 // We enable the command only if there are some modified buffers
1373 Buffer * first = theBufferList().first();
1378 // We cannot use a for loop as the buffer list is a cycle.
1380 if (!b->isClean()) {
1384 b = theBufferList().next(b);
1385 } while (b != first);
1389 case LFUN_BUFFER_WRITE_AS:
1390 enable = doc_buffer;
1393 case LFUN_BUFFER_CLOSE:
1394 enable = doc_buffer;
1397 case LFUN_BUFFER_CLOSE_ALL:
1398 enable = theBufferList().last() != theBufferList().first();
1401 case LFUN_SPLIT_VIEW:
1402 if (cmd.getArg(0) == "vertical")
1403 enable = doc_buffer && (d.splitter_->count() == 1 ||
1404 d.splitter_->orientation() == Qt::Vertical);
1406 enable = doc_buffer && (d.splitter_->count() == 1 ||
1407 d.splitter_->orientation() == Qt::Horizontal);
1410 case LFUN_CLOSE_TAB_GROUP:
1411 enable = d.currentTabWorkArea();
1414 case LFUN_TOOLBAR_TOGGLE:
1415 if (GuiToolbar * t = toolbar(cmd.getArg(0)))
1416 flag.setOnOff(t->isVisible());
1419 case LFUN_DROP_LAYOUTS_CHOICE:
1423 case LFUN_UI_TOGGLE:
1424 flag.setOnOff(isFullScreen());
1427 case LFUN_DIALOG_DISCONNECT_INSET:
1430 case LFUN_DIALOG_HIDE:
1431 // FIXME: should we check if the dialog is shown?
1434 case LFUN_DIALOG_TOGGLE:
1435 flag.setOnOff(isDialogVisible(cmd.getArg(0)));
1436 // fall through to set "enable"
1437 case LFUN_DIALOG_SHOW: {
1438 string const name = cmd.getArg(0);
1440 enable = name == "aboutlyx"
1441 || name == "file" //FIXME: should be removed.
1443 || name == "texinfo"
1444 || name == "progress"
1445 || name == "compare";
1446 else if (name == "print")
1447 enable = doc_buffer->isExportable("dvi")
1448 && lyxrc.print_command != "none";
1449 else if (name == "character" || name == "symbols") {
1450 if (!buf || buf->isReadonly()
1451 || !currentBufferView()->cursor().inTexted())
1454 // FIXME we should consider passthru
1456 Inset const & in = currentBufferView()->cursor().inset();
1457 enable = !in.getLayout().isPassThru();
1460 else if (name == "latexlog")
1461 enable = FileName(doc_buffer->logName()).isReadableFile();
1462 else if (name == "spellchecker")
1463 enable = theSpellChecker() && !doc_buffer->isReadonly();
1464 else if (name == "vclog")
1465 enable = doc_buffer->lyxvc().inUse();
1469 case LFUN_DIALOG_UPDATE: {
1470 string const name = cmd.getArg(0);
1472 enable = name == "prefs";
1476 case LFUN_COMMAND_EXECUTE:
1478 case LFUN_MENU_OPEN:
1479 // Nothing to check.
1482 case LFUN_COMPLETION_INLINE:
1483 if (!d.current_work_area_
1484 || !d.current_work_area_->completer().inlinePossible(
1485 currentBufferView()->cursor()))
1489 case LFUN_COMPLETION_POPUP:
1490 if (!d.current_work_area_
1491 || !d.current_work_area_->completer().popupPossible(
1492 currentBufferView()->cursor()))
1496 case LFUN_COMPLETION_COMPLETE:
1497 if (!d.current_work_area_
1498 || !d.current_work_area_->completer().inlinePossible(
1499 currentBufferView()->cursor()))
1503 case LFUN_COMPLETION_ACCEPT:
1504 if (!d.current_work_area_
1505 || (!d.current_work_area_->completer().popupVisible()
1506 && !d.current_work_area_->completer().inlineVisible()
1507 && !d.current_work_area_->completer().completionAvailable()))
1511 case LFUN_COMPLETION_CANCEL:
1512 if (!d.current_work_area_
1513 || (!d.current_work_area_->completer().popupVisible()
1514 && !d.current_work_area_->completer().inlineVisible()))
1518 case LFUN_BUFFER_ZOOM_OUT:
1519 enable = doc_buffer && lyxrc.zoom > 10;
1522 case LFUN_BUFFER_ZOOM_IN:
1523 enable = doc_buffer;
1526 case LFUN_BUFFER_NEXT:
1527 case LFUN_BUFFER_PREVIOUS:
1528 // FIXME: should we check is there is an previous or next buffer?
1530 case LFUN_BUFFER_SWITCH:
1531 // toggle on the current buffer, but do not toggle off
1532 // the other ones (is that a good idea?)
1534 && to_utf8(cmd.argument()) == doc_buffer->absFileName())
1535 flag.setOnOff(true);
1538 case LFUN_VC_REGISTER:
1539 enable = doc_buffer && !doc_buffer->lyxvc().inUse();
1541 case LFUN_VC_CHECK_IN:
1542 enable = doc_buffer && doc_buffer->lyxvc().checkInEnabled();
1544 case LFUN_VC_CHECK_OUT:
1545 enable = doc_buffer && doc_buffer->lyxvc().checkOutEnabled();
1547 case LFUN_VC_LOCKING_TOGGLE:
1548 enable = doc_buffer && !doc_buffer->isReadonly()
1549 && doc_buffer->lyxvc().lockingToggleEnabled();
1550 flag.setOnOff(enable && !doc_buffer->lyxvc().locker().empty());
1552 case LFUN_VC_REVERT:
1553 enable = doc_buffer && doc_buffer->lyxvc().inUse();
1555 case LFUN_VC_UNDO_LAST:
1556 enable = doc_buffer && doc_buffer->lyxvc().undoLastEnabled();
1558 case LFUN_VC_REPO_UPDATE:
1559 enable = doc_buffer && doc_buffer->lyxvc().inUse();
1561 case LFUN_VC_COMMAND: {
1562 if (cmd.argument().empty())
1564 if (!doc_buffer && contains(cmd.getArg(0), 'D'))
1569 case LFUN_SERVER_GOTO_FILE_ROW:
1577 flag.setEnabled(false);
1583 static FileName selectTemplateFile()
1585 FileDialog dlg(qt_("Select template file"));
1586 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1587 dlg.setButton1(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
1589 FileDialog::Result result = dlg.open(toqstr(lyxrc.template_path),
1590 QStringList(qt_("LyX Documents (*.lyx)")));
1592 if (result.first == FileDialog::Later)
1594 if (result.second.isEmpty())
1596 return FileName(fromqstr(result.second));
1600 Buffer * GuiView::loadDocument(FileName const & filename, bool tolastfiles)
1604 Buffer * newBuffer = checkAndLoadLyXFile(filename);
1607 message(_("Document not loaded."));
1612 setBuffer(newBuffer);
1614 // scroll to the position when the file was last closed
1615 if (lyxrc.use_lastfilepos) {
1616 LastFilePosSection::FilePos filepos =
1617 theSession().lastFilePos().load(filename);
1618 documentBufferView()->moveToPosition(filepos.pit, filepos.pos, 0, 0);
1622 theSession().lastFiles().add(filename);
1629 void GuiView::openDocument(string const & fname)
1631 string initpath = lyxrc.document_path;
1633 if (documentBufferView()) {
1634 string const trypath = documentBufferView()->buffer().filePath();
1635 // If directory is writeable, use this as default.
1636 if (FileName(trypath).isDirWritable())
1642 if (fname.empty()) {
1643 FileDialog dlg(qt_("Select document to open"), LFUN_FILE_OPEN);
1644 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1645 dlg.setButton2(qt_("Examples|#E#e"),
1646 toqstr(addPath(package().system_support().absFilename(), "examples")));
1648 QStringList filter(qt_("LyX Documents (*.lyx)"));
1649 filter << qt_("LyX-1.3.x Documents (*.lyx13)")
1650 << qt_("LyX-1.4.x Documents (*.lyx14)")
1651 << qt_("LyX-1.5.x Documents (*.lyx15)")
1652 << qt_("LyX-1.6.x Documents (*.lyx16)");
1653 FileDialog::Result result =
1654 dlg.open(toqstr(initpath), filter);
1656 if (result.first == FileDialog::Later)
1659 filename = fromqstr(result.second);
1661 // check selected filename
1662 if (filename.empty()) {
1663 message(_("Canceled."));
1669 // get absolute path of file and add ".lyx" to the filename if
1671 FileName const fullname =
1672 fileSearch(string(), filename, "lyx", support::may_not_exist);
1673 if (!fullname.empty())
1674 filename = fullname.absFilename();
1676 if (!fullname.onlyPath().isDirectory()) {
1677 Alert::warning(_("Invalid filename"),
1678 bformat(_("The directory in the given path\n%1$s\ndoes not exist."),
1679 from_utf8(fullname.absFilename())));
1682 // if the file doesn't exist, let the user create one
1683 if (!fullname.exists()) {
1684 // the user specifically chose this name. Believe him.
1685 Buffer * const b = newFile(filename, string(), true);
1691 docstring const disp_fn = makeDisplayPath(filename);
1692 message(bformat(_("Opening document %1$s..."), disp_fn));
1695 Buffer * buf = loadDocument(fullname);
1697 buf->updateLabels();
1699 buf->errors("Parse");
1700 str2 = bformat(_("Document %1$s opened."), disp_fn);
1701 if (buf->lyxvc().inUse())
1702 str2 += " " + from_utf8(buf->lyxvc().versionString()) +
1703 " " + _("Version control detected.");
1705 str2 = bformat(_("Could not open document %1$s"), disp_fn);
1710 // FIXME: clean that
1711 static bool import(GuiView * lv, FileName const & filename,
1712 string const & format, ErrorList & errorList)
1714 FileName const lyxfile(support::changeExtension(filename.absFilename(), ".lyx"));
1716 string loader_format;
1717 vector<string> loaders = theConverters().loaders();
1718 if (find(loaders.begin(), loaders.end(), format) == loaders.end()) {
1719 for (vector<string>::const_iterator it = loaders.begin();
1720 it != loaders.end(); ++it) {
1721 if (!theConverters().isReachable(format, *it))
1724 string const tofile =
1725 support::changeExtension(filename.absFilename(),
1726 formats.extension(*it));
1727 if (!theConverters().convert(0, filename, FileName(tofile),
1728 filename, format, *it, errorList))
1730 loader_format = *it;
1733 if (loader_format.empty()) {
1734 frontend::Alert::error(_("Couldn't import file"),
1735 bformat(_("No information for importing the format %1$s."),
1736 formats.prettyName(format)));
1740 loader_format = format;
1742 if (loader_format == "lyx") {
1743 Buffer * buf = lv->loadDocument(lyxfile);
1746 buf->updateLabels();
1748 buf->errors("Parse");
1750 Buffer * const b = newFile(lyxfile.absFilename(), string(), true);
1754 bool as_paragraphs = loader_format == "textparagraph";
1755 string filename2 = (loader_format == format) ? filename.absFilename()
1756 : support::changeExtension(filename.absFilename(),
1757 formats.extension(loader_format));
1758 lv->currentBufferView()->insertPlaintextFile(FileName(filename2),
1760 guiApp->setCurrentView(lv);
1761 lyx::dispatch(FuncRequest(LFUN_MARK_OFF));
1768 void GuiView::importDocument(string const & argument)
1771 string filename = split(argument, format, ' ');
1773 LYXERR(Debug::INFO, format << " file: " << filename);
1775 // need user interaction
1776 if (filename.empty()) {
1777 string initpath = lyxrc.document_path;
1778 if (documentBufferView()) {
1779 string const trypath = documentBufferView()->buffer().filePath();
1780 // If directory is writeable, use this as default.
1781 if (FileName(trypath).isDirWritable())
1785 docstring const text = bformat(_("Select %1$s file to import"),
1786 formats.prettyName(format));
1788 FileDialog dlg(toqstr(text), LFUN_BUFFER_IMPORT);
1789 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1790 dlg.setButton2(qt_("Examples|#E#e"),
1791 toqstr(addPath(package().system_support().absFilename(), "examples")));
1793 docstring filter = formats.prettyName(format);
1796 filter += from_utf8(formats.extension(format));
1799 FileDialog::Result result =
1800 dlg.open(toqstr(initpath), fileFilters(toqstr(filter)));
1802 if (result.first == FileDialog::Later)
1805 filename = fromqstr(result.second);
1807 // check selected filename
1808 if (filename.empty())
1809 message(_("Canceled."));
1812 if (filename.empty())
1815 // get absolute path of file
1816 FileName const fullname(support::makeAbsPath(filename));
1818 FileName const lyxfile(support::changeExtension(fullname.absFilename(), ".lyx"));
1820 // Check if the document already is open
1821 Buffer * buf = theBufferList().getBuffer(lyxfile);
1824 if (!closeBuffer()) {
1825 message(_("Canceled."));
1830 docstring const displaypath = makeDisplayPath(lyxfile.absFilename(), 30);
1832 // if the file exists already, and we didn't do
1833 // -i lyx thefile.lyx, warn
1834 if (lyxfile.exists() && fullname != lyxfile) {
1836 docstring text = bformat(_("The document %1$s already exists.\n\n"
1837 "Do you want to overwrite that document?"), displaypath);
1838 int const ret = Alert::prompt(_("Overwrite document?"),
1839 text, 0, 1, _("&Overwrite"), _("&Cancel"));
1842 message(_("Canceled."));
1847 message(bformat(_("Importing %1$s..."), displaypath));
1848 ErrorList errorList;
1849 if (import(this, fullname, format, errorList))
1850 message(_("imported."));
1852 message(_("file not imported!"));
1854 // FIXME (Abdel 12/08/06): Is there a need to display the error list here?
1858 void GuiView::newDocument(string const & filename, bool from_template)
1860 FileName initpath(lyxrc.document_path);
1861 if (documentBufferView()) {
1862 FileName const trypath(documentBufferView()->buffer().filePath());
1863 // If directory is writeable, use this as default.
1864 if (trypath.isDirWritable())
1868 string templatefile;
1869 if (from_template) {
1870 templatefile = selectTemplateFile().absFilename();
1871 if (templatefile.empty())
1876 if (filename.empty())
1877 b = newUnnamedFile(initpath, to_utf8(_("newfile")), templatefile);
1879 b = newFile(filename, templatefile, true);
1884 // If no new document could be created, it is unsure
1885 // whether there is a valid BufferView.
1886 if (currentBufferView())
1887 // Ensure the cursor is correctly positioned on screen.
1888 currentBufferView()->showCursor();
1892 void GuiView::insertLyXFile(docstring const & fname)
1894 BufferView * bv = documentBufferView();
1899 FileName filename(to_utf8(fname));
1901 if (!filename.empty()) {
1902 bv->insertLyXFile(filename);
1906 // Launch a file browser
1908 string initpath = lyxrc.document_path;
1909 string const trypath = bv->buffer().filePath();
1910 // If directory is writeable, use this as default.
1911 if (FileName(trypath).isDirWritable())
1915 FileDialog dlg(qt_("Select LyX document to insert"), LFUN_FILE_INSERT);
1916 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1917 dlg.setButton2(qt_("Examples|#E#e"),
1918 toqstr(addPath(package().system_support().absFilename(),
1921 FileDialog::Result result = dlg.open(toqstr(initpath),
1922 QStringList(qt_("LyX Documents (*.lyx)")));
1924 if (result.first == FileDialog::Later)
1928 filename.set(fromqstr(result.second));
1930 // check selected filename
1931 if (filename.empty()) {
1932 // emit message signal.
1933 message(_("Canceled."));
1937 bv->insertLyXFile(filename);
1941 void GuiView::insertPlaintextFile(docstring const & fname,
1944 BufferView * bv = documentBufferView();
1948 if (!fname.empty() && !FileName::isAbsolute(to_utf8(fname))) {
1949 message(_("Absolute filename expected."));
1954 FileName filename(to_utf8(fname));
1956 if (!filename.empty()) {
1957 bv->insertPlaintextFile(filename, asParagraph);
1961 FileDialog dlg(qt_("Select file to insert"), (asParagraph ?
1962 LFUN_FILE_INSERT_PLAINTEXT_PARA : LFUN_FILE_INSERT_PLAINTEXT));
1964 FileDialog::Result result = dlg.open(toqstr(bv->buffer().filePath()),
1965 QStringList(qt_("All Files (*)")));
1967 if (result.first == FileDialog::Later)
1971 filename.set(fromqstr(result.second));
1973 // check selected filename
1974 if (filename.empty()) {
1975 // emit message signal.
1976 message(_("Canceled."));
1980 bv->insertPlaintextFile(filename, asParagraph);
1984 bool GuiView::renameBuffer(Buffer & b, docstring const & newname)
1986 FileName fname = b.fileName();
1987 FileName const oldname = fname;
1989 if (!newname.empty()) {
1991 fname = support::makeAbsPath(to_utf8(newname), oldname.onlyPath().absFilename());
1993 // Switch to this Buffer.
1996 // No argument? Ask user through dialog.
1998 FileDialog dlg(qt_("Choose a filename to save document as"),
1999 LFUN_BUFFER_WRITE_AS);
2000 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2001 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
2003 if (!isLyXFilename(fname.absFilename()))
2004 fname.changeExtension(".lyx");
2006 FileDialog::Result result =
2007 dlg.save(toqstr(fname.onlyPath().absFilename()),
2008 QStringList(qt_("LyX Documents (*.lyx)")),
2009 toqstr(fname.onlyFileName()));
2011 if (result.first == FileDialog::Later)
2014 fname.set(fromqstr(result.second));
2019 if (!isLyXFilename(fname.absFilename()))
2020 fname.changeExtension(".lyx");
2023 if (FileName(fname).exists()) {
2024 docstring const file = makeDisplayPath(fname.absFilename(), 30);
2025 docstring text = bformat(_("The document %1$s already "
2026 "exists.\n\nDo you want to "
2027 "overwrite that document?"),
2029 int const ret = Alert::prompt(_("Overwrite document?"),
2030 text, 0, 2, _("&Overwrite"), _("&Rename"), _("&Cancel"));
2033 case 1: return renameBuffer(b, docstring());
2034 case 2: return false;
2038 FileName oldauto = b.getAutosaveFilename();
2040 // Ok, change the name of the buffer
2041 b.setFileName(fname.absFilename());
2043 bool unnamed = b.isUnnamed();
2044 b.setUnnamed(false);
2045 b.saveCheckSum(fname);
2047 // bring the autosave file with us, just in case.
2048 b.moveAutosaveFile(oldauto);
2050 if (!saveBuffer(b)) {
2051 oldauto = b.getAutosaveFilename();
2052 b.setFileName(oldname.absFilename());
2053 b.setUnnamed(unnamed);
2054 b.saveCheckSum(oldname);
2055 b.moveAutosaveFile(oldauto);
2063 bool GuiView::saveBuffer(Buffer & b)
2065 if (workArea(b) && workArea(b)->inDialogMode())
2069 return renameBuffer(b, docstring());
2072 theSession().lastFiles().add(b.fileName());
2076 // Switch to this Buffer.
2079 // FIXME: we don't tell the user *WHY* the save failed !!
2080 docstring const file = makeDisplayPath(b.absFileName(), 30);
2081 docstring text = bformat(_("The document %1$s could not be saved.\n\n"
2082 "Do you want to rename the document and "
2083 "try again?"), file);
2084 int const ret = Alert::prompt(_("Rename and save?"),
2085 text, 0, 2, _("&Rename"), _("&Retry"), _("&Cancel"));
2088 if (!renameBuffer(b, docstring()))
2097 return saveBuffer(b);
2101 bool GuiView::hideWorkArea(GuiWorkArea * wa)
2103 return closeWorkArea(wa, false);
2107 bool GuiView::closeWorkArea(GuiWorkArea * wa)
2109 Buffer & buf = wa->bufferView().buffer();
2110 return closeWorkArea(wa, !buf.parent());
2114 bool GuiView::closeBuffer()
2116 GuiWorkArea * wa = currentMainWorkArea();
2117 Buffer & buf = wa->bufferView().buffer();
2118 return wa && closeWorkArea(wa, !buf.parent());
2122 void GuiView::writeSession() const {
2123 GuiWorkArea const * active_wa = currentMainWorkArea();
2124 for (int i = 0; i < d.splitter_->count(); ++i) {
2125 TabWorkArea * twa = d.tabWorkArea(i);
2126 for (int j = 0; j < twa->count(); ++j) {
2127 GuiWorkArea * wa = static_cast<GuiWorkArea *>(twa->widget(j));
2128 Buffer & buf = wa->bufferView().buffer();
2129 theSession().lastOpened().add(buf.fileName(), wa == active_wa);
2135 bool GuiView::closeBufferAll()
2137 // Close the workareas in all other views
2138 QList<int> const ids = guiApp->viewIds();
2139 for (int i = 0; i != ids.size(); ++i) {
2140 if (id_ != ids[i] && !guiApp->view(ids[i]).closeWorkAreaAll())
2144 // Close our own workareas
2145 if (!closeWorkAreaAll())
2148 // Now close the hidden buffers. We prevent hidden buffers from being
2149 // dirty, so we can just close them.
2150 theBufferList().closeAll();
2155 bool GuiView::closeWorkAreaAll()
2157 setCurrentWorkArea(currentMainWorkArea());
2159 // We might be in a situation that there is still a tabWorkArea, but
2160 // there are no tabs anymore. This can happen when we get here after a
2161 // TabWorkArea::lastWorkAreaRemoved() signal. Therefore we count how
2162 // many TabWorkArea's have no documents anymore.
2165 // We have to call count() each time, because it can happen that
2166 // more than one splitter will disappear in one iteration (bug 5998).
2167 for (; d.splitter_->count() > empty_twa; ) {
2168 TabWorkArea * twa = d.tabWorkArea(empty_twa);
2170 if (twa->count() == 0)
2173 setCurrentWorkArea(twa->currentWorkArea());
2174 if (!closeTabWorkArea(twa))
2182 bool GuiView::closeWorkArea(GuiWorkArea * wa, bool close_buffer)
2187 Buffer & buf = wa->bufferView().buffer();
2190 return closeBuffer(buf);
2192 if (!inMultiTabs(wa))
2193 if (!saveBufferIfNeeded(buf, true))
2201 bool GuiView::closeBuffer(Buffer & buf)
2203 // If we are in a close_event all children will be closed in some time,
2204 // so no need to do it here. This will ensure that the children end up
2205 // in the session file in the correct order. If we close the master
2206 // buffer, we can close or release the child buffers here too.
2208 vector<Buffer *> clist = buf.getChildren(false);
2209 for (vector<Buffer *>::const_iterator it = clist.begin();
2210 it != clist.end(); ++it) {
2211 // If a child is dirty, do not close
2212 // without user intervention
2213 //FIXME: should we look in other tabworkareas?
2214 Buffer * child_buf = *it;
2215 GuiWorkArea * child_wa = workArea(*child_buf);
2217 if (!closeWorkArea(child_wa, true))
2220 theBufferList().releaseChild(&buf, child_buf);
2223 // goto bookmark to update bookmark pit.
2224 //FIXME: we should update only the bookmarks related to this buffer!
2225 LYXERR(Debug::DEBUG, "GuiView::closeBuffer()");
2226 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
2227 theLyXFunc().gotoBookmark(i+1, false, false);
2229 if (saveBufferIfNeeded(buf, false)) {
2230 theBufferList().release(&buf);
2237 bool GuiView::closeTabWorkArea(TabWorkArea * twa)
2239 while (twa == d.currentTabWorkArea()) {
2240 twa->setCurrentIndex(twa->count()-1);
2242 GuiWorkArea * wa = twa->currentWorkArea();
2243 Buffer & b = wa->bufferView().buffer();
2245 // We only want to close the buffer if the same buffer is not visible
2246 // in another view, and if this is not a child and if we are closing
2247 // a view (not a tabgroup).
2248 bool const close_buffer =
2249 !inMultiViews(wa) && !b.parent() && closing_;
2251 if (!closeWorkArea(wa, close_buffer))
2258 bool GuiView::saveBufferIfNeeded(Buffer & buf, bool hiding)
2260 if (buf.isClean() || buf.paragraphs().empty())
2263 // Switch to this Buffer.
2268 if (buf.isUnnamed())
2269 file = from_utf8(buf.fileName().onlyFileName());
2271 file = buf.fileName().displayName(30);
2273 // Bring this window to top before asking questions.
2278 if (hiding && buf.isUnnamed()) {
2279 docstring const text = bformat(_("The document %1$s has not been "
2280 "saved yet.\n\nDo you want to save "
2281 "the document?"), file);
2282 ret = Alert::prompt(_("Save new document?"),
2283 text, 0, 1, _("&Save"), _("&Cancel"));
2287 docstring const text = bformat(_("The document %1$s has unsaved changes."
2288 "\n\nDo you want to save the document or discard the changes?"), file);
2289 ret = Alert::prompt(_("Save changed document?"),
2290 text, 0, 2, _("&Save"), _("&Discard"), _("&Cancel"));
2295 if (!saveBuffer(buf))
2299 // if we crash after this we could
2300 // have no autosave file but I guess
2301 // this is really improbable (Jug)
2302 buf.removeAutosaveFile();
2304 // revert all changes
2305 buf.loadLyXFile(buf.fileName());
2315 bool GuiView::inMultiTabs(GuiWorkArea * wa)
2317 Buffer & buf = wa->bufferView().buffer();
2319 for (int i = 0; i != d.splitter_->count(); ++i) {
2320 GuiWorkArea * wa_ = d.tabWorkArea(i)->workArea(buf);
2321 if (wa_ && wa_ != wa)
2324 return inMultiViews(wa);
2328 bool GuiView::inMultiViews(GuiWorkArea * wa)
2330 QList<int> const ids = guiApp->viewIds();
2331 Buffer & buf = wa->bufferView().buffer();
2334 for (int i = 0; i != ids.size() && found_twa <= 1; ++i) {
2338 if (guiApp->view(ids[i]).workArea(buf))
2345 void GuiView::gotoNextOrPreviousBuffer(NextOrPrevious np)
2347 Buffer * const curbuf = documentBufferView()
2348 ? &documentBufferView()->buffer() : 0;
2349 Buffer * nextbuf = curbuf;
2351 if (np == NEXTBUFFER)
2352 nextbuf = theBufferList().next(nextbuf);
2354 nextbuf = theBufferList().previous(nextbuf);
2355 if (nextbuf == curbuf)
2361 if (workArea(*nextbuf))
2368 /// make sure the document is saved
2369 static bool ensureBufferClean(Buffer * buffer)
2371 LASSERT(buffer, return false);
2372 if (buffer->isClean() && !buffer->isUnnamed())
2375 docstring const file = buffer->fileName().displayName(30);
2378 if (!buffer->isUnnamed()) {
2379 text = bformat(_("The document %1$s has unsaved "
2380 "changes.\n\nDo you want to save "
2381 "the document?"), file);
2382 title = _("Save changed document?");
2385 text = bformat(_("The document %1$s has not been "
2386 "saved yet.\n\nDo you want to save "
2387 "the document?"), file);
2388 title = _("Save new document?");
2390 int const ret = Alert::prompt(title, text, 0, 1, _("&Save"), _("&Cancel"));
2393 dispatch(FuncRequest(LFUN_BUFFER_WRITE));
2395 return buffer->isClean() && !buffer->isUnnamed();
2399 void GuiView::reloadBuffer()
2401 Buffer * buf = &documentBufferView()->buffer();
2406 void GuiView::reloadBuffer(Buffer * buf)
2408 FileName filename = buf->fileName();
2409 Buffer const * master = buf->masterBuffer();
2410 bool const is_child = master != buf;
2411 // The user has already confirmed that the changes, if any, should
2412 // be discarded. So we just release the Buffer and don't call closeBuffer();
2413 theBufferList().release(buf);
2414 buf = loadDocument(filename);
2415 docstring const disp_fn = makeDisplayPath(filename.absFilename());
2418 // re-allocate master if necessary
2419 if (is_child && theBufferList().isLoaded(master)
2420 && buf->masterBuffer() != master)
2421 buf->setParent(master);
2422 buf->updateLabels();
2424 buf->errors("Parse");
2425 str = bformat(_("Document %1$s reloaded."), disp_fn);
2427 str = bformat(_("Could not reload document %1$s"), disp_fn);
2433 void GuiView::checkExternallyModifiedBuffers()
2435 BufferList::iterator bit = theBufferList().begin();
2436 BufferList::iterator const bend = theBufferList().end();
2437 for (; bit != bend; ++bit) {
2438 if ((*bit)->fileName().exists()
2439 && (*bit)->isExternallyModified(Buffer::checksum_method)) {
2440 docstring text = bformat(_("Document \n%1$s\n has been externally modified."
2441 " Reload now? Any local changes will be lost."),
2442 from_utf8((*bit)->absFileName()));
2443 int const ret = Alert::prompt(_("Reload externally changed document?"),
2444 text, 0, 1, _("&Reload"), _("&Cancel"));
2452 void GuiView::dispatchVC(FuncRequest const & cmd)
2454 Buffer * buffer = documentBufferView()
2455 ? &(documentBufferView()->buffer()) : 0;
2457 switch (cmd.action) {
2458 case LFUN_VC_REGISTER:
2459 if (!buffer || !ensureBufferClean(buffer))
2461 if (!buffer->lyxvc().inUse()) {
2462 if (buffer->lyxvc().registrer())
2467 case LFUN_VC_CHECK_IN:
2468 if (!buffer || !ensureBufferClean(buffer))
2470 if (buffer->lyxvc().inUse() && !buffer->isReadonly()) {
2471 message(from_utf8(buffer->lyxvc().checkIn()));
2476 case LFUN_VC_CHECK_OUT:
2477 if (!buffer || !ensureBufferClean(buffer))
2479 if (buffer->lyxvc().inUse()) {
2480 message(from_utf8(buffer->lyxvc().checkOut()));
2485 case LFUN_VC_LOCKING_TOGGLE:
2486 LASSERT(buffer, return);
2487 if (!ensureBufferClean(buffer) || buffer->isReadonly())
2489 if (buffer->lyxvc().inUse()) {
2490 string res = buffer->lyxvc().lockingToggle();
2492 frontend::Alert::error(_("Revision control error."),
2493 _("Error when setting the locking property."));
2495 message(from_utf8(res));
2501 case LFUN_VC_REVERT:
2502 LASSERT(buffer, return);
2503 buffer->lyxvc().revert();
2507 case LFUN_VC_UNDO_LAST:
2508 LASSERT(buffer, return);
2509 buffer->lyxvc().undoLast();
2513 case LFUN_VC_REPO_UPDATE:
2514 LASSERT(buffer, return);
2515 if (ensureBufferClean(buffer)) {
2516 string res = buffer->lyxvc().repoUpdate();
2517 message(from_utf8(res));
2518 checkExternallyModifiedBuffers();
2522 case LFUN_VC_COMMAND: {
2523 string flag = cmd.getArg(0);
2524 if (buffer && contains(flag, 'R') && !ensureBufferClean(buffer))
2527 if (contains(flag, 'M')) {
2528 if (!Alert::askForText(message, _("LyX VC: Log Message")))
2531 string path = cmd.getArg(1);
2532 if (contains(path, "$$p") && buffer)
2533 path = subst(path, "$$p", buffer->filePath());
2534 LYXERR(Debug::LYXVC, "Directory: " << path);
2536 if (!pp.isReadableDirectory()) {
2537 lyxerr << _("Directory is not accessible.") << endl;
2540 support::PathChanger p(pp);
2542 string command = cmd.getArg(2);
2543 if (command.empty())
2546 command = subst(command, "$$i", buffer->absFileName());
2547 command = subst(command, "$$p", buffer->filePath());
2549 command = subst(command, "$$m", to_utf8(message));
2550 LYXERR(Debug::LYXVC, "Command: " << command);
2552 one.startscript(Systemcall::Wait, command);
2556 if (contains(flag, 'I'))
2557 buffer->markDirty();
2558 if (contains(flag, 'R'))
2569 void GuiView::openChildDocument(string const & fname)
2571 LASSERT(documentBufferView(), return);
2572 Buffer & buffer = documentBufferView()->buffer();
2573 FileName const filename = support::makeAbsPath(fname, buffer.filePath());
2574 documentBufferView()->saveBookmark(false);
2576 bool parsed = false;
2577 if (theBufferList().exists(filename)) {
2578 child = theBufferList().getBuffer(filename);
2580 message(bformat(_("Opening child document %1$s..."),
2581 makeDisplayPath(filename.absFilename())));
2582 child = loadDocument(filename, false);
2588 // Set the parent name of the child document.
2589 // This makes insertion of citations and references in the child work,
2590 // when the target is in the parent or another child document.
2591 child->setParent(&buffer);
2592 child->masterBuffer()->updateLabels();
2595 child->errors("Parse");
2599 bool GuiView::goToFileRow(string const & argument)
2603 size_t i = argument.find_last_of(' ');
2604 if (i != string::npos) {
2605 file_name = os::internal_path(trim(argument.substr(0, i)));
2606 istringstream is(argument.substr(i + 1));
2611 if (i == string::npos) {
2612 LYXERR0("Wrong argument: " << argument);
2616 string const abstmp = package().temp_dir().absFilename();
2617 string const realtmp = package().temp_dir().realPath();
2618 // We have to use os::path_prefix_is() here, instead of
2619 // simply prefixIs(), because the file name comes from
2620 // an external application and may need case adjustment.
2621 if (os::path_prefix_is(file_name, abstmp, os::CASE_ADJUSTED)
2622 || os::path_prefix_is(file_name, realtmp, os::CASE_ADJUSTED)) {
2623 // Needed by inverse dvi search. If it is a file
2624 // in tmpdir, call the apropriated function.
2625 // If tmpdir is a symlink, we may have the real
2626 // path passed back, so we correct for that.
2627 if (!prefixIs(file_name, abstmp))
2628 file_name = subst(file_name, realtmp, abstmp);
2629 buf = theBufferList().getBufferFromTmp(file_name);
2631 // Must replace extension of the file to be .lyx
2632 // and get full path
2633 FileName const s = fileSearch(string(),
2634 support::changeExtension(file_name, ".lyx"), "lyx");
2635 // Either change buffer or load the file
2636 if (theBufferList().exists(s))
2637 buf = theBufferList().getBuffer(s);
2638 else if (s.exists()) {
2639 buf = loadDocument(s);
2640 buf->updateLabels();
2641 buf->errors("Parse");
2644 _("File does not exist: %1$s"),
2645 makeDisplayPath(file_name)));
2650 documentBufferView()->setCursorFromRow(row);
2655 static docstring exportAndDestroy(Buffer * buffer, string const & format)
2657 bool const success = buffer->doExport(format, true);
2660 ? bformat(_("Successful export to format: %1$s"), from_utf8(format))
2661 : bformat(_("Error exporting to format: %1$s"), from_utf8(format));
2665 static docstring previewAndDestroy(Buffer * buffer, string const & format)
2667 bool const success = buffer->preview(format);
2670 ? bformat(_("Successful preview of format: %1$s"), from_utf8(format))
2671 : bformat(_("Error previewing format: %1$s"), from_utf8(format));
2675 bool GuiView::dispatch(FuncRequest const & cmd)
2677 BufferView * bv = currentBufferView();
2678 // By default we won't need any update.
2680 bv->cursor().updateFlags(Update::None);
2682 Buffer * doc_buffer = documentBufferView()
2683 ? &(documentBufferView()->buffer()) : 0;
2685 bool dispatched = true;
2687 if (cmd.origin == FuncRequest::TOC) {
2688 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
2689 toc->doDispatch(bv->cursor(), cmd);
2693 string const argument = to_utf8(cmd.argument());
2695 switch(cmd.action) {
2696 case LFUN_BUFFER_CHILD_OPEN:
2697 openChildDocument(to_utf8(cmd.argument()));
2700 case LFUN_BUFFER_IMPORT:
2701 importDocument(to_utf8(cmd.argument()));
2704 case LFUN_BUFFER_EXPORT: {
2707 if (cmd.argument() == "custom") {
2708 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "sendto"));
2711 if (doc_buffer->doExport(argument, false)) {
2712 message(bformat(_("Error exporting to format: %1$s."),
2718 case LFUN_BUFFER_UPDATE: {
2721 string format = argument;
2722 if (argument.empty())
2723 format = doc_buffer->getDefaultOutputFormat();
2724 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
2725 ProgressInterface::instance()->clearMessages();
2726 ProgressInterface::instance()->appendMessage("Exporting ...");
2727 QFuture<docstring> f = QtConcurrent::run(exportAndDestroy,
2728 doc_buffer->clone(), format);
2729 d.setPreviewFuture(f);
2731 doc_buffer->doExport(format, true);
2735 case LFUN_BUFFER_VIEW: {
2738 string format = argument;
2739 if (argument.empty())
2740 format = doc_buffer->getDefaultOutputFormat();
2741 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
2742 ProgressInterface::instance()->clearMessages();
2743 ProgressInterface::instance()->appendMessage("Previewing ...");
2744 QFuture<docstring> f = QtConcurrent::run(previewAndDestroy,
2745 doc_buffer->clone(), format);
2746 d.setPreviewFuture(f);
2748 doc_buffer->preview(format);
2752 case LFUN_MASTER_BUFFER_UPDATE: {
2755 string format = argument;
2756 Buffer const * master = doc_buffer->masterBuffer();
2757 if (argument.empty())
2758 format = master->getDefaultOutputFormat();
2759 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
2760 QFuture<docstring> f = QtConcurrent::run(exportAndDestroy,
2761 master->clone(), format);
2762 d.setPreviewFuture(f);
2764 master->doExport(format, true);
2768 case LFUN_MASTER_BUFFER_VIEW: {
2769 string format = argument;
2770 Buffer const * master = doc_buffer->masterBuffer();
2771 if (argument.empty())
2772 format = master->getDefaultOutputFormat();
2773 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
2774 QFuture<docstring> f = QtConcurrent::run(previewAndDestroy,
2775 master->clone(), format);
2776 d.setPreviewFuture(f);
2778 master->preview(format);
2782 case LFUN_BUFFER_SWITCH:
2783 if (FileName::isAbsolute(to_utf8(cmd.argument()))) {
2785 theBufferList().getBuffer(FileName(to_utf8(cmd.argument())));
2789 message(_("Document not loaded"));
2793 case LFUN_BUFFER_NEXT:
2794 gotoNextOrPreviousBuffer(NEXTBUFFER);
2797 case LFUN_BUFFER_PREVIOUS:
2798 gotoNextOrPreviousBuffer(PREVBUFFER);
2801 case LFUN_COMMAND_EXECUTE: {
2802 bool const show_it = cmd.argument() != "off";
2803 // FIXME: this is a hack, "minibuffer" should not be
2805 if (GuiToolbar * t = toolbar("minibuffer")) {
2806 t->setVisible(show_it);
2807 if (show_it && t->commandBuffer())
2808 t->commandBuffer()->setFocus();
2812 case LFUN_DROP_LAYOUTS_CHOICE:
2813 d.layout_->showPopup();
2816 case LFUN_MENU_OPEN:
2817 if (QMenu * menu = guiApp->menus().menu(toqstr(cmd.argument()), *this))
2818 menu->exec(QCursor::pos());
2821 case LFUN_FILE_INSERT:
2822 insertLyXFile(cmd.argument());
2824 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
2825 insertPlaintextFile(cmd.argument(), true);
2828 case LFUN_FILE_INSERT_PLAINTEXT:
2829 insertPlaintextFile(cmd.argument(), false);
2832 case LFUN_BUFFER_RELOAD: {
2833 LASSERT(doc_buffer, break);
2834 docstring const file = makeDisplayPath(doc_buffer->absFileName(), 20);
2835 docstring text = bformat(_("Any changes will be lost. Are you sure "
2836 "you want to revert to the saved version of the document %1$s?"), file);
2837 int const ret = Alert::prompt(_("Revert to saved document?"),
2838 text, 1, 1, _("&Revert"), _("&Cancel"));
2841 doc_buffer->markClean();
2847 case LFUN_BUFFER_WRITE:
2848 LASSERT(doc_buffer, break);
2849 saveBuffer(*doc_buffer);
2852 case LFUN_BUFFER_WRITE_AS:
2853 LASSERT(doc_buffer, break);
2854 renameBuffer(*doc_buffer, cmd.argument());
2857 case LFUN_BUFFER_WRITE_ALL: {
2858 Buffer * first = theBufferList().first();
2861 message(_("Saving all documents..."));
2862 // We cannot use a for loop as the buffer list cycles.
2865 if (!b->isClean()) {
2867 LYXERR(Debug::ACTION, "Saved " << b->absFileName());
2869 b = theBufferList().next(b);
2870 } while (b != first);
2871 message(_("All documents saved."));
2875 case LFUN_BUFFER_CLOSE:
2879 case LFUN_BUFFER_CLOSE_ALL:
2883 case LFUN_TOOLBAR_TOGGLE: {
2884 string const name = cmd.getArg(0);
2885 if (GuiToolbar * t = toolbar(name))
2890 case LFUN_DIALOG_UPDATE: {
2891 string const name = to_utf8(cmd.argument());
2892 if (currentBufferView()) {
2893 Inset * inset = currentBufferView()->editedInset(name);
2894 // Can only update a dialog connected to an existing inset
2897 // FIXME: get rid of this indirection; GuiView ask the inset
2898 // if he is kind enough to update itself...
2899 FuncRequest fr(LFUN_INSET_DIALOG_UPDATE, cmd.argument());
2900 inset->dispatch(currentBufferView()->cursor(), fr);
2901 } else if (name == "paragraph") {
2902 lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
2903 } else if (name == "prefs" || name == "document") {
2904 updateDialog(name, string());
2909 case LFUN_DIALOG_TOGGLE: {
2910 if (isDialogVisible(cmd.getArg(0)))
2911 dispatch(FuncRequest(LFUN_DIALOG_HIDE, cmd.argument()));
2913 dispatch(FuncRequest(LFUN_DIALOG_SHOW, cmd.argument()));
2917 case LFUN_DIALOG_DISCONNECT_INSET:
2918 disconnectDialog(to_utf8(cmd.argument()));
2921 case LFUN_DIALOG_HIDE: {
2922 guiApp->hideDialogs(to_utf8(cmd.argument()), 0);
2926 case LFUN_DIALOG_SHOW: {
2927 string const name = cmd.getArg(0);
2928 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
2930 if (name == "character") {
2931 data = freefont2string();
2933 showDialog("character", data);
2934 } else if (name == "latexlog") {
2935 Buffer::LogType type;
2936 string const logfile = doc_buffer->logName(&type);
2938 case Buffer::latexlog:
2941 case Buffer::buildlog:
2945 data += Lexer::quoteString(logfile);
2946 showDialog("log", data);
2947 } else if (name == "vclog") {
2948 string const data = "vc " +
2949 Lexer::quoteString(doc_buffer->lyxvc().getLogFile());
2950 showDialog("log", data);
2951 } else if (name == "symbols") {
2952 data = bv->cursor().getEncoding()->name();
2954 showDialog("symbols", data);
2956 } else if (name == "prefs" && isFullScreen()) {
2957 FuncRequest fr(LFUN_INSET_INSERT, "fullscreen");
2959 showDialog("prefs", data);
2961 showDialog(name, data);
2966 message(cmd.argument());
2969 case LFUN_UI_TOGGLE:
2971 // Make sure the keyboard focus stays in the work area.
2975 case LFUN_SPLIT_VIEW: {
2976 LASSERT(doc_buffer, break);
2977 string const orientation = cmd.getArg(0);
2978 d.splitter_->setOrientation(orientation == "vertical"
2979 ? Qt::Vertical : Qt::Horizontal);
2980 TabWorkArea * twa = addTabWorkArea();
2981 GuiWorkArea * wa = twa->addWorkArea(*doc_buffer, *this);
2982 setCurrentWorkArea(wa);
2985 case LFUN_CLOSE_TAB_GROUP:
2986 if (TabWorkArea * twa = d.currentTabWorkArea()) {
2987 closeTabWorkArea(twa);
2988 d.current_work_area_ = 0;
2989 twa = d.currentTabWorkArea();
2990 // Switch to the next GuiWorkArea in the found TabWorkArea.
2992 // Make sure the work area is up to date.
2993 setCurrentWorkArea(twa->currentWorkArea());
2995 setCurrentWorkArea(0);
3000 case LFUN_COMPLETION_INLINE:
3001 if (d.current_work_area_)
3002 d.current_work_area_->completer().showInline();
3005 case LFUN_COMPLETION_POPUP:
3006 if (d.current_work_area_)
3007 d.current_work_area_->completer().showPopup();
3011 case LFUN_COMPLETION_COMPLETE:
3012 if (d.current_work_area_)
3013 d.current_work_area_->completer().tab();
3016 case LFUN_COMPLETION_CANCEL:
3017 if (d.current_work_area_) {
3018 if (d.current_work_area_->completer().popupVisible())
3019 d.current_work_area_->completer().hidePopup();
3021 d.current_work_area_->completer().hideInline();
3025 case LFUN_COMPLETION_ACCEPT:
3026 if (d.current_work_area_)
3027 d.current_work_area_->completer().activate();
3030 case LFUN_BUFFER_ZOOM_IN:
3031 case LFUN_BUFFER_ZOOM_OUT:
3032 if (cmd.argument().empty()) {
3033 if (cmd.action == LFUN_BUFFER_ZOOM_IN)
3038 lyxrc.zoom += convert<int>(cmd.argument());
3040 if (lyxrc.zoom < 10)
3043 // The global QPixmapCache is used in GuiPainter to cache text
3044 // painting so we must reset it.
3045 QPixmapCache::clear();
3046 guiApp->fontLoader().update();
3047 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
3050 case LFUN_VC_REGISTER:
3051 case LFUN_VC_CHECK_IN:
3052 case LFUN_VC_CHECK_OUT:
3053 case LFUN_VC_REPO_UPDATE:
3054 case LFUN_VC_LOCKING_TOGGLE:
3055 case LFUN_VC_REVERT:
3056 case LFUN_VC_UNDO_LAST:
3057 case LFUN_VC_COMMAND:
3061 case LFUN_SERVER_GOTO_FILE_ROW:
3062 goToFileRow(to_utf8(cmd.argument()));
3070 // Part of automatic menu appearance feature.
3071 if (isFullScreen()) {
3072 if (menuBar()->isVisible() && lyxrc.full_screen_menubar)
3074 if (statusBar()->isVisible())
3075 statusBar()->hide();
3082 void GuiView::lfunUiToggle(FuncRequest const & cmd)
3084 string const arg = cmd.getArg(0);
3085 if (arg == "scrollbar") {
3086 // hide() is of no help
3087 if (d.current_work_area_->verticalScrollBarPolicy() ==
3088 Qt::ScrollBarAlwaysOff)
3090 d.current_work_area_->setVerticalScrollBarPolicy(
3091 Qt::ScrollBarAsNeeded);
3093 d.current_work_area_->setVerticalScrollBarPolicy(
3094 Qt::ScrollBarAlwaysOff);
3097 if (arg == "statusbar") {
3098 statusBar()->setVisible(!statusBar()->isVisible());
3101 if (arg == "menubar") {
3102 menuBar()->setVisible(!menuBar()->isVisible());
3105 #if QT_VERSION >= 0x040300
3106 if (arg == "frame") {
3108 getContentsMargins(&l, &t, &r, &b);
3109 //are the frames in default state?
3110 d.current_work_area_->setFrameStyle(QFrame::NoFrame);
3112 setContentsMargins(-2, -2, -2, -2);
3114 setContentsMargins(0, 0, 0, 0);
3119 if (arg == "fullscreen") {
3124 message(bformat("LFUN_UI_TOGGLE " + _("%1$s unknown command!"), from_utf8(arg)));
3128 void GuiView::toggleFullScreen()
3130 if (isFullScreen()) {
3131 for (int i = 0; i != d.splitter_->count(); ++i)
3132 d.tabWorkArea(i)->setFullScreen(false);
3133 #if QT_VERSION >= 0x040300
3134 setContentsMargins(0, 0, 0, 0);
3136 setWindowState(windowState() ^ Qt::WindowFullScreen);
3139 statusBar()->show();
3142 hideDialogs("prefs", 0);
3143 for (int i = 0; i != d.splitter_->count(); ++i)
3144 d.tabWorkArea(i)->setFullScreen(true);
3145 #if QT_VERSION >= 0x040300
3146 setContentsMargins(-2, -2, -2, -2);
3149 setWindowState(windowState() ^ Qt::WindowFullScreen);
3150 statusBar()->hide();
3151 if (lyxrc.full_screen_menubar)
3153 if (lyxrc.full_screen_toolbars) {
3154 ToolbarMap::iterator end = d.toolbars_.end();
3155 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
3160 // give dialogs like the TOC a chance to adapt
3165 Buffer const * GuiView::updateInset(Inset const * inset)
3167 if (!d.current_work_area_)
3171 d.current_work_area_->scheduleRedraw();
3173 return &d.current_work_area_->bufferView().buffer();
3177 void GuiView::restartCursor()
3179 /* When we move around, or type, it's nice to be able to see
3180 * the cursor immediately after the keypress.
3182 if (d.current_work_area_)
3183 d.current_work_area_->startBlinkingCursor();
3185 // Take this occasion to update the other GUI elements.
3191 void GuiView::updateCompletion(Cursor & cur, bool start, bool keep)
3193 if (d.current_work_area_)
3194 d.current_work_area_->completer().updateVisibility(cur, start, keep);
3199 // This list should be kept in sync with the list of insets in
3200 // src/insets/Inset.cpp. I.e., if a dialog goes with an inset, the
3201 // dialog should have the same name as the inset.
3202 // Changes should be also recorded in LFUN_DIALOG_SHOW doxygen
3203 // docs in LyXAction.cpp.
3205 char const * const dialognames[] = {
3206 "aboutlyx", "bibitem", "bibtex", "box", "branch", "changes", "character",
3207 "citation", "compare", "document", "errorlist", "ert", "external", "file",
3208 "findreplace", "findreplaceadv", "float", "graphics", "href", "include",
3209 "index", "index_print", "info", "listings", "label", "log", "mathdelimiter",
3210 "mathmatrix", "mathspace", "nomenclature", "nomencl_print", "note",
3211 "paragraph", "phantom", "prefs", "print", "ref", "sendto", "space",
3212 "spellchecker", "symbols", "tabular", "tabularcreate", "thesaurus", "texinfo",
3213 "toc", "view-source", "vspace", "wrap", "progress"};
3215 char const * const * const end_dialognames =
3216 dialognames + (sizeof(dialognames) / sizeof(char *));
3220 cmpCStr(char const * name) : name_(name) {}
3221 bool operator()(char const * other) {
3222 return strcmp(other, name_) == 0;
3229 bool isValidName(string const & name)
3231 return find_if(dialognames, end_dialognames,
3232 cmpCStr(name.c_str())) != end_dialognames;
3238 void GuiView::resetDialogs()
3240 // Make sure that no LFUN uses any LyXView.
3241 guiApp->setCurrentView(0);
3244 constructToolbars();
3245 guiApp->menus().fillMenuBar(menuBar(), this, false);
3246 d.layout_->updateContents(true);
3247 // Now update controls with current buffer.
3248 guiApp->setCurrentView(this);
3254 Dialog * GuiView::findOrBuild(string const & name, bool hide_it)
3256 if (!isValidName(name))
3259 map<string, DialogPtr>::iterator it = d.dialogs_.find(name);
3261 if (it != d.dialogs_.end()) {
3263 it->second->hideView();
3264 return it->second.get();
3267 Dialog * dialog = build(name);
3268 d.dialogs_[name].reset(dialog);
3269 if (lyxrc.allow_geometry_session)
3270 dialog->restoreSession();
3277 void GuiView::showDialog(string const & name, string const & data,
3280 triggerShowDialog(toqstr(name), toqstr(data), inset);
3284 void GuiView::doShowDialog(QString const & qname, QString const & qdata,
3290 const string name = fromqstr(qname);
3291 const string data = fromqstr(qdata);
3295 Dialog * dialog = findOrBuild(name, false);
3297 dialog->showData(data);
3298 if (inset && currentBufferView())
3299 currentBufferView()->editInset(name, inset);
3302 catch (ExceptionMessage const & ex) {
3310 bool GuiView::isDialogVisible(string const & name) const
3312 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3313 if (it == d.dialogs_.end())
3315 return it->second.get()->isVisibleView() && !it->second.get()->isClosing();
3319 void GuiView::hideDialog(string const & name, Inset * inset)
3321 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3322 if (it == d.dialogs_.end())
3325 if (inset && currentBufferView()
3326 && inset != currentBufferView()->editedInset(name))
3329 Dialog * const dialog = it->second.get();
3330 if (dialog->isVisibleView())
3332 if (currentBufferView())
3333 currentBufferView()->editInset(name, 0);
3337 void GuiView::disconnectDialog(string const & name)
3339 if (!isValidName(name))
3341 if (currentBufferView())
3342 currentBufferView()->editInset(name, 0);
3346 void GuiView::hideAll() const
3348 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
3349 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3351 for(; it != end; ++it)
3352 it->second->hideView();
3356 void GuiView::updateDialogs()
3358 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
3359 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3361 for(; it != end; ++it) {
3362 Dialog * dialog = it->second.get();
3363 if (dialog && dialog->isVisibleView())
3364 dialog->checkStatus();
3371 // will be replaced by a proper factory...
3372 Dialog * createGuiAbout(GuiView & lv);
3373 Dialog * createGuiBibitem(GuiView & lv);
3374 Dialog * createGuiBibtex(GuiView & lv);
3375 Dialog * createGuiBox(GuiView & lv);
3376 Dialog * createGuiBranch(GuiView & lv);
3377 Dialog * createGuiChanges(GuiView & lv);
3378 Dialog * createGuiCharacter(GuiView & lv);
3379 Dialog * createGuiCitation(GuiView & lv);
3380 Dialog * createGuiCompare(GuiView & lv);
3381 Dialog * createGuiDelimiter(GuiView & lv);
3382 Dialog * createGuiDocument(GuiView & lv);
3383 Dialog * createGuiErrorList(GuiView & lv);
3384 Dialog * createGuiERT(GuiView & lv);
3385 Dialog * createGuiExternal(GuiView & lv);
3386 Dialog * createGuiFloat(GuiView & lv);
3387 Dialog * createGuiGraphics(GuiView & lv);
3388 Dialog * createGuiInclude(GuiView & lv);
3389 Dialog * createGuiIndex(GuiView & lv);
3390 Dialog * createGuiInfo(GuiView & lv);
3391 Dialog * createGuiLabel(GuiView & lv);
3392 Dialog * createGuiListings(GuiView & lv);
3393 Dialog * createGuiLog(GuiView & lv);
3394 Dialog * createGuiMathHSpace(GuiView & lv);
3395 Dialog * createGuiMathMatrix(GuiView & lv);
3396 Dialog * createGuiNomenclature(GuiView & lv);
3397 Dialog * createGuiNote(GuiView & lv);
3398 Dialog * createGuiParagraph(GuiView & lv);
3399 Dialog * createGuiPhantom(GuiView & lv);
3400 Dialog * createGuiPreferences(GuiView & lv);
3401 Dialog * createGuiPrint(GuiView & lv);
3402 Dialog * createGuiPrintindex(GuiView & lv);
3403 Dialog * createGuiPrintNomencl(GuiView & lv);
3404 Dialog * createGuiRef(GuiView & lv);
3405 Dialog * createGuiSearch(GuiView & lv);
3406 Dialog * createGuiSearchAdv(GuiView & lv);
3407 Dialog * createGuiSendTo(GuiView & lv);
3408 Dialog * createGuiShowFile(GuiView & lv);
3409 Dialog * createGuiSpellchecker(GuiView & lv);
3410 Dialog * createGuiSymbols(GuiView & lv);
3411 Dialog * createGuiTabularCreate(GuiView & lv);
3412 Dialog * createGuiTabular(GuiView & lv);
3413 Dialog * createGuiTexInfo(GuiView & lv);
3414 Dialog * createGuiTextHSpace(GuiView & lv);
3415 Dialog * createGuiToc(GuiView & lv);
3416 Dialog * createGuiThesaurus(GuiView & lv);
3417 Dialog * createGuiHyperlink(GuiView & lv);
3418 Dialog * createGuiVSpace(GuiView & lv);
3419 Dialog * createGuiViewSource(GuiView & lv);
3420 Dialog * createGuiWrap(GuiView & lv);
3421 Dialog * createGuiProgressView(GuiView & lv);
3425 Dialog * GuiView::build(string const & name)
3427 LASSERT(isValidName(name), return 0);
3429 if (name == "aboutlyx")
3430 return createGuiAbout(*this);
3431 if (name == "bibitem")
3432 return createGuiBibitem(*this);
3433 if (name == "bibtex")
3434 return createGuiBibtex(*this);
3436 return createGuiBox(*this);
3437 if (name == "branch")
3438 return createGuiBranch(*this);
3439 if (name == "changes")
3440 return createGuiChanges(*this);
3441 if (name == "character")
3442 return createGuiCharacter(*this);
3443 if (name == "citation")
3444 return createGuiCitation(*this);
3445 if (name == "compare")
3446 return createGuiCompare(*this);
3447 if (name == "document")
3448 return createGuiDocument(*this);
3449 if (name == "errorlist")
3450 return createGuiErrorList(*this);
3452 return createGuiERT(*this);
3453 if (name == "external")
3454 return createGuiExternal(*this);
3456 return createGuiShowFile(*this);
3457 if (name == "findreplace")
3458 return createGuiSearch(*this);
3459 if (name == "findreplaceadv")
3460 return createGuiSearchAdv(*this);
3461 if (name == "float")
3462 return createGuiFloat(*this);
3463 if (name == "graphics")
3464 return createGuiGraphics(*this);
3466 return createGuiHyperlink(*this);
3467 if (name == "include")
3468 return createGuiInclude(*this);
3469 if (name == "index")
3470 return createGuiIndex(*this);
3471 if (name == "index_print")
3472 return createGuiPrintindex(*this);
3474 return createGuiInfo(*this);
3475 if (name == "label")
3476 return createGuiLabel(*this);
3477 if (name == "listings")
3478 return createGuiListings(*this);
3480 return createGuiLog(*this);
3481 if (name == "mathdelimiter")
3482 return createGuiDelimiter(*this);
3483 if (name == "mathspace")
3484 return createGuiMathHSpace(*this);
3485 if (name == "mathmatrix")
3486 return createGuiMathMatrix(*this);
3487 if (name == "nomenclature")
3488 return createGuiNomenclature(*this);
3489 if (name == "nomencl_print")
3490 return createGuiPrintNomencl(*this);
3492 return createGuiNote(*this);
3493 if (name == "paragraph")
3494 return createGuiParagraph(*this);
3495 if (name == "phantom")
3496 return createGuiPhantom(*this);
3497 if (name == "prefs")
3498 return createGuiPreferences(*this);
3499 if (name == "print")
3500 return createGuiPrint(*this);
3502 return createGuiRef(*this);
3503 if (name == "sendto")
3504 return createGuiSendTo(*this);
3505 if (name == "space")
3506 return createGuiTextHSpace(*this);
3507 if (name == "spellchecker")
3508 return createGuiSpellchecker(*this);
3509 if (name == "symbols")
3510 return createGuiSymbols(*this);
3511 if (name == "tabular")
3512 return createGuiTabular(*this);
3513 if (name == "tabularcreate")
3514 return createGuiTabularCreate(*this);
3515 if (name == "texinfo")
3516 return createGuiTexInfo(*this);
3517 if (name == "thesaurus")
3518 return createGuiThesaurus(*this);
3520 return createGuiToc(*this);
3521 if (name == "view-source")
3522 return createGuiViewSource(*this);
3523 if (name == "vspace")
3524 return createGuiVSpace(*this);
3526 return createGuiWrap(*this);
3527 if (name == "progress")
3528 return createGuiProgressView(*this);
3534 } // namespace frontend
3537 #include "moc_GuiView.cpp"