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;
1518 #if (QT_VERSION >= 0x040400)
1519 GuiViewPrivate::busyBuffers.insert(buffer);
1520 QFuture<docstring> f = QtConcurrent::run(GuiViewPrivate::autosaveAndDestroy,
1521 buffer, buffer->clone());
1522 d.autosave_watcher_.setFuture(f);
1526 resetAutosaveTimers();
1530 void GuiView::resetAutosaveTimers()
1533 d.autosave_timeout_.restart();
1537 bool GuiView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1540 Buffer * buf = currentBufferView()
1541 ? ¤tBufferView()->buffer() : 0;
1542 Buffer * doc_buffer = documentBufferView()
1543 ? &(documentBufferView()->buffer()) : 0;
1545 // Check whether we need a buffer
1546 if (!lyxaction.funcHasFlag(cmd.action(), LyXAction::NoBuffer) && !buf) {
1547 // no, exit directly
1548 flag.message(from_utf8(N_("Command not allowed with"
1549 "out any document open")));
1550 flag.setEnabled(false);
1554 if (cmd.origin() == FuncRequest::TOC) {
1555 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
1556 if (!toc || !toc->getStatus(documentBufferView()->cursor(), cmd, flag))
1557 flag.setEnabled(false);
1561 switch(cmd.action()) {
1562 case LFUN_BUFFER_IMPORT:
1565 case LFUN_MASTER_BUFFER_UPDATE:
1566 case LFUN_MASTER_BUFFER_VIEW:
1567 enable = doc_buffer && doc_buffer->parent() != 0
1568 && !d.processing_thread_watcher_.isRunning();
1571 case LFUN_BUFFER_UPDATE:
1572 case LFUN_BUFFER_VIEW: {
1573 if (!doc_buffer || d.processing_thread_watcher_.isRunning()) {
1577 string format = to_utf8(cmd.argument());
1578 if (cmd.argument().empty())
1579 format = doc_buffer->getDefaultOutputFormat();
1580 enable = doc_buffer->isExportableFormat(format);
1584 case LFUN_BUFFER_RELOAD:
1585 enable = doc_buffer && !doc_buffer->isUnnamed()
1586 && doc_buffer->fileName().exists()
1587 && (!doc_buffer->isClean()
1588 || doc_buffer->isExternallyModified(Buffer::timestamp_method));
1591 case LFUN_BUFFER_CHILD_OPEN:
1592 enable = doc_buffer;
1595 case LFUN_BUFFER_WRITE:
1596 enable = doc_buffer && (doc_buffer->isUnnamed() || !doc_buffer->isClean());
1599 //FIXME: This LFUN should be moved to GuiApplication.
1600 case LFUN_BUFFER_WRITE_ALL: {
1601 // We enable the command only if there are some modified buffers
1602 Buffer * first = theBufferList().first();
1607 // We cannot use a for loop as the buffer list is a cycle.
1609 if (!b->isClean()) {
1613 b = theBufferList().next(b);
1614 } while (b != first);
1618 case LFUN_BUFFER_WRITE_AS:
1619 enable = doc_buffer;
1622 case LFUN_BUFFER_CLOSE:
1623 enable = doc_buffer;
1626 case LFUN_BUFFER_CLOSE_ALL:
1627 enable = theBufferList().last() != theBufferList().first();
1630 case LFUN_SPLIT_VIEW:
1631 if (cmd.getArg(0) == "vertical")
1632 enable = doc_buffer && (d.splitter_->count() == 1 ||
1633 d.splitter_->orientation() == Qt::Vertical);
1635 enable = doc_buffer && (d.splitter_->count() == 1 ||
1636 d.splitter_->orientation() == Qt::Horizontal);
1639 case LFUN_CLOSE_TAB_GROUP:
1640 enable = d.currentTabWorkArea();
1643 case LFUN_TOOLBAR_TOGGLE: {
1644 string const name = cmd.getArg(0);
1645 if (GuiToolbar * t = toolbar(name))
1646 flag.setOnOff(t->isVisible());
1649 docstring const msg =
1650 bformat(_("Unknown toolbar \"%1$s\""), from_utf8(name));
1656 case LFUN_DROP_LAYOUTS_CHOICE:
1660 case LFUN_UI_TOGGLE:
1661 flag.setOnOff(isFullScreen());
1664 case LFUN_DIALOG_DISCONNECT_INSET:
1667 case LFUN_DIALOG_HIDE:
1668 // FIXME: should we check if the dialog is shown?
1671 case LFUN_DIALOG_TOGGLE:
1672 flag.setOnOff(isDialogVisible(cmd.getArg(0)));
1673 // fall through to set "enable"
1674 case LFUN_DIALOG_SHOW: {
1675 string const name = cmd.getArg(0);
1677 enable = name == "aboutlyx"
1678 || name == "file" //FIXME: should be removed.
1680 || name == "texinfo"
1681 || name == "progress"
1682 || name == "compare";
1683 else if (name == "print")
1684 enable = doc_buffer->isExportable("dvi")
1685 && lyxrc.print_command != "none";
1686 else if (name == "character" || name == "symbols") {
1687 if (!buf || buf->isReadonly())
1690 Cursor const & cur = currentBufferView()->cursor();
1691 enable = !(cur.inTexted() && cur.paragraph().isPassThru());
1694 else if (name == "latexlog")
1695 enable = FileName(doc_buffer->logName()).isReadableFile();
1696 else if (name == "spellchecker")
1697 enable = theSpellChecker() && !doc_buffer->isReadonly();
1698 else if (name == "vclog")
1699 enable = doc_buffer->lyxvc().inUse();
1703 case LFUN_DIALOG_UPDATE: {
1704 string const name = cmd.getArg(0);
1706 enable = name == "prefs";
1710 case LFUN_COMMAND_EXECUTE:
1712 case LFUN_MENU_OPEN:
1713 // Nothing to check.
1716 case LFUN_COMPLETION_INLINE:
1717 if (!d.current_work_area_
1718 || !d.current_work_area_->completer().inlinePossible(
1719 currentBufferView()->cursor()))
1723 case LFUN_COMPLETION_POPUP:
1724 if (!d.current_work_area_
1725 || !d.current_work_area_->completer().popupPossible(
1726 currentBufferView()->cursor()))
1730 case LFUN_COMPLETION_COMPLETE:
1731 if (!d.current_work_area_
1732 || !d.current_work_area_->completer().inlinePossible(
1733 currentBufferView()->cursor()))
1737 case LFUN_COMPLETION_ACCEPT:
1738 if (!d.current_work_area_
1739 || (!d.current_work_area_->completer().popupVisible()
1740 && !d.current_work_area_->completer().inlineVisible()
1741 && !d.current_work_area_->completer().completionAvailable()))
1745 case LFUN_COMPLETION_CANCEL:
1746 if (!d.current_work_area_
1747 || (!d.current_work_area_->completer().popupVisible()
1748 && !d.current_work_area_->completer().inlineVisible()))
1752 case LFUN_BUFFER_ZOOM_OUT:
1753 enable = doc_buffer && lyxrc.zoom > 10;
1756 case LFUN_BUFFER_ZOOM_IN:
1757 enable = doc_buffer;
1760 case LFUN_BUFFER_NEXT:
1761 case LFUN_BUFFER_PREVIOUS:
1762 // FIXME: should we check is there is an previous or next buffer?
1764 case LFUN_BUFFER_SWITCH:
1765 // toggle on the current buffer, but do not toggle off
1766 // the other ones (is that a good idea?)
1768 && to_utf8(cmd.argument()) == doc_buffer->absFileName())
1769 flag.setOnOff(true);
1772 case LFUN_VC_REGISTER:
1773 enable = doc_buffer && !doc_buffer->lyxvc().inUse();
1775 case LFUN_VC_CHECK_IN:
1776 enable = doc_buffer && doc_buffer->lyxvc().checkInEnabled();
1778 case LFUN_VC_CHECK_OUT:
1779 enable = doc_buffer && doc_buffer->lyxvc().checkOutEnabled();
1781 case LFUN_VC_LOCKING_TOGGLE:
1782 enable = doc_buffer && !doc_buffer->isReadonly()
1783 && doc_buffer->lyxvc().lockingToggleEnabled();
1784 flag.setOnOff(enable && doc_buffer->lyxvc().locking());
1786 case LFUN_VC_REVERT:
1787 enable = doc_buffer && doc_buffer->lyxvc().inUse() && !doc_buffer->isReadonly();
1789 case LFUN_VC_UNDO_LAST:
1790 enable = doc_buffer && doc_buffer->lyxvc().undoLastEnabled();
1792 case LFUN_VC_REPO_UPDATE:
1793 enable = doc_buffer && doc_buffer->lyxvc().repoUpdateEnabled();
1795 case LFUN_VC_COMMAND: {
1796 if (cmd.argument().empty())
1798 if (!doc_buffer && contains(cmd.getArg(0), 'D'))
1802 case LFUN_VC_COMPARE:
1803 enable = doc_buffer && doc_buffer->lyxvc().prepareFileRevisionEnabled();
1806 case LFUN_SERVER_GOTO_FILE_ROW:
1808 case LFUN_FORWARD_SEARCH:
1809 enable = !(lyxrc.forward_search_dvi.empty() && lyxrc.forward_search_pdf.empty());
1817 flag.setEnabled(false);
1823 static FileName selectTemplateFile()
1825 FileDialog dlg(qt_("Select template file"));
1826 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1827 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
1829 FileDialog::Result result = dlg.open(toqstr(lyxrc.template_path),
1830 QStringList(qt_("LyX Documents (*.lyx)")));
1832 if (result.first == FileDialog::Later)
1834 if (result.second.isEmpty())
1836 return FileName(fromqstr(result.second));
1840 Buffer * GuiView::loadDocument(FileName const & filename, bool tolastfiles)
1844 Buffer * newBuffer = 0;
1846 newBuffer = checkAndLoadLyXFile(filename);
1847 } catch (ExceptionMessage const & e) {
1853 message(_("Document not loaded."));
1858 newBuffer->errors("Parse");
1859 setBuffer(newBuffer);
1862 theSession().lastFiles().add(filename);
1869 void GuiView::openDocument(string const & fname)
1871 string initpath = lyxrc.document_path;
1873 if (documentBufferView()) {
1874 string const trypath = documentBufferView()->buffer().filePath();
1875 // If directory is writeable, use this as default.
1876 if (FileName(trypath).isDirWritable())
1882 if (fname.empty()) {
1883 FileDialog dlg(qt_("Select document to open"), LFUN_FILE_OPEN);
1884 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1885 dlg.setButton2(qt_("Examples|#E#e"),
1886 toqstr(addPath(package().system_support().absFileName(), "examples")));
1888 QStringList filter(qt_("LyX Documents (*.lyx)"));
1889 filter << qt_("LyX-1.3.x Documents (*.lyx13)")
1890 << qt_("LyX-1.4.x Documents (*.lyx14)")
1891 << qt_("LyX-1.5.x Documents (*.lyx15)")
1892 << qt_("LyX-1.6.x Documents (*.lyx16)");
1893 FileDialog::Result result =
1894 dlg.open(toqstr(initpath), filter);
1896 if (result.first == FileDialog::Later)
1899 filename = fromqstr(result.second);
1901 // check selected filename
1902 if (filename.empty()) {
1903 message(_("Canceled."));
1909 // get absolute path of file and add ".lyx" to the filename if
1911 FileName const fullname =
1912 fileSearch(string(), filename, "lyx", support::may_not_exist);
1913 if (!fullname.empty())
1914 filename = fullname.absFileName();
1916 if (!fullname.onlyPath().isDirectory()) {
1917 Alert::warning(_("Invalid filename"),
1918 bformat(_("The directory in the given path\n%1$s\ndoes not exist."),
1919 from_utf8(fullname.absFileName())));
1923 // if the file doesn't exist and isn't already open (bug 6645),
1924 // let the user create one
1925 if (!fullname.exists() && !theBufferList().exists(fullname)) {
1926 // the user specifically chose this name. Believe him.
1927 Buffer * const b = newFile(filename, string(), true);
1933 docstring const disp_fn = makeDisplayPath(filename);
1934 message(bformat(_("Opening document %1$s..."), disp_fn));
1937 Buffer * buf = loadDocument(fullname);
1939 str2 = bformat(_("Document %1$s opened."), disp_fn);
1940 if (buf->lyxvc().inUse())
1941 str2 += " " + from_utf8(buf->lyxvc().versionString()) +
1942 " " + _("Version control detected.");
1944 str2 = bformat(_("Could not open document %1$s"), disp_fn);
1949 // FIXME: clean that
1950 static bool import(GuiView * lv, FileName const & filename,
1951 string const & format, ErrorList & errorList)
1953 FileName const lyxfile(support::changeExtension(filename.absFileName(), ".lyx"));
1955 string loader_format;
1956 vector<string> loaders = theConverters().loaders();
1957 if (find(loaders.begin(), loaders.end(), format) == loaders.end()) {
1958 for (vector<string>::const_iterator it = loaders.begin();
1959 it != loaders.end(); ++it) {
1960 if (!theConverters().isReachable(format, *it))
1963 string const tofile =
1964 support::changeExtension(filename.absFileName(),
1965 formats.extension(*it));
1966 if (!theConverters().convert(0, filename, FileName(tofile),
1967 filename, format, *it, errorList))
1969 loader_format = *it;
1972 if (loader_format.empty()) {
1973 frontend::Alert::error(_("Couldn't import file"),
1974 bformat(_("No information for importing the format %1$s."),
1975 formats.prettyName(format)));
1979 loader_format = format;
1981 if (loader_format == "lyx") {
1982 Buffer * buf = lv->loadDocument(lyxfile);
1986 Buffer * const b = newFile(lyxfile.absFileName(), string(), true);
1990 bool as_paragraphs = loader_format == "textparagraph";
1991 string filename2 = (loader_format == format) ? filename.absFileName()
1992 : support::changeExtension(filename.absFileName(),
1993 formats.extension(loader_format));
1994 lv->currentBufferView()->insertPlaintextFile(FileName(filename2),
1996 guiApp->setCurrentView(lv);
1997 lyx::dispatch(FuncRequest(LFUN_MARK_OFF));
2004 void GuiView::importDocument(string const & argument)
2007 string filename = split(argument, format, ' ');
2009 LYXERR(Debug::INFO, format << " file: " << filename);
2011 // need user interaction
2012 if (filename.empty()) {
2013 string initpath = lyxrc.document_path;
2014 if (documentBufferView()) {
2015 string const trypath = documentBufferView()->buffer().filePath();
2016 // If directory is writeable, use this as default.
2017 if (FileName(trypath).isDirWritable())
2021 docstring const text = bformat(_("Select %1$s file to import"),
2022 formats.prettyName(format));
2024 FileDialog dlg(toqstr(text), LFUN_BUFFER_IMPORT);
2025 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2026 dlg.setButton2(qt_("Examples|#E#e"),
2027 toqstr(addPath(package().system_support().absFileName(), "examples")));
2029 docstring filter = formats.prettyName(format);
2032 filter += from_utf8(formats.extension(format));
2035 FileDialog::Result result =
2036 dlg.open(toqstr(initpath), fileFilters(toqstr(filter)));
2038 if (result.first == FileDialog::Later)
2041 filename = fromqstr(result.second);
2043 // check selected filename
2044 if (filename.empty())
2045 message(_("Canceled."));
2048 if (filename.empty())
2051 // get absolute path of file
2052 FileName const fullname(support::makeAbsPath(filename));
2054 FileName const lyxfile(support::changeExtension(fullname.absFileName(), ".lyx"));
2056 // Check if the document already is open
2057 Buffer * buf = theBufferList().getBuffer(lyxfile);
2060 if (!closeBuffer()) {
2061 message(_("Canceled."));
2066 docstring const displaypath = makeDisplayPath(lyxfile.absFileName(), 30);
2068 // if the file exists already, and we didn't do
2069 // -i lyx thefile.lyx, warn
2070 if (lyxfile.exists() && fullname != lyxfile) {
2072 docstring text = bformat(_("The document %1$s already exists.\n\n"
2073 "Do you want to overwrite that document?"), displaypath);
2074 int const ret = Alert::prompt(_("Overwrite document?"),
2075 text, 0, 1, _("&Overwrite"), _("&Cancel"));
2078 message(_("Canceled."));
2083 message(bformat(_("Importing %1$s..."), displaypath));
2084 ErrorList errorList;
2085 if (import(this, fullname, format, errorList))
2086 message(_("imported."));
2088 message(_("file not imported!"));
2090 // FIXME (Abdel 12/08/06): Is there a need to display the error list here?
2094 void GuiView::newDocument(string const & filename, bool from_template)
2096 FileName initpath(lyxrc.document_path);
2097 if (documentBufferView()) {
2098 FileName const trypath(documentBufferView()->buffer().filePath());
2099 // If directory is writeable, use this as default.
2100 if (trypath.isDirWritable())
2104 string templatefile;
2105 if (from_template) {
2106 templatefile = selectTemplateFile().absFileName();
2107 if (templatefile.empty())
2112 if (filename.empty())
2113 b = newUnnamedFile(initpath, to_utf8(_("newfile")), templatefile);
2115 b = newFile(filename, templatefile, true);
2120 // If no new document could be created, it is unsure
2121 // whether there is a valid BufferView.
2122 if (currentBufferView())
2123 // Ensure the cursor is correctly positioned on screen.
2124 currentBufferView()->showCursor();
2128 void GuiView::insertLyXFile(docstring const & fname)
2130 BufferView * bv = documentBufferView();
2135 FileName filename(to_utf8(fname));
2136 if (filename.empty()) {
2137 // Launch a file browser
2139 string initpath = lyxrc.document_path;
2140 string const trypath = bv->buffer().filePath();
2141 // If directory is writeable, use this as default.
2142 if (FileName(trypath).isDirWritable())
2146 FileDialog dlg(qt_("Select LyX document to insert"), LFUN_FILE_INSERT);
2147 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2148 dlg.setButton2(qt_("Examples|#E#e"),
2149 toqstr(addPath(package().system_support().absFileName(),
2152 FileDialog::Result result = dlg.open(toqstr(initpath),
2153 QStringList(qt_("LyX Documents (*.lyx)")));
2155 if (result.first == FileDialog::Later)
2159 filename.set(fromqstr(result.second));
2161 // check selected filename
2162 if (filename.empty()) {
2163 // emit message signal.
2164 message(_("Canceled."));
2169 bv->insertLyXFile(filename);
2170 bv->buffer().errors("Parse");
2174 void GuiView::insertPlaintextFile(docstring const & fname,
2177 BufferView * bv = documentBufferView();
2181 if (!fname.empty() && !FileName::isAbsolute(to_utf8(fname))) {
2182 message(_("Absolute filename expected."));
2187 FileName filename(to_utf8(fname));
2189 if (!filename.empty()) {
2190 bv->insertPlaintextFile(filename, asParagraph);
2194 FileDialog dlg(qt_("Select file to insert"), (asParagraph ?
2195 LFUN_FILE_INSERT_PLAINTEXT_PARA : LFUN_FILE_INSERT_PLAINTEXT));
2197 FileDialog::Result result = dlg.open(toqstr(bv->buffer().filePath()),
2198 QStringList(qt_("All Files (*)")));
2200 if (result.first == FileDialog::Later)
2204 filename.set(fromqstr(result.second));
2206 // check selected filename
2207 if (filename.empty()) {
2208 // emit message signal.
2209 message(_("Canceled."));
2213 bv->insertPlaintextFile(filename, asParagraph);
2217 bool GuiView::renameBuffer(Buffer & b, docstring const & newname)
2219 FileName fname = b.fileName();
2220 FileName const oldname = fname;
2222 if (!newname.empty()) {
2224 fname = support::makeAbsPath(to_utf8(newname), oldname.onlyPath().absFileName());
2226 // Switch to this Buffer.
2229 // No argument? Ask user through dialog.
2231 FileDialog dlg(qt_("Choose a filename to save document as"),
2232 LFUN_BUFFER_WRITE_AS);
2233 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2234 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
2236 if (!isLyXFileName(fname.absFileName()))
2237 fname.changeExtension(".lyx");
2239 FileDialog::Result result =
2240 dlg.save(toqstr(fname.onlyPath().absFileName()),
2241 QStringList(qt_("LyX Documents (*.lyx)")),
2242 toqstr(fname.onlyFileName()));
2244 if (result.first == FileDialog::Later)
2247 fname.set(fromqstr(result.second));
2252 if (!isLyXFileName(fname.absFileName()))
2253 fname.changeExtension(".lyx");
2256 // fname is now the new Buffer location.
2257 if (FileName(fname).exists()) {
2258 docstring const file = makeDisplayPath(fname.absFileName(), 30);
2259 docstring text = bformat(_("The document %1$s already "
2260 "exists.\n\nDo you want to "
2261 "overwrite that document?"),
2263 int const ret = Alert::prompt(_("Overwrite document?"),
2264 text, 0, 2, _("&Overwrite"), _("&Rename"), _("&Cancel"));
2267 case 1: return renameBuffer(b, docstring());
2268 case 2: return false;
2272 return saveBuffer(b, fname);
2276 bool GuiView::saveBuffer(Buffer & b) {
2277 return saveBuffer(b, FileName());
2281 bool GuiView::saveBuffer(Buffer & b, FileName const & fn)
2283 if (workArea(b) && workArea(b)->inDialogMode())
2286 if (fn.empty() && b.isUnnamed())
2287 return renameBuffer(b, docstring());
2293 success = b.saveAs(fn);
2296 theSession().lastFiles().add(b.fileName());
2300 // Switch to this Buffer.
2303 // FIXME: we don't tell the user *WHY* the save failed !!
2304 docstring const file = makeDisplayPath(b.absFileName(), 30);
2305 docstring text = bformat(_("The document %1$s could not be saved.\n\n"
2306 "Do you want to rename the document and "
2307 "try again?"), file);
2308 int const ret = Alert::prompt(_("Rename and save?"),
2309 text, 0, 2, _("&Rename"), _("&Retry"), _("&Cancel"));
2312 if (!renameBuffer(b, docstring()))
2321 return saveBuffer(b);
2325 bool GuiView::hideWorkArea(GuiWorkArea * wa)
2327 return closeWorkArea(wa, false);
2331 bool GuiView::closeWorkArea(GuiWorkArea * wa)
2333 Buffer & buf = wa->bufferView().buffer();
2334 return closeWorkArea(wa, !buf.parent());
2338 bool GuiView::closeBuffer()
2340 GuiWorkArea * wa = currentMainWorkArea();
2341 setCurrentWorkArea(wa);
2342 Buffer & buf = wa->bufferView().buffer();
2343 return wa && closeWorkArea(wa, !buf.parent());
2347 void GuiView::writeSession() const {
2348 GuiWorkArea const * active_wa = currentMainWorkArea();
2349 for (int i = 0; i < d.splitter_->count(); ++i) {
2350 TabWorkArea * twa = d.tabWorkArea(i);
2351 for (int j = 0; j < twa->count(); ++j) {
2352 GuiWorkArea * wa = static_cast<GuiWorkArea *>(twa->widget(j));
2353 Buffer & buf = wa->bufferView().buffer();
2354 theSession().lastOpened().add(buf.fileName(), wa == active_wa);
2360 bool GuiView::closeBufferAll()
2362 // Close the workareas in all other views
2363 QList<int> const ids = guiApp->viewIds();
2364 for (int i = 0; i != ids.size(); ++i) {
2365 if (id_ != ids[i] && !guiApp->view(ids[i]).closeWorkAreaAll())
2369 // Close our own workareas
2370 if (!closeWorkAreaAll())
2373 // Now close the hidden buffers. We prevent hidden buffers from being
2374 // dirty, so we can just close them.
2375 theBufferList().closeAll();
2380 bool GuiView::closeWorkAreaAll()
2382 setCurrentWorkArea(currentMainWorkArea());
2384 // We might be in a situation that there is still a tabWorkArea, but
2385 // there are no tabs anymore. This can happen when we get here after a
2386 // TabWorkArea::lastWorkAreaRemoved() signal. Therefore we count how
2387 // many TabWorkArea's have no documents anymore.
2390 // We have to call count() each time, because it can happen that
2391 // more than one splitter will disappear in one iteration (bug 5998).
2392 for (; d.splitter_->count() > empty_twa; ) {
2393 TabWorkArea * twa = d.tabWorkArea(empty_twa);
2395 if (twa->count() == 0)
2398 setCurrentWorkArea(twa->currentWorkArea());
2399 if (!closeTabWorkArea(twa))
2407 bool GuiView::closeWorkArea(GuiWorkArea * wa, bool close_buffer)
2412 Buffer & buf = wa->bufferView().buffer();
2414 if (close_buffer && GuiViewPrivate::busyBuffers.contains(&buf)) {
2415 Alert::warning(_("Close document"),
2416 _("Document could not be closed because it is being processed by LyX."));
2421 return closeBuffer(buf);
2423 if (!inMultiTabs(wa))
2424 if (!saveBufferIfNeeded(buf, true))
2432 bool GuiView::closeBuffer(Buffer & buf)
2434 // If we are in a close_event all children will be closed in some time,
2435 // so no need to do it here. This will ensure that the children end up
2436 // in the session file in the correct order. If we close the master
2437 // buffer, we can close or release the child buffers here too.
2438 bool success = true;
2440 ListOfBuffers clist = buf.getChildren();
2441 ListOfBuffers::const_iterator it = clist.begin();
2442 ListOfBuffers::const_iterator const bend = clist.end();
2443 for (; it != bend; ++it) {
2444 // If a child is dirty, do not close
2445 // without user intervention
2446 //FIXME: should we look in other tabworkareas?
2447 Buffer * child_buf = *it;
2448 GuiWorkArea * child_wa = workArea(*child_buf);
2450 if (!closeWorkArea(child_wa, true)) {
2455 theBufferList().releaseChild(&buf, child_buf);
2459 // goto bookmark to update bookmark pit.
2460 //FIXME: we should update only the bookmarks related to this buffer!
2461 LYXERR(Debug::DEBUG, "GuiView::closeBuffer()");
2462 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
2463 guiApp->gotoBookmark(i+1, false, false);
2465 if (saveBufferIfNeeded(buf, false)) {
2466 buf.removeAutosaveFile();
2467 theBufferList().release(&buf);
2471 // open all children again to avoid a crash because of dangling
2472 // pointers (bug 6603)
2478 bool GuiView::closeTabWorkArea(TabWorkArea * twa)
2480 while (twa == d.currentTabWorkArea()) {
2481 twa->setCurrentIndex(twa->count()-1);
2483 GuiWorkArea * wa = twa->currentWorkArea();
2484 Buffer & b = wa->bufferView().buffer();
2486 // We only want to close the buffer if the same buffer is not visible
2487 // in another view, and if this is not a child and if we are closing
2488 // a view (not a tabgroup).
2489 bool const close_buffer =
2490 !inOtherView(b) && !b.parent() && closing_;
2492 if (!closeWorkArea(wa, close_buffer))
2499 bool GuiView::saveBufferIfNeeded(Buffer & buf, bool hiding)
2501 if (buf.isClean() || buf.paragraphs().empty())
2504 // Switch to this Buffer.
2509 if (buf.isUnnamed())
2510 file = from_utf8(buf.fileName().onlyFileName());
2512 file = buf.fileName().displayName(30);
2514 // Bring this window to top before asking questions.
2519 if (hiding && buf.isUnnamed()) {
2520 docstring const text = bformat(_("The document %1$s has not been "
2521 "saved yet.\n\nDo you want to save "
2522 "the document?"), file);
2523 ret = Alert::prompt(_("Save new document?"),
2524 text, 0, 1, _("&Save"), _("&Cancel"));
2528 docstring const text = bformat(_("The document %1$s has unsaved changes."
2529 "\n\nDo you want to save the document or discard the changes?"), file);
2530 ret = Alert::prompt(_("Save changed document?"),
2531 text, 0, 2, _("&Save"), _("&Discard"), _("&Cancel"));
2536 if (!saveBuffer(buf))
2540 // If we crash after this we could have no autosave file
2541 // but I guess this is really improbable (Jug).
2542 // Sometimes improbable things happen:
2543 // - see bug http://www.lyx.org/trac/ticket/6587 (ps)
2544 // buf.removeAutosaveFile();
2546 // revert all changes
2557 bool GuiView::inMultiTabs(GuiWorkArea * wa)
2559 Buffer & buf = wa->bufferView().buffer();
2561 for (int i = 0; i != d.splitter_->count(); ++i) {
2562 GuiWorkArea * wa_ = d.tabWorkArea(i)->workArea(buf);
2563 if (wa_ && wa_ != wa)
2566 return inOtherView(buf);
2570 bool GuiView::inOtherView(Buffer & buf)
2572 QList<int> const ids = guiApp->viewIds();
2574 for (int i = 0; i != ids.size(); ++i) {
2578 if (guiApp->view(ids[i]).workArea(buf))
2585 void GuiView::gotoNextOrPreviousBuffer(NextOrPrevious np)
2587 if (!documentBufferView())
2590 if (TabWorkArea * twa = d.currentTabWorkArea()) {
2591 Buffer * const curbuf = &documentBufferView()->buffer();
2592 int nwa = twa->count();
2593 for (int i = 0; i < nwa; ++i) {
2594 if (&workArea(i)->bufferView().buffer() == curbuf) {
2596 if (np == NEXTBUFFER)
2597 next_index = (i == nwa - 1 ? 0 : i + 1);
2599 next_index = (i == 0 ? nwa - 1 : i - 1);
2600 setBuffer(&workArea(next_index)->bufferView().buffer());
2608 /// make sure the document is saved
2609 static bool ensureBufferClean(Buffer * buffer)
2611 LASSERT(buffer, return false);
2612 if (buffer->isClean() && !buffer->isUnnamed())
2615 docstring const file = buffer->fileName().displayName(30);
2618 if (!buffer->isUnnamed()) {
2619 text = bformat(_("The document %1$s has unsaved "
2620 "changes.\n\nDo you want to save "
2621 "the document?"), file);
2622 title = _("Save changed document?");
2625 text = bformat(_("The document %1$s has not been "
2626 "saved yet.\n\nDo you want to save "
2627 "the document?"), file);
2628 title = _("Save new document?");
2630 int const ret = Alert::prompt(title, text, 0, 1, _("&Save"), _("&Cancel"));
2633 dispatch(FuncRequest(LFUN_BUFFER_WRITE));
2635 return buffer->isClean() && !buffer->isUnnamed();
2639 bool GuiView::reloadBuffer(Buffer & buf)
2641 Buffer::ReadStatus status = buf.reload();
2642 return status == Buffer::ReadSuccess;
2646 void GuiView::checkExternallyModifiedBuffers()
2648 BufferList::iterator bit = theBufferList().begin();
2649 BufferList::iterator const bend = theBufferList().end();
2650 for (; bit != bend; ++bit) {
2651 Buffer * buf = *bit;
2652 if (buf->fileName().exists()
2653 && buf->isExternallyModified(Buffer::checksum_method)) {
2654 docstring text = bformat(_("Document \n%1$s\n has been externally modified."
2655 " Reload now? Any local changes will be lost."),
2656 from_utf8(buf->absFileName()));
2657 int const ret = Alert::prompt(_("Reload externally changed document?"),
2658 text, 0, 1, _("&Reload"), _("&Cancel"));
2666 void GuiView::dispatchVC(FuncRequest const & cmd, DispatchResult & dr)
2668 Buffer * buffer = documentBufferView()
2669 ? &(documentBufferView()->buffer()) : 0;
2671 switch (cmd.action()) {
2672 case LFUN_VC_REGISTER:
2673 if (!buffer || !ensureBufferClean(buffer))
2675 if (!buffer->lyxvc().inUse()) {
2676 if (buffer->lyxvc().registrer()) {
2677 reloadBuffer(*buffer);
2678 dr.suppressMessageUpdate();
2683 case LFUN_VC_CHECK_IN:
2684 if (!buffer || !ensureBufferClean(buffer))
2686 if (buffer->lyxvc().inUse() && !buffer->isReadonly()) {
2687 dr.setMessage(buffer->lyxvc().checkIn());
2688 if (!dr.message().empty())
2689 reloadBuffer(*buffer);
2693 case LFUN_VC_CHECK_OUT:
2694 if (!buffer || !ensureBufferClean(buffer))
2696 if (buffer->lyxvc().inUse()) {
2697 dr.setMessage(buffer->lyxvc().checkOut());
2698 reloadBuffer(*buffer);
2702 case LFUN_VC_LOCKING_TOGGLE:
2703 LASSERT(buffer, return);
2704 if (!ensureBufferClean(buffer) || buffer->isReadonly())
2706 if (buffer->lyxvc().inUse()) {
2707 string res = buffer->lyxvc().lockingToggle();
2709 frontend::Alert::error(_("Revision control error."),
2710 _("Error when setting the locking property."));
2713 reloadBuffer(*buffer);
2718 case LFUN_VC_REVERT:
2719 LASSERT(buffer, return);
2720 if (buffer->lyxvc().revert()) {
2721 reloadBuffer(*buffer);
2722 dr.suppressMessageUpdate();
2726 case LFUN_VC_UNDO_LAST:
2727 LASSERT(buffer, return);
2728 buffer->lyxvc().undoLast();
2729 reloadBuffer(*buffer);
2730 dr.suppressMessageUpdate();
2733 case LFUN_VC_REPO_UPDATE:
2734 LASSERT(buffer, return);
2735 if (ensureBufferClean(buffer)) {
2736 dr.setMessage(buffer->lyxvc().repoUpdate());
2737 checkExternallyModifiedBuffers();
2741 case LFUN_VC_COMMAND: {
2742 string flag = cmd.getArg(0);
2743 if (buffer && contains(flag, 'R') && !ensureBufferClean(buffer))
2746 if (contains(flag, 'M')) {
2747 if (!Alert::askForText(message, _("LyX VC: Log Message")))
2750 string path = cmd.getArg(1);
2751 if (contains(path, "$$p") && buffer)
2752 path = subst(path, "$$p", buffer->filePath());
2753 LYXERR(Debug::LYXVC, "Directory: " << path);
2755 if (!pp.isReadableDirectory()) {
2756 lyxerr << _("Directory is not accessible.") << endl;
2759 support::PathChanger p(pp);
2761 string command = cmd.getArg(2);
2762 if (command.empty())
2765 command = subst(command, "$$i", buffer->absFileName());
2766 command = subst(command, "$$p", buffer->filePath());
2768 command = subst(command, "$$m", to_utf8(message));
2769 LYXERR(Debug::LYXVC, "Command: " << command);
2771 one.startscript(Systemcall::Wait, command);
2775 if (contains(flag, 'I'))
2776 buffer->markDirty();
2777 if (contains(flag, 'R'))
2778 reloadBuffer(*buffer);
2783 case LFUN_VC_COMPARE: {
2785 if (cmd.argument().empty()) {
2786 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "comparehistory"));
2790 string rev1 = cmd.getArg(0);
2794 if (!buffer->lyxvc().prepareFileRevision(rev1, f1))
2797 if (isStrInt(rev1) && convert<int>(rev1) <= 0) {
2798 f2 = buffer->absFileName();
2800 string rev2 = cmd.getArg(1);
2804 if (!buffer->lyxvc().prepareFileRevision(rev2, f2))
2808 LYXERR(Debug::LYXVC, "Launching comparison for fetched revisions:\n" <<
2809 f1 << "\n" << f2 << "\n" );
2810 string par = "compare run " + quoteName(f1) + " " + quoteName(f2);
2811 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, par));
2821 void GuiView::openChildDocument(string const & fname)
2823 LASSERT(documentBufferView(), return);
2824 Buffer & buffer = documentBufferView()->buffer();
2825 FileName const filename = support::makeAbsPath(fname, buffer.filePath());
2826 documentBufferView()->saveBookmark(false);
2828 if (theBufferList().exists(filename)) {
2829 child = theBufferList().getBuffer(filename);
2832 message(bformat(_("Opening child document %1$s..."),
2833 makeDisplayPath(filename.absFileName())));
2834 child = loadDocument(filename, false);
2836 // Set the parent name of the child document.
2837 // This makes insertion of citations and references in the child work,
2838 // when the target is in the parent or another child document.
2840 child->setParent(&buffer);
2844 bool GuiView::goToFileRow(string const & argument)
2848 size_t i = argument.find_last_of(' ');
2849 if (i != string::npos) {
2850 file_name = os::internal_path(trim(argument.substr(0, i)));
2851 istringstream is(argument.substr(i + 1));
2856 if (i == string::npos) {
2857 LYXERR0("Wrong argument: " << argument);
2861 string const abstmp = package().temp_dir().absFileName();
2862 string const realtmp = package().temp_dir().realPath();
2863 // We have to use os::path_prefix_is() here, instead of
2864 // simply prefixIs(), because the file name comes from
2865 // an external application and may need case adjustment.
2866 if (os::path_prefix_is(file_name, abstmp, os::CASE_ADJUSTED)
2867 || os::path_prefix_is(file_name, realtmp, os::CASE_ADJUSTED)) {
2868 // Needed by inverse dvi search. If it is a file
2869 // in tmpdir, call the apropriated function.
2870 // If tmpdir is a symlink, we may have the real
2871 // path passed back, so we correct for that.
2872 if (!prefixIs(file_name, abstmp))
2873 file_name = subst(file_name, realtmp, abstmp);
2874 buf = theBufferList().getBufferFromTmp(file_name);
2876 // Must replace extension of the file to be .lyx
2877 // and get full path
2878 FileName const s = fileSearch(string(),
2879 support::changeExtension(file_name, ".lyx"), "lyx");
2880 // Either change buffer or load the file
2881 if (theBufferList().exists(s))
2882 buf = theBufferList().getBuffer(s);
2883 else if (s.exists()) {
2884 buf = loadDocument(s);
2889 _("File does not exist: %1$s"),
2890 makeDisplayPath(file_name)));
2895 documentBufferView()->setCursorFromRow(row);
2900 #if (QT_VERSION >= 0x040400)
2902 docstring GuiView::GuiViewPrivate::runAndDestroy(const T& func, Buffer const * orig, Buffer * buffer, string const & format, string const & msg)
2904 bool const update_unincluded =
2905 buffer->params().maintain_unincluded_children
2906 && !buffer->params().getIncludedChildren().empty();
2907 bool const success = func(format, update_unincluded);
2909 busyBuffers.remove(orig);
2910 if (msg == "preview") {
2912 ? bformat(_("Successful preview of format: %1$s"), from_utf8(format))
2913 : bformat(_("Error while previewing format: %1$s"), from_utf8(format));
2916 ? bformat(_("Successful export to format: %1$s"), from_utf8(format))
2917 : bformat(_("Error while exporting format: %1$s"), from_utf8(format));
2921 docstring GuiView::GuiViewPrivate::compileAndDestroy(Buffer const * orig, Buffer * buffer, string const & format)
2923 bool (Buffer::* mem_func)(std::string const &, bool, bool) const = &Buffer::doExport;
2924 return runAndDestroy(bind(mem_func, buffer, _1, true, _2), orig, buffer, format, "export");
2928 docstring GuiView::GuiViewPrivate::exportAndDestroy(Buffer const * orig, Buffer * buffer, string const & format)
2930 bool (Buffer::* mem_func)(std::string const &, bool, bool) const = &Buffer::doExport;
2931 return runAndDestroy(bind(mem_func, buffer, _1, false, _2), orig, buffer, format, "export");
2935 docstring GuiView::GuiViewPrivate::previewAndDestroy(Buffer const * orig, Buffer * buffer, string const & format)
2937 bool(Buffer::* mem_func)(std::string const &, bool) const = &Buffer::preview;
2938 return runAndDestroy(bind(mem_func, buffer, _1, _2), orig, buffer, format, "preview");
2943 // not used, but the linker needs them
2945 docstring GuiView::GuiViewPrivate::compileAndDestroy(
2946 Buffer const *, Buffer *, string const &)
2952 docstring GuiView::GuiViewPrivate::exportAndDestroy(
2953 Buffer const *, Buffer *, string const &)
2959 docstring GuiView::GuiViewPrivate::previewAndDestroy(
2960 Buffer const *, Buffer *, string const &)
2968 bool GuiView::GuiViewPrivate::asyncBufferProcessing(
2969 string const & argument,
2970 Buffer const * used_buffer,
2971 docstring const & msg,
2972 docstring (*asyncFunc)(Buffer const *, Buffer *, string const &),
2973 bool (Buffer::*syncFunc)(string const &, bool, bool) const,
2974 bool (Buffer::*previewFunc)(string const &, bool) const)
2979 string format = argument;
2981 format = used_buffer->getDefaultOutputFormat();
2983 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
2985 progress_->clearMessages();
2988 GuiViewPrivate::busyBuffers.insert(used_buffer);
2989 QFuture<docstring> f = QtConcurrent::run(
2992 used_buffer->clone(),
2994 setPreviewFuture(f);
2995 last_export_format = used_buffer->bufferFormat();
2998 // We are asynchronous, so we don't know here anything about the success
3002 // TODO check here if it breaks exporting with Qt < 4.4
3003 bool const update_unincluded =
3004 used_buffer->params().maintain_unincluded_children &&
3005 !used_buffer->params().getIncludedChildren().empty();
3006 return (used_buffer->*syncFunc)(format, true, update_unincluded);
3007 } else if (previewFunc) {
3008 return (used_buffer->*previewFunc)(format, false);
3015 void GuiView::dispatchToBufferView(FuncRequest const & cmd, DispatchResult & dr)
3017 BufferView * bv = currentBufferView();
3020 // Let the current BufferView dispatch its own actions.
3021 bv->dispatch(cmd, dr);
3022 if (dr.dispatched())
3025 // Try with the document BufferView dispatch if any.
3026 BufferView * doc_bv = documentBufferView();
3028 doc_bv->dispatch(cmd, dr);
3029 if (dr.dispatched())
3033 // Then let the current Cursor dispatch its own actions.
3034 bv->cursor().dispatch(cmd);
3036 // update completion. We do it here and not in
3037 // processKeySym to avoid another redraw just for a
3038 // changed inline completion
3039 if (cmd.origin() == FuncRequest::KEYBOARD) {
3040 if (cmd.action() == LFUN_SELF_INSERT
3041 || (cmd.action() == LFUN_ERT_INSERT && bv->cursor().inMathed()))
3042 updateCompletion(bv->cursor(), true, true);
3043 else if (cmd.action() == LFUN_CHAR_DELETE_BACKWARD)
3044 updateCompletion(bv->cursor(), false, true);
3046 updateCompletion(bv->cursor(), false, false);
3049 dr = bv->cursor().result();
3053 void GuiView::dispatch(FuncRequest const & cmd, DispatchResult & dr)
3055 BufferView * bv = currentBufferView();
3056 // By default we won't need any update.
3057 dr.screenUpdate(Update::None);
3058 // assume cmd will be dispatched
3059 dr.dispatched(true);
3061 Buffer * doc_buffer = documentBufferView()
3062 ? &(documentBufferView()->buffer()) : 0;
3064 if (cmd.origin() == FuncRequest::TOC) {
3065 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
3066 // FIXME: do we need to pass a DispatchResult object here?
3067 toc->doDispatch(bv->cursor(), cmd);
3071 string const argument = to_utf8(cmd.argument());
3073 switch(cmd.action()) {
3074 case LFUN_BUFFER_CHILD_OPEN:
3075 openChildDocument(to_utf8(cmd.argument()));
3078 case LFUN_BUFFER_IMPORT:
3079 importDocument(to_utf8(cmd.argument()));
3082 case LFUN_BUFFER_EXPORT: {
3085 // GCC only sees strfwd.h when building merged
3086 if (::lyx::operator==(cmd.argument(), "custom")) {
3087 dispatch(FuncRequest(LFUN_DIALOG_SHOW, "sendto"), dr);
3090 #if QT_VERSION < 0x040400
3091 if (!doc_buffer->doExport(argument, false)) {
3093 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
3097 /* TODO/Review: Is it a problem to also export the children?
3098 See the update_unincluded flag */
3099 d.asyncBufferProcessing(argument,
3102 &GuiViewPrivate::exportAndDestroy,
3105 // TODO Inform user about success
3110 case LFUN_BUFFER_UPDATE: {
3111 d.asyncBufferProcessing(argument,
3114 &GuiViewPrivate::compileAndDestroy,
3119 case LFUN_BUFFER_VIEW: {
3120 d.asyncBufferProcessing(argument,
3122 _("Previewing ..."),
3123 &GuiViewPrivate::previewAndDestroy,
3128 case LFUN_MASTER_BUFFER_UPDATE: {
3129 d.asyncBufferProcessing(argument,
3130 (doc_buffer ? doc_buffer->masterBuffer() : 0),
3132 &GuiViewPrivate::compileAndDestroy,
3137 case LFUN_MASTER_BUFFER_VIEW: {
3138 d.asyncBufferProcessing(argument,
3139 (doc_buffer ? doc_buffer->masterBuffer() : 0),
3141 &GuiViewPrivate::previewAndDestroy,
3142 0, &Buffer::preview);
3145 case LFUN_BUFFER_SWITCH: {
3146 string const file_name = to_utf8(cmd.argument());
3147 if (!FileName::isAbsolute(file_name)) {
3149 dr.setMessage(_("Absolute filename expected."));
3153 Buffer * buffer = theBufferList().getBuffer(FileName(file_name));
3156 dr.setMessage(_("Document not loaded"));
3160 // Do we open or switch to the buffer in this view ?
3161 if (workArea(*buffer)
3162 || lyxrc.open_buffers_in_tabs || !documentBufferView()) {
3167 // Look for the buffer in other views
3168 QList<int> const ids = guiApp->viewIds();
3170 for (; i != ids.size(); ++i) {
3171 GuiView & gv = guiApp->view(ids[i]);
3172 if (gv.workArea(*buffer)) {
3173 gv.activateWindow();
3174 gv.setBuffer(buffer);
3179 // If necessary, open a new window as a last resort
3180 if (i == ids.size()) {
3181 lyx::dispatch(FuncRequest(LFUN_WINDOW_NEW));
3187 case LFUN_BUFFER_NEXT:
3188 gotoNextOrPreviousBuffer(NEXTBUFFER);
3191 case LFUN_BUFFER_PREVIOUS:
3192 gotoNextOrPreviousBuffer(PREVBUFFER);
3195 case LFUN_COMMAND_EXECUTE: {
3196 bool const show_it = cmd.argument() != "off";
3197 // FIXME: this is a hack, "minibuffer" should not be
3199 if (GuiToolbar * t = toolbar("minibuffer")) {
3200 t->setVisible(show_it);
3201 if (show_it && t->commandBuffer())
3202 t->commandBuffer()->setFocus();
3206 case LFUN_DROP_LAYOUTS_CHOICE:
3207 d.layout_->showPopup();
3210 case LFUN_MENU_OPEN:
3211 if (QMenu * menu = guiApp->menus().menu(toqstr(cmd.argument()), *this))
3212 menu->exec(QCursor::pos());
3215 case LFUN_FILE_INSERT:
3216 insertLyXFile(cmd.argument());
3219 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
3220 insertPlaintextFile(cmd.argument(), true);
3223 case LFUN_FILE_INSERT_PLAINTEXT:
3224 insertPlaintextFile(cmd.argument(), false);
3227 case LFUN_BUFFER_RELOAD: {
3228 LASSERT(doc_buffer, break);
3231 if (!doc_buffer->isClean()) {
3232 docstring const file =
3233 makeDisplayPath(doc_buffer->absFileName(), 20);
3234 docstring text = bformat(_("Any changes will be lost. "
3235 "Are you sure you want to revert to the saved version "
3236 "of the document %1$s?"), file);
3237 ret = Alert::prompt(_("Revert to saved document?"),
3238 text, 1, 1, _("&Revert"), _("&Cancel"));
3242 doc_buffer->markClean();
3243 reloadBuffer(*doc_buffer);
3244 dr.forceBufferUpdate();
3249 case LFUN_BUFFER_WRITE:
3250 LASSERT(doc_buffer, break);
3251 saveBuffer(*doc_buffer);
3254 case LFUN_BUFFER_WRITE_AS:
3255 LASSERT(doc_buffer, break);
3256 renameBuffer(*doc_buffer, cmd.argument());
3259 case LFUN_BUFFER_WRITE_ALL: {
3260 Buffer * first = theBufferList().first();
3263 message(_("Saving all documents..."));
3264 // We cannot use a for loop as the buffer list cycles.
3267 if (!b->isClean()) {
3269 LYXERR(Debug::ACTION, "Saved " << b->absFileName());
3271 b = theBufferList().next(b);
3272 } while (b != first);
3273 dr.setMessage(_("All documents saved."));
3277 case LFUN_BUFFER_CLOSE:
3281 case LFUN_BUFFER_CLOSE_ALL:
3285 case LFUN_TOOLBAR_TOGGLE: {
3286 string const name = cmd.getArg(0);
3287 if (GuiToolbar * t = toolbar(name))
3292 case LFUN_DIALOG_UPDATE: {
3293 string const name = to_utf8(cmd.argument());
3294 if (name == "prefs" || name == "document")
3295 updateDialog(name, string());
3296 else if (name == "paragraph")
3297 lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
3298 else if (currentBufferView()) {
3299 Inset * inset = currentBufferView()->editedInset(name);
3300 // Can only update a dialog connected to an existing inset
3302 // FIXME: get rid of this indirection; GuiView ask the inset
3303 // if he is kind enough to update itself...
3304 FuncRequest fr(LFUN_INSET_DIALOG_UPDATE, cmd.argument());
3305 //FIXME: pass DispatchResult here?
3306 inset->dispatch(currentBufferView()->cursor(), fr);
3312 case LFUN_DIALOG_TOGGLE: {
3313 FuncCode const func_code = isDialogVisible(cmd.getArg(0))
3314 ? LFUN_DIALOG_HIDE : LFUN_DIALOG_SHOW;
3315 dispatch(FuncRequest(func_code, cmd.argument()), dr);
3319 case LFUN_DIALOG_DISCONNECT_INSET:
3320 disconnectDialog(to_utf8(cmd.argument()));
3323 case LFUN_DIALOG_HIDE: {
3324 guiApp->hideDialogs(to_utf8(cmd.argument()), 0);
3328 case LFUN_DIALOG_SHOW: {
3329 string const name = cmd.getArg(0);
3330 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
3332 if (name == "character") {
3333 data = freefont2string();
3335 showDialog("character", data);
3336 } else if (name == "latexlog") {
3337 Buffer::LogType type;
3338 string const logfile = doc_buffer->logName(&type);
3340 case Buffer::latexlog:
3343 case Buffer::buildlog:
3347 data += Lexer::quoteString(logfile);
3348 showDialog("log", data);
3349 } else if (name == "vclog") {
3350 string const data = "vc " +
3351 Lexer::quoteString(doc_buffer->lyxvc().getLogFile());
3352 showDialog("log", data);
3353 } else if (name == "symbols") {
3354 data = bv->cursor().getEncoding()->name();
3356 showDialog("symbols", data);
3358 } else if (name == "prefs" && isFullScreen()) {
3359 lfunUiToggle("fullscreen");
3360 showDialog("prefs", data);
3362 showDialog(name, data);
3367 dr.setMessage(cmd.argument());
3370 case LFUN_UI_TOGGLE: {
3371 string arg = cmd.getArg(0);
3372 if (!lfunUiToggle(arg)) {
3373 docstring const msg = "ui-toggle " + _("%1$s unknown command!");
3374 dr.setMessage(bformat(msg, from_utf8(arg)));
3376 // Make sure the keyboard focus stays in the work area.
3381 case LFUN_SPLIT_VIEW: {
3382 LASSERT(doc_buffer, break);
3383 string const orientation = cmd.getArg(0);
3384 d.splitter_->setOrientation(orientation == "vertical"
3385 ? Qt::Vertical : Qt::Horizontal);
3386 TabWorkArea * twa = addTabWorkArea();
3387 GuiWorkArea * wa = twa->addWorkArea(*doc_buffer, *this);
3388 setCurrentWorkArea(wa);
3391 case LFUN_CLOSE_TAB_GROUP:
3392 if (TabWorkArea * twa = d.currentTabWorkArea()) {
3393 closeTabWorkArea(twa);
3394 d.current_work_area_ = 0;
3395 twa = d.currentTabWorkArea();
3396 // Switch to the next GuiWorkArea in the found TabWorkArea.
3398 // Make sure the work area is up to date.
3399 setCurrentWorkArea(twa->currentWorkArea());
3401 setCurrentWorkArea(0);
3406 case LFUN_COMPLETION_INLINE:
3407 if (d.current_work_area_)
3408 d.current_work_area_->completer().showInline();
3411 case LFUN_COMPLETION_POPUP:
3412 if (d.current_work_area_)
3413 d.current_work_area_->completer().showPopup();
3417 case LFUN_COMPLETION_COMPLETE:
3418 if (d.current_work_area_)
3419 d.current_work_area_->completer().tab();
3422 case LFUN_COMPLETION_CANCEL:
3423 if (d.current_work_area_) {
3424 if (d.current_work_area_->completer().popupVisible())
3425 d.current_work_area_->completer().hidePopup();
3427 d.current_work_area_->completer().hideInline();
3431 case LFUN_COMPLETION_ACCEPT:
3432 if (d.current_work_area_)
3433 d.current_work_area_->completer().activate();
3436 case LFUN_BUFFER_ZOOM_IN:
3437 case LFUN_BUFFER_ZOOM_OUT:
3438 if (cmd.argument().empty()) {
3439 if (cmd.action() == LFUN_BUFFER_ZOOM_IN)
3444 lyxrc.zoom += convert<int>(cmd.argument());
3446 if (lyxrc.zoom < 10)
3449 // The global QPixmapCache is used in GuiPainter to cache text
3450 // painting so we must reset it.
3451 QPixmapCache::clear();
3452 guiApp->fontLoader().update();
3453 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
3456 case LFUN_VC_REGISTER:
3457 case LFUN_VC_CHECK_IN:
3458 case LFUN_VC_CHECK_OUT:
3459 case LFUN_VC_REPO_UPDATE:
3460 case LFUN_VC_LOCKING_TOGGLE:
3461 case LFUN_VC_REVERT:
3462 case LFUN_VC_UNDO_LAST:
3463 case LFUN_VC_COMMAND:
3464 case LFUN_VC_COMPARE:
3465 dispatchVC(cmd, dr);
3468 case LFUN_SERVER_GOTO_FILE_ROW:
3469 goToFileRow(to_utf8(cmd.argument()));
3472 case LFUN_FORWARD_SEARCH: {
3473 Buffer const * doc_master = doc_buffer->masterBuffer();
3474 FileName const path(doc_master->temppath());
3475 string const texname = doc_master->isChild(doc_buffer)
3476 ? DocFileName(changeExtension(
3477 doc_buffer->absFileName(),
3478 "tex")).mangledFileName()
3479 : doc_buffer->latexName();
3480 string const mastername =
3481 removeExtension(doc_master->latexName());
3482 FileName const dviname(addName(path.absFileName(),
3483 addExtension(mastername, "dvi")));
3484 FileName const pdfname(addName(path.absFileName(),
3485 addExtension(mastername, "pdf")));
3486 if (!dviname.exists() && !pdfname.exists()) {
3487 dr.setMessage(_("Please, preview the document first."));
3490 string outname = dviname.onlyFileName();
3491 string command = lyxrc.forward_search_dvi;
3492 if (!dviname.exists() ||
3493 pdfname.lastModified() > dviname.lastModified()) {
3494 outname = pdfname.onlyFileName();
3495 command = lyxrc.forward_search_pdf;
3498 int row = doc_buffer->texrow().getRowFromIdPos(bv->cursor().paragraph().id(), bv->cursor().pos());
3499 LYXERR(Debug::ACTION, "Forward search: row:" << row
3500 << " id:" << bv->cursor().paragraph().id());
3501 if (!row || command.empty()) {
3502 dr.setMessage(_("Couldn't proceed."));
3505 string texrow = convert<string>(row);
3507 command = subst(command, "$$n", texrow);
3508 command = subst(command, "$$t", texname);
3509 command = subst(command, "$$o", outname);
3511 PathChanger p(path);
3513 one.startscript(Systemcall::DontWait, command);
3517 // The LFUN must be for one of BufferView, Buffer or Cursor;
3519 dispatchToBufferView(cmd, dr);
3523 // Part of automatic menu appearance feature.
3524 if (isFullScreen()) {
3525 if (menuBar()->isVisible() && lyxrc.full_screen_menubar)
3527 if (statusBar()->isVisible())
3528 statusBar()->hide();
3533 bool GuiView::lfunUiToggle(string const & ui_component)
3535 if (ui_component == "scrollbar") {
3536 // hide() is of no help
3537 if (d.current_work_area_->verticalScrollBarPolicy() ==
3538 Qt::ScrollBarAlwaysOff)
3540 d.current_work_area_->setVerticalScrollBarPolicy(
3541 Qt::ScrollBarAsNeeded);
3543 d.current_work_area_->setVerticalScrollBarPolicy(
3544 Qt::ScrollBarAlwaysOff);
3545 } else if (ui_component == "statusbar") {
3546 statusBar()->setVisible(!statusBar()->isVisible());
3547 } else if (ui_component == "menubar") {
3548 menuBar()->setVisible(!menuBar()->isVisible());
3550 #if QT_VERSION >= 0x040300
3551 if (ui_component == "frame") {
3553 getContentsMargins(&l, &t, &r, &b);
3554 //are the frames in default state?
3555 d.current_work_area_->setFrameStyle(QFrame::NoFrame);
3557 setContentsMargins(-2, -2, -2, -2);
3559 setContentsMargins(0, 0, 0, 0);
3563 if (ui_component == "fullscreen") {
3571 void GuiView::toggleFullScreen()
3573 if (isFullScreen()) {
3574 for (int i = 0; i != d.splitter_->count(); ++i)
3575 d.tabWorkArea(i)->setFullScreen(false);
3576 #if QT_VERSION >= 0x040300
3577 setContentsMargins(0, 0, 0, 0);
3579 setWindowState(windowState() ^ Qt::WindowFullScreen);
3582 statusBar()->show();
3585 hideDialogs("prefs", 0);
3586 for (int i = 0; i != d.splitter_->count(); ++i)
3587 d.tabWorkArea(i)->setFullScreen(true);
3588 #if QT_VERSION >= 0x040300
3589 setContentsMargins(-2, -2, -2, -2);
3592 setWindowState(windowState() ^ Qt::WindowFullScreen);
3593 statusBar()->hide();
3594 if (lyxrc.full_screen_menubar)
3596 if (lyxrc.full_screen_toolbars) {
3597 ToolbarMap::iterator end = d.toolbars_.end();
3598 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
3603 // give dialogs like the TOC a chance to adapt
3608 Buffer const * GuiView::updateInset(Inset const * inset)
3613 Buffer const * inset_buffer = &(inset->buffer());
3615 for (int i = 0; i != d.splitter_->count(); ++i) {
3616 GuiWorkArea * wa = d.tabWorkArea(i)->currentWorkArea();
3619 Buffer const * buffer = &(wa->bufferView().buffer());
3620 if (inset_buffer == buffer)
3621 wa->scheduleRedraw();
3623 return inset_buffer;
3627 void GuiView::restartCursor()
3629 /* When we move around, or type, it's nice to be able to see
3630 * the cursor immediately after the keypress.
3632 if (d.current_work_area_)
3633 d.current_work_area_->startBlinkingCursor();
3635 // Take this occasion to update the other GUI elements.
3641 void GuiView::updateCompletion(Cursor & cur, bool start, bool keep)
3643 if (d.current_work_area_)
3644 d.current_work_area_->completer().updateVisibility(cur, start, keep);
3649 // This list should be kept in sync with the list of insets in
3650 // src/insets/Inset.cpp. I.e., if a dialog goes with an inset, the
3651 // dialog should have the same name as the inset.
3652 // Changes should be also recorded in LFUN_DIALOG_SHOW doxygen
3653 // docs in LyXAction.cpp.
3655 char const * const dialognames[] = {
3657 "aboutlyx", "bibitem", "bibtex", "box", "branch", "changes", "character",
3658 "citation", "compare", "comparehistory", "document", "errorlist", "ert",
3659 "external", "file", "findreplace", "findreplaceadv", "float", "graphics",
3660 "href", "include", "index", "index_print", "info", "listings", "label", "line",
3661 "log", "mathdelimiter", "mathmatrix", "mathspace", "nomenclature",
3662 "nomencl_print", "note", "paragraph", "phantom", "prefs", "print", "ref",
3663 "sendto", "space", "spellchecker", "symbols", "tabular", "tabularcreate",
3664 "thesaurus", "texinfo", "toc", "view-source", "vspace", "wrap", "progress"};
3666 char const * const * const end_dialognames =
3667 dialognames + (sizeof(dialognames) / sizeof(char *));
3671 cmpCStr(char const * name) : name_(name) {}
3672 bool operator()(char const * other) {
3673 return strcmp(other, name_) == 0;
3680 bool isValidName(string const & name)
3682 return find_if(dialognames, end_dialognames,
3683 cmpCStr(name.c_str())) != end_dialognames;
3689 void GuiView::resetDialogs()
3691 // Make sure that no LFUN uses any GuiView.
3692 guiApp->setCurrentView(0);
3696 constructToolbars();
3697 guiApp->menus().fillMenuBar(menuBar(), this, false);
3698 d.layout_->updateContents(true);
3699 // Now update controls with current buffer.
3700 guiApp->setCurrentView(this);
3706 Dialog * GuiView::findOrBuild(string const & name, bool hide_it)
3708 if (!isValidName(name))
3711 map<string, DialogPtr>::iterator it = d.dialogs_.find(name);
3713 if (it != d.dialogs_.end()) {
3715 it->second->hideView();
3716 return it->second.get();
3719 Dialog * dialog = build(name);
3720 d.dialogs_[name].reset(dialog);
3721 if (lyxrc.allow_geometry_session)
3722 dialog->restoreSession();
3729 void GuiView::showDialog(string const & name, string const & data,
3732 triggerShowDialog(toqstr(name), toqstr(data), inset);
3736 void GuiView::doShowDialog(QString const & qname, QString const & qdata,
3742 const string name = fromqstr(qname);
3743 const string data = fromqstr(qdata);
3747 Dialog * dialog = findOrBuild(name, false);
3749 bool const visible = dialog->isVisibleView();
3750 dialog->showData(data);
3751 if (inset && currentBufferView())
3752 currentBufferView()->editInset(name, inset);
3753 // We only set the focus to the new dialog if it was not yet
3754 // visible in order not to change the existing previous behaviour
3756 // activateWindow is needed for floating dockviews
3757 dialog->asQWidget()->raise();
3758 dialog->asQWidget()->activateWindow();
3759 dialog->asQWidget()->setFocus();
3763 catch (ExceptionMessage const & ex) {
3771 bool GuiView::isDialogVisible(string const & name) const
3773 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3774 if (it == d.dialogs_.end())
3776 return it->second.get()->isVisibleView() && !it->second.get()->isClosing();
3780 void GuiView::hideDialog(string const & name, Inset * inset)
3782 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3783 if (it == d.dialogs_.end())
3787 if (!currentBufferView())
3789 if (inset != currentBufferView()->editedInset(name))
3793 Dialog * const dialog = it->second.get();
3794 if (dialog->isVisibleView())
3796 if (currentBufferView())
3797 currentBufferView()->editInset(name, 0);
3801 void GuiView::disconnectDialog(string const & name)
3803 if (!isValidName(name))
3805 if (currentBufferView())
3806 currentBufferView()->editInset(name, 0);
3810 void GuiView::hideAll() const
3812 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
3813 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3815 for(; it != end; ++it)
3816 it->second->hideView();
3820 void GuiView::updateDialogs()
3822 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
3823 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3825 for(; it != end; ++it) {
3826 Dialog * dialog = it->second.get();
3828 if (dialog->needBufferOpen() && !documentBufferView())
3829 hideDialog(fromqstr(dialog->name()), 0);
3830 else if (dialog->isVisibleView())
3831 dialog->checkStatus();
3838 Dialog * createDialog(GuiView & lv, string const & name);
3840 // will be replaced by a proper factory...
3841 Dialog * createGuiAbout(GuiView & lv);
3842 Dialog * createGuiBibtex(GuiView & lv);
3843 Dialog * createGuiChanges(GuiView & lv);
3844 Dialog * createGuiCharacter(GuiView & lv);
3845 Dialog * createGuiCitation(GuiView & lv);
3846 Dialog * createGuiCompare(GuiView & lv);
3847 Dialog * createGuiCompareHistory(GuiView & lv);
3848 Dialog * createGuiDelimiter(GuiView & lv);
3849 Dialog * createGuiDocument(GuiView & lv);
3850 Dialog * createGuiErrorList(GuiView & lv);
3851 Dialog * createGuiExternal(GuiView & lv);
3852 Dialog * createGuiGraphics(GuiView & lv);
3853 Dialog * createGuiInclude(GuiView & lv);
3854 Dialog * createGuiIndex(GuiView & lv);
3855 Dialog * createGuiListings(GuiView & lv);
3856 Dialog * createGuiLog(GuiView & lv);
3857 Dialog * createGuiMathMatrix(GuiView & lv);
3858 Dialog * createGuiNote(GuiView & lv);
3859 Dialog * createGuiParagraph(GuiView & lv);
3860 Dialog * createGuiPhantom(GuiView & lv);
3861 Dialog * createGuiPreferences(GuiView & lv);
3862 Dialog * createGuiPrint(GuiView & lv);
3863 Dialog * createGuiPrintindex(GuiView & lv);
3864 Dialog * createGuiRef(GuiView & lv);
3865 Dialog * createGuiSearch(GuiView & lv);
3866 Dialog * createGuiSearchAdv(GuiView & lv);
3867 Dialog * createGuiSendTo(GuiView & lv);
3868 Dialog * createGuiShowFile(GuiView & lv);
3869 Dialog * createGuiSpellchecker(GuiView & lv);
3870 Dialog * createGuiSymbols(GuiView & lv);
3871 Dialog * createGuiTabularCreate(GuiView & lv);
3872 Dialog * createGuiTexInfo(GuiView & lv);
3873 Dialog * createGuiToc(GuiView & lv);
3874 Dialog * createGuiThesaurus(GuiView & lv);
3875 Dialog * createGuiViewSource(GuiView & lv);
3876 Dialog * createGuiWrap(GuiView & lv);
3877 Dialog * createGuiProgressView(GuiView & lv);
3881 Dialog * GuiView::build(string const & name)
3883 LASSERT(isValidName(name), return 0);
3885 Dialog * dialog = createDialog(*this, name);
3889 if (name == "aboutlyx")
3890 return createGuiAbout(*this);
3891 if (name == "bibtex")
3892 return createGuiBibtex(*this);
3893 if (name == "changes")
3894 return createGuiChanges(*this);
3895 if (name == "character")
3896 return createGuiCharacter(*this);
3897 if (name == "citation")
3898 return createGuiCitation(*this);
3899 if (name == "compare")
3900 return createGuiCompare(*this);
3901 if (name == "comparehistory")
3902 return createGuiCompareHistory(*this);
3903 if (name == "document")
3904 return createGuiDocument(*this);
3905 if (name == "errorlist")
3906 return createGuiErrorList(*this);
3907 if (name == "external")
3908 return createGuiExternal(*this);
3910 return createGuiShowFile(*this);
3911 if (name == "findreplace")
3912 return createGuiSearch(*this);
3913 if (name == "findreplaceadv")
3914 return createGuiSearchAdv(*this);
3915 if (name == "graphics")
3916 return createGuiGraphics(*this);
3917 if (name == "include")
3918 return createGuiInclude(*this);
3919 if (name == "index")
3920 return createGuiIndex(*this);
3921 if (name == "index_print")
3922 return createGuiPrintindex(*this);
3923 if (name == "listings")
3924 return createGuiListings(*this);
3926 return createGuiLog(*this);
3927 if (name == "mathdelimiter")
3928 return createGuiDelimiter(*this);
3929 if (name == "mathmatrix")
3930 return createGuiMathMatrix(*this);
3932 return createGuiNote(*this);
3933 if (name == "paragraph")
3934 return createGuiParagraph(*this);
3935 if (name == "phantom")
3936 return createGuiPhantom(*this);
3937 if (name == "prefs")
3938 return createGuiPreferences(*this);
3939 if (name == "print")
3940 return createGuiPrint(*this);
3942 return createGuiRef(*this);
3943 if (name == "sendto")
3944 return createGuiSendTo(*this);
3945 if (name == "spellchecker")
3946 return createGuiSpellchecker(*this);
3947 if (name == "symbols")
3948 return createGuiSymbols(*this);
3949 if (name == "tabularcreate")
3950 return createGuiTabularCreate(*this);
3951 if (name == "texinfo")
3952 return createGuiTexInfo(*this);
3953 if (name == "thesaurus")
3954 return createGuiThesaurus(*this);
3956 return createGuiToc(*this);
3957 if (name == "view-source")
3958 return createGuiViewSource(*this);
3960 return createGuiWrap(*this);
3961 if (name == "progress")
3962 return createGuiProgressView(*this);
3968 } // namespace frontend
3971 #include "moc_GuiView.cpp"