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 #define EXPORT_in_THREAD 1
107 // QtConcurrent was introduced in Qt 4.4
108 #if (QT_VERSION >= 0x040400)
110 #include <QFutureWatcher>
111 #include <QtConcurrentRun>
114 #include <boost/bind.hpp>
118 #ifdef HAVE_SYS_TIME_H
119 # include <sys/time.h>
126 using namespace lyx::support;
133 class BackgroundWidget : public QWidget
138 LYXERR(Debug::GUI, "show banner: " << lyxrc.show_banner);
139 /// The text to be written on top of the pixmap
140 QString const text = lyx_version ?
141 qt_("version ") + lyx_version : qt_("unknown version");
142 splash_ = getPixmap("images/", "banner", "png");
144 QPainter pain(&splash_);
145 pain.setPen(QColor(0, 0, 0));
147 // The font used to display the version info
148 font.setStyleHint(QFont::SansSerif);
149 font.setWeight(QFont::Bold);
150 font.setPointSize(int(toqstr(lyxrc.font_sizes[FONT_SIZE_LARGE]).toDouble()));
152 pain.drawText(260, 15, text);
155 void paintEvent(QPaintEvent *)
157 int x = (width() - splash_.width()) / 2;
158 int y = (height() - splash_.height()) / 2;
160 pain.drawPixmap(x, y, splash_);
168 /// Toolbar store providing access to individual toolbars by name.
169 typedef std::map<std::string, GuiToolbar *> ToolbarMap;
171 typedef boost::shared_ptr<Dialog> DialogPtr;
176 struct GuiView::GuiViewPrivate
178 GuiViewPrivate(GuiView * gv)
179 : gv_(gv), current_work_area_(0), current_main_work_area_(0),
180 layout_(0), autosave_timeout_(5000),
183 // hardcode here the platform specific icon size
184 smallIconSize = 14; // scaling problems
185 normalIconSize = 20; // ok, default
186 bigIconSize = 26; // better for some math icons
188 splitter_ = new QSplitter;
189 bg_widget_ = new BackgroundWidget;
190 stack_widget_ = new QStackedWidget;
191 stack_widget_->addWidget(bg_widget_);
192 stack_widget_->addWidget(splitter_);
200 delete stack_widget_;
203 QMenu * toolBarPopup(GuiView * parent)
205 // FIXME: translation
206 QMenu * menu = new QMenu(parent);
207 QActionGroup * iconSizeGroup = new QActionGroup(parent);
209 QAction * smallIcons = new QAction(iconSizeGroup);
210 smallIcons->setText(qt_("Small-sized icons"));
211 smallIcons->setCheckable(true);
212 QObject::connect(smallIcons, SIGNAL(triggered()),
213 parent, SLOT(smallSizedIcons()));
214 menu->addAction(smallIcons);
216 QAction * normalIcons = new QAction(iconSizeGroup);
217 normalIcons->setText(qt_("Normal-sized icons"));
218 normalIcons->setCheckable(true);
219 QObject::connect(normalIcons, SIGNAL(triggered()),
220 parent, SLOT(normalSizedIcons()));
221 menu->addAction(normalIcons);
223 QAction * bigIcons = new QAction(iconSizeGroup);
224 bigIcons->setText(qt_("Big-sized icons"));
225 bigIcons->setCheckable(true);
226 QObject::connect(bigIcons, SIGNAL(triggered()),
227 parent, SLOT(bigSizedIcons()));
228 menu->addAction(bigIcons);
230 unsigned int cur = parent->iconSize().width();
231 if ( cur == parent->d.smallIconSize)
232 smallIcons->setChecked(true);
233 else if (cur == parent->d.normalIconSize)
234 normalIcons->setChecked(true);
235 else if (cur == parent->d.bigIconSize)
236 bigIcons->setChecked(true);
243 stack_widget_->setCurrentWidget(bg_widget_);
244 bg_widget_->setUpdatesEnabled(true);
247 TabWorkArea * tabWorkArea(int i)
249 return dynamic_cast<TabWorkArea *>(splitter_->widget(i));
252 TabWorkArea * currentTabWorkArea()
254 if (splitter_->count() == 1)
255 // The first TabWorkArea is always the first one, if any.
256 return tabWorkArea(0);
258 for (int i = 0; i != splitter_->count(); ++i) {
259 TabWorkArea * twa = tabWorkArea(i);
260 if (current_main_work_area_ == twa->currentWorkArea())
264 // None has the focus so we just take the first one.
265 return tabWorkArea(0);
268 void setPreviewFuture(QFuture<docstring> const & f)
270 preview_watcher_.setFuture(f);
271 connect(&preview_watcher_, SIGNAL(finished()), gv_,
272 SLOT(threadFinished()));
277 GuiWorkArea * current_work_area_;
278 GuiWorkArea * current_main_work_area_;
279 QSplitter * splitter_;
280 QStackedWidget * stack_widget_;
281 BackgroundWidget * bg_widget_;
283 ToolbarMap toolbars_;
284 /// The main layout box.
286 * \warning Don't Delete! The layout box is actually owned by
287 * whichever toolbar contains it. All the GuiView class needs is a
288 * means of accessing it.
290 * FIXME: replace that with a proper model so that we are not limited
291 * to only one dialog.
296 map<string, DialogPtr> dialogs_;
298 unsigned int smallIconSize;
299 unsigned int normalIconSize;
300 unsigned int bigIconSize;
302 QTimer statusbar_timer_;
303 /// auto-saving of buffers
304 Timeout autosave_timeout_;
305 /// flag against a race condition due to multiclicks, see bug #1119
309 TocModels toc_models_;
311 #if (QT_VERSION >= 0x040400)
313 QFutureWatcher<docstring> autosave_watcher_;
314 QFutureWatcher<docstring> preview_watcher_;
319 GuiView::GuiView(int id)
320 : d(*new GuiViewPrivate(this)), id_(id), closing_(false)
322 // GuiToolbars *must* be initialised before the menu bar.
323 normalSizedIcons(); // at least on Mac the default is 32 otherwise, which is huge
326 // set ourself as the current view. This is needed for the menu bar
327 // filling, at least for the static special menu item on Mac. Otherwise
328 // they are greyed out.
329 guiApp->setCurrentView(this);
331 // Fill up the menu bar.
332 guiApp->menus().fillMenuBar(menuBar(), this, true);
334 setCentralWidget(d.stack_widget_);
336 // Start autosave timer
337 if (lyxrc.autosave) {
338 d.autosave_timeout_.timeout.connect(boost::bind(&GuiView::autoSave, this));
339 d.autosave_timeout_.setTimeout(lyxrc.autosave * 1000);
340 d.autosave_timeout_.start();
342 connect(&d.statusbar_timer_, SIGNAL(timeout()),
343 this, SLOT(clearMessage()));
345 // We don't want to keep the window in memory if it is closed.
346 setAttribute(Qt::WA_DeleteOnClose, true);
348 #if (!defined(Q_WS_WIN) && !defined(Q_WS_MACX))
349 // assign an icon to main form. We do not do it under Qt/Win or Qt/Mac,
350 // since the icon is provided in the application bundle.
351 setWindowIcon(getPixmap("images/", "lyx", "png"));
355 setAcceptDrops(true);
357 statusBar()->setSizeGripEnabled(true);
359 // Forbid too small unresizable window because it can happen
360 // with some window manager under X11.
361 setMinimumSize(300, 200);
363 if (lyxrc.allow_geometry_session) {
364 // Now take care of session management.
369 // no session handling, default to a sane size.
370 setGeometry(50, 50, 690, 510);
373 // clear session data if any.
375 settings.remove("views");
377 #if (QT_VERSION >= 0x040400)
378 connect(&d.autosave_watcher_, SIGNAL(finished()), this,
379 SLOT(threadFinished()));
390 void GuiView::threadFinished()
392 #if (QT_VERSION >= 0x040400)
393 QFutureWatcher<docstring> const * watcher =
394 static_cast<QFutureWatcher<docstring> const *>(sender());
395 message(watcher->result());
400 void GuiView::saveLayout() const
403 settings.beginGroup("views");
404 settings.beginGroup(QString::number(id_));
406 settings.setValue("pos", pos());
407 settings.setValue("size", size());
409 settings.setValue("geometry", saveGeometry());
411 settings.setValue("layout", saveState(0));
412 settings.setValue("icon_size", iconSize());
416 bool GuiView::restoreLayout()
419 settings.beginGroup("views");
420 settings.beginGroup(QString::number(id_));
421 QString const icon_key = "icon_size";
422 if (!settings.contains(icon_key))
425 //code below is skipped when when ~/.config/LyX is (re)created
426 setIconSize(settings.value(icon_key).toSize());
428 QPoint pos = settings.value("pos", QPoint(50, 50)).toPoint();
429 QSize size = settings.value("size", QSize(690, 510)).toSize();
433 // Work-around for bug #6034: the window ends up in an undetermined
434 // state when trying to restore a maximized window when it is
435 // already maximized.
436 if (!(windowState() & Qt::WindowMaximized))
437 if (!restoreGeometry(settings.value("geometry").toByteArray()))
438 setGeometry(50, 50, 690, 510);
440 // Make sure layout is correctly oriented.
441 setLayoutDirection(qApp->layoutDirection());
443 // Allow the toc and view-source dock widget to be restored if needed.
445 if ((dialog = findOrBuild("toc", true)))
446 // see bug 5082. At least setup title and enabled state.
447 // Visibility will be adjusted by restoreState below.
448 dialog->prepareView();
449 if ((dialog = findOrBuild("view-source", true)))
450 dialog->prepareView();
452 if (!restoreState(settings.value("layout").toByteArray(), 0))
459 GuiToolbar * GuiView::toolbar(string const & name)
461 ToolbarMap::iterator it = d.toolbars_.find(name);
462 if (it != d.toolbars_.end())
465 LYXERR(Debug::GUI, "Toolbar::display: no toolbar named " << name);
466 message(bformat(_("Unknown toolbar \"%1$s\""), from_utf8(name)));
471 void GuiView::constructToolbars()
473 ToolbarMap::iterator it = d.toolbars_.begin();
474 for (; it != d.toolbars_.end(); ++it)
478 // I don't like doing this here, but the standard toolbar
479 // destroys this object when it's destroyed itself (vfr)
480 d.layout_ = new LayoutBox(*this);
481 d.stack_widget_->addWidget(d.layout_);
482 d.layout_->move(0,0);
484 // extracts the toolbars from the backend
485 Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
486 Toolbars::Infos::iterator end = guiApp->toolbars().end();
487 for (; cit != end; ++cit)
488 d.toolbars_[cit->name] = new GuiToolbar(*cit, *this);
492 void GuiView::initToolbars()
494 // extracts the toolbars from the backend
495 Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
496 Toolbars::Infos::iterator end = guiApp->toolbars().end();
497 for (; cit != end; ++cit) {
498 GuiToolbar * tb = toolbar(cit->name);
501 int const visibility = guiApp->toolbars().defaultVisibility(cit->name);
503 tb->setVisible(false);
504 tb->setVisibility(visibility);
506 if (visibility & Toolbars::TOP) {
508 addToolBarBreak(Qt::TopToolBarArea);
509 addToolBar(Qt::TopToolBarArea, tb);
512 if (visibility & Toolbars::BOTTOM) {
513 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
514 #if (QT_VERSION >= 0x040202)
515 addToolBarBreak(Qt::BottomToolBarArea);
517 addToolBar(Qt::BottomToolBarArea, tb);
520 if (visibility & Toolbars::LEFT) {
521 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
522 #if (QT_VERSION >= 0x040202)
523 addToolBarBreak(Qt::LeftToolBarArea);
525 addToolBar(Qt::LeftToolBarArea, tb);
528 if (visibility & Toolbars::RIGHT) {
529 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
530 #if (QT_VERSION >= 0x040202)
531 addToolBarBreak(Qt::RightToolBarArea);
533 addToolBar(Qt::RightToolBarArea, tb);
536 if (visibility & Toolbars::ON)
537 tb->setVisible(true);
542 TocModels & GuiView::tocModels()
544 return d.toc_models_;
548 void GuiView::setFocus()
550 LYXERR(Debug::DEBUG, "GuiView::setFocus()" << this);
551 // Make sure LyXFunc points to the correct view.
552 guiApp->setCurrentView(this);
553 QMainWindow::setFocus();
554 if (d.current_work_area_)
555 d.current_work_area_->setFocus();
559 QMenu * GuiView::createPopupMenu()
561 return d.toolBarPopup(this);
565 void GuiView::showEvent(QShowEvent * e)
567 LYXERR(Debug::GUI, "Passed Geometry "
568 << size().height() << "x" << size().width()
569 << "+" << pos().x() << "+" << pos().y());
571 if (d.splitter_->count() == 0)
572 // No work area, switch to the background widget.
575 QMainWindow::showEvent(e);
579 /** Destroy only all tabbed WorkAreas. Destruction of other WorkAreas
580 ** is responsibility of the container (e.g., dialog)
582 void GuiView::closeEvent(QCloseEvent * close_event)
584 LYXERR(Debug::DEBUG, "GuiView::closeEvent()");
589 // it can happen that this event arrives without selecting the view,
590 // e.g. when clicking the close button on a background window.
592 if (!closeWorkAreaAll()) {
594 close_event->ignore();
598 // Make sure that nothing will use this to be closed View.
599 guiApp->unregisterView(this);
601 if (isFullScreen()) {
602 // Switch off fullscreen before closing.
607 // Make sure the timer time out will not trigger a statusbar update.
608 d.statusbar_timer_.stop();
610 // Saving fullscreen requires additional tweaks in the toolbar code.
611 // It wouldn't also work under linux natively.
612 if (lyxrc.allow_geometry_session) {
613 // Save this window geometry and layout.
615 // Then the toolbar private states.
616 ToolbarMap::iterator end = d.toolbars_.end();
617 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
618 it->second->saveSession();
619 // Now take care of all other dialogs:
620 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
621 for (; it!= d.dialogs_.end(); ++it)
622 it->second->saveSession();
625 close_event->accept();
629 void GuiView::dragEnterEvent(QDragEnterEvent * event)
631 if (event->mimeData()->hasUrls())
633 /// \todo Ask lyx-devel is this is enough:
634 /// if (event->mimeData()->hasFormat("text/plain"))
635 /// event->acceptProposedAction();
639 void GuiView::dropEvent(QDropEvent * event)
641 QList<QUrl> files = event->mimeData()->urls();
645 LYXERR(Debug::GUI, "GuiView::dropEvent: got URLs!");
646 for (int i = 0; i != files.size(); ++i) {
647 string const file = os::internal_path(fromqstr(
648 files.at(i).toLocalFile()));
652 string const ext = support::getExtension(file);
653 vector<const Format *> found_formats;
655 // Find all formats that have the correct extension.
656 vector<const Format *> const & import_formats
657 = theConverters().importableFormats();
658 vector<const Format *>::const_iterator it = import_formats.begin();
659 for (; it != import_formats.end(); ++it)
660 if ((*it)->extension() == ext)
661 found_formats.push_back(*it);
664 if (found_formats.size() >= 1) {
665 if (found_formats.size() > 1) {
666 //FIXME: show a dialog to choose the correct importable format
668 "Multiple importable formats found, selecting first");
670 string const arg = found_formats[0]->name() + " " + file;
671 cmd = FuncRequest(LFUN_BUFFER_IMPORT, arg);
674 //FIXME: do we have to explicitly check whether it's a lyx file?
676 "No formats found, trying to open it as a lyx file");
677 cmd = FuncRequest(LFUN_FILE_OPEN, file);
680 // Asynchronously post the event. DropEvent usually come
681 // from the BufferView. But reloading a file might close
682 // the BufferView from within its own event handler.
683 guiApp->dispatchDelayed(cmd);
689 void GuiView::message(docstring const & str)
691 if (ForkedProcess::iAmAChild())
694 statusBar()->showMessage(toqstr(str));
695 d.statusbar_timer_.stop();
696 d.statusbar_timer_.start(3000);
700 void GuiView::smallSizedIcons()
702 setIconSize(QSize(d.smallIconSize, d.smallIconSize));
706 void GuiView::normalSizedIcons()
708 setIconSize(QSize(d.normalIconSize, d.normalIconSize));
712 void GuiView::bigSizedIcons()
714 setIconSize(QSize(d.bigIconSize, d.bigIconSize));
718 void GuiView::clearMessage()
723 d.statusbar_timer_.stop();
727 void GuiView::updateWindowTitle(GuiWorkArea * wa)
729 if (wa != d.current_work_area_)
731 setWindowTitle(qt_("LyX: ") + wa->windowTitle());
732 setWindowIconText(wa->windowIconText());
736 void GuiView::on_currentWorkAreaChanged(GuiWorkArea * wa)
739 disconnectBufferView();
740 connectBufferView(wa->bufferView());
741 connectBuffer(wa->bufferView().buffer());
742 d.current_work_area_ = wa;
743 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
744 this, SLOT(updateWindowTitle(GuiWorkArea *)));
745 updateWindowTitle(wa);
749 // The document settings needs to be reinitialised.
750 updateDialog("document", "");
752 // Buffer-dependent dialogs must be updated. This is done here because
753 // some dialogs require buffer()->text.
758 void GuiView::on_lastWorkAreaRemoved()
761 // We already are in a close event. Nothing more to do.
764 if (d.splitter_->count() > 1)
765 // We have a splitter so don't close anything.
768 // Reset and updates the dialogs.
769 d.toc_models_.reset(0);
770 updateDialog("document", "");
773 resetWindowTitleAndIconText();
775 if (lyxrc.open_buffers_in_tabs)
776 // Nothing more to do, the window should stay open.
779 if (guiApp->viewIds().size() > 1) {
785 // On Mac we also close the last window because the application stay
786 // resident in memory. On other platforms we don't close the last
787 // window because this would quit the application.
793 void GuiView::updateStatusBar()
795 // let the user see the explicit message
796 if (d.statusbar_timer_.isActive())
803 void GuiView::showMessage()
805 QString msg = toqstr(theGuiApp()->viewStatusMessage());
807 BufferView const * bv = currentBufferView();
809 msg = toqstr(bv->cursor().currentState());
811 msg = qt_("Welcome to LyX!");
813 statusBar()->showMessage(msg);
817 bool GuiView::event(QEvent * e)
821 // Useful debug code:
822 //case QEvent::ActivationChange:
823 //case QEvent::WindowDeactivate:
824 //case QEvent::Paint:
825 //case QEvent::Enter:
826 //case QEvent::Leave:
827 //case QEvent::HoverEnter:
828 //case QEvent::HoverLeave:
829 //case QEvent::HoverMove:
830 //case QEvent::StatusTip:
831 //case QEvent::DragEnter:
832 //case QEvent::DragLeave:
836 case QEvent::WindowActivate: {
837 GuiView * old_view = guiApp->currentView();
838 if (this == old_view) {
840 return QMainWindow::event(e);
842 if (old_view && old_view->currentBufferView()) {
843 // save current selection to the selection buffer to allow
844 // middle-button paste in this window.
845 cap::saveSelection(old_view->currentBufferView()->cursor());
847 guiApp->setCurrentView(this);
848 if (d.current_work_area_) {
849 BufferView & bv = d.current_work_area_->bufferView();
850 connectBufferView(bv);
851 connectBuffer(bv.buffer());
852 // The document structure, name and dialogs might have
853 // changed in another view.
855 // The document settings needs to be reinitialised.
856 updateDialog("document", "");
859 resetWindowTitleAndIconText();
862 return QMainWindow::event(e);
865 case QEvent::ShortcutOverride: {
868 #if (!defined Q_WS_X11) || (QT_VERSION >= 0x040500)
869 if (isFullScreen() && menuBar()->isHidden()) {
870 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
871 // FIXME: we should also try to detect special LyX shortcut such as
872 // Alt-P and Alt-M. Right now there is a hack in
873 // GuiWorkArea::processKeySym() that hides again the menubar for
875 if (ke->modifiers() & Qt::AltModifier && ke->key() != Qt::Key_Alt) {
877 return QMainWindow::event(e);
882 if (d.current_work_area_)
883 // Nothing special to do.
884 return QMainWindow::event(e);
886 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
887 // Let Qt handle menu access and the Tab keys to navigate keys to navigate
889 if (ke->modifiers() & Qt::AltModifier || ke->key() == Qt::Key_Tab
890 || ke->key() == Qt::Key_Backtab)
891 return QMainWindow::event(e);
893 // Allow processing of shortcuts that are allowed even when no Buffer
896 setKeySymbol(&sym, ke);
897 guiApp->processKeySym(sym, q_key_state(ke->modifiers()));
903 return QMainWindow::event(e);
907 void GuiView::resetWindowTitleAndIconText()
909 setWindowTitle(qt_("LyX"));
910 setWindowIconText(qt_("LyX"));
913 bool GuiView::focusNextPrevChild(bool /*next*/)
920 void GuiView::setBusy(bool busy)
922 if (d.current_work_area_) {
923 d.current_work_area_->setUpdatesEnabled(!busy);
925 d.current_work_area_->stopBlinkingCursor();
927 d.current_work_area_->startBlinkingCursor();
931 QApplication::setOverrideCursor(Qt::WaitCursor);
933 QApplication::restoreOverrideCursor();
937 GuiWorkArea * GuiView::workArea(Buffer & buffer)
939 if (currentWorkArea()
940 && ¤tWorkArea()->bufferView().buffer() == &buffer)
941 return (GuiWorkArea *) currentWorkArea();
942 if (TabWorkArea * twa = d.currentTabWorkArea())
943 return twa->workArea(buffer);
948 GuiWorkArea * GuiView::addWorkArea(Buffer & buffer)
950 // Automatically create a TabWorkArea if there are none yet.
951 TabWorkArea * tab_widget = d.splitter_->count()
952 ? d.currentTabWorkArea() : addTabWorkArea();
953 return tab_widget->addWorkArea(buffer, *this);
957 TabWorkArea * GuiView::addTabWorkArea()
959 TabWorkArea * twa = new TabWorkArea;
960 QObject::connect(twa, SIGNAL(currentWorkAreaChanged(GuiWorkArea *)),
961 this, SLOT(on_currentWorkAreaChanged(GuiWorkArea *)));
962 QObject::connect(twa, SIGNAL(lastWorkAreaRemoved()),
963 this, SLOT(on_lastWorkAreaRemoved()));
965 d.splitter_->addWidget(twa);
966 d.stack_widget_->setCurrentWidget(d.splitter_);
971 GuiWorkArea const * GuiView::currentWorkArea() const
973 return d.current_work_area_;
977 GuiWorkArea * GuiView::currentWorkArea()
979 return d.current_work_area_;
983 GuiWorkArea const * GuiView::currentMainWorkArea() const
985 if (d.currentTabWorkArea() == NULL)
987 return d.currentTabWorkArea()->currentWorkArea();
991 GuiWorkArea * GuiView::currentMainWorkArea()
993 if (d.currentTabWorkArea() == NULL)
995 return d.currentTabWorkArea()->currentWorkArea();
999 void GuiView::setCurrentWorkArea(GuiWorkArea * wa)
1001 LYXERR(Debug::DEBUG, "Setting current wa: " << wa << endl);
1003 d.current_work_area_ = NULL;
1007 GuiWorkArea * old_gwa = theGuiApp()->currentView()->currentWorkArea();
1011 if (currentBufferView())
1012 cap::saveSelection(currentBufferView()->cursor());
1014 theGuiApp()->setCurrentView(this);
1015 d.current_work_area_ = wa;
1016 for (int i = 0; i != d.splitter_->count(); ++i) {
1017 if (d.tabWorkArea(i)->setCurrentWorkArea(wa)) {
1018 //if (d.current_main_work_area_)
1019 // d.current_main_work_area_->setFrameStyle(QFrame::NoFrame);
1020 d.current_main_work_area_ = wa;
1021 //d.current_main_work_area_->setFrameStyle(QFrame::Box | QFrame::Plain);
1022 //d.current_main_work_area_->setLineWidth(2);
1023 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() << ", Current main wa: " << currentMainWorkArea());
1027 LYXERR(Debug::DEBUG, "This is not a tabbed wa");
1028 on_currentWorkAreaChanged(wa);
1029 BufferView & bv = wa->bufferView();
1030 bv.cursor().fixIfBroken();
1032 wa->setUpdatesEnabled(true);
1033 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() << ", Current main wa: " << currentMainWorkArea());
1037 void GuiView::removeWorkArea(GuiWorkArea * wa)
1039 LASSERT(wa, return);
1040 if (wa == d.current_work_area_) {
1042 disconnectBufferView();
1043 d.current_work_area_ = 0;
1044 d.current_main_work_area_ = 0;
1047 bool found_twa = false;
1048 for (int i = 0; i != d.splitter_->count(); ++i) {
1049 TabWorkArea * twa = d.tabWorkArea(i);
1050 if (twa->removeWorkArea(wa)) {
1051 // Found in this tab group, and deleted the GuiWorkArea.
1053 if (twa->count() != 0) {
1054 if (d.current_work_area_ == 0)
1055 // This means that we are closing the current GuiWorkArea, so
1056 // switch to the next GuiWorkArea in the found TabWorkArea.
1057 setCurrentWorkArea(twa->currentWorkArea());
1059 // No more WorkAreas in this tab group, so delete it.
1066 // It is not a tabbed work area (i.e., the search work area), so it
1067 // should be deleted by other means.
1068 LASSERT(found_twa, /* */);
1070 if (d.current_work_area_ == 0) {
1071 if (d.splitter_->count() != 0) {
1072 TabWorkArea * twa = d.currentTabWorkArea();
1073 setCurrentWorkArea(twa->currentWorkArea());
1075 // No more work areas, switch to the background widget.
1076 setCurrentWorkArea(0);
1082 LayoutBox * GuiView::getLayoutDialog() const
1088 void GuiView::updateLayoutList()
1091 d.layout_->updateContents(false);
1095 void GuiView::updateToolbars()
1097 ToolbarMap::iterator end = d.toolbars_.end();
1098 if (d.current_work_area_) {
1100 d.current_work_area_->bufferView().cursor().inMathed();
1102 lyx::getStatus(FuncRequest(LFUN_LAYOUT_TABULAR)).enabled();
1104 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).enabled() &&
1105 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).onoff(true);
1106 bool const mathmacrotemplate =
1107 lyx::getStatus(FuncRequest(LFUN_IN_MATHMACROTEMPLATE)).enabled();
1109 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1110 it->second->update(math, table, review, mathmacrotemplate);
1112 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1113 it->second->update(false, false, false, false);
1117 void GuiView::setBuffer(Buffer * newBuffer)
1119 LYXERR(Debug::DEBUG, "Setting buffer: " << newBuffer << std::endl);
1120 LASSERT(newBuffer, return);
1123 GuiWorkArea * wa = workArea(*newBuffer);
1125 newBuffer->masterBuffer()->updateLabels();
1126 wa = addWorkArea(*newBuffer);
1128 //Disconnect the old buffer...there's no new one.
1131 connectBuffer(*newBuffer);
1132 connectBufferView(wa->bufferView());
1133 setCurrentWorkArea(wa);
1139 void GuiView::connectBuffer(Buffer & buf)
1141 buf.setGuiDelegate(this);
1145 void GuiView::disconnectBuffer()
1147 if (d.current_work_area_)
1148 d.current_work_area_->bufferView().buffer().setGuiDelegate(0);
1152 void GuiView::connectBufferView(BufferView & bv)
1154 bv.setGuiDelegate(this);
1158 void GuiView::disconnectBufferView()
1160 if (d.current_work_area_)
1161 d.current_work_area_->bufferView().setGuiDelegate(0);
1165 void GuiView::errors(string const & error_type, bool from_master)
1167 ErrorList & el = from_master ?
1168 documentBufferView()->buffer().masterBuffer()->errorList(error_type)
1169 : documentBufferView()->buffer().errorList(error_type);
1170 string data = error_type;
1172 data = "from_master|" + error_type;
1174 showDialog("errorlist", data);
1178 void GuiView::updateTocItem(std::string const & type, DocIterator const & dit)
1180 d.toc_models_.updateItem(toqstr(type), dit);
1184 void GuiView::structureChanged()
1186 d.toc_models_.reset(documentBufferView());
1187 // Navigator needs more than a simple update in this case. It needs to be
1189 updateDialog("toc", "");
1193 void GuiView::updateDialog(string const & name, string const & data)
1195 if (!isDialogVisible(name))
1198 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
1199 if (it == d.dialogs_.end())
1202 Dialog * const dialog = it->second.get();
1203 if (dialog->isVisibleView())
1204 dialog->initialiseParams(data);
1208 BufferView * GuiView::documentBufferView()
1210 return currentMainWorkArea()
1211 ? ¤tMainWorkArea()->bufferView()
1216 BufferView const * GuiView::documentBufferView() const
1218 return currentMainWorkArea()
1219 ? ¤tMainWorkArea()->bufferView()
1224 BufferView * GuiView::currentBufferView()
1226 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1230 BufferView const * GuiView::currentBufferView() const
1232 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1236 static docstring saveAndDestroyBuffer(Buffer * buffer, FileName const & fname)
1239 FileName const tmp_ret = FileName::tempName("lyxauto");
1240 if (!tmp_ret.empty()) {
1241 if (buffer->writeFile(tmp_ret))
1242 failed = !tmp_ret.moveTo(fname);
1245 // failed to write/rename tmp_ret so try writing direct
1246 failed = buffer->writeFile(fname);
1250 ? _("Automatic save failed!")
1251 : _("Automatic save done.");
1255 void GuiView::autoSave()
1257 LYXERR(Debug::INFO, "Running autoSave()");
1259 Buffer * buffer = documentBufferView()
1260 ? &documentBufferView()->buffer() : 0;
1264 #if (QT_VERSION >= 0x040400)
1265 QFuture<docstring> f = QtConcurrent::run(saveAndDestroyBuffer, buffer->clone(),
1266 buffer->getAutosaveFilename());
1267 d.autosave_watcher_.setFuture(f);
1274 void GuiView::resetAutosaveTimers()
1277 d.autosave_timeout_.restart();
1281 bool GuiView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1284 Buffer * buf = currentBufferView()
1285 ? ¤tBufferView()->buffer() : 0;
1286 Buffer * doc_buffer = documentBufferView()
1287 ? &(documentBufferView()->buffer()) : 0;
1289 // Check whether we need a buffer
1290 if (!lyxaction.funcHasFlag(cmd.action, LyXAction::NoBuffer) && !buf) {
1291 // no, exit directly
1292 flag.message(from_utf8(N_("Command not allowed with"
1293 "out any document open")));
1294 flag.setEnabled(false);
1298 if (cmd.origin == FuncRequest::TOC) {
1299 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
1301 if (toc->getStatus(documentBufferView()->cursor(), cmd, fs))
1304 flag.setEnabled(false);
1308 switch(cmd.action) {
1309 case LFUN_BUFFER_IMPORT:
1312 case LFUN_MASTER_BUFFER_UPDATE:
1313 case LFUN_MASTER_BUFFER_VIEW:
1314 enable = doc_buffer && doc_buffer->parent() != 0;
1317 case LFUN_BUFFER_UPDATE:
1318 case LFUN_BUFFER_VIEW: {
1323 string format = to_utf8(cmd.argument());
1324 if (cmd.argument().empty())
1325 format = doc_buffer->getDefaultOutputFormat();
1326 enable = doc_buffer->isExportableFormat(format);
1330 case LFUN_BUFFER_RELOAD:
1331 enable = doc_buffer && !doc_buffer->isUnnamed()
1332 && doc_buffer->fileName().exists()
1333 && (!doc_buffer->isClean()
1334 || doc_buffer->isExternallyModified(Buffer::timestamp_method));
1337 case LFUN_BUFFER_CHILD_OPEN:
1338 enable = doc_buffer;
1341 case LFUN_BUFFER_WRITE:
1342 enable = doc_buffer && (doc_buffer->isUnnamed() || !doc_buffer->isClean());
1345 //FIXME: This LFUN should be moved to GuiApplication.
1346 case LFUN_BUFFER_WRITE_ALL: {
1347 // We enable the command only if there are some modified buffers
1348 Buffer * first = theBufferList().first();
1353 // We cannot use a for loop as the buffer list is a cycle.
1355 if (!b->isClean()) {
1359 b = theBufferList().next(b);
1360 } while (b != first);
1364 case LFUN_BUFFER_WRITE_AS:
1365 enable = doc_buffer;
1368 case LFUN_BUFFER_CLOSE:
1369 enable = doc_buffer;
1372 case LFUN_BUFFER_CLOSE_ALL:
1373 enable = theBufferList().last() != theBufferList().first();
1376 case LFUN_SPLIT_VIEW:
1377 if (cmd.getArg(0) == "vertical")
1378 enable = doc_buffer && (d.splitter_->count() == 1 ||
1379 d.splitter_->orientation() == Qt::Vertical);
1381 enable = doc_buffer && (d.splitter_->count() == 1 ||
1382 d.splitter_->orientation() == Qt::Horizontal);
1385 case LFUN_CLOSE_TAB_GROUP:
1386 enable = d.currentTabWorkArea();
1389 case LFUN_TOOLBAR_TOGGLE:
1390 if (GuiToolbar * t = toolbar(cmd.getArg(0)))
1391 flag.setOnOff(t->isVisible());
1394 case LFUN_DROP_LAYOUTS_CHOICE:
1398 case LFUN_UI_TOGGLE:
1399 flag.setOnOff(isFullScreen());
1402 case LFUN_DIALOG_DISCONNECT_INSET:
1405 case LFUN_DIALOG_HIDE:
1406 // FIXME: should we check if the dialog is shown?
1409 case LFUN_DIALOG_TOGGLE:
1410 flag.setOnOff(isDialogVisible(cmd.getArg(0)));
1411 // fall through to set "enable"
1412 case LFUN_DIALOG_SHOW: {
1413 string const name = cmd.getArg(0);
1415 enable = name == "aboutlyx"
1416 || name == "file" //FIXME: should be removed.
1418 || name == "texinfo"
1419 || name == "compare";
1420 else if (name == "print")
1421 enable = doc_buffer->isExportable("dvi")
1422 && lyxrc.print_command != "none";
1423 else if (name == "character" || name == "symbols") {
1424 if (!buf || buf->isReadonly()
1425 || !currentBufferView()->cursor().inTexted())
1428 // FIXME we should consider passthru
1430 Inset const & in = currentBufferView()->cursor().inset();
1431 enable = !in.getLayout().isPassThru();
1434 else if (name == "latexlog")
1435 enable = FileName(doc_buffer->logName()).isReadableFile();
1436 else if (name == "spellchecker")
1437 enable = theSpellChecker() && !doc_buffer->isReadonly();
1438 else if (name == "vclog")
1439 enable = doc_buffer->lyxvc().inUse();
1443 case LFUN_DIALOG_UPDATE: {
1444 string const name = cmd.getArg(0);
1446 enable = name == "prefs";
1450 case LFUN_COMMAND_EXECUTE:
1452 case LFUN_MENU_OPEN:
1453 // Nothing to check.
1456 case LFUN_COMPLETION_INLINE:
1457 if (!d.current_work_area_
1458 || !d.current_work_area_->completer().inlinePossible(
1459 currentBufferView()->cursor()))
1463 case LFUN_COMPLETION_POPUP:
1464 if (!d.current_work_area_
1465 || !d.current_work_area_->completer().popupPossible(
1466 currentBufferView()->cursor()))
1470 case LFUN_COMPLETION_COMPLETE:
1471 if (!d.current_work_area_
1472 || !d.current_work_area_->completer().inlinePossible(
1473 currentBufferView()->cursor()))
1477 case LFUN_COMPLETION_ACCEPT:
1478 if (!d.current_work_area_
1479 || (!d.current_work_area_->completer().popupVisible()
1480 && !d.current_work_area_->completer().inlineVisible()
1481 && !d.current_work_area_->completer().completionAvailable()))
1485 case LFUN_COMPLETION_CANCEL:
1486 if (!d.current_work_area_
1487 || (!d.current_work_area_->completer().popupVisible()
1488 && !d.current_work_area_->completer().inlineVisible()))
1492 case LFUN_BUFFER_ZOOM_OUT:
1493 enable = doc_buffer && lyxrc.zoom > 10;
1496 case LFUN_BUFFER_ZOOM_IN:
1497 enable = doc_buffer;
1500 case LFUN_BUFFER_NEXT:
1501 case LFUN_BUFFER_PREVIOUS:
1502 // FIXME: should we check is there is an previous or next buffer?
1504 case LFUN_BUFFER_SWITCH:
1505 // toggle on the current buffer, but do not toggle off
1506 // the other ones (is that a good idea?)
1508 && to_utf8(cmd.argument()) == doc_buffer->absFileName())
1509 flag.setOnOff(true);
1512 case LFUN_VC_REGISTER:
1513 enable = doc_buffer && !doc_buffer->lyxvc().inUse();
1515 case LFUN_VC_CHECK_IN:
1516 enable = doc_buffer && doc_buffer->lyxvc().checkInEnabled();
1518 case LFUN_VC_CHECK_OUT:
1519 enable = doc_buffer && doc_buffer->lyxvc().checkOutEnabled();
1521 case LFUN_VC_LOCKING_TOGGLE:
1522 enable = doc_buffer && !doc_buffer->isReadonly()
1523 && doc_buffer->lyxvc().lockingToggleEnabled();
1524 flag.setOnOff(enable && !doc_buffer->lyxvc().locker().empty());
1526 case LFUN_VC_REVERT:
1527 enable = doc_buffer && doc_buffer->lyxvc().inUse();
1529 case LFUN_VC_UNDO_LAST:
1530 enable = doc_buffer && doc_buffer->lyxvc().undoLastEnabled();
1532 case LFUN_VC_REPO_UPDATE:
1533 enable = doc_buffer && doc_buffer->lyxvc().inUse();
1535 case LFUN_VC_COMMAND: {
1536 if (cmd.argument().empty())
1538 if (!doc_buffer && contains(cmd.getArg(0), 'D'))
1543 case LFUN_SERVER_GOTO_FILE_ROW:
1551 flag.setEnabled(false);
1557 static FileName selectTemplateFile()
1559 FileDialog dlg(qt_("Select template file"));
1560 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1561 dlg.setButton1(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
1563 FileDialog::Result result = dlg.open(toqstr(lyxrc.template_path),
1564 QStringList(qt_("LyX Documents (*.lyx)")));
1566 if (result.first == FileDialog::Later)
1568 if (result.second.isEmpty())
1570 return FileName(fromqstr(result.second));
1574 Buffer * GuiView::loadDocument(FileName const & filename, bool tolastfiles)
1578 Buffer * newBuffer = checkAndLoadLyXFile(filename);
1581 message(_("Document not loaded."));
1586 setBuffer(newBuffer);
1588 // scroll to the position when the file was last closed
1589 if (lyxrc.use_lastfilepos) {
1590 LastFilePosSection::FilePos filepos =
1591 theSession().lastFilePos().load(filename);
1592 documentBufferView()->moveToPosition(filepos.pit, filepos.pos, 0, 0);
1596 theSession().lastFiles().add(filename);
1603 void GuiView::openDocument(string const & fname)
1605 string initpath = lyxrc.document_path;
1607 if (documentBufferView()) {
1608 string const trypath = documentBufferView()->buffer().filePath();
1609 // If directory is writeable, use this as default.
1610 if (FileName(trypath).isDirWritable())
1616 if (fname.empty()) {
1617 FileDialog dlg(qt_("Select document to open"), LFUN_FILE_OPEN);
1618 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1619 dlg.setButton2(qt_("Examples|#E#e"),
1620 toqstr(addPath(package().system_support().absFilename(), "examples")));
1622 QStringList filter(qt_("LyX Documents (*.lyx)"));
1623 filter << qt_("LyX-1.3.x Documents (*.lyx13)")
1624 << qt_("LyX-1.4.x Documents (*.lyx14)")
1625 << qt_("LyX-1.5.x Documents (*.lyx15)")
1626 << qt_("LyX-1.6.x Documents (*.lyx16)");
1627 FileDialog::Result result =
1628 dlg.open(toqstr(initpath), filter);
1630 if (result.first == FileDialog::Later)
1633 filename = fromqstr(result.second);
1635 // check selected filename
1636 if (filename.empty()) {
1637 message(_("Canceled."));
1643 // get absolute path of file and add ".lyx" to the filename if
1645 FileName const fullname =
1646 fileSearch(string(), filename, "lyx", support::may_not_exist);
1647 if (!fullname.empty())
1648 filename = fullname.absFilename();
1650 if (!fullname.onlyPath().isDirectory()) {
1651 Alert::warning(_("Invalid filename"),
1652 bformat(_("The directory in the given path\n%1$s\ndoes not exist."),
1653 from_utf8(fullname.absFilename())));
1656 // if the file doesn't exist, let the user create one
1657 if (!fullname.exists()) {
1658 // the user specifically chose this name. Believe him.
1659 Buffer * const b = newFile(filename, string(), true);
1665 docstring const disp_fn = makeDisplayPath(filename);
1666 message(bformat(_("Opening document %1$s..."), disp_fn));
1669 Buffer * buf = loadDocument(fullname);
1671 buf->updateLabels();
1673 buf->errors("Parse");
1674 str2 = bformat(_("Document %1$s opened."), disp_fn);
1675 if (buf->lyxvc().inUse())
1676 str2 += " " + from_utf8(buf->lyxvc().versionString()) +
1677 " " + _("Version control detected.");
1679 str2 = bformat(_("Could not open document %1$s"), disp_fn);
1684 // FIXME: clean that
1685 static bool import(GuiView * lv, FileName const & filename,
1686 string const & format, ErrorList & errorList)
1688 FileName const lyxfile(support::changeExtension(filename.absFilename(), ".lyx"));
1690 string loader_format;
1691 vector<string> loaders = theConverters().loaders();
1692 if (find(loaders.begin(), loaders.end(), format) == loaders.end()) {
1693 for (vector<string>::const_iterator it = loaders.begin();
1694 it != loaders.end(); ++it) {
1695 if (!theConverters().isReachable(format, *it))
1698 string const tofile =
1699 support::changeExtension(filename.absFilename(),
1700 formats.extension(*it));
1701 if (!theConverters().convert(0, filename, FileName(tofile),
1702 filename, format, *it, errorList))
1704 loader_format = *it;
1707 if (loader_format.empty()) {
1708 frontend::Alert::error(_("Couldn't import file"),
1709 bformat(_("No information for importing the format %1$s."),
1710 formats.prettyName(format)));
1714 loader_format = format;
1716 if (loader_format == "lyx") {
1717 Buffer * buf = lv->loadDocument(lyxfile);
1720 buf->updateLabels();
1722 buf->errors("Parse");
1724 Buffer * const b = newFile(lyxfile.absFilename(), string(), true);
1728 bool as_paragraphs = loader_format == "textparagraph";
1729 string filename2 = (loader_format == format) ? filename.absFilename()
1730 : support::changeExtension(filename.absFilename(),
1731 formats.extension(loader_format));
1732 lv->currentBufferView()->insertPlaintextFile(FileName(filename2),
1734 guiApp->setCurrentView(lv);
1735 lyx::dispatch(FuncRequest(LFUN_MARK_OFF));
1742 void GuiView::importDocument(string const & argument)
1745 string filename = split(argument, format, ' ');
1747 LYXERR(Debug::INFO, format << " file: " << filename);
1749 // need user interaction
1750 if (filename.empty()) {
1751 string initpath = lyxrc.document_path;
1752 if (documentBufferView()) {
1753 string const trypath = documentBufferView()->buffer().filePath();
1754 // If directory is writeable, use this as default.
1755 if (FileName(trypath).isDirWritable())
1759 docstring const text = bformat(_("Select %1$s file to import"),
1760 formats.prettyName(format));
1762 FileDialog dlg(toqstr(text), LFUN_BUFFER_IMPORT);
1763 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1764 dlg.setButton2(qt_("Examples|#E#e"),
1765 toqstr(addPath(package().system_support().absFilename(), "examples")));
1767 docstring filter = formats.prettyName(format);
1770 filter += from_utf8(formats.extension(format));
1773 FileDialog::Result result =
1774 dlg.open(toqstr(initpath), fileFilters(toqstr(filter)));
1776 if (result.first == FileDialog::Later)
1779 filename = fromqstr(result.second);
1781 // check selected filename
1782 if (filename.empty())
1783 message(_("Canceled."));
1786 if (filename.empty())
1789 // get absolute path of file
1790 FileName const fullname(support::makeAbsPath(filename));
1792 FileName const lyxfile(support::changeExtension(fullname.absFilename(), ".lyx"));
1794 // Check if the document already is open
1795 Buffer * buf = theBufferList().getBuffer(lyxfile);
1798 if (!closeBuffer()) {
1799 message(_("Canceled."));
1804 docstring const displaypath = makeDisplayPath(lyxfile.absFilename(), 30);
1806 // if the file exists already, and we didn't do
1807 // -i lyx thefile.lyx, warn
1808 if (lyxfile.exists() && fullname != lyxfile) {
1810 docstring text = bformat(_("The document %1$s already exists.\n\n"
1811 "Do you want to overwrite that document?"), displaypath);
1812 int const ret = Alert::prompt(_("Overwrite document?"),
1813 text, 0, 1, _("&Overwrite"), _("&Cancel"));
1816 message(_("Canceled."));
1821 message(bformat(_("Importing %1$s..."), displaypath));
1822 ErrorList errorList;
1823 if (import(this, fullname, format, errorList))
1824 message(_("imported."));
1826 message(_("file not imported!"));
1828 // FIXME (Abdel 12/08/06): Is there a need to display the error list here?
1832 void GuiView::newDocument(string const & filename, bool from_template)
1834 FileName initpath(lyxrc.document_path);
1835 if (documentBufferView()) {
1836 FileName const trypath(documentBufferView()->buffer().filePath());
1837 // If directory is writeable, use this as default.
1838 if (trypath.isDirWritable())
1842 string templatefile;
1843 if (from_template) {
1844 templatefile = selectTemplateFile().absFilename();
1845 if (templatefile.empty())
1850 if (filename.empty())
1851 b = newUnnamedFile(initpath, to_utf8(_("newfile")), templatefile);
1853 b = newFile(filename, templatefile, true);
1858 // If no new document could be created, it is unsure
1859 // whether there is a valid BufferView.
1860 if (currentBufferView())
1861 // Ensure the cursor is correctly positioned on screen.
1862 currentBufferView()->showCursor();
1866 void GuiView::insertLyXFile(docstring const & fname)
1868 BufferView * bv = documentBufferView();
1873 FileName filename(to_utf8(fname));
1875 if (!filename.empty()) {
1876 bv->insertLyXFile(filename);
1880 // Launch a file browser
1882 string initpath = lyxrc.document_path;
1883 string const trypath = bv->buffer().filePath();
1884 // If directory is writeable, use this as default.
1885 if (FileName(trypath).isDirWritable())
1889 FileDialog dlg(qt_("Select LyX document to insert"), LFUN_FILE_INSERT);
1890 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1891 dlg.setButton2(qt_("Examples|#E#e"),
1892 toqstr(addPath(package().system_support().absFilename(),
1895 FileDialog::Result result = dlg.open(toqstr(initpath),
1896 QStringList(qt_("LyX Documents (*.lyx)")));
1898 if (result.first == FileDialog::Later)
1902 filename.set(fromqstr(result.second));
1904 // check selected filename
1905 if (filename.empty()) {
1906 // emit message signal.
1907 message(_("Canceled."));
1911 bv->insertLyXFile(filename);
1915 void GuiView::insertPlaintextFile(docstring const & fname,
1918 BufferView * bv = documentBufferView();
1922 if (!fname.empty() && !FileName::isAbsolute(to_utf8(fname))) {
1923 message(_("Absolute filename expected."));
1928 FileName filename(to_utf8(fname));
1930 if (!filename.empty()) {
1931 bv->insertPlaintextFile(filename, asParagraph);
1935 FileDialog dlg(qt_("Select file to insert"), (asParagraph ?
1936 LFUN_FILE_INSERT_PLAINTEXT_PARA : LFUN_FILE_INSERT_PLAINTEXT));
1938 FileDialog::Result result = dlg.open(toqstr(bv->buffer().filePath()),
1939 QStringList(qt_("All Files (*)")));
1941 if (result.first == FileDialog::Later)
1945 filename.set(fromqstr(result.second));
1947 // check selected filename
1948 if (filename.empty()) {
1949 // emit message signal.
1950 message(_("Canceled."));
1954 bv->insertPlaintextFile(filename, asParagraph);
1958 bool GuiView::renameBuffer(Buffer & b, docstring const & newname)
1960 FileName fname = b.fileName();
1961 FileName const oldname = fname;
1963 if (!newname.empty()) {
1965 fname = support::makeAbsPath(to_utf8(newname), oldname.onlyPath().absFilename());
1967 // Switch to this Buffer.
1970 // No argument? Ask user through dialog.
1972 FileDialog dlg(qt_("Choose a filename to save document as"),
1973 LFUN_BUFFER_WRITE_AS);
1974 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1975 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
1977 if (!isLyXFilename(fname.absFilename()))
1978 fname.changeExtension(".lyx");
1980 FileDialog::Result result =
1981 dlg.save(toqstr(fname.onlyPath().absFilename()),
1982 QStringList(qt_("LyX Documents (*.lyx)")),
1983 toqstr(fname.onlyFileName()));
1985 if (result.first == FileDialog::Later)
1988 fname.set(fromqstr(result.second));
1993 if (!isLyXFilename(fname.absFilename()))
1994 fname.changeExtension(".lyx");
1997 if (FileName(fname).exists()) {
1998 docstring const file = makeDisplayPath(fname.absFilename(), 30);
1999 docstring text = bformat(_("The document %1$s already "
2000 "exists.\n\nDo you want to "
2001 "overwrite that document?"),
2003 int const ret = Alert::prompt(_("Overwrite document?"),
2004 text, 0, 2, _("&Overwrite"), _("&Rename"), _("&Cancel"));
2007 case 1: return renameBuffer(b, docstring());
2008 case 2: return false;
2012 FileName oldauto = b.getAutosaveFilename();
2014 // Ok, change the name of the buffer
2015 b.setFileName(fname.absFilename());
2017 bool unnamed = b.isUnnamed();
2018 b.setUnnamed(false);
2019 b.saveCheckSum(fname);
2021 // bring the autosave file with us, just in case.
2022 b.moveAutosaveFile(oldauto);
2024 if (!saveBuffer(b)) {
2025 oldauto = b.getAutosaveFilename();
2026 b.setFileName(oldname.absFilename());
2027 b.setUnnamed(unnamed);
2028 b.saveCheckSum(oldname);
2029 b.moveAutosaveFile(oldauto);
2037 bool GuiView::saveBuffer(Buffer & b)
2039 if (workArea(b) && workArea(b)->inDialogMode())
2043 return renameBuffer(b, docstring());
2046 theSession().lastFiles().add(b.fileName());
2050 // Switch to this Buffer.
2053 // FIXME: we don't tell the user *WHY* the save failed !!
2054 docstring const file = makeDisplayPath(b.absFileName(), 30);
2055 docstring text = bformat(_("The document %1$s could not be saved.\n\n"
2056 "Do you want to rename the document and "
2057 "try again?"), file);
2058 int const ret = Alert::prompt(_("Rename and save?"),
2059 text, 0, 2, _("&Rename"), _("&Retry"), _("&Cancel"));
2062 if (!renameBuffer(b, docstring()))
2071 return saveBuffer(b);
2075 bool GuiView::hideWorkArea(GuiWorkArea * wa)
2077 return closeWorkArea(wa, false);
2081 bool GuiView::closeWorkArea(GuiWorkArea * wa)
2083 Buffer & buf = wa->bufferView().buffer();
2084 return closeWorkArea(wa, !buf.parent());
2088 bool GuiView::closeBuffer()
2090 GuiWorkArea * wa = currentMainWorkArea();
2091 Buffer & buf = wa->bufferView().buffer();
2092 return wa && closeWorkArea(wa, !buf.parent());
2096 void GuiView::writeSession() const {
2097 GuiWorkArea const * active_wa = currentMainWorkArea();
2098 for (int i = 0; i < d.splitter_->count(); ++i) {
2099 TabWorkArea * twa = d.tabWorkArea(i);
2100 for (int j = 0; j < twa->count(); ++j) {
2101 GuiWorkArea * wa = static_cast<GuiWorkArea *>(twa->widget(j));
2102 Buffer & buf = wa->bufferView().buffer();
2103 theSession().lastOpened().add(buf.fileName(), wa == active_wa);
2109 bool GuiView::closeBufferAll()
2111 // Close the workareas in all other views
2112 QList<int> const ids = guiApp->viewIds();
2113 for (int i = 0; i != ids.size(); ++i) {
2114 if (id_ != ids[i] && !guiApp->view(ids[i]).closeWorkAreaAll())
2118 // Close our own workareas
2119 if (!closeWorkAreaAll())
2122 // Now close the hidden buffers. We prevent hidden buffers from being
2123 // dirty, so we can just close them.
2124 theBufferList().closeAll();
2129 bool GuiView::closeWorkAreaAll()
2131 setCurrentWorkArea(currentMainWorkArea());
2133 // We might be in a situation that there is still a tabWorkArea, but
2134 // there are no tabs anymore. This can happen when we get here after a
2135 // TabWorkArea::lastWorkAreaRemoved() signal. Therefore we count how
2136 // many TabWorkArea's have no documents anymore.
2139 // We have to call count() each time, because it can happen that
2140 // more than one splitter will disappear in one iteration (bug 5998).
2141 for (; d.splitter_->count() > empty_twa; ) {
2142 TabWorkArea * twa = d.tabWorkArea(empty_twa);
2144 if (twa->count() == 0)
2147 setCurrentWorkArea(twa->currentWorkArea());
2148 if (!closeTabWorkArea(twa))
2156 bool GuiView::closeWorkArea(GuiWorkArea * wa, bool close_buffer)
2161 Buffer & buf = wa->bufferView().buffer();
2164 return closeBuffer(buf);
2166 if (!inMultiTabs(wa))
2167 if (!saveBufferIfNeeded(buf, true))
2175 bool GuiView::closeBuffer(Buffer & buf)
2177 // If we are in a close_event all children will be closed in some time,
2178 // so no need to do it here. This will ensure that the children end up
2179 // in the session file in the correct order. If we close the master
2180 // buffer, we can close or release the child buffers here too.
2182 vector<Buffer *> clist = buf.getChildren(false);
2183 for (vector<Buffer *>::const_iterator it = clist.begin();
2184 it != clist.end(); ++it) {
2185 // If a child is dirty, do not close
2186 // without user intervention
2187 //FIXME: should we look in other tabworkareas?
2188 Buffer * child_buf = *it;
2189 GuiWorkArea * child_wa = workArea(*child_buf);
2191 if (!closeWorkArea(child_wa, true))
2194 theBufferList().releaseChild(&buf, child_buf);
2197 // goto bookmark to update bookmark pit.
2198 //FIXME: we should update only the bookmarks related to this buffer!
2199 LYXERR(Debug::DEBUG, "GuiView::closeBuffer()");
2200 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
2201 theLyXFunc().gotoBookmark(i+1, false, false);
2203 if (saveBufferIfNeeded(buf, false)) {
2204 theBufferList().release(&buf);
2211 bool GuiView::closeTabWorkArea(TabWorkArea * twa)
2213 while (twa == d.currentTabWorkArea()) {
2214 twa->setCurrentIndex(twa->count()-1);
2216 GuiWorkArea * wa = twa->currentWorkArea();
2217 Buffer & b = wa->bufferView().buffer();
2219 // We only want to close the buffer if the same buffer is not visible
2220 // in another view, and if this is not a child and if we are closing
2221 // a view (not a tabgroup).
2222 bool const close_buffer =
2223 !inMultiViews(wa) && !b.parent() && closing_;
2225 if (!closeWorkArea(wa, close_buffer))
2232 bool GuiView::saveBufferIfNeeded(Buffer & buf, bool hiding)
2234 if (buf.isClean() || buf.paragraphs().empty())
2237 // Switch to this Buffer.
2242 if (buf.isUnnamed())
2243 file = from_utf8(buf.fileName().onlyFileName());
2245 file = buf.fileName().displayName(30);
2247 // Bring this window to top before asking questions.
2252 if (hiding && buf.isUnnamed()) {
2253 docstring const text = bformat(_("The document %1$s has not been "
2254 "saved yet.\n\nDo you want to save "
2255 "the document?"), file);
2256 ret = Alert::prompt(_("Save new document?"),
2257 text, 0, 1, _("&Save"), _("&Cancel"));
2261 docstring const text = bformat(_("The document %1$s has unsaved changes."
2262 "\n\nDo you want to save the document or discard the changes?"), file);
2263 ret = Alert::prompt(_("Save changed document?"),
2264 text, 0, 2, _("&Save"), _("&Discard"), _("&Cancel"));
2269 if (!saveBuffer(buf))
2273 // if we crash after this we could
2274 // have no autosave file but I guess
2275 // this is really improbable (Jug)
2276 buf.removeAutosaveFile();
2278 // revert all changes
2279 buf.loadLyXFile(buf.fileName());
2289 bool GuiView::inMultiTabs(GuiWorkArea * wa)
2291 Buffer & buf = wa->bufferView().buffer();
2293 for (int i = 0; i != d.splitter_->count(); ++i) {
2294 GuiWorkArea * wa_ = d.tabWorkArea(i)->workArea(buf);
2295 if (wa_ && wa_ != wa)
2298 return inMultiViews(wa);
2302 bool GuiView::inMultiViews(GuiWorkArea * wa)
2304 QList<int> const ids = guiApp->viewIds();
2305 Buffer & buf = wa->bufferView().buffer();
2308 for (int i = 0; i != ids.size() && found_twa <= 1; ++i) {
2312 if (guiApp->view(ids[i]).workArea(buf))
2319 void GuiView::gotoNextOrPreviousBuffer(NextOrPrevious np)
2321 Buffer * const curbuf = documentBufferView()
2322 ? &documentBufferView()->buffer() : 0;
2323 Buffer * nextbuf = curbuf;
2325 if (np == NEXTBUFFER)
2326 nextbuf = theBufferList().next(nextbuf);
2328 nextbuf = theBufferList().previous(nextbuf);
2329 if (nextbuf == curbuf)
2335 if (workArea(*nextbuf))
2342 /// make sure the document is saved
2343 static bool ensureBufferClean(Buffer * buffer)
2345 LASSERT(buffer, return false);
2346 if (buffer->isClean() && !buffer->isUnnamed())
2349 docstring const file = buffer->fileName().displayName(30);
2352 if (!buffer->isUnnamed()) {
2353 text = bformat(_("The document %1$s has unsaved "
2354 "changes.\n\nDo you want to save "
2355 "the document?"), file);
2356 title = _("Save changed document?");
2359 text = bformat(_("The document %1$s has not been "
2360 "saved yet.\n\nDo you want to save "
2361 "the document?"), file);
2362 title = _("Save new document?");
2364 int const ret = Alert::prompt(title, text, 0, 1, _("&Save"), _("&Cancel"));
2367 dispatch(FuncRequest(LFUN_BUFFER_WRITE));
2369 return buffer->isClean() && !buffer->isUnnamed();
2373 void GuiView::reloadBuffer()
2375 Buffer * buf = &documentBufferView()->buffer();
2380 void GuiView::reloadBuffer(Buffer * buf)
2382 FileName filename = buf->fileName();
2383 Buffer const * master = buf->masterBuffer();
2384 bool const is_child = master != buf;
2385 // The user has already confirmed that the changes, if any, should
2386 // be discarded. So we just release the Buffer and don't call closeBuffer();
2387 theBufferList().release(buf);
2388 buf = loadDocument(filename);
2389 docstring const disp_fn = makeDisplayPath(filename.absFilename());
2392 // re-allocate master if necessary
2393 if (is_child && theBufferList().isLoaded(master)
2394 && buf->masterBuffer() != master)
2395 buf->setParent(master);
2396 buf->updateLabels();
2398 buf->errors("Parse");
2399 str = bformat(_("Document %1$s reloaded."), disp_fn);
2401 str = bformat(_("Could not reload document %1$s"), disp_fn);
2407 void GuiView::checkExternallyModifiedBuffers()
2409 BufferList::iterator bit = theBufferList().begin();
2410 BufferList::iterator const bend = theBufferList().end();
2411 for (; bit != bend; ++bit) {
2412 if ((*bit)->isExternallyModified(Buffer::checksum_method)) {
2413 docstring text = bformat(_("Document \n%1$s\n has been externally modified."
2414 " Reload now? Any local changes will be lost."),
2415 from_utf8((*bit)->absFileName()));
2416 int const ret = Alert::prompt(_("Reload externally changed document?"),
2417 text, 0, 1, _("&Reload"), _("&Cancel"));
2425 void GuiView::dispatchVC(FuncRequest const & cmd)
2427 Buffer * buffer = documentBufferView()
2428 ? &(documentBufferView()->buffer()) : 0;
2430 switch (cmd.action) {
2431 case LFUN_VC_REGISTER:
2432 if (!buffer || !ensureBufferClean(buffer))
2434 if (!buffer->lyxvc().inUse()) {
2435 if (buffer->lyxvc().registrer())
2440 case LFUN_VC_CHECK_IN:
2441 if (!buffer || !ensureBufferClean(buffer))
2443 if (buffer->lyxvc().inUse() && !buffer->isReadonly()) {
2444 message(from_utf8(buffer->lyxvc().checkIn()));
2449 case LFUN_VC_CHECK_OUT:
2450 if (!buffer || !ensureBufferClean(buffer))
2452 if (buffer->lyxvc().inUse()) {
2453 message(from_utf8(buffer->lyxvc().checkOut()));
2458 case LFUN_VC_LOCKING_TOGGLE:
2459 LASSERT(buffer, return);
2460 if (!ensureBufferClean(buffer) || buffer->isReadonly())
2462 if (buffer->lyxvc().inUse()) {
2463 string res = buffer->lyxvc().lockingToggle();
2465 frontend::Alert::error(_("Revision control error."),
2466 _("Error when setting the locking property."));
2468 message(from_utf8(res));
2474 case LFUN_VC_REVERT:
2475 LASSERT(buffer, return);
2476 buffer->lyxvc().revert();
2480 case LFUN_VC_UNDO_LAST:
2481 LASSERT(buffer, return);
2482 buffer->lyxvc().undoLast();
2486 case LFUN_VC_REPO_UPDATE:
2487 LASSERT(buffer, return);
2488 if (ensureBufferClean(buffer)) {
2489 string res = buffer->lyxvc().repoUpdate();
2490 message(from_utf8(res));
2491 checkExternallyModifiedBuffers();
2495 case LFUN_VC_COMMAND: {
2496 string flag = cmd.getArg(0);
2497 if (buffer && contains(flag, 'R') && !ensureBufferClean(buffer))
2500 if (contains(flag, 'M')) {
2501 if (!Alert::askForText(message, _("LyX VC: Log Message")))
2504 string path = cmd.getArg(1);
2505 if (contains(path, "$$p") && buffer)
2506 path = subst(path, "$$p", buffer->filePath());
2507 LYXERR(Debug::LYXVC, "Directory: " << path);
2509 if (!pp.isReadableDirectory()) {
2510 lyxerr << _("Directory is not accessible.") << endl;
2513 support::PathChanger p(pp);
2515 string command = cmd.getArg(2);
2516 if (command.empty())
2519 command = subst(command, "$$i", buffer->absFileName());
2520 command = subst(command, "$$p", buffer->filePath());
2522 command = subst(command, "$$m", to_utf8(message));
2523 LYXERR(Debug::LYXVC, "Command: " << command);
2525 one.startscript(Systemcall::Wait, command);
2529 if (contains(flag, 'I'))
2530 buffer->markDirty();
2531 if (contains(flag, 'R'))
2542 void GuiView::openChildDocument(string const & fname)
2544 LASSERT(documentBufferView(), return);
2545 Buffer & buffer = documentBufferView()->buffer();
2546 FileName const filename = support::makeAbsPath(fname, buffer.filePath());
2547 documentBufferView()->saveBookmark(false);
2549 bool parsed = false;
2550 if (theBufferList().exists(filename)) {
2551 child = theBufferList().getBuffer(filename);
2553 message(bformat(_("Opening child document %1$s..."),
2554 makeDisplayPath(filename.absFilename())));
2555 child = loadDocument(filename, false);
2561 // Set the parent name of the child document.
2562 // This makes insertion of citations and references in the child work,
2563 // when the target is in the parent or another child document.
2564 child->setParent(&buffer);
2565 child->masterBuffer()->updateLabels();
2568 child->errors("Parse");
2572 bool GuiView::goToFileRow(string const & argument)
2576 istringstream is(argument);
2577 is >> file_name >> row;
2578 file_name = os::internal_path(file_name);
2580 string const abstmp = package().temp_dir().absFilename();
2581 string const realtmp = package().temp_dir().realPath();
2582 // We have to use os::path_prefix_is() here, instead of
2583 // simply prefixIs(), because the file name comes from
2584 // an external application and may need case adjustment.
2585 if (os::path_prefix_is(file_name, abstmp, os::CASE_ADJUSTED)
2586 || os::path_prefix_is(file_name, realtmp, os::CASE_ADJUSTED)) {
2587 // Needed by inverse dvi search. If it is a file
2588 // in tmpdir, call the apropriated function.
2589 // If tmpdir is a symlink, we may have the real
2590 // path passed back, so we correct for that.
2591 if (!prefixIs(file_name, abstmp))
2592 file_name = subst(file_name, realtmp, abstmp);
2593 buf = theBufferList().getBufferFromTmp(file_name);
2595 // Must replace extension of the file to be .lyx
2596 // and get full path
2597 FileName const s = fileSearch(string(),
2598 support::changeExtension(file_name, ".lyx"), "lyx");
2599 // Either change buffer or load the file
2600 if (theBufferList().exists(s))
2601 buf = theBufferList().getBuffer(s);
2602 else if (s.exists()) {
2603 buf = loadDocument(s);
2604 buf->updateLabels();
2605 buf->errors("Parse");
2608 _("File does not exist: %1$s"),
2609 makeDisplayPath(file_name)));
2614 documentBufferView()->setCursorFromRow(row);
2619 static docstring exportAndDestroy(Buffer * buffer, std::string const & format)
2621 bool const success = buffer->doExport(format, true);
2624 ? bformat(_("Successful export to format: %1$s"), from_utf8(format))
2625 : bformat(_("Error exporting to format: %1$s"), from_utf8(format));
2629 static docstring previewAndDestroy(Buffer * buffer, std::string const & format)
2631 bool const success = buffer->preview(format);
2634 ? bformat(_("Successful preview of format: %1$s"), from_utf8(format))
2635 : bformat(_("Error previewing format: %1$s"), from_utf8(format));
2639 bool GuiView::dispatch(FuncRequest const & cmd)
2641 BufferView * bv = currentBufferView();
2642 // By default we won't need any update.
2644 bv->cursor().updateFlags(Update::None);
2646 Buffer * doc_buffer = documentBufferView()
2647 ? &(documentBufferView()->buffer()) : 0;
2649 bool dispatched = true;
2651 if (cmd.origin == FuncRequest::TOC) {
2652 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
2653 toc->doDispatch(bv->cursor(), cmd);
2657 string const argument = to_utf8(cmd.argument());
2659 switch(cmd.action) {
2660 case LFUN_BUFFER_CHILD_OPEN:
2661 openChildDocument(to_utf8(cmd.argument()));
2664 case LFUN_BUFFER_IMPORT:
2665 importDocument(to_utf8(cmd.argument()));
2668 case LFUN_BUFFER_EXPORT: {
2671 if (cmd.argument() == "custom") {
2672 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "sendto"));
2675 if (doc_buffer->doExport(argument, false)) {
2676 message(bformat(_("Error exporting to format: %1$s."),
2682 case LFUN_BUFFER_UPDATE: {
2685 string format = argument;
2686 if (argument.empty())
2687 format = doc_buffer->getDefaultOutputFormat();
2688 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
2689 QFuture<docstring> f = QtConcurrent::run(exportAndDestroy,
2690 doc_buffer->clone(), format);
2691 d.setPreviewFuture(f);
2693 doc_buffer->doExport(format, true);
2697 case LFUN_BUFFER_VIEW: {
2700 string format = argument;
2701 if (argument.empty())
2702 format = doc_buffer->getDefaultOutputFormat();
2703 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
2704 QFuture<docstring> f = QtConcurrent::run(previewAndDestroy,
2705 doc_buffer->clone(), format);
2706 d.setPreviewFuture(f);
2708 doc_buffer->preview(format);
2712 case LFUN_MASTER_BUFFER_UPDATE: {
2715 string format = argument;
2716 Buffer const * master = doc_buffer->masterBuffer();
2717 if (argument.empty())
2718 format = master->getDefaultOutputFormat();
2719 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
2720 QFuture<docstring> f = QtConcurrent::run(exportAndDestroy,
2721 master->clone(), format);
2722 d.setPreviewFuture(f);
2724 master->doExport(format, true);
2728 case LFUN_MASTER_BUFFER_VIEW: {
2729 string format = argument;
2730 Buffer const * master = doc_buffer->masterBuffer();
2731 if (argument.empty())
2732 format = master->getDefaultOutputFormat();
2733 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
2734 QFuture<docstring> f = QtConcurrent::run(previewAndDestroy,
2735 master->clone(), format);
2736 d.setPreviewFuture(f);
2738 master->preview(format);
2742 case LFUN_BUFFER_SWITCH:
2743 if (FileName::isAbsolute(to_utf8(cmd.argument()))) {
2745 theBufferList().getBuffer(FileName(to_utf8(cmd.argument())));
2749 message(_("Document not loaded"));
2753 case LFUN_BUFFER_NEXT:
2754 gotoNextOrPreviousBuffer(NEXTBUFFER);
2757 case LFUN_BUFFER_PREVIOUS:
2758 gotoNextOrPreviousBuffer(PREVBUFFER);
2761 case LFUN_COMMAND_EXECUTE: {
2762 bool const show_it = cmd.argument() != "off";
2763 // FIXME: this is a hack, "minibuffer" should not be
2765 if (GuiToolbar * t = toolbar("minibuffer")) {
2766 t->setVisible(show_it);
2767 if (show_it && t->commandBuffer())
2768 t->commandBuffer()->setFocus();
2772 case LFUN_DROP_LAYOUTS_CHOICE:
2773 d.layout_->showPopup();
2776 case LFUN_MENU_OPEN:
2777 if (QMenu * menu = guiApp->menus().menu(toqstr(cmd.argument()), *this))
2778 menu->exec(QCursor::pos());
2781 case LFUN_FILE_INSERT:
2782 insertLyXFile(cmd.argument());
2784 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
2785 insertPlaintextFile(cmd.argument(), true);
2788 case LFUN_FILE_INSERT_PLAINTEXT:
2789 insertPlaintextFile(cmd.argument(), false);
2792 case LFUN_BUFFER_RELOAD: {
2793 LASSERT(doc_buffer, break);
2794 docstring const file = makeDisplayPath(doc_buffer->absFileName(), 20);
2795 docstring text = bformat(_("Any changes will be lost. Are you sure "
2796 "you want to revert to the saved version of the document %1$s?"), file);
2797 int const ret = Alert::prompt(_("Revert to saved document?"),
2798 text, 1, 1, _("&Revert"), _("&Cancel"));
2801 doc_buffer->markClean();
2807 case LFUN_BUFFER_WRITE:
2808 LASSERT(doc_buffer, break);
2809 saveBuffer(*doc_buffer);
2812 case LFUN_BUFFER_WRITE_AS:
2813 LASSERT(doc_buffer, break);
2814 renameBuffer(*doc_buffer, cmd.argument());
2817 case LFUN_BUFFER_WRITE_ALL: {
2818 Buffer * first = theBufferList().first();
2821 message(_("Saving all documents..."));
2822 // We cannot use a for loop as the buffer list cycles.
2825 if (!b->isClean()) {
2827 LYXERR(Debug::ACTION, "Saved " << b->absFileName());
2829 b = theBufferList().next(b);
2830 } while (b != first);
2831 message(_("All documents saved."));
2835 case LFUN_BUFFER_CLOSE:
2839 case LFUN_BUFFER_CLOSE_ALL:
2843 case LFUN_TOOLBAR_TOGGLE: {
2844 string const name = cmd.getArg(0);
2845 if (GuiToolbar * t = toolbar(name))
2850 case LFUN_DIALOG_UPDATE: {
2851 string const name = to_utf8(cmd.argument());
2852 if (currentBufferView()) {
2853 Inset * inset = currentBufferView()->editedInset(name);
2854 // Can only update a dialog connected to an existing inset
2857 // FIXME: get rid of this indirection; GuiView ask the inset
2858 // if he is kind enough to update itself...
2859 FuncRequest fr(LFUN_INSET_DIALOG_UPDATE, cmd.argument());
2860 inset->dispatch(currentBufferView()->cursor(), fr);
2861 } else if (name == "paragraph") {
2862 lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
2863 } else if (name == "prefs" || name == "document") {
2864 updateDialog(name, string());
2869 case LFUN_DIALOG_TOGGLE: {
2870 if (isDialogVisible(cmd.getArg(0)))
2871 dispatch(FuncRequest(LFUN_DIALOG_HIDE, cmd.argument()));
2873 dispatch(FuncRequest(LFUN_DIALOG_SHOW, cmd.argument()));
2877 case LFUN_DIALOG_DISCONNECT_INSET:
2878 disconnectDialog(to_utf8(cmd.argument()));
2881 case LFUN_DIALOG_HIDE: {
2882 guiApp->hideDialogs(to_utf8(cmd.argument()), 0);
2886 case LFUN_DIALOG_SHOW: {
2887 string const name = cmd.getArg(0);
2888 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
2890 if (name == "character") {
2891 data = freefont2string();
2893 showDialog("character", data);
2894 } else if (name == "latexlog") {
2895 Buffer::LogType type;
2896 string const logfile = doc_buffer->logName(&type);
2898 case Buffer::latexlog:
2901 case Buffer::buildlog:
2905 data += Lexer::quoteString(logfile);
2906 showDialog("log", data);
2907 } else if (name == "vclog") {
2908 string const data = "vc " +
2909 Lexer::quoteString(doc_buffer->lyxvc().getLogFile());
2910 showDialog("log", data);
2911 } else if (name == "symbols") {
2912 data = bv->cursor().getEncoding()->name();
2914 showDialog("symbols", data);
2916 } else if (name == "prefs" && isFullScreen()) {
2917 FuncRequest fr(LFUN_INSET_INSERT, "fullscreen");
2919 showDialog("prefs", data);
2921 showDialog(name, data);
2926 message(cmd.argument());
2929 case LFUN_UI_TOGGLE:
2931 // Make sure the keyboard focus stays in the work area.
2935 case LFUN_SPLIT_VIEW: {
2936 LASSERT(doc_buffer, break);
2937 string const orientation = cmd.getArg(0);
2938 d.splitter_->setOrientation(orientation == "vertical"
2939 ? Qt::Vertical : Qt::Horizontal);
2940 TabWorkArea * twa = addTabWorkArea();
2941 GuiWorkArea * wa = twa->addWorkArea(*doc_buffer, *this);
2942 setCurrentWorkArea(wa);
2945 case LFUN_CLOSE_TAB_GROUP:
2946 if (TabWorkArea * twa = d.currentTabWorkArea()) {
2947 closeTabWorkArea(twa);
2948 d.current_work_area_ = 0;
2949 twa = d.currentTabWorkArea();
2950 // Switch to the next GuiWorkArea in the found TabWorkArea.
2952 // Make sure the work area is up to date.
2953 setCurrentWorkArea(twa->currentWorkArea());
2955 setCurrentWorkArea(0);
2960 case LFUN_COMPLETION_INLINE:
2961 if (d.current_work_area_)
2962 d.current_work_area_->completer().showInline();
2965 case LFUN_COMPLETION_POPUP:
2966 if (d.current_work_area_)
2967 d.current_work_area_->completer().showPopup();
2971 case LFUN_COMPLETION_COMPLETE:
2972 if (d.current_work_area_)
2973 d.current_work_area_->completer().tab();
2976 case LFUN_COMPLETION_CANCEL:
2977 if (d.current_work_area_) {
2978 if (d.current_work_area_->completer().popupVisible())
2979 d.current_work_area_->completer().hidePopup();
2981 d.current_work_area_->completer().hideInline();
2985 case LFUN_COMPLETION_ACCEPT:
2986 if (d.current_work_area_)
2987 d.current_work_area_->completer().activate();
2990 case LFUN_BUFFER_ZOOM_IN:
2991 case LFUN_BUFFER_ZOOM_OUT:
2992 if (cmd.argument().empty()) {
2993 if (cmd.action == LFUN_BUFFER_ZOOM_IN)
2998 lyxrc.zoom += convert<int>(cmd.argument());
3000 if (lyxrc.zoom < 10)
3003 // The global QPixmapCache is used in GuiPainter to cache text
3004 // painting so we must reset it.
3005 QPixmapCache::clear();
3006 guiApp->fontLoader().update();
3007 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
3010 case LFUN_VC_REGISTER:
3011 case LFUN_VC_CHECK_IN:
3012 case LFUN_VC_CHECK_OUT:
3013 case LFUN_VC_REPO_UPDATE:
3014 case LFUN_VC_LOCKING_TOGGLE:
3015 case LFUN_VC_REVERT:
3016 case LFUN_VC_UNDO_LAST:
3017 case LFUN_VC_COMMAND:
3021 case LFUN_SERVER_GOTO_FILE_ROW:
3022 goToFileRow(to_utf8(cmd.argument()));
3030 // Part of automatic menu appearance feature.
3031 if (isFullScreen()) {
3032 if (menuBar()->isVisible() && lyxrc.full_screen_menubar)
3034 if (statusBar()->isVisible())
3035 statusBar()->hide();
3042 void GuiView::lfunUiToggle(FuncRequest const & cmd)
3044 string const arg = cmd.getArg(0);
3045 if (arg == "scrollbar") {
3046 // hide() is of no help
3047 if (d.current_work_area_->verticalScrollBarPolicy() ==
3048 Qt::ScrollBarAlwaysOff)
3050 d.current_work_area_->setVerticalScrollBarPolicy(
3051 Qt::ScrollBarAsNeeded);
3053 d.current_work_area_->setVerticalScrollBarPolicy(
3054 Qt::ScrollBarAlwaysOff);
3057 if (arg == "statusbar") {
3058 statusBar()->setVisible(!statusBar()->isVisible());
3061 if (arg == "menubar") {
3062 menuBar()->setVisible(!menuBar()->isVisible());
3065 #if QT_VERSION >= 0x040300
3066 if (arg == "frame") {
3068 getContentsMargins(&l, &t, &r, &b);
3069 //are the frames in default state?
3070 d.current_work_area_->setFrameStyle(QFrame::NoFrame);
3072 setContentsMargins(-2, -2, -2, -2);
3074 setContentsMargins(0, 0, 0, 0);
3079 if (arg == "fullscreen") {
3084 message(bformat("LFUN_UI_TOGGLE " + _("%1$s unknown command!"), from_utf8(arg)));
3088 void GuiView::toggleFullScreen()
3090 if (isFullScreen()) {
3091 for (int i = 0; i != d.splitter_->count(); ++i)
3092 d.tabWorkArea(i)->setFullScreen(false);
3093 #if QT_VERSION >= 0x040300
3094 setContentsMargins(0, 0, 0, 0);
3096 setWindowState(windowState() ^ Qt::WindowFullScreen);
3099 statusBar()->show();
3102 hideDialogs("prefs", 0);
3103 for (int i = 0; i != d.splitter_->count(); ++i)
3104 d.tabWorkArea(i)->setFullScreen(true);
3105 #if QT_VERSION >= 0x040300
3106 setContentsMargins(-2, -2, -2, -2);
3109 setWindowState(windowState() ^ Qt::WindowFullScreen);
3110 statusBar()->hide();
3111 if (lyxrc.full_screen_menubar)
3113 if (lyxrc.full_screen_toolbars) {
3114 ToolbarMap::iterator end = d.toolbars_.end();
3115 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
3120 // give dialogs like the TOC a chance to adapt
3125 Buffer const * GuiView::updateInset(Inset const * inset)
3127 if (!d.current_work_area_)
3131 d.current_work_area_->scheduleRedraw();
3133 return &d.current_work_area_->bufferView().buffer();
3137 void GuiView::restartCursor()
3139 /* When we move around, or type, it's nice to be able to see
3140 * the cursor immediately after the keypress.
3142 if (d.current_work_area_)
3143 d.current_work_area_->startBlinkingCursor();
3145 // Take this occasion to update the other GUI elements.
3151 void GuiView::updateCompletion(Cursor & cur, bool start, bool keep)
3153 if (d.current_work_area_)
3154 d.current_work_area_->completer().updateVisibility(cur, start, keep);
3159 // This list should be kept in sync with the list of insets in
3160 // src/insets/Inset.cpp. I.e., if a dialog goes with an inset, the
3161 // dialog should have the same name as the inset.
3162 // Changes should be also recorded in LFUN_DIALOG_SHOW doxygen
3163 // docs in LyXAction.cpp.
3165 char const * const dialognames[] = {
3166 "aboutlyx", "bibitem", "bibtex", "box", "branch", "changes", "character",
3167 "citation", "compare", "document", "errorlist", "ert", "external", "file",
3168 "findreplace", "findreplaceadv", "float", "graphics", "href", "include",
3169 "index", "index_print", "info", "listings", "label", "log", "mathdelimiter",
3170 "mathmatrix", "mathspace", "nomenclature", "nomencl_print", "note",
3171 "paragraph", "phantom", "prefs", "print", "ref", "sendto", "space",
3172 "spellchecker", "symbols", "tabular", "tabularcreate", "thesaurus", "texinfo",
3173 "toc", "view-source", "vspace", "wrap" };
3175 char const * const * const end_dialognames =
3176 dialognames + (sizeof(dialognames) / sizeof(char *));
3180 cmpCStr(char const * name) : name_(name) {}
3181 bool operator()(char const * other) {
3182 return strcmp(other, name_) == 0;
3189 bool isValidName(string const & name)
3191 return find_if(dialognames, end_dialognames,
3192 cmpCStr(name.c_str())) != end_dialognames;
3198 void GuiView::resetDialogs()
3200 // Make sure that no LFUN uses any LyXView.
3201 guiApp->setCurrentView(0);
3204 constructToolbars();
3205 guiApp->menus().fillMenuBar(menuBar(), this, false);
3206 d.layout_->updateContents(true);
3207 // Now update controls with current buffer.
3208 guiApp->setCurrentView(this);
3214 Dialog * GuiView::findOrBuild(string const & name, bool hide_it)
3216 if (!isValidName(name))
3219 map<string, DialogPtr>::iterator it = d.dialogs_.find(name);
3221 if (it != d.dialogs_.end()) {
3223 it->second->hideView();
3224 return it->second.get();
3227 Dialog * dialog = build(name);
3228 d.dialogs_[name].reset(dialog);
3229 if (lyxrc.allow_geometry_session)
3230 dialog->restoreSession();
3237 void GuiView::showDialog(string const & name, string const & data,
3245 Dialog * dialog = findOrBuild(name, false);
3247 dialog->showData(data);
3248 if (inset && currentBufferView())
3249 currentBufferView()->editInset(name, inset);
3252 catch (ExceptionMessage const & ex) {
3260 bool GuiView::isDialogVisible(string const & name) const
3262 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3263 if (it == d.dialogs_.end())
3265 return it->second.get()->isVisibleView() && !it->second.get()->isClosing();
3269 void GuiView::hideDialog(string const & name, Inset * inset)
3271 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3272 if (it == d.dialogs_.end())
3275 if (inset && currentBufferView()
3276 && inset != currentBufferView()->editedInset(name))
3279 Dialog * const dialog = it->second.get();
3280 if (dialog->isVisibleView())
3282 if (currentBufferView())
3283 currentBufferView()->editInset(name, 0);
3287 void GuiView::disconnectDialog(string const & name)
3289 if (!isValidName(name))
3291 if (currentBufferView())
3292 currentBufferView()->editInset(name, 0);
3296 void GuiView::hideAll() const
3298 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
3299 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3301 for(; it != end; ++it)
3302 it->second->hideView();
3306 void GuiView::updateDialogs()
3308 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
3309 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3311 for(; it != end; ++it) {
3312 Dialog * dialog = it->second.get();
3313 if (dialog && dialog->isVisibleView())
3314 dialog->checkStatus();
3321 // will be replaced by a proper factory...
3322 Dialog * createGuiAbout(GuiView & lv);
3323 Dialog * createGuiBibitem(GuiView & lv);
3324 Dialog * createGuiBibtex(GuiView & lv);
3325 Dialog * createGuiBox(GuiView & lv);
3326 Dialog * createGuiBranch(GuiView & lv);
3327 Dialog * createGuiChanges(GuiView & lv);
3328 Dialog * createGuiCharacter(GuiView & lv);
3329 Dialog * createGuiCitation(GuiView & lv);
3330 Dialog * createGuiCompare(GuiView & lv);
3331 Dialog * createGuiDelimiter(GuiView & lv);
3332 Dialog * createGuiDocument(GuiView & lv);
3333 Dialog * createGuiErrorList(GuiView & lv);
3334 Dialog * createGuiERT(GuiView & lv);
3335 Dialog * createGuiExternal(GuiView & lv);
3336 Dialog * createGuiFloat(GuiView & lv);
3337 Dialog * createGuiGraphics(GuiView & lv);
3338 Dialog * createGuiInclude(GuiView & lv);
3339 Dialog * createGuiIndex(GuiView & lv);
3340 Dialog * createGuiInfo(GuiView & lv);
3341 Dialog * createGuiLabel(GuiView & lv);
3342 Dialog * createGuiListings(GuiView & lv);
3343 Dialog * createGuiLog(GuiView & lv);
3344 Dialog * createGuiMathHSpace(GuiView & lv);
3345 Dialog * createGuiMathMatrix(GuiView & lv);
3346 Dialog * createGuiNomenclature(GuiView & lv);
3347 Dialog * createGuiNote(GuiView & lv);
3348 Dialog * createGuiParagraph(GuiView & lv);
3349 Dialog * createGuiPhantom(GuiView & lv);
3350 Dialog * createGuiPreferences(GuiView & lv);
3351 Dialog * createGuiPrint(GuiView & lv);
3352 Dialog * createGuiPrintindex(GuiView & lv);
3353 Dialog * createGuiPrintNomencl(GuiView & lv);
3354 Dialog * createGuiRef(GuiView & lv);
3355 Dialog * createGuiSearch(GuiView & lv);
3356 Dialog * createGuiSearchAdv(GuiView & lv);
3357 Dialog * createGuiSendTo(GuiView & lv);
3358 Dialog * createGuiShowFile(GuiView & lv);
3359 Dialog * createGuiSpellchecker(GuiView & lv);
3360 Dialog * createGuiSymbols(GuiView & lv);
3361 Dialog * createGuiTabularCreate(GuiView & lv);
3362 Dialog * createGuiTabular(GuiView & lv);
3363 Dialog * createGuiTexInfo(GuiView & lv);
3364 Dialog * createGuiTextHSpace(GuiView & lv);
3365 Dialog * createGuiToc(GuiView & lv);
3366 Dialog * createGuiThesaurus(GuiView & lv);
3367 Dialog * createGuiHyperlink(GuiView & lv);
3368 Dialog * createGuiVSpace(GuiView & lv);
3369 Dialog * createGuiViewSource(GuiView & lv);
3370 Dialog * createGuiWrap(GuiView & lv);
3373 Dialog * GuiView::build(string const & name)
3375 LASSERT(isValidName(name), return 0);
3377 if (name == "aboutlyx")
3378 return createGuiAbout(*this);
3379 if (name == "bibitem")
3380 return createGuiBibitem(*this);
3381 if (name == "bibtex")
3382 return createGuiBibtex(*this);
3384 return createGuiBox(*this);
3385 if (name == "branch")
3386 return createGuiBranch(*this);
3387 if (name == "changes")
3388 return createGuiChanges(*this);
3389 if (name == "character")
3390 return createGuiCharacter(*this);
3391 if (name == "citation")
3392 return createGuiCitation(*this);
3393 if (name == "compare")
3394 return createGuiCompare(*this);
3395 if (name == "document")
3396 return createGuiDocument(*this);
3397 if (name == "errorlist")
3398 return createGuiErrorList(*this);
3400 return createGuiERT(*this);
3401 if (name == "external")
3402 return createGuiExternal(*this);
3404 return createGuiShowFile(*this);
3405 if (name == "findreplace")
3406 return createGuiSearch(*this);
3407 if (name == "findreplaceadv")
3408 return createGuiSearchAdv(*this);
3409 if (name == "float")
3410 return createGuiFloat(*this);
3411 if (name == "graphics")
3412 return createGuiGraphics(*this);
3414 return createGuiHyperlink(*this);
3415 if (name == "include")
3416 return createGuiInclude(*this);
3417 if (name == "index")
3418 return createGuiIndex(*this);
3419 if (name == "index_print")
3420 return createGuiPrintindex(*this);
3422 return createGuiInfo(*this);
3423 if (name == "label")
3424 return createGuiLabel(*this);
3425 if (name == "listings")
3426 return createGuiListings(*this);
3428 return createGuiLog(*this);
3429 if (name == "mathdelimiter")
3430 return createGuiDelimiter(*this);
3431 if (name == "mathspace")
3432 return createGuiMathHSpace(*this);
3433 if (name == "mathmatrix")
3434 return createGuiMathMatrix(*this);
3435 if (name == "nomenclature")
3436 return createGuiNomenclature(*this);
3437 if (name == "nomencl_print")
3438 return createGuiPrintNomencl(*this);
3440 return createGuiNote(*this);
3441 if (name == "paragraph")
3442 return createGuiParagraph(*this);
3443 if (name == "phantom")
3444 return createGuiPhantom(*this);
3445 if (name == "prefs")
3446 return createGuiPreferences(*this);
3447 if (name == "print")
3448 return createGuiPrint(*this);
3450 return createGuiRef(*this);
3451 if (name == "sendto")
3452 return createGuiSendTo(*this);
3453 if (name == "space")
3454 return createGuiTextHSpace(*this);
3455 if (name == "spellchecker")
3456 return createGuiSpellchecker(*this);
3457 if (name == "symbols")
3458 return createGuiSymbols(*this);
3459 if (name == "tabular")
3460 return createGuiTabular(*this);
3461 if (name == "tabularcreate")
3462 return createGuiTabularCreate(*this);
3463 if (name == "texinfo")
3464 return createGuiTexInfo(*this);
3465 if (name == "thesaurus")
3466 return createGuiThesaurus(*this);
3468 return createGuiToc(*this);
3469 if (name == "view-source")
3470 return createGuiViewSource(*this);
3471 if (name == "vspace")
3472 return createGuiVSpace(*this);
3474 return createGuiWrap(*this);
3480 } // namespace frontend
3483 #include "moc_GuiView.cpp"