3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Lars Gullik Bjønnes
8 * \author Abdelrazak Younes
11 * Full author contact details are available in file CREDITS.
19 #include "FileDialog.h"
20 #include "FontLoader.h"
21 #include "GuiApplication.h"
22 #include "GuiCommandBuffer.h"
23 #include "GuiCompleter.h"
24 #include "GuiWorkArea.h"
25 #include "GuiKeySymbol.h"
27 #include "GuiToolbar.h"
28 #include "LayoutBox.h"
32 #include "qt_helpers.h"
34 #include "frontends/alert.h"
36 #include "buffer_funcs.h"
38 #include "BufferList.h"
39 #include "BufferParams.h"
40 #include "BufferView.h"
41 #include "Converter.h"
43 #include "CutAndPaste.h"
45 #include "ErrorList.h"
47 #include "FuncStatus.h"
48 #include "FuncRequest.h"
52 #include "LyXAction.h"
57 #include "Paragraph.h"
58 #include "SpellChecker.h"
59 #include "TextClass.h"
64 #include "support/convert.h"
65 #include "support/debug.h"
66 #include "support/ExceptionMessage.h"
67 #include "support/FileName.h"
68 #include "support/filetools.h"
69 #include "support/gettext.h"
70 #include "support/filetools.h"
71 #include "support/ForkedCalls.h"
72 #include "support/lassert.h"
73 #include "support/lstrings.h"
74 #include "support/os.h"
75 #include "support/Package.h"
76 #include "support/Path.h"
77 #include "support/Systemcall.h"
78 #include "support/Timeout.h"
79 #include "support/ProgressInterface.h"
82 #include <QApplication>
83 #include <QCloseEvent>
85 #include <QDesktopWidget>
86 #include <QDragEnterEvent>
93 #include <QPixmapCache>
95 #include <QPushButton>
99 #include <QStackedWidget>
100 #include <QStatusBar>
104 #include <QScrollBar>
106 #define EXPORT_in_THREAD 1
108 // QtConcurrent was introduced in Qt 4.4
109 #if (QT_VERSION >= 0x040400)
111 #include <QFutureWatcher>
112 #include <QtConcurrentRun>
115 #include <boost/bind.hpp>
119 #ifdef HAVE_SYS_TIME_H
120 # include <sys/time.h>
127 using namespace lyx::support;
134 class BackgroundWidget : public QWidget
139 LYXERR(Debug::GUI, "show banner: " << lyxrc.show_banner);
140 /// The text to be written on top of the pixmap
141 QString const text = lyx_version ?
142 qt_("version ") + lyx_version : qt_("unknown version");
143 splash_ = getPixmap("images/", "banner", "png");
145 QPainter pain(&splash_);
146 pain.setPen(QColor(0, 0, 0));
148 // The font used to display the version info
149 font.setStyleHint(QFont::SansSerif);
150 font.setWeight(QFont::Bold);
151 font.setPointSize(int(toqstr(lyxrc.font_sizes[FONT_SIZE_LARGE]).toDouble()));
153 pain.drawText(260, 15, text);
156 void paintEvent(QPaintEvent *)
158 int x = (width() - splash_.width()) / 2;
159 int y = (height() - splash_.height()) / 2;
161 pain.drawPixmap(x, y, splash_);
169 /// Toolbar store providing access to individual toolbars by name.
170 typedef map<string, GuiToolbar *> ToolbarMap;
172 typedef boost::shared_ptr<Dialog> DialogPtr;
177 struct GuiView::GuiViewPrivate
179 GuiViewPrivate(GuiView * gv)
180 : gv_(gv), current_work_area_(0), current_main_work_area_(0),
181 layout_(0), autosave_timeout_(5000),
184 // hardcode here the platform specific icon size
185 smallIconSize = 14; // scaling problems
186 normalIconSize = 20; // ok, default
187 bigIconSize = 26; // better for some math icons
189 splitter_ = new QSplitter;
190 bg_widget_ = new BackgroundWidget;
191 stack_widget_ = new QStackedWidget;
192 stack_widget_->addWidget(bg_widget_);
193 stack_widget_->addWidget(splitter_);
201 delete stack_widget_;
204 QMenu * toolBarPopup(GuiView * parent)
206 // FIXME: translation
207 QMenu * menu = new QMenu(parent);
208 QActionGroup * iconSizeGroup = new QActionGroup(parent);
210 QAction * smallIcons = new QAction(iconSizeGroup);
211 smallIcons->setText(qt_("Small-sized icons"));
212 smallIcons->setCheckable(true);
213 QObject::connect(smallIcons, SIGNAL(triggered()),
214 parent, SLOT(smallSizedIcons()));
215 menu->addAction(smallIcons);
217 QAction * normalIcons = new QAction(iconSizeGroup);
218 normalIcons->setText(qt_("Normal-sized icons"));
219 normalIcons->setCheckable(true);
220 QObject::connect(normalIcons, SIGNAL(triggered()),
221 parent, SLOT(normalSizedIcons()));
222 menu->addAction(normalIcons);
224 QAction * bigIcons = new QAction(iconSizeGroup);
225 bigIcons->setText(qt_("Big-sized icons"));
226 bigIcons->setCheckable(true);
227 QObject::connect(bigIcons, SIGNAL(triggered()),
228 parent, SLOT(bigSizedIcons()));
229 menu->addAction(bigIcons);
231 unsigned int cur = parent->iconSize().width();
232 if ( cur == parent->d.smallIconSize)
233 smallIcons->setChecked(true);
234 else if (cur == parent->d.normalIconSize)
235 normalIcons->setChecked(true);
236 else if (cur == parent->d.bigIconSize)
237 bigIcons->setChecked(true);
244 stack_widget_->setCurrentWidget(bg_widget_);
245 bg_widget_->setUpdatesEnabled(true);
248 TabWorkArea * tabWorkArea(int i)
250 return dynamic_cast<TabWorkArea *>(splitter_->widget(i));
253 TabWorkArea * currentTabWorkArea()
255 if (splitter_->count() == 1)
256 // The first TabWorkArea is always the first one, if any.
257 return tabWorkArea(0);
259 for (int i = 0; i != splitter_->count(); ++i) {
260 TabWorkArea * twa = tabWorkArea(i);
261 if (current_main_work_area_ == twa->currentWorkArea())
265 // None has the focus so we just take the first one.
266 return tabWorkArea(0);
269 void setPreviewFuture(QFuture<docstring> const & f)
271 if (preview_watcher_.isRunning())
272 preview_watcher_.waitForFinished();
273 preview_watcher_.setFuture(f);
274 connect(&preview_watcher_, SIGNAL(finished()), gv_,
275 SLOT(threadFinished()));
280 GuiWorkArea * current_work_area_;
281 GuiWorkArea * current_main_work_area_;
282 QSplitter * splitter_;
283 QStackedWidget * stack_widget_;
284 BackgroundWidget * bg_widget_;
286 ToolbarMap toolbars_;
287 /// The main layout box.
289 * \warning Don't Delete! The layout box is actually owned by
290 * whichever toolbar contains it. All the GuiView class needs is a
291 * means of accessing it.
293 * FIXME: replace that with a proper model so that we are not limited
294 * to only one dialog.
299 map<string, DialogPtr> dialogs_;
301 unsigned int smallIconSize;
302 unsigned int normalIconSize;
303 unsigned int bigIconSize;
305 QTimer statusbar_timer_;
306 /// auto-saving of buffers
307 Timeout autosave_timeout_;
308 /// flag against a race condition due to multiclicks, see bug #1119
312 TocModels toc_models_;
314 #if (QT_VERSION >= 0x040400)
316 QFutureWatcher<docstring> autosave_watcher_;
317 QFutureWatcher<docstring> preview_watcher_;
322 GuiView::GuiView(int id)
323 : d(*new GuiViewPrivate(this)), id_(id), closing_(false)
325 // GuiToolbars *must* be initialised before the menu bar.
326 normalSizedIcons(); // at least on Mac the default is 32 otherwise, which is huge
329 // set ourself as the current view. This is needed for the menu bar
330 // filling, at least for the static special menu item on Mac. Otherwise
331 // they are greyed out.
332 guiApp->setCurrentView(this);
334 // Fill up the menu bar.
335 guiApp->menus().fillMenuBar(menuBar(), this, true);
337 setCentralWidget(d.stack_widget_);
339 // Start autosave timer
340 if (lyxrc.autosave) {
341 d.autosave_timeout_.timeout.connect(boost::bind(&GuiView::autoSave, this));
342 d.autosave_timeout_.setTimeout(lyxrc.autosave * 1000);
343 d.autosave_timeout_.start();
345 connect(&d.statusbar_timer_, SIGNAL(timeout()),
346 this, SLOT(clearMessage()));
348 // We don't want to keep the window in memory if it is closed.
349 setAttribute(Qt::WA_DeleteOnClose, true);
351 #if (!defined(Q_WS_WIN) && !defined(Q_WS_MACX))
352 // assign an icon to main form. We do not do it under Qt/Win or Qt/Mac,
353 // since the icon is provided in the application bundle.
354 setWindowIcon(getPixmap("images/", "lyx", "png"));
358 setAcceptDrops(true);
360 statusBar()->setSizeGripEnabled(true);
362 // Forbid too small unresizable window because it can happen
363 // with some window manager under X11.
364 setMinimumSize(300, 200);
366 if (lyxrc.allow_geometry_session) {
367 // Now take care of session management.
372 // no session handling, default to a sane size.
373 setGeometry(50, 50, 690, 510);
376 // clear session data if any.
378 settings.remove("views");
380 #if (QT_VERSION >= 0x040400)
381 connect(&d.autosave_watcher_, SIGNAL(finished()), this,
382 SLOT(threadFinished()));
393 void GuiView::threadFinished()
395 #if (QT_VERSION >= 0x040400)
396 QFutureWatcher<docstring> const * watcher =
397 static_cast<QFutureWatcher<docstring> const *>(sender());
398 message(watcher->result());
403 void GuiView::saveLayout() const
406 settings.beginGroup("views");
407 settings.beginGroup(QString::number(id_));
409 settings.setValue("pos", pos());
410 settings.setValue("size", size());
412 settings.setValue("geometry", saveGeometry());
414 settings.setValue("layout", saveState(0));
415 settings.setValue("icon_size", iconSize());
419 bool GuiView::restoreLayout()
422 settings.beginGroup("views");
423 settings.beginGroup(QString::number(id_));
424 QString const icon_key = "icon_size";
425 if (!settings.contains(icon_key))
428 //code below is skipped when when ~/.config/LyX is (re)created
429 setIconSize(settings.value(icon_key).toSize());
431 QPoint pos = settings.value("pos", QPoint(50, 50)).toPoint();
432 QSize size = settings.value("size", QSize(690, 510)).toSize();
436 // Work-around for bug #6034: the window ends up in an undetermined
437 // state when trying to restore a maximized window when it is
438 // already maximized.
439 if (!(windowState() & Qt::WindowMaximized))
440 if (!restoreGeometry(settings.value("geometry").toByteArray()))
441 setGeometry(50, 50, 690, 510);
443 // Make sure layout is correctly oriented.
444 setLayoutDirection(qApp->layoutDirection());
446 // Allow the toc and view-source dock widget to be restored if needed.
448 if ((dialog = findOrBuild("toc", true)))
449 // see bug 5082. At least setup title and enabled state.
450 // Visibility will be adjusted by restoreState below.
451 dialog->prepareView();
452 if ((dialog = findOrBuild("view-source", true)))
453 dialog->prepareView();
455 if (!restoreState(settings.value("layout").toByteArray(), 0))
462 GuiToolbar * GuiView::toolbar(string const & name)
464 ToolbarMap::iterator it = d.toolbars_.find(name);
465 if (it != d.toolbars_.end())
468 LYXERR(Debug::GUI, "Toolbar::display: no toolbar named " << name);
469 message(bformat(_("Unknown toolbar \"%1$s\""), from_utf8(name)));
474 void GuiView::constructToolbars()
476 ToolbarMap::iterator it = d.toolbars_.begin();
477 for (; it != d.toolbars_.end(); ++it)
481 // I don't like doing this here, but the standard toolbar
482 // destroys this object when it's destroyed itself (vfr)
483 d.layout_ = new LayoutBox(*this);
484 d.stack_widget_->addWidget(d.layout_);
485 d.layout_->move(0,0);
487 // extracts the toolbars from the backend
488 Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
489 Toolbars::Infos::iterator end = guiApp->toolbars().end();
490 for (; cit != end; ++cit)
491 d.toolbars_[cit->name] = new GuiToolbar(*cit, *this);
495 void GuiView::initToolbars()
497 // extracts the toolbars from the backend
498 Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
499 Toolbars::Infos::iterator end = guiApp->toolbars().end();
500 for (; cit != end; ++cit) {
501 GuiToolbar * tb = toolbar(cit->name);
504 int const visibility = guiApp->toolbars().defaultVisibility(cit->name);
506 tb->setVisible(false);
507 tb->setVisibility(visibility);
509 if (visibility & Toolbars::TOP) {
511 addToolBarBreak(Qt::TopToolBarArea);
512 addToolBar(Qt::TopToolBarArea, tb);
515 if (visibility & Toolbars::BOTTOM) {
516 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
517 #if (QT_VERSION >= 0x040202)
518 addToolBarBreak(Qt::BottomToolBarArea);
520 addToolBar(Qt::BottomToolBarArea, tb);
523 if (visibility & Toolbars::LEFT) {
524 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
525 #if (QT_VERSION >= 0x040202)
526 addToolBarBreak(Qt::LeftToolBarArea);
528 addToolBar(Qt::LeftToolBarArea, tb);
531 if (visibility & Toolbars::RIGHT) {
532 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
533 #if (QT_VERSION >= 0x040202)
534 addToolBarBreak(Qt::RightToolBarArea);
536 addToolBar(Qt::RightToolBarArea, tb);
539 if (visibility & Toolbars::ON)
540 tb->setVisible(true);
545 TocModels & GuiView::tocModels()
547 return d.toc_models_;
551 void GuiView::setFocus()
553 LYXERR(Debug::DEBUG, "GuiView::setFocus()" << this);
554 // Make sure LyXFunc points to the correct view.
555 guiApp->setCurrentView(this);
556 QMainWindow::setFocus();
557 if (d.current_work_area_)
558 d.current_work_area_->setFocus();
562 QMenu * GuiView::createPopupMenu()
564 return d.toolBarPopup(this);
568 void GuiView::showEvent(QShowEvent * e)
570 LYXERR(Debug::GUI, "Passed Geometry "
571 << size().height() << "x" << size().width()
572 << "+" << pos().x() << "+" << pos().y());
574 if (d.splitter_->count() == 0)
575 // No work area, switch to the background widget.
578 QMainWindow::showEvent(e);
582 /** Destroy only all tabbed WorkAreas. Destruction of other WorkAreas
583 ** is responsibility of the container (e.g., dialog)
585 void GuiView::closeEvent(QCloseEvent * close_event)
587 LYXERR(Debug::DEBUG, "GuiView::closeEvent()");
592 // it can happen that this event arrives without selecting the view,
593 // e.g. when clicking the close button on a background window.
595 if (!closeWorkAreaAll()) {
597 close_event->ignore();
601 // Make sure that nothing will use this to be closed View.
602 guiApp->unregisterView(this);
604 if (isFullScreen()) {
605 // Switch off fullscreen before closing.
610 // Make sure the timer time out will not trigger a statusbar update.
611 d.statusbar_timer_.stop();
613 // Saving fullscreen requires additional tweaks in the toolbar code.
614 // It wouldn't also work under linux natively.
615 if (lyxrc.allow_geometry_session) {
616 // Save this window geometry and layout.
618 // Then the toolbar private states.
619 ToolbarMap::iterator end = d.toolbars_.end();
620 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
621 it->second->saveSession();
622 // Now take care of all other dialogs:
623 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
624 for (; it!= d.dialogs_.end(); ++it)
625 it->second->saveSession();
628 close_event->accept();
632 void GuiView::dragEnterEvent(QDragEnterEvent * event)
634 if (event->mimeData()->hasUrls())
636 /// \todo Ask lyx-devel is this is enough:
637 /// if (event->mimeData()->hasFormat("text/plain"))
638 /// event->acceptProposedAction();
642 void GuiView::dropEvent(QDropEvent * event)
644 QList<QUrl> files = event->mimeData()->urls();
648 LYXERR(Debug::GUI, "GuiView::dropEvent: got URLs!");
649 for (int i = 0; i != files.size(); ++i) {
650 string const file = os::internal_path(fromqstr(
651 files.at(i).toLocalFile()));
655 string const ext = support::getExtension(file);
656 vector<const Format *> found_formats;
658 // Find all formats that have the correct extension.
659 vector<const Format *> const & import_formats
660 = theConverters().importableFormats();
661 vector<const Format *>::const_iterator it = import_formats.begin();
662 for (; it != import_formats.end(); ++it)
663 if ((*it)->extension() == ext)
664 found_formats.push_back(*it);
667 if (found_formats.size() >= 1) {
668 if (found_formats.size() > 1) {
669 //FIXME: show a dialog to choose the correct importable format
671 "Multiple importable formats found, selecting first");
673 string const arg = found_formats[0]->name() + " " + file;
674 cmd = FuncRequest(LFUN_BUFFER_IMPORT, arg);
677 //FIXME: do we have to explicitly check whether it's a lyx file?
679 "No formats found, trying to open it as a lyx file");
680 cmd = FuncRequest(LFUN_FILE_OPEN, file);
683 // Asynchronously post the event. DropEvent usually come
684 // from the BufferView. But reloading a file might close
685 // the BufferView from within its own event handler.
686 guiApp->dispatchDelayed(cmd);
692 void GuiView::message(docstring const & str)
694 if (ForkedProcess::iAmAChild())
697 statusBar()->showMessage(toqstr(str));
698 d.statusbar_timer_.stop();
699 d.statusbar_timer_.start(3000);
703 void GuiView::smallSizedIcons()
705 setIconSize(QSize(d.smallIconSize, d.smallIconSize));
709 void GuiView::normalSizedIcons()
711 setIconSize(QSize(d.normalIconSize, d.normalIconSize));
715 void GuiView::bigSizedIcons()
717 setIconSize(QSize(d.bigIconSize, d.bigIconSize));
721 void GuiView::clearMessage()
726 d.statusbar_timer_.stop();
730 void GuiView::updateWindowTitle(GuiWorkArea * wa)
732 if (wa != d.current_work_area_)
734 setWindowTitle(qt_("LyX: ") + wa->windowTitle());
735 setWindowIconText(wa->windowIconText());
739 void GuiView::on_currentWorkAreaChanged(GuiWorkArea * wa)
742 disconnectBufferView();
743 connectBufferView(wa->bufferView());
744 connectBuffer(wa->bufferView().buffer());
745 d.current_work_area_ = wa;
746 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
747 this, SLOT(updateWindowTitle(GuiWorkArea *)));
748 updateWindowTitle(wa);
752 // The document settings needs to be reinitialised.
753 updateDialog("document", "");
755 // Buffer-dependent dialogs must be updated. This is done here because
756 // some dialogs require buffer()->text.
761 void GuiView::on_lastWorkAreaRemoved()
764 // We already are in a close event. Nothing more to do.
767 if (d.splitter_->count() > 1)
768 // We have a splitter so don't close anything.
771 // Reset and updates the dialogs.
772 d.toc_models_.reset(0);
773 updateDialog("document", "");
776 resetWindowTitleAndIconText();
778 if (lyxrc.open_buffers_in_tabs)
779 // Nothing more to do, the window should stay open.
782 if (guiApp->viewIds().size() > 1) {
788 // On Mac we also close the last window because the application stay
789 // resident in memory. On other platforms we don't close the last
790 // window because this would quit the application.
796 void GuiView::updateStatusBar()
798 // let the user see the explicit message
799 if (d.statusbar_timer_.isActive())
806 void GuiView::showMessage()
808 QString msg = toqstr(theGuiApp()->viewStatusMessage());
810 BufferView const * bv = currentBufferView();
812 msg = toqstr(bv->cursor().currentState());
814 msg = qt_("Welcome to LyX!");
816 statusBar()->showMessage(msg);
820 bool GuiView::event(QEvent * e)
824 // Useful debug code:
825 //case QEvent::ActivationChange:
826 //case QEvent::WindowDeactivate:
827 //case QEvent::Paint:
828 //case QEvent::Enter:
829 //case QEvent::Leave:
830 //case QEvent::HoverEnter:
831 //case QEvent::HoverLeave:
832 //case QEvent::HoverMove:
833 //case QEvent::StatusTip:
834 //case QEvent::DragEnter:
835 //case QEvent::DragLeave:
839 case QEvent::WindowActivate: {
840 GuiView * old_view = guiApp->currentView();
841 if (this == old_view) {
843 return QMainWindow::event(e);
845 if (old_view && old_view->currentBufferView()) {
846 // save current selection to the selection buffer to allow
847 // middle-button paste in this window.
848 cap::saveSelection(old_view->currentBufferView()->cursor());
850 guiApp->setCurrentView(this);
851 if (d.current_work_area_) {
852 BufferView & bv = d.current_work_area_->bufferView();
853 connectBufferView(bv);
854 connectBuffer(bv.buffer());
855 // The document structure, name and dialogs might have
856 // changed in another view.
858 // The document settings needs to be reinitialised.
859 updateDialog("document", "");
862 resetWindowTitleAndIconText();
865 return QMainWindow::event(e);
868 case QEvent::ShortcutOverride: {
871 #if (!defined Q_WS_X11) || (QT_VERSION >= 0x040500)
872 if (isFullScreen() && menuBar()->isHidden()) {
873 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
874 // FIXME: we should also try to detect special LyX shortcut such as
875 // Alt-P and Alt-M. Right now there is a hack in
876 // GuiWorkArea::processKeySym() that hides again the menubar for
878 if (ke->modifiers() & Qt::AltModifier && ke->key() != Qt::Key_Alt) {
880 return QMainWindow::event(e);
885 if (d.current_work_area_)
886 // Nothing special to do.
887 return QMainWindow::event(e);
889 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
890 // Let Qt handle menu access and the Tab keys to navigate keys to navigate
892 if (ke->modifiers() & Qt::AltModifier || ke->key() == Qt::Key_Tab
893 || ke->key() == Qt::Key_Backtab)
894 return QMainWindow::event(e);
896 // Allow processing of shortcuts that are allowed even when no Buffer
899 setKeySymbol(&sym, ke);
900 guiApp->processKeySym(sym, q_key_state(ke->modifiers()));
906 return QMainWindow::event(e);
910 void GuiView::resetWindowTitleAndIconText()
912 setWindowTitle(qt_("LyX"));
913 setWindowIconText(qt_("LyX"));
916 bool GuiView::focusNextPrevChild(bool /*next*/)
923 void GuiView::setBusy(bool busy)
925 if (d.current_work_area_) {
926 d.current_work_area_->setUpdatesEnabled(!busy);
928 d.current_work_area_->stopBlinkingCursor();
930 d.current_work_area_->startBlinkingCursor();
934 QApplication::setOverrideCursor(Qt::WaitCursor);
936 QApplication::restoreOverrideCursor();
940 GuiWorkArea * GuiView::workArea(Buffer & buffer)
942 if (currentWorkArea()
943 && ¤tWorkArea()->bufferView().buffer() == &buffer)
944 return (GuiWorkArea *) currentWorkArea();
945 if (TabWorkArea * twa = d.currentTabWorkArea())
946 return twa->workArea(buffer);
951 GuiWorkArea * GuiView::addWorkArea(Buffer & buffer)
953 // Automatically create a TabWorkArea if there are none yet.
954 TabWorkArea * tab_widget = d.splitter_->count()
955 ? d.currentTabWorkArea() : addTabWorkArea();
956 return tab_widget->addWorkArea(buffer, *this);
960 TabWorkArea * GuiView::addTabWorkArea()
962 TabWorkArea * twa = new TabWorkArea;
963 QObject::connect(twa, SIGNAL(currentWorkAreaChanged(GuiWorkArea *)),
964 this, SLOT(on_currentWorkAreaChanged(GuiWorkArea *)));
965 QObject::connect(twa, SIGNAL(lastWorkAreaRemoved()),
966 this, SLOT(on_lastWorkAreaRemoved()));
968 d.splitter_->addWidget(twa);
969 d.stack_widget_->setCurrentWidget(d.splitter_);
974 GuiWorkArea const * GuiView::currentWorkArea() const
976 return d.current_work_area_;
980 GuiWorkArea * GuiView::currentWorkArea()
982 return d.current_work_area_;
986 GuiWorkArea const * GuiView::currentMainWorkArea() const
988 if (d.currentTabWorkArea() == NULL)
990 return d.currentTabWorkArea()->currentWorkArea();
994 GuiWorkArea * GuiView::currentMainWorkArea()
996 if (d.currentTabWorkArea() == NULL)
998 return d.currentTabWorkArea()->currentWorkArea();
1002 void GuiView::setCurrentWorkArea(GuiWorkArea * wa)
1004 LYXERR(Debug::DEBUG, "Setting current wa: " << wa << endl);
1006 d.current_work_area_ = NULL;
1010 GuiWorkArea * old_gwa = theGuiApp()->currentView()->currentWorkArea();
1014 if (currentBufferView())
1015 cap::saveSelection(currentBufferView()->cursor());
1017 theGuiApp()->setCurrentView(this);
1018 d.current_work_area_ = wa;
1019 for (int i = 0; i != d.splitter_->count(); ++i) {
1020 if (d.tabWorkArea(i)->setCurrentWorkArea(wa)) {
1021 //if (d.current_main_work_area_)
1022 // d.current_main_work_area_->setFrameStyle(QFrame::NoFrame);
1023 d.current_main_work_area_ = wa;
1024 //d.current_main_work_area_->setFrameStyle(QFrame::Box | QFrame::Plain);
1025 //d.current_main_work_area_->setLineWidth(2);
1026 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() << ", Current main wa: " << currentMainWorkArea());
1030 LYXERR(Debug::DEBUG, "This is not a tabbed wa");
1031 on_currentWorkAreaChanged(wa);
1032 BufferView & bv = wa->bufferView();
1033 bv.cursor().fixIfBroken();
1035 wa->setUpdatesEnabled(true);
1036 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() << ", Current main wa: " << currentMainWorkArea());
1040 void GuiView::removeWorkArea(GuiWorkArea * wa)
1042 LASSERT(wa, return);
1043 if (wa == d.current_work_area_) {
1045 disconnectBufferView();
1046 d.current_work_area_ = 0;
1047 d.current_main_work_area_ = 0;
1050 bool found_twa = false;
1051 for (int i = 0; i != d.splitter_->count(); ++i) {
1052 TabWorkArea * twa = d.tabWorkArea(i);
1053 if (twa->removeWorkArea(wa)) {
1054 // Found in this tab group, and deleted the GuiWorkArea.
1056 if (twa->count() != 0) {
1057 if (d.current_work_area_ == 0)
1058 // This means that we are closing the current GuiWorkArea, so
1059 // switch to the next GuiWorkArea in the found TabWorkArea.
1060 setCurrentWorkArea(twa->currentWorkArea());
1062 // No more WorkAreas in this tab group, so delete it.
1069 // It is not a tabbed work area (i.e., the search work area), so it
1070 // should be deleted by other means.
1071 LASSERT(found_twa, /* */);
1073 if (d.current_work_area_ == 0) {
1074 if (d.splitter_->count() != 0) {
1075 TabWorkArea * twa = d.currentTabWorkArea();
1076 setCurrentWorkArea(twa->currentWorkArea());
1078 // No more work areas, switch to the background widget.
1079 setCurrentWorkArea(0);
1085 LayoutBox * GuiView::getLayoutDialog() const
1091 void GuiView::updateLayoutList()
1094 d.layout_->updateContents(false);
1098 void GuiView::updateToolbars()
1100 ToolbarMap::iterator end = d.toolbars_.end();
1101 if (d.current_work_area_) {
1103 d.current_work_area_->bufferView().cursor().inMathed();
1105 lyx::getStatus(FuncRequest(LFUN_LAYOUT_TABULAR)).enabled();
1107 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).enabled() &&
1108 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).onoff(true);
1109 bool const mathmacrotemplate =
1110 lyx::getStatus(FuncRequest(LFUN_IN_MATHMACROTEMPLATE)).enabled();
1112 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1113 it->second->update(math, table, review, mathmacrotemplate);
1115 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1116 it->second->update(false, false, false, false);
1120 void GuiView::setBuffer(Buffer * newBuffer)
1122 LYXERR(Debug::DEBUG, "Setting buffer: " << newBuffer << endl);
1123 LASSERT(newBuffer, return);
1126 GuiWorkArea * wa = workArea(*newBuffer);
1128 newBuffer->masterBuffer()->updateLabels();
1129 wa = addWorkArea(*newBuffer);
1131 //Disconnect the old buffer...there's no new one.
1134 connectBuffer(*newBuffer);
1135 connectBufferView(wa->bufferView());
1136 setCurrentWorkArea(wa);
1142 void GuiView::connectBuffer(Buffer & buf)
1144 buf.setGuiDelegate(this);
1148 void GuiView::disconnectBuffer()
1150 if (d.current_work_area_)
1151 d.current_work_area_->bufferView().buffer().setGuiDelegate(0);
1155 void GuiView::connectBufferView(BufferView & bv)
1157 bv.setGuiDelegate(this);
1161 void GuiView::disconnectBufferView()
1163 if (d.current_work_area_)
1164 d.current_work_area_->bufferView().setGuiDelegate(0);
1168 void GuiView::errors(string const & error_type, bool from_master)
1170 ErrorList & el = from_master ?
1171 documentBufferView()->buffer().masterBuffer()->errorList(error_type)
1172 : documentBufferView()->buffer().errorList(error_type);
1173 string data = error_type;
1175 data = "from_master|" + error_type;
1177 showDialog("errorlist", data);
1181 void GuiView::updateTocItem(string const & type, DocIterator const & dit)
1183 d.toc_models_.updateItem(toqstr(type), dit);
1187 void GuiView::structureChanged()
1189 d.toc_models_.reset(documentBufferView());
1190 // Navigator needs more than a simple update in this case. It needs to be
1192 updateDialog("toc", "");
1196 void GuiView::updateDialog(string const & name, string const & data)
1198 if (!isDialogVisible(name))
1201 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
1202 if (it == d.dialogs_.end())
1205 Dialog * const dialog = it->second.get();
1206 if (dialog->isVisibleView())
1207 dialog->initialiseParams(data);
1211 BufferView * GuiView::documentBufferView()
1213 return currentMainWorkArea()
1214 ? ¤tMainWorkArea()->bufferView()
1219 BufferView const * GuiView::documentBufferView() const
1221 return currentMainWorkArea()
1222 ? ¤tMainWorkArea()->bufferView()
1227 BufferView * GuiView::currentBufferView()
1229 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1233 BufferView const * GuiView::currentBufferView() const
1235 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1239 static docstring saveAndDestroyBuffer(Buffer * buffer, FileName const & fname)
1242 FileName const tmp_ret = FileName::tempName("lyxauto");
1243 if (!tmp_ret.empty()) {
1244 if (buffer->writeFile(tmp_ret))
1245 failed = !tmp_ret.moveTo(fname);
1248 // failed to write/rename tmp_ret so try writing direct
1249 failed = buffer->writeFile(fname);
1253 ? _("Automatic save failed!")
1254 : _("Automatic save done.");
1258 void GuiView::autoSave()
1260 LYXERR(Debug::INFO, "Running autoSave()");
1262 Buffer * buffer = documentBufferView()
1263 ? &documentBufferView()->buffer() : 0;
1267 #if (QT_VERSION >= 0x040400)
1268 QFuture<docstring> f = QtConcurrent::run(saveAndDestroyBuffer, buffer->clone(),
1269 buffer->getAutosaveFilename());
1270 d.autosave_watcher_.setFuture(f);
1277 void GuiView::resetAutosaveTimers()
1280 d.autosave_timeout_.restart();
1284 bool GuiView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1287 Buffer * buf = currentBufferView()
1288 ? ¤tBufferView()->buffer() : 0;
1289 Buffer * doc_buffer = documentBufferView()
1290 ? &(documentBufferView()->buffer()) : 0;
1292 // Check whether we need a buffer
1293 if (!lyxaction.funcHasFlag(cmd.action, LyXAction::NoBuffer) && !buf) {
1294 // no, exit directly
1295 flag.message(from_utf8(N_("Command not allowed with"
1296 "out any document open")));
1297 flag.setEnabled(false);
1301 if (cmd.origin == FuncRequest::TOC) {
1302 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
1304 if (toc->getStatus(documentBufferView()->cursor(), cmd, fs))
1307 flag.setEnabled(false);
1311 switch(cmd.action) {
1312 case LFUN_BUFFER_IMPORT:
1315 case LFUN_MASTER_BUFFER_UPDATE:
1316 case LFUN_MASTER_BUFFER_VIEW:
1317 enable = doc_buffer && doc_buffer->parent() != 0
1318 && !d.preview_watcher_.isRunning();
1321 case LFUN_BUFFER_UPDATE:
1322 case LFUN_BUFFER_VIEW: {
1323 if (!doc_buffer || d.preview_watcher_.isRunning()) {
1327 string format = to_utf8(cmd.argument());
1328 if (cmd.argument().empty())
1329 format = doc_buffer->getDefaultOutputFormat();
1330 enable = doc_buffer->isExportableFormat(format);
1334 case LFUN_BUFFER_RELOAD:
1335 enable = doc_buffer && !doc_buffer->isUnnamed()
1336 && doc_buffer->fileName().exists()
1337 && (!doc_buffer->isClean()
1338 || doc_buffer->isExternallyModified(Buffer::timestamp_method));
1341 case LFUN_BUFFER_CHILD_OPEN:
1342 enable = doc_buffer;
1345 case LFUN_BUFFER_WRITE:
1346 enable = doc_buffer && (doc_buffer->isUnnamed() || !doc_buffer->isClean());
1349 //FIXME: This LFUN should be moved to GuiApplication.
1350 case LFUN_BUFFER_WRITE_ALL: {
1351 // We enable the command only if there are some modified buffers
1352 Buffer * first = theBufferList().first();
1357 // We cannot use a for loop as the buffer list is a cycle.
1359 if (!b->isClean()) {
1363 b = theBufferList().next(b);
1364 } while (b != first);
1368 case LFUN_BUFFER_WRITE_AS:
1369 enable = doc_buffer;
1372 case LFUN_BUFFER_CLOSE:
1373 enable = doc_buffer;
1376 case LFUN_BUFFER_CLOSE_ALL:
1377 enable = theBufferList().last() != theBufferList().first();
1380 case LFUN_SPLIT_VIEW:
1381 if (cmd.getArg(0) == "vertical")
1382 enable = doc_buffer && (d.splitter_->count() == 1 ||
1383 d.splitter_->orientation() == Qt::Vertical);
1385 enable = doc_buffer && (d.splitter_->count() == 1 ||
1386 d.splitter_->orientation() == Qt::Horizontal);
1389 case LFUN_CLOSE_TAB_GROUP:
1390 enable = d.currentTabWorkArea();
1393 case LFUN_TOOLBAR_TOGGLE:
1394 if (GuiToolbar * t = toolbar(cmd.getArg(0)))
1395 flag.setOnOff(t->isVisible());
1398 case LFUN_DROP_LAYOUTS_CHOICE:
1402 case LFUN_UI_TOGGLE:
1403 flag.setOnOff(isFullScreen());
1406 case LFUN_DIALOG_DISCONNECT_INSET:
1409 case LFUN_DIALOG_HIDE:
1410 // FIXME: should we check if the dialog is shown?
1413 case LFUN_DIALOG_TOGGLE:
1414 flag.setOnOff(isDialogVisible(cmd.getArg(0)));
1415 // fall through to set "enable"
1416 case LFUN_DIALOG_SHOW: {
1417 string const name = cmd.getArg(0);
1419 enable = name == "aboutlyx"
1420 || name == "file" //FIXME: should be removed.
1422 || name == "texinfo"
1423 || name == "progress"
1424 || name == "compare";
1425 else if (name == "print")
1426 enable = doc_buffer->isExportable("dvi")
1427 && lyxrc.print_command != "none";
1428 else if (name == "character" || name == "symbols") {
1429 if (!buf || buf->isReadonly()
1430 || !currentBufferView()->cursor().inTexted())
1433 // FIXME we should consider passthru
1435 Inset const & in = currentBufferView()->cursor().inset();
1436 enable = !in.getLayout().isPassThru();
1439 else if (name == "latexlog")
1440 enable = FileName(doc_buffer->logName()).isReadableFile();
1441 else if (name == "spellchecker")
1442 enable = theSpellChecker() && !doc_buffer->isReadonly();
1443 else if (name == "vclog")
1444 enable = doc_buffer->lyxvc().inUse();
1448 case LFUN_DIALOG_UPDATE: {
1449 string const name = cmd.getArg(0);
1451 enable = name == "prefs";
1455 case LFUN_COMMAND_EXECUTE:
1457 case LFUN_MENU_OPEN:
1458 // Nothing to check.
1461 case LFUN_COMPLETION_INLINE:
1462 if (!d.current_work_area_
1463 || !d.current_work_area_->completer().inlinePossible(
1464 currentBufferView()->cursor()))
1468 case LFUN_COMPLETION_POPUP:
1469 if (!d.current_work_area_
1470 || !d.current_work_area_->completer().popupPossible(
1471 currentBufferView()->cursor()))
1475 case LFUN_COMPLETION_COMPLETE:
1476 if (!d.current_work_area_
1477 || !d.current_work_area_->completer().inlinePossible(
1478 currentBufferView()->cursor()))
1482 case LFUN_COMPLETION_ACCEPT:
1483 if (!d.current_work_area_
1484 || (!d.current_work_area_->completer().popupVisible()
1485 && !d.current_work_area_->completer().inlineVisible()
1486 && !d.current_work_area_->completer().completionAvailable()))
1490 case LFUN_COMPLETION_CANCEL:
1491 if (!d.current_work_area_
1492 || (!d.current_work_area_->completer().popupVisible()
1493 && !d.current_work_area_->completer().inlineVisible()))
1497 case LFUN_BUFFER_ZOOM_OUT:
1498 enable = doc_buffer && lyxrc.zoom > 10;
1501 case LFUN_BUFFER_ZOOM_IN:
1502 enable = doc_buffer;
1505 case LFUN_BUFFER_NEXT:
1506 case LFUN_BUFFER_PREVIOUS:
1507 // FIXME: should we check is there is an previous or next buffer?
1509 case LFUN_BUFFER_SWITCH:
1510 // toggle on the current buffer, but do not toggle off
1511 // the other ones (is that a good idea?)
1513 && to_utf8(cmd.argument()) == doc_buffer->absFileName())
1514 flag.setOnOff(true);
1517 case LFUN_VC_REGISTER:
1518 enable = doc_buffer && !doc_buffer->lyxvc().inUse();
1520 case LFUN_VC_CHECK_IN:
1521 enable = doc_buffer && doc_buffer->lyxvc().checkInEnabled();
1523 case LFUN_VC_CHECK_OUT:
1524 enable = doc_buffer && doc_buffer->lyxvc().checkOutEnabled();
1526 case LFUN_VC_LOCKING_TOGGLE:
1527 enable = doc_buffer && !doc_buffer->isReadonly()
1528 && doc_buffer->lyxvc().lockingToggleEnabled();
1529 flag.setOnOff(enable && !doc_buffer->lyxvc().locker().empty());
1531 case LFUN_VC_REVERT:
1532 enable = doc_buffer && doc_buffer->lyxvc().inUse();
1534 case LFUN_VC_UNDO_LAST:
1535 enable = doc_buffer && doc_buffer->lyxvc().undoLastEnabled();
1537 case LFUN_VC_REPO_UPDATE:
1538 enable = doc_buffer && doc_buffer->lyxvc().inUse();
1540 case LFUN_VC_COMMAND: {
1541 if (cmd.argument().empty())
1543 if (!doc_buffer && contains(cmd.getArg(0), 'D'))
1548 case LFUN_SERVER_GOTO_FILE_ROW:
1556 flag.setEnabled(false);
1562 static FileName selectTemplateFile()
1564 FileDialog dlg(qt_("Select template file"));
1565 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1566 dlg.setButton1(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
1568 FileDialog::Result result = dlg.open(toqstr(lyxrc.template_path),
1569 QStringList(qt_("LyX Documents (*.lyx)")));
1571 if (result.first == FileDialog::Later)
1573 if (result.second.isEmpty())
1575 return FileName(fromqstr(result.second));
1579 Buffer * GuiView::loadDocument(FileName const & filename, bool tolastfiles)
1583 Buffer * newBuffer = checkAndLoadLyXFile(filename);
1586 message(_("Document not loaded."));
1591 setBuffer(newBuffer);
1593 // scroll to the position when the file was last closed
1594 if (lyxrc.use_lastfilepos) {
1595 LastFilePosSection::FilePos filepos =
1596 theSession().lastFilePos().load(filename);
1597 documentBufferView()->moveToPosition(filepos.pit, filepos.pos, 0, 0);
1601 theSession().lastFiles().add(filename);
1608 void GuiView::openDocument(string const & fname)
1610 string initpath = lyxrc.document_path;
1612 if (documentBufferView()) {
1613 string const trypath = documentBufferView()->buffer().filePath();
1614 // If directory is writeable, use this as default.
1615 if (FileName(trypath).isDirWritable())
1621 if (fname.empty()) {
1622 FileDialog dlg(qt_("Select document to open"), LFUN_FILE_OPEN);
1623 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1624 dlg.setButton2(qt_("Examples|#E#e"),
1625 toqstr(addPath(package().system_support().absFilename(), "examples")));
1627 QStringList filter(qt_("LyX Documents (*.lyx)"));
1628 filter << qt_("LyX-1.3.x Documents (*.lyx13)")
1629 << qt_("LyX-1.4.x Documents (*.lyx14)")
1630 << qt_("LyX-1.5.x Documents (*.lyx15)")
1631 << qt_("LyX-1.6.x Documents (*.lyx16)");
1632 FileDialog::Result result =
1633 dlg.open(toqstr(initpath), filter);
1635 if (result.first == FileDialog::Later)
1638 filename = fromqstr(result.second);
1640 // check selected filename
1641 if (filename.empty()) {
1642 message(_("Canceled."));
1648 // get absolute path of file and add ".lyx" to the filename if
1650 FileName const fullname =
1651 fileSearch(string(), filename, "lyx", support::may_not_exist);
1652 if (!fullname.empty())
1653 filename = fullname.absFilename();
1655 if (!fullname.onlyPath().isDirectory()) {
1656 Alert::warning(_("Invalid filename"),
1657 bformat(_("The directory in the given path\n%1$s\ndoes not exist."),
1658 from_utf8(fullname.absFilename())));
1661 // if the file doesn't exist, let the user create one
1662 if (!fullname.exists()) {
1663 // the user specifically chose this name. Believe him.
1664 Buffer * const b = newFile(filename, string(), true);
1670 docstring const disp_fn = makeDisplayPath(filename);
1671 message(bformat(_("Opening document %1$s..."), disp_fn));
1674 Buffer * buf = loadDocument(fullname);
1676 buf->updateLabels();
1678 buf->errors("Parse");
1679 str2 = bformat(_("Document %1$s opened."), disp_fn);
1680 if (buf->lyxvc().inUse())
1681 str2 += " " + from_utf8(buf->lyxvc().versionString()) +
1682 " " + _("Version control detected.");
1684 str2 = bformat(_("Could not open document %1$s"), disp_fn);
1689 // FIXME: clean that
1690 static bool import(GuiView * lv, FileName const & filename,
1691 string const & format, ErrorList & errorList)
1693 FileName const lyxfile(support::changeExtension(filename.absFilename(), ".lyx"));
1695 string loader_format;
1696 vector<string> loaders = theConverters().loaders();
1697 if (find(loaders.begin(), loaders.end(), format) == loaders.end()) {
1698 for (vector<string>::const_iterator it = loaders.begin();
1699 it != loaders.end(); ++it) {
1700 if (!theConverters().isReachable(format, *it))
1703 string const tofile =
1704 support::changeExtension(filename.absFilename(),
1705 formats.extension(*it));
1706 if (!theConverters().convert(0, filename, FileName(tofile),
1707 filename, format, *it, errorList))
1709 loader_format = *it;
1712 if (loader_format.empty()) {
1713 frontend::Alert::error(_("Couldn't import file"),
1714 bformat(_("No information for importing the format %1$s."),
1715 formats.prettyName(format)));
1719 loader_format = format;
1721 if (loader_format == "lyx") {
1722 Buffer * buf = lv->loadDocument(lyxfile);
1725 buf->updateLabels();
1727 buf->errors("Parse");
1729 Buffer * const b = newFile(lyxfile.absFilename(), string(), true);
1733 bool as_paragraphs = loader_format == "textparagraph";
1734 string filename2 = (loader_format == format) ? filename.absFilename()
1735 : support::changeExtension(filename.absFilename(),
1736 formats.extension(loader_format));
1737 lv->currentBufferView()->insertPlaintextFile(FileName(filename2),
1739 guiApp->setCurrentView(lv);
1740 lyx::dispatch(FuncRequest(LFUN_MARK_OFF));
1747 void GuiView::importDocument(string const & argument)
1750 string filename = split(argument, format, ' ');
1752 LYXERR(Debug::INFO, format << " file: " << filename);
1754 // need user interaction
1755 if (filename.empty()) {
1756 string initpath = lyxrc.document_path;
1757 if (documentBufferView()) {
1758 string const trypath = documentBufferView()->buffer().filePath();
1759 // If directory is writeable, use this as default.
1760 if (FileName(trypath).isDirWritable())
1764 docstring const text = bformat(_("Select %1$s file to import"),
1765 formats.prettyName(format));
1767 FileDialog dlg(toqstr(text), LFUN_BUFFER_IMPORT);
1768 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1769 dlg.setButton2(qt_("Examples|#E#e"),
1770 toqstr(addPath(package().system_support().absFilename(), "examples")));
1772 docstring filter = formats.prettyName(format);
1775 filter += from_utf8(formats.extension(format));
1778 FileDialog::Result result =
1779 dlg.open(toqstr(initpath), fileFilters(toqstr(filter)));
1781 if (result.first == FileDialog::Later)
1784 filename = fromqstr(result.second);
1786 // check selected filename
1787 if (filename.empty())
1788 message(_("Canceled."));
1791 if (filename.empty())
1794 // get absolute path of file
1795 FileName const fullname(support::makeAbsPath(filename));
1797 FileName const lyxfile(support::changeExtension(fullname.absFilename(), ".lyx"));
1799 // Check if the document already is open
1800 Buffer * buf = theBufferList().getBuffer(lyxfile);
1803 if (!closeBuffer()) {
1804 message(_("Canceled."));
1809 docstring const displaypath = makeDisplayPath(lyxfile.absFilename(), 30);
1811 // if the file exists already, and we didn't do
1812 // -i lyx thefile.lyx, warn
1813 if (lyxfile.exists() && fullname != lyxfile) {
1815 docstring text = bformat(_("The document %1$s already exists.\n\n"
1816 "Do you want to overwrite that document?"), displaypath);
1817 int const ret = Alert::prompt(_("Overwrite document?"),
1818 text, 0, 1, _("&Overwrite"), _("&Cancel"));
1821 message(_("Canceled."));
1826 message(bformat(_("Importing %1$s..."), displaypath));
1827 ErrorList errorList;
1828 if (import(this, fullname, format, errorList))
1829 message(_("imported."));
1831 message(_("file not imported!"));
1833 // FIXME (Abdel 12/08/06): Is there a need to display the error list here?
1837 void GuiView::newDocument(string const & filename, bool from_template)
1839 FileName initpath(lyxrc.document_path);
1840 if (documentBufferView()) {
1841 FileName const trypath(documentBufferView()->buffer().filePath());
1842 // If directory is writeable, use this as default.
1843 if (trypath.isDirWritable())
1847 string templatefile;
1848 if (from_template) {
1849 templatefile = selectTemplateFile().absFilename();
1850 if (templatefile.empty())
1855 if (filename.empty())
1856 b = newUnnamedFile(initpath, to_utf8(_("newfile")), templatefile);
1858 b = newFile(filename, templatefile, true);
1863 // If no new document could be created, it is unsure
1864 // whether there is a valid BufferView.
1865 if (currentBufferView())
1866 // Ensure the cursor is correctly positioned on screen.
1867 currentBufferView()->showCursor();
1871 void GuiView::insertLyXFile(docstring const & fname)
1873 BufferView * bv = documentBufferView();
1878 FileName filename(to_utf8(fname));
1880 if (!filename.empty()) {
1881 bv->insertLyXFile(filename);
1885 // Launch a file browser
1887 string initpath = lyxrc.document_path;
1888 string const trypath = bv->buffer().filePath();
1889 // If directory is writeable, use this as default.
1890 if (FileName(trypath).isDirWritable())
1894 FileDialog dlg(qt_("Select LyX document to insert"), LFUN_FILE_INSERT);
1895 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1896 dlg.setButton2(qt_("Examples|#E#e"),
1897 toqstr(addPath(package().system_support().absFilename(),
1900 FileDialog::Result result = dlg.open(toqstr(initpath),
1901 QStringList(qt_("LyX Documents (*.lyx)")));
1903 if (result.first == FileDialog::Later)
1907 filename.set(fromqstr(result.second));
1909 // check selected filename
1910 if (filename.empty()) {
1911 // emit message signal.
1912 message(_("Canceled."));
1916 bv->insertLyXFile(filename);
1920 void GuiView::insertPlaintextFile(docstring const & fname,
1923 BufferView * bv = documentBufferView();
1927 if (!fname.empty() && !FileName::isAbsolute(to_utf8(fname))) {
1928 message(_("Absolute filename expected."));
1933 FileName filename(to_utf8(fname));
1935 if (!filename.empty()) {
1936 bv->insertPlaintextFile(filename, asParagraph);
1940 FileDialog dlg(qt_("Select file to insert"), (asParagraph ?
1941 LFUN_FILE_INSERT_PLAINTEXT_PARA : LFUN_FILE_INSERT_PLAINTEXT));
1943 FileDialog::Result result = dlg.open(toqstr(bv->buffer().filePath()),
1944 QStringList(qt_("All Files (*)")));
1946 if (result.first == FileDialog::Later)
1950 filename.set(fromqstr(result.second));
1952 // check selected filename
1953 if (filename.empty()) {
1954 // emit message signal.
1955 message(_("Canceled."));
1959 bv->insertPlaintextFile(filename, asParagraph);
1963 bool GuiView::renameBuffer(Buffer & b, docstring const & newname)
1965 FileName fname = b.fileName();
1966 FileName const oldname = fname;
1968 if (!newname.empty()) {
1970 fname = support::makeAbsPath(to_utf8(newname), oldname.onlyPath().absFilename());
1972 // Switch to this Buffer.
1975 // No argument? Ask user through dialog.
1977 FileDialog dlg(qt_("Choose a filename to save document as"),
1978 LFUN_BUFFER_WRITE_AS);
1979 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1980 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
1982 if (!isLyXFilename(fname.absFilename()))
1983 fname.changeExtension(".lyx");
1985 FileDialog::Result result =
1986 dlg.save(toqstr(fname.onlyPath().absFilename()),
1987 QStringList(qt_("LyX Documents (*.lyx)")),
1988 toqstr(fname.onlyFileName()));
1990 if (result.first == FileDialog::Later)
1993 fname.set(fromqstr(result.second));
1998 if (!isLyXFilename(fname.absFilename()))
1999 fname.changeExtension(".lyx");
2002 if (FileName(fname).exists()) {
2003 docstring const file = makeDisplayPath(fname.absFilename(), 30);
2004 docstring text = bformat(_("The document %1$s already "
2005 "exists.\n\nDo you want to "
2006 "overwrite that document?"),
2008 int const ret = Alert::prompt(_("Overwrite document?"),
2009 text, 0, 2, _("&Overwrite"), _("&Rename"), _("&Cancel"));
2012 case 1: return renameBuffer(b, docstring());
2013 case 2: return false;
2017 FileName oldauto = b.getAutosaveFilename();
2019 // Ok, change the name of the buffer
2020 b.setFileName(fname.absFilename());
2022 bool unnamed = b.isUnnamed();
2023 b.setUnnamed(false);
2024 b.saveCheckSum(fname);
2026 // bring the autosave file with us, just in case.
2027 b.moveAutosaveFile(oldauto);
2029 if (!saveBuffer(b)) {
2030 oldauto = b.getAutosaveFilename();
2031 b.setFileName(oldname.absFilename());
2032 b.setUnnamed(unnamed);
2033 b.saveCheckSum(oldname);
2034 b.moveAutosaveFile(oldauto);
2042 bool GuiView::saveBuffer(Buffer & b)
2044 if (workArea(b) && workArea(b)->inDialogMode())
2048 return renameBuffer(b, docstring());
2051 theSession().lastFiles().add(b.fileName());
2055 // Switch to this Buffer.
2058 // FIXME: we don't tell the user *WHY* the save failed !!
2059 docstring const file = makeDisplayPath(b.absFileName(), 30);
2060 docstring text = bformat(_("The document %1$s could not be saved.\n\n"
2061 "Do you want to rename the document and "
2062 "try again?"), file);
2063 int const ret = Alert::prompt(_("Rename and save?"),
2064 text, 0, 2, _("&Rename"), _("&Retry"), _("&Cancel"));
2067 if (!renameBuffer(b, docstring()))
2076 return saveBuffer(b);
2080 bool GuiView::hideWorkArea(GuiWorkArea * wa)
2082 return closeWorkArea(wa, false);
2086 bool GuiView::closeWorkArea(GuiWorkArea * wa)
2088 Buffer & buf = wa->bufferView().buffer();
2089 return closeWorkArea(wa, !buf.parent());
2093 bool GuiView::closeBuffer()
2095 GuiWorkArea * wa = currentMainWorkArea();
2096 Buffer & buf = wa->bufferView().buffer();
2097 return wa && closeWorkArea(wa, !buf.parent());
2101 void GuiView::writeSession() const {
2102 GuiWorkArea const * active_wa = currentMainWorkArea();
2103 for (int i = 0; i < d.splitter_->count(); ++i) {
2104 TabWorkArea * twa = d.tabWorkArea(i);
2105 for (int j = 0; j < twa->count(); ++j) {
2106 GuiWorkArea * wa = static_cast<GuiWorkArea *>(twa->widget(j));
2107 Buffer & buf = wa->bufferView().buffer();
2108 theSession().lastOpened().add(buf.fileName(), wa == active_wa);
2114 bool GuiView::closeBufferAll()
2116 // Close the workareas in all other views
2117 QList<int> const ids = guiApp->viewIds();
2118 for (int i = 0; i != ids.size(); ++i) {
2119 if (id_ != ids[i] && !guiApp->view(ids[i]).closeWorkAreaAll())
2123 // Close our own workareas
2124 if (!closeWorkAreaAll())
2127 // Now close the hidden buffers. We prevent hidden buffers from being
2128 // dirty, so we can just close them.
2129 theBufferList().closeAll();
2134 bool GuiView::closeWorkAreaAll()
2136 setCurrentWorkArea(currentMainWorkArea());
2138 // We might be in a situation that there is still a tabWorkArea, but
2139 // there are no tabs anymore. This can happen when we get here after a
2140 // TabWorkArea::lastWorkAreaRemoved() signal. Therefore we count how
2141 // many TabWorkArea's have no documents anymore.
2144 // We have to call count() each time, because it can happen that
2145 // more than one splitter will disappear in one iteration (bug 5998).
2146 for (; d.splitter_->count() > empty_twa; ) {
2147 TabWorkArea * twa = d.tabWorkArea(empty_twa);
2149 if (twa->count() == 0)
2152 setCurrentWorkArea(twa->currentWorkArea());
2153 if (!closeTabWorkArea(twa))
2161 bool GuiView::closeWorkArea(GuiWorkArea * wa, bool close_buffer)
2166 Buffer & buf = wa->bufferView().buffer();
2169 return closeBuffer(buf);
2171 if (!inMultiTabs(wa))
2172 if (!saveBufferIfNeeded(buf, true))
2180 bool GuiView::closeBuffer(Buffer & buf)
2182 // If we are in a close_event all children will be closed in some time,
2183 // so no need to do it here. This will ensure that the children end up
2184 // in the session file in the correct order. If we close the master
2185 // buffer, we can close or release the child buffers here too.
2187 vector<Buffer *> clist = buf.getChildren(false);
2188 for (vector<Buffer *>::const_iterator it = clist.begin();
2189 it != clist.end(); ++it) {
2190 // If a child is dirty, do not close
2191 // without user intervention
2192 //FIXME: should we look in other tabworkareas?
2193 Buffer * child_buf = *it;
2194 GuiWorkArea * child_wa = workArea(*child_buf);
2196 if (!closeWorkArea(child_wa, true))
2199 theBufferList().releaseChild(&buf, child_buf);
2202 // goto bookmark to update bookmark pit.
2203 //FIXME: we should update only the bookmarks related to this buffer!
2204 LYXERR(Debug::DEBUG, "GuiView::closeBuffer()");
2205 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
2206 theLyXFunc().gotoBookmark(i+1, false, false);
2208 if (saveBufferIfNeeded(buf, false)) {
2209 theBufferList().release(&buf);
2216 bool GuiView::closeTabWorkArea(TabWorkArea * twa)
2218 while (twa == d.currentTabWorkArea()) {
2219 twa->setCurrentIndex(twa->count()-1);
2221 GuiWorkArea * wa = twa->currentWorkArea();
2222 Buffer & b = wa->bufferView().buffer();
2224 // We only want to close the buffer if the same buffer is not visible
2225 // in another view, and if this is not a child and if we are closing
2226 // a view (not a tabgroup).
2227 bool const close_buffer =
2228 !inMultiViews(wa) && !b.parent() && closing_;
2230 if (!closeWorkArea(wa, close_buffer))
2237 bool GuiView::saveBufferIfNeeded(Buffer & buf, bool hiding)
2239 if (buf.isClean() || buf.paragraphs().empty())
2242 // Switch to this Buffer.
2247 if (buf.isUnnamed())
2248 file = from_utf8(buf.fileName().onlyFileName());
2250 file = buf.fileName().displayName(30);
2252 // Bring this window to top before asking questions.
2257 if (hiding && buf.isUnnamed()) {
2258 docstring const text = bformat(_("The document %1$s has not been "
2259 "saved yet.\n\nDo you want to save "
2260 "the document?"), file);
2261 ret = Alert::prompt(_("Save new document?"),
2262 text, 0, 1, _("&Save"), _("&Cancel"));
2266 docstring const text = bformat(_("The document %1$s has unsaved changes."
2267 "\n\nDo you want to save the document or discard the changes?"), file);
2268 ret = Alert::prompt(_("Save changed document?"),
2269 text, 0, 2, _("&Save"), _("&Discard"), _("&Cancel"));
2274 if (!saveBuffer(buf))
2278 // if we crash after this we could
2279 // have no autosave file but I guess
2280 // this is really improbable (Jug)
2281 buf.removeAutosaveFile();
2283 // revert all changes
2284 buf.loadLyXFile(buf.fileName());
2294 bool GuiView::inMultiTabs(GuiWorkArea * wa)
2296 Buffer & buf = wa->bufferView().buffer();
2298 for (int i = 0; i != d.splitter_->count(); ++i) {
2299 GuiWorkArea * wa_ = d.tabWorkArea(i)->workArea(buf);
2300 if (wa_ && wa_ != wa)
2303 return inMultiViews(wa);
2307 bool GuiView::inMultiViews(GuiWorkArea * wa)
2309 QList<int> const ids = guiApp->viewIds();
2310 Buffer & buf = wa->bufferView().buffer();
2313 for (int i = 0; i != ids.size() && found_twa <= 1; ++i) {
2317 if (guiApp->view(ids[i]).workArea(buf))
2324 void GuiView::gotoNextOrPreviousBuffer(NextOrPrevious np)
2326 Buffer * const curbuf = documentBufferView()
2327 ? &documentBufferView()->buffer() : 0;
2328 Buffer * nextbuf = curbuf;
2330 if (np == NEXTBUFFER)
2331 nextbuf = theBufferList().next(nextbuf);
2333 nextbuf = theBufferList().previous(nextbuf);
2334 if (nextbuf == curbuf)
2340 if (workArea(*nextbuf))
2347 /// make sure the document is saved
2348 static bool ensureBufferClean(Buffer * buffer)
2350 LASSERT(buffer, return false);
2351 if (buffer->isClean() && !buffer->isUnnamed())
2354 docstring const file = buffer->fileName().displayName(30);
2357 if (!buffer->isUnnamed()) {
2358 text = bformat(_("The document %1$s has unsaved "
2359 "changes.\n\nDo you want to save "
2360 "the document?"), file);
2361 title = _("Save changed document?");
2364 text = bformat(_("The document %1$s has not been "
2365 "saved yet.\n\nDo you want to save "
2366 "the document?"), file);
2367 title = _("Save new document?");
2369 int const ret = Alert::prompt(title, text, 0, 1, _("&Save"), _("&Cancel"));
2372 dispatch(FuncRequest(LFUN_BUFFER_WRITE));
2374 return buffer->isClean() && !buffer->isUnnamed();
2378 void GuiView::reloadBuffer()
2380 Buffer * buf = &documentBufferView()->buffer();
2385 void GuiView::reloadBuffer(Buffer * buf)
2387 FileName filename = buf->fileName();
2388 Buffer const * master = buf->masterBuffer();
2389 bool const is_child = master != buf;
2390 // The user has already confirmed that the changes, if any, should
2391 // be discarded. So we just release the Buffer and don't call closeBuffer();
2392 theBufferList().release(buf);
2393 buf = loadDocument(filename);
2394 docstring const disp_fn = makeDisplayPath(filename.absFilename());
2397 // re-allocate master if necessary
2398 if (is_child && theBufferList().isLoaded(master)
2399 && buf->masterBuffer() != master)
2400 buf->setParent(master);
2401 buf->updateLabels();
2403 buf->errors("Parse");
2404 str = bformat(_("Document %1$s reloaded."), disp_fn);
2406 str = bformat(_("Could not reload document %1$s"), disp_fn);
2412 void GuiView::checkExternallyModifiedBuffers()
2414 BufferList::iterator bit = theBufferList().begin();
2415 BufferList::iterator const bend = theBufferList().end();
2416 for (; bit != bend; ++bit) {
2417 if ((*bit)->isExternallyModified(Buffer::checksum_method)) {
2418 docstring text = bformat(_("Document \n%1$s\n has been externally modified."
2419 " Reload now? Any local changes will be lost."),
2420 from_utf8((*bit)->absFileName()));
2421 int const ret = Alert::prompt(_("Reload externally changed document?"),
2422 text, 0, 1, _("&Reload"), _("&Cancel"));
2430 void GuiView::dispatchVC(FuncRequest const & cmd)
2432 Buffer * buffer = documentBufferView()
2433 ? &(documentBufferView()->buffer()) : 0;
2435 switch (cmd.action) {
2436 case LFUN_VC_REGISTER:
2437 if (!buffer || !ensureBufferClean(buffer))
2439 if (!buffer->lyxvc().inUse()) {
2440 if (buffer->lyxvc().registrer())
2445 case LFUN_VC_CHECK_IN:
2446 if (!buffer || !ensureBufferClean(buffer))
2448 if (buffer->lyxvc().inUse() && !buffer->isReadonly()) {
2449 message(from_utf8(buffer->lyxvc().checkIn()));
2454 case LFUN_VC_CHECK_OUT:
2455 if (!buffer || !ensureBufferClean(buffer))
2457 if (buffer->lyxvc().inUse()) {
2458 message(from_utf8(buffer->lyxvc().checkOut()));
2463 case LFUN_VC_LOCKING_TOGGLE:
2464 LASSERT(buffer, return);
2465 if (!ensureBufferClean(buffer) || buffer->isReadonly())
2467 if (buffer->lyxvc().inUse()) {
2468 string res = buffer->lyxvc().lockingToggle();
2470 frontend::Alert::error(_("Revision control error."),
2471 _("Error when setting the locking property."));
2473 message(from_utf8(res));
2479 case LFUN_VC_REVERT:
2480 LASSERT(buffer, return);
2481 buffer->lyxvc().revert();
2485 case LFUN_VC_UNDO_LAST:
2486 LASSERT(buffer, return);
2487 buffer->lyxvc().undoLast();
2491 case LFUN_VC_REPO_UPDATE:
2492 LASSERT(buffer, return);
2493 if (ensureBufferClean(buffer)) {
2494 string res = buffer->lyxvc().repoUpdate();
2495 message(from_utf8(res));
2496 checkExternallyModifiedBuffers();
2500 case LFUN_VC_COMMAND: {
2501 string flag = cmd.getArg(0);
2502 if (buffer && contains(flag, 'R') && !ensureBufferClean(buffer))
2505 if (contains(flag, 'M')) {
2506 if (!Alert::askForText(message, _("LyX VC: Log Message")))
2509 string path = cmd.getArg(1);
2510 if (contains(path, "$$p") && buffer)
2511 path = subst(path, "$$p", buffer->filePath());
2512 LYXERR(Debug::LYXVC, "Directory: " << path);
2514 if (!pp.isReadableDirectory()) {
2515 lyxerr << _("Directory is not accessible.") << endl;
2518 support::PathChanger p(pp);
2520 string command = cmd.getArg(2);
2521 if (command.empty())
2524 command = subst(command, "$$i", buffer->absFileName());
2525 command = subst(command, "$$p", buffer->filePath());
2527 command = subst(command, "$$m", to_utf8(message));
2528 LYXERR(Debug::LYXVC, "Command: " << command);
2530 one.startscript(Systemcall::Wait, command);
2534 if (contains(flag, 'I'))
2535 buffer->markDirty();
2536 if (contains(flag, 'R'))
2547 void GuiView::openChildDocument(string const & fname)
2549 LASSERT(documentBufferView(), return);
2550 Buffer & buffer = documentBufferView()->buffer();
2551 FileName const filename = support::makeAbsPath(fname, buffer.filePath());
2552 documentBufferView()->saveBookmark(false);
2554 bool parsed = false;
2555 if (theBufferList().exists(filename)) {
2556 child = theBufferList().getBuffer(filename);
2558 message(bformat(_("Opening child document %1$s..."),
2559 makeDisplayPath(filename.absFilename())));
2560 child = loadDocument(filename, false);
2566 // Set the parent name of the child document.
2567 // This makes insertion of citations and references in the child work,
2568 // when the target is in the parent or another child document.
2569 child->setParent(&buffer);
2570 child->masterBuffer()->updateLabels();
2573 child->errors("Parse");
2577 bool GuiView::goToFileRow(string const & argument)
2581 istringstream is(argument);
2582 is >> file_name >> row;
2583 file_name = os::internal_path(file_name);
2585 string const abstmp = package().temp_dir().absFilename();
2586 string const realtmp = package().temp_dir().realPath();
2587 // We have to use os::path_prefix_is() here, instead of
2588 // simply prefixIs(), because the file name comes from
2589 // an external application and may need case adjustment.
2590 if (os::path_prefix_is(file_name, abstmp, os::CASE_ADJUSTED)
2591 || os::path_prefix_is(file_name, realtmp, os::CASE_ADJUSTED)) {
2592 // Needed by inverse dvi search. If it is a file
2593 // in tmpdir, call the apropriated function.
2594 // If tmpdir is a symlink, we may have the real
2595 // path passed back, so we correct for that.
2596 if (!prefixIs(file_name, abstmp))
2597 file_name = subst(file_name, realtmp, abstmp);
2598 buf = theBufferList().getBufferFromTmp(file_name);
2600 // Must replace extension of the file to be .lyx
2601 // and get full path
2602 FileName const s = fileSearch(string(),
2603 support::changeExtension(file_name, ".lyx"), "lyx");
2604 // Either change buffer or load the file
2605 if (theBufferList().exists(s))
2606 buf = theBufferList().getBuffer(s);
2607 else if (s.exists()) {
2608 buf = loadDocument(s);
2609 buf->updateLabels();
2610 buf->errors("Parse");
2613 _("File does not exist: %1$s"),
2614 makeDisplayPath(file_name)));
2619 documentBufferView()->setCursorFromRow(row);
2624 static docstring exportAndDestroy(Buffer * buffer, string const & format)
2626 bool const success = buffer->doExport(format, true);
2629 ? bformat(_("Successful export to format: %1$s"), from_utf8(format))
2630 : bformat(_("Error exporting to format: %1$s"), from_utf8(format));
2634 static docstring previewAndDestroy(Buffer * buffer, string const & format)
2636 bool const success = buffer->preview(format);
2639 ? bformat(_("Successful preview of format: %1$s"), from_utf8(format))
2640 : bformat(_("Error previewing format: %1$s"), from_utf8(format));
2644 bool GuiView::dispatch(FuncRequest const & cmd)
2646 BufferView * bv = currentBufferView();
2647 // By default we won't need any update.
2649 bv->cursor().updateFlags(Update::None);
2651 Buffer * doc_buffer = documentBufferView()
2652 ? &(documentBufferView()->buffer()) : 0;
2654 bool dispatched = true;
2656 if (cmd.origin == FuncRequest::TOC) {
2657 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
2658 toc->doDispatch(bv->cursor(), cmd);
2662 string const argument = to_utf8(cmd.argument());
2664 switch(cmd.action) {
2665 case LFUN_BUFFER_CHILD_OPEN:
2666 openChildDocument(to_utf8(cmd.argument()));
2669 case LFUN_BUFFER_IMPORT:
2670 importDocument(to_utf8(cmd.argument()));
2673 case LFUN_BUFFER_EXPORT: {
2676 if (cmd.argument() == "custom") {
2677 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "sendto"));
2680 if (doc_buffer->doExport(argument, false)) {
2681 message(bformat(_("Error exporting to format: %1$s."),
2687 case LFUN_BUFFER_UPDATE: {
2690 string format = argument;
2691 if (argument.empty())
2692 format = doc_buffer->getDefaultOutputFormat();
2693 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
2694 QFuture<docstring> f = QtConcurrent::run(exportAndDestroy,
2695 doc_buffer->clone(), format);
2696 d.setPreviewFuture(f);
2698 doc_buffer->doExport(format, true);
2702 case LFUN_BUFFER_VIEW: {
2705 string format = argument;
2706 if (argument.empty())
2707 format = doc_buffer->getDefaultOutputFormat();
2708 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
2709 QFuture<docstring> f = QtConcurrent::run(previewAndDestroy,
2710 doc_buffer->clone(), format);
2711 d.setPreviewFuture(f);
2713 doc_buffer->preview(format);
2717 case LFUN_MASTER_BUFFER_UPDATE: {
2720 string format = argument;
2721 Buffer const * master = doc_buffer->masterBuffer();
2722 if (argument.empty())
2723 format = master->getDefaultOutputFormat();
2724 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
2725 QFuture<docstring> f = QtConcurrent::run(exportAndDestroy,
2726 master->clone(), format);
2727 d.setPreviewFuture(f);
2729 master->doExport(format, true);
2733 case LFUN_MASTER_BUFFER_VIEW: {
2734 string format = argument;
2735 Buffer const * master = doc_buffer->masterBuffer();
2736 if (argument.empty())
2737 format = master->getDefaultOutputFormat();
2738 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
2739 QFuture<docstring> f = QtConcurrent::run(previewAndDestroy,
2740 master->clone(), format);
2741 d.setPreviewFuture(f);
2743 master->preview(format);
2747 case LFUN_BUFFER_SWITCH:
2748 if (FileName::isAbsolute(to_utf8(cmd.argument()))) {
2750 theBufferList().getBuffer(FileName(to_utf8(cmd.argument())));
2754 message(_("Document not loaded"));
2758 case LFUN_BUFFER_NEXT:
2759 gotoNextOrPreviousBuffer(NEXTBUFFER);
2762 case LFUN_BUFFER_PREVIOUS:
2763 gotoNextOrPreviousBuffer(PREVBUFFER);
2766 case LFUN_COMMAND_EXECUTE: {
2767 bool const show_it = cmd.argument() != "off";
2768 // FIXME: this is a hack, "minibuffer" should not be
2770 if (GuiToolbar * t = toolbar("minibuffer")) {
2771 t->setVisible(show_it);
2772 if (show_it && t->commandBuffer())
2773 t->commandBuffer()->setFocus();
2777 case LFUN_DROP_LAYOUTS_CHOICE:
2778 d.layout_->showPopup();
2781 case LFUN_MENU_OPEN:
2782 if (QMenu * menu = guiApp->menus().menu(toqstr(cmd.argument()), *this))
2783 menu->exec(QCursor::pos());
2786 case LFUN_FILE_INSERT:
2787 insertLyXFile(cmd.argument());
2789 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
2790 insertPlaintextFile(cmd.argument(), true);
2793 case LFUN_FILE_INSERT_PLAINTEXT:
2794 insertPlaintextFile(cmd.argument(), false);
2797 case LFUN_BUFFER_RELOAD: {
2798 LASSERT(doc_buffer, break);
2799 docstring const file = makeDisplayPath(doc_buffer->absFileName(), 20);
2800 docstring text = bformat(_("Any changes will be lost. Are you sure "
2801 "you want to revert to the saved version of the document %1$s?"), file);
2802 int const ret = Alert::prompt(_("Revert to saved document?"),
2803 text, 1, 1, _("&Revert"), _("&Cancel"));
2806 doc_buffer->markClean();
2812 case LFUN_BUFFER_WRITE:
2813 LASSERT(doc_buffer, break);
2814 saveBuffer(*doc_buffer);
2817 case LFUN_BUFFER_WRITE_AS:
2818 LASSERT(doc_buffer, break);
2819 renameBuffer(*doc_buffer, cmd.argument());
2822 case LFUN_BUFFER_WRITE_ALL: {
2823 Buffer * first = theBufferList().first();
2826 message(_("Saving all documents..."));
2827 // We cannot use a for loop as the buffer list cycles.
2830 if (!b->isClean()) {
2832 LYXERR(Debug::ACTION, "Saved " << b->absFileName());
2834 b = theBufferList().next(b);
2835 } while (b != first);
2836 message(_("All documents saved."));
2840 case LFUN_BUFFER_CLOSE:
2844 case LFUN_BUFFER_CLOSE_ALL:
2848 case LFUN_TOOLBAR_TOGGLE: {
2849 string const name = cmd.getArg(0);
2850 if (GuiToolbar * t = toolbar(name))
2855 case LFUN_DIALOG_UPDATE: {
2856 string const name = to_utf8(cmd.argument());
2857 if (currentBufferView()) {
2858 Inset * inset = currentBufferView()->editedInset(name);
2859 // Can only update a dialog connected to an existing inset
2862 // FIXME: get rid of this indirection; GuiView ask the inset
2863 // if he is kind enough to update itself...
2864 FuncRequest fr(LFUN_INSET_DIALOG_UPDATE, cmd.argument());
2865 inset->dispatch(currentBufferView()->cursor(), fr);
2866 } else if (name == "paragraph") {
2867 lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
2868 } else if (name == "prefs" || name == "document") {
2869 updateDialog(name, string());
2874 case LFUN_DIALOG_TOGGLE: {
2875 if (isDialogVisible(cmd.getArg(0)))
2876 dispatch(FuncRequest(LFUN_DIALOG_HIDE, cmd.argument()));
2878 dispatch(FuncRequest(LFUN_DIALOG_SHOW, cmd.argument()));
2882 case LFUN_DIALOG_DISCONNECT_INSET:
2883 disconnectDialog(to_utf8(cmd.argument()));
2886 case LFUN_DIALOG_HIDE: {
2887 guiApp->hideDialogs(to_utf8(cmd.argument()), 0);
2891 case LFUN_DIALOG_SHOW: {
2892 string const name = cmd.getArg(0);
2893 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
2895 if (name == "character") {
2896 data = freefont2string();
2898 showDialog("character", data);
2899 } else if (name == "latexlog") {
2900 Buffer::LogType type;
2901 string const logfile = doc_buffer->logName(&type);
2903 case Buffer::latexlog:
2906 case Buffer::buildlog:
2910 data += Lexer::quoteString(logfile);
2911 showDialog("log", data);
2912 } else if (name == "vclog") {
2913 string const data = "vc " +
2914 Lexer::quoteString(doc_buffer->lyxvc().getLogFile());
2915 showDialog("log", data);
2916 } else if (name == "symbols") {
2917 data = bv->cursor().getEncoding()->name();
2919 showDialog("symbols", data);
2921 } else if (name == "prefs" && isFullScreen()) {
2922 FuncRequest fr(LFUN_INSET_INSERT, "fullscreen");
2924 showDialog("prefs", data);
2926 showDialog(name, data);
2931 message(cmd.argument());
2934 case LFUN_UI_TOGGLE:
2936 // Make sure the keyboard focus stays in the work area.
2940 case LFUN_SPLIT_VIEW: {
2941 LASSERT(doc_buffer, break);
2942 string const orientation = cmd.getArg(0);
2943 d.splitter_->setOrientation(orientation == "vertical"
2944 ? Qt::Vertical : Qt::Horizontal);
2945 TabWorkArea * twa = addTabWorkArea();
2946 GuiWorkArea * wa = twa->addWorkArea(*doc_buffer, *this);
2947 setCurrentWorkArea(wa);
2950 case LFUN_CLOSE_TAB_GROUP:
2951 if (TabWorkArea * twa = d.currentTabWorkArea()) {
2952 closeTabWorkArea(twa);
2953 d.current_work_area_ = 0;
2954 twa = d.currentTabWorkArea();
2955 // Switch to the next GuiWorkArea in the found TabWorkArea.
2957 // Make sure the work area is up to date.
2958 setCurrentWorkArea(twa->currentWorkArea());
2960 setCurrentWorkArea(0);
2965 case LFUN_COMPLETION_INLINE:
2966 if (d.current_work_area_)
2967 d.current_work_area_->completer().showInline();
2970 case LFUN_COMPLETION_POPUP:
2971 if (d.current_work_area_)
2972 d.current_work_area_->completer().showPopup();
2976 case LFUN_COMPLETION_COMPLETE:
2977 if (d.current_work_area_)
2978 d.current_work_area_->completer().tab();
2981 case LFUN_COMPLETION_CANCEL:
2982 if (d.current_work_area_) {
2983 if (d.current_work_area_->completer().popupVisible())
2984 d.current_work_area_->completer().hidePopup();
2986 d.current_work_area_->completer().hideInline();
2990 case LFUN_COMPLETION_ACCEPT:
2991 if (d.current_work_area_)
2992 d.current_work_area_->completer().activate();
2995 case LFUN_BUFFER_ZOOM_IN:
2996 case LFUN_BUFFER_ZOOM_OUT:
2997 if (cmd.argument().empty()) {
2998 if (cmd.action == LFUN_BUFFER_ZOOM_IN)
3003 lyxrc.zoom += convert<int>(cmd.argument());
3005 if (lyxrc.zoom < 10)
3008 // The global QPixmapCache is used in GuiPainter to cache text
3009 // painting so we must reset it.
3010 QPixmapCache::clear();
3011 guiApp->fontLoader().update();
3012 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
3015 case LFUN_VC_REGISTER:
3016 case LFUN_VC_CHECK_IN:
3017 case LFUN_VC_CHECK_OUT:
3018 case LFUN_VC_REPO_UPDATE:
3019 case LFUN_VC_LOCKING_TOGGLE:
3020 case LFUN_VC_REVERT:
3021 case LFUN_VC_UNDO_LAST:
3022 case LFUN_VC_COMMAND:
3026 case LFUN_SERVER_GOTO_FILE_ROW:
3027 goToFileRow(to_utf8(cmd.argument()));
3035 // Part of automatic menu appearance feature.
3036 if (isFullScreen()) {
3037 if (menuBar()->isVisible() && lyxrc.full_screen_menubar)
3039 if (statusBar()->isVisible())
3040 statusBar()->hide();
3047 void GuiView::lfunUiToggle(FuncRequest const & cmd)
3049 string const arg = cmd.getArg(0);
3050 if (arg == "scrollbar") {
3051 // hide() is of no help
3052 if (d.current_work_area_->verticalScrollBarPolicy() ==
3053 Qt::ScrollBarAlwaysOff)
3055 d.current_work_area_->setVerticalScrollBarPolicy(
3056 Qt::ScrollBarAsNeeded);
3058 d.current_work_area_->setVerticalScrollBarPolicy(
3059 Qt::ScrollBarAlwaysOff);
3062 if (arg == "statusbar") {
3063 statusBar()->setVisible(!statusBar()->isVisible());
3066 if (arg == "menubar") {
3067 menuBar()->setVisible(!menuBar()->isVisible());
3070 #if QT_VERSION >= 0x040300
3071 if (arg == "frame") {
3073 getContentsMargins(&l, &t, &r, &b);
3074 //are the frames in default state?
3075 d.current_work_area_->setFrameStyle(QFrame::NoFrame);
3077 setContentsMargins(-2, -2, -2, -2);
3079 setContentsMargins(0, 0, 0, 0);
3084 if (arg == "fullscreen") {
3089 message(bformat("LFUN_UI_TOGGLE " + _("%1$s unknown command!"), from_utf8(arg)));
3093 void GuiView::toggleFullScreen()
3095 if (isFullScreen()) {
3096 for (int i = 0; i != d.splitter_->count(); ++i)
3097 d.tabWorkArea(i)->setFullScreen(false);
3098 #if QT_VERSION >= 0x040300
3099 setContentsMargins(0, 0, 0, 0);
3101 setWindowState(windowState() ^ Qt::WindowFullScreen);
3104 statusBar()->show();
3107 hideDialogs("prefs", 0);
3108 for (int i = 0; i != d.splitter_->count(); ++i)
3109 d.tabWorkArea(i)->setFullScreen(true);
3110 #if QT_VERSION >= 0x040300
3111 setContentsMargins(-2, -2, -2, -2);
3114 setWindowState(windowState() ^ Qt::WindowFullScreen);
3115 statusBar()->hide();
3116 if (lyxrc.full_screen_menubar)
3118 if (lyxrc.full_screen_toolbars) {
3119 ToolbarMap::iterator end = d.toolbars_.end();
3120 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
3125 // give dialogs like the TOC a chance to adapt
3130 Buffer const * GuiView::updateInset(Inset const * inset)
3132 if (!d.current_work_area_)
3136 d.current_work_area_->scheduleRedraw();
3138 return &d.current_work_area_->bufferView().buffer();
3142 void GuiView::restartCursor()
3144 /* When we move around, or type, it's nice to be able to see
3145 * the cursor immediately after the keypress.
3147 if (d.current_work_area_)
3148 d.current_work_area_->startBlinkingCursor();
3150 // Take this occasion to update the other GUI elements.
3156 void GuiView::updateCompletion(Cursor & cur, bool start, bool keep)
3158 if (d.current_work_area_)
3159 d.current_work_area_->completer().updateVisibility(cur, start, keep);
3164 // This list should be kept in sync with the list of insets in
3165 // src/insets/Inset.cpp. I.e., if a dialog goes with an inset, the
3166 // dialog should have the same name as the inset.
3167 // Changes should be also recorded in LFUN_DIALOG_SHOW doxygen
3168 // docs in LyXAction.cpp.
3170 char const * const dialognames[] = {
3171 "aboutlyx", "bibitem", "bibtex", "box", "branch", "changes", "character",
3172 "citation", "compare", "document", "errorlist", "ert", "external", "file",
3173 "findreplace", "findreplaceadv", "float", "graphics", "href", "include",
3174 "index", "index_print", "info", "listings", "label", "log", "mathdelimiter",
3175 "mathmatrix", "mathspace", "nomenclature", "nomencl_print", "note",
3176 "paragraph", "phantom", "prefs", "print", "ref", "sendto", "space",
3177 "spellchecker", "symbols", "tabular", "tabularcreate", "thesaurus", "texinfo",
3178 "toc", "view-source", "vspace", "wrap", "progress" };
3180 char const * const * const end_dialognames =
3181 dialognames + (sizeof(dialognames) / sizeof(char *));
3185 cmpCStr(char const * name) : name_(name) {}
3186 bool operator()(char const * other) {
3187 return strcmp(other, name_) == 0;
3194 bool isValidName(string const & name)
3196 return find_if(dialognames, end_dialognames,
3197 cmpCStr(name.c_str())) != end_dialognames;
3203 void GuiView::resetDialogs()
3205 // Make sure that no LFUN uses any LyXView.
3206 guiApp->setCurrentView(0);
3209 constructToolbars();
3210 guiApp->menus().fillMenuBar(menuBar(), this, false);
3211 d.layout_->updateContents(true);
3212 // Now update controls with current buffer.
3213 guiApp->setCurrentView(this);
3219 Dialog * GuiView::findOrBuild(string const & name, bool hide_it)
3221 if (!isValidName(name))
3224 map<string, DialogPtr>::iterator it = d.dialogs_.find(name);
3226 if (it != d.dialogs_.end()) {
3228 it->second->hideView();
3229 return it->second.get();
3232 Dialog * dialog = build(name);
3233 d.dialogs_[name].reset(dialog);
3234 if (lyxrc.allow_geometry_session)
3235 dialog->restoreSession();
3242 void GuiView::showDialog(string const & name, string const & data,
3250 Dialog * dialog = findOrBuild(name, false);
3252 dialog->showData(data);
3253 if (inset && currentBufferView())
3254 currentBufferView()->editInset(name, inset);
3257 catch (ExceptionMessage const & ex) {
3265 bool GuiView::isDialogVisible(string const & name) const
3267 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3268 if (it == d.dialogs_.end())
3270 return it->second.get()->isVisibleView() && !it->second.get()->isClosing();
3274 void GuiView::hideDialog(string const & name, Inset * inset)
3276 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3277 if (it == d.dialogs_.end())
3280 if (inset && currentBufferView()
3281 && inset != currentBufferView()->editedInset(name))
3284 Dialog * const dialog = it->second.get();
3285 if (dialog->isVisibleView())
3287 if (currentBufferView())
3288 currentBufferView()->editInset(name, 0);
3292 void GuiView::disconnectDialog(string const & name)
3294 if (!isValidName(name))
3296 if (currentBufferView())
3297 currentBufferView()->editInset(name, 0);
3301 void GuiView::hideAll() const
3303 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
3304 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3306 for(; it != end; ++it)
3307 it->second->hideView();
3311 void GuiView::updateDialogs()
3313 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
3314 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3316 for(; it != end; ++it) {
3317 Dialog * dialog = it->second.get();
3318 if (dialog && dialog->isVisibleView())
3319 dialog->checkStatus();
3326 // will be replaced by a proper factory...
3327 Dialog * createGuiAbout(GuiView & lv);
3328 Dialog * createGuiBibitem(GuiView & lv);
3329 Dialog * createGuiBibtex(GuiView & lv);
3330 Dialog * createGuiBox(GuiView & lv);
3331 Dialog * createGuiBranch(GuiView & lv);
3332 Dialog * createGuiChanges(GuiView & lv);
3333 Dialog * createGuiCharacter(GuiView & lv);
3334 Dialog * createGuiCitation(GuiView & lv);
3335 Dialog * createGuiCompare(GuiView & lv);
3336 Dialog * createGuiDelimiter(GuiView & lv);
3337 Dialog * createGuiDocument(GuiView & lv);
3338 Dialog * createGuiErrorList(GuiView & lv);
3339 Dialog * createGuiERT(GuiView & lv);
3340 Dialog * createGuiExternal(GuiView & lv);
3341 Dialog * createGuiFloat(GuiView & lv);
3342 Dialog * createGuiGraphics(GuiView & lv);
3343 Dialog * createGuiInclude(GuiView & lv);
3344 Dialog * createGuiIndex(GuiView & lv);
3345 Dialog * createGuiInfo(GuiView & lv);
3346 Dialog * createGuiLabel(GuiView & lv);
3347 Dialog * createGuiListings(GuiView & lv);
3348 Dialog * createGuiLog(GuiView & lv);
3349 Dialog * createGuiMathHSpace(GuiView & lv);
3350 Dialog * createGuiMathMatrix(GuiView & lv);
3351 Dialog * createGuiNomenclature(GuiView & lv);
3352 Dialog * createGuiNote(GuiView & lv);
3353 Dialog * createGuiParagraph(GuiView & lv);
3354 Dialog * createGuiPhantom(GuiView & lv);
3355 Dialog * createGuiPreferences(GuiView & lv);
3356 Dialog * createGuiPrint(GuiView & lv);
3357 Dialog * createGuiPrintindex(GuiView & lv);
3358 Dialog * createGuiPrintNomencl(GuiView & lv);
3359 Dialog * createGuiRef(GuiView & lv);
3360 Dialog * createGuiSearch(GuiView & lv);
3361 Dialog * createGuiSearchAdv(GuiView & lv);
3362 Dialog * createGuiSendTo(GuiView & lv);
3363 Dialog * createGuiShowFile(GuiView & lv);
3364 Dialog * createGuiSpellchecker(GuiView & lv);
3365 Dialog * createGuiSymbols(GuiView & lv);
3366 Dialog * createGuiTabularCreate(GuiView & lv);
3367 Dialog * createGuiTabular(GuiView & lv);
3368 Dialog * createGuiTexInfo(GuiView & lv);
3369 Dialog * createGuiTextHSpace(GuiView & lv);
3370 Dialog * createGuiToc(GuiView & lv);
3371 Dialog * createGuiThesaurus(GuiView & lv);
3372 Dialog * createGuiHyperlink(GuiView & lv);
3373 Dialog * createGuiVSpace(GuiView & lv);
3374 Dialog * createGuiViewSource(GuiView & lv);
3375 Dialog * createGuiWrap(GuiView & lv);
3376 Dialog * createGuiProgress(GuiView & lv);
3378 Dialog * GuiView::build(string const & name)
3380 LASSERT(isValidName(name), return 0);
3382 if (name == "aboutlyx")
3383 return createGuiAbout(*this);
3384 if (name == "bibitem")
3385 return createGuiBibitem(*this);
3386 if (name == "bibtex")
3387 return createGuiBibtex(*this);
3389 return createGuiBox(*this);
3390 if (name == "branch")
3391 return createGuiBranch(*this);
3392 if (name == "changes")
3393 return createGuiChanges(*this);
3394 if (name == "character")
3395 return createGuiCharacter(*this);
3396 if (name == "citation")
3397 return createGuiCitation(*this);
3398 if (name == "compare")
3399 return createGuiCompare(*this);
3400 if (name == "document")
3401 return createGuiDocument(*this);
3402 if (name == "errorlist")
3403 return createGuiErrorList(*this);
3405 return createGuiERT(*this);
3406 if (name == "external")
3407 return createGuiExternal(*this);
3409 return createGuiShowFile(*this);
3410 if (name == "findreplace")
3411 return createGuiSearch(*this);
3412 if (name == "findreplaceadv")
3413 return createGuiSearchAdv(*this);
3414 if (name == "float")
3415 return createGuiFloat(*this);
3416 if (name == "graphics")
3417 return createGuiGraphics(*this);
3419 return createGuiHyperlink(*this);
3420 if (name == "include")
3421 return createGuiInclude(*this);
3422 if (name == "index")
3423 return createGuiIndex(*this);
3424 if (name == "index_print")
3425 return createGuiPrintindex(*this);
3427 return createGuiInfo(*this);
3428 if (name == "label")
3429 return createGuiLabel(*this);
3430 if (name == "listings")
3431 return createGuiListings(*this);
3433 return createGuiLog(*this);
3434 if (name == "mathdelimiter")
3435 return createGuiDelimiter(*this);
3436 if (name == "mathspace")
3437 return createGuiMathHSpace(*this);
3438 if (name == "mathmatrix")
3439 return createGuiMathMatrix(*this);
3440 if (name == "nomenclature")
3441 return createGuiNomenclature(*this);
3442 if (name == "nomencl_print")
3443 return createGuiPrintNomencl(*this);
3445 return createGuiNote(*this);
3446 if (name == "paragraph")
3447 return createGuiParagraph(*this);
3448 if (name == "phantom")
3449 return createGuiPhantom(*this);
3450 if (name == "prefs")
3451 return createGuiPreferences(*this);
3452 if (name == "print")
3453 return createGuiPrint(*this);
3455 return createGuiRef(*this);
3456 if (name == "sendto")
3457 return createGuiSendTo(*this);
3458 if (name == "space")
3459 return createGuiTextHSpace(*this);
3460 if (name == "spellchecker")
3461 return createGuiSpellchecker(*this);
3462 if (name == "symbols")
3463 return createGuiSymbols(*this);
3464 if (name == "tabular")
3465 return createGuiTabular(*this);
3466 if (name == "tabularcreate")
3467 return createGuiTabularCreate(*this);
3468 if (name == "texinfo")
3469 return createGuiTexInfo(*this);
3470 if (name == "thesaurus")
3471 return createGuiThesaurus(*this);
3473 return createGuiToc(*this);
3474 if (name == "view-source")
3475 return createGuiViewSource(*this);
3476 if (name == "vspace")
3477 return createGuiVSpace(*this);
3479 return createGuiWrap(*this);
3480 if (name == "progress")
3481 return createGuiProgress(*this);
3487 } // namespace frontend
3490 #include "moc_GuiView.cpp"