3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Lars Gullik Bjønnes
8 * \author Abdelrazak Younes
11 * Full author contact details are available in file CREDITS.
19 #include "DispatchResult.h"
20 #include "FileDialog.h"
21 #include "FontLoader.h"
22 #include "GuiApplication.h"
23 #include "GuiCommandBuffer.h"
24 #include "GuiCompleter.h"
25 #include "GuiKeySymbol.h"
27 #include "GuiToolbar.h"
28 #include "GuiWorkArea.h"
29 #include "GuiProgress.h"
30 #include "LayoutBox.h"
34 #include "qt_helpers.h"
36 #include "frontends/alert.h"
38 #include "buffer_funcs.h"
40 #include "BufferList.h"
41 #include "BufferParams.h"
42 #include "BufferView.h"
44 #include "Converter.h"
46 #include "CutAndPaste.h"
48 #include "ErrorList.h"
50 #include "FuncStatus.h"
51 #include "FuncRequest.h"
55 #include "LyXAction.h"
59 #include "Paragraph.h"
60 #include "SpellChecker.h"
62 #include "TextClass.h"
67 #include "support/convert.h"
68 #include "support/debug.h"
69 #include "support/ExceptionMessage.h"
70 #include "support/FileName.h"
71 #include "support/filetools.h"
72 #include "support/gettext.h"
73 #include "support/filetools.h"
74 #include "support/ForkedCalls.h"
75 #include "support/lassert.h"
76 #include "support/lstrings.h"
77 #include "support/os.h"
78 #include "support/Package.h"
79 #include "support/Path.h"
80 #include "support/Systemcall.h"
81 #include "support/Timeout.h"
82 #include "support/ProgressInterface.h"
85 #include <QApplication>
86 #include <QCloseEvent>
88 #include <QDesktopWidget>
89 #include <QDragEnterEvent>
98 #include <QPixmapCache>
100 #include <QPushButton>
102 #include <QShowEvent>
104 #include <QStackedWidget>
105 #include <QStatusBar>
110 #include <QScrollBar>
114 #define EXPORT_in_THREAD 1
116 // QtConcurrent was introduced in Qt 4.4
117 #if (QT_VERSION >= 0x040400)
119 #include <QFutureWatcher>
120 #include <QtConcurrentRun>
123 #include "support/bind.h"
127 #ifdef HAVE_SYS_TIME_H
128 # include <sys/time.h>
136 using namespace lyx::support;
143 class BackgroundWidget : public QWidget
148 LYXERR(Debug::GUI, "show banner: " << lyxrc.show_banner);
149 if (!lyxrc.show_banner)
151 /// The text to be written on top of the pixmap
152 QString const text = lyx_version ?
153 qt_("version ") + lyx_version : qt_("unknown version");
154 splash_ = getPixmap("images/", "banner", "png");
156 QPainter pain(&splash_);
157 pain.setPen(QColor(0, 0, 0));
159 // The font used to display the version info
160 font.setStyleHint(QFont::SansSerif);
161 font.setWeight(QFont::Bold);
162 font.setPointSize(int(toqstr(lyxrc.font_sizes[FONT_SIZE_LARGE]).toDouble()));
163 int width = QFontMetrics(font).width(text);
165 pain.drawText(397 - width, 15, text);
166 setFocusPolicy(Qt::StrongFocus);
169 void paintEvent(QPaintEvent *)
171 int x = (width() - splash_.width()) / 2;
172 int y = (height() - splash_.height()) / 2;
174 pain.drawPixmap(x, y, splash_);
177 void keyPressEvent(QKeyEvent * ev)
180 setKeySymbol(&sym, ev);
182 guiApp->processKeySym(sym, q_key_state(ev->modifiers()));
194 /// Toolbar store providing access to individual toolbars by name.
195 typedef map<string, GuiToolbar *> ToolbarMap;
197 typedef shared_ptr<Dialog> DialogPtr;
202 struct GuiView::GuiViewPrivate
204 GuiViewPrivate(GuiView * gv)
205 : gv_(gv), current_work_area_(0), current_main_work_area_(0),
206 layout_(0), autosave_timeout_(5000),
209 // hardcode here the platform specific icon size
210 smallIconSize = 14; // scaling problems
211 normalIconSize = 20; // ok, default
212 bigIconSize = 26; // better for some math icons
214 splitter_ = new QSplitter;
215 bg_widget_ = new BackgroundWidget;
216 stack_widget_ = new QStackedWidget;
217 stack_widget_->addWidget(bg_widget_);
218 stack_widget_->addWidget(splitter_);
221 // TODO cleanup, remove the singleton, handle multiple Windows?
222 progress_ = ProgressInterface::instance();
223 if (!dynamic_cast<GuiProgress*>(progress_)) {
224 progress_ = new GuiProgress(); // TODO who deletes it
225 ProgressInterface::setInstance(progress_);
228 dynamic_cast<GuiProgress*>(progress_),
229 SIGNAL(updateStatusBarMessage(QString const&)),
230 gv, SLOT(updateStatusBarMessage(QString const&)));
232 dynamic_cast<GuiProgress*>(progress_),
233 SIGNAL(clearMessageText()),
234 gv, SLOT(clearMessageText()));
241 delete stack_widget_;
244 QMenu * toolBarPopup(GuiView * parent)
246 // FIXME: translation
247 QMenu * menu = new QMenu(parent);
248 QActionGroup * iconSizeGroup = new QActionGroup(parent);
250 QAction * smallIcons = new QAction(iconSizeGroup);
251 smallIcons->setText(qt_("Small-sized icons"));
252 smallIcons->setCheckable(true);
253 QObject::connect(smallIcons, SIGNAL(triggered()),
254 parent, SLOT(smallSizedIcons()));
255 menu->addAction(smallIcons);
257 QAction * normalIcons = new QAction(iconSizeGroup);
258 normalIcons->setText(qt_("Normal-sized icons"));
259 normalIcons->setCheckable(true);
260 QObject::connect(normalIcons, SIGNAL(triggered()),
261 parent, SLOT(normalSizedIcons()));
262 menu->addAction(normalIcons);
264 QAction * bigIcons = new QAction(iconSizeGroup);
265 bigIcons->setText(qt_("Big-sized icons"));
266 bigIcons->setCheckable(true);
267 QObject::connect(bigIcons, SIGNAL(triggered()),
268 parent, SLOT(bigSizedIcons()));
269 menu->addAction(bigIcons);
271 unsigned int cur = parent->iconSize().width();
272 if ( cur == parent->d.smallIconSize)
273 smallIcons->setChecked(true);
274 else if (cur == parent->d.normalIconSize)
275 normalIcons->setChecked(true);
276 else if (cur == parent->d.bigIconSize)
277 bigIcons->setChecked(true);
284 stack_widget_->setCurrentWidget(bg_widget_);
285 bg_widget_->setUpdatesEnabled(true);
286 bg_widget_->setFocus();
289 int tabWorkAreaCount()
291 return splitter_->count();
294 TabWorkArea * tabWorkArea(int i)
296 return dynamic_cast<TabWorkArea *>(splitter_->widget(i));
299 TabWorkArea * currentTabWorkArea()
301 int areas = tabWorkAreaCount();
303 // The first TabWorkArea is always the first one, if any.
304 return tabWorkArea(0);
306 for (int i = 0; i != areas; ++i) {
307 TabWorkArea * twa = tabWorkArea(i);
308 if (current_main_work_area_ == twa->currentWorkArea())
312 // None has the focus so we just take the first one.
313 return tabWorkArea(0);
316 #if (QT_VERSION >= 0x040400)
317 void setPreviewFuture(QFuture<docstring> const & f)
319 if (processing_thread_watcher_.isRunning()) {
320 // we prefer to cancel this preview in order to keep a snappy
324 processing_thread_watcher_.setFuture(f);
330 GuiWorkArea * current_work_area_;
331 GuiWorkArea * current_main_work_area_;
332 QSplitter * splitter_;
333 QStackedWidget * stack_widget_;
334 BackgroundWidget * bg_widget_;
336 ToolbarMap toolbars_;
337 ProgressInterface* progress_;
338 /// The main layout box.
340 * \warning Don't Delete! The layout box is actually owned by
341 * whichever toolbar contains it. All the GuiView class needs is a
342 * means of accessing it.
344 * FIXME: replace that with a proper model so that we are not limited
345 * to only one dialog.
350 map<string, DialogPtr> dialogs_;
352 unsigned int smallIconSize;
353 unsigned int normalIconSize;
354 unsigned int bigIconSize;
356 QTimer statusbar_timer_;
357 /// auto-saving of buffers
358 Timeout autosave_timeout_;
359 /// flag against a race condition due to multiclicks, see bug #1119
363 TocModels toc_models_;
365 #if (QT_VERSION >= 0x040400)
367 QFutureWatcher<docstring> autosave_watcher_;
368 QFutureWatcher<docstring> processing_thread_watcher_;
370 string last_export_format;
372 struct DummyWatcher { bool isRunning(){return false;} };
373 DummyWatcher processing_thread_watcher_;
376 static QSet<Buffer const *> busyBuffers;
377 static docstring previewAndDestroy(Buffer const * orig, Buffer * buffer, string const & format);
378 static docstring exportAndDestroy(Buffer const * orig, Buffer * buffer, string const & format);
379 static docstring compileAndDestroy(Buffer const * orig, Buffer * buffer, string const & format);
380 static docstring autosaveAndDestroy(Buffer const * orig, Buffer * buffer);
383 static docstring runAndDestroy(const T& func, Buffer const * orig, Buffer * buffer, string const & format, string const & msg);
385 // TODO syncFunc/previewFunc: use bind
386 bool asyncBufferProcessing(string const & argument,
387 Buffer const * used_buffer,
388 docstring const & msg,
389 docstring (*asyncFunc)(Buffer const *, Buffer *, string const &),
390 bool (Buffer::*syncFunc)(string const &, bool, bool) const,
391 bool (Buffer::*previewFunc)(string const &, bool) const);
393 QTimer processing_cursor_timer_;
394 bool indicates_processing_;
395 QMap<GuiWorkArea*, Qt::CursorShape> orig_cursors_;
396 QVector<GuiWorkArea*> guiWorkAreas();
399 QSet<Buffer const *> GuiView::GuiViewPrivate::busyBuffers;
402 GuiView::GuiView(int id)
403 : d(*new GuiViewPrivate(this)), id_(id), closing_(false), busy_(0)
405 // GuiToolbars *must* be initialised before the menu bar.
406 normalSizedIcons(); // at least on Mac the default is 32 otherwise, which is huge
409 // set ourself as the current view. This is needed for the menu bar
410 // filling, at least for the static special menu item on Mac. Otherwise
411 // they are greyed out.
412 guiApp->setCurrentView(this);
414 // Fill up the menu bar.
415 guiApp->menus().fillMenuBar(menuBar(), this, true);
417 setCentralWidget(d.stack_widget_);
419 // Start autosave timer
420 if (lyxrc.autosave) {
421 d.autosave_timeout_.timeout.connect(bind(&GuiView::autoSave, this));
422 d.autosave_timeout_.setTimeout(lyxrc.autosave * 1000);
423 d.autosave_timeout_.start();
425 connect(&d.statusbar_timer_, SIGNAL(timeout()),
426 this, SLOT(clearMessage()));
428 // We don't want to keep the window in memory if it is closed.
429 setAttribute(Qt::WA_DeleteOnClose, true);
431 #if (!defined(Q_WS_WIN) && !defined(Q_WS_MACX))
432 // assign an icon to main form. We do not do it under Qt/Win or Qt/Mac,
433 // since the icon is provided in the application bundle.
434 setWindowIcon(getPixmap("images/", "lyx", "png"));
437 #if (QT_VERSION >= 0x040300)
438 // use tabbed dock area for multiple docks
439 // (such as "source" and "messages")
440 setDockOptions(QMainWindow::ForceTabbedDocks);
444 setAcceptDrops(true);
446 // add busy indicator to statusbar
447 QLabel * busylabel = new QLabel(statusBar());
448 statusBar()->addPermanentWidget(busylabel);
449 QString fn = toqstr(lyx::libFileSearch("images", "busy.gif").absFileName());
450 QMovie * busyanim = new QMovie(fn, QByteArray(), busylabel);
451 busylabel->setMovie(busyanim);
454 connect(&d.processing_thread_watcher_, SIGNAL(started()),
455 busylabel, SLOT(show()));
456 connect(&d.processing_thread_watcher_, SIGNAL(finished()),
457 busylabel, SLOT(hide()));
459 statusBar()->setSizeGripEnabled(true);
462 #if (QT_VERSION >= 0x040400)
463 connect(&d.autosave_watcher_, SIGNAL(finished()), this,
464 SLOT(autoSaveThreadFinished()));
465 connect(&d.processing_thread_watcher_, SIGNAL(finished()), this,
466 SLOT(processingThreadFinished()));
468 d.processing_cursor_timer_.setInterval(1000 * 3);
469 connect(&d.processing_cursor_timer_, SIGNAL(timeout()), this,
470 SLOT(indicateProcessing()));
473 connect(this, SIGNAL(triggerShowDialog(QString const &, QString const &, Inset *)),
474 SLOT(doShowDialog(QString const &, QString const &, Inset *)));
476 // Forbid too small unresizable window because it can happen
477 // with some window manager under X11.
478 setMinimumSize(300, 200);
480 if (lyxrc.allow_geometry_session) {
481 // Now take care of session management.
486 // no session handling, default to a sane size.
487 setGeometry(50, 50, 690, 510);
490 // clear session data if any.
492 settings.remove("views");
502 QVector<GuiWorkArea*> GuiView::GuiViewPrivate::guiWorkAreas()
504 QVector<GuiWorkArea*> areas;
505 for (int i = 0; i < tabWorkAreaCount(); i++) {
506 TabWorkArea* ta = tabWorkArea(i);
507 for (int u = 0; u < ta->count(); u++) {
508 areas << ta->workArea(u);
515 #if QT_VERSION >= 0x040400
516 void GuiView::setCursorShapes(Qt::CursorShape shape)
518 QVector<GuiWorkArea*> areas = d.guiWorkAreas();
519 Q_FOREACH(GuiWorkArea* wa, areas) {
520 wa->setCursorShape(shape);
525 void GuiView::restoreCursorShapes()
527 QVector<GuiWorkArea*> areas = d.guiWorkAreas();
528 Q_FOREACH(GuiWorkArea* wa, areas) {
529 if (d.orig_cursors_.contains(wa)) {
530 wa->setCursorShape(d.orig_cursors_[wa]);
536 void GuiView::saveCursorShapes()
538 d.orig_cursors_.clear();
539 QVector<GuiWorkArea*> areas = d.guiWorkAreas();
540 Q_FOREACH(GuiWorkArea* wa, areas) {
541 d.orig_cursors_[wa] = wa->cursorShape();
546 void GuiView::indicateProcessing()
548 if (d.indicates_processing_) {
549 restoreCursorShapes();
551 setCursorShapes(Qt::BusyCursor);
553 d.indicates_processing_ = !d.indicates_processing_;
557 void GuiView::processingThreadStarted()
560 d.indicates_processing_ = false;
561 indicateProcessing();
562 d.processing_cursor_timer_.start();
566 void GuiView::processingThreadFinished(bool show_errors)
568 QFutureWatcher<docstring> const * watcher =
569 static_cast<QFutureWatcher<docstring> const *>(sender());
570 message(watcher->result());
573 errors(d.last_export_format);
575 d.processing_cursor_timer_.stop();
576 restoreCursorShapes();
577 d.indicates_processing_ = false;
580 void GuiView::processingThreadFinished()
582 processingThreadFinished(true);
585 void GuiView::autoSaveThreadFinished()
587 processingThreadFinished(false);
592 void GuiView::setCursorShapes(Qt::CursorShape)
597 void GuiView::restoreCursorShapes()
602 void GuiView::saveCursorShapes()
607 void GuiView::indicateProcessing()
612 void GuiView::processingThreadStarted()
617 void GuiView::processingThreadFinished(bool)
622 void GuiView::processingThreadFinished()
627 void GuiView::autoSaveThreadFinished()
633 void GuiView::saveLayout() const
636 settings.beginGroup("views");
637 settings.beginGroup(QString::number(id_));
639 settings.setValue("pos", pos());
640 settings.setValue("size", size());
642 settings.setValue("geometry", saveGeometry());
644 settings.setValue("layout", saveState(0));
645 settings.setValue("icon_size", iconSize());
649 void GuiView::saveUISettings() const
651 // Save the toolbar private states
652 ToolbarMap::iterator end = d.toolbars_.end();
653 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
654 it->second->saveSession();
655 // Now take care of all other dialogs
656 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
657 for (; it!= d.dialogs_.end(); ++it)
658 it->second->saveSession();
662 bool GuiView::restoreLayout()
665 settings.beginGroup("views");
666 settings.beginGroup(QString::number(id_));
667 QString const icon_key = "icon_size";
668 if (!settings.contains(icon_key))
671 //code below is skipped when when ~/.config/LyX is (re)created
672 setIconSize(settings.value(icon_key).toSize());
674 QPoint pos = settings.value("pos", QPoint(50, 50)).toPoint();
675 QSize size = settings.value("size", QSize(690, 510)).toSize();
679 // Work-around for bug #6034: the window ends up in an undetermined
680 // state when trying to restore a maximized window when it is
681 // already maximized.
682 if (!(windowState() & Qt::WindowMaximized))
683 if (!restoreGeometry(settings.value("geometry").toByteArray()))
684 setGeometry(50, 50, 690, 510);
686 // Make sure layout is correctly oriented.
687 setLayoutDirection(qApp->layoutDirection());
689 // Allow the toc and view-source dock widget to be restored if needed.
691 if ((dialog = findOrBuild("toc", true)))
692 // see bug 5082. At least setup title and enabled state.
693 // Visibility will be adjusted by restoreState below.
694 dialog->prepareView();
695 if ((dialog = findOrBuild("view-source", true)))
696 dialog->prepareView();
697 if ((dialog = findOrBuild("progress", true)))
698 dialog->prepareView();
699 if ((dialog = findOrBuild("findreplaceadv", true)))
700 dialog->prepareView();
702 if (!restoreState(settings.value("layout").toByteArray(), 0))
709 GuiToolbar * GuiView::toolbar(string const & name)
711 ToolbarMap::iterator it = d.toolbars_.find(name);
712 if (it != d.toolbars_.end())
715 LYXERR(Debug::GUI, "Toolbar::display: no toolbar named " << name);
720 void GuiView::constructToolbars()
722 ToolbarMap::iterator it = d.toolbars_.begin();
723 for (; it != d.toolbars_.end(); ++it)
727 // I don't like doing this here, but the standard toolbar
728 // destroys this object when it's destroyed itself (vfr)
729 d.layout_ = new LayoutBox(*this);
730 d.stack_widget_->addWidget(d.layout_);
731 d.layout_->move(0,0);
733 // extracts the toolbars from the backend
734 Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
735 Toolbars::Infos::iterator end = guiApp->toolbars().end();
736 for (; cit != end; ++cit)
737 d.toolbars_[cit->name] = new GuiToolbar(*cit, *this);
741 void GuiView::initToolbars()
743 // extracts the toolbars from the backend
744 Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
745 Toolbars::Infos::iterator end = guiApp->toolbars().end();
746 for (; cit != end; ++cit) {
747 GuiToolbar * tb = toolbar(cit->name);
750 int const visibility = guiApp->toolbars().defaultVisibility(cit->name);
751 bool newline = !(visibility & Toolbars::SAMEROW);
752 tb->setVisible(false);
753 tb->setVisibility(visibility);
755 if (visibility & Toolbars::TOP) {
757 addToolBarBreak(Qt::TopToolBarArea);
758 addToolBar(Qt::TopToolBarArea, tb);
761 if (visibility & Toolbars::BOTTOM) {
762 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
763 #if (QT_VERSION >= 0x040202)
765 addToolBarBreak(Qt::BottomToolBarArea);
767 addToolBar(Qt::BottomToolBarArea, tb);
770 if (visibility & Toolbars::LEFT) {
771 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
772 #if (QT_VERSION >= 0x040202)
774 addToolBarBreak(Qt::LeftToolBarArea);
776 addToolBar(Qt::LeftToolBarArea, tb);
779 if (visibility & Toolbars::RIGHT) {
780 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
781 #if (QT_VERSION >= 0x040202)
783 addToolBarBreak(Qt::RightToolBarArea);
785 addToolBar(Qt::RightToolBarArea, tb);
788 if (visibility & Toolbars::ON)
789 tb->setVisible(true);
794 TocModels & GuiView::tocModels()
796 return d.toc_models_;
800 void GuiView::setFocus()
802 LYXERR(Debug::DEBUG, "GuiView::setFocus()" << this);
803 QMainWindow::setFocus();
807 void GuiView::focusInEvent(QFocusEvent * e)
809 LYXERR(Debug::DEBUG, "GuiView::focusInEvent()" << this);
810 QMainWindow::focusInEvent(e);
811 // Make sure guiApp points to the correct view.
812 guiApp->setCurrentView(this);
813 if (currentMainWorkArea())
814 currentMainWorkArea()->setFocus();
815 else if (currentWorkArea())
816 currentWorkArea()->setFocus();
818 d.bg_widget_->setFocus();
822 QMenu * GuiView::createPopupMenu()
824 return d.toolBarPopup(this);
828 void GuiView::showEvent(QShowEvent * e)
830 LYXERR(Debug::GUI, "Passed Geometry "
831 << size().height() << "x" << size().width()
832 << "+" << pos().x() << "+" << pos().y());
834 if (d.splitter_->count() == 0)
835 // No work area, switch to the background widget.
838 QMainWindow::showEvent(e);
842 bool GuiView::closeScheduled()
849 /** Destroy only all tabbed WorkAreas. Destruction of other WorkAreas
850 ** is responsibility of the container (e.g., dialog)
852 void GuiView::closeEvent(QCloseEvent * close_event)
854 LYXERR(Debug::DEBUG, "GuiView::closeEvent()");
856 if (!GuiViewPrivate::busyBuffers.isEmpty()) {
857 Alert::warning(_("Exit LyX"),
858 _("LyX could not be closed because documents are being processed by LyX."));
859 close_event->setAccepted(false);
863 // If the user pressed the x (so we didn't call closeView
864 // programmatically), we want to clear all existing entries.
866 theSession().lastOpened().clear();
871 // it can happen that this event arrives without selecting the view,
872 // e.g. when clicking the close button on a background window.
874 if (!closeWorkAreaAll()) {
876 close_event->ignore();
880 // Make sure that nothing will use this to be closed View.
881 guiApp->unregisterView(this);
883 if (isFullScreen()) {
884 // Switch off fullscreen before closing.
889 // Make sure the timer time out will not trigger a statusbar update.
890 d.statusbar_timer_.stop();
892 // Saving fullscreen requires additional tweaks in the toolbar code.
893 // It wouldn't also work under linux natively.
894 if (lyxrc.allow_geometry_session) {
899 close_event->accept();
903 void GuiView::dragEnterEvent(QDragEnterEvent * event)
905 if (event->mimeData()->hasUrls())
907 /// \todo Ask lyx-devel is this is enough:
908 /// if (event->mimeData()->hasFormat("text/plain"))
909 /// event->acceptProposedAction();
913 void GuiView::dropEvent(QDropEvent * event)
915 QList<QUrl> files = event->mimeData()->urls();
919 LYXERR(Debug::GUI, "GuiView::dropEvent: got URLs!");
920 for (int i = 0; i != files.size(); ++i) {
921 string const file = os::internal_path(fromqstr(
922 files.at(i).toLocalFile()));
926 string const ext = support::getExtension(file);
927 vector<const Format *> found_formats;
929 // Find all formats that have the correct extension.
930 vector<const Format *> const & import_formats
931 = theConverters().importableFormats();
932 vector<const Format *>::const_iterator it = import_formats.begin();
933 for (; it != import_formats.end(); ++it)
934 if ((*it)->extension() == ext)
935 found_formats.push_back(*it);
938 if (found_formats.size() >= 1) {
939 if (found_formats.size() > 1) {
940 //FIXME: show a dialog to choose the correct importable format
942 "Multiple importable formats found, selecting first");
944 string const arg = found_formats[0]->name() + " " + file;
945 cmd = FuncRequest(LFUN_BUFFER_IMPORT, arg);
948 //FIXME: do we have to explicitly check whether it's a lyx file?
950 "No formats found, trying to open it as a lyx file");
951 cmd = FuncRequest(LFUN_FILE_OPEN, file);
953 // add the functions to the queue
954 guiApp->addToFuncRequestQueue(cmd);
957 // now process the collected functions. We perform the events
958 // asynchronously. This prevents potential problems in case the
959 // BufferView is closed within an event.
960 guiApp->processFuncRequestQueueAsync();
964 void GuiView::message(docstring const & str)
966 if (ForkedProcess::iAmAChild())
969 // call is moved to GUI-thread by GuiProgress
970 d.progress_->appendMessage(toqstr(str));
974 void GuiView::clearMessageText()
976 message(docstring());
980 void GuiView::updateStatusBarMessage(QString const & str)
982 statusBar()->showMessage(str);
983 d.statusbar_timer_.stop();
984 d.statusbar_timer_.start(3000);
988 void GuiView::smallSizedIcons()
990 setIconSize(QSize(d.smallIconSize, d.smallIconSize));
994 void GuiView::normalSizedIcons()
996 setIconSize(QSize(d.normalIconSize, d.normalIconSize));
1000 void GuiView::bigSizedIcons()
1002 setIconSize(QSize(d.bigIconSize, d.bigIconSize));
1006 void GuiView::clearMessage()
1008 // FIXME: This code was introduced in r19643 to fix bug #4123. However,
1009 // the hasFocus function mostly returns false, even if the focus is on
1010 // a workarea in this view.
1014 d.statusbar_timer_.stop();
1018 void GuiView::updateWindowTitle(GuiWorkArea * wa)
1020 if (wa != d.current_work_area_
1021 || wa->bufferView().buffer().isInternal())
1023 setWindowTitle(qt_("LyX: ") + wa->windowTitle());
1024 setWindowIconText(wa->windowIconText());
1028 void GuiView::on_currentWorkAreaChanged(GuiWorkArea * wa)
1031 disconnectBufferView();
1032 connectBufferView(wa->bufferView());
1033 connectBuffer(wa->bufferView().buffer());
1034 d.current_work_area_ = wa;
1035 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
1036 this, SLOT(updateWindowTitle(GuiWorkArea *)));
1037 updateWindowTitle(wa);
1041 // The document settings needs to be reinitialised.
1042 updateDialog("document", "");
1044 // Buffer-dependent dialogs must be updated. This is done here because
1045 // some dialogs require buffer()->text.
1050 void GuiView::on_lastWorkAreaRemoved()
1053 // We already are in a close event. Nothing more to do.
1056 if (d.splitter_->count() > 1)
1057 // We have a splitter so don't close anything.
1060 // Reset and updates the dialogs.
1061 d.toc_models_.reset(0);
1062 updateDialog("document", "");
1065 resetWindowTitleAndIconText();
1068 if (lyxrc.open_buffers_in_tabs)
1069 // Nothing more to do, the window should stay open.
1072 if (guiApp->viewIds().size() > 1) {
1078 // On Mac we also close the last window because the application stay
1079 // resident in memory. On other platforms we don't close the last
1080 // window because this would quit the application.
1086 void GuiView::updateStatusBar()
1088 // let the user see the explicit message
1089 if (d.statusbar_timer_.isActive())
1096 void GuiView::showMessage()
1098 QString msg = toqstr(theGuiApp()->viewStatusMessage());
1099 if (msg.isEmpty()) {
1100 BufferView const * bv = currentBufferView();
1102 msg = toqstr(bv->cursor().currentState());
1104 msg = qt_("Welcome to LyX!");
1106 statusBar()->showMessage(msg);
1110 bool GuiView::event(QEvent * e)
1114 // Useful debug code:
1115 //case QEvent::ActivationChange:
1116 //case QEvent::WindowDeactivate:
1117 //case QEvent::Paint:
1118 //case QEvent::Enter:
1119 //case QEvent::Leave:
1120 //case QEvent::HoverEnter:
1121 //case QEvent::HoverLeave:
1122 //case QEvent::HoverMove:
1123 //case QEvent::StatusTip:
1124 //case QEvent::DragEnter:
1125 //case QEvent::DragLeave:
1126 //case QEvent::Drop:
1129 case QEvent::WindowActivate: {
1130 GuiView * old_view = guiApp->currentView();
1131 if (this == old_view) {
1133 return QMainWindow::event(e);
1135 if (old_view && old_view->currentBufferView()) {
1136 // save current selection to the selection buffer to allow
1137 // middle-button paste in this window.
1138 cap::saveSelection(old_view->currentBufferView()->cursor());
1140 guiApp->setCurrentView(this);
1141 if (d.current_work_area_) {
1142 BufferView & bv = d.current_work_area_->bufferView();
1143 connectBufferView(bv);
1144 connectBuffer(bv.buffer());
1145 // The document structure, name and dialogs might have
1146 // changed in another view.
1148 // The document settings needs to be reinitialised.
1149 updateDialog("document", "");
1152 resetWindowTitleAndIconText();
1155 return QMainWindow::event(e);
1158 case QEvent::ShortcutOverride: {
1161 #if (!defined Q_WS_X11) || (QT_VERSION >= 0x040500)
1162 if (isFullScreen() && menuBar()->isHidden()) {
1163 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
1164 // FIXME: we should also try to detect special LyX shortcut such as
1165 // Alt-P and Alt-M. Right now there is a hack in
1166 // GuiWorkArea::processKeySym() that hides again the menubar for
1168 if (ke->modifiers() & Qt::AltModifier && ke->key() != Qt::Key_Alt) {
1170 return QMainWindow::event(e);
1174 return QMainWindow::event(e);
1178 return QMainWindow::event(e);
1182 void GuiView::resetWindowTitleAndIconText()
1184 setWindowTitle(qt_("LyX"));
1185 setWindowIconText(qt_("LyX"));
1188 bool GuiView::focusNextPrevChild(bool /*next*/)
1195 bool GuiView::busy() const
1201 void GuiView::setBusy(bool busy)
1203 bool const busy_before = busy_ > 0;
1204 busy ? ++busy_ : --busy_;
1205 if ((busy_ > 0) == busy_before)
1206 // busy state didn't change
1209 if (d.current_work_area_) {
1210 d.current_work_area_->setUpdatesEnabled(!busy);
1212 d.current_work_area_->stopBlinkingCursor();
1214 d.current_work_area_->startBlinkingCursor();
1218 QApplication::setOverrideCursor(Qt::WaitCursor);
1220 QApplication::restoreOverrideCursor();
1224 GuiWorkArea * GuiView::workArea(int index)
1226 if (TabWorkArea * twa = d.currentTabWorkArea())
1227 if (index < twa->count())
1228 return dynamic_cast<GuiWorkArea *>(twa->widget(index));
1233 GuiWorkArea * GuiView::workArea(Buffer & buffer)
1235 if (currentWorkArea()
1236 && ¤tWorkArea()->bufferView().buffer() == &buffer)
1237 return (GuiWorkArea *) currentWorkArea();
1238 if (TabWorkArea * twa = d.currentTabWorkArea())
1239 return twa->workArea(buffer);
1244 GuiWorkArea * GuiView::addWorkArea(Buffer & buffer)
1246 // Automatically create a TabWorkArea if there are none yet.
1247 TabWorkArea * tab_widget = d.splitter_->count()
1248 ? d.currentTabWorkArea() : addTabWorkArea();
1249 return tab_widget->addWorkArea(buffer, *this);
1253 TabWorkArea * GuiView::addTabWorkArea()
1255 TabWorkArea * twa = new TabWorkArea;
1256 QObject::connect(twa, SIGNAL(currentWorkAreaChanged(GuiWorkArea *)),
1257 this, SLOT(on_currentWorkAreaChanged(GuiWorkArea *)));
1258 QObject::connect(twa, SIGNAL(lastWorkAreaRemoved()),
1259 this, SLOT(on_lastWorkAreaRemoved()));
1261 d.splitter_->addWidget(twa);
1262 d.stack_widget_->setCurrentWidget(d.splitter_);
1267 GuiWorkArea const * GuiView::currentWorkArea() const
1269 return d.current_work_area_;
1273 GuiWorkArea * GuiView::currentWorkArea()
1275 return d.current_work_area_;
1279 GuiWorkArea const * GuiView::currentMainWorkArea() const
1281 if (!d.currentTabWorkArea())
1283 return d.currentTabWorkArea()->currentWorkArea();
1287 GuiWorkArea * GuiView::currentMainWorkArea()
1289 if (!d.currentTabWorkArea())
1291 return d.currentTabWorkArea()->currentWorkArea();
1295 void GuiView::setCurrentWorkArea(GuiWorkArea * wa)
1297 LYXERR(Debug::DEBUG, "Setting current wa: " << wa << endl);
1299 d.current_work_area_ = 0;
1304 // FIXME: I've no clue why this is here and why it accesses
1305 // theGuiApp()->currentView, which might be 0 (bug 6464).
1306 // See also 27525 (vfr).
1307 if (theGuiApp()->currentView() == this
1308 && theGuiApp()->currentView()->currentWorkArea() == wa)
1311 if (currentBufferView())
1312 cap::saveSelection(currentBufferView()->cursor());
1314 theGuiApp()->setCurrentView(this);
1315 d.current_work_area_ = wa;
1317 // We need to reset this now, because it will need to be
1318 // right if the tabWorkArea gets reset in the for loop. We
1319 // will change it back if we aren't in that case.
1320 GuiWorkArea * const old_cmwa = d.current_main_work_area_;
1321 d.current_main_work_area_ = wa;
1323 for (int i = 0; i != d.splitter_->count(); ++i) {
1324 if (d.tabWorkArea(i)->setCurrentWorkArea(wa)) {
1325 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea()
1326 << ", Current main wa: " << currentMainWorkArea());
1331 d.current_main_work_area_ = old_cmwa;
1333 LYXERR(Debug::DEBUG, "This is not a tabbed wa");
1334 on_currentWorkAreaChanged(wa);
1335 BufferView & bv = wa->bufferView();
1336 bv.cursor().fixIfBroken();
1338 wa->setUpdatesEnabled(true);
1339 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() << ", Current main wa: " << currentMainWorkArea());
1343 void GuiView::removeWorkArea(GuiWorkArea * wa)
1345 LASSERT(wa, return);
1346 if (wa == d.current_work_area_) {
1348 disconnectBufferView();
1349 d.current_work_area_ = 0;
1350 d.current_main_work_area_ = 0;
1353 bool found_twa = false;
1354 for (int i = 0; i != d.splitter_->count(); ++i) {
1355 TabWorkArea * twa = d.tabWorkArea(i);
1356 if (twa->removeWorkArea(wa)) {
1357 // Found in this tab group, and deleted the GuiWorkArea.
1359 if (twa->count() != 0) {
1360 if (d.current_work_area_ == 0)
1361 // This means that we are closing the current GuiWorkArea, so
1362 // switch to the next GuiWorkArea in the found TabWorkArea.
1363 setCurrentWorkArea(twa->currentWorkArea());
1365 // No more WorkAreas in this tab group, so delete it.
1372 // It is not a tabbed work area (i.e., the search work area), so it
1373 // should be deleted by other means.
1374 LASSERT(found_twa, /* */);
1376 if (d.current_work_area_ == 0) {
1377 if (d.splitter_->count() != 0) {
1378 TabWorkArea * twa = d.currentTabWorkArea();
1379 setCurrentWorkArea(twa->currentWorkArea());
1381 // No more work areas, switch to the background widget.
1382 setCurrentWorkArea(0);
1388 LayoutBox * GuiView::getLayoutDialog() const
1394 void GuiView::updateLayoutList()
1397 d.layout_->updateContents(false);
1401 void GuiView::updateToolbars()
1403 ToolbarMap::iterator end = d.toolbars_.end();
1404 if (d.current_work_area_) {
1406 d.current_work_area_->bufferView().cursor().inMathed()
1407 && !d.current_work_area_->bufferView().cursor().inRegexped();
1409 lyx::getStatus(FuncRequest(LFUN_LAYOUT_TABULAR)).enabled();
1411 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).enabled() &&
1412 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).onOff(true);
1413 bool const mathmacrotemplate =
1414 lyx::getStatus(FuncRequest(LFUN_IN_MATHMACROTEMPLATE)).enabled();
1416 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1417 it->second->update(math, table, review, mathmacrotemplate);
1419 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1420 it->second->update(false, false, false, false);
1424 void GuiView::setBuffer(Buffer * newBuffer)
1426 LYXERR(Debug::DEBUG, "Setting buffer: " << newBuffer << endl);
1427 LASSERT(newBuffer, return);
1430 GuiWorkArea * wa = workArea(*newBuffer);
1432 newBuffer->masterBuffer()->updateBuffer();
1433 wa = addWorkArea(*newBuffer);
1434 // scroll to the position when the BufferView was last closed
1435 if (lyxrc.use_lastfilepos) {
1436 LastFilePosSection::FilePos filepos =
1437 theSession().lastFilePos().load(newBuffer->fileName());
1438 wa->bufferView().moveToPosition(filepos.pit, filepos.pos, 0, 0);
1441 //Disconnect the old buffer...there's no new one.
1444 connectBuffer(*newBuffer);
1445 connectBufferView(wa->bufferView());
1446 setCurrentWorkArea(wa);
1452 void GuiView::connectBuffer(Buffer & buf)
1454 buf.setGuiDelegate(this);
1458 void GuiView::disconnectBuffer()
1460 if (d.current_work_area_)
1461 d.current_work_area_->bufferView().buffer().setGuiDelegate(0);
1465 void GuiView::connectBufferView(BufferView & bv)
1467 bv.setGuiDelegate(this);
1471 void GuiView::disconnectBufferView()
1473 if (d.current_work_area_)
1474 d.current_work_area_->bufferView().setGuiDelegate(0);
1478 void GuiView::errors(string const & error_type, bool from_master)
1480 BufferView const * const bv = currentBufferView();
1484 ErrorList & el = from_master ?
1485 bv->buffer().masterBuffer()->errorList(error_type) :
1486 bv->buffer().errorList(error_type);
1490 string data = error_type;
1492 data = "from_master|" + error_type;
1493 showDialog("errorlist", data);
1497 void GuiView::updateTocItem(string const & type, DocIterator const & dit)
1499 d.toc_models_.updateItem(toqstr(type), dit);
1503 void GuiView::structureChanged()
1505 d.toc_models_.reset(documentBufferView());
1506 // Navigator needs more than a simple update in this case. It needs to be
1508 updateDialog("toc", "");
1512 void GuiView::updateDialog(string const & name, string const & data)
1514 if (!isDialogVisible(name))
1517 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
1518 if (it == d.dialogs_.end())
1521 Dialog * const dialog = it->second.get();
1522 if (dialog->isVisibleView())
1523 dialog->initialiseParams(data);
1527 BufferView * GuiView::documentBufferView()
1529 return currentMainWorkArea()
1530 ? ¤tMainWorkArea()->bufferView()
1535 BufferView const * GuiView::documentBufferView() const
1537 return currentMainWorkArea()
1538 ? ¤tMainWorkArea()->bufferView()
1543 BufferView * GuiView::currentBufferView()
1545 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1549 BufferView const * GuiView::currentBufferView() const
1551 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1555 #if (QT_VERSION >= 0x040400)
1556 docstring GuiView::GuiViewPrivate::autosaveAndDestroy(
1557 Buffer const * orig, Buffer * buffer)
1559 bool const success = buffer->autoSave();
1561 busyBuffers.remove(orig);
1563 ? _("Automatic save done.")
1564 : _("Automatic save failed!");
1569 void GuiView::autoSave()
1571 LYXERR(Debug::INFO, "Running autoSave()");
1573 Buffer * buffer = documentBufferView()
1574 ? &documentBufferView()->buffer() : 0;
1578 #if (QT_VERSION >= 0x040400)
1579 GuiViewPrivate::busyBuffers.insert(buffer);
1580 QFuture<docstring> f = QtConcurrent::run(GuiViewPrivate::autosaveAndDestroy,
1581 buffer, buffer->clone());
1582 d.autosave_watcher_.setFuture(f);
1586 resetAutosaveTimers();
1590 void GuiView::resetAutosaveTimers()
1593 d.autosave_timeout_.restart();
1597 bool GuiView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1600 Buffer * buf = currentBufferView()
1601 ? ¤tBufferView()->buffer() : 0;
1602 Buffer * doc_buffer = documentBufferView()
1603 ? &(documentBufferView()->buffer()) : 0;
1605 // Check whether we need a buffer
1606 if (!lyxaction.funcHasFlag(cmd.action(), LyXAction::NoBuffer) && !buf) {
1607 // no, exit directly
1608 flag.message(from_utf8(N_("Command not allowed with"
1609 "out any document open")));
1610 flag.setEnabled(false);
1614 if (cmd.origin() == FuncRequest::TOC) {
1615 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
1616 if (!toc || !toc->getStatus(documentBufferView()->cursor(), cmd, flag))
1617 flag.setEnabled(false);
1621 switch(cmd.action()) {
1622 case LFUN_BUFFER_IMPORT:
1625 case LFUN_MASTER_BUFFER_UPDATE:
1626 case LFUN_MASTER_BUFFER_VIEW:
1627 enable = doc_buffer && doc_buffer->parent() != 0
1628 && !d.processing_thread_watcher_.isRunning();
1631 case LFUN_BUFFER_UPDATE:
1632 case LFUN_BUFFER_VIEW: {
1633 if (!doc_buffer || d.processing_thread_watcher_.isRunning()) {
1637 string format = to_utf8(cmd.argument());
1638 if (cmd.argument().empty())
1639 format = doc_buffer->getDefaultOutputFormat();
1640 enable = doc_buffer->isExportableFormat(format);
1644 case LFUN_BUFFER_RELOAD:
1645 enable = doc_buffer && !doc_buffer->isUnnamed()
1646 && doc_buffer->fileName().exists()
1647 && (!doc_buffer->isClean()
1648 || doc_buffer->isExternallyModified(Buffer::timestamp_method));
1651 case LFUN_BUFFER_CHILD_OPEN:
1652 enable = doc_buffer;
1655 case LFUN_BUFFER_WRITE:
1656 enable = doc_buffer && (doc_buffer->isUnnamed() || !doc_buffer->isClean());
1659 //FIXME: This LFUN should be moved to GuiApplication.
1660 case LFUN_BUFFER_WRITE_ALL: {
1661 // We enable the command only if there are some modified buffers
1662 Buffer * first = theBufferList().first();
1667 // We cannot use a for loop as the buffer list is a cycle.
1669 if (!b->isClean()) {
1673 b = theBufferList().next(b);
1674 } while (b != first);
1678 case LFUN_BUFFER_WRITE_AS:
1679 enable = doc_buffer;
1682 case LFUN_BUFFER_CLOSE:
1683 enable = doc_buffer;
1686 case LFUN_BUFFER_CLOSE_ALL:
1687 enable = theBufferList().last() != theBufferList().first();
1690 case LFUN_SPLIT_VIEW:
1691 if (cmd.getArg(0) == "vertical")
1692 enable = doc_buffer && (d.splitter_->count() == 1 ||
1693 d.splitter_->orientation() == Qt::Vertical);
1695 enable = doc_buffer && (d.splitter_->count() == 1 ||
1696 d.splitter_->orientation() == Qt::Horizontal);
1699 case LFUN_CLOSE_TAB_GROUP:
1700 enable = d.currentTabWorkArea();
1703 case LFUN_TOOLBAR_TOGGLE: {
1704 string const name = cmd.getArg(0);
1705 if (GuiToolbar * t = toolbar(name))
1706 flag.setOnOff(t->isVisible());
1709 docstring const msg =
1710 bformat(_("Unknown toolbar \"%1$s\""), from_utf8(name));
1716 case LFUN_DROP_LAYOUTS_CHOICE:
1720 case LFUN_UI_TOGGLE:
1721 flag.setOnOff(isFullScreen());
1724 case LFUN_DIALOG_DISCONNECT_INSET:
1727 case LFUN_DIALOG_HIDE:
1728 // FIXME: should we check if the dialog is shown?
1731 case LFUN_DIALOG_TOGGLE:
1732 flag.setOnOff(isDialogVisible(cmd.getArg(0)));
1733 // fall through to set "enable"
1734 case LFUN_DIALOG_SHOW: {
1735 string const name = cmd.getArg(0);
1737 enable = name == "aboutlyx"
1738 || name == "file" //FIXME: should be removed.
1740 || name == "texinfo"
1741 || name == "progress"
1742 || name == "compare";
1743 else if (name == "print")
1744 enable = doc_buffer->isExportable("dvi")
1745 && lyxrc.print_command != "none";
1746 else if (name == "character" || name == "symbols") {
1747 if (!buf || buf->isReadonly())
1750 // FIXME we should consider passthru
1752 Inset const & in = currentBufferView()->cursor().inset();
1753 enable = !in.getLayout().isPassThru();
1756 else if (name == "latexlog")
1757 enable = FileName(doc_buffer->logName()).isReadableFile();
1758 else if (name == "spellchecker")
1759 enable = theSpellChecker() && !doc_buffer->isReadonly();
1760 else if (name == "vclog")
1761 enable = doc_buffer->lyxvc().inUse();
1765 case LFUN_DIALOG_UPDATE: {
1766 string const name = cmd.getArg(0);
1768 enable = name == "prefs";
1772 case LFUN_COMMAND_EXECUTE:
1774 case LFUN_MENU_OPEN:
1775 // Nothing to check.
1778 case LFUN_COMPLETION_INLINE:
1779 if (!d.current_work_area_
1780 || !d.current_work_area_->completer().inlinePossible(
1781 currentBufferView()->cursor()))
1785 case LFUN_COMPLETION_POPUP:
1786 if (!d.current_work_area_
1787 || !d.current_work_area_->completer().popupPossible(
1788 currentBufferView()->cursor()))
1792 case LFUN_COMPLETION_COMPLETE:
1793 if (!d.current_work_area_
1794 || !d.current_work_area_->completer().inlinePossible(
1795 currentBufferView()->cursor()))
1799 case LFUN_COMPLETION_ACCEPT:
1800 if (!d.current_work_area_
1801 || (!d.current_work_area_->completer().popupVisible()
1802 && !d.current_work_area_->completer().inlineVisible()
1803 && !d.current_work_area_->completer().completionAvailable()))
1807 case LFUN_COMPLETION_CANCEL:
1808 if (!d.current_work_area_
1809 || (!d.current_work_area_->completer().popupVisible()
1810 && !d.current_work_area_->completer().inlineVisible()))
1814 case LFUN_BUFFER_ZOOM_OUT:
1815 enable = doc_buffer && lyxrc.zoom > 10;
1818 case LFUN_BUFFER_ZOOM_IN:
1819 enable = doc_buffer;
1822 case LFUN_BUFFER_NEXT:
1823 case LFUN_BUFFER_PREVIOUS:
1824 // FIXME: should we check is there is an previous or next buffer?
1826 case LFUN_BUFFER_SWITCH:
1827 // toggle on the current buffer, but do not toggle off
1828 // the other ones (is that a good idea?)
1830 && to_utf8(cmd.argument()) == doc_buffer->absFileName())
1831 flag.setOnOff(true);
1834 case LFUN_VC_REGISTER:
1835 enable = doc_buffer && !doc_buffer->lyxvc().inUse();
1837 case LFUN_VC_CHECK_IN:
1838 enable = doc_buffer && doc_buffer->lyxvc().checkInEnabled();
1840 case LFUN_VC_CHECK_OUT:
1841 enable = doc_buffer && doc_buffer->lyxvc().checkOutEnabled();
1843 case LFUN_VC_LOCKING_TOGGLE:
1844 enable = doc_buffer && !doc_buffer->isReadonly()
1845 && doc_buffer->lyxvc().lockingToggleEnabled();
1846 flag.setOnOff(enable && doc_buffer->lyxvc().locking());
1848 case LFUN_VC_REVERT:
1849 enable = doc_buffer && doc_buffer->lyxvc().inUse() && !doc_buffer->isReadonly();
1851 case LFUN_VC_UNDO_LAST:
1852 enable = doc_buffer && doc_buffer->lyxvc().undoLastEnabled();
1854 case LFUN_VC_REPO_UPDATE:
1855 enable = doc_buffer && doc_buffer->lyxvc().repoUpdateEnabled();
1857 case LFUN_VC_COMMAND: {
1858 if (cmd.argument().empty())
1860 if (!doc_buffer && contains(cmd.getArg(0), 'D'))
1864 case LFUN_VC_COMPARE:
1865 enable = doc_buffer && doc_buffer->lyxvc().prepareFileRevisionEnabled();
1868 case LFUN_SERVER_GOTO_FILE_ROW:
1870 case LFUN_FORWARD_SEARCH:
1871 enable = !(lyxrc.forward_search_dvi.empty() && lyxrc.forward_search_pdf.empty());
1879 flag.setEnabled(false);
1885 static FileName selectTemplateFile()
1887 FileDialog dlg(qt_("Select template file"));
1888 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1889 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
1891 FileDialog::Result result = dlg.open(toqstr(lyxrc.template_path),
1892 QStringList(qt_("LyX Documents (*.lyx)")));
1894 if (result.first == FileDialog::Later)
1896 if (result.second.isEmpty())
1898 return FileName(fromqstr(result.second));
1902 Buffer * GuiView::loadDocument(FileName const & filename, bool tolastfiles)
1906 Buffer * newBuffer = 0;
1908 newBuffer = checkAndLoadLyXFile(filename);
1909 } catch (ExceptionMessage const & e) {
1915 message(_("Document not loaded."));
1920 newBuffer->errors("Parse");
1921 setBuffer(newBuffer);
1924 theSession().lastFiles().add(filename);
1931 void GuiView::openDocument(string const & fname)
1933 string initpath = lyxrc.document_path;
1935 if (documentBufferView()) {
1936 string const trypath = documentBufferView()->buffer().filePath();
1937 // If directory is writeable, use this as default.
1938 if (FileName(trypath).isDirWritable())
1944 if (fname.empty()) {
1945 FileDialog dlg(qt_("Select document to open"), LFUN_FILE_OPEN);
1946 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1947 dlg.setButton2(qt_("Examples|#E#e"),
1948 toqstr(addPath(package().system_support().absFileName(), "examples")));
1950 QStringList filter(qt_("LyX Documents (*.lyx)"));
1951 filter << qt_("LyX-1.3.x Documents (*.lyx13)")
1952 << qt_("LyX-1.4.x Documents (*.lyx14)")
1953 << qt_("LyX-1.5.x Documents (*.lyx15)")
1954 << qt_("LyX-1.6.x Documents (*.lyx16)");
1955 FileDialog::Result result =
1956 dlg.open(toqstr(initpath), filter);
1958 if (result.first == FileDialog::Later)
1961 filename = fromqstr(result.second);
1963 // check selected filename
1964 if (filename.empty()) {
1965 message(_("Canceled."));
1971 // get absolute path of file and add ".lyx" to the filename if
1973 FileName const fullname =
1974 fileSearch(string(), filename, "lyx", support::may_not_exist);
1975 if (!fullname.empty())
1976 filename = fullname.absFileName();
1978 if (!fullname.onlyPath().isDirectory()) {
1979 Alert::warning(_("Invalid filename"),
1980 bformat(_("The directory in the given path\n%1$s\ndoes not exist."),
1981 from_utf8(fullname.absFileName())));
1985 // if the file doesn't exist and isn't already open (bug 6645),
1986 // let the user create one
1987 if (!fullname.exists() && !theBufferList().exists(fullname)) {
1988 // the user specifically chose this name. Believe him.
1989 Buffer * const b = newFile(filename, string(), true);
1995 docstring const disp_fn = makeDisplayPath(filename);
1996 message(bformat(_("Opening document %1$s..."), disp_fn));
1999 Buffer * buf = loadDocument(fullname);
2001 str2 = bformat(_("Document %1$s opened."), disp_fn);
2002 if (buf->lyxvc().inUse())
2003 str2 += " " + from_utf8(buf->lyxvc().versionString()) +
2004 " " + _("Version control detected.");
2006 str2 = bformat(_("Could not open document %1$s"), disp_fn);
2011 // FIXME: clean that
2012 static bool import(GuiView * lv, FileName const & filename,
2013 string const & format, ErrorList & errorList)
2015 FileName const lyxfile(support::changeExtension(filename.absFileName(), ".lyx"));
2017 string loader_format;
2018 vector<string> loaders = theConverters().loaders();
2019 if (find(loaders.begin(), loaders.end(), format) == loaders.end()) {
2020 for (vector<string>::const_iterator it = loaders.begin();
2021 it != loaders.end(); ++it) {
2022 if (!theConverters().isReachable(format, *it))
2025 string const tofile =
2026 support::changeExtension(filename.absFileName(),
2027 formats.extension(*it));
2028 if (!theConverters().convert(0, filename, FileName(tofile),
2029 filename, format, *it, errorList))
2031 loader_format = *it;
2034 if (loader_format.empty()) {
2035 frontend::Alert::error(_("Couldn't import file"),
2036 bformat(_("No information for importing the format %1$s."),
2037 formats.prettyName(format)));
2041 loader_format = format;
2043 if (loader_format == "lyx") {
2044 Buffer * buf = lv->loadDocument(lyxfile);
2048 Buffer * const b = newFile(lyxfile.absFileName(), string(), true);
2052 bool as_paragraphs = loader_format == "textparagraph";
2053 string filename2 = (loader_format == format) ? filename.absFileName()
2054 : support::changeExtension(filename.absFileName(),
2055 formats.extension(loader_format));
2056 lv->currentBufferView()->insertPlaintextFile(FileName(filename2),
2058 guiApp->setCurrentView(lv);
2059 lyx::dispatch(FuncRequest(LFUN_MARK_OFF));
2066 void GuiView::importDocument(string const & argument)
2069 string filename = split(argument, format, ' ');
2071 LYXERR(Debug::INFO, format << " file: " << filename);
2073 // need user interaction
2074 if (filename.empty()) {
2075 string initpath = lyxrc.document_path;
2076 if (documentBufferView()) {
2077 string const trypath = documentBufferView()->buffer().filePath();
2078 // If directory is writeable, use this as default.
2079 if (FileName(trypath).isDirWritable())
2083 docstring const text = bformat(_("Select %1$s file to import"),
2084 formats.prettyName(format));
2086 FileDialog dlg(toqstr(text), LFUN_BUFFER_IMPORT);
2087 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2088 dlg.setButton2(qt_("Examples|#E#e"),
2089 toqstr(addPath(package().system_support().absFileName(), "examples")));
2091 docstring filter = formats.prettyName(format);
2094 filter += from_utf8(formats.extension(format));
2097 FileDialog::Result result =
2098 dlg.open(toqstr(initpath), fileFilters(toqstr(filter)));
2100 if (result.first == FileDialog::Later)
2103 filename = fromqstr(result.second);
2105 // check selected filename
2106 if (filename.empty())
2107 message(_("Canceled."));
2110 if (filename.empty())
2113 // get absolute path of file
2114 FileName const fullname(support::makeAbsPath(filename));
2116 FileName const lyxfile(support::changeExtension(fullname.absFileName(), ".lyx"));
2118 // Check if the document already is open
2119 Buffer * buf = theBufferList().getBuffer(lyxfile);
2122 if (!closeBuffer()) {
2123 message(_("Canceled."));
2128 docstring const displaypath = makeDisplayPath(lyxfile.absFileName(), 30);
2130 // if the file exists already, and we didn't do
2131 // -i lyx thefile.lyx, warn
2132 if (lyxfile.exists() && fullname != lyxfile) {
2134 docstring text = bformat(_("The document %1$s already exists.\n\n"
2135 "Do you want to overwrite that document?"), displaypath);
2136 int const ret = Alert::prompt(_("Overwrite document?"),
2137 text, 0, 1, _("&Overwrite"), _("&Cancel"));
2140 message(_("Canceled."));
2145 message(bformat(_("Importing %1$s..."), displaypath));
2146 ErrorList errorList;
2147 if (import(this, fullname, format, errorList))
2148 message(_("imported."));
2150 message(_("file not imported!"));
2152 // FIXME (Abdel 12/08/06): Is there a need to display the error list here?
2156 void GuiView::newDocument(string const & filename, bool from_template)
2158 FileName initpath(lyxrc.document_path);
2159 if (documentBufferView()) {
2160 FileName const trypath(documentBufferView()->buffer().filePath());
2161 // If directory is writeable, use this as default.
2162 if (trypath.isDirWritable())
2166 string templatefile;
2167 if (from_template) {
2168 templatefile = selectTemplateFile().absFileName();
2169 if (templatefile.empty())
2174 if (filename.empty())
2175 b = newUnnamedFile(initpath, to_utf8(_("newfile")), templatefile);
2177 b = newFile(filename, templatefile, true);
2182 // If no new document could be created, it is unsure
2183 // whether there is a valid BufferView.
2184 if (currentBufferView())
2185 // Ensure the cursor is correctly positioned on screen.
2186 currentBufferView()->showCursor();
2190 void GuiView::insertLyXFile(docstring const & fname)
2192 BufferView * bv = documentBufferView();
2197 FileName filename(to_utf8(fname));
2198 if (filename.empty()) {
2199 // Launch a file browser
2201 string initpath = lyxrc.document_path;
2202 string const trypath = bv->buffer().filePath();
2203 // If directory is writeable, use this as default.
2204 if (FileName(trypath).isDirWritable())
2208 FileDialog dlg(qt_("Select LyX document to insert"), LFUN_FILE_INSERT);
2209 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2210 dlg.setButton2(qt_("Examples|#E#e"),
2211 toqstr(addPath(package().system_support().absFileName(),
2214 FileDialog::Result result = dlg.open(toqstr(initpath),
2215 QStringList(qt_("LyX Documents (*.lyx)")));
2217 if (result.first == FileDialog::Later)
2221 filename.set(fromqstr(result.second));
2223 // check selected filename
2224 if (filename.empty()) {
2225 // emit message signal.
2226 message(_("Canceled."));
2231 bv->insertLyXFile(filename);
2232 bv->buffer().errors("Parse");
2236 void GuiView::insertPlaintextFile(docstring const & fname,
2239 BufferView * bv = documentBufferView();
2243 if (!fname.empty() && !FileName::isAbsolute(to_utf8(fname))) {
2244 message(_("Absolute filename expected."));
2249 FileName filename(to_utf8(fname));
2251 if (!filename.empty()) {
2252 bv->insertPlaintextFile(filename, asParagraph);
2256 FileDialog dlg(qt_("Select file to insert"), (asParagraph ?
2257 LFUN_FILE_INSERT_PLAINTEXT_PARA : LFUN_FILE_INSERT_PLAINTEXT));
2259 FileDialog::Result result = dlg.open(toqstr(bv->buffer().filePath()),
2260 QStringList(qt_("All Files (*)")));
2262 if (result.first == FileDialog::Later)
2266 filename.set(fromqstr(result.second));
2268 // check selected filename
2269 if (filename.empty()) {
2270 // emit message signal.
2271 message(_("Canceled."));
2275 bv->insertPlaintextFile(filename, asParagraph);
2279 bool GuiView::renameBuffer(Buffer & b, docstring const & newname)
2281 FileName fname = b.fileName();
2282 FileName const oldname = fname;
2284 if (!newname.empty()) {
2286 fname = support::makeAbsPath(to_utf8(newname), oldname.onlyPath().absFileName());
2288 // Switch to this Buffer.
2291 // No argument? Ask user through dialog.
2293 FileDialog dlg(qt_("Choose a filename to save document as"),
2294 LFUN_BUFFER_WRITE_AS);
2295 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2296 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
2298 if (!isLyXFileName(fname.absFileName()))
2299 fname.changeExtension(".lyx");
2301 FileDialog::Result result =
2302 dlg.save(toqstr(fname.onlyPath().absFileName()),
2303 QStringList(qt_("LyX Documents (*.lyx)")),
2304 toqstr(fname.onlyFileName()));
2306 if (result.first == FileDialog::Later)
2309 fname.set(fromqstr(result.second));
2314 if (!isLyXFileName(fname.absFileName()))
2315 fname.changeExtension(".lyx");
2318 // fname is now the new Buffer location.
2319 if (FileName(fname).exists()) {
2320 docstring const file = makeDisplayPath(fname.absFileName(), 30);
2321 docstring text = bformat(_("The document %1$s already "
2322 "exists.\n\nDo you want to "
2323 "overwrite that document?"),
2325 int const ret = Alert::prompt(_("Overwrite document?"),
2326 text, 0, 2, _("&Overwrite"), _("&Rename"), _("&Cancel"));
2329 case 1: return renameBuffer(b, docstring());
2330 case 2: return false;
2334 return saveBuffer(b, fname);
2338 bool GuiView::saveBuffer(Buffer & b) {
2339 return saveBuffer(b, FileName());
2343 bool GuiView::saveBuffer(Buffer & b, FileName const & fn)
2345 if (workArea(b) && workArea(b)->inDialogMode())
2348 if (fn.empty() && b.isUnnamed())
2349 return renameBuffer(b, docstring());
2355 success = b.saveAs(fn);
2358 theSession().lastFiles().add(b.fileName());
2362 // Switch to this Buffer.
2365 // FIXME: we don't tell the user *WHY* the save failed !!
2366 docstring const file = makeDisplayPath(b.absFileName(), 30);
2367 docstring text = bformat(_("The document %1$s could not be saved.\n\n"
2368 "Do you want to rename the document and "
2369 "try again?"), file);
2370 int const ret = Alert::prompt(_("Rename and save?"),
2371 text, 0, 2, _("&Rename"), _("&Retry"), _("&Cancel"));
2374 if (!renameBuffer(b, docstring()))
2383 return saveBuffer(b);
2387 bool GuiView::hideWorkArea(GuiWorkArea * wa)
2389 return closeWorkArea(wa, false);
2393 bool GuiView::closeWorkArea(GuiWorkArea * wa)
2395 Buffer & buf = wa->bufferView().buffer();
2396 return closeWorkArea(wa, !buf.parent());
2400 bool GuiView::closeBuffer()
2402 GuiWorkArea * wa = currentMainWorkArea();
2403 setCurrentWorkArea(wa);
2404 Buffer & buf = wa->bufferView().buffer();
2405 return wa && closeWorkArea(wa, !buf.parent());
2409 void GuiView::writeSession() const {
2410 GuiWorkArea const * active_wa = currentMainWorkArea();
2411 for (int i = 0; i < d.splitter_->count(); ++i) {
2412 TabWorkArea * twa = d.tabWorkArea(i);
2413 for (int j = 0; j < twa->count(); ++j) {
2414 GuiWorkArea * wa = static_cast<GuiWorkArea *>(twa->widget(j));
2415 Buffer & buf = wa->bufferView().buffer();
2416 theSession().lastOpened().add(buf.fileName(), wa == active_wa);
2422 bool GuiView::closeBufferAll()
2424 // Close the workareas in all other views
2425 QList<int> const ids = guiApp->viewIds();
2426 for (int i = 0; i != ids.size(); ++i) {
2427 if (id_ != ids[i] && !guiApp->view(ids[i]).closeWorkAreaAll())
2431 // Close our own workareas
2432 if (!closeWorkAreaAll())
2435 // Now close the hidden buffers. We prevent hidden buffers from being
2436 // dirty, so we can just close them.
2437 theBufferList().closeAll();
2442 bool GuiView::closeWorkAreaAll()
2444 setCurrentWorkArea(currentMainWorkArea());
2446 // We might be in a situation that there is still a tabWorkArea, but
2447 // there are no tabs anymore. This can happen when we get here after a
2448 // TabWorkArea::lastWorkAreaRemoved() signal. Therefore we count how
2449 // many TabWorkArea's have no documents anymore.
2452 // We have to call count() each time, because it can happen that
2453 // more than one splitter will disappear in one iteration (bug 5998).
2454 for (; d.splitter_->count() > empty_twa; ) {
2455 TabWorkArea * twa = d.tabWorkArea(empty_twa);
2457 if (twa->count() == 0)
2460 setCurrentWorkArea(twa->currentWorkArea());
2461 if (!closeTabWorkArea(twa))
2469 bool GuiView::closeWorkArea(GuiWorkArea * wa, bool close_buffer)
2474 Buffer & buf = wa->bufferView().buffer();
2476 if (close_buffer && GuiViewPrivate::busyBuffers.contains(&buf)) {
2477 Alert::warning(_("Close document"),
2478 _("Document could not be closed because it is being processed by LyX."));
2483 return closeBuffer(buf);
2485 if (!inMultiTabs(wa))
2486 if (!saveBufferIfNeeded(buf, true))
2494 bool GuiView::closeBuffer(Buffer & buf)
2496 // If we are in a close_event all children will be closed in some time,
2497 // so no need to do it here. This will ensure that the children end up
2498 // in the session file in the correct order. If we close the master
2499 // buffer, we can close or release the child buffers here too.
2500 bool success = true;
2502 ListOfBuffers clist = buf.getChildren();
2503 ListOfBuffers::const_iterator it = clist.begin();
2504 ListOfBuffers::const_iterator const bend = clist.end();
2505 for (; it != bend; ++it) {
2506 // If a child is dirty, do not close
2507 // without user intervention
2508 //FIXME: should we look in other tabworkareas?
2509 Buffer * child_buf = *it;
2510 GuiWorkArea * child_wa = workArea(*child_buf);
2512 if (!closeWorkArea(child_wa, true)) {
2517 theBufferList().releaseChild(&buf, child_buf);
2521 // goto bookmark to update bookmark pit.
2522 //FIXME: we should update only the bookmarks related to this buffer!
2523 LYXERR(Debug::DEBUG, "GuiView::closeBuffer()");
2524 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
2525 guiApp->gotoBookmark(i+1, false, false);
2527 if (saveBufferIfNeeded(buf, false)) {
2528 buf.removeAutosaveFile();
2529 theBufferList().release(&buf);
2533 // open all children again to avoid a crash because of dangling
2534 // pointers (bug 6603)
2540 bool GuiView::closeTabWorkArea(TabWorkArea * twa)
2542 while (twa == d.currentTabWorkArea()) {
2543 twa->setCurrentIndex(twa->count()-1);
2545 GuiWorkArea * wa = twa->currentWorkArea();
2546 Buffer & b = wa->bufferView().buffer();
2548 // We only want to close the buffer if the same buffer is not visible
2549 // in another view, and if this is not a child and if we are closing
2550 // a view (not a tabgroup).
2551 bool const close_buffer =
2552 !inOtherView(b) && !b.parent() && closing_;
2554 if (!closeWorkArea(wa, close_buffer))
2561 bool GuiView::saveBufferIfNeeded(Buffer & buf, bool hiding)
2563 if (buf.isClean() || buf.paragraphs().empty())
2566 // Switch to this Buffer.
2571 if (buf.isUnnamed())
2572 file = from_utf8(buf.fileName().onlyFileName());
2574 file = buf.fileName().displayName(30);
2576 // Bring this window to top before asking questions.
2581 if (hiding && buf.isUnnamed()) {
2582 docstring const text = bformat(_("The document %1$s has not been "
2583 "saved yet.\n\nDo you want to save "
2584 "the document?"), file);
2585 ret = Alert::prompt(_("Save new document?"),
2586 text, 0, 1, _("&Save"), _("&Cancel"));
2590 docstring const text = bformat(_("The document %1$s has unsaved changes."
2591 "\n\nDo you want to save the document or discard the changes?"), file);
2592 ret = Alert::prompt(_("Save changed document?"),
2593 text, 0, 2, _("&Save"), _("&Discard"), _("&Cancel"));
2598 if (!saveBuffer(buf))
2602 // If we crash after this we could have no autosave file
2603 // but I guess this is really improbable (Jug).
2604 // Sometimes improbable things happen:
2605 // - see bug http://www.lyx.org/trac/ticket/6587 (ps)
2606 // buf.removeAutosaveFile();
2608 // revert all changes
2619 bool GuiView::inMultiTabs(GuiWorkArea * wa)
2621 Buffer & buf = wa->bufferView().buffer();
2623 for (int i = 0; i != d.splitter_->count(); ++i) {
2624 GuiWorkArea * wa_ = d.tabWorkArea(i)->workArea(buf);
2625 if (wa_ && wa_ != wa)
2628 return inOtherView(buf);
2632 bool GuiView::inOtherView(Buffer & buf)
2634 QList<int> const ids = guiApp->viewIds();
2636 for (int i = 0; i != ids.size(); ++i) {
2640 if (guiApp->view(ids[i]).workArea(buf))
2647 void GuiView::gotoNextOrPreviousBuffer(NextOrPrevious np)
2649 if (!documentBufferView())
2652 if (TabWorkArea * twa = d.currentTabWorkArea()) {
2653 Buffer * const curbuf = &documentBufferView()->buffer();
2654 int nwa = twa->count();
2655 for (int i = 0; i < nwa; ++i) {
2656 if (&workArea(i)->bufferView().buffer() == curbuf) {
2658 if (np == NEXTBUFFER)
2659 next_index = (i == nwa - 1 ? 0 : i + 1);
2661 next_index = (i == 0 ? nwa - 1 : i - 1);
2662 setBuffer(&workArea(next_index)->bufferView().buffer());
2670 /// make sure the document is saved
2671 static bool ensureBufferClean(Buffer * buffer)
2673 LASSERT(buffer, return false);
2674 if (buffer->isClean() && !buffer->isUnnamed())
2677 docstring const file = buffer->fileName().displayName(30);
2680 if (!buffer->isUnnamed()) {
2681 text = bformat(_("The document %1$s has unsaved "
2682 "changes.\n\nDo you want to save "
2683 "the document?"), file);
2684 title = _("Save changed document?");
2687 text = bformat(_("The document %1$s has not been "
2688 "saved yet.\n\nDo you want to save "
2689 "the document?"), file);
2690 title = _("Save new document?");
2692 int const ret = Alert::prompt(title, text, 0, 1, _("&Save"), _("&Cancel"));
2695 dispatch(FuncRequest(LFUN_BUFFER_WRITE));
2697 return buffer->isClean() && !buffer->isUnnamed();
2701 bool GuiView::reloadBuffer(Buffer & buf)
2703 Buffer::ReadStatus status = buf.reload();
2704 return status == Buffer::ReadSuccess;
2708 void GuiView::checkExternallyModifiedBuffers()
2710 BufferList::iterator bit = theBufferList().begin();
2711 BufferList::iterator const bend = theBufferList().end();
2712 for (; bit != bend; ++bit) {
2713 Buffer * buf = *bit;
2714 if (buf->fileName().exists()
2715 && buf->isExternallyModified(Buffer::checksum_method)) {
2716 docstring text = bformat(_("Document \n%1$s\n has been externally modified."
2717 " Reload now? Any local changes will be lost."),
2718 from_utf8(buf->absFileName()));
2719 int const ret = Alert::prompt(_("Reload externally changed document?"),
2720 text, 0, 1, _("&Reload"), _("&Cancel"));
2728 void GuiView::dispatchVC(FuncRequest const & cmd, DispatchResult & dr)
2730 Buffer * buffer = documentBufferView()
2731 ? &(documentBufferView()->buffer()) : 0;
2733 switch (cmd.action()) {
2734 case LFUN_VC_REGISTER:
2735 if (!buffer || !ensureBufferClean(buffer))
2737 if (!buffer->lyxvc().inUse()) {
2738 if (buffer->lyxvc().registrer()) {
2739 reloadBuffer(*buffer);
2740 dr.suppressMessageUpdate();
2745 case LFUN_VC_CHECK_IN:
2746 if (!buffer || !ensureBufferClean(buffer))
2748 if (buffer->lyxvc().inUse() && !buffer->isReadonly()) {
2749 dr.setMessage(buffer->lyxvc().checkIn());
2750 if (!dr.message().empty())
2751 reloadBuffer(*buffer);
2755 case LFUN_VC_CHECK_OUT:
2756 if (!buffer || !ensureBufferClean(buffer))
2758 if (buffer->lyxvc().inUse()) {
2759 dr.setMessage(buffer->lyxvc().checkOut());
2760 reloadBuffer(*buffer);
2764 case LFUN_VC_LOCKING_TOGGLE:
2765 LASSERT(buffer, return);
2766 if (!ensureBufferClean(buffer) || buffer->isReadonly())
2768 if (buffer->lyxvc().inUse()) {
2769 string res = buffer->lyxvc().lockingToggle();
2771 frontend::Alert::error(_("Revision control error."),
2772 _("Error when setting the locking property."));
2775 reloadBuffer(*buffer);
2780 case LFUN_VC_REVERT:
2781 LASSERT(buffer, return);
2782 if (buffer->lyxvc().revert()) {
2783 reloadBuffer(*buffer);
2784 dr.suppressMessageUpdate();
2788 case LFUN_VC_UNDO_LAST:
2789 LASSERT(buffer, return);
2790 buffer->lyxvc().undoLast();
2791 reloadBuffer(*buffer);
2792 dr.suppressMessageUpdate();
2795 case LFUN_VC_REPO_UPDATE:
2796 LASSERT(buffer, return);
2797 if (ensureBufferClean(buffer)) {
2798 dr.setMessage(buffer->lyxvc().repoUpdate());
2799 checkExternallyModifiedBuffers();
2803 case LFUN_VC_COMMAND: {
2804 string flag = cmd.getArg(0);
2805 if (buffer && contains(flag, 'R') && !ensureBufferClean(buffer))
2808 if (contains(flag, 'M')) {
2809 if (!Alert::askForText(message, _("LyX VC: Log Message")))
2812 string path = cmd.getArg(1);
2813 if (contains(path, "$$p") && buffer)
2814 path = subst(path, "$$p", buffer->filePath());
2815 LYXERR(Debug::LYXVC, "Directory: " << path);
2817 if (!pp.isReadableDirectory()) {
2818 lyxerr << _("Directory is not accessible.") << endl;
2821 support::PathChanger p(pp);
2823 string command = cmd.getArg(2);
2824 if (command.empty())
2827 command = subst(command, "$$i", buffer->absFileName());
2828 command = subst(command, "$$p", buffer->filePath());
2830 command = subst(command, "$$m", to_utf8(message));
2831 LYXERR(Debug::LYXVC, "Command: " << command);
2833 one.startscript(Systemcall::Wait, command);
2837 if (contains(flag, 'I'))
2838 buffer->markDirty();
2839 if (contains(flag, 'R'))
2840 reloadBuffer(*buffer);
2845 case LFUN_VC_COMPARE: {
2847 if (cmd.argument().empty()) {
2848 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "comparehistory"));
2852 string rev1 = cmd.getArg(0);
2856 if (!buffer->lyxvc().prepareFileRevision(rev1, f1))
2859 if (isStrInt(rev1) && convert<int>(rev1) <= 0) {
2860 f2 = buffer->absFileName();
2862 string rev2 = cmd.getArg(1);
2866 if (!buffer->lyxvc().prepareFileRevision(rev2, f2))
2870 LYXERR(Debug::LYXVC, "Launching comparison for fetched revisions:\n" <<
2871 f1 << "\n" << f2 << "\n" );
2872 string par = "compare run " + quoteName(f1) + " " + quoteName(f2);
2873 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, par));
2883 void GuiView::openChildDocument(string const & fname)
2885 LASSERT(documentBufferView(), return);
2886 Buffer & buffer = documentBufferView()->buffer();
2887 FileName const filename = support::makeAbsPath(fname, buffer.filePath());
2888 documentBufferView()->saveBookmark(false);
2890 if (theBufferList().exists(filename)) {
2891 child = theBufferList().getBuffer(filename);
2894 message(bformat(_("Opening child document %1$s..."),
2895 makeDisplayPath(filename.absFileName())));
2896 child = loadDocument(filename, false);
2898 // Set the parent name of the child document.
2899 // This makes insertion of citations and references in the child work,
2900 // when the target is in the parent or another child document.
2902 child->setParent(&buffer);
2906 bool GuiView::goToFileRow(string const & argument)
2910 size_t i = argument.find_last_of(' ');
2911 if (i != string::npos) {
2912 file_name = os::internal_path(trim(argument.substr(0, i)));
2913 istringstream is(argument.substr(i + 1));
2918 if (i == string::npos) {
2919 LYXERR0("Wrong argument: " << argument);
2923 string const abstmp = package().temp_dir().absFileName();
2924 string const realtmp = package().temp_dir().realPath();
2925 // We have to use os::path_prefix_is() here, instead of
2926 // simply prefixIs(), because the file name comes from
2927 // an external application and may need case adjustment.
2928 if (os::path_prefix_is(file_name, abstmp, os::CASE_ADJUSTED)
2929 || os::path_prefix_is(file_name, realtmp, os::CASE_ADJUSTED)) {
2930 // Needed by inverse dvi search. If it is a file
2931 // in tmpdir, call the apropriated function.
2932 // If tmpdir is a symlink, we may have the real
2933 // path passed back, so we correct for that.
2934 if (!prefixIs(file_name, abstmp))
2935 file_name = subst(file_name, realtmp, abstmp);
2936 buf = theBufferList().getBufferFromTmp(file_name);
2938 // Must replace extension of the file to be .lyx
2939 // and get full path
2940 FileName const s = fileSearch(string(),
2941 support::changeExtension(file_name, ".lyx"), "lyx");
2942 // Either change buffer or load the file
2943 if (theBufferList().exists(s))
2944 buf = theBufferList().getBuffer(s);
2945 else if (s.exists()) {
2946 buf = loadDocument(s);
2951 _("File does not exist: %1$s"),
2952 makeDisplayPath(file_name)));
2957 documentBufferView()->setCursorFromRow(row);
2962 #if (QT_VERSION >= 0x040400)
2964 docstring GuiView::GuiViewPrivate::runAndDestroy(const T& func, Buffer const * orig, Buffer * buffer, string const & format, string const & msg)
2966 bool const update_unincluded =
2967 buffer->params().maintain_unincluded_children
2968 && !buffer->params().getIncludedChildren().empty();
2969 bool const success = func(format, update_unincluded);
2971 busyBuffers.remove(orig);
2972 if (msg == "preview") {
2974 ? bformat(_("Successful preview of format: %1$s"), from_utf8(format))
2975 : bformat(_("Error while previewing format: %1$s"), from_utf8(format));
2978 ? bformat(_("Successful export to format: %1$s"), from_utf8(format))
2979 : bformat(_("Error while exporting format: %1$s"), from_utf8(format));
2983 docstring GuiView::GuiViewPrivate::compileAndDestroy(Buffer const * orig, Buffer * buffer, string const & format)
2985 bool (Buffer::* mem_func)(std::string const &, bool, bool) const = &Buffer::doExport;
2986 return runAndDestroy(bind(mem_func, buffer, _1, true, _2), orig, buffer, format, "export");
2990 docstring GuiView::GuiViewPrivate::exportAndDestroy(Buffer const * orig, Buffer * buffer, string const & format)
2992 bool (Buffer::* mem_func)(std::string const &, bool, bool) const = &Buffer::doExport;
2993 return runAndDestroy(bind(mem_func, buffer, _1, false, _2), orig, buffer, format, "export");
2997 docstring GuiView::GuiViewPrivate::previewAndDestroy(Buffer const * orig, Buffer * buffer, string const & format)
2999 bool(Buffer::* mem_func)(std::string const &, bool) const = &Buffer::preview;
3000 return runAndDestroy(bind(mem_func, buffer, _1, _2), orig, buffer, format, "preview");
3005 // not used, but the linker needs them
3007 docstring GuiView::GuiViewPrivate::compileAndDestroy(
3008 Buffer const *, Buffer *, string const &)
3014 docstring GuiView::GuiViewPrivate::exportAndDestroy(
3015 Buffer const *, Buffer *, string const &)
3021 docstring GuiView::GuiViewPrivate::previewAndDestroy(
3022 Buffer const *, Buffer *, string const &)
3030 bool GuiView::GuiViewPrivate::asyncBufferProcessing(
3031 string const & argument,
3032 Buffer const * used_buffer,
3033 docstring const & msg,
3034 docstring (*asyncFunc)(Buffer const *, Buffer *, string const &),
3035 bool (Buffer::*syncFunc)(string const &, bool, bool) const,
3036 bool (Buffer::*previewFunc)(string const &, bool) const)
3041 string format = argument;
3043 format = used_buffer->getDefaultOutputFormat();
3045 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
3046 gv_->processingThreadStarted();
3048 progress_->clearMessages();
3051 GuiViewPrivate::busyBuffers.insert(used_buffer);
3052 QFuture<docstring> f = QtConcurrent::run(
3055 used_buffer->clone(),
3057 setPreviewFuture(f);
3058 last_export_format = used_buffer->bufferFormat();
3061 // We are asynchronous, so we don't know here anything about the success
3065 // TODO check here if it breaks exporting with Qt < 4.4
3066 bool const update_unincluded =
3067 used_buffer->params().maintain_unincluded_children &&
3068 !used_buffer->params().getIncludedChildren().empty();
3069 return (used_buffer->*syncFunc)(format, true, update_unincluded);
3070 } else if (previewFunc) {
3071 return (used_buffer->*previewFunc)(format, false);
3078 void GuiView::dispatchToBufferView(FuncRequest const & cmd, DispatchResult & dr)
3080 BufferView * bv = currentBufferView();
3083 // Let the current BufferView dispatch its own actions.
3084 bv->dispatch(cmd, dr);
3085 if (dr.dispatched())
3088 // Try with the document BufferView dispatch if any.
3089 BufferView * doc_bv = documentBufferView();
3091 doc_bv->dispatch(cmd, dr);
3092 if (dr.dispatched())
3096 // Then let the current Cursor dispatch its own actions.
3097 bv->cursor().dispatch(cmd);
3099 // update completion. We do it here and not in
3100 // processKeySym to avoid another redraw just for a
3101 // changed inline completion
3102 if (cmd.origin() == FuncRequest::KEYBOARD) {
3103 if (cmd.action() == LFUN_SELF_INSERT
3104 || (cmd.action() == LFUN_ERT_INSERT && bv->cursor().inMathed()))
3105 updateCompletion(bv->cursor(), true, true);
3106 else if (cmd.action() == LFUN_CHAR_DELETE_BACKWARD)
3107 updateCompletion(bv->cursor(), false, true);
3109 updateCompletion(bv->cursor(), false, false);
3112 dr = bv->cursor().result();
3116 void GuiView::dispatch(FuncRequest const & cmd, DispatchResult & dr)
3118 BufferView * bv = currentBufferView();
3119 // By default we won't need any update.
3120 dr.screenUpdate(Update::None);
3121 // assume cmd will be dispatched
3122 dr.dispatched(true);
3124 Buffer * doc_buffer = documentBufferView()
3125 ? &(documentBufferView()->buffer()) : 0;
3127 if (cmd.origin() == FuncRequest::TOC) {
3128 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
3129 // FIXME: do we need to pass a DispatchResult object here?
3130 toc->doDispatch(bv->cursor(), cmd);
3134 string const argument = to_utf8(cmd.argument());
3136 switch(cmd.action()) {
3137 case LFUN_BUFFER_CHILD_OPEN:
3138 openChildDocument(to_utf8(cmd.argument()));
3141 case LFUN_BUFFER_IMPORT:
3142 importDocument(to_utf8(cmd.argument()));
3145 case LFUN_BUFFER_EXPORT: {
3148 // GCC only sees strfwd.h when building merged
3149 if (::lyx::operator==(cmd.argument(), "custom")) {
3150 dispatch(FuncRequest(LFUN_DIALOG_SHOW, "sendto"), dr);
3153 #if QT_VERSION < 0x040400
3154 if (!doc_buffer->doExport(argument, false)) {
3156 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
3160 /* TODO/Review: Is it a problem to also export the children?
3161 See the update_unincluded flag */
3162 d.asyncBufferProcessing(argument,
3165 &GuiViewPrivate::exportAndDestroy,
3168 // TODO Inform user about success
3173 case LFUN_BUFFER_UPDATE: {
3174 d.asyncBufferProcessing(argument,
3177 &GuiViewPrivate::compileAndDestroy,
3182 case LFUN_BUFFER_VIEW: {
3183 d.asyncBufferProcessing(argument,
3185 _("Previewing ..."),
3186 &GuiViewPrivate::previewAndDestroy,
3191 case LFUN_MASTER_BUFFER_UPDATE: {
3192 d.asyncBufferProcessing(argument,
3193 (doc_buffer ? doc_buffer->masterBuffer() : 0),
3195 &GuiViewPrivate::compileAndDestroy,
3200 case LFUN_MASTER_BUFFER_VIEW: {
3201 d.asyncBufferProcessing(argument,
3202 (doc_buffer ? doc_buffer->masterBuffer() : 0),
3204 &GuiViewPrivate::previewAndDestroy,
3205 0, &Buffer::preview);
3208 case LFUN_BUFFER_SWITCH: {
3209 string const file_name = to_utf8(cmd.argument());
3210 if (!FileName::isAbsolute(file_name)) {
3212 dr.setMessage(_("Absolute filename expected."));
3216 Buffer * buffer = theBufferList().getBuffer(FileName(file_name));
3219 dr.setMessage(_("Document not loaded"));
3223 // Do we open or switch to the buffer in this view ?
3224 if (workArea(*buffer)
3225 || lyxrc.open_buffers_in_tabs || !documentBufferView()) {
3230 // Look for the buffer in other views
3231 QList<int> const ids = guiApp->viewIds();
3233 for (; i != ids.size(); ++i) {
3234 GuiView & gv = guiApp->view(ids[i]);
3235 if (gv.workArea(*buffer)) {
3236 gv.activateWindow();
3237 gv.setBuffer(buffer);
3242 // If necessary, open a new window as a last resort
3243 if (i == ids.size()) {
3244 lyx::dispatch(FuncRequest(LFUN_WINDOW_NEW));
3250 case LFUN_BUFFER_NEXT:
3251 gotoNextOrPreviousBuffer(NEXTBUFFER);
3254 case LFUN_BUFFER_PREVIOUS:
3255 gotoNextOrPreviousBuffer(PREVBUFFER);
3258 case LFUN_COMMAND_EXECUTE: {
3259 bool const show_it = cmd.argument() != "off";
3260 // FIXME: this is a hack, "minibuffer" should not be
3262 if (GuiToolbar * t = toolbar("minibuffer")) {
3263 t->setVisible(show_it);
3264 if (show_it && t->commandBuffer())
3265 t->commandBuffer()->setFocus();
3269 case LFUN_DROP_LAYOUTS_CHOICE:
3270 d.layout_->showPopup();
3273 case LFUN_MENU_OPEN:
3274 if (QMenu * menu = guiApp->menus().menu(toqstr(cmd.argument()), *this))
3275 menu->exec(QCursor::pos());
3278 case LFUN_FILE_INSERT:
3279 insertLyXFile(cmd.argument());
3282 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
3283 insertPlaintextFile(cmd.argument(), true);
3286 case LFUN_FILE_INSERT_PLAINTEXT:
3287 insertPlaintextFile(cmd.argument(), false);
3290 case LFUN_BUFFER_RELOAD: {
3291 LASSERT(doc_buffer, break);
3294 if (!doc_buffer->isClean()) {
3295 docstring const file =
3296 makeDisplayPath(doc_buffer->absFileName(), 20);
3297 docstring text = bformat(_("Any changes will be lost. "
3298 "Are you sure you want to revert to the saved version "
3299 "of the document %1$s?"), file);
3300 ret = Alert::prompt(_("Revert to saved document?"),
3301 text, 1, 1, _("&Revert"), _("&Cancel"));
3305 doc_buffer->markClean();
3306 reloadBuffer(*doc_buffer);
3307 dr.forceBufferUpdate();
3312 case LFUN_BUFFER_WRITE:
3313 LASSERT(doc_buffer, break);
3314 saveBuffer(*doc_buffer);
3317 case LFUN_BUFFER_WRITE_AS:
3318 LASSERT(doc_buffer, break);
3319 renameBuffer(*doc_buffer, cmd.argument());
3322 case LFUN_BUFFER_WRITE_ALL: {
3323 Buffer * first = theBufferList().first();
3326 message(_("Saving all documents..."));
3327 // We cannot use a for loop as the buffer list cycles.
3330 if (!b->isClean()) {
3332 LYXERR(Debug::ACTION, "Saved " << b->absFileName());
3334 b = theBufferList().next(b);
3335 } while (b != first);
3336 dr.setMessage(_("All documents saved."));
3340 case LFUN_BUFFER_CLOSE:
3344 case LFUN_BUFFER_CLOSE_ALL:
3348 case LFUN_TOOLBAR_TOGGLE: {
3349 string const name = cmd.getArg(0);
3350 if (GuiToolbar * t = toolbar(name))
3355 case LFUN_DIALOG_UPDATE: {
3356 string const name = to_utf8(cmd.argument());
3357 if (name == "prefs" || name == "document")
3358 updateDialog(name, string());
3359 else if (name == "paragraph")
3360 lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
3361 else if (currentBufferView()) {
3362 Inset * inset = currentBufferView()->editedInset(name);
3363 // Can only update a dialog connected to an existing inset
3365 // FIXME: get rid of this indirection; GuiView ask the inset
3366 // if he is kind enough to update itself...
3367 FuncRequest fr(LFUN_INSET_DIALOG_UPDATE, cmd.argument());
3368 //FIXME: pass DispatchResult here?
3369 inset->dispatch(currentBufferView()->cursor(), fr);
3375 case LFUN_DIALOG_TOGGLE: {
3376 if (isDialogVisible(cmd.getArg(0)))
3377 dispatch(FuncRequest(LFUN_DIALOG_HIDE, cmd.argument()), dr);
3379 dispatch(FuncRequest(LFUN_DIALOG_SHOW, cmd.argument()), dr);
3383 case LFUN_DIALOG_DISCONNECT_INSET:
3384 disconnectDialog(to_utf8(cmd.argument()));
3387 case LFUN_DIALOG_HIDE: {
3388 guiApp->hideDialogs(to_utf8(cmd.argument()), 0);
3392 case LFUN_DIALOG_SHOW: {
3393 string const name = cmd.getArg(0);
3394 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
3396 if (name == "character") {
3397 data = freefont2string();
3399 showDialog("character", data);
3400 } else if (name == "latexlog") {
3401 Buffer::LogType type;
3402 string const logfile = doc_buffer->logName(&type);
3404 case Buffer::latexlog:
3407 case Buffer::buildlog:
3411 data += Lexer::quoteString(logfile);
3412 showDialog("log", data);
3413 } else if (name == "vclog") {
3414 string const data = "vc " +
3415 Lexer::quoteString(doc_buffer->lyxvc().getLogFile());
3416 showDialog("log", data);
3417 } else if (name == "symbols") {
3418 data = bv->cursor().getEncoding()->name();
3420 showDialog("symbols", data);
3422 } else if (name == "prefs" && isFullScreen()) {
3423 lfunUiToggle("fullscreen");
3424 showDialog("prefs", data);
3426 showDialog(name, data);
3431 dr.setMessage(cmd.argument());
3434 case LFUN_UI_TOGGLE: {
3435 string arg = cmd.getArg(0);
3436 if (!lfunUiToggle(arg)) {
3437 docstring const msg = "ui-toggle " + _("%1$s unknown command!");
3438 dr.setMessage(bformat(msg, from_utf8(arg)));
3440 // Make sure the keyboard focus stays in the work area.
3445 case LFUN_SPLIT_VIEW: {
3446 LASSERT(doc_buffer, break);
3447 string const orientation = cmd.getArg(0);
3448 d.splitter_->setOrientation(orientation == "vertical"
3449 ? Qt::Vertical : Qt::Horizontal);
3450 TabWorkArea * twa = addTabWorkArea();
3451 GuiWorkArea * wa = twa->addWorkArea(*doc_buffer, *this);
3452 setCurrentWorkArea(wa);
3455 case LFUN_CLOSE_TAB_GROUP:
3456 if (TabWorkArea * twa = d.currentTabWorkArea()) {
3457 closeTabWorkArea(twa);
3458 d.current_work_area_ = 0;
3459 twa = d.currentTabWorkArea();
3460 // Switch to the next GuiWorkArea in the found TabWorkArea.
3462 // Make sure the work area is up to date.
3463 setCurrentWorkArea(twa->currentWorkArea());
3465 setCurrentWorkArea(0);
3470 case LFUN_COMPLETION_INLINE:
3471 if (d.current_work_area_)
3472 d.current_work_area_->completer().showInline();
3475 case LFUN_COMPLETION_POPUP:
3476 if (d.current_work_area_)
3477 d.current_work_area_->completer().showPopup();
3481 case LFUN_COMPLETION_COMPLETE:
3482 if (d.current_work_area_)
3483 d.current_work_area_->completer().tab();
3486 case LFUN_COMPLETION_CANCEL:
3487 if (d.current_work_area_) {
3488 if (d.current_work_area_->completer().popupVisible())
3489 d.current_work_area_->completer().hidePopup();
3491 d.current_work_area_->completer().hideInline();
3495 case LFUN_COMPLETION_ACCEPT:
3496 if (d.current_work_area_)
3497 d.current_work_area_->completer().activate();
3500 case LFUN_BUFFER_ZOOM_IN:
3501 case LFUN_BUFFER_ZOOM_OUT:
3502 if (cmd.argument().empty()) {
3503 if (cmd.action() == LFUN_BUFFER_ZOOM_IN)
3508 lyxrc.zoom += convert<int>(cmd.argument());
3510 if (lyxrc.zoom < 10)
3513 // The global QPixmapCache is used in GuiPainter to cache text
3514 // painting so we must reset it.
3515 QPixmapCache::clear();
3516 guiApp->fontLoader().update();
3517 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
3520 case LFUN_VC_REGISTER:
3521 case LFUN_VC_CHECK_IN:
3522 case LFUN_VC_CHECK_OUT:
3523 case LFUN_VC_REPO_UPDATE:
3524 case LFUN_VC_LOCKING_TOGGLE:
3525 case LFUN_VC_REVERT:
3526 case LFUN_VC_UNDO_LAST:
3527 case LFUN_VC_COMMAND:
3528 case LFUN_VC_COMPARE:
3529 dispatchVC(cmd, dr);
3532 case LFUN_SERVER_GOTO_FILE_ROW:
3533 goToFileRow(to_utf8(cmd.argument()));
3536 case LFUN_FORWARD_SEARCH: {
3537 FileName const path(doc_buffer->temppath());
3538 string const texname = doc_buffer->latexName();
3539 FileName const dviname(addName(path.absFileName(),
3540 support::changeExtension(texname, "dvi")));
3541 FileName const pdfname(addName(path.absFileName(),
3542 support::changeExtension(texname, "pdf")));
3543 if (!dviname.exists() && !pdfname.exists()) {
3544 dr.setMessage(_("Please, preview the document first."));
3547 string outname = dviname.onlyFileName();
3548 string command = lyxrc.forward_search_dvi;
3549 if (!dviname.exists() ||
3550 pdfname.lastModified() > dviname.lastModified()) {
3551 outname = pdfname.onlyFileName();
3552 command = lyxrc.forward_search_pdf;
3555 int row = doc_buffer->texrow().getRowFromIdPos(bv->cursor().paragraph().id(), bv->cursor().pos());
3556 LYXERR(Debug::ACTION, "Forward search: row:" << row
3557 << " id:" << bv->cursor().paragraph().id());
3558 if (!row || command.empty()) {
3559 dr.setMessage(_("Couldn't proceed."));
3562 string texrow = convert<string>(row);
3564 command = subst(command, "$$n", texrow);
3565 command = subst(command, "$$t", texname);
3566 command = subst(command, "$$o", outname);
3568 PathChanger p(path);
3570 one.startscript(Systemcall::DontWait, command);
3574 // The LFUN must be for one of BufferView, Buffer or Cursor;
3576 dispatchToBufferView(cmd, dr);
3580 // Part of automatic menu appearance feature.
3581 if (isFullScreen()) {
3582 if (menuBar()->isVisible() && lyxrc.full_screen_menubar)
3584 if (statusBar()->isVisible())
3585 statusBar()->hide();
3590 bool GuiView::lfunUiToggle(string const & ui_component)
3592 if (ui_component == "scrollbar") {
3593 // hide() is of no help
3594 if (d.current_work_area_->verticalScrollBarPolicy() ==
3595 Qt::ScrollBarAlwaysOff)
3597 d.current_work_area_->setVerticalScrollBarPolicy(
3598 Qt::ScrollBarAsNeeded);
3600 d.current_work_area_->setVerticalScrollBarPolicy(
3601 Qt::ScrollBarAlwaysOff);
3602 } else if (ui_component == "statusbar") {
3603 statusBar()->setVisible(!statusBar()->isVisible());
3604 } else if (ui_component == "menubar") {
3605 menuBar()->setVisible(!menuBar()->isVisible());
3607 #if QT_VERSION >= 0x040300
3608 if (ui_component == "frame") {
3610 getContentsMargins(&l, &t, &r, &b);
3611 //are the frames in default state?
3612 d.current_work_area_->setFrameStyle(QFrame::NoFrame);
3614 setContentsMargins(-2, -2, -2, -2);
3616 setContentsMargins(0, 0, 0, 0);
3620 if (ui_component == "fullscreen") {
3628 void GuiView::toggleFullScreen()
3630 if (isFullScreen()) {
3631 for (int i = 0; i != d.splitter_->count(); ++i)
3632 d.tabWorkArea(i)->setFullScreen(false);
3633 #if QT_VERSION >= 0x040300
3634 setContentsMargins(0, 0, 0, 0);
3636 setWindowState(windowState() ^ Qt::WindowFullScreen);
3639 statusBar()->show();
3642 hideDialogs("prefs", 0);
3643 for (int i = 0; i != d.splitter_->count(); ++i)
3644 d.tabWorkArea(i)->setFullScreen(true);
3645 #if QT_VERSION >= 0x040300
3646 setContentsMargins(-2, -2, -2, -2);
3649 setWindowState(windowState() ^ Qt::WindowFullScreen);
3650 statusBar()->hide();
3651 if (lyxrc.full_screen_menubar)
3653 if (lyxrc.full_screen_toolbars) {
3654 ToolbarMap::iterator end = d.toolbars_.end();
3655 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
3660 // give dialogs like the TOC a chance to adapt
3665 Buffer const * GuiView::updateInset(Inset const * inset)
3670 Buffer const * inset_buffer = &(inset->buffer());
3672 for (int i = 0; i != d.splitter_->count(); ++i) {
3673 GuiWorkArea * wa = d.tabWorkArea(i)->currentWorkArea();
3676 Buffer const * buffer = &(wa->bufferView().buffer());
3677 if (inset_buffer == buffer)
3678 wa->scheduleRedraw();
3680 return inset_buffer;
3684 void GuiView::restartCursor()
3686 /* When we move around, or type, it's nice to be able to see
3687 * the cursor immediately after the keypress.
3689 if (d.current_work_area_)
3690 d.current_work_area_->startBlinkingCursor();
3692 // Take this occasion to update the other GUI elements.
3698 void GuiView::updateCompletion(Cursor & cur, bool start, bool keep)
3700 if (d.current_work_area_)
3701 d.current_work_area_->completer().updateVisibility(cur, start, keep);
3706 // This list should be kept in sync with the list of insets in
3707 // src/insets/Inset.cpp. I.e., if a dialog goes with an inset, the
3708 // dialog should have the same name as the inset.
3709 // Changes should be also recorded in LFUN_DIALOG_SHOW doxygen
3710 // docs in LyXAction.cpp.
3712 char const * const dialognames[] = {
3714 "aboutlyx", "bibitem", "bibtex", "box", "branch", "changes", "character",
3715 "citation", "compare", "comparehistory", "document", "errorlist", "ert",
3716 "external", "file", "findreplace", "findreplaceadv", "float", "graphics",
3717 "href", "include", "index", "index_print", "info", "listings", "label", "line",
3718 "log", "mathdelimiter", "mathmatrix", "mathspace", "nomenclature",
3719 "nomencl_print", "note", "paragraph", "phantom", "prefs", "print", "ref",
3720 "sendto", "space", "spellchecker", "symbols", "tabular", "tabularcreate",
3721 "thesaurus", "texinfo", "toc", "view-source", "vspace", "wrap", "progress"};
3723 char const * const * const end_dialognames =
3724 dialognames + (sizeof(dialognames) / sizeof(char *));
3728 cmpCStr(char const * name) : name_(name) {}
3729 bool operator()(char const * other) {
3730 return strcmp(other, name_) == 0;
3737 bool isValidName(string const & name)
3739 return find_if(dialognames, end_dialognames,
3740 cmpCStr(name.c_str())) != end_dialognames;
3746 void GuiView::resetDialogs()
3748 // Make sure that no LFUN uses any GuiView.
3749 guiApp->setCurrentView(0);
3753 constructToolbars();
3754 guiApp->menus().fillMenuBar(menuBar(), this, false);
3755 d.layout_->updateContents(true);
3756 // Now update controls with current buffer.
3757 guiApp->setCurrentView(this);
3763 Dialog * GuiView::findOrBuild(string const & name, bool hide_it)
3765 if (!isValidName(name))
3768 map<string, DialogPtr>::iterator it = d.dialogs_.find(name);
3770 if (it != d.dialogs_.end()) {
3772 it->second->hideView();
3773 return it->second.get();
3776 Dialog * dialog = build(name);
3777 d.dialogs_[name].reset(dialog);
3778 if (lyxrc.allow_geometry_session)
3779 dialog->restoreSession();
3786 void GuiView::showDialog(string const & name, string const & data,
3789 triggerShowDialog(toqstr(name), toqstr(data), inset);
3793 void GuiView::doShowDialog(QString const & qname, QString const & qdata,
3799 const string name = fromqstr(qname);
3800 const string data = fromqstr(qdata);
3804 Dialog * dialog = findOrBuild(name, false);
3806 bool const visible = dialog->isVisibleView();
3807 dialog->showData(data);
3808 if (inset && currentBufferView())
3809 currentBufferView()->editInset(name, inset);
3810 // We only set the focus to the new dialog if it was not yet
3811 // visible in order not to change the existing previous behaviour
3813 // activateWindow is needed for floating dockviews
3814 dialog->asQWidget()->raise();
3815 dialog->asQWidget()->activateWindow();
3816 dialog->asQWidget()->setFocus();
3820 catch (ExceptionMessage const & ex) {
3828 bool GuiView::isDialogVisible(string const & name) const
3830 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3831 if (it == d.dialogs_.end())
3833 return it->second.get()->isVisibleView() && !it->second.get()->isClosing();
3837 void GuiView::hideDialog(string const & name, Inset * inset)
3839 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3840 if (it == d.dialogs_.end())
3844 if (!currentBufferView())
3846 if (inset != currentBufferView()->editedInset(name))
3850 Dialog * const dialog = it->second.get();
3851 if (dialog->isVisibleView())
3853 if (currentBufferView())
3854 currentBufferView()->editInset(name, 0);
3858 void GuiView::disconnectDialog(string const & name)
3860 if (!isValidName(name))
3862 if (currentBufferView())
3863 currentBufferView()->editInset(name, 0);
3867 void GuiView::hideAll() const
3869 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
3870 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3872 for(; it != end; ++it)
3873 it->second->hideView();
3877 void GuiView::updateDialogs()
3879 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
3880 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3882 for(; it != end; ++it) {
3883 Dialog * dialog = it->second.get();
3885 if (dialog->needBufferOpen() && !documentBufferView())
3886 hideDialog(fromqstr(dialog->name()), 0);
3887 else if (dialog->isVisibleView())
3888 dialog->checkStatus();
3895 Dialog * createDialog(GuiView & lv, string const & name);
3897 // will be replaced by a proper factory...
3898 Dialog * createGuiAbout(GuiView & lv);
3899 Dialog * createGuiBibtex(GuiView & lv);
3900 Dialog * createGuiChanges(GuiView & lv);
3901 Dialog * createGuiCharacter(GuiView & lv);
3902 Dialog * createGuiCitation(GuiView & lv);
3903 Dialog * createGuiCompare(GuiView & lv);
3904 Dialog * createGuiCompareHistory(GuiView & lv);
3905 Dialog * createGuiDelimiter(GuiView & lv);
3906 Dialog * createGuiDocument(GuiView & lv);
3907 Dialog * createGuiErrorList(GuiView & lv);
3908 Dialog * createGuiExternal(GuiView & lv);
3909 Dialog * createGuiGraphics(GuiView & lv);
3910 Dialog * createGuiInclude(GuiView & lv);
3911 Dialog * createGuiIndex(GuiView & lv);
3912 Dialog * createGuiListings(GuiView & lv);
3913 Dialog * createGuiLog(GuiView & lv);
3914 Dialog * createGuiMathMatrix(GuiView & lv);
3915 Dialog * createGuiNote(GuiView & lv);
3916 Dialog * createGuiParagraph(GuiView & lv);
3917 Dialog * createGuiPhantom(GuiView & lv);
3918 Dialog * createGuiPreferences(GuiView & lv);
3919 Dialog * createGuiPrint(GuiView & lv);
3920 Dialog * createGuiPrintindex(GuiView & lv);
3921 Dialog * createGuiRef(GuiView & lv);
3922 Dialog * createGuiSearch(GuiView & lv);
3923 Dialog * createGuiSearchAdv(GuiView & lv);
3924 Dialog * createGuiSendTo(GuiView & lv);
3925 Dialog * createGuiShowFile(GuiView & lv);
3926 Dialog * createGuiSpellchecker(GuiView & lv);
3927 Dialog * createGuiSymbols(GuiView & lv);
3928 Dialog * createGuiTabularCreate(GuiView & lv);
3929 Dialog * createGuiTexInfo(GuiView & lv);
3930 Dialog * createGuiToc(GuiView & lv);
3931 Dialog * createGuiThesaurus(GuiView & lv);
3932 Dialog * createGuiViewSource(GuiView & lv);
3933 Dialog * createGuiWrap(GuiView & lv);
3934 Dialog * createGuiProgressView(GuiView & lv);
3938 Dialog * GuiView::build(string const & name)
3940 LASSERT(isValidName(name), return 0);
3942 Dialog * dialog = createDialog(*this, name);
3946 if (name == "aboutlyx")
3947 return createGuiAbout(*this);
3948 if (name == "bibtex")
3949 return createGuiBibtex(*this);
3950 if (name == "changes")
3951 return createGuiChanges(*this);
3952 if (name == "character")
3953 return createGuiCharacter(*this);
3954 if (name == "citation")
3955 return createGuiCitation(*this);
3956 if (name == "compare")
3957 return createGuiCompare(*this);
3958 if (name == "comparehistory")
3959 return createGuiCompareHistory(*this);
3960 if (name == "document")
3961 return createGuiDocument(*this);
3962 if (name == "errorlist")
3963 return createGuiErrorList(*this);
3964 if (name == "external")
3965 return createGuiExternal(*this);
3967 return createGuiShowFile(*this);
3968 if (name == "findreplace")
3969 return createGuiSearch(*this);
3970 if (name == "findreplaceadv")
3971 return createGuiSearchAdv(*this);
3972 if (name == "graphics")
3973 return createGuiGraphics(*this);
3974 if (name == "include")
3975 return createGuiInclude(*this);
3976 if (name == "index")
3977 return createGuiIndex(*this);
3978 if (name == "index_print")
3979 return createGuiPrintindex(*this);
3980 if (name == "listings")
3981 return createGuiListings(*this);
3983 return createGuiLog(*this);
3984 if (name == "mathdelimiter")
3985 return createGuiDelimiter(*this);
3986 if (name == "mathmatrix")
3987 return createGuiMathMatrix(*this);
3989 return createGuiNote(*this);
3990 if (name == "paragraph")
3991 return createGuiParagraph(*this);
3992 if (name == "phantom")
3993 return createGuiPhantom(*this);
3994 if (name == "prefs")
3995 return createGuiPreferences(*this);
3996 if (name == "print")
3997 return createGuiPrint(*this);
3999 return createGuiRef(*this);
4000 if (name == "sendto")
4001 return createGuiSendTo(*this);
4002 if (name == "spellchecker")
4003 return createGuiSpellchecker(*this);
4004 if (name == "symbols")
4005 return createGuiSymbols(*this);
4006 if (name == "tabularcreate")
4007 return createGuiTabularCreate(*this);
4008 if (name == "texinfo")
4009 return createGuiTexInfo(*this);
4010 if (name == "thesaurus")
4011 return createGuiThesaurus(*this);
4013 return createGuiToc(*this);
4014 if (name == "view-source")
4015 return createGuiViewSource(*this);
4017 return createGuiWrap(*this);
4018 if (name == "progress")
4019 return createGuiProgressView(*this);
4025 } // namespace frontend
4028 #include "moc_GuiView.cpp"