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);
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 case LFUN_BUFFER_WRITE_AS:
1215 enable = doc_buffer;
1218 case LFUN_BUFFER_CLOSE:
1219 enable = doc_buffer;
1222 case LFUN_BUFFER_CLOSE_ALL:
1223 enable = theBufferList().last() != theBufferList().first();
1226 case LFUN_SPLIT_VIEW:
1227 if (cmd.getArg(0) == "vertical")
1228 enable = doc_buffer && (d.splitter_->count() == 1 ||
1229 d.splitter_->orientation() == Qt::Vertical);
1231 enable = doc_buffer && (d.splitter_->count() == 1 ||
1232 d.splitter_->orientation() == Qt::Horizontal);
1235 case LFUN_CLOSE_TAB_GROUP:
1236 enable = d.currentTabWorkArea();
1239 case LFUN_TOOLBAR_TOGGLE:
1240 if (GuiToolbar * t = toolbar(cmd.getArg(0)))
1241 flag.setOnOff(t->isVisible());
1244 case LFUN_UI_TOGGLE:
1245 flag.setOnOff(isFullScreen());
1248 case LFUN_DIALOG_DISCONNECT_INSET:
1251 case LFUN_DIALOG_HIDE:
1252 // FIXME: should we check if the dialog is shown?
1255 case LFUN_DIALOG_TOGGLE:
1256 flag.setOnOff(isDialogVisible(cmd.getArg(0)));
1257 // fall through to set "enable"
1258 case LFUN_DIALOG_SHOW: {
1259 string const name = cmd.getArg(0);
1261 enable = name == "aboutlyx"
1262 || name == "file" //FIXME: should be removed.
1264 || name == "texinfo";
1265 else if (name == "print")
1266 enable = doc_buffer->isExportable("dvi")
1267 && lyxrc.print_command != "none";
1268 else if (name == "character" || name == "symbols") {
1269 if (!buf || buf->isReadonly()
1270 || !currentBufferView()->cursor().inTexted())
1273 // FIXME we should consider passthru
1275 Inset const & in = currentBufferView()->cursor().inset();
1276 enable = !in.getLayout().isPassThru();
1279 else if (name == "latexlog")
1280 enable = FileName(doc_buffer->logName()).isReadableFile();
1281 else if (name == "spellchecker")
1282 enable = theSpellChecker() && !doc_buffer->isReadonly();
1283 else if (name == "vclog")
1284 enable = doc_buffer->lyxvc().inUse();
1288 case LFUN_DIALOG_UPDATE: {
1289 string const name = cmd.getArg(0);
1291 enable = name == "prefs";
1295 case LFUN_COMMAND_EXECUTE:
1297 case LFUN_MENU_OPEN:
1298 // Nothing to check.
1301 case LFUN_INSET_APPLY: {
1302 string const name = cmd.getArg(0);
1303 Inset * inset = getOpenInset(name);
1305 FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument());
1307 if (!inset->getStatus(currentBufferView()->cursor(), fr, fs)) {
1308 // Every inset is supposed to handle this
1309 LASSERT(false, break);
1313 FuncRequest fr(LFUN_INSET_INSERT, cmd.argument());
1314 flag |= lyx::getStatus(fr);
1316 enable = flag.enabled();
1320 case LFUN_COMPLETION_INLINE:
1321 if (!d.current_work_area_
1322 || !d.current_work_area_->completer().inlinePossible(
1323 currentBufferView()->cursor()))
1327 case LFUN_COMPLETION_POPUP:
1328 if (!d.current_work_area_
1329 || !d.current_work_area_->completer().popupPossible(
1330 currentBufferView()->cursor()))
1334 case LFUN_COMPLETION_COMPLETE:
1335 if (!d.current_work_area_
1336 || !d.current_work_area_->completer().inlinePossible(
1337 currentBufferView()->cursor()))
1341 case LFUN_COMPLETION_ACCEPT:
1342 if (!d.current_work_area_
1343 || (!d.current_work_area_->completer().popupVisible()
1344 && !d.current_work_area_->completer().inlineVisible()
1345 && !d.current_work_area_->completer().completionAvailable()))
1349 case LFUN_COMPLETION_CANCEL:
1350 if (!d.current_work_area_
1351 || (!d.current_work_area_->completer().popupVisible()
1352 && !d.current_work_area_->completer().inlineVisible()))
1356 case LFUN_BUFFER_ZOOM_OUT:
1357 enable = doc_buffer && lyxrc.zoom > 10;
1360 case LFUN_BUFFER_ZOOM_IN:
1361 enable = doc_buffer;
1364 case LFUN_BUFFER_NEXT:
1365 case LFUN_BUFFER_PREVIOUS:
1366 // FIXME: should we check is there is an previous or next buffer?
1368 case LFUN_BUFFER_SWITCH:
1369 // toggle on the current buffer, but do not toggle off
1370 // the other ones (is that a good idea?)
1372 && to_utf8(cmd.argument()) == doc_buffer->absFileName())
1373 flag.setOnOff(true);
1376 case LFUN_VC_REGISTER:
1377 enable = doc_buffer && !doc_buffer->lyxvc().inUse();
1379 case LFUN_VC_CHECK_IN:
1380 enable = doc_buffer && doc_buffer->lyxvc().checkInEnabled();
1382 case LFUN_VC_CHECK_OUT:
1383 enable = doc_buffer && doc_buffer->lyxvc().checkOutEnabled();
1385 case LFUN_VC_LOCKING_TOGGLE:
1386 enable = doc_buffer && !doc_buffer->isReadonly()
1387 && doc_buffer->lyxvc().lockingToggleEnabled();
1388 flag.setOnOff(enable && !doc_buffer->lyxvc().locker().empty());
1390 case LFUN_VC_REVERT:
1391 enable = doc_buffer && doc_buffer->lyxvc().inUse();
1393 case LFUN_VC_UNDO_LAST:
1394 enable = doc_buffer && doc_buffer->lyxvc().undoLastEnabled();
1396 case LFUN_VC_COMMAND: {
1397 if (cmd.argument().empty())
1399 if (!doc_buffer && contains(cmd.getArg(0), 'D'))
1409 flag.setEnabled(false);
1415 static FileName selectTemplateFile()
1417 FileDialog dlg(qt_("Select template file"));
1418 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1419 dlg.setButton1(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
1421 FileDialog::Result result = dlg.open(toqstr(lyxrc.template_path),
1422 QStringList(qt_("LyX Documents (*.lyx)")));
1424 if (result.first == FileDialog::Later)
1426 if (result.second.isEmpty())
1428 return FileName(fromqstr(result.second));
1432 Buffer * GuiView::loadDocument(FileName const & filename, bool tolastfiles)
1436 Buffer * newBuffer = checkAndLoadLyXFile(filename);
1439 message(_("Document not loaded."));
1444 setBuffer(newBuffer);
1446 // scroll to the position when the file was last closed
1447 if (lyxrc.use_lastfilepos) {
1448 LastFilePosSection::FilePos filepos =
1449 theSession().lastFilePos().load(filename);
1450 documentBufferView()->moveToPosition(filepos.pit, filepos.pos, 0, 0);
1454 theSession().lastFiles().add(filename);
1461 void GuiView::openDocument(string const & fname)
1463 string initpath = lyxrc.document_path;
1465 if (documentBufferView()) {
1466 string const trypath = documentBufferView()->buffer().filePath();
1467 // If directory is writeable, use this as default.
1468 if (FileName(trypath).isDirWritable())
1474 if (fname.empty()) {
1475 FileDialog dlg(qt_("Select document to open"), LFUN_FILE_OPEN);
1476 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1477 dlg.setButton2(qt_("Examples|#E#e"),
1478 toqstr(addPath(package().system_support().absFilename(), "examples")));
1480 QStringList filter(qt_("LyX Documents (*.lyx)"));
1481 filter << qt_("LyX-1.3.x Documents (*.lyx13)")
1482 << qt_("LyX-1.4.x Documents (*.lyx14)")
1483 << qt_("LyX-1.5.x Documents (*.lyx15)")
1484 << qt_("LyX-1.6.x Documents (*.lyx16)");
1485 FileDialog::Result result =
1486 dlg.open(toqstr(initpath), filter);
1488 if (result.first == FileDialog::Later)
1491 filename = fromqstr(result.second);
1493 // check selected filename
1494 if (filename.empty()) {
1495 message(_("Canceled."));
1501 // get absolute path of file and add ".lyx" to the filename if
1503 FileName const fullname =
1504 fileSearch(string(), filename, "lyx", support::may_not_exist);
1505 if (!fullname.empty())
1506 filename = fullname.absFilename();
1508 if (!fullname.onlyPath().isDirectory()) {
1509 Alert::warning(_("Invalid filename"),
1510 bformat(_("The directory in the given path\n%1$s\ndoes not exist."),
1511 from_utf8(fullname.absFilename())));
1514 // if the file doesn't exist, let the user create one
1515 if (!fullname.exists()) {
1516 // the user specifically chose this name. Believe him.
1517 Buffer * const b = newFile(filename, string(), true);
1523 docstring const disp_fn = makeDisplayPath(filename);
1524 message(bformat(_("Opening document %1$s..."), disp_fn));
1527 Buffer * buf = loadDocument(fullname);
1529 buf->updateLabels();
1531 buf->errors("Parse");
1532 str2 = bformat(_("Document %1$s opened."), disp_fn);
1533 if (buf->lyxvc().inUse())
1534 str2 += " " + from_utf8(buf->lyxvc().versionString()) +
1535 " " + _("Version control detected.");
1537 str2 = bformat(_("Could not open document %1$s"), disp_fn);
1542 // FIXME: clean that
1543 static bool import(GuiView * lv, FileName const & filename,
1544 string const & format, ErrorList & errorList)
1546 FileName const lyxfile(support::changeExtension(filename.absFilename(), ".lyx"));
1548 string loader_format;
1549 vector<string> loaders = theConverters().loaders();
1550 if (find(loaders.begin(), loaders.end(), format) == loaders.end()) {
1551 for (vector<string>::const_iterator it = loaders.begin();
1552 it != loaders.end(); ++it) {
1553 if (!theConverters().isReachable(format, *it))
1556 string const tofile =
1557 support::changeExtension(filename.absFilename(),
1558 formats.extension(*it));
1559 if (!theConverters().convert(0, filename, FileName(tofile),
1560 filename, format, *it, errorList))
1562 loader_format = *it;
1565 if (loader_format.empty()) {
1566 frontend::Alert::error(_("Couldn't import file"),
1567 bformat(_("No information for importing the format %1$s."),
1568 formats.prettyName(format)));
1572 loader_format = format;
1574 if (loader_format == "lyx") {
1575 Buffer * buf = lv->loadDocument(lyxfile);
1578 buf->updateLabels();
1580 buf->errors("Parse");
1582 Buffer * const b = newFile(lyxfile.absFilename(), string(), true);
1586 bool as_paragraphs = loader_format == "textparagraph";
1587 string filename2 = (loader_format == format) ? filename.absFilename()
1588 : support::changeExtension(filename.absFilename(),
1589 formats.extension(loader_format));
1590 lv->currentBufferView()->insertPlaintextFile(FileName(filename2),
1592 guiApp->setCurrentView(lv);
1593 lyx::dispatch(FuncRequest(LFUN_MARK_OFF));
1600 void GuiView::importDocument(string const & argument)
1603 string filename = split(argument, format, ' ');
1605 LYXERR(Debug::INFO, format << " file: " << filename);
1607 // need user interaction
1608 if (filename.empty()) {
1609 string initpath = lyxrc.document_path;
1610 if (documentBufferView()) {
1611 string const trypath = documentBufferView()->buffer().filePath();
1612 // If directory is writeable, use this as default.
1613 if (FileName(trypath).isDirWritable())
1617 docstring const text = bformat(_("Select %1$s file to import"),
1618 formats.prettyName(format));
1620 FileDialog dlg(toqstr(text), LFUN_BUFFER_IMPORT);
1621 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1622 dlg.setButton2(qt_("Examples|#E#e"),
1623 toqstr(addPath(package().system_support().absFilename(), "examples")));
1625 docstring filter = formats.prettyName(format);
1628 filter += from_utf8(formats.extension(format));
1631 FileDialog::Result result =
1632 dlg.open(toqstr(initpath), fileFilters(toqstr(filter)));
1634 if (result.first == FileDialog::Later)
1637 filename = fromqstr(result.second);
1639 // check selected filename
1640 if (filename.empty())
1641 message(_("Canceled."));
1644 if (filename.empty())
1647 // get absolute path of file
1648 FileName const fullname(support::makeAbsPath(filename));
1650 FileName const lyxfile(support::changeExtension(fullname.absFilename(), ".lyx"));
1652 // Check if the document already is open
1653 Buffer * buf = theBufferList().getBuffer(lyxfile);
1656 if (!closeBuffer()) {
1657 message(_("Canceled."));
1662 docstring const displaypath = makeDisplayPath(lyxfile.absFilename(), 30);
1664 // if the file exists already, and we didn't do
1665 // -i lyx thefile.lyx, warn
1666 if (lyxfile.exists() && fullname != lyxfile) {
1668 docstring text = bformat(_("The document %1$s already exists.\n\n"
1669 "Do you want to overwrite that document?"), displaypath);
1670 int const ret = Alert::prompt(_("Overwrite document?"),
1671 text, 0, 1, _("&Overwrite"), _("&Cancel"));
1674 message(_("Canceled."));
1679 message(bformat(_("Importing %1$s..."), displaypath));
1680 ErrorList errorList;
1681 if (import(this, fullname, format, errorList))
1682 message(_("imported."));
1684 message(_("file not imported!"));
1686 // FIXME (Abdel 12/08/06): Is there a need to display the error list here?
1690 void GuiView::newDocument(string const & filename, bool from_template)
1692 FileName initpath(lyxrc.document_path);
1693 if (documentBufferView()) {
1694 FileName const trypath(documentBufferView()->buffer().filePath());
1695 // If directory is writeable, use this as default.
1696 if (trypath.isDirWritable())
1700 string templatefile;
1701 if (from_template) {
1702 templatefile = selectTemplateFile().absFilename();
1703 if (templatefile.empty())
1708 if (filename.empty())
1709 b = newUnnamedFile(templatefile, initpath);
1711 b = newFile(filename, templatefile, true);
1716 // If no new document could be created, it is unsure
1717 // whether there is a valid BufferView.
1718 if (currentBufferView())
1719 // Ensure the cursor is correctly positioned on screen.
1720 currentBufferView()->showCursor();
1724 void GuiView::insertLyXFile(docstring const & fname)
1726 BufferView * bv = documentBufferView();
1731 FileName filename(to_utf8(fname));
1733 if (!filename.empty()) {
1734 bv->insertLyXFile(filename);
1738 // Launch a file browser
1740 string initpath = lyxrc.document_path;
1741 string const trypath = bv->buffer().filePath();
1742 // If directory is writeable, use this as default.
1743 if (FileName(trypath).isDirWritable())
1747 FileDialog dlg(qt_("Select LyX document to insert"), LFUN_FILE_INSERT);
1748 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1749 dlg.setButton2(qt_("Examples|#E#e"),
1750 toqstr(addPath(package().system_support().absFilename(),
1753 FileDialog::Result result = dlg.open(toqstr(initpath),
1754 QStringList(qt_("LyX Documents (*.lyx)")));
1756 if (result.first == FileDialog::Later)
1760 filename.set(fromqstr(result.second));
1762 // check selected filename
1763 if (filename.empty()) {
1764 // emit message signal.
1765 message(_("Canceled."));
1769 bv->insertLyXFile(filename);
1773 void GuiView::insertPlaintextFile(docstring const & fname,
1776 BufferView * bv = documentBufferView();
1780 if (!fname.empty() && !FileName::isAbsolute(to_utf8(fname))) {
1781 message(_("Absolute filename expected."));
1786 FileName filename(to_utf8(fname));
1788 if (!filename.empty()) {
1789 bv->insertPlaintextFile(filename, asParagraph);
1793 FileDialog dlg(qt_("Select file to insert"), (asParagraph ?
1794 LFUN_FILE_INSERT_PLAINTEXT_PARA : LFUN_FILE_INSERT_PLAINTEXT));
1796 FileDialog::Result result = dlg.open(toqstr(bv->buffer().filePath()),
1797 QStringList(qt_("All Files (*)")));
1799 if (result.first == FileDialog::Later)
1803 filename.set(fromqstr(result.second));
1805 // check selected filename
1806 if (filename.empty()) {
1807 // emit message signal.
1808 message(_("Canceled."));
1812 bv->insertPlaintextFile(filename, asParagraph);
1816 bool GuiView::renameBuffer(Buffer & b, docstring const & newname)
1818 FileName fname = b.fileName();
1819 FileName const oldname = fname;
1821 if (!newname.empty()) {
1823 fname = support::makeAbsPath(to_utf8(newname), oldname.onlyPath().absFilename());
1825 // Switch to this Buffer.
1828 // No argument? Ask user through dialog.
1830 FileDialog dlg(qt_("Choose a filename to save document as"),
1831 LFUN_BUFFER_WRITE_AS);
1832 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1833 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
1835 if (!isLyXFilename(fname.absFilename()))
1836 fname.changeExtension(".lyx");
1838 FileDialog::Result result =
1839 dlg.save(toqstr(fname.onlyPath().absFilename()),
1840 QStringList(qt_("LyX Documents (*.lyx)")),
1841 toqstr(fname.onlyFileName()));
1843 if (result.first == FileDialog::Later)
1846 fname.set(fromqstr(result.second));
1851 if (!isLyXFilename(fname.absFilename()))
1852 fname.changeExtension(".lyx");
1855 if (FileName(fname).exists()) {
1856 docstring const file = makeDisplayPath(fname.absFilename(), 30);
1857 docstring text = bformat(_("The document %1$s already "
1858 "exists.\n\nDo you want to "
1859 "overwrite that document?"),
1861 int const ret = Alert::prompt(_("Overwrite document?"),
1862 text, 0, 2, _("&Overwrite"), _("&Rename"), _("&Cancel"));
1865 case 1: return renameBuffer(b, docstring());
1866 case 2: return false;
1870 FileName oldauto = b.getAutosaveFilename();
1872 // Ok, change the name of the buffer
1873 b.setFileName(fname.absFilename());
1875 bool unnamed = b.isUnnamed();
1876 b.setUnnamed(false);
1877 b.saveCheckSum(fname);
1879 // bring the autosave file with us, just in case.
1880 b.moveAutosaveFile(oldauto);
1882 if (!saveBuffer(b)) {
1883 oldauto = b.getAutosaveFilename();
1884 b.setFileName(oldname.absFilename());
1885 b.setUnnamed(unnamed);
1886 b.saveCheckSum(oldname);
1887 b.moveAutosaveFile(oldauto);
1895 bool GuiView::saveBuffer(Buffer & b)
1897 if (workArea(b) && workArea(b)->inDialogMode())
1901 return renameBuffer(b, docstring());
1904 theSession().lastFiles().add(b.fileName());
1908 // Switch to this Buffer.
1911 // FIXME: we don't tell the user *WHY* the save failed !!
1912 docstring const file = makeDisplayPath(b.absFileName(), 30);
1913 docstring text = bformat(_("The document %1$s could not be saved.\n\n"
1914 "Do you want to rename the document and "
1915 "try again?"), file);
1916 int const ret = Alert::prompt(_("Rename and save?"),
1917 text, 0, 2, _("&Rename"), _("&Retry"), _("&Cancel"));
1920 if (!renameBuffer(b, docstring()))
1929 return saveBuffer(b);
1933 bool GuiView::hideWorkArea(GuiWorkArea * wa)
1935 return closeWorkArea(wa, false);
1939 bool GuiView::closeWorkArea(GuiWorkArea * wa)
1941 Buffer & buf = wa->bufferView().buffer();
1942 return closeWorkArea(wa, !buf.parent());
1946 bool GuiView::closeBuffer()
1948 GuiWorkArea * wa = currentMainWorkArea();
1949 Buffer & buf = wa->bufferView().buffer();
1950 return wa && closeWorkArea(wa, !buf.parent());
1954 void GuiView::writeSession() const {
1955 GuiWorkArea const * active_wa = currentMainWorkArea();
1956 for (int i = 0; i < d.splitter_->count(); ++i) {
1957 TabWorkArea * twa = d.tabWorkArea(i);
1958 for (int j = 0; j < twa->count(); ++j) {
1959 GuiWorkArea * wa = static_cast<GuiWorkArea *>(twa->widget(j));
1960 Buffer & buf = wa->bufferView().buffer();
1961 theSession().lastOpened().add(buf.fileName(), wa == active_wa);
1967 bool GuiView::closeBufferAll()
1969 // Close the workareas in all other views
1970 QList<int> const ids = guiApp->viewIds();
1971 for (int i = 0; i != ids.size(); ++i) {
1972 if (id_ != ids[i] && !guiApp->view(ids[i]).closeWorkAreaAll())
1976 // Close our own workareas
1977 if (!closeWorkAreaAll())
1980 // Now close the hidden buffers. We prevent hidden buffers from being
1981 // dirty, so we can just close them.
1982 theBufferList().closeAll();
1987 bool GuiView::closeWorkAreaAll()
1989 setCurrentWorkArea(currentMainWorkArea());
1991 // We might be in a situation that there is still a tabWorkArea, but
1992 // there are no tabs anymore. This can happen when we get here after a
1993 // TabWorkArea::lastWorkAreaRemoved() signal. Therefore we count how
1994 // many TabWorkArea's have no documents anymore.
1997 // We have to call count() each time, because it can happen that
1998 // more than one splitter will disappear in one iteration (bug 5998).
1999 for (; d.splitter_->count() > empty_twa; ) {
2000 TabWorkArea * twa = d.tabWorkArea(empty_twa);
2002 if (twa->count() == 0)
2005 setCurrentWorkArea(twa->currentWorkArea());
2006 if (!closeTabWorkArea(twa))
2014 bool GuiView::closeWorkArea(GuiWorkArea * wa, bool close_buffer)
2016 Buffer & buf = wa->bufferView().buffer();
2018 // If we are in a close_event all children will be closed in some time,
2019 // so no need to do it here. This will ensure that the children end up
2020 // in the session file in the correct order. If we close the master
2021 // buffer, we can close or release the child buffers here too.
2022 if (close_buffer && !closing_) {
2023 vector<Buffer *> clist = buf.getChildren();
2024 for (vector<Buffer *>::const_iterator it = clist.begin();
2025 it != clist.end(); ++it) {
2026 // If a child is dirty, do not close
2027 // without user intervention
2028 //FIXME: should we look in other tabworkareas?
2029 Buffer * child_buf = *it;
2030 GuiWorkArea * child_wa = workArea(*child_buf);
2032 if (!closeWorkArea(child_wa, true))
2035 theBufferList().releaseChild(&buf, child_buf);
2038 // goto bookmark to update bookmark pit.
2039 //FIXME: we should update only the bookmarks related to this buffer!
2040 LYXERR(Debug::DEBUG, "GuiView::closeBuffer()");
2041 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
2042 theLyXFunc().gotoBookmark(i+1, false, false);
2044 // if we are only hiding the buffer and there are multiple views
2045 // of the buffer, then we do not need to ensure a clean buffer.
2046 bool const allow_dirty = inMultiTabs(wa) && !close_buffer;
2048 if (allow_dirty || saveBufferIfNeeded(buf, !close_buffer)) {
2049 // save in sessions if requested
2050 // do not save childs if their master
2051 // is opened as well
2055 theBufferList().release(&buf);
2062 bool GuiView::closeTabWorkArea(TabWorkArea * twa)
2064 while (twa == d.currentTabWorkArea()) {
2065 twa->setCurrentIndex(twa->count()-1);
2067 GuiWorkArea * wa = twa->currentWorkArea();
2068 Buffer & b = wa->bufferView().buffer();
2070 // We only want to close the buffer if the same buffer is not visible
2071 // in another view, and if this is not a child and if we are closing
2072 // a view (not a tabgroup).
2073 bool const close_buffer =
2074 !inMultiViews(wa) && !b.parent() && closing_;
2076 if (!closeWorkArea(wa, close_buffer))
2083 bool GuiView::saveBufferIfNeeded(Buffer & buf, bool hiding)
2085 if (buf.isClean() || buf.paragraphs().empty())
2088 // Switch to this Buffer.
2093 if (buf.isUnnamed())
2094 file = from_utf8(buf.fileName().onlyFileName());
2096 file = buf.fileName().displayName(30);
2098 // Bring this window to top before asking questions.
2103 if (hiding && buf.isUnnamed()) {
2104 docstring const text = bformat(_("The document %1$s has not been "
2105 "saved yet.\n\nDo you want to save "
2106 "the document?"), file);
2107 ret = Alert::prompt(_("Save new document?"),
2108 text, 0, 1, _("&Save"), _("&Cancel"));
2112 docstring const text = bformat(_("The document %1$s has unsaved changes."
2113 "\n\nDo you want to save the document or discard the changes?"), file);
2114 ret = Alert::prompt(_("Save changed document?"),
2115 text, 0, 2, _("&Save"), _("&Discard"), _("&Cancel"));
2120 if (!saveBuffer(buf))
2124 // if we crash after this we could
2125 // have no autosave file but I guess
2126 // this is really improbable (Jug)
2127 buf.removeAutosaveFile();
2129 // revert all changes
2130 buf.loadLyXFile(buf.fileName());
2140 bool GuiView::inMultiTabs(GuiWorkArea * wa)
2142 Buffer & buf = wa->bufferView().buffer();
2144 for (int i = 0; i != d.splitter_->count(); ++i) {
2145 GuiWorkArea * wa_ = d.tabWorkArea(i)->workArea(buf);
2146 if (wa_ && wa_ != wa)
2149 return inMultiViews(wa);
2153 bool GuiView::inMultiViews(GuiWorkArea * wa)
2155 QList<int> const ids = guiApp->viewIds();
2156 Buffer & buf = wa->bufferView().buffer();
2159 for (int i = 0; i != ids.size() && found_twa <= 1; ++i) {
2163 if (guiApp->view(ids[i]).workArea(buf))
2170 void GuiView::gotoNextOrPreviousBuffer(NextOrPrevious np)
2172 Buffer * const curbuf = documentBufferView()
2173 ? &documentBufferView()->buffer() : 0;
2174 Buffer * nextbuf = curbuf;
2176 if (np == NEXTBUFFER)
2177 nextbuf = theBufferList().next(nextbuf);
2179 nextbuf = theBufferList().previous(nextbuf);
2180 if (nextbuf == curbuf)
2186 if (workArea(*nextbuf))
2193 /// make sure the document is saved
2194 static bool ensureBufferClean(Buffer * buffer)
2196 LASSERT(buffer, return false);
2197 if (buffer->isClean() && !buffer->isUnnamed())
2200 docstring const file = buffer->fileName().displayName(30);
2203 if (!buffer->isUnnamed()) {
2204 text = bformat(_("The document %1$s has unsaved "
2205 "changes.\n\nDo you want to save "
2206 "the document?"), file);
2207 title = _("Save changed document?");
2210 text = bformat(_("The document %1$s has not been "
2211 "saved yet.\n\nDo you want to save "
2212 "the document?"), file);
2213 title = _("Save new document?");
2215 int const ret = Alert::prompt(title, text, 0, 1, _("&Save"), _("&Cancel"));
2218 dispatch(FuncRequest(LFUN_BUFFER_WRITE));
2220 return buffer->isClean() && !buffer->isUnnamed();
2224 void GuiView::reloadBuffer()
2226 Buffer * buf = &documentBufferView()->buffer();
2227 FileName filename = buf->fileName();
2228 // The user has already confirmed that the changes, if any, should
2229 // be discarded. So we just release the Buffer and don't call closeBuffer();
2230 theBufferList().release(buf);
2231 buf = loadDocument(filename);
2232 docstring const disp_fn = makeDisplayPath(filename.absFilename());
2235 buf->updateLabels();
2237 buf->errors("Parse");
2238 str = bformat(_("Document %1$s reloaded."), disp_fn);
2240 str = bformat(_("Could not reload document %1$s"), disp_fn);
2246 void GuiView::dispatchVC(FuncRequest const & cmd)
2248 Buffer * buffer = documentBufferView()
2249 ? &(documentBufferView()->buffer()) : 0;
2251 switch (cmd.action) {
2252 case LFUN_VC_REGISTER:
2253 if (!buffer || !ensureBufferClean(buffer))
2255 if (!buffer->lyxvc().inUse()) {
2256 if (buffer->lyxvc().registrer())
2261 case LFUN_VC_CHECK_IN:
2262 if (!buffer || !ensureBufferClean(buffer))
2264 if (buffer->lyxvc().inUse() && !buffer->isReadonly()) {
2265 message(from_utf8(buffer->lyxvc().checkIn()));
2270 case LFUN_VC_CHECK_OUT:
2271 if (!buffer || !ensureBufferClean(buffer))
2273 if (buffer->lyxvc().inUse()) {
2274 message(from_utf8(buffer->lyxvc().checkOut()));
2279 case LFUN_VC_LOCKING_TOGGLE:
2280 LASSERT(buffer, return);
2281 if (!ensureBufferClean(buffer) || buffer->isReadonly())
2283 if (buffer->lyxvc().inUse()) {
2284 string res = buffer->lyxvc().lockingToggle();
2286 frontend::Alert::error(_("Revision control error."),
2287 _("Error when setting the locking property."));
2289 message(from_utf8(res));
2295 case LFUN_VC_REVERT:
2296 LASSERT(buffer, return);
2297 buffer->lyxvc().revert();
2301 case LFUN_VC_UNDO_LAST:
2302 LASSERT(buffer, return);
2303 buffer->lyxvc().undoLast();
2307 case LFUN_VC_COMMAND: {
2308 string flag = cmd.getArg(0);
2309 if (buffer && contains(flag, 'R') && !ensureBufferClean(buffer))
2312 if (contains(flag, 'M')) {
2313 if (!Alert::askForText(message, _("LyX VC: Log Message")))
2316 string path = cmd.getArg(1);
2317 if (contains(path, "$$p") && buffer)
2318 path = subst(path, "$$p", buffer->filePath());
2319 LYXERR(Debug::LYXVC, "Directory: " << path);
2321 if (!pp.isReadableDirectory()) {
2322 lyxerr << _("Directory is not accessible.") << endl;
2325 support::PathChanger p(pp);
2327 string command = cmd.getArg(2);
2328 if (command.empty())
2331 command = subst(command, "$$i", buffer->absFileName());
2332 command = subst(command, "$$p", buffer->filePath());
2334 command = subst(command, "$$m", to_utf8(message));
2335 LYXERR(Debug::LYXVC, "Command: " << command);
2337 one.startscript(Systemcall::Wait, command);
2341 if (contains(flag, 'I'))
2342 buffer->markDirty();
2343 if (contains(flag, 'R'))
2354 void GuiView::openChildDocument(string const & fname)
2356 LASSERT(documentBufferView(), return);
2357 Buffer & buffer = documentBufferView()->buffer();
2358 FileName const filename = support::makeAbsPath(fname, buffer.filePath());
2359 documentBufferView()->saveBookmark(false);
2361 bool parsed = false;
2362 if (theBufferList().exists(filename)) {
2363 child = theBufferList().getBuffer(filename);
2365 message(bformat(_("Opening child document %1$s..."),
2366 makeDisplayPath(filename.absFilename())));
2367 child = loadDocument(filename, false);
2373 // Set the parent name of the child document.
2374 // This makes insertion of citations and references in the child work,
2375 // when the target is in the parent or another child document.
2376 child->setParent(&buffer);
2377 child->masterBuffer()->updateLabels();
2380 child->errors("Parse");
2384 bool GuiView::dispatch(FuncRequest const & cmd)
2386 BufferView * bv = currentBufferView();
2387 // By default we won't need any update.
2389 bv->cursor().updateFlags(Update::None);
2391 Buffer * doc_buffer = documentBufferView()
2392 ? &(documentBufferView()->buffer()) : 0;
2394 bool dispatched = true;
2396 if (cmd.origin == FuncRequest::TOC) {
2397 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
2398 toc->doDispatch(bv->cursor(), cmd);
2402 switch(cmd.action) {
2403 case LFUN_BUFFER_CHILD_OPEN:
2404 openChildDocument(to_utf8(cmd.argument()));
2407 case LFUN_BUFFER_IMPORT:
2408 importDocument(to_utf8(cmd.argument()));
2411 case LFUN_BUFFER_SWITCH:
2412 if (FileName::isAbsolute(to_utf8(cmd.argument()))) {
2414 theBufferList().getBuffer(FileName(to_utf8(cmd.argument())));
2418 bv->cursor().message(_("Document not loaded"));
2422 case LFUN_BUFFER_NEXT:
2423 gotoNextOrPreviousBuffer(NEXTBUFFER);
2426 case LFUN_BUFFER_PREVIOUS:
2427 gotoNextOrPreviousBuffer(PREVBUFFER);
2430 case LFUN_COMMAND_EXECUTE: {
2431 bool const show_it = cmd.argument() != "off";
2432 // FIXME: this is a hack, "minibuffer" should not be
2434 if (GuiToolbar * t = toolbar("minibuffer")) {
2435 t->setVisible(show_it);
2436 if (show_it && t->commandBuffer())
2437 t->commandBuffer()->setFocus();
2441 case LFUN_DROP_LAYOUTS_CHOICE:
2442 d.layout_->showPopup();
2445 case LFUN_MENU_OPEN:
2446 if (QMenu * menu = guiApp->menus().menu(toqstr(cmd.argument()), *this))
2447 menu->exec(QCursor::pos());
2450 case LFUN_FILE_INSERT:
2451 insertLyXFile(cmd.argument());
2453 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
2454 insertPlaintextFile(cmd.argument(), true);
2457 case LFUN_FILE_INSERT_PLAINTEXT:
2458 insertPlaintextFile(cmd.argument(), false);
2461 case LFUN_BUFFER_RELOAD: {
2462 LASSERT(doc_buffer, break);
2463 docstring const file = makeDisplayPath(doc_buffer->absFileName(), 20);
2464 docstring text = bformat(_("Any changes will be lost. Are you sure "
2465 "you want to revert to the saved version of the document %1$s?"), file);
2466 int const ret = Alert::prompt(_("Revert to saved document?"),
2467 text, 1, 1, _("&Revert"), _("&Cancel"));
2474 case LFUN_BUFFER_WRITE:
2475 LASSERT(doc_buffer, break);
2476 saveBuffer(*doc_buffer);
2479 case LFUN_BUFFER_WRITE_AS:
2480 LASSERT(doc_buffer, break);
2481 renameBuffer(*doc_buffer, cmd.argument());
2484 case LFUN_BUFFER_WRITE_ALL: {
2485 Buffer * first = theBufferList().first();
2488 message(_("Saving all documents..."));
2489 // We cannot use a for loop as the buffer list cycles.
2492 if (!b->isClean()) {
2494 LYXERR(Debug::ACTION, "Saved " << b->absFileName());
2496 b = theBufferList().next(b);
2497 } while (b != first);
2498 message(_("All documents saved."));
2502 case LFUN_BUFFER_CLOSE:
2506 case LFUN_BUFFER_CLOSE_ALL:
2510 case LFUN_TOOLBAR_TOGGLE: {
2511 string const name = cmd.getArg(0);
2512 if (GuiToolbar * t = toolbar(name))
2517 case LFUN_DIALOG_UPDATE: {
2518 string const name = to_utf8(cmd.argument());
2519 // Can only update a dialog connected to an existing inset
2520 Inset * inset = getOpenInset(name);
2522 FuncRequest fr(LFUN_INSET_DIALOG_UPDATE, cmd.argument());
2523 inset->dispatch(currentBufferView()->cursor(), fr);
2524 } else if (name == "paragraph") {
2525 lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
2526 } else if (name == "prefs" || name == "document") {
2527 updateDialog(name, string());
2532 case LFUN_DIALOG_TOGGLE: {
2533 if (isDialogVisible(cmd.getArg(0)))
2534 dispatch(FuncRequest(LFUN_DIALOG_HIDE, cmd.argument()));
2536 dispatch(FuncRequest(LFUN_DIALOG_SHOW, cmd.argument()));
2540 case LFUN_DIALOG_DISCONNECT_INSET:
2541 disconnectDialog(to_utf8(cmd.argument()));
2544 case LFUN_DIALOG_HIDE: {
2545 guiApp->hideDialogs(to_utf8(cmd.argument()), 0);
2549 case LFUN_DIALOG_SHOW: {
2550 string const name = cmd.getArg(0);
2551 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
2553 if (name == "character") {
2554 data = freefont2string();
2556 showDialog("character", data);
2557 } else if (name == "latexlog") {
2558 Buffer::LogType type;
2559 string const logfile = doc_buffer->logName(&type);
2561 case Buffer::latexlog:
2564 case Buffer::buildlog:
2568 data += Lexer::quoteString(logfile);
2569 showDialog("log", data);
2570 } else if (name == "vclog") {
2571 string const data = "vc " +
2572 Lexer::quoteString(doc_buffer->lyxvc().getLogFile());
2573 showDialog("log", data);
2574 } else if (name == "symbols") {
2575 data = bv->cursor().getEncoding()->name();
2577 showDialog("symbols", data);
2579 } else if (name == "prefs" && isFullScreen()) {
2580 FuncRequest fr(LFUN_INSET_INSERT, "fullscreen");
2582 showDialog("prefs", data);
2584 showDialog(name, data);
2589 message(cmd.argument());
2592 case LFUN_INSET_APPLY: {
2593 string const name = cmd.getArg(0);
2594 Inset * inset = getOpenInset(name);
2596 // put cursor in front of inset.
2597 if (!currentBufferView()->setCursorFromInset(inset)) {
2598 LASSERT(false, break);
2600 BufferView * bv = currentBufferView();
2601 // useful if we are called from a dialog.
2602 bv->cursor().beginUndoGroup();
2603 bv->cursor().recordUndo();
2604 FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument());
2605 inset->dispatch(bv->cursor(), fr);
2606 bv->cursor().endUndoGroup();
2608 FuncRequest fr(LFUN_INSET_INSERT, cmd.argument());
2614 case LFUN_UI_TOGGLE:
2616 // Make sure the keyboard focus stays in the work area.
2620 case LFUN_SPLIT_VIEW: {
2621 LASSERT(doc_buffer, break);
2622 string const orientation = cmd.getArg(0);
2623 d.splitter_->setOrientation(orientation == "vertical"
2624 ? Qt::Vertical : Qt::Horizontal);
2625 TabWorkArea * twa = addTabWorkArea();
2626 GuiWorkArea * wa = twa->addWorkArea(*doc_buffer, *this);
2627 setCurrentWorkArea(wa);
2630 case LFUN_CLOSE_TAB_GROUP:
2631 if (TabWorkArea * twa = d.currentTabWorkArea()) {
2632 closeTabWorkArea(twa);
2633 d.current_work_area_ = 0;
2634 twa = d.currentTabWorkArea();
2635 // Switch to the next GuiWorkArea in the found TabWorkArea.
2637 // Make sure the work area is up to date.
2638 setCurrentWorkArea(twa->currentWorkArea());
2640 setCurrentWorkArea(0);
2645 case LFUN_COMPLETION_INLINE:
2646 if (d.current_work_area_)
2647 d.current_work_area_->completer().showInline();
2650 case LFUN_COMPLETION_POPUP:
2651 if (d.current_work_area_)
2652 d.current_work_area_->completer().showPopup();
2656 case LFUN_COMPLETION_COMPLETE:
2657 if (d.current_work_area_)
2658 d.current_work_area_->completer().tab();
2661 case LFUN_COMPLETION_CANCEL:
2662 if (d.current_work_area_) {
2663 if (d.current_work_area_->completer().popupVisible())
2664 d.current_work_area_->completer().hidePopup();
2666 d.current_work_area_->completer().hideInline();
2670 case LFUN_COMPLETION_ACCEPT:
2671 if (d.current_work_area_)
2672 d.current_work_area_->completer().activate();
2675 case LFUN_BUFFER_ZOOM_IN:
2676 case LFUN_BUFFER_ZOOM_OUT:
2677 if (cmd.argument().empty()) {
2678 if (cmd.action == LFUN_BUFFER_ZOOM_IN)
2683 lyxrc.zoom += convert<int>(cmd.argument());
2685 if (lyxrc.zoom < 10)
2688 // The global QPixmapCache is used in GuiPainter to cache text
2689 // painting so we must reset it.
2690 QPixmapCache::clear();
2691 guiApp->fontLoader().update();
2692 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
2695 case LFUN_VC_REGISTER:
2696 case LFUN_VC_CHECK_IN:
2697 case LFUN_VC_CHECK_OUT:
2698 case LFUN_VC_LOCKING_TOGGLE:
2699 case LFUN_VC_REVERT:
2700 case LFUN_VC_UNDO_LAST:
2701 case LFUN_VC_COMMAND:
2710 // Part of automatic menu appearance feature.
2711 if (isFullScreen()) {
2712 if (menuBar()->isVisible() && lyxrc.full_screen_menubar)
2714 if (statusBar()->isVisible())
2715 statusBar()->hide();
2722 void GuiView::lfunUiToggle(FuncRequest const & cmd)
2724 string const arg = cmd.getArg(0);
2725 if (arg == "scrollbar") {
2726 // hide() is of no help
2727 if (d.current_work_area_->verticalScrollBarPolicy() ==
2728 Qt::ScrollBarAlwaysOff)
2730 d.current_work_area_->setVerticalScrollBarPolicy(
2731 Qt::ScrollBarAsNeeded);
2733 d.current_work_area_->setVerticalScrollBarPolicy(
2734 Qt::ScrollBarAlwaysOff);
2737 if (arg == "statusbar") {
2738 statusBar()->setVisible(!statusBar()->isVisible());
2741 if (arg == "menubar") {
2742 menuBar()->setVisible(!menuBar()->isVisible());
2745 #if QT_VERSION >= 0x040300
2746 if (arg == "frame") {
2748 getContentsMargins(&l, &t, &r, &b);
2749 //are the frames in default state?
2750 d.current_work_area_->setFrameStyle(QFrame::NoFrame);
2752 setContentsMargins(-2, -2, -2, -2);
2754 setContentsMargins(0, 0, 0, 0);
2759 if (arg == "fullscreen") {
2764 message(bformat("LFUN_UI_TOGGLE " + _("%1$s unknown command!"), from_utf8(arg)));
2768 void GuiView::toggleFullScreen()
2770 if (isFullScreen()) {
2771 for (int i = 0; i != d.splitter_->count(); ++i)
2772 d.tabWorkArea(i)->setFullScreen(false);
2773 #if QT_VERSION >= 0x040300
2774 setContentsMargins(0, 0, 0, 0);
2776 setWindowState(windowState() ^ Qt::WindowFullScreen);
2779 statusBar()->show();
2782 hideDialogs("prefs", 0);
2783 for (int i = 0; i != d.splitter_->count(); ++i)
2784 d.tabWorkArea(i)->setFullScreen(true);
2785 #if QT_VERSION >= 0x040300
2786 setContentsMargins(-2, -2, -2, -2);
2789 setWindowState(windowState() ^ Qt::WindowFullScreen);
2790 statusBar()->hide();
2791 if (lyxrc.full_screen_menubar)
2793 if (lyxrc.full_screen_toolbars) {
2794 ToolbarMap::iterator end = d.toolbars_.end();
2795 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
2800 // give dialogs like the TOC a chance to adapt
2805 Buffer const * GuiView::updateInset(Inset const * inset)
2807 if (!d.current_work_area_)
2811 d.current_work_area_->scheduleRedraw();
2813 return &d.current_work_area_->bufferView().buffer();
2817 void GuiView::restartCursor()
2819 /* When we move around, or type, it's nice to be able to see
2820 * the cursor immediately after the keypress.
2822 if (d.current_work_area_)
2823 d.current_work_area_->startBlinkingCursor();
2825 // Take this occasion to update the other GUI elements.
2831 void GuiView::updateCompletion(Cursor & cur, bool start, bool keep)
2833 if (d.current_work_area_)
2834 d.current_work_area_->completer().updateVisibility(cur, start, keep);
2839 // This list should be kept in sync with the list of insets in
2840 // src/insets/Inset.cpp. I.e., if a dialog goes with an inset, the
2841 // dialog should have the same name as the inset.
2842 // Changes should be also recorded in LFUN_DIALOG_SHOW doxygen
2843 // docs in LyXAction.cpp.
2845 char const * const dialognames[] = {
2846 "aboutlyx", "bibitem", "bibtex", "box", "branch", "changes", "character",
2847 "citation", "document", "errorlist", "ert", "external", "file", "findreplace",
2848 "findreplaceadv", "float", "graphics", "href", "include", "index",
2849 "index_print", "info", "listings", "label", "log", "mathdelimiter",
2850 "mathmatrix", "mathspace", "nomenclature", "nomencl_print", "note",
2851 "paragraph", "phantom", "prefs", "print", "ref", "sendto", "space",
2852 "spellchecker", "symbols", "tabular", "tabularcreate", "thesaurus", "texinfo",
2853 "toc", "view-source", "vspace", "wrap" };
2855 char const * const * const end_dialognames =
2856 dialognames + (sizeof(dialognames) / sizeof(char *));
2860 cmpCStr(char const * name) : name_(name) {}
2861 bool operator()(char const * other) {
2862 return strcmp(other, name_) == 0;
2869 bool isValidName(string const & name)
2871 return find_if(dialognames, end_dialognames,
2872 cmpCStr(name.c_str())) != end_dialognames;
2878 void GuiView::resetDialogs()
2880 // Make sure that no LFUN uses any LyXView.
2881 guiApp->setCurrentView(0);
2884 constructToolbars();
2885 guiApp->menus().fillMenuBar(menuBar(), this, false);
2886 d.layout_->updateContents(true);
2887 // Now update controls with current buffer.
2888 guiApp->setCurrentView(this);
2894 Dialog * GuiView::findOrBuild(string const & name, bool hide_it)
2896 if (!isValidName(name))
2899 map<string, DialogPtr>::iterator it = d.dialogs_.find(name);
2901 if (it != d.dialogs_.end()) {
2903 it->second->hideView();
2904 return it->second.get();
2907 Dialog * dialog = build(name);
2908 d.dialogs_[name].reset(dialog);
2909 if (lyxrc.allow_geometry_session)
2910 dialog->restoreSession();
2917 void GuiView::showDialog(string const & name, string const & data,
2925 Dialog * dialog = findOrBuild(name, false);
2927 dialog->showData(data);
2929 d.open_insets_[name] = inset;
2932 catch (ExceptionMessage const & ex) {
2940 bool GuiView::isDialogVisible(string const & name) const
2942 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
2943 if (it == d.dialogs_.end())
2945 return it->second.get()->isVisibleView() && !it->second.get()->isClosing();
2949 void GuiView::hideDialog(string const & name, Inset * inset)
2951 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
2952 if (it == d.dialogs_.end())
2955 if (inset && inset != getOpenInset(name))
2958 Dialog * const dialog = it->second.get();
2959 if (dialog->isVisibleView())
2961 d.open_insets_[name] = 0;
2965 void GuiView::disconnectDialog(string const & name)
2967 if (!isValidName(name))
2970 if (d.open_insets_.find(name) != d.open_insets_.end())
2971 d.open_insets_[name] = 0;
2975 Inset * GuiView::getOpenInset(string const & name) const
2977 if (!isValidName(name))
2980 map<string, Inset *>::const_iterator it = d.open_insets_.find(name);
2981 return it == d.open_insets_.end() ? 0 : it->second;
2985 void GuiView::hideAll() const
2987 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
2988 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
2990 for(; it != end; ++it)
2991 it->second->hideView();
2995 void GuiView::updateDialogs()
2997 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
2998 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3000 for(; it != end; ++it) {
3001 Dialog * dialog = it->second.get();
3002 if (dialog && dialog->isVisibleView())
3003 dialog->checkStatus();
3010 // will be replaced by a proper factory...
3011 Dialog * createGuiAbout(GuiView & lv);
3012 Dialog * createGuiBibitem(GuiView & lv);
3013 Dialog * createGuiBibtex(GuiView & lv);
3014 Dialog * createGuiBox(GuiView & lv);
3015 Dialog * createGuiBranch(GuiView & lv);
3016 Dialog * createGuiChanges(GuiView & lv);
3017 Dialog * createGuiCharacter(GuiView & lv);
3018 Dialog * createGuiCitation(GuiView & lv);
3019 Dialog * createGuiDelimiter(GuiView & lv);
3020 Dialog * createGuiDocument(GuiView & lv);
3021 Dialog * createGuiErrorList(GuiView & lv);
3022 Dialog * createGuiERT(GuiView & lv);
3023 Dialog * createGuiExternal(GuiView & lv);
3024 Dialog * createGuiFloat(GuiView & lv);
3025 Dialog * createGuiGraphics(GuiView & lv);
3026 Dialog * createGuiInclude(GuiView & lv);
3027 Dialog * createGuiIndex(GuiView & lv);
3028 Dialog * createGuiInfo(GuiView & lv);
3029 Dialog * createGuiLabel(GuiView & lv);
3030 Dialog * createGuiListings(GuiView & lv);
3031 Dialog * createGuiLog(GuiView & lv);
3032 Dialog * createGuiMathHSpace(GuiView & lv);
3033 Dialog * createGuiMathMatrix(GuiView & lv);
3034 Dialog * createGuiNomenclature(GuiView & lv);
3035 Dialog * createGuiNote(GuiView & lv);
3036 Dialog * createGuiParagraph(GuiView & lv);
3037 Dialog * createGuiPhantom(GuiView & lv);
3038 Dialog * createGuiPreferences(GuiView & lv);
3039 Dialog * createGuiPrint(GuiView & lv);
3040 Dialog * createGuiPrintindex(GuiView & lv);
3041 Dialog * createGuiPrintNomencl(GuiView & lv);
3042 Dialog * createGuiRef(GuiView & lv);
3043 Dialog * createGuiSearch(GuiView & lv);
3044 Dialog * createGuiSearchAdv(GuiView & lv);
3045 Dialog * createGuiSendTo(GuiView & lv);
3046 Dialog * createGuiShowFile(GuiView & lv);
3047 Dialog * createGuiSpellchecker(GuiView & lv);
3048 Dialog * createGuiSymbols(GuiView & lv);
3049 Dialog * createGuiTabularCreate(GuiView & lv);
3050 Dialog * createGuiTabular(GuiView & lv);
3051 Dialog * createGuiTexInfo(GuiView & lv);
3052 Dialog * createGuiTextHSpace(GuiView & lv);
3053 Dialog * createGuiToc(GuiView & lv);
3054 Dialog * createGuiThesaurus(GuiView & lv);
3055 Dialog * createGuiHyperlink(GuiView & lv);
3056 Dialog * createGuiVSpace(GuiView & lv);
3057 Dialog * createGuiViewSource(GuiView & lv);
3058 Dialog * createGuiWrap(GuiView & lv);
3061 Dialog * GuiView::build(string const & name)
3063 LASSERT(isValidName(name), return 0);
3065 if (name == "aboutlyx")
3066 return createGuiAbout(*this);
3067 if (name == "bibitem")
3068 return createGuiBibitem(*this);
3069 if (name == "bibtex")
3070 return createGuiBibtex(*this);
3072 return createGuiBox(*this);
3073 if (name == "branch")
3074 return createGuiBranch(*this);
3075 if (name == "changes")
3076 return createGuiChanges(*this);
3077 if (name == "character")
3078 return createGuiCharacter(*this);
3079 if (name == "citation")
3080 return createGuiCitation(*this);
3081 if (name == "document")
3082 return createGuiDocument(*this);
3083 if (name == "errorlist")
3084 return createGuiErrorList(*this);
3086 return createGuiERT(*this);
3087 if (name == "external")
3088 return createGuiExternal(*this);
3090 return createGuiShowFile(*this);
3091 if (name == "findreplace")
3092 return createGuiSearch(*this);
3093 if (name == "findreplaceadv")
3094 return createGuiSearchAdv(*this);
3095 if (name == "float")
3096 return createGuiFloat(*this);
3097 if (name == "graphics")
3098 return createGuiGraphics(*this);
3100 return createGuiHyperlink(*this);
3101 if (name == "include")
3102 return createGuiInclude(*this);
3103 if (name == "index")
3104 return createGuiIndex(*this);
3105 if (name == "index_print")
3106 return createGuiPrintindex(*this);
3108 return createGuiInfo(*this);
3109 if (name == "label")
3110 return createGuiLabel(*this);
3111 if (name == "listings")
3112 return createGuiListings(*this);
3114 return createGuiLog(*this);
3115 if (name == "mathdelimiter")
3116 return createGuiDelimiter(*this);
3117 if (name == "mathspace")
3118 return createGuiMathHSpace(*this);
3119 if (name == "mathmatrix")
3120 return createGuiMathMatrix(*this);
3121 if (name == "nomenclature")
3122 return createGuiNomenclature(*this);
3123 if (name == "nomencl_print")
3124 return createGuiPrintNomencl(*this);
3126 return createGuiNote(*this);
3127 if (name == "paragraph")
3128 return createGuiParagraph(*this);
3129 if (name == "phantom")
3130 return createGuiPhantom(*this);
3131 if (name == "prefs")
3132 return createGuiPreferences(*this);
3133 if (name == "print")
3134 return createGuiPrint(*this);
3136 return createGuiRef(*this);
3137 if (name == "sendto")
3138 return createGuiSendTo(*this);
3139 if (name == "space")
3140 return createGuiTextHSpace(*this);
3141 if (name == "spellchecker")
3142 return createGuiSpellchecker(*this);
3143 if (name == "symbols")
3144 return createGuiSymbols(*this);
3145 if (name == "tabular")
3146 return createGuiTabular(*this);
3147 if (name == "tabularcreate")
3148 return createGuiTabularCreate(*this);
3149 if (name == "texinfo")
3150 return createGuiTexInfo(*this);
3151 if (name == "thesaurus")
3152 return createGuiThesaurus(*this);
3154 return createGuiToc(*this);
3155 if (name == "view-source")
3156 return createGuiViewSource(*this);
3157 if (name == "vspace")
3158 return createGuiVSpace(*this);
3160 return createGuiWrap(*this);
3166 } // namespace frontend
3169 #include "moc_GuiView.cpp"