3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Lars Gullik Bjønnes
8 * \author Abdelrazak Younes
11 * Full author contact details are available in file CREDITS.
19 #include "FileDialog.h"
20 #include "FontLoader.h"
21 #include "GuiApplication.h"
22 #include "GuiCommandBuffer.h"
23 #include "GuiCompleter.h"
24 #include "GuiWorkArea.h"
25 #include "GuiKeySymbol.h"
27 #include "GuiToolbar.h"
28 #include "LayoutBox.h"
32 #include "qt_helpers.h"
34 #include "frontends/alert.h"
36 #include "buffer_funcs.h"
38 #include "BufferList.h"
39 #include "BufferParams.h"
40 #include "BufferView.h"
41 #include "Converter.h"
43 #include "CutAndPaste.h"
45 #include "ErrorList.h"
47 #include "FuncStatus.h"
48 #include "FuncRequest.h"
52 #include "LyXAction.h"
57 #include "Paragraph.h"
58 #include "SpellChecker.h"
59 #include "TextClass.h"
64 #include "support/convert.h"
65 #include "support/debug.h"
66 #include "support/ExceptionMessage.h"
67 #include "support/FileName.h"
68 #include "support/filetools.h"
69 #include "support/gettext.h"
70 #include "support/filetools.h"
71 #include "support/ForkedCalls.h"
72 #include "support/lassert.h"
73 #include "support/lstrings.h"
74 #include "support/os.h"
75 #include "support/Package.h"
76 #include "support/Path.h"
77 #include "support/Systemcall.h"
78 #include "support/Timeout.h"
81 #include <QApplication>
82 #include <QCloseEvent>
84 #include <QDesktopWidget>
85 #include <QDragEnterEvent>
92 #include <QPixmapCache>
94 #include <QPushButton>
98 #include <QStackedWidget>
103 #include <QScrollBar>
105 #include <boost/bind.hpp>
107 #ifdef HAVE_SYS_TIME_H
108 # include <sys/time.h>
115 using namespace lyx::support;
122 class BackgroundWidget : public QWidget
127 LYXERR(Debug::GUI, "show banner: " << lyxrc.show_banner);
128 /// The text to be written on top of the pixmap
129 QString const text = lyx_version ?
130 qt_("version ") + lyx_version : qt_("unknown version");
131 splash_ = getPixmap("images/", "banner", "png");
133 QPainter pain(&splash_);
134 pain.setPen(QColor(0, 0, 0));
136 // The font used to display the version info
137 font.setStyleHint(QFont::SansSerif);
138 font.setWeight(QFont::Bold);
139 font.setPointSize(int(toqstr(lyxrc.font_sizes[FONT_SIZE_LARGE]).toDouble()));
141 pain.drawText(260, 15, text);
144 void paintEvent(QPaintEvent *)
146 int x = (width() - splash_.width()) / 2;
147 int y = (height() - splash_.height()) / 2;
149 pain.drawPixmap(x, y, splash_);
157 /// Toolbar store providing access to individual toolbars by name.
158 typedef std::map<std::string, GuiToolbar *> ToolbarMap;
160 typedef boost::shared_ptr<Dialog> DialogPtr;
165 struct GuiView::GuiViewPrivate
168 : current_work_area_(0), current_main_work_area_(0),
169 layout_(0), autosave_timeout_(5000),
172 // hardcode here the platform specific icon size
173 smallIconSize = 14; // scaling problems
174 normalIconSize = 20; // ok, default
175 bigIconSize = 26; // better for some math icons
177 splitter_ = new QSplitter;
178 bg_widget_ = new BackgroundWidget;
179 stack_widget_ = new QStackedWidget;
180 stack_widget_->addWidget(bg_widget_);
181 stack_widget_->addWidget(splitter_);
189 delete stack_widget_;
192 QMenu * toolBarPopup(GuiView * parent)
194 // FIXME: translation
195 QMenu * menu = new QMenu(parent);
196 QActionGroup * iconSizeGroup = new QActionGroup(parent);
198 QAction * smallIcons = new QAction(iconSizeGroup);
199 smallIcons->setText(qt_("Small-sized icons"));
200 smallIcons->setCheckable(true);
201 QObject::connect(smallIcons, SIGNAL(triggered()),
202 parent, SLOT(smallSizedIcons()));
203 menu->addAction(smallIcons);
205 QAction * normalIcons = new QAction(iconSizeGroup);
206 normalIcons->setText(qt_("Normal-sized icons"));
207 normalIcons->setCheckable(true);
208 QObject::connect(normalIcons, SIGNAL(triggered()),
209 parent, SLOT(normalSizedIcons()));
210 menu->addAction(normalIcons);
212 QAction * bigIcons = new QAction(iconSizeGroup);
213 bigIcons->setText(qt_("Big-sized icons"));
214 bigIcons->setCheckable(true);
215 QObject::connect(bigIcons, SIGNAL(triggered()),
216 parent, SLOT(bigSizedIcons()));
217 menu->addAction(bigIcons);
219 unsigned int cur = parent->iconSize().width();
220 if ( cur == parent->d.smallIconSize)
221 smallIcons->setChecked(true);
222 else if (cur == parent->d.normalIconSize)
223 normalIcons->setChecked(true);
224 else if (cur == parent->d.bigIconSize)
225 bigIcons->setChecked(true);
232 stack_widget_->setCurrentWidget(bg_widget_);
233 bg_widget_->setUpdatesEnabled(true);
236 TabWorkArea * tabWorkArea(int i)
238 return dynamic_cast<TabWorkArea *>(splitter_->widget(i));
241 TabWorkArea * currentTabWorkArea()
243 if (splitter_->count() == 1)
244 // The first TabWorkArea is always the first one, if any.
245 return tabWorkArea(0);
247 for (int i = 0; i != splitter_->count(); ++i) {
248 TabWorkArea * twa = tabWorkArea(i);
249 if (current_main_work_area_ == twa->currentWorkArea())
253 // None has the focus so we just take the first one.
254 return tabWorkArea(0);
258 GuiWorkArea * current_work_area_;
259 GuiWorkArea * current_main_work_area_;
260 QSplitter * splitter_;
261 QStackedWidget * stack_widget_;
262 BackgroundWidget * bg_widget_;
264 ToolbarMap toolbars_;
265 /// The main layout box.
267 * \warning Don't Delete! The layout box is actually owned by
268 * whichever toolbar contains it. All the GuiView class needs is a
269 * means of accessing it.
271 * FIXME: replace that with a proper model so that we are not limited
272 * to only one dialog.
277 map<string, Inset *> open_insets_;
280 map<string, DialogPtr> dialogs_;
282 unsigned int smallIconSize;
283 unsigned int normalIconSize;
284 unsigned int bigIconSize;
286 QTimer statusbar_timer_;
287 /// auto-saving of buffers
288 Timeout autosave_timeout_;
289 /// flag against a race condition due to multiclicks, see bug #1119
293 TocModels toc_models_;
297 GuiView::GuiView(int id)
298 : d(*new GuiViewPrivate), id_(id), closing_(false)
300 // GuiToolbars *must* be initialised before the menu bar.
301 normalSizedIcons(); // at least on Mac the default is 32 otherwise, which is huge
304 // set ourself as the current view. This is needed for the menu bar
305 // filling, at least for the static special menu item on Mac. Otherwise
306 // they are greyed out.
307 guiApp->setCurrentView(this);
309 // Fill up the menu bar.
310 guiApp->menus().fillMenuBar(menuBar(), this, true);
312 setCentralWidget(d.stack_widget_);
314 // Start autosave timer
315 if (lyxrc.autosave) {
316 d.autosave_timeout_.timeout.connect(boost::bind(&GuiView::autoSave, this));
317 d.autosave_timeout_.setTimeout(lyxrc.autosave * 1000);
318 d.autosave_timeout_.start();
320 connect(&d.statusbar_timer_, SIGNAL(timeout()),
321 this, SLOT(clearMessage()));
323 // We don't want to keep the window in memory if it is closed.
324 setAttribute(Qt::WA_DeleteOnClose, true);
326 #if (!defined(Q_WS_WIN) && !defined(Q_WS_MACX))
327 // assign an icon to main form. We do not do it under Qt/Win or Qt/Mac,
328 // since the icon is provided in the application bundle.
329 setWindowIcon(getPixmap("images/", "lyx", "png"));
333 setAcceptDrops(true);
335 statusBar()->setSizeGripEnabled(true);
337 // Forbid too small unresizable window because it can happen
338 // with some window manager under X11.
339 setMinimumSize(300, 200);
341 if (lyxrc.allow_geometry_session) {
342 // Now take care of session management.
347 // no session handling, default to a sane size.
348 setGeometry(50, 50, 690, 510);
351 // clear session data if any.
353 settings.remove("views");
363 void GuiView::saveLayout() const
366 settings.beginGroup("views");
367 settings.beginGroup(QString::number(id_));
369 settings.setValue("pos", pos());
370 settings.setValue("size", size());
372 settings.setValue("geometry", saveGeometry());
374 settings.setValue("layout", saveState(0));
375 settings.setValue("icon_size", iconSize());
379 bool GuiView::restoreLayout()
382 settings.beginGroup("views");
383 settings.beginGroup(QString::number(id_));
384 QString const icon_key = "icon_size";
385 if (!settings.contains(icon_key))
388 //code below is skipped when when ~/.config/LyX is (re)created
389 setIconSize(settings.value(icon_key).toSize());
391 QPoint pos = settings.value("pos", QPoint(50, 50)).toPoint();
392 QSize size = settings.value("size", QSize(690, 510)).toSize();
396 // Work-around for bug #6034: the window ends up in an undetermined
397 // state when trying to restore a maximized window when it is
398 // already maximized.
399 if (!(windowState() & Qt::WindowMaximized))
400 if (!restoreGeometry(settings.value("geometry").toByteArray()))
401 setGeometry(50, 50, 690, 510);
403 // Make sure layout is correctly oriented.
404 setLayoutDirection(qApp->layoutDirection());
406 // Allow the toc and view-source dock widget to be restored if needed.
408 if ((dialog = findOrBuild("toc", true)))
409 // see bug 5082. At least setup title and enabled state.
410 // Visibility will be adjusted by restoreState below.
411 dialog->prepareView();
412 if ((dialog = findOrBuild("view-source", true)))
413 dialog->prepareView();
415 if (!restoreState(settings.value("layout").toByteArray(), 0))
422 GuiToolbar * GuiView::toolbar(string const & name)
424 ToolbarMap::iterator it = d.toolbars_.find(name);
425 if (it != d.toolbars_.end())
428 LYXERR(Debug::GUI, "Toolbar::display: no toolbar named " << name);
429 message(bformat(_("Unknown toolbar \"%1$s\""), from_utf8(name)));
434 void GuiView::constructToolbars()
436 ToolbarMap::iterator it = d.toolbars_.begin();
437 for (; it != d.toolbars_.end(); ++it)
441 // I don't like doing this here, but the standard toolbar
442 // destroys this object when it's destroyed itself (vfr)
443 d.layout_ = new LayoutBox(*this);
444 d.stack_widget_->addWidget(d.layout_);
445 d.layout_->move(0,0);
447 // extracts the toolbars from the backend
448 Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
449 Toolbars::Infos::iterator end = guiApp->toolbars().end();
450 for (; cit != end; ++cit)
451 d.toolbars_[cit->name] = new GuiToolbar(*cit, *this);
455 void GuiView::initToolbars()
457 // extracts the toolbars from the backend
458 Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
459 Toolbars::Infos::iterator end = guiApp->toolbars().end();
460 for (; cit != end; ++cit) {
461 GuiToolbar * tb = toolbar(cit->name);
464 int const visibility = guiApp->toolbars().defaultVisibility(cit->name);
466 tb->setVisible(false);
467 tb->setVisibility(visibility);
469 if (visibility & Toolbars::TOP) {
471 addToolBarBreak(Qt::TopToolBarArea);
472 addToolBar(Qt::TopToolBarArea, tb);
475 if (visibility & Toolbars::BOTTOM) {
476 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
477 #if (QT_VERSION >= 0x040202)
478 addToolBarBreak(Qt::BottomToolBarArea);
480 addToolBar(Qt::BottomToolBarArea, tb);
483 if (visibility & Toolbars::LEFT) {
484 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
485 #if (QT_VERSION >= 0x040202)
486 addToolBarBreak(Qt::LeftToolBarArea);
488 addToolBar(Qt::LeftToolBarArea, tb);
491 if (visibility & Toolbars::RIGHT) {
492 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
493 #if (QT_VERSION >= 0x040202)
494 addToolBarBreak(Qt::RightToolBarArea);
496 addToolBar(Qt::RightToolBarArea, tb);
499 if (visibility & Toolbars::ON)
500 tb->setVisible(true);
505 TocModels & GuiView::tocModels()
507 return d.toc_models_;
511 void GuiView::setFocus()
513 LYXERR(Debug::DEBUG, "GuiView::setFocus()" << this);
514 // Make sure LyXFunc points to the correct view.
515 guiApp->setCurrentView(this);
516 QMainWindow::setFocus();
517 if (d.current_work_area_)
518 d.current_work_area_->setFocus();
522 QMenu * GuiView::createPopupMenu()
524 return d.toolBarPopup(this);
528 void GuiView::showEvent(QShowEvent * e)
530 LYXERR(Debug::GUI, "Passed Geometry "
531 << size().height() << "x" << size().width()
532 << "+" << pos().x() << "+" << pos().y());
534 if (d.splitter_->count() == 0)
535 // No work area, switch to the background widget.
538 QMainWindow::showEvent(e);
542 /** Destroy only all tabbed WorkAreas. Destruction of other WorkAreas
543 ** is responsibility of the container (e.g., dialog)
545 void GuiView::closeEvent(QCloseEvent * close_event)
547 LYXERR(Debug::DEBUG, "GuiView::closeEvent()");
552 // it can happen that this event arrives without selecting the view,
553 // e.g. when clicking the close button on a background window.
555 if (!closeWorkAreaAll()) {
557 close_event->ignore();
561 // Make sure that nothing will use this to be closed View.
562 guiApp->unregisterView(this);
564 if (isFullScreen()) {
565 // Switch off fullscreen before closing.
570 // Make sure the timer time out will not trigger a statusbar update.
571 d.statusbar_timer_.stop();
573 // Saving fullscreen requires additional tweaks in the toolbar code.
574 // It wouldn't also work under linux natively.
575 if (lyxrc.allow_geometry_session) {
576 // Save this window geometry and layout.
578 // Then the toolbar private states.
579 ToolbarMap::iterator end = d.toolbars_.end();
580 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
581 it->second->saveSession();
582 // Now take care of all other dialogs:
583 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
584 for (; it!= d.dialogs_.end(); ++it)
585 it->second->saveSession();
588 close_event->accept();
592 void GuiView::dragEnterEvent(QDragEnterEvent * event)
594 if (event->mimeData()->hasUrls())
596 /// \todo Ask lyx-devel is this is enough:
597 /// if (event->mimeData()->hasFormat("text/plain"))
598 /// event->acceptProposedAction();
602 void GuiView::dropEvent(QDropEvent * event)
604 QList<QUrl> files = event->mimeData()->urls();
608 LYXERR(Debug::GUI, "GuiView::dropEvent: got URLs!");
609 for (int i = 0; i != files.size(); ++i) {
610 string const file = os::internal_path(fromqstr(
611 files.at(i).toLocalFile()));
613 // Asynchronously post the event. DropEvent usually come
614 // from the BufferView. But reloading a file might close
615 // the BufferView from within its own event handler.
616 guiApp->dispatchDelayed(FuncRequest(LFUN_FILE_OPEN, file));
623 void GuiView::message(docstring const & str)
625 if (ForkedProcess::iAmAChild())
628 statusBar()->showMessage(toqstr(str));
629 d.statusbar_timer_.stop();
630 d.statusbar_timer_.start(3000);
634 void GuiView::smallSizedIcons()
636 setIconSize(QSize(d.smallIconSize, d.smallIconSize));
640 void GuiView::normalSizedIcons()
642 setIconSize(QSize(d.normalIconSize, d.normalIconSize));
646 void GuiView::bigSizedIcons()
648 setIconSize(QSize(d.bigIconSize, d.bigIconSize));
652 void GuiView::clearMessage()
656 statusBar()->showMessage(toqstr(theLyXFunc().viewStatusMessage()));
657 d.statusbar_timer_.stop();
661 void GuiView::updateWindowTitle(GuiWorkArea * wa)
663 if (wa != d.current_work_area_)
665 setWindowTitle(qt_("LyX: ") + wa->windowTitle());
666 setWindowIconText(wa->windowIconText());
670 void GuiView::on_currentWorkAreaChanged(GuiWorkArea * wa)
673 disconnectBufferView();
674 connectBufferView(wa->bufferView());
675 connectBuffer(wa->bufferView().buffer());
676 d.current_work_area_ = wa;
677 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
678 this, SLOT(updateWindowTitle(GuiWorkArea *)));
679 updateWindowTitle(wa);
683 // The document settings needs to be reinitialised.
684 updateDialog("document", "");
686 // Buffer-dependent dialogs must be updated. This is done here because
687 // some dialogs require buffer()->text.
692 void GuiView::on_lastWorkAreaRemoved()
695 // We already are in a close event. Nothing more to do.
698 if (d.splitter_->count() > 1)
699 // We have a splitter so don't close anything.
702 // Reset and updates the dialogs.
703 d.toc_models_.reset(0);
704 updateDialog("document", "");
707 resetWindowTitleAndIconText();
709 if (lyxrc.open_buffers_in_tabs)
710 // Nothing more to do, the window should stay open.
713 if (guiApp->viewIds().size() > 1) {
719 // On Mac we also close the last window because the application stay
720 // resident in memory. On other platforms we don't close the last
721 // window because this would quit the application.
727 void GuiView::updateStatusBar()
729 // let the user see the explicit message
730 if (d.statusbar_timer_.isActive())
733 statusBar()->showMessage(toqstr(theLyXFunc().viewStatusMessage()));
737 bool GuiView::hasFocus() const
739 return qApp->activeWindow() == this;
743 bool GuiView::event(QEvent * e)
747 // Useful debug code:
748 //case QEvent::ActivationChange:
749 //case QEvent::WindowDeactivate:
750 //case QEvent::Paint:
751 //case QEvent::Enter:
752 //case QEvent::Leave:
753 //case QEvent::HoverEnter:
754 //case QEvent::HoverLeave:
755 //case QEvent::HoverMove:
756 //case QEvent::StatusTip:
757 //case QEvent::DragEnter:
758 //case QEvent::DragLeave:
762 case QEvent::WindowActivate: {
763 GuiView * old_view = guiApp->currentView();
764 if (this == old_view) {
766 return QMainWindow::event(e);
768 if (old_view && old_view->currentBufferView()) {
769 // save current selection to the selection buffer to allow
770 // middle-button paste in this window.
771 cap::saveSelection(old_view->currentBufferView()->cursor());
773 guiApp->setCurrentView(this);
774 if (d.current_work_area_) {
775 BufferView & bv = d.current_work_area_->bufferView();
776 connectBufferView(bv);
777 connectBuffer(bv.buffer());
778 // The document structure, name and dialogs might have
779 // changed in another view.
781 // The document settings needs to be reinitialised.
782 updateDialog("document", "");
785 resetWindowTitleAndIconText();
788 return QMainWindow::event(e);
791 case QEvent::ShortcutOverride: {
794 #if (!defined Q_WS_X11) || (QT_VERSION >= 0x040500)
795 if (isFullScreen() && menuBar()->isHidden()) {
796 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
797 // FIXME: we should also try to detect special LyX shortcut such as
798 // Alt-P and Alt-M. Right now there is a hack in
799 // GuiWorkArea::processKeySym() that hides again the menubar for
801 if (ke->modifiers() & Qt::AltModifier && ke->key() != Qt::Key_Alt) {
803 return QMainWindow::event(e);
808 if (d.current_work_area_)
809 // Nothing special to do.
810 return QMainWindow::event(e);
812 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
813 // Let Qt handle menu access and the Tab keys to navigate keys to navigate
815 if (ke->modifiers() & Qt::AltModifier || ke->key() == Qt::Key_Tab
816 || ke->key() == Qt::Key_Backtab)
817 return QMainWindow::event(e);
819 // Allow processing of shortcuts that are allowed even when no Buffer
822 setKeySymbol(&sym, ke);
823 theLyXFunc().processKeySym(sym, q_key_state(ke->modifiers()));
829 return QMainWindow::event(e);
833 void GuiView::resetWindowTitleAndIconText()
835 setWindowTitle(qt_("LyX"));
836 setWindowIconText(qt_("LyX"));
839 bool GuiView::focusNextPrevChild(bool /*next*/)
846 void GuiView::setBusy(bool busy)
848 if (d.current_work_area_) {
849 d.current_work_area_->setUpdatesEnabled(!busy);
851 d.current_work_area_->stopBlinkingCursor();
853 d.current_work_area_->startBlinkingCursor();
857 QApplication::setOverrideCursor(Qt::WaitCursor);
859 QApplication::restoreOverrideCursor();
863 GuiWorkArea * GuiView::workArea(Buffer & buffer)
865 if (currentWorkArea()
866 && ¤tWorkArea()->bufferView().buffer() == &buffer)
867 return (GuiWorkArea *) currentWorkArea();
868 if (TabWorkArea * twa = d.currentTabWorkArea())
869 return twa->workArea(buffer);
874 GuiWorkArea * GuiView::addWorkArea(Buffer & buffer)
876 // Automatically create a TabWorkArea if there are none yet.
877 TabWorkArea * tab_widget = d.splitter_->count()
878 ? d.currentTabWorkArea() : addTabWorkArea();
879 return tab_widget->addWorkArea(buffer, *this);
883 TabWorkArea * GuiView::addTabWorkArea()
885 TabWorkArea * twa = new TabWorkArea;
886 QObject::connect(twa, SIGNAL(currentWorkAreaChanged(GuiWorkArea *)),
887 this, SLOT(on_currentWorkAreaChanged(GuiWorkArea *)));
888 QObject::connect(twa, SIGNAL(lastWorkAreaRemoved()),
889 this, SLOT(on_lastWorkAreaRemoved()));
891 d.splitter_->addWidget(twa);
892 d.stack_widget_->setCurrentWidget(d.splitter_);
897 GuiWorkArea const * GuiView::currentWorkArea() const
899 return d.current_work_area_;
903 GuiWorkArea * GuiView::currentWorkArea()
905 return d.current_work_area_;
909 GuiWorkArea const * GuiView::currentMainWorkArea() const
911 if (d.currentTabWorkArea() == NULL)
913 return d.currentTabWorkArea()->currentWorkArea();
917 GuiWorkArea * GuiView::currentMainWorkArea()
919 if (d.currentTabWorkArea() == NULL)
921 return d.currentTabWorkArea()->currentWorkArea();
925 void GuiView::setCurrentWorkArea(GuiWorkArea * wa)
927 LYXERR(Debug::DEBUG, "Setting current wa: " << wa << endl);
929 d.current_work_area_ = NULL;
933 GuiWorkArea * old_gwa = theGuiApp()->currentView()->currentWorkArea();
937 if (currentBufferView())
938 cap::saveSelection(currentBufferView()->cursor());
940 theGuiApp()->setCurrentView(this);
941 d.current_work_area_ = wa;
942 for (int i = 0; i != d.splitter_->count(); ++i) {
943 if (d.tabWorkArea(i)->setCurrentWorkArea(wa)) {
944 //if (d.current_main_work_area_)
945 // d.current_main_work_area_->setFrameStyle(QFrame::NoFrame);
946 d.current_main_work_area_ = wa;
947 //d.current_main_work_area_->setFrameStyle(QFrame::Box | QFrame::Plain);
948 //d.current_main_work_area_->setLineWidth(2);
949 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() << ", Current main wa: " << currentMainWorkArea());
953 LYXERR(Debug::DEBUG, "This is not a tabbed wa");
954 on_currentWorkAreaChanged(wa);
955 BufferView & bv = wa->bufferView();
956 bv.cursor().fixIfBroken();
958 wa->setUpdatesEnabled(true);
959 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() << ", Current main wa: " << currentMainWorkArea());
963 void GuiView::removeWorkArea(GuiWorkArea * wa)
966 if (wa == d.current_work_area_) {
968 disconnectBufferView();
969 d.current_work_area_ = 0;
970 d.current_main_work_area_ = 0;
973 bool found_twa = false;
974 for (int i = 0; i != d.splitter_->count(); ++i) {
975 TabWorkArea * twa = d.tabWorkArea(i);
976 if (twa->removeWorkArea(wa)) {
977 // Found in this tab group, and deleted the GuiWorkArea.
979 if (twa->count() != 0) {
980 if (d.current_work_area_ == 0)
981 // This means that we are closing the current GuiWorkArea, so
982 // switch to the next GuiWorkArea in the found TabWorkArea.
983 setCurrentWorkArea(twa->currentWorkArea());
985 // No more WorkAreas in this tab group, so delete it.
992 // It is not a tabbed work area (i.e., the search work area), so it
993 // should be deleted by other means.
994 LASSERT(found_twa, /* */);
996 if (d.current_work_area_ == 0) {
997 if (d.splitter_->count() != 0) {
998 TabWorkArea * twa = d.currentTabWorkArea();
999 setCurrentWorkArea(twa->currentWorkArea());
1001 // No more work areas, switch to the background widget.
1002 setCurrentWorkArea(0);
1008 LayoutBox * GuiView::getLayoutDialog() const
1014 void GuiView::updateLayoutList()
1017 d.layout_->updateContents(false);
1021 void GuiView::updateToolbars()
1023 ToolbarMap::iterator end = d.toolbars_.end();
1024 if (d.current_work_area_) {
1026 d.current_work_area_->bufferView().cursor().inMathed();
1028 lyx::getStatus(FuncRequest(LFUN_LAYOUT_TABULAR)).enabled();
1030 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).enabled() &&
1031 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).onoff(true);
1032 bool const mathmacrotemplate =
1033 lyx::getStatus(FuncRequest(LFUN_IN_MATHMACROTEMPLATE)).enabled();
1035 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1036 it->second->update(math, table, review, mathmacrotemplate);
1038 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1039 it->second->update(false, false, false, false);
1043 void GuiView::setBuffer(Buffer * newBuffer)
1045 LYXERR(Debug::DEBUG, "Setting buffer: " << newBuffer << std::endl);
1046 LASSERT(newBuffer, return);
1049 GuiWorkArea * wa = workArea(*newBuffer);
1051 newBuffer->masterBuffer()->updateLabels();
1052 wa = addWorkArea(*newBuffer);
1054 //Disconnect the old buffer...there's no new one.
1057 connectBuffer(*newBuffer);
1058 connectBufferView(wa->bufferView());
1059 setCurrentWorkArea(wa);
1065 void GuiView::connectBuffer(Buffer & buf)
1067 buf.setGuiDelegate(this);
1071 void GuiView::disconnectBuffer()
1073 if (d.current_work_area_)
1074 d.current_work_area_->bufferView().buffer().setGuiDelegate(0);
1078 void GuiView::connectBufferView(BufferView & bv)
1080 bv.setGuiDelegate(this);
1084 void GuiView::disconnectBufferView()
1086 if (d.current_work_area_)
1087 d.current_work_area_->bufferView().setGuiDelegate(0);
1091 void GuiView::errors(string const & error_type, bool from_master)
1093 ErrorList & el = from_master ?
1094 documentBufferView()->buffer().masterBuffer()->errorList(error_type)
1095 : documentBufferView()->buffer().errorList(error_type);
1096 string data = error_type;
1098 data = "from_master|" + error_type;
1100 showDialog("errorlist", data);
1104 void GuiView::updateTocItem(std::string const & type, DocIterator const & dit)
1106 d.toc_models_.updateItem(toqstr(type), dit);
1110 void GuiView::structureChanged()
1112 d.toc_models_.reset(documentBufferView());
1113 // Navigator needs more than a simple update in this case. It needs to be
1115 updateDialog("toc", "");
1119 void GuiView::updateDialog(string const & name, string const & data)
1121 if (!isDialogVisible(name))
1124 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
1125 if (it == d.dialogs_.end())
1128 Dialog * const dialog = it->second.get();
1129 if (dialog->isVisibleView())
1130 dialog->initialiseParams(data);
1134 BufferView * GuiView::documentBufferView()
1136 return currentMainWorkArea()
1137 ? ¤tMainWorkArea()->bufferView()
1142 BufferView const * GuiView::documentBufferView() const
1144 return currentMainWorkArea()
1145 ? ¤tMainWorkArea()->bufferView()
1150 BufferView * GuiView::currentBufferView()
1152 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1156 BufferView const * GuiView::currentBufferView() const
1158 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1162 void GuiView::autoSave()
1164 LYXERR(Debug::INFO, "Running autoSave()");
1166 if (documentBufferView())
1167 documentBufferView()->buffer().autoSave();
1171 void GuiView::resetAutosaveTimers()
1174 d.autosave_timeout_.restart();
1178 bool GuiView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1181 Buffer * buf = currentBufferView()
1182 ? ¤tBufferView()->buffer() : 0;
1183 Buffer * doc_buffer = documentBufferView()
1184 ? &(documentBufferView()->buffer()) : 0;
1186 // Check whether we need a buffer
1187 if (!lyxaction.funcHasFlag(cmd.action, LyXAction::NoBuffer) && !buf) {
1188 // no, exit directly
1189 flag.message(from_utf8(N_("Command not allowed with"
1190 "out any document open")));
1191 flag.setEnabled(false);
1195 if (cmd.origin == FuncRequest::TOC) {
1196 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
1198 if (toc->getStatus(documentBufferView()->cursor(), cmd, fs))
1201 flag.setEnabled(false);
1205 switch(cmd.action) {
1206 case LFUN_BUFFER_IMPORT:
1209 case LFUN_BUFFER_RELOAD:
1210 enable = doc_buffer && !doc_buffer->isUnnamed()
1211 && doc_buffer->fileName().exists()
1212 && (!doc_buffer->isClean()
1213 || doc_buffer->isExternallyModified(Buffer::timestamp_method));
1216 case LFUN_BUFFER_CHILD_OPEN:
1217 enable = doc_buffer;
1220 case LFUN_BUFFER_WRITE:
1221 enable = doc_buffer && (doc_buffer->isUnnamed() || !doc_buffer->isClean());
1224 //FIXME: This LFUN should be moved to GuiApplication.
1225 case LFUN_BUFFER_WRITE_ALL: {
1226 // We enable the command only if there are some modified buffers
1227 Buffer * first = theBufferList().first();
1232 // We cannot use a for loop as the buffer list is a cycle.
1234 if (!b->isClean()) {
1238 b = theBufferList().next(b);
1239 } while (b != first);
1243 case LFUN_BUFFER_WRITE_AS:
1244 enable = doc_buffer;
1247 case LFUN_BUFFER_CLOSE:
1248 enable = doc_buffer;
1251 case LFUN_BUFFER_CLOSE_ALL:
1252 enable = theBufferList().last() != theBufferList().first();
1255 case LFUN_SPLIT_VIEW:
1256 if (cmd.getArg(0) == "vertical")
1257 enable = doc_buffer && (d.splitter_->count() == 1 ||
1258 d.splitter_->orientation() == Qt::Vertical);
1260 enable = doc_buffer && (d.splitter_->count() == 1 ||
1261 d.splitter_->orientation() == Qt::Horizontal);
1264 case LFUN_CLOSE_TAB_GROUP:
1265 enable = d.currentTabWorkArea();
1268 case LFUN_TOOLBAR_TOGGLE:
1269 if (GuiToolbar * t = toolbar(cmd.getArg(0)))
1270 flag.setOnOff(t->isVisible());
1273 case LFUN_UI_TOGGLE:
1274 flag.setOnOff(isFullScreen());
1277 case LFUN_DIALOG_DISCONNECT_INSET:
1280 case LFUN_DIALOG_HIDE:
1281 // FIXME: should we check if the dialog is shown?
1284 case LFUN_DIALOG_TOGGLE:
1285 flag.setOnOff(isDialogVisible(cmd.getArg(0)));
1286 // fall through to set "enable"
1287 case LFUN_DIALOG_SHOW: {
1288 string const name = cmd.getArg(0);
1290 enable = name == "aboutlyx"
1291 || name == "file" //FIXME: should be removed.
1293 || name == "texinfo";
1294 else if (name == "print")
1295 enable = doc_buffer->isExportable("dvi")
1296 && lyxrc.print_command != "none";
1297 else if (name == "character" || name == "symbols") {
1298 if (!buf || buf->isReadonly()
1299 || !currentBufferView()->cursor().inTexted())
1302 // FIXME we should consider passthru
1304 Inset const & in = currentBufferView()->cursor().inset();
1305 enable = !in.getLayout().isPassThru();
1308 else if (name == "latexlog")
1309 enable = FileName(doc_buffer->logName()).isReadableFile();
1310 else if (name == "spellchecker")
1311 enable = theSpellChecker() && !doc_buffer->isReadonly();
1312 else if (name == "vclog")
1313 enable = doc_buffer->lyxvc().inUse();
1317 case LFUN_DIALOG_UPDATE: {
1318 string const name = cmd.getArg(0);
1320 enable = name == "prefs";
1324 case LFUN_COMMAND_EXECUTE:
1326 case LFUN_MENU_OPEN:
1327 // Nothing to check.
1330 case LFUN_INSET_APPLY: {
1331 string const name = cmd.getArg(0);
1332 Inset * inset = getOpenInset(name);
1334 FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument());
1336 if (!inset->getStatus(currentBufferView()->cursor(), fr, fs)) {
1337 // Every inset is supposed to handle this
1338 LASSERT(false, break);
1342 FuncRequest fr(LFUN_INSET_INSERT, cmd.argument());
1343 flag |= lyx::getStatus(fr);
1345 enable = flag.enabled();
1349 case LFUN_COMPLETION_INLINE:
1350 if (!d.current_work_area_
1351 || !d.current_work_area_->completer().inlinePossible(
1352 currentBufferView()->cursor()))
1356 case LFUN_COMPLETION_POPUP:
1357 if (!d.current_work_area_
1358 || !d.current_work_area_->completer().popupPossible(
1359 currentBufferView()->cursor()))
1363 case LFUN_COMPLETION_COMPLETE:
1364 if (!d.current_work_area_
1365 || !d.current_work_area_->completer().inlinePossible(
1366 currentBufferView()->cursor()))
1370 case LFUN_COMPLETION_ACCEPT:
1371 if (!d.current_work_area_
1372 || (!d.current_work_area_->completer().popupVisible()
1373 && !d.current_work_area_->completer().inlineVisible()
1374 && !d.current_work_area_->completer().completionAvailable()))
1378 case LFUN_COMPLETION_CANCEL:
1379 if (!d.current_work_area_
1380 || (!d.current_work_area_->completer().popupVisible()
1381 && !d.current_work_area_->completer().inlineVisible()))
1385 case LFUN_BUFFER_ZOOM_OUT:
1386 enable = doc_buffer && lyxrc.zoom > 10;
1389 case LFUN_BUFFER_ZOOM_IN:
1390 enable = doc_buffer;
1393 case LFUN_BUFFER_NEXT:
1394 case LFUN_BUFFER_PREVIOUS:
1395 // FIXME: should we check is there is an previous or next buffer?
1397 case LFUN_BUFFER_SWITCH:
1398 // toggle on the current buffer, but do not toggle off
1399 // the other ones (is that a good idea?)
1401 && to_utf8(cmd.argument()) == doc_buffer->absFileName())
1402 flag.setOnOff(true);
1405 case LFUN_VC_REGISTER:
1406 enable = doc_buffer && !doc_buffer->lyxvc().inUse();
1408 case LFUN_VC_CHECK_IN:
1409 enable = doc_buffer && doc_buffer->lyxvc().checkInEnabled();
1411 case LFUN_VC_CHECK_OUT:
1412 enable = doc_buffer && doc_buffer->lyxvc().checkOutEnabled();
1414 case LFUN_VC_LOCKING_TOGGLE:
1415 enable = doc_buffer && !doc_buffer->isReadonly()
1416 && doc_buffer->lyxvc().lockingToggleEnabled();
1417 flag.setOnOff(enable && !doc_buffer->lyxvc().locker().empty());
1419 case LFUN_VC_REVERT:
1420 enable = doc_buffer && doc_buffer->lyxvc().inUse();
1422 case LFUN_VC_UNDO_LAST:
1423 enable = doc_buffer && doc_buffer->lyxvc().undoLastEnabled();
1425 case LFUN_VC_COMMAND: {
1426 if (cmd.argument().empty())
1428 if (!doc_buffer && contains(cmd.getArg(0), 'D'))
1438 flag.setEnabled(false);
1444 static FileName selectTemplateFile()
1446 FileDialog dlg(qt_("Select template file"));
1447 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1448 dlg.setButton1(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
1450 FileDialog::Result result = dlg.open(toqstr(lyxrc.template_path),
1451 QStringList(qt_("LyX Documents (*.lyx)")));
1453 if (result.first == FileDialog::Later)
1455 if (result.second.isEmpty())
1457 return FileName(fromqstr(result.second));
1461 Buffer * GuiView::loadDocument(FileName const & filename, bool tolastfiles)
1465 Buffer * newBuffer = checkAndLoadLyXFile(filename);
1468 message(_("Document not loaded."));
1473 setBuffer(newBuffer);
1475 // scroll to the position when the file was last closed
1476 if (lyxrc.use_lastfilepos) {
1477 LastFilePosSection::FilePos filepos =
1478 theSession().lastFilePos().load(filename);
1479 documentBufferView()->moveToPosition(filepos.pit, filepos.pos, 0, 0);
1483 theSession().lastFiles().add(filename);
1490 void GuiView::openDocument(string const & fname)
1492 string initpath = lyxrc.document_path;
1494 if (documentBufferView()) {
1495 string const trypath = documentBufferView()->buffer().filePath();
1496 // If directory is writeable, use this as default.
1497 if (FileName(trypath).isDirWritable())
1503 if (fname.empty()) {
1504 FileDialog dlg(qt_("Select document to open"), LFUN_FILE_OPEN);
1505 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1506 dlg.setButton2(qt_("Examples|#E#e"),
1507 toqstr(addPath(package().system_support().absFilename(), "examples")));
1509 QStringList filter(qt_("LyX Documents (*.lyx)"));
1510 filter << qt_("LyX-1.3.x Documents (*.lyx13)")
1511 << qt_("LyX-1.4.x Documents (*.lyx14)")
1512 << qt_("LyX-1.5.x Documents (*.lyx15)")
1513 << qt_("LyX-1.6.x Documents (*.lyx16)");
1514 FileDialog::Result result =
1515 dlg.open(toqstr(initpath), filter);
1517 if (result.first == FileDialog::Later)
1520 filename = fromqstr(result.second);
1522 // check selected filename
1523 if (filename.empty()) {
1524 message(_("Canceled."));
1530 // get absolute path of file and add ".lyx" to the filename if
1532 FileName const fullname =
1533 fileSearch(string(), filename, "lyx", support::may_not_exist);
1534 if (!fullname.empty())
1535 filename = fullname.absFilename();
1537 if (!fullname.onlyPath().isDirectory()) {
1538 Alert::warning(_("Invalid filename"),
1539 bformat(_("The directory in the given path\n%1$s\ndoes not exist."),
1540 from_utf8(fullname.absFilename())));
1543 // if the file doesn't exist, let the user create one
1544 if (!fullname.exists()) {
1545 // the user specifically chose this name. Believe him.
1546 Buffer * const b = newFile(filename, string(), true);
1552 docstring const disp_fn = makeDisplayPath(filename);
1553 message(bformat(_("Opening document %1$s..."), disp_fn));
1556 Buffer * buf = loadDocument(fullname);
1558 buf->updateLabels();
1560 buf->errors("Parse");
1561 str2 = bformat(_("Document %1$s opened."), disp_fn);
1562 if (buf->lyxvc().inUse())
1563 str2 += " " + from_utf8(buf->lyxvc().versionString()) +
1564 " " + _("Version control detected.");
1566 str2 = bformat(_("Could not open document %1$s"), disp_fn);
1571 // FIXME: clean that
1572 static bool import(GuiView * lv, FileName const & filename,
1573 string const & format, ErrorList & errorList)
1575 FileName const lyxfile(support::changeExtension(filename.absFilename(), ".lyx"));
1577 string loader_format;
1578 vector<string> loaders = theConverters().loaders();
1579 if (find(loaders.begin(), loaders.end(), format) == loaders.end()) {
1580 for (vector<string>::const_iterator it = loaders.begin();
1581 it != loaders.end(); ++it) {
1582 if (!theConverters().isReachable(format, *it))
1585 string const tofile =
1586 support::changeExtension(filename.absFilename(),
1587 formats.extension(*it));
1588 if (!theConverters().convert(0, filename, FileName(tofile),
1589 filename, format, *it, errorList))
1591 loader_format = *it;
1594 if (loader_format.empty()) {
1595 frontend::Alert::error(_("Couldn't import file"),
1596 bformat(_("No information for importing the format %1$s."),
1597 formats.prettyName(format)));
1601 loader_format = format;
1603 if (loader_format == "lyx") {
1604 Buffer * buf = lv->loadDocument(lyxfile);
1607 buf->updateLabels();
1609 buf->errors("Parse");
1611 Buffer * const b = newFile(lyxfile.absFilename(), string(), true);
1615 bool as_paragraphs = loader_format == "textparagraph";
1616 string filename2 = (loader_format == format) ? filename.absFilename()
1617 : support::changeExtension(filename.absFilename(),
1618 formats.extension(loader_format));
1619 lv->currentBufferView()->insertPlaintextFile(FileName(filename2),
1621 guiApp->setCurrentView(lv);
1622 lyx::dispatch(FuncRequest(LFUN_MARK_OFF));
1629 void GuiView::importDocument(string const & argument)
1632 string filename = split(argument, format, ' ');
1634 LYXERR(Debug::INFO, format << " file: " << filename);
1636 // need user interaction
1637 if (filename.empty()) {
1638 string initpath = lyxrc.document_path;
1639 if (documentBufferView()) {
1640 string const trypath = documentBufferView()->buffer().filePath();
1641 // If directory is writeable, use this as default.
1642 if (FileName(trypath).isDirWritable())
1646 docstring const text = bformat(_("Select %1$s file to import"),
1647 formats.prettyName(format));
1649 FileDialog dlg(toqstr(text), LFUN_BUFFER_IMPORT);
1650 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1651 dlg.setButton2(qt_("Examples|#E#e"),
1652 toqstr(addPath(package().system_support().absFilename(), "examples")));
1654 docstring filter = formats.prettyName(format);
1657 filter += from_utf8(formats.extension(format));
1660 FileDialog::Result result =
1661 dlg.open(toqstr(initpath), fileFilters(toqstr(filter)));
1663 if (result.first == FileDialog::Later)
1666 filename = fromqstr(result.second);
1668 // check selected filename
1669 if (filename.empty())
1670 message(_("Canceled."));
1673 if (filename.empty())
1676 // get absolute path of file
1677 FileName const fullname(support::makeAbsPath(filename));
1679 FileName const lyxfile(support::changeExtension(fullname.absFilename(), ".lyx"));
1681 // Check if the document already is open
1682 Buffer * buf = theBufferList().getBuffer(lyxfile);
1685 if (!closeBuffer()) {
1686 message(_("Canceled."));
1691 docstring const displaypath = makeDisplayPath(lyxfile.absFilename(), 30);
1693 // if the file exists already, and we didn't do
1694 // -i lyx thefile.lyx, warn
1695 if (lyxfile.exists() && fullname != lyxfile) {
1697 docstring text = bformat(_("The document %1$s already exists.\n\n"
1698 "Do you want to overwrite that document?"), displaypath);
1699 int const ret = Alert::prompt(_("Overwrite document?"),
1700 text, 0, 1, _("&Overwrite"), _("&Cancel"));
1703 message(_("Canceled."));
1708 message(bformat(_("Importing %1$s..."), displaypath));
1709 ErrorList errorList;
1710 if (import(this, fullname, format, errorList))
1711 message(_("imported."));
1713 message(_("file not imported!"));
1715 // FIXME (Abdel 12/08/06): Is there a need to display the error list here?
1719 void GuiView::newDocument(string const & filename, bool from_template)
1721 FileName initpath(lyxrc.document_path);
1722 if (documentBufferView()) {
1723 FileName const trypath(documentBufferView()->buffer().filePath());
1724 // If directory is writeable, use this as default.
1725 if (trypath.isDirWritable())
1729 string templatefile;
1730 if (from_template) {
1731 templatefile = selectTemplateFile().absFilename();
1732 if (templatefile.empty())
1737 if (filename.empty())
1738 b = newUnnamedFile(templatefile, initpath);
1740 b = newFile(filename, templatefile, true);
1745 // If no new document could be created, it is unsure
1746 // whether there is a valid BufferView.
1747 if (currentBufferView())
1748 // Ensure the cursor is correctly positioned on screen.
1749 currentBufferView()->showCursor();
1753 void GuiView::insertLyXFile(docstring const & fname)
1755 BufferView * bv = documentBufferView();
1760 FileName filename(to_utf8(fname));
1762 if (!filename.empty()) {
1763 bv->insertLyXFile(filename);
1767 // Launch a file browser
1769 string initpath = lyxrc.document_path;
1770 string const trypath = bv->buffer().filePath();
1771 // If directory is writeable, use this as default.
1772 if (FileName(trypath).isDirWritable())
1776 FileDialog dlg(qt_("Select LyX document to insert"), LFUN_FILE_INSERT);
1777 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1778 dlg.setButton2(qt_("Examples|#E#e"),
1779 toqstr(addPath(package().system_support().absFilename(),
1782 FileDialog::Result result = dlg.open(toqstr(initpath),
1783 QStringList(qt_("LyX Documents (*.lyx)")));
1785 if (result.first == FileDialog::Later)
1789 filename.set(fromqstr(result.second));
1791 // check selected filename
1792 if (filename.empty()) {
1793 // emit message signal.
1794 message(_("Canceled."));
1798 bv->insertLyXFile(filename);
1802 void GuiView::insertPlaintextFile(docstring const & fname,
1805 BufferView * bv = documentBufferView();
1809 if (!fname.empty() && !FileName::isAbsolute(to_utf8(fname))) {
1810 message(_("Absolute filename expected."));
1815 FileName filename(to_utf8(fname));
1817 if (!filename.empty()) {
1818 bv->insertPlaintextFile(filename, asParagraph);
1822 FileDialog dlg(qt_("Select file to insert"), (asParagraph ?
1823 LFUN_FILE_INSERT_PLAINTEXT_PARA : LFUN_FILE_INSERT_PLAINTEXT));
1825 FileDialog::Result result = dlg.open(toqstr(bv->buffer().filePath()),
1826 QStringList(qt_("All Files (*)")));
1828 if (result.first == FileDialog::Later)
1832 filename.set(fromqstr(result.second));
1834 // check selected filename
1835 if (filename.empty()) {
1836 // emit message signal.
1837 message(_("Canceled."));
1841 bv->insertPlaintextFile(filename, asParagraph);
1845 bool GuiView::renameBuffer(Buffer & b, docstring const & newname)
1847 FileName fname = b.fileName();
1848 FileName const oldname = fname;
1850 if (!newname.empty()) {
1852 fname = support::makeAbsPath(to_utf8(newname), oldname.onlyPath().absFilename());
1854 // Switch to this Buffer.
1857 // No argument? Ask user through dialog.
1859 FileDialog dlg(qt_("Choose a filename to save document as"),
1860 LFUN_BUFFER_WRITE_AS);
1861 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1862 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
1864 if (!isLyXFilename(fname.absFilename()))
1865 fname.changeExtension(".lyx");
1867 FileDialog::Result result =
1868 dlg.save(toqstr(fname.onlyPath().absFilename()),
1869 QStringList(qt_("LyX Documents (*.lyx)")),
1870 toqstr(fname.onlyFileName()));
1872 if (result.first == FileDialog::Later)
1875 fname.set(fromqstr(result.second));
1880 if (!isLyXFilename(fname.absFilename()))
1881 fname.changeExtension(".lyx");
1884 if (FileName(fname).exists()) {
1885 docstring const file = makeDisplayPath(fname.absFilename(), 30);
1886 docstring text = bformat(_("The document %1$s already "
1887 "exists.\n\nDo you want to "
1888 "overwrite that document?"),
1890 int const ret = Alert::prompt(_("Overwrite document?"),
1891 text, 0, 2, _("&Overwrite"), _("&Rename"), _("&Cancel"));
1894 case 1: return renameBuffer(b, docstring());
1895 case 2: return false;
1899 FileName oldauto = b.getAutosaveFilename();
1901 // Ok, change the name of the buffer
1902 b.setFileName(fname.absFilename());
1904 bool unnamed = b.isUnnamed();
1905 b.setUnnamed(false);
1906 b.saveCheckSum(fname);
1908 // bring the autosave file with us, just in case.
1909 b.moveAutosaveFile(oldauto);
1911 if (!saveBuffer(b)) {
1912 oldauto = b.getAutosaveFilename();
1913 b.setFileName(oldname.absFilename());
1914 b.setUnnamed(unnamed);
1915 b.saveCheckSum(oldname);
1916 b.moveAutosaveFile(oldauto);
1924 bool GuiView::saveBuffer(Buffer & b)
1926 if (workArea(b) && workArea(b)->inDialogMode())
1930 return renameBuffer(b, docstring());
1933 theSession().lastFiles().add(b.fileName());
1937 // Switch to this Buffer.
1940 // FIXME: we don't tell the user *WHY* the save failed !!
1941 docstring const file = makeDisplayPath(b.absFileName(), 30);
1942 docstring text = bformat(_("The document %1$s could not be saved.\n\n"
1943 "Do you want to rename the document and "
1944 "try again?"), file);
1945 int const ret = Alert::prompt(_("Rename and save?"),
1946 text, 0, 2, _("&Rename"), _("&Retry"), _("&Cancel"));
1949 if (!renameBuffer(b, docstring()))
1958 return saveBuffer(b);
1962 bool GuiView::hideWorkArea(GuiWorkArea * wa)
1964 return closeWorkArea(wa, false);
1968 bool GuiView::closeWorkArea(GuiWorkArea * wa)
1970 Buffer & buf = wa->bufferView().buffer();
1971 return closeWorkArea(wa, !buf.parent());
1975 bool GuiView::closeBuffer()
1977 GuiWorkArea * wa = currentMainWorkArea();
1978 Buffer & buf = wa->bufferView().buffer();
1979 return wa && closeWorkArea(wa, !buf.parent());
1983 void GuiView::writeSession() const {
1984 GuiWorkArea const * active_wa = currentMainWorkArea();
1985 for (int i = 0; i < d.splitter_->count(); ++i) {
1986 TabWorkArea * twa = d.tabWorkArea(i);
1987 for (int j = 0; j < twa->count(); ++j) {
1988 GuiWorkArea * wa = static_cast<GuiWorkArea *>(twa->widget(j));
1989 Buffer & buf = wa->bufferView().buffer();
1990 theSession().lastOpened().add(buf.fileName(), wa == active_wa);
1996 bool GuiView::closeBufferAll()
1998 // Close the workareas in all other views
1999 QList<int> const ids = guiApp->viewIds();
2000 for (int i = 0; i != ids.size(); ++i) {
2001 if (id_ != ids[i] && !guiApp->view(ids[i]).closeWorkAreaAll())
2005 // Close our own workareas
2006 if (!closeWorkAreaAll())
2009 // Now close the hidden buffers. We prevent hidden buffers from being
2010 // dirty, so we can just close them.
2011 theBufferList().closeAll();
2016 bool GuiView::closeWorkAreaAll()
2018 setCurrentWorkArea(currentMainWorkArea());
2020 // We might be in a situation that there is still a tabWorkArea, but
2021 // there are no tabs anymore. This can happen when we get here after a
2022 // TabWorkArea::lastWorkAreaRemoved() signal. Therefore we count how
2023 // many TabWorkArea's have no documents anymore.
2026 // We have to call count() each time, because it can happen that
2027 // more than one splitter will disappear in one iteration (bug 5998).
2028 for (; d.splitter_->count() > empty_twa; ) {
2029 TabWorkArea * twa = d.tabWorkArea(empty_twa);
2031 if (twa->count() == 0)
2034 setCurrentWorkArea(twa->currentWorkArea());
2035 if (!closeTabWorkArea(twa))
2043 bool GuiView::closeWorkArea(GuiWorkArea * wa, bool close_buffer)
2045 Buffer & buf = wa->bufferView().buffer();
2047 // If we are in a close_event all children will be closed in some time,
2048 // so no need to do it here. This will ensure that the children end up
2049 // in the session file in the correct order. If we close the master
2050 // buffer, we can close or release the child buffers here too.
2051 if (close_buffer && !closing_) {
2052 vector<Buffer *> clist = buf.getChildren();
2053 for (vector<Buffer *>::const_iterator it = clist.begin();
2054 it != clist.end(); ++it) {
2055 // If a child is dirty, do not close
2056 // without user intervention
2057 //FIXME: should we look in other tabworkareas?
2058 Buffer * child_buf = *it;
2059 GuiWorkArea * child_wa = workArea(*child_buf);
2061 if (!closeWorkArea(child_wa, true))
2064 theBufferList().releaseChild(&buf, child_buf);
2067 // goto bookmark to update bookmark pit.
2068 //FIXME: we should update only the bookmarks related to this buffer!
2069 LYXERR(Debug::DEBUG, "GuiView::closeBuffer()");
2070 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
2071 theLyXFunc().gotoBookmark(i+1, false, false);
2073 // if we are only hiding the buffer and there are multiple views
2074 // of the buffer, then we do not need to ensure a clean buffer.
2075 bool const allow_dirty = inMultiTabs(wa) && !close_buffer;
2077 if (allow_dirty || saveBufferIfNeeded(buf, !close_buffer)) {
2078 // save in sessions if requested
2079 // do not save childs if their master
2080 // is opened as well
2084 theBufferList().release(&buf);
2091 bool GuiView::closeTabWorkArea(TabWorkArea * twa)
2093 while (twa == d.currentTabWorkArea()) {
2094 twa->setCurrentIndex(twa->count()-1);
2096 GuiWorkArea * wa = twa->currentWorkArea();
2097 Buffer & b = wa->bufferView().buffer();
2099 // We only want to close the buffer if the same buffer is not visible
2100 // in another view, and if this is not a child and if we are closing
2101 // a view (not a tabgroup).
2102 bool const close_buffer =
2103 !inMultiViews(wa) && !b.parent() && closing_;
2105 if (!closeWorkArea(wa, close_buffer))
2112 bool GuiView::saveBufferIfNeeded(Buffer & buf, bool hiding)
2114 if (buf.isClean() || buf.paragraphs().empty())
2117 // Switch to this Buffer.
2122 if (buf.isUnnamed())
2123 file = from_utf8(buf.fileName().onlyFileName());
2125 file = buf.fileName().displayName(30);
2127 // Bring this window to top before asking questions.
2132 if (hiding && buf.isUnnamed()) {
2133 docstring const text = bformat(_("The document %1$s has not been "
2134 "saved yet.\n\nDo you want to save "
2135 "the document?"), file);
2136 ret = Alert::prompt(_("Save new document?"),
2137 text, 0, 1, _("&Save"), _("&Cancel"));
2141 docstring const text = bformat(_("The document %1$s has unsaved changes."
2142 "\n\nDo you want to save the document or discard the changes?"), file);
2143 ret = Alert::prompt(_("Save changed document?"),
2144 text, 0, 2, _("&Save"), _("&Discard"), _("&Cancel"));
2149 if (!saveBuffer(buf))
2153 // if we crash after this we could
2154 // have no autosave file but I guess
2155 // this is really improbable (Jug)
2156 buf.removeAutosaveFile();
2158 // revert all changes
2159 buf.loadLyXFile(buf.fileName());
2169 bool GuiView::inMultiTabs(GuiWorkArea * wa)
2171 Buffer & buf = wa->bufferView().buffer();
2173 for (int i = 0; i != d.splitter_->count(); ++i) {
2174 GuiWorkArea * wa_ = d.tabWorkArea(i)->workArea(buf);
2175 if (wa_ && wa_ != wa)
2178 return inMultiViews(wa);
2182 bool GuiView::inMultiViews(GuiWorkArea * wa)
2184 QList<int> const ids = guiApp->viewIds();
2185 Buffer & buf = wa->bufferView().buffer();
2188 for (int i = 0; i != ids.size() && found_twa <= 1; ++i) {
2192 if (guiApp->view(ids[i]).workArea(buf))
2199 void GuiView::gotoNextOrPreviousBuffer(NextOrPrevious np)
2201 Buffer * const curbuf = documentBufferView()
2202 ? &documentBufferView()->buffer() : 0;
2203 Buffer * nextbuf = curbuf;
2205 if (np == NEXTBUFFER)
2206 nextbuf = theBufferList().next(nextbuf);
2208 nextbuf = theBufferList().previous(nextbuf);
2209 if (nextbuf == curbuf)
2215 if (workArea(*nextbuf))
2222 /// make sure the document is saved
2223 static bool ensureBufferClean(Buffer * buffer)
2225 LASSERT(buffer, return false);
2226 if (buffer->isClean() && !buffer->isUnnamed())
2229 docstring const file = buffer->fileName().displayName(30);
2232 if (!buffer->isUnnamed()) {
2233 text = bformat(_("The document %1$s has unsaved "
2234 "changes.\n\nDo you want to save "
2235 "the document?"), file);
2236 title = _("Save changed document?");
2239 text = bformat(_("The document %1$s has not been "
2240 "saved yet.\n\nDo you want to save "
2241 "the document?"), file);
2242 title = _("Save new document?");
2244 int const ret = Alert::prompt(title, text, 0, 1, _("&Save"), _("&Cancel"));
2247 dispatch(FuncRequest(LFUN_BUFFER_WRITE));
2249 return buffer->isClean() && !buffer->isUnnamed();
2253 void GuiView::reloadBuffer()
2255 Buffer * buf = &documentBufferView()->buffer();
2256 FileName filename = buf->fileName();
2257 // The user has already confirmed that the changes, if any, should
2258 // be discarded. So we just release the Buffer and don't call closeBuffer();
2259 theBufferList().release(buf);
2260 buf = loadDocument(filename);
2261 docstring const disp_fn = makeDisplayPath(filename.absFilename());
2264 buf->updateLabels();
2266 buf->errors("Parse");
2267 str = bformat(_("Document %1$s reloaded."), disp_fn);
2269 str = bformat(_("Could not reload document %1$s"), disp_fn);
2275 void GuiView::dispatchVC(FuncRequest const & cmd)
2277 Buffer * buffer = documentBufferView()
2278 ? &(documentBufferView()->buffer()) : 0;
2280 switch (cmd.action) {
2281 case LFUN_VC_REGISTER:
2282 if (!buffer || !ensureBufferClean(buffer))
2284 if (!buffer->lyxvc().inUse()) {
2285 if (buffer->lyxvc().registrer())
2290 case LFUN_VC_CHECK_IN:
2291 if (!buffer || !ensureBufferClean(buffer))
2293 if (buffer->lyxvc().inUse() && !buffer->isReadonly()) {
2294 message(from_utf8(buffer->lyxvc().checkIn()));
2299 case LFUN_VC_CHECK_OUT:
2300 if (!buffer || !ensureBufferClean(buffer))
2302 if (buffer->lyxvc().inUse()) {
2303 message(from_utf8(buffer->lyxvc().checkOut()));
2308 case LFUN_VC_LOCKING_TOGGLE:
2309 LASSERT(buffer, return);
2310 if (!ensureBufferClean(buffer) || buffer->isReadonly())
2312 if (buffer->lyxvc().inUse()) {
2313 string res = buffer->lyxvc().lockingToggle();
2315 frontend::Alert::error(_("Revision control error."),
2316 _("Error when setting the locking property."));
2318 message(from_utf8(res));
2324 case LFUN_VC_REVERT:
2325 LASSERT(buffer, return);
2326 buffer->lyxvc().revert();
2330 case LFUN_VC_UNDO_LAST:
2331 LASSERT(buffer, return);
2332 buffer->lyxvc().undoLast();
2336 case LFUN_VC_COMMAND: {
2337 string flag = cmd.getArg(0);
2338 if (buffer && contains(flag, 'R') && !ensureBufferClean(buffer))
2341 if (contains(flag, 'M')) {
2342 if (!Alert::askForText(message, _("LyX VC: Log Message")))
2345 string path = cmd.getArg(1);
2346 if (contains(path, "$$p") && buffer)
2347 path = subst(path, "$$p", buffer->filePath());
2348 LYXERR(Debug::LYXVC, "Directory: " << path);
2350 if (!pp.isReadableDirectory()) {
2351 lyxerr << _("Directory is not accessible.") << endl;
2354 support::PathChanger p(pp);
2356 string command = cmd.getArg(2);
2357 if (command.empty())
2360 command = subst(command, "$$i", buffer->absFileName());
2361 command = subst(command, "$$p", buffer->filePath());
2363 command = subst(command, "$$m", to_utf8(message));
2364 LYXERR(Debug::LYXVC, "Command: " << command);
2366 one.startscript(Systemcall::Wait, command);
2370 if (contains(flag, 'I'))
2371 buffer->markDirty();
2372 if (contains(flag, 'R'))
2383 void GuiView::openChildDocument(string const & fname)
2385 LASSERT(documentBufferView(), return);
2386 Buffer & buffer = documentBufferView()->buffer();
2387 FileName const filename = support::makeAbsPath(fname, buffer.filePath());
2388 documentBufferView()->saveBookmark(false);
2390 bool parsed = false;
2391 if (theBufferList().exists(filename)) {
2392 child = theBufferList().getBuffer(filename);
2394 message(bformat(_("Opening child document %1$s..."),
2395 makeDisplayPath(filename.absFilename())));
2396 child = loadDocument(filename, false);
2402 // Set the parent name of the child document.
2403 // This makes insertion of citations and references in the child work,
2404 // when the target is in the parent or another child document.
2405 child->setParent(&buffer);
2406 child->masterBuffer()->updateLabels();
2409 child->errors("Parse");
2413 bool GuiView::dispatch(FuncRequest const & cmd)
2415 BufferView * bv = currentBufferView();
2416 // By default we won't need any update.
2418 bv->cursor().updateFlags(Update::None);
2420 Buffer * doc_buffer = documentBufferView()
2421 ? &(documentBufferView()->buffer()) : 0;
2423 bool dispatched = true;
2425 if (cmd.origin == FuncRequest::TOC) {
2426 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
2427 toc->doDispatch(bv->cursor(), cmd);
2431 switch(cmd.action) {
2432 case LFUN_BUFFER_CHILD_OPEN:
2433 openChildDocument(to_utf8(cmd.argument()));
2436 case LFUN_BUFFER_IMPORT:
2437 importDocument(to_utf8(cmd.argument()));
2440 case LFUN_BUFFER_SWITCH:
2441 if (FileName::isAbsolute(to_utf8(cmd.argument()))) {
2443 theBufferList().getBuffer(FileName(to_utf8(cmd.argument())));
2447 bv->cursor().message(_("Document not loaded"));
2451 case LFUN_BUFFER_NEXT:
2452 gotoNextOrPreviousBuffer(NEXTBUFFER);
2455 case LFUN_BUFFER_PREVIOUS:
2456 gotoNextOrPreviousBuffer(PREVBUFFER);
2459 case LFUN_COMMAND_EXECUTE: {
2460 bool const show_it = cmd.argument() != "off";
2461 // FIXME: this is a hack, "minibuffer" should not be
2463 if (GuiToolbar * t = toolbar("minibuffer")) {
2464 t->setVisible(show_it);
2465 if (show_it && t->commandBuffer())
2466 t->commandBuffer()->setFocus();
2470 case LFUN_DROP_LAYOUTS_CHOICE:
2471 d.layout_->showPopup();
2474 case LFUN_MENU_OPEN:
2475 if (QMenu * menu = guiApp->menus().menu(toqstr(cmd.argument()), *this))
2476 menu->exec(QCursor::pos());
2479 case LFUN_FILE_INSERT:
2480 insertLyXFile(cmd.argument());
2482 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
2483 insertPlaintextFile(cmd.argument(), true);
2486 case LFUN_FILE_INSERT_PLAINTEXT:
2487 insertPlaintextFile(cmd.argument(), false);
2490 case LFUN_BUFFER_RELOAD: {
2491 LASSERT(doc_buffer, break);
2492 docstring const file = makeDisplayPath(doc_buffer->absFileName(), 20);
2493 docstring text = bformat(_("Any changes will be lost. Are you sure "
2494 "you want to revert to the saved version of the document %1$s?"), file);
2495 int const ret = Alert::prompt(_("Revert to saved document?"),
2496 text, 1, 1, _("&Revert"), _("&Cancel"));
2503 case LFUN_BUFFER_WRITE:
2504 LASSERT(doc_buffer, break);
2505 saveBuffer(*doc_buffer);
2508 case LFUN_BUFFER_WRITE_AS:
2509 LASSERT(doc_buffer, break);
2510 renameBuffer(*doc_buffer, cmd.argument());
2513 case LFUN_BUFFER_WRITE_ALL: {
2514 Buffer * first = theBufferList().first();
2517 message(_("Saving all documents..."));
2518 // We cannot use a for loop as the buffer list cycles.
2521 if (!b->isClean()) {
2523 LYXERR(Debug::ACTION, "Saved " << b->absFileName());
2525 b = theBufferList().next(b);
2526 } while (b != first);
2527 message(_("All documents saved."));
2531 case LFUN_BUFFER_CLOSE:
2535 case LFUN_BUFFER_CLOSE_ALL:
2539 case LFUN_TOOLBAR_TOGGLE: {
2540 string const name = cmd.getArg(0);
2541 if (GuiToolbar * t = toolbar(name))
2546 case LFUN_DIALOG_UPDATE: {
2547 string const name = to_utf8(cmd.argument());
2548 // Can only update a dialog connected to an existing inset
2549 Inset * inset = getOpenInset(name);
2551 FuncRequest fr(LFUN_INSET_DIALOG_UPDATE, cmd.argument());
2552 inset->dispatch(currentBufferView()->cursor(), fr);
2553 } else if (name == "paragraph") {
2554 lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
2555 } else if (name == "prefs" || name == "document") {
2556 updateDialog(name, string());
2561 case LFUN_DIALOG_TOGGLE: {
2562 if (isDialogVisible(cmd.getArg(0)))
2563 dispatch(FuncRequest(LFUN_DIALOG_HIDE, cmd.argument()));
2565 dispatch(FuncRequest(LFUN_DIALOG_SHOW, cmd.argument()));
2569 case LFUN_DIALOG_DISCONNECT_INSET:
2570 disconnectDialog(to_utf8(cmd.argument()));
2573 case LFUN_DIALOG_HIDE: {
2574 guiApp->hideDialogs(to_utf8(cmd.argument()), 0);
2578 case LFUN_DIALOG_SHOW: {
2579 string const name = cmd.getArg(0);
2580 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
2582 if (name == "character") {
2583 data = freefont2string();
2585 showDialog("character", data);
2586 } else if (name == "latexlog") {
2587 Buffer::LogType type;
2588 string const logfile = doc_buffer->logName(&type);
2590 case Buffer::latexlog:
2593 case Buffer::buildlog:
2597 data += Lexer::quoteString(logfile);
2598 showDialog("log", data);
2599 } else if (name == "vclog") {
2600 string const data = "vc " +
2601 Lexer::quoteString(doc_buffer->lyxvc().getLogFile());
2602 showDialog("log", data);
2603 } else if (name == "symbols") {
2604 data = bv->cursor().getEncoding()->name();
2606 showDialog("symbols", data);
2608 } else if (name == "prefs" && isFullScreen()) {
2609 FuncRequest fr(LFUN_INSET_INSERT, "fullscreen");
2611 showDialog("prefs", data);
2613 showDialog(name, data);
2618 message(cmd.argument());
2621 case LFUN_INSET_APPLY: {
2622 string const name = cmd.getArg(0);
2623 Inset * inset = getOpenInset(name);
2625 // put cursor in front of inset.
2626 if (!currentBufferView()->setCursorFromInset(inset)) {
2627 LASSERT(false, break);
2629 BufferView * bv = currentBufferView();
2630 // useful if we are called from a dialog.
2631 bv->cursor().beginUndoGroup();
2632 bv->cursor().recordUndo();
2633 FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument());
2634 inset->dispatch(bv->cursor(), fr);
2635 bv->cursor().endUndoGroup();
2637 FuncRequest fr(LFUN_INSET_INSERT, cmd.argument());
2643 case LFUN_UI_TOGGLE:
2645 // Make sure the keyboard focus stays in the work area.
2649 case LFUN_SPLIT_VIEW: {
2650 LASSERT(doc_buffer, break);
2651 string const orientation = cmd.getArg(0);
2652 d.splitter_->setOrientation(orientation == "vertical"
2653 ? Qt::Vertical : Qt::Horizontal);
2654 TabWorkArea * twa = addTabWorkArea();
2655 GuiWorkArea * wa = twa->addWorkArea(*doc_buffer, *this);
2656 setCurrentWorkArea(wa);
2659 case LFUN_CLOSE_TAB_GROUP:
2660 if (TabWorkArea * twa = d.currentTabWorkArea()) {
2661 closeTabWorkArea(twa);
2662 d.current_work_area_ = 0;
2663 twa = d.currentTabWorkArea();
2664 // Switch to the next GuiWorkArea in the found TabWorkArea.
2666 // Make sure the work area is up to date.
2667 setCurrentWorkArea(twa->currentWorkArea());
2669 setCurrentWorkArea(0);
2674 case LFUN_COMPLETION_INLINE:
2675 if (d.current_work_area_)
2676 d.current_work_area_->completer().showInline();
2679 case LFUN_COMPLETION_POPUP:
2680 if (d.current_work_area_)
2681 d.current_work_area_->completer().showPopup();
2685 case LFUN_COMPLETION_COMPLETE:
2686 if (d.current_work_area_)
2687 d.current_work_area_->completer().tab();
2690 case LFUN_COMPLETION_CANCEL:
2691 if (d.current_work_area_) {
2692 if (d.current_work_area_->completer().popupVisible())
2693 d.current_work_area_->completer().hidePopup();
2695 d.current_work_area_->completer().hideInline();
2699 case LFUN_COMPLETION_ACCEPT:
2700 if (d.current_work_area_)
2701 d.current_work_area_->completer().activate();
2704 case LFUN_BUFFER_ZOOM_IN:
2705 case LFUN_BUFFER_ZOOM_OUT:
2706 if (cmd.argument().empty()) {
2707 if (cmd.action == LFUN_BUFFER_ZOOM_IN)
2712 lyxrc.zoom += convert<int>(cmd.argument());
2714 if (lyxrc.zoom < 10)
2717 // The global QPixmapCache is used in GuiPainter to cache text
2718 // painting so we must reset it.
2719 QPixmapCache::clear();
2720 guiApp->fontLoader().update();
2721 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
2724 case LFUN_VC_REGISTER:
2725 case LFUN_VC_CHECK_IN:
2726 case LFUN_VC_CHECK_OUT:
2727 case LFUN_VC_LOCKING_TOGGLE:
2728 case LFUN_VC_REVERT:
2729 case LFUN_VC_UNDO_LAST:
2730 case LFUN_VC_COMMAND:
2739 // Part of automatic menu appearance feature.
2740 if (isFullScreen()) {
2741 if (menuBar()->isVisible() && lyxrc.full_screen_menubar)
2743 if (statusBar()->isVisible())
2744 statusBar()->hide();
2751 void GuiView::lfunUiToggle(FuncRequest const & cmd)
2753 string const arg = cmd.getArg(0);
2754 if (arg == "scrollbar") {
2755 // hide() is of no help
2756 if (d.current_work_area_->verticalScrollBarPolicy() ==
2757 Qt::ScrollBarAlwaysOff)
2759 d.current_work_area_->setVerticalScrollBarPolicy(
2760 Qt::ScrollBarAsNeeded);
2762 d.current_work_area_->setVerticalScrollBarPolicy(
2763 Qt::ScrollBarAlwaysOff);
2766 if (arg == "statusbar") {
2767 statusBar()->setVisible(!statusBar()->isVisible());
2770 if (arg == "menubar") {
2771 menuBar()->setVisible(!menuBar()->isVisible());
2774 #if QT_VERSION >= 0x040300
2775 if (arg == "frame") {
2777 getContentsMargins(&l, &t, &r, &b);
2778 //are the frames in default state?
2779 d.current_work_area_->setFrameStyle(QFrame::NoFrame);
2781 setContentsMargins(-2, -2, -2, -2);
2783 setContentsMargins(0, 0, 0, 0);
2788 if (arg == "fullscreen") {
2793 message(bformat("LFUN_UI_TOGGLE " + _("%1$s unknown command!"), from_utf8(arg)));
2797 void GuiView::toggleFullScreen()
2799 if (isFullScreen()) {
2800 for (int i = 0; i != d.splitter_->count(); ++i)
2801 d.tabWorkArea(i)->setFullScreen(false);
2802 #if QT_VERSION >= 0x040300
2803 setContentsMargins(0, 0, 0, 0);
2805 setWindowState(windowState() ^ Qt::WindowFullScreen);
2808 statusBar()->show();
2811 hideDialogs("prefs", 0);
2812 for (int i = 0; i != d.splitter_->count(); ++i)
2813 d.tabWorkArea(i)->setFullScreen(true);
2814 #if QT_VERSION >= 0x040300
2815 setContentsMargins(-2, -2, -2, -2);
2818 setWindowState(windowState() ^ Qt::WindowFullScreen);
2819 statusBar()->hide();
2820 if (lyxrc.full_screen_menubar)
2822 if (lyxrc.full_screen_toolbars) {
2823 ToolbarMap::iterator end = d.toolbars_.end();
2824 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
2829 // give dialogs like the TOC a chance to adapt
2834 Buffer const * GuiView::updateInset(Inset const * inset)
2836 if (!d.current_work_area_)
2840 d.current_work_area_->scheduleRedraw();
2842 return &d.current_work_area_->bufferView().buffer();
2846 void GuiView::restartCursor()
2848 /* When we move around, or type, it's nice to be able to see
2849 * the cursor immediately after the keypress.
2851 if (d.current_work_area_)
2852 d.current_work_area_->startBlinkingCursor();
2854 // Take this occasion to update the other GUI elements.
2860 void GuiView::updateCompletion(Cursor & cur, bool start, bool keep)
2862 if (d.current_work_area_)
2863 d.current_work_area_->completer().updateVisibility(cur, start, keep);
2868 // This list should be kept in sync with the list of insets in
2869 // src/insets/Inset.cpp. I.e., if a dialog goes with an inset, the
2870 // dialog should have the same name as the inset.
2871 // Changes should be also recorded in LFUN_DIALOG_SHOW doxygen
2872 // docs in LyXAction.cpp.
2874 char const * const dialognames[] = {
2875 "aboutlyx", "bibitem", "bibtex", "box", "branch", "changes", "character",
2876 "citation", "document", "errorlist", "ert", "external", "file", "findreplace",
2877 "findreplaceadv", "float", "graphics", "href", "include", "index",
2878 "index_print", "info", "listings", "label", "log", "mathdelimiter",
2879 "mathmatrix", "mathspace", "nomenclature", "nomencl_print", "note",
2880 "paragraph", "phantom", "prefs", "print", "ref", "sendto", "space",
2881 "spellchecker", "symbols", "tabular", "tabularcreate", "thesaurus", "texinfo",
2882 "toc", "view-source", "vspace", "wrap" };
2884 char const * const * const end_dialognames =
2885 dialognames + (sizeof(dialognames) / sizeof(char *));
2889 cmpCStr(char const * name) : name_(name) {}
2890 bool operator()(char const * other) {
2891 return strcmp(other, name_) == 0;
2898 bool isValidName(string const & name)
2900 return find_if(dialognames, end_dialognames,
2901 cmpCStr(name.c_str())) != end_dialognames;
2907 void GuiView::resetDialogs()
2909 // Make sure that no LFUN uses any LyXView.
2910 guiApp->setCurrentView(0);
2913 constructToolbars();
2914 guiApp->menus().fillMenuBar(menuBar(), this, false);
2915 d.layout_->updateContents(true);
2916 // Now update controls with current buffer.
2917 guiApp->setCurrentView(this);
2923 Dialog * GuiView::findOrBuild(string const & name, bool hide_it)
2925 if (!isValidName(name))
2928 map<string, DialogPtr>::iterator it = d.dialogs_.find(name);
2930 if (it != d.dialogs_.end()) {
2932 it->second->hideView();
2933 return it->second.get();
2936 Dialog * dialog = build(name);
2937 d.dialogs_[name].reset(dialog);
2938 if (lyxrc.allow_geometry_session)
2939 dialog->restoreSession();
2946 void GuiView::showDialog(string const & name, string const & data,
2954 Dialog * dialog = findOrBuild(name, false);
2956 dialog->showData(data);
2958 d.open_insets_[name] = inset;
2961 catch (ExceptionMessage const & ex) {
2969 bool GuiView::isDialogVisible(string const & name) const
2971 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
2972 if (it == d.dialogs_.end())
2974 return it->second.get()->isVisibleView() && !it->second.get()->isClosing();
2978 void GuiView::hideDialog(string const & name, Inset * inset)
2980 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
2981 if (it == d.dialogs_.end())
2984 if (inset && inset != getOpenInset(name))
2987 Dialog * const dialog = it->second.get();
2988 if (dialog->isVisibleView())
2990 d.open_insets_[name] = 0;
2994 void GuiView::disconnectDialog(string const & name)
2996 if (!isValidName(name))
2999 if (d.open_insets_.find(name) != d.open_insets_.end())
3000 d.open_insets_[name] = 0;
3004 Inset * GuiView::getOpenInset(string const & name) const
3006 if (!isValidName(name))
3009 map<string, Inset *>::const_iterator it = d.open_insets_.find(name);
3010 return it == d.open_insets_.end() ? 0 : it->second;
3014 void GuiView::hideAll() const
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 it->second->hideView();
3024 void GuiView::updateDialogs()
3026 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
3027 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3029 for(; it != end; ++it) {
3030 Dialog * dialog = it->second.get();
3031 if (dialog && dialog->isVisibleView())
3032 dialog->checkStatus();
3039 // will be replaced by a proper factory...
3040 Dialog * createGuiAbout(GuiView & lv);
3041 Dialog * createGuiBibitem(GuiView & lv);
3042 Dialog * createGuiBibtex(GuiView & lv);
3043 Dialog * createGuiBox(GuiView & lv);
3044 Dialog * createGuiBranch(GuiView & lv);
3045 Dialog * createGuiChanges(GuiView & lv);
3046 Dialog * createGuiCharacter(GuiView & lv);
3047 Dialog * createGuiCitation(GuiView & lv);
3048 Dialog * createGuiDelimiter(GuiView & lv);
3049 Dialog * createGuiDocument(GuiView & lv);
3050 Dialog * createGuiErrorList(GuiView & lv);
3051 Dialog * createGuiERT(GuiView & lv);
3052 Dialog * createGuiExternal(GuiView & lv);
3053 Dialog * createGuiFloat(GuiView & lv);
3054 Dialog * createGuiGraphics(GuiView & lv);
3055 Dialog * createGuiInclude(GuiView & lv);
3056 Dialog * createGuiIndex(GuiView & lv);
3057 Dialog * createGuiInfo(GuiView & lv);
3058 Dialog * createGuiLabel(GuiView & lv);
3059 Dialog * createGuiListings(GuiView & lv);
3060 Dialog * createGuiLog(GuiView & lv);
3061 Dialog * createGuiMathHSpace(GuiView & lv);
3062 Dialog * createGuiMathMatrix(GuiView & lv);
3063 Dialog * createGuiNomenclature(GuiView & lv);
3064 Dialog * createGuiNote(GuiView & lv);
3065 Dialog * createGuiParagraph(GuiView & lv);
3066 Dialog * createGuiPhantom(GuiView & lv);
3067 Dialog * createGuiPreferences(GuiView & lv);
3068 Dialog * createGuiPrint(GuiView & lv);
3069 Dialog * createGuiPrintindex(GuiView & lv);
3070 Dialog * createGuiPrintNomencl(GuiView & lv);
3071 Dialog * createGuiRef(GuiView & lv);
3072 Dialog * createGuiSearch(GuiView & lv);
3073 Dialog * createGuiSearchAdv(GuiView & lv);
3074 Dialog * createGuiSendTo(GuiView & lv);
3075 Dialog * createGuiShowFile(GuiView & lv);
3076 Dialog * createGuiSpellchecker(GuiView & lv);
3077 Dialog * createGuiSymbols(GuiView & lv);
3078 Dialog * createGuiTabularCreate(GuiView & lv);
3079 Dialog * createGuiTabular(GuiView & lv);
3080 Dialog * createGuiTexInfo(GuiView & lv);
3081 Dialog * createGuiTextHSpace(GuiView & lv);
3082 Dialog * createGuiToc(GuiView & lv);
3083 Dialog * createGuiThesaurus(GuiView & lv);
3084 Dialog * createGuiHyperlink(GuiView & lv);
3085 Dialog * createGuiVSpace(GuiView & lv);
3086 Dialog * createGuiViewSource(GuiView & lv);
3087 Dialog * createGuiWrap(GuiView & lv);
3090 Dialog * GuiView::build(string const & name)
3092 LASSERT(isValidName(name), return 0);
3094 if (name == "aboutlyx")
3095 return createGuiAbout(*this);
3096 if (name == "bibitem")
3097 return createGuiBibitem(*this);
3098 if (name == "bibtex")
3099 return createGuiBibtex(*this);
3101 return createGuiBox(*this);
3102 if (name == "branch")
3103 return createGuiBranch(*this);
3104 if (name == "changes")
3105 return createGuiChanges(*this);
3106 if (name == "character")
3107 return createGuiCharacter(*this);
3108 if (name == "citation")
3109 return createGuiCitation(*this);
3110 if (name == "document")
3111 return createGuiDocument(*this);
3112 if (name == "errorlist")
3113 return createGuiErrorList(*this);
3115 return createGuiERT(*this);
3116 if (name == "external")
3117 return createGuiExternal(*this);
3119 return createGuiShowFile(*this);
3120 if (name == "findreplace")
3121 return createGuiSearch(*this);
3122 if (name == "findreplaceadv")
3123 return createGuiSearchAdv(*this);
3124 if (name == "float")
3125 return createGuiFloat(*this);
3126 if (name == "graphics")
3127 return createGuiGraphics(*this);
3129 return createGuiHyperlink(*this);
3130 if (name == "include")
3131 return createGuiInclude(*this);
3132 if (name == "index")
3133 return createGuiIndex(*this);
3134 if (name == "index_print")
3135 return createGuiPrintindex(*this);
3137 return createGuiInfo(*this);
3138 if (name == "label")
3139 return createGuiLabel(*this);
3140 if (name == "listings")
3141 return createGuiListings(*this);
3143 return createGuiLog(*this);
3144 if (name == "mathdelimiter")
3145 return createGuiDelimiter(*this);
3146 if (name == "mathspace")
3147 return createGuiMathHSpace(*this);
3148 if (name == "mathmatrix")
3149 return createGuiMathMatrix(*this);
3150 if (name == "nomenclature")
3151 return createGuiNomenclature(*this);
3152 if (name == "nomencl_print")
3153 return createGuiPrintNomencl(*this);
3155 return createGuiNote(*this);
3156 if (name == "paragraph")
3157 return createGuiParagraph(*this);
3158 if (name == "phantom")
3159 return createGuiPhantom(*this);
3160 if (name == "prefs")
3161 return createGuiPreferences(*this);
3162 if (name == "print")
3163 return createGuiPrint(*this);
3165 return createGuiRef(*this);
3166 if (name == "sendto")
3167 return createGuiSendTo(*this);
3168 if (name == "space")
3169 return createGuiTextHSpace(*this);
3170 if (name == "spellchecker")
3171 return createGuiSpellchecker(*this);
3172 if (name == "symbols")
3173 return createGuiSymbols(*this);
3174 if (name == "tabular")
3175 return createGuiTabular(*this);
3176 if (name == "tabularcreate")
3177 return createGuiTabularCreate(*this);
3178 if (name == "texinfo")
3179 return createGuiTexInfo(*this);
3180 if (name == "thesaurus")
3181 return createGuiThesaurus(*this);
3183 return createGuiToc(*this);
3184 if (name == "view-source")
3185 return createGuiViewSource(*this);
3186 if (name == "vspace")
3187 return createGuiVSpace(*this);
3189 return createGuiWrap(*this);
3195 } // namespace frontend
3198 #include "moc_GuiView.cpp"