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>
134 using namespace lyx::support;
141 class BackgroundWidget : public QWidget
146 LYXERR(Debug::GUI, "show banner: " << lyxrc.show_banner);
147 if (!lyxrc.show_banner)
149 /// The text to be written on top of the pixmap
150 QString const text = lyx_version ?
151 qt_("version ") + lyx_version : qt_("unknown version");
152 splash_ = getPixmap("images/", "banner", "png");
154 QPainter pain(&splash_);
155 pain.setPen(QColor(0, 0, 0));
157 // The font used to display the version info
158 font.setStyleHint(QFont::SansSerif);
159 font.setWeight(QFont::Bold);
160 font.setPointSize(int(toqstr(lyxrc.font_sizes[FONT_SIZE_LARGE]).toDouble()));
161 int width = QFontMetrics(font).width(text);
163 pain.drawText(397 - width, 15, text);
164 setFocusPolicy(Qt::StrongFocus);
167 void paintEvent(QPaintEvent *)
169 int x = (width() - splash_.width()) / 2;
170 int y = (height() - splash_.height()) / 2;
172 pain.drawPixmap(x, y, splash_);
175 void keyPressEvent(QKeyEvent * ev)
178 setKeySymbol(&sym, ev);
180 guiApp->processKeySym(sym, q_key_state(ev->modifiers()));
192 /// Toolbar store providing access to individual toolbars by name.
193 typedef map<string, GuiToolbar *> ToolbarMap;
195 typedef shared_ptr<Dialog> DialogPtr;
200 struct GuiView::GuiViewPrivate
202 GuiViewPrivate(GuiView * gv)
203 : gv_(gv), current_work_area_(0), current_main_work_area_(0),
204 layout_(0), autosave_timeout_(5000),
207 // hardcode here the platform specific icon size
208 smallIconSize = 14; // scaling problems
209 normalIconSize = 20; // ok, default
210 bigIconSize = 26; // better for some math icons
212 splitter_ = new QSplitter;
213 bg_widget_ = new BackgroundWidget;
214 stack_widget_ = new QStackedWidget;
215 stack_widget_->addWidget(bg_widget_);
216 stack_widget_->addWidget(splitter_);
219 // TODO cleanup, remove the singleton, handle multiple Windows?
220 progress_ = ProgressInterface::instance();
221 if (!dynamic_cast<GuiProgress*>(progress_)) {
222 progress_ = new GuiProgress(); // TODO who deletes it
223 ProgressInterface::setInstance(progress_);
226 dynamic_cast<GuiProgress*>(progress_),
227 SIGNAL(updateStatusBarMessage(QString const&)),
228 gv, SLOT(updateStatusBarMessage(QString const&)));
230 dynamic_cast<GuiProgress*>(progress_),
231 SIGNAL(clearMessageText()),
232 gv, SLOT(clearMessageText()));
239 delete stack_widget_;
242 QMenu * toolBarPopup(GuiView * parent)
244 // FIXME: translation
245 QMenu * menu = new QMenu(parent);
246 QActionGroup * iconSizeGroup = new QActionGroup(parent);
248 QAction * smallIcons = new QAction(iconSizeGroup);
249 smallIcons->setText(qt_("Small-sized icons"));
250 smallIcons->setCheckable(true);
251 QObject::connect(smallIcons, SIGNAL(triggered()),
252 parent, SLOT(smallSizedIcons()));
253 menu->addAction(smallIcons);
255 QAction * normalIcons = new QAction(iconSizeGroup);
256 normalIcons->setText(qt_("Normal-sized icons"));
257 normalIcons->setCheckable(true);
258 QObject::connect(normalIcons, SIGNAL(triggered()),
259 parent, SLOT(normalSizedIcons()));
260 menu->addAction(normalIcons);
262 QAction * bigIcons = new QAction(iconSizeGroup);
263 bigIcons->setText(qt_("Big-sized icons"));
264 bigIcons->setCheckable(true);
265 QObject::connect(bigIcons, SIGNAL(triggered()),
266 parent, SLOT(bigSizedIcons()));
267 menu->addAction(bigIcons);
269 unsigned int cur = parent->iconSize().width();
270 if ( cur == parent->d.smallIconSize)
271 smallIcons->setChecked(true);
272 else if (cur == parent->d.normalIconSize)
273 normalIcons->setChecked(true);
274 else if (cur == parent->d.bigIconSize)
275 bigIcons->setChecked(true);
282 stack_widget_->setCurrentWidget(bg_widget_);
283 bg_widget_->setUpdatesEnabled(true);
284 bg_widget_->setFocus();
287 int tabWorkAreaCount()
289 return splitter_->count();
292 TabWorkArea * tabWorkArea(int i)
294 return dynamic_cast<TabWorkArea *>(splitter_->widget(i));
297 TabWorkArea * currentTabWorkArea()
299 int areas = tabWorkAreaCount();
301 // The first TabWorkArea is always the first one, if any.
302 return tabWorkArea(0);
304 for (int i = 0; i != areas; ++i) {
305 TabWorkArea * twa = tabWorkArea(i);
306 if (current_main_work_area_ == twa->currentWorkArea())
310 // None has the focus so we just take the first one.
311 return tabWorkArea(0);
314 #if (QT_VERSION >= 0x040400)
315 void setPreviewFuture(QFuture<docstring> const & f)
317 if (processing_thread_watcher_.isRunning()) {
318 // we prefer to cancel this preview in order to keep a snappy
322 processing_thread_watcher_.setFuture(f);
328 GuiWorkArea * current_work_area_;
329 GuiWorkArea * current_main_work_area_;
330 QSplitter * splitter_;
331 QStackedWidget * stack_widget_;
332 BackgroundWidget * bg_widget_;
334 ToolbarMap toolbars_;
335 ProgressInterface* progress_;
336 /// The main layout box.
338 * \warning Don't Delete! The layout box is actually owned by
339 * whichever toolbar contains it. All the GuiView class needs is a
340 * means of accessing it.
342 * FIXME: replace that with a proper model so that we are not limited
343 * to only one dialog.
348 map<string, DialogPtr> dialogs_;
350 unsigned int smallIconSize;
351 unsigned int normalIconSize;
352 unsigned int bigIconSize;
354 QTimer statusbar_timer_;
355 /// auto-saving of buffers
356 Timeout autosave_timeout_;
357 /// flag against a race condition due to multiclicks, see bug #1119
361 TocModels toc_models_;
363 #if (QT_VERSION >= 0x040400)
365 QFutureWatcher<docstring> autosave_watcher_;
366 QFutureWatcher<docstring> processing_thread_watcher_;
368 string last_export_format;
370 struct DummyWatcher { bool isRunning(){return false;} };
371 DummyWatcher processing_thread_watcher_;
374 static QSet<Buffer const *> busyBuffers;
375 static docstring previewAndDestroy(Buffer const * orig, Buffer * buffer, string const & format);
376 static docstring exportAndDestroy(Buffer const * orig, Buffer * buffer, string const & format);
377 static docstring compileAndDestroy(Buffer const * orig, Buffer * buffer, string const & format);
378 static docstring autosaveAndDestroy(Buffer const * orig, Buffer * buffer);
381 static docstring runAndDestroy(const T& func, Buffer const * orig, Buffer * buffer, string const & format, string const & msg);
383 // TODO syncFunc/previewFunc: use bind
384 bool asyncBufferProcessing(string const & argument,
385 Buffer const * used_buffer,
386 docstring const & msg,
387 docstring (*asyncFunc)(Buffer const *, Buffer *, string const &),
388 bool (Buffer::*syncFunc)(string const &, bool, bool) const,
389 bool (Buffer::*previewFunc)(string const &, bool) const);
391 QTimer processing_cursor_timer_;
392 bool indicates_processing_;
393 QMap<GuiWorkArea*, Qt::CursorShape> orig_cursors_;
394 QVector<GuiWorkArea*> guiWorkAreas();
397 QSet<Buffer const *> GuiView::GuiViewPrivate::busyBuffers;
400 GuiView::GuiView(int id)
401 : d(*new GuiViewPrivate(this)), id_(id), closing_(false), busy_(0)
403 // GuiToolbars *must* be initialised before the menu bar.
404 normalSizedIcons(); // at least on Mac the default is 32 otherwise, which is huge
407 // set ourself as the current view. This is needed for the menu bar
408 // filling, at least for the static special menu item on Mac. Otherwise
409 // they are greyed out.
410 guiApp->setCurrentView(this);
412 // Fill up the menu bar.
413 guiApp->menus().fillMenuBar(menuBar(), this, true);
415 setCentralWidget(d.stack_widget_);
417 // Start autosave timer
418 if (lyxrc.autosave) {
419 d.autosave_timeout_.timeout.connect(bind(&GuiView::autoSave, this));
420 d.autosave_timeout_.setTimeout(lyxrc.autosave * 1000);
421 d.autosave_timeout_.start();
423 connect(&d.statusbar_timer_, SIGNAL(timeout()),
424 this, SLOT(clearMessage()));
426 // We don't want to keep the window in memory if it is closed.
427 setAttribute(Qt::WA_DeleteOnClose, true);
429 #if (!defined(Q_WS_WIN) && !defined(Q_WS_MACX))
430 // assign an icon to main form. We do not do it under Qt/Win or Qt/Mac,
431 // since the icon is provided in the application bundle.
432 setWindowIcon(getPixmap("images/", "lyx", "png"));
435 #if (QT_VERSION >= 0x040300)
436 // use tabbed dock area for multiple docks
437 // (such as "source" and "messages")
438 setDockOptions(QMainWindow::ForceTabbedDocks);
442 setAcceptDrops(true);
444 statusBar()->setSizeGripEnabled(true);
447 #if (QT_VERSION >= 0x040400)
448 connect(&d.autosave_watcher_, SIGNAL(finished()), this,
449 SLOT(processingThreadFinished()));
450 connect(&d.processing_thread_watcher_, SIGNAL(finished()), this,
451 SLOT(processingThreadFinished()));
453 d.processing_cursor_timer_.setInterval(1000 * 3);
454 connect(&d.processing_cursor_timer_, SIGNAL(timeout()), this,
455 SLOT(indicateProcessing()));
458 connect(this, SIGNAL(triggerShowDialog(QString const &, QString const &, Inset *)),
459 SLOT(doShowDialog(QString const &, QString const &, Inset *)));
461 // Forbid too small unresizable window because it can happen
462 // with some window manager under X11.
463 setMinimumSize(300, 200);
465 if (lyxrc.allow_geometry_session) {
466 // Now take care of session management.
471 // no session handling, default to a sane size.
472 setGeometry(50, 50, 690, 510);
475 // clear session data if any.
477 settings.remove("views");
487 QVector<GuiWorkArea*> GuiView::GuiViewPrivate::guiWorkAreas()
489 QVector<GuiWorkArea*> areas;
490 for (int i = 0; i < tabWorkAreaCount(); i++) {
491 TabWorkArea* ta = tabWorkArea(i);
492 for (int u = 0; u < ta->count(); u++) {
493 areas << ta->workArea(u);
500 #if QT_VERSION >= 0x040400
501 void GuiView::setCursorShapes(Qt::CursorShape shape)
503 QVector<GuiWorkArea*> areas = d.guiWorkAreas();
504 Q_FOREACH(GuiWorkArea* wa, areas) {
505 wa->setCursorShape(shape);
510 void GuiView::restoreCursorShapes()
512 QVector<GuiWorkArea*> areas = d.guiWorkAreas();
513 Q_FOREACH(GuiWorkArea* wa, areas) {
514 if (d.orig_cursors_.contains(wa)) {
515 wa->setCursorShape(d.orig_cursors_[wa]);
521 void GuiView::saveCursorShapes()
523 d.orig_cursors_.clear();
524 QVector<GuiWorkArea*> areas = d.guiWorkAreas();
525 Q_FOREACH(GuiWorkArea* wa, areas) {
526 d.orig_cursors_[wa] = wa->cursorShape();
531 void GuiView::indicateProcessing()
533 if (d.indicates_processing_) {
534 restoreCursorShapes();
536 setCursorShapes(Qt::BusyCursor);
538 d.indicates_processing_ = !d.indicates_processing_;
542 void GuiView::processingThreadStarted()
545 d.indicates_processing_ = false;
546 indicateProcessing();
547 d.processing_cursor_timer_.start();
551 void GuiView::processingThreadFinished()
553 QFutureWatcher<docstring> const * watcher =
554 static_cast<QFutureWatcher<docstring> const *>(sender());
555 message(watcher->result());
557 errors(d.last_export_format);
558 d.processing_cursor_timer_.stop();
559 restoreCursorShapes();
560 d.indicates_processing_ = false;
565 void GuiView::setCursorShapes(Qt::CursorShape)
570 void GuiView::restoreCursorShapes()
575 void GuiView::saveCursorShapes()
580 void GuiView::indicateProcessing()
585 void GuiView::processingThreadStarted()
590 void GuiView::processingThreadFinished()
596 void GuiView::saveLayout() const
599 settings.beginGroup("views");
600 settings.beginGroup(QString::number(id_));
602 settings.setValue("pos", pos());
603 settings.setValue("size", size());
605 settings.setValue("geometry", saveGeometry());
607 settings.setValue("layout", saveState(0));
608 settings.setValue("icon_size", iconSize());
612 bool GuiView::restoreLayout()
615 settings.beginGroup("views");
616 settings.beginGroup(QString::number(id_));
617 QString const icon_key = "icon_size";
618 if (!settings.contains(icon_key))
621 //code below is skipped when when ~/.config/LyX is (re)created
622 setIconSize(settings.value(icon_key).toSize());
624 QPoint pos = settings.value("pos", QPoint(50, 50)).toPoint();
625 QSize size = settings.value("size", QSize(690, 510)).toSize();
629 // Work-around for bug #6034: the window ends up in an undetermined
630 // state when trying to restore a maximized window when it is
631 // already maximized.
632 if (!(windowState() & Qt::WindowMaximized))
633 if (!restoreGeometry(settings.value("geometry").toByteArray()))
634 setGeometry(50, 50, 690, 510);
636 // Make sure layout is correctly oriented.
637 setLayoutDirection(qApp->layoutDirection());
639 // Allow the toc and view-source dock widget to be restored if needed.
641 if ((dialog = findOrBuild("toc", true)))
642 // see bug 5082. At least setup title and enabled state.
643 // Visibility will be adjusted by restoreState below.
644 dialog->prepareView();
645 if ((dialog = findOrBuild("view-source", true)))
646 dialog->prepareView();
647 if ((dialog = findOrBuild("progress", true)))
648 dialog->prepareView();
650 if (!restoreState(settings.value("layout").toByteArray(), 0))
657 GuiToolbar * GuiView::toolbar(string const & name)
659 ToolbarMap::iterator it = d.toolbars_.find(name);
660 if (it != d.toolbars_.end())
663 LYXERR(Debug::GUI, "Toolbar::display: no toolbar named " << name);
668 void GuiView::constructToolbars()
670 ToolbarMap::iterator it = d.toolbars_.begin();
671 for (; it != d.toolbars_.end(); ++it)
675 // I don't like doing this here, but the standard toolbar
676 // destroys this object when it's destroyed itself (vfr)
677 d.layout_ = new LayoutBox(*this);
678 d.stack_widget_->addWidget(d.layout_);
679 d.layout_->move(0,0);
681 // extracts the toolbars from the backend
682 Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
683 Toolbars::Infos::iterator end = guiApp->toolbars().end();
684 for (; cit != end; ++cit)
685 d.toolbars_[cit->name] = new GuiToolbar(*cit, *this);
689 void GuiView::initToolbars()
691 // extracts the toolbars from the backend
692 Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
693 Toolbars::Infos::iterator end = guiApp->toolbars().end();
694 for (; cit != end; ++cit) {
695 GuiToolbar * tb = toolbar(cit->name);
698 int const visibility = guiApp->toolbars().defaultVisibility(cit->name);
699 bool newline = !(visibility & Toolbars::SAMEROW);
700 tb->setVisible(false);
701 tb->setVisibility(visibility);
703 if (visibility & Toolbars::TOP) {
705 addToolBarBreak(Qt::TopToolBarArea);
706 addToolBar(Qt::TopToolBarArea, tb);
709 if (visibility & Toolbars::BOTTOM) {
710 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
711 #if (QT_VERSION >= 0x040202)
713 addToolBarBreak(Qt::BottomToolBarArea);
715 addToolBar(Qt::BottomToolBarArea, tb);
718 if (visibility & Toolbars::LEFT) {
719 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
720 #if (QT_VERSION >= 0x040202)
722 addToolBarBreak(Qt::LeftToolBarArea);
724 addToolBar(Qt::LeftToolBarArea, tb);
727 if (visibility & Toolbars::RIGHT) {
728 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
729 #if (QT_VERSION >= 0x040202)
731 addToolBarBreak(Qt::RightToolBarArea);
733 addToolBar(Qt::RightToolBarArea, tb);
736 if (visibility & Toolbars::ON)
737 tb->setVisible(true);
742 TocModels & GuiView::tocModels()
744 return d.toc_models_;
748 void GuiView::setFocus()
750 LYXERR(Debug::DEBUG, "GuiView::setFocus()" << this);
751 QMainWindow::setFocus();
755 void GuiView::focusInEvent(QFocusEvent * e)
757 LYXERR(Debug::DEBUG, "GuiView::focusInEvent()" << this);
758 QMainWindow::focusInEvent(e);
759 // Make sure guiApp points to the correct view.
760 guiApp->setCurrentView(this);
761 if (currentMainWorkArea())
762 currentMainWorkArea()->setFocus();
763 else if (currentWorkArea())
764 currentWorkArea()->setFocus();
766 d.bg_widget_->setFocus();
770 QMenu * GuiView::createPopupMenu()
772 return d.toolBarPopup(this);
776 void GuiView::showEvent(QShowEvent * e)
778 LYXERR(Debug::GUI, "Passed Geometry "
779 << size().height() << "x" << size().width()
780 << "+" << pos().x() << "+" << pos().y());
782 if (d.splitter_->count() == 0)
783 // No work area, switch to the background widget.
786 QMainWindow::showEvent(e);
790 bool GuiView::closeScheduled()
797 /** Destroy only all tabbed WorkAreas. Destruction of other WorkAreas
798 ** is responsibility of the container (e.g., dialog)
800 void GuiView::closeEvent(QCloseEvent * close_event)
802 LYXERR(Debug::DEBUG, "GuiView::closeEvent()");
804 if (!GuiViewPrivate::busyBuffers.isEmpty()) {
805 Alert::warning(_("Exit LyX"), _("LyX could not be closed because documents are processed by LyX."));
806 close_event->setAccepted(false);
810 // If the user pressed the x (so we didn't call closeView
811 // programmatically), we want to clear all existing entries.
813 theSession().lastOpened().clear();
818 // it can happen that this event arrives without selecting the view,
819 // e.g. when clicking the close button on a background window.
821 if (!closeWorkAreaAll()) {
823 close_event->ignore();
827 // Make sure that nothing will use this to be closed View.
828 guiApp->unregisterView(this);
830 if (isFullScreen()) {
831 // Switch off fullscreen before closing.
836 // Make sure the timer time out will not trigger a statusbar update.
837 d.statusbar_timer_.stop();
839 // Saving fullscreen requires additional tweaks in the toolbar code.
840 // It wouldn't also work under linux natively.
841 if (lyxrc.allow_geometry_session) {
842 // Save this window geometry and layout.
844 // Then the toolbar private states.
845 ToolbarMap::iterator end = d.toolbars_.end();
846 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
847 it->second->saveSession();
848 // Now take care of all other dialogs:
849 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
850 for (; it!= d.dialogs_.end(); ++it)
851 it->second->saveSession();
854 close_event->accept();
858 void GuiView::dragEnterEvent(QDragEnterEvent * event)
860 if (event->mimeData()->hasUrls())
862 /// \todo Ask lyx-devel is this is enough:
863 /// if (event->mimeData()->hasFormat("text/plain"))
864 /// event->acceptProposedAction();
868 void GuiView::dropEvent(QDropEvent * event)
870 QList<QUrl> files = event->mimeData()->urls();
874 LYXERR(Debug::GUI, "GuiView::dropEvent: got URLs!");
875 for (int i = 0; i != files.size(); ++i) {
876 string const file = os::internal_path(fromqstr(
877 files.at(i).toLocalFile()));
881 string const ext = support::getExtension(file);
882 vector<const Format *> found_formats;
884 // Find all formats that have the correct extension.
885 vector<const Format *> const & import_formats
886 = theConverters().importableFormats();
887 vector<const Format *>::const_iterator it = import_formats.begin();
888 for (; it != import_formats.end(); ++it)
889 if ((*it)->extension() == ext)
890 found_formats.push_back(*it);
893 if (found_formats.size() >= 1) {
894 if (found_formats.size() > 1) {
895 //FIXME: show a dialog to choose the correct importable format
897 "Multiple importable formats found, selecting first");
899 string const arg = found_formats[0]->name() + " " + file;
900 cmd = FuncRequest(LFUN_BUFFER_IMPORT, arg);
903 //FIXME: do we have to explicitly check whether it's a lyx file?
905 "No formats found, trying to open it as a lyx file");
906 cmd = FuncRequest(LFUN_FILE_OPEN, file);
908 // add the functions to the queue
909 guiApp->addToFuncRequestQueue(cmd);
912 // now process the collected functions. We perform the events
913 // asynchronously. This prevents potential problems in case the
914 // BufferView is closed within an event.
915 guiApp->processFuncRequestQueueAsync();
919 void GuiView::message(docstring const & str)
921 if (ForkedProcess::iAmAChild())
924 // call is moved to GUI-thread by GuiProgress
925 d.progress_->appendMessage(toqstr(str));
929 void GuiView::clearMessageText()
931 message(docstring());
935 void GuiView::updateStatusBarMessage(QString const & str)
937 statusBar()->showMessage(str);
938 d.statusbar_timer_.stop();
939 d.statusbar_timer_.start(3000);
943 void GuiView::smallSizedIcons()
945 setIconSize(QSize(d.smallIconSize, d.smallIconSize));
949 void GuiView::normalSizedIcons()
951 setIconSize(QSize(d.normalIconSize, d.normalIconSize));
955 void GuiView::bigSizedIcons()
957 setIconSize(QSize(d.bigIconSize, d.bigIconSize));
961 void GuiView::clearMessage()
963 // FIXME: This code was introduced in r19643 to fix bug #4123. However,
964 // the hasFocus function mostly returns false, even if the focus is on
965 // a workarea in this view.
969 d.statusbar_timer_.stop();
973 void GuiView::updateWindowTitle(GuiWorkArea * wa)
975 if (wa != d.current_work_area_
976 || wa->bufferView().buffer().isInternal())
978 setWindowTitle(qt_("LyX: ") + wa->windowTitle());
979 setWindowIconText(wa->windowIconText());
983 void GuiView::on_currentWorkAreaChanged(GuiWorkArea * wa)
986 disconnectBufferView();
987 connectBufferView(wa->bufferView());
988 connectBuffer(wa->bufferView().buffer());
989 d.current_work_area_ = wa;
990 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
991 this, SLOT(updateWindowTitle(GuiWorkArea *)));
992 updateWindowTitle(wa);
996 // The document settings needs to be reinitialised.
997 updateDialog("document", "");
999 // Buffer-dependent dialogs must be updated. This is done here because
1000 // some dialogs require buffer()->text.
1005 void GuiView::on_lastWorkAreaRemoved()
1008 // We already are in a close event. Nothing more to do.
1011 if (d.splitter_->count() > 1)
1012 // We have a splitter so don't close anything.
1015 // Reset and updates the dialogs.
1016 d.toc_models_.reset(0);
1017 updateDialog("document", "");
1020 resetWindowTitleAndIconText();
1023 if (lyxrc.open_buffers_in_tabs)
1024 // Nothing more to do, the window should stay open.
1027 if (guiApp->viewIds().size() > 1) {
1033 // On Mac we also close the last window because the application stay
1034 // resident in memory. On other platforms we don't close the last
1035 // window because this would quit the application.
1041 void GuiView::updateStatusBar()
1043 // let the user see the explicit message
1044 if (d.statusbar_timer_.isActive())
1051 void GuiView::showMessage()
1053 QString msg = toqstr(theGuiApp()->viewStatusMessage());
1054 if (msg.isEmpty()) {
1055 BufferView const * bv = currentBufferView();
1057 msg = toqstr(bv->cursor().currentState());
1059 msg = qt_("Welcome to LyX!");
1061 statusBar()->showMessage(msg);
1065 bool GuiView::event(QEvent * e)
1069 // Useful debug code:
1070 //case QEvent::ActivationChange:
1071 //case QEvent::WindowDeactivate:
1072 //case QEvent::Paint:
1073 //case QEvent::Enter:
1074 //case QEvent::Leave:
1075 //case QEvent::HoverEnter:
1076 //case QEvent::HoverLeave:
1077 //case QEvent::HoverMove:
1078 //case QEvent::StatusTip:
1079 //case QEvent::DragEnter:
1080 //case QEvent::DragLeave:
1081 //case QEvent::Drop:
1084 case QEvent::WindowActivate: {
1085 GuiView * old_view = guiApp->currentView();
1086 if (this == old_view) {
1088 return QMainWindow::event(e);
1090 if (old_view && old_view->currentBufferView()) {
1091 // save current selection to the selection buffer to allow
1092 // middle-button paste in this window.
1093 cap::saveSelection(old_view->currentBufferView()->cursor());
1095 guiApp->setCurrentView(this);
1096 if (d.current_work_area_) {
1097 BufferView & bv = d.current_work_area_->bufferView();
1098 connectBufferView(bv);
1099 connectBuffer(bv.buffer());
1100 // The document structure, name and dialogs might have
1101 // changed in another view.
1103 // The document settings needs to be reinitialised.
1104 updateDialog("document", "");
1107 resetWindowTitleAndIconText();
1110 return QMainWindow::event(e);
1113 case QEvent::ShortcutOverride: {
1116 #if (!defined Q_WS_X11) || (QT_VERSION >= 0x040500)
1117 if (isFullScreen() && menuBar()->isHidden()) {
1118 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
1119 // FIXME: we should also try to detect special LyX shortcut such as
1120 // Alt-P and Alt-M. Right now there is a hack in
1121 // GuiWorkArea::processKeySym() that hides again the menubar for
1123 if (ke->modifiers() & Qt::AltModifier && ke->key() != Qt::Key_Alt) {
1125 return QMainWindow::event(e);
1129 return QMainWindow::event(e);
1133 return QMainWindow::event(e);
1137 void GuiView::resetWindowTitleAndIconText()
1139 setWindowTitle(qt_("LyX"));
1140 setWindowIconText(qt_("LyX"));
1143 bool GuiView::focusNextPrevChild(bool /*next*/)
1150 bool GuiView::busy() const
1156 void GuiView::setBusy(bool busy)
1158 bool const busy_before = busy_ > 0;
1159 busy ? ++busy_ : --busy_;
1160 if ((busy_ > 0) == busy_before)
1161 // busy state didn't change
1164 if (d.current_work_area_) {
1165 d.current_work_area_->setUpdatesEnabled(!busy);
1167 d.current_work_area_->stopBlinkingCursor();
1169 d.current_work_area_->startBlinkingCursor();
1173 QApplication::setOverrideCursor(Qt::WaitCursor);
1175 QApplication::restoreOverrideCursor();
1179 GuiWorkArea * GuiView::workArea(Buffer & buffer)
1181 if (currentWorkArea()
1182 && ¤tWorkArea()->bufferView().buffer() == &buffer)
1183 return (GuiWorkArea *) currentWorkArea();
1184 if (TabWorkArea * twa = d.currentTabWorkArea())
1185 return twa->workArea(buffer);
1190 GuiWorkArea * GuiView::addWorkArea(Buffer & buffer)
1192 // Automatically create a TabWorkArea if there are none yet.
1193 TabWorkArea * tab_widget = d.splitter_->count()
1194 ? d.currentTabWorkArea() : addTabWorkArea();
1195 return tab_widget->addWorkArea(buffer, *this);
1199 TabWorkArea * GuiView::addTabWorkArea()
1201 TabWorkArea * twa = new TabWorkArea;
1202 QObject::connect(twa, SIGNAL(currentWorkAreaChanged(GuiWorkArea *)),
1203 this, SLOT(on_currentWorkAreaChanged(GuiWorkArea *)));
1204 QObject::connect(twa, SIGNAL(lastWorkAreaRemoved()),
1205 this, SLOT(on_lastWorkAreaRemoved()));
1207 d.splitter_->addWidget(twa);
1208 d.stack_widget_->setCurrentWidget(d.splitter_);
1213 GuiWorkArea const * GuiView::currentWorkArea() const
1215 return d.current_work_area_;
1219 GuiWorkArea * GuiView::currentWorkArea()
1221 return d.current_work_area_;
1225 GuiWorkArea const * GuiView::currentMainWorkArea() const
1227 if (!d.currentTabWorkArea())
1229 return d.currentTabWorkArea()->currentWorkArea();
1233 GuiWorkArea * GuiView::currentMainWorkArea()
1235 if (!d.currentTabWorkArea())
1237 return d.currentTabWorkArea()->currentWorkArea();
1241 void GuiView::setCurrentWorkArea(GuiWorkArea * wa)
1243 LYXERR(Debug::DEBUG, "Setting current wa: " << wa << endl);
1245 d.current_work_area_ = 0;
1250 // FIXME: I've no clue why this is here and why it accesses
1251 // theGuiApp()->currentView, which might be 0 (bug 6464).
1252 // See also 27525 (vfr).
1253 if (theGuiApp()->currentView() == this
1254 && theGuiApp()->currentView()->currentWorkArea() == wa)
1257 if (currentBufferView())
1258 cap::saveSelection(currentBufferView()->cursor());
1260 theGuiApp()->setCurrentView(this);
1261 d.current_work_area_ = wa;
1263 // We need to reset this now, because it will need to be
1264 // right if the tabWorkArea gets reset in the for loop. We
1265 // will change it back if we aren't in that case.
1266 GuiWorkArea * const old_cmwa = d.current_main_work_area_;
1267 d.current_main_work_area_ = wa;
1269 for (int i = 0; i != d.splitter_->count(); ++i) {
1270 if (d.tabWorkArea(i)->setCurrentWorkArea(wa)) {
1271 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea()
1272 << ", Current main wa: " << currentMainWorkArea());
1277 d.current_main_work_area_ = old_cmwa;
1279 LYXERR(Debug::DEBUG, "This is not a tabbed wa");
1280 on_currentWorkAreaChanged(wa);
1281 BufferView & bv = wa->bufferView();
1282 bv.cursor().fixIfBroken();
1284 wa->setUpdatesEnabled(true);
1285 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() << ", Current main wa: " << currentMainWorkArea());
1289 void GuiView::removeWorkArea(GuiWorkArea * wa)
1291 LASSERT(wa, return);
1292 if (wa == d.current_work_area_) {
1294 disconnectBufferView();
1295 d.current_work_area_ = 0;
1296 d.current_main_work_area_ = 0;
1299 bool found_twa = false;
1300 for (int i = 0; i != d.splitter_->count(); ++i) {
1301 TabWorkArea * twa = d.tabWorkArea(i);
1302 if (twa->removeWorkArea(wa)) {
1303 // Found in this tab group, and deleted the GuiWorkArea.
1305 if (twa->count() != 0) {
1306 if (d.current_work_area_ == 0)
1307 // This means that we are closing the current GuiWorkArea, so
1308 // switch to the next GuiWorkArea in the found TabWorkArea.
1309 setCurrentWorkArea(twa->currentWorkArea());
1311 // No more WorkAreas in this tab group, so delete it.
1318 // It is not a tabbed work area (i.e., the search work area), so it
1319 // should be deleted by other means.
1320 LASSERT(found_twa, /* */);
1322 if (d.current_work_area_ == 0) {
1323 if (d.splitter_->count() != 0) {
1324 TabWorkArea * twa = d.currentTabWorkArea();
1325 setCurrentWorkArea(twa->currentWorkArea());
1327 // No more work areas, switch to the background widget.
1328 setCurrentWorkArea(0);
1334 LayoutBox * GuiView::getLayoutDialog() const
1340 void GuiView::updateLayoutList()
1343 d.layout_->updateContents(false);
1347 void GuiView::updateToolbars()
1349 ToolbarMap::iterator end = d.toolbars_.end();
1350 if (d.current_work_area_) {
1352 d.current_work_area_->bufferView().cursor().inMathed()
1353 && !d.current_work_area_->bufferView().cursor().inRegexped();
1355 lyx::getStatus(FuncRequest(LFUN_LAYOUT_TABULAR)).enabled();
1357 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).enabled() &&
1358 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).onOff(true);
1359 bool const mathmacrotemplate =
1360 lyx::getStatus(FuncRequest(LFUN_IN_MATHMACROTEMPLATE)).enabled();
1362 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1363 it->second->update(math, table, review, mathmacrotemplate);
1365 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1366 it->second->update(false, false, false, false);
1370 void GuiView::setBuffer(Buffer * newBuffer)
1372 LYXERR(Debug::DEBUG, "Setting buffer: " << newBuffer << endl);
1373 LASSERT(newBuffer, return);
1376 GuiWorkArea * wa = workArea(*newBuffer);
1378 newBuffer->masterBuffer()->updateBuffer();
1379 wa = addWorkArea(*newBuffer);
1380 // scroll to the position when the BufferView was last closed
1381 if (lyxrc.use_lastfilepos) {
1382 LastFilePosSection::FilePos filepos =
1383 theSession().lastFilePos().load(newBuffer->fileName());
1384 wa->bufferView().moveToPosition(filepos.pit, filepos.pos, 0, 0);
1387 //Disconnect the old buffer...there's no new one.
1390 connectBuffer(*newBuffer);
1391 connectBufferView(wa->bufferView());
1392 setCurrentWorkArea(wa);
1398 void GuiView::connectBuffer(Buffer & buf)
1400 buf.setGuiDelegate(this);
1404 void GuiView::disconnectBuffer()
1406 if (d.current_work_area_)
1407 d.current_work_area_->bufferView().buffer().setGuiDelegate(0);
1411 void GuiView::connectBufferView(BufferView & bv)
1413 bv.setGuiDelegate(this);
1417 void GuiView::disconnectBufferView()
1419 if (d.current_work_area_)
1420 d.current_work_area_->bufferView().setGuiDelegate(0);
1424 void GuiView::errors(string const & error_type, bool from_master)
1426 ErrorList & el = from_master ?
1427 currentBufferView()->buffer().masterBuffer()->errorList(error_type)
1428 : currentBufferView()->buffer().errorList(error_type);
1429 string data = error_type;
1431 data = "from_master|" + error_type;
1433 showDialog("errorlist", data);
1437 void GuiView::updateTocItem(string const & type, DocIterator const & dit)
1439 d.toc_models_.updateItem(toqstr(type), dit);
1443 void GuiView::structureChanged()
1445 d.toc_models_.reset(documentBufferView());
1446 // Navigator needs more than a simple update in this case. It needs to be
1448 updateDialog("toc", "");
1452 void GuiView::updateDialog(string const & name, string const & data)
1454 if (!isDialogVisible(name))
1457 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
1458 if (it == d.dialogs_.end())
1461 Dialog * const dialog = it->second.get();
1462 if (dialog->isVisibleView())
1463 dialog->initialiseParams(data);
1467 BufferView * GuiView::documentBufferView()
1469 return currentMainWorkArea()
1470 ? ¤tMainWorkArea()->bufferView()
1475 BufferView const * GuiView::documentBufferView() const
1477 return currentMainWorkArea()
1478 ? ¤tMainWorkArea()->bufferView()
1483 BufferView * GuiView::currentBufferView()
1485 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1489 BufferView const * GuiView::currentBufferView() const
1491 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1495 #if (QT_VERSION >= 0x040400)
1496 docstring GuiView::GuiViewPrivate::autosaveAndDestroy(
1497 Buffer const * orig, Buffer * buffer)
1499 bool const success = buffer->autoSave();
1501 busyBuffers.remove(orig);
1503 ? _("Automatic save done.")
1504 : _("Automatic save failed!");
1509 void GuiView::autoSave()
1511 LYXERR(Debug::INFO, "Running autoSave()");
1513 Buffer * buffer = documentBufferView()
1514 ? &documentBufferView()->buffer() : 0;
1518 #if (QT_VERSION >= 0x040400)
1519 GuiViewPrivate::busyBuffers.insert(buffer);
1520 QFuture<docstring> f = QtConcurrent::run(GuiViewPrivate::autosaveAndDestroy,
1521 buffer, buffer->clone());
1522 d.autosave_watcher_.setFuture(f);
1526 resetAutosaveTimers();
1530 void GuiView::resetAutosaveTimers()
1533 d.autosave_timeout_.restart();
1537 bool GuiView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1540 Buffer * buf = currentBufferView()
1541 ? ¤tBufferView()->buffer() : 0;
1542 Buffer * doc_buffer = documentBufferView()
1543 ? &(documentBufferView()->buffer()) : 0;
1545 // Check whether we need a buffer
1546 if (!lyxaction.funcHasFlag(cmd.action(), LyXAction::NoBuffer) && !buf) {
1547 // no, exit directly
1548 flag.message(from_utf8(N_("Command not allowed with"
1549 "out any document open")));
1550 flag.setEnabled(false);
1554 if (cmd.origin() == FuncRequest::TOC) {
1555 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
1556 if (!toc || !toc->getStatus(documentBufferView()->cursor(), cmd, flag))
1557 flag.setEnabled(false);
1561 switch(cmd.action()) {
1562 case LFUN_BUFFER_IMPORT:
1565 case LFUN_MASTER_BUFFER_UPDATE:
1566 case LFUN_MASTER_BUFFER_VIEW:
1567 enable = doc_buffer && doc_buffer->parent() != 0
1568 && !d.processing_thread_watcher_.isRunning();
1571 case LFUN_BUFFER_UPDATE:
1572 case LFUN_BUFFER_VIEW: {
1573 if (!doc_buffer || d.processing_thread_watcher_.isRunning()) {
1577 string format = to_utf8(cmd.argument());
1578 if (cmd.argument().empty())
1579 format = doc_buffer->getDefaultOutputFormat();
1580 enable = doc_buffer->isExportableFormat(format);
1584 case LFUN_BUFFER_RELOAD:
1585 enable = doc_buffer && !doc_buffer->isUnnamed()
1586 && doc_buffer->fileName().exists()
1587 && (!doc_buffer->isClean()
1588 || doc_buffer->isExternallyModified(Buffer::timestamp_method));
1591 case LFUN_BUFFER_CHILD_OPEN:
1592 enable = doc_buffer;
1595 case LFUN_BUFFER_WRITE:
1596 enable = doc_buffer && (doc_buffer->isUnnamed() || !doc_buffer->isClean());
1599 //FIXME: This LFUN should be moved to GuiApplication.
1600 case LFUN_BUFFER_WRITE_ALL: {
1601 // We enable the command only if there are some modified buffers
1602 Buffer * first = theBufferList().first();
1607 // We cannot use a for loop as the buffer list is a cycle.
1609 if (!b->isClean()) {
1613 b = theBufferList().next(b);
1614 } while (b != first);
1618 case LFUN_BUFFER_WRITE_AS:
1619 enable = doc_buffer;
1622 case LFUN_BUFFER_CLOSE:
1623 enable = doc_buffer;
1626 case LFUN_BUFFER_CLOSE_ALL:
1627 enable = theBufferList().last() != theBufferList().first();
1630 case LFUN_SPLIT_VIEW:
1631 if (cmd.getArg(0) == "vertical")
1632 enable = doc_buffer && (d.splitter_->count() == 1 ||
1633 d.splitter_->orientation() == Qt::Vertical);
1635 enable = doc_buffer && (d.splitter_->count() == 1 ||
1636 d.splitter_->orientation() == Qt::Horizontal);
1639 case LFUN_CLOSE_TAB_GROUP:
1640 enable = d.currentTabWorkArea();
1643 case LFUN_TOOLBAR_TOGGLE: {
1644 string const name = cmd.getArg(0);
1645 if (GuiToolbar * t = toolbar(name))
1646 flag.setOnOff(t->isVisible());
1649 docstring const msg =
1650 bformat(_("Unknown toolbar \"%1$s\""), from_utf8(name));
1656 case LFUN_DROP_LAYOUTS_CHOICE:
1660 case LFUN_UI_TOGGLE:
1661 flag.setOnOff(isFullScreen());
1664 case LFUN_DIALOG_DISCONNECT_INSET:
1667 case LFUN_DIALOG_HIDE:
1668 // FIXME: should we check if the dialog is shown?
1671 case LFUN_DIALOG_TOGGLE:
1672 flag.setOnOff(isDialogVisible(cmd.getArg(0)));
1673 // fall through to set "enable"
1674 case LFUN_DIALOG_SHOW: {
1675 string const name = cmd.getArg(0);
1677 enable = name == "aboutlyx"
1678 || name == "file" //FIXME: should be removed.
1680 || name == "texinfo"
1681 || name == "progress"
1682 || name == "compare";
1683 else if (name == "print")
1684 enable = doc_buffer->isExportable("dvi")
1685 && lyxrc.print_command != "none";
1686 else if (name == "character" || name == "symbols") {
1687 if (!buf || buf->isReadonly())
1690 // FIXME we should consider passthru
1692 Inset const & in = currentBufferView()->cursor().inset();
1693 enable = !in.getLayout().isPassThru();
1696 else if (name == "latexlog")
1697 enable = FileName(doc_buffer->logName()).isReadableFile();
1698 else if (name == "spellchecker")
1699 enable = theSpellChecker() && !doc_buffer->isReadonly();
1700 else if (name == "vclog")
1701 enable = doc_buffer->lyxvc().inUse();
1705 case LFUN_DIALOG_UPDATE: {
1706 string const name = cmd.getArg(0);
1708 enable = name == "prefs";
1712 case LFUN_COMMAND_EXECUTE:
1714 case LFUN_MENU_OPEN:
1715 // Nothing to check.
1718 case LFUN_COMPLETION_INLINE:
1719 if (!d.current_work_area_
1720 || !d.current_work_area_->completer().inlinePossible(
1721 currentBufferView()->cursor()))
1725 case LFUN_COMPLETION_POPUP:
1726 if (!d.current_work_area_
1727 || !d.current_work_area_->completer().popupPossible(
1728 currentBufferView()->cursor()))
1732 case LFUN_COMPLETION_COMPLETE:
1733 if (!d.current_work_area_
1734 || !d.current_work_area_->completer().inlinePossible(
1735 currentBufferView()->cursor()))
1739 case LFUN_COMPLETION_ACCEPT:
1740 if (!d.current_work_area_
1741 || (!d.current_work_area_->completer().popupVisible()
1742 && !d.current_work_area_->completer().inlineVisible()
1743 && !d.current_work_area_->completer().completionAvailable()))
1747 case LFUN_COMPLETION_CANCEL:
1748 if (!d.current_work_area_
1749 || (!d.current_work_area_->completer().popupVisible()
1750 && !d.current_work_area_->completer().inlineVisible()))
1754 case LFUN_BUFFER_ZOOM_OUT:
1755 enable = doc_buffer && lyxrc.zoom > 10;
1758 case LFUN_BUFFER_ZOOM_IN:
1759 enable = doc_buffer;
1762 case LFUN_BUFFER_NEXT:
1763 case LFUN_BUFFER_PREVIOUS:
1764 // FIXME: should we check is there is an previous or next buffer?
1766 case LFUN_BUFFER_SWITCH:
1767 // toggle on the current buffer, but do not toggle off
1768 // the other ones (is that a good idea?)
1770 && to_utf8(cmd.argument()) == doc_buffer->absFileName())
1771 flag.setOnOff(true);
1774 case LFUN_VC_REGISTER:
1775 enable = doc_buffer && !doc_buffer->lyxvc().inUse();
1777 case LFUN_VC_CHECK_IN:
1778 enable = doc_buffer && doc_buffer->lyxvc().checkInEnabled();
1780 case LFUN_VC_CHECK_OUT:
1781 enable = doc_buffer && doc_buffer->lyxvc().checkOutEnabled();
1783 case LFUN_VC_LOCKING_TOGGLE:
1784 enable = doc_buffer && !doc_buffer->isReadonly()
1785 && doc_buffer->lyxvc().lockingToggleEnabled();
1786 flag.setOnOff(enable && doc_buffer->lyxvc().locking());
1788 case LFUN_VC_REVERT:
1789 enable = doc_buffer && doc_buffer->lyxvc().inUse() && !doc_buffer->isReadonly();
1791 case LFUN_VC_UNDO_LAST:
1792 enable = doc_buffer && doc_buffer->lyxvc().undoLastEnabled();
1794 case LFUN_VC_REPO_UPDATE:
1795 enable = doc_buffer && doc_buffer->lyxvc().repoUpdateEnabled();
1797 case LFUN_VC_COMMAND: {
1798 if (cmd.argument().empty())
1800 if (!doc_buffer && contains(cmd.getArg(0), 'D'))
1804 case LFUN_VC_COMPARE:
1805 enable = doc_buffer && doc_buffer->lyxvc().prepareFileRevisionEnabled();
1808 case LFUN_SERVER_GOTO_FILE_ROW:
1810 case LFUN_FORWARD_SEARCH:
1811 enable = !(lyxrc.forward_search_dvi.empty() && lyxrc.forward_search_pdf.empty());
1819 flag.setEnabled(false);
1825 static FileName selectTemplateFile()
1827 FileDialog dlg(qt_("Select template file"));
1828 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1829 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
1831 FileDialog::Result result = dlg.open(toqstr(lyxrc.template_path),
1832 QStringList(qt_("LyX Documents (*.lyx)")));
1834 if (result.first == FileDialog::Later)
1836 if (result.second.isEmpty())
1838 return FileName(fromqstr(result.second));
1842 Buffer * GuiView::loadDocument(FileName const & filename, bool tolastfiles)
1846 Buffer * newBuffer = 0;
1848 newBuffer = checkAndLoadLyXFile(filename);
1849 } catch (ExceptionMessage const & e) {
1855 message(_("Document not loaded."));
1860 newBuffer->errors("Parse");
1861 setBuffer(newBuffer);
1864 theSession().lastFiles().add(filename);
1871 void GuiView::openDocument(string const & fname)
1873 string initpath = lyxrc.document_path;
1875 if (documentBufferView()) {
1876 string const trypath = documentBufferView()->buffer().filePath();
1877 // If directory is writeable, use this as default.
1878 if (FileName(trypath).isDirWritable())
1884 if (fname.empty()) {
1885 FileDialog dlg(qt_("Select document to open"), LFUN_FILE_OPEN);
1886 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1887 dlg.setButton2(qt_("Examples|#E#e"),
1888 toqstr(addPath(package().system_support().absFileName(), "examples")));
1890 QStringList filter(qt_("LyX Documents (*.lyx)"));
1891 filter << qt_("LyX-1.3.x Documents (*.lyx13)")
1892 << qt_("LyX-1.4.x Documents (*.lyx14)")
1893 << qt_("LyX-1.5.x Documents (*.lyx15)")
1894 << qt_("LyX-1.6.x Documents (*.lyx16)");
1895 FileDialog::Result result =
1896 dlg.open(toqstr(initpath), filter);
1898 if (result.first == FileDialog::Later)
1901 filename = fromqstr(result.second);
1903 // check selected filename
1904 if (filename.empty()) {
1905 message(_("Canceled."));
1911 // get absolute path of file and add ".lyx" to the filename if
1913 FileName const fullname =
1914 fileSearch(string(), filename, "lyx", support::may_not_exist);
1915 if (!fullname.empty())
1916 filename = fullname.absFileName();
1918 if (!fullname.onlyPath().isDirectory()) {
1919 Alert::warning(_("Invalid filename"),
1920 bformat(_("The directory in the given path\n%1$s\ndoes not exist."),
1921 from_utf8(fullname.absFileName())));
1925 // if the file doesn't exist and isn't already open (bug 6645),
1926 // let the user create one
1927 if (!fullname.exists() && !theBufferList().exists(fullname)) {
1928 // the user specifically chose this name. Believe him.
1929 Buffer * const b = newFile(filename, string(), true);
1935 docstring const disp_fn = makeDisplayPath(filename);
1936 message(bformat(_("Opening document %1$s..."), disp_fn));
1939 Buffer * buf = loadDocument(fullname);
1941 str2 = bformat(_("Document %1$s opened."), disp_fn);
1942 if (buf->lyxvc().inUse())
1943 str2 += " " + from_utf8(buf->lyxvc().versionString()) +
1944 " " + _("Version control detected.");
1946 str2 = bformat(_("Could not open document %1$s"), disp_fn);
1951 // FIXME: clean that
1952 static bool import(GuiView * lv, FileName const & filename,
1953 string const & format, ErrorList & errorList)
1955 FileName const lyxfile(support::changeExtension(filename.absFileName(), ".lyx"));
1957 string loader_format;
1958 vector<string> loaders = theConverters().loaders();
1959 if (find(loaders.begin(), loaders.end(), format) == loaders.end()) {
1960 for (vector<string>::const_iterator it = loaders.begin();
1961 it != loaders.end(); ++it) {
1962 if (!theConverters().isReachable(format, *it))
1965 string const tofile =
1966 support::changeExtension(filename.absFileName(),
1967 formats.extension(*it));
1968 if (!theConverters().convert(0, filename, FileName(tofile),
1969 filename, format, *it, errorList))
1971 loader_format = *it;
1974 if (loader_format.empty()) {
1975 frontend::Alert::error(_("Couldn't import file"),
1976 bformat(_("No information for importing the format %1$s."),
1977 formats.prettyName(format)));
1981 loader_format = format;
1983 if (loader_format == "lyx") {
1984 Buffer * buf = lv->loadDocument(lyxfile);
1988 Buffer * const b = newFile(lyxfile.absFileName(), string(), true);
1992 bool as_paragraphs = loader_format == "textparagraph";
1993 string filename2 = (loader_format == format) ? filename.absFileName()
1994 : support::changeExtension(filename.absFileName(),
1995 formats.extension(loader_format));
1996 lv->currentBufferView()->insertPlaintextFile(FileName(filename2),
1998 guiApp->setCurrentView(lv);
1999 lyx::dispatch(FuncRequest(LFUN_MARK_OFF));
2006 void GuiView::importDocument(string const & argument)
2009 string filename = split(argument, format, ' ');
2011 LYXERR(Debug::INFO, format << " file: " << filename);
2013 // need user interaction
2014 if (filename.empty()) {
2015 string initpath = lyxrc.document_path;
2016 if (documentBufferView()) {
2017 string const trypath = documentBufferView()->buffer().filePath();
2018 // If directory is writeable, use this as default.
2019 if (FileName(trypath).isDirWritable())
2023 docstring const text = bformat(_("Select %1$s file to import"),
2024 formats.prettyName(format));
2026 FileDialog dlg(toqstr(text), LFUN_BUFFER_IMPORT);
2027 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2028 dlg.setButton2(qt_("Examples|#E#e"),
2029 toqstr(addPath(package().system_support().absFileName(), "examples")));
2031 docstring filter = formats.prettyName(format);
2034 filter += from_utf8(formats.extension(format));
2037 FileDialog::Result result =
2038 dlg.open(toqstr(initpath), fileFilters(toqstr(filter)));
2040 if (result.first == FileDialog::Later)
2043 filename = fromqstr(result.second);
2045 // check selected filename
2046 if (filename.empty())
2047 message(_("Canceled."));
2050 if (filename.empty())
2053 // get absolute path of file
2054 FileName const fullname(support::makeAbsPath(filename));
2056 FileName const lyxfile(support::changeExtension(fullname.absFileName(), ".lyx"));
2058 // Check if the document already is open
2059 Buffer * buf = theBufferList().getBuffer(lyxfile);
2062 if (!closeBuffer()) {
2063 message(_("Canceled."));
2068 docstring const displaypath = makeDisplayPath(lyxfile.absFileName(), 30);
2070 // if the file exists already, and we didn't do
2071 // -i lyx thefile.lyx, warn
2072 if (lyxfile.exists() && fullname != lyxfile) {
2074 docstring text = bformat(_("The document %1$s already exists.\n\n"
2075 "Do you want to overwrite that document?"), displaypath);
2076 int const ret = Alert::prompt(_("Overwrite document?"),
2077 text, 0, 1, _("&Overwrite"), _("&Cancel"));
2080 message(_("Canceled."));
2085 message(bformat(_("Importing %1$s..."), displaypath));
2086 ErrorList errorList;
2087 if (import(this, fullname, format, errorList))
2088 message(_("imported."));
2090 message(_("file not imported!"));
2092 // FIXME (Abdel 12/08/06): Is there a need to display the error list here?
2096 void GuiView::newDocument(string const & filename, bool from_template)
2098 FileName initpath(lyxrc.document_path);
2099 if (documentBufferView()) {
2100 FileName const trypath(documentBufferView()->buffer().filePath());
2101 // If directory is writeable, use this as default.
2102 if (trypath.isDirWritable())
2106 string templatefile;
2107 if (from_template) {
2108 templatefile = selectTemplateFile().absFileName();
2109 if (templatefile.empty())
2114 if (filename.empty())
2115 b = newUnnamedFile(initpath, to_utf8(_("newfile")), templatefile);
2117 b = newFile(filename, templatefile, true);
2122 // If no new document could be created, it is unsure
2123 // whether there is a valid BufferView.
2124 if (currentBufferView())
2125 // Ensure the cursor is correctly positioned on screen.
2126 currentBufferView()->showCursor();
2130 void GuiView::insertLyXFile(docstring const & fname)
2132 BufferView * bv = documentBufferView();
2137 FileName filename(to_utf8(fname));
2138 if (filename.empty()) {
2139 // Launch a file browser
2141 string initpath = lyxrc.document_path;
2142 string const trypath = bv->buffer().filePath();
2143 // If directory is writeable, use this as default.
2144 if (FileName(trypath).isDirWritable())
2148 FileDialog dlg(qt_("Select LyX document to insert"), LFUN_FILE_INSERT);
2149 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2150 dlg.setButton2(qt_("Examples|#E#e"),
2151 toqstr(addPath(package().system_support().absFileName(),
2154 FileDialog::Result result = dlg.open(toqstr(initpath),
2155 QStringList(qt_("LyX Documents (*.lyx)")));
2157 if (result.first == FileDialog::Later)
2161 filename.set(fromqstr(result.second));
2163 // check selected filename
2164 if (filename.empty()) {
2165 // emit message signal.
2166 message(_("Canceled."));
2171 bv->insertLyXFile(filename);
2172 bv->buffer().errors("Parse");
2176 void GuiView::insertPlaintextFile(docstring const & fname,
2179 BufferView * bv = documentBufferView();
2183 if (!fname.empty() && !FileName::isAbsolute(to_utf8(fname))) {
2184 message(_("Absolute filename expected."));
2189 FileName filename(to_utf8(fname));
2191 if (!filename.empty()) {
2192 bv->insertPlaintextFile(filename, asParagraph);
2196 FileDialog dlg(qt_("Select file to insert"), (asParagraph ?
2197 LFUN_FILE_INSERT_PLAINTEXT_PARA : LFUN_FILE_INSERT_PLAINTEXT));
2199 FileDialog::Result result = dlg.open(toqstr(bv->buffer().filePath()),
2200 QStringList(qt_("All Files (*)")));
2202 if (result.first == FileDialog::Later)
2206 filename.set(fromqstr(result.second));
2208 // check selected filename
2209 if (filename.empty()) {
2210 // emit message signal.
2211 message(_("Canceled."));
2215 bv->insertPlaintextFile(filename, asParagraph);
2219 bool GuiView::renameBuffer(Buffer & b, docstring const & newname)
2221 FileName fname = b.fileName();
2222 FileName const oldname = fname;
2224 if (!newname.empty()) {
2226 fname = support::makeAbsPath(to_utf8(newname), oldname.onlyPath().absFileName());
2228 // Switch to this Buffer.
2231 // No argument? Ask user through dialog.
2233 FileDialog dlg(qt_("Choose a filename to save document as"),
2234 LFUN_BUFFER_WRITE_AS);
2235 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2236 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
2238 if (!isLyXFileName(fname.absFileName()))
2239 fname.changeExtension(".lyx");
2241 FileDialog::Result result =
2242 dlg.save(toqstr(fname.onlyPath().absFileName()),
2243 QStringList(qt_("LyX Documents (*.lyx)")),
2244 toqstr(fname.onlyFileName()));
2246 if (result.first == FileDialog::Later)
2249 fname.set(fromqstr(result.second));
2254 if (!isLyXFileName(fname.absFileName()))
2255 fname.changeExtension(".lyx");
2258 // fname is now the new Buffer location.
2259 if (FileName(fname).exists()) {
2260 docstring const file = makeDisplayPath(fname.absFileName(), 30);
2261 docstring text = bformat(_("The document %1$s already "
2262 "exists.\n\nDo you want to "
2263 "overwrite that document?"),
2265 int const ret = Alert::prompt(_("Overwrite document?"),
2266 text, 0, 2, _("&Overwrite"), _("&Rename"), _("&Cancel"));
2269 case 1: return renameBuffer(b, docstring());
2270 case 2: return false;
2274 return saveBuffer(b, fname);
2278 bool GuiView::saveBuffer(Buffer & b) {
2279 return saveBuffer(b, FileName());
2283 bool GuiView::saveBuffer(Buffer & b, FileName const & fn)
2285 if (workArea(b) && workArea(b)->inDialogMode())
2288 if (fn.empty() && b.isUnnamed())
2289 return renameBuffer(b, docstring());
2295 success = b.saveAs(fn);
2298 theSession().lastFiles().add(b.fileName());
2302 // Switch to this Buffer.
2305 // FIXME: we don't tell the user *WHY* the save failed !!
2306 docstring const file = makeDisplayPath(b.absFileName(), 30);
2307 docstring text = bformat(_("The document %1$s could not be saved.\n\n"
2308 "Do you want to rename the document and "
2309 "try again?"), file);
2310 int const ret = Alert::prompt(_("Rename and save?"),
2311 text, 0, 2, _("&Rename"), _("&Retry"), _("&Cancel"));
2314 if (!renameBuffer(b, docstring()))
2323 return saveBuffer(b);
2327 bool GuiView::hideWorkArea(GuiWorkArea * wa)
2329 return closeWorkArea(wa, false);
2333 bool GuiView::closeWorkArea(GuiWorkArea * wa)
2335 Buffer & buf = wa->bufferView().buffer();
2336 return closeWorkArea(wa, !buf.parent());
2340 bool GuiView::closeBuffer()
2342 GuiWorkArea * wa = currentMainWorkArea();
2343 setCurrentWorkArea(wa);
2344 Buffer & buf = wa->bufferView().buffer();
2345 return wa && closeWorkArea(wa, !buf.parent());
2349 void GuiView::writeSession() const {
2350 GuiWorkArea const * active_wa = currentMainWorkArea();
2351 for (int i = 0; i < d.splitter_->count(); ++i) {
2352 TabWorkArea * twa = d.tabWorkArea(i);
2353 for (int j = 0; j < twa->count(); ++j) {
2354 GuiWorkArea * wa = static_cast<GuiWorkArea *>(twa->widget(j));
2355 Buffer & buf = wa->bufferView().buffer();
2356 theSession().lastOpened().add(buf.fileName(), wa == active_wa);
2362 bool GuiView::closeBufferAll()
2364 // Close the workareas in all other views
2365 QList<int> const ids = guiApp->viewIds();
2366 for (int i = 0; i != ids.size(); ++i) {
2367 if (id_ != ids[i] && !guiApp->view(ids[i]).closeWorkAreaAll())
2371 // Close our own workareas
2372 if (!closeWorkAreaAll())
2375 // Now close the hidden buffers. We prevent hidden buffers from being
2376 // dirty, so we can just close them.
2377 theBufferList().closeAll();
2382 bool GuiView::closeWorkAreaAll()
2384 setCurrentWorkArea(currentMainWorkArea());
2386 // We might be in a situation that there is still a tabWorkArea, but
2387 // there are no tabs anymore. This can happen when we get here after a
2388 // TabWorkArea::lastWorkAreaRemoved() signal. Therefore we count how
2389 // many TabWorkArea's have no documents anymore.
2392 // We have to call count() each time, because it can happen that
2393 // more than one splitter will disappear in one iteration (bug 5998).
2394 for (; d.splitter_->count() > empty_twa; ) {
2395 TabWorkArea * twa = d.tabWorkArea(empty_twa);
2397 if (twa->count() == 0)
2400 setCurrentWorkArea(twa->currentWorkArea());
2401 if (!closeTabWorkArea(twa))
2409 bool GuiView::closeWorkArea(GuiWorkArea * wa, bool close_buffer)
2414 Buffer & buf = wa->bufferView().buffer();
2416 if (close_buffer && GuiViewPrivate::busyBuffers.contains(&buf)) {
2417 Alert::warning(_("Close document "), _("Document could not be closed because it is processed by LyX."));
2422 return closeBuffer(buf);
2424 if (!inMultiTabs(wa))
2425 if (!saveBufferIfNeeded(buf, true))
2433 bool GuiView::closeBuffer(Buffer & buf)
2435 // If we are in a close_event all children will be closed in some time,
2436 // so no need to do it here. This will ensure that the children end up
2437 // in the session file in the correct order. If we close the master
2438 // buffer, we can close or release the child buffers here too.
2440 ListOfBuffers clist = buf.getChildren();
2441 ListOfBuffers::const_iterator it = clist.begin();
2442 ListOfBuffers::const_iterator const bend = clist.end();
2443 for (; it != bend; ++it) {
2444 // If a child is dirty, do not close
2445 // without user intervention
2446 //FIXME: should we look in other tabworkareas?
2447 Buffer * child_buf = *it;
2448 GuiWorkArea * child_wa = workArea(*child_buf);
2450 if (!closeWorkArea(child_wa, true))
2453 theBufferList().releaseChild(&buf, child_buf);
2456 // goto bookmark to update bookmark pit.
2457 //FIXME: we should update only the bookmarks related to this buffer!
2458 LYXERR(Debug::DEBUG, "GuiView::closeBuffer()");
2459 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
2460 guiApp->gotoBookmark(i+1, false, false);
2462 if (saveBufferIfNeeded(buf, false)) {
2463 buf.removeAutosaveFile();
2464 theBufferList().release(&buf);
2471 bool GuiView::closeTabWorkArea(TabWorkArea * twa)
2473 while (twa == d.currentTabWorkArea()) {
2474 twa->setCurrentIndex(twa->count()-1);
2476 GuiWorkArea * wa = twa->currentWorkArea();
2477 Buffer & b = wa->bufferView().buffer();
2479 // We only want to close the buffer if the same buffer is not visible
2480 // in another view, and if this is not a child and if we are closing
2481 // a view (not a tabgroup).
2482 bool const close_buffer =
2483 !inMultiViews(wa) && !b.parent() && closing_;
2485 if (!closeWorkArea(wa, close_buffer))
2492 bool GuiView::saveBufferIfNeeded(Buffer & buf, bool hiding)
2494 if (buf.isClean() || buf.paragraphs().empty())
2497 // Switch to this Buffer.
2502 if (buf.isUnnamed())
2503 file = from_utf8(buf.fileName().onlyFileName());
2505 file = buf.fileName().displayName(30);
2507 // Bring this window to top before asking questions.
2512 if (hiding && buf.isUnnamed()) {
2513 docstring const text = bformat(_("The document %1$s has not been "
2514 "saved yet.\n\nDo you want to save "
2515 "the document?"), file);
2516 ret = Alert::prompt(_("Save new document?"),
2517 text, 0, 1, _("&Save"), _("&Cancel"));
2521 docstring const text = bformat(_("The document %1$s has unsaved changes."
2522 "\n\nDo you want to save the document or discard the changes?"), file);
2523 ret = Alert::prompt(_("Save changed document?"),
2524 text, 0, 2, _("&Save"), _("&Discard"), _("&Cancel"));
2529 if (!saveBuffer(buf))
2533 // if we crash after this we could
2534 // have no autosave file but I guess
2535 // this is really improbable (Jug)
2536 // Sometime improbable things happen, bug 6857 (ps)
2537 // buf.removeAutosaveFile();
2539 // revert all changes
2550 bool GuiView::inMultiTabs(GuiWorkArea * wa)
2552 Buffer & buf = wa->bufferView().buffer();
2554 for (int i = 0; i != d.splitter_->count(); ++i) {
2555 GuiWorkArea * wa_ = d.tabWorkArea(i)->workArea(buf);
2556 if (wa_ && wa_ != wa)
2559 return inMultiViews(wa);
2563 bool GuiView::inMultiViews(GuiWorkArea * wa)
2565 QList<int> const ids = guiApp->viewIds();
2566 Buffer & buf = wa->bufferView().buffer();
2569 for (int i = 0; i != ids.size() && found_twa <= 1; ++i) {
2573 if (guiApp->view(ids[i]).workArea(buf))
2580 void GuiView::gotoNextOrPreviousBuffer(NextOrPrevious np)
2582 Buffer * const curbuf = documentBufferView()
2583 ? &documentBufferView()->buffer() : 0;
2584 Buffer * nextbuf = curbuf;
2586 if (np == NEXTBUFFER)
2587 nextbuf = theBufferList().next(nextbuf);
2589 nextbuf = theBufferList().previous(nextbuf);
2590 if (nextbuf == curbuf)
2596 if (workArea(*nextbuf))
2603 /// make sure the document is saved
2604 static bool ensureBufferClean(Buffer * buffer)
2606 LASSERT(buffer, return false);
2607 if (buffer->isClean() && !buffer->isUnnamed())
2610 docstring const file = buffer->fileName().displayName(30);
2613 if (!buffer->isUnnamed()) {
2614 text = bformat(_("The document %1$s has unsaved "
2615 "changes.\n\nDo you want to save "
2616 "the document?"), file);
2617 title = _("Save changed document?");
2620 text = bformat(_("The document %1$s has not been "
2621 "saved yet.\n\nDo you want to save "
2622 "the document?"), file);
2623 title = _("Save new document?");
2625 int const ret = Alert::prompt(title, text, 0, 1, _("&Save"), _("&Cancel"));
2628 dispatch(FuncRequest(LFUN_BUFFER_WRITE));
2630 return buffer->isClean() && !buffer->isUnnamed();
2634 bool GuiView::reloadBuffer(Buffer & buf)
2636 Buffer::ReadStatus status = buf.reload();
2637 return status == Buffer::ReadSuccess;
2641 void GuiView::checkExternallyModifiedBuffers()
2643 BufferList::iterator bit = theBufferList().begin();
2644 BufferList::iterator const bend = theBufferList().end();
2645 for (; bit != bend; ++bit) {
2646 Buffer * buf = *bit;
2647 if (buf->fileName().exists()
2648 && buf->isExternallyModified(Buffer::checksum_method)) {
2649 docstring text = bformat(_("Document \n%1$s\n has been externally modified."
2650 " Reload now? Any local changes will be lost."),
2651 from_utf8(buf->absFileName()));
2652 int const ret = Alert::prompt(_("Reload externally changed document?"),
2653 text, 0, 1, _("&Reload"), _("&Cancel"));
2661 void GuiView::dispatchVC(FuncRequest const & cmd, DispatchResult & dr)
2663 Buffer * buffer = documentBufferView()
2664 ? &(documentBufferView()->buffer()) : 0;
2666 switch (cmd.action()) {
2667 case LFUN_VC_REGISTER:
2668 if (!buffer || !ensureBufferClean(buffer))
2670 if (!buffer->lyxvc().inUse()) {
2671 if (buffer->lyxvc().registrer()) {
2672 reloadBuffer(*buffer);
2673 dr.suppressMessageUpdate();
2678 case LFUN_VC_CHECK_IN:
2679 if (!buffer || !ensureBufferClean(buffer))
2681 if (buffer->lyxvc().inUse() && !buffer->isReadonly()) {
2682 dr.setMessage(buffer->lyxvc().checkIn());
2683 if (!dr.message().empty())
2684 reloadBuffer(*buffer);
2688 case LFUN_VC_CHECK_OUT:
2689 if (!buffer || !ensureBufferClean(buffer))
2691 if (buffer->lyxvc().inUse()) {
2692 dr.setMessage(buffer->lyxvc().checkOut());
2693 reloadBuffer(*buffer);
2697 case LFUN_VC_LOCKING_TOGGLE:
2698 LASSERT(buffer, return);
2699 if (!ensureBufferClean(buffer) || buffer->isReadonly())
2701 if (buffer->lyxvc().inUse()) {
2702 string res = buffer->lyxvc().lockingToggle();
2704 frontend::Alert::error(_("Revision control error."),
2705 _("Error when setting the locking property."));
2708 reloadBuffer(*buffer);
2713 case LFUN_VC_REVERT:
2714 LASSERT(buffer, return);
2715 if (buffer->lyxvc().revert()) {
2716 reloadBuffer(*buffer);
2717 dr.suppressMessageUpdate();
2721 case LFUN_VC_UNDO_LAST:
2722 LASSERT(buffer, return);
2723 buffer->lyxvc().undoLast();
2724 reloadBuffer(*buffer);
2725 dr.suppressMessageUpdate();
2728 case LFUN_VC_REPO_UPDATE:
2729 LASSERT(buffer, return);
2730 if (ensureBufferClean(buffer)) {
2731 dr.setMessage(buffer->lyxvc().repoUpdate());
2732 checkExternallyModifiedBuffers();
2736 case LFUN_VC_COMMAND: {
2737 string flag = cmd.getArg(0);
2738 if (buffer && contains(flag, 'R') && !ensureBufferClean(buffer))
2741 if (contains(flag, 'M')) {
2742 if (!Alert::askForText(message, _("LyX VC: Log Message")))
2745 string path = cmd.getArg(1);
2746 if (contains(path, "$$p") && buffer)
2747 path = subst(path, "$$p", buffer->filePath());
2748 LYXERR(Debug::LYXVC, "Directory: " << path);
2750 if (!pp.isReadableDirectory()) {
2751 lyxerr << _("Directory is not accessible.") << endl;
2754 support::PathChanger p(pp);
2756 string command = cmd.getArg(2);
2757 if (command.empty())
2760 command = subst(command, "$$i", buffer->absFileName());
2761 command = subst(command, "$$p", buffer->filePath());
2763 command = subst(command, "$$m", to_utf8(message));
2764 LYXERR(Debug::LYXVC, "Command: " << command);
2766 one.startscript(Systemcall::Wait, command);
2770 if (contains(flag, 'I'))
2771 buffer->markDirty();
2772 if (contains(flag, 'R'))
2773 reloadBuffer(*buffer);
2778 case LFUN_VC_COMPARE: {
2780 if (cmd.argument().empty()) {
2781 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "comparehistory"));
2785 string rev1 = cmd.getArg(0);
2789 if (!buffer->lyxvc().prepareFileRevision(rev1, f1))
2792 if (isStrInt(rev1) && convert<int>(rev1) <= 0) {
2793 f2 = buffer->absFileName();
2795 string rev2 = cmd.getArg(1);
2799 if (!buffer->lyxvc().prepareFileRevision(rev2, f2))
2803 LYXERR(Debug::LYXVC, "Launching comparison for fetched revisions:\n" <<
2804 f1 << "\n" << f2 << "\n" );
2805 string par = "compare run " + quoteName(f1) + " " + quoteName(f2);
2806 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, par));
2816 void GuiView::openChildDocument(string const & fname)
2818 LASSERT(documentBufferView(), return);
2819 Buffer & buffer = documentBufferView()->buffer();
2820 FileName const filename = support::makeAbsPath(fname, buffer.filePath());
2821 documentBufferView()->saveBookmark(false);
2823 if (theBufferList().exists(filename)) {
2824 child = theBufferList().getBuffer(filename);
2827 message(bformat(_("Opening child document %1$s..."),
2828 makeDisplayPath(filename.absFileName())));
2829 child = loadDocument(filename, false);
2831 // Set the parent name of the child document.
2832 // This makes insertion of citations and references in the child work,
2833 // when the target is in the parent or another child document.
2835 child->setParent(&buffer);
2839 bool GuiView::goToFileRow(string const & argument)
2843 size_t i = argument.find_last_of(' ');
2844 if (i != string::npos) {
2845 file_name = os::internal_path(trim(argument.substr(0, i)));
2846 istringstream is(argument.substr(i + 1));
2851 if (i == string::npos) {
2852 LYXERR0("Wrong argument: " << argument);
2856 string const abstmp = package().temp_dir().absFileName();
2857 string const realtmp = package().temp_dir().realPath();
2858 // We have to use os::path_prefix_is() here, instead of
2859 // simply prefixIs(), because the file name comes from
2860 // an external application and may need case adjustment.
2861 if (os::path_prefix_is(file_name, abstmp, os::CASE_ADJUSTED)
2862 || os::path_prefix_is(file_name, realtmp, os::CASE_ADJUSTED)) {
2863 // Needed by inverse dvi search. If it is a file
2864 // in tmpdir, call the apropriated function.
2865 // If tmpdir is a symlink, we may have the real
2866 // path passed back, so we correct for that.
2867 if (!prefixIs(file_name, abstmp))
2868 file_name = subst(file_name, realtmp, abstmp);
2869 buf = theBufferList().getBufferFromTmp(file_name);
2871 // Must replace extension of the file to be .lyx
2872 // and get full path
2873 FileName const s = fileSearch(string(),
2874 support::changeExtension(file_name, ".lyx"), "lyx");
2875 // Either change buffer or load the file
2876 if (theBufferList().exists(s))
2877 buf = theBufferList().getBuffer(s);
2878 else if (s.exists()) {
2879 buf = loadDocument(s);
2884 _("File does not exist: %1$s"),
2885 makeDisplayPath(file_name)));
2890 documentBufferView()->setCursorFromRow(row);
2895 #if (QT_VERSION >= 0x040400)
2897 docstring GuiView::GuiViewPrivate::runAndDestroy(const T& func, Buffer const * orig, Buffer * buffer, string const & format, string const & msg)
2899 bool const update_unincluded =
2900 buffer->params().maintain_unincluded_children
2901 && !buffer->params().getIncludedChildren().empty();
2902 bool const success = func(format, update_unincluded);
2904 busyBuffers.remove(orig);
2905 if (msg == "preview") {
2907 ? bformat(_("Successful preview of format: %1$s"), from_utf8(format))
2908 : bformat(_("Error while previewing format: %1$s"), from_utf8(format));
2911 ? bformat(_("Successful export to format: %1$s"), from_utf8(format))
2912 : bformat(_("Error while exporting format: %1$s"), from_utf8(format));
2916 docstring GuiView::GuiViewPrivate::compileAndDestroy(Buffer const * orig, Buffer * buffer, string const & format)
2918 bool (Buffer::* mem_func)(std::string const &, bool, bool) const = &Buffer::doExport;
2919 return runAndDestroy(bind(mem_func, buffer, _1, true, _2), orig, buffer, format, "export");
2923 docstring GuiView::GuiViewPrivate::exportAndDestroy(Buffer const * orig, Buffer * buffer, string const & format)
2925 bool (Buffer::* mem_func)(std::string const &, bool, bool) const = &Buffer::doExport;
2926 return runAndDestroy(bind(mem_func, buffer, _1, false, _2), orig, buffer, format, "export");
2930 docstring GuiView::GuiViewPrivate::previewAndDestroy(Buffer const * orig, Buffer * buffer, string const & format)
2932 bool(Buffer::* mem_func)(std::string const &, bool) const = &Buffer::preview;
2933 return runAndDestroy(bind(mem_func, buffer, _1, _2), orig, buffer, format, "preview");
2938 // not used, but the linker needs them
2940 docstring GuiView::GuiViewPrivate::compileAndDestroy(
2941 Buffer const *, Buffer *, string const &)
2947 docstring GuiView::GuiViewPrivate::exportAndDestroy(
2948 Buffer const *, Buffer *, string const &)
2954 docstring GuiView::GuiViewPrivate::previewAndDestroy(
2955 Buffer const *, Buffer *, string const &)
2963 bool GuiView::GuiViewPrivate::asyncBufferProcessing(
2964 string const & argument,
2965 Buffer const * used_buffer,
2966 docstring const & msg,
2967 docstring (*asyncFunc)(Buffer const *, Buffer *, string const &),
2968 bool (Buffer::*syncFunc)(string const &, bool, bool) const,
2969 bool (Buffer::*previewFunc)(string const &, bool) const)
2974 string format = argument;
2976 format = used_buffer->getDefaultOutputFormat();
2978 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
2979 gv_->processingThreadStarted();
2981 progress_->clearMessages();
2984 GuiViewPrivate::busyBuffers.insert(used_buffer);
2985 QFuture<docstring> f = QtConcurrent::run(
2988 used_buffer->clone(),
2990 setPreviewFuture(f);
2991 last_export_format = used_buffer->bufferFormat();
2994 // We are asynchronous, so we don't know here anything about the success
2998 // TODO check here if it breaks exporting with Qt < 4.4
2999 bool const update_unincluded =
3000 used_buffer->params().maintain_unincluded_children &&
3001 !used_buffer->params().getIncludedChildren().empty();
3002 return (used_buffer->*syncFunc)(format, true, update_unincluded);
3003 } else if (previewFunc) {
3004 return (used_buffer->*previewFunc)(format, false);
3011 void GuiView::dispatch(FuncRequest const & cmd, DispatchResult & dr)
3013 BufferView * bv = currentBufferView();
3014 // By default we won't need any update.
3015 dr.screenUpdate(Update::None);
3016 // assume cmd will be dispatched
3017 dr.dispatched(true);
3019 Buffer * doc_buffer = documentBufferView()
3020 ? &(documentBufferView()->buffer()) : 0;
3022 if (cmd.origin() == FuncRequest::TOC) {
3023 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
3024 // FIXME: do we need to pass a DispatchResult object here?
3025 toc->doDispatch(bv->cursor(), cmd);
3029 string const argument = to_utf8(cmd.argument());
3031 switch(cmd.action()) {
3032 case LFUN_BUFFER_CHILD_OPEN:
3033 openChildDocument(to_utf8(cmd.argument()));
3036 case LFUN_BUFFER_IMPORT:
3037 importDocument(to_utf8(cmd.argument()));
3040 case LFUN_BUFFER_EXPORT: {
3043 // GCC only sees strfwd.h when building merged
3044 if (::lyx::operator==(cmd.argument(), "custom")) {
3045 dispatch(FuncRequest(LFUN_DIALOG_SHOW, "sendto"), dr);
3048 #if QT_VERSION < 0x040400
3049 if (!doc_buffer->doExport(argument, false)) {
3051 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
3055 /* TODO/Review: Is it a problem to also export the children?
3056 See the update_unincluded flag */
3057 d.asyncBufferProcessing(argument,
3060 &GuiViewPrivate::exportAndDestroy,
3063 // TODO Inform user about success
3068 case LFUN_BUFFER_UPDATE: {
3069 d.asyncBufferProcessing(argument,
3072 &GuiViewPrivate::compileAndDestroy,
3077 case LFUN_BUFFER_VIEW: {
3078 d.asyncBufferProcessing(argument,
3080 _("Previewing ..."),
3081 &GuiViewPrivate::previewAndDestroy,
3086 case LFUN_MASTER_BUFFER_UPDATE: {
3087 d.asyncBufferProcessing(argument,
3088 (doc_buffer ? doc_buffer->masterBuffer() : 0),
3090 &GuiViewPrivate::compileAndDestroy,
3095 case LFUN_MASTER_BUFFER_VIEW: {
3096 d.asyncBufferProcessing(argument,
3097 (doc_buffer ? doc_buffer->masterBuffer() : 0),
3099 &GuiViewPrivate::previewAndDestroy,
3100 0, &Buffer::preview);
3103 case LFUN_BUFFER_SWITCH: {
3104 string const file_name = to_utf8(cmd.argument());
3105 if (!FileName::isAbsolute(file_name)) {
3107 dr.setMessage(_("Absolute filename expected."));
3111 Buffer * buffer = theBufferList().getBuffer(FileName(file_name));
3114 dr.setMessage(_("Document not loaded"));
3118 // Do we open or switch to the buffer in this view ?
3119 if (workArea(*buffer)
3120 || lyxrc.open_buffers_in_tabs || !documentBufferView()) {
3125 // Look for the buffer in other views
3126 QList<int> const ids = guiApp->viewIds();
3128 for (; i != ids.size(); ++i) {
3129 GuiView & gv = guiApp->view(ids[i]);
3130 if (gv.workArea(*buffer)) {
3131 gv.activateWindow();
3132 gv.setBuffer(buffer);
3137 // If necessary, open a new window as a last resort
3138 if (i == ids.size()) {
3139 lyx::dispatch(FuncRequest(LFUN_WINDOW_NEW));
3145 case LFUN_BUFFER_NEXT:
3146 gotoNextOrPreviousBuffer(NEXTBUFFER);
3149 case LFUN_BUFFER_PREVIOUS:
3150 gotoNextOrPreviousBuffer(PREVBUFFER);
3153 case LFUN_COMMAND_EXECUTE: {
3154 bool const show_it = cmd.argument() != "off";
3155 // FIXME: this is a hack, "minibuffer" should not be
3157 if (GuiToolbar * t = toolbar("minibuffer")) {
3158 t->setVisible(show_it);
3159 if (show_it && t->commandBuffer())
3160 t->commandBuffer()->setFocus();
3164 case LFUN_DROP_LAYOUTS_CHOICE:
3165 d.layout_->showPopup();
3168 case LFUN_MENU_OPEN:
3169 if (QMenu * menu = guiApp->menus().menu(toqstr(cmd.argument()), *this))
3170 menu->exec(QCursor::pos());
3173 case LFUN_FILE_INSERT:
3174 insertLyXFile(cmd.argument());
3177 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
3178 insertPlaintextFile(cmd.argument(), true);
3181 case LFUN_FILE_INSERT_PLAINTEXT:
3182 insertPlaintextFile(cmd.argument(), false);
3185 case LFUN_BUFFER_RELOAD: {
3186 LASSERT(doc_buffer, break);
3189 if (!doc_buffer->isClean()) {
3190 docstring const file =
3191 makeDisplayPath(doc_buffer->absFileName(), 20);
3192 docstring text = bformat(_("Any changes will be lost. "
3193 "Are you sure you want to revert to the saved version "
3194 "of the document %1$s?"), file);
3195 ret = Alert::prompt(_("Revert to saved document?"),
3196 text, 1, 1, _("&Revert"), _("&Cancel"));
3200 doc_buffer->markClean();
3201 reloadBuffer(*doc_buffer);
3202 dr.forceBufferUpdate();
3207 case LFUN_BUFFER_WRITE:
3208 LASSERT(doc_buffer, break);
3209 saveBuffer(*doc_buffer);
3212 case LFUN_BUFFER_WRITE_AS:
3213 LASSERT(doc_buffer, break);
3214 renameBuffer(*doc_buffer, cmd.argument());
3217 case LFUN_BUFFER_WRITE_ALL: {
3218 Buffer * first = theBufferList().first();
3221 message(_("Saving all documents..."));
3222 // We cannot use a for loop as the buffer list cycles.
3225 if (!b->isClean()) {
3227 LYXERR(Debug::ACTION, "Saved " << b->absFileName());
3229 b = theBufferList().next(b);
3230 } while (b != first);
3231 dr.setMessage(_("All documents saved."));
3235 case LFUN_BUFFER_CLOSE:
3239 case LFUN_BUFFER_CLOSE_ALL:
3243 case LFUN_TOOLBAR_TOGGLE: {
3244 string const name = cmd.getArg(0);
3245 if (GuiToolbar * t = toolbar(name))
3250 case LFUN_DIALOG_UPDATE: {
3251 string const name = to_utf8(cmd.argument());
3252 if (name == "prefs" || name == "document")
3253 updateDialog(name, string());
3254 else if (name == "paragraph")
3255 lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
3256 else if (currentBufferView()) {
3257 Inset * inset = currentBufferView()->editedInset(name);
3258 // Can only update a dialog connected to an existing inset
3260 // FIXME: get rid of this indirection; GuiView ask the inset
3261 // if he is kind enough to update itself...
3262 FuncRequest fr(LFUN_INSET_DIALOG_UPDATE, cmd.argument());
3263 //FIXME: pass DispatchResult here?
3264 inset->dispatch(currentBufferView()->cursor(), fr);
3270 case LFUN_DIALOG_TOGGLE: {
3271 if (isDialogVisible(cmd.getArg(0)))
3272 dispatch(FuncRequest(LFUN_DIALOG_HIDE, cmd.argument()), dr);
3274 dispatch(FuncRequest(LFUN_DIALOG_SHOW, cmd.argument()), dr);
3278 case LFUN_DIALOG_DISCONNECT_INSET:
3279 disconnectDialog(to_utf8(cmd.argument()));
3282 case LFUN_DIALOG_HIDE: {
3283 guiApp->hideDialogs(to_utf8(cmd.argument()), 0);
3287 case LFUN_DIALOG_SHOW: {
3288 string const name = cmd.getArg(0);
3289 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
3291 if (name == "character") {
3292 data = freefont2string();
3294 showDialog("character", data);
3295 } else if (name == "latexlog") {
3296 Buffer::LogType type;
3297 string const logfile = doc_buffer->logName(&type);
3299 case Buffer::latexlog:
3302 case Buffer::buildlog:
3306 data += Lexer::quoteString(logfile);
3307 showDialog("log", data);
3308 } else if (name == "vclog") {
3309 string const data = "vc " +
3310 Lexer::quoteString(doc_buffer->lyxvc().getLogFile());
3311 showDialog("log", data);
3312 } else if (name == "symbols") {
3313 data = bv->cursor().getEncoding()->name();
3315 showDialog("symbols", data);
3317 } else if (name == "prefs" && isFullScreen()) {
3318 lfunUiToggle("fullscreen");
3319 showDialog("prefs", data);
3321 showDialog(name, data);
3326 dr.setMessage(cmd.argument());
3329 case LFUN_UI_TOGGLE: {
3330 string arg = cmd.getArg(0);
3331 if (!lfunUiToggle(arg)) {
3332 docstring const msg = "ui-toggle " + _("%1$s unknown command!");
3333 dr.setMessage(bformat(msg, from_utf8(arg)));
3335 // Make sure the keyboard focus stays in the work area.
3340 case LFUN_SPLIT_VIEW: {
3341 LASSERT(doc_buffer, break);
3342 string const orientation = cmd.getArg(0);
3343 d.splitter_->setOrientation(orientation == "vertical"
3344 ? Qt::Vertical : Qt::Horizontal);
3345 TabWorkArea * twa = addTabWorkArea();
3346 GuiWorkArea * wa = twa->addWorkArea(*doc_buffer, *this);
3347 setCurrentWorkArea(wa);
3350 case LFUN_CLOSE_TAB_GROUP:
3351 if (TabWorkArea * twa = d.currentTabWorkArea()) {
3352 closeTabWorkArea(twa);
3353 d.current_work_area_ = 0;
3354 twa = d.currentTabWorkArea();
3355 // Switch to the next GuiWorkArea in the found TabWorkArea.
3357 // Make sure the work area is up to date.
3358 setCurrentWorkArea(twa->currentWorkArea());
3360 setCurrentWorkArea(0);
3365 case LFUN_COMPLETION_INLINE:
3366 if (d.current_work_area_)
3367 d.current_work_area_->completer().showInline();
3370 case LFUN_COMPLETION_POPUP:
3371 if (d.current_work_area_)
3372 d.current_work_area_->completer().showPopup();
3376 case LFUN_COMPLETION_COMPLETE:
3377 if (d.current_work_area_)
3378 d.current_work_area_->completer().tab();
3381 case LFUN_COMPLETION_CANCEL:
3382 if (d.current_work_area_) {
3383 if (d.current_work_area_->completer().popupVisible())
3384 d.current_work_area_->completer().hidePopup();
3386 d.current_work_area_->completer().hideInline();
3390 case LFUN_COMPLETION_ACCEPT:
3391 if (d.current_work_area_)
3392 d.current_work_area_->completer().activate();
3395 case LFUN_BUFFER_ZOOM_IN:
3396 case LFUN_BUFFER_ZOOM_OUT:
3397 if (cmd.argument().empty()) {
3398 if (cmd.action() == LFUN_BUFFER_ZOOM_IN)
3403 lyxrc.zoom += convert<int>(cmd.argument());
3405 if (lyxrc.zoom < 10)
3408 // The global QPixmapCache is used in GuiPainter to cache text
3409 // painting so we must reset it.
3410 QPixmapCache::clear();
3411 guiApp->fontLoader().update();
3412 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
3415 case LFUN_VC_REGISTER:
3416 case LFUN_VC_CHECK_IN:
3417 case LFUN_VC_CHECK_OUT:
3418 case LFUN_VC_REPO_UPDATE:
3419 case LFUN_VC_LOCKING_TOGGLE:
3420 case LFUN_VC_REVERT:
3421 case LFUN_VC_UNDO_LAST:
3422 case LFUN_VC_COMMAND:
3423 case LFUN_VC_COMPARE:
3424 dispatchVC(cmd, dr);
3427 case LFUN_SERVER_GOTO_FILE_ROW:
3428 goToFileRow(to_utf8(cmd.argument()));
3431 case LFUN_FORWARD_SEARCH: {
3432 FileName const path(doc_buffer->temppath());
3433 string const texname = doc_buffer->latexName();
3434 FileName const dviname(addName(path.absFileName(),
3435 support::changeExtension(texname, "dvi")));
3436 FileName const pdfname(addName(path.absFileName(),
3437 support::changeExtension(texname, "pdf")));
3438 if (!dviname.exists() && !pdfname.exists()) {
3439 dr.setMessage(_("Please, preview the document first."));
3442 string outname = dviname.onlyFileName();
3443 string command = lyxrc.forward_search_dvi;
3444 if (!dviname.exists() ||
3445 pdfname.lastModified() > dviname.lastModified()) {
3446 outname = pdfname.onlyFileName();
3447 command = lyxrc.forward_search_pdf;
3450 int row = doc_buffer->texrow().getRowFromIdPos(bv->cursor().paragraph().id(), bv->cursor().pos());
3451 LYXERR(Debug::ACTION, "Forward search: row:" << row
3452 << " id:" << bv->cursor().paragraph().id());
3453 if (!row || command.empty()) {
3454 dr.setMessage(_("Couldn't proceed."));
3457 string texrow = convert<string>(row);
3459 command = subst(command, "$$n", texrow);
3460 command = subst(command, "$$t", texname);
3461 command = subst(command, "$$o", outname);
3463 PathChanger p(path);
3465 one.startscript(Systemcall::DontWait, command);
3469 dr.dispatched(false);
3473 // Part of automatic menu appearance feature.
3474 if (isFullScreen()) {
3475 if (menuBar()->isVisible() && lyxrc.full_screen_menubar)
3477 if (statusBar()->isVisible())
3478 statusBar()->hide();
3485 bool GuiView::lfunUiToggle(string const & ui_component)
3487 if (ui_component == "scrollbar") {
3488 // hide() is of no help
3489 if (d.current_work_area_->verticalScrollBarPolicy() ==
3490 Qt::ScrollBarAlwaysOff)
3492 d.current_work_area_->setVerticalScrollBarPolicy(
3493 Qt::ScrollBarAsNeeded);
3495 d.current_work_area_->setVerticalScrollBarPolicy(
3496 Qt::ScrollBarAlwaysOff);
3497 } else if (ui_component == "statusbar") {
3498 statusBar()->setVisible(!statusBar()->isVisible());
3499 } else if (ui_component == "menubar") {
3500 menuBar()->setVisible(!menuBar()->isVisible());
3502 #if QT_VERSION >= 0x040300
3503 if (ui_component == "frame") {
3505 getContentsMargins(&l, &t, &r, &b);
3506 //are the frames in default state?
3507 d.current_work_area_->setFrameStyle(QFrame::NoFrame);
3509 setContentsMargins(-2, -2, -2, -2);
3511 setContentsMargins(0, 0, 0, 0);
3515 if (ui_component == "fullscreen") {
3523 void GuiView::toggleFullScreen()
3525 if (isFullScreen()) {
3526 for (int i = 0; i != d.splitter_->count(); ++i)
3527 d.tabWorkArea(i)->setFullScreen(false);
3528 #if QT_VERSION >= 0x040300
3529 setContentsMargins(0, 0, 0, 0);
3531 setWindowState(windowState() ^ Qt::WindowFullScreen);
3534 statusBar()->show();
3537 hideDialogs("prefs", 0);
3538 for (int i = 0; i != d.splitter_->count(); ++i)
3539 d.tabWorkArea(i)->setFullScreen(true);
3540 #if QT_VERSION >= 0x040300
3541 setContentsMargins(-2, -2, -2, -2);
3544 setWindowState(windowState() ^ Qt::WindowFullScreen);
3545 statusBar()->hide();
3546 if (lyxrc.full_screen_menubar)
3548 if (lyxrc.full_screen_toolbars) {
3549 ToolbarMap::iterator end = d.toolbars_.end();
3550 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
3555 // give dialogs like the TOC a chance to adapt
3560 Buffer const * GuiView::updateInset(Inset const * inset)
3565 Buffer const * inset_buffer = &(inset->buffer());
3567 for (int i = 0; i != d.splitter_->count(); ++i) {
3568 GuiWorkArea * wa = d.tabWorkArea(i)->currentWorkArea();
3571 Buffer const * buffer = &(wa->bufferView().buffer());
3572 if (inset_buffer == buffer)
3573 wa->scheduleRedraw();
3575 return inset_buffer;
3579 void GuiView::restartCursor()
3581 /* When we move around, or type, it's nice to be able to see
3582 * the cursor immediately after the keypress.
3584 if (d.current_work_area_)
3585 d.current_work_area_->startBlinkingCursor();
3587 // Take this occasion to update the other GUI elements.
3593 void GuiView::updateCompletion(Cursor & cur, bool start, bool keep)
3595 if (d.current_work_area_)
3596 d.current_work_area_->completer().updateVisibility(cur, start, keep);
3601 // This list should be kept in sync with the list of insets in
3602 // src/insets/Inset.cpp. I.e., if a dialog goes with an inset, the
3603 // dialog should have the same name as the inset.
3604 // Changes should be also recorded in LFUN_DIALOG_SHOW doxygen
3605 // docs in LyXAction.cpp.
3607 char const * const dialognames[] = {
3609 "aboutlyx", "bibitem", "bibtex", "box", "branch", "changes", "character",
3610 "citation", "compare", "comparehistory", "document", "errorlist", "ert",
3611 "external", "file", "findreplace", "findreplaceadv", "float", "graphics",
3612 "href", "include", "index", "index_print", "info", "listings", "label", "line",
3613 "log", "mathdelimiter", "mathmatrix", "mathspace", "nomenclature",
3614 "nomencl_print", "note", "paragraph", "phantom", "prefs", "print", "ref",
3615 "sendto", "space", "spellchecker", "symbols", "tabular", "tabularcreate",
3616 "thesaurus", "texinfo", "toc", "view-source", "vspace", "wrap", "progress"};
3618 char const * const * const end_dialognames =
3619 dialognames + (sizeof(dialognames) / sizeof(char *));
3623 cmpCStr(char const * name) : name_(name) {}
3624 bool operator()(char const * other) {
3625 return strcmp(other, name_) == 0;
3632 bool isValidName(string const & name)
3634 return find_if(dialognames, end_dialognames,
3635 cmpCStr(name.c_str())) != end_dialognames;
3641 void GuiView::resetDialogs()
3643 // Make sure that no LFUN uses any GuiView.
3644 guiApp->setCurrentView(0);
3647 constructToolbars();
3648 guiApp->menus().fillMenuBar(menuBar(), this, false);
3649 d.layout_->updateContents(true);
3650 // Now update controls with current buffer.
3651 guiApp->setCurrentView(this);
3657 Dialog * GuiView::findOrBuild(string const & name, bool hide_it)
3659 if (!isValidName(name))
3662 map<string, DialogPtr>::iterator it = d.dialogs_.find(name);
3664 if (it != d.dialogs_.end()) {
3666 it->second->hideView();
3667 return it->second.get();
3670 Dialog * dialog = build(name);
3671 d.dialogs_[name].reset(dialog);
3672 if (lyxrc.allow_geometry_session)
3673 dialog->restoreSession();
3680 void GuiView::showDialog(string const & name, string const & data,
3683 triggerShowDialog(toqstr(name), toqstr(data), inset);
3687 void GuiView::doShowDialog(QString const & qname, QString const & qdata,
3693 const string name = fromqstr(qname);
3694 const string data = fromqstr(qdata);
3698 Dialog * dialog = findOrBuild(name, false);
3700 bool const visible = dialog->isVisibleView();
3701 dialog->showData(data);
3702 if (inset && currentBufferView())
3703 currentBufferView()->editInset(name, inset);
3704 // We only set the focus to the new dialog if it was not yet
3705 // visible in order not to change the existing previous behaviour
3707 // activateWindow is needed for floating dockviews
3708 dialog->asQWidget()->raise();
3709 dialog->asQWidget()->activateWindow();
3710 dialog->asQWidget()->setFocus();
3714 catch (ExceptionMessage const & ex) {
3722 bool GuiView::isDialogVisible(string const & name) const
3724 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3725 if (it == d.dialogs_.end())
3727 return it->second.get()->isVisibleView() && !it->second.get()->isClosing();
3731 void GuiView::hideDialog(string const & name, Inset * inset)
3733 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3734 if (it == d.dialogs_.end())
3737 if (inset && currentBufferView()
3738 && inset != currentBufferView()->editedInset(name))
3741 Dialog * const dialog = it->second.get();
3742 if (dialog->isVisibleView())
3744 if (currentBufferView())
3745 currentBufferView()->editInset(name, 0);
3749 void GuiView::disconnectDialog(string const & name)
3751 if (!isValidName(name))
3753 if (currentBufferView())
3754 currentBufferView()->editInset(name, 0);
3758 void GuiView::hideAll() const
3760 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
3761 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3763 for(; it != end; ++it)
3764 it->second->hideView();
3768 void GuiView::updateDialogs()
3770 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
3771 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3773 for(; it != end; ++it) {
3774 Dialog * dialog = it->second.get();
3776 if (dialog->needBufferOpen() && !documentBufferView())
3777 hideDialog(fromqstr(dialog->name()), 0);
3778 else if (dialog->isVisibleView())
3779 dialog->checkStatus();
3786 Dialog * createDialog(GuiView & lv, string const & name);
3788 // will be replaced by a proper factory...
3789 Dialog * createGuiAbout(GuiView & lv);
3790 Dialog * createGuiBibtex(GuiView & lv);
3791 Dialog * createGuiChanges(GuiView & lv);
3792 Dialog * createGuiCharacter(GuiView & lv);
3793 Dialog * createGuiCitation(GuiView & lv);
3794 Dialog * createGuiCompare(GuiView & lv);
3795 Dialog * createGuiCompareHistory(GuiView & lv);
3796 Dialog * createGuiDelimiter(GuiView & lv);
3797 Dialog * createGuiDocument(GuiView & lv);
3798 Dialog * createGuiErrorList(GuiView & lv);
3799 Dialog * createGuiExternal(GuiView & lv);
3800 Dialog * createGuiGraphics(GuiView & lv);
3801 Dialog * createGuiInclude(GuiView & lv);
3802 Dialog * createGuiIndex(GuiView & lv);
3803 Dialog * createGuiListings(GuiView & lv);
3804 Dialog * createGuiLog(GuiView & lv);
3805 Dialog * createGuiMathMatrix(GuiView & lv);
3806 Dialog * createGuiNote(GuiView & lv);
3807 Dialog * createGuiParagraph(GuiView & lv);
3808 Dialog * createGuiPhantom(GuiView & lv);
3809 Dialog * createGuiPreferences(GuiView & lv);
3810 Dialog * createGuiPrint(GuiView & lv);
3811 Dialog * createGuiPrintindex(GuiView & lv);
3812 Dialog * createGuiRef(GuiView & lv);
3813 Dialog * createGuiSearch(GuiView & lv);
3814 Dialog * createGuiSearchAdv(GuiView & lv);
3815 Dialog * createGuiSendTo(GuiView & lv);
3816 Dialog * createGuiShowFile(GuiView & lv);
3817 Dialog * createGuiSpellchecker(GuiView & lv);
3818 Dialog * createGuiSymbols(GuiView & lv);
3819 Dialog * createGuiTabularCreate(GuiView & lv);
3820 Dialog * createGuiTexInfo(GuiView & lv);
3821 Dialog * createGuiToc(GuiView & lv);
3822 Dialog * createGuiThesaurus(GuiView & lv);
3823 Dialog * createGuiViewSource(GuiView & lv);
3824 Dialog * createGuiWrap(GuiView & lv);
3825 Dialog * createGuiProgressView(GuiView & lv);
3829 Dialog * GuiView::build(string const & name)
3831 LASSERT(isValidName(name), return 0);
3833 Dialog * dialog = createDialog(*this, name);
3837 if (name == "aboutlyx")
3838 return createGuiAbout(*this);
3839 if (name == "bibtex")
3840 return createGuiBibtex(*this);
3841 if (name == "changes")
3842 return createGuiChanges(*this);
3843 if (name == "character")
3844 return createGuiCharacter(*this);
3845 if (name == "citation")
3846 return createGuiCitation(*this);
3847 if (name == "compare")
3848 return createGuiCompare(*this);
3849 if (name == "comparehistory")
3850 return createGuiCompareHistory(*this);
3851 if (name == "document")
3852 return createGuiDocument(*this);
3853 if (name == "errorlist")
3854 return createGuiErrorList(*this);
3855 if (name == "external")
3856 return createGuiExternal(*this);
3858 return createGuiShowFile(*this);
3859 if (name == "findreplace")
3860 return createGuiSearch(*this);
3861 if (name == "findreplaceadv")
3862 return createGuiSearchAdv(*this);
3863 if (name == "graphics")
3864 return createGuiGraphics(*this);
3865 if (name == "include")
3866 return createGuiInclude(*this);
3867 if (name == "index")
3868 return createGuiIndex(*this);
3869 if (name == "index_print")
3870 return createGuiPrintindex(*this);
3871 if (name == "listings")
3872 return createGuiListings(*this);
3874 return createGuiLog(*this);
3875 if (name == "mathdelimiter")
3876 return createGuiDelimiter(*this);
3877 if (name == "mathmatrix")
3878 return createGuiMathMatrix(*this);
3880 return createGuiNote(*this);
3881 if (name == "paragraph")
3882 return createGuiParagraph(*this);
3883 if (name == "phantom")
3884 return createGuiPhantom(*this);
3885 if (name == "prefs")
3886 return createGuiPreferences(*this);
3887 if (name == "print")
3888 return createGuiPrint(*this);
3890 return createGuiRef(*this);
3891 if (name == "sendto")
3892 return createGuiSendTo(*this);
3893 if (name == "spellchecker")
3894 return createGuiSpellchecker(*this);
3895 if (name == "symbols")
3896 return createGuiSymbols(*this);
3897 if (name == "tabularcreate")
3898 return createGuiTabularCreate(*this);
3899 if (name == "texinfo")
3900 return createGuiTexInfo(*this);
3901 if (name == "thesaurus")
3902 return createGuiThesaurus(*this);
3904 return createGuiToc(*this);
3905 if (name == "view-source")
3906 return createGuiViewSource(*this);
3908 return createGuiWrap(*this);
3909 if (name == "progress")
3910 return createGuiProgressView(*this);
3916 } // namespace frontend
3919 #include "moc_GuiView.cpp"