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 "GuiKeySymbol.h"
26 #include "GuiToolbar.h"
27 #include "GuiWorkArea.h"
28 #include "LayoutBox.h"
32 #include "qt_helpers.h"
34 #include "frontends/alert.h"
36 #include "buffer_funcs.h"
38 #include "BufferList.h"
39 #include "BufferParams.h"
40 #include "BufferView.h"
41 #include "Converter.h"
43 #include "CutAndPaste.h"
45 #include "ErrorList.h"
47 #include "FuncStatus.h"
48 #include "FuncRequest.h"
52 #include "LyXAction.h"
57 #include "Paragraph.h"
58 #include "SpellChecker.h"
59 #include "TextClass.h"
64 #include "support/convert.h"
65 #include "support/debug.h"
66 #include "support/ExceptionMessage.h"
67 #include "support/FileName.h"
68 #include "support/filetools.h"
69 #include "support/gettext.h"
70 #include "support/filetools.h"
71 #include "support/ForkedCalls.h"
72 #include "support/lassert.h"
73 #include "support/lstrings.h"
74 #include "support/os.h"
75 #include "support/Package.h"
76 #include "support/Path.h"
77 #include "support/Systemcall.h"
78 #include "support/Timeout.h"
79 #include "support/ProgressInterface.h"
80 #include "GuiProgress.h"
83 #include <QApplication>
84 #include <QCloseEvent>
86 #include <QDesktopWidget>
87 #include <QDragEnterEvent>
94 #include <QPixmapCache>
96 #include <QPushButton>
100 #include <QStackedWidget>
101 #include <QStatusBar>
106 #include <QScrollBar>
108 #define EXPORT_in_THREAD 1
111 // QtConcurrent was introduced in Qt 4.4
112 #if (QT_VERSION >= 0x040400)
114 #include <QFutureWatcher>
115 #include <QtConcurrentRun>
118 #include <boost/bind.hpp>
122 #ifdef HAVE_SYS_TIME_H
123 # include <sys/time.h>
130 using namespace lyx::support;
137 class BackgroundWidget : public QWidget
142 LYXERR(Debug::GUI, "show banner: " << lyxrc.show_banner);
143 /// The text to be written on top of the pixmap
144 QString const text = lyx_version ?
145 qt_("version ") + lyx_version : qt_("unknown version");
146 splash_ = getPixmap("images/", "banner", "png");
148 QPainter pain(&splash_);
149 pain.setPen(QColor(0, 0, 0));
151 // The font used to display the version info
152 font.setStyleHint(QFont::SansSerif);
153 font.setWeight(QFont::Bold);
154 font.setPointSize(int(toqstr(lyxrc.font_sizes[FONT_SIZE_LARGE]).toDouble()));
156 pain.drawText(260, 15, text);
159 void paintEvent(QPaintEvent *)
161 int x = (width() - splash_.width()) / 2;
162 int y = (height() - splash_.height()) / 2;
164 pain.drawPixmap(x, y, splash_);
172 /// Toolbar store providing access to individual toolbars by name.
173 typedef map<string, GuiToolbar *> ToolbarMap;
175 typedef boost::shared_ptr<Dialog> DialogPtr;
180 struct GuiView::GuiViewPrivate
182 GuiViewPrivate(GuiView * gv)
183 : gv_(gv), current_work_area_(0), current_main_work_area_(0),
184 layout_(0), autosave_timeout_(5000),
187 // hardcode here the platform specific icon size
188 smallIconSize = 14; // scaling problems
189 normalIconSize = 20; // ok, default
190 bigIconSize = 26; // better for some math icons
192 splitter_ = new QSplitter;
193 bg_widget_ = new BackgroundWidget;
194 stack_widget_ = new QStackedWidget;
195 stack_widget_->addWidget(bg_widget_);
196 stack_widget_->addWidget(splitter_);
198 progress_ = new GuiProgress(gv);
205 delete stack_widget_;
209 QMenu * toolBarPopup(GuiView * parent)
211 // FIXME: translation
212 QMenu * menu = new QMenu(parent);
213 QActionGroup * iconSizeGroup = new QActionGroup(parent);
215 QAction * smallIcons = new QAction(iconSizeGroup);
216 smallIcons->setText(qt_("Small-sized icons"));
217 smallIcons->setCheckable(true);
218 QObject::connect(smallIcons, SIGNAL(triggered()),
219 parent, SLOT(smallSizedIcons()));
220 menu->addAction(smallIcons);
222 QAction * normalIcons = new QAction(iconSizeGroup);
223 normalIcons->setText(qt_("Normal-sized icons"));
224 normalIcons->setCheckable(true);
225 QObject::connect(normalIcons, SIGNAL(triggered()),
226 parent, SLOT(normalSizedIcons()));
227 menu->addAction(normalIcons);
229 QAction * bigIcons = new QAction(iconSizeGroup);
230 bigIcons->setText(qt_("Big-sized icons"));
231 bigIcons->setCheckable(true);
232 QObject::connect(bigIcons, SIGNAL(triggered()),
233 parent, SLOT(bigSizedIcons()));
234 menu->addAction(bigIcons);
236 unsigned int cur = parent->iconSize().width();
237 if ( cur == parent->d.smallIconSize)
238 smallIcons->setChecked(true);
239 else if (cur == parent->d.normalIconSize)
240 normalIcons->setChecked(true);
241 else if (cur == parent->d.bigIconSize)
242 bigIcons->setChecked(true);
249 stack_widget_->setCurrentWidget(bg_widget_);
250 bg_widget_->setUpdatesEnabled(true);
253 TabWorkArea * tabWorkArea(int i)
255 return dynamic_cast<TabWorkArea *>(splitter_->widget(i));
258 TabWorkArea * currentTabWorkArea()
260 if (splitter_->count() == 1)
261 // The first TabWorkArea is always the first one, if any.
262 return tabWorkArea(0);
264 for (int i = 0; i != splitter_->count(); ++i) {
265 TabWorkArea * twa = tabWorkArea(i);
266 if (current_main_work_area_ == twa->currentWorkArea())
270 // None has the focus so we just take the first one.
271 return tabWorkArea(0);
274 #if (QT_VERSION >= 0x040400)
275 void setPreviewFuture(QFuture<docstring> const & f)
277 if (preview_watcher_.isRunning()) {
278 // we prefer to cancel this preview in order to keep a snappy
282 preview_watcher_.setFuture(f);
288 GuiWorkArea * current_work_area_;
289 GuiWorkArea * current_main_work_area_;
290 QSplitter * splitter_;
291 QStackedWidget * stack_widget_;
292 BackgroundWidget * bg_widget_;
294 ToolbarMap toolbars_;
295 ProgressInterface* progress_;
296 /// The main layout box.
298 * \warning Don't Delete! The layout box is actually owned by
299 * whichever toolbar contains it. All the GuiView class needs is a
300 * means of accessing it.
302 * FIXME: replace that with a proper model so that we are not limited
303 * to only one dialog.
308 map<string, DialogPtr> dialogs_;
310 unsigned int smallIconSize;
311 unsigned int normalIconSize;
312 unsigned int bigIconSize;
314 QTimer statusbar_timer_;
315 /// auto-saving of buffers
316 Timeout autosave_timeout_;
317 /// flag against a race condition due to multiclicks, see bug #1119
321 TocModels toc_models_;
323 #if (QT_VERSION >= 0x040400)
325 QFutureWatcher<docstring> autosave_watcher_;
326 QFutureWatcher<docstring> preview_watcher_;
328 struct DummyWatcher { bool isRunning(){return false;} };
329 DummyWatcher preview_watcher_;
334 GuiView::GuiView(int id)
335 : d(*new GuiViewPrivate(this)), id_(id), closing_(false)
337 // GuiToolbars *must* be initialised before the menu bar.
338 normalSizedIcons(); // at least on Mac the default is 32 otherwise, which is huge
341 // set ourself as the current view. This is needed for the menu bar
342 // filling, at least for the static special menu item on Mac. Otherwise
343 // they are greyed out.
344 guiApp->setCurrentView(this);
346 // Fill up the menu bar.
347 guiApp->menus().fillMenuBar(menuBar(), this, true);
349 setCentralWidget(d.stack_widget_);
351 // Start autosave timer
352 if (lyxrc.autosave) {
353 d.autosave_timeout_.timeout.connect(boost::bind(&GuiView::autoSave, this));
354 d.autosave_timeout_.setTimeout(lyxrc.autosave * 1000);
355 d.autosave_timeout_.start();
357 connect(&d.statusbar_timer_, SIGNAL(timeout()),
358 this, SLOT(clearMessage()));
360 // We don't want to keep the window in memory if it is closed.
361 setAttribute(Qt::WA_DeleteOnClose, true);
363 #if (!defined(Q_WS_WIN) && !defined(Q_WS_MACX))
364 // assign an icon to main form. We do not do it under Qt/Win or Qt/Mac,
365 // since the icon is provided in the application bundle.
366 setWindowIcon(getPixmap("images/", "lyx", "png"));
370 setAcceptDrops(true);
372 statusBar()->setSizeGripEnabled(true);
375 #if (QT_VERSION >= 0x040400)
376 connect(&d.autosave_watcher_, SIGNAL(finished()), this,
377 SLOT(threadFinished()));
378 connect(&d.preview_watcher_, SIGNAL(finished()), this,
379 SLOT(threadFinished()));
382 connect(this, SIGNAL(triggerShowDialog(QString const &, QString const &, Inset *)),
383 SLOT(doShowDialog(QString const &, QString const &, Inset *)));
385 // Forbid too small unresizable window because it can happen
386 // with some window manager under X11.
387 setMinimumSize(300, 200);
389 if (lyxrc.allow_geometry_session) {
390 // Now take care of session management.
395 // no session handling, default to a sane size.
396 setGeometry(50, 50, 690, 510);
399 // clear session data if any.
401 settings.remove("views");
411 void GuiView::threadFinished()
413 #if (QT_VERSION >= 0x040400)
414 QFutureWatcher<docstring> const * watcher =
415 static_cast<QFutureWatcher<docstring> const *>(sender());
416 message(watcher->result());
421 void GuiView::saveLayout() const
424 settings.beginGroup("views");
425 settings.beginGroup(QString::number(id_));
427 settings.setValue("pos", pos());
428 settings.setValue("size", size());
430 settings.setValue("geometry", saveGeometry());
432 settings.setValue("layout", saveState(0));
433 settings.setValue("icon_size", iconSize());
437 bool GuiView::restoreLayout()
440 settings.beginGroup("views");
441 settings.beginGroup(QString::number(id_));
442 QString const icon_key = "icon_size";
443 if (!settings.contains(icon_key))
446 //code below is skipped when when ~/.config/LyX is (re)created
447 setIconSize(settings.value(icon_key).toSize());
449 QPoint pos = settings.value("pos", QPoint(50, 50)).toPoint();
450 QSize size = settings.value("size", QSize(690, 510)).toSize();
454 // Work-around for bug #6034: the window ends up in an undetermined
455 // state when trying to restore a maximized window when it is
456 // already maximized.
457 if (!(windowState() & Qt::WindowMaximized))
458 if (!restoreGeometry(settings.value("geometry").toByteArray()))
459 setGeometry(50, 50, 690, 510);
461 // Make sure layout is correctly oriented.
462 setLayoutDirection(qApp->layoutDirection());
464 // Allow the toc and view-source dock widget to be restored if needed.
466 if ((dialog = findOrBuild("toc", true)))
467 // see bug 5082. At least setup title and enabled state.
468 // Visibility will be adjusted by restoreState below.
469 dialog->prepareView();
470 if ((dialog = findOrBuild("view-source", true)))
471 dialog->prepareView();
472 if ((dialog = findOrBuild("progress", true)))
473 dialog->prepareView();
475 if (!restoreState(settings.value("layout").toByteArray(), 0))
482 GuiToolbar * GuiView::toolbar(string const & name)
484 ToolbarMap::iterator it = d.toolbars_.find(name);
485 if (it != d.toolbars_.end())
488 LYXERR(Debug::GUI, "Toolbar::display: no toolbar named " << name);
489 message(bformat(_("Unknown toolbar \"%1$s\""), from_utf8(name)));
494 void GuiView::constructToolbars()
496 ToolbarMap::iterator it = d.toolbars_.begin();
497 for (; it != d.toolbars_.end(); ++it)
501 // I don't like doing this here, but the standard toolbar
502 // destroys this object when it's destroyed itself (vfr)
503 d.layout_ = new LayoutBox(*this);
504 d.stack_widget_->addWidget(d.layout_);
505 d.layout_->move(0,0);
507 // extracts the toolbars from the backend
508 Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
509 Toolbars::Infos::iterator end = guiApp->toolbars().end();
510 for (; cit != end; ++cit)
511 d.toolbars_[cit->name] = new GuiToolbar(*cit, *this);
515 void GuiView::initToolbars()
517 // extracts the toolbars from the backend
518 Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
519 Toolbars::Infos::iterator end = guiApp->toolbars().end();
520 for (; cit != end; ++cit) {
521 GuiToolbar * tb = toolbar(cit->name);
524 int const visibility = guiApp->toolbars().defaultVisibility(cit->name);
526 tb->setVisible(false);
527 tb->setVisibility(visibility);
529 if (visibility & Toolbars::TOP) {
531 addToolBarBreak(Qt::TopToolBarArea);
532 addToolBar(Qt::TopToolBarArea, tb);
535 if (visibility & Toolbars::BOTTOM) {
536 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
537 #if (QT_VERSION >= 0x040202)
538 addToolBarBreak(Qt::BottomToolBarArea);
540 addToolBar(Qt::BottomToolBarArea, tb);
543 if (visibility & Toolbars::LEFT) {
544 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
545 #if (QT_VERSION >= 0x040202)
546 addToolBarBreak(Qt::LeftToolBarArea);
548 addToolBar(Qt::LeftToolBarArea, tb);
551 if (visibility & Toolbars::RIGHT) {
552 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
553 #if (QT_VERSION >= 0x040202)
554 addToolBarBreak(Qt::RightToolBarArea);
556 addToolBar(Qt::RightToolBarArea, tb);
559 if (visibility & Toolbars::ON)
560 tb->setVisible(true);
565 TocModels & GuiView::tocModels()
567 return d.toc_models_;
571 void GuiView::setFocus()
573 LYXERR(Debug::DEBUG, "GuiView::setFocus()" << this);
574 // Make sure LyXFunc points to the correct view.
575 guiApp->setCurrentView(this);
576 QMainWindow::setFocus();
577 if (d.current_work_area_)
578 d.current_work_area_->setFocus();
582 QMenu * GuiView::createPopupMenu()
584 return d.toolBarPopup(this);
588 void GuiView::showEvent(QShowEvent * e)
590 LYXERR(Debug::GUI, "Passed Geometry "
591 << size().height() << "x" << size().width()
592 << "+" << pos().x() << "+" << pos().y());
594 if (d.splitter_->count() == 0)
595 // No work area, switch to the background widget.
598 QMainWindow::showEvent(e);
602 /** Destroy only all tabbed WorkAreas. Destruction of other WorkAreas
603 ** is responsibility of the container (e.g., dialog)
605 void GuiView::closeEvent(QCloseEvent * close_event)
607 LYXERR(Debug::DEBUG, "GuiView::closeEvent()");
612 // it can happen that this event arrives without selecting the view,
613 // e.g. when clicking the close button on a background window.
615 if (!closeWorkAreaAll()) {
617 close_event->ignore();
621 // Make sure that nothing will use this to be closed View.
622 guiApp->unregisterView(this);
624 if (isFullScreen()) {
625 // Switch off fullscreen before closing.
630 // Make sure the timer time out will not trigger a statusbar update.
631 d.statusbar_timer_.stop();
633 // Saving fullscreen requires additional tweaks in the toolbar code.
634 // It wouldn't also work under linux natively.
635 if (lyxrc.allow_geometry_session) {
636 // Save this window geometry and layout.
638 // Then the toolbar private states.
639 ToolbarMap::iterator end = d.toolbars_.end();
640 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
641 it->second->saveSession();
642 // Now take care of all other dialogs:
643 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
644 for (; it!= d.dialogs_.end(); ++it)
645 it->second->saveSession();
648 close_event->accept();
652 void GuiView::dragEnterEvent(QDragEnterEvent * event)
654 if (event->mimeData()->hasUrls())
656 /// \todo Ask lyx-devel is this is enough:
657 /// if (event->mimeData()->hasFormat("text/plain"))
658 /// event->acceptProposedAction();
662 void GuiView::dropEvent(QDropEvent * event)
664 QList<QUrl> files = event->mimeData()->urls();
668 LYXERR(Debug::GUI, "GuiView::dropEvent: got URLs!");
669 for (int i = 0; i != files.size(); ++i) {
670 string const file = os::internal_path(fromqstr(
671 files.at(i).toLocalFile()));
675 string const ext = support::getExtension(file);
676 vector<const Format *> found_formats;
678 // Find all formats that have the correct extension.
679 vector<const Format *> const & import_formats
680 = theConverters().importableFormats();
681 vector<const Format *>::const_iterator it = import_formats.begin();
682 for (; it != import_formats.end(); ++it)
683 if ((*it)->extension() == ext)
684 found_formats.push_back(*it);
687 if (found_formats.size() >= 1) {
688 if (found_formats.size() > 1) {
689 //FIXME: show a dialog to choose the correct importable format
691 "Multiple importable formats found, selecting first");
693 string const arg = found_formats[0]->name() + " " + file;
694 cmd = FuncRequest(LFUN_BUFFER_IMPORT, arg);
697 //FIXME: do we have to explicitly check whether it's a lyx file?
699 "No formats found, trying to open it as a lyx file");
700 cmd = FuncRequest(LFUN_FILE_OPEN, file);
703 // Asynchronously post the event. DropEvent usually comes
704 // from the BufferView. But reloading a file might close
705 // the BufferView from within its own event handler.
706 guiApp->dispatchDelayed(cmd);
712 void GuiView::message(docstring const & str)
714 if (ForkedProcess::iAmAChild())
717 // call is moved to GUI-thread by GuiProgress
718 d.progress_->appendMessage(toqstr(str));
722 void GuiView::updateMessage(QString const & str)
724 statusBar()->showMessage(str);
725 d.statusbar_timer_.stop();
726 d.statusbar_timer_.start(3000);
730 void GuiView::smallSizedIcons()
732 setIconSize(QSize(d.smallIconSize, d.smallIconSize));
736 void GuiView::normalSizedIcons()
738 setIconSize(QSize(d.normalIconSize, d.normalIconSize));
742 void GuiView::bigSizedIcons()
744 setIconSize(QSize(d.bigIconSize, d.bigIconSize));
748 void GuiView::clearMessage()
750 // FIXME: This code was introduced in r19643 to fix bug #4123. However,
751 // the hasFocus function mostly returns false, even if the focus is on
752 // a workarea in this view.
756 d.statusbar_timer_.stop();
760 void GuiView::updateWindowTitle(GuiWorkArea * wa)
762 if (wa != d.current_work_area_
763 || wa->bufferView().buffer().isInternal())
765 setWindowTitle(qt_("LyX: ") + wa->windowTitle());
766 setWindowIconText(wa->windowIconText());
770 void GuiView::on_currentWorkAreaChanged(GuiWorkArea * wa)
773 disconnectBufferView();
774 connectBufferView(wa->bufferView());
775 connectBuffer(wa->bufferView().buffer());
776 d.current_work_area_ = wa;
777 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
778 this, SLOT(updateWindowTitle(GuiWorkArea *)));
779 updateWindowTitle(wa);
783 // The document settings needs to be reinitialised.
784 updateDialog("document", "");
786 // Buffer-dependent dialogs must be updated. This is done here because
787 // some dialogs require buffer()->text.
792 void GuiView::on_lastWorkAreaRemoved()
795 // We already are in a close event. Nothing more to do.
798 if (d.splitter_->count() > 1)
799 // We have a splitter so don't close anything.
802 // Reset and updates the dialogs.
803 d.toc_models_.reset(0);
804 updateDialog("document", "");
807 resetWindowTitleAndIconText();
810 if (lyxrc.open_buffers_in_tabs)
811 // Nothing more to do, the window should stay open.
814 if (guiApp->viewIds().size() > 1) {
820 // On Mac we also close the last window because the application stay
821 // resident in memory. On other platforms we don't close the last
822 // window because this would quit the application.
828 void GuiView::updateStatusBar()
830 // let the user see the explicit message
831 if (d.statusbar_timer_.isActive())
838 void GuiView::showMessage()
840 QString msg = toqstr(theGuiApp()->viewStatusMessage());
842 BufferView const * bv = currentBufferView();
844 msg = toqstr(bv->cursor().currentState());
846 msg = qt_("Welcome to LyX!");
848 statusBar()->showMessage(msg);
852 bool GuiView::event(QEvent * e)
856 // Useful debug code:
857 //case QEvent::ActivationChange:
858 //case QEvent::WindowDeactivate:
859 //case QEvent::Paint:
860 //case QEvent::Enter:
861 //case QEvent::Leave:
862 //case QEvent::HoverEnter:
863 //case QEvent::HoverLeave:
864 //case QEvent::HoverMove:
865 //case QEvent::StatusTip:
866 //case QEvent::DragEnter:
867 //case QEvent::DragLeave:
871 case QEvent::WindowActivate: {
872 GuiView * old_view = guiApp->currentView();
873 if (this == old_view) {
875 return QMainWindow::event(e);
877 if (old_view && old_view->currentBufferView()) {
878 // save current selection to the selection buffer to allow
879 // middle-button paste in this window.
880 cap::saveSelection(old_view->currentBufferView()->cursor());
882 guiApp->setCurrentView(this);
883 if (d.current_work_area_) {
884 BufferView & bv = d.current_work_area_->bufferView();
885 connectBufferView(bv);
886 connectBuffer(bv.buffer());
887 // The document structure, name and dialogs might have
888 // changed in another view.
890 // The document settings needs to be reinitialised.
891 updateDialog("document", "");
894 resetWindowTitleAndIconText();
897 return QMainWindow::event(e);
900 case QEvent::ShortcutOverride: {
903 #if (!defined Q_WS_X11) || (QT_VERSION >= 0x040500)
904 if (isFullScreen() && menuBar()->isHidden()) {
905 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
906 // FIXME: we should also try to detect special LyX shortcut such as
907 // Alt-P and Alt-M. Right now there is a hack in
908 // GuiWorkArea::processKeySym() that hides again the menubar for
910 if (ke->modifiers() & Qt::AltModifier && ke->key() != Qt::Key_Alt) {
912 return QMainWindow::event(e);
917 if (d.current_work_area_)
918 // Nothing special to do.
919 return QMainWindow::event(e);
921 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
922 // Let Qt handle menu access and the Tab keys to navigate keys to navigate
924 if (ke->modifiers() & Qt::AltModifier || ke->key() == Qt::Key_Tab
925 || ke->key() == Qt::Key_Backtab)
926 return QMainWindow::event(e);
928 // Allow processing of shortcuts that are allowed even when no Buffer
931 setKeySymbol(&sym, ke);
932 guiApp->processKeySym(sym, q_key_state(ke->modifiers()));
938 return QMainWindow::event(e);
942 void GuiView::resetWindowTitleAndIconText()
944 setWindowTitle(qt_("LyX"));
945 setWindowIconText(qt_("LyX"));
948 bool GuiView::focusNextPrevChild(bool /*next*/)
955 void GuiView::setBusy(bool busy)
957 if (d.current_work_area_) {
958 d.current_work_area_->setUpdatesEnabled(!busy);
960 d.current_work_area_->stopBlinkingCursor();
962 d.current_work_area_->startBlinkingCursor();
966 QApplication::setOverrideCursor(Qt::WaitCursor);
968 QApplication::restoreOverrideCursor();
972 GuiWorkArea * GuiView::workArea(Buffer & buffer)
974 if (currentWorkArea()
975 && ¤tWorkArea()->bufferView().buffer() == &buffer)
976 return (GuiWorkArea *) currentWorkArea();
977 if (TabWorkArea * twa = d.currentTabWorkArea())
978 return twa->workArea(buffer);
983 GuiWorkArea * GuiView::addWorkArea(Buffer & buffer)
985 // Automatically create a TabWorkArea if there are none yet.
986 TabWorkArea * tab_widget = d.splitter_->count()
987 ? d.currentTabWorkArea() : addTabWorkArea();
988 return tab_widget->addWorkArea(buffer, *this);
992 TabWorkArea * GuiView::addTabWorkArea()
994 TabWorkArea * twa = new TabWorkArea;
995 QObject::connect(twa, SIGNAL(currentWorkAreaChanged(GuiWorkArea *)),
996 this, SLOT(on_currentWorkAreaChanged(GuiWorkArea *)));
997 QObject::connect(twa, SIGNAL(lastWorkAreaRemoved()),
998 this, SLOT(on_lastWorkAreaRemoved()));
1000 d.splitter_->addWidget(twa);
1001 d.stack_widget_->setCurrentWidget(d.splitter_);
1006 GuiWorkArea const * GuiView::currentWorkArea() const
1008 return d.current_work_area_;
1012 GuiWorkArea * GuiView::currentWorkArea()
1014 return d.current_work_area_;
1018 GuiWorkArea const * GuiView::currentMainWorkArea() const
1020 if (d.currentTabWorkArea() == NULL)
1022 return d.currentTabWorkArea()->currentWorkArea();
1026 GuiWorkArea * GuiView::currentMainWorkArea()
1028 if (d.currentTabWorkArea() == NULL)
1030 return d.currentTabWorkArea()->currentWorkArea();
1034 void GuiView::setCurrentWorkArea(GuiWorkArea * wa)
1036 LYXERR(Debug::DEBUG, "Setting current wa: " << wa << endl);
1038 d.current_work_area_ = NULL;
1042 GuiWorkArea * old_gwa = theGuiApp()->currentView()->currentWorkArea();
1046 if (currentBufferView())
1047 cap::saveSelection(currentBufferView()->cursor());
1049 theGuiApp()->setCurrentView(this);
1050 d.current_work_area_ = wa;
1051 for (int i = 0; i != d.splitter_->count(); ++i) {
1052 if (d.tabWorkArea(i)->setCurrentWorkArea(wa)) {
1053 //if (d.current_main_work_area_)
1054 // d.current_main_work_area_->setFrameStyle(QFrame::NoFrame);
1055 d.current_main_work_area_ = wa;
1056 //d.current_main_work_area_->setFrameStyle(QFrame::Box | QFrame::Plain);
1057 //d.current_main_work_area_->setLineWidth(2);
1058 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() << ", Current main wa: " << currentMainWorkArea());
1062 LYXERR(Debug::DEBUG, "This is not a tabbed wa");
1063 on_currentWorkAreaChanged(wa);
1064 BufferView & bv = wa->bufferView();
1065 bv.cursor().fixIfBroken();
1067 wa->setUpdatesEnabled(true);
1068 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() << ", Current main wa: " << currentMainWorkArea());
1072 void GuiView::removeWorkArea(GuiWorkArea * wa)
1074 LASSERT(wa, return);
1075 if (wa == d.current_work_area_) {
1077 disconnectBufferView();
1078 d.current_work_area_ = 0;
1079 d.current_main_work_area_ = 0;
1082 bool found_twa = false;
1083 for (int i = 0; i != d.splitter_->count(); ++i) {
1084 TabWorkArea * twa = d.tabWorkArea(i);
1085 if (twa->removeWorkArea(wa)) {
1086 // Found in this tab group, and deleted the GuiWorkArea.
1088 if (twa->count() != 0) {
1089 if (d.current_work_area_ == 0)
1090 // This means that we are closing the current GuiWorkArea, so
1091 // switch to the next GuiWorkArea in the found TabWorkArea.
1092 setCurrentWorkArea(twa->currentWorkArea());
1094 // No more WorkAreas in this tab group, so delete it.
1101 // It is not a tabbed work area (i.e., the search work area), so it
1102 // should be deleted by other means.
1103 LASSERT(found_twa, /* */);
1105 if (d.current_work_area_ == 0) {
1106 if (d.splitter_->count() != 0) {
1107 TabWorkArea * twa = d.currentTabWorkArea();
1108 setCurrentWorkArea(twa->currentWorkArea());
1110 // No more work areas, switch to the background widget.
1111 setCurrentWorkArea(0);
1117 LayoutBox * GuiView::getLayoutDialog() const
1123 void GuiView::updateLayoutList()
1126 d.layout_->updateContents(false);
1130 void GuiView::updateToolbars()
1132 ToolbarMap::iterator end = d.toolbars_.end();
1133 if (d.current_work_area_) {
1135 d.current_work_area_->bufferView().cursor().inMathed();
1137 lyx::getStatus(FuncRequest(LFUN_LAYOUT_TABULAR)).enabled();
1139 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).enabled() &&
1140 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).onoff(true);
1141 bool const mathmacrotemplate =
1142 lyx::getStatus(FuncRequest(LFUN_IN_MATHMACROTEMPLATE)).enabled();
1144 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1145 it->second->update(math, table, review, mathmacrotemplate);
1147 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1148 it->second->update(false, false, false, false);
1152 void GuiView::setBuffer(Buffer * newBuffer)
1154 LYXERR(Debug::DEBUG, "Setting buffer: " << newBuffer << endl);
1155 LASSERT(newBuffer, return);
1158 GuiWorkArea * wa = workArea(*newBuffer);
1160 newBuffer->masterBuffer()->updateLabels();
1161 wa = addWorkArea(*newBuffer);
1163 //Disconnect the old buffer...there's no new one.
1166 connectBuffer(*newBuffer);
1167 connectBufferView(wa->bufferView());
1168 setCurrentWorkArea(wa);
1174 void GuiView::connectBuffer(Buffer & buf)
1176 buf.setGuiDelegate(this);
1180 void GuiView::disconnectBuffer()
1182 if (d.current_work_area_)
1183 d.current_work_area_->bufferView().buffer().setGuiDelegate(0);
1187 void GuiView::connectBufferView(BufferView & bv)
1189 bv.setGuiDelegate(this);
1193 void GuiView::disconnectBufferView()
1195 if (d.current_work_area_)
1196 d.current_work_area_->bufferView().setGuiDelegate(0);
1200 void GuiView::errors(string const & error_type, bool from_master)
1202 ErrorList & el = from_master ?
1203 documentBufferView()->buffer().masterBuffer()->errorList(error_type)
1204 : documentBufferView()->buffer().errorList(error_type);
1205 string data = error_type;
1207 data = "from_master|" + error_type;
1209 showDialog("errorlist", data);
1213 void GuiView::updateTocItem(string const & type, DocIterator const & dit)
1215 d.toc_models_.updateItem(toqstr(type), dit);
1219 void GuiView::structureChanged()
1221 d.toc_models_.reset(documentBufferView());
1222 // Navigator needs more than a simple update in this case. It needs to be
1224 updateDialog("toc", "");
1228 void GuiView::updateDialog(string const & name, string const & data)
1230 if (!isDialogVisible(name))
1233 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
1234 if (it == d.dialogs_.end())
1237 Dialog * const dialog = it->second.get();
1238 if (dialog->isVisibleView())
1239 dialog->initialiseParams(data);
1243 BufferView * GuiView::documentBufferView()
1245 return currentMainWorkArea()
1246 ? ¤tMainWorkArea()->bufferView()
1251 BufferView const * GuiView::documentBufferView() const
1253 return currentMainWorkArea()
1254 ? ¤tMainWorkArea()->bufferView()
1259 BufferView * GuiView::currentBufferView()
1261 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1265 BufferView const * GuiView::currentBufferView() const
1267 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1271 #if (QT_VERSION >= 0x040400)
1272 static docstring saveAndDestroyBuffer(Buffer * buffer, FileName const & fname)
1275 FileName const tmp_ret = FileName::tempName("lyxauto");
1276 if (!tmp_ret.empty()) {
1277 if (buffer->writeFile(tmp_ret))
1278 failed = !tmp_ret.moveTo(fname);
1281 // failed to write/rename tmp_ret so try writing direct
1282 failed = buffer->writeFile(fname);
1286 ? _("Automatic save failed!")
1287 : _("Automatic save done.");
1292 void GuiView::autoSave()
1294 LYXERR(Debug::INFO, "Running autoSave()");
1296 Buffer * buffer = documentBufferView()
1297 ? &documentBufferView()->buffer() : 0;
1301 #if (QT_VERSION >= 0x040400)
1302 QFuture<docstring> f = QtConcurrent::run(saveAndDestroyBuffer, buffer->clone(),
1303 buffer->getAutosaveFilename());
1304 d.autosave_watcher_.setFuture(f);
1311 void GuiView::resetAutosaveTimers()
1314 d.autosave_timeout_.restart();
1318 bool GuiView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1321 Buffer * buf = currentBufferView()
1322 ? ¤tBufferView()->buffer() : 0;
1323 Buffer * doc_buffer = documentBufferView()
1324 ? &(documentBufferView()->buffer()) : 0;
1326 // Check whether we need a buffer
1327 if (!lyxaction.funcHasFlag(cmd.action, LyXAction::NoBuffer) && !buf) {
1328 // no, exit directly
1329 flag.message(from_utf8(N_("Command not allowed with"
1330 "out any document open")));
1331 flag.setEnabled(false);
1335 if (cmd.origin == FuncRequest::TOC) {
1336 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
1338 if (toc->getStatus(documentBufferView()->cursor(), cmd, fs))
1341 flag.setEnabled(false);
1345 switch(cmd.action) {
1346 case LFUN_BUFFER_IMPORT:
1349 case LFUN_MASTER_BUFFER_UPDATE:
1350 case LFUN_MASTER_BUFFER_VIEW:
1351 enable = doc_buffer && doc_buffer->parent() != 0
1352 && !d.preview_watcher_.isRunning();
1355 case LFUN_BUFFER_UPDATE:
1356 case LFUN_BUFFER_VIEW: {
1357 if (!doc_buffer || d.preview_watcher_.isRunning()) {
1361 string format = to_utf8(cmd.argument());
1362 if (cmd.argument().empty())
1363 format = doc_buffer->getDefaultOutputFormat();
1364 enable = doc_buffer->isExportableFormat(format);
1368 case LFUN_BUFFER_RELOAD:
1369 enable = doc_buffer && !doc_buffer->isUnnamed()
1370 && doc_buffer->fileName().exists()
1371 && (!doc_buffer->isClean()
1372 || doc_buffer->isExternallyModified(Buffer::timestamp_method));
1375 case LFUN_BUFFER_CHILD_OPEN:
1376 enable = doc_buffer;
1379 case LFUN_BUFFER_WRITE:
1380 enable = doc_buffer && (doc_buffer->isUnnamed() || !doc_buffer->isClean());
1383 //FIXME: This LFUN should be moved to GuiApplication.
1384 case LFUN_BUFFER_WRITE_ALL: {
1385 // We enable the command only if there are some modified buffers
1386 Buffer * first = theBufferList().first();
1391 // We cannot use a for loop as the buffer list is a cycle.
1393 if (!b->isClean()) {
1397 b = theBufferList().next(b);
1398 } while (b != first);
1402 case LFUN_BUFFER_WRITE_AS:
1403 enable = doc_buffer;
1406 case LFUN_BUFFER_CLOSE:
1407 enable = doc_buffer;
1410 case LFUN_BUFFER_CLOSE_ALL:
1411 enable = theBufferList().last() != theBufferList().first();
1414 case LFUN_SPLIT_VIEW:
1415 if (cmd.getArg(0) == "vertical")
1416 enable = doc_buffer && (d.splitter_->count() == 1 ||
1417 d.splitter_->orientation() == Qt::Vertical);
1419 enable = doc_buffer && (d.splitter_->count() == 1 ||
1420 d.splitter_->orientation() == Qt::Horizontal);
1423 case LFUN_CLOSE_TAB_GROUP:
1424 enable = d.currentTabWorkArea();
1427 case LFUN_TOOLBAR_TOGGLE:
1428 if (GuiToolbar * t = toolbar(cmd.getArg(0)))
1429 flag.setOnOff(t->isVisible());
1432 case LFUN_DROP_LAYOUTS_CHOICE:
1436 case LFUN_UI_TOGGLE:
1437 flag.setOnOff(isFullScreen());
1440 case LFUN_DIALOG_DISCONNECT_INSET:
1443 case LFUN_DIALOG_HIDE:
1444 // FIXME: should we check if the dialog is shown?
1447 case LFUN_DIALOG_TOGGLE:
1448 flag.setOnOff(isDialogVisible(cmd.getArg(0)));
1449 // fall through to set "enable"
1450 case LFUN_DIALOG_SHOW: {
1451 string const name = cmd.getArg(0);
1453 enable = name == "aboutlyx"
1454 || name == "file" //FIXME: should be removed.
1456 || name == "texinfo"
1457 || name == "progress"
1458 || name == "compare";
1459 else if (name == "print")
1460 enable = doc_buffer->isExportable("dvi")
1461 && lyxrc.print_command != "none";
1462 else if (name == "character" || name == "symbols") {
1463 if (!buf || buf->isReadonly()
1464 || !currentBufferView()->cursor().inTexted())
1467 // FIXME we should consider passthru
1469 Inset const & in = currentBufferView()->cursor().inset();
1470 enable = !in.getLayout().isPassThru();
1473 else if (name == "latexlog")
1474 enable = FileName(doc_buffer->logName()).isReadableFile();
1475 else if (name == "spellchecker")
1476 enable = theSpellChecker() && !doc_buffer->isReadonly();
1477 else if (name == "vclog")
1478 enable = doc_buffer->lyxvc().inUse();
1482 case LFUN_DIALOG_UPDATE: {
1483 string const name = cmd.getArg(0);
1485 enable = name == "prefs";
1489 case LFUN_COMMAND_EXECUTE:
1491 case LFUN_MENU_OPEN:
1492 // Nothing to check.
1495 case LFUN_COMPLETION_INLINE:
1496 if (!d.current_work_area_
1497 || !d.current_work_area_->completer().inlinePossible(
1498 currentBufferView()->cursor()))
1502 case LFUN_COMPLETION_POPUP:
1503 if (!d.current_work_area_
1504 || !d.current_work_area_->completer().popupPossible(
1505 currentBufferView()->cursor()))
1509 case LFUN_COMPLETION_COMPLETE:
1510 if (!d.current_work_area_
1511 || !d.current_work_area_->completer().inlinePossible(
1512 currentBufferView()->cursor()))
1516 case LFUN_COMPLETION_ACCEPT:
1517 if (!d.current_work_area_
1518 || (!d.current_work_area_->completer().popupVisible()
1519 && !d.current_work_area_->completer().inlineVisible()
1520 && !d.current_work_area_->completer().completionAvailable()))
1524 case LFUN_COMPLETION_CANCEL:
1525 if (!d.current_work_area_
1526 || (!d.current_work_area_->completer().popupVisible()
1527 && !d.current_work_area_->completer().inlineVisible()))
1531 case LFUN_BUFFER_ZOOM_OUT:
1532 enable = doc_buffer && lyxrc.zoom > 10;
1535 case LFUN_BUFFER_ZOOM_IN:
1536 enable = doc_buffer;
1539 case LFUN_BUFFER_NEXT:
1540 case LFUN_BUFFER_PREVIOUS:
1541 // FIXME: should we check is there is an previous or next buffer?
1543 case LFUN_BUFFER_SWITCH:
1544 // toggle on the current buffer, but do not toggle off
1545 // the other ones (is that a good idea?)
1547 && to_utf8(cmd.argument()) == doc_buffer->absFileName())
1548 flag.setOnOff(true);
1551 case LFUN_VC_REGISTER:
1552 enable = doc_buffer && !doc_buffer->lyxvc().inUse();
1554 case LFUN_VC_CHECK_IN:
1555 enable = doc_buffer && doc_buffer->lyxvc().checkInEnabled();
1557 case LFUN_VC_CHECK_OUT:
1558 enable = doc_buffer && doc_buffer->lyxvc().checkOutEnabled();
1560 case LFUN_VC_LOCKING_TOGGLE:
1561 enable = doc_buffer && !doc_buffer->isReadonly()
1562 && doc_buffer->lyxvc().lockingToggleEnabled();
1563 flag.setOnOff(enable && !doc_buffer->lyxvc().locker().empty());
1565 case LFUN_VC_REVERT:
1566 enable = doc_buffer && doc_buffer->lyxvc().inUse();
1568 case LFUN_VC_UNDO_LAST:
1569 enable = doc_buffer && doc_buffer->lyxvc().undoLastEnabled();
1571 case LFUN_VC_REPO_UPDATE:
1572 enable = doc_buffer && doc_buffer->lyxvc().inUse();
1574 case LFUN_VC_COMMAND: {
1575 if (cmd.argument().empty())
1577 if (!doc_buffer && contains(cmd.getArg(0), 'D'))
1582 case LFUN_SERVER_GOTO_FILE_ROW:
1590 flag.setEnabled(false);
1596 static FileName selectTemplateFile()
1598 FileDialog dlg(qt_("Select template file"));
1599 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1600 dlg.setButton1(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
1602 FileDialog::Result result = dlg.open(toqstr(lyxrc.template_path),
1603 QStringList(qt_("LyX Documents (*.lyx)")));
1605 if (result.first == FileDialog::Later)
1607 if (result.second.isEmpty())
1609 return FileName(fromqstr(result.second));
1613 Buffer * GuiView::loadDocument(FileName const & filename, bool tolastfiles)
1617 Buffer * newBuffer = checkAndLoadLyXFile(filename);
1620 message(_("Document not loaded."));
1625 setBuffer(newBuffer);
1627 // scroll to the position when the file was last closed
1628 if (lyxrc.use_lastfilepos) {
1629 LastFilePosSection::FilePos filepos =
1630 theSession().lastFilePos().load(filename);
1631 documentBufferView()->moveToPosition(filepos.pit, filepos.pos, 0, 0);
1635 theSession().lastFiles().add(filename);
1642 void GuiView::openDocument(string const & fname)
1644 string initpath = lyxrc.document_path;
1646 if (documentBufferView()) {
1647 string const trypath = documentBufferView()->buffer().filePath();
1648 // If directory is writeable, use this as default.
1649 if (FileName(trypath).isDirWritable())
1655 if (fname.empty()) {
1656 FileDialog dlg(qt_("Select document to open"), LFUN_FILE_OPEN);
1657 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1658 dlg.setButton2(qt_("Examples|#E#e"),
1659 toqstr(addPath(package().system_support().absFilename(), "examples")));
1661 QStringList filter(qt_("LyX Documents (*.lyx)"));
1662 filter << qt_("LyX-1.3.x Documents (*.lyx13)")
1663 << qt_("LyX-1.4.x Documents (*.lyx14)")
1664 << qt_("LyX-1.5.x Documents (*.lyx15)")
1665 << qt_("LyX-1.6.x Documents (*.lyx16)");
1666 FileDialog::Result result =
1667 dlg.open(toqstr(initpath), filter);
1669 if (result.first == FileDialog::Later)
1672 filename = fromqstr(result.second);
1674 // check selected filename
1675 if (filename.empty()) {
1676 message(_("Canceled."));
1682 // get absolute path of file and add ".lyx" to the filename if
1684 FileName const fullname =
1685 fileSearch(string(), filename, "lyx", support::may_not_exist);
1686 if (!fullname.empty())
1687 filename = fullname.absFilename();
1689 if (!fullname.onlyPath().isDirectory()) {
1690 Alert::warning(_("Invalid filename"),
1691 bformat(_("The directory in the given path\n%1$s\ndoes not exist."),
1692 from_utf8(fullname.absFilename())));
1695 // if the file doesn't exist, let the user create one
1696 if (!fullname.exists()) {
1697 // the user specifically chose this name. Believe him.
1698 Buffer * const b = newFile(filename, string(), true);
1704 docstring const disp_fn = makeDisplayPath(filename);
1705 message(bformat(_("Opening document %1$s..."), disp_fn));
1708 Buffer * buf = loadDocument(fullname);
1710 buf->updateLabels();
1712 buf->errors("Parse");
1713 str2 = bformat(_("Document %1$s opened."), disp_fn);
1714 if (buf->lyxvc().inUse())
1715 str2 += " " + from_utf8(buf->lyxvc().versionString()) +
1716 " " + _("Version control detected.");
1718 str2 = bformat(_("Could not open document %1$s"), disp_fn);
1723 // FIXME: clean that
1724 static bool import(GuiView * lv, FileName const & filename,
1725 string const & format, ErrorList & errorList)
1727 FileName const lyxfile(support::changeExtension(filename.absFilename(), ".lyx"));
1729 string loader_format;
1730 vector<string> loaders = theConverters().loaders();
1731 if (find(loaders.begin(), loaders.end(), format) == loaders.end()) {
1732 for (vector<string>::const_iterator it = loaders.begin();
1733 it != loaders.end(); ++it) {
1734 if (!theConverters().isReachable(format, *it))
1737 string const tofile =
1738 support::changeExtension(filename.absFilename(),
1739 formats.extension(*it));
1740 if (!theConverters().convert(0, filename, FileName(tofile),
1741 filename, format, *it, errorList))
1743 loader_format = *it;
1746 if (loader_format.empty()) {
1747 frontend::Alert::error(_("Couldn't import file"),
1748 bformat(_("No information for importing the format %1$s."),
1749 formats.prettyName(format)));
1753 loader_format = format;
1755 if (loader_format == "lyx") {
1756 Buffer * buf = lv->loadDocument(lyxfile);
1759 buf->updateLabels();
1761 buf->errors("Parse");
1763 Buffer * const b = newFile(lyxfile.absFilename(), string(), true);
1767 bool as_paragraphs = loader_format == "textparagraph";
1768 string filename2 = (loader_format == format) ? filename.absFilename()
1769 : support::changeExtension(filename.absFilename(),
1770 formats.extension(loader_format));
1771 lv->currentBufferView()->insertPlaintextFile(FileName(filename2),
1773 guiApp->setCurrentView(lv);
1774 lyx::dispatch(FuncRequest(LFUN_MARK_OFF));
1781 void GuiView::importDocument(string const & argument)
1784 string filename = split(argument, format, ' ');
1786 LYXERR(Debug::INFO, format << " file: " << filename);
1788 // need user interaction
1789 if (filename.empty()) {
1790 string initpath = lyxrc.document_path;
1791 if (documentBufferView()) {
1792 string const trypath = documentBufferView()->buffer().filePath();
1793 // If directory is writeable, use this as default.
1794 if (FileName(trypath).isDirWritable())
1798 docstring const text = bformat(_("Select %1$s file to import"),
1799 formats.prettyName(format));
1801 FileDialog dlg(toqstr(text), LFUN_BUFFER_IMPORT);
1802 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1803 dlg.setButton2(qt_("Examples|#E#e"),
1804 toqstr(addPath(package().system_support().absFilename(), "examples")));
1806 docstring filter = formats.prettyName(format);
1809 filter += from_utf8(formats.extension(format));
1812 FileDialog::Result result =
1813 dlg.open(toqstr(initpath), fileFilters(toqstr(filter)));
1815 if (result.first == FileDialog::Later)
1818 filename = fromqstr(result.second);
1820 // check selected filename
1821 if (filename.empty())
1822 message(_("Canceled."));
1825 if (filename.empty())
1828 // get absolute path of file
1829 FileName const fullname(support::makeAbsPath(filename));
1831 FileName const lyxfile(support::changeExtension(fullname.absFilename(), ".lyx"));
1833 // Check if the document already is open
1834 Buffer * buf = theBufferList().getBuffer(lyxfile);
1837 if (!closeBuffer()) {
1838 message(_("Canceled."));
1843 docstring const displaypath = makeDisplayPath(lyxfile.absFilename(), 30);
1845 // if the file exists already, and we didn't do
1846 // -i lyx thefile.lyx, warn
1847 if (lyxfile.exists() && fullname != lyxfile) {
1849 docstring text = bformat(_("The document %1$s already exists.\n\n"
1850 "Do you want to overwrite that document?"), displaypath);
1851 int const ret = Alert::prompt(_("Overwrite document?"),
1852 text, 0, 1, _("&Overwrite"), _("&Cancel"));
1855 message(_("Canceled."));
1860 message(bformat(_("Importing %1$s..."), displaypath));
1861 ErrorList errorList;
1862 if (import(this, fullname, format, errorList))
1863 message(_("imported."));
1865 message(_("file not imported!"));
1867 // FIXME (Abdel 12/08/06): Is there a need to display the error list here?
1871 void GuiView::newDocument(string const & filename, bool from_template)
1873 FileName initpath(lyxrc.document_path);
1874 if (documentBufferView()) {
1875 FileName const trypath(documentBufferView()->buffer().filePath());
1876 // If directory is writeable, use this as default.
1877 if (trypath.isDirWritable())
1881 string templatefile;
1882 if (from_template) {
1883 templatefile = selectTemplateFile().absFilename();
1884 if (templatefile.empty())
1889 if (filename.empty())
1890 b = newUnnamedFile(initpath, to_utf8(_("newfile")), templatefile);
1892 b = newFile(filename, templatefile, true);
1897 // If no new document could be created, it is unsure
1898 // whether there is a valid BufferView.
1899 if (currentBufferView())
1900 // Ensure the cursor is correctly positioned on screen.
1901 currentBufferView()->showCursor();
1905 void GuiView::insertLyXFile(docstring const & fname)
1907 BufferView * bv = documentBufferView();
1912 FileName filename(to_utf8(fname));
1914 if (!filename.empty()) {
1915 bv->insertLyXFile(filename);
1919 // Launch a file browser
1921 string initpath = lyxrc.document_path;
1922 string const trypath = bv->buffer().filePath();
1923 // If directory is writeable, use this as default.
1924 if (FileName(trypath).isDirWritable())
1928 FileDialog dlg(qt_("Select LyX document to insert"), LFUN_FILE_INSERT);
1929 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1930 dlg.setButton2(qt_("Examples|#E#e"),
1931 toqstr(addPath(package().system_support().absFilename(),
1934 FileDialog::Result result = dlg.open(toqstr(initpath),
1935 QStringList(qt_("LyX Documents (*.lyx)")));
1937 if (result.first == FileDialog::Later)
1941 filename.set(fromqstr(result.second));
1943 // check selected filename
1944 if (filename.empty()) {
1945 // emit message signal.
1946 message(_("Canceled."));
1950 bv->insertLyXFile(filename);
1954 void GuiView::insertPlaintextFile(docstring const & fname,
1957 BufferView * bv = documentBufferView();
1961 if (!fname.empty() && !FileName::isAbsolute(to_utf8(fname))) {
1962 message(_("Absolute filename expected."));
1967 FileName filename(to_utf8(fname));
1969 if (!filename.empty()) {
1970 bv->insertPlaintextFile(filename, asParagraph);
1974 FileDialog dlg(qt_("Select file to insert"), (asParagraph ?
1975 LFUN_FILE_INSERT_PLAINTEXT_PARA : LFUN_FILE_INSERT_PLAINTEXT));
1977 FileDialog::Result result = dlg.open(toqstr(bv->buffer().filePath()),
1978 QStringList(qt_("All Files (*)")));
1980 if (result.first == FileDialog::Later)
1984 filename.set(fromqstr(result.second));
1986 // check selected filename
1987 if (filename.empty()) {
1988 // emit message signal.
1989 message(_("Canceled."));
1993 bv->insertPlaintextFile(filename, asParagraph);
1997 bool GuiView::renameBuffer(Buffer & b, docstring const & newname)
1999 FileName fname = b.fileName();
2000 FileName const oldname = fname;
2002 if (!newname.empty()) {
2004 fname = support::makeAbsPath(to_utf8(newname), oldname.onlyPath().absFilename());
2006 // Switch to this Buffer.
2009 // No argument? Ask user through dialog.
2011 FileDialog dlg(qt_("Choose a filename to save document as"),
2012 LFUN_BUFFER_WRITE_AS);
2013 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2014 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
2016 if (!isLyXFilename(fname.absFilename()))
2017 fname.changeExtension(".lyx");
2019 FileDialog::Result result =
2020 dlg.save(toqstr(fname.onlyPath().absFilename()),
2021 QStringList(qt_("LyX Documents (*.lyx)")),
2022 toqstr(fname.onlyFileName()));
2024 if (result.first == FileDialog::Later)
2027 fname.set(fromqstr(result.second));
2032 if (!isLyXFilename(fname.absFilename()))
2033 fname.changeExtension(".lyx");
2036 if (FileName(fname).exists()) {
2037 docstring const file = makeDisplayPath(fname.absFilename(), 30);
2038 docstring text = bformat(_("The document %1$s already "
2039 "exists.\n\nDo you want to "
2040 "overwrite that document?"),
2042 int const ret = Alert::prompt(_("Overwrite document?"),
2043 text, 0, 2, _("&Overwrite"), _("&Rename"), _("&Cancel"));
2046 case 1: return renameBuffer(b, docstring());
2047 case 2: return false;
2051 FileName oldauto = b.getAutosaveFilename();
2053 // Ok, change the name of the buffer
2054 b.setFileName(fname.absFilename());
2056 bool unnamed = b.isUnnamed();
2057 b.setUnnamed(false);
2058 b.saveCheckSum(fname);
2060 // bring the autosave file with us, just in case.
2061 b.moveAutosaveFile(oldauto);
2063 if (!saveBuffer(b)) {
2064 oldauto = b.getAutosaveFilename();
2065 b.setFileName(oldname.absFilename());
2066 b.setUnnamed(unnamed);
2067 b.saveCheckSum(oldname);
2068 b.moveAutosaveFile(oldauto);
2076 bool GuiView::saveBuffer(Buffer & b)
2078 if (workArea(b) && workArea(b)->inDialogMode())
2082 return renameBuffer(b, docstring());
2085 theSession().lastFiles().add(b.fileName());
2089 // Switch to this Buffer.
2092 // FIXME: we don't tell the user *WHY* the save failed !!
2093 docstring const file = makeDisplayPath(b.absFileName(), 30);
2094 docstring text = bformat(_("The document %1$s could not be saved.\n\n"
2095 "Do you want to rename the document and "
2096 "try again?"), file);
2097 int const ret = Alert::prompt(_("Rename and save?"),
2098 text, 0, 2, _("&Rename"), _("&Retry"), _("&Cancel"));
2101 if (!renameBuffer(b, docstring()))
2110 return saveBuffer(b);
2114 bool GuiView::hideWorkArea(GuiWorkArea * wa)
2116 return closeWorkArea(wa, false);
2120 bool GuiView::closeWorkArea(GuiWorkArea * wa)
2122 Buffer & buf = wa->bufferView().buffer();
2123 return closeWorkArea(wa, !buf.parent());
2127 bool GuiView::closeBuffer()
2129 GuiWorkArea * wa = currentMainWorkArea();
2130 setCurrentWorkArea(wa);
2131 Buffer & buf = wa->bufferView().buffer();
2132 return wa && closeWorkArea(wa, !buf.parent());
2136 void GuiView::writeSession() const {
2137 GuiWorkArea const * active_wa = currentMainWorkArea();
2138 for (int i = 0; i < d.splitter_->count(); ++i) {
2139 TabWorkArea * twa = d.tabWorkArea(i);
2140 for (int j = 0; j < twa->count(); ++j) {
2141 GuiWorkArea * wa = static_cast<GuiWorkArea *>(twa->widget(j));
2142 Buffer & buf = wa->bufferView().buffer();
2143 theSession().lastOpened().add(buf.fileName(), wa == active_wa);
2149 bool GuiView::closeBufferAll()
2151 // Close the workareas in all other views
2152 QList<int> const ids = guiApp->viewIds();
2153 for (int i = 0; i != ids.size(); ++i) {
2154 if (id_ != ids[i] && !guiApp->view(ids[i]).closeWorkAreaAll())
2158 // Close our own workareas
2159 if (!closeWorkAreaAll())
2162 // Now close the hidden buffers. We prevent hidden buffers from being
2163 // dirty, so we can just close them.
2164 theBufferList().closeAll();
2169 bool GuiView::closeWorkAreaAll()
2171 setCurrentWorkArea(currentMainWorkArea());
2173 // We might be in a situation that there is still a tabWorkArea, but
2174 // there are no tabs anymore. This can happen when we get here after a
2175 // TabWorkArea::lastWorkAreaRemoved() signal. Therefore we count how
2176 // many TabWorkArea's have no documents anymore.
2179 // We have to call count() each time, because it can happen that
2180 // more than one splitter will disappear in one iteration (bug 5998).
2181 for (; d.splitter_->count() > empty_twa; ) {
2182 TabWorkArea * twa = d.tabWorkArea(empty_twa);
2184 if (twa->count() == 0)
2187 setCurrentWorkArea(twa->currentWorkArea());
2188 if (!closeTabWorkArea(twa))
2196 bool GuiView::closeWorkArea(GuiWorkArea * wa, bool close_buffer)
2201 Buffer & buf = wa->bufferView().buffer();
2204 return closeBuffer(buf);
2206 if (!inMultiTabs(wa))
2207 if (!saveBufferIfNeeded(buf, true))
2215 bool GuiView::closeBuffer(Buffer & buf)
2217 // If we are in a close_event all children will be closed in some time,
2218 // so no need to do it here. This will ensure that the children end up
2219 // in the session file in the correct order. If we close the master
2220 // buffer, we can close or release the child buffers here too.
2222 vector<Buffer *> clist = buf.getChildren(false);
2223 for (vector<Buffer *>::const_iterator it = clist.begin();
2224 it != clist.end(); ++it) {
2225 // If a child is dirty, do not close
2226 // without user intervention
2227 //FIXME: should we look in other tabworkareas?
2228 Buffer * child_buf = *it;
2229 GuiWorkArea * child_wa = workArea(*child_buf);
2231 if (!closeWorkArea(child_wa, true))
2234 theBufferList().releaseChild(&buf, child_buf);
2237 // goto bookmark to update bookmark pit.
2238 //FIXME: we should update only the bookmarks related to this buffer!
2239 LYXERR(Debug::DEBUG, "GuiView::closeBuffer()");
2240 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
2241 theLyXFunc().gotoBookmark(i+1, false, false);
2243 if (saveBufferIfNeeded(buf, false)) {
2244 theBufferList().release(&buf);
2251 bool GuiView::closeTabWorkArea(TabWorkArea * twa)
2253 while (twa == d.currentTabWorkArea()) {
2254 twa->setCurrentIndex(twa->count()-1);
2256 GuiWorkArea * wa = twa->currentWorkArea();
2257 Buffer & b = wa->bufferView().buffer();
2259 // We only want to close the buffer if the same buffer is not visible
2260 // in another view, and if this is not a child and if we are closing
2261 // a view (not a tabgroup).
2262 bool const close_buffer =
2263 !inMultiViews(wa) && !b.parent() && closing_;
2265 if (!closeWorkArea(wa, close_buffer))
2272 bool GuiView::saveBufferIfNeeded(Buffer & buf, bool hiding)
2274 if (buf.isClean() || buf.paragraphs().empty())
2277 // Switch to this Buffer.
2282 if (buf.isUnnamed())
2283 file = from_utf8(buf.fileName().onlyFileName());
2285 file = buf.fileName().displayName(30);
2287 // Bring this window to top before asking questions.
2292 if (hiding && buf.isUnnamed()) {
2293 docstring const text = bformat(_("The document %1$s has not been "
2294 "saved yet.\n\nDo you want to save "
2295 "the document?"), file);
2296 ret = Alert::prompt(_("Save new document?"),
2297 text, 0, 1, _("&Save"), _("&Cancel"));
2301 docstring const text = bformat(_("The document %1$s has unsaved changes."
2302 "\n\nDo you want to save the document or discard the changes?"), file);
2303 ret = Alert::prompt(_("Save changed document?"),
2304 text, 0, 2, _("&Save"), _("&Discard"), _("&Cancel"));
2309 if (!saveBuffer(buf))
2313 // if we crash after this we could
2314 // have no autosave file but I guess
2315 // this is really improbable (Jug)
2316 buf.removeAutosaveFile();
2318 // revert all changes
2329 bool GuiView::inMultiTabs(GuiWorkArea * wa)
2331 Buffer & buf = wa->bufferView().buffer();
2333 for (int i = 0; i != d.splitter_->count(); ++i) {
2334 GuiWorkArea * wa_ = d.tabWorkArea(i)->workArea(buf);
2335 if (wa_ && wa_ != wa)
2338 return inMultiViews(wa);
2342 bool GuiView::inMultiViews(GuiWorkArea * wa)
2344 QList<int> const ids = guiApp->viewIds();
2345 Buffer & buf = wa->bufferView().buffer();
2348 for (int i = 0; i != ids.size() && found_twa <= 1; ++i) {
2352 if (guiApp->view(ids[i]).workArea(buf))
2359 void GuiView::gotoNextOrPreviousBuffer(NextOrPrevious np)
2361 Buffer * const curbuf = documentBufferView()
2362 ? &documentBufferView()->buffer() : 0;
2363 Buffer * nextbuf = curbuf;
2365 if (np == NEXTBUFFER)
2366 nextbuf = theBufferList().next(nextbuf);
2368 nextbuf = theBufferList().previous(nextbuf);
2369 if (nextbuf == curbuf)
2375 if (workArea(*nextbuf))
2382 /// make sure the document is saved
2383 static bool ensureBufferClean(Buffer * buffer)
2385 LASSERT(buffer, return false);
2386 if (buffer->isClean() && !buffer->isUnnamed())
2389 docstring const file = buffer->fileName().displayName(30);
2392 if (!buffer->isUnnamed()) {
2393 text = bformat(_("The document %1$s has unsaved "
2394 "changes.\n\nDo you want to save "
2395 "the document?"), file);
2396 title = _("Save changed document?");
2399 text = bformat(_("The document %1$s has not been "
2400 "saved yet.\n\nDo you want to save "
2401 "the document?"), file);
2402 title = _("Save new document?");
2404 int const ret = Alert::prompt(title, text, 0, 1, _("&Save"), _("&Cancel"));
2407 dispatch(FuncRequest(LFUN_BUFFER_WRITE));
2409 return buffer->isClean() && !buffer->isUnnamed();
2413 void GuiView::reloadBuffer()
2415 Buffer * buf = &documentBufferView()->buffer();
2420 void GuiView::checkExternallyModifiedBuffers()
2422 BufferList::iterator bit = theBufferList().begin();
2423 BufferList::iterator const bend = theBufferList().end();
2424 for (; bit != bend; ++bit) {
2425 if ((*bit)->fileName().exists()
2426 && (*bit)->isExternallyModified(Buffer::checksum_method)) {
2427 docstring text = bformat(_("Document \n%1$s\n has been externally modified."
2428 " Reload now? Any local changes will be lost."),
2429 from_utf8((*bit)->absFileName()));
2430 int const ret = Alert::prompt(_("Reload externally changed document?"),
2431 text, 0, 1, _("&Reload"), _("&Cancel"));
2439 void GuiView::dispatchVC(FuncRequest const & cmd)
2441 // message for statusbar
2443 Buffer * buffer = documentBufferView()
2444 ? &(documentBufferView()->buffer()) : 0;
2446 switch (cmd.action) {
2447 case LFUN_VC_REGISTER:
2448 if (!buffer || !ensureBufferClean(buffer))
2450 if (!buffer->lyxvc().inUse()) {
2451 if (buffer->lyxvc().registrer())
2456 case LFUN_VC_CHECK_IN:
2457 if (!buffer || !ensureBufferClean(buffer))
2459 if (buffer->lyxvc().inUse() && !buffer->isReadonly()) {
2460 msg = buffer->lyxvc().checkIn();
2465 case LFUN_VC_CHECK_OUT:
2466 if (!buffer || !ensureBufferClean(buffer))
2468 if (buffer->lyxvc().inUse()) {
2469 msg = buffer->lyxvc().checkOut();
2474 case LFUN_VC_LOCKING_TOGGLE:
2475 LASSERT(buffer, return);
2476 if (!ensureBufferClean(buffer) || buffer->isReadonly())
2478 if (buffer->lyxvc().inUse()) {
2479 string res = buffer->lyxvc().lockingToggle();
2481 frontend::Alert::error(_("Revision control error."),
2482 _("Error when setting the locking property."));
2490 case LFUN_VC_REVERT:
2491 LASSERT(buffer, return);
2492 buffer->lyxvc().revert();
2496 case LFUN_VC_UNDO_LAST:
2497 LASSERT(buffer, return);
2498 buffer->lyxvc().undoLast();
2502 case LFUN_VC_REPO_UPDATE:
2503 LASSERT(buffer, return);
2504 if (ensureBufferClean(buffer)) {
2505 msg = buffer->lyxvc().repoUpdate();
2506 checkExternallyModifiedBuffers();
2510 case LFUN_VC_COMMAND: {
2511 string flag = cmd.getArg(0);
2512 if (buffer && contains(flag, 'R') && !ensureBufferClean(buffer))
2515 if (contains(flag, 'M')) {
2516 if (!Alert::askForText(message, _("LyX VC: Log Message")))
2519 string path = cmd.getArg(1);
2520 if (contains(path, "$$p") && buffer)
2521 path = subst(path, "$$p", buffer->filePath());
2522 LYXERR(Debug::LYXVC, "Directory: " << path);
2524 if (!pp.isReadableDirectory()) {
2525 lyxerr << _("Directory is not accessible.") << endl;
2528 support::PathChanger p(pp);
2530 string command = cmd.getArg(2);
2531 if (command.empty())
2534 command = subst(command, "$$i", buffer->absFileName());
2535 command = subst(command, "$$p", buffer->filePath());
2537 command = subst(command, "$$m", to_utf8(message));
2538 LYXERR(Debug::LYXVC, "Command: " << command);
2540 one.startscript(Systemcall::Wait, command);
2544 if (contains(flag, 'I'))
2545 buffer->markDirty();
2546 if (contains(flag, 'R'))
2556 message(from_utf8(msg));
2560 void GuiView::openChildDocument(string const & fname)
2562 LASSERT(documentBufferView(), return);
2563 Buffer & buffer = documentBufferView()->buffer();
2564 FileName const filename = support::makeAbsPath(fname, buffer.filePath());
2565 documentBufferView()->saveBookmark(false);
2567 bool parsed = false;
2568 if (theBufferList().exists(filename)) {
2569 child = theBufferList().getBuffer(filename);
2571 message(bformat(_("Opening child document %1$s..."),
2572 makeDisplayPath(filename.absFilename())));
2573 child = loadDocument(filename, false);
2579 // Set the parent name of the child document.
2580 // This makes insertion of citations and references in the child work,
2581 // when the target is in the parent or another child document.
2582 child->setParent(&buffer);
2583 child->masterBuffer()->updateLabels();
2586 child->errors("Parse");
2590 bool GuiView::goToFileRow(string const & argument)
2594 size_t i = argument.find_last_of(' ');
2595 if (i != string::npos) {
2596 file_name = os::internal_path(trim(argument.substr(0, i)));
2597 istringstream is(argument.substr(i + 1));
2602 if (i == string::npos) {
2603 LYXERR0("Wrong argument: " << argument);
2607 string const abstmp = package().temp_dir().absFilename();
2608 string const realtmp = package().temp_dir().realPath();
2609 // We have to use os::path_prefix_is() here, instead of
2610 // simply prefixIs(), because the file name comes from
2611 // an external application and may need case adjustment.
2612 if (os::path_prefix_is(file_name, abstmp, os::CASE_ADJUSTED)
2613 || os::path_prefix_is(file_name, realtmp, os::CASE_ADJUSTED)) {
2614 // Needed by inverse dvi search. If it is a file
2615 // in tmpdir, call the apropriated function.
2616 // If tmpdir is a symlink, we may have the real
2617 // path passed back, so we correct for that.
2618 if (!prefixIs(file_name, abstmp))
2619 file_name = subst(file_name, realtmp, abstmp);
2620 buf = theBufferList().getBufferFromTmp(file_name);
2622 // Must replace extension of the file to be .lyx
2623 // and get full path
2624 FileName const s = fileSearch(string(),
2625 support::changeExtension(file_name, ".lyx"), "lyx");
2626 // Either change buffer or load the file
2627 if (theBufferList().exists(s))
2628 buf = theBufferList().getBuffer(s);
2629 else if (s.exists()) {
2630 buf = loadDocument(s);
2631 buf->updateLabels();
2632 buf->errors("Parse");
2635 _("File does not exist: %1$s"),
2636 makeDisplayPath(file_name)));
2641 documentBufferView()->setCursorFromRow(row);
2646 #if (QT_VERSION >= 0x040400)
2647 static docstring exportAndDestroy(Buffer * buffer, string const & format)
2649 bool const success = buffer->doExport(format, true);
2652 ? bformat(_("Successful export to format: %1$s"), from_utf8(format))
2653 : bformat(_("Error exporting to format: %1$s"), from_utf8(format));
2657 static docstring previewAndDestroy(Buffer * buffer, string const & format)
2659 bool const success = buffer->preview(format);
2662 ? bformat(_("Successful preview of format: %1$s"), from_utf8(format))
2663 : bformat(_("Error previewing format: %1$s"), from_utf8(format));
2668 bool GuiView::dispatch(FuncRequest const & cmd)
2670 BufferView * bv = currentBufferView();
2671 // By default we won't need any update.
2673 bv->cursor().updateFlags(Update::None);
2675 Buffer * doc_buffer = documentBufferView()
2676 ? &(documentBufferView()->buffer()) : 0;
2678 bool dispatched = true;
2680 if (cmd.origin == FuncRequest::TOC) {
2681 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
2682 toc->doDispatch(bv->cursor(), cmd);
2686 string const argument = to_utf8(cmd.argument());
2688 switch(cmd.action) {
2689 case LFUN_BUFFER_CHILD_OPEN:
2690 openChildDocument(to_utf8(cmd.argument()));
2693 case LFUN_BUFFER_IMPORT:
2694 importDocument(to_utf8(cmd.argument()));
2697 case LFUN_BUFFER_EXPORT: {
2700 if (cmd.argument() == "custom") {
2701 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "sendto"));
2704 if (doc_buffer->doExport(argument, false)) {
2705 message(bformat(_("Error exporting to format: %1$s."),
2711 case LFUN_BUFFER_UPDATE: {
2714 string format = argument;
2715 if (argument.empty())
2716 format = doc_buffer->getDefaultOutputFormat();
2717 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
2718 d.progress_->clearMessages();
2719 message(_("Exporting ..."));
2720 QFuture<docstring> f = QtConcurrent::run(exportAndDestroy,
2721 doc_buffer->clone(), format);
2722 d.setPreviewFuture(f);
2724 doc_buffer->doExport(format, true);
2728 case LFUN_BUFFER_VIEW: {
2731 string format = argument;
2732 if (argument.empty())
2733 format = doc_buffer->getDefaultOutputFormat();
2734 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
2735 d.progress_->clearMessages();
2736 message(_("Previewing ..."));
2737 QFuture<docstring> f = QtConcurrent::run(previewAndDestroy,
2738 doc_buffer->clone(), format);
2739 d.setPreviewFuture(f);
2741 doc_buffer->preview(format);
2745 case LFUN_MASTER_BUFFER_UPDATE: {
2748 string format = argument;
2749 Buffer const * master = doc_buffer->masterBuffer();
2750 if (argument.empty())
2751 format = master->getDefaultOutputFormat();
2752 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
2753 QFuture<docstring> f = QtConcurrent::run(exportAndDestroy,
2754 master->clone(), format);
2755 d.setPreviewFuture(f);
2757 master->doExport(format, true);
2761 case LFUN_MASTER_BUFFER_VIEW: {
2762 string format = argument;
2763 Buffer const * master = doc_buffer->masterBuffer();
2764 if (argument.empty())
2765 format = master->getDefaultOutputFormat();
2766 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
2767 QFuture<docstring> f = QtConcurrent::run(previewAndDestroy,
2768 master->clone(), format);
2769 d.setPreviewFuture(f);
2771 master->preview(format);
2775 case LFUN_BUFFER_SWITCH:
2776 if (FileName::isAbsolute(to_utf8(cmd.argument()))) {
2778 theBufferList().getBuffer(FileName(to_utf8(cmd.argument())));
2782 message(_("Document not loaded"));
2786 case LFUN_BUFFER_NEXT:
2787 gotoNextOrPreviousBuffer(NEXTBUFFER);
2790 case LFUN_BUFFER_PREVIOUS:
2791 gotoNextOrPreviousBuffer(PREVBUFFER);
2794 case LFUN_COMMAND_EXECUTE: {
2795 bool const show_it = cmd.argument() != "off";
2796 // FIXME: this is a hack, "minibuffer" should not be
2798 if (GuiToolbar * t = toolbar("minibuffer")) {
2799 t->setVisible(show_it);
2800 if (show_it && t->commandBuffer())
2801 t->commandBuffer()->setFocus();
2805 case LFUN_DROP_LAYOUTS_CHOICE:
2806 d.layout_->showPopup();
2809 case LFUN_MENU_OPEN:
2810 if (QMenu * menu = guiApp->menus().menu(toqstr(cmd.argument()), *this))
2811 menu->exec(QCursor::pos());
2814 case LFUN_FILE_INSERT:
2815 insertLyXFile(cmd.argument());
2817 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
2818 insertPlaintextFile(cmd.argument(), true);
2821 case LFUN_FILE_INSERT_PLAINTEXT:
2822 insertPlaintextFile(cmd.argument(), false);
2825 case LFUN_BUFFER_RELOAD: {
2826 LASSERT(doc_buffer, break);
2827 docstring const file = makeDisplayPath(doc_buffer->absFileName(), 20);
2828 docstring text = bformat(_("Any changes will be lost. Are you sure "
2829 "you want to revert to the saved version of the document %1$s?"), file);
2830 int const ret = Alert::prompt(_("Revert to saved document?"),
2831 text, 1, 1, _("&Revert"), _("&Cancel"));
2834 doc_buffer->markClean();
2840 case LFUN_BUFFER_WRITE:
2841 LASSERT(doc_buffer, break);
2842 saveBuffer(*doc_buffer);
2845 case LFUN_BUFFER_WRITE_AS:
2846 LASSERT(doc_buffer, break);
2847 renameBuffer(*doc_buffer, cmd.argument());
2850 case LFUN_BUFFER_WRITE_ALL: {
2851 Buffer * first = theBufferList().first();
2854 message(_("Saving all documents..."));
2855 // We cannot use a for loop as the buffer list cycles.
2858 if (!b->isClean()) {
2860 LYXERR(Debug::ACTION, "Saved " << b->absFileName());
2862 b = theBufferList().next(b);
2863 } while (b != first);
2864 message(_("All documents saved."));
2868 case LFUN_BUFFER_CLOSE:
2872 case LFUN_BUFFER_CLOSE_ALL:
2876 case LFUN_TOOLBAR_TOGGLE: {
2877 string const name = cmd.getArg(0);
2878 if (GuiToolbar * t = toolbar(name))
2883 case LFUN_DIALOG_UPDATE: {
2884 string const name = to_utf8(cmd.argument());
2885 if (currentBufferView()) {
2886 Inset * inset = currentBufferView()->editedInset(name);
2887 // Can only update a dialog connected to an existing inset
2890 // FIXME: get rid of this indirection; GuiView ask the inset
2891 // if he is kind enough to update itself...
2892 FuncRequest fr(LFUN_INSET_DIALOG_UPDATE, cmd.argument());
2893 inset->dispatch(currentBufferView()->cursor(), fr);
2894 } else if (name == "paragraph") {
2895 lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
2896 } else if (name == "prefs" || name == "document") {
2897 updateDialog(name, string());
2902 case LFUN_DIALOG_TOGGLE: {
2903 if (isDialogVisible(cmd.getArg(0)))
2904 dispatch(FuncRequest(LFUN_DIALOG_HIDE, cmd.argument()));
2906 dispatch(FuncRequest(LFUN_DIALOG_SHOW, cmd.argument()));
2910 case LFUN_DIALOG_DISCONNECT_INSET:
2911 disconnectDialog(to_utf8(cmd.argument()));
2914 case LFUN_DIALOG_HIDE: {
2915 guiApp->hideDialogs(to_utf8(cmd.argument()), 0);
2919 case LFUN_DIALOG_SHOW: {
2920 string const name = cmd.getArg(0);
2921 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
2923 if (name == "character") {
2924 data = freefont2string();
2926 showDialog("character", data);
2927 } else if (name == "latexlog") {
2928 Buffer::LogType type;
2929 string const logfile = doc_buffer->logName(&type);
2931 case Buffer::latexlog:
2934 case Buffer::buildlog:
2938 data += Lexer::quoteString(logfile);
2939 showDialog("log", data);
2940 } else if (name == "vclog") {
2941 string const data = "vc " +
2942 Lexer::quoteString(doc_buffer->lyxvc().getLogFile());
2943 showDialog("log", data);
2944 } else if (name == "symbols") {
2945 data = bv->cursor().getEncoding()->name();
2947 showDialog("symbols", data);
2949 } else if (name == "prefs" && isFullScreen()) {
2950 FuncRequest fr(LFUN_INSET_INSERT, "fullscreen");
2952 showDialog("prefs", data);
2954 showDialog(name, data);
2959 message(cmd.argument());
2962 case LFUN_UI_TOGGLE:
2964 // Make sure the keyboard focus stays in the work area.
2968 case LFUN_SPLIT_VIEW: {
2969 LASSERT(doc_buffer, break);
2970 string const orientation = cmd.getArg(0);
2971 d.splitter_->setOrientation(orientation == "vertical"
2972 ? Qt::Vertical : Qt::Horizontal);
2973 TabWorkArea * twa = addTabWorkArea();
2974 GuiWorkArea * wa = twa->addWorkArea(*doc_buffer, *this);
2975 setCurrentWorkArea(wa);
2978 case LFUN_CLOSE_TAB_GROUP:
2979 if (TabWorkArea * twa = d.currentTabWorkArea()) {
2980 closeTabWorkArea(twa);
2981 d.current_work_area_ = 0;
2982 twa = d.currentTabWorkArea();
2983 // Switch to the next GuiWorkArea in the found TabWorkArea.
2985 // Make sure the work area is up to date.
2986 setCurrentWorkArea(twa->currentWorkArea());
2988 setCurrentWorkArea(0);
2993 case LFUN_COMPLETION_INLINE:
2994 if (d.current_work_area_)
2995 d.current_work_area_->completer().showInline();
2998 case LFUN_COMPLETION_POPUP:
2999 if (d.current_work_area_)
3000 d.current_work_area_->completer().showPopup();
3004 case LFUN_COMPLETION_COMPLETE:
3005 if (d.current_work_area_)
3006 d.current_work_area_->completer().tab();
3009 case LFUN_COMPLETION_CANCEL:
3010 if (d.current_work_area_) {
3011 if (d.current_work_area_->completer().popupVisible())
3012 d.current_work_area_->completer().hidePopup();
3014 d.current_work_area_->completer().hideInline();
3018 case LFUN_COMPLETION_ACCEPT:
3019 if (d.current_work_area_)
3020 d.current_work_area_->completer().activate();
3023 case LFUN_BUFFER_ZOOM_IN:
3024 case LFUN_BUFFER_ZOOM_OUT:
3025 if (cmd.argument().empty()) {
3026 if (cmd.action == LFUN_BUFFER_ZOOM_IN)
3031 lyxrc.zoom += convert<int>(cmd.argument());
3033 if (lyxrc.zoom < 10)
3036 // The global QPixmapCache is used in GuiPainter to cache text
3037 // painting so we must reset it.
3038 QPixmapCache::clear();
3039 guiApp->fontLoader().update();
3040 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
3043 case LFUN_VC_REGISTER:
3044 case LFUN_VC_CHECK_IN:
3045 case LFUN_VC_CHECK_OUT:
3046 case LFUN_VC_REPO_UPDATE:
3047 case LFUN_VC_LOCKING_TOGGLE:
3048 case LFUN_VC_REVERT:
3049 case LFUN_VC_UNDO_LAST:
3050 case LFUN_VC_COMMAND:
3054 case LFUN_SERVER_GOTO_FILE_ROW:
3055 goToFileRow(to_utf8(cmd.argument()));
3063 // Part of automatic menu appearance feature.
3064 if (isFullScreen()) {
3065 if (menuBar()->isVisible() && lyxrc.full_screen_menubar)
3067 if (statusBar()->isVisible())
3068 statusBar()->hide();
3075 void GuiView::lfunUiToggle(FuncRequest const & cmd)
3077 string const arg = cmd.getArg(0);
3078 if (arg == "scrollbar") {
3079 // hide() is of no help
3080 if (d.current_work_area_->verticalScrollBarPolicy() ==
3081 Qt::ScrollBarAlwaysOff)
3083 d.current_work_area_->setVerticalScrollBarPolicy(
3084 Qt::ScrollBarAsNeeded);
3086 d.current_work_area_->setVerticalScrollBarPolicy(
3087 Qt::ScrollBarAlwaysOff);
3090 if (arg == "statusbar") {
3091 statusBar()->setVisible(!statusBar()->isVisible());
3094 if (arg == "menubar") {
3095 menuBar()->setVisible(!menuBar()->isVisible());
3098 #if QT_VERSION >= 0x040300
3099 if (arg == "frame") {
3101 getContentsMargins(&l, &t, &r, &b);
3102 //are the frames in default state?
3103 d.current_work_area_->setFrameStyle(QFrame::NoFrame);
3105 setContentsMargins(-2, -2, -2, -2);
3107 setContentsMargins(0, 0, 0, 0);
3112 if (arg == "fullscreen") {
3117 message(bformat("LFUN_UI_TOGGLE " + _("%1$s unknown command!"), from_utf8(arg)));
3121 void GuiView::toggleFullScreen()
3123 if (isFullScreen()) {
3124 for (int i = 0; i != d.splitter_->count(); ++i)
3125 d.tabWorkArea(i)->setFullScreen(false);
3126 #if QT_VERSION >= 0x040300
3127 setContentsMargins(0, 0, 0, 0);
3129 setWindowState(windowState() ^ Qt::WindowFullScreen);
3132 statusBar()->show();
3135 hideDialogs("prefs", 0);
3136 for (int i = 0; i != d.splitter_->count(); ++i)
3137 d.tabWorkArea(i)->setFullScreen(true);
3138 #if QT_VERSION >= 0x040300
3139 setContentsMargins(-2, -2, -2, -2);
3142 setWindowState(windowState() ^ Qt::WindowFullScreen);
3143 statusBar()->hide();
3144 if (lyxrc.full_screen_menubar)
3146 if (lyxrc.full_screen_toolbars) {
3147 ToolbarMap::iterator end = d.toolbars_.end();
3148 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
3153 // give dialogs like the TOC a chance to adapt
3158 Buffer const * GuiView::updateInset(Inset const * inset)
3160 if (!d.current_work_area_)
3164 d.current_work_area_->scheduleRedraw();
3166 return &d.current_work_area_->bufferView().buffer();
3170 void GuiView::restartCursor()
3172 /* When we move around, or type, it's nice to be able to see
3173 * the cursor immediately after the keypress.
3175 if (d.current_work_area_)
3176 d.current_work_area_->startBlinkingCursor();
3178 // Take this occasion to update the other GUI elements.
3184 void GuiView::updateCompletion(Cursor & cur, bool start, bool keep)
3186 if (d.current_work_area_)
3187 d.current_work_area_->completer().updateVisibility(cur, start, keep);
3192 // This list should be kept in sync with the list of insets in
3193 // src/insets/Inset.cpp. I.e., if a dialog goes with an inset, the
3194 // dialog should have the same name as the inset.
3195 // Changes should be also recorded in LFUN_DIALOG_SHOW doxygen
3196 // docs in LyXAction.cpp.
3198 char const * const dialognames[] = {
3199 "aboutlyx", "bibitem", "bibtex", "box", "branch", "changes", "character",
3200 "citation", "compare", "document", "errorlist", "ert", "external", "file",
3201 "findreplace", "findreplaceadv", "float", "graphics", "href", "include",
3202 "index", "index_print", "info", "listings", "label", "log", "mathdelimiter",
3203 "mathmatrix", "mathspace", "nomenclature", "nomencl_print", "note",
3204 "paragraph", "phantom", "prefs", "print", "ref", "sendto", "space",
3205 "spellchecker", "symbols", "tabular", "tabularcreate", "thesaurus", "texinfo",
3206 "toc", "view-source", "vspace", "wrap", "progress"};
3208 char const * const * const end_dialognames =
3209 dialognames + (sizeof(dialognames) / sizeof(char *));
3213 cmpCStr(char const * name) : name_(name) {}
3214 bool operator()(char const * other) {
3215 return strcmp(other, name_) == 0;
3222 bool isValidName(string const & name)
3224 return find_if(dialognames, end_dialognames,
3225 cmpCStr(name.c_str())) != end_dialognames;
3231 void GuiView::resetDialogs()
3233 // Make sure that no LFUN uses any LyXView.
3234 guiApp->setCurrentView(0);
3237 constructToolbars();
3238 guiApp->menus().fillMenuBar(menuBar(), this, false);
3239 d.layout_->updateContents(true);
3240 // Now update controls with current buffer.
3241 guiApp->setCurrentView(this);
3247 Dialog * GuiView::findOrBuild(string const & name, bool hide_it)
3249 if (!isValidName(name))
3252 map<string, DialogPtr>::iterator it = d.dialogs_.find(name);
3254 if (it != d.dialogs_.end()) {
3256 it->second->hideView();
3257 return it->second.get();
3260 Dialog * dialog = build(name);
3261 d.dialogs_[name].reset(dialog);
3262 if (lyxrc.allow_geometry_session)
3263 dialog->restoreSession();
3270 void GuiView::showDialog(string const & name, string const & data,
3273 triggerShowDialog(toqstr(name), toqstr(data), inset);
3277 void GuiView::doShowDialog(QString const & qname, QString const & qdata,
3283 const string name = fromqstr(qname);
3284 const string data = fromqstr(qdata);
3288 Dialog * dialog = findOrBuild(name, false);
3290 dialog->showData(data);
3291 if (inset && currentBufferView())
3292 currentBufferView()->editInset(name, inset);
3295 catch (ExceptionMessage const & ex) {
3303 bool GuiView::isDialogVisible(string const & name) const
3305 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3306 if (it == d.dialogs_.end())
3308 return it->second.get()->isVisibleView() && !it->second.get()->isClosing();
3312 void GuiView::hideDialog(string const & name, Inset * inset)
3314 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3315 if (it == d.dialogs_.end())
3318 if (inset && currentBufferView()
3319 && inset != currentBufferView()->editedInset(name))
3322 Dialog * const dialog = it->second.get();
3323 if (dialog->isVisibleView())
3325 if (currentBufferView())
3326 currentBufferView()->editInset(name, 0);
3330 void GuiView::disconnectDialog(string const & name)
3332 if (!isValidName(name))
3334 if (currentBufferView())
3335 currentBufferView()->editInset(name, 0);
3339 void GuiView::hideAll() const
3341 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
3342 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3344 for(; it != end; ++it)
3345 it->second->hideView();
3349 void GuiView::updateDialogs()
3351 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
3352 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3354 for(; it != end; ++it) {
3355 Dialog * dialog = it->second.get();
3356 if (dialog && dialog->isVisibleView())
3357 dialog->checkStatus();
3364 // will be replaced by a proper factory...
3365 Dialog * createGuiAbout(GuiView & lv);
3366 Dialog * createGuiBibitem(GuiView & lv);
3367 Dialog * createGuiBibtex(GuiView & lv);
3368 Dialog * createGuiBox(GuiView & lv);
3369 Dialog * createGuiBranch(GuiView & lv);
3370 Dialog * createGuiChanges(GuiView & lv);
3371 Dialog * createGuiCharacter(GuiView & lv);
3372 Dialog * createGuiCitation(GuiView & lv);
3373 Dialog * createGuiCompare(GuiView & lv);
3374 Dialog * createGuiDelimiter(GuiView & lv);
3375 Dialog * createGuiDocument(GuiView & lv);
3376 Dialog * createGuiErrorList(GuiView & lv);
3377 Dialog * createGuiERT(GuiView & lv);
3378 Dialog * createGuiExternal(GuiView & lv);
3379 Dialog * createGuiFloat(GuiView & lv);
3380 Dialog * createGuiGraphics(GuiView & lv);
3381 Dialog * createGuiInclude(GuiView & lv);
3382 Dialog * createGuiIndex(GuiView & lv);
3383 Dialog * createGuiInfo(GuiView & lv);
3384 Dialog * createGuiLabel(GuiView & lv);
3385 Dialog * createGuiListings(GuiView & lv);
3386 Dialog * createGuiLog(GuiView & lv);
3387 Dialog * createGuiMathHSpace(GuiView & lv);
3388 Dialog * createGuiMathMatrix(GuiView & lv);
3389 Dialog * createGuiNomenclature(GuiView & lv);
3390 Dialog * createGuiNote(GuiView & lv);
3391 Dialog * createGuiParagraph(GuiView & lv);
3392 Dialog * createGuiPhantom(GuiView & lv);
3393 Dialog * createGuiPreferences(GuiView & lv);
3394 Dialog * createGuiPrint(GuiView & lv);
3395 Dialog * createGuiPrintindex(GuiView & lv);
3396 Dialog * createGuiPrintNomencl(GuiView & lv);
3397 Dialog * createGuiRef(GuiView & lv);
3398 Dialog * createGuiSearch(GuiView & lv);
3399 Dialog * createGuiSearchAdv(GuiView & lv);
3400 Dialog * createGuiSendTo(GuiView & lv);
3401 Dialog * createGuiShowFile(GuiView & lv);
3402 Dialog * createGuiSpellchecker(GuiView & lv);
3403 Dialog * createGuiSymbols(GuiView & lv);
3404 Dialog * createGuiTabularCreate(GuiView & lv);
3405 Dialog * createGuiTabular(GuiView & lv);
3406 Dialog * createGuiTexInfo(GuiView & lv);
3407 Dialog * createGuiTextHSpace(GuiView & lv);
3408 Dialog * createGuiToc(GuiView & lv);
3409 Dialog * createGuiThesaurus(GuiView & lv);
3410 Dialog * createGuiHyperlink(GuiView & lv);
3411 Dialog * createGuiVSpace(GuiView & lv);
3412 Dialog * createGuiViewSource(GuiView & lv);
3413 Dialog * createGuiWrap(GuiView & lv);
3414 Dialog * createGuiProgressView(GuiView & lv);
3418 Dialog * GuiView::build(string const & name)
3420 LASSERT(isValidName(name), return 0);
3422 if (name == "aboutlyx")
3423 return createGuiAbout(*this);
3424 if (name == "bibitem")
3425 return createGuiBibitem(*this);
3426 if (name == "bibtex")
3427 return createGuiBibtex(*this);
3429 return createGuiBox(*this);
3430 if (name == "branch")
3431 return createGuiBranch(*this);
3432 if (name == "changes")
3433 return createGuiChanges(*this);
3434 if (name == "character")
3435 return createGuiCharacter(*this);
3436 if (name == "citation")
3437 return createGuiCitation(*this);
3438 if (name == "compare")
3439 return createGuiCompare(*this);
3440 if (name == "document")
3441 return createGuiDocument(*this);
3442 if (name == "errorlist")
3443 return createGuiErrorList(*this);
3445 return createGuiERT(*this);
3446 if (name == "external")
3447 return createGuiExternal(*this);
3449 return createGuiShowFile(*this);
3450 if (name == "findreplace")
3451 return createGuiSearch(*this);
3452 if (name == "findreplaceadv")
3453 return createGuiSearchAdv(*this);
3454 if (name == "float")
3455 return createGuiFloat(*this);
3456 if (name == "graphics")
3457 return createGuiGraphics(*this);
3459 return createGuiHyperlink(*this);
3460 if (name == "include")
3461 return createGuiInclude(*this);
3462 if (name == "index")
3463 return createGuiIndex(*this);
3464 if (name == "index_print")
3465 return createGuiPrintindex(*this);
3467 return createGuiInfo(*this);
3468 if (name == "label")
3469 return createGuiLabel(*this);
3470 if (name == "listings")
3471 return createGuiListings(*this);
3473 return createGuiLog(*this);
3474 if (name == "mathdelimiter")
3475 return createGuiDelimiter(*this);
3476 if (name == "mathspace")
3477 return createGuiMathHSpace(*this);
3478 if (name == "mathmatrix")
3479 return createGuiMathMatrix(*this);
3480 if (name == "nomenclature")
3481 return createGuiNomenclature(*this);
3482 if (name == "nomencl_print")
3483 return createGuiPrintNomencl(*this);
3485 return createGuiNote(*this);
3486 if (name == "paragraph")
3487 return createGuiParagraph(*this);
3488 if (name == "phantom")
3489 return createGuiPhantom(*this);
3490 if (name == "prefs")
3491 return createGuiPreferences(*this);
3492 if (name == "print")
3493 return createGuiPrint(*this);
3495 return createGuiRef(*this);
3496 if (name == "sendto")
3497 return createGuiSendTo(*this);
3498 if (name == "space")
3499 return createGuiTextHSpace(*this);
3500 if (name == "spellchecker")
3501 return createGuiSpellchecker(*this);
3502 if (name == "symbols")
3503 return createGuiSymbols(*this);
3504 if (name == "tabular")
3505 return createGuiTabular(*this);
3506 if (name == "tabularcreate")
3507 return createGuiTabularCreate(*this);
3508 if (name == "texinfo")
3509 return createGuiTexInfo(*this);
3510 if (name == "thesaurus")
3511 return createGuiThesaurus(*this);
3513 return createGuiToc(*this);
3514 if (name == "view-source")
3515 return createGuiViewSource(*this);
3516 if (name == "vspace")
3517 return createGuiVSpace(*this);
3519 return createGuiWrap(*this);
3520 if (name == "progress")
3521 return createGuiProgressView(*this);
3527 } // namespace frontend
3530 #include "moc_GuiView.cpp"