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()));
614 string const ext = support::getExtension(file);
615 vector<const Format *> found_formats;
617 // Find all formats that have the correct extension.
618 vector<const Format *> const & import_formats
619 = theConverters().importableFormats();
620 vector<const Format *>::const_iterator it = import_formats.begin();
621 for (; it != import_formats.end(); ++it)
622 if ((*it)->extension() == ext)
623 found_formats.push_back(*it);
626 if (found_formats.size() >= 1) {
627 if (found_formats.size() > 1) {
628 //FIXME: show a dialog to choose the correct importable format
630 "Multiple importable formats found, selecting first");
632 string const arg = found_formats[0]->name() + " " + file;
633 cmd = FuncRequest(LFUN_BUFFER_IMPORT, arg);
636 //FIXME: do we have to explicitly check whether it's a lyx file?
638 "No formats found, trying to open it as a lyx file");
639 cmd = FuncRequest(LFUN_FILE_OPEN, file);
642 // Asynchronously post the event. DropEvent usually come
643 // from the BufferView. But reloading a file might close
644 // the BufferView from within its own event handler.
645 guiApp->dispatchDelayed(cmd);
651 void GuiView::message(docstring const & str)
653 if (ForkedProcess::iAmAChild())
656 statusBar()->showMessage(toqstr(str));
657 d.statusbar_timer_.stop();
658 d.statusbar_timer_.start(3000);
662 void GuiView::smallSizedIcons()
664 setIconSize(QSize(d.smallIconSize, d.smallIconSize));
668 void GuiView::normalSizedIcons()
670 setIconSize(QSize(d.normalIconSize, d.normalIconSize));
674 void GuiView::bigSizedIcons()
676 setIconSize(QSize(d.bigIconSize, d.bigIconSize));
680 void GuiView::clearMessage()
685 d.statusbar_timer_.stop();
689 void GuiView::updateWindowTitle(GuiWorkArea * wa)
691 if (wa != d.current_work_area_)
693 setWindowTitle(qt_("LyX: ") + wa->windowTitle());
694 setWindowIconText(wa->windowIconText());
698 void GuiView::on_currentWorkAreaChanged(GuiWorkArea * wa)
701 disconnectBufferView();
702 connectBufferView(wa->bufferView());
703 connectBuffer(wa->bufferView().buffer());
704 d.current_work_area_ = wa;
705 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
706 this, SLOT(updateWindowTitle(GuiWorkArea *)));
707 updateWindowTitle(wa);
711 // The document settings needs to be reinitialised.
712 updateDialog("document", "");
714 // Buffer-dependent dialogs must be updated. This is done here because
715 // some dialogs require buffer()->text.
720 void GuiView::on_lastWorkAreaRemoved()
723 // We already are in a close event. Nothing more to do.
726 if (d.splitter_->count() > 1)
727 // We have a splitter so don't close anything.
730 // Reset and updates the dialogs.
731 d.toc_models_.reset(0);
732 updateDialog("document", "");
735 resetWindowTitleAndIconText();
737 if (lyxrc.open_buffers_in_tabs)
738 // Nothing more to do, the window should stay open.
741 if (guiApp->viewIds().size() > 1) {
747 // On Mac we also close the last window because the application stay
748 // resident in memory. On other platforms we don't close the last
749 // window because this would quit the application.
755 void GuiView::updateStatusBar()
757 // let the user see the explicit message
758 if (d.statusbar_timer_.isActive())
765 void GuiView::showMessage()
767 QString msg = toqstr(theGuiApp()->viewStatusMessage());
769 BufferView const * bv = currentBufferView();
771 msg = toqstr(bv->cursor().currentState());
773 msg = qt_("Welcome to LyX!");
775 statusBar()->showMessage(msg);
779 bool GuiView::event(QEvent * e)
783 // Useful debug code:
784 //case QEvent::ActivationChange:
785 //case QEvent::WindowDeactivate:
786 //case QEvent::Paint:
787 //case QEvent::Enter:
788 //case QEvent::Leave:
789 //case QEvent::HoverEnter:
790 //case QEvent::HoverLeave:
791 //case QEvent::HoverMove:
792 //case QEvent::StatusTip:
793 //case QEvent::DragEnter:
794 //case QEvent::DragLeave:
798 case QEvent::WindowActivate: {
799 GuiView * old_view = guiApp->currentView();
800 if (this == old_view) {
802 return QMainWindow::event(e);
804 if (old_view && old_view->currentBufferView()) {
805 // save current selection to the selection buffer to allow
806 // middle-button paste in this window.
807 cap::saveSelection(old_view->currentBufferView()->cursor());
809 guiApp->setCurrentView(this);
810 if (d.current_work_area_) {
811 BufferView & bv = d.current_work_area_->bufferView();
812 connectBufferView(bv);
813 connectBuffer(bv.buffer());
814 // The document structure, name and dialogs might have
815 // changed in another view.
817 // The document settings needs to be reinitialised.
818 updateDialog("document", "");
821 resetWindowTitleAndIconText();
824 return QMainWindow::event(e);
827 case QEvent::ShortcutOverride: {
830 #if (!defined Q_WS_X11) || (QT_VERSION >= 0x040500)
831 if (isFullScreen() && menuBar()->isHidden()) {
832 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
833 // FIXME: we should also try to detect special LyX shortcut such as
834 // Alt-P and Alt-M. Right now there is a hack in
835 // GuiWorkArea::processKeySym() that hides again the menubar for
837 if (ke->modifiers() & Qt::AltModifier && ke->key() != Qt::Key_Alt) {
839 return QMainWindow::event(e);
844 if (d.current_work_area_)
845 // Nothing special to do.
846 return QMainWindow::event(e);
848 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
849 // Let Qt handle menu access and the Tab keys to navigate keys to navigate
851 if (ke->modifiers() & Qt::AltModifier || ke->key() == Qt::Key_Tab
852 || ke->key() == Qt::Key_Backtab)
853 return QMainWindow::event(e);
855 // Allow processing of shortcuts that are allowed even when no Buffer
858 setKeySymbol(&sym, ke);
859 guiApp->processKeySym(sym, q_key_state(ke->modifiers()));
865 return QMainWindow::event(e);
869 void GuiView::resetWindowTitleAndIconText()
871 setWindowTitle(qt_("LyX"));
872 setWindowIconText(qt_("LyX"));
875 bool GuiView::focusNextPrevChild(bool /*next*/)
882 void GuiView::setBusy(bool busy)
884 if (d.current_work_area_) {
885 d.current_work_area_->setUpdatesEnabled(!busy);
887 d.current_work_area_->stopBlinkingCursor();
889 d.current_work_area_->startBlinkingCursor();
893 QApplication::setOverrideCursor(Qt::WaitCursor);
895 QApplication::restoreOverrideCursor();
899 GuiWorkArea * GuiView::workArea(Buffer & buffer)
901 if (currentWorkArea()
902 && ¤tWorkArea()->bufferView().buffer() == &buffer)
903 return (GuiWorkArea *) currentWorkArea();
904 if (TabWorkArea * twa = d.currentTabWorkArea())
905 return twa->workArea(buffer);
910 GuiWorkArea * GuiView::addWorkArea(Buffer & buffer)
912 // Automatically create a TabWorkArea if there are none yet.
913 TabWorkArea * tab_widget = d.splitter_->count()
914 ? d.currentTabWorkArea() : addTabWorkArea();
915 return tab_widget->addWorkArea(buffer, *this);
919 TabWorkArea * GuiView::addTabWorkArea()
921 TabWorkArea * twa = new TabWorkArea;
922 QObject::connect(twa, SIGNAL(currentWorkAreaChanged(GuiWorkArea *)),
923 this, SLOT(on_currentWorkAreaChanged(GuiWorkArea *)));
924 QObject::connect(twa, SIGNAL(lastWorkAreaRemoved()),
925 this, SLOT(on_lastWorkAreaRemoved()));
927 d.splitter_->addWidget(twa);
928 d.stack_widget_->setCurrentWidget(d.splitter_);
933 GuiWorkArea const * GuiView::currentWorkArea() const
935 return d.current_work_area_;
939 GuiWorkArea * GuiView::currentWorkArea()
941 return d.current_work_area_;
945 GuiWorkArea const * GuiView::currentMainWorkArea() const
947 if (d.currentTabWorkArea() == NULL)
949 return d.currentTabWorkArea()->currentWorkArea();
953 GuiWorkArea * GuiView::currentMainWorkArea()
955 if (d.currentTabWorkArea() == NULL)
957 return d.currentTabWorkArea()->currentWorkArea();
961 void GuiView::setCurrentWorkArea(GuiWorkArea * wa)
963 LYXERR(Debug::DEBUG, "Setting current wa: " << wa << endl);
965 d.current_work_area_ = NULL;
969 GuiWorkArea * old_gwa = theGuiApp()->currentView()->currentWorkArea();
973 if (currentBufferView())
974 cap::saveSelection(currentBufferView()->cursor());
976 theGuiApp()->setCurrentView(this);
977 d.current_work_area_ = wa;
978 for (int i = 0; i != d.splitter_->count(); ++i) {
979 if (d.tabWorkArea(i)->setCurrentWorkArea(wa)) {
980 //if (d.current_main_work_area_)
981 // d.current_main_work_area_->setFrameStyle(QFrame::NoFrame);
982 d.current_main_work_area_ = wa;
983 //d.current_main_work_area_->setFrameStyle(QFrame::Box | QFrame::Plain);
984 //d.current_main_work_area_->setLineWidth(2);
985 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() << ", Current main wa: " << currentMainWorkArea());
989 LYXERR(Debug::DEBUG, "This is not a tabbed wa");
990 on_currentWorkAreaChanged(wa);
991 BufferView & bv = wa->bufferView();
992 bv.cursor().fixIfBroken();
994 wa->setUpdatesEnabled(true);
995 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() << ", Current main wa: " << currentMainWorkArea());
999 void GuiView::removeWorkArea(GuiWorkArea * wa)
1001 LASSERT(wa, return);
1002 if (wa == d.current_work_area_) {
1004 disconnectBufferView();
1005 d.current_work_area_ = 0;
1006 d.current_main_work_area_ = 0;
1009 bool found_twa = false;
1010 for (int i = 0; i != d.splitter_->count(); ++i) {
1011 TabWorkArea * twa = d.tabWorkArea(i);
1012 if (twa->removeWorkArea(wa)) {
1013 // Found in this tab group, and deleted the GuiWorkArea.
1015 if (twa->count() != 0) {
1016 if (d.current_work_area_ == 0)
1017 // This means that we are closing the current GuiWorkArea, so
1018 // switch to the next GuiWorkArea in the found TabWorkArea.
1019 setCurrentWorkArea(twa->currentWorkArea());
1021 // No more WorkAreas in this tab group, so delete it.
1028 // It is not a tabbed work area (i.e., the search work area), so it
1029 // should be deleted by other means.
1030 LASSERT(found_twa, /* */);
1032 if (d.current_work_area_ == 0) {
1033 if (d.splitter_->count() != 0) {
1034 TabWorkArea * twa = d.currentTabWorkArea();
1035 setCurrentWorkArea(twa->currentWorkArea());
1037 // No more work areas, switch to the background widget.
1038 setCurrentWorkArea(0);
1044 LayoutBox * GuiView::getLayoutDialog() const
1050 void GuiView::updateLayoutList()
1053 d.layout_->updateContents(false);
1057 void GuiView::updateToolbars()
1059 ToolbarMap::iterator end = d.toolbars_.end();
1060 if (d.current_work_area_) {
1062 d.current_work_area_->bufferView().cursor().inMathed();
1064 lyx::getStatus(FuncRequest(LFUN_LAYOUT_TABULAR)).enabled();
1066 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).enabled() &&
1067 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).onoff(true);
1068 bool const mathmacrotemplate =
1069 lyx::getStatus(FuncRequest(LFUN_IN_MATHMACROTEMPLATE)).enabled();
1071 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1072 it->second->update(math, table, review, mathmacrotemplate);
1074 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1075 it->second->update(false, false, false, false);
1079 void GuiView::setBuffer(Buffer * newBuffer)
1081 LYXERR(Debug::DEBUG, "Setting buffer: " << newBuffer << std::endl);
1082 LASSERT(newBuffer, return);
1085 GuiWorkArea * wa = workArea(*newBuffer);
1087 newBuffer->masterBuffer()->updateLabels();
1088 wa = addWorkArea(*newBuffer);
1090 //Disconnect the old buffer...there's no new one.
1093 connectBuffer(*newBuffer);
1094 connectBufferView(wa->bufferView());
1095 setCurrentWorkArea(wa);
1101 void GuiView::connectBuffer(Buffer & buf)
1103 buf.setGuiDelegate(this);
1107 void GuiView::disconnectBuffer()
1109 if (d.current_work_area_)
1110 d.current_work_area_->bufferView().buffer().setGuiDelegate(0);
1114 void GuiView::connectBufferView(BufferView & bv)
1116 bv.setGuiDelegate(this);
1120 void GuiView::disconnectBufferView()
1122 if (d.current_work_area_)
1123 d.current_work_area_->bufferView().setGuiDelegate(0);
1127 void GuiView::errors(string const & error_type, bool from_master)
1129 ErrorList & el = from_master ?
1130 documentBufferView()->buffer().masterBuffer()->errorList(error_type)
1131 : documentBufferView()->buffer().errorList(error_type);
1132 string data = error_type;
1134 data = "from_master|" + error_type;
1136 showDialog("errorlist", data);
1140 void GuiView::updateTocItem(std::string const & type, DocIterator const & dit)
1142 d.toc_models_.updateItem(toqstr(type), dit);
1146 void GuiView::structureChanged()
1148 d.toc_models_.reset(documentBufferView());
1149 // Navigator needs more than a simple update in this case. It needs to be
1151 updateDialog("toc", "");
1155 void GuiView::updateDialog(string const & name, string const & data)
1157 if (!isDialogVisible(name))
1160 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
1161 if (it == d.dialogs_.end())
1164 Dialog * const dialog = it->second.get();
1165 if (dialog->isVisibleView())
1166 dialog->initialiseParams(data);
1170 BufferView * GuiView::documentBufferView()
1172 return currentMainWorkArea()
1173 ? ¤tMainWorkArea()->bufferView()
1178 BufferView const * GuiView::documentBufferView() const
1180 return currentMainWorkArea()
1181 ? ¤tMainWorkArea()->bufferView()
1186 BufferView * GuiView::currentBufferView()
1188 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1192 BufferView const * GuiView::currentBufferView() const
1194 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1198 void GuiView::autoSave()
1200 LYXERR(Debug::INFO, "Running autoSave()");
1202 if (documentBufferView())
1203 documentBufferView()->buffer().autoSave();
1207 void GuiView::resetAutosaveTimers()
1210 d.autosave_timeout_.restart();
1214 bool GuiView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1217 Buffer * buf = currentBufferView()
1218 ? ¤tBufferView()->buffer() : 0;
1219 Buffer * doc_buffer = documentBufferView()
1220 ? &(documentBufferView()->buffer()) : 0;
1222 // Check whether we need a buffer
1223 if (!lyxaction.funcHasFlag(cmd.action, LyXAction::NoBuffer) && !buf) {
1224 // no, exit directly
1225 flag.message(from_utf8(N_("Command not allowed with"
1226 "out any document open")));
1227 flag.setEnabled(false);
1231 if (cmd.origin == FuncRequest::TOC) {
1232 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
1234 if (toc->getStatus(documentBufferView()->cursor(), cmd, fs))
1237 flag.setEnabled(false);
1241 switch(cmd.action) {
1242 case LFUN_BUFFER_IMPORT:
1245 case LFUN_BUFFER_RELOAD:
1246 enable = doc_buffer && !doc_buffer->isUnnamed()
1247 && doc_buffer->fileName().exists()
1248 && (!doc_buffer->isClean()
1249 || doc_buffer->isExternallyModified(Buffer::timestamp_method));
1252 case LFUN_BUFFER_CHILD_OPEN:
1253 enable = doc_buffer;
1256 case LFUN_BUFFER_WRITE:
1257 enable = doc_buffer && (doc_buffer->isUnnamed() || !doc_buffer->isClean());
1260 //FIXME: This LFUN should be moved to GuiApplication.
1261 case LFUN_BUFFER_WRITE_ALL: {
1262 // We enable the command only if there are some modified buffers
1263 Buffer * first = theBufferList().first();
1268 // We cannot use a for loop as the buffer list is a cycle.
1270 if (!b->isClean()) {
1274 b = theBufferList().next(b);
1275 } while (b != first);
1279 case LFUN_BUFFER_WRITE_AS:
1280 enable = doc_buffer;
1283 case LFUN_BUFFER_CLOSE:
1284 enable = doc_buffer;
1287 case LFUN_BUFFER_CLOSE_ALL:
1288 enable = theBufferList().last() != theBufferList().first();
1291 case LFUN_SPLIT_VIEW:
1292 if (cmd.getArg(0) == "vertical")
1293 enable = doc_buffer && (d.splitter_->count() == 1 ||
1294 d.splitter_->orientation() == Qt::Vertical);
1296 enable = doc_buffer && (d.splitter_->count() == 1 ||
1297 d.splitter_->orientation() == Qt::Horizontal);
1300 case LFUN_CLOSE_TAB_GROUP:
1301 enable = d.currentTabWorkArea();
1304 case LFUN_TOOLBAR_TOGGLE:
1305 if (GuiToolbar * t = toolbar(cmd.getArg(0)))
1306 flag.setOnOff(t->isVisible());
1309 case LFUN_DROP_LAYOUTS_CHOICE:
1313 case LFUN_UI_TOGGLE:
1314 flag.setOnOff(isFullScreen());
1317 case LFUN_DIALOG_DISCONNECT_INSET:
1320 case LFUN_DIALOG_HIDE:
1321 // FIXME: should we check if the dialog is shown?
1324 case LFUN_DIALOG_TOGGLE:
1325 flag.setOnOff(isDialogVisible(cmd.getArg(0)));
1326 // fall through to set "enable"
1327 case LFUN_DIALOG_SHOW: {
1328 string const name = cmd.getArg(0);
1330 enable = name == "aboutlyx"
1331 || name == "file" //FIXME: should be removed.
1333 || name == "texinfo"
1334 || name == "compare";
1335 else if (name == "print")
1336 enable = doc_buffer->isExportable("dvi")
1337 && lyxrc.print_command != "none";
1338 else if (name == "character" || name == "symbols") {
1339 if (!buf || buf->isReadonly()
1340 || !currentBufferView()->cursor().inTexted())
1343 // FIXME we should consider passthru
1345 Inset const & in = currentBufferView()->cursor().inset();
1346 enable = !in.getLayout().isPassThru();
1349 else if (name == "latexlog")
1350 enable = FileName(doc_buffer->logName()).isReadableFile();
1351 else if (name == "spellchecker")
1352 enable = theSpellChecker() && !doc_buffer->isReadonly();
1353 else if (name == "vclog")
1354 enable = doc_buffer->lyxvc().inUse();
1358 case LFUN_DIALOG_UPDATE: {
1359 string const name = cmd.getArg(0);
1361 enable = name == "prefs";
1365 case LFUN_COMMAND_EXECUTE:
1367 case LFUN_MENU_OPEN:
1368 // Nothing to check.
1371 case LFUN_COMPLETION_INLINE:
1372 if (!d.current_work_area_
1373 || !d.current_work_area_->completer().inlinePossible(
1374 currentBufferView()->cursor()))
1378 case LFUN_COMPLETION_POPUP:
1379 if (!d.current_work_area_
1380 || !d.current_work_area_->completer().popupPossible(
1381 currentBufferView()->cursor()))
1385 case LFUN_COMPLETION_COMPLETE:
1386 if (!d.current_work_area_
1387 || !d.current_work_area_->completer().inlinePossible(
1388 currentBufferView()->cursor()))
1392 case LFUN_COMPLETION_ACCEPT:
1393 if (!d.current_work_area_
1394 || (!d.current_work_area_->completer().popupVisible()
1395 && !d.current_work_area_->completer().inlineVisible()
1396 && !d.current_work_area_->completer().completionAvailable()))
1400 case LFUN_COMPLETION_CANCEL:
1401 if (!d.current_work_area_
1402 || (!d.current_work_area_->completer().popupVisible()
1403 && !d.current_work_area_->completer().inlineVisible()))
1407 case LFUN_BUFFER_ZOOM_OUT:
1408 enable = doc_buffer && lyxrc.zoom > 10;
1411 case LFUN_BUFFER_ZOOM_IN:
1412 enable = doc_buffer;
1415 case LFUN_BUFFER_NEXT:
1416 case LFUN_BUFFER_PREVIOUS:
1417 // FIXME: should we check is there is an previous or next buffer?
1419 case LFUN_BUFFER_SWITCH:
1420 // toggle on the current buffer, but do not toggle off
1421 // the other ones (is that a good idea?)
1423 && to_utf8(cmd.argument()) == doc_buffer->absFileName())
1424 flag.setOnOff(true);
1427 case LFUN_VC_REGISTER:
1428 enable = doc_buffer && !doc_buffer->lyxvc().inUse();
1430 case LFUN_VC_CHECK_IN:
1431 enable = doc_buffer && doc_buffer->lyxvc().checkInEnabled();
1433 case LFUN_VC_CHECK_OUT:
1434 enable = doc_buffer && doc_buffer->lyxvc().checkOutEnabled();
1436 case LFUN_VC_LOCKING_TOGGLE:
1437 enable = doc_buffer && !doc_buffer->isReadonly()
1438 && doc_buffer->lyxvc().lockingToggleEnabled();
1439 flag.setOnOff(enable && !doc_buffer->lyxvc().locker().empty());
1441 case LFUN_VC_REVERT:
1442 enable = doc_buffer && doc_buffer->lyxvc().inUse();
1444 case LFUN_VC_UNDO_LAST:
1445 enable = doc_buffer && doc_buffer->lyxvc().undoLastEnabled();
1447 case LFUN_VC_REPO_UPDATE:
1448 enable = doc_buffer && doc_buffer->lyxvc().inUse();
1450 case LFUN_VC_COMMAND: {
1451 if (cmd.argument().empty())
1453 if (!doc_buffer && contains(cmd.getArg(0), 'D'))
1458 case LFUN_SERVER_GOTO_FILE_ROW:
1466 flag.setEnabled(false);
1472 static FileName selectTemplateFile()
1474 FileDialog dlg(qt_("Select template file"));
1475 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1476 dlg.setButton1(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
1478 FileDialog::Result result = dlg.open(toqstr(lyxrc.template_path),
1479 QStringList(qt_("LyX Documents (*.lyx)")));
1481 if (result.first == FileDialog::Later)
1483 if (result.second.isEmpty())
1485 return FileName(fromqstr(result.second));
1489 Buffer * GuiView::loadDocument(FileName const & filename, bool tolastfiles)
1493 Buffer * newBuffer = checkAndLoadLyXFile(filename);
1496 message(_("Document not loaded."));
1501 setBuffer(newBuffer);
1503 // scroll to the position when the file was last closed
1504 if (lyxrc.use_lastfilepos) {
1505 LastFilePosSection::FilePos filepos =
1506 theSession().lastFilePos().load(filename);
1507 documentBufferView()->moveToPosition(filepos.pit, filepos.pos, 0, 0);
1511 theSession().lastFiles().add(filename);
1518 void GuiView::openDocument(string const & fname)
1520 string initpath = lyxrc.document_path;
1522 if (documentBufferView()) {
1523 string const trypath = documentBufferView()->buffer().filePath();
1524 // If directory is writeable, use this as default.
1525 if (FileName(trypath).isDirWritable())
1531 if (fname.empty()) {
1532 FileDialog dlg(qt_("Select document to open"), LFUN_FILE_OPEN);
1533 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1534 dlg.setButton2(qt_("Examples|#E#e"),
1535 toqstr(addPath(package().system_support().absFilename(), "examples")));
1537 QStringList filter(qt_("LyX Documents (*.lyx)"));
1538 filter << qt_("LyX-1.3.x Documents (*.lyx13)")
1539 << qt_("LyX-1.4.x Documents (*.lyx14)")
1540 << qt_("LyX-1.5.x Documents (*.lyx15)")
1541 << qt_("LyX-1.6.x Documents (*.lyx16)");
1542 FileDialog::Result result =
1543 dlg.open(toqstr(initpath), filter);
1545 if (result.first == FileDialog::Later)
1548 filename = fromqstr(result.second);
1550 // check selected filename
1551 if (filename.empty()) {
1552 message(_("Canceled."));
1558 // get absolute path of file and add ".lyx" to the filename if
1560 FileName const fullname =
1561 fileSearch(string(), filename, "lyx", support::may_not_exist);
1562 if (!fullname.empty())
1563 filename = fullname.absFilename();
1565 if (!fullname.onlyPath().isDirectory()) {
1566 Alert::warning(_("Invalid filename"),
1567 bformat(_("The directory in the given path\n%1$s\ndoes not exist."),
1568 from_utf8(fullname.absFilename())));
1571 // if the file doesn't exist, let the user create one
1572 if (!fullname.exists()) {
1573 // the user specifically chose this name. Believe him.
1574 Buffer * const b = newFile(filename, string(), true);
1580 docstring const disp_fn = makeDisplayPath(filename);
1581 message(bformat(_("Opening document %1$s..."), disp_fn));
1584 Buffer * buf = loadDocument(fullname);
1586 buf->updateLabels();
1588 buf->errors("Parse");
1589 str2 = bformat(_("Document %1$s opened."), disp_fn);
1590 if (buf->lyxvc().inUse())
1591 str2 += " " + from_utf8(buf->lyxvc().versionString()) +
1592 " " + _("Version control detected.");
1594 str2 = bformat(_("Could not open document %1$s"), disp_fn);
1599 // FIXME: clean that
1600 static bool import(GuiView * lv, FileName const & filename,
1601 string const & format, ErrorList & errorList)
1603 FileName const lyxfile(support::changeExtension(filename.absFilename(), ".lyx"));
1605 string loader_format;
1606 vector<string> loaders = theConverters().loaders();
1607 if (find(loaders.begin(), loaders.end(), format) == loaders.end()) {
1608 for (vector<string>::const_iterator it = loaders.begin();
1609 it != loaders.end(); ++it) {
1610 if (!theConverters().isReachable(format, *it))
1613 string const tofile =
1614 support::changeExtension(filename.absFilename(),
1615 formats.extension(*it));
1616 if (!theConverters().convert(0, filename, FileName(tofile),
1617 filename, format, *it, errorList))
1619 loader_format = *it;
1622 if (loader_format.empty()) {
1623 frontend::Alert::error(_("Couldn't import file"),
1624 bformat(_("No information for importing the format %1$s."),
1625 formats.prettyName(format)));
1629 loader_format = format;
1631 if (loader_format == "lyx") {
1632 Buffer * buf = lv->loadDocument(lyxfile);
1635 buf->updateLabels();
1637 buf->errors("Parse");
1639 Buffer * const b = newFile(lyxfile.absFilename(), string(), true);
1643 bool as_paragraphs = loader_format == "textparagraph";
1644 string filename2 = (loader_format == format) ? filename.absFilename()
1645 : support::changeExtension(filename.absFilename(),
1646 formats.extension(loader_format));
1647 lv->currentBufferView()->insertPlaintextFile(FileName(filename2),
1649 guiApp->setCurrentView(lv);
1650 lyx::dispatch(FuncRequest(LFUN_MARK_OFF));
1657 void GuiView::importDocument(string const & argument)
1660 string filename = split(argument, format, ' ');
1662 LYXERR(Debug::INFO, format << " file: " << filename);
1664 // need user interaction
1665 if (filename.empty()) {
1666 string initpath = lyxrc.document_path;
1667 if (documentBufferView()) {
1668 string const trypath = documentBufferView()->buffer().filePath();
1669 // If directory is writeable, use this as default.
1670 if (FileName(trypath).isDirWritable())
1674 docstring const text = bformat(_("Select %1$s file to import"),
1675 formats.prettyName(format));
1677 FileDialog dlg(toqstr(text), LFUN_BUFFER_IMPORT);
1678 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1679 dlg.setButton2(qt_("Examples|#E#e"),
1680 toqstr(addPath(package().system_support().absFilename(), "examples")));
1682 docstring filter = formats.prettyName(format);
1685 filter += from_utf8(formats.extension(format));
1688 FileDialog::Result result =
1689 dlg.open(toqstr(initpath), fileFilters(toqstr(filter)));
1691 if (result.first == FileDialog::Later)
1694 filename = fromqstr(result.second);
1696 // check selected filename
1697 if (filename.empty())
1698 message(_("Canceled."));
1701 if (filename.empty())
1704 // get absolute path of file
1705 FileName const fullname(support::makeAbsPath(filename));
1707 FileName const lyxfile(support::changeExtension(fullname.absFilename(), ".lyx"));
1709 // Check if the document already is open
1710 Buffer * buf = theBufferList().getBuffer(lyxfile);
1713 if (!closeBuffer()) {
1714 message(_("Canceled."));
1719 docstring const displaypath = makeDisplayPath(lyxfile.absFilename(), 30);
1721 // if the file exists already, and we didn't do
1722 // -i lyx thefile.lyx, warn
1723 if (lyxfile.exists() && fullname != lyxfile) {
1725 docstring text = bformat(_("The document %1$s already exists.\n\n"
1726 "Do you want to overwrite that document?"), displaypath);
1727 int const ret = Alert::prompt(_("Overwrite document?"),
1728 text, 0, 1, _("&Overwrite"), _("&Cancel"));
1731 message(_("Canceled."));
1736 message(bformat(_("Importing %1$s..."), displaypath));
1737 ErrorList errorList;
1738 if (import(this, fullname, format, errorList))
1739 message(_("imported."));
1741 message(_("file not imported!"));
1743 // FIXME (Abdel 12/08/06): Is there a need to display the error list here?
1747 void GuiView::newDocument(string const & filename, bool from_template)
1749 FileName initpath(lyxrc.document_path);
1750 if (documentBufferView()) {
1751 FileName const trypath(documentBufferView()->buffer().filePath());
1752 // If directory is writeable, use this as default.
1753 if (trypath.isDirWritable())
1757 string templatefile;
1758 if (from_template) {
1759 templatefile = selectTemplateFile().absFilename();
1760 if (templatefile.empty())
1765 if (filename.empty())
1766 b = newUnnamedFile(initpath, to_utf8(_("newfile")), templatefile);
1768 b = newFile(filename, templatefile, true);
1773 // If no new document could be created, it is unsure
1774 // whether there is a valid BufferView.
1775 if (currentBufferView())
1776 // Ensure the cursor is correctly positioned on screen.
1777 currentBufferView()->showCursor();
1781 void GuiView::insertLyXFile(docstring const & fname)
1783 BufferView * bv = documentBufferView();
1788 FileName filename(to_utf8(fname));
1790 if (!filename.empty()) {
1791 bv->insertLyXFile(filename);
1795 // Launch a file browser
1797 string initpath = lyxrc.document_path;
1798 string const trypath = bv->buffer().filePath();
1799 // If directory is writeable, use this as default.
1800 if (FileName(trypath).isDirWritable())
1804 FileDialog dlg(qt_("Select LyX document to insert"), LFUN_FILE_INSERT);
1805 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1806 dlg.setButton2(qt_("Examples|#E#e"),
1807 toqstr(addPath(package().system_support().absFilename(),
1810 FileDialog::Result result = dlg.open(toqstr(initpath),
1811 QStringList(qt_("LyX Documents (*.lyx)")));
1813 if (result.first == FileDialog::Later)
1817 filename.set(fromqstr(result.second));
1819 // check selected filename
1820 if (filename.empty()) {
1821 // emit message signal.
1822 message(_("Canceled."));
1826 bv->insertLyXFile(filename);
1830 void GuiView::insertPlaintextFile(docstring const & fname,
1833 BufferView * bv = documentBufferView();
1837 if (!fname.empty() && !FileName::isAbsolute(to_utf8(fname))) {
1838 message(_("Absolute filename expected."));
1843 FileName filename(to_utf8(fname));
1845 if (!filename.empty()) {
1846 bv->insertPlaintextFile(filename, asParagraph);
1850 FileDialog dlg(qt_("Select file to insert"), (asParagraph ?
1851 LFUN_FILE_INSERT_PLAINTEXT_PARA : LFUN_FILE_INSERT_PLAINTEXT));
1853 FileDialog::Result result = dlg.open(toqstr(bv->buffer().filePath()),
1854 QStringList(qt_("All Files (*)")));
1856 if (result.first == FileDialog::Later)
1860 filename.set(fromqstr(result.second));
1862 // check selected filename
1863 if (filename.empty()) {
1864 // emit message signal.
1865 message(_("Canceled."));
1869 bv->insertPlaintextFile(filename, asParagraph);
1873 bool GuiView::renameBuffer(Buffer & b, docstring const & newname)
1875 FileName fname = b.fileName();
1876 FileName const oldname = fname;
1878 if (!newname.empty()) {
1880 fname = support::makeAbsPath(to_utf8(newname), oldname.onlyPath().absFilename());
1882 // Switch to this Buffer.
1885 // No argument? Ask user through dialog.
1887 FileDialog dlg(qt_("Choose a filename to save document as"),
1888 LFUN_BUFFER_WRITE_AS);
1889 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1890 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
1892 if (!isLyXFilename(fname.absFilename()))
1893 fname.changeExtension(".lyx");
1895 FileDialog::Result result =
1896 dlg.save(toqstr(fname.onlyPath().absFilename()),
1897 QStringList(qt_("LyX Documents (*.lyx)")),
1898 toqstr(fname.onlyFileName()));
1900 if (result.first == FileDialog::Later)
1903 fname.set(fromqstr(result.second));
1908 if (!isLyXFilename(fname.absFilename()))
1909 fname.changeExtension(".lyx");
1912 if (FileName(fname).exists()) {
1913 docstring const file = makeDisplayPath(fname.absFilename(), 30);
1914 docstring text = bformat(_("The document %1$s already "
1915 "exists.\n\nDo you want to "
1916 "overwrite that document?"),
1918 int const ret = Alert::prompt(_("Overwrite document?"),
1919 text, 0, 2, _("&Overwrite"), _("&Rename"), _("&Cancel"));
1922 case 1: return renameBuffer(b, docstring());
1923 case 2: return false;
1927 FileName oldauto = b.getAutosaveFilename();
1929 // Ok, change the name of the buffer
1930 b.setFileName(fname.absFilename());
1932 bool unnamed = b.isUnnamed();
1933 b.setUnnamed(false);
1934 b.saveCheckSum(fname);
1936 // bring the autosave file with us, just in case.
1937 b.moveAutosaveFile(oldauto);
1939 if (!saveBuffer(b)) {
1940 oldauto = b.getAutosaveFilename();
1941 b.setFileName(oldname.absFilename());
1942 b.setUnnamed(unnamed);
1943 b.saveCheckSum(oldname);
1944 b.moveAutosaveFile(oldauto);
1952 bool GuiView::saveBuffer(Buffer & b)
1954 if (workArea(b) && workArea(b)->inDialogMode())
1958 return renameBuffer(b, docstring());
1961 theSession().lastFiles().add(b.fileName());
1965 // Switch to this Buffer.
1968 // FIXME: we don't tell the user *WHY* the save failed !!
1969 docstring const file = makeDisplayPath(b.absFileName(), 30);
1970 docstring text = bformat(_("The document %1$s could not be saved.\n\n"
1971 "Do you want to rename the document and "
1972 "try again?"), file);
1973 int const ret = Alert::prompt(_("Rename and save?"),
1974 text, 0, 2, _("&Rename"), _("&Retry"), _("&Cancel"));
1977 if (!renameBuffer(b, docstring()))
1986 return saveBuffer(b);
1990 bool GuiView::hideWorkArea(GuiWorkArea * wa)
1992 return closeWorkArea(wa, false);
1996 bool GuiView::closeWorkArea(GuiWorkArea * wa)
1998 Buffer & buf = wa->bufferView().buffer();
1999 return closeWorkArea(wa, !buf.parent());
2003 bool GuiView::closeBuffer()
2005 GuiWorkArea * wa = currentMainWorkArea();
2006 Buffer & buf = wa->bufferView().buffer();
2007 return wa && closeWorkArea(wa, !buf.parent());
2011 void GuiView::writeSession() const {
2012 GuiWorkArea const * active_wa = currentMainWorkArea();
2013 for (int i = 0; i < d.splitter_->count(); ++i) {
2014 TabWorkArea * twa = d.tabWorkArea(i);
2015 for (int j = 0; j < twa->count(); ++j) {
2016 GuiWorkArea * wa = static_cast<GuiWorkArea *>(twa->widget(j));
2017 Buffer & buf = wa->bufferView().buffer();
2018 theSession().lastOpened().add(buf.fileName(), wa == active_wa);
2024 bool GuiView::closeBufferAll()
2026 // Close the workareas in all other views
2027 QList<int> const ids = guiApp->viewIds();
2028 for (int i = 0; i != ids.size(); ++i) {
2029 if (id_ != ids[i] && !guiApp->view(ids[i]).closeWorkAreaAll())
2033 // Close our own workareas
2034 if (!closeWorkAreaAll())
2037 // Now close the hidden buffers. We prevent hidden buffers from being
2038 // dirty, so we can just close them.
2039 theBufferList().closeAll();
2044 bool GuiView::closeWorkAreaAll()
2046 setCurrentWorkArea(currentMainWorkArea());
2048 // We might be in a situation that there is still a tabWorkArea, but
2049 // there are no tabs anymore. This can happen when we get here after a
2050 // TabWorkArea::lastWorkAreaRemoved() signal. Therefore we count how
2051 // many TabWorkArea's have no documents anymore.
2054 // We have to call count() each time, because it can happen that
2055 // more than one splitter will disappear in one iteration (bug 5998).
2056 for (; d.splitter_->count() > empty_twa; ) {
2057 TabWorkArea * twa = d.tabWorkArea(empty_twa);
2059 if (twa->count() == 0)
2062 setCurrentWorkArea(twa->currentWorkArea());
2063 if (!closeTabWorkArea(twa))
2071 bool GuiView::closeWorkArea(GuiWorkArea * wa, bool close_buffer)
2076 Buffer & buf = wa->bufferView().buffer();
2079 return closeBuffer(buf);
2081 if (!inMultiTabs(wa))
2082 if (!saveBufferIfNeeded(buf, true))
2090 bool GuiView::closeBuffer(Buffer & buf)
2092 // If we are in a close_event all children will be closed in some time,
2093 // so no need to do it here. This will ensure that the children end up
2094 // in the session file in the correct order. If we close the master
2095 // buffer, we can close or release the child buffers here too.
2097 vector<Buffer *> clist = buf.getChildren(false);
2098 for (vector<Buffer *>::const_iterator it = clist.begin();
2099 it != clist.end(); ++it) {
2100 // If a child is dirty, do not close
2101 // without user intervention
2102 //FIXME: should we look in other tabworkareas?
2103 Buffer * child_buf = *it;
2104 GuiWorkArea * child_wa = workArea(*child_buf);
2106 if (!closeWorkArea(child_wa, true))
2109 theBufferList().releaseChild(&buf, child_buf);
2112 // goto bookmark to update bookmark pit.
2113 //FIXME: we should update only the bookmarks related to this buffer!
2114 LYXERR(Debug::DEBUG, "GuiView::closeBuffer()");
2115 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
2116 theLyXFunc().gotoBookmark(i+1, false, false);
2118 if (saveBufferIfNeeded(buf, false)) {
2119 theBufferList().release(&buf);
2126 bool GuiView::closeTabWorkArea(TabWorkArea * twa)
2128 while (twa == d.currentTabWorkArea()) {
2129 twa->setCurrentIndex(twa->count()-1);
2131 GuiWorkArea * wa = twa->currentWorkArea();
2132 Buffer & b = wa->bufferView().buffer();
2134 // We only want to close the buffer if the same buffer is not visible
2135 // in another view, and if this is not a child and if we are closing
2136 // a view (not a tabgroup).
2137 bool const close_buffer =
2138 !inMultiViews(wa) && !b.parent() && closing_;
2140 if (!closeWorkArea(wa, close_buffer))
2147 bool GuiView::saveBufferIfNeeded(Buffer & buf, bool hiding)
2149 if (buf.isClean() || buf.paragraphs().empty())
2152 // Switch to this Buffer.
2157 if (buf.isUnnamed())
2158 file = from_utf8(buf.fileName().onlyFileName());
2160 file = buf.fileName().displayName(30);
2162 // Bring this window to top before asking questions.
2167 if (hiding && buf.isUnnamed()) {
2168 docstring const text = bformat(_("The document %1$s has not been "
2169 "saved yet.\n\nDo you want to save "
2170 "the document?"), file);
2171 ret = Alert::prompt(_("Save new document?"),
2172 text, 0, 1, _("&Save"), _("&Cancel"));
2176 docstring const text = bformat(_("The document %1$s has unsaved changes."
2177 "\n\nDo you want to save the document or discard the changes?"), file);
2178 ret = Alert::prompt(_("Save changed document?"),
2179 text, 0, 2, _("&Save"), _("&Discard"), _("&Cancel"));
2184 if (!saveBuffer(buf))
2188 // if we crash after this we could
2189 // have no autosave file but I guess
2190 // this is really improbable (Jug)
2191 buf.removeAutosaveFile();
2193 // revert all changes
2194 buf.loadLyXFile(buf.fileName());
2204 bool GuiView::inMultiTabs(GuiWorkArea * wa)
2206 Buffer & buf = wa->bufferView().buffer();
2208 for (int i = 0; i != d.splitter_->count(); ++i) {
2209 GuiWorkArea * wa_ = d.tabWorkArea(i)->workArea(buf);
2210 if (wa_ && wa_ != wa)
2213 return inMultiViews(wa);
2217 bool GuiView::inMultiViews(GuiWorkArea * wa)
2219 QList<int> const ids = guiApp->viewIds();
2220 Buffer & buf = wa->bufferView().buffer();
2223 for (int i = 0; i != ids.size() && found_twa <= 1; ++i) {
2227 if (guiApp->view(ids[i]).workArea(buf))
2234 void GuiView::gotoNextOrPreviousBuffer(NextOrPrevious np)
2236 Buffer * const curbuf = documentBufferView()
2237 ? &documentBufferView()->buffer() : 0;
2238 Buffer * nextbuf = curbuf;
2240 if (np == NEXTBUFFER)
2241 nextbuf = theBufferList().next(nextbuf);
2243 nextbuf = theBufferList().previous(nextbuf);
2244 if (nextbuf == curbuf)
2250 if (workArea(*nextbuf))
2257 /// make sure the document is saved
2258 static bool ensureBufferClean(Buffer * buffer)
2260 LASSERT(buffer, return false);
2261 if (buffer->isClean() && !buffer->isUnnamed())
2264 docstring const file = buffer->fileName().displayName(30);
2267 if (!buffer->isUnnamed()) {
2268 text = bformat(_("The document %1$s has unsaved "
2269 "changes.\n\nDo you want to save "
2270 "the document?"), file);
2271 title = _("Save changed document?");
2274 text = bformat(_("The document %1$s has not been "
2275 "saved yet.\n\nDo you want to save "
2276 "the document?"), file);
2277 title = _("Save new document?");
2279 int const ret = Alert::prompt(title, text, 0, 1, _("&Save"), _("&Cancel"));
2282 dispatch(FuncRequest(LFUN_BUFFER_WRITE));
2284 return buffer->isClean() && !buffer->isUnnamed();
2288 void GuiView::reloadBuffer()
2290 Buffer * buf = &documentBufferView()->buffer();
2295 void GuiView::reloadBuffer(Buffer * buf)
2297 FileName filename = buf->fileName();
2298 Buffer const * master = buf->masterBuffer();
2299 bool const is_child = master != buf;
2300 // The user has already confirmed that the changes, if any, should
2301 // be discarded. So we just release the Buffer and don't call closeBuffer();
2302 theBufferList().release(buf);
2303 buf = loadDocument(filename);
2304 docstring const disp_fn = makeDisplayPath(filename.absFilename());
2307 // re-allocate master if necessary
2308 if (is_child && theBufferList().isLoaded(master)
2309 && buf->masterBuffer() != master)
2310 buf->setParent(master);
2311 buf->updateLabels();
2313 buf->errors("Parse");
2314 str = bformat(_("Document %1$s reloaded."), disp_fn);
2316 str = bformat(_("Could not reload document %1$s"), disp_fn);
2322 void GuiView::checkExternallyModifiedBuffers()
2324 BufferList::iterator bit = theBufferList().begin();
2325 BufferList::iterator const bend = theBufferList().end();
2326 for (; bit != bend; ++bit) {
2327 if ((*bit)->isExternallyModified(Buffer::checksum_method)) {
2328 docstring text = bformat(_("Document \n%1$s\n has been externally modified."
2329 " Reload now? Any local changes will be lost."),
2330 from_utf8((*bit)->absFileName()));
2331 int const ret = Alert::prompt(_("Reload externally changed document?"),
2332 text, 0, 1, _("&Reload"), _("&Cancel"));
2340 void GuiView::dispatchVC(FuncRequest const & cmd)
2342 Buffer * buffer = documentBufferView()
2343 ? &(documentBufferView()->buffer()) : 0;
2345 switch (cmd.action) {
2346 case LFUN_VC_REGISTER:
2347 if (!buffer || !ensureBufferClean(buffer))
2349 if (!buffer->lyxvc().inUse()) {
2350 if (buffer->lyxvc().registrer())
2355 case LFUN_VC_CHECK_IN:
2356 if (!buffer || !ensureBufferClean(buffer))
2358 if (buffer->lyxvc().inUse() && !buffer->isReadonly()) {
2359 message(from_utf8(buffer->lyxvc().checkIn()));
2364 case LFUN_VC_CHECK_OUT:
2365 if (!buffer || !ensureBufferClean(buffer))
2367 if (buffer->lyxvc().inUse()) {
2368 message(from_utf8(buffer->lyxvc().checkOut()));
2373 case LFUN_VC_LOCKING_TOGGLE:
2374 LASSERT(buffer, return);
2375 if (!ensureBufferClean(buffer) || buffer->isReadonly())
2377 if (buffer->lyxvc().inUse()) {
2378 string res = buffer->lyxvc().lockingToggle();
2380 frontend::Alert::error(_("Revision control error."),
2381 _("Error when setting the locking property."));
2383 message(from_utf8(res));
2389 case LFUN_VC_REVERT:
2390 LASSERT(buffer, return);
2391 buffer->lyxvc().revert();
2395 case LFUN_VC_UNDO_LAST:
2396 LASSERT(buffer, return);
2397 buffer->lyxvc().undoLast();
2401 case LFUN_VC_REPO_UPDATE:
2402 LASSERT(buffer, return);
2403 if (ensureBufferClean(buffer)) {
2404 string res = buffer->lyxvc().repoUpdate();
2405 message(from_utf8(res));
2406 checkExternallyModifiedBuffers();
2410 case LFUN_VC_COMMAND: {
2411 string flag = cmd.getArg(0);
2412 if (buffer && contains(flag, 'R') && !ensureBufferClean(buffer))
2415 if (contains(flag, 'M')) {
2416 if (!Alert::askForText(message, _("LyX VC: Log Message")))
2419 string path = cmd.getArg(1);
2420 if (contains(path, "$$p") && buffer)
2421 path = subst(path, "$$p", buffer->filePath());
2422 LYXERR(Debug::LYXVC, "Directory: " << path);
2424 if (!pp.isReadableDirectory()) {
2425 lyxerr << _("Directory is not accessible.") << endl;
2428 support::PathChanger p(pp);
2430 string command = cmd.getArg(2);
2431 if (command.empty())
2434 command = subst(command, "$$i", buffer->absFileName());
2435 command = subst(command, "$$p", buffer->filePath());
2437 command = subst(command, "$$m", to_utf8(message));
2438 LYXERR(Debug::LYXVC, "Command: " << command);
2440 one.startscript(Systemcall::Wait, command);
2444 if (contains(flag, 'I'))
2445 buffer->markDirty();
2446 if (contains(flag, 'R'))
2457 void GuiView::openChildDocument(string const & fname)
2459 LASSERT(documentBufferView(), return);
2460 Buffer & buffer = documentBufferView()->buffer();
2461 FileName const filename = support::makeAbsPath(fname, buffer.filePath());
2462 documentBufferView()->saveBookmark(false);
2464 bool parsed = false;
2465 if (theBufferList().exists(filename)) {
2466 child = theBufferList().getBuffer(filename);
2468 message(bformat(_("Opening child document %1$s..."),
2469 makeDisplayPath(filename.absFilename())));
2470 child = loadDocument(filename, false);
2476 // Set the parent name of the child document.
2477 // This makes insertion of citations and references in the child work,
2478 // when the target is in the parent or another child document.
2479 child->setParent(&buffer);
2480 child->masterBuffer()->updateLabels();
2483 child->errors("Parse");
2487 bool GuiView::goToFileRow(string const & argument)
2491 istringstream is(argument);
2492 is >> file_name >> row;
2493 file_name = os::internal_path(file_name);
2495 string const abstmp = package().temp_dir().absFilename();
2496 string const realtmp = package().temp_dir().realPath();
2497 // We have to use os::path_prefix_is() here, instead of
2498 // simply prefixIs(), because the file name comes from
2499 // an external application and may need case adjustment.
2500 if (os::path_prefix_is(file_name, abstmp, os::CASE_ADJUSTED)
2501 || os::path_prefix_is(file_name, realtmp, os::CASE_ADJUSTED)) {
2502 // Needed by inverse dvi search. If it is a file
2503 // in tmpdir, call the apropriated function.
2504 // If tmpdir is a symlink, we may have the real
2505 // path passed back, so we correct for that.
2506 if (!prefixIs(file_name, abstmp))
2507 file_name = subst(file_name, realtmp, abstmp);
2508 buf = theBufferList().getBufferFromTmp(file_name);
2510 // Must replace extension of the file to be .lyx
2511 // and get full path
2512 FileName const s = fileSearch(string(),
2513 support::changeExtension(file_name, ".lyx"), "lyx");
2514 // Either change buffer or load the file
2515 if (theBufferList().exists(s))
2516 buf = theBufferList().getBuffer(s);
2517 else if (s.exists()) {
2518 buf = loadDocument(s);
2519 buf->updateLabels();
2520 buf->errors("Parse");
2523 _("File does not exist: %1$s"),
2524 makeDisplayPath(file_name)));
2529 documentBufferView()->setCursorFromRow(row);
2534 bool GuiView::dispatch(FuncRequest const & cmd)
2536 BufferView * bv = currentBufferView();
2537 // By default we won't need any update.
2539 bv->cursor().updateFlags(Update::None);
2541 Buffer * doc_buffer = documentBufferView()
2542 ? &(documentBufferView()->buffer()) : 0;
2544 bool dispatched = true;
2546 if (cmd.origin == FuncRequest::TOC) {
2547 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
2548 toc->doDispatch(bv->cursor(), cmd);
2552 switch(cmd.action) {
2553 case LFUN_BUFFER_CHILD_OPEN:
2554 openChildDocument(to_utf8(cmd.argument()));
2557 case LFUN_BUFFER_IMPORT:
2558 importDocument(to_utf8(cmd.argument()));
2561 case LFUN_BUFFER_SWITCH:
2562 if (FileName::isAbsolute(to_utf8(cmd.argument()))) {
2564 theBufferList().getBuffer(FileName(to_utf8(cmd.argument())));
2568 message(_("Document not loaded"));
2572 case LFUN_BUFFER_NEXT:
2573 gotoNextOrPreviousBuffer(NEXTBUFFER);
2576 case LFUN_BUFFER_PREVIOUS:
2577 gotoNextOrPreviousBuffer(PREVBUFFER);
2580 case LFUN_COMMAND_EXECUTE: {
2581 bool const show_it = cmd.argument() != "off";
2582 // FIXME: this is a hack, "minibuffer" should not be
2584 if (GuiToolbar * t = toolbar("minibuffer")) {
2585 t->setVisible(show_it);
2586 if (show_it && t->commandBuffer())
2587 t->commandBuffer()->setFocus();
2591 case LFUN_DROP_LAYOUTS_CHOICE:
2592 d.layout_->showPopup();
2595 case LFUN_MENU_OPEN:
2596 if (QMenu * menu = guiApp->menus().menu(toqstr(cmd.argument()), *this))
2597 menu->exec(QCursor::pos());
2600 case LFUN_FILE_INSERT:
2601 insertLyXFile(cmd.argument());
2603 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
2604 insertPlaintextFile(cmd.argument(), true);
2607 case LFUN_FILE_INSERT_PLAINTEXT:
2608 insertPlaintextFile(cmd.argument(), false);
2611 case LFUN_BUFFER_RELOAD: {
2612 LASSERT(doc_buffer, break);
2613 docstring const file = makeDisplayPath(doc_buffer->absFileName(), 20);
2614 docstring text = bformat(_("Any changes will be lost. Are you sure "
2615 "you want to revert to the saved version of the document %1$s?"), file);
2616 int const ret = Alert::prompt(_("Revert to saved document?"),
2617 text, 1, 1, _("&Revert"), _("&Cancel"));
2620 doc_buffer->markClean();
2626 case LFUN_BUFFER_WRITE:
2627 LASSERT(doc_buffer, break);
2628 saveBuffer(*doc_buffer);
2631 case LFUN_BUFFER_WRITE_AS:
2632 LASSERT(doc_buffer, break);
2633 renameBuffer(*doc_buffer, cmd.argument());
2636 case LFUN_BUFFER_WRITE_ALL: {
2637 Buffer * first = theBufferList().first();
2640 message(_("Saving all documents..."));
2641 // We cannot use a for loop as the buffer list cycles.
2644 if (!b->isClean()) {
2646 LYXERR(Debug::ACTION, "Saved " << b->absFileName());
2648 b = theBufferList().next(b);
2649 } while (b != first);
2650 message(_("All documents saved."));
2654 case LFUN_BUFFER_CLOSE:
2658 case LFUN_BUFFER_CLOSE_ALL:
2662 case LFUN_TOOLBAR_TOGGLE: {
2663 string const name = cmd.getArg(0);
2664 if (GuiToolbar * t = toolbar(name))
2669 case LFUN_DIALOG_UPDATE: {
2670 string const name = to_utf8(cmd.argument());
2671 if (currentBufferView()) {
2672 Inset * inset = currentBufferView()->editedInset(name);
2673 // Can only update a dialog connected to an existing inset
2676 // FIXME: get rid of this indirection; GuiView ask the inset
2677 // if he is kind enough to update itself...
2678 FuncRequest fr(LFUN_INSET_DIALOG_UPDATE, cmd.argument());
2679 inset->dispatch(currentBufferView()->cursor(), fr);
2680 } else if (name == "paragraph") {
2681 lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
2682 } else if (name == "prefs" || name == "document") {
2683 updateDialog(name, string());
2688 case LFUN_DIALOG_TOGGLE: {
2689 if (isDialogVisible(cmd.getArg(0)))
2690 dispatch(FuncRequest(LFUN_DIALOG_HIDE, cmd.argument()));
2692 dispatch(FuncRequest(LFUN_DIALOG_SHOW, cmd.argument()));
2696 case LFUN_DIALOG_DISCONNECT_INSET:
2697 disconnectDialog(to_utf8(cmd.argument()));
2700 case LFUN_DIALOG_HIDE: {
2701 guiApp->hideDialogs(to_utf8(cmd.argument()), 0);
2705 case LFUN_DIALOG_SHOW: {
2706 string const name = cmd.getArg(0);
2707 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
2709 if (name == "character") {
2710 data = freefont2string();
2712 showDialog("character", data);
2713 } else if (name == "latexlog") {
2714 Buffer::LogType type;
2715 string const logfile = doc_buffer->logName(&type);
2717 case Buffer::latexlog:
2720 case Buffer::buildlog:
2724 data += Lexer::quoteString(logfile);
2725 showDialog("log", data);
2726 } else if (name == "vclog") {
2727 string const data = "vc " +
2728 Lexer::quoteString(doc_buffer->lyxvc().getLogFile());
2729 showDialog("log", data);
2730 } else if (name == "symbols") {
2731 data = bv->cursor().getEncoding()->name();
2733 showDialog("symbols", data);
2735 } else if (name == "prefs" && isFullScreen()) {
2736 FuncRequest fr(LFUN_INSET_INSERT, "fullscreen");
2738 showDialog("prefs", data);
2740 showDialog(name, data);
2745 message(cmd.argument());
2748 case LFUN_UI_TOGGLE:
2750 // Make sure the keyboard focus stays in the work area.
2754 case LFUN_SPLIT_VIEW: {
2755 LASSERT(doc_buffer, break);
2756 string const orientation = cmd.getArg(0);
2757 d.splitter_->setOrientation(orientation == "vertical"
2758 ? Qt::Vertical : Qt::Horizontal);
2759 TabWorkArea * twa = addTabWorkArea();
2760 GuiWorkArea * wa = twa->addWorkArea(*doc_buffer, *this);
2761 setCurrentWorkArea(wa);
2764 case LFUN_CLOSE_TAB_GROUP:
2765 if (TabWorkArea * twa = d.currentTabWorkArea()) {
2766 closeTabWorkArea(twa);
2767 d.current_work_area_ = 0;
2768 twa = d.currentTabWorkArea();
2769 // Switch to the next GuiWorkArea in the found TabWorkArea.
2771 // Make sure the work area is up to date.
2772 setCurrentWorkArea(twa->currentWorkArea());
2774 setCurrentWorkArea(0);
2779 case LFUN_COMPLETION_INLINE:
2780 if (d.current_work_area_)
2781 d.current_work_area_->completer().showInline();
2784 case LFUN_COMPLETION_POPUP:
2785 if (d.current_work_area_)
2786 d.current_work_area_->completer().showPopup();
2790 case LFUN_COMPLETION_COMPLETE:
2791 if (d.current_work_area_)
2792 d.current_work_area_->completer().tab();
2795 case LFUN_COMPLETION_CANCEL:
2796 if (d.current_work_area_) {
2797 if (d.current_work_area_->completer().popupVisible())
2798 d.current_work_area_->completer().hidePopup();
2800 d.current_work_area_->completer().hideInline();
2804 case LFUN_COMPLETION_ACCEPT:
2805 if (d.current_work_area_)
2806 d.current_work_area_->completer().activate();
2809 case LFUN_BUFFER_ZOOM_IN:
2810 case LFUN_BUFFER_ZOOM_OUT:
2811 if (cmd.argument().empty()) {
2812 if (cmd.action == LFUN_BUFFER_ZOOM_IN)
2817 lyxrc.zoom += convert<int>(cmd.argument());
2819 if (lyxrc.zoom < 10)
2822 // The global QPixmapCache is used in GuiPainter to cache text
2823 // painting so we must reset it.
2824 QPixmapCache::clear();
2825 guiApp->fontLoader().update();
2826 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
2829 case LFUN_VC_REGISTER:
2830 case LFUN_VC_CHECK_IN:
2831 case LFUN_VC_CHECK_OUT:
2832 case LFUN_VC_REPO_UPDATE:
2833 case LFUN_VC_LOCKING_TOGGLE:
2834 case LFUN_VC_REVERT:
2835 case LFUN_VC_UNDO_LAST:
2836 case LFUN_VC_COMMAND:
2840 case LFUN_SERVER_GOTO_FILE_ROW:
2841 goToFileRow(to_utf8(cmd.argument()));
2849 // Part of automatic menu appearance feature.
2850 if (isFullScreen()) {
2851 if (menuBar()->isVisible() && lyxrc.full_screen_menubar)
2853 if (statusBar()->isVisible())
2854 statusBar()->hide();
2861 void GuiView::lfunUiToggle(FuncRequest const & cmd)
2863 string const arg = cmd.getArg(0);
2864 if (arg == "scrollbar") {
2865 // hide() is of no help
2866 if (d.current_work_area_->verticalScrollBarPolicy() ==
2867 Qt::ScrollBarAlwaysOff)
2869 d.current_work_area_->setVerticalScrollBarPolicy(
2870 Qt::ScrollBarAsNeeded);
2872 d.current_work_area_->setVerticalScrollBarPolicy(
2873 Qt::ScrollBarAlwaysOff);
2876 if (arg == "statusbar") {
2877 statusBar()->setVisible(!statusBar()->isVisible());
2880 if (arg == "menubar") {
2881 menuBar()->setVisible(!menuBar()->isVisible());
2884 #if QT_VERSION >= 0x040300
2885 if (arg == "frame") {
2887 getContentsMargins(&l, &t, &r, &b);
2888 //are the frames in default state?
2889 d.current_work_area_->setFrameStyle(QFrame::NoFrame);
2891 setContentsMargins(-2, -2, -2, -2);
2893 setContentsMargins(0, 0, 0, 0);
2898 if (arg == "fullscreen") {
2903 message(bformat("LFUN_UI_TOGGLE " + _("%1$s unknown command!"), from_utf8(arg)));
2907 void GuiView::toggleFullScreen()
2909 if (isFullScreen()) {
2910 for (int i = 0; i != d.splitter_->count(); ++i)
2911 d.tabWorkArea(i)->setFullScreen(false);
2912 #if QT_VERSION >= 0x040300
2913 setContentsMargins(0, 0, 0, 0);
2915 setWindowState(windowState() ^ Qt::WindowFullScreen);
2918 statusBar()->show();
2921 hideDialogs("prefs", 0);
2922 for (int i = 0; i != d.splitter_->count(); ++i)
2923 d.tabWorkArea(i)->setFullScreen(true);
2924 #if QT_VERSION >= 0x040300
2925 setContentsMargins(-2, -2, -2, -2);
2928 setWindowState(windowState() ^ Qt::WindowFullScreen);
2929 statusBar()->hide();
2930 if (lyxrc.full_screen_menubar)
2932 if (lyxrc.full_screen_toolbars) {
2933 ToolbarMap::iterator end = d.toolbars_.end();
2934 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
2939 // give dialogs like the TOC a chance to adapt
2944 Buffer const * GuiView::updateInset(Inset const * inset)
2946 if (!d.current_work_area_)
2950 d.current_work_area_->scheduleRedraw();
2952 return &d.current_work_area_->bufferView().buffer();
2956 void GuiView::restartCursor()
2958 /* When we move around, or type, it's nice to be able to see
2959 * the cursor immediately after the keypress.
2961 if (d.current_work_area_)
2962 d.current_work_area_->startBlinkingCursor();
2964 // Take this occasion to update the other GUI elements.
2970 void GuiView::updateCompletion(Cursor & cur, bool start, bool keep)
2972 if (d.current_work_area_)
2973 d.current_work_area_->completer().updateVisibility(cur, start, keep);
2978 // This list should be kept in sync with the list of insets in
2979 // src/insets/Inset.cpp. I.e., if a dialog goes with an inset, the
2980 // dialog should have the same name as the inset.
2981 // Changes should be also recorded in LFUN_DIALOG_SHOW doxygen
2982 // docs in LyXAction.cpp.
2984 char const * const dialognames[] = {
2985 "aboutlyx", "bibitem", "bibtex", "box", "branch", "changes", "character",
2986 "citation", "compare", "document", "errorlist", "ert", "external", "file",
2987 "findreplace", "findreplaceadv", "float", "graphics", "href", "include",
2988 "index", "index_print", "info", "listings", "label", "log", "mathdelimiter",
2989 "mathmatrix", "mathspace", "nomenclature", "nomencl_print", "note",
2990 "paragraph", "phantom", "prefs", "print", "ref", "sendto", "space",
2991 "spellchecker", "symbols", "tabular", "tabularcreate", "thesaurus", "texinfo",
2992 "toc", "view-source", "vspace", "wrap" };
2994 char const * const * const end_dialognames =
2995 dialognames + (sizeof(dialognames) / sizeof(char *));
2999 cmpCStr(char const * name) : name_(name) {}
3000 bool operator()(char const * other) {
3001 return strcmp(other, name_) == 0;
3008 bool isValidName(string const & name)
3010 return find_if(dialognames, end_dialognames,
3011 cmpCStr(name.c_str())) != end_dialognames;
3017 void GuiView::resetDialogs()
3019 // Make sure that no LFUN uses any LyXView.
3020 guiApp->setCurrentView(0);
3023 constructToolbars();
3024 guiApp->menus().fillMenuBar(menuBar(), this, false);
3025 d.layout_->updateContents(true);
3026 // Now update controls with current buffer.
3027 guiApp->setCurrentView(this);
3033 Dialog * GuiView::findOrBuild(string const & name, bool hide_it)
3035 if (!isValidName(name))
3038 map<string, DialogPtr>::iterator it = d.dialogs_.find(name);
3040 if (it != d.dialogs_.end()) {
3042 it->second->hideView();
3043 return it->second.get();
3046 Dialog * dialog = build(name);
3047 d.dialogs_[name].reset(dialog);
3048 if (lyxrc.allow_geometry_session)
3049 dialog->restoreSession();
3056 void GuiView::showDialog(string const & name, string const & data,
3064 Dialog * dialog = findOrBuild(name, false);
3066 dialog->showData(data);
3067 if (inset && currentBufferView())
3068 currentBufferView()->editInset(name, inset);
3071 catch (ExceptionMessage const & ex) {
3079 bool GuiView::isDialogVisible(string const & name) const
3081 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3082 if (it == d.dialogs_.end())
3084 return it->second.get()->isVisibleView() && !it->second.get()->isClosing();
3088 void GuiView::hideDialog(string const & name, Inset * inset)
3090 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3091 if (it == d.dialogs_.end())
3094 if (inset && currentBufferView()
3095 && inset != currentBufferView()->editedInset(name))
3098 Dialog * const dialog = it->second.get();
3099 if (dialog->isVisibleView())
3101 if (currentBufferView())
3102 currentBufferView()->editInset(name, 0);
3106 void GuiView::disconnectDialog(string const & name)
3108 if (!isValidName(name))
3110 if (currentBufferView())
3111 currentBufferView()->editInset(name, 0);
3115 void GuiView::hideAll() const
3117 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
3118 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3120 for(; it != end; ++it)
3121 it->second->hideView();
3125 void GuiView::updateDialogs()
3127 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
3128 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3130 for(; it != end; ++it) {
3131 Dialog * dialog = it->second.get();
3132 if (dialog && dialog->isVisibleView())
3133 dialog->checkStatus();
3140 // will be replaced by a proper factory...
3141 Dialog * createGuiAbout(GuiView & lv);
3142 Dialog * createGuiBibitem(GuiView & lv);
3143 Dialog * createGuiBibtex(GuiView & lv);
3144 Dialog * createGuiBox(GuiView & lv);
3145 Dialog * createGuiBranch(GuiView & lv);
3146 Dialog * createGuiChanges(GuiView & lv);
3147 Dialog * createGuiCharacter(GuiView & lv);
3148 Dialog * createGuiCitation(GuiView & lv);
3149 Dialog * createGuiCompare(GuiView & lv);
3150 Dialog * createGuiDelimiter(GuiView & lv);
3151 Dialog * createGuiDocument(GuiView & lv);
3152 Dialog * createGuiErrorList(GuiView & lv);
3153 Dialog * createGuiERT(GuiView & lv);
3154 Dialog * createGuiExternal(GuiView & lv);
3155 Dialog * createGuiFloat(GuiView & lv);
3156 Dialog * createGuiGraphics(GuiView & lv);
3157 Dialog * createGuiInclude(GuiView & lv);
3158 Dialog * createGuiIndex(GuiView & lv);
3159 Dialog * createGuiInfo(GuiView & lv);
3160 Dialog * createGuiLabel(GuiView & lv);
3161 Dialog * createGuiListings(GuiView & lv);
3162 Dialog * createGuiLog(GuiView & lv);
3163 Dialog * createGuiMathHSpace(GuiView & lv);
3164 Dialog * createGuiMathMatrix(GuiView & lv);
3165 Dialog * createGuiNomenclature(GuiView & lv);
3166 Dialog * createGuiNote(GuiView & lv);
3167 Dialog * createGuiParagraph(GuiView & lv);
3168 Dialog * createGuiPhantom(GuiView & lv);
3169 Dialog * createGuiPreferences(GuiView & lv);
3170 Dialog * createGuiPrint(GuiView & lv);
3171 Dialog * createGuiPrintindex(GuiView & lv);
3172 Dialog * createGuiPrintNomencl(GuiView & lv);
3173 Dialog * createGuiRef(GuiView & lv);
3174 Dialog * createGuiSearch(GuiView & lv);
3175 Dialog * createGuiSearchAdv(GuiView & lv);
3176 Dialog * createGuiSendTo(GuiView & lv);
3177 Dialog * createGuiShowFile(GuiView & lv);
3178 Dialog * createGuiSpellchecker(GuiView & lv);
3179 Dialog * createGuiSymbols(GuiView & lv);
3180 Dialog * createGuiTabularCreate(GuiView & lv);
3181 Dialog * createGuiTabular(GuiView & lv);
3182 Dialog * createGuiTexInfo(GuiView & lv);
3183 Dialog * createGuiTextHSpace(GuiView & lv);
3184 Dialog * createGuiToc(GuiView & lv);
3185 Dialog * createGuiThesaurus(GuiView & lv);
3186 Dialog * createGuiHyperlink(GuiView & lv);
3187 Dialog * createGuiVSpace(GuiView & lv);
3188 Dialog * createGuiViewSource(GuiView & lv);
3189 Dialog * createGuiWrap(GuiView & lv);
3192 Dialog * GuiView::build(string const & name)
3194 LASSERT(isValidName(name), return 0);
3196 if (name == "aboutlyx")
3197 return createGuiAbout(*this);
3198 if (name == "bibitem")
3199 return createGuiBibitem(*this);
3200 if (name == "bibtex")
3201 return createGuiBibtex(*this);
3203 return createGuiBox(*this);
3204 if (name == "branch")
3205 return createGuiBranch(*this);
3206 if (name == "changes")
3207 return createGuiChanges(*this);
3208 if (name == "character")
3209 return createGuiCharacter(*this);
3210 if (name == "citation")
3211 return createGuiCitation(*this);
3212 if (name == "compare")
3213 return createGuiCompare(*this);
3214 if (name == "document")
3215 return createGuiDocument(*this);
3216 if (name == "errorlist")
3217 return createGuiErrorList(*this);
3219 return createGuiERT(*this);
3220 if (name == "external")
3221 return createGuiExternal(*this);
3223 return createGuiShowFile(*this);
3224 if (name == "findreplace")
3225 return createGuiSearch(*this);
3226 if (name == "findreplaceadv")
3227 return createGuiSearchAdv(*this);
3228 if (name == "float")
3229 return createGuiFloat(*this);
3230 if (name == "graphics")
3231 return createGuiGraphics(*this);
3233 return createGuiHyperlink(*this);
3234 if (name == "include")
3235 return createGuiInclude(*this);
3236 if (name == "index")
3237 return createGuiIndex(*this);
3238 if (name == "index_print")
3239 return createGuiPrintindex(*this);
3241 return createGuiInfo(*this);
3242 if (name == "label")
3243 return createGuiLabel(*this);
3244 if (name == "listings")
3245 return createGuiListings(*this);
3247 return createGuiLog(*this);
3248 if (name == "mathdelimiter")
3249 return createGuiDelimiter(*this);
3250 if (name == "mathspace")
3251 return createGuiMathHSpace(*this);
3252 if (name == "mathmatrix")
3253 return createGuiMathMatrix(*this);
3254 if (name == "nomenclature")
3255 return createGuiNomenclature(*this);
3256 if (name == "nomencl_print")
3257 return createGuiPrintNomencl(*this);
3259 return createGuiNote(*this);
3260 if (name == "paragraph")
3261 return createGuiParagraph(*this);
3262 if (name == "phantom")
3263 return createGuiPhantom(*this);
3264 if (name == "prefs")
3265 return createGuiPreferences(*this);
3266 if (name == "print")
3267 return createGuiPrint(*this);
3269 return createGuiRef(*this);
3270 if (name == "sendto")
3271 return createGuiSendTo(*this);
3272 if (name == "space")
3273 return createGuiTextHSpace(*this);
3274 if (name == "spellchecker")
3275 return createGuiSpellchecker(*this);
3276 if (name == "symbols")
3277 return createGuiSymbols(*this);
3278 if (name == "tabular")
3279 return createGuiTabular(*this);
3280 if (name == "tabularcreate")
3281 return createGuiTabularCreate(*this);
3282 if (name == "texinfo")
3283 return createGuiTexInfo(*this);
3284 if (name == "thesaurus")
3285 return createGuiThesaurus(*this);
3287 return createGuiToc(*this);
3288 if (name == "view-source")
3289 return createGuiViewSource(*this);
3290 if (name == "vspace")
3291 return createGuiVSpace(*this);
3293 return createGuiWrap(*this);
3299 } // namespace frontend
3302 #include "moc_GuiView.cpp"