3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Lars Gullik Bjønnes
8 * \author Abdelrazak Younes
11 * Full author contact details are available in file CREDITS.
19 #include "FileDialog.h"
20 #include "FontLoader.h"
21 #include "GuiApplication.h"
22 #include "GuiCommandBuffer.h"
23 #include "GuiCompleter.h"
24 #include "GuiWorkArea.h"
25 #include "GuiKeySymbol.h"
27 #include "GuiToolbar.h"
28 #include "LayoutBox.h"
32 #include "qt_helpers.h"
34 #include "frontends/alert.h"
36 #include "buffer_funcs.h"
38 #include "BufferList.h"
39 #include "BufferParams.h"
40 #include "BufferView.h"
41 #include "Converter.h"
43 #include "CutAndPaste.h"
45 #include "ErrorList.h"
47 #include "FuncStatus.h"
48 #include "FuncRequest.h"
52 #include "LyXAction.h"
57 #include "Paragraph.h"
58 #include "SpellChecker.h"
59 #include "TextClass.h"
64 #include "support/convert.h"
65 #include "support/debug.h"
66 #include "support/ExceptionMessage.h"
67 #include "support/FileName.h"
68 #include "support/filetools.h"
69 #include "support/gettext.h"
70 #include "support/filetools.h"
71 #include "support/ForkedCalls.h"
72 #include "support/lassert.h"
73 #include "support/lstrings.h"
74 #include "support/os.h"
75 #include "support/Package.h"
76 #include "support/Path.h"
77 #include "support/Systemcall.h"
78 #include "support/Timeout.h"
81 #include <QApplication>
82 #include <QCloseEvent>
84 #include <QDesktopWidget>
85 #include <QDragEnterEvent>
92 #include <QPixmapCache>
94 #include <QPushButton>
98 #include <QStackedWidget>
103 #include <QScrollBar>
105 #include <boost/bind.hpp>
109 #ifdef HAVE_SYS_TIME_H
110 # include <sys/time.h>
117 using namespace lyx::support;
124 class BackgroundWidget : public QWidget
129 LYXERR(Debug::GUI, "show banner: " << lyxrc.show_banner);
130 /// The text to be written on top of the pixmap
131 QString const text = lyx_version ?
132 qt_("version ") + lyx_version : qt_("unknown version");
133 splash_ = getPixmap("images/", "banner", "png");
135 QPainter pain(&splash_);
136 pain.setPen(QColor(0, 0, 0));
138 // The font used to display the version info
139 font.setStyleHint(QFont::SansSerif);
140 font.setWeight(QFont::Bold);
141 font.setPointSize(int(toqstr(lyxrc.font_sizes[FONT_SIZE_LARGE]).toDouble()));
143 pain.drawText(260, 15, text);
146 void paintEvent(QPaintEvent *)
148 int x = (width() - splash_.width()) / 2;
149 int y = (height() - splash_.height()) / 2;
151 pain.drawPixmap(x, y, splash_);
159 /// Toolbar store providing access to individual toolbars by name.
160 typedef std::map<std::string, GuiToolbar *> ToolbarMap;
162 typedef boost::shared_ptr<Dialog> DialogPtr;
167 struct GuiView::GuiViewPrivate
170 : current_work_area_(0), current_main_work_area_(0),
171 layout_(0), autosave_timeout_(5000),
174 // hardcode here the platform specific icon size
175 smallIconSize = 14; // scaling problems
176 normalIconSize = 20; // ok, default
177 bigIconSize = 26; // better for some math icons
179 splitter_ = new QSplitter;
180 bg_widget_ = new BackgroundWidget;
181 stack_widget_ = new QStackedWidget;
182 stack_widget_->addWidget(bg_widget_);
183 stack_widget_->addWidget(splitter_);
191 delete stack_widget_;
194 QMenu * toolBarPopup(GuiView * parent)
196 // FIXME: translation
197 QMenu * menu = new QMenu(parent);
198 QActionGroup * iconSizeGroup = new QActionGroup(parent);
200 QAction * smallIcons = new QAction(iconSizeGroup);
201 smallIcons->setText(qt_("Small-sized icons"));
202 smallIcons->setCheckable(true);
203 QObject::connect(smallIcons, SIGNAL(triggered()),
204 parent, SLOT(smallSizedIcons()));
205 menu->addAction(smallIcons);
207 QAction * normalIcons = new QAction(iconSizeGroup);
208 normalIcons->setText(qt_("Normal-sized icons"));
209 normalIcons->setCheckable(true);
210 QObject::connect(normalIcons, SIGNAL(triggered()),
211 parent, SLOT(normalSizedIcons()));
212 menu->addAction(normalIcons);
214 QAction * bigIcons = new QAction(iconSizeGroup);
215 bigIcons->setText(qt_("Big-sized icons"));
216 bigIcons->setCheckable(true);
217 QObject::connect(bigIcons, SIGNAL(triggered()),
218 parent, SLOT(bigSizedIcons()));
219 menu->addAction(bigIcons);
221 unsigned int cur = parent->iconSize().width();
222 if ( cur == parent->d.smallIconSize)
223 smallIcons->setChecked(true);
224 else if (cur == parent->d.normalIconSize)
225 normalIcons->setChecked(true);
226 else if (cur == parent->d.bigIconSize)
227 bigIcons->setChecked(true);
234 stack_widget_->setCurrentWidget(bg_widget_);
235 bg_widget_->setUpdatesEnabled(true);
238 TabWorkArea * tabWorkArea(int i)
240 return dynamic_cast<TabWorkArea *>(splitter_->widget(i));
243 TabWorkArea * currentTabWorkArea()
245 if (splitter_->count() == 1)
246 // The first TabWorkArea is always the first one, if any.
247 return tabWorkArea(0);
249 for (int i = 0; i != splitter_->count(); ++i) {
250 TabWorkArea * twa = tabWorkArea(i);
251 if (current_main_work_area_ == twa->currentWorkArea())
255 // None has the focus so we just take the first one.
256 return tabWorkArea(0);
260 GuiWorkArea * current_work_area_;
261 GuiWorkArea * current_main_work_area_;
262 QSplitter * splitter_;
263 QStackedWidget * stack_widget_;
264 BackgroundWidget * bg_widget_;
266 ToolbarMap toolbars_;
267 /// The main layout box.
269 * \warning Don't Delete! The layout box is actually owned by
270 * whichever toolbar contains it. All the GuiView class needs is a
271 * means of accessing it.
273 * FIXME: replace that with a proper model so that we are not limited
274 * to only one dialog.
279 map<string, DialogPtr> dialogs_;
281 unsigned int smallIconSize;
282 unsigned int normalIconSize;
283 unsigned int bigIconSize;
285 QTimer statusbar_timer_;
286 /// auto-saving of buffers
287 Timeout autosave_timeout_;
288 /// flag against a race condition due to multiclicks, see bug #1119
292 TocModels toc_models_;
296 GuiView::GuiView(int id)
297 : d(*new GuiViewPrivate), id_(id), closing_(false)
299 // GuiToolbars *must* be initialised before the menu bar.
300 normalSizedIcons(); // at least on Mac the default is 32 otherwise, which is huge
303 // set ourself as the current view. This is needed for the menu bar
304 // filling, at least for the static special menu item on Mac. Otherwise
305 // they are greyed out.
306 guiApp->setCurrentView(this);
308 // Fill up the menu bar.
309 guiApp->menus().fillMenuBar(menuBar(), this, true);
311 setCentralWidget(d.stack_widget_);
313 // Start autosave timer
314 if (lyxrc.autosave) {
315 d.autosave_timeout_.timeout.connect(boost::bind(&GuiView::autoSave, this));
316 d.autosave_timeout_.setTimeout(lyxrc.autosave * 1000);
317 d.autosave_timeout_.start();
319 connect(&d.statusbar_timer_, SIGNAL(timeout()),
320 this, SLOT(clearMessage()));
322 // We don't want to keep the window in memory if it is closed.
323 setAttribute(Qt::WA_DeleteOnClose, true);
325 #if (!defined(Q_WS_WIN) && !defined(Q_WS_MACX))
326 // assign an icon to main form. We do not do it under Qt/Win or Qt/Mac,
327 // since the icon is provided in the application bundle.
328 setWindowIcon(getPixmap("images/", "lyx", "png"));
332 setAcceptDrops(true);
334 statusBar()->setSizeGripEnabled(true);
336 // Forbid too small unresizable window because it can happen
337 // with some window manager under X11.
338 setMinimumSize(300, 200);
340 if (lyxrc.allow_geometry_session) {
341 // Now take care of session management.
346 // no session handling, default to a sane size.
347 setGeometry(50, 50, 690, 510);
350 // clear session data if any.
352 settings.remove("views");
362 void GuiView::saveLayout() const
365 settings.beginGroup("views");
366 settings.beginGroup(QString::number(id_));
368 settings.setValue("pos", pos());
369 settings.setValue("size", size());
371 settings.setValue("geometry", saveGeometry());
373 settings.setValue("layout", saveState(0));
374 settings.setValue("icon_size", iconSize());
378 bool GuiView::restoreLayout()
381 settings.beginGroup("views");
382 settings.beginGroup(QString::number(id_));
383 QString const icon_key = "icon_size";
384 if (!settings.contains(icon_key))
387 //code below is skipped when when ~/.config/LyX is (re)created
388 setIconSize(settings.value(icon_key).toSize());
390 QPoint pos = settings.value("pos", QPoint(50, 50)).toPoint();
391 QSize size = settings.value("size", QSize(690, 510)).toSize();
395 // Work-around for bug #6034: the window ends up in an undetermined
396 // state when trying to restore a maximized window when it is
397 // already maximized.
398 if (!(windowState() & Qt::WindowMaximized))
399 if (!restoreGeometry(settings.value("geometry").toByteArray()))
400 setGeometry(50, 50, 690, 510);
402 // Make sure layout is correctly oriented.
403 setLayoutDirection(qApp->layoutDirection());
405 // Allow the toc and view-source dock widget to be restored if needed.
407 if ((dialog = findOrBuild("toc", true)))
408 // see bug 5082. At least setup title and enabled state.
409 // Visibility will be adjusted by restoreState below.
410 dialog->prepareView();
411 if ((dialog = findOrBuild("view-source", true)))
412 dialog->prepareView();
414 if (!restoreState(settings.value("layout").toByteArray(), 0))
421 GuiToolbar * GuiView::toolbar(string const & name)
423 ToolbarMap::iterator it = d.toolbars_.find(name);
424 if (it != d.toolbars_.end())
427 LYXERR(Debug::GUI, "Toolbar::display: no toolbar named " << name);
428 message(bformat(_("Unknown toolbar \"%1$s\""), from_utf8(name)));
433 void GuiView::constructToolbars()
435 ToolbarMap::iterator it = d.toolbars_.begin();
436 for (; it != d.toolbars_.end(); ++it)
440 // I don't like doing this here, but the standard toolbar
441 // destroys this object when it's destroyed itself (vfr)
442 d.layout_ = new LayoutBox(*this);
443 d.stack_widget_->addWidget(d.layout_);
444 d.layout_->move(0,0);
446 // extracts the toolbars from the backend
447 Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
448 Toolbars::Infos::iterator end = guiApp->toolbars().end();
449 for (; cit != end; ++cit)
450 d.toolbars_[cit->name] = new GuiToolbar(*cit, *this);
454 void GuiView::initToolbars()
456 // extracts the toolbars from the backend
457 Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
458 Toolbars::Infos::iterator end = guiApp->toolbars().end();
459 for (; cit != end; ++cit) {
460 GuiToolbar * tb = toolbar(cit->name);
463 int const visibility = guiApp->toolbars().defaultVisibility(cit->name);
465 tb->setVisible(false);
466 tb->setVisibility(visibility);
468 if (visibility & Toolbars::TOP) {
470 addToolBarBreak(Qt::TopToolBarArea);
471 addToolBar(Qt::TopToolBarArea, tb);
474 if (visibility & Toolbars::BOTTOM) {
475 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
476 #if (QT_VERSION >= 0x040202)
477 addToolBarBreak(Qt::BottomToolBarArea);
479 addToolBar(Qt::BottomToolBarArea, tb);
482 if (visibility & Toolbars::LEFT) {
483 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
484 #if (QT_VERSION >= 0x040202)
485 addToolBarBreak(Qt::LeftToolBarArea);
487 addToolBar(Qt::LeftToolBarArea, tb);
490 if (visibility & Toolbars::RIGHT) {
491 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
492 #if (QT_VERSION >= 0x040202)
493 addToolBarBreak(Qt::RightToolBarArea);
495 addToolBar(Qt::RightToolBarArea, tb);
498 if (visibility & Toolbars::ON)
499 tb->setVisible(true);
504 TocModels & GuiView::tocModels()
506 return d.toc_models_;
510 void GuiView::setFocus()
512 LYXERR(Debug::DEBUG, "GuiView::setFocus()" << this);
513 // Make sure LyXFunc points to the correct view.
514 guiApp->setCurrentView(this);
515 QMainWindow::setFocus();
516 if (d.current_work_area_)
517 d.current_work_area_->setFocus();
521 QMenu * GuiView::createPopupMenu()
523 return d.toolBarPopup(this);
527 void GuiView::showEvent(QShowEvent * e)
529 LYXERR(Debug::GUI, "Passed Geometry "
530 << size().height() << "x" << size().width()
531 << "+" << pos().x() << "+" << pos().y());
533 if (d.splitter_->count() == 0)
534 // No work area, switch to the background widget.
537 QMainWindow::showEvent(e);
541 /** Destroy only all tabbed WorkAreas. Destruction of other WorkAreas
542 ** is responsibility of the container (e.g., dialog)
544 void GuiView::closeEvent(QCloseEvent * close_event)
546 LYXERR(Debug::DEBUG, "GuiView::closeEvent()");
551 // it can happen that this event arrives without selecting the view,
552 // e.g. when clicking the close button on a background window.
554 if (!closeWorkAreaAll()) {
556 close_event->ignore();
560 // Make sure that nothing will use this to be closed View.
561 guiApp->unregisterView(this);
563 if (isFullScreen()) {
564 // Switch off fullscreen before closing.
569 // Make sure the timer time out will not trigger a statusbar update.
570 d.statusbar_timer_.stop();
572 // Saving fullscreen requires additional tweaks in the toolbar code.
573 // It wouldn't also work under linux natively.
574 if (lyxrc.allow_geometry_session) {
575 // Save this window geometry and layout.
577 // Then the toolbar private states.
578 ToolbarMap::iterator end = d.toolbars_.end();
579 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
580 it->second->saveSession();
581 // Now take care of all other dialogs:
582 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
583 for (; it!= d.dialogs_.end(); ++it)
584 it->second->saveSession();
587 close_event->accept();
591 void GuiView::dragEnterEvent(QDragEnterEvent * event)
593 if (event->mimeData()->hasUrls())
595 /// \todo Ask lyx-devel is this is enough:
596 /// if (event->mimeData()->hasFormat("text/plain"))
597 /// event->acceptProposedAction();
601 void GuiView::dropEvent(QDropEvent * event)
603 QList<QUrl> files = event->mimeData()->urls();
607 LYXERR(Debug::GUI, "GuiView::dropEvent: got URLs!");
608 for (int i = 0; i != files.size(); ++i) {
609 string const file = os::internal_path(fromqstr(
610 files.at(i).toLocalFile()));
612 // Asynchronously post the event. DropEvent usually come
613 // from the BufferView. But reloading a file might close
614 // the BufferView from within its own event handler.
615 guiApp->dispatchDelayed(FuncRequest(LFUN_FILE_OPEN, file));
622 void GuiView::message(docstring const & str)
624 if (ForkedProcess::iAmAChild())
627 statusBar()->showMessage(toqstr(str));
628 d.statusbar_timer_.stop();
629 d.statusbar_timer_.start(3000);
633 void GuiView::smallSizedIcons()
635 setIconSize(QSize(d.smallIconSize, d.smallIconSize));
639 void GuiView::normalSizedIcons()
641 setIconSize(QSize(d.normalIconSize, d.normalIconSize));
645 void GuiView::bigSizedIcons()
647 setIconSize(QSize(d.bigIconSize, d.bigIconSize));
651 void GuiView::clearMessage()
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::event(QEvent * e)
740 // Useful debug code:
741 //case QEvent::ActivationChange:
742 //case QEvent::WindowDeactivate:
743 //case QEvent::Paint:
744 //case QEvent::Enter:
745 //case QEvent::Leave:
746 //case QEvent::HoverEnter:
747 //case QEvent::HoverLeave:
748 //case QEvent::HoverMove:
749 //case QEvent::StatusTip:
750 //case QEvent::DragEnter:
751 //case QEvent::DragLeave:
755 case QEvent::WindowActivate: {
756 GuiView * old_view = guiApp->currentView();
757 if (this == old_view) {
759 return QMainWindow::event(e);
761 if (old_view && old_view->currentBufferView()) {
762 // save current selection to the selection buffer to allow
763 // middle-button paste in this window.
764 cap::saveSelection(old_view->currentBufferView()->cursor());
766 guiApp->setCurrentView(this);
767 if (d.current_work_area_) {
768 BufferView & bv = d.current_work_area_->bufferView();
769 connectBufferView(bv);
770 connectBuffer(bv.buffer());
771 // The document structure, name and dialogs might have
772 // changed in another view.
774 // The document settings needs to be reinitialised.
775 updateDialog("document", "");
778 resetWindowTitleAndIconText();
781 return QMainWindow::event(e);
784 case QEvent::ShortcutOverride: {
787 #if (!defined Q_WS_X11) || (QT_VERSION >= 0x040500)
788 if (isFullScreen() && menuBar()->isHidden()) {
789 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
790 // FIXME: we should also try to detect special LyX shortcut such as
791 // Alt-P and Alt-M. Right now there is a hack in
792 // GuiWorkArea::processKeySym() that hides again the menubar for
794 if (ke->modifiers() & Qt::AltModifier && ke->key() != Qt::Key_Alt) {
796 return QMainWindow::event(e);
801 if (d.current_work_area_)
802 // Nothing special to do.
803 return QMainWindow::event(e);
805 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
806 // Let Qt handle menu access and the Tab keys to navigate keys to navigate
808 if (ke->modifiers() & Qt::AltModifier || ke->key() == Qt::Key_Tab
809 || ke->key() == Qt::Key_Backtab)
810 return QMainWindow::event(e);
812 // Allow processing of shortcuts that are allowed even when no Buffer
815 setKeySymbol(&sym, ke);
816 theLyXFunc().processKeySym(sym, q_key_state(ke->modifiers()));
822 return QMainWindow::event(e);
826 void GuiView::resetWindowTitleAndIconText()
828 setWindowTitle(qt_("LyX"));
829 setWindowIconText(qt_("LyX"));
832 bool GuiView::focusNextPrevChild(bool /*next*/)
839 void GuiView::setBusy(bool busy)
841 if (d.current_work_area_) {
842 d.current_work_area_->setUpdatesEnabled(!busy);
844 d.current_work_area_->stopBlinkingCursor();
846 d.current_work_area_->startBlinkingCursor();
850 QApplication::setOverrideCursor(Qt::WaitCursor);
852 QApplication::restoreOverrideCursor();
856 GuiWorkArea * GuiView::workArea(Buffer & buffer)
858 if (currentWorkArea()
859 && ¤tWorkArea()->bufferView().buffer() == &buffer)
860 return (GuiWorkArea *) currentWorkArea();
861 if (TabWorkArea * twa = d.currentTabWorkArea())
862 return twa->workArea(buffer);
867 GuiWorkArea * GuiView::addWorkArea(Buffer & buffer)
869 // Automatically create a TabWorkArea if there are none yet.
870 TabWorkArea * tab_widget = d.splitter_->count()
871 ? d.currentTabWorkArea() : addTabWorkArea();
872 return tab_widget->addWorkArea(buffer, *this);
876 TabWorkArea * GuiView::addTabWorkArea()
878 TabWorkArea * twa = new TabWorkArea;
879 QObject::connect(twa, SIGNAL(currentWorkAreaChanged(GuiWorkArea *)),
880 this, SLOT(on_currentWorkAreaChanged(GuiWorkArea *)));
881 QObject::connect(twa, SIGNAL(lastWorkAreaRemoved()),
882 this, SLOT(on_lastWorkAreaRemoved()));
884 d.splitter_->addWidget(twa);
885 d.stack_widget_->setCurrentWidget(d.splitter_);
890 GuiWorkArea const * GuiView::currentWorkArea() const
892 return d.current_work_area_;
896 GuiWorkArea * GuiView::currentWorkArea()
898 return d.current_work_area_;
902 GuiWorkArea const * GuiView::currentMainWorkArea() const
904 if (d.currentTabWorkArea() == NULL)
906 return d.currentTabWorkArea()->currentWorkArea();
910 GuiWorkArea * GuiView::currentMainWorkArea()
912 if (d.currentTabWorkArea() == NULL)
914 return d.currentTabWorkArea()->currentWorkArea();
918 void GuiView::setCurrentWorkArea(GuiWorkArea * wa)
920 LYXERR(Debug::DEBUG, "Setting current wa: " << wa << endl);
922 d.current_work_area_ = NULL;
926 GuiWorkArea * old_gwa = theGuiApp()->currentView()->currentWorkArea();
930 if (currentBufferView())
931 cap::saveSelection(currentBufferView()->cursor());
933 theGuiApp()->setCurrentView(this);
934 d.current_work_area_ = wa;
935 for (int i = 0; i != d.splitter_->count(); ++i) {
936 if (d.tabWorkArea(i)->setCurrentWorkArea(wa)) {
937 //if (d.current_main_work_area_)
938 // d.current_main_work_area_->setFrameStyle(QFrame::NoFrame);
939 d.current_main_work_area_ = wa;
940 //d.current_main_work_area_->setFrameStyle(QFrame::Box | QFrame::Plain);
941 //d.current_main_work_area_->setLineWidth(2);
942 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() << ", Current main wa: " << currentMainWorkArea());
946 LYXERR(Debug::DEBUG, "This is not a tabbed wa");
947 on_currentWorkAreaChanged(wa);
948 BufferView & bv = wa->bufferView();
949 bv.cursor().fixIfBroken();
951 wa->setUpdatesEnabled(true);
952 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() << ", Current main wa: " << currentMainWorkArea());
956 void GuiView::removeWorkArea(GuiWorkArea * wa)
959 if (wa == d.current_work_area_) {
961 disconnectBufferView();
962 d.current_work_area_ = 0;
963 d.current_main_work_area_ = 0;
966 bool found_twa = false;
967 for (int i = 0; i != d.splitter_->count(); ++i) {
968 TabWorkArea * twa = d.tabWorkArea(i);
969 if (twa->removeWorkArea(wa)) {
970 // Found in this tab group, and deleted the GuiWorkArea.
972 if (twa->count() != 0) {
973 if (d.current_work_area_ == 0)
974 // This means that we are closing the current GuiWorkArea, so
975 // switch to the next GuiWorkArea in the found TabWorkArea.
976 setCurrentWorkArea(twa->currentWorkArea());
978 // No more WorkAreas in this tab group, so delete it.
985 // It is not a tabbed work area (i.e., the search work area), so it
986 // should be deleted by other means.
987 LASSERT(found_twa, /* */);
989 if (d.current_work_area_ == 0) {
990 if (d.splitter_->count() != 0) {
991 TabWorkArea * twa = d.currentTabWorkArea();
992 setCurrentWorkArea(twa->currentWorkArea());
994 // No more work areas, switch to the background widget.
995 setCurrentWorkArea(0);
1001 LayoutBox * GuiView::getLayoutDialog() const
1007 void GuiView::updateLayoutList()
1010 d.layout_->updateContents(false);
1014 void GuiView::updateToolbars()
1016 ToolbarMap::iterator end = d.toolbars_.end();
1017 if (d.current_work_area_) {
1019 d.current_work_area_->bufferView().cursor().inMathed();
1021 lyx::getStatus(FuncRequest(LFUN_LAYOUT_TABULAR)).enabled();
1023 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).enabled() &&
1024 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).onoff(true);
1025 bool const mathmacrotemplate =
1026 lyx::getStatus(FuncRequest(LFUN_IN_MATHMACROTEMPLATE)).enabled();
1028 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1029 it->second->update(math, table, review, mathmacrotemplate);
1031 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1032 it->second->update(false, false, false, false);
1036 void GuiView::setBuffer(Buffer * newBuffer)
1038 LYXERR(Debug::DEBUG, "Setting buffer: " << newBuffer << std::endl);
1039 LASSERT(newBuffer, return);
1042 GuiWorkArea * wa = workArea(*newBuffer);
1044 newBuffer->masterBuffer()->updateLabels();
1045 wa = addWorkArea(*newBuffer);
1047 //Disconnect the old buffer...there's no new one.
1050 connectBuffer(*newBuffer);
1051 connectBufferView(wa->bufferView());
1052 setCurrentWorkArea(wa);
1058 void GuiView::connectBuffer(Buffer & buf)
1060 buf.setGuiDelegate(this);
1064 void GuiView::disconnectBuffer()
1066 if (d.current_work_area_)
1067 d.current_work_area_->bufferView().buffer().setGuiDelegate(0);
1071 void GuiView::connectBufferView(BufferView & bv)
1073 bv.setGuiDelegate(this);
1077 void GuiView::disconnectBufferView()
1079 if (d.current_work_area_)
1080 d.current_work_area_->bufferView().setGuiDelegate(0);
1084 void GuiView::errors(string const & error_type, bool from_master)
1086 ErrorList & el = from_master ?
1087 documentBufferView()->buffer().masterBuffer()->errorList(error_type)
1088 : documentBufferView()->buffer().errorList(error_type);
1089 string data = error_type;
1091 data = "from_master|" + error_type;
1093 showDialog("errorlist", data);
1097 void GuiView::updateTocItem(std::string const & type, DocIterator const & dit)
1099 d.toc_models_.updateItem(toqstr(type), dit);
1103 void GuiView::structureChanged()
1105 d.toc_models_.reset(documentBufferView());
1106 // Navigator needs more than a simple update in this case. It needs to be
1108 updateDialog("toc", "");
1112 void GuiView::updateDialog(string const & name, string const & data)
1114 if (!isDialogVisible(name))
1117 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
1118 if (it == d.dialogs_.end())
1121 Dialog * const dialog = it->second.get();
1122 if (dialog->isVisibleView())
1123 dialog->initialiseParams(data);
1127 BufferView * GuiView::documentBufferView()
1129 return currentMainWorkArea()
1130 ? ¤tMainWorkArea()->bufferView()
1135 BufferView const * GuiView::documentBufferView() const
1137 return currentMainWorkArea()
1138 ? ¤tMainWorkArea()->bufferView()
1143 BufferView * GuiView::currentBufferView()
1145 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1149 BufferView const * GuiView::currentBufferView() const
1151 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1155 void GuiView::autoSave()
1157 LYXERR(Debug::INFO, "Running autoSave()");
1159 if (documentBufferView())
1160 documentBufferView()->buffer().autoSave();
1164 void GuiView::resetAutosaveTimers()
1167 d.autosave_timeout_.restart();
1171 bool GuiView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1174 Buffer * buf = currentBufferView()
1175 ? ¤tBufferView()->buffer() : 0;
1176 Buffer * doc_buffer = documentBufferView()
1177 ? &(documentBufferView()->buffer()) : 0;
1179 // Check whether we need a buffer
1180 if (!lyxaction.funcHasFlag(cmd.action, LyXAction::NoBuffer) && !buf) {
1181 // no, exit directly
1182 flag.message(from_utf8(N_("Command not allowed with"
1183 "out any document open")));
1184 flag.setEnabled(false);
1188 if (cmd.origin == FuncRequest::TOC) {
1189 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
1191 if (toc->getStatus(documentBufferView()->cursor(), cmd, fs))
1194 flag.setEnabled(false);
1198 switch(cmd.action) {
1199 case LFUN_BUFFER_IMPORT:
1202 case LFUN_BUFFER_RELOAD:
1203 enable = doc_buffer && !doc_buffer->isUnnamed()
1204 && doc_buffer->fileName().exists()
1205 && (!doc_buffer->isClean()
1206 || doc_buffer->isExternallyModified(Buffer::timestamp_method));
1209 case LFUN_BUFFER_CHILD_OPEN:
1210 enable = doc_buffer;
1213 case LFUN_BUFFER_WRITE:
1214 enable = doc_buffer && (doc_buffer->isUnnamed() || !doc_buffer->isClean());
1217 //FIXME: This LFUN should be moved to GuiApplication.
1218 case LFUN_BUFFER_WRITE_ALL: {
1219 // We enable the command only if there are some modified buffers
1220 Buffer * first = theBufferList().first();
1225 // We cannot use a for loop as the buffer list is a cycle.
1227 if (!b->isClean()) {
1231 b = theBufferList().next(b);
1232 } while (b != first);
1236 case LFUN_BUFFER_WRITE_AS:
1237 enable = doc_buffer;
1240 case LFUN_BUFFER_CLOSE:
1241 enable = doc_buffer;
1244 case LFUN_BUFFER_CLOSE_ALL:
1245 enable = theBufferList().last() != theBufferList().first();
1248 case LFUN_SPLIT_VIEW:
1249 if (cmd.getArg(0) == "vertical")
1250 enable = doc_buffer && (d.splitter_->count() == 1 ||
1251 d.splitter_->orientation() == Qt::Vertical);
1253 enable = doc_buffer && (d.splitter_->count() == 1 ||
1254 d.splitter_->orientation() == Qt::Horizontal);
1257 case LFUN_CLOSE_TAB_GROUP:
1258 enable = d.currentTabWorkArea();
1261 case LFUN_TOOLBAR_TOGGLE:
1262 if (GuiToolbar * t = toolbar(cmd.getArg(0)))
1263 flag.setOnOff(t->isVisible());
1266 case LFUN_UI_TOGGLE:
1267 flag.setOnOff(isFullScreen());
1270 case LFUN_DIALOG_DISCONNECT_INSET:
1273 case LFUN_DIALOG_HIDE:
1274 // FIXME: should we check if the dialog is shown?
1277 case LFUN_DIALOG_TOGGLE:
1278 flag.setOnOff(isDialogVisible(cmd.getArg(0)));
1279 // fall through to set "enable"
1280 case LFUN_DIALOG_SHOW: {
1281 string const name = cmd.getArg(0);
1283 enable = name == "aboutlyx"
1284 || name == "file" //FIXME: should be removed.
1286 || name == "texinfo";
1287 else if (name == "print")
1288 enable = doc_buffer->isExportable("dvi")
1289 && lyxrc.print_command != "none";
1290 else if (name == "character" || name == "symbols") {
1291 if (!buf || buf->isReadonly()
1292 || !currentBufferView()->cursor().inTexted())
1295 // FIXME we should consider passthru
1297 Inset const & in = currentBufferView()->cursor().inset();
1298 enable = !in.getLayout().isPassThru();
1301 else if (name == "latexlog")
1302 enable = FileName(doc_buffer->logName()).isReadableFile();
1303 else if (name == "spellchecker")
1304 enable = theSpellChecker() && !doc_buffer->isReadonly();
1305 else if (name == "vclog")
1306 enable = doc_buffer->lyxvc().inUse();
1310 case LFUN_DIALOG_UPDATE: {
1311 string const name = cmd.getArg(0);
1313 enable = name == "prefs";
1317 case LFUN_COMMAND_EXECUTE:
1319 case LFUN_MENU_OPEN:
1320 // Nothing to check.
1323 case LFUN_COMPLETION_INLINE:
1324 if (!d.current_work_area_
1325 || !d.current_work_area_->completer().inlinePossible(
1326 currentBufferView()->cursor()))
1330 case LFUN_COMPLETION_POPUP:
1331 if (!d.current_work_area_
1332 || !d.current_work_area_->completer().popupPossible(
1333 currentBufferView()->cursor()))
1337 case LFUN_COMPLETION_COMPLETE:
1338 if (!d.current_work_area_
1339 || !d.current_work_area_->completer().inlinePossible(
1340 currentBufferView()->cursor()))
1344 case LFUN_COMPLETION_ACCEPT:
1345 if (!d.current_work_area_
1346 || (!d.current_work_area_->completer().popupVisible()
1347 && !d.current_work_area_->completer().inlineVisible()
1348 && !d.current_work_area_->completer().completionAvailable()))
1352 case LFUN_COMPLETION_CANCEL:
1353 if (!d.current_work_area_
1354 || (!d.current_work_area_->completer().popupVisible()
1355 && !d.current_work_area_->completer().inlineVisible()))
1359 case LFUN_BUFFER_ZOOM_OUT:
1360 enable = doc_buffer && lyxrc.zoom > 10;
1363 case LFUN_BUFFER_ZOOM_IN:
1364 enable = doc_buffer;
1367 case LFUN_BUFFER_NEXT:
1368 case LFUN_BUFFER_PREVIOUS:
1369 // FIXME: should we check is there is an previous or next buffer?
1371 case LFUN_BUFFER_SWITCH:
1372 // toggle on the current buffer, but do not toggle off
1373 // the other ones (is that a good idea?)
1375 && to_utf8(cmd.argument()) == doc_buffer->absFileName())
1376 flag.setOnOff(true);
1379 case LFUN_VC_REGISTER:
1380 enable = doc_buffer && !doc_buffer->lyxvc().inUse();
1382 case LFUN_VC_CHECK_IN:
1383 enable = doc_buffer && doc_buffer->lyxvc().checkInEnabled();
1385 case LFUN_VC_CHECK_OUT:
1386 enable = doc_buffer && doc_buffer->lyxvc().checkOutEnabled();
1388 case LFUN_VC_LOCKING_TOGGLE:
1389 enable = doc_buffer && !doc_buffer->isReadonly()
1390 && doc_buffer->lyxvc().lockingToggleEnabled();
1391 flag.setOnOff(enable && !doc_buffer->lyxvc().locker().empty());
1393 case LFUN_VC_REVERT:
1394 enable = doc_buffer && doc_buffer->lyxvc().inUse();
1396 case LFUN_VC_UNDO_LAST:
1397 enable = doc_buffer && doc_buffer->lyxvc().undoLastEnabled();
1399 case LFUN_VC_COMMAND: {
1400 if (cmd.argument().empty())
1402 if (!doc_buffer && contains(cmd.getArg(0), 'D'))
1407 case LFUN_SERVER_GOTO_FILE_ROW:
1415 flag.setEnabled(false);
1421 static FileName selectTemplateFile()
1423 FileDialog dlg(qt_("Select template file"));
1424 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1425 dlg.setButton1(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
1427 FileDialog::Result result = dlg.open(toqstr(lyxrc.template_path),
1428 QStringList(qt_("LyX Documents (*.lyx)")));
1430 if (result.first == FileDialog::Later)
1432 if (result.second.isEmpty())
1434 return FileName(fromqstr(result.second));
1438 Buffer * GuiView::loadDocument(FileName const & filename, bool tolastfiles)
1442 Buffer * newBuffer = checkAndLoadLyXFile(filename);
1445 message(_("Document not loaded."));
1450 setBuffer(newBuffer);
1452 // scroll to the position when the file was last closed
1453 if (lyxrc.use_lastfilepos) {
1454 LastFilePosSection::FilePos filepos =
1455 theSession().lastFilePos().load(filename);
1456 documentBufferView()->moveToPosition(filepos.pit, filepos.pos, 0, 0);
1460 theSession().lastFiles().add(filename);
1467 void GuiView::openDocument(string const & fname)
1469 string initpath = lyxrc.document_path;
1471 if (documentBufferView()) {
1472 string const trypath = documentBufferView()->buffer().filePath();
1473 // If directory is writeable, use this as default.
1474 if (FileName(trypath).isDirWritable())
1480 if (fname.empty()) {
1481 FileDialog dlg(qt_("Select document to open"), LFUN_FILE_OPEN);
1482 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1483 dlg.setButton2(qt_("Examples|#E#e"),
1484 toqstr(addPath(package().system_support().absFilename(), "examples")));
1486 QStringList filter(qt_("LyX Documents (*.lyx)"));
1487 filter << qt_("LyX-1.3.x Documents (*.lyx13)")
1488 << qt_("LyX-1.4.x Documents (*.lyx14)")
1489 << qt_("LyX-1.5.x Documents (*.lyx15)")
1490 << qt_("LyX-1.6.x Documents (*.lyx16)");
1491 FileDialog::Result result =
1492 dlg.open(toqstr(initpath), filter);
1494 if (result.first == FileDialog::Later)
1497 filename = fromqstr(result.second);
1499 // check selected filename
1500 if (filename.empty()) {
1501 message(_("Canceled."));
1507 // get absolute path of file and add ".lyx" to the filename if
1509 FileName const fullname =
1510 fileSearch(string(), filename, "lyx", support::may_not_exist);
1511 if (!fullname.empty())
1512 filename = fullname.absFilename();
1514 if (!fullname.onlyPath().isDirectory()) {
1515 Alert::warning(_("Invalid filename"),
1516 bformat(_("The directory in the given path\n%1$s\ndoes not exist."),
1517 from_utf8(fullname.absFilename())));
1520 // if the file doesn't exist, let the user create one
1521 if (!fullname.exists()) {
1522 // the user specifically chose this name. Believe him.
1523 Buffer * const b = newFile(filename, string(), true);
1529 docstring const disp_fn = makeDisplayPath(filename);
1530 message(bformat(_("Opening document %1$s..."), disp_fn));
1533 Buffer * buf = loadDocument(fullname);
1535 buf->updateLabels();
1537 buf->errors("Parse");
1538 str2 = bformat(_("Document %1$s opened."), disp_fn);
1539 if (buf->lyxvc().inUse())
1540 str2 += " " + from_utf8(buf->lyxvc().versionString()) +
1541 " " + _("Version control detected.");
1543 str2 = bformat(_("Could not open document %1$s"), disp_fn);
1548 // FIXME: clean that
1549 static bool import(GuiView * lv, FileName const & filename,
1550 string const & format, ErrorList & errorList)
1552 FileName const lyxfile(support::changeExtension(filename.absFilename(), ".lyx"));
1554 string loader_format;
1555 vector<string> loaders = theConverters().loaders();
1556 if (find(loaders.begin(), loaders.end(), format) == loaders.end()) {
1557 for (vector<string>::const_iterator it = loaders.begin();
1558 it != loaders.end(); ++it) {
1559 if (!theConverters().isReachable(format, *it))
1562 string const tofile =
1563 support::changeExtension(filename.absFilename(),
1564 formats.extension(*it));
1565 if (!theConverters().convert(0, filename, FileName(tofile),
1566 filename, format, *it, errorList))
1568 loader_format = *it;
1571 if (loader_format.empty()) {
1572 frontend::Alert::error(_("Couldn't import file"),
1573 bformat(_("No information for importing the format %1$s."),
1574 formats.prettyName(format)));
1578 loader_format = format;
1580 if (loader_format == "lyx") {
1581 Buffer * buf = lv->loadDocument(lyxfile);
1584 buf->updateLabels();
1586 buf->errors("Parse");
1588 Buffer * const b = newFile(lyxfile.absFilename(), string(), true);
1592 bool as_paragraphs = loader_format == "textparagraph";
1593 string filename2 = (loader_format == format) ? filename.absFilename()
1594 : support::changeExtension(filename.absFilename(),
1595 formats.extension(loader_format));
1596 lv->currentBufferView()->insertPlaintextFile(FileName(filename2),
1598 guiApp->setCurrentView(lv);
1599 lyx::dispatch(FuncRequest(LFUN_MARK_OFF));
1606 void GuiView::importDocument(string const & argument)
1609 string filename = split(argument, format, ' ');
1611 LYXERR(Debug::INFO, format << " file: " << filename);
1613 // need user interaction
1614 if (filename.empty()) {
1615 string initpath = lyxrc.document_path;
1616 if (documentBufferView()) {
1617 string const trypath = documentBufferView()->buffer().filePath();
1618 // If directory is writeable, use this as default.
1619 if (FileName(trypath).isDirWritable())
1623 docstring const text = bformat(_("Select %1$s file to import"),
1624 formats.prettyName(format));
1626 FileDialog dlg(toqstr(text), LFUN_BUFFER_IMPORT);
1627 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1628 dlg.setButton2(qt_("Examples|#E#e"),
1629 toqstr(addPath(package().system_support().absFilename(), "examples")));
1631 docstring filter = formats.prettyName(format);
1634 filter += from_utf8(formats.extension(format));
1637 FileDialog::Result result =
1638 dlg.open(toqstr(initpath), fileFilters(toqstr(filter)));
1640 if (result.first == FileDialog::Later)
1643 filename = fromqstr(result.second);
1645 // check selected filename
1646 if (filename.empty())
1647 message(_("Canceled."));
1650 if (filename.empty())
1653 // get absolute path of file
1654 FileName const fullname(support::makeAbsPath(filename));
1656 FileName const lyxfile(support::changeExtension(fullname.absFilename(), ".lyx"));
1658 // Check if the document already is open
1659 Buffer * buf = theBufferList().getBuffer(lyxfile);
1662 if (!closeBuffer()) {
1663 message(_("Canceled."));
1668 docstring const displaypath = makeDisplayPath(lyxfile.absFilename(), 30);
1670 // if the file exists already, and we didn't do
1671 // -i lyx thefile.lyx, warn
1672 if (lyxfile.exists() && fullname != lyxfile) {
1674 docstring text = bformat(_("The document %1$s already exists.\n\n"
1675 "Do you want to overwrite that document?"), displaypath);
1676 int const ret = Alert::prompt(_("Overwrite document?"),
1677 text, 0, 1, _("&Overwrite"), _("&Cancel"));
1680 message(_("Canceled."));
1685 message(bformat(_("Importing %1$s..."), displaypath));
1686 ErrorList errorList;
1687 if (import(this, fullname, format, errorList))
1688 message(_("imported."));
1690 message(_("file not imported!"));
1692 // FIXME (Abdel 12/08/06): Is there a need to display the error list here?
1696 void GuiView::newDocument(string const & filename, bool from_template)
1698 FileName initpath(lyxrc.document_path);
1699 if (documentBufferView()) {
1700 FileName const trypath(documentBufferView()->buffer().filePath());
1701 // If directory is writeable, use this as default.
1702 if (trypath.isDirWritable())
1706 string templatefile;
1707 if (from_template) {
1708 templatefile = selectTemplateFile().absFilename();
1709 if (templatefile.empty())
1714 if (filename.empty())
1715 b = newUnnamedFile(templatefile, initpath);
1717 b = newFile(filename, templatefile, true);
1722 // If no new document could be created, it is unsure
1723 // whether there is a valid BufferView.
1724 if (currentBufferView())
1725 // Ensure the cursor is correctly positioned on screen.
1726 currentBufferView()->showCursor();
1730 void GuiView::insertLyXFile(docstring const & fname)
1732 BufferView * bv = documentBufferView();
1737 FileName filename(to_utf8(fname));
1739 if (!filename.empty()) {
1740 bv->insertLyXFile(filename);
1744 // Launch a file browser
1746 string initpath = lyxrc.document_path;
1747 string const trypath = bv->buffer().filePath();
1748 // If directory is writeable, use this as default.
1749 if (FileName(trypath).isDirWritable())
1753 FileDialog dlg(qt_("Select LyX document to insert"), LFUN_FILE_INSERT);
1754 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1755 dlg.setButton2(qt_("Examples|#E#e"),
1756 toqstr(addPath(package().system_support().absFilename(),
1759 FileDialog::Result result = dlg.open(toqstr(initpath),
1760 QStringList(qt_("LyX Documents (*.lyx)")));
1762 if (result.first == FileDialog::Later)
1766 filename.set(fromqstr(result.second));
1768 // check selected filename
1769 if (filename.empty()) {
1770 // emit message signal.
1771 message(_("Canceled."));
1775 bv->insertLyXFile(filename);
1779 void GuiView::insertPlaintextFile(docstring const & fname,
1782 BufferView * bv = documentBufferView();
1786 if (!fname.empty() && !FileName::isAbsolute(to_utf8(fname))) {
1787 message(_("Absolute filename expected."));
1792 FileName filename(to_utf8(fname));
1794 if (!filename.empty()) {
1795 bv->insertPlaintextFile(filename, asParagraph);
1799 FileDialog dlg(qt_("Select file to insert"), (asParagraph ?
1800 LFUN_FILE_INSERT_PLAINTEXT_PARA : LFUN_FILE_INSERT_PLAINTEXT));
1802 FileDialog::Result result = dlg.open(toqstr(bv->buffer().filePath()),
1803 QStringList(qt_("All Files (*)")));
1805 if (result.first == FileDialog::Later)
1809 filename.set(fromqstr(result.second));
1811 // check selected filename
1812 if (filename.empty()) {
1813 // emit message signal.
1814 message(_("Canceled."));
1818 bv->insertPlaintextFile(filename, asParagraph);
1822 bool GuiView::renameBuffer(Buffer & b, docstring const & newname)
1824 FileName fname = b.fileName();
1825 FileName const oldname = fname;
1827 if (!newname.empty()) {
1829 fname = support::makeAbsPath(to_utf8(newname), oldname.onlyPath().absFilename());
1831 // Switch to this Buffer.
1834 // No argument? Ask user through dialog.
1836 FileDialog dlg(qt_("Choose a filename to save document as"),
1837 LFUN_BUFFER_WRITE_AS);
1838 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1839 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
1841 if (!isLyXFilename(fname.absFilename()))
1842 fname.changeExtension(".lyx");
1844 FileDialog::Result result =
1845 dlg.save(toqstr(fname.onlyPath().absFilename()),
1846 QStringList(qt_("LyX Documents (*.lyx)")),
1847 toqstr(fname.onlyFileName()));
1849 if (result.first == FileDialog::Later)
1852 fname.set(fromqstr(result.second));
1857 if (!isLyXFilename(fname.absFilename()))
1858 fname.changeExtension(".lyx");
1861 if (FileName(fname).exists()) {
1862 docstring const file = makeDisplayPath(fname.absFilename(), 30);
1863 docstring text = bformat(_("The document %1$s already "
1864 "exists.\n\nDo you want to "
1865 "overwrite that document?"),
1867 int const ret = Alert::prompt(_("Overwrite document?"),
1868 text, 0, 2, _("&Overwrite"), _("&Rename"), _("&Cancel"));
1871 case 1: return renameBuffer(b, docstring());
1872 case 2: return false;
1876 FileName oldauto = b.getAutosaveFilename();
1878 // Ok, change the name of the buffer
1879 b.setFileName(fname.absFilename());
1881 bool unnamed = b.isUnnamed();
1882 b.setUnnamed(false);
1883 b.saveCheckSum(fname);
1885 // bring the autosave file with us, just in case.
1886 b.moveAutosaveFile(oldauto);
1888 if (!saveBuffer(b)) {
1889 oldauto = b.getAutosaveFilename();
1890 b.setFileName(oldname.absFilename());
1891 b.setUnnamed(unnamed);
1892 b.saveCheckSum(oldname);
1893 b.moveAutosaveFile(oldauto);
1901 bool GuiView::saveBuffer(Buffer & b)
1903 if (workArea(b) && workArea(b)->inDialogMode())
1907 return renameBuffer(b, docstring());
1910 theSession().lastFiles().add(b.fileName());
1914 // Switch to this Buffer.
1917 // FIXME: we don't tell the user *WHY* the save failed !!
1918 docstring const file = makeDisplayPath(b.absFileName(), 30);
1919 docstring text = bformat(_("The document %1$s could not be saved.\n\n"
1920 "Do you want to rename the document and "
1921 "try again?"), file);
1922 int const ret = Alert::prompt(_("Rename and save?"),
1923 text, 0, 2, _("&Rename"), _("&Retry"), _("&Cancel"));
1926 if (!renameBuffer(b, docstring()))
1935 return saveBuffer(b);
1939 bool GuiView::hideWorkArea(GuiWorkArea * wa)
1941 return closeWorkArea(wa, false);
1945 bool GuiView::closeWorkArea(GuiWorkArea * wa)
1947 Buffer & buf = wa->bufferView().buffer();
1948 return closeWorkArea(wa, !buf.parent());
1952 bool GuiView::closeBuffer()
1954 GuiWorkArea * wa = currentMainWorkArea();
1955 Buffer & buf = wa->bufferView().buffer();
1956 return wa && closeWorkArea(wa, !buf.parent());
1960 void GuiView::writeSession() const {
1961 GuiWorkArea const * active_wa = currentMainWorkArea();
1962 for (int i = 0; i < d.splitter_->count(); ++i) {
1963 TabWorkArea * twa = d.tabWorkArea(i);
1964 for (int j = 0; j < twa->count(); ++j) {
1965 GuiWorkArea * wa = static_cast<GuiWorkArea *>(twa->widget(j));
1966 Buffer & buf = wa->bufferView().buffer();
1967 theSession().lastOpened().add(buf.fileName(), wa == active_wa);
1973 bool GuiView::closeBufferAll()
1975 // Close the workareas in all other views
1976 QList<int> const ids = guiApp->viewIds();
1977 for (int i = 0; i != ids.size(); ++i) {
1978 if (id_ != ids[i] && !guiApp->view(ids[i]).closeWorkAreaAll())
1982 // Close our own workareas
1983 if (!closeWorkAreaAll())
1986 // Now close the hidden buffers. We prevent hidden buffers from being
1987 // dirty, so we can just close them.
1988 theBufferList().closeAll();
1993 bool GuiView::closeWorkAreaAll()
1995 setCurrentWorkArea(currentMainWorkArea());
1997 // We might be in a situation that there is still a tabWorkArea, but
1998 // there are no tabs anymore. This can happen when we get here after a
1999 // TabWorkArea::lastWorkAreaRemoved() signal. Therefore we count how
2000 // many TabWorkArea's have no documents anymore.
2003 // We have to call count() each time, because it can happen that
2004 // more than one splitter will disappear in one iteration (bug 5998).
2005 for (; d.splitter_->count() > empty_twa; ) {
2006 TabWorkArea * twa = d.tabWorkArea(empty_twa);
2008 if (twa->count() == 0)
2011 setCurrentWorkArea(twa->currentWorkArea());
2012 if (!closeTabWorkArea(twa))
2020 bool GuiView::closeWorkArea(GuiWorkArea * wa, bool close_buffer)
2022 Buffer & buf = wa->bufferView().buffer();
2024 // If we are in a close_event all children will be closed in some time,
2025 // so no need to do it here. This will ensure that the children end up
2026 // in the session file in the correct order. If we close the master
2027 // buffer, we can close or release the child buffers here too.
2028 if (close_buffer && !closing_) {
2029 vector<Buffer *> clist = buf.getChildren();
2030 for (vector<Buffer *>::const_iterator it = clist.begin();
2031 it != clist.end(); ++it) {
2032 // If a child is dirty, do not close
2033 // without user intervention
2034 //FIXME: should we look in other tabworkareas?
2035 Buffer * child_buf = *it;
2036 GuiWorkArea * child_wa = workArea(*child_buf);
2038 if (!closeWorkArea(child_wa, true))
2041 theBufferList().releaseChild(&buf, child_buf);
2044 // goto bookmark to update bookmark pit.
2045 //FIXME: we should update only the bookmarks related to this buffer!
2046 LYXERR(Debug::DEBUG, "GuiView::closeBuffer()");
2047 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
2048 theLyXFunc().gotoBookmark(i+1, false, false);
2050 // if we are only hiding the buffer and there are multiple views
2051 // of the buffer, then we do not need to ensure a clean buffer.
2052 bool const allow_dirty = inMultiTabs(wa) && !close_buffer;
2054 if (allow_dirty || saveBufferIfNeeded(buf, !close_buffer)) {
2055 // save in sessions if requested
2056 // do not save childs if their master
2057 // is opened as well
2061 theBufferList().release(&buf);
2068 bool GuiView::closeTabWorkArea(TabWorkArea * twa)
2070 while (twa == d.currentTabWorkArea()) {
2071 twa->setCurrentIndex(twa->count()-1);
2073 GuiWorkArea * wa = twa->currentWorkArea();
2074 Buffer & b = wa->bufferView().buffer();
2076 // We only want to close the buffer if the same buffer is not visible
2077 // in another view, and if this is not a child and if we are closing
2078 // a view (not a tabgroup).
2079 bool const close_buffer =
2080 !inMultiViews(wa) && !b.parent() && closing_;
2082 if (!closeWorkArea(wa, close_buffer))
2089 bool GuiView::saveBufferIfNeeded(Buffer & buf, bool hiding)
2091 if (buf.isClean() || buf.paragraphs().empty())
2094 // Switch to this Buffer.
2099 if (buf.isUnnamed())
2100 file = from_utf8(buf.fileName().onlyFileName());
2102 file = buf.fileName().displayName(30);
2104 // Bring this window to top before asking questions.
2109 if (hiding && buf.isUnnamed()) {
2110 docstring const text = bformat(_("The document %1$s has not been "
2111 "saved yet.\n\nDo you want to save "
2112 "the document?"), file);
2113 ret = Alert::prompt(_("Save new document?"),
2114 text, 0, 1, _("&Save"), _("&Cancel"));
2118 docstring const text = bformat(_("The document %1$s has unsaved changes."
2119 "\n\nDo you want to save the document or discard the changes?"), file);
2120 ret = Alert::prompt(_("Save changed document?"),
2121 text, 0, 2, _("&Save"), _("&Discard"), _("&Cancel"));
2126 if (!saveBuffer(buf))
2130 // if we crash after this we could
2131 // have no autosave file but I guess
2132 // this is really improbable (Jug)
2133 buf.removeAutosaveFile();
2135 // revert all changes
2136 buf.loadLyXFile(buf.fileName());
2146 bool GuiView::inMultiTabs(GuiWorkArea * wa)
2148 Buffer & buf = wa->bufferView().buffer();
2150 for (int i = 0; i != d.splitter_->count(); ++i) {
2151 GuiWorkArea * wa_ = d.tabWorkArea(i)->workArea(buf);
2152 if (wa_ && wa_ != wa)
2155 return inMultiViews(wa);
2159 bool GuiView::inMultiViews(GuiWorkArea * wa)
2161 QList<int> const ids = guiApp->viewIds();
2162 Buffer & buf = wa->bufferView().buffer();
2165 for (int i = 0; i != ids.size() && found_twa <= 1; ++i) {
2169 if (guiApp->view(ids[i]).workArea(buf))
2176 void GuiView::gotoNextOrPreviousBuffer(NextOrPrevious np)
2178 Buffer * const curbuf = documentBufferView()
2179 ? &documentBufferView()->buffer() : 0;
2180 Buffer * nextbuf = curbuf;
2182 if (np == NEXTBUFFER)
2183 nextbuf = theBufferList().next(nextbuf);
2185 nextbuf = theBufferList().previous(nextbuf);
2186 if (nextbuf == curbuf)
2192 if (workArea(*nextbuf))
2199 /// make sure the document is saved
2200 static bool ensureBufferClean(Buffer * buffer)
2202 LASSERT(buffer, return false);
2203 if (buffer->isClean() && !buffer->isUnnamed())
2206 docstring const file = buffer->fileName().displayName(30);
2209 if (!buffer->isUnnamed()) {
2210 text = bformat(_("The document %1$s has unsaved "
2211 "changes.\n\nDo you want to save "
2212 "the document?"), file);
2213 title = _("Save changed document?");
2216 text = bformat(_("The document %1$s has not been "
2217 "saved yet.\n\nDo you want to save "
2218 "the document?"), file);
2219 title = _("Save new document?");
2221 int const ret = Alert::prompt(title, text, 0, 1, _("&Save"), _("&Cancel"));
2224 dispatch(FuncRequest(LFUN_BUFFER_WRITE));
2226 return buffer->isClean() && !buffer->isUnnamed();
2230 void GuiView::reloadBuffer()
2232 Buffer * buf = &documentBufferView()->buffer();
2233 FileName filename = buf->fileName();
2234 // The user has already confirmed that the changes, if any, should
2235 // be discarded. So we just release the Buffer and don't call closeBuffer();
2236 theBufferList().release(buf);
2237 buf = loadDocument(filename);
2238 docstring const disp_fn = makeDisplayPath(filename.absFilename());
2241 buf->updateLabels();
2243 buf->errors("Parse");
2244 str = bformat(_("Document %1$s reloaded."), disp_fn);
2246 str = bformat(_("Could not reload document %1$s"), disp_fn);
2252 void GuiView::dispatchVC(FuncRequest const & cmd)
2254 Buffer * buffer = documentBufferView()
2255 ? &(documentBufferView()->buffer()) : 0;
2257 switch (cmd.action) {
2258 case LFUN_VC_REGISTER:
2259 if (!buffer || !ensureBufferClean(buffer))
2261 if (!buffer->lyxvc().inUse()) {
2262 if (buffer->lyxvc().registrer())
2267 case LFUN_VC_CHECK_IN:
2268 if (!buffer || !ensureBufferClean(buffer))
2270 if (buffer->lyxvc().inUse() && !buffer->isReadonly()) {
2271 message(from_utf8(buffer->lyxvc().checkIn()));
2276 case LFUN_VC_CHECK_OUT:
2277 if (!buffer || !ensureBufferClean(buffer))
2279 if (buffer->lyxvc().inUse()) {
2280 message(from_utf8(buffer->lyxvc().checkOut()));
2285 case LFUN_VC_LOCKING_TOGGLE:
2286 LASSERT(buffer, return);
2287 if (!ensureBufferClean(buffer) || buffer->isReadonly())
2289 if (buffer->lyxvc().inUse()) {
2290 string res = buffer->lyxvc().lockingToggle();
2292 frontend::Alert::error(_("Revision control error."),
2293 _("Error when setting the locking property."));
2295 message(from_utf8(res));
2301 case LFUN_VC_REVERT:
2302 LASSERT(buffer, return);
2303 buffer->lyxvc().revert();
2307 case LFUN_VC_UNDO_LAST:
2308 LASSERT(buffer, return);
2309 buffer->lyxvc().undoLast();
2313 case LFUN_VC_COMMAND: {
2314 string flag = cmd.getArg(0);
2315 if (buffer && contains(flag, 'R') && !ensureBufferClean(buffer))
2318 if (contains(flag, 'M')) {
2319 if (!Alert::askForText(message, _("LyX VC: Log Message")))
2322 string path = cmd.getArg(1);
2323 if (contains(path, "$$p") && buffer)
2324 path = subst(path, "$$p", buffer->filePath());
2325 LYXERR(Debug::LYXVC, "Directory: " << path);
2327 if (!pp.isReadableDirectory()) {
2328 lyxerr << _("Directory is not accessible.") << endl;
2331 support::PathChanger p(pp);
2333 string command = cmd.getArg(2);
2334 if (command.empty())
2337 command = subst(command, "$$i", buffer->absFileName());
2338 command = subst(command, "$$p", buffer->filePath());
2340 command = subst(command, "$$m", to_utf8(message));
2341 LYXERR(Debug::LYXVC, "Command: " << command);
2343 one.startscript(Systemcall::Wait, command);
2347 if (contains(flag, 'I'))
2348 buffer->markDirty();
2349 if (contains(flag, 'R'))
2360 void GuiView::openChildDocument(string const & fname)
2362 LASSERT(documentBufferView(), return);
2363 Buffer & buffer = documentBufferView()->buffer();
2364 FileName const filename = support::makeAbsPath(fname, buffer.filePath());
2365 documentBufferView()->saveBookmark(false);
2367 bool parsed = false;
2368 if (theBufferList().exists(filename)) {
2369 child = theBufferList().getBuffer(filename);
2371 message(bformat(_("Opening child document %1$s..."),
2372 makeDisplayPath(filename.absFilename())));
2373 child = loadDocument(filename, false);
2379 // Set the parent name of the child document.
2380 // This makes insertion of citations and references in the child work,
2381 // when the target is in the parent or another child document.
2382 child->setParent(&buffer);
2383 child->masterBuffer()->updateLabels();
2386 child->errors("Parse");
2390 bool GuiView::goToFileRow(string const & argument)
2394 istringstream is(argument);
2395 is >> file_name >> row;
2396 file_name = os::internal_path(file_name);
2398 string const abstmp = package().temp_dir().absFilename();
2399 string const realtmp = package().temp_dir().realPath();
2400 // We have to use os::path_prefix_is() here, instead of
2401 // simply prefixIs(), because the file name comes from
2402 // an external application and may need case adjustment.
2403 if (os::path_prefix_is(file_name, abstmp, os::CASE_ADJUSTED)
2404 || os::path_prefix_is(file_name, realtmp, os::CASE_ADJUSTED)) {
2405 // Needed by inverse dvi search. If it is a file
2406 // in tmpdir, call the apropriated function.
2407 // If tmpdir is a symlink, we may have the real
2408 // path passed back, so we correct for that.
2409 if (!prefixIs(file_name, abstmp))
2410 file_name = subst(file_name, realtmp, abstmp);
2411 buf = theBufferList().getBufferFromTmp(file_name);
2413 // Must replace extension of the file to be .lyx
2414 // and get full path
2415 FileName const s = fileSearch(string(),
2416 support::changeExtension(file_name, ".lyx"), "lyx");
2417 // Either change buffer or load the file
2418 if (theBufferList().exists(s))
2419 buf = theBufferList().getBuffer(s);
2420 else if (s.exists()) {
2421 buf = loadDocument(s);
2422 buf->updateLabels();
2423 buf->errors("Parse");
2426 _("File does not exist: %1$s"),
2427 makeDisplayPath(file_name)));
2432 documentBufferView()->setCursorFromRow(row);
2437 bool GuiView::dispatch(FuncRequest const & cmd)
2439 BufferView * bv = currentBufferView();
2440 // By default we won't need any update.
2442 bv->cursor().updateFlags(Update::None);
2444 Buffer * doc_buffer = documentBufferView()
2445 ? &(documentBufferView()->buffer()) : 0;
2447 bool dispatched = true;
2449 if (cmd.origin == FuncRequest::TOC) {
2450 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
2451 toc->doDispatch(bv->cursor(), cmd);
2455 switch(cmd.action) {
2456 case LFUN_BUFFER_CHILD_OPEN:
2457 openChildDocument(to_utf8(cmd.argument()));
2460 case LFUN_BUFFER_IMPORT:
2461 importDocument(to_utf8(cmd.argument()));
2464 case LFUN_BUFFER_SWITCH:
2465 if (FileName::isAbsolute(to_utf8(cmd.argument()))) {
2467 theBufferList().getBuffer(FileName(to_utf8(cmd.argument())));
2471 message(_("Document not loaded"));
2475 case LFUN_BUFFER_NEXT:
2476 gotoNextOrPreviousBuffer(NEXTBUFFER);
2479 case LFUN_BUFFER_PREVIOUS:
2480 gotoNextOrPreviousBuffer(PREVBUFFER);
2483 case LFUN_COMMAND_EXECUTE: {
2484 bool const show_it = cmd.argument() != "off";
2485 // FIXME: this is a hack, "minibuffer" should not be
2487 if (GuiToolbar * t = toolbar("minibuffer")) {
2488 t->setVisible(show_it);
2489 if (show_it && t->commandBuffer())
2490 t->commandBuffer()->setFocus();
2494 case LFUN_DROP_LAYOUTS_CHOICE:
2495 d.layout_->showPopup();
2498 case LFUN_MENU_OPEN:
2499 if (QMenu * menu = guiApp->menus().menu(toqstr(cmd.argument()), *this))
2500 menu->exec(QCursor::pos());
2503 case LFUN_FILE_INSERT:
2504 insertLyXFile(cmd.argument());
2506 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
2507 insertPlaintextFile(cmd.argument(), true);
2510 case LFUN_FILE_INSERT_PLAINTEXT:
2511 insertPlaintextFile(cmd.argument(), false);
2514 case LFUN_BUFFER_RELOAD: {
2515 LASSERT(doc_buffer, break);
2516 docstring const file = makeDisplayPath(doc_buffer->absFileName(), 20);
2517 docstring text = bformat(_("Any changes will be lost. Are you sure "
2518 "you want to revert to the saved version of the document %1$s?"), file);
2519 int const ret = Alert::prompt(_("Revert to saved document?"),
2520 text, 1, 1, _("&Revert"), _("&Cancel"));
2527 case LFUN_BUFFER_WRITE:
2528 LASSERT(doc_buffer, break);
2529 saveBuffer(*doc_buffer);
2532 case LFUN_BUFFER_WRITE_AS:
2533 LASSERT(doc_buffer, break);
2534 renameBuffer(*doc_buffer, cmd.argument());
2537 case LFUN_BUFFER_WRITE_ALL: {
2538 Buffer * first = theBufferList().first();
2541 message(_("Saving all documents..."));
2542 // We cannot use a for loop as the buffer list cycles.
2545 if (!b->isClean()) {
2547 LYXERR(Debug::ACTION, "Saved " << b->absFileName());
2549 b = theBufferList().next(b);
2550 } while (b != first);
2551 message(_("All documents saved."));
2555 case LFUN_BUFFER_CLOSE:
2559 case LFUN_BUFFER_CLOSE_ALL:
2563 case LFUN_TOOLBAR_TOGGLE: {
2564 string const name = cmd.getArg(0);
2565 if (GuiToolbar * t = toolbar(name))
2570 case LFUN_DIALOG_UPDATE: {
2571 string const name = to_utf8(cmd.argument());
2572 if (currentBufferView()) {
2573 Inset * inset = currentBufferView()->editedInset(name);
2574 // Can only update a dialog connected to an existing inset
2577 // FIXME: get rid of this indirection; GuiView ask the inset
2578 // if he is kind enough to update itself...
2579 FuncRequest fr(LFUN_INSET_DIALOG_UPDATE, cmd.argument());
2580 inset->dispatch(currentBufferView()->cursor(), fr);
2581 } else if (name == "paragraph") {
2582 lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
2583 } else if (name == "prefs" || name == "document") {
2584 updateDialog(name, string());
2589 case LFUN_DIALOG_TOGGLE: {
2590 if (isDialogVisible(cmd.getArg(0)))
2591 dispatch(FuncRequest(LFUN_DIALOG_HIDE, cmd.argument()));
2593 dispatch(FuncRequest(LFUN_DIALOG_SHOW, cmd.argument()));
2597 case LFUN_DIALOG_DISCONNECT_INSET:
2598 disconnectDialog(to_utf8(cmd.argument()));
2601 case LFUN_DIALOG_HIDE: {
2602 guiApp->hideDialogs(to_utf8(cmd.argument()), 0);
2606 case LFUN_DIALOG_SHOW: {
2607 string const name = cmd.getArg(0);
2608 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
2610 if (name == "character") {
2611 data = freefont2string();
2613 showDialog("character", data);
2614 } else if (name == "latexlog") {
2615 Buffer::LogType type;
2616 string const logfile = doc_buffer->logName(&type);
2618 case Buffer::latexlog:
2621 case Buffer::buildlog:
2625 data += Lexer::quoteString(logfile);
2626 showDialog("log", data);
2627 } else if (name == "vclog") {
2628 string const data = "vc " +
2629 Lexer::quoteString(doc_buffer->lyxvc().getLogFile());
2630 showDialog("log", data);
2631 } else if (name == "symbols") {
2632 data = bv->cursor().getEncoding()->name();
2634 showDialog("symbols", data);
2636 } else if (name == "prefs" && isFullScreen()) {
2637 FuncRequest fr(LFUN_INSET_INSERT, "fullscreen");
2639 showDialog("prefs", data);
2641 showDialog(name, data);
2646 message(cmd.argument());
2649 case LFUN_UI_TOGGLE:
2651 // Make sure the keyboard focus stays in the work area.
2655 case LFUN_SPLIT_VIEW: {
2656 LASSERT(doc_buffer, break);
2657 string const orientation = cmd.getArg(0);
2658 d.splitter_->setOrientation(orientation == "vertical"
2659 ? Qt::Vertical : Qt::Horizontal);
2660 TabWorkArea * twa = addTabWorkArea();
2661 GuiWorkArea * wa = twa->addWorkArea(*doc_buffer, *this);
2662 setCurrentWorkArea(wa);
2665 case LFUN_CLOSE_TAB_GROUP:
2666 if (TabWorkArea * twa = d.currentTabWorkArea()) {
2667 closeTabWorkArea(twa);
2668 d.current_work_area_ = 0;
2669 twa = d.currentTabWorkArea();
2670 // Switch to the next GuiWorkArea in the found TabWorkArea.
2672 // Make sure the work area is up to date.
2673 setCurrentWorkArea(twa->currentWorkArea());
2675 setCurrentWorkArea(0);
2680 case LFUN_COMPLETION_INLINE:
2681 if (d.current_work_area_)
2682 d.current_work_area_->completer().showInline();
2685 case LFUN_COMPLETION_POPUP:
2686 if (d.current_work_area_)
2687 d.current_work_area_->completer().showPopup();
2691 case LFUN_COMPLETION_COMPLETE:
2692 if (d.current_work_area_)
2693 d.current_work_area_->completer().tab();
2696 case LFUN_COMPLETION_CANCEL:
2697 if (d.current_work_area_) {
2698 if (d.current_work_area_->completer().popupVisible())
2699 d.current_work_area_->completer().hidePopup();
2701 d.current_work_area_->completer().hideInline();
2705 case LFUN_COMPLETION_ACCEPT:
2706 if (d.current_work_area_)
2707 d.current_work_area_->completer().activate();
2710 case LFUN_BUFFER_ZOOM_IN:
2711 case LFUN_BUFFER_ZOOM_OUT:
2712 if (cmd.argument().empty()) {
2713 if (cmd.action == LFUN_BUFFER_ZOOM_IN)
2718 lyxrc.zoom += convert<int>(cmd.argument());
2720 if (lyxrc.zoom < 10)
2723 // The global QPixmapCache is used in GuiPainter to cache text
2724 // painting so we must reset it.
2725 QPixmapCache::clear();
2726 guiApp->fontLoader().update();
2727 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
2730 case LFUN_VC_REGISTER:
2731 case LFUN_VC_CHECK_IN:
2732 case LFUN_VC_CHECK_OUT:
2733 case LFUN_VC_LOCKING_TOGGLE:
2734 case LFUN_VC_REVERT:
2735 case LFUN_VC_UNDO_LAST:
2736 case LFUN_VC_COMMAND:
2740 case LFUN_SERVER_GOTO_FILE_ROW:
2741 goToFileRow(to_utf8(cmd.argument()));
2749 // Part of automatic menu appearance feature.
2750 if (isFullScreen()) {
2751 if (menuBar()->isVisible() && lyxrc.full_screen_menubar)
2753 if (statusBar()->isVisible())
2754 statusBar()->hide();
2761 void GuiView::lfunUiToggle(FuncRequest const & cmd)
2763 string const arg = cmd.getArg(0);
2764 if (arg == "scrollbar") {
2765 // hide() is of no help
2766 if (d.current_work_area_->verticalScrollBarPolicy() ==
2767 Qt::ScrollBarAlwaysOff)
2769 d.current_work_area_->setVerticalScrollBarPolicy(
2770 Qt::ScrollBarAsNeeded);
2772 d.current_work_area_->setVerticalScrollBarPolicy(
2773 Qt::ScrollBarAlwaysOff);
2776 if (arg == "statusbar") {
2777 statusBar()->setVisible(!statusBar()->isVisible());
2780 if (arg == "menubar") {
2781 menuBar()->setVisible(!menuBar()->isVisible());
2784 #if QT_VERSION >= 0x040300
2785 if (arg == "frame") {
2787 getContentsMargins(&l, &t, &r, &b);
2788 //are the frames in default state?
2789 d.current_work_area_->setFrameStyle(QFrame::NoFrame);
2791 setContentsMargins(-2, -2, -2, -2);
2793 setContentsMargins(0, 0, 0, 0);
2798 if (arg == "fullscreen") {
2803 message(bformat("LFUN_UI_TOGGLE " + _("%1$s unknown command!"), from_utf8(arg)));
2807 void GuiView::toggleFullScreen()
2809 if (isFullScreen()) {
2810 for (int i = 0; i != d.splitter_->count(); ++i)
2811 d.tabWorkArea(i)->setFullScreen(false);
2812 #if QT_VERSION >= 0x040300
2813 setContentsMargins(0, 0, 0, 0);
2815 setWindowState(windowState() ^ Qt::WindowFullScreen);
2818 statusBar()->show();
2821 hideDialogs("prefs", 0);
2822 for (int i = 0; i != d.splitter_->count(); ++i)
2823 d.tabWorkArea(i)->setFullScreen(true);
2824 #if QT_VERSION >= 0x040300
2825 setContentsMargins(-2, -2, -2, -2);
2828 setWindowState(windowState() ^ Qt::WindowFullScreen);
2829 statusBar()->hide();
2830 if (lyxrc.full_screen_menubar)
2832 if (lyxrc.full_screen_toolbars) {
2833 ToolbarMap::iterator end = d.toolbars_.end();
2834 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
2839 // give dialogs like the TOC a chance to adapt
2844 Buffer const * GuiView::updateInset(Inset const * inset)
2846 if (!d.current_work_area_)
2850 d.current_work_area_->scheduleRedraw();
2852 return &d.current_work_area_->bufferView().buffer();
2856 void GuiView::restartCursor()
2858 /* When we move around, or type, it's nice to be able to see
2859 * the cursor immediately after the keypress.
2861 if (d.current_work_area_)
2862 d.current_work_area_->startBlinkingCursor();
2864 // Take this occasion to update the other GUI elements.
2870 void GuiView::updateCompletion(Cursor & cur, bool start, bool keep)
2872 if (d.current_work_area_)
2873 d.current_work_area_->completer().updateVisibility(cur, start, keep);
2878 // This list should be kept in sync with the list of insets in
2879 // src/insets/Inset.cpp. I.e., if a dialog goes with an inset, the
2880 // dialog should have the same name as the inset.
2881 // Changes should be also recorded in LFUN_DIALOG_SHOW doxygen
2882 // docs in LyXAction.cpp.
2884 char const * const dialognames[] = {
2885 "aboutlyx", "bibitem", "bibtex", "box", "branch", "changes", "character",
2886 "citation", "document", "errorlist", "ert", "external", "file", "findreplace",
2887 "findreplaceadv", "float", "graphics", "href", "include", "index",
2888 "index_print", "info", "listings", "label", "log", "mathdelimiter",
2889 "mathmatrix", "mathspace", "nomenclature", "nomencl_print", "note",
2890 "paragraph", "phantom", "prefs", "print", "ref", "sendto", "space",
2891 "spellchecker", "symbols", "tabular", "tabularcreate", "thesaurus", "texinfo",
2892 "toc", "view-source", "vspace", "wrap" };
2894 char const * const * const end_dialognames =
2895 dialognames + (sizeof(dialognames) / sizeof(char *));
2899 cmpCStr(char const * name) : name_(name) {}
2900 bool operator()(char const * other) {
2901 return strcmp(other, name_) == 0;
2908 bool isValidName(string const & name)
2910 return find_if(dialognames, end_dialognames,
2911 cmpCStr(name.c_str())) != end_dialognames;
2917 void GuiView::resetDialogs()
2919 // Make sure that no LFUN uses any LyXView.
2920 guiApp->setCurrentView(0);
2923 constructToolbars();
2924 guiApp->menus().fillMenuBar(menuBar(), this, false);
2925 d.layout_->updateContents(true);
2926 // Now update controls with current buffer.
2927 guiApp->setCurrentView(this);
2933 Dialog * GuiView::findOrBuild(string const & name, bool hide_it)
2935 if (!isValidName(name))
2938 map<string, DialogPtr>::iterator it = d.dialogs_.find(name);
2940 if (it != d.dialogs_.end()) {
2942 it->second->hideView();
2943 return it->second.get();
2946 Dialog * dialog = build(name);
2947 d.dialogs_[name].reset(dialog);
2948 if (lyxrc.allow_geometry_session)
2949 dialog->restoreSession();
2956 void GuiView::showDialog(string const & name, string const & data,
2964 Dialog * dialog = findOrBuild(name, false);
2966 dialog->showData(data);
2967 if (inset && currentBufferView())
2968 currentBufferView()->editInset(name, inset);
2971 catch (ExceptionMessage const & ex) {
2979 bool GuiView::isDialogVisible(string const & name) const
2981 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
2982 if (it == d.dialogs_.end())
2984 return it->second.get()->isVisibleView() && !it->second.get()->isClosing();
2988 void GuiView::hideDialog(string const & name, Inset * inset)
2990 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
2991 if (it == d.dialogs_.end())
2994 if (inset && currentBufferView()
2995 && inset != currentBufferView()->editedInset(name))
2998 Dialog * const dialog = it->second.get();
2999 if (dialog->isVisibleView())
3001 if (currentBufferView())
3002 currentBufferView()->editInset(name, 0);
3006 void GuiView::disconnectDialog(string const & name)
3008 if (!isValidName(name))
3010 if (currentBufferView())
3011 currentBufferView()->editInset(name, 0);
3015 void GuiView::hideAll() const
3017 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
3018 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3020 for(; it != end; ++it)
3021 it->second->hideView();
3025 void GuiView::updateDialogs()
3027 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
3028 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3030 for(; it != end; ++it) {
3031 Dialog * dialog = it->second.get();
3032 if (dialog && dialog->isVisibleView())
3033 dialog->checkStatus();
3040 // will be replaced by a proper factory...
3041 Dialog * createGuiAbout(GuiView & lv);
3042 Dialog * createGuiBibitem(GuiView & lv);
3043 Dialog * createGuiBibtex(GuiView & lv);
3044 Dialog * createGuiBox(GuiView & lv);
3045 Dialog * createGuiBranch(GuiView & lv);
3046 Dialog * createGuiChanges(GuiView & lv);
3047 Dialog * createGuiCharacter(GuiView & lv);
3048 Dialog * createGuiCitation(GuiView & lv);
3049 Dialog * createGuiDelimiter(GuiView & lv);
3050 Dialog * createGuiDocument(GuiView & lv);
3051 Dialog * createGuiErrorList(GuiView & lv);
3052 Dialog * createGuiERT(GuiView & lv);
3053 Dialog * createGuiExternal(GuiView & lv);
3054 Dialog * createGuiFloat(GuiView & lv);
3055 Dialog * createGuiGraphics(GuiView & lv);
3056 Dialog * createGuiInclude(GuiView & lv);
3057 Dialog * createGuiIndex(GuiView & lv);
3058 Dialog * createGuiInfo(GuiView & lv);
3059 Dialog * createGuiLabel(GuiView & lv);
3060 Dialog * createGuiListings(GuiView & lv);
3061 Dialog * createGuiLog(GuiView & lv);
3062 Dialog * createGuiMathHSpace(GuiView & lv);
3063 Dialog * createGuiMathMatrix(GuiView & lv);
3064 Dialog * createGuiNomenclature(GuiView & lv);
3065 Dialog * createGuiNote(GuiView & lv);
3066 Dialog * createGuiParagraph(GuiView & lv);
3067 Dialog * createGuiPhantom(GuiView & lv);
3068 Dialog * createGuiPreferences(GuiView & lv);
3069 Dialog * createGuiPrint(GuiView & lv);
3070 Dialog * createGuiPrintindex(GuiView & lv);
3071 Dialog * createGuiPrintNomencl(GuiView & lv);
3072 Dialog * createGuiRef(GuiView & lv);
3073 Dialog * createGuiSearch(GuiView & lv);
3074 Dialog * createGuiSearchAdv(GuiView & lv);
3075 Dialog * createGuiSendTo(GuiView & lv);
3076 Dialog * createGuiShowFile(GuiView & lv);
3077 Dialog * createGuiSpellchecker(GuiView & lv);
3078 Dialog * createGuiSymbols(GuiView & lv);
3079 Dialog * createGuiTabularCreate(GuiView & lv);
3080 Dialog * createGuiTabular(GuiView & lv);
3081 Dialog * createGuiTexInfo(GuiView & lv);
3082 Dialog * createGuiTextHSpace(GuiView & lv);
3083 Dialog * createGuiToc(GuiView & lv);
3084 Dialog * createGuiThesaurus(GuiView & lv);
3085 Dialog * createGuiHyperlink(GuiView & lv);
3086 Dialog * createGuiVSpace(GuiView & lv);
3087 Dialog * createGuiViewSource(GuiView & lv);
3088 Dialog * createGuiWrap(GuiView & lv);
3091 Dialog * GuiView::build(string const & name)
3093 LASSERT(isValidName(name), return 0);
3095 if (name == "aboutlyx")
3096 return createGuiAbout(*this);
3097 if (name == "bibitem")
3098 return createGuiBibitem(*this);
3099 if (name == "bibtex")
3100 return createGuiBibtex(*this);
3102 return createGuiBox(*this);
3103 if (name == "branch")
3104 return createGuiBranch(*this);
3105 if (name == "changes")
3106 return createGuiChanges(*this);
3107 if (name == "character")
3108 return createGuiCharacter(*this);
3109 if (name == "citation")
3110 return createGuiCitation(*this);
3111 if (name == "document")
3112 return createGuiDocument(*this);
3113 if (name == "errorlist")
3114 return createGuiErrorList(*this);
3116 return createGuiERT(*this);
3117 if (name == "external")
3118 return createGuiExternal(*this);
3120 return createGuiShowFile(*this);
3121 if (name == "findreplace")
3122 return createGuiSearch(*this);
3123 if (name == "findreplaceadv")
3124 return createGuiSearchAdv(*this);
3125 if (name == "float")
3126 return createGuiFloat(*this);
3127 if (name == "graphics")
3128 return createGuiGraphics(*this);
3130 return createGuiHyperlink(*this);
3131 if (name == "include")
3132 return createGuiInclude(*this);
3133 if (name == "index")
3134 return createGuiIndex(*this);
3135 if (name == "index_print")
3136 return createGuiPrintindex(*this);
3138 return createGuiInfo(*this);
3139 if (name == "label")
3140 return createGuiLabel(*this);
3141 if (name == "listings")
3142 return createGuiListings(*this);
3144 return createGuiLog(*this);
3145 if (name == "mathdelimiter")
3146 return createGuiDelimiter(*this);
3147 if (name == "mathspace")
3148 return createGuiMathHSpace(*this);
3149 if (name == "mathmatrix")
3150 return createGuiMathMatrix(*this);
3151 if (name == "nomenclature")
3152 return createGuiNomenclature(*this);
3153 if (name == "nomencl_print")
3154 return createGuiPrintNomencl(*this);
3156 return createGuiNote(*this);
3157 if (name == "paragraph")
3158 return createGuiParagraph(*this);
3159 if (name == "phantom")
3160 return createGuiPhantom(*this);
3161 if (name == "prefs")
3162 return createGuiPreferences(*this);
3163 if (name == "print")
3164 return createGuiPrint(*this);
3166 return createGuiRef(*this);
3167 if (name == "sendto")
3168 return createGuiSendTo(*this);
3169 if (name == "space")
3170 return createGuiTextHSpace(*this);
3171 if (name == "spellchecker")
3172 return createGuiSpellchecker(*this);
3173 if (name == "symbols")
3174 return createGuiSymbols(*this);
3175 if (name == "tabular")
3176 return createGuiTabular(*this);
3177 if (name == "tabularcreate")
3178 return createGuiTabularCreate(*this);
3179 if (name == "texinfo")
3180 return createGuiTexInfo(*this);
3181 if (name == "thesaurus")
3182 return createGuiThesaurus(*this);
3184 return createGuiToc(*this);
3185 if (name == "view-source")
3186 return createGuiViewSource(*this);
3187 if (name == "vspace")
3188 return createGuiVSpace(*this);
3190 return createGuiWrap(*this);
3196 } // namespace frontend
3199 #include "moc_GuiView.cpp"