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
216 bigIconSize = 26; // better for some math icons
218 splitter_ = new QSplitter;
219 bg_widget_ = new BackgroundWidget;
220 stack_widget_ = new QStackedWidget;
221 stack_widget_->addWidget(bg_widget_);
222 stack_widget_->addWidget(splitter_);
225 // TODO cleanup, remove the singleton, handle multiple Windows?
226 progress_ = ProgressInterface::instance();
227 if (!dynamic_cast<GuiProgress*>(progress_)) {
228 progress_ = new GuiProgress(); // TODO who deletes it
229 ProgressInterface::setInstance(progress_);
232 dynamic_cast<GuiProgress*>(progress_),
233 SIGNAL(updateStatusBarMessage(QString const&)),
234 gv, SLOT(updateStatusBarMessage(QString const&)));
236 dynamic_cast<GuiProgress*>(progress_),
237 SIGNAL(clearMessageText()),
238 gv, SLOT(clearMessageText()));
245 delete stack_widget_;
248 QMenu * toolBarPopup(GuiView * parent)
250 // FIXME: translation
251 QMenu * menu = new QMenu(parent);
252 QActionGroup * iconSizeGroup = new QActionGroup(parent);
254 QAction * smallIcons = new QAction(iconSizeGroup);
255 smallIcons->setText(qt_("Small-sized icons"));
256 smallIcons->setCheckable(true);
257 QObject::connect(smallIcons, SIGNAL(triggered()),
258 parent, SLOT(smallSizedIcons()));
259 menu->addAction(smallIcons);
261 QAction * normalIcons = new QAction(iconSizeGroup);
262 normalIcons->setText(qt_("Normal-sized icons"));
263 normalIcons->setCheckable(true);
264 QObject::connect(normalIcons, SIGNAL(triggered()),
265 parent, SLOT(normalSizedIcons()));
266 menu->addAction(normalIcons);
268 QAction * bigIcons = new QAction(iconSizeGroup);
269 bigIcons->setText(qt_("Big-sized icons"));
270 bigIcons->setCheckable(true);
271 QObject::connect(bigIcons, SIGNAL(triggered()),
272 parent, SLOT(bigSizedIcons()));
273 menu->addAction(bigIcons);
275 unsigned int cur = parent->iconSize().width();
276 if ( cur == parent->d.smallIconSize)
277 smallIcons->setChecked(true);
278 else if (cur == parent->d.normalIconSize)
279 normalIcons->setChecked(true);
280 else if (cur == parent->d.bigIconSize)
281 bigIcons->setChecked(true);
288 stack_widget_->setCurrentWidget(bg_widget_);
289 bg_widget_->setUpdatesEnabled(true);
290 bg_widget_->setFocus();
293 int tabWorkAreaCount()
295 return splitter_->count();
298 TabWorkArea * tabWorkArea(int i)
300 return dynamic_cast<TabWorkArea *>(splitter_->widget(i));
303 TabWorkArea * currentTabWorkArea()
305 int areas = tabWorkAreaCount();
307 // The first TabWorkArea is always the first one, if any.
308 return tabWorkArea(0);
310 for (int i = 0; i != areas; ++i) {
311 TabWorkArea * twa = tabWorkArea(i);
312 if (current_main_work_area_ == twa->currentWorkArea())
316 // None has the focus so we just take the first one.
317 return tabWorkArea(0);
320 #if (QT_VERSION >= 0x040400)
321 void setPreviewFuture(QFuture<docstring> const & f)
323 if (processing_thread_watcher_.isRunning()) {
324 // we prefer to cancel this preview in order to keep a snappy
328 processing_thread_watcher_.setFuture(f);
334 GuiWorkArea * current_work_area_;
335 GuiWorkArea * current_main_work_area_;
336 QSplitter * splitter_;
337 QStackedWidget * stack_widget_;
338 BackgroundWidget * bg_widget_;
340 ToolbarMap toolbars_;
341 ProgressInterface* progress_;
342 /// The main layout box.
344 * \warning Don't Delete! The layout box is actually owned by
345 * whichever toolbar contains it. All the GuiView class needs is a
346 * means of accessing it.
348 * FIXME: replace that with a proper model so that we are not limited
349 * to only one dialog.
354 map<string, DialogPtr> dialogs_;
356 unsigned int smallIconSize;
357 unsigned int normalIconSize;
358 unsigned int bigIconSize;
360 QTimer statusbar_timer_;
361 /// auto-saving of buffers
362 Timeout autosave_timeout_;
363 /// flag against a race condition due to multiclicks, see bug #1119
367 TocModels toc_models_;
369 #if (QT_VERSION >= 0x040400)
371 QFutureWatcher<docstring> autosave_watcher_;
372 QFutureWatcher<docstring> processing_thread_watcher_;
374 string last_export_format;
376 struct DummyWatcher { bool isRunning(){return false;} };
377 DummyWatcher processing_thread_watcher_;
380 static QSet<Buffer const *> busyBuffers;
381 static docstring previewAndDestroy(Buffer const * orig, Buffer * buffer, string const & format);
382 static docstring exportAndDestroy(Buffer const * orig, Buffer * buffer, string const & format);
383 static docstring compileAndDestroy(Buffer const * orig, Buffer * buffer, string const & format);
384 static docstring autosaveAndDestroy(Buffer const * orig, Buffer * buffer);
387 static docstring runAndDestroy(const T& func, Buffer const * orig, Buffer * buffer, string const & format, string const & msg);
389 // TODO syncFunc/previewFunc: use bind
390 bool asyncBufferProcessing(string const & argument,
391 Buffer const * used_buffer,
392 docstring const & msg,
393 docstring (*asyncFunc)(Buffer const *, Buffer *, string const &),
394 bool (Buffer::*syncFunc)(string const &, bool, bool) const,
395 bool (Buffer::*previewFunc)(string const &, bool) const);
397 QVector<GuiWorkArea*> guiWorkAreas();
400 QSet<Buffer const *> GuiView::GuiViewPrivate::busyBuffers;
403 GuiView::GuiView(int id)
404 : d(*new GuiViewPrivate(this)), id_(id), closing_(false), busy_(0)
406 // GuiToolbars *must* be initialised before the menu bar.
407 normalSizedIcons(); // at least on Mac the default is 32 otherwise, which is huge
410 // set ourself as the current view. This is needed for the menu bar
411 // filling, at least for the static special menu item on Mac. Otherwise
412 // they are greyed out.
413 guiApp->setCurrentView(this);
415 // Fill up the menu bar.
416 guiApp->menus().fillMenuBar(menuBar(), this, true);
418 setCentralWidget(d.stack_widget_);
420 // Start autosave timer
421 if (lyxrc.autosave) {
422 d.autosave_timeout_.timeout.connect(bind(&GuiView::autoSave, this));
423 d.autosave_timeout_.setTimeout(lyxrc.autosave * 1000);
424 d.autosave_timeout_.start();
426 connect(&d.statusbar_timer_, SIGNAL(timeout()),
427 this, SLOT(clearMessage()));
429 // We don't want to keep the window in memory if it is closed.
430 setAttribute(Qt::WA_DeleteOnClose, true);
432 #if (!defined(Q_WS_WIN) && !defined(Q_WS_MACX))
433 // assign an icon to main form. We do not do it under Qt/Win or Qt/Mac,
434 // since the icon is provided in the application bundle.
435 setWindowIcon(getPixmap("images/", "lyx", "png"));
438 #if (QT_VERSION >= 0x040300)
439 // use tabbed dock area for multiple docks
440 // (such as "source" and "messages")
441 setDockOptions(QMainWindow::ForceTabbedDocks);
445 setAcceptDrops(true);
447 #if (QT_VERSION >= 0x040400)
449 // add busy indicator to statusbar
450 QLabel * busylabel = new QLabel(statusBar());
451 statusBar()->addPermanentWidget(busylabel);
452 QString fn = toqstr(lyx::libFileSearch("images", "busy.gif").absFileName());
453 QMovie * busyanim = new QMovie(fn, QByteArray(), busylabel);
454 busylabel->setMovie(busyanim);
458 connect(&d.processing_thread_watcher_, SIGNAL(started()),
459 busylabel, SLOT(show()));
460 connect(&d.processing_thread_watcher_, SIGNAL(finished()),
461 busylabel, SLOT(hide()));
463 statusBar()->setSizeGripEnabled(true);
466 connect(&d.autosave_watcher_, SIGNAL(finished()), this,
467 SLOT(autoSaveThreadFinished()));
469 connect(&d.processing_thread_watcher_, SIGNAL(started()), this,
470 SLOT(processingThreadStarted()));
471 connect(&d.processing_thread_watcher_, SIGNAL(finished()), this,
472 SLOT(processingThreadFinished()));
476 connect(this, SIGNAL(triggerShowDialog(QString const &, QString const &, Inset *)),
477 SLOT(doShowDialog(QString const &, QString const &, Inset *)));
479 // Forbid too small unresizable window because it can happen
480 // with some window manager under X11.
481 setMinimumSize(300, 200);
483 if (lyxrc.allow_geometry_session) {
484 // Now take care of session management.
489 // no session handling, default to a sane size.
490 setGeometry(50, 50, 690, 510);
493 // clear session data if any.
495 settings.remove("views");
505 QVector<GuiWorkArea*> GuiView::GuiViewPrivate::guiWorkAreas()
507 QVector<GuiWorkArea*> areas;
508 for (int i = 0; i < tabWorkAreaCount(); i++) {
509 TabWorkArea* ta = tabWorkArea(i);
510 for (int u = 0; u < ta->count(); u++) {
511 areas << ta->workArea(u);
518 #if QT_VERSION >= 0x040400
520 void GuiView::processingThreadStarted()
525 void GuiView::processingThreadFinished(bool show_errors)
527 QFutureWatcher<docstring> const * watcher =
528 static_cast<QFutureWatcher<docstring> const *>(sender());
529 message(watcher->result());
532 BufferView const * const bv = currentBufferView();
533 if (bv && !bv->buffer().errorList("Export").empty()) {
537 errors(d.last_export_format);
542 void GuiView::processingThreadFinished()
544 processingThreadFinished(true);
548 void GuiView::autoSaveThreadFinished()
550 processingThreadFinished(false);
556 void GuiView::processingThreadStarted()
561 void GuiView::processingThreadFinished(bool)
566 void GuiView::processingThreadFinished()
571 void GuiView::autoSaveThreadFinished()
577 void GuiView::saveLayout() const
580 settings.beginGroup("views");
581 settings.beginGroup(QString::number(id_));
583 settings.setValue("pos", pos());
584 settings.setValue("size", size());
586 settings.setValue("geometry", saveGeometry());
588 settings.setValue("layout", saveState(0));
589 settings.setValue("icon_size", iconSize());
593 void GuiView::saveUISettings() const
595 // Save the toolbar private states
596 ToolbarMap::iterator end = d.toolbars_.end();
597 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
598 it->second->saveSession();
599 // Now take care of all other dialogs
600 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
601 for (; it!= d.dialogs_.end(); ++it)
602 it->second->saveSession();
606 bool GuiView::restoreLayout()
609 settings.beginGroup("views");
610 settings.beginGroup(QString::number(id_));
611 QString const icon_key = "icon_size";
612 if (!settings.contains(icon_key))
615 //code below is skipped when when ~/.config/LyX is (re)created
616 setIconSize(settings.value(icon_key).toSize());
618 QPoint pos = settings.value("pos", QPoint(50, 50)).toPoint();
619 QSize size = settings.value("size", QSize(690, 510)).toSize();
623 // Work-around for bug #6034: the window ends up in an undetermined
624 // state when trying to restore a maximized window when it is
625 // already maximized.
626 if (!(windowState() & Qt::WindowMaximized))
627 if (!restoreGeometry(settings.value("geometry").toByteArray()))
628 setGeometry(50, 50, 690, 510);
630 // Make sure layout is correctly oriented.
631 setLayoutDirection(qApp->layoutDirection());
633 // Allow the toc and view-source dock widget to be restored if needed.
635 if ((dialog = findOrBuild("toc", true)))
636 // see bug 5082. At least setup title and enabled state.
637 // Visibility will be adjusted by restoreState below.
638 dialog->prepareView();
639 if ((dialog = findOrBuild("view-source", true)))
640 dialog->prepareView();
641 if ((dialog = findOrBuild("progress", true)))
642 dialog->prepareView();
643 if ((dialog = findOrBuild("findreplaceadv", true)))
644 dialog->prepareView();
646 if (!restoreState(settings.value("layout").toByteArray(), 0))
653 GuiToolbar * GuiView::toolbar(string const & name)
655 ToolbarMap::iterator it = d.toolbars_.find(name);
656 if (it != d.toolbars_.end())
659 LYXERR(Debug::GUI, "Toolbar::display: no toolbar named " << name);
664 void GuiView::constructToolbars()
666 ToolbarMap::iterator it = d.toolbars_.begin();
667 for (; it != d.toolbars_.end(); ++it)
671 // I don't like doing this here, but the standard toolbar
672 // destroys this object when it's destroyed itself (vfr)
673 d.layout_ = new LayoutBox(*this);
674 d.stack_widget_->addWidget(d.layout_);
675 d.layout_->move(0,0);
677 // extracts the toolbars from the backend
678 Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
679 Toolbars::Infos::iterator end = guiApp->toolbars().end();
680 for (; cit != end; ++cit)
681 d.toolbars_[cit->name] = new GuiToolbar(*cit, *this);
685 void GuiView::initToolbars()
687 // extracts the toolbars from the backend
688 Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
689 Toolbars::Infos::iterator end = guiApp->toolbars().end();
690 for (; cit != end; ++cit) {
691 GuiToolbar * tb = toolbar(cit->name);
694 int const visibility = guiApp->toolbars().defaultVisibility(cit->name);
695 bool newline = !(visibility & Toolbars::SAMEROW);
696 tb->setVisible(false);
697 tb->setVisibility(visibility);
699 if (visibility & Toolbars::TOP) {
701 addToolBarBreak(Qt::TopToolBarArea);
702 addToolBar(Qt::TopToolBarArea, tb);
705 if (visibility & Toolbars::BOTTOM) {
706 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
707 #if (QT_VERSION >= 0x040202)
709 addToolBarBreak(Qt::BottomToolBarArea);
711 addToolBar(Qt::BottomToolBarArea, tb);
714 if (visibility & Toolbars::LEFT) {
715 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
716 #if (QT_VERSION >= 0x040202)
718 addToolBarBreak(Qt::LeftToolBarArea);
720 addToolBar(Qt::LeftToolBarArea, tb);
723 if (visibility & Toolbars::RIGHT) {
724 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
725 #if (QT_VERSION >= 0x040202)
727 addToolBarBreak(Qt::RightToolBarArea);
729 addToolBar(Qt::RightToolBarArea, tb);
732 if (visibility & Toolbars::ON)
733 tb->setVisible(true);
738 TocModels & GuiView::tocModels()
740 return d.toc_models_;
744 void GuiView::setFocus()
746 LYXERR(Debug::DEBUG, "GuiView::setFocus()" << this);
747 QMainWindow::setFocus();
751 void GuiView::focusInEvent(QFocusEvent * e)
753 LYXERR(Debug::DEBUG, "GuiView::focusInEvent()" << this);
754 QMainWindow::focusInEvent(e);
755 // Make sure guiApp points to the correct view.
756 guiApp->setCurrentView(this);
757 if (currentWorkArea())
758 currentWorkArea()->setFocus();
759 else if (currentMainWorkArea())
760 currentMainWorkArea()->setFocus();
762 d.bg_widget_->setFocus();
766 QMenu * GuiView::createPopupMenu()
768 return d.toolBarPopup(this);
772 void GuiView::showEvent(QShowEvent * e)
774 LYXERR(Debug::GUI, "Passed Geometry "
775 << size().height() << "x" << size().width()
776 << "+" << pos().x() << "+" << pos().y());
778 if (d.splitter_->count() == 0)
779 // No work area, switch to the background widget.
782 QMainWindow::showEvent(e);
786 bool GuiView::closeScheduled()
793 /** Destroy only all tabbed WorkAreas. Destruction of other WorkAreas
794 ** is responsibility of the container (e.g., dialog)
796 void GuiView::closeEvent(QCloseEvent * close_event)
798 LYXERR(Debug::DEBUG, "GuiView::closeEvent()");
800 if (!GuiViewPrivate::busyBuffers.isEmpty()) {
801 Alert::warning(_("Exit LyX"),
802 _("LyX could not be closed because documents are being processed by LyX."));
803 close_event->setAccepted(false);
807 // If the user pressed the x (so we didn't call closeView
808 // programmatically), we want to clear all existing entries.
810 theSession().lastOpened().clear();
815 // it can happen that this event arrives without selecting the view,
816 // e.g. when clicking the close button on a background window.
818 if (!closeWorkAreaAll()) {
820 close_event->ignore();
824 // Make sure that nothing will use this to be closed View.
825 guiApp->unregisterView(this);
827 if (isFullScreen()) {
828 // Switch off fullscreen before closing.
833 // Make sure the timer time out will not trigger a statusbar update.
834 d.statusbar_timer_.stop();
836 // Saving fullscreen requires additional tweaks in the toolbar code.
837 // It wouldn't also work under linux natively.
838 if (lyxrc.allow_geometry_session) {
843 close_event->accept();
847 void GuiView::dragEnterEvent(QDragEnterEvent * event)
849 if (event->mimeData()->hasUrls())
851 /// \todo Ask lyx-devel is this is enough:
852 /// if (event->mimeData()->hasFormat("text/plain"))
853 /// event->acceptProposedAction();
857 void GuiView::dropEvent(QDropEvent * event)
859 QList<QUrl> files = event->mimeData()->urls();
863 LYXERR(Debug::GUI, "GuiView::dropEvent: got URLs!");
864 for (int i = 0; i != files.size(); ++i) {
865 string const file = os::internal_path(fromqstr(
866 files.at(i).toLocalFile()));
870 string const ext = support::getExtension(file);
871 vector<const Format *> found_formats;
873 // Find all formats that have the correct extension.
874 vector<const Format *> const & import_formats
875 = theConverters().importableFormats();
876 vector<const Format *>::const_iterator it = import_formats.begin();
877 for (; it != import_formats.end(); ++it)
878 if ((*it)->extension() == ext)
879 found_formats.push_back(*it);
882 if (found_formats.size() >= 1) {
883 if (found_formats.size() > 1) {
884 //FIXME: show a dialog to choose the correct importable format
886 "Multiple importable formats found, selecting first");
888 string const arg = found_formats[0]->name() + " " + file;
889 cmd = FuncRequest(LFUN_BUFFER_IMPORT, arg);
892 //FIXME: do we have to explicitly check whether it's a lyx file?
894 "No formats found, trying to open it as a lyx file");
895 cmd = FuncRequest(LFUN_FILE_OPEN, file);
897 // add the functions to the queue
898 guiApp->addToFuncRequestQueue(cmd);
901 // now process the collected functions. We perform the events
902 // asynchronously. This prevents potential problems in case the
903 // BufferView is closed within an event.
904 guiApp->processFuncRequestQueueAsync();
908 void GuiView::message(docstring const & str)
910 if (ForkedProcess::iAmAChild())
913 // call is moved to GUI-thread by GuiProgress
914 d.progress_->appendMessage(toqstr(str));
918 void GuiView::clearMessageText()
920 message(docstring());
924 void GuiView::updateStatusBarMessage(QString const & str)
926 statusBar()->showMessage(str);
927 d.statusbar_timer_.stop();
928 d.statusbar_timer_.start(3000);
932 void GuiView::smallSizedIcons()
934 setIconSize(QSize(d.smallIconSize, d.smallIconSize));
938 void GuiView::normalSizedIcons()
940 setIconSize(QSize(d.normalIconSize, d.normalIconSize));
944 void GuiView::bigSizedIcons()
946 setIconSize(QSize(d.bigIconSize, d.bigIconSize));
950 void GuiView::clearMessage()
952 // FIXME: This code was introduced in r19643 to fix bug #4123. However,
953 // the hasFocus function mostly returns false, even if the focus is on
954 // a workarea in this view.
958 d.statusbar_timer_.stop();
962 void GuiView::updateWindowTitle(GuiWorkArea * wa)
964 if (wa != d.current_work_area_
965 || wa->bufferView().buffer().isInternal())
967 setWindowTitle(qt_("LyX: ") + wa->windowTitle());
968 setWindowIconText(wa->windowIconText());
972 void GuiView::on_currentWorkAreaChanged(GuiWorkArea * wa)
975 disconnectBufferView();
976 connectBufferView(wa->bufferView());
977 connectBuffer(wa->bufferView().buffer());
978 d.current_work_area_ = wa;
979 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
980 this, SLOT(updateWindowTitle(GuiWorkArea *)));
981 updateWindowTitle(wa);
985 // The document settings needs to be reinitialised.
986 updateDialog("document", "");
988 // Buffer-dependent dialogs must be updated. This is done here because
989 // some dialogs require buffer()->text.
994 void GuiView::on_lastWorkAreaRemoved()
997 // We already are in a close event. Nothing more to do.
1000 if (d.splitter_->count() > 1)
1001 // We have a splitter so don't close anything.
1004 // Reset and updates the dialogs.
1005 d.toc_models_.reset(0);
1006 updateDialog("document", "");
1009 resetWindowTitleAndIconText();
1012 if (lyxrc.open_buffers_in_tabs)
1013 // Nothing more to do, the window should stay open.
1016 if (guiApp->viewIds().size() > 1) {
1022 // On Mac we also close the last window because the application stay
1023 // resident in memory. On other platforms we don't close the last
1024 // window because this would quit the application.
1030 void GuiView::updateStatusBar()
1032 // let the user see the explicit message
1033 if (d.statusbar_timer_.isActive())
1040 void GuiView::showMessage()
1042 QString msg = toqstr(theGuiApp()->viewStatusMessage());
1043 if (msg.isEmpty()) {
1044 BufferView const * bv = currentBufferView();
1046 msg = toqstr(bv->cursor().currentState());
1048 msg = qt_("Welcome to LyX!");
1050 statusBar()->showMessage(msg);
1054 bool GuiView::event(QEvent * e)
1058 // Useful debug code:
1059 //case QEvent::ActivationChange:
1060 //case QEvent::WindowDeactivate:
1061 //case QEvent::Paint:
1062 //case QEvent::Enter:
1063 //case QEvent::Leave:
1064 //case QEvent::HoverEnter:
1065 //case QEvent::HoverLeave:
1066 //case QEvent::HoverMove:
1067 //case QEvent::StatusTip:
1068 //case QEvent::DragEnter:
1069 //case QEvent::DragLeave:
1070 //case QEvent::Drop:
1073 case QEvent::WindowActivate: {
1074 GuiView * old_view = guiApp->currentView();
1075 if (this == old_view) {
1077 return QMainWindow::event(e);
1079 if (old_view && old_view->currentBufferView()) {
1080 // save current selection to the selection buffer to allow
1081 // middle-button paste in this window.
1082 cap::saveSelection(old_view->currentBufferView()->cursor());
1084 guiApp->setCurrentView(this);
1085 if (d.current_work_area_) {
1086 BufferView & bv = d.current_work_area_->bufferView();
1087 connectBufferView(bv);
1088 connectBuffer(bv.buffer());
1089 // The document structure, name and dialogs might have
1090 // changed in another view.
1092 // The document settings needs to be reinitialised.
1093 updateDialog("document", "");
1096 resetWindowTitleAndIconText();
1099 return QMainWindow::event(e);
1102 case QEvent::ShortcutOverride: {
1105 #if (!defined Q_WS_X11) || (QT_VERSION >= 0x040500)
1106 if (isFullScreen() && menuBar()->isHidden()) {
1107 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
1108 // FIXME: we should also try to detect special LyX shortcut such as
1109 // Alt-P and Alt-M. Right now there is a hack in
1110 // GuiWorkArea::processKeySym() that hides again the menubar for
1112 if (ke->modifiers() & Qt::AltModifier && ke->key() != Qt::Key_Alt) {
1114 return QMainWindow::event(e);
1118 return QMainWindow::event(e);
1122 return QMainWindow::event(e);
1126 void GuiView::resetWindowTitleAndIconText()
1128 setWindowTitle(qt_("LyX"));
1129 setWindowIconText(qt_("LyX"));
1132 bool GuiView::focusNextPrevChild(bool /*next*/)
1139 bool GuiView::busy() const
1145 void GuiView::setBusy(bool busy)
1147 bool const busy_before = busy_ > 0;
1148 busy ? ++busy_ : --busy_;
1149 if ((busy_ > 0) == busy_before)
1150 // busy state didn't change
1153 if (d.current_work_area_) {
1154 d.current_work_area_->setUpdatesEnabled(!busy);
1156 d.current_work_area_->stopBlinkingCursor();
1158 d.current_work_area_->startBlinkingCursor();
1162 QApplication::setOverrideCursor(Qt::WaitCursor);
1164 QApplication::restoreOverrideCursor();
1168 GuiWorkArea * GuiView::workArea(int index)
1170 if (TabWorkArea * twa = d.currentTabWorkArea())
1171 if (index < twa->count())
1172 return dynamic_cast<GuiWorkArea *>(twa->widget(index));
1177 GuiWorkArea * GuiView::workArea(Buffer & buffer)
1179 if (currentWorkArea()
1180 && ¤tWorkArea()->bufferView().buffer() == &buffer)
1181 return (GuiWorkArea *) currentWorkArea();
1182 if (TabWorkArea * twa = d.currentTabWorkArea())
1183 return twa->workArea(buffer);
1188 GuiWorkArea * GuiView::addWorkArea(Buffer & buffer)
1190 // Automatically create a TabWorkArea if there are none yet.
1191 TabWorkArea * tab_widget = d.splitter_->count()
1192 ? d.currentTabWorkArea() : addTabWorkArea();
1193 return tab_widget->addWorkArea(buffer, *this);
1197 TabWorkArea * GuiView::addTabWorkArea()
1199 TabWorkArea * twa = new TabWorkArea;
1200 QObject::connect(twa, SIGNAL(currentWorkAreaChanged(GuiWorkArea *)),
1201 this, SLOT(on_currentWorkAreaChanged(GuiWorkArea *)));
1202 QObject::connect(twa, SIGNAL(lastWorkAreaRemoved()),
1203 this, SLOT(on_lastWorkAreaRemoved()));
1205 d.splitter_->addWidget(twa);
1206 d.stack_widget_->setCurrentWidget(d.splitter_);
1211 GuiWorkArea const * GuiView::currentWorkArea() const
1213 return d.current_work_area_;
1217 GuiWorkArea * GuiView::currentWorkArea()
1219 return d.current_work_area_;
1223 GuiWorkArea const * GuiView::currentMainWorkArea() const
1225 if (!d.currentTabWorkArea())
1227 return d.currentTabWorkArea()->currentWorkArea();
1231 GuiWorkArea * GuiView::currentMainWorkArea()
1233 if (!d.currentTabWorkArea())
1235 return d.currentTabWorkArea()->currentWorkArea();
1239 void GuiView::setCurrentWorkArea(GuiWorkArea * wa)
1241 LYXERR(Debug::DEBUG, "Setting current wa: " << wa << endl);
1243 d.current_work_area_ = 0;
1248 // FIXME: I've no clue why this is here and why it accesses
1249 // theGuiApp()->currentView, which might be 0 (bug 6464).
1250 // See also 27525 (vfr).
1251 if (theGuiApp()->currentView() == this
1252 && theGuiApp()->currentView()->currentWorkArea() == wa)
1255 if (currentBufferView())
1256 cap::saveSelection(currentBufferView()->cursor());
1258 theGuiApp()->setCurrentView(this);
1259 d.current_work_area_ = wa;
1261 // We need to reset this now, because it will need to be
1262 // right if the tabWorkArea gets reset in the for loop. We
1263 // will change it back if we aren't in that case.
1264 GuiWorkArea * const old_cmwa = d.current_main_work_area_;
1265 d.current_main_work_area_ = wa;
1267 for (int i = 0; i != d.splitter_->count(); ++i) {
1268 if (d.tabWorkArea(i)->setCurrentWorkArea(wa)) {
1269 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea()
1270 << ", Current main wa: " << currentMainWorkArea());
1275 d.current_main_work_area_ = old_cmwa;
1277 LYXERR(Debug::DEBUG, "This is not a tabbed wa");
1278 on_currentWorkAreaChanged(wa);
1279 BufferView & bv = wa->bufferView();
1280 bv.cursor().fixIfBroken();
1282 wa->setUpdatesEnabled(true);
1283 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() << ", Current main wa: " << currentMainWorkArea());
1287 void GuiView::removeWorkArea(GuiWorkArea * wa)
1289 LASSERT(wa, return);
1290 if (wa == d.current_work_area_) {
1292 disconnectBufferView();
1293 d.current_work_area_ = 0;
1294 d.current_main_work_area_ = 0;
1297 bool found_twa = false;
1298 for (int i = 0; i != d.splitter_->count(); ++i) {
1299 TabWorkArea * twa = d.tabWorkArea(i);
1300 if (twa->removeWorkArea(wa)) {
1301 // Found in this tab group, and deleted the GuiWorkArea.
1303 if (twa->count() != 0) {
1304 if (d.current_work_area_ == 0)
1305 // This means that we are closing the current GuiWorkArea, so
1306 // switch to the next GuiWorkArea in the found TabWorkArea.
1307 setCurrentWorkArea(twa->currentWorkArea());
1309 // No more WorkAreas in this tab group, so delete it.
1316 // It is not a tabbed work area (i.e., the search work area), so it
1317 // should be deleted by other means.
1318 LASSERT(found_twa, /* */);
1320 if (d.current_work_area_ == 0) {
1321 if (d.splitter_->count() != 0) {
1322 TabWorkArea * twa = d.currentTabWorkArea();
1323 setCurrentWorkArea(twa->currentWorkArea());
1325 // No more work areas, switch to the background widget.
1326 setCurrentWorkArea(0);
1332 LayoutBox * GuiView::getLayoutDialog() const
1338 void GuiView::updateLayoutList()
1341 d.layout_->updateContents(false);
1345 void GuiView::updateToolbars()
1347 ToolbarMap::iterator end = d.toolbars_.end();
1348 if (d.current_work_area_) {
1350 d.current_work_area_->bufferView().cursor().inMathed()
1351 && !d.current_work_area_->bufferView().cursor().inRegexped();
1353 lyx::getStatus(FuncRequest(LFUN_LAYOUT_TABULAR)).enabled();
1355 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).enabled() &&
1356 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).onOff(true);
1357 bool const mathmacrotemplate =
1358 lyx::getStatus(FuncRequest(LFUN_IN_MATHMACROTEMPLATE)).enabled();
1360 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1361 it->second->update(math, table, review, mathmacrotemplate);
1363 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1364 it->second->update(false, false, false, false);
1368 void GuiView::setBuffer(Buffer * newBuffer)
1370 LYXERR(Debug::DEBUG, "Setting buffer: " << newBuffer << endl);
1371 LASSERT(newBuffer, return);
1374 GuiWorkArea * wa = workArea(*newBuffer);
1376 newBuffer->masterBuffer()->updateBuffer();
1377 wa = addWorkArea(*newBuffer);
1378 // scroll to the position when the BufferView was last closed
1379 if (lyxrc.use_lastfilepos) {
1380 LastFilePosSection::FilePos filepos =
1381 theSession().lastFilePos().load(newBuffer->fileName());
1382 wa->bufferView().moveToPosition(filepos.pit, filepos.pos, 0, 0);
1385 //Disconnect the old buffer...there's no new one.
1388 connectBuffer(*newBuffer);
1389 connectBufferView(wa->bufferView());
1390 setCurrentWorkArea(wa);
1396 void GuiView::connectBuffer(Buffer & buf)
1398 buf.setGuiDelegate(this);
1402 void GuiView::disconnectBuffer()
1404 if (d.current_work_area_)
1405 d.current_work_area_->bufferView().buffer().setGuiDelegate(0);
1409 void GuiView::connectBufferView(BufferView & bv)
1411 bv.setGuiDelegate(this);
1415 void GuiView::disconnectBufferView()
1417 if (d.current_work_area_)
1418 d.current_work_area_->bufferView().setGuiDelegate(0);
1422 void GuiView::errors(string const & error_type, bool from_master)
1424 BufferView const * const bv = currentBufferView();
1428 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
1429 // We are called with from_master == false by default, so we
1430 // have to figure out whether that is the case or not.
1431 ErrorList & el = bv->buffer().errorList(error_type);
1433 el = bv->buffer().masterBuffer()->errorList(error_type);
1437 ErrorList & el = from_master ?
1438 bv->buffer().masterBuffer()->errorList(error_type) :
1439 bv->buffer().errorList(error_type);
1445 string data = error_type;
1447 data = "from_master|" + error_type;
1448 showDialog("errorlist", data);
1452 void GuiView::updateTocItem(string const & type, DocIterator const & dit)
1454 d.toc_models_.updateItem(toqstr(type), dit);
1458 void GuiView::structureChanged()
1460 d.toc_models_.reset(documentBufferView());
1461 // Navigator needs more than a simple update in this case. It needs to be
1463 updateDialog("toc", "");
1467 void GuiView::updateDialog(string const & name, string const & data)
1469 if (!isDialogVisible(name))
1472 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
1473 if (it == d.dialogs_.end())
1476 Dialog * const dialog = it->second.get();
1477 if (dialog->isVisibleView())
1478 dialog->initialiseParams(data);
1482 BufferView * GuiView::documentBufferView()
1484 return currentMainWorkArea()
1485 ? ¤tMainWorkArea()->bufferView()
1490 BufferView const * GuiView::documentBufferView() const
1492 return currentMainWorkArea()
1493 ? ¤tMainWorkArea()->bufferView()
1498 BufferView * GuiView::currentBufferView()
1500 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1504 BufferView const * GuiView::currentBufferView() const
1506 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1510 #if (QT_VERSION >= 0x040400)
1511 docstring GuiView::GuiViewPrivate::autosaveAndDestroy(
1512 Buffer const * orig, Buffer * buffer)
1514 bool const success = buffer->autoSave();
1516 busyBuffers.remove(orig);
1518 ? _("Automatic save done.")
1519 : _("Automatic save failed!");
1524 void GuiView::autoSave()
1526 LYXERR(Debug::INFO, "Running autoSave()");
1528 Buffer * buffer = documentBufferView()
1529 ? &documentBufferView()->buffer() : 0;
1531 resetAutosaveTimers();
1535 #if (QT_VERSION >= 0x040400)
1536 GuiViewPrivate::busyBuffers.insert(buffer);
1537 QFuture<docstring> f = QtConcurrent::run(GuiViewPrivate::autosaveAndDestroy,
1538 buffer, buffer->clone());
1539 d.autosave_watcher_.setFuture(f);
1543 resetAutosaveTimers();
1547 void GuiView::resetAutosaveTimers()
1550 d.autosave_timeout_.restart();
1554 bool GuiView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1557 Buffer * buf = currentBufferView()
1558 ? ¤tBufferView()->buffer() : 0;
1559 Buffer * doc_buffer = documentBufferView()
1560 ? &(documentBufferView()->buffer()) : 0;
1562 // Check whether we need a buffer
1563 if (!lyxaction.funcHasFlag(cmd.action(), LyXAction::NoBuffer) && !buf) {
1564 // no, exit directly
1565 flag.message(from_utf8(N_("Command not allowed with"
1566 "out any document open")));
1567 flag.setEnabled(false);
1571 if (cmd.origin() == FuncRequest::TOC) {
1572 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
1573 if (!toc || !toc->getStatus(documentBufferView()->cursor(), cmd, flag))
1574 flag.setEnabled(false);
1578 switch(cmd.action()) {
1579 case LFUN_BUFFER_IMPORT:
1582 case LFUN_MASTER_BUFFER_UPDATE:
1583 case LFUN_MASTER_BUFFER_VIEW:
1584 enable = doc_buffer && doc_buffer->parent() != 0
1585 && !d.processing_thread_watcher_.isRunning();
1588 case LFUN_BUFFER_UPDATE:
1589 case LFUN_BUFFER_VIEW: {
1590 if (!doc_buffer || d.processing_thread_watcher_.isRunning()) {
1594 string format = to_utf8(cmd.argument());
1595 if (cmd.argument().empty())
1596 format = doc_buffer->getDefaultOutputFormat();
1597 enable = doc_buffer->isExportableFormat(format);
1601 case LFUN_BUFFER_RELOAD:
1602 enable = doc_buffer && !doc_buffer->isUnnamed()
1603 && doc_buffer->fileName().exists()
1604 && (!doc_buffer->isClean()
1605 || doc_buffer->isExternallyModified(Buffer::timestamp_method));
1608 case LFUN_BUFFER_CHILD_OPEN:
1609 enable = doc_buffer;
1612 case LFUN_BUFFER_WRITE:
1613 enable = doc_buffer && (doc_buffer->isUnnamed() || !doc_buffer->isClean());
1616 //FIXME: This LFUN should be moved to GuiApplication.
1617 case LFUN_BUFFER_WRITE_ALL: {
1618 // We enable the command only if there are some modified buffers
1619 Buffer * first = theBufferList().first();
1624 // We cannot use a for loop as the buffer list is a cycle.
1626 if (!b->isClean()) {
1630 b = theBufferList().next(b);
1631 } while (b != first);
1635 case LFUN_BUFFER_WRITE_AS:
1636 enable = doc_buffer;
1639 case LFUN_BUFFER_CLOSE:
1640 enable = doc_buffer;
1643 case LFUN_BUFFER_CLOSE_ALL:
1644 enable = theBufferList().last() != theBufferList().first();
1647 case LFUN_SPLIT_VIEW:
1648 if (cmd.getArg(0) == "vertical")
1649 enable = doc_buffer && (d.splitter_->count() == 1 ||
1650 d.splitter_->orientation() == Qt::Vertical);
1652 enable = doc_buffer && (d.splitter_->count() == 1 ||
1653 d.splitter_->orientation() == Qt::Horizontal);
1656 case LFUN_CLOSE_TAB_GROUP:
1657 enable = d.currentTabWorkArea();
1660 case LFUN_TOOLBAR_TOGGLE: {
1661 string const name = cmd.getArg(0);
1662 if (GuiToolbar * t = toolbar(name))
1663 flag.setOnOff(t->isVisible());
1666 docstring const msg =
1667 bformat(_("Unknown toolbar \"%1$s\""), from_utf8(name));
1673 case LFUN_DROP_LAYOUTS_CHOICE:
1677 case LFUN_UI_TOGGLE:
1678 flag.setOnOff(isFullScreen());
1681 case LFUN_DIALOG_DISCONNECT_INSET:
1684 case LFUN_DIALOG_HIDE:
1685 // FIXME: should we check if the dialog is shown?
1688 case LFUN_DIALOG_TOGGLE:
1689 flag.setOnOff(isDialogVisible(cmd.getArg(0)));
1690 // fall through to set "enable"
1691 case LFUN_DIALOG_SHOW: {
1692 string const name = cmd.getArg(0);
1694 enable = name == "aboutlyx"
1695 || name == "file" //FIXME: should be removed.
1697 || name == "texinfo"
1698 || name == "progress"
1699 || name == "compare";
1700 else if (name == "print")
1701 enable = doc_buffer->isExportable("dvi")
1702 && lyxrc.print_command != "none";
1703 else if (name == "character" || name == "symbols") {
1704 if (!buf || buf->isReadonly())
1707 Cursor const & cur = currentBufferView()->cursor();
1708 enable = !(cur.inTexted() && cur.paragraph().isPassThru());
1711 else if (name == "latexlog")
1712 enable = FileName(doc_buffer->logName()).isReadableFile();
1713 else if (name == "spellchecker")
1714 enable = theSpellChecker() && !doc_buffer->isReadonly();
1715 else if (name == "vclog")
1716 enable = doc_buffer->lyxvc().inUse();
1720 case LFUN_DIALOG_UPDATE: {
1721 string const name = cmd.getArg(0);
1723 enable = name == "prefs";
1727 case LFUN_COMMAND_EXECUTE:
1729 case LFUN_MENU_OPEN:
1730 // Nothing to check.
1733 case LFUN_COMPLETION_INLINE:
1734 if (!d.current_work_area_
1735 || !d.current_work_area_->completer().inlinePossible(
1736 currentBufferView()->cursor()))
1740 case LFUN_COMPLETION_POPUP:
1741 if (!d.current_work_area_
1742 || !d.current_work_area_->completer().popupPossible(
1743 currentBufferView()->cursor()))
1747 case LFUN_COMPLETION_COMPLETE:
1748 if (!d.current_work_area_
1749 || !d.current_work_area_->completer().inlinePossible(
1750 currentBufferView()->cursor()))
1754 case LFUN_COMPLETION_ACCEPT:
1755 if (!d.current_work_area_
1756 || (!d.current_work_area_->completer().popupVisible()
1757 && !d.current_work_area_->completer().inlineVisible()
1758 && !d.current_work_area_->completer().completionAvailable()))
1762 case LFUN_COMPLETION_CANCEL:
1763 if (!d.current_work_area_
1764 || (!d.current_work_area_->completer().popupVisible()
1765 && !d.current_work_area_->completer().inlineVisible()))
1769 case LFUN_BUFFER_ZOOM_OUT:
1770 enable = doc_buffer && lyxrc.zoom > 10;
1773 case LFUN_BUFFER_ZOOM_IN:
1774 enable = doc_buffer;
1777 case LFUN_BUFFER_NEXT:
1778 case LFUN_BUFFER_PREVIOUS:
1779 // FIXME: should we check is there is an previous or next buffer?
1781 case LFUN_BUFFER_SWITCH:
1782 // toggle on the current buffer, but do not toggle off
1783 // the other ones (is that a good idea?)
1785 && to_utf8(cmd.argument()) == doc_buffer->absFileName())
1786 flag.setOnOff(true);
1789 case LFUN_VC_REGISTER:
1790 enable = doc_buffer && !doc_buffer->lyxvc().inUse();
1792 case LFUN_VC_CHECK_IN:
1793 enable = doc_buffer && doc_buffer->lyxvc().checkInEnabled();
1795 case LFUN_VC_CHECK_OUT:
1796 enable = doc_buffer && doc_buffer->lyxvc().checkOutEnabled();
1798 case LFUN_VC_LOCKING_TOGGLE:
1799 enable = doc_buffer && !doc_buffer->isReadonly()
1800 && doc_buffer->lyxvc().lockingToggleEnabled();
1801 flag.setOnOff(enable && doc_buffer->lyxvc().locking());
1803 case LFUN_VC_REVERT:
1804 enable = doc_buffer && doc_buffer->lyxvc().inUse() && !doc_buffer->isReadonly();
1806 case LFUN_VC_UNDO_LAST:
1807 enable = doc_buffer && doc_buffer->lyxvc().undoLastEnabled();
1809 case LFUN_VC_REPO_UPDATE:
1810 enable = doc_buffer && doc_buffer->lyxvc().repoUpdateEnabled();
1812 case LFUN_VC_COMMAND: {
1813 if (cmd.argument().empty())
1815 if (!doc_buffer && contains(cmd.getArg(0), 'D'))
1819 case LFUN_VC_COMPARE:
1820 enable = doc_buffer && doc_buffer->lyxvc().prepareFileRevisionEnabled();
1823 case LFUN_SERVER_GOTO_FILE_ROW:
1825 case LFUN_FORWARD_SEARCH:
1826 enable = !(lyxrc.forward_search_dvi.empty() && lyxrc.forward_search_pdf.empty());
1834 flag.setEnabled(false);
1840 static FileName selectTemplateFile()
1842 FileDialog dlg(qt_("Select template file"));
1843 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1844 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
1846 FileDialog::Result result = dlg.open(toqstr(lyxrc.template_path),
1847 QStringList(qt_("LyX Documents (*.lyx)")));
1849 if (result.first == FileDialog::Later)
1851 if (result.second.isEmpty())
1853 return FileName(fromqstr(result.second));
1857 Buffer * GuiView::loadDocument(FileName const & filename, bool tolastfiles)
1861 Buffer * newBuffer = 0;
1863 newBuffer = checkAndLoadLyXFile(filename);
1864 } catch (ExceptionMessage const & e) {
1870 message(_("Document not loaded."));
1875 newBuffer->errors("Parse");
1876 setBuffer(newBuffer);
1879 theSession().lastFiles().add(filename);
1886 void GuiView::openDocument(string const & fname)
1888 string initpath = lyxrc.document_path;
1890 if (documentBufferView()) {
1891 string const trypath = documentBufferView()->buffer().filePath();
1892 // If directory is writeable, use this as default.
1893 if (FileName(trypath).isDirWritable())
1899 if (fname.empty()) {
1900 FileDialog dlg(qt_("Select document to open"), LFUN_FILE_OPEN);
1901 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1902 dlg.setButton2(qt_("Examples|#E#e"),
1903 toqstr(addPath(package().system_support().absFileName(), "examples")));
1905 QStringList filter(qt_("LyX Documents (*.lyx)"));
1906 filter << qt_("LyX-1.3.x Documents (*.lyx13)")
1907 << qt_("LyX-1.4.x Documents (*.lyx14)")
1908 << qt_("LyX-1.5.x Documents (*.lyx15)")
1909 << qt_("LyX-1.6.x Documents (*.lyx16)");
1910 FileDialog::Result result =
1911 dlg.open(toqstr(initpath), filter);
1913 if (result.first == FileDialog::Later)
1916 filename = fromqstr(result.second);
1918 // check selected filename
1919 if (filename.empty()) {
1920 message(_("Canceled."));
1926 // get absolute path of file and add ".lyx" to the filename if
1928 FileName const fullname =
1929 fileSearch(string(), filename, "lyx", support::may_not_exist);
1930 if (!fullname.empty())
1931 filename = fullname.absFileName();
1933 if (!fullname.onlyPath().isDirectory()) {
1934 Alert::warning(_("Invalid filename"),
1935 bformat(_("The directory in the given path\n%1$s\ndoes not exist."),
1936 from_utf8(fullname.absFileName())));
1940 // if the file doesn't exist and isn't already open (bug 6645),
1941 // let the user create one
1942 if (!fullname.exists() && !theBufferList().exists(fullname)) {
1943 // the user specifically chose this name. Believe him.
1944 Buffer * const b = newFile(filename, string(), true);
1950 docstring const disp_fn = makeDisplayPath(filename);
1951 message(bformat(_("Opening document %1$s..."), disp_fn));
1954 Buffer * buf = loadDocument(fullname);
1956 str2 = bformat(_("Document %1$s opened."), disp_fn);
1957 if (buf->lyxvc().inUse())
1958 str2 += " " + from_utf8(buf->lyxvc().versionString()) +
1959 " " + _("Version control detected.");
1961 str2 = bformat(_("Could not open document %1$s"), disp_fn);
1966 // FIXME: clean that
1967 static bool import(GuiView * lv, FileName const & filename,
1968 string const & format, ErrorList & errorList)
1970 FileName const lyxfile(support::changeExtension(filename.absFileName(), ".lyx"));
1972 string loader_format;
1973 vector<string> loaders = theConverters().loaders();
1974 if (find(loaders.begin(), loaders.end(), format) == loaders.end()) {
1975 for (vector<string>::const_iterator it = loaders.begin();
1976 it != loaders.end(); ++it) {
1977 if (!theConverters().isReachable(format, *it))
1980 string const tofile =
1981 support::changeExtension(filename.absFileName(),
1982 formats.extension(*it));
1983 if (!theConverters().convert(0, filename, FileName(tofile),
1984 filename, format, *it, errorList))
1986 loader_format = *it;
1989 if (loader_format.empty()) {
1990 frontend::Alert::error(_("Couldn't import file"),
1991 bformat(_("No information for importing the format %1$s."),
1992 formats.prettyName(format)));
1996 loader_format = format;
1998 if (loader_format == "lyx") {
1999 Buffer * buf = lv->loadDocument(lyxfile);
2003 Buffer * const b = newFile(lyxfile.absFileName(), string(), true);
2007 bool as_paragraphs = loader_format == "textparagraph";
2008 string filename2 = (loader_format == format) ? filename.absFileName()
2009 : support::changeExtension(filename.absFileName(),
2010 formats.extension(loader_format));
2011 lv->currentBufferView()->insertPlaintextFile(FileName(filename2),
2013 guiApp->setCurrentView(lv);
2014 lyx::dispatch(FuncRequest(LFUN_MARK_OFF));
2021 void GuiView::importDocument(string const & argument)
2024 string filename = split(argument, format, ' ');
2026 LYXERR(Debug::INFO, format << " file: " << filename);
2028 // need user interaction
2029 if (filename.empty()) {
2030 string initpath = lyxrc.document_path;
2031 if (documentBufferView()) {
2032 string const trypath = documentBufferView()->buffer().filePath();
2033 // If directory is writeable, use this as default.
2034 if (FileName(trypath).isDirWritable())
2038 docstring const text = bformat(_("Select %1$s file to import"),
2039 formats.prettyName(format));
2041 FileDialog dlg(toqstr(text), LFUN_BUFFER_IMPORT);
2042 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2043 dlg.setButton2(qt_("Examples|#E#e"),
2044 toqstr(addPath(package().system_support().absFileName(), "examples")));
2046 docstring filter = formats.prettyName(format);
2049 filter += from_utf8(formats.extension(format));
2052 FileDialog::Result result =
2053 dlg.open(toqstr(initpath), fileFilters(toqstr(filter)));
2055 if (result.first == FileDialog::Later)
2058 filename = fromqstr(result.second);
2060 // check selected filename
2061 if (filename.empty())
2062 message(_("Canceled."));
2065 if (filename.empty())
2068 // get absolute path of file
2069 FileName const fullname(support::makeAbsPath(filename));
2071 FileName const lyxfile(support::changeExtension(fullname.absFileName(), ".lyx"));
2073 // Check if the document already is open
2074 Buffer * buf = theBufferList().getBuffer(lyxfile);
2077 if (!closeBuffer()) {
2078 message(_("Canceled."));
2083 docstring const displaypath = makeDisplayPath(lyxfile.absFileName(), 30);
2085 // if the file exists already, and we didn't do
2086 // -i lyx thefile.lyx, warn
2087 if (lyxfile.exists() && fullname != lyxfile) {
2089 docstring text = bformat(_("The document %1$s already exists.\n\n"
2090 "Do you want to overwrite that document?"), displaypath);
2091 int const ret = Alert::prompt(_("Overwrite document?"),
2092 text, 0, 1, _("&Overwrite"), _("&Cancel"));
2095 message(_("Canceled."));
2100 message(bformat(_("Importing %1$s..."), displaypath));
2101 ErrorList errorList;
2102 if (import(this, fullname, format, errorList))
2103 message(_("imported."));
2105 message(_("file not imported!"));
2107 // FIXME (Abdel 12/08/06): Is there a need to display the error list here?
2111 void GuiView::newDocument(string const & filename, bool from_template)
2113 FileName initpath(lyxrc.document_path);
2114 if (documentBufferView()) {
2115 FileName const trypath(documentBufferView()->buffer().filePath());
2116 // If directory is writeable, use this as default.
2117 if (trypath.isDirWritable())
2121 string templatefile;
2122 if (from_template) {
2123 templatefile = selectTemplateFile().absFileName();
2124 if (templatefile.empty())
2129 if (filename.empty())
2130 b = newUnnamedFile(initpath, to_utf8(_("newfile")), templatefile);
2132 b = newFile(filename, templatefile, true);
2137 // If no new document could be created, it is unsure
2138 // whether there is a valid BufferView.
2139 if (currentBufferView())
2140 // Ensure the cursor is correctly positioned on screen.
2141 currentBufferView()->showCursor();
2145 void GuiView::insertLyXFile(docstring const & fname)
2147 BufferView * bv = documentBufferView();
2152 FileName filename(to_utf8(fname));
2153 if (filename.empty()) {
2154 // Launch a file browser
2156 string initpath = lyxrc.document_path;
2157 string const trypath = bv->buffer().filePath();
2158 // If directory is writeable, use this as default.
2159 if (FileName(trypath).isDirWritable())
2163 FileDialog dlg(qt_("Select LyX document to insert"), LFUN_FILE_INSERT);
2164 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2165 dlg.setButton2(qt_("Examples|#E#e"),
2166 toqstr(addPath(package().system_support().absFileName(),
2169 FileDialog::Result result = dlg.open(toqstr(initpath),
2170 QStringList(qt_("LyX Documents (*.lyx)")));
2172 if (result.first == FileDialog::Later)
2176 filename.set(fromqstr(result.second));
2178 // check selected filename
2179 if (filename.empty()) {
2180 // emit message signal.
2181 message(_("Canceled."));
2186 bv->insertLyXFile(filename);
2187 bv->buffer().errors("Parse");
2191 void GuiView::insertPlaintextFile(docstring const & fname,
2194 BufferView * bv = documentBufferView();
2198 if (!fname.empty() && !FileName::isAbsolute(to_utf8(fname))) {
2199 message(_("Absolute filename expected."));
2204 FileName filename(to_utf8(fname));
2206 if (!filename.empty()) {
2207 bv->insertPlaintextFile(filename, asParagraph);
2211 FileDialog dlg(qt_("Select file to insert"), (asParagraph ?
2212 LFUN_FILE_INSERT_PLAINTEXT_PARA : LFUN_FILE_INSERT_PLAINTEXT));
2214 FileDialog::Result result = dlg.open(toqstr(bv->buffer().filePath()),
2215 QStringList(qt_("All Files (*)")));
2217 if (result.first == FileDialog::Later)
2221 filename.set(fromqstr(result.second));
2223 // check selected filename
2224 if (filename.empty()) {
2225 // emit message signal.
2226 message(_("Canceled."));
2230 bv->insertPlaintextFile(filename, asParagraph);
2234 bool GuiView::renameBuffer(Buffer & b, docstring const & newname)
2236 FileName fname = b.fileName();
2237 FileName const oldname = fname;
2239 if (!newname.empty()) {
2241 fname = support::makeAbsPath(to_utf8(newname), oldname.onlyPath().absFileName());
2243 // Switch to this Buffer.
2246 // No argument? Ask user through dialog.
2248 FileDialog dlg(qt_("Choose a filename to save document as"),
2249 LFUN_BUFFER_WRITE_AS);
2250 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2251 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
2253 if (!isLyXFileName(fname.absFileName()))
2254 fname.changeExtension(".lyx");
2256 FileDialog::Result result =
2257 dlg.save(toqstr(fname.onlyPath().absFileName()),
2258 QStringList(qt_("LyX Documents (*.lyx)")),
2259 toqstr(fname.onlyFileName()));
2261 if (result.first == FileDialog::Later)
2264 fname.set(fromqstr(result.second));
2269 if (!isLyXFileName(fname.absFileName()))
2270 fname.changeExtension(".lyx");
2273 // fname is now the new Buffer location.
2274 if (FileName(fname).exists()) {
2275 docstring const file = makeDisplayPath(fname.absFileName(), 30);
2276 docstring text = bformat(_("The document %1$s already "
2277 "exists.\n\nDo you want to "
2278 "overwrite that document?"),
2280 int const ret = Alert::prompt(_("Overwrite document?"),
2281 text, 0, 2, _("&Overwrite"), _("&Rename"), _("&Cancel"));
2284 case 1: return renameBuffer(b, docstring());
2285 case 2: return false;
2289 return saveBuffer(b, fname);
2293 bool GuiView::saveBuffer(Buffer & b) {
2294 return saveBuffer(b, FileName());
2298 bool GuiView::saveBuffer(Buffer & b, FileName const & fn)
2300 if (workArea(b) && workArea(b)->inDialogMode())
2303 if (fn.empty() && b.isUnnamed())
2304 return renameBuffer(b, docstring());
2310 success = b.saveAs(fn);
2313 theSession().lastFiles().add(b.fileName());
2317 // Switch to this Buffer.
2320 // FIXME: we don't tell the user *WHY* the save failed !!
2321 docstring const file = makeDisplayPath(b.absFileName(), 30);
2322 docstring text = bformat(_("The document %1$s could not be saved.\n\n"
2323 "Do you want to rename the document and "
2324 "try again?"), file);
2325 int const ret = Alert::prompt(_("Rename and save?"),
2326 text, 0, 2, _("&Rename"), _("&Retry"), _("&Cancel"));
2329 if (!renameBuffer(b, docstring()))
2338 return saveBuffer(b);
2342 bool GuiView::hideWorkArea(GuiWorkArea * wa)
2344 return closeWorkArea(wa, false);
2348 bool GuiView::closeWorkArea(GuiWorkArea * wa)
2350 Buffer & buf = wa->bufferView().buffer();
2351 return closeWorkArea(wa, !buf.parent());
2355 bool GuiView::closeBuffer()
2357 GuiWorkArea * wa = currentMainWorkArea();
2358 setCurrentWorkArea(wa);
2359 Buffer & buf = wa->bufferView().buffer();
2360 return wa && closeWorkArea(wa, !buf.parent());
2364 void GuiView::writeSession() const {
2365 GuiWorkArea const * active_wa = currentMainWorkArea();
2366 for (int i = 0; i < d.splitter_->count(); ++i) {
2367 TabWorkArea * twa = d.tabWorkArea(i);
2368 for (int j = 0; j < twa->count(); ++j) {
2369 GuiWorkArea * wa = static_cast<GuiWorkArea *>(twa->widget(j));
2370 Buffer & buf = wa->bufferView().buffer();
2371 theSession().lastOpened().add(buf.fileName(), wa == active_wa);
2377 bool GuiView::closeBufferAll()
2379 // Close the workareas in all other views
2380 QList<int> const ids = guiApp->viewIds();
2381 for (int i = 0; i != ids.size(); ++i) {
2382 if (id_ != ids[i] && !guiApp->view(ids[i]).closeWorkAreaAll())
2386 // Close our own workareas
2387 if (!closeWorkAreaAll())
2390 // Now close the hidden buffers. We prevent hidden buffers from being
2391 // dirty, so we can just close them.
2392 theBufferList().closeAll();
2397 bool GuiView::closeWorkAreaAll()
2399 setCurrentWorkArea(currentMainWorkArea());
2401 // We might be in a situation that there is still a tabWorkArea, but
2402 // there are no tabs anymore. This can happen when we get here after a
2403 // TabWorkArea::lastWorkAreaRemoved() signal. Therefore we count how
2404 // many TabWorkArea's have no documents anymore.
2407 // We have to call count() each time, because it can happen that
2408 // more than one splitter will disappear in one iteration (bug 5998).
2409 for (; d.splitter_->count() > empty_twa; ) {
2410 TabWorkArea * twa = d.tabWorkArea(empty_twa);
2412 if (twa->count() == 0)
2415 setCurrentWorkArea(twa->currentWorkArea());
2416 if (!closeTabWorkArea(twa))
2424 bool GuiView::closeWorkArea(GuiWorkArea * wa, bool close_buffer)
2429 Buffer & buf = wa->bufferView().buffer();
2431 if (close_buffer && GuiViewPrivate::busyBuffers.contains(&buf)) {
2432 Alert::warning(_("Close document"),
2433 _("Document could not be closed because it is being processed by LyX."));
2438 return closeBuffer(buf);
2440 if (!inMultiTabs(wa))
2441 if (!saveBufferIfNeeded(buf, true))
2449 bool GuiView::closeBuffer(Buffer & buf)
2451 // If we are in a close_event all children will be closed in some time,
2452 // so no need to do it here. This will ensure that the children end up
2453 // in the session file in the correct order. If we close the master
2454 // buffer, we can close or release the child buffers here too.
2455 bool success = true;
2457 ListOfBuffers clist = buf.getChildren();
2458 ListOfBuffers::const_iterator it = clist.begin();
2459 ListOfBuffers::const_iterator const bend = clist.end();
2460 for (; it != bend; ++it) {
2461 // If a child is dirty, do not close
2462 // without user intervention
2463 //FIXME: should we look in other tabworkareas?
2464 Buffer * child_buf = *it;
2465 GuiWorkArea * child_wa = workArea(*child_buf);
2467 if (!closeWorkArea(child_wa, true)) {
2472 theBufferList().releaseChild(&buf, child_buf);
2476 // goto bookmark to update bookmark pit.
2477 //FIXME: we should update only the bookmarks related to this buffer!
2478 LYXERR(Debug::DEBUG, "GuiView::closeBuffer()");
2479 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
2480 guiApp->gotoBookmark(i+1, false, false);
2482 if (saveBufferIfNeeded(buf, false)) {
2483 buf.removeAutosaveFile();
2484 theBufferList().release(&buf);
2488 // open all children again to avoid a crash because of dangling
2489 // pointers (bug 6603)
2495 bool GuiView::closeTabWorkArea(TabWorkArea * twa)
2497 while (twa == d.currentTabWorkArea()) {
2498 twa->setCurrentIndex(twa->count()-1);
2500 GuiWorkArea * wa = twa->currentWorkArea();
2501 Buffer & b = wa->bufferView().buffer();
2503 // We only want to close the buffer if the same buffer is not visible
2504 // in another view, and if this is not a child and if we are closing
2505 // a view (not a tabgroup).
2506 bool const close_buffer =
2507 !inOtherView(b) && !b.parent() && closing_;
2509 if (!closeWorkArea(wa, close_buffer))
2516 bool GuiView::saveBufferIfNeeded(Buffer & buf, bool hiding)
2518 if (buf.isClean() || buf.paragraphs().empty())
2521 // Switch to this Buffer.
2526 if (buf.isUnnamed())
2527 file = from_utf8(buf.fileName().onlyFileName());
2529 file = buf.fileName().displayName(30);
2531 // Bring this window to top before asking questions.
2536 if (hiding && buf.isUnnamed()) {
2537 docstring const text = bformat(_("The document %1$s has not been "
2538 "saved yet.\n\nDo you want to save "
2539 "the document?"), file);
2540 ret = Alert::prompt(_("Save new document?"),
2541 text, 0, 1, _("&Save"), _("&Cancel"));
2545 docstring const text = bformat(_("The document %1$s has unsaved changes."
2546 "\n\nDo you want to save the document or discard the changes?"), file);
2547 ret = Alert::prompt(_("Save changed document?"),
2548 text, 0, 2, _("&Save"), _("&Discard"), _("&Cancel"));
2553 if (!saveBuffer(buf))
2557 // If we crash after this we could have no autosave file
2558 // but I guess this is really improbable (Jug).
2559 // Sometimes improbable things happen:
2560 // - see bug http://www.lyx.org/trac/ticket/6587 (ps)
2561 // buf.removeAutosaveFile();
2563 // revert all changes
2574 bool GuiView::inMultiTabs(GuiWorkArea * wa)
2576 Buffer & buf = wa->bufferView().buffer();
2578 for (int i = 0; i != d.splitter_->count(); ++i) {
2579 GuiWorkArea * wa_ = d.tabWorkArea(i)->workArea(buf);
2580 if (wa_ && wa_ != wa)
2583 return inOtherView(buf);
2587 bool GuiView::inOtherView(Buffer & buf)
2589 QList<int> const ids = guiApp->viewIds();
2591 for (int i = 0; i != ids.size(); ++i) {
2595 if (guiApp->view(ids[i]).workArea(buf))
2602 void GuiView::gotoNextOrPreviousBuffer(NextOrPrevious np)
2604 if (!documentBufferView())
2607 if (TabWorkArea * twa = d.currentTabWorkArea()) {
2608 Buffer * const curbuf = &documentBufferView()->buffer();
2609 int nwa = twa->count();
2610 for (int i = 0; i < nwa; ++i) {
2611 if (&workArea(i)->bufferView().buffer() == curbuf) {
2613 if (np == NEXTBUFFER)
2614 next_index = (i == nwa - 1 ? 0 : i + 1);
2616 next_index = (i == 0 ? nwa - 1 : i - 1);
2617 setBuffer(&workArea(next_index)->bufferView().buffer());
2625 /// make sure the document is saved
2626 static bool ensureBufferClean(Buffer * buffer)
2628 LASSERT(buffer, return false);
2629 if (buffer->isClean() && !buffer->isUnnamed())
2632 docstring const file = buffer->fileName().displayName(30);
2635 if (!buffer->isUnnamed()) {
2636 text = bformat(_("The document %1$s has unsaved "
2637 "changes.\n\nDo you want to save "
2638 "the document?"), file);
2639 title = _("Save changed document?");
2642 text = bformat(_("The document %1$s has not been "
2643 "saved yet.\n\nDo you want to save "
2644 "the document?"), file);
2645 title = _("Save new document?");
2647 int const ret = Alert::prompt(title, text, 0, 1, _("&Save"), _("&Cancel"));
2650 dispatch(FuncRequest(LFUN_BUFFER_WRITE));
2652 return buffer->isClean() && !buffer->isUnnamed();
2656 bool GuiView::reloadBuffer(Buffer & buf)
2658 Buffer::ReadStatus status = buf.reload();
2659 return status == Buffer::ReadSuccess;
2663 void GuiView::checkExternallyModifiedBuffers()
2665 BufferList::iterator bit = theBufferList().begin();
2666 BufferList::iterator const bend = theBufferList().end();
2667 for (; bit != bend; ++bit) {
2668 Buffer * buf = *bit;
2669 if (buf->fileName().exists()
2670 && buf->isExternallyModified(Buffer::checksum_method)) {
2671 docstring text = bformat(_("Document \n%1$s\n has been externally modified."
2672 " Reload now? Any local changes will be lost."),
2673 from_utf8(buf->absFileName()));
2674 int const ret = Alert::prompt(_("Reload externally changed document?"),
2675 text, 0, 1, _("&Reload"), _("&Cancel"));
2683 void GuiView::dispatchVC(FuncRequest const & cmd, DispatchResult & dr)
2685 Buffer * buffer = documentBufferView()
2686 ? &(documentBufferView()->buffer()) : 0;
2688 switch (cmd.action()) {
2689 case LFUN_VC_REGISTER:
2690 if (!buffer || !ensureBufferClean(buffer))
2692 if (!buffer->lyxvc().inUse()) {
2693 if (buffer->lyxvc().registrer()) {
2694 reloadBuffer(*buffer);
2695 dr.suppressMessageUpdate();
2700 case LFUN_VC_CHECK_IN:
2701 if (!buffer || !ensureBufferClean(buffer))
2703 if (buffer->lyxvc().inUse() && !buffer->isReadonly()) {
2704 dr.setMessage(buffer->lyxvc().checkIn());
2705 if (!dr.message().empty())
2706 reloadBuffer(*buffer);
2710 case LFUN_VC_CHECK_OUT:
2711 if (!buffer || !ensureBufferClean(buffer))
2713 if (buffer->lyxvc().inUse()) {
2714 dr.setMessage(buffer->lyxvc().checkOut());
2715 reloadBuffer(*buffer);
2719 case LFUN_VC_LOCKING_TOGGLE:
2720 LASSERT(buffer, return);
2721 if (!ensureBufferClean(buffer) || buffer->isReadonly())
2723 if (buffer->lyxvc().inUse()) {
2724 string res = buffer->lyxvc().lockingToggle();
2726 frontend::Alert::error(_("Revision control error."),
2727 _("Error when setting the locking property."));
2730 reloadBuffer(*buffer);
2735 case LFUN_VC_REVERT:
2736 LASSERT(buffer, return);
2737 if (buffer->lyxvc().revert()) {
2738 reloadBuffer(*buffer);
2739 dr.suppressMessageUpdate();
2743 case LFUN_VC_UNDO_LAST:
2744 LASSERT(buffer, return);
2745 buffer->lyxvc().undoLast();
2746 reloadBuffer(*buffer);
2747 dr.suppressMessageUpdate();
2750 case LFUN_VC_REPO_UPDATE:
2751 LASSERT(buffer, return);
2752 if (ensureBufferClean(buffer)) {
2753 dr.setMessage(buffer->lyxvc().repoUpdate());
2754 checkExternallyModifiedBuffers();
2758 case LFUN_VC_COMMAND: {
2759 string flag = cmd.getArg(0);
2760 if (buffer && contains(flag, 'R') && !ensureBufferClean(buffer))
2763 if (contains(flag, 'M')) {
2764 if (!Alert::askForText(message, _("LyX VC: Log Message")))
2767 string path = cmd.getArg(1);
2768 if (contains(path, "$$p") && buffer)
2769 path = subst(path, "$$p", buffer->filePath());
2770 LYXERR(Debug::LYXVC, "Directory: " << path);
2772 if (!pp.isReadableDirectory()) {
2773 lyxerr << _("Directory is not accessible.") << endl;
2776 support::PathChanger p(pp);
2778 string command = cmd.getArg(2);
2779 if (command.empty())
2782 command = subst(command, "$$i", buffer->absFileName());
2783 command = subst(command, "$$p", buffer->filePath());
2785 command = subst(command, "$$m", to_utf8(message));
2786 LYXERR(Debug::LYXVC, "Command: " << command);
2788 one.startscript(Systemcall::Wait, command);
2792 if (contains(flag, 'I'))
2793 buffer->markDirty();
2794 if (contains(flag, 'R'))
2795 reloadBuffer(*buffer);
2800 case LFUN_VC_COMPARE: {
2802 if (cmd.argument().empty()) {
2803 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "comparehistory"));
2807 string rev1 = cmd.getArg(0);
2811 if (!buffer->lyxvc().prepareFileRevision(rev1, f1))
2814 if (isStrInt(rev1) && convert<int>(rev1) <= 0) {
2815 f2 = buffer->absFileName();
2817 string rev2 = cmd.getArg(1);
2821 if (!buffer->lyxvc().prepareFileRevision(rev2, f2))
2825 LYXERR(Debug::LYXVC, "Launching comparison for fetched revisions:\n" <<
2826 f1 << "\n" << f2 << "\n" );
2827 string par = "compare run " + quoteName(f1) + " " + quoteName(f2);
2828 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, par));
2838 void GuiView::openChildDocument(string const & fname)
2840 LASSERT(documentBufferView(), return);
2841 Buffer & buffer = documentBufferView()->buffer();
2842 FileName const filename = support::makeAbsPath(fname, buffer.filePath());
2843 documentBufferView()->saveBookmark(false);
2845 if (theBufferList().exists(filename)) {
2846 child = theBufferList().getBuffer(filename);
2849 message(bformat(_("Opening child document %1$s..."),
2850 makeDisplayPath(filename.absFileName())));
2851 child = loadDocument(filename, false);
2853 // Set the parent name of the child document.
2854 // This makes insertion of citations and references in the child work,
2855 // when the target is in the parent or another child document.
2857 child->setParent(&buffer);
2861 bool GuiView::goToFileRow(string const & argument)
2865 size_t i = argument.find_last_of(' ');
2866 if (i != string::npos) {
2867 file_name = os::internal_path(trim(argument.substr(0, i)));
2868 istringstream is(argument.substr(i + 1));
2873 if (i == string::npos) {
2874 LYXERR0("Wrong argument: " << argument);
2878 string const abstmp = package().temp_dir().absFileName();
2879 string const realtmp = package().temp_dir().realPath();
2880 // We have to use os::path_prefix_is() here, instead of
2881 // simply prefixIs(), because the file name comes from
2882 // an external application and may need case adjustment.
2883 if (os::path_prefix_is(file_name, abstmp, os::CASE_ADJUSTED)
2884 || os::path_prefix_is(file_name, realtmp, os::CASE_ADJUSTED)) {
2885 // Needed by inverse dvi search. If it is a file
2886 // in tmpdir, call the apropriated function.
2887 // If tmpdir is a symlink, we may have the real
2888 // path passed back, so we correct for that.
2889 if (!prefixIs(file_name, abstmp))
2890 file_name = subst(file_name, realtmp, abstmp);
2891 buf = theBufferList().getBufferFromTmp(file_name);
2893 // Must replace extension of the file to be .lyx
2894 // and get full path
2895 FileName const s = fileSearch(string(),
2896 support::changeExtension(file_name, ".lyx"), "lyx");
2897 // Either change buffer or load the file
2898 if (theBufferList().exists(s))
2899 buf = theBufferList().getBuffer(s);
2900 else if (s.exists()) {
2901 buf = loadDocument(s);
2906 _("File does not exist: %1$s"),
2907 makeDisplayPath(file_name)));
2912 documentBufferView()->setCursorFromRow(row);
2917 #if (QT_VERSION >= 0x040400)
2919 docstring GuiView::GuiViewPrivate::runAndDestroy(const T& func, Buffer const * orig, Buffer * buffer, string const & format, string const & msg)
2921 bool const update_unincluded =
2922 buffer->params().maintain_unincluded_children
2923 && !buffer->params().getIncludedChildren().empty();
2924 bool const success = func(format, update_unincluded);
2926 busyBuffers.remove(orig);
2927 if (msg == "preview") {
2929 ? bformat(_("Successful preview of format: %1$s"), from_utf8(format))
2930 : bformat(_("Error while previewing format: %1$s"), from_utf8(format));
2933 ? bformat(_("Successful export to format: %1$s"), from_utf8(format))
2934 : bformat(_("Error while exporting format: %1$s"), from_utf8(format));
2938 docstring GuiView::GuiViewPrivate::compileAndDestroy(Buffer const * orig, Buffer * buffer, string const & format)
2940 bool (Buffer::* mem_func)(std::string const &, bool, bool) const = &Buffer::doExport;
2941 return runAndDestroy(bind(mem_func, buffer, _1, true, _2), orig, buffer, format, "export");
2945 docstring GuiView::GuiViewPrivate::exportAndDestroy(Buffer const * orig, Buffer * buffer, string const & format)
2947 bool (Buffer::* mem_func)(std::string const &, bool, bool) const = &Buffer::doExport;
2948 return runAndDestroy(bind(mem_func, buffer, _1, false, _2), orig, buffer, format, "export");
2952 docstring GuiView::GuiViewPrivate::previewAndDestroy(Buffer const * orig, Buffer * buffer, string const & format)
2954 bool(Buffer::* mem_func)(std::string const &, bool) const = &Buffer::preview;
2955 return runAndDestroy(bind(mem_func, buffer, _1, _2), orig, buffer, format, "preview");
2960 // not used, but the linker needs them
2962 docstring GuiView::GuiViewPrivate::compileAndDestroy(
2963 Buffer const *, Buffer *, string const &)
2969 docstring GuiView::GuiViewPrivate::exportAndDestroy(
2970 Buffer const *, Buffer *, string const &)
2976 docstring GuiView::GuiViewPrivate::previewAndDestroy(
2977 Buffer const *, Buffer *, string const &)
2985 bool GuiView::GuiViewPrivate::asyncBufferProcessing(
2986 string const & argument,
2987 Buffer const * used_buffer,
2988 docstring const & msg,
2989 docstring (*asyncFunc)(Buffer const *, Buffer *, string const &),
2990 bool (Buffer::*syncFunc)(string const &, bool, bool) const,
2991 bool (Buffer::*previewFunc)(string const &, bool) const)
2996 string format = argument;
2998 format = used_buffer->getDefaultOutputFormat();
3000 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
3002 progress_->clearMessages();
3005 GuiViewPrivate::busyBuffers.insert(used_buffer);
3006 QFuture<docstring> f = QtConcurrent::run(
3009 used_buffer->clone(),
3011 setPreviewFuture(f);
3012 last_export_format = used_buffer->bufferFormat();
3015 // We are asynchronous, so we don't know here anything about the success
3019 // TODO check here if it breaks exporting with Qt < 4.4
3020 bool const update_unincluded =
3021 used_buffer->params().maintain_unincluded_children &&
3022 !used_buffer->params().getIncludedChildren().empty();
3023 return (used_buffer->*syncFunc)(format, true, update_unincluded);
3024 } else if (previewFunc) {
3025 return (used_buffer->*previewFunc)(format, false);
3032 void GuiView::dispatchToBufferView(FuncRequest const & cmd, DispatchResult & dr)
3034 BufferView * bv = currentBufferView();
3037 // Let the current BufferView dispatch its own actions.
3038 bv->dispatch(cmd, dr);
3039 if (dr.dispatched())
3042 // Try with the document BufferView dispatch if any.
3043 BufferView * doc_bv = documentBufferView();
3045 doc_bv->dispatch(cmd, dr);
3046 if (dr.dispatched())
3050 // Then let the current Cursor dispatch its own actions.
3051 bv->cursor().dispatch(cmd);
3053 // update completion. We do it here and not in
3054 // processKeySym to avoid another redraw just for a
3055 // changed inline completion
3056 if (cmd.origin() == FuncRequest::KEYBOARD) {
3057 if (cmd.action() == LFUN_SELF_INSERT
3058 || (cmd.action() == LFUN_ERT_INSERT && bv->cursor().inMathed()))
3059 updateCompletion(bv->cursor(), true, true);
3060 else if (cmd.action() == LFUN_CHAR_DELETE_BACKWARD)
3061 updateCompletion(bv->cursor(), false, true);
3063 updateCompletion(bv->cursor(), false, false);
3066 dr = bv->cursor().result();
3070 void GuiView::dispatch(FuncRequest const & cmd, DispatchResult & dr)
3072 BufferView * bv = currentBufferView();
3073 // By default we won't need any update.
3074 dr.screenUpdate(Update::None);
3075 // assume cmd will be dispatched
3076 dr.dispatched(true);
3078 Buffer * doc_buffer = documentBufferView()
3079 ? &(documentBufferView()->buffer()) : 0;
3081 if (cmd.origin() == FuncRequest::TOC) {
3082 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
3083 // FIXME: do we need to pass a DispatchResult object here?
3084 toc->doDispatch(bv->cursor(), cmd);
3088 string const argument = to_utf8(cmd.argument());
3090 switch(cmd.action()) {
3091 case LFUN_BUFFER_CHILD_OPEN:
3092 openChildDocument(to_utf8(cmd.argument()));
3095 case LFUN_BUFFER_IMPORT:
3096 importDocument(to_utf8(cmd.argument()));
3099 case LFUN_BUFFER_EXPORT: {
3102 // GCC only sees strfwd.h when building merged
3103 if (::lyx::operator==(cmd.argument(), "custom")) {
3104 dispatch(FuncRequest(LFUN_DIALOG_SHOW, "sendto"), dr);
3107 #if QT_VERSION < 0x040400
3108 if (!doc_buffer->doExport(argument, false)) {
3110 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
3114 /* TODO/Review: Is it a problem to also export the children?
3115 See the update_unincluded flag */
3116 d.asyncBufferProcessing(argument,
3119 &GuiViewPrivate::exportAndDestroy,
3122 // TODO Inform user about success
3127 case LFUN_BUFFER_UPDATE: {
3128 d.asyncBufferProcessing(argument,
3131 &GuiViewPrivate::compileAndDestroy,
3136 case LFUN_BUFFER_VIEW: {
3137 d.asyncBufferProcessing(argument,
3139 _("Previewing ..."),
3140 &GuiViewPrivate::previewAndDestroy,
3145 case LFUN_MASTER_BUFFER_UPDATE: {
3146 d.asyncBufferProcessing(argument,
3147 (doc_buffer ? doc_buffer->masterBuffer() : 0),
3149 &GuiViewPrivate::compileAndDestroy,
3154 case LFUN_MASTER_BUFFER_VIEW: {
3155 d.asyncBufferProcessing(argument,
3156 (doc_buffer ? doc_buffer->masterBuffer() : 0),
3158 &GuiViewPrivate::previewAndDestroy,
3159 0, &Buffer::preview);
3162 case LFUN_BUFFER_SWITCH: {
3163 string const file_name = to_utf8(cmd.argument());
3164 if (!FileName::isAbsolute(file_name)) {
3166 dr.setMessage(_("Absolute filename expected."));
3170 Buffer * buffer = theBufferList().getBuffer(FileName(file_name));
3173 dr.setMessage(_("Document not loaded"));
3177 // Do we open or switch to the buffer in this view ?
3178 if (workArea(*buffer)
3179 || lyxrc.open_buffers_in_tabs || !documentBufferView()) {
3184 // Look for the buffer in other views
3185 QList<int> const ids = guiApp->viewIds();
3187 for (; i != ids.size(); ++i) {
3188 GuiView & gv = guiApp->view(ids[i]);
3189 if (gv.workArea(*buffer)) {
3190 gv.activateWindow();
3191 gv.setBuffer(buffer);
3196 // If necessary, open a new window as a last resort
3197 if (i == ids.size()) {
3198 lyx::dispatch(FuncRequest(LFUN_WINDOW_NEW));
3204 case LFUN_BUFFER_NEXT:
3205 gotoNextOrPreviousBuffer(NEXTBUFFER);
3208 case LFUN_BUFFER_PREVIOUS:
3209 gotoNextOrPreviousBuffer(PREVBUFFER);
3212 case LFUN_COMMAND_EXECUTE: {
3213 bool const show_it = cmd.argument() != "off";
3214 // FIXME: this is a hack, "minibuffer" should not be
3216 if (GuiToolbar * t = toolbar("minibuffer")) {
3217 t->setVisible(show_it);
3218 if (show_it && t->commandBuffer())
3219 t->commandBuffer()->setFocus();
3223 case LFUN_DROP_LAYOUTS_CHOICE:
3224 d.layout_->showPopup();
3227 case LFUN_MENU_OPEN:
3228 if (QMenu * menu = guiApp->menus().menu(toqstr(cmd.argument()), *this))
3229 menu->exec(QCursor::pos());
3232 case LFUN_FILE_INSERT:
3233 insertLyXFile(cmd.argument());
3236 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
3237 insertPlaintextFile(cmd.argument(), true);
3240 case LFUN_FILE_INSERT_PLAINTEXT:
3241 insertPlaintextFile(cmd.argument(), false);
3244 case LFUN_BUFFER_RELOAD: {
3245 LASSERT(doc_buffer, break);
3248 if (!doc_buffer->isClean()) {
3249 docstring const file =
3250 makeDisplayPath(doc_buffer->absFileName(), 20);
3251 docstring text = bformat(_("Any changes will be lost. "
3252 "Are you sure you want to revert to the saved version "
3253 "of the document %1$s?"), file);
3254 ret = Alert::prompt(_("Revert to saved document?"),
3255 text, 1, 1, _("&Revert"), _("&Cancel"));
3259 doc_buffer->markClean();
3260 reloadBuffer(*doc_buffer);
3261 dr.forceBufferUpdate();
3266 case LFUN_BUFFER_WRITE:
3267 LASSERT(doc_buffer, break);
3268 saveBuffer(*doc_buffer);
3271 case LFUN_BUFFER_WRITE_AS:
3272 LASSERT(doc_buffer, break);
3273 renameBuffer(*doc_buffer, cmd.argument());
3276 case LFUN_BUFFER_WRITE_ALL: {
3277 Buffer * first = theBufferList().first();
3280 message(_("Saving all documents..."));
3281 // We cannot use a for loop as the buffer list cycles.
3284 if (!b->isClean()) {
3286 LYXERR(Debug::ACTION, "Saved " << b->absFileName());
3288 b = theBufferList().next(b);
3289 } while (b != first);
3290 dr.setMessage(_("All documents saved."));
3294 case LFUN_BUFFER_CLOSE:
3298 case LFUN_BUFFER_CLOSE_ALL:
3302 case LFUN_TOOLBAR_TOGGLE: {
3303 string const name = cmd.getArg(0);
3304 if (GuiToolbar * t = toolbar(name))
3309 case LFUN_DIALOG_UPDATE: {
3310 string const name = to_utf8(cmd.argument());
3311 if (name == "prefs" || name == "document")
3312 updateDialog(name, string());
3313 else if (name == "paragraph")
3314 lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
3315 else if (currentBufferView()) {
3316 Inset * inset = currentBufferView()->editedInset(name);
3317 // Can only update a dialog connected to an existing inset
3319 // FIXME: get rid of this indirection; GuiView ask the inset
3320 // if he is kind enough to update itself...
3321 FuncRequest fr(LFUN_INSET_DIALOG_UPDATE, cmd.argument());
3322 //FIXME: pass DispatchResult here?
3323 inset->dispatch(currentBufferView()->cursor(), fr);
3329 case LFUN_DIALOG_TOGGLE: {
3330 FuncCode const func_code = isDialogVisible(cmd.getArg(0))
3331 ? LFUN_DIALOG_HIDE : LFUN_DIALOG_SHOW;
3332 dispatch(FuncRequest(func_code, cmd.argument()), dr);
3336 case LFUN_DIALOG_DISCONNECT_INSET:
3337 disconnectDialog(to_utf8(cmd.argument()));
3340 case LFUN_DIALOG_HIDE: {
3341 guiApp->hideDialogs(to_utf8(cmd.argument()), 0);
3345 case LFUN_DIALOG_SHOW: {
3346 string const name = cmd.getArg(0);
3347 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
3349 if (name == "character") {
3350 data = freefont2string();
3352 showDialog("character", data);
3353 } else if (name == "latexlog") {
3354 Buffer::LogType type;
3355 string const logfile = doc_buffer->logName(&type);
3357 case Buffer::latexlog:
3360 case Buffer::buildlog:
3364 data += Lexer::quoteString(logfile);
3365 showDialog("log", data);
3366 } else if (name == "vclog") {
3367 string const data = "vc " +
3368 Lexer::quoteString(doc_buffer->lyxvc().getLogFile());
3369 showDialog("log", data);
3370 } else if (name == "symbols") {
3371 data = bv->cursor().getEncoding()->name();
3373 showDialog("symbols", data);
3375 } else if (name == "prefs" && isFullScreen()) {
3376 lfunUiToggle("fullscreen");
3377 showDialog("prefs", data);
3379 showDialog(name, data);
3384 dr.setMessage(cmd.argument());
3387 case LFUN_UI_TOGGLE: {
3388 string arg = cmd.getArg(0);
3389 if (!lfunUiToggle(arg)) {
3390 docstring const msg = "ui-toggle " + _("%1$s unknown command!");
3391 dr.setMessage(bformat(msg, from_utf8(arg)));
3393 // Make sure the keyboard focus stays in the work area.
3398 case LFUN_SPLIT_VIEW: {
3399 LASSERT(doc_buffer, break);
3400 string const orientation = cmd.getArg(0);
3401 d.splitter_->setOrientation(orientation == "vertical"
3402 ? Qt::Vertical : Qt::Horizontal);
3403 TabWorkArea * twa = addTabWorkArea();
3404 GuiWorkArea * wa = twa->addWorkArea(*doc_buffer, *this);
3405 setCurrentWorkArea(wa);
3408 case LFUN_CLOSE_TAB_GROUP:
3409 if (TabWorkArea * twa = d.currentTabWorkArea()) {
3410 closeTabWorkArea(twa);
3411 d.current_work_area_ = 0;
3412 twa = d.currentTabWorkArea();
3413 // Switch to the next GuiWorkArea in the found TabWorkArea.
3415 // Make sure the work area is up to date.
3416 setCurrentWorkArea(twa->currentWorkArea());
3418 setCurrentWorkArea(0);
3423 case LFUN_COMPLETION_INLINE:
3424 if (d.current_work_area_)
3425 d.current_work_area_->completer().showInline();
3428 case LFUN_COMPLETION_POPUP:
3429 if (d.current_work_area_)
3430 d.current_work_area_->completer().showPopup();
3434 case LFUN_COMPLETION_COMPLETE:
3435 if (d.current_work_area_)
3436 d.current_work_area_->completer().tab();
3439 case LFUN_COMPLETION_CANCEL:
3440 if (d.current_work_area_) {
3441 if (d.current_work_area_->completer().popupVisible())
3442 d.current_work_area_->completer().hidePopup();
3444 d.current_work_area_->completer().hideInline();
3448 case LFUN_COMPLETION_ACCEPT:
3449 if (d.current_work_area_)
3450 d.current_work_area_->completer().activate();
3453 case LFUN_BUFFER_ZOOM_IN:
3454 case LFUN_BUFFER_ZOOM_OUT:
3455 if (cmd.argument().empty()) {
3456 if (cmd.action() == LFUN_BUFFER_ZOOM_IN)
3461 lyxrc.zoom += convert<int>(cmd.argument());
3463 if (lyxrc.zoom < 10)
3466 // The global QPixmapCache is used in GuiPainter to cache text
3467 // painting so we must reset it.
3468 QPixmapCache::clear();
3469 guiApp->fontLoader().update();
3470 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
3473 case LFUN_VC_REGISTER:
3474 case LFUN_VC_CHECK_IN:
3475 case LFUN_VC_CHECK_OUT:
3476 case LFUN_VC_REPO_UPDATE:
3477 case LFUN_VC_LOCKING_TOGGLE:
3478 case LFUN_VC_REVERT:
3479 case LFUN_VC_UNDO_LAST:
3480 case LFUN_VC_COMMAND:
3481 case LFUN_VC_COMPARE:
3482 dispatchVC(cmd, dr);
3485 case LFUN_SERVER_GOTO_FILE_ROW:
3486 goToFileRow(to_utf8(cmd.argument()));
3489 case LFUN_FORWARD_SEARCH: {
3490 Buffer const * doc_master = doc_buffer->masterBuffer();
3491 FileName const path(doc_master->temppath());
3492 string const texname = doc_master->isChild(doc_buffer)
3493 ? DocFileName(changeExtension(
3494 doc_buffer->absFileName(),
3495 "tex")).mangledFileName()
3496 : doc_buffer->latexName();
3497 string const mastername =
3498 removeExtension(doc_master->latexName());
3499 FileName const dviname(addName(path.absFileName(),
3500 addExtension(mastername, "dvi")));
3501 FileName const pdfname(addName(path.absFileName(),
3502 addExtension(mastername, "pdf")));
3503 if (!dviname.exists() && !pdfname.exists()) {
3504 dr.setMessage(_("Please, preview the document first."));
3507 string outname = dviname.onlyFileName();
3508 string command = lyxrc.forward_search_dvi;
3509 if (!dviname.exists() ||
3510 pdfname.lastModified() > dviname.lastModified()) {
3511 outname = pdfname.onlyFileName();
3512 command = lyxrc.forward_search_pdf;
3515 int row = doc_buffer->texrow().getRowFromIdPos(bv->cursor().paragraph().id(), bv->cursor().pos());
3516 LYXERR(Debug::ACTION, "Forward search: row:" << row
3517 << " id:" << bv->cursor().paragraph().id());
3518 if (!row || command.empty()) {
3519 dr.setMessage(_("Couldn't proceed."));
3522 string texrow = convert<string>(row);
3524 command = subst(command, "$$n", texrow);
3525 command = subst(command, "$$t", texname);
3526 command = subst(command, "$$o", outname);
3528 PathChanger p(path);
3530 one.startscript(Systemcall::DontWait, command);
3534 // The LFUN must be for one of BufferView, Buffer or Cursor;
3536 dispatchToBufferView(cmd, dr);
3540 // Part of automatic menu appearance feature.
3541 if (isFullScreen()) {
3542 if (menuBar()->isVisible() && lyxrc.full_screen_menubar)
3544 if (statusBar()->isVisible())
3545 statusBar()->hide();
3550 bool GuiView::lfunUiToggle(string const & ui_component)
3552 if (ui_component == "scrollbar") {
3553 // hide() is of no help
3554 if (d.current_work_area_->verticalScrollBarPolicy() ==
3555 Qt::ScrollBarAlwaysOff)
3557 d.current_work_area_->setVerticalScrollBarPolicy(
3558 Qt::ScrollBarAsNeeded);
3560 d.current_work_area_->setVerticalScrollBarPolicy(
3561 Qt::ScrollBarAlwaysOff);
3562 } else if (ui_component == "statusbar") {
3563 statusBar()->setVisible(!statusBar()->isVisible());
3564 } else if (ui_component == "menubar") {
3565 menuBar()->setVisible(!menuBar()->isVisible());
3567 #if QT_VERSION >= 0x040300
3568 if (ui_component == "frame") {
3570 getContentsMargins(&l, &t, &r, &b);
3571 //are the frames in default state?
3572 d.current_work_area_->setFrameStyle(QFrame::NoFrame);
3574 setContentsMargins(-2, -2, -2, -2);
3576 setContentsMargins(0, 0, 0, 0);
3580 if (ui_component == "fullscreen") {
3588 void GuiView::toggleFullScreen()
3590 if (isFullScreen()) {
3591 for (int i = 0; i != d.splitter_->count(); ++i)
3592 d.tabWorkArea(i)->setFullScreen(false);
3593 #if QT_VERSION >= 0x040300
3594 setContentsMargins(0, 0, 0, 0);
3596 setWindowState(windowState() ^ Qt::WindowFullScreen);
3599 statusBar()->show();
3602 hideDialogs("prefs", 0);
3603 for (int i = 0; i != d.splitter_->count(); ++i)
3604 d.tabWorkArea(i)->setFullScreen(true);
3605 #if QT_VERSION >= 0x040300
3606 setContentsMargins(-2, -2, -2, -2);
3609 setWindowState(windowState() ^ Qt::WindowFullScreen);
3610 statusBar()->hide();
3611 if (lyxrc.full_screen_menubar)
3613 if (lyxrc.full_screen_toolbars) {
3614 ToolbarMap::iterator end = d.toolbars_.end();
3615 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
3620 // give dialogs like the TOC a chance to adapt
3625 Buffer const * GuiView::updateInset(Inset const * inset)
3630 Buffer const * inset_buffer = &(inset->buffer());
3632 for (int i = 0; i != d.splitter_->count(); ++i) {
3633 GuiWorkArea * wa = d.tabWorkArea(i)->currentWorkArea();
3636 Buffer const * buffer = &(wa->bufferView().buffer());
3637 if (inset_buffer == buffer)
3638 wa->scheduleRedraw();
3640 return inset_buffer;
3644 void GuiView::restartCursor()
3646 /* When we move around, or type, it's nice to be able to see
3647 * the cursor immediately after the keypress.
3649 if (d.current_work_area_)
3650 d.current_work_area_->startBlinkingCursor();
3652 // Take this occasion to update the other GUI elements.
3658 void GuiView::updateCompletion(Cursor & cur, bool start, bool keep)
3660 if (d.current_work_area_)
3661 d.current_work_area_->completer().updateVisibility(cur, start, keep);
3666 // This list should be kept in sync with the list of insets in
3667 // src/insets/Inset.cpp. I.e., if a dialog goes with an inset, the
3668 // dialog should have the same name as the inset.
3669 // Changes should be also recorded in LFUN_DIALOG_SHOW doxygen
3670 // docs in LyXAction.cpp.
3672 char const * const dialognames[] = {
3674 "aboutlyx", "bibitem", "bibtex", "box", "branch", "changes", "character",
3675 "citation", "compare", "comparehistory", "document", "errorlist", "ert",
3676 "external", "file", "findreplace", "findreplaceadv", "float", "graphics",
3677 "href", "include", "index", "index_print", "info", "listings", "label", "line",
3678 "log", "mathdelimiter", "mathmatrix", "mathspace", "nomenclature",
3679 "nomencl_print", "note", "paragraph", "phantom", "prefs", "print", "ref",
3680 "sendto", "space", "spellchecker", "symbols", "tabular", "tabularcreate",
3681 "thesaurus", "texinfo", "toc", "view-source", "vspace", "wrap", "progress"};
3683 char const * const * const end_dialognames =
3684 dialognames + (sizeof(dialognames) / sizeof(char *));
3688 cmpCStr(char const * name) : name_(name) {}
3689 bool operator()(char const * other) {
3690 return strcmp(other, name_) == 0;
3697 bool isValidName(string const & name)
3699 return find_if(dialognames, end_dialognames,
3700 cmpCStr(name.c_str())) != end_dialognames;
3706 void GuiView::resetDialogs()
3708 // Make sure that no LFUN uses any GuiView.
3709 guiApp->setCurrentView(0);
3713 constructToolbars();
3714 guiApp->menus().fillMenuBar(menuBar(), this, false);
3715 d.layout_->updateContents(true);
3716 // Now update controls with current buffer.
3717 guiApp->setCurrentView(this);
3723 Dialog * GuiView::findOrBuild(string const & name, bool hide_it)
3725 if (!isValidName(name))
3728 map<string, DialogPtr>::iterator it = d.dialogs_.find(name);
3730 if (it != d.dialogs_.end()) {
3732 it->second->hideView();
3733 return it->second.get();
3736 Dialog * dialog = build(name);
3737 d.dialogs_[name].reset(dialog);
3738 if (lyxrc.allow_geometry_session)
3739 dialog->restoreSession();
3746 void GuiView::showDialog(string const & name, string const & data,
3749 triggerShowDialog(toqstr(name), toqstr(data), inset);
3753 void GuiView::doShowDialog(QString const & qname, QString const & qdata,
3759 const string name = fromqstr(qname);
3760 const string data = fromqstr(qdata);
3764 Dialog * dialog = findOrBuild(name, false);
3766 bool const visible = dialog->isVisibleView();
3767 dialog->showData(data);
3768 if (inset && currentBufferView())
3769 currentBufferView()->editInset(name, inset);
3770 // We only set the focus to the new dialog if it was not yet
3771 // visible in order not to change the existing previous behaviour
3773 // activateWindow is needed for floating dockviews
3774 dialog->asQWidget()->raise();
3775 dialog->asQWidget()->activateWindow();
3776 dialog->asQWidget()->setFocus();
3780 catch (ExceptionMessage const & ex) {
3788 bool GuiView::isDialogVisible(string const & name) const
3790 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3791 if (it == d.dialogs_.end())
3793 return it->second.get()->isVisibleView() && !it->second.get()->isClosing();
3797 void GuiView::hideDialog(string const & name, Inset * inset)
3799 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3800 if (it == d.dialogs_.end())
3804 if (!currentBufferView())
3806 if (inset != currentBufferView()->editedInset(name))
3810 Dialog * const dialog = it->second.get();
3811 if (dialog->isVisibleView())
3813 if (currentBufferView())
3814 currentBufferView()->editInset(name, 0);
3818 void GuiView::disconnectDialog(string const & name)
3820 if (!isValidName(name))
3822 if (currentBufferView())
3823 currentBufferView()->editInset(name, 0);
3827 void GuiView::hideAll() const
3829 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
3830 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3832 for(; it != end; ++it)
3833 it->second->hideView();
3837 void GuiView::updateDialogs()
3839 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
3840 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3842 for(; it != end; ++it) {
3843 Dialog * dialog = it->second.get();
3845 if (dialog->needBufferOpen() && !documentBufferView())
3846 hideDialog(fromqstr(dialog->name()), 0);
3847 else if (dialog->isVisibleView())
3848 dialog->checkStatus();
3855 Dialog * createDialog(GuiView & lv, string const & name);
3857 // will be replaced by a proper factory...
3858 Dialog * createGuiAbout(GuiView & lv);
3859 Dialog * createGuiBibtex(GuiView & lv);
3860 Dialog * createGuiChanges(GuiView & lv);
3861 Dialog * createGuiCharacter(GuiView & lv);
3862 Dialog * createGuiCitation(GuiView & lv);
3863 Dialog * createGuiCompare(GuiView & lv);
3864 Dialog * createGuiCompareHistory(GuiView & lv);
3865 Dialog * createGuiDelimiter(GuiView & lv);
3866 Dialog * createGuiDocument(GuiView & lv);
3867 Dialog * createGuiErrorList(GuiView & lv);
3868 Dialog * createGuiExternal(GuiView & lv);
3869 Dialog * createGuiGraphics(GuiView & lv);
3870 Dialog * createGuiInclude(GuiView & lv);
3871 Dialog * createGuiIndex(GuiView & lv);
3872 Dialog * createGuiListings(GuiView & lv);
3873 Dialog * createGuiLog(GuiView & lv);
3874 Dialog * createGuiMathMatrix(GuiView & lv);
3875 Dialog * createGuiNote(GuiView & lv);
3876 Dialog * createGuiParagraph(GuiView & lv);
3877 Dialog * createGuiPhantom(GuiView & lv);
3878 Dialog * createGuiPreferences(GuiView & lv);
3879 Dialog * createGuiPrint(GuiView & lv);
3880 Dialog * createGuiPrintindex(GuiView & lv);
3881 Dialog * createGuiRef(GuiView & lv);
3882 Dialog * createGuiSearch(GuiView & lv);
3883 Dialog * createGuiSearchAdv(GuiView & lv);
3884 Dialog * createGuiSendTo(GuiView & lv);
3885 Dialog * createGuiShowFile(GuiView & lv);
3886 Dialog * createGuiSpellchecker(GuiView & lv);
3887 Dialog * createGuiSymbols(GuiView & lv);
3888 Dialog * createGuiTabularCreate(GuiView & lv);
3889 Dialog * createGuiTexInfo(GuiView & lv);
3890 Dialog * createGuiToc(GuiView & lv);
3891 Dialog * createGuiThesaurus(GuiView & lv);
3892 Dialog * createGuiViewSource(GuiView & lv);
3893 Dialog * createGuiWrap(GuiView & lv);
3894 Dialog * createGuiProgressView(GuiView & lv);
3898 Dialog * GuiView::build(string const & name)
3900 LASSERT(isValidName(name), return 0);
3902 Dialog * dialog = createDialog(*this, name);
3906 if (name == "aboutlyx")
3907 return createGuiAbout(*this);
3908 if (name == "bibtex")
3909 return createGuiBibtex(*this);
3910 if (name == "changes")
3911 return createGuiChanges(*this);
3912 if (name == "character")
3913 return createGuiCharacter(*this);
3914 if (name == "citation")
3915 return createGuiCitation(*this);
3916 if (name == "compare")
3917 return createGuiCompare(*this);
3918 if (name == "comparehistory")
3919 return createGuiCompareHistory(*this);
3920 if (name == "document")
3921 return createGuiDocument(*this);
3922 if (name == "errorlist")
3923 return createGuiErrorList(*this);
3924 if (name == "external")
3925 return createGuiExternal(*this);
3927 return createGuiShowFile(*this);
3928 if (name == "findreplace")
3929 return createGuiSearch(*this);
3930 if (name == "findreplaceadv")
3931 return createGuiSearchAdv(*this);
3932 if (name == "graphics")
3933 return createGuiGraphics(*this);
3934 if (name == "include")
3935 return createGuiInclude(*this);
3936 if (name == "index")
3937 return createGuiIndex(*this);
3938 if (name == "index_print")
3939 return createGuiPrintindex(*this);
3940 if (name == "listings")
3941 return createGuiListings(*this);
3943 return createGuiLog(*this);
3944 if (name == "mathdelimiter")
3945 return createGuiDelimiter(*this);
3946 if (name == "mathmatrix")
3947 return createGuiMathMatrix(*this);
3949 return createGuiNote(*this);
3950 if (name == "paragraph")
3951 return createGuiParagraph(*this);
3952 if (name == "phantom")
3953 return createGuiPhantom(*this);
3954 if (name == "prefs")
3955 return createGuiPreferences(*this);
3956 if (name == "print")
3957 return createGuiPrint(*this);
3959 return createGuiRef(*this);
3960 if (name == "sendto")
3961 return createGuiSendTo(*this);
3962 if (name == "spellchecker")
3963 return createGuiSpellchecker(*this);
3964 if (name == "symbols")
3965 return createGuiSymbols(*this);
3966 if (name == "tabularcreate")
3967 return createGuiTabularCreate(*this);
3968 if (name == "texinfo")
3969 return createGuiTexInfo(*this);
3970 if (name == "thesaurus")
3971 return createGuiThesaurus(*this);
3973 return createGuiToc(*this);
3974 if (name == "view-source")
3975 return createGuiViewSource(*this);
3977 return createGuiWrap(*this);
3978 if (name == "progress")
3979 return createGuiProgressView(*this);
3985 } // namespace frontend
3988 #include "moc_GuiView.cpp"