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 = 22; // 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 FileName const fn = lyx::libFileSearch("images", "iconsize.png");
221 QImage image(toqstr(fn.absFileName()));
222 if (image.width() < int(smallIconSize))
223 normalIconSize = smallIconSize;
224 else if (image.width() > int(bigIconSize))
225 normalIconSize = bigIconSize;
227 normalIconSize = image.width();
230 splitter_ = new QSplitter;
231 bg_widget_ = new BackgroundWidget;
232 stack_widget_ = new QStackedWidget;
233 stack_widget_->addWidget(bg_widget_);
234 stack_widget_->addWidget(splitter_);
237 // TODO cleanup, remove the singleton, handle multiple Windows?
238 progress_ = ProgressInterface::instance();
239 if (!dynamic_cast<GuiProgress*>(progress_)) {
240 progress_ = new GuiProgress(); // TODO who deletes it
241 ProgressInterface::setInstance(progress_);
244 dynamic_cast<GuiProgress*>(progress_),
245 SIGNAL(updateStatusBarMessage(QString const&)),
246 gv, SLOT(updateStatusBarMessage(QString const&)));
248 dynamic_cast<GuiProgress*>(progress_),
249 SIGNAL(clearMessageText()),
250 gv, SLOT(clearMessageText()));
257 delete stack_widget_;
260 QMenu * toolBarPopup(GuiView * parent)
262 // FIXME: translation
263 QMenu * menu = new QMenu(parent);
264 QActionGroup * iconSizeGroup = new QActionGroup(parent);
266 QAction * smallIcons = new QAction(iconSizeGroup);
267 smallIcons->setText(qt_("Small-sized icons"));
268 smallIcons->setCheckable(true);
269 QObject::connect(smallIcons, SIGNAL(triggered()),
270 parent, SLOT(smallSizedIcons()));
271 menu->addAction(smallIcons);
273 QAction * normalIcons = new QAction(iconSizeGroup);
274 normalIcons->setText(qt_("Normal-sized icons"));
275 normalIcons->setCheckable(true);
276 QObject::connect(normalIcons, SIGNAL(triggered()),
277 parent, SLOT(normalSizedIcons()));
278 menu->addAction(normalIcons);
280 QAction * bigIcons = new QAction(iconSizeGroup);
281 bigIcons->setText(qt_("Big-sized icons"));
282 bigIcons->setCheckable(true);
283 QObject::connect(bigIcons, SIGNAL(triggered()),
284 parent, SLOT(bigSizedIcons()));
285 menu->addAction(bigIcons);
287 unsigned int cur = parent->iconSize().width();
288 if ( cur == parent->d.smallIconSize)
289 smallIcons->setChecked(true);
290 else if (cur == parent->d.normalIconSize)
291 normalIcons->setChecked(true);
292 else if (cur == parent->d.bigIconSize)
293 bigIcons->setChecked(true);
300 stack_widget_->setCurrentWidget(bg_widget_);
301 bg_widget_->setUpdatesEnabled(true);
302 bg_widget_->setFocus();
305 int tabWorkAreaCount()
307 return splitter_->count();
310 TabWorkArea * tabWorkArea(int i)
312 return dynamic_cast<TabWorkArea *>(splitter_->widget(i));
315 TabWorkArea * currentTabWorkArea()
317 int areas = tabWorkAreaCount();
319 // The first TabWorkArea is always the first one, if any.
320 return tabWorkArea(0);
322 for (int i = 0; i != areas; ++i) {
323 TabWorkArea * twa = tabWorkArea(i);
324 if (current_main_work_area_ == twa->currentWorkArea())
328 // None has the focus so we just take the first one.
329 return tabWorkArea(0);
332 #if (QT_VERSION >= 0x040400)
333 void setPreviewFuture(QFuture<docstring> const & f)
335 if (processing_thread_watcher_.isRunning()) {
336 // we prefer to cancel this preview in order to keep a snappy
340 processing_thread_watcher_.setFuture(f);
346 GuiWorkArea * current_work_area_;
347 GuiWorkArea * current_main_work_area_;
348 QSplitter * splitter_;
349 QStackedWidget * stack_widget_;
350 BackgroundWidget * bg_widget_;
352 ToolbarMap toolbars_;
353 ProgressInterface* progress_;
354 /// The main layout box.
356 * \warning Don't Delete! The layout box is actually owned by
357 * whichever toolbar contains it. All the GuiView class needs is a
358 * means of accessing it.
360 * FIXME: replace that with a proper model so that we are not limited
361 * to only one dialog.
366 map<string, DialogPtr> dialogs_;
368 unsigned int smallIconSize;
369 unsigned int normalIconSize;
370 unsigned int bigIconSize;
372 QTimer statusbar_timer_;
373 /// auto-saving of buffers
374 Timeout autosave_timeout_;
375 /// flag against a race condition due to multiclicks, see bug #1119
379 TocModels toc_models_;
381 #if (QT_VERSION >= 0x040400)
383 QFutureWatcher<docstring> autosave_watcher_;
384 QFutureWatcher<docstring> processing_thread_watcher_;
386 string last_export_format;
388 struct DummyWatcher { bool isRunning(){return false;} };
389 DummyWatcher processing_thread_watcher_;
392 static QSet<Buffer const *> busyBuffers;
393 static docstring previewAndDestroy(Buffer const * orig, Buffer * buffer, string const & format);
394 static docstring exportAndDestroy(Buffer const * orig, Buffer * buffer, string const & format);
395 static docstring compileAndDestroy(Buffer const * orig, Buffer * buffer, string const & format);
396 static docstring autosaveAndDestroy(Buffer const * orig, Buffer * buffer);
399 static docstring runAndDestroy(const T& func, Buffer const * orig, Buffer * buffer, string const & format, string const & msg);
401 // TODO syncFunc/previewFunc: use bind
402 bool asyncBufferProcessing(string const & argument,
403 Buffer const * used_buffer,
404 docstring const & msg,
405 docstring (*asyncFunc)(Buffer const *, Buffer *, string const &),
406 bool (Buffer::*syncFunc)(string const &, bool, bool) const,
407 bool (Buffer::*previewFunc)(string const &, bool) const);
409 QVector<GuiWorkArea*> guiWorkAreas();
412 QSet<Buffer const *> GuiView::GuiViewPrivate::busyBuffers;
415 GuiView::GuiView(int id)
416 : d(*new GuiViewPrivate(this)), id_(id), closing_(false), busy_(0)
418 // GuiToolbars *must* be initialised before the menu bar.
419 normalSizedIcons(); // at least on Mac the default is 32 otherwise, which is huge
422 // set ourself as the current view. This is needed for the menu bar
423 // filling, at least for the static special menu item on Mac. Otherwise
424 // they are greyed out.
425 guiApp->setCurrentView(this);
427 // Fill up the menu bar.
428 guiApp->menus().fillMenuBar(menuBar(), this, true);
430 setCentralWidget(d.stack_widget_);
432 // Start autosave timer
433 if (lyxrc.autosave) {
434 d.autosave_timeout_.timeout.connect(bind(&GuiView::autoSave, this));
435 d.autosave_timeout_.setTimeout(lyxrc.autosave * 1000);
436 d.autosave_timeout_.start();
438 connect(&d.statusbar_timer_, SIGNAL(timeout()),
439 this, SLOT(clearMessage()));
441 // We don't want to keep the window in memory if it is closed.
442 setAttribute(Qt::WA_DeleteOnClose, true);
444 #if (!defined(Q_WS_WIN) && !defined(Q_WS_MACX))
445 // assign an icon to main form. We do not do it under Qt/Win or Qt/Mac,
446 // since the icon is provided in the application bundle.
447 setWindowIcon(getPixmap("images/", "lyx", "png"));
450 #if (QT_VERSION >= 0x040300)
451 // use tabbed dock area for multiple docks
452 // (such as "source" and "messages")
453 setDockOptions(QMainWindow::ForceTabbedDocks);
457 setAcceptDrops(true);
459 #if (QT_VERSION >= 0x040400)
461 // add busy indicator to statusbar
462 QLabel * busylabel = new QLabel(statusBar());
463 statusBar()->addPermanentWidget(busylabel);
464 QString fn = toqstr(lyx::libFileSearch("images", "busy.gif").absFileName());
465 QMovie * busyanim = new QMovie(fn, QByteArray(), busylabel);
466 busylabel->setMovie(busyanim);
470 connect(&d.processing_thread_watcher_, SIGNAL(started()),
471 busylabel, SLOT(show()));
472 connect(&d.processing_thread_watcher_, SIGNAL(finished()),
473 busylabel, SLOT(hide()));
475 statusBar()->setSizeGripEnabled(true);
478 connect(&d.autosave_watcher_, SIGNAL(finished()), this,
479 SLOT(autoSaveThreadFinished()));
481 connect(&d.processing_thread_watcher_, SIGNAL(started()), this,
482 SLOT(processingThreadStarted()));
483 connect(&d.processing_thread_watcher_, SIGNAL(finished()), this,
484 SLOT(processingThreadFinished()));
488 connect(this, SIGNAL(triggerShowDialog(QString const &, QString const &, Inset *)),
489 SLOT(doShowDialog(QString const &, QString const &, Inset *)));
491 // Forbid too small unresizable window because it can happen
492 // with some window manager under X11.
493 setMinimumSize(300, 200);
495 if (lyxrc.allow_geometry_session) {
496 // Now take care of session management.
501 // no session handling, default to a sane size.
502 setGeometry(50, 50, 690, 510);
505 // clear session data if any.
507 settings.remove("views");
517 QVector<GuiWorkArea*> GuiView::GuiViewPrivate::guiWorkAreas()
519 QVector<GuiWorkArea*> areas;
520 for (int i = 0; i < tabWorkAreaCount(); i++) {
521 TabWorkArea* ta = tabWorkArea(i);
522 for (int u = 0; u < ta->count(); u++) {
523 areas << ta->workArea(u);
530 #if QT_VERSION >= 0x040400
532 void GuiView::processingThreadStarted()
537 void GuiView::processingThreadFinished(bool show_errors)
539 QFutureWatcher<docstring> const * watcher =
540 static_cast<QFutureWatcher<docstring> const *>(sender());
541 message(watcher->result());
544 BufferView const * const bv = currentBufferView();
545 if (bv && !bv->buffer().errorList("Export").empty()) {
549 errors(d.last_export_format);
554 void GuiView::processingThreadFinished()
556 processingThreadFinished(true);
560 void GuiView::autoSaveThreadFinished()
562 processingThreadFinished(false);
568 void GuiView::processingThreadStarted()
573 void GuiView::processingThreadFinished(bool)
578 void GuiView::processingThreadFinished()
583 void GuiView::autoSaveThreadFinished()
589 void GuiView::saveLayout() const
592 settings.beginGroup("views");
593 settings.beginGroup(QString::number(id_));
595 settings.setValue("pos", pos());
596 settings.setValue("size", size());
598 settings.setValue("geometry", saveGeometry());
600 settings.setValue("layout", saveState(0));
601 settings.setValue("icon_size", iconSize());
605 void GuiView::saveUISettings() const
607 // Save the toolbar private states
608 ToolbarMap::iterator end = d.toolbars_.end();
609 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
610 it->second->saveSession();
611 // Now take care of all other dialogs
612 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
613 for (; it!= d.dialogs_.end(); ++it)
614 it->second->saveSession();
618 bool GuiView::restoreLayout()
621 settings.beginGroup("views");
622 settings.beginGroup(QString::number(id_));
623 QString const icon_key = "icon_size";
624 if (!settings.contains(icon_key))
627 //code below is skipped when when ~/.config/LyX is (re)created
628 setIconSize(settings.value(icon_key).toSize());
630 QPoint pos = settings.value("pos", QPoint(50, 50)).toPoint();
631 QSize size = settings.value("size", QSize(690, 510)).toSize();
635 // Work-around for bug #6034: the window ends up in an undetermined
636 // state when trying to restore a maximized window when it is
637 // already maximized.
638 if (!(windowState() & Qt::WindowMaximized))
639 if (!restoreGeometry(settings.value("geometry").toByteArray()))
640 setGeometry(50, 50, 690, 510);
642 // Make sure layout is correctly oriented.
643 setLayoutDirection(qApp->layoutDirection());
645 // Allow the toc and view-source dock widget to be restored if needed.
647 if ((dialog = findOrBuild("toc", true)))
648 // see bug 5082. At least setup title and enabled state.
649 // Visibility will be adjusted by restoreState below.
650 dialog->prepareView();
651 if ((dialog = findOrBuild("view-source", true)))
652 dialog->prepareView();
653 if ((dialog = findOrBuild("progress", true)))
654 dialog->prepareView();
655 if ((dialog = findOrBuild("findreplaceadv", true)))
656 dialog->prepareView();
658 if (!restoreState(settings.value("layout").toByteArray(), 0))
665 GuiToolbar * GuiView::toolbar(string const & name)
667 ToolbarMap::iterator it = d.toolbars_.find(name);
668 if (it != d.toolbars_.end())
671 LYXERR(Debug::GUI, "Toolbar::display: no toolbar named " << name);
676 void GuiView::constructToolbars()
678 ToolbarMap::iterator it = d.toolbars_.begin();
679 for (; it != d.toolbars_.end(); ++it)
683 // I don't like doing this here, but the standard toolbar
684 // destroys this object when it's destroyed itself (vfr)
685 d.layout_ = new LayoutBox(*this);
686 d.stack_widget_->addWidget(d.layout_);
687 d.layout_->move(0,0);
689 // extracts the toolbars from the backend
690 Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
691 Toolbars::Infos::iterator end = guiApp->toolbars().end();
692 for (; cit != end; ++cit)
693 d.toolbars_[cit->name] = new GuiToolbar(*cit, *this);
697 void GuiView::initToolbars()
699 // extracts the toolbars from the backend
700 Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
701 Toolbars::Infos::iterator end = guiApp->toolbars().end();
702 for (; cit != end; ++cit) {
703 GuiToolbar * tb = toolbar(cit->name);
706 int const visibility = guiApp->toolbars().defaultVisibility(cit->name);
707 bool newline = !(visibility & Toolbars::SAMEROW);
708 tb->setVisible(false);
709 tb->setVisibility(visibility);
711 if (visibility & Toolbars::TOP) {
713 addToolBarBreak(Qt::TopToolBarArea);
714 addToolBar(Qt::TopToolBarArea, tb);
717 if (visibility & Toolbars::BOTTOM) {
718 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
719 #if (QT_VERSION >= 0x040202)
721 addToolBarBreak(Qt::BottomToolBarArea);
723 addToolBar(Qt::BottomToolBarArea, tb);
726 if (visibility & Toolbars::LEFT) {
727 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
728 #if (QT_VERSION >= 0x040202)
730 addToolBarBreak(Qt::LeftToolBarArea);
732 addToolBar(Qt::LeftToolBarArea, tb);
735 if (visibility & Toolbars::RIGHT) {
736 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
737 #if (QT_VERSION >= 0x040202)
739 addToolBarBreak(Qt::RightToolBarArea);
741 addToolBar(Qt::RightToolBarArea, tb);
744 if (visibility & Toolbars::ON)
745 tb->setVisible(true);
750 TocModels & GuiView::tocModels()
752 return d.toc_models_;
756 void GuiView::setFocus()
758 LYXERR(Debug::DEBUG, "GuiView::setFocus()" << this);
759 QMainWindow::setFocus();
763 void GuiView::focusInEvent(QFocusEvent * e)
765 LYXERR(Debug::DEBUG, "GuiView::focusInEvent()" << this);
766 QMainWindow::focusInEvent(e);
767 // Make sure guiApp points to the correct view.
768 guiApp->setCurrentView(this);
769 if (currentWorkArea())
770 currentWorkArea()->setFocus();
771 else if (currentMainWorkArea())
772 currentMainWorkArea()->setFocus();
774 d.bg_widget_->setFocus();
778 QMenu * GuiView::createPopupMenu()
780 return d.toolBarPopup(this);
784 void GuiView::showEvent(QShowEvent * e)
786 LYXERR(Debug::GUI, "Passed Geometry "
787 << size().height() << "x" << size().width()
788 << "+" << pos().x() << "+" << pos().y());
790 if (d.splitter_->count() == 0)
791 // No work area, switch to the background widget.
794 QMainWindow::showEvent(e);
798 bool GuiView::closeScheduled()
805 /** Destroy only all tabbed WorkAreas. Destruction of other WorkAreas
806 ** is responsibility of the container (e.g., dialog)
808 void GuiView::closeEvent(QCloseEvent * close_event)
810 LYXERR(Debug::DEBUG, "GuiView::closeEvent()");
812 if (!GuiViewPrivate::busyBuffers.isEmpty()) {
813 Alert::warning(_("Exit LyX"),
814 _("LyX could not be closed because documents are being processed by LyX."));
815 close_event->setAccepted(false);
819 // If the user pressed the x (so we didn't call closeView
820 // programmatically), we want to clear all existing entries.
822 theSession().lastOpened().clear();
827 // it can happen that this event arrives without selecting the view,
828 // e.g. when clicking the close button on a background window.
830 if (!closeWorkAreaAll()) {
832 close_event->ignore();
836 // Make sure that nothing will use this to be closed View.
837 guiApp->unregisterView(this);
839 if (isFullScreen()) {
840 // Switch off fullscreen before closing.
845 // Make sure the timer time out will not trigger a statusbar update.
846 d.statusbar_timer_.stop();
848 // Saving fullscreen requires additional tweaks in the toolbar code.
849 // It wouldn't also work under linux natively.
850 if (lyxrc.allow_geometry_session) {
855 close_event->accept();
859 void GuiView::dragEnterEvent(QDragEnterEvent * event)
861 if (event->mimeData()->hasUrls())
863 /// \todo Ask lyx-devel is this is enough:
864 /// if (event->mimeData()->hasFormat("text/plain"))
865 /// event->acceptProposedAction();
869 void GuiView::dropEvent(QDropEvent * event)
871 QList<QUrl> files = event->mimeData()->urls();
875 LYXERR(Debug::GUI, "GuiView::dropEvent: got URLs!");
876 for (int i = 0; i != files.size(); ++i) {
877 string const file = os::internal_path(fromqstr(
878 files.at(i).toLocalFile()));
882 string const ext = support::getExtension(file);
883 vector<const Format *> found_formats;
885 // Find all formats that have the correct extension.
886 vector<const Format *> const & import_formats
887 = theConverters().importableFormats();
888 vector<const Format *>::const_iterator it = import_formats.begin();
889 for (; it != import_formats.end(); ++it)
890 if ((*it)->extension() == ext)
891 found_formats.push_back(*it);
894 if (found_formats.size() >= 1) {
895 if (found_formats.size() > 1) {
896 //FIXME: show a dialog to choose the correct importable format
898 "Multiple importable formats found, selecting first");
900 string const arg = found_formats[0]->name() + " " + file;
901 cmd = FuncRequest(LFUN_BUFFER_IMPORT, arg);
904 //FIXME: do we have to explicitly check whether it's a lyx file?
906 "No formats found, trying to open it as a lyx file");
907 cmd = FuncRequest(LFUN_FILE_OPEN, file);
909 // add the functions to the queue
910 guiApp->addToFuncRequestQueue(cmd);
913 // now process the collected functions. We perform the events
914 // asynchronously. This prevents potential problems in case the
915 // BufferView is closed within an event.
916 guiApp->processFuncRequestQueueAsync();
920 void GuiView::message(docstring const & str)
922 if (ForkedProcess::iAmAChild())
925 // call is moved to GUI-thread by GuiProgress
926 d.progress_->appendMessage(toqstr(str));
930 void GuiView::clearMessageText()
932 message(docstring());
936 void GuiView::updateStatusBarMessage(QString const & str)
938 statusBar()->showMessage(str);
939 d.statusbar_timer_.stop();
940 d.statusbar_timer_.start(3000);
944 void GuiView::smallSizedIcons()
946 setIconSize(QSize(d.smallIconSize, d.smallIconSize));
950 void GuiView::normalSizedIcons()
952 setIconSize(QSize(d.normalIconSize, d.normalIconSize));
956 void GuiView::bigSizedIcons()
958 setIconSize(QSize(d.bigIconSize, d.bigIconSize));
962 void GuiView::clearMessage()
964 // FIXME: This code was introduced in r19643 to fix bug #4123. However,
965 // the hasFocus function mostly returns false, even if the focus is on
966 // a workarea in this view.
970 d.statusbar_timer_.stop();
974 void GuiView::updateWindowTitle(GuiWorkArea * wa)
976 if (wa != d.current_work_area_
977 || wa->bufferView().buffer().isInternal())
979 setWindowTitle(qt_("LyX: ") + wa->windowTitle());
980 setWindowIconText(wa->windowIconText());
984 void GuiView::on_currentWorkAreaChanged(GuiWorkArea * wa)
987 disconnectBufferView();
988 connectBufferView(wa->bufferView());
989 connectBuffer(wa->bufferView().buffer());
990 d.current_work_area_ = wa;
991 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
992 this, SLOT(updateWindowTitle(GuiWorkArea *)));
993 updateWindowTitle(wa);
997 // The document settings needs to be reinitialised.
998 updateDialog("document", "");
1000 // Buffer-dependent dialogs must be updated. This is done here because
1001 // some dialogs require buffer()->text.
1006 void GuiView::on_lastWorkAreaRemoved()
1009 // We already are in a close event. Nothing more to do.
1012 if (d.splitter_->count() > 1)
1013 // We have a splitter so don't close anything.
1016 // Reset and updates the dialogs.
1017 d.toc_models_.reset(0);
1018 updateDialog("document", "");
1021 resetWindowTitleAndIconText();
1024 if (lyxrc.open_buffers_in_tabs)
1025 // Nothing more to do, the window should stay open.
1028 if (guiApp->viewIds().size() > 1) {
1034 // On Mac we also close the last window because the application stay
1035 // resident in memory. On other platforms we don't close the last
1036 // window because this would quit the application.
1042 void GuiView::updateStatusBar()
1044 // let the user see the explicit message
1045 if (d.statusbar_timer_.isActive())
1052 void GuiView::showMessage()
1054 QString msg = toqstr(theGuiApp()->viewStatusMessage());
1055 if (msg.isEmpty()) {
1056 BufferView const * bv = currentBufferView();
1058 msg = toqstr(bv->cursor().currentState());
1060 msg = qt_("Welcome to LyX!");
1062 statusBar()->showMessage(msg);
1066 bool GuiView::event(QEvent * e)
1070 // Useful debug code:
1071 //case QEvent::ActivationChange:
1072 //case QEvent::WindowDeactivate:
1073 //case QEvent::Paint:
1074 //case QEvent::Enter:
1075 //case QEvent::Leave:
1076 //case QEvent::HoverEnter:
1077 //case QEvent::HoverLeave:
1078 //case QEvent::HoverMove:
1079 //case QEvent::StatusTip:
1080 //case QEvent::DragEnter:
1081 //case QEvent::DragLeave:
1082 //case QEvent::Drop:
1085 case QEvent::WindowActivate: {
1086 GuiView * old_view = guiApp->currentView();
1087 if (this == old_view) {
1089 return QMainWindow::event(e);
1091 if (old_view && old_view->currentBufferView()) {
1092 // save current selection to the selection buffer to allow
1093 // middle-button paste in this window.
1094 cap::saveSelection(old_view->currentBufferView()->cursor());
1096 guiApp->setCurrentView(this);
1097 if (d.current_work_area_) {
1098 BufferView & bv = d.current_work_area_->bufferView();
1099 connectBufferView(bv);
1100 connectBuffer(bv.buffer());
1101 // The document structure, name and dialogs might have
1102 // changed in another view.
1104 // The document settings needs to be reinitialised.
1105 updateDialog("document", "");
1108 resetWindowTitleAndIconText();
1111 return QMainWindow::event(e);
1114 case QEvent::ShortcutOverride: {
1117 #if (!defined Q_WS_X11) || (QT_VERSION >= 0x040500)
1118 if (isFullScreen() && menuBar()->isHidden()) {
1119 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
1120 // FIXME: we should also try to detect special LyX shortcut such as
1121 // Alt-P and Alt-M. Right now there is a hack in
1122 // GuiWorkArea::processKeySym() that hides again the menubar for
1124 if (ke->modifiers() & Qt::AltModifier && ke->key() != Qt::Key_Alt) {
1126 return QMainWindow::event(e);
1130 return QMainWindow::event(e);
1134 return QMainWindow::event(e);
1138 void GuiView::resetWindowTitleAndIconText()
1140 setWindowTitle(qt_("LyX"));
1141 setWindowIconText(qt_("LyX"));
1144 bool GuiView::focusNextPrevChild(bool /*next*/)
1151 bool GuiView::busy() const
1157 void GuiView::setBusy(bool busy)
1159 bool const busy_before = busy_ > 0;
1160 busy ? ++busy_ : --busy_;
1161 if ((busy_ > 0) == busy_before)
1162 // busy state didn't change
1165 if (d.current_work_area_) {
1166 //Why would we want to stop updates only for one workarea and
1167 //not for the others ? This leads to problems as in #7314 (vfr).
1168 //d.current_work_area_->setUpdatesEnabled(!busy);
1170 d.current_work_area_->stopBlinkingCursor();
1172 d.current_work_area_->startBlinkingCursor();
1176 QApplication::setOverrideCursor(Qt::WaitCursor);
1178 QApplication::restoreOverrideCursor();
1182 GuiWorkArea * GuiView::workArea(int index)
1184 if (TabWorkArea * twa = d.currentTabWorkArea())
1185 if (index < twa->count())
1186 return dynamic_cast<GuiWorkArea *>(twa->widget(index));
1191 GuiWorkArea * GuiView::workArea(Buffer & buffer)
1193 if (currentWorkArea()
1194 && ¤tWorkArea()->bufferView().buffer() == &buffer)
1195 return (GuiWorkArea *) currentWorkArea();
1196 if (TabWorkArea * twa = d.currentTabWorkArea())
1197 return twa->workArea(buffer);
1202 GuiWorkArea * GuiView::addWorkArea(Buffer & buffer)
1204 // Automatically create a TabWorkArea if there are none yet.
1205 TabWorkArea * tab_widget = d.splitter_->count()
1206 ? d.currentTabWorkArea() : addTabWorkArea();
1207 return tab_widget->addWorkArea(buffer, *this);
1211 TabWorkArea * GuiView::addTabWorkArea()
1213 TabWorkArea * twa = new TabWorkArea;
1214 QObject::connect(twa, SIGNAL(currentWorkAreaChanged(GuiWorkArea *)),
1215 this, SLOT(on_currentWorkAreaChanged(GuiWorkArea *)));
1216 QObject::connect(twa, SIGNAL(lastWorkAreaRemoved()),
1217 this, SLOT(on_lastWorkAreaRemoved()));
1219 d.splitter_->addWidget(twa);
1220 d.stack_widget_->setCurrentWidget(d.splitter_);
1225 GuiWorkArea const * GuiView::currentWorkArea() const
1227 return d.current_work_area_;
1231 GuiWorkArea * GuiView::currentWorkArea()
1233 return d.current_work_area_;
1237 GuiWorkArea const * GuiView::currentMainWorkArea() const
1239 if (!d.currentTabWorkArea())
1241 return d.currentTabWorkArea()->currentWorkArea();
1245 GuiWorkArea * GuiView::currentMainWorkArea()
1247 if (!d.currentTabWorkArea())
1249 return d.currentTabWorkArea()->currentWorkArea();
1253 void GuiView::setCurrentWorkArea(GuiWorkArea * wa)
1255 LYXERR(Debug::DEBUG, "Setting current wa: " << wa << endl);
1257 d.current_work_area_ = 0;
1262 // FIXME: I've no clue why this is here and why it accesses
1263 // theGuiApp()->currentView, which might be 0 (bug 6464).
1264 // See also 27525 (vfr).
1265 if (theGuiApp()->currentView() == this
1266 && theGuiApp()->currentView()->currentWorkArea() == wa)
1269 if (currentBufferView())
1270 cap::saveSelection(currentBufferView()->cursor());
1272 theGuiApp()->setCurrentView(this);
1273 d.current_work_area_ = wa;
1275 // We need to reset this now, because it will need to be
1276 // right if the tabWorkArea gets reset in the for loop. We
1277 // will change it back if we aren't in that case.
1278 GuiWorkArea * const old_cmwa = d.current_main_work_area_;
1279 d.current_main_work_area_ = wa;
1281 for (int i = 0; i != d.splitter_->count(); ++i) {
1282 if (d.tabWorkArea(i)->setCurrentWorkArea(wa)) {
1283 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea()
1284 << ", Current main wa: " << currentMainWorkArea());
1289 d.current_main_work_area_ = old_cmwa;
1291 LYXERR(Debug::DEBUG, "This is not a tabbed wa");
1292 on_currentWorkAreaChanged(wa);
1293 BufferView & bv = wa->bufferView();
1294 bv.cursor().fixIfBroken();
1296 wa->setUpdatesEnabled(true);
1297 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() << ", Current main wa: " << currentMainWorkArea());
1301 void GuiView::removeWorkArea(GuiWorkArea * wa)
1303 LASSERT(wa, return);
1304 if (wa == d.current_work_area_) {
1306 disconnectBufferView();
1307 d.current_work_area_ = 0;
1308 d.current_main_work_area_ = 0;
1311 bool found_twa = false;
1312 for (int i = 0; i != d.splitter_->count(); ++i) {
1313 TabWorkArea * twa = d.tabWorkArea(i);
1314 if (twa->removeWorkArea(wa)) {
1315 // Found in this tab group, and deleted the GuiWorkArea.
1317 if (twa->count() != 0) {
1318 if (d.current_work_area_ == 0)
1319 // This means that we are closing the current GuiWorkArea, so
1320 // switch to the next GuiWorkArea in the found TabWorkArea.
1321 setCurrentWorkArea(twa->currentWorkArea());
1323 // No more WorkAreas in this tab group, so delete it.
1330 // It is not a tabbed work area (i.e., the search work area), so it
1331 // should be deleted by other means.
1332 LASSERT(found_twa, /* */);
1334 if (d.current_work_area_ == 0) {
1335 if (d.splitter_->count() != 0) {
1336 TabWorkArea * twa = d.currentTabWorkArea();
1337 setCurrentWorkArea(twa->currentWorkArea());
1339 // No more work areas, switch to the background widget.
1340 setCurrentWorkArea(0);
1346 LayoutBox * GuiView::getLayoutDialog() const
1352 void GuiView::updateLayoutList()
1355 d.layout_->updateContents(false);
1359 void GuiView::updateToolbars()
1361 ToolbarMap::iterator end = d.toolbars_.end();
1362 if (d.current_work_area_) {
1364 d.current_work_area_->bufferView().cursor().inMathed()
1365 && !d.current_work_area_->bufferView().cursor().inRegexped();
1367 lyx::getStatus(FuncRequest(LFUN_LAYOUT_TABULAR)).enabled();
1369 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).enabled() &&
1370 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).onOff(true);
1371 bool const mathmacrotemplate =
1372 lyx::getStatus(FuncRequest(LFUN_IN_MATHMACROTEMPLATE)).enabled();
1374 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1375 it->second->update(math, table, review, mathmacrotemplate);
1377 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1378 it->second->update(false, false, false, false);
1382 void GuiView::setBuffer(Buffer * newBuffer)
1384 LYXERR(Debug::DEBUG, "Setting buffer: " << newBuffer << endl);
1385 LASSERT(newBuffer, return);
1387 GuiWorkArea * wa = workArea(*newBuffer);
1390 newBuffer->masterBuffer()->updateBuffer();
1392 wa = addWorkArea(*newBuffer);
1393 // scroll to the position when the BufferView was last closed
1394 if (lyxrc.use_lastfilepos) {
1395 LastFilePosSection::FilePos filepos =
1396 theSession().lastFilePos().load(newBuffer->fileName());
1397 wa->bufferView().moveToPosition(filepos.pit, filepos.pos, 0, 0);
1400 //Disconnect the old buffer...there's no new one.
1403 connectBuffer(*newBuffer);
1404 connectBufferView(wa->bufferView());
1405 setCurrentWorkArea(wa);
1409 void GuiView::connectBuffer(Buffer & buf)
1411 buf.setGuiDelegate(this);
1415 void GuiView::disconnectBuffer()
1417 if (d.current_work_area_)
1418 d.current_work_area_->bufferView().buffer().setGuiDelegate(0);
1422 void GuiView::connectBufferView(BufferView & bv)
1424 bv.setGuiDelegate(this);
1428 void GuiView::disconnectBufferView()
1430 if (d.current_work_area_)
1431 d.current_work_area_->bufferView().setGuiDelegate(0);
1435 void GuiView::errors(string const & error_type, bool from_master)
1437 BufferView const * const bv = currentBufferView();
1441 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
1442 // We are called with from_master == false by default, so we
1443 // have to figure out whether that is the case or not.
1444 ErrorList & el = bv->buffer().errorList(error_type);
1446 el = bv->buffer().masterBuffer()->errorList(error_type);
1450 ErrorList & el = from_master ?
1451 bv->buffer().masterBuffer()->errorList(error_type) :
1452 bv->buffer().errorList(error_type);
1458 string data = error_type;
1460 data = "from_master|" + error_type;
1461 showDialog("errorlist", data);
1465 void GuiView::updateTocItem(string const & type, DocIterator const & dit)
1467 d.toc_models_.updateItem(toqstr(type), dit);
1471 void GuiView::structureChanged()
1473 d.toc_models_.reset(documentBufferView());
1474 // Navigator needs more than a simple update in this case. It needs to be
1476 updateDialog("toc", "");
1480 void GuiView::updateDialog(string const & name, string const & data)
1482 if (!isDialogVisible(name))
1485 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
1486 if (it == d.dialogs_.end())
1489 Dialog * const dialog = it->second.get();
1490 if (dialog->isVisibleView())
1491 dialog->initialiseParams(data);
1495 BufferView * GuiView::documentBufferView()
1497 return currentMainWorkArea()
1498 ? ¤tMainWorkArea()->bufferView()
1503 BufferView const * GuiView::documentBufferView() const
1505 return currentMainWorkArea()
1506 ? ¤tMainWorkArea()->bufferView()
1511 BufferView * GuiView::currentBufferView()
1513 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1517 BufferView const * GuiView::currentBufferView() const
1519 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1523 #if (QT_VERSION >= 0x040400)
1524 docstring GuiView::GuiViewPrivate::autosaveAndDestroy(
1525 Buffer const * orig, Buffer * buffer)
1527 bool const success = buffer->autoSave();
1529 busyBuffers.remove(orig);
1531 ? _("Automatic save done.")
1532 : _("Automatic save failed!");
1537 void GuiView::autoSave()
1539 LYXERR(Debug::INFO, "Running autoSave()");
1541 Buffer * buffer = documentBufferView()
1542 ? &documentBufferView()->buffer() : 0;
1544 resetAutosaveTimers();
1548 #if (QT_VERSION >= 0x040400)
1549 GuiViewPrivate::busyBuffers.insert(buffer);
1550 QFuture<docstring> f = QtConcurrent::run(GuiViewPrivate::autosaveAndDestroy,
1551 buffer, buffer->clone());
1552 d.autosave_watcher_.setFuture(f);
1556 resetAutosaveTimers();
1560 void GuiView::resetAutosaveTimers()
1563 d.autosave_timeout_.restart();
1567 bool GuiView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1570 Buffer * buf = currentBufferView()
1571 ? ¤tBufferView()->buffer() : 0;
1572 Buffer * doc_buffer = documentBufferView()
1573 ? &(documentBufferView()->buffer()) : 0;
1575 // Check whether we need a buffer
1576 if (!lyxaction.funcHasFlag(cmd.action(), LyXAction::NoBuffer) && !buf) {
1577 // no, exit directly
1578 flag.message(from_utf8(N_("Command not allowed with"
1579 "out any document open")));
1580 flag.setEnabled(false);
1584 if (cmd.origin() == FuncRequest::TOC) {
1585 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
1586 if (!toc || !toc->getStatus(documentBufferView()->cursor(), cmd, flag))
1587 flag.setEnabled(false);
1591 switch(cmd.action()) {
1592 case LFUN_BUFFER_IMPORT:
1595 case LFUN_MASTER_BUFFER_UPDATE:
1596 case LFUN_MASTER_BUFFER_VIEW:
1597 enable = doc_buffer && doc_buffer->parent() != 0
1598 && !d.processing_thread_watcher_.isRunning();
1601 case LFUN_BUFFER_UPDATE:
1602 case LFUN_BUFFER_VIEW: {
1603 if (!doc_buffer || d.processing_thread_watcher_.isRunning()) {
1607 string format = to_utf8(cmd.argument());
1608 if (cmd.argument().empty())
1609 format = doc_buffer->getDefaultOutputFormat();
1610 enable = doc_buffer->isExportableFormat(format);
1614 case LFUN_BUFFER_RELOAD:
1615 enable = doc_buffer && !doc_buffer->isUnnamed()
1616 && doc_buffer->fileName().exists()
1617 && (!doc_buffer->isClean()
1618 || doc_buffer->isExternallyModified(Buffer::timestamp_method));
1621 case LFUN_BUFFER_CHILD_OPEN:
1622 enable = doc_buffer;
1625 case LFUN_BUFFER_WRITE:
1626 enable = doc_buffer && (doc_buffer->isUnnamed() || !doc_buffer->isClean());
1629 //FIXME: This LFUN should be moved to GuiApplication.
1630 case LFUN_BUFFER_WRITE_ALL: {
1631 // We enable the command only if there are some modified buffers
1632 Buffer * first = theBufferList().first();
1637 // We cannot use a for loop as the buffer list is a cycle.
1639 if (!b->isClean()) {
1643 b = theBufferList().next(b);
1644 } while (b != first);
1648 case LFUN_BUFFER_WRITE_AS:
1649 enable = doc_buffer;
1652 case LFUN_BUFFER_CLOSE:
1653 enable = doc_buffer;
1656 case LFUN_BUFFER_CLOSE_ALL:
1657 enable = theBufferList().last() != theBufferList().first();
1660 case LFUN_SPLIT_VIEW:
1661 if (cmd.getArg(0) == "vertical")
1662 enable = doc_buffer && (d.splitter_->count() == 1 ||
1663 d.splitter_->orientation() == Qt::Vertical);
1665 enable = doc_buffer && (d.splitter_->count() == 1 ||
1666 d.splitter_->orientation() == Qt::Horizontal);
1669 case LFUN_CLOSE_TAB_GROUP:
1670 enable = d.currentTabWorkArea();
1673 case LFUN_TOOLBAR_TOGGLE: {
1674 string const name = cmd.getArg(0);
1675 if (GuiToolbar * t = toolbar(name))
1676 flag.setOnOff(t->isVisible());
1679 docstring const msg =
1680 bformat(_("Unknown toolbar \"%1$s\""), from_utf8(name));
1686 case LFUN_DROP_LAYOUTS_CHOICE:
1690 case LFUN_UI_TOGGLE:
1691 flag.setOnOff(isFullScreen());
1694 case LFUN_DIALOG_DISCONNECT_INSET:
1697 case LFUN_DIALOG_HIDE:
1698 // FIXME: should we check if the dialog is shown?
1701 case LFUN_DIALOG_TOGGLE:
1702 flag.setOnOff(isDialogVisible(cmd.getArg(0)));
1703 // fall through to set "enable"
1704 case LFUN_DIALOG_SHOW: {
1705 string const name = cmd.getArg(0);
1707 enable = name == "aboutlyx"
1708 || name == "file" //FIXME: should be removed.
1710 || name == "texinfo"
1711 || name == "progress"
1712 || name == "compare";
1713 else if (name == "print")
1714 enable = doc_buffer->isExportable("dvi")
1715 && lyxrc.print_command != "none";
1716 else if (name == "character" || name == "symbols") {
1717 if (!buf || buf->isReadonly())
1720 Cursor const & cur = currentBufferView()->cursor();
1721 enable = !(cur.inTexted() && cur.paragraph().isPassThru());
1724 else if (name == "latexlog")
1725 enable = FileName(doc_buffer->logName()).isReadableFile();
1726 else if (name == "spellchecker")
1727 enable = theSpellChecker() && !doc_buffer->isReadonly();
1728 else if (name == "vclog")
1729 enable = doc_buffer->lyxvc().inUse();
1733 case LFUN_DIALOG_UPDATE: {
1734 string const name = cmd.getArg(0);
1736 enable = name == "prefs";
1740 case LFUN_COMMAND_EXECUTE:
1742 case LFUN_MENU_OPEN:
1743 // Nothing to check.
1746 case LFUN_COMPLETION_INLINE:
1747 if (!d.current_work_area_
1748 || !d.current_work_area_->completer().inlinePossible(
1749 currentBufferView()->cursor()))
1753 case LFUN_COMPLETION_POPUP:
1754 if (!d.current_work_area_
1755 || !d.current_work_area_->completer().popupPossible(
1756 currentBufferView()->cursor()))
1760 case LFUN_COMPLETION_COMPLETE:
1761 if (!d.current_work_area_
1762 || !d.current_work_area_->completer().inlinePossible(
1763 currentBufferView()->cursor()))
1767 case LFUN_COMPLETION_ACCEPT:
1768 if (!d.current_work_area_
1769 || (!d.current_work_area_->completer().popupVisible()
1770 && !d.current_work_area_->completer().inlineVisible()
1771 && !d.current_work_area_->completer().completionAvailable()))
1775 case LFUN_COMPLETION_CANCEL:
1776 if (!d.current_work_area_
1777 || (!d.current_work_area_->completer().popupVisible()
1778 && !d.current_work_area_->completer().inlineVisible()))
1782 case LFUN_BUFFER_ZOOM_OUT:
1783 enable = doc_buffer && lyxrc.zoom > 10;
1786 case LFUN_BUFFER_ZOOM_IN:
1787 enable = doc_buffer;
1790 case LFUN_BUFFER_NEXT:
1791 case LFUN_BUFFER_PREVIOUS:
1792 // FIXME: should we check is there is an previous or next buffer?
1794 case LFUN_BUFFER_SWITCH:
1795 // toggle on the current buffer, but do not toggle off
1796 // the other ones (is that a good idea?)
1798 && to_utf8(cmd.argument()) == doc_buffer->absFileName())
1799 flag.setOnOff(true);
1802 case LFUN_VC_REGISTER:
1803 enable = doc_buffer && !doc_buffer->lyxvc().inUse();
1805 case LFUN_VC_CHECK_IN:
1806 enable = doc_buffer && doc_buffer->lyxvc().checkInEnabled();
1808 case LFUN_VC_CHECK_OUT:
1809 enable = doc_buffer && doc_buffer->lyxvc().checkOutEnabled();
1811 case LFUN_VC_LOCKING_TOGGLE:
1812 enable = doc_buffer && !doc_buffer->isReadonly()
1813 && doc_buffer->lyxvc().lockingToggleEnabled();
1814 flag.setOnOff(enable && doc_buffer->lyxvc().locking());
1816 case LFUN_VC_REVERT:
1817 enable = doc_buffer && doc_buffer->lyxvc().inUse() && !doc_buffer->isReadonly();
1819 case LFUN_VC_UNDO_LAST:
1820 enable = doc_buffer && doc_buffer->lyxvc().undoLastEnabled();
1822 case LFUN_VC_REPO_UPDATE:
1823 enable = doc_buffer && doc_buffer->lyxvc().repoUpdateEnabled();
1825 case LFUN_VC_COMMAND: {
1826 if (cmd.argument().empty())
1828 if (!doc_buffer && contains(cmd.getArg(0), 'D'))
1832 case LFUN_VC_COMPARE:
1833 enable = doc_buffer && doc_buffer->lyxvc().prepareFileRevisionEnabled();
1836 case LFUN_SERVER_GOTO_FILE_ROW:
1838 case LFUN_FORWARD_SEARCH:
1839 enable = !(lyxrc.forward_search_dvi.empty() && lyxrc.forward_search_pdf.empty());
1847 flag.setEnabled(false);
1853 static FileName selectTemplateFile()
1855 FileDialog dlg(qt_("Select template file"));
1856 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1857 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
1859 FileDialog::Result result = dlg.open(toqstr(lyxrc.template_path),
1860 QStringList(qt_("LyX Documents (*.lyx)")));
1862 if (result.first == FileDialog::Later)
1864 if (result.second.isEmpty())
1866 return FileName(fromqstr(result.second));
1870 Buffer * GuiView::loadDocument(FileName const & filename, bool tolastfiles)
1874 Buffer * newBuffer = 0;
1876 newBuffer = checkAndLoadLyXFile(filename);
1877 } catch (ExceptionMessage const & e) {
1884 message(_("Document not loaded."));
1888 newBuffer->errors("Parse");
1889 setBuffer(newBuffer);
1892 theSession().lastFiles().add(filename);
1898 void GuiView::openDocument(string const & fname)
1900 string initpath = lyxrc.document_path;
1902 if (documentBufferView()) {
1903 string const trypath = documentBufferView()->buffer().filePath();
1904 // If directory is writeable, use this as default.
1905 if (FileName(trypath).isDirWritable())
1911 if (fname.empty()) {
1912 FileDialog dlg(qt_("Select document to open"), LFUN_FILE_OPEN);
1913 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1914 dlg.setButton2(qt_("Examples|#E#e"),
1915 toqstr(addPath(package().system_support().absFileName(), "examples")));
1917 QStringList filter(qt_("LyX Documents (*.lyx)"));
1918 filter << qt_("LyX-1.3.x Documents (*.lyx13)")
1919 << qt_("LyX-1.4.x Documents (*.lyx14)")
1920 << qt_("LyX-1.5.x Documents (*.lyx15)")
1921 << qt_("LyX-1.6.x Documents (*.lyx16)");
1922 FileDialog::Result result =
1923 dlg.open(toqstr(initpath), filter);
1925 if (result.first == FileDialog::Later)
1928 filename = fromqstr(result.second);
1930 // check selected filename
1931 if (filename.empty()) {
1932 message(_("Canceled."));
1938 // get absolute path of file and add ".lyx" to the filename if
1940 FileName const fullname =
1941 fileSearch(string(), filename, "lyx", support::may_not_exist);
1942 if (!fullname.empty())
1943 filename = fullname.absFileName();
1945 if (!fullname.onlyPath().isDirectory()) {
1946 Alert::warning(_("Invalid filename"),
1947 bformat(_("The directory in the given path\n%1$s\ndoes not exist."),
1948 from_utf8(fullname.absFileName())));
1952 // if the file doesn't exist and isn't already open (bug 6645),
1953 // let the user create one
1954 if (!fullname.exists() && !theBufferList().exists(fullname)) {
1955 // the user specifically chose this name. Believe him.
1956 Buffer * const b = newFile(filename, string(), true);
1962 docstring const disp_fn = makeDisplayPath(filename);
1963 message(bformat(_("Opening document %1$s..."), disp_fn));
1966 Buffer * buf = loadDocument(fullname);
1968 str2 = bformat(_("Document %1$s opened."), disp_fn);
1969 if (buf->lyxvc().inUse())
1970 str2 += " " + from_utf8(buf->lyxvc().versionString()) +
1971 " " + _("Version control detected.");
1973 str2 = bformat(_("Could not open document %1$s"), disp_fn);
1978 // FIXME: clean that
1979 static bool import(GuiView * lv, FileName const & filename,
1980 string const & format, ErrorList & errorList)
1982 FileName const lyxfile(support::changeExtension(filename.absFileName(), ".lyx"));
1984 string loader_format;
1985 vector<string> loaders = theConverters().loaders();
1986 if (find(loaders.begin(), loaders.end(), format) == loaders.end()) {
1987 for (vector<string>::const_iterator it = loaders.begin();
1988 it != loaders.end(); ++it) {
1989 if (!theConverters().isReachable(format, *it))
1992 string const tofile =
1993 support::changeExtension(filename.absFileName(),
1994 formats.extension(*it));
1995 if (!theConverters().convert(0, filename, FileName(tofile),
1996 filename, format, *it, errorList))
1998 loader_format = *it;
2001 if (loader_format.empty()) {
2002 frontend::Alert::error(_("Couldn't import file"),
2003 bformat(_("No information for importing the format %1$s."),
2004 formats.prettyName(format)));
2008 loader_format = format;
2010 if (loader_format == "lyx") {
2011 Buffer * buf = lv->loadDocument(lyxfile);
2015 Buffer * const b = newFile(lyxfile.absFileName(), string(), true);
2019 bool as_paragraphs = loader_format == "textparagraph";
2020 string filename2 = (loader_format == format) ? filename.absFileName()
2021 : support::changeExtension(filename.absFileName(),
2022 formats.extension(loader_format));
2023 lv->currentBufferView()->insertPlaintextFile(FileName(filename2),
2025 guiApp->setCurrentView(lv);
2026 lyx::dispatch(FuncRequest(LFUN_MARK_OFF));
2033 void GuiView::importDocument(string const & argument)
2036 string filename = split(argument, format, ' ');
2038 LYXERR(Debug::INFO, format << " file: " << filename);
2040 // need user interaction
2041 if (filename.empty()) {
2042 string initpath = lyxrc.document_path;
2043 if (documentBufferView()) {
2044 string const trypath = documentBufferView()->buffer().filePath();
2045 // If directory is writeable, use this as default.
2046 if (FileName(trypath).isDirWritable())
2050 docstring const text = bformat(_("Select %1$s file to import"),
2051 formats.prettyName(format));
2053 FileDialog dlg(toqstr(text), LFUN_BUFFER_IMPORT);
2054 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2055 dlg.setButton2(qt_("Examples|#E#e"),
2056 toqstr(addPath(package().system_support().absFileName(), "examples")));
2058 docstring filter = formats.prettyName(format);
2061 filter += from_utf8(formats.extension(format));
2064 FileDialog::Result result =
2065 dlg.open(toqstr(initpath), fileFilters(toqstr(filter)));
2067 if (result.first == FileDialog::Later)
2070 filename = fromqstr(result.second);
2072 // check selected filename
2073 if (filename.empty())
2074 message(_("Canceled."));
2077 if (filename.empty())
2080 // get absolute path of file
2081 FileName const fullname(support::makeAbsPath(filename));
2083 FileName const lyxfile(support::changeExtension(fullname.absFileName(), ".lyx"));
2085 // Check if the document already is open
2086 Buffer * buf = theBufferList().getBuffer(lyxfile);
2089 if (!closeBuffer()) {
2090 message(_("Canceled."));
2095 docstring const displaypath = makeDisplayPath(lyxfile.absFileName(), 30);
2097 // if the file exists already, and we didn't do
2098 // -i lyx thefile.lyx, warn
2099 if (lyxfile.exists() && fullname != lyxfile) {
2101 docstring text = bformat(_("The document %1$s already exists.\n\n"
2102 "Do you want to overwrite that document?"), displaypath);
2103 int const ret = Alert::prompt(_("Overwrite document?"),
2104 text, 0, 1, _("&Overwrite"), _("&Cancel"));
2107 message(_("Canceled."));
2112 message(bformat(_("Importing %1$s..."), displaypath));
2113 ErrorList errorList;
2114 if (import(this, fullname, format, errorList))
2115 message(_("imported."));
2117 message(_("file not imported!"));
2119 // FIXME (Abdel 12/08/06): Is there a need to display the error list here?
2123 void GuiView::newDocument(string const & filename, bool from_template)
2125 FileName initpath(lyxrc.document_path);
2126 if (documentBufferView()) {
2127 FileName const trypath(documentBufferView()->buffer().filePath());
2128 // If directory is writeable, use this as default.
2129 if (trypath.isDirWritable())
2133 string templatefile;
2134 if (from_template) {
2135 templatefile = selectTemplateFile().absFileName();
2136 if (templatefile.empty())
2141 if (filename.empty())
2142 b = newUnnamedFile(initpath, to_utf8(_("newfile")), templatefile);
2144 b = newFile(filename, templatefile, true);
2149 // If no new document could be created, it is unsure
2150 // whether there is a valid BufferView.
2151 if (currentBufferView())
2152 // Ensure the cursor is correctly positioned on screen.
2153 currentBufferView()->showCursor();
2157 void GuiView::insertLyXFile(docstring const & fname)
2159 BufferView * bv = documentBufferView();
2164 FileName filename(to_utf8(fname));
2165 if (filename.empty()) {
2166 // Launch a file browser
2168 string initpath = lyxrc.document_path;
2169 string const trypath = bv->buffer().filePath();
2170 // If directory is writeable, use this as default.
2171 if (FileName(trypath).isDirWritable())
2175 FileDialog dlg(qt_("Select LyX document to insert"), LFUN_FILE_INSERT);
2176 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2177 dlg.setButton2(qt_("Examples|#E#e"),
2178 toqstr(addPath(package().system_support().absFileName(),
2181 FileDialog::Result result = dlg.open(toqstr(initpath),
2182 QStringList(qt_("LyX Documents (*.lyx)")));
2184 if (result.first == FileDialog::Later)
2188 filename.set(fromqstr(result.second));
2190 // check selected filename
2191 if (filename.empty()) {
2192 // emit message signal.
2193 message(_("Canceled."));
2198 bv->insertLyXFile(filename);
2199 bv->buffer().errors("Parse");
2203 void GuiView::insertPlaintextFile(docstring const & fname,
2206 BufferView * bv = documentBufferView();
2210 if (!fname.empty() && !FileName::isAbsolute(to_utf8(fname))) {
2211 message(_("Absolute filename expected."));
2216 FileName filename(to_utf8(fname));
2218 if (!filename.empty()) {
2219 bv->insertPlaintextFile(filename, asParagraph);
2223 FileDialog dlg(qt_("Select file to insert"), (asParagraph ?
2224 LFUN_FILE_INSERT_PLAINTEXT_PARA : LFUN_FILE_INSERT_PLAINTEXT));
2226 FileDialog::Result result = dlg.open(toqstr(bv->buffer().filePath()),
2227 QStringList(qt_("All Files (*)")));
2229 if (result.first == FileDialog::Later)
2233 filename.set(fromqstr(result.second));
2235 // check selected filename
2236 if (filename.empty()) {
2237 // emit message signal.
2238 message(_("Canceled."));
2242 bv->insertPlaintextFile(filename, asParagraph);
2246 bool GuiView::renameBuffer(Buffer & b, docstring const & newname)
2248 FileName fname = b.fileName();
2249 FileName const oldname = fname;
2251 if (!newname.empty()) {
2253 fname = support::makeAbsPath(to_utf8(newname), oldname.onlyPath().absFileName());
2255 // Switch to this Buffer.
2258 // No argument? Ask user through dialog.
2260 FileDialog dlg(qt_("Choose a filename to save document as"),
2261 LFUN_BUFFER_WRITE_AS);
2262 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2263 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
2265 if (!isLyXFileName(fname.absFileName()))
2266 fname.changeExtension(".lyx");
2268 FileDialog::Result result =
2269 dlg.save(toqstr(fname.onlyPath().absFileName()),
2270 QStringList(qt_("LyX Documents (*.lyx)")),
2271 toqstr(fname.onlyFileName()));
2273 if (result.first == FileDialog::Later)
2276 fname.set(fromqstr(result.second));
2281 if (!isLyXFileName(fname.absFileName()))
2282 fname.changeExtension(".lyx");
2285 // fname is now the new Buffer location.
2286 if (FileName(fname).exists()) {
2287 docstring const file = makeDisplayPath(fname.absFileName(), 30);
2288 docstring text = bformat(_("The document %1$s already "
2289 "exists.\n\nDo you want to "
2290 "overwrite that document?"),
2292 int const ret = Alert::prompt(_("Overwrite document?"),
2293 text, 0, 2, _("&Overwrite"), _("&Rename"), _("&Cancel"));
2296 case 1: return renameBuffer(b, docstring());
2297 case 2: return false;
2301 return saveBuffer(b, fname);
2305 bool GuiView::saveBuffer(Buffer & b) {
2306 return saveBuffer(b, FileName());
2310 bool GuiView::saveBuffer(Buffer & b, FileName const & fn)
2312 if (workArea(b) && workArea(b)->inDialogMode())
2315 if (fn.empty() && b.isUnnamed())
2316 return renameBuffer(b, docstring());
2322 success = b.saveAs(fn);
2325 theSession().lastFiles().add(b.fileName());
2329 // Switch to this Buffer.
2332 // FIXME: we don't tell the user *WHY* the save failed !!
2333 docstring const file = makeDisplayPath(b.absFileName(), 30);
2334 docstring text = bformat(_("The document %1$s could not be saved.\n\n"
2335 "Do you want to rename the document and "
2336 "try again?"), file);
2337 int const ret = Alert::prompt(_("Rename and save?"),
2338 text, 0, 2, _("&Rename"), _("&Retry"), _("&Cancel"));
2341 if (!renameBuffer(b, docstring()))
2350 return saveBuffer(b);
2354 bool GuiView::hideWorkArea(GuiWorkArea * wa)
2356 return closeWorkArea(wa, false);
2360 bool GuiView::closeWorkArea(GuiWorkArea * wa)
2362 Buffer & buf = wa->bufferView().buffer();
2363 return closeWorkArea(wa, !buf.parent());
2367 bool GuiView::closeBuffer()
2369 GuiWorkArea * wa = currentMainWorkArea();
2370 setCurrentWorkArea(wa);
2371 Buffer & buf = wa->bufferView().buffer();
2372 return wa && closeWorkArea(wa, !buf.parent());
2376 void GuiView::writeSession() const {
2377 GuiWorkArea const * active_wa = currentMainWorkArea();
2378 for (int i = 0; i < d.splitter_->count(); ++i) {
2379 TabWorkArea * twa = d.tabWorkArea(i);
2380 for (int j = 0; j < twa->count(); ++j) {
2381 GuiWorkArea * wa = static_cast<GuiWorkArea *>(twa->widget(j));
2382 Buffer & buf = wa->bufferView().buffer();
2383 theSession().lastOpened().add(buf.fileName(), wa == active_wa);
2389 bool GuiView::closeBufferAll()
2391 // Close the workareas in all other views
2392 QList<int> const ids = guiApp->viewIds();
2393 for (int i = 0; i != ids.size(); ++i) {
2394 if (id_ != ids[i] && !guiApp->view(ids[i]).closeWorkAreaAll())
2398 // Close our own workareas
2399 if (!closeWorkAreaAll())
2402 // Now close the hidden buffers. We prevent hidden buffers from being
2403 // dirty, so we can just close them.
2404 theBufferList().closeAll();
2409 bool GuiView::closeWorkAreaAll()
2411 setCurrentWorkArea(currentMainWorkArea());
2413 // We might be in a situation that there is still a tabWorkArea, but
2414 // there are no tabs anymore. This can happen when we get here after a
2415 // TabWorkArea::lastWorkAreaRemoved() signal. Therefore we count how
2416 // many TabWorkArea's have no documents anymore.
2419 // We have to call count() each time, because it can happen that
2420 // more than one splitter will disappear in one iteration (bug 5998).
2421 for (; d.splitter_->count() > empty_twa; ) {
2422 TabWorkArea * twa = d.tabWorkArea(empty_twa);
2424 if (twa->count() == 0)
2427 setCurrentWorkArea(twa->currentWorkArea());
2428 if (!closeTabWorkArea(twa))
2436 bool GuiView::closeWorkArea(GuiWorkArea * wa, bool close_buffer)
2441 Buffer & buf = wa->bufferView().buffer();
2443 if (close_buffer && GuiViewPrivate::busyBuffers.contains(&buf)) {
2444 Alert::warning(_("Close document"),
2445 _("Document could not be closed because it is being processed by LyX."));
2450 return closeBuffer(buf);
2452 if (!inMultiTabs(wa))
2453 if (!saveBufferIfNeeded(buf, true))
2461 bool GuiView::closeBuffer(Buffer & buf)
2463 // If we are in a close_event all children will be closed in some time,
2464 // so no need to do it here. This will ensure that the children end up
2465 // in the session file in the correct order. If we close the master
2466 // buffer, we can close or release the child buffers here too.
2467 bool success = true;
2469 ListOfBuffers clist = buf.getChildren();
2470 ListOfBuffers::const_iterator it = clist.begin();
2471 ListOfBuffers::const_iterator const bend = clist.end();
2472 for (; it != bend; ++it) {
2473 // If a child is dirty, do not close
2474 // without user intervention
2475 //FIXME: should we look in other tabworkareas?
2476 Buffer * child_buf = *it;
2477 GuiWorkArea * child_wa = workArea(*child_buf);
2479 if (!closeWorkArea(child_wa, true)) {
2484 theBufferList().releaseChild(&buf, child_buf);
2488 // goto bookmark to update bookmark pit.
2489 //FIXME: we should update only the bookmarks related to this buffer!
2490 LYXERR(Debug::DEBUG, "GuiView::closeBuffer()");
2491 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
2492 guiApp->gotoBookmark(i+1, false, false);
2494 if (saveBufferIfNeeded(buf, false)) {
2495 buf.removeAutosaveFile();
2496 theBufferList().release(&buf);
2500 // open all children again to avoid a crash because of dangling
2501 // pointers (bug 6603)
2507 bool GuiView::closeTabWorkArea(TabWorkArea * twa)
2509 while (twa == d.currentTabWorkArea()) {
2510 twa->setCurrentIndex(twa->count()-1);
2512 GuiWorkArea * wa = twa->currentWorkArea();
2513 Buffer & b = wa->bufferView().buffer();
2515 // We only want to close the buffer if the same buffer is not visible
2516 // in another view, and if this is not a child and if we are closing
2517 // a view (not a tabgroup).
2518 bool const close_buffer =
2519 !inOtherView(b) && !b.parent() && closing_;
2521 if (!closeWorkArea(wa, close_buffer))
2528 bool GuiView::saveBufferIfNeeded(Buffer & buf, bool hiding)
2530 if (buf.isClean() || buf.paragraphs().empty())
2533 // Switch to this Buffer.
2538 if (buf.isUnnamed())
2539 file = from_utf8(buf.fileName().onlyFileName());
2541 file = buf.fileName().displayName(30);
2543 // Bring this window to top before asking questions.
2548 if (hiding && buf.isUnnamed()) {
2549 docstring const text = bformat(_("The document %1$s has not been "
2550 "saved yet.\n\nDo you want to save "
2551 "the document?"), file);
2552 ret = Alert::prompt(_("Save new document?"),
2553 text, 0, 1, _("&Save"), _("&Cancel"));
2557 docstring const text = bformat(_("The document %1$s has unsaved changes."
2558 "\n\nDo you want to save the document or discard the changes?"), file);
2559 ret = Alert::prompt(_("Save changed document?"),
2560 text, 0, 2, _("&Save"), _("&Discard"), _("&Cancel"));
2565 if (!saveBuffer(buf))
2569 // If we crash after this we could have no autosave file
2570 // but I guess this is really improbable (Jug).
2571 // Sometimes improbable things happen:
2572 // - see bug http://www.lyx.org/trac/ticket/6587 (ps)
2573 // buf.removeAutosaveFile();
2575 // revert all changes
2586 bool GuiView::inMultiTabs(GuiWorkArea * wa)
2588 Buffer & buf = wa->bufferView().buffer();
2590 for (int i = 0; i != d.splitter_->count(); ++i) {
2591 GuiWorkArea * wa_ = d.tabWorkArea(i)->workArea(buf);
2592 if (wa_ && wa_ != wa)
2595 return inOtherView(buf);
2599 bool GuiView::inOtherView(Buffer & buf)
2601 QList<int> const ids = guiApp->viewIds();
2603 for (int i = 0; i != ids.size(); ++i) {
2607 if (guiApp->view(ids[i]).workArea(buf))
2614 void GuiView::gotoNextOrPreviousBuffer(NextOrPrevious np)
2616 if (!documentBufferView())
2619 if (TabWorkArea * twa = d.currentTabWorkArea()) {
2620 Buffer * const curbuf = &documentBufferView()->buffer();
2621 int nwa = twa->count();
2622 for (int i = 0; i < nwa; ++i) {
2623 if (&workArea(i)->bufferView().buffer() == curbuf) {
2625 if (np == NEXTBUFFER)
2626 next_index = (i == nwa - 1 ? 0 : i + 1);
2628 next_index = (i == 0 ? nwa - 1 : i - 1);
2629 setBuffer(&workArea(next_index)->bufferView().buffer());
2637 /// make sure the document is saved
2638 static bool ensureBufferClean(Buffer * buffer)
2640 LASSERT(buffer, return false);
2641 if (buffer->isClean() && !buffer->isUnnamed())
2644 docstring const file = buffer->fileName().displayName(30);
2647 if (!buffer->isUnnamed()) {
2648 text = bformat(_("The document %1$s has unsaved "
2649 "changes.\n\nDo you want to save "
2650 "the document?"), file);
2651 title = _("Save changed document?");
2654 text = bformat(_("The document %1$s has not been "
2655 "saved yet.\n\nDo you want to save "
2656 "the document?"), file);
2657 title = _("Save new document?");
2659 int const ret = Alert::prompt(title, text, 0, 1, _("&Save"), _("&Cancel"));
2662 dispatch(FuncRequest(LFUN_BUFFER_WRITE));
2664 return buffer->isClean() && !buffer->isUnnamed();
2668 bool GuiView::reloadBuffer(Buffer & buf)
2670 Buffer::ReadStatus status = buf.reload();
2671 return status == Buffer::ReadSuccess;
2675 void GuiView::checkExternallyModifiedBuffers()
2677 BufferList::iterator bit = theBufferList().begin();
2678 BufferList::iterator const bend = theBufferList().end();
2679 for (; bit != bend; ++bit) {
2680 Buffer * buf = *bit;
2681 if (buf->fileName().exists()
2682 && buf->isExternallyModified(Buffer::checksum_method)) {
2683 docstring text = bformat(_("Document \n%1$s\n has been externally modified."
2684 " Reload now? Any local changes will be lost."),
2685 from_utf8(buf->absFileName()));
2686 int const ret = Alert::prompt(_("Reload externally changed document?"),
2687 text, 0, 1, _("&Reload"), _("&Cancel"));
2695 void GuiView::dispatchVC(FuncRequest const & cmd, DispatchResult & dr)
2697 Buffer * buffer = documentBufferView()
2698 ? &(documentBufferView()->buffer()) : 0;
2700 switch (cmd.action()) {
2701 case LFUN_VC_REGISTER:
2702 if (!buffer || !ensureBufferClean(buffer))
2704 if (!buffer->lyxvc().inUse()) {
2705 if (buffer->lyxvc().registrer()) {
2706 reloadBuffer(*buffer);
2707 dr.suppressMessageUpdate();
2712 case LFUN_VC_CHECK_IN:
2713 if (!buffer || !ensureBufferClean(buffer))
2715 if (buffer->lyxvc().inUse() && !buffer->isReadonly()) {
2716 dr.setMessage(buffer->lyxvc().checkIn());
2717 if (!dr.message().empty())
2718 reloadBuffer(*buffer);
2722 case LFUN_VC_CHECK_OUT:
2723 if (!buffer || !ensureBufferClean(buffer))
2725 if (buffer->lyxvc().inUse()) {
2726 dr.setMessage(buffer->lyxvc().checkOut());
2727 reloadBuffer(*buffer);
2731 case LFUN_VC_LOCKING_TOGGLE:
2732 LASSERT(buffer, return);
2733 if (!ensureBufferClean(buffer) || buffer->isReadonly())
2735 if (buffer->lyxvc().inUse()) {
2736 string res = buffer->lyxvc().lockingToggle();
2738 frontend::Alert::error(_("Revision control error."),
2739 _("Error when setting the locking property."));
2742 reloadBuffer(*buffer);
2747 case LFUN_VC_REVERT:
2748 LASSERT(buffer, return);
2749 if (buffer->lyxvc().revert()) {
2750 reloadBuffer(*buffer);
2751 dr.suppressMessageUpdate();
2755 case LFUN_VC_UNDO_LAST:
2756 LASSERT(buffer, return);
2757 buffer->lyxvc().undoLast();
2758 reloadBuffer(*buffer);
2759 dr.suppressMessageUpdate();
2762 case LFUN_VC_REPO_UPDATE:
2763 LASSERT(buffer, return);
2764 if (ensureBufferClean(buffer)) {
2765 dr.setMessage(buffer->lyxvc().repoUpdate());
2766 checkExternallyModifiedBuffers();
2770 case LFUN_VC_COMMAND: {
2771 string flag = cmd.getArg(0);
2772 if (buffer && contains(flag, 'R') && !ensureBufferClean(buffer))
2775 if (contains(flag, 'M')) {
2776 if (!Alert::askForText(message, _("LyX VC: Log Message")))
2779 string path = cmd.getArg(1);
2780 if (contains(path, "$$p") && buffer)
2781 path = subst(path, "$$p", buffer->filePath());
2782 LYXERR(Debug::LYXVC, "Directory: " << path);
2784 if (!pp.isReadableDirectory()) {
2785 lyxerr << _("Directory is not accessible.") << endl;
2788 support::PathChanger p(pp);
2790 string command = cmd.getArg(2);
2791 if (command.empty())
2794 command = subst(command, "$$i", buffer->absFileName());
2795 command = subst(command, "$$p", buffer->filePath());
2797 command = subst(command, "$$m", to_utf8(message));
2798 LYXERR(Debug::LYXVC, "Command: " << command);
2800 one.startscript(Systemcall::Wait, command);
2804 if (contains(flag, 'I'))
2805 buffer->markDirty();
2806 if (contains(flag, 'R'))
2807 reloadBuffer(*buffer);
2812 case LFUN_VC_COMPARE: {
2814 if (cmd.argument().empty()) {
2815 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "comparehistory"));
2819 string rev1 = cmd.getArg(0);
2823 if (!buffer->lyxvc().prepareFileRevision(rev1, f1))
2826 if (isStrInt(rev1) && convert<int>(rev1) <= 0) {
2827 f2 = buffer->absFileName();
2829 string rev2 = cmd.getArg(1);
2833 if (!buffer->lyxvc().prepareFileRevision(rev2, f2))
2837 LYXERR(Debug::LYXVC, "Launching comparison for fetched revisions:\n" <<
2838 f1 << "\n" << f2 << "\n" );
2839 string par = "compare run " + quoteName(f1) + " " + quoteName(f2);
2840 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, par));
2850 void GuiView::openChildDocument(string const & fname)
2852 LASSERT(documentBufferView(), return);
2853 Buffer & buffer = documentBufferView()->buffer();
2854 FileName const filename = support::makeAbsPath(fname, buffer.filePath());
2855 documentBufferView()->saveBookmark(false);
2857 if (theBufferList().exists(filename)) {
2858 child = theBufferList().getBuffer(filename);
2861 message(bformat(_("Opening child document %1$s..."),
2862 makeDisplayPath(filename.absFileName())));
2863 child = loadDocument(filename, false);
2865 // Set the parent name of the child document.
2866 // This makes insertion of citations and references in the child work,
2867 // when the target is in the parent or another child document.
2869 child->setParent(&buffer);
2873 bool GuiView::goToFileRow(string const & argument)
2877 size_t i = argument.find_last_of(' ');
2878 if (i != string::npos) {
2879 file_name = os::internal_path(trim(argument.substr(0, i)));
2880 istringstream is(argument.substr(i + 1));
2885 if (i == string::npos) {
2886 LYXERR0("Wrong argument: " << argument);
2890 string const abstmp = package().temp_dir().absFileName();
2891 string const realtmp = package().temp_dir().realPath();
2892 // We have to use os::path_prefix_is() here, instead of
2893 // simply prefixIs(), because the file name comes from
2894 // an external application and may need case adjustment.
2895 if (os::path_prefix_is(file_name, abstmp, os::CASE_ADJUSTED)
2896 || os::path_prefix_is(file_name, realtmp, os::CASE_ADJUSTED)) {
2897 // Needed by inverse dvi search. If it is a file
2898 // in tmpdir, call the apropriated function.
2899 // If tmpdir is a symlink, we may have the real
2900 // path passed back, so we correct for that.
2901 if (!prefixIs(file_name, abstmp))
2902 file_name = subst(file_name, realtmp, abstmp);
2903 buf = theBufferList().getBufferFromTmp(file_name);
2905 // Must replace extension of the file to be .lyx
2906 // and get full path
2907 FileName const s = fileSearch(string(),
2908 support::changeExtension(file_name, ".lyx"), "lyx");
2909 // Either change buffer or load the file
2910 if (theBufferList().exists(s))
2911 buf = theBufferList().getBuffer(s);
2912 else if (s.exists()) {
2913 buf = loadDocument(s);
2918 _("File does not exist: %1$s"),
2919 makeDisplayPath(file_name)));
2924 documentBufferView()->setCursorFromRow(row);
2929 #if (QT_VERSION >= 0x040400)
2931 docstring GuiView::GuiViewPrivate::runAndDestroy(const T& func, Buffer const * orig, Buffer * buffer, string const & format, string const & msg)
2933 bool const update_unincluded =
2934 buffer->params().maintain_unincluded_children
2935 && !buffer->params().getIncludedChildren().empty();
2936 bool const success = func(format, update_unincluded);
2938 busyBuffers.remove(orig);
2939 if (msg == "preview") {
2941 ? bformat(_("Successful preview of format: %1$s"), from_utf8(format))
2942 : bformat(_("Error while previewing format: %1$s"), from_utf8(format));
2945 ? bformat(_("Successful export to format: %1$s"), from_utf8(format))
2946 : bformat(_("Error while exporting format: %1$s"), from_utf8(format));
2950 docstring GuiView::GuiViewPrivate::compileAndDestroy(Buffer const * orig, Buffer * buffer, string const & format)
2952 bool (Buffer::* mem_func)(std::string const &, bool, bool) const = &Buffer::doExport;
2953 return runAndDestroy(bind(mem_func, buffer, _1, true, _2), orig, buffer, format, "export");
2957 docstring GuiView::GuiViewPrivate::exportAndDestroy(Buffer const * orig, Buffer * buffer, string const & format)
2959 bool (Buffer::* mem_func)(std::string const &, bool, bool) const = &Buffer::doExport;
2960 return runAndDestroy(bind(mem_func, buffer, _1, false, _2), orig, buffer, format, "export");
2964 docstring GuiView::GuiViewPrivate::previewAndDestroy(Buffer const * orig, Buffer * buffer, string const & format)
2966 bool(Buffer::* mem_func)(std::string const &, bool) const = &Buffer::preview;
2967 return runAndDestroy(bind(mem_func, buffer, _1, _2), orig, buffer, format, "preview");
2972 // not used, but the linker needs them
2974 docstring GuiView::GuiViewPrivate::compileAndDestroy(
2975 Buffer const *, Buffer *, string const &)
2981 docstring GuiView::GuiViewPrivate::exportAndDestroy(
2982 Buffer const *, Buffer *, string const &)
2988 docstring GuiView::GuiViewPrivate::previewAndDestroy(
2989 Buffer const *, Buffer *, string const &)
2997 bool GuiView::GuiViewPrivate::asyncBufferProcessing(
2998 string const & argument,
2999 Buffer const * used_buffer,
3000 docstring const & msg,
3001 docstring (*asyncFunc)(Buffer const *, Buffer *, string const &),
3002 bool (Buffer::*syncFunc)(string const &, bool, bool) const,
3003 bool (Buffer::*previewFunc)(string const &, bool) const)
3008 string format = argument;
3010 format = used_buffer->getDefaultOutputFormat();
3012 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
3014 progress_->clearMessages();
3017 GuiViewPrivate::busyBuffers.insert(used_buffer);
3018 QFuture<docstring> f = QtConcurrent::run(
3021 used_buffer->clone(),
3023 setPreviewFuture(f);
3024 last_export_format = used_buffer->bufferFormat();
3027 // We are asynchronous, so we don't know here anything about the success
3031 // TODO check here if it breaks exporting with Qt < 4.4
3032 bool const update_unincluded =
3033 used_buffer->params().maintain_unincluded_children &&
3034 !used_buffer->params().getIncludedChildren().empty();
3035 return (used_buffer->*syncFunc)(format, true, update_unincluded);
3036 } else if (previewFunc) {
3037 return (used_buffer->*previewFunc)(format, false);
3044 void GuiView::dispatchToBufferView(FuncRequest const & cmd, DispatchResult & dr)
3046 BufferView * bv = currentBufferView();
3049 // Let the current BufferView dispatch its own actions.
3050 bv->dispatch(cmd, dr);
3051 if (dr.dispatched())
3054 // Try with the document BufferView dispatch if any.
3055 BufferView * doc_bv = documentBufferView();
3057 doc_bv->dispatch(cmd, dr);
3058 if (dr.dispatched())
3062 // Then let the current Cursor dispatch its own actions.
3063 bv->cursor().dispatch(cmd);
3065 // update completion. We do it here and not in
3066 // processKeySym to avoid another redraw just for a
3067 // changed inline completion
3068 if (cmd.origin() == FuncRequest::KEYBOARD) {
3069 if (cmd.action() == LFUN_SELF_INSERT
3070 || (cmd.action() == LFUN_ERT_INSERT && bv->cursor().inMathed()))
3071 updateCompletion(bv->cursor(), true, true);
3072 else if (cmd.action() == LFUN_CHAR_DELETE_BACKWARD)
3073 updateCompletion(bv->cursor(), false, true);
3075 updateCompletion(bv->cursor(), false, false);
3078 dr = bv->cursor().result();
3082 void GuiView::dispatch(FuncRequest const & cmd, DispatchResult & dr)
3084 BufferView * bv = currentBufferView();
3085 // By default we won't need any update.
3086 dr.screenUpdate(Update::None);
3087 // assume cmd will be dispatched
3088 dr.dispatched(true);
3090 Buffer * doc_buffer = documentBufferView()
3091 ? &(documentBufferView()->buffer()) : 0;
3093 if (cmd.origin() == FuncRequest::TOC) {
3094 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
3095 // FIXME: do we need to pass a DispatchResult object here?
3096 toc->doDispatch(bv->cursor(), cmd);
3100 string const argument = to_utf8(cmd.argument());
3102 switch(cmd.action()) {
3103 case LFUN_BUFFER_CHILD_OPEN:
3104 openChildDocument(to_utf8(cmd.argument()));
3107 case LFUN_BUFFER_IMPORT:
3108 importDocument(to_utf8(cmd.argument()));
3111 case LFUN_BUFFER_EXPORT: {
3114 // GCC only sees strfwd.h when building merged
3115 if (::lyx::operator==(cmd.argument(), "custom")) {
3116 dispatch(FuncRequest(LFUN_DIALOG_SHOW, "sendto"), dr);
3119 #if QT_VERSION < 0x040400
3120 if (!doc_buffer->doExport(argument, false)) {
3122 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
3126 /* TODO/Review: Is it a problem to also export the children?
3127 See the update_unincluded flag */
3128 d.asyncBufferProcessing(argument,
3131 &GuiViewPrivate::exportAndDestroy,
3134 // TODO Inform user about success
3139 case LFUN_BUFFER_UPDATE: {
3140 d.asyncBufferProcessing(argument,
3143 &GuiViewPrivate::compileAndDestroy,
3148 case LFUN_BUFFER_VIEW: {
3149 d.asyncBufferProcessing(argument,
3151 _("Previewing ..."),
3152 &GuiViewPrivate::previewAndDestroy,
3157 case LFUN_MASTER_BUFFER_UPDATE: {
3158 d.asyncBufferProcessing(argument,
3159 (doc_buffer ? doc_buffer->masterBuffer() : 0),
3161 &GuiViewPrivate::compileAndDestroy,
3166 case LFUN_MASTER_BUFFER_VIEW: {
3167 d.asyncBufferProcessing(argument,
3168 (doc_buffer ? doc_buffer->masterBuffer() : 0),
3170 &GuiViewPrivate::previewAndDestroy,
3171 0, &Buffer::preview);
3174 case LFUN_BUFFER_SWITCH: {
3175 string const file_name = to_utf8(cmd.argument());
3176 if (!FileName::isAbsolute(file_name)) {
3178 dr.setMessage(_("Absolute filename expected."));
3182 Buffer * buffer = theBufferList().getBuffer(FileName(file_name));
3185 dr.setMessage(_("Document not loaded"));
3189 // Do we open or switch to the buffer in this view ?
3190 if (workArea(*buffer)
3191 || lyxrc.open_buffers_in_tabs || !documentBufferView()) {
3196 // Look for the buffer in other views
3197 QList<int> const ids = guiApp->viewIds();
3199 for (; i != ids.size(); ++i) {
3200 GuiView & gv = guiApp->view(ids[i]);
3201 if (gv.workArea(*buffer)) {
3202 gv.activateWindow();
3203 gv.setBuffer(buffer);
3208 // If necessary, open a new window as a last resort
3209 if (i == ids.size()) {
3210 lyx::dispatch(FuncRequest(LFUN_WINDOW_NEW));
3216 case LFUN_BUFFER_NEXT:
3217 gotoNextOrPreviousBuffer(NEXTBUFFER);
3220 case LFUN_BUFFER_PREVIOUS:
3221 gotoNextOrPreviousBuffer(PREVBUFFER);
3224 case LFUN_COMMAND_EXECUTE: {
3225 bool const show_it = cmd.argument() != "off";
3226 // FIXME: this is a hack, "minibuffer" should not be
3228 if (GuiToolbar * t = toolbar("minibuffer")) {
3229 t->setVisible(show_it);
3230 if (show_it && t->commandBuffer())
3231 t->commandBuffer()->setFocus();
3235 case LFUN_DROP_LAYOUTS_CHOICE:
3236 d.layout_->showPopup();
3239 case LFUN_MENU_OPEN:
3240 if (QMenu * menu = guiApp->menus().menu(toqstr(cmd.argument()), *this))
3241 menu->exec(QCursor::pos());
3244 case LFUN_FILE_INSERT:
3245 insertLyXFile(cmd.argument());
3248 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
3249 insertPlaintextFile(cmd.argument(), true);
3252 case LFUN_FILE_INSERT_PLAINTEXT:
3253 insertPlaintextFile(cmd.argument(), false);
3256 case LFUN_BUFFER_RELOAD: {
3257 LASSERT(doc_buffer, break);
3260 if (!doc_buffer->isClean()) {
3261 docstring const file =
3262 makeDisplayPath(doc_buffer->absFileName(), 20);
3263 docstring text = bformat(_("Any changes will be lost. "
3264 "Are you sure you want to revert to the saved version "
3265 "of the document %1$s?"), file);
3266 ret = Alert::prompt(_("Revert to saved document?"),
3267 text, 1, 1, _("&Revert"), _("&Cancel"));
3271 doc_buffer->markClean();
3272 reloadBuffer(*doc_buffer);
3273 dr.forceBufferUpdate();
3278 case LFUN_BUFFER_WRITE:
3279 LASSERT(doc_buffer, break);
3280 saveBuffer(*doc_buffer);
3283 case LFUN_BUFFER_WRITE_AS:
3284 LASSERT(doc_buffer, break);
3285 renameBuffer(*doc_buffer, cmd.argument());
3288 case LFUN_BUFFER_WRITE_ALL: {
3289 Buffer * first = theBufferList().first();
3292 message(_("Saving all documents..."));
3293 // We cannot use a for loop as the buffer list cycles.
3296 if (!b->isClean()) {
3298 LYXERR(Debug::ACTION, "Saved " << b->absFileName());
3300 b = theBufferList().next(b);
3301 } while (b != first);
3302 dr.setMessage(_("All documents saved."));
3306 case LFUN_BUFFER_CLOSE:
3310 case LFUN_BUFFER_CLOSE_ALL:
3314 case LFUN_TOOLBAR_TOGGLE: {
3315 string const name = cmd.getArg(0);
3316 if (GuiToolbar * t = toolbar(name))
3321 case LFUN_DIALOG_UPDATE: {
3322 string const name = to_utf8(cmd.argument());
3323 if (name == "prefs" || name == "document")
3324 updateDialog(name, string());
3325 else if (name == "paragraph")
3326 lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
3327 else if (currentBufferView()) {
3328 Inset * inset = currentBufferView()->editedInset(name);
3329 // Can only update a dialog connected to an existing inset
3331 // FIXME: get rid of this indirection; GuiView ask the inset
3332 // if he is kind enough to update itself...
3333 FuncRequest fr(LFUN_INSET_DIALOG_UPDATE, cmd.argument());
3334 //FIXME: pass DispatchResult here?
3335 inset->dispatch(currentBufferView()->cursor(), fr);
3341 case LFUN_DIALOG_TOGGLE: {
3342 FuncCode const func_code = isDialogVisible(cmd.getArg(0))
3343 ? LFUN_DIALOG_HIDE : LFUN_DIALOG_SHOW;
3344 dispatch(FuncRequest(func_code, cmd.argument()), dr);
3348 case LFUN_DIALOG_DISCONNECT_INSET:
3349 disconnectDialog(to_utf8(cmd.argument()));
3352 case LFUN_DIALOG_HIDE: {
3353 guiApp->hideDialogs(to_utf8(cmd.argument()), 0);
3357 case LFUN_DIALOG_SHOW: {
3358 string const name = cmd.getArg(0);
3359 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
3361 if (name == "character") {
3362 data = freefont2string();
3364 showDialog("character", data);
3365 } else if (name == "latexlog") {
3366 Buffer::LogType type;
3367 string const logfile = doc_buffer->logName(&type);
3369 case Buffer::latexlog:
3372 case Buffer::buildlog:
3376 data += Lexer::quoteString(logfile);
3377 showDialog("log", data);
3378 } else if (name == "vclog") {
3379 string const data = "vc " +
3380 Lexer::quoteString(doc_buffer->lyxvc().getLogFile());
3381 showDialog("log", data);
3382 } else if (name == "symbols") {
3383 data = bv->cursor().getEncoding()->name();
3385 showDialog("symbols", data);
3387 } else if (name == "prefs" && isFullScreen()) {
3388 lfunUiToggle("fullscreen");
3389 showDialog("prefs", data);
3391 showDialog(name, data);
3396 dr.setMessage(cmd.argument());
3399 case LFUN_UI_TOGGLE: {
3400 string arg = cmd.getArg(0);
3401 if (!lfunUiToggle(arg)) {
3402 docstring const msg = "ui-toggle " + _("%1$s unknown command!");
3403 dr.setMessage(bformat(msg, from_utf8(arg)));
3405 // Make sure the keyboard focus stays in the work area.
3410 case LFUN_SPLIT_VIEW: {
3411 LASSERT(doc_buffer, break);
3412 string const orientation = cmd.getArg(0);
3413 d.splitter_->setOrientation(orientation == "vertical"
3414 ? Qt::Vertical : Qt::Horizontal);
3415 TabWorkArea * twa = addTabWorkArea();
3416 GuiWorkArea * wa = twa->addWorkArea(*doc_buffer, *this);
3417 setCurrentWorkArea(wa);
3420 case LFUN_CLOSE_TAB_GROUP:
3421 if (TabWorkArea * twa = d.currentTabWorkArea()) {
3422 closeTabWorkArea(twa);
3423 d.current_work_area_ = 0;
3424 twa = d.currentTabWorkArea();
3425 // Switch to the next GuiWorkArea in the found TabWorkArea.
3427 // Make sure the work area is up to date.
3428 setCurrentWorkArea(twa->currentWorkArea());
3430 setCurrentWorkArea(0);
3435 case LFUN_COMPLETION_INLINE:
3436 if (d.current_work_area_)
3437 d.current_work_area_->completer().showInline();
3440 case LFUN_COMPLETION_POPUP:
3441 if (d.current_work_area_)
3442 d.current_work_area_->completer().showPopup();
3446 case LFUN_COMPLETION_COMPLETE:
3447 if (d.current_work_area_)
3448 d.current_work_area_->completer().tab();
3451 case LFUN_COMPLETION_CANCEL:
3452 if (d.current_work_area_) {
3453 if (d.current_work_area_->completer().popupVisible())
3454 d.current_work_area_->completer().hidePopup();
3456 d.current_work_area_->completer().hideInline();
3460 case LFUN_COMPLETION_ACCEPT:
3461 if (d.current_work_area_)
3462 d.current_work_area_->completer().activate();
3465 case LFUN_BUFFER_ZOOM_IN:
3466 case LFUN_BUFFER_ZOOM_OUT:
3467 if (cmd.argument().empty()) {
3468 if (cmd.action() == LFUN_BUFFER_ZOOM_IN)
3473 lyxrc.zoom += convert<int>(cmd.argument());
3475 if (lyxrc.zoom < 10)
3478 // The global QPixmapCache is used in GuiPainter to cache text
3479 // painting so we must reset it.
3480 QPixmapCache::clear();
3481 guiApp->fontLoader().update();
3482 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
3485 case LFUN_VC_REGISTER:
3486 case LFUN_VC_CHECK_IN:
3487 case LFUN_VC_CHECK_OUT:
3488 case LFUN_VC_REPO_UPDATE:
3489 case LFUN_VC_LOCKING_TOGGLE:
3490 case LFUN_VC_REVERT:
3491 case LFUN_VC_UNDO_LAST:
3492 case LFUN_VC_COMMAND:
3493 case LFUN_VC_COMPARE:
3494 dispatchVC(cmd, dr);
3497 case LFUN_SERVER_GOTO_FILE_ROW:
3498 goToFileRow(to_utf8(cmd.argument()));
3501 case LFUN_FORWARD_SEARCH: {
3502 Buffer const * doc_master = doc_buffer->masterBuffer();
3503 FileName const path(doc_master->temppath());
3504 string const texname = doc_master->isChild(doc_buffer)
3505 ? DocFileName(changeExtension(
3506 doc_buffer->absFileName(),
3507 "tex")).mangledFileName()
3508 : doc_buffer->latexName();
3509 string const mastername =
3510 removeExtension(doc_master->latexName());
3511 FileName const dviname(addName(path.absFileName(),
3512 addExtension(mastername, "dvi")));
3513 FileName const pdfname(addName(path.absFileName(),
3514 addExtension(mastername, "pdf")));
3515 if (!dviname.exists() && !pdfname.exists()) {
3516 dr.setMessage(_("Please, preview the document first."));
3519 string outname = dviname.onlyFileName();
3520 string command = lyxrc.forward_search_dvi;
3521 if (!dviname.exists() ||
3522 pdfname.lastModified() > dviname.lastModified()) {
3523 outname = pdfname.onlyFileName();
3524 command = lyxrc.forward_search_pdf;
3527 int row = doc_buffer->texrow().getRowFromIdPos(bv->cursor().paragraph().id(), bv->cursor().pos());
3528 LYXERR(Debug::ACTION, "Forward search: row:" << row
3529 << " id:" << bv->cursor().paragraph().id());
3530 if (!row || command.empty()) {
3531 dr.setMessage(_("Couldn't proceed."));
3534 string texrow = convert<string>(row);
3536 command = subst(command, "$$n", texrow);
3537 command = subst(command, "$$t", texname);
3538 command = subst(command, "$$o", outname);
3540 PathChanger p(path);
3542 one.startscript(Systemcall::DontWait, command);
3546 // The LFUN must be for one of BufferView, Buffer or Cursor;
3548 dispatchToBufferView(cmd, dr);
3552 // Part of automatic menu appearance feature.
3553 if (isFullScreen()) {
3554 if (menuBar()->isVisible() && lyxrc.full_screen_menubar)
3556 if (statusBar()->isVisible())
3557 statusBar()->hide();
3562 bool GuiView::lfunUiToggle(string const & ui_component)
3564 if (ui_component == "scrollbar") {
3565 // hide() is of no help
3566 if (d.current_work_area_->verticalScrollBarPolicy() ==
3567 Qt::ScrollBarAlwaysOff)
3569 d.current_work_area_->setVerticalScrollBarPolicy(
3570 Qt::ScrollBarAsNeeded);
3572 d.current_work_area_->setVerticalScrollBarPolicy(
3573 Qt::ScrollBarAlwaysOff);
3574 } else if (ui_component == "statusbar") {
3575 statusBar()->setVisible(!statusBar()->isVisible());
3576 } else if (ui_component == "menubar") {
3577 menuBar()->setVisible(!menuBar()->isVisible());
3579 #if QT_VERSION >= 0x040300
3580 if (ui_component == "frame") {
3582 getContentsMargins(&l, &t, &r, &b);
3583 //are the frames in default state?
3584 d.current_work_area_->setFrameStyle(QFrame::NoFrame);
3586 setContentsMargins(-2, -2, -2, -2);
3588 setContentsMargins(0, 0, 0, 0);
3592 if (ui_component == "fullscreen") {
3600 void GuiView::toggleFullScreen()
3602 if (isFullScreen()) {
3603 for (int i = 0; i != d.splitter_->count(); ++i)
3604 d.tabWorkArea(i)->setFullScreen(false);
3605 #if QT_VERSION >= 0x040300
3606 setContentsMargins(0, 0, 0, 0);
3608 setWindowState(windowState() ^ Qt::WindowFullScreen);
3611 statusBar()->show();
3614 hideDialogs("prefs", 0);
3615 for (int i = 0; i != d.splitter_->count(); ++i)
3616 d.tabWorkArea(i)->setFullScreen(true);
3617 #if QT_VERSION >= 0x040300
3618 setContentsMargins(-2, -2, -2, -2);
3621 setWindowState(windowState() ^ Qt::WindowFullScreen);
3622 statusBar()->hide();
3623 if (lyxrc.full_screen_menubar)
3625 if (lyxrc.full_screen_toolbars) {
3626 ToolbarMap::iterator end = d.toolbars_.end();
3627 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
3632 // give dialogs like the TOC a chance to adapt
3637 Buffer const * GuiView::updateInset(Inset const * inset)
3642 Buffer const * inset_buffer = &(inset->buffer());
3644 for (int i = 0; i != d.splitter_->count(); ++i) {
3645 GuiWorkArea * wa = d.tabWorkArea(i)->currentWorkArea();
3648 Buffer const * buffer = &(wa->bufferView().buffer());
3649 if (inset_buffer == buffer)
3650 wa->scheduleRedraw();
3652 return inset_buffer;
3656 void GuiView::restartCursor()
3658 /* When we move around, or type, it's nice to be able to see
3659 * the cursor immediately after the keypress.
3661 if (d.current_work_area_)
3662 d.current_work_area_->startBlinkingCursor();
3664 // Take this occasion to update the other GUI elements.
3670 void GuiView::updateCompletion(Cursor & cur, bool start, bool keep)
3672 if (d.current_work_area_)
3673 d.current_work_area_->completer().updateVisibility(cur, start, keep);
3678 // This list should be kept in sync with the list of insets in
3679 // src/insets/Inset.cpp. I.e., if a dialog goes with an inset, the
3680 // dialog should have the same name as the inset.
3681 // Changes should be also recorded in LFUN_DIALOG_SHOW doxygen
3682 // docs in LyXAction.cpp.
3684 char const * const dialognames[] = {
3686 "aboutlyx", "bibitem", "bibtex", "box", "branch", "changes", "character",
3687 "citation", "compare", "comparehistory", "document", "errorlist", "ert",
3688 "external", "file", "findreplace", "findreplaceadv", "float", "graphics",
3689 "href", "include", "index", "index_print", "info", "listings", "label", "line",
3690 "log", "mathdelimiter", "mathmatrix", "mathspace", "nomenclature",
3691 "nomencl_print", "note", "paragraph", "phantom", "prefs", "print", "ref",
3692 "sendto", "space", "spellchecker", "symbols", "tabular", "tabularcreate",
3693 "thesaurus", "texinfo", "toc", "view-source", "vspace", "wrap", "progress"};
3695 char const * const * const end_dialognames =
3696 dialognames + (sizeof(dialognames) / sizeof(char *));
3700 cmpCStr(char const * name) : name_(name) {}
3701 bool operator()(char const * other) {
3702 return strcmp(other, name_) == 0;
3709 bool isValidName(string const & name)
3711 return find_if(dialognames, end_dialognames,
3712 cmpCStr(name.c_str())) != end_dialognames;
3718 void GuiView::resetDialogs()
3720 // Make sure that no LFUN uses any GuiView.
3721 guiApp->setCurrentView(0);
3725 constructToolbars();
3726 guiApp->menus().fillMenuBar(menuBar(), this, false);
3727 d.layout_->updateContents(true);
3728 // Now update controls with current buffer.
3729 guiApp->setCurrentView(this);
3735 Dialog * GuiView::findOrBuild(string const & name, bool hide_it)
3737 if (!isValidName(name))
3740 map<string, DialogPtr>::iterator it = d.dialogs_.find(name);
3742 if (it != d.dialogs_.end()) {
3744 it->second->hideView();
3745 return it->second.get();
3748 Dialog * dialog = build(name);
3749 d.dialogs_[name].reset(dialog);
3750 if (lyxrc.allow_geometry_session)
3751 dialog->restoreSession();
3758 void GuiView::showDialog(string const & name, string const & data,
3761 triggerShowDialog(toqstr(name), toqstr(data), inset);
3765 void GuiView::doShowDialog(QString const & qname, QString const & qdata,
3771 const string name = fromqstr(qname);
3772 const string data = fromqstr(qdata);
3776 Dialog * dialog = findOrBuild(name, false);
3778 bool const visible = dialog->isVisibleView();
3779 dialog->showData(data);
3780 if (inset && currentBufferView())
3781 currentBufferView()->editInset(name, inset);
3782 // We only set the focus to the new dialog if it was not yet
3783 // visible in order not to change the existing previous behaviour
3785 // activateWindow is needed for floating dockviews
3786 dialog->asQWidget()->raise();
3787 dialog->asQWidget()->activateWindow();
3788 dialog->asQWidget()->setFocus();
3792 catch (ExceptionMessage const & ex) {
3800 bool GuiView::isDialogVisible(string const & name) const
3802 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3803 if (it == d.dialogs_.end())
3805 return it->second.get()->isVisibleView() && !it->second.get()->isClosing();
3809 void GuiView::hideDialog(string const & name, Inset * inset)
3811 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3812 if (it == d.dialogs_.end())
3816 if (!currentBufferView())
3818 if (inset != currentBufferView()->editedInset(name))
3822 Dialog * const dialog = it->second.get();
3823 if (dialog->isVisibleView())
3825 if (currentBufferView())
3826 currentBufferView()->editInset(name, 0);
3830 void GuiView::disconnectDialog(string const & name)
3832 if (!isValidName(name))
3834 if (currentBufferView())
3835 currentBufferView()->editInset(name, 0);
3839 void GuiView::hideAll() const
3841 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
3842 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3844 for(; it != end; ++it)
3845 it->second->hideView();
3849 void GuiView::updateDialogs()
3851 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
3852 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3854 for(; it != end; ++it) {
3855 Dialog * dialog = it->second.get();
3857 if (dialog->needBufferOpen() && !documentBufferView())
3858 hideDialog(fromqstr(dialog->name()), 0);
3859 else if (dialog->isVisibleView())
3860 dialog->checkStatus();
3867 Dialog * createDialog(GuiView & lv, string const & name);
3869 // will be replaced by a proper factory...
3870 Dialog * createGuiAbout(GuiView & lv);
3871 Dialog * createGuiBibtex(GuiView & lv);
3872 Dialog * createGuiChanges(GuiView & lv);
3873 Dialog * createGuiCharacter(GuiView & lv);
3874 Dialog * createGuiCitation(GuiView & lv);
3875 Dialog * createGuiCompare(GuiView & lv);
3876 Dialog * createGuiCompareHistory(GuiView & lv);
3877 Dialog * createGuiDelimiter(GuiView & lv);
3878 Dialog * createGuiDocument(GuiView & lv);
3879 Dialog * createGuiErrorList(GuiView & lv);
3880 Dialog * createGuiExternal(GuiView & lv);
3881 Dialog * createGuiGraphics(GuiView & lv);
3882 Dialog * createGuiInclude(GuiView & lv);
3883 Dialog * createGuiIndex(GuiView & lv);
3884 Dialog * createGuiListings(GuiView & lv);
3885 Dialog * createGuiLog(GuiView & lv);
3886 Dialog * createGuiMathMatrix(GuiView & lv);
3887 Dialog * createGuiNote(GuiView & lv);
3888 Dialog * createGuiParagraph(GuiView & lv);
3889 Dialog * createGuiPhantom(GuiView & lv);
3890 Dialog * createGuiPreferences(GuiView & lv);
3891 Dialog * createGuiPrint(GuiView & lv);
3892 Dialog * createGuiPrintindex(GuiView & lv);
3893 Dialog * createGuiRef(GuiView & lv);
3894 Dialog * createGuiSearch(GuiView & lv);
3895 Dialog * createGuiSearchAdv(GuiView & lv);
3896 Dialog * createGuiSendTo(GuiView & lv);
3897 Dialog * createGuiShowFile(GuiView & lv);
3898 Dialog * createGuiSpellchecker(GuiView & lv);
3899 Dialog * createGuiSymbols(GuiView & lv);
3900 Dialog * createGuiTabularCreate(GuiView & lv);
3901 Dialog * createGuiTexInfo(GuiView & lv);
3902 Dialog * createGuiToc(GuiView & lv);
3903 Dialog * createGuiThesaurus(GuiView & lv);
3904 Dialog * createGuiViewSource(GuiView & lv);
3905 Dialog * createGuiWrap(GuiView & lv);
3906 Dialog * createGuiProgressView(GuiView & lv);
3910 Dialog * GuiView::build(string const & name)
3912 LASSERT(isValidName(name), return 0);
3914 Dialog * dialog = createDialog(*this, name);
3918 if (name == "aboutlyx")
3919 return createGuiAbout(*this);
3920 if (name == "bibtex")
3921 return createGuiBibtex(*this);
3922 if (name == "changes")
3923 return createGuiChanges(*this);
3924 if (name == "character")
3925 return createGuiCharacter(*this);
3926 if (name == "citation")
3927 return createGuiCitation(*this);
3928 if (name == "compare")
3929 return createGuiCompare(*this);
3930 if (name == "comparehistory")
3931 return createGuiCompareHistory(*this);
3932 if (name == "document")
3933 return createGuiDocument(*this);
3934 if (name == "errorlist")
3935 return createGuiErrorList(*this);
3936 if (name == "external")
3937 return createGuiExternal(*this);
3939 return createGuiShowFile(*this);
3940 if (name == "findreplace")
3941 return createGuiSearch(*this);
3942 if (name == "findreplaceadv")
3943 return createGuiSearchAdv(*this);
3944 if (name == "graphics")
3945 return createGuiGraphics(*this);
3946 if (name == "include")
3947 return createGuiInclude(*this);
3948 if (name == "index")
3949 return createGuiIndex(*this);
3950 if (name == "index_print")
3951 return createGuiPrintindex(*this);
3952 if (name == "listings")
3953 return createGuiListings(*this);
3955 return createGuiLog(*this);
3956 if (name == "mathdelimiter")
3957 return createGuiDelimiter(*this);
3958 if (name == "mathmatrix")
3959 return createGuiMathMatrix(*this);
3961 return createGuiNote(*this);
3962 if (name == "paragraph")
3963 return createGuiParagraph(*this);
3964 if (name == "phantom")
3965 return createGuiPhantom(*this);
3966 if (name == "prefs")
3967 return createGuiPreferences(*this);
3968 if (name == "print")
3969 return createGuiPrint(*this);
3971 return createGuiRef(*this);
3972 if (name == "sendto")
3973 return createGuiSendTo(*this);
3974 if (name == "spellchecker")
3975 return createGuiSpellchecker(*this);
3976 if (name == "symbols")
3977 return createGuiSymbols(*this);
3978 if (name == "tabularcreate")
3979 return createGuiTabularCreate(*this);
3980 if (name == "texinfo")
3981 return createGuiTexInfo(*this);
3982 if (name == "thesaurus")
3983 return createGuiThesaurus(*this);
3985 return createGuiToc(*this);
3986 if (name == "view-source")
3987 return createGuiViewSource(*this);
3989 return createGuiWrap(*this);
3990 if (name == "progress")
3991 return createGuiProgressView(*this);
3997 } // namespace frontend
4000 #include "moc_GuiView.cpp"