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()));
168 int width = QFontMetrics(font).width(text);
170 pain.drawText(397 - width, 15, text);
171 setFocusPolicy(Qt::StrongFocus);
174 void paintEvent(QPaintEvent *)
176 int x = (width() - splash_.width()) / 2;
177 int y = (height() - splash_.height()) / 2;
179 pain.drawPixmap(x, y, splash_);
182 void keyPressEvent(QKeyEvent * ev)
185 setKeySymbol(&sym, ev);
187 guiApp->processKeySym(sym, q_key_state(ev->modifiers()));
199 /// Toolbar store providing access to individual toolbars by name.
200 typedef map<string, GuiToolbar *> ToolbarMap;
202 typedef shared_ptr<Dialog> DialogPtr;
207 struct GuiView::GuiViewPrivate
209 GuiViewPrivate(GuiView * gv)
210 : gv_(gv), current_work_area_(0), current_main_work_area_(0),
211 layout_(0), autosave_timeout_(5000),
214 // hardcode here the platform specific icon size
215 smallIconSize = 14; // scaling problems
216 normalIconSize = 20; // ok, default
217 bigIconSize = 26; // better for some math icons
219 splitter_ = new QSplitter;
220 bg_widget_ = new BackgroundWidget;
221 stack_widget_ = new QStackedWidget;
222 stack_widget_->addWidget(bg_widget_);
223 stack_widget_->addWidget(splitter_);
226 // TODO cleanup, remove the singleton, handle multiple Windows?
227 progress_ = ProgressInterface::instance();
228 if (!dynamic_cast<GuiProgress*>(progress_)) {
229 progress_ = new GuiProgress(); // TODO who deletes it
230 ProgressInterface::setInstance(progress_);
233 dynamic_cast<GuiProgress*>(progress_),
234 SIGNAL(updateStatusBarMessage(QString const&)),
235 gv, SLOT(updateStatusBarMessage(QString const&)));
237 dynamic_cast<GuiProgress*>(progress_),
238 SIGNAL(clearMessageText()),
239 gv, SLOT(clearMessageText()));
246 delete stack_widget_;
249 QMenu * toolBarPopup(GuiView * parent)
251 // FIXME: translation
252 QMenu * menu = new QMenu(parent);
253 QActionGroup * iconSizeGroup = new QActionGroup(parent);
255 QAction * smallIcons = new QAction(iconSizeGroup);
256 smallIcons->setText(qt_("Small-sized icons"));
257 smallIcons->setCheckable(true);
258 QObject::connect(smallIcons, SIGNAL(triggered()),
259 parent, SLOT(smallSizedIcons()));
260 menu->addAction(smallIcons);
262 QAction * normalIcons = new QAction(iconSizeGroup);
263 normalIcons->setText(qt_("Normal-sized icons"));
264 normalIcons->setCheckable(true);
265 QObject::connect(normalIcons, SIGNAL(triggered()),
266 parent, SLOT(normalSizedIcons()));
267 menu->addAction(normalIcons);
269 QAction * bigIcons = new QAction(iconSizeGroup);
270 bigIcons->setText(qt_("Big-sized icons"));
271 bigIcons->setCheckable(true);
272 QObject::connect(bigIcons, SIGNAL(triggered()),
273 parent, SLOT(bigSizedIcons()));
274 menu->addAction(bigIcons);
276 unsigned int cur = parent->iconSize().width();
277 if ( cur == parent->d.smallIconSize)
278 smallIcons->setChecked(true);
279 else if (cur == parent->d.normalIconSize)
280 normalIcons->setChecked(true);
281 else if (cur == parent->d.bigIconSize)
282 bigIcons->setChecked(true);
289 stack_widget_->setCurrentWidget(bg_widget_);
290 bg_widget_->setUpdatesEnabled(true);
291 bg_widget_->setFocus();
294 int tabWorkAreaCount()
296 return splitter_->count();
299 TabWorkArea * tabWorkArea(int i)
301 return dynamic_cast<TabWorkArea *>(splitter_->widget(i));
304 TabWorkArea * currentTabWorkArea()
306 int areas = tabWorkAreaCount();
308 // The first TabWorkArea is always the first one, if any.
309 return tabWorkArea(0);
311 for (int i = 0; i != areas; ++i) {
312 TabWorkArea * twa = tabWorkArea(i);
313 if (current_main_work_area_ == twa->currentWorkArea())
317 // None has the focus so we just take the first one.
318 return tabWorkArea(0);
321 #if (QT_VERSION >= 0x040400)
322 void setPreviewFuture(QFuture<docstring> const & f)
324 if (processing_thread_watcher_.isRunning()) {
325 // we prefer to cancel this preview in order to keep a snappy
329 processing_thread_watcher_.setFuture(f);
335 GuiWorkArea * current_work_area_;
336 GuiWorkArea * current_main_work_area_;
337 QSplitter * splitter_;
338 QStackedWidget * stack_widget_;
339 BackgroundWidget * bg_widget_;
341 ToolbarMap toolbars_;
342 ProgressInterface* progress_;
343 /// The main layout box.
345 * \warning Don't Delete! The layout box is actually owned by
346 * whichever toolbar contains it. All the GuiView class needs is a
347 * means of accessing it.
349 * FIXME: replace that with a proper model so that we are not limited
350 * to only one dialog.
355 map<string, DialogPtr> dialogs_;
357 unsigned int smallIconSize;
358 unsigned int normalIconSize;
359 unsigned int bigIconSize;
361 QTimer statusbar_timer_;
362 /// auto-saving of buffers
363 Timeout autosave_timeout_;
364 /// flag against a race condition due to multiclicks, see bug #1119
368 TocModels toc_models_;
370 #if (QT_VERSION >= 0x040400)
372 QFutureWatcher<docstring> autosave_watcher_;
373 QFutureWatcher<docstring> processing_thread_watcher_;
375 string last_export_format;
377 struct DummyWatcher { bool isRunning(){return false;} };
378 DummyWatcher processing_thread_watcher_;
381 static QSet<Buffer const *> busyBuffers;
382 static docstring previewAndDestroy(Buffer const * orig, Buffer * buffer, string const & format);
383 static docstring exportAndDestroy(Buffer const * orig, Buffer * buffer, string const & format);
384 static docstring compileAndDestroy(Buffer const * orig, Buffer * buffer, string const & format);
385 static docstring autosaveAndDestroy(Buffer const * orig, Buffer * buffer);
388 static docstring runAndDestroy(const T& func, Buffer const * orig, Buffer * buffer, string const & format, string const & msg);
390 // TODO syncFunc/previewFunc: use bind
391 bool asyncBufferProcessing(string const & argument,
392 Buffer const * used_buffer,
393 docstring const & msg,
394 docstring (*asyncFunc)(Buffer const *, Buffer *, string const &),
395 bool (Buffer::*syncFunc)(string const &, bool, bool) const,
396 bool (Buffer::*previewFunc)(string const &, bool) const);
398 QVector<GuiWorkArea*> guiWorkAreas();
401 QSet<Buffer const *> GuiView::GuiViewPrivate::busyBuffers;
404 GuiView::GuiView(int id)
405 : d(*new GuiViewPrivate(this)), id_(id), closing_(false), busy_(0)
407 // GuiToolbars *must* be initialised before the menu bar.
408 normalSizedIcons(); // at least on Mac the default is 32 otherwise, which is huge
411 // set ourself as the current view. This is needed for the menu bar
412 // filling, at least for the static special menu item on Mac. Otherwise
413 // they are greyed out.
414 guiApp->setCurrentView(this);
416 // Fill up the menu bar.
417 guiApp->menus().fillMenuBar(menuBar(), this, true);
419 setCentralWidget(d.stack_widget_);
421 // Start autosave timer
422 if (lyxrc.autosave) {
423 d.autosave_timeout_.timeout.connect(bind(&GuiView::autoSave, this));
424 d.autosave_timeout_.setTimeout(lyxrc.autosave * 1000);
425 d.autosave_timeout_.start();
427 connect(&d.statusbar_timer_, SIGNAL(timeout()),
428 this, SLOT(clearMessage()));
430 // We don't want to keep the window in memory if it is closed.
431 setAttribute(Qt::WA_DeleteOnClose, true);
433 #if (!defined(Q_WS_WIN) && !defined(Q_WS_MACX))
434 // assign an icon to main form. We do not do it under Qt/Win or Qt/Mac,
435 // since the icon is provided in the application bundle.
436 setWindowIcon(getPixmap("images/", "lyx", "png"));
439 #if (QT_VERSION >= 0x040300)
440 // use tabbed dock area for multiple docks
441 // (such as "source" and "messages")
442 setDockOptions(QMainWindow::ForceTabbedDocks);
446 setAcceptDrops(true);
448 #if (QT_VERSION >= 0x040400)
450 // add busy indicator to statusbar
451 QLabel * busylabel = new QLabel(statusBar());
452 statusBar()->addPermanentWidget(busylabel);
453 QString fn = toqstr(lyx::libFileSearch("images", "busy.gif").absFileName());
454 QMovie * busyanim = new QMovie(fn, QByteArray(), busylabel);
455 busylabel->setMovie(busyanim);
459 connect(&d.processing_thread_watcher_, SIGNAL(started()),
460 busylabel, SLOT(show()));
461 connect(&d.processing_thread_watcher_, SIGNAL(finished()),
462 busylabel, SLOT(hide()));
464 statusBar()->setSizeGripEnabled(true);
467 connect(&d.autosave_watcher_, SIGNAL(finished()), this,
468 SLOT(autoSaveThreadFinished()));
470 connect(&d.processing_thread_watcher_, SIGNAL(started()), this,
471 SLOT(processingThreadStarted()));
472 connect(&d.processing_thread_watcher_, SIGNAL(finished()), this,
473 SLOT(processingThreadFinished()));
477 connect(this, SIGNAL(triggerShowDialog(QString const &, QString const &, Inset *)),
478 SLOT(doShowDialog(QString const &, QString const &, Inset *)));
480 // Forbid too small unresizable window because it can happen
481 // with some window manager under X11.
482 setMinimumSize(300, 200);
484 if (lyxrc.allow_geometry_session) {
485 // Now take care of session management.
490 // no session handling, default to a sane size.
491 setGeometry(50, 50, 690, 510);
494 // clear session data if any.
496 settings.remove("views");
506 QVector<GuiWorkArea*> GuiView::GuiViewPrivate::guiWorkAreas()
508 QVector<GuiWorkArea*> areas;
509 for (int i = 0; i < tabWorkAreaCount(); i++) {
510 TabWorkArea* ta = tabWorkArea(i);
511 for (int u = 0; u < ta->count(); u++) {
512 areas << ta->workArea(u);
519 #if QT_VERSION >= 0x040400
521 void GuiView::processingThreadStarted()
526 void GuiView::processingThreadFinished(bool show_errors)
528 QFutureWatcher<docstring> const * watcher =
529 static_cast<QFutureWatcher<docstring> const *>(sender());
530 message(watcher->result());
533 errors(d.last_export_format);
538 void GuiView::processingThreadFinished()
540 processingThreadFinished(true);
544 void GuiView::autoSaveThreadFinished()
546 processingThreadFinished(false);
552 void GuiView::processingThreadStarted()
557 void GuiView::processingThreadFinished(bool)
562 void GuiView::processingThreadFinished()
567 void GuiView::autoSaveThreadFinished()
573 void GuiView::saveLayout() const
576 settings.beginGroup("views");
577 settings.beginGroup(QString::number(id_));
579 settings.setValue("pos", pos());
580 settings.setValue("size", size());
582 settings.setValue("geometry", saveGeometry());
584 settings.setValue("layout", saveState(0));
585 settings.setValue("icon_size", iconSize());
589 void GuiView::saveUISettings() const
591 // Save the toolbar private states
592 ToolbarMap::iterator end = d.toolbars_.end();
593 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
594 it->second->saveSession();
595 // Now take care of all other dialogs
596 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
597 for (; it!= d.dialogs_.end(); ++it)
598 it->second->saveSession();
602 bool GuiView::restoreLayout()
605 settings.beginGroup("views");
606 settings.beginGroup(QString::number(id_));
607 QString const icon_key = "icon_size";
608 if (!settings.contains(icon_key))
611 //code below is skipped when when ~/.config/LyX is (re)created
612 setIconSize(settings.value(icon_key).toSize());
614 QPoint pos = settings.value("pos", QPoint(50, 50)).toPoint();
615 QSize size = settings.value("size", QSize(690, 510)).toSize();
619 // Work-around for bug #6034: the window ends up in an undetermined
620 // state when trying to restore a maximized window when it is
621 // already maximized.
622 if (!(windowState() & Qt::WindowMaximized))
623 if (!restoreGeometry(settings.value("geometry").toByteArray()))
624 setGeometry(50, 50, 690, 510);
626 // Make sure layout is correctly oriented.
627 setLayoutDirection(qApp->layoutDirection());
629 // Allow the toc and view-source dock widget to be restored if needed.
631 if ((dialog = findOrBuild("toc", true)))
632 // see bug 5082. At least setup title and enabled state.
633 // Visibility will be adjusted by restoreState below.
634 dialog->prepareView();
635 if ((dialog = findOrBuild("view-source", true)))
636 dialog->prepareView();
637 if ((dialog = findOrBuild("progress", true)))
638 dialog->prepareView();
639 if ((dialog = findOrBuild("findreplaceadv", true)))
640 dialog->prepareView();
642 if (!restoreState(settings.value("layout").toByteArray(), 0))
649 GuiToolbar * GuiView::toolbar(string const & name)
651 ToolbarMap::iterator it = d.toolbars_.find(name);
652 if (it != d.toolbars_.end())
655 LYXERR(Debug::GUI, "Toolbar::display: no toolbar named " << name);
660 void GuiView::constructToolbars()
662 ToolbarMap::iterator it = d.toolbars_.begin();
663 for (; it != d.toolbars_.end(); ++it)
667 // I don't like doing this here, but the standard toolbar
668 // destroys this object when it's destroyed itself (vfr)
669 d.layout_ = new LayoutBox(*this);
670 d.stack_widget_->addWidget(d.layout_);
671 d.layout_->move(0,0);
673 // extracts the toolbars from the backend
674 Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
675 Toolbars::Infos::iterator end = guiApp->toolbars().end();
676 for (; cit != end; ++cit)
677 d.toolbars_[cit->name] = new GuiToolbar(*cit, *this);
681 void GuiView::initToolbars()
683 // extracts the toolbars from the backend
684 Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
685 Toolbars::Infos::iterator end = guiApp->toolbars().end();
686 for (; cit != end; ++cit) {
687 GuiToolbar * tb = toolbar(cit->name);
690 int const visibility = guiApp->toolbars().defaultVisibility(cit->name);
691 bool newline = !(visibility & Toolbars::SAMEROW);
692 tb->setVisible(false);
693 tb->setVisibility(visibility);
695 if (visibility & Toolbars::TOP) {
697 addToolBarBreak(Qt::TopToolBarArea);
698 addToolBar(Qt::TopToolBarArea, tb);
701 if (visibility & Toolbars::BOTTOM) {
702 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
703 #if (QT_VERSION >= 0x040202)
705 addToolBarBreak(Qt::BottomToolBarArea);
707 addToolBar(Qt::BottomToolBarArea, tb);
710 if (visibility & Toolbars::LEFT) {
711 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
712 #if (QT_VERSION >= 0x040202)
714 addToolBarBreak(Qt::LeftToolBarArea);
716 addToolBar(Qt::LeftToolBarArea, tb);
719 if (visibility & Toolbars::RIGHT) {
720 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
721 #if (QT_VERSION >= 0x040202)
723 addToolBarBreak(Qt::RightToolBarArea);
725 addToolBar(Qt::RightToolBarArea, tb);
728 if (visibility & Toolbars::ON)
729 tb->setVisible(true);
734 TocModels & GuiView::tocModels()
736 return d.toc_models_;
740 void GuiView::setFocus()
742 LYXERR(Debug::DEBUG, "GuiView::setFocus()" << this);
743 QMainWindow::setFocus();
747 void GuiView::focusInEvent(QFocusEvent * e)
749 LYXERR(Debug::DEBUG, "GuiView::focusInEvent()" << this);
750 QMainWindow::focusInEvent(e);
751 // Make sure guiApp points to the correct view.
752 guiApp->setCurrentView(this);
753 if (currentWorkArea())
754 currentWorkArea()->setFocus();
755 else if (currentMainWorkArea())
756 currentMainWorkArea()->setFocus();
758 d.bg_widget_->setFocus();
762 QMenu * GuiView::createPopupMenu()
764 return d.toolBarPopup(this);
768 void GuiView::showEvent(QShowEvent * e)
770 LYXERR(Debug::GUI, "Passed Geometry "
771 << size().height() << "x" << size().width()
772 << "+" << pos().x() << "+" << pos().y());
774 if (d.splitter_->count() == 0)
775 // No work area, switch to the background widget.
778 QMainWindow::showEvent(e);
782 bool GuiView::closeScheduled()
789 /** Destroy only all tabbed WorkAreas. Destruction of other WorkAreas
790 ** is responsibility of the container (e.g., dialog)
792 void GuiView::closeEvent(QCloseEvent * close_event)
794 LYXERR(Debug::DEBUG, "GuiView::closeEvent()");
796 if (!GuiViewPrivate::busyBuffers.isEmpty()) {
797 Alert::warning(_("Exit LyX"),
798 _("LyX could not be closed because documents are being processed by LyX."));
799 close_event->setAccepted(false);
803 // If the user pressed the x (so we didn't call closeView
804 // programmatically), we want to clear all existing entries.
806 theSession().lastOpened().clear();
811 // it can happen that this event arrives without selecting the view,
812 // e.g. when clicking the close button on a background window.
814 if (!closeWorkAreaAll()) {
816 close_event->ignore();
820 // Make sure that nothing will use this to be closed View.
821 guiApp->unregisterView(this);
823 if (isFullScreen()) {
824 // Switch off fullscreen before closing.
829 // Make sure the timer time out will not trigger a statusbar update.
830 d.statusbar_timer_.stop();
832 // Saving fullscreen requires additional tweaks in the toolbar code.
833 // It wouldn't also work under linux natively.
834 if (lyxrc.allow_geometry_session) {
839 close_event->accept();
843 void GuiView::dragEnterEvent(QDragEnterEvent * event)
845 if (event->mimeData()->hasUrls())
847 /// \todo Ask lyx-devel is this is enough:
848 /// if (event->mimeData()->hasFormat("text/plain"))
849 /// event->acceptProposedAction();
853 void GuiView::dropEvent(QDropEvent * event)
855 QList<QUrl> files = event->mimeData()->urls();
859 LYXERR(Debug::GUI, "GuiView::dropEvent: got URLs!");
860 for (int i = 0; i != files.size(); ++i) {
861 string const file = os::internal_path(fromqstr(
862 files.at(i).toLocalFile()));
866 string const ext = support::getExtension(file);
867 vector<const Format *> found_formats;
869 // Find all formats that have the correct extension.
870 vector<const Format *> const & import_formats
871 = theConverters().importableFormats();
872 vector<const Format *>::const_iterator it = import_formats.begin();
873 for (; it != import_formats.end(); ++it)
874 if ((*it)->extension() == ext)
875 found_formats.push_back(*it);
878 if (found_formats.size() >= 1) {
879 if (found_formats.size() > 1) {
880 //FIXME: show a dialog to choose the correct importable format
882 "Multiple importable formats found, selecting first");
884 string const arg = found_formats[0]->name() + " " + file;
885 cmd = FuncRequest(LFUN_BUFFER_IMPORT, arg);
888 //FIXME: do we have to explicitly check whether it's a lyx file?
890 "No formats found, trying to open it as a lyx file");
891 cmd = FuncRequest(LFUN_FILE_OPEN, file);
893 // add the functions to the queue
894 guiApp->addToFuncRequestQueue(cmd);
897 // now process the collected functions. We perform the events
898 // asynchronously. This prevents potential problems in case the
899 // BufferView is closed within an event.
900 guiApp->processFuncRequestQueueAsync();
904 void GuiView::message(docstring const & str)
906 if (ForkedProcess::iAmAChild())
909 // call is moved to GUI-thread by GuiProgress
910 d.progress_->appendMessage(toqstr(str));
914 void GuiView::clearMessageText()
916 message(docstring());
920 void GuiView::updateStatusBarMessage(QString const & str)
922 statusBar()->showMessage(str);
923 d.statusbar_timer_.stop();
924 d.statusbar_timer_.start(3000);
928 void GuiView::smallSizedIcons()
930 setIconSize(QSize(d.smallIconSize, d.smallIconSize));
934 void GuiView::normalSizedIcons()
936 setIconSize(QSize(d.normalIconSize, d.normalIconSize));
940 void GuiView::bigSizedIcons()
942 setIconSize(QSize(d.bigIconSize, d.bigIconSize));
946 void GuiView::clearMessage()
948 // FIXME: This code was introduced in r19643 to fix bug #4123. However,
949 // the hasFocus function mostly returns false, even if the focus is on
950 // a workarea in this view.
954 d.statusbar_timer_.stop();
958 void GuiView::updateWindowTitle(GuiWorkArea * wa)
960 if (wa != d.current_work_area_
961 || wa->bufferView().buffer().isInternal())
963 setWindowTitle(qt_("LyX: ") + wa->windowTitle());
964 setWindowIconText(wa->windowIconText());
968 void GuiView::on_currentWorkAreaChanged(GuiWorkArea * wa)
971 disconnectBufferView();
972 connectBufferView(wa->bufferView());
973 connectBuffer(wa->bufferView().buffer());
974 d.current_work_area_ = wa;
975 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
976 this, SLOT(updateWindowTitle(GuiWorkArea *)));
977 updateWindowTitle(wa);
981 // The document settings needs to be reinitialised.
982 updateDialog("document", "");
984 // Buffer-dependent dialogs must be updated. This is done here because
985 // some dialogs require buffer()->text.
990 void GuiView::on_lastWorkAreaRemoved()
993 // We already are in a close event. Nothing more to do.
996 if (d.splitter_->count() > 1)
997 // We have a splitter so don't close anything.
1000 // Reset and updates the dialogs.
1001 d.toc_models_.reset(0);
1002 updateDialog("document", "");
1005 resetWindowTitleAndIconText();
1008 if (lyxrc.open_buffers_in_tabs)
1009 // Nothing more to do, the window should stay open.
1012 if (guiApp->viewIds().size() > 1) {
1018 // On Mac we also close the last window because the application stay
1019 // resident in memory. On other platforms we don't close the last
1020 // window because this would quit the application.
1026 void GuiView::updateStatusBar()
1028 // let the user see the explicit message
1029 if (d.statusbar_timer_.isActive())
1036 void GuiView::showMessage()
1038 QString msg = toqstr(theGuiApp()->viewStatusMessage());
1039 if (msg.isEmpty()) {
1040 BufferView const * bv = currentBufferView();
1042 msg = toqstr(bv->cursor().currentState());
1044 msg = qt_("Welcome to LyX!");
1046 statusBar()->showMessage(msg);
1050 bool GuiView::event(QEvent * e)
1054 // Useful debug code:
1055 //case QEvent::ActivationChange:
1056 //case QEvent::WindowDeactivate:
1057 //case QEvent::Paint:
1058 //case QEvent::Enter:
1059 //case QEvent::Leave:
1060 //case QEvent::HoverEnter:
1061 //case QEvent::HoverLeave:
1062 //case QEvent::HoverMove:
1063 //case QEvent::StatusTip:
1064 //case QEvent::DragEnter:
1065 //case QEvent::DragLeave:
1066 //case QEvent::Drop:
1069 case QEvent::WindowActivate: {
1070 GuiView * old_view = guiApp->currentView();
1071 if (this == old_view) {
1073 return QMainWindow::event(e);
1075 if (old_view && old_view->currentBufferView()) {
1076 // save current selection to the selection buffer to allow
1077 // middle-button paste in this window.
1078 cap::saveSelection(old_view->currentBufferView()->cursor());
1080 guiApp->setCurrentView(this);
1081 if (d.current_work_area_) {
1082 BufferView & bv = d.current_work_area_->bufferView();
1083 connectBufferView(bv);
1084 connectBuffer(bv.buffer());
1085 // The document structure, name and dialogs might have
1086 // changed in another view.
1088 // The document settings needs to be reinitialised.
1089 updateDialog("document", "");
1092 resetWindowTitleAndIconText();
1095 return QMainWindow::event(e);
1098 case QEvent::ShortcutOverride: {
1101 #if (!defined Q_WS_X11) || (QT_VERSION >= 0x040500)
1102 if (isFullScreen() && menuBar()->isHidden()) {
1103 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
1104 // FIXME: we should also try to detect special LyX shortcut such as
1105 // Alt-P and Alt-M. Right now there is a hack in
1106 // GuiWorkArea::processKeySym() that hides again the menubar for
1108 if (ke->modifiers() & Qt::AltModifier && ke->key() != Qt::Key_Alt) {
1110 return QMainWindow::event(e);
1114 return QMainWindow::event(e);
1118 return QMainWindow::event(e);
1122 void GuiView::resetWindowTitleAndIconText()
1124 setWindowTitle(qt_("LyX"));
1125 setWindowIconText(qt_("LyX"));
1128 bool GuiView::focusNextPrevChild(bool /*next*/)
1135 bool GuiView::busy() const
1141 void GuiView::setBusy(bool busy)
1143 bool const busy_before = busy_ > 0;
1144 busy ? ++busy_ : --busy_;
1145 if ((busy_ > 0) == busy_before)
1146 // busy state didn't change
1149 if (d.current_work_area_) {
1150 d.current_work_area_->setUpdatesEnabled(!busy);
1152 d.current_work_area_->stopBlinkingCursor();
1154 d.current_work_area_->startBlinkingCursor();
1158 QApplication::setOverrideCursor(Qt::WaitCursor);
1160 QApplication::restoreOverrideCursor();
1164 GuiWorkArea * GuiView::workArea(int index)
1166 if (TabWorkArea * twa = d.currentTabWorkArea())
1167 if (index < twa->count())
1168 return dynamic_cast<GuiWorkArea *>(twa->widget(index));
1173 GuiWorkArea * GuiView::workArea(Buffer & buffer)
1175 if (currentWorkArea()
1176 && ¤tWorkArea()->bufferView().buffer() == &buffer)
1177 return (GuiWorkArea *) currentWorkArea();
1178 if (TabWorkArea * twa = d.currentTabWorkArea())
1179 return twa->workArea(buffer);
1184 GuiWorkArea * GuiView::addWorkArea(Buffer & buffer)
1186 // Automatically create a TabWorkArea if there are none yet.
1187 TabWorkArea * tab_widget = d.splitter_->count()
1188 ? d.currentTabWorkArea() : addTabWorkArea();
1189 return tab_widget->addWorkArea(buffer, *this);
1193 TabWorkArea * GuiView::addTabWorkArea()
1195 TabWorkArea * twa = new TabWorkArea;
1196 QObject::connect(twa, SIGNAL(currentWorkAreaChanged(GuiWorkArea *)),
1197 this, SLOT(on_currentWorkAreaChanged(GuiWorkArea *)));
1198 QObject::connect(twa, SIGNAL(lastWorkAreaRemoved()),
1199 this, SLOT(on_lastWorkAreaRemoved()));
1201 d.splitter_->addWidget(twa);
1202 d.stack_widget_->setCurrentWidget(d.splitter_);
1207 GuiWorkArea const * GuiView::currentWorkArea() const
1209 return d.current_work_area_;
1213 GuiWorkArea * GuiView::currentWorkArea()
1215 return d.current_work_area_;
1219 GuiWorkArea const * GuiView::currentMainWorkArea() const
1221 if (!d.currentTabWorkArea())
1223 return d.currentTabWorkArea()->currentWorkArea();
1227 GuiWorkArea * GuiView::currentMainWorkArea()
1229 if (!d.currentTabWorkArea())
1231 return d.currentTabWorkArea()->currentWorkArea();
1235 void GuiView::setCurrentWorkArea(GuiWorkArea * wa)
1237 LYXERR(Debug::DEBUG, "Setting current wa: " << wa << endl);
1239 d.current_work_area_ = 0;
1244 // FIXME: I've no clue why this is here and why it accesses
1245 // theGuiApp()->currentView, which might be 0 (bug 6464).
1246 // See also 27525 (vfr).
1247 if (theGuiApp()->currentView() == this
1248 && theGuiApp()->currentView()->currentWorkArea() == wa)
1251 if (currentBufferView())
1252 cap::saveSelection(currentBufferView()->cursor());
1254 theGuiApp()->setCurrentView(this);
1255 d.current_work_area_ = wa;
1257 // We need to reset this now, because it will need to be
1258 // right if the tabWorkArea gets reset in the for loop. We
1259 // will change it back if we aren't in that case.
1260 GuiWorkArea * const old_cmwa = d.current_main_work_area_;
1261 d.current_main_work_area_ = wa;
1263 for (int i = 0; i != d.splitter_->count(); ++i) {
1264 if (d.tabWorkArea(i)->setCurrentWorkArea(wa)) {
1265 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea()
1266 << ", Current main wa: " << currentMainWorkArea());
1271 d.current_main_work_area_ = old_cmwa;
1273 LYXERR(Debug::DEBUG, "This is not a tabbed wa");
1274 on_currentWorkAreaChanged(wa);
1275 BufferView & bv = wa->bufferView();
1276 bv.cursor().fixIfBroken();
1278 wa->setUpdatesEnabled(true);
1279 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() << ", Current main wa: " << currentMainWorkArea());
1283 void GuiView::removeWorkArea(GuiWorkArea * wa)
1285 LASSERT(wa, return);
1286 if (wa == d.current_work_area_) {
1288 disconnectBufferView();
1289 d.current_work_area_ = 0;
1290 d.current_main_work_area_ = 0;
1293 bool found_twa = false;
1294 for (int i = 0; i != d.splitter_->count(); ++i) {
1295 TabWorkArea * twa = d.tabWorkArea(i);
1296 if (twa->removeWorkArea(wa)) {
1297 // Found in this tab group, and deleted the GuiWorkArea.
1299 if (twa->count() != 0) {
1300 if (d.current_work_area_ == 0)
1301 // This means that we are closing the current GuiWorkArea, so
1302 // switch to the next GuiWorkArea in the found TabWorkArea.
1303 setCurrentWorkArea(twa->currentWorkArea());
1305 // No more WorkAreas in this tab group, so delete it.
1312 // It is not a tabbed work area (i.e., the search work area), so it
1313 // should be deleted by other means.
1314 LASSERT(found_twa, /* */);
1316 if (d.current_work_area_ == 0) {
1317 if (d.splitter_->count() != 0) {
1318 TabWorkArea * twa = d.currentTabWorkArea();
1319 setCurrentWorkArea(twa->currentWorkArea());
1321 // No more work areas, switch to the background widget.
1322 setCurrentWorkArea(0);
1328 LayoutBox * GuiView::getLayoutDialog() const
1334 void GuiView::updateLayoutList()
1337 d.layout_->updateContents(false);
1341 void GuiView::updateToolbars()
1343 ToolbarMap::iterator end = d.toolbars_.end();
1344 if (d.current_work_area_) {
1346 d.current_work_area_->bufferView().cursor().inMathed()
1347 && !d.current_work_area_->bufferView().cursor().inRegexped();
1349 lyx::getStatus(FuncRequest(LFUN_LAYOUT_TABULAR)).enabled();
1351 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).enabled() &&
1352 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).onOff(true);
1353 bool const mathmacrotemplate =
1354 lyx::getStatus(FuncRequest(LFUN_IN_MATHMACROTEMPLATE)).enabled();
1356 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1357 it->second->update(math, table, review, mathmacrotemplate);
1359 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1360 it->second->update(false, false, false, false);
1364 void GuiView::setBuffer(Buffer * newBuffer)
1366 LYXERR(Debug::DEBUG, "Setting buffer: " << newBuffer << endl);
1367 LASSERT(newBuffer, return);
1370 GuiWorkArea * wa = workArea(*newBuffer);
1372 newBuffer->masterBuffer()->updateBuffer();
1373 wa = addWorkArea(*newBuffer);
1374 // scroll to the position when the BufferView was last closed
1375 if (lyxrc.use_lastfilepos) {
1376 LastFilePosSection::FilePos filepos =
1377 theSession().lastFilePos().load(newBuffer->fileName());
1378 wa->bufferView().moveToPosition(filepos.pit, filepos.pos, 0, 0);
1381 //Disconnect the old buffer...there's no new one.
1384 connectBuffer(*newBuffer);
1385 connectBufferView(wa->bufferView());
1386 setCurrentWorkArea(wa);
1392 void GuiView::connectBuffer(Buffer & buf)
1394 buf.setGuiDelegate(this);
1398 void GuiView::disconnectBuffer()
1400 if (d.current_work_area_)
1401 d.current_work_area_->bufferView().buffer().setGuiDelegate(0);
1405 void GuiView::connectBufferView(BufferView & bv)
1407 bv.setGuiDelegate(this);
1411 void GuiView::disconnectBufferView()
1413 if (d.current_work_area_)
1414 d.current_work_area_->bufferView().setGuiDelegate(0);
1418 void GuiView::errors(string const & error_type, bool from_master)
1420 BufferView const * const bv = currentBufferView();
1424 ErrorList & el = from_master ?
1425 bv->buffer().masterBuffer()->errorList(error_type) :
1426 bv->buffer().errorList(error_type);
1430 string data = error_type;
1432 data = "from_master|" + error_type;
1433 showDialog("errorlist", data);
1437 void GuiView::updateTocItem(string const & type, DocIterator const & dit)
1439 d.toc_models_.updateItem(toqstr(type), dit);
1443 void GuiView::structureChanged()
1445 d.toc_models_.reset(documentBufferView());
1446 // Navigator needs more than a simple update in this case. It needs to be
1448 updateDialog("toc", "");
1452 void GuiView::updateDialog(string const & name, string const & data)
1454 if (!isDialogVisible(name))
1457 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
1458 if (it == d.dialogs_.end())
1461 Dialog * const dialog = it->second.get();
1462 if (dialog->isVisibleView())
1463 dialog->initialiseParams(data);
1467 BufferView * GuiView::documentBufferView()
1469 return currentMainWorkArea()
1470 ? ¤tMainWorkArea()->bufferView()
1475 BufferView const * GuiView::documentBufferView() const
1477 return currentMainWorkArea()
1478 ? ¤tMainWorkArea()->bufferView()
1483 BufferView * GuiView::currentBufferView()
1485 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1489 BufferView const * GuiView::currentBufferView() const
1491 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1495 #if (QT_VERSION >= 0x040400)
1496 docstring GuiView::GuiViewPrivate::autosaveAndDestroy(
1497 Buffer const * orig, Buffer * buffer)
1499 bool const success = buffer->autoSave();
1501 busyBuffers.remove(orig);
1503 ? _("Automatic save done.")
1504 : _("Automatic save failed!");
1509 void GuiView::autoSave()
1511 LYXERR(Debug::INFO, "Running autoSave()");
1513 Buffer * buffer = documentBufferView()
1514 ? &documentBufferView()->buffer() : 0;
1516 resetAutosaveTimers();
1520 #if (QT_VERSION >= 0x040400)
1521 GuiViewPrivate::busyBuffers.insert(buffer);
1522 QFuture<docstring> f = QtConcurrent::run(GuiViewPrivate::autosaveAndDestroy,
1523 buffer, buffer->clone());
1524 d.autosave_watcher_.setFuture(f);
1528 resetAutosaveTimers();
1532 void GuiView::resetAutosaveTimers()
1535 d.autosave_timeout_.restart();
1539 bool GuiView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1542 Buffer * buf = currentBufferView()
1543 ? ¤tBufferView()->buffer() : 0;
1544 Buffer * doc_buffer = documentBufferView()
1545 ? &(documentBufferView()->buffer()) : 0;
1547 // Check whether we need a buffer
1548 if (!lyxaction.funcHasFlag(cmd.action(), LyXAction::NoBuffer) && !buf) {
1549 // no, exit directly
1550 flag.message(from_utf8(N_("Command not allowed with"
1551 "out any document open")));
1552 flag.setEnabled(false);
1556 if (cmd.origin() == FuncRequest::TOC) {
1557 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
1558 if (!toc || !toc->getStatus(documentBufferView()->cursor(), cmd, flag))
1559 flag.setEnabled(false);
1563 switch(cmd.action()) {
1564 case LFUN_BUFFER_IMPORT:
1567 case LFUN_MASTER_BUFFER_UPDATE:
1568 case LFUN_MASTER_BUFFER_VIEW:
1569 enable = doc_buffer && doc_buffer->parent() != 0
1570 && !d.processing_thread_watcher_.isRunning();
1573 case LFUN_BUFFER_UPDATE:
1574 case LFUN_BUFFER_VIEW: {
1575 if (!doc_buffer || d.processing_thread_watcher_.isRunning()) {
1579 string format = to_utf8(cmd.argument());
1580 if (cmd.argument().empty())
1581 format = doc_buffer->getDefaultOutputFormat();
1582 enable = doc_buffer->isExportableFormat(format);
1586 case LFUN_BUFFER_RELOAD:
1587 enable = doc_buffer && !doc_buffer->isUnnamed()
1588 && doc_buffer->fileName().exists()
1589 && (!doc_buffer->isClean()
1590 || doc_buffer->isExternallyModified(Buffer::timestamp_method));
1593 case LFUN_BUFFER_CHILD_OPEN:
1594 enable = doc_buffer;
1597 case LFUN_BUFFER_WRITE:
1598 enable = doc_buffer && (doc_buffer->isUnnamed() || !doc_buffer->isClean());
1601 //FIXME: This LFUN should be moved to GuiApplication.
1602 case LFUN_BUFFER_WRITE_ALL: {
1603 // We enable the command only if there are some modified buffers
1604 Buffer * first = theBufferList().first();
1609 // We cannot use a for loop as the buffer list is a cycle.
1611 if (!b->isClean()) {
1615 b = theBufferList().next(b);
1616 } while (b != first);
1620 case LFUN_BUFFER_WRITE_AS:
1621 enable = doc_buffer;
1624 case LFUN_BUFFER_CLOSE:
1625 enable = doc_buffer;
1628 case LFUN_BUFFER_CLOSE_ALL:
1629 enable = theBufferList().last() != theBufferList().first();
1632 case LFUN_SPLIT_VIEW:
1633 if (cmd.getArg(0) == "vertical")
1634 enable = doc_buffer && (d.splitter_->count() == 1 ||
1635 d.splitter_->orientation() == Qt::Vertical);
1637 enable = doc_buffer && (d.splitter_->count() == 1 ||
1638 d.splitter_->orientation() == Qt::Horizontal);
1641 case LFUN_CLOSE_TAB_GROUP:
1642 enable = d.currentTabWorkArea();
1645 case LFUN_TOOLBAR_TOGGLE: {
1646 string const name = cmd.getArg(0);
1647 if (GuiToolbar * t = toolbar(name))
1648 flag.setOnOff(t->isVisible());
1651 docstring const msg =
1652 bformat(_("Unknown toolbar \"%1$s\""), from_utf8(name));
1658 case LFUN_DROP_LAYOUTS_CHOICE:
1662 case LFUN_UI_TOGGLE:
1663 flag.setOnOff(isFullScreen());
1666 case LFUN_DIALOG_DISCONNECT_INSET:
1669 case LFUN_DIALOG_HIDE:
1670 // FIXME: should we check if the dialog is shown?
1673 case LFUN_DIALOG_TOGGLE:
1674 flag.setOnOff(isDialogVisible(cmd.getArg(0)));
1675 // fall through to set "enable"
1676 case LFUN_DIALOG_SHOW: {
1677 string const name = cmd.getArg(0);
1679 enable = name == "aboutlyx"
1680 || name == "file" //FIXME: should be removed.
1682 || name == "texinfo"
1683 || name == "progress"
1684 || name == "compare";
1685 else if (name == "print")
1686 enable = doc_buffer->isExportable("dvi")
1687 && lyxrc.print_command != "none";
1688 else if (name == "character" || name == "symbols") {
1689 if (!buf || buf->isReadonly())
1692 Cursor const & cur = currentBufferView()->cursor();
1693 enable = !(cur.inTexted() && cur.paragraph().isPassThru());
1696 else if (name == "latexlog")
1697 enable = FileName(doc_buffer->logName()).isReadableFile();
1698 else if (name == "spellchecker")
1699 enable = theSpellChecker() && !doc_buffer->isReadonly();
1700 else if (name == "vclog")
1701 enable = doc_buffer->lyxvc().inUse();
1705 case LFUN_DIALOG_UPDATE: {
1706 string const name = cmd.getArg(0);
1708 enable = name == "prefs";
1712 case LFUN_COMMAND_EXECUTE:
1714 case LFUN_MENU_OPEN:
1715 // Nothing to check.
1718 case LFUN_COMPLETION_INLINE:
1719 if (!d.current_work_area_
1720 || !d.current_work_area_->completer().inlinePossible(
1721 currentBufferView()->cursor()))
1725 case LFUN_COMPLETION_POPUP:
1726 if (!d.current_work_area_
1727 || !d.current_work_area_->completer().popupPossible(
1728 currentBufferView()->cursor()))
1732 case LFUN_COMPLETION_COMPLETE:
1733 if (!d.current_work_area_
1734 || !d.current_work_area_->completer().inlinePossible(
1735 currentBufferView()->cursor()))
1739 case LFUN_COMPLETION_ACCEPT:
1740 if (!d.current_work_area_
1741 || (!d.current_work_area_->completer().popupVisible()
1742 && !d.current_work_area_->completer().inlineVisible()
1743 && !d.current_work_area_->completer().completionAvailable()))
1747 case LFUN_COMPLETION_CANCEL:
1748 if (!d.current_work_area_
1749 || (!d.current_work_area_->completer().popupVisible()
1750 && !d.current_work_area_->completer().inlineVisible()))
1754 case LFUN_BUFFER_ZOOM_OUT:
1755 enable = doc_buffer && lyxrc.zoom > 10;
1758 case LFUN_BUFFER_ZOOM_IN:
1759 enable = doc_buffer;
1762 case LFUN_BUFFER_NEXT:
1763 case LFUN_BUFFER_PREVIOUS:
1764 // FIXME: should we check is there is an previous or next buffer?
1766 case LFUN_BUFFER_SWITCH:
1767 // toggle on the current buffer, but do not toggle off
1768 // the other ones (is that a good idea?)
1770 && to_utf8(cmd.argument()) == doc_buffer->absFileName())
1771 flag.setOnOff(true);
1774 case LFUN_VC_REGISTER:
1775 enable = doc_buffer && !doc_buffer->lyxvc().inUse();
1777 case LFUN_VC_CHECK_IN:
1778 enable = doc_buffer && doc_buffer->lyxvc().checkInEnabled();
1780 case LFUN_VC_CHECK_OUT:
1781 enable = doc_buffer && doc_buffer->lyxvc().checkOutEnabled();
1783 case LFUN_VC_LOCKING_TOGGLE:
1784 enable = doc_buffer && !doc_buffer->isReadonly()
1785 && doc_buffer->lyxvc().lockingToggleEnabled();
1786 flag.setOnOff(enable && doc_buffer->lyxvc().locking());
1788 case LFUN_VC_REVERT:
1789 enable = doc_buffer && doc_buffer->lyxvc().inUse() && !doc_buffer->isReadonly();
1791 case LFUN_VC_UNDO_LAST:
1792 enable = doc_buffer && doc_buffer->lyxvc().undoLastEnabled();
1794 case LFUN_VC_REPO_UPDATE:
1795 enable = doc_buffer && doc_buffer->lyxvc().repoUpdateEnabled();
1797 case LFUN_VC_COMMAND: {
1798 if (cmd.argument().empty())
1800 if (!doc_buffer && contains(cmd.getArg(0), 'D'))
1804 case LFUN_VC_COMPARE:
1805 enable = doc_buffer && doc_buffer->lyxvc().prepareFileRevisionEnabled();
1808 case LFUN_SERVER_GOTO_FILE_ROW:
1810 case LFUN_FORWARD_SEARCH:
1811 enable = !(lyxrc.forward_search_dvi.empty() && lyxrc.forward_search_pdf.empty());
1819 flag.setEnabled(false);
1825 static FileName selectTemplateFile()
1827 FileDialog dlg(qt_("Select template file"));
1828 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1829 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
1831 FileDialog::Result result = dlg.open(toqstr(lyxrc.template_path),
1832 QStringList(qt_("LyX Documents (*.lyx)")));
1834 if (result.first == FileDialog::Later)
1836 if (result.second.isEmpty())
1838 return FileName(fromqstr(result.second));
1842 Buffer * GuiView::loadDocument(FileName const & filename, bool tolastfiles)
1846 Buffer * newBuffer = 0;
1848 newBuffer = checkAndLoadLyXFile(filename);
1849 } catch (ExceptionMessage const & e) {
1855 message(_("Document not loaded."));
1860 newBuffer->errors("Parse");
1861 setBuffer(newBuffer);
1864 theSession().lastFiles().add(filename);
1871 void GuiView::openDocument(string const & fname)
1873 string initpath = lyxrc.document_path;
1875 if (documentBufferView()) {
1876 string const trypath = documentBufferView()->buffer().filePath();
1877 // If directory is writeable, use this as default.
1878 if (FileName(trypath).isDirWritable())
1884 if (fname.empty()) {
1885 FileDialog dlg(qt_("Select document to open"), LFUN_FILE_OPEN);
1886 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1887 dlg.setButton2(qt_("Examples|#E#e"),
1888 toqstr(addPath(package().system_support().absFileName(), "examples")));
1890 QStringList filter(qt_("LyX Documents (*.lyx)"));
1891 filter << qt_("LyX-1.3.x Documents (*.lyx13)")
1892 << qt_("LyX-1.4.x Documents (*.lyx14)")
1893 << qt_("LyX-1.5.x Documents (*.lyx15)")
1894 << qt_("LyX-1.6.x Documents (*.lyx16)");
1895 FileDialog::Result result =
1896 dlg.open(toqstr(initpath), filter);
1898 if (result.first == FileDialog::Later)
1901 filename = fromqstr(result.second);
1903 // check selected filename
1904 if (filename.empty()) {
1905 message(_("Canceled."));
1911 // get absolute path of file and add ".lyx" to the filename if
1913 FileName const fullname =
1914 fileSearch(string(), filename, "lyx", support::may_not_exist);
1915 if (!fullname.empty())
1916 filename = fullname.absFileName();
1918 if (!fullname.onlyPath().isDirectory()) {
1919 Alert::warning(_("Invalid filename"),
1920 bformat(_("The directory in the given path\n%1$s\ndoes not exist."),
1921 from_utf8(fullname.absFileName())));
1925 // if the file doesn't exist and isn't already open (bug 6645),
1926 // let the user create one
1927 if (!fullname.exists() && !theBufferList().exists(fullname)) {
1928 // the user specifically chose this name. Believe him.
1929 Buffer * const b = newFile(filename, string(), true);
1935 docstring const disp_fn = makeDisplayPath(filename);
1936 message(bformat(_("Opening document %1$s..."), disp_fn));
1939 Buffer * buf = loadDocument(fullname);
1941 str2 = bformat(_("Document %1$s opened."), disp_fn);
1942 if (buf->lyxvc().inUse())
1943 str2 += " " + from_utf8(buf->lyxvc().versionString()) +
1944 " " + _("Version control detected.");
1946 str2 = bformat(_("Could not open document %1$s"), disp_fn);
1951 // FIXME: clean that
1952 static bool import(GuiView * lv, FileName const & filename,
1953 string const & format, ErrorList & errorList)
1955 FileName const lyxfile(support::changeExtension(filename.absFileName(), ".lyx"));
1957 string loader_format;
1958 vector<string> loaders = theConverters().loaders();
1959 if (find(loaders.begin(), loaders.end(), format) == loaders.end()) {
1960 for (vector<string>::const_iterator it = loaders.begin();
1961 it != loaders.end(); ++it) {
1962 if (!theConverters().isReachable(format, *it))
1965 string const tofile =
1966 support::changeExtension(filename.absFileName(),
1967 formats.extension(*it));
1968 if (!theConverters().convert(0, filename, FileName(tofile),
1969 filename, format, *it, errorList))
1971 loader_format = *it;
1974 if (loader_format.empty()) {
1975 frontend::Alert::error(_("Couldn't import file"),
1976 bformat(_("No information for importing the format %1$s."),
1977 formats.prettyName(format)));
1981 loader_format = format;
1983 if (loader_format == "lyx") {
1984 Buffer * buf = lv->loadDocument(lyxfile);
1988 Buffer * const b = newFile(lyxfile.absFileName(), string(), true);
1992 bool as_paragraphs = loader_format == "textparagraph";
1993 string filename2 = (loader_format == format) ? filename.absFileName()
1994 : support::changeExtension(filename.absFileName(),
1995 formats.extension(loader_format));
1996 lv->currentBufferView()->insertPlaintextFile(FileName(filename2),
1998 guiApp->setCurrentView(lv);
1999 lyx::dispatch(FuncRequest(LFUN_MARK_OFF));
2006 void GuiView::importDocument(string const & argument)
2009 string filename = split(argument, format, ' ');
2011 LYXERR(Debug::INFO, format << " file: " << filename);
2013 // need user interaction
2014 if (filename.empty()) {
2015 string initpath = lyxrc.document_path;
2016 if (documentBufferView()) {
2017 string const trypath = documentBufferView()->buffer().filePath();
2018 // If directory is writeable, use this as default.
2019 if (FileName(trypath).isDirWritable())
2023 docstring const text = bformat(_("Select %1$s file to import"),
2024 formats.prettyName(format));
2026 FileDialog dlg(toqstr(text), LFUN_BUFFER_IMPORT);
2027 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2028 dlg.setButton2(qt_("Examples|#E#e"),
2029 toqstr(addPath(package().system_support().absFileName(), "examples")));
2031 docstring filter = formats.prettyName(format);
2034 filter += from_utf8(formats.extension(format));
2037 FileDialog::Result result =
2038 dlg.open(toqstr(initpath), fileFilters(toqstr(filter)));
2040 if (result.first == FileDialog::Later)
2043 filename = fromqstr(result.second);
2045 // check selected filename
2046 if (filename.empty())
2047 message(_("Canceled."));
2050 if (filename.empty())
2053 // get absolute path of file
2054 FileName const fullname(support::makeAbsPath(filename));
2056 FileName const lyxfile(support::changeExtension(fullname.absFileName(), ".lyx"));
2058 // Check if the document already is open
2059 Buffer * buf = theBufferList().getBuffer(lyxfile);
2062 if (!closeBuffer()) {
2063 message(_("Canceled."));
2068 docstring const displaypath = makeDisplayPath(lyxfile.absFileName(), 30);
2070 // if the file exists already, and we didn't do
2071 // -i lyx thefile.lyx, warn
2072 if (lyxfile.exists() && fullname != lyxfile) {
2074 docstring text = bformat(_("The document %1$s already exists.\n\n"
2075 "Do you want to overwrite that document?"), displaypath);
2076 int const ret = Alert::prompt(_("Overwrite document?"),
2077 text, 0, 1, _("&Overwrite"), _("&Cancel"));
2080 message(_("Canceled."));
2085 message(bformat(_("Importing %1$s..."), displaypath));
2086 ErrorList errorList;
2087 if (import(this, fullname, format, errorList))
2088 message(_("imported."));
2090 message(_("file not imported!"));
2092 // FIXME (Abdel 12/08/06): Is there a need to display the error list here?
2096 void GuiView::newDocument(string const & filename, bool from_template)
2098 FileName initpath(lyxrc.document_path);
2099 if (documentBufferView()) {
2100 FileName const trypath(documentBufferView()->buffer().filePath());
2101 // If directory is writeable, use this as default.
2102 if (trypath.isDirWritable())
2106 string templatefile;
2107 if (from_template) {
2108 templatefile = selectTemplateFile().absFileName();
2109 if (templatefile.empty())
2114 if (filename.empty())
2115 b = newUnnamedFile(initpath, to_utf8(_("newfile")), templatefile);
2117 b = newFile(filename, templatefile, true);
2122 // If no new document could be created, it is unsure
2123 // whether there is a valid BufferView.
2124 if (currentBufferView())
2125 // Ensure the cursor is correctly positioned on screen.
2126 currentBufferView()->showCursor();
2130 void GuiView::insertLyXFile(docstring const & fname)
2132 BufferView * bv = documentBufferView();
2137 FileName filename(to_utf8(fname));
2138 if (filename.empty()) {
2139 // Launch a file browser
2141 string initpath = lyxrc.document_path;
2142 string const trypath = bv->buffer().filePath();
2143 // If directory is writeable, use this as default.
2144 if (FileName(trypath).isDirWritable())
2148 FileDialog dlg(qt_("Select LyX document to insert"), LFUN_FILE_INSERT);
2149 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2150 dlg.setButton2(qt_("Examples|#E#e"),
2151 toqstr(addPath(package().system_support().absFileName(),
2154 FileDialog::Result result = dlg.open(toqstr(initpath),
2155 QStringList(qt_("LyX Documents (*.lyx)")));
2157 if (result.first == FileDialog::Later)
2161 filename.set(fromqstr(result.second));
2163 // check selected filename
2164 if (filename.empty()) {
2165 // emit message signal.
2166 message(_("Canceled."));
2171 bv->insertLyXFile(filename);
2172 bv->buffer().errors("Parse");
2176 void GuiView::insertPlaintextFile(docstring const & fname,
2179 BufferView * bv = documentBufferView();
2183 if (!fname.empty() && !FileName::isAbsolute(to_utf8(fname))) {
2184 message(_("Absolute filename expected."));
2189 FileName filename(to_utf8(fname));
2191 if (!filename.empty()) {
2192 bv->insertPlaintextFile(filename, asParagraph);
2196 FileDialog dlg(qt_("Select file to insert"), (asParagraph ?
2197 LFUN_FILE_INSERT_PLAINTEXT_PARA : LFUN_FILE_INSERT_PLAINTEXT));
2199 FileDialog::Result result = dlg.open(toqstr(bv->buffer().filePath()),
2200 QStringList(qt_("All Files (*)")));
2202 if (result.first == FileDialog::Later)
2206 filename.set(fromqstr(result.second));
2208 // check selected filename
2209 if (filename.empty()) {
2210 // emit message signal.
2211 message(_("Canceled."));
2215 bv->insertPlaintextFile(filename, asParagraph);
2219 bool GuiView::renameBuffer(Buffer & b, docstring const & newname)
2221 FileName fname = b.fileName();
2222 FileName const oldname = fname;
2224 if (!newname.empty()) {
2226 fname = support::makeAbsPath(to_utf8(newname), oldname.onlyPath().absFileName());
2228 // Switch to this Buffer.
2231 // No argument? Ask user through dialog.
2233 FileDialog dlg(qt_("Choose a filename to save document as"),
2234 LFUN_BUFFER_WRITE_AS);
2235 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2236 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
2238 if (!isLyXFileName(fname.absFileName()))
2239 fname.changeExtension(".lyx");
2241 FileDialog::Result result =
2242 dlg.save(toqstr(fname.onlyPath().absFileName()),
2243 QStringList(qt_("LyX Documents (*.lyx)")),
2244 toqstr(fname.onlyFileName()));
2246 if (result.first == FileDialog::Later)
2249 fname.set(fromqstr(result.second));
2254 if (!isLyXFileName(fname.absFileName()))
2255 fname.changeExtension(".lyx");
2258 // fname is now the new Buffer location.
2259 if (FileName(fname).exists()) {
2260 docstring const file = makeDisplayPath(fname.absFileName(), 30);
2261 docstring text = bformat(_("The document %1$s already "
2262 "exists.\n\nDo you want to "
2263 "overwrite that document?"),
2265 int const ret = Alert::prompt(_("Overwrite document?"),
2266 text, 0, 2, _("&Overwrite"), _("&Rename"), _("&Cancel"));
2269 case 1: return renameBuffer(b, docstring());
2270 case 2: return false;
2274 return saveBuffer(b, fname);
2278 bool GuiView::saveBuffer(Buffer & b) {
2279 return saveBuffer(b, FileName());
2283 bool GuiView::saveBuffer(Buffer & b, FileName const & fn)
2285 if (workArea(b) && workArea(b)->inDialogMode())
2288 if (fn.empty() && b.isUnnamed())
2289 return renameBuffer(b, docstring());
2295 success = b.saveAs(fn);
2298 theSession().lastFiles().add(b.fileName());
2302 // Switch to this Buffer.
2305 // FIXME: we don't tell the user *WHY* the save failed !!
2306 docstring const file = makeDisplayPath(b.absFileName(), 30);
2307 docstring text = bformat(_("The document %1$s could not be saved.\n\n"
2308 "Do you want to rename the document and "
2309 "try again?"), file);
2310 int const ret = Alert::prompt(_("Rename and save?"),
2311 text, 0, 2, _("&Rename"), _("&Retry"), _("&Cancel"));
2314 if (!renameBuffer(b, docstring()))
2323 return saveBuffer(b);
2327 bool GuiView::hideWorkArea(GuiWorkArea * wa)
2329 return closeWorkArea(wa, false);
2333 bool GuiView::closeWorkArea(GuiWorkArea * wa)
2335 Buffer & buf = wa->bufferView().buffer();
2336 return closeWorkArea(wa, !buf.parent());
2340 bool GuiView::closeBuffer()
2342 GuiWorkArea * wa = currentMainWorkArea();
2343 setCurrentWorkArea(wa);
2344 Buffer & buf = wa->bufferView().buffer();
2345 return wa && closeWorkArea(wa, !buf.parent());
2349 void GuiView::writeSession() const {
2350 GuiWorkArea const * active_wa = currentMainWorkArea();
2351 for (int i = 0; i < d.splitter_->count(); ++i) {
2352 TabWorkArea * twa = d.tabWorkArea(i);
2353 for (int j = 0; j < twa->count(); ++j) {
2354 GuiWorkArea * wa = static_cast<GuiWorkArea *>(twa->widget(j));
2355 Buffer & buf = wa->bufferView().buffer();
2356 theSession().lastOpened().add(buf.fileName(), wa == active_wa);
2362 bool GuiView::closeBufferAll()
2364 // Close the workareas in all other views
2365 QList<int> const ids = guiApp->viewIds();
2366 for (int i = 0; i != ids.size(); ++i) {
2367 if (id_ != ids[i] && !guiApp->view(ids[i]).closeWorkAreaAll())
2371 // Close our own workareas
2372 if (!closeWorkAreaAll())
2375 // Now close the hidden buffers. We prevent hidden buffers from being
2376 // dirty, so we can just close them.
2377 theBufferList().closeAll();
2382 bool GuiView::closeWorkAreaAll()
2384 setCurrentWorkArea(currentMainWorkArea());
2386 // We might be in a situation that there is still a tabWorkArea, but
2387 // there are no tabs anymore. This can happen when we get here after a
2388 // TabWorkArea::lastWorkAreaRemoved() signal. Therefore we count how
2389 // many TabWorkArea's have no documents anymore.
2392 // We have to call count() each time, because it can happen that
2393 // more than one splitter will disappear in one iteration (bug 5998).
2394 for (; d.splitter_->count() > empty_twa; ) {
2395 TabWorkArea * twa = d.tabWorkArea(empty_twa);
2397 if (twa->count() == 0)
2400 setCurrentWorkArea(twa->currentWorkArea());
2401 if (!closeTabWorkArea(twa))
2409 bool GuiView::closeWorkArea(GuiWorkArea * wa, bool close_buffer)
2414 Buffer & buf = wa->bufferView().buffer();
2416 if (close_buffer && GuiViewPrivate::busyBuffers.contains(&buf)) {
2417 Alert::warning(_("Close document"),
2418 _("Document could not be closed because it is being processed by LyX."));
2423 return closeBuffer(buf);
2425 if (!inMultiTabs(wa))
2426 if (!saveBufferIfNeeded(buf, true))
2434 bool GuiView::closeBuffer(Buffer & buf)
2436 // If we are in a close_event all children will be closed in some time,
2437 // so no need to do it here. This will ensure that the children end up
2438 // in the session file in the correct order. If we close the master
2439 // buffer, we can close or release the child buffers here too.
2440 bool success = true;
2442 ListOfBuffers clist = buf.getChildren();
2443 ListOfBuffers::const_iterator it = clist.begin();
2444 ListOfBuffers::const_iterator const bend = clist.end();
2445 for (; it != bend; ++it) {
2446 // If a child is dirty, do not close
2447 // without user intervention
2448 //FIXME: should we look in other tabworkareas?
2449 Buffer * child_buf = *it;
2450 GuiWorkArea * child_wa = workArea(*child_buf);
2452 if (!closeWorkArea(child_wa, true)) {
2457 theBufferList().releaseChild(&buf, child_buf);
2461 // goto bookmark to update bookmark pit.
2462 //FIXME: we should update only the bookmarks related to this buffer!
2463 LYXERR(Debug::DEBUG, "GuiView::closeBuffer()");
2464 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
2465 guiApp->gotoBookmark(i+1, false, false);
2467 if (saveBufferIfNeeded(buf, false)) {
2468 buf.removeAutosaveFile();
2469 theBufferList().release(&buf);
2473 // open all children again to avoid a crash because of dangling
2474 // pointers (bug 6603)
2480 bool GuiView::closeTabWorkArea(TabWorkArea * twa)
2482 while (twa == d.currentTabWorkArea()) {
2483 twa->setCurrentIndex(twa->count()-1);
2485 GuiWorkArea * wa = twa->currentWorkArea();
2486 Buffer & b = wa->bufferView().buffer();
2488 // We only want to close the buffer if the same buffer is not visible
2489 // in another view, and if this is not a child and if we are closing
2490 // a view (not a tabgroup).
2491 bool const close_buffer =
2492 !inOtherView(b) && !b.parent() && closing_;
2494 if (!closeWorkArea(wa, close_buffer))
2501 bool GuiView::saveBufferIfNeeded(Buffer & buf, bool hiding)
2503 if (buf.isClean() || buf.paragraphs().empty())
2506 // Switch to this Buffer.
2511 if (buf.isUnnamed())
2512 file = from_utf8(buf.fileName().onlyFileName());
2514 file = buf.fileName().displayName(30);
2516 // Bring this window to top before asking questions.
2521 if (hiding && buf.isUnnamed()) {
2522 docstring const text = bformat(_("The document %1$s has not been "
2523 "saved yet.\n\nDo you want to save "
2524 "the document?"), file);
2525 ret = Alert::prompt(_("Save new document?"),
2526 text, 0, 1, _("&Save"), _("&Cancel"));
2530 docstring const text = bformat(_("The document %1$s has unsaved changes."
2531 "\n\nDo you want to save the document or discard the changes?"), file);
2532 ret = Alert::prompt(_("Save changed document?"),
2533 text, 0, 2, _("&Save"), _("&Discard"), _("&Cancel"));
2538 if (!saveBuffer(buf))
2542 // If we crash after this we could have no autosave file
2543 // but I guess this is really improbable (Jug).
2544 // Sometimes improbable things happen:
2545 // - see bug http://www.lyx.org/trac/ticket/6587 (ps)
2546 // buf.removeAutosaveFile();
2548 // revert all changes
2559 bool GuiView::inMultiTabs(GuiWorkArea * wa)
2561 Buffer & buf = wa->bufferView().buffer();
2563 for (int i = 0; i != d.splitter_->count(); ++i) {
2564 GuiWorkArea * wa_ = d.tabWorkArea(i)->workArea(buf);
2565 if (wa_ && wa_ != wa)
2568 return inOtherView(buf);
2572 bool GuiView::inOtherView(Buffer & buf)
2574 QList<int> const ids = guiApp->viewIds();
2576 for (int i = 0; i != ids.size(); ++i) {
2580 if (guiApp->view(ids[i]).workArea(buf))
2587 void GuiView::gotoNextOrPreviousBuffer(NextOrPrevious np)
2589 if (!documentBufferView())
2592 if (TabWorkArea * twa = d.currentTabWorkArea()) {
2593 Buffer * const curbuf = &documentBufferView()->buffer();
2594 int nwa = twa->count();
2595 for (int i = 0; i < nwa; ++i) {
2596 if (&workArea(i)->bufferView().buffer() == curbuf) {
2598 if (np == NEXTBUFFER)
2599 next_index = (i == nwa - 1 ? 0 : i + 1);
2601 next_index = (i == 0 ? nwa - 1 : i - 1);
2602 setBuffer(&workArea(next_index)->bufferView().buffer());
2610 /// make sure the document is saved
2611 static bool ensureBufferClean(Buffer * buffer)
2613 LASSERT(buffer, return false);
2614 if (buffer->isClean() && !buffer->isUnnamed())
2617 docstring const file = buffer->fileName().displayName(30);
2620 if (!buffer->isUnnamed()) {
2621 text = bformat(_("The document %1$s has unsaved "
2622 "changes.\n\nDo you want to save "
2623 "the document?"), file);
2624 title = _("Save changed document?");
2627 text = bformat(_("The document %1$s has not been "
2628 "saved yet.\n\nDo you want to save "
2629 "the document?"), file);
2630 title = _("Save new document?");
2632 int const ret = Alert::prompt(title, text, 0, 1, _("&Save"), _("&Cancel"));
2635 dispatch(FuncRequest(LFUN_BUFFER_WRITE));
2637 return buffer->isClean() && !buffer->isUnnamed();
2641 bool GuiView::reloadBuffer(Buffer & buf)
2643 Buffer::ReadStatus status = buf.reload();
2644 return status == Buffer::ReadSuccess;
2648 void GuiView::checkExternallyModifiedBuffers()
2650 BufferList::iterator bit = theBufferList().begin();
2651 BufferList::iterator const bend = theBufferList().end();
2652 for (; bit != bend; ++bit) {
2653 Buffer * buf = *bit;
2654 if (buf->fileName().exists()
2655 && buf->isExternallyModified(Buffer::checksum_method)) {
2656 docstring text = bformat(_("Document \n%1$s\n has been externally modified."
2657 " Reload now? Any local changes will be lost."),
2658 from_utf8(buf->absFileName()));
2659 int const ret = Alert::prompt(_("Reload externally changed document?"),
2660 text, 0, 1, _("&Reload"), _("&Cancel"));
2668 void GuiView::dispatchVC(FuncRequest const & cmd, DispatchResult & dr)
2670 Buffer * buffer = documentBufferView()
2671 ? &(documentBufferView()->buffer()) : 0;
2673 switch (cmd.action()) {
2674 case LFUN_VC_REGISTER:
2675 if (!buffer || !ensureBufferClean(buffer))
2677 if (!buffer->lyxvc().inUse()) {
2678 if (buffer->lyxvc().registrer()) {
2679 reloadBuffer(*buffer);
2680 dr.suppressMessageUpdate();
2685 case LFUN_VC_CHECK_IN:
2686 if (!buffer || !ensureBufferClean(buffer))
2688 if (buffer->lyxvc().inUse() && !buffer->isReadonly()) {
2689 dr.setMessage(buffer->lyxvc().checkIn());
2690 if (!dr.message().empty())
2691 reloadBuffer(*buffer);
2695 case LFUN_VC_CHECK_OUT:
2696 if (!buffer || !ensureBufferClean(buffer))
2698 if (buffer->lyxvc().inUse()) {
2699 dr.setMessage(buffer->lyxvc().checkOut());
2700 reloadBuffer(*buffer);
2704 case LFUN_VC_LOCKING_TOGGLE:
2705 LASSERT(buffer, return);
2706 if (!ensureBufferClean(buffer) || buffer->isReadonly())
2708 if (buffer->lyxvc().inUse()) {
2709 string res = buffer->lyxvc().lockingToggle();
2711 frontend::Alert::error(_("Revision control error."),
2712 _("Error when setting the locking property."));
2715 reloadBuffer(*buffer);
2720 case LFUN_VC_REVERT:
2721 LASSERT(buffer, return);
2722 if (buffer->lyxvc().revert()) {
2723 reloadBuffer(*buffer);
2724 dr.suppressMessageUpdate();
2728 case LFUN_VC_UNDO_LAST:
2729 LASSERT(buffer, return);
2730 buffer->lyxvc().undoLast();
2731 reloadBuffer(*buffer);
2732 dr.suppressMessageUpdate();
2735 case LFUN_VC_REPO_UPDATE:
2736 LASSERT(buffer, return);
2737 if (ensureBufferClean(buffer)) {
2738 dr.setMessage(buffer->lyxvc().repoUpdate());
2739 checkExternallyModifiedBuffers();
2743 case LFUN_VC_COMMAND: {
2744 string flag = cmd.getArg(0);
2745 if (buffer && contains(flag, 'R') && !ensureBufferClean(buffer))
2748 if (contains(flag, 'M')) {
2749 if (!Alert::askForText(message, _("LyX VC: Log Message")))
2752 string path = cmd.getArg(1);
2753 if (contains(path, "$$p") && buffer)
2754 path = subst(path, "$$p", buffer->filePath());
2755 LYXERR(Debug::LYXVC, "Directory: " << path);
2757 if (!pp.isReadableDirectory()) {
2758 lyxerr << _("Directory is not accessible.") << endl;
2761 support::PathChanger p(pp);
2763 string command = cmd.getArg(2);
2764 if (command.empty())
2767 command = subst(command, "$$i", buffer->absFileName());
2768 command = subst(command, "$$p", buffer->filePath());
2770 command = subst(command, "$$m", to_utf8(message));
2771 LYXERR(Debug::LYXVC, "Command: " << command);
2773 one.startscript(Systemcall::Wait, command);
2777 if (contains(flag, 'I'))
2778 buffer->markDirty();
2779 if (contains(flag, 'R'))
2780 reloadBuffer(*buffer);
2785 case LFUN_VC_COMPARE: {
2787 if (cmd.argument().empty()) {
2788 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "comparehistory"));
2792 string rev1 = cmd.getArg(0);
2796 if (!buffer->lyxvc().prepareFileRevision(rev1, f1))
2799 if (isStrInt(rev1) && convert<int>(rev1) <= 0) {
2800 f2 = buffer->absFileName();
2802 string rev2 = cmd.getArg(1);
2806 if (!buffer->lyxvc().prepareFileRevision(rev2, f2))
2810 LYXERR(Debug::LYXVC, "Launching comparison for fetched revisions:\n" <<
2811 f1 << "\n" << f2 << "\n" );
2812 string par = "compare run " + quoteName(f1) + " " + quoteName(f2);
2813 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, par));
2823 void GuiView::openChildDocument(string const & fname)
2825 LASSERT(documentBufferView(), return);
2826 Buffer & buffer = documentBufferView()->buffer();
2827 FileName const filename = support::makeAbsPath(fname, buffer.filePath());
2828 documentBufferView()->saveBookmark(false);
2830 if (theBufferList().exists(filename)) {
2831 child = theBufferList().getBuffer(filename);
2834 message(bformat(_("Opening child document %1$s..."),
2835 makeDisplayPath(filename.absFileName())));
2836 child = loadDocument(filename, false);
2838 // Set the parent name of the child document.
2839 // This makes insertion of citations and references in the child work,
2840 // when the target is in the parent or another child document.
2842 child->setParent(&buffer);
2846 bool GuiView::goToFileRow(string const & argument)
2850 size_t i = argument.find_last_of(' ');
2851 if (i != string::npos) {
2852 file_name = os::internal_path(trim(argument.substr(0, i)));
2853 istringstream is(argument.substr(i + 1));
2858 if (i == string::npos) {
2859 LYXERR0("Wrong argument: " << argument);
2863 string const abstmp = package().temp_dir().absFileName();
2864 string const realtmp = package().temp_dir().realPath();
2865 // We have to use os::path_prefix_is() here, instead of
2866 // simply prefixIs(), because the file name comes from
2867 // an external application and may need case adjustment.
2868 if (os::path_prefix_is(file_name, abstmp, os::CASE_ADJUSTED)
2869 || os::path_prefix_is(file_name, realtmp, os::CASE_ADJUSTED)) {
2870 // Needed by inverse dvi search. If it is a file
2871 // in tmpdir, call the apropriated function.
2872 // If tmpdir is a symlink, we may have the real
2873 // path passed back, so we correct for that.
2874 if (!prefixIs(file_name, abstmp))
2875 file_name = subst(file_name, realtmp, abstmp);
2876 buf = theBufferList().getBufferFromTmp(file_name);
2878 // Must replace extension of the file to be .lyx
2879 // and get full path
2880 FileName const s = fileSearch(string(),
2881 support::changeExtension(file_name, ".lyx"), "lyx");
2882 // Either change buffer or load the file
2883 if (theBufferList().exists(s))
2884 buf = theBufferList().getBuffer(s);
2885 else if (s.exists()) {
2886 buf = loadDocument(s);
2891 _("File does not exist: %1$s"),
2892 makeDisplayPath(file_name)));
2897 documentBufferView()->setCursorFromRow(row);
2902 #if (QT_VERSION >= 0x040400)
2904 docstring GuiView::GuiViewPrivate::runAndDestroy(const T& func, Buffer const * orig, Buffer * buffer, string const & format, string const & msg)
2906 bool const update_unincluded =
2907 buffer->params().maintain_unincluded_children
2908 && !buffer->params().getIncludedChildren().empty();
2909 bool const success = func(format, update_unincluded);
2911 busyBuffers.remove(orig);
2912 if (msg == "preview") {
2914 ? bformat(_("Successful preview of format: %1$s"), from_utf8(format))
2915 : bformat(_("Error while previewing format: %1$s"), from_utf8(format));
2918 ? bformat(_("Successful export to format: %1$s"), from_utf8(format))
2919 : bformat(_("Error while exporting format: %1$s"), from_utf8(format));
2923 docstring GuiView::GuiViewPrivate::compileAndDestroy(Buffer const * orig, Buffer * buffer, string const & format)
2925 bool (Buffer::* mem_func)(std::string const &, bool, bool) const = &Buffer::doExport;
2926 return runAndDestroy(bind(mem_func, buffer, _1, true, _2), orig, buffer, format, "export");
2930 docstring GuiView::GuiViewPrivate::exportAndDestroy(Buffer const * orig, Buffer * buffer, string const & format)
2932 bool (Buffer::* mem_func)(std::string const &, bool, bool) const = &Buffer::doExport;
2933 return runAndDestroy(bind(mem_func, buffer, _1, false, _2), orig, buffer, format, "export");
2937 docstring GuiView::GuiViewPrivate::previewAndDestroy(Buffer const * orig, Buffer * buffer, string const & format)
2939 bool(Buffer::* mem_func)(std::string const &, bool) const = &Buffer::preview;
2940 return runAndDestroy(bind(mem_func, buffer, _1, _2), orig, buffer, format, "preview");
2945 // not used, but the linker needs them
2947 docstring GuiView::GuiViewPrivate::compileAndDestroy(
2948 Buffer const *, Buffer *, string const &)
2954 docstring GuiView::GuiViewPrivate::exportAndDestroy(
2955 Buffer const *, Buffer *, string const &)
2961 docstring GuiView::GuiViewPrivate::previewAndDestroy(
2962 Buffer const *, Buffer *, string const &)
2970 bool GuiView::GuiViewPrivate::asyncBufferProcessing(
2971 string const & argument,
2972 Buffer const * used_buffer,
2973 docstring const & msg,
2974 docstring (*asyncFunc)(Buffer const *, Buffer *, string const &),
2975 bool (Buffer::*syncFunc)(string const &, bool, bool) const,
2976 bool (Buffer::*previewFunc)(string const &, bool) const)
2981 string format = argument;
2983 format = used_buffer->getDefaultOutputFormat();
2985 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
2987 progress_->clearMessages();
2990 GuiViewPrivate::busyBuffers.insert(used_buffer);
2991 QFuture<docstring> f = QtConcurrent::run(
2994 used_buffer->clone(),
2996 setPreviewFuture(f);
2997 last_export_format = used_buffer->bufferFormat();
3000 // We are asynchronous, so we don't know here anything about the success
3004 // TODO check here if it breaks exporting with Qt < 4.4
3005 bool const update_unincluded =
3006 used_buffer->params().maintain_unincluded_children &&
3007 !used_buffer->params().getIncludedChildren().empty();
3008 return (used_buffer->*syncFunc)(format, true, update_unincluded);
3009 } else if (previewFunc) {
3010 return (used_buffer->*previewFunc)(format, false);
3017 void GuiView::dispatchToBufferView(FuncRequest const & cmd, DispatchResult & dr)
3019 BufferView * bv = currentBufferView();
3022 // Let the current BufferView dispatch its own actions.
3023 bv->dispatch(cmd, dr);
3024 if (dr.dispatched())
3027 // Try with the document BufferView dispatch if any.
3028 BufferView * doc_bv = documentBufferView();
3030 doc_bv->dispatch(cmd, dr);
3031 if (dr.dispatched())
3035 // Then let the current Cursor dispatch its own actions.
3036 bv->cursor().dispatch(cmd);
3038 // update completion. We do it here and not in
3039 // processKeySym to avoid another redraw just for a
3040 // changed inline completion
3041 if (cmd.origin() == FuncRequest::KEYBOARD) {
3042 if (cmd.action() == LFUN_SELF_INSERT
3043 || (cmd.action() == LFUN_ERT_INSERT && bv->cursor().inMathed()))
3044 updateCompletion(bv->cursor(), true, true);
3045 else if (cmd.action() == LFUN_CHAR_DELETE_BACKWARD)
3046 updateCompletion(bv->cursor(), false, true);
3048 updateCompletion(bv->cursor(), false, false);
3051 dr = bv->cursor().result();
3055 void GuiView::dispatch(FuncRequest const & cmd, DispatchResult & dr)
3057 BufferView * bv = currentBufferView();
3058 // By default we won't need any update.
3059 dr.screenUpdate(Update::None);
3060 // assume cmd will be dispatched
3061 dr.dispatched(true);
3063 Buffer * doc_buffer = documentBufferView()
3064 ? &(documentBufferView()->buffer()) : 0;
3066 if (cmd.origin() == FuncRequest::TOC) {
3067 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
3068 // FIXME: do we need to pass a DispatchResult object here?
3069 toc->doDispatch(bv->cursor(), cmd);
3073 string const argument = to_utf8(cmd.argument());
3075 switch(cmd.action()) {
3076 case LFUN_BUFFER_CHILD_OPEN:
3077 openChildDocument(to_utf8(cmd.argument()));
3080 case LFUN_BUFFER_IMPORT:
3081 importDocument(to_utf8(cmd.argument()));
3084 case LFUN_BUFFER_EXPORT: {
3087 // GCC only sees strfwd.h when building merged
3088 if (::lyx::operator==(cmd.argument(), "custom")) {
3089 dispatch(FuncRequest(LFUN_DIALOG_SHOW, "sendto"), dr);
3092 #if QT_VERSION < 0x040400
3093 if (!doc_buffer->doExport(argument, false)) {
3095 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
3099 /* TODO/Review: Is it a problem to also export the children?
3100 See the update_unincluded flag */
3101 d.asyncBufferProcessing(argument,
3104 &GuiViewPrivate::exportAndDestroy,
3107 // TODO Inform user about success
3112 case LFUN_BUFFER_UPDATE: {
3113 d.asyncBufferProcessing(argument,
3116 &GuiViewPrivate::compileAndDestroy,
3121 case LFUN_BUFFER_VIEW: {
3122 d.asyncBufferProcessing(argument,
3124 _("Previewing ..."),
3125 &GuiViewPrivate::previewAndDestroy,
3130 case LFUN_MASTER_BUFFER_UPDATE: {
3131 d.asyncBufferProcessing(argument,
3132 (doc_buffer ? doc_buffer->masterBuffer() : 0),
3134 &GuiViewPrivate::compileAndDestroy,
3139 case LFUN_MASTER_BUFFER_VIEW: {
3140 d.asyncBufferProcessing(argument,
3141 (doc_buffer ? doc_buffer->masterBuffer() : 0),
3143 &GuiViewPrivate::previewAndDestroy,
3144 0, &Buffer::preview);
3147 case LFUN_BUFFER_SWITCH: {
3148 string const file_name = to_utf8(cmd.argument());
3149 if (!FileName::isAbsolute(file_name)) {
3151 dr.setMessage(_("Absolute filename expected."));
3155 Buffer * buffer = theBufferList().getBuffer(FileName(file_name));
3158 dr.setMessage(_("Document not loaded"));
3162 // Do we open or switch to the buffer in this view ?
3163 if (workArea(*buffer)
3164 || lyxrc.open_buffers_in_tabs || !documentBufferView()) {
3169 // Look for the buffer in other views
3170 QList<int> const ids = guiApp->viewIds();
3172 for (; i != ids.size(); ++i) {
3173 GuiView & gv = guiApp->view(ids[i]);
3174 if (gv.workArea(*buffer)) {
3175 gv.activateWindow();
3176 gv.setBuffer(buffer);
3181 // If necessary, open a new window as a last resort
3182 if (i == ids.size()) {
3183 lyx::dispatch(FuncRequest(LFUN_WINDOW_NEW));
3189 case LFUN_BUFFER_NEXT:
3190 gotoNextOrPreviousBuffer(NEXTBUFFER);
3193 case LFUN_BUFFER_PREVIOUS:
3194 gotoNextOrPreviousBuffer(PREVBUFFER);
3197 case LFUN_COMMAND_EXECUTE: {
3198 bool const show_it = cmd.argument() != "off";
3199 // FIXME: this is a hack, "minibuffer" should not be
3201 if (GuiToolbar * t = toolbar("minibuffer")) {
3202 t->setVisible(show_it);
3203 if (show_it && t->commandBuffer())
3204 t->commandBuffer()->setFocus();
3208 case LFUN_DROP_LAYOUTS_CHOICE:
3209 d.layout_->showPopup();
3212 case LFUN_MENU_OPEN:
3213 if (QMenu * menu = guiApp->menus().menu(toqstr(cmd.argument()), *this))
3214 menu->exec(QCursor::pos());
3217 case LFUN_FILE_INSERT:
3218 insertLyXFile(cmd.argument());
3221 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
3222 insertPlaintextFile(cmd.argument(), true);
3225 case LFUN_FILE_INSERT_PLAINTEXT:
3226 insertPlaintextFile(cmd.argument(), false);
3229 case LFUN_BUFFER_RELOAD: {
3230 LASSERT(doc_buffer, break);
3233 if (!doc_buffer->isClean()) {
3234 docstring const file =
3235 makeDisplayPath(doc_buffer->absFileName(), 20);
3236 docstring text = bformat(_("Any changes will be lost. "
3237 "Are you sure you want to revert to the saved version "
3238 "of the document %1$s?"), file);
3239 ret = Alert::prompt(_("Revert to saved document?"),
3240 text, 1, 1, _("&Revert"), _("&Cancel"));
3244 doc_buffer->markClean();
3245 reloadBuffer(*doc_buffer);
3246 dr.forceBufferUpdate();
3251 case LFUN_BUFFER_WRITE:
3252 LASSERT(doc_buffer, break);
3253 saveBuffer(*doc_buffer);
3256 case LFUN_BUFFER_WRITE_AS:
3257 LASSERT(doc_buffer, break);
3258 renameBuffer(*doc_buffer, cmd.argument());
3261 case LFUN_BUFFER_WRITE_ALL: {
3262 Buffer * first = theBufferList().first();
3265 message(_("Saving all documents..."));
3266 // We cannot use a for loop as the buffer list cycles.
3269 if (!b->isClean()) {
3271 LYXERR(Debug::ACTION, "Saved " << b->absFileName());
3273 b = theBufferList().next(b);
3274 } while (b != first);
3275 dr.setMessage(_("All documents saved."));
3279 case LFUN_BUFFER_CLOSE:
3283 case LFUN_BUFFER_CLOSE_ALL:
3287 case LFUN_TOOLBAR_TOGGLE: {
3288 string const name = cmd.getArg(0);
3289 if (GuiToolbar * t = toolbar(name))
3294 case LFUN_DIALOG_UPDATE: {
3295 string const name = to_utf8(cmd.argument());
3296 if (name == "prefs" || name == "document")
3297 updateDialog(name, string());
3298 else if (name == "paragraph")
3299 lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
3300 else if (currentBufferView()) {
3301 Inset * inset = currentBufferView()->editedInset(name);
3302 // Can only update a dialog connected to an existing inset
3304 // FIXME: get rid of this indirection; GuiView ask the inset
3305 // if he is kind enough to update itself...
3306 FuncRequest fr(LFUN_INSET_DIALOG_UPDATE, cmd.argument());
3307 //FIXME: pass DispatchResult here?
3308 inset->dispatch(currentBufferView()->cursor(), fr);
3314 case LFUN_DIALOG_TOGGLE: {
3315 FuncCode const func_code = isDialogVisible(cmd.getArg(0))
3316 ? LFUN_DIALOG_HIDE : LFUN_DIALOG_SHOW;
3317 dispatch(FuncRequest(func_code, cmd.argument()), dr);
3321 case LFUN_DIALOG_DISCONNECT_INSET:
3322 disconnectDialog(to_utf8(cmd.argument()));
3325 case LFUN_DIALOG_HIDE: {
3326 guiApp->hideDialogs(to_utf8(cmd.argument()), 0);
3330 case LFUN_DIALOG_SHOW: {
3331 string const name = cmd.getArg(0);
3332 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
3334 if (name == "character") {
3335 data = freefont2string();
3337 showDialog("character", data);
3338 } else if (name == "latexlog") {
3339 Buffer::LogType type;
3340 string const logfile = doc_buffer->logName(&type);
3342 case Buffer::latexlog:
3345 case Buffer::buildlog:
3349 data += Lexer::quoteString(logfile);
3350 showDialog("log", data);
3351 } else if (name == "vclog") {
3352 string const data = "vc " +
3353 Lexer::quoteString(doc_buffer->lyxvc().getLogFile());
3354 showDialog("log", data);
3355 } else if (name == "symbols") {
3356 data = bv->cursor().getEncoding()->name();
3358 showDialog("symbols", data);
3360 } else if (name == "prefs" && isFullScreen()) {
3361 lfunUiToggle("fullscreen");
3362 showDialog("prefs", data);
3364 showDialog(name, data);
3369 dr.setMessage(cmd.argument());
3372 case LFUN_UI_TOGGLE: {
3373 string arg = cmd.getArg(0);
3374 if (!lfunUiToggle(arg)) {
3375 docstring const msg = "ui-toggle " + _("%1$s unknown command!");
3376 dr.setMessage(bformat(msg, from_utf8(arg)));
3378 // Make sure the keyboard focus stays in the work area.
3383 case LFUN_SPLIT_VIEW: {
3384 LASSERT(doc_buffer, break);
3385 string const orientation = cmd.getArg(0);
3386 d.splitter_->setOrientation(orientation == "vertical"
3387 ? Qt::Vertical : Qt::Horizontal);
3388 TabWorkArea * twa = addTabWorkArea();
3389 GuiWorkArea * wa = twa->addWorkArea(*doc_buffer, *this);
3390 setCurrentWorkArea(wa);
3393 case LFUN_CLOSE_TAB_GROUP:
3394 if (TabWorkArea * twa = d.currentTabWorkArea()) {
3395 closeTabWorkArea(twa);
3396 d.current_work_area_ = 0;
3397 twa = d.currentTabWorkArea();
3398 // Switch to the next GuiWorkArea in the found TabWorkArea.
3400 // Make sure the work area is up to date.
3401 setCurrentWorkArea(twa->currentWorkArea());
3403 setCurrentWorkArea(0);
3408 case LFUN_COMPLETION_INLINE:
3409 if (d.current_work_area_)
3410 d.current_work_area_->completer().showInline();
3413 case LFUN_COMPLETION_POPUP:
3414 if (d.current_work_area_)
3415 d.current_work_area_->completer().showPopup();
3419 case LFUN_COMPLETION_COMPLETE:
3420 if (d.current_work_area_)
3421 d.current_work_area_->completer().tab();
3424 case LFUN_COMPLETION_CANCEL:
3425 if (d.current_work_area_) {
3426 if (d.current_work_area_->completer().popupVisible())
3427 d.current_work_area_->completer().hidePopup();
3429 d.current_work_area_->completer().hideInline();
3433 case LFUN_COMPLETION_ACCEPT:
3434 if (d.current_work_area_)
3435 d.current_work_area_->completer().activate();
3438 case LFUN_BUFFER_ZOOM_IN:
3439 case LFUN_BUFFER_ZOOM_OUT:
3440 if (cmd.argument().empty()) {
3441 if (cmd.action() == LFUN_BUFFER_ZOOM_IN)
3446 lyxrc.zoom += convert<int>(cmd.argument());
3448 if (lyxrc.zoom < 10)
3451 // The global QPixmapCache is used in GuiPainter to cache text
3452 // painting so we must reset it.
3453 QPixmapCache::clear();
3454 guiApp->fontLoader().update();
3455 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
3458 case LFUN_VC_REGISTER:
3459 case LFUN_VC_CHECK_IN:
3460 case LFUN_VC_CHECK_OUT:
3461 case LFUN_VC_REPO_UPDATE:
3462 case LFUN_VC_LOCKING_TOGGLE:
3463 case LFUN_VC_REVERT:
3464 case LFUN_VC_UNDO_LAST:
3465 case LFUN_VC_COMMAND:
3466 case LFUN_VC_COMPARE:
3467 dispatchVC(cmd, dr);
3470 case LFUN_SERVER_GOTO_FILE_ROW:
3471 goToFileRow(to_utf8(cmd.argument()));
3474 case LFUN_FORWARD_SEARCH: {
3475 Buffer const * doc_master = doc_buffer->masterBuffer();
3476 FileName const path(doc_master->temppath());
3477 string const texname = doc_master->isChild(doc_buffer)
3478 ? DocFileName(changeExtension(
3479 doc_buffer->absFileName(),
3480 "tex")).mangledFileName()
3481 : doc_buffer->latexName();
3482 string const mastername =
3483 removeExtension(doc_master->latexName());
3484 FileName const dviname(addName(path.absFileName(),
3485 addExtension(mastername, "dvi")));
3486 FileName const pdfname(addName(path.absFileName(),
3487 addExtension(mastername, "pdf")));
3488 if (!dviname.exists() && !pdfname.exists()) {
3489 dr.setMessage(_("Please, preview the document first."));
3492 string outname = dviname.onlyFileName();
3493 string command = lyxrc.forward_search_dvi;
3494 if (!dviname.exists() ||
3495 pdfname.lastModified() > dviname.lastModified()) {
3496 outname = pdfname.onlyFileName();
3497 command = lyxrc.forward_search_pdf;
3500 int row = doc_buffer->texrow().getRowFromIdPos(bv->cursor().paragraph().id(), bv->cursor().pos());
3501 LYXERR(Debug::ACTION, "Forward search: row:" << row
3502 << " id:" << bv->cursor().paragraph().id());
3503 if (!row || command.empty()) {
3504 dr.setMessage(_("Couldn't proceed."));
3507 string texrow = convert<string>(row);
3509 command = subst(command, "$$n", texrow);
3510 command = subst(command, "$$t", texname);
3511 command = subst(command, "$$o", outname);
3513 PathChanger p(path);
3515 one.startscript(Systemcall::DontWait, command);
3519 // The LFUN must be for one of BufferView, Buffer or Cursor;
3521 dispatchToBufferView(cmd, dr);
3525 // Part of automatic menu appearance feature.
3526 if (isFullScreen()) {
3527 if (menuBar()->isVisible() && lyxrc.full_screen_menubar)
3529 if (statusBar()->isVisible())
3530 statusBar()->hide();
3535 bool GuiView::lfunUiToggle(string const & ui_component)
3537 if (ui_component == "scrollbar") {
3538 // hide() is of no help
3539 if (d.current_work_area_->verticalScrollBarPolicy() ==
3540 Qt::ScrollBarAlwaysOff)
3542 d.current_work_area_->setVerticalScrollBarPolicy(
3543 Qt::ScrollBarAsNeeded);
3545 d.current_work_area_->setVerticalScrollBarPolicy(
3546 Qt::ScrollBarAlwaysOff);
3547 } else if (ui_component == "statusbar") {
3548 statusBar()->setVisible(!statusBar()->isVisible());
3549 } else if (ui_component == "menubar") {
3550 menuBar()->setVisible(!menuBar()->isVisible());
3552 #if QT_VERSION >= 0x040300
3553 if (ui_component == "frame") {
3555 getContentsMargins(&l, &t, &r, &b);
3556 //are the frames in default state?
3557 d.current_work_area_->setFrameStyle(QFrame::NoFrame);
3559 setContentsMargins(-2, -2, -2, -2);
3561 setContentsMargins(0, 0, 0, 0);
3565 if (ui_component == "fullscreen") {
3573 void GuiView::toggleFullScreen()
3575 if (isFullScreen()) {
3576 for (int i = 0; i != d.splitter_->count(); ++i)
3577 d.tabWorkArea(i)->setFullScreen(false);
3578 #if QT_VERSION >= 0x040300
3579 setContentsMargins(0, 0, 0, 0);
3581 setWindowState(windowState() ^ Qt::WindowFullScreen);
3584 statusBar()->show();
3587 hideDialogs("prefs", 0);
3588 for (int i = 0; i != d.splitter_->count(); ++i)
3589 d.tabWorkArea(i)->setFullScreen(true);
3590 #if QT_VERSION >= 0x040300
3591 setContentsMargins(-2, -2, -2, -2);
3594 setWindowState(windowState() ^ Qt::WindowFullScreen);
3595 statusBar()->hide();
3596 if (lyxrc.full_screen_menubar)
3598 if (lyxrc.full_screen_toolbars) {
3599 ToolbarMap::iterator end = d.toolbars_.end();
3600 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
3605 // give dialogs like the TOC a chance to adapt
3610 Buffer const * GuiView::updateInset(Inset const * inset)
3615 Buffer const * inset_buffer = &(inset->buffer());
3617 for (int i = 0; i != d.splitter_->count(); ++i) {
3618 GuiWorkArea * wa = d.tabWorkArea(i)->currentWorkArea();
3621 Buffer const * buffer = &(wa->bufferView().buffer());
3622 if (inset_buffer == buffer)
3623 wa->scheduleRedraw();
3625 return inset_buffer;
3629 void GuiView::restartCursor()
3631 /* When we move around, or type, it's nice to be able to see
3632 * the cursor immediately after the keypress.
3634 if (d.current_work_area_)
3635 d.current_work_area_->startBlinkingCursor();
3637 // Take this occasion to update the other GUI elements.
3643 void GuiView::updateCompletion(Cursor & cur, bool start, bool keep)
3645 if (d.current_work_area_)
3646 d.current_work_area_->completer().updateVisibility(cur, start, keep);
3651 // This list should be kept in sync with the list of insets in
3652 // src/insets/Inset.cpp. I.e., if a dialog goes with an inset, the
3653 // dialog should have the same name as the inset.
3654 // Changes should be also recorded in LFUN_DIALOG_SHOW doxygen
3655 // docs in LyXAction.cpp.
3657 char const * const dialognames[] = {
3659 "aboutlyx", "bibitem", "bibtex", "box", "branch", "changes", "character",
3660 "citation", "compare", "comparehistory", "document", "errorlist", "ert",
3661 "external", "file", "findreplace", "findreplaceadv", "float", "graphics",
3662 "href", "include", "index", "index_print", "info", "listings", "label", "line",
3663 "log", "mathdelimiter", "mathmatrix", "mathspace", "nomenclature",
3664 "nomencl_print", "note", "paragraph", "phantom", "prefs", "print", "ref",
3665 "sendto", "space", "spellchecker", "symbols", "tabular", "tabularcreate",
3666 "thesaurus", "texinfo", "toc", "view-source", "vspace", "wrap", "progress"};
3668 char const * const * const end_dialognames =
3669 dialognames + (sizeof(dialognames) / sizeof(char *));
3673 cmpCStr(char const * name) : name_(name) {}
3674 bool operator()(char const * other) {
3675 return strcmp(other, name_) == 0;
3682 bool isValidName(string const & name)
3684 return find_if(dialognames, end_dialognames,
3685 cmpCStr(name.c_str())) != end_dialognames;
3691 void GuiView::resetDialogs()
3693 // Make sure that no LFUN uses any GuiView.
3694 guiApp->setCurrentView(0);
3698 constructToolbars();
3699 guiApp->menus().fillMenuBar(menuBar(), this, false);
3700 d.layout_->updateContents(true);
3701 // Now update controls with current buffer.
3702 guiApp->setCurrentView(this);
3708 Dialog * GuiView::findOrBuild(string const & name, bool hide_it)
3710 if (!isValidName(name))
3713 map<string, DialogPtr>::iterator it = d.dialogs_.find(name);
3715 if (it != d.dialogs_.end()) {
3717 it->second->hideView();
3718 return it->second.get();
3721 Dialog * dialog = build(name);
3722 d.dialogs_[name].reset(dialog);
3723 if (lyxrc.allow_geometry_session)
3724 dialog->restoreSession();
3731 void GuiView::showDialog(string const & name, string const & data,
3734 triggerShowDialog(toqstr(name), toqstr(data), inset);
3738 void GuiView::doShowDialog(QString const & qname, QString const & qdata,
3744 const string name = fromqstr(qname);
3745 const string data = fromqstr(qdata);
3749 Dialog * dialog = findOrBuild(name, false);
3751 bool const visible = dialog->isVisibleView();
3752 dialog->showData(data);
3753 if (inset && currentBufferView())
3754 currentBufferView()->editInset(name, inset);
3755 // We only set the focus to the new dialog if it was not yet
3756 // visible in order not to change the existing previous behaviour
3758 // activateWindow is needed for floating dockviews
3759 dialog->asQWidget()->raise();
3760 dialog->asQWidget()->activateWindow();
3761 dialog->asQWidget()->setFocus();
3765 catch (ExceptionMessage const & ex) {
3773 bool GuiView::isDialogVisible(string const & name) const
3775 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3776 if (it == d.dialogs_.end())
3778 return it->second.get()->isVisibleView() && !it->second.get()->isClosing();
3782 void GuiView::hideDialog(string const & name, Inset * inset)
3784 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3785 if (it == d.dialogs_.end())
3789 if (!currentBufferView())
3791 if (inset != currentBufferView()->editedInset(name))
3795 Dialog * const dialog = it->second.get();
3796 if (dialog->isVisibleView())
3798 if (currentBufferView())
3799 currentBufferView()->editInset(name, 0);
3803 void GuiView::disconnectDialog(string const & name)
3805 if (!isValidName(name))
3807 if (currentBufferView())
3808 currentBufferView()->editInset(name, 0);
3812 void GuiView::hideAll() const
3814 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
3815 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3817 for(; it != end; ++it)
3818 it->second->hideView();
3822 void GuiView::updateDialogs()
3824 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
3825 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3827 for(; it != end; ++it) {
3828 Dialog * dialog = it->second.get();
3830 if (dialog->needBufferOpen() && !documentBufferView())
3831 hideDialog(fromqstr(dialog->name()), 0);
3832 else if (dialog->isVisibleView())
3833 dialog->checkStatus();
3840 Dialog * createDialog(GuiView & lv, string const & name);
3842 // will be replaced by a proper factory...
3843 Dialog * createGuiAbout(GuiView & lv);
3844 Dialog * createGuiBibtex(GuiView & lv);
3845 Dialog * createGuiChanges(GuiView & lv);
3846 Dialog * createGuiCharacter(GuiView & lv);
3847 Dialog * createGuiCitation(GuiView & lv);
3848 Dialog * createGuiCompare(GuiView & lv);
3849 Dialog * createGuiCompareHistory(GuiView & lv);
3850 Dialog * createGuiDelimiter(GuiView & lv);
3851 Dialog * createGuiDocument(GuiView & lv);
3852 Dialog * createGuiErrorList(GuiView & lv);
3853 Dialog * createGuiExternal(GuiView & lv);
3854 Dialog * createGuiGraphics(GuiView & lv);
3855 Dialog * createGuiInclude(GuiView & lv);
3856 Dialog * createGuiIndex(GuiView & lv);
3857 Dialog * createGuiListings(GuiView & lv);
3858 Dialog * createGuiLog(GuiView & lv);
3859 Dialog * createGuiMathMatrix(GuiView & lv);
3860 Dialog * createGuiNote(GuiView & lv);
3861 Dialog * createGuiParagraph(GuiView & lv);
3862 Dialog * createGuiPhantom(GuiView & lv);
3863 Dialog * createGuiPreferences(GuiView & lv);
3864 Dialog * createGuiPrint(GuiView & lv);
3865 Dialog * createGuiPrintindex(GuiView & lv);
3866 Dialog * createGuiRef(GuiView & lv);
3867 Dialog * createGuiSearch(GuiView & lv);
3868 Dialog * createGuiSearchAdv(GuiView & lv);
3869 Dialog * createGuiSendTo(GuiView & lv);
3870 Dialog * createGuiShowFile(GuiView & lv);
3871 Dialog * createGuiSpellchecker(GuiView & lv);
3872 Dialog * createGuiSymbols(GuiView & lv);
3873 Dialog * createGuiTabularCreate(GuiView & lv);
3874 Dialog * createGuiTexInfo(GuiView & lv);
3875 Dialog * createGuiToc(GuiView & lv);
3876 Dialog * createGuiThesaurus(GuiView & lv);
3877 Dialog * createGuiViewSource(GuiView & lv);
3878 Dialog * createGuiWrap(GuiView & lv);
3879 Dialog * createGuiProgressView(GuiView & lv);
3883 Dialog * GuiView::build(string const & name)
3885 LASSERT(isValidName(name), return 0);
3887 Dialog * dialog = createDialog(*this, name);
3891 if (name == "aboutlyx")
3892 return createGuiAbout(*this);
3893 if (name == "bibtex")
3894 return createGuiBibtex(*this);
3895 if (name == "changes")
3896 return createGuiChanges(*this);
3897 if (name == "character")
3898 return createGuiCharacter(*this);
3899 if (name == "citation")
3900 return createGuiCitation(*this);
3901 if (name == "compare")
3902 return createGuiCompare(*this);
3903 if (name == "comparehistory")
3904 return createGuiCompareHistory(*this);
3905 if (name == "document")
3906 return createGuiDocument(*this);
3907 if (name == "errorlist")
3908 return createGuiErrorList(*this);
3909 if (name == "external")
3910 return createGuiExternal(*this);
3912 return createGuiShowFile(*this);
3913 if (name == "findreplace")
3914 return createGuiSearch(*this);
3915 if (name == "findreplaceadv")
3916 return createGuiSearchAdv(*this);
3917 if (name == "graphics")
3918 return createGuiGraphics(*this);
3919 if (name == "include")
3920 return createGuiInclude(*this);
3921 if (name == "index")
3922 return createGuiIndex(*this);
3923 if (name == "index_print")
3924 return createGuiPrintindex(*this);
3925 if (name == "listings")
3926 return createGuiListings(*this);
3928 return createGuiLog(*this);
3929 if (name == "mathdelimiter")
3930 return createGuiDelimiter(*this);
3931 if (name == "mathmatrix")
3932 return createGuiMathMatrix(*this);
3934 return createGuiNote(*this);
3935 if (name == "paragraph")
3936 return createGuiParagraph(*this);
3937 if (name == "phantom")
3938 return createGuiPhantom(*this);
3939 if (name == "prefs")
3940 return createGuiPreferences(*this);
3941 if (name == "print")
3942 return createGuiPrint(*this);
3944 return createGuiRef(*this);
3945 if (name == "sendto")
3946 return createGuiSendTo(*this);
3947 if (name == "spellchecker")
3948 return createGuiSpellchecker(*this);
3949 if (name == "symbols")
3950 return createGuiSymbols(*this);
3951 if (name == "tabularcreate")
3952 return createGuiTabularCreate(*this);
3953 if (name == "texinfo")
3954 return createGuiTexInfo(*this);
3955 if (name == "thesaurus")
3956 return createGuiThesaurus(*this);
3958 return createGuiToc(*this);
3959 if (name == "view-source")
3960 return createGuiViewSource(*this);
3962 return createGuiWrap(*this);
3963 if (name == "progress")
3964 return createGuiProgressView(*this);
3970 } // namespace frontend
3973 #include "moc_GuiView.cpp"