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 QMainWindow::setFocus();
592 void GuiView::focusInEvent(QFocusEvent * e)
594 LYXERR(Debug::DEBUG, "GuiView::focusInEvent()" << this);
595 QMainWindow::focusInEvent(e);
596 // Make sure LyXFunc points to the correct view.
597 guiApp->setCurrentView(this);
598 if (currentMainWorkArea())
599 currentMainWorkArea()->setFocus();
600 else if (currentWorkArea())
601 currentWorkArea()->setFocus();
603 d.bg_widget_->setFocus();
607 QMenu * GuiView::createPopupMenu()
609 return d.toolBarPopup(this);
613 void GuiView::showEvent(QShowEvent * e)
615 LYXERR(Debug::GUI, "Passed Geometry "
616 << size().height() << "x" << size().width()
617 << "+" << pos().x() << "+" << pos().y());
619 if (d.splitter_->count() == 0)
620 // No work area, switch to the background widget.
623 QMainWindow::showEvent(e);
627 /** Destroy only all tabbed WorkAreas. Destruction of other WorkAreas
628 ** is responsibility of the container (e.g., dialog)
630 void GuiView::closeEvent(QCloseEvent * close_event)
632 LYXERR(Debug::DEBUG, "GuiView::closeEvent()");
637 // it can happen that this event arrives without selecting the view,
638 // e.g. when clicking the close button on a background window.
640 if (!closeWorkAreaAll()) {
642 close_event->ignore();
646 // Make sure that nothing will use this to be closed View.
647 guiApp->unregisterView(this);
649 if (isFullScreen()) {
650 // Switch off fullscreen before closing.
655 // Make sure the timer time out will not trigger a statusbar update.
656 d.statusbar_timer_.stop();
658 // Saving fullscreen requires additional tweaks in the toolbar code.
659 // It wouldn't also work under linux natively.
660 if (lyxrc.allow_geometry_session) {
661 // Save this window geometry and layout.
663 // Then the toolbar private states.
664 ToolbarMap::iterator end = d.toolbars_.end();
665 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
666 it->second->saveSession();
667 // Now take care of all other dialogs:
668 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
669 for (; it!= d.dialogs_.end(); ++it)
670 it->second->saveSession();
673 close_event->accept();
677 void GuiView::dragEnterEvent(QDragEnterEvent * event)
679 if (event->mimeData()->hasUrls())
681 /// \todo Ask lyx-devel is this is enough:
682 /// if (event->mimeData()->hasFormat("text/plain"))
683 /// event->acceptProposedAction();
687 void GuiView::dropEvent(QDropEvent * event)
689 QList<QUrl> files = event->mimeData()->urls();
693 LYXERR(Debug::GUI, "GuiView::dropEvent: got URLs!");
694 for (int i = 0; i != files.size(); ++i) {
695 string const file = os::internal_path(fromqstr(
696 files.at(i).toLocalFile()));
700 string const ext = support::getExtension(file);
701 vector<const Format *> found_formats;
703 // Find all formats that have the correct extension.
704 vector<const Format *> const & import_formats
705 = theConverters().importableFormats();
706 vector<const Format *>::const_iterator it = import_formats.begin();
707 for (; it != import_formats.end(); ++it)
708 if ((*it)->extension() == ext)
709 found_formats.push_back(*it);
712 if (found_formats.size() >= 1) {
713 if (found_formats.size() > 1) {
714 //FIXME: show a dialog to choose the correct importable format
716 "Multiple importable formats found, selecting first");
718 string const arg = found_formats[0]->name() + " " + file;
719 cmd = FuncRequest(LFUN_BUFFER_IMPORT, arg);
722 //FIXME: do we have to explicitly check whether it's a lyx file?
724 "No formats found, trying to open it as a lyx file");
725 cmd = FuncRequest(LFUN_FILE_OPEN, file);
728 // Asynchronously post the event. DropEvent usually comes
729 // from the BufferView. But reloading a file might close
730 // the BufferView from within its own event handler.
731 guiApp->dispatchDelayed(cmd);
737 void GuiView::message(docstring const & str)
739 if (ForkedProcess::iAmAChild())
742 // call is moved to GUI-thread by GuiProgress
743 d.progress_->appendMessage(toqstr(str));
747 void GuiView::updateMessage(QString const & str)
749 statusBar()->showMessage(str);
750 d.statusbar_timer_.stop();
751 d.statusbar_timer_.start(3000);
755 void GuiView::smallSizedIcons()
757 setIconSize(QSize(d.smallIconSize, d.smallIconSize));
761 void GuiView::normalSizedIcons()
763 setIconSize(QSize(d.normalIconSize, d.normalIconSize));
767 void GuiView::bigSizedIcons()
769 setIconSize(QSize(d.bigIconSize, d.bigIconSize));
773 void GuiView::clearMessage()
775 // FIXME: This code was introduced in r19643 to fix bug #4123. However,
776 // the hasFocus function mostly returns false, even if the focus is on
777 // a workarea in this view.
781 d.statusbar_timer_.stop();
785 void GuiView::updateWindowTitle(GuiWorkArea * wa)
787 if (wa != d.current_work_area_
788 || wa->bufferView().buffer().isInternal())
790 setWindowTitle(qt_("LyX: ") + wa->windowTitle());
791 setWindowIconText(wa->windowIconText());
795 void GuiView::on_currentWorkAreaChanged(GuiWorkArea * wa)
798 disconnectBufferView();
799 connectBufferView(wa->bufferView());
800 connectBuffer(wa->bufferView().buffer());
801 d.current_work_area_ = wa;
802 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
803 this, SLOT(updateWindowTitle(GuiWorkArea *)));
804 updateWindowTitle(wa);
808 // The document settings needs to be reinitialised.
809 updateDialog("document", "");
811 // Buffer-dependent dialogs must be updated. This is done here because
812 // some dialogs require buffer()->text.
817 void GuiView::on_lastWorkAreaRemoved()
820 // We already are in a close event. Nothing more to do.
823 if (d.splitter_->count() > 1)
824 // We have a splitter so don't close anything.
827 // Reset and updates the dialogs.
828 d.toc_models_.reset(0);
829 updateDialog("document", "");
832 resetWindowTitleAndIconText();
835 if (lyxrc.open_buffers_in_tabs)
836 // Nothing more to do, the window should stay open.
839 if (guiApp->viewIds().size() > 1) {
845 // On Mac we also close the last window because the application stay
846 // resident in memory. On other platforms we don't close the last
847 // window because this would quit the application.
853 void GuiView::updateStatusBar()
855 // let the user see the explicit message
856 if (d.statusbar_timer_.isActive())
863 void GuiView::showMessage()
865 QString msg = toqstr(theGuiApp()->viewStatusMessage());
867 BufferView const * bv = currentBufferView();
869 msg = toqstr(bv->cursor().currentState());
871 msg = qt_("Welcome to LyX!");
873 statusBar()->showMessage(msg);
877 bool GuiView::event(QEvent * e)
881 // Useful debug code:
882 //case QEvent::ActivationChange:
883 //case QEvent::WindowDeactivate:
884 //case QEvent::Paint:
885 //case QEvent::Enter:
886 //case QEvent::Leave:
887 //case QEvent::HoverEnter:
888 //case QEvent::HoverLeave:
889 //case QEvent::HoverMove:
890 //case QEvent::StatusTip:
891 //case QEvent::DragEnter:
892 //case QEvent::DragLeave:
896 case QEvent::WindowActivate: {
897 GuiView * old_view = guiApp->currentView();
898 if (this == old_view) {
900 return QMainWindow::event(e);
902 if (old_view && old_view->currentBufferView()) {
903 // save current selection to the selection buffer to allow
904 // middle-button paste in this window.
905 cap::saveSelection(old_view->currentBufferView()->cursor());
907 guiApp->setCurrentView(this);
908 if (d.current_work_area_) {
909 BufferView & bv = d.current_work_area_->bufferView();
910 connectBufferView(bv);
911 connectBuffer(bv.buffer());
912 // The document structure, name and dialogs might have
913 // changed in another view.
915 // The document settings needs to be reinitialised.
916 updateDialog("document", "");
919 resetWindowTitleAndIconText();
922 return QMainWindow::event(e);
925 case QEvent::ShortcutOverride: {
928 #if (!defined Q_WS_X11) || (QT_VERSION >= 0x040500)
929 if (isFullScreen() && menuBar()->isHidden()) {
930 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
931 // FIXME: we should also try to detect special LyX shortcut such as
932 // Alt-P and Alt-M. Right now there is a hack in
933 // GuiWorkArea::processKeySym() that hides again the menubar for
935 if (ke->modifiers() & Qt::AltModifier && ke->key() != Qt::Key_Alt) {
937 return QMainWindow::event(e);
941 return QMainWindow::event(e);
945 return QMainWindow::event(e);
949 void GuiView::resetWindowTitleAndIconText()
951 setWindowTitle(qt_("LyX"));
952 setWindowIconText(qt_("LyX"));
955 bool GuiView::focusNextPrevChild(bool /*next*/)
962 void GuiView::setBusy(bool busy)
964 if (d.current_work_area_) {
965 d.current_work_area_->setUpdatesEnabled(!busy);
967 d.current_work_area_->stopBlinkingCursor();
969 d.current_work_area_->startBlinkingCursor();
973 QApplication::setOverrideCursor(Qt::WaitCursor);
975 QApplication::restoreOverrideCursor();
979 GuiWorkArea * GuiView::workArea(Buffer & buffer)
981 if (currentWorkArea()
982 && ¤tWorkArea()->bufferView().buffer() == &buffer)
983 return (GuiWorkArea *) currentWorkArea();
984 if (TabWorkArea * twa = d.currentTabWorkArea())
985 return twa->workArea(buffer);
990 GuiWorkArea * GuiView::addWorkArea(Buffer & buffer)
992 // Automatically create a TabWorkArea if there are none yet.
993 TabWorkArea * tab_widget = d.splitter_->count()
994 ? d.currentTabWorkArea() : addTabWorkArea();
995 return tab_widget->addWorkArea(buffer, *this);
999 TabWorkArea * GuiView::addTabWorkArea()
1001 TabWorkArea * twa = new TabWorkArea;
1002 QObject::connect(twa, SIGNAL(currentWorkAreaChanged(GuiWorkArea *)),
1003 this, SLOT(on_currentWorkAreaChanged(GuiWorkArea *)));
1004 QObject::connect(twa, SIGNAL(lastWorkAreaRemoved()),
1005 this, SLOT(on_lastWorkAreaRemoved()));
1007 d.splitter_->addWidget(twa);
1008 d.stack_widget_->setCurrentWidget(d.splitter_);
1013 GuiWorkArea const * GuiView::currentWorkArea() const
1015 return d.current_work_area_;
1019 GuiWorkArea * GuiView::currentWorkArea()
1021 return d.current_work_area_;
1025 GuiWorkArea const * GuiView::currentMainWorkArea() const
1027 if (d.currentTabWorkArea() == NULL)
1029 return d.currentTabWorkArea()->currentWorkArea();
1033 GuiWorkArea * GuiView::currentMainWorkArea()
1035 if (d.currentTabWorkArea() == NULL)
1037 return d.currentTabWorkArea()->currentWorkArea();
1041 void GuiView::setCurrentWorkArea(GuiWorkArea * wa)
1043 LYXERR(Debug::DEBUG, "Setting current wa: " << wa << endl);
1045 d.current_work_area_ = NULL;
1049 GuiWorkArea * old_gwa = theGuiApp()->currentView()->currentWorkArea();
1053 if (currentBufferView())
1054 cap::saveSelection(currentBufferView()->cursor());
1056 theGuiApp()->setCurrentView(this);
1057 d.current_work_area_ = wa;
1058 for (int i = 0; i != d.splitter_->count(); ++i) {
1059 if (d.tabWorkArea(i)->setCurrentWorkArea(wa)) {
1060 //if (d.current_main_work_area_)
1061 // d.current_main_work_area_->setFrameStyle(QFrame::NoFrame);
1062 d.current_main_work_area_ = wa;
1063 //d.current_main_work_area_->setFrameStyle(QFrame::Box | QFrame::Plain);
1064 //d.current_main_work_area_->setLineWidth(2);
1065 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() << ", Current main wa: " << currentMainWorkArea());
1069 LYXERR(Debug::DEBUG, "This is not a tabbed wa");
1070 on_currentWorkAreaChanged(wa);
1071 BufferView & bv = wa->bufferView();
1072 bv.cursor().fixIfBroken();
1074 wa->setUpdatesEnabled(true);
1075 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() << ", Current main wa: " << currentMainWorkArea());
1079 void GuiView::removeWorkArea(GuiWorkArea * wa)
1081 LASSERT(wa, return);
1082 if (wa == d.current_work_area_) {
1084 disconnectBufferView();
1085 d.current_work_area_ = 0;
1086 d.current_main_work_area_ = 0;
1089 bool found_twa = false;
1090 for (int i = 0; i != d.splitter_->count(); ++i) {
1091 TabWorkArea * twa = d.tabWorkArea(i);
1092 if (twa->removeWorkArea(wa)) {
1093 // Found in this tab group, and deleted the GuiWorkArea.
1095 if (twa->count() != 0) {
1096 if (d.current_work_area_ == 0)
1097 // This means that we are closing the current GuiWorkArea, so
1098 // switch to the next GuiWorkArea in the found TabWorkArea.
1099 setCurrentWorkArea(twa->currentWorkArea());
1101 // No more WorkAreas in this tab group, so delete it.
1108 // It is not a tabbed work area (i.e., the search work area), so it
1109 // should be deleted by other means.
1110 LASSERT(found_twa, /* */);
1112 if (d.current_work_area_ == 0) {
1113 if (d.splitter_->count() != 0) {
1114 TabWorkArea * twa = d.currentTabWorkArea();
1115 setCurrentWorkArea(twa->currentWorkArea());
1117 // No more work areas, switch to the background widget.
1118 setCurrentWorkArea(0);
1124 LayoutBox * GuiView::getLayoutDialog() const
1130 void GuiView::updateLayoutList()
1133 d.layout_->updateContents(false);
1137 void GuiView::updateToolbars()
1139 ToolbarMap::iterator end = d.toolbars_.end();
1140 if (d.current_work_area_) {
1142 d.current_work_area_->bufferView().cursor().inMathed();
1144 lyx::getStatus(FuncRequest(LFUN_LAYOUT_TABULAR)).enabled();
1146 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).enabled() &&
1147 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).onoff(true);
1148 bool const mathmacrotemplate =
1149 lyx::getStatus(FuncRequest(LFUN_IN_MATHMACROTEMPLATE)).enabled();
1151 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1152 it->second->update(math, table, review, mathmacrotemplate);
1154 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1155 it->second->update(false, false, false, false);
1159 void GuiView::setBuffer(Buffer * newBuffer)
1161 LYXERR(Debug::DEBUG, "Setting buffer: " << newBuffer << endl);
1162 LASSERT(newBuffer, return);
1165 GuiWorkArea * wa = workArea(*newBuffer);
1167 newBuffer->masterBuffer()->updateLabels();
1168 wa = addWorkArea(*newBuffer);
1170 //Disconnect the old buffer...there's no new one.
1173 connectBuffer(*newBuffer);
1174 connectBufferView(wa->bufferView());
1175 setCurrentWorkArea(wa);
1181 void GuiView::connectBuffer(Buffer & buf)
1183 buf.setGuiDelegate(this);
1187 void GuiView::disconnectBuffer()
1189 if (d.current_work_area_)
1190 d.current_work_area_->bufferView().buffer().setGuiDelegate(0);
1194 void GuiView::connectBufferView(BufferView & bv)
1196 bv.setGuiDelegate(this);
1200 void GuiView::disconnectBufferView()
1202 if (d.current_work_area_)
1203 d.current_work_area_->bufferView().setGuiDelegate(0);
1207 void GuiView::errors(string const & error_type, bool from_master)
1209 ErrorList & el = from_master ?
1210 documentBufferView()->buffer().masterBuffer()->errorList(error_type)
1211 : documentBufferView()->buffer().errorList(error_type);
1212 string data = error_type;
1214 data = "from_master|" + error_type;
1216 showDialog("errorlist", data);
1220 void GuiView::updateTocItem(string const & type, DocIterator const & dit)
1222 d.toc_models_.updateItem(toqstr(type), dit);
1226 void GuiView::structureChanged()
1228 d.toc_models_.reset(documentBufferView());
1229 // Navigator needs more than a simple update in this case. It needs to be
1231 updateDialog("toc", "");
1235 void GuiView::updateDialog(string const & name, string const & data)
1237 if (!isDialogVisible(name))
1240 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
1241 if (it == d.dialogs_.end())
1244 Dialog * const dialog = it->second.get();
1245 if (dialog->isVisibleView())
1246 dialog->initialiseParams(data);
1250 BufferView * GuiView::documentBufferView()
1252 return currentMainWorkArea()
1253 ? ¤tMainWorkArea()->bufferView()
1258 BufferView const * GuiView::documentBufferView() const
1260 return currentMainWorkArea()
1261 ? ¤tMainWorkArea()->bufferView()
1266 BufferView * GuiView::currentBufferView()
1268 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1272 BufferView const * GuiView::currentBufferView() const
1274 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1278 #if (QT_VERSION >= 0x040400)
1279 static docstring saveAndDestroyBuffer(Buffer * buffer, FileName const & fname)
1282 FileName const tmp_ret = FileName::tempName("lyxauto");
1283 if (!tmp_ret.empty()) {
1284 if (buffer->writeFile(tmp_ret))
1285 failed = !tmp_ret.moveTo(fname);
1288 // failed to write/rename tmp_ret so try writing direct
1289 failed = buffer->writeFile(fname);
1293 ? _("Automatic save failed!")
1294 : _("Automatic save done.");
1299 void GuiView::autoSave()
1301 LYXERR(Debug::INFO, "Running autoSave()");
1303 Buffer * buffer = documentBufferView()
1304 ? &documentBufferView()->buffer() : 0;
1308 #if (QT_VERSION >= 0x040400)
1309 QFuture<docstring> f = QtConcurrent::run(saveAndDestroyBuffer, buffer->clone(),
1310 buffer->getAutosaveFilename());
1311 d.autosave_watcher_.setFuture(f);
1318 void GuiView::resetAutosaveTimers()
1321 d.autosave_timeout_.restart();
1325 bool GuiView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1328 Buffer * buf = currentBufferView()
1329 ? ¤tBufferView()->buffer() : 0;
1330 Buffer * doc_buffer = documentBufferView()
1331 ? &(documentBufferView()->buffer()) : 0;
1333 // Check whether we need a buffer
1334 if (!lyxaction.funcHasFlag(cmd.action, LyXAction::NoBuffer) && !buf) {
1335 // no, exit directly
1336 flag.message(from_utf8(N_("Command not allowed with"
1337 "out any document open")));
1338 flag.setEnabled(false);
1342 if (cmd.origin == FuncRequest::TOC) {
1343 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
1345 if (toc->getStatus(documentBufferView()->cursor(), cmd, fs))
1348 flag.setEnabled(false);
1352 switch(cmd.action) {
1353 case LFUN_BUFFER_IMPORT:
1356 case LFUN_MASTER_BUFFER_UPDATE:
1357 case LFUN_MASTER_BUFFER_VIEW:
1358 enable = doc_buffer && doc_buffer->parent() != 0
1359 && !d.preview_watcher_.isRunning();
1362 case LFUN_BUFFER_UPDATE:
1363 case LFUN_BUFFER_VIEW: {
1364 if (!doc_buffer || d.preview_watcher_.isRunning()) {
1368 string format = to_utf8(cmd.argument());
1369 if (cmd.argument().empty())
1370 format = doc_buffer->getDefaultOutputFormat();
1371 enable = doc_buffer->isExportableFormat(format);
1375 case LFUN_BUFFER_RELOAD:
1376 enable = doc_buffer && !doc_buffer->isUnnamed()
1377 && doc_buffer->fileName().exists()
1378 && (!doc_buffer->isClean()
1379 || doc_buffer->isExternallyModified(Buffer::timestamp_method));
1382 case LFUN_BUFFER_CHILD_OPEN:
1383 enable = doc_buffer;
1386 case LFUN_BUFFER_WRITE:
1387 enable = doc_buffer && (doc_buffer->isUnnamed() || !doc_buffer->isClean());
1390 //FIXME: This LFUN should be moved to GuiApplication.
1391 case LFUN_BUFFER_WRITE_ALL: {
1392 // We enable the command only if there are some modified buffers
1393 Buffer * first = theBufferList().first();
1398 // We cannot use a for loop as the buffer list is a cycle.
1400 if (!b->isClean()) {
1404 b = theBufferList().next(b);
1405 } while (b != first);
1409 case LFUN_BUFFER_WRITE_AS:
1410 enable = doc_buffer;
1413 case LFUN_BUFFER_CLOSE:
1414 enable = doc_buffer;
1417 case LFUN_BUFFER_CLOSE_ALL:
1418 enable = theBufferList().last() != theBufferList().first();
1421 case LFUN_SPLIT_VIEW:
1422 if (cmd.getArg(0) == "vertical")
1423 enable = doc_buffer && (d.splitter_->count() == 1 ||
1424 d.splitter_->orientation() == Qt::Vertical);
1426 enable = doc_buffer && (d.splitter_->count() == 1 ||
1427 d.splitter_->orientation() == Qt::Horizontal);
1430 case LFUN_CLOSE_TAB_GROUP:
1431 enable = d.currentTabWorkArea();
1434 case LFUN_TOOLBAR_TOGGLE:
1435 if (GuiToolbar * t = toolbar(cmd.getArg(0)))
1436 flag.setOnOff(t->isVisible());
1439 case LFUN_DROP_LAYOUTS_CHOICE:
1443 case LFUN_UI_TOGGLE:
1444 flag.setOnOff(isFullScreen());
1447 case LFUN_DIALOG_DISCONNECT_INSET:
1450 case LFUN_DIALOG_HIDE:
1451 // FIXME: should we check if the dialog is shown?
1454 case LFUN_DIALOG_TOGGLE:
1455 flag.setOnOff(isDialogVisible(cmd.getArg(0)));
1456 // fall through to set "enable"
1457 case LFUN_DIALOG_SHOW: {
1458 string const name = cmd.getArg(0);
1460 enable = name == "aboutlyx"
1461 || name == "file" //FIXME: should be removed.
1463 || name == "texinfo"
1464 || name == "progress"
1465 || name == "compare";
1466 else if (name == "print")
1467 enable = doc_buffer->isExportable("dvi")
1468 && lyxrc.print_command != "none";
1469 else if (name == "character" || name == "symbols") {
1470 if (!buf || buf->isReadonly()
1471 || !currentBufferView()->cursor().inTexted())
1474 // FIXME we should consider passthru
1476 Inset const & in = currentBufferView()->cursor().inset();
1477 enable = !in.getLayout().isPassThru();
1480 else if (name == "latexlog")
1481 enable = FileName(doc_buffer->logName()).isReadableFile();
1482 else if (name == "spellchecker")
1483 enable = theSpellChecker() && !doc_buffer->isReadonly();
1484 else if (name == "vclog")
1485 enable = doc_buffer->lyxvc().inUse();
1489 case LFUN_DIALOG_UPDATE: {
1490 string const name = cmd.getArg(0);
1492 enable = name == "prefs";
1496 case LFUN_COMMAND_EXECUTE:
1498 case LFUN_MENU_OPEN:
1499 // Nothing to check.
1502 case LFUN_COMPLETION_INLINE:
1503 if (!d.current_work_area_
1504 || !d.current_work_area_->completer().inlinePossible(
1505 currentBufferView()->cursor()))
1509 case LFUN_COMPLETION_POPUP:
1510 if (!d.current_work_area_
1511 || !d.current_work_area_->completer().popupPossible(
1512 currentBufferView()->cursor()))
1516 case LFUN_COMPLETION_COMPLETE:
1517 if (!d.current_work_area_
1518 || !d.current_work_area_->completer().inlinePossible(
1519 currentBufferView()->cursor()))
1523 case LFUN_COMPLETION_ACCEPT:
1524 if (!d.current_work_area_
1525 || (!d.current_work_area_->completer().popupVisible()
1526 && !d.current_work_area_->completer().inlineVisible()
1527 && !d.current_work_area_->completer().completionAvailable()))
1531 case LFUN_COMPLETION_CANCEL:
1532 if (!d.current_work_area_
1533 || (!d.current_work_area_->completer().popupVisible()
1534 && !d.current_work_area_->completer().inlineVisible()))
1538 case LFUN_BUFFER_ZOOM_OUT:
1539 enable = doc_buffer && lyxrc.zoom > 10;
1542 case LFUN_BUFFER_ZOOM_IN:
1543 enable = doc_buffer;
1546 case LFUN_BUFFER_NEXT:
1547 case LFUN_BUFFER_PREVIOUS:
1548 // FIXME: should we check is there is an previous or next buffer?
1550 case LFUN_BUFFER_SWITCH:
1551 // toggle on the current buffer, but do not toggle off
1552 // the other ones (is that a good idea?)
1554 && to_utf8(cmd.argument()) == doc_buffer->absFileName())
1555 flag.setOnOff(true);
1558 case LFUN_VC_REGISTER:
1559 enable = doc_buffer && !doc_buffer->lyxvc().inUse();
1561 case LFUN_VC_CHECK_IN:
1562 enable = doc_buffer && doc_buffer->lyxvc().checkInEnabled();
1564 case LFUN_VC_CHECK_OUT:
1565 enable = doc_buffer && doc_buffer->lyxvc().checkOutEnabled();
1567 case LFUN_VC_LOCKING_TOGGLE:
1568 enable = doc_buffer && !doc_buffer->isReadonly()
1569 && doc_buffer->lyxvc().lockingToggleEnabled();
1570 flag.setOnOff(enable && !doc_buffer->lyxvc().locker().empty());
1572 case LFUN_VC_REVERT:
1573 enable = doc_buffer && doc_buffer->lyxvc().inUse();
1575 case LFUN_VC_UNDO_LAST:
1576 enable = doc_buffer && doc_buffer->lyxvc().undoLastEnabled();
1578 case LFUN_VC_REPO_UPDATE:
1579 enable = doc_buffer && doc_buffer->lyxvc().inUse();
1581 case LFUN_VC_COMMAND: {
1582 if (cmd.argument().empty())
1584 if (!doc_buffer && contains(cmd.getArg(0), 'D'))
1589 case LFUN_SERVER_GOTO_FILE_ROW:
1597 flag.setEnabled(false);
1603 static FileName selectTemplateFile()
1605 FileDialog dlg(qt_("Select template file"));
1606 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1607 dlg.setButton1(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
1609 FileDialog::Result result = dlg.open(toqstr(lyxrc.template_path),
1610 QStringList(qt_("LyX Documents (*.lyx)")));
1612 if (result.first == FileDialog::Later)
1614 if (result.second.isEmpty())
1616 return FileName(fromqstr(result.second));
1620 Buffer * GuiView::loadDocument(FileName const & filename, bool tolastfiles)
1624 Buffer * newBuffer = checkAndLoadLyXFile(filename);
1627 message(_("Document not loaded."));
1632 setBuffer(newBuffer);
1634 // scroll to the position when the file was last closed
1635 if (lyxrc.use_lastfilepos) {
1636 LastFilePosSection::FilePos filepos =
1637 theSession().lastFilePos().load(filename);
1638 documentBufferView()->moveToPosition(filepos.pit, filepos.pos, 0, 0);
1642 theSession().lastFiles().add(filename);
1649 void GuiView::openDocument(string const & fname)
1651 string initpath = lyxrc.document_path;
1653 if (documentBufferView()) {
1654 string const trypath = documentBufferView()->buffer().filePath();
1655 // If directory is writeable, use this as default.
1656 if (FileName(trypath).isDirWritable())
1662 if (fname.empty()) {
1663 FileDialog dlg(qt_("Select document to open"), LFUN_FILE_OPEN);
1664 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1665 dlg.setButton2(qt_("Examples|#E#e"),
1666 toqstr(addPath(package().system_support().absFilename(), "examples")));
1668 QStringList filter(qt_("LyX Documents (*.lyx)"));
1669 filter << qt_("LyX-1.3.x Documents (*.lyx13)")
1670 << qt_("LyX-1.4.x Documents (*.lyx14)")
1671 << qt_("LyX-1.5.x Documents (*.lyx15)")
1672 << qt_("LyX-1.6.x Documents (*.lyx16)");
1673 FileDialog::Result result =
1674 dlg.open(toqstr(initpath), filter);
1676 if (result.first == FileDialog::Later)
1679 filename = fromqstr(result.second);
1681 // check selected filename
1682 if (filename.empty()) {
1683 message(_("Canceled."));
1689 // get absolute path of file and add ".lyx" to the filename if
1691 FileName const fullname =
1692 fileSearch(string(), filename, "lyx", support::may_not_exist);
1693 if (!fullname.empty())
1694 filename = fullname.absFilename();
1696 if (!fullname.onlyPath().isDirectory()) {
1697 Alert::warning(_("Invalid filename"),
1698 bformat(_("The directory in the given path\n%1$s\ndoes not exist."),
1699 from_utf8(fullname.absFilename())));
1702 // if the file doesn't exist, let the user create one
1703 if (!fullname.exists()) {
1704 // the user specifically chose this name. Believe him.
1705 Buffer * const b = newFile(filename, string(), true);
1711 docstring const disp_fn = makeDisplayPath(filename);
1712 message(bformat(_("Opening document %1$s..."), disp_fn));
1715 Buffer * buf = loadDocument(fullname);
1717 buf->updateLabels();
1719 buf->errors("Parse");
1720 str2 = bformat(_("Document %1$s opened."), disp_fn);
1721 if (buf->lyxvc().inUse())
1722 str2 += " " + from_utf8(buf->lyxvc().versionString()) +
1723 " " + _("Version control detected.");
1725 str2 = bformat(_("Could not open document %1$s"), disp_fn);
1730 // FIXME: clean that
1731 static bool import(GuiView * lv, FileName const & filename,
1732 string const & format, ErrorList & errorList)
1734 FileName const lyxfile(support::changeExtension(filename.absFilename(), ".lyx"));
1736 string loader_format;
1737 vector<string> loaders = theConverters().loaders();
1738 if (find(loaders.begin(), loaders.end(), format) == loaders.end()) {
1739 for (vector<string>::const_iterator it = loaders.begin();
1740 it != loaders.end(); ++it) {
1741 if (!theConverters().isReachable(format, *it))
1744 string const tofile =
1745 support::changeExtension(filename.absFilename(),
1746 formats.extension(*it));
1747 if (!theConverters().convert(0, filename, FileName(tofile),
1748 filename, format, *it, errorList))
1750 loader_format = *it;
1753 if (loader_format.empty()) {
1754 frontend::Alert::error(_("Couldn't import file"),
1755 bformat(_("No information for importing the format %1$s."),
1756 formats.prettyName(format)));
1760 loader_format = format;
1762 if (loader_format == "lyx") {
1763 Buffer * buf = lv->loadDocument(lyxfile);
1766 buf->updateLabels();
1768 buf->errors("Parse");
1770 Buffer * const b = newFile(lyxfile.absFilename(), string(), true);
1774 bool as_paragraphs = loader_format == "textparagraph";
1775 string filename2 = (loader_format == format) ? filename.absFilename()
1776 : support::changeExtension(filename.absFilename(),
1777 formats.extension(loader_format));
1778 lv->currentBufferView()->insertPlaintextFile(FileName(filename2),
1780 guiApp->setCurrentView(lv);
1781 lyx::dispatch(FuncRequest(LFUN_MARK_OFF));
1788 void GuiView::importDocument(string const & argument)
1791 string filename = split(argument, format, ' ');
1793 LYXERR(Debug::INFO, format << " file: " << filename);
1795 // need user interaction
1796 if (filename.empty()) {
1797 string initpath = lyxrc.document_path;
1798 if (documentBufferView()) {
1799 string const trypath = documentBufferView()->buffer().filePath();
1800 // If directory is writeable, use this as default.
1801 if (FileName(trypath).isDirWritable())
1805 docstring const text = bformat(_("Select %1$s file to import"),
1806 formats.prettyName(format));
1808 FileDialog dlg(toqstr(text), LFUN_BUFFER_IMPORT);
1809 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1810 dlg.setButton2(qt_("Examples|#E#e"),
1811 toqstr(addPath(package().system_support().absFilename(), "examples")));
1813 docstring filter = formats.prettyName(format);
1816 filter += from_utf8(formats.extension(format));
1819 FileDialog::Result result =
1820 dlg.open(toqstr(initpath), fileFilters(toqstr(filter)));
1822 if (result.first == FileDialog::Later)
1825 filename = fromqstr(result.second);
1827 // check selected filename
1828 if (filename.empty())
1829 message(_("Canceled."));
1832 if (filename.empty())
1835 // get absolute path of file
1836 FileName const fullname(support::makeAbsPath(filename));
1838 FileName const lyxfile(support::changeExtension(fullname.absFilename(), ".lyx"));
1840 // Check if the document already is open
1841 Buffer * buf = theBufferList().getBuffer(lyxfile);
1844 if (!closeBuffer()) {
1845 message(_("Canceled."));
1850 docstring const displaypath = makeDisplayPath(lyxfile.absFilename(), 30);
1852 // if the file exists already, and we didn't do
1853 // -i lyx thefile.lyx, warn
1854 if (lyxfile.exists() && fullname != lyxfile) {
1856 docstring text = bformat(_("The document %1$s already exists.\n\n"
1857 "Do you want to overwrite that document?"), displaypath);
1858 int const ret = Alert::prompt(_("Overwrite document?"),
1859 text, 0, 1, _("&Overwrite"), _("&Cancel"));
1862 message(_("Canceled."));
1867 message(bformat(_("Importing %1$s..."), displaypath));
1868 ErrorList errorList;
1869 if (import(this, fullname, format, errorList))
1870 message(_("imported."));
1872 message(_("file not imported!"));
1874 // FIXME (Abdel 12/08/06): Is there a need to display the error list here?
1878 void GuiView::newDocument(string const & filename, bool from_template)
1880 FileName initpath(lyxrc.document_path);
1881 if (documentBufferView()) {
1882 FileName const trypath(documentBufferView()->buffer().filePath());
1883 // If directory is writeable, use this as default.
1884 if (trypath.isDirWritable())
1888 string templatefile;
1889 if (from_template) {
1890 templatefile = selectTemplateFile().absFilename();
1891 if (templatefile.empty())
1896 if (filename.empty())
1897 b = newUnnamedFile(initpath, to_utf8(_("newfile")), templatefile);
1899 b = newFile(filename, templatefile, true);
1904 // If no new document could be created, it is unsure
1905 // whether there is a valid BufferView.
1906 if (currentBufferView())
1907 // Ensure the cursor is correctly positioned on screen.
1908 currentBufferView()->showCursor();
1912 void GuiView::insertLyXFile(docstring const & fname)
1914 BufferView * bv = documentBufferView();
1919 FileName filename(to_utf8(fname));
1921 if (!filename.empty()) {
1922 bv->insertLyXFile(filename);
1926 // Launch a file browser
1928 string initpath = lyxrc.document_path;
1929 string const trypath = bv->buffer().filePath();
1930 // If directory is writeable, use this as default.
1931 if (FileName(trypath).isDirWritable())
1935 FileDialog dlg(qt_("Select LyX document to insert"), LFUN_FILE_INSERT);
1936 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1937 dlg.setButton2(qt_("Examples|#E#e"),
1938 toqstr(addPath(package().system_support().absFilename(),
1941 FileDialog::Result result = dlg.open(toqstr(initpath),
1942 QStringList(qt_("LyX Documents (*.lyx)")));
1944 if (result.first == FileDialog::Later)
1948 filename.set(fromqstr(result.second));
1950 // check selected filename
1951 if (filename.empty()) {
1952 // emit message signal.
1953 message(_("Canceled."));
1957 bv->insertLyXFile(filename);
1961 void GuiView::insertPlaintextFile(docstring const & fname,
1964 BufferView * bv = documentBufferView();
1968 if (!fname.empty() && !FileName::isAbsolute(to_utf8(fname))) {
1969 message(_("Absolute filename expected."));
1974 FileName filename(to_utf8(fname));
1976 if (!filename.empty()) {
1977 bv->insertPlaintextFile(filename, asParagraph);
1981 FileDialog dlg(qt_("Select file to insert"), (asParagraph ?
1982 LFUN_FILE_INSERT_PLAINTEXT_PARA : LFUN_FILE_INSERT_PLAINTEXT));
1984 FileDialog::Result result = dlg.open(toqstr(bv->buffer().filePath()),
1985 QStringList(qt_("All Files (*)")));
1987 if (result.first == FileDialog::Later)
1991 filename.set(fromqstr(result.second));
1993 // check selected filename
1994 if (filename.empty()) {
1995 // emit message signal.
1996 message(_("Canceled."));
2000 bv->insertPlaintextFile(filename, asParagraph);
2004 bool GuiView::renameBuffer(Buffer & b, docstring const & newname)
2006 FileName fname = b.fileName();
2007 FileName const oldname = fname;
2009 if (!newname.empty()) {
2011 fname = support::makeAbsPath(to_utf8(newname), oldname.onlyPath().absFilename());
2013 // Switch to this Buffer.
2016 // No argument? Ask user through dialog.
2018 FileDialog dlg(qt_("Choose a filename to save document as"),
2019 LFUN_BUFFER_WRITE_AS);
2020 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2021 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
2023 if (!isLyXFilename(fname.absFilename()))
2024 fname.changeExtension(".lyx");
2026 FileDialog::Result result =
2027 dlg.save(toqstr(fname.onlyPath().absFilename()),
2028 QStringList(qt_("LyX Documents (*.lyx)")),
2029 toqstr(fname.onlyFileName()));
2031 if (result.first == FileDialog::Later)
2034 fname.set(fromqstr(result.second));
2039 if (!isLyXFilename(fname.absFilename()))
2040 fname.changeExtension(".lyx");
2043 if (FileName(fname).exists()) {
2044 docstring const file = makeDisplayPath(fname.absFilename(), 30);
2045 docstring text = bformat(_("The document %1$s already "
2046 "exists.\n\nDo you want to "
2047 "overwrite that document?"),
2049 int const ret = Alert::prompt(_("Overwrite document?"),
2050 text, 0, 2, _("&Overwrite"), _("&Rename"), _("&Cancel"));
2053 case 1: return renameBuffer(b, docstring());
2054 case 2: return false;
2058 FileName oldauto = b.getAutosaveFilename();
2060 // Ok, change the name of the buffer
2061 b.setFileName(fname.absFilename());
2063 bool unnamed = b.isUnnamed();
2064 b.setUnnamed(false);
2065 b.saveCheckSum(fname);
2067 // bring the autosave file with us, just in case.
2068 b.moveAutosaveFile(oldauto);
2070 if (!saveBuffer(b)) {
2071 oldauto = b.getAutosaveFilename();
2072 b.setFileName(oldname.absFilename());
2073 b.setUnnamed(unnamed);
2074 b.saveCheckSum(oldname);
2075 b.moveAutosaveFile(oldauto);
2083 bool GuiView::saveBuffer(Buffer & b)
2085 if (workArea(b) && workArea(b)->inDialogMode())
2089 return renameBuffer(b, docstring());
2092 theSession().lastFiles().add(b.fileName());
2096 // Switch to this Buffer.
2099 // FIXME: we don't tell the user *WHY* the save failed !!
2100 docstring const file = makeDisplayPath(b.absFileName(), 30);
2101 docstring text = bformat(_("The document %1$s could not be saved.\n\n"
2102 "Do you want to rename the document and "
2103 "try again?"), file);
2104 int const ret = Alert::prompt(_("Rename and save?"),
2105 text, 0, 2, _("&Rename"), _("&Retry"), _("&Cancel"));
2108 if (!renameBuffer(b, docstring()))
2117 return saveBuffer(b);
2121 bool GuiView::hideWorkArea(GuiWorkArea * wa)
2123 return closeWorkArea(wa, false);
2127 bool GuiView::closeWorkArea(GuiWorkArea * wa)
2129 Buffer & buf = wa->bufferView().buffer();
2130 return closeWorkArea(wa, !buf.parent());
2134 bool GuiView::closeBuffer()
2136 GuiWorkArea * wa = currentMainWorkArea();
2137 setCurrentWorkArea(wa);
2138 Buffer & buf = wa->bufferView().buffer();
2139 return wa && closeWorkArea(wa, !buf.parent());
2143 void GuiView::writeSession() const {
2144 GuiWorkArea const * active_wa = currentMainWorkArea();
2145 for (int i = 0; i < d.splitter_->count(); ++i) {
2146 TabWorkArea * twa = d.tabWorkArea(i);
2147 for (int j = 0; j < twa->count(); ++j) {
2148 GuiWorkArea * wa = static_cast<GuiWorkArea *>(twa->widget(j));
2149 Buffer & buf = wa->bufferView().buffer();
2150 theSession().lastOpened().add(buf.fileName(), wa == active_wa);
2156 bool GuiView::closeBufferAll()
2158 // Close the workareas in all other views
2159 QList<int> const ids = guiApp->viewIds();
2160 for (int i = 0; i != ids.size(); ++i) {
2161 if (id_ != ids[i] && !guiApp->view(ids[i]).closeWorkAreaAll())
2165 // Close our own workareas
2166 if (!closeWorkAreaAll())
2169 // Now close the hidden buffers. We prevent hidden buffers from being
2170 // dirty, so we can just close them.
2171 theBufferList().closeAll();
2176 bool GuiView::closeWorkAreaAll()
2178 setCurrentWorkArea(currentMainWorkArea());
2180 // We might be in a situation that there is still a tabWorkArea, but
2181 // there are no tabs anymore. This can happen when we get here after a
2182 // TabWorkArea::lastWorkAreaRemoved() signal. Therefore we count how
2183 // many TabWorkArea's have no documents anymore.
2186 // We have to call count() each time, because it can happen that
2187 // more than one splitter will disappear in one iteration (bug 5998).
2188 for (; d.splitter_->count() > empty_twa; ) {
2189 TabWorkArea * twa = d.tabWorkArea(empty_twa);
2191 if (twa->count() == 0)
2194 setCurrentWorkArea(twa->currentWorkArea());
2195 if (!closeTabWorkArea(twa))
2203 bool GuiView::closeWorkArea(GuiWorkArea * wa, bool close_buffer)
2208 Buffer & buf = wa->bufferView().buffer();
2211 return closeBuffer(buf);
2213 if (!inMultiTabs(wa))
2214 if (!saveBufferIfNeeded(buf, true))
2222 bool GuiView::closeBuffer(Buffer & buf)
2224 // If we are in a close_event all children will be closed in some time,
2225 // so no need to do it here. This will ensure that the children end up
2226 // in the session file in the correct order. If we close the master
2227 // buffer, we can close or release the child buffers here too.
2229 vector<Buffer *> clist = buf.getChildren(false);
2230 for (vector<Buffer *>::const_iterator it = clist.begin();
2231 it != clist.end(); ++it) {
2232 // If a child is dirty, do not close
2233 // without user intervention
2234 //FIXME: should we look in other tabworkareas?
2235 Buffer * child_buf = *it;
2236 GuiWorkArea * child_wa = workArea(*child_buf);
2238 if (!closeWorkArea(child_wa, true))
2241 theBufferList().releaseChild(&buf, child_buf);
2244 // goto bookmark to update bookmark pit.
2245 //FIXME: we should update only the bookmarks related to this buffer!
2246 LYXERR(Debug::DEBUG, "GuiView::closeBuffer()");
2247 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
2248 theLyXFunc().gotoBookmark(i+1, false, false);
2250 if (saveBufferIfNeeded(buf, false)) {
2251 theBufferList().release(&buf);
2258 bool GuiView::closeTabWorkArea(TabWorkArea * twa)
2260 while (twa == d.currentTabWorkArea()) {
2261 twa->setCurrentIndex(twa->count()-1);
2263 GuiWorkArea * wa = twa->currentWorkArea();
2264 Buffer & b = wa->bufferView().buffer();
2266 // We only want to close the buffer if the same buffer is not visible
2267 // in another view, and if this is not a child and if we are closing
2268 // a view (not a tabgroup).
2269 bool const close_buffer =
2270 !inMultiViews(wa) && !b.parent() && closing_;
2272 if (!closeWorkArea(wa, close_buffer))
2279 bool GuiView::saveBufferIfNeeded(Buffer & buf, bool hiding)
2281 if (buf.isClean() || buf.paragraphs().empty())
2284 // Switch to this Buffer.
2289 if (buf.isUnnamed())
2290 file = from_utf8(buf.fileName().onlyFileName());
2292 file = buf.fileName().displayName(30);
2294 // Bring this window to top before asking questions.
2299 if (hiding && buf.isUnnamed()) {
2300 docstring const text = bformat(_("The document %1$s has not been "
2301 "saved yet.\n\nDo you want to save "
2302 "the document?"), file);
2303 ret = Alert::prompt(_("Save new document?"),
2304 text, 0, 1, _("&Save"), _("&Cancel"));
2308 docstring const text = bformat(_("The document %1$s has unsaved changes."
2309 "\n\nDo you want to save the document or discard the changes?"), file);
2310 ret = Alert::prompt(_("Save changed document?"),
2311 text, 0, 2, _("&Save"), _("&Discard"), _("&Cancel"));
2316 if (!saveBuffer(buf))
2320 // if we crash after this we could
2321 // have no autosave file but I guess
2322 // this is really improbable (Jug)
2323 buf.removeAutosaveFile();
2325 // revert all changes
2336 bool GuiView::inMultiTabs(GuiWorkArea * wa)
2338 Buffer & buf = wa->bufferView().buffer();
2340 for (int i = 0; i != d.splitter_->count(); ++i) {
2341 GuiWorkArea * wa_ = d.tabWorkArea(i)->workArea(buf);
2342 if (wa_ && wa_ != wa)
2345 return inMultiViews(wa);
2349 bool GuiView::inMultiViews(GuiWorkArea * wa)
2351 QList<int> const ids = guiApp->viewIds();
2352 Buffer & buf = wa->bufferView().buffer();
2355 for (int i = 0; i != ids.size() && found_twa <= 1; ++i) {
2359 if (guiApp->view(ids[i]).workArea(buf))
2366 void GuiView::gotoNextOrPreviousBuffer(NextOrPrevious np)
2368 Buffer * const curbuf = documentBufferView()
2369 ? &documentBufferView()->buffer() : 0;
2370 Buffer * nextbuf = curbuf;
2372 if (np == NEXTBUFFER)
2373 nextbuf = theBufferList().next(nextbuf);
2375 nextbuf = theBufferList().previous(nextbuf);
2376 if (nextbuf == curbuf)
2382 if (workArea(*nextbuf))
2389 /// make sure the document is saved
2390 static bool ensureBufferClean(Buffer * buffer)
2392 LASSERT(buffer, return false);
2393 if (buffer->isClean() && !buffer->isUnnamed())
2396 docstring const file = buffer->fileName().displayName(30);
2399 if (!buffer->isUnnamed()) {
2400 text = bformat(_("The document %1$s has unsaved "
2401 "changes.\n\nDo you want to save "
2402 "the document?"), file);
2403 title = _("Save changed document?");
2406 text = bformat(_("The document %1$s has not been "
2407 "saved yet.\n\nDo you want to save "
2408 "the document?"), file);
2409 title = _("Save new document?");
2411 int const ret = Alert::prompt(title, text, 0, 1, _("&Save"), _("&Cancel"));
2414 dispatch(FuncRequest(LFUN_BUFFER_WRITE));
2416 return buffer->isClean() && !buffer->isUnnamed();
2420 void GuiView::reloadBuffer()
2422 Buffer * buf = &documentBufferView()->buffer();
2427 void GuiView::checkExternallyModifiedBuffers()
2429 BufferList::iterator bit = theBufferList().begin();
2430 BufferList::iterator const bend = theBufferList().end();
2431 for (; bit != bend; ++bit) {
2432 if ((*bit)->fileName().exists()
2433 && (*bit)->isExternallyModified(Buffer::checksum_method)) {
2434 docstring text = bformat(_("Document \n%1$s\n has been externally modified."
2435 " Reload now? Any local changes will be lost."),
2436 from_utf8((*bit)->absFileName()));
2437 int const ret = Alert::prompt(_("Reload externally changed document?"),
2438 text, 0, 1, _("&Reload"), _("&Cancel"));
2446 void GuiView::dispatchVC(FuncRequest const & cmd)
2448 // message for statusbar
2450 Buffer * buffer = documentBufferView()
2451 ? &(documentBufferView()->buffer()) : 0;
2453 switch (cmd.action) {
2454 case LFUN_VC_REGISTER:
2455 if (!buffer || !ensureBufferClean(buffer))
2457 if (!buffer->lyxvc().inUse()) {
2458 if (buffer->lyxvc().registrer())
2463 case LFUN_VC_CHECK_IN:
2464 if (!buffer || !ensureBufferClean(buffer))
2466 if (buffer->lyxvc().inUse() && !buffer->isReadonly()) {
2467 msg = buffer->lyxvc().checkIn();
2473 case LFUN_VC_CHECK_OUT:
2474 if (!buffer || !ensureBufferClean(buffer))
2476 if (buffer->lyxvc().inUse()) {
2477 msg = buffer->lyxvc().checkOut();
2482 case LFUN_VC_LOCKING_TOGGLE:
2483 LASSERT(buffer, return);
2484 if (!ensureBufferClean(buffer) || buffer->isReadonly())
2486 if (buffer->lyxvc().inUse()) {
2487 string res = buffer->lyxvc().lockingToggle();
2489 frontend::Alert::error(_("Revision control error."),
2490 _("Error when setting the locking property."));
2498 case LFUN_VC_REVERT:
2499 LASSERT(buffer, return);
2500 buffer->lyxvc().revert();
2504 case LFUN_VC_UNDO_LAST:
2505 LASSERT(buffer, return);
2506 buffer->lyxvc().undoLast();
2510 case LFUN_VC_REPO_UPDATE:
2511 LASSERT(buffer, return);
2512 if (ensureBufferClean(buffer)) {
2513 msg = buffer->lyxvc().repoUpdate();
2514 checkExternallyModifiedBuffers();
2518 case LFUN_VC_COMMAND: {
2519 string flag = cmd.getArg(0);
2520 if (buffer && contains(flag, 'R') && !ensureBufferClean(buffer))
2523 if (contains(flag, 'M')) {
2524 if (!Alert::askForText(message, _("LyX VC: Log Message")))
2527 string path = cmd.getArg(1);
2528 if (contains(path, "$$p") && buffer)
2529 path = subst(path, "$$p", buffer->filePath());
2530 LYXERR(Debug::LYXVC, "Directory: " << path);
2532 if (!pp.isReadableDirectory()) {
2533 lyxerr << _("Directory is not accessible.") << endl;
2536 support::PathChanger p(pp);
2538 string command = cmd.getArg(2);
2539 if (command.empty())
2542 command = subst(command, "$$i", buffer->absFileName());
2543 command = subst(command, "$$p", buffer->filePath());
2545 command = subst(command, "$$m", to_utf8(message));
2546 LYXERR(Debug::LYXVC, "Command: " << command);
2548 one.startscript(Systemcall::Wait, command);
2552 if (contains(flag, 'I'))
2553 buffer->markDirty();
2554 if (contains(flag, 'R'))
2564 message(from_utf8(msg));
2568 void GuiView::openChildDocument(string const & fname)
2570 LASSERT(documentBufferView(), return);
2571 Buffer & buffer = documentBufferView()->buffer();
2572 FileName const filename = support::makeAbsPath(fname, buffer.filePath());
2573 documentBufferView()->saveBookmark(false);
2575 bool parsed = false;
2576 if (theBufferList().exists(filename)) {
2577 child = theBufferList().getBuffer(filename);
2579 message(bformat(_("Opening child document %1$s..."),
2580 makeDisplayPath(filename.absFilename())));
2581 child = loadDocument(filename, false);
2587 // Set the parent name of the child document.
2588 // This makes insertion of citations and references in the child work,
2589 // when the target is in the parent or another child document.
2590 child->setParent(&buffer);
2591 child->masterBuffer()->updateLabels();
2594 child->errors("Parse");
2598 bool GuiView::goToFileRow(string const & argument)
2602 size_t i = argument.find_last_of(' ');
2603 if (i != string::npos) {
2604 file_name = os::internal_path(trim(argument.substr(0, i)));
2605 istringstream is(argument.substr(i + 1));
2610 if (i == string::npos) {
2611 LYXERR0("Wrong argument: " << argument);
2615 string const abstmp = package().temp_dir().absFilename();
2616 string const realtmp = package().temp_dir().realPath();
2617 // We have to use os::path_prefix_is() here, instead of
2618 // simply prefixIs(), because the file name comes from
2619 // an external application and may need case adjustment.
2620 if (os::path_prefix_is(file_name, abstmp, os::CASE_ADJUSTED)
2621 || os::path_prefix_is(file_name, realtmp, os::CASE_ADJUSTED)) {
2622 // Needed by inverse dvi search. If it is a file
2623 // in tmpdir, call the apropriated function.
2624 // If tmpdir is a symlink, we may have the real
2625 // path passed back, so we correct for that.
2626 if (!prefixIs(file_name, abstmp))
2627 file_name = subst(file_name, realtmp, abstmp);
2628 buf = theBufferList().getBufferFromTmp(file_name);
2630 // Must replace extension of the file to be .lyx
2631 // and get full path
2632 FileName const s = fileSearch(string(),
2633 support::changeExtension(file_name, ".lyx"), "lyx");
2634 // Either change buffer or load the file
2635 if (theBufferList().exists(s))
2636 buf = theBufferList().getBuffer(s);
2637 else if (s.exists()) {
2638 buf = loadDocument(s);
2639 buf->updateLabels();
2640 buf->errors("Parse");
2643 _("File does not exist: %1$s"),
2644 makeDisplayPath(file_name)));
2649 documentBufferView()->setCursorFromRow(row);
2654 #if (QT_VERSION >= 0x040400)
2655 static docstring exportAndDestroy(Buffer * buffer, string const & format)
2657 bool const update_unincluded =
2658 buffer->params().maintain_unincluded_children
2659 && !buffer->params().getIncludedChildren().empty();
2660 bool const success = buffer->doExport(format, true, update_unincluded);
2663 ? bformat(_("Successful export to format: %1$s"), from_utf8(format))
2664 : bformat(_("Error exporting to format: %1$s"), from_utf8(format));
2668 static docstring previewAndDestroy(Buffer * buffer, string const & format)
2670 bool const update_unincluded =
2671 buffer->params().maintain_unincluded_children
2672 && !buffer->params().getIncludedChildren().empty();
2673 bool const success = buffer->preview(format, update_unincluded);
2676 ? bformat(_("Successful preview of format: %1$s"), from_utf8(format))
2677 : bformat(_("Error previewing format: %1$s"), from_utf8(format));
2682 bool GuiView::dispatch(FuncRequest const & cmd)
2684 BufferView * bv = currentBufferView();
2685 // By default we won't need any update.
2687 bv->cursor().updateFlags(Update::None);
2689 Buffer * doc_buffer = documentBufferView()
2690 ? &(documentBufferView()->buffer()) : 0;
2692 bool dispatched = true;
2694 if (cmd.origin == FuncRequest::TOC) {
2695 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
2696 toc->doDispatch(bv->cursor(), cmd);
2700 string const argument = to_utf8(cmd.argument());
2702 switch(cmd.action) {
2703 case LFUN_BUFFER_CHILD_OPEN:
2704 openChildDocument(to_utf8(cmd.argument()));
2707 case LFUN_BUFFER_IMPORT:
2708 importDocument(to_utf8(cmd.argument()));
2711 case LFUN_BUFFER_EXPORT: {
2714 if (cmd.argument() == "custom") {
2715 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "sendto"));
2718 if (doc_buffer->doExport(argument, false)) {
2719 message(bformat(_("Error exporting to format: %1$s."),
2725 case LFUN_BUFFER_UPDATE: {
2728 string format = argument;
2729 if (argument.empty())
2730 format = doc_buffer->getDefaultOutputFormat();
2731 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
2732 d.progress_->clearMessages();
2733 message(_("Exporting ..."));
2734 QFuture<docstring> f = QtConcurrent::run(exportAndDestroy,
2735 doc_buffer->clone(), format);
2736 d.setPreviewFuture(f);
2738 bool const update_unincluded =
2739 doc_buffer->params().maintain_unincluded_children
2740 && !doc_buffer->params().getIncludedChildren().empty();
2741 doc_buffer->doExport(format, true, update_unincluded);
2745 case LFUN_BUFFER_VIEW: {
2748 string format = argument;
2749 if (argument.empty())
2750 format = doc_buffer->getDefaultOutputFormat();
2751 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
2752 d.progress_->clearMessages();
2753 message(_("Previewing ..."));
2754 QFuture<docstring> f = QtConcurrent::run(previewAndDestroy,
2755 doc_buffer->clone(), format);
2756 d.setPreviewFuture(f);
2758 bool const update_unincluded =
2759 doc_buffer->params().maintain_unincluded_children
2760 && !doc_buffer->params().getIncludedChildren().empty();
2761 doc_buffer->preview(format, update_unincluded);
2765 case LFUN_MASTER_BUFFER_UPDATE: {
2768 string format = argument;
2769 Buffer const * master = doc_buffer->masterBuffer();
2770 if (argument.empty())
2771 format = master->getDefaultOutputFormat();
2772 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
2773 QFuture<docstring> f = QtConcurrent::run(exportAndDestroy,
2774 master->clone(), format);
2775 d.setPreviewFuture(f);
2777 bool const update_unincluded =
2778 master->params().maintain_unincluded_children
2779 && !master->params().getIncludedChildren().empty();
2780 master->doExport(format, true);
2784 case LFUN_MASTER_BUFFER_VIEW: {
2785 string format = argument;
2786 Buffer const * master = doc_buffer->masterBuffer();
2787 if (argument.empty())
2788 format = master->getDefaultOutputFormat();
2789 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
2790 QFuture<docstring> f = QtConcurrent::run(previewAndDestroy,
2791 master->clone(), format);
2792 d.setPreviewFuture(f);
2794 master->preview(format);
2798 case LFUN_BUFFER_SWITCH:
2799 if (FileName::isAbsolute(to_utf8(cmd.argument()))) {
2801 theBufferList().getBuffer(FileName(to_utf8(cmd.argument())));
2805 message(_("Document not loaded"));
2809 case LFUN_BUFFER_NEXT:
2810 gotoNextOrPreviousBuffer(NEXTBUFFER);
2813 case LFUN_BUFFER_PREVIOUS:
2814 gotoNextOrPreviousBuffer(PREVBUFFER);
2817 case LFUN_COMMAND_EXECUTE: {
2818 bool const show_it = cmd.argument() != "off";
2819 // FIXME: this is a hack, "minibuffer" should not be
2821 if (GuiToolbar * t = toolbar("minibuffer")) {
2822 t->setVisible(show_it);
2823 if (show_it && t->commandBuffer())
2824 t->commandBuffer()->setFocus();
2828 case LFUN_DROP_LAYOUTS_CHOICE:
2829 d.layout_->showPopup();
2832 case LFUN_MENU_OPEN:
2833 if (QMenu * menu = guiApp->menus().menu(toqstr(cmd.argument()), *this))
2834 menu->exec(QCursor::pos());
2837 case LFUN_FILE_INSERT:
2838 insertLyXFile(cmd.argument());
2840 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
2841 insertPlaintextFile(cmd.argument(), true);
2844 case LFUN_FILE_INSERT_PLAINTEXT:
2845 insertPlaintextFile(cmd.argument(), false);
2848 case LFUN_BUFFER_RELOAD: {
2849 LASSERT(doc_buffer, break);
2850 docstring const file = makeDisplayPath(doc_buffer->absFileName(), 20);
2851 docstring text = bformat(_("Any changes will be lost. Are you sure "
2852 "you want to revert to the saved version of the document %1$s?"), file);
2853 int const ret = Alert::prompt(_("Revert to saved document?"),
2854 text, 1, 1, _("&Revert"), _("&Cancel"));
2857 doc_buffer->markClean();
2863 case LFUN_BUFFER_WRITE:
2864 LASSERT(doc_buffer, break);
2865 saveBuffer(*doc_buffer);
2868 case LFUN_BUFFER_WRITE_AS:
2869 LASSERT(doc_buffer, break);
2870 renameBuffer(*doc_buffer, cmd.argument());
2873 case LFUN_BUFFER_WRITE_ALL: {
2874 Buffer * first = theBufferList().first();
2877 message(_("Saving all documents..."));
2878 // We cannot use a for loop as the buffer list cycles.
2881 if (!b->isClean()) {
2883 LYXERR(Debug::ACTION, "Saved " << b->absFileName());
2885 b = theBufferList().next(b);
2886 } while (b != first);
2887 message(_("All documents saved."));
2891 case LFUN_BUFFER_CLOSE:
2895 case LFUN_BUFFER_CLOSE_ALL:
2899 case LFUN_TOOLBAR_TOGGLE: {
2900 string const name = cmd.getArg(0);
2901 if (GuiToolbar * t = toolbar(name))
2906 case LFUN_DIALOG_UPDATE: {
2907 string const name = to_utf8(cmd.argument());
2908 if (currentBufferView()) {
2909 Inset * inset = currentBufferView()->editedInset(name);
2910 // Can only update a dialog connected to an existing inset
2913 // FIXME: get rid of this indirection; GuiView ask the inset
2914 // if he is kind enough to update itself...
2915 FuncRequest fr(LFUN_INSET_DIALOG_UPDATE, cmd.argument());
2916 inset->dispatch(currentBufferView()->cursor(), fr);
2917 } else if (name == "paragraph") {
2918 lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
2919 } else if (name == "prefs" || name == "document") {
2920 updateDialog(name, string());
2925 case LFUN_DIALOG_TOGGLE: {
2926 if (isDialogVisible(cmd.getArg(0)))
2927 dispatch(FuncRequest(LFUN_DIALOG_HIDE, cmd.argument()));
2929 dispatch(FuncRequest(LFUN_DIALOG_SHOW, cmd.argument()));
2933 case LFUN_DIALOG_DISCONNECT_INSET:
2934 disconnectDialog(to_utf8(cmd.argument()));
2937 case LFUN_DIALOG_HIDE: {
2938 guiApp->hideDialogs(to_utf8(cmd.argument()), 0);
2942 case LFUN_DIALOG_SHOW: {
2943 string const name = cmd.getArg(0);
2944 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
2946 if (name == "character") {
2947 data = freefont2string();
2949 showDialog("character", data);
2950 } else if (name == "latexlog") {
2951 Buffer::LogType type;
2952 string const logfile = doc_buffer->logName(&type);
2954 case Buffer::latexlog:
2957 case Buffer::buildlog:
2961 data += Lexer::quoteString(logfile);
2962 showDialog("log", data);
2963 } else if (name == "vclog") {
2964 string const data = "vc " +
2965 Lexer::quoteString(doc_buffer->lyxvc().getLogFile());
2966 showDialog("log", data);
2967 } else if (name == "symbols") {
2968 data = bv->cursor().getEncoding()->name();
2970 showDialog("symbols", data);
2972 } else if (name == "prefs" && isFullScreen()) {
2973 FuncRequest fr(LFUN_INSET_INSERT, "fullscreen");
2975 showDialog("prefs", data);
2977 showDialog(name, data);
2982 message(cmd.argument());
2985 case LFUN_UI_TOGGLE:
2987 // Make sure the keyboard focus stays in the work area.
2991 case LFUN_SPLIT_VIEW: {
2992 LASSERT(doc_buffer, break);
2993 string const orientation = cmd.getArg(0);
2994 d.splitter_->setOrientation(orientation == "vertical"
2995 ? Qt::Vertical : Qt::Horizontal);
2996 TabWorkArea * twa = addTabWorkArea();
2997 GuiWorkArea * wa = twa->addWorkArea(*doc_buffer, *this);
2998 setCurrentWorkArea(wa);
3001 case LFUN_CLOSE_TAB_GROUP:
3002 if (TabWorkArea * twa = d.currentTabWorkArea()) {
3003 closeTabWorkArea(twa);
3004 d.current_work_area_ = 0;
3005 twa = d.currentTabWorkArea();
3006 // Switch to the next GuiWorkArea in the found TabWorkArea.
3008 // Make sure the work area is up to date.
3009 setCurrentWorkArea(twa->currentWorkArea());
3011 setCurrentWorkArea(0);
3016 case LFUN_COMPLETION_INLINE:
3017 if (d.current_work_area_)
3018 d.current_work_area_->completer().showInline();
3021 case LFUN_COMPLETION_POPUP:
3022 if (d.current_work_area_)
3023 d.current_work_area_->completer().showPopup();
3027 case LFUN_COMPLETION_COMPLETE:
3028 if (d.current_work_area_)
3029 d.current_work_area_->completer().tab();
3032 case LFUN_COMPLETION_CANCEL:
3033 if (d.current_work_area_) {
3034 if (d.current_work_area_->completer().popupVisible())
3035 d.current_work_area_->completer().hidePopup();
3037 d.current_work_area_->completer().hideInline();
3041 case LFUN_COMPLETION_ACCEPT:
3042 if (d.current_work_area_)
3043 d.current_work_area_->completer().activate();
3046 case LFUN_BUFFER_ZOOM_IN:
3047 case LFUN_BUFFER_ZOOM_OUT:
3048 if (cmd.argument().empty()) {
3049 if (cmd.action == LFUN_BUFFER_ZOOM_IN)
3054 lyxrc.zoom += convert<int>(cmd.argument());
3056 if (lyxrc.zoom < 10)
3059 // The global QPixmapCache is used in GuiPainter to cache text
3060 // painting so we must reset it.
3061 QPixmapCache::clear();
3062 guiApp->fontLoader().update();
3063 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
3066 case LFUN_VC_REGISTER:
3067 case LFUN_VC_CHECK_IN:
3068 case LFUN_VC_CHECK_OUT:
3069 case LFUN_VC_REPO_UPDATE:
3070 case LFUN_VC_LOCKING_TOGGLE:
3071 case LFUN_VC_REVERT:
3072 case LFUN_VC_UNDO_LAST:
3073 case LFUN_VC_COMMAND:
3077 case LFUN_SERVER_GOTO_FILE_ROW:
3078 goToFileRow(to_utf8(cmd.argument()));
3086 // Part of automatic menu appearance feature.
3087 if (isFullScreen()) {
3088 if (menuBar()->isVisible() && lyxrc.full_screen_menubar)
3090 if (statusBar()->isVisible())
3091 statusBar()->hide();
3098 void GuiView::lfunUiToggle(FuncRequest const & cmd)
3100 string const arg = cmd.getArg(0);
3101 if (arg == "scrollbar") {
3102 // hide() is of no help
3103 if (d.current_work_area_->verticalScrollBarPolicy() ==
3104 Qt::ScrollBarAlwaysOff)
3106 d.current_work_area_->setVerticalScrollBarPolicy(
3107 Qt::ScrollBarAsNeeded);
3109 d.current_work_area_->setVerticalScrollBarPolicy(
3110 Qt::ScrollBarAlwaysOff);
3113 if (arg == "statusbar") {
3114 statusBar()->setVisible(!statusBar()->isVisible());
3117 if (arg == "menubar") {
3118 menuBar()->setVisible(!menuBar()->isVisible());
3121 #if QT_VERSION >= 0x040300
3122 if (arg == "frame") {
3124 getContentsMargins(&l, &t, &r, &b);
3125 //are the frames in default state?
3126 d.current_work_area_->setFrameStyle(QFrame::NoFrame);
3128 setContentsMargins(-2, -2, -2, -2);
3130 setContentsMargins(0, 0, 0, 0);
3135 if (arg == "fullscreen") {
3140 message(bformat("LFUN_UI_TOGGLE " + _("%1$s unknown command!"), from_utf8(arg)));
3144 void GuiView::toggleFullScreen()
3146 if (isFullScreen()) {
3147 for (int i = 0; i != d.splitter_->count(); ++i)
3148 d.tabWorkArea(i)->setFullScreen(false);
3149 #if QT_VERSION >= 0x040300
3150 setContentsMargins(0, 0, 0, 0);
3152 setWindowState(windowState() ^ Qt::WindowFullScreen);
3155 statusBar()->show();
3158 hideDialogs("prefs", 0);
3159 for (int i = 0; i != d.splitter_->count(); ++i)
3160 d.tabWorkArea(i)->setFullScreen(true);
3161 #if QT_VERSION >= 0x040300
3162 setContentsMargins(-2, -2, -2, -2);
3165 setWindowState(windowState() ^ Qt::WindowFullScreen);
3166 statusBar()->hide();
3167 if (lyxrc.full_screen_menubar)
3169 if (lyxrc.full_screen_toolbars) {
3170 ToolbarMap::iterator end = d.toolbars_.end();
3171 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
3176 // give dialogs like the TOC a chance to adapt
3181 Buffer const * GuiView::updateInset(Inset const * inset)
3183 if (!d.current_work_area_)
3187 d.current_work_area_->scheduleRedraw();
3189 return &d.current_work_area_->bufferView().buffer();
3193 void GuiView::restartCursor()
3195 /* When we move around, or type, it's nice to be able to see
3196 * the cursor immediately after the keypress.
3198 if (d.current_work_area_)
3199 d.current_work_area_->startBlinkingCursor();
3201 // Take this occasion to update the other GUI elements.
3207 void GuiView::updateCompletion(Cursor & cur, bool start, bool keep)
3209 if (d.current_work_area_)
3210 d.current_work_area_->completer().updateVisibility(cur, start, keep);
3215 // This list should be kept in sync with the list of insets in
3216 // src/insets/Inset.cpp. I.e., if a dialog goes with an inset, the
3217 // dialog should have the same name as the inset.
3218 // Changes should be also recorded in LFUN_DIALOG_SHOW doxygen
3219 // docs in LyXAction.cpp.
3221 char const * const dialognames[] = {
3222 "aboutlyx", "bibitem", "bibtex", "box", "branch", "changes", "character",
3223 "citation", "compare", "document", "errorlist", "ert", "external", "file",
3224 "findreplace", "findreplaceadv", "float", "graphics", "href", "include",
3225 "index", "index_print", "info", "listings", "label", "log", "mathdelimiter",
3226 "mathmatrix", "mathspace", "nomenclature", "nomencl_print", "note",
3227 "paragraph", "phantom", "prefs", "print", "ref", "sendto", "space",
3228 "spellchecker", "symbols", "tabular", "tabularcreate", "thesaurus", "texinfo",
3229 "toc", "view-source", "vspace", "wrap", "progress"};
3231 char const * const * const end_dialognames =
3232 dialognames + (sizeof(dialognames) / sizeof(char *));
3236 cmpCStr(char const * name) : name_(name) {}
3237 bool operator()(char const * other) {
3238 return strcmp(other, name_) == 0;
3245 bool isValidName(string const & name)
3247 return find_if(dialognames, end_dialognames,
3248 cmpCStr(name.c_str())) != end_dialognames;
3254 void GuiView::resetDialogs()
3256 // Make sure that no LFUN uses any LyXView.
3257 guiApp->setCurrentView(0);
3260 constructToolbars();
3261 guiApp->menus().fillMenuBar(menuBar(), this, false);
3262 d.layout_->updateContents(true);
3263 // Now update controls with current buffer.
3264 guiApp->setCurrentView(this);
3270 Dialog * GuiView::findOrBuild(string const & name, bool hide_it)
3272 if (!isValidName(name))
3275 map<string, DialogPtr>::iterator it = d.dialogs_.find(name);
3277 if (it != d.dialogs_.end()) {
3279 it->second->hideView();
3280 return it->second.get();
3283 Dialog * dialog = build(name);
3284 d.dialogs_[name].reset(dialog);
3285 if (lyxrc.allow_geometry_session)
3286 dialog->restoreSession();
3293 void GuiView::showDialog(string const & name, string const & data,
3296 triggerShowDialog(toqstr(name), toqstr(data), inset);
3300 void GuiView::doShowDialog(QString const & qname, QString const & qdata,
3306 const string name = fromqstr(qname);
3307 const string data = fromqstr(qdata);
3311 Dialog * dialog = findOrBuild(name, false);
3313 dialog->showData(data);
3314 if (inset && currentBufferView())
3315 currentBufferView()->editInset(name, inset);
3318 catch (ExceptionMessage const & ex) {
3326 bool GuiView::isDialogVisible(string const & name) const
3328 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3329 if (it == d.dialogs_.end())
3331 return it->second.get()->isVisibleView() && !it->second.get()->isClosing();
3335 void GuiView::hideDialog(string const & name, Inset * inset)
3337 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3338 if (it == d.dialogs_.end())
3341 if (inset && currentBufferView()
3342 && inset != currentBufferView()->editedInset(name))
3345 Dialog * const dialog = it->second.get();
3346 if (dialog->isVisibleView())
3348 if (currentBufferView())
3349 currentBufferView()->editInset(name, 0);
3353 void GuiView::disconnectDialog(string const & name)
3355 if (!isValidName(name))
3357 if (currentBufferView())
3358 currentBufferView()->editInset(name, 0);
3362 void GuiView::hideAll() const
3364 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
3365 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3367 for(; it != end; ++it)
3368 it->second->hideView();
3372 void GuiView::updateDialogs()
3374 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
3375 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3377 for(; it != end; ++it) {
3378 Dialog * dialog = it->second.get();
3379 if (dialog && dialog->isVisibleView())
3380 dialog->checkStatus();
3387 // will be replaced by a proper factory...
3388 Dialog * createGuiAbout(GuiView & lv);
3389 Dialog * createGuiBibitem(GuiView & lv);
3390 Dialog * createGuiBibtex(GuiView & lv);
3391 Dialog * createGuiBox(GuiView & lv);
3392 Dialog * createGuiBranch(GuiView & lv);
3393 Dialog * createGuiChanges(GuiView & lv);
3394 Dialog * createGuiCharacter(GuiView & lv);
3395 Dialog * createGuiCitation(GuiView & lv);
3396 Dialog * createGuiCompare(GuiView & lv);
3397 Dialog * createGuiDelimiter(GuiView & lv);
3398 Dialog * createGuiDocument(GuiView & lv);
3399 Dialog * createGuiErrorList(GuiView & lv);
3400 Dialog * createGuiERT(GuiView & lv);
3401 Dialog * createGuiExternal(GuiView & lv);
3402 Dialog * createGuiFloat(GuiView & lv);
3403 Dialog * createGuiGraphics(GuiView & lv);
3404 Dialog * createGuiInclude(GuiView & lv);
3405 Dialog * createGuiIndex(GuiView & lv);
3406 Dialog * createGuiInfo(GuiView & lv);
3407 Dialog * createGuiLabel(GuiView & lv);
3408 Dialog * createGuiListings(GuiView & lv);
3409 Dialog * createGuiLog(GuiView & lv);
3410 Dialog * createGuiMathHSpace(GuiView & lv);
3411 Dialog * createGuiMathMatrix(GuiView & lv);
3412 Dialog * createGuiNomenclature(GuiView & lv);
3413 Dialog * createGuiNote(GuiView & lv);
3414 Dialog * createGuiParagraph(GuiView & lv);
3415 Dialog * createGuiPhantom(GuiView & lv);
3416 Dialog * createGuiPreferences(GuiView & lv);
3417 Dialog * createGuiPrint(GuiView & lv);
3418 Dialog * createGuiPrintindex(GuiView & lv);
3419 Dialog * createGuiPrintNomencl(GuiView & lv);
3420 Dialog * createGuiRef(GuiView & lv);
3421 Dialog * createGuiSearch(GuiView & lv);
3422 Dialog * createGuiSearchAdv(GuiView & lv);
3423 Dialog * createGuiSendTo(GuiView & lv);
3424 Dialog * createGuiShowFile(GuiView & lv);
3425 Dialog * createGuiSpellchecker(GuiView & lv);
3426 Dialog * createGuiSymbols(GuiView & lv);
3427 Dialog * createGuiTabularCreate(GuiView & lv);
3428 Dialog * createGuiTabular(GuiView & lv);
3429 Dialog * createGuiTexInfo(GuiView & lv);
3430 Dialog * createGuiTextHSpace(GuiView & lv);
3431 Dialog * createGuiToc(GuiView & lv);
3432 Dialog * createGuiThesaurus(GuiView & lv);
3433 Dialog * createGuiHyperlink(GuiView & lv);
3434 Dialog * createGuiVSpace(GuiView & lv);
3435 Dialog * createGuiViewSource(GuiView & lv);
3436 Dialog * createGuiWrap(GuiView & lv);
3437 Dialog * createGuiProgressView(GuiView & lv);
3441 Dialog * GuiView::build(string const & name)
3443 LASSERT(isValidName(name), return 0);
3445 if (name == "aboutlyx")
3446 return createGuiAbout(*this);
3447 if (name == "bibitem")
3448 return createGuiBibitem(*this);
3449 if (name == "bibtex")
3450 return createGuiBibtex(*this);
3452 return createGuiBox(*this);
3453 if (name == "branch")
3454 return createGuiBranch(*this);
3455 if (name == "changes")
3456 return createGuiChanges(*this);
3457 if (name == "character")
3458 return createGuiCharacter(*this);
3459 if (name == "citation")
3460 return createGuiCitation(*this);
3461 if (name == "compare")
3462 return createGuiCompare(*this);
3463 if (name == "document")
3464 return createGuiDocument(*this);
3465 if (name == "errorlist")
3466 return createGuiErrorList(*this);
3468 return createGuiERT(*this);
3469 if (name == "external")
3470 return createGuiExternal(*this);
3472 return createGuiShowFile(*this);
3473 if (name == "findreplace")
3474 return createGuiSearch(*this);
3475 if (name == "findreplaceadv")
3476 return createGuiSearchAdv(*this);
3477 if (name == "float")
3478 return createGuiFloat(*this);
3479 if (name == "graphics")
3480 return createGuiGraphics(*this);
3482 return createGuiHyperlink(*this);
3483 if (name == "include")
3484 return createGuiInclude(*this);
3485 if (name == "index")
3486 return createGuiIndex(*this);
3487 if (name == "index_print")
3488 return createGuiPrintindex(*this);
3490 return createGuiInfo(*this);
3491 if (name == "label")
3492 return createGuiLabel(*this);
3493 if (name == "listings")
3494 return createGuiListings(*this);
3496 return createGuiLog(*this);
3497 if (name == "mathdelimiter")
3498 return createGuiDelimiter(*this);
3499 if (name == "mathspace")
3500 return createGuiMathHSpace(*this);
3501 if (name == "mathmatrix")
3502 return createGuiMathMatrix(*this);
3503 if (name == "nomenclature")
3504 return createGuiNomenclature(*this);
3505 if (name == "nomencl_print")
3506 return createGuiPrintNomencl(*this);
3508 return createGuiNote(*this);
3509 if (name == "paragraph")
3510 return createGuiParagraph(*this);
3511 if (name == "phantom")
3512 return createGuiPhantom(*this);
3513 if (name == "prefs")
3514 return createGuiPreferences(*this);
3515 if (name == "print")
3516 return createGuiPrint(*this);
3518 return createGuiRef(*this);
3519 if (name == "sendto")
3520 return createGuiSendTo(*this);
3521 if (name == "space")
3522 return createGuiTextHSpace(*this);
3523 if (name == "spellchecker")
3524 return createGuiSpellchecker(*this);
3525 if (name == "symbols")
3526 return createGuiSymbols(*this);
3527 if (name == "tabular")
3528 return createGuiTabular(*this);
3529 if (name == "tabularcreate")
3530 return createGuiTabularCreate(*this);
3531 if (name == "texinfo")
3532 return createGuiTexInfo(*this);
3533 if (name == "thesaurus")
3534 return createGuiThesaurus(*this);
3536 return createGuiToc(*this);
3537 if (name == "view-source")
3538 return createGuiViewSource(*this);
3539 if (name == "vspace")
3540 return createGuiVSpace(*this);
3542 return createGuiWrap(*this);
3543 if (name == "progress")
3544 return createGuiProgressView(*this);
3550 } // namespace frontend
3553 #include "moc_GuiView.cpp"