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(autoSaveThreadFinished()));
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(bool show_errors)
553 QFutureWatcher<docstring> const * watcher =
554 static_cast<QFutureWatcher<docstring> const *>(sender());
555 message(watcher->result());
558 errors(d.last_export_format);
560 d.processing_cursor_timer_.stop();
561 restoreCursorShapes();
562 d.indicates_processing_ = false;
565 void GuiView::processingThreadFinished()
567 processingThreadFinished(true);
570 void GuiView::autoSaveThreadFinished()
572 processingThreadFinished(false);
577 void GuiView::setCursorShapes(Qt::CursorShape)
582 void GuiView::restoreCursorShapes()
587 void GuiView::saveCursorShapes()
592 void GuiView::indicateProcessing()
597 void GuiView::processingThreadStarted()
602 void GuiView::processingThreadFinished(bool)
607 void GuiView::processingThreadFinished()
612 void GuiView::autoSaveThreadFinished()
618 void GuiView::saveLayout() const
621 settings.beginGroup("views");
622 settings.beginGroup(QString::number(id_));
624 settings.setValue("pos", pos());
625 settings.setValue("size", size());
627 settings.setValue("geometry", saveGeometry());
629 settings.setValue("layout", saveState(0));
630 settings.setValue("icon_size", iconSize());
634 bool GuiView::restoreLayout()
637 settings.beginGroup("views");
638 settings.beginGroup(QString::number(id_));
639 QString const icon_key = "icon_size";
640 if (!settings.contains(icon_key))
643 //code below is skipped when when ~/.config/LyX is (re)created
644 setIconSize(settings.value(icon_key).toSize());
646 QPoint pos = settings.value("pos", QPoint(50, 50)).toPoint();
647 QSize size = settings.value("size", QSize(690, 510)).toSize();
651 // Work-around for bug #6034: the window ends up in an undetermined
652 // state when trying to restore a maximized window when it is
653 // already maximized.
654 if (!(windowState() & Qt::WindowMaximized))
655 if (!restoreGeometry(settings.value("geometry").toByteArray()))
656 setGeometry(50, 50, 690, 510);
658 // Make sure layout is correctly oriented.
659 setLayoutDirection(qApp->layoutDirection());
661 // Allow the toc and view-source dock widget to be restored if needed.
663 if ((dialog = findOrBuild("toc", true)))
664 // see bug 5082. At least setup title and enabled state.
665 // Visibility will be adjusted by restoreState below.
666 dialog->prepareView();
667 if ((dialog = findOrBuild("view-source", true)))
668 dialog->prepareView();
669 if ((dialog = findOrBuild("progress", true)))
670 dialog->prepareView();
672 if (!restoreState(settings.value("layout").toByteArray(), 0))
679 GuiToolbar * GuiView::toolbar(string const & name)
681 ToolbarMap::iterator it = d.toolbars_.find(name);
682 if (it != d.toolbars_.end())
685 LYXERR(Debug::GUI, "Toolbar::display: no toolbar named " << name);
690 void GuiView::constructToolbars()
692 ToolbarMap::iterator it = d.toolbars_.begin();
693 for (; it != d.toolbars_.end(); ++it)
697 // I don't like doing this here, but the standard toolbar
698 // destroys this object when it's destroyed itself (vfr)
699 d.layout_ = new LayoutBox(*this);
700 d.stack_widget_->addWidget(d.layout_);
701 d.layout_->move(0,0);
703 // extracts the toolbars from the backend
704 Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
705 Toolbars::Infos::iterator end = guiApp->toolbars().end();
706 for (; cit != end; ++cit)
707 d.toolbars_[cit->name] = new GuiToolbar(*cit, *this);
711 void GuiView::initToolbars()
713 // extracts the toolbars from the backend
714 Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
715 Toolbars::Infos::iterator end = guiApp->toolbars().end();
716 for (; cit != end; ++cit) {
717 GuiToolbar * tb = toolbar(cit->name);
720 int const visibility = guiApp->toolbars().defaultVisibility(cit->name);
721 bool newline = !(visibility & Toolbars::SAMEROW);
722 tb->setVisible(false);
723 tb->setVisibility(visibility);
725 if (visibility & Toolbars::TOP) {
727 addToolBarBreak(Qt::TopToolBarArea);
728 addToolBar(Qt::TopToolBarArea, tb);
731 if (visibility & Toolbars::BOTTOM) {
732 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
733 #if (QT_VERSION >= 0x040202)
735 addToolBarBreak(Qt::BottomToolBarArea);
737 addToolBar(Qt::BottomToolBarArea, tb);
740 if (visibility & Toolbars::LEFT) {
741 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
742 #if (QT_VERSION >= 0x040202)
744 addToolBarBreak(Qt::LeftToolBarArea);
746 addToolBar(Qt::LeftToolBarArea, tb);
749 if (visibility & Toolbars::RIGHT) {
750 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
751 #if (QT_VERSION >= 0x040202)
753 addToolBarBreak(Qt::RightToolBarArea);
755 addToolBar(Qt::RightToolBarArea, tb);
758 if (visibility & Toolbars::ON)
759 tb->setVisible(true);
764 TocModels & GuiView::tocModels()
766 return d.toc_models_;
770 void GuiView::setFocus()
772 LYXERR(Debug::DEBUG, "GuiView::setFocus()" << this);
773 QMainWindow::setFocus();
777 void GuiView::focusInEvent(QFocusEvent * e)
779 LYXERR(Debug::DEBUG, "GuiView::focusInEvent()" << this);
780 QMainWindow::focusInEvent(e);
781 // Make sure guiApp points to the correct view.
782 guiApp->setCurrentView(this);
783 if (currentMainWorkArea())
784 currentMainWorkArea()->setFocus();
785 else if (currentWorkArea())
786 currentWorkArea()->setFocus();
788 d.bg_widget_->setFocus();
792 QMenu * GuiView::createPopupMenu()
794 return d.toolBarPopup(this);
798 void GuiView::showEvent(QShowEvent * e)
800 LYXERR(Debug::GUI, "Passed Geometry "
801 << size().height() << "x" << size().width()
802 << "+" << pos().x() << "+" << pos().y());
804 if (d.splitter_->count() == 0)
805 // No work area, switch to the background widget.
808 QMainWindow::showEvent(e);
812 bool GuiView::closeScheduled()
819 /** Destroy only all tabbed WorkAreas. Destruction of other WorkAreas
820 ** is responsibility of the container (e.g., dialog)
822 void GuiView::closeEvent(QCloseEvent * close_event)
824 LYXERR(Debug::DEBUG, "GuiView::closeEvent()");
826 if (!GuiViewPrivate::busyBuffers.isEmpty()) {
827 Alert::warning(_("Exit LyX"),
828 _("LyX could not be closed because documents are being processed by LyX."));
829 close_event->setAccepted(false);
833 // If the user pressed the x (so we didn't call closeView
834 // programmatically), we want to clear all existing entries.
836 theSession().lastOpened().clear();
841 // it can happen that this event arrives without selecting the view,
842 // e.g. when clicking the close button on a background window.
844 if (!closeWorkAreaAll()) {
846 close_event->ignore();
850 // Make sure that nothing will use this to be closed View.
851 guiApp->unregisterView(this);
853 if (isFullScreen()) {
854 // Switch off fullscreen before closing.
859 // Make sure the timer time out will not trigger a statusbar update.
860 d.statusbar_timer_.stop();
862 // Saving fullscreen requires additional tweaks in the toolbar code.
863 // It wouldn't also work under linux natively.
864 if (lyxrc.allow_geometry_session) {
865 // Save this window geometry and layout.
867 // Then the toolbar private states.
868 ToolbarMap::iterator end = d.toolbars_.end();
869 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
870 it->second->saveSession();
871 // Now take care of all other dialogs:
872 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
873 for (; it!= d.dialogs_.end(); ++it)
874 it->second->saveSession();
877 close_event->accept();
881 void GuiView::dragEnterEvent(QDragEnterEvent * event)
883 if (event->mimeData()->hasUrls())
885 /// \todo Ask lyx-devel is this is enough:
886 /// if (event->mimeData()->hasFormat("text/plain"))
887 /// event->acceptProposedAction();
891 void GuiView::dropEvent(QDropEvent * event)
893 QList<QUrl> files = event->mimeData()->urls();
897 LYXERR(Debug::GUI, "GuiView::dropEvent: got URLs!");
898 for (int i = 0; i != files.size(); ++i) {
899 string const file = os::internal_path(fromqstr(
900 files.at(i).toLocalFile()));
904 string const ext = support::getExtension(file);
905 vector<const Format *> found_formats;
907 // Find all formats that have the correct extension.
908 vector<const Format *> const & import_formats
909 = theConverters().importableFormats();
910 vector<const Format *>::const_iterator it = import_formats.begin();
911 for (; it != import_formats.end(); ++it)
912 if ((*it)->extension() == ext)
913 found_formats.push_back(*it);
916 if (found_formats.size() >= 1) {
917 if (found_formats.size() > 1) {
918 //FIXME: show a dialog to choose the correct importable format
920 "Multiple importable formats found, selecting first");
922 string const arg = found_formats[0]->name() + " " + file;
923 cmd = FuncRequest(LFUN_BUFFER_IMPORT, arg);
926 //FIXME: do we have to explicitly check whether it's a lyx file?
928 "No formats found, trying to open it as a lyx file");
929 cmd = FuncRequest(LFUN_FILE_OPEN, file);
931 // add the functions to the queue
932 guiApp->addToFuncRequestQueue(cmd);
935 // now process the collected functions. We perform the events
936 // asynchronously. This prevents potential problems in case the
937 // BufferView is closed within an event.
938 guiApp->processFuncRequestQueueAsync();
942 void GuiView::message(docstring const & str)
944 if (ForkedProcess::iAmAChild())
947 // call is moved to GUI-thread by GuiProgress
948 d.progress_->appendMessage(toqstr(str));
952 void GuiView::clearMessageText()
954 message(docstring());
958 void GuiView::updateStatusBarMessage(QString const & str)
960 statusBar()->showMessage(str);
961 d.statusbar_timer_.stop();
962 d.statusbar_timer_.start(3000);
966 void GuiView::smallSizedIcons()
968 setIconSize(QSize(d.smallIconSize, d.smallIconSize));
972 void GuiView::normalSizedIcons()
974 setIconSize(QSize(d.normalIconSize, d.normalIconSize));
978 void GuiView::bigSizedIcons()
980 setIconSize(QSize(d.bigIconSize, d.bigIconSize));
984 void GuiView::clearMessage()
986 // FIXME: This code was introduced in r19643 to fix bug #4123. However,
987 // the hasFocus function mostly returns false, even if the focus is on
988 // a workarea in this view.
992 d.statusbar_timer_.stop();
996 void GuiView::updateWindowTitle(GuiWorkArea * wa)
998 if (wa != d.current_work_area_
999 || wa->bufferView().buffer().isInternal())
1001 setWindowTitle(qt_("LyX: ") + wa->windowTitle());
1002 setWindowIconText(wa->windowIconText());
1006 void GuiView::on_currentWorkAreaChanged(GuiWorkArea * wa)
1009 disconnectBufferView();
1010 connectBufferView(wa->bufferView());
1011 connectBuffer(wa->bufferView().buffer());
1012 d.current_work_area_ = wa;
1013 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
1014 this, SLOT(updateWindowTitle(GuiWorkArea *)));
1015 updateWindowTitle(wa);
1019 // The document settings needs to be reinitialised.
1020 updateDialog("document", "");
1022 // Buffer-dependent dialogs must be updated. This is done here because
1023 // some dialogs require buffer()->text.
1028 void GuiView::on_lastWorkAreaRemoved()
1031 // We already are in a close event. Nothing more to do.
1034 if (d.splitter_->count() > 1)
1035 // We have a splitter so don't close anything.
1038 // Reset and updates the dialogs.
1039 d.toc_models_.reset(0);
1040 updateDialog("document", "");
1043 resetWindowTitleAndIconText();
1046 if (lyxrc.open_buffers_in_tabs)
1047 // Nothing more to do, the window should stay open.
1050 if (guiApp->viewIds().size() > 1) {
1056 // On Mac we also close the last window because the application stay
1057 // resident in memory. On other platforms we don't close the last
1058 // window because this would quit the application.
1064 void GuiView::updateStatusBar()
1066 // let the user see the explicit message
1067 if (d.statusbar_timer_.isActive())
1074 void GuiView::showMessage()
1076 QString msg = toqstr(theGuiApp()->viewStatusMessage());
1077 if (msg.isEmpty()) {
1078 BufferView const * bv = currentBufferView();
1080 msg = toqstr(bv->cursor().currentState());
1082 msg = qt_("Welcome to LyX!");
1084 statusBar()->showMessage(msg);
1088 bool GuiView::event(QEvent * e)
1092 // Useful debug code:
1093 //case QEvent::ActivationChange:
1094 //case QEvent::WindowDeactivate:
1095 //case QEvent::Paint:
1096 //case QEvent::Enter:
1097 //case QEvent::Leave:
1098 //case QEvent::HoverEnter:
1099 //case QEvent::HoverLeave:
1100 //case QEvent::HoverMove:
1101 //case QEvent::StatusTip:
1102 //case QEvent::DragEnter:
1103 //case QEvent::DragLeave:
1104 //case QEvent::Drop:
1107 case QEvent::WindowActivate: {
1108 GuiView * old_view = guiApp->currentView();
1109 if (this == old_view) {
1111 return QMainWindow::event(e);
1113 if (old_view && old_view->currentBufferView()) {
1114 // save current selection to the selection buffer to allow
1115 // middle-button paste in this window.
1116 cap::saveSelection(old_view->currentBufferView()->cursor());
1118 guiApp->setCurrentView(this);
1119 if (d.current_work_area_) {
1120 BufferView & bv = d.current_work_area_->bufferView();
1121 connectBufferView(bv);
1122 connectBuffer(bv.buffer());
1123 // The document structure, name and dialogs might have
1124 // changed in another view.
1126 // The document settings needs to be reinitialised.
1127 updateDialog("document", "");
1130 resetWindowTitleAndIconText();
1133 return QMainWindow::event(e);
1136 case QEvent::ShortcutOverride: {
1139 #if (!defined Q_WS_X11) || (QT_VERSION >= 0x040500)
1140 if (isFullScreen() && menuBar()->isHidden()) {
1141 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
1142 // FIXME: we should also try to detect special LyX shortcut such as
1143 // Alt-P and Alt-M. Right now there is a hack in
1144 // GuiWorkArea::processKeySym() that hides again the menubar for
1146 if (ke->modifiers() & Qt::AltModifier && ke->key() != Qt::Key_Alt) {
1148 return QMainWindow::event(e);
1152 return QMainWindow::event(e);
1156 return QMainWindow::event(e);
1160 void GuiView::resetWindowTitleAndIconText()
1162 setWindowTitle(qt_("LyX"));
1163 setWindowIconText(qt_("LyX"));
1166 bool GuiView::focusNextPrevChild(bool /*next*/)
1173 bool GuiView::busy() const
1179 void GuiView::setBusy(bool busy)
1181 bool const busy_before = busy_ > 0;
1182 busy ? ++busy_ : --busy_;
1183 if ((busy_ > 0) == busy_before)
1184 // busy state didn't change
1187 if (d.current_work_area_) {
1188 d.current_work_area_->setUpdatesEnabled(!busy);
1190 d.current_work_area_->stopBlinkingCursor();
1192 d.current_work_area_->startBlinkingCursor();
1196 QApplication::setOverrideCursor(Qt::WaitCursor);
1198 QApplication::restoreOverrideCursor();
1202 GuiWorkArea * GuiView::workArea(int index)
1204 if (TabWorkArea * twa = d.currentTabWorkArea())
1205 if (index < twa->count())
1206 return dynamic_cast<GuiWorkArea *>(twa->widget(index));
1211 GuiWorkArea * GuiView::workArea(Buffer & buffer)
1213 if (currentWorkArea()
1214 && ¤tWorkArea()->bufferView().buffer() == &buffer)
1215 return (GuiWorkArea *) currentWorkArea();
1216 if (TabWorkArea * twa = d.currentTabWorkArea())
1217 return twa->workArea(buffer);
1222 GuiWorkArea * GuiView::addWorkArea(Buffer & buffer)
1224 // Automatically create a TabWorkArea if there are none yet.
1225 TabWorkArea * tab_widget = d.splitter_->count()
1226 ? d.currentTabWorkArea() : addTabWorkArea();
1227 return tab_widget->addWorkArea(buffer, *this);
1231 TabWorkArea * GuiView::addTabWorkArea()
1233 TabWorkArea * twa = new TabWorkArea;
1234 QObject::connect(twa, SIGNAL(currentWorkAreaChanged(GuiWorkArea *)),
1235 this, SLOT(on_currentWorkAreaChanged(GuiWorkArea *)));
1236 QObject::connect(twa, SIGNAL(lastWorkAreaRemoved()),
1237 this, SLOT(on_lastWorkAreaRemoved()));
1239 d.splitter_->addWidget(twa);
1240 d.stack_widget_->setCurrentWidget(d.splitter_);
1245 GuiWorkArea const * GuiView::currentWorkArea() const
1247 return d.current_work_area_;
1251 GuiWorkArea * GuiView::currentWorkArea()
1253 return d.current_work_area_;
1257 GuiWorkArea const * GuiView::currentMainWorkArea() const
1259 if (!d.currentTabWorkArea())
1261 return d.currentTabWorkArea()->currentWorkArea();
1265 GuiWorkArea * GuiView::currentMainWorkArea()
1267 if (!d.currentTabWorkArea())
1269 return d.currentTabWorkArea()->currentWorkArea();
1273 void GuiView::setCurrentWorkArea(GuiWorkArea * wa)
1275 LYXERR(Debug::DEBUG, "Setting current wa: " << wa << endl);
1277 d.current_work_area_ = 0;
1282 // FIXME: I've no clue why this is here and why it accesses
1283 // theGuiApp()->currentView, which might be 0 (bug 6464).
1284 // See also 27525 (vfr).
1285 if (theGuiApp()->currentView() == this
1286 && theGuiApp()->currentView()->currentWorkArea() == wa)
1289 if (currentBufferView())
1290 cap::saveSelection(currentBufferView()->cursor());
1292 theGuiApp()->setCurrentView(this);
1293 d.current_work_area_ = wa;
1295 // We need to reset this now, because it will need to be
1296 // right if the tabWorkArea gets reset in the for loop. We
1297 // will change it back if we aren't in that case.
1298 GuiWorkArea * const old_cmwa = d.current_main_work_area_;
1299 d.current_main_work_area_ = wa;
1301 for (int i = 0; i != d.splitter_->count(); ++i) {
1302 if (d.tabWorkArea(i)->setCurrentWorkArea(wa)) {
1303 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea()
1304 << ", Current main wa: " << currentMainWorkArea());
1309 d.current_main_work_area_ = old_cmwa;
1311 LYXERR(Debug::DEBUG, "This is not a tabbed wa");
1312 on_currentWorkAreaChanged(wa);
1313 BufferView & bv = wa->bufferView();
1314 bv.cursor().fixIfBroken();
1316 wa->setUpdatesEnabled(true);
1317 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() << ", Current main wa: " << currentMainWorkArea());
1321 void GuiView::removeWorkArea(GuiWorkArea * wa)
1323 LASSERT(wa, return);
1324 if (wa == d.current_work_area_) {
1326 disconnectBufferView();
1327 d.current_work_area_ = 0;
1328 d.current_main_work_area_ = 0;
1331 bool found_twa = false;
1332 for (int i = 0; i != d.splitter_->count(); ++i) {
1333 TabWorkArea * twa = d.tabWorkArea(i);
1334 if (twa->removeWorkArea(wa)) {
1335 // Found in this tab group, and deleted the GuiWorkArea.
1337 if (twa->count() != 0) {
1338 if (d.current_work_area_ == 0)
1339 // This means that we are closing the current GuiWorkArea, so
1340 // switch to the next GuiWorkArea in the found TabWorkArea.
1341 setCurrentWorkArea(twa->currentWorkArea());
1343 // No more WorkAreas in this tab group, so delete it.
1350 // It is not a tabbed work area (i.e., the search work area), so it
1351 // should be deleted by other means.
1352 LASSERT(found_twa, /* */);
1354 if (d.current_work_area_ == 0) {
1355 if (d.splitter_->count() != 0) {
1356 TabWorkArea * twa = d.currentTabWorkArea();
1357 setCurrentWorkArea(twa->currentWorkArea());
1359 // No more work areas, switch to the background widget.
1360 setCurrentWorkArea(0);
1366 LayoutBox * GuiView::getLayoutDialog() const
1372 void GuiView::updateLayoutList()
1375 d.layout_->updateContents(false);
1379 void GuiView::updateToolbars()
1381 ToolbarMap::iterator end = d.toolbars_.end();
1382 if (d.current_work_area_) {
1384 d.current_work_area_->bufferView().cursor().inMathed()
1385 && !d.current_work_area_->bufferView().cursor().inRegexped();
1387 lyx::getStatus(FuncRequest(LFUN_LAYOUT_TABULAR)).enabled();
1389 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).enabled() &&
1390 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).onOff(true);
1391 bool const mathmacrotemplate =
1392 lyx::getStatus(FuncRequest(LFUN_IN_MATHMACROTEMPLATE)).enabled();
1394 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1395 it->second->update(math, table, review, mathmacrotemplate);
1397 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1398 it->second->update(false, false, false, false);
1402 void GuiView::setBuffer(Buffer * newBuffer)
1404 LYXERR(Debug::DEBUG, "Setting buffer: " << newBuffer << endl);
1405 LASSERT(newBuffer, return);
1408 GuiWorkArea * wa = workArea(*newBuffer);
1410 newBuffer->masterBuffer()->updateBuffer();
1411 wa = addWorkArea(*newBuffer);
1412 // scroll to the position when the BufferView was last closed
1413 if (lyxrc.use_lastfilepos) {
1414 LastFilePosSection::FilePos filepos =
1415 theSession().lastFilePos().load(newBuffer->fileName());
1416 wa->bufferView().moveToPosition(filepos.pit, filepos.pos, 0, 0);
1419 //Disconnect the old buffer...there's no new one.
1422 connectBuffer(*newBuffer);
1423 connectBufferView(wa->bufferView());
1424 setCurrentWorkArea(wa);
1430 void GuiView::connectBuffer(Buffer & buf)
1432 buf.setGuiDelegate(this);
1436 void GuiView::disconnectBuffer()
1438 if (d.current_work_area_)
1439 d.current_work_area_->bufferView().buffer().setGuiDelegate(0);
1443 void GuiView::connectBufferView(BufferView & bv)
1445 bv.setGuiDelegate(this);
1449 void GuiView::disconnectBufferView()
1451 if (d.current_work_area_)
1452 d.current_work_area_->bufferView().setGuiDelegate(0);
1456 void GuiView::errors(string const & error_type, bool from_master)
1458 BufferView const * const bv = currentBufferView();
1462 ErrorList & el = from_master ?
1463 bv->buffer().masterBuffer()->errorList(error_type) :
1464 bv->buffer().errorList(error_type);
1468 string data = error_type;
1470 data = "from_master|" + error_type;
1471 showDialog("errorlist", data);
1475 void GuiView::updateTocItem(string const & type, DocIterator const & dit)
1477 d.toc_models_.updateItem(toqstr(type), dit);
1481 void GuiView::structureChanged()
1483 d.toc_models_.reset(documentBufferView());
1484 // Navigator needs more than a simple update in this case. It needs to be
1486 updateDialog("toc", "");
1490 void GuiView::updateDialog(string const & name, string const & data)
1492 if (!isDialogVisible(name))
1495 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
1496 if (it == d.dialogs_.end())
1499 Dialog * const dialog = it->second.get();
1500 if (dialog->isVisibleView())
1501 dialog->initialiseParams(data);
1505 BufferView * GuiView::documentBufferView()
1507 return currentMainWorkArea()
1508 ? ¤tMainWorkArea()->bufferView()
1513 BufferView const * GuiView::documentBufferView() const
1515 return currentMainWorkArea()
1516 ? ¤tMainWorkArea()->bufferView()
1521 BufferView * GuiView::currentBufferView()
1523 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1527 BufferView const * GuiView::currentBufferView() const
1529 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1533 #if (QT_VERSION >= 0x040400)
1534 docstring GuiView::GuiViewPrivate::autosaveAndDestroy(
1535 Buffer const * orig, Buffer * buffer)
1537 bool const success = buffer->autoSave();
1539 busyBuffers.remove(orig);
1541 ? _("Automatic save done.")
1542 : _("Automatic save failed!");
1547 void GuiView::autoSave()
1549 LYXERR(Debug::INFO, "Running autoSave()");
1551 Buffer * buffer = documentBufferView()
1552 ? &documentBufferView()->buffer() : 0;
1556 #if (QT_VERSION >= 0x040400)
1557 GuiViewPrivate::busyBuffers.insert(buffer);
1558 QFuture<docstring> f = QtConcurrent::run(GuiViewPrivate::autosaveAndDestroy,
1559 buffer, buffer->clone());
1560 d.autosave_watcher_.setFuture(f);
1564 resetAutosaveTimers();
1568 void GuiView::resetAutosaveTimers()
1571 d.autosave_timeout_.restart();
1575 bool GuiView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1578 Buffer * buf = currentBufferView()
1579 ? ¤tBufferView()->buffer() : 0;
1580 Buffer * doc_buffer = documentBufferView()
1581 ? &(documentBufferView()->buffer()) : 0;
1583 // Check whether we need a buffer
1584 if (!lyxaction.funcHasFlag(cmd.action(), LyXAction::NoBuffer) && !buf) {
1585 // no, exit directly
1586 flag.message(from_utf8(N_("Command not allowed with"
1587 "out any document open")));
1588 flag.setEnabled(false);
1592 if (cmd.origin() == FuncRequest::TOC) {
1593 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
1594 if (!toc || !toc->getStatus(documentBufferView()->cursor(), cmd, flag))
1595 flag.setEnabled(false);
1599 switch(cmd.action()) {
1600 case LFUN_BUFFER_IMPORT:
1603 case LFUN_MASTER_BUFFER_UPDATE:
1604 case LFUN_MASTER_BUFFER_VIEW:
1605 enable = doc_buffer && doc_buffer->parent() != 0
1606 && !d.processing_thread_watcher_.isRunning();
1609 case LFUN_BUFFER_UPDATE:
1610 case LFUN_BUFFER_VIEW: {
1611 if (!doc_buffer || d.processing_thread_watcher_.isRunning()) {
1615 string format = to_utf8(cmd.argument());
1616 if (cmd.argument().empty())
1617 format = doc_buffer->getDefaultOutputFormat();
1618 enable = doc_buffer->isExportableFormat(format);
1622 case LFUN_BUFFER_RELOAD:
1623 enable = doc_buffer && !doc_buffer->isUnnamed()
1624 && doc_buffer->fileName().exists()
1625 && (!doc_buffer->isClean()
1626 || doc_buffer->isExternallyModified(Buffer::timestamp_method));
1629 case LFUN_BUFFER_CHILD_OPEN:
1630 enable = doc_buffer;
1633 case LFUN_BUFFER_WRITE:
1634 enable = doc_buffer && (doc_buffer->isUnnamed() || !doc_buffer->isClean());
1637 //FIXME: This LFUN should be moved to GuiApplication.
1638 case LFUN_BUFFER_WRITE_ALL: {
1639 // We enable the command only if there are some modified buffers
1640 Buffer * first = theBufferList().first();
1645 // We cannot use a for loop as the buffer list is a cycle.
1647 if (!b->isClean()) {
1651 b = theBufferList().next(b);
1652 } while (b != first);
1656 case LFUN_BUFFER_WRITE_AS:
1657 enable = doc_buffer;
1660 case LFUN_BUFFER_CLOSE:
1661 enable = doc_buffer;
1664 case LFUN_BUFFER_CLOSE_ALL:
1665 enable = theBufferList().last() != theBufferList().first();
1668 case LFUN_SPLIT_VIEW:
1669 if (cmd.getArg(0) == "vertical")
1670 enable = doc_buffer && (d.splitter_->count() == 1 ||
1671 d.splitter_->orientation() == Qt::Vertical);
1673 enable = doc_buffer && (d.splitter_->count() == 1 ||
1674 d.splitter_->orientation() == Qt::Horizontal);
1677 case LFUN_CLOSE_TAB_GROUP:
1678 enable = d.currentTabWorkArea();
1681 case LFUN_TOOLBAR_TOGGLE: {
1682 string const name = cmd.getArg(0);
1683 if (GuiToolbar * t = toolbar(name))
1684 flag.setOnOff(t->isVisible());
1687 docstring const msg =
1688 bformat(_("Unknown toolbar \"%1$s\""), from_utf8(name));
1694 case LFUN_DROP_LAYOUTS_CHOICE:
1698 case LFUN_UI_TOGGLE:
1699 flag.setOnOff(isFullScreen());
1702 case LFUN_DIALOG_DISCONNECT_INSET:
1705 case LFUN_DIALOG_HIDE:
1706 // FIXME: should we check if the dialog is shown?
1709 case LFUN_DIALOG_TOGGLE:
1710 flag.setOnOff(isDialogVisible(cmd.getArg(0)));
1711 // fall through to set "enable"
1712 case LFUN_DIALOG_SHOW: {
1713 string const name = cmd.getArg(0);
1715 enable = name == "aboutlyx"
1716 || name == "file" //FIXME: should be removed.
1718 || name == "texinfo"
1719 || name == "progress"
1720 || name == "compare";
1721 else if (name == "print")
1722 enable = doc_buffer->isExportable("dvi")
1723 && lyxrc.print_command != "none";
1724 else if (name == "character" || name == "symbols") {
1725 if (!buf || buf->isReadonly())
1728 // FIXME we should consider passthru
1730 Inset const & in = currentBufferView()->cursor().inset();
1731 enable = !in.getLayout().isPassThru();
1734 else if (name == "latexlog")
1735 enable = FileName(doc_buffer->logName()).isReadableFile();
1736 else if (name == "spellchecker")
1737 enable = theSpellChecker() && !doc_buffer->isReadonly();
1738 else if (name == "vclog")
1739 enable = doc_buffer->lyxvc().inUse();
1743 case LFUN_DIALOG_UPDATE: {
1744 string const name = cmd.getArg(0);
1746 enable = name == "prefs";
1750 case LFUN_COMMAND_EXECUTE:
1752 case LFUN_MENU_OPEN:
1753 // Nothing to check.
1756 case LFUN_COMPLETION_INLINE:
1757 if (!d.current_work_area_
1758 || !d.current_work_area_->completer().inlinePossible(
1759 currentBufferView()->cursor()))
1763 case LFUN_COMPLETION_POPUP:
1764 if (!d.current_work_area_
1765 || !d.current_work_area_->completer().popupPossible(
1766 currentBufferView()->cursor()))
1770 case LFUN_COMPLETION_COMPLETE:
1771 if (!d.current_work_area_
1772 || !d.current_work_area_->completer().inlinePossible(
1773 currentBufferView()->cursor()))
1777 case LFUN_COMPLETION_ACCEPT:
1778 if (!d.current_work_area_
1779 || (!d.current_work_area_->completer().popupVisible()
1780 && !d.current_work_area_->completer().inlineVisible()
1781 && !d.current_work_area_->completer().completionAvailable()))
1785 case LFUN_COMPLETION_CANCEL:
1786 if (!d.current_work_area_
1787 || (!d.current_work_area_->completer().popupVisible()
1788 && !d.current_work_area_->completer().inlineVisible()))
1792 case LFUN_BUFFER_ZOOM_OUT:
1793 enable = doc_buffer && lyxrc.zoom > 10;
1796 case LFUN_BUFFER_ZOOM_IN:
1797 enable = doc_buffer;
1800 case LFUN_BUFFER_NEXT:
1801 case LFUN_BUFFER_PREVIOUS:
1802 // FIXME: should we check is there is an previous or next buffer?
1804 case LFUN_BUFFER_SWITCH:
1805 // toggle on the current buffer, but do not toggle off
1806 // the other ones (is that a good idea?)
1808 && to_utf8(cmd.argument()) == doc_buffer->absFileName())
1809 flag.setOnOff(true);
1812 case LFUN_VC_REGISTER:
1813 enable = doc_buffer && !doc_buffer->lyxvc().inUse();
1815 case LFUN_VC_CHECK_IN:
1816 enable = doc_buffer && doc_buffer->lyxvc().checkInEnabled();
1818 case LFUN_VC_CHECK_OUT:
1819 enable = doc_buffer && doc_buffer->lyxvc().checkOutEnabled();
1821 case LFUN_VC_LOCKING_TOGGLE:
1822 enable = doc_buffer && !doc_buffer->isReadonly()
1823 && doc_buffer->lyxvc().lockingToggleEnabled();
1824 flag.setOnOff(enable && doc_buffer->lyxvc().locking());
1826 case LFUN_VC_REVERT:
1827 enable = doc_buffer && doc_buffer->lyxvc().inUse() && !doc_buffer->isReadonly();
1829 case LFUN_VC_UNDO_LAST:
1830 enable = doc_buffer && doc_buffer->lyxvc().undoLastEnabled();
1832 case LFUN_VC_REPO_UPDATE:
1833 enable = doc_buffer && doc_buffer->lyxvc().repoUpdateEnabled();
1835 case LFUN_VC_COMMAND: {
1836 if (cmd.argument().empty())
1838 if (!doc_buffer && contains(cmd.getArg(0), 'D'))
1842 case LFUN_VC_COMPARE:
1843 enable = doc_buffer && doc_buffer->lyxvc().prepareFileRevisionEnabled();
1846 case LFUN_SERVER_GOTO_FILE_ROW:
1848 case LFUN_FORWARD_SEARCH:
1849 enable = !(lyxrc.forward_search_dvi.empty() && lyxrc.forward_search_pdf.empty());
1857 flag.setEnabled(false);
1863 static FileName selectTemplateFile()
1865 FileDialog dlg(qt_("Select template file"));
1866 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1867 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
1869 FileDialog::Result result = dlg.open(toqstr(lyxrc.template_path),
1870 QStringList(qt_("LyX Documents (*.lyx)")));
1872 if (result.first == FileDialog::Later)
1874 if (result.second.isEmpty())
1876 return FileName(fromqstr(result.second));
1880 Buffer * GuiView::loadDocument(FileName const & filename, bool tolastfiles)
1884 Buffer * newBuffer = 0;
1886 newBuffer = checkAndLoadLyXFile(filename);
1887 } catch (ExceptionMessage const & e) {
1893 message(_("Document not loaded."));
1898 newBuffer->errors("Parse");
1899 setBuffer(newBuffer);
1902 theSession().lastFiles().add(filename);
1909 void GuiView::openDocument(string const & fname)
1911 string initpath = lyxrc.document_path;
1913 if (documentBufferView()) {
1914 string const trypath = documentBufferView()->buffer().filePath();
1915 // If directory is writeable, use this as default.
1916 if (FileName(trypath).isDirWritable())
1922 if (fname.empty()) {
1923 FileDialog dlg(qt_("Select document to open"), LFUN_FILE_OPEN);
1924 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1925 dlg.setButton2(qt_("Examples|#E#e"),
1926 toqstr(addPath(package().system_support().absFileName(), "examples")));
1928 QStringList filter(qt_("LyX Documents (*.lyx)"));
1929 filter << qt_("LyX-1.3.x Documents (*.lyx13)")
1930 << qt_("LyX-1.4.x Documents (*.lyx14)")
1931 << qt_("LyX-1.5.x Documents (*.lyx15)")
1932 << qt_("LyX-1.6.x Documents (*.lyx16)");
1933 FileDialog::Result result =
1934 dlg.open(toqstr(initpath), filter);
1936 if (result.first == FileDialog::Later)
1939 filename = fromqstr(result.second);
1941 // check selected filename
1942 if (filename.empty()) {
1943 message(_("Canceled."));
1949 // get absolute path of file and add ".lyx" to the filename if
1951 FileName const fullname =
1952 fileSearch(string(), filename, "lyx", support::may_not_exist);
1953 if (!fullname.empty())
1954 filename = fullname.absFileName();
1956 if (!fullname.onlyPath().isDirectory()) {
1957 Alert::warning(_("Invalid filename"),
1958 bformat(_("The directory in the given path\n%1$s\ndoes not exist."),
1959 from_utf8(fullname.absFileName())));
1963 // if the file doesn't exist and isn't already open (bug 6645),
1964 // let the user create one
1965 if (!fullname.exists() && !theBufferList().exists(fullname)) {
1966 // the user specifically chose this name. Believe him.
1967 Buffer * const b = newFile(filename, string(), true);
1973 docstring const disp_fn = makeDisplayPath(filename);
1974 message(bformat(_("Opening document %1$s..."), disp_fn));
1977 Buffer * buf = loadDocument(fullname);
1979 str2 = bformat(_("Document %1$s opened."), disp_fn);
1980 if (buf->lyxvc().inUse())
1981 str2 += " " + from_utf8(buf->lyxvc().versionString()) +
1982 " " + _("Version control detected.");
1984 str2 = bformat(_("Could not open document %1$s"), disp_fn);
1989 // FIXME: clean that
1990 static bool import(GuiView * lv, FileName const & filename,
1991 string const & format, ErrorList & errorList)
1993 FileName const lyxfile(support::changeExtension(filename.absFileName(), ".lyx"));
1995 string loader_format;
1996 vector<string> loaders = theConverters().loaders();
1997 if (find(loaders.begin(), loaders.end(), format) == loaders.end()) {
1998 for (vector<string>::const_iterator it = loaders.begin();
1999 it != loaders.end(); ++it) {
2000 if (!theConverters().isReachable(format, *it))
2003 string const tofile =
2004 support::changeExtension(filename.absFileName(),
2005 formats.extension(*it));
2006 if (!theConverters().convert(0, filename, FileName(tofile),
2007 filename, format, *it, errorList))
2009 loader_format = *it;
2012 if (loader_format.empty()) {
2013 frontend::Alert::error(_("Couldn't import file"),
2014 bformat(_("No information for importing the format %1$s."),
2015 formats.prettyName(format)));
2019 loader_format = format;
2021 if (loader_format == "lyx") {
2022 Buffer * buf = lv->loadDocument(lyxfile);
2026 Buffer * const b = newFile(lyxfile.absFileName(), string(), true);
2030 bool as_paragraphs = loader_format == "textparagraph";
2031 string filename2 = (loader_format == format) ? filename.absFileName()
2032 : support::changeExtension(filename.absFileName(),
2033 formats.extension(loader_format));
2034 lv->currentBufferView()->insertPlaintextFile(FileName(filename2),
2036 guiApp->setCurrentView(lv);
2037 lyx::dispatch(FuncRequest(LFUN_MARK_OFF));
2044 void GuiView::importDocument(string const & argument)
2047 string filename = split(argument, format, ' ');
2049 LYXERR(Debug::INFO, format << " file: " << filename);
2051 // need user interaction
2052 if (filename.empty()) {
2053 string initpath = lyxrc.document_path;
2054 if (documentBufferView()) {
2055 string const trypath = documentBufferView()->buffer().filePath();
2056 // If directory is writeable, use this as default.
2057 if (FileName(trypath).isDirWritable())
2061 docstring const text = bformat(_("Select %1$s file to import"),
2062 formats.prettyName(format));
2064 FileDialog dlg(toqstr(text), LFUN_BUFFER_IMPORT);
2065 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2066 dlg.setButton2(qt_("Examples|#E#e"),
2067 toqstr(addPath(package().system_support().absFileName(), "examples")));
2069 docstring filter = formats.prettyName(format);
2072 filter += from_utf8(formats.extension(format));
2075 FileDialog::Result result =
2076 dlg.open(toqstr(initpath), fileFilters(toqstr(filter)));
2078 if (result.first == FileDialog::Later)
2081 filename = fromqstr(result.second);
2083 // check selected filename
2084 if (filename.empty())
2085 message(_("Canceled."));
2088 if (filename.empty())
2091 // get absolute path of file
2092 FileName const fullname(support::makeAbsPath(filename));
2094 FileName const lyxfile(support::changeExtension(fullname.absFileName(), ".lyx"));
2096 // Check if the document already is open
2097 Buffer * buf = theBufferList().getBuffer(lyxfile);
2100 if (!closeBuffer()) {
2101 message(_("Canceled."));
2106 docstring const displaypath = makeDisplayPath(lyxfile.absFileName(), 30);
2108 // if the file exists already, and we didn't do
2109 // -i lyx thefile.lyx, warn
2110 if (lyxfile.exists() && fullname != lyxfile) {
2112 docstring text = bformat(_("The document %1$s already exists.\n\n"
2113 "Do you want to overwrite that document?"), displaypath);
2114 int const ret = Alert::prompt(_("Overwrite document?"),
2115 text, 0, 1, _("&Overwrite"), _("&Cancel"));
2118 message(_("Canceled."));
2123 message(bformat(_("Importing %1$s..."), displaypath));
2124 ErrorList errorList;
2125 if (import(this, fullname, format, errorList))
2126 message(_("imported."));
2128 message(_("file not imported!"));
2130 // FIXME (Abdel 12/08/06): Is there a need to display the error list here?
2134 void GuiView::newDocument(string const & filename, bool from_template)
2136 FileName initpath(lyxrc.document_path);
2137 if (documentBufferView()) {
2138 FileName const trypath(documentBufferView()->buffer().filePath());
2139 // If directory is writeable, use this as default.
2140 if (trypath.isDirWritable())
2144 string templatefile;
2145 if (from_template) {
2146 templatefile = selectTemplateFile().absFileName();
2147 if (templatefile.empty())
2152 if (filename.empty())
2153 b = newUnnamedFile(initpath, to_utf8(_("newfile")), templatefile);
2155 b = newFile(filename, templatefile, true);
2160 // If no new document could be created, it is unsure
2161 // whether there is a valid BufferView.
2162 if (currentBufferView())
2163 // Ensure the cursor is correctly positioned on screen.
2164 currentBufferView()->showCursor();
2168 void GuiView::insertLyXFile(docstring const & fname)
2170 BufferView * bv = documentBufferView();
2175 FileName filename(to_utf8(fname));
2176 if (filename.empty()) {
2177 // Launch a file browser
2179 string initpath = lyxrc.document_path;
2180 string const trypath = bv->buffer().filePath();
2181 // If directory is writeable, use this as default.
2182 if (FileName(trypath).isDirWritable())
2186 FileDialog dlg(qt_("Select LyX document to insert"), LFUN_FILE_INSERT);
2187 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2188 dlg.setButton2(qt_("Examples|#E#e"),
2189 toqstr(addPath(package().system_support().absFileName(),
2192 FileDialog::Result result = dlg.open(toqstr(initpath),
2193 QStringList(qt_("LyX Documents (*.lyx)")));
2195 if (result.first == FileDialog::Later)
2199 filename.set(fromqstr(result.second));
2201 // check selected filename
2202 if (filename.empty()) {
2203 // emit message signal.
2204 message(_("Canceled."));
2209 bv->insertLyXFile(filename);
2210 bv->buffer().errors("Parse");
2214 void GuiView::insertPlaintextFile(docstring const & fname,
2217 BufferView * bv = documentBufferView();
2221 if (!fname.empty() && !FileName::isAbsolute(to_utf8(fname))) {
2222 message(_("Absolute filename expected."));
2227 FileName filename(to_utf8(fname));
2229 if (!filename.empty()) {
2230 bv->insertPlaintextFile(filename, asParagraph);
2234 FileDialog dlg(qt_("Select file to insert"), (asParagraph ?
2235 LFUN_FILE_INSERT_PLAINTEXT_PARA : LFUN_FILE_INSERT_PLAINTEXT));
2237 FileDialog::Result result = dlg.open(toqstr(bv->buffer().filePath()),
2238 QStringList(qt_("All Files (*)")));
2240 if (result.first == FileDialog::Later)
2244 filename.set(fromqstr(result.second));
2246 // check selected filename
2247 if (filename.empty()) {
2248 // emit message signal.
2249 message(_("Canceled."));
2253 bv->insertPlaintextFile(filename, asParagraph);
2257 bool GuiView::renameBuffer(Buffer & b, docstring const & newname)
2259 FileName fname = b.fileName();
2260 FileName const oldname = fname;
2262 if (!newname.empty()) {
2264 fname = support::makeAbsPath(to_utf8(newname), oldname.onlyPath().absFileName());
2266 // Switch to this Buffer.
2269 // No argument? Ask user through dialog.
2271 FileDialog dlg(qt_("Choose a filename to save document as"),
2272 LFUN_BUFFER_WRITE_AS);
2273 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2274 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
2276 if (!isLyXFileName(fname.absFileName()))
2277 fname.changeExtension(".lyx");
2279 FileDialog::Result result =
2280 dlg.save(toqstr(fname.onlyPath().absFileName()),
2281 QStringList(qt_("LyX Documents (*.lyx)")),
2282 toqstr(fname.onlyFileName()));
2284 if (result.first == FileDialog::Later)
2287 fname.set(fromqstr(result.second));
2292 if (!isLyXFileName(fname.absFileName()))
2293 fname.changeExtension(".lyx");
2296 // fname is now the new Buffer location.
2297 if (FileName(fname).exists()) {
2298 docstring const file = makeDisplayPath(fname.absFileName(), 30);
2299 docstring text = bformat(_("The document %1$s already "
2300 "exists.\n\nDo you want to "
2301 "overwrite that document?"),
2303 int const ret = Alert::prompt(_("Overwrite document?"),
2304 text, 0, 2, _("&Overwrite"), _("&Rename"), _("&Cancel"));
2307 case 1: return renameBuffer(b, docstring());
2308 case 2: return false;
2312 return saveBuffer(b, fname);
2316 bool GuiView::saveBuffer(Buffer & b) {
2317 return saveBuffer(b, FileName());
2321 bool GuiView::saveBuffer(Buffer & b, FileName const & fn)
2323 if (workArea(b) && workArea(b)->inDialogMode())
2326 if (fn.empty() && b.isUnnamed())
2327 return renameBuffer(b, docstring());
2333 success = b.saveAs(fn);
2336 theSession().lastFiles().add(b.fileName());
2340 // Switch to this Buffer.
2343 // FIXME: we don't tell the user *WHY* the save failed !!
2344 docstring const file = makeDisplayPath(b.absFileName(), 30);
2345 docstring text = bformat(_("The document %1$s could not be saved.\n\n"
2346 "Do you want to rename the document and "
2347 "try again?"), file);
2348 int const ret = Alert::prompt(_("Rename and save?"),
2349 text, 0, 2, _("&Rename"), _("&Retry"), _("&Cancel"));
2352 if (!renameBuffer(b, docstring()))
2361 return saveBuffer(b);
2365 bool GuiView::hideWorkArea(GuiWorkArea * wa)
2367 return closeWorkArea(wa, false);
2371 bool GuiView::closeWorkArea(GuiWorkArea * wa)
2373 Buffer & buf = wa->bufferView().buffer();
2374 return closeWorkArea(wa, !buf.parent());
2378 bool GuiView::closeBuffer()
2380 GuiWorkArea * wa = currentMainWorkArea();
2381 setCurrentWorkArea(wa);
2382 Buffer & buf = wa->bufferView().buffer();
2383 return wa && closeWorkArea(wa, !buf.parent());
2387 void GuiView::writeSession() const {
2388 GuiWorkArea const * active_wa = currentMainWorkArea();
2389 for (int i = 0; i < d.splitter_->count(); ++i) {
2390 TabWorkArea * twa = d.tabWorkArea(i);
2391 for (int j = 0; j < twa->count(); ++j) {
2392 GuiWorkArea * wa = static_cast<GuiWorkArea *>(twa->widget(j));
2393 Buffer & buf = wa->bufferView().buffer();
2394 theSession().lastOpened().add(buf.fileName(), wa == active_wa);
2400 bool GuiView::closeBufferAll()
2402 // Close the workareas in all other views
2403 QList<int> const ids = guiApp->viewIds();
2404 for (int i = 0; i != ids.size(); ++i) {
2405 if (id_ != ids[i] && !guiApp->view(ids[i]).closeWorkAreaAll())
2409 // Close our own workareas
2410 if (!closeWorkAreaAll())
2413 // Now close the hidden buffers. We prevent hidden buffers from being
2414 // dirty, so we can just close them.
2415 theBufferList().closeAll();
2420 bool GuiView::closeWorkAreaAll()
2422 setCurrentWorkArea(currentMainWorkArea());
2424 // We might be in a situation that there is still a tabWorkArea, but
2425 // there are no tabs anymore. This can happen when we get here after a
2426 // TabWorkArea::lastWorkAreaRemoved() signal. Therefore we count how
2427 // many TabWorkArea's have no documents anymore.
2430 // We have to call count() each time, because it can happen that
2431 // more than one splitter will disappear in one iteration (bug 5998).
2432 for (; d.splitter_->count() > empty_twa; ) {
2433 TabWorkArea * twa = d.tabWorkArea(empty_twa);
2435 if (twa->count() == 0)
2438 setCurrentWorkArea(twa->currentWorkArea());
2439 if (!closeTabWorkArea(twa))
2447 bool GuiView::closeWorkArea(GuiWorkArea * wa, bool close_buffer)
2452 Buffer & buf = wa->bufferView().buffer();
2454 if (close_buffer && GuiViewPrivate::busyBuffers.contains(&buf)) {
2455 Alert::warning(_("Close document"),
2456 _("Document could not be closed because it is being processed by LyX."));
2461 return closeBuffer(buf);
2463 if (!inMultiTabs(wa))
2464 if (!saveBufferIfNeeded(buf, true))
2472 bool GuiView::closeBuffer(Buffer & buf)
2474 // If we are in a close_event all children will be closed in some time,
2475 // so no need to do it here. This will ensure that the children end up
2476 // in the session file in the correct order. If we close the master
2477 // buffer, we can close or release the child buffers here too.
2478 bool success = true;
2480 ListOfBuffers clist = buf.getChildren();
2481 ListOfBuffers::const_iterator it = clist.begin();
2482 ListOfBuffers::const_iterator const bend = clist.end();
2483 for (; it != bend; ++it) {
2484 // If a child is dirty, do not close
2485 // without user intervention
2486 //FIXME: should we look in other tabworkareas?
2487 Buffer * child_buf = *it;
2488 GuiWorkArea * child_wa = workArea(*child_buf);
2490 if (!closeWorkArea(child_wa, true)) {
2495 theBufferList().releaseChild(&buf, child_buf);
2499 // goto bookmark to update bookmark pit.
2500 //FIXME: we should update only the bookmarks related to this buffer!
2501 LYXERR(Debug::DEBUG, "GuiView::closeBuffer()");
2502 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
2503 guiApp->gotoBookmark(i+1, false, false);
2505 if (saveBufferIfNeeded(buf, false)) {
2506 buf.removeAutosaveFile();
2507 theBufferList().release(&buf);
2511 // open all children again to avoid a crash because of dangling
2512 // pointers (bug 6603)
2518 bool GuiView::closeTabWorkArea(TabWorkArea * twa)
2520 while (twa == d.currentTabWorkArea()) {
2521 twa->setCurrentIndex(twa->count()-1);
2523 GuiWorkArea * wa = twa->currentWorkArea();
2524 Buffer & b = wa->bufferView().buffer();
2526 // We only want to close the buffer if the same buffer is not visible
2527 // in another view, and if this is not a child and if we are closing
2528 // a view (not a tabgroup).
2529 bool const close_buffer =
2530 !inOtherView(b) && !b.parent() && closing_;
2532 if (!closeWorkArea(wa, close_buffer))
2539 bool GuiView::saveBufferIfNeeded(Buffer & buf, bool hiding)
2541 if (buf.isClean() || buf.paragraphs().empty())
2544 // Switch to this Buffer.
2549 if (buf.isUnnamed())
2550 file = from_utf8(buf.fileName().onlyFileName());
2552 file = buf.fileName().displayName(30);
2554 // Bring this window to top before asking questions.
2559 if (hiding && buf.isUnnamed()) {
2560 docstring const text = bformat(_("The document %1$s has not been "
2561 "saved yet.\n\nDo you want to save "
2562 "the document?"), file);
2563 ret = Alert::prompt(_("Save new document?"),
2564 text, 0, 1, _("&Save"), _("&Cancel"));
2568 docstring const text = bformat(_("The document %1$s has unsaved changes."
2569 "\n\nDo you want to save the document or discard the changes?"), file);
2570 ret = Alert::prompt(_("Save changed document?"),
2571 text, 0, 2, _("&Save"), _("&Discard"), _("&Cancel"));
2576 if (!saveBuffer(buf))
2580 // If we crash after this we could have no autosave file
2581 // but I guess this is really improbable (Jug).
2582 // Sometimes improbable things happen:
2583 // - see bug http://www.lyx.org/trac/ticket/6587 (ps)
2584 // buf.removeAutosaveFile();
2586 // revert all changes
2597 bool GuiView::inMultiTabs(GuiWorkArea * wa)
2599 Buffer & buf = wa->bufferView().buffer();
2601 for (int i = 0; i != d.splitter_->count(); ++i) {
2602 GuiWorkArea * wa_ = d.tabWorkArea(i)->workArea(buf);
2603 if (wa_ && wa_ != wa)
2606 return inOtherView(buf);
2610 bool GuiView::inOtherView(Buffer & buf)
2612 QList<int> const ids = guiApp->viewIds();
2614 for (int i = 0; i != ids.size(); ++i) {
2618 if (guiApp->view(ids[i]).workArea(buf))
2625 void GuiView::gotoNextOrPreviousBuffer(NextOrPrevious np)
2627 if (!documentBufferView())
2630 if (TabWorkArea * twa = d.currentTabWorkArea()) {
2631 Buffer * const curbuf = &documentBufferView()->buffer();
2632 int nwa = twa->count();
2633 for (int i = 0; i < nwa; ++i) {
2634 if (&workArea(i)->bufferView().buffer() == curbuf) {
2636 if (np == NEXTBUFFER)
2637 next_index = (i == nwa - 1 ? 0 : i + 1);
2639 next_index = (i == 0 ? nwa - 1 : i - 1);
2640 setBuffer(&workArea(next_index)->bufferView().buffer());
2648 /// make sure the document is saved
2649 static bool ensureBufferClean(Buffer * buffer)
2651 LASSERT(buffer, return false);
2652 if (buffer->isClean() && !buffer->isUnnamed())
2655 docstring const file = buffer->fileName().displayName(30);
2658 if (!buffer->isUnnamed()) {
2659 text = bformat(_("The document %1$s has unsaved "
2660 "changes.\n\nDo you want to save "
2661 "the document?"), file);
2662 title = _("Save changed document?");
2665 text = bformat(_("The document %1$s has not been "
2666 "saved yet.\n\nDo you want to save "
2667 "the document?"), file);
2668 title = _("Save new document?");
2670 int const ret = Alert::prompt(title, text, 0, 1, _("&Save"), _("&Cancel"));
2673 dispatch(FuncRequest(LFUN_BUFFER_WRITE));
2675 return buffer->isClean() && !buffer->isUnnamed();
2679 bool GuiView::reloadBuffer(Buffer & buf)
2681 Buffer::ReadStatus status = buf.reload();
2682 return status == Buffer::ReadSuccess;
2686 void GuiView::checkExternallyModifiedBuffers()
2688 BufferList::iterator bit = theBufferList().begin();
2689 BufferList::iterator const bend = theBufferList().end();
2690 for (; bit != bend; ++bit) {
2691 Buffer * buf = *bit;
2692 if (buf->fileName().exists()
2693 && buf->isExternallyModified(Buffer::checksum_method)) {
2694 docstring text = bformat(_("Document \n%1$s\n has been externally modified."
2695 " Reload now? Any local changes will be lost."),
2696 from_utf8(buf->absFileName()));
2697 int const ret = Alert::prompt(_("Reload externally changed document?"),
2698 text, 0, 1, _("&Reload"), _("&Cancel"));
2706 void GuiView::dispatchVC(FuncRequest const & cmd, DispatchResult & dr)
2708 Buffer * buffer = documentBufferView()
2709 ? &(documentBufferView()->buffer()) : 0;
2711 switch (cmd.action()) {
2712 case LFUN_VC_REGISTER:
2713 if (!buffer || !ensureBufferClean(buffer))
2715 if (!buffer->lyxvc().inUse()) {
2716 if (buffer->lyxvc().registrer()) {
2717 reloadBuffer(*buffer);
2718 dr.suppressMessageUpdate();
2723 case LFUN_VC_CHECK_IN:
2724 if (!buffer || !ensureBufferClean(buffer))
2726 if (buffer->lyxvc().inUse() && !buffer->isReadonly()) {
2727 dr.setMessage(buffer->lyxvc().checkIn());
2728 if (!dr.message().empty())
2729 reloadBuffer(*buffer);
2733 case LFUN_VC_CHECK_OUT:
2734 if (!buffer || !ensureBufferClean(buffer))
2736 if (buffer->lyxvc().inUse()) {
2737 dr.setMessage(buffer->lyxvc().checkOut());
2738 reloadBuffer(*buffer);
2742 case LFUN_VC_LOCKING_TOGGLE:
2743 LASSERT(buffer, return);
2744 if (!ensureBufferClean(buffer) || buffer->isReadonly())
2746 if (buffer->lyxvc().inUse()) {
2747 string res = buffer->lyxvc().lockingToggle();
2749 frontend::Alert::error(_("Revision control error."),
2750 _("Error when setting the locking property."));
2753 reloadBuffer(*buffer);
2758 case LFUN_VC_REVERT:
2759 LASSERT(buffer, return);
2760 if (buffer->lyxvc().revert()) {
2761 reloadBuffer(*buffer);
2762 dr.suppressMessageUpdate();
2766 case LFUN_VC_UNDO_LAST:
2767 LASSERT(buffer, return);
2768 buffer->lyxvc().undoLast();
2769 reloadBuffer(*buffer);
2770 dr.suppressMessageUpdate();
2773 case LFUN_VC_REPO_UPDATE:
2774 LASSERT(buffer, return);
2775 if (ensureBufferClean(buffer)) {
2776 dr.setMessage(buffer->lyxvc().repoUpdate());
2777 checkExternallyModifiedBuffers();
2781 case LFUN_VC_COMMAND: {
2782 string flag = cmd.getArg(0);
2783 if (buffer && contains(flag, 'R') && !ensureBufferClean(buffer))
2786 if (contains(flag, 'M')) {
2787 if (!Alert::askForText(message, _("LyX VC: Log Message")))
2790 string path = cmd.getArg(1);
2791 if (contains(path, "$$p") && buffer)
2792 path = subst(path, "$$p", buffer->filePath());
2793 LYXERR(Debug::LYXVC, "Directory: " << path);
2795 if (!pp.isReadableDirectory()) {
2796 lyxerr << _("Directory is not accessible.") << endl;
2799 support::PathChanger p(pp);
2801 string command = cmd.getArg(2);
2802 if (command.empty())
2805 command = subst(command, "$$i", buffer->absFileName());
2806 command = subst(command, "$$p", buffer->filePath());
2808 command = subst(command, "$$m", to_utf8(message));
2809 LYXERR(Debug::LYXVC, "Command: " << command);
2811 one.startscript(Systemcall::Wait, command);
2815 if (contains(flag, 'I'))
2816 buffer->markDirty();
2817 if (contains(flag, 'R'))
2818 reloadBuffer(*buffer);
2823 case LFUN_VC_COMPARE: {
2825 if (cmd.argument().empty()) {
2826 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "comparehistory"));
2830 string rev1 = cmd.getArg(0);
2834 if (!buffer->lyxvc().prepareFileRevision(rev1, f1))
2837 if (isStrInt(rev1) && convert<int>(rev1) <= 0) {
2838 f2 = buffer->absFileName();
2840 string rev2 = cmd.getArg(1);
2844 if (!buffer->lyxvc().prepareFileRevision(rev2, f2))
2848 LYXERR(Debug::LYXVC, "Launching comparison for fetched revisions:\n" <<
2849 f1 << "\n" << f2 << "\n" );
2850 string par = "compare run " + quoteName(f1) + " " + quoteName(f2);
2851 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, par));
2861 void GuiView::openChildDocument(string const & fname)
2863 LASSERT(documentBufferView(), return);
2864 Buffer & buffer = documentBufferView()->buffer();
2865 FileName const filename = support::makeAbsPath(fname, buffer.filePath());
2866 documentBufferView()->saveBookmark(false);
2868 if (theBufferList().exists(filename)) {
2869 child = theBufferList().getBuffer(filename);
2872 message(bformat(_("Opening child document %1$s..."),
2873 makeDisplayPath(filename.absFileName())));
2874 child = loadDocument(filename, false);
2876 // Set the parent name of the child document.
2877 // This makes insertion of citations and references in the child work,
2878 // when the target is in the parent or another child document.
2880 child->setParent(&buffer);
2884 bool GuiView::goToFileRow(string const & argument)
2888 size_t i = argument.find_last_of(' ');
2889 if (i != string::npos) {
2890 file_name = os::internal_path(trim(argument.substr(0, i)));
2891 istringstream is(argument.substr(i + 1));
2896 if (i == string::npos) {
2897 LYXERR0("Wrong argument: " << argument);
2901 string const abstmp = package().temp_dir().absFileName();
2902 string const realtmp = package().temp_dir().realPath();
2903 // We have to use os::path_prefix_is() here, instead of
2904 // simply prefixIs(), because the file name comes from
2905 // an external application and may need case adjustment.
2906 if (os::path_prefix_is(file_name, abstmp, os::CASE_ADJUSTED)
2907 || os::path_prefix_is(file_name, realtmp, os::CASE_ADJUSTED)) {
2908 // Needed by inverse dvi search. If it is a file
2909 // in tmpdir, call the apropriated function.
2910 // If tmpdir is a symlink, we may have the real
2911 // path passed back, so we correct for that.
2912 if (!prefixIs(file_name, abstmp))
2913 file_name = subst(file_name, realtmp, abstmp);
2914 buf = theBufferList().getBufferFromTmp(file_name);
2916 // Must replace extension of the file to be .lyx
2917 // and get full path
2918 FileName const s = fileSearch(string(),
2919 support::changeExtension(file_name, ".lyx"), "lyx");
2920 // Either change buffer or load the file
2921 if (theBufferList().exists(s))
2922 buf = theBufferList().getBuffer(s);
2923 else if (s.exists()) {
2924 buf = loadDocument(s);
2929 _("File does not exist: %1$s"),
2930 makeDisplayPath(file_name)));
2935 documentBufferView()->setCursorFromRow(row);
2940 #if (QT_VERSION >= 0x040400)
2942 docstring GuiView::GuiViewPrivate::runAndDestroy(const T& func, Buffer const * orig, Buffer * buffer, string const & format, string const & msg)
2944 bool const update_unincluded =
2945 buffer->params().maintain_unincluded_children
2946 && !buffer->params().getIncludedChildren().empty();
2947 bool const success = func(format, update_unincluded);
2949 busyBuffers.remove(orig);
2950 if (msg == "preview") {
2952 ? bformat(_("Successful preview of format: %1$s"), from_utf8(format))
2953 : bformat(_("Error while previewing format: %1$s"), from_utf8(format));
2956 ? bformat(_("Successful export to format: %1$s"), from_utf8(format))
2957 : bformat(_("Error while exporting format: %1$s"), from_utf8(format));
2961 docstring GuiView::GuiViewPrivate::compileAndDestroy(Buffer const * orig, Buffer * buffer, string const & format)
2963 bool (Buffer::* mem_func)(std::string const &, bool, bool) const = &Buffer::doExport;
2964 return runAndDestroy(bind(mem_func, buffer, _1, true, _2), orig, buffer, format, "export");
2968 docstring GuiView::GuiViewPrivate::exportAndDestroy(Buffer const * orig, Buffer * buffer, string const & format)
2970 bool (Buffer::* mem_func)(std::string const &, bool, bool) const = &Buffer::doExport;
2971 return runAndDestroy(bind(mem_func, buffer, _1, false, _2), orig, buffer, format, "export");
2975 docstring GuiView::GuiViewPrivate::previewAndDestroy(Buffer const * orig, Buffer * buffer, string const & format)
2977 bool(Buffer::* mem_func)(std::string const &, bool) const = &Buffer::preview;
2978 return runAndDestroy(bind(mem_func, buffer, _1, _2), orig, buffer, format, "preview");
2983 // not used, but the linker needs them
2985 docstring GuiView::GuiViewPrivate::compileAndDestroy(
2986 Buffer const *, Buffer *, string const &)
2992 docstring GuiView::GuiViewPrivate::exportAndDestroy(
2993 Buffer const *, Buffer *, string const &)
2999 docstring GuiView::GuiViewPrivate::previewAndDestroy(
3000 Buffer const *, Buffer *, string const &)
3008 bool GuiView::GuiViewPrivate::asyncBufferProcessing(
3009 string const & argument,
3010 Buffer const * used_buffer,
3011 docstring const & msg,
3012 docstring (*asyncFunc)(Buffer const *, Buffer *, string const &),
3013 bool (Buffer::*syncFunc)(string const &, bool, bool) const,
3014 bool (Buffer::*previewFunc)(string const &, bool) const)
3019 string format = argument;
3021 format = used_buffer->getDefaultOutputFormat();
3023 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
3024 gv_->processingThreadStarted();
3026 progress_->clearMessages();
3029 GuiViewPrivate::busyBuffers.insert(used_buffer);
3030 QFuture<docstring> f = QtConcurrent::run(
3033 used_buffer->clone(),
3035 setPreviewFuture(f);
3036 last_export_format = used_buffer->bufferFormat();
3039 // We are asynchronous, so we don't know here anything about the success
3043 // TODO check here if it breaks exporting with Qt < 4.4
3044 bool const update_unincluded =
3045 used_buffer->params().maintain_unincluded_children &&
3046 !used_buffer->params().getIncludedChildren().empty();
3047 return (used_buffer->*syncFunc)(format, true, update_unincluded);
3048 } else if (previewFunc) {
3049 return (used_buffer->*previewFunc)(format, false);
3056 void GuiView::dispatchToBufferView(FuncRequest const & cmd, DispatchResult & dr)
3058 BufferView * bv = currentBufferView();
3061 // Let the current BufferView dispatch its own actions.
3062 bv->dispatch(cmd, dr);
3063 if (dr.dispatched())
3066 // Try with the document BufferView dispatch if any.
3067 BufferView * doc_bv = documentBufferView();
3069 doc_bv->dispatch(cmd, dr);
3070 if (dr.dispatched())
3074 // Then let the current Cursor dispatch its own actions.
3075 bv->cursor().dispatch(cmd);
3077 // update completion. We do it here and not in
3078 // processKeySym to avoid another redraw just for a
3079 // changed inline completion
3080 if (cmd.origin() == FuncRequest::KEYBOARD) {
3081 if (cmd.action() == LFUN_SELF_INSERT
3082 || (cmd.action() == LFUN_ERT_INSERT && bv->cursor().inMathed()))
3083 updateCompletion(bv->cursor(), true, true);
3084 else if (cmd.action() == LFUN_CHAR_DELETE_BACKWARD)
3085 updateCompletion(bv->cursor(), false, true);
3087 updateCompletion(bv->cursor(), false, false);
3090 dr = bv->cursor().result();
3094 void GuiView::dispatch(FuncRequest const & cmd, DispatchResult & dr)
3096 BufferView * bv = currentBufferView();
3097 // By default we won't need any update.
3098 dr.screenUpdate(Update::None);
3099 // assume cmd will be dispatched
3100 dr.dispatched(true);
3102 Buffer * doc_buffer = documentBufferView()
3103 ? &(documentBufferView()->buffer()) : 0;
3105 if (cmd.origin() == FuncRequest::TOC) {
3106 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
3107 // FIXME: do we need to pass a DispatchResult object here?
3108 toc->doDispatch(bv->cursor(), cmd);
3112 string const argument = to_utf8(cmd.argument());
3114 switch(cmd.action()) {
3115 case LFUN_BUFFER_CHILD_OPEN:
3116 openChildDocument(to_utf8(cmd.argument()));
3119 case LFUN_BUFFER_IMPORT:
3120 importDocument(to_utf8(cmd.argument()));
3123 case LFUN_BUFFER_EXPORT: {
3126 // GCC only sees strfwd.h when building merged
3127 if (::lyx::operator==(cmd.argument(), "custom")) {
3128 dispatch(FuncRequest(LFUN_DIALOG_SHOW, "sendto"), dr);
3131 #if QT_VERSION < 0x040400
3132 if (!doc_buffer->doExport(argument, false)) {
3134 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
3138 /* TODO/Review: Is it a problem to also export the children?
3139 See the update_unincluded flag */
3140 d.asyncBufferProcessing(argument,
3143 &GuiViewPrivate::exportAndDestroy,
3146 // TODO Inform user about success
3151 case LFUN_BUFFER_UPDATE: {
3152 d.asyncBufferProcessing(argument,
3155 &GuiViewPrivate::compileAndDestroy,
3160 case LFUN_BUFFER_VIEW: {
3161 d.asyncBufferProcessing(argument,
3163 _("Previewing ..."),
3164 &GuiViewPrivate::previewAndDestroy,
3169 case LFUN_MASTER_BUFFER_UPDATE: {
3170 d.asyncBufferProcessing(argument,
3171 (doc_buffer ? doc_buffer->masterBuffer() : 0),
3173 &GuiViewPrivate::compileAndDestroy,
3178 case LFUN_MASTER_BUFFER_VIEW: {
3179 d.asyncBufferProcessing(argument,
3180 (doc_buffer ? doc_buffer->masterBuffer() : 0),
3182 &GuiViewPrivate::previewAndDestroy,
3183 0, &Buffer::preview);
3186 case LFUN_BUFFER_SWITCH: {
3187 string const file_name = to_utf8(cmd.argument());
3188 if (!FileName::isAbsolute(file_name)) {
3190 dr.setMessage(_("Absolute filename expected."));
3194 Buffer * buffer = theBufferList().getBuffer(FileName(file_name));
3197 dr.setMessage(_("Document not loaded"));
3201 // Do we open or switch to the buffer in this view ?
3202 if (workArea(*buffer)
3203 || lyxrc.open_buffers_in_tabs || !documentBufferView()) {
3208 // Look for the buffer in other views
3209 QList<int> const ids = guiApp->viewIds();
3211 for (; i != ids.size(); ++i) {
3212 GuiView & gv = guiApp->view(ids[i]);
3213 if (gv.workArea(*buffer)) {
3214 gv.activateWindow();
3215 gv.setBuffer(buffer);
3220 // If necessary, open a new window as a last resort
3221 if (i == ids.size()) {
3222 lyx::dispatch(FuncRequest(LFUN_WINDOW_NEW));
3228 case LFUN_BUFFER_NEXT:
3229 gotoNextOrPreviousBuffer(NEXTBUFFER);
3232 case LFUN_BUFFER_PREVIOUS:
3233 gotoNextOrPreviousBuffer(PREVBUFFER);
3236 case LFUN_COMMAND_EXECUTE: {
3237 bool const show_it = cmd.argument() != "off";
3238 // FIXME: this is a hack, "minibuffer" should not be
3240 if (GuiToolbar * t = toolbar("minibuffer")) {
3241 t->setVisible(show_it);
3242 if (show_it && t->commandBuffer())
3243 t->commandBuffer()->setFocus();
3247 case LFUN_DROP_LAYOUTS_CHOICE:
3248 d.layout_->showPopup();
3251 case LFUN_MENU_OPEN:
3252 if (QMenu * menu = guiApp->menus().menu(toqstr(cmd.argument()), *this))
3253 menu->exec(QCursor::pos());
3256 case LFUN_FILE_INSERT:
3257 insertLyXFile(cmd.argument());
3260 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
3261 insertPlaintextFile(cmd.argument(), true);
3264 case LFUN_FILE_INSERT_PLAINTEXT:
3265 insertPlaintextFile(cmd.argument(), false);
3268 case LFUN_BUFFER_RELOAD: {
3269 LASSERT(doc_buffer, break);
3272 if (!doc_buffer->isClean()) {
3273 docstring const file =
3274 makeDisplayPath(doc_buffer->absFileName(), 20);
3275 docstring text = bformat(_("Any changes will be lost. "
3276 "Are you sure you want to revert to the saved version "
3277 "of the document %1$s?"), file);
3278 ret = Alert::prompt(_("Revert to saved document?"),
3279 text, 1, 1, _("&Revert"), _("&Cancel"));
3283 doc_buffer->markClean();
3284 reloadBuffer(*doc_buffer);
3285 dr.forceBufferUpdate();
3290 case LFUN_BUFFER_WRITE:
3291 LASSERT(doc_buffer, break);
3292 saveBuffer(*doc_buffer);
3295 case LFUN_BUFFER_WRITE_AS:
3296 LASSERT(doc_buffer, break);
3297 renameBuffer(*doc_buffer, cmd.argument());
3300 case LFUN_BUFFER_WRITE_ALL: {
3301 Buffer * first = theBufferList().first();
3304 message(_("Saving all documents..."));
3305 // We cannot use a for loop as the buffer list cycles.
3308 if (!b->isClean()) {
3310 LYXERR(Debug::ACTION, "Saved " << b->absFileName());
3312 b = theBufferList().next(b);
3313 } while (b != first);
3314 dr.setMessage(_("All documents saved."));
3318 case LFUN_BUFFER_CLOSE:
3322 case LFUN_BUFFER_CLOSE_ALL:
3326 case LFUN_TOOLBAR_TOGGLE: {
3327 string const name = cmd.getArg(0);
3328 if (GuiToolbar * t = toolbar(name))
3333 case LFUN_DIALOG_UPDATE: {
3334 string const name = to_utf8(cmd.argument());
3335 if (name == "prefs" || name == "document")
3336 updateDialog(name, string());
3337 else if (name == "paragraph")
3338 lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
3339 else if (currentBufferView()) {
3340 Inset * inset = currentBufferView()->editedInset(name);
3341 // Can only update a dialog connected to an existing inset
3343 // FIXME: get rid of this indirection; GuiView ask the inset
3344 // if he is kind enough to update itself...
3345 FuncRequest fr(LFUN_INSET_DIALOG_UPDATE, cmd.argument());
3346 //FIXME: pass DispatchResult here?
3347 inset->dispatch(currentBufferView()->cursor(), fr);
3353 case LFUN_DIALOG_TOGGLE: {
3354 if (isDialogVisible(cmd.getArg(0)))
3355 dispatch(FuncRequest(LFUN_DIALOG_HIDE, cmd.argument()), dr);
3357 dispatch(FuncRequest(LFUN_DIALOG_SHOW, cmd.argument()), dr);
3361 case LFUN_DIALOG_DISCONNECT_INSET:
3362 disconnectDialog(to_utf8(cmd.argument()));
3365 case LFUN_DIALOG_HIDE: {
3366 guiApp->hideDialogs(to_utf8(cmd.argument()), 0);
3370 case LFUN_DIALOG_SHOW: {
3371 string const name = cmd.getArg(0);
3372 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
3374 if (name == "character") {
3375 data = freefont2string();
3377 showDialog("character", data);
3378 } else if (name == "latexlog") {
3379 Buffer::LogType type;
3380 string const logfile = doc_buffer->logName(&type);
3382 case Buffer::latexlog:
3385 case Buffer::buildlog:
3389 data += Lexer::quoteString(logfile);
3390 showDialog("log", data);
3391 } else if (name == "vclog") {
3392 string const data = "vc " +
3393 Lexer::quoteString(doc_buffer->lyxvc().getLogFile());
3394 showDialog("log", data);
3395 } else if (name == "symbols") {
3396 data = bv->cursor().getEncoding()->name();
3398 showDialog("symbols", data);
3400 } else if (name == "prefs" && isFullScreen()) {
3401 lfunUiToggle("fullscreen");
3402 showDialog("prefs", data);
3404 showDialog(name, data);
3409 dr.setMessage(cmd.argument());
3412 case LFUN_UI_TOGGLE: {
3413 string arg = cmd.getArg(0);
3414 if (!lfunUiToggle(arg)) {
3415 docstring const msg = "ui-toggle " + _("%1$s unknown command!");
3416 dr.setMessage(bformat(msg, from_utf8(arg)));
3418 // Make sure the keyboard focus stays in the work area.
3423 case LFUN_SPLIT_VIEW: {
3424 LASSERT(doc_buffer, break);
3425 string const orientation = cmd.getArg(0);
3426 d.splitter_->setOrientation(orientation == "vertical"
3427 ? Qt::Vertical : Qt::Horizontal);
3428 TabWorkArea * twa = addTabWorkArea();
3429 GuiWorkArea * wa = twa->addWorkArea(*doc_buffer, *this);
3430 setCurrentWorkArea(wa);
3433 case LFUN_CLOSE_TAB_GROUP:
3434 if (TabWorkArea * twa = d.currentTabWorkArea()) {
3435 closeTabWorkArea(twa);
3436 d.current_work_area_ = 0;
3437 twa = d.currentTabWorkArea();
3438 // Switch to the next GuiWorkArea in the found TabWorkArea.
3440 // Make sure the work area is up to date.
3441 setCurrentWorkArea(twa->currentWorkArea());
3443 setCurrentWorkArea(0);
3448 case LFUN_COMPLETION_INLINE:
3449 if (d.current_work_area_)
3450 d.current_work_area_->completer().showInline();
3453 case LFUN_COMPLETION_POPUP:
3454 if (d.current_work_area_)
3455 d.current_work_area_->completer().showPopup();
3459 case LFUN_COMPLETION_COMPLETE:
3460 if (d.current_work_area_)
3461 d.current_work_area_->completer().tab();
3464 case LFUN_COMPLETION_CANCEL:
3465 if (d.current_work_area_) {
3466 if (d.current_work_area_->completer().popupVisible())
3467 d.current_work_area_->completer().hidePopup();
3469 d.current_work_area_->completer().hideInline();
3473 case LFUN_COMPLETION_ACCEPT:
3474 if (d.current_work_area_)
3475 d.current_work_area_->completer().activate();
3478 case LFUN_BUFFER_ZOOM_IN:
3479 case LFUN_BUFFER_ZOOM_OUT:
3480 if (cmd.argument().empty()) {
3481 if (cmd.action() == LFUN_BUFFER_ZOOM_IN)
3486 lyxrc.zoom += convert<int>(cmd.argument());
3488 if (lyxrc.zoom < 10)
3491 // The global QPixmapCache is used in GuiPainter to cache text
3492 // painting so we must reset it.
3493 QPixmapCache::clear();
3494 guiApp->fontLoader().update();
3495 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
3498 case LFUN_VC_REGISTER:
3499 case LFUN_VC_CHECK_IN:
3500 case LFUN_VC_CHECK_OUT:
3501 case LFUN_VC_REPO_UPDATE:
3502 case LFUN_VC_LOCKING_TOGGLE:
3503 case LFUN_VC_REVERT:
3504 case LFUN_VC_UNDO_LAST:
3505 case LFUN_VC_COMMAND:
3506 case LFUN_VC_COMPARE:
3507 dispatchVC(cmd, dr);
3510 case LFUN_SERVER_GOTO_FILE_ROW:
3511 goToFileRow(to_utf8(cmd.argument()));
3514 case LFUN_FORWARD_SEARCH: {
3515 FileName const path(doc_buffer->temppath());
3516 string const texname = doc_buffer->latexName();
3517 FileName const dviname(addName(path.absFileName(),
3518 support::changeExtension(texname, "dvi")));
3519 FileName const pdfname(addName(path.absFileName(),
3520 support::changeExtension(texname, "pdf")));
3521 if (!dviname.exists() && !pdfname.exists()) {
3522 dr.setMessage(_("Please, preview the document first."));
3525 string outname = dviname.onlyFileName();
3526 string command = lyxrc.forward_search_dvi;
3527 if (!dviname.exists() ||
3528 pdfname.lastModified() > dviname.lastModified()) {
3529 outname = pdfname.onlyFileName();
3530 command = lyxrc.forward_search_pdf;
3533 int row = doc_buffer->texrow().getRowFromIdPos(bv->cursor().paragraph().id(), bv->cursor().pos());
3534 LYXERR(Debug::ACTION, "Forward search: row:" << row
3535 << " id:" << bv->cursor().paragraph().id());
3536 if (!row || command.empty()) {
3537 dr.setMessage(_("Couldn't proceed."));
3540 string texrow = convert<string>(row);
3542 command = subst(command, "$$n", texrow);
3543 command = subst(command, "$$t", texname);
3544 command = subst(command, "$$o", outname);
3546 PathChanger p(path);
3548 one.startscript(Systemcall::DontWait, command);
3552 // The LFUN must be for one of BufferView, Buffer or Cursor;
3554 dispatchToBufferView(cmd, dr);
3558 // Part of automatic menu appearance feature.
3559 if (isFullScreen()) {
3560 if (menuBar()->isVisible() && lyxrc.full_screen_menubar)
3562 if (statusBar()->isVisible())
3563 statusBar()->hide();
3568 bool GuiView::lfunUiToggle(string const & ui_component)
3570 if (ui_component == "scrollbar") {
3571 // hide() is of no help
3572 if (d.current_work_area_->verticalScrollBarPolicy() ==
3573 Qt::ScrollBarAlwaysOff)
3575 d.current_work_area_->setVerticalScrollBarPolicy(
3576 Qt::ScrollBarAsNeeded);
3578 d.current_work_area_->setVerticalScrollBarPolicy(
3579 Qt::ScrollBarAlwaysOff);
3580 } else if (ui_component == "statusbar") {
3581 statusBar()->setVisible(!statusBar()->isVisible());
3582 } else if (ui_component == "menubar") {
3583 menuBar()->setVisible(!menuBar()->isVisible());
3585 #if QT_VERSION >= 0x040300
3586 if (ui_component == "frame") {
3588 getContentsMargins(&l, &t, &r, &b);
3589 //are the frames in default state?
3590 d.current_work_area_->setFrameStyle(QFrame::NoFrame);
3592 setContentsMargins(-2, -2, -2, -2);
3594 setContentsMargins(0, 0, 0, 0);
3598 if (ui_component == "fullscreen") {
3606 void GuiView::toggleFullScreen()
3608 if (isFullScreen()) {
3609 for (int i = 0; i != d.splitter_->count(); ++i)
3610 d.tabWorkArea(i)->setFullScreen(false);
3611 #if QT_VERSION >= 0x040300
3612 setContentsMargins(0, 0, 0, 0);
3614 setWindowState(windowState() ^ Qt::WindowFullScreen);
3617 statusBar()->show();
3620 hideDialogs("prefs", 0);
3621 for (int i = 0; i != d.splitter_->count(); ++i)
3622 d.tabWorkArea(i)->setFullScreen(true);
3623 #if QT_VERSION >= 0x040300
3624 setContentsMargins(-2, -2, -2, -2);
3627 setWindowState(windowState() ^ Qt::WindowFullScreen);
3628 statusBar()->hide();
3629 if (lyxrc.full_screen_menubar)
3631 if (lyxrc.full_screen_toolbars) {
3632 ToolbarMap::iterator end = d.toolbars_.end();
3633 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
3638 // give dialogs like the TOC a chance to adapt
3643 Buffer const * GuiView::updateInset(Inset const * inset)
3648 Buffer const * inset_buffer = &(inset->buffer());
3650 for (int i = 0; i != d.splitter_->count(); ++i) {
3651 GuiWorkArea * wa = d.tabWorkArea(i)->currentWorkArea();
3654 Buffer const * buffer = &(wa->bufferView().buffer());
3655 if (inset_buffer == buffer)
3656 wa->scheduleRedraw();
3658 return inset_buffer;
3662 void GuiView::restartCursor()
3664 /* When we move around, or type, it's nice to be able to see
3665 * the cursor immediately after the keypress.
3667 if (d.current_work_area_)
3668 d.current_work_area_->startBlinkingCursor();
3670 // Take this occasion to update the other GUI elements.
3676 void GuiView::updateCompletion(Cursor & cur, bool start, bool keep)
3678 if (d.current_work_area_)
3679 d.current_work_area_->completer().updateVisibility(cur, start, keep);
3684 // This list should be kept in sync with the list of insets in
3685 // src/insets/Inset.cpp. I.e., if a dialog goes with an inset, the
3686 // dialog should have the same name as the inset.
3687 // Changes should be also recorded in LFUN_DIALOG_SHOW doxygen
3688 // docs in LyXAction.cpp.
3690 char const * const dialognames[] = {
3692 "aboutlyx", "bibitem", "bibtex", "box", "branch", "changes", "character",
3693 "citation", "compare", "comparehistory", "document", "errorlist", "ert",
3694 "external", "file", "findreplace", "findreplaceadv", "float", "graphics",
3695 "href", "include", "index", "index_print", "info", "listings", "label", "line",
3696 "log", "mathdelimiter", "mathmatrix", "mathspace", "nomenclature",
3697 "nomencl_print", "note", "paragraph", "phantom", "prefs", "print", "ref",
3698 "sendto", "space", "spellchecker", "symbols", "tabular", "tabularcreate",
3699 "thesaurus", "texinfo", "toc", "view-source", "vspace", "wrap", "progress"};
3701 char const * const * const end_dialognames =
3702 dialognames + (sizeof(dialognames) / sizeof(char *));
3706 cmpCStr(char const * name) : name_(name) {}
3707 bool operator()(char const * other) {
3708 return strcmp(other, name_) == 0;
3715 bool isValidName(string const & name)
3717 return find_if(dialognames, end_dialognames,
3718 cmpCStr(name.c_str())) != end_dialognames;
3724 void GuiView::resetDialogs()
3726 // Make sure that no LFUN uses any GuiView.
3727 guiApp->setCurrentView(0);
3730 constructToolbars();
3731 guiApp->menus().fillMenuBar(menuBar(), this, false);
3732 d.layout_->updateContents(true);
3733 // Now update controls with current buffer.
3734 guiApp->setCurrentView(this);
3740 Dialog * GuiView::findOrBuild(string const & name, bool hide_it)
3742 if (!isValidName(name))
3745 map<string, DialogPtr>::iterator it = d.dialogs_.find(name);
3747 if (it != d.dialogs_.end()) {
3749 it->second->hideView();
3750 return it->second.get();
3753 Dialog * dialog = build(name);
3754 d.dialogs_[name].reset(dialog);
3755 if (lyxrc.allow_geometry_session)
3756 dialog->restoreSession();
3763 void GuiView::showDialog(string const & name, string const & data,
3766 triggerShowDialog(toqstr(name), toqstr(data), inset);
3770 void GuiView::doShowDialog(QString const & qname, QString const & qdata,
3776 const string name = fromqstr(qname);
3777 const string data = fromqstr(qdata);
3781 Dialog * dialog = findOrBuild(name, false);
3783 bool const visible = dialog->isVisibleView();
3784 dialog->showData(data);
3785 if (inset && currentBufferView())
3786 currentBufferView()->editInset(name, inset);
3787 // We only set the focus to the new dialog if it was not yet
3788 // visible in order not to change the existing previous behaviour
3790 // activateWindow is needed for floating dockviews
3791 dialog->asQWidget()->raise();
3792 dialog->asQWidget()->activateWindow();
3793 dialog->asQWidget()->setFocus();
3797 catch (ExceptionMessage const & ex) {
3805 bool GuiView::isDialogVisible(string const & name) const
3807 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3808 if (it == d.dialogs_.end())
3810 return it->second.get()->isVisibleView() && !it->second.get()->isClosing();
3814 void GuiView::hideDialog(string const & name, Inset * inset)
3816 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3817 if (it == d.dialogs_.end())
3820 if (inset && currentBufferView()
3821 && inset != currentBufferView()->editedInset(name))
3824 Dialog * const dialog = it->second.get();
3825 if (dialog->isVisibleView())
3827 if (currentBufferView())
3828 currentBufferView()->editInset(name, 0);
3832 void GuiView::disconnectDialog(string const & name)
3834 if (!isValidName(name))
3836 if (currentBufferView())
3837 currentBufferView()->editInset(name, 0);
3841 void GuiView::hideAll() const
3843 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
3844 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3846 for(; it != end; ++it)
3847 it->second->hideView();
3851 void GuiView::updateDialogs()
3853 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
3854 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3856 for(; it != end; ++it) {
3857 Dialog * dialog = it->second.get();
3859 if (dialog->needBufferOpen() && !documentBufferView())
3860 hideDialog(fromqstr(dialog->name()), 0);
3861 else if (dialog->isVisibleView())
3862 dialog->checkStatus();
3869 Dialog * createDialog(GuiView & lv, string const & name);
3871 // will be replaced by a proper factory...
3872 Dialog * createGuiAbout(GuiView & lv);
3873 Dialog * createGuiBibtex(GuiView & lv);
3874 Dialog * createGuiChanges(GuiView & lv);
3875 Dialog * createGuiCharacter(GuiView & lv);
3876 Dialog * createGuiCitation(GuiView & lv);
3877 Dialog * createGuiCompare(GuiView & lv);
3878 Dialog * createGuiCompareHistory(GuiView & lv);
3879 Dialog * createGuiDelimiter(GuiView & lv);
3880 Dialog * createGuiDocument(GuiView & lv);
3881 Dialog * createGuiErrorList(GuiView & lv);
3882 Dialog * createGuiExternal(GuiView & lv);
3883 Dialog * createGuiGraphics(GuiView & lv);
3884 Dialog * createGuiInclude(GuiView & lv);
3885 Dialog * createGuiIndex(GuiView & lv);
3886 Dialog * createGuiListings(GuiView & lv);
3887 Dialog * createGuiLog(GuiView & lv);
3888 Dialog * createGuiMathMatrix(GuiView & lv);
3889 Dialog * createGuiNote(GuiView & lv);
3890 Dialog * createGuiParagraph(GuiView & lv);
3891 Dialog * createGuiPhantom(GuiView & lv);
3892 Dialog * createGuiPreferences(GuiView & lv);
3893 Dialog * createGuiPrint(GuiView & lv);
3894 Dialog * createGuiPrintindex(GuiView & lv);
3895 Dialog * createGuiRef(GuiView & lv);
3896 Dialog * createGuiSearch(GuiView & lv);
3897 Dialog * createGuiSearchAdv(GuiView & lv);
3898 Dialog * createGuiSendTo(GuiView & lv);
3899 Dialog * createGuiShowFile(GuiView & lv);
3900 Dialog * createGuiSpellchecker(GuiView & lv);
3901 Dialog * createGuiSymbols(GuiView & lv);
3902 Dialog * createGuiTabularCreate(GuiView & lv);
3903 Dialog * createGuiTexInfo(GuiView & lv);
3904 Dialog * createGuiToc(GuiView & lv);
3905 Dialog * createGuiThesaurus(GuiView & lv);
3906 Dialog * createGuiViewSource(GuiView & lv);
3907 Dialog * createGuiWrap(GuiView & lv);
3908 Dialog * createGuiProgressView(GuiView & lv);
3912 Dialog * GuiView::build(string const & name)
3914 LASSERT(isValidName(name), return 0);
3916 Dialog * dialog = createDialog(*this, name);
3920 if (name == "aboutlyx")
3921 return createGuiAbout(*this);
3922 if (name == "bibtex")
3923 return createGuiBibtex(*this);
3924 if (name == "changes")
3925 return createGuiChanges(*this);
3926 if (name == "character")
3927 return createGuiCharacter(*this);
3928 if (name == "citation")
3929 return createGuiCitation(*this);
3930 if (name == "compare")
3931 return createGuiCompare(*this);
3932 if (name == "comparehistory")
3933 return createGuiCompareHistory(*this);
3934 if (name == "document")
3935 return createGuiDocument(*this);
3936 if (name == "errorlist")
3937 return createGuiErrorList(*this);
3938 if (name == "external")
3939 return createGuiExternal(*this);
3941 return createGuiShowFile(*this);
3942 if (name == "findreplace")
3943 return createGuiSearch(*this);
3944 if (name == "findreplaceadv")
3945 return createGuiSearchAdv(*this);
3946 if (name == "graphics")
3947 return createGuiGraphics(*this);
3948 if (name == "include")
3949 return createGuiInclude(*this);
3950 if (name == "index")
3951 return createGuiIndex(*this);
3952 if (name == "index_print")
3953 return createGuiPrintindex(*this);
3954 if (name == "listings")
3955 return createGuiListings(*this);
3957 return createGuiLog(*this);
3958 if (name == "mathdelimiter")
3959 return createGuiDelimiter(*this);
3960 if (name == "mathmatrix")
3961 return createGuiMathMatrix(*this);
3963 return createGuiNote(*this);
3964 if (name == "paragraph")
3965 return createGuiParagraph(*this);
3966 if (name == "phantom")
3967 return createGuiPhantom(*this);
3968 if (name == "prefs")
3969 return createGuiPreferences(*this);
3970 if (name == "print")
3971 return createGuiPrint(*this);
3973 return createGuiRef(*this);
3974 if (name == "sendto")
3975 return createGuiSendTo(*this);
3976 if (name == "spellchecker")
3977 return createGuiSpellchecker(*this);
3978 if (name == "symbols")
3979 return createGuiSymbols(*this);
3980 if (name == "tabularcreate")
3981 return createGuiTabularCreate(*this);
3982 if (name == "texinfo")
3983 return createGuiTexInfo(*this);
3984 if (name == "thesaurus")
3985 return createGuiThesaurus(*this);
3987 return createGuiToc(*this);
3988 if (name == "view-source")
3989 return createGuiViewSource(*this);
3991 return createGuiWrap(*this);
3992 if (name == "progress")
3993 return createGuiProgressView(*this);
3999 } // namespace frontend
4002 #include "moc_GuiView.cpp"