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::event(QEvent * e)
741 // Useful debug code:
742 //case QEvent::ActivationChange:
743 //case QEvent::WindowDeactivate:
744 //case QEvent::Paint:
745 //case QEvent::Enter:
746 //case QEvent::Leave:
747 //case QEvent::HoverEnter:
748 //case QEvent::HoverLeave:
749 //case QEvent::HoverMove:
750 //case QEvent::StatusTip:
751 //case QEvent::DragEnter:
752 //case QEvent::DragLeave:
756 case QEvent::WindowActivate: {
757 GuiView * old_view = guiApp->currentView();
758 if (this == old_view) {
760 return QMainWindow::event(e);
762 if (old_view && old_view->currentBufferView()) {
763 // save current selection to the selection buffer to allow
764 // middle-button paste in this window.
765 cap::saveSelection(old_view->currentBufferView()->cursor());
767 guiApp->setCurrentView(this);
768 if (d.current_work_area_) {
769 BufferView & bv = d.current_work_area_->bufferView();
770 connectBufferView(bv);
771 connectBuffer(bv.buffer());
772 // The document structure, name and dialogs might have
773 // changed in another view.
775 // The document settings needs to be reinitialised.
776 updateDialog("document", "");
779 resetWindowTitleAndIconText();
782 return QMainWindow::event(e);
785 case QEvent::ShortcutOverride: {
788 #if (!defined Q_WS_X11) || (QT_VERSION >= 0x040500)
789 if (isFullScreen() && menuBar()->isHidden()) {
790 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
791 // FIXME: we should also try to detect special LyX shortcut such as
792 // Alt-P and Alt-M. Right now there is a hack in
793 // GuiWorkArea::processKeySym() that hides again the menubar for
795 if (ke->modifiers() & Qt::AltModifier && ke->key() != Qt::Key_Alt) {
797 return QMainWindow::event(e);
802 if (d.current_work_area_)
803 // Nothing special to do.
804 return QMainWindow::event(e);
806 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
807 // Let Qt handle menu access and the Tab keys to navigate keys to navigate
809 if (ke->modifiers() & Qt::AltModifier || ke->key() == Qt::Key_Tab
810 || ke->key() == Qt::Key_Backtab)
811 return QMainWindow::event(e);
813 // Allow processing of shortcuts that are allowed even when no Buffer
816 setKeySymbol(&sym, ke);
817 theLyXFunc().processKeySym(sym, q_key_state(ke->modifiers()));
823 return QMainWindow::event(e);
827 void GuiView::resetWindowTitleAndIconText()
829 setWindowTitle(qt_("LyX"));
830 setWindowIconText(qt_("LyX"));
833 bool GuiView::focusNextPrevChild(bool /*next*/)
840 void GuiView::setBusy(bool busy)
842 if (d.current_work_area_) {
843 d.current_work_area_->setUpdatesEnabled(!busy);
845 d.current_work_area_->stopBlinkingCursor();
847 d.current_work_area_->startBlinkingCursor();
851 QApplication::setOverrideCursor(Qt::WaitCursor);
853 QApplication::restoreOverrideCursor();
857 GuiWorkArea * GuiView::workArea(Buffer & buffer)
859 if (currentWorkArea()
860 && ¤tWorkArea()->bufferView().buffer() == &buffer)
861 return (GuiWorkArea *) currentWorkArea();
862 if (TabWorkArea * twa = d.currentTabWorkArea())
863 return twa->workArea(buffer);
868 GuiWorkArea * GuiView::addWorkArea(Buffer & buffer)
870 // Automatically create a TabWorkArea if there are none yet.
871 TabWorkArea * tab_widget = d.splitter_->count()
872 ? d.currentTabWorkArea() : addTabWorkArea();
873 return tab_widget->addWorkArea(buffer, *this);
877 TabWorkArea * GuiView::addTabWorkArea()
879 TabWorkArea * twa = new TabWorkArea;
880 QObject::connect(twa, SIGNAL(currentWorkAreaChanged(GuiWorkArea *)),
881 this, SLOT(on_currentWorkAreaChanged(GuiWorkArea *)));
882 QObject::connect(twa, SIGNAL(lastWorkAreaRemoved()),
883 this, SLOT(on_lastWorkAreaRemoved()));
885 d.splitter_->addWidget(twa);
886 d.stack_widget_->setCurrentWidget(d.splitter_);
891 GuiWorkArea const * GuiView::currentWorkArea() const
893 return d.current_work_area_;
897 GuiWorkArea * GuiView::currentWorkArea()
899 return d.current_work_area_;
903 GuiWorkArea const * GuiView::currentMainWorkArea() const
905 if (d.currentTabWorkArea() == NULL)
907 return d.currentTabWorkArea()->currentWorkArea();
911 GuiWorkArea * GuiView::currentMainWorkArea()
913 if (d.currentTabWorkArea() == NULL)
915 return d.currentTabWorkArea()->currentWorkArea();
919 void GuiView::setCurrentWorkArea(GuiWorkArea * wa)
921 LYXERR(Debug::DEBUG, "Setting current wa: " << wa << endl);
923 d.current_work_area_ = NULL;
927 GuiWorkArea * old_gwa = theGuiApp()->currentView()->currentWorkArea();
931 if (currentBufferView())
932 cap::saveSelection(currentBufferView()->cursor());
934 theGuiApp()->setCurrentView(this);
935 d.current_work_area_ = wa;
936 for (int i = 0; i != d.splitter_->count(); ++i) {
937 if (d.tabWorkArea(i)->setCurrentWorkArea(wa)) {
938 //if (d.current_main_work_area_)
939 // d.current_main_work_area_->setFrameStyle(QFrame::NoFrame);
940 d.current_main_work_area_ = wa;
941 //d.current_main_work_area_->setFrameStyle(QFrame::Box | QFrame::Plain);
942 //d.current_main_work_area_->setLineWidth(2);
943 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() << ", Current main wa: " << currentMainWorkArea());
947 LYXERR(Debug::DEBUG, "This is not a tabbed wa");
948 on_currentWorkAreaChanged(wa);
949 BufferView & bv = wa->bufferView();
950 bv.cursor().fixIfBroken();
952 wa->setUpdatesEnabled(true);
953 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() << ", Current main wa: " << currentMainWorkArea());
957 void GuiView::removeWorkArea(GuiWorkArea * wa)
960 if (wa == d.current_work_area_) {
962 disconnectBufferView();
963 d.current_work_area_ = 0;
964 d.current_main_work_area_ = 0;
967 bool found_twa = false;
968 for (int i = 0; i != d.splitter_->count(); ++i) {
969 TabWorkArea * twa = d.tabWorkArea(i);
970 if (twa->removeWorkArea(wa)) {
971 // Found in this tab group, and deleted the GuiWorkArea.
973 if (twa->count() != 0) {
974 if (d.current_work_area_ == 0)
975 // This means that we are closing the current GuiWorkArea, so
976 // switch to the next GuiWorkArea in the found TabWorkArea.
977 setCurrentWorkArea(twa->currentWorkArea());
979 // No more WorkAreas in this tab group, so delete it.
986 // It is not a tabbed work area (i.e., the search work area), so it
987 // should be deleted by other means.
988 LASSERT(found_twa, /* */);
990 if (d.current_work_area_ == 0) {
991 if (d.splitter_->count() != 0) {
992 TabWorkArea * twa = d.currentTabWorkArea();
993 setCurrentWorkArea(twa->currentWorkArea());
995 // No more work areas, switch to the background widget.
996 setCurrentWorkArea(0);
1002 LayoutBox * GuiView::getLayoutDialog() const
1008 void GuiView::updateLayoutList()
1011 d.layout_->updateContents(false);
1015 void GuiView::updateToolbars()
1017 ToolbarMap::iterator end = d.toolbars_.end();
1018 if (d.current_work_area_) {
1020 d.current_work_area_->bufferView().cursor().inMathed();
1022 lyx::getStatus(FuncRequest(LFUN_LAYOUT_TABULAR)).enabled();
1024 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).enabled() &&
1025 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).onoff(true);
1026 bool const mathmacrotemplate =
1027 lyx::getStatus(FuncRequest(LFUN_IN_MATHMACROTEMPLATE)).enabled();
1029 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1030 it->second->update(math, table, review, mathmacrotemplate);
1032 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1033 it->second->update(false, false, false, false);
1037 void GuiView::setBuffer(Buffer * newBuffer)
1039 LYXERR(Debug::DEBUG, "Setting buffer: " << newBuffer << std::endl);
1040 LASSERT(newBuffer, return);
1043 GuiWorkArea * wa = workArea(*newBuffer);
1045 newBuffer->masterBuffer()->updateLabels();
1046 wa = addWorkArea(*newBuffer);
1048 //Disconnect the old buffer...there's no new one.
1051 connectBuffer(*newBuffer);
1052 connectBufferView(wa->bufferView());
1053 setCurrentWorkArea(wa);
1059 void GuiView::connectBuffer(Buffer & buf)
1061 buf.setGuiDelegate(this);
1065 void GuiView::disconnectBuffer()
1067 if (d.current_work_area_)
1068 d.current_work_area_->bufferView().buffer().setGuiDelegate(0);
1072 void GuiView::connectBufferView(BufferView & bv)
1074 bv.setGuiDelegate(this);
1078 void GuiView::disconnectBufferView()
1080 if (d.current_work_area_)
1081 d.current_work_area_->bufferView().setGuiDelegate(0);
1085 void GuiView::errors(string const & error_type, bool from_master)
1087 ErrorList & el = from_master ?
1088 documentBufferView()->buffer().masterBuffer()->errorList(error_type)
1089 : documentBufferView()->buffer().errorList(error_type);
1090 string data = error_type;
1092 data = "from_master|" + error_type;
1094 showDialog("errorlist", data);
1098 void GuiView::updateTocItem(std::string const & type, DocIterator const & dit)
1100 d.toc_models_.updateItem(toqstr(type), dit);
1104 void GuiView::structureChanged()
1106 d.toc_models_.reset(documentBufferView());
1107 // Navigator needs more than a simple update in this case. It needs to be
1109 updateDialog("toc", "");
1113 void GuiView::updateDialog(string const & name, string const & data)
1115 if (!isDialogVisible(name))
1118 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
1119 if (it == d.dialogs_.end())
1122 Dialog * const dialog = it->second.get();
1123 if (dialog->isVisibleView())
1124 dialog->initialiseParams(data);
1128 BufferView * GuiView::documentBufferView()
1130 return currentMainWorkArea()
1131 ? ¤tMainWorkArea()->bufferView()
1136 BufferView const * GuiView::documentBufferView() const
1138 return currentMainWorkArea()
1139 ? ¤tMainWorkArea()->bufferView()
1144 BufferView * GuiView::currentBufferView()
1146 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1150 BufferView const * GuiView::currentBufferView() const
1152 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1156 void GuiView::autoSave()
1158 LYXERR(Debug::INFO, "Running autoSave()");
1160 if (documentBufferView())
1161 documentBufferView()->buffer().autoSave();
1165 void GuiView::resetAutosaveTimers()
1168 d.autosave_timeout_.restart();
1172 bool GuiView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1175 Buffer * buf = currentBufferView()
1176 ? ¤tBufferView()->buffer() : 0;
1177 Buffer * doc_buffer = documentBufferView()
1178 ? &(documentBufferView()->buffer()) : 0;
1180 // Check whether we need a buffer
1181 if (!lyxaction.funcHasFlag(cmd.action, LyXAction::NoBuffer) && !buf) {
1182 // no, exit directly
1183 flag.message(from_utf8(N_("Command not allowed with"
1184 "out any document open")));
1185 flag.setEnabled(false);
1189 if (cmd.origin == FuncRequest::TOC) {
1190 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
1192 if (toc->getStatus(documentBufferView()->cursor(), cmd, fs))
1195 flag.setEnabled(false);
1199 switch(cmd.action) {
1200 case LFUN_BUFFER_IMPORT:
1203 case LFUN_BUFFER_RELOAD:
1204 enable = doc_buffer && !doc_buffer->isUnnamed()
1205 && doc_buffer->fileName().exists()
1206 && (!doc_buffer->isClean()
1207 || doc_buffer->isExternallyModified(Buffer::timestamp_method));
1210 case LFUN_BUFFER_CHILD_OPEN:
1211 enable = doc_buffer;
1214 case LFUN_BUFFER_WRITE:
1215 enable = doc_buffer && (doc_buffer->isUnnamed() || !doc_buffer->isClean());
1218 //FIXME: This LFUN should be moved to GuiApplication.
1219 case LFUN_BUFFER_WRITE_ALL: {
1220 // We enable the command only if there are some modified buffers
1221 Buffer * first = theBufferList().first();
1226 // We cannot use a for loop as the buffer list is a cycle.
1228 if (!b->isClean()) {
1232 b = theBufferList().next(b);
1233 } while (b != first);
1237 case LFUN_BUFFER_WRITE_AS:
1238 enable = doc_buffer;
1241 case LFUN_BUFFER_CLOSE:
1242 enable = doc_buffer;
1245 case LFUN_BUFFER_CLOSE_ALL:
1246 enable = theBufferList().last() != theBufferList().first();
1249 case LFUN_SPLIT_VIEW:
1250 if (cmd.getArg(0) == "vertical")
1251 enable = doc_buffer && (d.splitter_->count() == 1 ||
1252 d.splitter_->orientation() == Qt::Vertical);
1254 enable = doc_buffer && (d.splitter_->count() == 1 ||
1255 d.splitter_->orientation() == Qt::Horizontal);
1258 case LFUN_CLOSE_TAB_GROUP:
1259 enable = d.currentTabWorkArea();
1262 case LFUN_TOOLBAR_TOGGLE:
1263 if (GuiToolbar * t = toolbar(cmd.getArg(0)))
1264 flag.setOnOff(t->isVisible());
1267 case LFUN_UI_TOGGLE:
1268 flag.setOnOff(isFullScreen());
1271 case LFUN_DIALOG_DISCONNECT_INSET:
1274 case LFUN_DIALOG_HIDE:
1275 // FIXME: should we check if the dialog is shown?
1278 case LFUN_DIALOG_TOGGLE:
1279 flag.setOnOff(isDialogVisible(cmd.getArg(0)));
1280 // fall through to set "enable"
1281 case LFUN_DIALOG_SHOW: {
1282 string const name = cmd.getArg(0);
1284 enable = name == "aboutlyx"
1285 || name == "file" //FIXME: should be removed.
1287 || name == "texinfo";
1288 else if (name == "print")
1289 enable = doc_buffer->isExportable("dvi")
1290 && lyxrc.print_command != "none";
1291 else if (name == "character" || name == "symbols") {
1292 if (!buf || buf->isReadonly()
1293 || !currentBufferView()->cursor().inTexted())
1296 // FIXME we should consider passthru
1298 Inset const & in = currentBufferView()->cursor().inset();
1299 enable = !in.getLayout().isPassThru();
1302 else if (name == "latexlog")
1303 enable = FileName(doc_buffer->logName()).isReadableFile();
1304 else if (name == "spellchecker")
1305 enable = theSpellChecker() && !doc_buffer->isReadonly();
1306 else if (name == "vclog")
1307 enable = doc_buffer->lyxvc().inUse();
1311 case LFUN_DIALOG_UPDATE: {
1312 string const name = cmd.getArg(0);
1314 enable = name == "prefs";
1318 case LFUN_COMMAND_EXECUTE:
1320 case LFUN_MENU_OPEN:
1321 // Nothing to check.
1324 case LFUN_INSET_APPLY: {
1325 string const name = cmd.getArg(0);
1326 Inset * inset = getOpenInset(name);
1328 FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument());
1330 if (!inset->getStatus(currentBufferView()->cursor(), fr, fs)) {
1331 // Every inset is supposed to handle this
1332 LASSERT(false, break);
1336 FuncRequest fr(LFUN_INSET_INSERT, cmd.argument());
1337 flag |= lyx::getStatus(fr);
1339 enable = flag.enabled();
1343 case LFUN_COMPLETION_INLINE:
1344 if (!d.current_work_area_
1345 || !d.current_work_area_->completer().inlinePossible(
1346 currentBufferView()->cursor()))
1350 case LFUN_COMPLETION_POPUP:
1351 if (!d.current_work_area_
1352 || !d.current_work_area_->completer().popupPossible(
1353 currentBufferView()->cursor()))
1357 case LFUN_COMPLETION_COMPLETE:
1358 if (!d.current_work_area_
1359 || !d.current_work_area_->completer().inlinePossible(
1360 currentBufferView()->cursor()))
1364 case LFUN_COMPLETION_ACCEPT:
1365 if (!d.current_work_area_
1366 || (!d.current_work_area_->completer().popupVisible()
1367 && !d.current_work_area_->completer().inlineVisible()
1368 && !d.current_work_area_->completer().completionAvailable()))
1372 case LFUN_COMPLETION_CANCEL:
1373 if (!d.current_work_area_
1374 || (!d.current_work_area_->completer().popupVisible()
1375 && !d.current_work_area_->completer().inlineVisible()))
1379 case LFUN_BUFFER_ZOOM_OUT:
1380 enable = doc_buffer && lyxrc.zoom > 10;
1383 case LFUN_BUFFER_ZOOM_IN:
1384 enable = doc_buffer;
1387 case LFUN_BUFFER_NEXT:
1388 case LFUN_BUFFER_PREVIOUS:
1389 // FIXME: should we check is there is an previous or next buffer?
1391 case LFUN_BUFFER_SWITCH:
1392 // toggle on the current buffer, but do not toggle off
1393 // the other ones (is that a good idea?)
1395 && to_utf8(cmd.argument()) == doc_buffer->absFileName())
1396 flag.setOnOff(true);
1399 case LFUN_VC_REGISTER:
1400 enable = doc_buffer && !doc_buffer->lyxvc().inUse();
1402 case LFUN_VC_CHECK_IN:
1403 enable = doc_buffer && doc_buffer->lyxvc().checkInEnabled();
1405 case LFUN_VC_CHECK_OUT:
1406 enable = doc_buffer && doc_buffer->lyxvc().checkOutEnabled();
1408 case LFUN_VC_LOCKING_TOGGLE:
1409 enable = doc_buffer && !doc_buffer->isReadonly()
1410 && doc_buffer->lyxvc().lockingToggleEnabled();
1411 flag.setOnOff(enable && !doc_buffer->lyxvc().locker().empty());
1413 case LFUN_VC_REVERT:
1414 enable = doc_buffer && doc_buffer->lyxvc().inUse();
1416 case LFUN_VC_UNDO_LAST:
1417 enable = doc_buffer && doc_buffer->lyxvc().undoLastEnabled();
1419 case LFUN_VC_COMMAND: {
1420 if (cmd.argument().empty())
1422 if (!doc_buffer && contains(cmd.getArg(0), 'D'))
1427 case LFUN_SERVER_GOTO_FILE_ROW:
1435 flag.setEnabled(false);
1441 static FileName selectTemplateFile()
1443 FileDialog dlg(qt_("Select template file"));
1444 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1445 dlg.setButton1(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
1447 FileDialog::Result result = dlg.open(toqstr(lyxrc.template_path),
1448 QStringList(qt_("LyX Documents (*.lyx)")));
1450 if (result.first == FileDialog::Later)
1452 if (result.second.isEmpty())
1454 return FileName(fromqstr(result.second));
1458 Buffer * GuiView::loadDocument(FileName const & filename, bool tolastfiles)
1462 Buffer * newBuffer = checkAndLoadLyXFile(filename);
1465 message(_("Document not loaded."));
1470 setBuffer(newBuffer);
1472 // scroll to the position when the file was last closed
1473 if (lyxrc.use_lastfilepos) {
1474 LastFilePosSection::FilePos filepos =
1475 theSession().lastFilePos().load(filename);
1476 documentBufferView()->moveToPosition(filepos.pit, filepos.pos, 0, 0);
1480 theSession().lastFiles().add(filename);
1487 void GuiView::openDocument(string const & fname)
1489 string initpath = lyxrc.document_path;
1491 if (documentBufferView()) {
1492 string const trypath = documentBufferView()->buffer().filePath();
1493 // If directory is writeable, use this as default.
1494 if (FileName(trypath).isDirWritable())
1500 if (fname.empty()) {
1501 FileDialog dlg(qt_("Select document to open"), LFUN_FILE_OPEN);
1502 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1503 dlg.setButton2(qt_("Examples|#E#e"),
1504 toqstr(addPath(package().system_support().absFilename(), "examples")));
1506 QStringList filter(qt_("LyX Documents (*.lyx)"));
1507 filter << qt_("LyX-1.3.x Documents (*.lyx13)")
1508 << qt_("LyX-1.4.x Documents (*.lyx14)")
1509 << qt_("LyX-1.5.x Documents (*.lyx15)")
1510 << qt_("LyX-1.6.x Documents (*.lyx16)");
1511 FileDialog::Result result =
1512 dlg.open(toqstr(initpath), filter);
1514 if (result.first == FileDialog::Later)
1517 filename = fromqstr(result.second);
1519 // check selected filename
1520 if (filename.empty()) {
1521 message(_("Canceled."));
1527 // get absolute path of file and add ".lyx" to the filename if
1529 FileName const fullname =
1530 fileSearch(string(), filename, "lyx", support::may_not_exist);
1531 if (!fullname.empty())
1532 filename = fullname.absFilename();
1534 if (!fullname.onlyPath().isDirectory()) {
1535 Alert::warning(_("Invalid filename"),
1536 bformat(_("The directory in the given path\n%1$s\ndoes not exist."),
1537 from_utf8(fullname.absFilename())));
1540 // if the file doesn't exist, let the user create one
1541 if (!fullname.exists()) {
1542 // the user specifically chose this name. Believe him.
1543 Buffer * const b = newFile(filename, string(), true);
1549 docstring const disp_fn = makeDisplayPath(filename);
1550 message(bformat(_("Opening document %1$s..."), disp_fn));
1553 Buffer * buf = loadDocument(fullname);
1555 buf->updateLabels();
1557 buf->errors("Parse");
1558 str2 = bformat(_("Document %1$s opened."), disp_fn);
1559 if (buf->lyxvc().inUse())
1560 str2 += " " + from_utf8(buf->lyxvc().versionString()) +
1561 " " + _("Version control detected.");
1563 str2 = bformat(_("Could not open document %1$s"), disp_fn);
1568 // FIXME: clean that
1569 static bool import(GuiView * lv, FileName const & filename,
1570 string const & format, ErrorList & errorList)
1572 FileName const lyxfile(support::changeExtension(filename.absFilename(), ".lyx"));
1574 string loader_format;
1575 vector<string> loaders = theConverters().loaders();
1576 if (find(loaders.begin(), loaders.end(), format) == loaders.end()) {
1577 for (vector<string>::const_iterator it = loaders.begin();
1578 it != loaders.end(); ++it) {
1579 if (!theConverters().isReachable(format, *it))
1582 string const tofile =
1583 support::changeExtension(filename.absFilename(),
1584 formats.extension(*it));
1585 if (!theConverters().convert(0, filename, FileName(tofile),
1586 filename, format, *it, errorList))
1588 loader_format = *it;
1591 if (loader_format.empty()) {
1592 frontend::Alert::error(_("Couldn't import file"),
1593 bformat(_("No information for importing the format %1$s."),
1594 formats.prettyName(format)));
1598 loader_format = format;
1600 if (loader_format == "lyx") {
1601 Buffer * buf = lv->loadDocument(lyxfile);
1604 buf->updateLabels();
1606 buf->errors("Parse");
1608 Buffer * const b = newFile(lyxfile.absFilename(), string(), true);
1612 bool as_paragraphs = loader_format == "textparagraph";
1613 string filename2 = (loader_format == format) ? filename.absFilename()
1614 : support::changeExtension(filename.absFilename(),
1615 formats.extension(loader_format));
1616 lv->currentBufferView()->insertPlaintextFile(FileName(filename2),
1618 guiApp->setCurrentView(lv);
1619 lyx::dispatch(FuncRequest(LFUN_MARK_OFF));
1626 void GuiView::importDocument(string const & argument)
1629 string filename = split(argument, format, ' ');
1631 LYXERR(Debug::INFO, format << " file: " << filename);
1633 // need user interaction
1634 if (filename.empty()) {
1635 string initpath = lyxrc.document_path;
1636 if (documentBufferView()) {
1637 string const trypath = documentBufferView()->buffer().filePath();
1638 // If directory is writeable, use this as default.
1639 if (FileName(trypath).isDirWritable())
1643 docstring const text = bformat(_("Select %1$s file to import"),
1644 formats.prettyName(format));
1646 FileDialog dlg(toqstr(text), LFUN_BUFFER_IMPORT);
1647 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1648 dlg.setButton2(qt_("Examples|#E#e"),
1649 toqstr(addPath(package().system_support().absFilename(), "examples")));
1651 docstring filter = formats.prettyName(format);
1654 filter += from_utf8(formats.extension(format));
1657 FileDialog::Result result =
1658 dlg.open(toqstr(initpath), fileFilters(toqstr(filter)));
1660 if (result.first == FileDialog::Later)
1663 filename = fromqstr(result.second);
1665 // check selected filename
1666 if (filename.empty())
1667 message(_("Canceled."));
1670 if (filename.empty())
1673 // get absolute path of file
1674 FileName const fullname(support::makeAbsPath(filename));
1676 FileName const lyxfile(support::changeExtension(fullname.absFilename(), ".lyx"));
1678 // Check if the document already is open
1679 Buffer * buf = theBufferList().getBuffer(lyxfile);
1682 if (!closeBuffer()) {
1683 message(_("Canceled."));
1688 docstring const displaypath = makeDisplayPath(lyxfile.absFilename(), 30);
1690 // if the file exists already, and we didn't do
1691 // -i lyx thefile.lyx, warn
1692 if (lyxfile.exists() && fullname != lyxfile) {
1694 docstring text = bformat(_("The document %1$s already exists.\n\n"
1695 "Do you want to overwrite that document?"), displaypath);
1696 int const ret = Alert::prompt(_("Overwrite document?"),
1697 text, 0, 1, _("&Overwrite"), _("&Cancel"));
1700 message(_("Canceled."));
1705 message(bformat(_("Importing %1$s..."), displaypath));
1706 ErrorList errorList;
1707 if (import(this, fullname, format, errorList))
1708 message(_("imported."));
1710 message(_("file not imported!"));
1712 // FIXME (Abdel 12/08/06): Is there a need to display the error list here?
1716 void GuiView::newDocument(string const & filename, bool from_template)
1718 FileName initpath(lyxrc.document_path);
1719 if (documentBufferView()) {
1720 FileName const trypath(documentBufferView()->buffer().filePath());
1721 // If directory is writeable, use this as default.
1722 if (trypath.isDirWritable())
1726 string templatefile;
1727 if (from_template) {
1728 templatefile = selectTemplateFile().absFilename();
1729 if (templatefile.empty())
1734 if (filename.empty())
1735 b = newUnnamedFile(templatefile, initpath);
1737 b = newFile(filename, templatefile, true);
1742 // If no new document could be created, it is unsure
1743 // whether there is a valid BufferView.
1744 if (currentBufferView())
1745 // Ensure the cursor is correctly positioned on screen.
1746 currentBufferView()->showCursor();
1750 void GuiView::insertLyXFile(docstring const & fname)
1752 BufferView * bv = documentBufferView();
1757 FileName filename(to_utf8(fname));
1759 if (!filename.empty()) {
1760 bv->insertLyXFile(filename);
1764 // Launch a file browser
1766 string initpath = lyxrc.document_path;
1767 string const trypath = bv->buffer().filePath();
1768 // If directory is writeable, use this as default.
1769 if (FileName(trypath).isDirWritable())
1773 FileDialog dlg(qt_("Select LyX document to insert"), LFUN_FILE_INSERT);
1774 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1775 dlg.setButton2(qt_("Examples|#E#e"),
1776 toqstr(addPath(package().system_support().absFilename(),
1779 FileDialog::Result result = dlg.open(toqstr(initpath),
1780 QStringList(qt_("LyX Documents (*.lyx)")));
1782 if (result.first == FileDialog::Later)
1786 filename.set(fromqstr(result.second));
1788 // check selected filename
1789 if (filename.empty()) {
1790 // emit message signal.
1791 message(_("Canceled."));
1795 bv->insertLyXFile(filename);
1799 void GuiView::insertPlaintextFile(docstring const & fname,
1802 BufferView * bv = documentBufferView();
1806 if (!fname.empty() && !FileName::isAbsolute(to_utf8(fname))) {
1807 message(_("Absolute filename expected."));
1812 FileName filename(to_utf8(fname));
1814 if (!filename.empty()) {
1815 bv->insertPlaintextFile(filename, asParagraph);
1819 FileDialog dlg(qt_("Select file to insert"), (asParagraph ?
1820 LFUN_FILE_INSERT_PLAINTEXT_PARA : LFUN_FILE_INSERT_PLAINTEXT));
1822 FileDialog::Result result = dlg.open(toqstr(bv->buffer().filePath()),
1823 QStringList(qt_("All Files (*)")));
1825 if (result.first == FileDialog::Later)
1829 filename.set(fromqstr(result.second));
1831 // check selected filename
1832 if (filename.empty()) {
1833 // emit message signal.
1834 message(_("Canceled."));
1838 bv->insertPlaintextFile(filename, asParagraph);
1842 bool GuiView::renameBuffer(Buffer & b, docstring const & newname)
1844 FileName fname = b.fileName();
1845 FileName const oldname = fname;
1847 if (!newname.empty()) {
1849 fname = support::makeAbsPath(to_utf8(newname), oldname.onlyPath().absFilename());
1851 // Switch to this Buffer.
1854 // No argument? Ask user through dialog.
1856 FileDialog dlg(qt_("Choose a filename to save document as"),
1857 LFUN_BUFFER_WRITE_AS);
1858 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1859 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
1861 if (!isLyXFilename(fname.absFilename()))
1862 fname.changeExtension(".lyx");
1864 FileDialog::Result result =
1865 dlg.save(toqstr(fname.onlyPath().absFilename()),
1866 QStringList(qt_("LyX Documents (*.lyx)")),
1867 toqstr(fname.onlyFileName()));
1869 if (result.first == FileDialog::Later)
1872 fname.set(fromqstr(result.second));
1877 if (!isLyXFilename(fname.absFilename()))
1878 fname.changeExtension(".lyx");
1881 if (FileName(fname).exists()) {
1882 docstring const file = makeDisplayPath(fname.absFilename(), 30);
1883 docstring text = bformat(_("The document %1$s already "
1884 "exists.\n\nDo you want to "
1885 "overwrite that document?"),
1887 int const ret = Alert::prompt(_("Overwrite document?"),
1888 text, 0, 2, _("&Overwrite"), _("&Rename"), _("&Cancel"));
1891 case 1: return renameBuffer(b, docstring());
1892 case 2: return false;
1896 FileName oldauto = b.getAutosaveFilename();
1898 // Ok, change the name of the buffer
1899 b.setFileName(fname.absFilename());
1901 bool unnamed = b.isUnnamed();
1902 b.setUnnamed(false);
1903 b.saveCheckSum(fname);
1905 // bring the autosave file with us, just in case.
1906 b.moveAutosaveFile(oldauto);
1908 if (!saveBuffer(b)) {
1909 oldauto = b.getAutosaveFilename();
1910 b.setFileName(oldname.absFilename());
1911 b.setUnnamed(unnamed);
1912 b.saveCheckSum(oldname);
1913 b.moveAutosaveFile(oldauto);
1921 bool GuiView::saveBuffer(Buffer & b)
1923 if (workArea(b) && workArea(b)->inDialogMode())
1927 return renameBuffer(b, docstring());
1930 theSession().lastFiles().add(b.fileName());
1934 // Switch to this Buffer.
1937 // FIXME: we don't tell the user *WHY* the save failed !!
1938 docstring const file = makeDisplayPath(b.absFileName(), 30);
1939 docstring text = bformat(_("The document %1$s could not be saved.\n\n"
1940 "Do you want to rename the document and "
1941 "try again?"), file);
1942 int const ret = Alert::prompt(_("Rename and save?"),
1943 text, 0, 2, _("&Rename"), _("&Retry"), _("&Cancel"));
1946 if (!renameBuffer(b, docstring()))
1955 return saveBuffer(b);
1959 bool GuiView::hideWorkArea(GuiWorkArea * wa)
1961 return closeWorkArea(wa, false);
1965 bool GuiView::closeWorkArea(GuiWorkArea * wa)
1967 Buffer & buf = wa->bufferView().buffer();
1968 return closeWorkArea(wa, !buf.parent());
1972 bool GuiView::closeBuffer()
1974 GuiWorkArea * wa = currentMainWorkArea();
1975 Buffer & buf = wa->bufferView().buffer();
1976 return wa && closeWorkArea(wa, !buf.parent());
1980 void GuiView::writeSession() const {
1981 GuiWorkArea const * active_wa = currentMainWorkArea();
1982 for (int i = 0; i < d.splitter_->count(); ++i) {
1983 TabWorkArea * twa = d.tabWorkArea(i);
1984 for (int j = 0; j < twa->count(); ++j) {
1985 GuiWorkArea * wa = static_cast<GuiWorkArea *>(twa->widget(j));
1986 Buffer & buf = wa->bufferView().buffer();
1987 theSession().lastOpened().add(buf.fileName(), wa == active_wa);
1993 bool GuiView::closeBufferAll()
1995 // Close the workareas in all other views
1996 QList<int> const ids = guiApp->viewIds();
1997 for (int i = 0; i != ids.size(); ++i) {
1998 if (id_ != ids[i] && !guiApp->view(ids[i]).closeWorkAreaAll())
2002 // Close our own workareas
2003 if (!closeWorkAreaAll())
2006 // Now close the hidden buffers. We prevent hidden buffers from being
2007 // dirty, so we can just close them.
2008 theBufferList().closeAll();
2013 bool GuiView::closeWorkAreaAll()
2015 setCurrentWorkArea(currentMainWorkArea());
2017 // We might be in a situation that there is still a tabWorkArea, but
2018 // there are no tabs anymore. This can happen when we get here after a
2019 // TabWorkArea::lastWorkAreaRemoved() signal. Therefore we count how
2020 // many TabWorkArea's have no documents anymore.
2023 // We have to call count() each time, because it can happen that
2024 // more than one splitter will disappear in one iteration (bug 5998).
2025 for (; d.splitter_->count() > empty_twa; ) {
2026 TabWorkArea * twa = d.tabWorkArea(empty_twa);
2028 if (twa->count() == 0)
2031 setCurrentWorkArea(twa->currentWorkArea());
2032 if (!closeTabWorkArea(twa))
2040 bool GuiView::closeWorkArea(GuiWorkArea * wa, bool close_buffer)
2042 Buffer & buf = wa->bufferView().buffer();
2044 // If we are in a close_event all children will be closed in some time,
2045 // so no need to do it here. This will ensure that the children end up
2046 // in the session file in the correct order. If we close the master
2047 // buffer, we can close or release the child buffers here too.
2048 if (close_buffer && !closing_) {
2049 vector<Buffer *> clist = buf.getChildren();
2050 for (vector<Buffer *>::const_iterator it = clist.begin();
2051 it != clist.end(); ++it) {
2052 // If a child is dirty, do not close
2053 // without user intervention
2054 //FIXME: should we look in other tabworkareas?
2055 Buffer * child_buf = *it;
2056 GuiWorkArea * child_wa = workArea(*child_buf);
2058 if (!closeWorkArea(child_wa, true))
2061 theBufferList().releaseChild(&buf, child_buf);
2064 // goto bookmark to update bookmark pit.
2065 //FIXME: we should update only the bookmarks related to this buffer!
2066 LYXERR(Debug::DEBUG, "GuiView::closeBuffer()");
2067 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
2068 theLyXFunc().gotoBookmark(i+1, false, false);
2070 // if we are only hiding the buffer and there are multiple views
2071 // of the buffer, then we do not need to ensure a clean buffer.
2072 bool const allow_dirty = inMultiTabs(wa) && !close_buffer;
2074 if (allow_dirty || saveBufferIfNeeded(buf, !close_buffer)) {
2075 // save in sessions if requested
2076 // do not save childs if their master
2077 // is opened as well
2081 theBufferList().release(&buf);
2088 bool GuiView::closeTabWorkArea(TabWorkArea * twa)
2090 while (twa == d.currentTabWorkArea()) {
2091 twa->setCurrentIndex(twa->count()-1);
2093 GuiWorkArea * wa = twa->currentWorkArea();
2094 Buffer & b = wa->bufferView().buffer();
2096 // We only want to close the buffer if the same buffer is not visible
2097 // in another view, and if this is not a child and if we are closing
2098 // a view (not a tabgroup).
2099 bool const close_buffer =
2100 !inMultiViews(wa) && !b.parent() && closing_;
2102 if (!closeWorkArea(wa, close_buffer))
2109 bool GuiView::saveBufferIfNeeded(Buffer & buf, bool hiding)
2111 if (buf.isClean() || buf.paragraphs().empty())
2114 // Switch to this Buffer.
2119 if (buf.isUnnamed())
2120 file = from_utf8(buf.fileName().onlyFileName());
2122 file = buf.fileName().displayName(30);
2124 // Bring this window to top before asking questions.
2129 if (hiding && buf.isUnnamed()) {
2130 docstring const text = bformat(_("The document %1$s has not been "
2131 "saved yet.\n\nDo you want to save "
2132 "the document?"), file);
2133 ret = Alert::prompt(_("Save new document?"),
2134 text, 0, 1, _("&Save"), _("&Cancel"));
2138 docstring const text = bformat(_("The document %1$s has unsaved changes."
2139 "\n\nDo you want to save the document or discard the changes?"), file);
2140 ret = Alert::prompt(_("Save changed document?"),
2141 text, 0, 2, _("&Save"), _("&Discard"), _("&Cancel"));
2146 if (!saveBuffer(buf))
2150 // if we crash after this we could
2151 // have no autosave file but I guess
2152 // this is really improbable (Jug)
2153 buf.removeAutosaveFile();
2155 // revert all changes
2156 buf.loadLyXFile(buf.fileName());
2166 bool GuiView::inMultiTabs(GuiWorkArea * wa)
2168 Buffer & buf = wa->bufferView().buffer();
2170 for (int i = 0; i != d.splitter_->count(); ++i) {
2171 GuiWorkArea * wa_ = d.tabWorkArea(i)->workArea(buf);
2172 if (wa_ && wa_ != wa)
2175 return inMultiViews(wa);
2179 bool GuiView::inMultiViews(GuiWorkArea * wa)
2181 QList<int> const ids = guiApp->viewIds();
2182 Buffer & buf = wa->bufferView().buffer();
2185 for (int i = 0; i != ids.size() && found_twa <= 1; ++i) {
2189 if (guiApp->view(ids[i]).workArea(buf))
2196 void GuiView::gotoNextOrPreviousBuffer(NextOrPrevious np)
2198 Buffer * const curbuf = documentBufferView()
2199 ? &documentBufferView()->buffer() : 0;
2200 Buffer * nextbuf = curbuf;
2202 if (np == NEXTBUFFER)
2203 nextbuf = theBufferList().next(nextbuf);
2205 nextbuf = theBufferList().previous(nextbuf);
2206 if (nextbuf == curbuf)
2212 if (workArea(*nextbuf))
2219 /// make sure the document is saved
2220 static bool ensureBufferClean(Buffer * buffer)
2222 LASSERT(buffer, return false);
2223 if (buffer->isClean() && !buffer->isUnnamed())
2226 docstring const file = buffer->fileName().displayName(30);
2229 if (!buffer->isUnnamed()) {
2230 text = bformat(_("The document %1$s has unsaved "
2231 "changes.\n\nDo you want to save "
2232 "the document?"), file);
2233 title = _("Save changed document?");
2236 text = bformat(_("The document %1$s has not been "
2237 "saved yet.\n\nDo you want to save "
2238 "the document?"), file);
2239 title = _("Save new document?");
2241 int const ret = Alert::prompt(title, text, 0, 1, _("&Save"), _("&Cancel"));
2244 dispatch(FuncRequest(LFUN_BUFFER_WRITE));
2246 return buffer->isClean() && !buffer->isUnnamed();
2250 void GuiView::reloadBuffer()
2252 Buffer * buf = &documentBufferView()->buffer();
2253 FileName filename = buf->fileName();
2254 // The user has already confirmed that the changes, if any, should
2255 // be discarded. So we just release the Buffer and don't call closeBuffer();
2256 theBufferList().release(buf);
2257 buf = loadDocument(filename);
2258 docstring const disp_fn = makeDisplayPath(filename.absFilename());
2261 buf->updateLabels();
2263 buf->errors("Parse");
2264 str = bformat(_("Document %1$s reloaded."), disp_fn);
2266 str = bformat(_("Could not reload document %1$s"), disp_fn);
2272 void GuiView::dispatchVC(FuncRequest const & cmd)
2274 Buffer * buffer = documentBufferView()
2275 ? &(documentBufferView()->buffer()) : 0;
2277 switch (cmd.action) {
2278 case LFUN_VC_REGISTER:
2279 if (!buffer || !ensureBufferClean(buffer))
2281 if (!buffer->lyxvc().inUse()) {
2282 if (buffer->lyxvc().registrer())
2287 case LFUN_VC_CHECK_IN:
2288 if (!buffer || !ensureBufferClean(buffer))
2290 if (buffer->lyxvc().inUse() && !buffer->isReadonly()) {
2291 message(from_utf8(buffer->lyxvc().checkIn()));
2296 case LFUN_VC_CHECK_OUT:
2297 if (!buffer || !ensureBufferClean(buffer))
2299 if (buffer->lyxvc().inUse()) {
2300 message(from_utf8(buffer->lyxvc().checkOut()));
2305 case LFUN_VC_LOCKING_TOGGLE:
2306 LASSERT(buffer, return);
2307 if (!ensureBufferClean(buffer) || buffer->isReadonly())
2309 if (buffer->lyxvc().inUse()) {
2310 string res = buffer->lyxvc().lockingToggle();
2312 frontend::Alert::error(_("Revision control error."),
2313 _("Error when setting the locking property."));
2315 message(from_utf8(res));
2321 case LFUN_VC_REVERT:
2322 LASSERT(buffer, return);
2323 buffer->lyxvc().revert();
2327 case LFUN_VC_UNDO_LAST:
2328 LASSERT(buffer, return);
2329 buffer->lyxvc().undoLast();
2333 case LFUN_VC_COMMAND: {
2334 string flag = cmd.getArg(0);
2335 if (buffer && contains(flag, 'R') && !ensureBufferClean(buffer))
2338 if (contains(flag, 'M')) {
2339 if (!Alert::askForText(message, _("LyX VC: Log Message")))
2342 string path = cmd.getArg(1);
2343 if (contains(path, "$$p") && buffer)
2344 path = subst(path, "$$p", buffer->filePath());
2345 LYXERR(Debug::LYXVC, "Directory: " << path);
2347 if (!pp.isReadableDirectory()) {
2348 lyxerr << _("Directory is not accessible.") << endl;
2351 support::PathChanger p(pp);
2353 string command = cmd.getArg(2);
2354 if (command.empty())
2357 command = subst(command, "$$i", buffer->absFileName());
2358 command = subst(command, "$$p", buffer->filePath());
2360 command = subst(command, "$$m", to_utf8(message));
2361 LYXERR(Debug::LYXVC, "Command: " << command);
2363 one.startscript(Systemcall::Wait, command);
2367 if (contains(flag, 'I'))
2368 buffer->markDirty();
2369 if (contains(flag, 'R'))
2380 void GuiView::openChildDocument(string const & fname)
2382 LASSERT(documentBufferView(), return);
2383 Buffer & buffer = documentBufferView()->buffer();
2384 FileName const filename = support::makeAbsPath(fname, buffer.filePath());
2385 documentBufferView()->saveBookmark(false);
2387 bool parsed = false;
2388 if (theBufferList().exists(filename)) {
2389 child = theBufferList().getBuffer(filename);
2391 message(bformat(_("Opening child document %1$s..."),
2392 makeDisplayPath(filename.absFilename())));
2393 child = loadDocument(filename, false);
2399 // Set the parent name of the child document.
2400 // This makes insertion of citations and references in the child work,
2401 // when the target is in the parent or another child document.
2402 child->setParent(&buffer);
2403 child->masterBuffer()->updateLabels();
2406 child->errors("Parse");
2410 bool GuiView::goToFileRow(string const & argument)
2414 istringstream is(argument);
2415 is >> file_name >> row;
2416 file_name = os::internal_path(file_name);
2418 string const abstmp = package().temp_dir().absFilename();
2419 string const realtmp = package().temp_dir().realPath();
2420 // We have to use os::path_prefix_is() here, instead of
2421 // simply prefixIs(), because the file name comes from
2422 // an external application and may need case adjustment.
2423 if (os::path_prefix_is(file_name, abstmp, os::CASE_ADJUSTED)
2424 || os::path_prefix_is(file_name, realtmp, os::CASE_ADJUSTED)) {
2425 // Needed by inverse dvi search. If it is a file
2426 // in tmpdir, call the apropriated function.
2427 // If tmpdir is a symlink, we may have the real
2428 // path passed back, so we correct for that.
2429 if (!prefixIs(file_name, abstmp))
2430 file_name = subst(file_name, realtmp, abstmp);
2431 buf = theBufferList().getBufferFromTmp(file_name);
2433 // Must replace extension of the file to be .lyx
2434 // and get full path
2435 FileName const s = fileSearch(string(),
2436 support::changeExtension(file_name, ".lyx"), "lyx");
2437 // Either change buffer or load the file
2438 if (theBufferList().exists(s))
2439 buf = theBufferList().getBuffer(s);
2440 else if (s.exists()) {
2441 buf = loadDocument(s);
2442 buf->updateLabels();
2443 buf->errors("Parse");
2446 _("File does not exist: %1$s"),
2447 makeDisplayPath(file_name)));
2452 documentBufferView()->setCursorFromRow(row);
2457 bool GuiView::dispatch(FuncRequest const & cmd)
2459 BufferView * bv = currentBufferView();
2460 // By default we won't need any update.
2462 bv->cursor().updateFlags(Update::None);
2464 Buffer * doc_buffer = documentBufferView()
2465 ? &(documentBufferView()->buffer()) : 0;
2467 bool dispatched = true;
2469 if (cmd.origin == FuncRequest::TOC) {
2470 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
2471 toc->doDispatch(bv->cursor(), cmd);
2475 switch(cmd.action) {
2476 case LFUN_BUFFER_CHILD_OPEN:
2477 openChildDocument(to_utf8(cmd.argument()));
2480 case LFUN_BUFFER_IMPORT:
2481 importDocument(to_utf8(cmd.argument()));
2484 case LFUN_BUFFER_SWITCH:
2485 if (FileName::isAbsolute(to_utf8(cmd.argument()))) {
2487 theBufferList().getBuffer(FileName(to_utf8(cmd.argument())));
2491 bv->cursor().message(_("Document not loaded"));
2495 case LFUN_BUFFER_NEXT:
2496 gotoNextOrPreviousBuffer(NEXTBUFFER);
2499 case LFUN_BUFFER_PREVIOUS:
2500 gotoNextOrPreviousBuffer(PREVBUFFER);
2503 case LFUN_COMMAND_EXECUTE: {
2504 bool const show_it = cmd.argument() != "off";
2505 // FIXME: this is a hack, "minibuffer" should not be
2507 if (GuiToolbar * t = toolbar("minibuffer")) {
2508 t->setVisible(show_it);
2509 if (show_it && t->commandBuffer())
2510 t->commandBuffer()->setFocus();
2514 case LFUN_DROP_LAYOUTS_CHOICE:
2515 d.layout_->showPopup();
2518 case LFUN_MENU_OPEN:
2519 if (QMenu * menu = guiApp->menus().menu(toqstr(cmd.argument()), *this))
2520 menu->exec(QCursor::pos());
2523 case LFUN_FILE_INSERT:
2524 insertLyXFile(cmd.argument());
2526 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
2527 insertPlaintextFile(cmd.argument(), true);
2530 case LFUN_FILE_INSERT_PLAINTEXT:
2531 insertPlaintextFile(cmd.argument(), false);
2534 case LFUN_BUFFER_RELOAD: {
2535 LASSERT(doc_buffer, break);
2536 docstring const file = makeDisplayPath(doc_buffer->absFileName(), 20);
2537 docstring text = bformat(_("Any changes will be lost. Are you sure "
2538 "you want to revert to the saved version of the document %1$s?"), file);
2539 int const ret = Alert::prompt(_("Revert to saved document?"),
2540 text, 1, 1, _("&Revert"), _("&Cancel"));
2547 case LFUN_BUFFER_WRITE:
2548 LASSERT(doc_buffer, break);
2549 saveBuffer(*doc_buffer);
2552 case LFUN_BUFFER_WRITE_AS:
2553 LASSERT(doc_buffer, break);
2554 renameBuffer(*doc_buffer, cmd.argument());
2557 case LFUN_BUFFER_WRITE_ALL: {
2558 Buffer * first = theBufferList().first();
2561 message(_("Saving all documents..."));
2562 // We cannot use a for loop as the buffer list cycles.
2565 if (!b->isClean()) {
2567 LYXERR(Debug::ACTION, "Saved " << b->absFileName());
2569 b = theBufferList().next(b);
2570 } while (b != first);
2571 message(_("All documents saved."));
2575 case LFUN_BUFFER_CLOSE:
2579 case LFUN_BUFFER_CLOSE_ALL:
2583 case LFUN_TOOLBAR_TOGGLE: {
2584 string const name = cmd.getArg(0);
2585 if (GuiToolbar * t = toolbar(name))
2590 case LFUN_DIALOG_UPDATE: {
2591 string const name = to_utf8(cmd.argument());
2592 // Can only update a dialog connected to an existing inset
2593 Inset * inset = getOpenInset(name);
2595 FuncRequest fr(LFUN_INSET_DIALOG_UPDATE, cmd.argument());
2596 inset->dispatch(currentBufferView()->cursor(), fr);
2597 } else if (name == "paragraph") {
2598 lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
2599 } else if (name == "prefs" || name == "document") {
2600 updateDialog(name, string());
2605 case LFUN_DIALOG_TOGGLE: {
2606 if (isDialogVisible(cmd.getArg(0)))
2607 dispatch(FuncRequest(LFUN_DIALOG_HIDE, cmd.argument()));
2609 dispatch(FuncRequest(LFUN_DIALOG_SHOW, cmd.argument()));
2613 case LFUN_DIALOG_DISCONNECT_INSET:
2614 disconnectDialog(to_utf8(cmd.argument()));
2617 case LFUN_DIALOG_HIDE: {
2618 guiApp->hideDialogs(to_utf8(cmd.argument()), 0);
2622 case LFUN_DIALOG_SHOW: {
2623 string const name = cmd.getArg(0);
2624 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
2626 if (name == "character") {
2627 data = freefont2string();
2629 showDialog("character", data);
2630 } else if (name == "latexlog") {
2631 Buffer::LogType type;
2632 string const logfile = doc_buffer->logName(&type);
2634 case Buffer::latexlog:
2637 case Buffer::buildlog:
2641 data += Lexer::quoteString(logfile);
2642 showDialog("log", data);
2643 } else if (name == "vclog") {
2644 string const data = "vc " +
2645 Lexer::quoteString(doc_buffer->lyxvc().getLogFile());
2646 showDialog("log", data);
2647 } else if (name == "symbols") {
2648 data = bv->cursor().getEncoding()->name();
2650 showDialog("symbols", data);
2652 } else if (name == "prefs" && isFullScreen()) {
2653 FuncRequest fr(LFUN_INSET_INSERT, "fullscreen");
2655 showDialog("prefs", data);
2657 showDialog(name, data);
2662 message(cmd.argument());
2665 case LFUN_INSET_APPLY: {
2666 string const name = cmd.getArg(0);
2667 Inset * inset = getOpenInset(name);
2669 // put cursor in front of inset.
2670 if (!currentBufferView()->setCursorFromInset(inset)) {
2671 LASSERT(false, break);
2673 BufferView * bv = currentBufferView();
2674 // useful if we are called from a dialog.
2675 bv->cursor().beginUndoGroup();
2676 bv->cursor().recordUndo();
2677 FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument());
2678 inset->dispatch(bv->cursor(), fr);
2679 bv->cursor().endUndoGroup();
2681 FuncRequest fr(LFUN_INSET_INSERT, cmd.argument());
2687 case LFUN_UI_TOGGLE:
2689 // Make sure the keyboard focus stays in the work area.
2693 case LFUN_SPLIT_VIEW: {
2694 LASSERT(doc_buffer, break);
2695 string const orientation = cmd.getArg(0);
2696 d.splitter_->setOrientation(orientation == "vertical"
2697 ? Qt::Vertical : Qt::Horizontal);
2698 TabWorkArea * twa = addTabWorkArea();
2699 GuiWorkArea * wa = twa->addWorkArea(*doc_buffer, *this);
2700 setCurrentWorkArea(wa);
2703 case LFUN_CLOSE_TAB_GROUP:
2704 if (TabWorkArea * twa = d.currentTabWorkArea()) {
2705 closeTabWorkArea(twa);
2706 d.current_work_area_ = 0;
2707 twa = d.currentTabWorkArea();
2708 // Switch to the next GuiWorkArea in the found TabWorkArea.
2710 // Make sure the work area is up to date.
2711 setCurrentWorkArea(twa->currentWorkArea());
2713 setCurrentWorkArea(0);
2718 case LFUN_COMPLETION_INLINE:
2719 if (d.current_work_area_)
2720 d.current_work_area_->completer().showInline();
2723 case LFUN_COMPLETION_POPUP:
2724 if (d.current_work_area_)
2725 d.current_work_area_->completer().showPopup();
2729 case LFUN_COMPLETION_COMPLETE:
2730 if (d.current_work_area_)
2731 d.current_work_area_->completer().tab();
2734 case LFUN_COMPLETION_CANCEL:
2735 if (d.current_work_area_) {
2736 if (d.current_work_area_->completer().popupVisible())
2737 d.current_work_area_->completer().hidePopup();
2739 d.current_work_area_->completer().hideInline();
2743 case LFUN_COMPLETION_ACCEPT:
2744 if (d.current_work_area_)
2745 d.current_work_area_->completer().activate();
2748 case LFUN_BUFFER_ZOOM_IN:
2749 case LFUN_BUFFER_ZOOM_OUT:
2750 if (cmd.argument().empty()) {
2751 if (cmd.action == LFUN_BUFFER_ZOOM_IN)
2756 lyxrc.zoom += convert<int>(cmd.argument());
2758 if (lyxrc.zoom < 10)
2761 // The global QPixmapCache is used in GuiPainter to cache text
2762 // painting so we must reset it.
2763 QPixmapCache::clear();
2764 guiApp->fontLoader().update();
2765 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
2768 case LFUN_VC_REGISTER:
2769 case LFUN_VC_CHECK_IN:
2770 case LFUN_VC_CHECK_OUT:
2771 case LFUN_VC_LOCKING_TOGGLE:
2772 case LFUN_VC_REVERT:
2773 case LFUN_VC_UNDO_LAST:
2774 case LFUN_VC_COMMAND:
2778 case LFUN_SERVER_GOTO_FILE_ROW:
2779 goToFileRow(to_utf8(cmd.argument()));
2787 // Part of automatic menu appearance feature.
2788 if (isFullScreen()) {
2789 if (menuBar()->isVisible() && lyxrc.full_screen_menubar)
2791 if (statusBar()->isVisible())
2792 statusBar()->hide();
2799 void GuiView::lfunUiToggle(FuncRequest const & cmd)
2801 string const arg = cmd.getArg(0);
2802 if (arg == "scrollbar") {
2803 // hide() is of no help
2804 if (d.current_work_area_->verticalScrollBarPolicy() ==
2805 Qt::ScrollBarAlwaysOff)
2807 d.current_work_area_->setVerticalScrollBarPolicy(
2808 Qt::ScrollBarAsNeeded);
2810 d.current_work_area_->setVerticalScrollBarPolicy(
2811 Qt::ScrollBarAlwaysOff);
2814 if (arg == "statusbar") {
2815 statusBar()->setVisible(!statusBar()->isVisible());
2818 if (arg == "menubar") {
2819 menuBar()->setVisible(!menuBar()->isVisible());
2822 #if QT_VERSION >= 0x040300
2823 if (arg == "frame") {
2825 getContentsMargins(&l, &t, &r, &b);
2826 //are the frames in default state?
2827 d.current_work_area_->setFrameStyle(QFrame::NoFrame);
2829 setContentsMargins(-2, -2, -2, -2);
2831 setContentsMargins(0, 0, 0, 0);
2836 if (arg == "fullscreen") {
2841 message(bformat("LFUN_UI_TOGGLE " + _("%1$s unknown command!"), from_utf8(arg)));
2845 void GuiView::toggleFullScreen()
2847 if (isFullScreen()) {
2848 for (int i = 0; i != d.splitter_->count(); ++i)
2849 d.tabWorkArea(i)->setFullScreen(false);
2850 #if QT_VERSION >= 0x040300
2851 setContentsMargins(0, 0, 0, 0);
2853 setWindowState(windowState() ^ Qt::WindowFullScreen);
2856 statusBar()->show();
2859 hideDialogs("prefs", 0);
2860 for (int i = 0; i != d.splitter_->count(); ++i)
2861 d.tabWorkArea(i)->setFullScreen(true);
2862 #if QT_VERSION >= 0x040300
2863 setContentsMargins(-2, -2, -2, -2);
2866 setWindowState(windowState() ^ Qt::WindowFullScreen);
2867 statusBar()->hide();
2868 if (lyxrc.full_screen_menubar)
2870 if (lyxrc.full_screen_toolbars) {
2871 ToolbarMap::iterator end = d.toolbars_.end();
2872 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
2877 // give dialogs like the TOC a chance to adapt
2882 Buffer const * GuiView::updateInset(Inset const * inset)
2884 if (!d.current_work_area_)
2888 d.current_work_area_->scheduleRedraw();
2890 return &d.current_work_area_->bufferView().buffer();
2894 void GuiView::restartCursor()
2896 /* When we move around, or type, it's nice to be able to see
2897 * the cursor immediately after the keypress.
2899 if (d.current_work_area_)
2900 d.current_work_area_->startBlinkingCursor();
2902 // Take this occasion to update the other GUI elements.
2908 void GuiView::updateCompletion(Cursor & cur, bool start, bool keep)
2910 if (d.current_work_area_)
2911 d.current_work_area_->completer().updateVisibility(cur, start, keep);
2916 // This list should be kept in sync with the list of insets in
2917 // src/insets/Inset.cpp. I.e., if a dialog goes with an inset, the
2918 // dialog should have the same name as the inset.
2919 // Changes should be also recorded in LFUN_DIALOG_SHOW doxygen
2920 // docs in LyXAction.cpp.
2922 char const * const dialognames[] = {
2923 "aboutlyx", "bibitem", "bibtex", "box", "branch", "changes", "character",
2924 "citation", "document", "errorlist", "ert", "external", "file", "findreplace",
2925 "findreplaceadv", "float", "graphics", "href", "include", "index",
2926 "index_print", "info", "listings", "label", "log", "mathdelimiter",
2927 "mathmatrix", "mathspace", "nomenclature", "nomencl_print", "note",
2928 "paragraph", "phantom", "prefs", "print", "ref", "sendto", "space",
2929 "spellchecker", "symbols", "tabular", "tabularcreate", "thesaurus", "texinfo",
2930 "toc", "view-source", "vspace", "wrap" };
2932 char const * const * const end_dialognames =
2933 dialognames + (sizeof(dialognames) / sizeof(char *));
2937 cmpCStr(char const * name) : name_(name) {}
2938 bool operator()(char const * other) {
2939 return strcmp(other, name_) == 0;
2946 bool isValidName(string const & name)
2948 return find_if(dialognames, end_dialognames,
2949 cmpCStr(name.c_str())) != end_dialognames;
2955 void GuiView::resetDialogs()
2957 // Make sure that no LFUN uses any LyXView.
2958 guiApp->setCurrentView(0);
2961 constructToolbars();
2962 guiApp->menus().fillMenuBar(menuBar(), this, false);
2963 d.layout_->updateContents(true);
2964 // Now update controls with current buffer.
2965 guiApp->setCurrentView(this);
2971 Dialog * GuiView::findOrBuild(string const & name, bool hide_it)
2973 if (!isValidName(name))
2976 map<string, DialogPtr>::iterator it = d.dialogs_.find(name);
2978 if (it != d.dialogs_.end()) {
2980 it->second->hideView();
2981 return it->second.get();
2984 Dialog * dialog = build(name);
2985 d.dialogs_[name].reset(dialog);
2986 if (lyxrc.allow_geometry_session)
2987 dialog->restoreSession();
2994 void GuiView::showDialog(string const & name, string const & data,
3002 Dialog * dialog = findOrBuild(name, false);
3004 dialog->showData(data);
3006 d.open_insets_[name] = inset;
3009 catch (ExceptionMessage const & ex) {
3017 bool GuiView::isDialogVisible(string const & name) const
3019 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3020 if (it == d.dialogs_.end())
3022 return it->second.get()->isVisibleView() && !it->second.get()->isClosing();
3026 void GuiView::hideDialog(string const & name, Inset * inset)
3028 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3029 if (it == d.dialogs_.end())
3032 if (inset && inset != getOpenInset(name))
3035 Dialog * const dialog = it->second.get();
3036 if (dialog->isVisibleView())
3038 d.open_insets_[name] = 0;
3042 void GuiView::disconnectDialog(string const & name)
3044 if (!isValidName(name))
3047 if (d.open_insets_.find(name) != d.open_insets_.end())
3048 d.open_insets_[name] = 0;
3052 Inset * GuiView::getOpenInset(string const & name) const
3054 if (!isValidName(name))
3057 map<string, Inset *>::const_iterator it = d.open_insets_.find(name);
3058 return it == d.open_insets_.end() ? 0 : it->second;
3062 void GuiView::hideAll() const
3064 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
3065 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3067 for(; it != end; ++it)
3068 it->second->hideView();
3072 void GuiView::updateDialogs()
3074 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
3075 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3077 for(; it != end; ++it) {
3078 Dialog * dialog = it->second.get();
3079 if (dialog && dialog->isVisibleView())
3080 dialog->checkStatus();
3087 // will be replaced by a proper factory...
3088 Dialog * createGuiAbout(GuiView & lv);
3089 Dialog * createGuiBibitem(GuiView & lv);
3090 Dialog * createGuiBibtex(GuiView & lv);
3091 Dialog * createGuiBox(GuiView & lv);
3092 Dialog * createGuiBranch(GuiView & lv);
3093 Dialog * createGuiChanges(GuiView & lv);
3094 Dialog * createGuiCharacter(GuiView & lv);
3095 Dialog * createGuiCitation(GuiView & lv);
3096 Dialog * createGuiDelimiter(GuiView & lv);
3097 Dialog * createGuiDocument(GuiView & lv);
3098 Dialog * createGuiErrorList(GuiView & lv);
3099 Dialog * createGuiERT(GuiView & lv);
3100 Dialog * createGuiExternal(GuiView & lv);
3101 Dialog * createGuiFloat(GuiView & lv);
3102 Dialog * createGuiGraphics(GuiView & lv);
3103 Dialog * createGuiInclude(GuiView & lv);
3104 Dialog * createGuiIndex(GuiView & lv);
3105 Dialog * createGuiInfo(GuiView & lv);
3106 Dialog * createGuiLabel(GuiView & lv);
3107 Dialog * createGuiListings(GuiView & lv);
3108 Dialog * createGuiLog(GuiView & lv);
3109 Dialog * createGuiMathHSpace(GuiView & lv);
3110 Dialog * createGuiMathMatrix(GuiView & lv);
3111 Dialog * createGuiNomenclature(GuiView & lv);
3112 Dialog * createGuiNote(GuiView & lv);
3113 Dialog * createGuiParagraph(GuiView & lv);
3114 Dialog * createGuiPhantom(GuiView & lv);
3115 Dialog * createGuiPreferences(GuiView & lv);
3116 Dialog * createGuiPrint(GuiView & lv);
3117 Dialog * createGuiPrintindex(GuiView & lv);
3118 Dialog * createGuiPrintNomencl(GuiView & lv);
3119 Dialog * createGuiRef(GuiView & lv);
3120 Dialog * createGuiSearch(GuiView & lv);
3121 Dialog * createGuiSearchAdv(GuiView & lv);
3122 Dialog * createGuiSendTo(GuiView & lv);
3123 Dialog * createGuiShowFile(GuiView & lv);
3124 Dialog * createGuiSpellchecker(GuiView & lv);
3125 Dialog * createGuiSymbols(GuiView & lv);
3126 Dialog * createGuiTabularCreate(GuiView & lv);
3127 Dialog * createGuiTabular(GuiView & lv);
3128 Dialog * createGuiTexInfo(GuiView & lv);
3129 Dialog * createGuiTextHSpace(GuiView & lv);
3130 Dialog * createGuiToc(GuiView & lv);
3131 Dialog * createGuiThesaurus(GuiView & lv);
3132 Dialog * createGuiHyperlink(GuiView & lv);
3133 Dialog * createGuiVSpace(GuiView & lv);
3134 Dialog * createGuiViewSource(GuiView & lv);
3135 Dialog * createGuiWrap(GuiView & lv);
3138 Dialog * GuiView::build(string const & name)
3140 LASSERT(isValidName(name), return 0);
3142 if (name == "aboutlyx")
3143 return createGuiAbout(*this);
3144 if (name == "bibitem")
3145 return createGuiBibitem(*this);
3146 if (name == "bibtex")
3147 return createGuiBibtex(*this);
3149 return createGuiBox(*this);
3150 if (name == "branch")
3151 return createGuiBranch(*this);
3152 if (name == "changes")
3153 return createGuiChanges(*this);
3154 if (name == "character")
3155 return createGuiCharacter(*this);
3156 if (name == "citation")
3157 return createGuiCitation(*this);
3158 if (name == "document")
3159 return createGuiDocument(*this);
3160 if (name == "errorlist")
3161 return createGuiErrorList(*this);
3163 return createGuiERT(*this);
3164 if (name == "external")
3165 return createGuiExternal(*this);
3167 return createGuiShowFile(*this);
3168 if (name == "findreplace")
3169 return createGuiSearch(*this);
3170 if (name == "findreplaceadv")
3171 return createGuiSearchAdv(*this);
3172 if (name == "float")
3173 return createGuiFloat(*this);
3174 if (name == "graphics")
3175 return createGuiGraphics(*this);
3177 return createGuiHyperlink(*this);
3178 if (name == "include")
3179 return createGuiInclude(*this);
3180 if (name == "index")
3181 return createGuiIndex(*this);
3182 if (name == "index_print")
3183 return createGuiPrintindex(*this);
3185 return createGuiInfo(*this);
3186 if (name == "label")
3187 return createGuiLabel(*this);
3188 if (name == "listings")
3189 return createGuiListings(*this);
3191 return createGuiLog(*this);
3192 if (name == "mathdelimiter")
3193 return createGuiDelimiter(*this);
3194 if (name == "mathspace")
3195 return createGuiMathHSpace(*this);
3196 if (name == "mathmatrix")
3197 return createGuiMathMatrix(*this);
3198 if (name == "nomenclature")
3199 return createGuiNomenclature(*this);
3200 if (name == "nomencl_print")
3201 return createGuiPrintNomencl(*this);
3203 return createGuiNote(*this);
3204 if (name == "paragraph")
3205 return createGuiParagraph(*this);
3206 if (name == "phantom")
3207 return createGuiPhantom(*this);
3208 if (name == "prefs")
3209 return createGuiPreferences(*this);
3210 if (name == "print")
3211 return createGuiPrint(*this);
3213 return createGuiRef(*this);
3214 if (name == "sendto")
3215 return createGuiSendTo(*this);
3216 if (name == "space")
3217 return createGuiTextHSpace(*this);
3218 if (name == "spellchecker")
3219 return createGuiSpellchecker(*this);
3220 if (name == "symbols")
3221 return createGuiSymbols(*this);
3222 if (name == "tabular")
3223 return createGuiTabular(*this);
3224 if (name == "tabularcreate")
3225 return createGuiTabularCreate(*this);
3226 if (name == "texinfo")
3227 return createGuiTexInfo(*this);
3228 if (name == "thesaurus")
3229 return createGuiThesaurus(*this);
3231 return createGuiToc(*this);
3232 if (name == "view-source")
3233 return createGuiViewSource(*this);
3234 if (name == "vspace")
3235 return createGuiVSpace(*this);
3237 return createGuiWrap(*this);
3243 } // namespace frontend
3246 #include "moc_GuiView.cpp"