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();
685 if (!restoreState(settings.value("layout").toByteArray(), 0))
692 GuiToolbar * GuiView::toolbar(string const & name)
694 ToolbarMap::iterator it = d.toolbars_.find(name);
695 if (it != d.toolbars_.end())
698 LYXERR(Debug::GUI, "Toolbar::display: no toolbar named " << name);
703 void GuiView::constructToolbars()
705 ToolbarMap::iterator it = d.toolbars_.begin();
706 for (; it != d.toolbars_.end(); ++it)
710 // I don't like doing this here, but the standard toolbar
711 // destroys this object when it's destroyed itself (vfr)
712 d.layout_ = new LayoutBox(*this);
713 d.stack_widget_->addWidget(d.layout_);
714 d.layout_->move(0,0);
716 // extracts the toolbars from the backend
717 Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
718 Toolbars::Infos::iterator end = guiApp->toolbars().end();
719 for (; cit != end; ++cit)
720 d.toolbars_[cit->name] = new GuiToolbar(*cit, *this);
724 void GuiView::initToolbars()
726 // extracts the toolbars from the backend
727 Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
728 Toolbars::Infos::iterator end = guiApp->toolbars().end();
729 for (; cit != end; ++cit) {
730 GuiToolbar * tb = toolbar(cit->name);
733 int const visibility = guiApp->toolbars().defaultVisibility(cit->name);
734 bool newline = !(visibility & Toolbars::SAMEROW);
735 tb->setVisible(false);
736 tb->setVisibility(visibility);
738 if (visibility & Toolbars::TOP) {
740 addToolBarBreak(Qt::TopToolBarArea);
741 addToolBar(Qt::TopToolBarArea, tb);
744 if (visibility & Toolbars::BOTTOM) {
745 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
746 #if (QT_VERSION >= 0x040202)
748 addToolBarBreak(Qt::BottomToolBarArea);
750 addToolBar(Qt::BottomToolBarArea, tb);
753 if (visibility & Toolbars::LEFT) {
754 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
755 #if (QT_VERSION >= 0x040202)
757 addToolBarBreak(Qt::LeftToolBarArea);
759 addToolBar(Qt::LeftToolBarArea, tb);
762 if (visibility & Toolbars::RIGHT) {
763 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
764 #if (QT_VERSION >= 0x040202)
766 addToolBarBreak(Qt::RightToolBarArea);
768 addToolBar(Qt::RightToolBarArea, tb);
771 if (visibility & Toolbars::ON)
772 tb->setVisible(true);
777 TocModels & GuiView::tocModels()
779 return d.toc_models_;
783 void GuiView::setFocus()
785 LYXERR(Debug::DEBUG, "GuiView::setFocus()" << this);
786 QMainWindow::setFocus();
790 void GuiView::focusInEvent(QFocusEvent * e)
792 LYXERR(Debug::DEBUG, "GuiView::focusInEvent()" << this);
793 QMainWindow::focusInEvent(e);
794 // Make sure guiApp points to the correct view.
795 guiApp->setCurrentView(this);
796 if (currentMainWorkArea())
797 currentMainWorkArea()->setFocus();
798 else if (currentWorkArea())
799 currentWorkArea()->setFocus();
801 d.bg_widget_->setFocus();
805 QMenu * GuiView::createPopupMenu()
807 return d.toolBarPopup(this);
811 void GuiView::showEvent(QShowEvent * e)
813 LYXERR(Debug::GUI, "Passed Geometry "
814 << size().height() << "x" << size().width()
815 << "+" << pos().x() << "+" << pos().y());
817 if (d.splitter_->count() == 0)
818 // No work area, switch to the background widget.
821 QMainWindow::showEvent(e);
825 bool GuiView::closeScheduled()
832 /** Destroy only all tabbed WorkAreas. Destruction of other WorkAreas
833 ** is responsibility of the container (e.g., dialog)
835 void GuiView::closeEvent(QCloseEvent * close_event)
837 LYXERR(Debug::DEBUG, "GuiView::closeEvent()");
839 if (!GuiViewPrivate::busyBuffers.isEmpty()) {
840 Alert::warning(_("Exit LyX"),
841 _("LyX could not be closed because documents are being processed by LyX."));
842 close_event->setAccepted(false);
846 // If the user pressed the x (so we didn't call closeView
847 // programmatically), we want to clear all existing entries.
849 theSession().lastOpened().clear();
854 // it can happen that this event arrives without selecting the view,
855 // e.g. when clicking the close button on a background window.
857 if (!closeWorkAreaAll()) {
859 close_event->ignore();
863 // Make sure that nothing will use this to be closed View.
864 guiApp->unregisterView(this);
866 if (isFullScreen()) {
867 // Switch off fullscreen before closing.
872 // Make sure the timer time out will not trigger a statusbar update.
873 d.statusbar_timer_.stop();
875 // Saving fullscreen requires additional tweaks in the toolbar code.
876 // It wouldn't also work under linux natively.
877 if (lyxrc.allow_geometry_session) {
882 close_event->accept();
886 void GuiView::dragEnterEvent(QDragEnterEvent * event)
888 if (event->mimeData()->hasUrls())
890 /// \todo Ask lyx-devel is this is enough:
891 /// if (event->mimeData()->hasFormat("text/plain"))
892 /// event->acceptProposedAction();
896 void GuiView::dropEvent(QDropEvent * event)
898 QList<QUrl> files = event->mimeData()->urls();
902 LYXERR(Debug::GUI, "GuiView::dropEvent: got URLs!");
903 for (int i = 0; i != files.size(); ++i) {
904 string const file = os::internal_path(fromqstr(
905 files.at(i).toLocalFile()));
909 string const ext = support::getExtension(file);
910 vector<const Format *> found_formats;
912 // Find all formats that have the correct extension.
913 vector<const Format *> const & import_formats
914 = theConverters().importableFormats();
915 vector<const Format *>::const_iterator it = import_formats.begin();
916 for (; it != import_formats.end(); ++it)
917 if ((*it)->extension() == ext)
918 found_formats.push_back(*it);
921 if (found_formats.size() >= 1) {
922 if (found_formats.size() > 1) {
923 //FIXME: show a dialog to choose the correct importable format
925 "Multiple importable formats found, selecting first");
927 string const arg = found_formats[0]->name() + " " + file;
928 cmd = FuncRequest(LFUN_BUFFER_IMPORT, arg);
931 //FIXME: do we have to explicitly check whether it's a lyx file?
933 "No formats found, trying to open it as a lyx file");
934 cmd = FuncRequest(LFUN_FILE_OPEN, file);
936 // add the functions to the queue
937 guiApp->addToFuncRequestQueue(cmd);
940 // now process the collected functions. We perform the events
941 // asynchronously. This prevents potential problems in case the
942 // BufferView is closed within an event.
943 guiApp->processFuncRequestQueueAsync();
947 void GuiView::message(docstring const & str)
949 if (ForkedProcess::iAmAChild())
952 // call is moved to GUI-thread by GuiProgress
953 d.progress_->appendMessage(toqstr(str));
957 void GuiView::clearMessageText()
959 message(docstring());
963 void GuiView::updateStatusBarMessage(QString const & str)
965 statusBar()->showMessage(str);
966 d.statusbar_timer_.stop();
967 d.statusbar_timer_.start(3000);
971 void GuiView::smallSizedIcons()
973 setIconSize(QSize(d.smallIconSize, d.smallIconSize));
977 void GuiView::normalSizedIcons()
979 setIconSize(QSize(d.normalIconSize, d.normalIconSize));
983 void GuiView::bigSizedIcons()
985 setIconSize(QSize(d.bigIconSize, d.bigIconSize));
989 void GuiView::clearMessage()
991 // FIXME: This code was introduced in r19643 to fix bug #4123. However,
992 // the hasFocus function mostly returns false, even if the focus is on
993 // a workarea in this view.
997 d.statusbar_timer_.stop();
1001 void GuiView::updateWindowTitle(GuiWorkArea * wa)
1003 if (wa != d.current_work_area_
1004 || wa->bufferView().buffer().isInternal())
1006 setWindowTitle(qt_("LyX: ") + wa->windowTitle());
1007 setWindowIconText(wa->windowIconText());
1011 void GuiView::on_currentWorkAreaChanged(GuiWorkArea * wa)
1014 disconnectBufferView();
1015 connectBufferView(wa->bufferView());
1016 connectBuffer(wa->bufferView().buffer());
1017 d.current_work_area_ = wa;
1018 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
1019 this, SLOT(updateWindowTitle(GuiWorkArea *)));
1020 updateWindowTitle(wa);
1024 // The document settings needs to be reinitialised.
1025 updateDialog("document", "");
1027 // Buffer-dependent dialogs must be updated. This is done here because
1028 // some dialogs require buffer()->text.
1033 void GuiView::on_lastWorkAreaRemoved()
1036 // We already are in a close event. Nothing more to do.
1039 if (d.splitter_->count() > 1)
1040 // We have a splitter so don't close anything.
1043 // Reset and updates the dialogs.
1044 d.toc_models_.reset(0);
1045 updateDialog("document", "");
1048 resetWindowTitleAndIconText();
1051 if (lyxrc.open_buffers_in_tabs)
1052 // Nothing more to do, the window should stay open.
1055 if (guiApp->viewIds().size() > 1) {
1061 // On Mac we also close the last window because the application stay
1062 // resident in memory. On other platforms we don't close the last
1063 // window because this would quit the application.
1069 void GuiView::updateStatusBar()
1071 // let the user see the explicit message
1072 if (d.statusbar_timer_.isActive())
1079 void GuiView::showMessage()
1081 QString msg = toqstr(theGuiApp()->viewStatusMessage());
1082 if (msg.isEmpty()) {
1083 BufferView const * bv = currentBufferView();
1085 msg = toqstr(bv->cursor().currentState());
1087 msg = qt_("Welcome to LyX!");
1089 statusBar()->showMessage(msg);
1093 bool GuiView::event(QEvent * e)
1097 // Useful debug code:
1098 //case QEvent::ActivationChange:
1099 //case QEvent::WindowDeactivate:
1100 //case QEvent::Paint:
1101 //case QEvent::Enter:
1102 //case QEvent::Leave:
1103 //case QEvent::HoverEnter:
1104 //case QEvent::HoverLeave:
1105 //case QEvent::HoverMove:
1106 //case QEvent::StatusTip:
1107 //case QEvent::DragEnter:
1108 //case QEvent::DragLeave:
1109 //case QEvent::Drop:
1112 case QEvent::WindowActivate: {
1113 GuiView * old_view = guiApp->currentView();
1114 if (this == old_view) {
1116 return QMainWindow::event(e);
1118 if (old_view && old_view->currentBufferView()) {
1119 // save current selection to the selection buffer to allow
1120 // middle-button paste in this window.
1121 cap::saveSelection(old_view->currentBufferView()->cursor());
1123 guiApp->setCurrentView(this);
1124 if (d.current_work_area_) {
1125 BufferView & bv = d.current_work_area_->bufferView();
1126 connectBufferView(bv);
1127 connectBuffer(bv.buffer());
1128 // The document structure, name and dialogs might have
1129 // changed in another view.
1131 // The document settings needs to be reinitialised.
1132 updateDialog("document", "");
1135 resetWindowTitleAndIconText();
1138 return QMainWindow::event(e);
1141 case QEvent::ShortcutOverride: {
1144 #if (!defined Q_WS_X11) || (QT_VERSION >= 0x040500)
1145 if (isFullScreen() && menuBar()->isHidden()) {
1146 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
1147 // FIXME: we should also try to detect special LyX shortcut such as
1148 // Alt-P and Alt-M. Right now there is a hack in
1149 // GuiWorkArea::processKeySym() that hides again the menubar for
1151 if (ke->modifiers() & Qt::AltModifier && ke->key() != Qt::Key_Alt) {
1153 return QMainWindow::event(e);
1157 return QMainWindow::event(e);
1161 return QMainWindow::event(e);
1165 void GuiView::resetWindowTitleAndIconText()
1167 setWindowTitle(qt_("LyX"));
1168 setWindowIconText(qt_("LyX"));
1171 bool GuiView::focusNextPrevChild(bool /*next*/)
1178 bool GuiView::busy() const
1184 void GuiView::setBusy(bool busy)
1186 bool const busy_before = busy_ > 0;
1187 busy ? ++busy_ : --busy_;
1188 if ((busy_ > 0) == busy_before)
1189 // busy state didn't change
1192 if (d.current_work_area_) {
1193 d.current_work_area_->setUpdatesEnabled(!busy);
1195 d.current_work_area_->stopBlinkingCursor();
1197 d.current_work_area_->startBlinkingCursor();
1201 QApplication::setOverrideCursor(Qt::WaitCursor);
1203 QApplication::restoreOverrideCursor();
1207 GuiWorkArea * GuiView::workArea(int index)
1209 if (TabWorkArea * twa = d.currentTabWorkArea())
1210 if (index < twa->count())
1211 return dynamic_cast<GuiWorkArea *>(twa->widget(index));
1216 GuiWorkArea * GuiView::workArea(Buffer & buffer)
1218 if (currentWorkArea()
1219 && ¤tWorkArea()->bufferView().buffer() == &buffer)
1220 return (GuiWorkArea *) currentWorkArea();
1221 if (TabWorkArea * twa = d.currentTabWorkArea())
1222 return twa->workArea(buffer);
1227 GuiWorkArea * GuiView::addWorkArea(Buffer & buffer)
1229 // Automatically create a TabWorkArea if there are none yet.
1230 TabWorkArea * tab_widget = d.splitter_->count()
1231 ? d.currentTabWorkArea() : addTabWorkArea();
1232 return tab_widget->addWorkArea(buffer, *this);
1236 TabWorkArea * GuiView::addTabWorkArea()
1238 TabWorkArea * twa = new TabWorkArea;
1239 QObject::connect(twa, SIGNAL(currentWorkAreaChanged(GuiWorkArea *)),
1240 this, SLOT(on_currentWorkAreaChanged(GuiWorkArea *)));
1241 QObject::connect(twa, SIGNAL(lastWorkAreaRemoved()),
1242 this, SLOT(on_lastWorkAreaRemoved()));
1244 d.splitter_->addWidget(twa);
1245 d.stack_widget_->setCurrentWidget(d.splitter_);
1250 GuiWorkArea const * GuiView::currentWorkArea() const
1252 return d.current_work_area_;
1256 GuiWorkArea * GuiView::currentWorkArea()
1258 return d.current_work_area_;
1262 GuiWorkArea const * GuiView::currentMainWorkArea() const
1264 if (!d.currentTabWorkArea())
1266 return d.currentTabWorkArea()->currentWorkArea();
1270 GuiWorkArea * GuiView::currentMainWorkArea()
1272 if (!d.currentTabWorkArea())
1274 return d.currentTabWorkArea()->currentWorkArea();
1278 void GuiView::setCurrentWorkArea(GuiWorkArea * wa)
1280 LYXERR(Debug::DEBUG, "Setting current wa: " << wa << endl);
1282 d.current_work_area_ = 0;
1287 // FIXME: I've no clue why this is here and why it accesses
1288 // theGuiApp()->currentView, which might be 0 (bug 6464).
1289 // See also 27525 (vfr).
1290 if (theGuiApp()->currentView() == this
1291 && theGuiApp()->currentView()->currentWorkArea() == wa)
1294 if (currentBufferView())
1295 cap::saveSelection(currentBufferView()->cursor());
1297 theGuiApp()->setCurrentView(this);
1298 d.current_work_area_ = wa;
1300 // We need to reset this now, because it will need to be
1301 // right if the tabWorkArea gets reset in the for loop. We
1302 // will change it back if we aren't in that case.
1303 GuiWorkArea * const old_cmwa = d.current_main_work_area_;
1304 d.current_main_work_area_ = wa;
1306 for (int i = 0; i != d.splitter_->count(); ++i) {
1307 if (d.tabWorkArea(i)->setCurrentWorkArea(wa)) {
1308 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea()
1309 << ", Current main wa: " << currentMainWorkArea());
1314 d.current_main_work_area_ = old_cmwa;
1316 LYXERR(Debug::DEBUG, "This is not a tabbed wa");
1317 on_currentWorkAreaChanged(wa);
1318 BufferView & bv = wa->bufferView();
1319 bv.cursor().fixIfBroken();
1321 wa->setUpdatesEnabled(true);
1322 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() << ", Current main wa: " << currentMainWorkArea());
1326 void GuiView::removeWorkArea(GuiWorkArea * wa)
1328 LASSERT(wa, return);
1329 if (wa == d.current_work_area_) {
1331 disconnectBufferView();
1332 d.current_work_area_ = 0;
1333 d.current_main_work_area_ = 0;
1336 bool found_twa = false;
1337 for (int i = 0; i != d.splitter_->count(); ++i) {
1338 TabWorkArea * twa = d.tabWorkArea(i);
1339 if (twa->removeWorkArea(wa)) {
1340 // Found in this tab group, and deleted the GuiWorkArea.
1342 if (twa->count() != 0) {
1343 if (d.current_work_area_ == 0)
1344 // This means that we are closing the current GuiWorkArea, so
1345 // switch to the next GuiWorkArea in the found TabWorkArea.
1346 setCurrentWorkArea(twa->currentWorkArea());
1348 // No more WorkAreas in this tab group, so delete it.
1355 // It is not a tabbed work area (i.e., the search work area), so it
1356 // should be deleted by other means.
1357 LASSERT(found_twa, /* */);
1359 if (d.current_work_area_ == 0) {
1360 if (d.splitter_->count() != 0) {
1361 TabWorkArea * twa = d.currentTabWorkArea();
1362 setCurrentWorkArea(twa->currentWorkArea());
1364 // No more work areas, switch to the background widget.
1365 setCurrentWorkArea(0);
1371 LayoutBox * GuiView::getLayoutDialog() const
1377 void GuiView::updateLayoutList()
1380 d.layout_->updateContents(false);
1384 void GuiView::updateToolbars()
1386 ToolbarMap::iterator end = d.toolbars_.end();
1387 if (d.current_work_area_) {
1389 d.current_work_area_->bufferView().cursor().inMathed()
1390 && !d.current_work_area_->bufferView().cursor().inRegexped();
1392 lyx::getStatus(FuncRequest(LFUN_LAYOUT_TABULAR)).enabled();
1394 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).enabled() &&
1395 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).onOff(true);
1396 bool const mathmacrotemplate =
1397 lyx::getStatus(FuncRequest(LFUN_IN_MATHMACROTEMPLATE)).enabled();
1399 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1400 it->second->update(math, table, review, mathmacrotemplate);
1402 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1403 it->second->update(false, false, false, false);
1407 void GuiView::setBuffer(Buffer * newBuffer)
1409 LYXERR(Debug::DEBUG, "Setting buffer: " << newBuffer << endl);
1410 LASSERT(newBuffer, return);
1413 GuiWorkArea * wa = workArea(*newBuffer);
1415 newBuffer->masterBuffer()->updateBuffer();
1416 wa = addWorkArea(*newBuffer);
1417 // scroll to the position when the BufferView was last closed
1418 if (lyxrc.use_lastfilepos) {
1419 LastFilePosSection::FilePos filepos =
1420 theSession().lastFilePos().load(newBuffer->fileName());
1421 wa->bufferView().moveToPosition(filepos.pit, filepos.pos, 0, 0);
1424 //Disconnect the old buffer...there's no new one.
1427 connectBuffer(*newBuffer);
1428 connectBufferView(wa->bufferView());
1429 setCurrentWorkArea(wa);
1435 void GuiView::connectBuffer(Buffer & buf)
1437 buf.setGuiDelegate(this);
1441 void GuiView::disconnectBuffer()
1443 if (d.current_work_area_)
1444 d.current_work_area_->bufferView().buffer().setGuiDelegate(0);
1448 void GuiView::connectBufferView(BufferView & bv)
1450 bv.setGuiDelegate(this);
1454 void GuiView::disconnectBufferView()
1456 if (d.current_work_area_)
1457 d.current_work_area_->bufferView().setGuiDelegate(0);
1461 void GuiView::errors(string const & error_type, bool from_master)
1463 BufferView const * const bv = currentBufferView();
1467 ErrorList & el = from_master ?
1468 bv->buffer().masterBuffer()->errorList(error_type) :
1469 bv->buffer().errorList(error_type);
1473 string data = error_type;
1475 data = "from_master|" + error_type;
1476 showDialog("errorlist", data);
1480 void GuiView::updateTocItem(string const & type, DocIterator const & dit)
1482 d.toc_models_.updateItem(toqstr(type), dit);
1486 void GuiView::structureChanged()
1488 d.toc_models_.reset(documentBufferView());
1489 // Navigator needs more than a simple update in this case. It needs to be
1491 updateDialog("toc", "");
1495 void GuiView::updateDialog(string const & name, string const & data)
1497 if (!isDialogVisible(name))
1500 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
1501 if (it == d.dialogs_.end())
1504 Dialog * const dialog = it->second.get();
1505 if (dialog->isVisibleView())
1506 dialog->initialiseParams(data);
1510 BufferView * GuiView::documentBufferView()
1512 return currentMainWorkArea()
1513 ? ¤tMainWorkArea()->bufferView()
1518 BufferView const * GuiView::documentBufferView() const
1520 return currentMainWorkArea()
1521 ? ¤tMainWorkArea()->bufferView()
1526 BufferView * GuiView::currentBufferView()
1528 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1532 BufferView const * GuiView::currentBufferView() const
1534 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1538 #if (QT_VERSION >= 0x040400)
1539 docstring GuiView::GuiViewPrivate::autosaveAndDestroy(
1540 Buffer const * orig, Buffer * buffer)
1542 bool const success = buffer->autoSave();
1544 busyBuffers.remove(orig);
1546 ? _("Automatic save done.")
1547 : _("Automatic save failed!");
1552 void GuiView::autoSave()
1554 LYXERR(Debug::INFO, "Running autoSave()");
1556 Buffer * buffer = documentBufferView()
1557 ? &documentBufferView()->buffer() : 0;
1561 #if (QT_VERSION >= 0x040400)
1562 GuiViewPrivate::busyBuffers.insert(buffer);
1563 QFuture<docstring> f = QtConcurrent::run(GuiViewPrivate::autosaveAndDestroy,
1564 buffer, buffer->clone());
1565 d.autosave_watcher_.setFuture(f);
1569 resetAutosaveTimers();
1573 void GuiView::resetAutosaveTimers()
1576 d.autosave_timeout_.restart();
1580 bool GuiView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1583 Buffer * buf = currentBufferView()
1584 ? ¤tBufferView()->buffer() : 0;
1585 Buffer * doc_buffer = documentBufferView()
1586 ? &(documentBufferView()->buffer()) : 0;
1588 // Check whether we need a buffer
1589 if (!lyxaction.funcHasFlag(cmd.action(), LyXAction::NoBuffer) && !buf) {
1590 // no, exit directly
1591 flag.message(from_utf8(N_("Command not allowed with"
1592 "out any document open")));
1593 flag.setEnabled(false);
1597 if (cmd.origin() == FuncRequest::TOC) {
1598 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
1599 if (!toc || !toc->getStatus(documentBufferView()->cursor(), cmd, flag))
1600 flag.setEnabled(false);
1604 switch(cmd.action()) {
1605 case LFUN_BUFFER_IMPORT:
1608 case LFUN_MASTER_BUFFER_UPDATE:
1609 case LFUN_MASTER_BUFFER_VIEW:
1610 enable = doc_buffer && doc_buffer->parent() != 0
1611 && !d.processing_thread_watcher_.isRunning();
1614 case LFUN_BUFFER_UPDATE:
1615 case LFUN_BUFFER_VIEW: {
1616 if (!doc_buffer || d.processing_thread_watcher_.isRunning()) {
1620 string format = to_utf8(cmd.argument());
1621 if (cmd.argument().empty())
1622 format = doc_buffer->getDefaultOutputFormat();
1623 enable = doc_buffer->isExportableFormat(format);
1627 case LFUN_BUFFER_RELOAD:
1628 enable = doc_buffer && !doc_buffer->isUnnamed()
1629 && doc_buffer->fileName().exists()
1630 && (!doc_buffer->isClean()
1631 || doc_buffer->isExternallyModified(Buffer::timestamp_method));
1634 case LFUN_BUFFER_CHILD_OPEN:
1635 enable = doc_buffer;
1638 case LFUN_BUFFER_WRITE:
1639 enable = doc_buffer && (doc_buffer->isUnnamed() || !doc_buffer->isClean());
1642 //FIXME: This LFUN should be moved to GuiApplication.
1643 case LFUN_BUFFER_WRITE_ALL: {
1644 // We enable the command only if there are some modified buffers
1645 Buffer * first = theBufferList().first();
1650 // We cannot use a for loop as the buffer list is a cycle.
1652 if (!b->isClean()) {
1656 b = theBufferList().next(b);
1657 } while (b != first);
1661 case LFUN_BUFFER_WRITE_AS:
1662 enable = doc_buffer;
1665 case LFUN_BUFFER_CLOSE:
1666 enable = doc_buffer;
1669 case LFUN_BUFFER_CLOSE_ALL:
1670 enable = theBufferList().last() != theBufferList().first();
1673 case LFUN_SPLIT_VIEW:
1674 if (cmd.getArg(0) == "vertical")
1675 enable = doc_buffer && (d.splitter_->count() == 1 ||
1676 d.splitter_->orientation() == Qt::Vertical);
1678 enable = doc_buffer && (d.splitter_->count() == 1 ||
1679 d.splitter_->orientation() == Qt::Horizontal);
1682 case LFUN_CLOSE_TAB_GROUP:
1683 enable = d.currentTabWorkArea();
1686 case LFUN_TOOLBAR_TOGGLE: {
1687 string const name = cmd.getArg(0);
1688 if (GuiToolbar * t = toolbar(name))
1689 flag.setOnOff(t->isVisible());
1692 docstring const msg =
1693 bformat(_("Unknown toolbar \"%1$s\""), from_utf8(name));
1699 case LFUN_DROP_LAYOUTS_CHOICE:
1703 case LFUN_UI_TOGGLE:
1704 flag.setOnOff(isFullScreen());
1707 case LFUN_DIALOG_DISCONNECT_INSET:
1710 case LFUN_DIALOG_HIDE:
1711 // FIXME: should we check if the dialog is shown?
1714 case LFUN_DIALOG_TOGGLE:
1715 flag.setOnOff(isDialogVisible(cmd.getArg(0)));
1716 // fall through to set "enable"
1717 case LFUN_DIALOG_SHOW: {
1718 string const name = cmd.getArg(0);
1720 enable = name == "aboutlyx"
1721 || name == "file" //FIXME: should be removed.
1723 || name == "texinfo"
1724 || name == "progress"
1725 || name == "compare";
1726 else if (name == "print")
1727 enable = doc_buffer->isExportable("dvi")
1728 && lyxrc.print_command != "none";
1729 else if (name == "character" || name == "symbols") {
1730 if (!buf || buf->isReadonly())
1733 // FIXME we should consider passthru
1735 Inset const & in = currentBufferView()->cursor().inset();
1736 enable = !in.getLayout().isPassThru();
1739 else if (name == "latexlog")
1740 enable = FileName(doc_buffer->logName()).isReadableFile();
1741 else if (name == "spellchecker")
1742 enable = theSpellChecker() && !doc_buffer->isReadonly();
1743 else if (name == "vclog")
1744 enable = doc_buffer->lyxvc().inUse();
1748 case LFUN_DIALOG_UPDATE: {
1749 string const name = cmd.getArg(0);
1751 enable = name == "prefs";
1755 case LFUN_COMMAND_EXECUTE:
1757 case LFUN_MENU_OPEN:
1758 // Nothing to check.
1761 case LFUN_COMPLETION_INLINE:
1762 if (!d.current_work_area_
1763 || !d.current_work_area_->completer().inlinePossible(
1764 currentBufferView()->cursor()))
1768 case LFUN_COMPLETION_POPUP:
1769 if (!d.current_work_area_
1770 || !d.current_work_area_->completer().popupPossible(
1771 currentBufferView()->cursor()))
1775 case LFUN_COMPLETION_COMPLETE:
1776 if (!d.current_work_area_
1777 || !d.current_work_area_->completer().inlinePossible(
1778 currentBufferView()->cursor()))
1782 case LFUN_COMPLETION_ACCEPT:
1783 if (!d.current_work_area_
1784 || (!d.current_work_area_->completer().popupVisible()
1785 && !d.current_work_area_->completer().inlineVisible()
1786 && !d.current_work_area_->completer().completionAvailable()))
1790 case LFUN_COMPLETION_CANCEL:
1791 if (!d.current_work_area_
1792 || (!d.current_work_area_->completer().popupVisible()
1793 && !d.current_work_area_->completer().inlineVisible()))
1797 case LFUN_BUFFER_ZOOM_OUT:
1798 enable = doc_buffer && lyxrc.zoom > 10;
1801 case LFUN_BUFFER_ZOOM_IN:
1802 enable = doc_buffer;
1805 case LFUN_BUFFER_NEXT:
1806 case LFUN_BUFFER_PREVIOUS:
1807 // FIXME: should we check is there is an previous or next buffer?
1809 case LFUN_BUFFER_SWITCH:
1810 // toggle on the current buffer, but do not toggle off
1811 // the other ones (is that a good idea?)
1813 && to_utf8(cmd.argument()) == doc_buffer->absFileName())
1814 flag.setOnOff(true);
1817 case LFUN_VC_REGISTER:
1818 enable = doc_buffer && !doc_buffer->lyxvc().inUse();
1820 case LFUN_VC_CHECK_IN:
1821 enable = doc_buffer && doc_buffer->lyxvc().checkInEnabled();
1823 case LFUN_VC_CHECK_OUT:
1824 enable = doc_buffer && doc_buffer->lyxvc().checkOutEnabled();
1826 case LFUN_VC_LOCKING_TOGGLE:
1827 enable = doc_buffer && !doc_buffer->isReadonly()
1828 && doc_buffer->lyxvc().lockingToggleEnabled();
1829 flag.setOnOff(enable && doc_buffer->lyxvc().locking());
1831 case LFUN_VC_REVERT:
1832 enable = doc_buffer && doc_buffer->lyxvc().inUse() && !doc_buffer->isReadonly();
1834 case LFUN_VC_UNDO_LAST:
1835 enable = doc_buffer && doc_buffer->lyxvc().undoLastEnabled();
1837 case LFUN_VC_REPO_UPDATE:
1838 enable = doc_buffer && doc_buffer->lyxvc().repoUpdateEnabled();
1840 case LFUN_VC_COMMAND: {
1841 if (cmd.argument().empty())
1843 if (!doc_buffer && contains(cmd.getArg(0), 'D'))
1847 case LFUN_VC_COMPARE:
1848 enable = doc_buffer && doc_buffer->lyxvc().prepareFileRevisionEnabled();
1851 case LFUN_SERVER_GOTO_FILE_ROW:
1853 case LFUN_FORWARD_SEARCH:
1854 enable = !(lyxrc.forward_search_dvi.empty() && lyxrc.forward_search_pdf.empty());
1862 flag.setEnabled(false);
1868 static FileName selectTemplateFile()
1870 FileDialog dlg(qt_("Select template file"));
1871 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1872 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
1874 FileDialog::Result result = dlg.open(toqstr(lyxrc.template_path),
1875 QStringList(qt_("LyX Documents (*.lyx)")));
1877 if (result.first == FileDialog::Later)
1879 if (result.second.isEmpty())
1881 return FileName(fromqstr(result.second));
1885 Buffer * GuiView::loadDocument(FileName const & filename, bool tolastfiles)
1889 Buffer * newBuffer = 0;
1891 newBuffer = checkAndLoadLyXFile(filename);
1892 } catch (ExceptionMessage const & e) {
1898 message(_("Document not loaded."));
1903 newBuffer->errors("Parse");
1904 setBuffer(newBuffer);
1907 theSession().lastFiles().add(filename);
1914 void GuiView::openDocument(string const & fname)
1916 string initpath = lyxrc.document_path;
1918 if (documentBufferView()) {
1919 string const trypath = documentBufferView()->buffer().filePath();
1920 // If directory is writeable, use this as default.
1921 if (FileName(trypath).isDirWritable())
1927 if (fname.empty()) {
1928 FileDialog dlg(qt_("Select document to open"), LFUN_FILE_OPEN);
1929 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1930 dlg.setButton2(qt_("Examples|#E#e"),
1931 toqstr(addPath(package().system_support().absFileName(), "examples")));
1933 QStringList filter(qt_("LyX Documents (*.lyx)"));
1934 filter << qt_("LyX-1.3.x Documents (*.lyx13)")
1935 << qt_("LyX-1.4.x Documents (*.lyx14)")
1936 << qt_("LyX-1.5.x Documents (*.lyx15)")
1937 << qt_("LyX-1.6.x Documents (*.lyx16)");
1938 FileDialog::Result result =
1939 dlg.open(toqstr(initpath), filter);
1941 if (result.first == FileDialog::Later)
1944 filename = fromqstr(result.second);
1946 // check selected filename
1947 if (filename.empty()) {
1948 message(_("Canceled."));
1954 // get absolute path of file and add ".lyx" to the filename if
1956 FileName const fullname =
1957 fileSearch(string(), filename, "lyx", support::may_not_exist);
1958 if (!fullname.empty())
1959 filename = fullname.absFileName();
1961 if (!fullname.onlyPath().isDirectory()) {
1962 Alert::warning(_("Invalid filename"),
1963 bformat(_("The directory in the given path\n%1$s\ndoes not exist."),
1964 from_utf8(fullname.absFileName())));
1968 // if the file doesn't exist and isn't already open (bug 6645),
1969 // let the user create one
1970 if (!fullname.exists() && !theBufferList().exists(fullname)) {
1971 // the user specifically chose this name. Believe him.
1972 Buffer * const b = newFile(filename, string(), true);
1978 docstring const disp_fn = makeDisplayPath(filename);
1979 message(bformat(_("Opening document %1$s..."), disp_fn));
1982 Buffer * buf = loadDocument(fullname);
1984 str2 = bformat(_("Document %1$s opened."), disp_fn);
1985 if (buf->lyxvc().inUse())
1986 str2 += " " + from_utf8(buf->lyxvc().versionString()) +
1987 " " + _("Version control detected.");
1989 str2 = bformat(_("Could not open document %1$s"), disp_fn);
1994 // FIXME: clean that
1995 static bool import(GuiView * lv, FileName const & filename,
1996 string const & format, ErrorList & errorList)
1998 FileName const lyxfile(support::changeExtension(filename.absFileName(), ".lyx"));
2000 string loader_format;
2001 vector<string> loaders = theConverters().loaders();
2002 if (find(loaders.begin(), loaders.end(), format) == loaders.end()) {
2003 for (vector<string>::const_iterator it = loaders.begin();
2004 it != loaders.end(); ++it) {
2005 if (!theConverters().isReachable(format, *it))
2008 string const tofile =
2009 support::changeExtension(filename.absFileName(),
2010 formats.extension(*it));
2011 if (!theConverters().convert(0, filename, FileName(tofile),
2012 filename, format, *it, errorList))
2014 loader_format = *it;
2017 if (loader_format.empty()) {
2018 frontend::Alert::error(_("Couldn't import file"),
2019 bformat(_("No information for importing the format %1$s."),
2020 formats.prettyName(format)));
2024 loader_format = format;
2026 if (loader_format == "lyx") {
2027 Buffer * buf = lv->loadDocument(lyxfile);
2031 Buffer * const b = newFile(lyxfile.absFileName(), string(), true);
2035 bool as_paragraphs = loader_format == "textparagraph";
2036 string filename2 = (loader_format == format) ? filename.absFileName()
2037 : support::changeExtension(filename.absFileName(),
2038 formats.extension(loader_format));
2039 lv->currentBufferView()->insertPlaintextFile(FileName(filename2),
2041 guiApp->setCurrentView(lv);
2042 lyx::dispatch(FuncRequest(LFUN_MARK_OFF));
2049 void GuiView::importDocument(string const & argument)
2052 string filename = split(argument, format, ' ');
2054 LYXERR(Debug::INFO, format << " file: " << filename);
2056 // need user interaction
2057 if (filename.empty()) {
2058 string initpath = lyxrc.document_path;
2059 if (documentBufferView()) {
2060 string const trypath = documentBufferView()->buffer().filePath();
2061 // If directory is writeable, use this as default.
2062 if (FileName(trypath).isDirWritable())
2066 docstring const text = bformat(_("Select %1$s file to import"),
2067 formats.prettyName(format));
2069 FileDialog dlg(toqstr(text), LFUN_BUFFER_IMPORT);
2070 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2071 dlg.setButton2(qt_("Examples|#E#e"),
2072 toqstr(addPath(package().system_support().absFileName(), "examples")));
2074 docstring filter = formats.prettyName(format);
2077 filter += from_utf8(formats.extension(format));
2080 FileDialog::Result result =
2081 dlg.open(toqstr(initpath), fileFilters(toqstr(filter)));
2083 if (result.first == FileDialog::Later)
2086 filename = fromqstr(result.second);
2088 // check selected filename
2089 if (filename.empty())
2090 message(_("Canceled."));
2093 if (filename.empty())
2096 // get absolute path of file
2097 FileName const fullname(support::makeAbsPath(filename));
2099 FileName const lyxfile(support::changeExtension(fullname.absFileName(), ".lyx"));
2101 // Check if the document already is open
2102 Buffer * buf = theBufferList().getBuffer(lyxfile);
2105 if (!closeBuffer()) {
2106 message(_("Canceled."));
2111 docstring const displaypath = makeDisplayPath(lyxfile.absFileName(), 30);
2113 // if the file exists already, and we didn't do
2114 // -i lyx thefile.lyx, warn
2115 if (lyxfile.exists() && fullname != lyxfile) {
2117 docstring text = bformat(_("The document %1$s already exists.\n\n"
2118 "Do you want to overwrite that document?"), displaypath);
2119 int const ret = Alert::prompt(_("Overwrite document?"),
2120 text, 0, 1, _("&Overwrite"), _("&Cancel"));
2123 message(_("Canceled."));
2128 message(bformat(_("Importing %1$s..."), displaypath));
2129 ErrorList errorList;
2130 if (import(this, fullname, format, errorList))
2131 message(_("imported."));
2133 message(_("file not imported!"));
2135 // FIXME (Abdel 12/08/06): Is there a need to display the error list here?
2139 void GuiView::newDocument(string const & filename, bool from_template)
2141 FileName initpath(lyxrc.document_path);
2142 if (documentBufferView()) {
2143 FileName const trypath(documentBufferView()->buffer().filePath());
2144 // If directory is writeable, use this as default.
2145 if (trypath.isDirWritable())
2149 string templatefile;
2150 if (from_template) {
2151 templatefile = selectTemplateFile().absFileName();
2152 if (templatefile.empty())
2157 if (filename.empty())
2158 b = newUnnamedFile(initpath, to_utf8(_("newfile")), templatefile);
2160 b = newFile(filename, templatefile, true);
2165 // If no new document could be created, it is unsure
2166 // whether there is a valid BufferView.
2167 if (currentBufferView())
2168 // Ensure the cursor is correctly positioned on screen.
2169 currentBufferView()->showCursor();
2173 void GuiView::insertLyXFile(docstring const & fname)
2175 BufferView * bv = documentBufferView();
2180 FileName filename(to_utf8(fname));
2181 if (filename.empty()) {
2182 // Launch a file browser
2184 string initpath = lyxrc.document_path;
2185 string const trypath = bv->buffer().filePath();
2186 // If directory is writeable, use this as default.
2187 if (FileName(trypath).isDirWritable())
2191 FileDialog dlg(qt_("Select LyX document to insert"), LFUN_FILE_INSERT);
2192 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2193 dlg.setButton2(qt_("Examples|#E#e"),
2194 toqstr(addPath(package().system_support().absFileName(),
2197 FileDialog::Result result = dlg.open(toqstr(initpath),
2198 QStringList(qt_("LyX Documents (*.lyx)")));
2200 if (result.first == FileDialog::Later)
2204 filename.set(fromqstr(result.second));
2206 // check selected filename
2207 if (filename.empty()) {
2208 // emit message signal.
2209 message(_("Canceled."));
2214 bv->insertLyXFile(filename);
2215 bv->buffer().errors("Parse");
2219 void GuiView::insertPlaintextFile(docstring const & fname,
2222 BufferView * bv = documentBufferView();
2226 if (!fname.empty() && !FileName::isAbsolute(to_utf8(fname))) {
2227 message(_("Absolute filename expected."));
2232 FileName filename(to_utf8(fname));
2234 if (!filename.empty()) {
2235 bv->insertPlaintextFile(filename, asParagraph);
2239 FileDialog dlg(qt_("Select file to insert"), (asParagraph ?
2240 LFUN_FILE_INSERT_PLAINTEXT_PARA : LFUN_FILE_INSERT_PLAINTEXT));
2242 FileDialog::Result result = dlg.open(toqstr(bv->buffer().filePath()),
2243 QStringList(qt_("All Files (*)")));
2245 if (result.first == FileDialog::Later)
2249 filename.set(fromqstr(result.second));
2251 // check selected filename
2252 if (filename.empty()) {
2253 // emit message signal.
2254 message(_("Canceled."));
2258 bv->insertPlaintextFile(filename, asParagraph);
2262 bool GuiView::renameBuffer(Buffer & b, docstring const & newname)
2264 FileName fname = b.fileName();
2265 FileName const oldname = fname;
2267 if (!newname.empty()) {
2269 fname = support::makeAbsPath(to_utf8(newname), oldname.onlyPath().absFileName());
2271 // Switch to this Buffer.
2274 // No argument? Ask user through dialog.
2276 FileDialog dlg(qt_("Choose a filename to save document as"),
2277 LFUN_BUFFER_WRITE_AS);
2278 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2279 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
2281 if (!isLyXFileName(fname.absFileName()))
2282 fname.changeExtension(".lyx");
2284 FileDialog::Result result =
2285 dlg.save(toqstr(fname.onlyPath().absFileName()),
2286 QStringList(qt_("LyX Documents (*.lyx)")),
2287 toqstr(fname.onlyFileName()));
2289 if (result.first == FileDialog::Later)
2292 fname.set(fromqstr(result.second));
2297 if (!isLyXFileName(fname.absFileName()))
2298 fname.changeExtension(".lyx");
2301 // fname is now the new Buffer location.
2302 if (FileName(fname).exists()) {
2303 docstring const file = makeDisplayPath(fname.absFileName(), 30);
2304 docstring text = bformat(_("The document %1$s already "
2305 "exists.\n\nDo you want to "
2306 "overwrite that document?"),
2308 int const ret = Alert::prompt(_("Overwrite document?"),
2309 text, 0, 2, _("&Overwrite"), _("&Rename"), _("&Cancel"));
2312 case 1: return renameBuffer(b, docstring());
2313 case 2: return false;
2317 return saveBuffer(b, fname);
2321 bool GuiView::saveBuffer(Buffer & b) {
2322 return saveBuffer(b, FileName());
2326 bool GuiView::saveBuffer(Buffer & b, FileName const & fn)
2328 if (workArea(b) && workArea(b)->inDialogMode())
2331 if (fn.empty() && b.isUnnamed())
2332 return renameBuffer(b, docstring());
2338 success = b.saveAs(fn);
2341 theSession().lastFiles().add(b.fileName());
2345 // Switch to this Buffer.
2348 // FIXME: we don't tell the user *WHY* the save failed !!
2349 docstring const file = makeDisplayPath(b.absFileName(), 30);
2350 docstring text = bformat(_("The document %1$s could not be saved.\n\n"
2351 "Do you want to rename the document and "
2352 "try again?"), file);
2353 int const ret = Alert::prompt(_("Rename and save?"),
2354 text, 0, 2, _("&Rename"), _("&Retry"), _("&Cancel"));
2357 if (!renameBuffer(b, docstring()))
2366 return saveBuffer(b);
2370 bool GuiView::hideWorkArea(GuiWorkArea * wa)
2372 return closeWorkArea(wa, false);
2376 bool GuiView::closeWorkArea(GuiWorkArea * wa)
2378 Buffer & buf = wa->bufferView().buffer();
2379 return closeWorkArea(wa, !buf.parent());
2383 bool GuiView::closeBuffer()
2385 GuiWorkArea * wa = currentMainWorkArea();
2386 setCurrentWorkArea(wa);
2387 Buffer & buf = wa->bufferView().buffer();
2388 return wa && closeWorkArea(wa, !buf.parent());
2392 void GuiView::writeSession() const {
2393 GuiWorkArea const * active_wa = currentMainWorkArea();
2394 for (int i = 0; i < d.splitter_->count(); ++i) {
2395 TabWorkArea * twa = d.tabWorkArea(i);
2396 for (int j = 0; j < twa->count(); ++j) {
2397 GuiWorkArea * wa = static_cast<GuiWorkArea *>(twa->widget(j));
2398 Buffer & buf = wa->bufferView().buffer();
2399 theSession().lastOpened().add(buf.fileName(), wa == active_wa);
2405 bool GuiView::closeBufferAll()
2407 // Close the workareas in all other views
2408 QList<int> const ids = guiApp->viewIds();
2409 for (int i = 0; i != ids.size(); ++i) {
2410 if (id_ != ids[i] && !guiApp->view(ids[i]).closeWorkAreaAll())
2414 // Close our own workareas
2415 if (!closeWorkAreaAll())
2418 // Now close the hidden buffers. We prevent hidden buffers from being
2419 // dirty, so we can just close them.
2420 theBufferList().closeAll();
2425 bool GuiView::closeWorkAreaAll()
2427 setCurrentWorkArea(currentMainWorkArea());
2429 // We might be in a situation that there is still a tabWorkArea, but
2430 // there are no tabs anymore. This can happen when we get here after a
2431 // TabWorkArea::lastWorkAreaRemoved() signal. Therefore we count how
2432 // many TabWorkArea's have no documents anymore.
2435 // We have to call count() each time, because it can happen that
2436 // more than one splitter will disappear in one iteration (bug 5998).
2437 for (; d.splitter_->count() > empty_twa; ) {
2438 TabWorkArea * twa = d.tabWorkArea(empty_twa);
2440 if (twa->count() == 0)
2443 setCurrentWorkArea(twa->currentWorkArea());
2444 if (!closeTabWorkArea(twa))
2452 bool GuiView::closeWorkArea(GuiWorkArea * wa, bool close_buffer)
2457 Buffer & buf = wa->bufferView().buffer();
2459 if (close_buffer && GuiViewPrivate::busyBuffers.contains(&buf)) {
2460 Alert::warning(_("Close document"),
2461 _("Document could not be closed because it is being processed by LyX."));
2466 return closeBuffer(buf);
2468 if (!inMultiTabs(wa))
2469 if (!saveBufferIfNeeded(buf, true))
2477 bool GuiView::closeBuffer(Buffer & buf)
2479 // If we are in a close_event all children will be closed in some time,
2480 // so no need to do it here. This will ensure that the children end up
2481 // in the session file in the correct order. If we close the master
2482 // buffer, we can close or release the child buffers here too.
2483 bool success = true;
2485 ListOfBuffers clist = buf.getChildren();
2486 ListOfBuffers::const_iterator it = clist.begin();
2487 ListOfBuffers::const_iterator const bend = clist.end();
2488 for (; it != bend; ++it) {
2489 // If a child is dirty, do not close
2490 // without user intervention
2491 //FIXME: should we look in other tabworkareas?
2492 Buffer * child_buf = *it;
2493 GuiWorkArea * child_wa = workArea(*child_buf);
2495 if (!closeWorkArea(child_wa, true)) {
2500 theBufferList().releaseChild(&buf, child_buf);
2504 // goto bookmark to update bookmark pit.
2505 //FIXME: we should update only the bookmarks related to this buffer!
2506 LYXERR(Debug::DEBUG, "GuiView::closeBuffer()");
2507 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
2508 guiApp->gotoBookmark(i+1, false, false);
2510 if (saveBufferIfNeeded(buf, false)) {
2511 buf.removeAutosaveFile();
2512 theBufferList().release(&buf);
2516 // open all children again to avoid a crash because of dangling
2517 // pointers (bug 6603)
2523 bool GuiView::closeTabWorkArea(TabWorkArea * twa)
2525 while (twa == d.currentTabWorkArea()) {
2526 twa->setCurrentIndex(twa->count()-1);
2528 GuiWorkArea * wa = twa->currentWorkArea();
2529 Buffer & b = wa->bufferView().buffer();
2531 // We only want to close the buffer if the same buffer is not visible
2532 // in another view, and if this is not a child and if we are closing
2533 // a view (not a tabgroup).
2534 bool const close_buffer =
2535 !inOtherView(b) && !b.parent() && closing_;
2537 if (!closeWorkArea(wa, close_buffer))
2544 bool GuiView::saveBufferIfNeeded(Buffer & buf, bool hiding)
2546 if (buf.isClean() || buf.paragraphs().empty())
2549 // Switch to this Buffer.
2554 if (buf.isUnnamed())
2555 file = from_utf8(buf.fileName().onlyFileName());
2557 file = buf.fileName().displayName(30);
2559 // Bring this window to top before asking questions.
2564 if (hiding && buf.isUnnamed()) {
2565 docstring const text = bformat(_("The document %1$s has not been "
2566 "saved yet.\n\nDo you want to save "
2567 "the document?"), file);
2568 ret = Alert::prompt(_("Save new document?"),
2569 text, 0, 1, _("&Save"), _("&Cancel"));
2573 docstring const text = bformat(_("The document %1$s has unsaved changes."
2574 "\n\nDo you want to save the document or discard the changes?"), file);
2575 ret = Alert::prompt(_("Save changed document?"),
2576 text, 0, 2, _("&Save"), _("&Discard"), _("&Cancel"));
2581 if (!saveBuffer(buf))
2585 // If we crash after this we could have no autosave file
2586 // but I guess this is really improbable (Jug).
2587 // Sometimes improbable things happen:
2588 // - see bug http://www.lyx.org/trac/ticket/6587 (ps)
2589 // buf.removeAutosaveFile();
2591 // revert all changes
2602 bool GuiView::inMultiTabs(GuiWorkArea * wa)
2604 Buffer & buf = wa->bufferView().buffer();
2606 for (int i = 0; i != d.splitter_->count(); ++i) {
2607 GuiWorkArea * wa_ = d.tabWorkArea(i)->workArea(buf);
2608 if (wa_ && wa_ != wa)
2611 return inOtherView(buf);
2615 bool GuiView::inOtherView(Buffer & buf)
2617 QList<int> const ids = guiApp->viewIds();
2619 for (int i = 0; i != ids.size(); ++i) {
2623 if (guiApp->view(ids[i]).workArea(buf))
2630 void GuiView::gotoNextOrPreviousBuffer(NextOrPrevious np)
2632 if (!documentBufferView())
2635 if (TabWorkArea * twa = d.currentTabWorkArea()) {
2636 Buffer * const curbuf = &documentBufferView()->buffer();
2637 int nwa = twa->count();
2638 for (int i = 0; i < nwa; ++i) {
2639 if (&workArea(i)->bufferView().buffer() == curbuf) {
2641 if (np == NEXTBUFFER)
2642 next_index = (i == nwa - 1 ? 0 : i + 1);
2644 next_index = (i == 0 ? nwa - 1 : i - 1);
2645 setBuffer(&workArea(next_index)->bufferView().buffer());
2653 /// make sure the document is saved
2654 static bool ensureBufferClean(Buffer * buffer)
2656 LASSERT(buffer, return false);
2657 if (buffer->isClean() && !buffer->isUnnamed())
2660 docstring const file = buffer->fileName().displayName(30);
2663 if (!buffer->isUnnamed()) {
2664 text = bformat(_("The document %1$s has unsaved "
2665 "changes.\n\nDo you want to save "
2666 "the document?"), file);
2667 title = _("Save changed document?");
2670 text = bformat(_("The document %1$s has not been "
2671 "saved yet.\n\nDo you want to save "
2672 "the document?"), file);
2673 title = _("Save new document?");
2675 int const ret = Alert::prompt(title, text, 0, 1, _("&Save"), _("&Cancel"));
2678 dispatch(FuncRequest(LFUN_BUFFER_WRITE));
2680 return buffer->isClean() && !buffer->isUnnamed();
2684 bool GuiView::reloadBuffer(Buffer & buf)
2686 Buffer::ReadStatus status = buf.reload();
2687 return status == Buffer::ReadSuccess;
2691 void GuiView::checkExternallyModifiedBuffers()
2693 BufferList::iterator bit = theBufferList().begin();
2694 BufferList::iterator const bend = theBufferList().end();
2695 for (; bit != bend; ++bit) {
2696 Buffer * buf = *bit;
2697 if (buf->fileName().exists()
2698 && buf->isExternallyModified(Buffer::checksum_method)) {
2699 docstring text = bformat(_("Document \n%1$s\n has been externally modified."
2700 " Reload now? Any local changes will be lost."),
2701 from_utf8(buf->absFileName()));
2702 int const ret = Alert::prompt(_("Reload externally changed document?"),
2703 text, 0, 1, _("&Reload"), _("&Cancel"));
2711 void GuiView::dispatchVC(FuncRequest const & cmd, DispatchResult & dr)
2713 Buffer * buffer = documentBufferView()
2714 ? &(documentBufferView()->buffer()) : 0;
2716 switch (cmd.action()) {
2717 case LFUN_VC_REGISTER:
2718 if (!buffer || !ensureBufferClean(buffer))
2720 if (!buffer->lyxvc().inUse()) {
2721 if (buffer->lyxvc().registrer()) {
2722 reloadBuffer(*buffer);
2723 dr.suppressMessageUpdate();
2728 case LFUN_VC_CHECK_IN:
2729 if (!buffer || !ensureBufferClean(buffer))
2731 if (buffer->lyxvc().inUse() && !buffer->isReadonly()) {
2732 dr.setMessage(buffer->lyxvc().checkIn());
2733 if (!dr.message().empty())
2734 reloadBuffer(*buffer);
2738 case LFUN_VC_CHECK_OUT:
2739 if (!buffer || !ensureBufferClean(buffer))
2741 if (buffer->lyxvc().inUse()) {
2742 dr.setMessage(buffer->lyxvc().checkOut());
2743 reloadBuffer(*buffer);
2747 case LFUN_VC_LOCKING_TOGGLE:
2748 LASSERT(buffer, return);
2749 if (!ensureBufferClean(buffer) || buffer->isReadonly())
2751 if (buffer->lyxvc().inUse()) {
2752 string res = buffer->lyxvc().lockingToggle();
2754 frontend::Alert::error(_("Revision control error."),
2755 _("Error when setting the locking property."));
2758 reloadBuffer(*buffer);
2763 case LFUN_VC_REVERT:
2764 LASSERT(buffer, return);
2765 if (buffer->lyxvc().revert()) {
2766 reloadBuffer(*buffer);
2767 dr.suppressMessageUpdate();
2771 case LFUN_VC_UNDO_LAST:
2772 LASSERT(buffer, return);
2773 buffer->lyxvc().undoLast();
2774 reloadBuffer(*buffer);
2775 dr.suppressMessageUpdate();
2778 case LFUN_VC_REPO_UPDATE:
2779 LASSERT(buffer, return);
2780 if (ensureBufferClean(buffer)) {
2781 dr.setMessage(buffer->lyxvc().repoUpdate());
2782 checkExternallyModifiedBuffers();
2786 case LFUN_VC_COMMAND: {
2787 string flag = cmd.getArg(0);
2788 if (buffer && contains(flag, 'R') && !ensureBufferClean(buffer))
2791 if (contains(flag, 'M')) {
2792 if (!Alert::askForText(message, _("LyX VC: Log Message")))
2795 string path = cmd.getArg(1);
2796 if (contains(path, "$$p") && buffer)
2797 path = subst(path, "$$p", buffer->filePath());
2798 LYXERR(Debug::LYXVC, "Directory: " << path);
2800 if (!pp.isReadableDirectory()) {
2801 lyxerr << _("Directory is not accessible.") << endl;
2804 support::PathChanger p(pp);
2806 string command = cmd.getArg(2);
2807 if (command.empty())
2810 command = subst(command, "$$i", buffer->absFileName());
2811 command = subst(command, "$$p", buffer->filePath());
2813 command = subst(command, "$$m", to_utf8(message));
2814 LYXERR(Debug::LYXVC, "Command: " << command);
2816 one.startscript(Systemcall::Wait, command);
2820 if (contains(flag, 'I'))
2821 buffer->markDirty();
2822 if (contains(flag, 'R'))
2823 reloadBuffer(*buffer);
2828 case LFUN_VC_COMPARE: {
2830 if (cmd.argument().empty()) {
2831 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "comparehistory"));
2835 string rev1 = cmd.getArg(0);
2839 if (!buffer->lyxvc().prepareFileRevision(rev1, f1))
2842 if (isStrInt(rev1) && convert<int>(rev1) <= 0) {
2843 f2 = buffer->absFileName();
2845 string rev2 = cmd.getArg(1);
2849 if (!buffer->lyxvc().prepareFileRevision(rev2, f2))
2853 LYXERR(Debug::LYXVC, "Launching comparison for fetched revisions:\n" <<
2854 f1 << "\n" << f2 << "\n" );
2855 string par = "compare run " + quoteName(f1) + " " + quoteName(f2);
2856 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, par));
2866 void GuiView::openChildDocument(string const & fname)
2868 LASSERT(documentBufferView(), return);
2869 Buffer & buffer = documentBufferView()->buffer();
2870 FileName const filename = support::makeAbsPath(fname, buffer.filePath());
2871 documentBufferView()->saveBookmark(false);
2873 if (theBufferList().exists(filename)) {
2874 child = theBufferList().getBuffer(filename);
2877 message(bformat(_("Opening child document %1$s..."),
2878 makeDisplayPath(filename.absFileName())));
2879 child = loadDocument(filename, false);
2881 // Set the parent name of the child document.
2882 // This makes insertion of citations and references in the child work,
2883 // when the target is in the parent or another child document.
2885 child->setParent(&buffer);
2889 bool GuiView::goToFileRow(string const & argument)
2893 size_t i = argument.find_last_of(' ');
2894 if (i != string::npos) {
2895 file_name = os::internal_path(trim(argument.substr(0, i)));
2896 istringstream is(argument.substr(i + 1));
2901 if (i == string::npos) {
2902 LYXERR0("Wrong argument: " << argument);
2906 string const abstmp = package().temp_dir().absFileName();
2907 string const realtmp = package().temp_dir().realPath();
2908 // We have to use os::path_prefix_is() here, instead of
2909 // simply prefixIs(), because the file name comes from
2910 // an external application and may need case adjustment.
2911 if (os::path_prefix_is(file_name, abstmp, os::CASE_ADJUSTED)
2912 || os::path_prefix_is(file_name, realtmp, os::CASE_ADJUSTED)) {
2913 // Needed by inverse dvi search. If it is a file
2914 // in tmpdir, call the apropriated function.
2915 // If tmpdir is a symlink, we may have the real
2916 // path passed back, so we correct for that.
2917 if (!prefixIs(file_name, abstmp))
2918 file_name = subst(file_name, realtmp, abstmp);
2919 buf = theBufferList().getBufferFromTmp(file_name);
2921 // Must replace extension of the file to be .lyx
2922 // and get full path
2923 FileName const s = fileSearch(string(),
2924 support::changeExtension(file_name, ".lyx"), "lyx");
2925 // Either change buffer or load the file
2926 if (theBufferList().exists(s))
2927 buf = theBufferList().getBuffer(s);
2928 else if (s.exists()) {
2929 buf = loadDocument(s);
2934 _("File does not exist: %1$s"),
2935 makeDisplayPath(file_name)));
2940 documentBufferView()->setCursorFromRow(row);
2945 #if (QT_VERSION >= 0x040400)
2947 docstring GuiView::GuiViewPrivate::runAndDestroy(const T& func, Buffer const * orig, Buffer * buffer, string const & format, string const & msg)
2949 bool const update_unincluded =
2950 buffer->params().maintain_unincluded_children
2951 && !buffer->params().getIncludedChildren().empty();
2952 bool const success = func(format, update_unincluded);
2954 busyBuffers.remove(orig);
2955 if (msg == "preview") {
2957 ? bformat(_("Successful preview of format: %1$s"), from_utf8(format))
2958 : bformat(_("Error while previewing format: %1$s"), from_utf8(format));
2961 ? bformat(_("Successful export to format: %1$s"), from_utf8(format))
2962 : bformat(_("Error while exporting format: %1$s"), from_utf8(format));
2966 docstring GuiView::GuiViewPrivate::compileAndDestroy(Buffer const * orig, Buffer * buffer, string const & format)
2968 bool (Buffer::* mem_func)(std::string const &, bool, bool) const = &Buffer::doExport;
2969 return runAndDestroy(bind(mem_func, buffer, _1, true, _2), orig, buffer, format, "export");
2973 docstring GuiView::GuiViewPrivate::exportAndDestroy(Buffer const * orig, Buffer * buffer, string const & format)
2975 bool (Buffer::* mem_func)(std::string const &, bool, bool) const = &Buffer::doExport;
2976 return runAndDestroy(bind(mem_func, buffer, _1, false, _2), orig, buffer, format, "export");
2980 docstring GuiView::GuiViewPrivate::previewAndDestroy(Buffer const * orig, Buffer * buffer, string const & format)
2982 bool(Buffer::* mem_func)(std::string const &, bool) const = &Buffer::preview;
2983 return runAndDestroy(bind(mem_func, buffer, _1, _2), orig, buffer, format, "preview");
2988 // not used, but the linker needs them
2990 docstring GuiView::GuiViewPrivate::compileAndDestroy(
2991 Buffer const *, Buffer *, string const &)
2997 docstring GuiView::GuiViewPrivate::exportAndDestroy(
2998 Buffer const *, Buffer *, string const &)
3004 docstring GuiView::GuiViewPrivate::previewAndDestroy(
3005 Buffer const *, Buffer *, string const &)
3013 bool GuiView::GuiViewPrivate::asyncBufferProcessing(
3014 string const & argument,
3015 Buffer const * used_buffer,
3016 docstring const & msg,
3017 docstring (*asyncFunc)(Buffer const *, Buffer *, string const &),
3018 bool (Buffer::*syncFunc)(string const &, bool, bool) const,
3019 bool (Buffer::*previewFunc)(string const &, bool) const)
3024 string format = argument;
3026 format = used_buffer->getDefaultOutputFormat();
3028 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
3029 gv_->processingThreadStarted();
3031 progress_->clearMessages();
3034 GuiViewPrivate::busyBuffers.insert(used_buffer);
3035 QFuture<docstring> f = QtConcurrent::run(
3038 used_buffer->clone(),
3040 setPreviewFuture(f);
3041 last_export_format = used_buffer->bufferFormat();
3044 // We are asynchronous, so we don't know here anything about the success
3048 // TODO check here if it breaks exporting with Qt < 4.4
3049 bool const update_unincluded =
3050 used_buffer->params().maintain_unincluded_children &&
3051 !used_buffer->params().getIncludedChildren().empty();
3052 return (used_buffer->*syncFunc)(format, true, update_unincluded);
3053 } else if (previewFunc) {
3054 return (used_buffer->*previewFunc)(format, false);
3061 void GuiView::dispatchToBufferView(FuncRequest const & cmd, DispatchResult & dr)
3063 BufferView * bv = currentBufferView();
3066 // Let the current BufferView dispatch its own actions.
3067 bv->dispatch(cmd, dr);
3068 if (dr.dispatched())
3071 // Try with the document BufferView dispatch if any.
3072 BufferView * doc_bv = documentBufferView();
3074 doc_bv->dispatch(cmd, dr);
3075 if (dr.dispatched())
3079 // Then let the current Cursor dispatch its own actions.
3080 bv->cursor().dispatch(cmd);
3082 // update completion. We do it here and not in
3083 // processKeySym to avoid another redraw just for a
3084 // changed inline completion
3085 if (cmd.origin() == FuncRequest::KEYBOARD) {
3086 if (cmd.action() == LFUN_SELF_INSERT
3087 || (cmd.action() == LFUN_ERT_INSERT && bv->cursor().inMathed()))
3088 updateCompletion(bv->cursor(), true, true);
3089 else if (cmd.action() == LFUN_CHAR_DELETE_BACKWARD)
3090 updateCompletion(bv->cursor(), false, true);
3092 updateCompletion(bv->cursor(), false, false);
3095 dr = bv->cursor().result();
3099 void GuiView::dispatch(FuncRequest const & cmd, DispatchResult & dr)
3101 BufferView * bv = currentBufferView();
3102 // By default we won't need any update.
3103 dr.screenUpdate(Update::None);
3104 // assume cmd will be dispatched
3105 dr.dispatched(true);
3107 Buffer * doc_buffer = documentBufferView()
3108 ? &(documentBufferView()->buffer()) : 0;
3110 if (cmd.origin() == FuncRequest::TOC) {
3111 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
3112 // FIXME: do we need to pass a DispatchResult object here?
3113 toc->doDispatch(bv->cursor(), cmd);
3117 string const argument = to_utf8(cmd.argument());
3119 switch(cmd.action()) {
3120 case LFUN_BUFFER_CHILD_OPEN:
3121 openChildDocument(to_utf8(cmd.argument()));
3124 case LFUN_BUFFER_IMPORT:
3125 importDocument(to_utf8(cmd.argument()));
3128 case LFUN_BUFFER_EXPORT: {
3131 // GCC only sees strfwd.h when building merged
3132 if (::lyx::operator==(cmd.argument(), "custom")) {
3133 dispatch(FuncRequest(LFUN_DIALOG_SHOW, "sendto"), dr);
3136 #if QT_VERSION < 0x040400
3137 if (!doc_buffer->doExport(argument, false)) {
3139 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
3143 /* TODO/Review: Is it a problem to also export the children?
3144 See the update_unincluded flag */
3145 d.asyncBufferProcessing(argument,
3148 &GuiViewPrivate::exportAndDestroy,
3151 // TODO Inform user about success
3156 case LFUN_BUFFER_UPDATE: {
3157 d.asyncBufferProcessing(argument,
3160 &GuiViewPrivate::compileAndDestroy,
3165 case LFUN_BUFFER_VIEW: {
3166 d.asyncBufferProcessing(argument,
3168 _("Previewing ..."),
3169 &GuiViewPrivate::previewAndDestroy,
3174 case LFUN_MASTER_BUFFER_UPDATE: {
3175 d.asyncBufferProcessing(argument,
3176 (doc_buffer ? doc_buffer->masterBuffer() : 0),
3178 &GuiViewPrivate::compileAndDestroy,
3183 case LFUN_MASTER_BUFFER_VIEW: {
3184 d.asyncBufferProcessing(argument,
3185 (doc_buffer ? doc_buffer->masterBuffer() : 0),
3187 &GuiViewPrivate::previewAndDestroy,
3188 0, &Buffer::preview);
3191 case LFUN_BUFFER_SWITCH: {
3192 string const file_name = to_utf8(cmd.argument());
3193 if (!FileName::isAbsolute(file_name)) {
3195 dr.setMessage(_("Absolute filename expected."));
3199 Buffer * buffer = theBufferList().getBuffer(FileName(file_name));
3202 dr.setMessage(_("Document not loaded"));
3206 // Do we open or switch to the buffer in this view ?
3207 if (workArea(*buffer)
3208 || lyxrc.open_buffers_in_tabs || !documentBufferView()) {
3213 // Look for the buffer in other views
3214 QList<int> const ids = guiApp->viewIds();
3216 for (; i != ids.size(); ++i) {
3217 GuiView & gv = guiApp->view(ids[i]);
3218 if (gv.workArea(*buffer)) {
3219 gv.activateWindow();
3220 gv.setBuffer(buffer);
3225 // If necessary, open a new window as a last resort
3226 if (i == ids.size()) {
3227 lyx::dispatch(FuncRequest(LFUN_WINDOW_NEW));
3233 case LFUN_BUFFER_NEXT:
3234 gotoNextOrPreviousBuffer(NEXTBUFFER);
3237 case LFUN_BUFFER_PREVIOUS:
3238 gotoNextOrPreviousBuffer(PREVBUFFER);
3241 case LFUN_COMMAND_EXECUTE: {
3242 bool const show_it = cmd.argument() != "off";
3243 // FIXME: this is a hack, "minibuffer" should not be
3245 if (GuiToolbar * t = toolbar("minibuffer")) {
3246 t->setVisible(show_it);
3247 if (show_it && t->commandBuffer())
3248 t->commandBuffer()->setFocus();
3252 case LFUN_DROP_LAYOUTS_CHOICE:
3253 d.layout_->showPopup();
3256 case LFUN_MENU_OPEN:
3257 if (QMenu * menu = guiApp->menus().menu(toqstr(cmd.argument()), *this))
3258 menu->exec(QCursor::pos());
3261 case LFUN_FILE_INSERT:
3262 insertLyXFile(cmd.argument());
3265 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
3266 insertPlaintextFile(cmd.argument(), true);
3269 case LFUN_FILE_INSERT_PLAINTEXT:
3270 insertPlaintextFile(cmd.argument(), false);
3273 case LFUN_BUFFER_RELOAD: {
3274 LASSERT(doc_buffer, break);
3277 if (!doc_buffer->isClean()) {
3278 docstring const file =
3279 makeDisplayPath(doc_buffer->absFileName(), 20);
3280 docstring text = bformat(_("Any changes will be lost. "
3281 "Are you sure you want to revert to the saved version "
3282 "of the document %1$s?"), file);
3283 ret = Alert::prompt(_("Revert to saved document?"),
3284 text, 1, 1, _("&Revert"), _("&Cancel"));
3288 doc_buffer->markClean();
3289 reloadBuffer(*doc_buffer);
3290 dr.forceBufferUpdate();
3295 case LFUN_BUFFER_WRITE:
3296 LASSERT(doc_buffer, break);
3297 saveBuffer(*doc_buffer);
3300 case LFUN_BUFFER_WRITE_AS:
3301 LASSERT(doc_buffer, break);
3302 renameBuffer(*doc_buffer, cmd.argument());
3305 case LFUN_BUFFER_WRITE_ALL: {
3306 Buffer * first = theBufferList().first();
3309 message(_("Saving all documents..."));
3310 // We cannot use a for loop as the buffer list cycles.
3313 if (!b->isClean()) {
3315 LYXERR(Debug::ACTION, "Saved " << b->absFileName());
3317 b = theBufferList().next(b);
3318 } while (b != first);
3319 dr.setMessage(_("All documents saved."));
3323 case LFUN_BUFFER_CLOSE:
3327 case LFUN_BUFFER_CLOSE_ALL:
3331 case LFUN_TOOLBAR_TOGGLE: {
3332 string const name = cmd.getArg(0);
3333 if (GuiToolbar * t = toolbar(name))
3338 case LFUN_DIALOG_UPDATE: {
3339 string const name = to_utf8(cmd.argument());
3340 if (name == "prefs" || name == "document")
3341 updateDialog(name, string());
3342 else if (name == "paragraph")
3343 lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
3344 else if (currentBufferView()) {
3345 Inset * inset = currentBufferView()->editedInset(name);
3346 // Can only update a dialog connected to an existing inset
3348 // FIXME: get rid of this indirection; GuiView ask the inset
3349 // if he is kind enough to update itself...
3350 FuncRequest fr(LFUN_INSET_DIALOG_UPDATE, cmd.argument());
3351 //FIXME: pass DispatchResult here?
3352 inset->dispatch(currentBufferView()->cursor(), fr);
3358 case LFUN_DIALOG_TOGGLE: {
3359 if (isDialogVisible(cmd.getArg(0)))
3360 dispatch(FuncRequest(LFUN_DIALOG_HIDE, cmd.argument()), dr);
3362 dispatch(FuncRequest(LFUN_DIALOG_SHOW, cmd.argument()), dr);
3366 case LFUN_DIALOG_DISCONNECT_INSET:
3367 disconnectDialog(to_utf8(cmd.argument()));
3370 case LFUN_DIALOG_HIDE: {
3371 guiApp->hideDialogs(to_utf8(cmd.argument()), 0);
3375 case LFUN_DIALOG_SHOW: {
3376 string const name = cmd.getArg(0);
3377 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
3379 if (name == "character") {
3380 data = freefont2string();
3382 showDialog("character", data);
3383 } else if (name == "latexlog") {
3384 Buffer::LogType type;
3385 string const logfile = doc_buffer->logName(&type);
3387 case Buffer::latexlog:
3390 case Buffer::buildlog:
3394 data += Lexer::quoteString(logfile);
3395 showDialog("log", data);
3396 } else if (name == "vclog") {
3397 string const data = "vc " +
3398 Lexer::quoteString(doc_buffer->lyxvc().getLogFile());
3399 showDialog("log", data);
3400 } else if (name == "symbols") {
3401 data = bv->cursor().getEncoding()->name();
3403 showDialog("symbols", data);
3405 } else if (name == "prefs" && isFullScreen()) {
3406 lfunUiToggle("fullscreen");
3407 showDialog("prefs", data);
3409 showDialog(name, data);
3414 dr.setMessage(cmd.argument());
3417 case LFUN_UI_TOGGLE: {
3418 string arg = cmd.getArg(0);
3419 if (!lfunUiToggle(arg)) {
3420 docstring const msg = "ui-toggle " + _("%1$s unknown command!");
3421 dr.setMessage(bformat(msg, from_utf8(arg)));
3423 // Make sure the keyboard focus stays in the work area.
3428 case LFUN_SPLIT_VIEW: {
3429 LASSERT(doc_buffer, break);
3430 string const orientation = cmd.getArg(0);
3431 d.splitter_->setOrientation(orientation == "vertical"
3432 ? Qt::Vertical : Qt::Horizontal);
3433 TabWorkArea * twa = addTabWorkArea();
3434 GuiWorkArea * wa = twa->addWorkArea(*doc_buffer, *this);
3435 setCurrentWorkArea(wa);
3438 case LFUN_CLOSE_TAB_GROUP:
3439 if (TabWorkArea * twa = d.currentTabWorkArea()) {
3440 closeTabWorkArea(twa);
3441 d.current_work_area_ = 0;
3442 twa = d.currentTabWorkArea();
3443 // Switch to the next GuiWorkArea in the found TabWorkArea.
3445 // Make sure the work area is up to date.
3446 setCurrentWorkArea(twa->currentWorkArea());
3448 setCurrentWorkArea(0);
3453 case LFUN_COMPLETION_INLINE:
3454 if (d.current_work_area_)
3455 d.current_work_area_->completer().showInline();
3458 case LFUN_COMPLETION_POPUP:
3459 if (d.current_work_area_)
3460 d.current_work_area_->completer().showPopup();
3464 case LFUN_COMPLETION_COMPLETE:
3465 if (d.current_work_area_)
3466 d.current_work_area_->completer().tab();
3469 case LFUN_COMPLETION_CANCEL:
3470 if (d.current_work_area_) {
3471 if (d.current_work_area_->completer().popupVisible())
3472 d.current_work_area_->completer().hidePopup();
3474 d.current_work_area_->completer().hideInline();
3478 case LFUN_COMPLETION_ACCEPT:
3479 if (d.current_work_area_)
3480 d.current_work_area_->completer().activate();
3483 case LFUN_BUFFER_ZOOM_IN:
3484 case LFUN_BUFFER_ZOOM_OUT:
3485 if (cmd.argument().empty()) {
3486 if (cmd.action() == LFUN_BUFFER_ZOOM_IN)
3491 lyxrc.zoom += convert<int>(cmd.argument());
3493 if (lyxrc.zoom < 10)
3496 // The global QPixmapCache is used in GuiPainter to cache text
3497 // painting so we must reset it.
3498 QPixmapCache::clear();
3499 guiApp->fontLoader().update();
3500 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
3503 case LFUN_VC_REGISTER:
3504 case LFUN_VC_CHECK_IN:
3505 case LFUN_VC_CHECK_OUT:
3506 case LFUN_VC_REPO_UPDATE:
3507 case LFUN_VC_LOCKING_TOGGLE:
3508 case LFUN_VC_REVERT:
3509 case LFUN_VC_UNDO_LAST:
3510 case LFUN_VC_COMMAND:
3511 case LFUN_VC_COMPARE:
3512 dispatchVC(cmd, dr);
3515 case LFUN_SERVER_GOTO_FILE_ROW:
3516 goToFileRow(to_utf8(cmd.argument()));
3519 case LFUN_FORWARD_SEARCH: {
3520 FileName const path(doc_buffer->temppath());
3521 string const texname = doc_buffer->latexName();
3522 FileName const dviname(addName(path.absFileName(),
3523 support::changeExtension(texname, "dvi")));
3524 FileName const pdfname(addName(path.absFileName(),
3525 support::changeExtension(texname, "pdf")));
3526 if (!dviname.exists() && !pdfname.exists()) {
3527 dr.setMessage(_("Please, preview the document first."));
3530 string outname = dviname.onlyFileName();
3531 string command = lyxrc.forward_search_dvi;
3532 if (!dviname.exists() ||
3533 pdfname.lastModified() > dviname.lastModified()) {
3534 outname = pdfname.onlyFileName();
3535 command = lyxrc.forward_search_pdf;
3538 int row = doc_buffer->texrow().getRowFromIdPos(bv->cursor().paragraph().id(), bv->cursor().pos());
3539 LYXERR(Debug::ACTION, "Forward search: row:" << row
3540 << " id:" << bv->cursor().paragraph().id());
3541 if (!row || command.empty()) {
3542 dr.setMessage(_("Couldn't proceed."));
3545 string texrow = convert<string>(row);
3547 command = subst(command, "$$n", texrow);
3548 command = subst(command, "$$t", texname);
3549 command = subst(command, "$$o", outname);
3551 PathChanger p(path);
3553 one.startscript(Systemcall::DontWait, command);
3557 // The LFUN must be for one of BufferView, Buffer or Cursor;
3559 dispatchToBufferView(cmd, dr);
3563 // Part of automatic menu appearance feature.
3564 if (isFullScreen()) {
3565 if (menuBar()->isVisible() && lyxrc.full_screen_menubar)
3567 if (statusBar()->isVisible())
3568 statusBar()->hide();
3573 bool GuiView::lfunUiToggle(string const & ui_component)
3575 if (ui_component == "scrollbar") {
3576 // hide() is of no help
3577 if (d.current_work_area_->verticalScrollBarPolicy() ==
3578 Qt::ScrollBarAlwaysOff)
3580 d.current_work_area_->setVerticalScrollBarPolicy(
3581 Qt::ScrollBarAsNeeded);
3583 d.current_work_area_->setVerticalScrollBarPolicy(
3584 Qt::ScrollBarAlwaysOff);
3585 } else if (ui_component == "statusbar") {
3586 statusBar()->setVisible(!statusBar()->isVisible());
3587 } else if (ui_component == "menubar") {
3588 menuBar()->setVisible(!menuBar()->isVisible());
3590 #if QT_VERSION >= 0x040300
3591 if (ui_component == "frame") {
3593 getContentsMargins(&l, &t, &r, &b);
3594 //are the frames in default state?
3595 d.current_work_area_->setFrameStyle(QFrame::NoFrame);
3597 setContentsMargins(-2, -2, -2, -2);
3599 setContentsMargins(0, 0, 0, 0);
3603 if (ui_component == "fullscreen") {
3611 void GuiView::toggleFullScreen()
3613 if (isFullScreen()) {
3614 for (int i = 0; i != d.splitter_->count(); ++i)
3615 d.tabWorkArea(i)->setFullScreen(false);
3616 #if QT_VERSION >= 0x040300
3617 setContentsMargins(0, 0, 0, 0);
3619 setWindowState(windowState() ^ Qt::WindowFullScreen);
3622 statusBar()->show();
3625 hideDialogs("prefs", 0);
3626 for (int i = 0; i != d.splitter_->count(); ++i)
3627 d.tabWorkArea(i)->setFullScreen(true);
3628 #if QT_VERSION >= 0x040300
3629 setContentsMargins(-2, -2, -2, -2);
3632 setWindowState(windowState() ^ Qt::WindowFullScreen);
3633 statusBar()->hide();
3634 if (lyxrc.full_screen_menubar)
3636 if (lyxrc.full_screen_toolbars) {
3637 ToolbarMap::iterator end = d.toolbars_.end();
3638 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
3643 // give dialogs like the TOC a chance to adapt
3648 Buffer const * GuiView::updateInset(Inset const * inset)
3653 Buffer const * inset_buffer = &(inset->buffer());
3655 for (int i = 0; i != d.splitter_->count(); ++i) {
3656 GuiWorkArea * wa = d.tabWorkArea(i)->currentWorkArea();
3659 Buffer const * buffer = &(wa->bufferView().buffer());
3660 if (inset_buffer == buffer)
3661 wa->scheduleRedraw();
3663 return inset_buffer;
3667 void GuiView::restartCursor()
3669 /* When we move around, or type, it's nice to be able to see
3670 * the cursor immediately after the keypress.
3672 if (d.current_work_area_)
3673 d.current_work_area_->startBlinkingCursor();
3675 // Take this occasion to update the other GUI elements.
3681 void GuiView::updateCompletion(Cursor & cur, bool start, bool keep)
3683 if (d.current_work_area_)
3684 d.current_work_area_->completer().updateVisibility(cur, start, keep);
3689 // This list should be kept in sync with the list of insets in
3690 // src/insets/Inset.cpp. I.e., if a dialog goes with an inset, the
3691 // dialog should have the same name as the inset.
3692 // Changes should be also recorded in LFUN_DIALOG_SHOW doxygen
3693 // docs in LyXAction.cpp.
3695 char const * const dialognames[] = {
3697 "aboutlyx", "bibitem", "bibtex", "box", "branch", "changes", "character",
3698 "citation", "compare", "comparehistory", "document", "errorlist", "ert",
3699 "external", "file", "findreplace", "findreplaceadv", "float", "graphics",
3700 "href", "include", "index", "index_print", "info", "listings", "label", "line",
3701 "log", "mathdelimiter", "mathmatrix", "mathspace", "nomenclature",
3702 "nomencl_print", "note", "paragraph", "phantom", "prefs", "print", "ref",
3703 "sendto", "space", "spellchecker", "symbols", "tabular", "tabularcreate",
3704 "thesaurus", "texinfo", "toc", "view-source", "vspace", "wrap", "progress"};
3706 char const * const * const end_dialognames =
3707 dialognames + (sizeof(dialognames) / sizeof(char *));
3711 cmpCStr(char const * name) : name_(name) {}
3712 bool operator()(char const * other) {
3713 return strcmp(other, name_) == 0;
3720 bool isValidName(string const & name)
3722 return find_if(dialognames, end_dialognames,
3723 cmpCStr(name.c_str())) != end_dialognames;
3729 void GuiView::resetDialogs()
3731 // Make sure that no LFUN uses any GuiView.
3732 guiApp->setCurrentView(0);
3736 constructToolbars();
3737 guiApp->menus().fillMenuBar(menuBar(), this, false);
3738 d.layout_->updateContents(true);
3739 // Now update controls with current buffer.
3740 guiApp->setCurrentView(this);
3746 Dialog * GuiView::findOrBuild(string const & name, bool hide_it)
3748 if (!isValidName(name))
3751 map<string, DialogPtr>::iterator it = d.dialogs_.find(name);
3753 if (it != d.dialogs_.end()) {
3755 it->second->hideView();
3756 return it->second.get();
3759 Dialog * dialog = build(name);
3760 d.dialogs_[name].reset(dialog);
3761 if (lyxrc.allow_geometry_session)
3762 dialog->restoreSession();
3769 void GuiView::showDialog(string const & name, string const & data,
3772 triggerShowDialog(toqstr(name), toqstr(data), inset);
3776 void GuiView::doShowDialog(QString const & qname, QString const & qdata,
3782 const string name = fromqstr(qname);
3783 const string data = fromqstr(qdata);
3787 Dialog * dialog = findOrBuild(name, false);
3789 bool const visible = dialog->isVisibleView();
3790 dialog->showData(data);
3791 if (inset && currentBufferView())
3792 currentBufferView()->editInset(name, inset);
3793 // We only set the focus to the new dialog if it was not yet
3794 // visible in order not to change the existing previous behaviour
3796 // activateWindow is needed for floating dockviews
3797 dialog->asQWidget()->raise();
3798 dialog->asQWidget()->activateWindow();
3799 dialog->asQWidget()->setFocus();
3803 catch (ExceptionMessage const & ex) {
3811 bool GuiView::isDialogVisible(string const & name) const
3813 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3814 if (it == d.dialogs_.end())
3816 return it->second.get()->isVisibleView() && !it->second.get()->isClosing();
3820 void GuiView::hideDialog(string const & name, Inset * inset)
3822 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3823 if (it == d.dialogs_.end())
3827 if (!currentBufferView())
3829 if (inset != currentBufferView()->editedInset(name))
3833 Dialog * const dialog = it->second.get();
3834 if (dialog->isVisibleView())
3836 if (currentBufferView())
3837 currentBufferView()->editInset(name, 0);
3841 void GuiView::disconnectDialog(string const & name)
3843 if (!isValidName(name))
3845 if (currentBufferView())
3846 currentBufferView()->editInset(name, 0);
3850 void GuiView::hideAll() const
3852 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
3853 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3855 for(; it != end; ++it)
3856 it->second->hideView();
3860 void GuiView::updateDialogs()
3862 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
3863 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3865 for(; it != end; ++it) {
3866 Dialog * dialog = it->second.get();
3868 if (dialog->needBufferOpen() && !documentBufferView())
3869 hideDialog(fromqstr(dialog->name()), 0);
3870 else if (dialog->isVisibleView())
3871 dialog->checkStatus();
3878 Dialog * createDialog(GuiView & lv, string const & name);
3880 // will be replaced by a proper factory...
3881 Dialog * createGuiAbout(GuiView & lv);
3882 Dialog * createGuiBibtex(GuiView & lv);
3883 Dialog * createGuiChanges(GuiView & lv);
3884 Dialog * createGuiCharacter(GuiView & lv);
3885 Dialog * createGuiCitation(GuiView & lv);
3886 Dialog * createGuiCompare(GuiView & lv);
3887 Dialog * createGuiCompareHistory(GuiView & lv);
3888 Dialog * createGuiDelimiter(GuiView & lv);
3889 Dialog * createGuiDocument(GuiView & lv);
3890 Dialog * createGuiErrorList(GuiView & lv);
3891 Dialog * createGuiExternal(GuiView & lv);
3892 Dialog * createGuiGraphics(GuiView & lv);
3893 Dialog * createGuiInclude(GuiView & lv);
3894 Dialog * createGuiIndex(GuiView & lv);
3895 Dialog * createGuiListings(GuiView & lv);
3896 Dialog * createGuiLog(GuiView & lv);
3897 Dialog * createGuiMathMatrix(GuiView & lv);
3898 Dialog * createGuiNote(GuiView & lv);
3899 Dialog * createGuiParagraph(GuiView & lv);
3900 Dialog * createGuiPhantom(GuiView & lv);
3901 Dialog * createGuiPreferences(GuiView & lv);
3902 Dialog * createGuiPrint(GuiView & lv);
3903 Dialog * createGuiPrintindex(GuiView & lv);
3904 Dialog * createGuiRef(GuiView & lv);
3905 Dialog * createGuiSearch(GuiView & lv);
3906 Dialog * createGuiSearchAdv(GuiView & lv);
3907 Dialog * createGuiSendTo(GuiView & lv);
3908 Dialog * createGuiShowFile(GuiView & lv);
3909 Dialog * createGuiSpellchecker(GuiView & lv);
3910 Dialog * createGuiSymbols(GuiView & lv);
3911 Dialog * createGuiTabularCreate(GuiView & lv);
3912 Dialog * createGuiTexInfo(GuiView & lv);
3913 Dialog * createGuiToc(GuiView & lv);
3914 Dialog * createGuiThesaurus(GuiView & lv);
3915 Dialog * createGuiViewSource(GuiView & lv);
3916 Dialog * createGuiWrap(GuiView & lv);
3917 Dialog * createGuiProgressView(GuiView & lv);
3921 Dialog * GuiView::build(string const & name)
3923 LASSERT(isValidName(name), return 0);
3925 Dialog * dialog = createDialog(*this, name);
3929 if (name == "aboutlyx")
3930 return createGuiAbout(*this);
3931 if (name == "bibtex")
3932 return createGuiBibtex(*this);
3933 if (name == "changes")
3934 return createGuiChanges(*this);
3935 if (name == "character")
3936 return createGuiCharacter(*this);
3937 if (name == "citation")
3938 return createGuiCitation(*this);
3939 if (name == "compare")
3940 return createGuiCompare(*this);
3941 if (name == "comparehistory")
3942 return createGuiCompareHistory(*this);
3943 if (name == "document")
3944 return createGuiDocument(*this);
3945 if (name == "errorlist")
3946 return createGuiErrorList(*this);
3947 if (name == "external")
3948 return createGuiExternal(*this);
3950 return createGuiShowFile(*this);
3951 if (name == "findreplace")
3952 return createGuiSearch(*this);
3953 if (name == "findreplaceadv")
3954 return createGuiSearchAdv(*this);
3955 if (name == "graphics")
3956 return createGuiGraphics(*this);
3957 if (name == "include")
3958 return createGuiInclude(*this);
3959 if (name == "index")
3960 return createGuiIndex(*this);
3961 if (name == "index_print")
3962 return createGuiPrintindex(*this);
3963 if (name == "listings")
3964 return createGuiListings(*this);
3966 return createGuiLog(*this);
3967 if (name == "mathdelimiter")
3968 return createGuiDelimiter(*this);
3969 if (name == "mathmatrix")
3970 return createGuiMathMatrix(*this);
3972 return createGuiNote(*this);
3973 if (name == "paragraph")
3974 return createGuiParagraph(*this);
3975 if (name == "phantom")
3976 return createGuiPhantom(*this);
3977 if (name == "prefs")
3978 return createGuiPreferences(*this);
3979 if (name == "print")
3980 return createGuiPrint(*this);
3982 return createGuiRef(*this);
3983 if (name == "sendto")
3984 return createGuiSendTo(*this);
3985 if (name == "spellchecker")
3986 return createGuiSpellchecker(*this);
3987 if (name == "symbols")
3988 return createGuiSymbols(*this);
3989 if (name == "tabularcreate")
3990 return createGuiTabularCreate(*this);
3991 if (name == "texinfo")
3992 return createGuiTexInfo(*this);
3993 if (name == "thesaurus")
3994 return createGuiThesaurus(*this);
3996 return createGuiToc(*this);
3997 if (name == "view-source")
3998 return createGuiViewSource(*this);
4000 return createGuiWrap(*this);
4001 if (name == "progress")
4002 return createGuiProgressView(*this);
4008 } // namespace frontend
4011 #include "moc_GuiView.cpp"