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 #include <boost/bind.hpp>
109 #ifdef HAVE_SYS_TIME_H
110 # include <sys/time.h>
117 using namespace lyx::support;
124 class BackgroundWidget : public QWidget
129 LYXERR(Debug::GUI, "show banner: " << lyxrc.show_banner);
130 /// The text to be written on top of the pixmap
131 QString const text = lyx_version ?
132 qt_("version ") + lyx_version : qt_("unknown version");
133 splash_ = getPixmap("images/", "banner", "png");
135 QPainter pain(&splash_);
136 pain.setPen(QColor(0, 0, 0));
138 // The font used to display the version info
139 font.setStyleHint(QFont::SansSerif);
140 font.setWeight(QFont::Bold);
141 font.setPointSize(int(toqstr(lyxrc.font_sizes[FONT_SIZE_LARGE]).toDouble()));
143 pain.drawText(260, 15, text);
146 void paintEvent(QPaintEvent *)
148 int x = (width() - splash_.width()) / 2;
149 int y = (height() - splash_.height()) / 2;
151 pain.drawPixmap(x, y, splash_);
159 /// Toolbar store providing access to individual toolbars by name.
160 typedef std::map<std::string, GuiToolbar *> ToolbarMap;
162 typedef boost::shared_ptr<Dialog> DialogPtr;
167 struct GuiView::GuiViewPrivate
170 : current_work_area_(0), current_main_work_area_(0),
171 layout_(0), autosave_timeout_(5000),
174 // hardcode here the platform specific icon size
175 smallIconSize = 14; // scaling problems
176 normalIconSize = 20; // ok, default
177 bigIconSize = 26; // better for some math icons
179 splitter_ = new QSplitter;
180 bg_widget_ = new BackgroundWidget;
181 stack_widget_ = new QStackedWidget;
182 stack_widget_->addWidget(bg_widget_);
183 stack_widget_->addWidget(splitter_);
191 delete stack_widget_;
194 QMenu * toolBarPopup(GuiView * parent)
196 // FIXME: translation
197 QMenu * menu = new QMenu(parent);
198 QActionGroup * iconSizeGroup = new QActionGroup(parent);
200 QAction * smallIcons = new QAction(iconSizeGroup);
201 smallIcons->setText(qt_("Small-sized icons"));
202 smallIcons->setCheckable(true);
203 QObject::connect(smallIcons, SIGNAL(triggered()),
204 parent, SLOT(smallSizedIcons()));
205 menu->addAction(smallIcons);
207 QAction * normalIcons = new QAction(iconSizeGroup);
208 normalIcons->setText(qt_("Normal-sized icons"));
209 normalIcons->setCheckable(true);
210 QObject::connect(normalIcons, SIGNAL(triggered()),
211 parent, SLOT(normalSizedIcons()));
212 menu->addAction(normalIcons);
214 QAction * bigIcons = new QAction(iconSizeGroup);
215 bigIcons->setText(qt_("Big-sized icons"));
216 bigIcons->setCheckable(true);
217 QObject::connect(bigIcons, SIGNAL(triggered()),
218 parent, SLOT(bigSizedIcons()));
219 menu->addAction(bigIcons);
221 unsigned int cur = parent->iconSize().width();
222 if ( cur == parent->d.smallIconSize)
223 smallIcons->setChecked(true);
224 else if (cur == parent->d.normalIconSize)
225 normalIcons->setChecked(true);
226 else if (cur == parent->d.bigIconSize)
227 bigIcons->setChecked(true);
234 stack_widget_->setCurrentWidget(bg_widget_);
235 bg_widget_->setUpdatesEnabled(true);
238 TabWorkArea * tabWorkArea(int i)
240 return dynamic_cast<TabWorkArea *>(splitter_->widget(i));
243 TabWorkArea * currentTabWorkArea()
245 if (splitter_->count() == 1)
246 // The first TabWorkArea is always the first one, if any.
247 return tabWorkArea(0);
249 for (int i = 0; i != splitter_->count(); ++i) {
250 TabWorkArea * twa = tabWorkArea(i);
251 if (current_main_work_area_ == twa->currentWorkArea())
255 // None has the focus so we just take the first one.
256 return tabWorkArea(0);
260 GuiWorkArea * current_work_area_;
261 GuiWorkArea * current_main_work_area_;
262 QSplitter * splitter_;
263 QStackedWidget * stack_widget_;
264 BackgroundWidget * bg_widget_;
266 ToolbarMap toolbars_;
267 /// The main layout box.
269 * \warning Don't Delete! The layout box is actually owned by
270 * whichever toolbar contains it. All the GuiView class needs is a
271 * means of accessing it.
273 * FIXME: replace that with a proper model so that we are not limited
274 * to only one dialog.
279 map<string, DialogPtr> dialogs_;
281 unsigned int smallIconSize;
282 unsigned int normalIconSize;
283 unsigned int bigIconSize;
285 QTimer statusbar_timer_;
286 /// auto-saving of buffers
287 Timeout autosave_timeout_;
288 /// flag against a race condition due to multiclicks, see bug #1119
292 TocModels toc_models_;
296 GuiView::GuiView(int id)
297 : d(*new GuiViewPrivate), id_(id), closing_(false)
299 // GuiToolbars *must* be initialised before the menu bar.
300 normalSizedIcons(); // at least on Mac the default is 32 otherwise, which is huge
303 // set ourself as the current view. This is needed for the menu bar
304 // filling, at least for the static special menu item on Mac. Otherwise
305 // they are greyed out.
306 guiApp->setCurrentView(this);
308 // Fill up the menu bar.
309 guiApp->menus().fillMenuBar(menuBar(), this, true);
311 setCentralWidget(d.stack_widget_);
313 // Start autosave timer
314 if (lyxrc.autosave) {
315 d.autosave_timeout_.timeout.connect(boost::bind(&GuiView::autoSave, this));
316 d.autosave_timeout_.setTimeout(lyxrc.autosave * 1000);
317 d.autosave_timeout_.start();
319 connect(&d.statusbar_timer_, SIGNAL(timeout()),
320 this, SLOT(clearMessage()));
322 // We don't want to keep the window in memory if it is closed.
323 setAttribute(Qt::WA_DeleteOnClose, true);
325 #if (!defined(Q_WS_WIN) && !defined(Q_WS_MACX))
326 // assign an icon to main form. We do not do it under Qt/Win or Qt/Mac,
327 // since the icon is provided in the application bundle.
328 setWindowIcon(getPixmap("images/", "lyx", "png"));
332 setAcceptDrops(true);
334 statusBar()->setSizeGripEnabled(true);
336 // Forbid too small unresizable window because it can happen
337 // with some window manager under X11.
338 setMinimumSize(300, 200);
340 if (lyxrc.allow_geometry_session) {
341 // Now take care of session management.
346 // no session handling, default to a sane size.
347 setGeometry(50, 50, 690, 510);
350 // clear session data if any.
352 settings.remove("views");
362 void GuiView::saveLayout() const
365 settings.beginGroup("views");
366 settings.beginGroup(QString::number(id_));
368 settings.setValue("pos", pos());
369 settings.setValue("size", size());
371 settings.setValue("geometry", saveGeometry());
373 settings.setValue("layout", saveState(0));
374 settings.setValue("icon_size", iconSize());
378 bool GuiView::restoreLayout()
381 settings.beginGroup("views");
382 settings.beginGroup(QString::number(id_));
383 QString const icon_key = "icon_size";
384 if (!settings.contains(icon_key))
387 //code below is skipped when when ~/.config/LyX is (re)created
388 setIconSize(settings.value(icon_key).toSize());
390 QPoint pos = settings.value("pos", QPoint(50, 50)).toPoint();
391 QSize size = settings.value("size", QSize(690, 510)).toSize();
395 // Work-around for bug #6034: the window ends up in an undetermined
396 // state when trying to restore a maximized window when it is
397 // already maximized.
398 if (!(windowState() & Qt::WindowMaximized))
399 if (!restoreGeometry(settings.value("geometry").toByteArray()))
400 setGeometry(50, 50, 690, 510);
402 // Make sure layout is correctly oriented.
403 setLayoutDirection(qApp->layoutDirection());
405 // Allow the toc and view-source dock widget to be restored if needed.
407 if ((dialog = findOrBuild("toc", true)))
408 // see bug 5082. At least setup title and enabled state.
409 // Visibility will be adjusted by restoreState below.
410 dialog->prepareView();
411 if ((dialog = findOrBuild("view-source", true)))
412 dialog->prepareView();
414 if (!restoreState(settings.value("layout").toByteArray(), 0))
421 GuiToolbar * GuiView::toolbar(string const & name)
423 ToolbarMap::iterator it = d.toolbars_.find(name);
424 if (it != d.toolbars_.end())
427 LYXERR(Debug::GUI, "Toolbar::display: no toolbar named " << name);
428 message(bformat(_("Unknown toolbar \"%1$s\""), from_utf8(name)));
433 void GuiView::constructToolbars()
435 ToolbarMap::iterator it = d.toolbars_.begin();
436 for (; it != d.toolbars_.end(); ++it)
440 // I don't like doing this here, but the standard toolbar
441 // destroys this object when it's destroyed itself (vfr)
442 d.layout_ = new LayoutBox(*this);
443 d.stack_widget_->addWidget(d.layout_);
444 d.layout_->move(0,0);
446 // extracts the toolbars from the backend
447 Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
448 Toolbars::Infos::iterator end = guiApp->toolbars().end();
449 for (; cit != end; ++cit)
450 d.toolbars_[cit->name] = new GuiToolbar(*cit, *this);
454 void GuiView::initToolbars()
456 // extracts the toolbars from the backend
457 Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
458 Toolbars::Infos::iterator end = guiApp->toolbars().end();
459 for (; cit != end; ++cit) {
460 GuiToolbar * tb = toolbar(cit->name);
463 int const visibility = guiApp->toolbars().defaultVisibility(cit->name);
465 tb->setVisible(false);
466 tb->setVisibility(visibility);
468 if (visibility & Toolbars::TOP) {
470 addToolBarBreak(Qt::TopToolBarArea);
471 addToolBar(Qt::TopToolBarArea, tb);
474 if (visibility & Toolbars::BOTTOM) {
475 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
476 #if (QT_VERSION >= 0x040202)
477 addToolBarBreak(Qt::BottomToolBarArea);
479 addToolBar(Qt::BottomToolBarArea, tb);
482 if (visibility & Toolbars::LEFT) {
483 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
484 #if (QT_VERSION >= 0x040202)
485 addToolBarBreak(Qt::LeftToolBarArea);
487 addToolBar(Qt::LeftToolBarArea, tb);
490 if (visibility & Toolbars::RIGHT) {
491 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
492 #if (QT_VERSION >= 0x040202)
493 addToolBarBreak(Qt::RightToolBarArea);
495 addToolBar(Qt::RightToolBarArea, tb);
498 if (visibility & Toolbars::ON)
499 tb->setVisible(true);
504 TocModels & GuiView::tocModels()
506 return d.toc_models_;
510 void GuiView::setFocus()
512 LYXERR(Debug::DEBUG, "GuiView::setFocus()" << this);
513 // Make sure LyXFunc points to the correct view.
514 guiApp->setCurrentView(this);
515 QMainWindow::setFocus();
516 if (d.current_work_area_)
517 d.current_work_area_->setFocus();
521 QMenu * GuiView::createPopupMenu()
523 return d.toolBarPopup(this);
527 void GuiView::showEvent(QShowEvent * e)
529 LYXERR(Debug::GUI, "Passed Geometry "
530 << size().height() << "x" << size().width()
531 << "+" << pos().x() << "+" << pos().y());
533 if (d.splitter_->count() == 0)
534 // No work area, switch to the background widget.
537 QMainWindow::showEvent(e);
541 /** Destroy only all tabbed WorkAreas. Destruction of other WorkAreas
542 ** is responsibility of the container (e.g., dialog)
544 void GuiView::closeEvent(QCloseEvent * close_event)
546 LYXERR(Debug::DEBUG, "GuiView::closeEvent()");
551 // it can happen that this event arrives without selecting the view,
552 // e.g. when clicking the close button on a background window.
554 if (!closeWorkAreaAll()) {
556 close_event->ignore();
560 // Make sure that nothing will use this to be closed View.
561 guiApp->unregisterView(this);
563 if (isFullScreen()) {
564 // Switch off fullscreen before closing.
569 // Make sure the timer time out will not trigger a statusbar update.
570 d.statusbar_timer_.stop();
572 // Saving fullscreen requires additional tweaks in the toolbar code.
573 // It wouldn't also work under linux natively.
574 if (lyxrc.allow_geometry_session) {
575 // Save this window geometry and layout.
577 // Then the toolbar private states.
578 ToolbarMap::iterator end = d.toolbars_.end();
579 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
580 it->second->saveSession();
581 // Now take care of all other dialogs:
582 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
583 for (; it!= d.dialogs_.end(); ++it)
584 it->second->saveSession();
587 close_event->accept();
591 void GuiView::dragEnterEvent(QDragEnterEvent * event)
593 if (event->mimeData()->hasUrls())
595 /// \todo Ask lyx-devel is this is enough:
596 /// if (event->mimeData()->hasFormat("text/plain"))
597 /// event->acceptProposedAction();
601 void GuiView::dropEvent(QDropEvent * event)
603 QList<QUrl> files = event->mimeData()->urls();
607 LYXERR(Debug::GUI, "GuiView::dropEvent: got URLs!");
608 for (int i = 0; i != files.size(); ++i) {
609 string const file = os::internal_path(fromqstr(
610 files.at(i).toLocalFile()));
612 // Asynchronously post the event. DropEvent usually come
613 // from the BufferView. But reloading a file might close
614 // the BufferView from within its own event handler.
615 guiApp->dispatchDelayed(FuncRequest(LFUN_FILE_OPEN, file));
622 void GuiView::message(docstring const & str)
624 if (ForkedProcess::iAmAChild())
627 statusBar()->showMessage(toqstr(str));
628 d.statusbar_timer_.stop();
629 d.statusbar_timer_.start(3000);
633 void GuiView::smallSizedIcons()
635 setIconSize(QSize(d.smallIconSize, d.smallIconSize));
639 void GuiView::normalSizedIcons()
641 setIconSize(QSize(d.normalIconSize, d.normalIconSize));
645 void GuiView::bigSizedIcons()
647 setIconSize(QSize(d.bigIconSize, d.bigIconSize));
651 void GuiView::clearMessage()
656 d.statusbar_timer_.stop();
660 void GuiView::updateWindowTitle(GuiWorkArea * wa)
662 if (wa != d.current_work_area_)
664 setWindowTitle(qt_("LyX: ") + wa->windowTitle());
665 setWindowIconText(wa->windowIconText());
669 void GuiView::on_currentWorkAreaChanged(GuiWorkArea * wa)
672 disconnectBufferView();
673 connectBufferView(wa->bufferView());
674 connectBuffer(wa->bufferView().buffer());
675 d.current_work_area_ = wa;
676 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
677 this, SLOT(updateWindowTitle(GuiWorkArea *)));
678 updateWindowTitle(wa);
682 // The document settings needs to be reinitialised.
683 updateDialog("document", "");
685 // Buffer-dependent dialogs must be updated. This is done here because
686 // some dialogs require buffer()->text.
691 void GuiView::on_lastWorkAreaRemoved()
694 // We already are in a close event. Nothing more to do.
697 if (d.splitter_->count() > 1)
698 // We have a splitter so don't close anything.
701 // Reset and updates the dialogs.
702 d.toc_models_.reset(0);
703 updateDialog("document", "");
706 resetWindowTitleAndIconText();
708 if (lyxrc.open_buffers_in_tabs)
709 // Nothing more to do, the window should stay open.
712 if (guiApp->viewIds().size() > 1) {
718 // On Mac we also close the last window because the application stay
719 // resident in memory. On other platforms we don't close the last
720 // window because this would quit the application.
726 void GuiView::updateStatusBar()
728 // let the user see the explicit message
729 if (d.statusbar_timer_.isActive())
736 void GuiView::showMessage()
738 QString msg = toqstr(theGuiApp()->viewStatusMessage());
740 BufferView const * bv = currentBufferView();
742 msg = toqstr(bv->cursor().currentState());
744 msg = qt_("Welcome to LyX!");
746 statusBar()->showMessage(msg);
750 bool GuiView::event(QEvent * e)
754 // Useful debug code:
755 //case QEvent::ActivationChange:
756 //case QEvent::WindowDeactivate:
757 //case QEvent::Paint:
758 //case QEvent::Enter:
759 //case QEvent::Leave:
760 //case QEvent::HoverEnter:
761 //case QEvent::HoverLeave:
762 //case QEvent::HoverMove:
763 //case QEvent::StatusTip:
764 //case QEvent::DragEnter:
765 //case QEvent::DragLeave:
769 case QEvent::WindowActivate: {
770 GuiView * old_view = guiApp->currentView();
771 if (this == old_view) {
773 return QMainWindow::event(e);
775 if (old_view && old_view->currentBufferView()) {
776 // save current selection to the selection buffer to allow
777 // middle-button paste in this window.
778 cap::saveSelection(old_view->currentBufferView()->cursor());
780 guiApp->setCurrentView(this);
781 if (d.current_work_area_) {
782 BufferView & bv = d.current_work_area_->bufferView();
783 connectBufferView(bv);
784 connectBuffer(bv.buffer());
785 // The document structure, name and dialogs might have
786 // changed in another view.
788 // The document settings needs to be reinitialised.
789 updateDialog("document", "");
792 resetWindowTitleAndIconText();
795 return QMainWindow::event(e);
798 case QEvent::ShortcutOverride: {
801 #if (!defined Q_WS_X11) || (QT_VERSION >= 0x040500)
802 if (isFullScreen() && menuBar()->isHidden()) {
803 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
804 // FIXME: we should also try to detect special LyX shortcut such as
805 // Alt-P and Alt-M. Right now there is a hack in
806 // GuiWorkArea::processKeySym() that hides again the menubar for
808 if (ke->modifiers() & Qt::AltModifier && ke->key() != Qt::Key_Alt) {
810 return QMainWindow::event(e);
815 if (d.current_work_area_)
816 // Nothing special to do.
817 return QMainWindow::event(e);
819 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
820 // Let Qt handle menu access and the Tab keys to navigate keys to navigate
822 if (ke->modifiers() & Qt::AltModifier || ke->key() == Qt::Key_Tab
823 || ke->key() == Qt::Key_Backtab)
824 return QMainWindow::event(e);
826 // Allow processing of shortcuts that are allowed even when no Buffer
829 setKeySymbol(&sym, ke);
830 guiApp->processKeySym(sym, q_key_state(ke->modifiers()));
836 return QMainWindow::event(e);
840 void GuiView::resetWindowTitleAndIconText()
842 setWindowTitle(qt_("LyX"));
843 setWindowIconText(qt_("LyX"));
846 bool GuiView::focusNextPrevChild(bool /*next*/)
853 void GuiView::setBusy(bool busy)
855 if (d.current_work_area_) {
856 d.current_work_area_->setUpdatesEnabled(!busy);
858 d.current_work_area_->stopBlinkingCursor();
860 d.current_work_area_->startBlinkingCursor();
864 QApplication::setOverrideCursor(Qt::WaitCursor);
866 QApplication::restoreOverrideCursor();
870 GuiWorkArea * GuiView::workArea(Buffer & buffer)
872 if (currentWorkArea()
873 && ¤tWorkArea()->bufferView().buffer() == &buffer)
874 return (GuiWorkArea *) currentWorkArea();
875 if (TabWorkArea * twa = d.currentTabWorkArea())
876 return twa->workArea(buffer);
881 GuiWorkArea * GuiView::addWorkArea(Buffer & buffer)
883 // Automatically create a TabWorkArea if there are none yet.
884 TabWorkArea * tab_widget = d.splitter_->count()
885 ? d.currentTabWorkArea() : addTabWorkArea();
886 return tab_widget->addWorkArea(buffer, *this);
890 TabWorkArea * GuiView::addTabWorkArea()
892 TabWorkArea * twa = new TabWorkArea;
893 QObject::connect(twa, SIGNAL(currentWorkAreaChanged(GuiWorkArea *)),
894 this, SLOT(on_currentWorkAreaChanged(GuiWorkArea *)));
895 QObject::connect(twa, SIGNAL(lastWorkAreaRemoved()),
896 this, SLOT(on_lastWorkAreaRemoved()));
898 d.splitter_->addWidget(twa);
899 d.stack_widget_->setCurrentWidget(d.splitter_);
904 GuiWorkArea const * GuiView::currentWorkArea() const
906 return d.current_work_area_;
910 GuiWorkArea * GuiView::currentWorkArea()
912 return d.current_work_area_;
916 GuiWorkArea const * GuiView::currentMainWorkArea() const
918 if (d.currentTabWorkArea() == NULL)
920 return d.currentTabWorkArea()->currentWorkArea();
924 GuiWorkArea * GuiView::currentMainWorkArea()
926 if (d.currentTabWorkArea() == NULL)
928 return d.currentTabWorkArea()->currentWorkArea();
932 void GuiView::setCurrentWorkArea(GuiWorkArea * wa)
934 LYXERR(Debug::DEBUG, "Setting current wa: " << wa << endl);
936 d.current_work_area_ = NULL;
940 GuiWorkArea * old_gwa = theGuiApp()->currentView()->currentWorkArea();
944 if (currentBufferView())
945 cap::saveSelection(currentBufferView()->cursor());
947 theGuiApp()->setCurrentView(this);
948 d.current_work_area_ = wa;
949 for (int i = 0; i != d.splitter_->count(); ++i) {
950 if (d.tabWorkArea(i)->setCurrentWorkArea(wa)) {
951 //if (d.current_main_work_area_)
952 // d.current_main_work_area_->setFrameStyle(QFrame::NoFrame);
953 d.current_main_work_area_ = wa;
954 //d.current_main_work_area_->setFrameStyle(QFrame::Box | QFrame::Plain);
955 //d.current_main_work_area_->setLineWidth(2);
956 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() << ", Current main wa: " << currentMainWorkArea());
960 LYXERR(Debug::DEBUG, "This is not a tabbed wa");
961 on_currentWorkAreaChanged(wa);
962 BufferView & bv = wa->bufferView();
963 bv.cursor().fixIfBroken();
965 wa->setUpdatesEnabled(true);
966 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() << ", Current main wa: " << currentMainWorkArea());
970 void GuiView::removeWorkArea(GuiWorkArea * wa)
973 if (wa == d.current_work_area_) {
975 disconnectBufferView();
976 d.current_work_area_ = 0;
977 d.current_main_work_area_ = 0;
980 bool found_twa = false;
981 for (int i = 0; i != d.splitter_->count(); ++i) {
982 TabWorkArea * twa = d.tabWorkArea(i);
983 if (twa->removeWorkArea(wa)) {
984 // Found in this tab group, and deleted the GuiWorkArea.
986 if (twa->count() != 0) {
987 if (d.current_work_area_ == 0)
988 // This means that we are closing the current GuiWorkArea, so
989 // switch to the next GuiWorkArea in the found TabWorkArea.
990 setCurrentWorkArea(twa->currentWorkArea());
992 // No more WorkAreas in this tab group, so delete it.
999 // It is not a tabbed work area (i.e., the search work area), so it
1000 // should be deleted by other means.
1001 LASSERT(found_twa, /* */);
1003 if (d.current_work_area_ == 0) {
1004 if (d.splitter_->count() != 0) {
1005 TabWorkArea * twa = d.currentTabWorkArea();
1006 setCurrentWorkArea(twa->currentWorkArea());
1008 // No more work areas, switch to the background widget.
1009 setCurrentWorkArea(0);
1015 LayoutBox * GuiView::getLayoutDialog() const
1021 void GuiView::updateLayoutList()
1024 d.layout_->updateContents(false);
1028 void GuiView::updateToolbars()
1030 ToolbarMap::iterator end = d.toolbars_.end();
1031 if (d.current_work_area_) {
1033 d.current_work_area_->bufferView().cursor().inMathed();
1035 lyx::getStatus(FuncRequest(LFUN_LAYOUT_TABULAR)).enabled();
1037 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).enabled() &&
1038 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).onoff(true);
1039 bool const mathmacrotemplate =
1040 lyx::getStatus(FuncRequest(LFUN_IN_MATHMACROTEMPLATE)).enabled();
1042 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1043 it->second->update(math, table, review, mathmacrotemplate);
1045 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1046 it->second->update(false, false, false, false);
1050 void GuiView::setBuffer(Buffer * newBuffer)
1052 LYXERR(Debug::DEBUG, "Setting buffer: " << newBuffer << std::endl);
1053 LASSERT(newBuffer, return);
1056 GuiWorkArea * wa = workArea(*newBuffer);
1058 newBuffer->masterBuffer()->updateLabels();
1059 wa = addWorkArea(*newBuffer);
1061 //Disconnect the old buffer...there's no new one.
1064 connectBuffer(*newBuffer);
1065 connectBufferView(wa->bufferView());
1066 setCurrentWorkArea(wa);
1072 void GuiView::connectBuffer(Buffer & buf)
1074 buf.setGuiDelegate(this);
1078 void GuiView::disconnectBuffer()
1080 if (d.current_work_area_)
1081 d.current_work_area_->bufferView().buffer().setGuiDelegate(0);
1085 void GuiView::connectBufferView(BufferView & bv)
1087 bv.setGuiDelegate(this);
1091 void GuiView::disconnectBufferView()
1093 if (d.current_work_area_)
1094 d.current_work_area_->bufferView().setGuiDelegate(0);
1098 void GuiView::errors(string const & error_type, bool from_master)
1100 ErrorList & el = from_master ?
1101 documentBufferView()->buffer().masterBuffer()->errorList(error_type)
1102 : documentBufferView()->buffer().errorList(error_type);
1103 string data = error_type;
1105 data = "from_master|" + error_type;
1107 showDialog("errorlist", data);
1111 void GuiView::updateTocItem(std::string const & type, DocIterator const & dit)
1113 d.toc_models_.updateItem(toqstr(type), dit);
1117 void GuiView::structureChanged()
1119 d.toc_models_.reset(documentBufferView());
1120 // Navigator needs more than a simple update in this case. It needs to be
1122 updateDialog("toc", "");
1126 void GuiView::updateDialog(string const & name, string const & data)
1128 if (!isDialogVisible(name))
1131 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
1132 if (it == d.dialogs_.end())
1135 Dialog * const dialog = it->second.get();
1136 if (dialog->isVisibleView())
1137 dialog->initialiseParams(data);
1141 BufferView * GuiView::documentBufferView()
1143 return currentMainWorkArea()
1144 ? ¤tMainWorkArea()->bufferView()
1149 BufferView const * GuiView::documentBufferView() const
1151 return currentMainWorkArea()
1152 ? ¤tMainWorkArea()->bufferView()
1157 BufferView * GuiView::currentBufferView()
1159 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1163 BufferView const * GuiView::currentBufferView() const
1165 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1169 void GuiView::autoSave()
1171 LYXERR(Debug::INFO, "Running autoSave()");
1173 if (documentBufferView())
1174 documentBufferView()->buffer().autoSave();
1178 void GuiView::resetAutosaveTimers()
1181 d.autosave_timeout_.restart();
1185 bool GuiView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1188 Buffer * buf = currentBufferView()
1189 ? ¤tBufferView()->buffer() : 0;
1190 Buffer * doc_buffer = documentBufferView()
1191 ? &(documentBufferView()->buffer()) : 0;
1193 // Check whether we need a buffer
1194 if (!lyxaction.funcHasFlag(cmd.action, LyXAction::NoBuffer) && !buf) {
1195 // no, exit directly
1196 flag.message(from_utf8(N_("Command not allowed with"
1197 "out any document open")));
1198 flag.setEnabled(false);
1202 if (cmd.origin == FuncRequest::TOC) {
1203 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
1205 if (toc->getStatus(documentBufferView()->cursor(), cmd, fs))
1208 flag.setEnabled(false);
1212 switch(cmd.action) {
1213 case LFUN_BUFFER_IMPORT:
1216 case LFUN_BUFFER_RELOAD:
1217 enable = doc_buffer && !doc_buffer->isUnnamed()
1218 && doc_buffer->fileName().exists()
1219 && (!doc_buffer->isClean()
1220 || doc_buffer->isExternallyModified(Buffer::timestamp_method));
1223 case LFUN_BUFFER_CHILD_OPEN:
1224 enable = doc_buffer;
1227 case LFUN_BUFFER_WRITE:
1228 enable = doc_buffer && (doc_buffer->isUnnamed() || !doc_buffer->isClean());
1231 //FIXME: This LFUN should be moved to GuiApplication.
1232 case LFUN_BUFFER_WRITE_ALL: {
1233 // We enable the command only if there are some modified buffers
1234 Buffer * first = theBufferList().first();
1239 // We cannot use a for loop as the buffer list is a cycle.
1241 if (!b->isClean()) {
1245 b = theBufferList().next(b);
1246 } while (b != first);
1250 case LFUN_BUFFER_WRITE_AS:
1251 enable = doc_buffer;
1254 case LFUN_BUFFER_CLOSE:
1255 enable = doc_buffer;
1258 case LFUN_BUFFER_CLOSE_ALL:
1259 enable = theBufferList().last() != theBufferList().first();
1262 case LFUN_SPLIT_VIEW:
1263 if (cmd.getArg(0) == "vertical")
1264 enable = doc_buffer && (d.splitter_->count() == 1 ||
1265 d.splitter_->orientation() == Qt::Vertical);
1267 enable = doc_buffer && (d.splitter_->count() == 1 ||
1268 d.splitter_->orientation() == Qt::Horizontal);
1271 case LFUN_CLOSE_TAB_GROUP:
1272 enable = d.currentTabWorkArea();
1275 case LFUN_TOOLBAR_TOGGLE:
1276 if (GuiToolbar * t = toolbar(cmd.getArg(0)))
1277 flag.setOnOff(t->isVisible());
1280 case LFUN_DROP_LAYOUTS_CHOICE:
1284 case LFUN_UI_TOGGLE:
1285 flag.setOnOff(isFullScreen());
1288 case LFUN_DIALOG_DISCONNECT_INSET:
1291 case LFUN_DIALOG_HIDE:
1292 // FIXME: should we check if the dialog is shown?
1295 case LFUN_DIALOG_TOGGLE:
1296 flag.setOnOff(isDialogVisible(cmd.getArg(0)));
1297 // fall through to set "enable"
1298 case LFUN_DIALOG_SHOW: {
1299 string const name = cmd.getArg(0);
1301 enable = name == "aboutlyx"
1302 || name == "file" //FIXME: should be removed.
1304 || name == "texinfo";
1305 else if (name == "print")
1306 enable = doc_buffer->isExportable("dvi")
1307 && lyxrc.print_command != "none";
1308 else if (name == "character" || name == "symbols") {
1309 if (!buf || buf->isReadonly()
1310 || !currentBufferView()->cursor().inTexted())
1313 // FIXME we should consider passthru
1315 Inset const & in = currentBufferView()->cursor().inset();
1316 enable = !in.getLayout().isPassThru();
1319 else if (name == "latexlog")
1320 enable = FileName(doc_buffer->logName()).isReadableFile();
1321 else if (name == "spellchecker")
1322 enable = theSpellChecker() && !doc_buffer->isReadonly();
1323 else if (name == "vclog")
1324 enable = doc_buffer->lyxvc().inUse();
1328 case LFUN_DIALOG_UPDATE: {
1329 string const name = cmd.getArg(0);
1331 enable = name == "prefs";
1335 case LFUN_COMMAND_EXECUTE:
1337 case LFUN_MENU_OPEN:
1338 // Nothing to check.
1341 case LFUN_COMPLETION_INLINE:
1342 if (!d.current_work_area_
1343 || !d.current_work_area_->completer().inlinePossible(
1344 currentBufferView()->cursor()))
1348 case LFUN_COMPLETION_POPUP:
1349 if (!d.current_work_area_
1350 || !d.current_work_area_->completer().popupPossible(
1351 currentBufferView()->cursor()))
1355 case LFUN_COMPLETION_COMPLETE:
1356 if (!d.current_work_area_
1357 || !d.current_work_area_->completer().inlinePossible(
1358 currentBufferView()->cursor()))
1362 case LFUN_COMPLETION_ACCEPT:
1363 if (!d.current_work_area_
1364 || (!d.current_work_area_->completer().popupVisible()
1365 && !d.current_work_area_->completer().inlineVisible()
1366 && !d.current_work_area_->completer().completionAvailable()))
1370 case LFUN_COMPLETION_CANCEL:
1371 if (!d.current_work_area_
1372 || (!d.current_work_area_->completer().popupVisible()
1373 && !d.current_work_area_->completer().inlineVisible()))
1377 case LFUN_BUFFER_ZOOM_OUT:
1378 enable = doc_buffer && lyxrc.zoom > 10;
1381 case LFUN_BUFFER_ZOOM_IN:
1382 enable = doc_buffer;
1385 case LFUN_BUFFER_NEXT:
1386 case LFUN_BUFFER_PREVIOUS:
1387 // FIXME: should we check is there is an previous or next buffer?
1389 case LFUN_BUFFER_SWITCH:
1390 // toggle on the current buffer, but do not toggle off
1391 // the other ones (is that a good idea?)
1393 && to_utf8(cmd.argument()) == doc_buffer->absFileName())
1394 flag.setOnOff(true);
1397 case LFUN_VC_REGISTER:
1398 enable = doc_buffer && !doc_buffer->lyxvc().inUse();
1400 case LFUN_VC_CHECK_IN:
1401 enable = doc_buffer && doc_buffer->lyxvc().checkInEnabled();
1403 case LFUN_VC_CHECK_OUT:
1404 enable = doc_buffer && doc_buffer->lyxvc().checkOutEnabled();
1406 case LFUN_VC_LOCKING_TOGGLE:
1407 enable = doc_buffer && !doc_buffer->isReadonly()
1408 && doc_buffer->lyxvc().lockingToggleEnabled();
1409 flag.setOnOff(enable && !doc_buffer->lyxvc().locker().empty());
1411 case LFUN_VC_REVERT:
1412 enable = doc_buffer && doc_buffer->lyxvc().inUse();
1414 case LFUN_VC_UNDO_LAST:
1415 enable = doc_buffer && doc_buffer->lyxvc().undoLastEnabled();
1417 case LFUN_VC_REPO_SYNCHRO:
1418 enable = doc_buffer && doc_buffer->lyxvc().inUse();
1420 case LFUN_VC_COMMAND: {
1421 if (cmd.argument().empty())
1423 if (!doc_buffer && contains(cmd.getArg(0), 'D'))
1428 case LFUN_SERVER_GOTO_FILE_ROW:
1436 flag.setEnabled(false);
1442 static FileName selectTemplateFile()
1444 FileDialog dlg(qt_("Select template file"));
1445 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1446 dlg.setButton1(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
1448 FileDialog::Result result = dlg.open(toqstr(lyxrc.template_path),
1449 QStringList(qt_("LyX Documents (*.lyx)")));
1451 if (result.first == FileDialog::Later)
1453 if (result.second.isEmpty())
1455 return FileName(fromqstr(result.second));
1459 Buffer * GuiView::loadDocument(FileName const & filename, bool tolastfiles)
1463 Buffer * newBuffer = checkAndLoadLyXFile(filename);
1466 message(_("Document not loaded."));
1471 setBuffer(newBuffer);
1473 // scroll to the position when the file was last closed
1474 if (lyxrc.use_lastfilepos) {
1475 LastFilePosSection::FilePos filepos =
1476 theSession().lastFilePos().load(filename);
1477 documentBufferView()->moveToPosition(filepos.pit, filepos.pos, 0, 0);
1481 theSession().lastFiles().add(filename);
1488 void GuiView::openDocument(string const & fname)
1490 string initpath = lyxrc.document_path;
1492 if (documentBufferView()) {
1493 string const trypath = documentBufferView()->buffer().filePath();
1494 // If directory is writeable, use this as default.
1495 if (FileName(trypath).isDirWritable())
1501 if (fname.empty()) {
1502 FileDialog dlg(qt_("Select document to open"), LFUN_FILE_OPEN);
1503 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1504 dlg.setButton2(qt_("Examples|#E#e"),
1505 toqstr(addPath(package().system_support().absFilename(), "examples")));
1507 QStringList filter(qt_("LyX Documents (*.lyx)"));
1508 filter << qt_("LyX-1.3.x Documents (*.lyx13)")
1509 << qt_("LyX-1.4.x Documents (*.lyx14)")
1510 << qt_("LyX-1.5.x Documents (*.lyx15)")
1511 << qt_("LyX-1.6.x Documents (*.lyx16)");
1512 FileDialog::Result result =
1513 dlg.open(toqstr(initpath), filter);
1515 if (result.first == FileDialog::Later)
1518 filename = fromqstr(result.second);
1520 // check selected filename
1521 if (filename.empty()) {
1522 message(_("Canceled."));
1528 // get absolute path of file and add ".lyx" to the filename if
1530 FileName const fullname =
1531 fileSearch(string(), filename, "lyx", support::may_not_exist);
1532 if (!fullname.empty())
1533 filename = fullname.absFilename();
1535 if (!fullname.onlyPath().isDirectory()) {
1536 Alert::warning(_("Invalid filename"),
1537 bformat(_("The directory in the given path\n%1$s\ndoes not exist."),
1538 from_utf8(fullname.absFilename())));
1541 // if the file doesn't exist, let the user create one
1542 if (!fullname.exists()) {
1543 // the user specifically chose this name. Believe him.
1544 Buffer * const b = newFile(filename, string(), true);
1550 docstring const disp_fn = makeDisplayPath(filename);
1551 message(bformat(_("Opening document %1$s..."), disp_fn));
1554 Buffer * buf = loadDocument(fullname);
1556 buf->updateLabels();
1558 buf->errors("Parse");
1559 str2 = bformat(_("Document %1$s opened."), disp_fn);
1560 if (buf->lyxvc().inUse())
1561 str2 += " " + from_utf8(buf->lyxvc().versionString()) +
1562 " " + _("Version control detected.");
1564 str2 = bformat(_("Could not open document %1$s"), disp_fn);
1569 // FIXME: clean that
1570 static bool import(GuiView * lv, FileName const & filename,
1571 string const & format, ErrorList & errorList)
1573 FileName const lyxfile(support::changeExtension(filename.absFilename(), ".lyx"));
1575 string loader_format;
1576 vector<string> loaders = theConverters().loaders();
1577 if (find(loaders.begin(), loaders.end(), format) == loaders.end()) {
1578 for (vector<string>::const_iterator it = loaders.begin();
1579 it != loaders.end(); ++it) {
1580 if (!theConverters().isReachable(format, *it))
1583 string const tofile =
1584 support::changeExtension(filename.absFilename(),
1585 formats.extension(*it));
1586 if (!theConverters().convert(0, filename, FileName(tofile),
1587 filename, format, *it, errorList))
1589 loader_format = *it;
1592 if (loader_format.empty()) {
1593 frontend::Alert::error(_("Couldn't import file"),
1594 bformat(_("No information for importing the format %1$s."),
1595 formats.prettyName(format)));
1599 loader_format = format;
1601 if (loader_format == "lyx") {
1602 Buffer * buf = lv->loadDocument(lyxfile);
1605 buf->updateLabels();
1607 buf->errors("Parse");
1609 Buffer * const b = newFile(lyxfile.absFilename(), string(), true);
1613 bool as_paragraphs = loader_format == "textparagraph";
1614 string filename2 = (loader_format == format) ? filename.absFilename()
1615 : support::changeExtension(filename.absFilename(),
1616 formats.extension(loader_format));
1617 lv->currentBufferView()->insertPlaintextFile(FileName(filename2),
1619 guiApp->setCurrentView(lv);
1620 lyx::dispatch(FuncRequest(LFUN_MARK_OFF));
1627 void GuiView::importDocument(string const & argument)
1630 string filename = split(argument, format, ' ');
1632 LYXERR(Debug::INFO, format << " file: " << filename);
1634 // need user interaction
1635 if (filename.empty()) {
1636 string initpath = lyxrc.document_path;
1637 if (documentBufferView()) {
1638 string const trypath = documentBufferView()->buffer().filePath();
1639 // If directory is writeable, use this as default.
1640 if (FileName(trypath).isDirWritable())
1644 docstring const text = bformat(_("Select %1$s file to import"),
1645 formats.prettyName(format));
1647 FileDialog dlg(toqstr(text), LFUN_BUFFER_IMPORT);
1648 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1649 dlg.setButton2(qt_("Examples|#E#e"),
1650 toqstr(addPath(package().system_support().absFilename(), "examples")));
1652 docstring filter = formats.prettyName(format);
1655 filter += from_utf8(formats.extension(format));
1658 FileDialog::Result result =
1659 dlg.open(toqstr(initpath), fileFilters(toqstr(filter)));
1661 if (result.first == FileDialog::Later)
1664 filename = fromqstr(result.second);
1666 // check selected filename
1667 if (filename.empty())
1668 message(_("Canceled."));
1671 if (filename.empty())
1674 // get absolute path of file
1675 FileName const fullname(support::makeAbsPath(filename));
1677 FileName const lyxfile(support::changeExtension(fullname.absFilename(), ".lyx"));
1679 // Check if the document already is open
1680 Buffer * buf = theBufferList().getBuffer(lyxfile);
1683 if (!closeBuffer()) {
1684 message(_("Canceled."));
1689 docstring const displaypath = makeDisplayPath(lyxfile.absFilename(), 30);
1691 // if the file exists already, and we didn't do
1692 // -i lyx thefile.lyx, warn
1693 if (lyxfile.exists() && fullname != lyxfile) {
1695 docstring text = bformat(_("The document %1$s already exists.\n\n"
1696 "Do you want to overwrite that document?"), displaypath);
1697 int const ret = Alert::prompt(_("Overwrite document?"),
1698 text, 0, 1, _("&Overwrite"), _("&Cancel"));
1701 message(_("Canceled."));
1706 message(bformat(_("Importing %1$s..."), displaypath));
1707 ErrorList errorList;
1708 if (import(this, fullname, format, errorList))
1709 message(_("imported."));
1711 message(_("file not imported!"));
1713 // FIXME (Abdel 12/08/06): Is there a need to display the error list here?
1717 void GuiView::newDocument(string const & filename, bool from_template)
1719 FileName initpath(lyxrc.document_path);
1720 if (documentBufferView()) {
1721 FileName const trypath(documentBufferView()->buffer().filePath());
1722 // If directory is writeable, use this as default.
1723 if (trypath.isDirWritable())
1727 string templatefile;
1728 if (from_template) {
1729 templatefile = selectTemplateFile().absFilename();
1730 if (templatefile.empty())
1735 if (filename.empty())
1736 b = newUnnamedFile(templatefile, initpath);
1738 b = newFile(filename, templatefile, true);
1743 // If no new document could be created, it is unsure
1744 // whether there is a valid BufferView.
1745 if (currentBufferView())
1746 // Ensure the cursor is correctly positioned on screen.
1747 currentBufferView()->showCursor();
1751 void GuiView::insertLyXFile(docstring const & fname)
1753 BufferView * bv = documentBufferView();
1758 FileName filename(to_utf8(fname));
1760 if (!filename.empty()) {
1761 bv->insertLyXFile(filename);
1765 // Launch a file browser
1767 string initpath = lyxrc.document_path;
1768 string const trypath = bv->buffer().filePath();
1769 // If directory is writeable, use this as default.
1770 if (FileName(trypath).isDirWritable())
1774 FileDialog dlg(qt_("Select LyX document to insert"), LFUN_FILE_INSERT);
1775 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1776 dlg.setButton2(qt_("Examples|#E#e"),
1777 toqstr(addPath(package().system_support().absFilename(),
1780 FileDialog::Result result = dlg.open(toqstr(initpath),
1781 QStringList(qt_("LyX Documents (*.lyx)")));
1783 if (result.first == FileDialog::Later)
1787 filename.set(fromqstr(result.second));
1789 // check selected filename
1790 if (filename.empty()) {
1791 // emit message signal.
1792 message(_("Canceled."));
1796 bv->insertLyXFile(filename);
1800 void GuiView::insertPlaintextFile(docstring const & fname,
1803 BufferView * bv = documentBufferView();
1807 if (!fname.empty() && !FileName::isAbsolute(to_utf8(fname))) {
1808 message(_("Absolute filename expected."));
1813 FileName filename(to_utf8(fname));
1815 if (!filename.empty()) {
1816 bv->insertPlaintextFile(filename, asParagraph);
1820 FileDialog dlg(qt_("Select file to insert"), (asParagraph ?
1821 LFUN_FILE_INSERT_PLAINTEXT_PARA : LFUN_FILE_INSERT_PLAINTEXT));
1823 FileDialog::Result result = dlg.open(toqstr(bv->buffer().filePath()),
1824 QStringList(qt_("All Files (*)")));
1826 if (result.first == FileDialog::Later)
1830 filename.set(fromqstr(result.second));
1832 // check selected filename
1833 if (filename.empty()) {
1834 // emit message signal.
1835 message(_("Canceled."));
1839 bv->insertPlaintextFile(filename, asParagraph);
1843 bool GuiView::renameBuffer(Buffer & b, docstring const & newname)
1845 FileName fname = b.fileName();
1846 FileName const oldname = fname;
1848 if (!newname.empty()) {
1850 fname = support::makeAbsPath(to_utf8(newname), oldname.onlyPath().absFilename());
1852 // Switch to this Buffer.
1855 // No argument? Ask user through dialog.
1857 FileDialog dlg(qt_("Choose a filename to save document as"),
1858 LFUN_BUFFER_WRITE_AS);
1859 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1860 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
1862 if (!isLyXFilename(fname.absFilename()))
1863 fname.changeExtension(".lyx");
1865 FileDialog::Result result =
1866 dlg.save(toqstr(fname.onlyPath().absFilename()),
1867 QStringList(qt_("LyX Documents (*.lyx)")),
1868 toqstr(fname.onlyFileName()));
1870 if (result.first == FileDialog::Later)
1873 fname.set(fromqstr(result.second));
1878 if (!isLyXFilename(fname.absFilename()))
1879 fname.changeExtension(".lyx");
1882 if (FileName(fname).exists()) {
1883 docstring const file = makeDisplayPath(fname.absFilename(), 30);
1884 docstring text = bformat(_("The document %1$s already "
1885 "exists.\n\nDo you want to "
1886 "overwrite that document?"),
1888 int const ret = Alert::prompt(_("Overwrite document?"),
1889 text, 0, 2, _("&Overwrite"), _("&Rename"), _("&Cancel"));
1892 case 1: return renameBuffer(b, docstring());
1893 case 2: return false;
1897 FileName oldauto = b.getAutosaveFilename();
1899 // Ok, change the name of the buffer
1900 b.setFileName(fname.absFilename());
1902 bool unnamed = b.isUnnamed();
1903 b.setUnnamed(false);
1904 b.saveCheckSum(fname);
1906 // bring the autosave file with us, just in case.
1907 b.moveAutosaveFile(oldauto);
1909 if (!saveBuffer(b)) {
1910 oldauto = b.getAutosaveFilename();
1911 b.setFileName(oldname.absFilename());
1912 b.setUnnamed(unnamed);
1913 b.saveCheckSum(oldname);
1914 b.moveAutosaveFile(oldauto);
1922 bool GuiView::saveBuffer(Buffer & b)
1924 if (workArea(b) && workArea(b)->inDialogMode())
1928 return renameBuffer(b, docstring());
1931 theSession().lastFiles().add(b.fileName());
1935 // Switch to this Buffer.
1938 // FIXME: we don't tell the user *WHY* the save failed !!
1939 docstring const file = makeDisplayPath(b.absFileName(), 30);
1940 docstring text = bformat(_("The document %1$s could not be saved.\n\n"
1941 "Do you want to rename the document and "
1942 "try again?"), file);
1943 int const ret = Alert::prompt(_("Rename and save?"),
1944 text, 0, 2, _("&Rename"), _("&Retry"), _("&Cancel"));
1947 if (!renameBuffer(b, docstring()))
1956 return saveBuffer(b);
1960 bool GuiView::hideWorkArea(GuiWorkArea * wa)
1962 return closeWorkArea(wa, false);
1966 bool GuiView::closeWorkArea(GuiWorkArea * wa)
1968 Buffer & buf = wa->bufferView().buffer();
1969 return closeWorkArea(wa, !buf.parent());
1973 bool GuiView::closeBuffer()
1975 GuiWorkArea * wa = currentMainWorkArea();
1976 Buffer & buf = wa->bufferView().buffer();
1977 return wa && closeWorkArea(wa, !buf.parent());
1981 void GuiView::writeSession() const {
1982 GuiWorkArea const * active_wa = currentMainWorkArea();
1983 for (int i = 0; i < d.splitter_->count(); ++i) {
1984 TabWorkArea * twa = d.tabWorkArea(i);
1985 for (int j = 0; j < twa->count(); ++j) {
1986 GuiWorkArea * wa = static_cast<GuiWorkArea *>(twa->widget(j));
1987 Buffer & buf = wa->bufferView().buffer();
1988 theSession().lastOpened().add(buf.fileName(), wa == active_wa);
1994 bool GuiView::closeBufferAll()
1996 // Close the workareas in all other views
1997 QList<int> const ids = guiApp->viewIds();
1998 for (int i = 0; i != ids.size(); ++i) {
1999 if (id_ != ids[i] && !guiApp->view(ids[i]).closeWorkAreaAll())
2003 // Close our own workareas
2004 if (!closeWorkAreaAll())
2007 // Now close the hidden buffers. We prevent hidden buffers from being
2008 // dirty, so we can just close them.
2009 theBufferList().closeAll();
2014 bool GuiView::closeWorkAreaAll()
2016 setCurrentWorkArea(currentMainWorkArea());
2018 // We might be in a situation that there is still a tabWorkArea, but
2019 // there are no tabs anymore. This can happen when we get here after a
2020 // TabWorkArea::lastWorkAreaRemoved() signal. Therefore we count how
2021 // many TabWorkArea's have no documents anymore.
2024 // We have to call count() each time, because it can happen that
2025 // more than one splitter will disappear in one iteration (bug 5998).
2026 for (; d.splitter_->count() > empty_twa; ) {
2027 TabWorkArea * twa = d.tabWorkArea(empty_twa);
2029 if (twa->count() == 0)
2032 setCurrentWorkArea(twa->currentWorkArea());
2033 if (!closeTabWorkArea(twa))
2041 bool GuiView::closeWorkArea(GuiWorkArea * wa, bool close_buffer)
2043 Buffer & buf = wa->bufferView().buffer();
2045 // If we are in a close_event all children will be closed in some time,
2046 // so no need to do it here. This will ensure that the children end up
2047 // in the session file in the correct order. If we close the master
2048 // buffer, we can close or release the child buffers here too.
2049 if (close_buffer && !closing_) {
2050 vector<Buffer *> clist = buf.getChildren();
2051 for (vector<Buffer *>::const_iterator it = clist.begin();
2052 it != clist.end(); ++it) {
2053 // If a child is dirty, do not close
2054 // without user intervention
2055 //FIXME: should we look in other tabworkareas?
2056 Buffer * child_buf = *it;
2057 GuiWorkArea * child_wa = workArea(*child_buf);
2059 if (!closeWorkArea(child_wa, true))
2062 theBufferList().releaseChild(&buf, child_buf);
2065 // goto bookmark to update bookmark pit.
2066 //FIXME: we should update only the bookmarks related to this buffer!
2067 LYXERR(Debug::DEBUG, "GuiView::closeBuffer()");
2068 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
2069 theLyXFunc().gotoBookmark(i+1, false, false);
2071 // if we are only hiding the buffer and there are multiple views
2072 // of the buffer, then we do not need to ensure a clean buffer.
2073 bool const allow_dirty = inMultiTabs(wa) && !close_buffer;
2075 if (allow_dirty || saveBufferIfNeeded(buf, !close_buffer)) {
2076 // save in sessions if requested
2077 // do not save childs if their master
2078 // is opened as well
2082 theBufferList().release(&buf);
2089 bool GuiView::closeTabWorkArea(TabWorkArea * twa)
2091 while (twa == d.currentTabWorkArea()) {
2092 twa->setCurrentIndex(twa->count()-1);
2094 GuiWorkArea * wa = twa->currentWorkArea();
2095 Buffer & b = wa->bufferView().buffer();
2097 // We only want to close the buffer if the same buffer is not visible
2098 // in another view, and if this is not a child and if we are closing
2099 // a view (not a tabgroup).
2100 bool const close_buffer =
2101 !inMultiViews(wa) && !b.parent() && closing_;
2103 if (!closeWorkArea(wa, close_buffer))
2110 bool GuiView::saveBufferIfNeeded(Buffer & buf, bool hiding)
2112 if (buf.isClean() || buf.paragraphs().empty())
2115 // Switch to this Buffer.
2120 if (buf.isUnnamed())
2121 file = from_utf8(buf.fileName().onlyFileName());
2123 file = buf.fileName().displayName(30);
2125 // Bring this window to top before asking questions.
2130 if (hiding && buf.isUnnamed()) {
2131 docstring const text = bformat(_("The document %1$s has not been "
2132 "saved yet.\n\nDo you want to save "
2133 "the document?"), file);
2134 ret = Alert::prompt(_("Save new document?"),
2135 text, 0, 1, _("&Save"), _("&Cancel"));
2139 docstring const text = bformat(_("The document %1$s has unsaved changes."
2140 "\n\nDo you want to save the document or discard the changes?"), file);
2141 ret = Alert::prompt(_("Save changed document?"),
2142 text, 0, 2, _("&Save"), _("&Discard"), _("&Cancel"));
2147 if (!saveBuffer(buf))
2151 // if we crash after this we could
2152 // have no autosave file but I guess
2153 // this is really improbable (Jug)
2154 buf.removeAutosaveFile();
2156 // revert all changes
2157 buf.loadLyXFile(buf.fileName());
2167 bool GuiView::inMultiTabs(GuiWorkArea * wa)
2169 Buffer & buf = wa->bufferView().buffer();
2171 for (int i = 0; i != d.splitter_->count(); ++i) {
2172 GuiWorkArea * wa_ = d.tabWorkArea(i)->workArea(buf);
2173 if (wa_ && wa_ != wa)
2176 return inMultiViews(wa);
2180 bool GuiView::inMultiViews(GuiWorkArea * wa)
2182 QList<int> const ids = guiApp->viewIds();
2183 Buffer & buf = wa->bufferView().buffer();
2186 for (int i = 0; i != ids.size() && found_twa <= 1; ++i) {
2190 if (guiApp->view(ids[i]).workArea(buf))
2197 void GuiView::gotoNextOrPreviousBuffer(NextOrPrevious np)
2199 Buffer * const curbuf = documentBufferView()
2200 ? &documentBufferView()->buffer() : 0;
2201 Buffer * nextbuf = curbuf;
2203 if (np == NEXTBUFFER)
2204 nextbuf = theBufferList().next(nextbuf);
2206 nextbuf = theBufferList().previous(nextbuf);
2207 if (nextbuf == curbuf)
2213 if (workArea(*nextbuf))
2220 /// make sure the document is saved
2221 static bool ensureBufferClean(Buffer * buffer)
2223 LASSERT(buffer, return false);
2224 if (buffer->isClean() && !buffer->isUnnamed())
2227 docstring const file = buffer->fileName().displayName(30);
2230 if (!buffer->isUnnamed()) {
2231 text = bformat(_("The document %1$s has unsaved "
2232 "changes.\n\nDo you want to save "
2233 "the document?"), file);
2234 title = _("Save changed document?");
2237 text = bformat(_("The document %1$s has not been "
2238 "saved yet.\n\nDo you want to save "
2239 "the document?"), file);
2240 title = _("Save new document?");
2242 int const ret = Alert::prompt(title, text, 0, 1, _("&Save"), _("&Cancel"));
2245 dispatch(FuncRequest(LFUN_BUFFER_WRITE));
2247 return buffer->isClean() && !buffer->isUnnamed();
2251 void GuiView::reloadBuffer()
2253 Buffer * buf = &documentBufferView()->buffer();
2254 FileName filename = buf->fileName();
2255 Buffer const * master = buf->masterBuffer();
2256 bool const is_child = master != buf;
2257 // The user has already confirmed that the changes, if any, should
2258 // be discarded. So we just release the Buffer and don't call closeBuffer();
2259 theBufferList().release(buf);
2260 buf = loadDocument(filename);
2261 docstring const disp_fn = makeDisplayPath(filename.absFilename());
2264 // re-allocate master if necessary
2265 if (is_child && theBufferList().isLoaded(master)
2266 && buf->masterBuffer() != master)
2267 buf->setParent(master);
2268 buf->updateLabels();
2270 buf->errors("Parse");
2271 str = bformat(_("Document %1$s reloaded."), disp_fn);
2273 str = bformat(_("Could not reload document %1$s"), disp_fn);
2279 void GuiView::dispatchVC(FuncRequest const & cmd)
2281 Buffer * buffer = documentBufferView()
2282 ? &(documentBufferView()->buffer()) : 0;
2284 switch (cmd.action) {
2285 case LFUN_VC_REGISTER:
2286 if (!buffer || !ensureBufferClean(buffer))
2288 if (!buffer->lyxvc().inUse()) {
2289 if (buffer->lyxvc().registrer())
2294 case LFUN_VC_CHECK_IN:
2295 if (!buffer || !ensureBufferClean(buffer))
2297 if (buffer->lyxvc().inUse() && !buffer->isReadonly()) {
2298 message(from_utf8(buffer->lyxvc().checkIn()));
2303 case LFUN_VC_CHECK_OUT:
2304 if (!buffer || !ensureBufferClean(buffer))
2306 if (buffer->lyxvc().inUse()) {
2307 message(from_utf8(buffer->lyxvc().checkOut()));
2312 case LFUN_VC_LOCKING_TOGGLE:
2313 LASSERT(buffer, return);
2314 if (!ensureBufferClean(buffer) || buffer->isReadonly())
2316 if (buffer->lyxvc().inUse()) {
2317 string res = buffer->lyxvc().lockingToggle();
2319 frontend::Alert::error(_("Revision control error."),
2320 _("Error when setting the locking property."));
2322 message(from_utf8(res));
2328 case LFUN_VC_REVERT:
2329 LASSERT(buffer, return);
2330 buffer->lyxvc().revert();
2334 case LFUN_VC_UNDO_LAST:
2335 LASSERT(buffer, return);
2336 buffer->lyxvc().undoLast();
2340 case LFUN_VC_REPO_SYNCHRO:
2341 LASSERT(buffer, return);
2342 if (ensureBufferClean(buffer)) {
2343 string res = buffer->lyxvc().repoSynchro();
2344 message(from_utf8(res));
2349 case LFUN_VC_COMMAND: {
2350 string flag = cmd.getArg(0);
2351 if (buffer && contains(flag, 'R') && !ensureBufferClean(buffer))
2354 if (contains(flag, 'M')) {
2355 if (!Alert::askForText(message, _("LyX VC: Log Message")))
2358 string path = cmd.getArg(1);
2359 if (contains(path, "$$p") && buffer)
2360 path = subst(path, "$$p", buffer->filePath());
2361 LYXERR(Debug::LYXVC, "Directory: " << path);
2363 if (!pp.isReadableDirectory()) {
2364 lyxerr << _("Directory is not accessible.") << endl;
2367 support::PathChanger p(pp);
2369 string command = cmd.getArg(2);
2370 if (command.empty())
2373 command = subst(command, "$$i", buffer->absFileName());
2374 command = subst(command, "$$p", buffer->filePath());
2376 command = subst(command, "$$m", to_utf8(message));
2377 LYXERR(Debug::LYXVC, "Command: " << command);
2379 one.startscript(Systemcall::Wait, command);
2383 if (contains(flag, 'I'))
2384 buffer->markDirty();
2385 if (contains(flag, 'R'))
2396 void GuiView::openChildDocument(string const & fname)
2398 LASSERT(documentBufferView(), return);
2399 Buffer & buffer = documentBufferView()->buffer();
2400 FileName const filename = support::makeAbsPath(fname, buffer.filePath());
2401 documentBufferView()->saveBookmark(false);
2403 bool parsed = false;
2404 if (theBufferList().exists(filename)) {
2405 child = theBufferList().getBuffer(filename);
2407 message(bformat(_("Opening child document %1$s..."),
2408 makeDisplayPath(filename.absFilename())));
2409 child = loadDocument(filename, false);
2415 // Set the parent name of the child document.
2416 // This makes insertion of citations and references in the child work,
2417 // when the target is in the parent or another child document.
2418 child->setParent(&buffer);
2419 child->masterBuffer()->updateLabels();
2422 child->errors("Parse");
2426 bool GuiView::goToFileRow(string const & argument)
2430 istringstream is(argument);
2431 is >> file_name >> row;
2432 file_name = os::internal_path(file_name);
2434 string const abstmp = package().temp_dir().absFilename();
2435 string const realtmp = package().temp_dir().realPath();
2436 // We have to use os::path_prefix_is() here, instead of
2437 // simply prefixIs(), because the file name comes from
2438 // an external application and may need case adjustment.
2439 if (os::path_prefix_is(file_name, abstmp, os::CASE_ADJUSTED)
2440 || os::path_prefix_is(file_name, realtmp, os::CASE_ADJUSTED)) {
2441 // Needed by inverse dvi search. If it is a file
2442 // in tmpdir, call the apropriated function.
2443 // If tmpdir is a symlink, we may have the real
2444 // path passed back, so we correct for that.
2445 if (!prefixIs(file_name, abstmp))
2446 file_name = subst(file_name, realtmp, abstmp);
2447 buf = theBufferList().getBufferFromTmp(file_name);
2449 // Must replace extension of the file to be .lyx
2450 // and get full path
2451 FileName const s = fileSearch(string(),
2452 support::changeExtension(file_name, ".lyx"), "lyx");
2453 // Either change buffer or load the file
2454 if (theBufferList().exists(s))
2455 buf = theBufferList().getBuffer(s);
2456 else if (s.exists()) {
2457 buf = loadDocument(s);
2458 buf->updateLabels();
2459 buf->errors("Parse");
2462 _("File does not exist: %1$s"),
2463 makeDisplayPath(file_name)));
2468 documentBufferView()->setCursorFromRow(row);
2473 bool GuiView::dispatch(FuncRequest const & cmd)
2475 BufferView * bv = currentBufferView();
2476 // By default we won't need any update.
2478 bv->cursor().updateFlags(Update::None);
2480 Buffer * doc_buffer = documentBufferView()
2481 ? &(documentBufferView()->buffer()) : 0;
2483 bool dispatched = true;
2485 if (cmd.origin == FuncRequest::TOC) {
2486 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
2487 toc->doDispatch(bv->cursor(), cmd);
2491 switch(cmd.action) {
2492 case LFUN_BUFFER_CHILD_OPEN:
2493 openChildDocument(to_utf8(cmd.argument()));
2496 case LFUN_BUFFER_IMPORT:
2497 importDocument(to_utf8(cmd.argument()));
2500 case LFUN_BUFFER_SWITCH:
2501 if (FileName::isAbsolute(to_utf8(cmd.argument()))) {
2503 theBufferList().getBuffer(FileName(to_utf8(cmd.argument())));
2507 message(_("Document not loaded"));
2511 case LFUN_BUFFER_NEXT:
2512 gotoNextOrPreviousBuffer(NEXTBUFFER);
2515 case LFUN_BUFFER_PREVIOUS:
2516 gotoNextOrPreviousBuffer(PREVBUFFER);
2519 case LFUN_COMMAND_EXECUTE: {
2520 bool const show_it = cmd.argument() != "off";
2521 // FIXME: this is a hack, "minibuffer" should not be
2523 if (GuiToolbar * t = toolbar("minibuffer")) {
2524 t->setVisible(show_it);
2525 if (show_it && t->commandBuffer())
2526 t->commandBuffer()->setFocus();
2530 case LFUN_DROP_LAYOUTS_CHOICE:
2531 d.layout_->showPopup();
2534 case LFUN_MENU_OPEN:
2535 if (QMenu * menu = guiApp->menus().menu(toqstr(cmd.argument()), *this))
2536 menu->exec(QCursor::pos());
2539 case LFUN_FILE_INSERT:
2540 insertLyXFile(cmd.argument());
2542 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
2543 insertPlaintextFile(cmd.argument(), true);
2546 case LFUN_FILE_INSERT_PLAINTEXT:
2547 insertPlaintextFile(cmd.argument(), false);
2550 case LFUN_BUFFER_RELOAD: {
2551 LASSERT(doc_buffer, break);
2552 docstring const file = makeDisplayPath(doc_buffer->absFileName(), 20);
2553 docstring text = bformat(_("Any changes will be lost. Are you sure "
2554 "you want to revert to the saved version of the document %1$s?"), file);
2555 int const ret = Alert::prompt(_("Revert to saved document?"),
2556 text, 1, 1, _("&Revert"), _("&Cancel"));
2563 case LFUN_BUFFER_WRITE:
2564 LASSERT(doc_buffer, break);
2565 saveBuffer(*doc_buffer);
2568 case LFUN_BUFFER_WRITE_AS:
2569 LASSERT(doc_buffer, break);
2570 renameBuffer(*doc_buffer, cmd.argument());
2573 case LFUN_BUFFER_WRITE_ALL: {
2574 Buffer * first = theBufferList().first();
2577 message(_("Saving all documents..."));
2578 // We cannot use a for loop as the buffer list cycles.
2581 if (!b->isClean()) {
2583 LYXERR(Debug::ACTION, "Saved " << b->absFileName());
2585 b = theBufferList().next(b);
2586 } while (b != first);
2587 message(_("All documents saved."));
2591 case LFUN_BUFFER_CLOSE:
2595 case LFUN_BUFFER_CLOSE_ALL:
2599 case LFUN_TOOLBAR_TOGGLE: {
2600 string const name = cmd.getArg(0);
2601 if (GuiToolbar * t = toolbar(name))
2606 case LFUN_DIALOG_UPDATE: {
2607 string const name = to_utf8(cmd.argument());
2608 if (currentBufferView()) {
2609 Inset * inset = currentBufferView()->editedInset(name);
2610 // Can only update a dialog connected to an existing inset
2613 // FIXME: get rid of this indirection; GuiView ask the inset
2614 // if he is kind enough to update itself...
2615 FuncRequest fr(LFUN_INSET_DIALOG_UPDATE, cmd.argument());
2616 inset->dispatch(currentBufferView()->cursor(), fr);
2617 } else if (name == "paragraph") {
2618 lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
2619 } else if (name == "prefs" || name == "document") {
2620 updateDialog(name, string());
2625 case LFUN_DIALOG_TOGGLE: {
2626 if (isDialogVisible(cmd.getArg(0)))
2627 dispatch(FuncRequest(LFUN_DIALOG_HIDE, cmd.argument()));
2629 dispatch(FuncRequest(LFUN_DIALOG_SHOW, cmd.argument()));
2633 case LFUN_DIALOG_DISCONNECT_INSET:
2634 disconnectDialog(to_utf8(cmd.argument()));
2637 case LFUN_DIALOG_HIDE: {
2638 guiApp->hideDialogs(to_utf8(cmd.argument()), 0);
2642 case LFUN_DIALOG_SHOW: {
2643 string const name = cmd.getArg(0);
2644 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
2646 if (name == "character") {
2647 data = freefont2string();
2649 showDialog("character", data);
2650 } else if (name == "latexlog") {
2651 Buffer::LogType type;
2652 string const logfile = doc_buffer->logName(&type);
2654 case Buffer::latexlog:
2657 case Buffer::buildlog:
2661 data += Lexer::quoteString(logfile);
2662 showDialog("log", data);
2663 } else if (name == "vclog") {
2664 string const data = "vc " +
2665 Lexer::quoteString(doc_buffer->lyxvc().getLogFile());
2666 showDialog("log", data);
2667 } else if (name == "symbols") {
2668 data = bv->cursor().getEncoding()->name();
2670 showDialog("symbols", data);
2672 } else if (name == "prefs" && isFullScreen()) {
2673 FuncRequest fr(LFUN_INSET_INSERT, "fullscreen");
2675 showDialog("prefs", data);
2677 showDialog(name, data);
2682 message(cmd.argument());
2685 case LFUN_UI_TOGGLE:
2687 // Make sure the keyboard focus stays in the work area.
2691 case LFUN_SPLIT_VIEW: {
2692 LASSERT(doc_buffer, break);
2693 string const orientation = cmd.getArg(0);
2694 d.splitter_->setOrientation(orientation == "vertical"
2695 ? Qt::Vertical : Qt::Horizontal);
2696 TabWorkArea * twa = addTabWorkArea();
2697 GuiWorkArea * wa = twa->addWorkArea(*doc_buffer, *this);
2698 setCurrentWorkArea(wa);
2701 case LFUN_CLOSE_TAB_GROUP:
2702 if (TabWorkArea * twa = d.currentTabWorkArea()) {
2703 closeTabWorkArea(twa);
2704 d.current_work_area_ = 0;
2705 twa = d.currentTabWorkArea();
2706 // Switch to the next GuiWorkArea in the found TabWorkArea.
2708 // Make sure the work area is up to date.
2709 setCurrentWorkArea(twa->currentWorkArea());
2711 setCurrentWorkArea(0);
2716 case LFUN_COMPLETION_INLINE:
2717 if (d.current_work_area_)
2718 d.current_work_area_->completer().showInline();
2721 case LFUN_COMPLETION_POPUP:
2722 if (d.current_work_area_)
2723 d.current_work_area_->completer().showPopup();
2727 case LFUN_COMPLETION_COMPLETE:
2728 if (d.current_work_area_)
2729 d.current_work_area_->completer().tab();
2732 case LFUN_COMPLETION_CANCEL:
2733 if (d.current_work_area_) {
2734 if (d.current_work_area_->completer().popupVisible())
2735 d.current_work_area_->completer().hidePopup();
2737 d.current_work_area_->completer().hideInline();
2741 case LFUN_COMPLETION_ACCEPT:
2742 if (d.current_work_area_)
2743 d.current_work_area_->completer().activate();
2746 case LFUN_BUFFER_ZOOM_IN:
2747 case LFUN_BUFFER_ZOOM_OUT:
2748 if (cmd.argument().empty()) {
2749 if (cmd.action == LFUN_BUFFER_ZOOM_IN)
2754 lyxrc.zoom += convert<int>(cmd.argument());
2756 if (lyxrc.zoom < 10)
2759 // The global QPixmapCache is used in GuiPainter to cache text
2760 // painting so we must reset it.
2761 QPixmapCache::clear();
2762 guiApp->fontLoader().update();
2763 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
2766 case LFUN_VC_REGISTER:
2767 case LFUN_VC_CHECK_IN:
2768 case LFUN_VC_CHECK_OUT:
2769 case LFUN_VC_REPO_SYNCHRO:
2770 case LFUN_VC_LOCKING_TOGGLE:
2771 case LFUN_VC_REVERT:
2772 case LFUN_VC_UNDO_LAST:
2773 case LFUN_VC_COMMAND:
2777 case LFUN_SERVER_GOTO_FILE_ROW:
2778 goToFileRow(to_utf8(cmd.argument()));
2786 // Part of automatic menu appearance feature.
2787 if (isFullScreen()) {
2788 if (menuBar()->isVisible() && lyxrc.full_screen_menubar)
2790 if (statusBar()->isVisible())
2791 statusBar()->hide();
2798 void GuiView::lfunUiToggle(FuncRequest const & cmd)
2800 string const arg = cmd.getArg(0);
2801 if (arg == "scrollbar") {
2802 // hide() is of no help
2803 if (d.current_work_area_->verticalScrollBarPolicy() ==
2804 Qt::ScrollBarAlwaysOff)
2806 d.current_work_area_->setVerticalScrollBarPolicy(
2807 Qt::ScrollBarAsNeeded);
2809 d.current_work_area_->setVerticalScrollBarPolicy(
2810 Qt::ScrollBarAlwaysOff);
2813 if (arg == "statusbar") {
2814 statusBar()->setVisible(!statusBar()->isVisible());
2817 if (arg == "menubar") {
2818 menuBar()->setVisible(!menuBar()->isVisible());
2821 #if QT_VERSION >= 0x040300
2822 if (arg == "frame") {
2824 getContentsMargins(&l, &t, &r, &b);
2825 //are the frames in default state?
2826 d.current_work_area_->setFrameStyle(QFrame::NoFrame);
2828 setContentsMargins(-2, -2, -2, -2);
2830 setContentsMargins(0, 0, 0, 0);
2835 if (arg == "fullscreen") {
2840 message(bformat("LFUN_UI_TOGGLE " + _("%1$s unknown command!"), from_utf8(arg)));
2844 void GuiView::toggleFullScreen()
2846 if (isFullScreen()) {
2847 for (int i = 0; i != d.splitter_->count(); ++i)
2848 d.tabWorkArea(i)->setFullScreen(false);
2849 #if QT_VERSION >= 0x040300
2850 setContentsMargins(0, 0, 0, 0);
2852 setWindowState(windowState() ^ Qt::WindowFullScreen);
2855 statusBar()->show();
2858 hideDialogs("prefs", 0);
2859 for (int i = 0; i != d.splitter_->count(); ++i)
2860 d.tabWorkArea(i)->setFullScreen(true);
2861 #if QT_VERSION >= 0x040300
2862 setContentsMargins(-2, -2, -2, -2);
2865 setWindowState(windowState() ^ Qt::WindowFullScreen);
2866 statusBar()->hide();
2867 if (lyxrc.full_screen_menubar)
2869 if (lyxrc.full_screen_toolbars) {
2870 ToolbarMap::iterator end = d.toolbars_.end();
2871 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
2876 // give dialogs like the TOC a chance to adapt
2881 Buffer const * GuiView::updateInset(Inset const * inset)
2883 if (!d.current_work_area_)
2887 d.current_work_area_->scheduleRedraw();
2889 return &d.current_work_area_->bufferView().buffer();
2893 void GuiView::restartCursor()
2895 /* When we move around, or type, it's nice to be able to see
2896 * the cursor immediately after the keypress.
2898 if (d.current_work_area_)
2899 d.current_work_area_->startBlinkingCursor();
2901 // Take this occasion to update the other GUI elements.
2907 void GuiView::updateCompletion(Cursor & cur, bool start, bool keep)
2909 if (d.current_work_area_)
2910 d.current_work_area_->completer().updateVisibility(cur, start, keep);
2915 // This list should be kept in sync with the list of insets in
2916 // src/insets/Inset.cpp. I.e., if a dialog goes with an inset, the
2917 // dialog should have the same name as the inset.
2918 // Changes should be also recorded in LFUN_DIALOG_SHOW doxygen
2919 // docs in LyXAction.cpp.
2921 char const * const dialognames[] = {
2922 "aboutlyx", "bibitem", "bibtex", "box", "branch", "changes", "character",
2923 "citation", "document", "errorlist", "ert", "external", "file", "findreplace",
2924 "findreplaceadv", "float", "graphics", "href", "include", "index",
2925 "index_print", "info", "listings", "label", "log", "mathdelimiter",
2926 "mathmatrix", "mathspace", "nomenclature", "nomencl_print", "note",
2927 "paragraph", "phantom", "prefs", "print", "ref", "sendto", "space",
2928 "spellchecker", "symbols", "tabular", "tabularcreate", "thesaurus", "texinfo",
2929 "toc", "view-source", "vspace", "wrap" };
2931 char const * const * const end_dialognames =
2932 dialognames + (sizeof(dialognames) / sizeof(char *));
2936 cmpCStr(char const * name) : name_(name) {}
2937 bool operator()(char const * other) {
2938 return strcmp(other, name_) == 0;
2945 bool isValidName(string const & name)
2947 return find_if(dialognames, end_dialognames,
2948 cmpCStr(name.c_str())) != end_dialognames;
2954 void GuiView::resetDialogs()
2956 // Make sure that no LFUN uses any LyXView.
2957 guiApp->setCurrentView(0);
2960 constructToolbars();
2961 guiApp->menus().fillMenuBar(menuBar(), this, false);
2962 d.layout_->updateContents(true);
2963 // Now update controls with current buffer.
2964 guiApp->setCurrentView(this);
2970 Dialog * GuiView::findOrBuild(string const & name, bool hide_it)
2972 if (!isValidName(name))
2975 map<string, DialogPtr>::iterator it = d.dialogs_.find(name);
2977 if (it != d.dialogs_.end()) {
2979 it->second->hideView();
2980 return it->second.get();
2983 Dialog * dialog = build(name);
2984 d.dialogs_[name].reset(dialog);
2985 if (lyxrc.allow_geometry_session)
2986 dialog->restoreSession();
2993 void GuiView::showDialog(string const & name, string const & data,
3001 Dialog * dialog = findOrBuild(name, false);
3003 dialog->showData(data);
3004 if (inset && currentBufferView())
3005 currentBufferView()->editInset(name, inset);
3008 catch (ExceptionMessage const & ex) {
3016 bool GuiView::isDialogVisible(string const & name) const
3018 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3019 if (it == d.dialogs_.end())
3021 return it->second.get()->isVisibleView() && !it->second.get()->isClosing();
3025 void GuiView::hideDialog(string const & name, Inset * inset)
3027 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3028 if (it == d.dialogs_.end())
3031 if (inset && currentBufferView()
3032 && inset != currentBufferView()->editedInset(name))
3035 Dialog * const dialog = it->second.get();
3036 if (dialog->isVisibleView())
3038 if (currentBufferView())
3039 currentBufferView()->editInset(name, 0);
3043 void GuiView::disconnectDialog(string const & name)
3045 if (!isValidName(name))
3047 if (currentBufferView())
3048 currentBufferView()->editInset(name, 0);
3052 void GuiView::hideAll() const
3054 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
3055 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3057 for(; it != end; ++it)
3058 it->second->hideView();
3062 void GuiView::updateDialogs()
3064 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
3065 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3067 for(; it != end; ++it) {
3068 Dialog * dialog = it->second.get();
3069 if (dialog && dialog->isVisibleView())
3070 dialog->checkStatus();
3077 // will be replaced by a proper factory...
3078 Dialog * createGuiAbout(GuiView & lv);
3079 Dialog * createGuiBibitem(GuiView & lv);
3080 Dialog * createGuiBibtex(GuiView & lv);
3081 Dialog * createGuiBox(GuiView & lv);
3082 Dialog * createGuiBranch(GuiView & lv);
3083 Dialog * createGuiChanges(GuiView & lv);
3084 Dialog * createGuiCharacter(GuiView & lv);
3085 Dialog * createGuiCitation(GuiView & lv);
3086 Dialog * createGuiDelimiter(GuiView & lv);
3087 Dialog * createGuiDocument(GuiView & lv);
3088 Dialog * createGuiErrorList(GuiView & lv);
3089 Dialog * createGuiERT(GuiView & lv);
3090 Dialog * createGuiExternal(GuiView & lv);
3091 Dialog * createGuiFloat(GuiView & lv);
3092 Dialog * createGuiGraphics(GuiView & lv);
3093 Dialog * createGuiInclude(GuiView & lv);
3094 Dialog * createGuiIndex(GuiView & lv);
3095 Dialog * createGuiInfo(GuiView & lv);
3096 Dialog * createGuiLabel(GuiView & lv);
3097 Dialog * createGuiListings(GuiView & lv);
3098 Dialog * createGuiLog(GuiView & lv);
3099 Dialog * createGuiMathHSpace(GuiView & lv);
3100 Dialog * createGuiMathMatrix(GuiView & lv);
3101 Dialog * createGuiNomenclature(GuiView & lv);
3102 Dialog * createGuiNote(GuiView & lv);
3103 Dialog * createGuiParagraph(GuiView & lv);
3104 Dialog * createGuiPhantom(GuiView & lv);
3105 Dialog * createGuiPreferences(GuiView & lv);
3106 Dialog * createGuiPrint(GuiView & lv);
3107 Dialog * createGuiPrintindex(GuiView & lv);
3108 Dialog * createGuiPrintNomencl(GuiView & lv);
3109 Dialog * createGuiRef(GuiView & lv);
3110 Dialog * createGuiSearch(GuiView & lv);
3111 Dialog * createGuiSearchAdv(GuiView & lv);
3112 Dialog * createGuiSendTo(GuiView & lv);
3113 Dialog * createGuiShowFile(GuiView & lv);
3114 Dialog * createGuiSpellchecker(GuiView & lv);
3115 Dialog * createGuiSymbols(GuiView & lv);
3116 Dialog * createGuiTabularCreate(GuiView & lv);
3117 Dialog * createGuiTabular(GuiView & lv);
3118 Dialog * createGuiTexInfo(GuiView & lv);
3119 Dialog * createGuiTextHSpace(GuiView & lv);
3120 Dialog * createGuiToc(GuiView & lv);
3121 Dialog * createGuiThesaurus(GuiView & lv);
3122 Dialog * createGuiHyperlink(GuiView & lv);
3123 Dialog * createGuiVSpace(GuiView & lv);
3124 Dialog * createGuiViewSource(GuiView & lv);
3125 Dialog * createGuiWrap(GuiView & lv);
3128 Dialog * GuiView::build(string const & name)
3130 LASSERT(isValidName(name), return 0);
3132 if (name == "aboutlyx")
3133 return createGuiAbout(*this);
3134 if (name == "bibitem")
3135 return createGuiBibitem(*this);
3136 if (name == "bibtex")
3137 return createGuiBibtex(*this);
3139 return createGuiBox(*this);
3140 if (name == "branch")
3141 return createGuiBranch(*this);
3142 if (name == "changes")
3143 return createGuiChanges(*this);
3144 if (name == "character")
3145 return createGuiCharacter(*this);
3146 if (name == "citation")
3147 return createGuiCitation(*this);
3148 if (name == "document")
3149 return createGuiDocument(*this);
3150 if (name == "errorlist")
3151 return createGuiErrorList(*this);
3153 return createGuiERT(*this);
3154 if (name == "external")
3155 return createGuiExternal(*this);
3157 return createGuiShowFile(*this);
3158 if (name == "findreplace")
3159 return createGuiSearch(*this);
3160 if (name == "findreplaceadv")
3161 return createGuiSearchAdv(*this);
3162 if (name == "float")
3163 return createGuiFloat(*this);
3164 if (name == "graphics")
3165 return createGuiGraphics(*this);
3167 return createGuiHyperlink(*this);
3168 if (name == "include")
3169 return createGuiInclude(*this);
3170 if (name == "index")
3171 return createGuiIndex(*this);
3172 if (name == "index_print")
3173 return createGuiPrintindex(*this);
3175 return createGuiInfo(*this);
3176 if (name == "label")
3177 return createGuiLabel(*this);
3178 if (name == "listings")
3179 return createGuiListings(*this);
3181 return createGuiLog(*this);
3182 if (name == "mathdelimiter")
3183 return createGuiDelimiter(*this);
3184 if (name == "mathspace")
3185 return createGuiMathHSpace(*this);
3186 if (name == "mathmatrix")
3187 return createGuiMathMatrix(*this);
3188 if (name == "nomenclature")
3189 return createGuiNomenclature(*this);
3190 if (name == "nomencl_print")
3191 return createGuiPrintNomencl(*this);
3193 return createGuiNote(*this);
3194 if (name == "paragraph")
3195 return createGuiParagraph(*this);
3196 if (name == "phantom")
3197 return createGuiPhantom(*this);
3198 if (name == "prefs")
3199 return createGuiPreferences(*this);
3200 if (name == "print")
3201 return createGuiPrint(*this);
3203 return createGuiRef(*this);
3204 if (name == "sendto")
3205 return createGuiSendTo(*this);
3206 if (name == "space")
3207 return createGuiTextHSpace(*this);
3208 if (name == "spellchecker")
3209 return createGuiSpellchecker(*this);
3210 if (name == "symbols")
3211 return createGuiSymbols(*this);
3212 if (name == "tabular")
3213 return createGuiTabular(*this);
3214 if (name == "tabularcreate")
3215 return createGuiTabularCreate(*this);
3216 if (name == "texinfo")
3217 return createGuiTexInfo(*this);
3218 if (name == "thesaurus")
3219 return createGuiThesaurus(*this);
3221 return createGuiToc(*this);
3222 if (name == "view-source")
3223 return createGuiViewSource(*this);
3224 if (name == "vspace")
3225 return createGuiVSpace(*this);
3227 return createGuiWrap(*this);
3233 } // namespace frontend
3236 #include "moc_GuiView.cpp"