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 ErrorList & el = from_master ?
1429 bv->buffer().masterBuffer()->errorList(error_type) :
1430 bv->buffer().errorList(error_type);
1434 string data = error_type;
1436 data = "from_master|" + error_type;
1437 showDialog("errorlist", data);
1441 void GuiView::updateTocItem(string const & type, DocIterator const & dit)
1443 d.toc_models_.updateItem(toqstr(type), dit);
1447 void GuiView::structureChanged()
1449 d.toc_models_.reset(documentBufferView());
1450 // Navigator needs more than a simple update in this case. It needs to be
1452 updateDialog("toc", "");
1456 void GuiView::updateDialog(string const & name, string const & data)
1458 if (!isDialogVisible(name))
1461 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
1462 if (it == d.dialogs_.end())
1465 Dialog * const dialog = it->second.get();
1466 if (dialog->isVisibleView())
1467 dialog->initialiseParams(data);
1471 BufferView * GuiView::documentBufferView()
1473 return currentMainWorkArea()
1474 ? ¤tMainWorkArea()->bufferView()
1479 BufferView const * GuiView::documentBufferView() const
1481 return currentMainWorkArea()
1482 ? ¤tMainWorkArea()->bufferView()
1487 BufferView * GuiView::currentBufferView()
1489 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1493 BufferView const * GuiView::currentBufferView() const
1495 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1499 #if (QT_VERSION >= 0x040400)
1500 docstring GuiView::GuiViewPrivate::autosaveAndDestroy(
1501 Buffer const * orig, Buffer * buffer)
1503 bool const success = buffer->autoSave();
1505 busyBuffers.remove(orig);
1507 ? _("Automatic save done.")
1508 : _("Automatic save failed!");
1513 void GuiView::autoSave()
1515 LYXERR(Debug::INFO, "Running autoSave()");
1517 Buffer * buffer = documentBufferView()
1518 ? &documentBufferView()->buffer() : 0;
1520 resetAutosaveTimers();
1524 #if (QT_VERSION >= 0x040400)
1525 GuiViewPrivate::busyBuffers.insert(buffer);
1526 QFuture<docstring> f = QtConcurrent::run(GuiViewPrivate::autosaveAndDestroy,
1527 buffer, buffer->clone());
1528 d.autosave_watcher_.setFuture(f);
1532 resetAutosaveTimers();
1536 void GuiView::resetAutosaveTimers()
1539 d.autosave_timeout_.restart();
1543 bool GuiView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1546 Buffer * buf = currentBufferView()
1547 ? ¤tBufferView()->buffer() : 0;
1548 Buffer * doc_buffer = documentBufferView()
1549 ? &(documentBufferView()->buffer()) : 0;
1551 // Check whether we need a buffer
1552 if (!lyxaction.funcHasFlag(cmd.action(), LyXAction::NoBuffer) && !buf) {
1553 // no, exit directly
1554 flag.message(from_utf8(N_("Command not allowed with"
1555 "out any document open")));
1556 flag.setEnabled(false);
1560 if (cmd.origin() == FuncRequest::TOC) {
1561 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
1562 if (!toc || !toc->getStatus(documentBufferView()->cursor(), cmd, flag))
1563 flag.setEnabled(false);
1567 switch(cmd.action()) {
1568 case LFUN_BUFFER_IMPORT:
1571 case LFUN_MASTER_BUFFER_UPDATE:
1572 case LFUN_MASTER_BUFFER_VIEW:
1573 enable = doc_buffer && doc_buffer->parent() != 0
1574 && !d.processing_thread_watcher_.isRunning();
1577 case LFUN_BUFFER_UPDATE:
1578 case LFUN_BUFFER_VIEW: {
1579 if (!doc_buffer || d.processing_thread_watcher_.isRunning()) {
1583 string format = to_utf8(cmd.argument());
1584 if (cmd.argument().empty())
1585 format = doc_buffer->getDefaultOutputFormat();
1586 enable = doc_buffer->isExportableFormat(format);
1590 case LFUN_BUFFER_RELOAD:
1591 enable = doc_buffer && !doc_buffer->isUnnamed()
1592 && doc_buffer->fileName().exists()
1593 && (!doc_buffer->isClean()
1594 || doc_buffer->isExternallyModified(Buffer::timestamp_method));
1597 case LFUN_BUFFER_CHILD_OPEN:
1598 enable = doc_buffer;
1601 case LFUN_BUFFER_WRITE:
1602 enable = doc_buffer && (doc_buffer->isUnnamed() || !doc_buffer->isClean());
1605 //FIXME: This LFUN should be moved to GuiApplication.
1606 case LFUN_BUFFER_WRITE_ALL: {
1607 // We enable the command only if there are some modified buffers
1608 Buffer * first = theBufferList().first();
1613 // We cannot use a for loop as the buffer list is a cycle.
1615 if (!b->isClean()) {
1619 b = theBufferList().next(b);
1620 } while (b != first);
1624 case LFUN_BUFFER_WRITE_AS:
1625 enable = doc_buffer;
1628 case LFUN_BUFFER_CLOSE:
1629 enable = doc_buffer;
1632 case LFUN_BUFFER_CLOSE_ALL:
1633 enable = theBufferList().last() != theBufferList().first();
1636 case LFUN_SPLIT_VIEW:
1637 if (cmd.getArg(0) == "vertical")
1638 enable = doc_buffer && (d.splitter_->count() == 1 ||
1639 d.splitter_->orientation() == Qt::Vertical);
1641 enable = doc_buffer && (d.splitter_->count() == 1 ||
1642 d.splitter_->orientation() == Qt::Horizontal);
1645 case LFUN_CLOSE_TAB_GROUP:
1646 enable = d.currentTabWorkArea();
1649 case LFUN_TOOLBAR_TOGGLE: {
1650 string const name = cmd.getArg(0);
1651 if (GuiToolbar * t = toolbar(name))
1652 flag.setOnOff(t->isVisible());
1655 docstring const msg =
1656 bformat(_("Unknown toolbar \"%1$s\""), from_utf8(name));
1662 case LFUN_DROP_LAYOUTS_CHOICE:
1666 case LFUN_UI_TOGGLE:
1667 flag.setOnOff(isFullScreen());
1670 case LFUN_DIALOG_DISCONNECT_INSET:
1673 case LFUN_DIALOG_HIDE:
1674 // FIXME: should we check if the dialog is shown?
1677 case LFUN_DIALOG_TOGGLE:
1678 flag.setOnOff(isDialogVisible(cmd.getArg(0)));
1679 // fall through to set "enable"
1680 case LFUN_DIALOG_SHOW: {
1681 string const name = cmd.getArg(0);
1683 enable = name == "aboutlyx"
1684 || name == "file" //FIXME: should be removed.
1686 || name == "texinfo"
1687 || name == "progress"
1688 || name == "compare";
1689 else if (name == "print")
1690 enable = doc_buffer->isExportable("dvi")
1691 && lyxrc.print_command != "none";
1692 else if (name == "character" || name == "symbols") {
1693 if (!buf || buf->isReadonly())
1696 Cursor const & cur = currentBufferView()->cursor();
1697 enable = !(cur.inTexted() && cur.paragraph().isPassThru());
1700 else if (name == "latexlog")
1701 enable = FileName(doc_buffer->logName()).isReadableFile();
1702 else if (name == "spellchecker")
1703 enable = theSpellChecker() && !doc_buffer->isReadonly();
1704 else if (name == "vclog")
1705 enable = doc_buffer->lyxvc().inUse();
1709 case LFUN_DIALOG_UPDATE: {
1710 string const name = cmd.getArg(0);
1712 enable = name == "prefs";
1716 case LFUN_COMMAND_EXECUTE:
1718 case LFUN_MENU_OPEN:
1719 // Nothing to check.
1722 case LFUN_COMPLETION_INLINE:
1723 if (!d.current_work_area_
1724 || !d.current_work_area_->completer().inlinePossible(
1725 currentBufferView()->cursor()))
1729 case LFUN_COMPLETION_POPUP:
1730 if (!d.current_work_area_
1731 || !d.current_work_area_->completer().popupPossible(
1732 currentBufferView()->cursor()))
1736 case LFUN_COMPLETION_COMPLETE:
1737 if (!d.current_work_area_
1738 || !d.current_work_area_->completer().inlinePossible(
1739 currentBufferView()->cursor()))
1743 case LFUN_COMPLETION_ACCEPT:
1744 if (!d.current_work_area_
1745 || (!d.current_work_area_->completer().popupVisible()
1746 && !d.current_work_area_->completer().inlineVisible()
1747 && !d.current_work_area_->completer().completionAvailable()))
1751 case LFUN_COMPLETION_CANCEL:
1752 if (!d.current_work_area_
1753 || (!d.current_work_area_->completer().popupVisible()
1754 && !d.current_work_area_->completer().inlineVisible()))
1758 case LFUN_BUFFER_ZOOM_OUT:
1759 enable = doc_buffer && lyxrc.zoom > 10;
1762 case LFUN_BUFFER_ZOOM_IN:
1763 enable = doc_buffer;
1766 case LFUN_BUFFER_NEXT:
1767 case LFUN_BUFFER_PREVIOUS:
1768 // FIXME: should we check is there is an previous or next buffer?
1770 case LFUN_BUFFER_SWITCH:
1771 // toggle on the current buffer, but do not toggle off
1772 // the other ones (is that a good idea?)
1774 && to_utf8(cmd.argument()) == doc_buffer->absFileName())
1775 flag.setOnOff(true);
1778 case LFUN_VC_REGISTER:
1779 enable = doc_buffer && !doc_buffer->lyxvc().inUse();
1781 case LFUN_VC_CHECK_IN:
1782 enable = doc_buffer && doc_buffer->lyxvc().checkInEnabled();
1784 case LFUN_VC_CHECK_OUT:
1785 enable = doc_buffer && doc_buffer->lyxvc().checkOutEnabled();
1787 case LFUN_VC_LOCKING_TOGGLE:
1788 enable = doc_buffer && !doc_buffer->isReadonly()
1789 && doc_buffer->lyxvc().lockingToggleEnabled();
1790 flag.setOnOff(enable && doc_buffer->lyxvc().locking());
1792 case LFUN_VC_REVERT:
1793 enable = doc_buffer && doc_buffer->lyxvc().inUse() && !doc_buffer->isReadonly();
1795 case LFUN_VC_UNDO_LAST:
1796 enable = doc_buffer && doc_buffer->lyxvc().undoLastEnabled();
1798 case LFUN_VC_REPO_UPDATE:
1799 enable = doc_buffer && doc_buffer->lyxvc().repoUpdateEnabled();
1801 case LFUN_VC_COMMAND: {
1802 if (cmd.argument().empty())
1804 if (!doc_buffer && contains(cmd.getArg(0), 'D'))
1808 case LFUN_VC_COMPARE:
1809 enable = doc_buffer && doc_buffer->lyxvc().prepareFileRevisionEnabled();
1812 case LFUN_SERVER_GOTO_FILE_ROW:
1814 case LFUN_FORWARD_SEARCH:
1815 enable = !(lyxrc.forward_search_dvi.empty() && lyxrc.forward_search_pdf.empty());
1823 flag.setEnabled(false);
1829 static FileName selectTemplateFile()
1831 FileDialog dlg(qt_("Select template file"));
1832 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1833 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
1835 FileDialog::Result result = dlg.open(toqstr(lyxrc.template_path),
1836 QStringList(qt_("LyX Documents (*.lyx)")));
1838 if (result.first == FileDialog::Later)
1840 if (result.second.isEmpty())
1842 return FileName(fromqstr(result.second));
1846 Buffer * GuiView::loadDocument(FileName const & filename, bool tolastfiles)
1850 Buffer * newBuffer = 0;
1852 newBuffer = checkAndLoadLyXFile(filename);
1853 } catch (ExceptionMessage const & e) {
1859 message(_("Document not loaded."));
1864 newBuffer->errors("Parse");
1865 setBuffer(newBuffer);
1868 theSession().lastFiles().add(filename);
1875 void GuiView::openDocument(string const & fname)
1877 string initpath = lyxrc.document_path;
1879 if (documentBufferView()) {
1880 string const trypath = documentBufferView()->buffer().filePath();
1881 // If directory is writeable, use this as default.
1882 if (FileName(trypath).isDirWritable())
1888 if (fname.empty()) {
1889 FileDialog dlg(qt_("Select document to open"), LFUN_FILE_OPEN);
1890 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1891 dlg.setButton2(qt_("Examples|#E#e"),
1892 toqstr(addPath(package().system_support().absFileName(), "examples")));
1894 QStringList filter(qt_("LyX Documents (*.lyx)"));
1895 filter << qt_("LyX-1.3.x Documents (*.lyx13)")
1896 << qt_("LyX-1.4.x Documents (*.lyx14)")
1897 << qt_("LyX-1.5.x Documents (*.lyx15)")
1898 << qt_("LyX-1.6.x Documents (*.lyx16)");
1899 FileDialog::Result result =
1900 dlg.open(toqstr(initpath), filter);
1902 if (result.first == FileDialog::Later)
1905 filename = fromqstr(result.second);
1907 // check selected filename
1908 if (filename.empty()) {
1909 message(_("Canceled."));
1915 // get absolute path of file and add ".lyx" to the filename if
1917 FileName const fullname =
1918 fileSearch(string(), filename, "lyx", support::may_not_exist);
1919 if (!fullname.empty())
1920 filename = fullname.absFileName();
1922 if (!fullname.onlyPath().isDirectory()) {
1923 Alert::warning(_("Invalid filename"),
1924 bformat(_("The directory in the given path\n%1$s\ndoes not exist."),
1925 from_utf8(fullname.absFileName())));
1929 // if the file doesn't exist and isn't already open (bug 6645),
1930 // let the user create one
1931 if (!fullname.exists() && !theBufferList().exists(fullname)) {
1932 // the user specifically chose this name. Believe him.
1933 Buffer * const b = newFile(filename, string(), true);
1939 docstring const disp_fn = makeDisplayPath(filename);
1940 message(bformat(_("Opening document %1$s..."), disp_fn));
1943 Buffer * buf = loadDocument(fullname);
1945 str2 = bformat(_("Document %1$s opened."), disp_fn);
1946 if (buf->lyxvc().inUse())
1947 str2 += " " + from_utf8(buf->lyxvc().versionString()) +
1948 " " + _("Version control detected.");
1950 str2 = bformat(_("Could not open document %1$s"), disp_fn);
1955 // FIXME: clean that
1956 static bool import(GuiView * lv, FileName const & filename,
1957 string const & format, ErrorList & errorList)
1959 FileName const lyxfile(support::changeExtension(filename.absFileName(), ".lyx"));
1961 string loader_format;
1962 vector<string> loaders = theConverters().loaders();
1963 if (find(loaders.begin(), loaders.end(), format) == loaders.end()) {
1964 for (vector<string>::const_iterator it = loaders.begin();
1965 it != loaders.end(); ++it) {
1966 if (!theConverters().isReachable(format, *it))
1969 string const tofile =
1970 support::changeExtension(filename.absFileName(),
1971 formats.extension(*it));
1972 if (!theConverters().convert(0, filename, FileName(tofile),
1973 filename, format, *it, errorList))
1975 loader_format = *it;
1978 if (loader_format.empty()) {
1979 frontend::Alert::error(_("Couldn't import file"),
1980 bformat(_("No information for importing the format %1$s."),
1981 formats.prettyName(format)));
1985 loader_format = format;
1987 if (loader_format == "lyx") {
1988 Buffer * buf = lv->loadDocument(lyxfile);
1992 Buffer * const b = newFile(lyxfile.absFileName(), string(), true);
1996 bool as_paragraphs = loader_format == "textparagraph";
1997 string filename2 = (loader_format == format) ? filename.absFileName()
1998 : support::changeExtension(filename.absFileName(),
1999 formats.extension(loader_format));
2000 lv->currentBufferView()->insertPlaintextFile(FileName(filename2),
2002 guiApp->setCurrentView(lv);
2003 lyx::dispatch(FuncRequest(LFUN_MARK_OFF));
2010 void GuiView::importDocument(string const & argument)
2013 string filename = split(argument, format, ' ');
2015 LYXERR(Debug::INFO, format << " file: " << filename);
2017 // need user interaction
2018 if (filename.empty()) {
2019 string initpath = lyxrc.document_path;
2020 if (documentBufferView()) {
2021 string const trypath = documentBufferView()->buffer().filePath();
2022 // If directory is writeable, use this as default.
2023 if (FileName(trypath).isDirWritable())
2027 docstring const text = bformat(_("Select %1$s file to import"),
2028 formats.prettyName(format));
2030 FileDialog dlg(toqstr(text), LFUN_BUFFER_IMPORT);
2031 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2032 dlg.setButton2(qt_("Examples|#E#e"),
2033 toqstr(addPath(package().system_support().absFileName(), "examples")));
2035 docstring filter = formats.prettyName(format);
2038 filter += from_utf8(formats.extension(format));
2041 FileDialog::Result result =
2042 dlg.open(toqstr(initpath), fileFilters(toqstr(filter)));
2044 if (result.first == FileDialog::Later)
2047 filename = fromqstr(result.second);
2049 // check selected filename
2050 if (filename.empty())
2051 message(_("Canceled."));
2054 if (filename.empty())
2057 // get absolute path of file
2058 FileName const fullname(support::makeAbsPath(filename));
2060 FileName const lyxfile(support::changeExtension(fullname.absFileName(), ".lyx"));
2062 // Check if the document already is open
2063 Buffer * buf = theBufferList().getBuffer(lyxfile);
2066 if (!closeBuffer()) {
2067 message(_("Canceled."));
2072 docstring const displaypath = makeDisplayPath(lyxfile.absFileName(), 30);
2074 // if the file exists already, and we didn't do
2075 // -i lyx thefile.lyx, warn
2076 if (lyxfile.exists() && fullname != lyxfile) {
2078 docstring text = bformat(_("The document %1$s already exists.\n\n"
2079 "Do you want to overwrite that document?"), displaypath);
2080 int const ret = Alert::prompt(_("Overwrite document?"),
2081 text, 0, 1, _("&Overwrite"), _("&Cancel"));
2084 message(_("Canceled."));
2089 message(bformat(_("Importing %1$s..."), displaypath));
2090 ErrorList errorList;
2091 if (import(this, fullname, format, errorList))
2092 message(_("imported."));
2094 message(_("file not imported!"));
2096 // FIXME (Abdel 12/08/06): Is there a need to display the error list here?
2100 void GuiView::newDocument(string const & filename, bool from_template)
2102 FileName initpath(lyxrc.document_path);
2103 if (documentBufferView()) {
2104 FileName const trypath(documentBufferView()->buffer().filePath());
2105 // If directory is writeable, use this as default.
2106 if (trypath.isDirWritable())
2110 string templatefile;
2111 if (from_template) {
2112 templatefile = selectTemplateFile().absFileName();
2113 if (templatefile.empty())
2118 if (filename.empty())
2119 b = newUnnamedFile(initpath, to_utf8(_("newfile")), templatefile);
2121 b = newFile(filename, templatefile, true);
2126 // If no new document could be created, it is unsure
2127 // whether there is a valid BufferView.
2128 if (currentBufferView())
2129 // Ensure the cursor is correctly positioned on screen.
2130 currentBufferView()->showCursor();
2134 void GuiView::insertLyXFile(docstring const & fname)
2136 BufferView * bv = documentBufferView();
2141 FileName filename(to_utf8(fname));
2142 if (filename.empty()) {
2143 // Launch a file browser
2145 string initpath = lyxrc.document_path;
2146 string const trypath = bv->buffer().filePath();
2147 // If directory is writeable, use this as default.
2148 if (FileName(trypath).isDirWritable())
2152 FileDialog dlg(qt_("Select LyX document to insert"), LFUN_FILE_INSERT);
2153 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2154 dlg.setButton2(qt_("Examples|#E#e"),
2155 toqstr(addPath(package().system_support().absFileName(),
2158 FileDialog::Result result = dlg.open(toqstr(initpath),
2159 QStringList(qt_("LyX Documents (*.lyx)")));
2161 if (result.first == FileDialog::Later)
2165 filename.set(fromqstr(result.second));
2167 // check selected filename
2168 if (filename.empty()) {
2169 // emit message signal.
2170 message(_("Canceled."));
2175 bv->insertLyXFile(filename);
2176 bv->buffer().errors("Parse");
2180 void GuiView::insertPlaintextFile(docstring const & fname,
2183 BufferView * bv = documentBufferView();
2187 if (!fname.empty() && !FileName::isAbsolute(to_utf8(fname))) {
2188 message(_("Absolute filename expected."));
2193 FileName filename(to_utf8(fname));
2195 if (!filename.empty()) {
2196 bv->insertPlaintextFile(filename, asParagraph);
2200 FileDialog dlg(qt_("Select file to insert"), (asParagraph ?
2201 LFUN_FILE_INSERT_PLAINTEXT_PARA : LFUN_FILE_INSERT_PLAINTEXT));
2203 FileDialog::Result result = dlg.open(toqstr(bv->buffer().filePath()),
2204 QStringList(qt_("All Files (*)")));
2206 if (result.first == FileDialog::Later)
2210 filename.set(fromqstr(result.second));
2212 // check selected filename
2213 if (filename.empty()) {
2214 // emit message signal.
2215 message(_("Canceled."));
2219 bv->insertPlaintextFile(filename, asParagraph);
2223 bool GuiView::renameBuffer(Buffer & b, docstring const & newname)
2225 FileName fname = b.fileName();
2226 FileName const oldname = fname;
2228 if (!newname.empty()) {
2230 fname = support::makeAbsPath(to_utf8(newname), oldname.onlyPath().absFileName());
2232 // Switch to this Buffer.
2235 // No argument? Ask user through dialog.
2237 FileDialog dlg(qt_("Choose a filename to save document as"),
2238 LFUN_BUFFER_WRITE_AS);
2239 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2240 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
2242 if (!isLyXFileName(fname.absFileName()))
2243 fname.changeExtension(".lyx");
2245 FileDialog::Result result =
2246 dlg.save(toqstr(fname.onlyPath().absFileName()),
2247 QStringList(qt_("LyX Documents (*.lyx)")),
2248 toqstr(fname.onlyFileName()));
2250 if (result.first == FileDialog::Later)
2253 fname.set(fromqstr(result.second));
2258 if (!isLyXFileName(fname.absFileName()))
2259 fname.changeExtension(".lyx");
2262 // fname is now the new Buffer location.
2263 if (FileName(fname).exists()) {
2264 docstring const file = makeDisplayPath(fname.absFileName(), 30);
2265 docstring text = bformat(_("The document %1$s already "
2266 "exists.\n\nDo you want to "
2267 "overwrite that document?"),
2269 int const ret = Alert::prompt(_("Overwrite document?"),
2270 text, 0, 2, _("&Overwrite"), _("&Rename"), _("&Cancel"));
2273 case 1: return renameBuffer(b, docstring());
2274 case 2: return false;
2278 return saveBuffer(b, fname);
2282 bool GuiView::saveBuffer(Buffer & b) {
2283 return saveBuffer(b, FileName());
2287 bool GuiView::saveBuffer(Buffer & b, FileName const & fn)
2289 if (workArea(b) && workArea(b)->inDialogMode())
2292 if (fn.empty() && b.isUnnamed())
2293 return renameBuffer(b, docstring());
2299 success = b.saveAs(fn);
2302 theSession().lastFiles().add(b.fileName());
2306 // Switch to this Buffer.
2309 // FIXME: we don't tell the user *WHY* the save failed !!
2310 docstring const file = makeDisplayPath(b.absFileName(), 30);
2311 docstring text = bformat(_("The document %1$s could not be saved.\n\n"
2312 "Do you want to rename the document and "
2313 "try again?"), file);
2314 int const ret = Alert::prompt(_("Rename and save?"),
2315 text, 0, 2, _("&Rename"), _("&Retry"), _("&Cancel"));
2318 if (!renameBuffer(b, docstring()))
2327 return saveBuffer(b);
2331 bool GuiView::hideWorkArea(GuiWorkArea * wa)
2333 return closeWorkArea(wa, false);
2337 bool GuiView::closeWorkArea(GuiWorkArea * wa)
2339 Buffer & buf = wa->bufferView().buffer();
2340 return closeWorkArea(wa, !buf.parent());
2344 bool GuiView::closeBuffer()
2346 GuiWorkArea * wa = currentMainWorkArea();
2347 setCurrentWorkArea(wa);
2348 Buffer & buf = wa->bufferView().buffer();
2349 return wa && closeWorkArea(wa, !buf.parent());
2353 void GuiView::writeSession() const {
2354 GuiWorkArea const * active_wa = currentMainWorkArea();
2355 for (int i = 0; i < d.splitter_->count(); ++i) {
2356 TabWorkArea * twa = d.tabWorkArea(i);
2357 for (int j = 0; j < twa->count(); ++j) {
2358 GuiWorkArea * wa = static_cast<GuiWorkArea *>(twa->widget(j));
2359 Buffer & buf = wa->bufferView().buffer();
2360 theSession().lastOpened().add(buf.fileName(), wa == active_wa);
2366 bool GuiView::closeBufferAll()
2368 // Close the workareas in all other views
2369 QList<int> const ids = guiApp->viewIds();
2370 for (int i = 0; i != ids.size(); ++i) {
2371 if (id_ != ids[i] && !guiApp->view(ids[i]).closeWorkAreaAll())
2375 // Close our own workareas
2376 if (!closeWorkAreaAll())
2379 // Now close the hidden buffers. We prevent hidden buffers from being
2380 // dirty, so we can just close them.
2381 theBufferList().closeAll();
2386 bool GuiView::closeWorkAreaAll()
2388 setCurrentWorkArea(currentMainWorkArea());
2390 // We might be in a situation that there is still a tabWorkArea, but
2391 // there are no tabs anymore. This can happen when we get here after a
2392 // TabWorkArea::lastWorkAreaRemoved() signal. Therefore we count how
2393 // many TabWorkArea's have no documents anymore.
2396 // We have to call count() each time, because it can happen that
2397 // more than one splitter will disappear in one iteration (bug 5998).
2398 for (; d.splitter_->count() > empty_twa; ) {
2399 TabWorkArea * twa = d.tabWorkArea(empty_twa);
2401 if (twa->count() == 0)
2404 setCurrentWorkArea(twa->currentWorkArea());
2405 if (!closeTabWorkArea(twa))
2413 bool GuiView::closeWorkArea(GuiWorkArea * wa, bool close_buffer)
2418 Buffer & buf = wa->bufferView().buffer();
2420 if (close_buffer && GuiViewPrivate::busyBuffers.contains(&buf)) {
2421 Alert::warning(_("Close document"),
2422 _("Document could not be closed because it is being processed by LyX."));
2427 return closeBuffer(buf);
2429 if (!inMultiTabs(wa))
2430 if (!saveBufferIfNeeded(buf, true))
2438 bool GuiView::closeBuffer(Buffer & buf)
2440 // If we are in a close_event all children will be closed in some time,
2441 // so no need to do it here. This will ensure that the children end up
2442 // in the session file in the correct order. If we close the master
2443 // buffer, we can close or release the child buffers here too.
2444 bool success = true;
2446 ListOfBuffers clist = buf.getChildren();
2447 ListOfBuffers::const_iterator it = clist.begin();
2448 ListOfBuffers::const_iterator const bend = clist.end();
2449 for (; it != bend; ++it) {
2450 // If a child is dirty, do not close
2451 // without user intervention
2452 //FIXME: should we look in other tabworkareas?
2453 Buffer * child_buf = *it;
2454 GuiWorkArea * child_wa = workArea(*child_buf);
2456 if (!closeWorkArea(child_wa, true)) {
2461 theBufferList().releaseChild(&buf, child_buf);
2465 // goto bookmark to update bookmark pit.
2466 //FIXME: we should update only the bookmarks related to this buffer!
2467 LYXERR(Debug::DEBUG, "GuiView::closeBuffer()");
2468 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
2469 guiApp->gotoBookmark(i+1, false, false);
2471 if (saveBufferIfNeeded(buf, false)) {
2472 buf.removeAutosaveFile();
2473 theBufferList().release(&buf);
2477 // open all children again to avoid a crash because of dangling
2478 // pointers (bug 6603)
2484 bool GuiView::closeTabWorkArea(TabWorkArea * twa)
2486 while (twa == d.currentTabWorkArea()) {
2487 twa->setCurrentIndex(twa->count()-1);
2489 GuiWorkArea * wa = twa->currentWorkArea();
2490 Buffer & b = wa->bufferView().buffer();
2492 // We only want to close the buffer if the same buffer is not visible
2493 // in another view, and if this is not a child and if we are closing
2494 // a view (not a tabgroup).
2495 bool const close_buffer =
2496 !inOtherView(b) && !b.parent() && closing_;
2498 if (!closeWorkArea(wa, close_buffer))
2505 bool GuiView::saveBufferIfNeeded(Buffer & buf, bool hiding)
2507 if (buf.isClean() || buf.paragraphs().empty())
2510 // Switch to this Buffer.
2515 if (buf.isUnnamed())
2516 file = from_utf8(buf.fileName().onlyFileName());
2518 file = buf.fileName().displayName(30);
2520 // Bring this window to top before asking questions.
2525 if (hiding && buf.isUnnamed()) {
2526 docstring const text = bformat(_("The document %1$s has not been "
2527 "saved yet.\n\nDo you want to save "
2528 "the document?"), file);
2529 ret = Alert::prompt(_("Save new document?"),
2530 text, 0, 1, _("&Save"), _("&Cancel"));
2534 docstring const text = bformat(_("The document %1$s has unsaved changes."
2535 "\n\nDo you want to save the document or discard the changes?"), file);
2536 ret = Alert::prompt(_("Save changed document?"),
2537 text, 0, 2, _("&Save"), _("&Discard"), _("&Cancel"));
2542 if (!saveBuffer(buf))
2546 // If we crash after this we could have no autosave file
2547 // but I guess this is really improbable (Jug).
2548 // Sometimes improbable things happen:
2549 // - see bug http://www.lyx.org/trac/ticket/6587 (ps)
2550 // buf.removeAutosaveFile();
2552 // revert all changes
2563 bool GuiView::inMultiTabs(GuiWorkArea * wa)
2565 Buffer & buf = wa->bufferView().buffer();
2567 for (int i = 0; i != d.splitter_->count(); ++i) {
2568 GuiWorkArea * wa_ = d.tabWorkArea(i)->workArea(buf);
2569 if (wa_ && wa_ != wa)
2572 return inOtherView(buf);
2576 bool GuiView::inOtherView(Buffer & buf)
2578 QList<int> const ids = guiApp->viewIds();
2580 for (int i = 0; i != ids.size(); ++i) {
2584 if (guiApp->view(ids[i]).workArea(buf))
2591 void GuiView::gotoNextOrPreviousBuffer(NextOrPrevious np)
2593 if (!documentBufferView())
2596 if (TabWorkArea * twa = d.currentTabWorkArea()) {
2597 Buffer * const curbuf = &documentBufferView()->buffer();
2598 int nwa = twa->count();
2599 for (int i = 0; i < nwa; ++i) {
2600 if (&workArea(i)->bufferView().buffer() == curbuf) {
2602 if (np == NEXTBUFFER)
2603 next_index = (i == nwa - 1 ? 0 : i + 1);
2605 next_index = (i == 0 ? nwa - 1 : i - 1);
2606 setBuffer(&workArea(next_index)->bufferView().buffer());
2614 /// make sure the document is saved
2615 static bool ensureBufferClean(Buffer * buffer)
2617 LASSERT(buffer, return false);
2618 if (buffer->isClean() && !buffer->isUnnamed())
2621 docstring const file = buffer->fileName().displayName(30);
2624 if (!buffer->isUnnamed()) {
2625 text = bformat(_("The document %1$s has unsaved "
2626 "changes.\n\nDo you want to save "
2627 "the document?"), file);
2628 title = _("Save changed document?");
2631 text = bformat(_("The document %1$s has not been "
2632 "saved yet.\n\nDo you want to save "
2633 "the document?"), file);
2634 title = _("Save new document?");
2636 int const ret = Alert::prompt(title, text, 0, 1, _("&Save"), _("&Cancel"));
2639 dispatch(FuncRequest(LFUN_BUFFER_WRITE));
2641 return buffer->isClean() && !buffer->isUnnamed();
2645 bool GuiView::reloadBuffer(Buffer & buf)
2647 Buffer::ReadStatus status = buf.reload();
2648 return status == Buffer::ReadSuccess;
2652 void GuiView::checkExternallyModifiedBuffers()
2654 BufferList::iterator bit = theBufferList().begin();
2655 BufferList::iterator const bend = theBufferList().end();
2656 for (; bit != bend; ++bit) {
2657 Buffer * buf = *bit;
2658 if (buf->fileName().exists()
2659 && buf->isExternallyModified(Buffer::checksum_method)) {
2660 docstring text = bformat(_("Document \n%1$s\n has been externally modified."
2661 " Reload now? Any local changes will be lost."),
2662 from_utf8(buf->absFileName()));
2663 int const ret = Alert::prompt(_("Reload externally changed document?"),
2664 text, 0, 1, _("&Reload"), _("&Cancel"));
2672 void GuiView::dispatchVC(FuncRequest const & cmd, DispatchResult & dr)
2674 Buffer * buffer = documentBufferView()
2675 ? &(documentBufferView()->buffer()) : 0;
2677 switch (cmd.action()) {
2678 case LFUN_VC_REGISTER:
2679 if (!buffer || !ensureBufferClean(buffer))
2681 if (!buffer->lyxvc().inUse()) {
2682 if (buffer->lyxvc().registrer()) {
2683 reloadBuffer(*buffer);
2684 dr.suppressMessageUpdate();
2689 case LFUN_VC_CHECK_IN:
2690 if (!buffer || !ensureBufferClean(buffer))
2692 if (buffer->lyxvc().inUse() && !buffer->isReadonly()) {
2693 dr.setMessage(buffer->lyxvc().checkIn());
2694 if (!dr.message().empty())
2695 reloadBuffer(*buffer);
2699 case LFUN_VC_CHECK_OUT:
2700 if (!buffer || !ensureBufferClean(buffer))
2702 if (buffer->lyxvc().inUse()) {
2703 dr.setMessage(buffer->lyxvc().checkOut());
2704 reloadBuffer(*buffer);
2708 case LFUN_VC_LOCKING_TOGGLE:
2709 LASSERT(buffer, return);
2710 if (!ensureBufferClean(buffer) || buffer->isReadonly())
2712 if (buffer->lyxvc().inUse()) {
2713 string res = buffer->lyxvc().lockingToggle();
2715 frontend::Alert::error(_("Revision control error."),
2716 _("Error when setting the locking property."));
2719 reloadBuffer(*buffer);
2724 case LFUN_VC_REVERT:
2725 LASSERT(buffer, return);
2726 if (buffer->lyxvc().revert()) {
2727 reloadBuffer(*buffer);
2728 dr.suppressMessageUpdate();
2732 case LFUN_VC_UNDO_LAST:
2733 LASSERT(buffer, return);
2734 buffer->lyxvc().undoLast();
2735 reloadBuffer(*buffer);
2736 dr.suppressMessageUpdate();
2739 case LFUN_VC_REPO_UPDATE:
2740 LASSERT(buffer, return);
2741 if (ensureBufferClean(buffer)) {
2742 dr.setMessage(buffer->lyxvc().repoUpdate());
2743 checkExternallyModifiedBuffers();
2747 case LFUN_VC_COMMAND: {
2748 string flag = cmd.getArg(0);
2749 if (buffer && contains(flag, 'R') && !ensureBufferClean(buffer))
2752 if (contains(flag, 'M')) {
2753 if (!Alert::askForText(message, _("LyX VC: Log Message")))
2756 string path = cmd.getArg(1);
2757 if (contains(path, "$$p") && buffer)
2758 path = subst(path, "$$p", buffer->filePath());
2759 LYXERR(Debug::LYXVC, "Directory: " << path);
2761 if (!pp.isReadableDirectory()) {
2762 lyxerr << _("Directory is not accessible.") << endl;
2765 support::PathChanger p(pp);
2767 string command = cmd.getArg(2);
2768 if (command.empty())
2771 command = subst(command, "$$i", buffer->absFileName());
2772 command = subst(command, "$$p", buffer->filePath());
2774 command = subst(command, "$$m", to_utf8(message));
2775 LYXERR(Debug::LYXVC, "Command: " << command);
2777 one.startscript(Systemcall::Wait, command);
2781 if (contains(flag, 'I'))
2782 buffer->markDirty();
2783 if (contains(flag, 'R'))
2784 reloadBuffer(*buffer);
2789 case LFUN_VC_COMPARE: {
2791 if (cmd.argument().empty()) {
2792 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "comparehistory"));
2796 string rev1 = cmd.getArg(0);
2800 if (!buffer->lyxvc().prepareFileRevision(rev1, f1))
2803 if (isStrInt(rev1) && convert<int>(rev1) <= 0) {
2804 f2 = buffer->absFileName();
2806 string rev2 = cmd.getArg(1);
2810 if (!buffer->lyxvc().prepareFileRevision(rev2, f2))
2814 LYXERR(Debug::LYXVC, "Launching comparison for fetched revisions:\n" <<
2815 f1 << "\n" << f2 << "\n" );
2816 string par = "compare run " + quoteName(f1) + " " + quoteName(f2);
2817 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, par));
2827 void GuiView::openChildDocument(string const & fname)
2829 LASSERT(documentBufferView(), return);
2830 Buffer & buffer = documentBufferView()->buffer();
2831 FileName const filename = support::makeAbsPath(fname, buffer.filePath());
2832 documentBufferView()->saveBookmark(false);
2834 if (theBufferList().exists(filename)) {
2835 child = theBufferList().getBuffer(filename);
2838 message(bformat(_("Opening child document %1$s..."),
2839 makeDisplayPath(filename.absFileName())));
2840 child = loadDocument(filename, false);
2842 // Set the parent name of the child document.
2843 // This makes insertion of citations and references in the child work,
2844 // when the target is in the parent or another child document.
2846 child->setParent(&buffer);
2850 bool GuiView::goToFileRow(string const & argument)
2854 size_t i = argument.find_last_of(' ');
2855 if (i != string::npos) {
2856 file_name = os::internal_path(trim(argument.substr(0, i)));
2857 istringstream is(argument.substr(i + 1));
2862 if (i == string::npos) {
2863 LYXERR0("Wrong argument: " << argument);
2867 string const abstmp = package().temp_dir().absFileName();
2868 string const realtmp = package().temp_dir().realPath();
2869 // We have to use os::path_prefix_is() here, instead of
2870 // simply prefixIs(), because the file name comes from
2871 // an external application and may need case adjustment.
2872 if (os::path_prefix_is(file_name, abstmp, os::CASE_ADJUSTED)
2873 || os::path_prefix_is(file_name, realtmp, os::CASE_ADJUSTED)) {
2874 // Needed by inverse dvi search. If it is a file
2875 // in tmpdir, call the apropriated function.
2876 // If tmpdir is a symlink, we may have the real
2877 // path passed back, so we correct for that.
2878 if (!prefixIs(file_name, abstmp))
2879 file_name = subst(file_name, realtmp, abstmp);
2880 buf = theBufferList().getBufferFromTmp(file_name);
2882 // Must replace extension of the file to be .lyx
2883 // and get full path
2884 FileName const s = fileSearch(string(),
2885 support::changeExtension(file_name, ".lyx"), "lyx");
2886 // Either change buffer or load the file
2887 if (theBufferList().exists(s))
2888 buf = theBufferList().getBuffer(s);
2889 else if (s.exists()) {
2890 buf = loadDocument(s);
2895 _("File does not exist: %1$s"),
2896 makeDisplayPath(file_name)));
2901 documentBufferView()->setCursorFromRow(row);
2906 #if (QT_VERSION >= 0x040400)
2908 docstring GuiView::GuiViewPrivate::runAndDestroy(const T& func, Buffer const * orig, Buffer * buffer, string const & format, string const & msg)
2910 bool const update_unincluded =
2911 buffer->params().maintain_unincluded_children
2912 && !buffer->params().getIncludedChildren().empty();
2913 bool const success = func(format, update_unincluded);
2915 busyBuffers.remove(orig);
2916 if (msg == "preview") {
2918 ? bformat(_("Successful preview of format: %1$s"), from_utf8(format))
2919 : bformat(_("Error while previewing format: %1$s"), from_utf8(format));
2922 ? bformat(_("Successful export to format: %1$s"), from_utf8(format))
2923 : bformat(_("Error while exporting format: %1$s"), from_utf8(format));
2927 docstring GuiView::GuiViewPrivate::compileAndDestroy(Buffer const * orig, Buffer * buffer, string const & format)
2929 bool (Buffer::* mem_func)(std::string const &, bool, bool) const = &Buffer::doExport;
2930 return runAndDestroy(bind(mem_func, buffer, _1, true, _2), orig, buffer, format, "export");
2934 docstring GuiView::GuiViewPrivate::exportAndDestroy(Buffer const * orig, Buffer * buffer, string const & format)
2936 bool (Buffer::* mem_func)(std::string const &, bool, bool) const = &Buffer::doExport;
2937 return runAndDestroy(bind(mem_func, buffer, _1, false, _2), orig, buffer, format, "export");
2941 docstring GuiView::GuiViewPrivate::previewAndDestroy(Buffer const * orig, Buffer * buffer, string const & format)
2943 bool(Buffer::* mem_func)(std::string const &, bool) const = &Buffer::preview;
2944 return runAndDestroy(bind(mem_func, buffer, _1, _2), orig, buffer, format, "preview");
2949 // not used, but the linker needs them
2951 docstring GuiView::GuiViewPrivate::compileAndDestroy(
2952 Buffer const *, Buffer *, string const &)
2958 docstring GuiView::GuiViewPrivate::exportAndDestroy(
2959 Buffer const *, Buffer *, string const &)
2965 docstring GuiView::GuiViewPrivate::previewAndDestroy(
2966 Buffer const *, Buffer *, string const &)
2974 bool GuiView::GuiViewPrivate::asyncBufferProcessing(
2975 string const & argument,
2976 Buffer const * used_buffer,
2977 docstring const & msg,
2978 docstring (*asyncFunc)(Buffer const *, Buffer *, string const &),
2979 bool (Buffer::*syncFunc)(string const &, bool, bool) const,
2980 bool (Buffer::*previewFunc)(string const &, bool) const)
2985 string format = argument;
2987 format = used_buffer->getDefaultOutputFormat();
2989 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
2991 progress_->clearMessages();
2994 GuiViewPrivate::busyBuffers.insert(used_buffer);
2995 QFuture<docstring> f = QtConcurrent::run(
2998 used_buffer->clone(),
3000 setPreviewFuture(f);
3001 last_export_format = used_buffer->bufferFormat();
3004 // We are asynchronous, so we don't know here anything about the success
3008 // TODO check here if it breaks exporting with Qt < 4.4
3009 bool const update_unincluded =
3010 used_buffer->params().maintain_unincluded_children &&
3011 !used_buffer->params().getIncludedChildren().empty();
3012 return (used_buffer->*syncFunc)(format, true, update_unincluded);
3013 } else if (previewFunc) {
3014 return (used_buffer->*previewFunc)(format, false);
3021 void GuiView::dispatchToBufferView(FuncRequest const & cmd, DispatchResult & dr)
3023 BufferView * bv = currentBufferView();
3026 // Let the current BufferView dispatch its own actions.
3027 bv->dispatch(cmd, dr);
3028 if (dr.dispatched())
3031 // Try with the document BufferView dispatch if any.
3032 BufferView * doc_bv = documentBufferView();
3034 doc_bv->dispatch(cmd, dr);
3035 if (dr.dispatched())
3039 // Then let the current Cursor dispatch its own actions.
3040 bv->cursor().dispatch(cmd);
3042 // update completion. We do it here and not in
3043 // processKeySym to avoid another redraw just for a
3044 // changed inline completion
3045 if (cmd.origin() == FuncRequest::KEYBOARD) {
3046 if (cmd.action() == LFUN_SELF_INSERT
3047 || (cmd.action() == LFUN_ERT_INSERT && bv->cursor().inMathed()))
3048 updateCompletion(bv->cursor(), true, true);
3049 else if (cmd.action() == LFUN_CHAR_DELETE_BACKWARD)
3050 updateCompletion(bv->cursor(), false, true);
3052 updateCompletion(bv->cursor(), false, false);
3055 dr = bv->cursor().result();
3059 void GuiView::dispatch(FuncRequest const & cmd, DispatchResult & dr)
3061 BufferView * bv = currentBufferView();
3062 // By default we won't need any update.
3063 dr.screenUpdate(Update::None);
3064 // assume cmd will be dispatched
3065 dr.dispatched(true);
3067 Buffer * doc_buffer = documentBufferView()
3068 ? &(documentBufferView()->buffer()) : 0;
3070 if (cmd.origin() == FuncRequest::TOC) {
3071 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
3072 // FIXME: do we need to pass a DispatchResult object here?
3073 toc->doDispatch(bv->cursor(), cmd);
3077 string const argument = to_utf8(cmd.argument());
3079 switch(cmd.action()) {
3080 case LFUN_BUFFER_CHILD_OPEN:
3081 openChildDocument(to_utf8(cmd.argument()));
3084 case LFUN_BUFFER_IMPORT:
3085 importDocument(to_utf8(cmd.argument()));
3088 case LFUN_BUFFER_EXPORT: {
3091 // GCC only sees strfwd.h when building merged
3092 if (::lyx::operator==(cmd.argument(), "custom")) {
3093 dispatch(FuncRequest(LFUN_DIALOG_SHOW, "sendto"), dr);
3096 #if QT_VERSION < 0x040400
3097 if (!doc_buffer->doExport(argument, false)) {
3099 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
3103 /* TODO/Review: Is it a problem to also export the children?
3104 See the update_unincluded flag */
3105 d.asyncBufferProcessing(argument,
3108 &GuiViewPrivate::exportAndDestroy,
3111 // TODO Inform user about success
3116 case LFUN_BUFFER_UPDATE: {
3117 d.asyncBufferProcessing(argument,
3120 &GuiViewPrivate::compileAndDestroy,
3125 case LFUN_BUFFER_VIEW: {
3126 d.asyncBufferProcessing(argument,
3128 _("Previewing ..."),
3129 &GuiViewPrivate::previewAndDestroy,
3134 case LFUN_MASTER_BUFFER_UPDATE: {
3135 d.asyncBufferProcessing(argument,
3136 (doc_buffer ? doc_buffer->masterBuffer() : 0),
3138 &GuiViewPrivate::compileAndDestroy,
3143 case LFUN_MASTER_BUFFER_VIEW: {
3144 d.asyncBufferProcessing(argument,
3145 (doc_buffer ? doc_buffer->masterBuffer() : 0),
3147 &GuiViewPrivate::previewAndDestroy,
3148 0, &Buffer::preview);
3151 case LFUN_BUFFER_SWITCH: {
3152 string const file_name = to_utf8(cmd.argument());
3153 if (!FileName::isAbsolute(file_name)) {
3155 dr.setMessage(_("Absolute filename expected."));
3159 Buffer * buffer = theBufferList().getBuffer(FileName(file_name));
3162 dr.setMessage(_("Document not loaded"));
3166 // Do we open or switch to the buffer in this view ?
3167 if (workArea(*buffer)
3168 || lyxrc.open_buffers_in_tabs || !documentBufferView()) {
3173 // Look for the buffer in other views
3174 QList<int> const ids = guiApp->viewIds();
3176 for (; i != ids.size(); ++i) {
3177 GuiView & gv = guiApp->view(ids[i]);
3178 if (gv.workArea(*buffer)) {
3179 gv.activateWindow();
3180 gv.setBuffer(buffer);
3185 // If necessary, open a new window as a last resort
3186 if (i == ids.size()) {
3187 lyx::dispatch(FuncRequest(LFUN_WINDOW_NEW));
3193 case LFUN_BUFFER_NEXT:
3194 gotoNextOrPreviousBuffer(NEXTBUFFER);
3197 case LFUN_BUFFER_PREVIOUS:
3198 gotoNextOrPreviousBuffer(PREVBUFFER);
3201 case LFUN_COMMAND_EXECUTE: {
3202 bool const show_it = cmd.argument() != "off";
3203 // FIXME: this is a hack, "minibuffer" should not be
3205 if (GuiToolbar * t = toolbar("minibuffer")) {
3206 t->setVisible(show_it);
3207 if (show_it && t->commandBuffer())
3208 t->commandBuffer()->setFocus();
3212 case LFUN_DROP_LAYOUTS_CHOICE:
3213 d.layout_->showPopup();
3216 case LFUN_MENU_OPEN:
3217 if (QMenu * menu = guiApp->menus().menu(toqstr(cmd.argument()), *this))
3218 menu->exec(QCursor::pos());
3221 case LFUN_FILE_INSERT:
3222 insertLyXFile(cmd.argument());
3225 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
3226 insertPlaintextFile(cmd.argument(), true);
3229 case LFUN_FILE_INSERT_PLAINTEXT:
3230 insertPlaintextFile(cmd.argument(), false);
3233 case LFUN_BUFFER_RELOAD: {
3234 LASSERT(doc_buffer, break);
3237 if (!doc_buffer->isClean()) {
3238 docstring const file =
3239 makeDisplayPath(doc_buffer->absFileName(), 20);
3240 docstring text = bformat(_("Any changes will be lost. "
3241 "Are you sure you want to revert to the saved version "
3242 "of the document %1$s?"), file);
3243 ret = Alert::prompt(_("Revert to saved document?"),
3244 text, 1, 1, _("&Revert"), _("&Cancel"));
3248 doc_buffer->markClean();
3249 reloadBuffer(*doc_buffer);
3250 dr.forceBufferUpdate();
3255 case LFUN_BUFFER_WRITE:
3256 LASSERT(doc_buffer, break);
3257 saveBuffer(*doc_buffer);
3260 case LFUN_BUFFER_WRITE_AS:
3261 LASSERT(doc_buffer, break);
3262 renameBuffer(*doc_buffer, cmd.argument());
3265 case LFUN_BUFFER_WRITE_ALL: {
3266 Buffer * first = theBufferList().first();
3269 message(_("Saving all documents..."));
3270 // We cannot use a for loop as the buffer list cycles.
3273 if (!b->isClean()) {
3275 LYXERR(Debug::ACTION, "Saved " << b->absFileName());
3277 b = theBufferList().next(b);
3278 } while (b != first);
3279 dr.setMessage(_("All documents saved."));
3283 case LFUN_BUFFER_CLOSE:
3287 case LFUN_BUFFER_CLOSE_ALL:
3291 case LFUN_TOOLBAR_TOGGLE: {
3292 string const name = cmd.getArg(0);
3293 if (GuiToolbar * t = toolbar(name))
3298 case LFUN_DIALOG_UPDATE: {
3299 string const name = to_utf8(cmd.argument());
3300 if (name == "prefs" || name == "document")
3301 updateDialog(name, string());
3302 else if (name == "paragraph")
3303 lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
3304 else if (currentBufferView()) {
3305 Inset * inset = currentBufferView()->editedInset(name);
3306 // Can only update a dialog connected to an existing inset
3308 // FIXME: get rid of this indirection; GuiView ask the inset
3309 // if he is kind enough to update itself...
3310 FuncRequest fr(LFUN_INSET_DIALOG_UPDATE, cmd.argument());
3311 //FIXME: pass DispatchResult here?
3312 inset->dispatch(currentBufferView()->cursor(), fr);
3318 case LFUN_DIALOG_TOGGLE: {
3319 FuncCode const func_code = isDialogVisible(cmd.getArg(0))
3320 ? LFUN_DIALOG_HIDE : LFUN_DIALOG_SHOW;
3321 dispatch(FuncRequest(func_code, cmd.argument()), dr);
3325 case LFUN_DIALOG_DISCONNECT_INSET:
3326 disconnectDialog(to_utf8(cmd.argument()));
3329 case LFUN_DIALOG_HIDE: {
3330 guiApp->hideDialogs(to_utf8(cmd.argument()), 0);
3334 case LFUN_DIALOG_SHOW: {
3335 string const name = cmd.getArg(0);
3336 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
3338 if (name == "character") {
3339 data = freefont2string();
3341 showDialog("character", data);
3342 } else if (name == "latexlog") {
3343 Buffer::LogType type;
3344 string const logfile = doc_buffer->logName(&type);
3346 case Buffer::latexlog:
3349 case Buffer::buildlog:
3353 data += Lexer::quoteString(logfile);
3354 showDialog("log", data);
3355 } else if (name == "vclog") {
3356 string const data = "vc " +
3357 Lexer::quoteString(doc_buffer->lyxvc().getLogFile());
3358 showDialog("log", data);
3359 } else if (name == "symbols") {
3360 data = bv->cursor().getEncoding()->name();
3362 showDialog("symbols", data);
3364 } else if (name == "prefs" && isFullScreen()) {
3365 lfunUiToggle("fullscreen");
3366 showDialog("prefs", data);
3368 showDialog(name, data);
3373 dr.setMessage(cmd.argument());
3376 case LFUN_UI_TOGGLE: {
3377 string arg = cmd.getArg(0);
3378 if (!lfunUiToggle(arg)) {
3379 docstring const msg = "ui-toggle " + _("%1$s unknown command!");
3380 dr.setMessage(bformat(msg, from_utf8(arg)));
3382 // Make sure the keyboard focus stays in the work area.
3387 case LFUN_SPLIT_VIEW: {
3388 LASSERT(doc_buffer, break);
3389 string const orientation = cmd.getArg(0);
3390 d.splitter_->setOrientation(orientation == "vertical"
3391 ? Qt::Vertical : Qt::Horizontal);
3392 TabWorkArea * twa = addTabWorkArea();
3393 GuiWorkArea * wa = twa->addWorkArea(*doc_buffer, *this);
3394 setCurrentWorkArea(wa);
3397 case LFUN_CLOSE_TAB_GROUP:
3398 if (TabWorkArea * twa = d.currentTabWorkArea()) {
3399 closeTabWorkArea(twa);
3400 d.current_work_area_ = 0;
3401 twa = d.currentTabWorkArea();
3402 // Switch to the next GuiWorkArea in the found TabWorkArea.
3404 // Make sure the work area is up to date.
3405 setCurrentWorkArea(twa->currentWorkArea());
3407 setCurrentWorkArea(0);
3412 case LFUN_COMPLETION_INLINE:
3413 if (d.current_work_area_)
3414 d.current_work_area_->completer().showInline();
3417 case LFUN_COMPLETION_POPUP:
3418 if (d.current_work_area_)
3419 d.current_work_area_->completer().showPopup();
3423 case LFUN_COMPLETION_COMPLETE:
3424 if (d.current_work_area_)
3425 d.current_work_area_->completer().tab();
3428 case LFUN_COMPLETION_CANCEL:
3429 if (d.current_work_area_) {
3430 if (d.current_work_area_->completer().popupVisible())
3431 d.current_work_area_->completer().hidePopup();
3433 d.current_work_area_->completer().hideInline();
3437 case LFUN_COMPLETION_ACCEPT:
3438 if (d.current_work_area_)
3439 d.current_work_area_->completer().activate();
3442 case LFUN_BUFFER_ZOOM_IN:
3443 case LFUN_BUFFER_ZOOM_OUT:
3444 if (cmd.argument().empty()) {
3445 if (cmd.action() == LFUN_BUFFER_ZOOM_IN)
3450 lyxrc.zoom += convert<int>(cmd.argument());
3452 if (lyxrc.zoom < 10)
3455 // The global QPixmapCache is used in GuiPainter to cache text
3456 // painting so we must reset it.
3457 QPixmapCache::clear();
3458 guiApp->fontLoader().update();
3459 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
3462 case LFUN_VC_REGISTER:
3463 case LFUN_VC_CHECK_IN:
3464 case LFUN_VC_CHECK_OUT:
3465 case LFUN_VC_REPO_UPDATE:
3466 case LFUN_VC_LOCKING_TOGGLE:
3467 case LFUN_VC_REVERT:
3468 case LFUN_VC_UNDO_LAST:
3469 case LFUN_VC_COMMAND:
3470 case LFUN_VC_COMPARE:
3471 dispatchVC(cmd, dr);
3474 case LFUN_SERVER_GOTO_FILE_ROW:
3475 goToFileRow(to_utf8(cmd.argument()));
3478 case LFUN_FORWARD_SEARCH: {
3479 Buffer const * doc_master = doc_buffer->masterBuffer();
3480 FileName const path(doc_master->temppath());
3481 string const texname = doc_master->isChild(doc_buffer)
3482 ? DocFileName(changeExtension(
3483 doc_buffer->absFileName(),
3484 "tex")).mangledFileName()
3485 : doc_buffer->latexName();
3486 string const mastername =
3487 removeExtension(doc_master->latexName());
3488 FileName const dviname(addName(path.absFileName(),
3489 addExtension(mastername, "dvi")));
3490 FileName const pdfname(addName(path.absFileName(),
3491 addExtension(mastername, "pdf")));
3492 if (!dviname.exists() && !pdfname.exists()) {
3493 dr.setMessage(_("Please, preview the document first."));
3496 string outname = dviname.onlyFileName();
3497 string command = lyxrc.forward_search_dvi;
3498 if (!dviname.exists() ||
3499 pdfname.lastModified() > dviname.lastModified()) {
3500 outname = pdfname.onlyFileName();
3501 command = lyxrc.forward_search_pdf;
3504 int row = doc_buffer->texrow().getRowFromIdPos(bv->cursor().paragraph().id(), bv->cursor().pos());
3505 LYXERR(Debug::ACTION, "Forward search: row:" << row
3506 << " id:" << bv->cursor().paragraph().id());
3507 if (!row || command.empty()) {
3508 dr.setMessage(_("Couldn't proceed."));
3511 string texrow = convert<string>(row);
3513 command = subst(command, "$$n", texrow);
3514 command = subst(command, "$$t", texname);
3515 command = subst(command, "$$o", outname);
3517 PathChanger p(path);
3519 one.startscript(Systemcall::DontWait, command);
3523 // The LFUN must be for one of BufferView, Buffer or Cursor;
3525 dispatchToBufferView(cmd, dr);
3529 // Part of automatic menu appearance feature.
3530 if (isFullScreen()) {
3531 if (menuBar()->isVisible() && lyxrc.full_screen_menubar)
3533 if (statusBar()->isVisible())
3534 statusBar()->hide();
3539 bool GuiView::lfunUiToggle(string const & ui_component)
3541 if (ui_component == "scrollbar") {
3542 // hide() is of no help
3543 if (d.current_work_area_->verticalScrollBarPolicy() ==
3544 Qt::ScrollBarAlwaysOff)
3546 d.current_work_area_->setVerticalScrollBarPolicy(
3547 Qt::ScrollBarAsNeeded);
3549 d.current_work_area_->setVerticalScrollBarPolicy(
3550 Qt::ScrollBarAlwaysOff);
3551 } else if (ui_component == "statusbar") {
3552 statusBar()->setVisible(!statusBar()->isVisible());
3553 } else if (ui_component == "menubar") {
3554 menuBar()->setVisible(!menuBar()->isVisible());
3556 #if QT_VERSION >= 0x040300
3557 if (ui_component == "frame") {
3559 getContentsMargins(&l, &t, &r, &b);
3560 //are the frames in default state?
3561 d.current_work_area_->setFrameStyle(QFrame::NoFrame);
3563 setContentsMargins(-2, -2, -2, -2);
3565 setContentsMargins(0, 0, 0, 0);
3569 if (ui_component == "fullscreen") {
3577 void GuiView::toggleFullScreen()
3579 if (isFullScreen()) {
3580 for (int i = 0; i != d.splitter_->count(); ++i)
3581 d.tabWorkArea(i)->setFullScreen(false);
3582 #if QT_VERSION >= 0x040300
3583 setContentsMargins(0, 0, 0, 0);
3585 setWindowState(windowState() ^ Qt::WindowFullScreen);
3588 statusBar()->show();
3591 hideDialogs("prefs", 0);
3592 for (int i = 0; i != d.splitter_->count(); ++i)
3593 d.tabWorkArea(i)->setFullScreen(true);
3594 #if QT_VERSION >= 0x040300
3595 setContentsMargins(-2, -2, -2, -2);
3598 setWindowState(windowState() ^ Qt::WindowFullScreen);
3599 statusBar()->hide();
3600 if (lyxrc.full_screen_menubar)
3602 if (lyxrc.full_screen_toolbars) {
3603 ToolbarMap::iterator end = d.toolbars_.end();
3604 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
3609 // give dialogs like the TOC a chance to adapt
3614 Buffer const * GuiView::updateInset(Inset const * inset)
3619 Buffer const * inset_buffer = &(inset->buffer());
3621 for (int i = 0; i != d.splitter_->count(); ++i) {
3622 GuiWorkArea * wa = d.tabWorkArea(i)->currentWorkArea();
3625 Buffer const * buffer = &(wa->bufferView().buffer());
3626 if (inset_buffer == buffer)
3627 wa->scheduleRedraw();
3629 return inset_buffer;
3633 void GuiView::restartCursor()
3635 /* When we move around, or type, it's nice to be able to see
3636 * the cursor immediately after the keypress.
3638 if (d.current_work_area_)
3639 d.current_work_area_->startBlinkingCursor();
3641 // Take this occasion to update the other GUI elements.
3647 void GuiView::updateCompletion(Cursor & cur, bool start, bool keep)
3649 if (d.current_work_area_)
3650 d.current_work_area_->completer().updateVisibility(cur, start, keep);
3655 // This list should be kept in sync with the list of insets in
3656 // src/insets/Inset.cpp. I.e., if a dialog goes with an inset, the
3657 // dialog should have the same name as the inset.
3658 // Changes should be also recorded in LFUN_DIALOG_SHOW doxygen
3659 // docs in LyXAction.cpp.
3661 char const * const dialognames[] = {
3663 "aboutlyx", "bibitem", "bibtex", "box", "branch", "changes", "character",
3664 "citation", "compare", "comparehistory", "document", "errorlist", "ert",
3665 "external", "file", "findreplace", "findreplaceadv", "float", "graphics",
3666 "href", "include", "index", "index_print", "info", "listings", "label", "line",
3667 "log", "mathdelimiter", "mathmatrix", "mathspace", "nomenclature",
3668 "nomencl_print", "note", "paragraph", "phantom", "prefs", "print", "ref",
3669 "sendto", "space", "spellchecker", "symbols", "tabular", "tabularcreate",
3670 "thesaurus", "texinfo", "toc", "view-source", "vspace", "wrap", "progress"};
3672 char const * const * const end_dialognames =
3673 dialognames + (sizeof(dialognames) / sizeof(char *));
3677 cmpCStr(char const * name) : name_(name) {}
3678 bool operator()(char const * other) {
3679 return strcmp(other, name_) == 0;
3686 bool isValidName(string const & name)
3688 return find_if(dialognames, end_dialognames,
3689 cmpCStr(name.c_str())) != end_dialognames;
3695 void GuiView::resetDialogs()
3697 // Make sure that no LFUN uses any GuiView.
3698 guiApp->setCurrentView(0);
3702 constructToolbars();
3703 guiApp->menus().fillMenuBar(menuBar(), this, false);
3704 d.layout_->updateContents(true);
3705 // Now update controls with current buffer.
3706 guiApp->setCurrentView(this);
3712 Dialog * GuiView::findOrBuild(string const & name, bool hide_it)
3714 if (!isValidName(name))
3717 map<string, DialogPtr>::iterator it = d.dialogs_.find(name);
3719 if (it != d.dialogs_.end()) {
3721 it->second->hideView();
3722 return it->second.get();
3725 Dialog * dialog = build(name);
3726 d.dialogs_[name].reset(dialog);
3727 if (lyxrc.allow_geometry_session)
3728 dialog->restoreSession();
3735 void GuiView::showDialog(string const & name, string const & data,
3738 triggerShowDialog(toqstr(name), toqstr(data), inset);
3742 void GuiView::doShowDialog(QString const & qname, QString const & qdata,
3748 const string name = fromqstr(qname);
3749 const string data = fromqstr(qdata);
3753 Dialog * dialog = findOrBuild(name, false);
3755 bool const visible = dialog->isVisibleView();
3756 dialog->showData(data);
3757 if (inset && currentBufferView())
3758 currentBufferView()->editInset(name, inset);
3759 // We only set the focus to the new dialog if it was not yet
3760 // visible in order not to change the existing previous behaviour
3762 // activateWindow is needed for floating dockviews
3763 dialog->asQWidget()->raise();
3764 dialog->asQWidget()->activateWindow();
3765 dialog->asQWidget()->setFocus();
3769 catch (ExceptionMessage const & ex) {
3777 bool GuiView::isDialogVisible(string const & name) const
3779 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3780 if (it == d.dialogs_.end())
3782 return it->second.get()->isVisibleView() && !it->second.get()->isClosing();
3786 void GuiView::hideDialog(string const & name, Inset * inset)
3788 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3789 if (it == d.dialogs_.end())
3793 if (!currentBufferView())
3795 if (inset != currentBufferView()->editedInset(name))
3799 Dialog * const dialog = it->second.get();
3800 if (dialog->isVisibleView())
3802 if (currentBufferView())
3803 currentBufferView()->editInset(name, 0);
3807 void GuiView::disconnectDialog(string const & name)
3809 if (!isValidName(name))
3811 if (currentBufferView())
3812 currentBufferView()->editInset(name, 0);
3816 void GuiView::hideAll() const
3818 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
3819 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3821 for(; it != end; ++it)
3822 it->second->hideView();
3826 void GuiView::updateDialogs()
3828 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
3829 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3831 for(; it != end; ++it) {
3832 Dialog * dialog = it->second.get();
3834 if (dialog->needBufferOpen() && !documentBufferView())
3835 hideDialog(fromqstr(dialog->name()), 0);
3836 else if (dialog->isVisibleView())
3837 dialog->checkStatus();
3844 Dialog * createDialog(GuiView & lv, string const & name);
3846 // will be replaced by a proper factory...
3847 Dialog * createGuiAbout(GuiView & lv);
3848 Dialog * createGuiBibtex(GuiView & lv);
3849 Dialog * createGuiChanges(GuiView & lv);
3850 Dialog * createGuiCharacter(GuiView & lv);
3851 Dialog * createGuiCitation(GuiView & lv);
3852 Dialog * createGuiCompare(GuiView & lv);
3853 Dialog * createGuiCompareHistory(GuiView & lv);
3854 Dialog * createGuiDelimiter(GuiView & lv);
3855 Dialog * createGuiDocument(GuiView & lv);
3856 Dialog * createGuiErrorList(GuiView & lv);
3857 Dialog * createGuiExternal(GuiView & lv);
3858 Dialog * createGuiGraphics(GuiView & lv);
3859 Dialog * createGuiInclude(GuiView & lv);
3860 Dialog * createGuiIndex(GuiView & lv);
3861 Dialog * createGuiListings(GuiView & lv);
3862 Dialog * createGuiLog(GuiView & lv);
3863 Dialog * createGuiMathMatrix(GuiView & lv);
3864 Dialog * createGuiNote(GuiView & lv);
3865 Dialog * createGuiParagraph(GuiView & lv);
3866 Dialog * createGuiPhantom(GuiView & lv);
3867 Dialog * createGuiPreferences(GuiView & lv);
3868 Dialog * createGuiPrint(GuiView & lv);
3869 Dialog * createGuiPrintindex(GuiView & lv);
3870 Dialog * createGuiRef(GuiView & lv);
3871 Dialog * createGuiSearch(GuiView & lv);
3872 Dialog * createGuiSearchAdv(GuiView & lv);
3873 Dialog * createGuiSendTo(GuiView & lv);
3874 Dialog * createGuiShowFile(GuiView & lv);
3875 Dialog * createGuiSpellchecker(GuiView & lv);
3876 Dialog * createGuiSymbols(GuiView & lv);
3877 Dialog * createGuiTabularCreate(GuiView & lv);
3878 Dialog * createGuiTexInfo(GuiView & lv);
3879 Dialog * createGuiToc(GuiView & lv);
3880 Dialog * createGuiThesaurus(GuiView & lv);
3881 Dialog * createGuiViewSource(GuiView & lv);
3882 Dialog * createGuiWrap(GuiView & lv);
3883 Dialog * createGuiProgressView(GuiView & lv);
3887 Dialog * GuiView::build(string const & name)
3889 LASSERT(isValidName(name), return 0);
3891 Dialog * dialog = createDialog(*this, name);
3895 if (name == "aboutlyx")
3896 return createGuiAbout(*this);
3897 if (name == "bibtex")
3898 return createGuiBibtex(*this);
3899 if (name == "changes")
3900 return createGuiChanges(*this);
3901 if (name == "character")
3902 return createGuiCharacter(*this);
3903 if (name == "citation")
3904 return createGuiCitation(*this);
3905 if (name == "compare")
3906 return createGuiCompare(*this);
3907 if (name == "comparehistory")
3908 return createGuiCompareHistory(*this);
3909 if (name == "document")
3910 return createGuiDocument(*this);
3911 if (name == "errorlist")
3912 return createGuiErrorList(*this);
3913 if (name == "external")
3914 return createGuiExternal(*this);
3916 return createGuiShowFile(*this);
3917 if (name == "findreplace")
3918 return createGuiSearch(*this);
3919 if (name == "findreplaceadv")
3920 return createGuiSearchAdv(*this);
3921 if (name == "graphics")
3922 return createGuiGraphics(*this);
3923 if (name == "include")
3924 return createGuiInclude(*this);
3925 if (name == "index")
3926 return createGuiIndex(*this);
3927 if (name == "index_print")
3928 return createGuiPrintindex(*this);
3929 if (name == "listings")
3930 return createGuiListings(*this);
3932 return createGuiLog(*this);
3933 if (name == "mathdelimiter")
3934 return createGuiDelimiter(*this);
3935 if (name == "mathmatrix")
3936 return createGuiMathMatrix(*this);
3938 return createGuiNote(*this);
3939 if (name == "paragraph")
3940 return createGuiParagraph(*this);
3941 if (name == "phantom")
3942 return createGuiPhantom(*this);
3943 if (name == "prefs")
3944 return createGuiPreferences(*this);
3945 if (name == "print")
3946 return createGuiPrint(*this);
3948 return createGuiRef(*this);
3949 if (name == "sendto")
3950 return createGuiSendTo(*this);
3951 if (name == "spellchecker")
3952 return createGuiSpellchecker(*this);
3953 if (name == "symbols")
3954 return createGuiSymbols(*this);
3955 if (name == "tabularcreate")
3956 return createGuiTabularCreate(*this);
3957 if (name == "texinfo")
3958 return createGuiTexInfo(*this);
3959 if (name == "thesaurus")
3960 return createGuiThesaurus(*this);
3962 return createGuiToc(*this);
3963 if (name == "view-source")
3964 return createGuiViewSource(*this);
3966 return createGuiWrap(*this);
3967 if (name == "progress")
3968 return createGuiProgressView(*this);
3974 } // namespace frontend
3977 #include "moc_GuiView.cpp"