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 "FileDialog.h"
20 #include "FontLoader.h"
21 #include "GuiApplication.h"
22 #include "GuiCommandBuffer.h"
23 #include "GuiCompleter.h"
24 #include "GuiWorkArea.h"
25 #include "GuiKeySymbol.h"
27 #include "GuiToolbar.h"
28 #include "LayoutBox.h"
32 #include "qt_helpers.h"
34 #include "frontends/alert.h"
36 #include "buffer_funcs.h"
38 #include "BufferList.h"
39 #include "BufferParams.h"
40 #include "BufferView.h"
41 #include "Converter.h"
43 #include "CutAndPaste.h"
45 #include "ErrorList.h"
47 #include "FuncStatus.h"
48 #include "FuncRequest.h"
52 #include "LyXAction.h"
57 #include "Paragraph.h"
58 #include "SpellChecker.h"
59 #include "TextClass.h"
64 #include "support/convert.h"
65 #include "support/debug.h"
66 #include "support/ExceptionMessage.h"
67 #include "support/FileName.h"
68 #include "support/filetools.h"
69 #include "support/gettext.h"
70 #include "support/filetools.h"
71 #include "support/ForkedCalls.h"
72 #include "support/lassert.h"
73 #include "support/lstrings.h"
74 #include "support/os.h"
75 #include "support/Package.h"
76 #include "support/Path.h"
77 #include "support/Systemcall.h"
78 #include "support/Timeout.h"
81 #include <QApplication>
82 #include <QCloseEvent>
84 #include <QDesktopWidget>
85 #include <QDragEnterEvent>
92 #include <QPixmapCache>
94 #include <QPushButton>
98 #include <QStackedWidget>
103 #include <QScrollBar>
105 // QtConcurrent was introduced in Qt 4.4
106 #if (QT_VERSION >= 0x040400)
108 #include <QFutureWatcher>
109 #include <QtConcurrentRun>
112 #include <boost/bind.hpp>
116 #ifdef HAVE_SYS_TIME_H
117 # include <sys/time.h>
124 using namespace lyx::support;
131 class BackgroundWidget : public QWidget
136 LYXERR(Debug::GUI, "show banner: " << lyxrc.show_banner);
137 /// The text to be written on top of the pixmap
138 QString const text = lyx_version ?
139 qt_("version ") + lyx_version : qt_("unknown version");
140 splash_ = getPixmap("images/", "banner", "png");
142 QPainter pain(&splash_);
143 pain.setPen(QColor(0, 0, 0));
145 // The font used to display the version info
146 font.setStyleHint(QFont::SansSerif);
147 font.setWeight(QFont::Bold);
148 font.setPointSize(int(toqstr(lyxrc.font_sizes[FONT_SIZE_LARGE]).toDouble()));
150 pain.drawText(260, 15, text);
153 void paintEvent(QPaintEvent *)
155 int x = (width() - splash_.width()) / 2;
156 int y = (height() - splash_.height()) / 2;
158 pain.drawPixmap(x, y, splash_);
166 /// Toolbar store providing access to individual toolbars by name.
167 typedef std::map<std::string, GuiToolbar *> ToolbarMap;
169 typedef boost::shared_ptr<Dialog> DialogPtr;
174 struct GuiView::GuiViewPrivate
177 : current_work_area_(0), current_main_work_area_(0),
178 layout_(0), autosave_timeout_(5000),
181 // hardcode here the platform specific icon size
182 smallIconSize = 14; // scaling problems
183 normalIconSize = 20; // ok, default
184 bigIconSize = 26; // better for some math icons
186 splitter_ = new QSplitter;
187 bg_widget_ = new BackgroundWidget;
188 stack_widget_ = new QStackedWidget;
189 stack_widget_->addWidget(bg_widget_);
190 stack_widget_->addWidget(splitter_);
198 delete stack_widget_;
201 QMenu * toolBarPopup(GuiView * parent)
203 // FIXME: translation
204 QMenu * menu = new QMenu(parent);
205 QActionGroup * iconSizeGroup = new QActionGroup(parent);
207 QAction * smallIcons = new QAction(iconSizeGroup);
208 smallIcons->setText(qt_("Small-sized icons"));
209 smallIcons->setCheckable(true);
210 QObject::connect(smallIcons, SIGNAL(triggered()),
211 parent, SLOT(smallSizedIcons()));
212 menu->addAction(smallIcons);
214 QAction * normalIcons = new QAction(iconSizeGroup);
215 normalIcons->setText(qt_("Normal-sized icons"));
216 normalIcons->setCheckable(true);
217 QObject::connect(normalIcons, SIGNAL(triggered()),
218 parent, SLOT(normalSizedIcons()));
219 menu->addAction(normalIcons);
221 QAction * bigIcons = new QAction(iconSizeGroup);
222 bigIcons->setText(qt_("Big-sized icons"));
223 bigIcons->setCheckable(true);
224 QObject::connect(bigIcons, SIGNAL(triggered()),
225 parent, SLOT(bigSizedIcons()));
226 menu->addAction(bigIcons);
228 unsigned int cur = parent->iconSize().width();
229 if ( cur == parent->d.smallIconSize)
230 smallIcons->setChecked(true);
231 else if (cur == parent->d.normalIconSize)
232 normalIcons->setChecked(true);
233 else if (cur == parent->d.bigIconSize)
234 bigIcons->setChecked(true);
241 stack_widget_->setCurrentWidget(bg_widget_);
242 bg_widget_->setUpdatesEnabled(true);
245 TabWorkArea * tabWorkArea(int i)
247 return dynamic_cast<TabWorkArea *>(splitter_->widget(i));
250 TabWorkArea * currentTabWorkArea()
252 if (splitter_->count() == 1)
253 // The first TabWorkArea is always the first one, if any.
254 return tabWorkArea(0);
256 for (int i = 0; i != splitter_->count(); ++i) {
257 TabWorkArea * twa = tabWorkArea(i);
258 if (current_main_work_area_ == twa->currentWorkArea())
262 // None has the focus so we just take the first one.
263 return tabWorkArea(0);
267 GuiWorkArea * current_work_area_;
268 GuiWorkArea * current_main_work_area_;
269 QSplitter * splitter_;
270 QStackedWidget * stack_widget_;
271 BackgroundWidget * bg_widget_;
273 ToolbarMap toolbars_;
274 /// The main layout box.
276 * \warning Don't Delete! The layout box is actually owned by
277 * whichever toolbar contains it. All the GuiView class needs is a
278 * means of accessing it.
280 * FIXME: replace that with a proper model so that we are not limited
281 * to only one dialog.
286 map<string, DialogPtr> dialogs_;
288 unsigned int smallIconSize;
289 unsigned int normalIconSize;
290 unsigned int bigIconSize;
292 QTimer statusbar_timer_;
293 /// auto-saving of buffers
294 Timeout autosave_timeout_;
295 /// flag against a race condition due to multiclicks, see bug #1119
299 TocModels toc_models_;
301 #if (QT_VERSION >= 0x040400)
303 QFutureWatcher<bool> autosave_watcher_;
308 GuiView::GuiView(int id)
309 : d(*new GuiViewPrivate), id_(id), closing_(false)
311 // GuiToolbars *must* be initialised before the menu bar.
312 normalSizedIcons(); // at least on Mac the default is 32 otherwise, which is huge
315 // set ourself as the current view. This is needed for the menu bar
316 // filling, at least for the static special menu item on Mac. Otherwise
317 // they are greyed out.
318 guiApp->setCurrentView(this);
320 // Fill up the menu bar.
321 guiApp->menus().fillMenuBar(menuBar(), this, true);
323 setCentralWidget(d.stack_widget_);
325 // Start autosave timer
326 if (lyxrc.autosave) {
327 d.autosave_timeout_.timeout.connect(boost::bind(&GuiView::autoSave, this));
328 d.autosave_timeout_.setTimeout(lyxrc.autosave * 1000);
329 d.autosave_timeout_.start();
331 connect(&d.statusbar_timer_, SIGNAL(timeout()),
332 this, SLOT(clearMessage()));
334 // We don't want to keep the window in memory if it is closed.
335 setAttribute(Qt::WA_DeleteOnClose, true);
337 #if (!defined(Q_WS_WIN) && !defined(Q_WS_MACX))
338 // assign an icon to main form. We do not do it under Qt/Win or Qt/Mac,
339 // since the icon is provided in the application bundle.
340 setWindowIcon(getPixmap("images/", "lyx", "png"));
344 setAcceptDrops(true);
346 statusBar()->setSizeGripEnabled(true);
348 // Forbid too small unresizable window because it can happen
349 // with some window manager under X11.
350 setMinimumSize(300, 200);
352 if (lyxrc.allow_geometry_session) {
353 // Now take care of session management.
358 // no session handling, default to a sane size.
359 setGeometry(50, 50, 690, 510);
362 // clear session data if any.
364 settings.remove("views");
366 #if (QT_VERSION >= 0x040400)
367 connect(&d.autosave_watcher_, SIGNAL(finished()), this,
368 SLOT(autoSaveFinished()));
379 void GuiView::autoSaveFinished()
381 #if (QT_VERSION >= 0x040400)
382 docstring const msg = d.autosave_watcher_.result()
383 ? _("Automatic save done.") : _("Automatic save failed!");
389 void GuiView::saveLayout() const
392 settings.beginGroup("views");
393 settings.beginGroup(QString::number(id_));
395 settings.setValue("pos", pos());
396 settings.setValue("size", size());
398 settings.setValue("geometry", saveGeometry());
400 settings.setValue("layout", saveState(0));
401 settings.setValue("icon_size", iconSize());
405 bool GuiView::restoreLayout()
408 settings.beginGroup("views");
409 settings.beginGroup(QString::number(id_));
410 QString const icon_key = "icon_size";
411 if (!settings.contains(icon_key))
414 //code below is skipped when when ~/.config/LyX is (re)created
415 setIconSize(settings.value(icon_key).toSize());
417 QPoint pos = settings.value("pos", QPoint(50, 50)).toPoint();
418 QSize size = settings.value("size", QSize(690, 510)).toSize();
422 // Work-around for bug #6034: the window ends up in an undetermined
423 // state when trying to restore a maximized window when it is
424 // already maximized.
425 if (!(windowState() & Qt::WindowMaximized))
426 if (!restoreGeometry(settings.value("geometry").toByteArray()))
427 setGeometry(50, 50, 690, 510);
429 // Make sure layout is correctly oriented.
430 setLayoutDirection(qApp->layoutDirection());
432 // Allow the toc and view-source dock widget to be restored if needed.
434 if ((dialog = findOrBuild("toc", true)))
435 // see bug 5082. At least setup title and enabled state.
436 // Visibility will be adjusted by restoreState below.
437 dialog->prepareView();
438 if ((dialog = findOrBuild("view-source", true)))
439 dialog->prepareView();
441 if (!restoreState(settings.value("layout").toByteArray(), 0))
448 GuiToolbar * GuiView::toolbar(string const & name)
450 ToolbarMap::iterator it = d.toolbars_.find(name);
451 if (it != d.toolbars_.end())
454 LYXERR(Debug::GUI, "Toolbar::display: no toolbar named " << name);
455 message(bformat(_("Unknown toolbar \"%1$s\""), from_utf8(name)));
460 void GuiView::constructToolbars()
462 ToolbarMap::iterator it = d.toolbars_.begin();
463 for (; it != d.toolbars_.end(); ++it)
467 // I don't like doing this here, but the standard toolbar
468 // destroys this object when it's destroyed itself (vfr)
469 d.layout_ = new LayoutBox(*this);
470 d.stack_widget_->addWidget(d.layout_);
471 d.layout_->move(0,0);
473 // extracts the toolbars from the backend
474 Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
475 Toolbars::Infos::iterator end = guiApp->toolbars().end();
476 for (; cit != end; ++cit)
477 d.toolbars_[cit->name] = new GuiToolbar(*cit, *this);
481 void GuiView::initToolbars()
483 // extracts the toolbars from the backend
484 Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
485 Toolbars::Infos::iterator end = guiApp->toolbars().end();
486 for (; cit != end; ++cit) {
487 GuiToolbar * tb = toolbar(cit->name);
490 int const visibility = guiApp->toolbars().defaultVisibility(cit->name);
492 tb->setVisible(false);
493 tb->setVisibility(visibility);
495 if (visibility & Toolbars::TOP) {
497 addToolBarBreak(Qt::TopToolBarArea);
498 addToolBar(Qt::TopToolBarArea, tb);
501 if (visibility & Toolbars::BOTTOM) {
502 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
503 #if (QT_VERSION >= 0x040202)
504 addToolBarBreak(Qt::BottomToolBarArea);
506 addToolBar(Qt::BottomToolBarArea, tb);
509 if (visibility & Toolbars::LEFT) {
510 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
511 #if (QT_VERSION >= 0x040202)
512 addToolBarBreak(Qt::LeftToolBarArea);
514 addToolBar(Qt::LeftToolBarArea, tb);
517 if (visibility & Toolbars::RIGHT) {
518 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
519 #if (QT_VERSION >= 0x040202)
520 addToolBarBreak(Qt::RightToolBarArea);
522 addToolBar(Qt::RightToolBarArea, tb);
525 if (visibility & Toolbars::ON)
526 tb->setVisible(true);
531 TocModels & GuiView::tocModels()
533 return d.toc_models_;
537 void GuiView::setFocus()
539 LYXERR(Debug::DEBUG, "GuiView::setFocus()" << this);
540 // Make sure LyXFunc points to the correct view.
541 guiApp->setCurrentView(this);
542 QMainWindow::setFocus();
543 if (d.current_work_area_)
544 d.current_work_area_->setFocus();
548 QMenu * GuiView::createPopupMenu()
550 return d.toolBarPopup(this);
554 void GuiView::showEvent(QShowEvent * e)
556 LYXERR(Debug::GUI, "Passed Geometry "
557 << size().height() << "x" << size().width()
558 << "+" << pos().x() << "+" << pos().y());
560 if (d.splitter_->count() == 0)
561 // No work area, switch to the background widget.
564 QMainWindow::showEvent(e);
568 /** Destroy only all tabbed WorkAreas. Destruction of other WorkAreas
569 ** is responsibility of the container (e.g., dialog)
571 void GuiView::closeEvent(QCloseEvent * close_event)
573 LYXERR(Debug::DEBUG, "GuiView::closeEvent()");
578 // it can happen that this event arrives without selecting the view,
579 // e.g. when clicking the close button on a background window.
581 if (!closeWorkAreaAll()) {
583 close_event->ignore();
587 // Make sure that nothing will use this to be closed View.
588 guiApp->unregisterView(this);
590 if (isFullScreen()) {
591 // Switch off fullscreen before closing.
596 // Make sure the timer time out will not trigger a statusbar update.
597 d.statusbar_timer_.stop();
599 // Saving fullscreen requires additional tweaks in the toolbar code.
600 // It wouldn't also work under linux natively.
601 if (lyxrc.allow_geometry_session) {
602 // Save this window geometry and layout.
604 // Then the toolbar private states.
605 ToolbarMap::iterator end = d.toolbars_.end();
606 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
607 it->second->saveSession();
608 // Now take care of all other dialogs:
609 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
610 for (; it!= d.dialogs_.end(); ++it)
611 it->second->saveSession();
614 close_event->accept();
618 void GuiView::dragEnterEvent(QDragEnterEvent * event)
620 if (event->mimeData()->hasUrls())
622 /// \todo Ask lyx-devel is this is enough:
623 /// if (event->mimeData()->hasFormat("text/plain"))
624 /// event->acceptProposedAction();
628 void GuiView::dropEvent(QDropEvent * event)
630 QList<QUrl> files = event->mimeData()->urls();
634 LYXERR(Debug::GUI, "GuiView::dropEvent: got URLs!");
635 for (int i = 0; i != files.size(); ++i) {
636 string const file = os::internal_path(fromqstr(
637 files.at(i).toLocalFile()));
641 string const ext = support::getExtension(file);
642 vector<const Format *> found_formats;
644 // Find all formats that have the correct extension.
645 vector<const Format *> const & import_formats
646 = theConverters().importableFormats();
647 vector<const Format *>::const_iterator it = import_formats.begin();
648 for (; it != import_formats.end(); ++it)
649 if ((*it)->extension() == ext)
650 found_formats.push_back(*it);
653 if (found_formats.size() >= 1) {
654 if (found_formats.size() > 1) {
655 //FIXME: show a dialog to choose the correct importable format
657 "Multiple importable formats found, selecting first");
659 string const arg = found_formats[0]->name() + " " + file;
660 cmd = FuncRequest(LFUN_BUFFER_IMPORT, arg);
663 //FIXME: do we have to explicitly check whether it's a lyx file?
665 "No formats found, trying to open it as a lyx file");
666 cmd = FuncRequest(LFUN_FILE_OPEN, file);
669 // Asynchronously post the event. DropEvent usually come
670 // from the BufferView. But reloading a file might close
671 // the BufferView from within its own event handler.
672 guiApp->dispatchDelayed(cmd);
678 void GuiView::message(docstring const & str)
680 if (ForkedProcess::iAmAChild())
683 statusBar()->showMessage(toqstr(str));
684 d.statusbar_timer_.stop();
685 d.statusbar_timer_.start(3000);
689 void GuiView::smallSizedIcons()
691 setIconSize(QSize(d.smallIconSize, d.smallIconSize));
695 void GuiView::normalSizedIcons()
697 setIconSize(QSize(d.normalIconSize, d.normalIconSize));
701 void GuiView::bigSizedIcons()
703 setIconSize(QSize(d.bigIconSize, d.bigIconSize));
707 void GuiView::clearMessage()
712 d.statusbar_timer_.stop();
716 void GuiView::updateWindowTitle(GuiWorkArea * wa)
718 if (wa != d.current_work_area_)
720 setWindowTitle(qt_("LyX: ") + wa->windowTitle());
721 setWindowIconText(wa->windowIconText());
725 void GuiView::on_currentWorkAreaChanged(GuiWorkArea * wa)
728 disconnectBufferView();
729 connectBufferView(wa->bufferView());
730 connectBuffer(wa->bufferView().buffer());
731 d.current_work_area_ = wa;
732 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
733 this, SLOT(updateWindowTitle(GuiWorkArea *)));
734 updateWindowTitle(wa);
738 // The document settings needs to be reinitialised.
739 updateDialog("document", "");
741 // Buffer-dependent dialogs must be updated. This is done here because
742 // some dialogs require buffer()->text.
747 void GuiView::on_lastWorkAreaRemoved()
750 // We already are in a close event. Nothing more to do.
753 if (d.splitter_->count() > 1)
754 // We have a splitter so don't close anything.
757 // Reset and updates the dialogs.
758 d.toc_models_.reset(0);
759 updateDialog("document", "");
762 resetWindowTitleAndIconText();
764 if (lyxrc.open_buffers_in_tabs)
765 // Nothing more to do, the window should stay open.
768 if (guiApp->viewIds().size() > 1) {
774 // On Mac we also close the last window because the application stay
775 // resident in memory. On other platforms we don't close the last
776 // window because this would quit the application.
782 void GuiView::updateStatusBar()
784 // let the user see the explicit message
785 if (d.statusbar_timer_.isActive())
792 void GuiView::showMessage()
794 QString msg = toqstr(theGuiApp()->viewStatusMessage());
796 BufferView const * bv = currentBufferView();
798 msg = toqstr(bv->cursor().currentState());
800 msg = qt_("Welcome to LyX!");
802 statusBar()->showMessage(msg);
806 bool GuiView::event(QEvent * e)
810 // Useful debug code:
811 //case QEvent::ActivationChange:
812 //case QEvent::WindowDeactivate:
813 //case QEvent::Paint:
814 //case QEvent::Enter:
815 //case QEvent::Leave:
816 //case QEvent::HoverEnter:
817 //case QEvent::HoverLeave:
818 //case QEvent::HoverMove:
819 //case QEvent::StatusTip:
820 //case QEvent::DragEnter:
821 //case QEvent::DragLeave:
825 case QEvent::WindowActivate: {
826 GuiView * old_view = guiApp->currentView();
827 if (this == old_view) {
829 return QMainWindow::event(e);
831 if (old_view && old_view->currentBufferView()) {
832 // save current selection to the selection buffer to allow
833 // middle-button paste in this window.
834 cap::saveSelection(old_view->currentBufferView()->cursor());
836 guiApp->setCurrentView(this);
837 if (d.current_work_area_) {
838 BufferView & bv = d.current_work_area_->bufferView();
839 connectBufferView(bv);
840 connectBuffer(bv.buffer());
841 // The document structure, name and dialogs might have
842 // changed in another view.
844 // The document settings needs to be reinitialised.
845 updateDialog("document", "");
848 resetWindowTitleAndIconText();
851 return QMainWindow::event(e);
854 case QEvent::ShortcutOverride: {
857 #if (!defined Q_WS_X11) || (QT_VERSION >= 0x040500)
858 if (isFullScreen() && menuBar()->isHidden()) {
859 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
860 // FIXME: we should also try to detect special LyX shortcut such as
861 // Alt-P and Alt-M. Right now there is a hack in
862 // GuiWorkArea::processKeySym() that hides again the menubar for
864 if (ke->modifiers() & Qt::AltModifier && ke->key() != Qt::Key_Alt) {
866 return QMainWindow::event(e);
871 if (d.current_work_area_)
872 // Nothing special to do.
873 return QMainWindow::event(e);
875 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
876 // Let Qt handle menu access and the Tab keys to navigate keys to navigate
878 if (ke->modifiers() & Qt::AltModifier || ke->key() == Qt::Key_Tab
879 || ke->key() == Qt::Key_Backtab)
880 return QMainWindow::event(e);
882 // Allow processing of shortcuts that are allowed even when no Buffer
885 setKeySymbol(&sym, ke);
886 guiApp->processKeySym(sym, q_key_state(ke->modifiers()));
892 return QMainWindow::event(e);
896 void GuiView::resetWindowTitleAndIconText()
898 setWindowTitle(qt_("LyX"));
899 setWindowIconText(qt_("LyX"));
902 bool GuiView::focusNextPrevChild(bool /*next*/)
909 void GuiView::setBusy(bool busy)
911 if (d.current_work_area_) {
912 d.current_work_area_->setUpdatesEnabled(!busy);
914 d.current_work_area_->stopBlinkingCursor();
916 d.current_work_area_->startBlinkingCursor();
920 QApplication::setOverrideCursor(Qt::WaitCursor);
922 QApplication::restoreOverrideCursor();
926 GuiWorkArea * GuiView::workArea(Buffer & buffer)
928 if (currentWorkArea()
929 && ¤tWorkArea()->bufferView().buffer() == &buffer)
930 return (GuiWorkArea *) currentWorkArea();
931 if (TabWorkArea * twa = d.currentTabWorkArea())
932 return twa->workArea(buffer);
937 GuiWorkArea * GuiView::addWorkArea(Buffer & buffer)
939 // Automatically create a TabWorkArea if there are none yet.
940 TabWorkArea * tab_widget = d.splitter_->count()
941 ? d.currentTabWorkArea() : addTabWorkArea();
942 return tab_widget->addWorkArea(buffer, *this);
946 TabWorkArea * GuiView::addTabWorkArea()
948 TabWorkArea * twa = new TabWorkArea;
949 QObject::connect(twa, SIGNAL(currentWorkAreaChanged(GuiWorkArea *)),
950 this, SLOT(on_currentWorkAreaChanged(GuiWorkArea *)));
951 QObject::connect(twa, SIGNAL(lastWorkAreaRemoved()),
952 this, SLOT(on_lastWorkAreaRemoved()));
954 d.splitter_->addWidget(twa);
955 d.stack_widget_->setCurrentWidget(d.splitter_);
960 GuiWorkArea const * GuiView::currentWorkArea() const
962 return d.current_work_area_;
966 GuiWorkArea * GuiView::currentWorkArea()
968 return d.current_work_area_;
972 GuiWorkArea const * GuiView::currentMainWorkArea() const
974 if (d.currentTabWorkArea() == NULL)
976 return d.currentTabWorkArea()->currentWorkArea();
980 GuiWorkArea * GuiView::currentMainWorkArea()
982 if (d.currentTabWorkArea() == NULL)
984 return d.currentTabWorkArea()->currentWorkArea();
988 void GuiView::setCurrentWorkArea(GuiWorkArea * wa)
990 LYXERR(Debug::DEBUG, "Setting current wa: " << wa << endl);
992 d.current_work_area_ = NULL;
996 GuiWorkArea * old_gwa = theGuiApp()->currentView()->currentWorkArea();
1000 if (currentBufferView())
1001 cap::saveSelection(currentBufferView()->cursor());
1003 theGuiApp()->setCurrentView(this);
1004 d.current_work_area_ = wa;
1005 for (int i = 0; i != d.splitter_->count(); ++i) {
1006 if (d.tabWorkArea(i)->setCurrentWorkArea(wa)) {
1007 //if (d.current_main_work_area_)
1008 // d.current_main_work_area_->setFrameStyle(QFrame::NoFrame);
1009 d.current_main_work_area_ = wa;
1010 //d.current_main_work_area_->setFrameStyle(QFrame::Box | QFrame::Plain);
1011 //d.current_main_work_area_->setLineWidth(2);
1012 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() << ", Current main wa: " << currentMainWorkArea());
1016 LYXERR(Debug::DEBUG, "This is not a tabbed wa");
1017 on_currentWorkAreaChanged(wa);
1018 BufferView & bv = wa->bufferView();
1019 bv.cursor().fixIfBroken();
1021 wa->setUpdatesEnabled(true);
1022 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() << ", Current main wa: " << currentMainWorkArea());
1026 void GuiView::removeWorkArea(GuiWorkArea * wa)
1028 LASSERT(wa, return);
1029 if (wa == d.current_work_area_) {
1031 disconnectBufferView();
1032 d.current_work_area_ = 0;
1033 d.current_main_work_area_ = 0;
1036 bool found_twa = false;
1037 for (int i = 0; i != d.splitter_->count(); ++i) {
1038 TabWorkArea * twa = d.tabWorkArea(i);
1039 if (twa->removeWorkArea(wa)) {
1040 // Found in this tab group, and deleted the GuiWorkArea.
1042 if (twa->count() != 0) {
1043 if (d.current_work_area_ == 0)
1044 // This means that we are closing the current GuiWorkArea, so
1045 // switch to the next GuiWorkArea in the found TabWorkArea.
1046 setCurrentWorkArea(twa->currentWorkArea());
1048 // No more WorkAreas in this tab group, so delete it.
1055 // It is not a tabbed work area (i.e., the search work area), so it
1056 // should be deleted by other means.
1057 LASSERT(found_twa, /* */);
1059 if (d.current_work_area_ == 0) {
1060 if (d.splitter_->count() != 0) {
1061 TabWorkArea * twa = d.currentTabWorkArea();
1062 setCurrentWorkArea(twa->currentWorkArea());
1064 // No more work areas, switch to the background widget.
1065 setCurrentWorkArea(0);
1071 LayoutBox * GuiView::getLayoutDialog() const
1077 void GuiView::updateLayoutList()
1080 d.layout_->updateContents(false);
1084 void GuiView::updateToolbars()
1086 ToolbarMap::iterator end = d.toolbars_.end();
1087 if (d.current_work_area_) {
1089 d.current_work_area_->bufferView().cursor().inMathed();
1091 lyx::getStatus(FuncRequest(LFUN_LAYOUT_TABULAR)).enabled();
1093 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).enabled() &&
1094 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).onoff(true);
1095 bool const mathmacrotemplate =
1096 lyx::getStatus(FuncRequest(LFUN_IN_MATHMACROTEMPLATE)).enabled();
1098 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1099 it->second->update(math, table, review, mathmacrotemplate);
1101 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1102 it->second->update(false, false, false, false);
1106 void GuiView::setBuffer(Buffer * newBuffer)
1108 LYXERR(Debug::DEBUG, "Setting buffer: " << newBuffer << std::endl);
1109 LASSERT(newBuffer, return);
1112 GuiWorkArea * wa = workArea(*newBuffer);
1114 newBuffer->masterBuffer()->updateLabels();
1115 wa = addWorkArea(*newBuffer);
1117 //Disconnect the old buffer...there's no new one.
1120 connectBuffer(*newBuffer);
1121 connectBufferView(wa->bufferView());
1122 setCurrentWorkArea(wa);
1128 void GuiView::connectBuffer(Buffer & buf)
1130 buf.setGuiDelegate(this);
1134 void GuiView::disconnectBuffer()
1136 if (d.current_work_area_)
1137 d.current_work_area_->bufferView().buffer().setGuiDelegate(0);
1141 void GuiView::connectBufferView(BufferView & bv)
1143 bv.setGuiDelegate(this);
1147 void GuiView::disconnectBufferView()
1149 if (d.current_work_area_)
1150 d.current_work_area_->bufferView().setGuiDelegate(0);
1154 void GuiView::errors(string const & error_type, bool from_master)
1156 ErrorList & el = from_master ?
1157 documentBufferView()->buffer().masterBuffer()->errorList(error_type)
1158 : documentBufferView()->buffer().errorList(error_type);
1159 string data = error_type;
1161 data = "from_master|" + error_type;
1163 showDialog("errorlist", data);
1167 void GuiView::updateTocItem(std::string const & type, DocIterator const & dit)
1169 d.toc_models_.updateItem(toqstr(type), dit);
1173 void GuiView::structureChanged()
1175 d.toc_models_.reset(documentBufferView());
1176 // Navigator needs more than a simple update in this case. It needs to be
1178 updateDialog("toc", "");
1182 void GuiView::updateDialog(string const & name, string const & data)
1184 if (!isDialogVisible(name))
1187 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
1188 if (it == d.dialogs_.end())
1191 Dialog * const dialog = it->second.get();
1192 if (dialog->isVisibleView())
1193 dialog->initialiseParams(data);
1197 BufferView * GuiView::documentBufferView()
1199 return currentMainWorkArea()
1200 ? ¤tMainWorkArea()->bufferView()
1205 BufferView const * GuiView::documentBufferView() const
1207 return currentMainWorkArea()
1208 ? ¤tMainWorkArea()->bufferView()
1213 BufferView * GuiView::currentBufferView()
1215 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1219 BufferView const * GuiView::currentBufferView() const
1221 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1225 static bool saveAndDestroyBuffer(Buffer * buffer, FileName const & fname)
1228 FileName const tmp_ret = FileName::tempName("lyxauto");
1229 if (!tmp_ret.empty()) {
1230 if (buffer->writeFile(tmp_ret))
1231 failed = !tmp_ret.moveTo(fname);
1234 // failed to write/rename tmp_ret so try writing direct
1235 failed = buffer->writeFile(fname);
1242 void GuiView::autoSave()
1244 LYXERR(Debug::INFO, "Running autoSave()");
1246 Buffer * buffer = documentBufferView()
1247 ? &documentBufferView()->buffer() : 0;
1251 #if (QT_VERSION >= 0x040400)
1252 QFuture<bool> f = QtConcurrent::run(saveAndDestroyBuffer, buffer->clone(),
1253 buffer->getAutosaveFilename());
1254 d.autosave_watcher_.setFuture(f);
1261 void GuiView::resetAutosaveTimers()
1264 d.autosave_timeout_.restart();
1268 bool GuiView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1271 Buffer * buf = currentBufferView()
1272 ? ¤tBufferView()->buffer() : 0;
1273 Buffer * doc_buffer = documentBufferView()
1274 ? &(documentBufferView()->buffer()) : 0;
1276 // Check whether we need a buffer
1277 if (!lyxaction.funcHasFlag(cmd.action, LyXAction::NoBuffer) && !buf) {
1278 // no, exit directly
1279 flag.message(from_utf8(N_("Command not allowed with"
1280 "out any document open")));
1281 flag.setEnabled(false);
1285 if (cmd.origin == FuncRequest::TOC) {
1286 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
1288 if (toc->getStatus(documentBufferView()->cursor(), cmd, fs))
1291 flag.setEnabled(false);
1295 switch(cmd.action) {
1296 case LFUN_BUFFER_IMPORT:
1299 case LFUN_BUFFER_RELOAD:
1300 enable = doc_buffer && !doc_buffer->isUnnamed()
1301 && doc_buffer->fileName().exists()
1302 && (!doc_buffer->isClean()
1303 || doc_buffer->isExternallyModified(Buffer::timestamp_method));
1306 case LFUN_BUFFER_CHILD_OPEN:
1307 enable = doc_buffer;
1310 case LFUN_BUFFER_WRITE:
1311 enable = doc_buffer && (doc_buffer->isUnnamed() || !doc_buffer->isClean());
1314 //FIXME: This LFUN should be moved to GuiApplication.
1315 case LFUN_BUFFER_WRITE_ALL: {
1316 // We enable the command only if there are some modified buffers
1317 Buffer * first = theBufferList().first();
1322 // We cannot use a for loop as the buffer list is a cycle.
1324 if (!b->isClean()) {
1328 b = theBufferList().next(b);
1329 } while (b != first);
1333 case LFUN_BUFFER_WRITE_AS:
1334 enable = doc_buffer;
1337 case LFUN_BUFFER_CLOSE:
1338 enable = doc_buffer;
1341 case LFUN_BUFFER_CLOSE_ALL:
1342 enable = theBufferList().last() != theBufferList().first();
1345 case LFUN_SPLIT_VIEW:
1346 if (cmd.getArg(0) == "vertical")
1347 enable = doc_buffer && (d.splitter_->count() == 1 ||
1348 d.splitter_->orientation() == Qt::Vertical);
1350 enable = doc_buffer && (d.splitter_->count() == 1 ||
1351 d.splitter_->orientation() == Qt::Horizontal);
1354 case LFUN_CLOSE_TAB_GROUP:
1355 enable = d.currentTabWorkArea();
1358 case LFUN_TOOLBAR_TOGGLE:
1359 if (GuiToolbar * t = toolbar(cmd.getArg(0)))
1360 flag.setOnOff(t->isVisible());
1363 case LFUN_DROP_LAYOUTS_CHOICE:
1367 case LFUN_UI_TOGGLE:
1368 flag.setOnOff(isFullScreen());
1371 case LFUN_DIALOG_DISCONNECT_INSET:
1374 case LFUN_DIALOG_HIDE:
1375 // FIXME: should we check if the dialog is shown?
1378 case LFUN_DIALOG_TOGGLE:
1379 flag.setOnOff(isDialogVisible(cmd.getArg(0)));
1380 // fall through to set "enable"
1381 case LFUN_DIALOG_SHOW: {
1382 string const name = cmd.getArg(0);
1384 enable = name == "aboutlyx"
1385 || name == "file" //FIXME: should be removed.
1387 || name == "texinfo"
1388 || name == "compare";
1389 else if (name == "print")
1390 enable = doc_buffer->isExportable("dvi")
1391 && lyxrc.print_command != "none";
1392 else if (name == "character" || name == "symbols") {
1393 if (!buf || buf->isReadonly()
1394 || !currentBufferView()->cursor().inTexted())
1397 // FIXME we should consider passthru
1399 Inset const & in = currentBufferView()->cursor().inset();
1400 enable = !in.getLayout().isPassThru();
1403 else if (name == "latexlog")
1404 enable = FileName(doc_buffer->logName()).isReadableFile();
1405 else if (name == "spellchecker")
1406 enable = theSpellChecker() && !doc_buffer->isReadonly();
1407 else if (name == "vclog")
1408 enable = doc_buffer->lyxvc().inUse();
1412 case LFUN_DIALOG_UPDATE: {
1413 string const name = cmd.getArg(0);
1415 enable = name == "prefs";
1419 case LFUN_COMMAND_EXECUTE:
1421 case LFUN_MENU_OPEN:
1422 // Nothing to check.
1425 case LFUN_COMPLETION_INLINE:
1426 if (!d.current_work_area_
1427 || !d.current_work_area_->completer().inlinePossible(
1428 currentBufferView()->cursor()))
1432 case LFUN_COMPLETION_POPUP:
1433 if (!d.current_work_area_
1434 || !d.current_work_area_->completer().popupPossible(
1435 currentBufferView()->cursor()))
1439 case LFUN_COMPLETION_COMPLETE:
1440 if (!d.current_work_area_
1441 || !d.current_work_area_->completer().inlinePossible(
1442 currentBufferView()->cursor()))
1446 case LFUN_COMPLETION_ACCEPT:
1447 if (!d.current_work_area_
1448 || (!d.current_work_area_->completer().popupVisible()
1449 && !d.current_work_area_->completer().inlineVisible()
1450 && !d.current_work_area_->completer().completionAvailable()))
1454 case LFUN_COMPLETION_CANCEL:
1455 if (!d.current_work_area_
1456 || (!d.current_work_area_->completer().popupVisible()
1457 && !d.current_work_area_->completer().inlineVisible()))
1461 case LFUN_BUFFER_ZOOM_OUT:
1462 enable = doc_buffer && lyxrc.zoom > 10;
1465 case LFUN_BUFFER_ZOOM_IN:
1466 enable = doc_buffer;
1469 case LFUN_BUFFER_NEXT:
1470 case LFUN_BUFFER_PREVIOUS:
1471 // FIXME: should we check is there is an previous or next buffer?
1473 case LFUN_BUFFER_SWITCH:
1474 // toggle on the current buffer, but do not toggle off
1475 // the other ones (is that a good idea?)
1477 && to_utf8(cmd.argument()) == doc_buffer->absFileName())
1478 flag.setOnOff(true);
1481 case LFUN_VC_REGISTER:
1482 enable = doc_buffer && !doc_buffer->lyxvc().inUse();
1484 case LFUN_VC_CHECK_IN:
1485 enable = doc_buffer && doc_buffer->lyxvc().checkInEnabled();
1487 case LFUN_VC_CHECK_OUT:
1488 enable = doc_buffer && doc_buffer->lyxvc().checkOutEnabled();
1490 case LFUN_VC_LOCKING_TOGGLE:
1491 enable = doc_buffer && !doc_buffer->isReadonly()
1492 && doc_buffer->lyxvc().lockingToggleEnabled();
1493 flag.setOnOff(enable && !doc_buffer->lyxvc().locker().empty());
1495 case LFUN_VC_REVERT:
1496 enable = doc_buffer && doc_buffer->lyxvc().inUse();
1498 case LFUN_VC_UNDO_LAST:
1499 enable = doc_buffer && doc_buffer->lyxvc().undoLastEnabled();
1501 case LFUN_VC_REPO_UPDATE:
1502 enable = doc_buffer && doc_buffer->lyxvc().inUse();
1504 case LFUN_VC_COMMAND: {
1505 if (cmd.argument().empty())
1507 if (!doc_buffer && contains(cmd.getArg(0), 'D'))
1512 case LFUN_SERVER_GOTO_FILE_ROW:
1520 flag.setEnabled(false);
1526 static FileName selectTemplateFile()
1528 FileDialog dlg(qt_("Select template file"));
1529 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1530 dlg.setButton1(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
1532 FileDialog::Result result = dlg.open(toqstr(lyxrc.template_path),
1533 QStringList(qt_("LyX Documents (*.lyx)")));
1535 if (result.first == FileDialog::Later)
1537 if (result.second.isEmpty())
1539 return FileName(fromqstr(result.second));
1543 Buffer * GuiView::loadDocument(FileName const & filename, bool tolastfiles)
1547 Buffer * newBuffer = checkAndLoadLyXFile(filename);
1550 message(_("Document not loaded."));
1555 setBuffer(newBuffer);
1557 // scroll to the position when the file was last closed
1558 if (lyxrc.use_lastfilepos) {
1559 LastFilePosSection::FilePos filepos =
1560 theSession().lastFilePos().load(filename);
1561 documentBufferView()->moveToPosition(filepos.pit, filepos.pos, 0, 0);
1565 theSession().lastFiles().add(filename);
1572 void GuiView::openDocument(string const & fname)
1574 string initpath = lyxrc.document_path;
1576 if (documentBufferView()) {
1577 string const trypath = documentBufferView()->buffer().filePath();
1578 // If directory is writeable, use this as default.
1579 if (FileName(trypath).isDirWritable())
1585 if (fname.empty()) {
1586 FileDialog dlg(qt_("Select document to open"), LFUN_FILE_OPEN);
1587 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1588 dlg.setButton2(qt_("Examples|#E#e"),
1589 toqstr(addPath(package().system_support().absFilename(), "examples")));
1591 QStringList filter(qt_("LyX Documents (*.lyx)"));
1592 filter << qt_("LyX-1.3.x Documents (*.lyx13)")
1593 << qt_("LyX-1.4.x Documents (*.lyx14)")
1594 << qt_("LyX-1.5.x Documents (*.lyx15)")
1595 << qt_("LyX-1.6.x Documents (*.lyx16)");
1596 FileDialog::Result result =
1597 dlg.open(toqstr(initpath), filter);
1599 if (result.first == FileDialog::Later)
1602 filename = fromqstr(result.second);
1604 // check selected filename
1605 if (filename.empty()) {
1606 message(_("Canceled."));
1612 // get absolute path of file and add ".lyx" to the filename if
1614 FileName const fullname =
1615 fileSearch(string(), filename, "lyx", support::may_not_exist);
1616 if (!fullname.empty())
1617 filename = fullname.absFilename();
1619 if (!fullname.onlyPath().isDirectory()) {
1620 Alert::warning(_("Invalid filename"),
1621 bformat(_("The directory in the given path\n%1$s\ndoes not exist."),
1622 from_utf8(fullname.absFilename())));
1625 // if the file doesn't exist, let the user create one
1626 if (!fullname.exists()) {
1627 // the user specifically chose this name. Believe him.
1628 Buffer * const b = newFile(filename, string(), true);
1634 docstring const disp_fn = makeDisplayPath(filename);
1635 message(bformat(_("Opening document %1$s..."), disp_fn));
1638 Buffer * buf = loadDocument(fullname);
1640 buf->updateLabels();
1642 buf->errors("Parse");
1643 str2 = bformat(_("Document %1$s opened."), disp_fn);
1644 if (buf->lyxvc().inUse())
1645 str2 += " " + from_utf8(buf->lyxvc().versionString()) +
1646 " " + _("Version control detected.");
1648 str2 = bformat(_("Could not open document %1$s"), disp_fn);
1653 // FIXME: clean that
1654 static bool import(GuiView * lv, FileName const & filename,
1655 string const & format, ErrorList & errorList)
1657 FileName const lyxfile(support::changeExtension(filename.absFilename(), ".lyx"));
1659 string loader_format;
1660 vector<string> loaders = theConverters().loaders();
1661 if (find(loaders.begin(), loaders.end(), format) == loaders.end()) {
1662 for (vector<string>::const_iterator it = loaders.begin();
1663 it != loaders.end(); ++it) {
1664 if (!theConverters().isReachable(format, *it))
1667 string const tofile =
1668 support::changeExtension(filename.absFilename(),
1669 formats.extension(*it));
1670 if (!theConverters().convert(0, filename, FileName(tofile),
1671 filename, format, *it, errorList))
1673 loader_format = *it;
1676 if (loader_format.empty()) {
1677 frontend::Alert::error(_("Couldn't import file"),
1678 bformat(_("No information for importing the format %1$s."),
1679 formats.prettyName(format)));
1683 loader_format = format;
1685 if (loader_format == "lyx") {
1686 Buffer * buf = lv->loadDocument(lyxfile);
1689 buf->updateLabels();
1691 buf->errors("Parse");
1693 Buffer * const b = newFile(lyxfile.absFilename(), string(), true);
1697 bool as_paragraphs = loader_format == "textparagraph";
1698 string filename2 = (loader_format == format) ? filename.absFilename()
1699 : support::changeExtension(filename.absFilename(),
1700 formats.extension(loader_format));
1701 lv->currentBufferView()->insertPlaintextFile(FileName(filename2),
1703 guiApp->setCurrentView(lv);
1704 lyx::dispatch(FuncRequest(LFUN_MARK_OFF));
1711 void GuiView::importDocument(string const & argument)
1714 string filename = split(argument, format, ' ');
1716 LYXERR(Debug::INFO, format << " file: " << filename);
1718 // need user interaction
1719 if (filename.empty()) {
1720 string initpath = lyxrc.document_path;
1721 if (documentBufferView()) {
1722 string const trypath = documentBufferView()->buffer().filePath();
1723 // If directory is writeable, use this as default.
1724 if (FileName(trypath).isDirWritable())
1728 docstring const text = bformat(_("Select %1$s file to import"),
1729 formats.prettyName(format));
1731 FileDialog dlg(toqstr(text), LFUN_BUFFER_IMPORT);
1732 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1733 dlg.setButton2(qt_("Examples|#E#e"),
1734 toqstr(addPath(package().system_support().absFilename(), "examples")));
1736 docstring filter = formats.prettyName(format);
1739 filter += from_utf8(formats.extension(format));
1742 FileDialog::Result result =
1743 dlg.open(toqstr(initpath), fileFilters(toqstr(filter)));
1745 if (result.first == FileDialog::Later)
1748 filename = fromqstr(result.second);
1750 // check selected filename
1751 if (filename.empty())
1752 message(_("Canceled."));
1755 if (filename.empty())
1758 // get absolute path of file
1759 FileName const fullname(support::makeAbsPath(filename));
1761 FileName const lyxfile(support::changeExtension(fullname.absFilename(), ".lyx"));
1763 // Check if the document already is open
1764 Buffer * buf = theBufferList().getBuffer(lyxfile);
1767 if (!closeBuffer()) {
1768 message(_("Canceled."));
1773 docstring const displaypath = makeDisplayPath(lyxfile.absFilename(), 30);
1775 // if the file exists already, and we didn't do
1776 // -i lyx thefile.lyx, warn
1777 if (lyxfile.exists() && fullname != lyxfile) {
1779 docstring text = bformat(_("The document %1$s already exists.\n\n"
1780 "Do you want to overwrite that document?"), displaypath);
1781 int const ret = Alert::prompt(_("Overwrite document?"),
1782 text, 0, 1, _("&Overwrite"), _("&Cancel"));
1785 message(_("Canceled."));
1790 message(bformat(_("Importing %1$s..."), displaypath));
1791 ErrorList errorList;
1792 if (import(this, fullname, format, errorList))
1793 message(_("imported."));
1795 message(_("file not imported!"));
1797 // FIXME (Abdel 12/08/06): Is there a need to display the error list here?
1801 void GuiView::newDocument(string const & filename, bool from_template)
1803 FileName initpath(lyxrc.document_path);
1804 if (documentBufferView()) {
1805 FileName const trypath(documentBufferView()->buffer().filePath());
1806 // If directory is writeable, use this as default.
1807 if (trypath.isDirWritable())
1811 string templatefile;
1812 if (from_template) {
1813 templatefile = selectTemplateFile().absFilename();
1814 if (templatefile.empty())
1819 if (filename.empty())
1820 b = newUnnamedFile(initpath, to_utf8(_("newfile")), templatefile);
1822 b = newFile(filename, templatefile, true);
1827 // If no new document could be created, it is unsure
1828 // whether there is a valid BufferView.
1829 if (currentBufferView())
1830 // Ensure the cursor is correctly positioned on screen.
1831 currentBufferView()->showCursor();
1835 void GuiView::insertLyXFile(docstring const & fname)
1837 BufferView * bv = documentBufferView();
1842 FileName filename(to_utf8(fname));
1844 if (!filename.empty()) {
1845 bv->insertLyXFile(filename);
1849 // Launch a file browser
1851 string initpath = lyxrc.document_path;
1852 string const trypath = bv->buffer().filePath();
1853 // If directory is writeable, use this as default.
1854 if (FileName(trypath).isDirWritable())
1858 FileDialog dlg(qt_("Select LyX document to insert"), LFUN_FILE_INSERT);
1859 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1860 dlg.setButton2(qt_("Examples|#E#e"),
1861 toqstr(addPath(package().system_support().absFilename(),
1864 FileDialog::Result result = dlg.open(toqstr(initpath),
1865 QStringList(qt_("LyX Documents (*.lyx)")));
1867 if (result.first == FileDialog::Later)
1871 filename.set(fromqstr(result.second));
1873 // check selected filename
1874 if (filename.empty()) {
1875 // emit message signal.
1876 message(_("Canceled."));
1880 bv->insertLyXFile(filename);
1884 void GuiView::insertPlaintextFile(docstring const & fname,
1887 BufferView * bv = documentBufferView();
1891 if (!fname.empty() && !FileName::isAbsolute(to_utf8(fname))) {
1892 message(_("Absolute filename expected."));
1897 FileName filename(to_utf8(fname));
1899 if (!filename.empty()) {
1900 bv->insertPlaintextFile(filename, asParagraph);
1904 FileDialog dlg(qt_("Select file to insert"), (asParagraph ?
1905 LFUN_FILE_INSERT_PLAINTEXT_PARA : LFUN_FILE_INSERT_PLAINTEXT));
1907 FileDialog::Result result = dlg.open(toqstr(bv->buffer().filePath()),
1908 QStringList(qt_("All Files (*)")));
1910 if (result.first == FileDialog::Later)
1914 filename.set(fromqstr(result.second));
1916 // check selected filename
1917 if (filename.empty()) {
1918 // emit message signal.
1919 message(_("Canceled."));
1923 bv->insertPlaintextFile(filename, asParagraph);
1927 bool GuiView::renameBuffer(Buffer & b, docstring const & newname)
1929 FileName fname = b.fileName();
1930 FileName const oldname = fname;
1932 if (!newname.empty()) {
1934 fname = support::makeAbsPath(to_utf8(newname), oldname.onlyPath().absFilename());
1936 // Switch to this Buffer.
1939 // No argument? Ask user through dialog.
1941 FileDialog dlg(qt_("Choose a filename to save document as"),
1942 LFUN_BUFFER_WRITE_AS);
1943 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1944 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
1946 if (!isLyXFilename(fname.absFilename()))
1947 fname.changeExtension(".lyx");
1949 FileDialog::Result result =
1950 dlg.save(toqstr(fname.onlyPath().absFilename()),
1951 QStringList(qt_("LyX Documents (*.lyx)")),
1952 toqstr(fname.onlyFileName()));
1954 if (result.first == FileDialog::Later)
1957 fname.set(fromqstr(result.second));
1962 if (!isLyXFilename(fname.absFilename()))
1963 fname.changeExtension(".lyx");
1966 if (FileName(fname).exists()) {
1967 docstring const file = makeDisplayPath(fname.absFilename(), 30);
1968 docstring text = bformat(_("The document %1$s already "
1969 "exists.\n\nDo you want to "
1970 "overwrite that document?"),
1972 int const ret = Alert::prompt(_("Overwrite document?"),
1973 text, 0, 2, _("&Overwrite"), _("&Rename"), _("&Cancel"));
1976 case 1: return renameBuffer(b, docstring());
1977 case 2: return false;
1981 FileName oldauto = b.getAutosaveFilename();
1983 // Ok, change the name of the buffer
1984 b.setFileName(fname.absFilename());
1986 bool unnamed = b.isUnnamed();
1987 b.setUnnamed(false);
1988 b.saveCheckSum(fname);
1990 // bring the autosave file with us, just in case.
1991 b.moveAutosaveFile(oldauto);
1993 if (!saveBuffer(b)) {
1994 oldauto = b.getAutosaveFilename();
1995 b.setFileName(oldname.absFilename());
1996 b.setUnnamed(unnamed);
1997 b.saveCheckSum(oldname);
1998 b.moveAutosaveFile(oldauto);
2006 bool GuiView::saveBuffer(Buffer & b)
2008 if (workArea(b) && workArea(b)->inDialogMode())
2012 return renameBuffer(b, docstring());
2015 theSession().lastFiles().add(b.fileName());
2019 // Switch to this Buffer.
2022 // FIXME: we don't tell the user *WHY* the save failed !!
2023 docstring const file = makeDisplayPath(b.absFileName(), 30);
2024 docstring text = bformat(_("The document %1$s could not be saved.\n\n"
2025 "Do you want to rename the document and "
2026 "try again?"), file);
2027 int const ret = Alert::prompt(_("Rename and save?"),
2028 text, 0, 2, _("&Rename"), _("&Retry"), _("&Cancel"));
2031 if (!renameBuffer(b, docstring()))
2040 return saveBuffer(b);
2044 bool GuiView::hideWorkArea(GuiWorkArea * wa)
2046 return closeWorkArea(wa, false);
2050 bool GuiView::closeWorkArea(GuiWorkArea * wa)
2052 Buffer & buf = wa->bufferView().buffer();
2053 return closeWorkArea(wa, !buf.parent());
2057 bool GuiView::closeBuffer()
2059 GuiWorkArea * wa = currentMainWorkArea();
2060 Buffer & buf = wa->bufferView().buffer();
2061 return wa && closeWorkArea(wa, !buf.parent());
2065 void GuiView::writeSession() const {
2066 GuiWorkArea const * active_wa = currentMainWorkArea();
2067 for (int i = 0; i < d.splitter_->count(); ++i) {
2068 TabWorkArea * twa = d.tabWorkArea(i);
2069 for (int j = 0; j < twa->count(); ++j) {
2070 GuiWorkArea * wa = static_cast<GuiWorkArea *>(twa->widget(j));
2071 Buffer & buf = wa->bufferView().buffer();
2072 theSession().lastOpened().add(buf.fileName(), wa == active_wa);
2078 bool GuiView::closeBufferAll()
2080 // Close the workareas in all other views
2081 QList<int> const ids = guiApp->viewIds();
2082 for (int i = 0; i != ids.size(); ++i) {
2083 if (id_ != ids[i] && !guiApp->view(ids[i]).closeWorkAreaAll())
2087 // Close our own workareas
2088 if (!closeWorkAreaAll())
2091 // Now close the hidden buffers. We prevent hidden buffers from being
2092 // dirty, so we can just close them.
2093 theBufferList().closeAll();
2098 bool GuiView::closeWorkAreaAll()
2100 setCurrentWorkArea(currentMainWorkArea());
2102 // We might be in a situation that there is still a tabWorkArea, but
2103 // there are no tabs anymore. This can happen when we get here after a
2104 // TabWorkArea::lastWorkAreaRemoved() signal. Therefore we count how
2105 // many TabWorkArea's have no documents anymore.
2108 // We have to call count() each time, because it can happen that
2109 // more than one splitter will disappear in one iteration (bug 5998).
2110 for (; d.splitter_->count() > empty_twa; ) {
2111 TabWorkArea * twa = d.tabWorkArea(empty_twa);
2113 if (twa->count() == 0)
2116 setCurrentWorkArea(twa->currentWorkArea());
2117 if (!closeTabWorkArea(twa))
2125 bool GuiView::closeWorkArea(GuiWorkArea * wa, bool close_buffer)
2130 Buffer & buf = wa->bufferView().buffer();
2133 return closeBuffer(buf);
2135 if (!inMultiTabs(wa))
2136 if (!saveBufferIfNeeded(buf, true))
2144 bool GuiView::closeBuffer(Buffer & buf)
2146 // If we are in a close_event all children will be closed in some time,
2147 // so no need to do it here. This will ensure that the children end up
2148 // in the session file in the correct order. If we close the master
2149 // buffer, we can close or release the child buffers here too.
2151 vector<Buffer *> clist = buf.getChildren(false);
2152 for (vector<Buffer *>::const_iterator it = clist.begin();
2153 it != clist.end(); ++it) {
2154 // If a child is dirty, do not close
2155 // without user intervention
2156 //FIXME: should we look in other tabworkareas?
2157 Buffer * child_buf = *it;
2158 GuiWorkArea * child_wa = workArea(*child_buf);
2160 if (!closeWorkArea(child_wa, true))
2163 theBufferList().releaseChild(&buf, child_buf);
2166 // goto bookmark to update bookmark pit.
2167 //FIXME: we should update only the bookmarks related to this buffer!
2168 LYXERR(Debug::DEBUG, "GuiView::closeBuffer()");
2169 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
2170 theLyXFunc().gotoBookmark(i+1, false, false);
2172 if (saveBufferIfNeeded(buf, false)) {
2173 theBufferList().release(&buf);
2180 bool GuiView::closeTabWorkArea(TabWorkArea * twa)
2182 while (twa == d.currentTabWorkArea()) {
2183 twa->setCurrentIndex(twa->count()-1);
2185 GuiWorkArea * wa = twa->currentWorkArea();
2186 Buffer & b = wa->bufferView().buffer();
2188 // We only want to close the buffer if the same buffer is not visible
2189 // in another view, and if this is not a child and if we are closing
2190 // a view (not a tabgroup).
2191 bool const close_buffer =
2192 !inMultiViews(wa) && !b.parent() && closing_;
2194 if (!closeWorkArea(wa, close_buffer))
2201 bool GuiView::saveBufferIfNeeded(Buffer & buf, bool hiding)
2203 if (buf.isClean() || buf.paragraphs().empty())
2206 // Switch to this Buffer.
2211 if (buf.isUnnamed())
2212 file = from_utf8(buf.fileName().onlyFileName());
2214 file = buf.fileName().displayName(30);
2216 // Bring this window to top before asking questions.
2221 if (hiding && buf.isUnnamed()) {
2222 docstring const text = bformat(_("The document %1$s has not been "
2223 "saved yet.\n\nDo you want to save "
2224 "the document?"), file);
2225 ret = Alert::prompt(_("Save new document?"),
2226 text, 0, 1, _("&Save"), _("&Cancel"));
2230 docstring const text = bformat(_("The document %1$s has unsaved changes."
2231 "\n\nDo you want to save the document or discard the changes?"), file);
2232 ret = Alert::prompt(_("Save changed document?"),
2233 text, 0, 2, _("&Save"), _("&Discard"), _("&Cancel"));
2238 if (!saveBuffer(buf))
2242 // if we crash after this we could
2243 // have no autosave file but I guess
2244 // this is really improbable (Jug)
2245 buf.removeAutosaveFile();
2247 // revert all changes
2248 buf.loadLyXFile(buf.fileName());
2258 bool GuiView::inMultiTabs(GuiWorkArea * wa)
2260 Buffer & buf = wa->bufferView().buffer();
2262 for (int i = 0; i != d.splitter_->count(); ++i) {
2263 GuiWorkArea * wa_ = d.tabWorkArea(i)->workArea(buf);
2264 if (wa_ && wa_ != wa)
2267 return inMultiViews(wa);
2271 bool GuiView::inMultiViews(GuiWorkArea * wa)
2273 QList<int> const ids = guiApp->viewIds();
2274 Buffer & buf = wa->bufferView().buffer();
2277 for (int i = 0; i != ids.size() && found_twa <= 1; ++i) {
2281 if (guiApp->view(ids[i]).workArea(buf))
2288 void GuiView::gotoNextOrPreviousBuffer(NextOrPrevious np)
2290 Buffer * const curbuf = documentBufferView()
2291 ? &documentBufferView()->buffer() : 0;
2292 Buffer * nextbuf = curbuf;
2294 if (np == NEXTBUFFER)
2295 nextbuf = theBufferList().next(nextbuf);
2297 nextbuf = theBufferList().previous(nextbuf);
2298 if (nextbuf == curbuf)
2304 if (workArea(*nextbuf))
2311 /// make sure the document is saved
2312 static bool ensureBufferClean(Buffer * buffer)
2314 LASSERT(buffer, return false);
2315 if (buffer->isClean() && !buffer->isUnnamed())
2318 docstring const file = buffer->fileName().displayName(30);
2321 if (!buffer->isUnnamed()) {
2322 text = bformat(_("The document %1$s has unsaved "
2323 "changes.\n\nDo you want to save "
2324 "the document?"), file);
2325 title = _("Save changed document?");
2328 text = bformat(_("The document %1$s has not been "
2329 "saved yet.\n\nDo you want to save "
2330 "the document?"), file);
2331 title = _("Save new document?");
2333 int const ret = Alert::prompt(title, text, 0, 1, _("&Save"), _("&Cancel"));
2336 dispatch(FuncRequest(LFUN_BUFFER_WRITE));
2338 return buffer->isClean() && !buffer->isUnnamed();
2342 void GuiView::reloadBuffer()
2344 Buffer * buf = &documentBufferView()->buffer();
2349 void GuiView::reloadBuffer(Buffer * buf)
2351 FileName filename = buf->fileName();
2352 Buffer const * master = buf->masterBuffer();
2353 bool const is_child = master != buf;
2354 // The user has already confirmed that the changes, if any, should
2355 // be discarded. So we just release the Buffer and don't call closeBuffer();
2356 theBufferList().release(buf);
2357 buf = loadDocument(filename);
2358 docstring const disp_fn = makeDisplayPath(filename.absFilename());
2361 // re-allocate master if necessary
2362 if (is_child && theBufferList().isLoaded(master)
2363 && buf->masterBuffer() != master)
2364 buf->setParent(master);
2365 buf->updateLabels();
2367 buf->errors("Parse");
2368 str = bformat(_("Document %1$s reloaded."), disp_fn);
2370 str = bformat(_("Could not reload document %1$s"), disp_fn);
2376 void GuiView::checkExternallyModifiedBuffers()
2378 BufferList::iterator bit = theBufferList().begin();
2379 BufferList::iterator const bend = theBufferList().end();
2380 for (; bit != bend; ++bit) {
2381 if ((*bit)->isExternallyModified(Buffer::checksum_method)) {
2382 docstring text = bformat(_("Document \n%1$s\n has been externally modified."
2383 " Reload now? Any local changes will be lost."),
2384 from_utf8((*bit)->absFileName()));
2385 int const ret = Alert::prompt(_("Reload externally changed document?"),
2386 text, 0, 1, _("&Reload"), _("&Cancel"));
2394 void GuiView::dispatchVC(FuncRequest const & cmd)
2396 Buffer * buffer = documentBufferView()
2397 ? &(documentBufferView()->buffer()) : 0;
2399 switch (cmd.action) {
2400 case LFUN_VC_REGISTER:
2401 if (!buffer || !ensureBufferClean(buffer))
2403 if (!buffer->lyxvc().inUse()) {
2404 if (buffer->lyxvc().registrer())
2409 case LFUN_VC_CHECK_IN:
2410 if (!buffer || !ensureBufferClean(buffer))
2412 if (buffer->lyxvc().inUse() && !buffer->isReadonly()) {
2413 message(from_utf8(buffer->lyxvc().checkIn()));
2418 case LFUN_VC_CHECK_OUT:
2419 if (!buffer || !ensureBufferClean(buffer))
2421 if (buffer->lyxvc().inUse()) {
2422 message(from_utf8(buffer->lyxvc().checkOut()));
2427 case LFUN_VC_LOCKING_TOGGLE:
2428 LASSERT(buffer, return);
2429 if (!ensureBufferClean(buffer) || buffer->isReadonly())
2431 if (buffer->lyxvc().inUse()) {
2432 string res = buffer->lyxvc().lockingToggle();
2434 frontend::Alert::error(_("Revision control error."),
2435 _("Error when setting the locking property."));
2437 message(from_utf8(res));
2443 case LFUN_VC_REVERT:
2444 LASSERT(buffer, return);
2445 buffer->lyxvc().revert();
2449 case LFUN_VC_UNDO_LAST:
2450 LASSERT(buffer, return);
2451 buffer->lyxvc().undoLast();
2455 case LFUN_VC_REPO_UPDATE:
2456 LASSERT(buffer, return);
2457 if (ensureBufferClean(buffer)) {
2458 string res = buffer->lyxvc().repoUpdate();
2459 message(from_utf8(res));
2460 checkExternallyModifiedBuffers();
2464 case LFUN_VC_COMMAND: {
2465 string flag = cmd.getArg(0);
2466 if (buffer && contains(flag, 'R') && !ensureBufferClean(buffer))
2469 if (contains(flag, 'M')) {
2470 if (!Alert::askForText(message, _("LyX VC: Log Message")))
2473 string path = cmd.getArg(1);
2474 if (contains(path, "$$p") && buffer)
2475 path = subst(path, "$$p", buffer->filePath());
2476 LYXERR(Debug::LYXVC, "Directory: " << path);
2478 if (!pp.isReadableDirectory()) {
2479 lyxerr << _("Directory is not accessible.") << endl;
2482 support::PathChanger p(pp);
2484 string command = cmd.getArg(2);
2485 if (command.empty())
2488 command = subst(command, "$$i", buffer->absFileName());
2489 command = subst(command, "$$p", buffer->filePath());
2491 command = subst(command, "$$m", to_utf8(message));
2492 LYXERR(Debug::LYXVC, "Command: " << command);
2494 one.startscript(Systemcall::Wait, command);
2498 if (contains(flag, 'I'))
2499 buffer->markDirty();
2500 if (contains(flag, 'R'))
2511 void GuiView::openChildDocument(string const & fname)
2513 LASSERT(documentBufferView(), return);
2514 Buffer & buffer = documentBufferView()->buffer();
2515 FileName const filename = support::makeAbsPath(fname, buffer.filePath());
2516 documentBufferView()->saveBookmark(false);
2518 bool parsed = false;
2519 if (theBufferList().exists(filename)) {
2520 child = theBufferList().getBuffer(filename);
2522 message(bformat(_("Opening child document %1$s..."),
2523 makeDisplayPath(filename.absFilename())));
2524 child = loadDocument(filename, false);
2530 // Set the parent name of the child document.
2531 // This makes insertion of citations and references in the child work,
2532 // when the target is in the parent or another child document.
2533 child->setParent(&buffer);
2534 child->masterBuffer()->updateLabels();
2537 child->errors("Parse");
2541 bool GuiView::goToFileRow(string const & argument)
2545 istringstream is(argument);
2546 is >> file_name >> row;
2547 file_name = os::internal_path(file_name);
2549 string const abstmp = package().temp_dir().absFilename();
2550 string const realtmp = package().temp_dir().realPath();
2551 // We have to use os::path_prefix_is() here, instead of
2552 // simply prefixIs(), because the file name comes from
2553 // an external application and may need case adjustment.
2554 if (os::path_prefix_is(file_name, abstmp, os::CASE_ADJUSTED)
2555 || os::path_prefix_is(file_name, realtmp, os::CASE_ADJUSTED)) {
2556 // Needed by inverse dvi search. If it is a file
2557 // in tmpdir, call the apropriated function.
2558 // If tmpdir is a symlink, we may have the real
2559 // path passed back, so we correct for that.
2560 if (!prefixIs(file_name, abstmp))
2561 file_name = subst(file_name, realtmp, abstmp);
2562 buf = theBufferList().getBufferFromTmp(file_name);
2564 // Must replace extension of the file to be .lyx
2565 // and get full path
2566 FileName const s = fileSearch(string(),
2567 support::changeExtension(file_name, ".lyx"), "lyx");
2568 // Either change buffer or load the file
2569 if (theBufferList().exists(s))
2570 buf = theBufferList().getBuffer(s);
2571 else if (s.exists()) {
2572 buf = loadDocument(s);
2573 buf->updateLabels();
2574 buf->errors("Parse");
2577 _("File does not exist: %1$s"),
2578 makeDisplayPath(file_name)));
2583 documentBufferView()->setCursorFromRow(row);
2588 bool GuiView::dispatch(FuncRequest const & cmd)
2590 BufferView * bv = currentBufferView();
2591 // By default we won't need any update.
2593 bv->cursor().updateFlags(Update::None);
2595 Buffer * doc_buffer = documentBufferView()
2596 ? &(documentBufferView()->buffer()) : 0;
2598 bool dispatched = true;
2600 if (cmd.origin == FuncRequest::TOC) {
2601 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
2602 toc->doDispatch(bv->cursor(), cmd);
2606 switch(cmd.action) {
2607 case LFUN_BUFFER_CHILD_OPEN:
2608 openChildDocument(to_utf8(cmd.argument()));
2611 case LFUN_BUFFER_IMPORT:
2612 importDocument(to_utf8(cmd.argument()));
2615 case LFUN_BUFFER_SWITCH:
2616 if (FileName::isAbsolute(to_utf8(cmd.argument()))) {
2618 theBufferList().getBuffer(FileName(to_utf8(cmd.argument())));
2622 message(_("Document not loaded"));
2626 case LFUN_BUFFER_NEXT:
2627 gotoNextOrPreviousBuffer(NEXTBUFFER);
2630 case LFUN_BUFFER_PREVIOUS:
2631 gotoNextOrPreviousBuffer(PREVBUFFER);
2634 case LFUN_COMMAND_EXECUTE: {
2635 bool const show_it = cmd.argument() != "off";
2636 // FIXME: this is a hack, "minibuffer" should not be
2638 if (GuiToolbar * t = toolbar("minibuffer")) {
2639 t->setVisible(show_it);
2640 if (show_it && t->commandBuffer())
2641 t->commandBuffer()->setFocus();
2645 case LFUN_DROP_LAYOUTS_CHOICE:
2646 d.layout_->showPopup();
2649 case LFUN_MENU_OPEN:
2650 if (QMenu * menu = guiApp->menus().menu(toqstr(cmd.argument()), *this))
2651 menu->exec(QCursor::pos());
2654 case LFUN_FILE_INSERT:
2655 insertLyXFile(cmd.argument());
2657 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
2658 insertPlaintextFile(cmd.argument(), true);
2661 case LFUN_FILE_INSERT_PLAINTEXT:
2662 insertPlaintextFile(cmd.argument(), false);
2665 case LFUN_BUFFER_RELOAD: {
2666 LASSERT(doc_buffer, break);
2667 docstring const file = makeDisplayPath(doc_buffer->absFileName(), 20);
2668 docstring text = bformat(_("Any changes will be lost. Are you sure "
2669 "you want to revert to the saved version of the document %1$s?"), file);
2670 int const ret = Alert::prompt(_("Revert to saved document?"),
2671 text, 1, 1, _("&Revert"), _("&Cancel"));
2674 doc_buffer->markClean();
2680 case LFUN_BUFFER_WRITE:
2681 LASSERT(doc_buffer, break);
2682 saveBuffer(*doc_buffer);
2685 case LFUN_BUFFER_WRITE_AS:
2686 LASSERT(doc_buffer, break);
2687 renameBuffer(*doc_buffer, cmd.argument());
2690 case LFUN_BUFFER_WRITE_ALL: {
2691 Buffer * first = theBufferList().first();
2694 message(_("Saving all documents..."));
2695 // We cannot use a for loop as the buffer list cycles.
2698 if (!b->isClean()) {
2700 LYXERR(Debug::ACTION, "Saved " << b->absFileName());
2702 b = theBufferList().next(b);
2703 } while (b != first);
2704 message(_("All documents saved."));
2708 case LFUN_BUFFER_CLOSE:
2712 case LFUN_BUFFER_CLOSE_ALL:
2716 case LFUN_TOOLBAR_TOGGLE: {
2717 string const name = cmd.getArg(0);
2718 if (GuiToolbar * t = toolbar(name))
2723 case LFUN_DIALOG_UPDATE: {
2724 string const name = to_utf8(cmd.argument());
2725 if (currentBufferView()) {
2726 Inset * inset = currentBufferView()->editedInset(name);
2727 // Can only update a dialog connected to an existing inset
2730 // FIXME: get rid of this indirection; GuiView ask the inset
2731 // if he is kind enough to update itself...
2732 FuncRequest fr(LFUN_INSET_DIALOG_UPDATE, cmd.argument());
2733 inset->dispatch(currentBufferView()->cursor(), fr);
2734 } else if (name == "paragraph") {
2735 lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
2736 } else if (name == "prefs" || name == "document") {
2737 updateDialog(name, string());
2742 case LFUN_DIALOG_TOGGLE: {
2743 if (isDialogVisible(cmd.getArg(0)))
2744 dispatch(FuncRequest(LFUN_DIALOG_HIDE, cmd.argument()));
2746 dispatch(FuncRequest(LFUN_DIALOG_SHOW, cmd.argument()));
2750 case LFUN_DIALOG_DISCONNECT_INSET:
2751 disconnectDialog(to_utf8(cmd.argument()));
2754 case LFUN_DIALOG_HIDE: {
2755 guiApp->hideDialogs(to_utf8(cmd.argument()), 0);
2759 case LFUN_DIALOG_SHOW: {
2760 string const name = cmd.getArg(0);
2761 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
2763 if (name == "character") {
2764 data = freefont2string();
2766 showDialog("character", data);
2767 } else if (name == "latexlog") {
2768 Buffer::LogType type;
2769 string const logfile = doc_buffer->logName(&type);
2771 case Buffer::latexlog:
2774 case Buffer::buildlog:
2778 data += Lexer::quoteString(logfile);
2779 showDialog("log", data);
2780 } else if (name == "vclog") {
2781 string const data = "vc " +
2782 Lexer::quoteString(doc_buffer->lyxvc().getLogFile());
2783 showDialog("log", data);
2784 } else if (name == "symbols") {
2785 data = bv->cursor().getEncoding()->name();
2787 showDialog("symbols", data);
2789 } else if (name == "prefs" && isFullScreen()) {
2790 FuncRequest fr(LFUN_INSET_INSERT, "fullscreen");
2792 showDialog("prefs", data);
2794 showDialog(name, data);
2799 message(cmd.argument());
2802 case LFUN_UI_TOGGLE:
2804 // Make sure the keyboard focus stays in the work area.
2808 case LFUN_SPLIT_VIEW: {
2809 LASSERT(doc_buffer, break);
2810 string const orientation = cmd.getArg(0);
2811 d.splitter_->setOrientation(orientation == "vertical"
2812 ? Qt::Vertical : Qt::Horizontal);
2813 TabWorkArea * twa = addTabWorkArea();
2814 GuiWorkArea * wa = twa->addWorkArea(*doc_buffer, *this);
2815 setCurrentWorkArea(wa);
2818 case LFUN_CLOSE_TAB_GROUP:
2819 if (TabWorkArea * twa = d.currentTabWorkArea()) {
2820 closeTabWorkArea(twa);
2821 d.current_work_area_ = 0;
2822 twa = d.currentTabWorkArea();
2823 // Switch to the next GuiWorkArea in the found TabWorkArea.
2825 // Make sure the work area is up to date.
2826 setCurrentWorkArea(twa->currentWorkArea());
2828 setCurrentWorkArea(0);
2833 case LFUN_COMPLETION_INLINE:
2834 if (d.current_work_area_)
2835 d.current_work_area_->completer().showInline();
2838 case LFUN_COMPLETION_POPUP:
2839 if (d.current_work_area_)
2840 d.current_work_area_->completer().showPopup();
2844 case LFUN_COMPLETION_COMPLETE:
2845 if (d.current_work_area_)
2846 d.current_work_area_->completer().tab();
2849 case LFUN_COMPLETION_CANCEL:
2850 if (d.current_work_area_) {
2851 if (d.current_work_area_->completer().popupVisible())
2852 d.current_work_area_->completer().hidePopup();
2854 d.current_work_area_->completer().hideInline();
2858 case LFUN_COMPLETION_ACCEPT:
2859 if (d.current_work_area_)
2860 d.current_work_area_->completer().activate();
2863 case LFUN_BUFFER_ZOOM_IN:
2864 case LFUN_BUFFER_ZOOM_OUT:
2865 if (cmd.argument().empty()) {
2866 if (cmd.action == LFUN_BUFFER_ZOOM_IN)
2871 lyxrc.zoom += convert<int>(cmd.argument());
2873 if (lyxrc.zoom < 10)
2876 // The global QPixmapCache is used in GuiPainter to cache text
2877 // painting so we must reset it.
2878 QPixmapCache::clear();
2879 guiApp->fontLoader().update();
2880 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
2883 case LFUN_VC_REGISTER:
2884 case LFUN_VC_CHECK_IN:
2885 case LFUN_VC_CHECK_OUT:
2886 case LFUN_VC_REPO_UPDATE:
2887 case LFUN_VC_LOCKING_TOGGLE:
2888 case LFUN_VC_REVERT:
2889 case LFUN_VC_UNDO_LAST:
2890 case LFUN_VC_COMMAND:
2894 case LFUN_SERVER_GOTO_FILE_ROW:
2895 goToFileRow(to_utf8(cmd.argument()));
2903 // Part of automatic menu appearance feature.
2904 if (isFullScreen()) {
2905 if (menuBar()->isVisible() && lyxrc.full_screen_menubar)
2907 if (statusBar()->isVisible())
2908 statusBar()->hide();
2915 void GuiView::lfunUiToggle(FuncRequest const & cmd)
2917 string const arg = cmd.getArg(0);
2918 if (arg == "scrollbar") {
2919 // hide() is of no help
2920 if (d.current_work_area_->verticalScrollBarPolicy() ==
2921 Qt::ScrollBarAlwaysOff)
2923 d.current_work_area_->setVerticalScrollBarPolicy(
2924 Qt::ScrollBarAsNeeded);
2926 d.current_work_area_->setVerticalScrollBarPolicy(
2927 Qt::ScrollBarAlwaysOff);
2930 if (arg == "statusbar") {
2931 statusBar()->setVisible(!statusBar()->isVisible());
2934 if (arg == "menubar") {
2935 menuBar()->setVisible(!menuBar()->isVisible());
2938 #if QT_VERSION >= 0x040300
2939 if (arg == "frame") {
2941 getContentsMargins(&l, &t, &r, &b);
2942 //are the frames in default state?
2943 d.current_work_area_->setFrameStyle(QFrame::NoFrame);
2945 setContentsMargins(-2, -2, -2, -2);
2947 setContentsMargins(0, 0, 0, 0);
2952 if (arg == "fullscreen") {
2957 message(bformat("LFUN_UI_TOGGLE " + _("%1$s unknown command!"), from_utf8(arg)));
2961 void GuiView::toggleFullScreen()
2963 if (isFullScreen()) {
2964 for (int i = 0; i != d.splitter_->count(); ++i)
2965 d.tabWorkArea(i)->setFullScreen(false);
2966 #if QT_VERSION >= 0x040300
2967 setContentsMargins(0, 0, 0, 0);
2969 setWindowState(windowState() ^ Qt::WindowFullScreen);
2972 statusBar()->show();
2975 hideDialogs("prefs", 0);
2976 for (int i = 0; i != d.splitter_->count(); ++i)
2977 d.tabWorkArea(i)->setFullScreen(true);
2978 #if QT_VERSION >= 0x040300
2979 setContentsMargins(-2, -2, -2, -2);
2982 setWindowState(windowState() ^ Qt::WindowFullScreen);
2983 statusBar()->hide();
2984 if (lyxrc.full_screen_menubar)
2986 if (lyxrc.full_screen_toolbars) {
2987 ToolbarMap::iterator end = d.toolbars_.end();
2988 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
2993 // give dialogs like the TOC a chance to adapt
2998 Buffer const * GuiView::updateInset(Inset const * inset)
3000 if (!d.current_work_area_)
3004 d.current_work_area_->scheduleRedraw();
3006 return &d.current_work_area_->bufferView().buffer();
3010 void GuiView::restartCursor()
3012 /* When we move around, or type, it's nice to be able to see
3013 * the cursor immediately after the keypress.
3015 if (d.current_work_area_)
3016 d.current_work_area_->startBlinkingCursor();
3018 // Take this occasion to update the other GUI elements.
3024 void GuiView::updateCompletion(Cursor & cur, bool start, bool keep)
3026 if (d.current_work_area_)
3027 d.current_work_area_->completer().updateVisibility(cur, start, keep);
3032 // This list should be kept in sync with the list of insets in
3033 // src/insets/Inset.cpp. I.e., if a dialog goes with an inset, the
3034 // dialog should have the same name as the inset.
3035 // Changes should be also recorded in LFUN_DIALOG_SHOW doxygen
3036 // docs in LyXAction.cpp.
3038 char const * const dialognames[] = {
3039 "aboutlyx", "bibitem", "bibtex", "box", "branch", "changes", "character",
3040 "citation", "compare", "document", "errorlist", "ert", "external", "file",
3041 "findreplace", "findreplaceadv", "float", "graphics", "href", "include",
3042 "index", "index_print", "info", "listings", "label", "log", "mathdelimiter",
3043 "mathmatrix", "mathspace", "nomenclature", "nomencl_print", "note",
3044 "paragraph", "phantom", "prefs", "print", "ref", "sendto", "space",
3045 "spellchecker", "symbols", "tabular", "tabularcreate", "thesaurus", "texinfo",
3046 "toc", "view-source", "vspace", "wrap" };
3048 char const * const * const end_dialognames =
3049 dialognames + (sizeof(dialognames) / sizeof(char *));
3053 cmpCStr(char const * name) : name_(name) {}
3054 bool operator()(char const * other) {
3055 return strcmp(other, name_) == 0;
3062 bool isValidName(string const & name)
3064 return find_if(dialognames, end_dialognames,
3065 cmpCStr(name.c_str())) != end_dialognames;
3071 void GuiView::resetDialogs()
3073 // Make sure that no LFUN uses any LyXView.
3074 guiApp->setCurrentView(0);
3077 constructToolbars();
3078 guiApp->menus().fillMenuBar(menuBar(), this, false);
3079 d.layout_->updateContents(true);
3080 // Now update controls with current buffer.
3081 guiApp->setCurrentView(this);
3087 Dialog * GuiView::findOrBuild(string const & name, bool hide_it)
3089 if (!isValidName(name))
3092 map<string, DialogPtr>::iterator it = d.dialogs_.find(name);
3094 if (it != d.dialogs_.end()) {
3096 it->second->hideView();
3097 return it->second.get();
3100 Dialog * dialog = build(name);
3101 d.dialogs_[name].reset(dialog);
3102 if (lyxrc.allow_geometry_session)
3103 dialog->restoreSession();
3110 void GuiView::showDialog(string const & name, string const & data,
3118 Dialog * dialog = findOrBuild(name, false);
3120 dialog->showData(data);
3121 if (inset && currentBufferView())
3122 currentBufferView()->editInset(name, inset);
3125 catch (ExceptionMessage const & ex) {
3133 bool GuiView::isDialogVisible(string const & name) const
3135 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3136 if (it == d.dialogs_.end())
3138 return it->second.get()->isVisibleView() && !it->second.get()->isClosing();
3142 void GuiView::hideDialog(string const & name, Inset * inset)
3144 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3145 if (it == d.dialogs_.end())
3148 if (inset && currentBufferView()
3149 && inset != currentBufferView()->editedInset(name))
3152 Dialog * const dialog = it->second.get();
3153 if (dialog->isVisibleView())
3155 if (currentBufferView())
3156 currentBufferView()->editInset(name, 0);
3160 void GuiView::disconnectDialog(string const & name)
3162 if (!isValidName(name))
3164 if (currentBufferView())
3165 currentBufferView()->editInset(name, 0);
3169 void GuiView::hideAll() const
3171 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
3172 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3174 for(; it != end; ++it)
3175 it->second->hideView();
3179 void GuiView::updateDialogs()
3181 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
3182 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3184 for(; it != end; ++it) {
3185 Dialog * dialog = it->second.get();
3186 if (dialog && dialog->isVisibleView())
3187 dialog->checkStatus();
3194 // will be replaced by a proper factory...
3195 Dialog * createGuiAbout(GuiView & lv);
3196 Dialog * createGuiBibitem(GuiView & lv);
3197 Dialog * createGuiBibtex(GuiView & lv);
3198 Dialog * createGuiBox(GuiView & lv);
3199 Dialog * createGuiBranch(GuiView & lv);
3200 Dialog * createGuiChanges(GuiView & lv);
3201 Dialog * createGuiCharacter(GuiView & lv);
3202 Dialog * createGuiCitation(GuiView & lv);
3203 Dialog * createGuiCompare(GuiView & lv);
3204 Dialog * createGuiDelimiter(GuiView & lv);
3205 Dialog * createGuiDocument(GuiView & lv);
3206 Dialog * createGuiErrorList(GuiView & lv);
3207 Dialog * createGuiERT(GuiView & lv);
3208 Dialog * createGuiExternal(GuiView & lv);
3209 Dialog * createGuiFloat(GuiView & lv);
3210 Dialog * createGuiGraphics(GuiView & lv);
3211 Dialog * createGuiInclude(GuiView & lv);
3212 Dialog * createGuiIndex(GuiView & lv);
3213 Dialog * createGuiInfo(GuiView & lv);
3214 Dialog * createGuiLabel(GuiView & lv);
3215 Dialog * createGuiListings(GuiView & lv);
3216 Dialog * createGuiLog(GuiView & lv);
3217 Dialog * createGuiMathHSpace(GuiView & lv);
3218 Dialog * createGuiMathMatrix(GuiView & lv);
3219 Dialog * createGuiNomenclature(GuiView & lv);
3220 Dialog * createGuiNote(GuiView & lv);
3221 Dialog * createGuiParagraph(GuiView & lv);
3222 Dialog * createGuiPhantom(GuiView & lv);
3223 Dialog * createGuiPreferences(GuiView & lv);
3224 Dialog * createGuiPrint(GuiView & lv);
3225 Dialog * createGuiPrintindex(GuiView & lv);
3226 Dialog * createGuiPrintNomencl(GuiView & lv);
3227 Dialog * createGuiRef(GuiView & lv);
3228 Dialog * createGuiSearch(GuiView & lv);
3229 Dialog * createGuiSearchAdv(GuiView & lv);
3230 Dialog * createGuiSendTo(GuiView & lv);
3231 Dialog * createGuiShowFile(GuiView & lv);
3232 Dialog * createGuiSpellchecker(GuiView & lv);
3233 Dialog * createGuiSymbols(GuiView & lv);
3234 Dialog * createGuiTabularCreate(GuiView & lv);
3235 Dialog * createGuiTabular(GuiView & lv);
3236 Dialog * createGuiTexInfo(GuiView & lv);
3237 Dialog * createGuiTextHSpace(GuiView & lv);
3238 Dialog * createGuiToc(GuiView & lv);
3239 Dialog * createGuiThesaurus(GuiView & lv);
3240 Dialog * createGuiHyperlink(GuiView & lv);
3241 Dialog * createGuiVSpace(GuiView & lv);
3242 Dialog * createGuiViewSource(GuiView & lv);
3243 Dialog * createGuiWrap(GuiView & lv);
3246 Dialog * GuiView::build(string const & name)
3248 LASSERT(isValidName(name), return 0);
3250 if (name == "aboutlyx")
3251 return createGuiAbout(*this);
3252 if (name == "bibitem")
3253 return createGuiBibitem(*this);
3254 if (name == "bibtex")
3255 return createGuiBibtex(*this);
3257 return createGuiBox(*this);
3258 if (name == "branch")
3259 return createGuiBranch(*this);
3260 if (name == "changes")
3261 return createGuiChanges(*this);
3262 if (name == "character")
3263 return createGuiCharacter(*this);
3264 if (name == "citation")
3265 return createGuiCitation(*this);
3266 if (name == "compare")
3267 return createGuiCompare(*this);
3268 if (name == "document")
3269 return createGuiDocument(*this);
3270 if (name == "errorlist")
3271 return createGuiErrorList(*this);
3273 return createGuiERT(*this);
3274 if (name == "external")
3275 return createGuiExternal(*this);
3277 return createGuiShowFile(*this);
3278 if (name == "findreplace")
3279 return createGuiSearch(*this);
3280 if (name == "findreplaceadv")
3281 return createGuiSearchAdv(*this);
3282 if (name == "float")
3283 return createGuiFloat(*this);
3284 if (name == "graphics")
3285 return createGuiGraphics(*this);
3287 return createGuiHyperlink(*this);
3288 if (name == "include")
3289 return createGuiInclude(*this);
3290 if (name == "index")
3291 return createGuiIndex(*this);
3292 if (name == "index_print")
3293 return createGuiPrintindex(*this);
3295 return createGuiInfo(*this);
3296 if (name == "label")
3297 return createGuiLabel(*this);
3298 if (name == "listings")
3299 return createGuiListings(*this);
3301 return createGuiLog(*this);
3302 if (name == "mathdelimiter")
3303 return createGuiDelimiter(*this);
3304 if (name == "mathspace")
3305 return createGuiMathHSpace(*this);
3306 if (name == "mathmatrix")
3307 return createGuiMathMatrix(*this);
3308 if (name == "nomenclature")
3309 return createGuiNomenclature(*this);
3310 if (name == "nomencl_print")
3311 return createGuiPrintNomencl(*this);
3313 return createGuiNote(*this);
3314 if (name == "paragraph")
3315 return createGuiParagraph(*this);
3316 if (name == "phantom")
3317 return createGuiPhantom(*this);
3318 if (name == "prefs")
3319 return createGuiPreferences(*this);
3320 if (name == "print")
3321 return createGuiPrint(*this);
3323 return createGuiRef(*this);
3324 if (name == "sendto")
3325 return createGuiSendTo(*this);
3326 if (name == "space")
3327 return createGuiTextHSpace(*this);
3328 if (name == "spellchecker")
3329 return createGuiSpellchecker(*this);
3330 if (name == "symbols")
3331 return createGuiSymbols(*this);
3332 if (name == "tabular")
3333 return createGuiTabular(*this);
3334 if (name == "tabularcreate")
3335 return createGuiTabularCreate(*this);
3336 if (name == "texinfo")
3337 return createGuiTexInfo(*this);
3338 if (name == "thesaurus")
3339 return createGuiThesaurus(*this);
3341 return createGuiToc(*this);
3342 if (name == "view-source")
3343 return createGuiViewSource(*this);
3344 if (name == "vspace")
3345 return createGuiVSpace(*this);
3347 return createGuiWrap(*this);
3353 } // namespace frontend
3356 #include "moc_GuiView.cpp"