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);
374 #if (QT_VERSION >= 0x040400)
375 connect(&d.autosave_watcher_, SIGNAL(finished()), this,
376 SLOT(threadFinished()));
379 connect(this, SIGNAL(triggerShowDialog(QString const &, QString const &, Inset *)),
380 SLOT(doShowDialog(QString const &, QString const &, Inset *)));
382 // Forbid too small unresizable window because it can happen
383 // with some window manager under X11.
384 setMinimumSize(300, 200);
386 if (lyxrc.allow_geometry_session) {
387 // Now take care of session management.
392 // no session handling, default to a sane size.
393 setGeometry(50, 50, 690, 510);
396 // clear session data if any.
398 settings.remove("views");
408 void GuiView::threadFinished()
410 #if (QT_VERSION >= 0x040400)
411 QFutureWatcher<docstring> const * watcher =
412 static_cast<QFutureWatcher<docstring> const *>(sender());
413 message(watcher->result());
418 void GuiView::saveLayout() const
421 settings.beginGroup("views");
422 settings.beginGroup(QString::number(id_));
424 settings.setValue("pos", pos());
425 settings.setValue("size", size());
427 settings.setValue("geometry", saveGeometry());
429 settings.setValue("layout", saveState(0));
430 settings.setValue("icon_size", iconSize());
434 bool GuiView::restoreLayout()
437 settings.beginGroup("views");
438 settings.beginGroup(QString::number(id_));
439 QString const icon_key = "icon_size";
440 if (!settings.contains(icon_key))
443 //code below is skipped when when ~/.config/LyX is (re)created
444 setIconSize(settings.value(icon_key).toSize());
446 QPoint pos = settings.value("pos", QPoint(50, 50)).toPoint();
447 QSize size = settings.value("size", QSize(690, 510)).toSize();
451 // Work-around for bug #6034: the window ends up in an undetermined
452 // state when trying to restore a maximized window when it is
453 // already maximized.
454 if (!(windowState() & Qt::WindowMaximized))
455 if (!restoreGeometry(settings.value("geometry").toByteArray()))
456 setGeometry(50, 50, 690, 510);
458 // Make sure layout is correctly oriented.
459 setLayoutDirection(qApp->layoutDirection());
461 // Allow the toc and view-source dock widget to be restored if needed.
463 if ((dialog = findOrBuild("toc", true)))
464 // see bug 5082. At least setup title and enabled state.
465 // Visibility will be adjusted by restoreState below.
466 dialog->prepareView();
467 if ((dialog = findOrBuild("view-source", true)))
468 dialog->prepareView();
470 if (!restoreState(settings.value("layout").toByteArray(), 0))
477 GuiToolbar * GuiView::toolbar(string const & name)
479 ToolbarMap::iterator it = d.toolbars_.find(name);
480 if (it != d.toolbars_.end())
483 LYXERR(Debug::GUI, "Toolbar::display: no toolbar named " << name);
484 message(bformat(_("Unknown toolbar \"%1$s\""), from_utf8(name)));
489 void GuiView::constructToolbars()
491 ToolbarMap::iterator it = d.toolbars_.begin();
492 for (; it != d.toolbars_.end(); ++it)
496 // I don't like doing this here, but the standard toolbar
497 // destroys this object when it's destroyed itself (vfr)
498 d.layout_ = new LayoutBox(*this);
499 d.stack_widget_->addWidget(d.layout_);
500 d.layout_->move(0,0);
502 // extracts the toolbars from the backend
503 Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
504 Toolbars::Infos::iterator end = guiApp->toolbars().end();
505 for (; cit != end; ++cit)
506 d.toolbars_[cit->name] = new GuiToolbar(*cit, *this);
510 void GuiView::initToolbars()
512 // extracts the toolbars from the backend
513 Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
514 Toolbars::Infos::iterator end = guiApp->toolbars().end();
515 for (; cit != end; ++cit) {
516 GuiToolbar * tb = toolbar(cit->name);
519 int const visibility = guiApp->toolbars().defaultVisibility(cit->name);
521 tb->setVisible(false);
522 tb->setVisibility(visibility);
524 if (visibility & Toolbars::TOP) {
526 addToolBarBreak(Qt::TopToolBarArea);
527 addToolBar(Qt::TopToolBarArea, tb);
530 if (visibility & Toolbars::BOTTOM) {
531 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
532 #if (QT_VERSION >= 0x040202)
533 addToolBarBreak(Qt::BottomToolBarArea);
535 addToolBar(Qt::BottomToolBarArea, tb);
538 if (visibility & Toolbars::LEFT) {
539 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
540 #if (QT_VERSION >= 0x040202)
541 addToolBarBreak(Qt::LeftToolBarArea);
543 addToolBar(Qt::LeftToolBarArea, tb);
546 if (visibility & Toolbars::RIGHT) {
547 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
548 #if (QT_VERSION >= 0x040202)
549 addToolBarBreak(Qt::RightToolBarArea);
551 addToolBar(Qt::RightToolBarArea, tb);
554 if (visibility & Toolbars::ON)
555 tb->setVisible(true);
560 TocModels & GuiView::tocModels()
562 return d.toc_models_;
566 void GuiView::setFocus()
568 LYXERR(Debug::DEBUG, "GuiView::setFocus()" << this);
569 // Make sure LyXFunc points to the correct view.
570 guiApp->setCurrentView(this);
571 QMainWindow::setFocus();
572 if (d.current_work_area_)
573 d.current_work_area_->setFocus();
577 QMenu * GuiView::createPopupMenu()
579 return d.toolBarPopup(this);
583 void GuiView::showEvent(QShowEvent * e)
585 LYXERR(Debug::GUI, "Passed Geometry "
586 << size().height() << "x" << size().width()
587 << "+" << pos().x() << "+" << pos().y());
589 if (d.splitter_->count() == 0)
590 // No work area, switch to the background widget.
593 QMainWindow::showEvent(e);
597 /** Destroy only all tabbed WorkAreas. Destruction of other WorkAreas
598 ** is responsibility of the container (e.g., dialog)
600 void GuiView::closeEvent(QCloseEvent * close_event)
602 LYXERR(Debug::DEBUG, "GuiView::closeEvent()");
607 // it can happen that this event arrives without selecting the view,
608 // e.g. when clicking the close button on a background window.
610 if (!closeWorkAreaAll()) {
612 close_event->ignore();
616 // Make sure that nothing will use this to be closed View.
617 guiApp->unregisterView(this);
619 if (isFullScreen()) {
620 // Switch off fullscreen before closing.
625 // Make sure the timer time out will not trigger a statusbar update.
626 d.statusbar_timer_.stop();
628 // Saving fullscreen requires additional tweaks in the toolbar code.
629 // It wouldn't also work under linux natively.
630 if (lyxrc.allow_geometry_session) {
631 // Save this window geometry and layout.
633 // Then the toolbar private states.
634 ToolbarMap::iterator end = d.toolbars_.end();
635 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
636 it->second->saveSession();
637 // Now take care of all other dialogs:
638 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
639 for (; it!= d.dialogs_.end(); ++it)
640 it->second->saveSession();
643 close_event->accept();
647 void GuiView::dragEnterEvent(QDragEnterEvent * event)
649 if (event->mimeData()->hasUrls())
651 /// \todo Ask lyx-devel is this is enough:
652 /// if (event->mimeData()->hasFormat("text/plain"))
653 /// event->acceptProposedAction();
657 void GuiView::dropEvent(QDropEvent * event)
659 QList<QUrl> files = event->mimeData()->urls();
663 LYXERR(Debug::GUI, "GuiView::dropEvent: got URLs!");
664 for (int i = 0; i != files.size(); ++i) {
665 string const file = os::internal_path(fromqstr(
666 files.at(i).toLocalFile()));
670 string const ext = support::getExtension(file);
671 vector<const Format *> found_formats;
673 // Find all formats that have the correct extension.
674 vector<const Format *> const & import_formats
675 = theConverters().importableFormats();
676 vector<const Format *>::const_iterator it = import_formats.begin();
677 for (; it != import_formats.end(); ++it)
678 if ((*it)->extension() == ext)
679 found_formats.push_back(*it);
682 if (found_formats.size() >= 1) {
683 if (found_formats.size() > 1) {
684 //FIXME: show a dialog to choose the correct importable format
686 "Multiple importable formats found, selecting first");
688 string const arg = found_formats[0]->name() + " " + file;
689 cmd = FuncRequest(LFUN_BUFFER_IMPORT, arg);
692 //FIXME: do we have to explicitly check whether it's a lyx file?
694 "No formats found, trying to open it as a lyx file");
695 cmd = FuncRequest(LFUN_FILE_OPEN, file);
698 // Asynchronously post the event. DropEvent usually come
699 // from the BufferView. But reloading a file might close
700 // the BufferView from within its own event handler.
701 guiApp->dispatchDelayed(cmd);
707 void GuiView::message(docstring const & str)
709 if (ForkedProcess::iAmAChild())
712 // call is moved to GUI-thread by GuiProgress
713 d.progress_->appendMessage(toqstr(str));
717 void GuiView::updateMessage(QString const & str)
719 statusBar()->showMessage(str);
720 d.statusbar_timer_.stop();
721 d.statusbar_timer_.start(3000);
725 void GuiView::smallSizedIcons()
727 setIconSize(QSize(d.smallIconSize, d.smallIconSize));
731 void GuiView::normalSizedIcons()
733 setIconSize(QSize(d.normalIconSize, d.normalIconSize));
737 void GuiView::bigSizedIcons()
739 setIconSize(QSize(d.bigIconSize, d.bigIconSize));
743 void GuiView::clearMessage()
745 // FIXME: This code was introduced in r19643 to fix bug #4123. However,
746 // the hasFocus function mostly returns false, even if the focus is on
747 // a workarea in this view.
751 d.statusbar_timer_.stop();
755 void GuiView::updateWindowTitle(GuiWorkArea * wa)
757 if (wa != d.current_work_area_)
759 setWindowTitle(qt_("LyX: ") + wa->windowTitle());
760 setWindowIconText(wa->windowIconText());
764 void GuiView::on_currentWorkAreaChanged(GuiWorkArea * wa)
767 disconnectBufferView();
768 connectBufferView(wa->bufferView());
769 connectBuffer(wa->bufferView().buffer());
770 d.current_work_area_ = wa;
771 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
772 this, SLOT(updateWindowTitle(GuiWorkArea *)));
773 updateWindowTitle(wa);
777 // The document settings needs to be reinitialised.
778 updateDialog("document", "");
780 // Buffer-dependent dialogs must be updated. This is done here because
781 // some dialogs require buffer()->text.
786 void GuiView::on_lastWorkAreaRemoved()
789 // We already are in a close event. Nothing more to do.
792 if (d.splitter_->count() > 1)
793 // We have a splitter so don't close anything.
796 // Reset and updates the dialogs.
797 d.toc_models_.reset(0);
798 updateDialog("document", "");
801 resetWindowTitleAndIconText();
804 if (lyxrc.open_buffers_in_tabs)
805 // Nothing more to do, the window should stay open.
808 if (guiApp->viewIds().size() > 1) {
814 // On Mac we also close the last window because the application stay
815 // resident in memory. On other platforms we don't close the last
816 // window because this would quit the application.
822 void GuiView::updateStatusBar()
824 // let the user see the explicit message
825 if (d.statusbar_timer_.isActive())
832 void GuiView::showMessage()
834 QString msg = toqstr(theGuiApp()->viewStatusMessage());
836 BufferView const * bv = currentBufferView();
838 msg = toqstr(bv->cursor().currentState());
840 msg = qt_("Welcome to LyX!");
842 statusBar()->showMessage(msg);
846 bool GuiView::event(QEvent * e)
850 // Useful debug code:
851 //case QEvent::ActivationChange:
852 //case QEvent::WindowDeactivate:
853 //case QEvent::Paint:
854 //case QEvent::Enter:
855 //case QEvent::Leave:
856 //case QEvent::HoverEnter:
857 //case QEvent::HoverLeave:
858 //case QEvent::HoverMove:
859 //case QEvent::StatusTip:
860 //case QEvent::DragEnter:
861 //case QEvent::DragLeave:
865 case QEvent::WindowActivate: {
866 GuiView * old_view = guiApp->currentView();
867 if (this == old_view) {
869 return QMainWindow::event(e);
871 if (old_view && old_view->currentBufferView()) {
872 // save current selection to the selection buffer to allow
873 // middle-button paste in this window.
874 cap::saveSelection(old_view->currentBufferView()->cursor());
876 guiApp->setCurrentView(this);
877 if (d.current_work_area_) {
878 BufferView & bv = d.current_work_area_->bufferView();
879 connectBufferView(bv);
880 connectBuffer(bv.buffer());
881 // The document structure, name and dialogs might have
882 // changed in another view.
884 // The document settings needs to be reinitialised.
885 updateDialog("document", "");
888 resetWindowTitleAndIconText();
891 return QMainWindow::event(e);
894 case QEvent::ShortcutOverride: {
897 #if (!defined Q_WS_X11) || (QT_VERSION >= 0x040500)
898 if (isFullScreen() && menuBar()->isHidden()) {
899 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
900 // FIXME: we should also try to detect special LyX shortcut such as
901 // Alt-P and Alt-M. Right now there is a hack in
902 // GuiWorkArea::processKeySym() that hides again the menubar for
904 if (ke->modifiers() & Qt::AltModifier && ke->key() != Qt::Key_Alt) {
906 return QMainWindow::event(e);
911 if (d.current_work_area_)
912 // Nothing special to do.
913 return QMainWindow::event(e);
915 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
916 // Let Qt handle menu access and the Tab keys to navigate keys to navigate
918 if (ke->modifiers() & Qt::AltModifier || ke->key() == Qt::Key_Tab
919 || ke->key() == Qt::Key_Backtab)
920 return QMainWindow::event(e);
922 // Allow processing of shortcuts that are allowed even when no Buffer
925 setKeySymbol(&sym, ke);
926 guiApp->processKeySym(sym, q_key_state(ke->modifiers()));
932 return QMainWindow::event(e);
936 void GuiView::resetWindowTitleAndIconText()
938 setWindowTitle(qt_("LyX"));
939 setWindowIconText(qt_("LyX"));
942 bool GuiView::focusNextPrevChild(bool /*next*/)
949 void GuiView::setBusy(bool busy)
951 if (d.current_work_area_) {
952 d.current_work_area_->setUpdatesEnabled(!busy);
954 d.current_work_area_->stopBlinkingCursor();
956 d.current_work_area_->startBlinkingCursor();
960 QApplication::setOverrideCursor(Qt::WaitCursor);
962 QApplication::restoreOverrideCursor();
966 GuiWorkArea * GuiView::workArea(Buffer & buffer)
968 if (currentWorkArea()
969 && ¤tWorkArea()->bufferView().buffer() == &buffer)
970 return (GuiWorkArea *) currentWorkArea();
971 if (TabWorkArea * twa = d.currentTabWorkArea())
972 return twa->workArea(buffer);
977 GuiWorkArea * GuiView::addWorkArea(Buffer & buffer)
979 // Automatically create a TabWorkArea if there are none yet.
980 TabWorkArea * tab_widget = d.splitter_->count()
981 ? d.currentTabWorkArea() : addTabWorkArea();
982 return tab_widget->addWorkArea(buffer, *this);
986 TabWorkArea * GuiView::addTabWorkArea()
988 TabWorkArea * twa = new TabWorkArea;
989 QObject::connect(twa, SIGNAL(currentWorkAreaChanged(GuiWorkArea *)),
990 this, SLOT(on_currentWorkAreaChanged(GuiWorkArea *)));
991 QObject::connect(twa, SIGNAL(lastWorkAreaRemoved()),
992 this, SLOT(on_lastWorkAreaRemoved()));
994 d.splitter_->addWidget(twa);
995 d.stack_widget_->setCurrentWidget(d.splitter_);
1000 GuiWorkArea const * GuiView::currentWorkArea() const
1002 return d.current_work_area_;
1006 GuiWorkArea * GuiView::currentWorkArea()
1008 return d.current_work_area_;
1012 GuiWorkArea const * GuiView::currentMainWorkArea() const
1014 if (d.currentTabWorkArea() == NULL)
1016 return d.currentTabWorkArea()->currentWorkArea();
1020 GuiWorkArea * GuiView::currentMainWorkArea()
1022 if (d.currentTabWorkArea() == NULL)
1024 return d.currentTabWorkArea()->currentWorkArea();
1028 void GuiView::setCurrentWorkArea(GuiWorkArea * wa)
1030 LYXERR(Debug::DEBUG, "Setting current wa: " << wa << endl);
1032 d.current_work_area_ = NULL;
1036 GuiWorkArea * old_gwa = theGuiApp()->currentView()->currentWorkArea();
1040 if (currentBufferView())
1041 cap::saveSelection(currentBufferView()->cursor());
1043 theGuiApp()->setCurrentView(this);
1044 d.current_work_area_ = wa;
1045 for (int i = 0; i != d.splitter_->count(); ++i) {
1046 if (d.tabWorkArea(i)->setCurrentWorkArea(wa)) {
1047 //if (d.current_main_work_area_)
1048 // d.current_main_work_area_->setFrameStyle(QFrame::NoFrame);
1049 d.current_main_work_area_ = wa;
1050 //d.current_main_work_area_->setFrameStyle(QFrame::Box | QFrame::Plain);
1051 //d.current_main_work_area_->setLineWidth(2);
1052 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() << ", Current main wa: " << currentMainWorkArea());
1056 LYXERR(Debug::DEBUG, "This is not a tabbed wa");
1057 on_currentWorkAreaChanged(wa);
1058 BufferView & bv = wa->bufferView();
1059 bv.cursor().fixIfBroken();
1061 wa->setUpdatesEnabled(true);
1062 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() << ", Current main wa: " << currentMainWorkArea());
1066 void GuiView::removeWorkArea(GuiWorkArea * wa)
1068 LASSERT(wa, return);
1069 if (wa == d.current_work_area_) {
1071 disconnectBufferView();
1072 d.current_work_area_ = 0;
1073 d.current_main_work_area_ = 0;
1076 bool found_twa = false;
1077 for (int i = 0; i != d.splitter_->count(); ++i) {
1078 TabWorkArea * twa = d.tabWorkArea(i);
1079 if (twa->removeWorkArea(wa)) {
1080 // Found in this tab group, and deleted the GuiWorkArea.
1082 if (twa->count() != 0) {
1083 if (d.current_work_area_ == 0)
1084 // This means that we are closing the current GuiWorkArea, so
1085 // switch to the next GuiWorkArea in the found TabWorkArea.
1086 setCurrentWorkArea(twa->currentWorkArea());
1088 // No more WorkAreas in this tab group, so delete it.
1095 // It is not a tabbed work area (i.e., the search work area), so it
1096 // should be deleted by other means.
1097 LASSERT(found_twa, /* */);
1099 if (d.current_work_area_ == 0) {
1100 if (d.splitter_->count() != 0) {
1101 TabWorkArea * twa = d.currentTabWorkArea();
1102 setCurrentWorkArea(twa->currentWorkArea());
1104 // No more work areas, switch to the background widget.
1105 setCurrentWorkArea(0);
1111 LayoutBox * GuiView::getLayoutDialog() const
1117 void GuiView::updateLayoutList()
1120 d.layout_->updateContents(false);
1124 void GuiView::updateToolbars()
1126 ToolbarMap::iterator end = d.toolbars_.end();
1127 if (d.current_work_area_) {
1129 d.current_work_area_->bufferView().cursor().inMathed();
1131 lyx::getStatus(FuncRequest(LFUN_LAYOUT_TABULAR)).enabled();
1133 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).enabled() &&
1134 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).onoff(true);
1135 bool const mathmacrotemplate =
1136 lyx::getStatus(FuncRequest(LFUN_IN_MATHMACROTEMPLATE)).enabled();
1138 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1139 it->second->update(math, table, review, mathmacrotemplate);
1141 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1142 it->second->update(false, false, false, false);
1146 void GuiView::setBuffer(Buffer * newBuffer)
1148 LYXERR(Debug::DEBUG, "Setting buffer: " << newBuffer << endl);
1149 LASSERT(newBuffer, return);
1152 GuiWorkArea * wa = workArea(*newBuffer);
1154 newBuffer->masterBuffer()->updateLabels();
1155 wa = addWorkArea(*newBuffer);
1157 //Disconnect the old buffer...there's no new one.
1160 connectBuffer(*newBuffer);
1161 connectBufferView(wa->bufferView());
1162 setCurrentWorkArea(wa);
1168 void GuiView::connectBuffer(Buffer & buf)
1170 buf.setGuiDelegate(this);
1174 void GuiView::disconnectBuffer()
1176 if (d.current_work_area_)
1177 d.current_work_area_->bufferView().buffer().setGuiDelegate(0);
1181 void GuiView::connectBufferView(BufferView & bv)
1183 bv.setGuiDelegate(this);
1187 void GuiView::disconnectBufferView()
1189 if (d.current_work_area_)
1190 d.current_work_area_->bufferView().setGuiDelegate(0);
1194 void GuiView::errors(string const & error_type, bool from_master)
1196 ErrorList & el = from_master ?
1197 documentBufferView()->buffer().masterBuffer()->errorList(error_type)
1198 : documentBufferView()->buffer().errorList(error_type);
1199 string data = error_type;
1201 data = "from_master|" + error_type;
1203 showDialog("errorlist", data);
1207 void GuiView::updateTocItem(string const & type, DocIterator const & dit)
1209 d.toc_models_.updateItem(toqstr(type), dit);
1213 void GuiView::structureChanged()
1215 d.toc_models_.reset(documentBufferView());
1216 // Navigator needs more than a simple update in this case. It needs to be
1218 updateDialog("toc", "");
1222 void GuiView::updateDialog(string const & name, string const & data)
1224 if (!isDialogVisible(name))
1227 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
1228 if (it == d.dialogs_.end())
1231 Dialog * const dialog = it->second.get();
1232 if (dialog->isVisibleView())
1233 dialog->initialiseParams(data);
1237 BufferView * GuiView::documentBufferView()
1239 return currentMainWorkArea()
1240 ? ¤tMainWorkArea()->bufferView()
1245 BufferView const * GuiView::documentBufferView() const
1247 return currentMainWorkArea()
1248 ? ¤tMainWorkArea()->bufferView()
1253 BufferView * GuiView::currentBufferView()
1255 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1259 BufferView const * GuiView::currentBufferView() const
1261 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1265 static docstring saveAndDestroyBuffer(Buffer * buffer, FileName const & fname)
1268 FileName const tmp_ret = FileName::tempName("lyxauto");
1269 if (!tmp_ret.empty()) {
1270 if (buffer->writeFile(tmp_ret))
1271 failed = !tmp_ret.moveTo(fname);
1274 // failed to write/rename tmp_ret so try writing direct
1275 failed = buffer->writeFile(fname);
1279 ? _("Automatic save failed!")
1280 : _("Automatic save done.");
1284 void GuiView::autoSave()
1286 LYXERR(Debug::INFO, "Running autoSave()");
1288 Buffer * buffer = documentBufferView()
1289 ? &documentBufferView()->buffer() : 0;
1293 #if (QT_VERSION >= 0x040400)
1294 QFuture<docstring> f = QtConcurrent::run(saveAndDestroyBuffer, buffer->clone(),
1295 buffer->getAutosaveFilename());
1296 d.autosave_watcher_.setFuture(f);
1303 void GuiView::resetAutosaveTimers()
1306 d.autosave_timeout_.restart();
1310 bool GuiView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1313 Buffer * buf = currentBufferView()
1314 ? ¤tBufferView()->buffer() : 0;
1315 Buffer * doc_buffer = documentBufferView()
1316 ? &(documentBufferView()->buffer()) : 0;
1318 // Check whether we need a buffer
1319 if (!lyxaction.funcHasFlag(cmd.action, LyXAction::NoBuffer) && !buf) {
1320 // no, exit directly
1321 flag.message(from_utf8(N_("Command not allowed with"
1322 "out any document open")));
1323 flag.setEnabled(false);
1327 if (cmd.origin == FuncRequest::TOC) {
1328 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
1330 if (toc->getStatus(documentBufferView()->cursor(), cmd, fs))
1333 flag.setEnabled(false);
1337 switch(cmd.action) {
1338 case LFUN_BUFFER_IMPORT:
1341 case LFUN_MASTER_BUFFER_UPDATE:
1342 case LFUN_MASTER_BUFFER_VIEW:
1343 enable = doc_buffer && doc_buffer->parent() != 0
1344 && !d.preview_watcher_.isRunning();
1347 case LFUN_BUFFER_UPDATE:
1348 case LFUN_BUFFER_VIEW: {
1349 if (!doc_buffer || d.preview_watcher_.isRunning()) {
1353 string format = to_utf8(cmd.argument());
1354 if (cmd.argument().empty())
1355 format = doc_buffer->getDefaultOutputFormat();
1356 enable = doc_buffer->isExportableFormat(format);
1360 case LFUN_BUFFER_RELOAD:
1361 enable = doc_buffer && !doc_buffer->isUnnamed()
1362 && doc_buffer->fileName().exists()
1363 && (!doc_buffer->isClean()
1364 || doc_buffer->isExternallyModified(Buffer::timestamp_method));
1367 case LFUN_BUFFER_CHILD_OPEN:
1368 enable = doc_buffer;
1371 case LFUN_BUFFER_WRITE:
1372 enable = doc_buffer && (doc_buffer->isUnnamed() || !doc_buffer->isClean());
1375 //FIXME: This LFUN should be moved to GuiApplication.
1376 case LFUN_BUFFER_WRITE_ALL: {
1377 // We enable the command only if there are some modified buffers
1378 Buffer * first = theBufferList().first();
1383 // We cannot use a for loop as the buffer list is a cycle.
1385 if (!b->isClean()) {
1389 b = theBufferList().next(b);
1390 } while (b != first);
1394 case LFUN_BUFFER_WRITE_AS:
1395 enable = doc_buffer;
1398 case LFUN_BUFFER_CLOSE:
1399 enable = doc_buffer;
1402 case LFUN_BUFFER_CLOSE_ALL:
1403 enable = theBufferList().last() != theBufferList().first();
1406 case LFUN_SPLIT_VIEW:
1407 if (cmd.getArg(0) == "vertical")
1408 enable = doc_buffer && (d.splitter_->count() == 1 ||
1409 d.splitter_->orientation() == Qt::Vertical);
1411 enable = doc_buffer && (d.splitter_->count() == 1 ||
1412 d.splitter_->orientation() == Qt::Horizontal);
1415 case LFUN_CLOSE_TAB_GROUP:
1416 enable = d.currentTabWorkArea();
1419 case LFUN_TOOLBAR_TOGGLE:
1420 if (GuiToolbar * t = toolbar(cmd.getArg(0)))
1421 flag.setOnOff(t->isVisible());
1424 case LFUN_DROP_LAYOUTS_CHOICE:
1428 case LFUN_UI_TOGGLE:
1429 flag.setOnOff(isFullScreen());
1432 case LFUN_DIALOG_DISCONNECT_INSET:
1435 case LFUN_DIALOG_HIDE:
1436 // FIXME: should we check if the dialog is shown?
1439 case LFUN_DIALOG_TOGGLE:
1440 flag.setOnOff(isDialogVisible(cmd.getArg(0)));
1441 // fall through to set "enable"
1442 case LFUN_DIALOG_SHOW: {
1443 string const name = cmd.getArg(0);
1445 enable = name == "aboutlyx"
1446 || name == "file" //FIXME: should be removed.
1448 || name == "texinfo"
1449 || name == "progress"
1450 || name == "compare";
1451 else if (name == "print")
1452 enable = doc_buffer->isExportable("dvi")
1453 && lyxrc.print_command != "none";
1454 else if (name == "character" || name == "symbols") {
1455 if (!buf || buf->isReadonly()
1456 || !currentBufferView()->cursor().inTexted())
1459 // FIXME we should consider passthru
1461 Inset const & in = currentBufferView()->cursor().inset();
1462 enable = !in.getLayout().isPassThru();
1465 else if (name == "latexlog")
1466 enable = FileName(doc_buffer->logName()).isReadableFile();
1467 else if (name == "spellchecker")
1468 enable = theSpellChecker() && !doc_buffer->isReadonly();
1469 else if (name == "vclog")
1470 enable = doc_buffer->lyxvc().inUse();
1474 case LFUN_DIALOG_UPDATE: {
1475 string const name = cmd.getArg(0);
1477 enable = name == "prefs";
1481 case LFUN_COMMAND_EXECUTE:
1483 case LFUN_MENU_OPEN:
1484 // Nothing to check.
1487 case LFUN_COMPLETION_INLINE:
1488 if (!d.current_work_area_
1489 || !d.current_work_area_->completer().inlinePossible(
1490 currentBufferView()->cursor()))
1494 case LFUN_COMPLETION_POPUP:
1495 if (!d.current_work_area_
1496 || !d.current_work_area_->completer().popupPossible(
1497 currentBufferView()->cursor()))
1501 case LFUN_COMPLETION_COMPLETE:
1502 if (!d.current_work_area_
1503 || !d.current_work_area_->completer().inlinePossible(
1504 currentBufferView()->cursor()))
1508 case LFUN_COMPLETION_ACCEPT:
1509 if (!d.current_work_area_
1510 || (!d.current_work_area_->completer().popupVisible()
1511 && !d.current_work_area_->completer().inlineVisible()
1512 && !d.current_work_area_->completer().completionAvailable()))
1516 case LFUN_COMPLETION_CANCEL:
1517 if (!d.current_work_area_
1518 || (!d.current_work_area_->completer().popupVisible()
1519 && !d.current_work_area_->completer().inlineVisible()))
1523 case LFUN_BUFFER_ZOOM_OUT:
1524 enable = doc_buffer && lyxrc.zoom > 10;
1527 case LFUN_BUFFER_ZOOM_IN:
1528 enable = doc_buffer;
1531 case LFUN_BUFFER_NEXT:
1532 case LFUN_BUFFER_PREVIOUS:
1533 // FIXME: should we check is there is an previous or next buffer?
1535 case LFUN_BUFFER_SWITCH:
1536 // toggle on the current buffer, but do not toggle off
1537 // the other ones (is that a good idea?)
1539 && to_utf8(cmd.argument()) == doc_buffer->absFileName())
1540 flag.setOnOff(true);
1543 case LFUN_VC_REGISTER:
1544 enable = doc_buffer && !doc_buffer->lyxvc().inUse();
1546 case LFUN_VC_CHECK_IN:
1547 enable = doc_buffer && doc_buffer->lyxvc().checkInEnabled();
1549 case LFUN_VC_CHECK_OUT:
1550 enable = doc_buffer && doc_buffer->lyxvc().checkOutEnabled();
1552 case LFUN_VC_LOCKING_TOGGLE:
1553 enable = doc_buffer && !doc_buffer->isReadonly()
1554 && doc_buffer->lyxvc().lockingToggleEnabled();
1555 flag.setOnOff(enable && !doc_buffer->lyxvc().locker().empty());
1557 case LFUN_VC_REVERT:
1558 enable = doc_buffer && doc_buffer->lyxvc().inUse();
1560 case LFUN_VC_UNDO_LAST:
1561 enable = doc_buffer && doc_buffer->lyxvc().undoLastEnabled();
1563 case LFUN_VC_REPO_UPDATE:
1564 enable = doc_buffer && doc_buffer->lyxvc().inUse();
1566 case LFUN_VC_COMMAND: {
1567 if (cmd.argument().empty())
1569 if (!doc_buffer && contains(cmd.getArg(0), 'D'))
1574 case LFUN_SERVER_GOTO_FILE_ROW:
1582 flag.setEnabled(false);
1588 static FileName selectTemplateFile()
1590 FileDialog dlg(qt_("Select template file"));
1591 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1592 dlg.setButton1(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
1594 FileDialog::Result result = dlg.open(toqstr(lyxrc.template_path),
1595 QStringList(qt_("LyX Documents (*.lyx)")));
1597 if (result.first == FileDialog::Later)
1599 if (result.second.isEmpty())
1601 return FileName(fromqstr(result.second));
1605 Buffer * GuiView::loadDocument(FileName const & filename, bool tolastfiles)
1609 Buffer * newBuffer = checkAndLoadLyXFile(filename);
1612 message(_("Document not loaded."));
1617 setBuffer(newBuffer);
1619 // scroll to the position when the file was last closed
1620 if (lyxrc.use_lastfilepos) {
1621 LastFilePosSection::FilePos filepos =
1622 theSession().lastFilePos().load(filename);
1623 documentBufferView()->moveToPosition(filepos.pit, filepos.pos, 0, 0);
1627 theSession().lastFiles().add(filename);
1634 void GuiView::openDocument(string const & fname)
1636 string initpath = lyxrc.document_path;
1638 if (documentBufferView()) {
1639 string const trypath = documentBufferView()->buffer().filePath();
1640 // If directory is writeable, use this as default.
1641 if (FileName(trypath).isDirWritable())
1647 if (fname.empty()) {
1648 FileDialog dlg(qt_("Select document to open"), LFUN_FILE_OPEN);
1649 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1650 dlg.setButton2(qt_("Examples|#E#e"),
1651 toqstr(addPath(package().system_support().absFilename(), "examples")));
1653 QStringList filter(qt_("LyX Documents (*.lyx)"));
1654 filter << qt_("LyX-1.3.x Documents (*.lyx13)")
1655 << qt_("LyX-1.4.x Documents (*.lyx14)")
1656 << qt_("LyX-1.5.x Documents (*.lyx15)")
1657 << qt_("LyX-1.6.x Documents (*.lyx16)");
1658 FileDialog::Result result =
1659 dlg.open(toqstr(initpath), filter);
1661 if (result.first == FileDialog::Later)
1664 filename = fromqstr(result.second);
1666 // check selected filename
1667 if (filename.empty()) {
1668 message(_("Canceled."));
1674 // get absolute path of file and add ".lyx" to the filename if
1676 FileName const fullname =
1677 fileSearch(string(), filename, "lyx", support::may_not_exist);
1678 if (!fullname.empty())
1679 filename = fullname.absFilename();
1681 if (!fullname.onlyPath().isDirectory()) {
1682 Alert::warning(_("Invalid filename"),
1683 bformat(_("The directory in the given path\n%1$s\ndoes not exist."),
1684 from_utf8(fullname.absFilename())));
1687 // if the file doesn't exist, let the user create one
1688 if (!fullname.exists()) {
1689 // the user specifically chose this name. Believe him.
1690 Buffer * const b = newFile(filename, string(), true);
1696 docstring const disp_fn = makeDisplayPath(filename);
1697 message(bformat(_("Opening document %1$s..."), disp_fn));
1700 Buffer * buf = loadDocument(fullname);
1702 buf->updateLabels();
1704 buf->errors("Parse");
1705 str2 = bformat(_("Document %1$s opened."), disp_fn);
1706 if (buf->lyxvc().inUse())
1707 str2 += " " + from_utf8(buf->lyxvc().versionString()) +
1708 " " + _("Version control detected.");
1710 str2 = bformat(_("Could not open document %1$s"), disp_fn);
1715 // FIXME: clean that
1716 static bool import(GuiView * lv, FileName const & filename,
1717 string const & format, ErrorList & errorList)
1719 FileName const lyxfile(support::changeExtension(filename.absFilename(), ".lyx"));
1721 string loader_format;
1722 vector<string> loaders = theConverters().loaders();
1723 if (find(loaders.begin(), loaders.end(), format) == loaders.end()) {
1724 for (vector<string>::const_iterator it = loaders.begin();
1725 it != loaders.end(); ++it) {
1726 if (!theConverters().isReachable(format, *it))
1729 string const tofile =
1730 support::changeExtension(filename.absFilename(),
1731 formats.extension(*it));
1732 if (!theConverters().convert(0, filename, FileName(tofile),
1733 filename, format, *it, errorList))
1735 loader_format = *it;
1738 if (loader_format.empty()) {
1739 frontend::Alert::error(_("Couldn't import file"),
1740 bformat(_("No information for importing the format %1$s."),
1741 formats.prettyName(format)));
1745 loader_format = format;
1747 if (loader_format == "lyx") {
1748 Buffer * buf = lv->loadDocument(lyxfile);
1751 buf->updateLabels();
1753 buf->errors("Parse");
1755 Buffer * const b = newFile(lyxfile.absFilename(), string(), true);
1759 bool as_paragraphs = loader_format == "textparagraph";
1760 string filename2 = (loader_format == format) ? filename.absFilename()
1761 : support::changeExtension(filename.absFilename(),
1762 formats.extension(loader_format));
1763 lv->currentBufferView()->insertPlaintextFile(FileName(filename2),
1765 guiApp->setCurrentView(lv);
1766 lyx::dispatch(FuncRequest(LFUN_MARK_OFF));
1773 void GuiView::importDocument(string const & argument)
1776 string filename = split(argument, format, ' ');
1778 LYXERR(Debug::INFO, format << " file: " << filename);
1780 // need user interaction
1781 if (filename.empty()) {
1782 string initpath = lyxrc.document_path;
1783 if (documentBufferView()) {
1784 string const trypath = documentBufferView()->buffer().filePath();
1785 // If directory is writeable, use this as default.
1786 if (FileName(trypath).isDirWritable())
1790 docstring const text = bformat(_("Select %1$s file to import"),
1791 formats.prettyName(format));
1793 FileDialog dlg(toqstr(text), LFUN_BUFFER_IMPORT);
1794 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1795 dlg.setButton2(qt_("Examples|#E#e"),
1796 toqstr(addPath(package().system_support().absFilename(), "examples")));
1798 docstring filter = formats.prettyName(format);
1801 filter += from_utf8(formats.extension(format));
1804 FileDialog::Result result =
1805 dlg.open(toqstr(initpath), fileFilters(toqstr(filter)));
1807 if (result.first == FileDialog::Later)
1810 filename = fromqstr(result.second);
1812 // check selected filename
1813 if (filename.empty())
1814 message(_("Canceled."));
1817 if (filename.empty())
1820 // get absolute path of file
1821 FileName const fullname(support::makeAbsPath(filename));
1823 FileName const lyxfile(support::changeExtension(fullname.absFilename(), ".lyx"));
1825 // Check if the document already is open
1826 Buffer * buf = theBufferList().getBuffer(lyxfile);
1829 if (!closeBuffer()) {
1830 message(_("Canceled."));
1835 docstring const displaypath = makeDisplayPath(lyxfile.absFilename(), 30);
1837 // if the file exists already, and we didn't do
1838 // -i lyx thefile.lyx, warn
1839 if (lyxfile.exists() && fullname != lyxfile) {
1841 docstring text = bformat(_("The document %1$s already exists.\n\n"
1842 "Do you want to overwrite that document?"), displaypath);
1843 int const ret = Alert::prompt(_("Overwrite document?"),
1844 text, 0, 1, _("&Overwrite"), _("&Cancel"));
1847 message(_("Canceled."));
1852 message(bformat(_("Importing %1$s..."), displaypath));
1853 ErrorList errorList;
1854 if (import(this, fullname, format, errorList))
1855 message(_("imported."));
1857 message(_("file not imported!"));
1859 // FIXME (Abdel 12/08/06): Is there a need to display the error list here?
1863 void GuiView::newDocument(string const & filename, bool from_template)
1865 FileName initpath(lyxrc.document_path);
1866 if (documentBufferView()) {
1867 FileName const trypath(documentBufferView()->buffer().filePath());
1868 // If directory is writeable, use this as default.
1869 if (trypath.isDirWritable())
1873 string templatefile;
1874 if (from_template) {
1875 templatefile = selectTemplateFile().absFilename();
1876 if (templatefile.empty())
1881 if (filename.empty())
1882 b = newUnnamedFile(initpath, to_utf8(_("newfile")), templatefile);
1884 b = newFile(filename, templatefile, true);
1889 // If no new document could be created, it is unsure
1890 // whether there is a valid BufferView.
1891 if (currentBufferView())
1892 // Ensure the cursor is correctly positioned on screen.
1893 currentBufferView()->showCursor();
1897 void GuiView::insertLyXFile(docstring const & fname)
1899 BufferView * bv = documentBufferView();
1904 FileName filename(to_utf8(fname));
1906 if (!filename.empty()) {
1907 bv->insertLyXFile(filename);
1911 // Launch a file browser
1913 string initpath = lyxrc.document_path;
1914 string const trypath = bv->buffer().filePath();
1915 // If directory is writeable, use this as default.
1916 if (FileName(trypath).isDirWritable())
1920 FileDialog dlg(qt_("Select LyX document to insert"), LFUN_FILE_INSERT);
1921 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1922 dlg.setButton2(qt_("Examples|#E#e"),
1923 toqstr(addPath(package().system_support().absFilename(),
1926 FileDialog::Result result = dlg.open(toqstr(initpath),
1927 QStringList(qt_("LyX Documents (*.lyx)")));
1929 if (result.first == FileDialog::Later)
1933 filename.set(fromqstr(result.second));
1935 // check selected filename
1936 if (filename.empty()) {
1937 // emit message signal.
1938 message(_("Canceled."));
1942 bv->insertLyXFile(filename);
1946 void GuiView::insertPlaintextFile(docstring const & fname,
1949 BufferView * bv = documentBufferView();
1953 if (!fname.empty() && !FileName::isAbsolute(to_utf8(fname))) {
1954 message(_("Absolute filename expected."));
1959 FileName filename(to_utf8(fname));
1961 if (!filename.empty()) {
1962 bv->insertPlaintextFile(filename, asParagraph);
1966 FileDialog dlg(qt_("Select file to insert"), (asParagraph ?
1967 LFUN_FILE_INSERT_PLAINTEXT_PARA : LFUN_FILE_INSERT_PLAINTEXT));
1969 FileDialog::Result result = dlg.open(toqstr(bv->buffer().filePath()),
1970 QStringList(qt_("All Files (*)")));
1972 if (result.first == FileDialog::Later)
1976 filename.set(fromqstr(result.second));
1978 // check selected filename
1979 if (filename.empty()) {
1980 // emit message signal.
1981 message(_("Canceled."));
1985 bv->insertPlaintextFile(filename, asParagraph);
1989 bool GuiView::renameBuffer(Buffer & b, docstring const & newname)
1991 FileName fname = b.fileName();
1992 FileName const oldname = fname;
1994 if (!newname.empty()) {
1996 fname = support::makeAbsPath(to_utf8(newname), oldname.onlyPath().absFilename());
1998 // Switch to this Buffer.
2001 // No argument? Ask user through dialog.
2003 FileDialog dlg(qt_("Choose a filename to save document as"),
2004 LFUN_BUFFER_WRITE_AS);
2005 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2006 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
2008 if (!isLyXFilename(fname.absFilename()))
2009 fname.changeExtension(".lyx");
2011 FileDialog::Result result =
2012 dlg.save(toqstr(fname.onlyPath().absFilename()),
2013 QStringList(qt_("LyX Documents (*.lyx)")),
2014 toqstr(fname.onlyFileName()));
2016 if (result.first == FileDialog::Later)
2019 fname.set(fromqstr(result.second));
2024 if (!isLyXFilename(fname.absFilename()))
2025 fname.changeExtension(".lyx");
2028 if (FileName(fname).exists()) {
2029 docstring const file = makeDisplayPath(fname.absFilename(), 30);
2030 docstring text = bformat(_("The document %1$s already "
2031 "exists.\n\nDo you want to "
2032 "overwrite that document?"),
2034 int const ret = Alert::prompt(_("Overwrite document?"),
2035 text, 0, 2, _("&Overwrite"), _("&Rename"), _("&Cancel"));
2038 case 1: return renameBuffer(b, docstring());
2039 case 2: return false;
2043 FileName oldauto = b.getAutosaveFilename();
2045 // Ok, change the name of the buffer
2046 b.setFileName(fname.absFilename());
2048 bool unnamed = b.isUnnamed();
2049 b.setUnnamed(false);
2050 b.saveCheckSum(fname);
2052 // bring the autosave file with us, just in case.
2053 b.moveAutosaveFile(oldauto);
2055 if (!saveBuffer(b)) {
2056 oldauto = b.getAutosaveFilename();
2057 b.setFileName(oldname.absFilename());
2058 b.setUnnamed(unnamed);
2059 b.saveCheckSum(oldname);
2060 b.moveAutosaveFile(oldauto);
2068 bool GuiView::saveBuffer(Buffer & b)
2070 if (workArea(b) && workArea(b)->inDialogMode())
2074 return renameBuffer(b, docstring());
2077 theSession().lastFiles().add(b.fileName());
2081 // Switch to this Buffer.
2084 // FIXME: we don't tell the user *WHY* the save failed !!
2085 docstring const file = makeDisplayPath(b.absFileName(), 30);
2086 docstring text = bformat(_("The document %1$s could not be saved.\n\n"
2087 "Do you want to rename the document and "
2088 "try again?"), file);
2089 int const ret = Alert::prompt(_("Rename and save?"),
2090 text, 0, 2, _("&Rename"), _("&Retry"), _("&Cancel"));
2093 if (!renameBuffer(b, docstring()))
2102 return saveBuffer(b);
2106 bool GuiView::hideWorkArea(GuiWorkArea * wa)
2108 return closeWorkArea(wa, false);
2112 bool GuiView::closeWorkArea(GuiWorkArea * wa)
2114 Buffer & buf = wa->bufferView().buffer();
2115 return closeWorkArea(wa, !buf.parent());
2119 bool GuiView::closeBuffer()
2121 GuiWorkArea * wa = currentMainWorkArea();
2122 Buffer & buf = wa->bufferView().buffer();
2123 return wa && closeWorkArea(wa, !buf.parent());
2127 void GuiView::writeSession() const {
2128 GuiWorkArea const * active_wa = currentMainWorkArea();
2129 for (int i = 0; i < d.splitter_->count(); ++i) {
2130 TabWorkArea * twa = d.tabWorkArea(i);
2131 for (int j = 0; j < twa->count(); ++j) {
2132 GuiWorkArea * wa = static_cast<GuiWorkArea *>(twa->widget(j));
2133 Buffer & buf = wa->bufferView().buffer();
2134 theSession().lastOpened().add(buf.fileName(), wa == active_wa);
2140 bool GuiView::closeBufferAll()
2142 // Close the workareas in all other views
2143 QList<int> const ids = guiApp->viewIds();
2144 for (int i = 0; i != ids.size(); ++i) {
2145 if (id_ != ids[i] && !guiApp->view(ids[i]).closeWorkAreaAll())
2149 // Close our own workareas
2150 if (!closeWorkAreaAll())
2153 // Now close the hidden buffers. We prevent hidden buffers from being
2154 // dirty, so we can just close them.
2155 theBufferList().closeAll();
2160 bool GuiView::closeWorkAreaAll()
2162 setCurrentWorkArea(currentMainWorkArea());
2164 // We might be in a situation that there is still a tabWorkArea, but
2165 // there are no tabs anymore. This can happen when we get here after a
2166 // TabWorkArea::lastWorkAreaRemoved() signal. Therefore we count how
2167 // many TabWorkArea's have no documents anymore.
2170 // We have to call count() each time, because it can happen that
2171 // more than one splitter will disappear in one iteration (bug 5998).
2172 for (; d.splitter_->count() > empty_twa; ) {
2173 TabWorkArea * twa = d.tabWorkArea(empty_twa);
2175 if (twa->count() == 0)
2178 setCurrentWorkArea(twa->currentWorkArea());
2179 if (!closeTabWorkArea(twa))
2187 bool GuiView::closeWorkArea(GuiWorkArea * wa, bool close_buffer)
2192 Buffer & buf = wa->bufferView().buffer();
2195 return closeBuffer(buf);
2197 if (!inMultiTabs(wa))
2198 if (!saveBufferIfNeeded(buf, true))
2206 bool GuiView::closeBuffer(Buffer & buf)
2208 // If we are in a close_event all children will be closed in some time,
2209 // so no need to do it here. This will ensure that the children end up
2210 // in the session file in the correct order. If we close the master
2211 // buffer, we can close or release the child buffers here too.
2213 vector<Buffer *> clist = buf.getChildren(false);
2214 for (vector<Buffer *>::const_iterator it = clist.begin();
2215 it != clist.end(); ++it) {
2216 // If a child is dirty, do not close
2217 // without user intervention
2218 //FIXME: should we look in other tabworkareas?
2219 Buffer * child_buf = *it;
2220 GuiWorkArea * child_wa = workArea(*child_buf);
2222 if (!closeWorkArea(child_wa, true))
2225 theBufferList().releaseChild(&buf, child_buf);
2228 // goto bookmark to update bookmark pit.
2229 //FIXME: we should update only the bookmarks related to this buffer!
2230 LYXERR(Debug::DEBUG, "GuiView::closeBuffer()");
2231 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
2232 theLyXFunc().gotoBookmark(i+1, false, false);
2234 if (saveBufferIfNeeded(buf, false)) {
2235 theBufferList().release(&buf);
2242 bool GuiView::closeTabWorkArea(TabWorkArea * twa)
2244 while (twa == d.currentTabWorkArea()) {
2245 twa->setCurrentIndex(twa->count()-1);
2247 GuiWorkArea * wa = twa->currentWorkArea();
2248 Buffer & b = wa->bufferView().buffer();
2250 // We only want to close the buffer if the same buffer is not visible
2251 // in another view, and if this is not a child and if we are closing
2252 // a view (not a tabgroup).
2253 bool const close_buffer =
2254 !inMultiViews(wa) && !b.parent() && closing_;
2256 if (!closeWorkArea(wa, close_buffer))
2263 bool GuiView::saveBufferIfNeeded(Buffer & buf, bool hiding)
2265 if (buf.isClean() || buf.paragraphs().empty())
2268 // Switch to this Buffer.
2273 if (buf.isUnnamed())
2274 file = from_utf8(buf.fileName().onlyFileName());
2276 file = buf.fileName().displayName(30);
2278 // Bring this window to top before asking questions.
2283 if (hiding && buf.isUnnamed()) {
2284 docstring const text = bformat(_("The document %1$s has not been "
2285 "saved yet.\n\nDo you want to save "
2286 "the document?"), file);
2287 ret = Alert::prompt(_("Save new document?"),
2288 text, 0, 1, _("&Save"), _("&Cancel"));
2292 docstring const text = bformat(_("The document %1$s has unsaved changes."
2293 "\n\nDo you want to save the document or discard the changes?"), file);
2294 ret = Alert::prompt(_("Save changed document?"),
2295 text, 0, 2, _("&Save"), _("&Discard"), _("&Cancel"));
2300 if (!saveBuffer(buf))
2304 // if we crash after this we could
2305 // have no autosave file but I guess
2306 // this is really improbable (Jug)
2307 buf.removeAutosaveFile();
2309 // revert all changes
2310 buf.loadLyXFile(buf.fileName());
2320 bool GuiView::inMultiTabs(GuiWorkArea * wa)
2322 Buffer & buf = wa->bufferView().buffer();
2324 for (int i = 0; i != d.splitter_->count(); ++i) {
2325 GuiWorkArea * wa_ = d.tabWorkArea(i)->workArea(buf);
2326 if (wa_ && wa_ != wa)
2329 return inMultiViews(wa);
2333 bool GuiView::inMultiViews(GuiWorkArea * wa)
2335 QList<int> const ids = guiApp->viewIds();
2336 Buffer & buf = wa->bufferView().buffer();
2339 for (int i = 0; i != ids.size() && found_twa <= 1; ++i) {
2343 if (guiApp->view(ids[i]).workArea(buf))
2350 void GuiView::gotoNextOrPreviousBuffer(NextOrPrevious np)
2352 Buffer * const curbuf = documentBufferView()
2353 ? &documentBufferView()->buffer() : 0;
2354 Buffer * nextbuf = curbuf;
2356 if (np == NEXTBUFFER)
2357 nextbuf = theBufferList().next(nextbuf);
2359 nextbuf = theBufferList().previous(nextbuf);
2360 if (nextbuf == curbuf)
2366 if (workArea(*nextbuf))
2373 /// make sure the document is saved
2374 static bool ensureBufferClean(Buffer * buffer)
2376 LASSERT(buffer, return false);
2377 if (buffer->isClean() && !buffer->isUnnamed())
2380 docstring const file = buffer->fileName().displayName(30);
2383 if (!buffer->isUnnamed()) {
2384 text = bformat(_("The document %1$s has unsaved "
2385 "changes.\n\nDo you want to save "
2386 "the document?"), file);
2387 title = _("Save changed document?");
2390 text = bformat(_("The document %1$s has not been "
2391 "saved yet.\n\nDo you want to save "
2392 "the document?"), file);
2393 title = _("Save new document?");
2395 int const ret = Alert::prompt(title, text, 0, 1, _("&Save"), _("&Cancel"));
2398 dispatch(FuncRequest(LFUN_BUFFER_WRITE));
2400 return buffer->isClean() && !buffer->isUnnamed();
2404 void GuiView::reloadBuffer()
2406 Buffer * buf = &documentBufferView()->buffer();
2411 void GuiView::reloadBuffer(Buffer * buf)
2413 FileName filename = buf->fileName();
2414 Buffer const * master = buf->masterBuffer();
2415 bool const is_child = master != buf;
2416 // The user has already confirmed that the changes, if any, should
2417 // be discarded. So we just release the Buffer and don't call closeBuffer();
2418 theBufferList().release(buf);
2419 buf = loadDocument(filename);
2420 docstring const disp_fn = makeDisplayPath(filename.absFilename());
2423 // re-allocate master if necessary
2424 if (is_child && theBufferList().isLoaded(master)
2425 && buf->masterBuffer() != master)
2426 buf->setParent(master);
2427 buf->updateLabels();
2429 buf->errors("Parse");
2430 str = bformat(_("Document %1$s reloaded."), disp_fn);
2432 str = bformat(_("Could not reload document %1$s"), disp_fn);
2438 void GuiView::checkExternallyModifiedBuffers()
2440 BufferList::iterator bit = theBufferList().begin();
2441 BufferList::iterator const bend = theBufferList().end();
2442 for (; bit != bend; ++bit) {
2443 if ((*bit)->fileName().exists()
2444 && (*bit)->isExternallyModified(Buffer::checksum_method)) {
2445 docstring text = bformat(_("Document \n%1$s\n has been externally modified."
2446 " Reload now? Any local changes will be lost."),
2447 from_utf8((*bit)->absFileName()));
2448 int const ret = Alert::prompt(_("Reload externally changed document?"),
2449 text, 0, 1, _("&Reload"), _("&Cancel"));
2457 void GuiView::dispatchVC(FuncRequest const & cmd)
2459 // message for statusbar
2461 Buffer * buffer = documentBufferView()
2462 ? &(documentBufferView()->buffer()) : 0;
2464 switch (cmd.action) {
2465 case LFUN_VC_REGISTER:
2466 if (!buffer || !ensureBufferClean(buffer))
2468 if (!buffer->lyxvc().inUse()) {
2469 if (buffer->lyxvc().registrer())
2474 case LFUN_VC_CHECK_IN:
2475 if (!buffer || !ensureBufferClean(buffer))
2477 if (buffer->lyxvc().inUse() && !buffer->isReadonly()) {
2478 msg = buffer->lyxvc().checkIn();
2483 case LFUN_VC_CHECK_OUT:
2484 if (!buffer || !ensureBufferClean(buffer))
2486 if (buffer->lyxvc().inUse()) {
2487 msg = buffer->lyxvc().checkOut();
2492 case LFUN_VC_LOCKING_TOGGLE:
2493 LASSERT(buffer, return);
2494 if (!ensureBufferClean(buffer) || buffer->isReadonly())
2496 if (buffer->lyxvc().inUse()) {
2497 string res = buffer->lyxvc().lockingToggle();
2499 frontend::Alert::error(_("Revision control error."),
2500 _("Error when setting the locking property."));
2508 case LFUN_VC_REVERT:
2509 LASSERT(buffer, return);
2510 buffer->lyxvc().revert();
2514 case LFUN_VC_UNDO_LAST:
2515 LASSERT(buffer, return);
2516 buffer->lyxvc().undoLast();
2520 case LFUN_VC_REPO_UPDATE:
2521 LASSERT(buffer, return);
2522 if (ensureBufferClean(buffer)) {
2523 msg = buffer->lyxvc().repoUpdate();
2524 checkExternallyModifiedBuffers();
2528 case LFUN_VC_COMMAND: {
2529 string flag = cmd.getArg(0);
2530 if (buffer && contains(flag, 'R') && !ensureBufferClean(buffer))
2533 if (contains(flag, 'M')) {
2534 if (!Alert::askForText(message, _("LyX VC: Log Message")))
2537 string path = cmd.getArg(1);
2538 if (contains(path, "$$p") && buffer)
2539 path = subst(path, "$$p", buffer->filePath());
2540 LYXERR(Debug::LYXVC, "Directory: " << path);
2542 if (!pp.isReadableDirectory()) {
2543 lyxerr << _("Directory is not accessible.") << endl;
2546 support::PathChanger p(pp);
2548 string command = cmd.getArg(2);
2549 if (command.empty())
2552 command = subst(command, "$$i", buffer->absFileName());
2553 command = subst(command, "$$p", buffer->filePath());
2555 command = subst(command, "$$m", to_utf8(message));
2556 LYXERR(Debug::LYXVC, "Command: " << command);
2558 one.startscript(Systemcall::Wait, command);
2562 if (contains(flag, 'I'))
2563 buffer->markDirty();
2564 if (contains(flag, 'R'))
2574 message(from_utf8(msg));
2578 void GuiView::openChildDocument(string const & fname)
2580 LASSERT(documentBufferView(), return);
2581 Buffer & buffer = documentBufferView()->buffer();
2582 FileName const filename = support::makeAbsPath(fname, buffer.filePath());
2583 documentBufferView()->saveBookmark(false);
2585 bool parsed = false;
2586 if (theBufferList().exists(filename)) {
2587 child = theBufferList().getBuffer(filename);
2589 message(bformat(_("Opening child document %1$s..."),
2590 makeDisplayPath(filename.absFilename())));
2591 child = loadDocument(filename, false);
2597 // Set the parent name of the child document.
2598 // This makes insertion of citations and references in the child work,
2599 // when the target is in the parent or another child document.
2600 child->setParent(&buffer);
2601 child->masterBuffer()->updateLabels();
2604 child->errors("Parse");
2608 bool GuiView::goToFileRow(string const & argument)
2612 size_t i = argument.find_last_of(' ');
2613 if (i != string::npos) {
2614 file_name = os::internal_path(trim(argument.substr(0, i)));
2615 istringstream is(argument.substr(i + 1));
2620 if (i == string::npos) {
2621 LYXERR0("Wrong argument: " << argument);
2625 string const abstmp = package().temp_dir().absFilename();
2626 string const realtmp = package().temp_dir().realPath();
2627 // We have to use os::path_prefix_is() here, instead of
2628 // simply prefixIs(), because the file name comes from
2629 // an external application and may need case adjustment.
2630 if (os::path_prefix_is(file_name, abstmp, os::CASE_ADJUSTED)
2631 || os::path_prefix_is(file_name, realtmp, os::CASE_ADJUSTED)) {
2632 // Needed by inverse dvi search. If it is a file
2633 // in tmpdir, call the apropriated function.
2634 // If tmpdir is a symlink, we may have the real
2635 // path passed back, so we correct for that.
2636 if (!prefixIs(file_name, abstmp))
2637 file_name = subst(file_name, realtmp, abstmp);
2638 buf = theBufferList().getBufferFromTmp(file_name);
2640 // Must replace extension of the file to be .lyx
2641 // and get full path
2642 FileName const s = fileSearch(string(),
2643 support::changeExtension(file_name, ".lyx"), "lyx");
2644 // Either change buffer or load the file
2645 if (theBufferList().exists(s))
2646 buf = theBufferList().getBuffer(s);
2647 else if (s.exists()) {
2648 buf = loadDocument(s);
2649 buf->updateLabels();
2650 buf->errors("Parse");
2653 _("File does not exist: %1$s"),
2654 makeDisplayPath(file_name)));
2659 documentBufferView()->setCursorFromRow(row);
2664 static docstring exportAndDestroy(Buffer * buffer, string const & format)
2666 bool const success = buffer->doExport(format, true);
2669 ? bformat(_("Successful export to format: %1$s"), from_utf8(format))
2670 : bformat(_("Error exporting to format: %1$s"), from_utf8(format));
2674 static docstring previewAndDestroy(Buffer * buffer, string const & format)
2676 bool const success = buffer->preview(format);
2679 ? bformat(_("Successful preview of format: %1$s"), from_utf8(format))
2680 : bformat(_("Error previewing format: %1$s"), from_utf8(format));
2684 bool GuiView::dispatch(FuncRequest const & cmd)
2686 BufferView * bv = currentBufferView();
2687 // By default we won't need any update.
2689 bv->cursor().updateFlags(Update::None);
2691 Buffer * doc_buffer = documentBufferView()
2692 ? &(documentBufferView()->buffer()) : 0;
2694 bool dispatched = true;
2696 if (cmd.origin == FuncRequest::TOC) {
2697 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
2698 toc->doDispatch(bv->cursor(), cmd);
2702 string const argument = to_utf8(cmd.argument());
2704 switch(cmd.action) {
2705 case LFUN_BUFFER_CHILD_OPEN:
2706 openChildDocument(to_utf8(cmd.argument()));
2709 case LFUN_BUFFER_IMPORT:
2710 importDocument(to_utf8(cmd.argument()));
2713 case LFUN_BUFFER_EXPORT: {
2716 if (cmd.argument() == "custom") {
2717 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "sendto"));
2720 if (doc_buffer->doExport(argument, false)) {
2721 message(bformat(_("Error exporting to format: %1$s."),
2727 case LFUN_BUFFER_UPDATE: {
2730 string format = argument;
2731 if (argument.empty())
2732 format = doc_buffer->getDefaultOutputFormat();
2733 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
2734 ProgressInterface::instance()->clearMessages();
2735 ProgressInterface::instance()->appendMessage("Exporting ...");
2736 QFuture<docstring> f = QtConcurrent::run(exportAndDestroy,
2737 doc_buffer->clone(), format);
2738 d.setPreviewFuture(f);
2740 doc_buffer->doExport(format, true);
2744 case LFUN_BUFFER_VIEW: {
2747 string format = argument;
2748 if (argument.empty())
2749 format = doc_buffer->getDefaultOutputFormat();
2750 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
2751 ProgressInterface::instance()->clearMessages();
2752 ProgressInterface::instance()->appendMessage("Previewing ...");
2753 QFuture<docstring> f = QtConcurrent::run(previewAndDestroy,
2754 doc_buffer->clone(), format);
2755 d.setPreviewFuture(f);
2757 doc_buffer->preview(format);
2761 case LFUN_MASTER_BUFFER_UPDATE: {
2764 string format = argument;
2765 Buffer const * master = doc_buffer->masterBuffer();
2766 if (argument.empty())
2767 format = master->getDefaultOutputFormat();
2768 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
2769 QFuture<docstring> f = QtConcurrent::run(exportAndDestroy,
2770 master->clone(), format);
2771 d.setPreviewFuture(f);
2773 master->doExport(format, true);
2777 case LFUN_MASTER_BUFFER_VIEW: {
2778 string format = argument;
2779 Buffer const * master = doc_buffer->masterBuffer();
2780 if (argument.empty())
2781 format = master->getDefaultOutputFormat();
2782 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
2783 QFuture<docstring> f = QtConcurrent::run(previewAndDestroy,
2784 master->clone(), format);
2785 d.setPreviewFuture(f);
2787 master->preview(format);
2791 case LFUN_BUFFER_SWITCH:
2792 if (FileName::isAbsolute(to_utf8(cmd.argument()))) {
2794 theBufferList().getBuffer(FileName(to_utf8(cmd.argument())));
2798 message(_("Document not loaded"));
2802 case LFUN_BUFFER_NEXT:
2803 gotoNextOrPreviousBuffer(NEXTBUFFER);
2806 case LFUN_BUFFER_PREVIOUS:
2807 gotoNextOrPreviousBuffer(PREVBUFFER);
2810 case LFUN_COMMAND_EXECUTE: {
2811 bool const show_it = cmd.argument() != "off";
2812 // FIXME: this is a hack, "minibuffer" should not be
2814 if (GuiToolbar * t = toolbar("minibuffer")) {
2815 t->setVisible(show_it);
2816 if (show_it && t->commandBuffer())
2817 t->commandBuffer()->setFocus();
2821 case LFUN_DROP_LAYOUTS_CHOICE:
2822 d.layout_->showPopup();
2825 case LFUN_MENU_OPEN:
2826 if (QMenu * menu = guiApp->menus().menu(toqstr(cmd.argument()), *this))
2827 menu->exec(QCursor::pos());
2830 case LFUN_FILE_INSERT:
2831 insertLyXFile(cmd.argument());
2833 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
2834 insertPlaintextFile(cmd.argument(), true);
2837 case LFUN_FILE_INSERT_PLAINTEXT:
2838 insertPlaintextFile(cmd.argument(), false);
2841 case LFUN_BUFFER_RELOAD: {
2842 LASSERT(doc_buffer, break);
2843 docstring const file = makeDisplayPath(doc_buffer->absFileName(), 20);
2844 docstring text = bformat(_("Any changes will be lost. Are you sure "
2845 "you want to revert to the saved version of the document %1$s?"), file);
2846 int const ret = Alert::prompt(_("Revert to saved document?"),
2847 text, 1, 1, _("&Revert"), _("&Cancel"));
2850 doc_buffer->markClean();
2856 case LFUN_BUFFER_WRITE:
2857 LASSERT(doc_buffer, break);
2858 saveBuffer(*doc_buffer);
2861 case LFUN_BUFFER_WRITE_AS:
2862 LASSERT(doc_buffer, break);
2863 renameBuffer(*doc_buffer, cmd.argument());
2866 case LFUN_BUFFER_WRITE_ALL: {
2867 Buffer * first = theBufferList().first();
2870 message(_("Saving all documents..."));
2871 // We cannot use a for loop as the buffer list cycles.
2874 if (!b->isClean()) {
2876 LYXERR(Debug::ACTION, "Saved " << b->absFileName());
2878 b = theBufferList().next(b);
2879 } while (b != first);
2880 message(_("All documents saved."));
2884 case LFUN_BUFFER_CLOSE:
2888 case LFUN_BUFFER_CLOSE_ALL:
2892 case LFUN_TOOLBAR_TOGGLE: {
2893 string const name = cmd.getArg(0);
2894 if (GuiToolbar * t = toolbar(name))
2899 case LFUN_DIALOG_UPDATE: {
2900 string const name = to_utf8(cmd.argument());
2901 if (currentBufferView()) {
2902 Inset * inset = currentBufferView()->editedInset(name);
2903 // Can only update a dialog connected to an existing inset
2906 // FIXME: get rid of this indirection; GuiView ask the inset
2907 // if he is kind enough to update itself...
2908 FuncRequest fr(LFUN_INSET_DIALOG_UPDATE, cmd.argument());
2909 inset->dispatch(currentBufferView()->cursor(), fr);
2910 } else if (name == "paragraph") {
2911 lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
2912 } else if (name == "prefs" || name == "document") {
2913 updateDialog(name, string());
2918 case LFUN_DIALOG_TOGGLE: {
2919 if (isDialogVisible(cmd.getArg(0)))
2920 dispatch(FuncRequest(LFUN_DIALOG_HIDE, cmd.argument()));
2922 dispatch(FuncRequest(LFUN_DIALOG_SHOW, cmd.argument()));
2926 case LFUN_DIALOG_DISCONNECT_INSET:
2927 disconnectDialog(to_utf8(cmd.argument()));
2930 case LFUN_DIALOG_HIDE: {
2931 guiApp->hideDialogs(to_utf8(cmd.argument()), 0);
2935 case LFUN_DIALOG_SHOW: {
2936 string const name = cmd.getArg(0);
2937 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
2939 if (name == "character") {
2940 data = freefont2string();
2942 showDialog("character", data);
2943 } else if (name == "latexlog") {
2944 Buffer::LogType type;
2945 string const logfile = doc_buffer->logName(&type);
2947 case Buffer::latexlog:
2950 case Buffer::buildlog:
2954 data += Lexer::quoteString(logfile);
2955 showDialog("log", data);
2956 } else if (name == "vclog") {
2957 string const data = "vc " +
2958 Lexer::quoteString(doc_buffer->lyxvc().getLogFile());
2959 showDialog("log", data);
2960 } else if (name == "symbols") {
2961 data = bv->cursor().getEncoding()->name();
2963 showDialog("symbols", data);
2965 } else if (name == "prefs" && isFullScreen()) {
2966 FuncRequest fr(LFUN_INSET_INSERT, "fullscreen");
2968 showDialog("prefs", data);
2970 showDialog(name, data);
2975 message(cmd.argument());
2978 case LFUN_UI_TOGGLE:
2980 // Make sure the keyboard focus stays in the work area.
2984 case LFUN_SPLIT_VIEW: {
2985 LASSERT(doc_buffer, break);
2986 string const orientation = cmd.getArg(0);
2987 d.splitter_->setOrientation(orientation == "vertical"
2988 ? Qt::Vertical : Qt::Horizontal);
2989 TabWorkArea * twa = addTabWorkArea();
2990 GuiWorkArea * wa = twa->addWorkArea(*doc_buffer, *this);
2991 setCurrentWorkArea(wa);
2994 case LFUN_CLOSE_TAB_GROUP:
2995 if (TabWorkArea * twa = d.currentTabWorkArea()) {
2996 closeTabWorkArea(twa);
2997 d.current_work_area_ = 0;
2998 twa = d.currentTabWorkArea();
2999 // Switch to the next GuiWorkArea in the found TabWorkArea.
3001 // Make sure the work area is up to date.
3002 setCurrentWorkArea(twa->currentWorkArea());
3004 setCurrentWorkArea(0);
3009 case LFUN_COMPLETION_INLINE:
3010 if (d.current_work_area_)
3011 d.current_work_area_->completer().showInline();
3014 case LFUN_COMPLETION_POPUP:
3015 if (d.current_work_area_)
3016 d.current_work_area_->completer().showPopup();
3020 case LFUN_COMPLETION_COMPLETE:
3021 if (d.current_work_area_)
3022 d.current_work_area_->completer().tab();
3025 case LFUN_COMPLETION_CANCEL:
3026 if (d.current_work_area_) {
3027 if (d.current_work_area_->completer().popupVisible())
3028 d.current_work_area_->completer().hidePopup();
3030 d.current_work_area_->completer().hideInline();
3034 case LFUN_COMPLETION_ACCEPT:
3035 if (d.current_work_area_)
3036 d.current_work_area_->completer().activate();
3039 case LFUN_BUFFER_ZOOM_IN:
3040 case LFUN_BUFFER_ZOOM_OUT:
3041 if (cmd.argument().empty()) {
3042 if (cmd.action == LFUN_BUFFER_ZOOM_IN)
3047 lyxrc.zoom += convert<int>(cmd.argument());
3049 if (lyxrc.zoom < 10)
3052 // The global QPixmapCache is used in GuiPainter to cache text
3053 // painting so we must reset it.
3054 QPixmapCache::clear();
3055 guiApp->fontLoader().update();
3056 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
3059 case LFUN_VC_REGISTER:
3060 case LFUN_VC_CHECK_IN:
3061 case LFUN_VC_CHECK_OUT:
3062 case LFUN_VC_REPO_UPDATE:
3063 case LFUN_VC_LOCKING_TOGGLE:
3064 case LFUN_VC_REVERT:
3065 case LFUN_VC_UNDO_LAST:
3066 case LFUN_VC_COMMAND:
3070 case LFUN_SERVER_GOTO_FILE_ROW:
3071 goToFileRow(to_utf8(cmd.argument()));
3079 // Part of automatic menu appearance feature.
3080 if (isFullScreen()) {
3081 if (menuBar()->isVisible() && lyxrc.full_screen_menubar)
3083 if (statusBar()->isVisible())
3084 statusBar()->hide();
3091 void GuiView::lfunUiToggle(FuncRequest const & cmd)
3093 string const arg = cmd.getArg(0);
3094 if (arg == "scrollbar") {
3095 // hide() is of no help
3096 if (d.current_work_area_->verticalScrollBarPolicy() ==
3097 Qt::ScrollBarAlwaysOff)
3099 d.current_work_area_->setVerticalScrollBarPolicy(
3100 Qt::ScrollBarAsNeeded);
3102 d.current_work_area_->setVerticalScrollBarPolicy(
3103 Qt::ScrollBarAlwaysOff);
3106 if (arg == "statusbar") {
3107 statusBar()->setVisible(!statusBar()->isVisible());
3110 if (arg == "menubar") {
3111 menuBar()->setVisible(!menuBar()->isVisible());
3114 #if QT_VERSION >= 0x040300
3115 if (arg == "frame") {
3117 getContentsMargins(&l, &t, &r, &b);
3118 //are the frames in default state?
3119 d.current_work_area_->setFrameStyle(QFrame::NoFrame);
3121 setContentsMargins(-2, -2, -2, -2);
3123 setContentsMargins(0, 0, 0, 0);
3128 if (arg == "fullscreen") {
3133 message(bformat("LFUN_UI_TOGGLE " + _("%1$s unknown command!"), from_utf8(arg)));
3137 void GuiView::toggleFullScreen()
3139 if (isFullScreen()) {
3140 for (int i = 0; i != d.splitter_->count(); ++i)
3141 d.tabWorkArea(i)->setFullScreen(false);
3142 #if QT_VERSION >= 0x040300
3143 setContentsMargins(0, 0, 0, 0);
3145 setWindowState(windowState() ^ Qt::WindowFullScreen);
3148 statusBar()->show();
3151 hideDialogs("prefs", 0);
3152 for (int i = 0; i != d.splitter_->count(); ++i)
3153 d.tabWorkArea(i)->setFullScreen(true);
3154 #if QT_VERSION >= 0x040300
3155 setContentsMargins(-2, -2, -2, -2);
3158 setWindowState(windowState() ^ Qt::WindowFullScreen);
3159 statusBar()->hide();
3160 if (lyxrc.full_screen_menubar)
3162 if (lyxrc.full_screen_toolbars) {
3163 ToolbarMap::iterator end = d.toolbars_.end();
3164 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
3169 // give dialogs like the TOC a chance to adapt
3174 Buffer const * GuiView::updateInset(Inset const * inset)
3176 if (!d.current_work_area_)
3180 d.current_work_area_->scheduleRedraw();
3182 return &d.current_work_area_->bufferView().buffer();
3186 void GuiView::restartCursor()
3188 /* When we move around, or type, it's nice to be able to see
3189 * the cursor immediately after the keypress.
3191 if (d.current_work_area_)
3192 d.current_work_area_->startBlinkingCursor();
3194 // Take this occasion to update the other GUI elements.
3200 void GuiView::updateCompletion(Cursor & cur, bool start, bool keep)
3202 if (d.current_work_area_)
3203 d.current_work_area_->completer().updateVisibility(cur, start, keep);
3208 // This list should be kept in sync with the list of insets in
3209 // src/insets/Inset.cpp. I.e., if a dialog goes with an inset, the
3210 // dialog should have the same name as the inset.
3211 // Changes should be also recorded in LFUN_DIALOG_SHOW doxygen
3212 // docs in LyXAction.cpp.
3214 char const * const dialognames[] = {
3215 "aboutlyx", "bibitem", "bibtex", "box", "branch", "changes", "character",
3216 "citation", "compare", "document", "errorlist", "ert", "external", "file",
3217 "findreplace", "findreplaceadv", "float", "graphics", "href", "include",
3218 "index", "index_print", "info", "listings", "label", "log", "mathdelimiter",
3219 "mathmatrix", "mathspace", "nomenclature", "nomencl_print", "note",
3220 "paragraph", "phantom", "prefs", "print", "ref", "sendto", "space",
3221 "spellchecker", "symbols", "tabular", "tabularcreate", "thesaurus", "texinfo",
3222 "toc", "view-source", "vspace", "wrap", "progress"};
3224 char const * const * const end_dialognames =
3225 dialognames + (sizeof(dialognames) / sizeof(char *));
3229 cmpCStr(char const * name) : name_(name) {}
3230 bool operator()(char const * other) {
3231 return strcmp(other, name_) == 0;
3238 bool isValidName(string const & name)
3240 return find_if(dialognames, end_dialognames,
3241 cmpCStr(name.c_str())) != end_dialognames;
3247 void GuiView::resetDialogs()
3249 // Make sure that no LFUN uses any LyXView.
3250 guiApp->setCurrentView(0);
3253 constructToolbars();
3254 guiApp->menus().fillMenuBar(menuBar(), this, false);
3255 d.layout_->updateContents(true);
3256 // Now update controls with current buffer.
3257 guiApp->setCurrentView(this);
3263 Dialog * GuiView::findOrBuild(string const & name, bool hide_it)
3265 if (!isValidName(name))
3268 map<string, DialogPtr>::iterator it = d.dialogs_.find(name);
3270 if (it != d.dialogs_.end()) {
3272 it->second->hideView();
3273 return it->second.get();
3276 Dialog * dialog = build(name);
3277 d.dialogs_[name].reset(dialog);
3278 if (lyxrc.allow_geometry_session)
3279 dialog->restoreSession();
3286 void GuiView::showDialog(string const & name, string const & data,
3289 triggerShowDialog(toqstr(name), toqstr(data), inset);
3293 void GuiView::doShowDialog(QString const & qname, QString const & qdata,
3299 const string name = fromqstr(qname);
3300 const string data = fromqstr(qdata);
3304 Dialog * dialog = findOrBuild(name, false);
3306 dialog->showData(data);
3307 if (inset && currentBufferView())
3308 currentBufferView()->editInset(name, inset);
3311 catch (ExceptionMessage const & ex) {
3319 bool GuiView::isDialogVisible(string const & name) const
3321 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3322 if (it == d.dialogs_.end())
3324 return it->second.get()->isVisibleView() && !it->second.get()->isClosing();
3328 void GuiView::hideDialog(string const & name, Inset * inset)
3330 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3331 if (it == d.dialogs_.end())
3334 if (inset && currentBufferView()
3335 && inset != currentBufferView()->editedInset(name))
3338 Dialog * const dialog = it->second.get();
3339 if (dialog->isVisibleView())
3341 if (currentBufferView())
3342 currentBufferView()->editInset(name, 0);
3346 void GuiView::disconnectDialog(string const & name)
3348 if (!isValidName(name))
3350 if (currentBufferView())
3351 currentBufferView()->editInset(name, 0);
3355 void GuiView::hideAll() const
3357 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
3358 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3360 for(; it != end; ++it)
3361 it->second->hideView();
3365 void GuiView::updateDialogs()
3367 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
3368 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3370 for(; it != end; ++it) {
3371 Dialog * dialog = it->second.get();
3372 if (dialog && dialog->isVisibleView())
3373 dialog->checkStatus();
3380 // will be replaced by a proper factory...
3381 Dialog * createGuiAbout(GuiView & lv);
3382 Dialog * createGuiBibitem(GuiView & lv);
3383 Dialog * createGuiBibtex(GuiView & lv);
3384 Dialog * createGuiBox(GuiView & lv);
3385 Dialog * createGuiBranch(GuiView & lv);
3386 Dialog * createGuiChanges(GuiView & lv);
3387 Dialog * createGuiCharacter(GuiView & lv);
3388 Dialog * createGuiCitation(GuiView & lv);
3389 Dialog * createGuiCompare(GuiView & lv);
3390 Dialog * createGuiDelimiter(GuiView & lv);
3391 Dialog * createGuiDocument(GuiView & lv);
3392 Dialog * createGuiErrorList(GuiView & lv);
3393 Dialog * createGuiERT(GuiView & lv);
3394 Dialog * createGuiExternal(GuiView & lv);
3395 Dialog * createGuiFloat(GuiView & lv);
3396 Dialog * createGuiGraphics(GuiView & lv);
3397 Dialog * createGuiInclude(GuiView & lv);
3398 Dialog * createGuiIndex(GuiView & lv);
3399 Dialog * createGuiInfo(GuiView & lv);
3400 Dialog * createGuiLabel(GuiView & lv);
3401 Dialog * createGuiListings(GuiView & lv);
3402 Dialog * createGuiLog(GuiView & lv);
3403 Dialog * createGuiMathHSpace(GuiView & lv);
3404 Dialog * createGuiMathMatrix(GuiView & lv);
3405 Dialog * createGuiNomenclature(GuiView & lv);
3406 Dialog * createGuiNote(GuiView & lv);
3407 Dialog * createGuiParagraph(GuiView & lv);
3408 Dialog * createGuiPhantom(GuiView & lv);
3409 Dialog * createGuiPreferences(GuiView & lv);
3410 Dialog * createGuiPrint(GuiView & lv);
3411 Dialog * createGuiPrintindex(GuiView & lv);
3412 Dialog * createGuiPrintNomencl(GuiView & lv);
3413 Dialog * createGuiRef(GuiView & lv);
3414 Dialog * createGuiSearch(GuiView & lv);
3415 Dialog * createGuiSearchAdv(GuiView & lv);
3416 Dialog * createGuiSendTo(GuiView & lv);
3417 Dialog * createGuiShowFile(GuiView & lv);
3418 Dialog * createGuiSpellchecker(GuiView & lv);
3419 Dialog * createGuiSymbols(GuiView & lv);
3420 Dialog * createGuiTabularCreate(GuiView & lv);
3421 Dialog * createGuiTabular(GuiView & lv);
3422 Dialog * createGuiTexInfo(GuiView & lv);
3423 Dialog * createGuiTextHSpace(GuiView & lv);
3424 Dialog * createGuiToc(GuiView & lv);
3425 Dialog * createGuiThesaurus(GuiView & lv);
3426 Dialog * createGuiHyperlink(GuiView & lv);
3427 Dialog * createGuiVSpace(GuiView & lv);
3428 Dialog * createGuiViewSource(GuiView & lv);
3429 Dialog * createGuiWrap(GuiView & lv);
3430 Dialog * createGuiProgressView(GuiView & lv);
3434 Dialog * GuiView::build(string const & name)
3436 LASSERT(isValidName(name), return 0);
3438 if (name == "aboutlyx")
3439 return createGuiAbout(*this);
3440 if (name == "bibitem")
3441 return createGuiBibitem(*this);
3442 if (name == "bibtex")
3443 return createGuiBibtex(*this);
3445 return createGuiBox(*this);
3446 if (name == "branch")
3447 return createGuiBranch(*this);
3448 if (name == "changes")
3449 return createGuiChanges(*this);
3450 if (name == "character")
3451 return createGuiCharacter(*this);
3452 if (name == "citation")
3453 return createGuiCitation(*this);
3454 if (name == "compare")
3455 return createGuiCompare(*this);
3456 if (name == "document")
3457 return createGuiDocument(*this);
3458 if (name == "errorlist")
3459 return createGuiErrorList(*this);
3461 return createGuiERT(*this);
3462 if (name == "external")
3463 return createGuiExternal(*this);
3465 return createGuiShowFile(*this);
3466 if (name == "findreplace")
3467 return createGuiSearch(*this);
3468 if (name == "findreplaceadv")
3469 return createGuiSearchAdv(*this);
3470 if (name == "float")
3471 return createGuiFloat(*this);
3472 if (name == "graphics")
3473 return createGuiGraphics(*this);
3475 return createGuiHyperlink(*this);
3476 if (name == "include")
3477 return createGuiInclude(*this);
3478 if (name == "index")
3479 return createGuiIndex(*this);
3480 if (name == "index_print")
3481 return createGuiPrintindex(*this);
3483 return createGuiInfo(*this);
3484 if (name == "label")
3485 return createGuiLabel(*this);
3486 if (name == "listings")
3487 return createGuiListings(*this);
3489 return createGuiLog(*this);
3490 if (name == "mathdelimiter")
3491 return createGuiDelimiter(*this);
3492 if (name == "mathspace")
3493 return createGuiMathHSpace(*this);
3494 if (name == "mathmatrix")
3495 return createGuiMathMatrix(*this);
3496 if (name == "nomenclature")
3497 return createGuiNomenclature(*this);
3498 if (name == "nomencl_print")
3499 return createGuiPrintNomencl(*this);
3501 return createGuiNote(*this);
3502 if (name == "paragraph")
3503 return createGuiParagraph(*this);
3504 if (name == "phantom")
3505 return createGuiPhantom(*this);
3506 if (name == "prefs")
3507 return createGuiPreferences(*this);
3508 if (name == "print")
3509 return createGuiPrint(*this);
3511 return createGuiRef(*this);
3512 if (name == "sendto")
3513 return createGuiSendTo(*this);
3514 if (name == "space")
3515 return createGuiTextHSpace(*this);
3516 if (name == "spellchecker")
3517 return createGuiSpellchecker(*this);
3518 if (name == "symbols")
3519 return createGuiSymbols(*this);
3520 if (name == "tabular")
3521 return createGuiTabular(*this);
3522 if (name == "tabularcreate")
3523 return createGuiTabularCreate(*this);
3524 if (name == "texinfo")
3525 return createGuiTexInfo(*this);
3526 if (name == "thesaurus")
3527 return createGuiThesaurus(*this);
3529 return createGuiToc(*this);
3530 if (name == "view-source")
3531 return createGuiViewSource(*this);
3532 if (name == "vspace")
3533 return createGuiVSpace(*this);
3535 return createGuiWrap(*this);
3536 if (name == "progress")
3537 return createGuiProgressView(*this);
3543 } // namespace frontend
3546 #include "moc_GuiView.cpp"