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 (currentMainWorkArea())
749 currentMainWorkArea()->setFocus();
750 else if (currentWorkArea())
751 currentWorkArea()->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 // FIXME we should consider passthru
1687 Inset const & in = currentBufferView()->cursor().inset();
1688 enable = !in.getLayout().isPassThru();
1691 else if (name == "latexlog")
1692 enable = FileName(doc_buffer->logName()).isReadableFile();
1693 else if (name == "spellchecker")
1694 enable = theSpellChecker() && !doc_buffer->isReadonly();
1695 else if (name == "vclog")
1696 enable = doc_buffer->lyxvc().inUse();
1700 case LFUN_DIALOG_UPDATE: {
1701 string const name = cmd.getArg(0);
1703 enable = name == "prefs";
1707 case LFUN_COMMAND_EXECUTE:
1709 case LFUN_MENU_OPEN:
1710 // Nothing to check.
1713 case LFUN_COMPLETION_INLINE:
1714 if (!d.current_work_area_
1715 || !d.current_work_area_->completer().inlinePossible(
1716 currentBufferView()->cursor()))
1720 case LFUN_COMPLETION_POPUP:
1721 if (!d.current_work_area_
1722 || !d.current_work_area_->completer().popupPossible(
1723 currentBufferView()->cursor()))
1727 case LFUN_COMPLETION_COMPLETE:
1728 if (!d.current_work_area_
1729 || !d.current_work_area_->completer().inlinePossible(
1730 currentBufferView()->cursor()))
1734 case LFUN_COMPLETION_ACCEPT:
1735 if (!d.current_work_area_
1736 || (!d.current_work_area_->completer().popupVisible()
1737 && !d.current_work_area_->completer().inlineVisible()
1738 && !d.current_work_area_->completer().completionAvailable()))
1742 case LFUN_COMPLETION_CANCEL:
1743 if (!d.current_work_area_
1744 || (!d.current_work_area_->completer().popupVisible()
1745 && !d.current_work_area_->completer().inlineVisible()))
1749 case LFUN_BUFFER_ZOOM_OUT:
1750 enable = doc_buffer && lyxrc.zoom > 10;
1753 case LFUN_BUFFER_ZOOM_IN:
1754 enable = doc_buffer;
1757 case LFUN_BUFFER_NEXT:
1758 case LFUN_BUFFER_PREVIOUS:
1759 // FIXME: should we check is there is an previous or next buffer?
1761 case LFUN_BUFFER_SWITCH:
1762 // toggle on the current buffer, but do not toggle off
1763 // the other ones (is that a good idea?)
1765 && to_utf8(cmd.argument()) == doc_buffer->absFileName())
1766 flag.setOnOff(true);
1769 case LFUN_VC_REGISTER:
1770 enable = doc_buffer && !doc_buffer->lyxvc().inUse();
1772 case LFUN_VC_CHECK_IN:
1773 enable = doc_buffer && doc_buffer->lyxvc().checkInEnabled();
1775 case LFUN_VC_CHECK_OUT:
1776 enable = doc_buffer && doc_buffer->lyxvc().checkOutEnabled();
1778 case LFUN_VC_LOCKING_TOGGLE:
1779 enable = doc_buffer && !doc_buffer->isReadonly()
1780 && doc_buffer->lyxvc().lockingToggleEnabled();
1781 flag.setOnOff(enable && doc_buffer->lyxvc().locking());
1783 case LFUN_VC_REVERT:
1784 enable = doc_buffer && doc_buffer->lyxvc().inUse() && !doc_buffer->isReadonly();
1786 case LFUN_VC_UNDO_LAST:
1787 enable = doc_buffer && doc_buffer->lyxvc().undoLastEnabled();
1789 case LFUN_VC_REPO_UPDATE:
1790 enable = doc_buffer && doc_buffer->lyxvc().repoUpdateEnabled();
1792 case LFUN_VC_COMMAND: {
1793 if (cmd.argument().empty())
1795 if (!doc_buffer && contains(cmd.getArg(0), 'D'))
1799 case LFUN_VC_COMPARE:
1800 enable = doc_buffer && doc_buffer->lyxvc().prepareFileRevisionEnabled();
1803 case LFUN_SERVER_GOTO_FILE_ROW:
1805 case LFUN_FORWARD_SEARCH:
1806 enable = !(lyxrc.forward_search_dvi.empty() && lyxrc.forward_search_pdf.empty());
1814 flag.setEnabled(false);
1820 static FileName selectTemplateFile()
1822 FileDialog dlg(qt_("Select template file"));
1823 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1824 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
1826 FileDialog::Result result = dlg.open(toqstr(lyxrc.template_path),
1827 QStringList(qt_("LyX Documents (*.lyx)")));
1829 if (result.first == FileDialog::Later)
1831 if (result.second.isEmpty())
1833 return FileName(fromqstr(result.second));
1837 Buffer * GuiView::loadDocument(FileName const & filename, bool tolastfiles)
1841 Buffer * newBuffer = 0;
1843 newBuffer = checkAndLoadLyXFile(filename);
1844 } catch (ExceptionMessage const & e) {
1850 message(_("Document not loaded."));
1855 newBuffer->errors("Parse");
1856 setBuffer(newBuffer);
1859 theSession().lastFiles().add(filename);
1866 void GuiView::openDocument(string const & fname)
1868 string initpath = lyxrc.document_path;
1870 if (documentBufferView()) {
1871 string const trypath = documentBufferView()->buffer().filePath();
1872 // If directory is writeable, use this as default.
1873 if (FileName(trypath).isDirWritable())
1879 if (fname.empty()) {
1880 FileDialog dlg(qt_("Select document to open"), LFUN_FILE_OPEN);
1881 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1882 dlg.setButton2(qt_("Examples|#E#e"),
1883 toqstr(addPath(package().system_support().absFileName(), "examples")));
1885 QStringList filter(qt_("LyX Documents (*.lyx)"));
1886 filter << qt_("LyX-1.3.x Documents (*.lyx13)")
1887 << qt_("LyX-1.4.x Documents (*.lyx14)")
1888 << qt_("LyX-1.5.x Documents (*.lyx15)")
1889 << qt_("LyX-1.6.x Documents (*.lyx16)");
1890 FileDialog::Result result =
1891 dlg.open(toqstr(initpath), filter);
1893 if (result.first == FileDialog::Later)
1896 filename = fromqstr(result.second);
1898 // check selected filename
1899 if (filename.empty()) {
1900 message(_("Canceled."));
1906 // get absolute path of file and add ".lyx" to the filename if
1908 FileName const fullname =
1909 fileSearch(string(), filename, "lyx", support::may_not_exist);
1910 if (!fullname.empty())
1911 filename = fullname.absFileName();
1913 if (!fullname.onlyPath().isDirectory()) {
1914 Alert::warning(_("Invalid filename"),
1915 bformat(_("The directory in the given path\n%1$s\ndoes not exist."),
1916 from_utf8(fullname.absFileName())));
1920 // if the file doesn't exist and isn't already open (bug 6645),
1921 // let the user create one
1922 if (!fullname.exists() && !theBufferList().exists(fullname)) {
1923 // the user specifically chose this name. Believe him.
1924 Buffer * const b = newFile(filename, string(), true);
1930 docstring const disp_fn = makeDisplayPath(filename);
1931 message(bformat(_("Opening document %1$s..."), disp_fn));
1934 Buffer * buf = loadDocument(fullname);
1936 str2 = bformat(_("Document %1$s opened."), disp_fn);
1937 if (buf->lyxvc().inUse())
1938 str2 += " " + from_utf8(buf->lyxvc().versionString()) +
1939 " " + _("Version control detected.");
1941 str2 = bformat(_("Could not open document %1$s"), disp_fn);
1946 // FIXME: clean that
1947 static bool import(GuiView * lv, FileName const & filename,
1948 string const & format, ErrorList & errorList)
1950 FileName const lyxfile(support::changeExtension(filename.absFileName(), ".lyx"));
1952 string loader_format;
1953 vector<string> loaders = theConverters().loaders();
1954 if (find(loaders.begin(), loaders.end(), format) == loaders.end()) {
1955 for (vector<string>::const_iterator it = loaders.begin();
1956 it != loaders.end(); ++it) {
1957 if (!theConverters().isReachable(format, *it))
1960 string const tofile =
1961 support::changeExtension(filename.absFileName(),
1962 formats.extension(*it));
1963 if (!theConverters().convert(0, filename, FileName(tofile),
1964 filename, format, *it, errorList))
1966 loader_format = *it;
1969 if (loader_format.empty()) {
1970 frontend::Alert::error(_("Couldn't import file"),
1971 bformat(_("No information for importing the format %1$s."),
1972 formats.prettyName(format)));
1976 loader_format = format;
1978 if (loader_format == "lyx") {
1979 Buffer * buf = lv->loadDocument(lyxfile);
1983 Buffer * const b = newFile(lyxfile.absFileName(), string(), true);
1987 bool as_paragraphs = loader_format == "textparagraph";
1988 string filename2 = (loader_format == format) ? filename.absFileName()
1989 : support::changeExtension(filename.absFileName(),
1990 formats.extension(loader_format));
1991 lv->currentBufferView()->insertPlaintextFile(FileName(filename2),
1993 guiApp->setCurrentView(lv);
1994 lyx::dispatch(FuncRequest(LFUN_MARK_OFF));
2001 void GuiView::importDocument(string const & argument)
2004 string filename = split(argument, format, ' ');
2006 LYXERR(Debug::INFO, format << " file: " << filename);
2008 // need user interaction
2009 if (filename.empty()) {
2010 string initpath = lyxrc.document_path;
2011 if (documentBufferView()) {
2012 string const trypath = documentBufferView()->buffer().filePath();
2013 // If directory is writeable, use this as default.
2014 if (FileName(trypath).isDirWritable())
2018 docstring const text = bformat(_("Select %1$s file to import"),
2019 formats.prettyName(format));
2021 FileDialog dlg(toqstr(text), LFUN_BUFFER_IMPORT);
2022 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2023 dlg.setButton2(qt_("Examples|#E#e"),
2024 toqstr(addPath(package().system_support().absFileName(), "examples")));
2026 docstring filter = formats.prettyName(format);
2029 filter += from_utf8(formats.extension(format));
2032 FileDialog::Result result =
2033 dlg.open(toqstr(initpath), fileFilters(toqstr(filter)));
2035 if (result.first == FileDialog::Later)
2038 filename = fromqstr(result.second);
2040 // check selected filename
2041 if (filename.empty())
2042 message(_("Canceled."));
2045 if (filename.empty())
2048 // get absolute path of file
2049 FileName const fullname(support::makeAbsPath(filename));
2051 FileName const lyxfile(support::changeExtension(fullname.absFileName(), ".lyx"));
2053 // Check if the document already is open
2054 Buffer * buf = theBufferList().getBuffer(lyxfile);
2057 if (!closeBuffer()) {
2058 message(_("Canceled."));
2063 docstring const displaypath = makeDisplayPath(lyxfile.absFileName(), 30);
2065 // if the file exists already, and we didn't do
2066 // -i lyx thefile.lyx, warn
2067 if (lyxfile.exists() && fullname != lyxfile) {
2069 docstring text = bformat(_("The document %1$s already exists.\n\n"
2070 "Do you want to overwrite that document?"), displaypath);
2071 int const ret = Alert::prompt(_("Overwrite document?"),
2072 text, 0, 1, _("&Overwrite"), _("&Cancel"));
2075 message(_("Canceled."));
2080 message(bformat(_("Importing %1$s..."), displaypath));
2081 ErrorList errorList;
2082 if (import(this, fullname, format, errorList))
2083 message(_("imported."));
2085 message(_("file not imported!"));
2087 // FIXME (Abdel 12/08/06): Is there a need to display the error list here?
2091 void GuiView::newDocument(string const & filename, bool from_template)
2093 FileName initpath(lyxrc.document_path);
2094 if (documentBufferView()) {
2095 FileName const trypath(documentBufferView()->buffer().filePath());
2096 // If directory is writeable, use this as default.
2097 if (trypath.isDirWritable())
2101 string templatefile;
2102 if (from_template) {
2103 templatefile = selectTemplateFile().absFileName();
2104 if (templatefile.empty())
2109 if (filename.empty())
2110 b = newUnnamedFile(initpath, to_utf8(_("newfile")), templatefile);
2112 b = newFile(filename, templatefile, true);
2117 // If no new document could be created, it is unsure
2118 // whether there is a valid BufferView.
2119 if (currentBufferView())
2120 // Ensure the cursor is correctly positioned on screen.
2121 currentBufferView()->showCursor();
2125 void GuiView::insertLyXFile(docstring const & fname)
2127 BufferView * bv = documentBufferView();
2132 FileName filename(to_utf8(fname));
2133 if (filename.empty()) {
2134 // Launch a file browser
2136 string initpath = lyxrc.document_path;
2137 string const trypath = bv->buffer().filePath();
2138 // If directory is writeable, use this as default.
2139 if (FileName(trypath).isDirWritable())
2143 FileDialog dlg(qt_("Select LyX document to insert"), LFUN_FILE_INSERT);
2144 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2145 dlg.setButton2(qt_("Examples|#E#e"),
2146 toqstr(addPath(package().system_support().absFileName(),
2149 FileDialog::Result result = dlg.open(toqstr(initpath),
2150 QStringList(qt_("LyX Documents (*.lyx)")));
2152 if (result.first == FileDialog::Later)
2156 filename.set(fromqstr(result.second));
2158 // check selected filename
2159 if (filename.empty()) {
2160 // emit message signal.
2161 message(_("Canceled."));
2166 bv->insertLyXFile(filename);
2167 bv->buffer().errors("Parse");
2171 void GuiView::insertPlaintextFile(docstring const & fname,
2174 BufferView * bv = documentBufferView();
2178 if (!fname.empty() && !FileName::isAbsolute(to_utf8(fname))) {
2179 message(_("Absolute filename expected."));
2184 FileName filename(to_utf8(fname));
2186 if (!filename.empty()) {
2187 bv->insertPlaintextFile(filename, asParagraph);
2191 FileDialog dlg(qt_("Select file to insert"), (asParagraph ?
2192 LFUN_FILE_INSERT_PLAINTEXT_PARA : LFUN_FILE_INSERT_PLAINTEXT));
2194 FileDialog::Result result = dlg.open(toqstr(bv->buffer().filePath()),
2195 QStringList(qt_("All Files (*)")));
2197 if (result.first == FileDialog::Later)
2201 filename.set(fromqstr(result.second));
2203 // check selected filename
2204 if (filename.empty()) {
2205 // emit message signal.
2206 message(_("Canceled."));
2210 bv->insertPlaintextFile(filename, asParagraph);
2214 bool GuiView::renameBuffer(Buffer & b, docstring const & newname)
2216 FileName fname = b.fileName();
2217 FileName const oldname = fname;
2219 if (!newname.empty()) {
2221 fname = support::makeAbsPath(to_utf8(newname), oldname.onlyPath().absFileName());
2223 // Switch to this Buffer.
2226 // No argument? Ask user through dialog.
2228 FileDialog dlg(qt_("Choose a filename to save document as"),
2229 LFUN_BUFFER_WRITE_AS);
2230 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2231 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
2233 if (!isLyXFileName(fname.absFileName()))
2234 fname.changeExtension(".lyx");
2236 FileDialog::Result result =
2237 dlg.save(toqstr(fname.onlyPath().absFileName()),
2238 QStringList(qt_("LyX Documents (*.lyx)")),
2239 toqstr(fname.onlyFileName()));
2241 if (result.first == FileDialog::Later)
2244 fname.set(fromqstr(result.second));
2249 if (!isLyXFileName(fname.absFileName()))
2250 fname.changeExtension(".lyx");
2253 // fname is now the new Buffer location.
2254 if (FileName(fname).exists()) {
2255 docstring const file = makeDisplayPath(fname.absFileName(), 30);
2256 docstring text = bformat(_("The document %1$s already "
2257 "exists.\n\nDo you want to "
2258 "overwrite that document?"),
2260 int const ret = Alert::prompt(_("Overwrite document?"),
2261 text, 0, 2, _("&Overwrite"), _("&Rename"), _("&Cancel"));
2264 case 1: return renameBuffer(b, docstring());
2265 case 2: return false;
2269 return saveBuffer(b, fname);
2273 bool GuiView::saveBuffer(Buffer & b) {
2274 return saveBuffer(b, FileName());
2278 bool GuiView::saveBuffer(Buffer & b, FileName const & fn)
2280 if (workArea(b) && workArea(b)->inDialogMode())
2283 if (fn.empty() && b.isUnnamed())
2284 return renameBuffer(b, docstring());
2290 success = b.saveAs(fn);
2293 theSession().lastFiles().add(b.fileName());
2297 // Switch to this Buffer.
2300 // FIXME: we don't tell the user *WHY* the save failed !!
2301 docstring const file = makeDisplayPath(b.absFileName(), 30);
2302 docstring text = bformat(_("The document %1$s could not be saved.\n\n"
2303 "Do you want to rename the document and "
2304 "try again?"), file);
2305 int const ret = Alert::prompt(_("Rename and save?"),
2306 text, 0, 2, _("&Rename"), _("&Retry"), _("&Cancel"));
2309 if (!renameBuffer(b, docstring()))
2318 return saveBuffer(b);
2322 bool GuiView::hideWorkArea(GuiWorkArea * wa)
2324 return closeWorkArea(wa, false);
2328 bool GuiView::closeWorkArea(GuiWorkArea * wa)
2330 Buffer & buf = wa->bufferView().buffer();
2331 return closeWorkArea(wa, !buf.parent());
2335 bool GuiView::closeBuffer()
2337 GuiWorkArea * wa = currentMainWorkArea();
2338 setCurrentWorkArea(wa);
2339 Buffer & buf = wa->bufferView().buffer();
2340 return wa && closeWorkArea(wa, !buf.parent());
2344 void GuiView::writeSession() const {
2345 GuiWorkArea const * active_wa = currentMainWorkArea();
2346 for (int i = 0; i < d.splitter_->count(); ++i) {
2347 TabWorkArea * twa = d.tabWorkArea(i);
2348 for (int j = 0; j < twa->count(); ++j) {
2349 GuiWorkArea * wa = static_cast<GuiWorkArea *>(twa->widget(j));
2350 Buffer & buf = wa->bufferView().buffer();
2351 theSession().lastOpened().add(buf.fileName(), wa == active_wa);
2357 bool GuiView::closeBufferAll()
2359 // Close the workareas in all other views
2360 QList<int> const ids = guiApp->viewIds();
2361 for (int i = 0; i != ids.size(); ++i) {
2362 if (id_ != ids[i] && !guiApp->view(ids[i]).closeWorkAreaAll())
2366 // Close our own workareas
2367 if (!closeWorkAreaAll())
2370 // Now close the hidden buffers. We prevent hidden buffers from being
2371 // dirty, so we can just close them.
2372 theBufferList().closeAll();
2377 bool GuiView::closeWorkAreaAll()
2379 setCurrentWorkArea(currentMainWorkArea());
2381 // We might be in a situation that there is still a tabWorkArea, but
2382 // there are no tabs anymore. This can happen when we get here after a
2383 // TabWorkArea::lastWorkAreaRemoved() signal. Therefore we count how
2384 // many TabWorkArea's have no documents anymore.
2387 // We have to call count() each time, because it can happen that
2388 // more than one splitter will disappear in one iteration (bug 5998).
2389 for (; d.splitter_->count() > empty_twa; ) {
2390 TabWorkArea * twa = d.tabWorkArea(empty_twa);
2392 if (twa->count() == 0)
2395 setCurrentWorkArea(twa->currentWorkArea());
2396 if (!closeTabWorkArea(twa))
2404 bool GuiView::closeWorkArea(GuiWorkArea * wa, bool close_buffer)
2409 Buffer & buf = wa->bufferView().buffer();
2411 if (close_buffer && GuiViewPrivate::busyBuffers.contains(&buf)) {
2412 Alert::warning(_("Close document"),
2413 _("Document could not be closed because it is being processed by LyX."));
2418 return closeBuffer(buf);
2420 if (!inMultiTabs(wa))
2421 if (!saveBufferIfNeeded(buf, true))
2429 bool GuiView::closeBuffer(Buffer & buf)
2431 // If we are in a close_event all children will be closed in some time,
2432 // so no need to do it here. This will ensure that the children end up
2433 // in the session file in the correct order. If we close the master
2434 // buffer, we can close or release the child buffers here too.
2435 bool success = true;
2437 ListOfBuffers clist = buf.getChildren();
2438 ListOfBuffers::const_iterator it = clist.begin();
2439 ListOfBuffers::const_iterator const bend = clist.end();
2440 for (; it != bend; ++it) {
2441 // If a child is dirty, do not close
2442 // without user intervention
2443 //FIXME: should we look in other tabworkareas?
2444 Buffer * child_buf = *it;
2445 GuiWorkArea * child_wa = workArea(*child_buf);
2447 if (!closeWorkArea(child_wa, true)) {
2452 theBufferList().releaseChild(&buf, child_buf);
2456 // goto bookmark to update bookmark pit.
2457 //FIXME: we should update only the bookmarks related to this buffer!
2458 LYXERR(Debug::DEBUG, "GuiView::closeBuffer()");
2459 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
2460 guiApp->gotoBookmark(i+1, false, false);
2462 if (saveBufferIfNeeded(buf, false)) {
2463 buf.removeAutosaveFile();
2464 theBufferList().release(&buf);
2468 // open all children again to avoid a crash because of dangling
2469 // pointers (bug 6603)
2475 bool GuiView::closeTabWorkArea(TabWorkArea * twa)
2477 while (twa == d.currentTabWorkArea()) {
2478 twa->setCurrentIndex(twa->count()-1);
2480 GuiWorkArea * wa = twa->currentWorkArea();
2481 Buffer & b = wa->bufferView().buffer();
2483 // We only want to close the buffer if the same buffer is not visible
2484 // in another view, and if this is not a child and if we are closing
2485 // a view (not a tabgroup).
2486 bool const close_buffer =
2487 !inOtherView(b) && !b.parent() && closing_;
2489 if (!closeWorkArea(wa, close_buffer))
2496 bool GuiView::saveBufferIfNeeded(Buffer & buf, bool hiding)
2498 if (buf.isClean() || buf.paragraphs().empty())
2501 // Switch to this Buffer.
2506 if (buf.isUnnamed())
2507 file = from_utf8(buf.fileName().onlyFileName());
2509 file = buf.fileName().displayName(30);
2511 // Bring this window to top before asking questions.
2516 if (hiding && buf.isUnnamed()) {
2517 docstring const text = bformat(_("The document %1$s has not been "
2518 "saved yet.\n\nDo you want to save "
2519 "the document?"), file);
2520 ret = Alert::prompt(_("Save new document?"),
2521 text, 0, 1, _("&Save"), _("&Cancel"));
2525 docstring const text = bformat(_("The document %1$s has unsaved changes."
2526 "\n\nDo you want to save the document or discard the changes?"), file);
2527 ret = Alert::prompt(_("Save changed document?"),
2528 text, 0, 2, _("&Save"), _("&Discard"), _("&Cancel"));
2533 if (!saveBuffer(buf))
2537 // If we crash after this we could have no autosave file
2538 // but I guess this is really improbable (Jug).
2539 // Sometimes improbable things happen:
2540 // - see bug http://www.lyx.org/trac/ticket/6587 (ps)
2541 // buf.removeAutosaveFile();
2543 // revert all changes
2554 bool GuiView::inMultiTabs(GuiWorkArea * wa)
2556 Buffer & buf = wa->bufferView().buffer();
2558 for (int i = 0; i != d.splitter_->count(); ++i) {
2559 GuiWorkArea * wa_ = d.tabWorkArea(i)->workArea(buf);
2560 if (wa_ && wa_ != wa)
2563 return inOtherView(buf);
2567 bool GuiView::inOtherView(Buffer & buf)
2569 QList<int> const ids = guiApp->viewIds();
2571 for (int i = 0; i != ids.size(); ++i) {
2575 if (guiApp->view(ids[i]).workArea(buf))
2582 void GuiView::gotoNextOrPreviousBuffer(NextOrPrevious np)
2584 if (!documentBufferView())
2587 if (TabWorkArea * twa = d.currentTabWorkArea()) {
2588 Buffer * const curbuf = &documentBufferView()->buffer();
2589 int nwa = twa->count();
2590 for (int i = 0; i < nwa; ++i) {
2591 if (&workArea(i)->bufferView().buffer() == curbuf) {
2593 if (np == NEXTBUFFER)
2594 next_index = (i == nwa - 1 ? 0 : i + 1);
2596 next_index = (i == 0 ? nwa - 1 : i - 1);
2597 setBuffer(&workArea(next_index)->bufferView().buffer());
2605 /// make sure the document is saved
2606 static bool ensureBufferClean(Buffer * buffer)
2608 LASSERT(buffer, return false);
2609 if (buffer->isClean() && !buffer->isUnnamed())
2612 docstring const file = buffer->fileName().displayName(30);
2615 if (!buffer->isUnnamed()) {
2616 text = bformat(_("The document %1$s has unsaved "
2617 "changes.\n\nDo you want to save "
2618 "the document?"), file);
2619 title = _("Save changed document?");
2622 text = bformat(_("The document %1$s has not been "
2623 "saved yet.\n\nDo you want to save "
2624 "the document?"), file);
2625 title = _("Save new document?");
2627 int const ret = Alert::prompt(title, text, 0, 1, _("&Save"), _("&Cancel"));
2630 dispatch(FuncRequest(LFUN_BUFFER_WRITE));
2632 return buffer->isClean() && !buffer->isUnnamed();
2636 bool GuiView::reloadBuffer(Buffer & buf)
2638 Buffer::ReadStatus status = buf.reload();
2639 return status == Buffer::ReadSuccess;
2643 void GuiView::checkExternallyModifiedBuffers()
2645 BufferList::iterator bit = theBufferList().begin();
2646 BufferList::iterator const bend = theBufferList().end();
2647 for (; bit != bend; ++bit) {
2648 Buffer * buf = *bit;
2649 if (buf->fileName().exists()
2650 && buf->isExternallyModified(Buffer::checksum_method)) {
2651 docstring text = bformat(_("Document \n%1$s\n has been externally modified."
2652 " Reload now? Any local changes will be lost."),
2653 from_utf8(buf->absFileName()));
2654 int const ret = Alert::prompt(_("Reload externally changed document?"),
2655 text, 0, 1, _("&Reload"), _("&Cancel"));
2663 void GuiView::dispatchVC(FuncRequest const & cmd, DispatchResult & dr)
2665 Buffer * buffer = documentBufferView()
2666 ? &(documentBufferView()->buffer()) : 0;
2668 switch (cmd.action()) {
2669 case LFUN_VC_REGISTER:
2670 if (!buffer || !ensureBufferClean(buffer))
2672 if (!buffer->lyxvc().inUse()) {
2673 if (buffer->lyxvc().registrer()) {
2674 reloadBuffer(*buffer);
2675 dr.suppressMessageUpdate();
2680 case LFUN_VC_CHECK_IN:
2681 if (!buffer || !ensureBufferClean(buffer))
2683 if (buffer->lyxvc().inUse() && !buffer->isReadonly()) {
2684 dr.setMessage(buffer->lyxvc().checkIn());
2685 if (!dr.message().empty())
2686 reloadBuffer(*buffer);
2690 case LFUN_VC_CHECK_OUT:
2691 if (!buffer || !ensureBufferClean(buffer))
2693 if (buffer->lyxvc().inUse()) {
2694 dr.setMessage(buffer->lyxvc().checkOut());
2695 reloadBuffer(*buffer);
2699 case LFUN_VC_LOCKING_TOGGLE:
2700 LASSERT(buffer, return);
2701 if (!ensureBufferClean(buffer) || buffer->isReadonly())
2703 if (buffer->lyxvc().inUse()) {
2704 string res = buffer->lyxvc().lockingToggle();
2706 frontend::Alert::error(_("Revision control error."),
2707 _("Error when setting the locking property."));
2710 reloadBuffer(*buffer);
2715 case LFUN_VC_REVERT:
2716 LASSERT(buffer, return);
2717 if (buffer->lyxvc().revert()) {
2718 reloadBuffer(*buffer);
2719 dr.suppressMessageUpdate();
2723 case LFUN_VC_UNDO_LAST:
2724 LASSERT(buffer, return);
2725 buffer->lyxvc().undoLast();
2726 reloadBuffer(*buffer);
2727 dr.suppressMessageUpdate();
2730 case LFUN_VC_REPO_UPDATE:
2731 LASSERT(buffer, return);
2732 if (ensureBufferClean(buffer)) {
2733 dr.setMessage(buffer->lyxvc().repoUpdate());
2734 checkExternallyModifiedBuffers();
2738 case LFUN_VC_COMMAND: {
2739 string flag = cmd.getArg(0);
2740 if (buffer && contains(flag, 'R') && !ensureBufferClean(buffer))
2743 if (contains(flag, 'M')) {
2744 if (!Alert::askForText(message, _("LyX VC: Log Message")))
2747 string path = cmd.getArg(1);
2748 if (contains(path, "$$p") && buffer)
2749 path = subst(path, "$$p", buffer->filePath());
2750 LYXERR(Debug::LYXVC, "Directory: " << path);
2752 if (!pp.isReadableDirectory()) {
2753 lyxerr << _("Directory is not accessible.") << endl;
2756 support::PathChanger p(pp);
2758 string command = cmd.getArg(2);
2759 if (command.empty())
2762 command = subst(command, "$$i", buffer->absFileName());
2763 command = subst(command, "$$p", buffer->filePath());
2765 command = subst(command, "$$m", to_utf8(message));
2766 LYXERR(Debug::LYXVC, "Command: " << command);
2768 one.startscript(Systemcall::Wait, command);
2772 if (contains(flag, 'I'))
2773 buffer->markDirty();
2774 if (contains(flag, 'R'))
2775 reloadBuffer(*buffer);
2780 case LFUN_VC_COMPARE: {
2782 if (cmd.argument().empty()) {
2783 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "comparehistory"));
2787 string rev1 = cmd.getArg(0);
2791 if (!buffer->lyxvc().prepareFileRevision(rev1, f1))
2794 if (isStrInt(rev1) && convert<int>(rev1) <= 0) {
2795 f2 = buffer->absFileName();
2797 string rev2 = cmd.getArg(1);
2801 if (!buffer->lyxvc().prepareFileRevision(rev2, f2))
2805 LYXERR(Debug::LYXVC, "Launching comparison for fetched revisions:\n" <<
2806 f1 << "\n" << f2 << "\n" );
2807 string par = "compare run " + quoteName(f1) + " " + quoteName(f2);
2808 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, par));
2818 void GuiView::openChildDocument(string const & fname)
2820 LASSERT(documentBufferView(), return);
2821 Buffer & buffer = documentBufferView()->buffer();
2822 FileName const filename = support::makeAbsPath(fname, buffer.filePath());
2823 documentBufferView()->saveBookmark(false);
2825 if (theBufferList().exists(filename)) {
2826 child = theBufferList().getBuffer(filename);
2829 message(bformat(_("Opening child document %1$s..."),
2830 makeDisplayPath(filename.absFileName())));
2831 child = loadDocument(filename, false);
2833 // Set the parent name of the child document.
2834 // This makes insertion of citations and references in the child work,
2835 // when the target is in the parent or another child document.
2837 child->setParent(&buffer);
2841 bool GuiView::goToFileRow(string const & argument)
2845 size_t i = argument.find_last_of(' ');
2846 if (i != string::npos) {
2847 file_name = os::internal_path(trim(argument.substr(0, i)));
2848 istringstream is(argument.substr(i + 1));
2853 if (i == string::npos) {
2854 LYXERR0("Wrong argument: " << argument);
2858 string const abstmp = package().temp_dir().absFileName();
2859 string const realtmp = package().temp_dir().realPath();
2860 // We have to use os::path_prefix_is() here, instead of
2861 // simply prefixIs(), because the file name comes from
2862 // an external application and may need case adjustment.
2863 if (os::path_prefix_is(file_name, abstmp, os::CASE_ADJUSTED)
2864 || os::path_prefix_is(file_name, realtmp, os::CASE_ADJUSTED)) {
2865 // Needed by inverse dvi search. If it is a file
2866 // in tmpdir, call the apropriated function.
2867 // If tmpdir is a symlink, we may have the real
2868 // path passed back, so we correct for that.
2869 if (!prefixIs(file_name, abstmp))
2870 file_name = subst(file_name, realtmp, abstmp);
2871 buf = theBufferList().getBufferFromTmp(file_name);
2873 // Must replace extension of the file to be .lyx
2874 // and get full path
2875 FileName const s = fileSearch(string(),
2876 support::changeExtension(file_name, ".lyx"), "lyx");
2877 // Either change buffer or load the file
2878 if (theBufferList().exists(s))
2879 buf = theBufferList().getBuffer(s);
2880 else if (s.exists()) {
2881 buf = loadDocument(s);
2886 _("File does not exist: %1$s"),
2887 makeDisplayPath(file_name)));
2892 documentBufferView()->setCursorFromRow(row);
2897 #if (QT_VERSION >= 0x040400)
2899 docstring GuiView::GuiViewPrivate::runAndDestroy(const T& func, Buffer const * orig, Buffer * buffer, string const & format, string const & msg)
2901 bool const update_unincluded =
2902 buffer->params().maintain_unincluded_children
2903 && !buffer->params().getIncludedChildren().empty();
2904 bool const success = func(format, update_unincluded);
2906 busyBuffers.remove(orig);
2907 if (msg == "preview") {
2909 ? bformat(_("Successful preview of format: %1$s"), from_utf8(format))
2910 : bformat(_("Error while previewing format: %1$s"), from_utf8(format));
2913 ? bformat(_("Successful export to format: %1$s"), from_utf8(format))
2914 : bformat(_("Error while exporting format: %1$s"), from_utf8(format));
2918 docstring GuiView::GuiViewPrivate::compileAndDestroy(Buffer const * orig, Buffer * buffer, string const & format)
2920 bool (Buffer::* mem_func)(std::string const &, bool, bool) const = &Buffer::doExport;
2921 return runAndDestroy(bind(mem_func, buffer, _1, true, _2), orig, buffer, format, "export");
2925 docstring GuiView::GuiViewPrivate::exportAndDestroy(Buffer const * orig, Buffer * buffer, string const & format)
2927 bool (Buffer::* mem_func)(std::string const &, bool, bool) const = &Buffer::doExport;
2928 return runAndDestroy(bind(mem_func, buffer, _1, false, _2), orig, buffer, format, "export");
2932 docstring GuiView::GuiViewPrivate::previewAndDestroy(Buffer const * orig, Buffer * buffer, string const & format)
2934 bool(Buffer::* mem_func)(std::string const &, bool) const = &Buffer::preview;
2935 return runAndDestroy(bind(mem_func, buffer, _1, _2), orig, buffer, format, "preview");
2940 // not used, but the linker needs them
2942 docstring GuiView::GuiViewPrivate::compileAndDestroy(
2943 Buffer const *, Buffer *, string const &)
2949 docstring GuiView::GuiViewPrivate::exportAndDestroy(
2950 Buffer const *, Buffer *, string const &)
2956 docstring GuiView::GuiViewPrivate::previewAndDestroy(
2957 Buffer const *, Buffer *, string const &)
2965 bool GuiView::GuiViewPrivate::asyncBufferProcessing(
2966 string const & argument,
2967 Buffer const * used_buffer,
2968 docstring const & msg,
2969 docstring (*asyncFunc)(Buffer const *, Buffer *, string const &),
2970 bool (Buffer::*syncFunc)(string const &, bool, bool) const,
2971 bool (Buffer::*previewFunc)(string const &, bool) const)
2976 string format = argument;
2978 format = used_buffer->getDefaultOutputFormat();
2980 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
2982 progress_->clearMessages();
2985 GuiViewPrivate::busyBuffers.insert(used_buffer);
2986 QFuture<docstring> f = QtConcurrent::run(
2989 used_buffer->clone(),
2991 setPreviewFuture(f);
2992 last_export_format = used_buffer->bufferFormat();
2995 // We are asynchronous, so we don't know here anything about the success
2999 // TODO check here if it breaks exporting with Qt < 4.4
3000 bool const update_unincluded =
3001 used_buffer->params().maintain_unincluded_children &&
3002 !used_buffer->params().getIncludedChildren().empty();
3003 return (used_buffer->*syncFunc)(format, true, update_unincluded);
3004 } else if (previewFunc) {
3005 return (used_buffer->*previewFunc)(format, false);
3012 void GuiView::dispatchToBufferView(FuncRequest const & cmd, DispatchResult & dr)
3014 BufferView * bv = currentBufferView();
3017 // Let the current BufferView dispatch its own actions.
3018 bv->dispatch(cmd, dr);
3019 if (dr.dispatched())
3022 // Try with the document BufferView dispatch if any.
3023 BufferView * doc_bv = documentBufferView();
3025 doc_bv->dispatch(cmd, dr);
3026 if (dr.dispatched())
3030 // Then let the current Cursor dispatch its own actions.
3031 bv->cursor().dispatch(cmd);
3033 // update completion. We do it here and not in
3034 // processKeySym to avoid another redraw just for a
3035 // changed inline completion
3036 if (cmd.origin() == FuncRequest::KEYBOARD) {
3037 if (cmd.action() == LFUN_SELF_INSERT
3038 || (cmd.action() == LFUN_ERT_INSERT && bv->cursor().inMathed()))
3039 updateCompletion(bv->cursor(), true, true);
3040 else if (cmd.action() == LFUN_CHAR_DELETE_BACKWARD)
3041 updateCompletion(bv->cursor(), false, true);
3043 updateCompletion(bv->cursor(), false, false);
3046 dr = bv->cursor().result();
3050 void GuiView::dispatch(FuncRequest const & cmd, DispatchResult & dr)
3052 BufferView * bv = currentBufferView();
3053 // By default we won't need any update.
3054 dr.screenUpdate(Update::None);
3055 // assume cmd will be dispatched
3056 dr.dispatched(true);
3058 Buffer * doc_buffer = documentBufferView()
3059 ? &(documentBufferView()->buffer()) : 0;
3061 if (cmd.origin() == FuncRequest::TOC) {
3062 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
3063 // FIXME: do we need to pass a DispatchResult object here?
3064 toc->doDispatch(bv->cursor(), cmd);
3068 string const argument = to_utf8(cmd.argument());
3070 switch(cmd.action()) {
3071 case LFUN_BUFFER_CHILD_OPEN:
3072 openChildDocument(to_utf8(cmd.argument()));
3075 case LFUN_BUFFER_IMPORT:
3076 importDocument(to_utf8(cmd.argument()));
3079 case LFUN_BUFFER_EXPORT: {
3082 // GCC only sees strfwd.h when building merged
3083 if (::lyx::operator==(cmd.argument(), "custom")) {
3084 dispatch(FuncRequest(LFUN_DIALOG_SHOW, "sendto"), dr);
3087 #if QT_VERSION < 0x040400
3088 if (!doc_buffer->doExport(argument, false)) {
3090 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
3094 /* TODO/Review: Is it a problem to also export the children?
3095 See the update_unincluded flag */
3096 d.asyncBufferProcessing(argument,
3099 &GuiViewPrivate::exportAndDestroy,
3102 // TODO Inform user about success
3107 case LFUN_BUFFER_UPDATE: {
3108 d.asyncBufferProcessing(argument,
3111 &GuiViewPrivate::compileAndDestroy,
3116 case LFUN_BUFFER_VIEW: {
3117 d.asyncBufferProcessing(argument,
3119 _("Previewing ..."),
3120 &GuiViewPrivate::previewAndDestroy,
3125 case LFUN_MASTER_BUFFER_UPDATE: {
3126 d.asyncBufferProcessing(argument,
3127 (doc_buffer ? doc_buffer->masterBuffer() : 0),
3129 &GuiViewPrivate::compileAndDestroy,
3134 case LFUN_MASTER_BUFFER_VIEW: {
3135 d.asyncBufferProcessing(argument,
3136 (doc_buffer ? doc_buffer->masterBuffer() : 0),
3138 &GuiViewPrivate::previewAndDestroy,
3139 0, &Buffer::preview);
3142 case LFUN_BUFFER_SWITCH: {
3143 string const file_name = to_utf8(cmd.argument());
3144 if (!FileName::isAbsolute(file_name)) {
3146 dr.setMessage(_("Absolute filename expected."));
3150 Buffer * buffer = theBufferList().getBuffer(FileName(file_name));
3153 dr.setMessage(_("Document not loaded"));
3157 // Do we open or switch to the buffer in this view ?
3158 if (workArea(*buffer)
3159 || lyxrc.open_buffers_in_tabs || !documentBufferView()) {
3164 // Look for the buffer in other views
3165 QList<int> const ids = guiApp->viewIds();
3167 for (; i != ids.size(); ++i) {
3168 GuiView & gv = guiApp->view(ids[i]);
3169 if (gv.workArea(*buffer)) {
3170 gv.activateWindow();
3171 gv.setBuffer(buffer);
3176 // If necessary, open a new window as a last resort
3177 if (i == ids.size()) {
3178 lyx::dispatch(FuncRequest(LFUN_WINDOW_NEW));
3184 case LFUN_BUFFER_NEXT:
3185 gotoNextOrPreviousBuffer(NEXTBUFFER);
3188 case LFUN_BUFFER_PREVIOUS:
3189 gotoNextOrPreviousBuffer(PREVBUFFER);
3192 case LFUN_COMMAND_EXECUTE: {
3193 bool const show_it = cmd.argument() != "off";
3194 // FIXME: this is a hack, "minibuffer" should not be
3196 if (GuiToolbar * t = toolbar("minibuffer")) {
3197 t->setVisible(show_it);
3198 if (show_it && t->commandBuffer())
3199 t->commandBuffer()->setFocus();
3203 case LFUN_DROP_LAYOUTS_CHOICE:
3204 d.layout_->showPopup();
3207 case LFUN_MENU_OPEN:
3208 if (QMenu * menu = guiApp->menus().menu(toqstr(cmd.argument()), *this))
3209 menu->exec(QCursor::pos());
3212 case LFUN_FILE_INSERT:
3213 insertLyXFile(cmd.argument());
3216 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
3217 insertPlaintextFile(cmd.argument(), true);
3220 case LFUN_FILE_INSERT_PLAINTEXT:
3221 insertPlaintextFile(cmd.argument(), false);
3224 case LFUN_BUFFER_RELOAD: {
3225 LASSERT(doc_buffer, break);
3228 if (!doc_buffer->isClean()) {
3229 docstring const file =
3230 makeDisplayPath(doc_buffer->absFileName(), 20);
3231 docstring text = bformat(_("Any changes will be lost. "
3232 "Are you sure you want to revert to the saved version "
3233 "of the document %1$s?"), file);
3234 ret = Alert::prompt(_("Revert to saved document?"),
3235 text, 1, 1, _("&Revert"), _("&Cancel"));
3239 doc_buffer->markClean();
3240 reloadBuffer(*doc_buffer);
3241 dr.forceBufferUpdate();
3246 case LFUN_BUFFER_WRITE:
3247 LASSERT(doc_buffer, break);
3248 saveBuffer(*doc_buffer);
3251 case LFUN_BUFFER_WRITE_AS:
3252 LASSERT(doc_buffer, break);
3253 renameBuffer(*doc_buffer, cmd.argument());
3256 case LFUN_BUFFER_WRITE_ALL: {
3257 Buffer * first = theBufferList().first();
3260 message(_("Saving all documents..."));
3261 // We cannot use a for loop as the buffer list cycles.
3264 if (!b->isClean()) {
3266 LYXERR(Debug::ACTION, "Saved " << b->absFileName());
3268 b = theBufferList().next(b);
3269 } while (b != first);
3270 dr.setMessage(_("All documents saved."));
3274 case LFUN_BUFFER_CLOSE:
3278 case LFUN_BUFFER_CLOSE_ALL:
3282 case LFUN_TOOLBAR_TOGGLE: {
3283 string const name = cmd.getArg(0);
3284 if (GuiToolbar * t = toolbar(name))
3289 case LFUN_DIALOG_UPDATE: {
3290 string const name = to_utf8(cmd.argument());
3291 if (name == "prefs" || name == "document")
3292 updateDialog(name, string());
3293 else if (name == "paragraph")
3294 lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
3295 else if (currentBufferView()) {
3296 Inset * inset = currentBufferView()->editedInset(name);
3297 // Can only update a dialog connected to an existing inset
3299 // FIXME: get rid of this indirection; GuiView ask the inset
3300 // if he is kind enough to update itself...
3301 FuncRequest fr(LFUN_INSET_DIALOG_UPDATE, cmd.argument());
3302 //FIXME: pass DispatchResult here?
3303 inset->dispatch(currentBufferView()->cursor(), fr);
3309 case LFUN_DIALOG_TOGGLE: {
3310 if (isDialogVisible(cmd.getArg(0)))
3311 dispatch(FuncRequest(LFUN_DIALOG_HIDE, cmd.argument()), dr);
3313 dispatch(FuncRequest(LFUN_DIALOG_SHOW, cmd.argument()), dr);
3317 case LFUN_DIALOG_DISCONNECT_INSET:
3318 disconnectDialog(to_utf8(cmd.argument()));
3321 case LFUN_DIALOG_HIDE: {
3322 guiApp->hideDialogs(to_utf8(cmd.argument()), 0);
3326 case LFUN_DIALOG_SHOW: {
3327 string const name = cmd.getArg(0);
3328 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
3330 if (name == "character") {
3331 data = freefont2string();
3333 showDialog("character", data);
3334 } else if (name == "latexlog") {
3335 Buffer::LogType type;
3336 string const logfile = doc_buffer->logName(&type);
3338 case Buffer::latexlog:
3341 case Buffer::buildlog:
3345 data += Lexer::quoteString(logfile);
3346 showDialog("log", data);
3347 } else if (name == "vclog") {
3348 string const data = "vc " +
3349 Lexer::quoteString(doc_buffer->lyxvc().getLogFile());
3350 showDialog("log", data);
3351 } else if (name == "symbols") {
3352 data = bv->cursor().getEncoding()->name();
3354 showDialog("symbols", data);
3356 } else if (name == "prefs" && isFullScreen()) {
3357 lfunUiToggle("fullscreen");
3358 showDialog("prefs", data);
3360 showDialog(name, data);
3365 dr.setMessage(cmd.argument());
3368 case LFUN_UI_TOGGLE: {
3369 string arg = cmd.getArg(0);
3370 if (!lfunUiToggle(arg)) {
3371 docstring const msg = "ui-toggle " + _("%1$s unknown command!");
3372 dr.setMessage(bformat(msg, from_utf8(arg)));
3374 // Make sure the keyboard focus stays in the work area.
3379 case LFUN_SPLIT_VIEW: {
3380 LASSERT(doc_buffer, break);
3381 string const orientation = cmd.getArg(0);
3382 d.splitter_->setOrientation(orientation == "vertical"
3383 ? Qt::Vertical : Qt::Horizontal);
3384 TabWorkArea * twa = addTabWorkArea();
3385 GuiWorkArea * wa = twa->addWorkArea(*doc_buffer, *this);
3386 setCurrentWorkArea(wa);
3389 case LFUN_CLOSE_TAB_GROUP:
3390 if (TabWorkArea * twa = d.currentTabWorkArea()) {
3391 closeTabWorkArea(twa);
3392 d.current_work_area_ = 0;
3393 twa = d.currentTabWorkArea();
3394 // Switch to the next GuiWorkArea in the found TabWorkArea.
3396 // Make sure the work area is up to date.
3397 setCurrentWorkArea(twa->currentWorkArea());
3399 setCurrentWorkArea(0);
3404 case LFUN_COMPLETION_INLINE:
3405 if (d.current_work_area_)
3406 d.current_work_area_->completer().showInline();
3409 case LFUN_COMPLETION_POPUP:
3410 if (d.current_work_area_)
3411 d.current_work_area_->completer().showPopup();
3415 case LFUN_COMPLETION_COMPLETE:
3416 if (d.current_work_area_)
3417 d.current_work_area_->completer().tab();
3420 case LFUN_COMPLETION_CANCEL:
3421 if (d.current_work_area_) {
3422 if (d.current_work_area_->completer().popupVisible())
3423 d.current_work_area_->completer().hidePopup();
3425 d.current_work_area_->completer().hideInline();
3429 case LFUN_COMPLETION_ACCEPT:
3430 if (d.current_work_area_)
3431 d.current_work_area_->completer().activate();
3434 case LFUN_BUFFER_ZOOM_IN:
3435 case LFUN_BUFFER_ZOOM_OUT:
3436 if (cmd.argument().empty()) {
3437 if (cmd.action() == LFUN_BUFFER_ZOOM_IN)
3442 lyxrc.zoom += convert<int>(cmd.argument());
3444 if (lyxrc.zoom < 10)
3447 // The global QPixmapCache is used in GuiPainter to cache text
3448 // painting so we must reset it.
3449 QPixmapCache::clear();
3450 guiApp->fontLoader().update();
3451 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
3454 case LFUN_VC_REGISTER:
3455 case LFUN_VC_CHECK_IN:
3456 case LFUN_VC_CHECK_OUT:
3457 case LFUN_VC_REPO_UPDATE:
3458 case LFUN_VC_LOCKING_TOGGLE:
3459 case LFUN_VC_REVERT:
3460 case LFUN_VC_UNDO_LAST:
3461 case LFUN_VC_COMMAND:
3462 case LFUN_VC_COMPARE:
3463 dispatchVC(cmd, dr);
3466 case LFUN_SERVER_GOTO_FILE_ROW:
3467 goToFileRow(to_utf8(cmd.argument()));
3470 case LFUN_FORWARD_SEARCH: {
3471 FileName const path(doc_buffer->temppath());
3472 string const texname = doc_buffer->latexName();
3473 FileName const dviname(addName(path.absFileName(),
3474 support::changeExtension(texname, "dvi")));
3475 FileName const pdfname(addName(path.absFileName(),
3476 support::changeExtension(texname, "pdf")));
3477 if (!dviname.exists() && !pdfname.exists()) {
3478 dr.setMessage(_("Please, preview the document first."));
3481 string outname = dviname.onlyFileName();
3482 string command = lyxrc.forward_search_dvi;
3483 if (!dviname.exists() ||
3484 pdfname.lastModified() > dviname.lastModified()) {
3485 outname = pdfname.onlyFileName();
3486 command = lyxrc.forward_search_pdf;
3489 int row = doc_buffer->texrow().getRowFromIdPos(bv->cursor().paragraph().id(), bv->cursor().pos());
3490 LYXERR(Debug::ACTION, "Forward search: row:" << row
3491 << " id:" << bv->cursor().paragraph().id());
3492 if (!row || command.empty()) {
3493 dr.setMessage(_("Couldn't proceed."));
3496 string texrow = convert<string>(row);
3498 command = subst(command, "$$n", texrow);
3499 command = subst(command, "$$t", texname);
3500 command = subst(command, "$$o", outname);
3502 PathChanger p(path);
3504 one.startscript(Systemcall::DontWait, command);
3508 // The LFUN must be for one of BufferView, Buffer or Cursor;
3510 dispatchToBufferView(cmd, dr);
3514 // Part of automatic menu appearance feature.
3515 if (isFullScreen()) {
3516 if (menuBar()->isVisible() && lyxrc.full_screen_menubar)
3518 if (statusBar()->isVisible())
3519 statusBar()->hide();
3524 bool GuiView::lfunUiToggle(string const & ui_component)
3526 if (ui_component == "scrollbar") {
3527 // hide() is of no help
3528 if (d.current_work_area_->verticalScrollBarPolicy() ==
3529 Qt::ScrollBarAlwaysOff)
3531 d.current_work_area_->setVerticalScrollBarPolicy(
3532 Qt::ScrollBarAsNeeded);
3534 d.current_work_area_->setVerticalScrollBarPolicy(
3535 Qt::ScrollBarAlwaysOff);
3536 } else if (ui_component == "statusbar") {
3537 statusBar()->setVisible(!statusBar()->isVisible());
3538 } else if (ui_component == "menubar") {
3539 menuBar()->setVisible(!menuBar()->isVisible());
3541 #if QT_VERSION >= 0x040300
3542 if (ui_component == "frame") {
3544 getContentsMargins(&l, &t, &r, &b);
3545 //are the frames in default state?
3546 d.current_work_area_->setFrameStyle(QFrame::NoFrame);
3548 setContentsMargins(-2, -2, -2, -2);
3550 setContentsMargins(0, 0, 0, 0);
3554 if (ui_component == "fullscreen") {
3562 void GuiView::toggleFullScreen()
3564 if (isFullScreen()) {
3565 for (int i = 0; i != d.splitter_->count(); ++i)
3566 d.tabWorkArea(i)->setFullScreen(false);
3567 #if QT_VERSION >= 0x040300
3568 setContentsMargins(0, 0, 0, 0);
3570 setWindowState(windowState() ^ Qt::WindowFullScreen);
3573 statusBar()->show();
3576 hideDialogs("prefs", 0);
3577 for (int i = 0; i != d.splitter_->count(); ++i)
3578 d.tabWorkArea(i)->setFullScreen(true);
3579 #if QT_VERSION >= 0x040300
3580 setContentsMargins(-2, -2, -2, -2);
3583 setWindowState(windowState() ^ Qt::WindowFullScreen);
3584 statusBar()->hide();
3585 if (lyxrc.full_screen_menubar)
3587 if (lyxrc.full_screen_toolbars) {
3588 ToolbarMap::iterator end = d.toolbars_.end();
3589 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
3594 // give dialogs like the TOC a chance to adapt
3599 Buffer const * GuiView::updateInset(Inset const * inset)
3604 Buffer const * inset_buffer = &(inset->buffer());
3606 for (int i = 0; i != d.splitter_->count(); ++i) {
3607 GuiWorkArea * wa = d.tabWorkArea(i)->currentWorkArea();
3610 Buffer const * buffer = &(wa->bufferView().buffer());
3611 if (inset_buffer == buffer)
3612 wa->scheduleRedraw();
3614 return inset_buffer;
3618 void GuiView::restartCursor()
3620 /* When we move around, or type, it's nice to be able to see
3621 * the cursor immediately after the keypress.
3623 if (d.current_work_area_)
3624 d.current_work_area_->startBlinkingCursor();
3626 // Take this occasion to update the other GUI elements.
3632 void GuiView::updateCompletion(Cursor & cur, bool start, bool keep)
3634 if (d.current_work_area_)
3635 d.current_work_area_->completer().updateVisibility(cur, start, keep);
3640 // This list should be kept in sync with the list of insets in
3641 // src/insets/Inset.cpp. I.e., if a dialog goes with an inset, the
3642 // dialog should have the same name as the inset.
3643 // Changes should be also recorded in LFUN_DIALOG_SHOW doxygen
3644 // docs in LyXAction.cpp.
3646 char const * const dialognames[] = {
3648 "aboutlyx", "bibitem", "bibtex", "box", "branch", "changes", "character",
3649 "citation", "compare", "comparehistory", "document", "errorlist", "ert",
3650 "external", "file", "findreplace", "findreplaceadv", "float", "graphics",
3651 "href", "include", "index", "index_print", "info", "listings", "label", "line",
3652 "log", "mathdelimiter", "mathmatrix", "mathspace", "nomenclature",
3653 "nomencl_print", "note", "paragraph", "phantom", "prefs", "print", "ref",
3654 "sendto", "space", "spellchecker", "symbols", "tabular", "tabularcreate",
3655 "thesaurus", "texinfo", "toc", "view-source", "vspace", "wrap", "progress"};
3657 char const * const * const end_dialognames =
3658 dialognames + (sizeof(dialognames) / sizeof(char *));
3662 cmpCStr(char const * name) : name_(name) {}
3663 bool operator()(char const * other) {
3664 return strcmp(other, name_) == 0;
3671 bool isValidName(string const & name)
3673 return find_if(dialognames, end_dialognames,
3674 cmpCStr(name.c_str())) != end_dialognames;
3680 void GuiView::resetDialogs()
3682 // Make sure that no LFUN uses any GuiView.
3683 guiApp->setCurrentView(0);
3687 constructToolbars();
3688 guiApp->menus().fillMenuBar(menuBar(), this, false);
3689 d.layout_->updateContents(true);
3690 // Now update controls with current buffer.
3691 guiApp->setCurrentView(this);
3697 Dialog * GuiView::findOrBuild(string const & name, bool hide_it)
3699 if (!isValidName(name))
3702 map<string, DialogPtr>::iterator it = d.dialogs_.find(name);
3704 if (it != d.dialogs_.end()) {
3706 it->second->hideView();
3707 return it->second.get();
3710 Dialog * dialog = build(name);
3711 d.dialogs_[name].reset(dialog);
3712 if (lyxrc.allow_geometry_session)
3713 dialog->restoreSession();
3720 void GuiView::showDialog(string const & name, string const & data,
3723 triggerShowDialog(toqstr(name), toqstr(data), inset);
3727 void GuiView::doShowDialog(QString const & qname, QString const & qdata,
3733 const string name = fromqstr(qname);
3734 const string data = fromqstr(qdata);
3738 Dialog * dialog = findOrBuild(name, false);
3740 bool const visible = dialog->isVisibleView();
3741 dialog->showData(data);
3742 if (inset && currentBufferView())
3743 currentBufferView()->editInset(name, inset);
3744 // We only set the focus to the new dialog if it was not yet
3745 // visible in order not to change the existing previous behaviour
3747 // activateWindow is needed for floating dockviews
3748 dialog->asQWidget()->raise();
3749 dialog->asQWidget()->activateWindow();
3750 dialog->asQWidget()->setFocus();
3754 catch (ExceptionMessage const & ex) {
3762 bool GuiView::isDialogVisible(string const & name) const
3764 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3765 if (it == d.dialogs_.end())
3767 return it->second.get()->isVisibleView() && !it->second.get()->isClosing();
3771 void GuiView::hideDialog(string const & name, Inset * inset)
3773 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3774 if (it == d.dialogs_.end())
3778 if (!currentBufferView())
3780 if (inset != currentBufferView()->editedInset(name))
3784 Dialog * const dialog = it->second.get();
3785 if (dialog->isVisibleView())
3787 if (currentBufferView())
3788 currentBufferView()->editInset(name, 0);
3792 void GuiView::disconnectDialog(string const & name)
3794 if (!isValidName(name))
3796 if (currentBufferView())
3797 currentBufferView()->editInset(name, 0);
3801 void GuiView::hideAll() const
3803 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
3804 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3806 for(; it != end; ++it)
3807 it->second->hideView();
3811 void GuiView::updateDialogs()
3813 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
3814 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3816 for(; it != end; ++it) {
3817 Dialog * dialog = it->second.get();
3819 if (dialog->needBufferOpen() && !documentBufferView())
3820 hideDialog(fromqstr(dialog->name()), 0);
3821 else if (dialog->isVisibleView())
3822 dialog->checkStatus();
3829 Dialog * createDialog(GuiView & lv, string const & name);
3831 // will be replaced by a proper factory...
3832 Dialog * createGuiAbout(GuiView & lv);
3833 Dialog * createGuiBibtex(GuiView & lv);
3834 Dialog * createGuiChanges(GuiView & lv);
3835 Dialog * createGuiCharacter(GuiView & lv);
3836 Dialog * createGuiCitation(GuiView & lv);
3837 Dialog * createGuiCompare(GuiView & lv);
3838 Dialog * createGuiCompareHistory(GuiView & lv);
3839 Dialog * createGuiDelimiter(GuiView & lv);
3840 Dialog * createGuiDocument(GuiView & lv);
3841 Dialog * createGuiErrorList(GuiView & lv);
3842 Dialog * createGuiExternal(GuiView & lv);
3843 Dialog * createGuiGraphics(GuiView & lv);
3844 Dialog * createGuiInclude(GuiView & lv);
3845 Dialog * createGuiIndex(GuiView & lv);
3846 Dialog * createGuiListings(GuiView & lv);
3847 Dialog * createGuiLog(GuiView & lv);
3848 Dialog * createGuiMathMatrix(GuiView & lv);
3849 Dialog * createGuiNote(GuiView & lv);
3850 Dialog * createGuiParagraph(GuiView & lv);
3851 Dialog * createGuiPhantom(GuiView & lv);
3852 Dialog * createGuiPreferences(GuiView & lv);
3853 Dialog * createGuiPrint(GuiView & lv);
3854 Dialog * createGuiPrintindex(GuiView & lv);
3855 Dialog * createGuiRef(GuiView & lv);
3856 Dialog * createGuiSearch(GuiView & lv);
3857 Dialog * createGuiSearchAdv(GuiView & lv);
3858 Dialog * createGuiSendTo(GuiView & lv);
3859 Dialog * createGuiShowFile(GuiView & lv);
3860 Dialog * createGuiSpellchecker(GuiView & lv);
3861 Dialog * createGuiSymbols(GuiView & lv);
3862 Dialog * createGuiTabularCreate(GuiView & lv);
3863 Dialog * createGuiTexInfo(GuiView & lv);
3864 Dialog * createGuiToc(GuiView & lv);
3865 Dialog * createGuiThesaurus(GuiView & lv);
3866 Dialog * createGuiViewSource(GuiView & lv);
3867 Dialog * createGuiWrap(GuiView & lv);
3868 Dialog * createGuiProgressView(GuiView & lv);
3872 Dialog * GuiView::build(string const & name)
3874 LASSERT(isValidName(name), return 0);
3876 Dialog * dialog = createDialog(*this, name);
3880 if (name == "aboutlyx")
3881 return createGuiAbout(*this);
3882 if (name == "bibtex")
3883 return createGuiBibtex(*this);
3884 if (name == "changes")
3885 return createGuiChanges(*this);
3886 if (name == "character")
3887 return createGuiCharacter(*this);
3888 if (name == "citation")
3889 return createGuiCitation(*this);
3890 if (name == "compare")
3891 return createGuiCompare(*this);
3892 if (name == "comparehistory")
3893 return createGuiCompareHistory(*this);
3894 if (name == "document")
3895 return createGuiDocument(*this);
3896 if (name == "errorlist")
3897 return createGuiErrorList(*this);
3898 if (name == "external")
3899 return createGuiExternal(*this);
3901 return createGuiShowFile(*this);
3902 if (name == "findreplace")
3903 return createGuiSearch(*this);
3904 if (name == "findreplaceadv")
3905 return createGuiSearchAdv(*this);
3906 if (name == "graphics")
3907 return createGuiGraphics(*this);
3908 if (name == "include")
3909 return createGuiInclude(*this);
3910 if (name == "index")
3911 return createGuiIndex(*this);
3912 if (name == "index_print")
3913 return createGuiPrintindex(*this);
3914 if (name == "listings")
3915 return createGuiListings(*this);
3917 return createGuiLog(*this);
3918 if (name == "mathdelimiter")
3919 return createGuiDelimiter(*this);
3920 if (name == "mathmatrix")
3921 return createGuiMathMatrix(*this);
3923 return createGuiNote(*this);
3924 if (name == "paragraph")
3925 return createGuiParagraph(*this);
3926 if (name == "phantom")
3927 return createGuiPhantom(*this);
3928 if (name == "prefs")
3929 return createGuiPreferences(*this);
3930 if (name == "print")
3931 return createGuiPrint(*this);
3933 return createGuiRef(*this);
3934 if (name == "sendto")
3935 return createGuiSendTo(*this);
3936 if (name == "spellchecker")
3937 return createGuiSpellchecker(*this);
3938 if (name == "symbols")
3939 return createGuiSymbols(*this);
3940 if (name == "tabularcreate")
3941 return createGuiTabularCreate(*this);
3942 if (name == "texinfo")
3943 return createGuiTexInfo(*this);
3944 if (name == "thesaurus")
3945 return createGuiThesaurus(*this);
3947 return createGuiToc(*this);
3948 if (name == "view-source")
3949 return createGuiViewSource(*this);
3951 return createGuiWrap(*this);
3952 if (name == "progress")
3953 return createGuiProgressView(*this);
3959 } // namespace frontend
3962 #include "moc_GuiView.cpp"