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;
140 using support::addExtension;
141 using support::changeExtension;
142 using support::removeExtension;
148 class BackgroundWidget : public QWidget
153 LYXERR(Debug::GUI, "show banner: " << lyxrc.show_banner);
154 if (!lyxrc.show_banner)
156 /// The text to be written on top of the pixmap
157 QString const text = lyx_version ?
158 qt_("version ") + lyx_version : qt_("unknown version");
159 splash_ = getPixmap("images/", "banner", "png");
161 QPainter pain(&splash_);
162 pain.setPen(QColor(0, 0, 0));
164 // The font used to display the version info
165 font.setStyleHint(QFont::SansSerif);
166 font.setWeight(QFont::Bold);
167 font.setPointSize(int(toqstr(lyxrc.font_sizes[FONT_SIZE_LARGE]).toDouble()));
169 pain.drawText(190, 225, text);
170 setFocusPolicy(Qt::StrongFocus);
173 void paintEvent(QPaintEvent *)
175 int x = (width() - splash_.width()) / 2;
176 int y = (height() - splash_.height()) / 2;
178 pain.drawPixmap(x, y, splash_);
181 void keyPressEvent(QKeyEvent * ev)
184 setKeySymbol(&sym, ev);
186 guiApp->processKeySym(sym, q_key_state(ev->modifiers()));
198 /// Toolbar store providing access to individual toolbars by name.
199 typedef map<string, GuiToolbar *> ToolbarMap;
201 typedef shared_ptr<Dialog> DialogPtr;
206 struct GuiView::GuiViewPrivate
208 GuiViewPrivate(GuiView * gv)
209 : gv_(gv), current_work_area_(0), current_main_work_area_(0),
210 layout_(0), autosave_timeout_(5000),
213 // hardcode here the platform specific icon size
214 smallIconSize = 16; // scaling problems
215 normalIconSize = 20; // ok, default if iconsize.png is missing
216 bigIconSize = 26; // better for some math icons
218 // if it exists, use width of iconsize.png as normal size
219 QString const dir = toqstr(addPath("images", lyxrc.icon_set));
220 FileName const fn = lyx::libFileSearch(dir, "iconsize.png");
222 QImage image(toqstr(fn.absFileName()));
223 if (image.width() < int(smallIconSize))
224 normalIconSize = smallIconSize;
225 else if (image.width() > int(bigIconSize))
226 normalIconSize = bigIconSize;
228 normalIconSize = image.width();
231 splitter_ = new QSplitter;
232 bg_widget_ = new BackgroundWidget;
233 stack_widget_ = new QStackedWidget;
234 stack_widget_->addWidget(bg_widget_);
235 stack_widget_->addWidget(splitter_);
238 // TODO cleanup, remove the singleton, handle multiple Windows?
239 progress_ = ProgressInterface::instance();
240 if (!dynamic_cast<GuiProgress*>(progress_)) {
241 progress_ = new GuiProgress(); // TODO who deletes it
242 ProgressInterface::setInstance(progress_);
245 dynamic_cast<GuiProgress*>(progress_),
246 SIGNAL(updateStatusBarMessage(QString const&)),
247 gv, SLOT(updateStatusBarMessage(QString const&)));
249 dynamic_cast<GuiProgress*>(progress_),
250 SIGNAL(clearMessageText()),
251 gv, SLOT(clearMessageText()));
258 delete stack_widget_;
261 QMenu * toolBarPopup(GuiView * parent)
263 // FIXME: translation
264 QMenu * menu = new QMenu(parent);
265 QActionGroup * iconSizeGroup = new QActionGroup(parent);
267 QAction * smallIcons = new QAction(iconSizeGroup);
268 smallIcons->setText(qt_("Small-sized icons"));
269 smallIcons->setCheckable(true);
270 QObject::connect(smallIcons, SIGNAL(triggered()),
271 parent, SLOT(smallSizedIcons()));
272 menu->addAction(smallIcons);
274 QAction * normalIcons = new QAction(iconSizeGroup);
275 normalIcons->setText(qt_("Normal-sized icons"));
276 normalIcons->setCheckable(true);
277 QObject::connect(normalIcons, SIGNAL(triggered()),
278 parent, SLOT(normalSizedIcons()));
279 menu->addAction(normalIcons);
281 QAction * bigIcons = new QAction(iconSizeGroup);
282 bigIcons->setText(qt_("Big-sized icons"));
283 bigIcons->setCheckable(true);
284 QObject::connect(bigIcons, SIGNAL(triggered()),
285 parent, SLOT(bigSizedIcons()));
286 menu->addAction(bigIcons);
288 unsigned int cur = parent->iconSize().width();
289 if ( cur == parent->d.smallIconSize)
290 smallIcons->setChecked(true);
291 else if (cur == parent->d.normalIconSize)
292 normalIcons->setChecked(true);
293 else if (cur == parent->d.bigIconSize)
294 bigIcons->setChecked(true);
301 stack_widget_->setCurrentWidget(bg_widget_);
302 bg_widget_->setUpdatesEnabled(true);
303 bg_widget_->setFocus();
306 int tabWorkAreaCount()
308 return splitter_->count();
311 TabWorkArea * tabWorkArea(int i)
313 return dynamic_cast<TabWorkArea *>(splitter_->widget(i));
316 TabWorkArea * currentTabWorkArea()
318 int areas = tabWorkAreaCount();
320 // The first TabWorkArea is always the first one, if any.
321 return tabWorkArea(0);
323 for (int i = 0; i != areas; ++i) {
324 TabWorkArea * twa = tabWorkArea(i);
325 if (current_main_work_area_ == twa->currentWorkArea())
329 // None has the focus so we just take the first one.
330 return tabWorkArea(0);
333 int countWorkAreasOf(Buffer & buf)
335 int areas = tabWorkAreaCount();
337 for (int i = 0; i != areas; ++i) {
338 TabWorkArea * twa = tabWorkArea(i);
339 if (twa->workArea(buf))
345 #if (QT_VERSION >= 0x040400)
346 void setPreviewFuture(QFuture<Buffer::ExportStatus> const & f)
348 if (processing_thread_watcher_.isRunning()) {
349 // we prefer to cancel this preview in order to keep a snappy
353 processing_thread_watcher_.setFuture(f);
359 GuiWorkArea * current_work_area_;
360 GuiWorkArea * current_main_work_area_;
361 QSplitter * splitter_;
362 QStackedWidget * stack_widget_;
363 BackgroundWidget * bg_widget_;
365 ToolbarMap toolbars_;
366 ProgressInterface* progress_;
367 /// The main layout box.
369 * \warning Don't Delete! The layout box is actually owned by
370 * whichever toolbar contains it. All the GuiView class needs is a
371 * means of accessing it.
373 * FIXME: replace that with a proper model so that we are not limited
374 * to only one dialog.
379 map<string, DialogPtr> dialogs_;
381 unsigned int smallIconSize;
382 unsigned int normalIconSize;
383 unsigned int bigIconSize;
385 QTimer statusbar_timer_;
386 /// auto-saving of buffers
387 Timeout autosave_timeout_;
388 /// flag against a race condition due to multiclicks, see bug #1119
392 TocModels toc_models_;
394 #if (QT_VERSION >= 0x040400)
396 QFutureWatcher<docstring> autosave_watcher_;
397 QFutureWatcher<Buffer::ExportStatus> processing_thread_watcher_;
399 string last_export_format;
400 string processing_format;
402 struct DummyWatcher { bool isRunning(){return false;} };
403 DummyWatcher processing_thread_watcher_;
406 static QSet<Buffer const *> busyBuffers;
407 static Buffer::ExportStatus previewAndDestroy(Buffer const * orig, Buffer * buffer, string const & format);
408 static Buffer::ExportStatus exportAndDestroy(Buffer const * orig, Buffer * buffer, string const & format);
409 static Buffer::ExportStatus compileAndDestroy(Buffer const * orig, Buffer * buffer, string const & format);
410 static docstring autosaveAndDestroy(Buffer const * orig, Buffer * buffer);
413 static Buffer::ExportStatus runAndDestroy(const T& func, Buffer const * orig, Buffer * buffer, string const & format);
415 // TODO syncFunc/previewFunc: use bind
416 bool asyncBufferProcessing(string const & argument,
417 Buffer const * used_buffer,
418 docstring const & msg,
419 Buffer::ExportStatus (*asyncFunc)(Buffer const *, Buffer *, string const &),
420 Buffer::ExportStatus (Buffer::*syncFunc)(string const &, bool) const,
421 Buffer::ExportStatus (Buffer::*previewFunc)(string const &) const);
423 QVector<GuiWorkArea*> guiWorkAreas();
426 QSet<Buffer const *> GuiView::GuiViewPrivate::busyBuffers;
429 GuiView::GuiView(int id)
430 : d(*new GuiViewPrivate(this)), id_(id), closing_(false), busy_(0)
432 // GuiToolbars *must* be initialised before the menu bar.
433 normalSizedIcons(); // at least on Mac the default is 32 otherwise, which is huge
436 // set ourself as the current view. This is needed for the menu bar
437 // filling, at least for the static special menu item on Mac. Otherwise
438 // they are greyed out.
439 guiApp->setCurrentView(this);
441 // Fill up the menu bar.
442 guiApp->menus().fillMenuBar(menuBar(), this, true);
444 setCentralWidget(d.stack_widget_);
446 // Start autosave timer
447 if (lyxrc.autosave) {
448 d.autosave_timeout_.timeout.connect(bind(&GuiView::autoSave, this));
449 d.autosave_timeout_.setTimeout(lyxrc.autosave * 1000);
450 d.autosave_timeout_.start();
452 connect(&d.statusbar_timer_, SIGNAL(timeout()),
453 this, SLOT(clearMessage()));
455 // We don't want to keep the window in memory if it is closed.
456 setAttribute(Qt::WA_DeleteOnClose, true);
458 #if (!defined(Q_WS_WIN) && !defined(Q_WS_MACX))
459 // QIcon::fromTheme was introduced in Qt 4.6
460 #if (QT_VERSION >= 0x040600)
461 // assign an icon to main form. We do not do it under Qt/Win or Qt/Mac,
462 // since the icon is provided in the application bundle. We use a themed
463 // version when available and use the bundled one as fallback.
464 setWindowIcon(QIcon::fromTheme("lyx", getPixmap("images/", "lyx", "png")));
466 setWindowIcon(getPixmap("images/", "lyx", "png"));
471 #if (QT_VERSION >= 0x040300)
472 // use tabbed dock area for multiple docks
473 // (such as "source" and "messages")
474 setDockOptions(QMainWindow::ForceTabbedDocks);
478 setAcceptDrops(true);
480 #if (QT_VERSION >= 0x040400)
482 // add busy indicator to statusbar
483 QLabel * busylabel = new QLabel(statusBar());
484 statusBar()->addPermanentWidget(busylabel);
485 QString fn = toqstr(lyx::libFileSearch("images", "busy.gif").absFileName());
486 QMovie * busyanim = new QMovie(fn, QByteArray(), busylabel);
487 busylabel->setMovie(busyanim);
491 connect(&d.processing_thread_watcher_, SIGNAL(started()),
492 busylabel, SLOT(show()));
493 connect(&d.processing_thread_watcher_, SIGNAL(finished()),
494 busylabel, SLOT(hide()));
496 statusBar()->setSizeGripEnabled(true);
499 connect(&d.autosave_watcher_, SIGNAL(finished()), this,
500 SLOT(autoSaveThreadFinished()));
502 connect(&d.processing_thread_watcher_, SIGNAL(started()), this,
503 SLOT(processingThreadStarted()));
504 connect(&d.processing_thread_watcher_, SIGNAL(finished()), this,
505 SLOT(processingThreadFinished()));
509 connect(this, SIGNAL(triggerShowDialog(QString const &, QString const &, Inset *)),
510 SLOT(doShowDialog(QString const &, QString const &, Inset *)));
512 // Forbid too small unresizable window because it can happen
513 // with some window manager under X11.
514 setMinimumSize(300, 200);
516 if (lyxrc.allow_geometry_session) {
517 // Now take care of session management.
522 // no session handling, default to a sane size.
523 setGeometry(50, 50, 690, 510);
526 // clear session data if any.
528 settings.remove("views");
538 QVector<GuiWorkArea*> GuiView::GuiViewPrivate::guiWorkAreas()
540 QVector<GuiWorkArea*> areas;
541 for (int i = 0; i < tabWorkAreaCount(); i++) {
542 TabWorkArea* ta = tabWorkArea(i);
543 for (int u = 0; u < ta->count(); u++) {
544 areas << ta->workArea(u);
550 static void handleExportStatus(GuiView * view, Buffer::ExportStatus status,
551 string const & format)
553 docstring const fmt = formats.prettyName(format);
556 case Buffer::ExportSuccess:
557 msg = bformat(_("Successful export to format: %1$s"), fmt);
559 case Buffer::ExportCancel:
560 msg = _("Document export cancelled.");
562 case Buffer::ExportError:
563 case Buffer::ExportNoPathToFormat:
564 case Buffer::ExportTexPathHasSpaces:
565 case Buffer::ExportConverterError:
566 msg = bformat(_("Error while exporting format: %1$s"), fmt);
568 case Buffer::PreviewSuccess:
569 msg = bformat(_("Successful preview of format: %1$s"), fmt);
571 case Buffer::PreviewError:
572 msg = bformat(_("Error while previewing format: %1$s"), fmt);
579 #if QT_VERSION >= 0x040400
581 void GuiView::processingThreadStarted()
586 void GuiView::processingThreadFinished()
588 QFutureWatcher<Buffer::ExportStatus> const * watcher =
589 static_cast<QFutureWatcher<Buffer::ExportStatus> const *>(sender());
591 Buffer::ExportStatus const status = watcher->result();
592 handleExportStatus(this, status, d.processing_format);
595 BufferView const * const bv = currentBufferView();
596 if (bv && !bv->buffer().errorList("Export").empty()) {
600 errors(d.last_export_format);
604 void GuiView::autoSaveThreadFinished()
606 QFutureWatcher<docstring> const * watcher =
607 static_cast<QFutureWatcher<docstring> const *>(sender());
608 message(watcher->result());
614 void GuiView::processingThreadStarted()
619 void GuiView::processingThreadFinished()
624 void GuiView::autoSaveThreadFinished()
630 void GuiView::saveLayout() const
633 settings.beginGroup("views");
634 settings.beginGroup(QString::number(id_));
636 settings.setValue("pos", pos());
637 settings.setValue("size", size());
639 settings.setValue("geometry", saveGeometry());
641 settings.setValue("layout", saveState(0));
642 settings.setValue("icon_size", iconSize());
646 void GuiView::saveUISettings() const
648 // Save the toolbar private states
649 ToolbarMap::iterator end = d.toolbars_.end();
650 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
651 it->second->saveSession();
652 // Now take care of all other dialogs
653 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
654 for (; it!= d.dialogs_.end(); ++it)
655 it->second->saveSession();
659 bool GuiView::restoreLayout()
662 settings.beginGroup("views");
663 settings.beginGroup(QString::number(id_));
664 QString const icon_key = "icon_size";
665 if (!settings.contains(icon_key))
668 //code below is skipped when when ~/.config/LyX is (re)created
669 QSize icon_size = settings.value(icon_key).toSize();
670 // Check whether session size changed.
671 if (icon_size.width() != int(d.smallIconSize) &&
672 icon_size.width() != int(d.normalIconSize) &&
673 icon_size.width() != int(d.bigIconSize)) {
674 icon_size.setWidth(d.normalIconSize);
675 icon_size.setHeight(d.normalIconSize);
677 setIconSize(icon_size);
680 QPoint pos = settings.value("pos", QPoint(50, 50)).toPoint();
681 QSize size = settings.value("size", QSize(690, 510)).toSize();
685 // Work-around for bug #6034: the window ends up in an undetermined
686 // state when trying to restore a maximized window when it is
687 // already maximized.
688 if (!(windowState() & Qt::WindowMaximized))
689 if (!restoreGeometry(settings.value("geometry").toByteArray()))
690 setGeometry(50, 50, 690, 510);
692 // Make sure layout is correctly oriented.
693 setLayoutDirection(qApp->layoutDirection());
695 // Allow the toc and view-source dock widget to be restored if needed.
697 if ((dialog = findOrBuild("toc", true)))
698 // see bug 5082. At least setup title and enabled state.
699 // Visibility will be adjusted by restoreState below.
700 dialog->prepareView();
701 if ((dialog = findOrBuild("view-source", true)))
702 dialog->prepareView();
703 if ((dialog = findOrBuild("progress", true)))
704 dialog->prepareView();
705 if ((dialog = findOrBuild("findreplaceadv", true)))
706 dialog->prepareView();
708 if (!restoreState(settings.value("layout").toByteArray(), 0))
715 GuiToolbar * GuiView::toolbar(string const & name)
717 ToolbarMap::iterator it = d.toolbars_.find(name);
718 if (it != d.toolbars_.end())
721 LYXERR(Debug::GUI, "Toolbar::display: no toolbar named " << name);
726 void GuiView::constructToolbars()
728 ToolbarMap::iterator it = d.toolbars_.begin();
729 for (; it != d.toolbars_.end(); ++it)
733 // I don't like doing this here, but the standard toolbar
734 // destroys this object when it's destroyed itself (vfr)
735 d.layout_ = new LayoutBox(*this);
736 d.stack_widget_->addWidget(d.layout_);
737 d.layout_->move(0,0);
739 // extracts the toolbars from the backend
740 Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
741 Toolbars::Infos::iterator end = guiApp->toolbars().end();
742 for (; cit != end; ++cit)
743 d.toolbars_[cit->name] = new GuiToolbar(*cit, *this);
747 void GuiView::initToolbars()
749 // extracts the toolbars from the backend
750 Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
751 Toolbars::Infos::iterator end = guiApp->toolbars().end();
752 for (; cit != end; ++cit) {
753 GuiToolbar * tb = toolbar(cit->name);
756 int const visibility = guiApp->toolbars().defaultVisibility(cit->name);
757 bool newline = !(visibility & Toolbars::SAMEROW);
758 tb->setVisible(false);
759 tb->setVisibility(visibility);
761 if (visibility & Toolbars::TOP) {
763 addToolBarBreak(Qt::TopToolBarArea);
764 addToolBar(Qt::TopToolBarArea, tb);
767 if (visibility & Toolbars::BOTTOM) {
768 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
769 #if (QT_VERSION >= 0x040202)
771 addToolBarBreak(Qt::BottomToolBarArea);
773 addToolBar(Qt::BottomToolBarArea, tb);
776 if (visibility & Toolbars::LEFT) {
777 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
778 #if (QT_VERSION >= 0x040202)
780 addToolBarBreak(Qt::LeftToolBarArea);
782 addToolBar(Qt::LeftToolBarArea, tb);
785 if (visibility & Toolbars::RIGHT) {
786 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
787 #if (QT_VERSION >= 0x040202)
789 addToolBarBreak(Qt::RightToolBarArea);
791 addToolBar(Qt::RightToolBarArea, tb);
794 if (visibility & Toolbars::ON)
795 tb->setVisible(true);
800 TocModels & GuiView::tocModels()
802 return d.toc_models_;
806 void GuiView::setFocus()
808 LYXERR(Debug::DEBUG, "GuiView::setFocus()" << this);
809 QMainWindow::setFocus();
813 void GuiView::focusInEvent(QFocusEvent * e)
815 LYXERR(Debug::DEBUG, "GuiView::focusInEvent()" << this);
816 QMainWindow::focusInEvent(e);
817 // Make sure guiApp points to the correct view.
818 guiApp->setCurrentView(this);
819 if (currentWorkArea())
820 currentWorkArea()->setFocus();
821 else if (currentMainWorkArea())
822 currentMainWorkArea()->setFocus();
824 d.bg_widget_->setFocus();
828 QMenu * GuiView::createPopupMenu()
830 return d.toolBarPopup(this);
834 void GuiView::showEvent(QShowEvent * e)
836 LYXERR(Debug::GUI, "Passed Geometry "
837 << size().height() << "x" << size().width()
838 << "+" << pos().x() << "+" << pos().y());
840 if (d.splitter_->count() == 0)
841 // No work area, switch to the background widget.
845 QMainWindow::showEvent(e);
849 bool GuiView::closeScheduled()
856 /** Destroy only all tabbed WorkAreas. Destruction of other WorkAreas
857 ** is responsibility of the container (e.g., dialog)
859 void GuiView::closeEvent(QCloseEvent * close_event)
861 LYXERR(Debug::DEBUG, "GuiView::closeEvent()");
863 if (!GuiViewPrivate::busyBuffers.isEmpty()) {
864 Alert::warning(_("Exit LyX"),
865 _("LyX could not be closed because documents are being processed by LyX."));
866 close_event->setAccepted(false);
870 // If the user pressed the x (so we didn't call closeView
871 // programmatically), we want to clear all existing entries.
873 theSession().lastOpened().clear();
878 // it can happen that this event arrives without selecting the view,
879 // e.g. when clicking the close button on a background window.
881 if (!closeWorkAreaAll()) {
883 close_event->ignore();
887 // Make sure that nothing will use this to be closed View.
888 guiApp->unregisterView(this);
890 if (isFullScreen()) {
891 // Switch off fullscreen before closing.
896 // Make sure the timer time out will not trigger a statusbar update.
897 d.statusbar_timer_.stop();
899 // Saving fullscreen requires additional tweaks in the toolbar code.
900 // It wouldn't also work under linux natively.
901 if (lyxrc.allow_geometry_session) {
906 close_event->accept();
910 void GuiView::dragEnterEvent(QDragEnterEvent * event)
912 if (event->mimeData()->hasUrls())
914 /// \todo Ask lyx-devel is this is enough:
915 /// if (event->mimeData()->hasFormat("text/plain"))
916 /// event->acceptProposedAction();
920 void GuiView::dropEvent(QDropEvent * event)
922 QList<QUrl> files = event->mimeData()->urls();
926 LYXERR(Debug::GUI, "GuiView::dropEvent: got URLs!");
927 for (int i = 0; i != files.size(); ++i) {
928 string const file = os::internal_path(fromqstr(
929 files.at(i).toLocalFile()));
933 string const ext = support::getExtension(file);
934 vector<const Format *> found_formats;
936 // Find all formats that have the correct extension.
937 vector<const Format *> const & import_formats
938 = theConverters().importableFormats();
939 vector<const Format *>::const_iterator it = import_formats.begin();
940 for (; it != import_formats.end(); ++it)
941 if ((*it)->hasExtension(ext))
942 found_formats.push_back(*it);
945 if (found_formats.size() >= 1) {
946 if (found_formats.size() > 1) {
947 //FIXME: show a dialog to choose the correct importable format
949 "Multiple importable formats found, selecting first");
951 string const arg = found_formats[0]->name() + " " + file;
952 cmd = FuncRequest(LFUN_BUFFER_IMPORT, arg);
955 //FIXME: do we have to explicitly check whether it's a lyx file?
957 "No formats found, trying to open it as a lyx file");
958 cmd = FuncRequest(LFUN_FILE_OPEN, file);
960 // add the functions to the queue
961 guiApp->addToFuncRequestQueue(cmd);
964 // now process the collected functions. We perform the events
965 // asynchronously. This prevents potential problems in case the
966 // BufferView is closed within an event.
967 guiApp->processFuncRequestQueueAsync();
971 void GuiView::message(docstring const & str)
973 if (ForkedProcess::iAmAChild())
976 // call is moved to GUI-thread by GuiProgress
977 d.progress_->appendMessage(toqstr(str));
981 void GuiView::clearMessageText()
983 message(docstring());
987 void GuiView::updateStatusBarMessage(QString const & str)
989 statusBar()->showMessage(str);
990 d.statusbar_timer_.stop();
991 d.statusbar_timer_.start(3000);
995 void GuiView::smallSizedIcons()
997 setIconSize(QSize(d.smallIconSize, d.smallIconSize));
1001 void GuiView::normalSizedIcons()
1003 setIconSize(QSize(d.normalIconSize, d.normalIconSize));
1007 void GuiView::bigSizedIcons()
1009 setIconSize(QSize(d.bigIconSize, d.bigIconSize));
1013 void GuiView::clearMessage()
1015 // FIXME: This code was introduced in r19643 to fix bug #4123. However,
1016 // the hasFocus function mostly returns false, even if the focus is on
1017 // a workarea in this view.
1021 d.statusbar_timer_.stop();
1025 void GuiView::updateWindowTitle(GuiWorkArea * wa)
1027 if (wa != d.current_work_area_
1028 || wa->bufferView().buffer().isInternal())
1030 setWindowTitle(qt_("LyX: ") + wa->windowTitle());
1031 setWindowIconText(wa->windowIconText());
1035 void GuiView::on_currentWorkAreaChanged(GuiWorkArea * wa)
1037 if (d.current_work_area_)
1038 QObject::disconnect(d.current_work_area_, SIGNAL(busy(bool)),
1039 this, SLOT(setBusy(bool)));
1041 disconnectBufferView();
1042 connectBufferView(wa->bufferView());
1043 connectBuffer(wa->bufferView().buffer());
1044 d.current_work_area_ = wa;
1045 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
1046 this, SLOT(updateWindowTitle(GuiWorkArea *)));
1047 QObject::connect(wa, SIGNAL(busy(bool)), this, SLOT(setBusy(bool)));
1048 updateWindowTitle(wa);
1052 // The document settings needs to be reinitialised.
1053 updateDialog("document", "");
1055 // Buffer-dependent dialogs must be updated. This is done here because
1056 // some dialogs require buffer()->text.
1061 void GuiView::on_lastWorkAreaRemoved()
1064 // We already are in a close event. Nothing more to do.
1067 if (d.splitter_->count() > 1)
1068 // We have a splitter so don't close anything.
1071 // Reset and updates the dialogs.
1072 d.toc_models_.reset(0);
1073 updateDialog("document", "");
1076 resetWindowTitleAndIconText();
1079 if (lyxrc.open_buffers_in_tabs)
1080 // Nothing more to do, the window should stay open.
1083 if (guiApp->viewIds().size() > 1) {
1089 // On Mac we also close the last window because the application stay
1090 // resident in memory. On other platforms we don't close the last
1091 // window because this would quit the application.
1097 void GuiView::updateStatusBar()
1099 // let the user see the explicit message
1100 if (d.statusbar_timer_.isActive())
1107 void GuiView::showMessage()
1109 QString msg = toqstr(theGuiApp()->viewStatusMessage());
1110 if (msg.isEmpty()) {
1111 BufferView const * bv = currentBufferView();
1113 msg = toqstr(bv->cursor().currentState());
1115 msg = qt_("Welcome to LyX!");
1117 statusBar()->showMessage(msg);
1121 bool GuiView::event(QEvent * e)
1125 // Useful debug code:
1126 //case QEvent::ActivationChange:
1127 //case QEvent::WindowDeactivate:
1128 //case QEvent::Paint:
1129 //case QEvent::Enter:
1130 //case QEvent::Leave:
1131 //case QEvent::HoverEnter:
1132 //case QEvent::HoverLeave:
1133 //case QEvent::HoverMove:
1134 //case QEvent::StatusTip:
1135 //case QEvent::DragEnter:
1136 //case QEvent::DragLeave:
1137 //case QEvent::Drop:
1140 case QEvent::WindowActivate: {
1141 GuiView * old_view = guiApp->currentView();
1142 if (this == old_view) {
1144 return QMainWindow::event(e);
1146 if (old_view && old_view->currentBufferView()) {
1147 // save current selection to the selection buffer to allow
1148 // middle-button paste in this window.
1149 cap::saveSelection(old_view->currentBufferView()->cursor());
1151 guiApp->setCurrentView(this);
1152 if (d.current_work_area_) {
1153 BufferView & bv = d.current_work_area_->bufferView();
1154 connectBufferView(bv);
1155 connectBuffer(bv.buffer());
1156 // The document structure, name and dialogs might have
1157 // changed in another view.
1159 // The document settings needs to be reinitialised.
1160 updateDialog("document", "");
1163 resetWindowTitleAndIconText();
1166 return QMainWindow::event(e);
1169 case QEvent::ShortcutOverride: {
1172 #if (!defined Q_WS_X11) || (QT_VERSION >= 0x040500)
1173 if (isFullScreen() && menuBar()->isHidden()) {
1174 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
1175 // FIXME: we should also try to detect special LyX shortcut such as
1176 // Alt-P and Alt-M. Right now there is a hack in
1177 // GuiWorkArea::processKeySym() that hides again the menubar for
1179 if (ke->modifiers() & Qt::AltModifier && ke->key() != Qt::Key_Alt) {
1181 return QMainWindow::event(e);
1185 return QMainWindow::event(e);
1189 return QMainWindow::event(e);
1193 void GuiView::resetWindowTitleAndIconText()
1195 setWindowTitle(qt_("LyX"));
1196 setWindowIconText(qt_("LyX"));
1199 bool GuiView::focusNextPrevChild(bool /*next*/)
1206 bool GuiView::busy() const
1212 void GuiView::setBusy(bool busy)
1214 bool const busy_before = busy_ > 0;
1215 busy ? ++busy_ : --busy_;
1216 if ((busy_ > 0) == busy_before)
1217 // busy state didn't change
1221 QApplication::setOverrideCursor(Qt::WaitCursor);
1224 QApplication::restoreOverrideCursor();
1229 GuiWorkArea * GuiView::workArea(int index)
1231 if (TabWorkArea * twa = d.currentTabWorkArea())
1232 if (index < twa->count())
1233 return dynamic_cast<GuiWorkArea *>(twa->widget(index));
1238 GuiWorkArea * GuiView::workArea(Buffer & buffer)
1240 if (currentWorkArea()
1241 && ¤tWorkArea()->bufferView().buffer() == &buffer)
1242 return (GuiWorkArea *) currentWorkArea();
1243 if (TabWorkArea * twa = d.currentTabWorkArea())
1244 return twa->workArea(buffer);
1249 GuiWorkArea * GuiView::addWorkArea(Buffer & buffer)
1251 // Automatically create a TabWorkArea if there are none yet.
1252 TabWorkArea * tab_widget = d.splitter_->count()
1253 ? d.currentTabWorkArea() : addTabWorkArea();
1254 return tab_widget->addWorkArea(buffer, *this);
1258 TabWorkArea * GuiView::addTabWorkArea()
1260 TabWorkArea * twa = new TabWorkArea;
1261 QObject::connect(twa, SIGNAL(currentWorkAreaChanged(GuiWorkArea *)),
1262 this, SLOT(on_currentWorkAreaChanged(GuiWorkArea *)));
1263 QObject::connect(twa, SIGNAL(lastWorkAreaRemoved()),
1264 this, SLOT(on_lastWorkAreaRemoved()));
1266 d.splitter_->addWidget(twa);
1267 d.stack_widget_->setCurrentWidget(d.splitter_);
1272 GuiWorkArea const * GuiView::currentWorkArea() const
1274 return d.current_work_area_;
1278 GuiWorkArea * GuiView::currentWorkArea()
1280 return d.current_work_area_;
1284 GuiWorkArea const * GuiView::currentMainWorkArea() const
1286 if (!d.currentTabWorkArea())
1288 return d.currentTabWorkArea()->currentWorkArea();
1292 GuiWorkArea * GuiView::currentMainWorkArea()
1294 if (!d.currentTabWorkArea())
1296 return d.currentTabWorkArea()->currentWorkArea();
1300 void GuiView::setCurrentWorkArea(GuiWorkArea * wa)
1302 LYXERR(Debug::DEBUG, "Setting current wa: " << wa << endl);
1304 d.current_work_area_ = 0;
1309 // FIXME: I've no clue why this is here and why it accesses
1310 // theGuiApp()->currentView, which might be 0 (bug 6464).
1311 // See also 27525 (vfr).
1312 if (theGuiApp()->currentView() == this
1313 && theGuiApp()->currentView()->currentWorkArea() == wa)
1316 if (currentBufferView())
1317 cap::saveSelection(currentBufferView()->cursor());
1319 theGuiApp()->setCurrentView(this);
1320 d.current_work_area_ = wa;
1322 // We need to reset this now, because it will need to be
1323 // right if the tabWorkArea gets reset in the for loop. We
1324 // will change it back if we aren't in that case.
1325 GuiWorkArea * const old_cmwa = d.current_main_work_area_;
1326 d.current_main_work_area_ = wa;
1328 for (int i = 0; i != d.splitter_->count(); ++i) {
1329 if (d.tabWorkArea(i)->setCurrentWorkArea(wa)) {
1330 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea()
1331 << ", Current main wa: " << currentMainWorkArea());
1336 d.current_main_work_area_ = old_cmwa;
1338 LYXERR(Debug::DEBUG, "This is not a tabbed wa");
1339 on_currentWorkAreaChanged(wa);
1340 BufferView & bv = wa->bufferView();
1341 bv.cursor().fixIfBroken();
1343 wa->setUpdatesEnabled(true);
1344 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() << ", Current main wa: " << currentMainWorkArea());
1348 void GuiView::removeWorkArea(GuiWorkArea * wa)
1350 LASSERT(wa, return);
1351 if (wa == d.current_work_area_) {
1353 disconnectBufferView();
1354 d.current_work_area_ = 0;
1355 d.current_main_work_area_ = 0;
1358 bool found_twa = false;
1359 for (int i = 0; i != d.splitter_->count(); ++i) {
1360 TabWorkArea * twa = d.tabWorkArea(i);
1361 if (twa->removeWorkArea(wa)) {
1362 // Found in this tab group, and deleted the GuiWorkArea.
1364 if (twa->count() != 0) {
1365 if (d.current_work_area_ == 0)
1366 // This means that we are closing the current GuiWorkArea, so
1367 // switch to the next GuiWorkArea in the found TabWorkArea.
1368 setCurrentWorkArea(twa->currentWorkArea());
1370 // No more WorkAreas in this tab group, so delete it.
1377 // It is not a tabbed work area (i.e., the search work area), so it
1378 // should be deleted by other means.
1379 LASSERT(found_twa, /* */);
1381 if (d.current_work_area_ == 0) {
1382 if (d.splitter_->count() != 0) {
1383 TabWorkArea * twa = d.currentTabWorkArea();
1384 setCurrentWorkArea(twa->currentWorkArea());
1386 // No more work areas, switch to the background widget.
1387 setCurrentWorkArea(0);
1393 LayoutBox * GuiView::getLayoutDialog() const
1399 void GuiView::updateLayoutList()
1402 d.layout_->updateContents(false);
1406 void GuiView::updateToolbars()
1408 ToolbarMap::iterator end = d.toolbars_.end();
1409 if (d.current_work_area_) {
1411 d.current_work_area_->bufferView().cursor().inMathed()
1412 && !d.current_work_area_->bufferView().cursor().inRegexped();
1414 lyx::getStatus(FuncRequest(LFUN_LAYOUT_TABULAR)).enabled();
1416 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).enabled() &&
1417 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).onOff(true);
1418 bool const mathmacrotemplate =
1419 lyx::getStatus(FuncRequest(LFUN_IN_MATHMACROTEMPLATE)).enabled();
1421 lyx::getStatus(FuncRequest(LFUN_IN_IPA)).enabled();
1423 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1424 it->second->update(math, table, review, mathmacrotemplate, ipa);
1426 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1427 it->second->update(false, false, false, false, false);
1431 void GuiView::setBuffer(Buffer * newBuffer)
1433 LYXERR(Debug::DEBUG, "Setting buffer: " << newBuffer << endl);
1434 LASSERT(newBuffer, return);
1436 GuiWorkArea * wa = workArea(*newBuffer);
1439 newBuffer->masterBuffer()->updateBuffer();
1441 wa = addWorkArea(*newBuffer);
1442 // scroll to the position when the BufferView was last closed
1443 if (lyxrc.use_lastfilepos) {
1444 LastFilePosSection::FilePos filepos =
1445 theSession().lastFilePos().load(newBuffer->fileName());
1446 wa->bufferView().moveToPosition(filepos.pit, filepos.pos, 0, 0);
1449 //Disconnect the old buffer...there's no new one.
1452 connectBuffer(*newBuffer);
1453 connectBufferView(wa->bufferView());
1454 setCurrentWorkArea(wa);
1458 void GuiView::connectBuffer(Buffer & buf)
1460 buf.setGuiDelegate(this);
1464 void GuiView::disconnectBuffer()
1466 if (d.current_work_area_)
1467 d.current_work_area_->bufferView().buffer().setGuiDelegate(0);
1471 void GuiView::connectBufferView(BufferView & bv)
1473 bv.setGuiDelegate(this);
1477 void GuiView::disconnectBufferView()
1479 if (d.current_work_area_)
1480 d.current_work_area_->bufferView().setGuiDelegate(0);
1484 void GuiView::errors(string const & error_type, bool from_master)
1486 BufferView const * const bv = currentBufferView();
1490 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
1491 // We are called with from_master == false by default, so we
1492 // have to figure out whether that is the case or not.
1493 ErrorList & el = bv->buffer().errorList(error_type);
1495 el = bv->buffer().masterBuffer()->errorList(error_type);
1499 ErrorList const & el = from_master ?
1500 bv->buffer().masterBuffer()->errorList(error_type) :
1501 bv->buffer().errorList(error_type);
1507 string data = error_type;
1509 data = "from_master|" + error_type;
1510 showDialog("errorlist", data);
1514 void GuiView::updateTocItem(string const & type, DocIterator const & dit)
1516 d.toc_models_.updateItem(toqstr(type), dit);
1520 void GuiView::structureChanged()
1522 d.toc_models_.reset(documentBufferView());
1523 // Navigator needs more than a simple update in this case. It needs to be
1525 updateDialog("toc", "");
1529 void GuiView::updateDialog(string const & name, string const & data)
1531 if (!isDialogVisible(name))
1534 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
1535 if (it == d.dialogs_.end())
1538 Dialog * const dialog = it->second.get();
1539 if (dialog->isVisibleView())
1540 dialog->initialiseParams(data);
1544 BufferView * GuiView::documentBufferView()
1546 return currentMainWorkArea()
1547 ? ¤tMainWorkArea()->bufferView()
1552 BufferView const * GuiView::documentBufferView() const
1554 return currentMainWorkArea()
1555 ? ¤tMainWorkArea()->bufferView()
1560 BufferView * GuiView::currentBufferView()
1562 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1566 BufferView const * GuiView::currentBufferView() const
1568 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1572 #if (QT_VERSION >= 0x040400)
1573 docstring GuiView::GuiViewPrivate::autosaveAndDestroy(
1574 Buffer const * orig, Buffer * clone)
1576 bool const success = clone->autoSave();
1578 busyBuffers.remove(orig);
1580 ? _("Automatic save done.")
1581 : _("Automatic save failed!");
1586 void GuiView::autoSave()
1588 LYXERR(Debug::INFO, "Running autoSave()");
1590 Buffer * buffer = documentBufferView()
1591 ? &documentBufferView()->buffer() : 0;
1593 resetAutosaveTimers();
1597 #if (QT_VERSION >= 0x040400)
1598 GuiViewPrivate::busyBuffers.insert(buffer);
1599 QFuture<docstring> f = QtConcurrent::run(GuiViewPrivate::autosaveAndDestroy,
1600 buffer, buffer->cloneBufferOnly());
1601 d.autosave_watcher_.setFuture(f);
1605 resetAutosaveTimers();
1609 void GuiView::resetAutosaveTimers()
1612 d.autosave_timeout_.restart();
1616 bool GuiView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1619 Buffer * buf = currentBufferView()
1620 ? ¤tBufferView()->buffer() : 0;
1621 Buffer * doc_buffer = documentBufferView()
1622 ? &(documentBufferView()->buffer()) : 0;
1624 // Check whether we need a buffer
1625 if (!lyxaction.funcHasFlag(cmd.action(), LyXAction::NoBuffer) && !buf) {
1626 // no, exit directly
1627 flag.message(from_utf8(N_("Command not allowed with"
1628 "out any document open")));
1629 flag.setEnabled(false);
1633 if (cmd.origin() == FuncRequest::TOC) {
1634 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
1635 if (!toc || !toc->getStatus(documentBufferView()->cursor(), cmd, flag))
1636 flag.setEnabled(false);
1640 switch(cmd.action()) {
1641 case LFUN_BUFFER_IMPORT:
1644 case LFUN_MASTER_BUFFER_UPDATE:
1645 case LFUN_MASTER_BUFFER_VIEW:
1646 enable = doc_buffer && doc_buffer->parent() != 0
1647 && !d.processing_thread_watcher_.isRunning();
1650 case LFUN_BUFFER_UPDATE:
1651 case LFUN_BUFFER_VIEW: {
1652 if (!doc_buffer || d.processing_thread_watcher_.isRunning()) {
1656 string format = to_utf8(cmd.argument());
1657 if (cmd.argument().empty())
1658 format = doc_buffer->params().getDefaultOutputFormat();
1659 enable = doc_buffer->params().isExportableFormat(format);
1663 case LFUN_BUFFER_RELOAD:
1664 enable = doc_buffer && !doc_buffer->isUnnamed()
1665 && doc_buffer->fileName().exists()
1666 && (!doc_buffer->isClean()
1667 || doc_buffer->isExternallyModified(Buffer::timestamp_method));
1670 case LFUN_BUFFER_CHILD_OPEN:
1671 enable = doc_buffer;
1674 case LFUN_BUFFER_WRITE:
1675 enable = doc_buffer && (doc_buffer->isUnnamed() || !doc_buffer->isClean());
1678 //FIXME: This LFUN should be moved to GuiApplication.
1679 case LFUN_BUFFER_WRITE_ALL: {
1680 // We enable the command only if there are some modified buffers
1681 Buffer * first = theBufferList().first();
1686 // We cannot use a for loop as the buffer list is a cycle.
1688 if (!b->isClean()) {
1692 b = theBufferList().next(b);
1693 } while (b != first);
1697 case LFUN_BUFFER_WRITE_AS:
1698 case LFUN_BUFFER_EXPORT_AS:
1699 enable = doc_buffer;
1702 case LFUN_BUFFER_CLOSE:
1703 case LFUN_VIEW_CLOSE:
1704 enable = doc_buffer;
1707 case LFUN_BUFFER_CLOSE_ALL:
1708 enable = theBufferList().last() != theBufferList().first();
1711 case LFUN_SPLIT_VIEW:
1712 if (cmd.getArg(0) == "vertical")
1713 enable = doc_buffer && (d.splitter_->count() == 1 ||
1714 d.splitter_->orientation() == Qt::Vertical);
1716 enable = doc_buffer && (d.splitter_->count() == 1 ||
1717 d.splitter_->orientation() == Qt::Horizontal);
1720 case LFUN_CLOSE_TAB_GROUP:
1721 enable = d.tabWorkAreaCount() > 1;
1724 case LFUN_TOOLBAR_TOGGLE: {
1725 string const name = cmd.getArg(0);
1726 if (GuiToolbar * t = toolbar(name))
1727 flag.setOnOff(t->isVisible());
1730 docstring const msg =
1731 bformat(_("Unknown toolbar \"%1$s\""), from_utf8(name));
1737 case LFUN_DROP_LAYOUTS_CHOICE:
1741 case LFUN_UI_TOGGLE:
1742 flag.setOnOff(isFullScreen());
1745 case LFUN_DIALOG_DISCONNECT_INSET:
1748 case LFUN_DIALOG_HIDE:
1749 // FIXME: should we check if the dialog is shown?
1752 case LFUN_DIALOG_TOGGLE:
1753 flag.setOnOff(isDialogVisible(cmd.getArg(0)));
1754 // fall through to set "enable"
1755 case LFUN_DIALOG_SHOW: {
1756 string const name = cmd.getArg(0);
1758 enable = name == "aboutlyx"
1759 || name == "file" //FIXME: should be removed.
1761 || name == "texinfo"
1762 || name == "progress"
1763 || name == "compare";
1764 else if (name == "print")
1765 enable = doc_buffer->params().isExportable("dvi")
1766 && lyxrc.print_command != "none";
1767 else if (name == "character" || name == "symbols") {
1768 if (!buf || buf->isReadonly())
1771 Cursor const & cur = currentBufferView()->cursor();
1772 enable = !(cur.inTexted() && cur.paragraph().isPassThru());
1775 else if (name == "latexlog")
1776 enable = FileName(doc_buffer->logName()).isReadableFile();
1777 else if (name == "spellchecker")
1778 enable = theSpellChecker()
1779 && !doc_buffer->isReadonly()
1780 && !doc_buffer->text().empty();
1781 else if (name == "vclog")
1782 enable = doc_buffer->lyxvc().inUse();
1786 case LFUN_DIALOG_UPDATE: {
1787 string const name = cmd.getArg(0);
1789 enable = name == "prefs";
1793 case LFUN_COMMAND_EXECUTE:
1795 case LFUN_MENU_OPEN:
1796 // Nothing to check.
1799 case LFUN_COMPLETION_INLINE:
1800 if (!d.current_work_area_
1801 || !d.current_work_area_->completer().inlinePossible(
1802 currentBufferView()->cursor()))
1806 case LFUN_COMPLETION_POPUP:
1807 if (!d.current_work_area_
1808 || !d.current_work_area_->completer().popupPossible(
1809 currentBufferView()->cursor()))
1813 case LFUN_COMPLETION_COMPLETE:
1814 if (!d.current_work_area_
1815 || !d.current_work_area_->completer().inlinePossible(
1816 currentBufferView()->cursor()))
1820 case LFUN_COMPLETION_ACCEPT:
1821 if (!d.current_work_area_
1822 || (!d.current_work_area_->completer().popupVisible()
1823 && !d.current_work_area_->completer().inlineVisible()
1824 && !d.current_work_area_->completer().completionAvailable()))
1828 case LFUN_COMPLETION_CANCEL:
1829 if (!d.current_work_area_
1830 || (!d.current_work_area_->completer().popupVisible()
1831 && !d.current_work_area_->completer().inlineVisible()))
1835 case LFUN_BUFFER_ZOOM_OUT:
1836 enable = doc_buffer && lyxrc.zoom > 10;
1839 case LFUN_BUFFER_ZOOM_IN:
1840 enable = doc_buffer;
1843 case LFUN_BUFFER_NEXT:
1844 case LFUN_BUFFER_PREVIOUS:
1845 // FIXME: should we check is there is an previous or next buffer?
1847 case LFUN_BUFFER_SWITCH:
1848 // toggle on the current buffer, but do not toggle off
1849 // the other ones (is that a good idea?)
1851 && to_utf8(cmd.argument()) == doc_buffer->absFileName())
1852 flag.setOnOff(true);
1855 case LFUN_VC_REGISTER:
1856 enable = doc_buffer && !doc_buffer->lyxvc().inUse();
1858 case LFUN_VC_CHECK_IN:
1859 enable = doc_buffer && doc_buffer->lyxvc().checkInEnabled();
1861 case LFUN_VC_CHECK_OUT:
1862 enable = doc_buffer && doc_buffer->lyxvc().checkOutEnabled();
1864 case LFUN_VC_LOCKING_TOGGLE:
1865 enable = doc_buffer && !doc_buffer->isReadonly()
1866 && doc_buffer->lyxvc().lockingToggleEnabled();
1867 flag.setOnOff(enable && doc_buffer->lyxvc().locking());
1869 case LFUN_VC_REVERT:
1870 enable = doc_buffer && doc_buffer->lyxvc().inUse() && !doc_buffer->isReadonly();
1872 case LFUN_VC_UNDO_LAST:
1873 enable = doc_buffer && doc_buffer->lyxvc().undoLastEnabled();
1875 case LFUN_VC_REPO_UPDATE:
1876 enable = doc_buffer && doc_buffer->lyxvc().repoUpdateEnabled();
1878 case LFUN_VC_COMMAND: {
1879 if (cmd.argument().empty())
1881 if (!doc_buffer && contains(cmd.getArg(0), 'D'))
1885 case LFUN_VC_COMPARE:
1886 enable = doc_buffer && doc_buffer->lyxvc().prepareFileRevisionEnabled();
1889 case LFUN_SERVER_GOTO_FILE_ROW:
1891 case LFUN_FORWARD_SEARCH:
1892 enable = !(lyxrc.forward_search_dvi.empty() && lyxrc.forward_search_pdf.empty());
1895 case LFUN_FILE_INSERT_PLAINTEXT:
1896 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
1897 enable = documentBufferView() && documentBufferView()->cursor().inTexted();
1905 flag.setEnabled(false);
1911 static FileName selectTemplateFile()
1913 FileDialog dlg(qt_("Select template file"));
1914 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1915 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
1917 FileDialog::Result result = dlg.open(toqstr(lyxrc.template_path),
1918 QStringList(qt_("LyX Documents (*.lyx)")));
1920 if (result.first == FileDialog::Later)
1922 if (result.second.isEmpty())
1924 return FileName(fromqstr(result.second));
1928 Buffer * GuiView::loadDocument(FileName const & filename, bool tolastfiles)
1932 Buffer * newBuffer = 0;
1934 newBuffer = checkAndLoadLyXFile(filename);
1935 } catch (ExceptionMessage const & e) {
1942 message(_("Document not loaded."));
1946 setBuffer(newBuffer);
1947 newBuffer->errors("Parse");
1950 theSession().lastFiles().add(filename);
1956 void GuiView::openDocument(string const & fname)
1958 string initpath = lyxrc.document_path;
1960 if (documentBufferView()) {
1961 string const trypath = documentBufferView()->buffer().filePath();
1962 // If directory is writeable, use this as default.
1963 if (FileName(trypath).isDirWritable())
1969 if (fname.empty()) {
1970 FileDialog dlg(qt_("Select document to open"), LFUN_FILE_OPEN);
1971 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1972 dlg.setButton2(qt_("Examples|#E#e"),
1973 toqstr(addPath(package().system_support().absFileName(), "examples")));
1975 QStringList filter(qt_("LyX Documents (*.lyx)"));
1976 filter << qt_("LyX-1.3.x Documents (*.lyx13)")
1977 << qt_("LyX-1.4.x Documents (*.lyx14)")
1978 << qt_("LyX-1.5.x Documents (*.lyx15)")
1979 << qt_("LyX-1.6.x Documents (*.lyx16)");
1980 FileDialog::Result result =
1981 dlg.open(toqstr(initpath), filter);
1983 if (result.first == FileDialog::Later)
1986 filename = fromqstr(result.second);
1988 // check selected filename
1989 if (filename.empty()) {
1990 message(_("Canceled."));
1996 // get absolute path of file and add ".lyx" to the filename if
1998 FileName const fullname =
1999 fileSearch(string(), filename, "lyx", support::may_not_exist);
2000 if (!fullname.empty())
2001 filename = fullname.absFileName();
2003 if (!fullname.onlyPath().isDirectory()) {
2004 Alert::warning(_("Invalid filename"),
2005 bformat(_("The directory in the given path\n%1$s\ndoes not exist."),
2006 from_utf8(fullname.absFileName())));
2010 // if the file doesn't exist and isn't already open (bug 6645),
2011 // let the user create one
2012 if (!fullname.exists() && !theBufferList().exists(fullname)) {
2013 // the user specifically chose this name. Believe him.
2014 Buffer * const b = newFile(filename, string(), true);
2020 docstring const disp_fn = makeDisplayPath(filename);
2021 message(bformat(_("Opening document %1$s..."), disp_fn));
2024 Buffer * buf = loadDocument(fullname);
2026 str2 = bformat(_("Document %1$s opened."), disp_fn);
2027 if (buf->lyxvc().inUse())
2028 str2 += " " + from_utf8(buf->lyxvc().versionString()) +
2029 " " + _("Version control detected.");
2031 str2 = bformat(_("Could not open document %1$s"), disp_fn);
2036 // FIXME: clean that
2037 static bool import(GuiView * lv, FileName const & filename,
2038 string const & format, ErrorList & errorList)
2040 FileName const lyxfile(support::changeExtension(filename.absFileName(), ".lyx"));
2042 string loader_format;
2043 vector<string> loaders = theConverters().loaders();
2044 if (find(loaders.begin(), loaders.end(), format) == loaders.end()) {
2045 vector<string>::const_iterator it = loaders.begin();
2046 vector<string>::const_iterator en = loaders.end();
2047 for (; it != en; ++it) {
2048 if (!theConverters().isReachable(format, *it))
2051 string const tofile =
2052 support::changeExtension(filename.absFileName(),
2053 formats.extension(*it));
2054 if (!theConverters().convert(0, filename, FileName(tofile),
2055 filename, format, *it, errorList))
2057 loader_format = *it;
2060 if (loader_format.empty()) {
2061 frontend::Alert::error(_("Couldn't import file"),
2062 bformat(_("No information for importing the format %1$s."),
2063 formats.prettyName(format)));
2067 loader_format = format;
2069 if (loader_format == "lyx") {
2070 Buffer * buf = lv->loadDocument(lyxfile);
2074 Buffer * const b = newFile(lyxfile.absFileName(), string(), true);
2078 bool as_paragraphs = loader_format == "textparagraph";
2079 string filename2 = (loader_format == format) ? filename.absFileName()
2080 : support::changeExtension(filename.absFileName(),
2081 formats.extension(loader_format));
2082 lv->currentBufferView()->insertPlaintextFile(FileName(filename2),
2084 guiApp->setCurrentView(lv);
2085 lyx::dispatch(FuncRequest(LFUN_MARK_OFF));
2092 void GuiView::importDocument(string const & argument)
2095 string filename = split(argument, format, ' ');
2097 LYXERR(Debug::INFO, format << " file: " << filename);
2099 // need user interaction
2100 if (filename.empty()) {
2101 string initpath = lyxrc.document_path;
2102 if (documentBufferView()) {
2103 string const trypath = documentBufferView()->buffer().filePath();
2104 // If directory is writeable, use this as default.
2105 if (FileName(trypath).isDirWritable())
2109 docstring const text = bformat(_("Select %1$s file to import"),
2110 formats.prettyName(format));
2112 FileDialog dlg(toqstr(text), LFUN_BUFFER_IMPORT);
2113 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2114 dlg.setButton2(qt_("Examples|#E#e"),
2115 toqstr(addPath(package().system_support().absFileName(), "examples")));
2117 docstring filter = formats.prettyName(format);
2120 filter += from_utf8(formats.extensions(format));
2123 FileDialog::Result result =
2124 dlg.open(toqstr(initpath), fileFilters(toqstr(filter)));
2126 if (result.first == FileDialog::Later)
2129 filename = fromqstr(result.second);
2131 // check selected filename
2132 if (filename.empty())
2133 message(_("Canceled."));
2136 if (filename.empty())
2139 // get absolute path of file
2140 FileName const fullname(support::makeAbsPath(filename));
2142 FileName const lyxfile(support::changeExtension(fullname.absFileName(), ".lyx"));
2144 // Check if the document already is open
2145 Buffer * buf = theBufferList().getBuffer(lyxfile);
2148 if (!closeBuffer()) {
2149 message(_("Canceled."));
2154 docstring const displaypath = makeDisplayPath(lyxfile.absFileName(), 30);
2156 // if the file exists already, and we didn't do
2157 // -i lyx thefile.lyx, warn
2158 if (lyxfile.exists() && fullname != lyxfile) {
2160 docstring text = bformat(_("The document %1$s already exists.\n\n"
2161 "Do you want to overwrite that document?"), displaypath);
2162 int const ret = Alert::prompt(_("Overwrite document?"),
2163 text, 0, 1, _("&Overwrite"), _("&Cancel"));
2166 message(_("Canceled."));
2171 message(bformat(_("Importing %1$s..."), displaypath));
2172 ErrorList errorList;
2173 if (import(this, fullname, format, errorList))
2174 message(_("imported."));
2176 message(_("file not imported!"));
2178 // FIXME (Abdel 12/08/06): Is there a need to display the error list here?
2182 void GuiView::newDocument(string const & filename, bool from_template)
2184 FileName initpath(lyxrc.document_path);
2185 if (documentBufferView()) {
2186 FileName const trypath(documentBufferView()->buffer().filePath());
2187 // If directory is writeable, use this as default.
2188 if (trypath.isDirWritable())
2192 string templatefile;
2193 if (from_template) {
2194 templatefile = selectTemplateFile().absFileName();
2195 if (templatefile.empty())
2200 if (filename.empty())
2201 b = newUnnamedFile(initpath, to_utf8(_("newfile")), templatefile);
2203 b = newFile(filename, templatefile, true);
2208 // If no new document could be created, it is unsure
2209 // whether there is a valid BufferView.
2210 if (currentBufferView())
2211 // Ensure the cursor is correctly positioned on screen.
2212 currentBufferView()->showCursor();
2216 void GuiView::insertLyXFile(docstring const & fname)
2218 BufferView * bv = documentBufferView();
2223 FileName filename(to_utf8(fname));
2224 if (filename.empty()) {
2225 // Launch a file browser
2227 string initpath = lyxrc.document_path;
2228 string const trypath = bv->buffer().filePath();
2229 // If directory is writeable, use this as default.
2230 if (FileName(trypath).isDirWritable())
2234 FileDialog dlg(qt_("Select LyX document to insert"), LFUN_FILE_INSERT);
2235 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2236 dlg.setButton2(qt_("Examples|#E#e"),
2237 toqstr(addPath(package().system_support().absFileName(),
2240 FileDialog::Result result = dlg.open(toqstr(initpath),
2241 QStringList(qt_("LyX Documents (*.lyx)")));
2243 if (result.first == FileDialog::Later)
2247 filename.set(fromqstr(result.second));
2249 // check selected filename
2250 if (filename.empty()) {
2251 // emit message signal.
2252 message(_("Canceled."));
2257 bv->insertLyXFile(filename);
2258 bv->buffer().errors("Parse");
2262 bool GuiView::renameBuffer(Buffer & b, docstring const & newname)
2264 FileName fname = b.fileName();
2265 FileName const oldname = fname;
2267 if (!newname.empty()) {
2269 fname = support::makeAbsPath(to_utf8(newname), oldname.onlyPath().absFileName());
2271 // Switch to this Buffer.
2274 // No argument? Ask user through dialog.
2276 FileDialog dlg(qt_("Choose a filename to save document as"),
2277 LFUN_BUFFER_WRITE_AS);
2278 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2279 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
2281 if (!isLyXFileName(fname.absFileName()))
2282 fname.changeExtension(".lyx");
2284 FileDialog::Result result =
2285 dlg.save(toqstr(fname.onlyPath().absFileName()),
2286 QStringList(qt_("LyX Documents (*.lyx)")),
2287 toqstr(fname.onlyFileName()));
2289 if (result.first == FileDialog::Later)
2292 fname.set(fromqstr(result.second));
2297 if (!isLyXFileName(fname.absFileName()))
2298 fname.changeExtension(".lyx");
2301 // fname is now the new Buffer location.
2303 // if there is already a Buffer open with this name, we do not want
2304 // to have another one. (the second test makes sure we're not just
2305 // trying to overwrite ourselves, which is fine.)
2306 if (theBufferList().exists(fname) && fname != oldname
2307 && theBufferList().getBuffer(fname) != &b) {
2308 docstring const text =
2309 bformat(_("The file\n%1$s\nis already open in your current session.\n"
2310 "Please close it before attempting to overwrite it.\n"
2311 "Do you want to choose a new filename?"),
2312 from_utf8(fname.absFileName()));
2313 int const ret = Alert::prompt(_("Chosen File Already Open"),
2314 text, 0, 1, _("&Rename"), _("&Cancel"));
2316 case 0: return renameBuffer(b, docstring());
2317 case 1: return false;
2322 if (FileName(fname).exists()) {
2323 docstring const file = makeDisplayPath(fname.absFileName(), 30);
2324 docstring const text = bformat(_("The document %1$s already "
2325 "exists.\n\nDo you want to "
2326 "overwrite that document?"),
2328 int const ret = Alert::prompt(_("Overwrite document?"),
2329 text, 0, 2, _("&Overwrite"), _("&Rename"), _("&Cancel"));
2332 case 1: return renameBuffer(b, docstring());
2333 case 2: return false;
2337 bool const saved = saveBuffer(b, fname);
2344 struct PrettyNameComparator
2346 bool operator()(Format const *first, Format const *second) const {
2347 return compare_ascii_no_case(first->prettyname(), second->prettyname()) <= 0;
2352 bool GuiView::exportBufferAs(Buffer & b)
2354 FileName fname = b.fileName();
2356 FileDialog dlg(qt_("Choose a filename to export the document as"));
2357 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2360 types << "Any supported format (*.*)";
2361 Formats::const_iterator it = formats.begin();
2362 vector<Format const *> export_formats;
2363 for (; it != formats.end(); ++it)
2364 if (it->documentFormat() && it->inExportMenu())
2365 export_formats.push_back(&(*it));
2366 PrettyNameComparator cmp;
2367 sort(export_formats.begin(), export_formats.end(), cmp);
2368 vector<Format const *>::const_iterator fit = export_formats.begin();
2369 for (; fit != export_formats.end(); ++fit)
2370 types << toqstr((*fit)->prettyname() + " (*." + (*fit)->extension() + ")");
2372 FileDialog::Result result =
2373 dlg.save(toqstr(fname.onlyPath().absFileName()),
2375 toqstr(fname.onlyFileName()),
2377 if (result.first != FileDialog::Chosen)
2380 string s = fromqstr(filter);
2381 size_t pos = s.find(" (*.");
2382 LASSERT(pos != string::npos, /**/);
2383 string fmt_prettyname = s.substr(0, pos);
2385 fname.set(fromqstr(result.second));
2386 if (fmt_prettyname == "Any supported format")
2387 fmt_name = formats.getFormatFromExtension(fname.extension());
2389 fmt_name = formats.getFormatFromPrettyName(fmt_prettyname);
2390 LYXERR(Debug::FILES, "fmt_prettyname=" << fmt_prettyname
2391 << ", fmt_name=" << fmt_name << ", fname=" << fname.absFileName());
2393 if (fmt_name.empty() || fname.empty())
2396 // fname is now the new Buffer location.
2397 if (FileName(fname).exists()) {
2398 docstring const file = makeDisplayPath(fname.absFileName(), 30);
2399 docstring text = bformat(_("The document %1$s already "
2400 "exists.\n\nDo you want to "
2401 "overwrite that document?"),
2403 int const ret = Alert::prompt(_("Overwrite document?"),
2404 text, 0, 2, _("&Overwrite"), _("&Rename"), _("&Cancel"));
2407 case 1: return exportBufferAs(b);
2408 case 2: return false;
2412 FuncRequest cmd(LFUN_BUFFER_EXPORT, fmt_name + " " + fname.absFileName());
2415 return dr.dispatched();
2419 bool GuiView::saveBuffer(Buffer & b) {
2420 return saveBuffer(b, FileName());
2424 bool GuiView::saveBuffer(Buffer & b, FileName const & fn)
2426 if (workArea(b) && workArea(b)->inDialogMode())
2429 if (fn.empty() && b.isUnnamed())
2430 return renameBuffer(b, docstring());
2436 success = b.saveAs(fn);
2439 theSession().lastFiles().add(b.fileName());
2443 // Switch to this Buffer.
2446 // FIXME: we don't tell the user *WHY* the save failed !!
2447 docstring const file = makeDisplayPath(b.absFileName(), 30);
2448 docstring text = bformat(_("The document %1$s could not be saved.\n\n"
2449 "Do you want to rename the document and "
2450 "try again?"), file);
2451 int const ret = Alert::prompt(_("Rename and save?"),
2452 text, 0, 2, _("&Rename"), _("&Retry"), _("&Cancel"));
2455 if (!renameBuffer(b, docstring()))
2464 return saveBuffer(b);
2468 bool GuiView::hideWorkArea(GuiWorkArea * wa)
2470 return closeWorkArea(wa, false);
2474 // We only want to close the buffer if it is not visible in other workareas
2475 // of the same view, nor in other views, and if this is not a child
2476 bool GuiView::closeWorkArea(GuiWorkArea * wa)
2478 Buffer & buf = wa->bufferView().buffer();
2480 bool last_wa = d.countWorkAreasOf(buf) == 1
2481 && !inOtherView(buf) && !buf.parent();
2483 bool close_buffer = last_wa;
2486 if (lyxrc.close_buffer_with_last_view == "yes")
2488 else if (lyxrc.close_buffer_with_last_view == "no")
2489 close_buffer = false;
2492 if (buf.isUnnamed())
2493 file = from_utf8(buf.fileName().onlyFileName());
2495 file = buf.fileName().displayName(30);
2496 docstring const text = bformat(
2497 _("Last view on document %1$s is being closed.\n"
2498 "Would you like to close or hide the document?\n"
2500 "Hidden documents can be displayed back through\n"
2501 "the menu: View->Hidden->...\n"
2503 "To remove this question, set your preference in:\n"
2504 " Tools->Preferences->Look&Feel->UserInterface\n"
2506 int ret = Alert::prompt(_("Close or hide document?"),
2507 text, 0, 1, _("&Close"), _("&Hide"));
2508 close_buffer = (ret == 0);
2512 return closeWorkArea(wa, close_buffer);
2516 bool GuiView::closeBuffer()
2518 GuiWorkArea * wa = currentMainWorkArea();
2519 setCurrentWorkArea(wa);
2520 Buffer & buf = wa->bufferView().buffer();
2521 return wa && closeWorkArea(wa, !buf.parent());
2525 void GuiView::writeSession() const {
2526 GuiWorkArea const * active_wa = currentMainWorkArea();
2527 for (int i = 0; i < d.splitter_->count(); ++i) {
2528 TabWorkArea * twa = d.tabWorkArea(i);
2529 for (int j = 0; j < twa->count(); ++j) {
2530 GuiWorkArea * wa = static_cast<GuiWorkArea *>(twa->widget(j));
2531 Buffer & buf = wa->bufferView().buffer();
2532 theSession().lastOpened().add(buf.fileName(), wa == active_wa);
2538 bool GuiView::closeBufferAll()
2540 // Close the workareas in all other views
2541 QList<int> const ids = guiApp->viewIds();
2542 for (int i = 0; i != ids.size(); ++i) {
2543 if (id_ != ids[i] && !guiApp->view(ids[i]).closeWorkAreaAll())
2547 // Close our own workareas
2548 if (!closeWorkAreaAll())
2551 // Now close the hidden buffers. We prevent hidden buffers from being
2552 // dirty, so we can just close them.
2553 theBufferList().closeAll();
2558 bool GuiView::closeWorkAreaAll()
2560 setCurrentWorkArea(currentMainWorkArea());
2562 // We might be in a situation that there is still a tabWorkArea, but
2563 // there are no tabs anymore. This can happen when we get here after a
2564 // TabWorkArea::lastWorkAreaRemoved() signal. Therefore we count how
2565 // many TabWorkArea's have no documents anymore.
2568 // We have to call count() each time, because it can happen that
2569 // more than one splitter will disappear in one iteration (bug 5998).
2570 for (; d.splitter_->count() > empty_twa; ) {
2571 TabWorkArea * twa = d.tabWorkArea(empty_twa);
2573 if (twa->count() == 0)
2576 setCurrentWorkArea(twa->currentWorkArea());
2577 if (!closeTabWorkArea(twa))
2585 bool GuiView::closeWorkArea(GuiWorkArea * wa, bool close_buffer)
2590 Buffer & buf = wa->bufferView().buffer();
2592 if (close_buffer && GuiViewPrivate::busyBuffers.contains(&buf)) {
2593 Alert::warning(_("Close document"),
2594 _("Document could not be closed because it is being processed by LyX."));
2599 return closeBuffer(buf);
2601 if (!inMultiTabs(wa))
2602 if (!saveBufferIfNeeded(buf, true))
2610 bool GuiView::closeBuffer(Buffer & buf)
2612 // If we are in a close_event all children will be closed in some time,
2613 // so no need to do it here. This will ensure that the children end up
2614 // in the session file in the correct order. If we close the master
2615 // buffer, we can close or release the child buffers here too.
2616 bool success = true;
2618 ListOfBuffers clist = buf.getChildren();
2619 ListOfBuffers::const_iterator it = clist.begin();
2620 ListOfBuffers::const_iterator const bend = clist.end();
2621 for (; it != bend; ++it) {
2622 // If a child is dirty, do not close
2623 // without user intervention
2624 //FIXME: should we look in other tabworkareas?
2625 Buffer * child_buf = *it;
2626 GuiWorkArea * child_wa = workArea(*child_buf);
2628 if (!closeWorkArea(child_wa, true)) {
2633 theBufferList().releaseChild(&buf, child_buf);
2637 // goto bookmark to update bookmark pit.
2638 //FIXME: we should update only the bookmarks related to this buffer!
2639 LYXERR(Debug::DEBUG, "GuiView::closeBuffer()");
2640 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
2641 guiApp->gotoBookmark(i+1, false, false);
2643 if (saveBufferIfNeeded(buf, false)) {
2644 buf.removeAutosaveFile();
2645 theBufferList().release(&buf);
2649 // open all children again to avoid a crash because of dangling
2650 // pointers (bug 6603)
2656 bool GuiView::closeTabWorkArea(TabWorkArea * twa)
2658 while (twa == d.currentTabWorkArea()) {
2659 twa->setCurrentIndex(twa->count()-1);
2661 GuiWorkArea * wa = twa->currentWorkArea();
2662 Buffer & b = wa->bufferView().buffer();
2664 // We only want to close the buffer if the same buffer is not visible
2665 // in another view, and if this is not a child and if we are closing
2666 // a view (not a tabgroup).
2667 bool const close_buffer =
2668 !inOtherView(b) && !b.parent() && closing_;
2670 if (!closeWorkArea(wa, close_buffer))
2677 bool GuiView::saveBufferIfNeeded(Buffer & buf, bool hiding)
2679 if (buf.isClean() || buf.paragraphs().empty())
2682 // Switch to this Buffer.
2687 if (buf.isUnnamed())
2688 file = from_utf8(buf.fileName().onlyFileName());
2690 file = buf.fileName().displayName(30);
2692 // Bring this window to top before asking questions.
2697 if (hiding && buf.isUnnamed()) {
2698 docstring const text = bformat(_("The document %1$s has not been "
2699 "saved yet.\n\nDo you want to save "
2700 "the document?"), file);
2701 ret = Alert::prompt(_("Save new document?"),
2702 text, 0, 1, _("&Save"), _("&Cancel"));
2706 docstring const text = bformat(_("The document %1$s has unsaved changes."
2707 "\n\nDo you want to save the document or discard the changes?"), file);
2708 ret = Alert::prompt(_("Save changed document?"),
2709 text, 0, 2, _("&Save"), _("&Discard"), _("&Cancel"));
2714 if (!saveBuffer(buf))
2718 // If we crash after this we could have no autosave file
2719 // but I guess this is really improbable (Jug).
2720 // Sometimes improbable things happen:
2721 // - see bug http://www.lyx.org/trac/ticket/6587 (ps)
2722 // buf.removeAutosaveFile();
2724 // revert all changes
2735 bool GuiView::inMultiTabs(GuiWorkArea * wa)
2737 Buffer & buf = wa->bufferView().buffer();
2739 for (int i = 0; i != d.splitter_->count(); ++i) {
2740 GuiWorkArea * wa_ = d.tabWorkArea(i)->workArea(buf);
2741 if (wa_ && wa_ != wa)
2744 return inOtherView(buf);
2748 bool GuiView::inOtherView(Buffer & buf)
2750 QList<int> const ids = guiApp->viewIds();
2752 for (int i = 0; i != ids.size(); ++i) {
2756 if (guiApp->view(ids[i]).workArea(buf))
2763 void GuiView::gotoNextOrPreviousBuffer(NextOrPrevious np)
2765 if (!documentBufferView())
2768 if (TabWorkArea * twa = d.currentTabWorkArea()) {
2769 Buffer * const curbuf = &documentBufferView()->buffer();
2770 int nwa = twa->count();
2771 for (int i = 0; i < nwa; ++i) {
2772 if (&workArea(i)->bufferView().buffer() == curbuf) {
2774 if (np == NEXTBUFFER)
2775 next_index = (i == nwa - 1 ? 0 : i + 1);
2777 next_index = (i == 0 ? nwa - 1 : i - 1);
2778 setBuffer(&workArea(next_index)->bufferView().buffer());
2786 /// make sure the document is saved
2787 static bool ensureBufferClean(Buffer * buffer)
2789 LASSERT(buffer, return false);
2790 if (buffer->isClean() && !buffer->isUnnamed())
2793 docstring const file = buffer->fileName().displayName(30);
2796 if (!buffer->isUnnamed()) {
2797 text = bformat(_("The document %1$s has unsaved "
2798 "changes.\n\nDo you want to save "
2799 "the document?"), file);
2800 title = _("Save changed document?");
2803 text = bformat(_("The document %1$s has not been "
2804 "saved yet.\n\nDo you want to save "
2805 "the document?"), file);
2806 title = _("Save new document?");
2808 int const ret = Alert::prompt(title, text, 0, 1, _("&Save"), _("&Cancel"));
2811 dispatch(FuncRequest(LFUN_BUFFER_WRITE));
2813 return buffer->isClean() && !buffer->isUnnamed();
2817 bool GuiView::reloadBuffer(Buffer & buf)
2819 Buffer::ReadStatus status = buf.reload();
2820 return status == Buffer::ReadSuccess;
2824 void GuiView::checkExternallyModifiedBuffers()
2826 BufferList::iterator bit = theBufferList().begin();
2827 BufferList::iterator const bend = theBufferList().end();
2828 for (; bit != bend; ++bit) {
2829 Buffer * buf = *bit;
2830 if (buf->fileName().exists()
2831 && buf->isExternallyModified(Buffer::checksum_method)) {
2832 docstring text = bformat(_("Document \n%1$s\n has been externally modified."
2833 " Reload now? Any local changes will be lost."),
2834 from_utf8(buf->absFileName()));
2835 int const ret = Alert::prompt(_("Reload externally changed document?"),
2836 text, 0, 1, _("&Reload"), _("&Cancel"));
2844 void GuiView::dispatchVC(FuncRequest const & cmd, DispatchResult & dr)
2846 Buffer * buffer = documentBufferView()
2847 ? &(documentBufferView()->buffer()) : 0;
2849 switch (cmd.action()) {
2850 case LFUN_VC_REGISTER:
2851 if (!buffer || !ensureBufferClean(buffer))
2853 if (!buffer->lyxvc().inUse()) {
2854 if (buffer->lyxvc().registrer()) {
2855 reloadBuffer(*buffer);
2856 dr.suppressMessageUpdate();
2861 case LFUN_VC_CHECK_IN:
2862 if (!buffer || !ensureBufferClean(buffer))
2864 if (buffer->lyxvc().inUse() && !buffer->isReadonly()) {
2865 dr.setMessage(buffer->lyxvc().checkIn());
2866 if (!dr.message().empty())
2867 reloadBuffer(*buffer);
2871 case LFUN_VC_CHECK_OUT:
2872 if (!buffer || !ensureBufferClean(buffer))
2874 if (buffer->lyxvc().inUse()) {
2875 dr.setMessage(buffer->lyxvc().checkOut());
2876 reloadBuffer(*buffer);
2880 case LFUN_VC_LOCKING_TOGGLE:
2881 LASSERT(buffer, return);
2882 if (!ensureBufferClean(buffer) || buffer->isReadonly())
2884 if (buffer->lyxvc().inUse()) {
2885 string res = buffer->lyxvc().lockingToggle();
2887 frontend::Alert::error(_("Revision control error."),
2888 _("Error when setting the locking property."));
2891 reloadBuffer(*buffer);
2896 case LFUN_VC_REVERT:
2897 LASSERT(buffer, return);
2898 if (buffer->lyxvc().revert()) {
2899 reloadBuffer(*buffer);
2900 dr.suppressMessageUpdate();
2904 case LFUN_VC_UNDO_LAST:
2905 LASSERT(buffer, return);
2906 buffer->lyxvc().undoLast();
2907 reloadBuffer(*buffer);
2908 dr.suppressMessageUpdate();
2911 case LFUN_VC_REPO_UPDATE:
2912 LASSERT(buffer, return);
2913 if (ensureBufferClean(buffer)) {
2914 dr.setMessage(buffer->lyxvc().repoUpdate());
2915 checkExternallyModifiedBuffers();
2919 case LFUN_VC_COMMAND: {
2920 string flag = cmd.getArg(0);
2921 if (buffer && contains(flag, 'R') && !ensureBufferClean(buffer))
2924 if (contains(flag, 'M')) {
2925 if (!Alert::askForText(message, _("LyX VC: Log Message")))
2928 string path = cmd.getArg(1);
2929 if (contains(path, "$$p") && buffer)
2930 path = subst(path, "$$p", buffer->filePath());
2931 LYXERR(Debug::LYXVC, "Directory: " << path);
2933 if (!pp.isReadableDirectory()) {
2934 lyxerr << _("Directory is not accessible.") << endl;
2937 support::PathChanger p(pp);
2939 string command = cmd.getArg(2);
2940 if (command.empty())
2943 command = subst(command, "$$i", buffer->absFileName());
2944 command = subst(command, "$$p", buffer->filePath());
2946 command = subst(command, "$$m", to_utf8(message));
2947 LYXERR(Debug::LYXVC, "Command: " << command);
2949 one.startscript(Systemcall::Wait, command);
2953 if (contains(flag, 'I'))
2954 buffer->markDirty();
2955 if (contains(flag, 'R'))
2956 reloadBuffer(*buffer);
2961 case LFUN_VC_COMPARE: {
2963 if (cmd.argument().empty()) {
2964 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "comparehistory"));
2968 string rev1 = cmd.getArg(0);
2972 if (!buffer->lyxvc().prepareFileRevision(rev1, f1))
2975 if (isStrInt(rev1) && convert<int>(rev1) <= 0) {
2976 f2 = buffer->absFileName();
2978 string rev2 = cmd.getArg(1);
2982 if (!buffer->lyxvc().prepareFileRevision(rev2, f2))
2986 LYXERR(Debug::LYXVC, "Launching comparison for fetched revisions:\n" <<
2987 f1 << "\n" << f2 << "\n" );
2988 string par = "compare run " + quoteName(f1) + " " + quoteName(f2);
2989 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, par));
2999 void GuiView::openChildDocument(string const & fname)
3001 LASSERT(documentBufferView(), return);
3002 Buffer & buffer = documentBufferView()->buffer();
3003 FileName const filename = support::makeAbsPath(fname, buffer.filePath());
3004 documentBufferView()->saveBookmark(false);
3006 if (theBufferList().exists(filename)) {
3007 child = theBufferList().getBuffer(filename);
3010 message(bformat(_("Opening child document %1$s..."),
3011 makeDisplayPath(filename.absFileName())));
3012 child = loadDocument(filename, false);
3014 // Set the parent name of the child document.
3015 // This makes insertion of citations and references in the child work,
3016 // when the target is in the parent or another child document.
3018 child->setParent(&buffer);
3022 bool GuiView::goToFileRow(string const & argument)
3026 size_t i = argument.find_last_of(' ');
3027 if (i != string::npos) {
3028 file_name = os::internal_path(trim(argument.substr(0, i)));
3029 istringstream is(argument.substr(i + 1));
3034 if (i == string::npos) {
3035 LYXERR0("Wrong argument: " << argument);
3039 string const abstmp = package().temp_dir().absFileName();
3040 string const realtmp = package().temp_dir().realPath();
3041 // We have to use os::path_prefix_is() here, instead of
3042 // simply prefixIs(), because the file name comes from
3043 // an external application and may need case adjustment.
3044 if (os::path_prefix_is(file_name, abstmp, os::CASE_ADJUSTED)
3045 || os::path_prefix_is(file_name, realtmp, os::CASE_ADJUSTED)) {
3046 // Needed by inverse dvi search. If it is a file
3047 // in tmpdir, call the apropriated function.
3048 // If tmpdir is a symlink, we may have the real
3049 // path passed back, so we correct for that.
3050 if (!prefixIs(file_name, abstmp))
3051 file_name = subst(file_name, realtmp, abstmp);
3052 buf = theBufferList().getBufferFromTmp(file_name);
3054 // Must replace extension of the file to be .lyx
3055 // and get full path
3056 FileName const s = fileSearch(string(),
3057 support::changeExtension(file_name, ".lyx"), "lyx");
3058 // Either change buffer or load the file
3059 if (theBufferList().exists(s))
3060 buf = theBufferList().getBuffer(s);
3061 else if (s.exists()) {
3062 buf = loadDocument(s);
3067 _("File does not exist: %1$s"),
3068 makeDisplayPath(file_name)));
3074 _("No buffer for file: %1$s."),
3075 makeDisplayPath(file_name))
3080 documentBufferView()->setCursorFromRow(row);
3085 #if (QT_VERSION >= 0x040400)
3087 Buffer::ExportStatus GuiView::GuiViewPrivate::runAndDestroy(const T& func, Buffer const * orig, Buffer * clone, string const & format)
3089 Buffer::ExportStatus const status = func(format);
3091 // the cloning operation will have produced a clone of the entire set of
3092 // documents, starting from the master. so we must delete those.
3093 Buffer * mbuf = const_cast<Buffer *>(clone->masterBuffer());
3095 busyBuffers.remove(orig);
3100 Buffer::ExportStatus GuiView::GuiViewPrivate::compileAndDestroy(Buffer const * orig, Buffer * clone, string const & format)
3102 Buffer::ExportStatus (Buffer::* mem_func)(std::string const &, bool) const = &Buffer::doExport;
3103 return runAndDestroy(bind(mem_func, clone, _1, true), orig, clone, format);
3107 Buffer::ExportStatus GuiView::GuiViewPrivate::exportAndDestroy(Buffer const * orig, Buffer * clone, string const & format)
3109 Buffer::ExportStatus (Buffer::* mem_func)(std::string const &, bool) const = &Buffer::doExport;
3110 return runAndDestroy(bind(mem_func, clone, _1, false), orig, clone, format);
3114 Buffer::ExportStatus GuiView::GuiViewPrivate::previewAndDestroy(Buffer const * orig, Buffer * clone, string const & format)
3116 Buffer::ExportStatus (Buffer::* mem_func)(std::string const &) const = &Buffer::preview;
3117 return runAndDestroy(bind(mem_func, clone, _1), orig, clone, format);
3122 // not used, but the linker needs them
3124 Buffer::ExportStatus GuiView::GuiViewPrivate::compileAndDestroy(
3125 Buffer const *, Buffer *, string const &)
3127 return Buffer::ExportSuccess;
3131 Buffer::ExportStatus GuiView::GuiViewPrivate::exportAndDestroy(
3132 Buffer const *, Buffer *, string const &)
3134 return Buffer::ExportSuccess;
3138 Buffer::ExportStatus GuiView::GuiViewPrivate::previewAndDestroy(
3139 Buffer const *, Buffer *, string const &)
3141 return Buffer::ExportSuccess;
3147 bool GuiView::GuiViewPrivate::asyncBufferProcessing(
3148 string const & argument,
3149 Buffer const * used_buffer,
3150 docstring const & msg,
3151 Buffer::ExportStatus (*asyncFunc)(Buffer const *, Buffer *, string const &),
3152 Buffer::ExportStatus (Buffer::*syncFunc)(string const &, bool) const,
3153 Buffer::ExportStatus (Buffer::*previewFunc)(string const &) const)
3158 string format = argument;
3160 format = used_buffer->params().getDefaultOutputFormat();
3161 processing_format = format;
3162 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
3164 progress_->clearMessages();
3167 GuiViewPrivate::busyBuffers.insert(used_buffer);
3168 Buffer * cloned_buffer = used_buffer->cloneFromMaster();
3169 if (!cloned_buffer) {
3170 Alert::error(_("Export Error"),
3171 _("Error cloning the Buffer."));
3174 QFuture<Buffer::ExportStatus> f = QtConcurrent::run(
3179 setPreviewFuture(f);
3180 last_export_format = used_buffer->params().bufferFormat();
3183 // We are asynchronous, so we don't know here anything about the success
3186 Buffer::ExportStatus status;
3188 // TODO check here if it breaks exporting with Qt < 4.4
3189 status = (used_buffer->*syncFunc)(format, true);
3190 } else if (previewFunc) {
3191 status = (used_buffer->*previewFunc)(format);
3194 handleExportStatus(gv_, status, format);
3196 return (status == Buffer::ExportSuccess
3197 || status == Buffer::PreviewSuccess);
3201 void GuiView::dispatchToBufferView(FuncRequest const & cmd, DispatchResult & dr)
3203 BufferView * bv = currentBufferView();
3206 // Let the current BufferView dispatch its own actions.
3207 bv->dispatch(cmd, dr);
3208 if (dr.dispatched())
3211 // Try with the document BufferView dispatch if any.
3212 BufferView * doc_bv = documentBufferView();
3213 if (doc_bv && doc_bv != bv) {
3214 doc_bv->dispatch(cmd, dr);
3215 if (dr.dispatched())
3219 // Then let the current Cursor dispatch its own actions.
3220 bv->cursor().dispatch(cmd);
3222 // update completion. We do it here and not in
3223 // processKeySym to avoid another redraw just for a
3224 // changed inline completion
3225 if (cmd.origin() == FuncRequest::KEYBOARD) {
3226 if (cmd.action() == LFUN_SELF_INSERT
3227 || (cmd.action() == LFUN_ERT_INSERT && bv->cursor().inMathed()))
3228 updateCompletion(bv->cursor(), true, true);
3229 else if (cmd.action() == LFUN_CHAR_DELETE_BACKWARD)
3230 updateCompletion(bv->cursor(), false, true);
3232 updateCompletion(bv->cursor(), false, false);
3235 dr = bv->cursor().result();
3239 void GuiView::dispatch(FuncRequest const & cmd, DispatchResult & dr)
3241 BufferView * bv = currentBufferView();
3242 // By default we won't need any update.
3243 dr.screenUpdate(Update::None);
3244 // assume cmd will be dispatched
3245 dr.dispatched(true);
3247 Buffer * doc_buffer = documentBufferView()
3248 ? &(documentBufferView()->buffer()) : 0;
3250 if (cmd.origin() == FuncRequest::TOC) {
3251 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
3252 // FIXME: do we need to pass a DispatchResult object here?
3253 toc->doDispatch(bv->cursor(), cmd);
3257 string const argument = to_utf8(cmd.argument());
3259 switch(cmd.action()) {
3260 case LFUN_BUFFER_CHILD_OPEN:
3261 openChildDocument(to_utf8(cmd.argument()));
3264 case LFUN_BUFFER_IMPORT:
3265 importDocument(to_utf8(cmd.argument()));
3268 case LFUN_BUFFER_EXPORT: {
3271 // GCC only sees strfwd.h when building merged
3272 if (::lyx::operator==(cmd.argument(), "custom")) {
3273 dispatch(FuncRequest(LFUN_DIALOG_SHOW, "sendto"), dr);
3276 #if QT_VERSION < 0x040400
3277 if (!doc_buffer->doExport(argument, false)) {
3279 dr.setMessage(bformat(_("Error exporting to format: %1$s"),
3283 /* TODO/Review: Is it a problem to also export the children?
3284 See the update_unincluded flag */
3285 d.asyncBufferProcessing(argument,
3288 &GuiViewPrivate::exportAndDestroy,
3291 // TODO Inform user about success
3296 case LFUN_BUFFER_EXPORT_AS:
3297 LASSERT(doc_buffer, break);
3298 exportBufferAs(*doc_buffer);
3301 case LFUN_BUFFER_UPDATE: {
3302 d.asyncBufferProcessing(argument,
3305 &GuiViewPrivate::compileAndDestroy,
3310 case LFUN_BUFFER_VIEW: {
3311 d.asyncBufferProcessing(argument,
3313 _("Previewing ..."),
3314 &GuiViewPrivate::previewAndDestroy,
3319 case LFUN_MASTER_BUFFER_UPDATE: {
3320 d.asyncBufferProcessing(argument,
3321 (doc_buffer ? doc_buffer->masterBuffer() : 0),
3323 &GuiViewPrivate::compileAndDestroy,
3328 case LFUN_MASTER_BUFFER_VIEW: {
3329 d.asyncBufferProcessing(argument,
3330 (doc_buffer ? doc_buffer->masterBuffer() : 0),
3332 &GuiViewPrivate::previewAndDestroy,
3333 0, &Buffer::preview);
3336 case LFUN_BUFFER_SWITCH: {
3337 string const file_name = to_utf8(cmd.argument());
3338 if (!FileName::isAbsolute(file_name)) {
3340 dr.setMessage(_("Absolute filename expected."));
3344 Buffer * buffer = theBufferList().getBuffer(FileName(file_name));
3347 dr.setMessage(_("Document not loaded"));
3351 // Do we open or switch to the buffer in this view ?
3352 if (workArea(*buffer)
3353 || lyxrc.open_buffers_in_tabs || !documentBufferView()) {
3358 // Look for the buffer in other views
3359 QList<int> const ids = guiApp->viewIds();
3361 for (; i != ids.size(); ++i) {
3362 GuiView & gv = guiApp->view(ids[i]);
3363 if (gv.workArea(*buffer)) {
3364 gv.activateWindow();
3365 gv.setBuffer(buffer);
3370 // If necessary, open a new window as a last resort
3371 if (i == ids.size()) {
3372 lyx::dispatch(FuncRequest(LFUN_WINDOW_NEW));
3378 case LFUN_BUFFER_NEXT:
3379 gotoNextOrPreviousBuffer(NEXTBUFFER);
3382 case LFUN_BUFFER_PREVIOUS:
3383 gotoNextOrPreviousBuffer(PREVBUFFER);
3386 case LFUN_COMMAND_EXECUTE: {
3387 bool const show_it = cmd.argument() != "off";
3388 // FIXME: this is a hack, "minibuffer" should not be
3390 if (GuiToolbar * t = toolbar("minibuffer")) {
3391 t->setVisible(show_it);
3392 if (show_it && t->commandBuffer())
3393 t->commandBuffer()->setFocus();
3397 case LFUN_DROP_LAYOUTS_CHOICE:
3398 d.layout_->showPopup();
3401 case LFUN_MENU_OPEN:
3402 if (QMenu * menu = guiApp->menus().menu(toqstr(cmd.argument()), *this))
3403 menu->exec(QCursor::pos());
3406 case LFUN_FILE_INSERT:
3407 insertLyXFile(cmd.argument());
3410 case LFUN_FILE_INSERT_PLAINTEXT:
3411 case LFUN_FILE_INSERT_PLAINTEXT_PARA: {
3412 bool const as_paragraph = (cmd.action() == LFUN_FILE_INSERT_PLAINTEXT_PARA);
3413 string const fname = to_utf8(cmd.argument());
3414 if (!fname.empty() && !FileName::isAbsolute(fname)) {
3415 dr.setMessage(_("Absolute filename expected."));
3419 FileName filename(fname);
3420 if (fname.empty()) {
3421 FileDialog dlg(qt_("Select file to insert"), (as_paragraph ?
3422 LFUN_FILE_INSERT_PLAINTEXT_PARA : LFUN_FILE_INSERT_PLAINTEXT));
3424 FileDialog::Result result = dlg.open(toqstr(bv->buffer().filePath()),
3425 QStringList(qt_("All Files (*)")));
3427 if (result.first == FileDialog::Later || result.second.isEmpty()) {
3428 dr.setMessage(_("Canceled."));
3432 filename.set(fromqstr(result.second));
3436 FuncRequest const new_cmd(cmd, filename.absoluteFilePath());
3437 bv->dispatch(new_cmd, dr);
3442 case LFUN_BUFFER_RELOAD: {
3443 LASSERT(doc_buffer, break);
3446 if (!doc_buffer->isClean()) {
3447 docstring const file =
3448 makeDisplayPath(doc_buffer->absFileName(), 20);
3449 docstring text = bformat(_("Any changes will be lost. "
3450 "Are you sure you want to revert to the saved version "
3451 "of the document %1$s?"), file);
3452 ret = Alert::prompt(_("Revert to saved document?"),
3453 text, 1, 1, _("&Revert"), _("&Cancel"));
3457 doc_buffer->markClean();
3458 reloadBuffer(*doc_buffer);
3459 dr.forceBufferUpdate();
3464 case LFUN_BUFFER_WRITE:
3465 LASSERT(doc_buffer, break);
3466 saveBuffer(*doc_buffer);
3469 case LFUN_BUFFER_WRITE_AS:
3470 LASSERT(doc_buffer, break);
3471 renameBuffer(*doc_buffer, cmd.argument());
3474 case LFUN_BUFFER_WRITE_ALL: {
3475 Buffer * first = theBufferList().first();
3478 message(_("Saving all documents..."));
3479 // We cannot use a for loop as the buffer list cycles.
3482 if (!b->isClean()) {
3484 LYXERR(Debug::ACTION, "Saved " << b->absFileName());
3486 b = theBufferList().next(b);
3487 } while (b != first);
3488 dr.setMessage(_("All documents saved."));
3492 case LFUN_BUFFER_CLOSE:
3496 case LFUN_BUFFER_CLOSE_ALL:
3500 case LFUN_TOOLBAR_TOGGLE: {
3501 string const name = cmd.getArg(0);
3502 if (GuiToolbar * t = toolbar(name))
3507 case LFUN_DIALOG_UPDATE: {
3508 string const name = to_utf8(cmd.argument());
3509 if (name == "prefs" || name == "document")
3510 updateDialog(name, string());
3511 else if (name == "paragraph")
3512 lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
3513 else if (currentBufferView()) {
3514 Inset * inset = currentBufferView()->editedInset(name);
3515 // Can only update a dialog connected to an existing inset
3517 // FIXME: get rid of this indirection; GuiView ask the inset
3518 // if he is kind enough to update itself...
3519 FuncRequest fr(LFUN_INSET_DIALOG_UPDATE, cmd.argument());
3520 //FIXME: pass DispatchResult here?
3521 inset->dispatch(currentBufferView()->cursor(), fr);
3527 case LFUN_DIALOG_TOGGLE: {
3528 FuncCode const func_code = isDialogVisible(cmd.getArg(0))
3529 ? LFUN_DIALOG_HIDE : LFUN_DIALOG_SHOW;
3530 dispatch(FuncRequest(func_code, cmd.argument()), dr);
3534 case LFUN_DIALOG_DISCONNECT_INSET:
3535 disconnectDialog(to_utf8(cmd.argument()));
3538 case LFUN_DIALOG_HIDE: {
3539 guiApp->hideDialogs(to_utf8(cmd.argument()), 0);
3543 case LFUN_DIALOG_SHOW: {
3544 string const name = cmd.getArg(0);
3545 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
3547 if (name == "character") {
3548 data = freefont2string();
3550 showDialog("character", data);
3551 } else if (name == "latexlog") {
3552 Buffer::LogType type;
3553 string const logfile = doc_buffer->logName(&type);
3555 case Buffer::latexlog:
3558 case Buffer::buildlog:
3562 data += Lexer::quoteString(logfile);
3563 showDialog("log", data);
3564 } else if (name == "vclog") {
3565 string const data = "vc " +
3566 Lexer::quoteString(doc_buffer->lyxvc().getLogFile());
3567 showDialog("log", data);
3568 } else if (name == "symbols") {
3569 data = bv->cursor().getEncoding()->name();
3571 showDialog("symbols", data);
3573 } else if (name == "prefs" && isFullScreen()) {
3574 lfunUiToggle("fullscreen");
3575 showDialog("prefs", data);
3577 showDialog(name, data);
3582 dr.setMessage(cmd.argument());
3585 case LFUN_UI_TOGGLE: {
3586 string arg = cmd.getArg(0);
3587 if (!lfunUiToggle(arg)) {
3588 docstring const msg = "ui-toggle " + _("%1$s unknown command!");
3589 dr.setMessage(bformat(msg, from_utf8(arg)));
3591 // Make sure the keyboard focus stays in the work area.
3596 case LFUN_SPLIT_VIEW: {
3597 LASSERT(doc_buffer, break);
3598 string const orientation = cmd.getArg(0);
3599 d.splitter_->setOrientation(orientation == "vertical"
3600 ? Qt::Vertical : Qt::Horizontal);
3601 TabWorkArea * twa = addTabWorkArea();
3602 GuiWorkArea * wa = twa->addWorkArea(*doc_buffer, *this);
3603 setCurrentWorkArea(wa);
3606 case LFUN_CLOSE_TAB_GROUP:
3607 if (TabWorkArea * twa = d.currentTabWorkArea()) {
3608 closeTabWorkArea(twa);
3609 d.current_work_area_ = 0;
3610 twa = d.currentTabWorkArea();
3611 // Switch to the next GuiWorkArea in the found TabWorkArea.
3613 // Make sure the work area is up to date.
3614 setCurrentWorkArea(twa->currentWorkArea());
3616 setCurrentWorkArea(0);
3621 case LFUN_VIEW_CLOSE:
3622 if (TabWorkArea * twa = d.currentTabWorkArea()) {
3623 closeWorkArea(twa->currentWorkArea());
3624 d.current_work_area_ = 0;
3625 twa = d.currentTabWorkArea();
3626 // Switch to the next GuiWorkArea in the found TabWorkArea.
3628 // Make sure the work area is up to date.
3629 setCurrentWorkArea(twa->currentWorkArea());
3631 setCurrentWorkArea(0);
3636 case LFUN_COMPLETION_INLINE:
3637 if (d.current_work_area_)
3638 d.current_work_area_->completer().showInline();
3641 case LFUN_COMPLETION_POPUP:
3642 if (d.current_work_area_)
3643 d.current_work_area_->completer().showPopup();
3647 case LFUN_COMPLETION_COMPLETE:
3648 if (d.current_work_area_)
3649 d.current_work_area_->completer().tab();
3652 case LFUN_COMPLETION_CANCEL:
3653 if (d.current_work_area_) {
3654 if (d.current_work_area_->completer().popupVisible())
3655 d.current_work_area_->completer().hidePopup();
3657 d.current_work_area_->completer().hideInline();
3661 case LFUN_COMPLETION_ACCEPT:
3662 if (d.current_work_area_)
3663 d.current_work_area_->completer().activate();
3666 case LFUN_BUFFER_ZOOM_IN:
3667 case LFUN_BUFFER_ZOOM_OUT:
3668 if (cmd.argument().empty()) {
3669 if (cmd.action() == LFUN_BUFFER_ZOOM_IN)
3674 lyxrc.zoom += convert<int>(cmd.argument());
3676 if (lyxrc.zoom < 10)
3679 // The global QPixmapCache is used in GuiPainter to cache text
3680 // painting so we must reset it.
3681 QPixmapCache::clear();
3682 guiApp->fontLoader().update();
3683 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
3686 case LFUN_VC_REGISTER:
3687 case LFUN_VC_CHECK_IN:
3688 case LFUN_VC_CHECK_OUT:
3689 case LFUN_VC_REPO_UPDATE:
3690 case LFUN_VC_LOCKING_TOGGLE:
3691 case LFUN_VC_REVERT:
3692 case LFUN_VC_UNDO_LAST:
3693 case LFUN_VC_COMMAND:
3694 case LFUN_VC_COMPARE:
3695 dispatchVC(cmd, dr);
3698 case LFUN_SERVER_GOTO_FILE_ROW:
3699 goToFileRow(to_utf8(cmd.argument()));
3702 case LFUN_FORWARD_SEARCH: {
3703 Buffer const * doc_master = doc_buffer->masterBuffer();
3704 FileName const path(doc_master->temppath());
3705 string const texname = doc_master->isChild(doc_buffer)
3706 ? DocFileName(changeExtension(
3707 doc_buffer->absFileName(),
3708 "tex")).mangledFileName()
3709 : doc_buffer->latexName();
3710 string const fulltexname =
3711 support::makeAbsPath(texname, doc_master->temppath()).absFileName();
3712 string const mastername =
3713 removeExtension(doc_master->latexName());
3714 FileName const dviname(addName(path.absFileName(),
3715 addExtension(mastername, "dvi")));
3716 FileName const pdfname(addName(path.absFileName(),
3717 addExtension(mastername, "pdf")));
3718 bool const have_dvi = dviname.exists();
3719 bool const have_pdf = pdfname.exists();
3720 if (!have_dvi && !have_pdf) {
3721 dr.setMessage(_("Please, preview the document first."));
3724 string outname = dviname.onlyFileName();
3725 string command = lyxrc.forward_search_dvi;
3726 if (!have_dvi || (have_pdf &&
3727 pdfname.lastModified() > dviname.lastModified())) {
3728 outname = pdfname.onlyFileName();
3729 command = lyxrc.forward_search_pdf;
3732 DocIterator tmpcur = bv->cursor();
3734 while (tmpcur.inMathed())
3736 int row = tmpcur.inMathed() ? 0 : doc_buffer->texrow().getRowFromIdPos(
3737 tmpcur.paragraph().id(), tmpcur.pos());
3738 LYXERR(Debug::ACTION, "Forward search: row:" << row
3739 << " id:" << tmpcur.paragraph().id());
3740 if (!row || command.empty()) {
3741 dr.setMessage(_("Couldn't proceed."));
3744 string texrow = convert<string>(row);
3746 command = subst(command, "$$n", texrow);
3747 command = subst(command, "$$f", fulltexname);
3748 command = subst(command, "$$t", texname);
3749 command = subst(command, "$$o", outname);
3751 PathChanger p(path);
3753 one.startscript(Systemcall::DontWait, command);
3757 // The LFUN must be for one of BufferView, Buffer or Cursor;
3759 dispatchToBufferView(cmd, dr);
3763 // Part of automatic menu appearance feature.
3764 if (isFullScreen()) {
3765 if (menuBar()->isVisible() && lyxrc.full_screen_menubar)
3767 if (statusBar()->isVisible())
3768 statusBar()->hide();
3773 bool GuiView::lfunUiToggle(string const & ui_component)
3775 if (ui_component == "scrollbar") {
3776 // hide() is of no help
3777 if (d.current_work_area_->verticalScrollBarPolicy() ==
3778 Qt::ScrollBarAlwaysOff)
3780 d.current_work_area_->setVerticalScrollBarPolicy(
3781 Qt::ScrollBarAsNeeded);
3783 d.current_work_area_->setVerticalScrollBarPolicy(
3784 Qt::ScrollBarAlwaysOff);
3785 } else if (ui_component == "statusbar") {
3786 statusBar()->setVisible(!statusBar()->isVisible());
3787 } else if (ui_component == "menubar") {
3788 menuBar()->setVisible(!menuBar()->isVisible());
3790 #if QT_VERSION >= 0x040300
3791 if (ui_component == "frame") {
3793 getContentsMargins(&l, &t, &r, &b);
3794 //are the frames in default state?
3795 d.current_work_area_->setFrameStyle(QFrame::NoFrame);
3797 setContentsMargins(-2, -2, -2, -2);
3799 setContentsMargins(0, 0, 0, 0);
3803 if (ui_component == "fullscreen") {
3811 void GuiView::toggleFullScreen()
3813 if (isFullScreen()) {
3814 for (int i = 0; i != d.splitter_->count(); ++i)
3815 d.tabWorkArea(i)->setFullScreen(false);
3816 #if QT_VERSION >= 0x040300
3817 setContentsMargins(0, 0, 0, 0);
3819 setWindowState(windowState() ^ Qt::WindowFullScreen);
3822 statusBar()->show();
3825 hideDialogs("prefs", 0);
3826 for (int i = 0; i != d.splitter_->count(); ++i)
3827 d.tabWorkArea(i)->setFullScreen(true);
3828 #if QT_VERSION >= 0x040300
3829 setContentsMargins(-2, -2, -2, -2);
3832 setWindowState(windowState() ^ Qt::WindowFullScreen);
3833 statusBar()->hide();
3834 if (lyxrc.full_screen_menubar)
3836 if (lyxrc.full_screen_toolbars) {
3837 ToolbarMap::iterator end = d.toolbars_.end();
3838 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
3843 // give dialogs like the TOC a chance to adapt
3848 Buffer const * GuiView::updateInset(Inset const * inset)
3853 Buffer const * inset_buffer = &(inset->buffer());
3855 for (int i = 0; i != d.splitter_->count(); ++i) {
3856 GuiWorkArea * wa = d.tabWorkArea(i)->currentWorkArea();
3859 Buffer const * buffer = &(wa->bufferView().buffer());
3860 if (inset_buffer == buffer)
3861 wa->scheduleRedraw();
3863 return inset_buffer;
3867 void GuiView::restartCursor()
3869 /* When we move around, or type, it's nice to be able to see
3870 * the cursor immediately after the keypress.
3872 if (d.current_work_area_)
3873 d.current_work_area_->startBlinkingCursor();
3875 // Take this occasion to update the other GUI elements.
3881 void GuiView::updateCompletion(Cursor & cur, bool start, bool keep)
3883 if (d.current_work_area_)
3884 d.current_work_area_->completer().updateVisibility(cur, start, keep);
3889 // This list should be kept in sync with the list of insets in
3890 // src/insets/Inset.cpp. I.e., if a dialog goes with an inset, the
3891 // dialog should have the same name as the inset.
3892 // Changes should be also recorded in LFUN_DIALOG_SHOW doxygen
3893 // docs in LyXAction.cpp.
3895 char const * const dialognames[] = {
3897 "aboutlyx", "bibitem", "bibtex", "box", "branch", "changes", "character",
3898 "citation", "compare", "comparehistory", "document", "errorlist", "ert",
3899 "external", "file", "findreplace", "findreplaceadv", "float", "graphics",
3900 "href", "include", "index", "index_print", "info", "listings", "label", "line",
3901 "log", "mathdelimiter", "mathmatrix", "mathspace", "nomenclature",
3902 "nomencl_print", "note", "paragraph", "phantom", "prefs", "print", "ref",
3903 "sendto", "space", "spellchecker", "symbols", "tabular", "tabularcreate",
3904 "thesaurus", "texinfo", "toc", "view-source", "vspace", "wrap", "progress"};
3906 char const * const * const end_dialognames =
3907 dialognames + (sizeof(dialognames) / sizeof(char *));
3911 cmpCStr(char const * name) : name_(name) {}
3912 bool operator()(char const * other) {
3913 return strcmp(other, name_) == 0;
3920 bool isValidName(string const & name)
3922 return find_if(dialognames, end_dialognames,
3923 cmpCStr(name.c_str())) != end_dialognames;
3929 void GuiView::resetDialogs()
3931 // Make sure that no LFUN uses any GuiView.
3932 guiApp->setCurrentView(0);
3936 constructToolbars();
3937 guiApp->menus().fillMenuBar(menuBar(), this, false);
3938 d.layout_->updateContents(true);
3939 // Now update controls with current buffer.
3940 guiApp->setCurrentView(this);
3946 Dialog * GuiView::findOrBuild(string const & name, bool hide_it)
3948 if (!isValidName(name))
3951 map<string, DialogPtr>::iterator it = d.dialogs_.find(name);
3953 if (it != d.dialogs_.end()) {
3955 it->second->hideView();
3956 return it->second.get();
3959 Dialog * dialog = build(name);
3960 d.dialogs_[name].reset(dialog);
3961 if (lyxrc.allow_geometry_session)
3962 dialog->restoreSession();
3969 void GuiView::showDialog(string const & name, string const & data,
3972 triggerShowDialog(toqstr(name), toqstr(data), inset);
3976 void GuiView::doShowDialog(QString const & qname, QString const & qdata,
3982 const string name = fromqstr(qname);
3983 const string data = fromqstr(qdata);
3987 Dialog * dialog = findOrBuild(name, false);
3989 bool const visible = dialog->isVisibleView();
3990 dialog->showData(data);
3991 if (inset && currentBufferView())
3992 currentBufferView()->editInset(name, inset);
3993 // We only set the focus to the new dialog if it was not yet
3994 // visible in order not to change the existing previous behaviour
3996 // activateWindow is needed for floating dockviews
3997 dialog->asQWidget()->raise();
3998 dialog->asQWidget()->activateWindow();
3999 dialog->asQWidget()->setFocus();
4003 catch (ExceptionMessage const & ex) {
4011 bool GuiView::isDialogVisible(string const & name) const
4013 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
4014 if (it == d.dialogs_.end())
4016 return it->second.get()->isVisibleView() && !it->second.get()->isClosing();
4020 void GuiView::hideDialog(string const & name, Inset * inset)
4022 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
4023 if (it == d.dialogs_.end())
4027 if (!currentBufferView())
4029 if (inset != currentBufferView()->editedInset(name))
4033 Dialog * const dialog = it->second.get();
4034 if (dialog->isVisibleView())
4036 if (currentBufferView())
4037 currentBufferView()->editInset(name, 0);
4041 void GuiView::disconnectDialog(string const & name)
4043 if (!isValidName(name))
4045 if (currentBufferView())
4046 currentBufferView()->editInset(name, 0);
4050 void GuiView::hideAll() const
4052 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
4053 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
4055 for(; it != end; ++it)
4056 it->second->hideView();
4060 void GuiView::updateDialogs()
4062 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
4063 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
4065 for(; it != end; ++it) {
4066 Dialog * dialog = it->second.get();
4068 if (dialog->needBufferOpen() && !documentBufferView())
4069 hideDialog(fromqstr(dialog->name()), 0);
4070 else if (dialog->isVisibleView())
4071 dialog->checkStatus();
4078 Dialog * createDialog(GuiView & lv, string const & name);
4080 // will be replaced by a proper factory...
4081 Dialog * createGuiAbout(GuiView & lv);
4082 Dialog * createGuiBibtex(GuiView & lv);
4083 Dialog * createGuiChanges(GuiView & lv);
4084 Dialog * createGuiCharacter(GuiView & lv);
4085 Dialog * createGuiCitation(GuiView & lv);
4086 Dialog * createGuiCompare(GuiView & lv);
4087 Dialog * createGuiCompareHistory(GuiView & lv);
4088 Dialog * createGuiDelimiter(GuiView & lv);
4089 Dialog * createGuiDocument(GuiView & lv);
4090 Dialog * createGuiErrorList(GuiView & lv);
4091 Dialog * createGuiExternal(GuiView & lv);
4092 Dialog * createGuiGraphics(GuiView & lv);
4093 Dialog * createGuiInclude(GuiView & lv);
4094 Dialog * createGuiIndex(GuiView & lv);
4095 Dialog * createGuiListings(GuiView & lv);
4096 Dialog * createGuiLog(GuiView & lv);
4097 Dialog * createGuiMathMatrix(GuiView & lv);
4098 Dialog * createGuiNote(GuiView & lv);
4099 Dialog * createGuiParagraph(GuiView & lv);
4100 Dialog * createGuiPhantom(GuiView & lv);
4101 Dialog * createGuiPreferences(GuiView & lv);
4102 Dialog * createGuiPrint(GuiView & lv);
4103 Dialog * createGuiPrintindex(GuiView & lv);
4104 Dialog * createGuiRef(GuiView & lv);
4105 Dialog * createGuiSearch(GuiView & lv);
4106 Dialog * createGuiSearchAdv(GuiView & lv);
4107 Dialog * createGuiSendTo(GuiView & lv);
4108 Dialog * createGuiShowFile(GuiView & lv);
4109 Dialog * createGuiSpellchecker(GuiView & lv);
4110 Dialog * createGuiSymbols(GuiView & lv);
4111 Dialog * createGuiTabularCreate(GuiView & lv);
4112 Dialog * createGuiTexInfo(GuiView & lv);
4113 Dialog * createGuiToc(GuiView & lv);
4114 Dialog * createGuiThesaurus(GuiView & lv);
4115 Dialog * createGuiViewSource(GuiView & lv);
4116 Dialog * createGuiWrap(GuiView & lv);
4117 Dialog * createGuiProgressView(GuiView & lv);
4121 Dialog * GuiView::build(string const & name)
4123 LASSERT(isValidName(name), return 0);
4125 Dialog * dialog = createDialog(*this, name);
4129 if (name == "aboutlyx")
4130 return createGuiAbout(*this);
4131 if (name == "bibtex")
4132 return createGuiBibtex(*this);
4133 if (name == "changes")
4134 return createGuiChanges(*this);
4135 if (name == "character")
4136 return createGuiCharacter(*this);
4137 if (name == "citation")
4138 return createGuiCitation(*this);
4139 if (name == "compare")
4140 return createGuiCompare(*this);
4141 if (name == "comparehistory")
4142 return createGuiCompareHistory(*this);
4143 if (name == "document")
4144 return createGuiDocument(*this);
4145 if (name == "errorlist")
4146 return createGuiErrorList(*this);
4147 if (name == "external")
4148 return createGuiExternal(*this);
4150 return createGuiShowFile(*this);
4151 if (name == "findreplace")
4152 return createGuiSearch(*this);
4153 if (name == "findreplaceadv")
4154 return createGuiSearchAdv(*this);
4155 if (name == "graphics")
4156 return createGuiGraphics(*this);
4157 if (name == "include")
4158 return createGuiInclude(*this);
4159 if (name == "index")
4160 return createGuiIndex(*this);
4161 if (name == "index_print")
4162 return createGuiPrintindex(*this);
4163 if (name == "listings")
4164 return createGuiListings(*this);
4166 return createGuiLog(*this);
4167 if (name == "mathdelimiter")
4168 return createGuiDelimiter(*this);
4169 if (name == "mathmatrix")
4170 return createGuiMathMatrix(*this);
4172 return createGuiNote(*this);
4173 if (name == "paragraph")
4174 return createGuiParagraph(*this);
4175 if (name == "phantom")
4176 return createGuiPhantom(*this);
4177 if (name == "prefs")
4178 return createGuiPreferences(*this);
4179 if (name == "print")
4180 return createGuiPrint(*this);
4182 return createGuiRef(*this);
4183 if (name == "sendto")
4184 return createGuiSendTo(*this);
4185 if (name == "spellchecker")
4186 return createGuiSpellchecker(*this);
4187 if (name == "symbols")
4188 return createGuiSymbols(*this);
4189 if (name == "tabularcreate")
4190 return createGuiTabularCreate(*this);
4191 if (name == "texinfo")
4192 return createGuiTexInfo(*this);
4193 if (name == "thesaurus")
4194 return createGuiThesaurus(*this);
4196 return createGuiToc(*this);
4197 if (name == "view-source")
4198 return createGuiViewSource(*this);
4200 return createGuiWrap(*this);
4201 if (name == "progress")
4202 return createGuiProgressView(*this);
4208 } // namespace frontend
4211 #include "moc_GuiView.cpp"