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 "DispatchResult.h"
20 #include "FileDialog.h"
21 #include "FontLoader.h"
22 #include "GuiApplication.h"
23 #include "GuiCommandBuffer.h"
24 #include "GuiCompleter.h"
25 #include "GuiKeySymbol.h"
27 #include "GuiToolbar.h"
28 #include "GuiWorkArea.h"
29 #include "LayoutBox.h"
33 #include "qt_helpers.h"
35 #include "frontends/alert.h"
37 #include "buffer_funcs.h"
39 #include "BufferList.h"
40 #include "BufferParams.h"
41 #include "BufferView.h"
43 #include "Converter.h"
45 #include "CutAndPaste.h"
47 #include "ErrorList.h"
49 #include "FuncStatus.h"
50 #include "FuncRequest.h"
54 #include "LyXAction.h"
58 #include "Paragraph.h"
59 #include "SpellChecker.h"
61 #include "TextClass.h"
66 #include "support/convert.h"
67 #include "support/debug.h"
68 #include "support/ExceptionMessage.h"
69 #include "support/FileName.h"
70 #include "support/filetools.h"
71 #include "support/gettext.h"
72 #include "support/filetools.h"
73 #include "support/ForkedCalls.h"
74 #include "support/lassert.h"
75 #include "support/lstrings.h"
76 #include "support/os.h"
77 #include "support/Package.h"
78 #include "support/Path.h"
79 #include "support/Systemcall.h"
80 #include "support/Timeout.h"
81 #include "support/ProgressInterface.h"
82 #include "GuiProgress.h"
85 #include <QApplication>
86 #include <QCloseEvent>
88 #include <QDesktopWidget>
89 #include <QDragEnterEvent>
96 #include <QPixmapCache>
98 #include <QPushButton>
100 #include <QShowEvent>
102 #include <QStackedWidget>
103 #include <QStatusBar>
108 #include <QScrollBar>
112 #define EXPORT_in_THREAD 1
114 // QtConcurrent was introduced in Qt 4.4
115 #if (QT_VERSION >= 0x040400)
117 #include <QFutureWatcher>
118 #include <QtConcurrentRun>
121 #include "support/bind.h"
125 #ifdef HAVE_SYS_TIME_H
126 # include <sys/time.h>
133 using namespace lyx::support;
140 class BackgroundWidget : public QWidget
145 LYXERR(Debug::GUI, "show banner: " << lyxrc.show_banner);
146 if (!lyxrc.show_banner)
148 /// The text to be written on top of the pixmap
149 QString const text = lyx_version ?
150 qt_("version ") + lyx_version : qt_("unknown version");
151 splash_ = getPixmap("images/", "banner", "png");
153 QPainter pain(&splash_);
154 pain.setPen(QColor(0, 0, 0));
156 // The font used to display the version info
157 font.setStyleHint(QFont::SansSerif);
158 font.setWeight(QFont::Bold);
159 font.setPointSize(int(toqstr(lyxrc.font_sizes[FONT_SIZE_LARGE]).toDouble()));
160 int width = QFontMetrics(font).width(text);
162 pain.drawText(397 - width, 15, text);
163 setFocusPolicy(Qt::StrongFocus);
166 void paintEvent(QPaintEvent *)
168 int x = (width() - splash_.width()) / 2;
169 int y = (height() - splash_.height()) / 2;
171 pain.drawPixmap(x, y, splash_);
174 void keyPressEvent(QKeyEvent * ev)
177 setKeySymbol(&sym, ev);
179 guiApp->processKeySym(sym, q_key_state(ev->modifiers()));
191 /// Toolbar store providing access to individual toolbars by name.
192 typedef map<string, GuiToolbar *> ToolbarMap;
194 typedef shared_ptr<Dialog> DialogPtr;
199 struct GuiView::GuiViewPrivate
201 GuiViewPrivate(GuiView * gv)
202 : gv_(gv), current_work_area_(0), current_main_work_area_(0),
203 layout_(0), autosave_timeout_(5000),
206 // hardcode here the platform specific icon size
207 smallIconSize = 14; // scaling problems
208 normalIconSize = 20; // ok, default
209 bigIconSize = 26; // better for some math icons
211 splitter_ = new QSplitter;
212 bg_widget_ = new BackgroundWidget;
213 stack_widget_ = new QStackedWidget;
214 stack_widget_->addWidget(bg_widget_);
215 stack_widget_->addWidget(splitter_);
218 // TODO cleanup, remove the singleton, handle multiple Windows?
219 progress_ = ProgressInterface::instance();
220 if (!dynamic_cast<GuiProgress*>(progress_)) {
221 progress_ = new GuiProgress(); // TODO who deletes it
222 ProgressInterface::setInstance(progress_);
225 dynamic_cast<GuiProgress*>(progress_),
226 SIGNAL(updateStatusBarMessage(QString const&)),
227 gv, SLOT(updateStatusBarMessage(QString const&)));
229 dynamic_cast<GuiProgress*>(progress_),
230 SIGNAL(clearMessageText()),
231 gv, SLOT(clearMessageText()));
238 delete stack_widget_;
241 QMenu * toolBarPopup(GuiView * parent)
243 // FIXME: translation
244 QMenu * menu = new QMenu(parent);
245 QActionGroup * iconSizeGroup = new QActionGroup(parent);
247 QAction * smallIcons = new QAction(iconSizeGroup);
248 smallIcons->setText(qt_("Small-sized icons"));
249 smallIcons->setCheckable(true);
250 QObject::connect(smallIcons, SIGNAL(triggered()),
251 parent, SLOT(smallSizedIcons()));
252 menu->addAction(smallIcons);
254 QAction * normalIcons = new QAction(iconSizeGroup);
255 normalIcons->setText(qt_("Normal-sized icons"));
256 normalIcons->setCheckable(true);
257 QObject::connect(normalIcons, SIGNAL(triggered()),
258 parent, SLOT(normalSizedIcons()));
259 menu->addAction(normalIcons);
261 QAction * bigIcons = new QAction(iconSizeGroup);
262 bigIcons->setText(qt_("Big-sized icons"));
263 bigIcons->setCheckable(true);
264 QObject::connect(bigIcons, SIGNAL(triggered()),
265 parent, SLOT(bigSizedIcons()));
266 menu->addAction(bigIcons);
268 unsigned int cur = parent->iconSize().width();
269 if ( cur == parent->d.smallIconSize)
270 smallIcons->setChecked(true);
271 else if (cur == parent->d.normalIconSize)
272 normalIcons->setChecked(true);
273 else if (cur == parent->d.bigIconSize)
274 bigIcons->setChecked(true);
281 stack_widget_->setCurrentWidget(bg_widget_);
282 bg_widget_->setUpdatesEnabled(true);
283 bg_widget_->setFocus();
286 TabWorkArea * tabWorkArea(int i)
288 return dynamic_cast<TabWorkArea *>(splitter_->widget(i));
291 TabWorkArea * currentTabWorkArea()
293 if (splitter_->count() == 1)
294 // The first TabWorkArea is always the first one, if any.
295 return tabWorkArea(0);
297 for (int i = 0; i != splitter_->count(); ++i) {
298 TabWorkArea * twa = tabWorkArea(i);
299 if (current_main_work_area_ == twa->currentWorkArea())
303 // None has the focus so we just take the first one.
304 return tabWorkArea(0);
307 #if (QT_VERSION >= 0x040400)
308 void setPreviewFuture(QFuture<docstring> const & f)
310 if (preview_watcher_.isRunning()) {
311 // we prefer to cancel this preview in order to keep a snappy
315 preview_watcher_.setFuture(f);
321 GuiWorkArea * current_work_area_;
322 GuiWorkArea * current_main_work_area_;
323 QSplitter * splitter_;
324 QStackedWidget * stack_widget_;
325 BackgroundWidget * bg_widget_;
327 ToolbarMap toolbars_;
328 ProgressInterface* progress_;
329 /// The main layout box.
331 * \warning Don't Delete! The layout box is actually owned by
332 * whichever toolbar contains it. All the GuiView class needs is a
333 * means of accessing it.
335 * FIXME: replace that with a proper model so that we are not limited
336 * to only one dialog.
341 map<string, DialogPtr> dialogs_;
343 unsigned int smallIconSize;
344 unsigned int normalIconSize;
345 unsigned int bigIconSize;
347 QTimer statusbar_timer_;
348 /// auto-saving of buffers
349 Timeout autosave_timeout_;
350 /// flag against a race condition due to multiclicks, see bug #1119
354 TocModels toc_models_;
356 #if (QT_VERSION >= 0x040400)
358 QFutureWatcher<docstring> autosave_watcher_;
359 QFutureWatcher<docstring> preview_watcher_;
361 string last_export_format;
363 struct DummyWatcher { bool isRunning(){return false;} };
364 DummyWatcher preview_watcher_;
367 static QSet<Buffer const *> busyBuffers;
368 static docstring previewAndDestroy(Buffer const * orig, Buffer * buffer, string const & format);
369 static docstring exportAndDestroy(Buffer const * orig, Buffer * buffer, string const & format);
370 static docstring saveAndDestroy(Buffer const * orig, Buffer * buffer, FileName const & fname);
374 QSet<Buffer const *> GuiView::GuiViewPrivate::busyBuffers;
377 GuiView::GuiView(int id)
378 : d(*new GuiViewPrivate(this)), id_(id), closing_(false)
380 // GuiToolbars *must* be initialised before the menu bar.
381 normalSizedIcons(); // at least on Mac the default is 32 otherwise, which is huge
384 // set ourself as the current view. This is needed for the menu bar
385 // filling, at least for the static special menu item on Mac. Otherwise
386 // they are greyed out.
387 guiApp->setCurrentView(this);
389 // Fill up the menu bar.
390 guiApp->menus().fillMenuBar(menuBar(), this, true);
392 setCentralWidget(d.stack_widget_);
394 // Start autosave timer
395 if (lyxrc.autosave) {
396 d.autosave_timeout_.timeout.connect(bind(&GuiView::autoSave, this));
397 d.autosave_timeout_.setTimeout(lyxrc.autosave * 1000);
398 d.autosave_timeout_.start();
400 connect(&d.statusbar_timer_, SIGNAL(timeout()),
401 this, SLOT(clearMessage()));
403 // We don't want to keep the window in memory if it is closed.
404 setAttribute(Qt::WA_DeleteOnClose, true);
406 #if (!defined(Q_WS_WIN) && !defined(Q_WS_MACX))
407 // assign an icon to main form. We do not do it under Qt/Win or Qt/Mac,
408 // since the icon is provided in the application bundle.
409 setWindowIcon(getPixmap("images/", "lyx", "png"));
412 #if (QT_VERSION >= 0x040300)
413 // use tabbed dock area for multiple docks
414 // (such as "source" and "messages")
415 setDockOptions(QMainWindow::ForceTabbedDocks);
419 setAcceptDrops(true);
421 statusBar()->setSizeGripEnabled(true);
424 #if (QT_VERSION >= 0x040400)
425 connect(&d.autosave_watcher_, SIGNAL(finished()), this,
426 SLOT(threadFinished()));
427 connect(&d.preview_watcher_, SIGNAL(finished()), this,
428 SLOT(threadFinished()));
431 connect(this, SIGNAL(triggerShowDialog(QString const &, QString const &, Inset *)),
432 SLOT(doShowDialog(QString const &, QString const &, Inset *)));
434 // Forbid too small unresizable window because it can happen
435 // with some window manager under X11.
436 setMinimumSize(300, 200);
438 if (lyxrc.allow_geometry_session) {
439 // Now take care of session management.
444 // no session handling, default to a sane size.
445 setGeometry(50, 50, 690, 510);
448 // clear session data if any.
450 settings.remove("views");
460 void GuiView::threadFinished()
462 #if (QT_VERSION >= 0x040400)
463 QFutureWatcher<docstring> const * watcher =
464 static_cast<QFutureWatcher<docstring> const *>(sender());
465 message(watcher->result());
467 errors(d.last_export_format);
472 void GuiView::saveLayout() const
475 settings.beginGroup("views");
476 settings.beginGroup(QString::number(id_));
478 settings.setValue("pos", pos());
479 settings.setValue("size", size());
481 settings.setValue("geometry", saveGeometry());
483 settings.setValue("layout", saveState(0));
484 settings.setValue("icon_size", iconSize());
488 bool GuiView::restoreLayout()
491 settings.beginGroup("views");
492 settings.beginGroup(QString::number(id_));
493 QString const icon_key = "icon_size";
494 if (!settings.contains(icon_key))
497 //code below is skipped when when ~/.config/LyX is (re)created
498 setIconSize(settings.value(icon_key).toSize());
500 QPoint pos = settings.value("pos", QPoint(50, 50)).toPoint();
501 QSize size = settings.value("size", QSize(690, 510)).toSize();
505 // Work-around for bug #6034: the window ends up in an undetermined
506 // state when trying to restore a maximized window when it is
507 // already maximized.
508 if (!(windowState() & Qt::WindowMaximized))
509 if (!restoreGeometry(settings.value("geometry").toByteArray()))
510 setGeometry(50, 50, 690, 510);
512 // Make sure layout is correctly oriented.
513 setLayoutDirection(qApp->layoutDirection());
515 // Allow the toc and view-source dock widget to be restored if needed.
517 if ((dialog = findOrBuild("toc", true)))
518 // see bug 5082. At least setup title and enabled state.
519 // Visibility will be adjusted by restoreState below.
520 dialog->prepareView();
521 if ((dialog = findOrBuild("view-source", true)))
522 dialog->prepareView();
523 if ((dialog = findOrBuild("progress", true)))
524 dialog->prepareView();
526 if (!restoreState(settings.value("layout").toByteArray(), 0))
533 GuiToolbar * GuiView::toolbar(string const & name)
535 ToolbarMap::iterator it = d.toolbars_.find(name);
536 if (it != d.toolbars_.end())
539 LYXERR(Debug::GUI, "Toolbar::display: no toolbar named " << name);
544 void GuiView::constructToolbars()
546 ToolbarMap::iterator it = d.toolbars_.begin();
547 for (; it != d.toolbars_.end(); ++it)
551 // I don't like doing this here, but the standard toolbar
552 // destroys this object when it's destroyed itself (vfr)
553 d.layout_ = new LayoutBox(*this);
554 d.stack_widget_->addWidget(d.layout_);
555 d.layout_->move(0,0);
557 // extracts the toolbars from the backend
558 Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
559 Toolbars::Infos::iterator end = guiApp->toolbars().end();
560 for (; cit != end; ++cit)
561 d.toolbars_[cit->name] = new GuiToolbar(*cit, *this);
565 void GuiView::initToolbars()
567 // extracts the toolbars from the backend
568 Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
569 Toolbars::Infos::iterator end = guiApp->toolbars().end();
570 for (; cit != end; ++cit) {
571 GuiToolbar * tb = toolbar(cit->name);
574 int const visibility = guiApp->toolbars().defaultVisibility(cit->name);
575 bool newline = !(visibility & Toolbars::SAMEROW);
576 tb->setVisible(false);
577 tb->setVisibility(visibility);
579 if (visibility & Toolbars::TOP) {
581 addToolBarBreak(Qt::TopToolBarArea);
582 addToolBar(Qt::TopToolBarArea, tb);
585 if (visibility & Toolbars::BOTTOM) {
586 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
587 #if (QT_VERSION >= 0x040202)
589 addToolBarBreak(Qt::BottomToolBarArea);
591 addToolBar(Qt::BottomToolBarArea, tb);
594 if (visibility & Toolbars::LEFT) {
595 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
596 #if (QT_VERSION >= 0x040202)
598 addToolBarBreak(Qt::LeftToolBarArea);
600 addToolBar(Qt::LeftToolBarArea, tb);
603 if (visibility & Toolbars::RIGHT) {
604 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
605 #if (QT_VERSION >= 0x040202)
607 addToolBarBreak(Qt::RightToolBarArea);
609 addToolBar(Qt::RightToolBarArea, tb);
612 if (visibility & Toolbars::ON)
613 tb->setVisible(true);
618 TocModels & GuiView::tocModels()
620 return d.toc_models_;
624 void GuiView::setFocus()
626 LYXERR(Debug::DEBUG, "GuiView::setFocus()" << this);
627 QMainWindow::setFocus();
631 void GuiView::focusInEvent(QFocusEvent * e)
633 LYXERR(Debug::DEBUG, "GuiView::focusInEvent()" << this);
634 QMainWindow::focusInEvent(e);
635 // Make sure guiApp points to the correct view.
636 guiApp->setCurrentView(this);
637 if (currentMainWorkArea())
638 currentMainWorkArea()->setFocus();
639 else if (currentWorkArea())
640 currentWorkArea()->setFocus();
642 d.bg_widget_->setFocus();
646 QMenu * GuiView::createPopupMenu()
648 return d.toolBarPopup(this);
652 void GuiView::showEvent(QShowEvent * e)
654 LYXERR(Debug::GUI, "Passed Geometry "
655 << size().height() << "x" << size().width()
656 << "+" << pos().x() << "+" << pos().y());
658 if (d.splitter_->count() == 0)
659 // No work area, switch to the background widget.
662 QMainWindow::showEvent(e);
666 bool GuiView::closeScheduled()
673 /** Destroy only all tabbed WorkAreas. Destruction of other WorkAreas
674 ** is responsibility of the container (e.g., dialog)
676 void GuiView::closeEvent(QCloseEvent * close_event)
678 LYXERR(Debug::DEBUG, "GuiView::closeEvent()");
680 if (!GuiViewPrivate::busyBuffers.isEmpty()) {
681 Alert::warning(_("Exit LyX"), _("LyX could not be closed because documents are processed by LyX."));
682 close_event->setAccepted(false);
686 // If the user pressed the x (so we didn't call closeView
687 // programmatically), we want to clear all existing entries.
689 theSession().lastOpened().clear();
694 // it can happen that this event arrives without selecting the view,
695 // e.g. when clicking the close button on a background window.
697 if (!closeWorkAreaAll()) {
699 close_event->ignore();
703 // Make sure that nothing will use this to be closed View.
704 guiApp->unregisterView(this);
706 if (isFullScreen()) {
707 // Switch off fullscreen before closing.
712 // Make sure the timer time out will not trigger a statusbar update.
713 d.statusbar_timer_.stop();
715 // Saving fullscreen requires additional tweaks in the toolbar code.
716 // It wouldn't also work under linux natively.
717 if (lyxrc.allow_geometry_session) {
718 // Save this window geometry and layout.
720 // Then the toolbar private states.
721 ToolbarMap::iterator end = d.toolbars_.end();
722 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
723 it->second->saveSession();
724 // Now take care of all other dialogs:
725 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
726 for (; it!= d.dialogs_.end(); ++it)
727 it->second->saveSession();
730 close_event->accept();
734 void GuiView::dragEnterEvent(QDragEnterEvent * event)
736 if (event->mimeData()->hasUrls())
738 /// \todo Ask lyx-devel is this is enough:
739 /// if (event->mimeData()->hasFormat("text/plain"))
740 /// event->acceptProposedAction();
744 void GuiView::dropEvent(QDropEvent * event)
746 QList<QUrl> files = event->mimeData()->urls();
750 LYXERR(Debug::GUI, "GuiView::dropEvent: got URLs!");
751 for (int i = 0; i != files.size(); ++i) {
752 string const file = os::internal_path(fromqstr(
753 files.at(i).toLocalFile()));
757 string const ext = support::getExtension(file);
758 vector<const Format *> found_formats;
760 // Find all formats that have the correct extension.
761 vector<const Format *> const & import_formats
762 = theConverters().importableFormats();
763 vector<const Format *>::const_iterator it = import_formats.begin();
764 for (; it != import_formats.end(); ++it)
765 if ((*it)->extension() == ext)
766 found_formats.push_back(*it);
769 if (found_formats.size() >= 1) {
770 if (found_formats.size() > 1) {
771 //FIXME: show a dialog to choose the correct importable format
773 "Multiple importable formats found, selecting first");
775 string const arg = found_formats[0]->name() + " " + file;
776 cmd = FuncRequest(LFUN_BUFFER_IMPORT, arg);
779 //FIXME: do we have to explicitly check whether it's a lyx file?
781 "No formats found, trying to open it as a lyx file");
782 cmd = FuncRequest(LFUN_FILE_OPEN, file);
785 // Asynchronously post the event. DropEvent usually comes
786 // from the BufferView. But reloading a file might close
787 // the BufferView from within its own event handler.
788 guiApp->dispatchDelayed(cmd);
794 void GuiView::message(docstring const & str)
796 if (ForkedProcess::iAmAChild())
799 // call is moved to GUI-thread by GuiProgress
800 d.progress_->appendMessage(toqstr(str));
804 void GuiView::clearMessageText()
806 message(docstring());
810 void GuiView::updateStatusBarMessage(QString const & str)
812 statusBar()->showMessage(str);
813 d.statusbar_timer_.stop();
814 d.statusbar_timer_.start(3000);
818 void GuiView::smallSizedIcons()
820 setIconSize(QSize(d.smallIconSize, d.smallIconSize));
824 void GuiView::normalSizedIcons()
826 setIconSize(QSize(d.normalIconSize, d.normalIconSize));
830 void GuiView::bigSizedIcons()
832 setIconSize(QSize(d.bigIconSize, d.bigIconSize));
836 void GuiView::clearMessage()
838 // FIXME: This code was introduced in r19643 to fix bug #4123. However,
839 // the hasFocus function mostly returns false, even if the focus is on
840 // a workarea in this view.
844 d.statusbar_timer_.stop();
848 void GuiView::updateWindowTitle(GuiWorkArea * wa)
850 if (wa != d.current_work_area_
851 || wa->bufferView().buffer().isInternal())
853 setWindowTitle(qt_("LyX: ") + wa->windowTitle());
854 setWindowIconText(wa->windowIconText());
858 void GuiView::on_currentWorkAreaChanged(GuiWorkArea * wa)
861 disconnectBufferView();
862 connectBufferView(wa->bufferView());
863 connectBuffer(wa->bufferView().buffer());
864 d.current_work_area_ = wa;
865 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
866 this, SLOT(updateWindowTitle(GuiWorkArea *)));
867 updateWindowTitle(wa);
871 // The document settings needs to be reinitialised.
872 updateDialog("document", "");
874 // Buffer-dependent dialogs must be updated. This is done here because
875 // some dialogs require buffer()->text.
880 void GuiView::on_lastWorkAreaRemoved()
883 // We already are in a close event. Nothing more to do.
886 if (d.splitter_->count() > 1)
887 // We have a splitter so don't close anything.
890 // Reset and updates the dialogs.
891 d.toc_models_.reset(0);
892 updateDialog("document", "");
895 resetWindowTitleAndIconText();
898 if (lyxrc.open_buffers_in_tabs)
899 // Nothing more to do, the window should stay open.
902 if (guiApp->viewIds().size() > 1) {
908 // On Mac we also close the last window because the application stay
909 // resident in memory. On other platforms we don't close the last
910 // window because this would quit the application.
916 void GuiView::updateStatusBar()
918 // let the user see the explicit message
919 if (d.statusbar_timer_.isActive())
926 void GuiView::showMessage()
928 QString msg = toqstr(theGuiApp()->viewStatusMessage());
930 BufferView const * bv = currentBufferView();
932 msg = toqstr(bv->cursor().currentState());
934 msg = qt_("Welcome to LyX!");
936 statusBar()->showMessage(msg);
940 bool GuiView::event(QEvent * e)
944 // Useful debug code:
945 //case QEvent::ActivationChange:
946 //case QEvent::WindowDeactivate:
947 //case QEvent::Paint:
948 //case QEvent::Enter:
949 //case QEvent::Leave:
950 //case QEvent::HoverEnter:
951 //case QEvent::HoverLeave:
952 //case QEvent::HoverMove:
953 //case QEvent::StatusTip:
954 //case QEvent::DragEnter:
955 //case QEvent::DragLeave:
959 case QEvent::WindowActivate: {
960 GuiView * old_view = guiApp->currentView();
961 if (this == old_view) {
963 return QMainWindow::event(e);
965 if (old_view && old_view->currentBufferView()) {
966 // save current selection to the selection buffer to allow
967 // middle-button paste in this window.
968 cap::saveSelection(old_view->currentBufferView()->cursor());
970 guiApp->setCurrentView(this);
971 if (d.current_work_area_) {
972 BufferView & bv = d.current_work_area_->bufferView();
973 connectBufferView(bv);
974 connectBuffer(bv.buffer());
975 // The document structure, name and dialogs might have
976 // changed in another view.
978 // The document settings needs to be reinitialised.
979 updateDialog("document", "");
982 resetWindowTitleAndIconText();
985 return QMainWindow::event(e);
988 case QEvent::ShortcutOverride: {
991 #if (!defined Q_WS_X11) || (QT_VERSION >= 0x040500)
992 if (isFullScreen() && menuBar()->isHidden()) {
993 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
994 // FIXME: we should also try to detect special LyX shortcut such as
995 // Alt-P and Alt-M. Right now there is a hack in
996 // GuiWorkArea::processKeySym() that hides again the menubar for
998 if (ke->modifiers() & Qt::AltModifier && ke->key() != Qt::Key_Alt) {
1000 return QMainWindow::event(e);
1004 return QMainWindow::event(e);
1008 return QMainWindow::event(e);
1012 void GuiView::resetWindowTitleAndIconText()
1014 setWindowTitle(qt_("LyX"));
1015 setWindowIconText(qt_("LyX"));
1018 bool GuiView::focusNextPrevChild(bool /*next*/)
1025 bool GuiView::busy() const
1031 void GuiView::setBusy(bool busy)
1034 if (d.current_work_area_) {
1035 d.current_work_area_->setUpdatesEnabled(!busy);
1037 d.current_work_area_->stopBlinkingCursor();
1039 d.current_work_area_->startBlinkingCursor();
1043 QApplication::setOverrideCursor(Qt::WaitCursor);
1045 QApplication::restoreOverrideCursor();
1049 GuiWorkArea * GuiView::workArea(Buffer & buffer)
1051 if (currentWorkArea()
1052 && ¤tWorkArea()->bufferView().buffer() == &buffer)
1053 return (GuiWorkArea *) currentWorkArea();
1054 if (TabWorkArea * twa = d.currentTabWorkArea())
1055 return twa->workArea(buffer);
1060 GuiWorkArea * GuiView::addWorkArea(Buffer & buffer)
1062 // Automatically create a TabWorkArea if there are none yet.
1063 TabWorkArea * tab_widget = d.splitter_->count()
1064 ? d.currentTabWorkArea() : addTabWorkArea();
1065 return tab_widget->addWorkArea(buffer, *this);
1069 TabWorkArea * GuiView::addTabWorkArea()
1071 TabWorkArea * twa = new TabWorkArea;
1072 QObject::connect(twa, SIGNAL(currentWorkAreaChanged(GuiWorkArea *)),
1073 this, SLOT(on_currentWorkAreaChanged(GuiWorkArea *)));
1074 QObject::connect(twa, SIGNAL(lastWorkAreaRemoved()),
1075 this, SLOT(on_lastWorkAreaRemoved()));
1077 d.splitter_->addWidget(twa);
1078 d.stack_widget_->setCurrentWidget(d.splitter_);
1083 GuiWorkArea const * GuiView::currentWorkArea() const
1085 return d.current_work_area_;
1089 GuiWorkArea * GuiView::currentWorkArea()
1091 return d.current_work_area_;
1095 GuiWorkArea const * GuiView::currentMainWorkArea() const
1097 if (!d.currentTabWorkArea())
1099 return d.currentTabWorkArea()->currentWorkArea();
1103 GuiWorkArea * GuiView::currentMainWorkArea()
1105 if (!d.currentTabWorkArea())
1107 return d.currentTabWorkArea()->currentWorkArea();
1111 void GuiView::setCurrentWorkArea(GuiWorkArea * wa)
1113 LYXERR(Debug::DEBUG, "Setting current wa: " << wa << endl);
1115 d.current_work_area_ = 0;
1120 // FIXME: I've no clue why this is here and why it accesses
1121 // theGuiApp()->currentView, which might be 0 (bug 6464).
1122 // See also 27525 (vfr).
1123 if (theGuiApp()->currentView() == this
1124 && theGuiApp()->currentView()->currentWorkArea() == wa)
1127 if (currentBufferView())
1128 cap::saveSelection(currentBufferView()->cursor());
1130 theGuiApp()->setCurrentView(this);
1131 d.current_work_area_ = wa;
1132 for (int i = 0; i != d.splitter_->count(); ++i) {
1133 if (d.tabWorkArea(i)->setCurrentWorkArea(wa)) {
1134 //if (d.current_main_work_area_)
1135 // d.current_main_work_area_->setFrameStyle(QFrame::NoFrame);
1136 d.current_main_work_area_ = wa;
1137 //d.current_main_work_area_->setFrameStyle(QFrame::Box | QFrame::Plain);
1138 //d.current_main_work_area_->setLineWidth(2);
1139 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() << ", Current main wa: " << currentMainWorkArea());
1143 LYXERR(Debug::DEBUG, "This is not a tabbed wa");
1144 on_currentWorkAreaChanged(wa);
1145 BufferView & bv = wa->bufferView();
1146 bv.cursor().fixIfBroken();
1148 wa->setUpdatesEnabled(true);
1149 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() << ", Current main wa: " << currentMainWorkArea());
1153 void GuiView::removeWorkArea(GuiWorkArea * wa)
1155 LASSERT(wa, return);
1156 if (wa == d.current_work_area_) {
1158 disconnectBufferView();
1159 d.current_work_area_ = 0;
1160 d.current_main_work_area_ = 0;
1163 bool found_twa = false;
1164 for (int i = 0; i != d.splitter_->count(); ++i) {
1165 TabWorkArea * twa = d.tabWorkArea(i);
1166 if (twa->removeWorkArea(wa)) {
1167 // Found in this tab group, and deleted the GuiWorkArea.
1169 if (twa->count() != 0) {
1170 if (d.current_work_area_ == 0)
1171 // This means that we are closing the current GuiWorkArea, so
1172 // switch to the next GuiWorkArea in the found TabWorkArea.
1173 setCurrentWorkArea(twa->currentWorkArea());
1175 // No more WorkAreas in this tab group, so delete it.
1182 // It is not a tabbed work area (i.e., the search work area), so it
1183 // should be deleted by other means.
1184 LASSERT(found_twa, /* */);
1186 if (d.current_work_area_ == 0) {
1187 if (d.splitter_->count() != 0) {
1188 TabWorkArea * twa = d.currentTabWorkArea();
1189 setCurrentWorkArea(twa->currentWorkArea());
1191 // No more work areas, switch to the background widget.
1192 setCurrentWorkArea(0);
1198 LayoutBox * GuiView::getLayoutDialog() const
1204 void GuiView::updateLayoutList()
1207 d.layout_->updateContents(false);
1211 void GuiView::updateToolbars()
1213 ToolbarMap::iterator end = d.toolbars_.end();
1214 if (d.current_work_area_) {
1216 d.current_work_area_->bufferView().cursor().inMathed()
1217 && !d.current_work_area_->bufferView().cursor().inRegexped();
1219 lyx::getStatus(FuncRequest(LFUN_LAYOUT_TABULAR)).enabled();
1221 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).enabled() &&
1222 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).onOff(true);
1223 bool const mathmacrotemplate =
1224 lyx::getStatus(FuncRequest(LFUN_IN_MATHMACROTEMPLATE)).enabled();
1226 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1227 it->second->update(math, table, review, mathmacrotemplate);
1229 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1230 it->second->update(false, false, false, false);
1234 void GuiView::setBuffer(Buffer * newBuffer)
1236 LYXERR(Debug::DEBUG, "Setting buffer: " << newBuffer << endl);
1237 LASSERT(newBuffer, return);
1240 GuiWorkArea * wa = workArea(*newBuffer);
1242 newBuffer->masterBuffer()->updateBuffer();
1243 wa = addWorkArea(*newBuffer);
1245 //Disconnect the old buffer...there's no new one.
1248 connectBuffer(*newBuffer);
1249 connectBufferView(wa->bufferView());
1250 setCurrentWorkArea(wa);
1256 void GuiView::connectBuffer(Buffer & buf)
1258 buf.setGuiDelegate(this);
1262 void GuiView::disconnectBuffer()
1264 if (d.current_work_area_)
1265 d.current_work_area_->bufferView().buffer().setGuiDelegate(0);
1269 void GuiView::connectBufferView(BufferView & bv)
1271 bv.setGuiDelegate(this);
1275 void GuiView::disconnectBufferView()
1277 if (d.current_work_area_)
1278 d.current_work_area_->bufferView().setGuiDelegate(0);
1282 void GuiView::errors(string const & error_type, bool from_master)
1284 ErrorList & el = from_master ?
1285 currentBufferView()->buffer().masterBuffer()->errorList(error_type)
1286 : currentBufferView()->buffer().errorList(error_type);
1287 string data = error_type;
1289 data = "from_master|" + error_type;
1291 showDialog("errorlist", data);
1295 void GuiView::updateTocItem(string const & type, DocIterator const & dit)
1297 d.toc_models_.updateItem(toqstr(type), dit);
1301 void GuiView::structureChanged()
1303 d.toc_models_.reset(documentBufferView());
1304 // Navigator needs more than a simple update in this case. It needs to be
1306 updateDialog("toc", "");
1310 void GuiView::updateDialog(string const & name, string const & data)
1312 if (!isDialogVisible(name))
1315 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
1316 if (it == d.dialogs_.end())
1319 Dialog * const dialog = it->second.get();
1320 if (dialog->isVisibleView())
1321 dialog->initialiseParams(data);
1325 BufferView * GuiView::documentBufferView()
1327 return currentMainWorkArea()
1328 ? ¤tMainWorkArea()->bufferView()
1333 BufferView const * GuiView::documentBufferView() const
1335 return currentMainWorkArea()
1336 ? ¤tMainWorkArea()->bufferView()
1341 BufferView * GuiView::currentBufferView()
1343 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1347 BufferView const * GuiView::currentBufferView() const
1349 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1353 #if (QT_VERSION >= 0x040400)
1354 docstring GuiView::GuiViewPrivate::saveAndDestroy(Buffer const * orig, Buffer * buffer, FileName const & fname)
1357 FileName const tmp_ret = FileName::tempName("lyxauto");
1358 if (!tmp_ret.empty()) {
1359 if (buffer->writeFile(tmp_ret))
1360 failed = !tmp_ret.moveTo(fname);
1363 // failed to write/rename tmp_ret so try writing direct
1364 failed = buffer->writeFile(fname);
1367 busyBuffers.remove(orig);
1369 ? _("Automatic save failed!")
1370 : _("Automatic save done.");
1375 void GuiView::autoSave()
1377 LYXERR(Debug::INFO, "Running autoSave()");
1379 Buffer * buffer = documentBufferView()
1380 ? &documentBufferView()->buffer() : 0;
1384 #if (QT_VERSION >= 0x040400)
1385 GuiViewPrivate::busyBuffers.insert(buffer);
1386 QFuture<docstring> f = QtConcurrent::run(GuiViewPrivate::saveAndDestroy, buffer, buffer->clone(),
1387 buffer->getAutosaveFileName());
1388 d.autosave_watcher_.setFuture(f);
1395 void GuiView::resetAutosaveTimers()
1398 d.autosave_timeout_.restart();
1402 bool GuiView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1405 Buffer * buf = currentBufferView()
1406 ? ¤tBufferView()->buffer() : 0;
1407 Buffer * doc_buffer = documentBufferView()
1408 ? &(documentBufferView()->buffer()) : 0;
1410 // Check whether we need a buffer
1411 if (!lyxaction.funcHasFlag(cmd.action(), LyXAction::NoBuffer) && !buf) {
1412 // no, exit directly
1413 flag.message(from_utf8(N_("Command not allowed with"
1414 "out any document open")));
1415 flag.setEnabled(false);
1419 if (cmd.origin() == FuncRequest::TOC) {
1420 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
1421 if (!toc || !toc->getStatus(documentBufferView()->cursor(), cmd, flag))
1422 flag.setEnabled(false);
1426 switch(cmd.action()) {
1427 case LFUN_BUFFER_IMPORT:
1430 case LFUN_MASTER_BUFFER_UPDATE:
1431 case LFUN_MASTER_BUFFER_VIEW:
1432 enable = doc_buffer && doc_buffer->parent() != 0
1433 && !d.preview_watcher_.isRunning();
1436 case LFUN_BUFFER_UPDATE:
1437 case LFUN_BUFFER_VIEW: {
1438 if (!doc_buffer || d.preview_watcher_.isRunning()) {
1442 string format = to_utf8(cmd.argument());
1443 if (cmd.argument().empty())
1444 format = doc_buffer->getDefaultOutputFormat();
1445 enable = doc_buffer->isExportableFormat(format);
1449 case LFUN_BUFFER_RELOAD:
1450 enable = doc_buffer && !doc_buffer->isUnnamed()
1451 && doc_buffer->fileName().exists()
1452 && (!doc_buffer->isClean()
1453 || doc_buffer->isExternallyModified(Buffer::timestamp_method));
1456 case LFUN_BUFFER_CHILD_OPEN:
1457 enable = doc_buffer;
1460 case LFUN_BUFFER_WRITE:
1461 enable = doc_buffer && (doc_buffer->isUnnamed() || !doc_buffer->isClean());
1464 //FIXME: This LFUN should be moved to GuiApplication.
1465 case LFUN_BUFFER_WRITE_ALL: {
1466 // We enable the command only if there are some modified buffers
1467 Buffer * first = theBufferList().first();
1472 // We cannot use a for loop as the buffer list is a cycle.
1474 if (!b->isClean()) {
1478 b = theBufferList().next(b);
1479 } while (b != first);
1483 case LFUN_BUFFER_WRITE_AS:
1484 enable = doc_buffer;
1487 case LFUN_BUFFER_CLOSE:
1488 enable = doc_buffer;
1491 case LFUN_BUFFER_CLOSE_ALL:
1492 enable = theBufferList().last() != theBufferList().first();
1495 case LFUN_SPLIT_VIEW:
1496 if (cmd.getArg(0) == "vertical")
1497 enable = doc_buffer && (d.splitter_->count() == 1 ||
1498 d.splitter_->orientation() == Qt::Vertical);
1500 enable = doc_buffer && (d.splitter_->count() == 1 ||
1501 d.splitter_->orientation() == Qt::Horizontal);
1504 case LFUN_CLOSE_TAB_GROUP:
1505 enable = d.currentTabWorkArea();
1508 case LFUN_TOOLBAR_TOGGLE: {
1509 string const name = cmd.getArg(0);
1510 if (GuiToolbar * t = toolbar(name))
1511 flag.setOnOff(t->isVisible());
1514 docstring const msg =
1515 bformat(_("Unknown toolbar \"%1$s\""), from_utf8(name));
1521 case LFUN_DROP_LAYOUTS_CHOICE:
1525 case LFUN_UI_TOGGLE:
1526 flag.setOnOff(isFullScreen());
1529 case LFUN_DIALOG_DISCONNECT_INSET:
1532 case LFUN_DIALOG_HIDE:
1533 // FIXME: should we check if the dialog is shown?
1536 case LFUN_DIALOG_TOGGLE:
1537 flag.setOnOff(isDialogVisible(cmd.getArg(0)));
1538 // fall through to set "enable"
1539 case LFUN_DIALOG_SHOW: {
1540 string const name = cmd.getArg(0);
1542 enable = name == "aboutlyx"
1543 || name == "file" //FIXME: should be removed.
1545 || name == "texinfo"
1546 || name == "progress"
1547 || name == "compare";
1548 else if (name == "print")
1549 enable = doc_buffer->isExportable("dvi")
1550 && lyxrc.print_command != "none";
1551 else if (name == "character" || name == "symbols") {
1552 if (!buf || buf->isReadonly())
1555 // FIXME we should consider passthru
1557 Inset const & in = currentBufferView()->cursor().inset();
1558 enable = !in.getLayout().isPassThru();
1561 else if (name == "latexlog")
1562 enable = FileName(doc_buffer->logName()).isReadableFile();
1563 else if (name == "spellchecker")
1564 enable = theSpellChecker() && !doc_buffer->isReadonly();
1565 else if (name == "vclog")
1566 enable = doc_buffer->lyxvc().inUse();
1570 case LFUN_DIALOG_UPDATE: {
1571 string const name = cmd.getArg(0);
1573 enable = name == "prefs";
1577 case LFUN_COMMAND_EXECUTE:
1579 case LFUN_MENU_OPEN:
1580 // Nothing to check.
1583 case LFUN_COMPLETION_INLINE:
1584 if (!d.current_work_area_
1585 || !d.current_work_area_->completer().inlinePossible(
1586 currentBufferView()->cursor()))
1590 case LFUN_COMPLETION_POPUP:
1591 if (!d.current_work_area_
1592 || !d.current_work_area_->completer().popupPossible(
1593 currentBufferView()->cursor()))
1597 case LFUN_COMPLETION_COMPLETE:
1598 if (!d.current_work_area_
1599 || !d.current_work_area_->completer().inlinePossible(
1600 currentBufferView()->cursor()))
1604 case LFUN_COMPLETION_ACCEPT:
1605 if (!d.current_work_area_
1606 || (!d.current_work_area_->completer().popupVisible()
1607 && !d.current_work_area_->completer().inlineVisible()
1608 && !d.current_work_area_->completer().completionAvailable()))
1612 case LFUN_COMPLETION_CANCEL:
1613 if (!d.current_work_area_
1614 || (!d.current_work_area_->completer().popupVisible()
1615 && !d.current_work_area_->completer().inlineVisible()))
1619 case LFUN_BUFFER_ZOOM_OUT:
1620 enable = doc_buffer && lyxrc.zoom > 10;
1623 case LFUN_BUFFER_ZOOM_IN:
1624 enable = doc_buffer;
1627 case LFUN_BUFFER_NEXT:
1628 case LFUN_BUFFER_PREVIOUS:
1629 // FIXME: should we check is there is an previous or next buffer?
1631 case LFUN_BUFFER_SWITCH:
1632 // toggle on the current buffer, but do not toggle off
1633 // the other ones (is that a good idea?)
1635 && to_utf8(cmd.argument()) == doc_buffer->absFileName())
1636 flag.setOnOff(true);
1639 case LFUN_VC_REGISTER:
1640 enable = doc_buffer && !doc_buffer->lyxvc().inUse();
1642 case LFUN_VC_CHECK_IN:
1643 enable = doc_buffer && doc_buffer->lyxvc().checkInEnabled();
1645 case LFUN_VC_CHECK_OUT:
1646 enable = doc_buffer && doc_buffer->lyxvc().checkOutEnabled();
1648 case LFUN_VC_LOCKING_TOGGLE:
1649 enable = doc_buffer && !doc_buffer->isReadonly()
1650 && doc_buffer->lyxvc().lockingToggleEnabled();
1651 flag.setOnOff(enable && doc_buffer->lyxvc().locking());
1653 case LFUN_VC_REVERT:
1654 enable = doc_buffer && doc_buffer->lyxvc().inUse();
1656 case LFUN_VC_UNDO_LAST:
1657 enable = doc_buffer && doc_buffer->lyxvc().undoLastEnabled();
1659 case LFUN_VC_REPO_UPDATE:
1660 enable = doc_buffer && doc_buffer->lyxvc().inUse();
1662 case LFUN_VC_COMMAND: {
1663 if (cmd.argument().empty())
1665 if (!doc_buffer && contains(cmd.getArg(0), 'D'))
1669 case LFUN_VC_COMPARE:
1670 enable = doc_buffer && doc_buffer->lyxvc().prepareFileRevisionEnabled();
1673 case LFUN_SERVER_GOTO_FILE_ROW:
1675 case LFUN_FORWARD_SEARCH:
1676 enable = !(lyxrc.forward_search_dvi.empty() && lyxrc.forward_search_pdf.empty());
1684 flag.setEnabled(false);
1690 static FileName selectTemplateFile()
1692 FileDialog dlg(qt_("Select template file"));
1693 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1694 dlg.setButton1(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
1696 FileDialog::Result result = dlg.open(toqstr(lyxrc.template_path),
1697 QStringList(qt_("LyX Documents (*.lyx)")));
1699 if (result.first == FileDialog::Later)
1701 if (result.second.isEmpty())
1703 return FileName(fromqstr(result.second));
1707 Buffer * GuiView::loadDocument(FileName const & filename, bool tolastfiles)
1711 Buffer * newBuffer = checkAndLoadLyXFile(filename);
1714 message(_("Document not loaded."));
1719 setBuffer(newBuffer);
1721 // scroll to the position when the file was last closed
1722 if (lyxrc.use_lastfilepos) {
1723 LastFilePosSection::FilePos filepos =
1724 theSession().lastFilePos().load(filename);
1725 documentBufferView()->moveToPosition(filepos.pit, filepos.pos, 0, 0);
1729 theSession().lastFiles().add(filename);
1736 void GuiView::openDocument(string const & fname)
1738 string initpath = lyxrc.document_path;
1740 if (documentBufferView()) {
1741 string const trypath = documentBufferView()->buffer().filePath();
1742 // If directory is writeable, use this as default.
1743 if (FileName(trypath).isDirWritable())
1749 if (fname.empty()) {
1750 FileDialog dlg(qt_("Select document to open"), LFUN_FILE_OPEN);
1751 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1752 dlg.setButton2(qt_("Examples|#E#e"),
1753 toqstr(addPath(package().system_support().absFileName(), "examples")));
1755 QStringList filter(qt_("LyX Documents (*.lyx)"));
1756 filter << qt_("LyX-1.3.x Documents (*.lyx13)")
1757 << qt_("LyX-1.4.x Documents (*.lyx14)")
1758 << qt_("LyX-1.5.x Documents (*.lyx15)")
1759 << qt_("LyX-1.6.x Documents (*.lyx16)");
1760 FileDialog::Result result =
1761 dlg.open(toqstr(initpath), filter);
1763 if (result.first == FileDialog::Later)
1766 filename = fromqstr(result.second);
1768 // check selected filename
1769 if (filename.empty()) {
1770 message(_("Canceled."));
1776 // get absolute path of file and add ".lyx" to the filename if
1778 FileName const fullname =
1779 fileSearch(string(), filename, "lyx", support::may_not_exist);
1780 if (!fullname.empty())
1781 filename = fullname.absFileName();
1783 if (!fullname.onlyPath().isDirectory()) {
1784 Alert::warning(_("Invalid filename"),
1785 bformat(_("The directory in the given path\n%1$s\ndoes not exist."),
1786 from_utf8(fullname.absFileName())));
1790 // if the file doesn't exist and isn't already open (bug 6645),
1791 // let the user create one
1792 if (!fullname.exists() && !theBufferList().exists(fullname)) {
1793 // the user specifically chose this name. Believe him.
1794 Buffer * const b = newFile(filename, string(), true);
1800 docstring const disp_fn = makeDisplayPath(filename);
1801 message(bformat(_("Opening document %1$s..."), disp_fn));
1804 Buffer * buf = loadDocument(fullname);
1806 // I don't think this is needed, since it will be done in setBuffer().
1807 // buf->updateBuffer();
1809 buf->errors("Parse");
1810 str2 = bformat(_("Document %1$s opened."), disp_fn);
1811 if (buf->lyxvc().inUse())
1812 str2 += " " + from_utf8(buf->lyxvc().versionString()) +
1813 " " + _("Version control detected.");
1815 str2 = bformat(_("Could not open document %1$s"), disp_fn);
1820 // FIXME: clean that
1821 static bool import(GuiView * lv, FileName const & filename,
1822 string const & format, ErrorList & errorList)
1824 FileName const lyxfile(support::changeExtension(filename.absFileName(), ".lyx"));
1826 string loader_format;
1827 vector<string> loaders = theConverters().loaders();
1828 if (find(loaders.begin(), loaders.end(), format) == loaders.end()) {
1829 for (vector<string>::const_iterator it = loaders.begin();
1830 it != loaders.end(); ++it) {
1831 if (!theConverters().isReachable(format, *it))
1834 string const tofile =
1835 support::changeExtension(filename.absFileName(),
1836 formats.extension(*it));
1837 if (!theConverters().convert(0, filename, FileName(tofile),
1838 filename, format, *it, errorList))
1840 loader_format = *it;
1843 if (loader_format.empty()) {
1844 frontend::Alert::error(_("Couldn't import file"),
1845 bformat(_("No information for importing the format %1$s."),
1846 formats.prettyName(format)));
1850 loader_format = format;
1852 if (loader_format == "lyx") {
1853 Buffer * buf = lv->loadDocument(lyxfile);
1856 // I don't think this is needed, since it will be done in setBuffer().
1857 // buf->updateBuffer();
1859 buf->errors("Parse");
1861 Buffer * const b = newFile(lyxfile.absFileName(), string(), true);
1865 bool as_paragraphs = loader_format == "textparagraph";
1866 string filename2 = (loader_format == format) ? filename.absFileName()
1867 : support::changeExtension(filename.absFileName(),
1868 formats.extension(loader_format));
1869 lv->currentBufferView()->insertPlaintextFile(FileName(filename2),
1871 guiApp->setCurrentView(lv);
1872 lyx::dispatch(FuncRequest(LFUN_MARK_OFF));
1879 void GuiView::importDocument(string const & argument)
1882 string filename = split(argument, format, ' ');
1884 LYXERR(Debug::INFO, format << " file: " << filename);
1886 // need user interaction
1887 if (filename.empty()) {
1888 string initpath = lyxrc.document_path;
1889 if (documentBufferView()) {
1890 string const trypath = documentBufferView()->buffer().filePath();
1891 // If directory is writeable, use this as default.
1892 if (FileName(trypath).isDirWritable())
1896 docstring const text = bformat(_("Select %1$s file to import"),
1897 formats.prettyName(format));
1899 FileDialog dlg(toqstr(text), LFUN_BUFFER_IMPORT);
1900 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1901 dlg.setButton2(qt_("Examples|#E#e"),
1902 toqstr(addPath(package().system_support().absFileName(), "examples")));
1904 docstring filter = formats.prettyName(format);
1907 filter += from_utf8(formats.extension(format));
1910 FileDialog::Result result =
1911 dlg.open(toqstr(initpath), fileFilters(toqstr(filter)));
1913 if (result.first == FileDialog::Later)
1916 filename = fromqstr(result.second);
1918 // check selected filename
1919 if (filename.empty())
1920 message(_("Canceled."));
1923 if (filename.empty())
1926 // get absolute path of file
1927 FileName const fullname(support::makeAbsPath(filename));
1929 FileName const lyxfile(support::changeExtension(fullname.absFileName(), ".lyx"));
1931 // Check if the document already is open
1932 Buffer * buf = theBufferList().getBuffer(lyxfile);
1935 if (!closeBuffer()) {
1936 message(_("Canceled."));
1941 docstring const displaypath = makeDisplayPath(lyxfile.absFileName(), 30);
1943 // if the file exists already, and we didn't do
1944 // -i lyx thefile.lyx, warn
1945 if (lyxfile.exists() && fullname != lyxfile) {
1947 docstring text = bformat(_("The document %1$s already exists.\n\n"
1948 "Do you want to overwrite that document?"), displaypath);
1949 int const ret = Alert::prompt(_("Overwrite document?"),
1950 text, 0, 1, _("&Overwrite"), _("&Cancel"));
1953 message(_("Canceled."));
1958 message(bformat(_("Importing %1$s..."), displaypath));
1959 ErrorList errorList;
1960 if (import(this, fullname, format, errorList))
1961 message(_("imported."));
1963 message(_("file not imported!"));
1965 // FIXME (Abdel 12/08/06): Is there a need to display the error list here?
1969 void GuiView::newDocument(string const & filename, bool from_template)
1971 FileName initpath(lyxrc.document_path);
1972 if (documentBufferView()) {
1973 FileName const trypath(documentBufferView()->buffer().filePath());
1974 // If directory is writeable, use this as default.
1975 if (trypath.isDirWritable())
1979 string templatefile;
1980 if (from_template) {
1981 templatefile = selectTemplateFile().absFileName();
1982 if (templatefile.empty())
1987 if (filename.empty())
1988 b = newUnnamedFile(initpath, to_utf8(_("newfile")), templatefile);
1990 b = newFile(filename, templatefile, true);
1995 // If no new document could be created, it is unsure
1996 // whether there is a valid BufferView.
1997 if (currentBufferView())
1998 // Ensure the cursor is correctly positioned on screen.
1999 currentBufferView()->showCursor();
2003 void GuiView::insertLyXFile(docstring const & fname)
2005 BufferView * bv = documentBufferView();
2010 FileName filename(to_utf8(fname));
2012 if (!filename.empty()) {
2013 bv->insertLyXFile(filename);
2017 // Launch a file browser
2019 string initpath = lyxrc.document_path;
2020 string const trypath = bv->buffer().filePath();
2021 // If directory is writeable, use this as default.
2022 if (FileName(trypath).isDirWritable())
2026 FileDialog dlg(qt_("Select LyX document to insert"), LFUN_FILE_INSERT);
2027 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2028 dlg.setButton2(qt_("Examples|#E#e"),
2029 toqstr(addPath(package().system_support().absFileName(),
2032 FileDialog::Result result = dlg.open(toqstr(initpath),
2033 QStringList(qt_("LyX Documents (*.lyx)")));
2035 if (result.first == FileDialog::Later)
2039 filename.set(fromqstr(result.second));
2041 // check selected filename
2042 if (filename.empty()) {
2043 // emit message signal.
2044 message(_("Canceled."));
2048 bv->insertLyXFile(filename);
2052 void GuiView::insertPlaintextFile(docstring const & fname,
2055 BufferView * bv = documentBufferView();
2059 if (!fname.empty() && !FileName::isAbsolute(to_utf8(fname))) {
2060 message(_("Absolute filename expected."));
2065 FileName filename(to_utf8(fname));
2067 if (!filename.empty()) {
2068 bv->insertPlaintextFile(filename, asParagraph);
2072 FileDialog dlg(qt_("Select file to insert"), (asParagraph ?
2073 LFUN_FILE_INSERT_PLAINTEXT_PARA : LFUN_FILE_INSERT_PLAINTEXT));
2075 FileDialog::Result result = dlg.open(toqstr(bv->buffer().filePath()),
2076 QStringList(qt_("All Files (*)")));
2078 if (result.first == FileDialog::Later)
2082 filename.set(fromqstr(result.second));
2084 // check selected filename
2085 if (filename.empty()) {
2086 // emit message signal.
2087 message(_("Canceled."));
2091 bv->insertPlaintextFile(filename, asParagraph);
2095 bool GuiView::renameBuffer(Buffer & b, docstring const & newname)
2097 FileName fname = b.fileName();
2098 FileName const oldname = fname;
2100 if (!newname.empty()) {
2102 fname = support::makeAbsPath(to_utf8(newname), oldname.onlyPath().absFileName());
2104 // Switch to this Buffer.
2107 // No argument? Ask user through dialog.
2109 FileDialog dlg(qt_("Choose a filename to save document as"),
2110 LFUN_BUFFER_WRITE_AS);
2111 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2112 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
2114 if (!isLyXFileName(fname.absFileName()))
2115 fname.changeExtension(".lyx");
2117 FileDialog::Result result =
2118 dlg.save(toqstr(fname.onlyPath().absFileName()),
2119 QStringList(qt_("LyX Documents (*.lyx)")),
2120 toqstr(fname.onlyFileName()));
2122 if (result.first == FileDialog::Later)
2125 fname.set(fromqstr(result.second));
2130 if (!isLyXFileName(fname.absFileName()))
2131 fname.changeExtension(".lyx");
2134 // fname is now the new Buffer location.
2135 if (FileName(fname).exists()) {
2136 docstring const file = makeDisplayPath(fname.absFileName(), 30);
2137 docstring text = bformat(_("The document %1$s already "
2138 "exists.\n\nDo you want to "
2139 "overwrite that document?"),
2141 int const ret = Alert::prompt(_("Overwrite document?"),
2142 text, 0, 2, _("&Overwrite"), _("&Rename"), _("&Cancel"));
2145 case 1: return renameBuffer(b, docstring());
2146 case 2: return false;
2150 FileName oldauto = b.getAutosaveFileName();
2152 // Ok, change the name of the buffer
2153 b.setFileName(fname.absFileName());
2155 bool unnamed = b.isUnnamed();
2156 b.setUnnamed(false);
2157 b.saveCheckSum(fname);
2159 // bring the autosave file with us, just in case.
2160 b.moveAutosaveFile(oldauto);
2162 if (!saveBuffer(b)) {
2163 oldauto = b.getAutosaveFileName();
2164 b.setFileName(oldname.absFileName());
2165 b.setUnnamed(unnamed);
2166 b.saveCheckSum(oldname);
2167 b.moveAutosaveFile(oldauto);
2171 // the file has now been saved to the new location.
2172 // we need to check that the locations of child buffers
2174 b.checkChildBuffers();
2180 bool GuiView::saveBuffer(Buffer & b)
2182 if (workArea(b) && workArea(b)->inDialogMode())
2186 return renameBuffer(b, docstring());
2189 theSession().lastFiles().add(b.fileName());
2193 // Switch to this Buffer.
2196 // FIXME: we don't tell the user *WHY* the save failed !!
2197 docstring const file = makeDisplayPath(b.absFileName(), 30);
2198 docstring text = bformat(_("The document %1$s could not be saved.\n\n"
2199 "Do you want to rename the document and "
2200 "try again?"), file);
2201 int const ret = Alert::prompt(_("Rename and save?"),
2202 text, 0, 2, _("&Rename"), _("&Retry"), _("&Cancel"));
2205 if (!renameBuffer(b, docstring()))
2214 return saveBuffer(b);
2218 bool GuiView::hideWorkArea(GuiWorkArea * wa)
2220 return closeWorkArea(wa, false);
2224 bool GuiView::closeWorkArea(GuiWorkArea * wa)
2226 Buffer & buf = wa->bufferView().buffer();
2227 return closeWorkArea(wa, !buf.parent());
2231 bool GuiView::closeBuffer()
2233 GuiWorkArea * wa = currentMainWorkArea();
2234 setCurrentWorkArea(wa);
2235 Buffer & buf = wa->bufferView().buffer();
2236 return wa && closeWorkArea(wa, !buf.parent());
2240 void GuiView::writeSession() const {
2241 GuiWorkArea const * active_wa = currentMainWorkArea();
2242 for (int i = 0; i < d.splitter_->count(); ++i) {
2243 TabWorkArea * twa = d.tabWorkArea(i);
2244 for (int j = 0; j < twa->count(); ++j) {
2245 GuiWorkArea * wa = static_cast<GuiWorkArea *>(twa->widget(j));
2246 Buffer & buf = wa->bufferView().buffer();
2247 theSession().lastOpened().add(buf.fileName(), wa == active_wa);
2253 bool GuiView::closeBufferAll()
2255 // Close the workareas in all other views
2256 QList<int> const ids = guiApp->viewIds();
2257 for (int i = 0; i != ids.size(); ++i) {
2258 if (id_ != ids[i] && !guiApp->view(ids[i]).closeWorkAreaAll())
2262 // Close our own workareas
2263 if (!closeWorkAreaAll())
2266 // Now close the hidden buffers. We prevent hidden buffers from being
2267 // dirty, so we can just close them.
2268 theBufferList().closeAll();
2273 bool GuiView::closeWorkAreaAll()
2275 setCurrentWorkArea(currentMainWorkArea());
2277 // We might be in a situation that there is still a tabWorkArea, but
2278 // there are no tabs anymore. This can happen when we get here after a
2279 // TabWorkArea::lastWorkAreaRemoved() signal. Therefore we count how
2280 // many TabWorkArea's have no documents anymore.
2283 // We have to call count() each time, because it can happen that
2284 // more than one splitter will disappear in one iteration (bug 5998).
2285 for (; d.splitter_->count() > empty_twa; ) {
2286 TabWorkArea * twa = d.tabWorkArea(empty_twa);
2288 if (twa->count() == 0)
2291 setCurrentWorkArea(twa->currentWorkArea());
2292 if (!closeTabWorkArea(twa))
2300 bool GuiView::closeWorkArea(GuiWorkArea * wa, bool close_buffer)
2305 Buffer & buf = wa->bufferView().buffer();
2307 if (close_buffer && GuiViewPrivate::busyBuffers.contains(&buf)) {
2308 Alert::warning(_("Close document "), _("Document could not be closed because it is processed by LyX."));
2313 return closeBuffer(buf);
2315 if (!inMultiTabs(wa))
2316 if (!saveBufferIfNeeded(buf, true))
2324 bool GuiView::closeBuffer(Buffer & buf)
2326 // If we are in a close_event all children will be closed in some time,
2327 // so no need to do it here. This will ensure that the children end up
2328 // in the session file in the correct order. If we close the master
2329 // buffer, we can close or release the child buffers here too.
2331 vector<Buffer *> clist = buf.getChildren(false);
2332 for (vector<Buffer *>::const_iterator it = clist.begin();
2333 it != clist.end(); ++it) {
2334 // If a child is dirty, do not close
2335 // without user intervention
2336 //FIXME: should we look in other tabworkareas?
2337 Buffer * child_buf = *it;
2338 GuiWorkArea * child_wa = workArea(*child_buf);
2340 if (!closeWorkArea(child_wa, true))
2343 theBufferList().releaseChild(&buf, child_buf);
2346 // goto bookmark to update bookmark pit.
2347 //FIXME: we should update only the bookmarks related to this buffer!
2348 LYXERR(Debug::DEBUG, "GuiView::closeBuffer()");
2349 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
2350 guiApp->gotoBookmark(i+1, false, false);
2352 if (saveBufferIfNeeded(buf, false)) {
2353 buf.removeAutosaveFile();
2354 theBufferList().release(&buf);
2361 bool GuiView::closeTabWorkArea(TabWorkArea * twa)
2363 while (twa == d.currentTabWorkArea()) {
2364 twa->setCurrentIndex(twa->count()-1);
2366 GuiWorkArea * wa = twa->currentWorkArea();
2367 Buffer & b = wa->bufferView().buffer();
2369 // We only want to close the buffer if the same buffer is not visible
2370 // in another view, and if this is not a child and if we are closing
2371 // a view (not a tabgroup).
2372 bool const close_buffer =
2373 !inMultiViews(wa) && !b.parent() && closing_;
2375 if (!closeWorkArea(wa, close_buffer))
2382 bool GuiView::saveBufferIfNeeded(Buffer & buf, bool hiding)
2384 if (buf.isClean() || buf.paragraphs().empty())
2387 // Switch to this Buffer.
2392 if (buf.isUnnamed())
2393 file = from_utf8(buf.fileName().onlyFileName());
2395 file = buf.fileName().displayName(30);
2397 // Bring this window to top before asking questions.
2402 if (hiding && buf.isUnnamed()) {
2403 docstring const text = bformat(_("The document %1$s has not been "
2404 "saved yet.\n\nDo you want to save "
2405 "the document?"), file);
2406 ret = Alert::prompt(_("Save new document?"),
2407 text, 0, 1, _("&Save"), _("&Cancel"));
2411 docstring const text = bformat(_("The document %1$s has unsaved changes."
2412 "\n\nDo you want to save the document or discard the changes?"), file);
2413 ret = Alert::prompt(_("Save changed document?"),
2414 text, 0, 2, _("&Save"), _("&Discard"), _("&Cancel"));
2419 if (!saveBuffer(buf))
2423 // if we crash after this we could
2424 // have no autosave file but I guess
2425 // this is really improbable (Jug)
2426 // Sometime improbable things happen, bug 6857 (ps)
2427 // buf.removeAutosaveFile();
2429 // revert all changes
2440 bool GuiView::inMultiTabs(GuiWorkArea * wa)
2442 Buffer & buf = wa->bufferView().buffer();
2444 for (int i = 0; i != d.splitter_->count(); ++i) {
2445 GuiWorkArea * wa_ = d.tabWorkArea(i)->workArea(buf);
2446 if (wa_ && wa_ != wa)
2449 return inMultiViews(wa);
2453 bool GuiView::inMultiViews(GuiWorkArea * wa)
2455 QList<int> const ids = guiApp->viewIds();
2456 Buffer & buf = wa->bufferView().buffer();
2459 for (int i = 0; i != ids.size() && found_twa <= 1; ++i) {
2463 if (guiApp->view(ids[i]).workArea(buf))
2470 void GuiView::gotoNextOrPreviousBuffer(NextOrPrevious np)
2472 Buffer * const curbuf = documentBufferView()
2473 ? &documentBufferView()->buffer() : 0;
2474 Buffer * nextbuf = curbuf;
2476 if (np == NEXTBUFFER)
2477 nextbuf = theBufferList().next(nextbuf);
2479 nextbuf = theBufferList().previous(nextbuf);
2480 if (nextbuf == curbuf)
2486 if (workArea(*nextbuf))
2493 /// make sure the document is saved
2494 static bool ensureBufferClean(Buffer * buffer)
2496 LASSERT(buffer, return false);
2497 if (buffer->isClean() && !buffer->isUnnamed())
2500 docstring const file = buffer->fileName().displayName(30);
2503 if (!buffer->isUnnamed()) {
2504 text = bformat(_("The document %1$s has unsaved "
2505 "changes.\n\nDo you want to save "
2506 "the document?"), file);
2507 title = _("Save changed document?");
2510 text = bformat(_("The document %1$s has not been "
2511 "saved yet.\n\nDo you want to save "
2512 "the document?"), file);
2513 title = _("Save new document?");
2515 int const ret = Alert::prompt(title, text, 0, 1, _("&Save"), _("&Cancel"));
2518 dispatch(FuncRequest(LFUN_BUFFER_WRITE));
2520 return buffer->isClean() && !buffer->isUnnamed();
2524 void GuiView::reloadBuffer()
2526 Buffer * buf = &documentBufferView()->buffer();
2531 void GuiView::checkExternallyModifiedBuffers()
2533 BufferList::iterator bit = theBufferList().begin();
2534 BufferList::iterator const bend = theBufferList().end();
2535 for (; bit != bend; ++bit) {
2536 if ((*bit)->fileName().exists()
2537 && (*bit)->isExternallyModified(Buffer::checksum_method)) {
2538 docstring text = bformat(_("Document \n%1$s\n has been externally modified."
2539 " Reload now? Any local changes will be lost."),
2540 from_utf8((*bit)->absFileName()));
2541 int const ret = Alert::prompt(_("Reload externally changed document?"),
2542 text, 0, 1, _("&Reload"), _("&Cancel"));
2550 //FIXME use a DispatchResult object to transmit messages
2551 void GuiView::dispatchVC(FuncRequest const & cmd)
2553 // message for statusbar
2555 Buffer * buffer = documentBufferView()
2556 ? &(documentBufferView()->buffer()) : 0;
2558 switch (cmd.action()) {
2559 case LFUN_VC_REGISTER:
2560 if (!buffer || !ensureBufferClean(buffer))
2562 if (!buffer->lyxvc().inUse()) {
2563 if (buffer->lyxvc().registrer())
2568 case LFUN_VC_CHECK_IN:
2569 if (!buffer || !ensureBufferClean(buffer))
2571 if (buffer->lyxvc().inUse() && !buffer->isReadonly()) {
2572 msg = buffer->lyxvc().checkIn();
2578 case LFUN_VC_CHECK_OUT:
2579 if (!buffer || !ensureBufferClean(buffer))
2581 if (buffer->lyxvc().inUse()) {
2582 msg = buffer->lyxvc().checkOut();
2587 case LFUN_VC_LOCKING_TOGGLE:
2588 LASSERT(buffer, return);
2589 if (!ensureBufferClean(buffer) || buffer->isReadonly())
2591 if (buffer->lyxvc().inUse()) {
2592 string res = buffer->lyxvc().lockingToggle();
2594 frontend::Alert::error(_("Revision control error."),
2595 _("Error when setting the locking property."));
2603 case LFUN_VC_REVERT:
2604 LASSERT(buffer, return);
2605 buffer->lyxvc().revert();
2609 case LFUN_VC_UNDO_LAST:
2610 LASSERT(buffer, return);
2611 buffer->lyxvc().undoLast();
2615 case LFUN_VC_REPO_UPDATE:
2616 LASSERT(buffer, return);
2617 if (ensureBufferClean(buffer)) {
2618 msg = buffer->lyxvc().repoUpdate();
2619 checkExternallyModifiedBuffers();
2623 case LFUN_VC_COMMAND: {
2624 string flag = cmd.getArg(0);
2625 if (buffer && contains(flag, 'R') && !ensureBufferClean(buffer))
2628 if (contains(flag, 'M')) {
2629 if (!Alert::askForText(message, _("LyX VC: Log Message")))
2632 string path = cmd.getArg(1);
2633 if (contains(path, "$$p") && buffer)
2634 path = subst(path, "$$p", buffer->filePath());
2635 LYXERR(Debug::LYXVC, "Directory: " << path);
2637 if (!pp.isReadableDirectory()) {
2638 lyxerr << _("Directory is not accessible.") << endl;
2641 support::PathChanger p(pp);
2643 string command = cmd.getArg(2);
2644 if (command.empty())
2647 command = subst(command, "$$i", buffer->absFileName());
2648 command = subst(command, "$$p", buffer->filePath());
2650 command = subst(command, "$$m", to_utf8(message));
2651 LYXERR(Debug::LYXVC, "Command: " << command);
2653 one.startscript(Systemcall::Wait, command);
2657 if (contains(flag, 'I'))
2658 buffer->markDirty();
2659 if (contains(flag, 'R'))
2665 case LFUN_VC_COMPARE: {
2667 if (cmd.argument().empty()) {
2668 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "comparehistory"));
2672 string rev1 = cmd.getArg(0);
2676 if (!buffer->lyxvc().prepareFileRevision(rev1, f1))
2679 if (isStrInt(rev1) && convert<int>(rev1) <= 0) {
2680 f2 = buffer->absFileName();
2682 string rev2 = cmd.getArg(1);
2686 if (!buffer->lyxvc().prepareFileRevision(rev2, f2))
2690 LYXERR(Debug::LYXVC, "Launching comparison for fetched revisions: " <<
2691 f1 << "\n" << f2 << "\n" );
2692 string par = "compare run " + f1 + " " + f2;
2693 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, par));
2702 message(from_utf8(msg));
2706 void GuiView::openChildDocument(string const & fname)
2708 LASSERT(documentBufferView(), return);
2709 Buffer & buffer = documentBufferView()->buffer();
2710 FileName const filename = support::makeAbsPath(fname, buffer.filePath());
2711 documentBufferView()->saveBookmark(false);
2713 bool parsed = false;
2714 if (theBufferList().exists(filename)) {
2715 child = theBufferList().getBuffer(filename);
2717 message(bformat(_("Opening child document %1$s..."),
2718 makeDisplayPath(filename.absFileName())));
2719 child = loadDocument(filename, false);
2725 // Set the parent name of the child document.
2726 // This makes insertion of citations and references in the child work,
2727 // when the target is in the parent or another child document.
2728 child->setParent(&buffer);
2730 // I don't think this is needed, since it will be called in
2732 // child->masterBuffer()->updateBuffer();
2735 child->errors("Parse");
2739 bool GuiView::goToFileRow(string const & argument)
2743 size_t i = argument.find_last_of(' ');
2744 if (i != string::npos) {
2745 file_name = os::internal_path(trim(argument.substr(0, i)));
2746 istringstream is(argument.substr(i + 1));
2751 if (i == string::npos) {
2752 LYXERR0("Wrong argument: " << argument);
2756 string const abstmp = package().temp_dir().absFileName();
2757 string const realtmp = package().temp_dir().realPath();
2758 // We have to use os::path_prefix_is() here, instead of
2759 // simply prefixIs(), because the file name comes from
2760 // an external application and may need case adjustment.
2761 if (os::path_prefix_is(file_name, abstmp, os::CASE_ADJUSTED)
2762 || os::path_prefix_is(file_name, realtmp, os::CASE_ADJUSTED)) {
2763 // Needed by inverse dvi search. If it is a file
2764 // in tmpdir, call the apropriated function.
2765 // If tmpdir is a symlink, we may have the real
2766 // path passed back, so we correct for that.
2767 if (!prefixIs(file_name, abstmp))
2768 file_name = subst(file_name, realtmp, abstmp);
2769 buf = theBufferList().getBufferFromTmp(file_name);
2771 // Must replace extension of the file to be .lyx
2772 // and get full path
2773 FileName const s = fileSearch(string(),
2774 support::changeExtension(file_name, ".lyx"), "lyx");
2775 // Either change buffer or load the file
2776 if (theBufferList().exists(s))
2777 buf = theBufferList().getBuffer(s);
2778 else if (s.exists()) {
2779 buf = loadDocument(s);
2782 // I don't think this is needed. loadDocument() calls
2783 // setBuffer(), which calls updateBuffer().
2784 // buf->updateBuffer();
2785 buf->errors("Parse");
2788 _("File does not exist: %1$s"),
2789 makeDisplayPath(file_name)));
2794 documentBufferView()->setCursorFromRow(row);
2799 #if (QT_VERSION >= 0x040400)
2800 docstring GuiView::GuiViewPrivate::exportAndDestroy(Buffer const * orig, Buffer * buffer, string const & format)
2802 bool const update_unincluded =
2803 buffer->params().maintain_unincluded_children
2804 && !buffer->params().getIncludedChildren().empty();
2805 bool const success = buffer->doExport(format, true, update_unincluded);
2807 busyBuffers.remove(orig);
2809 ? bformat(_("Successful export to format: %1$s"), from_utf8(format))
2810 : bformat(_("Error exporting to format: %1$s"), from_utf8(format));
2814 docstring GuiView::GuiViewPrivate::previewAndDestroy(Buffer const * orig, Buffer * buffer, string const & format)
2816 bool const update_unincluded =
2817 buffer->params().maintain_unincluded_children
2818 && !buffer->params().getIncludedChildren().empty();
2819 bool const success = buffer->preview(format, update_unincluded);
2821 busyBuffers.remove(orig);
2823 ? bformat(_("Successful preview of format: %1$s"), from_utf8(format))
2824 : bformat(_("Error previewing format: %1$s"), from_utf8(format));
2829 void GuiView::dispatch(FuncRequest const & cmd, DispatchResult & dr)
2831 BufferView * bv = currentBufferView();
2832 // By default we won't need any update.
2833 dr.update(Update::None);
2834 // assume cmd will be dispatched
2835 dr.dispatched(true);
2837 Buffer * doc_buffer = documentBufferView()
2838 ? &(documentBufferView()->buffer()) : 0;
2840 if (cmd.origin() == FuncRequest::TOC) {
2841 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
2842 // FIXME: do we need to pass a DispatchResult object here?
2843 toc->doDispatch(bv->cursor(), cmd);
2847 string const argument = to_utf8(cmd.argument());
2849 switch(cmd.action()) {
2850 case LFUN_BUFFER_CHILD_OPEN:
2851 openChildDocument(to_utf8(cmd.argument()));
2854 case LFUN_BUFFER_IMPORT:
2855 importDocument(to_utf8(cmd.argument()));
2858 case LFUN_BUFFER_EXPORT: {
2861 // GCC only sees strfwd.h when building merged
2862 if (::lyx::operator==(cmd.argument(), "custom")) {
2863 dispatch(FuncRequest(LFUN_DIALOG_SHOW, "sendto"),
2867 if (!doc_buffer->doExport(argument, false)) {
2869 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
2875 case LFUN_BUFFER_UPDATE: {
2878 string format = argument;
2879 if (argument.empty())
2880 format = doc_buffer->getDefaultOutputFormat();
2881 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
2882 d.progress_->clearMessages();
2883 message(_("Exporting ..."));
2884 GuiViewPrivate::busyBuffers.insert(doc_buffer);
2885 QFuture<docstring> f = QtConcurrent::run(GuiViewPrivate::exportAndDestroy,
2886 doc_buffer, doc_buffer->clone(), format);
2887 d.setPreviewFuture(f);
2888 d.last_export_format = doc_buffer->bufferFormat();
2890 bool const update_unincluded =
2891 doc_buffer->params().maintain_unincluded_children
2892 && !doc_buffer->params().getIncludedChildren().empty();
2893 doc_buffer->doExport(format, true, update_unincluded);
2897 case LFUN_BUFFER_VIEW: {
2900 string format = argument;
2901 if (argument.empty())
2902 format = doc_buffer->getDefaultOutputFormat();
2903 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
2904 d.progress_->clearMessages();
2905 message(_("Previewing ..."));
2906 GuiViewPrivate::busyBuffers.insert(doc_buffer);
2907 QFuture<docstring> f = QtConcurrent::run(GuiViewPrivate::previewAndDestroy,
2908 doc_buffer, doc_buffer->clone(), format);
2909 d.setPreviewFuture(f);
2910 d.last_export_format = doc_buffer->bufferFormat();
2912 bool const update_unincluded =
2913 doc_buffer->params().maintain_unincluded_children
2914 && !doc_buffer->params().getIncludedChildren().empty();
2915 doc_buffer->preview(format, update_unincluded);
2919 case LFUN_MASTER_BUFFER_UPDATE: {
2922 string format = argument;
2923 Buffer const * master = doc_buffer->masterBuffer();
2924 if (argument.empty())
2925 format = master->getDefaultOutputFormat();
2926 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
2927 GuiViewPrivate::busyBuffers.insert(master);
2928 QFuture<docstring> f = QtConcurrent::run(GuiViewPrivate::exportAndDestroy,
2929 master, master->clone(), format);
2930 d.setPreviewFuture(f);
2931 d.last_export_format = doc_buffer->bufferFormat();
2933 bool const update_unincluded =
2934 master->params().maintain_unincluded_children
2935 && !master->params().getIncludedChildren().empty();
2936 master->doExport(format, true);
2940 case LFUN_MASTER_BUFFER_VIEW: {
2941 string format = argument;
2942 Buffer const * master = doc_buffer->masterBuffer();
2943 if (argument.empty())
2944 format = master->getDefaultOutputFormat();
2945 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
2946 GuiViewPrivate::busyBuffers.insert(master);
2947 QFuture<docstring> f = QtConcurrent::run(GuiViewPrivate::previewAndDestroy,
2948 master, master->clone(), format);
2949 d.setPreviewFuture(f);
2950 d.last_export_format = doc_buffer->bufferFormat();
2952 master->preview(format);
2956 case LFUN_BUFFER_SWITCH: {
2957 string const file_name = to_utf8(cmd.argument());
2958 if (!FileName::isAbsolute(file_name)) {
2960 dr.setMessage(_("Absolute filename expected."));
2964 Buffer * buffer = theBufferList().getBuffer(FileName(file_name));
2967 dr.setMessage(_("Document not loaded"));
2971 // Do we open or switch to the buffer in this view ?
2972 if (workArea(*buffer)
2973 || lyxrc.open_buffers_in_tabs || !documentBufferView()) {
2978 // Look for the buffer in other views
2979 QList<int> const ids = guiApp->viewIds();
2981 for (; i != ids.size(); ++i) {
2982 GuiView & gv = guiApp->view(ids[i]);
2983 if (gv.workArea(*buffer)) {
2984 gv.activateWindow();
2985 gv.setBuffer(buffer);
2990 // If necessary, open a new window as a last resort
2991 if (i == ids.size()) {
2992 lyx::dispatch(FuncRequest(LFUN_WINDOW_NEW));
2998 case LFUN_BUFFER_NEXT:
2999 gotoNextOrPreviousBuffer(NEXTBUFFER);
3002 case LFUN_BUFFER_PREVIOUS:
3003 gotoNextOrPreviousBuffer(PREVBUFFER);
3006 case LFUN_COMMAND_EXECUTE: {
3007 bool const show_it = cmd.argument() != "off";
3008 // FIXME: this is a hack, "minibuffer" should not be
3010 if (GuiToolbar * t = toolbar("minibuffer")) {
3011 t->setVisible(show_it);
3012 if (show_it && t->commandBuffer())
3013 t->commandBuffer()->setFocus();
3017 case LFUN_DROP_LAYOUTS_CHOICE:
3018 d.layout_->showPopup();
3021 case LFUN_MENU_OPEN:
3022 if (QMenu * menu = guiApp->menus().menu(toqstr(cmd.argument()), *this))
3023 menu->exec(QCursor::pos());
3026 case LFUN_FILE_INSERT:
3027 insertLyXFile(cmd.argument());
3029 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
3030 insertPlaintextFile(cmd.argument(), true);
3033 case LFUN_FILE_INSERT_PLAINTEXT:
3034 insertPlaintextFile(cmd.argument(), false);
3037 case LFUN_BUFFER_RELOAD: {
3038 LASSERT(doc_buffer, break);
3039 docstring const file = makeDisplayPath(doc_buffer->absFileName(), 20);
3040 docstring text = bformat(_("Any changes will be lost. Are you sure "
3041 "you want to revert to the saved version of the document %1$s?"), file);
3042 int const ret = Alert::prompt(_("Revert to saved document?"),
3043 text, 1, 1, _("&Revert"), _("&Cancel"));
3046 doc_buffer->markClean();
3048 dr.forceBufferUpdate();
3053 case LFUN_BUFFER_WRITE:
3054 LASSERT(doc_buffer, break);
3055 saveBuffer(*doc_buffer);
3058 case LFUN_BUFFER_WRITE_AS:
3059 LASSERT(doc_buffer, break);
3060 renameBuffer(*doc_buffer, cmd.argument());
3063 case LFUN_BUFFER_WRITE_ALL: {
3064 Buffer * first = theBufferList().first();
3067 message(_("Saving all documents..."));
3068 // We cannot use a for loop as the buffer list cycles.
3071 if (!b->isClean()) {
3073 LYXERR(Debug::ACTION, "Saved " << b->absFileName());
3075 b = theBufferList().next(b);
3076 } while (b != first);
3077 dr.setMessage(_("All documents saved."));
3081 case LFUN_BUFFER_CLOSE:
3085 case LFUN_BUFFER_CLOSE_ALL:
3089 case LFUN_TOOLBAR_TOGGLE: {
3090 string const name = cmd.getArg(0);
3091 if (GuiToolbar * t = toolbar(name))
3096 case LFUN_DIALOG_UPDATE: {
3097 string const name = to_utf8(cmd.argument());
3098 if (currentBufferView()) {
3099 Inset * inset = currentBufferView()->editedInset(name);
3100 // Can only update a dialog connected to an existing inset
3103 // FIXME: get rid of this indirection; GuiView ask the inset
3104 // if he is kind enough to update itself...
3105 FuncRequest fr(LFUN_INSET_DIALOG_UPDATE, cmd.argument());
3106 //FIXME: pass DispatchResult here?
3107 inset->dispatch(currentBufferView()->cursor(), fr);
3108 } else if (name == "paragraph") {
3109 lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
3110 } else if (name == "prefs" || name == "document") {
3111 updateDialog(name, string());
3116 case LFUN_DIALOG_TOGGLE: {
3117 if (isDialogVisible(cmd.getArg(0)))
3118 dispatch(FuncRequest(LFUN_DIALOG_HIDE, cmd.argument()), dr);
3120 dispatch(FuncRequest(LFUN_DIALOG_SHOW, cmd.argument()), dr);
3124 case LFUN_DIALOG_DISCONNECT_INSET:
3125 disconnectDialog(to_utf8(cmd.argument()));
3128 case LFUN_DIALOG_HIDE: {
3129 guiApp->hideDialogs(to_utf8(cmd.argument()), 0);
3133 case LFUN_DIALOG_SHOW: {
3134 string const name = cmd.getArg(0);
3135 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
3137 if (name == "character") {
3138 data = freefont2string();
3140 showDialog("character", data);
3141 } else if (name == "latexlog") {
3142 Buffer::LogType type;
3143 string const logfile = doc_buffer->logName(&type);
3145 case Buffer::latexlog:
3148 case Buffer::buildlog:
3152 data += Lexer::quoteString(logfile);
3153 showDialog("log", data);
3154 } else if (name == "vclog") {
3155 string const data = "vc " +
3156 Lexer::quoteString(doc_buffer->lyxvc().getLogFile());
3157 showDialog("log", data);
3158 } else if (name == "symbols") {
3159 data = bv->cursor().getEncoding()->name();
3161 showDialog("symbols", data);
3163 } else if (name == "prefs" && isFullScreen()) {
3164 lfunUiToggle("fullscreen");
3165 showDialog("prefs", data);
3167 showDialog(name, data);
3172 dr.setMessage(cmd.argument());
3175 case LFUN_UI_TOGGLE: {
3176 string arg = cmd.getArg(0);
3177 if (!lfunUiToggle(arg)) {
3178 docstring const msg = "ui-toggle " + _("%1$s unknown command!");
3179 dr.setMessage(bformat(msg, from_utf8(arg)));
3181 // Make sure the keyboard focus stays in the work area.
3186 case LFUN_SPLIT_VIEW: {
3187 LASSERT(doc_buffer, break);
3188 string const orientation = cmd.getArg(0);
3189 d.splitter_->setOrientation(orientation == "vertical"
3190 ? Qt::Vertical : Qt::Horizontal);
3191 TabWorkArea * twa = addTabWorkArea();
3192 GuiWorkArea * wa = twa->addWorkArea(*doc_buffer, *this);
3193 setCurrentWorkArea(wa);
3196 case LFUN_CLOSE_TAB_GROUP:
3197 if (TabWorkArea * twa = d.currentTabWorkArea()) {
3198 closeTabWorkArea(twa);
3199 d.current_work_area_ = 0;
3200 twa = d.currentTabWorkArea();
3201 // Switch to the next GuiWorkArea in the found TabWorkArea.
3203 // Make sure the work area is up to date.
3204 setCurrentWorkArea(twa->currentWorkArea());
3206 setCurrentWorkArea(0);
3211 case LFUN_COMPLETION_INLINE:
3212 if (d.current_work_area_)
3213 d.current_work_area_->completer().showInline();
3216 case LFUN_COMPLETION_POPUP:
3217 if (d.current_work_area_)
3218 d.current_work_area_->completer().showPopup();
3222 case LFUN_COMPLETION_COMPLETE:
3223 if (d.current_work_area_)
3224 d.current_work_area_->completer().tab();
3227 case LFUN_COMPLETION_CANCEL:
3228 if (d.current_work_area_) {
3229 if (d.current_work_area_->completer().popupVisible())
3230 d.current_work_area_->completer().hidePopup();
3232 d.current_work_area_->completer().hideInline();
3236 case LFUN_COMPLETION_ACCEPT:
3237 if (d.current_work_area_)
3238 d.current_work_area_->completer().activate();
3241 case LFUN_BUFFER_ZOOM_IN:
3242 case LFUN_BUFFER_ZOOM_OUT:
3243 if (cmd.argument().empty()) {
3244 if (cmd.action() == LFUN_BUFFER_ZOOM_IN)
3249 lyxrc.zoom += convert<int>(cmd.argument());
3251 if (lyxrc.zoom < 10)
3254 // The global QPixmapCache is used in GuiPainter to cache text
3255 // painting so we must reset it.
3256 QPixmapCache::clear();
3257 guiApp->fontLoader().update();
3258 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
3261 case LFUN_VC_REGISTER:
3262 case LFUN_VC_CHECK_IN:
3263 case LFUN_VC_CHECK_OUT:
3264 case LFUN_VC_REPO_UPDATE:
3265 case LFUN_VC_LOCKING_TOGGLE:
3266 case LFUN_VC_REVERT:
3267 case LFUN_VC_UNDO_LAST:
3268 case LFUN_VC_COMMAND:
3269 case LFUN_VC_COMPARE:
3273 case LFUN_SERVER_GOTO_FILE_ROW:
3274 goToFileRow(to_utf8(cmd.argument()));
3277 case LFUN_FORWARD_SEARCH: {
3278 FileName const path(doc_buffer->temppath());
3279 string const texname = doc_buffer->latexName();
3280 FileName const dviname(addName(path.absFileName(),
3281 support::changeExtension(texname, "dvi")));
3282 FileName const pdfname(addName(path.absFileName(),
3283 support::changeExtension(texname, "pdf")));
3284 if (!dviname.exists() && !pdfname.exists()) {
3285 dr.setMessage(_("Please, preview the document first."));
3288 string outname = dviname.onlyFileName();
3289 string command = lyxrc.forward_search_dvi;
3290 if (!dviname.exists() ||
3291 pdfname.lastModified() > dviname.lastModified()) {
3292 outname = pdfname.onlyFileName();
3293 command = lyxrc.forward_search_pdf;
3296 int row = doc_buffer->texrow().getRowFromIdPos(bv->cursor().paragraph().id(), bv->cursor().pos());
3297 LYXERR(Debug::ACTION, "Forward search: row:" << row
3298 << " id:" << bv->cursor().paragraph().id());
3299 if (!row || command.empty()) {
3300 dr.setMessage(_("Couldn't proceed."));
3303 string texrow = convert<string>(row);
3305 command = subst(command, "$$n", texrow);
3306 command = subst(command, "$$t", texname);
3307 command = subst(command, "$$o", outname);
3309 PathChanger p(path);
3311 one.startscript(Systemcall::DontWait, command);
3315 dr.dispatched(false);
3319 // Part of automatic menu appearance feature.
3320 if (isFullScreen()) {
3321 if (menuBar()->isVisible() && lyxrc.full_screen_menubar)
3323 if (statusBar()->isVisible())
3324 statusBar()->hide();
3331 bool GuiView::lfunUiToggle(string const & ui_component)
3333 if (ui_component == "scrollbar") {
3334 // hide() is of no help
3335 if (d.current_work_area_->verticalScrollBarPolicy() ==
3336 Qt::ScrollBarAlwaysOff)
3338 d.current_work_area_->setVerticalScrollBarPolicy(
3339 Qt::ScrollBarAsNeeded);
3341 d.current_work_area_->setVerticalScrollBarPolicy(
3342 Qt::ScrollBarAlwaysOff);
3343 } else if (ui_component == "statusbar") {
3344 statusBar()->setVisible(!statusBar()->isVisible());
3345 } else if (ui_component == "menubar") {
3346 menuBar()->setVisible(!menuBar()->isVisible());
3348 #if QT_VERSION >= 0x040300
3349 if (ui_component == "frame") {
3351 getContentsMargins(&l, &t, &r, &b);
3352 //are the frames in default state?
3353 d.current_work_area_->setFrameStyle(QFrame::NoFrame);
3355 setContentsMargins(-2, -2, -2, -2);
3357 setContentsMargins(0, 0, 0, 0);
3361 if (ui_component == "fullscreen") {
3369 void GuiView::toggleFullScreen()
3371 if (isFullScreen()) {
3372 for (int i = 0; i != d.splitter_->count(); ++i)
3373 d.tabWorkArea(i)->setFullScreen(false);
3374 #if QT_VERSION >= 0x040300
3375 setContentsMargins(0, 0, 0, 0);
3377 setWindowState(windowState() ^ Qt::WindowFullScreen);
3380 statusBar()->show();
3383 hideDialogs("prefs", 0);
3384 for (int i = 0; i != d.splitter_->count(); ++i)
3385 d.tabWorkArea(i)->setFullScreen(true);
3386 #if QT_VERSION >= 0x040300
3387 setContentsMargins(-2, -2, -2, -2);
3390 setWindowState(windowState() ^ Qt::WindowFullScreen);
3391 statusBar()->hide();
3392 if (lyxrc.full_screen_menubar)
3394 if (lyxrc.full_screen_toolbars) {
3395 ToolbarMap::iterator end = d.toolbars_.end();
3396 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
3401 // give dialogs like the TOC a chance to adapt
3406 Buffer const * GuiView::updateInset(Inset const * inset)
3411 Buffer const * inset_buffer = &(inset->buffer());
3413 for (int i = 0; i != d.splitter_->count(); ++i) {
3414 GuiWorkArea * wa = d.tabWorkArea(i)->currentWorkArea();
3417 Buffer const * buffer = &(wa->bufferView().buffer());
3418 if (inset_buffer == buffer)
3419 wa->scheduleRedraw();
3421 return inset_buffer;
3425 void GuiView::restartCursor()
3427 /* When we move around, or type, it's nice to be able to see
3428 * the cursor immediately after the keypress.
3430 if (d.current_work_area_)
3431 d.current_work_area_->startBlinkingCursor();
3433 // Take this occasion to update the other GUI elements.
3439 void GuiView::updateCompletion(Cursor & cur, bool start, bool keep)
3441 if (d.current_work_area_)
3442 d.current_work_area_->completer().updateVisibility(cur, start, keep);
3447 // This list should be kept in sync with the list of insets in
3448 // src/insets/Inset.cpp. I.e., if a dialog goes with an inset, the
3449 // dialog should have the same name as the inset.
3450 // Changes should be also recorded in LFUN_DIALOG_SHOW doxygen
3451 // docs in LyXAction.cpp.
3453 char const * const dialognames[] = {
3455 "aboutlyx", "bibitem", "bibtex", "box", "branch", "changes", "character",
3456 "citation", "compare", "comparehistory", "document", "errorlist", "ert",
3457 "external", "file", "findreplace", "findreplaceadv", "float", "graphics",
3458 "href", "include", "index", "index_print", "info", "listings", "label", "line",
3459 "log", "mathdelimiter", "mathmatrix", "mathspace", "nomenclature",
3460 "nomencl_print", "note", "paragraph", "phantom", "prefs", "print", "ref",
3461 "sendto", "space", "spellchecker", "symbols", "tabular", "tabularcreate",
3462 "thesaurus", "texinfo", "toc", "view-source", "vspace", "wrap", "progress"};
3464 char const * const * const end_dialognames =
3465 dialognames + (sizeof(dialognames) / sizeof(char *));
3469 cmpCStr(char const * name) : name_(name) {}
3470 bool operator()(char const * other) {
3471 return strcmp(other, name_) == 0;
3478 bool isValidName(string const & name)
3480 return find_if(dialognames, end_dialognames,
3481 cmpCStr(name.c_str())) != end_dialognames;
3487 void GuiView::resetDialogs()
3489 // Make sure that no LFUN uses any GuiView.
3490 guiApp->setCurrentView(0);
3493 constructToolbars();
3494 guiApp->menus().fillMenuBar(menuBar(), this, false);
3495 d.layout_->updateContents(true);
3496 // Now update controls with current buffer.
3497 guiApp->setCurrentView(this);
3503 Dialog * GuiView::findOrBuild(string const & name, bool hide_it)
3505 if (!isValidName(name))
3508 map<string, DialogPtr>::iterator it = d.dialogs_.find(name);
3510 if (it != d.dialogs_.end()) {
3512 it->second->hideView();
3513 return it->second.get();
3516 Dialog * dialog = build(name);
3517 d.dialogs_[name].reset(dialog);
3518 if (lyxrc.allow_geometry_session)
3519 dialog->restoreSession();
3526 void GuiView::showDialog(string const & name, string const & data,
3529 triggerShowDialog(toqstr(name), toqstr(data), inset);
3533 void GuiView::doShowDialog(QString const & qname, QString const & qdata,
3539 const string name = fromqstr(qname);
3540 const string data = fromqstr(qdata);
3544 Dialog * dialog = findOrBuild(name, false);
3546 bool const visible = dialog->isVisibleView();
3547 dialog->showData(data);
3548 if (inset && currentBufferView())
3549 currentBufferView()->editInset(name, inset);
3550 // We only set the focus to the new dialog if it was not yet
3551 // visible in order not to change the existing previous behaviour
3553 // activateWindow is needed for floating dockviews
3554 dialog->asQWidget()->raise();
3555 dialog->asQWidget()->activateWindow();
3556 dialog->asQWidget()->setFocus();
3560 catch (ExceptionMessage const & ex) {
3568 bool GuiView::isDialogVisible(string const & name) const
3570 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3571 if (it == d.dialogs_.end())
3573 return it->second.get()->isVisibleView() && !it->second.get()->isClosing();
3577 void GuiView::hideDialog(string const & name, Inset * inset)
3579 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3580 if (it == d.dialogs_.end())
3583 if (inset && currentBufferView()
3584 && inset != currentBufferView()->editedInset(name))
3587 Dialog * const dialog = it->second.get();
3588 if (dialog->isVisibleView())
3590 if (currentBufferView())
3591 currentBufferView()->editInset(name, 0);
3595 void GuiView::disconnectDialog(string const & name)
3597 if (!isValidName(name))
3599 if (currentBufferView())
3600 currentBufferView()->editInset(name, 0);
3604 void GuiView::hideAll() const
3606 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
3607 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3609 for(; it != end; ++it)
3610 it->second->hideView();
3614 void GuiView::updateDialogs()
3616 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
3617 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3619 for(; it != end; ++it) {
3620 Dialog * dialog = it->second.get();
3622 if (dialog->needBufferOpen() && !documentBufferView())
3623 hideDialog(fromqstr(dialog->name()), 0);
3624 else if (dialog->isVisibleView())
3625 dialog->checkStatus();
3632 Dialog * createDialog(GuiView & lv, string const & name);
3634 // will be replaced by a proper factory...
3635 Dialog * createGuiAbout(GuiView & lv);
3636 Dialog * createGuiBibtex(GuiView & lv);
3637 Dialog * createGuiChanges(GuiView & lv);
3638 Dialog * createGuiCharacter(GuiView & lv);
3639 Dialog * createGuiCitation(GuiView & lv);
3640 Dialog * createGuiCompare(GuiView & lv);
3641 Dialog * createGuiCompareHistory(GuiView & lv);
3642 Dialog * createGuiDelimiter(GuiView & lv);
3643 Dialog * createGuiDocument(GuiView & lv);
3644 Dialog * createGuiErrorList(GuiView & lv);
3645 Dialog * createGuiExternal(GuiView & lv);
3646 Dialog * createGuiGraphics(GuiView & lv);
3647 Dialog * createGuiInclude(GuiView & lv);
3648 Dialog * createGuiIndex(GuiView & lv);
3649 Dialog * createGuiLabel(GuiView & lv);
3650 Dialog * createGuiLine(GuiView & lv);
3651 Dialog * createGuiListings(GuiView & lv);
3652 Dialog * createGuiLog(GuiView & lv);
3653 Dialog * createGuiMathMatrix(GuiView & lv);
3654 Dialog * createGuiNomenclature(GuiView & lv);
3655 Dialog * createGuiNote(GuiView & lv);
3656 Dialog * createGuiParagraph(GuiView & lv);
3657 Dialog * createGuiPhantom(GuiView & lv);
3658 Dialog * createGuiPreferences(GuiView & lv);
3659 Dialog * createGuiPrint(GuiView & lv);
3660 Dialog * createGuiPrintindex(GuiView & lv);
3661 Dialog * createGuiPrintNomencl(GuiView & lv);
3662 Dialog * createGuiRef(GuiView & lv);
3663 Dialog * createGuiSearch(GuiView & lv);
3664 Dialog * createGuiSearchAdv(GuiView & lv);
3665 Dialog * createGuiSendTo(GuiView & lv);
3666 Dialog * createGuiShowFile(GuiView & lv);
3667 Dialog * createGuiSpellchecker(GuiView & lv);
3668 Dialog * createGuiSymbols(GuiView & lv);
3669 Dialog * createGuiTabularCreate(GuiView & lv);
3670 Dialog * createGuiTexInfo(GuiView & lv);
3671 Dialog * createGuiToc(GuiView & lv);
3672 Dialog * createGuiThesaurus(GuiView & lv);
3673 Dialog * createGuiHyperlink(GuiView & lv);
3674 Dialog * createGuiViewSource(GuiView & lv);
3675 Dialog * createGuiWrap(GuiView & lv);
3676 Dialog * createGuiProgressView(GuiView & lv);
3680 Dialog * GuiView::build(string const & name)
3682 LASSERT(isValidName(name), return 0);
3684 Dialog * dialog = createDialog(*this, name);
3688 if (name == "aboutlyx")
3689 return createGuiAbout(*this);
3690 if (name == "bibtex")
3691 return createGuiBibtex(*this);
3692 if (name == "changes")
3693 return createGuiChanges(*this);
3694 if (name == "character")
3695 return createGuiCharacter(*this);
3696 if (name == "citation")
3697 return createGuiCitation(*this);
3698 if (name == "compare")
3699 return createGuiCompare(*this);
3700 if (name == "comparehistory")
3701 return createGuiCompareHistory(*this);
3702 if (name == "document")
3703 return createGuiDocument(*this);
3704 if (name == "errorlist")
3705 return createGuiErrorList(*this);
3706 if (name == "external")
3707 return createGuiExternal(*this);
3709 return createGuiShowFile(*this);
3710 if (name == "findreplace")
3711 return createGuiSearch(*this);
3712 if (name == "findreplaceadv")
3713 return createGuiSearchAdv(*this);
3714 if (name == "graphics")
3715 return createGuiGraphics(*this);
3717 return createGuiHyperlink(*this);
3718 if (name == "include")
3719 return createGuiInclude(*this);
3720 if (name == "index")
3721 return createGuiIndex(*this);
3722 if (name == "index_print")
3723 return createGuiPrintindex(*this);
3724 if (name == "label")
3725 return createGuiLabel(*this);
3727 return createGuiLine(*this);
3728 if (name == "listings")
3729 return createGuiListings(*this);
3731 return createGuiLog(*this);
3732 if (name == "mathdelimiter")
3733 return createGuiDelimiter(*this);
3734 if (name == "mathmatrix")
3735 return createGuiMathMatrix(*this);
3736 if (name == "nomenclature")
3737 return createGuiNomenclature(*this);
3738 if (name == "nomencl_print")
3739 return createGuiPrintNomencl(*this);
3741 return createGuiNote(*this);
3742 if (name == "paragraph")
3743 return createGuiParagraph(*this);
3744 if (name == "phantom")
3745 return createGuiPhantom(*this);
3746 if (name == "prefs")
3747 return createGuiPreferences(*this);
3748 if (name == "print")
3749 return createGuiPrint(*this);
3751 return createGuiRef(*this);
3752 if (name == "sendto")
3753 return createGuiSendTo(*this);
3754 if (name == "spellchecker")
3755 return createGuiSpellchecker(*this);
3756 if (name == "symbols")
3757 return createGuiSymbols(*this);
3758 if (name == "tabularcreate")
3759 return createGuiTabularCreate(*this);
3760 if (name == "texinfo")
3761 return createGuiTexInfo(*this);
3762 if (name == "thesaurus")
3763 return createGuiThesaurus(*this);
3765 return createGuiToc(*this);
3766 if (name == "view-source")
3767 return createGuiViewSource(*this);
3769 return createGuiWrap(*this);
3770 if (name == "progress")
3771 return createGuiProgressView(*this);
3777 } // namespace frontend
3780 #include "moc_GuiView.cpp"