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"));
383 #if (QT_VERSION >= 0x040300)
384 // use tabbed dock area for multiple docks
385 // (such as "source" and "messages")
386 setDockOptions(QMainWindow::ForceTabbedDocks);
390 setAcceptDrops(true);
392 statusBar()->setSizeGripEnabled(true);
395 #if (QT_VERSION >= 0x040400)
396 connect(&d.autosave_watcher_, SIGNAL(finished()), this,
397 SLOT(threadFinished()));
398 connect(&d.preview_watcher_, SIGNAL(finished()), this,
399 SLOT(threadFinished()));
402 connect(this, SIGNAL(triggerShowDialog(QString const &, QString const &, Inset *)),
403 SLOT(doShowDialog(QString const &, QString const &, Inset *)));
405 // Forbid too small unresizable window because it can happen
406 // with some window manager under X11.
407 setMinimumSize(300, 200);
409 if (lyxrc.allow_geometry_session) {
410 // Now take care of session management.
415 // no session handling, default to a sane size.
416 setGeometry(50, 50, 690, 510);
419 // clear session data if any.
421 settings.remove("views");
431 void GuiView::threadFinished()
433 #if (QT_VERSION >= 0x040400)
434 QFutureWatcher<docstring> const * watcher =
435 static_cast<QFutureWatcher<docstring> const *>(sender());
436 message(watcher->result());
441 void GuiView::saveLayout() const
444 settings.beginGroup("views");
445 settings.beginGroup(QString::number(id_));
447 settings.setValue("pos", pos());
448 settings.setValue("size", size());
450 settings.setValue("geometry", saveGeometry());
452 settings.setValue("layout", saveState(0));
453 settings.setValue("icon_size", iconSize());
457 bool GuiView::restoreLayout()
460 settings.beginGroup("views");
461 settings.beginGroup(QString::number(id_));
462 QString const icon_key = "icon_size";
463 if (!settings.contains(icon_key))
466 //code below is skipped when when ~/.config/LyX is (re)created
467 setIconSize(settings.value(icon_key).toSize());
469 QPoint pos = settings.value("pos", QPoint(50, 50)).toPoint();
470 QSize size = settings.value("size", QSize(690, 510)).toSize();
474 // Work-around for bug #6034: the window ends up in an undetermined
475 // state when trying to restore a maximized window when it is
476 // already maximized.
477 if (!(windowState() & Qt::WindowMaximized))
478 if (!restoreGeometry(settings.value("geometry").toByteArray()))
479 setGeometry(50, 50, 690, 510);
481 // Make sure layout is correctly oriented.
482 setLayoutDirection(qApp->layoutDirection());
484 // Allow the toc and view-source dock widget to be restored if needed.
486 if ((dialog = findOrBuild("toc", true)))
487 // see bug 5082. At least setup title and enabled state.
488 // Visibility will be adjusted by restoreState below.
489 dialog->prepareView();
490 if ((dialog = findOrBuild("view-source", true)))
491 dialog->prepareView();
492 if ((dialog = findOrBuild("progress", true)))
493 dialog->prepareView();
495 if (!restoreState(settings.value("layout").toByteArray(), 0))
502 GuiToolbar * GuiView::toolbar(string const & name)
504 ToolbarMap::iterator it = d.toolbars_.find(name);
505 if (it != d.toolbars_.end())
508 LYXERR(Debug::GUI, "Toolbar::display: no toolbar named " << name);
509 message(bformat(_("Unknown toolbar \"%1$s\""), from_utf8(name)));
514 void GuiView::constructToolbars()
516 ToolbarMap::iterator it = d.toolbars_.begin();
517 for (; it != d.toolbars_.end(); ++it)
521 // I don't like doing this here, but the standard toolbar
522 // destroys this object when it's destroyed itself (vfr)
523 d.layout_ = new LayoutBox(*this);
524 d.stack_widget_->addWidget(d.layout_);
525 d.layout_->move(0,0);
527 // extracts the toolbars from the backend
528 Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
529 Toolbars::Infos::iterator end = guiApp->toolbars().end();
530 for (; cit != end; ++cit)
531 d.toolbars_[cit->name] = new GuiToolbar(*cit, *this);
535 void GuiView::initToolbars()
537 // extracts the toolbars from the backend
538 Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
539 Toolbars::Infos::iterator end = guiApp->toolbars().end();
540 for (; cit != end; ++cit) {
541 GuiToolbar * tb = toolbar(cit->name);
544 int const visibility = guiApp->toolbars().defaultVisibility(cit->name);
545 bool newline = !(visibility & Toolbars::SAMEROW);
546 tb->setVisible(false);
547 tb->setVisibility(visibility);
549 if (visibility & Toolbars::TOP) {
551 addToolBarBreak(Qt::TopToolBarArea);
552 addToolBar(Qt::TopToolBarArea, tb);
555 if (visibility & Toolbars::BOTTOM) {
556 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
557 #if (QT_VERSION >= 0x040202)
559 addToolBarBreak(Qt::BottomToolBarArea);
561 addToolBar(Qt::BottomToolBarArea, tb);
564 if (visibility & Toolbars::LEFT) {
565 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
566 #if (QT_VERSION >= 0x040202)
568 addToolBarBreak(Qt::LeftToolBarArea);
570 addToolBar(Qt::LeftToolBarArea, tb);
573 if (visibility & Toolbars::RIGHT) {
574 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
575 #if (QT_VERSION >= 0x040202)
577 addToolBarBreak(Qt::RightToolBarArea);
579 addToolBar(Qt::RightToolBarArea, tb);
582 if (visibility & Toolbars::ON)
583 tb->setVisible(true);
588 TocModels & GuiView::tocModels()
590 return d.toc_models_;
594 void GuiView::setFocus()
596 LYXERR(Debug::DEBUG, "GuiView::setFocus()" << this);
597 QMainWindow::setFocus();
601 void GuiView::focusInEvent(QFocusEvent * e)
603 LYXERR(Debug::DEBUG, "GuiView::focusInEvent()" << this);
604 QMainWindow::focusInEvent(e);
605 // Make sure LyXFunc points to the correct view.
606 guiApp->setCurrentView(this);
607 if (currentMainWorkArea())
608 currentMainWorkArea()->setFocus();
609 else if (currentWorkArea())
610 currentWorkArea()->setFocus();
612 d.bg_widget_->setFocus();
616 QMenu * GuiView::createPopupMenu()
618 return d.toolBarPopup(this);
622 void GuiView::showEvent(QShowEvent * e)
624 LYXERR(Debug::GUI, "Passed Geometry "
625 << size().height() << "x" << size().width()
626 << "+" << pos().x() << "+" << pos().y());
628 if (d.splitter_->count() == 0)
629 // No work area, switch to the background widget.
632 QMainWindow::showEvent(e);
636 /** Destroy only all tabbed WorkAreas. Destruction of other WorkAreas
637 ** is responsibility of the container (e.g., dialog)
639 void GuiView::closeEvent(QCloseEvent * close_event)
641 LYXERR(Debug::DEBUG, "GuiView::closeEvent()");
646 // it can happen that this event arrives without selecting the view,
647 // e.g. when clicking the close button on a background window.
649 if (!closeWorkAreaAll()) {
651 close_event->ignore();
655 // Make sure that nothing will use this to be closed View.
656 guiApp->unregisterView(this);
658 if (isFullScreen()) {
659 // Switch off fullscreen before closing.
664 // Make sure the timer time out will not trigger a statusbar update.
665 d.statusbar_timer_.stop();
667 // Saving fullscreen requires additional tweaks in the toolbar code.
668 // It wouldn't also work under linux natively.
669 if (lyxrc.allow_geometry_session) {
670 // Save this window geometry and layout.
672 // Then the toolbar private states.
673 ToolbarMap::iterator end = d.toolbars_.end();
674 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
675 it->second->saveSession();
676 // Now take care of all other dialogs:
677 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
678 for (; it!= d.dialogs_.end(); ++it)
679 it->second->saveSession();
682 close_event->accept();
686 void GuiView::dragEnterEvent(QDragEnterEvent * event)
688 if (event->mimeData()->hasUrls())
690 /// \todo Ask lyx-devel is this is enough:
691 /// if (event->mimeData()->hasFormat("text/plain"))
692 /// event->acceptProposedAction();
696 void GuiView::dropEvent(QDropEvent * event)
698 QList<QUrl> files = event->mimeData()->urls();
702 LYXERR(Debug::GUI, "GuiView::dropEvent: got URLs!");
703 for (int i = 0; i != files.size(); ++i) {
704 string const file = os::internal_path(fromqstr(
705 files.at(i).toLocalFile()));
709 string const ext = support::getExtension(file);
710 vector<const Format *> found_formats;
712 // Find all formats that have the correct extension.
713 vector<const Format *> const & import_formats
714 = theConverters().importableFormats();
715 vector<const Format *>::const_iterator it = import_formats.begin();
716 for (; it != import_formats.end(); ++it)
717 if ((*it)->extension() == ext)
718 found_formats.push_back(*it);
721 if (found_formats.size() >= 1) {
722 if (found_formats.size() > 1) {
723 //FIXME: show a dialog to choose the correct importable format
725 "Multiple importable formats found, selecting first");
727 string const arg = found_formats[0]->name() + " " + file;
728 cmd = FuncRequest(LFUN_BUFFER_IMPORT, arg);
731 //FIXME: do we have to explicitly check whether it's a lyx file?
733 "No formats found, trying to open it as a lyx file");
734 cmd = FuncRequest(LFUN_FILE_OPEN, file);
737 // Asynchronously post the event. DropEvent usually comes
738 // from the BufferView. But reloading a file might close
739 // the BufferView from within its own event handler.
740 guiApp->dispatchDelayed(cmd);
746 void GuiView::message(docstring const & str)
748 if (ForkedProcess::iAmAChild())
751 // call is moved to GUI-thread by GuiProgress
752 d.progress_->appendMessage(toqstr(str));
756 void GuiView::updateMessage(QString const & str)
758 statusBar()->showMessage(str);
759 d.statusbar_timer_.stop();
760 d.statusbar_timer_.start(3000);
764 void GuiView::smallSizedIcons()
766 setIconSize(QSize(d.smallIconSize, d.smallIconSize));
770 void GuiView::normalSizedIcons()
772 setIconSize(QSize(d.normalIconSize, d.normalIconSize));
776 void GuiView::bigSizedIcons()
778 setIconSize(QSize(d.bigIconSize, d.bigIconSize));
782 void GuiView::clearMessage()
784 // FIXME: This code was introduced in r19643 to fix bug #4123. However,
785 // the hasFocus function mostly returns false, even if the focus is on
786 // a workarea in this view.
790 d.statusbar_timer_.stop();
794 void GuiView::updateWindowTitle(GuiWorkArea * wa)
796 if (wa != d.current_work_area_
797 || wa->bufferView().buffer().isInternal())
799 setWindowTitle(qt_("LyX: ") + wa->windowTitle());
800 setWindowIconText(wa->windowIconText());
804 void GuiView::on_currentWorkAreaChanged(GuiWorkArea * wa)
807 disconnectBufferView();
808 connectBufferView(wa->bufferView());
809 connectBuffer(wa->bufferView().buffer());
810 d.current_work_area_ = wa;
811 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
812 this, SLOT(updateWindowTitle(GuiWorkArea *)));
813 updateWindowTitle(wa);
817 // The document settings needs to be reinitialised.
818 updateDialog("document", "");
820 // Buffer-dependent dialogs must be updated. This is done here because
821 // some dialogs require buffer()->text.
826 void GuiView::on_lastWorkAreaRemoved()
829 // We already are in a close event. Nothing more to do.
832 if (d.splitter_->count() > 1)
833 // We have a splitter so don't close anything.
836 // Reset and updates the dialogs.
837 d.toc_models_.reset(0);
838 updateDialog("document", "");
841 resetWindowTitleAndIconText();
844 if (lyxrc.open_buffers_in_tabs)
845 // Nothing more to do, the window should stay open.
848 if (guiApp->viewIds().size() > 1) {
854 // On Mac we also close the last window because the application stay
855 // resident in memory. On other platforms we don't close the last
856 // window because this would quit the application.
862 void GuiView::updateStatusBar()
864 // let the user see the explicit message
865 if (d.statusbar_timer_.isActive())
872 void GuiView::showMessage()
874 QString msg = toqstr(theGuiApp()->viewStatusMessage());
876 BufferView const * bv = currentBufferView();
878 msg = toqstr(bv->cursor().currentState());
880 msg = qt_("Welcome to LyX!");
882 statusBar()->showMessage(msg);
886 bool GuiView::event(QEvent * e)
890 // Useful debug code:
891 //case QEvent::ActivationChange:
892 //case QEvent::WindowDeactivate:
893 //case QEvent::Paint:
894 //case QEvent::Enter:
895 //case QEvent::Leave:
896 //case QEvent::HoverEnter:
897 //case QEvent::HoverLeave:
898 //case QEvent::HoverMove:
899 //case QEvent::StatusTip:
900 //case QEvent::DragEnter:
901 //case QEvent::DragLeave:
905 case QEvent::WindowActivate: {
906 GuiView * old_view = guiApp->currentView();
907 if (this == old_view) {
909 return QMainWindow::event(e);
911 if (old_view && old_view->currentBufferView()) {
912 // save current selection to the selection buffer to allow
913 // middle-button paste in this window.
914 cap::saveSelection(old_view->currentBufferView()->cursor());
916 guiApp->setCurrentView(this);
917 if (d.current_work_area_) {
918 BufferView & bv = d.current_work_area_->bufferView();
919 connectBufferView(bv);
920 connectBuffer(bv.buffer());
921 // The document structure, name and dialogs might have
922 // changed in another view.
924 // The document settings needs to be reinitialised.
925 updateDialog("document", "");
928 resetWindowTitleAndIconText();
931 return QMainWindow::event(e);
934 case QEvent::ShortcutOverride: {
937 #if (!defined Q_WS_X11) || (QT_VERSION >= 0x040500)
938 if (isFullScreen() && menuBar()->isHidden()) {
939 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
940 // FIXME: we should also try to detect special LyX shortcut such as
941 // Alt-P and Alt-M. Right now there is a hack in
942 // GuiWorkArea::processKeySym() that hides again the menubar for
944 if (ke->modifiers() & Qt::AltModifier && ke->key() != Qt::Key_Alt) {
946 return QMainWindow::event(e);
950 return QMainWindow::event(e);
954 return QMainWindow::event(e);
958 void GuiView::resetWindowTitleAndIconText()
960 setWindowTitle(qt_("LyX"));
961 setWindowIconText(qt_("LyX"));
964 bool GuiView::focusNextPrevChild(bool /*next*/)
971 void GuiView::setBusy(bool busy)
973 if (d.current_work_area_) {
974 d.current_work_area_->setUpdatesEnabled(!busy);
976 d.current_work_area_->stopBlinkingCursor();
978 d.current_work_area_->startBlinkingCursor();
982 QApplication::setOverrideCursor(Qt::WaitCursor);
984 QApplication::restoreOverrideCursor();
988 GuiWorkArea * GuiView::workArea(Buffer & buffer)
990 if (currentWorkArea()
991 && ¤tWorkArea()->bufferView().buffer() == &buffer)
992 return (GuiWorkArea *) currentWorkArea();
993 if (TabWorkArea * twa = d.currentTabWorkArea())
994 return twa->workArea(buffer);
999 GuiWorkArea * GuiView::addWorkArea(Buffer & buffer)
1001 // Automatically create a TabWorkArea if there are none yet.
1002 TabWorkArea * tab_widget = d.splitter_->count()
1003 ? d.currentTabWorkArea() : addTabWorkArea();
1004 return tab_widget->addWorkArea(buffer, *this);
1008 TabWorkArea * GuiView::addTabWorkArea()
1010 TabWorkArea * twa = new TabWorkArea;
1011 QObject::connect(twa, SIGNAL(currentWorkAreaChanged(GuiWorkArea *)),
1012 this, SLOT(on_currentWorkAreaChanged(GuiWorkArea *)));
1013 QObject::connect(twa, SIGNAL(lastWorkAreaRemoved()),
1014 this, SLOT(on_lastWorkAreaRemoved()));
1016 d.splitter_->addWidget(twa);
1017 d.stack_widget_->setCurrentWidget(d.splitter_);
1022 GuiWorkArea const * GuiView::currentWorkArea() const
1024 return d.current_work_area_;
1028 GuiWorkArea * GuiView::currentWorkArea()
1030 return d.current_work_area_;
1034 GuiWorkArea const * GuiView::currentMainWorkArea() const
1036 if (d.currentTabWorkArea() == NULL)
1038 return d.currentTabWorkArea()->currentWorkArea();
1042 GuiWorkArea * GuiView::currentMainWorkArea()
1044 if (d.currentTabWorkArea() == NULL)
1046 return d.currentTabWorkArea()->currentWorkArea();
1050 void GuiView::setCurrentWorkArea(GuiWorkArea * wa)
1052 LYXERR(Debug::DEBUG, "Setting current wa: " << wa << endl);
1054 d.current_work_area_ = NULL;
1058 GuiWorkArea * old_gwa = theGuiApp()->currentView()->currentWorkArea();
1062 if (currentBufferView())
1063 cap::saveSelection(currentBufferView()->cursor());
1065 theGuiApp()->setCurrentView(this);
1066 d.current_work_area_ = wa;
1067 for (int i = 0; i != d.splitter_->count(); ++i) {
1068 if (d.tabWorkArea(i)->setCurrentWorkArea(wa)) {
1069 //if (d.current_main_work_area_)
1070 // d.current_main_work_area_->setFrameStyle(QFrame::NoFrame);
1071 d.current_main_work_area_ = wa;
1072 //d.current_main_work_area_->setFrameStyle(QFrame::Box | QFrame::Plain);
1073 //d.current_main_work_area_->setLineWidth(2);
1074 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() << ", Current main wa: " << currentMainWorkArea());
1078 LYXERR(Debug::DEBUG, "This is not a tabbed wa");
1079 on_currentWorkAreaChanged(wa);
1080 BufferView & bv = wa->bufferView();
1081 bv.cursor().fixIfBroken();
1083 wa->setUpdatesEnabled(true);
1084 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() << ", Current main wa: " << currentMainWorkArea());
1088 void GuiView::removeWorkArea(GuiWorkArea * wa)
1090 LASSERT(wa, return);
1091 if (wa == d.current_work_area_) {
1093 disconnectBufferView();
1094 d.current_work_area_ = 0;
1095 d.current_main_work_area_ = 0;
1098 bool found_twa = false;
1099 for (int i = 0; i != d.splitter_->count(); ++i) {
1100 TabWorkArea * twa = d.tabWorkArea(i);
1101 if (twa->removeWorkArea(wa)) {
1102 // Found in this tab group, and deleted the GuiWorkArea.
1104 if (twa->count() != 0) {
1105 if (d.current_work_area_ == 0)
1106 // This means that we are closing the current GuiWorkArea, so
1107 // switch to the next GuiWorkArea in the found TabWorkArea.
1108 setCurrentWorkArea(twa->currentWorkArea());
1110 // No more WorkAreas in this tab group, so delete it.
1117 // It is not a tabbed work area (i.e., the search work area), so it
1118 // should be deleted by other means.
1119 LASSERT(found_twa, /* */);
1121 if (d.current_work_area_ == 0) {
1122 if (d.splitter_->count() != 0) {
1123 TabWorkArea * twa = d.currentTabWorkArea();
1124 setCurrentWorkArea(twa->currentWorkArea());
1126 // No more work areas, switch to the background widget.
1127 setCurrentWorkArea(0);
1133 LayoutBox * GuiView::getLayoutDialog() const
1139 void GuiView::updateLayoutList()
1142 d.layout_->updateContents(false);
1146 void GuiView::updateToolbars()
1148 ToolbarMap::iterator end = d.toolbars_.end();
1149 if (d.current_work_area_) {
1151 d.current_work_area_->bufferView().cursor().inMathed();
1153 lyx::getStatus(FuncRequest(LFUN_LAYOUT_TABULAR)).enabled();
1155 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).enabled() &&
1156 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).onoff(true);
1157 bool const mathmacrotemplate =
1158 lyx::getStatus(FuncRequest(LFUN_IN_MATHMACROTEMPLATE)).enabled();
1160 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1161 it->second->update(math, table, review, mathmacrotemplate);
1163 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1164 it->second->update(false, false, false, false);
1168 void GuiView::setBuffer(Buffer * newBuffer)
1170 LYXERR(Debug::DEBUG, "Setting buffer: " << newBuffer << endl);
1171 LASSERT(newBuffer, return);
1174 GuiWorkArea * wa = workArea(*newBuffer);
1176 newBuffer->masterBuffer()->updateLabels();
1177 wa = addWorkArea(*newBuffer);
1179 //Disconnect the old buffer...there's no new one.
1182 connectBuffer(*newBuffer);
1183 connectBufferView(wa->bufferView());
1184 setCurrentWorkArea(wa);
1190 void GuiView::connectBuffer(Buffer & buf)
1192 buf.setGuiDelegate(this);
1196 void GuiView::disconnectBuffer()
1198 if (d.current_work_area_)
1199 d.current_work_area_->bufferView().buffer().setGuiDelegate(0);
1203 void GuiView::connectBufferView(BufferView & bv)
1205 bv.setGuiDelegate(this);
1209 void GuiView::disconnectBufferView()
1211 if (d.current_work_area_)
1212 d.current_work_area_->bufferView().setGuiDelegate(0);
1216 void GuiView::errors(string const & error_type, bool from_master)
1218 ErrorList & el = from_master ?
1219 documentBufferView()->buffer().masterBuffer()->errorList(error_type)
1220 : documentBufferView()->buffer().errorList(error_type);
1221 string data = error_type;
1223 data = "from_master|" + error_type;
1225 showDialog("errorlist", data);
1229 void GuiView::updateTocItem(string const & type, DocIterator const & dit)
1231 d.toc_models_.updateItem(toqstr(type), dit);
1235 void GuiView::structureChanged()
1237 d.toc_models_.reset(documentBufferView());
1238 // Navigator needs more than a simple update in this case. It needs to be
1240 updateDialog("toc", "");
1244 void GuiView::updateDialog(string const & name, string const & data)
1246 if (!isDialogVisible(name))
1249 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
1250 if (it == d.dialogs_.end())
1253 Dialog * const dialog = it->second.get();
1254 if (dialog->isVisibleView())
1255 dialog->initialiseParams(data);
1259 BufferView * GuiView::documentBufferView()
1261 return currentMainWorkArea()
1262 ? ¤tMainWorkArea()->bufferView()
1267 BufferView const * GuiView::documentBufferView() const
1269 return currentMainWorkArea()
1270 ? ¤tMainWorkArea()->bufferView()
1275 BufferView * GuiView::currentBufferView()
1277 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1281 BufferView const * GuiView::currentBufferView() const
1283 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1287 #if (QT_VERSION >= 0x040400)
1288 static docstring saveAndDestroyBuffer(Buffer * buffer, FileName const & fname)
1291 FileName const tmp_ret = FileName::tempName("lyxauto");
1292 if (!tmp_ret.empty()) {
1293 if (buffer->writeFile(tmp_ret))
1294 failed = !tmp_ret.moveTo(fname);
1297 // failed to write/rename tmp_ret so try writing direct
1298 failed = buffer->writeFile(fname);
1302 ? _("Automatic save failed!")
1303 : _("Automatic save done.");
1308 void GuiView::autoSave()
1310 LYXERR(Debug::INFO, "Running autoSave()");
1312 Buffer * buffer = documentBufferView()
1313 ? &documentBufferView()->buffer() : 0;
1317 #if (QT_VERSION >= 0x040400)
1318 QFuture<docstring> f = QtConcurrent::run(saveAndDestroyBuffer, buffer->clone(),
1319 buffer->getAutosaveFilename());
1320 d.autosave_watcher_.setFuture(f);
1327 void GuiView::resetAutosaveTimers()
1330 d.autosave_timeout_.restart();
1334 bool GuiView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1337 Buffer * buf = currentBufferView()
1338 ? ¤tBufferView()->buffer() : 0;
1339 Buffer * doc_buffer = documentBufferView()
1340 ? &(documentBufferView()->buffer()) : 0;
1342 // Check whether we need a buffer
1343 if (!lyxaction.funcHasFlag(cmd.action, LyXAction::NoBuffer) && !buf) {
1344 // no, exit directly
1345 flag.message(from_utf8(N_("Command not allowed with"
1346 "out any document open")));
1347 flag.setEnabled(false);
1351 if (cmd.origin == FuncRequest::TOC) {
1352 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
1354 if (toc->getStatus(documentBufferView()->cursor(), cmd, fs))
1357 flag.setEnabled(false);
1361 switch(cmd.action) {
1362 case LFUN_BUFFER_IMPORT:
1365 case LFUN_MASTER_BUFFER_UPDATE:
1366 case LFUN_MASTER_BUFFER_VIEW:
1367 enable = doc_buffer && doc_buffer->parent() != 0
1368 && !d.preview_watcher_.isRunning();
1371 case LFUN_BUFFER_UPDATE:
1372 case LFUN_BUFFER_VIEW: {
1373 if (!doc_buffer || d.preview_watcher_.isRunning()) {
1377 string format = to_utf8(cmd.argument());
1378 if (cmd.argument().empty())
1379 format = doc_buffer->getDefaultOutputFormat();
1380 enable = doc_buffer->isExportableFormat(format);
1384 case LFUN_BUFFER_RELOAD:
1385 enable = doc_buffer && !doc_buffer->isUnnamed()
1386 && doc_buffer->fileName().exists()
1387 && (!doc_buffer->isClean()
1388 || doc_buffer->isExternallyModified(Buffer::timestamp_method));
1391 case LFUN_BUFFER_CHILD_OPEN:
1392 enable = doc_buffer;
1395 case LFUN_BUFFER_WRITE:
1396 enable = doc_buffer && (doc_buffer->isUnnamed() || !doc_buffer->isClean());
1399 //FIXME: This LFUN should be moved to GuiApplication.
1400 case LFUN_BUFFER_WRITE_ALL: {
1401 // We enable the command only if there are some modified buffers
1402 Buffer * first = theBufferList().first();
1407 // We cannot use a for loop as the buffer list is a cycle.
1409 if (!b->isClean()) {
1413 b = theBufferList().next(b);
1414 } while (b != first);
1418 case LFUN_BUFFER_WRITE_AS:
1419 enable = doc_buffer;
1422 case LFUN_BUFFER_CLOSE:
1423 enable = doc_buffer;
1426 case LFUN_BUFFER_CLOSE_ALL:
1427 enable = theBufferList().last() != theBufferList().first();
1430 case LFUN_SPLIT_VIEW:
1431 if (cmd.getArg(0) == "vertical")
1432 enable = doc_buffer && (d.splitter_->count() == 1 ||
1433 d.splitter_->orientation() == Qt::Vertical);
1435 enable = doc_buffer && (d.splitter_->count() == 1 ||
1436 d.splitter_->orientation() == Qt::Horizontal);
1439 case LFUN_CLOSE_TAB_GROUP:
1440 enable = d.currentTabWorkArea();
1443 case LFUN_TOOLBAR_TOGGLE:
1444 if (GuiToolbar * t = toolbar(cmd.getArg(0)))
1445 flag.setOnOff(t->isVisible());
1448 case LFUN_DROP_LAYOUTS_CHOICE:
1452 case LFUN_UI_TOGGLE:
1453 flag.setOnOff(isFullScreen());
1456 case LFUN_DIALOG_DISCONNECT_INSET:
1459 case LFUN_DIALOG_HIDE:
1460 // FIXME: should we check if the dialog is shown?
1463 case LFUN_DIALOG_TOGGLE:
1464 flag.setOnOff(isDialogVisible(cmd.getArg(0)));
1465 // fall through to set "enable"
1466 case LFUN_DIALOG_SHOW: {
1467 string const name = cmd.getArg(0);
1469 enable = name == "aboutlyx"
1470 || name == "file" //FIXME: should be removed.
1472 || name == "texinfo"
1473 || name == "progress"
1474 || name == "compare";
1475 else if (name == "print")
1476 enable = doc_buffer->isExportable("dvi")
1477 && lyxrc.print_command != "none";
1478 else if (name == "character" || name == "symbols") {
1479 if (!buf || buf->isReadonly()
1480 || !currentBufferView()->cursor().inTexted())
1483 // FIXME we should consider passthru
1485 Inset const & in = currentBufferView()->cursor().inset();
1486 enable = !in.getLayout().isPassThru();
1489 else if (name == "latexlog")
1490 enable = FileName(doc_buffer->logName()).isReadableFile();
1491 else if (name == "spellchecker")
1492 enable = theSpellChecker() && !doc_buffer->isReadonly();
1493 else if (name == "vclog")
1494 enable = doc_buffer->lyxvc().inUse();
1498 case LFUN_DIALOG_UPDATE: {
1499 string const name = cmd.getArg(0);
1501 enable = name == "prefs";
1505 case LFUN_COMMAND_EXECUTE:
1507 case LFUN_MENU_OPEN:
1508 // Nothing to check.
1511 case LFUN_COMPLETION_INLINE:
1512 if (!d.current_work_area_
1513 || !d.current_work_area_->completer().inlinePossible(
1514 currentBufferView()->cursor()))
1518 case LFUN_COMPLETION_POPUP:
1519 if (!d.current_work_area_
1520 || !d.current_work_area_->completer().popupPossible(
1521 currentBufferView()->cursor()))
1525 case LFUN_COMPLETION_COMPLETE:
1526 if (!d.current_work_area_
1527 || !d.current_work_area_->completer().inlinePossible(
1528 currentBufferView()->cursor()))
1532 case LFUN_COMPLETION_ACCEPT:
1533 if (!d.current_work_area_
1534 || (!d.current_work_area_->completer().popupVisible()
1535 && !d.current_work_area_->completer().inlineVisible()
1536 && !d.current_work_area_->completer().completionAvailable()))
1540 case LFUN_COMPLETION_CANCEL:
1541 if (!d.current_work_area_
1542 || (!d.current_work_area_->completer().popupVisible()
1543 && !d.current_work_area_->completer().inlineVisible()))
1547 case LFUN_BUFFER_ZOOM_OUT:
1548 enable = doc_buffer && lyxrc.zoom > 10;
1551 case LFUN_BUFFER_ZOOM_IN:
1552 enable = doc_buffer;
1555 case LFUN_BUFFER_NEXT:
1556 case LFUN_BUFFER_PREVIOUS:
1557 // FIXME: should we check is there is an previous or next buffer?
1559 case LFUN_BUFFER_SWITCH:
1560 // toggle on the current buffer, but do not toggle off
1561 // the other ones (is that a good idea?)
1563 && to_utf8(cmd.argument()) == doc_buffer->absFileName())
1564 flag.setOnOff(true);
1567 case LFUN_VC_REGISTER:
1568 enable = doc_buffer && !doc_buffer->lyxvc().inUse();
1570 case LFUN_VC_CHECK_IN:
1571 enable = doc_buffer && doc_buffer->lyxvc().checkInEnabled();
1573 case LFUN_VC_CHECK_OUT:
1574 enable = doc_buffer && doc_buffer->lyxvc().checkOutEnabled();
1576 case LFUN_VC_LOCKING_TOGGLE:
1577 enable = doc_buffer && !doc_buffer->isReadonly()
1578 && doc_buffer->lyxvc().lockingToggleEnabled();
1579 flag.setOnOff(enable && !doc_buffer->lyxvc().locker().empty());
1581 case LFUN_VC_REVERT:
1582 enable = doc_buffer && doc_buffer->lyxvc().inUse();
1584 case LFUN_VC_UNDO_LAST:
1585 enable = doc_buffer && doc_buffer->lyxvc().undoLastEnabled();
1587 case LFUN_VC_REPO_UPDATE:
1588 enable = doc_buffer && doc_buffer->lyxvc().inUse();
1590 case LFUN_VC_COMMAND: {
1591 if (cmd.argument().empty())
1593 if (!doc_buffer && contains(cmd.getArg(0), 'D'))
1598 case LFUN_SERVER_GOTO_FILE_ROW:
1606 flag.setEnabled(false);
1612 static FileName selectTemplateFile()
1614 FileDialog dlg(qt_("Select template file"));
1615 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1616 dlg.setButton1(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
1618 FileDialog::Result result = dlg.open(toqstr(lyxrc.template_path),
1619 QStringList(qt_("LyX Documents (*.lyx)")));
1621 if (result.first == FileDialog::Later)
1623 if (result.second.isEmpty())
1625 return FileName(fromqstr(result.second));
1629 Buffer * GuiView::loadDocument(FileName const & filename, bool tolastfiles)
1633 Buffer * newBuffer = checkAndLoadLyXFile(filename);
1636 message(_("Document not loaded."));
1641 setBuffer(newBuffer);
1643 // scroll to the position when the file was last closed
1644 if (lyxrc.use_lastfilepos) {
1645 LastFilePosSection::FilePos filepos =
1646 theSession().lastFilePos().load(filename);
1647 documentBufferView()->moveToPosition(filepos.pit, filepos.pos, 0, 0);
1651 theSession().lastFiles().add(filename);
1658 void GuiView::openDocument(string const & fname)
1660 string initpath = lyxrc.document_path;
1662 if (documentBufferView()) {
1663 string const trypath = documentBufferView()->buffer().filePath();
1664 // If directory is writeable, use this as default.
1665 if (FileName(trypath).isDirWritable())
1671 if (fname.empty()) {
1672 FileDialog dlg(qt_("Select document to open"), LFUN_FILE_OPEN);
1673 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1674 dlg.setButton2(qt_("Examples|#E#e"),
1675 toqstr(addPath(package().system_support().absFilename(), "examples")));
1677 QStringList filter(qt_("LyX Documents (*.lyx)"));
1678 filter << qt_("LyX-1.3.x Documents (*.lyx13)")
1679 << qt_("LyX-1.4.x Documents (*.lyx14)")
1680 << qt_("LyX-1.5.x Documents (*.lyx15)")
1681 << qt_("LyX-1.6.x Documents (*.lyx16)");
1682 FileDialog::Result result =
1683 dlg.open(toqstr(initpath), filter);
1685 if (result.first == FileDialog::Later)
1688 filename = fromqstr(result.second);
1690 // check selected filename
1691 if (filename.empty()) {
1692 message(_("Canceled."));
1698 // get absolute path of file and add ".lyx" to the filename if
1700 FileName const fullname =
1701 fileSearch(string(), filename, "lyx", support::may_not_exist);
1702 if (!fullname.empty())
1703 filename = fullname.absFilename();
1705 if (!fullname.onlyPath().isDirectory()) {
1706 Alert::warning(_("Invalid filename"),
1707 bformat(_("The directory in the given path\n%1$s\ndoes not exist."),
1708 from_utf8(fullname.absFilename())));
1711 // if the file doesn't exist, let the user create one
1712 if (!fullname.exists()) {
1713 // the user specifically chose this name. Believe him.
1714 Buffer * const b = newFile(filename, string(), true);
1720 docstring const disp_fn = makeDisplayPath(filename);
1721 message(bformat(_("Opening document %1$s..."), disp_fn));
1724 Buffer * buf = loadDocument(fullname);
1726 buf->updateLabels();
1728 buf->errors("Parse");
1729 str2 = bformat(_("Document %1$s opened."), disp_fn);
1730 if (buf->lyxvc().inUse())
1731 str2 += " " + from_utf8(buf->lyxvc().versionString()) +
1732 " " + _("Version control detected.");
1734 str2 = bformat(_("Could not open document %1$s"), disp_fn);
1739 // FIXME: clean that
1740 static bool import(GuiView * lv, FileName const & filename,
1741 string const & format, ErrorList & errorList)
1743 FileName const lyxfile(support::changeExtension(filename.absFilename(), ".lyx"));
1745 string loader_format;
1746 vector<string> loaders = theConverters().loaders();
1747 if (find(loaders.begin(), loaders.end(), format) == loaders.end()) {
1748 for (vector<string>::const_iterator it = loaders.begin();
1749 it != loaders.end(); ++it) {
1750 if (!theConverters().isReachable(format, *it))
1753 string const tofile =
1754 support::changeExtension(filename.absFilename(),
1755 formats.extension(*it));
1756 if (!theConverters().convert(0, filename, FileName(tofile),
1757 filename, format, *it, errorList))
1759 loader_format = *it;
1762 if (loader_format.empty()) {
1763 frontend::Alert::error(_("Couldn't import file"),
1764 bformat(_("No information for importing the format %1$s."),
1765 formats.prettyName(format)));
1769 loader_format = format;
1771 if (loader_format == "lyx") {
1772 Buffer * buf = lv->loadDocument(lyxfile);
1775 buf->updateLabels();
1777 buf->errors("Parse");
1779 Buffer * const b = newFile(lyxfile.absFilename(), string(), true);
1783 bool as_paragraphs = loader_format == "textparagraph";
1784 string filename2 = (loader_format == format) ? filename.absFilename()
1785 : support::changeExtension(filename.absFilename(),
1786 formats.extension(loader_format));
1787 lv->currentBufferView()->insertPlaintextFile(FileName(filename2),
1789 guiApp->setCurrentView(lv);
1790 lyx::dispatch(FuncRequest(LFUN_MARK_OFF));
1797 void GuiView::importDocument(string const & argument)
1800 string filename = split(argument, format, ' ');
1802 LYXERR(Debug::INFO, format << " file: " << filename);
1804 // need user interaction
1805 if (filename.empty()) {
1806 string initpath = lyxrc.document_path;
1807 if (documentBufferView()) {
1808 string const trypath = documentBufferView()->buffer().filePath();
1809 // If directory is writeable, use this as default.
1810 if (FileName(trypath).isDirWritable())
1814 docstring const text = bformat(_("Select %1$s file to import"),
1815 formats.prettyName(format));
1817 FileDialog dlg(toqstr(text), LFUN_BUFFER_IMPORT);
1818 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1819 dlg.setButton2(qt_("Examples|#E#e"),
1820 toqstr(addPath(package().system_support().absFilename(), "examples")));
1822 docstring filter = formats.prettyName(format);
1825 filter += from_utf8(formats.extension(format));
1828 FileDialog::Result result =
1829 dlg.open(toqstr(initpath), fileFilters(toqstr(filter)));
1831 if (result.first == FileDialog::Later)
1834 filename = fromqstr(result.second);
1836 // check selected filename
1837 if (filename.empty())
1838 message(_("Canceled."));
1841 if (filename.empty())
1844 // get absolute path of file
1845 FileName const fullname(support::makeAbsPath(filename));
1847 FileName const lyxfile(support::changeExtension(fullname.absFilename(), ".lyx"));
1849 // Check if the document already is open
1850 Buffer * buf = theBufferList().getBuffer(lyxfile);
1853 if (!closeBuffer()) {
1854 message(_("Canceled."));
1859 docstring const displaypath = makeDisplayPath(lyxfile.absFilename(), 30);
1861 // if the file exists already, and we didn't do
1862 // -i lyx thefile.lyx, warn
1863 if (lyxfile.exists() && fullname != lyxfile) {
1865 docstring text = bformat(_("The document %1$s already exists.\n\n"
1866 "Do you want to overwrite that document?"), displaypath);
1867 int const ret = Alert::prompt(_("Overwrite document?"),
1868 text, 0, 1, _("&Overwrite"), _("&Cancel"));
1871 message(_("Canceled."));
1876 message(bformat(_("Importing %1$s..."), displaypath));
1877 ErrorList errorList;
1878 if (import(this, fullname, format, errorList))
1879 message(_("imported."));
1881 message(_("file not imported!"));
1883 // FIXME (Abdel 12/08/06): Is there a need to display the error list here?
1887 void GuiView::newDocument(string const & filename, bool from_template)
1889 FileName initpath(lyxrc.document_path);
1890 if (documentBufferView()) {
1891 FileName const trypath(documentBufferView()->buffer().filePath());
1892 // If directory is writeable, use this as default.
1893 if (trypath.isDirWritable())
1897 string templatefile;
1898 if (from_template) {
1899 templatefile = selectTemplateFile().absFilename();
1900 if (templatefile.empty())
1905 if (filename.empty())
1906 b = newUnnamedFile(initpath, to_utf8(_("newfile")), templatefile);
1908 b = newFile(filename, templatefile, true);
1913 // If no new document could be created, it is unsure
1914 // whether there is a valid BufferView.
1915 if (currentBufferView())
1916 // Ensure the cursor is correctly positioned on screen.
1917 currentBufferView()->showCursor();
1921 void GuiView::insertLyXFile(docstring const & fname)
1923 BufferView * bv = documentBufferView();
1928 FileName filename(to_utf8(fname));
1930 if (!filename.empty()) {
1931 bv->insertLyXFile(filename);
1935 // Launch a file browser
1937 string initpath = lyxrc.document_path;
1938 string const trypath = bv->buffer().filePath();
1939 // If directory is writeable, use this as default.
1940 if (FileName(trypath).isDirWritable())
1944 FileDialog dlg(qt_("Select LyX document to insert"), LFUN_FILE_INSERT);
1945 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1946 dlg.setButton2(qt_("Examples|#E#e"),
1947 toqstr(addPath(package().system_support().absFilename(),
1950 FileDialog::Result result = dlg.open(toqstr(initpath),
1951 QStringList(qt_("LyX Documents (*.lyx)")));
1953 if (result.first == FileDialog::Later)
1957 filename.set(fromqstr(result.second));
1959 // check selected filename
1960 if (filename.empty()) {
1961 // emit message signal.
1962 message(_("Canceled."));
1966 bv->insertLyXFile(filename);
1970 void GuiView::insertPlaintextFile(docstring const & fname,
1973 BufferView * bv = documentBufferView();
1977 if (!fname.empty() && !FileName::isAbsolute(to_utf8(fname))) {
1978 message(_("Absolute filename expected."));
1983 FileName filename(to_utf8(fname));
1985 if (!filename.empty()) {
1986 bv->insertPlaintextFile(filename, asParagraph);
1990 FileDialog dlg(qt_("Select file to insert"), (asParagraph ?
1991 LFUN_FILE_INSERT_PLAINTEXT_PARA : LFUN_FILE_INSERT_PLAINTEXT));
1993 FileDialog::Result result = dlg.open(toqstr(bv->buffer().filePath()),
1994 QStringList(qt_("All Files (*)")));
1996 if (result.first == FileDialog::Later)
2000 filename.set(fromqstr(result.second));
2002 // check selected filename
2003 if (filename.empty()) {
2004 // emit message signal.
2005 message(_("Canceled."));
2009 bv->insertPlaintextFile(filename, asParagraph);
2013 bool GuiView::renameBuffer(Buffer & b, docstring const & newname)
2015 FileName fname = b.fileName();
2016 FileName const oldname = fname;
2018 if (!newname.empty()) {
2020 fname = support::makeAbsPath(to_utf8(newname), oldname.onlyPath().absFilename());
2022 // Switch to this Buffer.
2025 // No argument? Ask user through dialog.
2027 FileDialog dlg(qt_("Choose a filename to save document as"),
2028 LFUN_BUFFER_WRITE_AS);
2029 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2030 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
2032 if (!isLyXFilename(fname.absFilename()))
2033 fname.changeExtension(".lyx");
2035 FileDialog::Result result =
2036 dlg.save(toqstr(fname.onlyPath().absFilename()),
2037 QStringList(qt_("LyX Documents (*.lyx)")),
2038 toqstr(fname.onlyFileName()));
2040 if (result.first == FileDialog::Later)
2043 fname.set(fromqstr(result.second));
2048 if (!isLyXFilename(fname.absFilename()))
2049 fname.changeExtension(".lyx");
2052 if (FileName(fname).exists()) {
2053 docstring const file = makeDisplayPath(fname.absFilename(), 30);
2054 docstring text = bformat(_("The document %1$s already "
2055 "exists.\n\nDo you want to "
2056 "overwrite that document?"),
2058 int const ret = Alert::prompt(_("Overwrite document?"),
2059 text, 0, 2, _("&Overwrite"), _("&Rename"), _("&Cancel"));
2062 case 1: return renameBuffer(b, docstring());
2063 case 2: return false;
2067 FileName oldauto = b.getAutosaveFilename();
2069 // Ok, change the name of the buffer
2070 b.setFileName(fname.absFilename());
2072 bool unnamed = b.isUnnamed();
2073 b.setUnnamed(false);
2074 b.saveCheckSum(fname);
2076 // bring the autosave file with us, just in case.
2077 b.moveAutosaveFile(oldauto);
2079 if (!saveBuffer(b)) {
2080 oldauto = b.getAutosaveFilename();
2081 b.setFileName(oldname.absFilename());
2082 b.setUnnamed(unnamed);
2083 b.saveCheckSum(oldname);
2084 b.moveAutosaveFile(oldauto);
2092 bool GuiView::saveBuffer(Buffer & b)
2094 if (workArea(b) && workArea(b)->inDialogMode())
2098 return renameBuffer(b, docstring());
2101 theSession().lastFiles().add(b.fileName());
2105 // Switch to this Buffer.
2108 // FIXME: we don't tell the user *WHY* the save failed !!
2109 docstring const file = makeDisplayPath(b.absFileName(), 30);
2110 docstring text = bformat(_("The document %1$s could not be saved.\n\n"
2111 "Do you want to rename the document and "
2112 "try again?"), file);
2113 int const ret = Alert::prompt(_("Rename and save?"),
2114 text, 0, 2, _("&Rename"), _("&Retry"), _("&Cancel"));
2117 if (!renameBuffer(b, docstring()))
2126 return saveBuffer(b);
2130 bool GuiView::hideWorkArea(GuiWorkArea * wa)
2132 return closeWorkArea(wa, false);
2136 bool GuiView::closeWorkArea(GuiWorkArea * wa)
2138 Buffer & buf = wa->bufferView().buffer();
2139 return closeWorkArea(wa, !buf.parent());
2143 bool GuiView::closeBuffer()
2145 GuiWorkArea * wa = currentMainWorkArea();
2146 setCurrentWorkArea(wa);
2147 Buffer & buf = wa->bufferView().buffer();
2148 return wa && closeWorkArea(wa, !buf.parent());
2152 void GuiView::writeSession() const {
2153 GuiWorkArea const * active_wa = currentMainWorkArea();
2154 for (int i = 0; i < d.splitter_->count(); ++i) {
2155 TabWorkArea * twa = d.tabWorkArea(i);
2156 for (int j = 0; j < twa->count(); ++j) {
2157 GuiWorkArea * wa = static_cast<GuiWorkArea *>(twa->widget(j));
2158 Buffer & buf = wa->bufferView().buffer();
2159 theSession().lastOpened().add(buf.fileName(), wa == active_wa);
2165 bool GuiView::closeBufferAll()
2167 // Close the workareas in all other views
2168 QList<int> const ids = guiApp->viewIds();
2169 for (int i = 0; i != ids.size(); ++i) {
2170 if (id_ != ids[i] && !guiApp->view(ids[i]).closeWorkAreaAll())
2174 // Close our own workareas
2175 if (!closeWorkAreaAll())
2178 // Now close the hidden buffers. We prevent hidden buffers from being
2179 // dirty, so we can just close them.
2180 theBufferList().closeAll();
2185 bool GuiView::closeWorkAreaAll()
2187 setCurrentWorkArea(currentMainWorkArea());
2189 // We might be in a situation that there is still a tabWorkArea, but
2190 // there are no tabs anymore. This can happen when we get here after a
2191 // TabWorkArea::lastWorkAreaRemoved() signal. Therefore we count how
2192 // many TabWorkArea's have no documents anymore.
2195 // We have to call count() each time, because it can happen that
2196 // more than one splitter will disappear in one iteration (bug 5998).
2197 for (; d.splitter_->count() > empty_twa; ) {
2198 TabWorkArea * twa = d.tabWorkArea(empty_twa);
2200 if (twa->count() == 0)
2203 setCurrentWorkArea(twa->currentWorkArea());
2204 if (!closeTabWorkArea(twa))
2212 bool GuiView::closeWorkArea(GuiWorkArea * wa, bool close_buffer)
2217 Buffer & buf = wa->bufferView().buffer();
2220 return closeBuffer(buf);
2222 if (!inMultiTabs(wa))
2223 if (!saveBufferIfNeeded(buf, true))
2231 bool GuiView::closeBuffer(Buffer & buf)
2233 // If we are in a close_event all children will be closed in some time,
2234 // so no need to do it here. This will ensure that the children end up
2235 // in the session file in the correct order. If we close the master
2236 // buffer, we can close or release the child buffers here too.
2238 vector<Buffer *> clist = buf.getChildren(false);
2239 for (vector<Buffer *>::const_iterator it = clist.begin();
2240 it != clist.end(); ++it) {
2241 // If a child is dirty, do not close
2242 // without user intervention
2243 //FIXME: should we look in other tabworkareas?
2244 Buffer * child_buf = *it;
2245 GuiWorkArea * child_wa = workArea(*child_buf);
2247 if (!closeWorkArea(child_wa, true))
2250 theBufferList().releaseChild(&buf, child_buf);
2253 // goto bookmark to update bookmark pit.
2254 //FIXME: we should update only the bookmarks related to this buffer!
2255 LYXERR(Debug::DEBUG, "GuiView::closeBuffer()");
2256 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
2257 theLyXFunc().gotoBookmark(i+1, false, false);
2259 if (saveBufferIfNeeded(buf, false)) {
2260 theBufferList().release(&buf);
2267 bool GuiView::closeTabWorkArea(TabWorkArea * twa)
2269 while (twa == d.currentTabWorkArea()) {
2270 twa->setCurrentIndex(twa->count()-1);
2272 GuiWorkArea * wa = twa->currentWorkArea();
2273 Buffer & b = wa->bufferView().buffer();
2275 // We only want to close the buffer if the same buffer is not visible
2276 // in another view, and if this is not a child and if we are closing
2277 // a view (not a tabgroup).
2278 bool const close_buffer =
2279 !inMultiViews(wa) && !b.parent() && closing_;
2281 if (!closeWorkArea(wa, close_buffer))
2288 bool GuiView::saveBufferIfNeeded(Buffer & buf, bool hiding)
2290 if (buf.isClean() || buf.paragraphs().empty())
2293 // Switch to this Buffer.
2298 if (buf.isUnnamed())
2299 file = from_utf8(buf.fileName().onlyFileName());
2301 file = buf.fileName().displayName(30);
2303 // Bring this window to top before asking questions.
2308 if (hiding && buf.isUnnamed()) {
2309 docstring const text = bformat(_("The document %1$s has not been "
2310 "saved yet.\n\nDo you want to save "
2311 "the document?"), file);
2312 ret = Alert::prompt(_("Save new document?"),
2313 text, 0, 1, _("&Save"), _("&Cancel"));
2317 docstring const text = bformat(_("The document %1$s has unsaved changes."
2318 "\n\nDo you want to save the document or discard the changes?"), file);
2319 ret = Alert::prompt(_("Save changed document?"),
2320 text, 0, 2, _("&Save"), _("&Discard"), _("&Cancel"));
2325 if (!saveBuffer(buf))
2329 // if we crash after this we could
2330 // have no autosave file but I guess
2331 // this is really improbable (Jug)
2332 buf.removeAutosaveFile();
2334 // revert all changes
2345 bool GuiView::inMultiTabs(GuiWorkArea * wa)
2347 Buffer & buf = wa->bufferView().buffer();
2349 for (int i = 0; i != d.splitter_->count(); ++i) {
2350 GuiWorkArea * wa_ = d.tabWorkArea(i)->workArea(buf);
2351 if (wa_ && wa_ != wa)
2354 return inMultiViews(wa);
2358 bool GuiView::inMultiViews(GuiWorkArea * wa)
2360 QList<int> const ids = guiApp->viewIds();
2361 Buffer & buf = wa->bufferView().buffer();
2364 for (int i = 0; i != ids.size() && found_twa <= 1; ++i) {
2368 if (guiApp->view(ids[i]).workArea(buf))
2375 void GuiView::gotoNextOrPreviousBuffer(NextOrPrevious np)
2377 Buffer * const curbuf = documentBufferView()
2378 ? &documentBufferView()->buffer() : 0;
2379 Buffer * nextbuf = curbuf;
2381 if (np == NEXTBUFFER)
2382 nextbuf = theBufferList().next(nextbuf);
2384 nextbuf = theBufferList().previous(nextbuf);
2385 if (nextbuf == curbuf)
2391 if (workArea(*nextbuf))
2398 /// make sure the document is saved
2399 static bool ensureBufferClean(Buffer * buffer)
2401 LASSERT(buffer, return false);
2402 if (buffer->isClean() && !buffer->isUnnamed())
2405 docstring const file = buffer->fileName().displayName(30);
2408 if (!buffer->isUnnamed()) {
2409 text = bformat(_("The document %1$s has unsaved "
2410 "changes.\n\nDo you want to save "
2411 "the document?"), file);
2412 title = _("Save changed document?");
2415 text = bformat(_("The document %1$s has not been "
2416 "saved yet.\n\nDo you want to save "
2417 "the document?"), file);
2418 title = _("Save new document?");
2420 int const ret = Alert::prompt(title, text, 0, 1, _("&Save"), _("&Cancel"));
2423 dispatch(FuncRequest(LFUN_BUFFER_WRITE));
2425 return buffer->isClean() && !buffer->isUnnamed();
2429 void GuiView::reloadBuffer()
2431 Buffer * buf = &documentBufferView()->buffer();
2436 void GuiView::checkExternallyModifiedBuffers()
2438 BufferList::iterator bit = theBufferList().begin();
2439 BufferList::iterator const bend = theBufferList().end();
2440 for (; bit != bend; ++bit) {
2441 if ((*bit)->fileName().exists()
2442 && (*bit)->isExternallyModified(Buffer::checksum_method)) {
2443 docstring text = bformat(_("Document \n%1$s\n has been externally modified."
2444 " Reload now? Any local changes will be lost."),
2445 from_utf8((*bit)->absFileName()));
2446 int const ret = Alert::prompt(_("Reload externally changed document?"),
2447 text, 0, 1, _("&Reload"), _("&Cancel"));
2455 void GuiView::dispatchVC(FuncRequest const & cmd)
2457 // message for statusbar
2459 Buffer * buffer = documentBufferView()
2460 ? &(documentBufferView()->buffer()) : 0;
2462 switch (cmd.action) {
2463 case LFUN_VC_REGISTER:
2464 if (!buffer || !ensureBufferClean(buffer))
2466 if (!buffer->lyxvc().inUse()) {
2467 if (buffer->lyxvc().registrer())
2472 case LFUN_VC_CHECK_IN:
2473 if (!buffer || !ensureBufferClean(buffer))
2475 if (buffer->lyxvc().inUse() && !buffer->isReadonly()) {
2476 msg = buffer->lyxvc().checkIn();
2482 case LFUN_VC_CHECK_OUT:
2483 if (!buffer || !ensureBufferClean(buffer))
2485 if (buffer->lyxvc().inUse()) {
2486 msg = buffer->lyxvc().checkOut();
2491 case LFUN_VC_LOCKING_TOGGLE:
2492 LASSERT(buffer, return);
2493 if (!ensureBufferClean(buffer) || buffer->isReadonly())
2495 if (buffer->lyxvc().inUse()) {
2496 string res = buffer->lyxvc().lockingToggle();
2498 frontend::Alert::error(_("Revision control error."),
2499 _("Error when setting the locking property."));
2507 case LFUN_VC_REVERT:
2508 LASSERT(buffer, return);
2509 buffer->lyxvc().revert();
2513 case LFUN_VC_UNDO_LAST:
2514 LASSERT(buffer, return);
2515 buffer->lyxvc().undoLast();
2519 case LFUN_VC_REPO_UPDATE:
2520 LASSERT(buffer, return);
2521 if (ensureBufferClean(buffer)) {
2522 msg = buffer->lyxvc().repoUpdate();
2523 checkExternallyModifiedBuffers();
2527 case LFUN_VC_COMMAND: {
2528 string flag = cmd.getArg(0);
2529 if (buffer && contains(flag, 'R') && !ensureBufferClean(buffer))
2532 if (contains(flag, 'M')) {
2533 if (!Alert::askForText(message, _("LyX VC: Log Message")))
2536 string path = cmd.getArg(1);
2537 if (contains(path, "$$p") && buffer)
2538 path = subst(path, "$$p", buffer->filePath());
2539 LYXERR(Debug::LYXVC, "Directory: " << path);
2541 if (!pp.isReadableDirectory()) {
2542 lyxerr << _("Directory is not accessible.") << endl;
2545 support::PathChanger p(pp);
2547 string command = cmd.getArg(2);
2548 if (command.empty())
2551 command = subst(command, "$$i", buffer->absFileName());
2552 command = subst(command, "$$p", buffer->filePath());
2554 command = subst(command, "$$m", to_utf8(message));
2555 LYXERR(Debug::LYXVC, "Command: " << command);
2557 one.startscript(Systemcall::Wait, command);
2561 if (contains(flag, 'I'))
2562 buffer->markDirty();
2563 if (contains(flag, 'R'))
2573 message(from_utf8(msg));
2577 void GuiView::openChildDocument(string const & fname)
2579 LASSERT(documentBufferView(), return);
2580 Buffer & buffer = documentBufferView()->buffer();
2581 FileName const filename = support::makeAbsPath(fname, buffer.filePath());
2582 documentBufferView()->saveBookmark(false);
2584 bool parsed = false;
2585 if (theBufferList().exists(filename)) {
2586 child = theBufferList().getBuffer(filename);
2588 message(bformat(_("Opening child document %1$s..."),
2589 makeDisplayPath(filename.absFilename())));
2590 child = loadDocument(filename, false);
2596 // Set the parent name of the child document.
2597 // This makes insertion of citations and references in the child work,
2598 // when the target is in the parent or another child document.
2599 child->setParent(&buffer);
2600 child->masterBuffer()->updateLabels();
2603 child->errors("Parse");
2607 bool GuiView::goToFileRow(string const & argument)
2611 size_t i = argument.find_last_of(' ');
2612 if (i != string::npos) {
2613 file_name = os::internal_path(trim(argument.substr(0, i)));
2614 istringstream is(argument.substr(i + 1));
2619 if (i == string::npos) {
2620 LYXERR0("Wrong argument: " << argument);
2624 string const abstmp = package().temp_dir().absFilename();
2625 string const realtmp = package().temp_dir().realPath();
2626 // We have to use os::path_prefix_is() here, instead of
2627 // simply prefixIs(), because the file name comes from
2628 // an external application and may need case adjustment.
2629 if (os::path_prefix_is(file_name, abstmp, os::CASE_ADJUSTED)
2630 || os::path_prefix_is(file_name, realtmp, os::CASE_ADJUSTED)) {
2631 // Needed by inverse dvi search. If it is a file
2632 // in tmpdir, call the apropriated function.
2633 // If tmpdir is a symlink, we may have the real
2634 // path passed back, so we correct for that.
2635 if (!prefixIs(file_name, abstmp))
2636 file_name = subst(file_name, realtmp, abstmp);
2637 buf = theBufferList().getBufferFromTmp(file_name);
2639 // Must replace extension of the file to be .lyx
2640 // and get full path
2641 FileName const s = fileSearch(string(),
2642 support::changeExtension(file_name, ".lyx"), "lyx");
2643 // Either change buffer or load the file
2644 if (theBufferList().exists(s))
2645 buf = theBufferList().getBuffer(s);
2646 else if (s.exists()) {
2647 buf = loadDocument(s);
2648 buf->updateLabels();
2649 buf->errors("Parse");
2652 _("File does not exist: %1$s"),
2653 makeDisplayPath(file_name)));
2658 documentBufferView()->setCursorFromRow(row);
2663 #if (QT_VERSION >= 0x040400)
2664 static docstring exportAndDestroy(Buffer * buffer, string const & format)
2666 bool const update_unincluded =
2667 buffer->params().maintain_unincluded_children
2668 && !buffer->params().getIncludedChildren().empty();
2669 bool const success = buffer->doExport(format, true, update_unincluded);
2672 ? bformat(_("Successful export to format: %1$s"), from_utf8(format))
2673 : bformat(_("Error exporting to format: %1$s"), from_utf8(format));
2677 static docstring previewAndDestroy(Buffer * buffer, string const & format)
2679 bool const update_unincluded =
2680 buffer->params().maintain_unincluded_children
2681 && !buffer->params().getIncludedChildren().empty();
2682 bool const success = buffer->preview(format, update_unincluded);
2685 ? bformat(_("Successful preview of format: %1$s"), from_utf8(format))
2686 : bformat(_("Error previewing format: %1$s"), from_utf8(format));
2691 bool GuiView::dispatch(FuncRequest const & cmd)
2693 BufferView * bv = currentBufferView();
2694 // By default we won't need any update.
2696 bv->cursor().updateFlags(Update::None);
2698 Buffer * doc_buffer = documentBufferView()
2699 ? &(documentBufferView()->buffer()) : 0;
2701 bool dispatched = true;
2703 if (cmd.origin == FuncRequest::TOC) {
2704 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
2705 toc->doDispatch(bv->cursor(), cmd);
2709 string const argument = to_utf8(cmd.argument());
2711 switch(cmd.action) {
2712 case LFUN_BUFFER_CHILD_OPEN:
2713 openChildDocument(to_utf8(cmd.argument()));
2716 case LFUN_BUFFER_IMPORT:
2717 importDocument(to_utf8(cmd.argument()));
2720 case LFUN_BUFFER_EXPORT: {
2723 if (cmd.argument() == "custom") {
2724 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "sendto"));
2727 if (doc_buffer->doExport(argument, false)) {
2728 message(bformat(_("Error exporting to format: %1$s."),
2734 case LFUN_BUFFER_UPDATE: {
2737 string format = argument;
2738 if (argument.empty())
2739 format = doc_buffer->getDefaultOutputFormat();
2740 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
2741 d.progress_->clearMessages();
2742 message(_("Exporting ..."));
2743 QFuture<docstring> f = QtConcurrent::run(exportAndDestroy,
2744 doc_buffer->clone(), format);
2745 d.setPreviewFuture(f);
2747 bool const update_unincluded =
2748 doc_buffer->params().maintain_unincluded_children
2749 && !doc_buffer->params().getIncludedChildren().empty();
2750 doc_buffer->doExport(format, true, update_unincluded);
2754 case LFUN_BUFFER_VIEW: {
2757 string format = argument;
2758 if (argument.empty())
2759 format = doc_buffer->getDefaultOutputFormat();
2760 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
2761 d.progress_->clearMessages();
2762 message(_("Previewing ..."));
2763 QFuture<docstring> f = QtConcurrent::run(previewAndDestroy,
2764 doc_buffer->clone(), format);
2765 d.setPreviewFuture(f);
2767 bool const update_unincluded =
2768 doc_buffer->params().maintain_unincluded_children
2769 && !doc_buffer->params().getIncludedChildren().empty();
2770 doc_buffer->preview(format, update_unincluded);
2774 case LFUN_MASTER_BUFFER_UPDATE: {
2777 string format = argument;
2778 Buffer const * master = doc_buffer->masterBuffer();
2779 if (argument.empty())
2780 format = master->getDefaultOutputFormat();
2781 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
2782 QFuture<docstring> f = QtConcurrent::run(exportAndDestroy,
2783 master->clone(), format);
2784 d.setPreviewFuture(f);
2786 bool const update_unincluded =
2787 master->params().maintain_unincluded_children
2788 && !master->params().getIncludedChildren().empty();
2789 master->doExport(format, true);
2793 case LFUN_MASTER_BUFFER_VIEW: {
2794 string format = argument;
2795 Buffer const * master = doc_buffer->masterBuffer();
2796 if (argument.empty())
2797 format = master->getDefaultOutputFormat();
2798 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
2799 QFuture<docstring> f = QtConcurrent::run(previewAndDestroy,
2800 master->clone(), format);
2801 d.setPreviewFuture(f);
2803 master->preview(format);
2807 case LFUN_BUFFER_SWITCH:
2808 if (FileName::isAbsolute(to_utf8(cmd.argument()))) {
2810 theBufferList().getBuffer(FileName(to_utf8(cmd.argument())));
2814 message(_("Document not loaded"));
2818 case LFUN_BUFFER_NEXT:
2819 gotoNextOrPreviousBuffer(NEXTBUFFER);
2822 case LFUN_BUFFER_PREVIOUS:
2823 gotoNextOrPreviousBuffer(PREVBUFFER);
2826 case LFUN_COMMAND_EXECUTE: {
2827 bool const show_it = cmd.argument() != "off";
2828 // FIXME: this is a hack, "minibuffer" should not be
2830 if (GuiToolbar * t = toolbar("minibuffer")) {
2831 t->setVisible(show_it);
2832 if (show_it && t->commandBuffer())
2833 t->commandBuffer()->setFocus();
2837 case LFUN_DROP_LAYOUTS_CHOICE:
2838 d.layout_->showPopup();
2841 case LFUN_MENU_OPEN:
2842 if (QMenu * menu = guiApp->menus().menu(toqstr(cmd.argument()), *this))
2843 menu->exec(QCursor::pos());
2846 case LFUN_FILE_INSERT:
2847 insertLyXFile(cmd.argument());
2849 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
2850 insertPlaintextFile(cmd.argument(), true);
2853 case LFUN_FILE_INSERT_PLAINTEXT:
2854 insertPlaintextFile(cmd.argument(), false);
2857 case LFUN_BUFFER_RELOAD: {
2858 LASSERT(doc_buffer, break);
2859 docstring const file = makeDisplayPath(doc_buffer->absFileName(), 20);
2860 docstring text = bformat(_("Any changes will be lost. Are you sure "
2861 "you want to revert to the saved version of the document %1$s?"), file);
2862 int const ret = Alert::prompt(_("Revert to saved document?"),
2863 text, 1, 1, _("&Revert"), _("&Cancel"));
2866 doc_buffer->markClean();
2872 case LFUN_BUFFER_WRITE:
2873 LASSERT(doc_buffer, break);
2874 saveBuffer(*doc_buffer);
2877 case LFUN_BUFFER_WRITE_AS:
2878 LASSERT(doc_buffer, break);
2879 renameBuffer(*doc_buffer, cmd.argument());
2882 case LFUN_BUFFER_WRITE_ALL: {
2883 Buffer * first = theBufferList().first();
2886 message(_("Saving all documents..."));
2887 // We cannot use a for loop as the buffer list cycles.
2890 if (!b->isClean()) {
2892 LYXERR(Debug::ACTION, "Saved " << b->absFileName());
2894 b = theBufferList().next(b);
2895 } while (b != first);
2896 message(_("All documents saved."));
2900 case LFUN_BUFFER_CLOSE:
2904 case LFUN_BUFFER_CLOSE_ALL:
2908 case LFUN_TOOLBAR_TOGGLE: {
2909 string const name = cmd.getArg(0);
2910 if (GuiToolbar * t = toolbar(name))
2915 case LFUN_DIALOG_UPDATE: {
2916 string const name = to_utf8(cmd.argument());
2917 if (currentBufferView()) {
2918 Inset * inset = currentBufferView()->editedInset(name);
2919 // Can only update a dialog connected to an existing inset
2922 // FIXME: get rid of this indirection; GuiView ask the inset
2923 // if he is kind enough to update itself...
2924 FuncRequest fr(LFUN_INSET_DIALOG_UPDATE, cmd.argument());
2925 inset->dispatch(currentBufferView()->cursor(), fr);
2926 } else if (name == "paragraph") {
2927 lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
2928 } else if (name == "prefs" || name == "document") {
2929 updateDialog(name, string());
2934 case LFUN_DIALOG_TOGGLE: {
2935 if (isDialogVisible(cmd.getArg(0)))
2936 dispatch(FuncRequest(LFUN_DIALOG_HIDE, cmd.argument()));
2938 dispatch(FuncRequest(LFUN_DIALOG_SHOW, cmd.argument()));
2942 case LFUN_DIALOG_DISCONNECT_INSET:
2943 disconnectDialog(to_utf8(cmd.argument()));
2946 case LFUN_DIALOG_HIDE: {
2947 guiApp->hideDialogs(to_utf8(cmd.argument()), 0);
2951 case LFUN_DIALOG_SHOW: {
2952 string const name = cmd.getArg(0);
2953 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
2955 if (name == "character") {
2956 data = freefont2string();
2958 showDialog("character", data);
2959 } else if (name == "latexlog") {
2960 Buffer::LogType type;
2961 string const logfile = doc_buffer->logName(&type);
2963 case Buffer::latexlog:
2966 case Buffer::buildlog:
2970 data += Lexer::quoteString(logfile);
2971 showDialog("log", data);
2972 } else if (name == "vclog") {
2973 string const data = "vc " +
2974 Lexer::quoteString(doc_buffer->lyxvc().getLogFile());
2975 showDialog("log", data);
2976 } else if (name == "symbols") {
2977 data = bv->cursor().getEncoding()->name();
2979 showDialog("symbols", data);
2981 } else if (name == "prefs" && isFullScreen()) {
2982 FuncRequest fr(LFUN_INSET_INSERT, "fullscreen");
2984 showDialog("prefs", data);
2986 showDialog(name, data);
2991 message(cmd.argument());
2994 case LFUN_UI_TOGGLE:
2996 // Make sure the keyboard focus stays in the work area.
3000 case LFUN_SPLIT_VIEW: {
3001 LASSERT(doc_buffer, break);
3002 string const orientation = cmd.getArg(0);
3003 d.splitter_->setOrientation(orientation == "vertical"
3004 ? Qt::Vertical : Qt::Horizontal);
3005 TabWorkArea * twa = addTabWorkArea();
3006 GuiWorkArea * wa = twa->addWorkArea(*doc_buffer, *this);
3007 setCurrentWorkArea(wa);
3010 case LFUN_CLOSE_TAB_GROUP:
3011 if (TabWorkArea * twa = d.currentTabWorkArea()) {
3012 closeTabWorkArea(twa);
3013 d.current_work_area_ = 0;
3014 twa = d.currentTabWorkArea();
3015 // Switch to the next GuiWorkArea in the found TabWorkArea.
3017 // Make sure the work area is up to date.
3018 setCurrentWorkArea(twa->currentWorkArea());
3020 setCurrentWorkArea(0);
3025 case LFUN_COMPLETION_INLINE:
3026 if (d.current_work_area_)
3027 d.current_work_area_->completer().showInline();
3030 case LFUN_COMPLETION_POPUP:
3031 if (d.current_work_area_)
3032 d.current_work_area_->completer().showPopup();
3036 case LFUN_COMPLETION_COMPLETE:
3037 if (d.current_work_area_)
3038 d.current_work_area_->completer().tab();
3041 case LFUN_COMPLETION_CANCEL:
3042 if (d.current_work_area_) {
3043 if (d.current_work_area_->completer().popupVisible())
3044 d.current_work_area_->completer().hidePopup();
3046 d.current_work_area_->completer().hideInline();
3050 case LFUN_COMPLETION_ACCEPT:
3051 if (d.current_work_area_)
3052 d.current_work_area_->completer().activate();
3055 case LFUN_BUFFER_ZOOM_IN:
3056 case LFUN_BUFFER_ZOOM_OUT:
3057 if (cmd.argument().empty()) {
3058 if (cmd.action == LFUN_BUFFER_ZOOM_IN)
3063 lyxrc.zoom += convert<int>(cmd.argument());
3065 if (lyxrc.zoom < 10)
3068 // The global QPixmapCache is used in GuiPainter to cache text
3069 // painting so we must reset it.
3070 QPixmapCache::clear();
3071 guiApp->fontLoader().update();
3072 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
3075 case LFUN_VC_REGISTER:
3076 case LFUN_VC_CHECK_IN:
3077 case LFUN_VC_CHECK_OUT:
3078 case LFUN_VC_REPO_UPDATE:
3079 case LFUN_VC_LOCKING_TOGGLE:
3080 case LFUN_VC_REVERT:
3081 case LFUN_VC_UNDO_LAST:
3082 case LFUN_VC_COMMAND:
3086 case LFUN_SERVER_GOTO_FILE_ROW:
3087 goToFileRow(to_utf8(cmd.argument()));
3095 // Part of automatic menu appearance feature.
3096 if (isFullScreen()) {
3097 if (menuBar()->isVisible() && lyxrc.full_screen_menubar)
3099 if (statusBar()->isVisible())
3100 statusBar()->hide();
3107 void GuiView::lfunUiToggle(FuncRequest const & cmd)
3109 string const arg = cmd.getArg(0);
3110 if (arg == "scrollbar") {
3111 // hide() is of no help
3112 if (d.current_work_area_->verticalScrollBarPolicy() ==
3113 Qt::ScrollBarAlwaysOff)
3115 d.current_work_area_->setVerticalScrollBarPolicy(
3116 Qt::ScrollBarAsNeeded);
3118 d.current_work_area_->setVerticalScrollBarPolicy(
3119 Qt::ScrollBarAlwaysOff);
3122 if (arg == "statusbar") {
3123 statusBar()->setVisible(!statusBar()->isVisible());
3126 if (arg == "menubar") {
3127 menuBar()->setVisible(!menuBar()->isVisible());
3130 #if QT_VERSION >= 0x040300
3131 if (arg == "frame") {
3133 getContentsMargins(&l, &t, &r, &b);
3134 //are the frames in default state?
3135 d.current_work_area_->setFrameStyle(QFrame::NoFrame);
3137 setContentsMargins(-2, -2, -2, -2);
3139 setContentsMargins(0, 0, 0, 0);
3144 if (arg == "fullscreen") {
3149 message(bformat("LFUN_UI_TOGGLE " + _("%1$s unknown command!"), from_utf8(arg)));
3153 void GuiView::toggleFullScreen()
3155 if (isFullScreen()) {
3156 for (int i = 0; i != d.splitter_->count(); ++i)
3157 d.tabWorkArea(i)->setFullScreen(false);
3158 #if QT_VERSION >= 0x040300
3159 setContentsMargins(0, 0, 0, 0);
3161 setWindowState(windowState() ^ Qt::WindowFullScreen);
3164 statusBar()->show();
3167 hideDialogs("prefs", 0);
3168 for (int i = 0; i != d.splitter_->count(); ++i)
3169 d.tabWorkArea(i)->setFullScreen(true);
3170 #if QT_VERSION >= 0x040300
3171 setContentsMargins(-2, -2, -2, -2);
3174 setWindowState(windowState() ^ Qt::WindowFullScreen);
3175 statusBar()->hide();
3176 if (lyxrc.full_screen_menubar)
3178 if (lyxrc.full_screen_toolbars) {
3179 ToolbarMap::iterator end = d.toolbars_.end();
3180 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
3185 // give dialogs like the TOC a chance to adapt
3190 Buffer const * GuiView::updateInset(Inset const * inset)
3192 if (!d.current_work_area_)
3196 d.current_work_area_->scheduleRedraw();
3198 return &d.current_work_area_->bufferView().buffer();
3202 void GuiView::restartCursor()
3204 /* When we move around, or type, it's nice to be able to see
3205 * the cursor immediately after the keypress.
3207 if (d.current_work_area_)
3208 d.current_work_area_->startBlinkingCursor();
3210 // Take this occasion to update the other GUI elements.
3216 void GuiView::updateCompletion(Cursor & cur, bool start, bool keep)
3218 if (d.current_work_area_)
3219 d.current_work_area_->completer().updateVisibility(cur, start, keep);
3224 // This list should be kept in sync with the list of insets in
3225 // src/insets/Inset.cpp. I.e., if a dialog goes with an inset, the
3226 // dialog should have the same name as the inset.
3227 // Changes should be also recorded in LFUN_DIALOG_SHOW doxygen
3228 // docs in LyXAction.cpp.
3230 char const * const dialognames[] = {
3231 "aboutlyx", "bibitem", "bibtex", "box", "branch", "changes", "character",
3232 "citation", "compare", "document", "errorlist", "ert", "external", "file",
3233 "findreplace", "findreplaceadv", "float", "graphics", "href", "include",
3234 "index", "index_print", "info", "listings", "label", "log", "mathdelimiter",
3235 "mathmatrix", "mathspace", "nomenclature", "nomencl_print", "note",
3236 "paragraph", "phantom", "prefs", "print", "ref", "sendto", "space",
3237 "spellchecker", "symbols", "tabular", "tabularcreate", "thesaurus", "texinfo",
3238 "toc", "view-source", "vspace", "wrap", "progress"};
3240 char const * const * const end_dialognames =
3241 dialognames + (sizeof(dialognames) / sizeof(char *));
3245 cmpCStr(char const * name) : name_(name) {}
3246 bool operator()(char const * other) {
3247 return strcmp(other, name_) == 0;
3254 bool isValidName(string const & name)
3256 return find_if(dialognames, end_dialognames,
3257 cmpCStr(name.c_str())) != end_dialognames;
3263 void GuiView::resetDialogs()
3265 // Make sure that no LFUN uses any LyXView.
3266 guiApp->setCurrentView(0);
3269 constructToolbars();
3270 guiApp->menus().fillMenuBar(menuBar(), this, false);
3271 d.layout_->updateContents(true);
3272 // Now update controls with current buffer.
3273 guiApp->setCurrentView(this);
3279 Dialog * GuiView::findOrBuild(string const & name, bool hide_it)
3281 if (!isValidName(name))
3284 map<string, DialogPtr>::iterator it = d.dialogs_.find(name);
3286 if (it != d.dialogs_.end()) {
3288 it->second->hideView();
3289 return it->second.get();
3292 Dialog * dialog = build(name);
3293 d.dialogs_[name].reset(dialog);
3294 if (lyxrc.allow_geometry_session)
3295 dialog->restoreSession();
3302 void GuiView::showDialog(string const & name, string const & data,
3305 triggerShowDialog(toqstr(name), toqstr(data), inset);
3309 void GuiView::doShowDialog(QString const & qname, QString const & qdata,
3315 const string name = fromqstr(qname);
3316 const string data = fromqstr(qdata);
3320 Dialog * dialog = findOrBuild(name, false);
3322 dialog->showData(data);
3323 if (inset && currentBufferView())
3324 currentBufferView()->editInset(name, inset);
3327 catch (ExceptionMessage const & ex) {
3335 bool GuiView::isDialogVisible(string const & name) const
3337 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3338 if (it == d.dialogs_.end())
3340 return it->second.get()->isVisibleView() && !it->second.get()->isClosing();
3344 void GuiView::hideDialog(string const & name, Inset * inset)
3346 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3347 if (it == d.dialogs_.end())
3350 if (inset && currentBufferView()
3351 && inset != currentBufferView()->editedInset(name))
3354 Dialog * const dialog = it->second.get();
3355 if (dialog->isVisibleView())
3357 if (currentBufferView())
3358 currentBufferView()->editInset(name, 0);
3362 void GuiView::disconnectDialog(string const & name)
3364 if (!isValidName(name))
3366 if (currentBufferView())
3367 currentBufferView()->editInset(name, 0);
3371 void GuiView::hideAll() const
3373 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
3374 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3376 for(; it != end; ++it)
3377 it->second->hideView();
3381 void GuiView::updateDialogs()
3383 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
3384 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3386 for(; it != end; ++it) {
3387 Dialog * dialog = it->second.get();
3389 if (dialog->isBufferDependent() && !documentBufferView())
3390 hideDialog(fromqstr(dialog->name()), 0);
3391 else if (dialog->isVisibleView())
3392 dialog->checkStatus();
3400 // will be replaced by a proper factory...
3401 Dialog * createGuiAbout(GuiView & lv);
3402 Dialog * createGuiBibitem(GuiView & lv);
3403 Dialog * createGuiBibtex(GuiView & lv);
3404 Dialog * createGuiBox(GuiView & lv);
3405 Dialog * createGuiBranch(GuiView & lv);
3406 Dialog * createGuiChanges(GuiView & lv);
3407 Dialog * createGuiCharacter(GuiView & lv);
3408 Dialog * createGuiCitation(GuiView & lv);
3409 Dialog * createGuiCompare(GuiView & lv);
3410 Dialog * createGuiDelimiter(GuiView & lv);
3411 Dialog * createGuiDocument(GuiView & lv);
3412 Dialog * createGuiErrorList(GuiView & lv);
3413 Dialog * createGuiERT(GuiView & lv);
3414 Dialog * createGuiExternal(GuiView & lv);
3415 Dialog * createGuiFloat(GuiView & lv);
3416 Dialog * createGuiGraphics(GuiView & lv);
3417 Dialog * createGuiInclude(GuiView & lv);
3418 Dialog * createGuiIndex(GuiView & lv);
3419 Dialog * createGuiInfo(GuiView & lv);
3420 Dialog * createGuiLabel(GuiView & lv);
3421 Dialog * createGuiListings(GuiView & lv);
3422 Dialog * createGuiLog(GuiView & lv);
3423 Dialog * createGuiMathHSpace(GuiView & lv);
3424 Dialog * createGuiMathMatrix(GuiView & lv);
3425 Dialog * createGuiNomenclature(GuiView & lv);
3426 Dialog * createGuiNote(GuiView & lv);
3427 Dialog * createGuiParagraph(GuiView & lv);
3428 Dialog * createGuiPhantom(GuiView & lv);
3429 Dialog * createGuiPreferences(GuiView & lv);
3430 Dialog * createGuiPrint(GuiView & lv);
3431 Dialog * createGuiPrintindex(GuiView & lv);
3432 Dialog * createGuiPrintNomencl(GuiView & lv);
3433 Dialog * createGuiRef(GuiView & lv);
3434 Dialog * createGuiSearch(GuiView & lv);
3435 Dialog * createGuiSearchAdv(GuiView & lv);
3436 Dialog * createGuiSendTo(GuiView & lv);
3437 Dialog * createGuiShowFile(GuiView & lv);
3438 Dialog * createGuiSpellchecker(GuiView & lv);
3439 Dialog * createGuiSymbols(GuiView & lv);
3440 Dialog * createGuiTabularCreate(GuiView & lv);
3441 Dialog * createGuiTabular(GuiView & lv);
3442 Dialog * createGuiTexInfo(GuiView & lv);
3443 Dialog * createGuiTextHSpace(GuiView & lv);
3444 Dialog * createGuiToc(GuiView & lv);
3445 Dialog * createGuiThesaurus(GuiView & lv);
3446 Dialog * createGuiHyperlink(GuiView & lv);
3447 Dialog * createGuiVSpace(GuiView & lv);
3448 Dialog * createGuiViewSource(GuiView & lv);
3449 Dialog * createGuiWrap(GuiView & lv);
3450 Dialog * createGuiProgressView(GuiView & lv);
3454 Dialog * GuiView::build(string const & name)
3456 LASSERT(isValidName(name), return 0);
3458 if (name == "aboutlyx")
3459 return createGuiAbout(*this);
3460 if (name == "bibitem")
3461 return createGuiBibitem(*this);
3462 if (name == "bibtex")
3463 return createGuiBibtex(*this);
3465 return createGuiBox(*this);
3466 if (name == "branch")
3467 return createGuiBranch(*this);
3468 if (name == "changes")
3469 return createGuiChanges(*this);
3470 if (name == "character")
3471 return createGuiCharacter(*this);
3472 if (name == "citation")
3473 return createGuiCitation(*this);
3474 if (name == "compare")
3475 return createGuiCompare(*this);
3476 if (name == "document")
3477 return createGuiDocument(*this);
3478 if (name == "errorlist")
3479 return createGuiErrorList(*this);
3481 return createGuiERT(*this);
3482 if (name == "external")
3483 return createGuiExternal(*this);
3485 return createGuiShowFile(*this);
3486 if (name == "findreplace")
3487 return createGuiSearch(*this);
3488 if (name == "findreplaceadv")
3489 return createGuiSearchAdv(*this);
3490 if (name == "float")
3491 return createGuiFloat(*this);
3492 if (name == "graphics")
3493 return createGuiGraphics(*this);
3495 return createGuiHyperlink(*this);
3496 if (name == "include")
3497 return createGuiInclude(*this);
3498 if (name == "index")
3499 return createGuiIndex(*this);
3500 if (name == "index_print")
3501 return createGuiPrintindex(*this);
3503 return createGuiInfo(*this);
3504 if (name == "label")
3505 return createGuiLabel(*this);
3506 if (name == "listings")
3507 return createGuiListings(*this);
3509 return createGuiLog(*this);
3510 if (name == "mathdelimiter")
3511 return createGuiDelimiter(*this);
3512 if (name == "mathspace")
3513 return createGuiMathHSpace(*this);
3514 if (name == "mathmatrix")
3515 return createGuiMathMatrix(*this);
3516 if (name == "nomenclature")
3517 return createGuiNomenclature(*this);
3518 if (name == "nomencl_print")
3519 return createGuiPrintNomencl(*this);
3521 return createGuiNote(*this);
3522 if (name == "paragraph")
3523 return createGuiParagraph(*this);
3524 if (name == "phantom")
3525 return createGuiPhantom(*this);
3526 if (name == "prefs")
3527 return createGuiPreferences(*this);
3528 if (name == "print")
3529 return createGuiPrint(*this);
3531 return createGuiRef(*this);
3532 if (name == "sendto")
3533 return createGuiSendTo(*this);
3534 if (name == "space")
3535 return createGuiTextHSpace(*this);
3536 if (name == "spellchecker")
3537 return createGuiSpellchecker(*this);
3538 if (name == "symbols")
3539 return createGuiSymbols(*this);
3540 if (name == "tabular")
3541 return createGuiTabular(*this);
3542 if (name == "tabularcreate")
3543 return createGuiTabularCreate(*this);
3544 if (name == "texinfo")
3545 return createGuiTexInfo(*this);
3546 if (name == "thesaurus")
3547 return createGuiThesaurus(*this);
3549 return createGuiToc(*this);
3550 if (name == "view-source")
3551 return createGuiViewSource(*this);
3552 if (name == "vspace")
3553 return createGuiVSpace(*this);
3555 return createGuiWrap(*this);
3556 if (name == "progress")
3557 return createGuiProgressView(*this);
3563 } // namespace frontend
3566 #include "moc_GuiView.cpp"