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"
56 #include "Paragraph.h"
57 #include "SpellChecker.h"
58 #include "TextClass.h"
63 #include "support/convert.h"
64 #include "support/debug.h"
65 #include "support/ExceptionMessage.h"
66 #include "support/FileName.h"
67 #include "support/filetools.h"
68 #include "support/gettext.h"
69 #include "support/filetools.h"
70 #include "support/ForkedCalls.h"
71 #include "support/lassert.h"
72 #include "support/lstrings.h"
73 #include "support/os.h"
74 #include "support/Package.h"
75 #include "support/Path.h"
76 #include "support/Systemcall.h"
77 #include "support/Timeout.h"
80 #include <QApplication>
81 #include <QCloseEvent>
83 #include <QDesktopWidget>
84 #include <QDragEnterEvent>
91 #include <QPixmapCache>
93 #include <QPushButton>
97 #include <QStackedWidget>
102 #include <QScrollBar>
104 #include <boost/bind.hpp>
106 #ifdef HAVE_SYS_TIME_H
107 # include <sys/time.h>
114 using namespace lyx::support;
121 class BackgroundWidget : public QWidget
126 LYXERR(Debug::GUI, "show banner: " << lyxrc.show_banner);
127 /// The text to be written on top of the pixmap
128 QString const text = lyx_version ?
129 qt_("version ") + lyx_version : qt_("unknown version");
130 splash_ = getPixmap("images/", "banner", "png");
132 QPainter pain(&splash_);
133 pain.setPen(QColor(0, 0, 0));
135 // The font used to display the version info
136 font.setStyleHint(QFont::SansSerif);
137 font.setWeight(QFont::Bold);
138 font.setPointSize(int(toqstr(lyxrc.font_sizes[FONT_SIZE_LARGE]).toDouble()));
140 pain.drawText(260, 15, text);
143 void paintEvent(QPaintEvent *)
145 int x = (width() - splash_.width()) / 2;
146 int y = (height() - splash_.height()) / 2;
148 pain.drawPixmap(x, y, splash_);
156 /// Toolbar store providing access to individual toolbars by name.
157 typedef std::map<std::string, GuiToolbar *> ToolbarMap;
159 typedef boost::shared_ptr<Dialog> DialogPtr;
164 struct GuiView::GuiViewPrivate
167 : current_work_area_(0), current_main_work_area_(0),
168 layout_(0), autosave_timeout_(5000),
171 // hardcode here the platform specific icon size
172 smallIconSize = 14; // scaling problems
173 normalIconSize = 20; // ok, default
174 bigIconSize = 26; // better for some math icons
176 splitter_ = new QSplitter;
177 bg_widget_ = new BackgroundWidget;
178 stack_widget_ = new QStackedWidget;
179 stack_widget_->addWidget(bg_widget_);
180 stack_widget_->addWidget(splitter_);
188 delete stack_widget_;
191 QMenu * toolBarPopup(GuiView * parent)
193 // FIXME: translation
194 QMenu * menu = new QMenu(parent);
195 QActionGroup * iconSizeGroup = new QActionGroup(parent);
197 QAction * smallIcons = new QAction(iconSizeGroup);
198 smallIcons->setText(qt_("Small-sized icons"));
199 smallIcons->setCheckable(true);
200 QObject::connect(smallIcons, SIGNAL(triggered()),
201 parent, SLOT(smallSizedIcons()));
202 menu->addAction(smallIcons);
204 QAction * normalIcons = new QAction(iconSizeGroup);
205 normalIcons->setText(qt_("Normal-sized icons"));
206 normalIcons->setCheckable(true);
207 QObject::connect(normalIcons, SIGNAL(triggered()),
208 parent, SLOT(normalSizedIcons()));
209 menu->addAction(normalIcons);
211 QAction * bigIcons = new QAction(iconSizeGroup);
212 bigIcons->setText(qt_("Big-sized icons"));
213 bigIcons->setCheckable(true);
214 QObject::connect(bigIcons, SIGNAL(triggered()),
215 parent, SLOT(bigSizedIcons()));
216 menu->addAction(bigIcons);
218 unsigned int cur = parent->iconSize().width();
219 if ( cur == parent->d.smallIconSize)
220 smallIcons->setChecked(true);
221 else if (cur == parent->d.normalIconSize)
222 normalIcons->setChecked(true);
223 else if (cur == parent->d.bigIconSize)
224 bigIcons->setChecked(true);
231 stack_widget_->setCurrentWidget(bg_widget_);
232 bg_widget_->setUpdatesEnabled(true);
235 TabWorkArea * tabWorkArea(int i)
237 return dynamic_cast<TabWorkArea *>(splitter_->widget(i));
240 TabWorkArea * currentTabWorkArea()
242 if (splitter_->count() == 1)
243 // The first TabWorkArea is always the first one, if any.
244 return tabWorkArea(0);
246 for (int i = 0; i != splitter_->count(); ++i) {
247 TabWorkArea * twa = tabWorkArea(i);
248 if (current_main_work_area_ == twa->currentWorkArea())
252 // None has the focus so we just take the first one.
253 return tabWorkArea(0);
257 GuiWorkArea * current_work_area_;
258 GuiWorkArea * current_main_work_area_;
259 QSplitter * splitter_;
260 QStackedWidget * stack_widget_;
261 BackgroundWidget * bg_widget_;
263 ToolbarMap toolbars_;
264 /// The main layout box.
266 * \warning Don't Delete! The layout box is actually owned by
267 * whichever toolbar contains it. All the GuiView class needs is a
268 * means of accessing it.
270 * FIXME: replace that with a proper model so that we are not limited
271 * to only one dialog.
276 map<string, Inset *> open_insets_;
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()
655 statusBar()->showMessage(toqstr(theLyXFunc().viewStatusMessage()));
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())
732 statusBar()->showMessage(toqstr(theLyXFunc().viewStatusMessage()));
736 bool GuiView::hasFocus() const
738 return qApp->activeWindow() == this;
742 bool GuiView::event(QEvent * e)
746 // Useful debug code:
747 //case QEvent::ActivationChange:
748 //case QEvent::WindowDeactivate:
749 //case QEvent::Paint:
750 //case QEvent::Enter:
751 //case QEvent::Leave:
752 //case QEvent::HoverEnter:
753 //case QEvent::HoverLeave:
754 //case QEvent::HoverMove:
755 //case QEvent::StatusTip:
756 //case QEvent::DragEnter:
757 //case QEvent::DragLeave:
761 case QEvent::WindowActivate: {
762 GuiView * old_view = guiApp->currentView();
763 if (this == old_view) {
765 return QMainWindow::event(e);
767 if (old_view && old_view->currentBufferView()) {
768 // save current selection to the selection buffer to allow
769 // middle-button paste in this window.
770 cap::saveSelection(old_view->currentBufferView()->cursor());
772 guiApp->setCurrentView(this);
773 if (d.current_work_area_) {
774 BufferView & bv = d.current_work_area_->bufferView();
775 connectBufferView(bv);
776 connectBuffer(bv.buffer());
777 // The document structure, name and dialogs might have
778 // changed in another view.
780 // The document settings needs to be reinitialised.
781 updateDialog("document", "");
784 resetWindowTitleAndIconText();
787 return QMainWindow::event(e);
790 case QEvent::ShortcutOverride: {
793 #if (!defined Q_WS_X11) || (QT_VERSION >= 0x040500)
794 if (isFullScreen() && menuBar()->isHidden()) {
795 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
796 // FIXME: we should also try to detect special LyX shortcut such as
797 // Alt-P and Alt-M. Right now there is a hack in
798 // GuiWorkArea::processKeySym() that hides again the menubar for
800 if (ke->modifiers() & Qt::AltModifier && ke->key() != Qt::Key_Alt) {
802 return QMainWindow::event(e);
807 if (d.current_work_area_)
808 // Nothing special to do.
809 return QMainWindow::event(e);
811 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
812 // Let Qt handle menu access and the Tab keys to navigate keys to navigate
814 if (ke->modifiers() & Qt::AltModifier || ke->key() == Qt::Key_Tab
815 || ke->key() == Qt::Key_Backtab)
816 return QMainWindow::event(e);
818 // Allow processing of shortcuts that are allowed even when no Buffer
821 setKeySymbol(&sym, ke);
822 theLyXFunc().processKeySym(sym, q_key_state(ke->modifiers()));
828 return QMainWindow::event(e);
832 void GuiView::resetWindowTitleAndIconText()
834 setWindowTitle(qt_("LyX"));
835 setWindowIconText(qt_("LyX"));
838 bool GuiView::focusNextPrevChild(bool /*next*/)
845 void GuiView::setBusy(bool busy)
847 if (d.current_work_area_) {
848 d.current_work_area_->setUpdatesEnabled(!busy);
850 d.current_work_area_->stopBlinkingCursor();
852 d.current_work_area_->startBlinkingCursor();
856 QApplication::setOverrideCursor(Qt::WaitCursor);
858 QApplication::restoreOverrideCursor();
862 GuiWorkArea * GuiView::workArea(Buffer & buffer)
864 if (currentWorkArea()
865 && ¤tWorkArea()->bufferView().buffer() == &buffer)
866 return (GuiWorkArea *) currentWorkArea();
867 if (TabWorkArea * twa = d.currentTabWorkArea())
868 return twa->workArea(buffer);
873 GuiWorkArea * GuiView::addWorkArea(Buffer & buffer)
875 // Automatically create a TabWorkArea if there are none yet.
876 TabWorkArea * tab_widget = d.splitter_->count()
877 ? d.currentTabWorkArea() : addTabWorkArea();
878 return tab_widget->addWorkArea(buffer, *this);
882 TabWorkArea * GuiView::addTabWorkArea()
884 TabWorkArea * twa = new TabWorkArea;
885 QObject::connect(twa, SIGNAL(currentWorkAreaChanged(GuiWorkArea *)),
886 this, SLOT(on_currentWorkAreaChanged(GuiWorkArea *)));
887 QObject::connect(twa, SIGNAL(lastWorkAreaRemoved()),
888 this, SLOT(on_lastWorkAreaRemoved()));
890 d.splitter_->addWidget(twa);
891 d.stack_widget_->setCurrentWidget(d.splitter_);
896 GuiWorkArea const * GuiView::currentWorkArea() const
898 return d.current_work_area_;
902 GuiWorkArea * GuiView::currentWorkArea()
904 return d.current_work_area_;
908 GuiWorkArea const * GuiView::currentMainWorkArea() const
910 if (d.currentTabWorkArea() == NULL)
912 return d.currentTabWorkArea()->currentWorkArea();
916 GuiWorkArea * GuiView::currentMainWorkArea()
918 if (d.currentTabWorkArea() == NULL)
920 return d.currentTabWorkArea()->currentWorkArea();
924 void GuiView::setCurrentWorkArea(GuiWorkArea * wa)
926 LYXERR(Debug::DEBUG, "Setting current wa: " << wa << endl);
928 d.current_work_area_ = NULL;
932 GuiWorkArea * old_gwa = theGuiApp()->currentView()->currentWorkArea();
936 if (currentBufferView())
937 cap::saveSelection(currentBufferView()->cursor());
939 theGuiApp()->setCurrentView(this);
940 d.current_work_area_ = wa;
941 for (int i = 0; i != d.splitter_->count(); ++i) {
942 if (d.tabWorkArea(i)->setCurrentWorkArea(wa)) {
943 //if (d.current_main_work_area_)
944 // d.current_main_work_area_->setFrameStyle(QFrame::NoFrame);
945 d.current_main_work_area_ = wa;
946 //d.current_main_work_area_->setFrameStyle(QFrame::Box | QFrame::Plain);
947 //d.current_main_work_area_->setLineWidth(2);
948 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() << ", Current main wa: " << currentMainWorkArea());
952 LYXERR(Debug::DEBUG, "This is not a tabbed wa");
953 on_currentWorkAreaChanged(wa);
954 BufferView & bv = wa->bufferView();
955 bv.cursor().fixIfBroken();
957 wa->setUpdatesEnabled(true);
958 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() << ", Current main wa: " << currentMainWorkArea());
962 void GuiView::removeWorkArea(GuiWorkArea * wa)
965 if (wa == d.current_work_area_) {
967 disconnectBufferView();
968 d.current_work_area_ = 0;
969 d.current_main_work_area_ = 0;
972 bool found_twa = false;
973 for (int i = 0; i != d.splitter_->count(); ++i) {
974 TabWorkArea * twa = d.tabWorkArea(i);
975 if (twa->removeWorkArea(wa)) {
976 // Found in this tab group, and deleted the GuiWorkArea.
978 if (twa->count() != 0) {
979 if (d.current_work_area_ == 0)
980 // This means that we are closing the current GuiWorkArea, so
981 // switch to the next GuiWorkArea in the found TabWorkArea.
982 setCurrentWorkArea(twa->currentWorkArea());
984 // No more WorkAreas in this tab group, so delete it.
991 // It is not a tabbed work area (i.e., the search work area), so it
992 // should be deleted by other means.
993 LASSERT(found_twa, /* */);
995 if (d.current_work_area_ == 0) {
996 if (d.splitter_->count() != 0) {
997 TabWorkArea * twa = d.currentTabWorkArea();
998 setCurrentWorkArea(twa->currentWorkArea());
1000 // No more work areas, switch to the background widget.
1001 setCurrentWorkArea(0);
1007 LayoutBox * GuiView::getLayoutDialog() const
1013 void GuiView::updateLayoutList()
1016 d.layout_->updateContents(false);
1020 void GuiView::updateToolbars()
1022 ToolbarMap::iterator end = d.toolbars_.end();
1023 if (d.current_work_area_) {
1025 d.current_work_area_->bufferView().cursor().inMathed();
1027 lyx::getStatus(FuncRequest(LFUN_LAYOUT_TABULAR)).enabled();
1029 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).enabled() &&
1030 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).onoff(true);
1031 bool const mathmacrotemplate =
1032 lyx::getStatus(FuncRequest(LFUN_IN_MATHMACROTEMPLATE)).enabled();
1034 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1035 it->second->update(math, table, review, mathmacrotemplate);
1037 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1038 it->second->update(false, false, false, false);
1042 void GuiView::setBuffer(Buffer * newBuffer)
1044 LYXERR(Debug::DEBUG, "Setting buffer: " << newBuffer << std::endl);
1045 LASSERT(newBuffer, return);
1048 GuiWorkArea * wa = workArea(*newBuffer);
1050 newBuffer->masterBuffer()->updateLabels();
1051 wa = addWorkArea(*newBuffer);
1053 //Disconnect the old buffer...there's no new one.
1056 connectBuffer(*newBuffer);
1057 connectBufferView(wa->bufferView());
1058 setCurrentWorkArea(wa);
1064 void GuiView::connectBuffer(Buffer & buf)
1066 buf.setGuiDelegate(this);
1070 void GuiView::disconnectBuffer()
1072 if (d.current_work_area_)
1073 d.current_work_area_->bufferView().buffer().setGuiDelegate(0);
1077 void GuiView::connectBufferView(BufferView & bv)
1079 bv.setGuiDelegate(this);
1083 void GuiView::disconnectBufferView()
1085 if (d.current_work_area_)
1086 d.current_work_area_->bufferView().setGuiDelegate(0);
1090 void GuiView::errors(string const & error_type, bool from_master)
1092 ErrorList & el = from_master ?
1093 documentBufferView()->buffer().masterBuffer()->errorList(error_type)
1094 : documentBufferView()->buffer().errorList(error_type);
1095 string data = error_type;
1097 data = "from_master|" + error_type;
1099 showDialog("errorlist", data);
1103 void GuiView::updateTocItem(std::string const & type, DocIterator const & dit)
1105 d.toc_models_.updateItem(toqstr(type), dit);
1109 void GuiView::structureChanged()
1111 d.toc_models_.reset(documentBufferView());
1112 // Navigator needs more than a simple update in this case. It needs to be
1114 updateDialog("toc", "");
1118 void GuiView::updateDialog(string const & name, string const & data)
1120 if (!isDialogVisible(name))
1123 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
1124 if (it == d.dialogs_.end())
1127 Dialog * const dialog = it->second.get();
1128 if (dialog->isVisibleView())
1129 dialog->initialiseParams(data);
1133 BufferView * GuiView::documentBufferView()
1135 return currentMainWorkArea()
1136 ? ¤tMainWorkArea()->bufferView()
1141 BufferView const * GuiView::documentBufferView() const
1143 return currentMainWorkArea()
1144 ? ¤tMainWorkArea()->bufferView()
1149 BufferView * GuiView::currentBufferView()
1151 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1155 BufferView const * GuiView::currentBufferView() const
1157 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1161 void GuiView::autoSave()
1163 LYXERR(Debug::INFO, "Running autoSave()");
1165 if (documentBufferView())
1166 documentBufferView()->buffer().autoSave();
1170 void GuiView::resetAutosaveTimers()
1173 d.autosave_timeout_.restart();
1177 bool GuiView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1180 Buffer * buf = currentBufferView()
1181 ? ¤tBufferView()->buffer() : 0;
1182 Buffer * doc_buffer = documentBufferView()
1183 ? &(documentBufferView()->buffer()) : 0;
1185 if (cmd.origin == FuncRequest::TOC) {
1186 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
1188 if (toc->getStatus(documentBufferView()->cursor(), cmd, fs))
1191 flag.setEnabled(false);
1195 switch(cmd.action) {
1196 case LFUN_BUFFER_IMPORT:
1199 case LFUN_BUFFER_RELOAD:
1200 enable = doc_buffer && !doc_buffer->isUnnamed()
1201 && doc_buffer->fileName().exists()
1202 && (!doc_buffer->isClean()
1203 || doc_buffer->isExternallyModified(Buffer::timestamp_method));
1206 case LFUN_BUFFER_CHILD_OPEN:
1207 enable = doc_buffer;
1210 case LFUN_BUFFER_WRITE:
1211 enable = doc_buffer && (doc_buffer->isUnnamed() || !doc_buffer->isClean());
1214 //FIXME: This LFUN should be moved to GuiApplication.
1215 case LFUN_BUFFER_WRITE_ALL: {
1216 // We enable the command only if there are some modified buffers
1217 Buffer * first = theBufferList().first();
1222 // We cannot use a for loop as the buffer list is a cycle.
1224 if (!b->isClean()) {
1228 b = theBufferList().next(b);
1229 } while (b != first);
1233 case LFUN_BUFFER_WRITE_AS:
1234 enable = doc_buffer;
1237 case LFUN_BUFFER_CLOSE:
1238 enable = doc_buffer;
1241 case LFUN_BUFFER_CLOSE_ALL:
1242 enable = theBufferList().last() != theBufferList().first();
1245 case LFUN_SPLIT_VIEW:
1246 if (cmd.getArg(0) == "vertical")
1247 enable = doc_buffer && (d.splitter_->count() == 1 ||
1248 d.splitter_->orientation() == Qt::Vertical);
1250 enable = doc_buffer && (d.splitter_->count() == 1 ||
1251 d.splitter_->orientation() == Qt::Horizontal);
1254 case LFUN_CLOSE_TAB_GROUP:
1255 enable = d.currentTabWorkArea();
1258 case LFUN_TOOLBAR_TOGGLE:
1259 if (GuiToolbar * t = toolbar(cmd.getArg(0)))
1260 flag.setOnOff(t->isVisible());
1263 case LFUN_UI_TOGGLE:
1264 flag.setOnOff(isFullScreen());
1267 case LFUN_DIALOG_DISCONNECT_INSET:
1270 case LFUN_DIALOG_HIDE:
1271 // FIXME: should we check if the dialog is shown?
1274 case LFUN_DIALOG_TOGGLE:
1275 flag.setOnOff(isDialogVisible(cmd.getArg(0)));
1276 // fall through to set "enable"
1277 case LFUN_DIALOG_SHOW: {
1278 string const name = cmd.getArg(0);
1280 enable = name == "aboutlyx"
1281 || name == "file" //FIXME: should be removed.
1283 || name == "texinfo";
1284 else if (name == "print")
1285 enable = doc_buffer->isExportable("dvi")
1286 && lyxrc.print_command != "none";
1287 else if (name == "character" || name == "symbols") {
1288 if (!buf || buf->isReadonly()
1289 || !currentBufferView()->cursor().inTexted())
1292 // FIXME we should consider passthru
1294 Inset const & in = currentBufferView()->cursor().inset();
1295 enable = !in.getLayout().isPassThru();
1298 else if (name == "latexlog")
1299 enable = FileName(doc_buffer->logName()).isReadableFile();
1300 else if (name == "spellchecker")
1301 enable = theSpellChecker() && !doc_buffer->isReadonly();
1302 else if (name == "vclog")
1303 enable = doc_buffer->lyxvc().inUse();
1307 case LFUN_DIALOG_UPDATE: {
1308 string const name = cmd.getArg(0);
1310 enable = name == "prefs";
1314 case LFUN_COMMAND_EXECUTE:
1316 case LFUN_MENU_OPEN:
1317 // Nothing to check.
1320 case LFUN_INSET_APPLY: {
1321 string const name = cmd.getArg(0);
1322 Inset * inset = getOpenInset(name);
1324 FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument());
1326 if (!inset->getStatus(currentBufferView()->cursor(), fr, fs)) {
1327 // Every inset is supposed to handle this
1328 LASSERT(false, break);
1332 FuncRequest fr(LFUN_INSET_INSERT, cmd.argument());
1333 flag |= lyx::getStatus(fr);
1335 enable = flag.enabled();
1339 case LFUN_COMPLETION_INLINE:
1340 if (!d.current_work_area_
1341 || !d.current_work_area_->completer().inlinePossible(
1342 currentBufferView()->cursor()))
1346 case LFUN_COMPLETION_POPUP:
1347 if (!d.current_work_area_
1348 || !d.current_work_area_->completer().popupPossible(
1349 currentBufferView()->cursor()))
1353 case LFUN_COMPLETION_COMPLETE:
1354 if (!d.current_work_area_
1355 || !d.current_work_area_->completer().inlinePossible(
1356 currentBufferView()->cursor()))
1360 case LFUN_COMPLETION_ACCEPT:
1361 if (!d.current_work_area_
1362 || (!d.current_work_area_->completer().popupVisible()
1363 && !d.current_work_area_->completer().inlineVisible()
1364 && !d.current_work_area_->completer().completionAvailable()))
1368 case LFUN_COMPLETION_CANCEL:
1369 if (!d.current_work_area_
1370 || (!d.current_work_area_->completer().popupVisible()
1371 && !d.current_work_area_->completer().inlineVisible()))
1375 case LFUN_BUFFER_ZOOM_OUT:
1376 enable = doc_buffer && lyxrc.zoom > 10;
1379 case LFUN_BUFFER_ZOOM_IN:
1380 enable = doc_buffer;
1383 case LFUN_BUFFER_NEXT:
1384 case LFUN_BUFFER_PREVIOUS:
1385 // FIXME: should we check is there is an previous or next buffer?
1387 case LFUN_BUFFER_SWITCH:
1388 // toggle on the current buffer, but do not toggle off
1389 // the other ones (is that a good idea?)
1391 && to_utf8(cmd.argument()) == doc_buffer->absFileName())
1392 flag.setOnOff(true);
1395 case LFUN_VC_REGISTER:
1396 enable = doc_buffer && !doc_buffer->lyxvc().inUse();
1398 case LFUN_VC_CHECK_IN:
1399 enable = doc_buffer && doc_buffer->lyxvc().checkInEnabled();
1401 case LFUN_VC_CHECK_OUT:
1402 enable = doc_buffer && doc_buffer->lyxvc().checkOutEnabled();
1404 case LFUN_VC_LOCKING_TOGGLE:
1405 enable = doc_buffer && !doc_buffer->isReadonly()
1406 && doc_buffer->lyxvc().lockingToggleEnabled();
1407 flag.setOnOff(enable && !doc_buffer->lyxvc().locker().empty());
1409 case LFUN_VC_REVERT:
1410 enable = doc_buffer && doc_buffer->lyxvc().inUse();
1412 case LFUN_VC_UNDO_LAST:
1413 enable = doc_buffer && doc_buffer->lyxvc().undoLastEnabled();
1415 case LFUN_VC_COMMAND: {
1416 if (cmd.argument().empty())
1418 if (!doc_buffer && contains(cmd.getArg(0), 'D'))
1428 flag.setEnabled(false);
1434 static FileName selectTemplateFile()
1436 FileDialog dlg(qt_("Select template file"));
1437 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1438 dlg.setButton1(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
1440 FileDialog::Result result = dlg.open(toqstr(lyxrc.template_path),
1441 QStringList(qt_("LyX Documents (*.lyx)")));
1443 if (result.first == FileDialog::Later)
1445 if (result.second.isEmpty())
1447 return FileName(fromqstr(result.second));
1451 Buffer * GuiView::loadDocument(FileName const & filename, bool tolastfiles)
1455 Buffer * newBuffer = checkAndLoadLyXFile(filename);
1458 message(_("Document not loaded."));
1463 setBuffer(newBuffer);
1465 // scroll to the position when the file was last closed
1466 if (lyxrc.use_lastfilepos) {
1467 LastFilePosSection::FilePos filepos =
1468 theSession().lastFilePos().load(filename);
1469 documentBufferView()->moveToPosition(filepos.pit, filepos.pos, 0, 0);
1473 theSession().lastFiles().add(filename);
1480 void GuiView::openDocument(string const & fname)
1482 string initpath = lyxrc.document_path;
1484 if (documentBufferView()) {
1485 string const trypath = documentBufferView()->buffer().filePath();
1486 // If directory is writeable, use this as default.
1487 if (FileName(trypath).isDirWritable())
1493 if (fname.empty()) {
1494 FileDialog dlg(qt_("Select document to open"), LFUN_FILE_OPEN);
1495 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1496 dlg.setButton2(qt_("Examples|#E#e"),
1497 toqstr(addPath(package().system_support().absFilename(), "examples")));
1499 QStringList filter(qt_("LyX Documents (*.lyx)"));
1500 filter << qt_("LyX-1.3.x Documents (*.lyx13)")
1501 << qt_("LyX-1.4.x Documents (*.lyx14)")
1502 << qt_("LyX-1.5.x Documents (*.lyx15)")
1503 << qt_("LyX-1.6.x Documents (*.lyx16)");
1504 FileDialog::Result result =
1505 dlg.open(toqstr(initpath), filter);
1507 if (result.first == FileDialog::Later)
1510 filename = fromqstr(result.second);
1512 // check selected filename
1513 if (filename.empty()) {
1514 message(_("Canceled."));
1520 // get absolute path of file and add ".lyx" to the filename if
1522 FileName const fullname =
1523 fileSearch(string(), filename, "lyx", support::may_not_exist);
1524 if (!fullname.empty())
1525 filename = fullname.absFilename();
1527 if (!fullname.onlyPath().isDirectory()) {
1528 Alert::warning(_("Invalid filename"),
1529 bformat(_("The directory in the given path\n%1$s\ndoes not exist."),
1530 from_utf8(fullname.absFilename())));
1533 // if the file doesn't exist, let the user create one
1534 if (!fullname.exists()) {
1535 // the user specifically chose this name. Believe him.
1536 Buffer * const b = newFile(filename, string(), true);
1542 docstring const disp_fn = makeDisplayPath(filename);
1543 message(bformat(_("Opening document %1$s..."), disp_fn));
1546 Buffer * buf = loadDocument(fullname);
1548 buf->updateLabels();
1550 buf->errors("Parse");
1551 str2 = bformat(_("Document %1$s opened."), disp_fn);
1552 if (buf->lyxvc().inUse())
1553 str2 += " " + from_utf8(buf->lyxvc().versionString()) +
1554 " " + _("Version control detected.");
1556 str2 = bformat(_("Could not open document %1$s"), disp_fn);
1561 // FIXME: clean that
1562 static bool import(GuiView * lv, FileName const & filename,
1563 string const & format, ErrorList & errorList)
1565 FileName const lyxfile(support::changeExtension(filename.absFilename(), ".lyx"));
1567 string loader_format;
1568 vector<string> loaders = theConverters().loaders();
1569 if (find(loaders.begin(), loaders.end(), format) == loaders.end()) {
1570 for (vector<string>::const_iterator it = loaders.begin();
1571 it != loaders.end(); ++it) {
1572 if (!theConverters().isReachable(format, *it))
1575 string const tofile =
1576 support::changeExtension(filename.absFilename(),
1577 formats.extension(*it));
1578 if (!theConverters().convert(0, filename, FileName(tofile),
1579 filename, format, *it, errorList))
1581 loader_format = *it;
1584 if (loader_format.empty()) {
1585 frontend::Alert::error(_("Couldn't import file"),
1586 bformat(_("No information for importing the format %1$s."),
1587 formats.prettyName(format)));
1591 loader_format = format;
1593 if (loader_format == "lyx") {
1594 Buffer * buf = lv->loadDocument(lyxfile);
1597 buf->updateLabels();
1599 buf->errors("Parse");
1601 Buffer * const b = newFile(lyxfile.absFilename(), string(), true);
1605 bool as_paragraphs = loader_format == "textparagraph";
1606 string filename2 = (loader_format == format) ? filename.absFilename()
1607 : support::changeExtension(filename.absFilename(),
1608 formats.extension(loader_format));
1609 lv->currentBufferView()->insertPlaintextFile(FileName(filename2),
1611 guiApp->setCurrentView(lv);
1612 lyx::dispatch(FuncRequest(LFUN_MARK_OFF));
1619 void GuiView::importDocument(string const & argument)
1622 string filename = split(argument, format, ' ');
1624 LYXERR(Debug::INFO, format << " file: " << filename);
1626 // need user interaction
1627 if (filename.empty()) {
1628 string initpath = lyxrc.document_path;
1629 if (documentBufferView()) {
1630 string const trypath = documentBufferView()->buffer().filePath();
1631 // If directory is writeable, use this as default.
1632 if (FileName(trypath).isDirWritable())
1636 docstring const text = bformat(_("Select %1$s file to import"),
1637 formats.prettyName(format));
1639 FileDialog dlg(toqstr(text), LFUN_BUFFER_IMPORT);
1640 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1641 dlg.setButton2(qt_("Examples|#E#e"),
1642 toqstr(addPath(package().system_support().absFilename(), "examples")));
1644 docstring filter = formats.prettyName(format);
1647 filter += from_utf8(formats.extension(format));
1650 FileDialog::Result result =
1651 dlg.open(toqstr(initpath), fileFilters(toqstr(filter)));
1653 if (result.first == FileDialog::Later)
1656 filename = fromqstr(result.second);
1658 // check selected filename
1659 if (filename.empty())
1660 message(_("Canceled."));
1663 if (filename.empty())
1666 // get absolute path of file
1667 FileName const fullname(support::makeAbsPath(filename));
1669 FileName const lyxfile(support::changeExtension(fullname.absFilename(), ".lyx"));
1671 // Check if the document already is open
1672 Buffer * buf = theBufferList().getBuffer(lyxfile);
1675 if (!closeBuffer()) {
1676 message(_("Canceled."));
1681 docstring const displaypath = makeDisplayPath(lyxfile.absFilename(), 30);
1683 // if the file exists already, and we didn't do
1684 // -i lyx thefile.lyx, warn
1685 if (lyxfile.exists() && fullname != lyxfile) {
1687 docstring text = bformat(_("The document %1$s already exists.\n\n"
1688 "Do you want to overwrite that document?"), displaypath);
1689 int const ret = Alert::prompt(_("Overwrite document?"),
1690 text, 0, 1, _("&Overwrite"), _("&Cancel"));
1693 message(_("Canceled."));
1698 message(bformat(_("Importing %1$s..."), displaypath));
1699 ErrorList errorList;
1700 if (import(this, fullname, format, errorList))
1701 message(_("imported."));
1703 message(_("file not imported!"));
1705 // FIXME (Abdel 12/08/06): Is there a need to display the error list here?
1709 void GuiView::newDocument(string const & filename, bool from_template)
1711 FileName initpath(lyxrc.document_path);
1712 if (documentBufferView()) {
1713 FileName const trypath(documentBufferView()->buffer().filePath());
1714 // If directory is writeable, use this as default.
1715 if (trypath.isDirWritable())
1719 string templatefile;
1720 if (from_template) {
1721 templatefile = selectTemplateFile().absFilename();
1722 if (templatefile.empty())
1727 if (filename.empty())
1728 b = newUnnamedFile(templatefile, initpath);
1730 b = newFile(filename, templatefile, true);
1735 // If no new document could be created, it is unsure
1736 // whether there is a valid BufferView.
1737 if (currentBufferView())
1738 // Ensure the cursor is correctly positioned on screen.
1739 currentBufferView()->showCursor();
1743 void GuiView::insertLyXFile(docstring const & fname)
1745 BufferView * bv = documentBufferView();
1750 FileName filename(to_utf8(fname));
1752 if (!filename.empty()) {
1753 bv->insertLyXFile(filename);
1757 // Launch a file browser
1759 string initpath = lyxrc.document_path;
1760 string const trypath = bv->buffer().filePath();
1761 // If directory is writeable, use this as default.
1762 if (FileName(trypath).isDirWritable())
1766 FileDialog dlg(qt_("Select LyX document to insert"), LFUN_FILE_INSERT);
1767 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1768 dlg.setButton2(qt_("Examples|#E#e"),
1769 toqstr(addPath(package().system_support().absFilename(),
1772 FileDialog::Result result = dlg.open(toqstr(initpath),
1773 QStringList(qt_("LyX Documents (*.lyx)")));
1775 if (result.first == FileDialog::Later)
1779 filename.set(fromqstr(result.second));
1781 // check selected filename
1782 if (filename.empty()) {
1783 // emit message signal.
1784 message(_("Canceled."));
1788 bv->insertLyXFile(filename);
1792 void GuiView::insertPlaintextFile(docstring const & fname,
1795 BufferView * bv = documentBufferView();
1799 if (!fname.empty() && !FileName::isAbsolute(to_utf8(fname))) {
1800 message(_("Absolute filename expected."));
1805 FileName filename(to_utf8(fname));
1807 if (!filename.empty()) {
1808 bv->insertPlaintextFile(filename, asParagraph);
1812 FileDialog dlg(qt_("Select file to insert"), (asParagraph ?
1813 LFUN_FILE_INSERT_PLAINTEXT_PARA : LFUN_FILE_INSERT_PLAINTEXT));
1815 FileDialog::Result result = dlg.open(toqstr(bv->buffer().filePath()),
1816 QStringList(qt_("All Files (*)")));
1818 if (result.first == FileDialog::Later)
1822 filename.set(fromqstr(result.second));
1824 // check selected filename
1825 if (filename.empty()) {
1826 // emit message signal.
1827 message(_("Canceled."));
1831 bv->insertPlaintextFile(filename, asParagraph);
1835 bool GuiView::renameBuffer(Buffer & b, docstring const & newname)
1837 FileName fname = b.fileName();
1838 FileName const oldname = fname;
1840 if (!newname.empty()) {
1842 fname = support::makeAbsPath(to_utf8(newname), oldname.onlyPath().absFilename());
1844 // Switch to this Buffer.
1847 // No argument? Ask user through dialog.
1849 FileDialog dlg(qt_("Choose a filename to save document as"),
1850 LFUN_BUFFER_WRITE_AS);
1851 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1852 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
1854 if (!isLyXFilename(fname.absFilename()))
1855 fname.changeExtension(".lyx");
1857 FileDialog::Result result =
1858 dlg.save(toqstr(fname.onlyPath().absFilename()),
1859 QStringList(qt_("LyX Documents (*.lyx)")),
1860 toqstr(fname.onlyFileName()));
1862 if (result.first == FileDialog::Later)
1865 fname.set(fromqstr(result.second));
1870 if (!isLyXFilename(fname.absFilename()))
1871 fname.changeExtension(".lyx");
1874 if (FileName(fname).exists()) {
1875 docstring const file = makeDisplayPath(fname.absFilename(), 30);
1876 docstring text = bformat(_("The document %1$s already "
1877 "exists.\n\nDo you want to "
1878 "overwrite that document?"),
1880 int const ret = Alert::prompt(_("Overwrite document?"),
1881 text, 0, 2, _("&Overwrite"), _("&Rename"), _("&Cancel"));
1884 case 1: return renameBuffer(b, docstring());
1885 case 2: return false;
1889 FileName oldauto = b.getAutosaveFilename();
1891 // Ok, change the name of the buffer
1892 b.setFileName(fname.absFilename());
1894 bool unnamed = b.isUnnamed();
1895 b.setUnnamed(false);
1896 b.saveCheckSum(fname);
1898 // bring the autosave file with us, just in case.
1899 b.moveAutosaveFile(oldauto);
1901 if (!saveBuffer(b)) {
1902 oldauto = b.getAutosaveFilename();
1903 b.setFileName(oldname.absFilename());
1904 b.setUnnamed(unnamed);
1905 b.saveCheckSum(oldname);
1906 b.moveAutosaveFile(oldauto);
1914 bool GuiView::saveBuffer(Buffer & b)
1916 if (workArea(b) && workArea(b)->inDialogMode())
1920 return renameBuffer(b, docstring());
1923 theSession().lastFiles().add(b.fileName());
1927 // Switch to this Buffer.
1930 // FIXME: we don't tell the user *WHY* the save failed !!
1931 docstring const file = makeDisplayPath(b.absFileName(), 30);
1932 docstring text = bformat(_("The document %1$s could not be saved.\n\n"
1933 "Do you want to rename the document and "
1934 "try again?"), file);
1935 int const ret = Alert::prompt(_("Rename and save?"),
1936 text, 0, 2, _("&Rename"), _("&Retry"), _("&Cancel"));
1939 if (!renameBuffer(b, docstring()))
1948 return saveBuffer(b);
1952 bool GuiView::hideWorkArea(GuiWorkArea * wa)
1954 return closeWorkArea(wa, false);
1958 bool GuiView::closeWorkArea(GuiWorkArea * wa)
1960 Buffer & buf = wa->bufferView().buffer();
1961 return closeWorkArea(wa, !buf.parent());
1965 bool GuiView::closeBuffer()
1967 GuiWorkArea * wa = currentMainWorkArea();
1968 Buffer & buf = wa->bufferView().buffer();
1969 return wa && closeWorkArea(wa, !buf.parent());
1973 void GuiView::writeSession() const {
1974 GuiWorkArea const * active_wa = currentMainWorkArea();
1975 for (int i = 0; i < d.splitter_->count(); ++i) {
1976 TabWorkArea * twa = d.tabWorkArea(i);
1977 for (int j = 0; j < twa->count(); ++j) {
1978 GuiWorkArea * wa = static_cast<GuiWorkArea *>(twa->widget(j));
1979 Buffer & buf = wa->bufferView().buffer();
1980 theSession().lastOpened().add(buf.fileName(), wa == active_wa);
1986 bool GuiView::closeBufferAll()
1988 // Close the workareas in all other views
1989 QList<int> const ids = guiApp->viewIds();
1990 for (int i = 0; i != ids.size(); ++i) {
1991 if (id_ != ids[i] && !guiApp->view(ids[i]).closeWorkAreaAll())
1995 // Close our own workareas
1996 if (!closeWorkAreaAll())
1999 // Now close the hidden buffers. We prevent hidden buffers from being
2000 // dirty, so we can just close them.
2001 theBufferList().closeAll();
2006 bool GuiView::closeWorkAreaAll()
2008 setCurrentWorkArea(currentMainWorkArea());
2010 // We might be in a situation that there is still a tabWorkArea, but
2011 // there are no tabs anymore. This can happen when we get here after a
2012 // TabWorkArea::lastWorkAreaRemoved() signal. Therefore we count how
2013 // many TabWorkArea's have no documents anymore.
2016 // We have to call count() each time, because it can happen that
2017 // more than one splitter will disappear in one iteration (bug 5998).
2018 for (; d.splitter_->count() > empty_twa; ) {
2019 TabWorkArea * twa = d.tabWorkArea(empty_twa);
2021 if (twa->count() == 0)
2024 setCurrentWorkArea(twa->currentWorkArea());
2025 if (!closeTabWorkArea(twa))
2033 bool GuiView::closeWorkArea(GuiWorkArea * wa, bool close_buffer)
2035 Buffer & buf = wa->bufferView().buffer();
2037 // If we are in a close_event all children will be closed in some time,
2038 // so no need to do it here. This will ensure that the children end up
2039 // in the session file in the correct order. If we close the master
2040 // buffer, we can close or release the child buffers here too.
2041 if (close_buffer && !closing_) {
2042 vector<Buffer *> clist = buf.getChildren();
2043 for (vector<Buffer *>::const_iterator it = clist.begin();
2044 it != clist.end(); ++it) {
2045 // If a child is dirty, do not close
2046 // without user intervention
2047 //FIXME: should we look in other tabworkareas?
2048 Buffer * child_buf = *it;
2049 GuiWorkArea * child_wa = workArea(*child_buf);
2051 if (!closeWorkArea(child_wa, true))
2054 theBufferList().releaseChild(&buf, child_buf);
2057 // goto bookmark to update bookmark pit.
2058 //FIXME: we should update only the bookmarks related to this buffer!
2059 LYXERR(Debug::DEBUG, "GuiView::closeBuffer()");
2060 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
2061 theLyXFunc().gotoBookmark(i+1, false, false);
2063 // if we are only hiding the buffer and there are multiple views
2064 // of the buffer, then we do not need to ensure a clean buffer.
2065 bool const allow_dirty = inMultiTabs(wa) && !close_buffer;
2067 if (allow_dirty || saveBufferIfNeeded(buf, !close_buffer)) {
2068 // save in sessions if requested
2069 // do not save childs if their master
2070 // is opened as well
2074 theBufferList().release(&buf);
2081 bool GuiView::closeTabWorkArea(TabWorkArea * twa)
2083 while (twa == d.currentTabWorkArea()) {
2084 twa->setCurrentIndex(twa->count()-1);
2086 GuiWorkArea * wa = twa->currentWorkArea();
2087 Buffer & b = wa->bufferView().buffer();
2089 // We only want to close the buffer if the same buffer is not visible
2090 // in another view, and if this is not a child and if we are closing
2091 // a view (not a tabgroup).
2092 bool const close_buffer =
2093 !inMultiViews(wa) && !b.parent() && closing_;
2095 if (!closeWorkArea(wa, close_buffer))
2102 bool GuiView::saveBufferIfNeeded(Buffer & buf, bool hiding)
2104 if (buf.isClean() || buf.paragraphs().empty())
2107 // Switch to this Buffer.
2112 if (buf.isUnnamed())
2113 file = from_utf8(buf.fileName().onlyFileName());
2115 file = buf.fileName().displayName(30);
2117 // Bring this window to top before asking questions.
2122 if (hiding && buf.isUnnamed()) {
2123 docstring const text = bformat(_("The document %1$s has not been "
2124 "saved yet.\n\nDo you want to save "
2125 "the document?"), file);
2126 ret = Alert::prompt(_("Save new document?"),
2127 text, 0, 1, _("&Save"), _("&Cancel"));
2131 docstring const text = bformat(_("The document %1$s has unsaved changes."
2132 "\n\nDo you want to save the document or discard the changes?"), file);
2133 ret = Alert::prompt(_("Save changed document?"),
2134 text, 0, 2, _("&Save"), _("&Discard"), _("&Cancel"));
2139 if (!saveBuffer(buf))
2143 // if we crash after this we could
2144 // have no autosave file but I guess
2145 // this is really improbable (Jug)
2146 buf.removeAutosaveFile();
2148 // revert all changes
2149 buf.loadLyXFile(buf.fileName());
2159 bool GuiView::inMultiTabs(GuiWorkArea * wa)
2161 Buffer & buf = wa->bufferView().buffer();
2163 for (int i = 0; i != d.splitter_->count(); ++i) {
2164 GuiWorkArea * wa_ = d.tabWorkArea(i)->workArea(buf);
2165 if (wa_ && wa_ != wa)
2168 return inMultiViews(wa);
2172 bool GuiView::inMultiViews(GuiWorkArea * wa)
2174 QList<int> const ids = guiApp->viewIds();
2175 Buffer & buf = wa->bufferView().buffer();
2178 for (int i = 0; i != ids.size() && found_twa <= 1; ++i) {
2182 if (guiApp->view(ids[i]).workArea(buf))
2189 void GuiView::gotoNextOrPreviousBuffer(NextOrPrevious np)
2191 Buffer * const curbuf = documentBufferView()
2192 ? &documentBufferView()->buffer() : 0;
2193 Buffer * nextbuf = curbuf;
2195 if (np == NEXTBUFFER)
2196 nextbuf = theBufferList().next(nextbuf);
2198 nextbuf = theBufferList().previous(nextbuf);
2199 if (nextbuf == curbuf)
2205 if (workArea(*nextbuf))
2212 /// make sure the document is saved
2213 static bool ensureBufferClean(Buffer * buffer)
2215 LASSERT(buffer, return false);
2216 if (buffer->isClean() && !buffer->isUnnamed())
2219 docstring const file = buffer->fileName().displayName(30);
2222 if (!buffer->isUnnamed()) {
2223 text = bformat(_("The document %1$s has unsaved "
2224 "changes.\n\nDo you want to save "
2225 "the document?"), file);
2226 title = _("Save changed document?");
2229 text = bformat(_("The document %1$s has not been "
2230 "saved yet.\n\nDo you want to save "
2231 "the document?"), file);
2232 title = _("Save new document?");
2234 int const ret = Alert::prompt(title, text, 0, 1, _("&Save"), _("&Cancel"));
2237 dispatch(FuncRequest(LFUN_BUFFER_WRITE));
2239 return buffer->isClean() && !buffer->isUnnamed();
2243 void GuiView::reloadBuffer()
2245 Buffer * buf = &documentBufferView()->buffer();
2246 FileName filename = buf->fileName();
2247 // The user has already confirmed that the changes, if any, should
2248 // be discarded. So we just release the Buffer and don't call closeBuffer();
2249 theBufferList().release(buf);
2250 buf = loadDocument(filename);
2251 docstring const disp_fn = makeDisplayPath(filename.absFilename());
2254 buf->updateLabels();
2256 buf->errors("Parse");
2257 str = bformat(_("Document %1$s reloaded."), disp_fn);
2259 str = bformat(_("Could not reload document %1$s"), disp_fn);
2265 void GuiView::dispatchVC(FuncRequest const & cmd)
2267 Buffer * buffer = documentBufferView()
2268 ? &(documentBufferView()->buffer()) : 0;
2270 switch (cmd.action) {
2271 case LFUN_VC_REGISTER:
2272 if (!buffer || !ensureBufferClean(buffer))
2274 if (!buffer->lyxvc().inUse()) {
2275 if (buffer->lyxvc().registrer())
2280 case LFUN_VC_CHECK_IN:
2281 if (!buffer || !ensureBufferClean(buffer))
2283 if (buffer->lyxvc().inUse() && !buffer->isReadonly()) {
2284 message(from_utf8(buffer->lyxvc().checkIn()));
2289 case LFUN_VC_CHECK_OUT:
2290 if (!buffer || !ensureBufferClean(buffer))
2292 if (buffer->lyxvc().inUse()) {
2293 message(from_utf8(buffer->lyxvc().checkOut()));
2298 case LFUN_VC_LOCKING_TOGGLE:
2299 LASSERT(buffer, return);
2300 if (!ensureBufferClean(buffer) || buffer->isReadonly())
2302 if (buffer->lyxvc().inUse()) {
2303 string res = buffer->lyxvc().lockingToggle();
2305 frontend::Alert::error(_("Revision control error."),
2306 _("Error when setting the locking property."));
2308 message(from_utf8(res));
2314 case LFUN_VC_REVERT:
2315 LASSERT(buffer, return);
2316 buffer->lyxvc().revert();
2320 case LFUN_VC_UNDO_LAST:
2321 LASSERT(buffer, return);
2322 buffer->lyxvc().undoLast();
2326 case LFUN_VC_COMMAND: {
2327 string flag = cmd.getArg(0);
2328 if (buffer && contains(flag, 'R') && !ensureBufferClean(buffer))
2331 if (contains(flag, 'M')) {
2332 if (!Alert::askForText(message, _("LyX VC: Log Message")))
2335 string path = cmd.getArg(1);
2336 if (contains(path, "$$p") && buffer)
2337 path = subst(path, "$$p", buffer->filePath());
2338 LYXERR(Debug::LYXVC, "Directory: " << path);
2340 if (!pp.isReadableDirectory()) {
2341 lyxerr << _("Directory is not accessible.") << endl;
2344 support::PathChanger p(pp);
2346 string command = cmd.getArg(2);
2347 if (command.empty())
2350 command = subst(command, "$$i", buffer->absFileName());
2351 command = subst(command, "$$p", buffer->filePath());
2353 command = subst(command, "$$m", to_utf8(message));
2354 LYXERR(Debug::LYXVC, "Command: " << command);
2356 one.startscript(Systemcall::Wait, command);
2360 if (contains(flag, 'I'))
2361 buffer->markDirty();
2362 if (contains(flag, 'R'))
2373 void GuiView::openChildDocument(string const & fname)
2375 LASSERT(documentBufferView(), return);
2376 Buffer & buffer = documentBufferView()->buffer();
2377 FileName const filename = support::makeAbsPath(fname, buffer.filePath());
2378 documentBufferView()->saveBookmark(false);
2380 bool parsed = false;
2381 if (theBufferList().exists(filename)) {
2382 child = theBufferList().getBuffer(filename);
2384 message(bformat(_("Opening child document %1$s..."),
2385 makeDisplayPath(filename.absFilename())));
2386 child = loadDocument(filename, false);
2392 // Set the parent name of the child document.
2393 // This makes insertion of citations and references in the child work,
2394 // when the target is in the parent or another child document.
2395 child->setParent(&buffer);
2396 child->masterBuffer()->updateLabels();
2399 child->errors("Parse");
2403 bool GuiView::dispatch(FuncRequest const & cmd)
2405 BufferView * bv = currentBufferView();
2406 // By default we won't need any update.
2408 bv->cursor().updateFlags(Update::None);
2410 Buffer * doc_buffer = documentBufferView()
2411 ? &(documentBufferView()->buffer()) : 0;
2413 bool dispatched = true;
2415 if (cmd.origin == FuncRequest::TOC) {
2416 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
2417 toc->doDispatch(bv->cursor(), cmd);
2421 switch(cmd.action) {
2422 case LFUN_BUFFER_CHILD_OPEN:
2423 openChildDocument(to_utf8(cmd.argument()));
2426 case LFUN_BUFFER_IMPORT:
2427 importDocument(to_utf8(cmd.argument()));
2430 case LFUN_BUFFER_SWITCH:
2431 if (FileName::isAbsolute(to_utf8(cmd.argument()))) {
2433 theBufferList().getBuffer(FileName(to_utf8(cmd.argument())));
2437 bv->cursor().message(_("Document not loaded"));
2441 case LFUN_BUFFER_NEXT:
2442 gotoNextOrPreviousBuffer(NEXTBUFFER);
2445 case LFUN_BUFFER_PREVIOUS:
2446 gotoNextOrPreviousBuffer(PREVBUFFER);
2449 case LFUN_COMMAND_EXECUTE: {
2450 bool const show_it = cmd.argument() != "off";
2451 // FIXME: this is a hack, "minibuffer" should not be
2453 if (GuiToolbar * t = toolbar("minibuffer")) {
2454 t->setVisible(show_it);
2455 if (show_it && t->commandBuffer())
2456 t->commandBuffer()->setFocus();
2460 case LFUN_DROP_LAYOUTS_CHOICE:
2461 d.layout_->showPopup();
2464 case LFUN_MENU_OPEN:
2465 if (QMenu * menu = guiApp->menus().menu(toqstr(cmd.argument()), *this))
2466 menu->exec(QCursor::pos());
2469 case LFUN_FILE_INSERT:
2470 insertLyXFile(cmd.argument());
2472 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
2473 insertPlaintextFile(cmd.argument(), true);
2476 case LFUN_FILE_INSERT_PLAINTEXT:
2477 insertPlaintextFile(cmd.argument(), false);
2480 case LFUN_BUFFER_RELOAD: {
2481 LASSERT(doc_buffer, break);
2482 docstring const file = makeDisplayPath(doc_buffer->absFileName(), 20);
2483 docstring text = bformat(_("Any changes will be lost. Are you sure "
2484 "you want to revert to the saved version of the document %1$s?"), file);
2485 int const ret = Alert::prompt(_("Revert to saved document?"),
2486 text, 1, 1, _("&Revert"), _("&Cancel"));
2493 case LFUN_BUFFER_WRITE:
2494 LASSERT(doc_buffer, break);
2495 saveBuffer(*doc_buffer);
2498 case LFUN_BUFFER_WRITE_AS:
2499 LASSERT(doc_buffer, break);
2500 renameBuffer(*doc_buffer, cmd.argument());
2503 case LFUN_BUFFER_WRITE_ALL: {
2504 Buffer * first = theBufferList().first();
2507 message(_("Saving all documents..."));
2508 // We cannot use a for loop as the buffer list cycles.
2511 if (!b->isClean()) {
2513 LYXERR(Debug::ACTION, "Saved " << b->absFileName());
2515 b = theBufferList().next(b);
2516 } while (b != first);
2517 message(_("All documents saved."));
2521 case LFUN_BUFFER_CLOSE:
2525 case LFUN_BUFFER_CLOSE_ALL:
2529 case LFUN_TOOLBAR_TOGGLE: {
2530 string const name = cmd.getArg(0);
2531 if (GuiToolbar * t = toolbar(name))
2536 case LFUN_DIALOG_UPDATE: {
2537 string const name = to_utf8(cmd.argument());
2538 // Can only update a dialog connected to an existing inset
2539 Inset * inset = getOpenInset(name);
2541 FuncRequest fr(LFUN_INSET_DIALOG_UPDATE, cmd.argument());
2542 inset->dispatch(currentBufferView()->cursor(), fr);
2543 } else if (name == "paragraph") {
2544 lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
2545 } else if (name == "prefs" || name == "document") {
2546 updateDialog(name, string());
2551 case LFUN_DIALOG_TOGGLE: {
2552 if (isDialogVisible(cmd.getArg(0)))
2553 dispatch(FuncRequest(LFUN_DIALOG_HIDE, cmd.argument()));
2555 dispatch(FuncRequest(LFUN_DIALOG_SHOW, cmd.argument()));
2559 case LFUN_DIALOG_DISCONNECT_INSET:
2560 disconnectDialog(to_utf8(cmd.argument()));
2563 case LFUN_DIALOG_HIDE: {
2564 guiApp->hideDialogs(to_utf8(cmd.argument()), 0);
2568 case LFUN_DIALOG_SHOW: {
2569 string const name = cmd.getArg(0);
2570 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
2572 if (name == "character") {
2573 data = freefont2string();
2575 showDialog("character", data);
2576 } else if (name == "latexlog") {
2577 Buffer::LogType type;
2578 string const logfile = doc_buffer->logName(&type);
2580 case Buffer::latexlog:
2583 case Buffer::buildlog:
2587 data += Lexer::quoteString(logfile);
2588 showDialog("log", data);
2589 } else if (name == "vclog") {
2590 string const data = "vc " +
2591 Lexer::quoteString(doc_buffer->lyxvc().getLogFile());
2592 showDialog("log", data);
2593 } else if (name == "symbols") {
2594 data = bv->cursor().getEncoding()->name();
2596 showDialog("symbols", data);
2598 } else if (name == "prefs" && isFullScreen()) {
2599 FuncRequest fr(LFUN_INSET_INSERT, "fullscreen");
2601 showDialog("prefs", data);
2603 showDialog(name, data);
2608 message(cmd.argument());
2611 case LFUN_INSET_APPLY: {
2612 string const name = cmd.getArg(0);
2613 Inset * inset = getOpenInset(name);
2615 // put cursor in front of inset.
2616 if (!currentBufferView()->setCursorFromInset(inset)) {
2617 LASSERT(false, break);
2619 BufferView * bv = currentBufferView();
2620 // useful if we are called from a dialog.
2621 bv->cursor().beginUndoGroup();
2622 bv->cursor().recordUndo();
2623 FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument());
2624 inset->dispatch(bv->cursor(), fr);
2625 bv->cursor().endUndoGroup();
2627 FuncRequest fr(LFUN_INSET_INSERT, cmd.argument());
2633 case LFUN_UI_TOGGLE:
2635 // Make sure the keyboard focus stays in the work area.
2639 case LFUN_SPLIT_VIEW: {
2640 LASSERT(doc_buffer, break);
2641 string const orientation = cmd.getArg(0);
2642 d.splitter_->setOrientation(orientation == "vertical"
2643 ? Qt::Vertical : Qt::Horizontal);
2644 TabWorkArea * twa = addTabWorkArea();
2645 GuiWorkArea * wa = twa->addWorkArea(*doc_buffer, *this);
2646 setCurrentWorkArea(wa);
2649 case LFUN_CLOSE_TAB_GROUP:
2650 if (TabWorkArea * twa = d.currentTabWorkArea()) {
2651 closeTabWorkArea(twa);
2652 d.current_work_area_ = 0;
2653 twa = d.currentTabWorkArea();
2654 // Switch to the next GuiWorkArea in the found TabWorkArea.
2656 // Make sure the work area is up to date.
2657 setCurrentWorkArea(twa->currentWorkArea());
2659 setCurrentWorkArea(0);
2664 case LFUN_COMPLETION_INLINE:
2665 if (d.current_work_area_)
2666 d.current_work_area_->completer().showInline();
2669 case LFUN_COMPLETION_POPUP:
2670 if (d.current_work_area_)
2671 d.current_work_area_->completer().showPopup();
2675 case LFUN_COMPLETION_COMPLETE:
2676 if (d.current_work_area_)
2677 d.current_work_area_->completer().tab();
2680 case LFUN_COMPLETION_CANCEL:
2681 if (d.current_work_area_) {
2682 if (d.current_work_area_->completer().popupVisible())
2683 d.current_work_area_->completer().hidePopup();
2685 d.current_work_area_->completer().hideInline();
2689 case LFUN_COMPLETION_ACCEPT:
2690 if (d.current_work_area_)
2691 d.current_work_area_->completer().activate();
2694 case LFUN_BUFFER_ZOOM_IN:
2695 case LFUN_BUFFER_ZOOM_OUT:
2696 if (cmd.argument().empty()) {
2697 if (cmd.action == LFUN_BUFFER_ZOOM_IN)
2702 lyxrc.zoom += convert<int>(cmd.argument());
2704 if (lyxrc.zoom < 10)
2707 // The global QPixmapCache is used in GuiPainter to cache text
2708 // painting so we must reset it.
2709 QPixmapCache::clear();
2710 guiApp->fontLoader().update();
2711 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
2714 case LFUN_VC_REGISTER:
2715 case LFUN_VC_CHECK_IN:
2716 case LFUN_VC_CHECK_OUT:
2717 case LFUN_VC_LOCKING_TOGGLE:
2718 case LFUN_VC_REVERT:
2719 case LFUN_VC_UNDO_LAST:
2720 case LFUN_VC_COMMAND:
2729 // Part of automatic menu appearance feature.
2730 if (isFullScreen()) {
2731 if (menuBar()->isVisible() && lyxrc.full_screen_menubar)
2733 if (statusBar()->isVisible())
2734 statusBar()->hide();
2741 void GuiView::lfunUiToggle(FuncRequest const & cmd)
2743 string const arg = cmd.getArg(0);
2744 if (arg == "scrollbar") {
2745 // hide() is of no help
2746 if (d.current_work_area_->verticalScrollBarPolicy() ==
2747 Qt::ScrollBarAlwaysOff)
2749 d.current_work_area_->setVerticalScrollBarPolicy(
2750 Qt::ScrollBarAsNeeded);
2752 d.current_work_area_->setVerticalScrollBarPolicy(
2753 Qt::ScrollBarAlwaysOff);
2756 if (arg == "statusbar") {
2757 statusBar()->setVisible(!statusBar()->isVisible());
2760 if (arg == "menubar") {
2761 menuBar()->setVisible(!menuBar()->isVisible());
2764 #if QT_VERSION >= 0x040300
2765 if (arg == "frame") {
2767 getContentsMargins(&l, &t, &r, &b);
2768 //are the frames in default state?
2769 d.current_work_area_->setFrameStyle(QFrame::NoFrame);
2771 setContentsMargins(-2, -2, -2, -2);
2773 setContentsMargins(0, 0, 0, 0);
2778 if (arg == "fullscreen") {
2783 message(bformat("LFUN_UI_TOGGLE " + _("%1$s unknown command!"), from_utf8(arg)));
2787 void GuiView::toggleFullScreen()
2789 if (isFullScreen()) {
2790 for (int i = 0; i != d.splitter_->count(); ++i)
2791 d.tabWorkArea(i)->setFullScreen(false);
2792 #if QT_VERSION >= 0x040300
2793 setContentsMargins(0, 0, 0, 0);
2795 setWindowState(windowState() ^ Qt::WindowFullScreen);
2798 statusBar()->show();
2801 hideDialogs("prefs", 0);
2802 for (int i = 0; i != d.splitter_->count(); ++i)
2803 d.tabWorkArea(i)->setFullScreen(true);
2804 #if QT_VERSION >= 0x040300
2805 setContentsMargins(-2, -2, -2, -2);
2808 setWindowState(windowState() ^ Qt::WindowFullScreen);
2809 statusBar()->hide();
2810 if (lyxrc.full_screen_menubar)
2812 if (lyxrc.full_screen_toolbars) {
2813 ToolbarMap::iterator end = d.toolbars_.end();
2814 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
2819 // give dialogs like the TOC a chance to adapt
2824 Buffer const * GuiView::updateInset(Inset const * inset)
2826 if (!d.current_work_area_)
2830 d.current_work_area_->scheduleRedraw();
2832 return &d.current_work_area_->bufferView().buffer();
2836 void GuiView::restartCursor()
2838 /* When we move around, or type, it's nice to be able to see
2839 * the cursor immediately after the keypress.
2841 if (d.current_work_area_)
2842 d.current_work_area_->startBlinkingCursor();
2844 // Take this occasion to update the other GUI elements.
2850 void GuiView::updateCompletion(Cursor & cur, bool start, bool keep)
2852 if (d.current_work_area_)
2853 d.current_work_area_->completer().updateVisibility(cur, start, keep);
2858 // This list should be kept in sync with the list of insets in
2859 // src/insets/Inset.cpp. I.e., if a dialog goes with an inset, the
2860 // dialog should have the same name as the inset.
2861 // Changes should be also recorded in LFUN_DIALOG_SHOW doxygen
2862 // docs in LyXAction.cpp.
2864 char const * const dialognames[] = {
2865 "aboutlyx", "bibitem", "bibtex", "box", "branch", "changes", "character",
2866 "citation", "document", "errorlist", "ert", "external", "file", "findreplace",
2867 "findreplaceadv", "float", "graphics", "href", "include", "index",
2868 "index_print", "info", "listings", "label", "log", "mathdelimiter",
2869 "mathmatrix", "mathspace", "nomenclature", "nomencl_print", "note",
2870 "paragraph", "phantom", "prefs", "print", "ref", "sendto", "space",
2871 "spellchecker", "symbols", "tabular", "tabularcreate", "thesaurus", "texinfo",
2872 "toc", "view-source", "vspace", "wrap" };
2874 char const * const * const end_dialognames =
2875 dialognames + (sizeof(dialognames) / sizeof(char *));
2879 cmpCStr(char const * name) : name_(name) {}
2880 bool operator()(char const * other) {
2881 return strcmp(other, name_) == 0;
2888 bool isValidName(string const & name)
2890 return find_if(dialognames, end_dialognames,
2891 cmpCStr(name.c_str())) != end_dialognames;
2897 void GuiView::resetDialogs()
2899 // Make sure that no LFUN uses any LyXView.
2900 guiApp->setCurrentView(0);
2903 constructToolbars();
2904 guiApp->menus().fillMenuBar(menuBar(), this, false);
2905 d.layout_->updateContents(true);
2906 // Now update controls with current buffer.
2907 guiApp->setCurrentView(this);
2913 Dialog * GuiView::findOrBuild(string const & name, bool hide_it)
2915 if (!isValidName(name))
2918 map<string, DialogPtr>::iterator it = d.dialogs_.find(name);
2920 if (it != d.dialogs_.end()) {
2922 it->second->hideView();
2923 return it->second.get();
2926 Dialog * dialog = build(name);
2927 d.dialogs_[name].reset(dialog);
2928 if (lyxrc.allow_geometry_session)
2929 dialog->restoreSession();
2936 void GuiView::showDialog(string const & name, string const & data,
2944 Dialog * dialog = findOrBuild(name, false);
2946 dialog->showData(data);
2948 d.open_insets_[name] = inset;
2951 catch (ExceptionMessage const & ex) {
2959 bool GuiView::isDialogVisible(string const & name) const
2961 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
2962 if (it == d.dialogs_.end())
2964 return it->second.get()->isVisibleView() && !it->second.get()->isClosing();
2968 void GuiView::hideDialog(string const & name, Inset * inset)
2970 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
2971 if (it == d.dialogs_.end())
2974 if (inset && inset != getOpenInset(name))
2977 Dialog * const dialog = it->second.get();
2978 if (dialog->isVisibleView())
2980 d.open_insets_[name] = 0;
2984 void GuiView::disconnectDialog(string const & name)
2986 if (!isValidName(name))
2989 if (d.open_insets_.find(name) != d.open_insets_.end())
2990 d.open_insets_[name] = 0;
2994 Inset * GuiView::getOpenInset(string const & name) const
2996 if (!isValidName(name))
2999 map<string, Inset *>::const_iterator it = d.open_insets_.find(name);
3000 return it == d.open_insets_.end() ? 0 : it->second;
3004 void GuiView::hideAll() const
3006 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
3007 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3009 for(; it != end; ++it)
3010 it->second->hideView();
3014 void GuiView::updateDialogs()
3016 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
3017 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3019 for(; it != end; ++it) {
3020 Dialog * dialog = it->second.get();
3021 if (dialog && dialog->isVisibleView())
3022 dialog->checkStatus();
3029 // will be replaced by a proper factory...
3030 Dialog * createGuiAbout(GuiView & lv);
3031 Dialog * createGuiBibitem(GuiView & lv);
3032 Dialog * createGuiBibtex(GuiView & lv);
3033 Dialog * createGuiBox(GuiView & lv);
3034 Dialog * createGuiBranch(GuiView & lv);
3035 Dialog * createGuiChanges(GuiView & lv);
3036 Dialog * createGuiCharacter(GuiView & lv);
3037 Dialog * createGuiCitation(GuiView & lv);
3038 Dialog * createGuiDelimiter(GuiView & lv);
3039 Dialog * createGuiDocument(GuiView & lv);
3040 Dialog * createGuiErrorList(GuiView & lv);
3041 Dialog * createGuiERT(GuiView & lv);
3042 Dialog * createGuiExternal(GuiView & lv);
3043 Dialog * createGuiFloat(GuiView & lv);
3044 Dialog * createGuiGraphics(GuiView & lv);
3045 Dialog * createGuiInclude(GuiView & lv);
3046 Dialog * createGuiIndex(GuiView & lv);
3047 Dialog * createGuiInfo(GuiView & lv);
3048 Dialog * createGuiLabel(GuiView & lv);
3049 Dialog * createGuiListings(GuiView & lv);
3050 Dialog * createGuiLog(GuiView & lv);
3051 Dialog * createGuiMathHSpace(GuiView & lv);
3052 Dialog * createGuiMathMatrix(GuiView & lv);
3053 Dialog * createGuiNomenclature(GuiView & lv);
3054 Dialog * createGuiNote(GuiView & lv);
3055 Dialog * createGuiParagraph(GuiView & lv);
3056 Dialog * createGuiPhantom(GuiView & lv);
3057 Dialog * createGuiPreferences(GuiView & lv);
3058 Dialog * createGuiPrint(GuiView & lv);
3059 Dialog * createGuiPrintindex(GuiView & lv);
3060 Dialog * createGuiPrintNomencl(GuiView & lv);
3061 Dialog * createGuiRef(GuiView & lv);
3062 Dialog * createGuiSearch(GuiView & lv);
3063 Dialog * createGuiSearchAdv(GuiView & lv);
3064 Dialog * createGuiSendTo(GuiView & lv);
3065 Dialog * createGuiShowFile(GuiView & lv);
3066 Dialog * createGuiSpellchecker(GuiView & lv);
3067 Dialog * createGuiSymbols(GuiView & lv);
3068 Dialog * createGuiTabularCreate(GuiView & lv);
3069 Dialog * createGuiTabular(GuiView & lv);
3070 Dialog * createGuiTexInfo(GuiView & lv);
3071 Dialog * createGuiTextHSpace(GuiView & lv);
3072 Dialog * createGuiToc(GuiView & lv);
3073 Dialog * createGuiThesaurus(GuiView & lv);
3074 Dialog * createGuiHyperlink(GuiView & lv);
3075 Dialog * createGuiVSpace(GuiView & lv);
3076 Dialog * createGuiViewSource(GuiView & lv);
3077 Dialog * createGuiWrap(GuiView & lv);
3080 Dialog * GuiView::build(string const & name)
3082 LASSERT(isValidName(name), return 0);
3084 if (name == "aboutlyx")
3085 return createGuiAbout(*this);
3086 if (name == "bibitem")
3087 return createGuiBibitem(*this);
3088 if (name == "bibtex")
3089 return createGuiBibtex(*this);
3091 return createGuiBox(*this);
3092 if (name == "branch")
3093 return createGuiBranch(*this);
3094 if (name == "changes")
3095 return createGuiChanges(*this);
3096 if (name == "character")
3097 return createGuiCharacter(*this);
3098 if (name == "citation")
3099 return createGuiCitation(*this);
3100 if (name == "document")
3101 return createGuiDocument(*this);
3102 if (name == "errorlist")
3103 return createGuiErrorList(*this);
3105 return createGuiERT(*this);
3106 if (name == "external")
3107 return createGuiExternal(*this);
3109 return createGuiShowFile(*this);
3110 if (name == "findreplace")
3111 return createGuiSearch(*this);
3112 if (name == "findreplaceadv")
3113 return createGuiSearchAdv(*this);
3114 if (name == "float")
3115 return createGuiFloat(*this);
3116 if (name == "graphics")
3117 return createGuiGraphics(*this);
3119 return createGuiHyperlink(*this);
3120 if (name == "include")
3121 return createGuiInclude(*this);
3122 if (name == "index")
3123 return createGuiIndex(*this);
3124 if (name == "index_print")
3125 return createGuiPrintindex(*this);
3127 return createGuiInfo(*this);
3128 if (name == "label")
3129 return createGuiLabel(*this);
3130 if (name == "listings")
3131 return createGuiListings(*this);
3133 return createGuiLog(*this);
3134 if (name == "mathdelimiter")
3135 return createGuiDelimiter(*this);
3136 if (name == "mathspace")
3137 return createGuiMathHSpace(*this);
3138 if (name == "mathmatrix")
3139 return createGuiMathMatrix(*this);
3140 if (name == "nomenclature")
3141 return createGuiNomenclature(*this);
3142 if (name == "nomencl_print")
3143 return createGuiPrintNomencl(*this);
3145 return createGuiNote(*this);
3146 if (name == "paragraph")
3147 return createGuiParagraph(*this);
3148 if (name == "phantom")
3149 return createGuiPhantom(*this);
3150 if (name == "prefs")
3151 return createGuiPreferences(*this);
3152 if (name == "print")
3153 return createGuiPrint(*this);
3155 return createGuiRef(*this);
3156 if (name == "sendto")
3157 return createGuiSendTo(*this);
3158 if (name == "space")
3159 return createGuiTextHSpace(*this);
3160 if (name == "spellchecker")
3161 return createGuiSpellchecker(*this);
3162 if (name == "symbols")
3163 return createGuiSymbols(*this);
3164 if (name == "tabular")
3165 return createGuiTabular(*this);
3166 if (name == "tabularcreate")
3167 return createGuiTabularCreate(*this);
3168 if (name == "texinfo")
3169 return createGuiTexInfo(*this);
3170 if (name == "thesaurus")
3171 return createGuiThesaurus(*this);
3173 return createGuiToc(*this);
3174 if (name == "view-source")
3175 return createGuiViewSource(*this);
3176 if (name == "vspace")
3177 return createGuiVSpace(*this);
3179 return createGuiWrap(*this);
3185 } // namespace frontend
3188 #include "moc_GuiView.cpp"