3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Lars Gullik Bjønnes
8 * \author Abdelrazak Younes
11 * Full author contact details are available in file CREDITS.
19 #include "FileDialog.h"
20 #include "FontLoader.h"
21 #include "GuiApplication.h"
22 #include "GuiCommandBuffer.h"
23 #include "GuiCompleter.h"
24 #include "GuiWorkArea.h"
25 #include "GuiKeySymbol.h"
27 #include "GuiToolbar.h"
28 #include "LayoutBox.h"
32 #include "qt_helpers.h"
34 #include "frontends/alert.h"
36 #include "buffer_funcs.h"
38 #include "BufferList.h"
39 #include "BufferParams.h"
40 #include "BufferView.h"
41 #include "Converter.h"
43 #include "CutAndPaste.h"
45 #include "ErrorList.h"
47 #include "FuncStatus.h"
48 #include "FuncRequest.h"
52 #include "LyXAction.h"
57 #include "Paragraph.h"
58 #include "SpellChecker.h"
59 #include "TextClass.h"
64 #include "support/convert.h"
65 #include "support/debug.h"
66 #include "support/ExceptionMessage.h"
67 #include "support/FileName.h"
68 #include "support/filetools.h"
69 #include "support/gettext.h"
70 #include "support/filetools.h"
71 #include "support/ForkedCalls.h"
72 #include "support/lassert.h"
73 #include "support/lstrings.h"
74 #include "support/os.h"
75 #include "support/Package.h"
76 #include "support/Path.h"
77 #include "support/Systemcall.h"
78 #include "support/Timeout.h"
79 #include "support/ProgressInterface.h"
80 #include "GuiProgress.h"
83 #include <QApplication>
84 #include <QCloseEvent>
86 #include <QDesktopWidget>
87 #include <QDragEnterEvent>
94 #include <QPixmapCache>
96 #include <QPushButton>
100 #include <QStackedWidget>
101 #include <QStatusBar>
105 #include <QScrollBar>
107 #define EXPORT_in_THREAD 1
109 // QtConcurrent was introduced in Qt 4.4
110 #if (QT_VERSION >= 0x040400)
112 #include <QFutureWatcher>
113 #include <QtConcurrentRun>
116 #include <boost/bind.hpp>
120 #ifdef HAVE_SYS_TIME_H
121 # include <sys/time.h>
128 using namespace lyx::support;
135 class BackgroundWidget : public QWidget
140 LYXERR(Debug::GUI, "show banner: " << lyxrc.show_banner);
141 /// The text to be written on top of the pixmap
142 QString const text = lyx_version ?
143 qt_("version ") + lyx_version : qt_("unknown version");
144 splash_ = getPixmap("images/", "banner", "png");
146 QPainter pain(&splash_);
147 pain.setPen(QColor(0, 0, 0));
149 // The font used to display the version info
150 font.setStyleHint(QFont::SansSerif);
151 font.setWeight(QFont::Bold);
152 font.setPointSize(int(toqstr(lyxrc.font_sizes[FONT_SIZE_LARGE]).toDouble()));
154 pain.drawText(260, 15, text);
157 void paintEvent(QPaintEvent *)
159 int x = (width() - splash_.width()) / 2;
160 int y = (height() - splash_.height()) / 2;
162 pain.drawPixmap(x, y, splash_);
170 /// Toolbar store providing access to individual toolbars by name.
171 typedef map<string, GuiToolbar *> ToolbarMap;
173 typedef boost::shared_ptr<Dialog> DialogPtr;
178 struct GuiView::GuiViewPrivate
180 GuiViewPrivate(GuiView * gv)
181 : gv_(gv), current_work_area_(0), current_main_work_area_(0),
182 layout_(0), autosave_timeout_(5000),
185 // hardcode here the platform specific icon size
186 smallIconSize = 14; // scaling problems
187 normalIconSize = 20; // ok, default
188 bigIconSize = 26; // better for some math icons
190 splitter_ = new QSplitter;
191 bg_widget_ = new BackgroundWidget;
192 stack_widget_ = new QStackedWidget;
193 stack_widget_->addWidget(bg_widget_);
194 stack_widget_->addWidget(splitter_);
196 progress = new GuiProgress(gv);
203 delete stack_widget_;
207 QMenu * toolBarPopup(GuiView * parent)
209 // FIXME: translation
210 QMenu * menu = new QMenu(parent);
211 QActionGroup * iconSizeGroup = new QActionGroup(parent);
213 QAction * smallIcons = new QAction(iconSizeGroup);
214 smallIcons->setText(qt_("Small-sized icons"));
215 smallIcons->setCheckable(true);
216 QObject::connect(smallIcons, SIGNAL(triggered()),
217 parent, SLOT(smallSizedIcons()));
218 menu->addAction(smallIcons);
220 QAction * normalIcons = new QAction(iconSizeGroup);
221 normalIcons->setText(qt_("Normal-sized icons"));
222 normalIcons->setCheckable(true);
223 QObject::connect(normalIcons, SIGNAL(triggered()),
224 parent, SLOT(normalSizedIcons()));
225 menu->addAction(normalIcons);
227 QAction * bigIcons = new QAction(iconSizeGroup);
228 bigIcons->setText(qt_("Big-sized icons"));
229 bigIcons->setCheckable(true);
230 QObject::connect(bigIcons, SIGNAL(triggered()),
231 parent, SLOT(bigSizedIcons()));
232 menu->addAction(bigIcons);
234 unsigned int cur = parent->iconSize().width();
235 if ( cur == parent->d.smallIconSize)
236 smallIcons->setChecked(true);
237 else if (cur == parent->d.normalIconSize)
238 normalIcons->setChecked(true);
239 else if (cur == parent->d.bigIconSize)
240 bigIcons->setChecked(true);
247 stack_widget_->setCurrentWidget(bg_widget_);
248 bg_widget_->setUpdatesEnabled(true);
251 TabWorkArea * tabWorkArea(int i)
253 return dynamic_cast<TabWorkArea *>(splitter_->widget(i));
256 TabWorkArea * currentTabWorkArea()
258 if (splitter_->count() == 1)
259 // The first TabWorkArea is always the first one, if any.
260 return tabWorkArea(0);
262 for (int i = 0; i != splitter_->count(); ++i) {
263 TabWorkArea * twa = tabWorkArea(i);
264 if (current_main_work_area_ == twa->currentWorkArea())
268 // None has the focus so we just take the first one.
269 return tabWorkArea(0);
272 void setPreviewFuture(QFuture<docstring> const & f)
274 if (preview_watcher_.isRunning())
275 preview_watcher_.waitForFinished();
276 preview_watcher_.setFuture(f);
277 connect(&preview_watcher_, SIGNAL(finished()), gv_,
278 SLOT(threadFinished()));
283 GuiWorkArea * current_work_area_;
284 GuiWorkArea * current_main_work_area_;
285 QSplitter * splitter_;
286 QStackedWidget * stack_widget_;
287 BackgroundWidget * bg_widget_;
289 ToolbarMap toolbars_;
290 GuiProgress* progress;
291 /// The main layout box.
293 * \warning Don't Delete! The layout box is actually owned by
294 * whichever toolbar contains it. All the GuiView class needs is a
295 * means of accessing it.
297 * FIXME: replace that with a proper model so that we are not limited
298 * to only one dialog.
303 map<string, DialogPtr> dialogs_;
305 unsigned int smallIconSize;
306 unsigned int normalIconSize;
307 unsigned int bigIconSize;
309 QTimer statusbar_timer_;
310 /// auto-saving of buffers
311 Timeout autosave_timeout_;
312 /// flag against a race condition due to multiclicks, see bug #1119
316 TocModels toc_models_;
318 #if (QT_VERSION >= 0x040400)
320 QFutureWatcher<docstring> autosave_watcher_;
321 QFutureWatcher<docstring> preview_watcher_;
326 GuiView::GuiView(int id)
327 : d(*new GuiViewPrivate(this)), id_(id), closing_(false)
329 // GuiToolbars *must* be initialised before the menu bar.
330 normalSizedIcons(); // at least on Mac the default is 32 otherwise, which is huge
333 // set ourself as the current view. This is needed for the menu bar
334 // filling, at least for the static special menu item on Mac. Otherwise
335 // they are greyed out.
336 guiApp->setCurrentView(this);
338 // Fill up the menu bar.
339 guiApp->menus().fillMenuBar(menuBar(), this, true);
341 setCentralWidget(d.stack_widget_);
343 // Start autosave timer
344 if (lyxrc.autosave) {
345 d.autosave_timeout_.timeout.connect(boost::bind(&GuiView::autoSave, this));
346 d.autosave_timeout_.setTimeout(lyxrc.autosave * 1000);
347 d.autosave_timeout_.start();
349 connect(&d.statusbar_timer_, SIGNAL(timeout()),
350 this, SLOT(clearMessage()));
352 // We don't want to keep the window in memory if it is closed.
353 setAttribute(Qt::WA_DeleteOnClose, true);
355 #if (!defined(Q_WS_WIN) && !defined(Q_WS_MACX))
356 // assign an icon to main form. We do not do it under Qt/Win or Qt/Mac,
357 // since the icon is provided in the application bundle.
358 setWindowIcon(getPixmap("images/", "lyx", "png"));
362 setAcceptDrops(true);
364 statusBar()->setSizeGripEnabled(true);
366 // Forbid too small unresizable window because it can happen
367 // with some window manager under X11.
368 setMinimumSize(300, 200);
370 if (lyxrc.allow_geometry_session) {
371 // Now take care of session management.
376 // no session handling, default to a sane size.
377 setGeometry(50, 50, 690, 510);
380 // clear session data if any.
382 settings.remove("views");
384 #if (QT_VERSION >= 0x040400)
385 connect(&d.autosave_watcher_, SIGNAL(finished()), this,
386 SLOT(threadFinished()));
397 void GuiView::threadFinished()
399 #if (QT_VERSION >= 0x040400)
400 QFutureWatcher<docstring> const * watcher =
401 static_cast<QFutureWatcher<docstring> const *>(sender());
402 message(watcher->result());
407 void GuiView::saveLayout() const
410 settings.beginGroup("views");
411 settings.beginGroup(QString::number(id_));
413 settings.setValue("pos", pos());
414 settings.setValue("size", size());
416 settings.setValue("geometry", saveGeometry());
418 settings.setValue("layout", saveState(0));
419 settings.setValue("icon_size", iconSize());
423 bool GuiView::restoreLayout()
426 settings.beginGroup("views");
427 settings.beginGroup(QString::number(id_));
428 QString const icon_key = "icon_size";
429 if (!settings.contains(icon_key))
432 //code below is skipped when when ~/.config/LyX is (re)created
433 setIconSize(settings.value(icon_key).toSize());
435 QPoint pos = settings.value("pos", QPoint(50, 50)).toPoint();
436 QSize size = settings.value("size", QSize(690, 510)).toSize();
440 // Work-around for bug #6034: the window ends up in an undetermined
441 // state when trying to restore a maximized window when it is
442 // already maximized.
443 if (!(windowState() & Qt::WindowMaximized))
444 if (!restoreGeometry(settings.value("geometry").toByteArray()))
445 setGeometry(50, 50, 690, 510);
447 // Make sure layout is correctly oriented.
448 setLayoutDirection(qApp->layoutDirection());
450 // Allow the toc and view-source dock widget to be restored if needed.
452 if ((dialog = findOrBuild("toc", true)))
453 // see bug 5082. At least setup title and enabled state.
454 // Visibility will be adjusted by restoreState below.
455 dialog->prepareView();
456 if ((dialog = findOrBuild("view-source", true)))
457 dialog->prepareView();
459 if (!restoreState(settings.value("layout").toByteArray(), 0))
466 GuiToolbar * GuiView::toolbar(string const & name)
468 ToolbarMap::iterator it = d.toolbars_.find(name);
469 if (it != d.toolbars_.end())
472 LYXERR(Debug::GUI, "Toolbar::display: no toolbar named " << name);
473 message(bformat(_("Unknown toolbar \"%1$s\""), from_utf8(name)));
478 void GuiView::constructToolbars()
480 ToolbarMap::iterator it = d.toolbars_.begin();
481 for (; it != d.toolbars_.end(); ++it)
485 // I don't like doing this here, but the standard toolbar
486 // destroys this object when it's destroyed itself (vfr)
487 d.layout_ = new LayoutBox(*this);
488 d.stack_widget_->addWidget(d.layout_);
489 d.layout_->move(0,0);
491 // extracts the toolbars from the backend
492 Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
493 Toolbars::Infos::iterator end = guiApp->toolbars().end();
494 for (; cit != end; ++cit)
495 d.toolbars_[cit->name] = new GuiToolbar(*cit, *this);
499 void GuiView::initToolbars()
501 // extracts the toolbars from the backend
502 Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
503 Toolbars::Infos::iterator end = guiApp->toolbars().end();
504 for (; cit != end; ++cit) {
505 GuiToolbar * tb = toolbar(cit->name);
508 int const visibility = guiApp->toolbars().defaultVisibility(cit->name);
510 tb->setVisible(false);
511 tb->setVisibility(visibility);
513 if (visibility & Toolbars::TOP) {
515 addToolBarBreak(Qt::TopToolBarArea);
516 addToolBar(Qt::TopToolBarArea, tb);
519 if (visibility & Toolbars::BOTTOM) {
520 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
521 #if (QT_VERSION >= 0x040202)
522 addToolBarBreak(Qt::BottomToolBarArea);
524 addToolBar(Qt::BottomToolBarArea, tb);
527 if (visibility & Toolbars::LEFT) {
528 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
529 #if (QT_VERSION >= 0x040202)
530 addToolBarBreak(Qt::LeftToolBarArea);
532 addToolBar(Qt::LeftToolBarArea, tb);
535 if (visibility & Toolbars::RIGHT) {
536 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
537 #if (QT_VERSION >= 0x040202)
538 addToolBarBreak(Qt::RightToolBarArea);
540 addToolBar(Qt::RightToolBarArea, tb);
543 if (visibility & Toolbars::ON)
544 tb->setVisible(true);
549 TocModels & GuiView::tocModels()
551 return d.toc_models_;
555 void GuiView::setFocus()
557 LYXERR(Debug::DEBUG, "GuiView::setFocus()" << this);
558 // Make sure LyXFunc points to the correct view.
559 guiApp->setCurrentView(this);
560 QMainWindow::setFocus();
561 if (d.current_work_area_)
562 d.current_work_area_->setFocus();
566 QMenu * GuiView::createPopupMenu()
568 return d.toolBarPopup(this);
572 void GuiView::showEvent(QShowEvent * e)
574 LYXERR(Debug::GUI, "Passed Geometry "
575 << size().height() << "x" << size().width()
576 << "+" << pos().x() << "+" << pos().y());
578 if (d.splitter_->count() == 0)
579 // No work area, switch to the background widget.
582 QMainWindow::showEvent(e);
586 /** Destroy only all tabbed WorkAreas. Destruction of other WorkAreas
587 ** is responsibility of the container (e.g., dialog)
589 void GuiView::closeEvent(QCloseEvent * close_event)
591 LYXERR(Debug::DEBUG, "GuiView::closeEvent()");
596 // it can happen that this event arrives without selecting the view,
597 // e.g. when clicking the close button on a background window.
599 if (!closeWorkAreaAll()) {
601 close_event->ignore();
605 // Make sure that nothing will use this to be closed View.
606 guiApp->unregisterView(this);
608 if (isFullScreen()) {
609 // Switch off fullscreen before closing.
614 // Make sure the timer time out will not trigger a statusbar update.
615 d.statusbar_timer_.stop();
617 // Saving fullscreen requires additional tweaks in the toolbar code.
618 // It wouldn't also work under linux natively.
619 if (lyxrc.allow_geometry_session) {
620 // Save this window geometry and layout.
622 // Then the toolbar private states.
623 ToolbarMap::iterator end = d.toolbars_.end();
624 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
625 it->second->saveSession();
626 // Now take care of all other dialogs:
627 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
628 for (; it!= d.dialogs_.end(); ++it)
629 it->second->saveSession();
632 close_event->accept();
636 void GuiView::dragEnterEvent(QDragEnterEvent * event)
638 if (event->mimeData()->hasUrls())
640 /// \todo Ask lyx-devel is this is enough:
641 /// if (event->mimeData()->hasFormat("text/plain"))
642 /// event->acceptProposedAction();
646 void GuiView::dropEvent(QDropEvent * event)
648 QList<QUrl> files = event->mimeData()->urls();
652 LYXERR(Debug::GUI, "GuiView::dropEvent: got URLs!");
653 for (int i = 0; i != files.size(); ++i) {
654 string const file = os::internal_path(fromqstr(
655 files.at(i).toLocalFile()));
659 string const ext = support::getExtension(file);
660 vector<const Format *> found_formats;
662 // Find all formats that have the correct extension.
663 vector<const Format *> const & import_formats
664 = theConverters().importableFormats();
665 vector<const Format *>::const_iterator it = import_formats.begin();
666 for (; it != import_formats.end(); ++it)
667 if ((*it)->extension() == ext)
668 found_formats.push_back(*it);
671 if (found_formats.size() >= 1) {
672 if (found_formats.size() > 1) {
673 //FIXME: show a dialog to choose the correct importable format
675 "Multiple importable formats found, selecting first");
677 string const arg = found_formats[0]->name() + " " + file;
678 cmd = FuncRequest(LFUN_BUFFER_IMPORT, arg);
681 //FIXME: do we have to explicitly check whether it's a lyx file?
683 "No formats found, trying to open it as a lyx file");
684 cmd = FuncRequest(LFUN_FILE_OPEN, file);
687 // Asynchronously post the event. DropEvent usually come
688 // from the BufferView. But reloading a file might close
689 // the BufferView from within its own event handler.
690 guiApp->dispatchDelayed(cmd);
696 void GuiView::message(docstring const & str)
698 if (ForkedProcess::iAmAChild())
701 statusBar()->showMessage(toqstr(str));
702 d.statusbar_timer_.stop();
703 d.statusbar_timer_.start(3000);
707 void GuiView::smallSizedIcons()
709 setIconSize(QSize(d.smallIconSize, d.smallIconSize));
713 void GuiView::normalSizedIcons()
715 setIconSize(QSize(d.normalIconSize, d.normalIconSize));
719 void GuiView::bigSizedIcons()
721 setIconSize(QSize(d.bigIconSize, d.bigIconSize));
725 void GuiView::clearMessage()
730 d.statusbar_timer_.stop();
734 void GuiView::updateWindowTitle(GuiWorkArea * wa)
736 if (wa != d.current_work_area_)
738 setWindowTitle(qt_("LyX: ") + wa->windowTitle());
739 setWindowIconText(wa->windowIconText());
743 void GuiView::on_currentWorkAreaChanged(GuiWorkArea * wa)
746 disconnectBufferView();
747 connectBufferView(wa->bufferView());
748 connectBuffer(wa->bufferView().buffer());
749 d.current_work_area_ = wa;
750 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
751 this, SLOT(updateWindowTitle(GuiWorkArea *)));
752 updateWindowTitle(wa);
756 // The document settings needs to be reinitialised.
757 updateDialog("document", "");
759 // Buffer-dependent dialogs must be updated. This is done here because
760 // some dialogs require buffer()->text.
765 void GuiView::on_lastWorkAreaRemoved()
768 // We already are in a close event. Nothing more to do.
771 if (d.splitter_->count() > 1)
772 // We have a splitter so don't close anything.
775 // Reset and updates the dialogs.
776 d.toc_models_.reset(0);
777 updateDialog("document", "");
780 resetWindowTitleAndIconText();
782 if (lyxrc.open_buffers_in_tabs)
783 // Nothing more to do, the window should stay open.
786 if (guiApp->viewIds().size() > 1) {
792 // On Mac we also close the last window because the application stay
793 // resident in memory. On other platforms we don't close the last
794 // window because this would quit the application.
800 void GuiView::updateStatusBar()
802 // let the user see the explicit message
803 if (d.statusbar_timer_.isActive())
810 void GuiView::showMessage()
812 QString msg = toqstr(theGuiApp()->viewStatusMessage());
814 BufferView const * bv = currentBufferView();
816 msg = toqstr(bv->cursor().currentState());
818 msg = qt_("Welcome to LyX!");
820 statusBar()->showMessage(msg);
824 bool GuiView::event(QEvent * e)
828 // Useful debug code:
829 //case QEvent::ActivationChange:
830 //case QEvent::WindowDeactivate:
831 //case QEvent::Paint:
832 //case QEvent::Enter:
833 //case QEvent::Leave:
834 //case QEvent::HoverEnter:
835 //case QEvent::HoverLeave:
836 //case QEvent::HoverMove:
837 //case QEvent::StatusTip:
838 //case QEvent::DragEnter:
839 //case QEvent::DragLeave:
843 case QEvent::WindowActivate: {
844 GuiView * old_view = guiApp->currentView();
845 if (this == old_view) {
847 return QMainWindow::event(e);
849 if (old_view && old_view->currentBufferView()) {
850 // save current selection to the selection buffer to allow
851 // middle-button paste in this window.
852 cap::saveSelection(old_view->currentBufferView()->cursor());
854 guiApp->setCurrentView(this);
855 if (d.current_work_area_) {
856 BufferView & bv = d.current_work_area_->bufferView();
857 connectBufferView(bv);
858 connectBuffer(bv.buffer());
859 // The document structure, name and dialogs might have
860 // changed in another view.
862 // The document settings needs to be reinitialised.
863 updateDialog("document", "");
866 resetWindowTitleAndIconText();
869 return QMainWindow::event(e);
872 case QEvent::ShortcutOverride: {
875 #if (!defined Q_WS_X11) || (QT_VERSION >= 0x040500)
876 if (isFullScreen() && menuBar()->isHidden()) {
877 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
878 // FIXME: we should also try to detect special LyX shortcut such as
879 // Alt-P and Alt-M. Right now there is a hack in
880 // GuiWorkArea::processKeySym() that hides again the menubar for
882 if (ke->modifiers() & Qt::AltModifier && ke->key() != Qt::Key_Alt) {
884 return QMainWindow::event(e);
889 if (d.current_work_area_)
890 // Nothing special to do.
891 return QMainWindow::event(e);
893 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
894 // Let Qt handle menu access and the Tab keys to navigate keys to navigate
896 if (ke->modifiers() & Qt::AltModifier || ke->key() == Qt::Key_Tab
897 || ke->key() == Qt::Key_Backtab)
898 return QMainWindow::event(e);
900 // Allow processing of shortcuts that are allowed even when no Buffer
903 setKeySymbol(&sym, ke);
904 guiApp->processKeySym(sym, q_key_state(ke->modifiers()));
910 return QMainWindow::event(e);
914 void GuiView::resetWindowTitleAndIconText()
916 setWindowTitle(qt_("LyX"));
917 setWindowIconText(qt_("LyX"));
920 bool GuiView::focusNextPrevChild(bool /*next*/)
927 void GuiView::setBusy(bool busy)
929 if (d.current_work_area_) {
930 d.current_work_area_->setUpdatesEnabled(!busy);
932 d.current_work_area_->stopBlinkingCursor();
934 d.current_work_area_->startBlinkingCursor();
938 QApplication::setOverrideCursor(Qt::WaitCursor);
940 QApplication::restoreOverrideCursor();
944 GuiWorkArea * GuiView::workArea(Buffer & buffer)
946 if (currentWorkArea()
947 && ¤tWorkArea()->bufferView().buffer() == &buffer)
948 return (GuiWorkArea *) currentWorkArea();
949 if (TabWorkArea * twa = d.currentTabWorkArea())
950 return twa->workArea(buffer);
955 GuiWorkArea * GuiView::addWorkArea(Buffer & buffer)
957 // Automatically create a TabWorkArea if there are none yet.
958 TabWorkArea * tab_widget = d.splitter_->count()
959 ? d.currentTabWorkArea() : addTabWorkArea();
960 return tab_widget->addWorkArea(buffer, *this);
964 TabWorkArea * GuiView::addTabWorkArea()
966 TabWorkArea * twa = new TabWorkArea;
967 QObject::connect(twa, SIGNAL(currentWorkAreaChanged(GuiWorkArea *)),
968 this, SLOT(on_currentWorkAreaChanged(GuiWorkArea *)));
969 QObject::connect(twa, SIGNAL(lastWorkAreaRemoved()),
970 this, SLOT(on_lastWorkAreaRemoved()));
972 d.splitter_->addWidget(twa);
973 d.stack_widget_->setCurrentWidget(d.splitter_);
978 GuiWorkArea const * GuiView::currentWorkArea() const
980 return d.current_work_area_;
984 GuiWorkArea * GuiView::currentWorkArea()
986 return d.current_work_area_;
990 GuiWorkArea const * GuiView::currentMainWorkArea() const
992 if (d.currentTabWorkArea() == NULL)
994 return d.currentTabWorkArea()->currentWorkArea();
998 GuiWorkArea * GuiView::currentMainWorkArea()
1000 if (d.currentTabWorkArea() == NULL)
1002 return d.currentTabWorkArea()->currentWorkArea();
1006 void GuiView::setCurrentWorkArea(GuiWorkArea * wa)
1008 LYXERR(Debug::DEBUG, "Setting current wa: " << wa << endl);
1010 d.current_work_area_ = NULL;
1014 GuiWorkArea * old_gwa = theGuiApp()->currentView()->currentWorkArea();
1018 if (currentBufferView())
1019 cap::saveSelection(currentBufferView()->cursor());
1021 theGuiApp()->setCurrentView(this);
1022 d.current_work_area_ = wa;
1023 for (int i = 0; i != d.splitter_->count(); ++i) {
1024 if (d.tabWorkArea(i)->setCurrentWorkArea(wa)) {
1025 //if (d.current_main_work_area_)
1026 // d.current_main_work_area_->setFrameStyle(QFrame::NoFrame);
1027 d.current_main_work_area_ = wa;
1028 //d.current_main_work_area_->setFrameStyle(QFrame::Box | QFrame::Plain);
1029 //d.current_main_work_area_->setLineWidth(2);
1030 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() << ", Current main wa: " << currentMainWorkArea());
1034 LYXERR(Debug::DEBUG, "This is not a tabbed wa");
1035 on_currentWorkAreaChanged(wa);
1036 BufferView & bv = wa->bufferView();
1037 bv.cursor().fixIfBroken();
1039 wa->setUpdatesEnabled(true);
1040 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() << ", Current main wa: " << currentMainWorkArea());
1044 void GuiView::removeWorkArea(GuiWorkArea * wa)
1046 LASSERT(wa, return);
1047 if (wa == d.current_work_area_) {
1049 disconnectBufferView();
1050 d.current_work_area_ = 0;
1051 d.current_main_work_area_ = 0;
1054 bool found_twa = false;
1055 for (int i = 0; i != d.splitter_->count(); ++i) {
1056 TabWorkArea * twa = d.tabWorkArea(i);
1057 if (twa->removeWorkArea(wa)) {
1058 // Found in this tab group, and deleted the GuiWorkArea.
1060 if (twa->count() != 0) {
1061 if (d.current_work_area_ == 0)
1062 // This means that we are closing the current GuiWorkArea, so
1063 // switch to the next GuiWorkArea in the found TabWorkArea.
1064 setCurrentWorkArea(twa->currentWorkArea());
1066 // No more WorkAreas in this tab group, so delete it.
1073 // It is not a tabbed work area (i.e., the search work area), so it
1074 // should be deleted by other means.
1075 LASSERT(found_twa, /* */);
1077 if (d.current_work_area_ == 0) {
1078 if (d.splitter_->count() != 0) {
1079 TabWorkArea * twa = d.currentTabWorkArea();
1080 setCurrentWorkArea(twa->currentWorkArea());
1082 // No more work areas, switch to the background widget.
1083 setCurrentWorkArea(0);
1089 LayoutBox * GuiView::getLayoutDialog() const
1095 void GuiView::updateLayoutList()
1098 d.layout_->updateContents(false);
1102 void GuiView::updateToolbars()
1104 ToolbarMap::iterator end = d.toolbars_.end();
1105 if (d.current_work_area_) {
1107 d.current_work_area_->bufferView().cursor().inMathed();
1109 lyx::getStatus(FuncRequest(LFUN_LAYOUT_TABULAR)).enabled();
1111 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).enabled() &&
1112 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).onoff(true);
1113 bool const mathmacrotemplate =
1114 lyx::getStatus(FuncRequest(LFUN_IN_MATHMACROTEMPLATE)).enabled();
1116 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1117 it->second->update(math, table, review, mathmacrotemplate);
1119 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1120 it->second->update(false, false, false, false);
1124 void GuiView::setBuffer(Buffer * newBuffer)
1126 LYXERR(Debug::DEBUG, "Setting buffer: " << newBuffer << endl);
1127 LASSERT(newBuffer, return);
1130 GuiWorkArea * wa = workArea(*newBuffer);
1132 newBuffer->masterBuffer()->updateLabels();
1133 wa = addWorkArea(*newBuffer);
1135 //Disconnect the old buffer...there's no new one.
1138 connectBuffer(*newBuffer);
1139 connectBufferView(wa->bufferView());
1140 setCurrentWorkArea(wa);
1146 void GuiView::connectBuffer(Buffer & buf)
1148 buf.setGuiDelegate(this);
1152 void GuiView::disconnectBuffer()
1154 if (d.current_work_area_)
1155 d.current_work_area_->bufferView().buffer().setGuiDelegate(0);
1159 void GuiView::connectBufferView(BufferView & bv)
1161 bv.setGuiDelegate(this);
1165 void GuiView::disconnectBufferView()
1167 if (d.current_work_area_)
1168 d.current_work_area_->bufferView().setGuiDelegate(0);
1172 void GuiView::errors(string const & error_type, bool from_master)
1174 ErrorList & el = from_master ?
1175 documentBufferView()->buffer().masterBuffer()->errorList(error_type)
1176 : documentBufferView()->buffer().errorList(error_type);
1177 string data = error_type;
1179 data = "from_master|" + error_type;
1181 showDialog("errorlist", data);
1185 void GuiView::updateTocItem(string const & type, DocIterator const & dit)
1187 d.toc_models_.updateItem(toqstr(type), dit);
1191 void GuiView::structureChanged()
1193 d.toc_models_.reset(documentBufferView());
1194 // Navigator needs more than a simple update in this case. It needs to be
1196 updateDialog("toc", "");
1200 void GuiView::updateDialog(string const & name, string const & data)
1202 if (!isDialogVisible(name))
1205 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
1206 if (it == d.dialogs_.end())
1209 Dialog * const dialog = it->second.get();
1210 if (dialog->isVisibleView())
1211 dialog->initialiseParams(data);
1215 BufferView * GuiView::documentBufferView()
1217 return currentMainWorkArea()
1218 ? ¤tMainWorkArea()->bufferView()
1223 BufferView const * GuiView::documentBufferView() const
1225 return currentMainWorkArea()
1226 ? ¤tMainWorkArea()->bufferView()
1231 BufferView * GuiView::currentBufferView()
1233 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1237 BufferView const * GuiView::currentBufferView() const
1239 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1243 static docstring saveAndDestroyBuffer(Buffer * buffer, FileName const & fname)
1246 FileName const tmp_ret = FileName::tempName("lyxauto");
1247 if (!tmp_ret.empty()) {
1248 if (buffer->writeFile(tmp_ret))
1249 failed = !tmp_ret.moveTo(fname);
1252 // failed to write/rename tmp_ret so try writing direct
1253 failed = buffer->writeFile(fname);
1257 ? _("Automatic save failed!")
1258 : _("Automatic save done.");
1262 void GuiView::autoSave()
1264 LYXERR(Debug::INFO, "Running autoSave()");
1266 Buffer * buffer = documentBufferView()
1267 ? &documentBufferView()->buffer() : 0;
1271 #if (QT_VERSION >= 0x040400)
1272 QFuture<docstring> f = QtConcurrent::run(saveAndDestroyBuffer, buffer->clone(),
1273 buffer->getAutosaveFilename());
1274 d.autosave_watcher_.setFuture(f);
1281 void GuiView::resetAutosaveTimers()
1284 d.autosave_timeout_.restart();
1288 bool GuiView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1291 Buffer * buf = currentBufferView()
1292 ? ¤tBufferView()->buffer() : 0;
1293 Buffer * doc_buffer = documentBufferView()
1294 ? &(documentBufferView()->buffer()) : 0;
1296 // Check whether we need a buffer
1297 if (!lyxaction.funcHasFlag(cmd.action, LyXAction::NoBuffer) && !buf) {
1298 // no, exit directly
1299 flag.message(from_utf8(N_("Command not allowed with"
1300 "out any document open")));
1301 flag.setEnabled(false);
1305 if (cmd.origin == FuncRequest::TOC) {
1306 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
1308 if (toc->getStatus(documentBufferView()->cursor(), cmd, fs))
1311 flag.setEnabled(false);
1315 switch(cmd.action) {
1316 case LFUN_BUFFER_IMPORT:
1319 case LFUN_MASTER_BUFFER_UPDATE:
1320 case LFUN_MASTER_BUFFER_VIEW:
1321 enable = doc_buffer && doc_buffer->parent() != 0
1322 && !d.preview_watcher_.isRunning();
1325 case LFUN_BUFFER_UPDATE:
1326 case LFUN_BUFFER_VIEW: {
1327 if (!doc_buffer || d.preview_watcher_.isRunning()) {
1331 string format = to_utf8(cmd.argument());
1332 if (cmd.argument().empty())
1333 format = doc_buffer->getDefaultOutputFormat();
1334 enable = doc_buffer->isExportableFormat(format);
1338 case LFUN_BUFFER_RELOAD:
1339 enable = doc_buffer && !doc_buffer->isUnnamed()
1340 && doc_buffer->fileName().exists()
1341 && (!doc_buffer->isClean()
1342 || doc_buffer->isExternallyModified(Buffer::timestamp_method));
1345 case LFUN_BUFFER_CHILD_OPEN:
1346 enable = doc_buffer;
1349 case LFUN_BUFFER_WRITE:
1350 enable = doc_buffer && (doc_buffer->isUnnamed() || !doc_buffer->isClean());
1353 //FIXME: This LFUN should be moved to GuiApplication.
1354 case LFUN_BUFFER_WRITE_ALL: {
1355 // We enable the command only if there are some modified buffers
1356 Buffer * first = theBufferList().first();
1361 // We cannot use a for loop as the buffer list is a cycle.
1363 if (!b->isClean()) {
1367 b = theBufferList().next(b);
1368 } while (b != first);
1372 case LFUN_BUFFER_WRITE_AS:
1373 enable = doc_buffer;
1376 case LFUN_BUFFER_CLOSE:
1377 enable = doc_buffer;
1380 case LFUN_BUFFER_CLOSE_ALL:
1381 enable = theBufferList().last() != theBufferList().first();
1384 case LFUN_SPLIT_VIEW:
1385 if (cmd.getArg(0) == "vertical")
1386 enable = doc_buffer && (d.splitter_->count() == 1 ||
1387 d.splitter_->orientation() == Qt::Vertical);
1389 enable = doc_buffer && (d.splitter_->count() == 1 ||
1390 d.splitter_->orientation() == Qt::Horizontal);
1393 case LFUN_CLOSE_TAB_GROUP:
1394 enable = d.currentTabWorkArea();
1397 case LFUN_TOOLBAR_TOGGLE:
1398 if (GuiToolbar * t = toolbar(cmd.getArg(0)))
1399 flag.setOnOff(t->isVisible());
1402 case LFUN_DROP_LAYOUTS_CHOICE:
1406 case LFUN_UI_TOGGLE:
1407 flag.setOnOff(isFullScreen());
1410 case LFUN_DIALOG_DISCONNECT_INSET:
1413 case LFUN_DIALOG_HIDE:
1414 // FIXME: should we check if the dialog is shown?
1417 case LFUN_DIALOG_TOGGLE:
1418 flag.setOnOff(isDialogVisible(cmd.getArg(0)));
1419 // fall through to set "enable"
1420 case LFUN_DIALOG_SHOW: {
1421 string const name = cmd.getArg(0);
1423 enable = name == "aboutlyx"
1424 || name == "file" //FIXME: should be removed.
1426 || name == "texinfo"
1427 || name == "compare";
1428 else if (name == "print")
1429 enable = doc_buffer->isExportable("dvi")
1430 && lyxrc.print_command != "none";
1431 else if (name == "character" || name == "symbols") {
1432 if (!buf || buf->isReadonly()
1433 || !currentBufferView()->cursor().inTexted())
1436 // FIXME we should consider passthru
1438 Inset const & in = currentBufferView()->cursor().inset();
1439 enable = !in.getLayout().isPassThru();
1442 else if (name == "latexlog")
1443 enable = FileName(doc_buffer->logName()).isReadableFile();
1444 else if (name == "spellchecker")
1445 enable = theSpellChecker() && !doc_buffer->isReadonly();
1446 else if (name == "vclog")
1447 enable = doc_buffer->lyxvc().inUse();
1451 case LFUN_DIALOG_UPDATE: {
1452 string const name = cmd.getArg(0);
1454 enable = name == "prefs";
1458 case LFUN_COMMAND_EXECUTE:
1460 case LFUN_MENU_OPEN:
1461 // Nothing to check.
1464 case LFUN_COMPLETION_INLINE:
1465 if (!d.current_work_area_
1466 || !d.current_work_area_->completer().inlinePossible(
1467 currentBufferView()->cursor()))
1471 case LFUN_COMPLETION_POPUP:
1472 if (!d.current_work_area_
1473 || !d.current_work_area_->completer().popupPossible(
1474 currentBufferView()->cursor()))
1478 case LFUN_COMPLETION_COMPLETE:
1479 if (!d.current_work_area_
1480 || !d.current_work_area_->completer().inlinePossible(
1481 currentBufferView()->cursor()))
1485 case LFUN_COMPLETION_ACCEPT:
1486 if (!d.current_work_area_
1487 || (!d.current_work_area_->completer().popupVisible()
1488 && !d.current_work_area_->completer().inlineVisible()
1489 && !d.current_work_area_->completer().completionAvailable()))
1493 case LFUN_COMPLETION_CANCEL:
1494 if (!d.current_work_area_
1495 || (!d.current_work_area_->completer().popupVisible()
1496 && !d.current_work_area_->completer().inlineVisible()))
1500 case LFUN_BUFFER_ZOOM_OUT:
1501 enable = doc_buffer && lyxrc.zoom > 10;
1504 case LFUN_BUFFER_ZOOM_IN:
1505 enable = doc_buffer;
1508 case LFUN_BUFFER_NEXT:
1509 case LFUN_BUFFER_PREVIOUS:
1510 // FIXME: should we check is there is an previous or next buffer?
1512 case LFUN_BUFFER_SWITCH:
1513 // toggle on the current buffer, but do not toggle off
1514 // the other ones (is that a good idea?)
1516 && to_utf8(cmd.argument()) == doc_buffer->absFileName())
1517 flag.setOnOff(true);
1520 case LFUN_VC_REGISTER:
1521 enable = doc_buffer && !doc_buffer->lyxvc().inUse();
1523 case LFUN_VC_CHECK_IN:
1524 enable = doc_buffer && doc_buffer->lyxvc().checkInEnabled();
1526 case LFUN_VC_CHECK_OUT:
1527 enable = doc_buffer && doc_buffer->lyxvc().checkOutEnabled();
1529 case LFUN_VC_LOCKING_TOGGLE:
1530 enable = doc_buffer && !doc_buffer->isReadonly()
1531 && doc_buffer->lyxvc().lockingToggleEnabled();
1532 flag.setOnOff(enable && !doc_buffer->lyxvc().locker().empty());
1534 case LFUN_VC_REVERT:
1535 enable = doc_buffer && doc_buffer->lyxvc().inUse();
1537 case LFUN_VC_UNDO_LAST:
1538 enable = doc_buffer && doc_buffer->lyxvc().undoLastEnabled();
1540 case LFUN_VC_REPO_UPDATE:
1541 enable = doc_buffer && doc_buffer->lyxvc().inUse();
1543 case LFUN_VC_COMMAND: {
1544 if (cmd.argument().empty())
1546 if (!doc_buffer && contains(cmd.getArg(0), 'D'))
1551 case LFUN_SERVER_GOTO_FILE_ROW:
1559 flag.setEnabled(false);
1565 static FileName selectTemplateFile()
1567 FileDialog dlg(qt_("Select template file"));
1568 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1569 dlg.setButton1(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
1571 FileDialog::Result result = dlg.open(toqstr(lyxrc.template_path),
1572 QStringList(qt_("LyX Documents (*.lyx)")));
1574 if (result.first == FileDialog::Later)
1576 if (result.second.isEmpty())
1578 return FileName(fromqstr(result.second));
1582 Buffer * GuiView::loadDocument(FileName const & filename, bool tolastfiles)
1586 Buffer * newBuffer = checkAndLoadLyXFile(filename);
1589 message(_("Document not loaded."));
1594 setBuffer(newBuffer);
1596 // scroll to the position when the file was last closed
1597 if (lyxrc.use_lastfilepos) {
1598 LastFilePosSection::FilePos filepos =
1599 theSession().lastFilePos().load(filename);
1600 documentBufferView()->moveToPosition(filepos.pit, filepos.pos, 0, 0);
1604 theSession().lastFiles().add(filename);
1611 void GuiView::openDocument(string const & fname)
1613 string initpath = lyxrc.document_path;
1615 if (documentBufferView()) {
1616 string const trypath = documentBufferView()->buffer().filePath();
1617 // If directory is writeable, use this as default.
1618 if (FileName(trypath).isDirWritable())
1624 if (fname.empty()) {
1625 FileDialog dlg(qt_("Select document to open"), LFUN_FILE_OPEN);
1626 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1627 dlg.setButton2(qt_("Examples|#E#e"),
1628 toqstr(addPath(package().system_support().absFilename(), "examples")));
1630 QStringList filter(qt_("LyX Documents (*.lyx)"));
1631 filter << qt_("LyX-1.3.x Documents (*.lyx13)")
1632 << qt_("LyX-1.4.x Documents (*.lyx14)")
1633 << qt_("LyX-1.5.x Documents (*.lyx15)")
1634 << qt_("LyX-1.6.x Documents (*.lyx16)");
1635 FileDialog::Result result =
1636 dlg.open(toqstr(initpath), filter);
1638 if (result.first == FileDialog::Later)
1641 filename = fromqstr(result.second);
1643 // check selected filename
1644 if (filename.empty()) {
1645 message(_("Canceled."));
1651 // get absolute path of file and add ".lyx" to the filename if
1653 FileName const fullname =
1654 fileSearch(string(), filename, "lyx", support::may_not_exist);
1655 if (!fullname.empty())
1656 filename = fullname.absFilename();
1658 if (!fullname.onlyPath().isDirectory()) {
1659 Alert::warning(_("Invalid filename"),
1660 bformat(_("The directory in the given path\n%1$s\ndoes not exist."),
1661 from_utf8(fullname.absFilename())));
1664 // if the file doesn't exist, let the user create one
1665 if (!fullname.exists()) {
1666 // the user specifically chose this name. Believe him.
1667 Buffer * const b = newFile(filename, string(), true);
1673 docstring const disp_fn = makeDisplayPath(filename);
1674 message(bformat(_("Opening document %1$s..."), disp_fn));
1677 Buffer * buf = loadDocument(fullname);
1679 buf->updateLabels();
1681 buf->errors("Parse");
1682 str2 = bformat(_("Document %1$s opened."), disp_fn);
1683 if (buf->lyxvc().inUse())
1684 str2 += " " + from_utf8(buf->lyxvc().versionString()) +
1685 " " + _("Version control detected.");
1687 str2 = bformat(_("Could not open document %1$s"), disp_fn);
1692 // FIXME: clean that
1693 static bool import(GuiView * lv, FileName const & filename,
1694 string const & format, ErrorList & errorList)
1696 FileName const lyxfile(support::changeExtension(filename.absFilename(), ".lyx"));
1698 string loader_format;
1699 vector<string> loaders = theConverters().loaders();
1700 if (find(loaders.begin(), loaders.end(), format) == loaders.end()) {
1701 for (vector<string>::const_iterator it = loaders.begin();
1702 it != loaders.end(); ++it) {
1703 if (!theConverters().isReachable(format, *it))
1706 string const tofile =
1707 support::changeExtension(filename.absFilename(),
1708 formats.extension(*it));
1709 if (!theConverters().convert(0, filename, FileName(tofile),
1710 filename, format, *it, errorList))
1712 loader_format = *it;
1715 if (loader_format.empty()) {
1716 frontend::Alert::error(_("Couldn't import file"),
1717 bformat(_("No information for importing the format %1$s."),
1718 formats.prettyName(format)));
1722 loader_format = format;
1724 if (loader_format == "lyx") {
1725 Buffer * buf = lv->loadDocument(lyxfile);
1728 buf->updateLabels();
1730 buf->errors("Parse");
1732 Buffer * const b = newFile(lyxfile.absFilename(), string(), true);
1736 bool as_paragraphs = loader_format == "textparagraph";
1737 string filename2 = (loader_format == format) ? filename.absFilename()
1738 : support::changeExtension(filename.absFilename(),
1739 formats.extension(loader_format));
1740 lv->currentBufferView()->insertPlaintextFile(FileName(filename2),
1742 guiApp->setCurrentView(lv);
1743 lyx::dispatch(FuncRequest(LFUN_MARK_OFF));
1750 void GuiView::importDocument(string const & argument)
1753 string filename = split(argument, format, ' ');
1755 LYXERR(Debug::INFO, format << " file: " << filename);
1757 // need user interaction
1758 if (filename.empty()) {
1759 string initpath = lyxrc.document_path;
1760 if (documentBufferView()) {
1761 string const trypath = documentBufferView()->buffer().filePath();
1762 // If directory is writeable, use this as default.
1763 if (FileName(trypath).isDirWritable())
1767 docstring const text = bformat(_("Select %1$s file to import"),
1768 formats.prettyName(format));
1770 FileDialog dlg(toqstr(text), LFUN_BUFFER_IMPORT);
1771 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1772 dlg.setButton2(qt_("Examples|#E#e"),
1773 toqstr(addPath(package().system_support().absFilename(), "examples")));
1775 docstring filter = formats.prettyName(format);
1778 filter += from_utf8(formats.extension(format));
1781 FileDialog::Result result =
1782 dlg.open(toqstr(initpath), fileFilters(toqstr(filter)));
1784 if (result.first == FileDialog::Later)
1787 filename = fromqstr(result.second);
1789 // check selected filename
1790 if (filename.empty())
1791 message(_("Canceled."));
1794 if (filename.empty())
1797 // get absolute path of file
1798 FileName const fullname(support::makeAbsPath(filename));
1800 FileName const lyxfile(support::changeExtension(fullname.absFilename(), ".lyx"));
1802 // Check if the document already is open
1803 Buffer * buf = theBufferList().getBuffer(lyxfile);
1806 if (!closeBuffer()) {
1807 message(_("Canceled."));
1812 docstring const displaypath = makeDisplayPath(lyxfile.absFilename(), 30);
1814 // if the file exists already, and we didn't do
1815 // -i lyx thefile.lyx, warn
1816 if (lyxfile.exists() && fullname != lyxfile) {
1818 docstring text = bformat(_("The document %1$s already exists.\n\n"
1819 "Do you want to overwrite that document?"), displaypath);
1820 int const ret = Alert::prompt(_("Overwrite document?"),
1821 text, 0, 1, _("&Overwrite"), _("&Cancel"));
1824 message(_("Canceled."));
1829 message(bformat(_("Importing %1$s..."), displaypath));
1830 ErrorList errorList;
1831 if (import(this, fullname, format, errorList))
1832 message(_("imported."));
1834 message(_("file not imported!"));
1836 // FIXME (Abdel 12/08/06): Is there a need to display the error list here?
1840 void GuiView::newDocument(string const & filename, bool from_template)
1842 FileName initpath(lyxrc.document_path);
1843 if (documentBufferView()) {
1844 FileName const trypath(documentBufferView()->buffer().filePath());
1845 // If directory is writeable, use this as default.
1846 if (trypath.isDirWritable())
1850 string templatefile;
1851 if (from_template) {
1852 templatefile = selectTemplateFile().absFilename();
1853 if (templatefile.empty())
1858 if (filename.empty())
1859 b = newUnnamedFile(initpath, to_utf8(_("newfile")), templatefile);
1861 b = newFile(filename, templatefile, true);
1866 // If no new document could be created, it is unsure
1867 // whether there is a valid BufferView.
1868 if (currentBufferView())
1869 // Ensure the cursor is correctly positioned on screen.
1870 currentBufferView()->showCursor();
1874 void GuiView::insertLyXFile(docstring const & fname)
1876 BufferView * bv = documentBufferView();
1881 FileName filename(to_utf8(fname));
1883 if (!filename.empty()) {
1884 bv->insertLyXFile(filename);
1888 // Launch a file browser
1890 string initpath = lyxrc.document_path;
1891 string const trypath = bv->buffer().filePath();
1892 // If directory is writeable, use this as default.
1893 if (FileName(trypath).isDirWritable())
1897 FileDialog dlg(qt_("Select LyX document to insert"), LFUN_FILE_INSERT);
1898 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1899 dlg.setButton2(qt_("Examples|#E#e"),
1900 toqstr(addPath(package().system_support().absFilename(),
1903 FileDialog::Result result = dlg.open(toqstr(initpath),
1904 QStringList(qt_("LyX Documents (*.lyx)")));
1906 if (result.first == FileDialog::Later)
1910 filename.set(fromqstr(result.second));
1912 // check selected filename
1913 if (filename.empty()) {
1914 // emit message signal.
1915 message(_("Canceled."));
1919 bv->insertLyXFile(filename);
1923 void GuiView::insertPlaintextFile(docstring const & fname,
1926 BufferView * bv = documentBufferView();
1930 if (!fname.empty() && !FileName::isAbsolute(to_utf8(fname))) {
1931 message(_("Absolute filename expected."));
1936 FileName filename(to_utf8(fname));
1938 if (!filename.empty()) {
1939 bv->insertPlaintextFile(filename, asParagraph);
1943 FileDialog dlg(qt_("Select file to insert"), (asParagraph ?
1944 LFUN_FILE_INSERT_PLAINTEXT_PARA : LFUN_FILE_INSERT_PLAINTEXT));
1946 FileDialog::Result result = dlg.open(toqstr(bv->buffer().filePath()),
1947 QStringList(qt_("All Files (*)")));
1949 if (result.first == FileDialog::Later)
1953 filename.set(fromqstr(result.second));
1955 // check selected filename
1956 if (filename.empty()) {
1957 // emit message signal.
1958 message(_("Canceled."));
1962 bv->insertPlaintextFile(filename, asParagraph);
1966 bool GuiView::renameBuffer(Buffer & b, docstring const & newname)
1968 FileName fname = b.fileName();
1969 FileName const oldname = fname;
1971 if (!newname.empty()) {
1973 fname = support::makeAbsPath(to_utf8(newname), oldname.onlyPath().absFilename());
1975 // Switch to this Buffer.
1978 // No argument? Ask user through dialog.
1980 FileDialog dlg(qt_("Choose a filename to save document as"),
1981 LFUN_BUFFER_WRITE_AS);
1982 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1983 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
1985 if (!isLyXFilename(fname.absFilename()))
1986 fname.changeExtension(".lyx");
1988 FileDialog::Result result =
1989 dlg.save(toqstr(fname.onlyPath().absFilename()),
1990 QStringList(qt_("LyX Documents (*.lyx)")),
1991 toqstr(fname.onlyFileName()));
1993 if (result.first == FileDialog::Later)
1996 fname.set(fromqstr(result.second));
2001 if (!isLyXFilename(fname.absFilename()))
2002 fname.changeExtension(".lyx");
2005 if (FileName(fname).exists()) {
2006 docstring const file = makeDisplayPath(fname.absFilename(), 30);
2007 docstring text = bformat(_("The document %1$s already "
2008 "exists.\n\nDo you want to "
2009 "overwrite that document?"),
2011 int const ret = Alert::prompt(_("Overwrite document?"),
2012 text, 0, 2, _("&Overwrite"), _("&Rename"), _("&Cancel"));
2015 case 1: return renameBuffer(b, docstring());
2016 case 2: return false;
2020 FileName oldauto = b.getAutosaveFilename();
2022 // Ok, change the name of the buffer
2023 b.setFileName(fname.absFilename());
2025 bool unnamed = b.isUnnamed();
2026 b.setUnnamed(false);
2027 b.saveCheckSum(fname);
2029 // bring the autosave file with us, just in case.
2030 b.moveAutosaveFile(oldauto);
2032 if (!saveBuffer(b)) {
2033 oldauto = b.getAutosaveFilename();
2034 b.setFileName(oldname.absFilename());
2035 b.setUnnamed(unnamed);
2036 b.saveCheckSum(oldname);
2037 b.moveAutosaveFile(oldauto);
2045 bool GuiView::saveBuffer(Buffer & b)
2047 if (workArea(b) && workArea(b)->inDialogMode())
2051 return renameBuffer(b, docstring());
2054 theSession().lastFiles().add(b.fileName());
2058 // Switch to this Buffer.
2061 // FIXME: we don't tell the user *WHY* the save failed !!
2062 docstring const file = makeDisplayPath(b.absFileName(), 30);
2063 docstring text = bformat(_("The document %1$s could not be saved.\n\n"
2064 "Do you want to rename the document and "
2065 "try again?"), file);
2066 int const ret = Alert::prompt(_("Rename and save?"),
2067 text, 0, 2, _("&Rename"), _("&Retry"), _("&Cancel"));
2070 if (!renameBuffer(b, docstring()))
2079 return saveBuffer(b);
2083 bool GuiView::hideWorkArea(GuiWorkArea * wa)
2085 return closeWorkArea(wa, false);
2089 bool GuiView::closeWorkArea(GuiWorkArea * wa)
2091 Buffer & buf = wa->bufferView().buffer();
2092 return closeWorkArea(wa, !buf.parent());
2096 bool GuiView::closeBuffer()
2098 GuiWorkArea * wa = currentMainWorkArea();
2099 Buffer & buf = wa->bufferView().buffer();
2100 return wa && closeWorkArea(wa, !buf.parent());
2104 void GuiView::writeSession() const {
2105 GuiWorkArea const * active_wa = currentMainWorkArea();
2106 for (int i = 0; i < d.splitter_->count(); ++i) {
2107 TabWorkArea * twa = d.tabWorkArea(i);
2108 for (int j = 0; j < twa->count(); ++j) {
2109 GuiWorkArea * wa = static_cast<GuiWorkArea *>(twa->widget(j));
2110 Buffer & buf = wa->bufferView().buffer();
2111 theSession().lastOpened().add(buf.fileName(), wa == active_wa);
2117 bool GuiView::closeBufferAll()
2119 // Close the workareas in all other views
2120 QList<int> const ids = guiApp->viewIds();
2121 for (int i = 0; i != ids.size(); ++i) {
2122 if (id_ != ids[i] && !guiApp->view(ids[i]).closeWorkAreaAll())
2126 // Close our own workareas
2127 if (!closeWorkAreaAll())
2130 // Now close the hidden buffers. We prevent hidden buffers from being
2131 // dirty, so we can just close them.
2132 theBufferList().closeAll();
2137 bool GuiView::closeWorkAreaAll()
2139 setCurrentWorkArea(currentMainWorkArea());
2141 // We might be in a situation that there is still a tabWorkArea, but
2142 // there are no tabs anymore. This can happen when we get here after a
2143 // TabWorkArea::lastWorkAreaRemoved() signal. Therefore we count how
2144 // many TabWorkArea's have no documents anymore.
2147 // We have to call count() each time, because it can happen that
2148 // more than one splitter will disappear in one iteration (bug 5998).
2149 for (; d.splitter_->count() > empty_twa; ) {
2150 TabWorkArea * twa = d.tabWorkArea(empty_twa);
2152 if (twa->count() == 0)
2155 setCurrentWorkArea(twa->currentWorkArea());
2156 if (!closeTabWorkArea(twa))
2164 bool GuiView::closeWorkArea(GuiWorkArea * wa, bool close_buffer)
2169 Buffer & buf = wa->bufferView().buffer();
2172 return closeBuffer(buf);
2174 if (!inMultiTabs(wa))
2175 if (!saveBufferIfNeeded(buf, true))
2183 bool GuiView::closeBuffer(Buffer & buf)
2185 // If we are in a close_event all children will be closed in some time,
2186 // so no need to do it here. This will ensure that the children end up
2187 // in the session file in the correct order. If we close the master
2188 // buffer, we can close or release the child buffers here too.
2190 vector<Buffer *> clist = buf.getChildren(false);
2191 for (vector<Buffer *>::const_iterator it = clist.begin();
2192 it != clist.end(); ++it) {
2193 // If a child is dirty, do not close
2194 // without user intervention
2195 //FIXME: should we look in other tabworkareas?
2196 Buffer * child_buf = *it;
2197 GuiWorkArea * child_wa = workArea(*child_buf);
2199 if (!closeWorkArea(child_wa, true))
2202 theBufferList().releaseChild(&buf, child_buf);
2205 // goto bookmark to update bookmark pit.
2206 //FIXME: we should update only the bookmarks related to this buffer!
2207 LYXERR(Debug::DEBUG, "GuiView::closeBuffer()");
2208 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
2209 theLyXFunc().gotoBookmark(i+1, false, false);
2211 if (saveBufferIfNeeded(buf, false)) {
2212 theBufferList().release(&buf);
2219 bool GuiView::closeTabWorkArea(TabWorkArea * twa)
2221 while (twa == d.currentTabWorkArea()) {
2222 twa->setCurrentIndex(twa->count()-1);
2224 GuiWorkArea * wa = twa->currentWorkArea();
2225 Buffer & b = wa->bufferView().buffer();
2227 // We only want to close the buffer if the same buffer is not visible
2228 // in another view, and if this is not a child and if we are closing
2229 // a view (not a tabgroup).
2230 bool const close_buffer =
2231 !inMultiViews(wa) && !b.parent() && closing_;
2233 if (!closeWorkArea(wa, close_buffer))
2240 bool GuiView::saveBufferIfNeeded(Buffer & buf, bool hiding)
2242 if (buf.isClean() || buf.paragraphs().empty())
2245 // Switch to this Buffer.
2250 if (buf.isUnnamed())
2251 file = from_utf8(buf.fileName().onlyFileName());
2253 file = buf.fileName().displayName(30);
2255 // Bring this window to top before asking questions.
2260 if (hiding && buf.isUnnamed()) {
2261 docstring const text = bformat(_("The document %1$s has not been "
2262 "saved yet.\n\nDo you want to save "
2263 "the document?"), file);
2264 ret = Alert::prompt(_("Save new document?"),
2265 text, 0, 1, _("&Save"), _("&Cancel"));
2269 docstring const text = bformat(_("The document %1$s has unsaved changes."
2270 "\n\nDo you want to save the document or discard the changes?"), file);
2271 ret = Alert::prompt(_("Save changed document?"),
2272 text, 0, 2, _("&Save"), _("&Discard"), _("&Cancel"));
2277 if (!saveBuffer(buf))
2281 // if we crash after this we could
2282 // have no autosave file but I guess
2283 // this is really improbable (Jug)
2284 buf.removeAutosaveFile();
2286 // revert all changes
2287 buf.loadLyXFile(buf.fileName());
2297 bool GuiView::inMultiTabs(GuiWorkArea * wa)
2299 Buffer & buf = wa->bufferView().buffer();
2301 for (int i = 0; i != d.splitter_->count(); ++i) {
2302 GuiWorkArea * wa_ = d.tabWorkArea(i)->workArea(buf);
2303 if (wa_ && wa_ != wa)
2306 return inMultiViews(wa);
2310 bool GuiView::inMultiViews(GuiWorkArea * wa)
2312 QList<int> const ids = guiApp->viewIds();
2313 Buffer & buf = wa->bufferView().buffer();
2316 for (int i = 0; i != ids.size() && found_twa <= 1; ++i) {
2320 if (guiApp->view(ids[i]).workArea(buf))
2327 void GuiView::gotoNextOrPreviousBuffer(NextOrPrevious np)
2329 Buffer * const curbuf = documentBufferView()
2330 ? &documentBufferView()->buffer() : 0;
2331 Buffer * nextbuf = curbuf;
2333 if (np == NEXTBUFFER)
2334 nextbuf = theBufferList().next(nextbuf);
2336 nextbuf = theBufferList().previous(nextbuf);
2337 if (nextbuf == curbuf)
2343 if (workArea(*nextbuf))
2350 /// make sure the document is saved
2351 static bool ensureBufferClean(Buffer * buffer)
2353 LASSERT(buffer, return false);
2354 if (buffer->isClean() && !buffer->isUnnamed())
2357 docstring const file = buffer->fileName().displayName(30);
2360 if (!buffer->isUnnamed()) {
2361 text = bformat(_("The document %1$s has unsaved "
2362 "changes.\n\nDo you want to save "
2363 "the document?"), file);
2364 title = _("Save changed document?");
2367 text = bformat(_("The document %1$s has not been "
2368 "saved yet.\n\nDo you want to save "
2369 "the document?"), file);
2370 title = _("Save new document?");
2372 int const ret = Alert::prompt(title, text, 0, 1, _("&Save"), _("&Cancel"));
2375 dispatch(FuncRequest(LFUN_BUFFER_WRITE));
2377 return buffer->isClean() && !buffer->isUnnamed();
2381 void GuiView::reloadBuffer()
2383 Buffer * buf = &documentBufferView()->buffer();
2388 void GuiView::reloadBuffer(Buffer * buf)
2390 FileName filename = buf->fileName();
2391 Buffer const * master = buf->masterBuffer();
2392 bool const is_child = master != buf;
2393 // The user has already confirmed that the changes, if any, should
2394 // be discarded. So we just release the Buffer and don't call closeBuffer();
2395 theBufferList().release(buf);
2396 buf = loadDocument(filename);
2397 docstring const disp_fn = makeDisplayPath(filename.absFilename());
2400 // re-allocate master if necessary
2401 if (is_child && theBufferList().isLoaded(master)
2402 && buf->masterBuffer() != master)
2403 buf->setParent(master);
2404 buf->updateLabels();
2406 buf->errors("Parse");
2407 str = bformat(_("Document %1$s reloaded."), disp_fn);
2409 str = bformat(_("Could not reload document %1$s"), disp_fn);
2415 void GuiView::checkExternallyModifiedBuffers()
2417 BufferList::iterator bit = theBufferList().begin();
2418 BufferList::iterator const bend = theBufferList().end();
2419 for (; bit != bend; ++bit) {
2420 if ((*bit)->isExternallyModified(Buffer::checksum_method)) {
2421 docstring text = bformat(_("Document \n%1$s\n has been externally modified."
2422 " Reload now? Any local changes will be lost."),
2423 from_utf8((*bit)->absFileName()));
2424 int const ret = Alert::prompt(_("Reload externally changed document?"),
2425 text, 0, 1, _("&Reload"), _("&Cancel"));
2433 void GuiView::dispatchVC(FuncRequest const & cmd)
2435 Buffer * buffer = documentBufferView()
2436 ? &(documentBufferView()->buffer()) : 0;
2438 switch (cmd.action) {
2439 case LFUN_VC_REGISTER:
2440 if (!buffer || !ensureBufferClean(buffer))
2442 if (!buffer->lyxvc().inUse()) {
2443 if (buffer->lyxvc().registrer())
2448 case LFUN_VC_CHECK_IN:
2449 if (!buffer || !ensureBufferClean(buffer))
2451 if (buffer->lyxvc().inUse() && !buffer->isReadonly()) {
2452 message(from_utf8(buffer->lyxvc().checkIn()));
2457 case LFUN_VC_CHECK_OUT:
2458 if (!buffer || !ensureBufferClean(buffer))
2460 if (buffer->lyxvc().inUse()) {
2461 message(from_utf8(buffer->lyxvc().checkOut()));
2466 case LFUN_VC_LOCKING_TOGGLE:
2467 LASSERT(buffer, return);
2468 if (!ensureBufferClean(buffer) || buffer->isReadonly())
2470 if (buffer->lyxvc().inUse()) {
2471 string res = buffer->lyxvc().lockingToggle();
2473 frontend::Alert::error(_("Revision control error."),
2474 _("Error when setting the locking property."));
2476 message(from_utf8(res));
2482 case LFUN_VC_REVERT:
2483 LASSERT(buffer, return);
2484 buffer->lyxvc().revert();
2488 case LFUN_VC_UNDO_LAST:
2489 LASSERT(buffer, return);
2490 buffer->lyxvc().undoLast();
2494 case LFUN_VC_REPO_UPDATE:
2495 LASSERT(buffer, return);
2496 if (ensureBufferClean(buffer)) {
2497 string res = buffer->lyxvc().repoUpdate();
2498 message(from_utf8(res));
2499 checkExternallyModifiedBuffers();
2503 case LFUN_VC_COMMAND: {
2504 string flag = cmd.getArg(0);
2505 if (buffer && contains(flag, 'R') && !ensureBufferClean(buffer))
2508 if (contains(flag, 'M')) {
2509 if (!Alert::askForText(message, _("LyX VC: Log Message")))
2512 string path = cmd.getArg(1);
2513 if (contains(path, "$$p") && buffer)
2514 path = subst(path, "$$p", buffer->filePath());
2515 LYXERR(Debug::LYXVC, "Directory: " << path);
2517 if (!pp.isReadableDirectory()) {
2518 lyxerr << _("Directory is not accessible.") << endl;
2521 support::PathChanger p(pp);
2523 string command = cmd.getArg(2);
2524 if (command.empty())
2527 command = subst(command, "$$i", buffer->absFileName());
2528 command = subst(command, "$$p", buffer->filePath());
2530 command = subst(command, "$$m", to_utf8(message));
2531 LYXERR(Debug::LYXVC, "Command: " << command);
2533 one.startscript(Systemcall::Wait, command);
2537 if (contains(flag, 'I'))
2538 buffer->markDirty();
2539 if (contains(flag, 'R'))
2550 void GuiView::openChildDocument(string const & fname)
2552 LASSERT(documentBufferView(), return);
2553 Buffer & buffer = documentBufferView()->buffer();
2554 FileName const filename = support::makeAbsPath(fname, buffer.filePath());
2555 documentBufferView()->saveBookmark(false);
2557 bool parsed = false;
2558 if (theBufferList().exists(filename)) {
2559 child = theBufferList().getBuffer(filename);
2561 message(bformat(_("Opening child document %1$s..."),
2562 makeDisplayPath(filename.absFilename())));
2563 child = loadDocument(filename, false);
2569 // Set the parent name of the child document.
2570 // This makes insertion of citations and references in the child work,
2571 // when the target is in the parent or another child document.
2572 child->setParent(&buffer);
2573 child->masterBuffer()->updateLabels();
2576 child->errors("Parse");
2580 bool GuiView::goToFileRow(string const & argument)
2584 istringstream is(argument);
2585 is >> file_name >> row;
2586 file_name = os::internal_path(file_name);
2588 string const abstmp = package().temp_dir().absFilename();
2589 string const realtmp = package().temp_dir().realPath();
2590 // We have to use os::path_prefix_is() here, instead of
2591 // simply prefixIs(), because the file name comes from
2592 // an external application and may need case adjustment.
2593 if (os::path_prefix_is(file_name, abstmp, os::CASE_ADJUSTED)
2594 || os::path_prefix_is(file_name, realtmp, os::CASE_ADJUSTED)) {
2595 // Needed by inverse dvi search. If it is a file
2596 // in tmpdir, call the apropriated function.
2597 // If tmpdir is a symlink, we may have the real
2598 // path passed back, so we correct for that.
2599 if (!prefixIs(file_name, abstmp))
2600 file_name = subst(file_name, realtmp, abstmp);
2601 buf = theBufferList().getBufferFromTmp(file_name);
2603 // Must replace extension of the file to be .lyx
2604 // and get full path
2605 FileName const s = fileSearch(string(),
2606 support::changeExtension(file_name, ".lyx"), "lyx");
2607 // Either change buffer or load the file
2608 if (theBufferList().exists(s))
2609 buf = theBufferList().getBuffer(s);
2610 else if (s.exists()) {
2611 buf = loadDocument(s);
2612 buf->updateLabels();
2613 buf->errors("Parse");
2616 _("File does not exist: %1$s"),
2617 makeDisplayPath(file_name)));
2622 documentBufferView()->setCursorFromRow(row);
2627 static docstring exportAndDestroy(Buffer * buffer, string const & format)
2629 bool const success = buffer->doExport(format, true);
2632 ? bformat(_("Successful export to format: %1$s"), from_utf8(format))
2633 : bformat(_("Error exporting to format: %1$s"), from_utf8(format));
2637 static docstring previewAndDestroy(Buffer * buffer, string const & format)
2639 bool const success = buffer->preview(format);
2642 ? bformat(_("Successful preview of format: %1$s"), from_utf8(format))
2643 : bformat(_("Error previewing format: %1$s"), from_utf8(format));
2647 bool GuiView::dispatch(FuncRequest const & cmd)
2649 BufferView * bv = currentBufferView();
2650 // By default we won't need any update.
2652 bv->cursor().updateFlags(Update::None);
2654 Buffer * doc_buffer = documentBufferView()
2655 ? &(documentBufferView()->buffer()) : 0;
2657 bool dispatched = true;
2659 if (cmd.origin == FuncRequest::TOC) {
2660 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
2661 toc->doDispatch(bv->cursor(), cmd);
2665 string const argument = to_utf8(cmd.argument());
2667 switch(cmd.action) {
2668 case LFUN_BUFFER_CHILD_OPEN:
2669 openChildDocument(to_utf8(cmd.argument()));
2672 case LFUN_BUFFER_IMPORT:
2673 importDocument(to_utf8(cmd.argument()));
2676 case LFUN_BUFFER_EXPORT: {
2679 if (cmd.argument() == "custom") {
2680 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "sendto"));
2683 if (doc_buffer->doExport(argument, false)) {
2684 message(bformat(_("Error exporting to format: %1$s."),
2690 case LFUN_BUFFER_UPDATE: {
2693 string format = argument;
2694 if (argument.empty())
2695 format = doc_buffer->getDefaultOutputFormat();
2696 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
2697 ProgressInterface::instance()->clearMessages();
2698 QString time = QTime::currentTime().toString(Qt::SystemLocaleShortDate);
2699 ProgressInterface::instance()->appendMessage(time + ": Exporting ...\n");
2700 QFuture<docstring> f = QtConcurrent::run(exportAndDestroy,
2701 doc_buffer->clone(), format);
2702 d.setPreviewFuture(f);
2704 doc_buffer->doExport(format, true);
2708 case LFUN_BUFFER_VIEW: {
2711 string format = argument;
2712 if (argument.empty())
2713 format = doc_buffer->getDefaultOutputFormat();
2714 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
2715 ProgressInterface::instance()->clearMessages();
2716 QString time = QTime::currentTime().toString(Qt::SystemLocaleShortDate);
2717 ProgressInterface::instance()->appendMessage(time + ": Previewing ...\n");
2718 QFuture<docstring> f = QtConcurrent::run(previewAndDestroy,
2719 doc_buffer->clone(), format);
2720 d.setPreviewFuture(f);
2722 doc_buffer->preview(format);
2726 case LFUN_MASTER_BUFFER_UPDATE: {
2729 string format = argument;
2730 Buffer const * master = doc_buffer->masterBuffer();
2731 if (argument.empty())
2732 format = master->getDefaultOutputFormat();
2733 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
2734 QFuture<docstring> f = QtConcurrent::run(exportAndDestroy,
2735 master->clone(), format);
2736 d.setPreviewFuture(f);
2738 master->doExport(format, true);
2742 case LFUN_MASTER_BUFFER_VIEW: {
2743 string format = argument;
2744 Buffer const * master = doc_buffer->masterBuffer();
2745 if (argument.empty())
2746 format = master->getDefaultOutputFormat();
2747 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
2748 QFuture<docstring> f = QtConcurrent::run(previewAndDestroy,
2749 master->clone(), format);
2750 d.setPreviewFuture(f);
2752 master->preview(format);
2756 case LFUN_BUFFER_SWITCH:
2757 if (FileName::isAbsolute(to_utf8(cmd.argument()))) {
2759 theBufferList().getBuffer(FileName(to_utf8(cmd.argument())));
2763 message(_("Document not loaded"));
2767 case LFUN_BUFFER_NEXT:
2768 gotoNextOrPreviousBuffer(NEXTBUFFER);
2771 case LFUN_BUFFER_PREVIOUS:
2772 gotoNextOrPreviousBuffer(PREVBUFFER);
2775 case LFUN_COMMAND_EXECUTE: {
2776 bool const show_it = cmd.argument() != "off";
2777 // FIXME: this is a hack, "minibuffer" should not be
2779 if (GuiToolbar * t = toolbar("minibuffer")) {
2780 t->setVisible(show_it);
2781 if (show_it && t->commandBuffer())
2782 t->commandBuffer()->setFocus();
2786 case LFUN_DROP_LAYOUTS_CHOICE:
2787 d.layout_->showPopup();
2790 case LFUN_MENU_OPEN:
2791 if (QMenu * menu = guiApp->menus().menu(toqstr(cmd.argument()), *this))
2792 menu->exec(QCursor::pos());
2795 case LFUN_FILE_INSERT:
2796 insertLyXFile(cmd.argument());
2798 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
2799 insertPlaintextFile(cmd.argument(), true);
2802 case LFUN_FILE_INSERT_PLAINTEXT:
2803 insertPlaintextFile(cmd.argument(), false);
2806 case LFUN_BUFFER_RELOAD: {
2807 LASSERT(doc_buffer, break);
2808 docstring const file = makeDisplayPath(doc_buffer->absFileName(), 20);
2809 docstring text = bformat(_("Any changes will be lost. Are you sure "
2810 "you want to revert to the saved version of the document %1$s?"), file);
2811 int const ret = Alert::prompt(_("Revert to saved document?"),
2812 text, 1, 1, _("&Revert"), _("&Cancel"));
2815 doc_buffer->markClean();
2821 case LFUN_BUFFER_WRITE:
2822 LASSERT(doc_buffer, break);
2823 saveBuffer(*doc_buffer);
2826 case LFUN_BUFFER_WRITE_AS:
2827 LASSERT(doc_buffer, break);
2828 renameBuffer(*doc_buffer, cmd.argument());
2831 case LFUN_BUFFER_WRITE_ALL: {
2832 Buffer * first = theBufferList().first();
2835 message(_("Saving all documents..."));
2836 // We cannot use a for loop as the buffer list cycles.
2839 if (!b->isClean()) {
2841 LYXERR(Debug::ACTION, "Saved " << b->absFileName());
2843 b = theBufferList().next(b);
2844 } while (b != first);
2845 message(_("All documents saved."));
2849 case LFUN_BUFFER_CLOSE:
2853 case LFUN_BUFFER_CLOSE_ALL:
2857 case LFUN_TOOLBAR_TOGGLE: {
2858 string const name = cmd.getArg(0);
2859 if (GuiToolbar * t = toolbar(name))
2864 case LFUN_DIALOG_UPDATE: {
2865 string const name = to_utf8(cmd.argument());
2866 if (currentBufferView()) {
2867 Inset * inset = currentBufferView()->editedInset(name);
2868 // Can only update a dialog connected to an existing inset
2871 // FIXME: get rid of this indirection; GuiView ask the inset
2872 // if he is kind enough to update itself...
2873 FuncRequest fr(LFUN_INSET_DIALOG_UPDATE, cmd.argument());
2874 inset->dispatch(currentBufferView()->cursor(), fr);
2875 } else if (name == "paragraph") {
2876 lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
2877 } else if (name == "prefs" || name == "document") {
2878 updateDialog(name, string());
2883 case LFUN_DIALOG_TOGGLE: {
2884 if (isDialogVisible(cmd.getArg(0)))
2885 dispatch(FuncRequest(LFUN_DIALOG_HIDE, cmd.argument()));
2887 dispatch(FuncRequest(LFUN_DIALOG_SHOW, cmd.argument()));
2891 case LFUN_DIALOG_DISCONNECT_INSET:
2892 disconnectDialog(to_utf8(cmd.argument()));
2895 case LFUN_DIALOG_HIDE: {
2896 guiApp->hideDialogs(to_utf8(cmd.argument()), 0);
2900 case LFUN_DIALOG_SHOW: {
2901 string const name = cmd.getArg(0);
2902 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
2904 if (name == "character") {
2905 data = freefont2string();
2907 showDialog("character", data);
2908 } else if (name == "latexlog") {
2909 Buffer::LogType type;
2910 string const logfile = doc_buffer->logName(&type);
2912 case Buffer::latexlog:
2915 case Buffer::buildlog:
2919 data += Lexer::quoteString(logfile);
2920 showDialog("log", data);
2921 } else if (name == "vclog") {
2922 string const data = "vc " +
2923 Lexer::quoteString(doc_buffer->lyxvc().getLogFile());
2924 showDialog("log", data);
2925 } else if (name == "symbols") {
2926 data = bv->cursor().getEncoding()->name();
2928 showDialog("symbols", data);
2930 } else if (name == "prefs" && isFullScreen()) {
2931 FuncRequest fr(LFUN_INSET_INSERT, "fullscreen");
2933 showDialog("prefs", data);
2935 showDialog(name, data);
2940 message(cmd.argument());
2943 case LFUN_UI_TOGGLE:
2945 // Make sure the keyboard focus stays in the work area.
2949 case LFUN_SPLIT_VIEW: {
2950 LASSERT(doc_buffer, break);
2951 string const orientation = cmd.getArg(0);
2952 d.splitter_->setOrientation(orientation == "vertical"
2953 ? Qt::Vertical : Qt::Horizontal);
2954 TabWorkArea * twa = addTabWorkArea();
2955 GuiWorkArea * wa = twa->addWorkArea(*doc_buffer, *this);
2956 setCurrentWorkArea(wa);
2959 case LFUN_CLOSE_TAB_GROUP:
2960 if (TabWorkArea * twa = d.currentTabWorkArea()) {
2961 closeTabWorkArea(twa);
2962 d.current_work_area_ = 0;
2963 twa = d.currentTabWorkArea();
2964 // Switch to the next GuiWorkArea in the found TabWorkArea.
2966 // Make sure the work area is up to date.
2967 setCurrentWorkArea(twa->currentWorkArea());
2969 setCurrentWorkArea(0);
2974 case LFUN_COMPLETION_INLINE:
2975 if (d.current_work_area_)
2976 d.current_work_area_->completer().showInline();
2979 case LFUN_COMPLETION_POPUP:
2980 if (d.current_work_area_)
2981 d.current_work_area_->completer().showPopup();
2985 case LFUN_COMPLETION_COMPLETE:
2986 if (d.current_work_area_)
2987 d.current_work_area_->completer().tab();
2990 case LFUN_COMPLETION_CANCEL:
2991 if (d.current_work_area_) {
2992 if (d.current_work_area_->completer().popupVisible())
2993 d.current_work_area_->completer().hidePopup();
2995 d.current_work_area_->completer().hideInline();
2999 case LFUN_COMPLETION_ACCEPT:
3000 if (d.current_work_area_)
3001 d.current_work_area_->completer().activate();
3004 case LFUN_BUFFER_ZOOM_IN:
3005 case LFUN_BUFFER_ZOOM_OUT:
3006 if (cmd.argument().empty()) {
3007 if (cmd.action == LFUN_BUFFER_ZOOM_IN)
3012 lyxrc.zoom += convert<int>(cmd.argument());
3014 if (lyxrc.zoom < 10)
3017 // The global QPixmapCache is used in GuiPainter to cache text
3018 // painting so we must reset it.
3019 QPixmapCache::clear();
3020 guiApp->fontLoader().update();
3021 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
3024 case LFUN_VC_REGISTER:
3025 case LFUN_VC_CHECK_IN:
3026 case LFUN_VC_CHECK_OUT:
3027 case LFUN_VC_REPO_UPDATE:
3028 case LFUN_VC_LOCKING_TOGGLE:
3029 case LFUN_VC_REVERT:
3030 case LFUN_VC_UNDO_LAST:
3031 case LFUN_VC_COMMAND:
3035 case LFUN_SERVER_GOTO_FILE_ROW:
3036 goToFileRow(to_utf8(cmd.argument()));
3044 // Part of automatic menu appearance feature.
3045 if (isFullScreen()) {
3046 if (menuBar()->isVisible() && lyxrc.full_screen_menubar)
3048 if (statusBar()->isVisible())
3049 statusBar()->hide();
3056 void GuiView::lfunUiToggle(FuncRequest const & cmd)
3058 string const arg = cmd.getArg(0);
3059 if (arg == "scrollbar") {
3060 // hide() is of no help
3061 if (d.current_work_area_->verticalScrollBarPolicy() ==
3062 Qt::ScrollBarAlwaysOff)
3064 d.current_work_area_->setVerticalScrollBarPolicy(
3065 Qt::ScrollBarAsNeeded);
3067 d.current_work_area_->setVerticalScrollBarPolicy(
3068 Qt::ScrollBarAlwaysOff);
3071 if (arg == "statusbar") {
3072 statusBar()->setVisible(!statusBar()->isVisible());
3075 if (arg == "menubar") {
3076 menuBar()->setVisible(!menuBar()->isVisible());
3079 #if QT_VERSION >= 0x040300
3080 if (arg == "frame") {
3082 getContentsMargins(&l, &t, &r, &b);
3083 //are the frames in default state?
3084 d.current_work_area_->setFrameStyle(QFrame::NoFrame);
3086 setContentsMargins(-2, -2, -2, -2);
3088 setContentsMargins(0, 0, 0, 0);
3093 if (arg == "fullscreen") {
3098 message(bformat("LFUN_UI_TOGGLE " + _("%1$s unknown command!"), from_utf8(arg)));
3102 void GuiView::toggleFullScreen()
3104 if (isFullScreen()) {
3105 for (int i = 0; i != d.splitter_->count(); ++i)
3106 d.tabWorkArea(i)->setFullScreen(false);
3107 #if QT_VERSION >= 0x040300
3108 setContentsMargins(0, 0, 0, 0);
3110 setWindowState(windowState() ^ Qt::WindowFullScreen);
3113 statusBar()->show();
3116 hideDialogs("prefs", 0);
3117 for (int i = 0; i != d.splitter_->count(); ++i)
3118 d.tabWorkArea(i)->setFullScreen(true);
3119 #if QT_VERSION >= 0x040300
3120 setContentsMargins(-2, -2, -2, -2);
3123 setWindowState(windowState() ^ Qt::WindowFullScreen);
3124 statusBar()->hide();
3125 if (lyxrc.full_screen_menubar)
3127 if (lyxrc.full_screen_toolbars) {
3128 ToolbarMap::iterator end = d.toolbars_.end();
3129 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
3134 // give dialogs like the TOC a chance to adapt
3139 Buffer const * GuiView::updateInset(Inset const * inset)
3141 if (!d.current_work_area_)
3145 d.current_work_area_->scheduleRedraw();
3147 return &d.current_work_area_->bufferView().buffer();
3151 void GuiView::restartCursor()
3153 /* When we move around, or type, it's nice to be able to see
3154 * the cursor immediately after the keypress.
3156 if (d.current_work_area_)
3157 d.current_work_area_->startBlinkingCursor();
3159 // Take this occasion to update the other GUI elements.
3165 void GuiView::updateCompletion(Cursor & cur, bool start, bool keep)
3167 if (d.current_work_area_)
3168 d.current_work_area_->completer().updateVisibility(cur, start, keep);
3173 // This list should be kept in sync with the list of insets in
3174 // src/insets/Inset.cpp. I.e., if a dialog goes with an inset, the
3175 // dialog should have the same name as the inset.
3176 // Changes should be also recorded in LFUN_DIALOG_SHOW doxygen
3177 // docs in LyXAction.cpp.
3179 char const * const dialognames[] = {
3180 "aboutlyx", "bibitem", "bibtex", "box", "branch", "changes", "character",
3181 "citation", "compare", "document", "errorlist", "ert", "external", "file",
3182 "findreplace", "findreplaceadv", "float", "graphics", "href", "include",
3183 "index", "index_print", "info", "listings", "label", "log", "mathdelimiter",
3184 "mathmatrix", "mathspace", "nomenclature", "nomencl_print", "note",
3185 "paragraph", "phantom", "prefs", "print", "ref", "sendto", "space",
3186 "spellchecker", "symbols", "tabular", "tabularcreate", "thesaurus", "texinfo",
3187 "toc", "view-source", "vspace", "wrap"};
3189 char const * const * const end_dialognames =
3190 dialognames + (sizeof(dialognames) / sizeof(char *));
3194 cmpCStr(char const * name) : name_(name) {}
3195 bool operator()(char const * other) {
3196 return strcmp(other, name_) == 0;
3203 bool isValidName(string const & name)
3205 return find_if(dialognames, end_dialognames,
3206 cmpCStr(name.c_str())) != end_dialognames;
3212 void GuiView::resetDialogs()
3214 // Make sure that no LFUN uses any LyXView.
3215 guiApp->setCurrentView(0);
3218 constructToolbars();
3219 guiApp->menus().fillMenuBar(menuBar(), this, false);
3220 d.layout_->updateContents(true);
3221 // Now update controls with current buffer.
3222 guiApp->setCurrentView(this);
3228 Dialog * GuiView::findOrBuild(string const & name, bool hide_it)
3230 if (!isValidName(name))
3233 map<string, DialogPtr>::iterator it = d.dialogs_.find(name);
3235 if (it != d.dialogs_.end()) {
3237 it->second->hideView();
3238 return it->second.get();
3241 Dialog * dialog = build(name);
3242 d.dialogs_[name].reset(dialog);
3243 if (lyxrc.allow_geometry_session)
3244 dialog->restoreSession();
3251 void GuiView::showDialog(string const & name, string const & data,
3259 Dialog * dialog = findOrBuild(name, false);
3261 dialog->showData(data);
3262 if (inset && currentBufferView())
3263 currentBufferView()->editInset(name, inset);
3266 catch (ExceptionMessage const & ex) {
3274 bool GuiView::isDialogVisible(string const & name) const
3276 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3277 if (it == d.dialogs_.end())
3279 return it->second.get()->isVisibleView() && !it->second.get()->isClosing();
3283 void GuiView::hideDialog(string const & name, Inset * inset)
3285 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3286 if (it == d.dialogs_.end())
3289 if (inset && currentBufferView()
3290 && inset != currentBufferView()->editedInset(name))
3293 Dialog * const dialog = it->second.get();
3294 if (dialog->isVisibleView())
3296 if (currentBufferView())
3297 currentBufferView()->editInset(name, 0);
3301 void GuiView::disconnectDialog(string const & name)
3303 if (!isValidName(name))
3305 if (currentBufferView())
3306 currentBufferView()->editInset(name, 0);
3310 void GuiView::hideAll() const
3312 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
3313 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3315 for(; it != end; ++it)
3316 it->second->hideView();
3320 void GuiView::updateDialogs()
3322 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
3323 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3325 for(; it != end; ++it) {
3326 Dialog * dialog = it->second.get();
3327 if (dialog && dialog->isVisibleView())
3328 dialog->checkStatus();
3335 // will be replaced by a proper factory...
3336 Dialog * createGuiAbout(GuiView & lv);
3337 Dialog * createGuiBibitem(GuiView & lv);
3338 Dialog * createGuiBibtex(GuiView & lv);
3339 Dialog * createGuiBox(GuiView & lv);
3340 Dialog * createGuiBranch(GuiView & lv);
3341 Dialog * createGuiChanges(GuiView & lv);
3342 Dialog * createGuiCharacter(GuiView & lv);
3343 Dialog * createGuiCitation(GuiView & lv);
3344 Dialog * createGuiCompare(GuiView & lv);
3345 Dialog * createGuiDelimiter(GuiView & lv);
3346 Dialog * createGuiDocument(GuiView & lv);
3347 Dialog * createGuiErrorList(GuiView & lv);
3348 Dialog * createGuiERT(GuiView & lv);
3349 Dialog * createGuiExternal(GuiView & lv);
3350 Dialog * createGuiFloat(GuiView & lv);
3351 Dialog * createGuiGraphics(GuiView & lv);
3352 Dialog * createGuiInclude(GuiView & lv);
3353 Dialog * createGuiIndex(GuiView & lv);
3354 Dialog * createGuiInfo(GuiView & lv);
3355 Dialog * createGuiLabel(GuiView & lv);
3356 Dialog * createGuiListings(GuiView & lv);
3357 Dialog * createGuiLog(GuiView & lv);
3358 Dialog * createGuiMathHSpace(GuiView & lv);
3359 Dialog * createGuiMathMatrix(GuiView & lv);
3360 Dialog * createGuiNomenclature(GuiView & lv);
3361 Dialog * createGuiNote(GuiView & lv);
3362 Dialog * createGuiParagraph(GuiView & lv);
3363 Dialog * createGuiPhantom(GuiView & lv);
3364 Dialog * createGuiPreferences(GuiView & lv);
3365 Dialog * createGuiPrint(GuiView & lv);
3366 Dialog * createGuiPrintindex(GuiView & lv);
3367 Dialog * createGuiPrintNomencl(GuiView & lv);
3368 Dialog * createGuiRef(GuiView & lv);
3369 Dialog * createGuiSearch(GuiView & lv);
3370 Dialog * createGuiSearchAdv(GuiView & lv);
3371 Dialog * createGuiSendTo(GuiView & lv);
3372 Dialog * createGuiShowFile(GuiView & lv);
3373 Dialog * createGuiSpellchecker(GuiView & lv);
3374 Dialog * createGuiSymbols(GuiView & lv);
3375 Dialog * createGuiTabularCreate(GuiView & lv);
3376 Dialog * createGuiTabular(GuiView & lv);
3377 Dialog * createGuiTexInfo(GuiView & lv);
3378 Dialog * createGuiTextHSpace(GuiView & lv);
3379 Dialog * createGuiToc(GuiView & lv);
3380 Dialog * createGuiThesaurus(GuiView & lv);
3381 Dialog * createGuiHyperlink(GuiView & lv);
3382 Dialog * createGuiVSpace(GuiView & lv);
3383 Dialog * createGuiViewSource(GuiView & lv);
3384 Dialog * createGuiWrap(GuiView & lv);
3388 Dialog * GuiView::build(string const & name)
3390 LASSERT(isValidName(name), return 0);
3392 if (name == "aboutlyx")
3393 return createGuiAbout(*this);
3394 if (name == "bibitem")
3395 return createGuiBibitem(*this);
3396 if (name == "bibtex")
3397 return createGuiBibtex(*this);
3399 return createGuiBox(*this);
3400 if (name == "branch")
3401 return createGuiBranch(*this);
3402 if (name == "changes")
3403 return createGuiChanges(*this);
3404 if (name == "character")
3405 return createGuiCharacter(*this);
3406 if (name == "citation")
3407 return createGuiCitation(*this);
3408 if (name == "compare")
3409 return createGuiCompare(*this);
3410 if (name == "document")
3411 return createGuiDocument(*this);
3412 if (name == "errorlist")
3413 return createGuiErrorList(*this);
3415 return createGuiERT(*this);
3416 if (name == "external")
3417 return createGuiExternal(*this);
3419 return createGuiShowFile(*this);
3420 if (name == "findreplace")
3421 return createGuiSearch(*this);
3422 if (name == "findreplaceadv")
3423 return createGuiSearchAdv(*this);
3424 if (name == "float")
3425 return createGuiFloat(*this);
3426 if (name == "graphics")
3427 return createGuiGraphics(*this);
3429 return createGuiHyperlink(*this);
3430 if (name == "include")
3431 return createGuiInclude(*this);
3432 if (name == "index")
3433 return createGuiIndex(*this);
3434 if (name == "index_print")
3435 return createGuiPrintindex(*this);
3437 return createGuiInfo(*this);
3438 if (name == "label")
3439 return createGuiLabel(*this);
3440 if (name == "listings")
3441 return createGuiListings(*this);
3443 return createGuiLog(*this);
3444 if (name == "mathdelimiter")
3445 return createGuiDelimiter(*this);
3446 if (name == "mathspace")
3447 return createGuiMathHSpace(*this);
3448 if (name == "mathmatrix")
3449 return createGuiMathMatrix(*this);
3450 if (name == "nomenclature")
3451 return createGuiNomenclature(*this);
3452 if (name == "nomencl_print")
3453 return createGuiPrintNomencl(*this);
3455 return createGuiNote(*this);
3456 if (name == "paragraph")
3457 return createGuiParagraph(*this);
3458 if (name == "phantom")
3459 return createGuiPhantom(*this);
3460 if (name == "prefs")
3461 return createGuiPreferences(*this);
3462 if (name == "print")
3463 return createGuiPrint(*this);
3465 return createGuiRef(*this);
3466 if (name == "sendto")
3467 return createGuiSendTo(*this);
3468 if (name == "space")
3469 return createGuiTextHSpace(*this);
3470 if (name == "spellchecker")
3471 return createGuiSpellchecker(*this);
3472 if (name == "symbols")
3473 return createGuiSymbols(*this);
3474 if (name == "tabular")
3475 return createGuiTabular(*this);
3476 if (name == "tabularcreate")
3477 return createGuiTabularCreate(*this);
3478 if (name == "texinfo")
3479 return createGuiTexInfo(*this);
3480 if (name == "thesaurus")
3481 return createGuiThesaurus(*this);
3483 return createGuiToc(*this);
3484 if (name == "view-source")
3485 return createGuiViewSource(*this);
3486 if (name == "vspace")
3487 return createGuiVSpace(*this);
3489 return createGuiWrap(*this);
3495 } // namespace frontend
3498 #include "moc_GuiView.cpp"