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(processingThreadFinished()));
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()
553 QFutureWatcher<docstring> const * watcher =
554 static_cast<QFutureWatcher<docstring> const *>(sender());
555 message(watcher->result());
557 errors(d.last_export_format);
558 d.processing_cursor_timer_.stop();
559 restoreCursorShapes();
560 d.indicates_processing_ = false;
565 void GuiView::setCursorShapes(Qt::CursorShape)
570 void GuiView::restoreCursorShapes()
575 void GuiView::saveCursorShapes()
580 void GuiView::indicateProcessing()
585 void GuiView::processingThreadStarted()
590 void GuiView::processingThreadFinished()
596 void GuiView::saveLayout() const
599 settings.beginGroup("views");
600 settings.beginGroup(QString::number(id_));
602 settings.setValue("pos", pos());
603 settings.setValue("size", size());
605 settings.setValue("geometry", saveGeometry());
607 settings.setValue("layout", saveState(0));
608 settings.setValue("icon_size", iconSize());
612 bool GuiView::restoreLayout()
615 settings.beginGroup("views");
616 settings.beginGroup(QString::number(id_));
617 QString const icon_key = "icon_size";
618 if (!settings.contains(icon_key))
621 //code below is skipped when when ~/.config/LyX is (re)created
622 setIconSize(settings.value(icon_key).toSize());
624 QPoint pos = settings.value("pos", QPoint(50, 50)).toPoint();
625 QSize size = settings.value("size", QSize(690, 510)).toSize();
629 // Work-around for bug #6034: the window ends up in an undetermined
630 // state when trying to restore a maximized window when it is
631 // already maximized.
632 if (!(windowState() & Qt::WindowMaximized))
633 if (!restoreGeometry(settings.value("geometry").toByteArray()))
634 setGeometry(50, 50, 690, 510);
636 // Make sure layout is correctly oriented.
637 setLayoutDirection(qApp->layoutDirection());
639 // Allow the toc and view-source dock widget to be restored if needed.
641 if ((dialog = findOrBuild("toc", true)))
642 // see bug 5082. At least setup title and enabled state.
643 // Visibility will be adjusted by restoreState below.
644 dialog->prepareView();
645 if ((dialog = findOrBuild("view-source", true)))
646 dialog->prepareView();
647 if ((dialog = findOrBuild("progress", true)))
648 dialog->prepareView();
650 if (!restoreState(settings.value("layout").toByteArray(), 0))
657 GuiToolbar * GuiView::toolbar(string const & name)
659 ToolbarMap::iterator it = d.toolbars_.find(name);
660 if (it != d.toolbars_.end())
663 LYXERR(Debug::GUI, "Toolbar::display: no toolbar named " << name);
668 void GuiView::constructToolbars()
670 ToolbarMap::iterator it = d.toolbars_.begin();
671 for (; it != d.toolbars_.end(); ++it)
675 // I don't like doing this here, but the standard toolbar
676 // destroys this object when it's destroyed itself (vfr)
677 d.layout_ = new LayoutBox(*this);
678 d.stack_widget_->addWidget(d.layout_);
679 d.layout_->move(0,0);
681 // extracts the toolbars from the backend
682 Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
683 Toolbars::Infos::iterator end = guiApp->toolbars().end();
684 for (; cit != end; ++cit)
685 d.toolbars_[cit->name] = new GuiToolbar(*cit, *this);
689 void GuiView::initToolbars()
691 // extracts the toolbars from the backend
692 Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
693 Toolbars::Infos::iterator end = guiApp->toolbars().end();
694 for (; cit != end; ++cit) {
695 GuiToolbar * tb = toolbar(cit->name);
698 int const visibility = guiApp->toolbars().defaultVisibility(cit->name);
699 bool newline = !(visibility & Toolbars::SAMEROW);
700 tb->setVisible(false);
701 tb->setVisibility(visibility);
703 if (visibility & Toolbars::TOP) {
705 addToolBarBreak(Qt::TopToolBarArea);
706 addToolBar(Qt::TopToolBarArea, tb);
709 if (visibility & Toolbars::BOTTOM) {
710 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
711 #if (QT_VERSION >= 0x040202)
713 addToolBarBreak(Qt::BottomToolBarArea);
715 addToolBar(Qt::BottomToolBarArea, tb);
718 if (visibility & Toolbars::LEFT) {
719 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
720 #if (QT_VERSION >= 0x040202)
722 addToolBarBreak(Qt::LeftToolBarArea);
724 addToolBar(Qt::LeftToolBarArea, tb);
727 if (visibility & Toolbars::RIGHT) {
728 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
729 #if (QT_VERSION >= 0x040202)
731 addToolBarBreak(Qt::RightToolBarArea);
733 addToolBar(Qt::RightToolBarArea, tb);
736 if (visibility & Toolbars::ON)
737 tb->setVisible(true);
742 TocModels & GuiView::tocModels()
744 return d.toc_models_;
748 void GuiView::setFocus()
750 LYXERR(Debug::DEBUG, "GuiView::setFocus()" << this);
751 QMainWindow::setFocus();
755 void GuiView::focusInEvent(QFocusEvent * e)
757 LYXERR(Debug::DEBUG, "GuiView::focusInEvent()" << this);
758 QMainWindow::focusInEvent(e);
759 // Make sure guiApp points to the correct view.
760 guiApp->setCurrentView(this);
761 if (currentMainWorkArea())
762 currentMainWorkArea()->setFocus();
763 else if (currentWorkArea())
764 currentWorkArea()->setFocus();
766 d.bg_widget_->setFocus();
770 QMenu * GuiView::createPopupMenu()
772 return d.toolBarPopup(this);
776 void GuiView::showEvent(QShowEvent * e)
778 LYXERR(Debug::GUI, "Passed Geometry "
779 << size().height() << "x" << size().width()
780 << "+" << pos().x() << "+" << pos().y());
782 if (d.splitter_->count() == 0)
783 // No work area, switch to the background widget.
786 QMainWindow::showEvent(e);
790 bool GuiView::closeScheduled()
797 /** Destroy only all tabbed WorkAreas. Destruction of other WorkAreas
798 ** is responsibility of the container (e.g., dialog)
800 void GuiView::closeEvent(QCloseEvent * close_event)
802 LYXERR(Debug::DEBUG, "GuiView::closeEvent()");
804 if (!GuiViewPrivate::busyBuffers.isEmpty()) {
805 Alert::warning(_("Exit LyX"),
806 _("LyX could not be closed because documents are being processed by LyX."));
807 close_event->setAccepted(false);
811 // If the user pressed the x (so we didn't call closeView
812 // programmatically), we want to clear all existing entries.
814 theSession().lastOpened().clear();
819 // it can happen that this event arrives without selecting the view,
820 // e.g. when clicking the close button on a background window.
822 if (!closeWorkAreaAll()) {
824 close_event->ignore();
828 // Make sure that nothing will use this to be closed View.
829 guiApp->unregisterView(this);
831 if (isFullScreen()) {
832 // Switch off fullscreen before closing.
837 // Make sure the timer time out will not trigger a statusbar update.
838 d.statusbar_timer_.stop();
840 // Saving fullscreen requires additional tweaks in the toolbar code.
841 // It wouldn't also work under linux natively.
842 if (lyxrc.allow_geometry_session) {
843 // Save this window geometry and layout.
845 // Then the toolbar private states.
846 ToolbarMap::iterator end = d.toolbars_.end();
847 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
848 it->second->saveSession();
849 // Now take care of all other dialogs:
850 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
851 for (; it!= d.dialogs_.end(); ++it)
852 it->second->saveSession();
855 close_event->accept();
859 void GuiView::dragEnterEvent(QDragEnterEvent * event)
861 if (event->mimeData()->hasUrls())
863 /// \todo Ask lyx-devel is this is enough:
864 /// if (event->mimeData()->hasFormat("text/plain"))
865 /// event->acceptProposedAction();
869 void GuiView::dropEvent(QDropEvent * event)
871 QList<QUrl> files = event->mimeData()->urls();
875 LYXERR(Debug::GUI, "GuiView::dropEvent: got URLs!");
876 for (int i = 0; i != files.size(); ++i) {
877 string const file = os::internal_path(fromqstr(
878 files.at(i).toLocalFile()));
882 string const ext = support::getExtension(file);
883 vector<const Format *> found_formats;
885 // Find all formats that have the correct extension.
886 vector<const Format *> const & import_formats
887 = theConverters().importableFormats();
888 vector<const Format *>::const_iterator it = import_formats.begin();
889 for (; it != import_formats.end(); ++it)
890 if ((*it)->extension() == ext)
891 found_formats.push_back(*it);
894 if (found_formats.size() >= 1) {
895 if (found_formats.size() > 1) {
896 //FIXME: show a dialog to choose the correct importable format
898 "Multiple importable formats found, selecting first");
900 string const arg = found_formats[0]->name() + " " + file;
901 cmd = FuncRequest(LFUN_BUFFER_IMPORT, arg);
904 //FIXME: do we have to explicitly check whether it's a lyx file?
906 "No formats found, trying to open it as a lyx file");
907 cmd = FuncRequest(LFUN_FILE_OPEN, file);
909 // add the functions to the queue
910 guiApp->addToFuncRequestQueue(cmd);
913 // now process the collected functions. We perform the events
914 // asynchronously. This prevents potential problems in case the
915 // BufferView is closed within an event.
916 guiApp->processFuncRequestQueueAsync();
920 void GuiView::message(docstring const & str)
922 if (ForkedProcess::iAmAChild())
925 // call is moved to GUI-thread by GuiProgress
926 d.progress_->appendMessage(toqstr(str));
930 void GuiView::clearMessageText()
932 message(docstring());
936 void GuiView::updateStatusBarMessage(QString const & str)
938 statusBar()->showMessage(str);
939 d.statusbar_timer_.stop();
940 d.statusbar_timer_.start(3000);
944 void GuiView::smallSizedIcons()
946 setIconSize(QSize(d.smallIconSize, d.smallIconSize));
950 void GuiView::normalSizedIcons()
952 setIconSize(QSize(d.normalIconSize, d.normalIconSize));
956 void GuiView::bigSizedIcons()
958 setIconSize(QSize(d.bigIconSize, d.bigIconSize));
962 void GuiView::clearMessage()
964 // FIXME: This code was introduced in r19643 to fix bug #4123. However,
965 // the hasFocus function mostly returns false, even if the focus is on
966 // a workarea in this view.
970 d.statusbar_timer_.stop();
974 void GuiView::updateWindowTitle(GuiWorkArea * wa)
976 if (wa != d.current_work_area_
977 || wa->bufferView().buffer().isInternal())
979 setWindowTitle(qt_("LyX: ") + wa->windowTitle());
980 setWindowIconText(wa->windowIconText());
984 void GuiView::on_currentWorkAreaChanged(GuiWorkArea * wa)
987 disconnectBufferView();
988 connectBufferView(wa->bufferView());
989 connectBuffer(wa->bufferView().buffer());
990 d.current_work_area_ = wa;
991 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
992 this, SLOT(updateWindowTitle(GuiWorkArea *)));
993 updateWindowTitle(wa);
997 // The document settings needs to be reinitialised.
998 updateDialog("document", "");
1000 // Buffer-dependent dialogs must be updated. This is done here because
1001 // some dialogs require buffer()->text.
1006 void GuiView::on_lastWorkAreaRemoved()
1009 // We already are in a close event. Nothing more to do.
1012 if (d.splitter_->count() > 1)
1013 // We have a splitter so don't close anything.
1016 // Reset and updates the dialogs.
1017 d.toc_models_.reset(0);
1018 updateDialog("document", "");
1021 resetWindowTitleAndIconText();
1024 if (lyxrc.open_buffers_in_tabs)
1025 // Nothing more to do, the window should stay open.
1028 if (guiApp->viewIds().size() > 1) {
1034 // On Mac we also close the last window because the application stay
1035 // resident in memory. On other platforms we don't close the last
1036 // window because this would quit the application.
1042 void GuiView::updateStatusBar()
1044 // let the user see the explicit message
1045 if (d.statusbar_timer_.isActive())
1052 void GuiView::showMessage()
1054 QString msg = toqstr(theGuiApp()->viewStatusMessage());
1055 if (msg.isEmpty()) {
1056 BufferView const * bv = currentBufferView();
1058 msg = toqstr(bv->cursor().currentState());
1060 msg = qt_("Welcome to LyX!");
1062 statusBar()->showMessage(msg);
1066 bool GuiView::event(QEvent * e)
1070 // Useful debug code:
1071 //case QEvent::ActivationChange:
1072 //case QEvent::WindowDeactivate:
1073 //case QEvent::Paint:
1074 //case QEvent::Enter:
1075 //case QEvent::Leave:
1076 //case QEvent::HoverEnter:
1077 //case QEvent::HoverLeave:
1078 //case QEvent::HoverMove:
1079 //case QEvent::StatusTip:
1080 //case QEvent::DragEnter:
1081 //case QEvent::DragLeave:
1082 //case QEvent::Drop:
1085 case QEvent::WindowActivate: {
1086 GuiView * old_view = guiApp->currentView();
1087 if (this == old_view) {
1089 return QMainWindow::event(e);
1091 if (old_view && old_view->currentBufferView()) {
1092 // save current selection to the selection buffer to allow
1093 // middle-button paste in this window.
1094 cap::saveSelection(old_view->currentBufferView()->cursor());
1096 guiApp->setCurrentView(this);
1097 if (d.current_work_area_) {
1098 BufferView & bv = d.current_work_area_->bufferView();
1099 connectBufferView(bv);
1100 connectBuffer(bv.buffer());
1101 // The document structure, name and dialogs might have
1102 // changed in another view.
1104 // The document settings needs to be reinitialised.
1105 updateDialog("document", "");
1108 resetWindowTitleAndIconText();
1111 return QMainWindow::event(e);
1114 case QEvent::ShortcutOverride: {
1117 #if (!defined Q_WS_X11) || (QT_VERSION >= 0x040500)
1118 if (isFullScreen() && menuBar()->isHidden()) {
1119 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
1120 // FIXME: we should also try to detect special LyX shortcut such as
1121 // Alt-P and Alt-M. Right now there is a hack in
1122 // GuiWorkArea::processKeySym() that hides again the menubar for
1124 if (ke->modifiers() & Qt::AltModifier && ke->key() != Qt::Key_Alt) {
1126 return QMainWindow::event(e);
1130 return QMainWindow::event(e);
1134 return QMainWindow::event(e);
1138 void GuiView::resetWindowTitleAndIconText()
1140 setWindowTitle(qt_("LyX"));
1141 setWindowIconText(qt_("LyX"));
1144 bool GuiView::focusNextPrevChild(bool /*next*/)
1151 bool GuiView::busy() const
1157 void GuiView::setBusy(bool busy)
1159 bool const busy_before = busy_ > 0;
1160 busy ? ++busy_ : --busy_;
1161 if ((busy_ > 0) == busy_before)
1162 // busy state didn't change
1165 if (d.current_work_area_) {
1166 d.current_work_area_->setUpdatesEnabled(!busy);
1168 d.current_work_area_->stopBlinkingCursor();
1170 d.current_work_area_->startBlinkingCursor();
1174 QApplication::setOverrideCursor(Qt::WaitCursor);
1176 QApplication::restoreOverrideCursor();
1180 GuiWorkArea * GuiView::workArea(int index)
1182 if (TabWorkArea * twa = d.currentTabWorkArea())
1183 if (index < twa->count())
1184 return dynamic_cast<GuiWorkArea *>(twa->widget(index));
1189 GuiWorkArea * GuiView::workArea(Buffer & buffer)
1191 if (currentWorkArea()
1192 && ¤tWorkArea()->bufferView().buffer() == &buffer)
1193 return (GuiWorkArea *) currentWorkArea();
1194 if (TabWorkArea * twa = d.currentTabWorkArea())
1195 return twa->workArea(buffer);
1200 GuiWorkArea * GuiView::addWorkArea(Buffer & buffer)
1202 // Automatically create a TabWorkArea if there are none yet.
1203 TabWorkArea * tab_widget = d.splitter_->count()
1204 ? d.currentTabWorkArea() : addTabWorkArea();
1205 return tab_widget->addWorkArea(buffer, *this);
1209 TabWorkArea * GuiView::addTabWorkArea()
1211 TabWorkArea * twa = new TabWorkArea;
1212 QObject::connect(twa, SIGNAL(currentWorkAreaChanged(GuiWorkArea *)),
1213 this, SLOT(on_currentWorkAreaChanged(GuiWorkArea *)));
1214 QObject::connect(twa, SIGNAL(lastWorkAreaRemoved()),
1215 this, SLOT(on_lastWorkAreaRemoved()));
1217 d.splitter_->addWidget(twa);
1218 d.stack_widget_->setCurrentWidget(d.splitter_);
1223 GuiWorkArea const * GuiView::currentWorkArea() const
1225 return d.current_work_area_;
1229 GuiWorkArea * GuiView::currentWorkArea()
1231 return d.current_work_area_;
1235 GuiWorkArea const * GuiView::currentMainWorkArea() const
1237 if (!d.currentTabWorkArea())
1239 return d.currentTabWorkArea()->currentWorkArea();
1243 GuiWorkArea * GuiView::currentMainWorkArea()
1245 if (!d.currentTabWorkArea())
1247 return d.currentTabWorkArea()->currentWorkArea();
1251 void GuiView::setCurrentWorkArea(GuiWorkArea * wa)
1253 LYXERR(Debug::DEBUG, "Setting current wa: " << wa << endl);
1255 d.current_work_area_ = 0;
1260 // FIXME: I've no clue why this is here and why it accesses
1261 // theGuiApp()->currentView, which might be 0 (bug 6464).
1262 // See also 27525 (vfr).
1263 if (theGuiApp()->currentView() == this
1264 && theGuiApp()->currentView()->currentWorkArea() == wa)
1267 if (currentBufferView())
1268 cap::saveSelection(currentBufferView()->cursor());
1270 theGuiApp()->setCurrentView(this);
1271 d.current_work_area_ = wa;
1273 // We need to reset this now, because it will need to be
1274 // right if the tabWorkArea gets reset in the for loop. We
1275 // will change it back if we aren't in that case.
1276 GuiWorkArea * const old_cmwa = d.current_main_work_area_;
1277 d.current_main_work_area_ = wa;
1279 for (int i = 0; i != d.splitter_->count(); ++i) {
1280 if (d.tabWorkArea(i)->setCurrentWorkArea(wa)) {
1281 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea()
1282 << ", Current main wa: " << currentMainWorkArea());
1287 d.current_main_work_area_ = old_cmwa;
1289 LYXERR(Debug::DEBUG, "This is not a tabbed wa");
1290 on_currentWorkAreaChanged(wa);
1291 BufferView & bv = wa->bufferView();
1292 bv.cursor().fixIfBroken();
1294 wa->setUpdatesEnabled(true);
1295 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() << ", Current main wa: " << currentMainWorkArea());
1299 void GuiView::removeWorkArea(GuiWorkArea * wa)
1301 LASSERT(wa, return);
1302 if (wa == d.current_work_area_) {
1304 disconnectBufferView();
1305 d.current_work_area_ = 0;
1306 d.current_main_work_area_ = 0;
1309 bool found_twa = false;
1310 for (int i = 0; i != d.splitter_->count(); ++i) {
1311 TabWorkArea * twa = d.tabWorkArea(i);
1312 if (twa->removeWorkArea(wa)) {
1313 // Found in this tab group, and deleted the GuiWorkArea.
1315 if (twa->count() != 0) {
1316 if (d.current_work_area_ == 0)
1317 // This means that we are closing the current GuiWorkArea, so
1318 // switch to the next GuiWorkArea in the found TabWorkArea.
1319 setCurrentWorkArea(twa->currentWorkArea());
1321 // No more WorkAreas in this tab group, so delete it.
1328 // It is not a tabbed work area (i.e., the search work area), so it
1329 // should be deleted by other means.
1330 LASSERT(found_twa, /* */);
1332 if (d.current_work_area_ == 0) {
1333 if (d.splitter_->count() != 0) {
1334 TabWorkArea * twa = d.currentTabWorkArea();
1335 setCurrentWorkArea(twa->currentWorkArea());
1337 // No more work areas, switch to the background widget.
1338 setCurrentWorkArea(0);
1344 LayoutBox * GuiView::getLayoutDialog() const
1350 void GuiView::updateLayoutList()
1353 d.layout_->updateContents(false);
1357 void GuiView::updateToolbars()
1359 ToolbarMap::iterator end = d.toolbars_.end();
1360 if (d.current_work_area_) {
1362 d.current_work_area_->bufferView().cursor().inMathed()
1363 && !d.current_work_area_->bufferView().cursor().inRegexped();
1365 lyx::getStatus(FuncRequest(LFUN_LAYOUT_TABULAR)).enabled();
1367 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).enabled() &&
1368 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).onOff(true);
1369 bool const mathmacrotemplate =
1370 lyx::getStatus(FuncRequest(LFUN_IN_MATHMACROTEMPLATE)).enabled();
1372 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1373 it->second->update(math, table, review, mathmacrotemplate);
1375 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1376 it->second->update(false, false, false, false);
1380 void GuiView::setBuffer(Buffer * newBuffer)
1382 LYXERR(Debug::DEBUG, "Setting buffer: " << newBuffer << endl);
1383 LASSERT(newBuffer, return);
1386 GuiWorkArea * wa = workArea(*newBuffer);
1388 newBuffer->masterBuffer()->updateBuffer();
1389 wa = addWorkArea(*newBuffer);
1390 // scroll to the position when the BufferView was last closed
1391 if (lyxrc.use_lastfilepos) {
1392 LastFilePosSection::FilePos filepos =
1393 theSession().lastFilePos().load(newBuffer->fileName());
1394 wa->bufferView().moveToPosition(filepos.pit, filepos.pos, 0, 0);
1397 //Disconnect the old buffer...there's no new one.
1400 connectBuffer(*newBuffer);
1401 connectBufferView(wa->bufferView());
1402 setCurrentWorkArea(wa);
1408 void GuiView::connectBuffer(Buffer & buf)
1410 buf.setGuiDelegate(this);
1414 void GuiView::disconnectBuffer()
1416 if (d.current_work_area_)
1417 d.current_work_area_->bufferView().buffer().setGuiDelegate(0);
1421 void GuiView::connectBufferView(BufferView & bv)
1423 bv.setGuiDelegate(this);
1427 void GuiView::disconnectBufferView()
1429 if (d.current_work_area_)
1430 d.current_work_area_->bufferView().setGuiDelegate(0);
1434 void GuiView::errors(string const & error_type, bool from_master)
1436 ErrorList & el = from_master ?
1437 currentBufferView()->buffer().masterBuffer()->errorList(error_type)
1438 : currentBufferView()->buffer().errorList(error_type);
1439 string data = error_type;
1441 data = "from_master|" + error_type;
1443 showDialog("errorlist", data);
1447 void GuiView::updateTocItem(string const & type, DocIterator const & dit)
1449 d.toc_models_.updateItem(toqstr(type), dit);
1453 void GuiView::structureChanged()
1455 d.toc_models_.reset(documentBufferView());
1456 // Navigator needs more than a simple update in this case. It needs to be
1458 updateDialog("toc", "");
1462 void GuiView::updateDialog(string const & name, string const & data)
1464 if (!isDialogVisible(name))
1467 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
1468 if (it == d.dialogs_.end())
1471 Dialog * const dialog = it->second.get();
1472 if (dialog->isVisibleView())
1473 dialog->initialiseParams(data);
1477 BufferView * GuiView::documentBufferView()
1479 return currentMainWorkArea()
1480 ? ¤tMainWorkArea()->bufferView()
1485 BufferView const * GuiView::documentBufferView() const
1487 return currentMainWorkArea()
1488 ? ¤tMainWorkArea()->bufferView()
1493 BufferView * GuiView::currentBufferView()
1495 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1499 BufferView const * GuiView::currentBufferView() const
1501 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1505 #if (QT_VERSION >= 0x040400)
1506 docstring GuiView::GuiViewPrivate::autosaveAndDestroy(
1507 Buffer const * orig, Buffer * buffer)
1509 bool const success = buffer->autoSave();
1511 busyBuffers.remove(orig);
1513 ? _("Automatic save done.")
1514 : _("Automatic save failed!");
1519 void GuiView::autoSave()
1521 LYXERR(Debug::INFO, "Running autoSave()");
1523 Buffer * buffer = documentBufferView()
1524 ? &documentBufferView()->buffer() : 0;
1528 #if (QT_VERSION >= 0x040400)
1529 GuiViewPrivate::busyBuffers.insert(buffer);
1530 QFuture<docstring> f = QtConcurrent::run(GuiViewPrivate::autosaveAndDestroy,
1531 buffer, buffer->clone());
1532 d.autosave_watcher_.setFuture(f);
1536 resetAutosaveTimers();
1540 void GuiView::resetAutosaveTimers()
1543 d.autosave_timeout_.restart();
1547 bool GuiView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1550 Buffer * buf = currentBufferView()
1551 ? ¤tBufferView()->buffer() : 0;
1552 Buffer * doc_buffer = documentBufferView()
1553 ? &(documentBufferView()->buffer()) : 0;
1555 // Check whether we need a buffer
1556 if (!lyxaction.funcHasFlag(cmd.action(), LyXAction::NoBuffer) && !buf) {
1557 // no, exit directly
1558 flag.message(from_utf8(N_("Command not allowed with"
1559 "out any document open")));
1560 flag.setEnabled(false);
1564 if (cmd.origin() == FuncRequest::TOC) {
1565 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
1566 if (!toc || !toc->getStatus(documentBufferView()->cursor(), cmd, flag))
1567 flag.setEnabled(false);
1571 switch(cmd.action()) {
1572 case LFUN_BUFFER_IMPORT:
1575 case LFUN_MASTER_BUFFER_UPDATE:
1576 case LFUN_MASTER_BUFFER_VIEW:
1577 enable = doc_buffer && doc_buffer->parent() != 0
1578 && !d.processing_thread_watcher_.isRunning();
1581 case LFUN_BUFFER_UPDATE:
1582 case LFUN_BUFFER_VIEW: {
1583 if (!doc_buffer || d.processing_thread_watcher_.isRunning()) {
1587 string format = to_utf8(cmd.argument());
1588 if (cmd.argument().empty())
1589 format = doc_buffer->getDefaultOutputFormat();
1590 enable = doc_buffer->isExportableFormat(format);
1594 case LFUN_BUFFER_RELOAD:
1595 enable = doc_buffer && !doc_buffer->isUnnamed()
1596 && doc_buffer->fileName().exists()
1597 && (!doc_buffer->isClean()
1598 || doc_buffer->isExternallyModified(Buffer::timestamp_method));
1601 case LFUN_BUFFER_CHILD_OPEN:
1602 enable = doc_buffer;
1605 case LFUN_BUFFER_WRITE:
1606 enable = doc_buffer && (doc_buffer->isUnnamed() || !doc_buffer->isClean());
1609 //FIXME: This LFUN should be moved to GuiApplication.
1610 case LFUN_BUFFER_WRITE_ALL: {
1611 // We enable the command only if there are some modified buffers
1612 Buffer * first = theBufferList().first();
1617 // We cannot use a for loop as the buffer list is a cycle.
1619 if (!b->isClean()) {
1623 b = theBufferList().next(b);
1624 } while (b != first);
1628 case LFUN_BUFFER_WRITE_AS:
1629 enable = doc_buffer;
1632 case LFUN_BUFFER_CLOSE:
1633 enable = doc_buffer;
1636 case LFUN_BUFFER_CLOSE_ALL:
1637 enable = theBufferList().last() != theBufferList().first();
1640 case LFUN_SPLIT_VIEW:
1641 if (cmd.getArg(0) == "vertical")
1642 enable = doc_buffer && (d.splitter_->count() == 1 ||
1643 d.splitter_->orientation() == Qt::Vertical);
1645 enable = doc_buffer && (d.splitter_->count() == 1 ||
1646 d.splitter_->orientation() == Qt::Horizontal);
1649 case LFUN_CLOSE_TAB_GROUP:
1650 enable = d.currentTabWorkArea();
1653 case LFUN_TOOLBAR_TOGGLE: {
1654 string const name = cmd.getArg(0);
1655 if (GuiToolbar * t = toolbar(name))
1656 flag.setOnOff(t->isVisible());
1659 docstring const msg =
1660 bformat(_("Unknown toolbar \"%1$s\""), from_utf8(name));
1666 case LFUN_DROP_LAYOUTS_CHOICE:
1670 case LFUN_UI_TOGGLE:
1671 flag.setOnOff(isFullScreen());
1674 case LFUN_DIALOG_DISCONNECT_INSET:
1677 case LFUN_DIALOG_HIDE:
1678 // FIXME: should we check if the dialog is shown?
1681 case LFUN_DIALOG_TOGGLE:
1682 flag.setOnOff(isDialogVisible(cmd.getArg(0)));
1683 // fall through to set "enable"
1684 case LFUN_DIALOG_SHOW: {
1685 string const name = cmd.getArg(0);
1687 enable = name == "aboutlyx"
1688 || name == "file" //FIXME: should be removed.
1690 || name == "texinfo"
1691 || name == "progress"
1692 || name == "compare";
1693 else if (name == "print")
1694 enable = doc_buffer->isExportable("dvi")
1695 && lyxrc.print_command != "none";
1696 else if (name == "character" || name == "symbols") {
1697 if (!buf || buf->isReadonly())
1700 // FIXME we should consider passthru
1702 Inset const & in = currentBufferView()->cursor().inset();
1703 enable = !in.getLayout().isPassThru();
1706 else if (name == "latexlog")
1707 enable = FileName(doc_buffer->logName()).isReadableFile();
1708 else if (name == "spellchecker")
1709 enable = theSpellChecker() && !doc_buffer->isReadonly();
1710 else if (name == "vclog")
1711 enable = doc_buffer->lyxvc().inUse();
1715 case LFUN_DIALOG_UPDATE: {
1716 string const name = cmd.getArg(0);
1718 enable = name == "prefs";
1722 case LFUN_COMMAND_EXECUTE:
1724 case LFUN_MENU_OPEN:
1725 // Nothing to check.
1728 case LFUN_COMPLETION_INLINE:
1729 if (!d.current_work_area_
1730 || !d.current_work_area_->completer().inlinePossible(
1731 currentBufferView()->cursor()))
1735 case LFUN_COMPLETION_POPUP:
1736 if (!d.current_work_area_
1737 || !d.current_work_area_->completer().popupPossible(
1738 currentBufferView()->cursor()))
1742 case LFUN_COMPLETION_COMPLETE:
1743 if (!d.current_work_area_
1744 || !d.current_work_area_->completer().inlinePossible(
1745 currentBufferView()->cursor()))
1749 case LFUN_COMPLETION_ACCEPT:
1750 if (!d.current_work_area_
1751 || (!d.current_work_area_->completer().popupVisible()
1752 && !d.current_work_area_->completer().inlineVisible()
1753 && !d.current_work_area_->completer().completionAvailable()))
1757 case LFUN_COMPLETION_CANCEL:
1758 if (!d.current_work_area_
1759 || (!d.current_work_area_->completer().popupVisible()
1760 && !d.current_work_area_->completer().inlineVisible()))
1764 case LFUN_BUFFER_ZOOM_OUT:
1765 enable = doc_buffer && lyxrc.zoom > 10;
1768 case LFUN_BUFFER_ZOOM_IN:
1769 enable = doc_buffer;
1772 case LFUN_BUFFER_NEXT:
1773 case LFUN_BUFFER_PREVIOUS:
1774 // FIXME: should we check is there is an previous or next buffer?
1776 case LFUN_BUFFER_SWITCH:
1777 // toggle on the current buffer, but do not toggle off
1778 // the other ones (is that a good idea?)
1780 && to_utf8(cmd.argument()) == doc_buffer->absFileName())
1781 flag.setOnOff(true);
1784 case LFUN_VC_REGISTER:
1785 enable = doc_buffer && !doc_buffer->lyxvc().inUse();
1787 case LFUN_VC_CHECK_IN:
1788 enable = doc_buffer && doc_buffer->lyxvc().checkInEnabled();
1790 case LFUN_VC_CHECK_OUT:
1791 enable = doc_buffer && doc_buffer->lyxvc().checkOutEnabled();
1793 case LFUN_VC_LOCKING_TOGGLE:
1794 enable = doc_buffer && !doc_buffer->isReadonly()
1795 && doc_buffer->lyxvc().lockingToggleEnabled();
1796 flag.setOnOff(enable && doc_buffer->lyxvc().locking());
1798 case LFUN_VC_REVERT:
1799 enable = doc_buffer && doc_buffer->lyxvc().inUse() && !doc_buffer->isReadonly();
1801 case LFUN_VC_UNDO_LAST:
1802 enable = doc_buffer && doc_buffer->lyxvc().undoLastEnabled();
1804 case LFUN_VC_REPO_UPDATE:
1805 enable = doc_buffer && doc_buffer->lyxvc().repoUpdateEnabled();
1807 case LFUN_VC_COMMAND: {
1808 if (cmd.argument().empty())
1810 if (!doc_buffer && contains(cmd.getArg(0), 'D'))
1814 case LFUN_VC_COMPARE:
1815 enable = doc_buffer && doc_buffer->lyxvc().prepareFileRevisionEnabled();
1818 case LFUN_SERVER_GOTO_FILE_ROW:
1820 case LFUN_FORWARD_SEARCH:
1821 enable = !(lyxrc.forward_search_dvi.empty() && lyxrc.forward_search_pdf.empty());
1829 flag.setEnabled(false);
1835 static FileName selectTemplateFile()
1837 FileDialog dlg(qt_("Select template file"));
1838 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1839 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
1841 FileDialog::Result result = dlg.open(toqstr(lyxrc.template_path),
1842 QStringList(qt_("LyX Documents (*.lyx)")));
1844 if (result.first == FileDialog::Later)
1846 if (result.second.isEmpty())
1848 return FileName(fromqstr(result.second));
1852 Buffer * GuiView::loadDocument(FileName const & filename, bool tolastfiles)
1856 Buffer * newBuffer = 0;
1858 newBuffer = checkAndLoadLyXFile(filename);
1859 } catch (ExceptionMessage const & e) {
1865 message(_("Document not loaded."));
1870 newBuffer->errors("Parse");
1871 setBuffer(newBuffer);
1874 theSession().lastFiles().add(filename);
1881 void GuiView::openDocument(string const & fname)
1883 string initpath = lyxrc.document_path;
1885 if (documentBufferView()) {
1886 string const trypath = documentBufferView()->buffer().filePath();
1887 // If directory is writeable, use this as default.
1888 if (FileName(trypath).isDirWritable())
1894 if (fname.empty()) {
1895 FileDialog dlg(qt_("Select document to open"), LFUN_FILE_OPEN);
1896 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1897 dlg.setButton2(qt_("Examples|#E#e"),
1898 toqstr(addPath(package().system_support().absFileName(), "examples")));
1900 QStringList filter(qt_("LyX Documents (*.lyx)"));
1901 filter << qt_("LyX-1.3.x Documents (*.lyx13)")
1902 << qt_("LyX-1.4.x Documents (*.lyx14)")
1903 << qt_("LyX-1.5.x Documents (*.lyx15)")
1904 << qt_("LyX-1.6.x Documents (*.lyx16)");
1905 FileDialog::Result result =
1906 dlg.open(toqstr(initpath), filter);
1908 if (result.first == FileDialog::Later)
1911 filename = fromqstr(result.second);
1913 // check selected filename
1914 if (filename.empty()) {
1915 message(_("Canceled."));
1921 // get absolute path of file and add ".lyx" to the filename if
1923 FileName const fullname =
1924 fileSearch(string(), filename, "lyx", support::may_not_exist);
1925 if (!fullname.empty())
1926 filename = fullname.absFileName();
1928 if (!fullname.onlyPath().isDirectory()) {
1929 Alert::warning(_("Invalid filename"),
1930 bformat(_("The directory in the given path\n%1$s\ndoes not exist."),
1931 from_utf8(fullname.absFileName())));
1935 // if the file doesn't exist and isn't already open (bug 6645),
1936 // let the user create one
1937 if (!fullname.exists() && !theBufferList().exists(fullname)) {
1938 // the user specifically chose this name. Believe him.
1939 Buffer * const b = newFile(filename, string(), true);
1945 docstring const disp_fn = makeDisplayPath(filename);
1946 message(bformat(_("Opening document %1$s..."), disp_fn));
1949 Buffer * buf = loadDocument(fullname);
1951 str2 = bformat(_("Document %1$s opened."), disp_fn);
1952 if (buf->lyxvc().inUse())
1953 str2 += " " + from_utf8(buf->lyxvc().versionString()) +
1954 " " + _("Version control detected.");
1956 str2 = bformat(_("Could not open document %1$s"), disp_fn);
1961 // FIXME: clean that
1962 static bool import(GuiView * lv, FileName const & filename,
1963 string const & format, ErrorList & errorList)
1965 FileName const lyxfile(support::changeExtension(filename.absFileName(), ".lyx"));
1967 string loader_format;
1968 vector<string> loaders = theConverters().loaders();
1969 if (find(loaders.begin(), loaders.end(), format) == loaders.end()) {
1970 for (vector<string>::const_iterator it = loaders.begin();
1971 it != loaders.end(); ++it) {
1972 if (!theConverters().isReachable(format, *it))
1975 string const tofile =
1976 support::changeExtension(filename.absFileName(),
1977 formats.extension(*it));
1978 if (!theConverters().convert(0, filename, FileName(tofile),
1979 filename, format, *it, errorList))
1981 loader_format = *it;
1984 if (loader_format.empty()) {
1985 frontend::Alert::error(_("Couldn't import file"),
1986 bformat(_("No information for importing the format %1$s."),
1987 formats.prettyName(format)));
1991 loader_format = format;
1993 if (loader_format == "lyx") {
1994 Buffer * buf = lv->loadDocument(lyxfile);
1998 Buffer * const b = newFile(lyxfile.absFileName(), string(), true);
2002 bool as_paragraphs = loader_format == "textparagraph";
2003 string filename2 = (loader_format == format) ? filename.absFileName()
2004 : support::changeExtension(filename.absFileName(),
2005 formats.extension(loader_format));
2006 lv->currentBufferView()->insertPlaintextFile(FileName(filename2),
2008 guiApp->setCurrentView(lv);
2009 lyx::dispatch(FuncRequest(LFUN_MARK_OFF));
2016 void GuiView::importDocument(string const & argument)
2019 string filename = split(argument, format, ' ');
2021 LYXERR(Debug::INFO, format << " file: " << filename);
2023 // need user interaction
2024 if (filename.empty()) {
2025 string initpath = lyxrc.document_path;
2026 if (documentBufferView()) {
2027 string const trypath = documentBufferView()->buffer().filePath();
2028 // If directory is writeable, use this as default.
2029 if (FileName(trypath).isDirWritable())
2033 docstring const text = bformat(_("Select %1$s file to import"),
2034 formats.prettyName(format));
2036 FileDialog dlg(toqstr(text), LFUN_BUFFER_IMPORT);
2037 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2038 dlg.setButton2(qt_("Examples|#E#e"),
2039 toqstr(addPath(package().system_support().absFileName(), "examples")));
2041 docstring filter = formats.prettyName(format);
2044 filter += from_utf8(formats.extension(format));
2047 FileDialog::Result result =
2048 dlg.open(toqstr(initpath), fileFilters(toqstr(filter)));
2050 if (result.first == FileDialog::Later)
2053 filename = fromqstr(result.second);
2055 // check selected filename
2056 if (filename.empty())
2057 message(_("Canceled."));
2060 if (filename.empty())
2063 // get absolute path of file
2064 FileName const fullname(support::makeAbsPath(filename));
2066 FileName const lyxfile(support::changeExtension(fullname.absFileName(), ".lyx"));
2068 // Check if the document already is open
2069 Buffer * buf = theBufferList().getBuffer(lyxfile);
2072 if (!closeBuffer()) {
2073 message(_("Canceled."));
2078 docstring const displaypath = makeDisplayPath(lyxfile.absFileName(), 30);
2080 // if the file exists already, and we didn't do
2081 // -i lyx thefile.lyx, warn
2082 if (lyxfile.exists() && fullname != lyxfile) {
2084 docstring text = bformat(_("The document %1$s already exists.\n\n"
2085 "Do you want to overwrite that document?"), displaypath);
2086 int const ret = Alert::prompt(_("Overwrite document?"),
2087 text, 0, 1, _("&Overwrite"), _("&Cancel"));
2090 message(_("Canceled."));
2095 message(bformat(_("Importing %1$s..."), displaypath));
2096 ErrorList errorList;
2097 if (import(this, fullname, format, errorList))
2098 message(_("imported."));
2100 message(_("file not imported!"));
2102 // FIXME (Abdel 12/08/06): Is there a need to display the error list here?
2106 void GuiView::newDocument(string const & filename, bool from_template)
2108 FileName initpath(lyxrc.document_path);
2109 if (documentBufferView()) {
2110 FileName const trypath(documentBufferView()->buffer().filePath());
2111 // If directory is writeable, use this as default.
2112 if (trypath.isDirWritable())
2116 string templatefile;
2117 if (from_template) {
2118 templatefile = selectTemplateFile().absFileName();
2119 if (templatefile.empty())
2124 if (filename.empty())
2125 b = newUnnamedFile(initpath, to_utf8(_("newfile")), templatefile);
2127 b = newFile(filename, templatefile, true);
2132 // If no new document could be created, it is unsure
2133 // whether there is a valid BufferView.
2134 if (currentBufferView())
2135 // Ensure the cursor is correctly positioned on screen.
2136 currentBufferView()->showCursor();
2140 void GuiView::insertLyXFile(docstring const & fname)
2142 BufferView * bv = documentBufferView();
2147 FileName filename(to_utf8(fname));
2148 if (filename.empty()) {
2149 // Launch a file browser
2151 string initpath = lyxrc.document_path;
2152 string const trypath = bv->buffer().filePath();
2153 // If directory is writeable, use this as default.
2154 if (FileName(trypath).isDirWritable())
2158 FileDialog dlg(qt_("Select LyX document to insert"), LFUN_FILE_INSERT);
2159 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2160 dlg.setButton2(qt_("Examples|#E#e"),
2161 toqstr(addPath(package().system_support().absFileName(),
2164 FileDialog::Result result = dlg.open(toqstr(initpath),
2165 QStringList(qt_("LyX Documents (*.lyx)")));
2167 if (result.first == FileDialog::Later)
2171 filename.set(fromqstr(result.second));
2173 // check selected filename
2174 if (filename.empty()) {
2175 // emit message signal.
2176 message(_("Canceled."));
2181 bv->insertLyXFile(filename);
2182 bv->buffer().errors("Parse");
2186 void GuiView::insertPlaintextFile(docstring const & fname,
2189 BufferView * bv = documentBufferView();
2193 if (!fname.empty() && !FileName::isAbsolute(to_utf8(fname))) {
2194 message(_("Absolute filename expected."));
2199 FileName filename(to_utf8(fname));
2201 if (!filename.empty()) {
2202 bv->insertPlaintextFile(filename, asParagraph);
2206 FileDialog dlg(qt_("Select file to insert"), (asParagraph ?
2207 LFUN_FILE_INSERT_PLAINTEXT_PARA : LFUN_FILE_INSERT_PLAINTEXT));
2209 FileDialog::Result result = dlg.open(toqstr(bv->buffer().filePath()),
2210 QStringList(qt_("All Files (*)")));
2212 if (result.first == FileDialog::Later)
2216 filename.set(fromqstr(result.second));
2218 // check selected filename
2219 if (filename.empty()) {
2220 // emit message signal.
2221 message(_("Canceled."));
2225 bv->insertPlaintextFile(filename, asParagraph);
2229 bool GuiView::renameBuffer(Buffer & b, docstring const & newname)
2231 FileName fname = b.fileName();
2232 FileName const oldname = fname;
2234 if (!newname.empty()) {
2236 fname = support::makeAbsPath(to_utf8(newname), oldname.onlyPath().absFileName());
2238 // Switch to this Buffer.
2241 // No argument? Ask user through dialog.
2243 FileDialog dlg(qt_("Choose a filename to save document as"),
2244 LFUN_BUFFER_WRITE_AS);
2245 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2246 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
2248 if (!isLyXFileName(fname.absFileName()))
2249 fname.changeExtension(".lyx");
2251 FileDialog::Result result =
2252 dlg.save(toqstr(fname.onlyPath().absFileName()),
2253 QStringList(qt_("LyX Documents (*.lyx)")),
2254 toqstr(fname.onlyFileName()));
2256 if (result.first == FileDialog::Later)
2259 fname.set(fromqstr(result.second));
2264 if (!isLyXFileName(fname.absFileName()))
2265 fname.changeExtension(".lyx");
2268 // fname is now the new Buffer location.
2269 if (FileName(fname).exists()) {
2270 docstring const file = makeDisplayPath(fname.absFileName(), 30);
2271 docstring text = bformat(_("The document %1$s already "
2272 "exists.\n\nDo you want to "
2273 "overwrite that document?"),
2275 int const ret = Alert::prompt(_("Overwrite document?"),
2276 text, 0, 2, _("&Overwrite"), _("&Rename"), _("&Cancel"));
2279 case 1: return renameBuffer(b, docstring());
2280 case 2: return false;
2284 return saveBuffer(b, fname);
2288 bool GuiView::saveBuffer(Buffer & b) {
2289 return saveBuffer(b, FileName());
2293 bool GuiView::saveBuffer(Buffer & b, FileName const & fn)
2295 if (workArea(b) && workArea(b)->inDialogMode())
2298 if (fn.empty() && b.isUnnamed())
2299 return renameBuffer(b, docstring());
2305 success = b.saveAs(fn);
2308 theSession().lastFiles().add(b.fileName());
2312 // Switch to this Buffer.
2315 // FIXME: we don't tell the user *WHY* the save failed !!
2316 docstring const file = makeDisplayPath(b.absFileName(), 30);
2317 docstring text = bformat(_("The document %1$s could not be saved.\n\n"
2318 "Do you want to rename the document and "
2319 "try again?"), file);
2320 int const ret = Alert::prompt(_("Rename and save?"),
2321 text, 0, 2, _("&Rename"), _("&Retry"), _("&Cancel"));
2324 if (!renameBuffer(b, docstring()))
2333 return saveBuffer(b);
2337 bool GuiView::hideWorkArea(GuiWorkArea * wa)
2339 return closeWorkArea(wa, false);
2343 bool GuiView::closeWorkArea(GuiWorkArea * wa)
2345 Buffer & buf = wa->bufferView().buffer();
2346 return closeWorkArea(wa, !buf.parent());
2350 bool GuiView::closeBuffer()
2352 GuiWorkArea * wa = currentMainWorkArea();
2353 setCurrentWorkArea(wa);
2354 Buffer & buf = wa->bufferView().buffer();
2355 return wa && closeWorkArea(wa, !buf.parent());
2359 void GuiView::writeSession() const {
2360 GuiWorkArea const * active_wa = currentMainWorkArea();
2361 for (int i = 0; i < d.splitter_->count(); ++i) {
2362 TabWorkArea * twa = d.tabWorkArea(i);
2363 for (int j = 0; j < twa->count(); ++j) {
2364 GuiWorkArea * wa = static_cast<GuiWorkArea *>(twa->widget(j));
2365 Buffer & buf = wa->bufferView().buffer();
2366 theSession().lastOpened().add(buf.fileName(), wa == active_wa);
2372 bool GuiView::closeBufferAll()
2374 // Close the workareas in all other views
2375 QList<int> const ids = guiApp->viewIds();
2376 for (int i = 0; i != ids.size(); ++i) {
2377 if (id_ != ids[i] && !guiApp->view(ids[i]).closeWorkAreaAll())
2381 // Close our own workareas
2382 if (!closeWorkAreaAll())
2385 // Now close the hidden buffers. We prevent hidden buffers from being
2386 // dirty, so we can just close them.
2387 theBufferList().closeAll();
2392 bool GuiView::closeWorkAreaAll()
2394 setCurrentWorkArea(currentMainWorkArea());
2396 // We might be in a situation that there is still a tabWorkArea, but
2397 // there are no tabs anymore. This can happen when we get here after a
2398 // TabWorkArea::lastWorkAreaRemoved() signal. Therefore we count how
2399 // many TabWorkArea's have no documents anymore.
2402 // We have to call count() each time, because it can happen that
2403 // more than one splitter will disappear in one iteration (bug 5998).
2404 for (; d.splitter_->count() > empty_twa; ) {
2405 TabWorkArea * twa = d.tabWorkArea(empty_twa);
2407 if (twa->count() == 0)
2410 setCurrentWorkArea(twa->currentWorkArea());
2411 if (!closeTabWorkArea(twa))
2419 bool GuiView::closeWorkArea(GuiWorkArea * wa, bool close_buffer)
2424 Buffer & buf = wa->bufferView().buffer();
2426 if (close_buffer && GuiViewPrivate::busyBuffers.contains(&buf)) {
2427 Alert::warning(_("Close document"),
2428 _("Document could not be closed because it is being processed by LyX."));
2433 return closeBuffer(buf);
2435 if (!inMultiTabs(wa))
2436 if (!saveBufferIfNeeded(buf, true))
2444 bool GuiView::closeBuffer(Buffer & buf)
2446 // If we are in a close_event all children will be closed in some time,
2447 // so no need to do it here. This will ensure that the children end up
2448 // in the session file in the correct order. If we close the master
2449 // buffer, we can close or release the child buffers here too.
2451 ListOfBuffers clist = buf.getChildren();
2452 ListOfBuffers::const_iterator it = clist.begin();
2453 ListOfBuffers::const_iterator const bend = clist.end();
2454 for (; it != bend; ++it) {
2455 // If a child is dirty, do not close
2456 // without user intervention
2457 //FIXME: should we look in other tabworkareas?
2458 Buffer * child_buf = *it;
2459 GuiWorkArea * child_wa = workArea(*child_buf);
2461 if (!closeWorkArea(child_wa, true))
2464 theBufferList().releaseChild(&buf, child_buf);
2467 // goto bookmark to update bookmark pit.
2468 //FIXME: we should update only the bookmarks related to this buffer!
2469 LYXERR(Debug::DEBUG, "GuiView::closeBuffer()");
2470 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
2471 guiApp->gotoBookmark(i+1, false, false);
2473 if (saveBufferIfNeeded(buf, false)) {
2474 buf.removeAutosaveFile();
2475 theBufferList().release(&buf);
2482 bool GuiView::closeTabWorkArea(TabWorkArea * twa)
2484 while (twa == d.currentTabWorkArea()) {
2485 twa->setCurrentIndex(twa->count()-1);
2487 GuiWorkArea * wa = twa->currentWorkArea();
2488 Buffer & b = wa->bufferView().buffer();
2490 // We only want to close the buffer if the same buffer is not visible
2491 // in another view, and if this is not a child and if we are closing
2492 // a view (not a tabgroup).
2493 bool const close_buffer =
2494 !inMultiViews(wa) && !b.parent() && closing_;
2496 if (!closeWorkArea(wa, close_buffer))
2503 bool GuiView::saveBufferIfNeeded(Buffer & buf, bool hiding)
2505 if (buf.isClean() || buf.paragraphs().empty())
2508 // Switch to this Buffer.
2513 if (buf.isUnnamed())
2514 file = from_utf8(buf.fileName().onlyFileName());
2516 file = buf.fileName().displayName(30);
2518 // Bring this window to top before asking questions.
2523 if (hiding && buf.isUnnamed()) {
2524 docstring const text = bformat(_("The document %1$s has not been "
2525 "saved yet.\n\nDo you want to save "
2526 "the document?"), file);
2527 ret = Alert::prompt(_("Save new document?"),
2528 text, 0, 1, _("&Save"), _("&Cancel"));
2532 docstring const text = bformat(_("The document %1$s has unsaved changes."
2533 "\n\nDo you want to save the document or discard the changes?"), file);
2534 ret = Alert::prompt(_("Save changed document?"),
2535 text, 0, 2, _("&Save"), _("&Discard"), _("&Cancel"));
2540 if (!saveBuffer(buf))
2544 // If we crash after this we could have no autosave file
2545 // but I guess this is really improbable (Jug).
2546 // Sometimes improbable things happen:
2547 // - see bug http://www.lyx.org/trac/ticket/6587 (ps)
2548 // buf.removeAutosaveFile();
2550 // revert all changes
2561 bool GuiView::inMultiTabs(GuiWorkArea * wa)
2563 Buffer & buf = wa->bufferView().buffer();
2565 for (int i = 0; i != d.splitter_->count(); ++i) {
2566 GuiWorkArea * wa_ = d.tabWorkArea(i)->workArea(buf);
2567 if (wa_ && wa_ != wa)
2570 return inMultiViews(wa);
2574 bool GuiView::inMultiViews(GuiWorkArea * wa)
2576 QList<int> const ids = guiApp->viewIds();
2577 Buffer & buf = wa->bufferView().buffer();
2580 for (int i = 0; i != ids.size() && found_twa <= 1; ++i) {
2584 if (guiApp->view(ids[i]).workArea(buf))
2591 void GuiView::gotoNextOrPreviousBuffer(NextOrPrevious np)
2593 if (!documentBufferView())
2596 if (TabWorkArea * twa = d.currentTabWorkArea()) {
2597 Buffer * const curbuf = &documentBufferView()->buffer();
2598 int nwa = twa->count();
2599 for (int i = 0; i < nwa; ++i) {
2600 if (&workArea(i)->bufferView().buffer() == curbuf) {
2602 if (np == NEXTBUFFER)
2603 next_index = (i == nwa - 1 ? 0 : i + 1);
2605 next_index = (i == 0 ? nwa - 1 : i - 1);
2606 setBuffer(&workArea(next_index)->bufferView().buffer());
2614 /// make sure the document is saved
2615 static bool ensureBufferClean(Buffer * buffer)
2617 LASSERT(buffer, return false);
2618 if (buffer->isClean() && !buffer->isUnnamed())
2621 docstring const file = buffer->fileName().displayName(30);
2624 if (!buffer->isUnnamed()) {
2625 text = bformat(_("The document %1$s has unsaved "
2626 "changes.\n\nDo you want to save "
2627 "the document?"), file);
2628 title = _("Save changed document?");
2631 text = bformat(_("The document %1$s has not been "
2632 "saved yet.\n\nDo you want to save "
2633 "the document?"), file);
2634 title = _("Save new document?");
2636 int const ret = Alert::prompt(title, text, 0, 1, _("&Save"), _("&Cancel"));
2639 dispatch(FuncRequest(LFUN_BUFFER_WRITE));
2641 return buffer->isClean() && !buffer->isUnnamed();
2645 bool GuiView::reloadBuffer(Buffer & buf)
2647 Buffer::ReadStatus status = buf.reload();
2648 return status == Buffer::ReadSuccess;
2652 void GuiView::checkExternallyModifiedBuffers()
2654 BufferList::iterator bit = theBufferList().begin();
2655 BufferList::iterator const bend = theBufferList().end();
2656 for (; bit != bend; ++bit) {
2657 Buffer * buf = *bit;
2658 if (buf->fileName().exists()
2659 && buf->isExternallyModified(Buffer::checksum_method)) {
2660 docstring text = bformat(_("Document \n%1$s\n has been externally modified."
2661 " Reload now? Any local changes will be lost."),
2662 from_utf8(buf->absFileName()));
2663 int const ret = Alert::prompt(_("Reload externally changed document?"),
2664 text, 0, 1, _("&Reload"), _("&Cancel"));
2672 void GuiView::dispatchVC(FuncRequest const & cmd, DispatchResult & dr)
2674 Buffer * buffer = documentBufferView()
2675 ? &(documentBufferView()->buffer()) : 0;
2677 switch (cmd.action()) {
2678 case LFUN_VC_REGISTER:
2679 if (!buffer || !ensureBufferClean(buffer))
2681 if (!buffer->lyxvc().inUse()) {
2682 if (buffer->lyxvc().registrer()) {
2683 reloadBuffer(*buffer);
2684 dr.suppressMessageUpdate();
2689 case LFUN_VC_CHECK_IN:
2690 if (!buffer || !ensureBufferClean(buffer))
2692 if (buffer->lyxvc().inUse() && !buffer->isReadonly()) {
2693 dr.setMessage(buffer->lyxvc().checkIn());
2694 if (!dr.message().empty())
2695 reloadBuffer(*buffer);
2699 case LFUN_VC_CHECK_OUT:
2700 if (!buffer || !ensureBufferClean(buffer))
2702 if (buffer->lyxvc().inUse()) {
2703 dr.setMessage(buffer->lyxvc().checkOut());
2704 reloadBuffer(*buffer);
2708 case LFUN_VC_LOCKING_TOGGLE:
2709 LASSERT(buffer, return);
2710 if (!ensureBufferClean(buffer) || buffer->isReadonly())
2712 if (buffer->lyxvc().inUse()) {
2713 string res = buffer->lyxvc().lockingToggle();
2715 frontend::Alert::error(_("Revision control error."),
2716 _("Error when setting the locking property."));
2719 reloadBuffer(*buffer);
2724 case LFUN_VC_REVERT:
2725 LASSERT(buffer, return);
2726 if (buffer->lyxvc().revert()) {
2727 reloadBuffer(*buffer);
2728 dr.suppressMessageUpdate();
2732 case LFUN_VC_UNDO_LAST:
2733 LASSERT(buffer, return);
2734 buffer->lyxvc().undoLast();
2735 reloadBuffer(*buffer);
2736 dr.suppressMessageUpdate();
2739 case LFUN_VC_REPO_UPDATE:
2740 LASSERT(buffer, return);
2741 if (ensureBufferClean(buffer)) {
2742 dr.setMessage(buffer->lyxvc().repoUpdate());
2743 checkExternallyModifiedBuffers();
2747 case LFUN_VC_COMMAND: {
2748 string flag = cmd.getArg(0);
2749 if (buffer && contains(flag, 'R') && !ensureBufferClean(buffer))
2752 if (contains(flag, 'M')) {
2753 if (!Alert::askForText(message, _("LyX VC: Log Message")))
2756 string path = cmd.getArg(1);
2757 if (contains(path, "$$p") && buffer)
2758 path = subst(path, "$$p", buffer->filePath());
2759 LYXERR(Debug::LYXVC, "Directory: " << path);
2761 if (!pp.isReadableDirectory()) {
2762 lyxerr << _("Directory is not accessible.") << endl;
2765 support::PathChanger p(pp);
2767 string command = cmd.getArg(2);
2768 if (command.empty())
2771 command = subst(command, "$$i", buffer->absFileName());
2772 command = subst(command, "$$p", buffer->filePath());
2774 command = subst(command, "$$m", to_utf8(message));
2775 LYXERR(Debug::LYXVC, "Command: " << command);
2777 one.startscript(Systemcall::Wait, command);
2781 if (contains(flag, 'I'))
2782 buffer->markDirty();
2783 if (contains(flag, 'R'))
2784 reloadBuffer(*buffer);
2789 case LFUN_VC_COMPARE: {
2791 if (cmd.argument().empty()) {
2792 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "comparehistory"));
2796 string rev1 = cmd.getArg(0);
2800 if (!buffer->lyxvc().prepareFileRevision(rev1, f1))
2803 if (isStrInt(rev1) && convert<int>(rev1) <= 0) {
2804 f2 = buffer->absFileName();
2806 string rev2 = cmd.getArg(1);
2810 if (!buffer->lyxvc().prepareFileRevision(rev2, f2))
2814 LYXERR(Debug::LYXVC, "Launching comparison for fetched revisions:\n" <<
2815 f1 << "\n" << f2 << "\n" );
2816 string par = "compare run " + quoteName(f1) + " " + quoteName(f2);
2817 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, par));
2827 void GuiView::openChildDocument(string const & fname)
2829 LASSERT(documentBufferView(), return);
2830 Buffer & buffer = documentBufferView()->buffer();
2831 FileName const filename = support::makeAbsPath(fname, buffer.filePath());
2832 documentBufferView()->saveBookmark(false);
2834 if (theBufferList().exists(filename)) {
2835 child = theBufferList().getBuffer(filename);
2838 message(bformat(_("Opening child document %1$s..."),
2839 makeDisplayPath(filename.absFileName())));
2840 child = loadDocument(filename, false);
2842 // Set the parent name of the child document.
2843 // This makes insertion of citations and references in the child work,
2844 // when the target is in the parent or another child document.
2846 child->setParent(&buffer);
2850 bool GuiView::goToFileRow(string const & argument)
2854 size_t i = argument.find_last_of(' ');
2855 if (i != string::npos) {
2856 file_name = os::internal_path(trim(argument.substr(0, i)));
2857 istringstream is(argument.substr(i + 1));
2862 if (i == string::npos) {
2863 LYXERR0("Wrong argument: " << argument);
2867 string const abstmp = package().temp_dir().absFileName();
2868 string const realtmp = package().temp_dir().realPath();
2869 // We have to use os::path_prefix_is() here, instead of
2870 // simply prefixIs(), because the file name comes from
2871 // an external application and may need case adjustment.
2872 if (os::path_prefix_is(file_name, abstmp, os::CASE_ADJUSTED)
2873 || os::path_prefix_is(file_name, realtmp, os::CASE_ADJUSTED)) {
2874 // Needed by inverse dvi search. If it is a file
2875 // in tmpdir, call the apropriated function.
2876 // If tmpdir is a symlink, we may have the real
2877 // path passed back, so we correct for that.
2878 if (!prefixIs(file_name, abstmp))
2879 file_name = subst(file_name, realtmp, abstmp);
2880 buf = theBufferList().getBufferFromTmp(file_name);
2882 // Must replace extension of the file to be .lyx
2883 // and get full path
2884 FileName const s = fileSearch(string(),
2885 support::changeExtension(file_name, ".lyx"), "lyx");
2886 // Either change buffer or load the file
2887 if (theBufferList().exists(s))
2888 buf = theBufferList().getBuffer(s);
2889 else if (s.exists()) {
2890 buf = loadDocument(s);
2895 _("File does not exist: %1$s"),
2896 makeDisplayPath(file_name)));
2901 documentBufferView()->setCursorFromRow(row);
2906 #if (QT_VERSION >= 0x040400)
2908 docstring GuiView::GuiViewPrivate::runAndDestroy(const T& func, Buffer const * orig, Buffer * buffer, string const & format, string const & msg)
2910 bool const update_unincluded =
2911 buffer->params().maintain_unincluded_children
2912 && !buffer->params().getIncludedChildren().empty();
2913 bool const success = func(format, update_unincluded);
2915 busyBuffers.remove(orig);
2916 if (msg == "preview") {
2918 ? bformat(_("Successful preview of format: %1$s"), from_utf8(format))
2919 : bformat(_("Error while previewing format: %1$s"), from_utf8(format));
2922 ? bformat(_("Successful export to format: %1$s"), from_utf8(format))
2923 : bformat(_("Error while exporting format: %1$s"), from_utf8(format));
2927 docstring GuiView::GuiViewPrivate::compileAndDestroy(Buffer const * orig, Buffer * buffer, string const & format)
2929 bool (Buffer::* mem_func)(std::string const &, bool, bool) const = &Buffer::doExport;
2930 return runAndDestroy(bind(mem_func, buffer, _1, true, _2), orig, buffer, format, "export");
2934 docstring GuiView::GuiViewPrivate::exportAndDestroy(Buffer const * orig, Buffer * buffer, string const & format)
2936 bool (Buffer::* mem_func)(std::string const &, bool, bool) const = &Buffer::doExport;
2937 return runAndDestroy(bind(mem_func, buffer, _1, false, _2), orig, buffer, format, "export");
2941 docstring GuiView::GuiViewPrivate::previewAndDestroy(Buffer const * orig, Buffer * buffer, string const & format)
2943 bool(Buffer::* mem_func)(std::string const &, bool) const = &Buffer::preview;
2944 return runAndDestroy(bind(mem_func, buffer, _1, _2), orig, buffer, format, "preview");
2949 // not used, but the linker needs them
2951 docstring GuiView::GuiViewPrivate::compileAndDestroy(
2952 Buffer const *, Buffer *, string const &)
2958 docstring GuiView::GuiViewPrivate::exportAndDestroy(
2959 Buffer const *, Buffer *, string const &)
2965 docstring GuiView::GuiViewPrivate::previewAndDestroy(
2966 Buffer const *, Buffer *, string const &)
2974 bool GuiView::GuiViewPrivate::asyncBufferProcessing(
2975 string const & argument,
2976 Buffer const * used_buffer,
2977 docstring const & msg,
2978 docstring (*asyncFunc)(Buffer const *, Buffer *, string const &),
2979 bool (Buffer::*syncFunc)(string const &, bool, bool) const,
2980 bool (Buffer::*previewFunc)(string const &, bool) const)
2985 string format = argument;
2987 format = used_buffer->getDefaultOutputFormat();
2989 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
2990 gv_->processingThreadStarted();
2992 progress_->clearMessages();
2995 GuiViewPrivate::busyBuffers.insert(used_buffer);
2996 QFuture<docstring> f = QtConcurrent::run(
2999 used_buffer->clone(),
3001 setPreviewFuture(f);
3002 last_export_format = used_buffer->bufferFormat();
3005 // We are asynchronous, so we don't know here anything about the success
3009 // TODO check here if it breaks exporting with Qt < 4.4
3010 bool const update_unincluded =
3011 used_buffer->params().maintain_unincluded_children &&
3012 !used_buffer->params().getIncludedChildren().empty();
3013 return (used_buffer->*syncFunc)(format, true, update_unincluded);
3014 } else if (previewFunc) {
3015 return (used_buffer->*previewFunc)(format, false);
3022 void GuiView::dispatchToBufferView(FuncRequest const & cmd, DispatchResult & dr)
3024 BufferView * bv = currentBufferView();
3027 // Let the current BufferView dispatch its own actions.
3028 bv->dispatch(cmd, dr);
3029 if (dr.dispatched())
3032 // Try with the document BufferView dispatch if any.
3033 BufferView * doc_bv = documentBufferView();
3035 doc_bv->dispatch(cmd, dr);
3036 if (dr.dispatched())
3040 // Then let the current Cursor dispatch its own actions.
3041 bv->cursor().dispatch(cmd);
3043 // update completion. We do it here and not in
3044 // processKeySym to avoid another redraw just for a
3045 // changed inline completion
3046 if (cmd.origin() == FuncRequest::KEYBOARD) {
3047 if (cmd.action() == LFUN_SELF_INSERT
3048 || (cmd.action() == LFUN_ERT_INSERT && bv->cursor().inMathed()))
3049 updateCompletion(bv->cursor(), true, true);
3050 else if (cmd.action() == LFUN_CHAR_DELETE_BACKWARD)
3051 updateCompletion(bv->cursor(), false, true);
3053 updateCompletion(bv->cursor(), false, false);
3056 dr = bv->cursor().result();
3060 void GuiView::dispatch(FuncRequest const & cmd, DispatchResult & dr)
3062 BufferView * bv = currentBufferView();
3063 // By default we won't need any update.
3064 dr.screenUpdate(Update::None);
3065 // assume cmd will be dispatched
3066 dr.dispatched(true);
3068 Buffer * doc_buffer = documentBufferView()
3069 ? &(documentBufferView()->buffer()) : 0;
3071 if (cmd.origin() == FuncRequest::TOC) {
3072 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
3073 // FIXME: do we need to pass a DispatchResult object here?
3074 toc->doDispatch(bv->cursor(), cmd);
3078 string const argument = to_utf8(cmd.argument());
3080 switch(cmd.action()) {
3081 case LFUN_BUFFER_CHILD_OPEN:
3082 openChildDocument(to_utf8(cmd.argument()));
3085 case LFUN_BUFFER_IMPORT:
3086 importDocument(to_utf8(cmd.argument()));
3089 case LFUN_BUFFER_EXPORT: {
3092 // GCC only sees strfwd.h when building merged
3093 if (::lyx::operator==(cmd.argument(), "custom")) {
3094 dispatch(FuncRequest(LFUN_DIALOG_SHOW, "sendto"), dr);
3097 #if QT_VERSION < 0x040400
3098 if (!doc_buffer->doExport(argument, false)) {
3100 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
3104 /* TODO/Review: Is it a problem to also export the children?
3105 See the update_unincluded flag */
3106 d.asyncBufferProcessing(argument,
3109 &GuiViewPrivate::exportAndDestroy,
3112 // TODO Inform user about success
3117 case LFUN_BUFFER_UPDATE: {
3118 d.asyncBufferProcessing(argument,
3121 &GuiViewPrivate::compileAndDestroy,
3126 case LFUN_BUFFER_VIEW: {
3127 d.asyncBufferProcessing(argument,
3129 _("Previewing ..."),
3130 &GuiViewPrivate::previewAndDestroy,
3135 case LFUN_MASTER_BUFFER_UPDATE: {
3136 d.asyncBufferProcessing(argument,
3137 (doc_buffer ? doc_buffer->masterBuffer() : 0),
3139 &GuiViewPrivate::compileAndDestroy,
3144 case LFUN_MASTER_BUFFER_VIEW: {
3145 d.asyncBufferProcessing(argument,
3146 (doc_buffer ? doc_buffer->masterBuffer() : 0),
3148 &GuiViewPrivate::previewAndDestroy,
3149 0, &Buffer::preview);
3152 case LFUN_BUFFER_SWITCH: {
3153 string const file_name = to_utf8(cmd.argument());
3154 if (!FileName::isAbsolute(file_name)) {
3156 dr.setMessage(_("Absolute filename expected."));
3160 Buffer * buffer = theBufferList().getBuffer(FileName(file_name));
3163 dr.setMessage(_("Document not loaded"));
3167 // Do we open or switch to the buffer in this view ?
3168 if (workArea(*buffer)
3169 || lyxrc.open_buffers_in_tabs || !documentBufferView()) {
3174 // Look for the buffer in other views
3175 QList<int> const ids = guiApp->viewIds();
3177 for (; i != ids.size(); ++i) {
3178 GuiView & gv = guiApp->view(ids[i]);
3179 if (gv.workArea(*buffer)) {
3180 gv.activateWindow();
3181 gv.setBuffer(buffer);
3186 // If necessary, open a new window as a last resort
3187 if (i == ids.size()) {
3188 lyx::dispatch(FuncRequest(LFUN_WINDOW_NEW));
3194 case LFUN_BUFFER_NEXT:
3195 gotoNextOrPreviousBuffer(NEXTBUFFER);
3198 case LFUN_BUFFER_PREVIOUS:
3199 gotoNextOrPreviousBuffer(PREVBUFFER);
3202 case LFUN_COMMAND_EXECUTE: {
3203 bool const show_it = cmd.argument() != "off";
3204 // FIXME: this is a hack, "minibuffer" should not be
3206 if (GuiToolbar * t = toolbar("minibuffer")) {
3207 t->setVisible(show_it);
3208 if (show_it && t->commandBuffer())
3209 t->commandBuffer()->setFocus();
3213 case LFUN_DROP_LAYOUTS_CHOICE:
3214 d.layout_->showPopup();
3217 case LFUN_MENU_OPEN:
3218 if (QMenu * menu = guiApp->menus().menu(toqstr(cmd.argument()), *this))
3219 menu->exec(QCursor::pos());
3222 case LFUN_FILE_INSERT:
3223 insertLyXFile(cmd.argument());
3226 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
3227 insertPlaintextFile(cmd.argument(), true);
3230 case LFUN_FILE_INSERT_PLAINTEXT:
3231 insertPlaintextFile(cmd.argument(), false);
3234 case LFUN_BUFFER_RELOAD: {
3235 LASSERT(doc_buffer, break);
3238 if (!doc_buffer->isClean()) {
3239 docstring const file =
3240 makeDisplayPath(doc_buffer->absFileName(), 20);
3241 docstring text = bformat(_("Any changes will be lost. "
3242 "Are you sure you want to revert to the saved version "
3243 "of the document %1$s?"), file);
3244 ret = Alert::prompt(_("Revert to saved document?"),
3245 text, 1, 1, _("&Revert"), _("&Cancel"));
3249 doc_buffer->markClean();
3250 reloadBuffer(*doc_buffer);
3251 dr.forceBufferUpdate();
3256 case LFUN_BUFFER_WRITE:
3257 LASSERT(doc_buffer, break);
3258 saveBuffer(*doc_buffer);
3261 case LFUN_BUFFER_WRITE_AS:
3262 LASSERT(doc_buffer, break);
3263 renameBuffer(*doc_buffer, cmd.argument());
3266 case LFUN_BUFFER_WRITE_ALL: {
3267 Buffer * first = theBufferList().first();
3270 message(_("Saving all documents..."));
3271 // We cannot use a for loop as the buffer list cycles.
3274 if (!b->isClean()) {
3276 LYXERR(Debug::ACTION, "Saved " << b->absFileName());
3278 b = theBufferList().next(b);
3279 } while (b != first);
3280 dr.setMessage(_("All documents saved."));
3284 case LFUN_BUFFER_CLOSE:
3288 case LFUN_BUFFER_CLOSE_ALL:
3292 case LFUN_TOOLBAR_TOGGLE: {
3293 string const name = cmd.getArg(0);
3294 if (GuiToolbar * t = toolbar(name))
3299 case LFUN_DIALOG_UPDATE: {
3300 string const name = to_utf8(cmd.argument());
3301 if (name == "prefs" || name == "document")
3302 updateDialog(name, string());
3303 else if (name == "paragraph")
3304 lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
3305 else if (currentBufferView()) {
3306 Inset * inset = currentBufferView()->editedInset(name);
3307 // Can only update a dialog connected to an existing inset
3309 // FIXME: get rid of this indirection; GuiView ask the inset
3310 // if he is kind enough to update itself...
3311 FuncRequest fr(LFUN_INSET_DIALOG_UPDATE, cmd.argument());
3312 //FIXME: pass DispatchResult here?
3313 inset->dispatch(currentBufferView()->cursor(), fr);
3319 case LFUN_DIALOG_TOGGLE: {
3320 if (isDialogVisible(cmd.getArg(0)))
3321 dispatch(FuncRequest(LFUN_DIALOG_HIDE, cmd.argument()), dr);
3323 dispatch(FuncRequest(LFUN_DIALOG_SHOW, cmd.argument()), dr);
3327 case LFUN_DIALOG_DISCONNECT_INSET:
3328 disconnectDialog(to_utf8(cmd.argument()));
3331 case LFUN_DIALOG_HIDE: {
3332 guiApp->hideDialogs(to_utf8(cmd.argument()), 0);
3336 case LFUN_DIALOG_SHOW: {
3337 string const name = cmd.getArg(0);
3338 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
3340 if (name == "character") {
3341 data = freefont2string();
3343 showDialog("character", data);
3344 } else if (name == "latexlog") {
3345 Buffer::LogType type;
3346 string const logfile = doc_buffer->logName(&type);
3348 case Buffer::latexlog:
3351 case Buffer::buildlog:
3355 data += Lexer::quoteString(logfile);
3356 showDialog("log", data);
3357 } else if (name == "vclog") {
3358 string const data = "vc " +
3359 Lexer::quoteString(doc_buffer->lyxvc().getLogFile());
3360 showDialog("log", data);
3361 } else if (name == "symbols") {
3362 data = bv->cursor().getEncoding()->name();
3364 showDialog("symbols", data);
3366 } else if (name == "prefs" && isFullScreen()) {
3367 lfunUiToggle("fullscreen");
3368 showDialog("prefs", data);
3370 showDialog(name, data);
3375 dr.setMessage(cmd.argument());
3378 case LFUN_UI_TOGGLE: {
3379 string arg = cmd.getArg(0);
3380 if (!lfunUiToggle(arg)) {
3381 docstring const msg = "ui-toggle " + _("%1$s unknown command!");
3382 dr.setMessage(bformat(msg, from_utf8(arg)));
3384 // Make sure the keyboard focus stays in the work area.
3389 case LFUN_SPLIT_VIEW: {
3390 LASSERT(doc_buffer, break);
3391 string const orientation = cmd.getArg(0);
3392 d.splitter_->setOrientation(orientation == "vertical"
3393 ? Qt::Vertical : Qt::Horizontal);
3394 TabWorkArea * twa = addTabWorkArea();
3395 GuiWorkArea * wa = twa->addWorkArea(*doc_buffer, *this);
3396 setCurrentWorkArea(wa);
3399 case LFUN_CLOSE_TAB_GROUP:
3400 if (TabWorkArea * twa = d.currentTabWorkArea()) {
3401 closeTabWorkArea(twa);
3402 d.current_work_area_ = 0;
3403 twa = d.currentTabWorkArea();
3404 // Switch to the next GuiWorkArea in the found TabWorkArea.
3406 // Make sure the work area is up to date.
3407 setCurrentWorkArea(twa->currentWorkArea());
3409 setCurrentWorkArea(0);
3414 case LFUN_COMPLETION_INLINE:
3415 if (d.current_work_area_)
3416 d.current_work_area_->completer().showInline();
3419 case LFUN_COMPLETION_POPUP:
3420 if (d.current_work_area_)
3421 d.current_work_area_->completer().showPopup();
3425 case LFUN_COMPLETION_COMPLETE:
3426 if (d.current_work_area_)
3427 d.current_work_area_->completer().tab();
3430 case LFUN_COMPLETION_CANCEL:
3431 if (d.current_work_area_) {
3432 if (d.current_work_area_->completer().popupVisible())
3433 d.current_work_area_->completer().hidePopup();
3435 d.current_work_area_->completer().hideInline();
3439 case LFUN_COMPLETION_ACCEPT:
3440 if (d.current_work_area_)
3441 d.current_work_area_->completer().activate();
3444 case LFUN_BUFFER_ZOOM_IN:
3445 case LFUN_BUFFER_ZOOM_OUT:
3446 if (cmd.argument().empty()) {
3447 if (cmd.action() == LFUN_BUFFER_ZOOM_IN)
3452 lyxrc.zoom += convert<int>(cmd.argument());
3454 if (lyxrc.zoom < 10)
3457 // The global QPixmapCache is used in GuiPainter to cache text
3458 // painting so we must reset it.
3459 QPixmapCache::clear();
3460 guiApp->fontLoader().update();
3461 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
3464 case LFUN_VC_REGISTER:
3465 case LFUN_VC_CHECK_IN:
3466 case LFUN_VC_CHECK_OUT:
3467 case LFUN_VC_REPO_UPDATE:
3468 case LFUN_VC_LOCKING_TOGGLE:
3469 case LFUN_VC_REVERT:
3470 case LFUN_VC_UNDO_LAST:
3471 case LFUN_VC_COMMAND:
3472 case LFUN_VC_COMPARE:
3473 dispatchVC(cmd, dr);
3476 case LFUN_SERVER_GOTO_FILE_ROW:
3477 goToFileRow(to_utf8(cmd.argument()));
3480 case LFUN_FORWARD_SEARCH: {
3481 FileName const path(doc_buffer->temppath());
3482 string const texname = doc_buffer->latexName();
3483 FileName const dviname(addName(path.absFileName(),
3484 support::changeExtension(texname, "dvi")));
3485 FileName const pdfname(addName(path.absFileName(),
3486 support::changeExtension(texname, "pdf")));
3487 if (!dviname.exists() && !pdfname.exists()) {
3488 dr.setMessage(_("Please, preview the document first."));
3491 string outname = dviname.onlyFileName();
3492 string command = lyxrc.forward_search_dvi;
3493 if (!dviname.exists() ||
3494 pdfname.lastModified() > dviname.lastModified()) {
3495 outname = pdfname.onlyFileName();
3496 command = lyxrc.forward_search_pdf;
3499 int row = doc_buffer->texrow().getRowFromIdPos(bv->cursor().paragraph().id(), bv->cursor().pos());
3500 LYXERR(Debug::ACTION, "Forward search: row:" << row
3501 << " id:" << bv->cursor().paragraph().id());
3502 if (!row || command.empty()) {
3503 dr.setMessage(_("Couldn't proceed."));
3506 string texrow = convert<string>(row);
3508 command = subst(command, "$$n", texrow);
3509 command = subst(command, "$$t", texname);
3510 command = subst(command, "$$o", outname);
3512 PathChanger p(path);
3514 one.startscript(Systemcall::DontWait, command);
3518 // The LFUN must be for one of BufferView, Buffer or Cursor;
3520 dispatchToBufferView(cmd, dr);
3524 // Part of automatic menu appearance feature.
3525 if (isFullScreen()) {
3526 if (menuBar()->isVisible() && lyxrc.full_screen_menubar)
3528 if (statusBar()->isVisible())
3529 statusBar()->hide();
3534 bool GuiView::lfunUiToggle(string const & ui_component)
3536 if (ui_component == "scrollbar") {
3537 // hide() is of no help
3538 if (d.current_work_area_->verticalScrollBarPolicy() ==
3539 Qt::ScrollBarAlwaysOff)
3541 d.current_work_area_->setVerticalScrollBarPolicy(
3542 Qt::ScrollBarAsNeeded);
3544 d.current_work_area_->setVerticalScrollBarPolicy(
3545 Qt::ScrollBarAlwaysOff);
3546 } else if (ui_component == "statusbar") {
3547 statusBar()->setVisible(!statusBar()->isVisible());
3548 } else if (ui_component == "menubar") {
3549 menuBar()->setVisible(!menuBar()->isVisible());
3551 #if QT_VERSION >= 0x040300
3552 if (ui_component == "frame") {
3554 getContentsMargins(&l, &t, &r, &b);
3555 //are the frames in default state?
3556 d.current_work_area_->setFrameStyle(QFrame::NoFrame);
3558 setContentsMargins(-2, -2, -2, -2);
3560 setContentsMargins(0, 0, 0, 0);
3564 if (ui_component == "fullscreen") {
3572 void GuiView::toggleFullScreen()
3574 if (isFullScreen()) {
3575 for (int i = 0; i != d.splitter_->count(); ++i)
3576 d.tabWorkArea(i)->setFullScreen(false);
3577 #if QT_VERSION >= 0x040300
3578 setContentsMargins(0, 0, 0, 0);
3580 setWindowState(windowState() ^ Qt::WindowFullScreen);
3583 statusBar()->show();
3586 hideDialogs("prefs", 0);
3587 for (int i = 0; i != d.splitter_->count(); ++i)
3588 d.tabWorkArea(i)->setFullScreen(true);
3589 #if QT_VERSION >= 0x040300
3590 setContentsMargins(-2, -2, -2, -2);
3593 setWindowState(windowState() ^ Qt::WindowFullScreen);
3594 statusBar()->hide();
3595 if (lyxrc.full_screen_menubar)
3597 if (lyxrc.full_screen_toolbars) {
3598 ToolbarMap::iterator end = d.toolbars_.end();
3599 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
3604 // give dialogs like the TOC a chance to adapt
3609 Buffer const * GuiView::updateInset(Inset const * inset)
3614 Buffer const * inset_buffer = &(inset->buffer());
3616 for (int i = 0; i != d.splitter_->count(); ++i) {
3617 GuiWorkArea * wa = d.tabWorkArea(i)->currentWorkArea();
3620 Buffer const * buffer = &(wa->bufferView().buffer());
3621 if (inset_buffer == buffer)
3622 wa->scheduleRedraw();
3624 return inset_buffer;
3628 void GuiView::restartCursor()
3630 /* When we move around, or type, it's nice to be able to see
3631 * the cursor immediately after the keypress.
3633 if (d.current_work_area_)
3634 d.current_work_area_->startBlinkingCursor();
3636 // Take this occasion to update the other GUI elements.
3642 void GuiView::updateCompletion(Cursor & cur, bool start, bool keep)
3644 if (d.current_work_area_)
3645 d.current_work_area_->completer().updateVisibility(cur, start, keep);
3650 // This list should be kept in sync with the list of insets in
3651 // src/insets/Inset.cpp. I.e., if a dialog goes with an inset, the
3652 // dialog should have the same name as the inset.
3653 // Changes should be also recorded in LFUN_DIALOG_SHOW doxygen
3654 // docs in LyXAction.cpp.
3656 char const * const dialognames[] = {
3658 "aboutlyx", "bibitem", "bibtex", "box", "branch", "changes", "character",
3659 "citation", "compare", "comparehistory", "document", "errorlist", "ert",
3660 "external", "file", "findreplace", "findreplaceadv", "float", "graphics",
3661 "href", "include", "index", "index_print", "info", "listings", "label", "line",
3662 "log", "mathdelimiter", "mathmatrix", "mathspace", "nomenclature",
3663 "nomencl_print", "note", "paragraph", "phantom", "prefs", "print", "ref",
3664 "sendto", "space", "spellchecker", "symbols", "tabular", "tabularcreate",
3665 "thesaurus", "texinfo", "toc", "view-source", "vspace", "wrap", "progress"};
3667 char const * const * const end_dialognames =
3668 dialognames + (sizeof(dialognames) / sizeof(char *));
3672 cmpCStr(char const * name) : name_(name) {}
3673 bool operator()(char const * other) {
3674 return strcmp(other, name_) == 0;
3681 bool isValidName(string const & name)
3683 return find_if(dialognames, end_dialognames,
3684 cmpCStr(name.c_str())) != end_dialognames;
3690 void GuiView::resetDialogs()
3692 // Make sure that no LFUN uses any GuiView.
3693 guiApp->setCurrentView(0);
3696 constructToolbars();
3697 guiApp->menus().fillMenuBar(menuBar(), this, false);
3698 d.layout_->updateContents(true);
3699 // Now update controls with current buffer.
3700 guiApp->setCurrentView(this);
3706 Dialog * GuiView::findOrBuild(string const & name, bool hide_it)
3708 if (!isValidName(name))
3711 map<string, DialogPtr>::iterator it = d.dialogs_.find(name);
3713 if (it != d.dialogs_.end()) {
3715 it->second->hideView();
3716 return it->second.get();
3719 Dialog * dialog = build(name);
3720 d.dialogs_[name].reset(dialog);
3721 if (lyxrc.allow_geometry_session)
3722 dialog->restoreSession();
3729 void GuiView::showDialog(string const & name, string const & data,
3732 triggerShowDialog(toqstr(name), toqstr(data), inset);
3736 void GuiView::doShowDialog(QString const & qname, QString const & qdata,
3742 const string name = fromqstr(qname);
3743 const string data = fromqstr(qdata);
3747 Dialog * dialog = findOrBuild(name, false);
3749 bool const visible = dialog->isVisibleView();
3750 dialog->showData(data);
3751 if (inset && currentBufferView())
3752 currentBufferView()->editInset(name, inset);
3753 // We only set the focus to the new dialog if it was not yet
3754 // visible in order not to change the existing previous behaviour
3756 // activateWindow is needed for floating dockviews
3757 dialog->asQWidget()->raise();
3758 dialog->asQWidget()->activateWindow();
3759 dialog->asQWidget()->setFocus();
3763 catch (ExceptionMessage const & ex) {
3771 bool GuiView::isDialogVisible(string const & name) const
3773 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3774 if (it == d.dialogs_.end())
3776 return it->second.get()->isVisibleView() && !it->second.get()->isClosing();
3780 void GuiView::hideDialog(string const & name, Inset * inset)
3782 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3783 if (it == d.dialogs_.end())
3786 if (inset && currentBufferView()
3787 && inset != currentBufferView()->editedInset(name))
3790 Dialog * const dialog = it->second.get();
3791 if (dialog->isVisibleView())
3793 if (currentBufferView())
3794 currentBufferView()->editInset(name, 0);
3798 void GuiView::disconnectDialog(string const & name)
3800 if (!isValidName(name))
3802 if (currentBufferView())
3803 currentBufferView()->editInset(name, 0);
3807 void GuiView::hideAll() const
3809 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
3810 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3812 for(; it != end; ++it)
3813 it->second->hideView();
3817 void GuiView::updateDialogs()
3819 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
3820 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3822 for(; it != end; ++it) {
3823 Dialog * dialog = it->second.get();
3825 if (dialog->needBufferOpen() && !documentBufferView())
3826 hideDialog(fromqstr(dialog->name()), 0);
3827 else if (dialog->isVisibleView())
3828 dialog->checkStatus();
3835 Dialog * createDialog(GuiView & lv, string const & name);
3837 // will be replaced by a proper factory...
3838 Dialog * createGuiAbout(GuiView & lv);
3839 Dialog * createGuiBibtex(GuiView & lv);
3840 Dialog * createGuiChanges(GuiView & lv);
3841 Dialog * createGuiCharacter(GuiView & lv);
3842 Dialog * createGuiCitation(GuiView & lv);
3843 Dialog * createGuiCompare(GuiView & lv);
3844 Dialog * createGuiCompareHistory(GuiView & lv);
3845 Dialog * createGuiDelimiter(GuiView & lv);
3846 Dialog * createGuiDocument(GuiView & lv);
3847 Dialog * createGuiErrorList(GuiView & lv);
3848 Dialog * createGuiExternal(GuiView & lv);
3849 Dialog * createGuiGraphics(GuiView & lv);
3850 Dialog * createGuiInclude(GuiView & lv);
3851 Dialog * createGuiIndex(GuiView & lv);
3852 Dialog * createGuiListings(GuiView & lv);
3853 Dialog * createGuiLog(GuiView & lv);
3854 Dialog * createGuiMathMatrix(GuiView & lv);
3855 Dialog * createGuiNote(GuiView & lv);
3856 Dialog * createGuiParagraph(GuiView & lv);
3857 Dialog * createGuiPhantom(GuiView & lv);
3858 Dialog * createGuiPreferences(GuiView & lv);
3859 Dialog * createGuiPrint(GuiView & lv);
3860 Dialog * createGuiPrintindex(GuiView & lv);
3861 Dialog * createGuiRef(GuiView & lv);
3862 Dialog * createGuiSearch(GuiView & lv);
3863 Dialog * createGuiSearchAdv(GuiView & lv);
3864 Dialog * createGuiSendTo(GuiView & lv);
3865 Dialog * createGuiShowFile(GuiView & lv);
3866 Dialog * createGuiSpellchecker(GuiView & lv);
3867 Dialog * createGuiSymbols(GuiView & lv);
3868 Dialog * createGuiTabularCreate(GuiView & lv);
3869 Dialog * createGuiTexInfo(GuiView & lv);
3870 Dialog * createGuiToc(GuiView & lv);
3871 Dialog * createGuiThesaurus(GuiView & lv);
3872 Dialog * createGuiViewSource(GuiView & lv);
3873 Dialog * createGuiWrap(GuiView & lv);
3874 Dialog * createGuiProgressView(GuiView & lv);
3878 Dialog * GuiView::build(string const & name)
3880 LASSERT(isValidName(name), return 0);
3882 Dialog * dialog = createDialog(*this, name);
3886 if (name == "aboutlyx")
3887 return createGuiAbout(*this);
3888 if (name == "bibtex")
3889 return createGuiBibtex(*this);
3890 if (name == "changes")
3891 return createGuiChanges(*this);
3892 if (name == "character")
3893 return createGuiCharacter(*this);
3894 if (name == "citation")
3895 return createGuiCitation(*this);
3896 if (name == "compare")
3897 return createGuiCompare(*this);
3898 if (name == "comparehistory")
3899 return createGuiCompareHistory(*this);
3900 if (name == "document")
3901 return createGuiDocument(*this);
3902 if (name == "errorlist")
3903 return createGuiErrorList(*this);
3904 if (name == "external")
3905 return createGuiExternal(*this);
3907 return createGuiShowFile(*this);
3908 if (name == "findreplace")
3909 return createGuiSearch(*this);
3910 if (name == "findreplaceadv")
3911 return createGuiSearchAdv(*this);
3912 if (name == "graphics")
3913 return createGuiGraphics(*this);
3914 if (name == "include")
3915 return createGuiInclude(*this);
3916 if (name == "index")
3917 return createGuiIndex(*this);
3918 if (name == "index_print")
3919 return createGuiPrintindex(*this);
3920 if (name == "listings")
3921 return createGuiListings(*this);
3923 return createGuiLog(*this);
3924 if (name == "mathdelimiter")
3925 return createGuiDelimiter(*this);
3926 if (name == "mathmatrix")
3927 return createGuiMathMatrix(*this);
3929 return createGuiNote(*this);
3930 if (name == "paragraph")
3931 return createGuiParagraph(*this);
3932 if (name == "phantom")
3933 return createGuiPhantom(*this);
3934 if (name == "prefs")
3935 return createGuiPreferences(*this);
3936 if (name == "print")
3937 return createGuiPrint(*this);
3939 return createGuiRef(*this);
3940 if (name == "sendto")
3941 return createGuiSendTo(*this);
3942 if (name == "spellchecker")
3943 return createGuiSpellchecker(*this);
3944 if (name == "symbols")
3945 return createGuiSymbols(*this);
3946 if (name == "tabularcreate")
3947 return createGuiTabularCreate(*this);
3948 if (name == "texinfo")
3949 return createGuiTexInfo(*this);
3950 if (name == "thesaurus")
3951 return createGuiThesaurus(*this);
3953 return createGuiToc(*this);
3954 if (name == "view-source")
3955 return createGuiViewSource(*this);
3957 return createGuiWrap(*this);
3958 if (name == "progress")
3959 return createGuiProgressView(*this);
3965 } // namespace frontend
3968 #include "moc_GuiView.cpp"