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 ErrorList & el = from_master ?
1459 currentBufferView()->buffer().masterBuffer()->errorList(error_type)
1460 : currentBufferView()->buffer().errorList(error_type);
1461 string data = error_type;
1463 data = "from_master|" + error_type;
1465 showDialog("errorlist", data);
1469 void GuiView::updateTocItem(string const & type, DocIterator const & dit)
1471 d.toc_models_.updateItem(toqstr(type), dit);
1475 void GuiView::structureChanged()
1477 d.toc_models_.reset(documentBufferView());
1478 // Navigator needs more than a simple update in this case. It needs to be
1480 updateDialog("toc", "");
1484 void GuiView::updateDialog(string const & name, string const & data)
1486 if (!isDialogVisible(name))
1489 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
1490 if (it == d.dialogs_.end())
1493 Dialog * const dialog = it->second.get();
1494 if (dialog->isVisibleView())
1495 dialog->initialiseParams(data);
1499 BufferView * GuiView::documentBufferView()
1501 return currentMainWorkArea()
1502 ? ¤tMainWorkArea()->bufferView()
1507 BufferView const * GuiView::documentBufferView() const
1509 return currentMainWorkArea()
1510 ? ¤tMainWorkArea()->bufferView()
1515 BufferView * GuiView::currentBufferView()
1517 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1521 BufferView const * GuiView::currentBufferView() const
1523 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1527 #if (QT_VERSION >= 0x040400)
1528 docstring GuiView::GuiViewPrivate::autosaveAndDestroy(
1529 Buffer const * orig, Buffer * buffer)
1531 bool const success = buffer->autoSave();
1533 busyBuffers.remove(orig);
1535 ? _("Automatic save done.")
1536 : _("Automatic save failed!");
1541 void GuiView::autoSave()
1543 LYXERR(Debug::INFO, "Running autoSave()");
1545 Buffer * buffer = documentBufferView()
1546 ? &documentBufferView()->buffer() : 0;
1550 #if (QT_VERSION >= 0x040400)
1551 GuiViewPrivate::busyBuffers.insert(buffer);
1552 QFuture<docstring> f = QtConcurrent::run(GuiViewPrivate::autosaveAndDestroy,
1553 buffer, buffer->clone());
1554 d.autosave_watcher_.setFuture(f);
1558 resetAutosaveTimers();
1562 void GuiView::resetAutosaveTimers()
1565 d.autosave_timeout_.restart();
1569 bool GuiView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1572 Buffer * buf = currentBufferView()
1573 ? ¤tBufferView()->buffer() : 0;
1574 Buffer * doc_buffer = documentBufferView()
1575 ? &(documentBufferView()->buffer()) : 0;
1577 // Check whether we need a buffer
1578 if (!lyxaction.funcHasFlag(cmd.action(), LyXAction::NoBuffer) && !buf) {
1579 // no, exit directly
1580 flag.message(from_utf8(N_("Command not allowed with"
1581 "out any document open")));
1582 flag.setEnabled(false);
1586 if (cmd.origin() == FuncRequest::TOC) {
1587 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
1588 if (!toc || !toc->getStatus(documentBufferView()->cursor(), cmd, flag))
1589 flag.setEnabled(false);
1593 switch(cmd.action()) {
1594 case LFUN_BUFFER_IMPORT:
1597 case LFUN_MASTER_BUFFER_UPDATE:
1598 case LFUN_MASTER_BUFFER_VIEW:
1599 enable = doc_buffer && doc_buffer->parent() != 0
1600 && !d.processing_thread_watcher_.isRunning();
1603 case LFUN_BUFFER_UPDATE:
1604 case LFUN_BUFFER_VIEW: {
1605 if (!doc_buffer || d.processing_thread_watcher_.isRunning()) {
1609 string format = to_utf8(cmd.argument());
1610 if (cmd.argument().empty())
1611 format = doc_buffer->getDefaultOutputFormat();
1612 enable = doc_buffer->isExportableFormat(format);
1616 case LFUN_BUFFER_RELOAD:
1617 enable = doc_buffer && !doc_buffer->isUnnamed()
1618 && doc_buffer->fileName().exists()
1619 && (!doc_buffer->isClean()
1620 || doc_buffer->isExternallyModified(Buffer::timestamp_method));
1623 case LFUN_BUFFER_CHILD_OPEN:
1624 enable = doc_buffer;
1627 case LFUN_BUFFER_WRITE:
1628 enable = doc_buffer && (doc_buffer->isUnnamed() || !doc_buffer->isClean());
1631 //FIXME: This LFUN should be moved to GuiApplication.
1632 case LFUN_BUFFER_WRITE_ALL: {
1633 // We enable the command only if there are some modified buffers
1634 Buffer * first = theBufferList().first();
1639 // We cannot use a for loop as the buffer list is a cycle.
1641 if (!b->isClean()) {
1645 b = theBufferList().next(b);
1646 } while (b != first);
1650 case LFUN_BUFFER_WRITE_AS:
1651 enable = doc_buffer;
1654 case LFUN_BUFFER_CLOSE:
1655 enable = doc_buffer;
1658 case LFUN_BUFFER_CLOSE_ALL:
1659 enable = theBufferList().last() != theBufferList().first();
1662 case LFUN_SPLIT_VIEW:
1663 if (cmd.getArg(0) == "vertical")
1664 enable = doc_buffer && (d.splitter_->count() == 1 ||
1665 d.splitter_->orientation() == Qt::Vertical);
1667 enable = doc_buffer && (d.splitter_->count() == 1 ||
1668 d.splitter_->orientation() == Qt::Horizontal);
1671 case LFUN_CLOSE_TAB_GROUP:
1672 enable = d.currentTabWorkArea();
1675 case LFUN_TOOLBAR_TOGGLE: {
1676 string const name = cmd.getArg(0);
1677 if (GuiToolbar * t = toolbar(name))
1678 flag.setOnOff(t->isVisible());
1681 docstring const msg =
1682 bformat(_("Unknown toolbar \"%1$s\""), from_utf8(name));
1688 case LFUN_DROP_LAYOUTS_CHOICE:
1692 case LFUN_UI_TOGGLE:
1693 flag.setOnOff(isFullScreen());
1696 case LFUN_DIALOG_DISCONNECT_INSET:
1699 case LFUN_DIALOG_HIDE:
1700 // FIXME: should we check if the dialog is shown?
1703 case LFUN_DIALOG_TOGGLE:
1704 flag.setOnOff(isDialogVisible(cmd.getArg(0)));
1705 // fall through to set "enable"
1706 case LFUN_DIALOG_SHOW: {
1707 string const name = cmd.getArg(0);
1709 enable = name == "aboutlyx"
1710 || name == "file" //FIXME: should be removed.
1712 || name == "texinfo"
1713 || name == "progress"
1714 || name == "compare";
1715 else if (name == "print")
1716 enable = doc_buffer->isExportable("dvi")
1717 && lyxrc.print_command != "none";
1718 else if (name == "character" || name == "symbols") {
1719 if (!buf || buf->isReadonly())
1722 // FIXME we should consider passthru
1724 Inset const & in = currentBufferView()->cursor().inset();
1725 enable = !in.getLayout().isPassThru();
1728 else if (name == "latexlog")
1729 enable = FileName(doc_buffer->logName()).isReadableFile();
1730 else if (name == "spellchecker")
1731 enable = theSpellChecker() && !doc_buffer->isReadonly();
1732 else if (name == "vclog")
1733 enable = doc_buffer->lyxvc().inUse();
1737 case LFUN_DIALOG_UPDATE: {
1738 string const name = cmd.getArg(0);
1740 enable = name == "prefs";
1744 case LFUN_COMMAND_EXECUTE:
1746 case LFUN_MENU_OPEN:
1747 // Nothing to check.
1750 case LFUN_COMPLETION_INLINE:
1751 if (!d.current_work_area_
1752 || !d.current_work_area_->completer().inlinePossible(
1753 currentBufferView()->cursor()))
1757 case LFUN_COMPLETION_POPUP:
1758 if (!d.current_work_area_
1759 || !d.current_work_area_->completer().popupPossible(
1760 currentBufferView()->cursor()))
1764 case LFUN_COMPLETION_COMPLETE:
1765 if (!d.current_work_area_
1766 || !d.current_work_area_->completer().inlinePossible(
1767 currentBufferView()->cursor()))
1771 case LFUN_COMPLETION_ACCEPT:
1772 if (!d.current_work_area_
1773 || (!d.current_work_area_->completer().popupVisible()
1774 && !d.current_work_area_->completer().inlineVisible()
1775 && !d.current_work_area_->completer().completionAvailable()))
1779 case LFUN_COMPLETION_CANCEL:
1780 if (!d.current_work_area_
1781 || (!d.current_work_area_->completer().popupVisible()
1782 && !d.current_work_area_->completer().inlineVisible()))
1786 case LFUN_BUFFER_ZOOM_OUT:
1787 enable = doc_buffer && lyxrc.zoom > 10;
1790 case LFUN_BUFFER_ZOOM_IN:
1791 enable = doc_buffer;
1794 case LFUN_BUFFER_NEXT:
1795 case LFUN_BUFFER_PREVIOUS:
1796 // FIXME: should we check is there is an previous or next buffer?
1798 case LFUN_BUFFER_SWITCH:
1799 // toggle on the current buffer, but do not toggle off
1800 // the other ones (is that a good idea?)
1802 && to_utf8(cmd.argument()) == doc_buffer->absFileName())
1803 flag.setOnOff(true);
1806 case LFUN_VC_REGISTER:
1807 enable = doc_buffer && !doc_buffer->lyxvc().inUse();
1809 case LFUN_VC_CHECK_IN:
1810 enable = doc_buffer && doc_buffer->lyxvc().checkInEnabled();
1812 case LFUN_VC_CHECK_OUT:
1813 enable = doc_buffer && doc_buffer->lyxvc().checkOutEnabled();
1815 case LFUN_VC_LOCKING_TOGGLE:
1816 enable = doc_buffer && !doc_buffer->isReadonly()
1817 && doc_buffer->lyxvc().lockingToggleEnabled();
1818 flag.setOnOff(enable && doc_buffer->lyxvc().locking());
1820 case LFUN_VC_REVERT:
1821 enable = doc_buffer && doc_buffer->lyxvc().inUse() && !doc_buffer->isReadonly();
1823 case LFUN_VC_UNDO_LAST:
1824 enable = doc_buffer && doc_buffer->lyxvc().undoLastEnabled();
1826 case LFUN_VC_REPO_UPDATE:
1827 enable = doc_buffer && doc_buffer->lyxvc().repoUpdateEnabled();
1829 case LFUN_VC_COMMAND: {
1830 if (cmd.argument().empty())
1832 if (!doc_buffer && contains(cmd.getArg(0), 'D'))
1836 case LFUN_VC_COMPARE:
1837 enable = doc_buffer && doc_buffer->lyxvc().prepareFileRevisionEnabled();
1840 case LFUN_SERVER_GOTO_FILE_ROW:
1842 case LFUN_FORWARD_SEARCH:
1843 enable = !(lyxrc.forward_search_dvi.empty() && lyxrc.forward_search_pdf.empty());
1851 flag.setEnabled(false);
1857 static FileName selectTemplateFile()
1859 FileDialog dlg(qt_("Select template file"));
1860 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1861 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
1863 FileDialog::Result result = dlg.open(toqstr(lyxrc.template_path),
1864 QStringList(qt_("LyX Documents (*.lyx)")));
1866 if (result.first == FileDialog::Later)
1868 if (result.second.isEmpty())
1870 return FileName(fromqstr(result.second));
1874 Buffer * GuiView::loadDocument(FileName const & filename, bool tolastfiles)
1878 Buffer * newBuffer = 0;
1880 newBuffer = checkAndLoadLyXFile(filename);
1881 } catch (ExceptionMessage const & e) {
1887 message(_("Document not loaded."));
1892 newBuffer->errors("Parse");
1893 setBuffer(newBuffer);
1896 theSession().lastFiles().add(filename);
1903 void GuiView::openDocument(string const & fname)
1905 string initpath = lyxrc.document_path;
1907 if (documentBufferView()) {
1908 string const trypath = documentBufferView()->buffer().filePath();
1909 // If directory is writeable, use this as default.
1910 if (FileName(trypath).isDirWritable())
1916 if (fname.empty()) {
1917 FileDialog dlg(qt_("Select document to open"), LFUN_FILE_OPEN);
1918 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1919 dlg.setButton2(qt_("Examples|#E#e"),
1920 toqstr(addPath(package().system_support().absFileName(), "examples")));
1922 QStringList filter(qt_("LyX Documents (*.lyx)"));
1923 filter << qt_("LyX-1.3.x Documents (*.lyx13)")
1924 << qt_("LyX-1.4.x Documents (*.lyx14)")
1925 << qt_("LyX-1.5.x Documents (*.lyx15)")
1926 << qt_("LyX-1.6.x Documents (*.lyx16)");
1927 FileDialog::Result result =
1928 dlg.open(toqstr(initpath), filter);
1930 if (result.first == FileDialog::Later)
1933 filename = fromqstr(result.second);
1935 // check selected filename
1936 if (filename.empty()) {
1937 message(_("Canceled."));
1943 // get absolute path of file and add ".lyx" to the filename if
1945 FileName const fullname =
1946 fileSearch(string(), filename, "lyx", support::may_not_exist);
1947 if (!fullname.empty())
1948 filename = fullname.absFileName();
1950 if (!fullname.onlyPath().isDirectory()) {
1951 Alert::warning(_("Invalid filename"),
1952 bformat(_("The directory in the given path\n%1$s\ndoes not exist."),
1953 from_utf8(fullname.absFileName())));
1957 // if the file doesn't exist and isn't already open (bug 6645),
1958 // let the user create one
1959 if (!fullname.exists() && !theBufferList().exists(fullname)) {
1960 // the user specifically chose this name. Believe him.
1961 Buffer * const b = newFile(filename, string(), true);
1967 docstring const disp_fn = makeDisplayPath(filename);
1968 message(bformat(_("Opening document %1$s..."), disp_fn));
1971 Buffer * buf = loadDocument(fullname);
1973 str2 = bformat(_("Document %1$s opened."), disp_fn);
1974 if (buf->lyxvc().inUse())
1975 str2 += " " + from_utf8(buf->lyxvc().versionString()) +
1976 " " + _("Version control detected.");
1978 str2 = bformat(_("Could not open document %1$s"), disp_fn);
1983 // FIXME: clean that
1984 static bool import(GuiView * lv, FileName const & filename,
1985 string const & format, ErrorList & errorList)
1987 FileName const lyxfile(support::changeExtension(filename.absFileName(), ".lyx"));
1989 string loader_format;
1990 vector<string> loaders = theConverters().loaders();
1991 if (find(loaders.begin(), loaders.end(), format) == loaders.end()) {
1992 for (vector<string>::const_iterator it = loaders.begin();
1993 it != loaders.end(); ++it) {
1994 if (!theConverters().isReachable(format, *it))
1997 string const tofile =
1998 support::changeExtension(filename.absFileName(),
1999 formats.extension(*it));
2000 if (!theConverters().convert(0, filename, FileName(tofile),
2001 filename, format, *it, errorList))
2003 loader_format = *it;
2006 if (loader_format.empty()) {
2007 frontend::Alert::error(_("Couldn't import file"),
2008 bformat(_("No information for importing the format %1$s."),
2009 formats.prettyName(format)));
2013 loader_format = format;
2015 if (loader_format == "lyx") {
2016 Buffer * buf = lv->loadDocument(lyxfile);
2020 Buffer * const b = newFile(lyxfile.absFileName(), string(), true);
2024 bool as_paragraphs = loader_format == "textparagraph";
2025 string filename2 = (loader_format == format) ? filename.absFileName()
2026 : support::changeExtension(filename.absFileName(),
2027 formats.extension(loader_format));
2028 lv->currentBufferView()->insertPlaintextFile(FileName(filename2),
2030 guiApp->setCurrentView(lv);
2031 lyx::dispatch(FuncRequest(LFUN_MARK_OFF));
2038 void GuiView::importDocument(string const & argument)
2041 string filename = split(argument, format, ' ');
2043 LYXERR(Debug::INFO, format << " file: " << filename);
2045 // need user interaction
2046 if (filename.empty()) {
2047 string initpath = lyxrc.document_path;
2048 if (documentBufferView()) {
2049 string const trypath = documentBufferView()->buffer().filePath();
2050 // If directory is writeable, use this as default.
2051 if (FileName(trypath).isDirWritable())
2055 docstring const text = bformat(_("Select %1$s file to import"),
2056 formats.prettyName(format));
2058 FileDialog dlg(toqstr(text), LFUN_BUFFER_IMPORT);
2059 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2060 dlg.setButton2(qt_("Examples|#E#e"),
2061 toqstr(addPath(package().system_support().absFileName(), "examples")));
2063 docstring filter = formats.prettyName(format);
2066 filter += from_utf8(formats.extension(format));
2069 FileDialog::Result result =
2070 dlg.open(toqstr(initpath), fileFilters(toqstr(filter)));
2072 if (result.first == FileDialog::Later)
2075 filename = fromqstr(result.second);
2077 // check selected filename
2078 if (filename.empty())
2079 message(_("Canceled."));
2082 if (filename.empty())
2085 // get absolute path of file
2086 FileName const fullname(support::makeAbsPath(filename));
2088 FileName const lyxfile(support::changeExtension(fullname.absFileName(), ".lyx"));
2090 // Check if the document already is open
2091 Buffer * buf = theBufferList().getBuffer(lyxfile);
2094 if (!closeBuffer()) {
2095 message(_("Canceled."));
2100 docstring const displaypath = makeDisplayPath(lyxfile.absFileName(), 30);
2102 // if the file exists already, and we didn't do
2103 // -i lyx thefile.lyx, warn
2104 if (lyxfile.exists() && fullname != lyxfile) {
2106 docstring text = bformat(_("The document %1$s already exists.\n\n"
2107 "Do you want to overwrite that document?"), displaypath);
2108 int const ret = Alert::prompt(_("Overwrite document?"),
2109 text, 0, 1, _("&Overwrite"), _("&Cancel"));
2112 message(_("Canceled."));
2117 message(bformat(_("Importing %1$s..."), displaypath));
2118 ErrorList errorList;
2119 if (import(this, fullname, format, errorList))
2120 message(_("imported."));
2122 message(_("file not imported!"));
2124 // FIXME (Abdel 12/08/06): Is there a need to display the error list here?
2128 void GuiView::newDocument(string const & filename, bool from_template)
2130 FileName initpath(lyxrc.document_path);
2131 if (documentBufferView()) {
2132 FileName const trypath(documentBufferView()->buffer().filePath());
2133 // If directory is writeable, use this as default.
2134 if (trypath.isDirWritable())
2138 string templatefile;
2139 if (from_template) {
2140 templatefile = selectTemplateFile().absFileName();
2141 if (templatefile.empty())
2146 if (filename.empty())
2147 b = newUnnamedFile(initpath, to_utf8(_("newfile")), templatefile);
2149 b = newFile(filename, templatefile, true);
2154 // If no new document could be created, it is unsure
2155 // whether there is a valid BufferView.
2156 if (currentBufferView())
2157 // Ensure the cursor is correctly positioned on screen.
2158 currentBufferView()->showCursor();
2162 void GuiView::insertLyXFile(docstring const & fname)
2164 BufferView * bv = documentBufferView();
2169 FileName filename(to_utf8(fname));
2170 if (filename.empty()) {
2171 // Launch a file browser
2173 string initpath = lyxrc.document_path;
2174 string const trypath = bv->buffer().filePath();
2175 // If directory is writeable, use this as default.
2176 if (FileName(trypath).isDirWritable())
2180 FileDialog dlg(qt_("Select LyX document to insert"), LFUN_FILE_INSERT);
2181 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2182 dlg.setButton2(qt_("Examples|#E#e"),
2183 toqstr(addPath(package().system_support().absFileName(),
2186 FileDialog::Result result = dlg.open(toqstr(initpath),
2187 QStringList(qt_("LyX Documents (*.lyx)")));
2189 if (result.first == FileDialog::Later)
2193 filename.set(fromqstr(result.second));
2195 // check selected filename
2196 if (filename.empty()) {
2197 // emit message signal.
2198 message(_("Canceled."));
2203 bv->insertLyXFile(filename);
2204 bv->buffer().errors("Parse");
2208 void GuiView::insertPlaintextFile(docstring const & fname,
2211 BufferView * bv = documentBufferView();
2215 if (!fname.empty() && !FileName::isAbsolute(to_utf8(fname))) {
2216 message(_("Absolute filename expected."));
2221 FileName filename(to_utf8(fname));
2223 if (!filename.empty()) {
2224 bv->insertPlaintextFile(filename, asParagraph);
2228 FileDialog dlg(qt_("Select file to insert"), (asParagraph ?
2229 LFUN_FILE_INSERT_PLAINTEXT_PARA : LFUN_FILE_INSERT_PLAINTEXT));
2231 FileDialog::Result result = dlg.open(toqstr(bv->buffer().filePath()),
2232 QStringList(qt_("All Files (*)")));
2234 if (result.first == FileDialog::Later)
2238 filename.set(fromqstr(result.second));
2240 // check selected filename
2241 if (filename.empty()) {
2242 // emit message signal.
2243 message(_("Canceled."));
2247 bv->insertPlaintextFile(filename, asParagraph);
2251 bool GuiView::renameBuffer(Buffer & b, docstring const & newname)
2253 FileName fname = b.fileName();
2254 FileName const oldname = fname;
2256 if (!newname.empty()) {
2258 fname = support::makeAbsPath(to_utf8(newname), oldname.onlyPath().absFileName());
2260 // Switch to this Buffer.
2263 // No argument? Ask user through dialog.
2265 FileDialog dlg(qt_("Choose a filename to save document as"),
2266 LFUN_BUFFER_WRITE_AS);
2267 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2268 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
2270 if (!isLyXFileName(fname.absFileName()))
2271 fname.changeExtension(".lyx");
2273 FileDialog::Result result =
2274 dlg.save(toqstr(fname.onlyPath().absFileName()),
2275 QStringList(qt_("LyX Documents (*.lyx)")),
2276 toqstr(fname.onlyFileName()));
2278 if (result.first == FileDialog::Later)
2281 fname.set(fromqstr(result.second));
2286 if (!isLyXFileName(fname.absFileName()))
2287 fname.changeExtension(".lyx");
2290 // fname is now the new Buffer location.
2291 if (FileName(fname).exists()) {
2292 docstring const file = makeDisplayPath(fname.absFileName(), 30);
2293 docstring text = bformat(_("The document %1$s already "
2294 "exists.\n\nDo you want to "
2295 "overwrite that document?"),
2297 int const ret = Alert::prompt(_("Overwrite document?"),
2298 text, 0, 2, _("&Overwrite"), _("&Rename"), _("&Cancel"));
2301 case 1: return renameBuffer(b, docstring());
2302 case 2: return false;
2306 return saveBuffer(b, fname);
2310 bool GuiView::saveBuffer(Buffer & b) {
2311 return saveBuffer(b, FileName());
2315 bool GuiView::saveBuffer(Buffer & b, FileName const & fn)
2317 if (workArea(b) && workArea(b)->inDialogMode())
2320 if (fn.empty() && b.isUnnamed())
2321 return renameBuffer(b, docstring());
2327 success = b.saveAs(fn);
2330 theSession().lastFiles().add(b.fileName());
2334 // Switch to this Buffer.
2337 // FIXME: we don't tell the user *WHY* the save failed !!
2338 docstring const file = makeDisplayPath(b.absFileName(), 30);
2339 docstring text = bformat(_("The document %1$s could not be saved.\n\n"
2340 "Do you want to rename the document and "
2341 "try again?"), file);
2342 int const ret = Alert::prompt(_("Rename and save?"),
2343 text, 0, 2, _("&Rename"), _("&Retry"), _("&Cancel"));
2346 if (!renameBuffer(b, docstring()))
2355 return saveBuffer(b);
2359 bool GuiView::hideWorkArea(GuiWorkArea * wa)
2361 return closeWorkArea(wa, false);
2365 bool GuiView::closeWorkArea(GuiWorkArea * wa)
2367 Buffer & buf = wa->bufferView().buffer();
2368 return closeWorkArea(wa, !buf.parent());
2372 bool GuiView::closeBuffer()
2374 GuiWorkArea * wa = currentMainWorkArea();
2375 setCurrentWorkArea(wa);
2376 Buffer & buf = wa->bufferView().buffer();
2377 return wa && closeWorkArea(wa, !buf.parent());
2381 void GuiView::writeSession() const {
2382 GuiWorkArea const * active_wa = currentMainWorkArea();
2383 for (int i = 0; i < d.splitter_->count(); ++i) {
2384 TabWorkArea * twa = d.tabWorkArea(i);
2385 for (int j = 0; j < twa->count(); ++j) {
2386 GuiWorkArea * wa = static_cast<GuiWorkArea *>(twa->widget(j));
2387 Buffer & buf = wa->bufferView().buffer();
2388 theSession().lastOpened().add(buf.fileName(), wa == active_wa);
2394 bool GuiView::closeBufferAll()
2396 // Close the workareas in all other views
2397 QList<int> const ids = guiApp->viewIds();
2398 for (int i = 0; i != ids.size(); ++i) {
2399 if (id_ != ids[i] && !guiApp->view(ids[i]).closeWorkAreaAll())
2403 // Close our own workareas
2404 if (!closeWorkAreaAll())
2407 // Now close the hidden buffers. We prevent hidden buffers from being
2408 // dirty, so we can just close them.
2409 theBufferList().closeAll();
2414 bool GuiView::closeWorkAreaAll()
2416 setCurrentWorkArea(currentMainWorkArea());
2418 // We might be in a situation that there is still a tabWorkArea, but
2419 // there are no tabs anymore. This can happen when we get here after a
2420 // TabWorkArea::lastWorkAreaRemoved() signal. Therefore we count how
2421 // many TabWorkArea's have no documents anymore.
2424 // We have to call count() each time, because it can happen that
2425 // more than one splitter will disappear in one iteration (bug 5998).
2426 for (; d.splitter_->count() > empty_twa; ) {
2427 TabWorkArea * twa = d.tabWorkArea(empty_twa);
2429 if (twa->count() == 0)
2432 setCurrentWorkArea(twa->currentWorkArea());
2433 if (!closeTabWorkArea(twa))
2441 bool GuiView::closeWorkArea(GuiWorkArea * wa, bool close_buffer)
2446 Buffer & buf = wa->bufferView().buffer();
2448 if (close_buffer && GuiViewPrivate::busyBuffers.contains(&buf)) {
2449 Alert::warning(_("Close document"),
2450 _("Document could not be closed because it is being processed by LyX."));
2455 return closeBuffer(buf);
2457 if (!inMultiTabs(wa))
2458 if (!saveBufferIfNeeded(buf, true))
2466 bool GuiView::closeBuffer(Buffer & buf)
2468 // If we are in a close_event all children will be closed in some time,
2469 // so no need to do it here. This will ensure that the children end up
2470 // in the session file in the correct order. If we close the master
2471 // buffer, we can close or release the child buffers here too.
2473 ListOfBuffers clist = buf.getChildren();
2474 ListOfBuffers::const_iterator it = clist.begin();
2475 ListOfBuffers::const_iterator const bend = clist.end();
2476 for (; it != bend; ++it) {
2477 // If a child is dirty, do not close
2478 // without user intervention
2479 //FIXME: should we look in other tabworkareas?
2480 Buffer * child_buf = *it;
2481 GuiWorkArea * child_wa = workArea(*child_buf);
2483 if (!closeWorkArea(child_wa, true))
2486 theBufferList().releaseChild(&buf, child_buf);
2489 // goto bookmark to update bookmark pit.
2490 //FIXME: we should update only the bookmarks related to this buffer!
2491 LYXERR(Debug::DEBUG, "GuiView::closeBuffer()");
2492 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
2493 guiApp->gotoBookmark(i+1, false, false);
2495 if (saveBufferIfNeeded(buf, false)) {
2496 buf.removeAutosaveFile();
2497 theBufferList().release(&buf);
2500 // open all children again to avoid a crash (bug 6603)
2501 // FIXME updateMacros() does more than needed
2503 // get rid of dangling inset pointers in TOC (bug 6603)
2504 buf.tocBackend().update();
2509 bool GuiView::closeTabWorkArea(TabWorkArea * twa)
2511 while (twa == d.currentTabWorkArea()) {
2512 twa->setCurrentIndex(twa->count()-1);
2514 GuiWorkArea * wa = twa->currentWorkArea();
2515 Buffer & b = wa->bufferView().buffer();
2517 // We only want to close the buffer if the same buffer is not visible
2518 // in another view, and if this is not a child and if we are closing
2519 // a view (not a tabgroup).
2520 bool const close_buffer =
2521 !inMultiViews(wa) && !b.parent() && closing_;
2523 if (!closeWorkArea(wa, close_buffer))
2530 bool GuiView::saveBufferIfNeeded(Buffer & buf, bool hiding)
2532 if (buf.isClean() || buf.paragraphs().empty())
2535 // Switch to this Buffer.
2540 if (buf.isUnnamed())
2541 file = from_utf8(buf.fileName().onlyFileName());
2543 file = buf.fileName().displayName(30);
2545 // Bring this window to top before asking questions.
2550 if (hiding && buf.isUnnamed()) {
2551 docstring const text = bformat(_("The document %1$s has not been "
2552 "saved yet.\n\nDo you want to save "
2553 "the document?"), file);
2554 ret = Alert::prompt(_("Save new document?"),
2555 text, 0, 1, _("&Save"), _("&Cancel"));
2559 docstring const text = bformat(_("The document %1$s has unsaved changes."
2560 "\n\nDo you want to save the document or discard the changes?"), file);
2561 ret = Alert::prompt(_("Save changed document?"),
2562 text, 0, 2, _("&Save"), _("&Discard"), _("&Cancel"));
2567 if (!saveBuffer(buf))
2571 // If we crash after this we could have no autosave file
2572 // but I guess this is really improbable (Jug).
2573 // Sometimes improbable things happen:
2574 // - see bug http://www.lyx.org/trac/ticket/6587 (ps)
2575 // buf.removeAutosaveFile();
2577 // revert all changes
2588 bool GuiView::inMultiTabs(GuiWorkArea * wa)
2590 Buffer & buf = wa->bufferView().buffer();
2592 for (int i = 0; i != d.splitter_->count(); ++i) {
2593 GuiWorkArea * wa_ = d.tabWorkArea(i)->workArea(buf);
2594 if (wa_ && wa_ != wa)
2597 return inMultiViews(wa);
2601 bool GuiView::inMultiViews(GuiWorkArea * wa)
2603 QList<int> const ids = guiApp->viewIds();
2604 Buffer & buf = wa->bufferView().buffer();
2607 for (int i = 0; i != ids.size() && found_twa <= 1; ++i) {
2611 if (guiApp->view(ids[i]).workArea(buf))
2618 void GuiView::gotoNextOrPreviousBuffer(NextOrPrevious np)
2620 if (!documentBufferView())
2623 if (TabWorkArea * twa = d.currentTabWorkArea()) {
2624 Buffer * const curbuf = &documentBufferView()->buffer();
2625 int nwa = twa->count();
2626 for (int i = 0; i < nwa; ++i) {
2627 if (&workArea(i)->bufferView().buffer() == curbuf) {
2629 if (np == NEXTBUFFER)
2630 next_index = (i == nwa - 1 ? 0 : i + 1);
2632 next_index = (i == 0 ? nwa - 1 : i - 1);
2633 setBuffer(&workArea(next_index)->bufferView().buffer());
2641 /// make sure the document is saved
2642 static bool ensureBufferClean(Buffer * buffer)
2644 LASSERT(buffer, return false);
2645 if (buffer->isClean() && !buffer->isUnnamed())
2648 docstring const file = buffer->fileName().displayName(30);
2651 if (!buffer->isUnnamed()) {
2652 text = bformat(_("The document %1$s has unsaved "
2653 "changes.\n\nDo you want to save "
2654 "the document?"), file);
2655 title = _("Save changed document?");
2658 text = bformat(_("The document %1$s has not been "
2659 "saved yet.\n\nDo you want to save "
2660 "the document?"), file);
2661 title = _("Save new document?");
2663 int const ret = Alert::prompt(title, text, 0, 1, _("&Save"), _("&Cancel"));
2666 dispatch(FuncRequest(LFUN_BUFFER_WRITE));
2668 return buffer->isClean() && !buffer->isUnnamed();
2672 bool GuiView::reloadBuffer(Buffer & buf)
2674 Buffer::ReadStatus status = buf.reload();
2675 return status == Buffer::ReadSuccess;
2679 void GuiView::checkExternallyModifiedBuffers()
2681 BufferList::iterator bit = theBufferList().begin();
2682 BufferList::iterator const bend = theBufferList().end();
2683 for (; bit != bend; ++bit) {
2684 Buffer * buf = *bit;
2685 if (buf->fileName().exists()
2686 && buf->isExternallyModified(Buffer::checksum_method)) {
2687 docstring text = bformat(_("Document \n%1$s\n has been externally modified."
2688 " Reload now? Any local changes will be lost."),
2689 from_utf8(buf->absFileName()));
2690 int const ret = Alert::prompt(_("Reload externally changed document?"),
2691 text, 0, 1, _("&Reload"), _("&Cancel"));
2699 void GuiView::dispatchVC(FuncRequest const & cmd, DispatchResult & dr)
2701 Buffer * buffer = documentBufferView()
2702 ? &(documentBufferView()->buffer()) : 0;
2704 switch (cmd.action()) {
2705 case LFUN_VC_REGISTER:
2706 if (!buffer || !ensureBufferClean(buffer))
2708 if (!buffer->lyxvc().inUse()) {
2709 if (buffer->lyxvc().registrer()) {
2710 reloadBuffer(*buffer);
2711 dr.suppressMessageUpdate();
2716 case LFUN_VC_CHECK_IN:
2717 if (!buffer || !ensureBufferClean(buffer))
2719 if (buffer->lyxvc().inUse() && !buffer->isReadonly()) {
2720 dr.setMessage(buffer->lyxvc().checkIn());
2721 if (!dr.message().empty())
2722 reloadBuffer(*buffer);
2726 case LFUN_VC_CHECK_OUT:
2727 if (!buffer || !ensureBufferClean(buffer))
2729 if (buffer->lyxvc().inUse()) {
2730 dr.setMessage(buffer->lyxvc().checkOut());
2731 reloadBuffer(*buffer);
2735 case LFUN_VC_LOCKING_TOGGLE:
2736 LASSERT(buffer, return);
2737 if (!ensureBufferClean(buffer) || buffer->isReadonly())
2739 if (buffer->lyxvc().inUse()) {
2740 string res = buffer->lyxvc().lockingToggle();
2742 frontend::Alert::error(_("Revision control error."),
2743 _("Error when setting the locking property."));
2746 reloadBuffer(*buffer);
2751 case LFUN_VC_REVERT:
2752 LASSERT(buffer, return);
2753 if (buffer->lyxvc().revert()) {
2754 reloadBuffer(*buffer);
2755 dr.suppressMessageUpdate();
2759 case LFUN_VC_UNDO_LAST:
2760 LASSERT(buffer, return);
2761 buffer->lyxvc().undoLast();
2762 reloadBuffer(*buffer);
2763 dr.suppressMessageUpdate();
2766 case LFUN_VC_REPO_UPDATE:
2767 LASSERT(buffer, return);
2768 if (ensureBufferClean(buffer)) {
2769 dr.setMessage(buffer->lyxvc().repoUpdate());
2770 checkExternallyModifiedBuffers();
2774 case LFUN_VC_COMMAND: {
2775 string flag = cmd.getArg(0);
2776 if (buffer && contains(flag, 'R') && !ensureBufferClean(buffer))
2779 if (contains(flag, 'M')) {
2780 if (!Alert::askForText(message, _("LyX VC: Log Message")))
2783 string path = cmd.getArg(1);
2784 if (contains(path, "$$p") && buffer)
2785 path = subst(path, "$$p", buffer->filePath());
2786 LYXERR(Debug::LYXVC, "Directory: " << path);
2788 if (!pp.isReadableDirectory()) {
2789 lyxerr << _("Directory is not accessible.") << endl;
2792 support::PathChanger p(pp);
2794 string command = cmd.getArg(2);
2795 if (command.empty())
2798 command = subst(command, "$$i", buffer->absFileName());
2799 command = subst(command, "$$p", buffer->filePath());
2801 command = subst(command, "$$m", to_utf8(message));
2802 LYXERR(Debug::LYXVC, "Command: " << command);
2804 one.startscript(Systemcall::Wait, command);
2808 if (contains(flag, 'I'))
2809 buffer->markDirty();
2810 if (contains(flag, 'R'))
2811 reloadBuffer(*buffer);
2816 case LFUN_VC_COMPARE: {
2818 if (cmd.argument().empty()) {
2819 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "comparehistory"));
2823 string rev1 = cmd.getArg(0);
2827 if (!buffer->lyxvc().prepareFileRevision(rev1, f1))
2830 if (isStrInt(rev1) && convert<int>(rev1) <= 0) {
2831 f2 = buffer->absFileName();
2833 string rev2 = cmd.getArg(1);
2837 if (!buffer->lyxvc().prepareFileRevision(rev2, f2))
2841 LYXERR(Debug::LYXVC, "Launching comparison for fetched revisions:\n" <<
2842 f1 << "\n" << f2 << "\n" );
2843 string par = "compare run " + quoteName(f1) + " " + quoteName(f2);
2844 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, par));
2854 void GuiView::openChildDocument(string const & fname)
2856 LASSERT(documentBufferView(), return);
2857 Buffer & buffer = documentBufferView()->buffer();
2858 FileName const filename = support::makeAbsPath(fname, buffer.filePath());
2859 documentBufferView()->saveBookmark(false);
2861 if (theBufferList().exists(filename)) {
2862 child = theBufferList().getBuffer(filename);
2865 message(bformat(_("Opening child document %1$s..."),
2866 makeDisplayPath(filename.absFileName())));
2867 child = loadDocument(filename, false);
2869 // Set the parent name of the child document.
2870 // This makes insertion of citations and references in the child work,
2871 // when the target is in the parent or another child document.
2873 child->setParent(&buffer);
2877 bool GuiView::goToFileRow(string const & argument)
2881 size_t i = argument.find_last_of(' ');
2882 if (i != string::npos) {
2883 file_name = os::internal_path(trim(argument.substr(0, i)));
2884 istringstream is(argument.substr(i + 1));
2889 if (i == string::npos) {
2890 LYXERR0("Wrong argument: " << argument);
2894 string const abstmp = package().temp_dir().absFileName();
2895 string const realtmp = package().temp_dir().realPath();
2896 // We have to use os::path_prefix_is() here, instead of
2897 // simply prefixIs(), because the file name comes from
2898 // an external application and may need case adjustment.
2899 if (os::path_prefix_is(file_name, abstmp, os::CASE_ADJUSTED)
2900 || os::path_prefix_is(file_name, realtmp, os::CASE_ADJUSTED)) {
2901 // Needed by inverse dvi search. If it is a file
2902 // in tmpdir, call the apropriated function.
2903 // If tmpdir is a symlink, we may have the real
2904 // path passed back, so we correct for that.
2905 if (!prefixIs(file_name, abstmp))
2906 file_name = subst(file_name, realtmp, abstmp);
2907 buf = theBufferList().getBufferFromTmp(file_name);
2909 // Must replace extension of the file to be .lyx
2910 // and get full path
2911 FileName const s = fileSearch(string(),
2912 support::changeExtension(file_name, ".lyx"), "lyx");
2913 // Either change buffer or load the file
2914 if (theBufferList().exists(s))
2915 buf = theBufferList().getBuffer(s);
2916 else if (s.exists()) {
2917 buf = loadDocument(s);
2922 _("File does not exist: %1$s"),
2923 makeDisplayPath(file_name)));
2928 documentBufferView()->setCursorFromRow(row);
2933 #if (QT_VERSION >= 0x040400)
2935 docstring GuiView::GuiViewPrivate::runAndDestroy(const T& func, Buffer const * orig, Buffer * buffer, string const & format, string const & msg)
2937 bool const update_unincluded =
2938 buffer->params().maintain_unincluded_children
2939 && !buffer->params().getIncludedChildren().empty();
2940 bool const success = func(format, update_unincluded);
2942 busyBuffers.remove(orig);
2943 if (msg == "preview") {
2945 ? bformat(_("Successful preview of format: %1$s"), from_utf8(format))
2946 : bformat(_("Error while previewing format: %1$s"), from_utf8(format));
2949 ? bformat(_("Successful export to format: %1$s"), from_utf8(format))
2950 : bformat(_("Error while exporting format: %1$s"), from_utf8(format));
2954 docstring GuiView::GuiViewPrivate::compileAndDestroy(Buffer const * orig, Buffer * buffer, string const & format)
2956 bool (Buffer::* mem_func)(std::string const &, bool, bool) const = &Buffer::doExport;
2957 return runAndDestroy(bind(mem_func, buffer, _1, true, _2), orig, buffer, format, "export");
2961 docstring GuiView::GuiViewPrivate::exportAndDestroy(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, false, _2), orig, buffer, format, "export");
2968 docstring GuiView::GuiViewPrivate::previewAndDestroy(Buffer const * orig, Buffer * buffer, string const & format)
2970 bool(Buffer::* mem_func)(std::string const &, bool) const = &Buffer::preview;
2971 return runAndDestroy(bind(mem_func, buffer, _1, _2), orig, buffer, format, "preview");
2976 // not used, but the linker needs them
2978 docstring GuiView::GuiViewPrivate::compileAndDestroy(
2979 Buffer const *, Buffer *, string const &)
2985 docstring GuiView::GuiViewPrivate::exportAndDestroy(
2986 Buffer const *, Buffer *, string const &)
2992 docstring GuiView::GuiViewPrivate::previewAndDestroy(
2993 Buffer const *, Buffer *, string const &)
3001 bool GuiView::GuiViewPrivate::asyncBufferProcessing(
3002 string const & argument,
3003 Buffer const * used_buffer,
3004 docstring const & msg,
3005 docstring (*asyncFunc)(Buffer const *, Buffer *, string const &),
3006 bool (Buffer::*syncFunc)(string const &, bool, bool) const,
3007 bool (Buffer::*previewFunc)(string const &, bool) const)
3012 string format = argument;
3014 format = used_buffer->getDefaultOutputFormat();
3016 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
3017 gv_->processingThreadStarted();
3019 progress_->clearMessages();
3022 GuiViewPrivate::busyBuffers.insert(used_buffer);
3023 QFuture<docstring> f = QtConcurrent::run(
3026 used_buffer->clone(),
3028 setPreviewFuture(f);
3029 last_export_format = used_buffer->bufferFormat();
3032 // We are asynchronous, so we don't know here anything about the success
3036 // TODO check here if it breaks exporting with Qt < 4.4
3037 bool const update_unincluded =
3038 used_buffer->params().maintain_unincluded_children &&
3039 !used_buffer->params().getIncludedChildren().empty();
3040 return (used_buffer->*syncFunc)(format, true, update_unincluded);
3041 } else if (previewFunc) {
3042 return (used_buffer->*previewFunc)(format, false);
3049 void GuiView::dispatchToBufferView(FuncRequest const & cmd, DispatchResult & dr)
3051 BufferView * bv = currentBufferView();
3054 // Let the current BufferView dispatch its own actions.
3055 bv->dispatch(cmd, dr);
3056 if (dr.dispatched())
3059 // Try with the document BufferView dispatch if any.
3060 BufferView * doc_bv = documentBufferView();
3062 doc_bv->dispatch(cmd, dr);
3063 if (dr.dispatched())
3067 // Then let the current Cursor dispatch its own actions.
3068 bv->cursor().dispatch(cmd);
3070 // update completion. We do it here and not in
3071 // processKeySym to avoid another redraw just for a
3072 // changed inline completion
3073 if (cmd.origin() == FuncRequest::KEYBOARD) {
3074 if (cmd.action() == LFUN_SELF_INSERT
3075 || (cmd.action() == LFUN_ERT_INSERT && bv->cursor().inMathed()))
3076 updateCompletion(bv->cursor(), true, true);
3077 else if (cmd.action() == LFUN_CHAR_DELETE_BACKWARD)
3078 updateCompletion(bv->cursor(), false, true);
3080 updateCompletion(bv->cursor(), false, false);
3083 dr = bv->cursor().result();
3087 void GuiView::dispatch(FuncRequest const & cmd, DispatchResult & dr)
3089 BufferView * bv = currentBufferView();
3090 // By default we won't need any update.
3091 dr.screenUpdate(Update::None);
3092 // assume cmd will be dispatched
3093 dr.dispatched(true);
3095 Buffer * doc_buffer = documentBufferView()
3096 ? &(documentBufferView()->buffer()) : 0;
3098 if (cmd.origin() == FuncRequest::TOC) {
3099 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
3100 // FIXME: do we need to pass a DispatchResult object here?
3101 toc->doDispatch(bv->cursor(), cmd);
3105 string const argument = to_utf8(cmd.argument());
3107 switch(cmd.action()) {
3108 case LFUN_BUFFER_CHILD_OPEN:
3109 openChildDocument(to_utf8(cmd.argument()));
3112 case LFUN_BUFFER_IMPORT:
3113 importDocument(to_utf8(cmd.argument()));
3116 case LFUN_BUFFER_EXPORT: {
3119 // GCC only sees strfwd.h when building merged
3120 if (::lyx::operator==(cmd.argument(), "custom")) {
3121 dispatch(FuncRequest(LFUN_DIALOG_SHOW, "sendto"), dr);
3124 #if QT_VERSION < 0x040400
3125 if (!doc_buffer->doExport(argument, false)) {
3127 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
3131 /* TODO/Review: Is it a problem to also export the children?
3132 See the update_unincluded flag */
3133 d.asyncBufferProcessing(argument,
3136 &GuiViewPrivate::exportAndDestroy,
3139 // TODO Inform user about success
3144 case LFUN_BUFFER_UPDATE: {
3145 d.asyncBufferProcessing(argument,
3148 &GuiViewPrivate::compileAndDestroy,
3153 case LFUN_BUFFER_VIEW: {
3154 d.asyncBufferProcessing(argument,
3156 _("Previewing ..."),
3157 &GuiViewPrivate::previewAndDestroy,
3162 case LFUN_MASTER_BUFFER_UPDATE: {
3163 d.asyncBufferProcessing(argument,
3164 (doc_buffer ? doc_buffer->masterBuffer() : 0),
3166 &GuiViewPrivate::compileAndDestroy,
3171 case LFUN_MASTER_BUFFER_VIEW: {
3172 d.asyncBufferProcessing(argument,
3173 (doc_buffer ? doc_buffer->masterBuffer() : 0),
3175 &GuiViewPrivate::previewAndDestroy,
3176 0, &Buffer::preview);
3179 case LFUN_BUFFER_SWITCH: {
3180 string const file_name = to_utf8(cmd.argument());
3181 if (!FileName::isAbsolute(file_name)) {
3183 dr.setMessage(_("Absolute filename expected."));
3187 Buffer * buffer = theBufferList().getBuffer(FileName(file_name));
3190 dr.setMessage(_("Document not loaded"));
3194 // Do we open or switch to the buffer in this view ?
3195 if (workArea(*buffer)
3196 || lyxrc.open_buffers_in_tabs || !documentBufferView()) {
3201 // Look for the buffer in other views
3202 QList<int> const ids = guiApp->viewIds();
3204 for (; i != ids.size(); ++i) {
3205 GuiView & gv = guiApp->view(ids[i]);
3206 if (gv.workArea(*buffer)) {
3207 gv.activateWindow();
3208 gv.setBuffer(buffer);
3213 // If necessary, open a new window as a last resort
3214 if (i == ids.size()) {
3215 lyx::dispatch(FuncRequest(LFUN_WINDOW_NEW));
3221 case LFUN_BUFFER_NEXT:
3222 gotoNextOrPreviousBuffer(NEXTBUFFER);
3225 case LFUN_BUFFER_PREVIOUS:
3226 gotoNextOrPreviousBuffer(PREVBUFFER);
3229 case LFUN_COMMAND_EXECUTE: {
3230 bool const show_it = cmd.argument() != "off";
3231 // FIXME: this is a hack, "minibuffer" should not be
3233 if (GuiToolbar * t = toolbar("minibuffer")) {
3234 t->setVisible(show_it);
3235 if (show_it && t->commandBuffer())
3236 t->commandBuffer()->setFocus();
3240 case LFUN_DROP_LAYOUTS_CHOICE:
3241 d.layout_->showPopup();
3244 case LFUN_MENU_OPEN:
3245 if (QMenu * menu = guiApp->menus().menu(toqstr(cmd.argument()), *this))
3246 menu->exec(QCursor::pos());
3249 case LFUN_FILE_INSERT:
3250 insertLyXFile(cmd.argument());
3253 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
3254 insertPlaintextFile(cmd.argument(), true);
3257 case LFUN_FILE_INSERT_PLAINTEXT:
3258 insertPlaintextFile(cmd.argument(), false);
3261 case LFUN_BUFFER_RELOAD: {
3262 LASSERT(doc_buffer, break);
3265 if (!doc_buffer->isClean()) {
3266 docstring const file =
3267 makeDisplayPath(doc_buffer->absFileName(), 20);
3268 docstring text = bformat(_("Any changes will be lost. "
3269 "Are you sure you want to revert to the saved version "
3270 "of the document %1$s?"), file);
3271 ret = Alert::prompt(_("Revert to saved document?"),
3272 text, 1, 1, _("&Revert"), _("&Cancel"));
3276 doc_buffer->markClean();
3277 reloadBuffer(*doc_buffer);
3278 dr.forceBufferUpdate();
3283 case LFUN_BUFFER_WRITE:
3284 LASSERT(doc_buffer, break);
3285 saveBuffer(*doc_buffer);
3288 case LFUN_BUFFER_WRITE_AS:
3289 LASSERT(doc_buffer, break);
3290 renameBuffer(*doc_buffer, cmd.argument());
3293 case LFUN_BUFFER_WRITE_ALL: {
3294 Buffer * first = theBufferList().first();
3297 message(_("Saving all documents..."));
3298 // We cannot use a for loop as the buffer list cycles.
3301 if (!b->isClean()) {
3303 LYXERR(Debug::ACTION, "Saved " << b->absFileName());
3305 b = theBufferList().next(b);
3306 } while (b != first);
3307 dr.setMessage(_("All documents saved."));
3311 case LFUN_BUFFER_CLOSE:
3315 case LFUN_BUFFER_CLOSE_ALL:
3319 case LFUN_TOOLBAR_TOGGLE: {
3320 string const name = cmd.getArg(0);
3321 if (GuiToolbar * t = toolbar(name))
3326 case LFUN_DIALOG_UPDATE: {
3327 string const name = to_utf8(cmd.argument());
3328 if (name == "prefs" || name == "document")
3329 updateDialog(name, string());
3330 else if (name == "paragraph")
3331 lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
3332 else if (currentBufferView()) {
3333 Inset * inset = currentBufferView()->editedInset(name);
3334 // Can only update a dialog connected to an existing inset
3336 // FIXME: get rid of this indirection; GuiView ask the inset
3337 // if he is kind enough to update itself...
3338 FuncRequest fr(LFUN_INSET_DIALOG_UPDATE, cmd.argument());
3339 //FIXME: pass DispatchResult here?
3340 inset->dispatch(currentBufferView()->cursor(), fr);
3346 case LFUN_DIALOG_TOGGLE: {
3347 if (isDialogVisible(cmd.getArg(0)))
3348 dispatch(FuncRequest(LFUN_DIALOG_HIDE, cmd.argument()), dr);
3350 dispatch(FuncRequest(LFUN_DIALOG_SHOW, cmd.argument()), dr);
3354 case LFUN_DIALOG_DISCONNECT_INSET:
3355 disconnectDialog(to_utf8(cmd.argument()));
3358 case LFUN_DIALOG_HIDE: {
3359 guiApp->hideDialogs(to_utf8(cmd.argument()), 0);
3363 case LFUN_DIALOG_SHOW: {
3364 string const name = cmd.getArg(0);
3365 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
3367 if (name == "character") {
3368 data = freefont2string();
3370 showDialog("character", data);
3371 } else if (name == "latexlog") {
3372 Buffer::LogType type;
3373 string const logfile = doc_buffer->logName(&type);
3375 case Buffer::latexlog:
3378 case Buffer::buildlog:
3382 data += Lexer::quoteString(logfile);
3383 showDialog("log", data);
3384 } else if (name == "vclog") {
3385 string const data = "vc " +
3386 Lexer::quoteString(doc_buffer->lyxvc().getLogFile());
3387 showDialog("log", data);
3388 } else if (name == "symbols") {
3389 data = bv->cursor().getEncoding()->name();
3391 showDialog("symbols", data);
3393 } else if (name == "prefs" && isFullScreen()) {
3394 lfunUiToggle("fullscreen");
3395 showDialog("prefs", data);
3397 showDialog(name, data);
3402 dr.setMessage(cmd.argument());
3405 case LFUN_UI_TOGGLE: {
3406 string arg = cmd.getArg(0);
3407 if (!lfunUiToggle(arg)) {
3408 docstring const msg = "ui-toggle " + _("%1$s unknown command!");
3409 dr.setMessage(bformat(msg, from_utf8(arg)));
3411 // Make sure the keyboard focus stays in the work area.
3416 case LFUN_SPLIT_VIEW: {
3417 LASSERT(doc_buffer, break);
3418 string const orientation = cmd.getArg(0);
3419 d.splitter_->setOrientation(orientation == "vertical"
3420 ? Qt::Vertical : Qt::Horizontal);
3421 TabWorkArea * twa = addTabWorkArea();
3422 GuiWorkArea * wa = twa->addWorkArea(*doc_buffer, *this);
3423 setCurrentWorkArea(wa);
3426 case LFUN_CLOSE_TAB_GROUP:
3427 if (TabWorkArea * twa = d.currentTabWorkArea()) {
3428 closeTabWorkArea(twa);
3429 d.current_work_area_ = 0;
3430 twa = d.currentTabWorkArea();
3431 // Switch to the next GuiWorkArea in the found TabWorkArea.
3433 // Make sure the work area is up to date.
3434 setCurrentWorkArea(twa->currentWorkArea());
3436 setCurrentWorkArea(0);
3441 case LFUN_COMPLETION_INLINE:
3442 if (d.current_work_area_)
3443 d.current_work_area_->completer().showInline();
3446 case LFUN_COMPLETION_POPUP:
3447 if (d.current_work_area_)
3448 d.current_work_area_->completer().showPopup();
3452 case LFUN_COMPLETION_COMPLETE:
3453 if (d.current_work_area_)
3454 d.current_work_area_->completer().tab();
3457 case LFUN_COMPLETION_CANCEL:
3458 if (d.current_work_area_) {
3459 if (d.current_work_area_->completer().popupVisible())
3460 d.current_work_area_->completer().hidePopup();
3462 d.current_work_area_->completer().hideInline();
3466 case LFUN_COMPLETION_ACCEPT:
3467 if (d.current_work_area_)
3468 d.current_work_area_->completer().activate();
3471 case LFUN_BUFFER_ZOOM_IN:
3472 case LFUN_BUFFER_ZOOM_OUT:
3473 if (cmd.argument().empty()) {
3474 if (cmd.action() == LFUN_BUFFER_ZOOM_IN)
3479 lyxrc.zoom += convert<int>(cmd.argument());
3481 if (lyxrc.zoom < 10)
3484 // The global QPixmapCache is used in GuiPainter to cache text
3485 // painting so we must reset it.
3486 QPixmapCache::clear();
3487 guiApp->fontLoader().update();
3488 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
3491 case LFUN_VC_REGISTER:
3492 case LFUN_VC_CHECK_IN:
3493 case LFUN_VC_CHECK_OUT:
3494 case LFUN_VC_REPO_UPDATE:
3495 case LFUN_VC_LOCKING_TOGGLE:
3496 case LFUN_VC_REVERT:
3497 case LFUN_VC_UNDO_LAST:
3498 case LFUN_VC_COMMAND:
3499 case LFUN_VC_COMPARE:
3500 dispatchVC(cmd, dr);
3503 case LFUN_SERVER_GOTO_FILE_ROW:
3504 goToFileRow(to_utf8(cmd.argument()));
3507 case LFUN_FORWARD_SEARCH: {
3508 FileName const path(doc_buffer->temppath());
3509 string const texname = doc_buffer->latexName();
3510 FileName const dviname(addName(path.absFileName(),
3511 support::changeExtension(texname, "dvi")));
3512 FileName const pdfname(addName(path.absFileName(),
3513 support::changeExtension(texname, "pdf")));
3514 if (!dviname.exists() && !pdfname.exists()) {
3515 dr.setMessage(_("Please, preview the document first."));
3518 string outname = dviname.onlyFileName();
3519 string command = lyxrc.forward_search_dvi;
3520 if (!dviname.exists() ||
3521 pdfname.lastModified() > dviname.lastModified()) {
3522 outname = pdfname.onlyFileName();
3523 command = lyxrc.forward_search_pdf;
3526 int row = doc_buffer->texrow().getRowFromIdPos(bv->cursor().paragraph().id(), bv->cursor().pos());
3527 LYXERR(Debug::ACTION, "Forward search: row:" << row
3528 << " id:" << bv->cursor().paragraph().id());
3529 if (!row || command.empty()) {
3530 dr.setMessage(_("Couldn't proceed."));
3533 string texrow = convert<string>(row);
3535 command = subst(command, "$$n", texrow);
3536 command = subst(command, "$$t", texname);
3537 command = subst(command, "$$o", outname);
3539 PathChanger p(path);
3541 one.startscript(Systemcall::DontWait, command);
3545 // The LFUN must be for one of BufferView, Buffer or Cursor;
3547 dispatchToBufferView(cmd, dr);
3551 // Part of automatic menu appearance feature.
3552 if (isFullScreen()) {
3553 if (menuBar()->isVisible() && lyxrc.full_screen_menubar)
3555 if (statusBar()->isVisible())
3556 statusBar()->hide();
3561 bool GuiView::lfunUiToggle(string const & ui_component)
3563 if (ui_component == "scrollbar") {
3564 // hide() is of no help
3565 if (d.current_work_area_->verticalScrollBarPolicy() ==
3566 Qt::ScrollBarAlwaysOff)
3568 d.current_work_area_->setVerticalScrollBarPolicy(
3569 Qt::ScrollBarAsNeeded);
3571 d.current_work_area_->setVerticalScrollBarPolicy(
3572 Qt::ScrollBarAlwaysOff);
3573 } else if (ui_component == "statusbar") {
3574 statusBar()->setVisible(!statusBar()->isVisible());
3575 } else if (ui_component == "menubar") {
3576 menuBar()->setVisible(!menuBar()->isVisible());
3578 #if QT_VERSION >= 0x040300
3579 if (ui_component == "frame") {
3581 getContentsMargins(&l, &t, &r, &b);
3582 //are the frames in default state?
3583 d.current_work_area_->setFrameStyle(QFrame::NoFrame);
3585 setContentsMargins(-2, -2, -2, -2);
3587 setContentsMargins(0, 0, 0, 0);
3591 if (ui_component == "fullscreen") {
3599 void GuiView::toggleFullScreen()
3601 if (isFullScreen()) {
3602 for (int i = 0; i != d.splitter_->count(); ++i)
3603 d.tabWorkArea(i)->setFullScreen(false);
3604 #if QT_VERSION >= 0x040300
3605 setContentsMargins(0, 0, 0, 0);
3607 setWindowState(windowState() ^ Qt::WindowFullScreen);
3610 statusBar()->show();
3613 hideDialogs("prefs", 0);
3614 for (int i = 0; i != d.splitter_->count(); ++i)
3615 d.tabWorkArea(i)->setFullScreen(true);
3616 #if QT_VERSION >= 0x040300
3617 setContentsMargins(-2, -2, -2, -2);
3620 setWindowState(windowState() ^ Qt::WindowFullScreen);
3621 statusBar()->hide();
3622 if (lyxrc.full_screen_menubar)
3624 if (lyxrc.full_screen_toolbars) {
3625 ToolbarMap::iterator end = d.toolbars_.end();
3626 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
3631 // give dialogs like the TOC a chance to adapt
3636 Buffer const * GuiView::updateInset(Inset const * inset)
3641 Buffer const * inset_buffer = &(inset->buffer());
3643 for (int i = 0; i != d.splitter_->count(); ++i) {
3644 GuiWorkArea * wa = d.tabWorkArea(i)->currentWorkArea();
3647 Buffer const * buffer = &(wa->bufferView().buffer());
3648 if (inset_buffer == buffer)
3649 wa->scheduleRedraw();
3651 return inset_buffer;
3655 void GuiView::restartCursor()
3657 /* When we move around, or type, it's nice to be able to see
3658 * the cursor immediately after the keypress.
3660 if (d.current_work_area_)
3661 d.current_work_area_->startBlinkingCursor();
3663 // Take this occasion to update the other GUI elements.
3669 void GuiView::updateCompletion(Cursor & cur, bool start, bool keep)
3671 if (d.current_work_area_)
3672 d.current_work_area_->completer().updateVisibility(cur, start, keep);
3677 // This list should be kept in sync with the list of insets in
3678 // src/insets/Inset.cpp. I.e., if a dialog goes with an inset, the
3679 // dialog should have the same name as the inset.
3680 // Changes should be also recorded in LFUN_DIALOG_SHOW doxygen
3681 // docs in LyXAction.cpp.
3683 char const * const dialognames[] = {
3685 "aboutlyx", "bibitem", "bibtex", "box", "branch", "changes", "character",
3686 "citation", "compare", "comparehistory", "document", "errorlist", "ert",
3687 "external", "file", "findreplace", "findreplaceadv", "float", "graphics",
3688 "href", "include", "index", "index_print", "info", "listings", "label", "line",
3689 "log", "mathdelimiter", "mathmatrix", "mathspace", "nomenclature",
3690 "nomencl_print", "note", "paragraph", "phantom", "prefs", "print", "ref",
3691 "sendto", "space", "spellchecker", "symbols", "tabular", "tabularcreate",
3692 "thesaurus", "texinfo", "toc", "view-source", "vspace", "wrap", "progress"};
3694 char const * const * const end_dialognames =
3695 dialognames + (sizeof(dialognames) / sizeof(char *));
3699 cmpCStr(char const * name) : name_(name) {}
3700 bool operator()(char const * other) {
3701 return strcmp(other, name_) == 0;
3708 bool isValidName(string const & name)
3710 return find_if(dialognames, end_dialognames,
3711 cmpCStr(name.c_str())) != end_dialognames;
3717 void GuiView::resetDialogs()
3719 // Make sure that no LFUN uses any GuiView.
3720 guiApp->setCurrentView(0);
3723 constructToolbars();
3724 guiApp->menus().fillMenuBar(menuBar(), this, false);
3725 d.layout_->updateContents(true);
3726 // Now update controls with current buffer.
3727 guiApp->setCurrentView(this);
3733 Dialog * GuiView::findOrBuild(string const & name, bool hide_it)
3735 if (!isValidName(name))
3738 map<string, DialogPtr>::iterator it = d.dialogs_.find(name);
3740 if (it != d.dialogs_.end()) {
3742 it->second->hideView();
3743 return it->second.get();
3746 Dialog * dialog = build(name);
3747 d.dialogs_[name].reset(dialog);
3748 if (lyxrc.allow_geometry_session)
3749 dialog->restoreSession();
3756 void GuiView::showDialog(string const & name, string const & data,
3759 triggerShowDialog(toqstr(name), toqstr(data), inset);
3763 void GuiView::doShowDialog(QString const & qname, QString const & qdata,
3769 const string name = fromqstr(qname);
3770 const string data = fromqstr(qdata);
3774 Dialog * dialog = findOrBuild(name, false);
3776 bool const visible = dialog->isVisibleView();
3777 dialog->showData(data);
3778 if (inset && currentBufferView())
3779 currentBufferView()->editInset(name, inset);
3780 // We only set the focus to the new dialog if it was not yet
3781 // visible in order not to change the existing previous behaviour
3783 // activateWindow is needed for floating dockviews
3784 dialog->asQWidget()->raise();
3785 dialog->asQWidget()->activateWindow();
3786 dialog->asQWidget()->setFocus();
3790 catch (ExceptionMessage const & ex) {
3798 bool GuiView::isDialogVisible(string const & name) const
3800 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3801 if (it == d.dialogs_.end())
3803 return it->second.get()->isVisibleView() && !it->second.get()->isClosing();
3807 void GuiView::hideDialog(string const & name, Inset * inset)
3809 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3810 if (it == d.dialogs_.end())
3813 if (inset && currentBufferView()
3814 && inset != currentBufferView()->editedInset(name))
3817 Dialog * const dialog = it->second.get();
3818 if (dialog->isVisibleView())
3820 if (currentBufferView())
3821 currentBufferView()->editInset(name, 0);
3825 void GuiView::disconnectDialog(string const & name)
3827 if (!isValidName(name))
3829 if (currentBufferView())
3830 currentBufferView()->editInset(name, 0);
3834 void GuiView::hideAll() const
3836 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
3837 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3839 for(; it != end; ++it)
3840 it->second->hideView();
3844 void GuiView::updateDialogs()
3846 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
3847 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3849 for(; it != end; ++it) {
3850 Dialog * dialog = it->second.get();
3852 if (dialog->needBufferOpen() && !documentBufferView())
3853 hideDialog(fromqstr(dialog->name()), 0);
3854 else if (dialog->isVisibleView())
3855 dialog->checkStatus();
3862 Dialog * createDialog(GuiView & lv, string const & name);
3864 // will be replaced by a proper factory...
3865 Dialog * createGuiAbout(GuiView & lv);
3866 Dialog * createGuiBibtex(GuiView & lv);
3867 Dialog * createGuiChanges(GuiView & lv);
3868 Dialog * createGuiCharacter(GuiView & lv);
3869 Dialog * createGuiCitation(GuiView & lv);
3870 Dialog * createGuiCompare(GuiView & lv);
3871 Dialog * createGuiCompareHistory(GuiView & lv);
3872 Dialog * createGuiDelimiter(GuiView & lv);
3873 Dialog * createGuiDocument(GuiView & lv);
3874 Dialog * createGuiErrorList(GuiView & lv);
3875 Dialog * createGuiExternal(GuiView & lv);
3876 Dialog * createGuiGraphics(GuiView & lv);
3877 Dialog * createGuiInclude(GuiView & lv);
3878 Dialog * createGuiIndex(GuiView & lv);
3879 Dialog * createGuiListings(GuiView & lv);
3880 Dialog * createGuiLog(GuiView & lv);
3881 Dialog * createGuiMathMatrix(GuiView & lv);
3882 Dialog * createGuiNote(GuiView & lv);
3883 Dialog * createGuiParagraph(GuiView & lv);
3884 Dialog * createGuiPhantom(GuiView & lv);
3885 Dialog * createGuiPreferences(GuiView & lv);
3886 Dialog * createGuiPrint(GuiView & lv);
3887 Dialog * createGuiPrintindex(GuiView & lv);
3888 Dialog * createGuiRef(GuiView & lv);
3889 Dialog * createGuiSearch(GuiView & lv);
3890 Dialog * createGuiSearchAdv(GuiView & lv);
3891 Dialog * createGuiSendTo(GuiView & lv);
3892 Dialog * createGuiShowFile(GuiView & lv);
3893 Dialog * createGuiSpellchecker(GuiView & lv);
3894 Dialog * createGuiSymbols(GuiView & lv);
3895 Dialog * createGuiTabularCreate(GuiView & lv);
3896 Dialog * createGuiTexInfo(GuiView & lv);
3897 Dialog * createGuiToc(GuiView & lv);
3898 Dialog * createGuiThesaurus(GuiView & lv);
3899 Dialog * createGuiViewSource(GuiView & lv);
3900 Dialog * createGuiWrap(GuiView & lv);
3901 Dialog * createGuiProgressView(GuiView & lv);
3905 Dialog * GuiView::build(string const & name)
3907 LASSERT(isValidName(name), return 0);
3909 Dialog * dialog = createDialog(*this, name);
3913 if (name == "aboutlyx")
3914 return createGuiAbout(*this);
3915 if (name == "bibtex")
3916 return createGuiBibtex(*this);
3917 if (name == "changes")
3918 return createGuiChanges(*this);
3919 if (name == "character")
3920 return createGuiCharacter(*this);
3921 if (name == "citation")
3922 return createGuiCitation(*this);
3923 if (name == "compare")
3924 return createGuiCompare(*this);
3925 if (name == "comparehistory")
3926 return createGuiCompareHistory(*this);
3927 if (name == "document")
3928 return createGuiDocument(*this);
3929 if (name == "errorlist")
3930 return createGuiErrorList(*this);
3931 if (name == "external")
3932 return createGuiExternal(*this);
3934 return createGuiShowFile(*this);
3935 if (name == "findreplace")
3936 return createGuiSearch(*this);
3937 if (name == "findreplaceadv")
3938 return createGuiSearchAdv(*this);
3939 if (name == "graphics")
3940 return createGuiGraphics(*this);
3941 if (name == "include")
3942 return createGuiInclude(*this);
3943 if (name == "index")
3944 return createGuiIndex(*this);
3945 if (name == "index_print")
3946 return createGuiPrintindex(*this);
3947 if (name == "listings")
3948 return createGuiListings(*this);
3950 return createGuiLog(*this);
3951 if (name == "mathdelimiter")
3952 return createGuiDelimiter(*this);
3953 if (name == "mathmatrix")
3954 return createGuiMathMatrix(*this);
3956 return createGuiNote(*this);
3957 if (name == "paragraph")
3958 return createGuiParagraph(*this);
3959 if (name == "phantom")
3960 return createGuiPhantom(*this);
3961 if (name == "prefs")
3962 return createGuiPreferences(*this);
3963 if (name == "print")
3964 return createGuiPrint(*this);
3966 return createGuiRef(*this);
3967 if (name == "sendto")
3968 return createGuiSendTo(*this);
3969 if (name == "spellchecker")
3970 return createGuiSpellchecker(*this);
3971 if (name == "symbols")
3972 return createGuiSymbols(*this);
3973 if (name == "tabularcreate")
3974 return createGuiTabularCreate(*this);
3975 if (name == "texinfo")
3976 return createGuiTexInfo(*this);
3977 if (name == "thesaurus")
3978 return createGuiThesaurus(*this);
3980 return createGuiToc(*this);
3981 if (name == "view-source")
3982 return createGuiViewSource(*this);
3984 return createGuiWrap(*this);
3985 if (name == "progress")
3986 return createGuiProgressView(*this);
3992 } // namespace frontend
3995 #include "moc_GuiView.cpp"