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);
372 // TODO syncFunc/previewFunc: use bind
373 bool asyncBufferProcessing(
374 string const & argument,
375 Buffer const * used_buffer,
376 docstring const & msg,
377 docstring (*asyncFunc)(Buffer const *, Buffer *, string const &),
378 bool (Buffer::*syncFunc)(string const &, bool, bool) const,
379 bool (Buffer::*previewFunc)(string const &, bool) const);
384 QSet<Buffer const *> GuiView::GuiViewPrivate::busyBuffers;
387 GuiView::GuiView(int id)
388 : d(*new GuiViewPrivate(this)), id_(id), closing_(false)
390 // GuiToolbars *must* be initialised before the menu bar.
391 normalSizedIcons(); // at least on Mac the default is 32 otherwise, which is huge
394 // set ourself as the current view. This is needed for the menu bar
395 // filling, at least for the static special menu item on Mac. Otherwise
396 // they are greyed out.
397 guiApp->setCurrentView(this);
399 // Fill up the menu bar.
400 guiApp->menus().fillMenuBar(menuBar(), this, true);
402 setCentralWidget(d.stack_widget_);
404 // Start autosave timer
405 if (lyxrc.autosave) {
406 d.autosave_timeout_.timeout.connect(bind(&GuiView::autoSave, this));
407 d.autosave_timeout_.setTimeout(lyxrc.autosave * 1000);
408 d.autosave_timeout_.start();
410 connect(&d.statusbar_timer_, SIGNAL(timeout()),
411 this, SLOT(clearMessage()));
413 // We don't want to keep the window in memory if it is closed.
414 setAttribute(Qt::WA_DeleteOnClose, true);
416 #if (!defined(Q_WS_WIN) && !defined(Q_WS_MACX))
417 // assign an icon to main form. We do not do it under Qt/Win or Qt/Mac,
418 // since the icon is provided in the application bundle.
419 setWindowIcon(getPixmap("images/", "lyx", "png"));
422 #if (QT_VERSION >= 0x040300)
423 // use tabbed dock area for multiple docks
424 // (such as "source" and "messages")
425 setDockOptions(QMainWindow::ForceTabbedDocks);
429 setAcceptDrops(true);
431 statusBar()->setSizeGripEnabled(true);
434 #if (QT_VERSION >= 0x040400)
435 connect(&d.autosave_watcher_, SIGNAL(finished()), this,
436 SLOT(threadFinished()));
437 connect(&d.preview_watcher_, SIGNAL(finished()), this,
438 SLOT(threadFinished()));
441 connect(this, SIGNAL(triggerShowDialog(QString const &, QString const &, Inset *)),
442 SLOT(doShowDialog(QString const &, QString const &, Inset *)));
444 // Forbid too small unresizable window because it can happen
445 // with some window manager under X11.
446 setMinimumSize(300, 200);
448 if (lyxrc.allow_geometry_session) {
449 // Now take care of session management.
454 // no session handling, default to a sane size.
455 setGeometry(50, 50, 690, 510);
458 // clear session data if any.
460 settings.remove("views");
470 void GuiView::threadFinished()
472 #if (QT_VERSION >= 0x040400)
473 QFutureWatcher<docstring> const * watcher =
474 static_cast<QFutureWatcher<docstring> const *>(sender());
475 message(watcher->result());
477 errors(d.last_export_format);
482 void GuiView::saveLayout() const
485 settings.beginGroup("views");
486 settings.beginGroup(QString::number(id_));
488 settings.setValue("pos", pos());
489 settings.setValue("size", size());
491 settings.setValue("geometry", saveGeometry());
493 settings.setValue("layout", saveState(0));
494 settings.setValue("icon_size", iconSize());
498 bool GuiView::restoreLayout()
501 settings.beginGroup("views");
502 settings.beginGroup(QString::number(id_));
503 QString const icon_key = "icon_size";
504 if (!settings.contains(icon_key))
507 //code below is skipped when when ~/.config/LyX is (re)created
508 setIconSize(settings.value(icon_key).toSize());
510 QPoint pos = settings.value("pos", QPoint(50, 50)).toPoint();
511 QSize size = settings.value("size", QSize(690, 510)).toSize();
515 // Work-around for bug #6034: the window ends up in an undetermined
516 // state when trying to restore a maximized window when it is
517 // already maximized.
518 if (!(windowState() & Qt::WindowMaximized))
519 if (!restoreGeometry(settings.value("geometry").toByteArray()))
520 setGeometry(50, 50, 690, 510);
522 // Make sure layout is correctly oriented.
523 setLayoutDirection(qApp->layoutDirection());
525 // Allow the toc and view-source dock widget to be restored if needed.
527 if ((dialog = findOrBuild("toc", true)))
528 // see bug 5082. At least setup title and enabled state.
529 // Visibility will be adjusted by restoreState below.
530 dialog->prepareView();
531 if ((dialog = findOrBuild("view-source", true)))
532 dialog->prepareView();
533 if ((dialog = findOrBuild("progress", true)))
534 dialog->prepareView();
536 if (!restoreState(settings.value("layout").toByteArray(), 0))
543 GuiToolbar * GuiView::toolbar(string const & name)
545 ToolbarMap::iterator it = d.toolbars_.find(name);
546 if (it != d.toolbars_.end())
549 LYXERR(Debug::GUI, "Toolbar::display: no toolbar named " << name);
554 void GuiView::constructToolbars()
556 ToolbarMap::iterator it = d.toolbars_.begin();
557 for (; it != d.toolbars_.end(); ++it)
561 // I don't like doing this here, but the standard toolbar
562 // destroys this object when it's destroyed itself (vfr)
563 d.layout_ = new LayoutBox(*this);
564 d.stack_widget_->addWidget(d.layout_);
565 d.layout_->move(0,0);
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 d.toolbars_[cit->name] = new GuiToolbar(*cit, *this);
575 void GuiView::initToolbars()
577 // extracts the toolbars from the backend
578 Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
579 Toolbars::Infos::iterator end = guiApp->toolbars().end();
580 for (; cit != end; ++cit) {
581 GuiToolbar * tb = toolbar(cit->name);
584 int const visibility = guiApp->toolbars().defaultVisibility(cit->name);
585 bool newline = !(visibility & Toolbars::SAMEROW);
586 tb->setVisible(false);
587 tb->setVisibility(visibility);
589 if (visibility & Toolbars::TOP) {
591 addToolBarBreak(Qt::TopToolBarArea);
592 addToolBar(Qt::TopToolBarArea, tb);
595 if (visibility & Toolbars::BOTTOM) {
596 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
597 #if (QT_VERSION >= 0x040202)
599 addToolBarBreak(Qt::BottomToolBarArea);
601 addToolBar(Qt::BottomToolBarArea, tb);
604 if (visibility & Toolbars::LEFT) {
605 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
606 #if (QT_VERSION >= 0x040202)
608 addToolBarBreak(Qt::LeftToolBarArea);
610 addToolBar(Qt::LeftToolBarArea, tb);
613 if (visibility & Toolbars::RIGHT) {
614 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
615 #if (QT_VERSION >= 0x040202)
617 addToolBarBreak(Qt::RightToolBarArea);
619 addToolBar(Qt::RightToolBarArea, tb);
622 if (visibility & Toolbars::ON)
623 tb->setVisible(true);
628 TocModels & GuiView::tocModels()
630 return d.toc_models_;
634 void GuiView::setFocus()
636 LYXERR(Debug::DEBUG, "GuiView::setFocus()" << this);
637 QMainWindow::setFocus();
641 void GuiView::focusInEvent(QFocusEvent * e)
643 LYXERR(Debug::DEBUG, "GuiView::focusInEvent()" << this);
644 QMainWindow::focusInEvent(e);
645 // Make sure guiApp points to the correct view.
646 guiApp->setCurrentView(this);
647 if (currentMainWorkArea())
648 currentMainWorkArea()->setFocus();
649 else if (currentWorkArea())
650 currentWorkArea()->setFocus();
652 d.bg_widget_->setFocus();
656 QMenu * GuiView::createPopupMenu()
658 return d.toolBarPopup(this);
662 void GuiView::showEvent(QShowEvent * e)
664 LYXERR(Debug::GUI, "Passed Geometry "
665 << size().height() << "x" << size().width()
666 << "+" << pos().x() << "+" << pos().y());
668 if (d.splitter_->count() == 0)
669 // No work area, switch to the background widget.
672 QMainWindow::showEvent(e);
676 bool GuiView::closeScheduled()
683 /** Destroy only all tabbed WorkAreas. Destruction of other WorkAreas
684 ** is responsibility of the container (e.g., dialog)
686 void GuiView::closeEvent(QCloseEvent * close_event)
688 LYXERR(Debug::DEBUG, "GuiView::closeEvent()");
690 if (!GuiViewPrivate::busyBuffers.isEmpty()) {
691 Alert::warning(_("Exit LyX"), _("LyX could not be closed because documents are processed by LyX."));
692 close_event->setAccepted(false);
696 // If the user pressed the x (so we didn't call closeView
697 // programmatically), we want to clear all existing entries.
699 theSession().lastOpened().clear();
704 // it can happen that this event arrives without selecting the view,
705 // e.g. when clicking the close button on a background window.
707 if (!closeWorkAreaAll()) {
709 close_event->ignore();
713 // Make sure that nothing will use this to be closed View.
714 guiApp->unregisterView(this);
716 if (isFullScreen()) {
717 // Switch off fullscreen before closing.
722 // Make sure the timer time out will not trigger a statusbar update.
723 d.statusbar_timer_.stop();
725 // Saving fullscreen requires additional tweaks in the toolbar code.
726 // It wouldn't also work under linux natively.
727 if (lyxrc.allow_geometry_session) {
728 // Save this window geometry and layout.
730 // Then the toolbar private states.
731 ToolbarMap::iterator end = d.toolbars_.end();
732 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
733 it->second->saveSession();
734 // Now take care of all other dialogs:
735 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
736 for (; it!= d.dialogs_.end(); ++it)
737 it->second->saveSession();
740 close_event->accept();
744 void GuiView::dragEnterEvent(QDragEnterEvent * event)
746 if (event->mimeData()->hasUrls())
748 /// \todo Ask lyx-devel is this is enough:
749 /// if (event->mimeData()->hasFormat("text/plain"))
750 /// event->acceptProposedAction();
754 void GuiView::dropEvent(QDropEvent * event)
756 QList<QUrl> files = event->mimeData()->urls();
760 LYXERR(Debug::GUI, "GuiView::dropEvent: got URLs!");
761 for (int i = 0; i != files.size(); ++i) {
762 string const file = os::internal_path(fromqstr(
763 files.at(i).toLocalFile()));
767 string const ext = support::getExtension(file);
768 vector<const Format *> found_formats;
770 // Find all formats that have the correct extension.
771 vector<const Format *> const & import_formats
772 = theConverters().importableFormats();
773 vector<const Format *>::const_iterator it = import_formats.begin();
774 for (; it != import_formats.end(); ++it)
775 if ((*it)->extension() == ext)
776 found_formats.push_back(*it);
779 if (found_formats.size() >= 1) {
780 if (found_formats.size() > 1) {
781 //FIXME: show a dialog to choose the correct importable format
783 "Multiple importable formats found, selecting first");
785 string const arg = found_formats[0]->name() + " " + file;
786 cmd = FuncRequest(LFUN_BUFFER_IMPORT, arg);
789 //FIXME: do we have to explicitly check whether it's a lyx file?
791 "No formats found, trying to open it as a lyx file");
792 cmd = FuncRequest(LFUN_FILE_OPEN, file);
795 // Asynchronously post the event. DropEvent usually comes
796 // from the BufferView. But reloading a file might close
797 // the BufferView from within its own event handler.
798 guiApp->dispatchDelayed(cmd);
804 void GuiView::message(docstring const & str)
806 if (ForkedProcess::iAmAChild())
809 // call is moved to GUI-thread by GuiProgress
810 d.progress_->appendMessage(toqstr(str));
814 void GuiView::clearMessageText()
816 message(docstring());
820 void GuiView::updateStatusBarMessage(QString const & str)
822 statusBar()->showMessage(str);
823 d.statusbar_timer_.stop();
824 d.statusbar_timer_.start(3000);
828 void GuiView::smallSizedIcons()
830 setIconSize(QSize(d.smallIconSize, d.smallIconSize));
834 void GuiView::normalSizedIcons()
836 setIconSize(QSize(d.normalIconSize, d.normalIconSize));
840 void GuiView::bigSizedIcons()
842 setIconSize(QSize(d.bigIconSize, d.bigIconSize));
846 void GuiView::clearMessage()
848 // FIXME: This code was introduced in r19643 to fix bug #4123. However,
849 // the hasFocus function mostly returns false, even if the focus is on
850 // a workarea in this view.
854 d.statusbar_timer_.stop();
858 void GuiView::updateWindowTitle(GuiWorkArea * wa)
860 if (wa != d.current_work_area_
861 || wa->bufferView().buffer().isInternal())
863 setWindowTitle(qt_("LyX: ") + wa->windowTitle());
864 setWindowIconText(wa->windowIconText());
868 void GuiView::on_currentWorkAreaChanged(GuiWorkArea * wa)
871 disconnectBufferView();
872 connectBufferView(wa->bufferView());
873 connectBuffer(wa->bufferView().buffer());
874 d.current_work_area_ = wa;
875 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
876 this, SLOT(updateWindowTitle(GuiWorkArea *)));
877 updateWindowTitle(wa);
881 // The document settings needs to be reinitialised.
882 updateDialog("document", "");
884 // Buffer-dependent dialogs must be updated. This is done here because
885 // some dialogs require buffer()->text.
890 void GuiView::on_lastWorkAreaRemoved()
893 // We already are in a close event. Nothing more to do.
896 if (d.splitter_->count() > 1)
897 // We have a splitter so don't close anything.
900 // Reset and updates the dialogs.
901 d.toc_models_.reset(0);
902 updateDialog("document", "");
905 resetWindowTitleAndIconText();
908 if (lyxrc.open_buffers_in_tabs)
909 // Nothing more to do, the window should stay open.
912 if (guiApp->viewIds().size() > 1) {
918 // On Mac we also close the last window because the application stay
919 // resident in memory. On other platforms we don't close the last
920 // window because this would quit the application.
926 void GuiView::updateStatusBar()
928 // let the user see the explicit message
929 if (d.statusbar_timer_.isActive())
936 void GuiView::showMessage()
938 QString msg = toqstr(theGuiApp()->viewStatusMessage());
940 BufferView const * bv = currentBufferView();
942 msg = toqstr(bv->cursor().currentState());
944 msg = qt_("Welcome to LyX!");
946 statusBar()->showMessage(msg);
950 bool GuiView::event(QEvent * e)
954 // Useful debug code:
955 //case QEvent::ActivationChange:
956 //case QEvent::WindowDeactivate:
957 //case QEvent::Paint:
958 //case QEvent::Enter:
959 //case QEvent::Leave:
960 //case QEvent::HoverEnter:
961 //case QEvent::HoverLeave:
962 //case QEvent::HoverMove:
963 //case QEvent::StatusTip:
964 //case QEvent::DragEnter:
965 //case QEvent::DragLeave:
969 case QEvent::WindowActivate: {
970 GuiView * old_view = guiApp->currentView();
971 if (this == old_view) {
973 return QMainWindow::event(e);
975 if (old_view && old_view->currentBufferView()) {
976 // save current selection to the selection buffer to allow
977 // middle-button paste in this window.
978 cap::saveSelection(old_view->currentBufferView()->cursor());
980 guiApp->setCurrentView(this);
981 if (d.current_work_area_) {
982 BufferView & bv = d.current_work_area_->bufferView();
983 connectBufferView(bv);
984 connectBuffer(bv.buffer());
985 // The document structure, name and dialogs might have
986 // changed in another view.
988 // The document settings needs to be reinitialised.
989 updateDialog("document", "");
992 resetWindowTitleAndIconText();
995 return QMainWindow::event(e);
998 case QEvent::ShortcutOverride: {
1001 #if (!defined Q_WS_X11) || (QT_VERSION >= 0x040500)
1002 if (isFullScreen() && menuBar()->isHidden()) {
1003 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
1004 // FIXME: we should also try to detect special LyX shortcut such as
1005 // Alt-P and Alt-M. Right now there is a hack in
1006 // GuiWorkArea::processKeySym() that hides again the menubar for
1008 if (ke->modifiers() & Qt::AltModifier && ke->key() != Qt::Key_Alt) {
1010 return QMainWindow::event(e);
1014 return QMainWindow::event(e);
1018 return QMainWindow::event(e);
1022 void GuiView::resetWindowTitleAndIconText()
1024 setWindowTitle(qt_("LyX"));
1025 setWindowIconText(qt_("LyX"));
1028 bool GuiView::focusNextPrevChild(bool /*next*/)
1035 bool GuiView::busy() const
1041 void GuiView::setBusy(bool busy)
1044 if (d.current_work_area_) {
1045 d.current_work_area_->setUpdatesEnabled(!busy);
1047 d.current_work_area_->stopBlinkingCursor();
1049 d.current_work_area_->startBlinkingCursor();
1053 QApplication::setOverrideCursor(Qt::WaitCursor);
1055 QApplication::restoreOverrideCursor();
1059 GuiWorkArea * GuiView::workArea(Buffer & buffer)
1061 if (currentWorkArea()
1062 && ¤tWorkArea()->bufferView().buffer() == &buffer)
1063 return (GuiWorkArea *) currentWorkArea();
1064 if (TabWorkArea * twa = d.currentTabWorkArea())
1065 return twa->workArea(buffer);
1070 GuiWorkArea * GuiView::addWorkArea(Buffer & buffer)
1072 // Automatically create a TabWorkArea if there are none yet.
1073 TabWorkArea * tab_widget = d.splitter_->count()
1074 ? d.currentTabWorkArea() : addTabWorkArea();
1075 return tab_widget->addWorkArea(buffer, *this);
1079 TabWorkArea * GuiView::addTabWorkArea()
1081 TabWorkArea * twa = new TabWorkArea;
1082 QObject::connect(twa, SIGNAL(currentWorkAreaChanged(GuiWorkArea *)),
1083 this, SLOT(on_currentWorkAreaChanged(GuiWorkArea *)));
1084 QObject::connect(twa, SIGNAL(lastWorkAreaRemoved()),
1085 this, SLOT(on_lastWorkAreaRemoved()));
1087 d.splitter_->addWidget(twa);
1088 d.stack_widget_->setCurrentWidget(d.splitter_);
1093 GuiWorkArea const * GuiView::currentWorkArea() const
1095 return d.current_work_area_;
1099 GuiWorkArea * GuiView::currentWorkArea()
1101 return d.current_work_area_;
1105 GuiWorkArea const * GuiView::currentMainWorkArea() const
1107 if (!d.currentTabWorkArea())
1109 return d.currentTabWorkArea()->currentWorkArea();
1113 GuiWorkArea * GuiView::currentMainWorkArea()
1115 if (!d.currentTabWorkArea())
1117 return d.currentTabWorkArea()->currentWorkArea();
1121 void GuiView::setCurrentWorkArea(GuiWorkArea * wa)
1123 LYXERR(Debug::DEBUG, "Setting current wa: " << wa << endl);
1125 d.current_work_area_ = 0;
1130 // FIXME: I've no clue why this is here and why it accesses
1131 // theGuiApp()->currentView, which might be 0 (bug 6464).
1132 // See also 27525 (vfr).
1133 if (theGuiApp()->currentView() == this
1134 && theGuiApp()->currentView()->currentWorkArea() == wa)
1137 if (currentBufferView())
1138 cap::saveSelection(currentBufferView()->cursor());
1140 theGuiApp()->setCurrentView(this);
1141 d.current_work_area_ = wa;
1142 for (int i = 0; i != d.splitter_->count(); ++i) {
1143 if (d.tabWorkArea(i)->setCurrentWorkArea(wa)) {
1144 //if (d.current_main_work_area_)
1145 // d.current_main_work_area_->setFrameStyle(QFrame::NoFrame);
1146 d.current_main_work_area_ = wa;
1147 //d.current_main_work_area_->setFrameStyle(QFrame::Box | QFrame::Plain);
1148 //d.current_main_work_area_->setLineWidth(2);
1149 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() << ", Current main wa: " << currentMainWorkArea());
1153 LYXERR(Debug::DEBUG, "This is not a tabbed wa");
1154 on_currentWorkAreaChanged(wa);
1155 BufferView & bv = wa->bufferView();
1156 bv.cursor().fixIfBroken();
1158 wa->setUpdatesEnabled(true);
1159 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() << ", Current main wa: " << currentMainWorkArea());
1163 void GuiView::removeWorkArea(GuiWorkArea * wa)
1165 LASSERT(wa, return);
1166 if (wa == d.current_work_area_) {
1168 disconnectBufferView();
1169 d.current_work_area_ = 0;
1170 d.current_main_work_area_ = 0;
1173 bool found_twa = false;
1174 for (int i = 0; i != d.splitter_->count(); ++i) {
1175 TabWorkArea * twa = d.tabWorkArea(i);
1176 if (twa->removeWorkArea(wa)) {
1177 // Found in this tab group, and deleted the GuiWorkArea.
1179 if (twa->count() != 0) {
1180 if (d.current_work_area_ == 0)
1181 // This means that we are closing the current GuiWorkArea, so
1182 // switch to the next GuiWorkArea in the found TabWorkArea.
1183 setCurrentWorkArea(twa->currentWorkArea());
1185 // No more WorkAreas in this tab group, so delete it.
1192 // It is not a tabbed work area (i.e., the search work area), so it
1193 // should be deleted by other means.
1194 LASSERT(found_twa, /* */);
1196 if (d.current_work_area_ == 0) {
1197 if (d.splitter_->count() != 0) {
1198 TabWorkArea * twa = d.currentTabWorkArea();
1199 setCurrentWorkArea(twa->currentWorkArea());
1201 // No more work areas, switch to the background widget.
1202 setCurrentWorkArea(0);
1208 LayoutBox * GuiView::getLayoutDialog() const
1214 void GuiView::updateLayoutList()
1217 d.layout_->updateContents(false);
1221 void GuiView::updateToolbars()
1223 ToolbarMap::iterator end = d.toolbars_.end();
1224 if (d.current_work_area_) {
1226 d.current_work_area_->bufferView().cursor().inMathed()
1227 && !d.current_work_area_->bufferView().cursor().inRegexped();
1229 lyx::getStatus(FuncRequest(LFUN_LAYOUT_TABULAR)).enabled();
1231 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).enabled() &&
1232 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).onOff(true);
1233 bool const mathmacrotemplate =
1234 lyx::getStatus(FuncRequest(LFUN_IN_MATHMACROTEMPLATE)).enabled();
1236 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1237 it->second->update(math, table, review, mathmacrotemplate);
1239 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1240 it->second->update(false, false, false, false);
1244 void GuiView::setBuffer(Buffer * newBuffer)
1246 LYXERR(Debug::DEBUG, "Setting buffer: " << newBuffer << endl);
1247 LASSERT(newBuffer, return);
1250 GuiWorkArea * wa = workArea(*newBuffer);
1252 newBuffer->masterBuffer()->updateBuffer();
1253 wa = addWorkArea(*newBuffer);
1255 //Disconnect the old buffer...there's no new one.
1258 connectBuffer(*newBuffer);
1259 connectBufferView(wa->bufferView());
1260 setCurrentWorkArea(wa);
1266 void GuiView::connectBuffer(Buffer & buf)
1268 buf.setGuiDelegate(this);
1272 void GuiView::disconnectBuffer()
1274 if (d.current_work_area_)
1275 d.current_work_area_->bufferView().buffer().setGuiDelegate(0);
1279 void GuiView::connectBufferView(BufferView & bv)
1281 bv.setGuiDelegate(this);
1285 void GuiView::disconnectBufferView()
1287 if (d.current_work_area_)
1288 d.current_work_area_->bufferView().setGuiDelegate(0);
1292 void GuiView::errors(string const & error_type, bool from_master)
1294 ErrorList & el = from_master ?
1295 currentBufferView()->buffer().masterBuffer()->errorList(error_type)
1296 : currentBufferView()->buffer().errorList(error_type);
1297 string data = error_type;
1299 data = "from_master|" + error_type;
1301 showDialog("errorlist", data);
1305 void GuiView::updateTocItem(string const & type, DocIterator const & dit)
1307 d.toc_models_.updateItem(toqstr(type), dit);
1311 void GuiView::structureChanged()
1313 d.toc_models_.reset(documentBufferView());
1314 // Navigator needs more than a simple update in this case. It needs to be
1316 updateDialog("toc", "");
1320 void GuiView::updateDialog(string const & name, string const & data)
1322 if (!isDialogVisible(name))
1325 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
1326 if (it == d.dialogs_.end())
1329 Dialog * const dialog = it->second.get();
1330 if (dialog->isVisibleView())
1331 dialog->initialiseParams(data);
1335 BufferView * GuiView::documentBufferView()
1337 return currentMainWorkArea()
1338 ? ¤tMainWorkArea()->bufferView()
1343 BufferView const * GuiView::documentBufferView() const
1345 return currentMainWorkArea()
1346 ? ¤tMainWorkArea()->bufferView()
1351 BufferView * GuiView::currentBufferView()
1353 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1357 BufferView const * GuiView::currentBufferView() const
1359 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1363 #if (QT_VERSION >= 0x040400)
1364 docstring GuiView::GuiViewPrivate::saveAndDestroy(Buffer const * orig, Buffer * buffer, FileName const & fname)
1367 FileName const tmp_ret = FileName::tempName("lyxauto");
1368 if (!tmp_ret.empty()) {
1369 if (buffer->writeFile(tmp_ret))
1370 failed = !tmp_ret.moveTo(fname);
1373 // failed to write/rename tmp_ret so try writing direct
1374 failed = buffer->writeFile(fname);
1377 busyBuffers.remove(orig);
1379 ? _("Automatic save failed!")
1380 : _("Automatic save done.");
1385 void GuiView::autoSave()
1387 LYXERR(Debug::INFO, "Running autoSave()");
1389 Buffer * buffer = documentBufferView()
1390 ? &documentBufferView()->buffer() : 0;
1394 #if (QT_VERSION >= 0x040400)
1395 GuiViewPrivate::busyBuffers.insert(buffer);
1396 QFuture<docstring> f = QtConcurrent::run(GuiViewPrivate::saveAndDestroy, buffer, buffer->clone(),
1397 buffer->getAutosaveFileName());
1398 d.autosave_watcher_.setFuture(f);
1405 void GuiView::resetAutosaveTimers()
1408 d.autosave_timeout_.restart();
1412 bool GuiView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1415 Buffer * buf = currentBufferView()
1416 ? ¤tBufferView()->buffer() : 0;
1417 Buffer * doc_buffer = documentBufferView()
1418 ? &(documentBufferView()->buffer()) : 0;
1420 // Check whether we need a buffer
1421 if (!lyxaction.funcHasFlag(cmd.action(), LyXAction::NoBuffer) && !buf) {
1422 // no, exit directly
1423 flag.message(from_utf8(N_("Command not allowed with"
1424 "out any document open")));
1425 flag.setEnabled(false);
1429 if (cmd.origin() == FuncRequest::TOC) {
1430 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
1431 if (!toc || !toc->getStatus(documentBufferView()->cursor(), cmd, flag))
1432 flag.setEnabled(false);
1436 switch(cmd.action()) {
1437 case LFUN_BUFFER_IMPORT:
1440 case LFUN_MASTER_BUFFER_UPDATE:
1441 case LFUN_MASTER_BUFFER_VIEW:
1442 enable = doc_buffer && doc_buffer->parent() != 0
1443 && !d.preview_watcher_.isRunning();
1446 case LFUN_BUFFER_UPDATE:
1447 case LFUN_BUFFER_VIEW: {
1448 if (!doc_buffer || d.preview_watcher_.isRunning()) {
1452 string format = to_utf8(cmd.argument());
1453 if (cmd.argument().empty())
1454 format = doc_buffer->getDefaultOutputFormat();
1455 enable = doc_buffer->isExportableFormat(format);
1459 case LFUN_BUFFER_RELOAD:
1460 enable = doc_buffer && !doc_buffer->isUnnamed()
1461 && doc_buffer->fileName().exists()
1462 && (!doc_buffer->isClean()
1463 || doc_buffer->isExternallyModified(Buffer::timestamp_method));
1466 case LFUN_BUFFER_CHILD_OPEN:
1467 enable = doc_buffer;
1470 case LFUN_BUFFER_WRITE:
1471 enable = doc_buffer && (doc_buffer->isUnnamed() || !doc_buffer->isClean());
1474 //FIXME: This LFUN should be moved to GuiApplication.
1475 case LFUN_BUFFER_WRITE_ALL: {
1476 // We enable the command only if there are some modified buffers
1477 Buffer * first = theBufferList().first();
1482 // We cannot use a for loop as the buffer list is a cycle.
1484 if (!b->isClean()) {
1488 b = theBufferList().next(b);
1489 } while (b != first);
1493 case LFUN_BUFFER_WRITE_AS:
1494 enable = doc_buffer;
1497 case LFUN_BUFFER_CLOSE:
1498 enable = doc_buffer;
1501 case LFUN_BUFFER_CLOSE_ALL:
1502 enable = theBufferList().last() != theBufferList().first();
1505 case LFUN_SPLIT_VIEW:
1506 if (cmd.getArg(0) == "vertical")
1507 enable = doc_buffer && (d.splitter_->count() == 1 ||
1508 d.splitter_->orientation() == Qt::Vertical);
1510 enable = doc_buffer && (d.splitter_->count() == 1 ||
1511 d.splitter_->orientation() == Qt::Horizontal);
1514 case LFUN_CLOSE_TAB_GROUP:
1515 enable = d.currentTabWorkArea();
1518 case LFUN_TOOLBAR_TOGGLE: {
1519 string const name = cmd.getArg(0);
1520 if (GuiToolbar * t = toolbar(name))
1521 flag.setOnOff(t->isVisible());
1524 docstring const msg =
1525 bformat(_("Unknown toolbar \"%1$s\""), from_utf8(name));
1531 case LFUN_DROP_LAYOUTS_CHOICE:
1535 case LFUN_UI_TOGGLE:
1536 flag.setOnOff(isFullScreen());
1539 case LFUN_DIALOG_DISCONNECT_INSET:
1542 case LFUN_DIALOG_HIDE:
1543 // FIXME: should we check if the dialog is shown?
1546 case LFUN_DIALOG_TOGGLE:
1547 flag.setOnOff(isDialogVisible(cmd.getArg(0)));
1548 // fall through to set "enable"
1549 case LFUN_DIALOG_SHOW: {
1550 string const name = cmd.getArg(0);
1552 enable = name == "aboutlyx"
1553 || name == "file" //FIXME: should be removed.
1555 || name == "texinfo"
1556 || name == "progress"
1557 || name == "compare";
1558 else if (name == "print")
1559 enable = doc_buffer->isExportable("dvi")
1560 && lyxrc.print_command != "none";
1561 else if (name == "character" || name == "symbols") {
1562 if (!buf || buf->isReadonly())
1565 // FIXME we should consider passthru
1567 Inset const & in = currentBufferView()->cursor().inset();
1568 enable = !in.getLayout().isPassThru();
1571 else if (name == "latexlog")
1572 enable = FileName(doc_buffer->logName()).isReadableFile();
1573 else if (name == "spellchecker")
1574 enable = theSpellChecker() && !doc_buffer->isReadonly();
1575 else if (name == "vclog")
1576 enable = doc_buffer->lyxvc().inUse();
1580 case LFUN_DIALOG_UPDATE: {
1581 string const name = cmd.getArg(0);
1583 enable = name == "prefs";
1587 case LFUN_COMMAND_EXECUTE:
1589 case LFUN_MENU_OPEN:
1590 // Nothing to check.
1593 case LFUN_COMPLETION_INLINE:
1594 if (!d.current_work_area_
1595 || !d.current_work_area_->completer().inlinePossible(
1596 currentBufferView()->cursor()))
1600 case LFUN_COMPLETION_POPUP:
1601 if (!d.current_work_area_
1602 || !d.current_work_area_->completer().popupPossible(
1603 currentBufferView()->cursor()))
1607 case LFUN_COMPLETION_COMPLETE:
1608 if (!d.current_work_area_
1609 || !d.current_work_area_->completer().inlinePossible(
1610 currentBufferView()->cursor()))
1614 case LFUN_COMPLETION_ACCEPT:
1615 if (!d.current_work_area_
1616 || (!d.current_work_area_->completer().popupVisible()
1617 && !d.current_work_area_->completer().inlineVisible()
1618 && !d.current_work_area_->completer().completionAvailable()))
1622 case LFUN_COMPLETION_CANCEL:
1623 if (!d.current_work_area_
1624 || (!d.current_work_area_->completer().popupVisible()
1625 && !d.current_work_area_->completer().inlineVisible()))
1629 case LFUN_BUFFER_ZOOM_OUT:
1630 enable = doc_buffer && lyxrc.zoom > 10;
1633 case LFUN_BUFFER_ZOOM_IN:
1634 enable = doc_buffer;
1637 case LFUN_BUFFER_NEXT:
1638 case LFUN_BUFFER_PREVIOUS:
1639 // FIXME: should we check is there is an previous or next buffer?
1641 case LFUN_BUFFER_SWITCH:
1642 // toggle on the current buffer, but do not toggle off
1643 // the other ones (is that a good idea?)
1645 && to_utf8(cmd.argument()) == doc_buffer->absFileName())
1646 flag.setOnOff(true);
1649 case LFUN_VC_REGISTER:
1650 enable = doc_buffer && !doc_buffer->lyxvc().inUse();
1652 case LFUN_VC_CHECK_IN:
1653 enable = doc_buffer && doc_buffer->lyxvc().checkInEnabled();
1655 case LFUN_VC_CHECK_OUT:
1656 enable = doc_buffer && doc_buffer->lyxvc().checkOutEnabled();
1658 case LFUN_VC_LOCKING_TOGGLE:
1659 enable = doc_buffer && !doc_buffer->isReadonly()
1660 && doc_buffer->lyxvc().lockingToggleEnabled();
1661 flag.setOnOff(enable && doc_buffer->lyxvc().locking());
1663 case LFUN_VC_REVERT:
1664 enable = doc_buffer && doc_buffer->lyxvc().inUse() && !doc_buffer->isReadonly();
1666 case LFUN_VC_UNDO_LAST:
1667 enable = doc_buffer && doc_buffer->lyxvc().undoLastEnabled();
1669 case LFUN_VC_REPO_UPDATE:
1670 enable = doc_buffer && doc_buffer->lyxvc().repoUpdateEnabled();
1672 case LFUN_VC_COMMAND: {
1673 if (cmd.argument().empty())
1675 if (!doc_buffer && contains(cmd.getArg(0), 'D'))
1679 case LFUN_VC_COMPARE:
1680 enable = doc_buffer && doc_buffer->lyxvc().prepareFileRevisionEnabled();
1683 case LFUN_SERVER_GOTO_FILE_ROW:
1685 case LFUN_FORWARD_SEARCH:
1686 enable = !(lyxrc.forward_search_dvi.empty() && lyxrc.forward_search_pdf.empty());
1694 flag.setEnabled(false);
1700 static FileName selectTemplateFile()
1702 FileDialog dlg(qt_("Select template file"));
1703 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1704 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
1706 FileDialog::Result result = dlg.open(toqstr(lyxrc.template_path),
1707 QStringList(qt_("LyX Documents (*.lyx)")));
1709 if (result.first == FileDialog::Later)
1711 if (result.second.isEmpty())
1713 return FileName(fromqstr(result.second));
1717 Buffer * GuiView::loadDocument(FileName const & filename, bool tolastfiles)
1721 Buffer * newBuffer = checkAndLoadLyXFile(filename);
1724 message(_("Document not loaded."));
1729 setBuffer(newBuffer);
1731 // scroll to the position when the file was last closed
1732 if (lyxrc.use_lastfilepos) {
1733 LastFilePosSection::FilePos filepos =
1734 theSession().lastFilePos().load(filename);
1735 documentBufferView()->moveToPosition(filepos.pit, filepos.pos, 0, 0);
1739 theSession().lastFiles().add(filename);
1746 void GuiView::openDocument(string const & fname)
1748 string initpath = lyxrc.document_path;
1750 if (documentBufferView()) {
1751 string const trypath = documentBufferView()->buffer().filePath();
1752 // If directory is writeable, use this as default.
1753 if (FileName(trypath).isDirWritable())
1759 if (fname.empty()) {
1760 FileDialog dlg(qt_("Select document to open"), LFUN_FILE_OPEN);
1761 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1762 dlg.setButton2(qt_("Examples|#E#e"),
1763 toqstr(addPath(package().system_support().absFileName(), "examples")));
1765 QStringList filter(qt_("LyX Documents (*.lyx)"));
1766 filter << qt_("LyX-1.3.x Documents (*.lyx13)")
1767 << qt_("LyX-1.4.x Documents (*.lyx14)")
1768 << qt_("LyX-1.5.x Documents (*.lyx15)")
1769 << qt_("LyX-1.6.x Documents (*.lyx16)");
1770 FileDialog::Result result =
1771 dlg.open(toqstr(initpath), filter);
1773 if (result.first == FileDialog::Later)
1776 filename = fromqstr(result.second);
1778 // check selected filename
1779 if (filename.empty()) {
1780 message(_("Canceled."));
1786 // get absolute path of file and add ".lyx" to the filename if
1788 FileName const fullname =
1789 fileSearch(string(), filename, "lyx", support::may_not_exist);
1790 if (!fullname.empty())
1791 filename = fullname.absFileName();
1793 if (!fullname.onlyPath().isDirectory()) {
1794 Alert::warning(_("Invalid filename"),
1795 bformat(_("The directory in the given path\n%1$s\ndoes not exist."),
1796 from_utf8(fullname.absFileName())));
1800 // if the file doesn't exist and isn't already open (bug 6645),
1801 // let the user create one
1802 if (!fullname.exists() && !theBufferList().exists(fullname)) {
1803 // the user specifically chose this name. Believe him.
1804 Buffer * const b = newFile(filename, string(), true);
1810 docstring const disp_fn = makeDisplayPath(filename);
1811 message(bformat(_("Opening document %1$s..."), disp_fn));
1814 Buffer * buf = loadDocument(fullname);
1816 // I don't think this is needed, since it will be done in setBuffer().
1817 // buf->updateBuffer();
1819 buf->errors("Parse");
1820 str2 = bformat(_("Document %1$s opened."), disp_fn);
1821 if (buf->lyxvc().inUse())
1822 str2 += " " + from_utf8(buf->lyxvc().versionString()) +
1823 " " + _("Version control detected.");
1825 str2 = bformat(_("Could not open document %1$s"), disp_fn);
1830 // FIXME: clean that
1831 static bool import(GuiView * lv, FileName const & filename,
1832 string const & format, ErrorList & errorList)
1834 FileName const lyxfile(support::changeExtension(filename.absFileName(), ".lyx"));
1836 string loader_format;
1837 vector<string> loaders = theConverters().loaders();
1838 if (find(loaders.begin(), loaders.end(), format) == loaders.end()) {
1839 for (vector<string>::const_iterator it = loaders.begin();
1840 it != loaders.end(); ++it) {
1841 if (!theConverters().isReachable(format, *it))
1844 string const tofile =
1845 support::changeExtension(filename.absFileName(),
1846 formats.extension(*it));
1847 if (!theConverters().convert(0, filename, FileName(tofile),
1848 filename, format, *it, errorList))
1850 loader_format = *it;
1853 if (loader_format.empty()) {
1854 frontend::Alert::error(_("Couldn't import file"),
1855 bformat(_("No information for importing the format %1$s."),
1856 formats.prettyName(format)));
1860 loader_format = format;
1862 if (loader_format == "lyx") {
1863 Buffer * buf = lv->loadDocument(lyxfile);
1866 // I don't think this is needed, since it will be done in setBuffer().
1867 // buf->updateBuffer();
1869 buf->errors("Parse");
1871 Buffer * const b = newFile(lyxfile.absFileName(), string(), true);
1875 bool as_paragraphs = loader_format == "textparagraph";
1876 string filename2 = (loader_format == format) ? filename.absFileName()
1877 : support::changeExtension(filename.absFileName(),
1878 formats.extension(loader_format));
1879 lv->currentBufferView()->insertPlaintextFile(FileName(filename2),
1881 guiApp->setCurrentView(lv);
1882 lyx::dispatch(FuncRequest(LFUN_MARK_OFF));
1889 void GuiView::importDocument(string const & argument)
1892 string filename = split(argument, format, ' ');
1894 LYXERR(Debug::INFO, format << " file: " << filename);
1896 // need user interaction
1897 if (filename.empty()) {
1898 string initpath = lyxrc.document_path;
1899 if (documentBufferView()) {
1900 string const trypath = documentBufferView()->buffer().filePath();
1901 // If directory is writeable, use this as default.
1902 if (FileName(trypath).isDirWritable())
1906 docstring const text = bformat(_("Select %1$s file to import"),
1907 formats.prettyName(format));
1909 FileDialog dlg(toqstr(text), LFUN_BUFFER_IMPORT);
1910 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1911 dlg.setButton2(qt_("Examples|#E#e"),
1912 toqstr(addPath(package().system_support().absFileName(), "examples")));
1914 docstring filter = formats.prettyName(format);
1917 filter += from_utf8(formats.extension(format));
1920 FileDialog::Result result =
1921 dlg.open(toqstr(initpath), fileFilters(toqstr(filter)));
1923 if (result.first == FileDialog::Later)
1926 filename = fromqstr(result.second);
1928 // check selected filename
1929 if (filename.empty())
1930 message(_("Canceled."));
1933 if (filename.empty())
1936 // get absolute path of file
1937 FileName const fullname(support::makeAbsPath(filename));
1939 FileName const lyxfile(support::changeExtension(fullname.absFileName(), ".lyx"));
1941 // Check if the document already is open
1942 Buffer * buf = theBufferList().getBuffer(lyxfile);
1945 if (!closeBuffer()) {
1946 message(_("Canceled."));
1951 docstring const displaypath = makeDisplayPath(lyxfile.absFileName(), 30);
1953 // if the file exists already, and we didn't do
1954 // -i lyx thefile.lyx, warn
1955 if (lyxfile.exists() && fullname != lyxfile) {
1957 docstring text = bformat(_("The document %1$s already exists.\n\n"
1958 "Do you want to overwrite that document?"), displaypath);
1959 int const ret = Alert::prompt(_("Overwrite document?"),
1960 text, 0, 1, _("&Overwrite"), _("&Cancel"));
1963 message(_("Canceled."));
1968 message(bformat(_("Importing %1$s..."), displaypath));
1969 ErrorList errorList;
1970 if (import(this, fullname, format, errorList))
1971 message(_("imported."));
1973 message(_("file not imported!"));
1975 // FIXME (Abdel 12/08/06): Is there a need to display the error list here?
1979 void GuiView::newDocument(string const & filename, bool from_template)
1981 FileName initpath(lyxrc.document_path);
1982 if (documentBufferView()) {
1983 FileName const trypath(documentBufferView()->buffer().filePath());
1984 // If directory is writeable, use this as default.
1985 if (trypath.isDirWritable())
1989 string templatefile;
1990 if (from_template) {
1991 templatefile = selectTemplateFile().absFileName();
1992 if (templatefile.empty())
1997 if (filename.empty())
1998 b = newUnnamedFile(initpath, to_utf8(_("newfile")), templatefile);
2000 b = newFile(filename, templatefile, true);
2005 // If no new document could be created, it is unsure
2006 // whether there is a valid BufferView.
2007 if (currentBufferView())
2008 // Ensure the cursor is correctly positioned on screen.
2009 currentBufferView()->showCursor();
2013 void GuiView::insertLyXFile(docstring const & fname)
2015 BufferView * bv = documentBufferView();
2020 FileName filename(to_utf8(fname));
2022 if (!filename.empty()) {
2023 bv->insertLyXFile(filename);
2027 // Launch a file browser
2029 string initpath = lyxrc.document_path;
2030 string const trypath = bv->buffer().filePath();
2031 // If directory is writeable, use this as default.
2032 if (FileName(trypath).isDirWritable())
2036 FileDialog dlg(qt_("Select LyX document to insert"), LFUN_FILE_INSERT);
2037 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2038 dlg.setButton2(qt_("Examples|#E#e"),
2039 toqstr(addPath(package().system_support().absFileName(),
2042 FileDialog::Result result = dlg.open(toqstr(initpath),
2043 QStringList(qt_("LyX Documents (*.lyx)")));
2045 if (result.first == FileDialog::Later)
2049 filename.set(fromqstr(result.second));
2051 // check selected filename
2052 if (filename.empty()) {
2053 // emit message signal.
2054 message(_("Canceled."));
2058 bv->insertLyXFile(filename);
2062 void GuiView::insertPlaintextFile(docstring const & fname,
2065 BufferView * bv = documentBufferView();
2069 if (!fname.empty() && !FileName::isAbsolute(to_utf8(fname))) {
2070 message(_("Absolute filename expected."));
2075 FileName filename(to_utf8(fname));
2077 if (!filename.empty()) {
2078 bv->insertPlaintextFile(filename, asParagraph);
2082 FileDialog dlg(qt_("Select file to insert"), (asParagraph ?
2083 LFUN_FILE_INSERT_PLAINTEXT_PARA : LFUN_FILE_INSERT_PLAINTEXT));
2085 FileDialog::Result result = dlg.open(toqstr(bv->buffer().filePath()),
2086 QStringList(qt_("All Files (*)")));
2088 if (result.first == FileDialog::Later)
2092 filename.set(fromqstr(result.second));
2094 // check selected filename
2095 if (filename.empty()) {
2096 // emit message signal.
2097 message(_("Canceled."));
2101 bv->insertPlaintextFile(filename, asParagraph);
2105 bool GuiView::renameBuffer(Buffer & b, docstring const & newname)
2107 FileName fname = b.fileName();
2108 FileName const oldname = fname;
2110 if (!newname.empty()) {
2112 fname = support::makeAbsPath(to_utf8(newname), oldname.onlyPath().absFileName());
2114 // Switch to this Buffer.
2117 // No argument? Ask user through dialog.
2119 FileDialog dlg(qt_("Choose a filename to save document as"),
2120 LFUN_BUFFER_WRITE_AS);
2121 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2122 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
2124 if (!isLyXFileName(fname.absFileName()))
2125 fname.changeExtension(".lyx");
2127 FileDialog::Result result =
2128 dlg.save(toqstr(fname.onlyPath().absFileName()),
2129 QStringList(qt_("LyX Documents (*.lyx)")),
2130 toqstr(fname.onlyFileName()));
2132 if (result.first == FileDialog::Later)
2135 fname.set(fromqstr(result.second));
2140 if (!isLyXFileName(fname.absFileName()))
2141 fname.changeExtension(".lyx");
2144 // fname is now the new Buffer location.
2145 if (FileName(fname).exists()) {
2146 docstring const file = makeDisplayPath(fname.absFileName(), 30);
2147 docstring text = bformat(_("The document %1$s already "
2148 "exists.\n\nDo you want to "
2149 "overwrite that document?"),
2151 int const ret = Alert::prompt(_("Overwrite document?"),
2152 text, 0, 2, _("&Overwrite"), _("&Rename"), _("&Cancel"));
2155 case 1: return renameBuffer(b, docstring());
2156 case 2: return false;
2160 FileName oldauto = b.getAutosaveFileName();
2162 // Ok, change the name of the buffer
2163 b.setFileName(fname.absFileName());
2165 bool unnamed = b.isUnnamed();
2166 b.setUnnamed(false);
2167 b.saveCheckSum(fname);
2169 // bring the autosave file with us, just in case.
2170 b.moveAutosaveFile(oldauto);
2172 if (!saveBuffer(b)) {
2173 oldauto = b.getAutosaveFileName();
2174 b.setFileName(oldname.absFileName());
2175 b.setUnnamed(unnamed);
2176 b.saveCheckSum(oldname);
2177 b.moveAutosaveFile(oldauto);
2181 // the file has now been saved to the new location.
2182 // we need to check that the locations of child buffers
2184 b.checkChildBuffers();
2190 bool GuiView::saveBuffer(Buffer & b)
2192 if (workArea(b) && workArea(b)->inDialogMode())
2196 return renameBuffer(b, docstring());
2199 theSession().lastFiles().add(b.fileName());
2203 // Switch to this Buffer.
2206 // FIXME: we don't tell the user *WHY* the save failed !!
2207 docstring const file = makeDisplayPath(b.absFileName(), 30);
2208 docstring text = bformat(_("The document %1$s could not be saved.\n\n"
2209 "Do you want to rename the document and "
2210 "try again?"), file);
2211 int const ret = Alert::prompt(_("Rename and save?"),
2212 text, 0, 2, _("&Rename"), _("&Retry"), _("&Cancel"));
2215 if (!renameBuffer(b, docstring()))
2224 return saveBuffer(b);
2228 bool GuiView::hideWorkArea(GuiWorkArea * wa)
2230 return closeWorkArea(wa, false);
2234 bool GuiView::closeWorkArea(GuiWorkArea * wa)
2236 Buffer & buf = wa->bufferView().buffer();
2237 return closeWorkArea(wa, !buf.parent());
2241 bool GuiView::closeBuffer()
2243 GuiWorkArea * wa = currentMainWorkArea();
2244 setCurrentWorkArea(wa);
2245 Buffer & buf = wa->bufferView().buffer();
2246 return wa && closeWorkArea(wa, !buf.parent());
2250 void GuiView::writeSession() const {
2251 GuiWorkArea const * active_wa = currentMainWorkArea();
2252 for (int i = 0; i < d.splitter_->count(); ++i) {
2253 TabWorkArea * twa = d.tabWorkArea(i);
2254 for (int j = 0; j < twa->count(); ++j) {
2255 GuiWorkArea * wa = static_cast<GuiWorkArea *>(twa->widget(j));
2256 Buffer & buf = wa->bufferView().buffer();
2257 theSession().lastOpened().add(buf.fileName(), wa == active_wa);
2263 bool GuiView::closeBufferAll()
2265 // Close the workareas in all other views
2266 QList<int> const ids = guiApp->viewIds();
2267 for (int i = 0; i != ids.size(); ++i) {
2268 if (id_ != ids[i] && !guiApp->view(ids[i]).closeWorkAreaAll())
2272 // Close our own workareas
2273 if (!closeWorkAreaAll())
2276 // Now close the hidden buffers. We prevent hidden buffers from being
2277 // dirty, so we can just close them.
2278 theBufferList().closeAll();
2283 bool GuiView::closeWorkAreaAll()
2285 setCurrentWorkArea(currentMainWorkArea());
2287 // We might be in a situation that there is still a tabWorkArea, but
2288 // there are no tabs anymore. This can happen when we get here after a
2289 // TabWorkArea::lastWorkAreaRemoved() signal. Therefore we count how
2290 // many TabWorkArea's have no documents anymore.
2293 // We have to call count() each time, because it can happen that
2294 // more than one splitter will disappear in one iteration (bug 5998).
2295 for (; d.splitter_->count() > empty_twa; ) {
2296 TabWorkArea * twa = d.tabWorkArea(empty_twa);
2298 if (twa->count() == 0)
2301 setCurrentWorkArea(twa->currentWorkArea());
2302 if (!closeTabWorkArea(twa))
2310 bool GuiView::closeWorkArea(GuiWorkArea * wa, bool close_buffer)
2315 Buffer & buf = wa->bufferView().buffer();
2317 if (close_buffer && GuiViewPrivate::busyBuffers.contains(&buf)) {
2318 Alert::warning(_("Close document "), _("Document could not be closed because it is processed by LyX."));
2323 return closeBuffer(buf);
2325 if (!inMultiTabs(wa))
2326 if (!saveBufferIfNeeded(buf, true))
2334 bool GuiView::closeBuffer(Buffer & buf)
2336 // If we are in a close_event all children will be closed in some time,
2337 // so no need to do it here. This will ensure that the children end up
2338 // in the session file in the correct order. If we close the master
2339 // buffer, we can close or release the child buffers here too.
2341 ListOfBuffers clist = buf.getChildren();
2342 ListOfBuffers::const_iterator it = clist.begin();
2343 ListOfBuffers::const_iterator const bend = clist.end();
2344 for (; it != bend; ++it) {
2345 // If a child is dirty, do not close
2346 // without user intervention
2347 //FIXME: should we look in other tabworkareas?
2348 Buffer * child_buf = *it;
2349 GuiWorkArea * child_wa = workArea(*child_buf);
2351 if (!closeWorkArea(child_wa, true))
2354 theBufferList().releaseChild(&buf, child_buf);
2357 // goto bookmark to update bookmark pit.
2358 //FIXME: we should update only the bookmarks related to this buffer!
2359 LYXERR(Debug::DEBUG, "GuiView::closeBuffer()");
2360 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
2361 guiApp->gotoBookmark(i+1, false, false);
2363 if (saveBufferIfNeeded(buf, false)) {
2364 buf.removeAutosaveFile();
2365 theBufferList().release(&buf);
2372 bool GuiView::closeTabWorkArea(TabWorkArea * twa)
2374 while (twa == d.currentTabWorkArea()) {
2375 twa->setCurrentIndex(twa->count()-1);
2377 GuiWorkArea * wa = twa->currentWorkArea();
2378 Buffer & b = wa->bufferView().buffer();
2380 // We only want to close the buffer if the same buffer is not visible
2381 // in another view, and if this is not a child and if we are closing
2382 // a view (not a tabgroup).
2383 bool const close_buffer =
2384 !inMultiViews(wa) && !b.parent() && closing_;
2386 if (!closeWorkArea(wa, close_buffer))
2393 bool GuiView::saveBufferIfNeeded(Buffer & buf, bool hiding)
2395 if (buf.isClean() || buf.paragraphs().empty())
2398 // Switch to this Buffer.
2403 if (buf.isUnnamed())
2404 file = from_utf8(buf.fileName().onlyFileName());
2406 file = buf.fileName().displayName(30);
2408 // Bring this window to top before asking questions.
2413 if (hiding && buf.isUnnamed()) {
2414 docstring const text = bformat(_("The document %1$s has not been "
2415 "saved yet.\n\nDo you want to save "
2416 "the document?"), file);
2417 ret = Alert::prompt(_("Save new document?"),
2418 text, 0, 1, _("&Save"), _("&Cancel"));
2422 docstring const text = bformat(_("The document %1$s has unsaved changes."
2423 "\n\nDo you want to save the document or discard the changes?"), file);
2424 ret = Alert::prompt(_("Save changed document?"),
2425 text, 0, 2, _("&Save"), _("&Discard"), _("&Cancel"));
2430 if (!saveBuffer(buf))
2434 // if we crash after this we could
2435 // have no autosave file but I guess
2436 // this is really improbable (Jug)
2437 // Sometime improbable things happen, bug 6857 (ps)
2438 // buf.removeAutosaveFile();
2440 // revert all changes
2451 bool GuiView::inMultiTabs(GuiWorkArea * wa)
2453 Buffer & buf = wa->bufferView().buffer();
2455 for (int i = 0; i != d.splitter_->count(); ++i) {
2456 GuiWorkArea * wa_ = d.tabWorkArea(i)->workArea(buf);
2457 if (wa_ && wa_ != wa)
2460 return inMultiViews(wa);
2464 bool GuiView::inMultiViews(GuiWorkArea * wa)
2466 QList<int> const ids = guiApp->viewIds();
2467 Buffer & buf = wa->bufferView().buffer();
2470 for (int i = 0; i != ids.size() && found_twa <= 1; ++i) {
2474 if (guiApp->view(ids[i]).workArea(buf))
2481 void GuiView::gotoNextOrPreviousBuffer(NextOrPrevious np)
2483 Buffer * const curbuf = documentBufferView()
2484 ? &documentBufferView()->buffer() : 0;
2485 Buffer * nextbuf = curbuf;
2487 if (np == NEXTBUFFER)
2488 nextbuf = theBufferList().next(nextbuf);
2490 nextbuf = theBufferList().previous(nextbuf);
2491 if (nextbuf == curbuf)
2497 if (workArea(*nextbuf))
2504 /// make sure the document is saved
2505 static bool ensureBufferClean(Buffer * buffer)
2507 LASSERT(buffer, return false);
2508 if (buffer->isClean() && !buffer->isUnnamed())
2511 docstring const file = buffer->fileName().displayName(30);
2514 if (!buffer->isUnnamed()) {
2515 text = bformat(_("The document %1$s has unsaved "
2516 "changes.\n\nDo you want to save "
2517 "the document?"), file);
2518 title = _("Save changed document?");
2521 text = bformat(_("The document %1$s has not been "
2522 "saved yet.\n\nDo you want to save "
2523 "the document?"), file);
2524 title = _("Save new document?");
2526 int const ret = Alert::prompt(title, text, 0, 1, _("&Save"), _("&Cancel"));
2529 dispatch(FuncRequest(LFUN_BUFFER_WRITE));
2531 return buffer->isClean() && !buffer->isUnnamed();
2535 bool GuiView::reloadBuffer()
2537 Buffer * buf = &documentBufferView()->buffer();
2538 return buf->reload();
2542 void GuiView::checkExternallyModifiedBuffers()
2544 BufferList::iterator bit = theBufferList().begin();
2545 BufferList::iterator const bend = theBufferList().end();
2546 for (; bit != bend; ++bit) {
2547 if ((*bit)->fileName().exists()
2548 && (*bit)->isExternallyModified(Buffer::checksum_method)) {
2549 docstring text = bformat(_("Document \n%1$s\n has been externally modified."
2550 " Reload now? Any local changes will be lost."),
2551 from_utf8((*bit)->absFileName()));
2552 int const ret = Alert::prompt(_("Reload externally changed document?"),
2553 text, 0, 1, _("&Reload"), _("&Cancel"));
2561 void GuiView::dispatchVC(FuncRequest const & cmd, DispatchResult & dr)
2563 Buffer * buffer = documentBufferView()
2564 ? &(documentBufferView()->buffer()) : 0;
2566 switch (cmd.action()) {
2567 case LFUN_VC_REGISTER:
2568 if (!buffer || !ensureBufferClean(buffer))
2570 if (!buffer->lyxvc().inUse()) {
2571 if (buffer->lyxvc().registrer()) {
2573 dr.suppressMessageUpdate();
2578 case LFUN_VC_CHECK_IN:
2579 if (!buffer || !ensureBufferClean(buffer))
2581 if (buffer->lyxvc().inUse() && !buffer->isReadonly()) {
2582 dr.setMessage(buffer->lyxvc().checkIn());
2583 if (!dr.message().empty())
2588 case LFUN_VC_CHECK_OUT:
2589 if (!buffer || !ensureBufferClean(buffer))
2591 if (buffer->lyxvc().inUse()) {
2592 dr.setMessage(buffer->lyxvc().checkOut());
2597 case LFUN_VC_LOCKING_TOGGLE:
2598 LASSERT(buffer, return);
2599 if (!ensureBufferClean(buffer) || buffer->isReadonly())
2601 if (buffer->lyxvc().inUse()) {
2602 string res = buffer->lyxvc().lockingToggle();
2604 frontend::Alert::error(_("Revision control error."),
2605 _("Error when setting the locking property."));
2613 case LFUN_VC_REVERT:
2614 LASSERT(buffer, return);
2615 buffer->lyxvc().revert();
2617 dr.suppressMessageUpdate();
2620 case LFUN_VC_UNDO_LAST:
2621 LASSERT(buffer, return);
2622 buffer->lyxvc().undoLast();
2624 dr.suppressMessageUpdate();
2627 case LFUN_VC_REPO_UPDATE:
2628 LASSERT(buffer, return);
2629 if (ensureBufferClean(buffer)) {
2630 dr.setMessage(buffer->lyxvc().repoUpdate());
2631 checkExternallyModifiedBuffers();
2635 case LFUN_VC_COMMAND: {
2636 string flag = cmd.getArg(0);
2637 if (buffer && contains(flag, 'R') && !ensureBufferClean(buffer))
2640 if (contains(flag, 'M')) {
2641 if (!Alert::askForText(message, _("LyX VC: Log Message")))
2644 string path = cmd.getArg(1);
2645 if (contains(path, "$$p") && buffer)
2646 path = subst(path, "$$p", buffer->filePath());
2647 LYXERR(Debug::LYXVC, "Directory: " << path);
2649 if (!pp.isReadableDirectory()) {
2650 lyxerr << _("Directory is not accessible.") << endl;
2653 support::PathChanger p(pp);
2655 string command = cmd.getArg(2);
2656 if (command.empty())
2659 command = subst(command, "$$i", buffer->absFileName());
2660 command = subst(command, "$$p", buffer->filePath());
2662 command = subst(command, "$$m", to_utf8(message));
2663 LYXERR(Debug::LYXVC, "Command: " << command);
2665 one.startscript(Systemcall::Wait, command);
2669 if (contains(flag, 'I'))
2670 buffer->markDirty();
2671 if (contains(flag, 'R'))
2677 case LFUN_VC_COMPARE: {
2679 if (cmd.argument().empty()) {
2680 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "comparehistory"));
2684 string rev1 = cmd.getArg(0);
2688 if (!buffer->lyxvc().prepareFileRevision(rev1, f1))
2691 if (isStrInt(rev1) && convert<int>(rev1) <= 0) {
2692 f2 = buffer->absFileName();
2694 string rev2 = cmd.getArg(1);
2698 if (!buffer->lyxvc().prepareFileRevision(rev2, f2))
2702 LYXERR(Debug::LYXVC, "Launching comparison for fetched revisions:\n" <<
2703 f1 << "\n" << f2 << "\n" );
2704 string par = "compare run " + quoteName(f1) + " " + quoteName(f2);
2705 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, par));
2715 void GuiView::openChildDocument(string const & fname)
2717 LASSERT(documentBufferView(), return);
2718 Buffer & buffer = documentBufferView()->buffer();
2719 FileName const filename = support::makeAbsPath(fname, buffer.filePath());
2720 documentBufferView()->saveBookmark(false);
2722 bool parsed = false;
2723 if (theBufferList().exists(filename)) {
2724 child = theBufferList().getBuffer(filename);
2726 message(bformat(_("Opening child document %1$s..."),
2727 makeDisplayPath(filename.absFileName())));
2728 child = loadDocument(filename, false);
2734 // Set the parent name of the child document.
2735 // This makes insertion of citations and references in the child work,
2736 // when the target is in the parent or another child document.
2737 child->setParent(&buffer);
2739 // I don't think this is needed, since it will be called in
2741 // child->masterBuffer()->updateBuffer();
2744 child->errors("Parse");
2748 bool GuiView::goToFileRow(string const & argument)
2752 size_t i = argument.find_last_of(' ');
2753 if (i != string::npos) {
2754 file_name = os::internal_path(trim(argument.substr(0, i)));
2755 istringstream is(argument.substr(i + 1));
2760 if (i == string::npos) {
2761 LYXERR0("Wrong argument: " << argument);
2765 string const abstmp = package().temp_dir().absFileName();
2766 string const realtmp = package().temp_dir().realPath();
2767 // We have to use os::path_prefix_is() here, instead of
2768 // simply prefixIs(), because the file name comes from
2769 // an external application and may need case adjustment.
2770 if (os::path_prefix_is(file_name, abstmp, os::CASE_ADJUSTED)
2771 || os::path_prefix_is(file_name, realtmp, os::CASE_ADJUSTED)) {
2772 // Needed by inverse dvi search. If it is a file
2773 // in tmpdir, call the apropriated function.
2774 // If tmpdir is a symlink, we may have the real
2775 // path passed back, so we correct for that.
2776 if (!prefixIs(file_name, abstmp))
2777 file_name = subst(file_name, realtmp, abstmp);
2778 buf = theBufferList().getBufferFromTmp(file_name);
2780 // Must replace extension of the file to be .lyx
2781 // and get full path
2782 FileName const s = fileSearch(string(),
2783 support::changeExtension(file_name, ".lyx"), "lyx");
2784 // Either change buffer or load the file
2785 if (theBufferList().exists(s))
2786 buf = theBufferList().getBuffer(s);
2787 else if (s.exists()) {
2788 buf = loadDocument(s);
2791 // I don't think this is needed. loadDocument() calls
2792 // setBuffer(), which calls updateBuffer().
2793 // buf->updateBuffer();
2794 buf->errors("Parse");
2797 _("File does not exist: %1$s"),
2798 makeDisplayPath(file_name)));
2803 documentBufferView()->setCursorFromRow(row);
2808 #if (QT_VERSION >= 0x040400)
2809 docstring GuiView::GuiViewPrivate::exportAndDestroy(Buffer const * orig, Buffer * buffer, string const & format)
2811 bool const update_unincluded =
2812 buffer->params().maintain_unincluded_children
2813 && !buffer->params().getIncludedChildren().empty();
2814 bool const success = buffer->doExport(format, true, update_unincluded);
2816 busyBuffers.remove(orig);
2818 ? bformat(_("Successful export to format: %1$s"), from_utf8(format))
2819 : bformat(_("Error exporting to format: %1$s"), from_utf8(format));
2823 docstring GuiView::GuiViewPrivate::previewAndDestroy(Buffer const * orig, Buffer * buffer, string const & format)
2825 bool const update_unincluded =
2826 buffer->params().maintain_unincluded_children
2827 && !buffer->params().getIncludedChildren().empty();
2828 bool const success = buffer->preview(format, update_unincluded);
2830 busyBuffers.remove(orig);
2832 ? bformat(_("Successful preview of format: %1$s"), from_utf8(format))
2833 : bformat(_("Error previewing format: %1$s"), from_utf8(format));
2838 bool GuiView::GuiViewPrivate::asyncBufferProcessing(
2839 string const & argument,
2840 Buffer const * used_buffer,
2841 docstring const & msg,
2842 docstring (*asyncFunc)(Buffer const *, Buffer *, string const &),
2843 bool (Buffer::*syncFunc)(string const &, bool, bool) const,
2844 bool (Buffer::*previewFunc)(string const &, bool) const)
2849 string format = argument;
2850 if (format.empty()) {
2851 format = used_buffer->getDefaultOutputFormat();
2853 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
2855 progress_->clearMessages();
2858 GuiViewPrivate::busyBuffers.insert(used_buffer);
2859 QFuture<docstring> f = QtConcurrent::run(
2862 used_buffer->clone(),
2864 setPreviewFuture(f);
2865 last_export_format = used_buffer->bufferFormat();
2868 // We are asynchronous, so we don't know here anything about the success
2871 bool const update_unincluded =
2872 used_buffer->params().maintain_unincluded_children &&
2873 !used_buffer->params().getIncludedChildren().empty();
2875 return (used_buffer->*syncFunc)(format, true, update_unincluded);
2876 } else if (previewFunc) {
2877 return (used_buffer->*previewFunc)(format, update_unincluded);
2883 void GuiView::dispatch(FuncRequest const & cmd, DispatchResult & dr)
2885 BufferView * bv = currentBufferView();
2886 // By default we won't need any update.
2887 dr.screenUpdate(Update::None);
2888 // assume cmd will be dispatched
2889 dr.dispatched(true);
2891 Buffer * doc_buffer = documentBufferView()
2892 ? &(documentBufferView()->buffer()) : 0;
2894 if (cmd.origin() == FuncRequest::TOC) {
2895 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
2896 // FIXME: do we need to pass a DispatchResult object here?
2897 toc->doDispatch(bv->cursor(), cmd);
2901 string const argument = to_utf8(cmd.argument());
2903 switch(cmd.action()) {
2904 case LFUN_BUFFER_CHILD_OPEN:
2905 openChildDocument(to_utf8(cmd.argument()));
2908 case LFUN_BUFFER_IMPORT:
2909 importDocument(to_utf8(cmd.argument()));
2912 case LFUN_BUFFER_EXPORT: {
2915 // GCC only sees strfwd.h when building merged
2916 if (::lyx::operator==(cmd.argument(), "custom")) {
2917 dispatch(FuncRequest(LFUN_DIALOG_SHOW, "sendto"), dr);
2921 // TODO Remove if we could export asynchronous
2922 if (!doc_buffer->doExport(argument, false)) {
2924 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
2928 /* TODO/Review: Is it a problem to also export the children?
2929 See the update_unincluded flag
2931 d.asyncBufferProcessing(argument,
2934 &GuiViewPrivate::exportAndDestroy,
2935 &Buffer::doExport, 0);
2936 // TODO Inform user about success
2941 case LFUN_BUFFER_UPDATE: {
2942 d.asyncBufferProcessing(argument,
2945 &GuiViewPrivate::exportAndDestroy,
2946 &Buffer::doExport, 0);
2949 case LFUN_BUFFER_VIEW: {
2950 d.asyncBufferProcessing(argument,
2952 _("Previewing ..."),
2953 &GuiViewPrivate::previewAndDestroy,
2954 0, &Buffer::preview);
2957 case LFUN_MASTER_BUFFER_UPDATE: {
2958 d.asyncBufferProcessing(argument,
2959 (doc_buffer ? doc_buffer->masterBuffer() : 0),
2961 &GuiViewPrivate::exportAndDestroy,
2962 &Buffer::doExport, 0);
2965 case LFUN_MASTER_BUFFER_VIEW: {
2966 d.asyncBufferProcessing(argument,
2967 (doc_buffer ? doc_buffer->masterBuffer() : 0),
2969 &GuiViewPrivate::previewAndDestroy,
2970 0, &Buffer::preview);
2973 case LFUN_BUFFER_SWITCH: {
2974 string const file_name = to_utf8(cmd.argument());
2975 if (!FileName::isAbsolute(file_name)) {
2977 dr.setMessage(_("Absolute filename expected."));
2981 Buffer * buffer = theBufferList().getBuffer(FileName(file_name));
2984 dr.setMessage(_("Document not loaded"));
2988 // Do we open or switch to the buffer in this view ?
2989 if (workArea(*buffer)
2990 || lyxrc.open_buffers_in_tabs || !documentBufferView()) {
2995 // Look for the buffer in other views
2996 QList<int> const ids = guiApp->viewIds();
2998 for (; i != ids.size(); ++i) {
2999 GuiView & gv = guiApp->view(ids[i]);
3000 if (gv.workArea(*buffer)) {
3001 gv.activateWindow();
3002 gv.setBuffer(buffer);
3007 // If necessary, open a new window as a last resort
3008 if (i == ids.size()) {
3009 lyx::dispatch(FuncRequest(LFUN_WINDOW_NEW));
3015 case LFUN_BUFFER_NEXT:
3016 gotoNextOrPreviousBuffer(NEXTBUFFER);
3019 case LFUN_BUFFER_PREVIOUS:
3020 gotoNextOrPreviousBuffer(PREVBUFFER);
3023 case LFUN_COMMAND_EXECUTE: {
3024 bool const show_it = cmd.argument() != "off";
3025 // FIXME: this is a hack, "minibuffer" should not be
3027 if (GuiToolbar * t = toolbar("minibuffer")) {
3028 t->setVisible(show_it);
3029 if (show_it && t->commandBuffer())
3030 t->commandBuffer()->setFocus();
3034 case LFUN_DROP_LAYOUTS_CHOICE:
3035 d.layout_->showPopup();
3038 case LFUN_MENU_OPEN:
3039 if (QMenu * menu = guiApp->menus().menu(toqstr(cmd.argument()), *this))
3040 menu->exec(QCursor::pos());
3043 case LFUN_FILE_INSERT:
3044 insertLyXFile(cmd.argument());
3046 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
3047 insertPlaintextFile(cmd.argument(), true);
3050 case LFUN_FILE_INSERT_PLAINTEXT:
3051 insertPlaintextFile(cmd.argument(), false);
3054 case LFUN_BUFFER_RELOAD: {
3055 LASSERT(doc_buffer, break);
3056 docstring const file = makeDisplayPath(doc_buffer->absFileName(), 20);
3057 docstring text = bformat(_("Any changes will be lost. Are you sure "
3058 "you want to revert to the saved version of the document %1$s?"), file);
3059 int const ret = Alert::prompt(_("Revert to saved document?"),
3060 text, 1, 1, _("&Revert"), _("&Cancel"));
3063 doc_buffer->markClean();
3065 dr.forceBufferUpdate();
3070 case LFUN_BUFFER_WRITE:
3071 LASSERT(doc_buffer, break);
3072 saveBuffer(*doc_buffer);
3075 case LFUN_BUFFER_WRITE_AS:
3076 LASSERT(doc_buffer, break);
3077 renameBuffer(*doc_buffer, cmd.argument());
3080 case LFUN_BUFFER_WRITE_ALL: {
3081 Buffer * first = theBufferList().first();
3084 message(_("Saving all documents..."));
3085 // We cannot use a for loop as the buffer list cycles.
3088 if (!b->isClean()) {
3090 LYXERR(Debug::ACTION, "Saved " << b->absFileName());
3092 b = theBufferList().next(b);
3093 } while (b != first);
3094 dr.setMessage(_("All documents saved."));
3098 case LFUN_BUFFER_CLOSE:
3102 case LFUN_BUFFER_CLOSE_ALL:
3106 case LFUN_TOOLBAR_TOGGLE: {
3107 string const name = cmd.getArg(0);
3108 if (GuiToolbar * t = toolbar(name))
3113 case LFUN_DIALOG_UPDATE: {
3114 string const name = to_utf8(cmd.argument());
3115 if (currentBufferView()) {
3116 Inset * inset = currentBufferView()->editedInset(name);
3117 // Can only update a dialog connected to an existing inset
3120 // FIXME: get rid of this indirection; GuiView ask the inset
3121 // if he is kind enough to update itself...
3122 FuncRequest fr(LFUN_INSET_DIALOG_UPDATE, cmd.argument());
3123 //FIXME: pass DispatchResult here?
3124 inset->dispatch(currentBufferView()->cursor(), fr);
3125 } else if (name == "paragraph") {
3126 lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
3127 } else if (name == "prefs" || name == "document") {
3128 updateDialog(name, string());
3133 case LFUN_DIALOG_TOGGLE: {
3134 if (isDialogVisible(cmd.getArg(0)))
3135 dispatch(FuncRequest(LFUN_DIALOG_HIDE, cmd.argument()), dr);
3137 dispatch(FuncRequest(LFUN_DIALOG_SHOW, cmd.argument()), dr);
3141 case LFUN_DIALOG_DISCONNECT_INSET:
3142 disconnectDialog(to_utf8(cmd.argument()));
3145 case LFUN_DIALOG_HIDE: {
3146 guiApp->hideDialogs(to_utf8(cmd.argument()), 0);
3150 case LFUN_DIALOG_SHOW: {
3151 string const name = cmd.getArg(0);
3152 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
3154 if (name == "character") {
3155 data = freefont2string();
3157 showDialog("character", data);
3158 } else if (name == "latexlog") {
3159 Buffer::LogType type;
3160 string const logfile = doc_buffer->logName(&type);
3162 case Buffer::latexlog:
3165 case Buffer::buildlog:
3169 data += Lexer::quoteString(logfile);
3170 showDialog("log", data);
3171 } else if (name == "vclog") {
3172 string const data = "vc " +
3173 Lexer::quoteString(doc_buffer->lyxvc().getLogFile());
3174 showDialog("log", data);
3175 } else if (name == "symbols") {
3176 data = bv->cursor().getEncoding()->name();
3178 showDialog("symbols", data);
3180 } else if (name == "prefs" && isFullScreen()) {
3181 lfunUiToggle("fullscreen");
3182 showDialog("prefs", data);
3184 showDialog(name, data);
3189 dr.setMessage(cmd.argument());
3192 case LFUN_UI_TOGGLE: {
3193 string arg = cmd.getArg(0);
3194 if (!lfunUiToggle(arg)) {
3195 docstring const msg = "ui-toggle " + _("%1$s unknown command!");
3196 dr.setMessage(bformat(msg, from_utf8(arg)));
3198 // Make sure the keyboard focus stays in the work area.
3203 case LFUN_SPLIT_VIEW: {
3204 LASSERT(doc_buffer, break);
3205 string const orientation = cmd.getArg(0);
3206 d.splitter_->setOrientation(orientation == "vertical"
3207 ? Qt::Vertical : Qt::Horizontal);
3208 TabWorkArea * twa = addTabWorkArea();
3209 GuiWorkArea * wa = twa->addWorkArea(*doc_buffer, *this);
3210 setCurrentWorkArea(wa);
3213 case LFUN_CLOSE_TAB_GROUP:
3214 if (TabWorkArea * twa = d.currentTabWorkArea()) {
3215 closeTabWorkArea(twa);
3216 d.current_work_area_ = 0;
3217 twa = d.currentTabWorkArea();
3218 // Switch to the next GuiWorkArea in the found TabWorkArea.
3220 // Make sure the work area is up to date.
3221 setCurrentWorkArea(twa->currentWorkArea());
3223 setCurrentWorkArea(0);
3228 case LFUN_COMPLETION_INLINE:
3229 if (d.current_work_area_)
3230 d.current_work_area_->completer().showInline();
3233 case LFUN_COMPLETION_POPUP:
3234 if (d.current_work_area_)
3235 d.current_work_area_->completer().showPopup();
3239 case LFUN_COMPLETION_COMPLETE:
3240 if (d.current_work_area_)
3241 d.current_work_area_->completer().tab();
3244 case LFUN_COMPLETION_CANCEL:
3245 if (d.current_work_area_) {
3246 if (d.current_work_area_->completer().popupVisible())
3247 d.current_work_area_->completer().hidePopup();
3249 d.current_work_area_->completer().hideInline();
3253 case LFUN_COMPLETION_ACCEPT:
3254 if (d.current_work_area_)
3255 d.current_work_area_->completer().activate();
3258 case LFUN_BUFFER_ZOOM_IN:
3259 case LFUN_BUFFER_ZOOM_OUT:
3260 if (cmd.argument().empty()) {
3261 if (cmd.action() == LFUN_BUFFER_ZOOM_IN)
3266 lyxrc.zoom += convert<int>(cmd.argument());
3268 if (lyxrc.zoom < 10)
3271 // The global QPixmapCache is used in GuiPainter to cache text
3272 // painting so we must reset it.
3273 QPixmapCache::clear();
3274 guiApp->fontLoader().update();
3275 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
3278 case LFUN_VC_REGISTER:
3279 case LFUN_VC_CHECK_IN:
3280 case LFUN_VC_CHECK_OUT:
3281 case LFUN_VC_REPO_UPDATE:
3282 case LFUN_VC_LOCKING_TOGGLE:
3283 case LFUN_VC_REVERT:
3284 case LFUN_VC_UNDO_LAST:
3285 case LFUN_VC_COMMAND:
3286 case LFUN_VC_COMPARE:
3287 dispatchVC(cmd, dr);
3290 case LFUN_SERVER_GOTO_FILE_ROW:
3291 goToFileRow(to_utf8(cmd.argument()));
3294 case LFUN_FORWARD_SEARCH: {
3295 FileName const path(doc_buffer->temppath());
3296 string const texname = doc_buffer->latexName();
3297 FileName const dviname(addName(path.absFileName(),
3298 support::changeExtension(texname, "dvi")));
3299 FileName const pdfname(addName(path.absFileName(),
3300 support::changeExtension(texname, "pdf")));
3301 if (!dviname.exists() && !pdfname.exists()) {
3302 dr.setMessage(_("Please, preview the document first."));
3305 string outname = dviname.onlyFileName();
3306 string command = lyxrc.forward_search_dvi;
3307 if (!dviname.exists() ||
3308 pdfname.lastModified() > dviname.lastModified()) {
3309 outname = pdfname.onlyFileName();
3310 command = lyxrc.forward_search_pdf;
3313 int row = doc_buffer->texrow().getRowFromIdPos(bv->cursor().paragraph().id(), bv->cursor().pos());
3314 LYXERR(Debug::ACTION, "Forward search: row:" << row
3315 << " id:" << bv->cursor().paragraph().id());
3316 if (!row || command.empty()) {
3317 dr.setMessage(_("Couldn't proceed."));
3320 string texrow = convert<string>(row);
3322 command = subst(command, "$$n", texrow);
3323 command = subst(command, "$$t", texname);
3324 command = subst(command, "$$o", outname);
3326 PathChanger p(path);
3328 one.startscript(Systemcall::DontWait, command);
3332 dr.dispatched(false);
3336 // Part of automatic menu appearance feature.
3337 if (isFullScreen()) {
3338 if (menuBar()->isVisible() && lyxrc.full_screen_menubar)
3340 if (statusBar()->isVisible())
3341 statusBar()->hide();
3348 bool GuiView::lfunUiToggle(string const & ui_component)
3350 if (ui_component == "scrollbar") {
3351 // hide() is of no help
3352 if (d.current_work_area_->verticalScrollBarPolicy() ==
3353 Qt::ScrollBarAlwaysOff)
3355 d.current_work_area_->setVerticalScrollBarPolicy(
3356 Qt::ScrollBarAsNeeded);
3358 d.current_work_area_->setVerticalScrollBarPolicy(
3359 Qt::ScrollBarAlwaysOff);
3360 } else if (ui_component == "statusbar") {
3361 statusBar()->setVisible(!statusBar()->isVisible());
3362 } else if (ui_component == "menubar") {
3363 menuBar()->setVisible(!menuBar()->isVisible());
3365 #if QT_VERSION >= 0x040300
3366 if (ui_component == "frame") {
3368 getContentsMargins(&l, &t, &r, &b);
3369 //are the frames in default state?
3370 d.current_work_area_->setFrameStyle(QFrame::NoFrame);
3372 setContentsMargins(-2, -2, -2, -2);
3374 setContentsMargins(0, 0, 0, 0);
3378 if (ui_component == "fullscreen") {
3386 void GuiView::toggleFullScreen()
3388 if (isFullScreen()) {
3389 for (int i = 0; i != d.splitter_->count(); ++i)
3390 d.tabWorkArea(i)->setFullScreen(false);
3391 #if QT_VERSION >= 0x040300
3392 setContentsMargins(0, 0, 0, 0);
3394 setWindowState(windowState() ^ Qt::WindowFullScreen);
3397 statusBar()->show();
3400 hideDialogs("prefs", 0);
3401 for (int i = 0; i != d.splitter_->count(); ++i)
3402 d.tabWorkArea(i)->setFullScreen(true);
3403 #if QT_VERSION >= 0x040300
3404 setContentsMargins(-2, -2, -2, -2);
3407 setWindowState(windowState() ^ Qt::WindowFullScreen);
3408 statusBar()->hide();
3409 if (lyxrc.full_screen_menubar)
3411 if (lyxrc.full_screen_toolbars) {
3412 ToolbarMap::iterator end = d.toolbars_.end();
3413 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
3418 // give dialogs like the TOC a chance to adapt
3423 Buffer const * GuiView::updateInset(Inset const * inset)
3428 Buffer const * inset_buffer = &(inset->buffer());
3430 for (int i = 0; i != d.splitter_->count(); ++i) {
3431 GuiWorkArea * wa = d.tabWorkArea(i)->currentWorkArea();
3434 Buffer const * buffer = &(wa->bufferView().buffer());
3435 if (inset_buffer == buffer)
3436 wa->scheduleRedraw();
3438 return inset_buffer;
3442 void GuiView::restartCursor()
3444 /* When we move around, or type, it's nice to be able to see
3445 * the cursor immediately after the keypress.
3447 if (d.current_work_area_)
3448 d.current_work_area_->startBlinkingCursor();
3450 // Take this occasion to update the other GUI elements.
3456 void GuiView::updateCompletion(Cursor & cur, bool start, bool keep)
3458 if (d.current_work_area_)
3459 d.current_work_area_->completer().updateVisibility(cur, start, keep);
3464 // This list should be kept in sync with the list of insets in
3465 // src/insets/Inset.cpp. I.e., if a dialog goes with an inset, the
3466 // dialog should have the same name as the inset.
3467 // Changes should be also recorded in LFUN_DIALOG_SHOW doxygen
3468 // docs in LyXAction.cpp.
3470 char const * const dialognames[] = {
3472 "aboutlyx", "bibitem", "bibtex", "box", "branch", "changes", "character",
3473 "citation", "compare", "comparehistory", "document", "errorlist", "ert",
3474 "external", "file", "findreplace", "findreplaceadv", "float", "graphics",
3475 "href", "include", "index", "index_print", "info", "listings", "label", "line",
3476 "log", "mathdelimiter", "mathmatrix", "mathspace", "nomenclature",
3477 "nomencl_print", "note", "paragraph", "phantom", "prefs", "print", "ref",
3478 "sendto", "space", "spellchecker", "symbols", "tabular", "tabularcreate",
3479 "thesaurus", "texinfo", "toc", "view-source", "vspace", "wrap", "progress"};
3481 char const * const * const end_dialognames =
3482 dialognames + (sizeof(dialognames) / sizeof(char *));
3486 cmpCStr(char const * name) : name_(name) {}
3487 bool operator()(char const * other) {
3488 return strcmp(other, name_) == 0;
3495 bool isValidName(string const & name)
3497 return find_if(dialognames, end_dialognames,
3498 cmpCStr(name.c_str())) != end_dialognames;
3504 void GuiView::resetDialogs()
3506 // Make sure that no LFUN uses any GuiView.
3507 guiApp->setCurrentView(0);
3510 constructToolbars();
3511 guiApp->menus().fillMenuBar(menuBar(), this, false);
3512 d.layout_->updateContents(true);
3513 // Now update controls with current buffer.
3514 guiApp->setCurrentView(this);
3520 Dialog * GuiView::findOrBuild(string const & name, bool hide_it)
3522 if (!isValidName(name))
3525 map<string, DialogPtr>::iterator it = d.dialogs_.find(name);
3527 if (it != d.dialogs_.end()) {
3529 it->second->hideView();
3530 return it->second.get();
3533 Dialog * dialog = build(name);
3534 d.dialogs_[name].reset(dialog);
3535 if (lyxrc.allow_geometry_session)
3536 dialog->restoreSession();
3543 void GuiView::showDialog(string const & name, string const & data,
3546 triggerShowDialog(toqstr(name), toqstr(data), inset);
3550 void GuiView::doShowDialog(QString const & qname, QString const & qdata,
3556 const string name = fromqstr(qname);
3557 const string data = fromqstr(qdata);
3561 Dialog * dialog = findOrBuild(name, false);
3563 bool const visible = dialog->isVisibleView();
3564 dialog->showData(data);
3565 if (inset && currentBufferView())
3566 currentBufferView()->editInset(name, inset);
3567 // We only set the focus to the new dialog if it was not yet
3568 // visible in order not to change the existing previous behaviour
3570 // activateWindow is needed for floating dockviews
3571 dialog->asQWidget()->raise();
3572 dialog->asQWidget()->activateWindow();
3573 dialog->asQWidget()->setFocus();
3577 catch (ExceptionMessage const & ex) {
3585 bool GuiView::isDialogVisible(string const & name) const
3587 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3588 if (it == d.dialogs_.end())
3590 return it->second.get()->isVisibleView() && !it->second.get()->isClosing();
3594 void GuiView::hideDialog(string const & name, Inset * inset)
3596 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3597 if (it == d.dialogs_.end())
3600 if (inset && currentBufferView()
3601 && inset != currentBufferView()->editedInset(name))
3604 Dialog * const dialog = it->second.get();
3605 if (dialog->isVisibleView())
3607 if (currentBufferView())
3608 currentBufferView()->editInset(name, 0);
3612 void GuiView::disconnectDialog(string const & name)
3614 if (!isValidName(name))
3616 if (currentBufferView())
3617 currentBufferView()->editInset(name, 0);
3621 void GuiView::hideAll() const
3623 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
3624 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3626 for(; it != end; ++it)
3627 it->second->hideView();
3631 void GuiView::updateDialogs()
3633 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
3634 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3636 for(; it != end; ++it) {
3637 Dialog * dialog = it->second.get();
3639 if (dialog->needBufferOpen() && !documentBufferView())
3640 hideDialog(fromqstr(dialog->name()), 0);
3641 else if (dialog->isVisibleView())
3642 dialog->checkStatus();
3649 Dialog * createDialog(GuiView & lv, string const & name);
3651 // will be replaced by a proper factory...
3652 Dialog * createGuiAbout(GuiView & lv);
3653 Dialog * createGuiBibtex(GuiView & lv);
3654 Dialog * createGuiChanges(GuiView & lv);
3655 Dialog * createGuiCharacter(GuiView & lv);
3656 Dialog * createGuiCitation(GuiView & lv);
3657 Dialog * createGuiCompare(GuiView & lv);
3658 Dialog * createGuiCompareHistory(GuiView & lv);
3659 Dialog * createGuiDelimiter(GuiView & lv);
3660 Dialog * createGuiDocument(GuiView & lv);
3661 Dialog * createGuiErrorList(GuiView & lv);
3662 Dialog * createGuiExternal(GuiView & lv);
3663 Dialog * createGuiGraphics(GuiView & lv);
3664 Dialog * createGuiInclude(GuiView & lv);
3665 Dialog * createGuiIndex(GuiView & lv);
3666 Dialog * createGuiLabel(GuiView & lv);
3667 Dialog * createGuiListings(GuiView & lv);
3668 Dialog * createGuiLog(GuiView & lv);
3669 Dialog * createGuiMathMatrix(GuiView & lv);
3670 Dialog * createGuiNomenclature(GuiView & lv);
3671 Dialog * createGuiNote(GuiView & lv);
3672 Dialog * createGuiParagraph(GuiView & lv);
3673 Dialog * createGuiPhantom(GuiView & lv);
3674 Dialog * createGuiPreferences(GuiView & lv);
3675 Dialog * createGuiPrint(GuiView & lv);
3676 Dialog * createGuiPrintindex(GuiView & lv);
3677 Dialog * createGuiPrintNomencl(GuiView & lv);
3678 Dialog * createGuiRef(GuiView & lv);
3679 Dialog * createGuiSearch(GuiView & lv);
3680 Dialog * createGuiSearchAdv(GuiView & lv);
3681 Dialog * createGuiSendTo(GuiView & lv);
3682 Dialog * createGuiShowFile(GuiView & lv);
3683 Dialog * createGuiSpellchecker(GuiView & lv);
3684 Dialog * createGuiSymbols(GuiView & lv);
3685 Dialog * createGuiTabularCreate(GuiView & lv);
3686 Dialog * createGuiTexInfo(GuiView & lv);
3687 Dialog * createGuiToc(GuiView & lv);
3688 Dialog * createGuiThesaurus(GuiView & lv);
3689 Dialog * createGuiHyperlink(GuiView & lv);
3690 Dialog * createGuiViewSource(GuiView & lv);
3691 Dialog * createGuiWrap(GuiView & lv);
3692 Dialog * createGuiProgressView(GuiView & lv);
3696 Dialog * GuiView::build(string const & name)
3698 LASSERT(isValidName(name), return 0);
3700 Dialog * dialog = createDialog(*this, name);
3704 if (name == "aboutlyx")
3705 return createGuiAbout(*this);
3706 if (name == "bibtex")
3707 return createGuiBibtex(*this);
3708 if (name == "changes")
3709 return createGuiChanges(*this);
3710 if (name == "character")
3711 return createGuiCharacter(*this);
3712 if (name == "citation")
3713 return createGuiCitation(*this);
3714 if (name == "compare")
3715 return createGuiCompare(*this);
3716 if (name == "comparehistory")
3717 return createGuiCompareHistory(*this);
3718 if (name == "document")
3719 return createGuiDocument(*this);
3720 if (name == "errorlist")
3721 return createGuiErrorList(*this);
3722 if (name == "external")
3723 return createGuiExternal(*this);
3725 return createGuiShowFile(*this);
3726 if (name == "findreplace")
3727 return createGuiSearch(*this);
3728 if (name == "findreplaceadv")
3729 return createGuiSearchAdv(*this);
3730 if (name == "graphics")
3731 return createGuiGraphics(*this);
3733 return createGuiHyperlink(*this);
3734 if (name == "include")
3735 return createGuiInclude(*this);
3736 if (name == "index")
3737 return createGuiIndex(*this);
3738 if (name == "index_print")
3739 return createGuiPrintindex(*this);
3740 if (name == "label")
3741 return createGuiLabel(*this);
3742 if (name == "listings")
3743 return createGuiListings(*this);
3745 return createGuiLog(*this);
3746 if (name == "mathdelimiter")
3747 return createGuiDelimiter(*this);
3748 if (name == "mathmatrix")
3749 return createGuiMathMatrix(*this);
3750 if (name == "nomenclature")
3751 return createGuiNomenclature(*this);
3752 if (name == "nomencl_print")
3753 return createGuiPrintNomencl(*this);
3755 return createGuiNote(*this);
3756 if (name == "paragraph")
3757 return createGuiParagraph(*this);
3758 if (name == "phantom")
3759 return createGuiPhantom(*this);
3760 if (name == "prefs")
3761 return createGuiPreferences(*this);
3762 if (name == "print")
3763 return createGuiPrint(*this);
3765 return createGuiRef(*this);
3766 if (name == "sendto")
3767 return createGuiSendTo(*this);
3768 if (name == "spellchecker")
3769 return createGuiSpellchecker(*this);
3770 if (name == "symbols")
3771 return createGuiSymbols(*this);
3772 if (name == "tabularcreate")
3773 return createGuiTabularCreate(*this);
3774 if (name == "texinfo")
3775 return createGuiTexInfo(*this);
3776 if (name == "thesaurus")
3777 return createGuiThesaurus(*this);
3779 return createGuiToc(*this);
3780 if (name == "view-source")
3781 return createGuiViewSource(*this);
3783 return createGuiWrap(*this);
3784 if (name == "progress")
3785 return createGuiProgressView(*this);
3791 } // namespace frontend
3794 #include "moc_GuiView.cpp"