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);
285 GuiWorkArea * current_work_area_;
286 GuiWorkArea * current_main_work_area_;
287 QSplitter * splitter_;
288 QStackedWidget * stack_widget_;
289 BackgroundWidget * bg_widget_;
291 ToolbarMap toolbars_;
292 ProgressInterface* progress_;
293 /// The main layout box.
295 * \warning Don't Delete! The layout box is actually owned by
296 * whichever toolbar contains it. All the GuiView class needs is a
297 * means of accessing it.
299 * FIXME: replace that with a proper model so that we are not limited
300 * to only one dialog.
305 map<string, DialogPtr> dialogs_;
307 unsigned int smallIconSize;
308 unsigned int normalIconSize;
309 unsigned int bigIconSize;
311 QTimer statusbar_timer_;
312 /// auto-saving of buffers
313 Timeout autosave_timeout_;
314 /// flag against a race condition due to multiclicks, see bug #1119
318 TocModels toc_models_;
320 #if (QT_VERSION >= 0x040400)
322 QFutureWatcher<docstring> autosave_watcher_;
323 QFutureWatcher<docstring> preview_watcher_;
325 struct DummyWatcher { bool isRunning(){return false;} };
326 DummyWatcher preview_watcher_;
331 GuiView::GuiView(int id)
332 : d(*new GuiViewPrivate(this)), id_(id), closing_(false)
334 // GuiToolbars *must* be initialised before the menu bar.
335 normalSizedIcons(); // at least on Mac the default is 32 otherwise, which is huge
338 // set ourself as the current view. This is needed for the menu bar
339 // filling, at least for the static special menu item on Mac. Otherwise
340 // they are greyed out.
341 guiApp->setCurrentView(this);
343 // Fill up the menu bar.
344 guiApp->menus().fillMenuBar(menuBar(), this, true);
346 setCentralWidget(d.stack_widget_);
348 // Start autosave timer
349 if (lyxrc.autosave) {
350 d.autosave_timeout_.timeout.connect(boost::bind(&GuiView::autoSave, this));
351 d.autosave_timeout_.setTimeout(lyxrc.autosave * 1000);
352 d.autosave_timeout_.start();
354 connect(&d.statusbar_timer_, SIGNAL(timeout()),
355 this, SLOT(clearMessage()));
357 // We don't want to keep the window in memory if it is closed.
358 setAttribute(Qt::WA_DeleteOnClose, true);
360 #if (!defined(Q_WS_WIN) && !defined(Q_WS_MACX))
361 // assign an icon to main form. We do not do it under Qt/Win or Qt/Mac,
362 // since the icon is provided in the application bundle.
363 setWindowIcon(getPixmap("images/", "lyx", "png"));
367 setAcceptDrops(true);
369 statusBar()->setSizeGripEnabled(true);
372 #if (QT_VERSION >= 0x040400)
373 connect(&d.autosave_watcher_, SIGNAL(finished()), this,
374 SLOT(threadFinished()));
375 connect(&d.preview_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();
469 if ((dialog = findOrBuild("progress", true)))
470 dialog->prepareView();
472 if (!restoreState(settings.value("layout").toByteArray(), 0))
479 GuiToolbar * GuiView::toolbar(string const & name)
481 ToolbarMap::iterator it = d.toolbars_.find(name);
482 if (it != d.toolbars_.end())
485 LYXERR(Debug::GUI, "Toolbar::display: no toolbar named " << name);
486 message(bformat(_("Unknown toolbar \"%1$s\""), from_utf8(name)));
491 void GuiView::constructToolbars()
493 ToolbarMap::iterator it = d.toolbars_.begin();
494 for (; it != d.toolbars_.end(); ++it)
498 // I don't like doing this here, but the standard toolbar
499 // destroys this object when it's destroyed itself (vfr)
500 d.layout_ = new LayoutBox(*this);
501 d.stack_widget_->addWidget(d.layout_);
502 d.layout_->move(0,0);
504 // extracts the toolbars from the backend
505 Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
506 Toolbars::Infos::iterator end = guiApp->toolbars().end();
507 for (; cit != end; ++cit)
508 d.toolbars_[cit->name] = new GuiToolbar(*cit, *this);
512 void GuiView::initToolbars()
514 // extracts the toolbars from the backend
515 Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
516 Toolbars::Infos::iterator end = guiApp->toolbars().end();
517 for (; cit != end; ++cit) {
518 GuiToolbar * tb = toolbar(cit->name);
521 int const visibility = guiApp->toolbars().defaultVisibility(cit->name);
523 tb->setVisible(false);
524 tb->setVisibility(visibility);
526 if (visibility & Toolbars::TOP) {
528 addToolBarBreak(Qt::TopToolBarArea);
529 addToolBar(Qt::TopToolBarArea, tb);
532 if (visibility & Toolbars::BOTTOM) {
533 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
534 #if (QT_VERSION >= 0x040202)
535 addToolBarBreak(Qt::BottomToolBarArea);
537 addToolBar(Qt::BottomToolBarArea, tb);
540 if (visibility & Toolbars::LEFT) {
541 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
542 #if (QT_VERSION >= 0x040202)
543 addToolBarBreak(Qt::LeftToolBarArea);
545 addToolBar(Qt::LeftToolBarArea, tb);
548 if (visibility & Toolbars::RIGHT) {
549 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
550 #if (QT_VERSION >= 0x040202)
551 addToolBarBreak(Qt::RightToolBarArea);
553 addToolBar(Qt::RightToolBarArea, tb);
556 if (visibility & Toolbars::ON)
557 tb->setVisible(true);
562 TocModels & GuiView::tocModels()
564 return d.toc_models_;
568 void GuiView::setFocus()
570 LYXERR(Debug::DEBUG, "GuiView::setFocus()" << this);
571 // Make sure LyXFunc points to the correct view.
572 guiApp->setCurrentView(this);
573 QMainWindow::setFocus();
574 if (d.current_work_area_)
575 d.current_work_area_->setFocus();
579 QMenu * GuiView::createPopupMenu()
581 return d.toolBarPopup(this);
585 void GuiView::showEvent(QShowEvent * e)
587 LYXERR(Debug::GUI, "Passed Geometry "
588 << size().height() << "x" << size().width()
589 << "+" << pos().x() << "+" << pos().y());
591 if (d.splitter_->count() == 0)
592 // No work area, switch to the background widget.
595 QMainWindow::showEvent(e);
599 /** Destroy only all tabbed WorkAreas. Destruction of other WorkAreas
600 ** is responsibility of the container (e.g., dialog)
602 void GuiView::closeEvent(QCloseEvent * close_event)
604 LYXERR(Debug::DEBUG, "GuiView::closeEvent()");
609 // it can happen that this event arrives without selecting the view,
610 // e.g. when clicking the close button on a background window.
612 if (!closeWorkAreaAll()) {
614 close_event->ignore();
618 // Make sure that nothing will use this to be closed View.
619 guiApp->unregisterView(this);
621 if (isFullScreen()) {
622 // Switch off fullscreen before closing.
627 // Make sure the timer time out will not trigger a statusbar update.
628 d.statusbar_timer_.stop();
630 // Saving fullscreen requires additional tweaks in the toolbar code.
631 // It wouldn't also work under linux natively.
632 if (lyxrc.allow_geometry_session) {
633 // Save this window geometry and layout.
635 // Then the toolbar private states.
636 ToolbarMap::iterator end = d.toolbars_.end();
637 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
638 it->second->saveSession();
639 // Now take care of all other dialogs:
640 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
641 for (; it!= d.dialogs_.end(); ++it)
642 it->second->saveSession();
645 close_event->accept();
649 void GuiView::dragEnterEvent(QDragEnterEvent * event)
651 if (event->mimeData()->hasUrls())
653 /// \todo Ask lyx-devel is this is enough:
654 /// if (event->mimeData()->hasFormat("text/plain"))
655 /// event->acceptProposedAction();
659 void GuiView::dropEvent(QDropEvent * event)
661 QList<QUrl> files = event->mimeData()->urls();
665 LYXERR(Debug::GUI, "GuiView::dropEvent: got URLs!");
666 for (int i = 0; i != files.size(); ++i) {
667 string const file = os::internal_path(fromqstr(
668 files.at(i).toLocalFile()));
672 string const ext = support::getExtension(file);
673 vector<const Format *> found_formats;
675 // Find all formats that have the correct extension.
676 vector<const Format *> const & import_formats
677 = theConverters().importableFormats();
678 vector<const Format *>::const_iterator it = import_formats.begin();
679 for (; it != import_formats.end(); ++it)
680 if ((*it)->extension() == ext)
681 found_formats.push_back(*it);
684 if (found_formats.size() >= 1) {
685 if (found_formats.size() > 1) {
686 //FIXME: show a dialog to choose the correct importable format
688 "Multiple importable formats found, selecting first");
690 string const arg = found_formats[0]->name() + " " + file;
691 cmd = FuncRequest(LFUN_BUFFER_IMPORT, arg);
694 //FIXME: do we have to explicitly check whether it's a lyx file?
696 "No formats found, trying to open it as a lyx file");
697 cmd = FuncRequest(LFUN_FILE_OPEN, file);
700 // Asynchronously post the event. DropEvent usually come
701 // from the BufferView. But reloading a file might close
702 // the BufferView from within its own event handler.
703 guiApp->dispatchDelayed(cmd);
709 void GuiView::message(docstring const & str)
711 if (ForkedProcess::iAmAChild())
714 // call is moved to GUI-thread by GuiProgress
715 d.progress_->appendMessage(toqstr(str));
719 void GuiView::updateMessage(QString const & str)
721 statusBar()->showMessage(str);
722 d.statusbar_timer_.stop();
723 d.statusbar_timer_.start(3000);
727 void GuiView::smallSizedIcons()
729 setIconSize(QSize(d.smallIconSize, d.smallIconSize));
733 void GuiView::normalSizedIcons()
735 setIconSize(QSize(d.normalIconSize, d.normalIconSize));
739 void GuiView::bigSizedIcons()
741 setIconSize(QSize(d.bigIconSize, d.bigIconSize));
745 void GuiView::clearMessage()
747 // FIXME: This code was introduced in r19643 to fix bug #4123. However,
748 // the hasFocus function mostly returns false, even if the focus is on
749 // a workarea in this view.
753 d.statusbar_timer_.stop();
757 void GuiView::updateWindowTitle(GuiWorkArea * wa)
759 if (wa != d.current_work_area_)
761 setWindowTitle(qt_("LyX: ") + wa->windowTitle());
762 setWindowIconText(wa->windowIconText());
766 void GuiView::on_currentWorkAreaChanged(GuiWorkArea * wa)
769 disconnectBufferView();
770 connectBufferView(wa->bufferView());
771 connectBuffer(wa->bufferView().buffer());
772 d.current_work_area_ = wa;
773 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
774 this, SLOT(updateWindowTitle(GuiWorkArea *)));
775 updateWindowTitle(wa);
779 // The document settings needs to be reinitialised.
780 updateDialog("document", "");
782 // Buffer-dependent dialogs must be updated. This is done here because
783 // some dialogs require buffer()->text.
788 void GuiView::on_lastWorkAreaRemoved()
791 // We already are in a close event. Nothing more to do.
794 if (d.splitter_->count() > 1)
795 // We have a splitter so don't close anything.
798 // Reset and updates the dialogs.
799 d.toc_models_.reset(0);
800 updateDialog("document", "");
803 resetWindowTitleAndIconText();
806 if (lyxrc.open_buffers_in_tabs)
807 // Nothing more to do, the window should stay open.
810 if (guiApp->viewIds().size() > 1) {
816 // On Mac we also close the last window because the application stay
817 // resident in memory. On other platforms we don't close the last
818 // window because this would quit the application.
824 void GuiView::updateStatusBar()
826 // let the user see the explicit message
827 if (d.statusbar_timer_.isActive())
834 void GuiView::showMessage()
836 QString msg = toqstr(theGuiApp()->viewStatusMessage());
838 BufferView const * bv = currentBufferView();
840 msg = toqstr(bv->cursor().currentState());
842 msg = qt_("Welcome to LyX!");
844 statusBar()->showMessage(msg);
848 bool GuiView::event(QEvent * e)
852 // Useful debug code:
853 //case QEvent::ActivationChange:
854 //case QEvent::WindowDeactivate:
855 //case QEvent::Paint:
856 //case QEvent::Enter:
857 //case QEvent::Leave:
858 //case QEvent::HoverEnter:
859 //case QEvent::HoverLeave:
860 //case QEvent::HoverMove:
861 //case QEvent::StatusTip:
862 //case QEvent::DragEnter:
863 //case QEvent::DragLeave:
867 case QEvent::WindowActivate: {
868 GuiView * old_view = guiApp->currentView();
869 if (this == old_view) {
871 return QMainWindow::event(e);
873 if (old_view && old_view->currentBufferView()) {
874 // save current selection to the selection buffer to allow
875 // middle-button paste in this window.
876 cap::saveSelection(old_view->currentBufferView()->cursor());
878 guiApp->setCurrentView(this);
879 if (d.current_work_area_) {
880 BufferView & bv = d.current_work_area_->bufferView();
881 connectBufferView(bv);
882 connectBuffer(bv.buffer());
883 // The document structure, name and dialogs might have
884 // changed in another view.
886 // The document settings needs to be reinitialised.
887 updateDialog("document", "");
890 resetWindowTitleAndIconText();
893 return QMainWindow::event(e);
896 case QEvent::ShortcutOverride: {
899 #if (!defined Q_WS_X11) || (QT_VERSION >= 0x040500)
900 if (isFullScreen() && menuBar()->isHidden()) {
901 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
902 // FIXME: we should also try to detect special LyX shortcut such as
903 // Alt-P and Alt-M. Right now there is a hack in
904 // GuiWorkArea::processKeySym() that hides again the menubar for
906 if (ke->modifiers() & Qt::AltModifier && ke->key() != Qt::Key_Alt) {
908 return QMainWindow::event(e);
913 if (d.current_work_area_)
914 // Nothing special to do.
915 return QMainWindow::event(e);
917 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
918 // Let Qt handle menu access and the Tab keys to navigate keys to navigate
920 if (ke->modifiers() & Qt::AltModifier || ke->key() == Qt::Key_Tab
921 || ke->key() == Qt::Key_Backtab)
922 return QMainWindow::event(e);
924 // Allow processing of shortcuts that are allowed even when no Buffer
927 setKeySymbol(&sym, ke);
928 guiApp->processKeySym(sym, q_key_state(ke->modifiers()));
934 return QMainWindow::event(e);
938 void GuiView::resetWindowTitleAndIconText()
940 setWindowTitle(qt_("LyX"));
941 setWindowIconText(qt_("LyX"));
944 bool GuiView::focusNextPrevChild(bool /*next*/)
951 void GuiView::setBusy(bool busy)
953 if (d.current_work_area_) {
954 d.current_work_area_->setUpdatesEnabled(!busy);
956 d.current_work_area_->stopBlinkingCursor();
958 d.current_work_area_->startBlinkingCursor();
962 QApplication::setOverrideCursor(Qt::WaitCursor);
964 QApplication::restoreOverrideCursor();
968 GuiWorkArea * GuiView::workArea(Buffer & buffer)
970 if (currentWorkArea()
971 && ¤tWorkArea()->bufferView().buffer() == &buffer)
972 return (GuiWorkArea *) currentWorkArea();
973 if (TabWorkArea * twa = d.currentTabWorkArea())
974 return twa->workArea(buffer);
979 GuiWorkArea * GuiView::addWorkArea(Buffer & buffer)
981 // Automatically create a TabWorkArea if there are none yet.
982 TabWorkArea * tab_widget = d.splitter_->count()
983 ? d.currentTabWorkArea() : addTabWorkArea();
984 return tab_widget->addWorkArea(buffer, *this);
988 TabWorkArea * GuiView::addTabWorkArea()
990 TabWorkArea * twa = new TabWorkArea;
991 QObject::connect(twa, SIGNAL(currentWorkAreaChanged(GuiWorkArea *)),
992 this, SLOT(on_currentWorkAreaChanged(GuiWorkArea *)));
993 QObject::connect(twa, SIGNAL(lastWorkAreaRemoved()),
994 this, SLOT(on_lastWorkAreaRemoved()));
996 d.splitter_->addWidget(twa);
997 d.stack_widget_->setCurrentWidget(d.splitter_);
1002 GuiWorkArea const * GuiView::currentWorkArea() const
1004 return d.current_work_area_;
1008 GuiWorkArea * GuiView::currentWorkArea()
1010 return d.current_work_area_;
1014 GuiWorkArea const * GuiView::currentMainWorkArea() const
1016 if (d.currentTabWorkArea() == NULL)
1018 return d.currentTabWorkArea()->currentWorkArea();
1022 GuiWorkArea * GuiView::currentMainWorkArea()
1024 if (d.currentTabWorkArea() == NULL)
1026 return d.currentTabWorkArea()->currentWorkArea();
1030 void GuiView::setCurrentWorkArea(GuiWorkArea * wa)
1032 LYXERR(Debug::DEBUG, "Setting current wa: " << wa << endl);
1034 d.current_work_area_ = NULL;
1038 GuiWorkArea * old_gwa = theGuiApp()->currentView()->currentWorkArea();
1042 if (currentBufferView())
1043 cap::saveSelection(currentBufferView()->cursor());
1045 theGuiApp()->setCurrentView(this);
1046 d.current_work_area_ = wa;
1047 for (int i = 0; i != d.splitter_->count(); ++i) {
1048 if (d.tabWorkArea(i)->setCurrentWorkArea(wa)) {
1049 //if (d.current_main_work_area_)
1050 // d.current_main_work_area_->setFrameStyle(QFrame::NoFrame);
1051 d.current_main_work_area_ = wa;
1052 //d.current_main_work_area_->setFrameStyle(QFrame::Box | QFrame::Plain);
1053 //d.current_main_work_area_->setLineWidth(2);
1054 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() << ", Current main wa: " << currentMainWorkArea());
1058 LYXERR(Debug::DEBUG, "This is not a tabbed wa");
1059 on_currentWorkAreaChanged(wa);
1060 BufferView & bv = wa->bufferView();
1061 bv.cursor().fixIfBroken();
1063 wa->setUpdatesEnabled(true);
1064 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() << ", Current main wa: " << currentMainWorkArea());
1068 void GuiView::removeWorkArea(GuiWorkArea * wa)
1070 LASSERT(wa, return);
1071 if (wa == d.current_work_area_) {
1073 disconnectBufferView();
1074 d.current_work_area_ = 0;
1075 d.current_main_work_area_ = 0;
1078 bool found_twa = false;
1079 for (int i = 0; i != d.splitter_->count(); ++i) {
1080 TabWorkArea * twa = d.tabWorkArea(i);
1081 if (twa->removeWorkArea(wa)) {
1082 // Found in this tab group, and deleted the GuiWorkArea.
1084 if (twa->count() != 0) {
1085 if (d.current_work_area_ == 0)
1086 // This means that we are closing the current GuiWorkArea, so
1087 // switch to the next GuiWorkArea in the found TabWorkArea.
1088 setCurrentWorkArea(twa->currentWorkArea());
1090 // No more WorkAreas in this tab group, so delete it.
1097 // It is not a tabbed work area (i.e., the search work area), so it
1098 // should be deleted by other means.
1099 LASSERT(found_twa, /* */);
1101 if (d.current_work_area_ == 0) {
1102 if (d.splitter_->count() != 0) {
1103 TabWorkArea * twa = d.currentTabWorkArea();
1104 setCurrentWorkArea(twa->currentWorkArea());
1106 // No more work areas, switch to the background widget.
1107 setCurrentWorkArea(0);
1113 LayoutBox * GuiView::getLayoutDialog() const
1119 void GuiView::updateLayoutList()
1122 d.layout_->updateContents(false);
1126 void GuiView::updateToolbars()
1128 ToolbarMap::iterator end = d.toolbars_.end();
1129 if (d.current_work_area_) {
1131 d.current_work_area_->bufferView().cursor().inMathed();
1133 lyx::getStatus(FuncRequest(LFUN_LAYOUT_TABULAR)).enabled();
1135 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).enabled() &&
1136 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).onoff(true);
1137 bool const mathmacrotemplate =
1138 lyx::getStatus(FuncRequest(LFUN_IN_MATHMACROTEMPLATE)).enabled();
1140 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1141 it->second->update(math, table, review, mathmacrotemplate);
1143 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1144 it->second->update(false, false, false, false);
1148 void GuiView::setBuffer(Buffer * newBuffer)
1150 LYXERR(Debug::DEBUG, "Setting buffer: " << newBuffer << endl);
1151 LASSERT(newBuffer, return);
1154 GuiWorkArea * wa = workArea(*newBuffer);
1156 newBuffer->masterBuffer()->updateLabels();
1157 wa = addWorkArea(*newBuffer);
1159 //Disconnect the old buffer...there's no new one.
1162 connectBuffer(*newBuffer);
1163 connectBufferView(wa->bufferView());
1164 setCurrentWorkArea(wa);
1170 void GuiView::connectBuffer(Buffer & buf)
1172 buf.setGuiDelegate(this);
1176 void GuiView::disconnectBuffer()
1178 if (d.current_work_area_)
1179 d.current_work_area_->bufferView().buffer().setGuiDelegate(0);
1183 void GuiView::connectBufferView(BufferView & bv)
1185 bv.setGuiDelegate(this);
1189 void GuiView::disconnectBufferView()
1191 if (d.current_work_area_)
1192 d.current_work_area_->bufferView().setGuiDelegate(0);
1196 void GuiView::errors(string const & error_type, bool from_master)
1198 ErrorList & el = from_master ?
1199 documentBufferView()->buffer().masterBuffer()->errorList(error_type)
1200 : documentBufferView()->buffer().errorList(error_type);
1201 string data = error_type;
1203 data = "from_master|" + error_type;
1205 showDialog("errorlist", data);
1209 void GuiView::updateTocItem(string const & type, DocIterator const & dit)
1211 d.toc_models_.updateItem(toqstr(type), dit);
1215 void GuiView::structureChanged()
1217 d.toc_models_.reset(documentBufferView());
1218 // Navigator needs more than a simple update in this case. It needs to be
1220 updateDialog("toc", "");
1224 void GuiView::updateDialog(string const & name, string const & data)
1226 if (!isDialogVisible(name))
1229 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
1230 if (it == d.dialogs_.end())
1233 Dialog * const dialog = it->second.get();
1234 if (dialog->isVisibleView())
1235 dialog->initialiseParams(data);
1239 BufferView * GuiView::documentBufferView()
1241 return currentMainWorkArea()
1242 ? ¤tMainWorkArea()->bufferView()
1247 BufferView const * GuiView::documentBufferView() const
1249 return currentMainWorkArea()
1250 ? ¤tMainWorkArea()->bufferView()
1255 BufferView * GuiView::currentBufferView()
1257 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1261 BufferView const * GuiView::currentBufferView() const
1263 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1267 static docstring saveAndDestroyBuffer(Buffer * buffer, FileName const & fname)
1270 FileName const tmp_ret = FileName::tempName("lyxauto");
1271 if (!tmp_ret.empty()) {
1272 if (buffer->writeFile(tmp_ret))
1273 failed = !tmp_ret.moveTo(fname);
1276 // failed to write/rename tmp_ret so try writing direct
1277 failed = buffer->writeFile(fname);
1281 ? _("Automatic save failed!")
1282 : _("Automatic save done.");
1286 void GuiView::autoSave()
1288 LYXERR(Debug::INFO, "Running autoSave()");
1290 Buffer * buffer = documentBufferView()
1291 ? &documentBufferView()->buffer() : 0;
1295 #if (QT_VERSION >= 0x040400)
1296 QFuture<docstring> f = QtConcurrent::run(saveAndDestroyBuffer, buffer->clone(),
1297 buffer->getAutosaveFilename());
1298 d.autosave_watcher_.setFuture(f);
1305 void GuiView::resetAutosaveTimers()
1308 d.autosave_timeout_.restart();
1312 bool GuiView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1315 Buffer * buf = currentBufferView()
1316 ? ¤tBufferView()->buffer() : 0;
1317 Buffer * doc_buffer = documentBufferView()
1318 ? &(documentBufferView()->buffer()) : 0;
1320 // Check whether we need a buffer
1321 if (!lyxaction.funcHasFlag(cmd.action, LyXAction::NoBuffer) && !buf) {
1322 // no, exit directly
1323 flag.message(from_utf8(N_("Command not allowed with"
1324 "out any document open")));
1325 flag.setEnabled(false);
1329 if (cmd.origin == FuncRequest::TOC) {
1330 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
1332 if (toc->getStatus(documentBufferView()->cursor(), cmd, fs))
1335 flag.setEnabled(false);
1339 switch(cmd.action) {
1340 case LFUN_BUFFER_IMPORT:
1343 case LFUN_MASTER_BUFFER_UPDATE:
1344 case LFUN_MASTER_BUFFER_VIEW:
1345 enable = doc_buffer && doc_buffer->parent() != 0
1346 && !d.preview_watcher_.isRunning();
1349 case LFUN_BUFFER_UPDATE:
1350 case LFUN_BUFFER_VIEW: {
1351 if (!doc_buffer || d.preview_watcher_.isRunning()) {
1355 string format = to_utf8(cmd.argument());
1356 if (cmd.argument().empty())
1357 format = doc_buffer->getDefaultOutputFormat();
1358 enable = doc_buffer->isExportableFormat(format);
1362 case LFUN_BUFFER_RELOAD:
1363 enable = doc_buffer && !doc_buffer->isUnnamed()
1364 && doc_buffer->fileName().exists()
1365 && (!doc_buffer->isClean()
1366 || doc_buffer->isExternallyModified(Buffer::timestamp_method));
1369 case LFUN_BUFFER_CHILD_OPEN:
1370 enable = doc_buffer;
1373 case LFUN_BUFFER_WRITE:
1374 enable = doc_buffer && (doc_buffer->isUnnamed() || !doc_buffer->isClean());
1377 //FIXME: This LFUN should be moved to GuiApplication.
1378 case LFUN_BUFFER_WRITE_ALL: {
1379 // We enable the command only if there are some modified buffers
1380 Buffer * first = theBufferList().first();
1385 // We cannot use a for loop as the buffer list is a cycle.
1387 if (!b->isClean()) {
1391 b = theBufferList().next(b);
1392 } while (b != first);
1396 case LFUN_BUFFER_WRITE_AS:
1397 enable = doc_buffer;
1400 case LFUN_BUFFER_CLOSE:
1401 enable = doc_buffer;
1404 case LFUN_BUFFER_CLOSE_ALL:
1405 enable = theBufferList().last() != theBufferList().first();
1408 case LFUN_SPLIT_VIEW:
1409 if (cmd.getArg(0) == "vertical")
1410 enable = doc_buffer && (d.splitter_->count() == 1 ||
1411 d.splitter_->orientation() == Qt::Vertical);
1413 enable = doc_buffer && (d.splitter_->count() == 1 ||
1414 d.splitter_->orientation() == Qt::Horizontal);
1417 case LFUN_CLOSE_TAB_GROUP:
1418 enable = d.currentTabWorkArea();
1421 case LFUN_TOOLBAR_TOGGLE:
1422 if (GuiToolbar * t = toolbar(cmd.getArg(0)))
1423 flag.setOnOff(t->isVisible());
1426 case LFUN_DROP_LAYOUTS_CHOICE:
1430 case LFUN_UI_TOGGLE:
1431 flag.setOnOff(isFullScreen());
1434 case LFUN_DIALOG_DISCONNECT_INSET:
1437 case LFUN_DIALOG_HIDE:
1438 // FIXME: should we check if the dialog is shown?
1441 case LFUN_DIALOG_TOGGLE:
1442 flag.setOnOff(isDialogVisible(cmd.getArg(0)));
1443 // fall through to set "enable"
1444 case LFUN_DIALOG_SHOW: {
1445 string const name = cmd.getArg(0);
1447 enable = name == "aboutlyx"
1448 || name == "file" //FIXME: should be removed.
1450 || name == "texinfo"
1451 || name == "progress"
1452 || name == "compare";
1453 else if (name == "print")
1454 enable = doc_buffer->isExportable("dvi")
1455 && lyxrc.print_command != "none";
1456 else if (name == "character" || name == "symbols") {
1457 if (!buf || buf->isReadonly()
1458 || !currentBufferView()->cursor().inTexted())
1461 // FIXME we should consider passthru
1463 Inset const & in = currentBufferView()->cursor().inset();
1464 enable = !in.getLayout().isPassThru();
1467 else if (name == "latexlog")
1468 enable = FileName(doc_buffer->logName()).isReadableFile();
1469 else if (name == "spellchecker")
1470 enable = theSpellChecker() && !doc_buffer->isReadonly();
1471 else if (name == "vclog")
1472 enable = doc_buffer->lyxvc().inUse();
1476 case LFUN_DIALOG_UPDATE: {
1477 string const name = cmd.getArg(0);
1479 enable = name == "prefs";
1483 case LFUN_COMMAND_EXECUTE:
1485 case LFUN_MENU_OPEN:
1486 // Nothing to check.
1489 case LFUN_COMPLETION_INLINE:
1490 if (!d.current_work_area_
1491 || !d.current_work_area_->completer().inlinePossible(
1492 currentBufferView()->cursor()))
1496 case LFUN_COMPLETION_POPUP:
1497 if (!d.current_work_area_
1498 || !d.current_work_area_->completer().popupPossible(
1499 currentBufferView()->cursor()))
1503 case LFUN_COMPLETION_COMPLETE:
1504 if (!d.current_work_area_
1505 || !d.current_work_area_->completer().inlinePossible(
1506 currentBufferView()->cursor()))
1510 case LFUN_COMPLETION_ACCEPT:
1511 if (!d.current_work_area_
1512 || (!d.current_work_area_->completer().popupVisible()
1513 && !d.current_work_area_->completer().inlineVisible()
1514 && !d.current_work_area_->completer().completionAvailable()))
1518 case LFUN_COMPLETION_CANCEL:
1519 if (!d.current_work_area_
1520 || (!d.current_work_area_->completer().popupVisible()
1521 && !d.current_work_area_->completer().inlineVisible()))
1525 case LFUN_BUFFER_ZOOM_OUT:
1526 enable = doc_buffer && lyxrc.zoom > 10;
1529 case LFUN_BUFFER_ZOOM_IN:
1530 enable = doc_buffer;
1533 case LFUN_BUFFER_NEXT:
1534 case LFUN_BUFFER_PREVIOUS:
1535 // FIXME: should we check is there is an previous or next buffer?
1537 case LFUN_BUFFER_SWITCH:
1538 // toggle on the current buffer, but do not toggle off
1539 // the other ones (is that a good idea?)
1541 && to_utf8(cmd.argument()) == doc_buffer->absFileName())
1542 flag.setOnOff(true);
1545 case LFUN_VC_REGISTER:
1546 enable = doc_buffer && !doc_buffer->lyxvc().inUse();
1548 case LFUN_VC_CHECK_IN:
1549 enable = doc_buffer && doc_buffer->lyxvc().checkInEnabled();
1551 case LFUN_VC_CHECK_OUT:
1552 enable = doc_buffer && doc_buffer->lyxvc().checkOutEnabled();
1554 case LFUN_VC_LOCKING_TOGGLE:
1555 enable = doc_buffer && !doc_buffer->isReadonly()
1556 && doc_buffer->lyxvc().lockingToggleEnabled();
1557 flag.setOnOff(enable && !doc_buffer->lyxvc().locker().empty());
1559 case LFUN_VC_REVERT:
1560 enable = doc_buffer && doc_buffer->lyxvc().inUse();
1562 case LFUN_VC_UNDO_LAST:
1563 enable = doc_buffer && doc_buffer->lyxvc().undoLastEnabled();
1565 case LFUN_VC_REPO_UPDATE:
1566 enable = doc_buffer && doc_buffer->lyxvc().inUse();
1568 case LFUN_VC_COMMAND: {
1569 if (cmd.argument().empty())
1571 if (!doc_buffer && contains(cmd.getArg(0), 'D'))
1576 case LFUN_SERVER_GOTO_FILE_ROW:
1584 flag.setEnabled(false);
1590 static FileName selectTemplateFile()
1592 FileDialog dlg(qt_("Select template file"));
1593 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1594 dlg.setButton1(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
1596 FileDialog::Result result = dlg.open(toqstr(lyxrc.template_path),
1597 QStringList(qt_("LyX Documents (*.lyx)")));
1599 if (result.first == FileDialog::Later)
1601 if (result.second.isEmpty())
1603 return FileName(fromqstr(result.second));
1607 Buffer * GuiView::loadDocument(FileName const & filename, bool tolastfiles)
1611 Buffer * newBuffer = checkAndLoadLyXFile(filename);
1614 message(_("Document not loaded."));
1619 setBuffer(newBuffer);
1621 // scroll to the position when the file was last closed
1622 if (lyxrc.use_lastfilepos) {
1623 LastFilePosSection::FilePos filepos =
1624 theSession().lastFilePos().load(filename);
1625 documentBufferView()->moveToPosition(filepos.pit, filepos.pos, 0, 0);
1629 theSession().lastFiles().add(filename);
1636 void GuiView::openDocument(string const & fname)
1638 string initpath = lyxrc.document_path;
1640 if (documentBufferView()) {
1641 string const trypath = documentBufferView()->buffer().filePath();
1642 // If directory is writeable, use this as default.
1643 if (FileName(trypath).isDirWritable())
1649 if (fname.empty()) {
1650 FileDialog dlg(qt_("Select document to open"), LFUN_FILE_OPEN);
1651 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1652 dlg.setButton2(qt_("Examples|#E#e"),
1653 toqstr(addPath(package().system_support().absFilename(), "examples")));
1655 QStringList filter(qt_("LyX Documents (*.lyx)"));
1656 filter << qt_("LyX-1.3.x Documents (*.lyx13)")
1657 << qt_("LyX-1.4.x Documents (*.lyx14)")
1658 << qt_("LyX-1.5.x Documents (*.lyx15)")
1659 << qt_("LyX-1.6.x Documents (*.lyx16)");
1660 FileDialog::Result result =
1661 dlg.open(toqstr(initpath), filter);
1663 if (result.first == FileDialog::Later)
1666 filename = fromqstr(result.second);
1668 // check selected filename
1669 if (filename.empty()) {
1670 message(_("Canceled."));
1676 // get absolute path of file and add ".lyx" to the filename if
1678 FileName const fullname =
1679 fileSearch(string(), filename, "lyx", support::may_not_exist);
1680 if (!fullname.empty())
1681 filename = fullname.absFilename();
1683 if (!fullname.onlyPath().isDirectory()) {
1684 Alert::warning(_("Invalid filename"),
1685 bformat(_("The directory in the given path\n%1$s\ndoes not exist."),
1686 from_utf8(fullname.absFilename())));
1689 // if the file doesn't exist, let the user create one
1690 if (!fullname.exists()) {
1691 // the user specifically chose this name. Believe him.
1692 Buffer * const b = newFile(filename, string(), true);
1698 docstring const disp_fn = makeDisplayPath(filename);
1699 message(bformat(_("Opening document %1$s..."), disp_fn));
1702 Buffer * buf = loadDocument(fullname);
1704 buf->updateLabels();
1706 buf->errors("Parse");
1707 str2 = bformat(_("Document %1$s opened."), disp_fn);
1708 if (buf->lyxvc().inUse())
1709 str2 += " " + from_utf8(buf->lyxvc().versionString()) +
1710 " " + _("Version control detected.");
1712 str2 = bformat(_("Could not open document %1$s"), disp_fn);
1717 // FIXME: clean that
1718 static bool import(GuiView * lv, FileName const & filename,
1719 string const & format, ErrorList & errorList)
1721 FileName const lyxfile(support::changeExtension(filename.absFilename(), ".lyx"));
1723 string loader_format;
1724 vector<string> loaders = theConverters().loaders();
1725 if (find(loaders.begin(), loaders.end(), format) == loaders.end()) {
1726 for (vector<string>::const_iterator it = loaders.begin();
1727 it != loaders.end(); ++it) {
1728 if (!theConverters().isReachable(format, *it))
1731 string const tofile =
1732 support::changeExtension(filename.absFilename(),
1733 formats.extension(*it));
1734 if (!theConverters().convert(0, filename, FileName(tofile),
1735 filename, format, *it, errorList))
1737 loader_format = *it;
1740 if (loader_format.empty()) {
1741 frontend::Alert::error(_("Couldn't import file"),
1742 bformat(_("No information for importing the format %1$s."),
1743 formats.prettyName(format)));
1747 loader_format = format;
1749 if (loader_format == "lyx") {
1750 Buffer * buf = lv->loadDocument(lyxfile);
1753 buf->updateLabels();
1755 buf->errors("Parse");
1757 Buffer * const b = newFile(lyxfile.absFilename(), string(), true);
1761 bool as_paragraphs = loader_format == "textparagraph";
1762 string filename2 = (loader_format == format) ? filename.absFilename()
1763 : support::changeExtension(filename.absFilename(),
1764 formats.extension(loader_format));
1765 lv->currentBufferView()->insertPlaintextFile(FileName(filename2),
1767 guiApp->setCurrentView(lv);
1768 lyx::dispatch(FuncRequest(LFUN_MARK_OFF));
1775 void GuiView::importDocument(string const & argument)
1778 string filename = split(argument, format, ' ');
1780 LYXERR(Debug::INFO, format << " file: " << filename);
1782 // need user interaction
1783 if (filename.empty()) {
1784 string initpath = lyxrc.document_path;
1785 if (documentBufferView()) {
1786 string const trypath = documentBufferView()->buffer().filePath();
1787 // If directory is writeable, use this as default.
1788 if (FileName(trypath).isDirWritable())
1792 docstring const text = bformat(_("Select %1$s file to import"),
1793 formats.prettyName(format));
1795 FileDialog dlg(toqstr(text), LFUN_BUFFER_IMPORT);
1796 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1797 dlg.setButton2(qt_("Examples|#E#e"),
1798 toqstr(addPath(package().system_support().absFilename(), "examples")));
1800 docstring filter = formats.prettyName(format);
1803 filter += from_utf8(formats.extension(format));
1806 FileDialog::Result result =
1807 dlg.open(toqstr(initpath), fileFilters(toqstr(filter)));
1809 if (result.first == FileDialog::Later)
1812 filename = fromqstr(result.second);
1814 // check selected filename
1815 if (filename.empty())
1816 message(_("Canceled."));
1819 if (filename.empty())
1822 // get absolute path of file
1823 FileName const fullname(support::makeAbsPath(filename));
1825 FileName const lyxfile(support::changeExtension(fullname.absFilename(), ".lyx"));
1827 // Check if the document already is open
1828 Buffer * buf = theBufferList().getBuffer(lyxfile);
1831 if (!closeBuffer()) {
1832 message(_("Canceled."));
1837 docstring const displaypath = makeDisplayPath(lyxfile.absFilename(), 30);
1839 // if the file exists already, and we didn't do
1840 // -i lyx thefile.lyx, warn
1841 if (lyxfile.exists() && fullname != lyxfile) {
1843 docstring text = bformat(_("The document %1$s already exists.\n\n"
1844 "Do you want to overwrite that document?"), displaypath);
1845 int const ret = Alert::prompt(_("Overwrite document?"),
1846 text, 0, 1, _("&Overwrite"), _("&Cancel"));
1849 message(_("Canceled."));
1854 message(bformat(_("Importing %1$s..."), displaypath));
1855 ErrorList errorList;
1856 if (import(this, fullname, format, errorList))
1857 message(_("imported."));
1859 message(_("file not imported!"));
1861 // FIXME (Abdel 12/08/06): Is there a need to display the error list here?
1865 void GuiView::newDocument(string const & filename, bool from_template)
1867 FileName initpath(lyxrc.document_path);
1868 if (documentBufferView()) {
1869 FileName const trypath(documentBufferView()->buffer().filePath());
1870 // If directory is writeable, use this as default.
1871 if (trypath.isDirWritable())
1875 string templatefile;
1876 if (from_template) {
1877 templatefile = selectTemplateFile().absFilename();
1878 if (templatefile.empty())
1883 if (filename.empty())
1884 b = newUnnamedFile(initpath, to_utf8(_("newfile")), templatefile);
1886 b = newFile(filename, templatefile, true);
1891 // If no new document could be created, it is unsure
1892 // whether there is a valid BufferView.
1893 if (currentBufferView())
1894 // Ensure the cursor is correctly positioned on screen.
1895 currentBufferView()->showCursor();
1899 void GuiView::insertLyXFile(docstring const & fname)
1901 BufferView * bv = documentBufferView();
1906 FileName filename(to_utf8(fname));
1908 if (!filename.empty()) {
1909 bv->insertLyXFile(filename);
1913 // Launch a file browser
1915 string initpath = lyxrc.document_path;
1916 string const trypath = bv->buffer().filePath();
1917 // If directory is writeable, use this as default.
1918 if (FileName(trypath).isDirWritable())
1922 FileDialog dlg(qt_("Select LyX document to insert"), LFUN_FILE_INSERT);
1923 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1924 dlg.setButton2(qt_("Examples|#E#e"),
1925 toqstr(addPath(package().system_support().absFilename(),
1928 FileDialog::Result result = dlg.open(toqstr(initpath),
1929 QStringList(qt_("LyX Documents (*.lyx)")));
1931 if (result.first == FileDialog::Later)
1935 filename.set(fromqstr(result.second));
1937 // check selected filename
1938 if (filename.empty()) {
1939 // emit message signal.
1940 message(_("Canceled."));
1944 bv->insertLyXFile(filename);
1948 void GuiView::insertPlaintextFile(docstring const & fname,
1951 BufferView * bv = documentBufferView();
1955 if (!fname.empty() && !FileName::isAbsolute(to_utf8(fname))) {
1956 message(_("Absolute filename expected."));
1961 FileName filename(to_utf8(fname));
1963 if (!filename.empty()) {
1964 bv->insertPlaintextFile(filename, asParagraph);
1968 FileDialog dlg(qt_("Select file to insert"), (asParagraph ?
1969 LFUN_FILE_INSERT_PLAINTEXT_PARA : LFUN_FILE_INSERT_PLAINTEXT));
1971 FileDialog::Result result = dlg.open(toqstr(bv->buffer().filePath()),
1972 QStringList(qt_("All Files (*)")));
1974 if (result.first == FileDialog::Later)
1978 filename.set(fromqstr(result.second));
1980 // check selected filename
1981 if (filename.empty()) {
1982 // emit message signal.
1983 message(_("Canceled."));
1987 bv->insertPlaintextFile(filename, asParagraph);
1991 bool GuiView::renameBuffer(Buffer & b, docstring const & newname)
1993 FileName fname = b.fileName();
1994 FileName const oldname = fname;
1996 if (!newname.empty()) {
1998 fname = support::makeAbsPath(to_utf8(newname), oldname.onlyPath().absFilename());
2000 // Switch to this Buffer.
2003 // No argument? Ask user through dialog.
2005 FileDialog dlg(qt_("Choose a filename to save document as"),
2006 LFUN_BUFFER_WRITE_AS);
2007 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2008 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
2010 if (!isLyXFilename(fname.absFilename()))
2011 fname.changeExtension(".lyx");
2013 FileDialog::Result result =
2014 dlg.save(toqstr(fname.onlyPath().absFilename()),
2015 QStringList(qt_("LyX Documents (*.lyx)")),
2016 toqstr(fname.onlyFileName()));
2018 if (result.first == FileDialog::Later)
2021 fname.set(fromqstr(result.second));
2026 if (!isLyXFilename(fname.absFilename()))
2027 fname.changeExtension(".lyx");
2030 if (FileName(fname).exists()) {
2031 docstring const file = makeDisplayPath(fname.absFilename(), 30);
2032 docstring text = bformat(_("The document %1$s already "
2033 "exists.\n\nDo you want to "
2034 "overwrite that document?"),
2036 int const ret = Alert::prompt(_("Overwrite document?"),
2037 text, 0, 2, _("&Overwrite"), _("&Rename"), _("&Cancel"));
2040 case 1: return renameBuffer(b, docstring());
2041 case 2: return false;
2045 FileName oldauto = b.getAutosaveFilename();
2047 // Ok, change the name of the buffer
2048 b.setFileName(fname.absFilename());
2050 bool unnamed = b.isUnnamed();
2051 b.setUnnamed(false);
2052 b.saveCheckSum(fname);
2054 // bring the autosave file with us, just in case.
2055 b.moveAutosaveFile(oldauto);
2057 if (!saveBuffer(b)) {
2058 oldauto = b.getAutosaveFilename();
2059 b.setFileName(oldname.absFilename());
2060 b.setUnnamed(unnamed);
2061 b.saveCheckSum(oldname);
2062 b.moveAutosaveFile(oldauto);
2070 bool GuiView::saveBuffer(Buffer & b)
2072 if (workArea(b) && workArea(b)->inDialogMode())
2076 return renameBuffer(b, docstring());
2079 theSession().lastFiles().add(b.fileName());
2083 // Switch to this Buffer.
2086 // FIXME: we don't tell the user *WHY* the save failed !!
2087 docstring const file = makeDisplayPath(b.absFileName(), 30);
2088 docstring text = bformat(_("The document %1$s could not be saved.\n\n"
2089 "Do you want to rename the document and "
2090 "try again?"), file);
2091 int const ret = Alert::prompt(_("Rename and save?"),
2092 text, 0, 2, _("&Rename"), _("&Retry"), _("&Cancel"));
2095 if (!renameBuffer(b, docstring()))
2104 return saveBuffer(b);
2108 bool GuiView::hideWorkArea(GuiWorkArea * wa)
2110 return closeWorkArea(wa, false);
2114 bool GuiView::closeWorkArea(GuiWorkArea * wa)
2116 Buffer & buf = wa->bufferView().buffer();
2117 return closeWorkArea(wa, !buf.parent());
2121 bool GuiView::closeBuffer()
2123 GuiWorkArea * wa = currentMainWorkArea();
2124 Buffer & buf = wa->bufferView().buffer();
2125 return wa && closeWorkArea(wa, !buf.parent());
2129 void GuiView::writeSession() const {
2130 GuiWorkArea const * active_wa = currentMainWorkArea();
2131 for (int i = 0; i < d.splitter_->count(); ++i) {
2132 TabWorkArea * twa = d.tabWorkArea(i);
2133 for (int j = 0; j < twa->count(); ++j) {
2134 GuiWorkArea * wa = static_cast<GuiWorkArea *>(twa->widget(j));
2135 Buffer & buf = wa->bufferView().buffer();
2136 theSession().lastOpened().add(buf.fileName(), wa == active_wa);
2142 bool GuiView::closeBufferAll()
2144 // Close the workareas in all other views
2145 QList<int> const ids = guiApp->viewIds();
2146 for (int i = 0; i != ids.size(); ++i) {
2147 if (id_ != ids[i] && !guiApp->view(ids[i]).closeWorkAreaAll())
2151 // Close our own workareas
2152 if (!closeWorkAreaAll())
2155 // Now close the hidden buffers. We prevent hidden buffers from being
2156 // dirty, so we can just close them.
2157 theBufferList().closeAll();
2162 bool GuiView::closeWorkAreaAll()
2164 setCurrentWorkArea(currentMainWorkArea());
2166 // We might be in a situation that there is still a tabWorkArea, but
2167 // there are no tabs anymore. This can happen when we get here after a
2168 // TabWorkArea::lastWorkAreaRemoved() signal. Therefore we count how
2169 // many TabWorkArea's have no documents anymore.
2172 // We have to call count() each time, because it can happen that
2173 // more than one splitter will disappear in one iteration (bug 5998).
2174 for (; d.splitter_->count() > empty_twa; ) {
2175 TabWorkArea * twa = d.tabWorkArea(empty_twa);
2177 if (twa->count() == 0)
2180 setCurrentWorkArea(twa->currentWorkArea());
2181 if (!closeTabWorkArea(twa))
2189 bool GuiView::closeWorkArea(GuiWorkArea * wa, bool close_buffer)
2194 Buffer & buf = wa->bufferView().buffer();
2197 return closeBuffer(buf);
2199 if (!inMultiTabs(wa))
2200 if (!saveBufferIfNeeded(buf, true))
2208 bool GuiView::closeBuffer(Buffer & buf)
2210 // If we are in a close_event all children will be closed in some time,
2211 // so no need to do it here. This will ensure that the children end up
2212 // in the session file in the correct order. If we close the master
2213 // buffer, we can close or release the child buffers here too.
2215 vector<Buffer *> clist = buf.getChildren(false);
2216 for (vector<Buffer *>::const_iterator it = clist.begin();
2217 it != clist.end(); ++it) {
2218 // If a child is dirty, do not close
2219 // without user intervention
2220 //FIXME: should we look in other tabworkareas?
2221 Buffer * child_buf = *it;
2222 GuiWorkArea * child_wa = workArea(*child_buf);
2224 if (!closeWorkArea(child_wa, true))
2227 theBufferList().releaseChild(&buf, child_buf);
2230 // goto bookmark to update bookmark pit.
2231 //FIXME: we should update only the bookmarks related to this buffer!
2232 LYXERR(Debug::DEBUG, "GuiView::closeBuffer()");
2233 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
2234 theLyXFunc().gotoBookmark(i+1, false, false);
2236 if (saveBufferIfNeeded(buf, false)) {
2237 theBufferList().release(&buf);
2244 bool GuiView::closeTabWorkArea(TabWorkArea * twa)
2246 while (twa == d.currentTabWorkArea()) {
2247 twa->setCurrentIndex(twa->count()-1);
2249 GuiWorkArea * wa = twa->currentWorkArea();
2250 Buffer & b = wa->bufferView().buffer();
2252 // We only want to close the buffer if the same buffer is not visible
2253 // in another view, and if this is not a child and if we are closing
2254 // a view (not a tabgroup).
2255 bool const close_buffer =
2256 !inMultiViews(wa) && !b.parent() && closing_;
2258 if (!closeWorkArea(wa, close_buffer))
2265 bool GuiView::saveBufferIfNeeded(Buffer & buf, bool hiding)
2267 if (buf.isClean() || buf.paragraphs().empty())
2270 // Switch to this Buffer.
2275 if (buf.isUnnamed())
2276 file = from_utf8(buf.fileName().onlyFileName());
2278 file = buf.fileName().displayName(30);
2280 // Bring this window to top before asking questions.
2285 if (hiding && buf.isUnnamed()) {
2286 docstring const text = bformat(_("The document %1$s has not been "
2287 "saved yet.\n\nDo you want to save "
2288 "the document?"), file);
2289 ret = Alert::prompt(_("Save new document?"),
2290 text, 0, 1, _("&Save"), _("&Cancel"));
2294 docstring const text = bformat(_("The document %1$s has unsaved changes."
2295 "\n\nDo you want to save the document or discard the changes?"), file);
2296 ret = Alert::prompt(_("Save changed document?"),
2297 text, 0, 2, _("&Save"), _("&Discard"), _("&Cancel"));
2302 if (!saveBuffer(buf))
2306 // if we crash after this we could
2307 // have no autosave file but I guess
2308 // this is really improbable (Jug)
2309 buf.removeAutosaveFile();
2311 // revert all changes
2312 buf.loadLyXFile(buf.fileName());
2322 bool GuiView::inMultiTabs(GuiWorkArea * wa)
2324 Buffer & buf = wa->bufferView().buffer();
2326 for (int i = 0; i != d.splitter_->count(); ++i) {
2327 GuiWorkArea * wa_ = d.tabWorkArea(i)->workArea(buf);
2328 if (wa_ && wa_ != wa)
2331 return inMultiViews(wa);
2335 bool GuiView::inMultiViews(GuiWorkArea * wa)
2337 QList<int> const ids = guiApp->viewIds();
2338 Buffer & buf = wa->bufferView().buffer();
2341 for (int i = 0; i != ids.size() && found_twa <= 1; ++i) {
2345 if (guiApp->view(ids[i]).workArea(buf))
2352 void GuiView::gotoNextOrPreviousBuffer(NextOrPrevious np)
2354 Buffer * const curbuf = documentBufferView()
2355 ? &documentBufferView()->buffer() : 0;
2356 Buffer * nextbuf = curbuf;
2358 if (np == NEXTBUFFER)
2359 nextbuf = theBufferList().next(nextbuf);
2361 nextbuf = theBufferList().previous(nextbuf);
2362 if (nextbuf == curbuf)
2368 if (workArea(*nextbuf))
2375 /// make sure the document is saved
2376 static bool ensureBufferClean(Buffer * buffer)
2378 LASSERT(buffer, return false);
2379 if (buffer->isClean() && !buffer->isUnnamed())
2382 docstring const file = buffer->fileName().displayName(30);
2385 if (!buffer->isUnnamed()) {
2386 text = bformat(_("The document %1$s has unsaved "
2387 "changes.\n\nDo you want to save "
2388 "the document?"), file);
2389 title = _("Save changed document?");
2392 text = bformat(_("The document %1$s has not been "
2393 "saved yet.\n\nDo you want to save "
2394 "the document?"), file);
2395 title = _("Save new document?");
2397 int const ret = Alert::prompt(title, text, 0, 1, _("&Save"), _("&Cancel"));
2400 dispatch(FuncRequest(LFUN_BUFFER_WRITE));
2402 return buffer->isClean() && !buffer->isUnnamed();
2406 void GuiView::reloadBuffer()
2408 Buffer * buf = &documentBufferView()->buffer();
2413 void GuiView::reloadBuffer(Buffer * buf)
2415 FileName filename = buf->fileName();
2416 Buffer const * master = buf->masterBuffer();
2417 bool const is_child = master != buf;
2418 // The user has already confirmed that the changes, if any, should
2419 // be discarded. So we just release the Buffer and don't call closeBuffer();
2420 theBufferList().release(buf);
2421 buf = loadDocument(filename);
2422 docstring const disp_fn = makeDisplayPath(filename.absFilename());
2425 // re-allocate master if necessary
2426 if (is_child && theBufferList().isLoaded(master)
2427 && buf->masterBuffer() != master)
2428 buf->setParent(master);
2429 buf->updateLabels();
2431 buf->errors("Parse");
2432 str = bformat(_("Document %1$s reloaded."), disp_fn);
2434 str = bformat(_("Could not reload document %1$s"), disp_fn);
2440 void GuiView::checkExternallyModifiedBuffers()
2442 BufferList::iterator bit = theBufferList().begin();
2443 BufferList::iterator const bend = theBufferList().end();
2444 for (; bit != bend; ++bit) {
2445 if ((*bit)->fileName().exists()
2446 && (*bit)->isExternallyModified(Buffer::checksum_method)) {
2447 docstring text = bformat(_("Document \n%1$s\n has been externally modified."
2448 " Reload now? Any local changes will be lost."),
2449 from_utf8((*bit)->absFileName()));
2450 int const ret = Alert::prompt(_("Reload externally changed document?"),
2451 text, 0, 1, _("&Reload"), _("&Cancel"));
2459 void GuiView::dispatchVC(FuncRequest const & cmd)
2461 // message for statusbar
2463 Buffer * buffer = documentBufferView()
2464 ? &(documentBufferView()->buffer()) : 0;
2466 switch (cmd.action) {
2467 case LFUN_VC_REGISTER:
2468 if (!buffer || !ensureBufferClean(buffer))
2470 if (!buffer->lyxvc().inUse()) {
2471 if (buffer->lyxvc().registrer())
2476 case LFUN_VC_CHECK_IN:
2477 if (!buffer || !ensureBufferClean(buffer))
2479 if (buffer->lyxvc().inUse() && !buffer->isReadonly()) {
2480 msg = buffer->lyxvc().checkIn();
2485 case LFUN_VC_CHECK_OUT:
2486 if (!buffer || !ensureBufferClean(buffer))
2488 if (buffer->lyxvc().inUse()) {
2489 msg = buffer->lyxvc().checkOut();
2494 case LFUN_VC_LOCKING_TOGGLE:
2495 LASSERT(buffer, return);
2496 if (!ensureBufferClean(buffer) || buffer->isReadonly())
2498 if (buffer->lyxvc().inUse()) {
2499 string res = buffer->lyxvc().lockingToggle();
2501 frontend::Alert::error(_("Revision control error."),
2502 _("Error when setting the locking property."));
2510 case LFUN_VC_REVERT:
2511 LASSERT(buffer, return);
2512 buffer->lyxvc().revert();
2516 case LFUN_VC_UNDO_LAST:
2517 LASSERT(buffer, return);
2518 buffer->lyxvc().undoLast();
2522 case LFUN_VC_REPO_UPDATE:
2523 LASSERT(buffer, return);
2524 if (ensureBufferClean(buffer)) {
2525 msg = buffer->lyxvc().repoUpdate();
2526 checkExternallyModifiedBuffers();
2530 case LFUN_VC_COMMAND: {
2531 string flag = cmd.getArg(0);
2532 if (buffer && contains(flag, 'R') && !ensureBufferClean(buffer))
2535 if (contains(flag, 'M')) {
2536 if (!Alert::askForText(message, _("LyX VC: Log Message")))
2539 string path = cmd.getArg(1);
2540 if (contains(path, "$$p") && buffer)
2541 path = subst(path, "$$p", buffer->filePath());
2542 LYXERR(Debug::LYXVC, "Directory: " << path);
2544 if (!pp.isReadableDirectory()) {
2545 lyxerr << _("Directory is not accessible.") << endl;
2548 support::PathChanger p(pp);
2550 string command = cmd.getArg(2);
2551 if (command.empty())
2554 command = subst(command, "$$i", buffer->absFileName());
2555 command = subst(command, "$$p", buffer->filePath());
2557 command = subst(command, "$$m", to_utf8(message));
2558 LYXERR(Debug::LYXVC, "Command: " << command);
2560 one.startscript(Systemcall::Wait, command);
2564 if (contains(flag, 'I'))
2565 buffer->markDirty();
2566 if (contains(flag, 'R'))
2576 message(from_utf8(msg));
2580 void GuiView::openChildDocument(string const & fname)
2582 LASSERT(documentBufferView(), return);
2583 Buffer & buffer = documentBufferView()->buffer();
2584 FileName const filename = support::makeAbsPath(fname, buffer.filePath());
2585 documentBufferView()->saveBookmark(false);
2587 bool parsed = false;
2588 if (theBufferList().exists(filename)) {
2589 child = theBufferList().getBuffer(filename);
2591 message(bformat(_("Opening child document %1$s..."),
2592 makeDisplayPath(filename.absFilename())));
2593 child = loadDocument(filename, false);
2599 // Set the parent name of the child document.
2600 // This makes insertion of citations and references in the child work,
2601 // when the target is in the parent or another child document.
2602 child->setParent(&buffer);
2603 child->masterBuffer()->updateLabels();
2606 child->errors("Parse");
2610 bool GuiView::goToFileRow(string const & argument)
2614 size_t i = argument.find_last_of(' ');
2615 if (i != string::npos) {
2616 file_name = os::internal_path(trim(argument.substr(0, i)));
2617 istringstream is(argument.substr(i + 1));
2622 if (i == string::npos) {
2623 LYXERR0("Wrong argument: " << argument);
2627 string const abstmp = package().temp_dir().absFilename();
2628 string const realtmp = package().temp_dir().realPath();
2629 // We have to use os::path_prefix_is() here, instead of
2630 // simply prefixIs(), because the file name comes from
2631 // an external application and may need case adjustment.
2632 if (os::path_prefix_is(file_name, abstmp, os::CASE_ADJUSTED)
2633 || os::path_prefix_is(file_name, realtmp, os::CASE_ADJUSTED)) {
2634 // Needed by inverse dvi search. If it is a file
2635 // in tmpdir, call the apropriated function.
2636 // If tmpdir is a symlink, we may have the real
2637 // path passed back, so we correct for that.
2638 if (!prefixIs(file_name, abstmp))
2639 file_name = subst(file_name, realtmp, abstmp);
2640 buf = theBufferList().getBufferFromTmp(file_name);
2642 // Must replace extension of the file to be .lyx
2643 // and get full path
2644 FileName const s = fileSearch(string(),
2645 support::changeExtension(file_name, ".lyx"), "lyx");
2646 // Either change buffer or load the file
2647 if (theBufferList().exists(s))
2648 buf = theBufferList().getBuffer(s);
2649 else if (s.exists()) {
2650 buf = loadDocument(s);
2651 buf->updateLabels();
2652 buf->errors("Parse");
2655 _("File does not exist: %1$s"),
2656 makeDisplayPath(file_name)));
2661 documentBufferView()->setCursorFromRow(row);
2666 static docstring exportAndDestroy(Buffer * buffer, string const & format)
2668 bool const success = buffer->doExport(format, true);
2671 ? bformat(_("Successful export to format: %1$s"), from_utf8(format))
2672 : bformat(_("Error exporting to format: %1$s"), from_utf8(format));
2676 static docstring previewAndDestroy(Buffer * buffer, string const & format)
2678 bool const success = buffer->preview(format);
2681 ? bformat(_("Successful preview of format: %1$s"), from_utf8(format))
2682 : bformat(_("Error previewing format: %1$s"), from_utf8(format));
2686 bool GuiView::dispatch(FuncRequest const & cmd)
2688 BufferView * bv = currentBufferView();
2689 // By default we won't need any update.
2691 bv->cursor().updateFlags(Update::None);
2693 Buffer * doc_buffer = documentBufferView()
2694 ? &(documentBufferView()->buffer()) : 0;
2696 bool dispatched = true;
2698 if (cmd.origin == FuncRequest::TOC) {
2699 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
2700 toc->doDispatch(bv->cursor(), cmd);
2704 string const argument = to_utf8(cmd.argument());
2706 switch(cmd.action) {
2707 case LFUN_BUFFER_CHILD_OPEN:
2708 openChildDocument(to_utf8(cmd.argument()));
2711 case LFUN_BUFFER_IMPORT:
2712 importDocument(to_utf8(cmd.argument()));
2715 case LFUN_BUFFER_EXPORT: {
2718 if (cmd.argument() == "custom") {
2719 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "sendto"));
2722 if (doc_buffer->doExport(argument, false)) {
2723 message(bformat(_("Error exporting to format: %1$s."),
2729 case LFUN_BUFFER_UPDATE: {
2732 string format = argument;
2733 if (argument.empty())
2734 format = doc_buffer->getDefaultOutputFormat();
2735 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
2736 d.progress_->clearMessages();
2737 message(_("Exporting ..."));
2738 QFuture<docstring> f = QtConcurrent::run(exportAndDestroy,
2739 doc_buffer->clone(), format);
2740 d.setPreviewFuture(f);
2742 doc_buffer->doExport(format, true);
2746 case LFUN_BUFFER_VIEW: {
2749 string format = argument;
2750 if (argument.empty())
2751 format = doc_buffer->getDefaultOutputFormat();
2752 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
2753 d.progress_->clearMessages();
2754 message(_("Previewing ..."));
2755 QFuture<docstring> f = QtConcurrent::run(previewAndDestroy,
2756 doc_buffer->clone(), format);
2757 d.setPreviewFuture(f);
2759 doc_buffer->preview(format);
2763 case LFUN_MASTER_BUFFER_UPDATE: {
2766 string format = argument;
2767 Buffer const * master = doc_buffer->masterBuffer();
2768 if (argument.empty())
2769 format = master->getDefaultOutputFormat();
2770 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
2771 QFuture<docstring> f = QtConcurrent::run(exportAndDestroy,
2772 master->clone(), format);
2773 d.setPreviewFuture(f);
2775 master->doExport(format, true);
2779 case LFUN_MASTER_BUFFER_VIEW: {
2780 string format = argument;
2781 Buffer const * master = doc_buffer->masterBuffer();
2782 if (argument.empty())
2783 format = master->getDefaultOutputFormat();
2784 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
2785 QFuture<docstring> f = QtConcurrent::run(previewAndDestroy,
2786 master->clone(), format);
2787 d.setPreviewFuture(f);
2789 master->preview(format);
2793 case LFUN_BUFFER_SWITCH:
2794 if (FileName::isAbsolute(to_utf8(cmd.argument()))) {
2796 theBufferList().getBuffer(FileName(to_utf8(cmd.argument())));
2800 message(_("Document not loaded"));
2804 case LFUN_BUFFER_NEXT:
2805 gotoNextOrPreviousBuffer(NEXTBUFFER);
2808 case LFUN_BUFFER_PREVIOUS:
2809 gotoNextOrPreviousBuffer(PREVBUFFER);
2812 case LFUN_COMMAND_EXECUTE: {
2813 bool const show_it = cmd.argument() != "off";
2814 // FIXME: this is a hack, "minibuffer" should not be
2816 if (GuiToolbar * t = toolbar("minibuffer")) {
2817 t->setVisible(show_it);
2818 if (show_it && t->commandBuffer())
2819 t->commandBuffer()->setFocus();
2823 case LFUN_DROP_LAYOUTS_CHOICE:
2824 d.layout_->showPopup();
2827 case LFUN_MENU_OPEN:
2828 if (QMenu * menu = guiApp->menus().menu(toqstr(cmd.argument()), *this))
2829 menu->exec(QCursor::pos());
2832 case LFUN_FILE_INSERT:
2833 insertLyXFile(cmd.argument());
2835 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
2836 insertPlaintextFile(cmd.argument(), true);
2839 case LFUN_FILE_INSERT_PLAINTEXT:
2840 insertPlaintextFile(cmd.argument(), false);
2843 case LFUN_BUFFER_RELOAD: {
2844 LASSERT(doc_buffer, break);
2845 docstring const file = makeDisplayPath(doc_buffer->absFileName(), 20);
2846 docstring text = bformat(_("Any changes will be lost. Are you sure "
2847 "you want to revert to the saved version of the document %1$s?"), file);
2848 int const ret = Alert::prompt(_("Revert to saved document?"),
2849 text, 1, 1, _("&Revert"), _("&Cancel"));
2852 doc_buffer->markClean();
2858 case LFUN_BUFFER_WRITE:
2859 LASSERT(doc_buffer, break);
2860 saveBuffer(*doc_buffer);
2863 case LFUN_BUFFER_WRITE_AS:
2864 LASSERT(doc_buffer, break);
2865 renameBuffer(*doc_buffer, cmd.argument());
2868 case LFUN_BUFFER_WRITE_ALL: {
2869 Buffer * first = theBufferList().first();
2872 message(_("Saving all documents..."));
2873 // We cannot use a for loop as the buffer list cycles.
2876 if (!b->isClean()) {
2878 LYXERR(Debug::ACTION, "Saved " << b->absFileName());
2880 b = theBufferList().next(b);
2881 } while (b != first);
2882 message(_("All documents saved."));
2886 case LFUN_BUFFER_CLOSE:
2890 case LFUN_BUFFER_CLOSE_ALL:
2894 case LFUN_TOOLBAR_TOGGLE: {
2895 string const name = cmd.getArg(0);
2896 if (GuiToolbar * t = toolbar(name))
2901 case LFUN_DIALOG_UPDATE: {
2902 string const name = to_utf8(cmd.argument());
2903 if (currentBufferView()) {
2904 Inset * inset = currentBufferView()->editedInset(name);
2905 // Can only update a dialog connected to an existing inset
2908 // FIXME: get rid of this indirection; GuiView ask the inset
2909 // if he is kind enough to update itself...
2910 FuncRequest fr(LFUN_INSET_DIALOG_UPDATE, cmd.argument());
2911 inset->dispatch(currentBufferView()->cursor(), fr);
2912 } else if (name == "paragraph") {
2913 lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
2914 } else if (name == "prefs" || name == "document") {
2915 updateDialog(name, string());
2920 case LFUN_DIALOG_TOGGLE: {
2921 if (isDialogVisible(cmd.getArg(0)))
2922 dispatch(FuncRequest(LFUN_DIALOG_HIDE, cmd.argument()));
2924 dispatch(FuncRequest(LFUN_DIALOG_SHOW, cmd.argument()));
2928 case LFUN_DIALOG_DISCONNECT_INSET:
2929 disconnectDialog(to_utf8(cmd.argument()));
2932 case LFUN_DIALOG_HIDE: {
2933 guiApp->hideDialogs(to_utf8(cmd.argument()), 0);
2937 case LFUN_DIALOG_SHOW: {
2938 string const name = cmd.getArg(0);
2939 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
2941 if (name == "character") {
2942 data = freefont2string();
2944 showDialog("character", data);
2945 } else if (name == "latexlog") {
2946 Buffer::LogType type;
2947 string const logfile = doc_buffer->logName(&type);
2949 case Buffer::latexlog:
2952 case Buffer::buildlog:
2956 data += Lexer::quoteString(logfile);
2957 showDialog("log", data);
2958 } else if (name == "vclog") {
2959 string const data = "vc " +
2960 Lexer::quoteString(doc_buffer->lyxvc().getLogFile());
2961 showDialog("log", data);
2962 } else if (name == "symbols") {
2963 data = bv->cursor().getEncoding()->name();
2965 showDialog("symbols", data);
2967 } else if (name == "prefs" && isFullScreen()) {
2968 FuncRequest fr(LFUN_INSET_INSERT, "fullscreen");
2970 showDialog("prefs", data);
2972 showDialog(name, data);
2977 message(cmd.argument());
2980 case LFUN_UI_TOGGLE:
2982 // Make sure the keyboard focus stays in the work area.
2986 case LFUN_SPLIT_VIEW: {
2987 LASSERT(doc_buffer, break);
2988 string const orientation = cmd.getArg(0);
2989 d.splitter_->setOrientation(orientation == "vertical"
2990 ? Qt::Vertical : Qt::Horizontal);
2991 TabWorkArea * twa = addTabWorkArea();
2992 GuiWorkArea * wa = twa->addWorkArea(*doc_buffer, *this);
2993 setCurrentWorkArea(wa);
2996 case LFUN_CLOSE_TAB_GROUP:
2997 if (TabWorkArea * twa = d.currentTabWorkArea()) {
2998 closeTabWorkArea(twa);
2999 d.current_work_area_ = 0;
3000 twa = d.currentTabWorkArea();
3001 // Switch to the next GuiWorkArea in the found TabWorkArea.
3003 // Make sure the work area is up to date.
3004 setCurrentWorkArea(twa->currentWorkArea());
3006 setCurrentWorkArea(0);
3011 case LFUN_COMPLETION_INLINE:
3012 if (d.current_work_area_)
3013 d.current_work_area_->completer().showInline();
3016 case LFUN_COMPLETION_POPUP:
3017 if (d.current_work_area_)
3018 d.current_work_area_->completer().showPopup();
3022 case LFUN_COMPLETION_COMPLETE:
3023 if (d.current_work_area_)
3024 d.current_work_area_->completer().tab();
3027 case LFUN_COMPLETION_CANCEL:
3028 if (d.current_work_area_) {
3029 if (d.current_work_area_->completer().popupVisible())
3030 d.current_work_area_->completer().hidePopup();
3032 d.current_work_area_->completer().hideInline();
3036 case LFUN_COMPLETION_ACCEPT:
3037 if (d.current_work_area_)
3038 d.current_work_area_->completer().activate();
3041 case LFUN_BUFFER_ZOOM_IN:
3042 case LFUN_BUFFER_ZOOM_OUT:
3043 if (cmd.argument().empty()) {
3044 if (cmd.action == LFUN_BUFFER_ZOOM_IN)
3049 lyxrc.zoom += convert<int>(cmd.argument());
3051 if (lyxrc.zoom < 10)
3054 // The global QPixmapCache is used in GuiPainter to cache text
3055 // painting so we must reset it.
3056 QPixmapCache::clear();
3057 guiApp->fontLoader().update();
3058 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
3061 case LFUN_VC_REGISTER:
3062 case LFUN_VC_CHECK_IN:
3063 case LFUN_VC_CHECK_OUT:
3064 case LFUN_VC_REPO_UPDATE:
3065 case LFUN_VC_LOCKING_TOGGLE:
3066 case LFUN_VC_REVERT:
3067 case LFUN_VC_UNDO_LAST:
3068 case LFUN_VC_COMMAND:
3072 case LFUN_SERVER_GOTO_FILE_ROW:
3073 goToFileRow(to_utf8(cmd.argument()));
3081 // Part of automatic menu appearance feature.
3082 if (isFullScreen()) {
3083 if (menuBar()->isVisible() && lyxrc.full_screen_menubar)
3085 if (statusBar()->isVisible())
3086 statusBar()->hide();
3093 void GuiView::lfunUiToggle(FuncRequest const & cmd)
3095 string const arg = cmd.getArg(0);
3096 if (arg == "scrollbar") {
3097 // hide() is of no help
3098 if (d.current_work_area_->verticalScrollBarPolicy() ==
3099 Qt::ScrollBarAlwaysOff)
3101 d.current_work_area_->setVerticalScrollBarPolicy(
3102 Qt::ScrollBarAsNeeded);
3104 d.current_work_area_->setVerticalScrollBarPolicy(
3105 Qt::ScrollBarAlwaysOff);
3108 if (arg == "statusbar") {
3109 statusBar()->setVisible(!statusBar()->isVisible());
3112 if (arg == "menubar") {
3113 menuBar()->setVisible(!menuBar()->isVisible());
3116 #if QT_VERSION >= 0x040300
3117 if (arg == "frame") {
3119 getContentsMargins(&l, &t, &r, &b);
3120 //are the frames in default state?
3121 d.current_work_area_->setFrameStyle(QFrame::NoFrame);
3123 setContentsMargins(-2, -2, -2, -2);
3125 setContentsMargins(0, 0, 0, 0);
3130 if (arg == "fullscreen") {
3135 message(bformat("LFUN_UI_TOGGLE " + _("%1$s unknown command!"), from_utf8(arg)));
3139 void GuiView::toggleFullScreen()
3141 if (isFullScreen()) {
3142 for (int i = 0; i != d.splitter_->count(); ++i)
3143 d.tabWorkArea(i)->setFullScreen(false);
3144 #if QT_VERSION >= 0x040300
3145 setContentsMargins(0, 0, 0, 0);
3147 setWindowState(windowState() ^ Qt::WindowFullScreen);
3150 statusBar()->show();
3153 hideDialogs("prefs", 0);
3154 for (int i = 0; i != d.splitter_->count(); ++i)
3155 d.tabWorkArea(i)->setFullScreen(true);
3156 #if QT_VERSION >= 0x040300
3157 setContentsMargins(-2, -2, -2, -2);
3160 setWindowState(windowState() ^ Qt::WindowFullScreen);
3161 statusBar()->hide();
3162 if (lyxrc.full_screen_menubar)
3164 if (lyxrc.full_screen_toolbars) {
3165 ToolbarMap::iterator end = d.toolbars_.end();
3166 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
3171 // give dialogs like the TOC a chance to adapt
3176 Buffer const * GuiView::updateInset(Inset const * inset)
3178 if (!d.current_work_area_)
3182 d.current_work_area_->scheduleRedraw();
3184 return &d.current_work_area_->bufferView().buffer();
3188 void GuiView::restartCursor()
3190 /* When we move around, or type, it's nice to be able to see
3191 * the cursor immediately after the keypress.
3193 if (d.current_work_area_)
3194 d.current_work_area_->startBlinkingCursor();
3196 // Take this occasion to update the other GUI elements.
3202 void GuiView::updateCompletion(Cursor & cur, bool start, bool keep)
3204 if (d.current_work_area_)
3205 d.current_work_area_->completer().updateVisibility(cur, start, keep);
3210 // This list should be kept in sync with the list of insets in
3211 // src/insets/Inset.cpp. I.e., if a dialog goes with an inset, the
3212 // dialog should have the same name as the inset.
3213 // Changes should be also recorded in LFUN_DIALOG_SHOW doxygen
3214 // docs in LyXAction.cpp.
3216 char const * const dialognames[] = {
3217 "aboutlyx", "bibitem", "bibtex", "box", "branch", "changes", "character",
3218 "citation", "compare", "document", "errorlist", "ert", "external", "file",
3219 "findreplace", "findreplaceadv", "float", "graphics", "href", "include",
3220 "index", "index_print", "info", "listings", "label", "log", "mathdelimiter",
3221 "mathmatrix", "mathspace", "nomenclature", "nomencl_print", "note",
3222 "paragraph", "phantom", "prefs", "print", "ref", "sendto", "space",
3223 "spellchecker", "symbols", "tabular", "tabularcreate", "thesaurus", "texinfo",
3224 "toc", "view-source", "vspace", "wrap", "progress"};
3226 char const * const * const end_dialognames =
3227 dialognames + (sizeof(dialognames) / sizeof(char *));
3231 cmpCStr(char const * name) : name_(name) {}
3232 bool operator()(char const * other) {
3233 return strcmp(other, name_) == 0;
3240 bool isValidName(string const & name)
3242 return find_if(dialognames, end_dialognames,
3243 cmpCStr(name.c_str())) != end_dialognames;
3249 void GuiView::resetDialogs()
3251 // Make sure that no LFUN uses any LyXView.
3252 guiApp->setCurrentView(0);
3255 constructToolbars();
3256 guiApp->menus().fillMenuBar(menuBar(), this, false);
3257 d.layout_->updateContents(true);
3258 // Now update controls with current buffer.
3259 guiApp->setCurrentView(this);
3265 Dialog * GuiView::findOrBuild(string const & name, bool hide_it)
3267 if (!isValidName(name))
3270 map<string, DialogPtr>::iterator it = d.dialogs_.find(name);
3272 if (it != d.dialogs_.end()) {
3274 it->second->hideView();
3275 return it->second.get();
3278 Dialog * dialog = build(name);
3279 d.dialogs_[name].reset(dialog);
3280 if (lyxrc.allow_geometry_session)
3281 dialog->restoreSession();
3288 void GuiView::showDialog(string const & name, string const & data,
3291 triggerShowDialog(toqstr(name), toqstr(data), inset);
3295 void GuiView::doShowDialog(QString const & qname, QString const & qdata,
3301 const string name = fromqstr(qname);
3302 const string data = fromqstr(qdata);
3306 Dialog * dialog = findOrBuild(name, false);
3308 dialog->showData(data);
3309 if (inset && currentBufferView())
3310 currentBufferView()->editInset(name, inset);
3313 catch (ExceptionMessage const & ex) {
3321 bool GuiView::isDialogVisible(string const & name) const
3323 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3324 if (it == d.dialogs_.end())
3326 return it->second.get()->isVisibleView() && !it->second.get()->isClosing();
3330 void GuiView::hideDialog(string const & name, Inset * inset)
3332 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3333 if (it == d.dialogs_.end())
3336 if (inset && currentBufferView()
3337 && inset != currentBufferView()->editedInset(name))
3340 Dialog * const dialog = it->second.get();
3341 if (dialog->isVisibleView())
3343 if (currentBufferView())
3344 currentBufferView()->editInset(name, 0);
3348 void GuiView::disconnectDialog(string const & name)
3350 if (!isValidName(name))
3352 if (currentBufferView())
3353 currentBufferView()->editInset(name, 0);
3357 void GuiView::hideAll() const
3359 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
3360 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3362 for(; it != end; ++it)
3363 it->second->hideView();
3367 void GuiView::updateDialogs()
3369 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
3370 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3372 for(; it != end; ++it) {
3373 Dialog * dialog = it->second.get();
3374 if (dialog && dialog->isVisibleView())
3375 dialog->checkStatus();
3382 // will be replaced by a proper factory...
3383 Dialog * createGuiAbout(GuiView & lv);
3384 Dialog * createGuiBibitem(GuiView & lv);
3385 Dialog * createGuiBibtex(GuiView & lv);
3386 Dialog * createGuiBox(GuiView & lv);
3387 Dialog * createGuiBranch(GuiView & lv);
3388 Dialog * createGuiChanges(GuiView & lv);
3389 Dialog * createGuiCharacter(GuiView & lv);
3390 Dialog * createGuiCitation(GuiView & lv);
3391 Dialog * createGuiCompare(GuiView & lv);
3392 Dialog * createGuiDelimiter(GuiView & lv);
3393 Dialog * createGuiDocument(GuiView & lv);
3394 Dialog * createGuiErrorList(GuiView & lv);
3395 Dialog * createGuiERT(GuiView & lv);
3396 Dialog * createGuiExternal(GuiView & lv);
3397 Dialog * createGuiFloat(GuiView & lv);
3398 Dialog * createGuiGraphics(GuiView & lv);
3399 Dialog * createGuiInclude(GuiView & lv);
3400 Dialog * createGuiIndex(GuiView & lv);
3401 Dialog * createGuiInfo(GuiView & lv);
3402 Dialog * createGuiLabel(GuiView & lv);
3403 Dialog * createGuiListings(GuiView & lv);
3404 Dialog * createGuiLog(GuiView & lv);
3405 Dialog * createGuiMathHSpace(GuiView & lv);
3406 Dialog * createGuiMathMatrix(GuiView & lv);
3407 Dialog * createGuiNomenclature(GuiView & lv);
3408 Dialog * createGuiNote(GuiView & lv);
3409 Dialog * createGuiParagraph(GuiView & lv);
3410 Dialog * createGuiPhantom(GuiView & lv);
3411 Dialog * createGuiPreferences(GuiView & lv);
3412 Dialog * createGuiPrint(GuiView & lv);
3413 Dialog * createGuiPrintindex(GuiView & lv);
3414 Dialog * createGuiPrintNomencl(GuiView & lv);
3415 Dialog * createGuiRef(GuiView & lv);
3416 Dialog * createGuiSearch(GuiView & lv);
3417 Dialog * createGuiSearchAdv(GuiView & lv);
3418 Dialog * createGuiSendTo(GuiView & lv);
3419 Dialog * createGuiShowFile(GuiView & lv);
3420 Dialog * createGuiSpellchecker(GuiView & lv);
3421 Dialog * createGuiSymbols(GuiView & lv);
3422 Dialog * createGuiTabularCreate(GuiView & lv);
3423 Dialog * createGuiTabular(GuiView & lv);
3424 Dialog * createGuiTexInfo(GuiView & lv);
3425 Dialog * createGuiTextHSpace(GuiView & lv);
3426 Dialog * createGuiToc(GuiView & lv);
3427 Dialog * createGuiThesaurus(GuiView & lv);
3428 Dialog * createGuiHyperlink(GuiView & lv);
3429 Dialog * createGuiVSpace(GuiView & lv);
3430 Dialog * createGuiViewSource(GuiView & lv);
3431 Dialog * createGuiWrap(GuiView & lv);
3432 Dialog * createGuiProgressView(GuiView & lv);
3436 Dialog * GuiView::build(string const & name)
3438 LASSERT(isValidName(name), return 0);
3440 if (name == "aboutlyx")
3441 return createGuiAbout(*this);
3442 if (name == "bibitem")
3443 return createGuiBibitem(*this);
3444 if (name == "bibtex")
3445 return createGuiBibtex(*this);
3447 return createGuiBox(*this);
3448 if (name == "branch")
3449 return createGuiBranch(*this);
3450 if (name == "changes")
3451 return createGuiChanges(*this);
3452 if (name == "character")
3453 return createGuiCharacter(*this);
3454 if (name == "citation")
3455 return createGuiCitation(*this);
3456 if (name == "compare")
3457 return createGuiCompare(*this);
3458 if (name == "document")
3459 return createGuiDocument(*this);
3460 if (name == "errorlist")
3461 return createGuiErrorList(*this);
3463 return createGuiERT(*this);
3464 if (name == "external")
3465 return createGuiExternal(*this);
3467 return createGuiShowFile(*this);
3468 if (name == "findreplace")
3469 return createGuiSearch(*this);
3470 if (name == "findreplaceadv")
3471 return createGuiSearchAdv(*this);
3472 if (name == "float")
3473 return createGuiFloat(*this);
3474 if (name == "graphics")
3475 return createGuiGraphics(*this);
3477 return createGuiHyperlink(*this);
3478 if (name == "include")
3479 return createGuiInclude(*this);
3480 if (name == "index")
3481 return createGuiIndex(*this);
3482 if (name == "index_print")
3483 return createGuiPrintindex(*this);
3485 return createGuiInfo(*this);
3486 if (name == "label")
3487 return createGuiLabel(*this);
3488 if (name == "listings")
3489 return createGuiListings(*this);
3491 return createGuiLog(*this);
3492 if (name == "mathdelimiter")
3493 return createGuiDelimiter(*this);
3494 if (name == "mathspace")
3495 return createGuiMathHSpace(*this);
3496 if (name == "mathmatrix")
3497 return createGuiMathMatrix(*this);
3498 if (name == "nomenclature")
3499 return createGuiNomenclature(*this);
3500 if (name == "nomencl_print")
3501 return createGuiPrintNomencl(*this);
3503 return createGuiNote(*this);
3504 if (name == "paragraph")
3505 return createGuiParagraph(*this);
3506 if (name == "phantom")
3507 return createGuiPhantom(*this);
3508 if (name == "prefs")
3509 return createGuiPreferences(*this);
3510 if (name == "print")
3511 return createGuiPrint(*this);
3513 return createGuiRef(*this);
3514 if (name == "sendto")
3515 return createGuiSendTo(*this);
3516 if (name == "space")
3517 return createGuiTextHSpace(*this);
3518 if (name == "spellchecker")
3519 return createGuiSpellchecker(*this);
3520 if (name == "symbols")
3521 return createGuiSymbols(*this);
3522 if (name == "tabular")
3523 return createGuiTabular(*this);
3524 if (name == "tabularcreate")
3525 return createGuiTabularCreate(*this);
3526 if (name == "texinfo")
3527 return createGuiTexInfo(*this);
3528 if (name == "thesaurus")
3529 return createGuiThesaurus(*this);
3531 return createGuiToc(*this);
3532 if (name == "view-source")
3533 return createGuiViewSource(*this);
3534 if (name == "vspace")
3535 return createGuiVSpace(*this);
3537 return createGuiWrap(*this);
3538 if (name == "progress")
3539 return createGuiProgressView(*this);
3545 void GuiView::selectDocumentBuffer(Buffer const * p_buf) {
3546 setBuffer(const_cast<Buffer *>(p_buf));
3550 } // namespace frontend
3553 #include "moc_GuiView.cpp"