3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Lars Gullik Bjønnes
8 * \author Abdelrazak Younes
11 * Full author contact details are available in file CREDITS.
19 #include "FileDialog.h"
20 #include "FontLoader.h"
21 #include "GuiApplication.h"
22 #include "GuiCommandBuffer.h"
23 #include "GuiCompleter.h"
24 #include "GuiKeySymbol.h"
26 #include "GuiToolbar.h"
27 #include "GuiWorkArea.h"
28 #include "LayoutBox.h"
32 #include "qt_helpers.h"
34 #include "frontends/alert.h"
36 #include "buffer_funcs.h"
38 #include "BufferList.h"
39 #include "BufferParams.h"
40 #include "BufferView.h"
41 #include "Converter.h"
43 #include "CutAndPaste.h"
45 #include "ErrorList.h"
47 #include "FuncStatus.h"
48 #include "FuncRequest.h"
52 #include "LyXAction.h"
57 #include "Paragraph.h"
58 #include "SpellChecker.h"
59 #include "TextClass.h"
64 #include "support/convert.h"
65 #include "support/debug.h"
66 #include "support/ExceptionMessage.h"
67 #include "support/FileName.h"
68 #include "support/filetools.h"
69 #include "support/gettext.h"
70 #include "support/filetools.h"
71 #include "support/ForkedCalls.h"
72 #include "support/lassert.h"
73 #include "support/lstrings.h"
74 #include "support/os.h"
75 #include "support/Package.h"
76 #include "support/Path.h"
77 #include "support/Systemcall.h"
78 #include "support/Timeout.h"
79 #include "support/ProgressInterface.h"
80 #include "GuiProgress.h"
83 #include <QApplication>
84 #include <QCloseEvent>
86 #include <QDesktopWidget>
87 #include <QDragEnterEvent>
94 #include <QPixmapCache>
96 #include <QPushButton>
100 #include <QStackedWidget>
101 #include <QStatusBar>
106 #include <QScrollBar>
108 #define EXPORT_in_THREAD 1
111 // QtConcurrent was introduced in Qt 4.4
112 #if (QT_VERSION >= 0x040400)
114 #include <QFutureWatcher>
115 #include <QtConcurrentRun>
118 #include <boost/bind.hpp>
122 #ifdef HAVE_SYS_TIME_H
123 # include <sys/time.h>
130 using namespace lyx::support;
137 class BackgroundWidget : public QWidget
142 LYXERR(Debug::GUI, "show banner: " << lyxrc.show_banner);
143 /// The text to be written on top of the pixmap
144 QString const text = lyx_version ?
145 qt_("version ") + lyx_version : qt_("unknown version");
146 splash_ = getPixmap("images/", "banner", "png");
148 QPainter pain(&splash_);
149 pain.setPen(QColor(0, 0, 0));
151 // The font used to display the version info
152 font.setStyleHint(QFont::SansSerif);
153 font.setWeight(QFont::Bold);
154 font.setPointSize(int(toqstr(lyxrc.font_sizes[FONT_SIZE_LARGE]).toDouble()));
156 pain.drawText(260, 15, text);
157 setFocusPolicy(Qt::StrongFocus);
160 void paintEvent(QPaintEvent *)
162 int x = (width() - splash_.width()) / 2;
163 int y = (height() - splash_.height()) / 2;
165 pain.drawPixmap(x, y, splash_);
168 void keyPressEvent(QKeyEvent * ev)
171 setKeySymbol(&sym, ev);
173 guiApp->processKeySym(sym, q_key_state(ev->modifiers()));
185 /// Toolbar store providing access to individual toolbars by name.
186 typedef map<string, GuiToolbar *> ToolbarMap;
188 typedef boost::shared_ptr<Dialog> DialogPtr;
193 struct GuiView::GuiViewPrivate
195 GuiViewPrivate(GuiView * gv)
196 : gv_(gv), current_work_area_(0), current_main_work_area_(0),
197 layout_(0), autosave_timeout_(5000),
200 // hardcode here the platform specific icon size
201 smallIconSize = 14; // scaling problems
202 normalIconSize = 20; // ok, default
203 bigIconSize = 26; // better for some math icons
205 splitter_ = new QSplitter;
206 bg_widget_ = new BackgroundWidget;
207 stack_widget_ = new QStackedWidget;
208 stack_widget_->addWidget(bg_widget_);
209 stack_widget_->addWidget(splitter_);
211 progress_ = new GuiProgress(gv);
218 delete stack_widget_;
222 QMenu * toolBarPopup(GuiView * parent)
224 // FIXME: translation
225 QMenu * menu = new QMenu(parent);
226 QActionGroup * iconSizeGroup = new QActionGroup(parent);
228 QAction * smallIcons = new QAction(iconSizeGroup);
229 smallIcons->setText(qt_("Small-sized icons"));
230 smallIcons->setCheckable(true);
231 QObject::connect(smallIcons, SIGNAL(triggered()),
232 parent, SLOT(smallSizedIcons()));
233 menu->addAction(smallIcons);
235 QAction * normalIcons = new QAction(iconSizeGroup);
236 normalIcons->setText(qt_("Normal-sized icons"));
237 normalIcons->setCheckable(true);
238 QObject::connect(normalIcons, SIGNAL(triggered()),
239 parent, SLOT(normalSizedIcons()));
240 menu->addAction(normalIcons);
242 QAction * bigIcons = new QAction(iconSizeGroup);
243 bigIcons->setText(qt_("Big-sized icons"));
244 bigIcons->setCheckable(true);
245 QObject::connect(bigIcons, SIGNAL(triggered()),
246 parent, SLOT(bigSizedIcons()));
247 menu->addAction(bigIcons);
249 unsigned int cur = parent->iconSize().width();
250 if ( cur == parent->d.smallIconSize)
251 smallIcons->setChecked(true);
252 else if (cur == parent->d.normalIconSize)
253 normalIcons->setChecked(true);
254 else if (cur == parent->d.bigIconSize)
255 bigIcons->setChecked(true);
262 stack_widget_->setCurrentWidget(bg_widget_);
263 bg_widget_->setUpdatesEnabled(true);
264 bg_widget_->setFocus();
267 TabWorkArea * tabWorkArea(int i)
269 return dynamic_cast<TabWorkArea *>(splitter_->widget(i));
272 TabWorkArea * currentTabWorkArea()
274 if (splitter_->count() == 1)
275 // The first TabWorkArea is always the first one, if any.
276 return tabWorkArea(0);
278 for (int i = 0; i != splitter_->count(); ++i) {
279 TabWorkArea * twa = tabWorkArea(i);
280 if (current_main_work_area_ == twa->currentWorkArea())
284 // None has the focus so we just take the first one.
285 return tabWorkArea(0);
288 #if (QT_VERSION >= 0x040400)
289 void setPreviewFuture(QFuture<docstring> const & f)
291 if (preview_watcher_.isRunning()) {
292 // we prefer to cancel this preview in order to keep a snappy
296 preview_watcher_.setFuture(f);
302 GuiWorkArea * current_work_area_;
303 GuiWorkArea * current_main_work_area_;
304 QSplitter * splitter_;
305 QStackedWidget * stack_widget_;
306 BackgroundWidget * bg_widget_;
308 ToolbarMap toolbars_;
309 ProgressInterface* progress_;
310 /// The main layout box.
312 * \warning Don't Delete! The layout box is actually owned by
313 * whichever toolbar contains it. All the GuiView class needs is a
314 * means of accessing it.
316 * FIXME: replace that with a proper model so that we are not limited
317 * to only one dialog.
322 map<string, DialogPtr> dialogs_;
324 unsigned int smallIconSize;
325 unsigned int normalIconSize;
326 unsigned int bigIconSize;
328 QTimer statusbar_timer_;
329 /// auto-saving of buffers
330 Timeout autosave_timeout_;
331 /// flag against a race condition due to multiclicks, see bug #1119
335 TocModels toc_models_;
337 #if (QT_VERSION >= 0x040400)
339 QFutureWatcher<docstring> autosave_watcher_;
340 QFutureWatcher<docstring> preview_watcher_;
342 struct DummyWatcher { bool isRunning(){return false;} };
343 DummyWatcher preview_watcher_;
348 GuiView::GuiView(int id)
349 : d(*new GuiViewPrivate(this)), id_(id), closing_(false)
351 // GuiToolbars *must* be initialised before the menu bar.
352 normalSizedIcons(); // at least on Mac the default is 32 otherwise, which is huge
355 // set ourself as the current view. This is needed for the menu bar
356 // filling, at least for the static special menu item on Mac. Otherwise
357 // they are greyed out.
358 guiApp->setCurrentView(this);
360 // Fill up the menu bar.
361 guiApp->menus().fillMenuBar(menuBar(), this, true);
363 setCentralWidget(d.stack_widget_);
365 // Start autosave timer
366 if (lyxrc.autosave) {
367 d.autosave_timeout_.timeout.connect(boost::bind(&GuiView::autoSave, this));
368 d.autosave_timeout_.setTimeout(lyxrc.autosave * 1000);
369 d.autosave_timeout_.start();
371 connect(&d.statusbar_timer_, SIGNAL(timeout()),
372 this, SLOT(clearMessage()));
374 // We don't want to keep the window in memory if it is closed.
375 setAttribute(Qt::WA_DeleteOnClose, true);
377 #if (!defined(Q_WS_WIN) && !defined(Q_WS_MACX))
378 // assign an icon to main form. We do not do it under Qt/Win or Qt/Mac,
379 // since the icon is provided in the application bundle.
380 setWindowIcon(getPixmap("images/", "lyx", "png"));
384 setAcceptDrops(true);
386 statusBar()->setSizeGripEnabled(true);
389 #if (QT_VERSION >= 0x040400)
390 connect(&d.autosave_watcher_, SIGNAL(finished()), this,
391 SLOT(threadFinished()));
392 connect(&d.preview_watcher_, SIGNAL(finished()), this,
393 SLOT(threadFinished()));
396 connect(this, SIGNAL(triggerShowDialog(QString const &, QString const &, Inset *)),
397 SLOT(doShowDialog(QString const &, QString const &, Inset *)));
399 // Forbid too small unresizable window because it can happen
400 // with some window manager under X11.
401 setMinimumSize(300, 200);
403 if (lyxrc.allow_geometry_session) {
404 // Now take care of session management.
409 // no session handling, default to a sane size.
410 setGeometry(50, 50, 690, 510);
413 // clear session data if any.
415 settings.remove("views");
425 void GuiView::threadFinished()
427 #if (QT_VERSION >= 0x040400)
428 QFutureWatcher<docstring> const * watcher =
429 static_cast<QFutureWatcher<docstring> const *>(sender());
430 message(watcher->result());
435 void GuiView::saveLayout() const
438 settings.beginGroup("views");
439 settings.beginGroup(QString::number(id_));
441 settings.setValue("pos", pos());
442 settings.setValue("size", size());
444 settings.setValue("geometry", saveGeometry());
446 settings.setValue("layout", saveState(0));
447 settings.setValue("icon_size", iconSize());
451 bool GuiView::restoreLayout()
454 settings.beginGroup("views");
455 settings.beginGroup(QString::number(id_));
456 QString const icon_key = "icon_size";
457 if (!settings.contains(icon_key))
460 //code below is skipped when when ~/.config/LyX is (re)created
461 setIconSize(settings.value(icon_key).toSize());
463 QPoint pos = settings.value("pos", QPoint(50, 50)).toPoint();
464 QSize size = settings.value("size", QSize(690, 510)).toSize();
468 // Work-around for bug #6034: the window ends up in an undetermined
469 // state when trying to restore a maximized window when it is
470 // already maximized.
471 if (!(windowState() & Qt::WindowMaximized))
472 if (!restoreGeometry(settings.value("geometry").toByteArray()))
473 setGeometry(50, 50, 690, 510);
475 // Make sure layout is correctly oriented.
476 setLayoutDirection(qApp->layoutDirection());
478 // Allow the toc and view-source dock widget to be restored if needed.
480 if ((dialog = findOrBuild("toc", true)))
481 // see bug 5082. At least setup title and enabled state.
482 // Visibility will be adjusted by restoreState below.
483 dialog->prepareView();
484 if ((dialog = findOrBuild("view-source", true)))
485 dialog->prepareView();
486 if ((dialog = findOrBuild("progress", true)))
487 dialog->prepareView();
489 if (!restoreState(settings.value("layout").toByteArray(), 0))
496 GuiToolbar * GuiView::toolbar(string const & name)
498 ToolbarMap::iterator it = d.toolbars_.find(name);
499 if (it != d.toolbars_.end())
502 LYXERR(Debug::GUI, "Toolbar::display: no toolbar named " << name);
503 message(bformat(_("Unknown toolbar \"%1$s\""), from_utf8(name)));
508 void GuiView::constructToolbars()
510 ToolbarMap::iterator it = d.toolbars_.begin();
511 for (; it != d.toolbars_.end(); ++it)
515 // I don't like doing this here, but the standard toolbar
516 // destroys this object when it's destroyed itself (vfr)
517 d.layout_ = new LayoutBox(*this);
518 d.stack_widget_->addWidget(d.layout_);
519 d.layout_->move(0,0);
521 // extracts the toolbars from the backend
522 Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
523 Toolbars::Infos::iterator end = guiApp->toolbars().end();
524 for (; cit != end; ++cit)
525 d.toolbars_[cit->name] = new GuiToolbar(*cit, *this);
529 void GuiView::initToolbars()
531 // extracts the toolbars from the backend
532 Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
533 Toolbars::Infos::iterator end = guiApp->toolbars().end();
534 for (; cit != end; ++cit) {
535 GuiToolbar * tb = toolbar(cit->name);
538 int const visibility = guiApp->toolbars().defaultVisibility(cit->name);
539 bool newline = !(visibility & Toolbars::SAMEROW);
540 tb->setVisible(false);
541 tb->setVisibility(visibility);
543 if (visibility & Toolbars::TOP) {
545 addToolBarBreak(Qt::TopToolBarArea);
546 addToolBar(Qt::TopToolBarArea, tb);
549 if (visibility & Toolbars::BOTTOM) {
550 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
551 #if (QT_VERSION >= 0x040202)
553 addToolBarBreak(Qt::BottomToolBarArea);
555 addToolBar(Qt::BottomToolBarArea, tb);
558 if (visibility & Toolbars::LEFT) {
559 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
560 #if (QT_VERSION >= 0x040202)
562 addToolBarBreak(Qt::LeftToolBarArea);
564 addToolBar(Qt::LeftToolBarArea, tb);
567 if (visibility & Toolbars::RIGHT) {
568 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
569 #if (QT_VERSION >= 0x040202)
571 addToolBarBreak(Qt::RightToolBarArea);
573 addToolBar(Qt::RightToolBarArea, tb);
576 if (visibility & Toolbars::ON)
577 tb->setVisible(true);
582 TocModels & GuiView::tocModels()
584 return d.toc_models_;
588 void GuiView::setFocus()
590 LYXERR(Debug::DEBUG, "GuiView::setFocus()" << this);
591 QMainWindow::setFocus();
595 void GuiView::focusInEvent(QFocusEvent * e)
597 LYXERR(Debug::DEBUG, "GuiView::focusInEvent()" << this);
598 QMainWindow::focusInEvent(e);
599 // Make sure LyXFunc points to the correct view.
600 guiApp->setCurrentView(this);
601 if (currentMainWorkArea())
602 currentMainWorkArea()->setFocus();
603 else if (currentWorkArea())
604 currentWorkArea()->setFocus();
606 d.bg_widget_->setFocus();
610 QMenu * GuiView::createPopupMenu()
612 return d.toolBarPopup(this);
616 void GuiView::showEvent(QShowEvent * e)
618 LYXERR(Debug::GUI, "Passed Geometry "
619 << size().height() << "x" << size().width()
620 << "+" << pos().x() << "+" << pos().y());
622 if (d.splitter_->count() == 0)
623 // No work area, switch to the background widget.
626 QMainWindow::showEvent(e);
630 /** Destroy only all tabbed WorkAreas. Destruction of other WorkAreas
631 ** is responsibility of the container (e.g., dialog)
633 void GuiView::closeEvent(QCloseEvent * close_event)
635 LYXERR(Debug::DEBUG, "GuiView::closeEvent()");
640 // it can happen that this event arrives without selecting the view,
641 // e.g. when clicking the close button on a background window.
643 if (!closeWorkAreaAll()) {
645 close_event->ignore();
649 // Make sure that nothing will use this to be closed View.
650 guiApp->unregisterView(this);
652 if (isFullScreen()) {
653 // Switch off fullscreen before closing.
658 // Make sure the timer time out will not trigger a statusbar update.
659 d.statusbar_timer_.stop();
661 // Saving fullscreen requires additional tweaks in the toolbar code.
662 // It wouldn't also work under linux natively.
663 if (lyxrc.allow_geometry_session) {
664 // Save this window geometry and layout.
666 // Then the toolbar private states.
667 ToolbarMap::iterator end = d.toolbars_.end();
668 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
669 it->second->saveSession();
670 // Now take care of all other dialogs:
671 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
672 for (; it!= d.dialogs_.end(); ++it)
673 it->second->saveSession();
676 close_event->accept();
680 void GuiView::dragEnterEvent(QDragEnterEvent * event)
682 if (event->mimeData()->hasUrls())
684 /// \todo Ask lyx-devel is this is enough:
685 /// if (event->mimeData()->hasFormat("text/plain"))
686 /// event->acceptProposedAction();
690 void GuiView::dropEvent(QDropEvent * event)
692 QList<QUrl> files = event->mimeData()->urls();
696 LYXERR(Debug::GUI, "GuiView::dropEvent: got URLs!");
697 for (int i = 0; i != files.size(); ++i) {
698 string const file = os::internal_path(fromqstr(
699 files.at(i).toLocalFile()));
703 string const ext = support::getExtension(file);
704 vector<const Format *> found_formats;
706 // Find all formats that have the correct extension.
707 vector<const Format *> const & import_formats
708 = theConverters().importableFormats();
709 vector<const Format *>::const_iterator it = import_formats.begin();
710 for (; it != import_formats.end(); ++it)
711 if ((*it)->extension() == ext)
712 found_formats.push_back(*it);
715 if (found_formats.size() >= 1) {
716 if (found_formats.size() > 1) {
717 //FIXME: show a dialog to choose the correct importable format
719 "Multiple importable formats found, selecting first");
721 string const arg = found_formats[0]->name() + " " + file;
722 cmd = FuncRequest(LFUN_BUFFER_IMPORT, arg);
725 //FIXME: do we have to explicitly check whether it's a lyx file?
727 "No formats found, trying to open it as a lyx file");
728 cmd = FuncRequest(LFUN_FILE_OPEN, file);
731 // Asynchronously post the event. DropEvent usually comes
732 // from the BufferView. But reloading a file might close
733 // the BufferView from within its own event handler.
734 guiApp->dispatchDelayed(cmd);
740 void GuiView::message(docstring const & str)
742 if (ForkedProcess::iAmAChild())
745 // call is moved to GUI-thread by GuiProgress
746 d.progress_->appendMessage(toqstr(str));
750 void GuiView::updateMessage(QString const & str)
752 statusBar()->showMessage(str);
753 d.statusbar_timer_.stop();
754 d.statusbar_timer_.start(3000);
758 void GuiView::smallSizedIcons()
760 setIconSize(QSize(d.smallIconSize, d.smallIconSize));
764 void GuiView::normalSizedIcons()
766 setIconSize(QSize(d.normalIconSize, d.normalIconSize));
770 void GuiView::bigSizedIcons()
772 setIconSize(QSize(d.bigIconSize, d.bigIconSize));
776 void GuiView::clearMessage()
778 // FIXME: This code was introduced in r19643 to fix bug #4123. However,
779 // the hasFocus function mostly returns false, even if the focus is on
780 // a workarea in this view.
784 d.statusbar_timer_.stop();
788 void GuiView::updateWindowTitle(GuiWorkArea * wa)
790 if (wa != d.current_work_area_
791 || wa->bufferView().buffer().isInternal())
793 setWindowTitle(qt_("LyX: ") + wa->windowTitle());
794 setWindowIconText(wa->windowIconText());
798 void GuiView::on_currentWorkAreaChanged(GuiWorkArea * wa)
801 disconnectBufferView();
802 connectBufferView(wa->bufferView());
803 connectBuffer(wa->bufferView().buffer());
804 d.current_work_area_ = wa;
805 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
806 this, SLOT(updateWindowTitle(GuiWorkArea *)));
807 updateWindowTitle(wa);
811 // The document settings needs to be reinitialised.
812 updateDialog("document", "");
814 // Buffer-dependent dialogs must be updated. This is done here because
815 // some dialogs require buffer()->text.
820 void GuiView::on_lastWorkAreaRemoved()
823 // We already are in a close event. Nothing more to do.
826 if (d.splitter_->count() > 1)
827 // We have a splitter so don't close anything.
830 // Reset and updates the dialogs.
831 d.toc_models_.reset(0);
832 updateDialog("document", "");
835 resetWindowTitleAndIconText();
838 if (lyxrc.open_buffers_in_tabs)
839 // Nothing more to do, the window should stay open.
842 if (guiApp->viewIds().size() > 1) {
848 // On Mac we also close the last window because the application stay
849 // resident in memory. On other platforms we don't close the last
850 // window because this would quit the application.
856 void GuiView::updateStatusBar()
858 // let the user see the explicit message
859 if (d.statusbar_timer_.isActive())
866 void GuiView::showMessage()
868 QString msg = toqstr(theGuiApp()->viewStatusMessage());
870 BufferView const * bv = currentBufferView();
872 msg = toqstr(bv->cursor().currentState());
874 msg = qt_("Welcome to LyX!");
876 statusBar()->showMessage(msg);
880 bool GuiView::event(QEvent * e)
884 // Useful debug code:
885 //case QEvent::ActivationChange:
886 //case QEvent::WindowDeactivate:
887 //case QEvent::Paint:
888 //case QEvent::Enter:
889 //case QEvent::Leave:
890 //case QEvent::HoverEnter:
891 //case QEvent::HoverLeave:
892 //case QEvent::HoverMove:
893 //case QEvent::StatusTip:
894 //case QEvent::DragEnter:
895 //case QEvent::DragLeave:
899 case QEvent::WindowActivate: {
900 GuiView * old_view = guiApp->currentView();
901 if (this == old_view) {
903 return QMainWindow::event(e);
905 if (old_view && old_view->currentBufferView()) {
906 // save current selection to the selection buffer to allow
907 // middle-button paste in this window.
908 cap::saveSelection(old_view->currentBufferView()->cursor());
910 guiApp->setCurrentView(this);
911 if (d.current_work_area_) {
912 BufferView & bv = d.current_work_area_->bufferView();
913 connectBufferView(bv);
914 connectBuffer(bv.buffer());
915 // The document structure, name and dialogs might have
916 // changed in another view.
918 // The document settings needs to be reinitialised.
919 updateDialog("document", "");
922 resetWindowTitleAndIconText();
925 return QMainWindow::event(e);
928 case QEvent::ShortcutOverride: {
931 #if (!defined Q_WS_X11) || (QT_VERSION >= 0x040500)
932 if (isFullScreen() && menuBar()->isHidden()) {
933 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
934 // FIXME: we should also try to detect special LyX shortcut such as
935 // Alt-P and Alt-M. Right now there is a hack in
936 // GuiWorkArea::processKeySym() that hides again the menubar for
938 if (ke->modifiers() & Qt::AltModifier && ke->key() != Qt::Key_Alt) {
940 return QMainWindow::event(e);
944 return QMainWindow::event(e);
948 return QMainWindow::event(e);
952 void GuiView::resetWindowTitleAndIconText()
954 setWindowTitle(qt_("LyX"));
955 setWindowIconText(qt_("LyX"));
958 bool GuiView::focusNextPrevChild(bool /*next*/)
965 void GuiView::setBusy(bool busy)
967 if (d.current_work_area_) {
968 d.current_work_area_->setUpdatesEnabled(!busy);
970 d.current_work_area_->stopBlinkingCursor();
972 d.current_work_area_->startBlinkingCursor();
976 QApplication::setOverrideCursor(Qt::WaitCursor);
978 QApplication::restoreOverrideCursor();
982 GuiWorkArea * GuiView::workArea(Buffer & buffer)
984 if (currentWorkArea()
985 && ¤tWorkArea()->bufferView().buffer() == &buffer)
986 return (GuiWorkArea *) currentWorkArea();
987 if (TabWorkArea * twa = d.currentTabWorkArea())
988 return twa->workArea(buffer);
993 GuiWorkArea * GuiView::addWorkArea(Buffer & buffer)
995 // Automatically create a TabWorkArea if there are none yet.
996 TabWorkArea * tab_widget = d.splitter_->count()
997 ? d.currentTabWorkArea() : addTabWorkArea();
998 return tab_widget->addWorkArea(buffer, *this);
1002 TabWorkArea * GuiView::addTabWorkArea()
1004 TabWorkArea * twa = new TabWorkArea;
1005 QObject::connect(twa, SIGNAL(currentWorkAreaChanged(GuiWorkArea *)),
1006 this, SLOT(on_currentWorkAreaChanged(GuiWorkArea *)));
1007 QObject::connect(twa, SIGNAL(lastWorkAreaRemoved()),
1008 this, SLOT(on_lastWorkAreaRemoved()));
1010 d.splitter_->addWidget(twa);
1011 d.stack_widget_->setCurrentWidget(d.splitter_);
1016 GuiWorkArea const * GuiView::currentWorkArea() const
1018 return d.current_work_area_;
1022 GuiWorkArea * GuiView::currentWorkArea()
1024 return d.current_work_area_;
1028 GuiWorkArea const * GuiView::currentMainWorkArea() const
1030 if (d.currentTabWorkArea() == NULL)
1032 return d.currentTabWorkArea()->currentWorkArea();
1036 GuiWorkArea * GuiView::currentMainWorkArea()
1038 if (d.currentTabWorkArea() == NULL)
1040 return d.currentTabWorkArea()->currentWorkArea();
1044 void GuiView::setCurrentWorkArea(GuiWorkArea * wa)
1046 LYXERR(Debug::DEBUG, "Setting current wa: " << wa << endl);
1048 d.current_work_area_ = NULL;
1052 GuiWorkArea * old_gwa = theGuiApp()->currentView()->currentWorkArea();
1056 if (currentBufferView())
1057 cap::saveSelection(currentBufferView()->cursor());
1059 theGuiApp()->setCurrentView(this);
1060 d.current_work_area_ = wa;
1061 for (int i = 0; i != d.splitter_->count(); ++i) {
1062 if (d.tabWorkArea(i)->setCurrentWorkArea(wa)) {
1063 //if (d.current_main_work_area_)
1064 // d.current_main_work_area_->setFrameStyle(QFrame::NoFrame);
1065 d.current_main_work_area_ = wa;
1066 //d.current_main_work_area_->setFrameStyle(QFrame::Box | QFrame::Plain);
1067 //d.current_main_work_area_->setLineWidth(2);
1068 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() << ", Current main wa: " << currentMainWorkArea());
1072 LYXERR(Debug::DEBUG, "This is not a tabbed wa");
1073 on_currentWorkAreaChanged(wa);
1074 BufferView & bv = wa->bufferView();
1075 bv.cursor().fixIfBroken();
1077 wa->setUpdatesEnabled(true);
1078 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() << ", Current main wa: " << currentMainWorkArea());
1082 void GuiView::removeWorkArea(GuiWorkArea * wa)
1084 LASSERT(wa, return);
1085 if (wa == d.current_work_area_) {
1087 disconnectBufferView();
1088 d.current_work_area_ = 0;
1089 d.current_main_work_area_ = 0;
1092 bool found_twa = false;
1093 for (int i = 0; i != d.splitter_->count(); ++i) {
1094 TabWorkArea * twa = d.tabWorkArea(i);
1095 if (twa->removeWorkArea(wa)) {
1096 // Found in this tab group, and deleted the GuiWorkArea.
1098 if (twa->count() != 0) {
1099 if (d.current_work_area_ == 0)
1100 // This means that we are closing the current GuiWorkArea, so
1101 // switch to the next GuiWorkArea in the found TabWorkArea.
1102 setCurrentWorkArea(twa->currentWorkArea());
1104 // No more WorkAreas in this tab group, so delete it.
1111 // It is not a tabbed work area (i.e., the search work area), so it
1112 // should be deleted by other means.
1113 LASSERT(found_twa, /* */);
1115 if (d.current_work_area_ == 0) {
1116 if (d.splitter_->count() != 0) {
1117 TabWorkArea * twa = d.currentTabWorkArea();
1118 setCurrentWorkArea(twa->currentWorkArea());
1120 // No more work areas, switch to the background widget.
1121 setCurrentWorkArea(0);
1127 LayoutBox * GuiView::getLayoutDialog() const
1133 void GuiView::updateLayoutList()
1136 d.layout_->updateContents(false);
1140 void GuiView::updateToolbars()
1142 ToolbarMap::iterator end = d.toolbars_.end();
1143 if (d.current_work_area_) {
1145 d.current_work_area_->bufferView().cursor().inMathed();
1147 lyx::getStatus(FuncRequest(LFUN_LAYOUT_TABULAR)).enabled();
1149 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).enabled() &&
1150 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).onoff(true);
1151 bool const mathmacrotemplate =
1152 lyx::getStatus(FuncRequest(LFUN_IN_MATHMACROTEMPLATE)).enabled();
1154 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1155 it->second->update(math, table, review, mathmacrotemplate);
1157 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1158 it->second->update(false, false, false, false);
1162 void GuiView::setBuffer(Buffer * newBuffer)
1164 LYXERR(Debug::DEBUG, "Setting buffer: " << newBuffer << endl);
1165 LASSERT(newBuffer, return);
1168 GuiWorkArea * wa = workArea(*newBuffer);
1170 newBuffer->masterBuffer()->updateLabels();
1171 wa = addWorkArea(*newBuffer);
1173 //Disconnect the old buffer...there's no new one.
1176 connectBuffer(*newBuffer);
1177 connectBufferView(wa->bufferView());
1178 setCurrentWorkArea(wa);
1184 void GuiView::connectBuffer(Buffer & buf)
1186 buf.setGuiDelegate(this);
1190 void GuiView::disconnectBuffer()
1192 if (d.current_work_area_)
1193 d.current_work_area_->bufferView().buffer().setGuiDelegate(0);
1197 void GuiView::connectBufferView(BufferView & bv)
1199 bv.setGuiDelegate(this);
1203 void GuiView::disconnectBufferView()
1205 if (d.current_work_area_)
1206 d.current_work_area_->bufferView().setGuiDelegate(0);
1210 void GuiView::errors(string const & error_type, bool from_master)
1212 ErrorList & el = from_master ?
1213 documentBufferView()->buffer().masterBuffer()->errorList(error_type)
1214 : documentBufferView()->buffer().errorList(error_type);
1215 string data = error_type;
1217 data = "from_master|" + error_type;
1219 showDialog("errorlist", data);
1223 void GuiView::updateTocItem(string const & type, DocIterator const & dit)
1225 d.toc_models_.updateItem(toqstr(type), dit);
1229 void GuiView::structureChanged()
1231 d.toc_models_.reset(documentBufferView());
1232 // Navigator needs more than a simple update in this case. It needs to be
1234 updateDialog("toc", "");
1238 void GuiView::updateDialog(string const & name, string const & data)
1240 if (!isDialogVisible(name))
1243 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
1244 if (it == d.dialogs_.end())
1247 Dialog * const dialog = it->second.get();
1248 if (dialog->isVisibleView())
1249 dialog->initialiseParams(data);
1253 BufferView * GuiView::documentBufferView()
1255 return currentMainWorkArea()
1256 ? ¤tMainWorkArea()->bufferView()
1261 BufferView const * GuiView::documentBufferView() const
1263 return currentMainWorkArea()
1264 ? ¤tMainWorkArea()->bufferView()
1269 BufferView * GuiView::currentBufferView()
1271 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1275 BufferView const * GuiView::currentBufferView() const
1277 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1281 #if (QT_VERSION >= 0x040400)
1282 static docstring saveAndDestroyBuffer(Buffer * buffer, FileName const & fname)
1285 FileName const tmp_ret = FileName::tempName("lyxauto");
1286 if (!tmp_ret.empty()) {
1287 if (buffer->writeFile(tmp_ret))
1288 failed = !tmp_ret.moveTo(fname);
1291 // failed to write/rename tmp_ret so try writing direct
1292 failed = buffer->writeFile(fname);
1296 ? _("Automatic save failed!")
1297 : _("Automatic save done.");
1302 void GuiView::autoSave()
1304 LYXERR(Debug::INFO, "Running autoSave()");
1306 Buffer * buffer = documentBufferView()
1307 ? &documentBufferView()->buffer() : 0;
1311 #if (QT_VERSION >= 0x040400)
1312 QFuture<docstring> f = QtConcurrent::run(saveAndDestroyBuffer, buffer->clone(),
1313 buffer->getAutosaveFilename());
1314 d.autosave_watcher_.setFuture(f);
1321 void GuiView::resetAutosaveTimers()
1324 d.autosave_timeout_.restart();
1328 bool GuiView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1331 Buffer * buf = currentBufferView()
1332 ? ¤tBufferView()->buffer() : 0;
1333 Buffer * doc_buffer = documentBufferView()
1334 ? &(documentBufferView()->buffer()) : 0;
1336 // Check whether we need a buffer
1337 if (!lyxaction.funcHasFlag(cmd.action, LyXAction::NoBuffer) && !buf) {
1338 // no, exit directly
1339 flag.message(from_utf8(N_("Command not allowed with"
1340 "out any document open")));
1341 flag.setEnabled(false);
1345 if (cmd.origin == FuncRequest::TOC) {
1346 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
1348 if (toc->getStatus(documentBufferView()->cursor(), cmd, fs))
1351 flag.setEnabled(false);
1355 switch(cmd.action) {
1356 case LFUN_BUFFER_IMPORT:
1359 case LFUN_MASTER_BUFFER_UPDATE:
1360 case LFUN_MASTER_BUFFER_VIEW:
1361 enable = doc_buffer && doc_buffer->parent() != 0
1362 && !d.preview_watcher_.isRunning();
1365 case LFUN_BUFFER_UPDATE:
1366 case LFUN_BUFFER_VIEW: {
1367 if (!doc_buffer || d.preview_watcher_.isRunning()) {
1371 string format = to_utf8(cmd.argument());
1372 if (cmd.argument().empty())
1373 format = doc_buffer->getDefaultOutputFormat();
1374 enable = doc_buffer->isExportableFormat(format);
1378 case LFUN_BUFFER_RELOAD:
1379 enable = doc_buffer && !doc_buffer->isUnnamed()
1380 && doc_buffer->fileName().exists()
1381 && (!doc_buffer->isClean()
1382 || doc_buffer->isExternallyModified(Buffer::timestamp_method));
1385 case LFUN_BUFFER_CHILD_OPEN:
1386 enable = doc_buffer;
1389 case LFUN_BUFFER_WRITE:
1390 enable = doc_buffer && (doc_buffer->isUnnamed() || !doc_buffer->isClean());
1393 //FIXME: This LFUN should be moved to GuiApplication.
1394 case LFUN_BUFFER_WRITE_ALL: {
1395 // We enable the command only if there are some modified buffers
1396 Buffer * first = theBufferList().first();
1401 // We cannot use a for loop as the buffer list is a cycle.
1403 if (!b->isClean()) {
1407 b = theBufferList().next(b);
1408 } while (b != first);
1412 case LFUN_BUFFER_WRITE_AS:
1413 enable = doc_buffer;
1416 case LFUN_BUFFER_CLOSE:
1417 enable = doc_buffer;
1420 case LFUN_BUFFER_CLOSE_ALL:
1421 enable = theBufferList().last() != theBufferList().first();
1424 case LFUN_SPLIT_VIEW:
1425 if (cmd.getArg(0) == "vertical")
1426 enable = doc_buffer && (d.splitter_->count() == 1 ||
1427 d.splitter_->orientation() == Qt::Vertical);
1429 enable = doc_buffer && (d.splitter_->count() == 1 ||
1430 d.splitter_->orientation() == Qt::Horizontal);
1433 case LFUN_CLOSE_TAB_GROUP:
1434 enable = d.currentTabWorkArea();
1437 case LFUN_TOOLBAR_TOGGLE:
1438 if (GuiToolbar * t = toolbar(cmd.getArg(0)))
1439 flag.setOnOff(t->isVisible());
1442 case LFUN_DROP_LAYOUTS_CHOICE:
1446 case LFUN_UI_TOGGLE:
1447 flag.setOnOff(isFullScreen());
1450 case LFUN_DIALOG_DISCONNECT_INSET:
1453 case LFUN_DIALOG_HIDE:
1454 // FIXME: should we check if the dialog is shown?
1457 case LFUN_DIALOG_TOGGLE:
1458 flag.setOnOff(isDialogVisible(cmd.getArg(0)));
1459 // fall through to set "enable"
1460 case LFUN_DIALOG_SHOW: {
1461 string const name = cmd.getArg(0);
1463 enable = name == "aboutlyx"
1464 || name == "file" //FIXME: should be removed.
1466 || name == "texinfo"
1467 || name == "progress"
1468 || name == "compare";
1469 else if (name == "print")
1470 enable = doc_buffer->isExportable("dvi")
1471 && lyxrc.print_command != "none";
1472 else if (name == "character" || name == "symbols") {
1473 if (!buf || buf->isReadonly()
1474 || !currentBufferView()->cursor().inTexted())
1477 // FIXME we should consider passthru
1479 Inset const & in = currentBufferView()->cursor().inset();
1480 enable = !in.getLayout().isPassThru();
1483 else if (name == "latexlog")
1484 enable = FileName(doc_buffer->logName()).isReadableFile();
1485 else if (name == "spellchecker")
1486 enable = theSpellChecker() && !doc_buffer->isReadonly();
1487 else if (name == "vclog")
1488 enable = doc_buffer->lyxvc().inUse();
1492 case LFUN_DIALOG_UPDATE: {
1493 string const name = cmd.getArg(0);
1495 enable = name == "prefs";
1499 case LFUN_COMMAND_EXECUTE:
1501 case LFUN_MENU_OPEN:
1502 // Nothing to check.
1505 case LFUN_COMPLETION_INLINE:
1506 if (!d.current_work_area_
1507 || !d.current_work_area_->completer().inlinePossible(
1508 currentBufferView()->cursor()))
1512 case LFUN_COMPLETION_POPUP:
1513 if (!d.current_work_area_
1514 || !d.current_work_area_->completer().popupPossible(
1515 currentBufferView()->cursor()))
1519 case LFUN_COMPLETION_COMPLETE:
1520 if (!d.current_work_area_
1521 || !d.current_work_area_->completer().inlinePossible(
1522 currentBufferView()->cursor()))
1526 case LFUN_COMPLETION_ACCEPT:
1527 if (!d.current_work_area_
1528 || (!d.current_work_area_->completer().popupVisible()
1529 && !d.current_work_area_->completer().inlineVisible()
1530 && !d.current_work_area_->completer().completionAvailable()))
1534 case LFUN_COMPLETION_CANCEL:
1535 if (!d.current_work_area_
1536 || (!d.current_work_area_->completer().popupVisible()
1537 && !d.current_work_area_->completer().inlineVisible()))
1541 case LFUN_BUFFER_ZOOM_OUT:
1542 enable = doc_buffer && lyxrc.zoom > 10;
1545 case LFUN_BUFFER_ZOOM_IN:
1546 enable = doc_buffer;
1549 case LFUN_BUFFER_NEXT:
1550 case LFUN_BUFFER_PREVIOUS:
1551 // FIXME: should we check is there is an previous or next buffer?
1553 case LFUN_BUFFER_SWITCH:
1554 // toggle on the current buffer, but do not toggle off
1555 // the other ones (is that a good idea?)
1557 && to_utf8(cmd.argument()) == doc_buffer->absFileName())
1558 flag.setOnOff(true);
1561 case LFUN_VC_REGISTER:
1562 enable = doc_buffer && !doc_buffer->lyxvc().inUse();
1564 case LFUN_VC_CHECK_IN:
1565 enable = doc_buffer && doc_buffer->lyxvc().checkInEnabled();
1567 case LFUN_VC_CHECK_OUT:
1568 enable = doc_buffer && doc_buffer->lyxvc().checkOutEnabled();
1570 case LFUN_VC_LOCKING_TOGGLE:
1571 enable = doc_buffer && !doc_buffer->isReadonly()
1572 && doc_buffer->lyxvc().lockingToggleEnabled();
1573 flag.setOnOff(enable && !doc_buffer->lyxvc().locker().empty());
1575 case LFUN_VC_REVERT:
1576 enable = doc_buffer && doc_buffer->lyxvc().inUse();
1578 case LFUN_VC_UNDO_LAST:
1579 enable = doc_buffer && doc_buffer->lyxvc().undoLastEnabled();
1581 case LFUN_VC_REPO_UPDATE:
1582 enable = doc_buffer && doc_buffer->lyxvc().inUse();
1584 case LFUN_VC_COMMAND: {
1585 if (cmd.argument().empty())
1587 if (!doc_buffer && contains(cmd.getArg(0), 'D'))
1592 case LFUN_SERVER_GOTO_FILE_ROW:
1600 flag.setEnabled(false);
1606 static FileName selectTemplateFile()
1608 FileDialog dlg(qt_("Select template file"));
1609 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1610 dlg.setButton1(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
1612 FileDialog::Result result = dlg.open(toqstr(lyxrc.template_path),
1613 QStringList(qt_("LyX Documents (*.lyx)")));
1615 if (result.first == FileDialog::Later)
1617 if (result.second.isEmpty())
1619 return FileName(fromqstr(result.second));
1623 Buffer * GuiView::loadDocument(FileName const & filename, bool tolastfiles)
1627 Buffer * newBuffer = checkAndLoadLyXFile(filename);
1630 message(_("Document not loaded."));
1635 setBuffer(newBuffer);
1637 // scroll to the position when the file was last closed
1638 if (lyxrc.use_lastfilepos) {
1639 LastFilePosSection::FilePos filepos =
1640 theSession().lastFilePos().load(filename);
1641 documentBufferView()->moveToPosition(filepos.pit, filepos.pos, 0, 0);
1645 theSession().lastFiles().add(filename);
1652 void GuiView::openDocument(string const & fname)
1654 string initpath = lyxrc.document_path;
1656 if (documentBufferView()) {
1657 string const trypath = documentBufferView()->buffer().filePath();
1658 // If directory is writeable, use this as default.
1659 if (FileName(trypath).isDirWritable())
1665 if (fname.empty()) {
1666 FileDialog dlg(qt_("Select document to open"), LFUN_FILE_OPEN);
1667 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1668 dlg.setButton2(qt_("Examples|#E#e"),
1669 toqstr(addPath(package().system_support().absFilename(), "examples")));
1671 QStringList filter(qt_("LyX Documents (*.lyx)"));
1672 filter << qt_("LyX-1.3.x Documents (*.lyx13)")
1673 << qt_("LyX-1.4.x Documents (*.lyx14)")
1674 << qt_("LyX-1.5.x Documents (*.lyx15)")
1675 << qt_("LyX-1.6.x Documents (*.lyx16)");
1676 FileDialog::Result result =
1677 dlg.open(toqstr(initpath), filter);
1679 if (result.first == FileDialog::Later)
1682 filename = fromqstr(result.second);
1684 // check selected filename
1685 if (filename.empty()) {
1686 message(_("Canceled."));
1692 // get absolute path of file and add ".lyx" to the filename if
1694 FileName const fullname =
1695 fileSearch(string(), filename, "lyx", support::may_not_exist);
1696 if (!fullname.empty())
1697 filename = fullname.absFilename();
1699 if (!fullname.onlyPath().isDirectory()) {
1700 Alert::warning(_("Invalid filename"),
1701 bformat(_("The directory in the given path\n%1$s\ndoes not exist."),
1702 from_utf8(fullname.absFilename())));
1705 // if the file doesn't exist, let the user create one
1706 if (!fullname.exists()) {
1707 // the user specifically chose this name. Believe him.
1708 Buffer * const b = newFile(filename, string(), true);
1714 docstring const disp_fn = makeDisplayPath(filename);
1715 message(bformat(_("Opening document %1$s..."), disp_fn));
1718 Buffer * buf = loadDocument(fullname);
1720 buf->updateLabels();
1722 buf->errors("Parse");
1723 str2 = bformat(_("Document %1$s opened."), disp_fn);
1724 if (buf->lyxvc().inUse())
1725 str2 += " " + from_utf8(buf->lyxvc().versionString()) +
1726 " " + _("Version control detected.");
1728 str2 = bformat(_("Could not open document %1$s"), disp_fn);
1733 // FIXME: clean that
1734 static bool import(GuiView * lv, FileName const & filename,
1735 string const & format, ErrorList & errorList)
1737 FileName const lyxfile(support::changeExtension(filename.absFilename(), ".lyx"));
1739 string loader_format;
1740 vector<string> loaders = theConverters().loaders();
1741 if (find(loaders.begin(), loaders.end(), format) == loaders.end()) {
1742 for (vector<string>::const_iterator it = loaders.begin();
1743 it != loaders.end(); ++it) {
1744 if (!theConverters().isReachable(format, *it))
1747 string const tofile =
1748 support::changeExtension(filename.absFilename(),
1749 formats.extension(*it));
1750 if (!theConverters().convert(0, filename, FileName(tofile),
1751 filename, format, *it, errorList))
1753 loader_format = *it;
1756 if (loader_format.empty()) {
1757 frontend::Alert::error(_("Couldn't import file"),
1758 bformat(_("No information for importing the format %1$s."),
1759 formats.prettyName(format)));
1763 loader_format = format;
1765 if (loader_format == "lyx") {
1766 Buffer * buf = lv->loadDocument(lyxfile);
1769 buf->updateLabels();
1771 buf->errors("Parse");
1773 Buffer * const b = newFile(lyxfile.absFilename(), string(), true);
1777 bool as_paragraphs = loader_format == "textparagraph";
1778 string filename2 = (loader_format == format) ? filename.absFilename()
1779 : support::changeExtension(filename.absFilename(),
1780 formats.extension(loader_format));
1781 lv->currentBufferView()->insertPlaintextFile(FileName(filename2),
1783 guiApp->setCurrentView(lv);
1784 lyx::dispatch(FuncRequest(LFUN_MARK_OFF));
1791 void GuiView::importDocument(string const & argument)
1794 string filename = split(argument, format, ' ');
1796 LYXERR(Debug::INFO, format << " file: " << filename);
1798 // need user interaction
1799 if (filename.empty()) {
1800 string initpath = lyxrc.document_path;
1801 if (documentBufferView()) {
1802 string const trypath = documentBufferView()->buffer().filePath();
1803 // If directory is writeable, use this as default.
1804 if (FileName(trypath).isDirWritable())
1808 docstring const text = bformat(_("Select %1$s file to import"),
1809 formats.prettyName(format));
1811 FileDialog dlg(toqstr(text), LFUN_BUFFER_IMPORT);
1812 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1813 dlg.setButton2(qt_("Examples|#E#e"),
1814 toqstr(addPath(package().system_support().absFilename(), "examples")));
1816 docstring filter = formats.prettyName(format);
1819 filter += from_utf8(formats.extension(format));
1822 FileDialog::Result result =
1823 dlg.open(toqstr(initpath), fileFilters(toqstr(filter)));
1825 if (result.first == FileDialog::Later)
1828 filename = fromqstr(result.second);
1830 // check selected filename
1831 if (filename.empty())
1832 message(_("Canceled."));
1835 if (filename.empty())
1838 // get absolute path of file
1839 FileName const fullname(support::makeAbsPath(filename));
1841 FileName const lyxfile(support::changeExtension(fullname.absFilename(), ".lyx"));
1843 // Check if the document already is open
1844 Buffer * buf = theBufferList().getBuffer(lyxfile);
1847 if (!closeBuffer()) {
1848 message(_("Canceled."));
1853 docstring const displaypath = makeDisplayPath(lyxfile.absFilename(), 30);
1855 // if the file exists already, and we didn't do
1856 // -i lyx thefile.lyx, warn
1857 if (lyxfile.exists() && fullname != lyxfile) {
1859 docstring text = bformat(_("The document %1$s already exists.\n\n"
1860 "Do you want to overwrite that document?"), displaypath);
1861 int const ret = Alert::prompt(_("Overwrite document?"),
1862 text, 0, 1, _("&Overwrite"), _("&Cancel"));
1865 message(_("Canceled."));
1870 message(bformat(_("Importing %1$s..."), displaypath));
1871 ErrorList errorList;
1872 if (import(this, fullname, format, errorList))
1873 message(_("imported."));
1875 message(_("file not imported!"));
1877 // FIXME (Abdel 12/08/06): Is there a need to display the error list here?
1881 void GuiView::newDocument(string const & filename, bool from_template)
1883 FileName initpath(lyxrc.document_path);
1884 if (documentBufferView()) {
1885 FileName const trypath(documentBufferView()->buffer().filePath());
1886 // If directory is writeable, use this as default.
1887 if (trypath.isDirWritable())
1891 string templatefile;
1892 if (from_template) {
1893 templatefile = selectTemplateFile().absFilename();
1894 if (templatefile.empty())
1899 if (filename.empty())
1900 b = newUnnamedFile(initpath, to_utf8(_("newfile")), templatefile);
1902 b = newFile(filename, templatefile, true);
1907 // If no new document could be created, it is unsure
1908 // whether there is a valid BufferView.
1909 if (currentBufferView())
1910 // Ensure the cursor is correctly positioned on screen.
1911 currentBufferView()->showCursor();
1915 void GuiView::insertLyXFile(docstring const & fname)
1917 BufferView * bv = documentBufferView();
1922 FileName filename(to_utf8(fname));
1924 if (!filename.empty()) {
1925 bv->insertLyXFile(filename);
1929 // Launch a file browser
1931 string initpath = lyxrc.document_path;
1932 string const trypath = bv->buffer().filePath();
1933 // If directory is writeable, use this as default.
1934 if (FileName(trypath).isDirWritable())
1938 FileDialog dlg(qt_("Select LyX document to insert"), LFUN_FILE_INSERT);
1939 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1940 dlg.setButton2(qt_("Examples|#E#e"),
1941 toqstr(addPath(package().system_support().absFilename(),
1944 FileDialog::Result result = dlg.open(toqstr(initpath),
1945 QStringList(qt_("LyX Documents (*.lyx)")));
1947 if (result.first == FileDialog::Later)
1951 filename.set(fromqstr(result.second));
1953 // check selected filename
1954 if (filename.empty()) {
1955 // emit message signal.
1956 message(_("Canceled."));
1960 bv->insertLyXFile(filename);
1964 void GuiView::insertPlaintextFile(docstring const & fname,
1967 BufferView * bv = documentBufferView();
1971 if (!fname.empty() && !FileName::isAbsolute(to_utf8(fname))) {
1972 message(_("Absolute filename expected."));
1977 FileName filename(to_utf8(fname));
1979 if (!filename.empty()) {
1980 bv->insertPlaintextFile(filename, asParagraph);
1984 FileDialog dlg(qt_("Select file to insert"), (asParagraph ?
1985 LFUN_FILE_INSERT_PLAINTEXT_PARA : LFUN_FILE_INSERT_PLAINTEXT));
1987 FileDialog::Result result = dlg.open(toqstr(bv->buffer().filePath()),
1988 QStringList(qt_("All Files (*)")));
1990 if (result.first == FileDialog::Later)
1994 filename.set(fromqstr(result.second));
1996 // check selected filename
1997 if (filename.empty()) {
1998 // emit message signal.
1999 message(_("Canceled."));
2003 bv->insertPlaintextFile(filename, asParagraph);
2007 bool GuiView::renameBuffer(Buffer & b, docstring const & newname)
2009 FileName fname = b.fileName();
2010 FileName const oldname = fname;
2012 if (!newname.empty()) {
2014 fname = support::makeAbsPath(to_utf8(newname), oldname.onlyPath().absFilename());
2016 // Switch to this Buffer.
2019 // No argument? Ask user through dialog.
2021 FileDialog dlg(qt_("Choose a filename to save document as"),
2022 LFUN_BUFFER_WRITE_AS);
2023 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2024 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
2026 if (!isLyXFilename(fname.absFilename()))
2027 fname.changeExtension(".lyx");
2029 FileDialog::Result result =
2030 dlg.save(toqstr(fname.onlyPath().absFilename()),
2031 QStringList(qt_("LyX Documents (*.lyx)")),
2032 toqstr(fname.onlyFileName()));
2034 if (result.first == FileDialog::Later)
2037 fname.set(fromqstr(result.second));
2042 if (!isLyXFilename(fname.absFilename()))
2043 fname.changeExtension(".lyx");
2046 if (FileName(fname).exists()) {
2047 docstring const file = makeDisplayPath(fname.absFilename(), 30);
2048 docstring text = bformat(_("The document %1$s already "
2049 "exists.\n\nDo you want to "
2050 "overwrite that document?"),
2052 int const ret = Alert::prompt(_("Overwrite document?"),
2053 text, 0, 2, _("&Overwrite"), _("&Rename"), _("&Cancel"));
2056 case 1: return renameBuffer(b, docstring());
2057 case 2: return false;
2061 FileName oldauto = b.getAutosaveFilename();
2063 // Ok, change the name of the buffer
2064 b.setFileName(fname.absFilename());
2066 bool unnamed = b.isUnnamed();
2067 b.setUnnamed(false);
2068 b.saveCheckSum(fname);
2070 // bring the autosave file with us, just in case.
2071 b.moveAutosaveFile(oldauto);
2073 if (!saveBuffer(b)) {
2074 oldauto = b.getAutosaveFilename();
2075 b.setFileName(oldname.absFilename());
2076 b.setUnnamed(unnamed);
2077 b.saveCheckSum(oldname);
2078 b.moveAutosaveFile(oldauto);
2086 bool GuiView::saveBuffer(Buffer & b)
2088 if (workArea(b) && workArea(b)->inDialogMode())
2092 return renameBuffer(b, docstring());
2095 theSession().lastFiles().add(b.fileName());
2099 // Switch to this Buffer.
2102 // FIXME: we don't tell the user *WHY* the save failed !!
2103 docstring const file = makeDisplayPath(b.absFileName(), 30);
2104 docstring text = bformat(_("The document %1$s could not be saved.\n\n"
2105 "Do you want to rename the document and "
2106 "try again?"), file);
2107 int const ret = Alert::prompt(_("Rename and save?"),
2108 text, 0, 2, _("&Rename"), _("&Retry"), _("&Cancel"));
2111 if (!renameBuffer(b, docstring()))
2120 return saveBuffer(b);
2124 bool GuiView::hideWorkArea(GuiWorkArea * wa)
2126 return closeWorkArea(wa, false);
2130 bool GuiView::closeWorkArea(GuiWorkArea * wa)
2132 Buffer & buf = wa->bufferView().buffer();
2133 return closeWorkArea(wa, !buf.parent());
2137 bool GuiView::closeBuffer()
2139 GuiWorkArea * wa = currentMainWorkArea();
2140 setCurrentWorkArea(wa);
2141 Buffer & buf = wa->bufferView().buffer();
2142 return wa && closeWorkArea(wa, !buf.parent());
2146 void GuiView::writeSession() const {
2147 GuiWorkArea const * active_wa = currentMainWorkArea();
2148 for (int i = 0; i < d.splitter_->count(); ++i) {
2149 TabWorkArea * twa = d.tabWorkArea(i);
2150 for (int j = 0; j < twa->count(); ++j) {
2151 GuiWorkArea * wa = static_cast<GuiWorkArea *>(twa->widget(j));
2152 Buffer & buf = wa->bufferView().buffer();
2153 theSession().lastOpened().add(buf.fileName(), wa == active_wa);
2159 bool GuiView::closeBufferAll()
2161 // Close the workareas in all other views
2162 QList<int> const ids = guiApp->viewIds();
2163 for (int i = 0; i != ids.size(); ++i) {
2164 if (id_ != ids[i] && !guiApp->view(ids[i]).closeWorkAreaAll())
2168 // Close our own workareas
2169 if (!closeWorkAreaAll())
2172 // Now close the hidden buffers. We prevent hidden buffers from being
2173 // dirty, so we can just close them.
2174 theBufferList().closeAll();
2179 bool GuiView::closeWorkAreaAll()
2181 setCurrentWorkArea(currentMainWorkArea());
2183 // We might be in a situation that there is still a tabWorkArea, but
2184 // there are no tabs anymore. This can happen when we get here after a
2185 // TabWorkArea::lastWorkAreaRemoved() signal. Therefore we count how
2186 // many TabWorkArea's have no documents anymore.
2189 // We have to call count() each time, because it can happen that
2190 // more than one splitter will disappear in one iteration (bug 5998).
2191 for (; d.splitter_->count() > empty_twa; ) {
2192 TabWorkArea * twa = d.tabWorkArea(empty_twa);
2194 if (twa->count() == 0)
2197 setCurrentWorkArea(twa->currentWorkArea());
2198 if (!closeTabWorkArea(twa))
2206 bool GuiView::closeWorkArea(GuiWorkArea * wa, bool close_buffer)
2211 Buffer & buf = wa->bufferView().buffer();
2214 return closeBuffer(buf);
2216 if (!inMultiTabs(wa))
2217 if (!saveBufferIfNeeded(buf, true))
2225 bool GuiView::closeBuffer(Buffer & buf)
2227 // If we are in a close_event all children will be closed in some time,
2228 // so no need to do it here. This will ensure that the children end up
2229 // in the session file in the correct order. If we close the master
2230 // buffer, we can close or release the child buffers here too.
2232 vector<Buffer *> clist = buf.getChildren(false);
2233 for (vector<Buffer *>::const_iterator it = clist.begin();
2234 it != clist.end(); ++it) {
2235 // If a child is dirty, do not close
2236 // without user intervention
2237 //FIXME: should we look in other tabworkareas?
2238 Buffer * child_buf = *it;
2239 GuiWorkArea * child_wa = workArea(*child_buf);
2241 if (!closeWorkArea(child_wa, true))
2244 theBufferList().releaseChild(&buf, child_buf);
2247 // goto bookmark to update bookmark pit.
2248 //FIXME: we should update only the bookmarks related to this buffer!
2249 LYXERR(Debug::DEBUG, "GuiView::closeBuffer()");
2250 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
2251 theLyXFunc().gotoBookmark(i+1, false, false);
2253 if (saveBufferIfNeeded(buf, false)) {
2254 theBufferList().release(&buf);
2261 bool GuiView::closeTabWorkArea(TabWorkArea * twa)
2263 while (twa == d.currentTabWorkArea()) {
2264 twa->setCurrentIndex(twa->count()-1);
2266 GuiWorkArea * wa = twa->currentWorkArea();
2267 Buffer & b = wa->bufferView().buffer();
2269 // We only want to close the buffer if the same buffer is not visible
2270 // in another view, and if this is not a child and if we are closing
2271 // a view (not a tabgroup).
2272 bool const close_buffer =
2273 !inMultiViews(wa) && !b.parent() && closing_;
2275 if (!closeWorkArea(wa, close_buffer))
2282 bool GuiView::saveBufferIfNeeded(Buffer & buf, bool hiding)
2284 if (buf.isClean() || buf.paragraphs().empty())
2287 // Switch to this Buffer.
2292 if (buf.isUnnamed())
2293 file = from_utf8(buf.fileName().onlyFileName());
2295 file = buf.fileName().displayName(30);
2297 // Bring this window to top before asking questions.
2302 if (hiding && buf.isUnnamed()) {
2303 docstring const text = bformat(_("The document %1$s has not been "
2304 "saved yet.\n\nDo you want to save "
2305 "the document?"), file);
2306 ret = Alert::prompt(_("Save new document?"),
2307 text, 0, 1, _("&Save"), _("&Cancel"));
2311 docstring const text = bformat(_("The document %1$s has unsaved changes."
2312 "\n\nDo you want to save the document or discard the changes?"), file);
2313 ret = Alert::prompt(_("Save changed document?"),
2314 text, 0, 2, _("&Save"), _("&Discard"), _("&Cancel"));
2319 if (!saveBuffer(buf))
2323 // if we crash after this we could
2324 // have no autosave file but I guess
2325 // this is really improbable (Jug)
2326 buf.removeAutosaveFile();
2328 // revert all changes
2339 bool GuiView::inMultiTabs(GuiWorkArea * wa)
2341 Buffer & buf = wa->bufferView().buffer();
2343 for (int i = 0; i != d.splitter_->count(); ++i) {
2344 GuiWorkArea * wa_ = d.tabWorkArea(i)->workArea(buf);
2345 if (wa_ && wa_ != wa)
2348 return inMultiViews(wa);
2352 bool GuiView::inMultiViews(GuiWorkArea * wa)
2354 QList<int> const ids = guiApp->viewIds();
2355 Buffer & buf = wa->bufferView().buffer();
2358 for (int i = 0; i != ids.size() && found_twa <= 1; ++i) {
2362 if (guiApp->view(ids[i]).workArea(buf))
2369 void GuiView::gotoNextOrPreviousBuffer(NextOrPrevious np)
2371 Buffer * const curbuf = documentBufferView()
2372 ? &documentBufferView()->buffer() : 0;
2373 Buffer * nextbuf = curbuf;
2375 if (np == NEXTBUFFER)
2376 nextbuf = theBufferList().next(nextbuf);
2378 nextbuf = theBufferList().previous(nextbuf);
2379 if (nextbuf == curbuf)
2385 if (workArea(*nextbuf))
2392 /// make sure the document is saved
2393 static bool ensureBufferClean(Buffer * buffer)
2395 LASSERT(buffer, return false);
2396 if (buffer->isClean() && !buffer->isUnnamed())
2399 docstring const file = buffer->fileName().displayName(30);
2402 if (!buffer->isUnnamed()) {
2403 text = bformat(_("The document %1$s has unsaved "
2404 "changes.\n\nDo you want to save "
2405 "the document?"), file);
2406 title = _("Save changed document?");
2409 text = bformat(_("The document %1$s has not been "
2410 "saved yet.\n\nDo you want to save "
2411 "the document?"), file);
2412 title = _("Save new document?");
2414 int const ret = Alert::prompt(title, text, 0, 1, _("&Save"), _("&Cancel"));
2417 dispatch(FuncRequest(LFUN_BUFFER_WRITE));
2419 return buffer->isClean() && !buffer->isUnnamed();
2423 void GuiView::reloadBuffer()
2425 Buffer * buf = &documentBufferView()->buffer();
2430 void GuiView::checkExternallyModifiedBuffers()
2432 BufferList::iterator bit = theBufferList().begin();
2433 BufferList::iterator const bend = theBufferList().end();
2434 for (; bit != bend; ++bit) {
2435 if ((*bit)->fileName().exists()
2436 && (*bit)->isExternallyModified(Buffer::checksum_method)) {
2437 docstring text = bformat(_("Document \n%1$s\n has been externally modified."
2438 " Reload now? Any local changes will be lost."),
2439 from_utf8((*bit)->absFileName()));
2440 int const ret = Alert::prompt(_("Reload externally changed document?"),
2441 text, 0, 1, _("&Reload"), _("&Cancel"));
2449 void GuiView::dispatchVC(FuncRequest const & cmd)
2451 // message for statusbar
2453 Buffer * buffer = documentBufferView()
2454 ? &(documentBufferView()->buffer()) : 0;
2456 switch (cmd.action) {
2457 case LFUN_VC_REGISTER:
2458 if (!buffer || !ensureBufferClean(buffer))
2460 if (!buffer->lyxvc().inUse()) {
2461 if (buffer->lyxvc().registrer())
2466 case LFUN_VC_CHECK_IN:
2467 if (!buffer || !ensureBufferClean(buffer))
2469 if (buffer->lyxvc().inUse() && !buffer->isReadonly()) {
2470 msg = buffer->lyxvc().checkIn();
2476 case LFUN_VC_CHECK_OUT:
2477 if (!buffer || !ensureBufferClean(buffer))
2479 if (buffer->lyxvc().inUse()) {
2480 msg = buffer->lyxvc().checkOut();
2485 case LFUN_VC_LOCKING_TOGGLE:
2486 LASSERT(buffer, return);
2487 if (!ensureBufferClean(buffer) || buffer->isReadonly())
2489 if (buffer->lyxvc().inUse()) {
2490 string res = buffer->lyxvc().lockingToggle();
2492 frontend::Alert::error(_("Revision control error."),
2493 _("Error when setting the locking property."));
2501 case LFUN_VC_REVERT:
2502 LASSERT(buffer, return);
2503 buffer->lyxvc().revert();
2507 case LFUN_VC_UNDO_LAST:
2508 LASSERT(buffer, return);
2509 buffer->lyxvc().undoLast();
2513 case LFUN_VC_REPO_UPDATE:
2514 LASSERT(buffer, return);
2515 if (ensureBufferClean(buffer)) {
2516 msg = buffer->lyxvc().repoUpdate();
2517 checkExternallyModifiedBuffers();
2521 case LFUN_VC_COMMAND: {
2522 string flag = cmd.getArg(0);
2523 if (buffer && contains(flag, 'R') && !ensureBufferClean(buffer))
2526 if (contains(flag, 'M')) {
2527 if (!Alert::askForText(message, _("LyX VC: Log Message")))
2530 string path = cmd.getArg(1);
2531 if (contains(path, "$$p") && buffer)
2532 path = subst(path, "$$p", buffer->filePath());
2533 LYXERR(Debug::LYXVC, "Directory: " << path);
2535 if (!pp.isReadableDirectory()) {
2536 lyxerr << _("Directory is not accessible.") << endl;
2539 support::PathChanger p(pp);
2541 string command = cmd.getArg(2);
2542 if (command.empty())
2545 command = subst(command, "$$i", buffer->absFileName());
2546 command = subst(command, "$$p", buffer->filePath());
2548 command = subst(command, "$$m", to_utf8(message));
2549 LYXERR(Debug::LYXVC, "Command: " << command);
2551 one.startscript(Systemcall::Wait, command);
2555 if (contains(flag, 'I'))
2556 buffer->markDirty();
2557 if (contains(flag, 'R'))
2567 message(from_utf8(msg));
2571 void GuiView::openChildDocument(string const & fname)
2573 LASSERT(documentBufferView(), return);
2574 Buffer & buffer = documentBufferView()->buffer();
2575 FileName const filename = support::makeAbsPath(fname, buffer.filePath());
2576 documentBufferView()->saveBookmark(false);
2578 bool parsed = false;
2579 if (theBufferList().exists(filename)) {
2580 child = theBufferList().getBuffer(filename);
2582 message(bformat(_("Opening child document %1$s..."),
2583 makeDisplayPath(filename.absFilename())));
2584 child = loadDocument(filename, false);
2590 // Set the parent name of the child document.
2591 // This makes insertion of citations and references in the child work,
2592 // when the target is in the parent or another child document.
2593 child->setParent(&buffer);
2594 child->masterBuffer()->updateLabels();
2597 child->errors("Parse");
2601 bool GuiView::goToFileRow(string const & argument)
2605 size_t i = argument.find_last_of(' ');
2606 if (i != string::npos) {
2607 file_name = os::internal_path(trim(argument.substr(0, i)));
2608 istringstream is(argument.substr(i + 1));
2613 if (i == string::npos) {
2614 LYXERR0("Wrong argument: " << argument);
2618 string const abstmp = package().temp_dir().absFilename();
2619 string const realtmp = package().temp_dir().realPath();
2620 // We have to use os::path_prefix_is() here, instead of
2621 // simply prefixIs(), because the file name comes from
2622 // an external application and may need case adjustment.
2623 if (os::path_prefix_is(file_name, abstmp, os::CASE_ADJUSTED)
2624 || os::path_prefix_is(file_name, realtmp, os::CASE_ADJUSTED)) {
2625 // Needed by inverse dvi search. If it is a file
2626 // in tmpdir, call the apropriated function.
2627 // If tmpdir is a symlink, we may have the real
2628 // path passed back, so we correct for that.
2629 if (!prefixIs(file_name, abstmp))
2630 file_name = subst(file_name, realtmp, abstmp);
2631 buf = theBufferList().getBufferFromTmp(file_name);
2633 // Must replace extension of the file to be .lyx
2634 // and get full path
2635 FileName const s = fileSearch(string(),
2636 support::changeExtension(file_name, ".lyx"), "lyx");
2637 // Either change buffer or load the file
2638 if (theBufferList().exists(s))
2639 buf = theBufferList().getBuffer(s);
2640 else if (s.exists()) {
2641 buf = loadDocument(s);
2642 buf->updateLabels();
2643 buf->errors("Parse");
2646 _("File does not exist: %1$s"),
2647 makeDisplayPath(file_name)));
2652 documentBufferView()->setCursorFromRow(row);
2657 #if (QT_VERSION >= 0x040400)
2658 static docstring exportAndDestroy(Buffer * buffer, string const & format)
2660 bool const update_unincluded =
2661 buffer->params().maintain_unincluded_children
2662 && !buffer->params().getIncludedChildren().empty();
2663 bool const success = buffer->doExport(format, true, update_unincluded);
2666 ? bformat(_("Successful export to format: %1$s"), from_utf8(format))
2667 : bformat(_("Error exporting to format: %1$s"), from_utf8(format));
2671 static docstring previewAndDestroy(Buffer * buffer, string const & format)
2673 bool const update_unincluded =
2674 buffer->params().maintain_unincluded_children
2675 && !buffer->params().getIncludedChildren().empty();
2676 bool const success = buffer->preview(format, update_unincluded);
2679 ? bformat(_("Successful preview of format: %1$s"), from_utf8(format))
2680 : bformat(_("Error previewing format: %1$s"), from_utf8(format));
2685 bool GuiView::dispatch(FuncRequest const & cmd)
2687 BufferView * bv = currentBufferView();
2688 // By default we won't need any update.
2690 bv->cursor().updateFlags(Update::None);
2692 Buffer * doc_buffer = documentBufferView()
2693 ? &(documentBufferView()->buffer()) : 0;
2695 bool dispatched = true;
2697 if (cmd.origin == FuncRequest::TOC) {
2698 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
2699 toc->doDispatch(bv->cursor(), cmd);
2703 string const argument = to_utf8(cmd.argument());
2705 switch(cmd.action) {
2706 case LFUN_BUFFER_CHILD_OPEN:
2707 openChildDocument(to_utf8(cmd.argument()));
2710 case LFUN_BUFFER_IMPORT:
2711 importDocument(to_utf8(cmd.argument()));
2714 case LFUN_BUFFER_EXPORT: {
2717 if (cmd.argument() == "custom") {
2718 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "sendto"));
2721 if (doc_buffer->doExport(argument, false)) {
2722 message(bformat(_("Error exporting to format: %1$s."),
2728 case LFUN_BUFFER_UPDATE: {
2731 string format = argument;
2732 if (argument.empty())
2733 format = doc_buffer->getDefaultOutputFormat();
2734 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
2735 d.progress_->clearMessages();
2736 message(_("Exporting ..."));
2737 QFuture<docstring> f = QtConcurrent::run(exportAndDestroy,
2738 doc_buffer->clone(), format);
2739 d.setPreviewFuture(f);
2741 bool const update_unincluded =
2742 doc_buffer->params().maintain_unincluded_children
2743 && !doc_buffer->params().getIncludedChildren().empty();
2744 doc_buffer->doExport(format, true, update_unincluded);
2748 case LFUN_BUFFER_VIEW: {
2751 string format = argument;
2752 if (argument.empty())
2753 format = doc_buffer->getDefaultOutputFormat();
2754 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
2755 d.progress_->clearMessages();
2756 message(_("Previewing ..."));
2757 QFuture<docstring> f = QtConcurrent::run(previewAndDestroy,
2758 doc_buffer->clone(), format);
2759 d.setPreviewFuture(f);
2761 bool const update_unincluded =
2762 doc_buffer->params().maintain_unincluded_children
2763 && !doc_buffer->params().getIncludedChildren().empty();
2764 doc_buffer->preview(format, update_unincluded);
2768 case LFUN_MASTER_BUFFER_UPDATE: {
2771 string format = argument;
2772 Buffer const * master = doc_buffer->masterBuffer();
2773 if (argument.empty())
2774 format = master->getDefaultOutputFormat();
2775 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
2776 QFuture<docstring> f = QtConcurrent::run(exportAndDestroy,
2777 master->clone(), format);
2778 d.setPreviewFuture(f);
2780 bool const update_unincluded =
2781 master->params().maintain_unincluded_children
2782 && !master->params().getIncludedChildren().empty();
2783 master->doExport(format, true);
2787 case LFUN_MASTER_BUFFER_VIEW: {
2788 string format = argument;
2789 Buffer const * master = doc_buffer->masterBuffer();
2790 if (argument.empty())
2791 format = master->getDefaultOutputFormat();
2792 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
2793 QFuture<docstring> f = QtConcurrent::run(previewAndDestroy,
2794 master->clone(), format);
2795 d.setPreviewFuture(f);
2797 master->preview(format);
2801 case LFUN_BUFFER_SWITCH:
2802 if (FileName::isAbsolute(to_utf8(cmd.argument()))) {
2804 theBufferList().getBuffer(FileName(to_utf8(cmd.argument())));
2808 message(_("Document not loaded"));
2812 case LFUN_BUFFER_NEXT:
2813 gotoNextOrPreviousBuffer(NEXTBUFFER);
2816 case LFUN_BUFFER_PREVIOUS:
2817 gotoNextOrPreviousBuffer(PREVBUFFER);
2820 case LFUN_COMMAND_EXECUTE: {
2821 bool const show_it = cmd.argument() != "off";
2822 // FIXME: this is a hack, "minibuffer" should not be
2824 if (GuiToolbar * t = toolbar("minibuffer")) {
2825 t->setVisible(show_it);
2826 if (show_it && t->commandBuffer())
2827 t->commandBuffer()->setFocus();
2831 case LFUN_DROP_LAYOUTS_CHOICE:
2832 d.layout_->showPopup();
2835 case LFUN_MENU_OPEN:
2836 if (QMenu * menu = guiApp->menus().menu(toqstr(cmd.argument()), *this))
2837 menu->exec(QCursor::pos());
2840 case LFUN_FILE_INSERT:
2841 insertLyXFile(cmd.argument());
2843 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
2844 insertPlaintextFile(cmd.argument(), true);
2847 case LFUN_FILE_INSERT_PLAINTEXT:
2848 insertPlaintextFile(cmd.argument(), false);
2851 case LFUN_BUFFER_RELOAD: {
2852 LASSERT(doc_buffer, break);
2853 docstring const file = makeDisplayPath(doc_buffer->absFileName(), 20);
2854 docstring text = bformat(_("Any changes will be lost. Are you sure "
2855 "you want to revert to the saved version of the document %1$s?"), file);
2856 int const ret = Alert::prompt(_("Revert to saved document?"),
2857 text, 1, 1, _("&Revert"), _("&Cancel"));
2860 doc_buffer->markClean();
2866 case LFUN_BUFFER_WRITE:
2867 LASSERT(doc_buffer, break);
2868 saveBuffer(*doc_buffer);
2871 case LFUN_BUFFER_WRITE_AS:
2872 LASSERT(doc_buffer, break);
2873 renameBuffer(*doc_buffer, cmd.argument());
2876 case LFUN_BUFFER_WRITE_ALL: {
2877 Buffer * first = theBufferList().first();
2880 message(_("Saving all documents..."));
2881 // We cannot use a for loop as the buffer list cycles.
2884 if (!b->isClean()) {
2886 LYXERR(Debug::ACTION, "Saved " << b->absFileName());
2888 b = theBufferList().next(b);
2889 } while (b != first);
2890 message(_("All documents saved."));
2894 case LFUN_BUFFER_CLOSE:
2898 case LFUN_BUFFER_CLOSE_ALL:
2902 case LFUN_TOOLBAR_TOGGLE: {
2903 string const name = cmd.getArg(0);
2904 if (GuiToolbar * t = toolbar(name))
2909 case LFUN_DIALOG_UPDATE: {
2910 string const name = to_utf8(cmd.argument());
2911 if (currentBufferView()) {
2912 Inset * inset = currentBufferView()->editedInset(name);
2913 // Can only update a dialog connected to an existing inset
2916 // FIXME: get rid of this indirection; GuiView ask the inset
2917 // if he is kind enough to update itself...
2918 FuncRequest fr(LFUN_INSET_DIALOG_UPDATE, cmd.argument());
2919 inset->dispatch(currentBufferView()->cursor(), fr);
2920 } else if (name == "paragraph") {
2921 lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
2922 } else if (name == "prefs" || name == "document") {
2923 updateDialog(name, string());
2928 case LFUN_DIALOG_TOGGLE: {
2929 if (isDialogVisible(cmd.getArg(0)))
2930 dispatch(FuncRequest(LFUN_DIALOG_HIDE, cmd.argument()));
2932 dispatch(FuncRequest(LFUN_DIALOG_SHOW, cmd.argument()));
2936 case LFUN_DIALOG_DISCONNECT_INSET:
2937 disconnectDialog(to_utf8(cmd.argument()));
2940 case LFUN_DIALOG_HIDE: {
2941 guiApp->hideDialogs(to_utf8(cmd.argument()), 0);
2945 case LFUN_DIALOG_SHOW: {
2946 string const name = cmd.getArg(0);
2947 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
2949 if (name == "character") {
2950 data = freefont2string();
2952 showDialog("character", data);
2953 } else if (name == "latexlog") {
2954 Buffer::LogType type;
2955 string const logfile = doc_buffer->logName(&type);
2957 case Buffer::latexlog:
2960 case Buffer::buildlog:
2964 data += Lexer::quoteString(logfile);
2965 showDialog("log", data);
2966 } else if (name == "vclog") {
2967 string const data = "vc " +
2968 Lexer::quoteString(doc_buffer->lyxvc().getLogFile());
2969 showDialog("log", data);
2970 } else if (name == "symbols") {
2971 data = bv->cursor().getEncoding()->name();
2973 showDialog("symbols", data);
2975 } else if (name == "prefs" && isFullScreen()) {
2976 FuncRequest fr(LFUN_INSET_INSERT, "fullscreen");
2978 showDialog("prefs", data);
2980 showDialog(name, data);
2985 message(cmd.argument());
2988 case LFUN_UI_TOGGLE:
2990 // Make sure the keyboard focus stays in the work area.
2994 case LFUN_SPLIT_VIEW: {
2995 LASSERT(doc_buffer, break);
2996 string const orientation = cmd.getArg(0);
2997 d.splitter_->setOrientation(orientation == "vertical"
2998 ? Qt::Vertical : Qt::Horizontal);
2999 TabWorkArea * twa = addTabWorkArea();
3000 GuiWorkArea * wa = twa->addWorkArea(*doc_buffer, *this);
3001 setCurrentWorkArea(wa);
3004 case LFUN_CLOSE_TAB_GROUP:
3005 if (TabWorkArea * twa = d.currentTabWorkArea()) {
3006 closeTabWorkArea(twa);
3007 d.current_work_area_ = 0;
3008 twa = d.currentTabWorkArea();
3009 // Switch to the next GuiWorkArea in the found TabWorkArea.
3011 // Make sure the work area is up to date.
3012 setCurrentWorkArea(twa->currentWorkArea());
3014 setCurrentWorkArea(0);
3019 case LFUN_COMPLETION_INLINE:
3020 if (d.current_work_area_)
3021 d.current_work_area_->completer().showInline();
3024 case LFUN_COMPLETION_POPUP:
3025 if (d.current_work_area_)
3026 d.current_work_area_->completer().showPopup();
3030 case LFUN_COMPLETION_COMPLETE:
3031 if (d.current_work_area_)
3032 d.current_work_area_->completer().tab();
3035 case LFUN_COMPLETION_CANCEL:
3036 if (d.current_work_area_) {
3037 if (d.current_work_area_->completer().popupVisible())
3038 d.current_work_area_->completer().hidePopup();
3040 d.current_work_area_->completer().hideInline();
3044 case LFUN_COMPLETION_ACCEPT:
3045 if (d.current_work_area_)
3046 d.current_work_area_->completer().activate();
3049 case LFUN_BUFFER_ZOOM_IN:
3050 case LFUN_BUFFER_ZOOM_OUT:
3051 if (cmd.argument().empty()) {
3052 if (cmd.action == LFUN_BUFFER_ZOOM_IN)
3057 lyxrc.zoom += convert<int>(cmd.argument());
3059 if (lyxrc.zoom < 10)
3062 // The global QPixmapCache is used in GuiPainter to cache text
3063 // painting so we must reset it.
3064 QPixmapCache::clear();
3065 guiApp->fontLoader().update();
3066 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
3069 case LFUN_VC_REGISTER:
3070 case LFUN_VC_CHECK_IN:
3071 case LFUN_VC_CHECK_OUT:
3072 case LFUN_VC_REPO_UPDATE:
3073 case LFUN_VC_LOCKING_TOGGLE:
3074 case LFUN_VC_REVERT:
3075 case LFUN_VC_UNDO_LAST:
3076 case LFUN_VC_COMMAND:
3080 case LFUN_SERVER_GOTO_FILE_ROW:
3081 goToFileRow(to_utf8(cmd.argument()));
3089 // Part of automatic menu appearance feature.
3090 if (isFullScreen()) {
3091 if (menuBar()->isVisible() && lyxrc.full_screen_menubar)
3093 if (statusBar()->isVisible())
3094 statusBar()->hide();
3101 void GuiView::lfunUiToggle(FuncRequest const & cmd)
3103 string const arg = cmd.getArg(0);
3104 if (arg == "scrollbar") {
3105 // hide() is of no help
3106 if (d.current_work_area_->verticalScrollBarPolicy() ==
3107 Qt::ScrollBarAlwaysOff)
3109 d.current_work_area_->setVerticalScrollBarPolicy(
3110 Qt::ScrollBarAsNeeded);
3112 d.current_work_area_->setVerticalScrollBarPolicy(
3113 Qt::ScrollBarAlwaysOff);
3116 if (arg == "statusbar") {
3117 statusBar()->setVisible(!statusBar()->isVisible());
3120 if (arg == "menubar") {
3121 menuBar()->setVisible(!menuBar()->isVisible());
3124 #if QT_VERSION >= 0x040300
3125 if (arg == "frame") {
3127 getContentsMargins(&l, &t, &r, &b);
3128 //are the frames in default state?
3129 d.current_work_area_->setFrameStyle(QFrame::NoFrame);
3131 setContentsMargins(-2, -2, -2, -2);
3133 setContentsMargins(0, 0, 0, 0);
3138 if (arg == "fullscreen") {
3143 message(bformat("LFUN_UI_TOGGLE " + _("%1$s unknown command!"), from_utf8(arg)));
3147 void GuiView::toggleFullScreen()
3149 if (isFullScreen()) {
3150 for (int i = 0; i != d.splitter_->count(); ++i)
3151 d.tabWorkArea(i)->setFullScreen(false);
3152 #if QT_VERSION >= 0x040300
3153 setContentsMargins(0, 0, 0, 0);
3155 setWindowState(windowState() ^ Qt::WindowFullScreen);
3158 statusBar()->show();
3161 hideDialogs("prefs", 0);
3162 for (int i = 0; i != d.splitter_->count(); ++i)
3163 d.tabWorkArea(i)->setFullScreen(true);
3164 #if QT_VERSION >= 0x040300
3165 setContentsMargins(-2, -2, -2, -2);
3168 setWindowState(windowState() ^ Qt::WindowFullScreen);
3169 statusBar()->hide();
3170 if (lyxrc.full_screen_menubar)
3172 if (lyxrc.full_screen_toolbars) {
3173 ToolbarMap::iterator end = d.toolbars_.end();
3174 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
3179 // give dialogs like the TOC a chance to adapt
3184 Buffer const * GuiView::updateInset(Inset const * inset)
3186 if (!d.current_work_area_)
3190 d.current_work_area_->scheduleRedraw();
3192 return &d.current_work_area_->bufferView().buffer();
3196 void GuiView::restartCursor()
3198 /* When we move around, or type, it's nice to be able to see
3199 * the cursor immediately after the keypress.
3201 if (d.current_work_area_)
3202 d.current_work_area_->startBlinkingCursor();
3204 // Take this occasion to update the other GUI elements.
3210 void GuiView::updateCompletion(Cursor & cur, bool start, bool keep)
3212 if (d.current_work_area_)
3213 d.current_work_area_->completer().updateVisibility(cur, start, keep);
3218 // This list should be kept in sync with the list of insets in
3219 // src/insets/Inset.cpp. I.e., if a dialog goes with an inset, the
3220 // dialog should have the same name as the inset.
3221 // Changes should be also recorded in LFUN_DIALOG_SHOW doxygen
3222 // docs in LyXAction.cpp.
3224 char const * const dialognames[] = {
3225 "aboutlyx", "bibitem", "bibtex", "box", "branch", "changes", "character",
3226 "citation", "compare", "document", "errorlist", "ert", "external", "file",
3227 "findreplace", "findreplaceadv", "float", "graphics", "href", "include",
3228 "index", "index_print", "info", "listings", "label", "log", "mathdelimiter",
3229 "mathmatrix", "mathspace", "nomenclature", "nomencl_print", "note",
3230 "paragraph", "phantom", "prefs", "print", "ref", "sendto", "space",
3231 "spellchecker", "symbols", "tabular", "tabularcreate", "thesaurus", "texinfo",
3232 "toc", "view-source", "vspace", "wrap", "progress"};
3234 char const * const * const end_dialognames =
3235 dialognames + (sizeof(dialognames) / sizeof(char *));
3239 cmpCStr(char const * name) : name_(name) {}
3240 bool operator()(char const * other) {
3241 return strcmp(other, name_) == 0;
3248 bool isValidName(string const & name)
3250 return find_if(dialognames, end_dialognames,
3251 cmpCStr(name.c_str())) != end_dialognames;
3257 void GuiView::resetDialogs()
3259 // Make sure that no LFUN uses any LyXView.
3260 guiApp->setCurrentView(0);
3263 constructToolbars();
3264 guiApp->menus().fillMenuBar(menuBar(), this, false);
3265 d.layout_->updateContents(true);
3266 // Now update controls with current buffer.
3267 guiApp->setCurrentView(this);
3273 Dialog * GuiView::findOrBuild(string const & name, bool hide_it)
3275 if (!isValidName(name))
3278 map<string, DialogPtr>::iterator it = d.dialogs_.find(name);
3280 if (it != d.dialogs_.end()) {
3282 it->second->hideView();
3283 return it->second.get();
3286 Dialog * dialog = build(name);
3287 d.dialogs_[name].reset(dialog);
3288 if (lyxrc.allow_geometry_session)
3289 dialog->restoreSession();
3296 void GuiView::showDialog(string const & name, string const & data,
3299 triggerShowDialog(toqstr(name), toqstr(data), inset);
3303 void GuiView::doShowDialog(QString const & qname, QString const & qdata,
3309 const string name = fromqstr(qname);
3310 const string data = fromqstr(qdata);
3314 Dialog * dialog = findOrBuild(name, false);
3316 dialog->showData(data);
3317 if (inset && currentBufferView())
3318 currentBufferView()->editInset(name, inset);
3321 catch (ExceptionMessage const & ex) {
3329 bool GuiView::isDialogVisible(string const & name) const
3331 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3332 if (it == d.dialogs_.end())
3334 return it->second.get()->isVisibleView() && !it->second.get()->isClosing();
3338 void GuiView::hideDialog(string const & name, Inset * inset)
3340 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3341 if (it == d.dialogs_.end())
3344 if (inset && currentBufferView()
3345 && inset != currentBufferView()->editedInset(name))
3348 Dialog * const dialog = it->second.get();
3349 if (dialog->isVisibleView())
3351 if (currentBufferView())
3352 currentBufferView()->editInset(name, 0);
3356 void GuiView::disconnectDialog(string const & name)
3358 if (!isValidName(name))
3360 if (currentBufferView())
3361 currentBufferView()->editInset(name, 0);
3365 void GuiView::hideAll() const
3367 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
3368 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3370 for(; it != end; ++it)
3371 it->second->hideView();
3375 void GuiView::updateDialogs()
3377 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
3378 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3380 for(; it != end; ++it) {
3381 Dialog * dialog = it->second.get();
3383 if (dialog->isBufferDependent() && !documentBufferView())
3384 hideDialog(fromqstr(dialog->name()), 0);
3385 else if (dialog->isVisibleView())
3386 dialog->checkStatus();
3394 // will be replaced by a proper factory...
3395 Dialog * createGuiAbout(GuiView & lv);
3396 Dialog * createGuiBibitem(GuiView & lv);
3397 Dialog * createGuiBibtex(GuiView & lv);
3398 Dialog * createGuiBox(GuiView & lv);
3399 Dialog * createGuiBranch(GuiView & lv);
3400 Dialog * createGuiChanges(GuiView & lv);
3401 Dialog * createGuiCharacter(GuiView & lv);
3402 Dialog * createGuiCitation(GuiView & lv);
3403 Dialog * createGuiCompare(GuiView & lv);
3404 Dialog * createGuiDelimiter(GuiView & lv);
3405 Dialog * createGuiDocument(GuiView & lv);
3406 Dialog * createGuiErrorList(GuiView & lv);
3407 Dialog * createGuiERT(GuiView & lv);
3408 Dialog * createGuiExternal(GuiView & lv);
3409 Dialog * createGuiFloat(GuiView & lv);
3410 Dialog * createGuiGraphics(GuiView & lv);
3411 Dialog * createGuiInclude(GuiView & lv);
3412 Dialog * createGuiIndex(GuiView & lv);
3413 Dialog * createGuiInfo(GuiView & lv);
3414 Dialog * createGuiLabel(GuiView & lv);
3415 Dialog * createGuiListings(GuiView & lv);
3416 Dialog * createGuiLog(GuiView & lv);
3417 Dialog * createGuiMathHSpace(GuiView & lv);
3418 Dialog * createGuiMathMatrix(GuiView & lv);
3419 Dialog * createGuiNomenclature(GuiView & lv);
3420 Dialog * createGuiNote(GuiView & lv);
3421 Dialog * createGuiParagraph(GuiView & lv);
3422 Dialog * createGuiPhantom(GuiView & lv);
3423 Dialog * createGuiPreferences(GuiView & lv);
3424 Dialog * createGuiPrint(GuiView & lv);
3425 Dialog * createGuiPrintindex(GuiView & lv);
3426 Dialog * createGuiPrintNomencl(GuiView & lv);
3427 Dialog * createGuiRef(GuiView & lv);
3428 Dialog * createGuiSearch(GuiView & lv);
3429 Dialog * createGuiSearchAdv(GuiView & lv);
3430 Dialog * createGuiSendTo(GuiView & lv);
3431 Dialog * createGuiShowFile(GuiView & lv);
3432 Dialog * createGuiSpellchecker(GuiView & lv);
3433 Dialog * createGuiSymbols(GuiView & lv);
3434 Dialog * createGuiTabularCreate(GuiView & lv);
3435 Dialog * createGuiTabular(GuiView & lv);
3436 Dialog * createGuiTexInfo(GuiView & lv);
3437 Dialog * createGuiTextHSpace(GuiView & lv);
3438 Dialog * createGuiToc(GuiView & lv);
3439 Dialog * createGuiThesaurus(GuiView & lv);
3440 Dialog * createGuiHyperlink(GuiView & lv);
3441 Dialog * createGuiVSpace(GuiView & lv);
3442 Dialog * createGuiViewSource(GuiView & lv);
3443 Dialog * createGuiWrap(GuiView & lv);
3444 Dialog * createGuiProgressView(GuiView & lv);
3448 Dialog * GuiView::build(string const & name)
3450 LASSERT(isValidName(name), return 0);
3452 if (name == "aboutlyx")
3453 return createGuiAbout(*this);
3454 if (name == "bibitem")
3455 return createGuiBibitem(*this);
3456 if (name == "bibtex")
3457 return createGuiBibtex(*this);
3459 return createGuiBox(*this);
3460 if (name == "branch")
3461 return createGuiBranch(*this);
3462 if (name == "changes")
3463 return createGuiChanges(*this);
3464 if (name == "character")
3465 return createGuiCharacter(*this);
3466 if (name == "citation")
3467 return createGuiCitation(*this);
3468 if (name == "compare")
3469 return createGuiCompare(*this);
3470 if (name == "document")
3471 return createGuiDocument(*this);
3472 if (name == "errorlist")
3473 return createGuiErrorList(*this);
3475 return createGuiERT(*this);
3476 if (name == "external")
3477 return createGuiExternal(*this);
3479 return createGuiShowFile(*this);
3480 if (name == "findreplace")
3481 return createGuiSearch(*this);
3482 if (name == "findreplaceadv")
3483 return createGuiSearchAdv(*this);
3484 if (name == "float")
3485 return createGuiFloat(*this);
3486 if (name == "graphics")
3487 return createGuiGraphics(*this);
3489 return createGuiHyperlink(*this);
3490 if (name == "include")
3491 return createGuiInclude(*this);
3492 if (name == "index")
3493 return createGuiIndex(*this);
3494 if (name == "index_print")
3495 return createGuiPrintindex(*this);
3497 return createGuiInfo(*this);
3498 if (name == "label")
3499 return createGuiLabel(*this);
3500 if (name == "listings")
3501 return createGuiListings(*this);
3503 return createGuiLog(*this);
3504 if (name == "mathdelimiter")
3505 return createGuiDelimiter(*this);
3506 if (name == "mathspace")
3507 return createGuiMathHSpace(*this);
3508 if (name == "mathmatrix")
3509 return createGuiMathMatrix(*this);
3510 if (name == "nomenclature")
3511 return createGuiNomenclature(*this);
3512 if (name == "nomencl_print")
3513 return createGuiPrintNomencl(*this);
3515 return createGuiNote(*this);
3516 if (name == "paragraph")
3517 return createGuiParagraph(*this);
3518 if (name == "phantom")
3519 return createGuiPhantom(*this);
3520 if (name == "prefs")
3521 return createGuiPreferences(*this);
3522 if (name == "print")
3523 return createGuiPrint(*this);
3525 return createGuiRef(*this);
3526 if (name == "sendto")
3527 return createGuiSendTo(*this);
3528 if (name == "space")
3529 return createGuiTextHSpace(*this);
3530 if (name == "spellchecker")
3531 return createGuiSpellchecker(*this);
3532 if (name == "symbols")
3533 return createGuiSymbols(*this);
3534 if (name == "tabular")
3535 return createGuiTabular(*this);
3536 if (name == "tabularcreate")
3537 return createGuiTabularCreate(*this);
3538 if (name == "texinfo")
3539 return createGuiTexInfo(*this);
3540 if (name == "thesaurus")
3541 return createGuiThesaurus(*this);
3543 return createGuiToc(*this);
3544 if (name == "view-source")
3545 return createGuiViewSource(*this);
3546 if (name == "vspace")
3547 return createGuiVSpace(*this);
3549 return createGuiWrap(*this);
3550 if (name == "progress")
3551 return createGuiProgressView(*this);
3557 } // namespace frontend
3560 #include "moc_GuiView.cpp"