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"
79 #include "support/ProgressInterface.h"
82 #include <QApplication>
83 #include <QCloseEvent>
85 #include <QDesktopWidget>
86 #include <QDragEnterEvent>
93 #include <QPixmapCache>
95 #include <QPushButton>
99 #include <QStackedWidget>
100 #include <QStatusBar>
104 #include <QScrollBar>
106 #define EXPORT_in_THREAD 1
108 // QtConcurrent was introduced in Qt 4.4
109 #if (QT_VERSION >= 0x040400)
111 #include <QFutureWatcher>
112 #include <QtConcurrentRun>
115 #include <boost/bind.hpp>
119 #ifdef HAVE_SYS_TIME_H
120 # include <sys/time.h>
127 using namespace lyx::support;
134 class BackgroundWidget : public QWidget
139 LYXERR(Debug::GUI, "show banner: " << lyxrc.show_banner);
140 /// The text to be written on top of the pixmap
141 QString const text = lyx_version ?
142 qt_("version ") + lyx_version : qt_("unknown version");
143 splash_ = getPixmap("images/", "banner", "png");
145 QPainter pain(&splash_);
146 pain.setPen(QColor(0, 0, 0));
148 // The font used to display the version info
149 font.setStyleHint(QFont::SansSerif);
150 font.setWeight(QFont::Bold);
151 font.setPointSize(int(toqstr(lyxrc.font_sizes[FONT_SIZE_LARGE]).toDouble()));
153 pain.drawText(260, 15, text);
156 void paintEvent(QPaintEvent *)
158 int x = (width() - splash_.width()) / 2;
159 int y = (height() - splash_.height()) / 2;
161 pain.drawPixmap(x, y, splash_);
169 /// Toolbar store providing access to individual toolbars by name.
170 typedef std::map<std::string, GuiToolbar *> ToolbarMap;
172 typedef boost::shared_ptr<Dialog> DialogPtr;
177 struct GuiView::GuiViewPrivate
179 GuiViewPrivate(GuiView * gv)
180 : gv_(gv), current_work_area_(0), current_main_work_area_(0),
181 layout_(0), autosave_timeout_(5000),
184 // hardcode here the platform specific icon size
185 smallIconSize = 14; // scaling problems
186 normalIconSize = 20; // ok, default
187 bigIconSize = 26; // better for some math icons
189 splitter_ = new QSplitter;
190 bg_widget_ = new BackgroundWidget;
191 stack_widget_ = new QStackedWidget;
192 stack_widget_->addWidget(bg_widget_);
193 stack_widget_->addWidget(splitter_);
201 delete stack_widget_;
204 QMenu * toolBarPopup(GuiView * parent)
206 // FIXME: translation
207 QMenu * menu = new QMenu(parent);
208 QActionGroup * iconSizeGroup = new QActionGroup(parent);
210 QAction * smallIcons = new QAction(iconSizeGroup);
211 smallIcons->setText(qt_("Small-sized icons"));
212 smallIcons->setCheckable(true);
213 QObject::connect(smallIcons, SIGNAL(triggered()),
214 parent, SLOT(smallSizedIcons()));
215 menu->addAction(smallIcons);
217 QAction * normalIcons = new QAction(iconSizeGroup);
218 normalIcons->setText(qt_("Normal-sized icons"));
219 normalIcons->setCheckable(true);
220 QObject::connect(normalIcons, SIGNAL(triggered()),
221 parent, SLOT(normalSizedIcons()));
222 menu->addAction(normalIcons);
224 QAction * bigIcons = new QAction(iconSizeGroup);
225 bigIcons->setText(qt_("Big-sized icons"));
226 bigIcons->setCheckable(true);
227 QObject::connect(bigIcons, SIGNAL(triggered()),
228 parent, SLOT(bigSizedIcons()));
229 menu->addAction(bigIcons);
231 unsigned int cur = parent->iconSize().width();
232 if ( cur == parent->d.smallIconSize)
233 smallIcons->setChecked(true);
234 else if (cur == parent->d.normalIconSize)
235 normalIcons->setChecked(true);
236 else if (cur == parent->d.bigIconSize)
237 bigIcons->setChecked(true);
244 stack_widget_->setCurrentWidget(bg_widget_);
245 bg_widget_->setUpdatesEnabled(true);
248 TabWorkArea * tabWorkArea(int i)
250 return dynamic_cast<TabWorkArea *>(splitter_->widget(i));
253 TabWorkArea * currentTabWorkArea()
255 if (splitter_->count() == 1)
256 // The first TabWorkArea is always the first one, if any.
257 return tabWorkArea(0);
259 for (int i = 0; i != splitter_->count(); ++i) {
260 TabWorkArea * twa = tabWorkArea(i);
261 if (current_main_work_area_ == twa->currentWorkArea())
265 // None has the focus so we just take the first one.
266 return tabWorkArea(0);
269 void setPreviewFuture(QFuture<docstring> const & f)
271 preview_watcher_.setFuture(f);
272 connect(&preview_watcher_, SIGNAL(finished()), gv_,
273 SLOT(threadFinished()));
278 GuiWorkArea * current_work_area_;
279 GuiWorkArea * current_main_work_area_;
280 QSplitter * splitter_;
281 QStackedWidget * stack_widget_;
282 BackgroundWidget * bg_widget_;
284 ToolbarMap toolbars_;
285 /// The main layout box.
287 * \warning Don't Delete! The layout box is actually owned by
288 * whichever toolbar contains it. All the GuiView class needs is a
289 * means of accessing it.
291 * FIXME: replace that with a proper model so that we are not limited
292 * to only one dialog.
297 map<string, DialogPtr> dialogs_;
299 unsigned int smallIconSize;
300 unsigned int normalIconSize;
301 unsigned int bigIconSize;
303 QTimer statusbar_timer_;
304 /// auto-saving of buffers
305 Timeout autosave_timeout_;
306 /// flag against a race condition due to multiclicks, see bug #1119
310 TocModels toc_models_;
312 #if (QT_VERSION >= 0x040400)
314 QFutureWatcher<docstring> autosave_watcher_;
315 QFutureWatcher<docstring> preview_watcher_;
320 GuiView::GuiView(int id)
321 : d(*new GuiViewPrivate(this)), id_(id), closing_(false)
323 // GuiToolbars *must* be initialised before the menu bar.
324 normalSizedIcons(); // at least on Mac the default is 32 otherwise, which is huge
327 // set ourself as the current view. This is needed for the menu bar
328 // filling, at least for the static special menu item on Mac. Otherwise
329 // they are greyed out.
330 guiApp->setCurrentView(this);
332 // Fill up the menu bar.
333 guiApp->menus().fillMenuBar(menuBar(), this, true);
335 setCentralWidget(d.stack_widget_);
337 // Start autosave timer
338 if (lyxrc.autosave) {
339 d.autosave_timeout_.timeout.connect(boost::bind(&GuiView::autoSave, this));
340 d.autosave_timeout_.setTimeout(lyxrc.autosave * 1000);
341 d.autosave_timeout_.start();
343 connect(&d.statusbar_timer_, SIGNAL(timeout()),
344 this, SLOT(clearMessage()));
346 // We don't want to keep the window in memory if it is closed.
347 setAttribute(Qt::WA_DeleteOnClose, true);
349 #if (!defined(Q_WS_WIN) && !defined(Q_WS_MACX))
350 // assign an icon to main form. We do not do it under Qt/Win or Qt/Mac,
351 // since the icon is provided in the application bundle.
352 setWindowIcon(getPixmap("images/", "lyx", "png"));
356 setAcceptDrops(true);
358 statusBar()->setSizeGripEnabled(true);
360 // Forbid too small unresizable window because it can happen
361 // with some window manager under X11.
362 setMinimumSize(300, 200);
364 if (lyxrc.allow_geometry_session) {
365 // Now take care of session management.
370 // no session handling, default to a sane size.
371 setGeometry(50, 50, 690, 510);
374 // clear session data if any.
376 settings.remove("views");
378 #if (QT_VERSION >= 0x040400)
379 connect(&d.autosave_watcher_, SIGNAL(finished()), this,
380 SLOT(threadFinished()));
391 void GuiView::threadFinished()
393 #if (QT_VERSION >= 0x040400)
394 QFutureWatcher<docstring> const * watcher =
395 static_cast<QFutureWatcher<docstring> const *>(sender());
396 message(watcher->result());
401 void GuiView::saveLayout() const
404 settings.beginGroup("views");
405 settings.beginGroup(QString::number(id_));
407 settings.setValue("pos", pos());
408 settings.setValue("size", size());
410 settings.setValue("geometry", saveGeometry());
412 settings.setValue("layout", saveState(0));
413 settings.setValue("icon_size", iconSize());
417 bool GuiView::restoreLayout()
420 settings.beginGroup("views");
421 settings.beginGroup(QString::number(id_));
422 QString const icon_key = "icon_size";
423 if (!settings.contains(icon_key))
426 //code below is skipped when when ~/.config/LyX is (re)created
427 setIconSize(settings.value(icon_key).toSize());
429 QPoint pos = settings.value("pos", QPoint(50, 50)).toPoint();
430 QSize size = settings.value("size", QSize(690, 510)).toSize();
434 // Work-around for bug #6034: the window ends up in an undetermined
435 // state when trying to restore a maximized window when it is
436 // already maximized.
437 if (!(windowState() & Qt::WindowMaximized))
438 if (!restoreGeometry(settings.value("geometry").toByteArray()))
439 setGeometry(50, 50, 690, 510);
441 // Make sure layout is correctly oriented.
442 setLayoutDirection(qApp->layoutDirection());
444 // Allow the toc and view-source dock widget to be restored if needed.
446 if ((dialog = findOrBuild("toc", true)))
447 // see bug 5082. At least setup title and enabled state.
448 // Visibility will be adjusted by restoreState below.
449 dialog->prepareView();
450 if ((dialog = findOrBuild("view-source", true)))
451 dialog->prepareView();
453 if (!restoreState(settings.value("layout").toByteArray(), 0))
460 GuiToolbar * GuiView::toolbar(string const & name)
462 ToolbarMap::iterator it = d.toolbars_.find(name);
463 if (it != d.toolbars_.end())
466 LYXERR(Debug::GUI, "Toolbar::display: no toolbar named " << name);
467 message(bformat(_("Unknown toolbar \"%1$s\""), from_utf8(name)));
472 void GuiView::constructToolbars()
474 ToolbarMap::iterator it = d.toolbars_.begin();
475 for (; it != d.toolbars_.end(); ++it)
479 // I don't like doing this here, but the standard toolbar
480 // destroys this object when it's destroyed itself (vfr)
481 d.layout_ = new LayoutBox(*this);
482 d.stack_widget_->addWidget(d.layout_);
483 d.layout_->move(0,0);
485 // extracts the toolbars from the backend
486 Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
487 Toolbars::Infos::iterator end = guiApp->toolbars().end();
488 for (; cit != end; ++cit)
489 d.toolbars_[cit->name] = new GuiToolbar(*cit, *this);
493 void GuiView::initToolbars()
495 // extracts the toolbars from the backend
496 Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
497 Toolbars::Infos::iterator end = guiApp->toolbars().end();
498 for (; cit != end; ++cit) {
499 GuiToolbar * tb = toolbar(cit->name);
502 int const visibility = guiApp->toolbars().defaultVisibility(cit->name);
504 tb->setVisible(false);
505 tb->setVisibility(visibility);
507 if (visibility & Toolbars::TOP) {
509 addToolBarBreak(Qt::TopToolBarArea);
510 addToolBar(Qt::TopToolBarArea, tb);
513 if (visibility & Toolbars::BOTTOM) {
514 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
515 #if (QT_VERSION >= 0x040202)
516 addToolBarBreak(Qt::BottomToolBarArea);
518 addToolBar(Qt::BottomToolBarArea, tb);
521 if (visibility & Toolbars::LEFT) {
522 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
523 #if (QT_VERSION >= 0x040202)
524 addToolBarBreak(Qt::LeftToolBarArea);
526 addToolBar(Qt::LeftToolBarArea, tb);
529 if (visibility & Toolbars::RIGHT) {
530 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
531 #if (QT_VERSION >= 0x040202)
532 addToolBarBreak(Qt::RightToolBarArea);
534 addToolBar(Qt::RightToolBarArea, tb);
537 if (visibility & Toolbars::ON)
538 tb->setVisible(true);
543 TocModels & GuiView::tocModels()
545 return d.toc_models_;
549 void GuiView::setFocus()
551 LYXERR(Debug::DEBUG, "GuiView::setFocus()" << this);
552 // Make sure LyXFunc points to the correct view.
553 guiApp->setCurrentView(this);
554 QMainWindow::setFocus();
555 if (d.current_work_area_)
556 d.current_work_area_->setFocus();
560 QMenu * GuiView::createPopupMenu()
562 return d.toolBarPopup(this);
566 void GuiView::showEvent(QShowEvent * e)
568 LYXERR(Debug::GUI, "Passed Geometry "
569 << size().height() << "x" << size().width()
570 << "+" << pos().x() << "+" << pos().y());
572 if (d.splitter_->count() == 0)
573 // No work area, switch to the background widget.
576 QMainWindow::showEvent(e);
580 /** Destroy only all tabbed WorkAreas. Destruction of other WorkAreas
581 ** is responsibility of the container (e.g., dialog)
583 void GuiView::closeEvent(QCloseEvent * close_event)
585 LYXERR(Debug::DEBUG, "GuiView::closeEvent()");
590 // it can happen that this event arrives without selecting the view,
591 // e.g. when clicking the close button on a background window.
593 if (!closeWorkAreaAll()) {
595 close_event->ignore();
599 // Make sure that nothing will use this to be closed View.
600 guiApp->unregisterView(this);
602 if (isFullScreen()) {
603 // Switch off fullscreen before closing.
608 // Make sure the timer time out will not trigger a statusbar update.
609 d.statusbar_timer_.stop();
611 // Saving fullscreen requires additional tweaks in the toolbar code.
612 // It wouldn't also work under linux natively.
613 if (lyxrc.allow_geometry_session) {
614 // Save this window geometry and layout.
616 // Then the toolbar private states.
617 ToolbarMap::iterator end = d.toolbars_.end();
618 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
619 it->second->saveSession();
620 // Now take care of all other dialogs:
621 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
622 for (; it!= d.dialogs_.end(); ++it)
623 it->second->saveSession();
626 close_event->accept();
630 void GuiView::dragEnterEvent(QDragEnterEvent * event)
632 if (event->mimeData()->hasUrls())
634 /// \todo Ask lyx-devel is this is enough:
635 /// if (event->mimeData()->hasFormat("text/plain"))
636 /// event->acceptProposedAction();
640 void GuiView::dropEvent(QDropEvent * event)
642 QList<QUrl> files = event->mimeData()->urls();
646 LYXERR(Debug::GUI, "GuiView::dropEvent: got URLs!");
647 for (int i = 0; i != files.size(); ++i) {
648 string const file = os::internal_path(fromqstr(
649 files.at(i).toLocalFile()));
653 string const ext = support::getExtension(file);
654 vector<const Format *> found_formats;
656 // Find all formats that have the correct extension.
657 vector<const Format *> const & import_formats
658 = theConverters().importableFormats();
659 vector<const Format *>::const_iterator it = import_formats.begin();
660 for (; it != import_formats.end(); ++it)
661 if ((*it)->extension() == ext)
662 found_formats.push_back(*it);
665 if (found_formats.size() >= 1) {
666 if (found_formats.size() > 1) {
667 //FIXME: show a dialog to choose the correct importable format
669 "Multiple importable formats found, selecting first");
671 string const arg = found_formats[0]->name() + " " + file;
672 cmd = FuncRequest(LFUN_BUFFER_IMPORT, arg);
675 //FIXME: do we have to explicitly check whether it's a lyx file?
677 "No formats found, trying to open it as a lyx file");
678 cmd = FuncRequest(LFUN_FILE_OPEN, file);
681 // Asynchronously post the event. DropEvent usually come
682 // from the BufferView. But reloading a file might close
683 // the BufferView from within its own event handler.
684 guiApp->dispatchDelayed(cmd);
690 void GuiView::message(docstring const & str)
692 if (ForkedProcess::iAmAChild())
695 statusBar()->showMessage(toqstr(str));
696 d.statusbar_timer_.stop();
697 d.statusbar_timer_.start(3000);
701 void GuiView::smallSizedIcons()
703 setIconSize(QSize(d.smallIconSize, d.smallIconSize));
707 void GuiView::normalSizedIcons()
709 setIconSize(QSize(d.normalIconSize, d.normalIconSize));
713 void GuiView::bigSizedIcons()
715 setIconSize(QSize(d.bigIconSize, d.bigIconSize));
719 void GuiView::clearMessage()
724 d.statusbar_timer_.stop();
728 void GuiView::updateWindowTitle(GuiWorkArea * wa)
730 if (wa != d.current_work_area_)
732 setWindowTitle(qt_("LyX: ") + wa->windowTitle());
733 setWindowIconText(wa->windowIconText());
737 void GuiView::on_currentWorkAreaChanged(GuiWorkArea * wa)
740 disconnectBufferView();
741 connectBufferView(wa->bufferView());
742 connectBuffer(wa->bufferView().buffer());
743 d.current_work_area_ = wa;
744 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
745 this, SLOT(updateWindowTitle(GuiWorkArea *)));
746 updateWindowTitle(wa);
750 // The document settings needs to be reinitialised.
751 updateDialog("document", "");
753 // Buffer-dependent dialogs must be updated. This is done here because
754 // some dialogs require buffer()->text.
759 void GuiView::on_lastWorkAreaRemoved()
762 // We already are in a close event. Nothing more to do.
765 if (d.splitter_->count() > 1)
766 // We have a splitter so don't close anything.
769 // Reset and updates the dialogs.
770 d.toc_models_.reset(0);
771 updateDialog("document", "");
774 resetWindowTitleAndIconText();
776 if (lyxrc.open_buffers_in_tabs)
777 // Nothing more to do, the window should stay open.
780 if (guiApp->viewIds().size() > 1) {
786 // On Mac we also close the last window because the application stay
787 // resident in memory. On other platforms we don't close the last
788 // window because this would quit the application.
794 void GuiView::updateStatusBar()
796 // let the user see the explicit message
797 if (d.statusbar_timer_.isActive())
804 void GuiView::showMessage()
806 QString msg = toqstr(theGuiApp()->viewStatusMessage());
808 BufferView const * bv = currentBufferView();
810 msg = toqstr(bv->cursor().currentState());
812 msg = qt_("Welcome to LyX!");
814 statusBar()->showMessage(msg);
818 bool GuiView::event(QEvent * e)
822 // Useful debug code:
823 //case QEvent::ActivationChange:
824 //case QEvent::WindowDeactivate:
825 //case QEvent::Paint:
826 //case QEvent::Enter:
827 //case QEvent::Leave:
828 //case QEvent::HoverEnter:
829 //case QEvent::HoverLeave:
830 //case QEvent::HoverMove:
831 //case QEvent::StatusTip:
832 //case QEvent::DragEnter:
833 //case QEvent::DragLeave:
837 case QEvent::WindowActivate: {
838 GuiView * old_view = guiApp->currentView();
839 if (this == old_view) {
841 return QMainWindow::event(e);
843 if (old_view && old_view->currentBufferView()) {
844 // save current selection to the selection buffer to allow
845 // middle-button paste in this window.
846 cap::saveSelection(old_view->currentBufferView()->cursor());
848 guiApp->setCurrentView(this);
849 if (d.current_work_area_) {
850 BufferView & bv = d.current_work_area_->bufferView();
851 connectBufferView(bv);
852 connectBuffer(bv.buffer());
853 // The document structure, name and dialogs might have
854 // changed in another view.
856 // The document settings needs to be reinitialised.
857 updateDialog("document", "");
860 resetWindowTitleAndIconText();
863 return QMainWindow::event(e);
866 case QEvent::ShortcutOverride: {
869 #if (!defined Q_WS_X11) || (QT_VERSION >= 0x040500)
870 if (isFullScreen() && menuBar()->isHidden()) {
871 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
872 // FIXME: we should also try to detect special LyX shortcut such as
873 // Alt-P and Alt-M. Right now there is a hack in
874 // GuiWorkArea::processKeySym() that hides again the menubar for
876 if (ke->modifiers() & Qt::AltModifier && ke->key() != Qt::Key_Alt) {
878 return QMainWindow::event(e);
883 if (d.current_work_area_)
884 // Nothing special to do.
885 return QMainWindow::event(e);
887 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
888 // Let Qt handle menu access and the Tab keys to navigate keys to navigate
890 if (ke->modifiers() & Qt::AltModifier || ke->key() == Qt::Key_Tab
891 || ke->key() == Qt::Key_Backtab)
892 return QMainWindow::event(e);
894 // Allow processing of shortcuts that are allowed even when no Buffer
897 setKeySymbol(&sym, ke);
898 guiApp->processKeySym(sym, q_key_state(ke->modifiers()));
904 return QMainWindow::event(e);
908 void GuiView::resetWindowTitleAndIconText()
910 setWindowTitle(qt_("LyX"));
911 setWindowIconText(qt_("LyX"));
914 bool GuiView::focusNextPrevChild(bool /*next*/)
921 void GuiView::setBusy(bool busy)
923 if (d.current_work_area_) {
924 d.current_work_area_->setUpdatesEnabled(!busy);
926 d.current_work_area_->stopBlinkingCursor();
928 d.current_work_area_->startBlinkingCursor();
932 QApplication::setOverrideCursor(Qt::WaitCursor);
934 QApplication::restoreOverrideCursor();
938 GuiWorkArea * GuiView::workArea(Buffer & buffer)
940 if (currentWorkArea()
941 && ¤tWorkArea()->bufferView().buffer() == &buffer)
942 return (GuiWorkArea *) currentWorkArea();
943 if (TabWorkArea * twa = d.currentTabWorkArea())
944 return twa->workArea(buffer);
949 GuiWorkArea * GuiView::addWorkArea(Buffer & buffer)
951 // Automatically create a TabWorkArea if there are none yet.
952 TabWorkArea * tab_widget = d.splitter_->count()
953 ? d.currentTabWorkArea() : addTabWorkArea();
954 return tab_widget->addWorkArea(buffer, *this);
958 TabWorkArea * GuiView::addTabWorkArea()
960 TabWorkArea * twa = new TabWorkArea;
961 QObject::connect(twa, SIGNAL(currentWorkAreaChanged(GuiWorkArea *)),
962 this, SLOT(on_currentWorkAreaChanged(GuiWorkArea *)));
963 QObject::connect(twa, SIGNAL(lastWorkAreaRemoved()),
964 this, SLOT(on_lastWorkAreaRemoved()));
966 d.splitter_->addWidget(twa);
967 d.stack_widget_->setCurrentWidget(d.splitter_);
972 GuiWorkArea const * GuiView::currentWorkArea() const
974 return d.current_work_area_;
978 GuiWorkArea * GuiView::currentWorkArea()
980 return d.current_work_area_;
984 GuiWorkArea const * GuiView::currentMainWorkArea() const
986 if (d.currentTabWorkArea() == NULL)
988 return d.currentTabWorkArea()->currentWorkArea();
992 GuiWorkArea * GuiView::currentMainWorkArea()
994 if (d.currentTabWorkArea() == NULL)
996 return d.currentTabWorkArea()->currentWorkArea();
1000 void GuiView::setCurrentWorkArea(GuiWorkArea * wa)
1002 LYXERR(Debug::DEBUG, "Setting current wa: " << wa << endl);
1004 d.current_work_area_ = NULL;
1008 GuiWorkArea * old_gwa = theGuiApp()->currentView()->currentWorkArea();
1012 if (currentBufferView())
1013 cap::saveSelection(currentBufferView()->cursor());
1015 theGuiApp()->setCurrentView(this);
1016 d.current_work_area_ = wa;
1017 for (int i = 0; i != d.splitter_->count(); ++i) {
1018 if (d.tabWorkArea(i)->setCurrentWorkArea(wa)) {
1019 //if (d.current_main_work_area_)
1020 // d.current_main_work_area_->setFrameStyle(QFrame::NoFrame);
1021 d.current_main_work_area_ = wa;
1022 //d.current_main_work_area_->setFrameStyle(QFrame::Box | QFrame::Plain);
1023 //d.current_main_work_area_->setLineWidth(2);
1024 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() << ", Current main wa: " << currentMainWorkArea());
1028 LYXERR(Debug::DEBUG, "This is not a tabbed wa");
1029 on_currentWorkAreaChanged(wa);
1030 BufferView & bv = wa->bufferView();
1031 bv.cursor().fixIfBroken();
1033 wa->setUpdatesEnabled(true);
1034 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() << ", Current main wa: " << currentMainWorkArea());
1038 void GuiView::removeWorkArea(GuiWorkArea * wa)
1040 LASSERT(wa, return);
1041 if (wa == d.current_work_area_) {
1043 disconnectBufferView();
1044 d.current_work_area_ = 0;
1045 d.current_main_work_area_ = 0;
1048 bool found_twa = false;
1049 for (int i = 0; i != d.splitter_->count(); ++i) {
1050 TabWorkArea * twa = d.tabWorkArea(i);
1051 if (twa->removeWorkArea(wa)) {
1052 // Found in this tab group, and deleted the GuiWorkArea.
1054 if (twa->count() != 0) {
1055 if (d.current_work_area_ == 0)
1056 // This means that we are closing the current GuiWorkArea, so
1057 // switch to the next GuiWorkArea in the found TabWorkArea.
1058 setCurrentWorkArea(twa->currentWorkArea());
1060 // No more WorkAreas in this tab group, so delete it.
1067 // It is not a tabbed work area (i.e., the search work area), so it
1068 // should be deleted by other means.
1069 LASSERT(found_twa, /* */);
1071 if (d.current_work_area_ == 0) {
1072 if (d.splitter_->count() != 0) {
1073 TabWorkArea * twa = d.currentTabWorkArea();
1074 setCurrentWorkArea(twa->currentWorkArea());
1076 // No more work areas, switch to the background widget.
1077 setCurrentWorkArea(0);
1083 LayoutBox * GuiView::getLayoutDialog() const
1089 void GuiView::updateLayoutList()
1092 d.layout_->updateContents(false);
1096 void GuiView::updateToolbars()
1098 ToolbarMap::iterator end = d.toolbars_.end();
1099 if (d.current_work_area_) {
1101 d.current_work_area_->bufferView().cursor().inMathed();
1103 lyx::getStatus(FuncRequest(LFUN_LAYOUT_TABULAR)).enabled();
1105 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).enabled() &&
1106 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).onoff(true);
1107 bool const mathmacrotemplate =
1108 lyx::getStatus(FuncRequest(LFUN_IN_MATHMACROTEMPLATE)).enabled();
1110 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1111 it->second->update(math, table, review, mathmacrotemplate);
1113 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1114 it->second->update(false, false, false, false);
1118 void GuiView::setBuffer(Buffer * newBuffer)
1120 LYXERR(Debug::DEBUG, "Setting buffer: " << newBuffer << std::endl);
1121 LASSERT(newBuffer, return);
1124 GuiWorkArea * wa = workArea(*newBuffer);
1126 newBuffer->masterBuffer()->updateLabels();
1127 wa = addWorkArea(*newBuffer);
1129 //Disconnect the old buffer...there's no new one.
1132 connectBuffer(*newBuffer);
1133 connectBufferView(wa->bufferView());
1134 setCurrentWorkArea(wa);
1140 void GuiView::connectBuffer(Buffer & buf)
1142 buf.setGuiDelegate(this);
1146 void GuiView::disconnectBuffer()
1148 if (d.current_work_area_)
1149 d.current_work_area_->bufferView().buffer().setGuiDelegate(0);
1153 void GuiView::connectBufferView(BufferView & bv)
1155 bv.setGuiDelegate(this);
1159 void GuiView::disconnectBufferView()
1161 if (d.current_work_area_)
1162 d.current_work_area_->bufferView().setGuiDelegate(0);
1166 void GuiView::errors(string const & error_type, bool from_master)
1168 ErrorList & el = from_master ?
1169 documentBufferView()->buffer().masterBuffer()->errorList(error_type)
1170 : documentBufferView()->buffer().errorList(error_type);
1171 string data = error_type;
1173 data = "from_master|" + error_type;
1175 showDialog("errorlist", data);
1179 void GuiView::updateTocItem(std::string const & type, DocIterator const & dit)
1181 d.toc_models_.updateItem(toqstr(type), dit);
1185 void GuiView::structureChanged()
1187 d.toc_models_.reset(documentBufferView());
1188 // Navigator needs more than a simple update in this case. It needs to be
1190 updateDialog("toc", "");
1194 void GuiView::updateDialog(string const & name, string const & data)
1196 if (!isDialogVisible(name))
1199 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
1200 if (it == d.dialogs_.end())
1203 Dialog * const dialog = it->second.get();
1204 if (dialog->isVisibleView())
1205 dialog->initialiseParams(data);
1209 BufferView * GuiView::documentBufferView()
1211 return currentMainWorkArea()
1212 ? ¤tMainWorkArea()->bufferView()
1217 BufferView const * GuiView::documentBufferView() const
1219 return currentMainWorkArea()
1220 ? ¤tMainWorkArea()->bufferView()
1225 BufferView * GuiView::currentBufferView()
1227 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1231 BufferView const * GuiView::currentBufferView() const
1233 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1237 static docstring saveAndDestroyBuffer(Buffer * buffer, FileName const & fname)
1240 FileName const tmp_ret = FileName::tempName("lyxauto");
1241 if (!tmp_ret.empty()) {
1242 if (buffer->writeFile(tmp_ret))
1243 failed = !tmp_ret.moveTo(fname);
1246 // failed to write/rename tmp_ret so try writing direct
1247 failed = buffer->writeFile(fname);
1251 ? _("Automatic save failed!")
1252 : _("Automatic save done.");
1256 void GuiView::autoSave()
1258 LYXERR(Debug::INFO, "Running autoSave()");
1260 Buffer * buffer = documentBufferView()
1261 ? &documentBufferView()->buffer() : 0;
1265 #if (QT_VERSION >= 0x040400)
1266 QFuture<docstring> f = QtConcurrent::run(saveAndDestroyBuffer, buffer->clone(),
1267 buffer->getAutosaveFilename());
1268 d.autosave_watcher_.setFuture(f);
1275 void GuiView::resetAutosaveTimers()
1278 d.autosave_timeout_.restart();
1282 bool GuiView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1285 Buffer * buf = currentBufferView()
1286 ? ¤tBufferView()->buffer() : 0;
1287 Buffer * doc_buffer = documentBufferView()
1288 ? &(documentBufferView()->buffer()) : 0;
1290 // Check whether we need a buffer
1291 if (!lyxaction.funcHasFlag(cmd.action, LyXAction::NoBuffer) && !buf) {
1292 // no, exit directly
1293 flag.message(from_utf8(N_("Command not allowed with"
1294 "out any document open")));
1295 flag.setEnabled(false);
1299 if (cmd.origin == FuncRequest::TOC) {
1300 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
1302 if (toc->getStatus(documentBufferView()->cursor(), cmd, fs))
1305 flag.setEnabled(false);
1309 switch(cmd.action) {
1310 case LFUN_BUFFER_IMPORT:
1313 case LFUN_MASTER_BUFFER_UPDATE:
1314 case LFUN_MASTER_BUFFER_VIEW:
1315 enable = doc_buffer && doc_buffer->parent() != 0;
1318 case LFUN_BUFFER_UPDATE:
1319 case LFUN_BUFFER_VIEW: {
1324 string format = to_utf8(cmd.argument());
1325 if (cmd.argument().empty())
1326 format = doc_buffer->getDefaultOutputFormat();
1327 enable = doc_buffer->isExportableFormat(format);
1331 case LFUN_BUFFER_RELOAD:
1332 enable = doc_buffer && !doc_buffer->isUnnamed()
1333 && doc_buffer->fileName().exists()
1334 && (!doc_buffer->isClean()
1335 || doc_buffer->isExternallyModified(Buffer::timestamp_method));
1338 case LFUN_BUFFER_CHILD_OPEN:
1339 enable = doc_buffer;
1342 case LFUN_BUFFER_WRITE:
1343 enable = doc_buffer && (doc_buffer->isUnnamed() || !doc_buffer->isClean());
1346 //FIXME: This LFUN should be moved to GuiApplication.
1347 case LFUN_BUFFER_WRITE_ALL: {
1348 // We enable the command only if there are some modified buffers
1349 Buffer * first = theBufferList().first();
1354 // We cannot use a for loop as the buffer list is a cycle.
1356 if (!b->isClean()) {
1360 b = theBufferList().next(b);
1361 } while (b != first);
1365 case LFUN_BUFFER_WRITE_AS:
1366 enable = doc_buffer;
1369 case LFUN_BUFFER_CLOSE:
1370 enable = doc_buffer;
1373 case LFUN_BUFFER_CLOSE_ALL:
1374 enable = theBufferList().last() != theBufferList().first();
1377 case LFUN_SPLIT_VIEW:
1378 if (cmd.getArg(0) == "vertical")
1379 enable = doc_buffer && (d.splitter_->count() == 1 ||
1380 d.splitter_->orientation() == Qt::Vertical);
1382 enable = doc_buffer && (d.splitter_->count() == 1 ||
1383 d.splitter_->orientation() == Qt::Horizontal);
1386 case LFUN_CLOSE_TAB_GROUP:
1387 enable = d.currentTabWorkArea();
1390 case LFUN_TOOLBAR_TOGGLE:
1391 if (GuiToolbar * t = toolbar(cmd.getArg(0)))
1392 flag.setOnOff(t->isVisible());
1395 case LFUN_DROP_LAYOUTS_CHOICE:
1399 case LFUN_UI_TOGGLE:
1400 flag.setOnOff(isFullScreen());
1403 case LFUN_DIALOG_DISCONNECT_INSET:
1406 case LFUN_DIALOG_HIDE:
1407 // FIXME: should we check if the dialog is shown?
1410 case LFUN_DIALOG_TOGGLE:
1411 flag.setOnOff(isDialogVisible(cmd.getArg(0)));
1412 // fall through to set "enable"
1413 case LFUN_DIALOG_SHOW: {
1414 string const name = cmd.getArg(0);
1416 enable = name == "aboutlyx"
1417 || name == "file" //FIXME: should be removed.
1419 || name == "texinfo"
1420 || name == "progress"
1421 || name == "compare";
1422 else if (name == "print")
1423 enable = doc_buffer->isExportable("dvi")
1424 && lyxrc.print_command != "none";
1425 else if (name == "character" || name == "symbols") {
1426 if (!buf || buf->isReadonly()
1427 || !currentBufferView()->cursor().inTexted())
1430 // FIXME we should consider passthru
1432 Inset const & in = currentBufferView()->cursor().inset();
1433 enable = !in.getLayout().isPassThru();
1436 else if (name == "latexlog")
1437 enable = FileName(doc_buffer->logName()).isReadableFile();
1438 else if (name == "spellchecker")
1439 enable = theSpellChecker() && !doc_buffer->isReadonly();
1440 else if (name == "vclog")
1441 enable = doc_buffer->lyxvc().inUse();
1445 case LFUN_DIALOG_UPDATE: {
1446 string const name = cmd.getArg(0);
1448 enable = name == "prefs";
1452 case LFUN_COMMAND_EXECUTE:
1454 case LFUN_MENU_OPEN:
1455 // Nothing to check.
1458 case LFUN_COMPLETION_INLINE:
1459 if (!d.current_work_area_
1460 || !d.current_work_area_->completer().inlinePossible(
1461 currentBufferView()->cursor()))
1465 case LFUN_COMPLETION_POPUP:
1466 if (!d.current_work_area_
1467 || !d.current_work_area_->completer().popupPossible(
1468 currentBufferView()->cursor()))
1472 case LFUN_COMPLETION_COMPLETE:
1473 if (!d.current_work_area_
1474 || !d.current_work_area_->completer().inlinePossible(
1475 currentBufferView()->cursor()))
1479 case LFUN_COMPLETION_ACCEPT:
1480 if (!d.current_work_area_
1481 || (!d.current_work_area_->completer().popupVisible()
1482 && !d.current_work_area_->completer().inlineVisible()
1483 && !d.current_work_area_->completer().completionAvailable()))
1487 case LFUN_COMPLETION_CANCEL:
1488 if (!d.current_work_area_
1489 || (!d.current_work_area_->completer().popupVisible()
1490 && !d.current_work_area_->completer().inlineVisible()))
1494 case LFUN_BUFFER_ZOOM_OUT:
1495 enable = doc_buffer && lyxrc.zoom > 10;
1498 case LFUN_BUFFER_ZOOM_IN:
1499 enable = doc_buffer;
1502 case LFUN_BUFFER_NEXT:
1503 case LFUN_BUFFER_PREVIOUS:
1504 // FIXME: should we check is there is an previous or next buffer?
1506 case LFUN_BUFFER_SWITCH:
1507 // toggle on the current buffer, but do not toggle off
1508 // the other ones (is that a good idea?)
1510 && to_utf8(cmd.argument()) == doc_buffer->absFileName())
1511 flag.setOnOff(true);
1514 case LFUN_VC_REGISTER:
1515 enable = doc_buffer && !doc_buffer->lyxvc().inUse();
1517 case LFUN_VC_CHECK_IN:
1518 enable = doc_buffer && doc_buffer->lyxvc().checkInEnabled();
1520 case LFUN_VC_CHECK_OUT:
1521 enable = doc_buffer && doc_buffer->lyxvc().checkOutEnabled();
1523 case LFUN_VC_LOCKING_TOGGLE:
1524 enable = doc_buffer && !doc_buffer->isReadonly()
1525 && doc_buffer->lyxvc().lockingToggleEnabled();
1526 flag.setOnOff(enable && !doc_buffer->lyxvc().locker().empty());
1528 case LFUN_VC_REVERT:
1529 enable = doc_buffer && doc_buffer->lyxvc().inUse();
1531 case LFUN_VC_UNDO_LAST:
1532 enable = doc_buffer && doc_buffer->lyxvc().undoLastEnabled();
1534 case LFUN_VC_REPO_UPDATE:
1535 enable = doc_buffer && doc_buffer->lyxvc().inUse();
1537 case LFUN_VC_COMMAND: {
1538 if (cmd.argument().empty())
1540 if (!doc_buffer && contains(cmd.getArg(0), 'D'))
1545 case LFUN_SERVER_GOTO_FILE_ROW:
1553 flag.setEnabled(false);
1559 static FileName selectTemplateFile()
1561 FileDialog dlg(qt_("Select template file"));
1562 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1563 dlg.setButton1(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
1565 FileDialog::Result result = dlg.open(toqstr(lyxrc.template_path),
1566 QStringList(qt_("LyX Documents (*.lyx)")));
1568 if (result.first == FileDialog::Later)
1570 if (result.second.isEmpty())
1572 return FileName(fromqstr(result.second));
1576 Buffer * GuiView::loadDocument(FileName const & filename, bool tolastfiles)
1580 Buffer * newBuffer = checkAndLoadLyXFile(filename);
1583 message(_("Document not loaded."));
1588 setBuffer(newBuffer);
1590 // scroll to the position when the file was last closed
1591 if (lyxrc.use_lastfilepos) {
1592 LastFilePosSection::FilePos filepos =
1593 theSession().lastFilePos().load(filename);
1594 documentBufferView()->moveToPosition(filepos.pit, filepos.pos, 0, 0);
1598 theSession().lastFiles().add(filename);
1605 void GuiView::openDocument(string const & fname)
1607 string initpath = lyxrc.document_path;
1609 if (documentBufferView()) {
1610 string const trypath = documentBufferView()->buffer().filePath();
1611 // If directory is writeable, use this as default.
1612 if (FileName(trypath).isDirWritable())
1618 if (fname.empty()) {
1619 FileDialog dlg(qt_("Select document to open"), LFUN_FILE_OPEN);
1620 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1621 dlg.setButton2(qt_("Examples|#E#e"),
1622 toqstr(addPath(package().system_support().absFilename(), "examples")));
1624 QStringList filter(qt_("LyX Documents (*.lyx)"));
1625 filter << qt_("LyX-1.3.x Documents (*.lyx13)")
1626 << qt_("LyX-1.4.x Documents (*.lyx14)")
1627 << qt_("LyX-1.5.x Documents (*.lyx15)")
1628 << qt_("LyX-1.6.x Documents (*.lyx16)");
1629 FileDialog::Result result =
1630 dlg.open(toqstr(initpath), filter);
1632 if (result.first == FileDialog::Later)
1635 filename = fromqstr(result.second);
1637 // check selected filename
1638 if (filename.empty()) {
1639 message(_("Canceled."));
1645 // get absolute path of file and add ".lyx" to the filename if
1647 FileName const fullname =
1648 fileSearch(string(), filename, "lyx", support::may_not_exist);
1649 if (!fullname.empty())
1650 filename = fullname.absFilename();
1652 if (!fullname.onlyPath().isDirectory()) {
1653 Alert::warning(_("Invalid filename"),
1654 bformat(_("The directory in the given path\n%1$s\ndoes not exist."),
1655 from_utf8(fullname.absFilename())));
1658 // if the file doesn't exist, let the user create one
1659 if (!fullname.exists()) {
1660 // the user specifically chose this name. Believe him.
1661 Buffer * const b = newFile(filename, string(), true);
1667 docstring const disp_fn = makeDisplayPath(filename);
1668 message(bformat(_("Opening document %1$s..."), disp_fn));
1671 Buffer * buf = loadDocument(fullname);
1673 buf->updateLabels();
1675 buf->errors("Parse");
1676 str2 = bformat(_("Document %1$s opened."), disp_fn);
1677 if (buf->lyxvc().inUse())
1678 str2 += " " + from_utf8(buf->lyxvc().versionString()) +
1679 " " + _("Version control detected.");
1681 str2 = bformat(_("Could not open document %1$s"), disp_fn);
1686 // FIXME: clean that
1687 static bool import(GuiView * lv, FileName const & filename,
1688 string const & format, ErrorList & errorList)
1690 FileName const lyxfile(support::changeExtension(filename.absFilename(), ".lyx"));
1692 string loader_format;
1693 vector<string> loaders = theConverters().loaders();
1694 if (find(loaders.begin(), loaders.end(), format) == loaders.end()) {
1695 for (vector<string>::const_iterator it = loaders.begin();
1696 it != loaders.end(); ++it) {
1697 if (!theConverters().isReachable(format, *it))
1700 string const tofile =
1701 support::changeExtension(filename.absFilename(),
1702 formats.extension(*it));
1703 if (!theConverters().convert(0, filename, FileName(tofile),
1704 filename, format, *it, errorList))
1706 loader_format = *it;
1709 if (loader_format.empty()) {
1710 frontend::Alert::error(_("Couldn't import file"),
1711 bformat(_("No information for importing the format %1$s."),
1712 formats.prettyName(format)));
1716 loader_format = format;
1718 if (loader_format == "lyx") {
1719 Buffer * buf = lv->loadDocument(lyxfile);
1722 buf->updateLabels();
1724 buf->errors("Parse");
1726 Buffer * const b = newFile(lyxfile.absFilename(), string(), true);
1730 bool as_paragraphs = loader_format == "textparagraph";
1731 string filename2 = (loader_format == format) ? filename.absFilename()
1732 : support::changeExtension(filename.absFilename(),
1733 formats.extension(loader_format));
1734 lv->currentBufferView()->insertPlaintextFile(FileName(filename2),
1736 guiApp->setCurrentView(lv);
1737 lyx::dispatch(FuncRequest(LFUN_MARK_OFF));
1744 void GuiView::importDocument(string const & argument)
1747 string filename = split(argument, format, ' ');
1749 LYXERR(Debug::INFO, format << " file: " << filename);
1751 // need user interaction
1752 if (filename.empty()) {
1753 string initpath = lyxrc.document_path;
1754 if (documentBufferView()) {
1755 string const trypath = documentBufferView()->buffer().filePath();
1756 // If directory is writeable, use this as default.
1757 if (FileName(trypath).isDirWritable())
1761 docstring const text = bformat(_("Select %1$s file to import"),
1762 formats.prettyName(format));
1764 FileDialog dlg(toqstr(text), LFUN_BUFFER_IMPORT);
1765 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1766 dlg.setButton2(qt_("Examples|#E#e"),
1767 toqstr(addPath(package().system_support().absFilename(), "examples")));
1769 docstring filter = formats.prettyName(format);
1772 filter += from_utf8(formats.extension(format));
1775 FileDialog::Result result =
1776 dlg.open(toqstr(initpath), fileFilters(toqstr(filter)));
1778 if (result.first == FileDialog::Later)
1781 filename = fromqstr(result.second);
1783 // check selected filename
1784 if (filename.empty())
1785 message(_("Canceled."));
1788 if (filename.empty())
1791 // get absolute path of file
1792 FileName const fullname(support::makeAbsPath(filename));
1794 FileName const lyxfile(support::changeExtension(fullname.absFilename(), ".lyx"));
1796 // Check if the document already is open
1797 Buffer * buf = theBufferList().getBuffer(lyxfile);
1800 if (!closeBuffer()) {
1801 message(_("Canceled."));
1806 docstring const displaypath = makeDisplayPath(lyxfile.absFilename(), 30);
1808 // if the file exists already, and we didn't do
1809 // -i lyx thefile.lyx, warn
1810 if (lyxfile.exists() && fullname != lyxfile) {
1812 docstring text = bformat(_("The document %1$s already exists.\n\n"
1813 "Do you want to overwrite that document?"), displaypath);
1814 int const ret = Alert::prompt(_("Overwrite document?"),
1815 text, 0, 1, _("&Overwrite"), _("&Cancel"));
1818 message(_("Canceled."));
1823 message(bformat(_("Importing %1$s..."), displaypath));
1824 ErrorList errorList;
1825 if (import(this, fullname, format, errorList))
1826 message(_("imported."));
1828 message(_("file not imported!"));
1830 // FIXME (Abdel 12/08/06): Is there a need to display the error list here?
1834 void GuiView::newDocument(string const & filename, bool from_template)
1836 FileName initpath(lyxrc.document_path);
1837 if (documentBufferView()) {
1838 FileName const trypath(documentBufferView()->buffer().filePath());
1839 // If directory is writeable, use this as default.
1840 if (trypath.isDirWritable())
1844 string templatefile;
1845 if (from_template) {
1846 templatefile = selectTemplateFile().absFilename();
1847 if (templatefile.empty())
1852 if (filename.empty())
1853 b = newUnnamedFile(initpath, to_utf8(_("newfile")), templatefile);
1855 b = newFile(filename, templatefile, true);
1860 // If no new document could be created, it is unsure
1861 // whether there is a valid BufferView.
1862 if (currentBufferView())
1863 // Ensure the cursor is correctly positioned on screen.
1864 currentBufferView()->showCursor();
1868 void GuiView::insertLyXFile(docstring const & fname)
1870 BufferView * bv = documentBufferView();
1875 FileName filename(to_utf8(fname));
1877 if (!filename.empty()) {
1878 bv->insertLyXFile(filename);
1882 // Launch a file browser
1884 string initpath = lyxrc.document_path;
1885 string const trypath = bv->buffer().filePath();
1886 // If directory is writeable, use this as default.
1887 if (FileName(trypath).isDirWritable())
1891 FileDialog dlg(qt_("Select LyX document to insert"), LFUN_FILE_INSERT);
1892 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1893 dlg.setButton2(qt_("Examples|#E#e"),
1894 toqstr(addPath(package().system_support().absFilename(),
1897 FileDialog::Result result = dlg.open(toqstr(initpath),
1898 QStringList(qt_("LyX Documents (*.lyx)")));
1900 if (result.first == FileDialog::Later)
1904 filename.set(fromqstr(result.second));
1906 // check selected filename
1907 if (filename.empty()) {
1908 // emit message signal.
1909 message(_("Canceled."));
1913 bv->insertLyXFile(filename);
1917 void GuiView::insertPlaintextFile(docstring const & fname,
1920 BufferView * bv = documentBufferView();
1924 if (!fname.empty() && !FileName::isAbsolute(to_utf8(fname))) {
1925 message(_("Absolute filename expected."));
1930 FileName filename(to_utf8(fname));
1932 if (!filename.empty()) {
1933 bv->insertPlaintextFile(filename, asParagraph);
1937 FileDialog dlg(qt_("Select file to insert"), (asParagraph ?
1938 LFUN_FILE_INSERT_PLAINTEXT_PARA : LFUN_FILE_INSERT_PLAINTEXT));
1940 FileDialog::Result result = dlg.open(toqstr(bv->buffer().filePath()),
1941 QStringList(qt_("All Files (*)")));
1943 if (result.first == FileDialog::Later)
1947 filename.set(fromqstr(result.second));
1949 // check selected filename
1950 if (filename.empty()) {
1951 // emit message signal.
1952 message(_("Canceled."));
1956 bv->insertPlaintextFile(filename, asParagraph);
1960 bool GuiView::renameBuffer(Buffer & b, docstring const & newname)
1962 FileName fname = b.fileName();
1963 FileName const oldname = fname;
1965 if (!newname.empty()) {
1967 fname = support::makeAbsPath(to_utf8(newname), oldname.onlyPath().absFilename());
1969 // Switch to this Buffer.
1972 // No argument? Ask user through dialog.
1974 FileDialog dlg(qt_("Choose a filename to save document as"),
1975 LFUN_BUFFER_WRITE_AS);
1976 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1977 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
1979 if (!isLyXFilename(fname.absFilename()))
1980 fname.changeExtension(".lyx");
1982 FileDialog::Result result =
1983 dlg.save(toqstr(fname.onlyPath().absFilename()),
1984 QStringList(qt_("LyX Documents (*.lyx)")),
1985 toqstr(fname.onlyFileName()));
1987 if (result.first == FileDialog::Later)
1990 fname.set(fromqstr(result.second));
1995 if (!isLyXFilename(fname.absFilename()))
1996 fname.changeExtension(".lyx");
1999 if (FileName(fname).exists()) {
2000 docstring const file = makeDisplayPath(fname.absFilename(), 30);
2001 docstring text = bformat(_("The document %1$s already "
2002 "exists.\n\nDo you want to "
2003 "overwrite that document?"),
2005 int const ret = Alert::prompt(_("Overwrite document?"),
2006 text, 0, 2, _("&Overwrite"), _("&Rename"), _("&Cancel"));
2009 case 1: return renameBuffer(b, docstring());
2010 case 2: return false;
2014 FileName oldauto = b.getAutosaveFilename();
2016 // Ok, change the name of the buffer
2017 b.setFileName(fname.absFilename());
2019 bool unnamed = b.isUnnamed();
2020 b.setUnnamed(false);
2021 b.saveCheckSum(fname);
2023 // bring the autosave file with us, just in case.
2024 b.moveAutosaveFile(oldauto);
2026 if (!saveBuffer(b)) {
2027 oldauto = b.getAutosaveFilename();
2028 b.setFileName(oldname.absFilename());
2029 b.setUnnamed(unnamed);
2030 b.saveCheckSum(oldname);
2031 b.moveAutosaveFile(oldauto);
2039 bool GuiView::saveBuffer(Buffer & b)
2041 if (workArea(b) && workArea(b)->inDialogMode())
2045 return renameBuffer(b, docstring());
2048 theSession().lastFiles().add(b.fileName());
2052 // Switch to this Buffer.
2055 // FIXME: we don't tell the user *WHY* the save failed !!
2056 docstring const file = makeDisplayPath(b.absFileName(), 30);
2057 docstring text = bformat(_("The document %1$s could not be saved.\n\n"
2058 "Do you want to rename the document and "
2059 "try again?"), file);
2060 int const ret = Alert::prompt(_("Rename and save?"),
2061 text, 0, 2, _("&Rename"), _("&Retry"), _("&Cancel"));
2064 if (!renameBuffer(b, docstring()))
2073 return saveBuffer(b);
2077 bool GuiView::hideWorkArea(GuiWorkArea * wa)
2079 return closeWorkArea(wa, false);
2083 bool GuiView::closeWorkArea(GuiWorkArea * wa)
2085 Buffer & buf = wa->bufferView().buffer();
2086 return closeWorkArea(wa, !buf.parent());
2090 bool GuiView::closeBuffer()
2092 GuiWorkArea * wa = currentMainWorkArea();
2093 Buffer & buf = wa->bufferView().buffer();
2094 return wa && closeWorkArea(wa, !buf.parent());
2098 void GuiView::writeSession() const {
2099 GuiWorkArea const * active_wa = currentMainWorkArea();
2100 for (int i = 0; i < d.splitter_->count(); ++i) {
2101 TabWorkArea * twa = d.tabWorkArea(i);
2102 for (int j = 0; j < twa->count(); ++j) {
2103 GuiWorkArea * wa = static_cast<GuiWorkArea *>(twa->widget(j));
2104 Buffer & buf = wa->bufferView().buffer();
2105 theSession().lastOpened().add(buf.fileName(), wa == active_wa);
2111 bool GuiView::closeBufferAll()
2113 // Close the workareas in all other views
2114 QList<int> const ids = guiApp->viewIds();
2115 for (int i = 0; i != ids.size(); ++i) {
2116 if (id_ != ids[i] && !guiApp->view(ids[i]).closeWorkAreaAll())
2120 // Close our own workareas
2121 if (!closeWorkAreaAll())
2124 // Now close the hidden buffers. We prevent hidden buffers from being
2125 // dirty, so we can just close them.
2126 theBufferList().closeAll();
2131 bool GuiView::closeWorkAreaAll()
2133 setCurrentWorkArea(currentMainWorkArea());
2135 // We might be in a situation that there is still a tabWorkArea, but
2136 // there are no tabs anymore. This can happen when we get here after a
2137 // TabWorkArea::lastWorkAreaRemoved() signal. Therefore we count how
2138 // many TabWorkArea's have no documents anymore.
2141 // We have to call count() each time, because it can happen that
2142 // more than one splitter will disappear in one iteration (bug 5998).
2143 for (; d.splitter_->count() > empty_twa; ) {
2144 TabWorkArea * twa = d.tabWorkArea(empty_twa);
2146 if (twa->count() == 0)
2149 setCurrentWorkArea(twa->currentWorkArea());
2150 if (!closeTabWorkArea(twa))
2158 bool GuiView::closeWorkArea(GuiWorkArea * wa, bool close_buffer)
2163 Buffer & buf = wa->bufferView().buffer();
2166 return closeBuffer(buf);
2168 if (!inMultiTabs(wa))
2169 if (!saveBufferIfNeeded(buf, true))
2177 bool GuiView::closeBuffer(Buffer & buf)
2179 // If we are in a close_event all children will be closed in some time,
2180 // so no need to do it here. This will ensure that the children end up
2181 // in the session file in the correct order. If we close the master
2182 // buffer, we can close or release the child buffers here too.
2184 vector<Buffer *> clist = buf.getChildren(false);
2185 for (vector<Buffer *>::const_iterator it = clist.begin();
2186 it != clist.end(); ++it) {
2187 // If a child is dirty, do not close
2188 // without user intervention
2189 //FIXME: should we look in other tabworkareas?
2190 Buffer * child_buf = *it;
2191 GuiWorkArea * child_wa = workArea(*child_buf);
2193 if (!closeWorkArea(child_wa, true))
2196 theBufferList().releaseChild(&buf, child_buf);
2199 // goto bookmark to update bookmark pit.
2200 //FIXME: we should update only the bookmarks related to this buffer!
2201 LYXERR(Debug::DEBUG, "GuiView::closeBuffer()");
2202 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
2203 theLyXFunc().gotoBookmark(i+1, false, false);
2205 if (saveBufferIfNeeded(buf, false)) {
2206 theBufferList().release(&buf);
2213 bool GuiView::closeTabWorkArea(TabWorkArea * twa)
2215 while (twa == d.currentTabWorkArea()) {
2216 twa->setCurrentIndex(twa->count()-1);
2218 GuiWorkArea * wa = twa->currentWorkArea();
2219 Buffer & b = wa->bufferView().buffer();
2221 // We only want to close the buffer if the same buffer is not visible
2222 // in another view, and if this is not a child and if we are closing
2223 // a view (not a tabgroup).
2224 bool const close_buffer =
2225 !inMultiViews(wa) && !b.parent() && closing_;
2227 if (!closeWorkArea(wa, close_buffer))
2234 bool GuiView::saveBufferIfNeeded(Buffer & buf, bool hiding)
2236 if (buf.isClean() || buf.paragraphs().empty())
2239 // Switch to this Buffer.
2244 if (buf.isUnnamed())
2245 file = from_utf8(buf.fileName().onlyFileName());
2247 file = buf.fileName().displayName(30);
2249 // Bring this window to top before asking questions.
2254 if (hiding && buf.isUnnamed()) {
2255 docstring const text = bformat(_("The document %1$s has not been "
2256 "saved yet.\n\nDo you want to save "
2257 "the document?"), file);
2258 ret = Alert::prompt(_("Save new document?"),
2259 text, 0, 1, _("&Save"), _("&Cancel"));
2263 docstring const text = bformat(_("The document %1$s has unsaved changes."
2264 "\n\nDo you want to save the document or discard the changes?"), file);
2265 ret = Alert::prompt(_("Save changed document?"),
2266 text, 0, 2, _("&Save"), _("&Discard"), _("&Cancel"));
2271 if (!saveBuffer(buf))
2275 // if we crash after this we could
2276 // have no autosave file but I guess
2277 // this is really improbable (Jug)
2278 buf.removeAutosaveFile();
2280 // revert all changes
2281 buf.loadLyXFile(buf.fileName());
2291 bool GuiView::inMultiTabs(GuiWorkArea * wa)
2293 Buffer & buf = wa->bufferView().buffer();
2295 for (int i = 0; i != d.splitter_->count(); ++i) {
2296 GuiWorkArea * wa_ = d.tabWorkArea(i)->workArea(buf);
2297 if (wa_ && wa_ != wa)
2300 return inMultiViews(wa);
2304 bool GuiView::inMultiViews(GuiWorkArea * wa)
2306 QList<int> const ids = guiApp->viewIds();
2307 Buffer & buf = wa->bufferView().buffer();
2310 for (int i = 0; i != ids.size() && found_twa <= 1; ++i) {
2314 if (guiApp->view(ids[i]).workArea(buf))
2321 void GuiView::gotoNextOrPreviousBuffer(NextOrPrevious np)
2323 Buffer * const curbuf = documentBufferView()
2324 ? &documentBufferView()->buffer() : 0;
2325 Buffer * nextbuf = curbuf;
2327 if (np == NEXTBUFFER)
2328 nextbuf = theBufferList().next(nextbuf);
2330 nextbuf = theBufferList().previous(nextbuf);
2331 if (nextbuf == curbuf)
2337 if (workArea(*nextbuf))
2344 /// make sure the document is saved
2345 static bool ensureBufferClean(Buffer * buffer)
2347 LASSERT(buffer, return false);
2348 if (buffer->isClean() && !buffer->isUnnamed())
2351 docstring const file = buffer->fileName().displayName(30);
2354 if (!buffer->isUnnamed()) {
2355 text = bformat(_("The document %1$s has unsaved "
2356 "changes.\n\nDo you want to save "
2357 "the document?"), file);
2358 title = _("Save changed document?");
2361 text = bformat(_("The document %1$s has not been "
2362 "saved yet.\n\nDo you want to save "
2363 "the document?"), file);
2364 title = _("Save new document?");
2366 int const ret = Alert::prompt(title, text, 0, 1, _("&Save"), _("&Cancel"));
2369 dispatch(FuncRequest(LFUN_BUFFER_WRITE));
2371 return buffer->isClean() && !buffer->isUnnamed();
2375 void GuiView::reloadBuffer()
2377 Buffer * buf = &documentBufferView()->buffer();
2382 void GuiView::reloadBuffer(Buffer * buf)
2384 FileName filename = buf->fileName();
2385 Buffer const * master = buf->masterBuffer();
2386 bool const is_child = master != buf;
2387 // The user has already confirmed that the changes, if any, should
2388 // be discarded. So we just release the Buffer and don't call closeBuffer();
2389 theBufferList().release(buf);
2390 buf = loadDocument(filename);
2391 docstring const disp_fn = makeDisplayPath(filename.absFilename());
2394 // re-allocate master if necessary
2395 if (is_child && theBufferList().isLoaded(master)
2396 && buf->masterBuffer() != master)
2397 buf->setParent(master);
2398 buf->updateLabels();
2400 buf->errors("Parse");
2401 str = bformat(_("Document %1$s reloaded."), disp_fn);
2403 str = bformat(_("Could not reload document %1$s"), disp_fn);
2409 void GuiView::checkExternallyModifiedBuffers()
2411 BufferList::iterator bit = theBufferList().begin();
2412 BufferList::iterator const bend = theBufferList().end();
2413 for (; bit != bend; ++bit) {
2414 if ((*bit)->isExternallyModified(Buffer::checksum_method)) {
2415 docstring text = bformat(_("Document \n%1$s\n has been externally modified."
2416 " Reload now? Any local changes will be lost."),
2417 from_utf8((*bit)->absFileName()));
2418 int const ret = Alert::prompt(_("Reload externally changed document?"),
2419 text, 0, 1, _("&Reload"), _("&Cancel"));
2427 void GuiView::dispatchVC(FuncRequest const & cmd)
2429 Buffer * buffer = documentBufferView()
2430 ? &(documentBufferView()->buffer()) : 0;
2432 switch (cmd.action) {
2433 case LFUN_VC_REGISTER:
2434 if (!buffer || !ensureBufferClean(buffer))
2436 if (!buffer->lyxvc().inUse()) {
2437 if (buffer->lyxvc().registrer())
2442 case LFUN_VC_CHECK_IN:
2443 if (!buffer || !ensureBufferClean(buffer))
2445 if (buffer->lyxvc().inUse() && !buffer->isReadonly()) {
2446 message(from_utf8(buffer->lyxvc().checkIn()));
2451 case LFUN_VC_CHECK_OUT:
2452 if (!buffer || !ensureBufferClean(buffer))
2454 if (buffer->lyxvc().inUse()) {
2455 message(from_utf8(buffer->lyxvc().checkOut()));
2460 case LFUN_VC_LOCKING_TOGGLE:
2461 LASSERT(buffer, return);
2462 if (!ensureBufferClean(buffer) || buffer->isReadonly())
2464 if (buffer->lyxvc().inUse()) {
2465 string res = buffer->lyxvc().lockingToggle();
2467 frontend::Alert::error(_("Revision control error."),
2468 _("Error when setting the locking property."));
2470 message(from_utf8(res));
2476 case LFUN_VC_REVERT:
2477 LASSERT(buffer, return);
2478 buffer->lyxvc().revert();
2482 case LFUN_VC_UNDO_LAST:
2483 LASSERT(buffer, return);
2484 buffer->lyxvc().undoLast();
2488 case LFUN_VC_REPO_UPDATE:
2489 LASSERT(buffer, return);
2490 if (ensureBufferClean(buffer)) {
2491 string res = buffer->lyxvc().repoUpdate();
2492 message(from_utf8(res));
2493 checkExternallyModifiedBuffers();
2497 case LFUN_VC_COMMAND: {
2498 string flag = cmd.getArg(0);
2499 if (buffer && contains(flag, 'R') && !ensureBufferClean(buffer))
2502 if (contains(flag, 'M')) {
2503 if (!Alert::askForText(message, _("LyX VC: Log Message")))
2506 string path = cmd.getArg(1);
2507 if (contains(path, "$$p") && buffer)
2508 path = subst(path, "$$p", buffer->filePath());
2509 LYXERR(Debug::LYXVC, "Directory: " << path);
2511 if (!pp.isReadableDirectory()) {
2512 lyxerr << _("Directory is not accessible.") << endl;
2515 support::PathChanger p(pp);
2517 string command = cmd.getArg(2);
2518 if (command.empty())
2521 command = subst(command, "$$i", buffer->absFileName());
2522 command = subst(command, "$$p", buffer->filePath());
2524 command = subst(command, "$$m", to_utf8(message));
2525 LYXERR(Debug::LYXVC, "Command: " << command);
2527 one.startscript(Systemcall::Wait, command);
2531 if (contains(flag, 'I'))
2532 buffer->markDirty();
2533 if (contains(flag, 'R'))
2544 void GuiView::openChildDocument(string const & fname)
2546 LASSERT(documentBufferView(), return);
2547 Buffer & buffer = documentBufferView()->buffer();
2548 FileName const filename = support::makeAbsPath(fname, buffer.filePath());
2549 documentBufferView()->saveBookmark(false);
2551 bool parsed = false;
2552 if (theBufferList().exists(filename)) {
2553 child = theBufferList().getBuffer(filename);
2555 message(bformat(_("Opening child document %1$s..."),
2556 makeDisplayPath(filename.absFilename())));
2557 child = loadDocument(filename, false);
2563 // Set the parent name of the child document.
2564 // This makes insertion of citations and references in the child work,
2565 // when the target is in the parent or another child document.
2566 child->setParent(&buffer);
2567 child->masterBuffer()->updateLabels();
2570 child->errors("Parse");
2574 bool GuiView::goToFileRow(string const & argument)
2578 istringstream is(argument);
2579 is >> file_name >> row;
2580 file_name = os::internal_path(file_name);
2582 string const abstmp = package().temp_dir().absFilename();
2583 string const realtmp = package().temp_dir().realPath();
2584 // We have to use os::path_prefix_is() here, instead of
2585 // simply prefixIs(), because the file name comes from
2586 // an external application and may need case adjustment.
2587 if (os::path_prefix_is(file_name, abstmp, os::CASE_ADJUSTED)
2588 || os::path_prefix_is(file_name, realtmp, os::CASE_ADJUSTED)) {
2589 // Needed by inverse dvi search. If it is a file
2590 // in tmpdir, call the apropriated function.
2591 // If tmpdir is a symlink, we may have the real
2592 // path passed back, so we correct for that.
2593 if (!prefixIs(file_name, abstmp))
2594 file_name = subst(file_name, realtmp, abstmp);
2595 buf = theBufferList().getBufferFromTmp(file_name);
2597 // Must replace extension of the file to be .lyx
2598 // and get full path
2599 FileName const s = fileSearch(string(),
2600 support::changeExtension(file_name, ".lyx"), "lyx");
2601 // Either change buffer or load the file
2602 if (theBufferList().exists(s))
2603 buf = theBufferList().getBuffer(s);
2604 else if (s.exists()) {
2605 buf = loadDocument(s);
2606 buf->updateLabels();
2607 buf->errors("Parse");
2610 _("File does not exist: %1$s"),
2611 makeDisplayPath(file_name)));
2616 documentBufferView()->setCursorFromRow(row);
2621 static docstring exportAndDestroy(Buffer * buffer, std::string const & format)
2623 bool const success = buffer->doExport(format, true);
2626 ? bformat(_("Successful export to format: %1$s"), from_utf8(format))
2627 : bformat(_("Error exporting to format: %1$s"), from_utf8(format));
2631 static docstring previewAndDestroy(Buffer * buffer, std::string const & format)
2633 bool const success = buffer->preview(format);
2636 ? bformat(_("Successful preview of format: %1$s"), from_utf8(format))
2637 : bformat(_("Error previewing format: %1$s"), from_utf8(format));
2641 bool GuiView::dispatch(FuncRequest const & cmd)
2643 BufferView * bv = currentBufferView();
2644 // By default we won't need any update.
2646 bv->cursor().updateFlags(Update::None);
2648 Buffer * doc_buffer = documentBufferView()
2649 ? &(documentBufferView()->buffer()) : 0;
2651 bool dispatched = true;
2653 if (cmd.origin == FuncRequest::TOC) {
2654 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
2655 toc->doDispatch(bv->cursor(), cmd);
2659 string const argument = to_utf8(cmd.argument());
2661 switch(cmd.action) {
2662 case LFUN_BUFFER_CHILD_OPEN:
2663 openChildDocument(to_utf8(cmd.argument()));
2666 case LFUN_BUFFER_IMPORT:
2667 importDocument(to_utf8(cmd.argument()));
2670 case LFUN_BUFFER_EXPORT: {
2673 if (cmd.argument() == "custom") {
2674 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "sendto"));
2677 if (doc_buffer->doExport(argument, false)) {
2678 message(bformat(_("Error exporting to format: %1$s."),
2684 case LFUN_BUFFER_UPDATE: {
2687 string format = argument;
2688 if (argument.empty())
2689 format = doc_buffer->getDefaultOutputFormat();
2690 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
2691 QFuture<docstring> f = QtConcurrent::run(exportAndDestroy,
2692 doc_buffer->clone(), format);
2693 d.setPreviewFuture(f);
2695 doc_buffer->doExport(format, true);
2699 case LFUN_BUFFER_VIEW: {
2702 string format = argument;
2703 if (argument.empty())
2704 format = doc_buffer->getDefaultOutputFormat();
2705 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
2706 QFuture<docstring> f = QtConcurrent::run(previewAndDestroy,
2707 doc_buffer->clone(), format);
2708 d.setPreviewFuture(f);
2710 doc_buffer->preview(format);
2714 case LFUN_MASTER_BUFFER_UPDATE: {
2717 string format = argument;
2718 Buffer const * master = doc_buffer->masterBuffer();
2719 if (argument.empty())
2720 format = master->getDefaultOutputFormat();
2721 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
2722 QFuture<docstring> f = QtConcurrent::run(exportAndDestroy,
2723 master->clone(), format);
2724 d.setPreviewFuture(f);
2726 master->doExport(format, true);
2730 case LFUN_MASTER_BUFFER_VIEW: {
2731 string format = argument;
2732 Buffer const * master = doc_buffer->masterBuffer();
2733 if (argument.empty())
2734 format = master->getDefaultOutputFormat();
2735 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
2736 QFuture<docstring> f = QtConcurrent::run(previewAndDestroy,
2737 master->clone(), format);
2738 d.setPreviewFuture(f);
2740 master->preview(format);
2744 case LFUN_BUFFER_SWITCH:
2745 if (FileName::isAbsolute(to_utf8(cmd.argument()))) {
2747 theBufferList().getBuffer(FileName(to_utf8(cmd.argument())));
2751 message(_("Document not loaded"));
2755 case LFUN_BUFFER_NEXT:
2756 gotoNextOrPreviousBuffer(NEXTBUFFER);
2759 case LFUN_BUFFER_PREVIOUS:
2760 gotoNextOrPreviousBuffer(PREVBUFFER);
2763 case LFUN_COMMAND_EXECUTE: {
2764 bool const show_it = cmd.argument() != "off";
2765 // FIXME: this is a hack, "minibuffer" should not be
2767 if (GuiToolbar * t = toolbar("minibuffer")) {
2768 t->setVisible(show_it);
2769 if (show_it && t->commandBuffer())
2770 t->commandBuffer()->setFocus();
2774 case LFUN_DROP_LAYOUTS_CHOICE:
2775 d.layout_->showPopup();
2778 case LFUN_MENU_OPEN:
2779 if (QMenu * menu = guiApp->menus().menu(toqstr(cmd.argument()), *this))
2780 menu->exec(QCursor::pos());
2783 case LFUN_FILE_INSERT:
2784 insertLyXFile(cmd.argument());
2786 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
2787 insertPlaintextFile(cmd.argument(), true);
2790 case LFUN_FILE_INSERT_PLAINTEXT:
2791 insertPlaintextFile(cmd.argument(), false);
2794 case LFUN_BUFFER_RELOAD: {
2795 LASSERT(doc_buffer, break);
2796 docstring const file = makeDisplayPath(doc_buffer->absFileName(), 20);
2797 docstring text = bformat(_("Any changes will be lost. Are you sure "
2798 "you want to revert to the saved version of the document %1$s?"), file);
2799 int const ret = Alert::prompt(_("Revert to saved document?"),
2800 text, 1, 1, _("&Revert"), _("&Cancel"));
2803 doc_buffer->markClean();
2809 case LFUN_BUFFER_WRITE:
2810 LASSERT(doc_buffer, break);
2811 saveBuffer(*doc_buffer);
2814 case LFUN_BUFFER_WRITE_AS:
2815 LASSERT(doc_buffer, break);
2816 renameBuffer(*doc_buffer, cmd.argument());
2819 case LFUN_BUFFER_WRITE_ALL: {
2820 Buffer * first = theBufferList().first();
2823 message(_("Saving all documents..."));
2824 // We cannot use a for loop as the buffer list cycles.
2827 if (!b->isClean()) {
2829 LYXERR(Debug::ACTION, "Saved " << b->absFileName());
2831 b = theBufferList().next(b);
2832 } while (b != first);
2833 message(_("All documents saved."));
2837 case LFUN_BUFFER_CLOSE:
2841 case LFUN_BUFFER_CLOSE_ALL:
2845 case LFUN_TOOLBAR_TOGGLE: {
2846 string const name = cmd.getArg(0);
2847 if (GuiToolbar * t = toolbar(name))
2852 case LFUN_DIALOG_UPDATE: {
2853 string const name = to_utf8(cmd.argument());
2854 if (currentBufferView()) {
2855 Inset * inset = currentBufferView()->editedInset(name);
2856 // Can only update a dialog connected to an existing inset
2859 // FIXME: get rid of this indirection; GuiView ask the inset
2860 // if he is kind enough to update itself...
2861 FuncRequest fr(LFUN_INSET_DIALOG_UPDATE, cmd.argument());
2862 inset->dispatch(currentBufferView()->cursor(), fr);
2863 } else if (name == "paragraph") {
2864 lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
2865 } else if (name == "prefs" || name == "document") {
2866 updateDialog(name, string());
2871 case LFUN_DIALOG_TOGGLE: {
2872 if (isDialogVisible(cmd.getArg(0)))
2873 dispatch(FuncRequest(LFUN_DIALOG_HIDE, cmd.argument()));
2875 dispatch(FuncRequest(LFUN_DIALOG_SHOW, cmd.argument()));
2879 case LFUN_DIALOG_DISCONNECT_INSET:
2880 disconnectDialog(to_utf8(cmd.argument()));
2883 case LFUN_DIALOG_HIDE: {
2884 guiApp->hideDialogs(to_utf8(cmd.argument()), 0);
2888 case LFUN_DIALOG_SHOW: {
2889 string const name = cmd.getArg(0);
2890 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
2892 if (name == "character") {
2893 data = freefont2string();
2895 showDialog("character", data);
2896 } else if (name == "latexlog") {
2897 Buffer::LogType type;
2898 string const logfile = doc_buffer->logName(&type);
2900 case Buffer::latexlog:
2903 case Buffer::buildlog:
2907 data += Lexer::quoteString(logfile);
2908 showDialog("log", data);
2909 } else if (name == "vclog") {
2910 string const data = "vc " +
2911 Lexer::quoteString(doc_buffer->lyxvc().getLogFile());
2912 showDialog("log", data);
2913 } else if (name == "symbols") {
2914 data = bv->cursor().getEncoding()->name();
2916 showDialog("symbols", data);
2918 } else if (name == "prefs" && isFullScreen()) {
2919 FuncRequest fr(LFUN_INSET_INSERT, "fullscreen");
2921 showDialog("prefs", data);
2923 showDialog(name, data);
2928 message(cmd.argument());
2931 case LFUN_UI_TOGGLE:
2933 // Make sure the keyboard focus stays in the work area.
2937 case LFUN_SPLIT_VIEW: {
2938 LASSERT(doc_buffer, break);
2939 string const orientation = cmd.getArg(0);
2940 d.splitter_->setOrientation(orientation == "vertical"
2941 ? Qt::Vertical : Qt::Horizontal);
2942 TabWorkArea * twa = addTabWorkArea();
2943 GuiWorkArea * wa = twa->addWorkArea(*doc_buffer, *this);
2944 setCurrentWorkArea(wa);
2947 case LFUN_CLOSE_TAB_GROUP:
2948 if (TabWorkArea * twa = d.currentTabWorkArea()) {
2949 closeTabWorkArea(twa);
2950 d.current_work_area_ = 0;
2951 twa = d.currentTabWorkArea();
2952 // Switch to the next GuiWorkArea in the found TabWorkArea.
2954 // Make sure the work area is up to date.
2955 setCurrentWorkArea(twa->currentWorkArea());
2957 setCurrentWorkArea(0);
2962 case LFUN_COMPLETION_INLINE:
2963 if (d.current_work_area_)
2964 d.current_work_area_->completer().showInline();
2967 case LFUN_COMPLETION_POPUP:
2968 if (d.current_work_area_)
2969 d.current_work_area_->completer().showPopup();
2973 case LFUN_COMPLETION_COMPLETE:
2974 if (d.current_work_area_)
2975 d.current_work_area_->completer().tab();
2978 case LFUN_COMPLETION_CANCEL:
2979 if (d.current_work_area_) {
2980 if (d.current_work_area_->completer().popupVisible())
2981 d.current_work_area_->completer().hidePopup();
2983 d.current_work_area_->completer().hideInline();
2987 case LFUN_COMPLETION_ACCEPT:
2988 if (d.current_work_area_)
2989 d.current_work_area_->completer().activate();
2992 case LFUN_BUFFER_ZOOM_IN:
2993 case LFUN_BUFFER_ZOOM_OUT:
2994 if (cmd.argument().empty()) {
2995 if (cmd.action == LFUN_BUFFER_ZOOM_IN)
3000 lyxrc.zoom += convert<int>(cmd.argument());
3002 if (lyxrc.zoom < 10)
3005 // The global QPixmapCache is used in GuiPainter to cache text
3006 // painting so we must reset it.
3007 QPixmapCache::clear();
3008 guiApp->fontLoader().update();
3009 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
3012 case LFUN_VC_REGISTER:
3013 case LFUN_VC_CHECK_IN:
3014 case LFUN_VC_CHECK_OUT:
3015 case LFUN_VC_REPO_UPDATE:
3016 case LFUN_VC_LOCKING_TOGGLE:
3017 case LFUN_VC_REVERT:
3018 case LFUN_VC_UNDO_LAST:
3019 case LFUN_VC_COMMAND:
3023 case LFUN_SERVER_GOTO_FILE_ROW:
3024 goToFileRow(to_utf8(cmd.argument()));
3032 // Part of automatic menu appearance feature.
3033 if (isFullScreen()) {
3034 if (menuBar()->isVisible() && lyxrc.full_screen_menubar)
3036 if (statusBar()->isVisible())
3037 statusBar()->hide();
3044 void GuiView::lfunUiToggle(FuncRequest const & cmd)
3046 string const arg = cmd.getArg(0);
3047 if (arg == "scrollbar") {
3048 // hide() is of no help
3049 if (d.current_work_area_->verticalScrollBarPolicy() ==
3050 Qt::ScrollBarAlwaysOff)
3052 d.current_work_area_->setVerticalScrollBarPolicy(
3053 Qt::ScrollBarAsNeeded);
3055 d.current_work_area_->setVerticalScrollBarPolicy(
3056 Qt::ScrollBarAlwaysOff);
3059 if (arg == "statusbar") {
3060 statusBar()->setVisible(!statusBar()->isVisible());
3063 if (arg == "menubar") {
3064 menuBar()->setVisible(!menuBar()->isVisible());
3067 #if QT_VERSION >= 0x040300
3068 if (arg == "frame") {
3070 getContentsMargins(&l, &t, &r, &b);
3071 //are the frames in default state?
3072 d.current_work_area_->setFrameStyle(QFrame::NoFrame);
3074 setContentsMargins(-2, -2, -2, -2);
3076 setContentsMargins(0, 0, 0, 0);
3081 if (arg == "fullscreen") {
3086 message(bformat("LFUN_UI_TOGGLE " + _("%1$s unknown command!"), from_utf8(arg)));
3090 void GuiView::toggleFullScreen()
3092 if (isFullScreen()) {
3093 for (int i = 0; i != d.splitter_->count(); ++i)
3094 d.tabWorkArea(i)->setFullScreen(false);
3095 #if QT_VERSION >= 0x040300
3096 setContentsMargins(0, 0, 0, 0);
3098 setWindowState(windowState() ^ Qt::WindowFullScreen);
3101 statusBar()->show();
3104 hideDialogs("prefs", 0);
3105 for (int i = 0; i != d.splitter_->count(); ++i)
3106 d.tabWorkArea(i)->setFullScreen(true);
3107 #if QT_VERSION >= 0x040300
3108 setContentsMargins(-2, -2, -2, -2);
3111 setWindowState(windowState() ^ Qt::WindowFullScreen);
3112 statusBar()->hide();
3113 if (lyxrc.full_screen_menubar)
3115 if (lyxrc.full_screen_toolbars) {
3116 ToolbarMap::iterator end = d.toolbars_.end();
3117 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
3122 // give dialogs like the TOC a chance to adapt
3127 Buffer const * GuiView::updateInset(Inset const * inset)
3129 if (!d.current_work_area_)
3133 d.current_work_area_->scheduleRedraw();
3135 return &d.current_work_area_->bufferView().buffer();
3139 void GuiView::restartCursor()
3141 /* When we move around, or type, it's nice to be able to see
3142 * the cursor immediately after the keypress.
3144 if (d.current_work_area_)
3145 d.current_work_area_->startBlinkingCursor();
3147 // Take this occasion to update the other GUI elements.
3153 void GuiView::updateCompletion(Cursor & cur, bool start, bool keep)
3155 if (d.current_work_area_)
3156 d.current_work_area_->completer().updateVisibility(cur, start, keep);
3161 // This list should be kept in sync with the list of insets in
3162 // src/insets/Inset.cpp. I.e., if a dialog goes with an inset, the
3163 // dialog should have the same name as the inset.
3164 // Changes should be also recorded in LFUN_DIALOG_SHOW doxygen
3165 // docs in LyXAction.cpp.
3167 char const * const dialognames[] = {
3168 "aboutlyx", "bibitem", "bibtex", "box", "branch", "changes", "character",
3169 "citation", "compare", "document", "errorlist", "ert", "external", "file",
3170 "findreplace", "findreplaceadv", "float", "graphics", "href", "include",
3171 "index", "index_print", "info", "listings", "label", "log", "mathdelimiter",
3172 "mathmatrix", "mathspace", "nomenclature", "nomencl_print", "note",
3173 "paragraph", "phantom", "prefs", "print", "ref", "sendto", "space",
3174 "spellchecker", "symbols", "tabular", "tabularcreate", "thesaurus", "texinfo",
3175 "toc", "view-source", "vspace", "wrap", "progress" };
3177 char const * const * const end_dialognames =
3178 dialognames + (sizeof(dialognames) / sizeof(char *));
3182 cmpCStr(char const * name) : name_(name) {}
3183 bool operator()(char const * other) {
3184 return strcmp(other, name_) == 0;
3191 bool isValidName(string const & name)
3193 return find_if(dialognames, end_dialognames,
3194 cmpCStr(name.c_str())) != end_dialognames;
3200 void GuiView::resetDialogs()
3202 // Make sure that no LFUN uses any LyXView.
3203 guiApp->setCurrentView(0);
3206 constructToolbars();
3207 guiApp->menus().fillMenuBar(menuBar(), this, false);
3208 d.layout_->updateContents(true);
3209 // Now update controls with current buffer.
3210 guiApp->setCurrentView(this);
3216 Dialog * GuiView::findOrBuild(string const & name, bool hide_it)
3218 if (!isValidName(name))
3221 map<string, DialogPtr>::iterator it = d.dialogs_.find(name);
3223 if (it != d.dialogs_.end()) {
3225 it->second->hideView();
3226 return it->second.get();
3229 Dialog * dialog = build(name);
3230 d.dialogs_[name].reset(dialog);
3231 if (lyxrc.allow_geometry_session)
3232 dialog->restoreSession();
3239 void GuiView::showDialog(string const & name, string const & data,
3247 Dialog * dialog = findOrBuild(name, false);
3249 dialog->showData(data);
3250 if (inset && currentBufferView())
3251 currentBufferView()->editInset(name, inset);
3254 catch (ExceptionMessage const & ex) {
3262 bool GuiView::isDialogVisible(string const & name) const
3264 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3265 if (it == d.dialogs_.end())
3267 return it->second.get()->isVisibleView() && !it->second.get()->isClosing();
3271 void GuiView::hideDialog(string const & name, Inset * inset)
3273 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3274 if (it == d.dialogs_.end())
3277 if (inset && currentBufferView()
3278 && inset != currentBufferView()->editedInset(name))
3281 Dialog * const dialog = it->second.get();
3282 if (dialog->isVisibleView())
3284 if (currentBufferView())
3285 currentBufferView()->editInset(name, 0);
3289 void GuiView::disconnectDialog(string const & name)
3291 if (!isValidName(name))
3293 if (currentBufferView())
3294 currentBufferView()->editInset(name, 0);
3298 void GuiView::hideAll() const
3300 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
3301 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3303 for(; it != end; ++it)
3304 it->second->hideView();
3308 void GuiView::updateDialogs()
3310 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
3311 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3313 for(; it != end; ++it) {
3314 Dialog * dialog = it->second.get();
3315 if (dialog && dialog->isVisibleView())
3316 dialog->checkStatus();
3323 // will be replaced by a proper factory...
3324 Dialog * createGuiAbout(GuiView & lv);
3325 Dialog * createGuiBibitem(GuiView & lv);
3326 Dialog * createGuiBibtex(GuiView & lv);
3327 Dialog * createGuiBox(GuiView & lv);
3328 Dialog * createGuiBranch(GuiView & lv);
3329 Dialog * createGuiChanges(GuiView & lv);
3330 Dialog * createGuiCharacter(GuiView & lv);
3331 Dialog * createGuiCitation(GuiView & lv);
3332 Dialog * createGuiCompare(GuiView & lv);
3333 Dialog * createGuiDelimiter(GuiView & lv);
3334 Dialog * createGuiDocument(GuiView & lv);
3335 Dialog * createGuiErrorList(GuiView & lv);
3336 Dialog * createGuiERT(GuiView & lv);
3337 Dialog * createGuiExternal(GuiView & lv);
3338 Dialog * createGuiFloat(GuiView & lv);
3339 Dialog * createGuiGraphics(GuiView & lv);
3340 Dialog * createGuiInclude(GuiView & lv);
3341 Dialog * createGuiIndex(GuiView & lv);
3342 Dialog * createGuiInfo(GuiView & lv);
3343 Dialog * createGuiLabel(GuiView & lv);
3344 Dialog * createGuiListings(GuiView & lv);
3345 Dialog * createGuiLog(GuiView & lv);
3346 Dialog * createGuiMathHSpace(GuiView & lv);
3347 Dialog * createGuiMathMatrix(GuiView & lv);
3348 Dialog * createGuiNomenclature(GuiView & lv);
3349 Dialog * createGuiNote(GuiView & lv);
3350 Dialog * createGuiParagraph(GuiView & lv);
3351 Dialog * createGuiPhantom(GuiView & lv);
3352 Dialog * createGuiPreferences(GuiView & lv);
3353 Dialog * createGuiPrint(GuiView & lv);
3354 Dialog * createGuiPrintindex(GuiView & lv);
3355 Dialog * createGuiPrintNomencl(GuiView & lv);
3356 Dialog * createGuiRef(GuiView & lv);
3357 Dialog * createGuiSearch(GuiView & lv);
3358 Dialog * createGuiSearchAdv(GuiView & lv);
3359 Dialog * createGuiSendTo(GuiView & lv);
3360 Dialog * createGuiShowFile(GuiView & lv);
3361 Dialog * createGuiSpellchecker(GuiView & lv);
3362 Dialog * createGuiSymbols(GuiView & lv);
3363 Dialog * createGuiTabularCreate(GuiView & lv);
3364 Dialog * createGuiTabular(GuiView & lv);
3365 Dialog * createGuiTexInfo(GuiView & lv);
3366 Dialog * createGuiTextHSpace(GuiView & lv);
3367 Dialog * createGuiToc(GuiView & lv);
3368 Dialog * createGuiThesaurus(GuiView & lv);
3369 Dialog * createGuiHyperlink(GuiView & lv);
3370 Dialog * createGuiVSpace(GuiView & lv);
3371 Dialog * createGuiViewSource(GuiView & lv);
3372 Dialog * createGuiWrap(GuiView & lv);
3373 Dialog * createGuiProgress(GuiView & lv);
3375 Dialog * GuiView::build(string const & name)
3377 LASSERT(isValidName(name), return 0);
3379 if (name == "aboutlyx")
3380 return createGuiAbout(*this);
3381 if (name == "bibitem")
3382 return createGuiBibitem(*this);
3383 if (name == "bibtex")
3384 return createGuiBibtex(*this);
3386 return createGuiBox(*this);
3387 if (name == "branch")
3388 return createGuiBranch(*this);
3389 if (name == "changes")
3390 return createGuiChanges(*this);
3391 if (name == "character")
3392 return createGuiCharacter(*this);
3393 if (name == "citation")
3394 return createGuiCitation(*this);
3395 if (name == "compare")
3396 return createGuiCompare(*this);
3397 if (name == "document")
3398 return createGuiDocument(*this);
3399 if (name == "errorlist")
3400 return createGuiErrorList(*this);
3402 return createGuiERT(*this);
3403 if (name == "external")
3404 return createGuiExternal(*this);
3406 return createGuiShowFile(*this);
3407 if (name == "findreplace")
3408 return createGuiSearch(*this);
3409 if (name == "findreplaceadv")
3410 return createGuiSearchAdv(*this);
3411 if (name == "float")
3412 return createGuiFloat(*this);
3413 if (name == "graphics")
3414 return createGuiGraphics(*this);
3416 return createGuiHyperlink(*this);
3417 if (name == "include")
3418 return createGuiInclude(*this);
3419 if (name == "index")
3420 return createGuiIndex(*this);
3421 if (name == "index_print")
3422 return createGuiPrintindex(*this);
3424 return createGuiInfo(*this);
3425 if (name == "label")
3426 return createGuiLabel(*this);
3427 if (name == "listings")
3428 return createGuiListings(*this);
3430 return createGuiLog(*this);
3431 if (name == "mathdelimiter")
3432 return createGuiDelimiter(*this);
3433 if (name == "mathspace")
3434 return createGuiMathHSpace(*this);
3435 if (name == "mathmatrix")
3436 return createGuiMathMatrix(*this);
3437 if (name == "nomenclature")
3438 return createGuiNomenclature(*this);
3439 if (name == "nomencl_print")
3440 return createGuiPrintNomencl(*this);
3442 return createGuiNote(*this);
3443 if (name == "paragraph")
3444 return createGuiParagraph(*this);
3445 if (name == "phantom")
3446 return createGuiPhantom(*this);
3447 if (name == "prefs")
3448 return createGuiPreferences(*this);
3449 if (name == "print")
3450 return createGuiPrint(*this);
3452 return createGuiRef(*this);
3453 if (name == "sendto")
3454 return createGuiSendTo(*this);
3455 if (name == "space")
3456 return createGuiTextHSpace(*this);
3457 if (name == "spellchecker")
3458 return createGuiSpellchecker(*this);
3459 if (name == "symbols")
3460 return createGuiSymbols(*this);
3461 if (name == "tabular")
3462 return createGuiTabular(*this);
3463 if (name == "tabularcreate")
3464 return createGuiTabularCreate(*this);
3465 if (name == "texinfo")
3466 return createGuiTexInfo(*this);
3467 if (name == "thesaurus")
3468 return createGuiThesaurus(*this);
3470 return createGuiToc(*this);
3471 if (name == "view-source")
3472 return createGuiViewSource(*this);
3473 if (name == "vspace")
3474 return createGuiVSpace(*this);
3476 return createGuiWrap(*this);
3477 if (name == "progress")
3478 return createGuiProgress(*this);
3484 } // namespace frontend
3487 #include "moc_GuiView.cpp"