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(string const & argument,
374 Buffer const * used_buffer,
375 docstring const & msg,
376 docstring (*asyncFunc)(Buffer const *, Buffer *, string const &),
377 bool (Buffer::*syncFunc)(string const &, bool, bool) const,
378 bool (Buffer::*previewFunc)(string const &, bool) const);
383 QSet<Buffer const *> GuiView::GuiViewPrivate::busyBuffers;
386 GuiView::GuiView(int id)
387 : d(*new GuiViewPrivate(this)), id_(id), closing_(false)
389 // GuiToolbars *must* be initialised before the menu bar.
390 normalSizedIcons(); // at least on Mac the default is 32 otherwise, which is huge
393 // set ourself as the current view. This is needed for the menu bar
394 // filling, at least for the static special menu item on Mac. Otherwise
395 // they are greyed out.
396 guiApp->setCurrentView(this);
398 // Fill up the menu bar.
399 guiApp->menus().fillMenuBar(menuBar(), this, true);
401 setCentralWidget(d.stack_widget_);
403 // Start autosave timer
404 if (lyxrc.autosave) {
405 d.autosave_timeout_.timeout.connect(bind(&GuiView::autoSave, this));
406 d.autosave_timeout_.setTimeout(lyxrc.autosave * 1000);
407 d.autosave_timeout_.start();
409 connect(&d.statusbar_timer_, SIGNAL(timeout()),
410 this, SLOT(clearMessage()));
412 // We don't want to keep the window in memory if it is closed.
413 setAttribute(Qt::WA_DeleteOnClose, true);
415 #if (!defined(Q_WS_WIN) && !defined(Q_WS_MACX))
416 // assign an icon to main form. We do not do it under Qt/Win or Qt/Mac,
417 // since the icon is provided in the application bundle.
418 setWindowIcon(getPixmap("images/", "lyx", "png"));
421 #if (QT_VERSION >= 0x040300)
422 // use tabbed dock area for multiple docks
423 // (such as "source" and "messages")
424 setDockOptions(QMainWindow::ForceTabbedDocks);
428 setAcceptDrops(true);
430 statusBar()->setSizeGripEnabled(true);
433 #if (QT_VERSION >= 0x040400)
434 connect(&d.autosave_watcher_, SIGNAL(finished()), this,
435 SLOT(threadFinished()));
436 connect(&d.preview_watcher_, SIGNAL(finished()), this,
437 SLOT(threadFinished()));
440 connect(this, SIGNAL(triggerShowDialog(QString const &, QString const &, Inset *)),
441 SLOT(doShowDialog(QString const &, QString const &, Inset *)));
443 // Forbid too small unresizable window because it can happen
444 // with some window manager under X11.
445 setMinimumSize(300, 200);
447 if (lyxrc.allow_geometry_session) {
448 // Now take care of session management.
453 // no session handling, default to a sane size.
454 setGeometry(50, 50, 690, 510);
457 // clear session data if any.
459 settings.remove("views");
469 void GuiView::threadFinished()
471 #if (QT_VERSION >= 0x040400)
472 QFutureWatcher<docstring> const * watcher =
473 static_cast<QFutureWatcher<docstring> const *>(sender());
474 message(watcher->result());
476 errors(d.last_export_format);
481 void GuiView::saveLayout() const
484 settings.beginGroup("views");
485 settings.beginGroup(QString::number(id_));
487 settings.setValue("pos", pos());
488 settings.setValue("size", size());
490 settings.setValue("geometry", saveGeometry());
492 settings.setValue("layout", saveState(0));
493 settings.setValue("icon_size", iconSize());
497 bool GuiView::restoreLayout()
500 settings.beginGroup("views");
501 settings.beginGroup(QString::number(id_));
502 QString const icon_key = "icon_size";
503 if (!settings.contains(icon_key))
506 //code below is skipped when when ~/.config/LyX is (re)created
507 setIconSize(settings.value(icon_key).toSize());
509 QPoint pos = settings.value("pos", QPoint(50, 50)).toPoint();
510 QSize size = settings.value("size", QSize(690, 510)).toSize();
514 // Work-around for bug #6034: the window ends up in an undetermined
515 // state when trying to restore a maximized window when it is
516 // already maximized.
517 if (!(windowState() & Qt::WindowMaximized))
518 if (!restoreGeometry(settings.value("geometry").toByteArray()))
519 setGeometry(50, 50, 690, 510);
521 // Make sure layout is correctly oriented.
522 setLayoutDirection(qApp->layoutDirection());
524 // Allow the toc and view-source dock widget to be restored if needed.
526 if ((dialog = findOrBuild("toc", true)))
527 // see bug 5082. At least setup title and enabled state.
528 // Visibility will be adjusted by restoreState below.
529 dialog->prepareView();
530 if ((dialog = findOrBuild("view-source", true)))
531 dialog->prepareView();
532 if ((dialog = findOrBuild("progress", true)))
533 dialog->prepareView();
535 if (!restoreState(settings.value("layout").toByteArray(), 0))
542 GuiToolbar * GuiView::toolbar(string const & name)
544 ToolbarMap::iterator it = d.toolbars_.find(name);
545 if (it != d.toolbars_.end())
548 LYXERR(Debug::GUI, "Toolbar::display: no toolbar named " << name);
553 void GuiView::constructToolbars()
555 ToolbarMap::iterator it = d.toolbars_.begin();
556 for (; it != d.toolbars_.end(); ++it)
560 // I don't like doing this here, but the standard toolbar
561 // destroys this object when it's destroyed itself (vfr)
562 d.layout_ = new LayoutBox(*this);
563 d.stack_widget_->addWidget(d.layout_);
564 d.layout_->move(0,0);
566 // extracts the toolbars from the backend
567 Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
568 Toolbars::Infos::iterator end = guiApp->toolbars().end();
569 for (; cit != end; ++cit)
570 d.toolbars_[cit->name] = new GuiToolbar(*cit, *this);
574 void GuiView::initToolbars()
576 // extracts the toolbars from the backend
577 Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
578 Toolbars::Infos::iterator end = guiApp->toolbars().end();
579 for (; cit != end; ++cit) {
580 GuiToolbar * tb = toolbar(cit->name);
583 int const visibility = guiApp->toolbars().defaultVisibility(cit->name);
584 bool newline = !(visibility & Toolbars::SAMEROW);
585 tb->setVisible(false);
586 tb->setVisibility(visibility);
588 if (visibility & Toolbars::TOP) {
590 addToolBarBreak(Qt::TopToolBarArea);
591 addToolBar(Qt::TopToolBarArea, tb);
594 if (visibility & Toolbars::BOTTOM) {
595 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
596 #if (QT_VERSION >= 0x040202)
598 addToolBarBreak(Qt::BottomToolBarArea);
600 addToolBar(Qt::BottomToolBarArea, tb);
603 if (visibility & Toolbars::LEFT) {
604 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
605 #if (QT_VERSION >= 0x040202)
607 addToolBarBreak(Qt::LeftToolBarArea);
609 addToolBar(Qt::LeftToolBarArea, tb);
612 if (visibility & Toolbars::RIGHT) {
613 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
614 #if (QT_VERSION >= 0x040202)
616 addToolBarBreak(Qt::RightToolBarArea);
618 addToolBar(Qt::RightToolBarArea, tb);
621 if (visibility & Toolbars::ON)
622 tb->setVisible(true);
627 TocModels & GuiView::tocModels()
629 return d.toc_models_;
633 void GuiView::setFocus()
635 LYXERR(Debug::DEBUG, "GuiView::setFocus()" << this);
636 QMainWindow::setFocus();
640 void GuiView::focusInEvent(QFocusEvent * e)
642 LYXERR(Debug::DEBUG, "GuiView::focusInEvent()" << this);
643 QMainWindow::focusInEvent(e);
644 // Make sure guiApp points to the correct view.
645 guiApp->setCurrentView(this);
646 if (currentMainWorkArea())
647 currentMainWorkArea()->setFocus();
648 else if (currentWorkArea())
649 currentWorkArea()->setFocus();
651 d.bg_widget_->setFocus();
655 QMenu * GuiView::createPopupMenu()
657 return d.toolBarPopup(this);
661 void GuiView::showEvent(QShowEvent * e)
663 LYXERR(Debug::GUI, "Passed Geometry "
664 << size().height() << "x" << size().width()
665 << "+" << pos().x() << "+" << pos().y());
667 if (d.splitter_->count() == 0)
668 // No work area, switch to the background widget.
671 QMainWindow::showEvent(e);
675 bool GuiView::closeScheduled()
682 /** Destroy only all tabbed WorkAreas. Destruction of other WorkAreas
683 ** is responsibility of the container (e.g., dialog)
685 void GuiView::closeEvent(QCloseEvent * close_event)
687 LYXERR(Debug::DEBUG, "GuiView::closeEvent()");
689 if (!GuiViewPrivate::busyBuffers.isEmpty()) {
690 Alert::warning(_("Exit LyX"), _("LyX could not be closed because documents are processed by LyX."));
691 close_event->setAccepted(false);
695 // If the user pressed the x (so we didn't call closeView
696 // programmatically), we want to clear all existing entries.
698 theSession().lastOpened().clear();
703 // it can happen that this event arrives without selecting the view,
704 // e.g. when clicking the close button on a background window.
706 if (!closeWorkAreaAll()) {
708 close_event->ignore();
712 // Make sure that nothing will use this to be closed View.
713 guiApp->unregisterView(this);
715 if (isFullScreen()) {
716 // Switch off fullscreen before closing.
721 // Make sure the timer time out will not trigger a statusbar update.
722 d.statusbar_timer_.stop();
724 // Saving fullscreen requires additional tweaks in the toolbar code.
725 // It wouldn't also work under linux natively.
726 if (lyxrc.allow_geometry_session) {
727 // Save this window geometry and layout.
729 // Then the toolbar private states.
730 ToolbarMap::iterator end = d.toolbars_.end();
731 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
732 it->second->saveSession();
733 // Now take care of all other dialogs:
734 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
735 for (; it!= d.dialogs_.end(); ++it)
736 it->second->saveSession();
739 close_event->accept();
743 void GuiView::dragEnterEvent(QDragEnterEvent * event)
745 if (event->mimeData()->hasUrls())
747 /// \todo Ask lyx-devel is this is enough:
748 /// if (event->mimeData()->hasFormat("text/plain"))
749 /// event->acceptProposedAction();
753 void GuiView::dropEvent(QDropEvent * event)
755 QList<QUrl> files = event->mimeData()->urls();
759 LYXERR(Debug::GUI, "GuiView::dropEvent: got URLs!");
760 for (int i = 0; i != files.size(); ++i) {
761 string const file = os::internal_path(fromqstr(
762 files.at(i).toLocalFile()));
766 string const ext = support::getExtension(file);
767 vector<const Format *> found_formats;
769 // Find all formats that have the correct extension.
770 vector<const Format *> const & import_formats
771 = theConverters().importableFormats();
772 vector<const Format *>::const_iterator it = import_formats.begin();
773 for (; it != import_formats.end(); ++it)
774 if ((*it)->extension() == ext)
775 found_formats.push_back(*it);
778 if (found_formats.size() >= 1) {
779 if (found_formats.size() > 1) {
780 //FIXME: show a dialog to choose the correct importable format
782 "Multiple importable formats found, selecting first");
784 string const arg = found_formats[0]->name() + " " + file;
785 cmd = FuncRequest(LFUN_BUFFER_IMPORT, arg);
788 //FIXME: do we have to explicitly check whether it's a lyx file?
790 "No formats found, trying to open it as a lyx file");
791 cmd = FuncRequest(LFUN_FILE_OPEN, file);
794 // Asynchronously post the event. DropEvent usually comes
795 // from the BufferView. But reloading a file might close
796 // the BufferView from within its own event handler.
797 guiApp->dispatchDelayed(cmd);
803 void GuiView::message(docstring const & str)
805 if (ForkedProcess::iAmAChild())
808 // call is moved to GUI-thread by GuiProgress
809 d.progress_->appendMessage(toqstr(str));
813 void GuiView::clearMessageText()
815 message(docstring());
819 void GuiView::updateStatusBarMessage(QString const & str)
821 statusBar()->showMessage(str);
822 d.statusbar_timer_.stop();
823 d.statusbar_timer_.start(3000);
827 void GuiView::smallSizedIcons()
829 setIconSize(QSize(d.smallIconSize, d.smallIconSize));
833 void GuiView::normalSizedIcons()
835 setIconSize(QSize(d.normalIconSize, d.normalIconSize));
839 void GuiView::bigSizedIcons()
841 setIconSize(QSize(d.bigIconSize, d.bigIconSize));
845 void GuiView::clearMessage()
847 // FIXME: This code was introduced in r19643 to fix bug #4123. However,
848 // the hasFocus function mostly returns false, even if the focus is on
849 // a workarea in this view.
853 d.statusbar_timer_.stop();
857 void GuiView::updateWindowTitle(GuiWorkArea * wa)
859 if (wa != d.current_work_area_
860 || wa->bufferView().buffer().isInternal())
862 setWindowTitle(qt_("LyX: ") + wa->windowTitle());
863 setWindowIconText(wa->windowIconText());
867 void GuiView::on_currentWorkAreaChanged(GuiWorkArea * wa)
870 disconnectBufferView();
871 connectBufferView(wa->bufferView());
872 connectBuffer(wa->bufferView().buffer());
873 d.current_work_area_ = wa;
874 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
875 this, SLOT(updateWindowTitle(GuiWorkArea *)));
876 updateWindowTitle(wa);
880 // The document settings needs to be reinitialised.
881 updateDialog("document", "");
883 // Buffer-dependent dialogs must be updated. This is done here because
884 // some dialogs require buffer()->text.
889 void GuiView::on_lastWorkAreaRemoved()
892 // We already are in a close event. Nothing more to do.
895 if (d.splitter_->count() > 1)
896 // We have a splitter so don't close anything.
899 // Reset and updates the dialogs.
900 d.toc_models_.reset(0);
901 updateDialog("document", "");
904 resetWindowTitleAndIconText();
907 if (lyxrc.open_buffers_in_tabs)
908 // Nothing more to do, the window should stay open.
911 if (guiApp->viewIds().size() > 1) {
917 // On Mac we also close the last window because the application stay
918 // resident in memory. On other platforms we don't close the last
919 // window because this would quit the application.
925 void GuiView::updateStatusBar()
927 // let the user see the explicit message
928 if (d.statusbar_timer_.isActive())
935 void GuiView::showMessage()
937 QString msg = toqstr(theGuiApp()->viewStatusMessage());
939 BufferView const * bv = currentBufferView();
941 msg = toqstr(bv->cursor().currentState());
943 msg = qt_("Welcome to LyX!");
945 statusBar()->showMessage(msg);
949 bool GuiView::event(QEvent * e)
953 // Useful debug code:
954 //case QEvent::ActivationChange:
955 //case QEvent::WindowDeactivate:
956 //case QEvent::Paint:
957 //case QEvent::Enter:
958 //case QEvent::Leave:
959 //case QEvent::HoverEnter:
960 //case QEvent::HoverLeave:
961 //case QEvent::HoverMove:
962 //case QEvent::StatusTip:
963 //case QEvent::DragEnter:
964 //case QEvent::DragLeave:
968 case QEvent::WindowActivate: {
969 GuiView * old_view = guiApp->currentView();
970 if (this == old_view) {
972 return QMainWindow::event(e);
974 if (old_view && old_view->currentBufferView()) {
975 // save current selection to the selection buffer to allow
976 // middle-button paste in this window.
977 cap::saveSelection(old_view->currentBufferView()->cursor());
979 guiApp->setCurrentView(this);
980 if (d.current_work_area_) {
981 BufferView & bv = d.current_work_area_->bufferView();
982 connectBufferView(bv);
983 connectBuffer(bv.buffer());
984 // The document structure, name and dialogs might have
985 // changed in another view.
987 // The document settings needs to be reinitialised.
988 updateDialog("document", "");
991 resetWindowTitleAndIconText();
994 return QMainWindow::event(e);
997 case QEvent::ShortcutOverride: {
1000 #if (!defined Q_WS_X11) || (QT_VERSION >= 0x040500)
1001 if (isFullScreen() && menuBar()->isHidden()) {
1002 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
1003 // FIXME: we should also try to detect special LyX shortcut such as
1004 // Alt-P and Alt-M. Right now there is a hack in
1005 // GuiWorkArea::processKeySym() that hides again the menubar for
1007 if (ke->modifiers() & Qt::AltModifier && ke->key() != Qt::Key_Alt) {
1009 return QMainWindow::event(e);
1013 return QMainWindow::event(e);
1017 return QMainWindow::event(e);
1021 void GuiView::resetWindowTitleAndIconText()
1023 setWindowTitle(qt_("LyX"));
1024 setWindowIconText(qt_("LyX"));
1027 bool GuiView::focusNextPrevChild(bool /*next*/)
1034 bool GuiView::busy() const
1040 void GuiView::setBusy(bool busy)
1043 if (d.current_work_area_) {
1044 d.current_work_area_->setUpdatesEnabled(!busy);
1046 d.current_work_area_->stopBlinkingCursor();
1048 d.current_work_area_->startBlinkingCursor();
1052 QApplication::setOverrideCursor(Qt::WaitCursor);
1054 QApplication::restoreOverrideCursor();
1058 GuiWorkArea * GuiView::workArea(Buffer & buffer)
1060 if (currentWorkArea()
1061 && ¤tWorkArea()->bufferView().buffer() == &buffer)
1062 return (GuiWorkArea *) currentWorkArea();
1063 if (TabWorkArea * twa = d.currentTabWorkArea())
1064 return twa->workArea(buffer);
1069 GuiWorkArea * GuiView::addWorkArea(Buffer & buffer)
1071 // Automatically create a TabWorkArea if there are none yet.
1072 TabWorkArea * tab_widget = d.splitter_->count()
1073 ? d.currentTabWorkArea() : addTabWorkArea();
1074 return tab_widget->addWorkArea(buffer, *this);
1078 TabWorkArea * GuiView::addTabWorkArea()
1080 TabWorkArea * twa = new TabWorkArea;
1081 QObject::connect(twa, SIGNAL(currentWorkAreaChanged(GuiWorkArea *)),
1082 this, SLOT(on_currentWorkAreaChanged(GuiWorkArea *)));
1083 QObject::connect(twa, SIGNAL(lastWorkAreaRemoved()),
1084 this, SLOT(on_lastWorkAreaRemoved()));
1086 d.splitter_->addWidget(twa);
1087 d.stack_widget_->setCurrentWidget(d.splitter_);
1092 GuiWorkArea const * GuiView::currentWorkArea() const
1094 return d.current_work_area_;
1098 GuiWorkArea * GuiView::currentWorkArea()
1100 return d.current_work_area_;
1104 GuiWorkArea const * GuiView::currentMainWorkArea() const
1106 if (!d.currentTabWorkArea())
1108 return d.currentTabWorkArea()->currentWorkArea();
1112 GuiWorkArea * GuiView::currentMainWorkArea()
1114 if (!d.currentTabWorkArea())
1116 return d.currentTabWorkArea()->currentWorkArea();
1120 void GuiView::setCurrentWorkArea(GuiWorkArea * wa)
1122 LYXERR(Debug::DEBUG, "Setting current wa: " << wa << endl);
1124 d.current_work_area_ = 0;
1129 // FIXME: I've no clue why this is here and why it accesses
1130 // theGuiApp()->currentView, which might be 0 (bug 6464).
1131 // See also 27525 (vfr).
1132 if (theGuiApp()->currentView() == this
1133 && theGuiApp()->currentView()->currentWorkArea() == wa)
1136 if (currentBufferView())
1137 cap::saveSelection(currentBufferView()->cursor());
1139 theGuiApp()->setCurrentView(this);
1140 d.current_work_area_ = wa;
1141 for (int i = 0; i != d.splitter_->count(); ++i) {
1142 if (d.tabWorkArea(i)->setCurrentWorkArea(wa)) {
1143 //if (d.current_main_work_area_)
1144 // d.current_main_work_area_->setFrameStyle(QFrame::NoFrame);
1145 d.current_main_work_area_ = wa;
1146 //d.current_main_work_area_->setFrameStyle(QFrame::Box | QFrame::Plain);
1147 //d.current_main_work_area_->setLineWidth(2);
1148 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() << ", Current main wa: " << currentMainWorkArea());
1152 LYXERR(Debug::DEBUG, "This is not a tabbed wa");
1153 on_currentWorkAreaChanged(wa);
1154 BufferView & bv = wa->bufferView();
1155 bv.cursor().fixIfBroken();
1157 wa->setUpdatesEnabled(true);
1158 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() << ", Current main wa: " << currentMainWorkArea());
1162 void GuiView::removeWorkArea(GuiWorkArea * wa)
1164 LASSERT(wa, return);
1165 if (wa == d.current_work_area_) {
1167 disconnectBufferView();
1168 d.current_work_area_ = 0;
1169 d.current_main_work_area_ = 0;
1172 bool found_twa = false;
1173 for (int i = 0; i != d.splitter_->count(); ++i) {
1174 TabWorkArea * twa = d.tabWorkArea(i);
1175 if (twa->removeWorkArea(wa)) {
1176 // Found in this tab group, and deleted the GuiWorkArea.
1178 if (twa->count() != 0) {
1179 if (d.current_work_area_ == 0)
1180 // This means that we are closing the current GuiWorkArea, so
1181 // switch to the next GuiWorkArea in the found TabWorkArea.
1182 setCurrentWorkArea(twa->currentWorkArea());
1184 // No more WorkAreas in this tab group, so delete it.
1191 // It is not a tabbed work area (i.e., the search work area), so it
1192 // should be deleted by other means.
1193 LASSERT(found_twa, /* */);
1195 if (d.current_work_area_ == 0) {
1196 if (d.splitter_->count() != 0) {
1197 TabWorkArea * twa = d.currentTabWorkArea();
1198 setCurrentWorkArea(twa->currentWorkArea());
1200 // No more work areas, switch to the background widget.
1201 setCurrentWorkArea(0);
1207 LayoutBox * GuiView::getLayoutDialog() const
1213 void GuiView::updateLayoutList()
1216 d.layout_->updateContents(false);
1220 void GuiView::updateToolbars()
1222 ToolbarMap::iterator end = d.toolbars_.end();
1223 if (d.current_work_area_) {
1225 d.current_work_area_->bufferView().cursor().inMathed()
1226 && !d.current_work_area_->bufferView().cursor().inRegexped();
1228 lyx::getStatus(FuncRequest(LFUN_LAYOUT_TABULAR)).enabled();
1230 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).enabled() &&
1231 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).onOff(true);
1232 bool const mathmacrotemplate =
1233 lyx::getStatus(FuncRequest(LFUN_IN_MATHMACROTEMPLATE)).enabled();
1235 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1236 it->second->update(math, table, review, mathmacrotemplate);
1238 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1239 it->second->update(false, false, false, false);
1243 void GuiView::setBuffer(Buffer * newBuffer)
1245 LYXERR(Debug::DEBUG, "Setting buffer: " << newBuffer << endl);
1246 LASSERT(newBuffer, return);
1249 GuiWorkArea * wa = workArea(*newBuffer);
1251 newBuffer->masterBuffer()->updateBuffer();
1252 wa = addWorkArea(*newBuffer);
1254 //Disconnect the old buffer...there's no new one.
1257 connectBuffer(*newBuffer);
1258 connectBufferView(wa->bufferView());
1259 setCurrentWorkArea(wa);
1265 void GuiView::connectBuffer(Buffer & buf)
1267 buf.setGuiDelegate(this);
1271 void GuiView::disconnectBuffer()
1273 if (d.current_work_area_)
1274 d.current_work_area_->bufferView().buffer().setGuiDelegate(0);
1278 void GuiView::connectBufferView(BufferView & bv)
1280 bv.setGuiDelegate(this);
1284 void GuiView::disconnectBufferView()
1286 if (d.current_work_area_)
1287 d.current_work_area_->bufferView().setGuiDelegate(0);
1291 void GuiView::errors(string const & error_type, bool from_master)
1293 ErrorList & el = from_master ?
1294 currentBufferView()->buffer().masterBuffer()->errorList(error_type)
1295 : currentBufferView()->buffer().errorList(error_type);
1296 string data = error_type;
1298 data = "from_master|" + error_type;
1300 showDialog("errorlist", data);
1304 void GuiView::updateTocItem(string const & type, DocIterator const & dit)
1306 d.toc_models_.updateItem(toqstr(type), dit);
1310 void GuiView::structureChanged()
1312 d.toc_models_.reset(documentBufferView());
1313 // Navigator needs more than a simple update in this case. It needs to be
1315 updateDialog("toc", "");
1319 void GuiView::updateDialog(string const & name, string const & data)
1321 if (!isDialogVisible(name))
1324 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
1325 if (it == d.dialogs_.end())
1328 Dialog * const dialog = it->second.get();
1329 if (dialog->isVisibleView())
1330 dialog->initialiseParams(data);
1334 BufferView * GuiView::documentBufferView()
1336 return currentMainWorkArea()
1337 ? ¤tMainWorkArea()->bufferView()
1342 BufferView const * GuiView::documentBufferView() const
1344 return currentMainWorkArea()
1345 ? ¤tMainWorkArea()->bufferView()
1350 BufferView * GuiView::currentBufferView()
1352 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1356 BufferView const * GuiView::currentBufferView() const
1358 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1362 #if (QT_VERSION >= 0x040400)
1363 docstring GuiView::GuiViewPrivate::saveAndDestroy(Buffer const * orig, Buffer * buffer, FileName const & fname)
1366 FileName const tmp_ret = FileName::tempName("lyxauto");
1367 if (!tmp_ret.empty()) {
1368 if (buffer->writeFile(tmp_ret))
1369 failed = !tmp_ret.moveTo(fname);
1372 // failed to write/rename tmp_ret so try writing direct
1373 failed = buffer->writeFile(fname);
1376 busyBuffers.remove(orig);
1378 ? _("Automatic save failed!")
1379 : _("Automatic save done.");
1384 void GuiView::autoSave()
1386 LYXERR(Debug::INFO, "Running autoSave()");
1388 Buffer * buffer = documentBufferView()
1389 ? &documentBufferView()->buffer() : 0;
1393 #if (QT_VERSION >= 0x040400)
1394 GuiViewPrivate::busyBuffers.insert(buffer);
1395 QFuture<docstring> f = QtConcurrent::run(GuiViewPrivate::saveAndDestroy, buffer, buffer->clone(),
1396 buffer->getAutosaveFileName());
1397 d.autosave_watcher_.setFuture(f);
1404 void GuiView::resetAutosaveTimers()
1407 d.autosave_timeout_.restart();
1411 bool GuiView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1414 Buffer * buf = currentBufferView()
1415 ? ¤tBufferView()->buffer() : 0;
1416 Buffer * doc_buffer = documentBufferView()
1417 ? &(documentBufferView()->buffer()) : 0;
1419 // Check whether we need a buffer
1420 if (!lyxaction.funcHasFlag(cmd.action(), LyXAction::NoBuffer) && !buf) {
1421 // no, exit directly
1422 flag.message(from_utf8(N_("Command not allowed with"
1423 "out any document open")));
1424 flag.setEnabled(false);
1428 if (cmd.origin() == FuncRequest::TOC) {
1429 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
1430 if (!toc || !toc->getStatus(documentBufferView()->cursor(), cmd, flag))
1431 flag.setEnabled(false);
1435 switch(cmd.action()) {
1436 case LFUN_BUFFER_IMPORT:
1439 case LFUN_MASTER_BUFFER_UPDATE:
1440 case LFUN_MASTER_BUFFER_VIEW:
1441 enable = doc_buffer && doc_buffer->parent() != 0
1442 && !d.preview_watcher_.isRunning();
1445 case LFUN_BUFFER_UPDATE:
1446 case LFUN_BUFFER_VIEW: {
1447 if (!doc_buffer || d.preview_watcher_.isRunning()) {
1451 string format = to_utf8(cmd.argument());
1452 if (cmd.argument().empty())
1453 format = doc_buffer->getDefaultOutputFormat();
1454 enable = doc_buffer->isExportableFormat(format);
1458 case LFUN_BUFFER_RELOAD:
1459 enable = doc_buffer && !doc_buffer->isUnnamed()
1460 && doc_buffer->fileName().exists()
1461 && (!doc_buffer->isClean()
1462 || doc_buffer->isExternallyModified(Buffer::timestamp_method));
1465 case LFUN_BUFFER_CHILD_OPEN:
1466 enable = doc_buffer;
1469 case LFUN_BUFFER_WRITE:
1470 enable = doc_buffer && (doc_buffer->isUnnamed() || !doc_buffer->isClean());
1473 //FIXME: This LFUN should be moved to GuiApplication.
1474 case LFUN_BUFFER_WRITE_ALL: {
1475 // We enable the command only if there are some modified buffers
1476 Buffer * first = theBufferList().first();
1481 // We cannot use a for loop as the buffer list is a cycle.
1483 if (!b->isClean()) {
1487 b = theBufferList().next(b);
1488 } while (b != first);
1492 case LFUN_BUFFER_WRITE_AS:
1493 enable = doc_buffer;
1496 case LFUN_BUFFER_CLOSE:
1497 enable = doc_buffer;
1500 case LFUN_BUFFER_CLOSE_ALL:
1501 enable = theBufferList().last() != theBufferList().first();
1504 case LFUN_SPLIT_VIEW:
1505 if (cmd.getArg(0) == "vertical")
1506 enable = doc_buffer && (d.splitter_->count() == 1 ||
1507 d.splitter_->orientation() == Qt::Vertical);
1509 enable = doc_buffer && (d.splitter_->count() == 1 ||
1510 d.splitter_->orientation() == Qt::Horizontal);
1513 case LFUN_CLOSE_TAB_GROUP:
1514 enable = d.currentTabWorkArea();
1517 case LFUN_TOOLBAR_TOGGLE: {
1518 string const name = cmd.getArg(0);
1519 if (GuiToolbar * t = toolbar(name))
1520 flag.setOnOff(t->isVisible());
1523 docstring const msg =
1524 bformat(_("Unknown toolbar \"%1$s\""), from_utf8(name));
1530 case LFUN_DROP_LAYOUTS_CHOICE:
1534 case LFUN_UI_TOGGLE:
1535 flag.setOnOff(isFullScreen());
1538 case LFUN_DIALOG_DISCONNECT_INSET:
1541 case LFUN_DIALOG_HIDE:
1542 // FIXME: should we check if the dialog is shown?
1545 case LFUN_DIALOG_TOGGLE:
1546 flag.setOnOff(isDialogVisible(cmd.getArg(0)));
1547 // fall through to set "enable"
1548 case LFUN_DIALOG_SHOW: {
1549 string const name = cmd.getArg(0);
1551 enable = name == "aboutlyx"
1552 || name == "file" //FIXME: should be removed.
1554 || name == "texinfo"
1555 || name == "progress"
1556 || name == "compare";
1557 else if (name == "print")
1558 enable = doc_buffer->isExportable("dvi")
1559 && lyxrc.print_command != "none";
1560 else if (name == "character" || name == "symbols") {
1561 if (!buf || buf->isReadonly())
1564 // FIXME we should consider passthru
1566 Inset const & in = currentBufferView()->cursor().inset();
1567 enable = !in.getLayout().isPassThru();
1570 else if (name == "latexlog")
1571 enable = FileName(doc_buffer->logName()).isReadableFile();
1572 else if (name == "spellchecker")
1573 enable = theSpellChecker() && !doc_buffer->isReadonly();
1574 else if (name == "vclog")
1575 enable = doc_buffer->lyxvc().inUse();
1579 case LFUN_DIALOG_UPDATE: {
1580 string const name = cmd.getArg(0);
1582 enable = name == "prefs";
1586 case LFUN_COMMAND_EXECUTE:
1588 case LFUN_MENU_OPEN:
1589 // Nothing to check.
1592 case LFUN_COMPLETION_INLINE:
1593 if (!d.current_work_area_
1594 || !d.current_work_area_->completer().inlinePossible(
1595 currentBufferView()->cursor()))
1599 case LFUN_COMPLETION_POPUP:
1600 if (!d.current_work_area_
1601 || !d.current_work_area_->completer().popupPossible(
1602 currentBufferView()->cursor()))
1606 case LFUN_COMPLETION_COMPLETE:
1607 if (!d.current_work_area_
1608 || !d.current_work_area_->completer().inlinePossible(
1609 currentBufferView()->cursor()))
1613 case LFUN_COMPLETION_ACCEPT:
1614 if (!d.current_work_area_
1615 || (!d.current_work_area_->completer().popupVisible()
1616 && !d.current_work_area_->completer().inlineVisible()
1617 && !d.current_work_area_->completer().completionAvailable()))
1621 case LFUN_COMPLETION_CANCEL:
1622 if (!d.current_work_area_
1623 || (!d.current_work_area_->completer().popupVisible()
1624 && !d.current_work_area_->completer().inlineVisible()))
1628 case LFUN_BUFFER_ZOOM_OUT:
1629 enable = doc_buffer && lyxrc.zoom > 10;
1632 case LFUN_BUFFER_ZOOM_IN:
1633 enable = doc_buffer;
1636 case LFUN_BUFFER_NEXT:
1637 case LFUN_BUFFER_PREVIOUS:
1638 // FIXME: should we check is there is an previous or next buffer?
1640 case LFUN_BUFFER_SWITCH:
1641 // toggle on the current buffer, but do not toggle off
1642 // the other ones (is that a good idea?)
1644 && to_utf8(cmd.argument()) == doc_buffer->absFileName())
1645 flag.setOnOff(true);
1648 case LFUN_VC_REGISTER:
1649 enable = doc_buffer && !doc_buffer->lyxvc().inUse();
1651 case LFUN_VC_CHECK_IN:
1652 enable = doc_buffer && doc_buffer->lyxvc().checkInEnabled();
1654 case LFUN_VC_CHECK_OUT:
1655 enable = doc_buffer && doc_buffer->lyxvc().checkOutEnabled();
1657 case LFUN_VC_LOCKING_TOGGLE:
1658 enable = doc_buffer && !doc_buffer->isReadonly()
1659 && doc_buffer->lyxvc().lockingToggleEnabled();
1660 flag.setOnOff(enable && doc_buffer->lyxvc().locking());
1662 case LFUN_VC_REVERT:
1663 enable = doc_buffer && doc_buffer->lyxvc().inUse() && !doc_buffer->isReadonly();
1665 case LFUN_VC_UNDO_LAST:
1666 enable = doc_buffer && doc_buffer->lyxvc().undoLastEnabled();
1668 case LFUN_VC_REPO_UPDATE:
1669 enable = doc_buffer && doc_buffer->lyxvc().repoUpdateEnabled();
1671 case LFUN_VC_COMMAND: {
1672 if (cmd.argument().empty())
1674 if (!doc_buffer && contains(cmd.getArg(0), 'D'))
1678 case LFUN_VC_COMPARE:
1679 enable = doc_buffer && doc_buffer->lyxvc().prepareFileRevisionEnabled();
1682 case LFUN_SERVER_GOTO_FILE_ROW:
1684 case LFUN_FORWARD_SEARCH:
1685 enable = !(lyxrc.forward_search_dvi.empty() && lyxrc.forward_search_pdf.empty());
1693 flag.setEnabled(false);
1699 static FileName selectTemplateFile()
1701 FileDialog dlg(qt_("Select template file"));
1702 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1703 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
1705 FileDialog::Result result = dlg.open(toqstr(lyxrc.template_path),
1706 QStringList(qt_("LyX Documents (*.lyx)")));
1708 if (result.first == FileDialog::Later)
1710 if (result.second.isEmpty())
1712 return FileName(fromqstr(result.second));
1716 Buffer * GuiView::loadDocument(FileName const & filename, bool tolastfiles)
1720 Buffer * newBuffer = checkAndLoadLyXFile(filename);
1723 message(_("Document not loaded."));
1728 setBuffer(newBuffer);
1730 // scroll to the position when the file was last closed
1731 if (lyxrc.use_lastfilepos) {
1732 LastFilePosSection::FilePos filepos =
1733 theSession().lastFilePos().load(filename);
1734 documentBufferView()->moveToPosition(filepos.pit, filepos.pos, 0, 0);
1738 theSession().lastFiles().add(filename);
1745 void GuiView::openDocument(string const & fname)
1747 string initpath = lyxrc.document_path;
1749 if (documentBufferView()) {
1750 string const trypath = documentBufferView()->buffer().filePath();
1751 // If directory is writeable, use this as default.
1752 if (FileName(trypath).isDirWritable())
1758 if (fname.empty()) {
1759 FileDialog dlg(qt_("Select document to open"), LFUN_FILE_OPEN);
1760 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1761 dlg.setButton2(qt_("Examples|#E#e"),
1762 toqstr(addPath(package().system_support().absFileName(), "examples")));
1764 QStringList filter(qt_("LyX Documents (*.lyx)"));
1765 filter << qt_("LyX-1.3.x Documents (*.lyx13)")
1766 << qt_("LyX-1.4.x Documents (*.lyx14)")
1767 << qt_("LyX-1.5.x Documents (*.lyx15)")
1768 << qt_("LyX-1.6.x Documents (*.lyx16)");
1769 FileDialog::Result result =
1770 dlg.open(toqstr(initpath), filter);
1772 if (result.first == FileDialog::Later)
1775 filename = fromqstr(result.second);
1777 // check selected filename
1778 if (filename.empty()) {
1779 message(_("Canceled."));
1785 // get absolute path of file and add ".lyx" to the filename if
1787 FileName const fullname =
1788 fileSearch(string(), filename, "lyx", support::may_not_exist);
1789 if (!fullname.empty())
1790 filename = fullname.absFileName();
1792 if (!fullname.onlyPath().isDirectory()) {
1793 Alert::warning(_("Invalid filename"),
1794 bformat(_("The directory in the given path\n%1$s\ndoes not exist."),
1795 from_utf8(fullname.absFileName())));
1799 // if the file doesn't exist and isn't already open (bug 6645),
1800 // let the user create one
1801 if (!fullname.exists() && !theBufferList().exists(fullname)) {
1802 // the user specifically chose this name. Believe him.
1803 Buffer * const b = newFile(filename, string(), true);
1809 docstring const disp_fn = makeDisplayPath(filename);
1810 message(bformat(_("Opening document %1$s..."), disp_fn));
1813 Buffer * buf = loadDocument(fullname);
1815 // I don't think this is needed, since it will be done in setBuffer().
1816 // buf->updateBuffer();
1818 buf->errors("Parse");
1819 str2 = bformat(_("Document %1$s opened."), disp_fn);
1820 if (buf->lyxvc().inUse())
1821 str2 += " " + from_utf8(buf->lyxvc().versionString()) +
1822 " " + _("Version control detected.");
1824 str2 = bformat(_("Could not open document %1$s"), disp_fn);
1829 // FIXME: clean that
1830 static bool import(GuiView * lv, FileName const & filename,
1831 string const & format, ErrorList & errorList)
1833 FileName const lyxfile(support::changeExtension(filename.absFileName(), ".lyx"));
1835 string loader_format;
1836 vector<string> loaders = theConverters().loaders();
1837 if (find(loaders.begin(), loaders.end(), format) == loaders.end()) {
1838 for (vector<string>::const_iterator it = loaders.begin();
1839 it != loaders.end(); ++it) {
1840 if (!theConverters().isReachable(format, *it))
1843 string const tofile =
1844 support::changeExtension(filename.absFileName(),
1845 formats.extension(*it));
1846 if (!theConverters().convert(0, filename, FileName(tofile),
1847 filename, format, *it, errorList))
1849 loader_format = *it;
1852 if (loader_format.empty()) {
1853 frontend::Alert::error(_("Couldn't import file"),
1854 bformat(_("No information for importing the format %1$s."),
1855 formats.prettyName(format)));
1859 loader_format = format;
1861 if (loader_format == "lyx") {
1862 Buffer * buf = lv->loadDocument(lyxfile);
1865 // I don't think this is needed, since it will be done in setBuffer().
1866 // buf->updateBuffer();
1868 buf->errors("Parse");
1870 Buffer * const b = newFile(lyxfile.absFileName(), string(), true);
1874 bool as_paragraphs = loader_format == "textparagraph";
1875 string filename2 = (loader_format == format) ? filename.absFileName()
1876 : support::changeExtension(filename.absFileName(),
1877 formats.extension(loader_format));
1878 lv->currentBufferView()->insertPlaintextFile(FileName(filename2),
1880 guiApp->setCurrentView(lv);
1881 lyx::dispatch(FuncRequest(LFUN_MARK_OFF));
1888 void GuiView::importDocument(string const & argument)
1891 string filename = split(argument, format, ' ');
1893 LYXERR(Debug::INFO, format << " file: " << filename);
1895 // need user interaction
1896 if (filename.empty()) {
1897 string initpath = lyxrc.document_path;
1898 if (documentBufferView()) {
1899 string const trypath = documentBufferView()->buffer().filePath();
1900 // If directory is writeable, use this as default.
1901 if (FileName(trypath).isDirWritable())
1905 docstring const text = bformat(_("Select %1$s file to import"),
1906 formats.prettyName(format));
1908 FileDialog dlg(toqstr(text), LFUN_BUFFER_IMPORT);
1909 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1910 dlg.setButton2(qt_("Examples|#E#e"),
1911 toqstr(addPath(package().system_support().absFileName(), "examples")));
1913 docstring filter = formats.prettyName(format);
1916 filter += from_utf8(formats.extension(format));
1919 FileDialog::Result result =
1920 dlg.open(toqstr(initpath), fileFilters(toqstr(filter)));
1922 if (result.first == FileDialog::Later)
1925 filename = fromqstr(result.second);
1927 // check selected filename
1928 if (filename.empty())
1929 message(_("Canceled."));
1932 if (filename.empty())
1935 // get absolute path of file
1936 FileName const fullname(support::makeAbsPath(filename));
1938 FileName const lyxfile(support::changeExtension(fullname.absFileName(), ".lyx"));
1940 // Check if the document already is open
1941 Buffer * buf = theBufferList().getBuffer(lyxfile);
1944 if (!closeBuffer()) {
1945 message(_("Canceled."));
1950 docstring const displaypath = makeDisplayPath(lyxfile.absFileName(), 30);
1952 // if the file exists already, and we didn't do
1953 // -i lyx thefile.lyx, warn
1954 if (lyxfile.exists() && fullname != lyxfile) {
1956 docstring text = bformat(_("The document %1$s already exists.\n\n"
1957 "Do you want to overwrite that document?"), displaypath);
1958 int const ret = Alert::prompt(_("Overwrite document?"),
1959 text, 0, 1, _("&Overwrite"), _("&Cancel"));
1962 message(_("Canceled."));
1967 message(bformat(_("Importing %1$s..."), displaypath));
1968 ErrorList errorList;
1969 if (import(this, fullname, format, errorList))
1970 message(_("imported."));
1972 message(_("file not imported!"));
1974 // FIXME (Abdel 12/08/06): Is there a need to display the error list here?
1978 void GuiView::newDocument(string const & filename, bool from_template)
1980 FileName initpath(lyxrc.document_path);
1981 if (documentBufferView()) {
1982 FileName const trypath(documentBufferView()->buffer().filePath());
1983 // If directory is writeable, use this as default.
1984 if (trypath.isDirWritable())
1988 string templatefile;
1989 if (from_template) {
1990 templatefile = selectTemplateFile().absFileName();
1991 if (templatefile.empty())
1996 if (filename.empty())
1997 b = newUnnamedFile(initpath, to_utf8(_("newfile")), templatefile);
1999 b = newFile(filename, templatefile, true);
2004 // If no new document could be created, it is unsure
2005 // whether there is a valid BufferView.
2006 if (currentBufferView())
2007 // Ensure the cursor is correctly positioned on screen.
2008 currentBufferView()->showCursor();
2012 void GuiView::insertLyXFile(docstring const & fname)
2014 BufferView * bv = documentBufferView();
2019 FileName filename(to_utf8(fname));
2021 if (!filename.empty()) {
2022 bv->insertLyXFile(filename);
2026 // Launch a file browser
2028 string initpath = lyxrc.document_path;
2029 string const trypath = bv->buffer().filePath();
2030 // If directory is writeable, use this as default.
2031 if (FileName(trypath).isDirWritable())
2035 FileDialog dlg(qt_("Select LyX document to insert"), LFUN_FILE_INSERT);
2036 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2037 dlg.setButton2(qt_("Examples|#E#e"),
2038 toqstr(addPath(package().system_support().absFileName(),
2041 FileDialog::Result result = dlg.open(toqstr(initpath),
2042 QStringList(qt_("LyX Documents (*.lyx)")));
2044 if (result.first == FileDialog::Later)
2048 filename.set(fromqstr(result.second));
2050 // check selected filename
2051 if (filename.empty()) {
2052 // emit message signal.
2053 message(_("Canceled."));
2057 bv->insertLyXFile(filename);
2061 void GuiView::insertPlaintextFile(docstring const & fname,
2064 BufferView * bv = documentBufferView();
2068 if (!fname.empty() && !FileName::isAbsolute(to_utf8(fname))) {
2069 message(_("Absolute filename expected."));
2074 FileName filename(to_utf8(fname));
2076 if (!filename.empty()) {
2077 bv->insertPlaintextFile(filename, asParagraph);
2081 FileDialog dlg(qt_("Select file to insert"), (asParagraph ?
2082 LFUN_FILE_INSERT_PLAINTEXT_PARA : LFUN_FILE_INSERT_PLAINTEXT));
2084 FileDialog::Result result = dlg.open(toqstr(bv->buffer().filePath()),
2085 QStringList(qt_("All Files (*)")));
2087 if (result.first == FileDialog::Later)
2091 filename.set(fromqstr(result.second));
2093 // check selected filename
2094 if (filename.empty()) {
2095 // emit message signal.
2096 message(_("Canceled."));
2100 bv->insertPlaintextFile(filename, asParagraph);
2104 bool GuiView::renameBuffer(Buffer & b, docstring const & newname)
2106 FileName fname = b.fileName();
2107 FileName const oldname = fname;
2109 if (!newname.empty()) {
2111 fname = support::makeAbsPath(to_utf8(newname), oldname.onlyPath().absFileName());
2113 // Switch to this Buffer.
2116 // No argument? Ask user through dialog.
2118 FileDialog dlg(qt_("Choose a filename to save document as"),
2119 LFUN_BUFFER_WRITE_AS);
2120 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2121 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
2123 if (!isLyXFileName(fname.absFileName()))
2124 fname.changeExtension(".lyx");
2126 FileDialog::Result result =
2127 dlg.save(toqstr(fname.onlyPath().absFileName()),
2128 QStringList(qt_("LyX Documents (*.lyx)")),
2129 toqstr(fname.onlyFileName()));
2131 if (result.first == FileDialog::Later)
2134 fname.set(fromqstr(result.second));
2139 if (!isLyXFileName(fname.absFileName()))
2140 fname.changeExtension(".lyx");
2143 // fname is now the new Buffer location.
2144 if (FileName(fname).exists()) {
2145 docstring const file = makeDisplayPath(fname.absFileName(), 30);
2146 docstring text = bformat(_("The document %1$s already "
2147 "exists.\n\nDo you want to "
2148 "overwrite that document?"),
2150 int const ret = Alert::prompt(_("Overwrite document?"),
2151 text, 0, 2, _("&Overwrite"), _("&Rename"), _("&Cancel"));
2154 case 1: return renameBuffer(b, docstring());
2155 case 2: return false;
2159 FileName oldauto = b.getAutosaveFileName();
2161 // Ok, change the name of the buffer
2162 b.setFileName(fname.absFileName());
2164 bool unnamed = b.isUnnamed();
2165 b.setUnnamed(false);
2166 b.saveCheckSum(fname);
2168 // bring the autosave file with us, just in case.
2169 b.moveAutosaveFile(oldauto);
2171 if (!saveBuffer(b)) {
2172 oldauto = b.getAutosaveFileName();
2173 b.setFileName(oldname.absFileName());
2174 b.setUnnamed(unnamed);
2175 b.saveCheckSum(oldname);
2176 b.moveAutosaveFile(oldauto);
2180 // the file has now been saved to the new location.
2181 // we need to check that the locations of child buffers
2183 b.checkChildBuffers();
2189 bool GuiView::saveBuffer(Buffer & b)
2191 if (workArea(b) && workArea(b)->inDialogMode())
2195 return renameBuffer(b, docstring());
2198 theSession().lastFiles().add(b.fileName());
2202 // Switch to this Buffer.
2205 // FIXME: we don't tell the user *WHY* the save failed !!
2206 docstring const file = makeDisplayPath(b.absFileName(), 30);
2207 docstring text = bformat(_("The document %1$s could not be saved.\n\n"
2208 "Do you want to rename the document and "
2209 "try again?"), file);
2210 int const ret = Alert::prompt(_("Rename and save?"),
2211 text, 0, 2, _("&Rename"), _("&Retry"), _("&Cancel"));
2214 if (!renameBuffer(b, docstring()))
2223 return saveBuffer(b);
2227 bool GuiView::hideWorkArea(GuiWorkArea * wa)
2229 return closeWorkArea(wa, false);
2233 bool GuiView::closeWorkArea(GuiWorkArea * wa)
2235 Buffer & buf = wa->bufferView().buffer();
2236 return closeWorkArea(wa, !buf.parent());
2240 bool GuiView::closeBuffer()
2242 GuiWorkArea * wa = currentMainWorkArea();
2243 setCurrentWorkArea(wa);
2244 Buffer & buf = wa->bufferView().buffer();
2245 return wa && closeWorkArea(wa, !buf.parent());
2249 void GuiView::writeSession() const {
2250 GuiWorkArea const * active_wa = currentMainWorkArea();
2251 for (int i = 0; i < d.splitter_->count(); ++i) {
2252 TabWorkArea * twa = d.tabWorkArea(i);
2253 for (int j = 0; j < twa->count(); ++j) {
2254 GuiWorkArea * wa = static_cast<GuiWorkArea *>(twa->widget(j));
2255 Buffer & buf = wa->bufferView().buffer();
2256 theSession().lastOpened().add(buf.fileName(), wa == active_wa);
2262 bool GuiView::closeBufferAll()
2264 // Close the workareas in all other views
2265 QList<int> const ids = guiApp->viewIds();
2266 for (int i = 0; i != ids.size(); ++i) {
2267 if (id_ != ids[i] && !guiApp->view(ids[i]).closeWorkAreaAll())
2271 // Close our own workareas
2272 if (!closeWorkAreaAll())
2275 // Now close the hidden buffers. We prevent hidden buffers from being
2276 // dirty, so we can just close them.
2277 theBufferList().closeAll();
2282 bool GuiView::closeWorkAreaAll()
2284 setCurrentWorkArea(currentMainWorkArea());
2286 // We might be in a situation that there is still a tabWorkArea, but
2287 // there are no tabs anymore. This can happen when we get here after a
2288 // TabWorkArea::lastWorkAreaRemoved() signal. Therefore we count how
2289 // many TabWorkArea's have no documents anymore.
2292 // We have to call count() each time, because it can happen that
2293 // more than one splitter will disappear in one iteration (bug 5998).
2294 for (; d.splitter_->count() > empty_twa; ) {
2295 TabWorkArea * twa = d.tabWorkArea(empty_twa);
2297 if (twa->count() == 0)
2300 setCurrentWorkArea(twa->currentWorkArea());
2301 if (!closeTabWorkArea(twa))
2309 bool GuiView::closeWorkArea(GuiWorkArea * wa, bool close_buffer)
2314 Buffer & buf = wa->bufferView().buffer();
2316 if (close_buffer && GuiViewPrivate::busyBuffers.contains(&buf)) {
2317 Alert::warning(_("Close document "), _("Document could not be closed because it is processed by LyX."));
2322 return closeBuffer(buf);
2324 if (!inMultiTabs(wa))
2325 if (!saveBufferIfNeeded(buf, true))
2333 bool GuiView::closeBuffer(Buffer & buf)
2335 // If we are in a close_event all children will be closed in some time,
2336 // so no need to do it here. This will ensure that the children end up
2337 // in the session file in the correct order. If we close the master
2338 // buffer, we can close or release the child buffers here too.
2340 ListOfBuffers clist = buf.getChildren();
2341 ListOfBuffers::const_iterator it = clist.begin();
2342 ListOfBuffers::const_iterator const bend = clist.end();
2343 for (; it != bend; ++it) {
2344 // If a child is dirty, do not close
2345 // without user intervention
2346 //FIXME: should we look in other tabworkareas?
2347 Buffer * child_buf = *it;
2348 GuiWorkArea * child_wa = workArea(*child_buf);
2350 if (!closeWorkArea(child_wa, true))
2353 theBufferList().releaseChild(&buf, child_buf);
2356 // goto bookmark to update bookmark pit.
2357 //FIXME: we should update only the bookmarks related to this buffer!
2358 LYXERR(Debug::DEBUG, "GuiView::closeBuffer()");
2359 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
2360 guiApp->gotoBookmark(i+1, false, false);
2362 if (saveBufferIfNeeded(buf, false)) {
2363 buf.removeAutosaveFile();
2364 theBufferList().release(&buf);
2371 bool GuiView::closeTabWorkArea(TabWorkArea * twa)
2373 while (twa == d.currentTabWorkArea()) {
2374 twa->setCurrentIndex(twa->count()-1);
2376 GuiWorkArea * wa = twa->currentWorkArea();
2377 Buffer & b = wa->bufferView().buffer();
2379 // We only want to close the buffer if the same buffer is not visible
2380 // in another view, and if this is not a child and if we are closing
2381 // a view (not a tabgroup).
2382 bool const close_buffer =
2383 !inMultiViews(wa) && !b.parent() && closing_;
2385 if (!closeWorkArea(wa, close_buffer))
2392 bool GuiView::saveBufferIfNeeded(Buffer & buf, bool hiding)
2394 if (buf.isClean() || buf.paragraphs().empty())
2397 // Switch to this Buffer.
2402 if (buf.isUnnamed())
2403 file = from_utf8(buf.fileName().onlyFileName());
2405 file = buf.fileName().displayName(30);
2407 // Bring this window to top before asking questions.
2412 if (hiding && buf.isUnnamed()) {
2413 docstring const text = bformat(_("The document %1$s has not been "
2414 "saved yet.\n\nDo you want to save "
2415 "the document?"), file);
2416 ret = Alert::prompt(_("Save new document?"),
2417 text, 0, 1, _("&Save"), _("&Cancel"));
2421 docstring const text = bformat(_("The document %1$s has unsaved changes."
2422 "\n\nDo you want to save the document or discard the changes?"), file);
2423 ret = Alert::prompt(_("Save changed document?"),
2424 text, 0, 2, _("&Save"), _("&Discard"), _("&Cancel"));
2429 if (!saveBuffer(buf))
2433 // if we crash after this we could
2434 // have no autosave file but I guess
2435 // this is really improbable (Jug)
2436 // Sometime improbable things happen, bug 6857 (ps)
2437 // buf.removeAutosaveFile();
2439 // revert all changes
2450 bool GuiView::inMultiTabs(GuiWorkArea * wa)
2452 Buffer & buf = wa->bufferView().buffer();
2454 for (int i = 0; i != d.splitter_->count(); ++i) {
2455 GuiWorkArea * wa_ = d.tabWorkArea(i)->workArea(buf);
2456 if (wa_ && wa_ != wa)
2459 return inMultiViews(wa);
2463 bool GuiView::inMultiViews(GuiWorkArea * wa)
2465 QList<int> const ids = guiApp->viewIds();
2466 Buffer & buf = wa->bufferView().buffer();
2469 for (int i = 0; i != ids.size() && found_twa <= 1; ++i) {
2473 if (guiApp->view(ids[i]).workArea(buf))
2480 void GuiView::gotoNextOrPreviousBuffer(NextOrPrevious np)
2482 Buffer * const curbuf = documentBufferView()
2483 ? &documentBufferView()->buffer() : 0;
2484 Buffer * nextbuf = curbuf;
2486 if (np == NEXTBUFFER)
2487 nextbuf = theBufferList().next(nextbuf);
2489 nextbuf = theBufferList().previous(nextbuf);
2490 if (nextbuf == curbuf)
2496 if (workArea(*nextbuf))
2503 /// make sure the document is saved
2504 static bool ensureBufferClean(Buffer * buffer)
2506 LASSERT(buffer, return false);
2507 if (buffer->isClean() && !buffer->isUnnamed())
2510 docstring const file = buffer->fileName().displayName(30);
2513 if (!buffer->isUnnamed()) {
2514 text = bformat(_("The document %1$s has unsaved "
2515 "changes.\n\nDo you want to save "
2516 "the document?"), file);
2517 title = _("Save changed document?");
2520 text = bformat(_("The document %1$s has not been "
2521 "saved yet.\n\nDo you want to save "
2522 "the document?"), file);
2523 title = _("Save new document?");
2525 int const ret = Alert::prompt(title, text, 0, 1, _("&Save"), _("&Cancel"));
2528 dispatch(FuncRequest(LFUN_BUFFER_WRITE));
2530 return buffer->isClean() && !buffer->isUnnamed();
2534 bool GuiView::reloadBuffer()
2536 Buffer * buffer = documentBufferView()
2537 ? &(documentBufferView()->buffer()) : 0;
2539 return buffer->reload();
2544 void GuiView::checkExternallyModifiedBuffers()
2546 BufferList::iterator bit = theBufferList().begin();
2547 BufferList::iterator const bend = theBufferList().end();
2548 for (; bit != bend; ++bit) {
2549 if ((*bit)->fileName().exists()
2550 && (*bit)->isExternallyModified(Buffer::checksum_method)) {
2551 docstring text = bformat(_("Document \n%1$s\n has been externally modified."
2552 " Reload now? Any local changes will be lost."),
2553 from_utf8((*bit)->absFileName()));
2554 int const ret = Alert::prompt(_("Reload externally changed document?"),
2555 text, 0, 1, _("&Reload"), _("&Cancel"));
2563 void GuiView::dispatchVC(FuncRequest const & cmd, DispatchResult & dr)
2565 Buffer * buffer = documentBufferView()
2566 ? &(documentBufferView()->buffer()) : 0;
2568 switch (cmd.action()) {
2569 case LFUN_VC_REGISTER:
2570 if (!buffer || !ensureBufferClean(buffer))
2572 if (!buffer->lyxvc().inUse()) {
2573 if (buffer->lyxvc().registrer()) {
2575 dr.suppressMessageUpdate();
2580 case LFUN_VC_CHECK_IN:
2581 if (!buffer || !ensureBufferClean(buffer))
2583 if (buffer->lyxvc().inUse() && !buffer->isReadonly()) {
2584 dr.setMessage(buffer->lyxvc().checkIn());
2585 if (!dr.message().empty())
2590 case LFUN_VC_CHECK_OUT:
2591 if (!buffer || !ensureBufferClean(buffer))
2593 if (buffer->lyxvc().inUse()) {
2594 dr.setMessage(buffer->lyxvc().checkOut());
2599 case LFUN_VC_LOCKING_TOGGLE:
2600 LASSERT(buffer, return);
2601 if (!ensureBufferClean(buffer) || buffer->isReadonly())
2603 if (buffer->lyxvc().inUse()) {
2604 string res = buffer->lyxvc().lockingToggle();
2606 frontend::Alert::error(_("Revision control error."),
2607 _("Error when setting the locking property."));
2615 case LFUN_VC_REVERT:
2616 LASSERT(buffer, return);
2617 buffer->lyxvc().revert();
2619 dr.suppressMessageUpdate();
2622 case LFUN_VC_UNDO_LAST:
2623 LASSERT(buffer, return);
2624 buffer->lyxvc().undoLast();
2626 dr.suppressMessageUpdate();
2629 case LFUN_VC_REPO_UPDATE:
2630 LASSERT(buffer, return);
2631 if (ensureBufferClean(buffer)) {
2632 dr.setMessage(buffer->lyxvc().repoUpdate());
2633 checkExternallyModifiedBuffers();
2637 case LFUN_VC_COMMAND: {
2638 string flag = cmd.getArg(0);
2639 if (buffer && contains(flag, 'R') && !ensureBufferClean(buffer))
2642 if (contains(flag, 'M')) {
2643 if (!Alert::askForText(message, _("LyX VC: Log Message")))
2646 string path = cmd.getArg(1);
2647 if (contains(path, "$$p") && buffer)
2648 path = subst(path, "$$p", buffer->filePath());
2649 LYXERR(Debug::LYXVC, "Directory: " << path);
2651 if (!pp.isReadableDirectory()) {
2652 lyxerr << _("Directory is not accessible.") << endl;
2655 support::PathChanger p(pp);
2657 string command = cmd.getArg(2);
2658 if (command.empty())
2661 command = subst(command, "$$i", buffer->absFileName());
2662 command = subst(command, "$$p", buffer->filePath());
2664 command = subst(command, "$$m", to_utf8(message));
2665 LYXERR(Debug::LYXVC, "Command: " << command);
2667 one.startscript(Systemcall::Wait, command);
2671 if (contains(flag, 'I'))
2672 buffer->markDirty();
2673 if (contains(flag, 'R'))
2679 case LFUN_VC_COMPARE: {
2681 if (cmd.argument().empty()) {
2682 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "comparehistory"));
2686 string rev1 = cmd.getArg(0);
2690 if (!buffer->lyxvc().prepareFileRevision(rev1, f1))
2693 if (isStrInt(rev1) && convert<int>(rev1) <= 0) {
2694 f2 = buffer->absFileName();
2696 string rev2 = cmd.getArg(1);
2700 if (!buffer->lyxvc().prepareFileRevision(rev2, f2))
2704 LYXERR(Debug::LYXVC, "Launching comparison for fetched revisions:\n" <<
2705 f1 << "\n" << f2 << "\n" );
2706 string par = "compare run " + quoteName(f1) + " " + quoteName(f2);
2707 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, par));
2717 void GuiView::openChildDocument(string const & fname)
2719 LASSERT(documentBufferView(), return);
2720 Buffer & buffer = documentBufferView()->buffer();
2721 FileName const filename = support::makeAbsPath(fname, buffer.filePath());
2722 documentBufferView()->saveBookmark(false);
2724 bool parsed = false;
2725 if (theBufferList().exists(filename)) {
2726 child = theBufferList().getBuffer(filename);
2728 message(bformat(_("Opening child document %1$s..."),
2729 makeDisplayPath(filename.absFileName())));
2730 child = loadDocument(filename, false);
2736 // Set the parent name of the child document.
2737 // This makes insertion of citations and references in the child work,
2738 // when the target is in the parent or another child document.
2739 child->setParent(&buffer);
2741 // I don't think this is needed, since it will be called in
2743 // child->masterBuffer()->updateBuffer();
2746 child->errors("Parse");
2750 bool GuiView::goToFileRow(string const & argument)
2754 size_t i = argument.find_last_of(' ');
2755 if (i != string::npos) {
2756 file_name = os::internal_path(trim(argument.substr(0, i)));
2757 istringstream is(argument.substr(i + 1));
2762 if (i == string::npos) {
2763 LYXERR0("Wrong argument: " << argument);
2767 string const abstmp = package().temp_dir().absFileName();
2768 string const realtmp = package().temp_dir().realPath();
2769 // We have to use os::path_prefix_is() here, instead of
2770 // simply prefixIs(), because the file name comes from
2771 // an external application and may need case adjustment.
2772 if (os::path_prefix_is(file_name, abstmp, os::CASE_ADJUSTED)
2773 || os::path_prefix_is(file_name, realtmp, os::CASE_ADJUSTED)) {
2774 // Needed by inverse dvi search. If it is a file
2775 // in tmpdir, call the apropriated function.
2776 // If tmpdir is a symlink, we may have the real
2777 // path passed back, so we correct for that.
2778 if (!prefixIs(file_name, abstmp))
2779 file_name = subst(file_name, realtmp, abstmp);
2780 buf = theBufferList().getBufferFromTmp(file_name);
2782 // Must replace extension of the file to be .lyx
2783 // and get full path
2784 FileName const s = fileSearch(string(),
2785 support::changeExtension(file_name, ".lyx"), "lyx");
2786 // Either change buffer or load the file
2787 if (theBufferList().exists(s))
2788 buf = theBufferList().getBuffer(s);
2789 else if (s.exists()) {
2790 buf = loadDocument(s);
2793 // I don't think this is needed. loadDocument() calls
2794 // setBuffer(), which calls updateBuffer().
2795 // buf->updateBuffer();
2796 buf->errors("Parse");
2799 _("File does not exist: %1$s"),
2800 makeDisplayPath(file_name)));
2805 documentBufferView()->setCursorFromRow(row);
2810 #if (QT_VERSION >= 0x040400)
2811 docstring GuiView::GuiViewPrivate::exportAndDestroy(Buffer const * orig, Buffer * buffer, string const & format)
2813 bool const update_unincluded =
2814 buffer->params().maintain_unincluded_children
2815 && !buffer->params().getIncludedChildren().empty();
2816 bool const success = buffer->doExport(format, true, update_unincluded);
2818 busyBuffers.remove(orig);
2820 ? bformat(_("Successful export to format: %1$s"), from_utf8(format))
2821 : bformat(_("Error exporting to format: %1$s"), from_utf8(format));
2825 docstring GuiView::GuiViewPrivate::previewAndDestroy(Buffer const * orig, Buffer * buffer, string const & format)
2827 bool const update_unincluded =
2828 buffer->params().maintain_unincluded_children
2829 && !buffer->params().getIncludedChildren().empty();
2830 bool const success = buffer->preview(format, update_unincluded);
2832 busyBuffers.remove(orig);
2834 ? bformat(_("Successful preview of format: %1$s"), from_utf8(format))
2835 : bformat(_("Error previewing format: %1$s"), from_utf8(format));
2840 bool GuiView::GuiViewPrivate::asyncBufferProcessing(
2841 string const & argument,
2842 Buffer const * used_buffer,
2843 docstring const & msg,
2844 docstring (*asyncFunc)(Buffer const *, Buffer *, string const &),
2845 bool (Buffer::*syncFunc)(string const &, bool, bool) const,
2846 bool (Buffer::*previewFunc)(string const &, bool) const)
2851 string format = argument;
2852 if (format.empty()) {
2853 format = used_buffer->getDefaultOutputFormat();
2855 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
2857 progress_->clearMessages();
2860 GuiViewPrivate::busyBuffers.insert(used_buffer);
2861 QFuture<docstring> f = QtConcurrent::run(
2864 used_buffer->clone(),
2866 setPreviewFuture(f);
2867 last_export_format = used_buffer->bufferFormat();
2870 // We are asynchronous, so we don't know here anything about the success
2873 bool const update_unincluded =
2874 used_buffer->params().maintain_unincluded_children &&
2875 !used_buffer->params().getIncludedChildren().empty();
2877 return (used_buffer->*syncFunc)(format, true, update_unincluded);
2878 } else if (previewFunc) {
2879 return (used_buffer->*previewFunc)(format, update_unincluded);
2886 void GuiView::dispatch(FuncRequest const & cmd, DispatchResult & dr)
2888 BufferView * bv = currentBufferView();
2889 // By default we won't need any update.
2890 dr.screenUpdate(Update::None);
2891 // assume cmd will be dispatched
2892 dr.dispatched(true);
2894 Buffer * doc_buffer = documentBufferView()
2895 ? &(documentBufferView()->buffer()) : 0;
2897 if (cmd.origin() == FuncRequest::TOC) {
2898 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
2899 // FIXME: do we need to pass a DispatchResult object here?
2900 toc->doDispatch(bv->cursor(), cmd);
2904 string const argument = to_utf8(cmd.argument());
2906 switch(cmd.action()) {
2907 case LFUN_BUFFER_CHILD_OPEN:
2908 openChildDocument(to_utf8(cmd.argument()));
2911 case LFUN_BUFFER_IMPORT:
2912 importDocument(to_utf8(cmd.argument()));
2915 case LFUN_BUFFER_EXPORT: {
2918 // GCC only sees strfwd.h when building merged
2919 if (::lyx::operator==(cmd.argument(), "custom")) {
2920 dispatch(FuncRequest(LFUN_DIALOG_SHOW, "sendto"), dr);
2924 // TODO Remove if we could export asynchronous
2925 if (!doc_buffer->doExport(argument, false)) {
2927 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
2931 /* TODO/Review: Is it a problem to also export the children?
2932 See the update_unincluded flag */
2933 d.asyncBufferProcessing(argument,
2936 &GuiViewPrivate::exportAndDestroy,
2939 // TODO Inform user about success
2944 case LFUN_BUFFER_UPDATE: {
2945 d.asyncBufferProcessing(argument,
2948 &GuiViewPrivate::exportAndDestroy,
2953 case LFUN_BUFFER_VIEW: {
2954 d.asyncBufferProcessing(argument,
2956 _("Previewing ..."),
2957 &GuiViewPrivate::previewAndDestroy,
2962 case LFUN_MASTER_BUFFER_UPDATE: {
2963 d.asyncBufferProcessing(argument,
2964 (doc_buffer ? doc_buffer->masterBuffer() : 0),
2966 &GuiViewPrivate::exportAndDestroy,
2971 case LFUN_MASTER_BUFFER_VIEW: {
2972 d.asyncBufferProcessing(argument,
2973 (doc_buffer ? doc_buffer->masterBuffer() : 0),
2975 &GuiViewPrivate::previewAndDestroy,
2976 0, &Buffer::preview);
2979 case LFUN_BUFFER_SWITCH: {
2980 string const file_name = to_utf8(cmd.argument());
2981 if (!FileName::isAbsolute(file_name)) {
2983 dr.setMessage(_("Absolute filename expected."));
2987 Buffer * buffer = theBufferList().getBuffer(FileName(file_name));
2990 dr.setMessage(_("Document not loaded"));
2994 // Do we open or switch to the buffer in this view ?
2995 if (workArea(*buffer)
2996 || lyxrc.open_buffers_in_tabs || !documentBufferView()) {
3001 // Look for the buffer in other views
3002 QList<int> const ids = guiApp->viewIds();
3004 for (; i != ids.size(); ++i) {
3005 GuiView & gv = guiApp->view(ids[i]);
3006 if (gv.workArea(*buffer)) {
3007 gv.activateWindow();
3008 gv.setBuffer(buffer);
3013 // If necessary, open a new window as a last resort
3014 if (i == ids.size()) {
3015 lyx::dispatch(FuncRequest(LFUN_WINDOW_NEW));
3021 case LFUN_BUFFER_NEXT:
3022 gotoNextOrPreviousBuffer(NEXTBUFFER);
3025 case LFUN_BUFFER_PREVIOUS:
3026 gotoNextOrPreviousBuffer(PREVBUFFER);
3029 case LFUN_COMMAND_EXECUTE: {
3030 bool const show_it = cmd.argument() != "off";
3031 // FIXME: this is a hack, "minibuffer" should not be
3033 if (GuiToolbar * t = toolbar("minibuffer")) {
3034 t->setVisible(show_it);
3035 if (show_it && t->commandBuffer())
3036 t->commandBuffer()->setFocus();
3040 case LFUN_DROP_LAYOUTS_CHOICE:
3041 d.layout_->showPopup();
3044 case LFUN_MENU_OPEN:
3045 if (QMenu * menu = guiApp->menus().menu(toqstr(cmd.argument()), *this))
3046 menu->exec(QCursor::pos());
3049 case LFUN_FILE_INSERT:
3050 insertLyXFile(cmd.argument());
3053 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
3054 insertPlaintextFile(cmd.argument(), true);
3057 case LFUN_FILE_INSERT_PLAINTEXT:
3058 insertPlaintextFile(cmd.argument(), false);
3061 case LFUN_BUFFER_RELOAD: {
3062 LASSERT(doc_buffer, break);
3063 docstring const file = makeDisplayPath(doc_buffer->absFileName(), 20);
3064 docstring text = bformat(_("Any changes will be lost. Are you sure "
3065 "you want to revert to the saved version of the document %1$s?"), file);
3066 int const ret = Alert::prompt(_("Revert to saved document?"),
3067 text, 1, 1, _("&Revert"), _("&Cancel"));
3070 doc_buffer->markClean();
3072 dr.forceBufferUpdate();
3077 case LFUN_BUFFER_WRITE:
3078 LASSERT(doc_buffer, break);
3079 saveBuffer(*doc_buffer);
3082 case LFUN_BUFFER_WRITE_AS:
3083 LASSERT(doc_buffer, break);
3084 renameBuffer(*doc_buffer, cmd.argument());
3087 case LFUN_BUFFER_WRITE_ALL: {
3088 Buffer * first = theBufferList().first();
3091 message(_("Saving all documents..."));
3092 // We cannot use a for loop as the buffer list cycles.
3095 if (!b->isClean()) {
3097 LYXERR(Debug::ACTION, "Saved " << b->absFileName());
3099 b = theBufferList().next(b);
3100 } while (b != first);
3101 dr.setMessage(_("All documents saved."));
3105 case LFUN_BUFFER_CLOSE:
3109 case LFUN_BUFFER_CLOSE_ALL:
3113 case LFUN_TOOLBAR_TOGGLE: {
3114 string const name = cmd.getArg(0);
3115 if (GuiToolbar * t = toolbar(name))
3120 case LFUN_DIALOG_UPDATE: {
3121 string const name = to_utf8(cmd.argument());
3122 if (currentBufferView()) {
3123 Inset * inset = currentBufferView()->editedInset(name);
3124 // Can only update a dialog connected to an existing inset
3127 // FIXME: get rid of this indirection; GuiView ask the inset
3128 // if he is kind enough to update itself...
3129 FuncRequest fr(LFUN_INSET_DIALOG_UPDATE, cmd.argument());
3130 //FIXME: pass DispatchResult here?
3131 inset->dispatch(currentBufferView()->cursor(), fr);
3132 } else if (name == "paragraph") {
3133 lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
3134 } else if (name == "prefs" || name == "document") {
3135 updateDialog(name, string());
3140 case LFUN_DIALOG_TOGGLE: {
3141 if (isDialogVisible(cmd.getArg(0)))
3142 dispatch(FuncRequest(LFUN_DIALOG_HIDE, cmd.argument()), dr);
3144 dispatch(FuncRequest(LFUN_DIALOG_SHOW, cmd.argument()), dr);
3148 case LFUN_DIALOG_DISCONNECT_INSET:
3149 disconnectDialog(to_utf8(cmd.argument()));
3152 case LFUN_DIALOG_HIDE: {
3153 guiApp->hideDialogs(to_utf8(cmd.argument()), 0);
3157 case LFUN_DIALOG_SHOW: {
3158 string const name = cmd.getArg(0);
3159 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
3161 if (name == "character") {
3162 data = freefont2string();
3164 showDialog("character", data);
3165 } else if (name == "latexlog") {
3166 Buffer::LogType type;
3167 string const logfile = doc_buffer->logName(&type);
3169 case Buffer::latexlog:
3172 case Buffer::buildlog:
3176 data += Lexer::quoteString(logfile);
3177 showDialog("log", data);
3178 } else if (name == "vclog") {
3179 string const data = "vc " +
3180 Lexer::quoteString(doc_buffer->lyxvc().getLogFile());
3181 showDialog("log", data);
3182 } else if (name == "symbols") {
3183 data = bv->cursor().getEncoding()->name();
3185 showDialog("symbols", data);
3187 } else if (name == "prefs" && isFullScreen()) {
3188 lfunUiToggle("fullscreen");
3189 showDialog("prefs", data);
3191 showDialog(name, data);
3196 dr.setMessage(cmd.argument());
3199 case LFUN_UI_TOGGLE: {
3200 string arg = cmd.getArg(0);
3201 if (!lfunUiToggle(arg)) {
3202 docstring const msg = "ui-toggle " + _("%1$s unknown command!");
3203 dr.setMessage(bformat(msg, from_utf8(arg)));
3205 // Make sure the keyboard focus stays in the work area.
3210 case LFUN_SPLIT_VIEW: {
3211 LASSERT(doc_buffer, break);
3212 string const orientation = cmd.getArg(0);
3213 d.splitter_->setOrientation(orientation == "vertical"
3214 ? Qt::Vertical : Qt::Horizontal);
3215 TabWorkArea * twa = addTabWorkArea();
3216 GuiWorkArea * wa = twa->addWorkArea(*doc_buffer, *this);
3217 setCurrentWorkArea(wa);
3220 case LFUN_CLOSE_TAB_GROUP:
3221 if (TabWorkArea * twa = d.currentTabWorkArea()) {
3222 closeTabWorkArea(twa);
3223 d.current_work_area_ = 0;
3224 twa = d.currentTabWorkArea();
3225 // Switch to the next GuiWorkArea in the found TabWorkArea.
3227 // Make sure the work area is up to date.
3228 setCurrentWorkArea(twa->currentWorkArea());
3230 setCurrentWorkArea(0);
3235 case LFUN_COMPLETION_INLINE:
3236 if (d.current_work_area_)
3237 d.current_work_area_->completer().showInline();
3240 case LFUN_COMPLETION_POPUP:
3241 if (d.current_work_area_)
3242 d.current_work_area_->completer().showPopup();
3246 case LFUN_COMPLETION_COMPLETE:
3247 if (d.current_work_area_)
3248 d.current_work_area_->completer().tab();
3251 case LFUN_COMPLETION_CANCEL:
3252 if (d.current_work_area_) {
3253 if (d.current_work_area_->completer().popupVisible())
3254 d.current_work_area_->completer().hidePopup();
3256 d.current_work_area_->completer().hideInline();
3260 case LFUN_COMPLETION_ACCEPT:
3261 if (d.current_work_area_)
3262 d.current_work_area_->completer().activate();
3265 case LFUN_BUFFER_ZOOM_IN:
3266 case LFUN_BUFFER_ZOOM_OUT:
3267 if (cmd.argument().empty()) {
3268 if (cmd.action() == LFUN_BUFFER_ZOOM_IN)
3273 lyxrc.zoom += convert<int>(cmd.argument());
3275 if (lyxrc.zoom < 10)
3278 // The global QPixmapCache is used in GuiPainter to cache text
3279 // painting so we must reset it.
3280 QPixmapCache::clear();
3281 guiApp->fontLoader().update();
3282 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
3285 case LFUN_VC_REGISTER:
3286 case LFUN_VC_CHECK_IN:
3287 case LFUN_VC_CHECK_OUT:
3288 case LFUN_VC_REPO_UPDATE:
3289 case LFUN_VC_LOCKING_TOGGLE:
3290 case LFUN_VC_REVERT:
3291 case LFUN_VC_UNDO_LAST:
3292 case LFUN_VC_COMMAND:
3293 case LFUN_VC_COMPARE:
3294 dispatchVC(cmd, dr);
3297 case LFUN_SERVER_GOTO_FILE_ROW:
3298 goToFileRow(to_utf8(cmd.argument()));
3301 case LFUN_FORWARD_SEARCH: {
3302 FileName const path(doc_buffer->temppath());
3303 string const texname = doc_buffer->latexName();
3304 FileName const dviname(addName(path.absFileName(),
3305 support::changeExtension(texname, "dvi")));
3306 FileName const pdfname(addName(path.absFileName(),
3307 support::changeExtension(texname, "pdf")));
3308 if (!dviname.exists() && !pdfname.exists()) {
3309 dr.setMessage(_("Please, preview the document first."));
3312 string outname = dviname.onlyFileName();
3313 string command = lyxrc.forward_search_dvi;
3314 if (!dviname.exists() ||
3315 pdfname.lastModified() > dviname.lastModified()) {
3316 outname = pdfname.onlyFileName();
3317 command = lyxrc.forward_search_pdf;
3320 int row = doc_buffer->texrow().getRowFromIdPos(bv->cursor().paragraph().id(), bv->cursor().pos());
3321 LYXERR(Debug::ACTION, "Forward search: row:" << row
3322 << " id:" << bv->cursor().paragraph().id());
3323 if (!row || command.empty()) {
3324 dr.setMessage(_("Couldn't proceed."));
3327 string texrow = convert<string>(row);
3329 command = subst(command, "$$n", texrow);
3330 command = subst(command, "$$t", texname);
3331 command = subst(command, "$$o", outname);
3333 PathChanger p(path);
3335 one.startscript(Systemcall::DontWait, command);
3339 dr.dispatched(false);
3343 // Part of automatic menu appearance feature.
3344 if (isFullScreen()) {
3345 if (menuBar()->isVisible() && lyxrc.full_screen_menubar)
3347 if (statusBar()->isVisible())
3348 statusBar()->hide();
3355 bool GuiView::lfunUiToggle(string const & ui_component)
3357 if (ui_component == "scrollbar") {
3358 // hide() is of no help
3359 if (d.current_work_area_->verticalScrollBarPolicy() ==
3360 Qt::ScrollBarAlwaysOff)
3362 d.current_work_area_->setVerticalScrollBarPolicy(
3363 Qt::ScrollBarAsNeeded);
3365 d.current_work_area_->setVerticalScrollBarPolicy(
3366 Qt::ScrollBarAlwaysOff);
3367 } else if (ui_component == "statusbar") {
3368 statusBar()->setVisible(!statusBar()->isVisible());
3369 } else if (ui_component == "menubar") {
3370 menuBar()->setVisible(!menuBar()->isVisible());
3372 #if QT_VERSION >= 0x040300
3373 if (ui_component == "frame") {
3375 getContentsMargins(&l, &t, &r, &b);
3376 //are the frames in default state?
3377 d.current_work_area_->setFrameStyle(QFrame::NoFrame);
3379 setContentsMargins(-2, -2, -2, -2);
3381 setContentsMargins(0, 0, 0, 0);
3385 if (ui_component == "fullscreen") {
3393 void GuiView::toggleFullScreen()
3395 if (isFullScreen()) {
3396 for (int i = 0; i != d.splitter_->count(); ++i)
3397 d.tabWorkArea(i)->setFullScreen(false);
3398 #if QT_VERSION >= 0x040300
3399 setContentsMargins(0, 0, 0, 0);
3401 setWindowState(windowState() ^ Qt::WindowFullScreen);
3404 statusBar()->show();
3407 hideDialogs("prefs", 0);
3408 for (int i = 0; i != d.splitter_->count(); ++i)
3409 d.tabWorkArea(i)->setFullScreen(true);
3410 #if QT_VERSION >= 0x040300
3411 setContentsMargins(-2, -2, -2, -2);
3414 setWindowState(windowState() ^ Qt::WindowFullScreen);
3415 statusBar()->hide();
3416 if (lyxrc.full_screen_menubar)
3418 if (lyxrc.full_screen_toolbars) {
3419 ToolbarMap::iterator end = d.toolbars_.end();
3420 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
3425 // give dialogs like the TOC a chance to adapt
3430 Buffer const * GuiView::updateInset(Inset const * inset)
3435 Buffer const * inset_buffer = &(inset->buffer());
3437 for (int i = 0; i != d.splitter_->count(); ++i) {
3438 GuiWorkArea * wa = d.tabWorkArea(i)->currentWorkArea();
3441 Buffer const * buffer = &(wa->bufferView().buffer());
3442 if (inset_buffer == buffer)
3443 wa->scheduleRedraw();
3445 return inset_buffer;
3449 void GuiView::restartCursor()
3451 /* When we move around, or type, it's nice to be able to see
3452 * the cursor immediately after the keypress.
3454 if (d.current_work_area_)
3455 d.current_work_area_->startBlinkingCursor();
3457 // Take this occasion to update the other GUI elements.
3463 void GuiView::updateCompletion(Cursor & cur, bool start, bool keep)
3465 if (d.current_work_area_)
3466 d.current_work_area_->completer().updateVisibility(cur, start, keep);
3471 // This list should be kept in sync with the list of insets in
3472 // src/insets/Inset.cpp. I.e., if a dialog goes with an inset, the
3473 // dialog should have the same name as the inset.
3474 // Changes should be also recorded in LFUN_DIALOG_SHOW doxygen
3475 // docs in LyXAction.cpp.
3477 char const * const dialognames[] = {
3479 "aboutlyx", "bibitem", "bibtex", "box", "branch", "changes", "character",
3480 "citation", "compare", "comparehistory", "document", "errorlist", "ert",
3481 "external", "file", "findreplace", "findreplaceadv", "float", "graphics",
3482 "href", "include", "index", "index_print", "info", "listings", "label", "line",
3483 "log", "mathdelimiter", "mathmatrix", "mathspace", "nomenclature",
3484 "nomencl_print", "note", "paragraph", "phantom", "prefs", "print", "ref",
3485 "sendto", "space", "spellchecker", "symbols", "tabular", "tabularcreate",
3486 "thesaurus", "texinfo", "toc", "view-source", "vspace", "wrap", "progress"};
3488 char const * const * const end_dialognames =
3489 dialognames + (sizeof(dialognames) / sizeof(char *));
3493 cmpCStr(char const * name) : name_(name) {}
3494 bool operator()(char const * other) {
3495 return strcmp(other, name_) == 0;
3502 bool isValidName(string const & name)
3504 return find_if(dialognames, end_dialognames,
3505 cmpCStr(name.c_str())) != end_dialognames;
3511 void GuiView::resetDialogs()
3513 // Make sure that no LFUN uses any GuiView.
3514 guiApp->setCurrentView(0);
3517 constructToolbars();
3518 guiApp->menus().fillMenuBar(menuBar(), this, false);
3519 d.layout_->updateContents(true);
3520 // Now update controls with current buffer.
3521 guiApp->setCurrentView(this);
3527 Dialog * GuiView::findOrBuild(string const & name, bool hide_it)
3529 if (!isValidName(name))
3532 map<string, DialogPtr>::iterator it = d.dialogs_.find(name);
3534 if (it != d.dialogs_.end()) {
3536 it->second->hideView();
3537 return it->second.get();
3540 Dialog * dialog = build(name);
3541 d.dialogs_[name].reset(dialog);
3542 if (lyxrc.allow_geometry_session)
3543 dialog->restoreSession();
3550 void GuiView::showDialog(string const & name, string const & data,
3553 triggerShowDialog(toqstr(name), toqstr(data), inset);
3557 void GuiView::doShowDialog(QString const & qname, QString const & qdata,
3563 const string name = fromqstr(qname);
3564 const string data = fromqstr(qdata);
3568 Dialog * dialog = findOrBuild(name, false);
3570 bool const visible = dialog->isVisibleView();
3571 dialog->showData(data);
3572 if (inset && currentBufferView())
3573 currentBufferView()->editInset(name, inset);
3574 // We only set the focus to the new dialog if it was not yet
3575 // visible in order not to change the existing previous behaviour
3577 // activateWindow is needed for floating dockviews
3578 dialog->asQWidget()->raise();
3579 dialog->asQWidget()->activateWindow();
3580 dialog->asQWidget()->setFocus();
3584 catch (ExceptionMessage const & ex) {
3592 bool GuiView::isDialogVisible(string const & name) const
3594 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3595 if (it == d.dialogs_.end())
3597 return it->second.get()->isVisibleView() && !it->second.get()->isClosing();
3601 void GuiView::hideDialog(string const & name, Inset * inset)
3603 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3604 if (it == d.dialogs_.end())
3607 if (inset && currentBufferView()
3608 && inset != currentBufferView()->editedInset(name))
3611 Dialog * const dialog = it->second.get();
3612 if (dialog->isVisibleView())
3614 if (currentBufferView())
3615 currentBufferView()->editInset(name, 0);
3619 void GuiView::disconnectDialog(string const & name)
3621 if (!isValidName(name))
3623 if (currentBufferView())
3624 currentBufferView()->editInset(name, 0);
3628 void GuiView::hideAll() const
3630 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
3631 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3633 for(; it != end; ++it)
3634 it->second->hideView();
3638 void GuiView::updateDialogs()
3640 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
3641 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3643 for(; it != end; ++it) {
3644 Dialog * dialog = it->second.get();
3646 if (dialog->needBufferOpen() && !documentBufferView())
3647 hideDialog(fromqstr(dialog->name()), 0);
3648 else if (dialog->isVisibleView())
3649 dialog->checkStatus();
3656 Dialog * createDialog(GuiView & lv, string const & name);
3658 // will be replaced by a proper factory...
3659 Dialog * createGuiAbout(GuiView & lv);
3660 Dialog * createGuiBibtex(GuiView & lv);
3661 Dialog * createGuiChanges(GuiView & lv);
3662 Dialog * createGuiCharacter(GuiView & lv);
3663 Dialog * createGuiCitation(GuiView & lv);
3664 Dialog * createGuiCompare(GuiView & lv);
3665 Dialog * createGuiCompareHistory(GuiView & lv);
3666 Dialog * createGuiDelimiter(GuiView & lv);
3667 Dialog * createGuiDocument(GuiView & lv);
3668 Dialog * createGuiErrorList(GuiView & lv);
3669 Dialog * createGuiExternal(GuiView & lv);
3670 Dialog * createGuiGraphics(GuiView & lv);
3671 Dialog * createGuiInclude(GuiView & lv);
3672 Dialog * createGuiIndex(GuiView & lv);
3673 Dialog * createGuiLabel(GuiView & lv);
3674 Dialog * createGuiListings(GuiView & lv);
3675 Dialog * createGuiLog(GuiView & lv);
3676 Dialog * createGuiMathMatrix(GuiView & lv);
3677 Dialog * createGuiNomenclature(GuiView & lv);
3678 Dialog * createGuiNote(GuiView & lv);
3679 Dialog * createGuiParagraph(GuiView & lv);
3680 Dialog * createGuiPhantom(GuiView & lv);
3681 Dialog * createGuiPreferences(GuiView & lv);
3682 Dialog * createGuiPrint(GuiView & lv);
3683 Dialog * createGuiPrintindex(GuiView & lv);
3684 Dialog * createGuiPrintNomencl(GuiView & lv);
3685 Dialog * createGuiRef(GuiView & lv);
3686 Dialog * createGuiSearch(GuiView & lv);
3687 Dialog * createGuiSearchAdv(GuiView & lv);
3688 Dialog * createGuiSendTo(GuiView & lv);
3689 Dialog * createGuiShowFile(GuiView & lv);
3690 Dialog * createGuiSpellchecker(GuiView & lv);
3691 Dialog * createGuiSymbols(GuiView & lv);
3692 Dialog * createGuiTabularCreate(GuiView & lv);
3693 Dialog * createGuiTexInfo(GuiView & lv);
3694 Dialog * createGuiToc(GuiView & lv);
3695 Dialog * createGuiThesaurus(GuiView & lv);
3696 Dialog * createGuiHyperlink(GuiView & lv);
3697 Dialog * createGuiViewSource(GuiView & lv);
3698 Dialog * createGuiWrap(GuiView & lv);
3699 Dialog * createGuiProgressView(GuiView & lv);
3703 Dialog * GuiView::build(string const & name)
3705 LASSERT(isValidName(name), return 0);
3707 Dialog * dialog = createDialog(*this, name);
3711 if (name == "aboutlyx")
3712 return createGuiAbout(*this);
3713 if (name == "bibtex")
3714 return createGuiBibtex(*this);
3715 if (name == "changes")
3716 return createGuiChanges(*this);
3717 if (name == "character")
3718 return createGuiCharacter(*this);
3719 if (name == "citation")
3720 return createGuiCitation(*this);
3721 if (name == "compare")
3722 return createGuiCompare(*this);
3723 if (name == "comparehistory")
3724 return createGuiCompareHistory(*this);
3725 if (name == "document")
3726 return createGuiDocument(*this);
3727 if (name == "errorlist")
3728 return createGuiErrorList(*this);
3729 if (name == "external")
3730 return createGuiExternal(*this);
3732 return createGuiShowFile(*this);
3733 if (name == "findreplace")
3734 return createGuiSearch(*this);
3735 if (name == "findreplaceadv")
3736 return createGuiSearchAdv(*this);
3737 if (name == "graphics")
3738 return createGuiGraphics(*this);
3740 return createGuiHyperlink(*this);
3741 if (name == "include")
3742 return createGuiInclude(*this);
3743 if (name == "index")
3744 return createGuiIndex(*this);
3745 if (name == "index_print")
3746 return createGuiPrintindex(*this);
3747 if (name == "label")
3748 return createGuiLabel(*this);
3749 if (name == "listings")
3750 return createGuiListings(*this);
3752 return createGuiLog(*this);
3753 if (name == "mathdelimiter")
3754 return createGuiDelimiter(*this);
3755 if (name == "mathmatrix")
3756 return createGuiMathMatrix(*this);
3757 if (name == "nomenclature")
3758 return createGuiNomenclature(*this);
3759 if (name == "nomencl_print")
3760 return createGuiPrintNomencl(*this);
3762 return createGuiNote(*this);
3763 if (name == "paragraph")
3764 return createGuiParagraph(*this);
3765 if (name == "phantom")
3766 return createGuiPhantom(*this);
3767 if (name == "prefs")
3768 return createGuiPreferences(*this);
3769 if (name == "print")
3770 return createGuiPrint(*this);
3772 return createGuiRef(*this);
3773 if (name == "sendto")
3774 return createGuiSendTo(*this);
3775 if (name == "spellchecker")
3776 return createGuiSpellchecker(*this);
3777 if (name == "symbols")
3778 return createGuiSymbols(*this);
3779 if (name == "tabularcreate")
3780 return createGuiTabularCreate(*this);
3781 if (name == "texinfo")
3782 return createGuiTexInfo(*this);
3783 if (name == "thesaurus")
3784 return createGuiThesaurus(*this);
3786 return createGuiToc(*this);
3787 if (name == "view-source")
3788 return createGuiViewSource(*this);
3790 return createGuiWrap(*this);
3791 if (name == "progress")
3792 return createGuiProgressView(*this);
3798 } // namespace frontend
3801 #include "moc_GuiView.cpp"