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>
96 #include <QPixmapCache>
98 #include <QPushButton>
100 #include <QShowEvent>
102 #include <QStackedWidget>
103 #include <QStatusBar>
108 #include <QScrollBar>
112 #define EXPORT_in_THREAD 1
114 // QtConcurrent was introduced in Qt 4.4
115 #if (QT_VERSION >= 0x040400)
117 #include <QFutureWatcher>
118 #include <QtConcurrentRun>
121 #include "support/bind.h"
125 #ifdef HAVE_SYS_TIME_H
126 # include <sys/time.h>
134 using namespace lyx::support;
141 class BackgroundWidget : public QWidget
146 LYXERR(Debug::GUI, "show banner: " << lyxrc.show_banner);
147 if (!lyxrc.show_banner)
149 /// The text to be written on top of the pixmap
150 QString const text = lyx_version ?
151 qt_("version ") + lyx_version : qt_("unknown version");
152 splash_ = getPixmap("images/", "banner", "png");
154 QPainter pain(&splash_);
155 pain.setPen(QColor(0, 0, 0));
157 // The font used to display the version info
158 font.setStyleHint(QFont::SansSerif);
159 font.setWeight(QFont::Bold);
160 font.setPointSize(int(toqstr(lyxrc.font_sizes[FONT_SIZE_LARGE]).toDouble()));
161 int width = QFontMetrics(font).width(text);
163 pain.drawText(397 - width, 15, text);
164 setFocusPolicy(Qt::StrongFocus);
167 void paintEvent(QPaintEvent *)
169 int x = (width() - splash_.width()) / 2;
170 int y = (height() - splash_.height()) / 2;
172 pain.drawPixmap(x, y, splash_);
175 void keyPressEvent(QKeyEvent * ev)
178 setKeySymbol(&sym, ev);
180 guiApp->processKeySym(sym, q_key_state(ev->modifiers()));
192 /// Toolbar store providing access to individual toolbars by name.
193 typedef map<string, GuiToolbar *> ToolbarMap;
195 typedef shared_ptr<Dialog> DialogPtr;
200 struct GuiView::GuiViewPrivate
202 GuiViewPrivate(GuiView * gv)
203 : gv_(gv), current_work_area_(0), current_main_work_area_(0),
204 layout_(0), autosave_timeout_(5000),
207 // hardcode here the platform specific icon size
208 smallIconSize = 14; // scaling problems
209 normalIconSize = 20; // ok, default
210 bigIconSize = 26; // better for some math icons
212 splitter_ = new QSplitter;
213 bg_widget_ = new BackgroundWidget;
214 stack_widget_ = new QStackedWidget;
215 stack_widget_->addWidget(bg_widget_);
216 stack_widget_->addWidget(splitter_);
219 // TODO cleanup, remove the singleton, handle multiple Windows?
220 progress_ = ProgressInterface::instance();
221 if (!dynamic_cast<GuiProgress*>(progress_)) {
222 progress_ = new GuiProgress(); // TODO who deletes it
223 ProgressInterface::setInstance(progress_);
226 dynamic_cast<GuiProgress*>(progress_),
227 SIGNAL(updateStatusBarMessage(QString const&)),
228 gv, SLOT(updateStatusBarMessage(QString const&)));
230 dynamic_cast<GuiProgress*>(progress_),
231 SIGNAL(clearMessageText()),
232 gv, SLOT(clearMessageText()));
239 delete stack_widget_;
242 QMenu * toolBarPopup(GuiView * parent)
244 // FIXME: translation
245 QMenu * menu = new QMenu(parent);
246 QActionGroup * iconSizeGroup = new QActionGroup(parent);
248 QAction * smallIcons = new QAction(iconSizeGroup);
249 smallIcons->setText(qt_("Small-sized icons"));
250 smallIcons->setCheckable(true);
251 QObject::connect(smallIcons, SIGNAL(triggered()),
252 parent, SLOT(smallSizedIcons()));
253 menu->addAction(smallIcons);
255 QAction * normalIcons = new QAction(iconSizeGroup);
256 normalIcons->setText(qt_("Normal-sized icons"));
257 normalIcons->setCheckable(true);
258 QObject::connect(normalIcons, SIGNAL(triggered()),
259 parent, SLOT(normalSizedIcons()));
260 menu->addAction(normalIcons);
262 QAction * bigIcons = new QAction(iconSizeGroup);
263 bigIcons->setText(qt_("Big-sized icons"));
264 bigIcons->setCheckable(true);
265 QObject::connect(bigIcons, SIGNAL(triggered()),
266 parent, SLOT(bigSizedIcons()));
267 menu->addAction(bigIcons);
269 unsigned int cur = parent->iconSize().width();
270 if ( cur == parent->d.smallIconSize)
271 smallIcons->setChecked(true);
272 else if (cur == parent->d.normalIconSize)
273 normalIcons->setChecked(true);
274 else if (cur == parent->d.bigIconSize)
275 bigIcons->setChecked(true);
282 stack_widget_->setCurrentWidget(bg_widget_);
283 bg_widget_->setUpdatesEnabled(true);
284 bg_widget_->setFocus();
287 int tabWorkAreaCount()
289 return splitter_->count();
292 TabWorkArea * tabWorkArea(int i)
294 return dynamic_cast<TabWorkArea *>(splitter_->widget(i));
297 TabWorkArea * currentTabWorkArea()
299 int areas = tabWorkAreaCount();
301 // The first TabWorkArea is always the first one, if any.
302 return tabWorkArea(0);
304 for (int i = 0; i != areas; ++i) {
305 TabWorkArea * twa = tabWorkArea(i);
306 if (current_main_work_area_ == twa->currentWorkArea())
310 // None has the focus so we just take the first one.
311 return tabWorkArea(0);
314 #if (QT_VERSION >= 0x040400)
315 void setPreviewFuture(QFuture<docstring> const & f)
317 if (processing_thread_watcher_.isRunning()) {
318 // we prefer to cancel this preview in order to keep a snappy
322 processing_thread_watcher_.setFuture(f);
328 GuiWorkArea * current_work_area_;
329 GuiWorkArea * current_main_work_area_;
330 QSplitter * splitter_;
331 QStackedWidget * stack_widget_;
332 BackgroundWidget * bg_widget_;
334 ToolbarMap toolbars_;
335 ProgressInterface* progress_;
336 /// The main layout box.
338 * \warning Don't Delete! The layout box is actually owned by
339 * whichever toolbar contains it. All the GuiView class needs is a
340 * means of accessing it.
342 * FIXME: replace that with a proper model so that we are not limited
343 * to only one dialog.
348 map<string, DialogPtr> dialogs_;
350 unsigned int smallIconSize;
351 unsigned int normalIconSize;
352 unsigned int bigIconSize;
354 QTimer statusbar_timer_;
355 /// auto-saving of buffers
356 Timeout autosave_timeout_;
357 /// flag against a race condition due to multiclicks, see bug #1119
361 TocModels toc_models_;
363 #if (QT_VERSION >= 0x040400)
365 QFutureWatcher<docstring> autosave_watcher_;
366 QFutureWatcher<docstring> processing_thread_watcher_;
368 string last_export_format;
370 struct DummyWatcher { bool isRunning(){return false;} };
371 DummyWatcher processing_thread_watcher_;
374 static QSet<Buffer const *> busyBuffers;
375 static docstring previewAndDestroy(Buffer const * orig, Buffer * buffer, string const & format);
376 static docstring exportAndDestroy(Buffer const * orig, Buffer * buffer, string const & format);
377 static docstring compileAndDestroy(Buffer const * orig, Buffer * buffer, string const & format);
378 static docstring autosaveAndDestroy(Buffer const * orig, Buffer * buffer);
381 static docstring runAndDestroy(const T& func, Buffer const * orig, Buffer * buffer, string const & format, string const & msg);
383 // TODO syncFunc/previewFunc: use bind
384 bool asyncBufferProcessing(string const & argument,
385 Buffer const * used_buffer,
386 docstring const & msg,
387 docstring (*asyncFunc)(Buffer const *, Buffer *, string const &),
388 bool (Buffer::*syncFunc)(string const &, bool, bool) const,
389 bool (Buffer::*previewFunc)(string const &, bool) const);
391 QTimer processing_cursor_timer_;
392 bool indicates_processing_;
393 QMap<GuiWorkArea*, Qt::CursorShape> orig_cursors_;
394 QVector<GuiWorkArea*> guiWorkAreas();
397 QSet<Buffer const *> GuiView::GuiViewPrivate::busyBuffers;
400 GuiView::GuiView(int id)
401 : d(*new GuiViewPrivate(this)), id_(id), closing_(false), busy_(0)
403 // GuiToolbars *must* be initialised before the menu bar.
404 normalSizedIcons(); // at least on Mac the default is 32 otherwise, which is huge
407 // set ourself as the current view. This is needed for the menu bar
408 // filling, at least for the static special menu item on Mac. Otherwise
409 // they are greyed out.
410 guiApp->setCurrentView(this);
412 // Fill up the menu bar.
413 guiApp->menus().fillMenuBar(menuBar(), this, true);
415 setCentralWidget(d.stack_widget_);
417 // Start autosave timer
418 if (lyxrc.autosave) {
419 d.autosave_timeout_.timeout.connect(bind(&GuiView::autoSave, this));
420 d.autosave_timeout_.setTimeout(lyxrc.autosave * 1000);
421 d.autosave_timeout_.start();
423 connect(&d.statusbar_timer_, SIGNAL(timeout()),
424 this, SLOT(clearMessage()));
426 // We don't want to keep the window in memory if it is closed.
427 setAttribute(Qt::WA_DeleteOnClose, true);
429 #if (!defined(Q_WS_WIN) && !defined(Q_WS_MACX))
430 // assign an icon to main form. We do not do it under Qt/Win or Qt/Mac,
431 // since the icon is provided in the application bundle.
432 setWindowIcon(getPixmap("images/", "lyx", "png"));
435 #if (QT_VERSION >= 0x040300)
436 // use tabbed dock area for multiple docks
437 // (such as "source" and "messages")
438 setDockOptions(QMainWindow::ForceTabbedDocks);
442 setAcceptDrops(true);
444 statusBar()->setSizeGripEnabled(true);
447 #if (QT_VERSION >= 0x040400)
448 connect(&d.autosave_watcher_, SIGNAL(finished()), this,
449 SLOT(autoSaveThreadFinished()));
450 connect(&d.processing_thread_watcher_, SIGNAL(finished()), this,
451 SLOT(processingThreadFinished()));
453 d.processing_cursor_timer_.setInterval(1000 * 3);
454 connect(&d.processing_cursor_timer_, SIGNAL(timeout()), this,
455 SLOT(indicateProcessing()));
458 connect(this, SIGNAL(triggerShowDialog(QString const &, QString const &, Inset *)),
459 SLOT(doShowDialog(QString const &, QString const &, Inset *)));
461 // Forbid too small unresizable window because it can happen
462 // with some window manager under X11.
463 setMinimumSize(300, 200);
465 if (lyxrc.allow_geometry_session) {
466 // Now take care of session management.
471 // no session handling, default to a sane size.
472 setGeometry(50, 50, 690, 510);
475 // clear session data if any.
477 settings.remove("views");
487 QVector<GuiWorkArea*> GuiView::GuiViewPrivate::guiWorkAreas()
489 QVector<GuiWorkArea*> areas;
490 for (int i = 0; i < tabWorkAreaCount(); i++) {
491 TabWorkArea* ta = tabWorkArea(i);
492 for (int u = 0; u < ta->count(); u++) {
493 areas << ta->workArea(u);
500 #if QT_VERSION >= 0x040400
501 void GuiView::setCursorShapes(Qt::CursorShape shape)
503 QVector<GuiWorkArea*> areas = d.guiWorkAreas();
504 Q_FOREACH(GuiWorkArea* wa, areas) {
505 wa->setCursorShape(shape);
510 void GuiView::restoreCursorShapes()
512 QVector<GuiWorkArea*> areas = d.guiWorkAreas();
513 Q_FOREACH(GuiWorkArea* wa, areas) {
514 if (d.orig_cursors_.contains(wa)) {
515 wa->setCursorShape(d.orig_cursors_[wa]);
521 void GuiView::saveCursorShapes()
523 d.orig_cursors_.clear();
524 QVector<GuiWorkArea*> areas = d.guiWorkAreas();
525 Q_FOREACH(GuiWorkArea* wa, areas) {
526 d.orig_cursors_[wa] = wa->cursorShape();
531 void GuiView::indicateProcessing()
533 if (d.indicates_processing_) {
534 restoreCursorShapes();
536 setCursorShapes(Qt::BusyCursor);
538 d.indicates_processing_ = !d.indicates_processing_;
542 void GuiView::processingThreadStarted()
545 d.indicates_processing_ = false;
546 indicateProcessing();
547 d.processing_cursor_timer_.start();
551 void GuiView::processingThreadFinished(bool show_errors)
553 QFutureWatcher<docstring> const * watcher =
554 static_cast<QFutureWatcher<docstring> const *>(sender());
555 message(watcher->result());
558 errors(d.last_export_format);
560 d.processing_cursor_timer_.stop();
561 restoreCursorShapes();
562 d.indicates_processing_ = false;
565 void GuiView::processingThreadFinished()
567 processingThreadFinished(true);
570 void GuiView::autoSaveThreadFinished()
572 processingThreadFinished(false);
577 void GuiView::setCursorShapes(Qt::CursorShape)
582 void GuiView::restoreCursorShapes()
587 void GuiView::saveCursorShapes()
592 void GuiView::indicateProcessing()
597 void GuiView::processingThreadStarted()
602 void GuiView::processingThreadFinished(bool)
607 void GuiView::processingThreadFinished()
612 void GuiView::autoSaveThreadFinished()
618 void GuiView::saveLayout() const
621 settings.beginGroup("views");
622 settings.beginGroup(QString::number(id_));
624 settings.setValue("pos", pos());
625 settings.setValue("size", size());
627 settings.setValue("geometry", saveGeometry());
629 settings.setValue("layout", saveState(0));
630 settings.setValue("icon_size", iconSize());
634 void GuiView::saveUISettings() const
636 // Save the toolbar private states
637 ToolbarMap::iterator end = d.toolbars_.end();
638 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
639 it->second->saveSession();
640 // Now take care of all other dialogs
641 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
642 for (; it!= d.dialogs_.end(); ++it)
643 it->second->saveSession();
647 bool GuiView::restoreLayout()
650 settings.beginGroup("views");
651 settings.beginGroup(QString::number(id_));
652 QString const icon_key = "icon_size";
653 if (!settings.contains(icon_key))
656 //code below is skipped when when ~/.config/LyX is (re)created
657 setIconSize(settings.value(icon_key).toSize());
659 QPoint pos = settings.value("pos", QPoint(50, 50)).toPoint();
660 QSize size = settings.value("size", QSize(690, 510)).toSize();
664 // Work-around for bug #6034: the window ends up in an undetermined
665 // state when trying to restore a maximized window when it is
666 // already maximized.
667 if (!(windowState() & Qt::WindowMaximized))
668 if (!restoreGeometry(settings.value("geometry").toByteArray()))
669 setGeometry(50, 50, 690, 510);
671 // Make sure layout is correctly oriented.
672 setLayoutDirection(qApp->layoutDirection());
674 // Allow the toc and view-source dock widget to be restored if needed.
676 if ((dialog = findOrBuild("toc", true)))
677 // see bug 5082. At least setup title and enabled state.
678 // Visibility will be adjusted by restoreState below.
679 dialog->prepareView();
680 if ((dialog = findOrBuild("view-source", true)))
681 dialog->prepareView();
682 if ((dialog = findOrBuild("progress", true)))
683 dialog->prepareView();
684 if ((dialog = findOrBuild("findreplaceadv", true)))
685 dialog->prepareView();
687 if (!restoreState(settings.value("layout").toByteArray(), 0))
694 GuiToolbar * GuiView::toolbar(string const & name)
696 ToolbarMap::iterator it = d.toolbars_.find(name);
697 if (it != d.toolbars_.end())
700 LYXERR(Debug::GUI, "Toolbar::display: no toolbar named " << name);
705 void GuiView::constructToolbars()
707 ToolbarMap::iterator it = d.toolbars_.begin();
708 for (; it != d.toolbars_.end(); ++it)
712 // I don't like doing this here, but the standard toolbar
713 // destroys this object when it's destroyed itself (vfr)
714 d.layout_ = new LayoutBox(*this);
715 d.stack_widget_->addWidget(d.layout_);
716 d.layout_->move(0,0);
718 // extracts the toolbars from the backend
719 Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
720 Toolbars::Infos::iterator end = guiApp->toolbars().end();
721 for (; cit != end; ++cit)
722 d.toolbars_[cit->name] = new GuiToolbar(*cit, *this);
726 void GuiView::initToolbars()
728 // extracts the toolbars from the backend
729 Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
730 Toolbars::Infos::iterator end = guiApp->toolbars().end();
731 for (; cit != end; ++cit) {
732 GuiToolbar * tb = toolbar(cit->name);
735 int const visibility = guiApp->toolbars().defaultVisibility(cit->name);
736 bool newline = !(visibility & Toolbars::SAMEROW);
737 tb->setVisible(false);
738 tb->setVisibility(visibility);
740 if (visibility & Toolbars::TOP) {
742 addToolBarBreak(Qt::TopToolBarArea);
743 addToolBar(Qt::TopToolBarArea, tb);
746 if (visibility & Toolbars::BOTTOM) {
747 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
748 #if (QT_VERSION >= 0x040202)
750 addToolBarBreak(Qt::BottomToolBarArea);
752 addToolBar(Qt::BottomToolBarArea, tb);
755 if (visibility & Toolbars::LEFT) {
756 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
757 #if (QT_VERSION >= 0x040202)
759 addToolBarBreak(Qt::LeftToolBarArea);
761 addToolBar(Qt::LeftToolBarArea, tb);
764 if (visibility & Toolbars::RIGHT) {
765 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
766 #if (QT_VERSION >= 0x040202)
768 addToolBarBreak(Qt::RightToolBarArea);
770 addToolBar(Qt::RightToolBarArea, tb);
773 if (visibility & Toolbars::ON)
774 tb->setVisible(true);
779 TocModels & GuiView::tocModels()
781 return d.toc_models_;
785 void GuiView::setFocus()
787 LYXERR(Debug::DEBUG, "GuiView::setFocus()" << this);
788 QMainWindow::setFocus();
792 void GuiView::focusInEvent(QFocusEvent * e)
794 LYXERR(Debug::DEBUG, "GuiView::focusInEvent()" << this);
795 QMainWindow::focusInEvent(e);
796 // Make sure guiApp points to the correct view.
797 guiApp->setCurrentView(this);
798 if (currentMainWorkArea())
799 currentMainWorkArea()->setFocus();
800 else if (currentWorkArea())
801 currentWorkArea()->setFocus();
803 d.bg_widget_->setFocus();
807 QMenu * GuiView::createPopupMenu()
809 return d.toolBarPopup(this);
813 void GuiView::showEvent(QShowEvent * e)
815 LYXERR(Debug::GUI, "Passed Geometry "
816 << size().height() << "x" << size().width()
817 << "+" << pos().x() << "+" << pos().y());
819 if (d.splitter_->count() == 0)
820 // No work area, switch to the background widget.
823 QMainWindow::showEvent(e);
827 bool GuiView::closeScheduled()
834 /** Destroy only all tabbed WorkAreas. Destruction of other WorkAreas
835 ** is responsibility of the container (e.g., dialog)
837 void GuiView::closeEvent(QCloseEvent * close_event)
839 LYXERR(Debug::DEBUG, "GuiView::closeEvent()");
841 if (!GuiViewPrivate::busyBuffers.isEmpty()) {
842 Alert::warning(_("Exit LyX"),
843 _("LyX could not be closed because documents are being processed by LyX."));
844 close_event->setAccepted(false);
848 // If the user pressed the x (so we didn't call closeView
849 // programmatically), we want to clear all existing entries.
851 theSession().lastOpened().clear();
856 // it can happen that this event arrives without selecting the view,
857 // e.g. when clicking the close button on a background window.
859 if (!closeWorkAreaAll()) {
861 close_event->ignore();
865 // Make sure that nothing will use this to be closed View.
866 guiApp->unregisterView(this);
868 if (isFullScreen()) {
869 // Switch off fullscreen before closing.
874 // Make sure the timer time out will not trigger a statusbar update.
875 d.statusbar_timer_.stop();
877 // Saving fullscreen requires additional tweaks in the toolbar code.
878 // It wouldn't also work under linux natively.
879 if (lyxrc.allow_geometry_session) {
884 close_event->accept();
888 void GuiView::dragEnterEvent(QDragEnterEvent * event)
890 if (event->mimeData()->hasUrls())
892 /// \todo Ask lyx-devel is this is enough:
893 /// if (event->mimeData()->hasFormat("text/plain"))
894 /// event->acceptProposedAction();
898 void GuiView::dropEvent(QDropEvent * event)
900 QList<QUrl> files = event->mimeData()->urls();
904 LYXERR(Debug::GUI, "GuiView::dropEvent: got URLs!");
905 for (int i = 0; i != files.size(); ++i) {
906 string const file = os::internal_path(fromqstr(
907 files.at(i).toLocalFile()));
911 string const ext = support::getExtension(file);
912 vector<const Format *> found_formats;
914 // Find all formats that have the correct extension.
915 vector<const Format *> const & import_formats
916 = theConverters().importableFormats();
917 vector<const Format *>::const_iterator it = import_formats.begin();
918 for (; it != import_formats.end(); ++it)
919 if ((*it)->extension() == ext)
920 found_formats.push_back(*it);
923 if (found_formats.size() >= 1) {
924 if (found_formats.size() > 1) {
925 //FIXME: show a dialog to choose the correct importable format
927 "Multiple importable formats found, selecting first");
929 string const arg = found_formats[0]->name() + " " + file;
930 cmd = FuncRequest(LFUN_BUFFER_IMPORT, arg);
933 //FIXME: do we have to explicitly check whether it's a lyx file?
935 "No formats found, trying to open it as a lyx file");
936 cmd = FuncRequest(LFUN_FILE_OPEN, file);
938 // add the functions to the queue
939 guiApp->addToFuncRequestQueue(cmd);
942 // now process the collected functions. We perform the events
943 // asynchronously. This prevents potential problems in case the
944 // BufferView is closed within an event.
945 guiApp->processFuncRequestQueueAsync();
949 void GuiView::message(docstring const & str)
951 if (ForkedProcess::iAmAChild())
954 // call is moved to GUI-thread by GuiProgress
955 d.progress_->appendMessage(toqstr(str));
959 void GuiView::clearMessageText()
961 message(docstring());
965 void GuiView::updateStatusBarMessage(QString const & str)
967 statusBar()->showMessage(str);
968 d.statusbar_timer_.stop();
969 d.statusbar_timer_.start(3000);
973 void GuiView::smallSizedIcons()
975 setIconSize(QSize(d.smallIconSize, d.smallIconSize));
979 void GuiView::normalSizedIcons()
981 setIconSize(QSize(d.normalIconSize, d.normalIconSize));
985 void GuiView::bigSizedIcons()
987 setIconSize(QSize(d.bigIconSize, d.bigIconSize));
991 void GuiView::clearMessage()
993 // FIXME: This code was introduced in r19643 to fix bug #4123. However,
994 // the hasFocus function mostly returns false, even if the focus is on
995 // a workarea in this view.
999 d.statusbar_timer_.stop();
1003 void GuiView::updateWindowTitle(GuiWorkArea * wa)
1005 if (wa != d.current_work_area_
1006 || wa->bufferView().buffer().isInternal())
1008 setWindowTitle(qt_("LyX: ") + wa->windowTitle());
1009 setWindowIconText(wa->windowIconText());
1013 void GuiView::on_currentWorkAreaChanged(GuiWorkArea * wa)
1016 disconnectBufferView();
1017 connectBufferView(wa->bufferView());
1018 connectBuffer(wa->bufferView().buffer());
1019 d.current_work_area_ = wa;
1020 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
1021 this, SLOT(updateWindowTitle(GuiWorkArea *)));
1022 updateWindowTitle(wa);
1026 // The document settings needs to be reinitialised.
1027 updateDialog("document", "");
1029 // Buffer-dependent dialogs must be updated. This is done here because
1030 // some dialogs require buffer()->text.
1035 void GuiView::on_lastWorkAreaRemoved()
1038 // We already are in a close event. Nothing more to do.
1041 if (d.splitter_->count() > 1)
1042 // We have a splitter so don't close anything.
1045 // Reset and updates the dialogs.
1046 d.toc_models_.reset(0);
1047 updateDialog("document", "");
1050 resetWindowTitleAndIconText();
1053 if (lyxrc.open_buffers_in_tabs)
1054 // Nothing more to do, the window should stay open.
1057 if (guiApp->viewIds().size() > 1) {
1063 // On Mac we also close the last window because the application stay
1064 // resident in memory. On other platforms we don't close the last
1065 // window because this would quit the application.
1071 void GuiView::updateStatusBar()
1073 // let the user see the explicit message
1074 if (d.statusbar_timer_.isActive())
1081 void GuiView::showMessage()
1083 QString msg = toqstr(theGuiApp()->viewStatusMessage());
1084 if (msg.isEmpty()) {
1085 BufferView const * bv = currentBufferView();
1087 msg = toqstr(bv->cursor().currentState());
1089 msg = qt_("Welcome to LyX!");
1091 statusBar()->showMessage(msg);
1095 bool GuiView::event(QEvent * e)
1099 // Useful debug code:
1100 //case QEvent::ActivationChange:
1101 //case QEvent::WindowDeactivate:
1102 //case QEvent::Paint:
1103 //case QEvent::Enter:
1104 //case QEvent::Leave:
1105 //case QEvent::HoverEnter:
1106 //case QEvent::HoverLeave:
1107 //case QEvent::HoverMove:
1108 //case QEvent::StatusTip:
1109 //case QEvent::DragEnter:
1110 //case QEvent::DragLeave:
1111 //case QEvent::Drop:
1114 case QEvent::WindowActivate: {
1115 GuiView * old_view = guiApp->currentView();
1116 if (this == old_view) {
1118 return QMainWindow::event(e);
1120 if (old_view && old_view->currentBufferView()) {
1121 // save current selection to the selection buffer to allow
1122 // middle-button paste in this window.
1123 cap::saveSelection(old_view->currentBufferView()->cursor());
1125 guiApp->setCurrentView(this);
1126 if (d.current_work_area_) {
1127 BufferView & bv = d.current_work_area_->bufferView();
1128 connectBufferView(bv);
1129 connectBuffer(bv.buffer());
1130 // The document structure, name and dialogs might have
1131 // changed in another view.
1133 // The document settings needs to be reinitialised.
1134 updateDialog("document", "");
1137 resetWindowTitleAndIconText();
1140 return QMainWindow::event(e);
1143 case QEvent::ShortcutOverride: {
1146 #if (!defined Q_WS_X11) || (QT_VERSION >= 0x040500)
1147 if (isFullScreen() && menuBar()->isHidden()) {
1148 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
1149 // FIXME: we should also try to detect special LyX shortcut such as
1150 // Alt-P and Alt-M. Right now there is a hack in
1151 // GuiWorkArea::processKeySym() that hides again the menubar for
1153 if (ke->modifiers() & Qt::AltModifier && ke->key() != Qt::Key_Alt) {
1155 return QMainWindow::event(e);
1159 return QMainWindow::event(e);
1163 return QMainWindow::event(e);
1167 void GuiView::resetWindowTitleAndIconText()
1169 setWindowTitle(qt_("LyX"));
1170 setWindowIconText(qt_("LyX"));
1173 bool GuiView::focusNextPrevChild(bool /*next*/)
1180 bool GuiView::busy() const
1186 void GuiView::setBusy(bool busy)
1188 bool const busy_before = busy_ > 0;
1189 busy ? ++busy_ : --busy_;
1190 if ((busy_ > 0) == busy_before)
1191 // busy state didn't change
1194 if (d.current_work_area_) {
1195 d.current_work_area_->setUpdatesEnabled(!busy);
1197 d.current_work_area_->stopBlinkingCursor();
1199 d.current_work_area_->startBlinkingCursor();
1203 QApplication::setOverrideCursor(Qt::WaitCursor);
1205 QApplication::restoreOverrideCursor();
1209 GuiWorkArea * GuiView::workArea(int index)
1211 if (TabWorkArea * twa = d.currentTabWorkArea())
1212 if (index < twa->count())
1213 return dynamic_cast<GuiWorkArea *>(twa->widget(index));
1218 GuiWorkArea * GuiView::workArea(Buffer & buffer)
1220 if (currentWorkArea()
1221 && ¤tWorkArea()->bufferView().buffer() == &buffer)
1222 return (GuiWorkArea *) currentWorkArea();
1223 if (TabWorkArea * twa = d.currentTabWorkArea())
1224 return twa->workArea(buffer);
1229 GuiWorkArea * GuiView::addWorkArea(Buffer & buffer)
1231 // Automatically create a TabWorkArea if there are none yet.
1232 TabWorkArea * tab_widget = d.splitter_->count()
1233 ? d.currentTabWorkArea() : addTabWorkArea();
1234 return tab_widget->addWorkArea(buffer, *this);
1238 TabWorkArea * GuiView::addTabWorkArea()
1240 TabWorkArea * twa = new TabWorkArea;
1241 QObject::connect(twa, SIGNAL(currentWorkAreaChanged(GuiWorkArea *)),
1242 this, SLOT(on_currentWorkAreaChanged(GuiWorkArea *)));
1243 QObject::connect(twa, SIGNAL(lastWorkAreaRemoved()),
1244 this, SLOT(on_lastWorkAreaRemoved()));
1246 d.splitter_->addWidget(twa);
1247 d.stack_widget_->setCurrentWidget(d.splitter_);
1252 GuiWorkArea const * GuiView::currentWorkArea() const
1254 return d.current_work_area_;
1258 GuiWorkArea * GuiView::currentWorkArea()
1260 return d.current_work_area_;
1264 GuiWorkArea const * GuiView::currentMainWorkArea() const
1266 if (!d.currentTabWorkArea())
1268 return d.currentTabWorkArea()->currentWorkArea();
1272 GuiWorkArea * GuiView::currentMainWorkArea()
1274 if (!d.currentTabWorkArea())
1276 return d.currentTabWorkArea()->currentWorkArea();
1280 void GuiView::setCurrentWorkArea(GuiWorkArea * wa)
1282 LYXERR(Debug::DEBUG, "Setting current wa: " << wa << endl);
1284 d.current_work_area_ = 0;
1289 // FIXME: I've no clue why this is here and why it accesses
1290 // theGuiApp()->currentView, which might be 0 (bug 6464).
1291 // See also 27525 (vfr).
1292 if (theGuiApp()->currentView() == this
1293 && theGuiApp()->currentView()->currentWorkArea() == wa)
1296 if (currentBufferView())
1297 cap::saveSelection(currentBufferView()->cursor());
1299 theGuiApp()->setCurrentView(this);
1300 d.current_work_area_ = wa;
1302 // We need to reset this now, because it will need to be
1303 // right if the tabWorkArea gets reset in the for loop. We
1304 // will change it back if we aren't in that case.
1305 GuiWorkArea * const old_cmwa = d.current_main_work_area_;
1306 d.current_main_work_area_ = wa;
1308 for (int i = 0; i != d.splitter_->count(); ++i) {
1309 if (d.tabWorkArea(i)->setCurrentWorkArea(wa)) {
1310 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea()
1311 << ", Current main wa: " << currentMainWorkArea());
1316 d.current_main_work_area_ = old_cmwa;
1318 LYXERR(Debug::DEBUG, "This is not a tabbed wa");
1319 on_currentWorkAreaChanged(wa);
1320 BufferView & bv = wa->bufferView();
1321 bv.cursor().fixIfBroken();
1323 wa->setUpdatesEnabled(true);
1324 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() << ", Current main wa: " << currentMainWorkArea());
1328 void GuiView::removeWorkArea(GuiWorkArea * wa)
1330 LASSERT(wa, return);
1331 if (wa == d.current_work_area_) {
1333 disconnectBufferView();
1334 d.current_work_area_ = 0;
1335 d.current_main_work_area_ = 0;
1338 bool found_twa = false;
1339 for (int i = 0; i != d.splitter_->count(); ++i) {
1340 TabWorkArea * twa = d.tabWorkArea(i);
1341 if (twa->removeWorkArea(wa)) {
1342 // Found in this tab group, and deleted the GuiWorkArea.
1344 if (twa->count() != 0) {
1345 if (d.current_work_area_ == 0)
1346 // This means that we are closing the current GuiWorkArea, so
1347 // switch to the next GuiWorkArea in the found TabWorkArea.
1348 setCurrentWorkArea(twa->currentWorkArea());
1350 // No more WorkAreas in this tab group, so delete it.
1357 // It is not a tabbed work area (i.e., the search work area), so it
1358 // should be deleted by other means.
1359 LASSERT(found_twa, /* */);
1361 if (d.current_work_area_ == 0) {
1362 if (d.splitter_->count() != 0) {
1363 TabWorkArea * twa = d.currentTabWorkArea();
1364 setCurrentWorkArea(twa->currentWorkArea());
1366 // No more work areas, switch to the background widget.
1367 setCurrentWorkArea(0);
1373 LayoutBox * GuiView::getLayoutDialog() const
1379 void GuiView::updateLayoutList()
1382 d.layout_->updateContents(false);
1386 void GuiView::updateToolbars()
1388 ToolbarMap::iterator end = d.toolbars_.end();
1389 if (d.current_work_area_) {
1391 d.current_work_area_->bufferView().cursor().inMathed()
1392 && !d.current_work_area_->bufferView().cursor().inRegexped();
1394 lyx::getStatus(FuncRequest(LFUN_LAYOUT_TABULAR)).enabled();
1396 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).enabled() &&
1397 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).onOff(true);
1398 bool const mathmacrotemplate =
1399 lyx::getStatus(FuncRequest(LFUN_IN_MATHMACROTEMPLATE)).enabled();
1401 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1402 it->second->update(math, table, review, mathmacrotemplate);
1404 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1405 it->second->update(false, false, false, false);
1409 void GuiView::setBuffer(Buffer * newBuffer)
1411 LYXERR(Debug::DEBUG, "Setting buffer: " << newBuffer << endl);
1412 LASSERT(newBuffer, return);
1415 GuiWorkArea * wa = workArea(*newBuffer);
1417 newBuffer->masterBuffer()->updateBuffer();
1418 wa = addWorkArea(*newBuffer);
1419 // scroll to the position when the BufferView was last closed
1420 if (lyxrc.use_lastfilepos) {
1421 LastFilePosSection::FilePos filepos =
1422 theSession().lastFilePos().load(newBuffer->fileName());
1423 wa->bufferView().moveToPosition(filepos.pit, filepos.pos, 0, 0);
1426 //Disconnect the old buffer...there's no new one.
1429 connectBuffer(*newBuffer);
1430 connectBufferView(wa->bufferView());
1431 setCurrentWorkArea(wa);
1437 void GuiView::connectBuffer(Buffer & buf)
1439 buf.setGuiDelegate(this);
1443 void GuiView::disconnectBuffer()
1445 if (d.current_work_area_)
1446 d.current_work_area_->bufferView().buffer().setGuiDelegate(0);
1450 void GuiView::connectBufferView(BufferView & bv)
1452 bv.setGuiDelegate(this);
1456 void GuiView::disconnectBufferView()
1458 if (d.current_work_area_)
1459 d.current_work_area_->bufferView().setGuiDelegate(0);
1463 void GuiView::errors(string const & error_type, bool from_master)
1465 BufferView const * const bv = currentBufferView();
1469 ErrorList & el = from_master ?
1470 bv->buffer().masterBuffer()->errorList(error_type) :
1471 bv->buffer().errorList(error_type);
1475 string data = error_type;
1477 data = "from_master|" + error_type;
1478 showDialog("errorlist", data);
1482 void GuiView::updateTocItem(string const & type, DocIterator const & dit)
1484 d.toc_models_.updateItem(toqstr(type), dit);
1488 void GuiView::structureChanged()
1490 d.toc_models_.reset(documentBufferView());
1491 // Navigator needs more than a simple update in this case. It needs to be
1493 updateDialog("toc", "");
1497 void GuiView::updateDialog(string const & name, string const & data)
1499 if (!isDialogVisible(name))
1502 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
1503 if (it == d.dialogs_.end())
1506 Dialog * const dialog = it->second.get();
1507 if (dialog->isVisibleView())
1508 dialog->initialiseParams(data);
1512 BufferView * GuiView::documentBufferView()
1514 return currentMainWorkArea()
1515 ? ¤tMainWorkArea()->bufferView()
1520 BufferView const * GuiView::documentBufferView() const
1522 return currentMainWorkArea()
1523 ? ¤tMainWorkArea()->bufferView()
1528 BufferView * GuiView::currentBufferView()
1530 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1534 BufferView const * GuiView::currentBufferView() const
1536 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1540 #if (QT_VERSION >= 0x040400)
1541 docstring GuiView::GuiViewPrivate::autosaveAndDestroy(
1542 Buffer const * orig, Buffer * buffer)
1544 bool const success = buffer->autoSave();
1546 busyBuffers.remove(orig);
1548 ? _("Automatic save done.")
1549 : _("Automatic save failed!");
1554 void GuiView::autoSave()
1556 LYXERR(Debug::INFO, "Running autoSave()");
1558 Buffer * buffer = documentBufferView()
1559 ? &documentBufferView()->buffer() : 0;
1563 #if (QT_VERSION >= 0x040400)
1564 GuiViewPrivate::busyBuffers.insert(buffer);
1565 QFuture<docstring> f = QtConcurrent::run(GuiViewPrivate::autosaveAndDestroy,
1566 buffer, buffer->clone());
1567 d.autosave_watcher_.setFuture(f);
1571 resetAutosaveTimers();
1575 void GuiView::resetAutosaveTimers()
1578 d.autosave_timeout_.restart();
1582 bool GuiView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1585 Buffer * buf = currentBufferView()
1586 ? ¤tBufferView()->buffer() : 0;
1587 Buffer * doc_buffer = documentBufferView()
1588 ? &(documentBufferView()->buffer()) : 0;
1590 // Check whether we need a buffer
1591 if (!lyxaction.funcHasFlag(cmd.action(), LyXAction::NoBuffer) && !buf) {
1592 // no, exit directly
1593 flag.message(from_utf8(N_("Command not allowed with"
1594 "out any document open")));
1595 flag.setEnabled(false);
1599 if (cmd.origin() == FuncRequest::TOC) {
1600 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
1601 if (!toc || !toc->getStatus(documentBufferView()->cursor(), cmd, flag))
1602 flag.setEnabled(false);
1606 switch(cmd.action()) {
1607 case LFUN_BUFFER_IMPORT:
1610 case LFUN_MASTER_BUFFER_UPDATE:
1611 case LFUN_MASTER_BUFFER_VIEW:
1612 enable = doc_buffer && doc_buffer->parent() != 0
1613 && !d.processing_thread_watcher_.isRunning();
1616 case LFUN_BUFFER_UPDATE:
1617 case LFUN_BUFFER_VIEW: {
1618 if (!doc_buffer || d.processing_thread_watcher_.isRunning()) {
1622 string format = to_utf8(cmd.argument());
1623 if (cmd.argument().empty())
1624 format = doc_buffer->getDefaultOutputFormat();
1625 enable = doc_buffer->isExportableFormat(format);
1629 case LFUN_BUFFER_RELOAD:
1630 enable = doc_buffer && !doc_buffer->isUnnamed()
1631 && doc_buffer->fileName().exists()
1632 && (!doc_buffer->isClean()
1633 || doc_buffer->isExternallyModified(Buffer::timestamp_method));
1636 case LFUN_BUFFER_CHILD_OPEN:
1637 enable = doc_buffer;
1640 case LFUN_BUFFER_WRITE:
1641 enable = doc_buffer && (doc_buffer->isUnnamed() || !doc_buffer->isClean());
1644 //FIXME: This LFUN should be moved to GuiApplication.
1645 case LFUN_BUFFER_WRITE_ALL: {
1646 // We enable the command only if there are some modified buffers
1647 Buffer * first = theBufferList().first();
1652 // We cannot use a for loop as the buffer list is a cycle.
1654 if (!b->isClean()) {
1658 b = theBufferList().next(b);
1659 } while (b != first);
1663 case LFUN_BUFFER_WRITE_AS:
1664 enable = doc_buffer;
1667 case LFUN_BUFFER_CLOSE:
1668 enable = doc_buffer;
1671 case LFUN_BUFFER_CLOSE_ALL:
1672 enable = theBufferList().last() != theBufferList().first();
1675 case LFUN_SPLIT_VIEW:
1676 if (cmd.getArg(0) == "vertical")
1677 enable = doc_buffer && (d.splitter_->count() == 1 ||
1678 d.splitter_->orientation() == Qt::Vertical);
1680 enable = doc_buffer && (d.splitter_->count() == 1 ||
1681 d.splitter_->orientation() == Qt::Horizontal);
1684 case LFUN_CLOSE_TAB_GROUP:
1685 enable = d.currentTabWorkArea();
1688 case LFUN_TOOLBAR_TOGGLE: {
1689 string const name = cmd.getArg(0);
1690 if (GuiToolbar * t = toolbar(name))
1691 flag.setOnOff(t->isVisible());
1694 docstring const msg =
1695 bformat(_("Unknown toolbar \"%1$s\""), from_utf8(name));
1701 case LFUN_DROP_LAYOUTS_CHOICE:
1705 case LFUN_UI_TOGGLE:
1706 flag.setOnOff(isFullScreen());
1709 case LFUN_DIALOG_DISCONNECT_INSET:
1712 case LFUN_DIALOG_HIDE:
1713 // FIXME: should we check if the dialog is shown?
1716 case LFUN_DIALOG_TOGGLE:
1717 flag.setOnOff(isDialogVisible(cmd.getArg(0)));
1718 // fall through to set "enable"
1719 case LFUN_DIALOG_SHOW: {
1720 string const name = cmd.getArg(0);
1722 enable = name == "aboutlyx"
1723 || name == "file" //FIXME: should be removed.
1725 || name == "texinfo"
1726 || name == "progress"
1727 || name == "compare";
1728 else if (name == "print")
1729 enable = doc_buffer->isExportable("dvi")
1730 && lyxrc.print_command != "none";
1731 else if (name == "character" || name == "symbols") {
1732 if (!buf || buf->isReadonly())
1735 // FIXME we should consider passthru
1737 Inset const & in = currentBufferView()->cursor().inset();
1738 enable = !in.getLayout().isPassThru();
1741 else if (name == "latexlog")
1742 enable = FileName(doc_buffer->logName()).isReadableFile();
1743 else if (name == "spellchecker")
1744 enable = theSpellChecker() && !doc_buffer->isReadonly();
1745 else if (name == "vclog")
1746 enable = doc_buffer->lyxvc().inUse();
1750 case LFUN_DIALOG_UPDATE: {
1751 string const name = cmd.getArg(0);
1753 enable = name == "prefs";
1757 case LFUN_COMMAND_EXECUTE:
1759 case LFUN_MENU_OPEN:
1760 // Nothing to check.
1763 case LFUN_COMPLETION_INLINE:
1764 if (!d.current_work_area_
1765 || !d.current_work_area_->completer().inlinePossible(
1766 currentBufferView()->cursor()))
1770 case LFUN_COMPLETION_POPUP:
1771 if (!d.current_work_area_
1772 || !d.current_work_area_->completer().popupPossible(
1773 currentBufferView()->cursor()))
1777 case LFUN_COMPLETION_COMPLETE:
1778 if (!d.current_work_area_
1779 || !d.current_work_area_->completer().inlinePossible(
1780 currentBufferView()->cursor()))
1784 case LFUN_COMPLETION_ACCEPT:
1785 if (!d.current_work_area_
1786 || (!d.current_work_area_->completer().popupVisible()
1787 && !d.current_work_area_->completer().inlineVisible()
1788 && !d.current_work_area_->completer().completionAvailable()))
1792 case LFUN_COMPLETION_CANCEL:
1793 if (!d.current_work_area_
1794 || (!d.current_work_area_->completer().popupVisible()
1795 && !d.current_work_area_->completer().inlineVisible()))
1799 case LFUN_BUFFER_ZOOM_OUT:
1800 enable = doc_buffer && lyxrc.zoom > 10;
1803 case LFUN_BUFFER_ZOOM_IN:
1804 enable = doc_buffer;
1807 case LFUN_BUFFER_NEXT:
1808 case LFUN_BUFFER_PREVIOUS:
1809 // FIXME: should we check is there is an previous or next buffer?
1811 case LFUN_BUFFER_SWITCH:
1812 // toggle on the current buffer, but do not toggle off
1813 // the other ones (is that a good idea?)
1815 && to_utf8(cmd.argument()) == doc_buffer->absFileName())
1816 flag.setOnOff(true);
1819 case LFUN_VC_REGISTER:
1820 enable = doc_buffer && !doc_buffer->lyxvc().inUse();
1822 case LFUN_VC_CHECK_IN:
1823 enable = doc_buffer && doc_buffer->lyxvc().checkInEnabled();
1825 case LFUN_VC_CHECK_OUT:
1826 enable = doc_buffer && doc_buffer->lyxvc().checkOutEnabled();
1828 case LFUN_VC_LOCKING_TOGGLE:
1829 enable = doc_buffer && !doc_buffer->isReadonly()
1830 && doc_buffer->lyxvc().lockingToggleEnabled();
1831 flag.setOnOff(enable && doc_buffer->lyxvc().locking());
1833 case LFUN_VC_REVERT:
1834 enable = doc_buffer && doc_buffer->lyxvc().inUse() && !doc_buffer->isReadonly();
1836 case LFUN_VC_UNDO_LAST:
1837 enable = doc_buffer && doc_buffer->lyxvc().undoLastEnabled();
1839 case LFUN_VC_REPO_UPDATE:
1840 enable = doc_buffer && doc_buffer->lyxvc().repoUpdateEnabled();
1842 case LFUN_VC_COMMAND: {
1843 if (cmd.argument().empty())
1845 if (!doc_buffer && contains(cmd.getArg(0), 'D'))
1849 case LFUN_VC_COMPARE:
1850 enable = doc_buffer && doc_buffer->lyxvc().prepareFileRevisionEnabled();
1853 case LFUN_SERVER_GOTO_FILE_ROW:
1855 case LFUN_FORWARD_SEARCH:
1856 enable = !(lyxrc.forward_search_dvi.empty() && lyxrc.forward_search_pdf.empty());
1864 flag.setEnabled(false);
1870 static FileName selectTemplateFile()
1872 FileDialog dlg(qt_("Select template file"));
1873 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1874 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
1876 FileDialog::Result result = dlg.open(toqstr(lyxrc.template_path),
1877 QStringList(qt_("LyX Documents (*.lyx)")));
1879 if (result.first == FileDialog::Later)
1881 if (result.second.isEmpty())
1883 return FileName(fromqstr(result.second));
1887 Buffer * GuiView::loadDocument(FileName const & filename, bool tolastfiles)
1891 Buffer * newBuffer = 0;
1893 newBuffer = checkAndLoadLyXFile(filename);
1894 } catch (ExceptionMessage const & e) {
1900 message(_("Document not loaded."));
1905 newBuffer->errors("Parse");
1906 setBuffer(newBuffer);
1909 theSession().lastFiles().add(filename);
1916 void GuiView::openDocument(string const & fname)
1918 string initpath = lyxrc.document_path;
1920 if (documentBufferView()) {
1921 string const trypath = documentBufferView()->buffer().filePath();
1922 // If directory is writeable, use this as default.
1923 if (FileName(trypath).isDirWritable())
1929 if (fname.empty()) {
1930 FileDialog dlg(qt_("Select document to open"), LFUN_FILE_OPEN);
1931 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1932 dlg.setButton2(qt_("Examples|#E#e"),
1933 toqstr(addPath(package().system_support().absFileName(), "examples")));
1935 QStringList filter(qt_("LyX Documents (*.lyx)"));
1936 filter << qt_("LyX-1.3.x Documents (*.lyx13)")
1937 << qt_("LyX-1.4.x Documents (*.lyx14)")
1938 << qt_("LyX-1.5.x Documents (*.lyx15)")
1939 << qt_("LyX-1.6.x Documents (*.lyx16)");
1940 FileDialog::Result result =
1941 dlg.open(toqstr(initpath), filter);
1943 if (result.first == FileDialog::Later)
1946 filename = fromqstr(result.second);
1948 // check selected filename
1949 if (filename.empty()) {
1950 message(_("Canceled."));
1956 // get absolute path of file and add ".lyx" to the filename if
1958 FileName const fullname =
1959 fileSearch(string(), filename, "lyx", support::may_not_exist);
1960 if (!fullname.empty())
1961 filename = fullname.absFileName();
1963 if (!fullname.onlyPath().isDirectory()) {
1964 Alert::warning(_("Invalid filename"),
1965 bformat(_("The directory in the given path\n%1$s\ndoes not exist."),
1966 from_utf8(fullname.absFileName())));
1970 // if the file doesn't exist and isn't already open (bug 6645),
1971 // let the user create one
1972 if (!fullname.exists() && !theBufferList().exists(fullname)) {
1973 // the user specifically chose this name. Believe him.
1974 Buffer * const b = newFile(filename, string(), true);
1980 docstring const disp_fn = makeDisplayPath(filename);
1981 message(bformat(_("Opening document %1$s..."), disp_fn));
1984 Buffer * buf = loadDocument(fullname);
1986 str2 = bformat(_("Document %1$s opened."), disp_fn);
1987 if (buf->lyxvc().inUse())
1988 str2 += " " + from_utf8(buf->lyxvc().versionString()) +
1989 " " + _("Version control detected.");
1991 str2 = bformat(_("Could not open document %1$s"), disp_fn);
1996 // FIXME: clean that
1997 static bool import(GuiView * lv, FileName const & filename,
1998 string const & format, ErrorList & errorList)
2000 FileName const lyxfile(support::changeExtension(filename.absFileName(), ".lyx"));
2002 string loader_format;
2003 vector<string> loaders = theConverters().loaders();
2004 if (find(loaders.begin(), loaders.end(), format) == loaders.end()) {
2005 for (vector<string>::const_iterator it = loaders.begin();
2006 it != loaders.end(); ++it) {
2007 if (!theConverters().isReachable(format, *it))
2010 string const tofile =
2011 support::changeExtension(filename.absFileName(),
2012 formats.extension(*it));
2013 if (!theConverters().convert(0, filename, FileName(tofile),
2014 filename, format, *it, errorList))
2016 loader_format = *it;
2019 if (loader_format.empty()) {
2020 frontend::Alert::error(_("Couldn't import file"),
2021 bformat(_("No information for importing the format %1$s."),
2022 formats.prettyName(format)));
2026 loader_format = format;
2028 if (loader_format == "lyx") {
2029 Buffer * buf = lv->loadDocument(lyxfile);
2033 Buffer * const b = newFile(lyxfile.absFileName(), string(), true);
2037 bool as_paragraphs = loader_format == "textparagraph";
2038 string filename2 = (loader_format == format) ? filename.absFileName()
2039 : support::changeExtension(filename.absFileName(),
2040 formats.extension(loader_format));
2041 lv->currentBufferView()->insertPlaintextFile(FileName(filename2),
2043 guiApp->setCurrentView(lv);
2044 lyx::dispatch(FuncRequest(LFUN_MARK_OFF));
2051 void GuiView::importDocument(string const & argument)
2054 string filename = split(argument, format, ' ');
2056 LYXERR(Debug::INFO, format << " file: " << filename);
2058 // need user interaction
2059 if (filename.empty()) {
2060 string initpath = lyxrc.document_path;
2061 if (documentBufferView()) {
2062 string const trypath = documentBufferView()->buffer().filePath();
2063 // If directory is writeable, use this as default.
2064 if (FileName(trypath).isDirWritable())
2068 docstring const text = bformat(_("Select %1$s file to import"),
2069 formats.prettyName(format));
2071 FileDialog dlg(toqstr(text), LFUN_BUFFER_IMPORT);
2072 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2073 dlg.setButton2(qt_("Examples|#E#e"),
2074 toqstr(addPath(package().system_support().absFileName(), "examples")));
2076 docstring filter = formats.prettyName(format);
2079 filter += from_utf8(formats.extension(format));
2082 FileDialog::Result result =
2083 dlg.open(toqstr(initpath), fileFilters(toqstr(filter)));
2085 if (result.first == FileDialog::Later)
2088 filename = fromqstr(result.second);
2090 // check selected filename
2091 if (filename.empty())
2092 message(_("Canceled."));
2095 if (filename.empty())
2098 // get absolute path of file
2099 FileName const fullname(support::makeAbsPath(filename));
2101 FileName const lyxfile(support::changeExtension(fullname.absFileName(), ".lyx"));
2103 // Check if the document already is open
2104 Buffer * buf = theBufferList().getBuffer(lyxfile);
2107 if (!closeBuffer()) {
2108 message(_("Canceled."));
2113 docstring const displaypath = makeDisplayPath(lyxfile.absFileName(), 30);
2115 // if the file exists already, and we didn't do
2116 // -i lyx thefile.lyx, warn
2117 if (lyxfile.exists() && fullname != lyxfile) {
2119 docstring text = bformat(_("The document %1$s already exists.\n\n"
2120 "Do you want to overwrite that document?"), displaypath);
2121 int const ret = Alert::prompt(_("Overwrite document?"),
2122 text, 0, 1, _("&Overwrite"), _("&Cancel"));
2125 message(_("Canceled."));
2130 message(bformat(_("Importing %1$s..."), displaypath));
2131 ErrorList errorList;
2132 if (import(this, fullname, format, errorList))
2133 message(_("imported."));
2135 message(_("file not imported!"));
2137 // FIXME (Abdel 12/08/06): Is there a need to display the error list here?
2141 void GuiView::newDocument(string const & filename, bool from_template)
2143 FileName initpath(lyxrc.document_path);
2144 if (documentBufferView()) {
2145 FileName const trypath(documentBufferView()->buffer().filePath());
2146 // If directory is writeable, use this as default.
2147 if (trypath.isDirWritable())
2151 string templatefile;
2152 if (from_template) {
2153 templatefile = selectTemplateFile().absFileName();
2154 if (templatefile.empty())
2159 if (filename.empty())
2160 b = newUnnamedFile(initpath, to_utf8(_("newfile")), templatefile);
2162 b = newFile(filename, templatefile, true);
2167 // If no new document could be created, it is unsure
2168 // whether there is a valid BufferView.
2169 if (currentBufferView())
2170 // Ensure the cursor is correctly positioned on screen.
2171 currentBufferView()->showCursor();
2175 void GuiView::insertLyXFile(docstring const & fname)
2177 BufferView * bv = documentBufferView();
2182 FileName filename(to_utf8(fname));
2183 if (filename.empty()) {
2184 // Launch a file browser
2186 string initpath = lyxrc.document_path;
2187 string const trypath = bv->buffer().filePath();
2188 // If directory is writeable, use this as default.
2189 if (FileName(trypath).isDirWritable())
2193 FileDialog dlg(qt_("Select LyX document to insert"), LFUN_FILE_INSERT);
2194 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2195 dlg.setButton2(qt_("Examples|#E#e"),
2196 toqstr(addPath(package().system_support().absFileName(),
2199 FileDialog::Result result = dlg.open(toqstr(initpath),
2200 QStringList(qt_("LyX Documents (*.lyx)")));
2202 if (result.first == FileDialog::Later)
2206 filename.set(fromqstr(result.second));
2208 // check selected filename
2209 if (filename.empty()) {
2210 // emit message signal.
2211 message(_("Canceled."));
2216 bv->insertLyXFile(filename);
2217 bv->buffer().errors("Parse");
2221 void GuiView::insertPlaintextFile(docstring const & fname,
2224 BufferView * bv = documentBufferView();
2228 if (!fname.empty() && !FileName::isAbsolute(to_utf8(fname))) {
2229 message(_("Absolute filename expected."));
2234 FileName filename(to_utf8(fname));
2236 if (!filename.empty()) {
2237 bv->insertPlaintextFile(filename, asParagraph);
2241 FileDialog dlg(qt_("Select file to insert"), (asParagraph ?
2242 LFUN_FILE_INSERT_PLAINTEXT_PARA : LFUN_FILE_INSERT_PLAINTEXT));
2244 FileDialog::Result result = dlg.open(toqstr(bv->buffer().filePath()),
2245 QStringList(qt_("All Files (*)")));
2247 if (result.first == FileDialog::Later)
2251 filename.set(fromqstr(result.second));
2253 // check selected filename
2254 if (filename.empty()) {
2255 // emit message signal.
2256 message(_("Canceled."));
2260 bv->insertPlaintextFile(filename, asParagraph);
2264 bool GuiView::renameBuffer(Buffer & b, docstring const & newname)
2266 FileName fname = b.fileName();
2267 FileName const oldname = fname;
2269 if (!newname.empty()) {
2271 fname = support::makeAbsPath(to_utf8(newname), oldname.onlyPath().absFileName());
2273 // Switch to this Buffer.
2276 // No argument? Ask user through dialog.
2278 FileDialog dlg(qt_("Choose a filename to save document as"),
2279 LFUN_BUFFER_WRITE_AS);
2280 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2281 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
2283 if (!isLyXFileName(fname.absFileName()))
2284 fname.changeExtension(".lyx");
2286 FileDialog::Result result =
2287 dlg.save(toqstr(fname.onlyPath().absFileName()),
2288 QStringList(qt_("LyX Documents (*.lyx)")),
2289 toqstr(fname.onlyFileName()));
2291 if (result.first == FileDialog::Later)
2294 fname.set(fromqstr(result.second));
2299 if (!isLyXFileName(fname.absFileName()))
2300 fname.changeExtension(".lyx");
2303 // fname is now the new Buffer location.
2304 if (FileName(fname).exists()) {
2305 docstring const file = makeDisplayPath(fname.absFileName(), 30);
2306 docstring text = bformat(_("The document %1$s already "
2307 "exists.\n\nDo you want to "
2308 "overwrite that document?"),
2310 int const ret = Alert::prompt(_("Overwrite document?"),
2311 text, 0, 2, _("&Overwrite"), _("&Rename"), _("&Cancel"));
2314 case 1: return renameBuffer(b, docstring());
2315 case 2: return false;
2319 return saveBuffer(b, fname);
2323 bool GuiView::saveBuffer(Buffer & b) {
2324 return saveBuffer(b, FileName());
2328 bool GuiView::saveBuffer(Buffer & b, FileName const & fn)
2330 if (workArea(b) && workArea(b)->inDialogMode())
2333 if (fn.empty() && b.isUnnamed())
2334 return renameBuffer(b, docstring());
2340 success = b.saveAs(fn);
2343 theSession().lastFiles().add(b.fileName());
2347 // Switch to this Buffer.
2350 // FIXME: we don't tell the user *WHY* the save failed !!
2351 docstring const file = makeDisplayPath(b.absFileName(), 30);
2352 docstring text = bformat(_("The document %1$s could not be saved.\n\n"
2353 "Do you want to rename the document and "
2354 "try again?"), file);
2355 int const ret = Alert::prompt(_("Rename and save?"),
2356 text, 0, 2, _("&Rename"), _("&Retry"), _("&Cancel"));
2359 if (!renameBuffer(b, docstring()))
2368 return saveBuffer(b);
2372 bool GuiView::hideWorkArea(GuiWorkArea * wa)
2374 return closeWorkArea(wa, false);
2378 bool GuiView::closeWorkArea(GuiWorkArea * wa)
2380 Buffer & buf = wa->bufferView().buffer();
2381 return closeWorkArea(wa, !buf.parent());
2385 bool GuiView::closeBuffer()
2387 GuiWorkArea * wa = currentMainWorkArea();
2388 setCurrentWorkArea(wa);
2389 Buffer & buf = wa->bufferView().buffer();
2390 return wa && closeWorkArea(wa, !buf.parent());
2394 void GuiView::writeSession() const {
2395 GuiWorkArea const * active_wa = currentMainWorkArea();
2396 for (int i = 0; i < d.splitter_->count(); ++i) {
2397 TabWorkArea * twa = d.tabWorkArea(i);
2398 for (int j = 0; j < twa->count(); ++j) {
2399 GuiWorkArea * wa = static_cast<GuiWorkArea *>(twa->widget(j));
2400 Buffer & buf = wa->bufferView().buffer();
2401 theSession().lastOpened().add(buf.fileName(), wa == active_wa);
2407 bool GuiView::closeBufferAll()
2409 // Close the workareas in all other views
2410 QList<int> const ids = guiApp->viewIds();
2411 for (int i = 0; i != ids.size(); ++i) {
2412 if (id_ != ids[i] && !guiApp->view(ids[i]).closeWorkAreaAll())
2416 // Close our own workareas
2417 if (!closeWorkAreaAll())
2420 // Now close the hidden buffers. We prevent hidden buffers from being
2421 // dirty, so we can just close them.
2422 theBufferList().closeAll();
2427 bool GuiView::closeWorkAreaAll()
2429 setCurrentWorkArea(currentMainWorkArea());
2431 // We might be in a situation that there is still a tabWorkArea, but
2432 // there are no tabs anymore. This can happen when we get here after a
2433 // TabWorkArea::lastWorkAreaRemoved() signal. Therefore we count how
2434 // many TabWorkArea's have no documents anymore.
2437 // We have to call count() each time, because it can happen that
2438 // more than one splitter will disappear in one iteration (bug 5998).
2439 for (; d.splitter_->count() > empty_twa; ) {
2440 TabWorkArea * twa = d.tabWorkArea(empty_twa);
2442 if (twa->count() == 0)
2445 setCurrentWorkArea(twa->currentWorkArea());
2446 if (!closeTabWorkArea(twa))
2454 bool GuiView::closeWorkArea(GuiWorkArea * wa, bool close_buffer)
2459 Buffer & buf = wa->bufferView().buffer();
2461 if (close_buffer && GuiViewPrivate::busyBuffers.contains(&buf)) {
2462 Alert::warning(_("Close document"),
2463 _("Document could not be closed because it is being processed by LyX."));
2468 return closeBuffer(buf);
2470 if (!inMultiTabs(wa))
2471 if (!saveBufferIfNeeded(buf, true))
2479 bool GuiView::closeBuffer(Buffer & buf)
2481 // If we are in a close_event all children will be closed in some time,
2482 // so no need to do it here. This will ensure that the children end up
2483 // in the session file in the correct order. If we close the master
2484 // buffer, we can close or release the child buffers here too.
2485 bool success = true;
2487 ListOfBuffers clist = buf.getChildren();
2488 ListOfBuffers::const_iterator it = clist.begin();
2489 ListOfBuffers::const_iterator const bend = clist.end();
2490 for (; it != bend; ++it) {
2491 // If a child is dirty, do not close
2492 // without user intervention
2493 //FIXME: should we look in other tabworkareas?
2494 Buffer * child_buf = *it;
2495 GuiWorkArea * child_wa = workArea(*child_buf);
2497 if (!closeWorkArea(child_wa, true)) {
2502 theBufferList().releaseChild(&buf, child_buf);
2506 // goto bookmark to update bookmark pit.
2507 //FIXME: we should update only the bookmarks related to this buffer!
2508 LYXERR(Debug::DEBUG, "GuiView::closeBuffer()");
2509 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
2510 guiApp->gotoBookmark(i+1, false, false);
2512 if (saveBufferIfNeeded(buf, false)) {
2513 buf.removeAutosaveFile();
2514 theBufferList().release(&buf);
2518 // open all children again to avoid a crash because of dangling
2519 // pointers (bug 6603)
2525 bool GuiView::closeTabWorkArea(TabWorkArea * twa)
2527 while (twa == d.currentTabWorkArea()) {
2528 twa->setCurrentIndex(twa->count()-1);
2530 GuiWorkArea * wa = twa->currentWorkArea();
2531 Buffer & b = wa->bufferView().buffer();
2533 // We only want to close the buffer if the same buffer is not visible
2534 // in another view, and if this is not a child and if we are closing
2535 // a view (not a tabgroup).
2536 bool const close_buffer =
2537 !inOtherView(b) && !b.parent() && closing_;
2539 if (!closeWorkArea(wa, close_buffer))
2546 bool GuiView::saveBufferIfNeeded(Buffer & buf, bool hiding)
2548 if (buf.isClean() || buf.paragraphs().empty())
2551 // Switch to this Buffer.
2556 if (buf.isUnnamed())
2557 file = from_utf8(buf.fileName().onlyFileName());
2559 file = buf.fileName().displayName(30);
2561 // Bring this window to top before asking questions.
2566 if (hiding && buf.isUnnamed()) {
2567 docstring const text = bformat(_("The document %1$s has not been "
2568 "saved yet.\n\nDo you want to save "
2569 "the document?"), file);
2570 ret = Alert::prompt(_("Save new document?"),
2571 text, 0, 1, _("&Save"), _("&Cancel"));
2575 docstring const text = bformat(_("The document %1$s has unsaved changes."
2576 "\n\nDo you want to save the document or discard the changes?"), file);
2577 ret = Alert::prompt(_("Save changed document?"),
2578 text, 0, 2, _("&Save"), _("&Discard"), _("&Cancel"));
2583 if (!saveBuffer(buf))
2587 // If we crash after this we could have no autosave file
2588 // but I guess this is really improbable (Jug).
2589 // Sometimes improbable things happen:
2590 // - see bug http://www.lyx.org/trac/ticket/6587 (ps)
2591 // buf.removeAutosaveFile();
2593 // revert all changes
2604 bool GuiView::inMultiTabs(GuiWorkArea * wa)
2606 Buffer & buf = wa->bufferView().buffer();
2608 for (int i = 0; i != d.splitter_->count(); ++i) {
2609 GuiWorkArea * wa_ = d.tabWorkArea(i)->workArea(buf);
2610 if (wa_ && wa_ != wa)
2613 return inOtherView(buf);
2617 bool GuiView::inOtherView(Buffer & buf)
2619 QList<int> const ids = guiApp->viewIds();
2621 for (int i = 0; i != ids.size(); ++i) {
2625 if (guiApp->view(ids[i]).workArea(buf))
2632 void GuiView::gotoNextOrPreviousBuffer(NextOrPrevious np)
2634 if (!documentBufferView())
2637 if (TabWorkArea * twa = d.currentTabWorkArea()) {
2638 Buffer * const curbuf = &documentBufferView()->buffer();
2639 int nwa = twa->count();
2640 for (int i = 0; i < nwa; ++i) {
2641 if (&workArea(i)->bufferView().buffer() == curbuf) {
2643 if (np == NEXTBUFFER)
2644 next_index = (i == nwa - 1 ? 0 : i + 1);
2646 next_index = (i == 0 ? nwa - 1 : i - 1);
2647 setBuffer(&workArea(next_index)->bufferView().buffer());
2655 /// make sure the document is saved
2656 static bool ensureBufferClean(Buffer * buffer)
2658 LASSERT(buffer, return false);
2659 if (buffer->isClean() && !buffer->isUnnamed())
2662 docstring const file = buffer->fileName().displayName(30);
2665 if (!buffer->isUnnamed()) {
2666 text = bformat(_("The document %1$s has unsaved "
2667 "changes.\n\nDo you want to save "
2668 "the document?"), file);
2669 title = _("Save changed document?");
2672 text = bformat(_("The document %1$s has not been "
2673 "saved yet.\n\nDo you want to save "
2674 "the document?"), file);
2675 title = _("Save new document?");
2677 int const ret = Alert::prompt(title, text, 0, 1, _("&Save"), _("&Cancel"));
2680 dispatch(FuncRequest(LFUN_BUFFER_WRITE));
2682 return buffer->isClean() && !buffer->isUnnamed();
2686 bool GuiView::reloadBuffer(Buffer & buf)
2688 Buffer::ReadStatus status = buf.reload();
2689 return status == Buffer::ReadSuccess;
2693 void GuiView::checkExternallyModifiedBuffers()
2695 BufferList::iterator bit = theBufferList().begin();
2696 BufferList::iterator const bend = theBufferList().end();
2697 for (; bit != bend; ++bit) {
2698 Buffer * buf = *bit;
2699 if (buf->fileName().exists()
2700 && buf->isExternallyModified(Buffer::checksum_method)) {
2701 docstring text = bformat(_("Document \n%1$s\n has been externally modified."
2702 " Reload now? Any local changes will be lost."),
2703 from_utf8(buf->absFileName()));
2704 int const ret = Alert::prompt(_("Reload externally changed document?"),
2705 text, 0, 1, _("&Reload"), _("&Cancel"));
2713 void GuiView::dispatchVC(FuncRequest const & cmd, DispatchResult & dr)
2715 Buffer * buffer = documentBufferView()
2716 ? &(documentBufferView()->buffer()) : 0;
2718 switch (cmd.action()) {
2719 case LFUN_VC_REGISTER:
2720 if (!buffer || !ensureBufferClean(buffer))
2722 if (!buffer->lyxvc().inUse()) {
2723 if (buffer->lyxvc().registrer()) {
2724 reloadBuffer(*buffer);
2725 dr.suppressMessageUpdate();
2730 case LFUN_VC_CHECK_IN:
2731 if (!buffer || !ensureBufferClean(buffer))
2733 if (buffer->lyxvc().inUse() && !buffer->isReadonly()) {
2734 dr.setMessage(buffer->lyxvc().checkIn());
2735 if (!dr.message().empty())
2736 reloadBuffer(*buffer);
2740 case LFUN_VC_CHECK_OUT:
2741 if (!buffer || !ensureBufferClean(buffer))
2743 if (buffer->lyxvc().inUse()) {
2744 dr.setMessage(buffer->lyxvc().checkOut());
2745 reloadBuffer(*buffer);
2749 case LFUN_VC_LOCKING_TOGGLE:
2750 LASSERT(buffer, return);
2751 if (!ensureBufferClean(buffer) || buffer->isReadonly())
2753 if (buffer->lyxvc().inUse()) {
2754 string res = buffer->lyxvc().lockingToggle();
2756 frontend::Alert::error(_("Revision control error."),
2757 _("Error when setting the locking property."));
2760 reloadBuffer(*buffer);
2765 case LFUN_VC_REVERT:
2766 LASSERT(buffer, return);
2767 if (buffer->lyxvc().revert()) {
2768 reloadBuffer(*buffer);
2769 dr.suppressMessageUpdate();
2773 case LFUN_VC_UNDO_LAST:
2774 LASSERT(buffer, return);
2775 buffer->lyxvc().undoLast();
2776 reloadBuffer(*buffer);
2777 dr.suppressMessageUpdate();
2780 case LFUN_VC_REPO_UPDATE:
2781 LASSERT(buffer, return);
2782 if (ensureBufferClean(buffer)) {
2783 dr.setMessage(buffer->lyxvc().repoUpdate());
2784 checkExternallyModifiedBuffers();
2788 case LFUN_VC_COMMAND: {
2789 string flag = cmd.getArg(0);
2790 if (buffer && contains(flag, 'R') && !ensureBufferClean(buffer))
2793 if (contains(flag, 'M')) {
2794 if (!Alert::askForText(message, _("LyX VC: Log Message")))
2797 string path = cmd.getArg(1);
2798 if (contains(path, "$$p") && buffer)
2799 path = subst(path, "$$p", buffer->filePath());
2800 LYXERR(Debug::LYXVC, "Directory: " << path);
2802 if (!pp.isReadableDirectory()) {
2803 lyxerr << _("Directory is not accessible.") << endl;
2806 support::PathChanger p(pp);
2808 string command = cmd.getArg(2);
2809 if (command.empty())
2812 command = subst(command, "$$i", buffer->absFileName());
2813 command = subst(command, "$$p", buffer->filePath());
2815 command = subst(command, "$$m", to_utf8(message));
2816 LYXERR(Debug::LYXVC, "Command: " << command);
2818 one.startscript(Systemcall::Wait, command);
2822 if (contains(flag, 'I'))
2823 buffer->markDirty();
2824 if (contains(flag, 'R'))
2825 reloadBuffer(*buffer);
2830 case LFUN_VC_COMPARE: {
2832 if (cmd.argument().empty()) {
2833 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "comparehistory"));
2837 string rev1 = cmd.getArg(0);
2841 if (!buffer->lyxvc().prepareFileRevision(rev1, f1))
2844 if (isStrInt(rev1) && convert<int>(rev1) <= 0) {
2845 f2 = buffer->absFileName();
2847 string rev2 = cmd.getArg(1);
2851 if (!buffer->lyxvc().prepareFileRevision(rev2, f2))
2855 LYXERR(Debug::LYXVC, "Launching comparison for fetched revisions:\n" <<
2856 f1 << "\n" << f2 << "\n" );
2857 string par = "compare run " + quoteName(f1) + " " + quoteName(f2);
2858 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, par));
2868 void GuiView::openChildDocument(string const & fname)
2870 LASSERT(documentBufferView(), return);
2871 Buffer & buffer = documentBufferView()->buffer();
2872 FileName const filename = support::makeAbsPath(fname, buffer.filePath());
2873 documentBufferView()->saveBookmark(false);
2875 if (theBufferList().exists(filename)) {
2876 child = theBufferList().getBuffer(filename);
2879 message(bformat(_("Opening child document %1$s..."),
2880 makeDisplayPath(filename.absFileName())));
2881 child = loadDocument(filename, false);
2883 // Set the parent name of the child document.
2884 // This makes insertion of citations and references in the child work,
2885 // when the target is in the parent or another child document.
2887 child->setParent(&buffer);
2891 bool GuiView::goToFileRow(string const & argument)
2895 size_t i = argument.find_last_of(' ');
2896 if (i != string::npos) {
2897 file_name = os::internal_path(trim(argument.substr(0, i)));
2898 istringstream is(argument.substr(i + 1));
2903 if (i == string::npos) {
2904 LYXERR0("Wrong argument: " << argument);
2908 string const abstmp = package().temp_dir().absFileName();
2909 string const realtmp = package().temp_dir().realPath();
2910 // We have to use os::path_prefix_is() here, instead of
2911 // simply prefixIs(), because the file name comes from
2912 // an external application and may need case adjustment.
2913 if (os::path_prefix_is(file_name, abstmp, os::CASE_ADJUSTED)
2914 || os::path_prefix_is(file_name, realtmp, os::CASE_ADJUSTED)) {
2915 // Needed by inverse dvi search. If it is a file
2916 // in tmpdir, call the apropriated function.
2917 // If tmpdir is a symlink, we may have the real
2918 // path passed back, so we correct for that.
2919 if (!prefixIs(file_name, abstmp))
2920 file_name = subst(file_name, realtmp, abstmp);
2921 buf = theBufferList().getBufferFromTmp(file_name);
2923 // Must replace extension of the file to be .lyx
2924 // and get full path
2925 FileName const s = fileSearch(string(),
2926 support::changeExtension(file_name, ".lyx"), "lyx");
2927 // Either change buffer or load the file
2928 if (theBufferList().exists(s))
2929 buf = theBufferList().getBuffer(s);
2930 else if (s.exists()) {
2931 buf = loadDocument(s);
2936 _("File does not exist: %1$s"),
2937 makeDisplayPath(file_name)));
2942 documentBufferView()->setCursorFromRow(row);
2947 #if (QT_VERSION >= 0x040400)
2949 docstring GuiView::GuiViewPrivate::runAndDestroy(const T& func, Buffer const * orig, Buffer * buffer, string const & format, string const & msg)
2951 bool const update_unincluded =
2952 buffer->params().maintain_unincluded_children
2953 && !buffer->params().getIncludedChildren().empty();
2954 bool const success = func(format, update_unincluded);
2956 busyBuffers.remove(orig);
2957 if (msg == "preview") {
2959 ? bformat(_("Successful preview of format: %1$s"), from_utf8(format))
2960 : bformat(_("Error while previewing format: %1$s"), from_utf8(format));
2963 ? bformat(_("Successful export to format: %1$s"), from_utf8(format))
2964 : bformat(_("Error while exporting format: %1$s"), from_utf8(format));
2968 docstring GuiView::GuiViewPrivate::compileAndDestroy(Buffer const * orig, Buffer * buffer, string const & format)
2970 bool (Buffer::* mem_func)(std::string const &, bool, bool) const = &Buffer::doExport;
2971 return runAndDestroy(bind(mem_func, buffer, _1, true, _2), orig, buffer, format, "export");
2975 docstring GuiView::GuiViewPrivate::exportAndDestroy(Buffer const * orig, Buffer * buffer, string const & format)
2977 bool (Buffer::* mem_func)(std::string const &, bool, bool) const = &Buffer::doExport;
2978 return runAndDestroy(bind(mem_func, buffer, _1, false, _2), orig, buffer, format, "export");
2982 docstring GuiView::GuiViewPrivate::previewAndDestroy(Buffer const * orig, Buffer * buffer, string const & format)
2984 bool(Buffer::* mem_func)(std::string const &, bool) const = &Buffer::preview;
2985 return runAndDestroy(bind(mem_func, buffer, _1, _2), orig, buffer, format, "preview");
2990 // not used, but the linker needs them
2992 docstring GuiView::GuiViewPrivate::compileAndDestroy(
2993 Buffer const *, Buffer *, string const &)
2999 docstring GuiView::GuiViewPrivate::exportAndDestroy(
3000 Buffer const *, Buffer *, string const &)
3006 docstring GuiView::GuiViewPrivate::previewAndDestroy(
3007 Buffer const *, Buffer *, string const &)
3015 bool GuiView::GuiViewPrivate::asyncBufferProcessing(
3016 string const & argument,
3017 Buffer const * used_buffer,
3018 docstring const & msg,
3019 docstring (*asyncFunc)(Buffer const *, Buffer *, string const &),
3020 bool (Buffer::*syncFunc)(string const &, bool, bool) const,
3021 bool (Buffer::*previewFunc)(string const &, bool) const)
3026 string format = argument;
3028 format = used_buffer->getDefaultOutputFormat();
3030 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
3031 gv_->processingThreadStarted();
3033 progress_->clearMessages();
3036 GuiViewPrivate::busyBuffers.insert(used_buffer);
3037 QFuture<docstring> f = QtConcurrent::run(
3040 used_buffer->clone(),
3042 setPreviewFuture(f);
3043 last_export_format = used_buffer->bufferFormat();
3046 // We are asynchronous, so we don't know here anything about the success
3050 // TODO check here if it breaks exporting with Qt < 4.4
3051 bool const update_unincluded =
3052 used_buffer->params().maintain_unincluded_children &&
3053 !used_buffer->params().getIncludedChildren().empty();
3054 return (used_buffer->*syncFunc)(format, true, update_unincluded);
3055 } else if (previewFunc) {
3056 return (used_buffer->*previewFunc)(format, false);
3063 void GuiView::dispatchToBufferView(FuncRequest const & cmd, DispatchResult & dr)
3065 BufferView * bv = currentBufferView();
3068 // Let the current BufferView dispatch its own actions.
3069 bv->dispatch(cmd, dr);
3070 if (dr.dispatched())
3073 // Try with the document BufferView dispatch if any.
3074 BufferView * doc_bv = documentBufferView();
3076 doc_bv->dispatch(cmd, dr);
3077 if (dr.dispatched())
3081 // Then let the current Cursor dispatch its own actions.
3082 bv->cursor().dispatch(cmd);
3084 // update completion. We do it here and not in
3085 // processKeySym to avoid another redraw just for a
3086 // changed inline completion
3087 if (cmd.origin() == FuncRequest::KEYBOARD) {
3088 if (cmd.action() == LFUN_SELF_INSERT
3089 || (cmd.action() == LFUN_ERT_INSERT && bv->cursor().inMathed()))
3090 updateCompletion(bv->cursor(), true, true);
3091 else if (cmd.action() == LFUN_CHAR_DELETE_BACKWARD)
3092 updateCompletion(bv->cursor(), false, true);
3094 updateCompletion(bv->cursor(), false, false);
3097 dr = bv->cursor().result();
3101 void GuiView::dispatch(FuncRequest const & cmd, DispatchResult & dr)
3103 BufferView * bv = currentBufferView();
3104 // By default we won't need any update.
3105 dr.screenUpdate(Update::None);
3106 // assume cmd will be dispatched
3107 dr.dispatched(true);
3109 Buffer * doc_buffer = documentBufferView()
3110 ? &(documentBufferView()->buffer()) : 0;
3112 if (cmd.origin() == FuncRequest::TOC) {
3113 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
3114 // FIXME: do we need to pass a DispatchResult object here?
3115 toc->doDispatch(bv->cursor(), cmd);
3119 string const argument = to_utf8(cmd.argument());
3121 switch(cmd.action()) {
3122 case LFUN_BUFFER_CHILD_OPEN:
3123 openChildDocument(to_utf8(cmd.argument()));
3126 case LFUN_BUFFER_IMPORT:
3127 importDocument(to_utf8(cmd.argument()));
3130 case LFUN_BUFFER_EXPORT: {
3133 // GCC only sees strfwd.h when building merged
3134 if (::lyx::operator==(cmd.argument(), "custom")) {
3135 dispatch(FuncRequest(LFUN_DIALOG_SHOW, "sendto"), dr);
3138 #if QT_VERSION < 0x040400
3139 if (!doc_buffer->doExport(argument, false)) {
3141 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
3145 /* TODO/Review: Is it a problem to also export the children?
3146 See the update_unincluded flag */
3147 d.asyncBufferProcessing(argument,
3150 &GuiViewPrivate::exportAndDestroy,
3153 // TODO Inform user about success
3158 case LFUN_BUFFER_UPDATE: {
3159 d.asyncBufferProcessing(argument,
3162 &GuiViewPrivate::compileAndDestroy,
3167 case LFUN_BUFFER_VIEW: {
3168 d.asyncBufferProcessing(argument,
3170 _("Previewing ..."),
3171 &GuiViewPrivate::previewAndDestroy,
3176 case LFUN_MASTER_BUFFER_UPDATE: {
3177 d.asyncBufferProcessing(argument,
3178 (doc_buffer ? doc_buffer->masterBuffer() : 0),
3180 &GuiViewPrivate::compileAndDestroy,
3185 case LFUN_MASTER_BUFFER_VIEW: {
3186 d.asyncBufferProcessing(argument,
3187 (doc_buffer ? doc_buffer->masterBuffer() : 0),
3189 &GuiViewPrivate::previewAndDestroy,
3190 0, &Buffer::preview);
3193 case LFUN_BUFFER_SWITCH: {
3194 string const file_name = to_utf8(cmd.argument());
3195 if (!FileName::isAbsolute(file_name)) {
3197 dr.setMessage(_("Absolute filename expected."));
3201 Buffer * buffer = theBufferList().getBuffer(FileName(file_name));
3204 dr.setMessage(_("Document not loaded"));
3208 // Do we open or switch to the buffer in this view ?
3209 if (workArea(*buffer)
3210 || lyxrc.open_buffers_in_tabs || !documentBufferView()) {
3215 // Look for the buffer in other views
3216 QList<int> const ids = guiApp->viewIds();
3218 for (; i != ids.size(); ++i) {
3219 GuiView & gv = guiApp->view(ids[i]);
3220 if (gv.workArea(*buffer)) {
3221 gv.activateWindow();
3222 gv.setBuffer(buffer);
3227 // If necessary, open a new window as a last resort
3228 if (i == ids.size()) {
3229 lyx::dispatch(FuncRequest(LFUN_WINDOW_NEW));
3235 case LFUN_BUFFER_NEXT:
3236 gotoNextOrPreviousBuffer(NEXTBUFFER);
3239 case LFUN_BUFFER_PREVIOUS:
3240 gotoNextOrPreviousBuffer(PREVBUFFER);
3243 case LFUN_COMMAND_EXECUTE: {
3244 bool const show_it = cmd.argument() != "off";
3245 // FIXME: this is a hack, "minibuffer" should not be
3247 if (GuiToolbar * t = toolbar("minibuffer")) {
3248 t->setVisible(show_it);
3249 if (show_it && t->commandBuffer())
3250 t->commandBuffer()->setFocus();
3254 case LFUN_DROP_LAYOUTS_CHOICE:
3255 d.layout_->showPopup();
3258 case LFUN_MENU_OPEN:
3259 if (QMenu * menu = guiApp->menus().menu(toqstr(cmd.argument()), *this))
3260 menu->exec(QCursor::pos());
3263 case LFUN_FILE_INSERT:
3264 insertLyXFile(cmd.argument());
3267 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
3268 insertPlaintextFile(cmd.argument(), true);
3271 case LFUN_FILE_INSERT_PLAINTEXT:
3272 insertPlaintextFile(cmd.argument(), false);
3275 case LFUN_BUFFER_RELOAD: {
3276 LASSERT(doc_buffer, break);
3279 if (!doc_buffer->isClean()) {
3280 docstring const file =
3281 makeDisplayPath(doc_buffer->absFileName(), 20);
3282 docstring text = bformat(_("Any changes will be lost. "
3283 "Are you sure you want to revert to the saved version "
3284 "of the document %1$s?"), file);
3285 ret = Alert::prompt(_("Revert to saved document?"),
3286 text, 1, 1, _("&Revert"), _("&Cancel"));
3290 doc_buffer->markClean();
3291 reloadBuffer(*doc_buffer);
3292 dr.forceBufferUpdate();
3297 case LFUN_BUFFER_WRITE:
3298 LASSERT(doc_buffer, break);
3299 saveBuffer(*doc_buffer);
3302 case LFUN_BUFFER_WRITE_AS:
3303 LASSERT(doc_buffer, break);
3304 renameBuffer(*doc_buffer, cmd.argument());
3307 case LFUN_BUFFER_WRITE_ALL: {
3308 Buffer * first = theBufferList().first();
3311 message(_("Saving all documents..."));
3312 // We cannot use a for loop as the buffer list cycles.
3315 if (!b->isClean()) {
3317 LYXERR(Debug::ACTION, "Saved " << b->absFileName());
3319 b = theBufferList().next(b);
3320 } while (b != first);
3321 dr.setMessage(_("All documents saved."));
3325 case LFUN_BUFFER_CLOSE:
3329 case LFUN_BUFFER_CLOSE_ALL:
3333 case LFUN_TOOLBAR_TOGGLE: {
3334 string const name = cmd.getArg(0);
3335 if (GuiToolbar * t = toolbar(name))
3340 case LFUN_DIALOG_UPDATE: {
3341 string const name = to_utf8(cmd.argument());
3342 if (name == "prefs" || name == "document")
3343 updateDialog(name, string());
3344 else if (name == "paragraph")
3345 lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
3346 else if (currentBufferView()) {
3347 Inset * inset = currentBufferView()->editedInset(name);
3348 // Can only update a dialog connected to an existing inset
3350 // FIXME: get rid of this indirection; GuiView ask the inset
3351 // if he is kind enough to update itself...
3352 FuncRequest fr(LFUN_INSET_DIALOG_UPDATE, cmd.argument());
3353 //FIXME: pass DispatchResult here?
3354 inset->dispatch(currentBufferView()->cursor(), fr);
3360 case LFUN_DIALOG_TOGGLE: {
3361 if (isDialogVisible(cmd.getArg(0)))
3362 dispatch(FuncRequest(LFUN_DIALOG_HIDE, cmd.argument()), dr);
3364 dispatch(FuncRequest(LFUN_DIALOG_SHOW, cmd.argument()), dr);
3368 case LFUN_DIALOG_DISCONNECT_INSET:
3369 disconnectDialog(to_utf8(cmd.argument()));
3372 case LFUN_DIALOG_HIDE: {
3373 guiApp->hideDialogs(to_utf8(cmd.argument()), 0);
3377 case LFUN_DIALOG_SHOW: {
3378 string const name = cmd.getArg(0);
3379 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
3381 if (name == "character") {
3382 data = freefont2string();
3384 showDialog("character", data);
3385 } else if (name == "latexlog") {
3386 Buffer::LogType type;
3387 string const logfile = doc_buffer->logName(&type);
3389 case Buffer::latexlog:
3392 case Buffer::buildlog:
3396 data += Lexer::quoteString(logfile);
3397 showDialog("log", data);
3398 } else if (name == "vclog") {
3399 string const data = "vc " +
3400 Lexer::quoteString(doc_buffer->lyxvc().getLogFile());
3401 showDialog("log", data);
3402 } else if (name == "symbols") {
3403 data = bv->cursor().getEncoding()->name();
3405 showDialog("symbols", data);
3407 } else if (name == "prefs" && isFullScreen()) {
3408 lfunUiToggle("fullscreen");
3409 showDialog("prefs", data);
3411 showDialog(name, data);
3416 dr.setMessage(cmd.argument());
3419 case LFUN_UI_TOGGLE: {
3420 string arg = cmd.getArg(0);
3421 if (!lfunUiToggle(arg)) {
3422 docstring const msg = "ui-toggle " + _("%1$s unknown command!");
3423 dr.setMessage(bformat(msg, from_utf8(arg)));
3425 // Make sure the keyboard focus stays in the work area.
3430 case LFUN_SPLIT_VIEW: {
3431 LASSERT(doc_buffer, break);
3432 string const orientation = cmd.getArg(0);
3433 d.splitter_->setOrientation(orientation == "vertical"
3434 ? Qt::Vertical : Qt::Horizontal);
3435 TabWorkArea * twa = addTabWorkArea();
3436 GuiWorkArea * wa = twa->addWorkArea(*doc_buffer, *this);
3437 setCurrentWorkArea(wa);
3440 case LFUN_CLOSE_TAB_GROUP:
3441 if (TabWorkArea * twa = d.currentTabWorkArea()) {
3442 closeTabWorkArea(twa);
3443 d.current_work_area_ = 0;
3444 twa = d.currentTabWorkArea();
3445 // Switch to the next GuiWorkArea in the found TabWorkArea.
3447 // Make sure the work area is up to date.
3448 setCurrentWorkArea(twa->currentWorkArea());
3450 setCurrentWorkArea(0);
3455 case LFUN_COMPLETION_INLINE:
3456 if (d.current_work_area_)
3457 d.current_work_area_->completer().showInline();
3460 case LFUN_COMPLETION_POPUP:
3461 if (d.current_work_area_)
3462 d.current_work_area_->completer().showPopup();
3466 case LFUN_COMPLETION_COMPLETE:
3467 if (d.current_work_area_)
3468 d.current_work_area_->completer().tab();
3471 case LFUN_COMPLETION_CANCEL:
3472 if (d.current_work_area_) {
3473 if (d.current_work_area_->completer().popupVisible())
3474 d.current_work_area_->completer().hidePopup();
3476 d.current_work_area_->completer().hideInline();
3480 case LFUN_COMPLETION_ACCEPT:
3481 if (d.current_work_area_)
3482 d.current_work_area_->completer().activate();
3485 case LFUN_BUFFER_ZOOM_IN:
3486 case LFUN_BUFFER_ZOOM_OUT:
3487 if (cmd.argument().empty()) {
3488 if (cmd.action() == LFUN_BUFFER_ZOOM_IN)
3493 lyxrc.zoom += convert<int>(cmd.argument());
3495 if (lyxrc.zoom < 10)
3498 // The global QPixmapCache is used in GuiPainter to cache text
3499 // painting so we must reset it.
3500 QPixmapCache::clear();
3501 guiApp->fontLoader().update();
3502 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
3505 case LFUN_VC_REGISTER:
3506 case LFUN_VC_CHECK_IN:
3507 case LFUN_VC_CHECK_OUT:
3508 case LFUN_VC_REPO_UPDATE:
3509 case LFUN_VC_LOCKING_TOGGLE:
3510 case LFUN_VC_REVERT:
3511 case LFUN_VC_UNDO_LAST:
3512 case LFUN_VC_COMMAND:
3513 case LFUN_VC_COMPARE:
3514 dispatchVC(cmd, dr);
3517 case LFUN_SERVER_GOTO_FILE_ROW:
3518 goToFileRow(to_utf8(cmd.argument()));
3521 case LFUN_FORWARD_SEARCH: {
3522 FileName const path(doc_buffer->temppath());
3523 string const texname = doc_buffer->latexName();
3524 FileName const dviname(addName(path.absFileName(),
3525 support::changeExtension(texname, "dvi")));
3526 FileName const pdfname(addName(path.absFileName(),
3527 support::changeExtension(texname, "pdf")));
3528 if (!dviname.exists() && !pdfname.exists()) {
3529 dr.setMessage(_("Please, preview the document first."));
3532 string outname = dviname.onlyFileName();
3533 string command = lyxrc.forward_search_dvi;
3534 if (!dviname.exists() ||
3535 pdfname.lastModified() > dviname.lastModified()) {
3536 outname = pdfname.onlyFileName();
3537 command = lyxrc.forward_search_pdf;
3540 int row = doc_buffer->texrow().getRowFromIdPos(bv->cursor().paragraph().id(), bv->cursor().pos());
3541 LYXERR(Debug::ACTION, "Forward search: row:" << row
3542 << " id:" << bv->cursor().paragraph().id());
3543 if (!row || command.empty()) {
3544 dr.setMessage(_("Couldn't proceed."));
3547 string texrow = convert<string>(row);
3549 command = subst(command, "$$n", texrow);
3550 command = subst(command, "$$t", texname);
3551 command = subst(command, "$$o", outname);
3553 PathChanger p(path);
3555 one.startscript(Systemcall::DontWait, command);
3559 // The LFUN must be for one of BufferView, Buffer or Cursor;
3561 dispatchToBufferView(cmd, dr);
3565 // Part of automatic menu appearance feature.
3566 if (isFullScreen()) {
3567 if (menuBar()->isVisible() && lyxrc.full_screen_menubar)
3569 if (statusBar()->isVisible())
3570 statusBar()->hide();
3575 bool GuiView::lfunUiToggle(string const & ui_component)
3577 if (ui_component == "scrollbar") {
3578 // hide() is of no help
3579 if (d.current_work_area_->verticalScrollBarPolicy() ==
3580 Qt::ScrollBarAlwaysOff)
3582 d.current_work_area_->setVerticalScrollBarPolicy(
3583 Qt::ScrollBarAsNeeded);
3585 d.current_work_area_->setVerticalScrollBarPolicy(
3586 Qt::ScrollBarAlwaysOff);
3587 } else if (ui_component == "statusbar") {
3588 statusBar()->setVisible(!statusBar()->isVisible());
3589 } else if (ui_component == "menubar") {
3590 menuBar()->setVisible(!menuBar()->isVisible());
3592 #if QT_VERSION >= 0x040300
3593 if (ui_component == "frame") {
3595 getContentsMargins(&l, &t, &r, &b);
3596 //are the frames in default state?
3597 d.current_work_area_->setFrameStyle(QFrame::NoFrame);
3599 setContentsMargins(-2, -2, -2, -2);
3601 setContentsMargins(0, 0, 0, 0);
3605 if (ui_component == "fullscreen") {
3613 void GuiView::toggleFullScreen()
3615 if (isFullScreen()) {
3616 for (int i = 0; i != d.splitter_->count(); ++i)
3617 d.tabWorkArea(i)->setFullScreen(false);
3618 #if QT_VERSION >= 0x040300
3619 setContentsMargins(0, 0, 0, 0);
3621 setWindowState(windowState() ^ Qt::WindowFullScreen);
3624 statusBar()->show();
3627 hideDialogs("prefs", 0);
3628 for (int i = 0; i != d.splitter_->count(); ++i)
3629 d.tabWorkArea(i)->setFullScreen(true);
3630 #if QT_VERSION >= 0x040300
3631 setContentsMargins(-2, -2, -2, -2);
3634 setWindowState(windowState() ^ Qt::WindowFullScreen);
3635 statusBar()->hide();
3636 if (lyxrc.full_screen_menubar)
3638 if (lyxrc.full_screen_toolbars) {
3639 ToolbarMap::iterator end = d.toolbars_.end();
3640 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
3645 // give dialogs like the TOC a chance to adapt
3650 Buffer const * GuiView::updateInset(Inset const * inset)
3655 Buffer const * inset_buffer = &(inset->buffer());
3657 for (int i = 0; i != d.splitter_->count(); ++i) {
3658 GuiWorkArea * wa = d.tabWorkArea(i)->currentWorkArea();
3661 Buffer const * buffer = &(wa->bufferView().buffer());
3662 if (inset_buffer == buffer)
3663 wa->scheduleRedraw();
3665 return inset_buffer;
3669 void GuiView::restartCursor()
3671 /* When we move around, or type, it's nice to be able to see
3672 * the cursor immediately after the keypress.
3674 if (d.current_work_area_)
3675 d.current_work_area_->startBlinkingCursor();
3677 // Take this occasion to update the other GUI elements.
3683 void GuiView::updateCompletion(Cursor & cur, bool start, bool keep)
3685 if (d.current_work_area_)
3686 d.current_work_area_->completer().updateVisibility(cur, start, keep);
3691 // This list should be kept in sync with the list of insets in
3692 // src/insets/Inset.cpp. I.e., if a dialog goes with an inset, the
3693 // dialog should have the same name as the inset.
3694 // Changes should be also recorded in LFUN_DIALOG_SHOW doxygen
3695 // docs in LyXAction.cpp.
3697 char const * const dialognames[] = {
3699 "aboutlyx", "bibitem", "bibtex", "box", "branch", "changes", "character",
3700 "citation", "compare", "comparehistory", "document", "errorlist", "ert",
3701 "external", "file", "findreplace", "findreplaceadv", "float", "graphics",
3702 "href", "include", "index", "index_print", "info", "listings", "label", "line",
3703 "log", "mathdelimiter", "mathmatrix", "mathspace", "nomenclature",
3704 "nomencl_print", "note", "paragraph", "phantom", "prefs", "print", "ref",
3705 "sendto", "space", "spellchecker", "symbols", "tabular", "tabularcreate",
3706 "thesaurus", "texinfo", "toc", "view-source", "vspace", "wrap", "progress"};
3708 char const * const * const end_dialognames =
3709 dialognames + (sizeof(dialognames) / sizeof(char *));
3713 cmpCStr(char const * name) : name_(name) {}
3714 bool operator()(char const * other) {
3715 return strcmp(other, name_) == 0;
3722 bool isValidName(string const & name)
3724 return find_if(dialognames, end_dialognames,
3725 cmpCStr(name.c_str())) != end_dialognames;
3731 void GuiView::resetDialogs()
3733 // Make sure that no LFUN uses any GuiView.
3734 guiApp->setCurrentView(0);
3738 constructToolbars();
3739 guiApp->menus().fillMenuBar(menuBar(), this, false);
3740 d.layout_->updateContents(true);
3741 // Now update controls with current buffer.
3742 guiApp->setCurrentView(this);
3748 Dialog * GuiView::findOrBuild(string const & name, bool hide_it)
3750 if (!isValidName(name))
3753 map<string, DialogPtr>::iterator it = d.dialogs_.find(name);
3755 if (it != d.dialogs_.end()) {
3757 it->second->hideView();
3758 return it->second.get();
3761 Dialog * dialog = build(name);
3762 d.dialogs_[name].reset(dialog);
3763 if (lyxrc.allow_geometry_session)
3764 dialog->restoreSession();
3771 void GuiView::showDialog(string const & name, string const & data,
3774 triggerShowDialog(toqstr(name), toqstr(data), inset);
3778 void GuiView::doShowDialog(QString const & qname, QString const & qdata,
3784 const string name = fromqstr(qname);
3785 const string data = fromqstr(qdata);
3789 Dialog * dialog = findOrBuild(name, false);
3791 bool const visible = dialog->isVisibleView();
3792 dialog->showData(data);
3793 if (inset && currentBufferView())
3794 currentBufferView()->editInset(name, inset);
3795 // We only set the focus to the new dialog if it was not yet
3796 // visible in order not to change the existing previous behaviour
3798 // activateWindow is needed for floating dockviews
3799 dialog->asQWidget()->raise();
3800 dialog->asQWidget()->activateWindow();
3801 dialog->asQWidget()->setFocus();
3805 catch (ExceptionMessage const & ex) {
3813 bool GuiView::isDialogVisible(string const & name) const
3815 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3816 if (it == d.dialogs_.end())
3818 return it->second.get()->isVisibleView() && !it->second.get()->isClosing();
3822 void GuiView::hideDialog(string const & name, Inset * inset)
3824 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3825 if (it == d.dialogs_.end())
3829 if (!currentBufferView())
3831 if (inset != currentBufferView()->editedInset(name))
3835 Dialog * const dialog = it->second.get();
3836 if (dialog->isVisibleView())
3838 if (currentBufferView())
3839 currentBufferView()->editInset(name, 0);
3843 void GuiView::disconnectDialog(string const & name)
3845 if (!isValidName(name))
3847 if (currentBufferView())
3848 currentBufferView()->editInset(name, 0);
3852 void GuiView::hideAll() const
3854 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
3855 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3857 for(; it != end; ++it)
3858 it->second->hideView();
3862 void GuiView::updateDialogs()
3864 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
3865 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3867 for(; it != end; ++it) {
3868 Dialog * dialog = it->second.get();
3870 if (dialog->needBufferOpen() && !documentBufferView())
3871 hideDialog(fromqstr(dialog->name()), 0);
3872 else if (dialog->isVisibleView())
3873 dialog->checkStatus();
3880 Dialog * createDialog(GuiView & lv, string const & name);
3882 // will be replaced by a proper factory...
3883 Dialog * createGuiAbout(GuiView & lv);
3884 Dialog * createGuiBibtex(GuiView & lv);
3885 Dialog * createGuiChanges(GuiView & lv);
3886 Dialog * createGuiCharacter(GuiView & lv);
3887 Dialog * createGuiCitation(GuiView & lv);
3888 Dialog * createGuiCompare(GuiView & lv);
3889 Dialog * createGuiCompareHistory(GuiView & lv);
3890 Dialog * createGuiDelimiter(GuiView & lv);
3891 Dialog * createGuiDocument(GuiView & lv);
3892 Dialog * createGuiErrorList(GuiView & lv);
3893 Dialog * createGuiExternal(GuiView & lv);
3894 Dialog * createGuiGraphics(GuiView & lv);
3895 Dialog * createGuiInclude(GuiView & lv);
3896 Dialog * createGuiIndex(GuiView & lv);
3897 Dialog * createGuiListings(GuiView & lv);
3898 Dialog * createGuiLog(GuiView & lv);
3899 Dialog * createGuiMathMatrix(GuiView & lv);
3900 Dialog * createGuiNote(GuiView & lv);
3901 Dialog * createGuiParagraph(GuiView & lv);
3902 Dialog * createGuiPhantom(GuiView & lv);
3903 Dialog * createGuiPreferences(GuiView & lv);
3904 Dialog * createGuiPrint(GuiView & lv);
3905 Dialog * createGuiPrintindex(GuiView & lv);
3906 Dialog * createGuiRef(GuiView & lv);
3907 Dialog * createGuiSearch(GuiView & lv);
3908 Dialog * createGuiSearchAdv(GuiView & lv);
3909 Dialog * createGuiSendTo(GuiView & lv);
3910 Dialog * createGuiShowFile(GuiView & lv);
3911 Dialog * createGuiSpellchecker(GuiView & lv);
3912 Dialog * createGuiSymbols(GuiView & lv);
3913 Dialog * createGuiTabularCreate(GuiView & lv);
3914 Dialog * createGuiTexInfo(GuiView & lv);
3915 Dialog * createGuiToc(GuiView & lv);
3916 Dialog * createGuiThesaurus(GuiView & lv);
3917 Dialog * createGuiViewSource(GuiView & lv);
3918 Dialog * createGuiWrap(GuiView & lv);
3919 Dialog * createGuiProgressView(GuiView & lv);
3923 Dialog * GuiView::build(string const & name)
3925 LASSERT(isValidName(name), return 0);
3927 Dialog * dialog = createDialog(*this, name);
3931 if (name == "aboutlyx")
3932 return createGuiAbout(*this);
3933 if (name == "bibtex")
3934 return createGuiBibtex(*this);
3935 if (name == "changes")
3936 return createGuiChanges(*this);
3937 if (name == "character")
3938 return createGuiCharacter(*this);
3939 if (name == "citation")
3940 return createGuiCitation(*this);
3941 if (name == "compare")
3942 return createGuiCompare(*this);
3943 if (name == "comparehistory")
3944 return createGuiCompareHistory(*this);
3945 if (name == "document")
3946 return createGuiDocument(*this);
3947 if (name == "errorlist")
3948 return createGuiErrorList(*this);
3949 if (name == "external")
3950 return createGuiExternal(*this);
3952 return createGuiShowFile(*this);
3953 if (name == "findreplace")
3954 return createGuiSearch(*this);
3955 if (name == "findreplaceadv")
3956 return createGuiSearchAdv(*this);
3957 if (name == "graphics")
3958 return createGuiGraphics(*this);
3959 if (name == "include")
3960 return createGuiInclude(*this);
3961 if (name == "index")
3962 return createGuiIndex(*this);
3963 if (name == "index_print")
3964 return createGuiPrintindex(*this);
3965 if (name == "listings")
3966 return createGuiListings(*this);
3968 return createGuiLog(*this);
3969 if (name == "mathdelimiter")
3970 return createGuiDelimiter(*this);
3971 if (name == "mathmatrix")
3972 return createGuiMathMatrix(*this);
3974 return createGuiNote(*this);
3975 if (name == "paragraph")
3976 return createGuiParagraph(*this);
3977 if (name == "phantom")
3978 return createGuiPhantom(*this);
3979 if (name == "prefs")
3980 return createGuiPreferences(*this);
3981 if (name == "print")
3982 return createGuiPrint(*this);
3984 return createGuiRef(*this);
3985 if (name == "sendto")
3986 return createGuiSendTo(*this);
3987 if (name == "spellchecker")
3988 return createGuiSpellchecker(*this);
3989 if (name == "symbols")
3990 return createGuiSymbols(*this);
3991 if (name == "tabularcreate")
3992 return createGuiTabularCreate(*this);
3993 if (name == "texinfo")
3994 return createGuiTexInfo(*this);
3995 if (name == "thesaurus")
3996 return createGuiThesaurus(*this);
3998 return createGuiToc(*this);
3999 if (name == "view-source")
4000 return createGuiViewSource(*this);
4002 return createGuiWrap(*this);
4003 if (name == "progress")
4004 return createGuiProgressView(*this);
4010 } // namespace frontend
4013 #include "moc_GuiView.cpp"