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>
98 #include <QPixmapCache>
100 #include <QPushButton>
102 #include <QShowEvent>
104 #include <QStackedWidget>
105 #include <QStatusBar>
110 #include <QScrollBar>
114 #define EXPORT_in_THREAD 1
116 // QtConcurrent was introduced in Qt 4.4
117 #if (QT_VERSION >= 0x040400)
119 #include <QFutureWatcher>
120 #include <QtConcurrentRun>
123 #include "support/bind.h"
127 #ifdef HAVE_SYS_TIME_H
128 # include <sys/time.h>
136 using namespace lyx::support;
140 using support::addExtension;
141 using support::changeExtension;
142 using support::removeExtension;
148 class BackgroundWidget : public QWidget
153 LYXERR(Debug::GUI, "show banner: " << lyxrc.show_banner);
154 if (!lyxrc.show_banner)
156 /// The text to be written on top of the pixmap
157 QString const text = lyx_version ?
158 qt_("version ") + lyx_version : qt_("unknown version");
159 splash_ = getPixmap("images/", "banner", "png");
161 QPainter pain(&splash_);
162 pain.setPen(QColor(0, 0, 0));
164 // The font used to display the version info
165 font.setStyleHint(QFont::SansSerif);
166 font.setWeight(QFont::Bold);
167 font.setPointSize(int(toqstr(lyxrc.font_sizes[FONT_SIZE_LARGE]).toDouble()));
169 pain.drawText(190, 225, text);
170 setFocusPolicy(Qt::StrongFocus);
173 void paintEvent(QPaintEvent *)
175 int x = (width() - splash_.width()) / 2;
176 int y = (height() - splash_.height()) / 2;
178 pain.drawPixmap(x, y, splash_);
181 void keyPressEvent(QKeyEvent * ev)
184 setKeySymbol(&sym, ev);
186 guiApp->processKeySym(sym, q_key_state(ev->modifiers()));
198 /// Toolbar store providing access to individual toolbars by name.
199 typedef map<string, GuiToolbar *> ToolbarMap;
201 typedef shared_ptr<Dialog> DialogPtr;
206 struct GuiView::GuiViewPrivate
208 GuiViewPrivate(GuiView * gv)
209 : gv_(gv), current_work_area_(0), current_main_work_area_(0),
210 layout_(0), autosave_timeout_(5000),
213 // hardcode here the platform specific icon size
214 smallIconSize = 16; // scaling problems
215 normalIconSize = 22; // ok, default if iconsize.png is missing
216 bigIconSize = 26; // better for some math icons
218 // if it exists, use width of iconsize.png as normal size
219 QString const dir = toqstr(addPath("images", lyxrc.icon_set));
220 FileName const fn = lyx::libFileSearch(dir, "iconsize.png");
222 QImage image(toqstr(fn.absFileName()));
223 if (image.width() < int(smallIconSize))
224 normalIconSize = smallIconSize;
225 else if (image.width() > int(bigIconSize))
226 normalIconSize = bigIconSize;
228 normalIconSize = image.width();
231 splitter_ = new QSplitter;
232 bg_widget_ = new BackgroundWidget;
233 stack_widget_ = new QStackedWidget;
234 stack_widget_->addWidget(bg_widget_);
235 stack_widget_->addWidget(splitter_);
238 // TODO cleanup, remove the singleton, handle multiple Windows?
239 progress_ = ProgressInterface::instance();
240 if (!dynamic_cast<GuiProgress*>(progress_)) {
241 progress_ = new GuiProgress(); // TODO who deletes it
242 ProgressInterface::setInstance(progress_);
245 dynamic_cast<GuiProgress*>(progress_),
246 SIGNAL(updateStatusBarMessage(QString const&)),
247 gv, SLOT(updateStatusBarMessage(QString const&)));
249 dynamic_cast<GuiProgress*>(progress_),
250 SIGNAL(clearMessageText()),
251 gv, SLOT(clearMessageText()));
258 delete stack_widget_;
261 QMenu * toolBarPopup(GuiView * parent)
263 // FIXME: translation
264 QMenu * menu = new QMenu(parent);
265 QActionGroup * iconSizeGroup = new QActionGroup(parent);
267 QAction * smallIcons = new QAction(iconSizeGroup);
268 smallIcons->setText(qt_("Small-sized icons"));
269 smallIcons->setCheckable(true);
270 QObject::connect(smallIcons, SIGNAL(triggered()),
271 parent, SLOT(smallSizedIcons()));
272 menu->addAction(smallIcons);
274 QAction * normalIcons = new QAction(iconSizeGroup);
275 normalIcons->setText(qt_("Normal-sized icons"));
276 normalIcons->setCheckable(true);
277 QObject::connect(normalIcons, SIGNAL(triggered()),
278 parent, SLOT(normalSizedIcons()));
279 menu->addAction(normalIcons);
281 QAction * bigIcons = new QAction(iconSizeGroup);
282 bigIcons->setText(qt_("Big-sized icons"));
283 bigIcons->setCheckable(true);
284 QObject::connect(bigIcons, SIGNAL(triggered()),
285 parent, SLOT(bigSizedIcons()));
286 menu->addAction(bigIcons);
288 unsigned int cur = parent->iconSize().width();
289 if ( cur == parent->d.smallIconSize)
290 smallIcons->setChecked(true);
291 else if (cur == parent->d.normalIconSize)
292 normalIcons->setChecked(true);
293 else if (cur == parent->d.bigIconSize)
294 bigIcons->setChecked(true);
301 stack_widget_->setCurrentWidget(bg_widget_);
302 bg_widget_->setUpdatesEnabled(true);
303 bg_widget_->setFocus();
306 int tabWorkAreaCount()
308 return splitter_->count();
311 TabWorkArea * tabWorkArea(int i)
313 return dynamic_cast<TabWorkArea *>(splitter_->widget(i));
316 TabWorkArea * currentTabWorkArea()
318 int areas = tabWorkAreaCount();
320 // The first TabWorkArea is always the first one, if any.
321 return tabWorkArea(0);
323 for (int i = 0; i != areas; ++i) {
324 TabWorkArea * twa = tabWorkArea(i);
325 if (current_main_work_area_ == twa->currentWorkArea())
329 // None has the focus so we just take the first one.
330 return tabWorkArea(0);
333 #if (QT_VERSION >= 0x040400)
334 void setPreviewFuture(QFuture<docstring> const & f)
336 if (processing_thread_watcher_.isRunning()) {
337 // we prefer to cancel this preview in order to keep a snappy
341 processing_thread_watcher_.setFuture(f);
347 GuiWorkArea * current_work_area_;
348 GuiWorkArea * current_main_work_area_;
349 QSplitter * splitter_;
350 QStackedWidget * stack_widget_;
351 BackgroundWidget * bg_widget_;
353 ToolbarMap toolbars_;
354 ProgressInterface* progress_;
355 /// The main layout box.
357 * \warning Don't Delete! The layout box is actually owned by
358 * whichever toolbar contains it. All the GuiView class needs is a
359 * means of accessing it.
361 * FIXME: replace that with a proper model so that we are not limited
362 * to only one dialog.
367 map<string, DialogPtr> dialogs_;
369 unsigned int smallIconSize;
370 unsigned int normalIconSize;
371 unsigned int bigIconSize;
373 QTimer statusbar_timer_;
374 /// auto-saving of buffers
375 Timeout autosave_timeout_;
376 /// flag against a race condition due to multiclicks, see bug #1119
380 TocModels toc_models_;
382 #if (QT_VERSION >= 0x040400)
384 QFutureWatcher<docstring> autosave_watcher_;
385 QFutureWatcher<docstring> processing_thread_watcher_;
387 string last_export_format;
389 struct DummyWatcher { bool isRunning(){return false;} };
390 DummyWatcher processing_thread_watcher_;
393 static QSet<Buffer const *> busyBuffers;
394 static docstring previewAndDestroy(Buffer const * orig, Buffer * buffer, string const & format);
395 static docstring exportAndDestroy(Buffer const * orig, Buffer * buffer, string const & format);
396 static docstring compileAndDestroy(Buffer const * orig, Buffer * buffer, string const & format);
397 static docstring autosaveAndDestroy(Buffer const * orig, Buffer * buffer);
400 static docstring runAndDestroy(const T& func, Buffer const * orig, Buffer * buffer, string const & format, string const & msg);
402 // TODO syncFunc/previewFunc: use bind
403 bool asyncBufferProcessing(string const & argument,
404 Buffer const * used_buffer,
405 docstring const & msg,
406 docstring (*asyncFunc)(Buffer const *, Buffer *, string const &),
407 bool (Buffer::*syncFunc)(string const &, bool, bool) const,
408 bool (Buffer::*previewFunc)(string const &, bool) const);
410 QVector<GuiWorkArea*> guiWorkAreas();
413 QSet<Buffer const *> GuiView::GuiViewPrivate::busyBuffers;
416 GuiView::GuiView(int id)
417 : d(*new GuiViewPrivate(this)), id_(id), closing_(false), busy_(0)
419 // GuiToolbars *must* be initialised before the menu bar.
420 normalSizedIcons(); // at least on Mac the default is 32 otherwise, which is huge
423 // set ourself as the current view. This is needed for the menu bar
424 // filling, at least for the static special menu item on Mac. Otherwise
425 // they are greyed out.
426 guiApp->setCurrentView(this);
428 // Fill up the menu bar.
429 guiApp->menus().fillMenuBar(menuBar(), this, true);
431 setCentralWidget(d.stack_widget_);
433 // Start autosave timer
434 if (lyxrc.autosave) {
435 d.autosave_timeout_.timeout.connect(bind(&GuiView::autoSave, this));
436 d.autosave_timeout_.setTimeout(lyxrc.autosave * 1000);
437 d.autosave_timeout_.start();
439 connect(&d.statusbar_timer_, SIGNAL(timeout()),
440 this, SLOT(clearMessage()));
442 // We don't want to keep the window in memory if it is closed.
443 setAttribute(Qt::WA_DeleteOnClose, true);
445 #if (!defined(Q_WS_WIN) && !defined(Q_WS_MACX))
446 // assign an icon to main form. We do not do it under Qt/Win or Qt/Mac,
447 // since the icon is provided in the application bundle.
448 setWindowIcon(getPixmap("images/", "lyx", "png"));
451 #if (QT_VERSION >= 0x040300)
452 // use tabbed dock area for multiple docks
453 // (such as "source" and "messages")
454 setDockOptions(QMainWindow::ForceTabbedDocks);
458 setAcceptDrops(true);
460 #if (QT_VERSION >= 0x040400)
462 // add busy indicator to statusbar
463 QLabel * busylabel = new QLabel(statusBar());
464 statusBar()->addPermanentWidget(busylabel);
465 QString fn = toqstr(lyx::libFileSearch("images", "busy.gif").absFileName());
466 QMovie * busyanim = new QMovie(fn, QByteArray(), busylabel);
467 busylabel->setMovie(busyanim);
471 connect(&d.processing_thread_watcher_, SIGNAL(started()),
472 busylabel, SLOT(show()));
473 connect(&d.processing_thread_watcher_, SIGNAL(finished()),
474 busylabel, SLOT(hide()));
476 statusBar()->setSizeGripEnabled(true);
479 connect(&d.autosave_watcher_, SIGNAL(finished()), this,
480 SLOT(autoSaveThreadFinished()));
482 connect(&d.processing_thread_watcher_, SIGNAL(started()), this,
483 SLOT(processingThreadStarted()));
484 connect(&d.processing_thread_watcher_, SIGNAL(finished()), this,
485 SLOT(processingThreadFinished()));
489 connect(this, SIGNAL(triggerShowDialog(QString const &, QString const &, Inset *)),
490 SLOT(doShowDialog(QString const &, QString const &, Inset *)));
492 // Forbid too small unresizable window because it can happen
493 // with some window manager under X11.
494 setMinimumSize(300, 200);
496 if (lyxrc.allow_geometry_session) {
497 // Now take care of session management.
502 // no session handling, default to a sane size.
503 setGeometry(50, 50, 690, 510);
506 // clear session data if any.
508 settings.remove("views");
518 QVector<GuiWorkArea*> GuiView::GuiViewPrivate::guiWorkAreas()
520 QVector<GuiWorkArea*> areas;
521 for (int i = 0; i < tabWorkAreaCount(); i++) {
522 TabWorkArea* ta = tabWorkArea(i);
523 for (int u = 0; u < ta->count(); u++) {
524 areas << ta->workArea(u);
531 #if QT_VERSION >= 0x040400
533 void GuiView::processingThreadStarted()
538 void GuiView::processingThreadFinished(bool show_errors)
540 QFutureWatcher<docstring> const * watcher =
541 static_cast<QFutureWatcher<docstring> const *>(sender());
542 message(watcher->result());
545 BufferView const * const bv = currentBufferView();
546 if (bv && !bv->buffer().errorList("Export").empty()) {
550 errors(d.last_export_format);
555 void GuiView::processingThreadFinished()
557 processingThreadFinished(true);
561 void GuiView::autoSaveThreadFinished()
563 processingThreadFinished(false);
569 void GuiView::processingThreadStarted()
574 void GuiView::processingThreadFinished(bool)
579 void GuiView::processingThreadFinished()
584 void GuiView::autoSaveThreadFinished()
590 void GuiView::saveLayout() const
593 settings.beginGroup("views");
594 settings.beginGroup(QString::number(id_));
596 settings.setValue("pos", pos());
597 settings.setValue("size", size());
599 settings.setValue("geometry", saveGeometry());
601 settings.setValue("layout", saveState(0));
602 settings.setValue("icon_size", iconSize());
606 void GuiView::saveUISettings() const
608 // Save the toolbar private states
609 ToolbarMap::iterator end = d.toolbars_.end();
610 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
611 it->second->saveSession();
612 // Now take care of all other dialogs
613 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
614 for (; it!= d.dialogs_.end(); ++it)
615 it->second->saveSession();
619 bool GuiView::restoreLayout()
622 settings.beginGroup("views");
623 settings.beginGroup(QString::number(id_));
624 QString const icon_key = "icon_size";
625 if (!settings.contains(icon_key))
628 //code below is skipped when when ~/.config/LyX is (re)created
629 setIconSize(settings.value(icon_key).toSize());
631 QPoint pos = settings.value("pos", QPoint(50, 50)).toPoint();
632 QSize size = settings.value("size", QSize(690, 510)).toSize();
636 // Work-around for bug #6034: the window ends up in an undetermined
637 // state when trying to restore a maximized window when it is
638 // already maximized.
639 if (!(windowState() & Qt::WindowMaximized))
640 if (!restoreGeometry(settings.value("geometry").toByteArray()))
641 setGeometry(50, 50, 690, 510);
643 // Make sure layout is correctly oriented.
644 setLayoutDirection(qApp->layoutDirection());
646 // Allow the toc and view-source dock widget to be restored if needed.
648 if ((dialog = findOrBuild("toc", true)))
649 // see bug 5082. At least setup title and enabled state.
650 // Visibility will be adjusted by restoreState below.
651 dialog->prepareView();
652 if ((dialog = findOrBuild("view-source", true)))
653 dialog->prepareView();
654 if ((dialog = findOrBuild("progress", true)))
655 dialog->prepareView();
656 if ((dialog = findOrBuild("findreplaceadv", true)))
657 dialog->prepareView();
659 if (!restoreState(settings.value("layout").toByteArray(), 0))
666 GuiToolbar * GuiView::toolbar(string const & name)
668 ToolbarMap::iterator it = d.toolbars_.find(name);
669 if (it != d.toolbars_.end())
672 LYXERR(Debug::GUI, "Toolbar::display: no toolbar named " << name);
677 void GuiView::constructToolbars()
679 ToolbarMap::iterator it = d.toolbars_.begin();
680 for (; it != d.toolbars_.end(); ++it)
684 // I don't like doing this here, but the standard toolbar
685 // destroys this object when it's destroyed itself (vfr)
686 d.layout_ = new LayoutBox(*this);
687 d.stack_widget_->addWidget(d.layout_);
688 d.layout_->move(0,0);
690 // extracts the toolbars from the backend
691 Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
692 Toolbars::Infos::iterator end = guiApp->toolbars().end();
693 for (; cit != end; ++cit)
694 d.toolbars_[cit->name] = new GuiToolbar(*cit, *this);
698 void GuiView::initToolbars()
700 // extracts the toolbars from the backend
701 Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
702 Toolbars::Infos::iterator end = guiApp->toolbars().end();
703 for (; cit != end; ++cit) {
704 GuiToolbar * tb = toolbar(cit->name);
707 int const visibility = guiApp->toolbars().defaultVisibility(cit->name);
708 bool newline = !(visibility & Toolbars::SAMEROW);
709 tb->setVisible(false);
710 tb->setVisibility(visibility);
712 if (visibility & Toolbars::TOP) {
714 addToolBarBreak(Qt::TopToolBarArea);
715 addToolBar(Qt::TopToolBarArea, tb);
718 if (visibility & Toolbars::BOTTOM) {
719 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
720 #if (QT_VERSION >= 0x040202)
722 addToolBarBreak(Qt::BottomToolBarArea);
724 addToolBar(Qt::BottomToolBarArea, tb);
727 if (visibility & Toolbars::LEFT) {
728 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
729 #if (QT_VERSION >= 0x040202)
731 addToolBarBreak(Qt::LeftToolBarArea);
733 addToolBar(Qt::LeftToolBarArea, tb);
736 if (visibility & Toolbars::RIGHT) {
737 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
738 #if (QT_VERSION >= 0x040202)
740 addToolBarBreak(Qt::RightToolBarArea);
742 addToolBar(Qt::RightToolBarArea, tb);
745 if (visibility & Toolbars::ON)
746 tb->setVisible(true);
751 TocModels & GuiView::tocModels()
753 return d.toc_models_;
757 void GuiView::setFocus()
759 LYXERR(Debug::DEBUG, "GuiView::setFocus()" << this);
760 QMainWindow::setFocus();
764 void GuiView::focusInEvent(QFocusEvent * e)
766 LYXERR(Debug::DEBUG, "GuiView::focusInEvent()" << this);
767 QMainWindow::focusInEvent(e);
768 // Make sure guiApp points to the correct view.
769 guiApp->setCurrentView(this);
770 if (currentWorkArea())
771 currentWorkArea()->setFocus();
772 else if (currentMainWorkArea())
773 currentMainWorkArea()->setFocus();
775 d.bg_widget_->setFocus();
779 QMenu * GuiView::createPopupMenu()
781 return d.toolBarPopup(this);
785 void GuiView::showEvent(QShowEvent * e)
787 LYXERR(Debug::GUI, "Passed Geometry "
788 << size().height() << "x" << size().width()
789 << "+" << pos().x() << "+" << pos().y());
791 if (d.splitter_->count() == 0)
792 // No work area, switch to the background widget.
795 QMainWindow::showEvent(e);
799 bool GuiView::closeScheduled()
806 /** Destroy only all tabbed WorkAreas. Destruction of other WorkAreas
807 ** is responsibility of the container (e.g., dialog)
809 void GuiView::closeEvent(QCloseEvent * close_event)
811 LYXERR(Debug::DEBUG, "GuiView::closeEvent()");
813 if (!GuiViewPrivate::busyBuffers.isEmpty()) {
814 Alert::warning(_("Exit LyX"),
815 _("LyX could not be closed because documents are being processed by LyX."));
816 close_event->setAccepted(false);
820 // If the user pressed the x (so we didn't call closeView
821 // programmatically), we want to clear all existing entries.
823 theSession().lastOpened().clear();
828 // it can happen that this event arrives without selecting the view,
829 // e.g. when clicking the close button on a background window.
831 if (!closeWorkAreaAll()) {
833 close_event->ignore();
837 // Make sure that nothing will use this to be closed View.
838 guiApp->unregisterView(this);
840 if (isFullScreen()) {
841 // Switch off fullscreen before closing.
846 // Make sure the timer time out will not trigger a statusbar update.
847 d.statusbar_timer_.stop();
849 // Saving fullscreen requires additional tweaks in the toolbar code.
850 // It wouldn't also work under linux natively.
851 if (lyxrc.allow_geometry_session) {
856 close_event->accept();
860 void GuiView::dragEnterEvent(QDragEnterEvent * event)
862 if (event->mimeData()->hasUrls())
864 /// \todo Ask lyx-devel is this is enough:
865 /// if (event->mimeData()->hasFormat("text/plain"))
866 /// event->acceptProposedAction();
870 void GuiView::dropEvent(QDropEvent * event)
872 QList<QUrl> files = event->mimeData()->urls();
876 LYXERR(Debug::GUI, "GuiView::dropEvent: got URLs!");
877 for (int i = 0; i != files.size(); ++i) {
878 string const file = os::internal_path(fromqstr(
879 files.at(i).toLocalFile()));
883 string const ext = support::getExtension(file);
884 vector<const Format *> found_formats;
886 // Find all formats that have the correct extension.
887 vector<const Format *> const & import_formats
888 = theConverters().importableFormats();
889 vector<const Format *>::const_iterator it = import_formats.begin();
890 for (; it != import_formats.end(); ++it)
891 if ((*it)->extension() == ext)
892 found_formats.push_back(*it);
895 if (found_formats.size() >= 1) {
896 if (found_formats.size() > 1) {
897 //FIXME: show a dialog to choose the correct importable format
899 "Multiple importable formats found, selecting first");
901 string const arg = found_formats[0]->name() + " " + file;
902 cmd = FuncRequest(LFUN_BUFFER_IMPORT, arg);
905 //FIXME: do we have to explicitly check whether it's a lyx file?
907 "No formats found, trying to open it as a lyx file");
908 cmd = FuncRequest(LFUN_FILE_OPEN, file);
910 // add the functions to the queue
911 guiApp->addToFuncRequestQueue(cmd);
914 // now process the collected functions. We perform the events
915 // asynchronously. This prevents potential problems in case the
916 // BufferView is closed within an event.
917 guiApp->processFuncRequestQueueAsync();
921 void GuiView::message(docstring const & str)
923 if (ForkedProcess::iAmAChild())
926 // call is moved to GUI-thread by GuiProgress
927 d.progress_->appendMessage(toqstr(str));
931 void GuiView::clearMessageText()
933 message(docstring());
937 void GuiView::updateStatusBarMessage(QString const & str)
939 statusBar()->showMessage(str);
940 d.statusbar_timer_.stop();
941 d.statusbar_timer_.start(3000);
945 void GuiView::smallSizedIcons()
947 setIconSize(QSize(d.smallIconSize, d.smallIconSize));
951 void GuiView::normalSizedIcons()
953 setIconSize(QSize(d.normalIconSize, d.normalIconSize));
957 void GuiView::bigSizedIcons()
959 setIconSize(QSize(d.bigIconSize, d.bigIconSize));
963 void GuiView::clearMessage()
965 // FIXME: This code was introduced in r19643 to fix bug #4123. However,
966 // the hasFocus function mostly returns false, even if the focus is on
967 // a workarea in this view.
971 d.statusbar_timer_.stop();
975 void GuiView::updateWindowTitle(GuiWorkArea * wa)
977 if (wa != d.current_work_area_
978 || wa->bufferView().buffer().isInternal())
980 setWindowTitle(qt_("LyX: ") + wa->windowTitle());
981 setWindowIconText(wa->windowIconText());
985 void GuiView::on_currentWorkAreaChanged(GuiWorkArea * wa)
988 disconnectBufferView();
989 connectBufferView(wa->bufferView());
990 connectBuffer(wa->bufferView().buffer());
991 d.current_work_area_ = wa;
992 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
993 this, SLOT(updateWindowTitle(GuiWorkArea *)));
994 updateWindowTitle(wa);
998 // The document settings needs to be reinitialised.
999 updateDialog("document", "");
1001 // Buffer-dependent dialogs must be updated. This is done here because
1002 // some dialogs require buffer()->text.
1007 void GuiView::on_lastWorkAreaRemoved()
1010 // We already are in a close event. Nothing more to do.
1013 if (d.splitter_->count() > 1)
1014 // We have a splitter so don't close anything.
1017 // Reset and updates the dialogs.
1018 d.toc_models_.reset(0);
1019 updateDialog("document", "");
1022 resetWindowTitleAndIconText();
1025 if (lyxrc.open_buffers_in_tabs)
1026 // Nothing more to do, the window should stay open.
1029 if (guiApp->viewIds().size() > 1) {
1035 // On Mac we also close the last window because the application stay
1036 // resident in memory. On other platforms we don't close the last
1037 // window because this would quit the application.
1043 void GuiView::updateStatusBar()
1045 // let the user see the explicit message
1046 if (d.statusbar_timer_.isActive())
1053 void GuiView::showMessage()
1055 QString msg = toqstr(theGuiApp()->viewStatusMessage());
1056 if (msg.isEmpty()) {
1057 BufferView const * bv = currentBufferView();
1059 msg = toqstr(bv->cursor().currentState());
1061 msg = qt_("Welcome to LyX!");
1063 statusBar()->showMessage(msg);
1067 bool GuiView::event(QEvent * e)
1071 // Useful debug code:
1072 //case QEvent::ActivationChange:
1073 //case QEvent::WindowDeactivate:
1074 //case QEvent::Paint:
1075 //case QEvent::Enter:
1076 //case QEvent::Leave:
1077 //case QEvent::HoverEnter:
1078 //case QEvent::HoverLeave:
1079 //case QEvent::HoverMove:
1080 //case QEvent::StatusTip:
1081 //case QEvent::DragEnter:
1082 //case QEvent::DragLeave:
1083 //case QEvent::Drop:
1086 case QEvent::WindowActivate: {
1087 GuiView * old_view = guiApp->currentView();
1088 if (this == old_view) {
1090 return QMainWindow::event(e);
1092 if (old_view && old_view->currentBufferView()) {
1093 // save current selection to the selection buffer to allow
1094 // middle-button paste in this window.
1095 cap::saveSelection(old_view->currentBufferView()->cursor());
1097 guiApp->setCurrentView(this);
1098 if (d.current_work_area_) {
1099 BufferView & bv = d.current_work_area_->bufferView();
1100 connectBufferView(bv);
1101 connectBuffer(bv.buffer());
1102 // The document structure, name and dialogs might have
1103 // changed in another view.
1105 // The document settings needs to be reinitialised.
1106 updateDialog("document", "");
1109 resetWindowTitleAndIconText();
1112 return QMainWindow::event(e);
1115 case QEvent::ShortcutOverride: {
1118 #if (!defined Q_WS_X11) || (QT_VERSION >= 0x040500)
1119 if (isFullScreen() && menuBar()->isHidden()) {
1120 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
1121 // FIXME: we should also try to detect special LyX shortcut such as
1122 // Alt-P and Alt-M. Right now there is a hack in
1123 // GuiWorkArea::processKeySym() that hides again the menubar for
1125 if (ke->modifiers() & Qt::AltModifier && ke->key() != Qt::Key_Alt) {
1127 return QMainWindow::event(e);
1131 return QMainWindow::event(e);
1135 return QMainWindow::event(e);
1139 void GuiView::resetWindowTitleAndIconText()
1141 setWindowTitle(qt_("LyX"));
1142 setWindowIconText(qt_("LyX"));
1145 bool GuiView::focusNextPrevChild(bool /*next*/)
1152 bool GuiView::busy() const
1158 void GuiView::setBusy(bool busy)
1160 bool const busy_before = busy_ > 0;
1161 busy ? ++busy_ : --busy_;
1162 if ((busy_ > 0) == busy_before)
1163 // busy state didn't change
1166 if (d.current_work_area_) {
1167 //Why would we want to stop updates only for one workarea and
1168 //not for the others ? This leads to problems as in #7314 (vfr).
1169 //d.current_work_area_->setUpdatesEnabled(!busy);
1171 d.current_work_area_->stopBlinkingCursor();
1173 d.current_work_area_->startBlinkingCursor();
1177 QApplication::setOverrideCursor(Qt::WaitCursor);
1179 QApplication::restoreOverrideCursor();
1183 GuiWorkArea * GuiView::workArea(int index)
1185 if (TabWorkArea * twa = d.currentTabWorkArea())
1186 if (index < twa->count())
1187 return dynamic_cast<GuiWorkArea *>(twa->widget(index));
1192 GuiWorkArea * GuiView::workArea(Buffer & buffer)
1194 if (currentWorkArea()
1195 && ¤tWorkArea()->bufferView().buffer() == &buffer)
1196 return (GuiWorkArea *) currentWorkArea();
1197 if (TabWorkArea * twa = d.currentTabWorkArea())
1198 return twa->workArea(buffer);
1203 GuiWorkArea * GuiView::addWorkArea(Buffer & buffer)
1205 // Automatically create a TabWorkArea if there are none yet.
1206 TabWorkArea * tab_widget = d.splitter_->count()
1207 ? d.currentTabWorkArea() : addTabWorkArea();
1208 return tab_widget->addWorkArea(buffer, *this);
1212 TabWorkArea * GuiView::addTabWorkArea()
1214 TabWorkArea * twa = new TabWorkArea;
1215 QObject::connect(twa, SIGNAL(currentWorkAreaChanged(GuiWorkArea *)),
1216 this, SLOT(on_currentWorkAreaChanged(GuiWorkArea *)));
1217 QObject::connect(twa, SIGNAL(lastWorkAreaRemoved()),
1218 this, SLOT(on_lastWorkAreaRemoved()));
1220 d.splitter_->addWidget(twa);
1221 d.stack_widget_->setCurrentWidget(d.splitter_);
1226 GuiWorkArea const * GuiView::currentWorkArea() const
1228 return d.current_work_area_;
1232 GuiWorkArea * GuiView::currentWorkArea()
1234 return d.current_work_area_;
1238 GuiWorkArea const * GuiView::currentMainWorkArea() const
1240 if (!d.currentTabWorkArea())
1242 return d.currentTabWorkArea()->currentWorkArea();
1246 GuiWorkArea * GuiView::currentMainWorkArea()
1248 if (!d.currentTabWorkArea())
1250 return d.currentTabWorkArea()->currentWorkArea();
1254 void GuiView::setCurrentWorkArea(GuiWorkArea * wa)
1256 LYXERR(Debug::DEBUG, "Setting current wa: " << wa << endl);
1258 d.current_work_area_ = 0;
1263 // FIXME: I've no clue why this is here and why it accesses
1264 // theGuiApp()->currentView, which might be 0 (bug 6464).
1265 // See also 27525 (vfr).
1266 if (theGuiApp()->currentView() == this
1267 && theGuiApp()->currentView()->currentWorkArea() == wa)
1270 if (currentBufferView())
1271 cap::saveSelection(currentBufferView()->cursor());
1273 theGuiApp()->setCurrentView(this);
1274 d.current_work_area_ = wa;
1276 // We need to reset this now, because it will need to be
1277 // right if the tabWorkArea gets reset in the for loop. We
1278 // will change it back if we aren't in that case.
1279 GuiWorkArea * const old_cmwa = d.current_main_work_area_;
1280 d.current_main_work_area_ = wa;
1282 for (int i = 0; i != d.splitter_->count(); ++i) {
1283 if (d.tabWorkArea(i)->setCurrentWorkArea(wa)) {
1284 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea()
1285 << ", Current main wa: " << currentMainWorkArea());
1290 d.current_main_work_area_ = old_cmwa;
1292 LYXERR(Debug::DEBUG, "This is not a tabbed wa");
1293 on_currentWorkAreaChanged(wa);
1294 BufferView & bv = wa->bufferView();
1295 bv.cursor().fixIfBroken();
1297 wa->setUpdatesEnabled(true);
1298 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() << ", Current main wa: " << currentMainWorkArea());
1302 void GuiView::removeWorkArea(GuiWorkArea * wa)
1304 LASSERT(wa, return);
1305 if (wa == d.current_work_area_) {
1307 disconnectBufferView();
1308 d.current_work_area_ = 0;
1309 d.current_main_work_area_ = 0;
1312 bool found_twa = false;
1313 for (int i = 0; i != d.splitter_->count(); ++i) {
1314 TabWorkArea * twa = d.tabWorkArea(i);
1315 if (twa->removeWorkArea(wa)) {
1316 // Found in this tab group, and deleted the GuiWorkArea.
1318 if (twa->count() != 0) {
1319 if (d.current_work_area_ == 0)
1320 // This means that we are closing the current GuiWorkArea, so
1321 // switch to the next GuiWorkArea in the found TabWorkArea.
1322 setCurrentWorkArea(twa->currentWorkArea());
1324 // No more WorkAreas in this tab group, so delete it.
1331 // It is not a tabbed work area (i.e., the search work area), so it
1332 // should be deleted by other means.
1333 LASSERT(found_twa, /* */);
1335 if (d.current_work_area_ == 0) {
1336 if (d.splitter_->count() != 0) {
1337 TabWorkArea * twa = d.currentTabWorkArea();
1338 setCurrentWorkArea(twa->currentWorkArea());
1340 // No more work areas, switch to the background widget.
1341 setCurrentWorkArea(0);
1347 LayoutBox * GuiView::getLayoutDialog() const
1353 void GuiView::updateLayoutList()
1356 d.layout_->updateContents(false);
1360 void GuiView::updateToolbars()
1362 ToolbarMap::iterator end = d.toolbars_.end();
1363 if (d.current_work_area_) {
1365 d.current_work_area_->bufferView().cursor().inMathed()
1366 && !d.current_work_area_->bufferView().cursor().inRegexped();
1368 lyx::getStatus(FuncRequest(LFUN_LAYOUT_TABULAR)).enabled();
1370 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).enabled() &&
1371 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).onOff(true);
1372 bool const mathmacrotemplate =
1373 lyx::getStatus(FuncRequest(LFUN_IN_MATHMACROTEMPLATE)).enabled();
1375 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1376 it->second->update(math, table, review, mathmacrotemplate);
1378 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1379 it->second->update(false, false, false, false);
1383 void GuiView::setBuffer(Buffer * newBuffer)
1385 LYXERR(Debug::DEBUG, "Setting buffer: " << newBuffer << endl);
1386 LASSERT(newBuffer, return);
1388 GuiWorkArea * wa = workArea(*newBuffer);
1391 newBuffer->masterBuffer()->updateBuffer();
1393 wa = addWorkArea(*newBuffer);
1394 // scroll to the position when the BufferView was last closed
1395 if (lyxrc.use_lastfilepos) {
1396 LastFilePosSection::FilePos filepos =
1397 theSession().lastFilePos().load(newBuffer->fileName());
1398 wa->bufferView().moveToPosition(filepos.pit, filepos.pos, 0, 0);
1401 //Disconnect the old buffer...there's no new one.
1404 connectBuffer(*newBuffer);
1405 connectBufferView(wa->bufferView());
1406 setCurrentWorkArea(wa);
1410 void GuiView::connectBuffer(Buffer & buf)
1412 buf.setGuiDelegate(this);
1416 void GuiView::disconnectBuffer()
1418 if (d.current_work_area_)
1419 d.current_work_area_->bufferView().buffer().setGuiDelegate(0);
1423 void GuiView::connectBufferView(BufferView & bv)
1425 bv.setGuiDelegate(this);
1429 void GuiView::disconnectBufferView()
1431 if (d.current_work_area_)
1432 d.current_work_area_->bufferView().setGuiDelegate(0);
1436 void GuiView::errors(string const & error_type, bool from_master)
1438 BufferView const * const bv = currentBufferView();
1442 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
1443 // We are called with from_master == false by default, so we
1444 // have to figure out whether that is the case or not.
1445 ErrorList & el = bv->buffer().errorList(error_type);
1447 el = bv->buffer().masterBuffer()->errorList(error_type);
1451 ErrorList & el = from_master ?
1452 bv->buffer().masterBuffer()->errorList(error_type) :
1453 bv->buffer().errorList(error_type);
1459 string data = error_type;
1461 data = "from_master|" + error_type;
1462 showDialog("errorlist", data);
1466 void GuiView::updateTocItem(string const & type, DocIterator const & dit)
1468 d.toc_models_.updateItem(toqstr(type), dit);
1472 void GuiView::structureChanged()
1474 d.toc_models_.reset(documentBufferView());
1475 // Navigator needs more than a simple update in this case. It needs to be
1477 updateDialog("toc", "");
1481 void GuiView::updateDialog(string const & name, string const & data)
1483 if (!isDialogVisible(name))
1486 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
1487 if (it == d.dialogs_.end())
1490 Dialog * const dialog = it->second.get();
1491 if (dialog->isVisibleView())
1492 dialog->initialiseParams(data);
1496 BufferView * GuiView::documentBufferView()
1498 return currentMainWorkArea()
1499 ? ¤tMainWorkArea()->bufferView()
1504 BufferView const * GuiView::documentBufferView() const
1506 return currentMainWorkArea()
1507 ? ¤tMainWorkArea()->bufferView()
1512 BufferView * GuiView::currentBufferView()
1514 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1518 BufferView const * GuiView::currentBufferView() const
1520 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1524 #if (QT_VERSION >= 0x040400)
1525 docstring GuiView::GuiViewPrivate::autosaveAndDestroy(
1526 Buffer const * orig, Buffer * buffer)
1528 bool const success = buffer->autoSave();
1530 busyBuffers.remove(orig);
1532 ? _("Automatic save done.")
1533 : _("Automatic save failed!");
1538 void GuiView::autoSave()
1540 LYXERR(Debug::INFO, "Running autoSave()");
1542 Buffer * buffer = documentBufferView()
1543 ? &documentBufferView()->buffer() : 0;
1545 resetAutosaveTimers();
1549 #if (QT_VERSION >= 0x040400)
1550 GuiViewPrivate::busyBuffers.insert(buffer);
1551 QFuture<docstring> f = QtConcurrent::run(GuiViewPrivate::autosaveAndDestroy,
1552 buffer, buffer->clone());
1553 d.autosave_watcher_.setFuture(f);
1557 resetAutosaveTimers();
1561 void GuiView::resetAutosaveTimers()
1564 d.autosave_timeout_.restart();
1568 bool GuiView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1571 Buffer * buf = currentBufferView()
1572 ? ¤tBufferView()->buffer() : 0;
1573 Buffer * doc_buffer = documentBufferView()
1574 ? &(documentBufferView()->buffer()) : 0;
1576 // Check whether we need a buffer
1577 if (!lyxaction.funcHasFlag(cmd.action(), LyXAction::NoBuffer) && !buf) {
1578 // no, exit directly
1579 flag.message(from_utf8(N_("Command not allowed with"
1580 "out any document open")));
1581 flag.setEnabled(false);
1585 if (cmd.origin() == FuncRequest::TOC) {
1586 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
1587 if (!toc || !toc->getStatus(documentBufferView()->cursor(), cmd, flag))
1588 flag.setEnabled(false);
1592 switch(cmd.action()) {
1593 case LFUN_BUFFER_IMPORT:
1596 case LFUN_MASTER_BUFFER_UPDATE:
1597 case LFUN_MASTER_BUFFER_VIEW:
1598 enable = doc_buffer && doc_buffer->parent() != 0
1599 && !d.processing_thread_watcher_.isRunning();
1602 case LFUN_BUFFER_UPDATE:
1603 case LFUN_BUFFER_VIEW: {
1604 if (!doc_buffer || d.processing_thread_watcher_.isRunning()) {
1608 string format = to_utf8(cmd.argument());
1609 if (cmd.argument().empty())
1610 format = doc_buffer->getDefaultOutputFormat();
1611 enable = doc_buffer->isExportableFormat(format);
1615 case LFUN_BUFFER_RELOAD:
1616 enable = doc_buffer && !doc_buffer->isUnnamed()
1617 && doc_buffer->fileName().exists()
1618 && (!doc_buffer->isClean()
1619 || doc_buffer->isExternallyModified(Buffer::timestamp_method));
1622 case LFUN_BUFFER_CHILD_OPEN:
1623 enable = doc_buffer;
1626 case LFUN_BUFFER_WRITE:
1627 enable = doc_buffer && (doc_buffer->isUnnamed() || !doc_buffer->isClean());
1630 //FIXME: This LFUN should be moved to GuiApplication.
1631 case LFUN_BUFFER_WRITE_ALL: {
1632 // We enable the command only if there are some modified buffers
1633 Buffer * first = theBufferList().first();
1638 // We cannot use a for loop as the buffer list is a cycle.
1640 if (!b->isClean()) {
1644 b = theBufferList().next(b);
1645 } while (b != first);
1649 case LFUN_BUFFER_WRITE_AS:
1650 enable = doc_buffer;
1653 case LFUN_BUFFER_CLOSE:
1654 enable = doc_buffer;
1657 case LFUN_BUFFER_CLOSE_ALL:
1658 enable = theBufferList().last() != theBufferList().first();
1661 case LFUN_SPLIT_VIEW:
1662 if (cmd.getArg(0) == "vertical")
1663 enable = doc_buffer && (d.splitter_->count() == 1 ||
1664 d.splitter_->orientation() == Qt::Vertical);
1666 enable = doc_buffer && (d.splitter_->count() == 1 ||
1667 d.splitter_->orientation() == Qt::Horizontal);
1670 case LFUN_CLOSE_TAB_GROUP:
1671 enable = d.currentTabWorkArea();
1674 case LFUN_TOOLBAR_TOGGLE: {
1675 string const name = cmd.getArg(0);
1676 if (GuiToolbar * t = toolbar(name))
1677 flag.setOnOff(t->isVisible());
1680 docstring const msg =
1681 bformat(_("Unknown toolbar \"%1$s\""), from_utf8(name));
1687 case LFUN_DROP_LAYOUTS_CHOICE:
1691 case LFUN_UI_TOGGLE:
1692 flag.setOnOff(isFullScreen());
1695 case LFUN_DIALOG_DISCONNECT_INSET:
1698 case LFUN_DIALOG_HIDE:
1699 // FIXME: should we check if the dialog is shown?
1702 case LFUN_DIALOG_TOGGLE:
1703 flag.setOnOff(isDialogVisible(cmd.getArg(0)));
1704 // fall through to set "enable"
1705 case LFUN_DIALOG_SHOW: {
1706 string const name = cmd.getArg(0);
1708 enable = name == "aboutlyx"
1709 || name == "file" //FIXME: should be removed.
1711 || name == "texinfo"
1712 || name == "progress"
1713 || name == "compare";
1714 else if (name == "print")
1715 enable = doc_buffer->isExportable("dvi")
1716 && lyxrc.print_command != "none";
1717 else if (name == "character" || name == "symbols") {
1718 if (!buf || buf->isReadonly())
1721 Cursor const & cur = currentBufferView()->cursor();
1722 enable = !(cur.inTexted() && cur.paragraph().isPassThru());
1725 else if (name == "latexlog")
1726 enable = FileName(doc_buffer->logName()).isReadableFile();
1727 else if (name == "spellchecker")
1728 enable = theSpellChecker() && !doc_buffer->isReadonly();
1729 else if (name == "vclog")
1730 enable = doc_buffer->lyxvc().inUse();
1734 case LFUN_DIALOG_UPDATE: {
1735 string const name = cmd.getArg(0);
1737 enable = name == "prefs";
1741 case LFUN_COMMAND_EXECUTE:
1743 case LFUN_MENU_OPEN:
1744 // Nothing to check.
1747 case LFUN_COMPLETION_INLINE:
1748 if (!d.current_work_area_
1749 || !d.current_work_area_->completer().inlinePossible(
1750 currentBufferView()->cursor()))
1754 case LFUN_COMPLETION_POPUP:
1755 if (!d.current_work_area_
1756 || !d.current_work_area_->completer().popupPossible(
1757 currentBufferView()->cursor()))
1761 case LFUN_COMPLETION_COMPLETE:
1762 if (!d.current_work_area_
1763 || !d.current_work_area_->completer().inlinePossible(
1764 currentBufferView()->cursor()))
1768 case LFUN_COMPLETION_ACCEPT:
1769 if (!d.current_work_area_
1770 || (!d.current_work_area_->completer().popupVisible()
1771 && !d.current_work_area_->completer().inlineVisible()
1772 && !d.current_work_area_->completer().completionAvailable()))
1776 case LFUN_COMPLETION_CANCEL:
1777 if (!d.current_work_area_
1778 || (!d.current_work_area_->completer().popupVisible()
1779 && !d.current_work_area_->completer().inlineVisible()))
1783 case LFUN_BUFFER_ZOOM_OUT:
1784 enable = doc_buffer && lyxrc.zoom > 10;
1787 case LFUN_BUFFER_ZOOM_IN:
1788 enable = doc_buffer;
1791 case LFUN_BUFFER_NEXT:
1792 case LFUN_BUFFER_PREVIOUS:
1793 // FIXME: should we check is there is an previous or next buffer?
1795 case LFUN_BUFFER_SWITCH:
1796 // toggle on the current buffer, but do not toggle off
1797 // the other ones (is that a good idea?)
1799 && to_utf8(cmd.argument()) == doc_buffer->absFileName())
1800 flag.setOnOff(true);
1803 case LFUN_VC_REGISTER:
1804 enable = doc_buffer && !doc_buffer->lyxvc().inUse();
1806 case LFUN_VC_CHECK_IN:
1807 enable = doc_buffer && doc_buffer->lyxvc().checkInEnabled();
1809 case LFUN_VC_CHECK_OUT:
1810 enable = doc_buffer && doc_buffer->lyxvc().checkOutEnabled();
1812 case LFUN_VC_LOCKING_TOGGLE:
1813 enable = doc_buffer && !doc_buffer->isReadonly()
1814 && doc_buffer->lyxvc().lockingToggleEnabled();
1815 flag.setOnOff(enable && doc_buffer->lyxvc().locking());
1817 case LFUN_VC_REVERT:
1818 enable = doc_buffer && doc_buffer->lyxvc().inUse() && !doc_buffer->isReadonly();
1820 case LFUN_VC_UNDO_LAST:
1821 enable = doc_buffer && doc_buffer->lyxvc().undoLastEnabled();
1823 case LFUN_VC_REPO_UPDATE:
1824 enable = doc_buffer && doc_buffer->lyxvc().repoUpdateEnabled();
1826 case LFUN_VC_COMMAND: {
1827 if (cmd.argument().empty())
1829 if (!doc_buffer && contains(cmd.getArg(0), 'D'))
1833 case LFUN_VC_COMPARE:
1834 enable = doc_buffer && doc_buffer->lyxvc().prepareFileRevisionEnabled();
1837 case LFUN_SERVER_GOTO_FILE_ROW:
1839 case LFUN_FORWARD_SEARCH:
1840 enable = !(lyxrc.forward_search_dvi.empty() && lyxrc.forward_search_pdf.empty());
1848 flag.setEnabled(false);
1854 static FileName selectTemplateFile()
1856 FileDialog dlg(qt_("Select template file"));
1857 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1858 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
1860 FileDialog::Result result = dlg.open(toqstr(lyxrc.template_path),
1861 QStringList(qt_("LyX Documents (*.lyx)")));
1863 if (result.first == FileDialog::Later)
1865 if (result.second.isEmpty())
1867 return FileName(fromqstr(result.second));
1871 Buffer * GuiView::loadDocument(FileName const & filename, bool tolastfiles)
1875 Buffer * newBuffer = 0;
1877 newBuffer = checkAndLoadLyXFile(filename);
1878 } catch (ExceptionMessage const & e) {
1885 message(_("Document not loaded."));
1889 newBuffer->errors("Parse");
1890 setBuffer(newBuffer);
1893 theSession().lastFiles().add(filename);
1899 void GuiView::openDocument(string const & fname)
1901 string initpath = lyxrc.document_path;
1903 if (documentBufferView()) {
1904 string const trypath = documentBufferView()->buffer().filePath();
1905 // If directory is writeable, use this as default.
1906 if (FileName(trypath).isDirWritable())
1912 if (fname.empty()) {
1913 FileDialog dlg(qt_("Select document to open"), LFUN_FILE_OPEN);
1914 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1915 dlg.setButton2(qt_("Examples|#E#e"),
1916 toqstr(addPath(package().system_support().absFileName(), "examples")));
1918 QStringList filter(qt_("LyX Documents (*.lyx)"));
1919 filter << qt_("LyX-1.3.x Documents (*.lyx13)")
1920 << qt_("LyX-1.4.x Documents (*.lyx14)")
1921 << qt_("LyX-1.5.x Documents (*.lyx15)")
1922 << qt_("LyX-1.6.x Documents (*.lyx16)");
1923 FileDialog::Result result =
1924 dlg.open(toqstr(initpath), filter);
1926 if (result.first == FileDialog::Later)
1929 filename = fromqstr(result.second);
1931 // check selected filename
1932 if (filename.empty()) {
1933 message(_("Canceled."));
1939 // get absolute path of file and add ".lyx" to the filename if
1941 FileName const fullname =
1942 fileSearch(string(), filename, "lyx", support::may_not_exist);
1943 if (!fullname.empty())
1944 filename = fullname.absFileName();
1946 if (!fullname.onlyPath().isDirectory()) {
1947 Alert::warning(_("Invalid filename"),
1948 bformat(_("The directory in the given path\n%1$s\ndoes not exist."),
1949 from_utf8(fullname.absFileName())));
1953 // if the file doesn't exist and isn't already open (bug 6645),
1954 // let the user create one
1955 if (!fullname.exists() && !theBufferList().exists(fullname)) {
1956 // the user specifically chose this name. Believe him.
1957 Buffer * const b = newFile(filename, string(), true);
1963 docstring const disp_fn = makeDisplayPath(filename);
1964 message(bformat(_("Opening document %1$s..."), disp_fn));
1967 Buffer * buf = loadDocument(fullname);
1969 str2 = bformat(_("Document %1$s opened."), disp_fn);
1970 if (buf->lyxvc().inUse())
1971 str2 += " " + from_utf8(buf->lyxvc().versionString()) +
1972 " " + _("Version control detected.");
1974 str2 = bformat(_("Could not open document %1$s"), disp_fn);
1979 // FIXME: clean that
1980 static bool import(GuiView * lv, FileName const & filename,
1981 string const & format, ErrorList & errorList)
1983 FileName const lyxfile(support::changeExtension(filename.absFileName(), ".lyx"));
1985 string loader_format;
1986 vector<string> loaders = theConverters().loaders();
1987 if (find(loaders.begin(), loaders.end(), format) == loaders.end()) {
1988 for (vector<string>::const_iterator it = loaders.begin();
1989 it != loaders.end(); ++it) {
1990 if (!theConverters().isReachable(format, *it))
1993 string const tofile =
1994 support::changeExtension(filename.absFileName(),
1995 formats.extension(*it));
1996 if (!theConverters().convert(0, filename, FileName(tofile),
1997 filename, format, *it, errorList))
1999 loader_format = *it;
2002 if (loader_format.empty()) {
2003 frontend::Alert::error(_("Couldn't import file"),
2004 bformat(_("No information for importing the format %1$s."),
2005 formats.prettyName(format)));
2009 loader_format = format;
2011 if (loader_format == "lyx") {
2012 Buffer * buf = lv->loadDocument(lyxfile);
2016 Buffer * const b = newFile(lyxfile.absFileName(), string(), true);
2020 bool as_paragraphs = loader_format == "textparagraph";
2021 string filename2 = (loader_format == format) ? filename.absFileName()
2022 : support::changeExtension(filename.absFileName(),
2023 formats.extension(loader_format));
2024 lv->currentBufferView()->insertPlaintextFile(FileName(filename2),
2026 guiApp->setCurrentView(lv);
2027 lyx::dispatch(FuncRequest(LFUN_MARK_OFF));
2034 void GuiView::importDocument(string const & argument)
2037 string filename = split(argument, format, ' ');
2039 LYXERR(Debug::INFO, format << " file: " << filename);
2041 // need user interaction
2042 if (filename.empty()) {
2043 string initpath = lyxrc.document_path;
2044 if (documentBufferView()) {
2045 string const trypath = documentBufferView()->buffer().filePath();
2046 // If directory is writeable, use this as default.
2047 if (FileName(trypath).isDirWritable())
2051 docstring const text = bformat(_("Select %1$s file to import"),
2052 formats.prettyName(format));
2054 FileDialog dlg(toqstr(text), LFUN_BUFFER_IMPORT);
2055 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2056 dlg.setButton2(qt_("Examples|#E#e"),
2057 toqstr(addPath(package().system_support().absFileName(), "examples")));
2059 docstring filter = formats.prettyName(format);
2062 filter += from_utf8(formats.extension(format));
2065 FileDialog::Result result =
2066 dlg.open(toqstr(initpath), fileFilters(toqstr(filter)));
2068 if (result.first == FileDialog::Later)
2071 filename = fromqstr(result.second);
2073 // check selected filename
2074 if (filename.empty())
2075 message(_("Canceled."));
2078 if (filename.empty())
2081 // get absolute path of file
2082 FileName const fullname(support::makeAbsPath(filename));
2084 FileName const lyxfile(support::changeExtension(fullname.absFileName(), ".lyx"));
2086 // Check if the document already is open
2087 Buffer * buf = theBufferList().getBuffer(lyxfile);
2090 if (!closeBuffer()) {
2091 message(_("Canceled."));
2096 docstring const displaypath = makeDisplayPath(lyxfile.absFileName(), 30);
2098 // if the file exists already, and we didn't do
2099 // -i lyx thefile.lyx, warn
2100 if (lyxfile.exists() && fullname != lyxfile) {
2102 docstring text = bformat(_("The document %1$s already exists.\n\n"
2103 "Do you want to overwrite that document?"), displaypath);
2104 int const ret = Alert::prompt(_("Overwrite document?"),
2105 text, 0, 1, _("&Overwrite"), _("&Cancel"));
2108 message(_("Canceled."));
2113 message(bformat(_("Importing %1$s..."), displaypath));
2114 ErrorList errorList;
2115 if (import(this, fullname, format, errorList))
2116 message(_("imported."));
2118 message(_("file not imported!"));
2120 // FIXME (Abdel 12/08/06): Is there a need to display the error list here?
2124 void GuiView::newDocument(string const & filename, bool from_template)
2126 FileName initpath(lyxrc.document_path);
2127 if (documentBufferView()) {
2128 FileName const trypath(documentBufferView()->buffer().filePath());
2129 // If directory is writeable, use this as default.
2130 if (trypath.isDirWritable())
2134 string templatefile;
2135 if (from_template) {
2136 templatefile = selectTemplateFile().absFileName();
2137 if (templatefile.empty())
2142 if (filename.empty())
2143 b = newUnnamedFile(initpath, to_utf8(_("newfile")), templatefile);
2145 b = newFile(filename, templatefile, true);
2150 // If no new document could be created, it is unsure
2151 // whether there is a valid BufferView.
2152 if (currentBufferView())
2153 // Ensure the cursor is correctly positioned on screen.
2154 currentBufferView()->showCursor();
2158 void GuiView::insertLyXFile(docstring const & fname)
2160 BufferView * bv = documentBufferView();
2165 FileName filename(to_utf8(fname));
2166 if (filename.empty()) {
2167 // Launch a file browser
2169 string initpath = lyxrc.document_path;
2170 string const trypath = bv->buffer().filePath();
2171 // If directory is writeable, use this as default.
2172 if (FileName(trypath).isDirWritable())
2176 FileDialog dlg(qt_("Select LyX document to insert"), LFUN_FILE_INSERT);
2177 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2178 dlg.setButton2(qt_("Examples|#E#e"),
2179 toqstr(addPath(package().system_support().absFileName(),
2182 FileDialog::Result result = dlg.open(toqstr(initpath),
2183 QStringList(qt_("LyX Documents (*.lyx)")));
2185 if (result.first == FileDialog::Later)
2189 filename.set(fromqstr(result.second));
2191 // check selected filename
2192 if (filename.empty()) {
2193 // emit message signal.
2194 message(_("Canceled."));
2199 bv->insertLyXFile(filename);
2200 bv->buffer().errors("Parse");
2204 void GuiView::insertPlaintextFile(docstring const & fname,
2207 BufferView * bv = documentBufferView();
2211 if (!fname.empty() && !FileName::isAbsolute(to_utf8(fname))) {
2212 message(_("Absolute filename expected."));
2217 FileName filename(to_utf8(fname));
2219 if (!filename.empty()) {
2220 bv->insertPlaintextFile(filename, asParagraph);
2224 FileDialog dlg(qt_("Select file to insert"), (asParagraph ?
2225 LFUN_FILE_INSERT_PLAINTEXT_PARA : LFUN_FILE_INSERT_PLAINTEXT));
2227 FileDialog::Result result = dlg.open(toqstr(bv->buffer().filePath()),
2228 QStringList(qt_("All Files (*)")));
2230 if (result.first == FileDialog::Later)
2234 filename.set(fromqstr(result.second));
2236 // check selected filename
2237 if (filename.empty()) {
2238 // emit message signal.
2239 message(_("Canceled."));
2243 bv->insertPlaintextFile(filename, asParagraph);
2247 bool GuiView::renameBuffer(Buffer & b, docstring const & newname)
2249 FileName fname = b.fileName();
2250 FileName const oldname = fname;
2252 if (!newname.empty()) {
2254 fname = support::makeAbsPath(to_utf8(newname), oldname.onlyPath().absFileName());
2256 // Switch to this Buffer.
2259 // No argument? Ask user through dialog.
2261 FileDialog dlg(qt_("Choose a filename to save document as"),
2262 LFUN_BUFFER_WRITE_AS);
2263 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2264 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
2266 if (!isLyXFileName(fname.absFileName()))
2267 fname.changeExtension(".lyx");
2269 FileDialog::Result result =
2270 dlg.save(toqstr(fname.onlyPath().absFileName()),
2271 QStringList(qt_("LyX Documents (*.lyx)")),
2272 toqstr(fname.onlyFileName()));
2274 if (result.first == FileDialog::Later)
2277 fname.set(fromqstr(result.second));
2282 if (!isLyXFileName(fname.absFileName()))
2283 fname.changeExtension(".lyx");
2286 // fname is now the new Buffer location.
2287 if (FileName(fname).exists()) {
2288 docstring const file = makeDisplayPath(fname.absFileName(), 30);
2289 docstring text = bformat(_("The document %1$s already "
2290 "exists.\n\nDo you want to "
2291 "overwrite that document?"),
2293 int const ret = Alert::prompt(_("Overwrite document?"),
2294 text, 0, 2, _("&Overwrite"), _("&Rename"), _("&Cancel"));
2297 case 1: return renameBuffer(b, docstring());
2298 case 2: return false;
2302 return saveBuffer(b, fname);
2306 bool GuiView::saveBuffer(Buffer & b) {
2307 return saveBuffer(b, FileName());
2311 bool GuiView::saveBuffer(Buffer & b, FileName const & fn)
2313 if (workArea(b) && workArea(b)->inDialogMode())
2316 if (fn.empty() && b.isUnnamed())
2317 return renameBuffer(b, docstring());
2323 success = b.saveAs(fn);
2326 theSession().lastFiles().add(b.fileName());
2330 // Switch to this Buffer.
2333 // FIXME: we don't tell the user *WHY* the save failed !!
2334 docstring const file = makeDisplayPath(b.absFileName(), 30);
2335 docstring text = bformat(_("The document %1$s could not be saved.\n\n"
2336 "Do you want to rename the document and "
2337 "try again?"), file);
2338 int const ret = Alert::prompt(_("Rename and save?"),
2339 text, 0, 2, _("&Rename"), _("&Retry"), _("&Cancel"));
2342 if (!renameBuffer(b, docstring()))
2351 return saveBuffer(b);
2355 bool GuiView::hideWorkArea(GuiWorkArea * wa)
2357 return closeWorkArea(wa, false);
2361 bool GuiView::closeWorkArea(GuiWorkArea * wa)
2363 Buffer & buf = wa->bufferView().buffer();
2364 return closeWorkArea(wa, !buf.parent());
2368 bool GuiView::closeBuffer()
2370 GuiWorkArea * wa = currentMainWorkArea();
2371 setCurrentWorkArea(wa);
2372 Buffer & buf = wa->bufferView().buffer();
2373 return wa && closeWorkArea(wa, !buf.parent());
2377 void GuiView::writeSession() const {
2378 GuiWorkArea const * active_wa = currentMainWorkArea();
2379 for (int i = 0; i < d.splitter_->count(); ++i) {
2380 TabWorkArea * twa = d.tabWorkArea(i);
2381 for (int j = 0; j < twa->count(); ++j) {
2382 GuiWorkArea * wa = static_cast<GuiWorkArea *>(twa->widget(j));
2383 Buffer & buf = wa->bufferView().buffer();
2384 theSession().lastOpened().add(buf.fileName(), wa == active_wa);
2390 bool GuiView::closeBufferAll()
2392 // Close the workareas in all other views
2393 QList<int> const ids = guiApp->viewIds();
2394 for (int i = 0; i != ids.size(); ++i) {
2395 if (id_ != ids[i] && !guiApp->view(ids[i]).closeWorkAreaAll())
2399 // Close our own workareas
2400 if (!closeWorkAreaAll())
2403 // Now close the hidden buffers. We prevent hidden buffers from being
2404 // dirty, so we can just close them.
2405 theBufferList().closeAll();
2410 bool GuiView::closeWorkAreaAll()
2412 setCurrentWorkArea(currentMainWorkArea());
2414 // We might be in a situation that there is still a tabWorkArea, but
2415 // there are no tabs anymore. This can happen when we get here after a
2416 // TabWorkArea::lastWorkAreaRemoved() signal. Therefore we count how
2417 // many TabWorkArea's have no documents anymore.
2420 // We have to call count() each time, because it can happen that
2421 // more than one splitter will disappear in one iteration (bug 5998).
2422 for (; d.splitter_->count() > empty_twa; ) {
2423 TabWorkArea * twa = d.tabWorkArea(empty_twa);
2425 if (twa->count() == 0)
2428 setCurrentWorkArea(twa->currentWorkArea());
2429 if (!closeTabWorkArea(twa))
2437 bool GuiView::closeWorkArea(GuiWorkArea * wa, bool close_buffer)
2442 Buffer & buf = wa->bufferView().buffer();
2444 if (close_buffer && GuiViewPrivate::busyBuffers.contains(&buf)) {
2445 Alert::warning(_("Close document"),
2446 _("Document could not be closed because it is being processed by LyX."));
2451 return closeBuffer(buf);
2453 if (!inMultiTabs(wa))
2454 if (!saveBufferIfNeeded(buf, true))
2462 bool GuiView::closeBuffer(Buffer & buf)
2464 // If we are in a close_event all children will be closed in some time,
2465 // so no need to do it here. This will ensure that the children end up
2466 // in the session file in the correct order. If we close the master
2467 // buffer, we can close or release the child buffers here too.
2468 bool success = true;
2470 ListOfBuffers clist = buf.getChildren();
2471 ListOfBuffers::const_iterator it = clist.begin();
2472 ListOfBuffers::const_iterator const bend = clist.end();
2473 for (; it != bend; ++it) {
2474 // If a child is dirty, do not close
2475 // without user intervention
2476 //FIXME: should we look in other tabworkareas?
2477 Buffer * child_buf = *it;
2478 GuiWorkArea * child_wa = workArea(*child_buf);
2480 if (!closeWorkArea(child_wa, true)) {
2485 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);
2501 // open all children again to avoid a crash because of dangling
2502 // pointers (bug 6603)
2508 bool GuiView::closeTabWorkArea(TabWorkArea * twa)
2510 while (twa == d.currentTabWorkArea()) {
2511 twa->setCurrentIndex(twa->count()-1);
2513 GuiWorkArea * wa = twa->currentWorkArea();
2514 Buffer & b = wa->bufferView().buffer();
2516 // We only want to close the buffer if the same buffer is not visible
2517 // in another view, and if this is not a child and if we are closing
2518 // a view (not a tabgroup).
2519 bool const close_buffer =
2520 !inOtherView(b) && !b.parent() && closing_;
2522 if (!closeWorkArea(wa, close_buffer))
2529 bool GuiView::saveBufferIfNeeded(Buffer & buf, bool hiding)
2531 if (buf.isClean() || buf.paragraphs().empty())
2534 // Switch to this Buffer.
2539 if (buf.isUnnamed())
2540 file = from_utf8(buf.fileName().onlyFileName());
2542 file = buf.fileName().displayName(30);
2544 // Bring this window to top before asking questions.
2549 if (hiding && buf.isUnnamed()) {
2550 docstring const text = bformat(_("The document %1$s has not been "
2551 "saved yet.\n\nDo you want to save "
2552 "the document?"), file);
2553 ret = Alert::prompt(_("Save new document?"),
2554 text, 0, 1, _("&Save"), _("&Cancel"));
2558 docstring const text = bformat(_("The document %1$s has unsaved changes."
2559 "\n\nDo you want to save the document or discard the changes?"), file);
2560 ret = Alert::prompt(_("Save changed document?"),
2561 text, 0, 2, _("&Save"), _("&Discard"), _("&Cancel"));
2566 if (!saveBuffer(buf))
2570 // If we crash after this we could have no autosave file
2571 // but I guess this is really improbable (Jug).
2572 // Sometimes improbable things happen:
2573 // - see bug http://www.lyx.org/trac/ticket/6587 (ps)
2574 // buf.removeAutosaveFile();
2576 // revert all changes
2587 bool GuiView::inMultiTabs(GuiWorkArea * wa)
2589 Buffer & buf = wa->bufferView().buffer();
2591 for (int i = 0; i != d.splitter_->count(); ++i) {
2592 GuiWorkArea * wa_ = d.tabWorkArea(i)->workArea(buf);
2593 if (wa_ && wa_ != wa)
2596 return inOtherView(buf);
2600 bool GuiView::inOtherView(Buffer & buf)
2602 QList<int> const ids = guiApp->viewIds();
2604 for (int i = 0; i != ids.size(); ++i) {
2608 if (guiApp->view(ids[i]).workArea(buf))
2615 void GuiView::gotoNextOrPreviousBuffer(NextOrPrevious np)
2617 if (!documentBufferView())
2620 if (TabWorkArea * twa = d.currentTabWorkArea()) {
2621 Buffer * const curbuf = &documentBufferView()->buffer();
2622 int nwa = twa->count();
2623 for (int i = 0; i < nwa; ++i) {
2624 if (&workArea(i)->bufferView().buffer() == curbuf) {
2626 if (np == NEXTBUFFER)
2627 next_index = (i == nwa - 1 ? 0 : i + 1);
2629 next_index = (i == 0 ? nwa - 1 : i - 1);
2630 setBuffer(&workArea(next_index)->bufferView().buffer());
2638 /// make sure the document is saved
2639 static bool ensureBufferClean(Buffer * buffer)
2641 LASSERT(buffer, return false);
2642 if (buffer->isClean() && !buffer->isUnnamed())
2645 docstring const file = buffer->fileName().displayName(30);
2648 if (!buffer->isUnnamed()) {
2649 text = bformat(_("The document %1$s has unsaved "
2650 "changes.\n\nDo you want to save "
2651 "the document?"), file);
2652 title = _("Save changed document?");
2655 text = bformat(_("The document %1$s has not been "
2656 "saved yet.\n\nDo you want to save "
2657 "the document?"), file);
2658 title = _("Save new document?");
2660 int const ret = Alert::prompt(title, text, 0, 1, _("&Save"), _("&Cancel"));
2663 dispatch(FuncRequest(LFUN_BUFFER_WRITE));
2665 return buffer->isClean() && !buffer->isUnnamed();
2669 bool GuiView::reloadBuffer(Buffer & buf)
2671 Buffer::ReadStatus status = buf.reload();
2672 return status == Buffer::ReadSuccess;
2676 void GuiView::checkExternallyModifiedBuffers()
2678 BufferList::iterator bit = theBufferList().begin();
2679 BufferList::iterator const bend = theBufferList().end();
2680 for (; bit != bend; ++bit) {
2681 Buffer * buf = *bit;
2682 if (buf->fileName().exists()
2683 && buf->isExternallyModified(Buffer::checksum_method)) {
2684 docstring text = bformat(_("Document \n%1$s\n has been externally modified."
2685 " Reload now? Any local changes will be lost."),
2686 from_utf8(buf->absFileName()));
2687 int const ret = Alert::prompt(_("Reload externally changed document?"),
2688 text, 0, 1, _("&Reload"), _("&Cancel"));
2696 void GuiView::dispatchVC(FuncRequest const & cmd, DispatchResult & dr)
2698 Buffer * buffer = documentBufferView()
2699 ? &(documentBufferView()->buffer()) : 0;
2701 switch (cmd.action()) {
2702 case LFUN_VC_REGISTER:
2703 if (!buffer || !ensureBufferClean(buffer))
2705 if (!buffer->lyxvc().inUse()) {
2706 if (buffer->lyxvc().registrer()) {
2707 reloadBuffer(*buffer);
2708 dr.suppressMessageUpdate();
2713 case LFUN_VC_CHECK_IN:
2714 if (!buffer || !ensureBufferClean(buffer))
2716 if (buffer->lyxvc().inUse() && !buffer->isReadonly()) {
2717 dr.setMessage(buffer->lyxvc().checkIn());
2718 if (!dr.message().empty())
2719 reloadBuffer(*buffer);
2723 case LFUN_VC_CHECK_OUT:
2724 if (!buffer || !ensureBufferClean(buffer))
2726 if (buffer->lyxvc().inUse()) {
2727 dr.setMessage(buffer->lyxvc().checkOut());
2728 reloadBuffer(*buffer);
2732 case LFUN_VC_LOCKING_TOGGLE:
2733 LASSERT(buffer, return);
2734 if (!ensureBufferClean(buffer) || buffer->isReadonly())
2736 if (buffer->lyxvc().inUse()) {
2737 string res = buffer->lyxvc().lockingToggle();
2739 frontend::Alert::error(_("Revision control error."),
2740 _("Error when setting the locking property."));
2743 reloadBuffer(*buffer);
2748 case LFUN_VC_REVERT:
2749 LASSERT(buffer, return);
2750 if (buffer->lyxvc().revert()) {
2751 reloadBuffer(*buffer);
2752 dr.suppressMessageUpdate();
2756 case LFUN_VC_UNDO_LAST:
2757 LASSERT(buffer, return);
2758 buffer->lyxvc().undoLast();
2759 reloadBuffer(*buffer);
2760 dr.suppressMessageUpdate();
2763 case LFUN_VC_REPO_UPDATE:
2764 LASSERT(buffer, return);
2765 if (ensureBufferClean(buffer)) {
2766 dr.setMessage(buffer->lyxvc().repoUpdate());
2767 checkExternallyModifiedBuffers();
2771 case LFUN_VC_COMMAND: {
2772 string flag = cmd.getArg(0);
2773 if (buffer && contains(flag, 'R') && !ensureBufferClean(buffer))
2776 if (contains(flag, 'M')) {
2777 if (!Alert::askForText(message, _("LyX VC: Log Message")))
2780 string path = cmd.getArg(1);
2781 if (contains(path, "$$p") && buffer)
2782 path = subst(path, "$$p", buffer->filePath());
2783 LYXERR(Debug::LYXVC, "Directory: " << path);
2785 if (!pp.isReadableDirectory()) {
2786 lyxerr << _("Directory is not accessible.") << endl;
2789 support::PathChanger p(pp);
2791 string command = cmd.getArg(2);
2792 if (command.empty())
2795 command = subst(command, "$$i", buffer->absFileName());
2796 command = subst(command, "$$p", buffer->filePath());
2798 command = subst(command, "$$m", to_utf8(message));
2799 LYXERR(Debug::LYXVC, "Command: " << command);
2801 one.startscript(Systemcall::Wait, command);
2805 if (contains(flag, 'I'))
2806 buffer->markDirty();
2807 if (contains(flag, 'R'))
2808 reloadBuffer(*buffer);
2813 case LFUN_VC_COMPARE: {
2815 if (cmd.argument().empty()) {
2816 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "comparehistory"));
2820 string rev1 = cmd.getArg(0);
2824 if (!buffer->lyxvc().prepareFileRevision(rev1, f1))
2827 if (isStrInt(rev1) && convert<int>(rev1) <= 0) {
2828 f2 = buffer->absFileName();
2830 string rev2 = cmd.getArg(1);
2834 if (!buffer->lyxvc().prepareFileRevision(rev2, f2))
2838 LYXERR(Debug::LYXVC, "Launching comparison for fetched revisions:\n" <<
2839 f1 << "\n" << f2 << "\n" );
2840 string par = "compare run " + quoteName(f1) + " " + quoteName(f2);
2841 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, par));
2851 void GuiView::openChildDocument(string const & fname)
2853 LASSERT(documentBufferView(), return);
2854 Buffer & buffer = documentBufferView()->buffer();
2855 FileName const filename = support::makeAbsPath(fname, buffer.filePath());
2856 documentBufferView()->saveBookmark(false);
2858 if (theBufferList().exists(filename)) {
2859 child = theBufferList().getBuffer(filename);
2862 message(bformat(_("Opening child document %1$s..."),
2863 makeDisplayPath(filename.absFileName())));
2864 child = loadDocument(filename, false);
2866 // Set the parent name of the child document.
2867 // This makes insertion of citations and references in the child work,
2868 // when the target is in the parent or another child document.
2870 child->setParent(&buffer);
2874 bool GuiView::goToFileRow(string const & argument)
2878 size_t i = argument.find_last_of(' ');
2879 if (i != string::npos) {
2880 file_name = os::internal_path(trim(argument.substr(0, i)));
2881 istringstream is(argument.substr(i + 1));
2886 if (i == string::npos) {
2887 LYXERR0("Wrong argument: " << argument);
2891 string const abstmp = package().temp_dir().absFileName();
2892 string const realtmp = package().temp_dir().realPath();
2893 // We have to use os::path_prefix_is() here, instead of
2894 // simply prefixIs(), because the file name comes from
2895 // an external application and may need case adjustment.
2896 if (os::path_prefix_is(file_name, abstmp, os::CASE_ADJUSTED)
2897 || os::path_prefix_is(file_name, realtmp, os::CASE_ADJUSTED)) {
2898 // Needed by inverse dvi search. If it is a file
2899 // in tmpdir, call the apropriated function.
2900 // If tmpdir is a symlink, we may have the real
2901 // path passed back, so we correct for that.
2902 if (!prefixIs(file_name, abstmp))
2903 file_name = subst(file_name, realtmp, abstmp);
2904 buf = theBufferList().getBufferFromTmp(file_name);
2906 // Must replace extension of the file to be .lyx
2907 // and get full path
2908 FileName const s = fileSearch(string(),
2909 support::changeExtension(file_name, ".lyx"), "lyx");
2910 // Either change buffer or load the file
2911 if (theBufferList().exists(s))
2912 buf = theBufferList().getBuffer(s);
2913 else if (s.exists()) {
2914 buf = loadDocument(s);
2919 _("File does not exist: %1$s"),
2920 makeDisplayPath(file_name)));
2925 documentBufferView()->setCursorFromRow(row);
2930 #if (QT_VERSION >= 0x040400)
2932 docstring GuiView::GuiViewPrivate::runAndDestroy(const T& func, Buffer const * orig, Buffer * buffer, string const & format, string const & msg)
2934 bool const update_unincluded =
2935 buffer->params().maintain_unincluded_children
2936 && !buffer->params().getIncludedChildren().empty();
2937 bool const success = func(format, update_unincluded);
2939 busyBuffers.remove(orig);
2940 if (msg == "preview") {
2942 ? bformat(_("Successful preview of format: %1$s"), from_utf8(format))
2943 : bformat(_("Error while previewing format: %1$s"), from_utf8(format));
2946 ? bformat(_("Successful export to format: %1$s"), from_utf8(format))
2947 : bformat(_("Error while exporting format: %1$s"), from_utf8(format));
2951 docstring GuiView::GuiViewPrivate::compileAndDestroy(Buffer const * orig, Buffer * buffer, string const & format)
2953 bool (Buffer::* mem_func)(std::string const &, bool, bool) const = &Buffer::doExport;
2954 return runAndDestroy(bind(mem_func, buffer, _1, true, _2), orig, buffer, format, "export");
2958 docstring GuiView::GuiViewPrivate::exportAndDestroy(Buffer const * orig, Buffer * buffer, string const & format)
2960 bool (Buffer::* mem_func)(std::string const &, bool, bool) const = &Buffer::doExport;
2961 return runAndDestroy(bind(mem_func, buffer, _1, false, _2), orig, buffer, format, "export");
2965 docstring GuiView::GuiViewPrivate::previewAndDestroy(Buffer const * orig, Buffer * buffer, string const & format)
2967 bool(Buffer::* mem_func)(std::string const &, bool) const = &Buffer::preview;
2968 return runAndDestroy(bind(mem_func, buffer, _1, _2), orig, buffer, format, "preview");
2973 // not used, but the linker needs them
2975 docstring GuiView::GuiViewPrivate::compileAndDestroy(
2976 Buffer const *, Buffer *, string const &)
2982 docstring GuiView::GuiViewPrivate::exportAndDestroy(
2983 Buffer const *, Buffer *, string const &)
2989 docstring GuiView::GuiViewPrivate::previewAndDestroy(
2990 Buffer const *, Buffer *, string const &)
2998 bool GuiView::GuiViewPrivate::asyncBufferProcessing(
2999 string const & argument,
3000 Buffer const * used_buffer,
3001 docstring const & msg,
3002 docstring (*asyncFunc)(Buffer const *, Buffer *, string const &),
3003 bool (Buffer::*syncFunc)(string const &, bool, bool) const,
3004 bool (Buffer::*previewFunc)(string const &, bool) const)
3009 string format = argument;
3011 format = used_buffer->getDefaultOutputFormat();
3013 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
3015 progress_->clearMessages();
3018 GuiViewPrivate::busyBuffers.insert(used_buffer);
3019 QFuture<docstring> f = QtConcurrent::run(
3022 used_buffer->clone(),
3024 setPreviewFuture(f);
3025 last_export_format = used_buffer->bufferFormat();
3028 // We are asynchronous, so we don't know here anything about the success
3032 // TODO check here if it breaks exporting with Qt < 4.4
3033 bool const update_unincluded =
3034 used_buffer->params().maintain_unincluded_children &&
3035 !used_buffer->params().getIncludedChildren().empty();
3036 return (used_buffer->*syncFunc)(format, true, update_unincluded);
3037 } else if (previewFunc) {
3038 return (used_buffer->*previewFunc)(format, false);
3045 void GuiView::dispatchToBufferView(FuncRequest const & cmd, DispatchResult & dr)
3047 BufferView * bv = currentBufferView();
3050 // Let the current BufferView dispatch its own actions.
3051 bv->dispatch(cmd, dr);
3052 if (dr.dispatched())
3055 // Try with the document BufferView dispatch if any.
3056 BufferView * doc_bv = documentBufferView();
3058 doc_bv->dispatch(cmd, dr);
3059 if (dr.dispatched())
3063 // Then let the current Cursor dispatch its own actions.
3064 bv->cursor().dispatch(cmd);
3066 // update completion. We do it here and not in
3067 // processKeySym to avoid another redraw just for a
3068 // changed inline completion
3069 if (cmd.origin() == FuncRequest::KEYBOARD) {
3070 if (cmd.action() == LFUN_SELF_INSERT
3071 || (cmd.action() == LFUN_ERT_INSERT && bv->cursor().inMathed()))
3072 updateCompletion(bv->cursor(), true, true);
3073 else if (cmd.action() == LFUN_CHAR_DELETE_BACKWARD)
3074 updateCompletion(bv->cursor(), false, true);
3076 updateCompletion(bv->cursor(), false, false);
3079 dr = bv->cursor().result();
3083 void GuiView::dispatch(FuncRequest const & cmd, DispatchResult & dr)
3085 BufferView * bv = currentBufferView();
3086 // By default we won't need any update.
3087 dr.screenUpdate(Update::None);
3088 // assume cmd will be dispatched
3089 dr.dispatched(true);
3091 Buffer * doc_buffer = documentBufferView()
3092 ? &(documentBufferView()->buffer()) : 0;
3094 if (cmd.origin() == FuncRequest::TOC) {
3095 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
3096 // FIXME: do we need to pass a DispatchResult object here?
3097 toc->doDispatch(bv->cursor(), cmd);
3101 string const argument = to_utf8(cmd.argument());
3103 switch(cmd.action()) {
3104 case LFUN_BUFFER_CHILD_OPEN:
3105 openChildDocument(to_utf8(cmd.argument()));
3108 case LFUN_BUFFER_IMPORT:
3109 importDocument(to_utf8(cmd.argument()));
3112 case LFUN_BUFFER_EXPORT: {
3115 // GCC only sees strfwd.h when building merged
3116 if (::lyx::operator==(cmd.argument(), "custom")) {
3117 dispatch(FuncRequest(LFUN_DIALOG_SHOW, "sendto"), dr);
3120 #if QT_VERSION < 0x040400
3121 if (!doc_buffer->doExport(argument, false)) {
3123 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
3127 /* TODO/Review: Is it a problem to also export the children?
3128 See the update_unincluded flag */
3129 d.asyncBufferProcessing(argument,
3132 &GuiViewPrivate::exportAndDestroy,
3135 // TODO Inform user about success
3140 case LFUN_BUFFER_UPDATE: {
3141 d.asyncBufferProcessing(argument,
3144 &GuiViewPrivate::compileAndDestroy,
3149 case LFUN_BUFFER_VIEW: {
3150 d.asyncBufferProcessing(argument,
3152 _("Previewing ..."),
3153 &GuiViewPrivate::previewAndDestroy,
3158 case LFUN_MASTER_BUFFER_UPDATE: {
3159 d.asyncBufferProcessing(argument,
3160 (doc_buffer ? doc_buffer->masterBuffer() : 0),
3162 &GuiViewPrivate::compileAndDestroy,
3167 case LFUN_MASTER_BUFFER_VIEW: {
3168 d.asyncBufferProcessing(argument,
3169 (doc_buffer ? doc_buffer->masterBuffer() : 0),
3171 &GuiViewPrivate::previewAndDestroy,
3172 0, &Buffer::preview);
3175 case LFUN_BUFFER_SWITCH: {
3176 string const file_name = to_utf8(cmd.argument());
3177 if (!FileName::isAbsolute(file_name)) {
3179 dr.setMessage(_("Absolute filename expected."));
3183 Buffer * buffer = theBufferList().getBuffer(FileName(file_name));
3186 dr.setMessage(_("Document not loaded"));
3190 // Do we open or switch to the buffer in this view ?
3191 if (workArea(*buffer)
3192 || lyxrc.open_buffers_in_tabs || !documentBufferView()) {
3197 // Look for the buffer in other views
3198 QList<int> const ids = guiApp->viewIds();
3200 for (; i != ids.size(); ++i) {
3201 GuiView & gv = guiApp->view(ids[i]);
3202 if (gv.workArea(*buffer)) {
3203 gv.activateWindow();
3204 gv.setBuffer(buffer);
3209 // If necessary, open a new window as a last resort
3210 if (i == ids.size()) {
3211 lyx::dispatch(FuncRequest(LFUN_WINDOW_NEW));
3217 case LFUN_BUFFER_NEXT:
3218 gotoNextOrPreviousBuffer(NEXTBUFFER);
3221 case LFUN_BUFFER_PREVIOUS:
3222 gotoNextOrPreviousBuffer(PREVBUFFER);
3225 case LFUN_COMMAND_EXECUTE: {
3226 bool const show_it = cmd.argument() != "off";
3227 // FIXME: this is a hack, "minibuffer" should not be
3229 if (GuiToolbar * t = toolbar("minibuffer")) {
3230 t->setVisible(show_it);
3231 if (show_it && t->commandBuffer())
3232 t->commandBuffer()->setFocus();
3236 case LFUN_DROP_LAYOUTS_CHOICE:
3237 d.layout_->showPopup();
3240 case LFUN_MENU_OPEN:
3241 if (QMenu * menu = guiApp->menus().menu(toqstr(cmd.argument()), *this))
3242 menu->exec(QCursor::pos());
3245 case LFUN_FILE_INSERT:
3246 insertLyXFile(cmd.argument());
3249 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
3250 insertPlaintextFile(cmd.argument(), true);
3253 case LFUN_FILE_INSERT_PLAINTEXT:
3254 insertPlaintextFile(cmd.argument(), false);
3257 case LFUN_BUFFER_RELOAD: {
3258 LASSERT(doc_buffer, break);
3261 if (!doc_buffer->isClean()) {
3262 docstring const file =
3263 makeDisplayPath(doc_buffer->absFileName(), 20);
3264 docstring text = bformat(_("Any changes will be lost. "
3265 "Are you sure you want to revert to the saved version "
3266 "of the document %1$s?"), file);
3267 ret = Alert::prompt(_("Revert to saved document?"),
3268 text, 1, 1, _("&Revert"), _("&Cancel"));
3272 doc_buffer->markClean();
3273 reloadBuffer(*doc_buffer);
3274 dr.forceBufferUpdate();
3279 case LFUN_BUFFER_WRITE:
3280 LASSERT(doc_buffer, break);
3281 saveBuffer(*doc_buffer);
3284 case LFUN_BUFFER_WRITE_AS:
3285 LASSERT(doc_buffer, break);
3286 renameBuffer(*doc_buffer, cmd.argument());
3289 case LFUN_BUFFER_WRITE_ALL: {
3290 Buffer * first = theBufferList().first();
3293 message(_("Saving all documents..."));
3294 // We cannot use a for loop as the buffer list cycles.
3297 if (!b->isClean()) {
3299 LYXERR(Debug::ACTION, "Saved " << b->absFileName());
3301 b = theBufferList().next(b);
3302 } while (b != first);
3303 dr.setMessage(_("All documents saved."));
3307 case LFUN_BUFFER_CLOSE:
3311 case LFUN_BUFFER_CLOSE_ALL:
3315 case LFUN_TOOLBAR_TOGGLE: {
3316 string const name = cmd.getArg(0);
3317 if (GuiToolbar * t = toolbar(name))
3322 case LFUN_DIALOG_UPDATE: {
3323 string const name = to_utf8(cmd.argument());
3324 if (name == "prefs" || name == "document")
3325 updateDialog(name, string());
3326 else if (name == "paragraph")
3327 lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
3328 else if (currentBufferView()) {
3329 Inset * inset = currentBufferView()->editedInset(name);
3330 // Can only update a dialog connected to an existing inset
3332 // FIXME: get rid of this indirection; GuiView ask the inset
3333 // if he is kind enough to update itself...
3334 FuncRequest fr(LFUN_INSET_DIALOG_UPDATE, cmd.argument());
3335 //FIXME: pass DispatchResult here?
3336 inset->dispatch(currentBufferView()->cursor(), fr);
3342 case LFUN_DIALOG_TOGGLE: {
3343 FuncCode const func_code = isDialogVisible(cmd.getArg(0))
3344 ? LFUN_DIALOG_HIDE : LFUN_DIALOG_SHOW;
3345 dispatch(FuncRequest(func_code, cmd.argument()), dr);
3349 case LFUN_DIALOG_DISCONNECT_INSET:
3350 disconnectDialog(to_utf8(cmd.argument()));
3353 case LFUN_DIALOG_HIDE: {
3354 guiApp->hideDialogs(to_utf8(cmd.argument()), 0);
3358 case LFUN_DIALOG_SHOW: {
3359 string const name = cmd.getArg(0);
3360 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
3362 if (name == "character") {
3363 data = freefont2string();
3365 showDialog("character", data);
3366 } else if (name == "latexlog") {
3367 Buffer::LogType type;
3368 string const logfile = doc_buffer->logName(&type);
3370 case Buffer::latexlog:
3373 case Buffer::buildlog:
3377 data += Lexer::quoteString(logfile);
3378 showDialog("log", data);
3379 } else if (name == "vclog") {
3380 string const data = "vc " +
3381 Lexer::quoteString(doc_buffer->lyxvc().getLogFile());
3382 showDialog("log", data);
3383 } else if (name == "symbols") {
3384 data = bv->cursor().getEncoding()->name();
3386 showDialog("symbols", data);
3388 } else if (name == "prefs" && isFullScreen()) {
3389 lfunUiToggle("fullscreen");
3390 showDialog("prefs", data);
3392 showDialog(name, data);
3397 dr.setMessage(cmd.argument());
3400 case LFUN_UI_TOGGLE: {
3401 string arg = cmd.getArg(0);
3402 if (!lfunUiToggle(arg)) {
3403 docstring const msg = "ui-toggle " + _("%1$s unknown command!");
3404 dr.setMessage(bformat(msg, from_utf8(arg)));
3406 // Make sure the keyboard focus stays in the work area.
3411 case LFUN_SPLIT_VIEW: {
3412 LASSERT(doc_buffer, break);
3413 string const orientation = cmd.getArg(0);
3414 d.splitter_->setOrientation(orientation == "vertical"
3415 ? Qt::Vertical : Qt::Horizontal);
3416 TabWorkArea * twa = addTabWorkArea();
3417 GuiWorkArea * wa = twa->addWorkArea(*doc_buffer, *this);
3418 setCurrentWorkArea(wa);
3421 case LFUN_CLOSE_TAB_GROUP:
3422 if (TabWorkArea * twa = d.currentTabWorkArea()) {
3423 closeTabWorkArea(twa);
3424 d.current_work_area_ = 0;
3425 twa = d.currentTabWorkArea();
3426 // Switch to the next GuiWorkArea in the found TabWorkArea.
3428 // Make sure the work area is up to date.
3429 setCurrentWorkArea(twa->currentWorkArea());
3431 setCurrentWorkArea(0);
3436 case LFUN_COMPLETION_INLINE:
3437 if (d.current_work_area_)
3438 d.current_work_area_->completer().showInline();
3441 case LFUN_COMPLETION_POPUP:
3442 if (d.current_work_area_)
3443 d.current_work_area_->completer().showPopup();
3447 case LFUN_COMPLETION_COMPLETE:
3448 if (d.current_work_area_)
3449 d.current_work_area_->completer().tab();
3452 case LFUN_COMPLETION_CANCEL:
3453 if (d.current_work_area_) {
3454 if (d.current_work_area_->completer().popupVisible())
3455 d.current_work_area_->completer().hidePopup();
3457 d.current_work_area_->completer().hideInline();
3461 case LFUN_COMPLETION_ACCEPT:
3462 if (d.current_work_area_)
3463 d.current_work_area_->completer().activate();
3466 case LFUN_BUFFER_ZOOM_IN:
3467 case LFUN_BUFFER_ZOOM_OUT:
3468 if (cmd.argument().empty()) {
3469 if (cmd.action() == LFUN_BUFFER_ZOOM_IN)
3474 lyxrc.zoom += convert<int>(cmd.argument());
3476 if (lyxrc.zoom < 10)
3479 // The global QPixmapCache is used in GuiPainter to cache text
3480 // painting so we must reset it.
3481 QPixmapCache::clear();
3482 guiApp->fontLoader().update();
3483 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
3486 case LFUN_VC_REGISTER:
3487 case LFUN_VC_CHECK_IN:
3488 case LFUN_VC_CHECK_OUT:
3489 case LFUN_VC_REPO_UPDATE:
3490 case LFUN_VC_LOCKING_TOGGLE:
3491 case LFUN_VC_REVERT:
3492 case LFUN_VC_UNDO_LAST:
3493 case LFUN_VC_COMMAND:
3494 case LFUN_VC_COMPARE:
3495 dispatchVC(cmd, dr);
3498 case LFUN_SERVER_GOTO_FILE_ROW:
3499 goToFileRow(to_utf8(cmd.argument()));
3502 case LFUN_FORWARD_SEARCH: {
3503 Buffer const * doc_master = doc_buffer->masterBuffer();
3504 FileName const path(doc_master->temppath());
3505 string const texname = doc_master->isChild(doc_buffer)
3506 ? DocFileName(changeExtension(
3507 doc_buffer->absFileName(),
3508 "tex")).mangledFileName()
3509 : doc_buffer->latexName();
3510 string const mastername =
3511 removeExtension(doc_master->latexName());
3512 FileName const dviname(addName(path.absFileName(),
3513 addExtension(mastername, "dvi")));
3514 FileName const pdfname(addName(path.absFileName(),
3515 addExtension(mastername, "pdf")));
3516 if (!dviname.exists() && !pdfname.exists()) {
3517 dr.setMessage(_("Please, preview the document first."));
3520 string outname = dviname.onlyFileName();
3521 string command = lyxrc.forward_search_dvi;
3522 if (!dviname.exists() ||
3523 pdfname.lastModified() > dviname.lastModified()) {
3524 outname = pdfname.onlyFileName();
3525 command = lyxrc.forward_search_pdf;
3528 int row = doc_buffer->texrow().getRowFromIdPos(bv->cursor().paragraph().id(), bv->cursor().pos());
3529 LYXERR(Debug::ACTION, "Forward search: row:" << row
3530 << " id:" << bv->cursor().paragraph().id());
3531 if (!row || command.empty()) {
3532 dr.setMessage(_("Couldn't proceed."));
3535 string texrow = convert<string>(row);
3537 command = subst(command, "$$n", texrow);
3538 command = subst(command, "$$t", texname);
3539 command = subst(command, "$$o", outname);
3541 PathChanger p(path);
3543 one.startscript(Systemcall::DontWait, command);
3547 // The LFUN must be for one of BufferView, Buffer or Cursor;
3549 dispatchToBufferView(cmd, dr);
3553 // Part of automatic menu appearance feature.
3554 if (isFullScreen()) {
3555 if (menuBar()->isVisible() && lyxrc.full_screen_menubar)
3557 if (statusBar()->isVisible())
3558 statusBar()->hide();
3563 bool GuiView::lfunUiToggle(string const & ui_component)
3565 if (ui_component == "scrollbar") {
3566 // hide() is of no help
3567 if (d.current_work_area_->verticalScrollBarPolicy() ==
3568 Qt::ScrollBarAlwaysOff)
3570 d.current_work_area_->setVerticalScrollBarPolicy(
3571 Qt::ScrollBarAsNeeded);
3573 d.current_work_area_->setVerticalScrollBarPolicy(
3574 Qt::ScrollBarAlwaysOff);
3575 } else if (ui_component == "statusbar") {
3576 statusBar()->setVisible(!statusBar()->isVisible());
3577 } else if (ui_component == "menubar") {
3578 menuBar()->setVisible(!menuBar()->isVisible());
3580 #if QT_VERSION >= 0x040300
3581 if (ui_component == "frame") {
3583 getContentsMargins(&l, &t, &r, &b);
3584 //are the frames in default state?
3585 d.current_work_area_->setFrameStyle(QFrame::NoFrame);
3587 setContentsMargins(-2, -2, -2, -2);
3589 setContentsMargins(0, 0, 0, 0);
3593 if (ui_component == "fullscreen") {
3601 void GuiView::toggleFullScreen()
3603 if (isFullScreen()) {
3604 for (int i = 0; i != d.splitter_->count(); ++i)
3605 d.tabWorkArea(i)->setFullScreen(false);
3606 #if QT_VERSION >= 0x040300
3607 setContentsMargins(0, 0, 0, 0);
3609 setWindowState(windowState() ^ Qt::WindowFullScreen);
3612 statusBar()->show();
3615 hideDialogs("prefs", 0);
3616 for (int i = 0; i != d.splitter_->count(); ++i)
3617 d.tabWorkArea(i)->setFullScreen(true);
3618 #if QT_VERSION >= 0x040300
3619 setContentsMargins(-2, -2, -2, -2);
3622 setWindowState(windowState() ^ Qt::WindowFullScreen);
3623 statusBar()->hide();
3624 if (lyxrc.full_screen_menubar)
3626 if (lyxrc.full_screen_toolbars) {
3627 ToolbarMap::iterator end = d.toolbars_.end();
3628 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
3633 // give dialogs like the TOC a chance to adapt
3638 Buffer const * GuiView::updateInset(Inset const * inset)
3643 Buffer const * inset_buffer = &(inset->buffer());
3645 for (int i = 0; i != d.splitter_->count(); ++i) {
3646 GuiWorkArea * wa = d.tabWorkArea(i)->currentWorkArea();
3649 Buffer const * buffer = &(wa->bufferView().buffer());
3650 if (inset_buffer == buffer)
3651 wa->scheduleRedraw();
3653 return inset_buffer;
3657 void GuiView::restartCursor()
3659 /* When we move around, or type, it's nice to be able to see
3660 * the cursor immediately after the keypress.
3662 if (d.current_work_area_)
3663 d.current_work_area_->startBlinkingCursor();
3665 // Take this occasion to update the other GUI elements.
3671 void GuiView::updateCompletion(Cursor & cur, bool start, bool keep)
3673 if (d.current_work_area_)
3674 d.current_work_area_->completer().updateVisibility(cur, start, keep);
3679 // This list should be kept in sync with the list of insets in
3680 // src/insets/Inset.cpp. I.e., if a dialog goes with an inset, the
3681 // dialog should have the same name as the inset.
3682 // Changes should be also recorded in LFUN_DIALOG_SHOW doxygen
3683 // docs in LyXAction.cpp.
3685 char const * const dialognames[] = {
3687 "aboutlyx", "bibitem", "bibtex", "box", "branch", "changes", "character",
3688 "citation", "compare", "comparehistory", "document", "errorlist", "ert",
3689 "external", "file", "findreplace", "findreplaceadv", "float", "graphics",
3690 "href", "include", "index", "index_print", "info", "listings", "label", "line",
3691 "log", "mathdelimiter", "mathmatrix", "mathspace", "nomenclature",
3692 "nomencl_print", "note", "paragraph", "phantom", "prefs", "print", "ref",
3693 "sendto", "space", "spellchecker", "symbols", "tabular", "tabularcreate",
3694 "thesaurus", "texinfo", "toc", "view-source", "vspace", "wrap", "progress"};
3696 char const * const * const end_dialognames =
3697 dialognames + (sizeof(dialognames) / sizeof(char *));
3701 cmpCStr(char const * name) : name_(name) {}
3702 bool operator()(char const * other) {
3703 return strcmp(other, name_) == 0;
3710 bool isValidName(string const & name)
3712 return find_if(dialognames, end_dialognames,
3713 cmpCStr(name.c_str())) != end_dialognames;
3719 void GuiView::resetDialogs()
3721 // Make sure that no LFUN uses any GuiView.
3722 guiApp->setCurrentView(0);
3726 constructToolbars();
3727 guiApp->menus().fillMenuBar(menuBar(), this, false);
3728 d.layout_->updateContents(true);
3729 // Now update controls with current buffer.
3730 guiApp->setCurrentView(this);
3736 Dialog * GuiView::findOrBuild(string const & name, bool hide_it)
3738 if (!isValidName(name))
3741 map<string, DialogPtr>::iterator it = d.dialogs_.find(name);
3743 if (it != d.dialogs_.end()) {
3745 it->second->hideView();
3746 return it->second.get();
3749 Dialog * dialog = build(name);
3750 d.dialogs_[name].reset(dialog);
3751 if (lyxrc.allow_geometry_session)
3752 dialog->restoreSession();
3759 void GuiView::showDialog(string const & name, string const & data,
3762 triggerShowDialog(toqstr(name), toqstr(data), inset);
3766 void GuiView::doShowDialog(QString const & qname, QString const & qdata,
3772 const string name = fromqstr(qname);
3773 const string data = fromqstr(qdata);
3777 Dialog * dialog = findOrBuild(name, false);
3779 bool const visible = dialog->isVisibleView();
3780 dialog->showData(data);
3781 if (inset && currentBufferView())
3782 currentBufferView()->editInset(name, inset);
3783 // We only set the focus to the new dialog if it was not yet
3784 // visible in order not to change the existing previous behaviour
3786 // activateWindow is needed for floating dockviews
3787 dialog->asQWidget()->raise();
3788 dialog->asQWidget()->activateWindow();
3789 dialog->asQWidget()->setFocus();
3793 catch (ExceptionMessage const & ex) {
3801 bool GuiView::isDialogVisible(string const & name) const
3803 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3804 if (it == d.dialogs_.end())
3806 return it->second.get()->isVisibleView() && !it->second.get()->isClosing();
3810 void GuiView::hideDialog(string const & name, Inset * inset)
3812 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3813 if (it == d.dialogs_.end())
3817 if (!currentBufferView())
3819 if (inset != currentBufferView()->editedInset(name))
3823 Dialog * const dialog = it->second.get();
3824 if (dialog->isVisibleView())
3826 if (currentBufferView())
3827 currentBufferView()->editInset(name, 0);
3831 void GuiView::disconnectDialog(string const & name)
3833 if (!isValidName(name))
3835 if (currentBufferView())
3836 currentBufferView()->editInset(name, 0);
3840 void GuiView::hideAll() const
3842 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
3843 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3845 for(; it != end; ++it)
3846 it->second->hideView();
3850 void GuiView::updateDialogs()
3852 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
3853 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3855 for(; it != end; ++it) {
3856 Dialog * dialog = it->second.get();
3858 if (dialog->needBufferOpen() && !documentBufferView())
3859 hideDialog(fromqstr(dialog->name()), 0);
3860 else if (dialog->isVisibleView())
3861 dialog->checkStatus();
3868 Dialog * createDialog(GuiView & lv, string const & name);
3870 // will be replaced by a proper factory...
3871 Dialog * createGuiAbout(GuiView & lv);
3872 Dialog * createGuiBibtex(GuiView & lv);
3873 Dialog * createGuiChanges(GuiView & lv);
3874 Dialog * createGuiCharacter(GuiView & lv);
3875 Dialog * createGuiCitation(GuiView & lv);
3876 Dialog * createGuiCompare(GuiView & lv);
3877 Dialog * createGuiCompareHistory(GuiView & lv);
3878 Dialog * createGuiDelimiter(GuiView & lv);
3879 Dialog * createGuiDocument(GuiView & lv);
3880 Dialog * createGuiErrorList(GuiView & lv);
3881 Dialog * createGuiExternal(GuiView & lv);
3882 Dialog * createGuiGraphics(GuiView & lv);
3883 Dialog * createGuiInclude(GuiView & lv);
3884 Dialog * createGuiIndex(GuiView & lv);
3885 Dialog * createGuiListings(GuiView & lv);
3886 Dialog * createGuiLog(GuiView & lv);
3887 Dialog * createGuiMathMatrix(GuiView & lv);
3888 Dialog * createGuiNote(GuiView & lv);
3889 Dialog * createGuiParagraph(GuiView & lv);
3890 Dialog * createGuiPhantom(GuiView & lv);
3891 Dialog * createGuiPreferences(GuiView & lv);
3892 Dialog * createGuiPrint(GuiView & lv);
3893 Dialog * createGuiPrintindex(GuiView & lv);
3894 Dialog * createGuiRef(GuiView & lv);
3895 Dialog * createGuiSearch(GuiView & lv);
3896 Dialog * createGuiSearchAdv(GuiView & lv);
3897 Dialog * createGuiSendTo(GuiView & lv);
3898 Dialog * createGuiShowFile(GuiView & lv);
3899 Dialog * createGuiSpellchecker(GuiView & lv);
3900 Dialog * createGuiSymbols(GuiView & lv);
3901 Dialog * createGuiTabularCreate(GuiView & lv);
3902 Dialog * createGuiTexInfo(GuiView & lv);
3903 Dialog * createGuiToc(GuiView & lv);
3904 Dialog * createGuiThesaurus(GuiView & lv);
3905 Dialog * createGuiViewSource(GuiView & lv);
3906 Dialog * createGuiWrap(GuiView & lv);
3907 Dialog * createGuiProgressView(GuiView & lv);
3911 Dialog * GuiView::build(string const & name)
3913 LASSERT(isValidName(name), return 0);
3915 Dialog * dialog = createDialog(*this, name);
3919 if (name == "aboutlyx")
3920 return createGuiAbout(*this);
3921 if (name == "bibtex")
3922 return createGuiBibtex(*this);
3923 if (name == "changes")
3924 return createGuiChanges(*this);
3925 if (name == "character")
3926 return createGuiCharacter(*this);
3927 if (name == "citation")
3928 return createGuiCitation(*this);
3929 if (name == "compare")
3930 return createGuiCompare(*this);
3931 if (name == "comparehistory")
3932 return createGuiCompareHistory(*this);
3933 if (name == "document")
3934 return createGuiDocument(*this);
3935 if (name == "errorlist")
3936 return createGuiErrorList(*this);
3937 if (name == "external")
3938 return createGuiExternal(*this);
3940 return createGuiShowFile(*this);
3941 if (name == "findreplace")
3942 return createGuiSearch(*this);
3943 if (name == "findreplaceadv")
3944 return createGuiSearchAdv(*this);
3945 if (name == "graphics")
3946 return createGuiGraphics(*this);
3947 if (name == "include")
3948 return createGuiInclude(*this);
3949 if (name == "index")
3950 return createGuiIndex(*this);
3951 if (name == "index_print")
3952 return createGuiPrintindex(*this);
3953 if (name == "listings")
3954 return createGuiListings(*this);
3956 return createGuiLog(*this);
3957 if (name == "mathdelimiter")
3958 return createGuiDelimiter(*this);
3959 if (name == "mathmatrix")
3960 return createGuiMathMatrix(*this);
3962 return createGuiNote(*this);
3963 if (name == "paragraph")
3964 return createGuiParagraph(*this);
3965 if (name == "phantom")
3966 return createGuiPhantom(*this);
3967 if (name == "prefs")
3968 return createGuiPreferences(*this);
3969 if (name == "print")
3970 return createGuiPrint(*this);
3972 return createGuiRef(*this);
3973 if (name == "sendto")
3974 return createGuiSendTo(*this);
3975 if (name == "spellchecker")
3976 return createGuiSpellchecker(*this);
3977 if (name == "symbols")
3978 return createGuiSymbols(*this);
3979 if (name == "tabularcreate")
3980 return createGuiTabularCreate(*this);
3981 if (name == "texinfo")
3982 return createGuiTexInfo(*this);
3983 if (name == "thesaurus")
3984 return createGuiThesaurus(*this);
3986 return createGuiToc(*this);
3987 if (name == "view-source")
3988 return createGuiViewSource(*this);
3990 return createGuiWrap(*this);
3991 if (name == "progress")
3992 return createGuiProgressView(*this);
3998 } // namespace frontend
4001 #include "moc_GuiView.cpp"