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 "GuiProgress.h"
30 #include "LayoutBox.h"
34 #include "qt_helpers.h"
36 #include "frontends/alert.h"
38 #include "buffer_funcs.h"
40 #include "BufferList.h"
41 #include "BufferParams.h"
42 #include "BufferView.h"
44 #include "Converter.h"
46 #include "CutAndPaste.h"
48 #include "ErrorList.h"
50 #include "FuncStatus.h"
51 #include "FuncRequest.h"
55 #include "LyXAction.h"
59 #include "Paragraph.h"
60 #include "SpellChecker.h"
62 #include "TextClass.h"
67 #include "support/convert.h"
68 #include "support/debug.h"
69 #include "support/ExceptionMessage.h"
70 #include "support/FileName.h"
71 #include "support/filetools.h"
72 #include "support/gettext.h"
73 #include "support/filetools.h"
74 #include "support/ForkedCalls.h"
75 #include "support/lassert.h"
76 #include "support/lstrings.h"
77 #include "support/os.h"
78 #include "support/Package.h"
79 #include "support/Path.h"
80 #include "support/Systemcall.h"
81 #include "support/Timeout.h"
82 #include "support/ProgressInterface.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 int tabWorkAreaCount()
288 return splitter_->count();
291 TabWorkArea * tabWorkArea(int i)
293 return dynamic_cast<TabWorkArea *>(splitter_->widget(i));
296 TabWorkArea * currentTabWorkArea()
298 int areas = tabWorkAreaCount();
300 // The first TabWorkArea is always the first one, if any.
301 return tabWorkArea(0);
303 for (int i = 0; i != areas; ++i) {
304 TabWorkArea * twa = tabWorkArea(i);
305 if (current_main_work_area_ == twa->currentWorkArea())
309 // None has the focus so we just take the first one.
310 return tabWorkArea(0);
313 #if (QT_VERSION >= 0x040400)
314 void setPreviewFuture(QFuture<docstring> const & f)
316 if (processing_thread_watcher_.isRunning()) {
317 // we prefer to cancel this preview in order to keep a snappy
321 processing_thread_watcher_.setFuture(f);
327 GuiWorkArea * current_work_area_;
328 GuiWorkArea * current_main_work_area_;
329 QSplitter * splitter_;
330 QStackedWidget * stack_widget_;
331 BackgroundWidget * bg_widget_;
333 ToolbarMap toolbars_;
334 ProgressInterface* progress_;
335 /// The main layout box.
337 * \warning Don't Delete! The layout box is actually owned by
338 * whichever toolbar contains it. All the GuiView class needs is a
339 * means of accessing it.
341 * FIXME: replace that with a proper model so that we are not limited
342 * to only one dialog.
347 map<string, DialogPtr> dialogs_;
349 unsigned int smallIconSize;
350 unsigned int normalIconSize;
351 unsigned int bigIconSize;
353 QTimer statusbar_timer_;
354 /// auto-saving of buffers
355 Timeout autosave_timeout_;
356 /// flag against a race condition due to multiclicks, see bug #1119
360 TocModels toc_models_;
362 #if (QT_VERSION >= 0x040400)
364 QFutureWatcher<docstring> autosave_watcher_;
365 QFutureWatcher<docstring> processing_thread_watcher_;
367 string last_export_format;
369 struct DummyWatcher { bool isRunning(){return false;} };
370 DummyWatcher processing_thread_watcher_;
373 static QSet<Buffer const *> busyBuffers;
374 static docstring previewAndDestroy(Buffer const * orig, Buffer * buffer, string const & format);
375 static docstring exportAndDestroy(Buffer const * orig, Buffer * buffer, string const & format);
376 static docstring compileAndDestroy(Buffer const * orig, Buffer * buffer, string const & format);
377 static docstring saveAndDestroy(Buffer const * orig, Buffer * buffer, FileName const & fname);
380 static docstring runAndDestroy(const T& func, Buffer const * orig, Buffer * buffer, string const & format, string const & msg);
382 // TODO syncFunc/previewFunc: use bind
383 bool asyncBufferProcessing(string const & argument,
384 Buffer const * used_buffer,
385 docstring const & msg,
386 docstring (*asyncFunc)(Buffer const *, Buffer *, string const &),
387 bool (Buffer::*syncFunc)(string const &, bool, bool) const,
388 bool (Buffer::*previewFunc)(string const &, bool) const);
390 QTimer processing_cursor_timer_;
391 bool indicates_processing_;
392 QMap<GuiWorkArea*, Qt::CursorShape> orig_cursors_;
393 QVector<GuiWorkArea*> guiWorkAreas();
396 QSet<Buffer const *> GuiView::GuiViewPrivate::busyBuffers;
399 GuiView::GuiView(int id)
400 : d(*new GuiViewPrivate(this)), id_(id), closing_(false)
402 // GuiToolbars *must* be initialised before the menu bar.
403 normalSizedIcons(); // at least on Mac the default is 32 otherwise, which is huge
406 // set ourself as the current view. This is needed for the menu bar
407 // filling, at least for the static special menu item on Mac. Otherwise
408 // they are greyed out.
409 guiApp->setCurrentView(this);
411 // Fill up the menu bar.
412 guiApp->menus().fillMenuBar(menuBar(), this, true);
414 setCentralWidget(d.stack_widget_);
416 // Start autosave timer
417 if (lyxrc.autosave) {
418 d.autosave_timeout_.timeout.connect(bind(&GuiView::autoSave, this));
419 d.autosave_timeout_.setTimeout(lyxrc.autosave * 1000);
420 d.autosave_timeout_.start();
422 connect(&d.statusbar_timer_, SIGNAL(timeout()),
423 this, SLOT(clearMessage()));
425 // We don't want to keep the window in memory if it is closed.
426 setAttribute(Qt::WA_DeleteOnClose, true);
428 #if (!defined(Q_WS_WIN) && !defined(Q_WS_MACX))
429 // assign an icon to main form. We do not do it under Qt/Win or Qt/Mac,
430 // since the icon is provided in the application bundle.
431 setWindowIcon(getPixmap("images/", "lyx", "png"));
434 #if (QT_VERSION >= 0x040300)
435 // use tabbed dock area for multiple docks
436 // (such as "source" and "messages")
437 setDockOptions(QMainWindow::ForceTabbedDocks);
441 setAcceptDrops(true);
443 statusBar()->setSizeGripEnabled(true);
446 #if (QT_VERSION >= 0x040400)
447 connect(&d.autosave_watcher_, SIGNAL(finished()), this,
448 SLOT(processingThreadFinished()));
449 connect(&d.processing_thread_watcher_, SIGNAL(finished()), this,
450 SLOT(processingThreadFinished()));
452 d.processing_cursor_timer_.setInterval(1000 * 3);
453 connect(&d.processing_cursor_timer_, SIGNAL(timeout()), this,
454 SLOT(indicateProcessing()));
457 connect(this, SIGNAL(triggerShowDialog(QString const &, QString const &, Inset *)),
458 SLOT(doShowDialog(QString const &, QString const &, Inset *)));
460 // Forbid too small unresizable window because it can happen
461 // with some window manager under X11.
462 setMinimumSize(300, 200);
464 if (lyxrc.allow_geometry_session) {
465 // Now take care of session management.
470 // no session handling, default to a sane size.
471 setGeometry(50, 50, 690, 510);
474 // clear session data if any.
476 settings.remove("views");
486 QVector<GuiWorkArea*> GuiView::GuiViewPrivate::guiWorkAreas()
488 QVector<GuiWorkArea*> areas;
489 for (int i = 0; i < tabWorkAreaCount(); i++) {
490 TabWorkArea* ta = tabWorkArea(i);
491 for (int u = 0; u < ta->count(); u++) {
492 areas << ta->workArea(u);
498 void GuiView::setCursorShapes(Qt::CursorShape shape)
500 QVector<GuiWorkArea*> areas = d.guiWorkAreas();
501 Q_FOREACH(GuiWorkArea* wa, areas) {
502 wa->setCursorShape(shape);
506 void GuiView::restoreCursorShapes()
508 QVector<GuiWorkArea*> areas = d.guiWorkAreas();
509 Q_FOREACH(GuiWorkArea* wa, areas) {
510 if (d.orig_cursors_.contains(wa)) {
511 wa->setCursorShape(d.orig_cursors_[wa]);
516 void GuiView::saveCursorShapes()
518 d.orig_cursors_.clear();
519 QVector<GuiWorkArea*> areas = d.guiWorkAreas();
520 Q_FOREACH(GuiWorkArea* wa, areas) {
521 d.orig_cursors_[wa] = wa->cursorShape();
525 void GuiView::indicateProcessing()
527 if (d.indicates_processing_) {
528 restoreCursorShapes();
530 setCursorShapes(Qt::BusyCursor);
532 d.indicates_processing_ = !d.indicates_processing_;
535 void GuiView::processingThreadStarted()
538 d.indicates_processing_ = false;
539 indicateProcessing();
540 d.processing_cursor_timer_.start();
543 void GuiView::processingThreadFinished()
545 #if (QT_VERSION >= 0x040400)
546 QFutureWatcher<docstring> const * watcher =
547 static_cast<QFutureWatcher<docstring> const *>(sender());
548 message(watcher->result());
550 errors(d.last_export_format);
551 d.processing_cursor_timer_.stop();
552 restoreCursorShapes();
553 d.indicates_processing_ = false;
558 void GuiView::saveLayout() const
561 settings.beginGroup("views");
562 settings.beginGroup(QString::number(id_));
564 settings.setValue("pos", pos());
565 settings.setValue("size", size());
567 settings.setValue("geometry", saveGeometry());
569 settings.setValue("layout", saveState(0));
570 settings.setValue("icon_size", iconSize());
574 bool GuiView::restoreLayout()
577 settings.beginGroup("views");
578 settings.beginGroup(QString::number(id_));
579 QString const icon_key = "icon_size";
580 if (!settings.contains(icon_key))
583 //code below is skipped when when ~/.config/LyX is (re)created
584 setIconSize(settings.value(icon_key).toSize());
586 QPoint pos = settings.value("pos", QPoint(50, 50)).toPoint();
587 QSize size = settings.value("size", QSize(690, 510)).toSize();
591 // Work-around for bug #6034: the window ends up in an undetermined
592 // state when trying to restore a maximized window when it is
593 // already maximized.
594 if (!(windowState() & Qt::WindowMaximized))
595 if (!restoreGeometry(settings.value("geometry").toByteArray()))
596 setGeometry(50, 50, 690, 510);
598 // Make sure layout is correctly oriented.
599 setLayoutDirection(qApp->layoutDirection());
601 // Allow the toc and view-source dock widget to be restored if needed.
603 if ((dialog = findOrBuild("toc", true)))
604 // see bug 5082. At least setup title and enabled state.
605 // Visibility will be adjusted by restoreState below.
606 dialog->prepareView();
607 if ((dialog = findOrBuild("view-source", true)))
608 dialog->prepareView();
609 if ((dialog = findOrBuild("progress", true)))
610 dialog->prepareView();
612 if (!restoreState(settings.value("layout").toByteArray(), 0))
619 GuiToolbar * GuiView::toolbar(string const & name)
621 ToolbarMap::iterator it = d.toolbars_.find(name);
622 if (it != d.toolbars_.end())
625 LYXERR(Debug::GUI, "Toolbar::display: no toolbar named " << name);
630 void GuiView::constructToolbars()
632 ToolbarMap::iterator it = d.toolbars_.begin();
633 for (; it != d.toolbars_.end(); ++it)
637 // I don't like doing this here, but the standard toolbar
638 // destroys this object when it's destroyed itself (vfr)
639 d.layout_ = new LayoutBox(*this);
640 d.stack_widget_->addWidget(d.layout_);
641 d.layout_->move(0,0);
643 // extracts the toolbars from the backend
644 Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
645 Toolbars::Infos::iterator end = guiApp->toolbars().end();
646 for (; cit != end; ++cit)
647 d.toolbars_[cit->name] = new GuiToolbar(*cit, *this);
651 void GuiView::initToolbars()
653 // extracts the toolbars from the backend
654 Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
655 Toolbars::Infos::iterator end = guiApp->toolbars().end();
656 for (; cit != end; ++cit) {
657 GuiToolbar * tb = toolbar(cit->name);
660 int const visibility = guiApp->toolbars().defaultVisibility(cit->name);
661 bool newline = !(visibility & Toolbars::SAMEROW);
662 tb->setVisible(false);
663 tb->setVisibility(visibility);
665 if (visibility & Toolbars::TOP) {
667 addToolBarBreak(Qt::TopToolBarArea);
668 addToolBar(Qt::TopToolBarArea, tb);
671 if (visibility & Toolbars::BOTTOM) {
672 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
673 #if (QT_VERSION >= 0x040202)
675 addToolBarBreak(Qt::BottomToolBarArea);
677 addToolBar(Qt::BottomToolBarArea, tb);
680 if (visibility & Toolbars::LEFT) {
681 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
682 #if (QT_VERSION >= 0x040202)
684 addToolBarBreak(Qt::LeftToolBarArea);
686 addToolBar(Qt::LeftToolBarArea, tb);
689 if (visibility & Toolbars::RIGHT) {
690 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
691 #if (QT_VERSION >= 0x040202)
693 addToolBarBreak(Qt::RightToolBarArea);
695 addToolBar(Qt::RightToolBarArea, tb);
698 if (visibility & Toolbars::ON)
699 tb->setVisible(true);
704 TocModels & GuiView::tocModels()
706 return d.toc_models_;
710 void GuiView::setFocus()
712 LYXERR(Debug::DEBUG, "GuiView::setFocus()" << this);
713 QMainWindow::setFocus();
717 void GuiView::focusInEvent(QFocusEvent * e)
719 LYXERR(Debug::DEBUG, "GuiView::focusInEvent()" << this);
720 QMainWindow::focusInEvent(e);
721 // Make sure guiApp points to the correct view.
722 guiApp->setCurrentView(this);
723 if (currentMainWorkArea())
724 currentMainWorkArea()->setFocus();
725 else if (currentWorkArea())
726 currentWorkArea()->setFocus();
728 d.bg_widget_->setFocus();
732 QMenu * GuiView::createPopupMenu()
734 return d.toolBarPopup(this);
738 void GuiView::showEvent(QShowEvent * e)
740 LYXERR(Debug::GUI, "Passed Geometry "
741 << size().height() << "x" << size().width()
742 << "+" << pos().x() << "+" << pos().y());
744 if (d.splitter_->count() == 0)
745 // No work area, switch to the background widget.
748 QMainWindow::showEvent(e);
752 bool GuiView::closeScheduled()
759 /** Destroy only all tabbed WorkAreas. Destruction of other WorkAreas
760 ** is responsibility of the container (e.g., dialog)
762 void GuiView::closeEvent(QCloseEvent * close_event)
764 LYXERR(Debug::DEBUG, "GuiView::closeEvent()");
766 if (!GuiViewPrivate::busyBuffers.isEmpty()) {
767 Alert::warning(_("Exit LyX"), _("LyX could not be closed because documents are processed by LyX."));
768 close_event->setAccepted(false);
772 // If the user pressed the x (so we didn't call closeView
773 // programmatically), we want to clear all existing entries.
775 theSession().lastOpened().clear();
780 // it can happen that this event arrives without selecting the view,
781 // e.g. when clicking the close button on a background window.
783 if (!closeWorkAreaAll()) {
785 close_event->ignore();
789 // Make sure that nothing will use this to be closed View.
790 guiApp->unregisterView(this);
792 if (isFullScreen()) {
793 // Switch off fullscreen before closing.
798 // Make sure the timer time out will not trigger a statusbar update.
799 d.statusbar_timer_.stop();
801 // Saving fullscreen requires additional tweaks in the toolbar code.
802 // It wouldn't also work under linux natively.
803 if (lyxrc.allow_geometry_session) {
804 // Save this window geometry and layout.
806 // Then the toolbar private states.
807 ToolbarMap::iterator end = d.toolbars_.end();
808 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
809 it->second->saveSession();
810 // Now take care of all other dialogs:
811 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
812 for (; it!= d.dialogs_.end(); ++it)
813 it->second->saveSession();
816 close_event->accept();
820 void GuiView::dragEnterEvent(QDragEnterEvent * event)
822 if (event->mimeData()->hasUrls())
824 /// \todo Ask lyx-devel is this is enough:
825 /// if (event->mimeData()->hasFormat("text/plain"))
826 /// event->acceptProposedAction();
830 void GuiView::dropEvent(QDropEvent * event)
832 QList<QUrl> files = event->mimeData()->urls();
836 LYXERR(Debug::GUI, "GuiView::dropEvent: got URLs!");
837 for (int i = 0; i != files.size(); ++i) {
838 string const file = os::internal_path(fromqstr(
839 files.at(i).toLocalFile()));
843 string const ext = support::getExtension(file);
844 vector<const Format *> found_formats;
846 // Find all formats that have the correct extension.
847 vector<const Format *> const & import_formats
848 = theConverters().importableFormats();
849 vector<const Format *>::const_iterator it = import_formats.begin();
850 for (; it != import_formats.end(); ++it)
851 if ((*it)->extension() == ext)
852 found_formats.push_back(*it);
855 if (found_formats.size() >= 1) {
856 if (found_formats.size() > 1) {
857 //FIXME: show a dialog to choose the correct importable format
859 "Multiple importable formats found, selecting first");
861 string const arg = found_formats[0]->name() + " " + file;
862 cmd = FuncRequest(LFUN_BUFFER_IMPORT, arg);
865 //FIXME: do we have to explicitly check whether it's a lyx file?
867 "No formats found, trying to open it as a lyx file");
868 cmd = FuncRequest(LFUN_FILE_OPEN, file);
870 // add the functions to the queue
871 guiApp->addToFuncRequestQueue(cmd);
874 // now process the collected functions. We perform the events
875 // asynchronously. This prevents potential problems in case the
876 // BufferView is closed within an event.
877 guiApp->processFuncRequestQueueAsync();
881 void GuiView::message(docstring const & str)
883 if (ForkedProcess::iAmAChild())
886 // call is moved to GUI-thread by GuiProgress
887 d.progress_->appendMessage(toqstr(str));
891 void GuiView::clearMessageText()
893 message(docstring());
897 void GuiView::updateStatusBarMessage(QString const & str)
899 statusBar()->showMessage(str);
900 d.statusbar_timer_.stop();
901 d.statusbar_timer_.start(3000);
905 void GuiView::smallSizedIcons()
907 setIconSize(QSize(d.smallIconSize, d.smallIconSize));
911 void GuiView::normalSizedIcons()
913 setIconSize(QSize(d.normalIconSize, d.normalIconSize));
917 void GuiView::bigSizedIcons()
919 setIconSize(QSize(d.bigIconSize, d.bigIconSize));
923 void GuiView::clearMessage()
925 // FIXME: This code was introduced in r19643 to fix bug #4123. However,
926 // the hasFocus function mostly returns false, even if the focus is on
927 // a workarea in this view.
931 d.statusbar_timer_.stop();
935 void GuiView::updateWindowTitle(GuiWorkArea * wa)
937 if (wa != d.current_work_area_
938 || wa->bufferView().buffer().isInternal())
940 setWindowTitle(qt_("LyX: ") + wa->windowTitle());
941 setWindowIconText(wa->windowIconText());
945 void GuiView::on_currentWorkAreaChanged(GuiWorkArea * wa)
948 disconnectBufferView();
949 connectBufferView(wa->bufferView());
950 connectBuffer(wa->bufferView().buffer());
951 d.current_work_area_ = wa;
952 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
953 this, SLOT(updateWindowTitle(GuiWorkArea *)));
954 updateWindowTitle(wa);
958 // The document settings needs to be reinitialised.
959 updateDialog("document", "");
961 // Buffer-dependent dialogs must be updated. This is done here because
962 // some dialogs require buffer()->text.
967 void GuiView::on_lastWorkAreaRemoved()
970 // We already are in a close event. Nothing more to do.
973 if (d.splitter_->count() > 1)
974 // We have a splitter so don't close anything.
977 // Reset and updates the dialogs.
978 d.toc_models_.reset(0);
979 updateDialog("document", "");
982 resetWindowTitleAndIconText();
985 if (lyxrc.open_buffers_in_tabs)
986 // Nothing more to do, the window should stay open.
989 if (guiApp->viewIds().size() > 1) {
995 // On Mac we also close the last window because the application stay
996 // resident in memory. On other platforms we don't close the last
997 // window because this would quit the application.
1003 void GuiView::updateStatusBar()
1005 // let the user see the explicit message
1006 if (d.statusbar_timer_.isActive())
1013 void GuiView::showMessage()
1015 QString msg = toqstr(theGuiApp()->viewStatusMessage());
1016 if (msg.isEmpty()) {
1017 BufferView const * bv = currentBufferView();
1019 msg = toqstr(bv->cursor().currentState());
1021 msg = qt_("Welcome to LyX!");
1023 statusBar()->showMessage(msg);
1027 bool GuiView::event(QEvent * e)
1031 // Useful debug code:
1032 //case QEvent::ActivationChange:
1033 //case QEvent::WindowDeactivate:
1034 //case QEvent::Paint:
1035 //case QEvent::Enter:
1036 //case QEvent::Leave:
1037 //case QEvent::HoverEnter:
1038 //case QEvent::HoverLeave:
1039 //case QEvent::HoverMove:
1040 //case QEvent::StatusTip:
1041 //case QEvent::DragEnter:
1042 //case QEvent::DragLeave:
1043 //case QEvent::Drop:
1046 case QEvent::WindowActivate: {
1047 GuiView * old_view = guiApp->currentView();
1048 if (this == old_view) {
1050 return QMainWindow::event(e);
1052 if (old_view && old_view->currentBufferView()) {
1053 // save current selection to the selection buffer to allow
1054 // middle-button paste in this window.
1055 cap::saveSelection(old_view->currentBufferView()->cursor());
1057 guiApp->setCurrentView(this);
1058 if (d.current_work_area_) {
1059 BufferView & bv = d.current_work_area_->bufferView();
1060 connectBufferView(bv);
1061 connectBuffer(bv.buffer());
1062 // The document structure, name and dialogs might have
1063 // changed in another view.
1065 // The document settings needs to be reinitialised.
1066 updateDialog("document", "");
1069 resetWindowTitleAndIconText();
1072 return QMainWindow::event(e);
1075 case QEvent::ShortcutOverride: {
1078 #if (!defined Q_WS_X11) || (QT_VERSION >= 0x040500)
1079 if (isFullScreen() && menuBar()->isHidden()) {
1080 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
1081 // FIXME: we should also try to detect special LyX shortcut such as
1082 // Alt-P and Alt-M. Right now there is a hack in
1083 // GuiWorkArea::processKeySym() that hides again the menubar for
1085 if (ke->modifiers() & Qt::AltModifier && ke->key() != Qt::Key_Alt) {
1087 return QMainWindow::event(e);
1091 return QMainWindow::event(e);
1095 return QMainWindow::event(e);
1099 void GuiView::resetWindowTitleAndIconText()
1101 setWindowTitle(qt_("LyX"));
1102 setWindowIconText(qt_("LyX"));
1105 bool GuiView::focusNextPrevChild(bool /*next*/)
1112 bool GuiView::busy() const
1118 void GuiView::setBusy(bool busy)
1121 if (d.current_work_area_) {
1122 d.current_work_area_->setUpdatesEnabled(!busy);
1124 d.current_work_area_->stopBlinkingCursor();
1126 d.current_work_area_->startBlinkingCursor();
1130 QApplication::setOverrideCursor(Qt::WaitCursor);
1132 QApplication::restoreOverrideCursor();
1136 GuiWorkArea * GuiView::workArea(Buffer & buffer)
1138 if (currentWorkArea()
1139 && ¤tWorkArea()->bufferView().buffer() == &buffer)
1140 return (GuiWorkArea *) currentWorkArea();
1141 if (TabWorkArea * twa = d.currentTabWorkArea())
1142 return twa->workArea(buffer);
1147 GuiWorkArea * GuiView::addWorkArea(Buffer & buffer)
1149 // Automatically create a TabWorkArea if there are none yet.
1150 TabWorkArea * tab_widget = d.splitter_->count()
1151 ? d.currentTabWorkArea() : addTabWorkArea();
1152 return tab_widget->addWorkArea(buffer, *this);
1156 TabWorkArea * GuiView::addTabWorkArea()
1158 TabWorkArea * twa = new TabWorkArea;
1159 QObject::connect(twa, SIGNAL(currentWorkAreaChanged(GuiWorkArea *)),
1160 this, SLOT(on_currentWorkAreaChanged(GuiWorkArea *)));
1161 QObject::connect(twa, SIGNAL(lastWorkAreaRemoved()),
1162 this, SLOT(on_lastWorkAreaRemoved()));
1164 d.splitter_->addWidget(twa);
1165 d.stack_widget_->setCurrentWidget(d.splitter_);
1170 GuiWorkArea const * GuiView::currentWorkArea() const
1172 return d.current_work_area_;
1176 GuiWorkArea * GuiView::currentWorkArea()
1178 return d.current_work_area_;
1182 GuiWorkArea const * GuiView::currentMainWorkArea() const
1184 if (!d.currentTabWorkArea())
1186 return d.currentTabWorkArea()->currentWorkArea();
1190 GuiWorkArea * GuiView::currentMainWorkArea()
1192 if (!d.currentTabWorkArea())
1194 return d.currentTabWorkArea()->currentWorkArea();
1198 void GuiView::setCurrentWorkArea(GuiWorkArea * wa)
1200 LYXERR(Debug::DEBUG, "Setting current wa: " << wa << endl);
1202 d.current_work_area_ = 0;
1207 // FIXME: I've no clue why this is here and why it accesses
1208 // theGuiApp()->currentView, which might be 0 (bug 6464).
1209 // See also 27525 (vfr).
1210 if (theGuiApp()->currentView() == this
1211 && theGuiApp()->currentView()->currentWorkArea() == wa)
1214 if (currentBufferView())
1215 cap::saveSelection(currentBufferView()->cursor());
1217 theGuiApp()->setCurrentView(this);
1218 d.current_work_area_ = wa;
1219 for (int i = 0; i != d.splitter_->count(); ++i) {
1220 if (d.tabWorkArea(i)->setCurrentWorkArea(wa)) {
1221 //if (d.current_main_work_area_)
1222 // d.current_main_work_area_->setFrameStyle(QFrame::NoFrame);
1223 d.current_main_work_area_ = wa;
1224 //d.current_main_work_area_->setFrameStyle(QFrame::Box | QFrame::Plain);
1225 //d.current_main_work_area_->setLineWidth(2);
1226 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() << ", Current main wa: " << currentMainWorkArea());
1230 LYXERR(Debug::DEBUG, "This is not a tabbed wa");
1231 on_currentWorkAreaChanged(wa);
1232 BufferView & bv = wa->bufferView();
1233 bv.cursor().fixIfBroken();
1235 wa->setUpdatesEnabled(true);
1236 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() << ", Current main wa: " << currentMainWorkArea());
1240 void GuiView::removeWorkArea(GuiWorkArea * wa)
1242 LASSERT(wa, return);
1243 if (wa == d.current_work_area_) {
1245 disconnectBufferView();
1246 d.current_work_area_ = 0;
1247 d.current_main_work_area_ = 0;
1250 bool found_twa = false;
1251 for (int i = 0; i != d.splitter_->count(); ++i) {
1252 TabWorkArea * twa = d.tabWorkArea(i);
1253 if (twa->removeWorkArea(wa)) {
1254 // Found in this tab group, and deleted the GuiWorkArea.
1256 if (twa->count() != 0) {
1257 if (d.current_work_area_ == 0)
1258 // This means that we are closing the current GuiWorkArea, so
1259 // switch to the next GuiWorkArea in the found TabWorkArea.
1260 setCurrentWorkArea(twa->currentWorkArea());
1262 // No more WorkAreas in this tab group, so delete it.
1269 // It is not a tabbed work area (i.e., the search work area), so it
1270 // should be deleted by other means.
1271 LASSERT(found_twa, /* */);
1273 if (d.current_work_area_ == 0) {
1274 if (d.splitter_->count() != 0) {
1275 TabWorkArea * twa = d.currentTabWorkArea();
1276 setCurrentWorkArea(twa->currentWorkArea());
1278 // No more work areas, switch to the background widget.
1279 setCurrentWorkArea(0);
1285 LayoutBox * GuiView::getLayoutDialog() const
1291 void GuiView::updateLayoutList()
1294 d.layout_->updateContents(false);
1298 void GuiView::updateToolbars()
1300 ToolbarMap::iterator end = d.toolbars_.end();
1301 if (d.current_work_area_) {
1303 d.current_work_area_->bufferView().cursor().inMathed()
1304 && !d.current_work_area_->bufferView().cursor().inRegexped();
1306 lyx::getStatus(FuncRequest(LFUN_LAYOUT_TABULAR)).enabled();
1308 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).enabled() &&
1309 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).onOff(true);
1310 bool const mathmacrotemplate =
1311 lyx::getStatus(FuncRequest(LFUN_IN_MATHMACROTEMPLATE)).enabled();
1313 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1314 it->second->update(math, table, review, mathmacrotemplate);
1316 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1317 it->second->update(false, false, false, false);
1321 void GuiView::setBuffer(Buffer * newBuffer)
1323 LYXERR(Debug::DEBUG, "Setting buffer: " << newBuffer << endl);
1324 LASSERT(newBuffer, return);
1327 GuiWorkArea * wa = workArea(*newBuffer);
1329 newBuffer->masterBuffer()->updateBuffer();
1330 wa = addWorkArea(*newBuffer);
1332 //Disconnect the old buffer...there's no new one.
1335 connectBuffer(*newBuffer);
1336 connectBufferView(wa->bufferView());
1337 setCurrentWorkArea(wa);
1343 void GuiView::connectBuffer(Buffer & buf)
1345 buf.setGuiDelegate(this);
1349 void GuiView::disconnectBuffer()
1351 if (d.current_work_area_)
1352 d.current_work_area_->bufferView().buffer().setGuiDelegate(0);
1356 void GuiView::connectBufferView(BufferView & bv)
1358 bv.setGuiDelegate(this);
1362 void GuiView::disconnectBufferView()
1364 if (d.current_work_area_)
1365 d.current_work_area_->bufferView().setGuiDelegate(0);
1369 void GuiView::errors(string const & error_type, bool from_master)
1371 ErrorList & el = from_master ?
1372 currentBufferView()->buffer().masterBuffer()->errorList(error_type)
1373 : currentBufferView()->buffer().errorList(error_type);
1374 string data = error_type;
1376 data = "from_master|" + error_type;
1378 showDialog("errorlist", data);
1382 void GuiView::updateTocItem(string const & type, DocIterator const & dit)
1384 d.toc_models_.updateItem(toqstr(type), dit);
1388 void GuiView::structureChanged()
1390 d.toc_models_.reset(documentBufferView());
1391 // Navigator needs more than a simple update in this case. It needs to be
1393 updateDialog("toc", "");
1397 void GuiView::updateDialog(string const & name, string const & data)
1399 if (!isDialogVisible(name))
1402 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
1403 if (it == d.dialogs_.end())
1406 Dialog * const dialog = it->second.get();
1407 if (dialog->isVisibleView())
1408 dialog->initialiseParams(data);
1412 BufferView * GuiView::documentBufferView()
1414 return currentMainWorkArea()
1415 ? ¤tMainWorkArea()->bufferView()
1420 BufferView const * GuiView::documentBufferView() const
1422 return currentMainWorkArea()
1423 ? ¤tMainWorkArea()->bufferView()
1428 BufferView * GuiView::currentBufferView()
1430 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1434 BufferView const * GuiView::currentBufferView() const
1436 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1440 #if (QT_VERSION >= 0x040400)
1441 docstring GuiView::GuiViewPrivate::saveAndDestroy(Buffer const * orig, Buffer * buffer, FileName const & fname)
1444 FileName const tmp_ret = FileName::tempName("lyxauto");
1445 if (!tmp_ret.empty()) {
1446 if (buffer->writeFile(tmp_ret))
1447 failed = !tmp_ret.moveTo(fname);
1450 // failed to write/rename tmp_ret so try writing direct
1451 failed = buffer->writeFile(fname);
1454 busyBuffers.remove(orig);
1456 ? _("Automatic save failed!")
1457 : _("Automatic save done.");
1462 void GuiView::autoSave()
1464 LYXERR(Debug::INFO, "Running autoSave()");
1466 Buffer * buffer = documentBufferView()
1467 ? &documentBufferView()->buffer() : 0;
1471 #if (QT_VERSION >= 0x040400)
1472 GuiViewPrivate::busyBuffers.insert(buffer);
1473 QFuture<docstring> f = QtConcurrent::run(GuiViewPrivate::saveAndDestroy, buffer, buffer->clone(),
1474 buffer->getAutosaveFileName());
1475 d.autosave_watcher_.setFuture(f);
1482 void GuiView::resetAutosaveTimers()
1485 d.autosave_timeout_.restart();
1489 bool GuiView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1492 Buffer * buf = currentBufferView()
1493 ? ¤tBufferView()->buffer() : 0;
1494 Buffer * doc_buffer = documentBufferView()
1495 ? &(documentBufferView()->buffer()) : 0;
1497 // Check whether we need a buffer
1498 if (!lyxaction.funcHasFlag(cmd.action(), LyXAction::NoBuffer) && !buf) {
1499 // no, exit directly
1500 flag.message(from_utf8(N_("Command not allowed with"
1501 "out any document open")));
1502 flag.setEnabled(false);
1506 if (cmd.origin() == FuncRequest::TOC) {
1507 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
1508 if (!toc || !toc->getStatus(documentBufferView()->cursor(), cmd, flag))
1509 flag.setEnabled(false);
1513 switch(cmd.action()) {
1514 case LFUN_BUFFER_IMPORT:
1517 case LFUN_MASTER_BUFFER_UPDATE:
1518 case LFUN_MASTER_BUFFER_VIEW:
1519 enable = doc_buffer && doc_buffer->parent() != 0
1520 && !d.processing_thread_watcher_.isRunning();
1523 case LFUN_BUFFER_UPDATE:
1524 case LFUN_BUFFER_VIEW: {
1525 if (!doc_buffer || d.processing_thread_watcher_.isRunning()) {
1529 string format = to_utf8(cmd.argument());
1530 if (cmd.argument().empty())
1531 format = doc_buffer->getDefaultOutputFormat();
1532 enable = doc_buffer->isExportableFormat(format);
1536 case LFUN_BUFFER_RELOAD:
1537 enable = doc_buffer && !doc_buffer->isUnnamed()
1538 && doc_buffer->fileName().exists()
1539 && (!doc_buffer->isClean()
1540 || doc_buffer->isExternallyModified(Buffer::timestamp_method));
1543 case LFUN_BUFFER_CHILD_OPEN:
1544 enable = doc_buffer;
1547 case LFUN_BUFFER_WRITE:
1548 enable = doc_buffer && (doc_buffer->isUnnamed() || !doc_buffer->isClean());
1551 //FIXME: This LFUN should be moved to GuiApplication.
1552 case LFUN_BUFFER_WRITE_ALL: {
1553 // We enable the command only if there are some modified buffers
1554 Buffer * first = theBufferList().first();
1559 // We cannot use a for loop as the buffer list is a cycle.
1561 if (!b->isClean()) {
1565 b = theBufferList().next(b);
1566 } while (b != first);
1570 case LFUN_BUFFER_WRITE_AS:
1571 enable = doc_buffer;
1574 case LFUN_BUFFER_CLOSE:
1575 enable = doc_buffer;
1578 case LFUN_BUFFER_CLOSE_ALL:
1579 enable = theBufferList().last() != theBufferList().first();
1582 case LFUN_SPLIT_VIEW:
1583 if (cmd.getArg(0) == "vertical")
1584 enable = doc_buffer && (d.splitter_->count() == 1 ||
1585 d.splitter_->orientation() == Qt::Vertical);
1587 enable = doc_buffer && (d.splitter_->count() == 1 ||
1588 d.splitter_->orientation() == Qt::Horizontal);
1591 case LFUN_CLOSE_TAB_GROUP:
1592 enable = d.currentTabWorkArea();
1595 case LFUN_TOOLBAR_TOGGLE: {
1596 string const name = cmd.getArg(0);
1597 if (GuiToolbar * t = toolbar(name))
1598 flag.setOnOff(t->isVisible());
1601 docstring const msg =
1602 bformat(_("Unknown toolbar \"%1$s\""), from_utf8(name));
1608 case LFUN_DROP_LAYOUTS_CHOICE:
1612 case LFUN_UI_TOGGLE:
1613 flag.setOnOff(isFullScreen());
1616 case LFUN_DIALOG_DISCONNECT_INSET:
1619 case LFUN_DIALOG_HIDE:
1620 // FIXME: should we check if the dialog is shown?
1623 case LFUN_DIALOG_TOGGLE:
1624 flag.setOnOff(isDialogVisible(cmd.getArg(0)));
1625 // fall through to set "enable"
1626 case LFUN_DIALOG_SHOW: {
1627 string const name = cmd.getArg(0);
1629 enable = name == "aboutlyx"
1630 || name == "file" //FIXME: should be removed.
1632 || name == "texinfo"
1633 || name == "progress"
1634 || name == "compare";
1635 else if (name == "print")
1636 enable = doc_buffer->isExportable("dvi")
1637 && lyxrc.print_command != "none";
1638 else if (name == "character" || name == "symbols") {
1639 if (!buf || buf->isReadonly())
1642 // FIXME we should consider passthru
1644 Inset const & in = currentBufferView()->cursor().inset();
1645 enable = !in.getLayout().isPassThru();
1648 else if (name == "latexlog")
1649 enable = FileName(doc_buffer->logName()).isReadableFile();
1650 else if (name == "spellchecker")
1651 enable = theSpellChecker() && !doc_buffer->isReadonly();
1652 else if (name == "vclog")
1653 enable = doc_buffer->lyxvc().inUse();
1657 case LFUN_DIALOG_UPDATE: {
1658 string const name = cmd.getArg(0);
1660 enable = name == "prefs";
1664 case LFUN_COMMAND_EXECUTE:
1666 case LFUN_MENU_OPEN:
1667 // Nothing to check.
1670 case LFUN_COMPLETION_INLINE:
1671 if (!d.current_work_area_
1672 || !d.current_work_area_->completer().inlinePossible(
1673 currentBufferView()->cursor()))
1677 case LFUN_COMPLETION_POPUP:
1678 if (!d.current_work_area_
1679 || !d.current_work_area_->completer().popupPossible(
1680 currentBufferView()->cursor()))
1684 case LFUN_COMPLETION_COMPLETE:
1685 if (!d.current_work_area_
1686 || !d.current_work_area_->completer().inlinePossible(
1687 currentBufferView()->cursor()))
1691 case LFUN_COMPLETION_ACCEPT:
1692 if (!d.current_work_area_
1693 || (!d.current_work_area_->completer().popupVisible()
1694 && !d.current_work_area_->completer().inlineVisible()
1695 && !d.current_work_area_->completer().completionAvailable()))
1699 case LFUN_COMPLETION_CANCEL:
1700 if (!d.current_work_area_
1701 || (!d.current_work_area_->completer().popupVisible()
1702 && !d.current_work_area_->completer().inlineVisible()))
1706 case LFUN_BUFFER_ZOOM_OUT:
1707 enable = doc_buffer && lyxrc.zoom > 10;
1710 case LFUN_BUFFER_ZOOM_IN:
1711 enable = doc_buffer;
1714 case LFUN_BUFFER_NEXT:
1715 case LFUN_BUFFER_PREVIOUS:
1716 // FIXME: should we check is there is an previous or next buffer?
1718 case LFUN_BUFFER_SWITCH:
1719 // toggle on the current buffer, but do not toggle off
1720 // the other ones (is that a good idea?)
1722 && to_utf8(cmd.argument()) == doc_buffer->absFileName())
1723 flag.setOnOff(true);
1726 case LFUN_VC_REGISTER:
1727 enable = doc_buffer && !doc_buffer->lyxvc().inUse();
1729 case LFUN_VC_CHECK_IN:
1730 enable = doc_buffer && doc_buffer->lyxvc().checkInEnabled();
1732 case LFUN_VC_CHECK_OUT:
1733 enable = doc_buffer && doc_buffer->lyxvc().checkOutEnabled();
1735 case LFUN_VC_LOCKING_TOGGLE:
1736 enable = doc_buffer && !doc_buffer->isReadonly()
1737 && doc_buffer->lyxvc().lockingToggleEnabled();
1738 flag.setOnOff(enable && doc_buffer->lyxvc().locking());
1740 case LFUN_VC_REVERT:
1741 enable = doc_buffer && doc_buffer->lyxvc().inUse() && !doc_buffer->isReadonly();
1743 case LFUN_VC_UNDO_LAST:
1744 enable = doc_buffer && doc_buffer->lyxvc().undoLastEnabled();
1746 case LFUN_VC_REPO_UPDATE:
1747 enable = doc_buffer && doc_buffer->lyxvc().repoUpdateEnabled();
1749 case LFUN_VC_COMMAND: {
1750 if (cmd.argument().empty())
1752 if (!doc_buffer && contains(cmd.getArg(0), 'D'))
1756 case LFUN_VC_COMPARE:
1757 enable = doc_buffer && doc_buffer->lyxvc().prepareFileRevisionEnabled();
1760 case LFUN_SERVER_GOTO_FILE_ROW:
1762 case LFUN_FORWARD_SEARCH:
1763 enable = !(lyxrc.forward_search_dvi.empty() && lyxrc.forward_search_pdf.empty());
1771 flag.setEnabled(false);
1777 static FileName selectTemplateFile()
1779 FileDialog dlg(qt_("Select template file"));
1780 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1781 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
1783 FileDialog::Result result = dlg.open(toqstr(lyxrc.template_path),
1784 QStringList(qt_("LyX Documents (*.lyx)")));
1786 if (result.first == FileDialog::Later)
1788 if (result.second.isEmpty())
1790 return FileName(fromqstr(result.second));
1794 Buffer * GuiView::loadDocument(FileName const & filename, bool tolastfiles)
1798 Buffer * newBuffer = 0;
1800 newBuffer = checkAndLoadLyXFile(filename);
1801 } catch (ExceptionMessage const & e) {
1807 message(_("Document not loaded."));
1812 setBuffer(newBuffer);
1814 // scroll to the position when the file was last closed
1815 if (lyxrc.use_lastfilepos) {
1816 LastFilePosSection::FilePos filepos =
1817 theSession().lastFilePos().load(filename);
1818 documentBufferView()->moveToPosition(filepos.pit, filepos.pos, 0, 0);
1822 theSession().lastFiles().add(filename);
1829 void GuiView::openDocument(string const & fname)
1831 string initpath = lyxrc.document_path;
1833 if (documentBufferView()) {
1834 string const trypath = documentBufferView()->buffer().filePath();
1835 // If directory is writeable, use this as default.
1836 if (FileName(trypath).isDirWritable())
1842 if (fname.empty()) {
1843 FileDialog dlg(qt_("Select document to open"), LFUN_FILE_OPEN);
1844 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1845 dlg.setButton2(qt_("Examples|#E#e"),
1846 toqstr(addPath(package().system_support().absFileName(), "examples")));
1848 QStringList filter(qt_("LyX Documents (*.lyx)"));
1849 filter << qt_("LyX-1.3.x Documents (*.lyx13)")
1850 << qt_("LyX-1.4.x Documents (*.lyx14)")
1851 << qt_("LyX-1.5.x Documents (*.lyx15)")
1852 << qt_("LyX-1.6.x Documents (*.lyx16)");
1853 FileDialog::Result result =
1854 dlg.open(toqstr(initpath), filter);
1856 if (result.first == FileDialog::Later)
1859 filename = fromqstr(result.second);
1861 // check selected filename
1862 if (filename.empty()) {
1863 message(_("Canceled."));
1869 // get absolute path of file and add ".lyx" to the filename if
1871 FileName const fullname =
1872 fileSearch(string(), filename, "lyx", support::may_not_exist);
1873 if (!fullname.empty())
1874 filename = fullname.absFileName();
1876 if (!fullname.onlyPath().isDirectory()) {
1877 Alert::warning(_("Invalid filename"),
1878 bformat(_("The directory in the given path\n%1$s\ndoes not exist."),
1879 from_utf8(fullname.absFileName())));
1883 // if the file doesn't exist and isn't already open (bug 6645),
1884 // let the user create one
1885 if (!fullname.exists() && !theBufferList().exists(fullname)) {
1886 // the user specifically chose this name. Believe him.
1887 Buffer * const b = newFile(filename, string(), true);
1893 docstring const disp_fn = makeDisplayPath(filename);
1894 message(bformat(_("Opening document %1$s..."), disp_fn));
1897 Buffer * buf = loadDocument(fullname);
1899 // I don't think this is needed, since it will be done in setBuffer().
1900 // buf->updateBuffer();
1902 buf->errors("Parse");
1903 str2 = bformat(_("Document %1$s opened."), disp_fn);
1904 if (buf->lyxvc().inUse())
1905 str2 += " " + from_utf8(buf->lyxvc().versionString()) +
1906 " " + _("Version control detected.");
1908 str2 = bformat(_("Could not open document %1$s"), disp_fn);
1913 // FIXME: clean that
1914 static bool import(GuiView * lv, FileName const & filename,
1915 string const & format, ErrorList & errorList)
1917 FileName const lyxfile(support::changeExtension(filename.absFileName(), ".lyx"));
1919 string loader_format;
1920 vector<string> loaders = theConverters().loaders();
1921 if (find(loaders.begin(), loaders.end(), format) == loaders.end()) {
1922 for (vector<string>::const_iterator it = loaders.begin();
1923 it != loaders.end(); ++it) {
1924 if (!theConverters().isReachable(format, *it))
1927 string const tofile =
1928 support::changeExtension(filename.absFileName(),
1929 formats.extension(*it));
1930 if (!theConverters().convert(0, filename, FileName(tofile),
1931 filename, format, *it, errorList))
1933 loader_format = *it;
1936 if (loader_format.empty()) {
1937 frontend::Alert::error(_("Couldn't import file"),
1938 bformat(_("No information for importing the format %1$s."),
1939 formats.prettyName(format)));
1943 loader_format = format;
1945 if (loader_format == "lyx") {
1946 Buffer * buf = lv->loadDocument(lyxfile);
1949 // I don't think this is needed, since it will be done in setBuffer().
1950 // buf->updateBuffer();
1952 buf->errors("Parse");
1954 Buffer * const b = newFile(lyxfile.absFileName(), string(), true);
1958 bool as_paragraphs = loader_format == "textparagraph";
1959 string filename2 = (loader_format == format) ? filename.absFileName()
1960 : support::changeExtension(filename.absFileName(),
1961 formats.extension(loader_format));
1962 lv->currentBufferView()->insertPlaintextFile(FileName(filename2),
1964 guiApp->setCurrentView(lv);
1965 lyx::dispatch(FuncRequest(LFUN_MARK_OFF));
1972 void GuiView::importDocument(string const & argument)
1975 string filename = split(argument, format, ' ');
1977 LYXERR(Debug::INFO, format << " file: " << filename);
1979 // need user interaction
1980 if (filename.empty()) {
1981 string initpath = lyxrc.document_path;
1982 if (documentBufferView()) {
1983 string const trypath = documentBufferView()->buffer().filePath();
1984 // If directory is writeable, use this as default.
1985 if (FileName(trypath).isDirWritable())
1989 docstring const text = bformat(_("Select %1$s file to import"),
1990 formats.prettyName(format));
1992 FileDialog dlg(toqstr(text), LFUN_BUFFER_IMPORT);
1993 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1994 dlg.setButton2(qt_("Examples|#E#e"),
1995 toqstr(addPath(package().system_support().absFileName(), "examples")));
1997 docstring filter = formats.prettyName(format);
2000 filter += from_utf8(formats.extension(format));
2003 FileDialog::Result result =
2004 dlg.open(toqstr(initpath), fileFilters(toqstr(filter)));
2006 if (result.first == FileDialog::Later)
2009 filename = fromqstr(result.second);
2011 // check selected filename
2012 if (filename.empty())
2013 message(_("Canceled."));
2016 if (filename.empty())
2019 // get absolute path of file
2020 FileName const fullname(support::makeAbsPath(filename));
2022 FileName const lyxfile(support::changeExtension(fullname.absFileName(), ".lyx"));
2024 // Check if the document already is open
2025 Buffer * buf = theBufferList().getBuffer(lyxfile);
2028 if (!closeBuffer()) {
2029 message(_("Canceled."));
2034 docstring const displaypath = makeDisplayPath(lyxfile.absFileName(), 30);
2036 // if the file exists already, and we didn't do
2037 // -i lyx thefile.lyx, warn
2038 if (lyxfile.exists() && fullname != lyxfile) {
2040 docstring text = bformat(_("The document %1$s already exists.\n\n"
2041 "Do you want to overwrite that document?"), displaypath);
2042 int const ret = Alert::prompt(_("Overwrite document?"),
2043 text, 0, 1, _("&Overwrite"), _("&Cancel"));
2046 message(_("Canceled."));
2051 message(bformat(_("Importing %1$s..."), displaypath));
2052 ErrorList errorList;
2053 if (import(this, fullname, format, errorList))
2054 message(_("imported."));
2056 message(_("file not imported!"));
2058 // FIXME (Abdel 12/08/06): Is there a need to display the error list here?
2062 void GuiView::newDocument(string const & filename, bool from_template)
2064 FileName initpath(lyxrc.document_path);
2065 if (documentBufferView()) {
2066 FileName const trypath(documentBufferView()->buffer().filePath());
2067 // If directory is writeable, use this as default.
2068 if (trypath.isDirWritable())
2072 string templatefile;
2073 if (from_template) {
2074 templatefile = selectTemplateFile().absFileName();
2075 if (templatefile.empty())
2080 if (filename.empty())
2081 b = newUnnamedFile(initpath, to_utf8(_("newfile")), templatefile);
2083 b = newFile(filename, templatefile, true);
2088 // If no new document could be created, it is unsure
2089 // whether there is a valid BufferView.
2090 if (currentBufferView())
2091 // Ensure the cursor is correctly positioned on screen.
2092 currentBufferView()->showCursor();
2096 void GuiView::insertLyXFile(docstring const & fname)
2098 BufferView * bv = documentBufferView();
2103 FileName filename(to_utf8(fname));
2105 if (!filename.empty()) {
2106 bv->insertLyXFile(filename);
2110 // Launch a file browser
2112 string initpath = lyxrc.document_path;
2113 string const trypath = bv->buffer().filePath();
2114 // If directory is writeable, use this as default.
2115 if (FileName(trypath).isDirWritable())
2119 FileDialog dlg(qt_("Select LyX document to insert"), LFUN_FILE_INSERT);
2120 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2121 dlg.setButton2(qt_("Examples|#E#e"),
2122 toqstr(addPath(package().system_support().absFileName(),
2125 FileDialog::Result result = dlg.open(toqstr(initpath),
2126 QStringList(qt_("LyX Documents (*.lyx)")));
2128 if (result.first == FileDialog::Later)
2132 filename.set(fromqstr(result.second));
2134 // check selected filename
2135 if (filename.empty()) {
2136 // emit message signal.
2137 message(_("Canceled."));
2141 bv->insertLyXFile(filename);
2145 void GuiView::insertPlaintextFile(docstring const & fname,
2148 BufferView * bv = documentBufferView();
2152 if (!fname.empty() && !FileName::isAbsolute(to_utf8(fname))) {
2153 message(_("Absolute filename expected."));
2158 FileName filename(to_utf8(fname));
2160 if (!filename.empty()) {
2161 bv->insertPlaintextFile(filename, asParagraph);
2165 FileDialog dlg(qt_("Select file to insert"), (asParagraph ?
2166 LFUN_FILE_INSERT_PLAINTEXT_PARA : LFUN_FILE_INSERT_PLAINTEXT));
2168 FileDialog::Result result = dlg.open(toqstr(bv->buffer().filePath()),
2169 QStringList(qt_("All Files (*)")));
2171 if (result.first == FileDialog::Later)
2175 filename.set(fromqstr(result.second));
2177 // check selected filename
2178 if (filename.empty()) {
2179 // emit message signal.
2180 message(_("Canceled."));
2184 bv->insertPlaintextFile(filename, asParagraph);
2188 bool GuiView::renameBuffer(Buffer & b, docstring const & newname)
2190 FileName fname = b.fileName();
2191 FileName const oldname = fname;
2193 if (!newname.empty()) {
2195 fname = support::makeAbsPath(to_utf8(newname), oldname.onlyPath().absFileName());
2197 // Switch to this Buffer.
2200 // No argument? Ask user through dialog.
2202 FileDialog dlg(qt_("Choose a filename to save document as"),
2203 LFUN_BUFFER_WRITE_AS);
2204 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2205 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
2207 if (!isLyXFileName(fname.absFileName()))
2208 fname.changeExtension(".lyx");
2210 FileDialog::Result result =
2211 dlg.save(toqstr(fname.onlyPath().absFileName()),
2212 QStringList(qt_("LyX Documents (*.lyx)")),
2213 toqstr(fname.onlyFileName()));
2215 if (result.first == FileDialog::Later)
2218 fname.set(fromqstr(result.second));
2223 if (!isLyXFileName(fname.absFileName()))
2224 fname.changeExtension(".lyx");
2227 // fname is now the new Buffer location.
2228 if (FileName(fname).exists()) {
2229 docstring const file = makeDisplayPath(fname.absFileName(), 30);
2230 docstring text = bformat(_("The document %1$s already "
2231 "exists.\n\nDo you want to "
2232 "overwrite that document?"),
2234 int const ret = Alert::prompt(_("Overwrite document?"),
2235 text, 0, 2, _("&Overwrite"), _("&Rename"), _("&Cancel"));
2238 case 1: return renameBuffer(b, docstring());
2239 case 2: return false;
2243 FileName oldauto = b.getAutosaveFileName();
2245 // Ok, change the name of the buffer
2246 b.setFileName(fname.absFileName());
2248 bool unnamed = b.isUnnamed();
2249 b.setUnnamed(false);
2250 b.saveCheckSum(fname);
2252 // bring the autosave file with us, just in case.
2253 b.moveAutosaveFile(oldauto);
2255 if (!saveBuffer(b)) {
2256 oldauto = b.getAutosaveFileName();
2257 b.setFileName(oldname.absFileName());
2258 b.setUnnamed(unnamed);
2259 b.saveCheckSum(oldname);
2260 b.moveAutosaveFile(oldauto);
2264 // the file has now been saved to the new location.
2265 // we need to check that the locations of child buffers
2267 b.checkChildBuffers();
2273 bool GuiView::saveBuffer(Buffer & b)
2275 if (workArea(b) && workArea(b)->inDialogMode())
2279 return renameBuffer(b, docstring());
2282 theSession().lastFiles().add(b.fileName());
2283 // validate version control data and
2284 // correct buffer title
2285 b.lyxvc().file_found_hook(b.fileName());
2290 // Switch to this Buffer.
2293 // FIXME: we don't tell the user *WHY* the save failed !!
2294 docstring const file = makeDisplayPath(b.absFileName(), 30);
2295 docstring text = bformat(_("The document %1$s could not be saved.\n\n"
2296 "Do you want to rename the document and "
2297 "try again?"), file);
2298 int const ret = Alert::prompt(_("Rename and save?"),
2299 text, 0, 2, _("&Rename"), _("&Retry"), _("&Cancel"));
2302 if (!renameBuffer(b, docstring()))
2311 return saveBuffer(b);
2315 bool GuiView::hideWorkArea(GuiWorkArea * wa)
2317 return closeWorkArea(wa, false);
2321 bool GuiView::closeWorkArea(GuiWorkArea * wa)
2323 Buffer & buf = wa->bufferView().buffer();
2324 return closeWorkArea(wa, !buf.parent());
2328 bool GuiView::closeBuffer()
2330 GuiWorkArea * wa = currentMainWorkArea();
2331 setCurrentWorkArea(wa);
2332 Buffer & buf = wa->bufferView().buffer();
2333 return wa && closeWorkArea(wa, !buf.parent());
2337 void GuiView::writeSession() const {
2338 GuiWorkArea const * active_wa = currentMainWorkArea();
2339 for (int i = 0; i < d.splitter_->count(); ++i) {
2340 TabWorkArea * twa = d.tabWorkArea(i);
2341 for (int j = 0; j < twa->count(); ++j) {
2342 GuiWorkArea * wa = static_cast<GuiWorkArea *>(twa->widget(j));
2343 Buffer & buf = wa->bufferView().buffer();
2344 theSession().lastOpened().add(buf.fileName(), wa == active_wa);
2350 bool GuiView::closeBufferAll()
2352 // Close the workareas in all other views
2353 QList<int> const ids = guiApp->viewIds();
2354 for (int i = 0; i != ids.size(); ++i) {
2355 if (id_ != ids[i] && !guiApp->view(ids[i]).closeWorkAreaAll())
2359 // Close our own workareas
2360 if (!closeWorkAreaAll())
2363 // Now close the hidden buffers. We prevent hidden buffers from being
2364 // dirty, so we can just close them.
2365 theBufferList().closeAll();
2370 bool GuiView::closeWorkAreaAll()
2372 setCurrentWorkArea(currentMainWorkArea());
2374 // We might be in a situation that there is still a tabWorkArea, but
2375 // there are no tabs anymore. This can happen when we get here after a
2376 // TabWorkArea::lastWorkAreaRemoved() signal. Therefore we count how
2377 // many TabWorkArea's have no documents anymore.
2380 // We have to call count() each time, because it can happen that
2381 // more than one splitter will disappear in one iteration (bug 5998).
2382 for (; d.splitter_->count() > empty_twa; ) {
2383 TabWorkArea * twa = d.tabWorkArea(empty_twa);
2385 if (twa->count() == 0)
2388 setCurrentWorkArea(twa->currentWorkArea());
2389 if (!closeTabWorkArea(twa))
2397 bool GuiView::closeWorkArea(GuiWorkArea * wa, bool close_buffer)
2402 Buffer & buf = wa->bufferView().buffer();
2404 if (close_buffer && GuiViewPrivate::busyBuffers.contains(&buf)) {
2405 Alert::warning(_("Close document "), _("Document could not be closed because it is processed by LyX."));
2410 return closeBuffer(buf);
2412 if (!inMultiTabs(wa))
2413 if (!saveBufferIfNeeded(buf, true))
2421 bool GuiView::closeBuffer(Buffer & buf)
2423 // If we are in a close_event all children will be closed in some time,
2424 // so no need to do it here. This will ensure that the children end up
2425 // in the session file in the correct order. If we close the master
2426 // buffer, we can close or release the child buffers here too.
2428 ListOfBuffers clist = buf.getChildren();
2429 ListOfBuffers::const_iterator it = clist.begin();
2430 ListOfBuffers::const_iterator const bend = clist.end();
2431 for (; it != bend; ++it) {
2432 // If a child is dirty, do not close
2433 // without user intervention
2434 //FIXME: should we look in other tabworkareas?
2435 Buffer * child_buf = *it;
2436 GuiWorkArea * child_wa = workArea(*child_buf);
2438 if (!closeWorkArea(child_wa, true))
2441 theBufferList().releaseChild(&buf, child_buf);
2444 // goto bookmark to update bookmark pit.
2445 //FIXME: we should update only the bookmarks related to this buffer!
2446 LYXERR(Debug::DEBUG, "GuiView::closeBuffer()");
2447 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
2448 guiApp->gotoBookmark(i+1, false, false);
2450 if (saveBufferIfNeeded(buf, false)) {
2451 buf.removeAutosaveFile();
2452 theBufferList().release(&buf);
2459 bool GuiView::closeTabWorkArea(TabWorkArea * twa)
2461 while (twa == d.currentTabWorkArea()) {
2462 twa->setCurrentIndex(twa->count()-1);
2464 GuiWorkArea * wa = twa->currentWorkArea();
2465 Buffer & b = wa->bufferView().buffer();
2467 // We only want to close the buffer if the same buffer is not visible
2468 // in another view, and if this is not a child and if we are closing
2469 // a view (not a tabgroup).
2470 bool const close_buffer =
2471 !inMultiViews(wa) && !b.parent() && closing_;
2473 if (!closeWorkArea(wa, close_buffer))
2480 bool GuiView::saveBufferIfNeeded(Buffer & buf, bool hiding)
2482 if (buf.isClean() || buf.paragraphs().empty())
2485 // Switch to this Buffer.
2490 if (buf.isUnnamed())
2491 file = from_utf8(buf.fileName().onlyFileName());
2493 file = buf.fileName().displayName(30);
2495 // Bring this window to top before asking questions.
2500 if (hiding && buf.isUnnamed()) {
2501 docstring const text = bformat(_("The document %1$s has not been "
2502 "saved yet.\n\nDo you want to save "
2503 "the document?"), file);
2504 ret = Alert::prompt(_("Save new document?"),
2505 text, 0, 1, _("&Save"), _("&Cancel"));
2509 docstring const text = bformat(_("The document %1$s has unsaved changes."
2510 "\n\nDo you want to save the document or discard the changes?"), file);
2511 ret = Alert::prompt(_("Save changed document?"),
2512 text, 0, 2, _("&Save"), _("&Discard"), _("&Cancel"));
2517 if (!saveBuffer(buf))
2521 // if we crash after this we could
2522 // have no autosave file but I guess
2523 // this is really improbable (Jug)
2524 // Sometime improbable things happen, bug 6857 (ps)
2525 // buf.removeAutosaveFile();
2527 // revert all changes
2538 bool GuiView::inMultiTabs(GuiWorkArea * wa)
2540 Buffer & buf = wa->bufferView().buffer();
2542 for (int i = 0; i != d.splitter_->count(); ++i) {
2543 GuiWorkArea * wa_ = d.tabWorkArea(i)->workArea(buf);
2544 if (wa_ && wa_ != wa)
2547 return inMultiViews(wa);
2551 bool GuiView::inMultiViews(GuiWorkArea * wa)
2553 QList<int> const ids = guiApp->viewIds();
2554 Buffer & buf = wa->bufferView().buffer();
2557 for (int i = 0; i != ids.size() && found_twa <= 1; ++i) {
2561 if (guiApp->view(ids[i]).workArea(buf))
2568 void GuiView::gotoNextOrPreviousBuffer(NextOrPrevious np)
2570 Buffer * const curbuf = documentBufferView()
2571 ? &documentBufferView()->buffer() : 0;
2572 Buffer * nextbuf = curbuf;
2574 if (np == NEXTBUFFER)
2575 nextbuf = theBufferList().next(nextbuf);
2577 nextbuf = theBufferList().previous(nextbuf);
2578 if (nextbuf == curbuf)
2584 if (workArea(*nextbuf))
2591 /// make sure the document is saved
2592 static bool ensureBufferClean(Buffer * buffer)
2594 LASSERT(buffer, return false);
2595 if (buffer->isClean() && !buffer->isUnnamed())
2598 docstring const file = buffer->fileName().displayName(30);
2601 if (!buffer->isUnnamed()) {
2602 text = bformat(_("The document %1$s has unsaved "
2603 "changes.\n\nDo you want to save "
2604 "the document?"), file);
2605 title = _("Save changed document?");
2608 text = bformat(_("The document %1$s has not been "
2609 "saved yet.\n\nDo you want to save "
2610 "the document?"), file);
2611 title = _("Save new document?");
2613 int const ret = Alert::prompt(title, text, 0, 1, _("&Save"), _("&Cancel"));
2616 dispatch(FuncRequest(LFUN_BUFFER_WRITE));
2618 return buffer->isClean() && !buffer->isUnnamed();
2622 bool GuiView::reloadBuffer()
2624 Buffer * buffer = documentBufferView()
2625 ? &(documentBufferView()->buffer()) : 0;
2627 return buffer->reload();
2632 void GuiView::checkExternallyModifiedBuffers()
2634 BufferList::iterator bit = theBufferList().begin();
2635 BufferList::iterator const bend = theBufferList().end();
2636 for (; bit != bend; ++bit) {
2637 if ((*bit)->fileName().exists()
2638 && (*bit)->isExternallyModified(Buffer::checksum_method)) {
2639 docstring text = bformat(_("Document \n%1$s\n has been externally modified."
2640 " Reload now? Any local changes will be lost."),
2641 from_utf8((*bit)->absFileName()));
2642 int const ret = Alert::prompt(_("Reload externally changed document?"),
2643 text, 0, 1, _("&Reload"), _("&Cancel"));
2651 void GuiView::dispatchVC(FuncRequest const & cmd, DispatchResult & dr)
2653 Buffer * buffer = documentBufferView()
2654 ? &(documentBufferView()->buffer()) : 0;
2656 switch (cmd.action()) {
2657 case LFUN_VC_REGISTER:
2658 if (!buffer || !ensureBufferClean(buffer))
2660 if (!buffer->lyxvc().inUse()) {
2661 if (buffer->lyxvc().registrer()) {
2663 dr.suppressMessageUpdate();
2668 case LFUN_VC_CHECK_IN:
2669 if (!buffer || !ensureBufferClean(buffer))
2671 if (buffer->lyxvc().inUse() && !buffer->isReadonly()) {
2672 dr.setMessage(buffer->lyxvc().checkIn());
2673 if (!dr.message().empty())
2678 case LFUN_VC_CHECK_OUT:
2679 if (!buffer || !ensureBufferClean(buffer))
2681 if (buffer->lyxvc().inUse()) {
2682 dr.setMessage(buffer->lyxvc().checkOut());
2687 case LFUN_VC_LOCKING_TOGGLE:
2688 LASSERT(buffer, return);
2689 if (!ensureBufferClean(buffer) || buffer->isReadonly())
2691 if (buffer->lyxvc().inUse()) {
2692 string res = buffer->lyxvc().lockingToggle();
2694 frontend::Alert::error(_("Revision control error."),
2695 _("Error when setting the locking property."));
2703 case LFUN_VC_REVERT:
2704 LASSERT(buffer, return);
2705 buffer->lyxvc().revert();
2707 dr.suppressMessageUpdate();
2710 case LFUN_VC_UNDO_LAST:
2711 LASSERT(buffer, return);
2712 buffer->lyxvc().undoLast();
2714 dr.suppressMessageUpdate();
2717 case LFUN_VC_REPO_UPDATE:
2718 LASSERT(buffer, return);
2719 if (ensureBufferClean(buffer)) {
2720 dr.setMessage(buffer->lyxvc().repoUpdate());
2721 checkExternallyModifiedBuffers();
2725 case LFUN_VC_COMMAND: {
2726 string flag = cmd.getArg(0);
2727 if (buffer && contains(flag, 'R') && !ensureBufferClean(buffer))
2730 if (contains(flag, 'M')) {
2731 if (!Alert::askForText(message, _("LyX VC: Log Message")))
2734 string path = cmd.getArg(1);
2735 if (contains(path, "$$p") && buffer)
2736 path = subst(path, "$$p", buffer->filePath());
2737 LYXERR(Debug::LYXVC, "Directory: " << path);
2739 if (!pp.isReadableDirectory()) {
2740 lyxerr << _("Directory is not accessible.") << endl;
2743 support::PathChanger p(pp);
2745 string command = cmd.getArg(2);
2746 if (command.empty())
2749 command = subst(command, "$$i", buffer->absFileName());
2750 command = subst(command, "$$p", buffer->filePath());
2752 command = subst(command, "$$m", to_utf8(message));
2753 LYXERR(Debug::LYXVC, "Command: " << command);
2755 one.startscript(Systemcall::Wait, command);
2759 if (contains(flag, 'I'))
2760 buffer->markDirty();
2761 if (contains(flag, 'R'))
2767 case LFUN_VC_COMPARE: {
2769 if (cmd.argument().empty()) {
2770 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "comparehistory"));
2774 string rev1 = cmd.getArg(0);
2778 if (!buffer->lyxvc().prepareFileRevision(rev1, f1))
2781 if (isStrInt(rev1) && convert<int>(rev1) <= 0) {
2782 f2 = buffer->absFileName();
2784 string rev2 = cmd.getArg(1);
2788 if (!buffer->lyxvc().prepareFileRevision(rev2, f2))
2792 LYXERR(Debug::LYXVC, "Launching comparison for fetched revisions:\n" <<
2793 f1 << "\n" << f2 << "\n" );
2794 string par = "compare run " + quoteName(f1) + " " + quoteName(f2);
2795 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, par));
2805 void GuiView::openChildDocument(string const & fname)
2807 LASSERT(documentBufferView(), return);
2808 Buffer & buffer = documentBufferView()->buffer();
2809 FileName const filename = support::makeAbsPath(fname, buffer.filePath());
2810 documentBufferView()->saveBookmark(false);
2812 bool parsed = false;
2813 if (theBufferList().exists(filename)) {
2814 child = theBufferList().getBuffer(filename);
2816 message(bformat(_("Opening child document %1$s..."),
2817 makeDisplayPath(filename.absFileName())));
2818 child = loadDocument(filename, false);
2824 // Set the parent name of the child document.
2825 // This makes insertion of citations and references in the child work,
2826 // when the target is in the parent or another child document.
2827 child->setParent(&buffer);
2829 // I don't think this is needed, since it will be called in
2831 // child->masterBuffer()->updateBuffer();
2834 child->errors("Parse");
2838 bool GuiView::goToFileRow(string const & argument)
2842 size_t i = argument.find_last_of(' ');
2843 if (i != string::npos) {
2844 file_name = os::internal_path(trim(argument.substr(0, i)));
2845 istringstream is(argument.substr(i + 1));
2850 if (i == string::npos) {
2851 LYXERR0("Wrong argument: " << argument);
2855 string const abstmp = package().temp_dir().absFileName();
2856 string const realtmp = package().temp_dir().realPath();
2857 // We have to use os::path_prefix_is() here, instead of
2858 // simply prefixIs(), because the file name comes from
2859 // an external application and may need case adjustment.
2860 if (os::path_prefix_is(file_name, abstmp, os::CASE_ADJUSTED)
2861 || os::path_prefix_is(file_name, realtmp, os::CASE_ADJUSTED)) {
2862 // Needed by inverse dvi search. If it is a file
2863 // in tmpdir, call the apropriated function.
2864 // If tmpdir is a symlink, we may have the real
2865 // path passed back, so we correct for that.
2866 if (!prefixIs(file_name, abstmp))
2867 file_name = subst(file_name, realtmp, abstmp);
2868 buf = theBufferList().getBufferFromTmp(file_name);
2870 // Must replace extension of the file to be .lyx
2871 // and get full path
2872 FileName const s = fileSearch(string(),
2873 support::changeExtension(file_name, ".lyx"), "lyx");
2874 // Either change buffer or load the file
2875 if (theBufferList().exists(s))
2876 buf = theBufferList().getBuffer(s);
2877 else if (s.exists()) {
2878 buf = loadDocument(s);
2881 // I don't think this is needed. loadDocument() calls
2882 // setBuffer(), which calls updateBuffer().
2883 // buf->updateBuffer();
2884 buf->errors("Parse");
2887 _("File does not exist: %1$s"),
2888 makeDisplayPath(file_name)));
2893 documentBufferView()->setCursorFromRow(row);
2898 #if (QT_VERSION >= 0x040400)
2900 docstring GuiView::GuiViewPrivate::runAndDestroy(const T& func, Buffer const * orig, Buffer * buffer, string const & format, string const & msg)
2902 bool const update_unincluded =
2903 buffer->params().maintain_unincluded_children
2904 && !buffer->params().getIncludedChildren().empty();
2905 bool const success = func(format, update_unincluded);
2907 busyBuffers.remove(orig);
2909 ? bformat(_("Successful " + msg + " to format: %1$s"), from_utf8(format))
2910 : bformat(_("Error " + msg + " format: %1$s"), from_utf8(format));
2913 docstring GuiView::GuiViewPrivate::compileAndDestroy(Buffer const * orig, Buffer * buffer, string const & format)
2915 bool (Buffer::* mem_func)(std::string const &, bool, bool) const = &Buffer::doExport;
2916 return runAndDestroy(bind(mem_func, buffer, _1, true, _2), orig, buffer, format, "export");
2919 docstring GuiView::GuiViewPrivate::exportAndDestroy(Buffer const * orig, Buffer * buffer, string const & format)
2921 bool (Buffer::* mem_func)(std::string const &, bool, bool) const = &Buffer::doExport;
2922 return runAndDestroy(bind(mem_func, buffer, _1, false, _2), orig, buffer, format, "export");
2926 docstring GuiView::GuiViewPrivate::previewAndDestroy(Buffer const * orig, Buffer * buffer, string const & format)
2928 bool(Buffer::* mem_func)(std::string const &, bool) const = &Buffer::preview;
2929 return runAndDestroy(bind(mem_func, buffer, _1, _2), orig, buffer, format, "preview");
2934 bool GuiView::GuiViewPrivate::asyncBufferProcessing(
2935 string const & argument,
2936 Buffer const * used_buffer,
2937 docstring const & msg,
2938 docstring (*asyncFunc)(Buffer const *, Buffer *, string const &),
2939 bool (Buffer::*syncFunc)(string const &, bool, bool) const,
2940 bool (Buffer::*previewFunc)(string const &, bool) const)
2945 gv_->processingThreadStarted();
2946 string format = argument;
2947 if (format.empty()) {
2948 format = used_buffer->getDefaultOutputFormat();
2950 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
2952 progress_->clearMessages();
2955 GuiViewPrivate::busyBuffers.insert(used_buffer);
2956 QFuture<docstring> f = QtConcurrent::run(
2959 used_buffer->clone(),
2961 setPreviewFuture(f);
2962 last_export_format = used_buffer->bufferFormat();
2965 // We are asynchronous, so we don't know here anything about the success
2968 bool const update_unincluded =
2969 used_buffer->params().maintain_unincluded_children &&
2970 !used_buffer->params().getIncludedChildren().empty();
2972 return (used_buffer->*syncFunc)(format, true, update_unincluded);
2973 } else if (previewFunc) {
2974 return (used_buffer->*previewFunc)(format, update_unincluded);
2981 void GuiView::dispatch(FuncRequest const & cmd, DispatchResult & dr)
2983 BufferView * bv = currentBufferView();
2984 // By default we won't need any update.
2985 dr.screenUpdate(Update::None);
2986 // assume cmd will be dispatched
2987 dr.dispatched(true);
2989 Buffer * doc_buffer = documentBufferView()
2990 ? &(documentBufferView()->buffer()) : 0;
2992 if (cmd.origin() == FuncRequest::TOC) {
2993 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
2994 // FIXME: do we need to pass a DispatchResult object here?
2995 toc->doDispatch(bv->cursor(), cmd);
2999 string const argument = to_utf8(cmd.argument());
3001 switch(cmd.action()) {
3002 case LFUN_BUFFER_CHILD_OPEN:
3003 openChildDocument(to_utf8(cmd.argument()));
3006 case LFUN_BUFFER_IMPORT:
3007 importDocument(to_utf8(cmd.argument()));
3010 case LFUN_BUFFER_EXPORT: {
3013 // GCC only sees strfwd.h when building merged
3014 if (::lyx::operator==(cmd.argument(), "custom")) {
3015 dispatch(FuncRequest(LFUN_DIALOG_SHOW, "sendto"), dr);
3019 // TODO Remove if we could export asynchronous
3020 if (!doc_buffer->doExport(argument, false)) {
3022 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
3026 /* TODO/Review: Is it a problem to also export the children?
3027 See the update_unincluded flag */
3028 d.asyncBufferProcessing(argument,
3031 &GuiViewPrivate::exportAndDestroy,
3034 // TODO Inform user about success
3039 case LFUN_BUFFER_UPDATE: {
3040 d.asyncBufferProcessing(argument,
3043 &GuiViewPrivate::compileAndDestroy,
3048 case LFUN_BUFFER_VIEW: {
3049 d.asyncBufferProcessing(argument,
3051 _("Previewing ..."),
3052 &GuiViewPrivate::previewAndDestroy,
3057 case LFUN_MASTER_BUFFER_UPDATE: {
3058 d.asyncBufferProcessing(argument,
3059 (doc_buffer ? doc_buffer->masterBuffer() : 0),
3061 &GuiViewPrivate::compileAndDestroy,
3066 case LFUN_MASTER_BUFFER_VIEW: {
3067 d.asyncBufferProcessing(argument,
3068 (doc_buffer ? doc_buffer->masterBuffer() : 0),
3070 &GuiViewPrivate::previewAndDestroy,
3071 0, &Buffer::preview);
3074 case LFUN_BUFFER_SWITCH: {
3075 string const file_name = to_utf8(cmd.argument());
3076 if (!FileName::isAbsolute(file_name)) {
3078 dr.setMessage(_("Absolute filename expected."));
3082 Buffer * buffer = theBufferList().getBuffer(FileName(file_name));
3085 dr.setMessage(_("Document not loaded"));
3089 // Do we open or switch to the buffer in this view ?
3090 if (workArea(*buffer)
3091 || lyxrc.open_buffers_in_tabs || !documentBufferView()) {
3096 // Look for the buffer in other views
3097 QList<int> const ids = guiApp->viewIds();
3099 for (; i != ids.size(); ++i) {
3100 GuiView & gv = guiApp->view(ids[i]);
3101 if (gv.workArea(*buffer)) {
3102 gv.activateWindow();
3103 gv.setBuffer(buffer);
3108 // If necessary, open a new window as a last resort
3109 if (i == ids.size()) {
3110 lyx::dispatch(FuncRequest(LFUN_WINDOW_NEW));
3116 case LFUN_BUFFER_NEXT:
3117 gotoNextOrPreviousBuffer(NEXTBUFFER);
3120 case LFUN_BUFFER_PREVIOUS:
3121 gotoNextOrPreviousBuffer(PREVBUFFER);
3124 case LFUN_COMMAND_EXECUTE: {
3125 bool const show_it = cmd.argument() != "off";
3126 // FIXME: this is a hack, "minibuffer" should not be
3128 if (GuiToolbar * t = toolbar("minibuffer")) {
3129 t->setVisible(show_it);
3130 if (show_it && t->commandBuffer())
3131 t->commandBuffer()->setFocus();
3135 case LFUN_DROP_LAYOUTS_CHOICE:
3136 d.layout_->showPopup();
3139 case LFUN_MENU_OPEN:
3140 if (QMenu * menu = guiApp->menus().menu(toqstr(cmd.argument()), *this))
3141 menu->exec(QCursor::pos());
3144 case LFUN_FILE_INSERT:
3145 insertLyXFile(cmd.argument());
3148 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
3149 insertPlaintextFile(cmd.argument(), true);
3152 case LFUN_FILE_INSERT_PLAINTEXT:
3153 insertPlaintextFile(cmd.argument(), false);
3156 case LFUN_BUFFER_RELOAD: {
3157 LASSERT(doc_buffer, break);
3158 docstring const file = makeDisplayPath(doc_buffer->absFileName(), 20);
3159 docstring text = bformat(_("Any changes will be lost. Are you sure "
3160 "you want to revert to the saved version of the document %1$s?"), file);
3161 int const ret = Alert::prompt(_("Revert to saved document?"),
3162 text, 1, 1, _("&Revert"), _("&Cancel"));
3165 doc_buffer->markClean();
3167 dr.forceBufferUpdate();
3172 case LFUN_BUFFER_WRITE:
3173 LASSERT(doc_buffer, break);
3174 saveBuffer(*doc_buffer);
3177 case LFUN_BUFFER_WRITE_AS:
3178 LASSERT(doc_buffer, break);
3179 renameBuffer(*doc_buffer, cmd.argument());
3182 case LFUN_BUFFER_WRITE_ALL: {
3183 Buffer * first = theBufferList().first();
3186 message(_("Saving all documents..."));
3187 // We cannot use a for loop as the buffer list cycles.
3190 if (!b->isClean()) {
3192 LYXERR(Debug::ACTION, "Saved " << b->absFileName());
3194 b = theBufferList().next(b);
3195 } while (b != first);
3196 dr.setMessage(_("All documents saved."));
3200 case LFUN_BUFFER_CLOSE:
3204 case LFUN_BUFFER_CLOSE_ALL:
3208 case LFUN_TOOLBAR_TOGGLE: {
3209 string const name = cmd.getArg(0);
3210 if (GuiToolbar * t = toolbar(name))
3215 case LFUN_DIALOG_UPDATE: {
3216 string const name = to_utf8(cmd.argument());
3217 if (name == "prefs" || name == "document")
3218 updateDialog(name, string());
3219 else if (name == "paragraph")
3220 lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
3221 else if (currentBufferView()) {
3222 Inset * inset = currentBufferView()->editedInset(name);
3223 // Can only update a dialog connected to an existing inset
3225 // FIXME: get rid of this indirection; GuiView ask the inset
3226 // if he is kind enough to update itself...
3227 FuncRequest fr(LFUN_INSET_DIALOG_UPDATE, cmd.argument());
3228 //FIXME: pass DispatchResult here?
3229 inset->dispatch(currentBufferView()->cursor(), fr);
3235 case LFUN_DIALOG_TOGGLE: {
3236 if (isDialogVisible(cmd.getArg(0)))
3237 dispatch(FuncRequest(LFUN_DIALOG_HIDE, cmd.argument()), dr);
3239 dispatch(FuncRequest(LFUN_DIALOG_SHOW, cmd.argument()), dr);
3243 case LFUN_DIALOG_DISCONNECT_INSET:
3244 disconnectDialog(to_utf8(cmd.argument()));
3247 case LFUN_DIALOG_HIDE: {
3248 guiApp->hideDialogs(to_utf8(cmd.argument()), 0);
3252 case LFUN_DIALOG_SHOW: {
3253 string const name = cmd.getArg(0);
3254 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
3256 if (name == "character") {
3257 data = freefont2string();
3259 showDialog("character", data);
3260 } else if (name == "latexlog") {
3261 Buffer::LogType type;
3262 string const logfile = doc_buffer->logName(&type);
3264 case Buffer::latexlog:
3267 case Buffer::buildlog:
3271 data += Lexer::quoteString(logfile);
3272 showDialog("log", data);
3273 } else if (name == "vclog") {
3274 string const data = "vc " +
3275 Lexer::quoteString(doc_buffer->lyxvc().getLogFile());
3276 showDialog("log", data);
3277 } else if (name == "symbols") {
3278 data = bv->cursor().getEncoding()->name();
3280 showDialog("symbols", data);
3282 } else if (name == "prefs" && isFullScreen()) {
3283 lfunUiToggle("fullscreen");
3284 showDialog("prefs", data);
3286 showDialog(name, data);
3291 dr.setMessage(cmd.argument());
3294 case LFUN_UI_TOGGLE: {
3295 string arg = cmd.getArg(0);
3296 if (!lfunUiToggle(arg)) {
3297 docstring const msg = "ui-toggle " + _("%1$s unknown command!");
3298 dr.setMessage(bformat(msg, from_utf8(arg)));
3300 // Make sure the keyboard focus stays in the work area.
3305 case LFUN_SPLIT_VIEW: {
3306 LASSERT(doc_buffer, break);
3307 string const orientation = cmd.getArg(0);
3308 d.splitter_->setOrientation(orientation == "vertical"
3309 ? Qt::Vertical : Qt::Horizontal);
3310 TabWorkArea * twa = addTabWorkArea();
3311 GuiWorkArea * wa = twa->addWorkArea(*doc_buffer, *this);
3312 setCurrentWorkArea(wa);
3315 case LFUN_CLOSE_TAB_GROUP:
3316 if (TabWorkArea * twa = d.currentTabWorkArea()) {
3317 closeTabWorkArea(twa);
3318 d.current_work_area_ = 0;
3319 twa = d.currentTabWorkArea();
3320 // Switch to the next GuiWorkArea in the found TabWorkArea.
3322 // Make sure the work area is up to date.
3323 setCurrentWorkArea(twa->currentWorkArea());
3325 setCurrentWorkArea(0);
3330 case LFUN_COMPLETION_INLINE:
3331 if (d.current_work_area_)
3332 d.current_work_area_->completer().showInline();
3335 case LFUN_COMPLETION_POPUP:
3336 if (d.current_work_area_)
3337 d.current_work_area_->completer().showPopup();
3341 case LFUN_COMPLETION_COMPLETE:
3342 if (d.current_work_area_)
3343 d.current_work_area_->completer().tab();
3346 case LFUN_COMPLETION_CANCEL:
3347 if (d.current_work_area_) {
3348 if (d.current_work_area_->completer().popupVisible())
3349 d.current_work_area_->completer().hidePopup();
3351 d.current_work_area_->completer().hideInline();
3355 case LFUN_COMPLETION_ACCEPT:
3356 if (d.current_work_area_)
3357 d.current_work_area_->completer().activate();
3360 case LFUN_BUFFER_ZOOM_IN:
3361 case LFUN_BUFFER_ZOOM_OUT:
3362 if (cmd.argument().empty()) {
3363 if (cmd.action() == LFUN_BUFFER_ZOOM_IN)
3368 lyxrc.zoom += convert<int>(cmd.argument());
3370 if (lyxrc.zoom < 10)
3373 // The global QPixmapCache is used in GuiPainter to cache text
3374 // painting so we must reset it.
3375 QPixmapCache::clear();
3376 guiApp->fontLoader().update();
3377 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
3380 case LFUN_VC_REGISTER:
3381 case LFUN_VC_CHECK_IN:
3382 case LFUN_VC_CHECK_OUT:
3383 case LFUN_VC_REPO_UPDATE:
3384 case LFUN_VC_LOCKING_TOGGLE:
3385 case LFUN_VC_REVERT:
3386 case LFUN_VC_UNDO_LAST:
3387 case LFUN_VC_COMMAND:
3388 case LFUN_VC_COMPARE:
3389 dispatchVC(cmd, dr);
3392 case LFUN_SERVER_GOTO_FILE_ROW:
3393 goToFileRow(to_utf8(cmd.argument()));
3396 case LFUN_FORWARD_SEARCH: {
3397 FileName const path(doc_buffer->temppath());
3398 string const texname = doc_buffer->latexName();
3399 FileName const dviname(addName(path.absFileName(),
3400 support::changeExtension(texname, "dvi")));
3401 FileName const pdfname(addName(path.absFileName(),
3402 support::changeExtension(texname, "pdf")));
3403 if (!dviname.exists() && !pdfname.exists()) {
3404 dr.setMessage(_("Please, preview the document first."));
3407 string outname = dviname.onlyFileName();
3408 string command = lyxrc.forward_search_dvi;
3409 if (!dviname.exists() ||
3410 pdfname.lastModified() > dviname.lastModified()) {
3411 outname = pdfname.onlyFileName();
3412 command = lyxrc.forward_search_pdf;
3415 int row = doc_buffer->texrow().getRowFromIdPos(bv->cursor().paragraph().id(), bv->cursor().pos());
3416 LYXERR(Debug::ACTION, "Forward search: row:" << row
3417 << " id:" << bv->cursor().paragraph().id());
3418 if (!row || command.empty()) {
3419 dr.setMessage(_("Couldn't proceed."));
3422 string texrow = convert<string>(row);
3424 command = subst(command, "$$n", texrow);
3425 command = subst(command, "$$t", texname);
3426 command = subst(command, "$$o", outname);
3428 PathChanger p(path);
3430 one.startscript(Systemcall::DontWait, command);
3434 dr.dispatched(false);
3438 // Part of automatic menu appearance feature.
3439 if (isFullScreen()) {
3440 if (menuBar()->isVisible() && lyxrc.full_screen_menubar)
3442 if (statusBar()->isVisible())
3443 statusBar()->hide();
3450 bool GuiView::lfunUiToggle(string const & ui_component)
3452 if (ui_component == "scrollbar") {
3453 // hide() is of no help
3454 if (d.current_work_area_->verticalScrollBarPolicy() ==
3455 Qt::ScrollBarAlwaysOff)
3457 d.current_work_area_->setVerticalScrollBarPolicy(
3458 Qt::ScrollBarAsNeeded);
3460 d.current_work_area_->setVerticalScrollBarPolicy(
3461 Qt::ScrollBarAlwaysOff);
3462 } else if (ui_component == "statusbar") {
3463 statusBar()->setVisible(!statusBar()->isVisible());
3464 } else if (ui_component == "menubar") {
3465 menuBar()->setVisible(!menuBar()->isVisible());
3467 #if QT_VERSION >= 0x040300
3468 if (ui_component == "frame") {
3470 getContentsMargins(&l, &t, &r, &b);
3471 //are the frames in default state?
3472 d.current_work_area_->setFrameStyle(QFrame::NoFrame);
3474 setContentsMargins(-2, -2, -2, -2);
3476 setContentsMargins(0, 0, 0, 0);
3480 if (ui_component == "fullscreen") {
3488 void GuiView::toggleFullScreen()
3490 if (isFullScreen()) {
3491 for (int i = 0; i != d.splitter_->count(); ++i)
3492 d.tabWorkArea(i)->setFullScreen(false);
3493 #if QT_VERSION >= 0x040300
3494 setContentsMargins(0, 0, 0, 0);
3496 setWindowState(windowState() ^ Qt::WindowFullScreen);
3499 statusBar()->show();
3502 hideDialogs("prefs", 0);
3503 for (int i = 0; i != d.splitter_->count(); ++i)
3504 d.tabWorkArea(i)->setFullScreen(true);
3505 #if QT_VERSION >= 0x040300
3506 setContentsMargins(-2, -2, -2, -2);
3509 setWindowState(windowState() ^ Qt::WindowFullScreen);
3510 statusBar()->hide();
3511 if (lyxrc.full_screen_menubar)
3513 if (lyxrc.full_screen_toolbars) {
3514 ToolbarMap::iterator end = d.toolbars_.end();
3515 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
3520 // give dialogs like the TOC a chance to adapt
3525 Buffer const * GuiView::updateInset(Inset const * inset)
3530 Buffer const * inset_buffer = &(inset->buffer());
3532 for (int i = 0; i != d.splitter_->count(); ++i) {
3533 GuiWorkArea * wa = d.tabWorkArea(i)->currentWorkArea();
3536 Buffer const * buffer = &(wa->bufferView().buffer());
3537 if (inset_buffer == buffer)
3538 wa->scheduleRedraw();
3540 return inset_buffer;
3544 void GuiView::restartCursor()
3546 /* When we move around, or type, it's nice to be able to see
3547 * the cursor immediately after the keypress.
3549 if (d.current_work_area_)
3550 d.current_work_area_->startBlinkingCursor();
3552 // Take this occasion to update the other GUI elements.
3558 void GuiView::updateCompletion(Cursor & cur, bool start, bool keep)
3560 if (d.current_work_area_)
3561 d.current_work_area_->completer().updateVisibility(cur, start, keep);
3566 // This list should be kept in sync with the list of insets in
3567 // src/insets/Inset.cpp. I.e., if a dialog goes with an inset, the
3568 // dialog should have the same name as the inset.
3569 // Changes should be also recorded in LFUN_DIALOG_SHOW doxygen
3570 // docs in LyXAction.cpp.
3572 char const * const dialognames[] = {
3574 "aboutlyx", "bibitem", "bibtex", "box", "branch", "changes", "character",
3575 "citation", "compare", "comparehistory", "document", "errorlist", "ert",
3576 "external", "file", "findreplace", "findreplaceadv", "float", "graphics",
3577 "href", "include", "index", "index_print", "info", "listings", "label", "line",
3578 "log", "mathdelimiter", "mathmatrix", "mathspace", "nomenclature",
3579 "nomencl_print", "note", "paragraph", "phantom", "prefs", "print", "ref",
3580 "sendto", "space", "spellchecker", "symbols", "tabular", "tabularcreate",
3581 "thesaurus", "texinfo", "toc", "view-source", "vspace", "wrap", "progress"};
3583 char const * const * const end_dialognames =
3584 dialognames + (sizeof(dialognames) / sizeof(char *));
3588 cmpCStr(char const * name) : name_(name) {}
3589 bool operator()(char const * other) {
3590 return strcmp(other, name_) == 0;
3597 bool isValidName(string const & name)
3599 return find_if(dialognames, end_dialognames,
3600 cmpCStr(name.c_str())) != end_dialognames;
3606 void GuiView::resetDialogs()
3608 // Make sure that no LFUN uses any GuiView.
3609 guiApp->setCurrentView(0);
3612 constructToolbars();
3613 guiApp->menus().fillMenuBar(menuBar(), this, false);
3614 d.layout_->updateContents(true);
3615 // Now update controls with current buffer.
3616 guiApp->setCurrentView(this);
3622 Dialog * GuiView::findOrBuild(string const & name, bool hide_it)
3624 if (!isValidName(name))
3627 map<string, DialogPtr>::iterator it = d.dialogs_.find(name);
3629 if (it != d.dialogs_.end()) {
3631 it->second->hideView();
3632 return it->second.get();
3635 Dialog * dialog = build(name);
3636 d.dialogs_[name].reset(dialog);
3637 if (lyxrc.allow_geometry_session)
3638 dialog->restoreSession();
3645 void GuiView::showDialog(string const & name, string const & data,
3648 triggerShowDialog(toqstr(name), toqstr(data), inset);
3652 void GuiView::doShowDialog(QString const & qname, QString const & qdata,
3658 const string name = fromqstr(qname);
3659 const string data = fromqstr(qdata);
3663 Dialog * dialog = findOrBuild(name, false);
3665 bool const visible = dialog->isVisibleView();
3666 dialog->showData(data);
3667 if (inset && currentBufferView())
3668 currentBufferView()->editInset(name, inset);
3669 // We only set the focus to the new dialog if it was not yet
3670 // visible in order not to change the existing previous behaviour
3672 // activateWindow is needed for floating dockviews
3673 dialog->asQWidget()->raise();
3674 dialog->asQWidget()->activateWindow();
3675 dialog->asQWidget()->setFocus();
3679 catch (ExceptionMessage const & ex) {
3687 bool GuiView::isDialogVisible(string const & name) const
3689 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3690 if (it == d.dialogs_.end())
3692 return it->second.get()->isVisibleView() && !it->second.get()->isClosing();
3696 void GuiView::hideDialog(string const & name, Inset * inset)
3698 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3699 if (it == d.dialogs_.end())
3702 if (inset && currentBufferView()
3703 && inset != currentBufferView()->editedInset(name))
3706 Dialog * const dialog = it->second.get();
3707 if (dialog->isVisibleView())
3709 if (currentBufferView())
3710 currentBufferView()->editInset(name, 0);
3714 void GuiView::disconnectDialog(string const & name)
3716 if (!isValidName(name))
3718 if (currentBufferView())
3719 currentBufferView()->editInset(name, 0);
3723 void GuiView::hideAll() const
3725 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
3726 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3728 for(; it != end; ++it)
3729 it->second->hideView();
3733 void GuiView::updateDialogs()
3735 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
3736 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3738 for(; it != end; ++it) {
3739 Dialog * dialog = it->second.get();
3741 if (dialog->needBufferOpen() && !documentBufferView())
3742 hideDialog(fromqstr(dialog->name()), 0);
3743 else if (dialog->isVisibleView())
3744 dialog->checkStatus();
3751 Dialog * createDialog(GuiView & lv, string const & name);
3753 // will be replaced by a proper factory...
3754 Dialog * createGuiAbout(GuiView & lv);
3755 Dialog * createGuiBibtex(GuiView & lv);
3756 Dialog * createGuiChanges(GuiView & lv);
3757 Dialog * createGuiCharacter(GuiView & lv);
3758 Dialog * createGuiCitation(GuiView & lv);
3759 Dialog * createGuiCompare(GuiView & lv);
3760 Dialog * createGuiCompareHistory(GuiView & lv);
3761 Dialog * createGuiDelimiter(GuiView & lv);
3762 Dialog * createGuiDocument(GuiView & lv);
3763 Dialog * createGuiErrorList(GuiView & lv);
3764 Dialog * createGuiExternal(GuiView & lv);
3765 Dialog * createGuiGraphics(GuiView & lv);
3766 Dialog * createGuiInclude(GuiView & lv);
3767 Dialog * createGuiIndex(GuiView & lv);
3768 Dialog * createGuiLabel(GuiView & lv);
3769 Dialog * createGuiListings(GuiView & lv);
3770 Dialog * createGuiLog(GuiView & lv);
3771 Dialog * createGuiMathMatrix(GuiView & lv);
3772 Dialog * createGuiNomenclature(GuiView & lv);
3773 Dialog * createGuiNote(GuiView & lv);
3774 Dialog * createGuiParagraph(GuiView & lv);
3775 Dialog * createGuiPhantom(GuiView & lv);
3776 Dialog * createGuiPreferences(GuiView & lv);
3777 Dialog * createGuiPrint(GuiView & lv);
3778 Dialog * createGuiPrintindex(GuiView & lv);
3779 Dialog * createGuiPrintNomencl(GuiView & lv);
3780 Dialog * createGuiRef(GuiView & lv);
3781 Dialog * createGuiSearch(GuiView & lv);
3782 Dialog * createGuiSearchAdv(GuiView & lv);
3783 Dialog * createGuiSendTo(GuiView & lv);
3784 Dialog * createGuiShowFile(GuiView & lv);
3785 Dialog * createGuiSpellchecker(GuiView & lv);
3786 Dialog * createGuiSymbols(GuiView & lv);
3787 Dialog * createGuiTabularCreate(GuiView & lv);
3788 Dialog * createGuiTexInfo(GuiView & lv);
3789 Dialog * createGuiToc(GuiView & lv);
3790 Dialog * createGuiThesaurus(GuiView & lv);
3791 Dialog * createGuiHyperlink(GuiView & lv);
3792 Dialog * createGuiViewSource(GuiView & lv);
3793 Dialog * createGuiWrap(GuiView & lv);
3794 Dialog * createGuiProgressView(GuiView & lv);
3798 Dialog * GuiView::build(string const & name)
3800 LASSERT(isValidName(name), return 0);
3802 Dialog * dialog = createDialog(*this, name);
3806 if (name == "aboutlyx")
3807 return createGuiAbout(*this);
3808 if (name == "bibtex")
3809 return createGuiBibtex(*this);
3810 if (name == "changes")
3811 return createGuiChanges(*this);
3812 if (name == "character")
3813 return createGuiCharacter(*this);
3814 if (name == "citation")
3815 return createGuiCitation(*this);
3816 if (name == "compare")
3817 return createGuiCompare(*this);
3818 if (name == "comparehistory")
3819 return createGuiCompareHistory(*this);
3820 if (name == "document")
3821 return createGuiDocument(*this);
3822 if (name == "errorlist")
3823 return createGuiErrorList(*this);
3824 if (name == "external")
3825 return createGuiExternal(*this);
3827 return createGuiShowFile(*this);
3828 if (name == "findreplace")
3829 return createGuiSearch(*this);
3830 if (name == "findreplaceadv")
3831 return createGuiSearchAdv(*this);
3832 if (name == "graphics")
3833 return createGuiGraphics(*this);
3835 return createGuiHyperlink(*this);
3836 if (name == "include")
3837 return createGuiInclude(*this);
3838 if (name == "index")
3839 return createGuiIndex(*this);
3840 if (name == "index_print")
3841 return createGuiPrintindex(*this);
3842 if (name == "label")
3843 return createGuiLabel(*this);
3844 if (name == "listings")
3845 return createGuiListings(*this);
3847 return createGuiLog(*this);
3848 if (name == "mathdelimiter")
3849 return createGuiDelimiter(*this);
3850 if (name == "mathmatrix")
3851 return createGuiMathMatrix(*this);
3852 if (name == "nomenclature")
3853 return createGuiNomenclature(*this);
3854 if (name == "nomencl_print")
3855 return createGuiPrintNomencl(*this);
3857 return createGuiNote(*this);
3858 if (name == "paragraph")
3859 return createGuiParagraph(*this);
3860 if (name == "phantom")
3861 return createGuiPhantom(*this);
3862 if (name == "prefs")
3863 return createGuiPreferences(*this);
3864 if (name == "print")
3865 return createGuiPrint(*this);
3867 return createGuiRef(*this);
3868 if (name == "sendto")
3869 return createGuiSendTo(*this);
3870 if (name == "spellchecker")
3871 return createGuiSpellchecker(*this);
3872 if (name == "symbols")
3873 return createGuiSymbols(*this);
3874 if (name == "tabularcreate")
3875 return createGuiTabularCreate(*this);
3876 if (name == "texinfo")
3877 return createGuiTexInfo(*this);
3878 if (name == "thesaurus")
3879 return createGuiThesaurus(*this);
3881 return createGuiToc(*this);
3882 if (name == "view-source")
3883 return createGuiViewSource(*this);
3885 return createGuiWrap(*this);
3886 if (name == "progress")
3887 return createGuiProgressView(*this);
3893 } // namespace frontend
3896 #include "moc_GuiView.cpp"