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);
157 setFocusPolicy(Qt::StrongFocus);
160 void paintEvent(QPaintEvent *)
162 int x = (width() - splash_.width()) / 2;
163 int y = (height() - splash_.height()) / 2;
165 pain.drawPixmap(x, y, splash_);
168 void keyPressEvent(QKeyEvent * ev)
171 setKeySymbol(&sym, ev);
173 guiApp->processKeySym(sym, q_key_state(ev->modifiers()));
185 /// Toolbar store providing access to individual toolbars by name.
186 typedef map<string, GuiToolbar *> ToolbarMap;
188 typedef boost::shared_ptr<Dialog> DialogPtr;
193 struct GuiView::GuiViewPrivate
195 GuiViewPrivate(GuiView * gv)
196 : gv_(gv), current_work_area_(0), current_main_work_area_(0),
197 layout_(0), autosave_timeout_(5000),
200 // hardcode here the platform specific icon size
201 smallIconSize = 14; // scaling problems
202 normalIconSize = 20; // ok, default
203 bigIconSize = 26; // better for some math icons
205 splitter_ = new QSplitter;
206 bg_widget_ = new BackgroundWidget;
207 stack_widget_ = new QStackedWidget;
208 stack_widget_->addWidget(bg_widget_);
209 stack_widget_->addWidget(splitter_);
211 progress_ = new GuiProgress(gv);
218 delete stack_widget_;
222 QMenu * toolBarPopup(GuiView * parent)
224 // FIXME: translation
225 QMenu * menu = new QMenu(parent);
226 QActionGroup * iconSizeGroup = new QActionGroup(parent);
228 QAction * smallIcons = new QAction(iconSizeGroup);
229 smallIcons->setText(qt_("Small-sized icons"));
230 smallIcons->setCheckable(true);
231 QObject::connect(smallIcons, SIGNAL(triggered()),
232 parent, SLOT(smallSizedIcons()));
233 menu->addAction(smallIcons);
235 QAction * normalIcons = new QAction(iconSizeGroup);
236 normalIcons->setText(qt_("Normal-sized icons"));
237 normalIcons->setCheckable(true);
238 QObject::connect(normalIcons, SIGNAL(triggered()),
239 parent, SLOT(normalSizedIcons()));
240 menu->addAction(normalIcons);
242 QAction * bigIcons = new QAction(iconSizeGroup);
243 bigIcons->setText(qt_("Big-sized icons"));
244 bigIcons->setCheckable(true);
245 QObject::connect(bigIcons, SIGNAL(triggered()),
246 parent, SLOT(bigSizedIcons()));
247 menu->addAction(bigIcons);
249 unsigned int cur = parent->iconSize().width();
250 if ( cur == parent->d.smallIconSize)
251 smallIcons->setChecked(true);
252 else if (cur == parent->d.normalIconSize)
253 normalIcons->setChecked(true);
254 else if (cur == parent->d.bigIconSize)
255 bigIcons->setChecked(true);
262 stack_widget_->setCurrentWidget(bg_widget_);
263 bg_widget_->setUpdatesEnabled(true);
264 bg_widget_->setFocus();
267 TabWorkArea * tabWorkArea(int i)
269 return dynamic_cast<TabWorkArea *>(splitter_->widget(i));
272 TabWorkArea * currentTabWorkArea()
274 if (splitter_->count() == 1)
275 // The first TabWorkArea is always the first one, if any.
276 return tabWorkArea(0);
278 for (int i = 0; i != splitter_->count(); ++i) {
279 TabWorkArea * twa = tabWorkArea(i);
280 if (current_main_work_area_ == twa->currentWorkArea())
284 // None has the focus so we just take the first one.
285 return tabWorkArea(0);
288 #if (QT_VERSION >= 0x040400)
289 void setPreviewFuture(QFuture<docstring> const & f)
291 if (preview_watcher_.isRunning()) {
292 // we prefer to cancel this preview in order to keep a snappy
296 preview_watcher_.setFuture(f);
302 GuiWorkArea * current_work_area_;
303 GuiWorkArea * current_main_work_area_;
304 QSplitter * splitter_;
305 QStackedWidget * stack_widget_;
306 BackgroundWidget * bg_widget_;
308 ToolbarMap toolbars_;
309 ProgressInterface* progress_;
310 /// The main layout box.
312 * \warning Don't Delete! The layout box is actually owned by
313 * whichever toolbar contains it. All the GuiView class needs is a
314 * means of accessing it.
316 * FIXME: replace that with a proper model so that we are not limited
317 * to only one dialog.
322 map<string, DialogPtr> dialogs_;
324 unsigned int smallIconSize;
325 unsigned int normalIconSize;
326 unsigned int bigIconSize;
328 QTimer statusbar_timer_;
329 /// auto-saving of buffers
330 Timeout autosave_timeout_;
331 /// flag against a race condition due to multiclicks, see bug #1119
335 TocModels toc_models_;
337 #if (QT_VERSION >= 0x040400)
339 QFutureWatcher<docstring> autosave_watcher_;
340 QFutureWatcher<docstring> preview_watcher_;
342 struct DummyWatcher { bool isRunning(){return false;} };
343 DummyWatcher preview_watcher_;
348 GuiView::GuiView(int id)
349 : d(*new GuiViewPrivate(this)), id_(id), closing_(false)
351 // GuiToolbars *must* be initialised before the menu bar.
352 normalSizedIcons(); // at least on Mac the default is 32 otherwise, which is huge
355 // set ourself as the current view. This is needed for the menu bar
356 // filling, at least for the static special menu item on Mac. Otherwise
357 // they are greyed out.
358 guiApp->setCurrentView(this);
360 // Fill up the menu bar.
361 guiApp->menus().fillMenuBar(menuBar(), this, true);
363 setCentralWidget(d.stack_widget_);
365 // Start autosave timer
366 if (lyxrc.autosave) {
367 d.autosave_timeout_.timeout.connect(boost::bind(&GuiView::autoSave, this));
368 d.autosave_timeout_.setTimeout(lyxrc.autosave * 1000);
369 d.autosave_timeout_.start();
371 connect(&d.statusbar_timer_, SIGNAL(timeout()),
372 this, SLOT(clearMessage()));
374 // We don't want to keep the window in memory if it is closed.
375 setAttribute(Qt::WA_DeleteOnClose, true);
377 #if (!defined(Q_WS_WIN) && !defined(Q_WS_MACX))
378 // assign an icon to main form. We do not do it under Qt/Win or Qt/Mac,
379 // since the icon is provided in the application bundle.
380 setWindowIcon(getPixmap("images/", "lyx", "png"));
384 setAcceptDrops(true);
386 statusBar()->setSizeGripEnabled(true);
389 #if (QT_VERSION >= 0x040400)
390 connect(&d.autosave_watcher_, SIGNAL(finished()), this,
391 SLOT(threadFinished()));
392 connect(&d.preview_watcher_, SIGNAL(finished()), this,
393 SLOT(threadFinished()));
396 connect(this, SIGNAL(triggerShowDialog(QString const &, QString const &, Inset *)),
397 SLOT(doShowDialog(QString const &, QString const &, Inset *)));
399 // Forbid too small unresizable window because it can happen
400 // with some window manager under X11.
401 setMinimumSize(300, 200);
403 if (lyxrc.allow_geometry_session) {
404 // Now take care of session management.
409 // no session handling, default to a sane size.
410 setGeometry(50, 50, 690, 510);
413 // clear session data if any.
415 settings.remove("views");
425 void GuiView::threadFinished()
427 #if (QT_VERSION >= 0x040400)
428 QFutureWatcher<docstring> const * watcher =
429 static_cast<QFutureWatcher<docstring> const *>(sender());
430 message(watcher->result());
435 void GuiView::saveLayout() const
438 settings.beginGroup("views");
439 settings.beginGroup(QString::number(id_));
441 settings.setValue("pos", pos());
442 settings.setValue("size", size());
444 settings.setValue("geometry", saveGeometry());
446 settings.setValue("layout", saveState(0));
447 settings.setValue("icon_size", iconSize());
451 bool GuiView::restoreLayout()
454 settings.beginGroup("views");
455 settings.beginGroup(QString::number(id_));
456 QString const icon_key = "icon_size";
457 if (!settings.contains(icon_key))
460 //code below is skipped when when ~/.config/LyX is (re)created
461 setIconSize(settings.value(icon_key).toSize());
463 QPoint pos = settings.value("pos", QPoint(50, 50)).toPoint();
464 QSize size = settings.value("size", QSize(690, 510)).toSize();
468 // Work-around for bug #6034: the window ends up in an undetermined
469 // state when trying to restore a maximized window when it is
470 // already maximized.
471 if (!(windowState() & Qt::WindowMaximized))
472 if (!restoreGeometry(settings.value("geometry").toByteArray()))
473 setGeometry(50, 50, 690, 510);
475 // Make sure layout is correctly oriented.
476 setLayoutDirection(qApp->layoutDirection());
478 // Allow the toc and view-source dock widget to be restored if needed.
480 if ((dialog = findOrBuild("toc", true)))
481 // see bug 5082. At least setup title and enabled state.
482 // Visibility will be adjusted by restoreState below.
483 dialog->prepareView();
484 if ((dialog = findOrBuild("view-source", true)))
485 dialog->prepareView();
486 if ((dialog = findOrBuild("progress", true)))
487 dialog->prepareView();
489 if (!restoreState(settings.value("layout").toByteArray(), 0))
496 GuiToolbar * GuiView::toolbar(string const & name)
498 ToolbarMap::iterator it = d.toolbars_.find(name);
499 if (it != d.toolbars_.end())
502 LYXERR(Debug::GUI, "Toolbar::display: no toolbar named " << name);
503 message(bformat(_("Unknown toolbar \"%1$s\""), from_utf8(name)));
508 void GuiView::constructToolbars()
510 ToolbarMap::iterator it = d.toolbars_.begin();
511 for (; it != d.toolbars_.end(); ++it)
515 // I don't like doing this here, but the standard toolbar
516 // destroys this object when it's destroyed itself (vfr)
517 d.layout_ = new LayoutBox(*this);
518 d.stack_widget_->addWidget(d.layout_);
519 d.layout_->move(0,0);
521 // extracts the toolbars from the backend
522 Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
523 Toolbars::Infos::iterator end = guiApp->toolbars().end();
524 for (; cit != end; ++cit)
525 d.toolbars_[cit->name] = new GuiToolbar(*cit, *this);
529 void GuiView::initToolbars()
531 // extracts the toolbars from the backend
532 Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
533 Toolbars::Infos::iterator end = guiApp->toolbars().end();
534 for (; cit != end; ++cit) {
535 GuiToolbar * tb = toolbar(cit->name);
538 int const visibility = guiApp->toolbars().defaultVisibility(cit->name);
540 tb->setVisible(false);
541 tb->setVisibility(visibility);
543 if (visibility & Toolbars::TOP) {
545 addToolBarBreak(Qt::TopToolBarArea);
546 addToolBar(Qt::TopToolBarArea, tb);
549 if (visibility & Toolbars::BOTTOM) {
550 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
551 #if (QT_VERSION >= 0x040202)
552 addToolBarBreak(Qt::BottomToolBarArea);
554 addToolBar(Qt::BottomToolBarArea, tb);
557 if (visibility & Toolbars::LEFT) {
558 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
559 #if (QT_VERSION >= 0x040202)
560 addToolBarBreak(Qt::LeftToolBarArea);
562 addToolBar(Qt::LeftToolBarArea, tb);
565 if (visibility & Toolbars::RIGHT) {
566 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
567 #if (QT_VERSION >= 0x040202)
568 addToolBarBreak(Qt::RightToolBarArea);
570 addToolBar(Qt::RightToolBarArea, tb);
573 if (visibility & Toolbars::ON)
574 tb->setVisible(true);
579 TocModels & GuiView::tocModels()
581 return d.toc_models_;
585 void GuiView::setFocus()
587 LYXERR(Debug::DEBUG, "GuiView::setFocus()" << this);
588 // Make sure LyXFunc points to the correct view.
589 guiApp->setCurrentView(this);
590 QMainWindow::setFocus();
591 if (d.current_work_area_)
592 d.current_work_area_->setFocus();
594 d.bg_widget_->setFocus();
598 QMenu * GuiView::createPopupMenu()
600 return d.toolBarPopup(this);
604 void GuiView::showEvent(QShowEvent * e)
606 LYXERR(Debug::GUI, "Passed Geometry "
607 << size().height() << "x" << size().width()
608 << "+" << pos().x() << "+" << pos().y());
610 if (d.splitter_->count() == 0)
611 // No work area, switch to the background widget.
614 QMainWindow::showEvent(e);
618 /** Destroy only all tabbed WorkAreas. Destruction of other WorkAreas
619 ** is responsibility of the container (e.g., dialog)
621 void GuiView::closeEvent(QCloseEvent * close_event)
623 LYXERR(Debug::DEBUG, "GuiView::closeEvent()");
628 // it can happen that this event arrives without selecting the view,
629 // e.g. when clicking the close button on a background window.
631 if (!closeWorkAreaAll()) {
633 close_event->ignore();
637 // Make sure that nothing will use this to be closed View.
638 guiApp->unregisterView(this);
640 if (isFullScreen()) {
641 // Switch off fullscreen before closing.
646 // Make sure the timer time out will not trigger a statusbar update.
647 d.statusbar_timer_.stop();
649 // Saving fullscreen requires additional tweaks in the toolbar code.
650 // It wouldn't also work under linux natively.
651 if (lyxrc.allow_geometry_session) {
652 // Save this window geometry and layout.
654 // Then the toolbar private states.
655 ToolbarMap::iterator end = d.toolbars_.end();
656 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
657 it->second->saveSession();
658 // Now take care of all other dialogs:
659 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
660 for (; it!= d.dialogs_.end(); ++it)
661 it->second->saveSession();
664 close_event->accept();
668 void GuiView::dragEnterEvent(QDragEnterEvent * event)
670 if (event->mimeData()->hasUrls())
672 /// \todo Ask lyx-devel is this is enough:
673 /// if (event->mimeData()->hasFormat("text/plain"))
674 /// event->acceptProposedAction();
678 void GuiView::dropEvent(QDropEvent * event)
680 QList<QUrl> files = event->mimeData()->urls();
684 LYXERR(Debug::GUI, "GuiView::dropEvent: got URLs!");
685 for (int i = 0; i != files.size(); ++i) {
686 string const file = os::internal_path(fromqstr(
687 files.at(i).toLocalFile()));
691 string const ext = support::getExtension(file);
692 vector<const Format *> found_formats;
694 // Find all formats that have the correct extension.
695 vector<const Format *> const & import_formats
696 = theConverters().importableFormats();
697 vector<const Format *>::const_iterator it = import_formats.begin();
698 for (; it != import_formats.end(); ++it)
699 if ((*it)->extension() == ext)
700 found_formats.push_back(*it);
703 if (found_formats.size() >= 1) {
704 if (found_formats.size() > 1) {
705 //FIXME: show a dialog to choose the correct importable format
707 "Multiple importable formats found, selecting first");
709 string const arg = found_formats[0]->name() + " " + file;
710 cmd = FuncRequest(LFUN_BUFFER_IMPORT, arg);
713 //FIXME: do we have to explicitly check whether it's a lyx file?
715 "No formats found, trying to open it as a lyx file");
716 cmd = FuncRequest(LFUN_FILE_OPEN, file);
719 // Asynchronously post the event. DropEvent usually comes
720 // from the BufferView. But reloading a file might close
721 // the BufferView from within its own event handler.
722 guiApp->dispatchDelayed(cmd);
728 void GuiView::message(docstring const & str)
730 if (ForkedProcess::iAmAChild())
733 // call is moved to GUI-thread by GuiProgress
734 d.progress_->appendMessage(toqstr(str));
738 void GuiView::updateMessage(QString const & str)
740 statusBar()->showMessage(str);
741 d.statusbar_timer_.stop();
742 d.statusbar_timer_.start(3000);
746 void GuiView::smallSizedIcons()
748 setIconSize(QSize(d.smallIconSize, d.smallIconSize));
752 void GuiView::normalSizedIcons()
754 setIconSize(QSize(d.normalIconSize, d.normalIconSize));
758 void GuiView::bigSizedIcons()
760 setIconSize(QSize(d.bigIconSize, d.bigIconSize));
764 void GuiView::clearMessage()
766 // FIXME: This code was introduced in r19643 to fix bug #4123. However,
767 // the hasFocus function mostly returns false, even if the focus is on
768 // a workarea in this view.
772 d.statusbar_timer_.stop();
776 void GuiView::updateWindowTitle(GuiWorkArea * wa)
778 if (wa != d.current_work_area_
779 || wa->bufferView().buffer().isInternal())
781 setWindowTitle(qt_("LyX: ") + wa->windowTitle());
782 setWindowIconText(wa->windowIconText());
786 void GuiView::on_currentWorkAreaChanged(GuiWorkArea * wa)
789 disconnectBufferView();
790 connectBufferView(wa->bufferView());
791 connectBuffer(wa->bufferView().buffer());
792 d.current_work_area_ = wa;
793 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
794 this, SLOT(updateWindowTitle(GuiWorkArea *)));
795 updateWindowTitle(wa);
799 // The document settings needs to be reinitialised.
800 updateDialog("document", "");
802 // Buffer-dependent dialogs must be updated. This is done here because
803 // some dialogs require buffer()->text.
808 void GuiView::on_lastWorkAreaRemoved()
811 // We already are in a close event. Nothing more to do.
814 if (d.splitter_->count() > 1)
815 // We have a splitter so don't close anything.
818 // Reset and updates the dialogs.
819 d.toc_models_.reset(0);
820 updateDialog("document", "");
823 resetWindowTitleAndIconText();
826 if (lyxrc.open_buffers_in_tabs)
827 // Nothing more to do, the window should stay open.
830 if (guiApp->viewIds().size() > 1) {
836 // On Mac we also close the last window because the application stay
837 // resident in memory. On other platforms we don't close the last
838 // window because this would quit the application.
844 void GuiView::updateStatusBar()
846 // let the user see the explicit message
847 if (d.statusbar_timer_.isActive())
854 void GuiView::showMessage()
856 QString msg = toqstr(theGuiApp()->viewStatusMessage());
858 BufferView const * bv = currentBufferView();
860 msg = toqstr(bv->cursor().currentState());
862 msg = qt_("Welcome to LyX!");
864 statusBar()->showMessage(msg);
868 bool GuiView::event(QEvent * e)
872 // Useful debug code:
873 //case QEvent::ActivationChange:
874 //case QEvent::WindowDeactivate:
875 //case QEvent::Paint:
876 //case QEvent::Enter:
877 //case QEvent::Leave:
878 //case QEvent::HoverEnter:
879 //case QEvent::HoverLeave:
880 //case QEvent::HoverMove:
881 //case QEvent::StatusTip:
882 //case QEvent::DragEnter:
883 //case QEvent::DragLeave:
887 case QEvent::WindowActivate: {
888 GuiView * old_view = guiApp->currentView();
889 if (this == old_view) {
891 return QMainWindow::event(e);
893 if (old_view && old_view->currentBufferView()) {
894 // save current selection to the selection buffer to allow
895 // middle-button paste in this window.
896 cap::saveSelection(old_view->currentBufferView()->cursor());
898 guiApp->setCurrentView(this);
899 if (d.current_work_area_) {
900 BufferView & bv = d.current_work_area_->bufferView();
901 connectBufferView(bv);
902 connectBuffer(bv.buffer());
903 // The document structure, name and dialogs might have
904 // changed in another view.
906 // The document settings needs to be reinitialised.
907 updateDialog("document", "");
910 resetWindowTitleAndIconText();
913 return QMainWindow::event(e);
916 case QEvent::ShortcutOverride: {
919 #if (!defined Q_WS_X11) || (QT_VERSION >= 0x040500)
920 if (isFullScreen() && menuBar()->isHidden()) {
921 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
922 // FIXME: we should also try to detect special LyX shortcut such as
923 // Alt-P and Alt-M. Right now there is a hack in
924 // GuiWorkArea::processKeySym() that hides again the menubar for
926 if (ke->modifiers() & Qt::AltModifier && ke->key() != Qt::Key_Alt) {
928 return QMainWindow::event(e);
932 return QMainWindow::event(e);
936 return QMainWindow::event(e);
940 void GuiView::resetWindowTitleAndIconText()
942 setWindowTitle(qt_("LyX"));
943 setWindowIconText(qt_("LyX"));
946 bool GuiView::focusNextPrevChild(bool /*next*/)
953 void GuiView::setBusy(bool busy)
955 if (d.current_work_area_) {
956 d.current_work_area_->setUpdatesEnabled(!busy);
958 d.current_work_area_->stopBlinkingCursor();
960 d.current_work_area_->startBlinkingCursor();
964 QApplication::setOverrideCursor(Qt::WaitCursor);
966 QApplication::restoreOverrideCursor();
970 GuiWorkArea * GuiView::workArea(Buffer & buffer)
972 if (currentWorkArea()
973 && ¤tWorkArea()->bufferView().buffer() == &buffer)
974 return (GuiWorkArea *) currentWorkArea();
975 if (TabWorkArea * twa = d.currentTabWorkArea())
976 return twa->workArea(buffer);
981 GuiWorkArea * GuiView::addWorkArea(Buffer & buffer)
983 // Automatically create a TabWorkArea if there are none yet.
984 TabWorkArea * tab_widget = d.splitter_->count()
985 ? d.currentTabWorkArea() : addTabWorkArea();
986 return tab_widget->addWorkArea(buffer, *this);
990 TabWorkArea * GuiView::addTabWorkArea()
992 TabWorkArea * twa = new TabWorkArea;
993 QObject::connect(twa, SIGNAL(currentWorkAreaChanged(GuiWorkArea *)),
994 this, SLOT(on_currentWorkAreaChanged(GuiWorkArea *)));
995 QObject::connect(twa, SIGNAL(lastWorkAreaRemoved()),
996 this, SLOT(on_lastWorkAreaRemoved()));
998 d.splitter_->addWidget(twa);
999 d.stack_widget_->setCurrentWidget(d.splitter_);
1004 GuiWorkArea const * GuiView::currentWorkArea() const
1006 return d.current_work_area_;
1010 GuiWorkArea * GuiView::currentWorkArea()
1012 return d.current_work_area_;
1016 GuiWorkArea const * GuiView::currentMainWorkArea() const
1018 if (d.currentTabWorkArea() == NULL)
1020 return d.currentTabWorkArea()->currentWorkArea();
1024 GuiWorkArea * GuiView::currentMainWorkArea()
1026 if (d.currentTabWorkArea() == NULL)
1028 return d.currentTabWorkArea()->currentWorkArea();
1032 void GuiView::setCurrentWorkArea(GuiWorkArea * wa)
1034 LYXERR(Debug::DEBUG, "Setting current wa: " << wa << endl);
1036 d.current_work_area_ = NULL;
1040 GuiWorkArea * old_gwa = theGuiApp()->currentView()->currentWorkArea();
1044 if (currentBufferView())
1045 cap::saveSelection(currentBufferView()->cursor());
1047 theGuiApp()->setCurrentView(this);
1048 d.current_work_area_ = wa;
1049 for (int i = 0; i != d.splitter_->count(); ++i) {
1050 if (d.tabWorkArea(i)->setCurrentWorkArea(wa)) {
1051 //if (d.current_main_work_area_)
1052 // d.current_main_work_area_->setFrameStyle(QFrame::NoFrame);
1053 d.current_main_work_area_ = wa;
1054 //d.current_main_work_area_->setFrameStyle(QFrame::Box | QFrame::Plain);
1055 //d.current_main_work_area_->setLineWidth(2);
1056 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() << ", Current main wa: " << currentMainWorkArea());
1060 LYXERR(Debug::DEBUG, "This is not a tabbed wa");
1061 on_currentWorkAreaChanged(wa);
1062 BufferView & bv = wa->bufferView();
1063 bv.cursor().fixIfBroken();
1065 wa->setUpdatesEnabled(true);
1066 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() << ", Current main wa: " << currentMainWorkArea());
1070 void GuiView::removeWorkArea(GuiWorkArea * wa)
1072 LASSERT(wa, return);
1073 if (wa == d.current_work_area_) {
1075 disconnectBufferView();
1076 d.current_work_area_ = 0;
1077 d.current_main_work_area_ = 0;
1080 bool found_twa = false;
1081 for (int i = 0; i != d.splitter_->count(); ++i) {
1082 TabWorkArea * twa = d.tabWorkArea(i);
1083 if (twa->removeWorkArea(wa)) {
1084 // Found in this tab group, and deleted the GuiWorkArea.
1086 if (twa->count() != 0) {
1087 if (d.current_work_area_ == 0)
1088 // This means that we are closing the current GuiWorkArea, so
1089 // switch to the next GuiWorkArea in the found TabWorkArea.
1090 setCurrentWorkArea(twa->currentWorkArea());
1092 // No more WorkAreas in this tab group, so delete it.
1099 // It is not a tabbed work area (i.e., the search work area), so it
1100 // should be deleted by other means.
1101 LASSERT(found_twa, /* */);
1103 if (d.current_work_area_ == 0) {
1104 if (d.splitter_->count() != 0) {
1105 TabWorkArea * twa = d.currentTabWorkArea();
1106 setCurrentWorkArea(twa->currentWorkArea());
1108 // No more work areas, switch to the background widget.
1109 setCurrentWorkArea(0);
1115 LayoutBox * GuiView::getLayoutDialog() const
1121 void GuiView::updateLayoutList()
1124 d.layout_->updateContents(false);
1128 void GuiView::updateToolbars()
1130 ToolbarMap::iterator end = d.toolbars_.end();
1131 if (d.current_work_area_) {
1133 d.current_work_area_->bufferView().cursor().inMathed();
1135 lyx::getStatus(FuncRequest(LFUN_LAYOUT_TABULAR)).enabled();
1137 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).enabled() &&
1138 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).onoff(true);
1139 bool const mathmacrotemplate =
1140 lyx::getStatus(FuncRequest(LFUN_IN_MATHMACROTEMPLATE)).enabled();
1142 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1143 it->second->update(math, table, review, mathmacrotemplate);
1145 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1146 it->second->update(false, false, false, false);
1150 void GuiView::setBuffer(Buffer * newBuffer)
1152 LYXERR(Debug::DEBUG, "Setting buffer: " << newBuffer << endl);
1153 LASSERT(newBuffer, return);
1156 GuiWorkArea * wa = workArea(*newBuffer);
1158 newBuffer->masterBuffer()->updateLabels();
1159 wa = addWorkArea(*newBuffer);
1161 //Disconnect the old buffer...there's no new one.
1164 connectBuffer(*newBuffer);
1165 connectBufferView(wa->bufferView());
1166 setCurrentWorkArea(wa);
1172 void GuiView::connectBuffer(Buffer & buf)
1174 buf.setGuiDelegate(this);
1178 void GuiView::disconnectBuffer()
1180 if (d.current_work_area_)
1181 d.current_work_area_->bufferView().buffer().setGuiDelegate(0);
1185 void GuiView::connectBufferView(BufferView & bv)
1187 bv.setGuiDelegate(this);
1191 void GuiView::disconnectBufferView()
1193 if (d.current_work_area_)
1194 d.current_work_area_->bufferView().setGuiDelegate(0);
1198 void GuiView::errors(string const & error_type, bool from_master)
1200 ErrorList & el = from_master ?
1201 documentBufferView()->buffer().masterBuffer()->errorList(error_type)
1202 : documentBufferView()->buffer().errorList(error_type);
1203 string data = error_type;
1205 data = "from_master|" + error_type;
1207 showDialog("errorlist", data);
1211 void GuiView::updateTocItem(string const & type, DocIterator const & dit)
1213 d.toc_models_.updateItem(toqstr(type), dit);
1217 void GuiView::structureChanged()
1219 d.toc_models_.reset(documentBufferView());
1220 // Navigator needs more than a simple update in this case. It needs to be
1222 updateDialog("toc", "");
1226 void GuiView::updateDialog(string const & name, string const & data)
1228 if (!isDialogVisible(name))
1231 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
1232 if (it == d.dialogs_.end())
1235 Dialog * const dialog = it->second.get();
1236 if (dialog->isVisibleView())
1237 dialog->initialiseParams(data);
1241 BufferView * GuiView::documentBufferView()
1243 return currentMainWorkArea()
1244 ? ¤tMainWorkArea()->bufferView()
1249 BufferView const * GuiView::documentBufferView() const
1251 return currentMainWorkArea()
1252 ? ¤tMainWorkArea()->bufferView()
1257 BufferView * GuiView::currentBufferView()
1259 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1263 BufferView const * GuiView::currentBufferView() const
1265 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1269 #if (QT_VERSION >= 0x040400)
1270 static docstring saveAndDestroyBuffer(Buffer * buffer, FileName const & fname)
1273 FileName const tmp_ret = FileName::tempName("lyxauto");
1274 if (!tmp_ret.empty()) {
1275 if (buffer->writeFile(tmp_ret))
1276 failed = !tmp_ret.moveTo(fname);
1279 // failed to write/rename tmp_ret so try writing direct
1280 failed = buffer->writeFile(fname);
1284 ? _("Automatic save failed!")
1285 : _("Automatic save done.");
1290 void GuiView::autoSave()
1292 LYXERR(Debug::INFO, "Running autoSave()");
1294 Buffer * buffer = documentBufferView()
1295 ? &documentBufferView()->buffer() : 0;
1299 #if (QT_VERSION >= 0x040400)
1300 QFuture<docstring> f = QtConcurrent::run(saveAndDestroyBuffer, buffer->clone(),
1301 buffer->getAutosaveFilename());
1302 d.autosave_watcher_.setFuture(f);
1309 void GuiView::resetAutosaveTimers()
1312 d.autosave_timeout_.restart();
1316 bool GuiView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1319 Buffer * buf = currentBufferView()
1320 ? ¤tBufferView()->buffer() : 0;
1321 Buffer * doc_buffer = documentBufferView()
1322 ? &(documentBufferView()->buffer()) : 0;
1324 // Check whether we need a buffer
1325 if (!lyxaction.funcHasFlag(cmd.action, LyXAction::NoBuffer) && !buf) {
1326 // no, exit directly
1327 flag.message(from_utf8(N_("Command not allowed with"
1328 "out any document open")));
1329 flag.setEnabled(false);
1333 if (cmd.origin == FuncRequest::TOC) {
1334 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
1336 if (toc->getStatus(documentBufferView()->cursor(), cmd, fs))
1339 flag.setEnabled(false);
1343 switch(cmd.action) {
1344 case LFUN_BUFFER_IMPORT:
1347 case LFUN_MASTER_BUFFER_UPDATE:
1348 case LFUN_MASTER_BUFFER_VIEW:
1349 enable = doc_buffer && doc_buffer->parent() != 0
1350 && !d.preview_watcher_.isRunning();
1353 case LFUN_BUFFER_UPDATE:
1354 case LFUN_BUFFER_VIEW: {
1355 if (!doc_buffer || d.preview_watcher_.isRunning()) {
1359 string format = to_utf8(cmd.argument());
1360 if (cmd.argument().empty())
1361 format = doc_buffer->getDefaultOutputFormat();
1362 enable = doc_buffer->isExportableFormat(format);
1366 case LFUN_BUFFER_RELOAD:
1367 enable = doc_buffer && !doc_buffer->isUnnamed()
1368 && doc_buffer->fileName().exists()
1369 && (!doc_buffer->isClean()
1370 || doc_buffer->isExternallyModified(Buffer::timestamp_method));
1373 case LFUN_BUFFER_CHILD_OPEN:
1374 enable = doc_buffer;
1377 case LFUN_BUFFER_WRITE:
1378 enable = doc_buffer && (doc_buffer->isUnnamed() || !doc_buffer->isClean());
1381 //FIXME: This LFUN should be moved to GuiApplication.
1382 case LFUN_BUFFER_WRITE_ALL: {
1383 // We enable the command only if there are some modified buffers
1384 Buffer * first = theBufferList().first();
1389 // We cannot use a for loop as the buffer list is a cycle.
1391 if (!b->isClean()) {
1395 b = theBufferList().next(b);
1396 } while (b != first);
1400 case LFUN_BUFFER_WRITE_AS:
1401 enable = doc_buffer;
1404 case LFUN_BUFFER_CLOSE:
1405 enable = doc_buffer;
1408 case LFUN_BUFFER_CLOSE_ALL:
1409 enable = theBufferList().last() != theBufferList().first();
1412 case LFUN_SPLIT_VIEW:
1413 if (cmd.getArg(0) == "vertical")
1414 enable = doc_buffer && (d.splitter_->count() == 1 ||
1415 d.splitter_->orientation() == Qt::Vertical);
1417 enable = doc_buffer && (d.splitter_->count() == 1 ||
1418 d.splitter_->orientation() == Qt::Horizontal);
1421 case LFUN_CLOSE_TAB_GROUP:
1422 enable = d.currentTabWorkArea();
1425 case LFUN_TOOLBAR_TOGGLE:
1426 if (GuiToolbar * t = toolbar(cmd.getArg(0)))
1427 flag.setOnOff(t->isVisible());
1430 case LFUN_DROP_LAYOUTS_CHOICE:
1434 case LFUN_UI_TOGGLE:
1435 flag.setOnOff(isFullScreen());
1438 case LFUN_DIALOG_DISCONNECT_INSET:
1441 case LFUN_DIALOG_HIDE:
1442 // FIXME: should we check if the dialog is shown?
1445 case LFUN_DIALOG_TOGGLE:
1446 flag.setOnOff(isDialogVisible(cmd.getArg(0)));
1447 // fall through to set "enable"
1448 case LFUN_DIALOG_SHOW: {
1449 string const name = cmd.getArg(0);
1451 enable = name == "aboutlyx"
1452 || name == "file" //FIXME: should be removed.
1454 || name == "texinfo"
1455 || name == "progress"
1456 || name == "compare";
1457 else if (name == "print")
1458 enable = doc_buffer->isExportable("dvi")
1459 && lyxrc.print_command != "none";
1460 else if (name == "character" || name == "symbols") {
1461 if (!buf || buf->isReadonly()
1462 || !currentBufferView()->cursor().inTexted())
1465 // FIXME we should consider passthru
1467 Inset const & in = currentBufferView()->cursor().inset();
1468 enable = !in.getLayout().isPassThru();
1471 else if (name == "latexlog")
1472 enable = FileName(doc_buffer->logName()).isReadableFile();
1473 else if (name == "spellchecker")
1474 enable = theSpellChecker() && !doc_buffer->isReadonly();
1475 else if (name == "vclog")
1476 enable = doc_buffer->lyxvc().inUse();
1480 case LFUN_DIALOG_UPDATE: {
1481 string const name = cmd.getArg(0);
1483 enable = name == "prefs";
1487 case LFUN_COMMAND_EXECUTE:
1489 case LFUN_MENU_OPEN:
1490 // Nothing to check.
1493 case LFUN_COMPLETION_INLINE:
1494 if (!d.current_work_area_
1495 || !d.current_work_area_->completer().inlinePossible(
1496 currentBufferView()->cursor()))
1500 case LFUN_COMPLETION_POPUP:
1501 if (!d.current_work_area_
1502 || !d.current_work_area_->completer().popupPossible(
1503 currentBufferView()->cursor()))
1507 case LFUN_COMPLETION_COMPLETE:
1508 if (!d.current_work_area_
1509 || !d.current_work_area_->completer().inlinePossible(
1510 currentBufferView()->cursor()))
1514 case LFUN_COMPLETION_ACCEPT:
1515 if (!d.current_work_area_
1516 || (!d.current_work_area_->completer().popupVisible()
1517 && !d.current_work_area_->completer().inlineVisible()
1518 && !d.current_work_area_->completer().completionAvailable()))
1522 case LFUN_COMPLETION_CANCEL:
1523 if (!d.current_work_area_
1524 || (!d.current_work_area_->completer().popupVisible()
1525 && !d.current_work_area_->completer().inlineVisible()))
1529 case LFUN_BUFFER_ZOOM_OUT:
1530 enable = doc_buffer && lyxrc.zoom > 10;
1533 case LFUN_BUFFER_ZOOM_IN:
1534 enable = doc_buffer;
1537 case LFUN_BUFFER_NEXT:
1538 case LFUN_BUFFER_PREVIOUS:
1539 // FIXME: should we check is there is an previous or next buffer?
1541 case LFUN_BUFFER_SWITCH:
1542 // toggle on the current buffer, but do not toggle off
1543 // the other ones (is that a good idea?)
1545 && to_utf8(cmd.argument()) == doc_buffer->absFileName())
1546 flag.setOnOff(true);
1549 case LFUN_VC_REGISTER:
1550 enable = doc_buffer && !doc_buffer->lyxvc().inUse();
1552 case LFUN_VC_CHECK_IN:
1553 enable = doc_buffer && doc_buffer->lyxvc().checkInEnabled();
1555 case LFUN_VC_CHECK_OUT:
1556 enable = doc_buffer && doc_buffer->lyxvc().checkOutEnabled();
1558 case LFUN_VC_LOCKING_TOGGLE:
1559 enable = doc_buffer && !doc_buffer->isReadonly()
1560 && doc_buffer->lyxvc().lockingToggleEnabled();
1561 flag.setOnOff(enable && !doc_buffer->lyxvc().locker().empty());
1563 case LFUN_VC_REVERT:
1564 enable = doc_buffer && doc_buffer->lyxvc().inUse();
1566 case LFUN_VC_UNDO_LAST:
1567 enable = doc_buffer && doc_buffer->lyxvc().undoLastEnabled();
1569 case LFUN_VC_REPO_UPDATE:
1570 enable = doc_buffer && doc_buffer->lyxvc().inUse();
1572 case LFUN_VC_COMMAND: {
1573 if (cmd.argument().empty())
1575 if (!doc_buffer && contains(cmd.getArg(0), 'D'))
1580 case LFUN_SERVER_GOTO_FILE_ROW:
1588 flag.setEnabled(false);
1594 static FileName selectTemplateFile()
1596 FileDialog dlg(qt_("Select template file"));
1597 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1598 dlg.setButton1(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
1600 FileDialog::Result result = dlg.open(toqstr(lyxrc.template_path),
1601 QStringList(qt_("LyX Documents (*.lyx)")));
1603 if (result.first == FileDialog::Later)
1605 if (result.second.isEmpty())
1607 return FileName(fromqstr(result.second));
1611 Buffer * GuiView::loadDocument(FileName const & filename, bool tolastfiles)
1615 Buffer * newBuffer = checkAndLoadLyXFile(filename);
1618 message(_("Document not loaded."));
1623 setBuffer(newBuffer);
1625 // scroll to the position when the file was last closed
1626 if (lyxrc.use_lastfilepos) {
1627 LastFilePosSection::FilePos filepos =
1628 theSession().lastFilePos().load(filename);
1629 documentBufferView()->moveToPosition(filepos.pit, filepos.pos, 0, 0);
1633 theSession().lastFiles().add(filename);
1640 void GuiView::openDocument(string const & fname)
1642 string initpath = lyxrc.document_path;
1644 if (documentBufferView()) {
1645 string const trypath = documentBufferView()->buffer().filePath();
1646 // If directory is writeable, use this as default.
1647 if (FileName(trypath).isDirWritable())
1653 if (fname.empty()) {
1654 FileDialog dlg(qt_("Select document to open"), LFUN_FILE_OPEN);
1655 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1656 dlg.setButton2(qt_("Examples|#E#e"),
1657 toqstr(addPath(package().system_support().absFilename(), "examples")));
1659 QStringList filter(qt_("LyX Documents (*.lyx)"));
1660 filter << qt_("LyX-1.3.x Documents (*.lyx13)")
1661 << qt_("LyX-1.4.x Documents (*.lyx14)")
1662 << qt_("LyX-1.5.x Documents (*.lyx15)")
1663 << qt_("LyX-1.6.x Documents (*.lyx16)");
1664 FileDialog::Result result =
1665 dlg.open(toqstr(initpath), filter);
1667 if (result.first == FileDialog::Later)
1670 filename = fromqstr(result.second);
1672 // check selected filename
1673 if (filename.empty()) {
1674 message(_("Canceled."));
1680 // get absolute path of file and add ".lyx" to the filename if
1682 FileName const fullname =
1683 fileSearch(string(), filename, "lyx", support::may_not_exist);
1684 if (!fullname.empty())
1685 filename = fullname.absFilename();
1687 if (!fullname.onlyPath().isDirectory()) {
1688 Alert::warning(_("Invalid filename"),
1689 bformat(_("The directory in the given path\n%1$s\ndoes not exist."),
1690 from_utf8(fullname.absFilename())));
1693 // if the file doesn't exist, let the user create one
1694 if (!fullname.exists()) {
1695 // the user specifically chose this name. Believe him.
1696 Buffer * const b = newFile(filename, string(), true);
1702 docstring const disp_fn = makeDisplayPath(filename);
1703 message(bformat(_("Opening document %1$s..."), disp_fn));
1706 Buffer * buf = loadDocument(fullname);
1708 buf->updateLabels();
1710 buf->errors("Parse");
1711 str2 = bformat(_("Document %1$s opened."), disp_fn);
1712 if (buf->lyxvc().inUse())
1713 str2 += " " + from_utf8(buf->lyxvc().versionString()) +
1714 " " + _("Version control detected.");
1716 str2 = bformat(_("Could not open document %1$s"), disp_fn);
1721 // FIXME: clean that
1722 static bool import(GuiView * lv, FileName const & filename,
1723 string const & format, ErrorList & errorList)
1725 FileName const lyxfile(support::changeExtension(filename.absFilename(), ".lyx"));
1727 string loader_format;
1728 vector<string> loaders = theConverters().loaders();
1729 if (find(loaders.begin(), loaders.end(), format) == loaders.end()) {
1730 for (vector<string>::const_iterator it = loaders.begin();
1731 it != loaders.end(); ++it) {
1732 if (!theConverters().isReachable(format, *it))
1735 string const tofile =
1736 support::changeExtension(filename.absFilename(),
1737 formats.extension(*it));
1738 if (!theConverters().convert(0, filename, FileName(tofile),
1739 filename, format, *it, errorList))
1741 loader_format = *it;
1744 if (loader_format.empty()) {
1745 frontend::Alert::error(_("Couldn't import file"),
1746 bformat(_("No information for importing the format %1$s."),
1747 formats.prettyName(format)));
1751 loader_format = format;
1753 if (loader_format == "lyx") {
1754 Buffer * buf = lv->loadDocument(lyxfile);
1757 buf->updateLabels();
1759 buf->errors("Parse");
1761 Buffer * const b = newFile(lyxfile.absFilename(), string(), true);
1765 bool as_paragraphs = loader_format == "textparagraph";
1766 string filename2 = (loader_format == format) ? filename.absFilename()
1767 : support::changeExtension(filename.absFilename(),
1768 formats.extension(loader_format));
1769 lv->currentBufferView()->insertPlaintextFile(FileName(filename2),
1771 guiApp->setCurrentView(lv);
1772 lyx::dispatch(FuncRequest(LFUN_MARK_OFF));
1779 void GuiView::importDocument(string const & argument)
1782 string filename = split(argument, format, ' ');
1784 LYXERR(Debug::INFO, format << " file: " << filename);
1786 // need user interaction
1787 if (filename.empty()) {
1788 string initpath = lyxrc.document_path;
1789 if (documentBufferView()) {
1790 string const trypath = documentBufferView()->buffer().filePath();
1791 // If directory is writeable, use this as default.
1792 if (FileName(trypath).isDirWritable())
1796 docstring const text = bformat(_("Select %1$s file to import"),
1797 formats.prettyName(format));
1799 FileDialog dlg(toqstr(text), LFUN_BUFFER_IMPORT);
1800 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1801 dlg.setButton2(qt_("Examples|#E#e"),
1802 toqstr(addPath(package().system_support().absFilename(), "examples")));
1804 docstring filter = formats.prettyName(format);
1807 filter += from_utf8(formats.extension(format));
1810 FileDialog::Result result =
1811 dlg.open(toqstr(initpath), fileFilters(toqstr(filter)));
1813 if (result.first == FileDialog::Later)
1816 filename = fromqstr(result.second);
1818 // check selected filename
1819 if (filename.empty())
1820 message(_("Canceled."));
1823 if (filename.empty())
1826 // get absolute path of file
1827 FileName const fullname(support::makeAbsPath(filename));
1829 FileName const lyxfile(support::changeExtension(fullname.absFilename(), ".lyx"));
1831 // Check if the document already is open
1832 Buffer * buf = theBufferList().getBuffer(lyxfile);
1835 if (!closeBuffer()) {
1836 message(_("Canceled."));
1841 docstring const displaypath = makeDisplayPath(lyxfile.absFilename(), 30);
1843 // if the file exists already, and we didn't do
1844 // -i lyx thefile.lyx, warn
1845 if (lyxfile.exists() && fullname != lyxfile) {
1847 docstring text = bformat(_("The document %1$s already exists.\n\n"
1848 "Do you want to overwrite that document?"), displaypath);
1849 int const ret = Alert::prompt(_("Overwrite document?"),
1850 text, 0, 1, _("&Overwrite"), _("&Cancel"));
1853 message(_("Canceled."));
1858 message(bformat(_("Importing %1$s..."), displaypath));
1859 ErrorList errorList;
1860 if (import(this, fullname, format, errorList))
1861 message(_("imported."));
1863 message(_("file not imported!"));
1865 // FIXME (Abdel 12/08/06): Is there a need to display the error list here?
1869 void GuiView::newDocument(string const & filename, bool from_template)
1871 FileName initpath(lyxrc.document_path);
1872 if (documentBufferView()) {
1873 FileName const trypath(documentBufferView()->buffer().filePath());
1874 // If directory is writeable, use this as default.
1875 if (trypath.isDirWritable())
1879 string templatefile;
1880 if (from_template) {
1881 templatefile = selectTemplateFile().absFilename();
1882 if (templatefile.empty())
1887 if (filename.empty())
1888 b = newUnnamedFile(initpath, to_utf8(_("newfile")), templatefile);
1890 b = newFile(filename, templatefile, true);
1895 // If no new document could be created, it is unsure
1896 // whether there is a valid BufferView.
1897 if (currentBufferView())
1898 // Ensure the cursor is correctly positioned on screen.
1899 currentBufferView()->showCursor();
1903 void GuiView::insertLyXFile(docstring const & fname)
1905 BufferView * bv = documentBufferView();
1910 FileName filename(to_utf8(fname));
1912 if (!filename.empty()) {
1913 bv->insertLyXFile(filename);
1917 // Launch a file browser
1919 string initpath = lyxrc.document_path;
1920 string const trypath = bv->buffer().filePath();
1921 // If directory is writeable, use this as default.
1922 if (FileName(trypath).isDirWritable())
1926 FileDialog dlg(qt_("Select LyX document to insert"), LFUN_FILE_INSERT);
1927 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1928 dlg.setButton2(qt_("Examples|#E#e"),
1929 toqstr(addPath(package().system_support().absFilename(),
1932 FileDialog::Result result = dlg.open(toqstr(initpath),
1933 QStringList(qt_("LyX Documents (*.lyx)")));
1935 if (result.first == FileDialog::Later)
1939 filename.set(fromqstr(result.second));
1941 // check selected filename
1942 if (filename.empty()) {
1943 // emit message signal.
1944 message(_("Canceled."));
1948 bv->insertLyXFile(filename);
1952 void GuiView::insertPlaintextFile(docstring const & fname,
1955 BufferView * bv = documentBufferView();
1959 if (!fname.empty() && !FileName::isAbsolute(to_utf8(fname))) {
1960 message(_("Absolute filename expected."));
1965 FileName filename(to_utf8(fname));
1967 if (!filename.empty()) {
1968 bv->insertPlaintextFile(filename, asParagraph);
1972 FileDialog dlg(qt_("Select file to insert"), (asParagraph ?
1973 LFUN_FILE_INSERT_PLAINTEXT_PARA : LFUN_FILE_INSERT_PLAINTEXT));
1975 FileDialog::Result result = dlg.open(toqstr(bv->buffer().filePath()),
1976 QStringList(qt_("All Files (*)")));
1978 if (result.first == FileDialog::Later)
1982 filename.set(fromqstr(result.second));
1984 // check selected filename
1985 if (filename.empty()) {
1986 // emit message signal.
1987 message(_("Canceled."));
1991 bv->insertPlaintextFile(filename, asParagraph);
1995 bool GuiView::renameBuffer(Buffer & b, docstring const & newname)
1997 FileName fname = b.fileName();
1998 FileName const oldname = fname;
2000 if (!newname.empty()) {
2002 fname = support::makeAbsPath(to_utf8(newname), oldname.onlyPath().absFilename());
2004 // Switch to this Buffer.
2007 // No argument? Ask user through dialog.
2009 FileDialog dlg(qt_("Choose a filename to save document as"),
2010 LFUN_BUFFER_WRITE_AS);
2011 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2012 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
2014 if (!isLyXFilename(fname.absFilename()))
2015 fname.changeExtension(".lyx");
2017 FileDialog::Result result =
2018 dlg.save(toqstr(fname.onlyPath().absFilename()),
2019 QStringList(qt_("LyX Documents (*.lyx)")),
2020 toqstr(fname.onlyFileName()));
2022 if (result.first == FileDialog::Later)
2025 fname.set(fromqstr(result.second));
2030 if (!isLyXFilename(fname.absFilename()))
2031 fname.changeExtension(".lyx");
2034 if (FileName(fname).exists()) {
2035 docstring const file = makeDisplayPath(fname.absFilename(), 30);
2036 docstring text = bformat(_("The document %1$s already "
2037 "exists.\n\nDo you want to "
2038 "overwrite that document?"),
2040 int const ret = Alert::prompt(_("Overwrite document?"),
2041 text, 0, 2, _("&Overwrite"), _("&Rename"), _("&Cancel"));
2044 case 1: return renameBuffer(b, docstring());
2045 case 2: return false;
2049 FileName oldauto = b.getAutosaveFilename();
2051 // Ok, change the name of the buffer
2052 b.setFileName(fname.absFilename());
2054 bool unnamed = b.isUnnamed();
2055 b.setUnnamed(false);
2056 b.saveCheckSum(fname);
2058 // bring the autosave file with us, just in case.
2059 b.moveAutosaveFile(oldauto);
2061 if (!saveBuffer(b)) {
2062 oldauto = b.getAutosaveFilename();
2063 b.setFileName(oldname.absFilename());
2064 b.setUnnamed(unnamed);
2065 b.saveCheckSum(oldname);
2066 b.moveAutosaveFile(oldauto);
2074 bool GuiView::saveBuffer(Buffer & b)
2076 if (workArea(b) && workArea(b)->inDialogMode())
2080 return renameBuffer(b, docstring());
2083 theSession().lastFiles().add(b.fileName());
2087 // Switch to this Buffer.
2090 // FIXME: we don't tell the user *WHY* the save failed !!
2091 docstring const file = makeDisplayPath(b.absFileName(), 30);
2092 docstring text = bformat(_("The document %1$s could not be saved.\n\n"
2093 "Do you want to rename the document and "
2094 "try again?"), file);
2095 int const ret = Alert::prompt(_("Rename and save?"),
2096 text, 0, 2, _("&Rename"), _("&Retry"), _("&Cancel"));
2099 if (!renameBuffer(b, docstring()))
2108 return saveBuffer(b);
2112 bool GuiView::hideWorkArea(GuiWorkArea * wa)
2114 return closeWorkArea(wa, false);
2118 bool GuiView::closeWorkArea(GuiWorkArea * wa)
2120 Buffer & buf = wa->bufferView().buffer();
2121 return closeWorkArea(wa, !buf.parent());
2125 bool GuiView::closeBuffer()
2127 GuiWorkArea * wa = currentMainWorkArea();
2128 setCurrentWorkArea(wa);
2129 Buffer & buf = wa->bufferView().buffer();
2130 return wa && closeWorkArea(wa, !buf.parent());
2134 void GuiView::writeSession() const {
2135 GuiWorkArea const * active_wa = currentMainWorkArea();
2136 for (int i = 0; i < d.splitter_->count(); ++i) {
2137 TabWorkArea * twa = d.tabWorkArea(i);
2138 for (int j = 0; j < twa->count(); ++j) {
2139 GuiWorkArea * wa = static_cast<GuiWorkArea *>(twa->widget(j));
2140 Buffer & buf = wa->bufferView().buffer();
2141 theSession().lastOpened().add(buf.fileName(), wa == active_wa);
2147 bool GuiView::closeBufferAll()
2149 // Close the workareas in all other views
2150 QList<int> const ids = guiApp->viewIds();
2151 for (int i = 0; i != ids.size(); ++i) {
2152 if (id_ != ids[i] && !guiApp->view(ids[i]).closeWorkAreaAll())
2156 // Close our own workareas
2157 if (!closeWorkAreaAll())
2160 // Now close the hidden buffers. We prevent hidden buffers from being
2161 // dirty, so we can just close them.
2162 theBufferList().closeAll();
2167 bool GuiView::closeWorkAreaAll()
2169 setCurrentWorkArea(currentMainWorkArea());
2171 // We might be in a situation that there is still a tabWorkArea, but
2172 // there are no tabs anymore. This can happen when we get here after a
2173 // TabWorkArea::lastWorkAreaRemoved() signal. Therefore we count how
2174 // many TabWorkArea's have no documents anymore.
2177 // We have to call count() each time, because it can happen that
2178 // more than one splitter will disappear in one iteration (bug 5998).
2179 for (; d.splitter_->count() > empty_twa; ) {
2180 TabWorkArea * twa = d.tabWorkArea(empty_twa);
2182 if (twa->count() == 0)
2185 setCurrentWorkArea(twa->currentWorkArea());
2186 if (!closeTabWorkArea(twa))
2194 bool GuiView::closeWorkArea(GuiWorkArea * wa, bool close_buffer)
2199 Buffer & buf = wa->bufferView().buffer();
2202 return closeBuffer(buf);
2204 if (!inMultiTabs(wa))
2205 if (!saveBufferIfNeeded(buf, true))
2213 bool GuiView::closeBuffer(Buffer & buf)
2215 // If we are in a close_event all children will be closed in some time,
2216 // so no need to do it here. This will ensure that the children end up
2217 // in the session file in the correct order. If we close the master
2218 // buffer, we can close or release the child buffers here too.
2220 vector<Buffer *> clist = buf.getChildren(false);
2221 for (vector<Buffer *>::const_iterator it = clist.begin();
2222 it != clist.end(); ++it) {
2223 // If a child is dirty, do not close
2224 // without user intervention
2225 //FIXME: should we look in other tabworkareas?
2226 Buffer * child_buf = *it;
2227 GuiWorkArea * child_wa = workArea(*child_buf);
2229 if (!closeWorkArea(child_wa, true))
2232 theBufferList().releaseChild(&buf, child_buf);
2235 // goto bookmark to update bookmark pit.
2236 //FIXME: we should update only the bookmarks related to this buffer!
2237 LYXERR(Debug::DEBUG, "GuiView::closeBuffer()");
2238 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
2239 theLyXFunc().gotoBookmark(i+1, false, false);
2241 if (saveBufferIfNeeded(buf, false)) {
2242 theBufferList().release(&buf);
2249 bool GuiView::closeTabWorkArea(TabWorkArea * twa)
2251 while (twa == d.currentTabWorkArea()) {
2252 twa->setCurrentIndex(twa->count()-1);
2254 GuiWorkArea * wa = twa->currentWorkArea();
2255 Buffer & b = wa->bufferView().buffer();
2257 // We only want to close the buffer if the same buffer is not visible
2258 // in another view, and if this is not a child and if we are closing
2259 // a view (not a tabgroup).
2260 bool const close_buffer =
2261 !inMultiViews(wa) && !b.parent() && closing_;
2263 if (!closeWorkArea(wa, close_buffer))
2270 bool GuiView::saveBufferIfNeeded(Buffer & buf, bool hiding)
2272 if (buf.isClean() || buf.paragraphs().empty())
2275 // Switch to this Buffer.
2280 if (buf.isUnnamed())
2281 file = from_utf8(buf.fileName().onlyFileName());
2283 file = buf.fileName().displayName(30);
2285 // Bring this window to top before asking questions.
2290 if (hiding && buf.isUnnamed()) {
2291 docstring const text = bformat(_("The document %1$s has not been "
2292 "saved yet.\n\nDo you want to save "
2293 "the document?"), file);
2294 ret = Alert::prompt(_("Save new document?"),
2295 text, 0, 1, _("&Save"), _("&Cancel"));
2299 docstring const text = bformat(_("The document %1$s has unsaved changes."
2300 "\n\nDo you want to save the document or discard the changes?"), file);
2301 ret = Alert::prompt(_("Save changed document?"),
2302 text, 0, 2, _("&Save"), _("&Discard"), _("&Cancel"));
2307 if (!saveBuffer(buf))
2311 // if we crash after this we could
2312 // have no autosave file but I guess
2313 // this is really improbable (Jug)
2314 buf.removeAutosaveFile();
2316 // revert all changes
2327 bool GuiView::inMultiTabs(GuiWorkArea * wa)
2329 Buffer & buf = wa->bufferView().buffer();
2331 for (int i = 0; i != d.splitter_->count(); ++i) {
2332 GuiWorkArea * wa_ = d.tabWorkArea(i)->workArea(buf);
2333 if (wa_ && wa_ != wa)
2336 return inMultiViews(wa);
2340 bool GuiView::inMultiViews(GuiWorkArea * wa)
2342 QList<int> const ids = guiApp->viewIds();
2343 Buffer & buf = wa->bufferView().buffer();
2346 for (int i = 0; i != ids.size() && found_twa <= 1; ++i) {
2350 if (guiApp->view(ids[i]).workArea(buf))
2357 void GuiView::gotoNextOrPreviousBuffer(NextOrPrevious np)
2359 Buffer * const curbuf = documentBufferView()
2360 ? &documentBufferView()->buffer() : 0;
2361 Buffer * nextbuf = curbuf;
2363 if (np == NEXTBUFFER)
2364 nextbuf = theBufferList().next(nextbuf);
2366 nextbuf = theBufferList().previous(nextbuf);
2367 if (nextbuf == curbuf)
2373 if (workArea(*nextbuf))
2380 /// make sure the document is saved
2381 static bool ensureBufferClean(Buffer * buffer)
2383 LASSERT(buffer, return false);
2384 if (buffer->isClean() && !buffer->isUnnamed())
2387 docstring const file = buffer->fileName().displayName(30);
2390 if (!buffer->isUnnamed()) {
2391 text = bformat(_("The document %1$s has unsaved "
2392 "changes.\n\nDo you want to save "
2393 "the document?"), file);
2394 title = _("Save changed document?");
2397 text = bformat(_("The document %1$s has not been "
2398 "saved yet.\n\nDo you want to save "
2399 "the document?"), file);
2400 title = _("Save new document?");
2402 int const ret = Alert::prompt(title, text, 0, 1, _("&Save"), _("&Cancel"));
2405 dispatch(FuncRequest(LFUN_BUFFER_WRITE));
2407 return buffer->isClean() && !buffer->isUnnamed();
2411 void GuiView::reloadBuffer()
2413 Buffer * buf = &documentBufferView()->buffer();
2418 void GuiView::checkExternallyModifiedBuffers()
2420 BufferList::iterator bit = theBufferList().begin();
2421 BufferList::iterator const bend = theBufferList().end();
2422 for (; bit != bend; ++bit) {
2423 if ((*bit)->fileName().exists()
2424 && (*bit)->isExternallyModified(Buffer::checksum_method)) {
2425 docstring text = bformat(_("Document \n%1$s\n has been externally modified."
2426 " Reload now? Any local changes will be lost."),
2427 from_utf8((*bit)->absFileName()));
2428 int const ret = Alert::prompt(_("Reload externally changed document?"),
2429 text, 0, 1, _("&Reload"), _("&Cancel"));
2437 void GuiView::dispatchVC(FuncRequest const & cmd)
2439 // message for statusbar
2441 Buffer * buffer = documentBufferView()
2442 ? &(documentBufferView()->buffer()) : 0;
2444 switch (cmd.action) {
2445 case LFUN_VC_REGISTER:
2446 if (!buffer || !ensureBufferClean(buffer))
2448 if (!buffer->lyxvc().inUse()) {
2449 if (buffer->lyxvc().registrer())
2454 case LFUN_VC_CHECK_IN:
2455 if (!buffer || !ensureBufferClean(buffer))
2457 if (buffer->lyxvc().inUse() && !buffer->isReadonly()) {
2458 msg = buffer->lyxvc().checkIn();
2463 case LFUN_VC_CHECK_OUT:
2464 if (!buffer || !ensureBufferClean(buffer))
2466 if (buffer->lyxvc().inUse()) {
2467 msg = buffer->lyxvc().checkOut();
2472 case LFUN_VC_LOCKING_TOGGLE:
2473 LASSERT(buffer, return);
2474 if (!ensureBufferClean(buffer) || buffer->isReadonly())
2476 if (buffer->lyxvc().inUse()) {
2477 string res = buffer->lyxvc().lockingToggle();
2479 frontend::Alert::error(_("Revision control error."),
2480 _("Error when setting the locking property."));
2488 case LFUN_VC_REVERT:
2489 LASSERT(buffer, return);
2490 buffer->lyxvc().revert();
2494 case LFUN_VC_UNDO_LAST:
2495 LASSERT(buffer, return);
2496 buffer->lyxvc().undoLast();
2500 case LFUN_VC_REPO_UPDATE:
2501 LASSERT(buffer, return);
2502 if (ensureBufferClean(buffer)) {
2503 msg = buffer->lyxvc().repoUpdate();
2504 checkExternallyModifiedBuffers();
2508 case LFUN_VC_COMMAND: {
2509 string flag = cmd.getArg(0);
2510 if (buffer && contains(flag, 'R') && !ensureBufferClean(buffer))
2513 if (contains(flag, 'M')) {
2514 if (!Alert::askForText(message, _("LyX VC: Log Message")))
2517 string path = cmd.getArg(1);
2518 if (contains(path, "$$p") && buffer)
2519 path = subst(path, "$$p", buffer->filePath());
2520 LYXERR(Debug::LYXVC, "Directory: " << path);
2522 if (!pp.isReadableDirectory()) {
2523 lyxerr << _("Directory is not accessible.") << endl;
2526 support::PathChanger p(pp);
2528 string command = cmd.getArg(2);
2529 if (command.empty())
2532 command = subst(command, "$$i", buffer->absFileName());
2533 command = subst(command, "$$p", buffer->filePath());
2535 command = subst(command, "$$m", to_utf8(message));
2536 LYXERR(Debug::LYXVC, "Command: " << command);
2538 one.startscript(Systemcall::Wait, command);
2542 if (contains(flag, 'I'))
2543 buffer->markDirty();
2544 if (contains(flag, 'R'))
2554 message(from_utf8(msg));
2558 void GuiView::openChildDocument(string const & fname)
2560 LASSERT(documentBufferView(), return);
2561 Buffer & buffer = documentBufferView()->buffer();
2562 FileName const filename = support::makeAbsPath(fname, buffer.filePath());
2563 documentBufferView()->saveBookmark(false);
2565 bool parsed = false;
2566 if (theBufferList().exists(filename)) {
2567 child = theBufferList().getBuffer(filename);
2569 message(bformat(_("Opening child document %1$s..."),
2570 makeDisplayPath(filename.absFilename())));
2571 child = loadDocument(filename, false);
2577 // Set the parent name of the child document.
2578 // This makes insertion of citations and references in the child work,
2579 // when the target is in the parent or another child document.
2580 child->setParent(&buffer);
2581 child->masterBuffer()->updateLabels();
2584 child->errors("Parse");
2588 bool GuiView::goToFileRow(string const & argument)
2592 size_t i = argument.find_last_of(' ');
2593 if (i != string::npos) {
2594 file_name = os::internal_path(trim(argument.substr(0, i)));
2595 istringstream is(argument.substr(i + 1));
2600 if (i == string::npos) {
2601 LYXERR0("Wrong argument: " << argument);
2605 string const abstmp = package().temp_dir().absFilename();
2606 string const realtmp = package().temp_dir().realPath();
2607 // We have to use os::path_prefix_is() here, instead of
2608 // simply prefixIs(), because the file name comes from
2609 // an external application and may need case adjustment.
2610 if (os::path_prefix_is(file_name, abstmp, os::CASE_ADJUSTED)
2611 || os::path_prefix_is(file_name, realtmp, os::CASE_ADJUSTED)) {
2612 // Needed by inverse dvi search. If it is a file
2613 // in tmpdir, call the apropriated function.
2614 // If tmpdir is a symlink, we may have the real
2615 // path passed back, so we correct for that.
2616 if (!prefixIs(file_name, abstmp))
2617 file_name = subst(file_name, realtmp, abstmp);
2618 buf = theBufferList().getBufferFromTmp(file_name);
2620 // Must replace extension of the file to be .lyx
2621 // and get full path
2622 FileName const s = fileSearch(string(),
2623 support::changeExtension(file_name, ".lyx"), "lyx");
2624 // Either change buffer or load the file
2625 if (theBufferList().exists(s))
2626 buf = theBufferList().getBuffer(s);
2627 else if (s.exists()) {
2628 buf = loadDocument(s);
2629 buf->updateLabels();
2630 buf->errors("Parse");
2633 _("File does not exist: %1$s"),
2634 makeDisplayPath(file_name)));
2639 documentBufferView()->setCursorFromRow(row);
2644 #if (QT_VERSION >= 0x040400)
2645 static docstring exportAndDestroy(Buffer * buffer, string const & format)
2647 bool const success = buffer->doExport(format, true);
2650 ? bformat(_("Successful export to format: %1$s"), from_utf8(format))
2651 : bformat(_("Error exporting to format: %1$s"), from_utf8(format));
2655 static docstring previewAndDestroy(Buffer * buffer, string const & format)
2657 bool const success = buffer->preview(format);
2660 ? bformat(_("Successful preview of format: %1$s"), from_utf8(format))
2661 : bformat(_("Error previewing format: %1$s"), from_utf8(format));
2666 bool GuiView::dispatch(FuncRequest const & cmd)
2668 BufferView * bv = currentBufferView();
2669 // By default we won't need any update.
2671 bv->cursor().updateFlags(Update::None);
2673 Buffer * doc_buffer = documentBufferView()
2674 ? &(documentBufferView()->buffer()) : 0;
2676 bool dispatched = true;
2678 if (cmd.origin == FuncRequest::TOC) {
2679 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
2680 toc->doDispatch(bv->cursor(), cmd);
2684 string const argument = to_utf8(cmd.argument());
2686 switch(cmd.action) {
2687 case LFUN_BUFFER_CHILD_OPEN:
2688 openChildDocument(to_utf8(cmd.argument()));
2691 case LFUN_BUFFER_IMPORT:
2692 importDocument(to_utf8(cmd.argument()));
2695 case LFUN_BUFFER_EXPORT: {
2698 if (cmd.argument() == "custom") {
2699 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "sendto"));
2702 if (doc_buffer->doExport(argument, false)) {
2703 message(bformat(_("Error exporting to format: %1$s."),
2709 case LFUN_BUFFER_UPDATE: {
2712 string format = argument;
2713 if (argument.empty())
2714 format = doc_buffer->getDefaultOutputFormat();
2715 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
2716 d.progress_->clearMessages();
2717 message(_("Exporting ..."));
2718 QFuture<docstring> f = QtConcurrent::run(exportAndDestroy,
2719 doc_buffer->clone(), format);
2720 d.setPreviewFuture(f);
2722 doc_buffer->doExport(format, true);
2726 case LFUN_BUFFER_VIEW: {
2729 string format = argument;
2730 if (argument.empty())
2731 format = doc_buffer->getDefaultOutputFormat();
2732 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
2733 d.progress_->clearMessages();
2734 message(_("Previewing ..."));
2735 QFuture<docstring> f = QtConcurrent::run(previewAndDestroy,
2736 doc_buffer->clone(), format);
2737 d.setPreviewFuture(f);
2739 doc_buffer->preview(format);
2743 case LFUN_MASTER_BUFFER_UPDATE: {
2746 string format = argument;
2747 Buffer const * master = doc_buffer->masterBuffer();
2748 if (argument.empty())
2749 format = master->getDefaultOutputFormat();
2750 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
2751 QFuture<docstring> f = QtConcurrent::run(exportAndDestroy,
2752 master->clone(), format);
2753 d.setPreviewFuture(f);
2755 master->doExport(format, true);
2759 case LFUN_MASTER_BUFFER_VIEW: {
2760 string format = argument;
2761 Buffer const * master = doc_buffer->masterBuffer();
2762 if (argument.empty())
2763 format = master->getDefaultOutputFormat();
2764 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
2765 QFuture<docstring> f = QtConcurrent::run(previewAndDestroy,
2766 master->clone(), format);
2767 d.setPreviewFuture(f);
2769 master->preview(format);
2773 case LFUN_BUFFER_SWITCH:
2774 if (FileName::isAbsolute(to_utf8(cmd.argument()))) {
2776 theBufferList().getBuffer(FileName(to_utf8(cmd.argument())));
2780 message(_("Document not loaded"));
2784 case LFUN_BUFFER_NEXT:
2785 gotoNextOrPreviousBuffer(NEXTBUFFER);
2788 case LFUN_BUFFER_PREVIOUS:
2789 gotoNextOrPreviousBuffer(PREVBUFFER);
2792 case LFUN_COMMAND_EXECUTE: {
2793 bool const show_it = cmd.argument() != "off";
2794 // FIXME: this is a hack, "minibuffer" should not be
2796 if (GuiToolbar * t = toolbar("minibuffer")) {
2797 t->setVisible(show_it);
2798 if (show_it && t->commandBuffer())
2799 t->commandBuffer()->setFocus();
2803 case LFUN_DROP_LAYOUTS_CHOICE:
2804 d.layout_->showPopup();
2807 case LFUN_MENU_OPEN:
2808 if (QMenu * menu = guiApp->menus().menu(toqstr(cmd.argument()), *this))
2809 menu->exec(QCursor::pos());
2812 case LFUN_FILE_INSERT:
2813 insertLyXFile(cmd.argument());
2815 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
2816 insertPlaintextFile(cmd.argument(), true);
2819 case LFUN_FILE_INSERT_PLAINTEXT:
2820 insertPlaintextFile(cmd.argument(), false);
2823 case LFUN_BUFFER_RELOAD: {
2824 LASSERT(doc_buffer, break);
2825 docstring const file = makeDisplayPath(doc_buffer->absFileName(), 20);
2826 docstring text = bformat(_("Any changes will be lost. Are you sure "
2827 "you want to revert to the saved version of the document %1$s?"), file);
2828 int const ret = Alert::prompt(_("Revert to saved document?"),
2829 text, 1, 1, _("&Revert"), _("&Cancel"));
2832 doc_buffer->markClean();
2838 case LFUN_BUFFER_WRITE:
2839 LASSERT(doc_buffer, break);
2840 saveBuffer(*doc_buffer);
2843 case LFUN_BUFFER_WRITE_AS:
2844 LASSERT(doc_buffer, break);
2845 renameBuffer(*doc_buffer, cmd.argument());
2848 case LFUN_BUFFER_WRITE_ALL: {
2849 Buffer * first = theBufferList().first();
2852 message(_("Saving all documents..."));
2853 // We cannot use a for loop as the buffer list cycles.
2856 if (!b->isClean()) {
2858 LYXERR(Debug::ACTION, "Saved " << b->absFileName());
2860 b = theBufferList().next(b);
2861 } while (b != first);
2862 message(_("All documents saved."));
2866 case LFUN_BUFFER_CLOSE:
2870 case LFUN_BUFFER_CLOSE_ALL:
2874 case LFUN_TOOLBAR_TOGGLE: {
2875 string const name = cmd.getArg(0);
2876 if (GuiToolbar * t = toolbar(name))
2881 case LFUN_DIALOG_UPDATE: {
2882 string const name = to_utf8(cmd.argument());
2883 if (currentBufferView()) {
2884 Inset * inset = currentBufferView()->editedInset(name);
2885 // Can only update a dialog connected to an existing inset
2888 // FIXME: get rid of this indirection; GuiView ask the inset
2889 // if he is kind enough to update itself...
2890 FuncRequest fr(LFUN_INSET_DIALOG_UPDATE, cmd.argument());
2891 inset->dispatch(currentBufferView()->cursor(), fr);
2892 } else if (name == "paragraph") {
2893 lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
2894 } else if (name == "prefs" || name == "document") {
2895 updateDialog(name, string());
2900 case LFUN_DIALOG_TOGGLE: {
2901 if (isDialogVisible(cmd.getArg(0)))
2902 dispatch(FuncRequest(LFUN_DIALOG_HIDE, cmd.argument()));
2904 dispatch(FuncRequest(LFUN_DIALOG_SHOW, cmd.argument()));
2908 case LFUN_DIALOG_DISCONNECT_INSET:
2909 disconnectDialog(to_utf8(cmd.argument()));
2912 case LFUN_DIALOG_HIDE: {
2913 guiApp->hideDialogs(to_utf8(cmd.argument()), 0);
2917 case LFUN_DIALOG_SHOW: {
2918 string const name = cmd.getArg(0);
2919 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
2921 if (name == "character") {
2922 data = freefont2string();
2924 showDialog("character", data);
2925 } else if (name == "latexlog") {
2926 Buffer::LogType type;
2927 string const logfile = doc_buffer->logName(&type);
2929 case Buffer::latexlog:
2932 case Buffer::buildlog:
2936 data += Lexer::quoteString(logfile);
2937 showDialog("log", data);
2938 } else if (name == "vclog") {
2939 string const data = "vc " +
2940 Lexer::quoteString(doc_buffer->lyxvc().getLogFile());
2941 showDialog("log", data);
2942 } else if (name == "symbols") {
2943 data = bv->cursor().getEncoding()->name();
2945 showDialog("symbols", data);
2947 } else if (name == "prefs" && isFullScreen()) {
2948 FuncRequest fr(LFUN_INSET_INSERT, "fullscreen");
2950 showDialog("prefs", data);
2952 showDialog(name, data);
2957 message(cmd.argument());
2960 case LFUN_UI_TOGGLE:
2962 // Make sure the keyboard focus stays in the work area.
2966 case LFUN_SPLIT_VIEW: {
2967 LASSERT(doc_buffer, break);
2968 string const orientation = cmd.getArg(0);
2969 d.splitter_->setOrientation(orientation == "vertical"
2970 ? Qt::Vertical : Qt::Horizontal);
2971 TabWorkArea * twa = addTabWorkArea();
2972 GuiWorkArea * wa = twa->addWorkArea(*doc_buffer, *this);
2973 setCurrentWorkArea(wa);
2976 case LFUN_CLOSE_TAB_GROUP:
2977 if (TabWorkArea * twa = d.currentTabWorkArea()) {
2978 closeTabWorkArea(twa);
2979 d.current_work_area_ = 0;
2980 twa = d.currentTabWorkArea();
2981 // Switch to the next GuiWorkArea in the found TabWorkArea.
2983 // Make sure the work area is up to date.
2984 setCurrentWorkArea(twa->currentWorkArea());
2986 setCurrentWorkArea(0);
2991 case LFUN_COMPLETION_INLINE:
2992 if (d.current_work_area_)
2993 d.current_work_area_->completer().showInline();
2996 case LFUN_COMPLETION_POPUP:
2997 if (d.current_work_area_)
2998 d.current_work_area_->completer().showPopup();
3002 case LFUN_COMPLETION_COMPLETE:
3003 if (d.current_work_area_)
3004 d.current_work_area_->completer().tab();
3007 case LFUN_COMPLETION_CANCEL:
3008 if (d.current_work_area_) {
3009 if (d.current_work_area_->completer().popupVisible())
3010 d.current_work_area_->completer().hidePopup();
3012 d.current_work_area_->completer().hideInline();
3016 case LFUN_COMPLETION_ACCEPT:
3017 if (d.current_work_area_)
3018 d.current_work_area_->completer().activate();
3021 case LFUN_BUFFER_ZOOM_IN:
3022 case LFUN_BUFFER_ZOOM_OUT:
3023 if (cmd.argument().empty()) {
3024 if (cmd.action == LFUN_BUFFER_ZOOM_IN)
3029 lyxrc.zoom += convert<int>(cmd.argument());
3031 if (lyxrc.zoom < 10)
3034 // The global QPixmapCache is used in GuiPainter to cache text
3035 // painting so we must reset it.
3036 QPixmapCache::clear();
3037 guiApp->fontLoader().update();
3038 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
3041 case LFUN_VC_REGISTER:
3042 case LFUN_VC_CHECK_IN:
3043 case LFUN_VC_CHECK_OUT:
3044 case LFUN_VC_REPO_UPDATE:
3045 case LFUN_VC_LOCKING_TOGGLE:
3046 case LFUN_VC_REVERT:
3047 case LFUN_VC_UNDO_LAST:
3048 case LFUN_VC_COMMAND:
3052 case LFUN_SERVER_GOTO_FILE_ROW:
3053 goToFileRow(to_utf8(cmd.argument()));
3061 // Part of automatic menu appearance feature.
3062 if (isFullScreen()) {
3063 if (menuBar()->isVisible() && lyxrc.full_screen_menubar)
3065 if (statusBar()->isVisible())
3066 statusBar()->hide();
3073 void GuiView::lfunUiToggle(FuncRequest const & cmd)
3075 string const arg = cmd.getArg(0);
3076 if (arg == "scrollbar") {
3077 // hide() is of no help
3078 if (d.current_work_area_->verticalScrollBarPolicy() ==
3079 Qt::ScrollBarAlwaysOff)
3081 d.current_work_area_->setVerticalScrollBarPolicy(
3082 Qt::ScrollBarAsNeeded);
3084 d.current_work_area_->setVerticalScrollBarPolicy(
3085 Qt::ScrollBarAlwaysOff);
3088 if (arg == "statusbar") {
3089 statusBar()->setVisible(!statusBar()->isVisible());
3092 if (arg == "menubar") {
3093 menuBar()->setVisible(!menuBar()->isVisible());
3096 #if QT_VERSION >= 0x040300
3097 if (arg == "frame") {
3099 getContentsMargins(&l, &t, &r, &b);
3100 //are the frames in default state?
3101 d.current_work_area_->setFrameStyle(QFrame::NoFrame);
3103 setContentsMargins(-2, -2, -2, -2);
3105 setContentsMargins(0, 0, 0, 0);
3110 if (arg == "fullscreen") {
3115 message(bformat("LFUN_UI_TOGGLE " + _("%1$s unknown command!"), from_utf8(arg)));
3119 void GuiView::toggleFullScreen()
3121 if (isFullScreen()) {
3122 for (int i = 0; i != d.splitter_->count(); ++i)
3123 d.tabWorkArea(i)->setFullScreen(false);
3124 #if QT_VERSION >= 0x040300
3125 setContentsMargins(0, 0, 0, 0);
3127 setWindowState(windowState() ^ Qt::WindowFullScreen);
3130 statusBar()->show();
3133 hideDialogs("prefs", 0);
3134 for (int i = 0; i != d.splitter_->count(); ++i)
3135 d.tabWorkArea(i)->setFullScreen(true);
3136 #if QT_VERSION >= 0x040300
3137 setContentsMargins(-2, -2, -2, -2);
3140 setWindowState(windowState() ^ Qt::WindowFullScreen);
3141 statusBar()->hide();
3142 if (lyxrc.full_screen_menubar)
3144 if (lyxrc.full_screen_toolbars) {
3145 ToolbarMap::iterator end = d.toolbars_.end();
3146 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
3151 // give dialogs like the TOC a chance to adapt
3156 Buffer const * GuiView::updateInset(Inset const * inset)
3158 if (!d.current_work_area_)
3162 d.current_work_area_->scheduleRedraw();
3164 return &d.current_work_area_->bufferView().buffer();
3168 void GuiView::restartCursor()
3170 /* When we move around, or type, it's nice to be able to see
3171 * the cursor immediately after the keypress.
3173 if (d.current_work_area_)
3174 d.current_work_area_->startBlinkingCursor();
3176 // Take this occasion to update the other GUI elements.
3182 void GuiView::updateCompletion(Cursor & cur, bool start, bool keep)
3184 if (d.current_work_area_)
3185 d.current_work_area_->completer().updateVisibility(cur, start, keep);
3190 // This list should be kept in sync with the list of insets in
3191 // src/insets/Inset.cpp. I.e., if a dialog goes with an inset, the
3192 // dialog should have the same name as the inset.
3193 // Changes should be also recorded in LFUN_DIALOG_SHOW doxygen
3194 // docs in LyXAction.cpp.
3196 char const * const dialognames[] = {
3197 "aboutlyx", "bibitem", "bibtex", "box", "branch", "changes", "character",
3198 "citation", "compare", "document", "errorlist", "ert", "external", "file",
3199 "findreplace", "findreplaceadv", "float", "graphics", "href", "include",
3200 "index", "index_print", "info", "listings", "label", "log", "mathdelimiter",
3201 "mathmatrix", "mathspace", "nomenclature", "nomencl_print", "note",
3202 "paragraph", "phantom", "prefs", "print", "ref", "sendto", "space",
3203 "spellchecker", "symbols", "tabular", "tabularcreate", "thesaurus", "texinfo",
3204 "toc", "view-source", "vspace", "wrap", "progress"};
3206 char const * const * const end_dialognames =
3207 dialognames + (sizeof(dialognames) / sizeof(char *));
3211 cmpCStr(char const * name) : name_(name) {}
3212 bool operator()(char const * other) {
3213 return strcmp(other, name_) == 0;
3220 bool isValidName(string const & name)
3222 return find_if(dialognames, end_dialognames,
3223 cmpCStr(name.c_str())) != end_dialognames;
3229 void GuiView::resetDialogs()
3231 // Make sure that no LFUN uses any LyXView.
3232 guiApp->setCurrentView(0);
3235 constructToolbars();
3236 guiApp->menus().fillMenuBar(menuBar(), this, false);
3237 d.layout_->updateContents(true);
3238 // Now update controls with current buffer.
3239 guiApp->setCurrentView(this);
3245 Dialog * GuiView::findOrBuild(string const & name, bool hide_it)
3247 if (!isValidName(name))
3250 map<string, DialogPtr>::iterator it = d.dialogs_.find(name);
3252 if (it != d.dialogs_.end()) {
3254 it->second->hideView();
3255 return it->second.get();
3258 Dialog * dialog = build(name);
3259 d.dialogs_[name].reset(dialog);
3260 if (lyxrc.allow_geometry_session)
3261 dialog->restoreSession();
3268 void GuiView::showDialog(string const & name, string const & data,
3271 triggerShowDialog(toqstr(name), toqstr(data), inset);
3275 void GuiView::doShowDialog(QString const & qname, QString const & qdata,
3281 const string name = fromqstr(qname);
3282 const string data = fromqstr(qdata);
3286 Dialog * dialog = findOrBuild(name, false);
3288 dialog->showData(data);
3289 if (inset && currentBufferView())
3290 currentBufferView()->editInset(name, inset);
3293 catch (ExceptionMessage const & ex) {
3301 bool GuiView::isDialogVisible(string const & name) const
3303 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3304 if (it == d.dialogs_.end())
3306 return it->second.get()->isVisibleView() && !it->second.get()->isClosing();
3310 void GuiView::hideDialog(string const & name, Inset * inset)
3312 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3313 if (it == d.dialogs_.end())
3316 if (inset && currentBufferView()
3317 && inset != currentBufferView()->editedInset(name))
3320 Dialog * const dialog = it->second.get();
3321 if (dialog->isVisibleView())
3323 if (currentBufferView())
3324 currentBufferView()->editInset(name, 0);
3328 void GuiView::disconnectDialog(string const & name)
3330 if (!isValidName(name))
3332 if (currentBufferView())
3333 currentBufferView()->editInset(name, 0);
3337 void GuiView::hideAll() const
3339 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
3340 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3342 for(; it != end; ++it)
3343 it->second->hideView();
3347 void GuiView::updateDialogs()
3349 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
3350 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3352 for(; it != end; ++it) {
3353 Dialog * dialog = it->second.get();
3354 if (dialog && dialog->isVisibleView())
3355 dialog->checkStatus();
3362 // will be replaced by a proper factory...
3363 Dialog * createGuiAbout(GuiView & lv);
3364 Dialog * createGuiBibitem(GuiView & lv);
3365 Dialog * createGuiBibtex(GuiView & lv);
3366 Dialog * createGuiBox(GuiView & lv);
3367 Dialog * createGuiBranch(GuiView & lv);
3368 Dialog * createGuiChanges(GuiView & lv);
3369 Dialog * createGuiCharacter(GuiView & lv);
3370 Dialog * createGuiCitation(GuiView & lv);
3371 Dialog * createGuiCompare(GuiView & lv);
3372 Dialog * createGuiDelimiter(GuiView & lv);
3373 Dialog * createGuiDocument(GuiView & lv);
3374 Dialog * createGuiErrorList(GuiView & lv);
3375 Dialog * createGuiERT(GuiView & lv);
3376 Dialog * createGuiExternal(GuiView & lv);
3377 Dialog * createGuiFloat(GuiView & lv);
3378 Dialog * createGuiGraphics(GuiView & lv);
3379 Dialog * createGuiInclude(GuiView & lv);
3380 Dialog * createGuiIndex(GuiView & lv);
3381 Dialog * createGuiInfo(GuiView & lv);
3382 Dialog * createGuiLabel(GuiView & lv);
3383 Dialog * createGuiListings(GuiView & lv);
3384 Dialog * createGuiLog(GuiView & lv);
3385 Dialog * createGuiMathHSpace(GuiView & lv);
3386 Dialog * createGuiMathMatrix(GuiView & lv);
3387 Dialog * createGuiNomenclature(GuiView & lv);
3388 Dialog * createGuiNote(GuiView & lv);
3389 Dialog * createGuiParagraph(GuiView & lv);
3390 Dialog * createGuiPhantom(GuiView & lv);
3391 Dialog * createGuiPreferences(GuiView & lv);
3392 Dialog * createGuiPrint(GuiView & lv);
3393 Dialog * createGuiPrintindex(GuiView & lv);
3394 Dialog * createGuiPrintNomencl(GuiView & lv);
3395 Dialog * createGuiRef(GuiView & lv);
3396 Dialog * createGuiSearch(GuiView & lv);
3397 Dialog * createGuiSearchAdv(GuiView & lv);
3398 Dialog * createGuiSendTo(GuiView & lv);
3399 Dialog * createGuiShowFile(GuiView & lv);
3400 Dialog * createGuiSpellchecker(GuiView & lv);
3401 Dialog * createGuiSymbols(GuiView & lv);
3402 Dialog * createGuiTabularCreate(GuiView & lv);
3403 Dialog * createGuiTabular(GuiView & lv);
3404 Dialog * createGuiTexInfo(GuiView & lv);
3405 Dialog * createGuiTextHSpace(GuiView & lv);
3406 Dialog * createGuiToc(GuiView & lv);
3407 Dialog * createGuiThesaurus(GuiView & lv);
3408 Dialog * createGuiHyperlink(GuiView & lv);
3409 Dialog * createGuiVSpace(GuiView & lv);
3410 Dialog * createGuiViewSource(GuiView & lv);
3411 Dialog * createGuiWrap(GuiView & lv);
3412 Dialog * createGuiProgressView(GuiView & lv);
3416 Dialog * GuiView::build(string const & name)
3418 LASSERT(isValidName(name), return 0);
3420 if (name == "aboutlyx")
3421 return createGuiAbout(*this);
3422 if (name == "bibitem")
3423 return createGuiBibitem(*this);
3424 if (name == "bibtex")
3425 return createGuiBibtex(*this);
3427 return createGuiBox(*this);
3428 if (name == "branch")
3429 return createGuiBranch(*this);
3430 if (name == "changes")
3431 return createGuiChanges(*this);
3432 if (name == "character")
3433 return createGuiCharacter(*this);
3434 if (name == "citation")
3435 return createGuiCitation(*this);
3436 if (name == "compare")
3437 return createGuiCompare(*this);
3438 if (name == "document")
3439 return createGuiDocument(*this);
3440 if (name == "errorlist")
3441 return createGuiErrorList(*this);
3443 return createGuiERT(*this);
3444 if (name == "external")
3445 return createGuiExternal(*this);
3447 return createGuiShowFile(*this);
3448 if (name == "findreplace")
3449 return createGuiSearch(*this);
3450 if (name == "findreplaceadv")
3451 return createGuiSearchAdv(*this);
3452 if (name == "float")
3453 return createGuiFloat(*this);
3454 if (name == "graphics")
3455 return createGuiGraphics(*this);
3457 return createGuiHyperlink(*this);
3458 if (name == "include")
3459 return createGuiInclude(*this);
3460 if (name == "index")
3461 return createGuiIndex(*this);
3462 if (name == "index_print")
3463 return createGuiPrintindex(*this);
3465 return createGuiInfo(*this);
3466 if (name == "label")
3467 return createGuiLabel(*this);
3468 if (name == "listings")
3469 return createGuiListings(*this);
3471 return createGuiLog(*this);
3472 if (name == "mathdelimiter")
3473 return createGuiDelimiter(*this);
3474 if (name == "mathspace")
3475 return createGuiMathHSpace(*this);
3476 if (name == "mathmatrix")
3477 return createGuiMathMatrix(*this);
3478 if (name == "nomenclature")
3479 return createGuiNomenclature(*this);
3480 if (name == "nomencl_print")
3481 return createGuiPrintNomencl(*this);
3483 return createGuiNote(*this);
3484 if (name == "paragraph")
3485 return createGuiParagraph(*this);
3486 if (name == "phantom")
3487 return createGuiPhantom(*this);
3488 if (name == "prefs")
3489 return createGuiPreferences(*this);
3490 if (name == "print")
3491 return createGuiPrint(*this);
3493 return createGuiRef(*this);
3494 if (name == "sendto")
3495 return createGuiSendTo(*this);
3496 if (name == "space")
3497 return createGuiTextHSpace(*this);
3498 if (name == "spellchecker")
3499 return createGuiSpellchecker(*this);
3500 if (name == "symbols")
3501 return createGuiSymbols(*this);
3502 if (name == "tabular")
3503 return createGuiTabular(*this);
3504 if (name == "tabularcreate")
3505 return createGuiTabularCreate(*this);
3506 if (name == "texinfo")
3507 return createGuiTexInfo(*this);
3508 if (name == "thesaurus")
3509 return createGuiThesaurus(*this);
3511 return createGuiToc(*this);
3512 if (name == "view-source")
3513 return createGuiViewSource(*this);
3514 if (name == "vspace")
3515 return createGuiVSpace(*this);
3517 return createGuiWrap(*this);
3518 if (name == "progress")
3519 return createGuiProgressView(*this);
3525 } // namespace frontend
3528 #include "moc_GuiView.cpp"