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;
143 class BackgroundWidget : public QWidget
148 LYXERR(Debug::GUI, "show banner: " << lyxrc.show_banner);
149 if (!lyxrc.show_banner)
151 /// The text to be written on top of the pixmap
152 QString const text = lyx_version ?
153 qt_("version ") + lyx_version : qt_("unknown version");
154 splash_ = getPixmap("images/", "banner", "png");
156 QPainter pain(&splash_);
157 pain.setPen(QColor(0, 0, 0));
159 // The font used to display the version info
160 font.setStyleHint(QFont::SansSerif);
161 font.setWeight(QFont::Bold);
162 font.setPointSize(int(toqstr(lyxrc.font_sizes[FONT_SIZE_LARGE]).toDouble()));
163 int width = QFontMetrics(font).width(text);
165 pain.drawText(397 - width, 15, text);
166 setFocusPolicy(Qt::StrongFocus);
169 void paintEvent(QPaintEvent *)
171 int x = (width() - splash_.width()) / 2;
172 int y = (height() - splash_.height()) / 2;
174 pain.drawPixmap(x, y, splash_);
177 void keyPressEvent(QKeyEvent * ev)
180 setKeySymbol(&sym, ev);
182 guiApp->processKeySym(sym, q_key_state(ev->modifiers()));
194 /// Toolbar store providing access to individual toolbars by name.
195 typedef map<string, GuiToolbar *> ToolbarMap;
197 typedef shared_ptr<Dialog> DialogPtr;
202 struct GuiView::GuiViewPrivate
204 GuiViewPrivate(GuiView * gv)
205 : gv_(gv), current_work_area_(0), current_main_work_area_(0),
206 layout_(0), autosave_timeout_(5000),
209 // hardcode here the platform specific icon size
210 smallIconSize = 14; // scaling problems
211 normalIconSize = 20; // ok, default
212 bigIconSize = 26; // better for some math icons
214 splitter_ = new QSplitter;
215 bg_widget_ = new BackgroundWidget;
216 stack_widget_ = new QStackedWidget;
217 stack_widget_->addWidget(bg_widget_);
218 stack_widget_->addWidget(splitter_);
221 // TODO cleanup, remove the singleton, handle multiple Windows?
222 progress_ = ProgressInterface::instance();
223 if (!dynamic_cast<GuiProgress*>(progress_)) {
224 progress_ = new GuiProgress(); // TODO who deletes it
225 ProgressInterface::setInstance(progress_);
228 dynamic_cast<GuiProgress*>(progress_),
229 SIGNAL(updateStatusBarMessage(QString const&)),
230 gv, SLOT(updateStatusBarMessage(QString const&)));
232 dynamic_cast<GuiProgress*>(progress_),
233 SIGNAL(clearMessageText()),
234 gv, SLOT(clearMessageText()));
241 delete stack_widget_;
244 QMenu * toolBarPopup(GuiView * parent)
246 // FIXME: translation
247 QMenu * menu = new QMenu(parent);
248 QActionGroup * iconSizeGroup = new QActionGroup(parent);
250 QAction * smallIcons = new QAction(iconSizeGroup);
251 smallIcons->setText(qt_("Small-sized icons"));
252 smallIcons->setCheckable(true);
253 QObject::connect(smallIcons, SIGNAL(triggered()),
254 parent, SLOT(smallSizedIcons()));
255 menu->addAction(smallIcons);
257 QAction * normalIcons = new QAction(iconSizeGroup);
258 normalIcons->setText(qt_("Normal-sized icons"));
259 normalIcons->setCheckable(true);
260 QObject::connect(normalIcons, SIGNAL(triggered()),
261 parent, SLOT(normalSizedIcons()));
262 menu->addAction(normalIcons);
264 QAction * bigIcons = new QAction(iconSizeGroup);
265 bigIcons->setText(qt_("Big-sized icons"));
266 bigIcons->setCheckable(true);
267 QObject::connect(bigIcons, SIGNAL(triggered()),
268 parent, SLOT(bigSizedIcons()));
269 menu->addAction(bigIcons);
271 unsigned int cur = parent->iconSize().width();
272 if ( cur == parent->d.smallIconSize)
273 smallIcons->setChecked(true);
274 else if (cur == parent->d.normalIconSize)
275 normalIcons->setChecked(true);
276 else if (cur == parent->d.bigIconSize)
277 bigIcons->setChecked(true);
284 stack_widget_->setCurrentWidget(bg_widget_);
285 bg_widget_->setUpdatesEnabled(true);
286 bg_widget_->setFocus();
289 int tabWorkAreaCount()
291 return splitter_->count();
294 TabWorkArea * tabWorkArea(int i)
296 return dynamic_cast<TabWorkArea *>(splitter_->widget(i));
299 TabWorkArea * currentTabWorkArea()
301 int areas = tabWorkAreaCount();
303 // The first TabWorkArea is always the first one, if any.
304 return tabWorkArea(0);
306 for (int i = 0; i != areas; ++i) {
307 TabWorkArea * twa = tabWorkArea(i);
308 if (current_main_work_area_ == twa->currentWorkArea())
312 // None has the focus so we just take the first one.
313 return tabWorkArea(0);
316 #if (QT_VERSION >= 0x040400)
317 void setPreviewFuture(QFuture<docstring> const & f)
319 if (processing_thread_watcher_.isRunning()) {
320 // we prefer to cancel this preview in order to keep a snappy
324 processing_thread_watcher_.setFuture(f);
330 GuiWorkArea * current_work_area_;
331 GuiWorkArea * current_main_work_area_;
332 QSplitter * splitter_;
333 QStackedWidget * stack_widget_;
334 BackgroundWidget * bg_widget_;
336 ToolbarMap toolbars_;
337 ProgressInterface* progress_;
338 /// The main layout box.
340 * \warning Don't Delete! The layout box is actually owned by
341 * whichever toolbar contains it. All the GuiView class needs is a
342 * means of accessing it.
344 * FIXME: replace that with a proper model so that we are not limited
345 * to only one dialog.
350 map<string, DialogPtr> dialogs_;
352 unsigned int smallIconSize;
353 unsigned int normalIconSize;
354 unsigned int bigIconSize;
356 QTimer statusbar_timer_;
357 /// auto-saving of buffers
358 Timeout autosave_timeout_;
359 /// flag against a race condition due to multiclicks, see bug #1119
363 TocModels toc_models_;
365 #if (QT_VERSION >= 0x040400)
367 QFutureWatcher<docstring> autosave_watcher_;
368 QFutureWatcher<docstring> processing_thread_watcher_;
370 string last_export_format;
372 struct DummyWatcher { bool isRunning(){return false;} };
373 DummyWatcher processing_thread_watcher_;
376 static QSet<Buffer const *> busyBuffers;
377 static docstring previewAndDestroy(Buffer const * orig, Buffer * buffer, string const & format);
378 static docstring exportAndDestroy(Buffer const * orig, Buffer * buffer, string const & format);
379 static docstring compileAndDestroy(Buffer const * orig, Buffer * buffer, string const & format);
380 static docstring autosaveAndDestroy(Buffer const * orig, Buffer * buffer);
383 static docstring runAndDestroy(const T& func, Buffer const * orig, Buffer * buffer, string const & format, string const & msg);
385 // TODO syncFunc/previewFunc: use bind
386 bool asyncBufferProcessing(string const & argument,
387 Buffer const * used_buffer,
388 docstring const & msg,
389 docstring (*asyncFunc)(Buffer const *, Buffer *, string const &),
390 bool (Buffer::*syncFunc)(string const &, bool, bool) const,
391 bool (Buffer::*previewFunc)(string const &, bool) const);
393 QVector<GuiWorkArea*> guiWorkAreas();
396 QSet<Buffer const *> GuiView::GuiViewPrivate::busyBuffers;
399 GuiView::GuiView(int id)
400 : d(*new GuiViewPrivate(this)), id_(id), closing_(false), busy_(0)
402 // GuiToolbars *must* be initialised before the menu bar.
403 normalSizedIcons(); // at least on Mac the default is 32 otherwise, which is huge
406 // set ourself as the current view. This is needed for the menu bar
407 // filling, at least for the static special menu item on Mac. Otherwise
408 // they are greyed out.
409 guiApp->setCurrentView(this);
411 // Fill up the menu bar.
412 guiApp->menus().fillMenuBar(menuBar(), this, true);
414 setCentralWidget(d.stack_widget_);
416 // Start autosave timer
417 if (lyxrc.autosave) {
418 d.autosave_timeout_.timeout.connect(bind(&GuiView::autoSave, this));
419 d.autosave_timeout_.setTimeout(lyxrc.autosave * 1000);
420 d.autosave_timeout_.start();
422 connect(&d.statusbar_timer_, SIGNAL(timeout()),
423 this, SLOT(clearMessage()));
425 // We don't want to keep the window in memory if it is closed.
426 setAttribute(Qt::WA_DeleteOnClose, true);
428 #if (!defined(Q_WS_WIN) && !defined(Q_WS_MACX))
429 // assign an icon to main form. We do not do it under Qt/Win or Qt/Mac,
430 // since the icon is provided in the application bundle.
431 setWindowIcon(getPixmap("images/", "lyx", "png"));
434 #if (QT_VERSION >= 0x040300)
435 // use tabbed dock area for multiple docks
436 // (such as "source" and "messages")
437 setDockOptions(QMainWindow::ForceTabbedDocks);
441 setAcceptDrops(true);
443 #if (QT_VERSION >= 0x040400)
445 // add busy indicator to statusbar
446 QLabel * busylabel = new QLabel(statusBar());
447 statusBar()->addPermanentWidget(busylabel);
448 QString fn = toqstr(lyx::libFileSearch("images", "busy.gif").absFileName());
449 QMovie * busyanim = new QMovie(fn, QByteArray(), busylabel);
450 busylabel->setMovie(busyanim);
454 connect(&d.processing_thread_watcher_, SIGNAL(started()),
455 busylabel, SLOT(show()));
456 connect(&d.processing_thread_watcher_, SIGNAL(finished()),
457 busylabel, SLOT(hide()));
459 statusBar()->setSizeGripEnabled(true);
462 connect(&d.autosave_watcher_, SIGNAL(finished()), this,
463 SLOT(autoSaveThreadFinished()));
465 connect(&d.processing_thread_watcher_, SIGNAL(started()), this,
466 SLOT(processingThreadStarted()));
467 connect(&d.processing_thread_watcher_, SIGNAL(finished()), this,
468 SLOT(processingThreadFinished()));
472 connect(this, SIGNAL(triggerShowDialog(QString const &, QString const &, Inset *)),
473 SLOT(doShowDialog(QString const &, QString const &, Inset *)));
475 // Forbid too small unresizable window because it can happen
476 // with some window manager under X11.
477 setMinimumSize(300, 200);
479 if (lyxrc.allow_geometry_session) {
480 // Now take care of session management.
485 // no session handling, default to a sane size.
486 setGeometry(50, 50, 690, 510);
489 // clear session data if any.
491 settings.remove("views");
501 QVector<GuiWorkArea*> GuiView::GuiViewPrivate::guiWorkAreas()
503 QVector<GuiWorkArea*> areas;
504 for (int i = 0; i < tabWorkAreaCount(); i++) {
505 TabWorkArea* ta = tabWorkArea(i);
506 for (int u = 0; u < ta->count(); u++) {
507 areas << ta->workArea(u);
514 #if QT_VERSION >= 0x040400
516 void GuiView::processingThreadStarted()
521 void GuiView::processingThreadFinished(bool show_errors)
523 QFutureWatcher<docstring> const * watcher =
524 static_cast<QFutureWatcher<docstring> const *>(sender());
525 message(watcher->result());
528 errors(d.last_export_format);
533 void GuiView::processingThreadFinished()
535 processingThreadFinished(true);
539 void GuiView::autoSaveThreadFinished()
541 processingThreadFinished(false);
547 void GuiView::processingThreadStarted()
552 void GuiView::processingThreadFinished(bool)
557 void GuiView::processingThreadFinished()
562 void GuiView::autoSaveThreadFinished()
568 void GuiView::saveLayout() const
571 settings.beginGroup("views");
572 settings.beginGroup(QString::number(id_));
574 settings.setValue("pos", pos());
575 settings.setValue("size", size());
577 settings.setValue("geometry", saveGeometry());
579 settings.setValue("layout", saveState(0));
580 settings.setValue("icon_size", iconSize());
584 void GuiView::saveUISettings() const
586 // Save the toolbar private states
587 ToolbarMap::iterator end = d.toolbars_.end();
588 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
589 it->second->saveSession();
590 // Now take care of all other dialogs
591 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
592 for (; it!= d.dialogs_.end(); ++it)
593 it->second->saveSession();
597 bool GuiView::restoreLayout()
600 settings.beginGroup("views");
601 settings.beginGroup(QString::number(id_));
602 QString const icon_key = "icon_size";
603 if (!settings.contains(icon_key))
606 //code below is skipped when when ~/.config/LyX is (re)created
607 setIconSize(settings.value(icon_key).toSize());
609 QPoint pos = settings.value("pos", QPoint(50, 50)).toPoint();
610 QSize size = settings.value("size", QSize(690, 510)).toSize();
614 // Work-around for bug #6034: the window ends up in an undetermined
615 // state when trying to restore a maximized window when it is
616 // already maximized.
617 if (!(windowState() & Qt::WindowMaximized))
618 if (!restoreGeometry(settings.value("geometry").toByteArray()))
619 setGeometry(50, 50, 690, 510);
621 // Make sure layout is correctly oriented.
622 setLayoutDirection(qApp->layoutDirection());
624 // Allow the toc and view-source dock widget to be restored if needed.
626 if ((dialog = findOrBuild("toc", true)))
627 // see bug 5082. At least setup title and enabled state.
628 // Visibility will be adjusted by restoreState below.
629 dialog->prepareView();
630 if ((dialog = findOrBuild("view-source", true)))
631 dialog->prepareView();
632 if ((dialog = findOrBuild("progress", true)))
633 dialog->prepareView();
634 if ((dialog = findOrBuild("findreplaceadv", true)))
635 dialog->prepareView();
637 if (!restoreState(settings.value("layout").toByteArray(), 0))
644 GuiToolbar * GuiView::toolbar(string const & name)
646 ToolbarMap::iterator it = d.toolbars_.find(name);
647 if (it != d.toolbars_.end())
650 LYXERR(Debug::GUI, "Toolbar::display: no toolbar named " << name);
655 void GuiView::constructToolbars()
657 ToolbarMap::iterator it = d.toolbars_.begin();
658 for (; it != d.toolbars_.end(); ++it)
662 // I don't like doing this here, but the standard toolbar
663 // destroys this object when it's destroyed itself (vfr)
664 d.layout_ = new LayoutBox(*this);
665 d.stack_widget_->addWidget(d.layout_);
666 d.layout_->move(0,0);
668 // extracts the toolbars from the backend
669 Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
670 Toolbars::Infos::iterator end = guiApp->toolbars().end();
671 for (; cit != end; ++cit)
672 d.toolbars_[cit->name] = new GuiToolbar(*cit, *this);
676 void GuiView::initToolbars()
678 // extracts the toolbars from the backend
679 Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
680 Toolbars::Infos::iterator end = guiApp->toolbars().end();
681 for (; cit != end; ++cit) {
682 GuiToolbar * tb = toolbar(cit->name);
685 int const visibility = guiApp->toolbars().defaultVisibility(cit->name);
686 bool newline = !(visibility & Toolbars::SAMEROW);
687 tb->setVisible(false);
688 tb->setVisibility(visibility);
690 if (visibility & Toolbars::TOP) {
692 addToolBarBreak(Qt::TopToolBarArea);
693 addToolBar(Qt::TopToolBarArea, tb);
696 if (visibility & Toolbars::BOTTOM) {
697 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
698 #if (QT_VERSION >= 0x040202)
700 addToolBarBreak(Qt::BottomToolBarArea);
702 addToolBar(Qt::BottomToolBarArea, tb);
705 if (visibility & Toolbars::LEFT) {
706 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
707 #if (QT_VERSION >= 0x040202)
709 addToolBarBreak(Qt::LeftToolBarArea);
711 addToolBar(Qt::LeftToolBarArea, tb);
714 if (visibility & Toolbars::RIGHT) {
715 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
716 #if (QT_VERSION >= 0x040202)
718 addToolBarBreak(Qt::RightToolBarArea);
720 addToolBar(Qt::RightToolBarArea, tb);
723 if (visibility & Toolbars::ON)
724 tb->setVisible(true);
729 TocModels & GuiView::tocModels()
731 return d.toc_models_;
735 void GuiView::setFocus()
737 LYXERR(Debug::DEBUG, "GuiView::setFocus()" << this);
738 QMainWindow::setFocus();
742 void GuiView::focusInEvent(QFocusEvent * e)
744 LYXERR(Debug::DEBUG, "GuiView::focusInEvent()" << this);
745 QMainWindow::focusInEvent(e);
746 // Make sure guiApp points to the correct view.
747 guiApp->setCurrentView(this);
748 if (currentWorkArea())
749 currentWorkArea()->setFocus();
750 else if (currentMainWorkArea())
751 currentMainWorkArea()->setFocus();
753 d.bg_widget_->setFocus();
757 QMenu * GuiView::createPopupMenu()
759 return d.toolBarPopup(this);
763 void GuiView::showEvent(QShowEvent * e)
765 LYXERR(Debug::GUI, "Passed Geometry "
766 << size().height() << "x" << size().width()
767 << "+" << pos().x() << "+" << pos().y());
769 if (d.splitter_->count() == 0)
770 // No work area, switch to the background widget.
773 QMainWindow::showEvent(e);
777 bool GuiView::closeScheduled()
784 /** Destroy only all tabbed WorkAreas. Destruction of other WorkAreas
785 ** is responsibility of the container (e.g., dialog)
787 void GuiView::closeEvent(QCloseEvent * close_event)
789 LYXERR(Debug::DEBUG, "GuiView::closeEvent()");
791 if (!GuiViewPrivate::busyBuffers.isEmpty()) {
792 Alert::warning(_("Exit LyX"),
793 _("LyX could not be closed because documents are being processed by LyX."));
794 close_event->setAccepted(false);
798 // If the user pressed the x (so we didn't call closeView
799 // programmatically), we want to clear all existing entries.
801 theSession().lastOpened().clear();
806 // it can happen that this event arrives without selecting the view,
807 // e.g. when clicking the close button on a background window.
809 if (!closeWorkAreaAll()) {
811 close_event->ignore();
815 // Make sure that nothing will use this to be closed View.
816 guiApp->unregisterView(this);
818 if (isFullScreen()) {
819 // Switch off fullscreen before closing.
824 // Make sure the timer time out will not trigger a statusbar update.
825 d.statusbar_timer_.stop();
827 // Saving fullscreen requires additional tweaks in the toolbar code.
828 // It wouldn't also work under linux natively.
829 if (lyxrc.allow_geometry_session) {
834 close_event->accept();
838 void GuiView::dragEnterEvent(QDragEnterEvent * event)
840 if (event->mimeData()->hasUrls())
842 /// \todo Ask lyx-devel is this is enough:
843 /// if (event->mimeData()->hasFormat("text/plain"))
844 /// event->acceptProposedAction();
848 void GuiView::dropEvent(QDropEvent * event)
850 QList<QUrl> files = event->mimeData()->urls();
854 LYXERR(Debug::GUI, "GuiView::dropEvent: got URLs!");
855 for (int i = 0; i != files.size(); ++i) {
856 string const file = os::internal_path(fromqstr(
857 files.at(i).toLocalFile()));
861 string const ext = support::getExtension(file);
862 vector<const Format *> found_formats;
864 // Find all formats that have the correct extension.
865 vector<const Format *> const & import_formats
866 = theConverters().importableFormats();
867 vector<const Format *>::const_iterator it = import_formats.begin();
868 for (; it != import_formats.end(); ++it)
869 if ((*it)->extension() == ext)
870 found_formats.push_back(*it);
873 if (found_formats.size() >= 1) {
874 if (found_formats.size() > 1) {
875 //FIXME: show a dialog to choose the correct importable format
877 "Multiple importable formats found, selecting first");
879 string const arg = found_formats[0]->name() + " " + file;
880 cmd = FuncRequest(LFUN_BUFFER_IMPORT, arg);
883 //FIXME: do we have to explicitly check whether it's a lyx file?
885 "No formats found, trying to open it as a lyx file");
886 cmd = FuncRequest(LFUN_FILE_OPEN, file);
888 // add the functions to the queue
889 guiApp->addToFuncRequestQueue(cmd);
892 // now process the collected functions. We perform the events
893 // asynchronously. This prevents potential problems in case the
894 // BufferView is closed within an event.
895 guiApp->processFuncRequestQueueAsync();
899 void GuiView::message(docstring const & str)
901 if (ForkedProcess::iAmAChild())
904 // call is moved to GUI-thread by GuiProgress
905 d.progress_->appendMessage(toqstr(str));
909 void GuiView::clearMessageText()
911 message(docstring());
915 void GuiView::updateStatusBarMessage(QString const & str)
917 statusBar()->showMessage(str);
918 d.statusbar_timer_.stop();
919 d.statusbar_timer_.start(3000);
923 void GuiView::smallSizedIcons()
925 setIconSize(QSize(d.smallIconSize, d.smallIconSize));
929 void GuiView::normalSizedIcons()
931 setIconSize(QSize(d.normalIconSize, d.normalIconSize));
935 void GuiView::bigSizedIcons()
937 setIconSize(QSize(d.bigIconSize, d.bigIconSize));
941 void GuiView::clearMessage()
943 // FIXME: This code was introduced in r19643 to fix bug #4123. However,
944 // the hasFocus function mostly returns false, even if the focus is on
945 // a workarea in this view.
949 d.statusbar_timer_.stop();
953 void GuiView::updateWindowTitle(GuiWorkArea * wa)
955 if (wa != d.current_work_area_
956 || wa->bufferView().buffer().isInternal())
958 setWindowTitle(qt_("LyX: ") + wa->windowTitle());
959 setWindowIconText(wa->windowIconText());
963 void GuiView::on_currentWorkAreaChanged(GuiWorkArea * wa)
966 disconnectBufferView();
967 connectBufferView(wa->bufferView());
968 connectBuffer(wa->bufferView().buffer());
969 d.current_work_area_ = wa;
970 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
971 this, SLOT(updateWindowTitle(GuiWorkArea *)));
972 updateWindowTitle(wa);
976 // The document settings needs to be reinitialised.
977 updateDialog("document", "");
979 // Buffer-dependent dialogs must be updated. This is done here because
980 // some dialogs require buffer()->text.
985 void GuiView::on_lastWorkAreaRemoved()
988 // We already are in a close event. Nothing more to do.
991 if (d.splitter_->count() > 1)
992 // We have a splitter so don't close anything.
995 // Reset and updates the dialogs.
996 d.toc_models_.reset(0);
997 updateDialog("document", "");
1000 resetWindowTitleAndIconText();
1003 if (lyxrc.open_buffers_in_tabs)
1004 // Nothing more to do, the window should stay open.
1007 if (guiApp->viewIds().size() > 1) {
1013 // On Mac we also close the last window because the application stay
1014 // resident in memory. On other platforms we don't close the last
1015 // window because this would quit the application.
1021 void GuiView::updateStatusBar()
1023 // let the user see the explicit message
1024 if (d.statusbar_timer_.isActive())
1031 void GuiView::showMessage()
1033 QString msg = toqstr(theGuiApp()->viewStatusMessage());
1034 if (msg.isEmpty()) {
1035 BufferView const * bv = currentBufferView();
1037 msg = toqstr(bv->cursor().currentState());
1039 msg = qt_("Welcome to LyX!");
1041 statusBar()->showMessage(msg);
1045 bool GuiView::event(QEvent * e)
1049 // Useful debug code:
1050 //case QEvent::ActivationChange:
1051 //case QEvent::WindowDeactivate:
1052 //case QEvent::Paint:
1053 //case QEvent::Enter:
1054 //case QEvent::Leave:
1055 //case QEvent::HoverEnter:
1056 //case QEvent::HoverLeave:
1057 //case QEvent::HoverMove:
1058 //case QEvent::StatusTip:
1059 //case QEvent::DragEnter:
1060 //case QEvent::DragLeave:
1061 //case QEvent::Drop:
1064 case QEvent::WindowActivate: {
1065 GuiView * old_view = guiApp->currentView();
1066 if (this == old_view) {
1068 return QMainWindow::event(e);
1070 if (old_view && old_view->currentBufferView()) {
1071 // save current selection to the selection buffer to allow
1072 // middle-button paste in this window.
1073 cap::saveSelection(old_view->currentBufferView()->cursor());
1075 guiApp->setCurrentView(this);
1076 if (d.current_work_area_) {
1077 BufferView & bv = d.current_work_area_->bufferView();
1078 connectBufferView(bv);
1079 connectBuffer(bv.buffer());
1080 // The document structure, name and dialogs might have
1081 // changed in another view.
1083 // The document settings needs to be reinitialised.
1084 updateDialog("document", "");
1087 resetWindowTitleAndIconText();
1090 return QMainWindow::event(e);
1093 case QEvent::ShortcutOverride: {
1096 #if (!defined Q_WS_X11) || (QT_VERSION >= 0x040500)
1097 if (isFullScreen() && menuBar()->isHidden()) {
1098 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
1099 // FIXME: we should also try to detect special LyX shortcut such as
1100 // Alt-P and Alt-M. Right now there is a hack in
1101 // GuiWorkArea::processKeySym() that hides again the menubar for
1103 if (ke->modifiers() & Qt::AltModifier && ke->key() != Qt::Key_Alt) {
1105 return QMainWindow::event(e);
1109 return QMainWindow::event(e);
1113 return QMainWindow::event(e);
1117 void GuiView::resetWindowTitleAndIconText()
1119 setWindowTitle(qt_("LyX"));
1120 setWindowIconText(qt_("LyX"));
1123 bool GuiView::focusNextPrevChild(bool /*next*/)
1130 bool GuiView::busy() const
1136 void GuiView::setBusy(bool busy)
1138 bool const busy_before = busy_ > 0;
1139 busy ? ++busy_ : --busy_;
1140 if ((busy_ > 0) == busy_before)
1141 // busy state didn't change
1144 if (d.current_work_area_) {
1145 d.current_work_area_->setUpdatesEnabled(!busy);
1147 d.current_work_area_->stopBlinkingCursor();
1149 d.current_work_area_->startBlinkingCursor();
1153 QApplication::setOverrideCursor(Qt::WaitCursor);
1155 QApplication::restoreOverrideCursor();
1159 GuiWorkArea * GuiView::workArea(int index)
1161 if (TabWorkArea * twa = d.currentTabWorkArea())
1162 if (index < twa->count())
1163 return dynamic_cast<GuiWorkArea *>(twa->widget(index));
1168 GuiWorkArea * GuiView::workArea(Buffer & buffer)
1170 if (currentWorkArea()
1171 && ¤tWorkArea()->bufferView().buffer() == &buffer)
1172 return (GuiWorkArea *) currentWorkArea();
1173 if (TabWorkArea * twa = d.currentTabWorkArea())
1174 return twa->workArea(buffer);
1179 GuiWorkArea * GuiView::addWorkArea(Buffer & buffer)
1181 // Automatically create a TabWorkArea if there are none yet.
1182 TabWorkArea * tab_widget = d.splitter_->count()
1183 ? d.currentTabWorkArea() : addTabWorkArea();
1184 return tab_widget->addWorkArea(buffer, *this);
1188 TabWorkArea * GuiView::addTabWorkArea()
1190 TabWorkArea * twa = new TabWorkArea;
1191 QObject::connect(twa, SIGNAL(currentWorkAreaChanged(GuiWorkArea *)),
1192 this, SLOT(on_currentWorkAreaChanged(GuiWorkArea *)));
1193 QObject::connect(twa, SIGNAL(lastWorkAreaRemoved()),
1194 this, SLOT(on_lastWorkAreaRemoved()));
1196 d.splitter_->addWidget(twa);
1197 d.stack_widget_->setCurrentWidget(d.splitter_);
1202 GuiWorkArea const * GuiView::currentWorkArea() const
1204 return d.current_work_area_;
1208 GuiWorkArea * GuiView::currentWorkArea()
1210 return d.current_work_area_;
1214 GuiWorkArea const * GuiView::currentMainWorkArea() const
1216 if (!d.currentTabWorkArea())
1218 return d.currentTabWorkArea()->currentWorkArea();
1222 GuiWorkArea * GuiView::currentMainWorkArea()
1224 if (!d.currentTabWorkArea())
1226 return d.currentTabWorkArea()->currentWorkArea();
1230 void GuiView::setCurrentWorkArea(GuiWorkArea * wa)
1232 LYXERR(Debug::DEBUG, "Setting current wa: " << wa << endl);
1234 d.current_work_area_ = 0;
1239 // FIXME: I've no clue why this is here and why it accesses
1240 // theGuiApp()->currentView, which might be 0 (bug 6464).
1241 // See also 27525 (vfr).
1242 if (theGuiApp()->currentView() == this
1243 && theGuiApp()->currentView()->currentWorkArea() == wa)
1246 if (currentBufferView())
1247 cap::saveSelection(currentBufferView()->cursor());
1249 theGuiApp()->setCurrentView(this);
1250 d.current_work_area_ = wa;
1252 // We need to reset this now, because it will need to be
1253 // right if the tabWorkArea gets reset in the for loop. We
1254 // will change it back if we aren't in that case.
1255 GuiWorkArea * const old_cmwa = d.current_main_work_area_;
1256 d.current_main_work_area_ = wa;
1258 for (int i = 0; i != d.splitter_->count(); ++i) {
1259 if (d.tabWorkArea(i)->setCurrentWorkArea(wa)) {
1260 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea()
1261 << ", Current main wa: " << currentMainWorkArea());
1266 d.current_main_work_area_ = old_cmwa;
1268 LYXERR(Debug::DEBUG, "This is not a tabbed wa");
1269 on_currentWorkAreaChanged(wa);
1270 BufferView & bv = wa->bufferView();
1271 bv.cursor().fixIfBroken();
1273 wa->setUpdatesEnabled(true);
1274 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() << ", Current main wa: " << currentMainWorkArea());
1278 void GuiView::removeWorkArea(GuiWorkArea * wa)
1280 LASSERT(wa, return);
1281 if (wa == d.current_work_area_) {
1283 disconnectBufferView();
1284 d.current_work_area_ = 0;
1285 d.current_main_work_area_ = 0;
1288 bool found_twa = false;
1289 for (int i = 0; i != d.splitter_->count(); ++i) {
1290 TabWorkArea * twa = d.tabWorkArea(i);
1291 if (twa->removeWorkArea(wa)) {
1292 // Found in this tab group, and deleted the GuiWorkArea.
1294 if (twa->count() != 0) {
1295 if (d.current_work_area_ == 0)
1296 // This means that we are closing the current GuiWorkArea, so
1297 // switch to the next GuiWorkArea in the found TabWorkArea.
1298 setCurrentWorkArea(twa->currentWorkArea());
1300 // No more WorkAreas in this tab group, so delete it.
1307 // It is not a tabbed work area (i.e., the search work area), so it
1308 // should be deleted by other means.
1309 LASSERT(found_twa, /* */);
1311 if (d.current_work_area_ == 0) {
1312 if (d.splitter_->count() != 0) {
1313 TabWorkArea * twa = d.currentTabWorkArea();
1314 setCurrentWorkArea(twa->currentWorkArea());
1316 // No more work areas, switch to the background widget.
1317 setCurrentWorkArea(0);
1323 LayoutBox * GuiView::getLayoutDialog() const
1329 void GuiView::updateLayoutList()
1332 d.layout_->updateContents(false);
1336 void GuiView::updateToolbars()
1338 ToolbarMap::iterator end = d.toolbars_.end();
1339 if (d.current_work_area_) {
1341 d.current_work_area_->bufferView().cursor().inMathed()
1342 && !d.current_work_area_->bufferView().cursor().inRegexped();
1344 lyx::getStatus(FuncRequest(LFUN_LAYOUT_TABULAR)).enabled();
1346 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).enabled() &&
1347 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).onOff(true);
1348 bool const mathmacrotemplate =
1349 lyx::getStatus(FuncRequest(LFUN_IN_MATHMACROTEMPLATE)).enabled();
1351 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1352 it->second->update(math, table, review, mathmacrotemplate);
1354 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1355 it->second->update(false, false, false, false);
1359 void GuiView::setBuffer(Buffer * newBuffer)
1361 LYXERR(Debug::DEBUG, "Setting buffer: " << newBuffer << endl);
1362 LASSERT(newBuffer, return);
1365 GuiWorkArea * wa = workArea(*newBuffer);
1367 newBuffer->masterBuffer()->updateBuffer();
1368 wa = addWorkArea(*newBuffer);
1369 // scroll to the position when the BufferView was last closed
1370 if (lyxrc.use_lastfilepos) {
1371 LastFilePosSection::FilePos filepos =
1372 theSession().lastFilePos().load(newBuffer->fileName());
1373 wa->bufferView().moveToPosition(filepos.pit, filepos.pos, 0, 0);
1376 //Disconnect the old buffer...there's no new one.
1379 connectBuffer(*newBuffer);
1380 connectBufferView(wa->bufferView());
1381 setCurrentWorkArea(wa);
1387 void GuiView::connectBuffer(Buffer & buf)
1389 buf.setGuiDelegate(this);
1393 void GuiView::disconnectBuffer()
1395 if (d.current_work_area_)
1396 d.current_work_area_->bufferView().buffer().setGuiDelegate(0);
1400 void GuiView::connectBufferView(BufferView & bv)
1402 bv.setGuiDelegate(this);
1406 void GuiView::disconnectBufferView()
1408 if (d.current_work_area_)
1409 d.current_work_area_->bufferView().setGuiDelegate(0);
1413 void GuiView::errors(string const & error_type, bool from_master)
1415 BufferView const * const bv = currentBufferView();
1419 ErrorList & el = from_master ?
1420 bv->buffer().masterBuffer()->errorList(error_type) :
1421 bv->buffer().errorList(error_type);
1425 string data = error_type;
1427 data = "from_master|" + error_type;
1428 showDialog("errorlist", data);
1432 void GuiView::updateTocItem(string const & type, DocIterator const & dit)
1434 d.toc_models_.updateItem(toqstr(type), dit);
1438 void GuiView::structureChanged()
1440 d.toc_models_.reset(documentBufferView());
1441 // Navigator needs more than a simple update in this case. It needs to be
1443 updateDialog("toc", "");
1447 void GuiView::updateDialog(string const & name, string const & data)
1449 if (!isDialogVisible(name))
1452 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
1453 if (it == d.dialogs_.end())
1456 Dialog * const dialog = it->second.get();
1457 if (dialog->isVisibleView())
1458 dialog->initialiseParams(data);
1462 BufferView * GuiView::documentBufferView()
1464 return currentMainWorkArea()
1465 ? ¤tMainWorkArea()->bufferView()
1470 BufferView const * GuiView::documentBufferView() const
1472 return currentMainWorkArea()
1473 ? ¤tMainWorkArea()->bufferView()
1478 BufferView * GuiView::currentBufferView()
1480 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1484 BufferView const * GuiView::currentBufferView() const
1486 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1490 #if (QT_VERSION >= 0x040400)
1491 docstring GuiView::GuiViewPrivate::autosaveAndDestroy(
1492 Buffer const * orig, Buffer * buffer)
1494 bool const success = buffer->autoSave();
1496 busyBuffers.remove(orig);
1498 ? _("Automatic save done.")
1499 : _("Automatic save failed!");
1504 void GuiView::autoSave()
1506 LYXERR(Debug::INFO, "Running autoSave()");
1508 Buffer * buffer = documentBufferView()
1509 ? &documentBufferView()->buffer() : 0;
1513 #if (QT_VERSION >= 0x040400)
1514 GuiViewPrivate::busyBuffers.insert(buffer);
1515 QFuture<docstring> f = QtConcurrent::run(GuiViewPrivate::autosaveAndDestroy,
1516 buffer, buffer->clone());
1517 d.autosave_watcher_.setFuture(f);
1521 resetAutosaveTimers();
1525 void GuiView::resetAutosaveTimers()
1528 d.autosave_timeout_.restart();
1532 bool GuiView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1535 Buffer * buf = currentBufferView()
1536 ? ¤tBufferView()->buffer() : 0;
1537 Buffer * doc_buffer = documentBufferView()
1538 ? &(documentBufferView()->buffer()) : 0;
1540 // Check whether we need a buffer
1541 if (!lyxaction.funcHasFlag(cmd.action(), LyXAction::NoBuffer) && !buf) {
1542 // no, exit directly
1543 flag.message(from_utf8(N_("Command not allowed with"
1544 "out any document open")));
1545 flag.setEnabled(false);
1549 if (cmd.origin() == FuncRequest::TOC) {
1550 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
1551 if (!toc || !toc->getStatus(documentBufferView()->cursor(), cmd, flag))
1552 flag.setEnabled(false);
1556 switch(cmd.action()) {
1557 case LFUN_BUFFER_IMPORT:
1560 case LFUN_MASTER_BUFFER_UPDATE:
1561 case LFUN_MASTER_BUFFER_VIEW:
1562 enable = doc_buffer && doc_buffer->parent() != 0
1563 && !d.processing_thread_watcher_.isRunning();
1566 case LFUN_BUFFER_UPDATE:
1567 case LFUN_BUFFER_VIEW: {
1568 if (!doc_buffer || d.processing_thread_watcher_.isRunning()) {
1572 string format = to_utf8(cmd.argument());
1573 if (cmd.argument().empty())
1574 format = doc_buffer->getDefaultOutputFormat();
1575 enable = doc_buffer->isExportableFormat(format);
1579 case LFUN_BUFFER_RELOAD:
1580 enable = doc_buffer && !doc_buffer->isUnnamed()
1581 && doc_buffer->fileName().exists()
1582 && (!doc_buffer->isClean()
1583 || doc_buffer->isExternallyModified(Buffer::timestamp_method));
1586 case LFUN_BUFFER_CHILD_OPEN:
1587 enable = doc_buffer;
1590 case LFUN_BUFFER_WRITE:
1591 enable = doc_buffer && (doc_buffer->isUnnamed() || !doc_buffer->isClean());
1594 //FIXME: This LFUN should be moved to GuiApplication.
1595 case LFUN_BUFFER_WRITE_ALL: {
1596 // We enable the command only if there are some modified buffers
1597 Buffer * first = theBufferList().first();
1602 // We cannot use a for loop as the buffer list is a cycle.
1604 if (!b->isClean()) {
1608 b = theBufferList().next(b);
1609 } while (b != first);
1613 case LFUN_BUFFER_WRITE_AS:
1614 enable = doc_buffer;
1617 case LFUN_BUFFER_CLOSE:
1618 enable = doc_buffer;
1621 case LFUN_BUFFER_CLOSE_ALL:
1622 enable = theBufferList().last() != theBufferList().first();
1625 case LFUN_SPLIT_VIEW:
1626 if (cmd.getArg(0) == "vertical")
1627 enable = doc_buffer && (d.splitter_->count() == 1 ||
1628 d.splitter_->orientation() == Qt::Vertical);
1630 enable = doc_buffer && (d.splitter_->count() == 1 ||
1631 d.splitter_->orientation() == Qt::Horizontal);
1634 case LFUN_CLOSE_TAB_GROUP:
1635 enable = d.currentTabWorkArea();
1638 case LFUN_TOOLBAR_TOGGLE: {
1639 string const name = cmd.getArg(0);
1640 if (GuiToolbar * t = toolbar(name))
1641 flag.setOnOff(t->isVisible());
1644 docstring const msg =
1645 bformat(_("Unknown toolbar \"%1$s\""), from_utf8(name));
1651 case LFUN_DROP_LAYOUTS_CHOICE:
1655 case LFUN_UI_TOGGLE:
1656 flag.setOnOff(isFullScreen());
1659 case LFUN_DIALOG_DISCONNECT_INSET:
1662 case LFUN_DIALOG_HIDE:
1663 // FIXME: should we check if the dialog is shown?
1666 case LFUN_DIALOG_TOGGLE:
1667 flag.setOnOff(isDialogVisible(cmd.getArg(0)));
1668 // fall through to set "enable"
1669 case LFUN_DIALOG_SHOW: {
1670 string const name = cmd.getArg(0);
1672 enable = name == "aboutlyx"
1673 || name == "file" //FIXME: should be removed.
1675 || name == "texinfo"
1676 || name == "progress"
1677 || name == "compare";
1678 else if (name == "print")
1679 enable = doc_buffer->isExportable("dvi")
1680 && lyxrc.print_command != "none";
1681 else if (name == "character" || name == "symbols") {
1682 if (!buf || buf->isReadonly())
1685 Cursor const & cur = currentBufferView()->cursor();
1686 enable = !(cur.inTexted() && cur.paragraph().isPassThru());
1689 else if (name == "latexlog")
1690 enable = FileName(doc_buffer->logName()).isReadableFile();
1691 else if (name == "spellchecker")
1692 enable = theSpellChecker() && !doc_buffer->isReadonly();
1693 else if (name == "vclog")
1694 enable = doc_buffer->lyxvc().inUse();
1698 case LFUN_DIALOG_UPDATE: {
1699 string const name = cmd.getArg(0);
1701 enable = name == "prefs";
1705 case LFUN_COMMAND_EXECUTE:
1707 case LFUN_MENU_OPEN:
1708 // Nothing to check.
1711 case LFUN_COMPLETION_INLINE:
1712 if (!d.current_work_area_
1713 || !d.current_work_area_->completer().inlinePossible(
1714 currentBufferView()->cursor()))
1718 case LFUN_COMPLETION_POPUP:
1719 if (!d.current_work_area_
1720 || !d.current_work_area_->completer().popupPossible(
1721 currentBufferView()->cursor()))
1725 case LFUN_COMPLETION_COMPLETE:
1726 if (!d.current_work_area_
1727 || !d.current_work_area_->completer().inlinePossible(
1728 currentBufferView()->cursor()))
1732 case LFUN_COMPLETION_ACCEPT:
1733 if (!d.current_work_area_
1734 || (!d.current_work_area_->completer().popupVisible()
1735 && !d.current_work_area_->completer().inlineVisible()
1736 && !d.current_work_area_->completer().completionAvailable()))
1740 case LFUN_COMPLETION_CANCEL:
1741 if (!d.current_work_area_
1742 || (!d.current_work_area_->completer().popupVisible()
1743 && !d.current_work_area_->completer().inlineVisible()))
1747 case LFUN_BUFFER_ZOOM_OUT:
1748 enable = doc_buffer && lyxrc.zoom > 10;
1751 case LFUN_BUFFER_ZOOM_IN:
1752 enable = doc_buffer;
1755 case LFUN_BUFFER_NEXT:
1756 case LFUN_BUFFER_PREVIOUS:
1757 // FIXME: should we check is there is an previous or next buffer?
1759 case LFUN_BUFFER_SWITCH:
1760 // toggle on the current buffer, but do not toggle off
1761 // the other ones (is that a good idea?)
1763 && to_utf8(cmd.argument()) == doc_buffer->absFileName())
1764 flag.setOnOff(true);
1767 case LFUN_VC_REGISTER:
1768 enable = doc_buffer && !doc_buffer->lyxvc().inUse();
1770 case LFUN_VC_CHECK_IN:
1771 enable = doc_buffer && doc_buffer->lyxvc().checkInEnabled();
1773 case LFUN_VC_CHECK_OUT:
1774 enable = doc_buffer && doc_buffer->lyxvc().checkOutEnabled();
1776 case LFUN_VC_LOCKING_TOGGLE:
1777 enable = doc_buffer && !doc_buffer->isReadonly()
1778 && doc_buffer->lyxvc().lockingToggleEnabled();
1779 flag.setOnOff(enable && doc_buffer->lyxvc().locking());
1781 case LFUN_VC_REVERT:
1782 enable = doc_buffer && doc_buffer->lyxvc().inUse() && !doc_buffer->isReadonly();
1784 case LFUN_VC_UNDO_LAST:
1785 enable = doc_buffer && doc_buffer->lyxvc().undoLastEnabled();
1787 case LFUN_VC_REPO_UPDATE:
1788 enable = doc_buffer && doc_buffer->lyxvc().repoUpdateEnabled();
1790 case LFUN_VC_COMMAND: {
1791 if (cmd.argument().empty())
1793 if (!doc_buffer && contains(cmd.getArg(0), 'D'))
1797 case LFUN_VC_COMPARE:
1798 enable = doc_buffer && doc_buffer->lyxvc().prepareFileRevisionEnabled();
1801 case LFUN_SERVER_GOTO_FILE_ROW:
1803 case LFUN_FORWARD_SEARCH:
1804 enable = !(lyxrc.forward_search_dvi.empty() && lyxrc.forward_search_pdf.empty());
1812 flag.setEnabled(false);
1818 static FileName selectTemplateFile()
1820 FileDialog dlg(qt_("Select template file"));
1821 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1822 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
1824 FileDialog::Result result = dlg.open(toqstr(lyxrc.template_path),
1825 QStringList(qt_("LyX Documents (*.lyx)")));
1827 if (result.first == FileDialog::Later)
1829 if (result.second.isEmpty())
1831 return FileName(fromqstr(result.second));
1835 Buffer * GuiView::loadDocument(FileName const & filename, bool tolastfiles)
1839 Buffer * newBuffer = 0;
1841 newBuffer = checkAndLoadLyXFile(filename);
1842 } catch (ExceptionMessage const & e) {
1848 message(_("Document not loaded."));
1853 newBuffer->errors("Parse");
1854 setBuffer(newBuffer);
1857 theSession().lastFiles().add(filename);
1864 void GuiView::openDocument(string const & fname)
1866 string initpath = lyxrc.document_path;
1868 if (documentBufferView()) {
1869 string const trypath = documentBufferView()->buffer().filePath();
1870 // If directory is writeable, use this as default.
1871 if (FileName(trypath).isDirWritable())
1877 if (fname.empty()) {
1878 FileDialog dlg(qt_("Select document to open"), LFUN_FILE_OPEN);
1879 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1880 dlg.setButton2(qt_("Examples|#E#e"),
1881 toqstr(addPath(package().system_support().absFileName(), "examples")));
1883 QStringList filter(qt_("LyX Documents (*.lyx)"));
1884 filter << qt_("LyX-1.3.x Documents (*.lyx13)")
1885 << qt_("LyX-1.4.x Documents (*.lyx14)")
1886 << qt_("LyX-1.5.x Documents (*.lyx15)")
1887 << qt_("LyX-1.6.x Documents (*.lyx16)");
1888 FileDialog::Result result =
1889 dlg.open(toqstr(initpath), filter);
1891 if (result.first == FileDialog::Later)
1894 filename = fromqstr(result.second);
1896 // check selected filename
1897 if (filename.empty()) {
1898 message(_("Canceled."));
1904 // get absolute path of file and add ".lyx" to the filename if
1906 FileName const fullname =
1907 fileSearch(string(), filename, "lyx", support::may_not_exist);
1908 if (!fullname.empty())
1909 filename = fullname.absFileName();
1911 if (!fullname.onlyPath().isDirectory()) {
1912 Alert::warning(_("Invalid filename"),
1913 bformat(_("The directory in the given path\n%1$s\ndoes not exist."),
1914 from_utf8(fullname.absFileName())));
1918 // if the file doesn't exist and isn't already open (bug 6645),
1919 // let the user create one
1920 if (!fullname.exists() && !theBufferList().exists(fullname)) {
1921 // the user specifically chose this name. Believe him.
1922 Buffer * const b = newFile(filename, string(), true);
1928 docstring const disp_fn = makeDisplayPath(filename);
1929 message(bformat(_("Opening document %1$s..."), disp_fn));
1932 Buffer * buf = loadDocument(fullname);
1934 str2 = bformat(_("Document %1$s opened."), disp_fn);
1935 if (buf->lyxvc().inUse())
1936 str2 += " " + from_utf8(buf->lyxvc().versionString()) +
1937 " " + _("Version control detected.");
1939 str2 = bformat(_("Could not open document %1$s"), disp_fn);
1944 // FIXME: clean that
1945 static bool import(GuiView * lv, FileName const & filename,
1946 string const & format, ErrorList & errorList)
1948 FileName const lyxfile(support::changeExtension(filename.absFileName(), ".lyx"));
1950 string loader_format;
1951 vector<string> loaders = theConverters().loaders();
1952 if (find(loaders.begin(), loaders.end(), format) == loaders.end()) {
1953 for (vector<string>::const_iterator it = loaders.begin();
1954 it != loaders.end(); ++it) {
1955 if (!theConverters().isReachable(format, *it))
1958 string const tofile =
1959 support::changeExtension(filename.absFileName(),
1960 formats.extension(*it));
1961 if (!theConverters().convert(0, filename, FileName(tofile),
1962 filename, format, *it, errorList))
1964 loader_format = *it;
1967 if (loader_format.empty()) {
1968 frontend::Alert::error(_("Couldn't import file"),
1969 bformat(_("No information for importing the format %1$s."),
1970 formats.prettyName(format)));
1974 loader_format = format;
1976 if (loader_format == "lyx") {
1977 Buffer * buf = lv->loadDocument(lyxfile);
1981 Buffer * const b = newFile(lyxfile.absFileName(), string(), true);
1985 bool as_paragraphs = loader_format == "textparagraph";
1986 string filename2 = (loader_format == format) ? filename.absFileName()
1987 : support::changeExtension(filename.absFileName(),
1988 formats.extension(loader_format));
1989 lv->currentBufferView()->insertPlaintextFile(FileName(filename2),
1991 guiApp->setCurrentView(lv);
1992 lyx::dispatch(FuncRequest(LFUN_MARK_OFF));
1999 void GuiView::importDocument(string const & argument)
2002 string filename = split(argument, format, ' ');
2004 LYXERR(Debug::INFO, format << " file: " << filename);
2006 // need user interaction
2007 if (filename.empty()) {
2008 string initpath = lyxrc.document_path;
2009 if (documentBufferView()) {
2010 string const trypath = documentBufferView()->buffer().filePath();
2011 // If directory is writeable, use this as default.
2012 if (FileName(trypath).isDirWritable())
2016 docstring const text = bformat(_("Select %1$s file to import"),
2017 formats.prettyName(format));
2019 FileDialog dlg(toqstr(text), LFUN_BUFFER_IMPORT);
2020 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2021 dlg.setButton2(qt_("Examples|#E#e"),
2022 toqstr(addPath(package().system_support().absFileName(), "examples")));
2024 docstring filter = formats.prettyName(format);
2027 filter += from_utf8(formats.extension(format));
2030 FileDialog::Result result =
2031 dlg.open(toqstr(initpath), fileFilters(toqstr(filter)));
2033 if (result.first == FileDialog::Later)
2036 filename = fromqstr(result.second);
2038 // check selected filename
2039 if (filename.empty())
2040 message(_("Canceled."));
2043 if (filename.empty())
2046 // get absolute path of file
2047 FileName const fullname(support::makeAbsPath(filename));
2049 FileName const lyxfile(support::changeExtension(fullname.absFileName(), ".lyx"));
2051 // Check if the document already is open
2052 Buffer * buf = theBufferList().getBuffer(lyxfile);
2055 if (!closeBuffer()) {
2056 message(_("Canceled."));
2061 docstring const displaypath = makeDisplayPath(lyxfile.absFileName(), 30);
2063 // if the file exists already, and we didn't do
2064 // -i lyx thefile.lyx, warn
2065 if (lyxfile.exists() && fullname != lyxfile) {
2067 docstring text = bformat(_("The document %1$s already exists.\n\n"
2068 "Do you want to overwrite that document?"), displaypath);
2069 int const ret = Alert::prompt(_("Overwrite document?"),
2070 text, 0, 1, _("&Overwrite"), _("&Cancel"));
2073 message(_("Canceled."));
2078 message(bformat(_("Importing %1$s..."), displaypath));
2079 ErrorList errorList;
2080 if (import(this, fullname, format, errorList))
2081 message(_("imported."));
2083 message(_("file not imported!"));
2085 // FIXME (Abdel 12/08/06): Is there a need to display the error list here?
2089 void GuiView::newDocument(string const & filename, bool from_template)
2091 FileName initpath(lyxrc.document_path);
2092 if (documentBufferView()) {
2093 FileName const trypath(documentBufferView()->buffer().filePath());
2094 // If directory is writeable, use this as default.
2095 if (trypath.isDirWritable())
2099 string templatefile;
2100 if (from_template) {
2101 templatefile = selectTemplateFile().absFileName();
2102 if (templatefile.empty())
2107 if (filename.empty())
2108 b = newUnnamedFile(initpath, to_utf8(_("newfile")), templatefile);
2110 b = newFile(filename, templatefile, true);
2115 // If no new document could be created, it is unsure
2116 // whether there is a valid BufferView.
2117 if (currentBufferView())
2118 // Ensure the cursor is correctly positioned on screen.
2119 currentBufferView()->showCursor();
2123 void GuiView::insertLyXFile(docstring const & fname)
2125 BufferView * bv = documentBufferView();
2130 FileName filename(to_utf8(fname));
2131 if (filename.empty()) {
2132 // Launch a file browser
2134 string initpath = lyxrc.document_path;
2135 string const trypath = bv->buffer().filePath();
2136 // If directory is writeable, use this as default.
2137 if (FileName(trypath).isDirWritable())
2141 FileDialog dlg(qt_("Select LyX document to insert"), LFUN_FILE_INSERT);
2142 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2143 dlg.setButton2(qt_("Examples|#E#e"),
2144 toqstr(addPath(package().system_support().absFileName(),
2147 FileDialog::Result result = dlg.open(toqstr(initpath),
2148 QStringList(qt_("LyX Documents (*.lyx)")));
2150 if (result.first == FileDialog::Later)
2154 filename.set(fromqstr(result.second));
2156 // check selected filename
2157 if (filename.empty()) {
2158 // emit message signal.
2159 message(_("Canceled."));
2164 bv->insertLyXFile(filename);
2165 bv->buffer().errors("Parse");
2169 void GuiView::insertPlaintextFile(docstring const & fname,
2172 BufferView * bv = documentBufferView();
2176 if (!fname.empty() && !FileName::isAbsolute(to_utf8(fname))) {
2177 message(_("Absolute filename expected."));
2182 FileName filename(to_utf8(fname));
2184 if (!filename.empty()) {
2185 bv->insertPlaintextFile(filename, asParagraph);
2189 FileDialog dlg(qt_("Select file to insert"), (asParagraph ?
2190 LFUN_FILE_INSERT_PLAINTEXT_PARA : LFUN_FILE_INSERT_PLAINTEXT));
2192 FileDialog::Result result = dlg.open(toqstr(bv->buffer().filePath()),
2193 QStringList(qt_("All Files (*)")));
2195 if (result.first == FileDialog::Later)
2199 filename.set(fromqstr(result.second));
2201 // check selected filename
2202 if (filename.empty()) {
2203 // emit message signal.
2204 message(_("Canceled."));
2208 bv->insertPlaintextFile(filename, asParagraph);
2212 bool GuiView::renameBuffer(Buffer & b, docstring const & newname)
2214 FileName fname = b.fileName();
2215 FileName const oldname = fname;
2217 if (!newname.empty()) {
2219 fname = support::makeAbsPath(to_utf8(newname), oldname.onlyPath().absFileName());
2221 // Switch to this Buffer.
2224 // No argument? Ask user through dialog.
2226 FileDialog dlg(qt_("Choose a filename to save document as"),
2227 LFUN_BUFFER_WRITE_AS);
2228 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2229 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
2231 if (!isLyXFileName(fname.absFileName()))
2232 fname.changeExtension(".lyx");
2234 FileDialog::Result result =
2235 dlg.save(toqstr(fname.onlyPath().absFileName()),
2236 QStringList(qt_("LyX Documents (*.lyx)")),
2237 toqstr(fname.onlyFileName()));
2239 if (result.first == FileDialog::Later)
2242 fname.set(fromqstr(result.second));
2247 if (!isLyXFileName(fname.absFileName()))
2248 fname.changeExtension(".lyx");
2251 // fname is now the new Buffer location.
2252 if (FileName(fname).exists()) {
2253 docstring const file = makeDisplayPath(fname.absFileName(), 30);
2254 docstring text = bformat(_("The document %1$s already "
2255 "exists.\n\nDo you want to "
2256 "overwrite that document?"),
2258 int const ret = Alert::prompt(_("Overwrite document?"),
2259 text, 0, 2, _("&Overwrite"), _("&Rename"), _("&Cancel"));
2262 case 1: return renameBuffer(b, docstring());
2263 case 2: return false;
2267 return saveBuffer(b, fname);
2271 bool GuiView::saveBuffer(Buffer & b) {
2272 return saveBuffer(b, FileName());
2276 bool GuiView::saveBuffer(Buffer & b, FileName const & fn)
2278 if (workArea(b) && workArea(b)->inDialogMode())
2281 if (fn.empty() && b.isUnnamed())
2282 return renameBuffer(b, docstring());
2288 success = b.saveAs(fn);
2291 theSession().lastFiles().add(b.fileName());
2295 // Switch to this Buffer.
2298 // FIXME: we don't tell the user *WHY* the save failed !!
2299 docstring const file = makeDisplayPath(b.absFileName(), 30);
2300 docstring text = bformat(_("The document %1$s could not be saved.\n\n"
2301 "Do you want to rename the document and "
2302 "try again?"), file);
2303 int const ret = Alert::prompt(_("Rename and save?"),
2304 text, 0, 2, _("&Rename"), _("&Retry"), _("&Cancel"));
2307 if (!renameBuffer(b, docstring()))
2316 return saveBuffer(b);
2320 bool GuiView::hideWorkArea(GuiWorkArea * wa)
2322 return closeWorkArea(wa, false);
2326 bool GuiView::closeWorkArea(GuiWorkArea * wa)
2328 Buffer & buf = wa->bufferView().buffer();
2329 return closeWorkArea(wa, !buf.parent());
2333 bool GuiView::closeBuffer()
2335 GuiWorkArea * wa = currentMainWorkArea();
2336 setCurrentWorkArea(wa);
2337 Buffer & buf = wa->bufferView().buffer();
2338 return wa && closeWorkArea(wa, !buf.parent());
2342 void GuiView::writeSession() const {
2343 GuiWorkArea const * active_wa = currentMainWorkArea();
2344 for (int i = 0; i < d.splitter_->count(); ++i) {
2345 TabWorkArea * twa = d.tabWorkArea(i);
2346 for (int j = 0; j < twa->count(); ++j) {
2347 GuiWorkArea * wa = static_cast<GuiWorkArea *>(twa->widget(j));
2348 Buffer & buf = wa->bufferView().buffer();
2349 theSession().lastOpened().add(buf.fileName(), wa == active_wa);
2355 bool GuiView::closeBufferAll()
2357 // Close the workareas in all other views
2358 QList<int> const ids = guiApp->viewIds();
2359 for (int i = 0; i != ids.size(); ++i) {
2360 if (id_ != ids[i] && !guiApp->view(ids[i]).closeWorkAreaAll())
2364 // Close our own workareas
2365 if (!closeWorkAreaAll())
2368 // Now close the hidden buffers. We prevent hidden buffers from being
2369 // dirty, so we can just close them.
2370 theBufferList().closeAll();
2375 bool GuiView::closeWorkAreaAll()
2377 setCurrentWorkArea(currentMainWorkArea());
2379 // We might be in a situation that there is still a tabWorkArea, but
2380 // there are no tabs anymore. This can happen when we get here after a
2381 // TabWorkArea::lastWorkAreaRemoved() signal. Therefore we count how
2382 // many TabWorkArea's have no documents anymore.
2385 // We have to call count() each time, because it can happen that
2386 // more than one splitter will disappear in one iteration (bug 5998).
2387 for (; d.splitter_->count() > empty_twa; ) {
2388 TabWorkArea * twa = d.tabWorkArea(empty_twa);
2390 if (twa->count() == 0)
2393 setCurrentWorkArea(twa->currentWorkArea());
2394 if (!closeTabWorkArea(twa))
2402 bool GuiView::closeWorkArea(GuiWorkArea * wa, bool close_buffer)
2407 Buffer & buf = wa->bufferView().buffer();
2409 if (close_buffer && GuiViewPrivate::busyBuffers.contains(&buf)) {
2410 Alert::warning(_("Close document"),
2411 _("Document could not be closed because it is being processed by LyX."));
2416 return closeBuffer(buf);
2418 if (!inMultiTabs(wa))
2419 if (!saveBufferIfNeeded(buf, true))
2427 bool GuiView::closeBuffer(Buffer & buf)
2429 // If we are in a close_event all children will be closed in some time,
2430 // so no need to do it here. This will ensure that the children end up
2431 // in the session file in the correct order. If we close the master
2432 // buffer, we can close or release the child buffers here too.
2433 bool success = true;
2435 ListOfBuffers clist = buf.getChildren();
2436 ListOfBuffers::const_iterator it = clist.begin();
2437 ListOfBuffers::const_iterator const bend = clist.end();
2438 for (; it != bend; ++it) {
2439 // If a child is dirty, do not close
2440 // without user intervention
2441 //FIXME: should we look in other tabworkareas?
2442 Buffer * child_buf = *it;
2443 GuiWorkArea * child_wa = workArea(*child_buf);
2445 if (!closeWorkArea(child_wa, true)) {
2450 theBufferList().releaseChild(&buf, child_buf);
2454 // goto bookmark to update bookmark pit.
2455 //FIXME: we should update only the bookmarks related to this buffer!
2456 LYXERR(Debug::DEBUG, "GuiView::closeBuffer()");
2457 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
2458 guiApp->gotoBookmark(i+1, false, false);
2460 if (saveBufferIfNeeded(buf, false)) {
2461 buf.removeAutosaveFile();
2462 theBufferList().release(&buf);
2466 // open all children again to avoid a crash because of dangling
2467 // pointers (bug 6603)
2473 bool GuiView::closeTabWorkArea(TabWorkArea * twa)
2475 while (twa == d.currentTabWorkArea()) {
2476 twa->setCurrentIndex(twa->count()-1);
2478 GuiWorkArea * wa = twa->currentWorkArea();
2479 Buffer & b = wa->bufferView().buffer();
2481 // We only want to close the buffer if the same buffer is not visible
2482 // in another view, and if this is not a child and if we are closing
2483 // a view (not a tabgroup).
2484 bool const close_buffer =
2485 !inOtherView(b) && !b.parent() && closing_;
2487 if (!closeWorkArea(wa, close_buffer))
2494 bool GuiView::saveBufferIfNeeded(Buffer & buf, bool hiding)
2496 if (buf.isClean() || buf.paragraphs().empty())
2499 // Switch to this Buffer.
2504 if (buf.isUnnamed())
2505 file = from_utf8(buf.fileName().onlyFileName());
2507 file = buf.fileName().displayName(30);
2509 // Bring this window to top before asking questions.
2514 if (hiding && buf.isUnnamed()) {
2515 docstring const text = bformat(_("The document %1$s has not been "
2516 "saved yet.\n\nDo you want to save "
2517 "the document?"), file);
2518 ret = Alert::prompt(_("Save new document?"),
2519 text, 0, 1, _("&Save"), _("&Cancel"));
2523 docstring const text = bformat(_("The document %1$s has unsaved changes."
2524 "\n\nDo you want to save the document or discard the changes?"), file);
2525 ret = Alert::prompt(_("Save changed document?"),
2526 text, 0, 2, _("&Save"), _("&Discard"), _("&Cancel"));
2531 if (!saveBuffer(buf))
2535 // If we crash after this we could have no autosave file
2536 // but I guess this is really improbable (Jug).
2537 // Sometimes improbable things happen:
2538 // - see bug http://www.lyx.org/trac/ticket/6587 (ps)
2539 // buf.removeAutosaveFile();
2541 // revert all changes
2552 bool GuiView::inMultiTabs(GuiWorkArea * wa)
2554 Buffer & buf = wa->bufferView().buffer();
2556 for (int i = 0; i != d.splitter_->count(); ++i) {
2557 GuiWorkArea * wa_ = d.tabWorkArea(i)->workArea(buf);
2558 if (wa_ && wa_ != wa)
2561 return inOtherView(buf);
2565 bool GuiView::inOtherView(Buffer & buf)
2567 QList<int> const ids = guiApp->viewIds();
2569 for (int i = 0; i != ids.size(); ++i) {
2573 if (guiApp->view(ids[i]).workArea(buf))
2580 void GuiView::gotoNextOrPreviousBuffer(NextOrPrevious np)
2582 if (!documentBufferView())
2585 if (TabWorkArea * twa = d.currentTabWorkArea()) {
2586 Buffer * const curbuf = &documentBufferView()->buffer();
2587 int nwa = twa->count();
2588 for (int i = 0; i < nwa; ++i) {
2589 if (&workArea(i)->bufferView().buffer() == curbuf) {
2591 if (np == NEXTBUFFER)
2592 next_index = (i == nwa - 1 ? 0 : i + 1);
2594 next_index = (i == 0 ? nwa - 1 : i - 1);
2595 setBuffer(&workArea(next_index)->bufferView().buffer());
2603 /// make sure the document is saved
2604 static bool ensureBufferClean(Buffer * buffer)
2606 LASSERT(buffer, return false);
2607 if (buffer->isClean() && !buffer->isUnnamed())
2610 docstring const file = buffer->fileName().displayName(30);
2613 if (!buffer->isUnnamed()) {
2614 text = bformat(_("The document %1$s has unsaved "
2615 "changes.\n\nDo you want to save "
2616 "the document?"), file);
2617 title = _("Save changed document?");
2620 text = bformat(_("The document %1$s has not been "
2621 "saved yet.\n\nDo you want to save "
2622 "the document?"), file);
2623 title = _("Save new document?");
2625 int const ret = Alert::prompt(title, text, 0, 1, _("&Save"), _("&Cancel"));
2628 dispatch(FuncRequest(LFUN_BUFFER_WRITE));
2630 return buffer->isClean() && !buffer->isUnnamed();
2634 bool GuiView::reloadBuffer(Buffer & buf)
2636 Buffer::ReadStatus status = buf.reload();
2637 return status == Buffer::ReadSuccess;
2641 void GuiView::checkExternallyModifiedBuffers()
2643 BufferList::iterator bit = theBufferList().begin();
2644 BufferList::iterator const bend = theBufferList().end();
2645 for (; bit != bend; ++bit) {
2646 Buffer * buf = *bit;
2647 if (buf->fileName().exists()
2648 && buf->isExternallyModified(Buffer::checksum_method)) {
2649 docstring text = bformat(_("Document \n%1$s\n has been externally modified."
2650 " Reload now? Any local changes will be lost."),
2651 from_utf8(buf->absFileName()));
2652 int const ret = Alert::prompt(_("Reload externally changed document?"),
2653 text, 0, 1, _("&Reload"), _("&Cancel"));
2661 void GuiView::dispatchVC(FuncRequest const & cmd, DispatchResult & dr)
2663 Buffer * buffer = documentBufferView()
2664 ? &(documentBufferView()->buffer()) : 0;
2666 switch (cmd.action()) {
2667 case LFUN_VC_REGISTER:
2668 if (!buffer || !ensureBufferClean(buffer))
2670 if (!buffer->lyxvc().inUse()) {
2671 if (buffer->lyxvc().registrer()) {
2672 reloadBuffer(*buffer);
2673 dr.suppressMessageUpdate();
2678 case LFUN_VC_CHECK_IN:
2679 if (!buffer || !ensureBufferClean(buffer))
2681 if (buffer->lyxvc().inUse() && !buffer->isReadonly()) {
2682 dr.setMessage(buffer->lyxvc().checkIn());
2683 if (!dr.message().empty())
2684 reloadBuffer(*buffer);
2688 case LFUN_VC_CHECK_OUT:
2689 if (!buffer || !ensureBufferClean(buffer))
2691 if (buffer->lyxvc().inUse()) {
2692 dr.setMessage(buffer->lyxvc().checkOut());
2693 reloadBuffer(*buffer);
2697 case LFUN_VC_LOCKING_TOGGLE:
2698 LASSERT(buffer, return);
2699 if (!ensureBufferClean(buffer) || buffer->isReadonly())
2701 if (buffer->lyxvc().inUse()) {
2702 string res = buffer->lyxvc().lockingToggle();
2704 frontend::Alert::error(_("Revision control error."),
2705 _("Error when setting the locking property."));
2708 reloadBuffer(*buffer);
2713 case LFUN_VC_REVERT:
2714 LASSERT(buffer, return);
2715 if (buffer->lyxvc().revert()) {
2716 reloadBuffer(*buffer);
2717 dr.suppressMessageUpdate();
2721 case LFUN_VC_UNDO_LAST:
2722 LASSERT(buffer, return);
2723 buffer->lyxvc().undoLast();
2724 reloadBuffer(*buffer);
2725 dr.suppressMessageUpdate();
2728 case LFUN_VC_REPO_UPDATE:
2729 LASSERT(buffer, return);
2730 if (ensureBufferClean(buffer)) {
2731 dr.setMessage(buffer->lyxvc().repoUpdate());
2732 checkExternallyModifiedBuffers();
2736 case LFUN_VC_COMMAND: {
2737 string flag = cmd.getArg(0);
2738 if (buffer && contains(flag, 'R') && !ensureBufferClean(buffer))
2741 if (contains(flag, 'M')) {
2742 if (!Alert::askForText(message, _("LyX VC: Log Message")))
2745 string path = cmd.getArg(1);
2746 if (contains(path, "$$p") && buffer)
2747 path = subst(path, "$$p", buffer->filePath());
2748 LYXERR(Debug::LYXVC, "Directory: " << path);
2750 if (!pp.isReadableDirectory()) {
2751 lyxerr << _("Directory is not accessible.") << endl;
2754 support::PathChanger p(pp);
2756 string command = cmd.getArg(2);
2757 if (command.empty())
2760 command = subst(command, "$$i", buffer->absFileName());
2761 command = subst(command, "$$p", buffer->filePath());
2763 command = subst(command, "$$m", to_utf8(message));
2764 LYXERR(Debug::LYXVC, "Command: " << command);
2766 one.startscript(Systemcall::Wait, command);
2770 if (contains(flag, 'I'))
2771 buffer->markDirty();
2772 if (contains(flag, 'R'))
2773 reloadBuffer(*buffer);
2778 case LFUN_VC_COMPARE: {
2780 if (cmd.argument().empty()) {
2781 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "comparehistory"));
2785 string rev1 = cmd.getArg(0);
2789 if (!buffer->lyxvc().prepareFileRevision(rev1, f1))
2792 if (isStrInt(rev1) && convert<int>(rev1) <= 0) {
2793 f2 = buffer->absFileName();
2795 string rev2 = cmd.getArg(1);
2799 if (!buffer->lyxvc().prepareFileRevision(rev2, f2))
2803 LYXERR(Debug::LYXVC, "Launching comparison for fetched revisions:\n" <<
2804 f1 << "\n" << f2 << "\n" );
2805 string par = "compare run " + quoteName(f1) + " " + quoteName(f2);
2806 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, par));
2816 void GuiView::openChildDocument(string const & fname)
2818 LASSERT(documentBufferView(), return);
2819 Buffer & buffer = documentBufferView()->buffer();
2820 FileName const filename = support::makeAbsPath(fname, buffer.filePath());
2821 documentBufferView()->saveBookmark(false);
2823 if (theBufferList().exists(filename)) {
2824 child = theBufferList().getBuffer(filename);
2827 message(bformat(_("Opening child document %1$s..."),
2828 makeDisplayPath(filename.absFileName())));
2829 child = loadDocument(filename, false);
2831 // Set the parent name of the child document.
2832 // This makes insertion of citations and references in the child work,
2833 // when the target is in the parent or another child document.
2835 child->setParent(&buffer);
2839 bool GuiView::goToFileRow(string const & argument)
2843 size_t i = argument.find_last_of(' ');
2844 if (i != string::npos) {
2845 file_name = os::internal_path(trim(argument.substr(0, i)));
2846 istringstream is(argument.substr(i + 1));
2851 if (i == string::npos) {
2852 LYXERR0("Wrong argument: " << argument);
2856 string const abstmp = package().temp_dir().absFileName();
2857 string const realtmp = package().temp_dir().realPath();
2858 // We have to use os::path_prefix_is() here, instead of
2859 // simply prefixIs(), because the file name comes from
2860 // an external application and may need case adjustment.
2861 if (os::path_prefix_is(file_name, abstmp, os::CASE_ADJUSTED)
2862 || os::path_prefix_is(file_name, realtmp, os::CASE_ADJUSTED)) {
2863 // Needed by inverse dvi search. If it is a file
2864 // in tmpdir, call the apropriated function.
2865 // If tmpdir is a symlink, we may have the real
2866 // path passed back, so we correct for that.
2867 if (!prefixIs(file_name, abstmp))
2868 file_name = subst(file_name, realtmp, abstmp);
2869 buf = theBufferList().getBufferFromTmp(file_name);
2871 // Must replace extension of the file to be .lyx
2872 // and get full path
2873 FileName const s = fileSearch(string(),
2874 support::changeExtension(file_name, ".lyx"), "lyx");
2875 // Either change buffer or load the file
2876 if (theBufferList().exists(s))
2877 buf = theBufferList().getBuffer(s);
2878 else if (s.exists()) {
2879 buf = loadDocument(s);
2884 _("File does not exist: %1$s"),
2885 makeDisplayPath(file_name)));
2890 documentBufferView()->setCursorFromRow(row);
2895 #if (QT_VERSION >= 0x040400)
2897 docstring GuiView::GuiViewPrivate::runAndDestroy(const T& func, Buffer const * orig, Buffer * buffer, string const & format, string const & msg)
2899 bool const update_unincluded =
2900 buffer->params().maintain_unincluded_children
2901 && !buffer->params().getIncludedChildren().empty();
2902 bool const success = func(format, update_unincluded);
2904 busyBuffers.remove(orig);
2905 if (msg == "preview") {
2907 ? bformat(_("Successful preview of format: %1$s"), from_utf8(format))
2908 : bformat(_("Error while previewing format: %1$s"), from_utf8(format));
2911 ? bformat(_("Successful export to format: %1$s"), from_utf8(format))
2912 : bformat(_("Error while exporting format: %1$s"), from_utf8(format));
2916 docstring GuiView::GuiViewPrivate::compileAndDestroy(Buffer const * orig, Buffer * buffer, string const & format)
2918 bool (Buffer::* mem_func)(std::string const &, bool, bool) const = &Buffer::doExport;
2919 return runAndDestroy(bind(mem_func, buffer, _1, true, _2), orig, buffer, format, "export");
2923 docstring GuiView::GuiViewPrivate::exportAndDestroy(Buffer const * orig, Buffer * buffer, string const & format)
2925 bool (Buffer::* mem_func)(std::string const &, bool, bool) const = &Buffer::doExport;
2926 return runAndDestroy(bind(mem_func, buffer, _1, false, _2), orig, buffer, format, "export");
2930 docstring GuiView::GuiViewPrivate::previewAndDestroy(Buffer const * orig, Buffer * buffer, string const & format)
2932 bool(Buffer::* mem_func)(std::string const &, bool) const = &Buffer::preview;
2933 return runAndDestroy(bind(mem_func, buffer, _1, _2), orig, buffer, format, "preview");
2938 // not used, but the linker needs them
2940 docstring GuiView::GuiViewPrivate::compileAndDestroy(
2941 Buffer const *, Buffer *, string const &)
2947 docstring GuiView::GuiViewPrivate::exportAndDestroy(
2948 Buffer const *, Buffer *, string const &)
2954 docstring GuiView::GuiViewPrivate::previewAndDestroy(
2955 Buffer const *, Buffer *, string const &)
2963 bool GuiView::GuiViewPrivate::asyncBufferProcessing(
2964 string const & argument,
2965 Buffer const * used_buffer,
2966 docstring const & msg,
2967 docstring (*asyncFunc)(Buffer const *, Buffer *, string const &),
2968 bool (Buffer::*syncFunc)(string const &, bool, bool) const,
2969 bool (Buffer::*previewFunc)(string const &, bool) const)
2974 string format = argument;
2976 format = used_buffer->getDefaultOutputFormat();
2978 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
2980 progress_->clearMessages();
2983 GuiViewPrivate::busyBuffers.insert(used_buffer);
2984 QFuture<docstring> f = QtConcurrent::run(
2987 used_buffer->clone(),
2989 setPreviewFuture(f);
2990 last_export_format = used_buffer->bufferFormat();
2993 // We are asynchronous, so we don't know here anything about the success
2997 // TODO check here if it breaks exporting with Qt < 4.4
2998 bool const update_unincluded =
2999 used_buffer->params().maintain_unincluded_children &&
3000 !used_buffer->params().getIncludedChildren().empty();
3001 return (used_buffer->*syncFunc)(format, true, update_unincluded);
3002 } else if (previewFunc) {
3003 return (used_buffer->*previewFunc)(format, false);
3010 void GuiView::dispatchToBufferView(FuncRequest const & cmd, DispatchResult & dr)
3012 BufferView * bv = currentBufferView();
3015 // Let the current BufferView dispatch its own actions.
3016 bv->dispatch(cmd, dr);
3017 if (dr.dispatched())
3020 // Try with the document BufferView dispatch if any.
3021 BufferView * doc_bv = documentBufferView();
3023 doc_bv->dispatch(cmd, dr);
3024 if (dr.dispatched())
3028 // Then let the current Cursor dispatch its own actions.
3029 bv->cursor().dispatch(cmd);
3031 // update completion. We do it here and not in
3032 // processKeySym to avoid another redraw just for a
3033 // changed inline completion
3034 if (cmd.origin() == FuncRequest::KEYBOARD) {
3035 if (cmd.action() == LFUN_SELF_INSERT
3036 || (cmd.action() == LFUN_ERT_INSERT && bv->cursor().inMathed()))
3037 updateCompletion(bv->cursor(), true, true);
3038 else if (cmd.action() == LFUN_CHAR_DELETE_BACKWARD)
3039 updateCompletion(bv->cursor(), false, true);
3041 updateCompletion(bv->cursor(), false, false);
3044 dr = bv->cursor().result();
3048 void GuiView::dispatch(FuncRequest const & cmd, DispatchResult & dr)
3050 BufferView * bv = currentBufferView();
3051 // By default we won't need any update.
3052 dr.screenUpdate(Update::None);
3053 // assume cmd will be dispatched
3054 dr.dispatched(true);
3056 Buffer * doc_buffer = documentBufferView()
3057 ? &(documentBufferView()->buffer()) : 0;
3059 if (cmd.origin() == FuncRequest::TOC) {
3060 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
3061 // FIXME: do we need to pass a DispatchResult object here?
3062 toc->doDispatch(bv->cursor(), cmd);
3066 string const argument = to_utf8(cmd.argument());
3068 switch(cmd.action()) {
3069 case LFUN_BUFFER_CHILD_OPEN:
3070 openChildDocument(to_utf8(cmd.argument()));
3073 case LFUN_BUFFER_IMPORT:
3074 importDocument(to_utf8(cmd.argument()));
3077 case LFUN_BUFFER_EXPORT: {
3080 // GCC only sees strfwd.h when building merged
3081 if (::lyx::operator==(cmd.argument(), "custom")) {
3082 dispatch(FuncRequest(LFUN_DIALOG_SHOW, "sendto"), dr);
3085 #if QT_VERSION < 0x040400
3086 if (!doc_buffer->doExport(argument, false)) {
3088 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
3092 /* TODO/Review: Is it a problem to also export the children?
3093 See the update_unincluded flag */
3094 d.asyncBufferProcessing(argument,
3097 &GuiViewPrivate::exportAndDestroy,
3100 // TODO Inform user about success
3105 case LFUN_BUFFER_UPDATE: {
3106 d.asyncBufferProcessing(argument,
3109 &GuiViewPrivate::compileAndDestroy,
3114 case LFUN_BUFFER_VIEW: {
3115 d.asyncBufferProcessing(argument,
3117 _("Previewing ..."),
3118 &GuiViewPrivate::previewAndDestroy,
3123 case LFUN_MASTER_BUFFER_UPDATE: {
3124 d.asyncBufferProcessing(argument,
3125 (doc_buffer ? doc_buffer->masterBuffer() : 0),
3127 &GuiViewPrivate::compileAndDestroy,
3132 case LFUN_MASTER_BUFFER_VIEW: {
3133 d.asyncBufferProcessing(argument,
3134 (doc_buffer ? doc_buffer->masterBuffer() : 0),
3136 &GuiViewPrivate::previewAndDestroy,
3137 0, &Buffer::preview);
3140 case LFUN_BUFFER_SWITCH: {
3141 string const file_name = to_utf8(cmd.argument());
3142 if (!FileName::isAbsolute(file_name)) {
3144 dr.setMessage(_("Absolute filename expected."));
3148 Buffer * buffer = theBufferList().getBuffer(FileName(file_name));
3151 dr.setMessage(_("Document not loaded"));
3155 // Do we open or switch to the buffer in this view ?
3156 if (workArea(*buffer)
3157 || lyxrc.open_buffers_in_tabs || !documentBufferView()) {
3162 // Look for the buffer in other views
3163 QList<int> const ids = guiApp->viewIds();
3165 for (; i != ids.size(); ++i) {
3166 GuiView & gv = guiApp->view(ids[i]);
3167 if (gv.workArea(*buffer)) {
3168 gv.activateWindow();
3169 gv.setBuffer(buffer);
3174 // If necessary, open a new window as a last resort
3175 if (i == ids.size()) {
3176 lyx::dispatch(FuncRequest(LFUN_WINDOW_NEW));
3182 case LFUN_BUFFER_NEXT:
3183 gotoNextOrPreviousBuffer(NEXTBUFFER);
3186 case LFUN_BUFFER_PREVIOUS:
3187 gotoNextOrPreviousBuffer(PREVBUFFER);
3190 case LFUN_COMMAND_EXECUTE: {
3191 bool const show_it = cmd.argument() != "off";
3192 // FIXME: this is a hack, "minibuffer" should not be
3194 if (GuiToolbar * t = toolbar("minibuffer")) {
3195 t->setVisible(show_it);
3196 if (show_it && t->commandBuffer())
3197 t->commandBuffer()->setFocus();
3201 case LFUN_DROP_LAYOUTS_CHOICE:
3202 d.layout_->showPopup();
3205 case LFUN_MENU_OPEN:
3206 if (QMenu * menu = guiApp->menus().menu(toqstr(cmd.argument()), *this))
3207 menu->exec(QCursor::pos());
3210 case LFUN_FILE_INSERT:
3211 insertLyXFile(cmd.argument());
3214 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
3215 insertPlaintextFile(cmd.argument(), true);
3218 case LFUN_FILE_INSERT_PLAINTEXT:
3219 insertPlaintextFile(cmd.argument(), false);
3222 case LFUN_BUFFER_RELOAD: {
3223 LASSERT(doc_buffer, break);
3226 if (!doc_buffer->isClean()) {
3227 docstring const file =
3228 makeDisplayPath(doc_buffer->absFileName(), 20);
3229 docstring text = bformat(_("Any changes will be lost. "
3230 "Are you sure you want to revert to the saved version "
3231 "of the document %1$s?"), file);
3232 ret = Alert::prompt(_("Revert to saved document?"),
3233 text, 1, 1, _("&Revert"), _("&Cancel"));
3237 doc_buffer->markClean();
3238 reloadBuffer(*doc_buffer);
3239 dr.forceBufferUpdate();
3244 case LFUN_BUFFER_WRITE:
3245 LASSERT(doc_buffer, break);
3246 saveBuffer(*doc_buffer);
3249 case LFUN_BUFFER_WRITE_AS:
3250 LASSERT(doc_buffer, break);
3251 renameBuffer(*doc_buffer, cmd.argument());
3254 case LFUN_BUFFER_WRITE_ALL: {
3255 Buffer * first = theBufferList().first();
3258 message(_("Saving all documents..."));
3259 // We cannot use a for loop as the buffer list cycles.
3262 if (!b->isClean()) {
3264 LYXERR(Debug::ACTION, "Saved " << b->absFileName());
3266 b = theBufferList().next(b);
3267 } while (b != first);
3268 dr.setMessage(_("All documents saved."));
3272 case LFUN_BUFFER_CLOSE:
3276 case LFUN_BUFFER_CLOSE_ALL:
3280 case LFUN_TOOLBAR_TOGGLE: {
3281 string const name = cmd.getArg(0);
3282 if (GuiToolbar * t = toolbar(name))
3287 case LFUN_DIALOG_UPDATE: {
3288 string const name = to_utf8(cmd.argument());
3289 if (name == "prefs" || name == "document")
3290 updateDialog(name, string());
3291 else if (name == "paragraph")
3292 lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
3293 else if (currentBufferView()) {
3294 Inset * inset = currentBufferView()->editedInset(name);
3295 // Can only update a dialog connected to an existing inset
3297 // FIXME: get rid of this indirection; GuiView ask the inset
3298 // if he is kind enough to update itself...
3299 FuncRequest fr(LFUN_INSET_DIALOG_UPDATE, cmd.argument());
3300 //FIXME: pass DispatchResult here?
3301 inset->dispatch(currentBufferView()->cursor(), fr);
3307 case LFUN_DIALOG_TOGGLE: {
3308 if (isDialogVisible(cmd.getArg(0)))
3309 dispatch(FuncRequest(LFUN_DIALOG_HIDE, cmd.argument()), dr);
3311 dispatch(FuncRequest(LFUN_DIALOG_SHOW, cmd.argument()), dr);
3315 case LFUN_DIALOG_DISCONNECT_INSET:
3316 disconnectDialog(to_utf8(cmd.argument()));
3319 case LFUN_DIALOG_HIDE: {
3320 guiApp->hideDialogs(to_utf8(cmd.argument()), 0);
3324 case LFUN_DIALOG_SHOW: {
3325 string const name = cmd.getArg(0);
3326 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
3328 if (name == "character") {
3329 data = freefont2string();
3331 showDialog("character", data);
3332 } else if (name == "latexlog") {
3333 Buffer::LogType type;
3334 string const logfile = doc_buffer->logName(&type);
3336 case Buffer::latexlog:
3339 case Buffer::buildlog:
3343 data += Lexer::quoteString(logfile);
3344 showDialog("log", data);
3345 } else if (name == "vclog") {
3346 string const data = "vc " +
3347 Lexer::quoteString(doc_buffer->lyxvc().getLogFile());
3348 showDialog("log", data);
3349 } else if (name == "symbols") {
3350 data = bv->cursor().getEncoding()->name();
3352 showDialog("symbols", data);
3354 } else if (name == "prefs" && isFullScreen()) {
3355 lfunUiToggle("fullscreen");
3356 showDialog("prefs", data);
3358 showDialog(name, data);
3363 dr.setMessage(cmd.argument());
3366 case LFUN_UI_TOGGLE: {
3367 string arg = cmd.getArg(0);
3368 if (!lfunUiToggle(arg)) {
3369 docstring const msg = "ui-toggle " + _("%1$s unknown command!");
3370 dr.setMessage(bformat(msg, from_utf8(arg)));
3372 // Make sure the keyboard focus stays in the work area.
3377 case LFUN_SPLIT_VIEW: {
3378 LASSERT(doc_buffer, break);
3379 string const orientation = cmd.getArg(0);
3380 d.splitter_->setOrientation(orientation == "vertical"
3381 ? Qt::Vertical : Qt::Horizontal);
3382 TabWorkArea * twa = addTabWorkArea();
3383 GuiWorkArea * wa = twa->addWorkArea(*doc_buffer, *this);
3384 setCurrentWorkArea(wa);
3387 case LFUN_CLOSE_TAB_GROUP:
3388 if (TabWorkArea * twa = d.currentTabWorkArea()) {
3389 closeTabWorkArea(twa);
3390 d.current_work_area_ = 0;
3391 twa = d.currentTabWorkArea();
3392 // Switch to the next GuiWorkArea in the found TabWorkArea.
3394 // Make sure the work area is up to date.
3395 setCurrentWorkArea(twa->currentWorkArea());
3397 setCurrentWorkArea(0);
3402 case LFUN_COMPLETION_INLINE:
3403 if (d.current_work_area_)
3404 d.current_work_area_->completer().showInline();
3407 case LFUN_COMPLETION_POPUP:
3408 if (d.current_work_area_)
3409 d.current_work_area_->completer().showPopup();
3413 case LFUN_COMPLETION_COMPLETE:
3414 if (d.current_work_area_)
3415 d.current_work_area_->completer().tab();
3418 case LFUN_COMPLETION_CANCEL:
3419 if (d.current_work_area_) {
3420 if (d.current_work_area_->completer().popupVisible())
3421 d.current_work_area_->completer().hidePopup();
3423 d.current_work_area_->completer().hideInline();
3427 case LFUN_COMPLETION_ACCEPT:
3428 if (d.current_work_area_)
3429 d.current_work_area_->completer().activate();
3432 case LFUN_BUFFER_ZOOM_IN:
3433 case LFUN_BUFFER_ZOOM_OUT:
3434 if (cmd.argument().empty()) {
3435 if (cmd.action() == LFUN_BUFFER_ZOOM_IN)
3440 lyxrc.zoom += convert<int>(cmd.argument());
3442 if (lyxrc.zoom < 10)
3445 // The global QPixmapCache is used in GuiPainter to cache text
3446 // painting so we must reset it.
3447 QPixmapCache::clear();
3448 guiApp->fontLoader().update();
3449 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
3452 case LFUN_VC_REGISTER:
3453 case LFUN_VC_CHECK_IN:
3454 case LFUN_VC_CHECK_OUT:
3455 case LFUN_VC_REPO_UPDATE:
3456 case LFUN_VC_LOCKING_TOGGLE:
3457 case LFUN_VC_REVERT:
3458 case LFUN_VC_UNDO_LAST:
3459 case LFUN_VC_COMMAND:
3460 case LFUN_VC_COMPARE:
3461 dispatchVC(cmd, dr);
3464 case LFUN_SERVER_GOTO_FILE_ROW:
3465 goToFileRow(to_utf8(cmd.argument()));
3468 case LFUN_FORWARD_SEARCH: {
3469 FileName const path(doc_buffer->temppath());
3470 string const texname = doc_buffer->latexName();
3471 FileName const dviname(addName(path.absFileName(),
3472 support::changeExtension(texname, "dvi")));
3473 FileName const pdfname(addName(path.absFileName(),
3474 support::changeExtension(texname, "pdf")));
3475 if (!dviname.exists() && !pdfname.exists()) {
3476 dr.setMessage(_("Please, preview the document first."));
3479 string outname = dviname.onlyFileName();
3480 string command = lyxrc.forward_search_dvi;
3481 if (!dviname.exists() ||
3482 pdfname.lastModified() > dviname.lastModified()) {
3483 outname = pdfname.onlyFileName();
3484 command = lyxrc.forward_search_pdf;
3487 int row = doc_buffer->texrow().getRowFromIdPos(bv->cursor().paragraph().id(), bv->cursor().pos());
3488 LYXERR(Debug::ACTION, "Forward search: row:" << row
3489 << " id:" << bv->cursor().paragraph().id());
3490 if (!row || command.empty()) {
3491 dr.setMessage(_("Couldn't proceed."));
3494 string texrow = convert<string>(row);
3496 command = subst(command, "$$n", texrow);
3497 command = subst(command, "$$t", texname);
3498 command = subst(command, "$$o", outname);
3500 PathChanger p(path);
3502 one.startscript(Systemcall::DontWait, command);
3506 // The LFUN must be for one of BufferView, Buffer or Cursor;
3508 dispatchToBufferView(cmd, dr);
3512 // Part of automatic menu appearance feature.
3513 if (isFullScreen()) {
3514 if (menuBar()->isVisible() && lyxrc.full_screen_menubar)
3516 if (statusBar()->isVisible())
3517 statusBar()->hide();
3522 bool GuiView::lfunUiToggle(string const & ui_component)
3524 if (ui_component == "scrollbar") {
3525 // hide() is of no help
3526 if (d.current_work_area_->verticalScrollBarPolicy() ==
3527 Qt::ScrollBarAlwaysOff)
3529 d.current_work_area_->setVerticalScrollBarPolicy(
3530 Qt::ScrollBarAsNeeded);
3532 d.current_work_area_->setVerticalScrollBarPolicy(
3533 Qt::ScrollBarAlwaysOff);
3534 } else if (ui_component == "statusbar") {
3535 statusBar()->setVisible(!statusBar()->isVisible());
3536 } else if (ui_component == "menubar") {
3537 menuBar()->setVisible(!menuBar()->isVisible());
3539 #if QT_VERSION >= 0x040300
3540 if (ui_component == "frame") {
3542 getContentsMargins(&l, &t, &r, &b);
3543 //are the frames in default state?
3544 d.current_work_area_->setFrameStyle(QFrame::NoFrame);
3546 setContentsMargins(-2, -2, -2, -2);
3548 setContentsMargins(0, 0, 0, 0);
3552 if (ui_component == "fullscreen") {
3560 void GuiView::toggleFullScreen()
3562 if (isFullScreen()) {
3563 for (int i = 0; i != d.splitter_->count(); ++i)
3564 d.tabWorkArea(i)->setFullScreen(false);
3565 #if QT_VERSION >= 0x040300
3566 setContentsMargins(0, 0, 0, 0);
3568 setWindowState(windowState() ^ Qt::WindowFullScreen);
3571 statusBar()->show();
3574 hideDialogs("prefs", 0);
3575 for (int i = 0; i != d.splitter_->count(); ++i)
3576 d.tabWorkArea(i)->setFullScreen(true);
3577 #if QT_VERSION >= 0x040300
3578 setContentsMargins(-2, -2, -2, -2);
3581 setWindowState(windowState() ^ Qt::WindowFullScreen);
3582 statusBar()->hide();
3583 if (lyxrc.full_screen_menubar)
3585 if (lyxrc.full_screen_toolbars) {
3586 ToolbarMap::iterator end = d.toolbars_.end();
3587 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
3592 // give dialogs like the TOC a chance to adapt
3597 Buffer const * GuiView::updateInset(Inset const * inset)
3602 Buffer const * inset_buffer = &(inset->buffer());
3604 for (int i = 0; i != d.splitter_->count(); ++i) {
3605 GuiWorkArea * wa = d.tabWorkArea(i)->currentWorkArea();
3608 Buffer const * buffer = &(wa->bufferView().buffer());
3609 if (inset_buffer == buffer)
3610 wa->scheduleRedraw();
3612 return inset_buffer;
3616 void GuiView::restartCursor()
3618 /* When we move around, or type, it's nice to be able to see
3619 * the cursor immediately after the keypress.
3621 if (d.current_work_area_)
3622 d.current_work_area_->startBlinkingCursor();
3624 // Take this occasion to update the other GUI elements.
3630 void GuiView::updateCompletion(Cursor & cur, bool start, bool keep)
3632 if (d.current_work_area_)
3633 d.current_work_area_->completer().updateVisibility(cur, start, keep);
3638 // This list should be kept in sync with the list of insets in
3639 // src/insets/Inset.cpp. I.e., if a dialog goes with an inset, the
3640 // dialog should have the same name as the inset.
3641 // Changes should be also recorded in LFUN_DIALOG_SHOW doxygen
3642 // docs in LyXAction.cpp.
3644 char const * const dialognames[] = {
3646 "aboutlyx", "bibitem", "bibtex", "box", "branch", "changes", "character",
3647 "citation", "compare", "comparehistory", "document", "errorlist", "ert",
3648 "external", "file", "findreplace", "findreplaceadv", "float", "graphics",
3649 "href", "include", "index", "index_print", "info", "listings", "label", "line",
3650 "log", "mathdelimiter", "mathmatrix", "mathspace", "nomenclature",
3651 "nomencl_print", "note", "paragraph", "phantom", "prefs", "print", "ref",
3652 "sendto", "space", "spellchecker", "symbols", "tabular", "tabularcreate",
3653 "thesaurus", "texinfo", "toc", "view-source", "vspace", "wrap", "progress"};
3655 char const * const * const end_dialognames =
3656 dialognames + (sizeof(dialognames) / sizeof(char *));
3660 cmpCStr(char const * name) : name_(name) {}
3661 bool operator()(char const * other) {
3662 return strcmp(other, name_) == 0;
3669 bool isValidName(string const & name)
3671 return find_if(dialognames, end_dialognames,
3672 cmpCStr(name.c_str())) != end_dialognames;
3678 void GuiView::resetDialogs()
3680 // Make sure that no LFUN uses any GuiView.
3681 guiApp->setCurrentView(0);
3685 constructToolbars();
3686 guiApp->menus().fillMenuBar(menuBar(), this, false);
3687 d.layout_->updateContents(true);
3688 // Now update controls with current buffer.
3689 guiApp->setCurrentView(this);
3695 Dialog * GuiView::findOrBuild(string const & name, bool hide_it)
3697 if (!isValidName(name))
3700 map<string, DialogPtr>::iterator it = d.dialogs_.find(name);
3702 if (it != d.dialogs_.end()) {
3704 it->second->hideView();
3705 return it->second.get();
3708 Dialog * dialog = build(name);
3709 d.dialogs_[name].reset(dialog);
3710 if (lyxrc.allow_geometry_session)
3711 dialog->restoreSession();
3718 void GuiView::showDialog(string const & name, string const & data,
3721 triggerShowDialog(toqstr(name), toqstr(data), inset);
3725 void GuiView::doShowDialog(QString const & qname, QString const & qdata,
3731 const string name = fromqstr(qname);
3732 const string data = fromqstr(qdata);
3736 Dialog * dialog = findOrBuild(name, false);
3738 bool const visible = dialog->isVisibleView();
3739 dialog->showData(data);
3740 if (inset && currentBufferView())
3741 currentBufferView()->editInset(name, inset);
3742 // We only set the focus to the new dialog if it was not yet
3743 // visible in order not to change the existing previous behaviour
3745 // activateWindow is needed for floating dockviews
3746 dialog->asQWidget()->raise();
3747 dialog->asQWidget()->activateWindow();
3748 dialog->asQWidget()->setFocus();
3752 catch (ExceptionMessage const & ex) {
3760 bool GuiView::isDialogVisible(string const & name) const
3762 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3763 if (it == d.dialogs_.end())
3765 return it->second.get()->isVisibleView() && !it->second.get()->isClosing();
3769 void GuiView::hideDialog(string const & name, Inset * inset)
3771 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3772 if (it == d.dialogs_.end())
3776 if (!currentBufferView())
3778 if (inset != currentBufferView()->editedInset(name))
3782 Dialog * const dialog = it->second.get();
3783 if (dialog->isVisibleView())
3785 if (currentBufferView())
3786 currentBufferView()->editInset(name, 0);
3790 void GuiView::disconnectDialog(string const & name)
3792 if (!isValidName(name))
3794 if (currentBufferView())
3795 currentBufferView()->editInset(name, 0);
3799 void GuiView::hideAll() const
3801 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
3802 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3804 for(; it != end; ++it)
3805 it->second->hideView();
3809 void GuiView::updateDialogs()
3811 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
3812 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3814 for(; it != end; ++it) {
3815 Dialog * dialog = it->second.get();
3817 if (dialog->needBufferOpen() && !documentBufferView())
3818 hideDialog(fromqstr(dialog->name()), 0);
3819 else if (dialog->isVisibleView())
3820 dialog->checkStatus();
3827 Dialog * createDialog(GuiView & lv, string const & name);
3829 // will be replaced by a proper factory...
3830 Dialog * createGuiAbout(GuiView & lv);
3831 Dialog * createGuiBibtex(GuiView & lv);
3832 Dialog * createGuiChanges(GuiView & lv);
3833 Dialog * createGuiCharacter(GuiView & lv);
3834 Dialog * createGuiCitation(GuiView & lv);
3835 Dialog * createGuiCompare(GuiView & lv);
3836 Dialog * createGuiCompareHistory(GuiView & lv);
3837 Dialog * createGuiDelimiter(GuiView & lv);
3838 Dialog * createGuiDocument(GuiView & lv);
3839 Dialog * createGuiErrorList(GuiView & lv);
3840 Dialog * createGuiExternal(GuiView & lv);
3841 Dialog * createGuiGraphics(GuiView & lv);
3842 Dialog * createGuiInclude(GuiView & lv);
3843 Dialog * createGuiIndex(GuiView & lv);
3844 Dialog * createGuiListings(GuiView & lv);
3845 Dialog * createGuiLog(GuiView & lv);
3846 Dialog * createGuiMathMatrix(GuiView & lv);
3847 Dialog * createGuiNote(GuiView & lv);
3848 Dialog * createGuiParagraph(GuiView & lv);
3849 Dialog * createGuiPhantom(GuiView & lv);
3850 Dialog * createGuiPreferences(GuiView & lv);
3851 Dialog * createGuiPrint(GuiView & lv);
3852 Dialog * createGuiPrintindex(GuiView & lv);
3853 Dialog * createGuiRef(GuiView & lv);
3854 Dialog * createGuiSearch(GuiView & lv);
3855 Dialog * createGuiSearchAdv(GuiView & lv);
3856 Dialog * createGuiSendTo(GuiView & lv);
3857 Dialog * createGuiShowFile(GuiView & lv);
3858 Dialog * createGuiSpellchecker(GuiView & lv);
3859 Dialog * createGuiSymbols(GuiView & lv);
3860 Dialog * createGuiTabularCreate(GuiView & lv);
3861 Dialog * createGuiTexInfo(GuiView & lv);
3862 Dialog * createGuiToc(GuiView & lv);
3863 Dialog * createGuiThesaurus(GuiView & lv);
3864 Dialog * createGuiViewSource(GuiView & lv);
3865 Dialog * createGuiWrap(GuiView & lv);
3866 Dialog * createGuiProgressView(GuiView & lv);
3870 Dialog * GuiView::build(string const & name)
3872 LASSERT(isValidName(name), return 0);
3874 Dialog * dialog = createDialog(*this, name);
3878 if (name == "aboutlyx")
3879 return createGuiAbout(*this);
3880 if (name == "bibtex")
3881 return createGuiBibtex(*this);
3882 if (name == "changes")
3883 return createGuiChanges(*this);
3884 if (name == "character")
3885 return createGuiCharacter(*this);
3886 if (name == "citation")
3887 return createGuiCitation(*this);
3888 if (name == "compare")
3889 return createGuiCompare(*this);
3890 if (name == "comparehistory")
3891 return createGuiCompareHistory(*this);
3892 if (name == "document")
3893 return createGuiDocument(*this);
3894 if (name == "errorlist")
3895 return createGuiErrorList(*this);
3896 if (name == "external")
3897 return createGuiExternal(*this);
3899 return createGuiShowFile(*this);
3900 if (name == "findreplace")
3901 return createGuiSearch(*this);
3902 if (name == "findreplaceadv")
3903 return createGuiSearchAdv(*this);
3904 if (name == "graphics")
3905 return createGuiGraphics(*this);
3906 if (name == "include")
3907 return createGuiInclude(*this);
3908 if (name == "index")
3909 return createGuiIndex(*this);
3910 if (name == "index_print")
3911 return createGuiPrintindex(*this);
3912 if (name == "listings")
3913 return createGuiListings(*this);
3915 return createGuiLog(*this);
3916 if (name == "mathdelimiter")
3917 return createGuiDelimiter(*this);
3918 if (name == "mathmatrix")
3919 return createGuiMathMatrix(*this);
3921 return createGuiNote(*this);
3922 if (name == "paragraph")
3923 return createGuiParagraph(*this);
3924 if (name == "phantom")
3925 return createGuiPhantom(*this);
3926 if (name == "prefs")
3927 return createGuiPreferences(*this);
3928 if (name == "print")
3929 return createGuiPrint(*this);
3931 return createGuiRef(*this);
3932 if (name == "sendto")
3933 return createGuiSendTo(*this);
3934 if (name == "spellchecker")
3935 return createGuiSpellchecker(*this);
3936 if (name == "symbols")
3937 return createGuiSymbols(*this);
3938 if (name == "tabularcreate")
3939 return createGuiTabularCreate(*this);
3940 if (name == "texinfo")
3941 return createGuiTexInfo(*this);
3942 if (name == "thesaurus")
3943 return createGuiThesaurus(*this);
3945 return createGuiToc(*this);
3946 if (name == "view-source")
3947 return createGuiViewSource(*this);
3949 return createGuiWrap(*this);
3950 if (name == "progress")
3951 return createGuiProgressView(*this);
3957 } // namespace frontend
3960 #include "moc_GuiView.cpp"