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
179 : 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);
269 GuiWorkArea * current_work_area_;
270 GuiWorkArea * current_main_work_area_;
271 QSplitter * splitter_;
272 QStackedWidget * stack_widget_;
273 BackgroundWidget * bg_widget_;
275 ToolbarMap toolbars_;
276 /// The main layout box.
278 * \warning Don't Delete! The layout box is actually owned by
279 * whichever toolbar contains it. All the GuiView class needs is a
280 * means of accessing it.
282 * FIXME: replace that with a proper model so that we are not limited
283 * to only one dialog.
288 map<string, DialogPtr> dialogs_;
290 unsigned int smallIconSize;
291 unsigned int normalIconSize;
292 unsigned int bigIconSize;
294 QTimer statusbar_timer_;
295 /// auto-saving of buffers
296 Timeout autosave_timeout_;
297 /// flag against a race condition due to multiclicks, see bug #1119
301 TocModels toc_models_;
303 #if (QT_VERSION >= 0x040400)
305 QFutureWatcher<docstring> autosave_watcher_;
306 QFutureWatcher<docstring> preview_watcher_;
311 GuiView::GuiView(int id)
312 : d(*new GuiViewPrivate), id_(id), closing_(false)
314 // GuiToolbars *must* be initialised before the menu bar.
315 normalSizedIcons(); // at least on Mac the default is 32 otherwise, which is huge
318 // set ourself as the current view. This is needed for the menu bar
319 // filling, at least for the static special menu item on Mac. Otherwise
320 // they are greyed out.
321 guiApp->setCurrentView(this);
323 // Fill up the menu bar.
324 guiApp->menus().fillMenuBar(menuBar(), this, true);
326 setCentralWidget(d.stack_widget_);
328 // Start autosave timer
329 if (lyxrc.autosave) {
330 d.autosave_timeout_.timeout.connect(boost::bind(&GuiView::autoSave, this));
331 d.autosave_timeout_.setTimeout(lyxrc.autosave * 1000);
332 d.autosave_timeout_.start();
334 connect(&d.statusbar_timer_, SIGNAL(timeout()),
335 this, SLOT(clearMessage()));
337 // We don't want to keep the window in memory if it is closed.
338 setAttribute(Qt::WA_DeleteOnClose, true);
340 #if (!defined(Q_WS_WIN) && !defined(Q_WS_MACX))
341 // assign an icon to main form. We do not do it under Qt/Win or Qt/Mac,
342 // since the icon is provided in the application bundle.
343 setWindowIcon(getPixmap("images/", "lyx", "png"));
347 setAcceptDrops(true);
349 statusBar()->setSizeGripEnabled(true);
351 // Forbid too small unresizable window because it can happen
352 // with some window manager under X11.
353 setMinimumSize(300, 200);
355 if (lyxrc.allow_geometry_session) {
356 // Now take care of session management.
361 // no session handling, default to a sane size.
362 setGeometry(50, 50, 690, 510);
365 // clear session data if any.
367 settings.remove("views");
369 #if (QT_VERSION >= 0x040400)
370 connect(&d.autosave_watcher_, SIGNAL(finished()), this,
371 SLOT(threadFinished()));
372 connect(&d.preview_watcher_, SIGNAL(finished()), this,
373 SLOT(threadFinished()));
384 void GuiView::threadFinished()
386 #if (QT_VERSION >= 0x040400)
387 QFutureWatcher<docstring> const * watcher =
388 static_cast<QFutureWatcher<docstring> const *>(sender());
389 message(watcher->result());
394 void GuiView::saveLayout() const
397 settings.beginGroup("views");
398 settings.beginGroup(QString::number(id_));
400 settings.setValue("pos", pos());
401 settings.setValue("size", size());
403 settings.setValue("geometry", saveGeometry());
405 settings.setValue("layout", saveState(0));
406 settings.setValue("icon_size", iconSize());
410 bool GuiView::restoreLayout()
413 settings.beginGroup("views");
414 settings.beginGroup(QString::number(id_));
415 QString const icon_key = "icon_size";
416 if (!settings.contains(icon_key))
419 //code below is skipped when when ~/.config/LyX is (re)created
420 setIconSize(settings.value(icon_key).toSize());
422 QPoint pos = settings.value("pos", QPoint(50, 50)).toPoint();
423 QSize size = settings.value("size", QSize(690, 510)).toSize();
427 // Work-around for bug #6034: the window ends up in an undetermined
428 // state when trying to restore a maximized window when it is
429 // already maximized.
430 if (!(windowState() & Qt::WindowMaximized))
431 if (!restoreGeometry(settings.value("geometry").toByteArray()))
432 setGeometry(50, 50, 690, 510);
434 // Make sure layout is correctly oriented.
435 setLayoutDirection(qApp->layoutDirection());
437 // Allow the toc and view-source dock widget to be restored if needed.
439 if ((dialog = findOrBuild("toc", true)))
440 // see bug 5082. At least setup title and enabled state.
441 // Visibility will be adjusted by restoreState below.
442 dialog->prepareView();
443 if ((dialog = findOrBuild("view-source", true)))
444 dialog->prepareView();
446 if (!restoreState(settings.value("layout").toByteArray(), 0))
453 GuiToolbar * GuiView::toolbar(string const & name)
455 ToolbarMap::iterator it = d.toolbars_.find(name);
456 if (it != d.toolbars_.end())
459 LYXERR(Debug::GUI, "Toolbar::display: no toolbar named " << name);
460 message(bformat(_("Unknown toolbar \"%1$s\""), from_utf8(name)));
465 void GuiView::constructToolbars()
467 ToolbarMap::iterator it = d.toolbars_.begin();
468 for (; it != d.toolbars_.end(); ++it)
472 // I don't like doing this here, but the standard toolbar
473 // destroys this object when it's destroyed itself (vfr)
474 d.layout_ = new LayoutBox(*this);
475 d.stack_widget_->addWidget(d.layout_);
476 d.layout_->move(0,0);
478 // extracts the toolbars from the backend
479 Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
480 Toolbars::Infos::iterator end = guiApp->toolbars().end();
481 for (; cit != end; ++cit)
482 d.toolbars_[cit->name] = new GuiToolbar(*cit, *this);
486 void GuiView::initToolbars()
488 // extracts the toolbars from the backend
489 Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
490 Toolbars::Infos::iterator end = guiApp->toolbars().end();
491 for (; cit != end; ++cit) {
492 GuiToolbar * tb = toolbar(cit->name);
495 int const visibility = guiApp->toolbars().defaultVisibility(cit->name);
497 tb->setVisible(false);
498 tb->setVisibility(visibility);
500 if (visibility & Toolbars::TOP) {
502 addToolBarBreak(Qt::TopToolBarArea);
503 addToolBar(Qt::TopToolBarArea, tb);
506 if (visibility & Toolbars::BOTTOM) {
507 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
508 #if (QT_VERSION >= 0x040202)
509 addToolBarBreak(Qt::BottomToolBarArea);
511 addToolBar(Qt::BottomToolBarArea, tb);
514 if (visibility & Toolbars::LEFT) {
515 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
516 #if (QT_VERSION >= 0x040202)
517 addToolBarBreak(Qt::LeftToolBarArea);
519 addToolBar(Qt::LeftToolBarArea, tb);
522 if (visibility & Toolbars::RIGHT) {
523 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
524 #if (QT_VERSION >= 0x040202)
525 addToolBarBreak(Qt::RightToolBarArea);
527 addToolBar(Qt::RightToolBarArea, tb);
530 if (visibility & Toolbars::ON)
531 tb->setVisible(true);
536 TocModels & GuiView::tocModels()
538 return d.toc_models_;
542 void GuiView::setFocus()
544 LYXERR(Debug::DEBUG, "GuiView::setFocus()" << this);
545 // Make sure LyXFunc points to the correct view.
546 guiApp->setCurrentView(this);
547 QMainWindow::setFocus();
548 if (d.current_work_area_)
549 d.current_work_area_->setFocus();
553 QMenu * GuiView::createPopupMenu()
555 return d.toolBarPopup(this);
559 void GuiView::showEvent(QShowEvent * e)
561 LYXERR(Debug::GUI, "Passed Geometry "
562 << size().height() << "x" << size().width()
563 << "+" << pos().x() << "+" << pos().y());
565 if (d.splitter_->count() == 0)
566 // No work area, switch to the background widget.
569 QMainWindow::showEvent(e);
573 /** Destroy only all tabbed WorkAreas. Destruction of other WorkAreas
574 ** is responsibility of the container (e.g., dialog)
576 void GuiView::closeEvent(QCloseEvent * close_event)
578 LYXERR(Debug::DEBUG, "GuiView::closeEvent()");
583 // it can happen that this event arrives without selecting the view,
584 // e.g. when clicking the close button on a background window.
586 if (!closeWorkAreaAll()) {
588 close_event->ignore();
592 // Make sure that nothing will use this to be closed View.
593 guiApp->unregisterView(this);
595 if (isFullScreen()) {
596 // Switch off fullscreen before closing.
601 // Make sure the timer time out will not trigger a statusbar update.
602 d.statusbar_timer_.stop();
604 // Saving fullscreen requires additional tweaks in the toolbar code.
605 // It wouldn't also work under linux natively.
606 if (lyxrc.allow_geometry_session) {
607 // Save this window geometry and layout.
609 // Then the toolbar private states.
610 ToolbarMap::iterator end = d.toolbars_.end();
611 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
612 it->second->saveSession();
613 // Now take care of all other dialogs:
614 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
615 for (; it!= d.dialogs_.end(); ++it)
616 it->second->saveSession();
619 close_event->accept();
623 void GuiView::dragEnterEvent(QDragEnterEvent * event)
625 if (event->mimeData()->hasUrls())
627 /// \todo Ask lyx-devel is this is enough:
628 /// if (event->mimeData()->hasFormat("text/plain"))
629 /// event->acceptProposedAction();
633 void GuiView::dropEvent(QDropEvent * event)
635 QList<QUrl> files = event->mimeData()->urls();
639 LYXERR(Debug::GUI, "GuiView::dropEvent: got URLs!");
640 for (int i = 0; i != files.size(); ++i) {
641 string const file = os::internal_path(fromqstr(
642 files.at(i).toLocalFile()));
646 string const ext = support::getExtension(file);
647 vector<const Format *> found_formats;
649 // Find all formats that have the correct extension.
650 vector<const Format *> const & import_formats
651 = theConverters().importableFormats();
652 vector<const Format *>::const_iterator it = import_formats.begin();
653 for (; it != import_formats.end(); ++it)
654 if ((*it)->extension() == ext)
655 found_formats.push_back(*it);
658 if (found_formats.size() >= 1) {
659 if (found_formats.size() > 1) {
660 //FIXME: show a dialog to choose the correct importable format
662 "Multiple importable formats found, selecting first");
664 string const arg = found_formats[0]->name() + " " + file;
665 cmd = FuncRequest(LFUN_BUFFER_IMPORT, arg);
668 //FIXME: do we have to explicitly check whether it's a lyx file?
670 "No formats found, trying to open it as a lyx file");
671 cmd = FuncRequest(LFUN_FILE_OPEN, file);
674 // Asynchronously post the event. DropEvent usually come
675 // from the BufferView. But reloading a file might close
676 // the BufferView from within its own event handler.
677 guiApp->dispatchDelayed(cmd);
683 void GuiView::message(docstring const & str)
685 if (ForkedProcess::iAmAChild())
688 statusBar()->showMessage(toqstr(str));
689 d.statusbar_timer_.stop();
690 d.statusbar_timer_.start(3000);
694 void GuiView::smallSizedIcons()
696 setIconSize(QSize(d.smallIconSize, d.smallIconSize));
700 void GuiView::normalSizedIcons()
702 setIconSize(QSize(d.normalIconSize, d.normalIconSize));
706 void GuiView::bigSizedIcons()
708 setIconSize(QSize(d.bigIconSize, d.bigIconSize));
712 void GuiView::clearMessage()
717 d.statusbar_timer_.stop();
721 void GuiView::updateWindowTitle(GuiWorkArea * wa)
723 if (wa != d.current_work_area_)
725 setWindowTitle(qt_("LyX: ") + wa->windowTitle());
726 setWindowIconText(wa->windowIconText());
730 void GuiView::on_currentWorkAreaChanged(GuiWorkArea * wa)
733 disconnectBufferView();
734 connectBufferView(wa->bufferView());
735 connectBuffer(wa->bufferView().buffer());
736 d.current_work_area_ = wa;
737 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
738 this, SLOT(updateWindowTitle(GuiWorkArea *)));
739 updateWindowTitle(wa);
743 // The document settings needs to be reinitialised.
744 updateDialog("document", "");
746 // Buffer-dependent dialogs must be updated. This is done here because
747 // some dialogs require buffer()->text.
752 void GuiView::on_lastWorkAreaRemoved()
755 // We already are in a close event. Nothing more to do.
758 if (d.splitter_->count() > 1)
759 // We have a splitter so don't close anything.
762 // Reset and updates the dialogs.
763 d.toc_models_.reset(0);
764 updateDialog("document", "");
767 resetWindowTitleAndIconText();
769 if (lyxrc.open_buffers_in_tabs)
770 // Nothing more to do, the window should stay open.
773 if (guiApp->viewIds().size() > 1) {
779 // On Mac we also close the last window because the application stay
780 // resident in memory. On other platforms we don't close the last
781 // window because this would quit the application.
787 void GuiView::updateStatusBar()
789 // let the user see the explicit message
790 if (d.statusbar_timer_.isActive())
797 void GuiView::showMessage()
799 QString msg = toqstr(theGuiApp()->viewStatusMessage());
801 BufferView const * bv = currentBufferView();
803 msg = toqstr(bv->cursor().currentState());
805 msg = qt_("Welcome to LyX!");
807 statusBar()->showMessage(msg);
811 bool GuiView::event(QEvent * e)
815 // Useful debug code:
816 //case QEvent::ActivationChange:
817 //case QEvent::WindowDeactivate:
818 //case QEvent::Paint:
819 //case QEvent::Enter:
820 //case QEvent::Leave:
821 //case QEvent::HoverEnter:
822 //case QEvent::HoverLeave:
823 //case QEvent::HoverMove:
824 //case QEvent::StatusTip:
825 //case QEvent::DragEnter:
826 //case QEvent::DragLeave:
830 case QEvent::WindowActivate: {
831 GuiView * old_view = guiApp->currentView();
832 if (this == old_view) {
834 return QMainWindow::event(e);
836 if (old_view && old_view->currentBufferView()) {
837 // save current selection to the selection buffer to allow
838 // middle-button paste in this window.
839 cap::saveSelection(old_view->currentBufferView()->cursor());
841 guiApp->setCurrentView(this);
842 if (d.current_work_area_) {
843 BufferView & bv = d.current_work_area_->bufferView();
844 connectBufferView(bv);
845 connectBuffer(bv.buffer());
846 // The document structure, name and dialogs might have
847 // changed in another view.
849 // The document settings needs to be reinitialised.
850 updateDialog("document", "");
853 resetWindowTitleAndIconText();
856 return QMainWindow::event(e);
859 case QEvent::ShortcutOverride: {
862 #if (!defined Q_WS_X11) || (QT_VERSION >= 0x040500)
863 if (isFullScreen() && menuBar()->isHidden()) {
864 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
865 // FIXME: we should also try to detect special LyX shortcut such as
866 // Alt-P and Alt-M. Right now there is a hack in
867 // GuiWorkArea::processKeySym() that hides again the menubar for
869 if (ke->modifiers() & Qt::AltModifier && ke->key() != Qt::Key_Alt) {
871 return QMainWindow::event(e);
876 if (d.current_work_area_)
877 // Nothing special to do.
878 return QMainWindow::event(e);
880 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
881 // Let Qt handle menu access and the Tab keys to navigate keys to navigate
883 if (ke->modifiers() & Qt::AltModifier || ke->key() == Qt::Key_Tab
884 || ke->key() == Qt::Key_Backtab)
885 return QMainWindow::event(e);
887 // Allow processing of shortcuts that are allowed even when no Buffer
890 setKeySymbol(&sym, ke);
891 guiApp->processKeySym(sym, q_key_state(ke->modifiers()));
897 return QMainWindow::event(e);
901 void GuiView::resetWindowTitleAndIconText()
903 setWindowTitle(qt_("LyX"));
904 setWindowIconText(qt_("LyX"));
907 bool GuiView::focusNextPrevChild(bool /*next*/)
914 void GuiView::setBusy(bool busy)
916 if (d.current_work_area_) {
917 d.current_work_area_->setUpdatesEnabled(!busy);
919 d.current_work_area_->stopBlinkingCursor();
921 d.current_work_area_->startBlinkingCursor();
925 QApplication::setOverrideCursor(Qt::WaitCursor);
927 QApplication::restoreOverrideCursor();
931 GuiWorkArea * GuiView::workArea(Buffer & buffer)
933 if (currentWorkArea()
934 && ¤tWorkArea()->bufferView().buffer() == &buffer)
935 return (GuiWorkArea *) currentWorkArea();
936 if (TabWorkArea * twa = d.currentTabWorkArea())
937 return twa->workArea(buffer);
942 GuiWorkArea * GuiView::addWorkArea(Buffer & buffer)
944 // Automatically create a TabWorkArea if there are none yet.
945 TabWorkArea * tab_widget = d.splitter_->count()
946 ? d.currentTabWorkArea() : addTabWorkArea();
947 return tab_widget->addWorkArea(buffer, *this);
951 TabWorkArea * GuiView::addTabWorkArea()
953 TabWorkArea * twa = new TabWorkArea;
954 QObject::connect(twa, SIGNAL(currentWorkAreaChanged(GuiWorkArea *)),
955 this, SLOT(on_currentWorkAreaChanged(GuiWorkArea *)));
956 QObject::connect(twa, SIGNAL(lastWorkAreaRemoved()),
957 this, SLOT(on_lastWorkAreaRemoved()));
959 d.splitter_->addWidget(twa);
960 d.stack_widget_->setCurrentWidget(d.splitter_);
965 GuiWorkArea const * GuiView::currentWorkArea() const
967 return d.current_work_area_;
971 GuiWorkArea * GuiView::currentWorkArea()
973 return d.current_work_area_;
977 GuiWorkArea const * GuiView::currentMainWorkArea() const
979 if (d.currentTabWorkArea() == NULL)
981 return d.currentTabWorkArea()->currentWorkArea();
985 GuiWorkArea * GuiView::currentMainWorkArea()
987 if (d.currentTabWorkArea() == NULL)
989 return d.currentTabWorkArea()->currentWorkArea();
993 void GuiView::setCurrentWorkArea(GuiWorkArea * wa)
995 LYXERR(Debug::DEBUG, "Setting current wa: " << wa << endl);
997 d.current_work_area_ = NULL;
1001 GuiWorkArea * old_gwa = theGuiApp()->currentView()->currentWorkArea();
1005 if (currentBufferView())
1006 cap::saveSelection(currentBufferView()->cursor());
1008 theGuiApp()->setCurrentView(this);
1009 d.current_work_area_ = wa;
1010 for (int i = 0; i != d.splitter_->count(); ++i) {
1011 if (d.tabWorkArea(i)->setCurrentWorkArea(wa)) {
1012 //if (d.current_main_work_area_)
1013 // d.current_main_work_area_->setFrameStyle(QFrame::NoFrame);
1014 d.current_main_work_area_ = wa;
1015 //d.current_main_work_area_->setFrameStyle(QFrame::Box | QFrame::Plain);
1016 //d.current_main_work_area_->setLineWidth(2);
1017 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() << ", Current main wa: " << currentMainWorkArea());
1021 LYXERR(Debug::DEBUG, "This is not a tabbed wa");
1022 on_currentWorkAreaChanged(wa);
1023 BufferView & bv = wa->bufferView();
1024 bv.cursor().fixIfBroken();
1026 wa->setUpdatesEnabled(true);
1027 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() << ", Current main wa: " << currentMainWorkArea());
1031 void GuiView::removeWorkArea(GuiWorkArea * wa)
1033 LASSERT(wa, return);
1034 if (wa == d.current_work_area_) {
1036 disconnectBufferView();
1037 d.current_work_area_ = 0;
1038 d.current_main_work_area_ = 0;
1041 bool found_twa = false;
1042 for (int i = 0; i != d.splitter_->count(); ++i) {
1043 TabWorkArea * twa = d.tabWorkArea(i);
1044 if (twa->removeWorkArea(wa)) {
1045 // Found in this tab group, and deleted the GuiWorkArea.
1047 if (twa->count() != 0) {
1048 if (d.current_work_area_ == 0)
1049 // This means that we are closing the current GuiWorkArea, so
1050 // switch to the next GuiWorkArea in the found TabWorkArea.
1051 setCurrentWorkArea(twa->currentWorkArea());
1053 // No more WorkAreas in this tab group, so delete it.
1060 // It is not a tabbed work area (i.e., the search work area), so it
1061 // should be deleted by other means.
1062 LASSERT(found_twa, /* */);
1064 if (d.current_work_area_ == 0) {
1065 if (d.splitter_->count() != 0) {
1066 TabWorkArea * twa = d.currentTabWorkArea();
1067 setCurrentWorkArea(twa->currentWorkArea());
1069 // No more work areas, switch to the background widget.
1070 setCurrentWorkArea(0);
1076 LayoutBox * GuiView::getLayoutDialog() const
1082 void GuiView::updateLayoutList()
1085 d.layout_->updateContents(false);
1089 void GuiView::updateToolbars()
1091 ToolbarMap::iterator end = d.toolbars_.end();
1092 if (d.current_work_area_) {
1094 d.current_work_area_->bufferView().cursor().inMathed();
1096 lyx::getStatus(FuncRequest(LFUN_LAYOUT_TABULAR)).enabled();
1098 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).enabled() &&
1099 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).onoff(true);
1100 bool const mathmacrotemplate =
1101 lyx::getStatus(FuncRequest(LFUN_IN_MATHMACROTEMPLATE)).enabled();
1103 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1104 it->second->update(math, table, review, mathmacrotemplate);
1106 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1107 it->second->update(false, false, false, false);
1111 void GuiView::setBuffer(Buffer * newBuffer)
1113 LYXERR(Debug::DEBUG, "Setting buffer: " << newBuffer << std::endl);
1114 LASSERT(newBuffer, return);
1117 GuiWorkArea * wa = workArea(*newBuffer);
1119 newBuffer->masterBuffer()->updateLabels();
1120 wa = addWorkArea(*newBuffer);
1122 //Disconnect the old buffer...there's no new one.
1125 connectBuffer(*newBuffer);
1126 connectBufferView(wa->bufferView());
1127 setCurrentWorkArea(wa);
1133 void GuiView::connectBuffer(Buffer & buf)
1135 buf.setGuiDelegate(this);
1139 void GuiView::disconnectBuffer()
1141 if (d.current_work_area_)
1142 d.current_work_area_->bufferView().buffer().setGuiDelegate(0);
1146 void GuiView::connectBufferView(BufferView & bv)
1148 bv.setGuiDelegate(this);
1152 void GuiView::disconnectBufferView()
1154 if (d.current_work_area_)
1155 d.current_work_area_->bufferView().setGuiDelegate(0);
1159 void GuiView::errors(string const & error_type, bool from_master)
1161 ErrorList & el = from_master ?
1162 documentBufferView()->buffer().masterBuffer()->errorList(error_type)
1163 : documentBufferView()->buffer().errorList(error_type);
1164 string data = error_type;
1166 data = "from_master|" + error_type;
1168 showDialog("errorlist", data);
1172 void GuiView::updateTocItem(std::string const & type, DocIterator const & dit)
1174 d.toc_models_.updateItem(toqstr(type), dit);
1178 void GuiView::structureChanged()
1180 d.toc_models_.reset(documentBufferView());
1181 // Navigator needs more than a simple update in this case. It needs to be
1183 updateDialog("toc", "");
1187 void GuiView::updateDialog(string const & name, string const & data)
1189 if (!isDialogVisible(name))
1192 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
1193 if (it == d.dialogs_.end())
1196 Dialog * const dialog = it->second.get();
1197 if (dialog->isVisibleView())
1198 dialog->initialiseParams(data);
1202 BufferView * GuiView::documentBufferView()
1204 return currentMainWorkArea()
1205 ? ¤tMainWorkArea()->bufferView()
1210 BufferView const * GuiView::documentBufferView() const
1212 return currentMainWorkArea()
1213 ? ¤tMainWorkArea()->bufferView()
1218 BufferView * GuiView::currentBufferView()
1220 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1224 BufferView const * GuiView::currentBufferView() const
1226 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1230 static docstring saveAndDestroyBuffer(Buffer * buffer, FileName const & fname)
1233 FileName const tmp_ret = FileName::tempName("lyxauto");
1234 if (!tmp_ret.empty()) {
1235 if (buffer->writeFile(tmp_ret))
1236 failed = !tmp_ret.moveTo(fname);
1239 // failed to write/rename tmp_ret so try writing direct
1240 failed = buffer->writeFile(fname);
1244 ? _("Automatic save failed!")
1245 : _("Automatic save done.");
1249 void GuiView::autoSave()
1251 LYXERR(Debug::INFO, "Running autoSave()");
1253 Buffer * buffer = documentBufferView()
1254 ? &documentBufferView()->buffer() : 0;
1258 #if (QT_VERSION >= 0x040400)
1259 QFuture<docstring> f = QtConcurrent::run(saveAndDestroyBuffer, buffer->clone(),
1260 buffer->getAutosaveFilename());
1261 d.autosave_watcher_.setFuture(f);
1268 void GuiView::resetAutosaveTimers()
1271 d.autosave_timeout_.restart();
1275 bool GuiView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1278 Buffer * buf = currentBufferView()
1279 ? ¤tBufferView()->buffer() : 0;
1280 Buffer * doc_buffer = documentBufferView()
1281 ? &(documentBufferView()->buffer()) : 0;
1283 // Check whether we need a buffer
1284 if (!lyxaction.funcHasFlag(cmd.action, LyXAction::NoBuffer) && !buf) {
1285 // no, exit directly
1286 flag.message(from_utf8(N_("Command not allowed with"
1287 "out any document open")));
1288 flag.setEnabled(false);
1292 if (cmd.origin == FuncRequest::TOC) {
1293 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
1295 if (toc->getStatus(documentBufferView()->cursor(), cmd, fs))
1298 flag.setEnabled(false);
1302 switch(cmd.action) {
1303 case LFUN_BUFFER_IMPORT:
1306 case LFUN_MASTER_BUFFER_UPDATE:
1307 case LFUN_MASTER_BUFFER_VIEW:
1308 enable = doc_buffer && doc_buffer->parent() != 0;
1311 case LFUN_BUFFER_UPDATE:
1312 case LFUN_BUFFER_VIEW: {
1317 string format = to_utf8(cmd.argument());
1318 if (cmd.argument().empty())
1319 format = doc_buffer->getDefaultOutputFormat();
1320 enable = doc_buffer->isExportableFormat(format);
1324 case LFUN_BUFFER_RELOAD:
1325 enable = doc_buffer && !doc_buffer->isUnnamed()
1326 && doc_buffer->fileName().exists()
1327 && (!doc_buffer->isClean()
1328 || doc_buffer->isExternallyModified(Buffer::timestamp_method));
1331 case LFUN_BUFFER_CHILD_OPEN:
1332 enable = doc_buffer;
1335 case LFUN_BUFFER_WRITE:
1336 enable = doc_buffer && (doc_buffer->isUnnamed() || !doc_buffer->isClean());
1339 //FIXME: This LFUN should be moved to GuiApplication.
1340 case LFUN_BUFFER_WRITE_ALL: {
1341 // We enable the command only if there are some modified buffers
1342 Buffer * first = theBufferList().first();
1347 // We cannot use a for loop as the buffer list is a cycle.
1349 if (!b->isClean()) {
1353 b = theBufferList().next(b);
1354 } while (b != first);
1358 case LFUN_BUFFER_WRITE_AS:
1359 enable = doc_buffer;
1362 case LFUN_BUFFER_CLOSE:
1363 enable = doc_buffer;
1366 case LFUN_BUFFER_CLOSE_ALL:
1367 enable = theBufferList().last() != theBufferList().first();
1370 case LFUN_SPLIT_VIEW:
1371 if (cmd.getArg(0) == "vertical")
1372 enable = doc_buffer && (d.splitter_->count() == 1 ||
1373 d.splitter_->orientation() == Qt::Vertical);
1375 enable = doc_buffer && (d.splitter_->count() == 1 ||
1376 d.splitter_->orientation() == Qt::Horizontal);
1379 case LFUN_CLOSE_TAB_GROUP:
1380 enable = d.currentTabWorkArea();
1383 case LFUN_TOOLBAR_TOGGLE:
1384 if (GuiToolbar * t = toolbar(cmd.getArg(0)))
1385 flag.setOnOff(t->isVisible());
1388 case LFUN_DROP_LAYOUTS_CHOICE:
1392 case LFUN_UI_TOGGLE:
1393 flag.setOnOff(isFullScreen());
1396 case LFUN_DIALOG_DISCONNECT_INSET:
1399 case LFUN_DIALOG_HIDE:
1400 // FIXME: should we check if the dialog is shown?
1403 case LFUN_DIALOG_TOGGLE:
1404 flag.setOnOff(isDialogVisible(cmd.getArg(0)));
1405 // fall through to set "enable"
1406 case LFUN_DIALOG_SHOW: {
1407 string const name = cmd.getArg(0);
1409 enable = name == "aboutlyx"
1410 || name == "file" //FIXME: should be removed.
1412 || name == "texinfo"
1413 || name == "compare";
1414 else if (name == "print")
1415 enable = doc_buffer->isExportable("dvi")
1416 && lyxrc.print_command != "none";
1417 else if (name == "character" || name == "symbols") {
1418 if (!buf || buf->isReadonly()
1419 || !currentBufferView()->cursor().inTexted())
1422 // FIXME we should consider passthru
1424 Inset const & in = currentBufferView()->cursor().inset();
1425 enable = !in.getLayout().isPassThru();
1428 else if (name == "latexlog")
1429 enable = FileName(doc_buffer->logName()).isReadableFile();
1430 else if (name == "spellchecker")
1431 enable = theSpellChecker() && !doc_buffer->isReadonly();
1432 else if (name == "vclog")
1433 enable = doc_buffer->lyxvc().inUse();
1437 case LFUN_DIALOG_UPDATE: {
1438 string const name = cmd.getArg(0);
1440 enable = name == "prefs";
1444 case LFUN_COMMAND_EXECUTE:
1446 case LFUN_MENU_OPEN:
1447 // Nothing to check.
1450 case LFUN_COMPLETION_INLINE:
1451 if (!d.current_work_area_
1452 || !d.current_work_area_->completer().inlinePossible(
1453 currentBufferView()->cursor()))
1457 case LFUN_COMPLETION_POPUP:
1458 if (!d.current_work_area_
1459 || !d.current_work_area_->completer().popupPossible(
1460 currentBufferView()->cursor()))
1464 case LFUN_COMPLETION_COMPLETE:
1465 if (!d.current_work_area_
1466 || !d.current_work_area_->completer().inlinePossible(
1467 currentBufferView()->cursor()))
1471 case LFUN_COMPLETION_ACCEPT:
1472 if (!d.current_work_area_
1473 || (!d.current_work_area_->completer().popupVisible()
1474 && !d.current_work_area_->completer().inlineVisible()
1475 && !d.current_work_area_->completer().completionAvailable()))
1479 case LFUN_COMPLETION_CANCEL:
1480 if (!d.current_work_area_
1481 || (!d.current_work_area_->completer().popupVisible()
1482 && !d.current_work_area_->completer().inlineVisible()))
1486 case LFUN_BUFFER_ZOOM_OUT:
1487 enable = doc_buffer && lyxrc.zoom > 10;
1490 case LFUN_BUFFER_ZOOM_IN:
1491 enable = doc_buffer;
1494 case LFUN_BUFFER_NEXT:
1495 case LFUN_BUFFER_PREVIOUS:
1496 // FIXME: should we check is there is an previous or next buffer?
1498 case LFUN_BUFFER_SWITCH:
1499 // toggle on the current buffer, but do not toggle off
1500 // the other ones (is that a good idea?)
1502 && to_utf8(cmd.argument()) == doc_buffer->absFileName())
1503 flag.setOnOff(true);
1506 case LFUN_VC_REGISTER:
1507 enable = doc_buffer && !doc_buffer->lyxvc().inUse();
1509 case LFUN_VC_CHECK_IN:
1510 enable = doc_buffer && doc_buffer->lyxvc().checkInEnabled();
1512 case LFUN_VC_CHECK_OUT:
1513 enable = doc_buffer && doc_buffer->lyxvc().checkOutEnabled();
1515 case LFUN_VC_LOCKING_TOGGLE:
1516 enable = doc_buffer && !doc_buffer->isReadonly()
1517 && doc_buffer->lyxvc().lockingToggleEnabled();
1518 flag.setOnOff(enable && !doc_buffer->lyxvc().locker().empty());
1520 case LFUN_VC_REVERT:
1521 enable = doc_buffer && doc_buffer->lyxvc().inUse();
1523 case LFUN_VC_UNDO_LAST:
1524 enable = doc_buffer && doc_buffer->lyxvc().undoLastEnabled();
1526 case LFUN_VC_REPO_UPDATE:
1527 enable = doc_buffer && doc_buffer->lyxvc().inUse();
1529 case LFUN_VC_COMMAND: {
1530 if (cmd.argument().empty())
1532 if (!doc_buffer && contains(cmd.getArg(0), 'D'))
1537 case LFUN_SERVER_GOTO_FILE_ROW:
1545 flag.setEnabled(false);
1551 static FileName selectTemplateFile()
1553 FileDialog dlg(qt_("Select template file"));
1554 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1555 dlg.setButton1(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
1557 FileDialog::Result result = dlg.open(toqstr(lyxrc.template_path),
1558 QStringList(qt_("LyX Documents (*.lyx)")));
1560 if (result.first == FileDialog::Later)
1562 if (result.second.isEmpty())
1564 return FileName(fromqstr(result.second));
1568 Buffer * GuiView::loadDocument(FileName const & filename, bool tolastfiles)
1572 Buffer * newBuffer = checkAndLoadLyXFile(filename);
1575 message(_("Document not loaded."));
1580 setBuffer(newBuffer);
1582 // scroll to the position when the file was last closed
1583 if (lyxrc.use_lastfilepos) {
1584 LastFilePosSection::FilePos filepos =
1585 theSession().lastFilePos().load(filename);
1586 documentBufferView()->moveToPosition(filepos.pit, filepos.pos, 0, 0);
1590 theSession().lastFiles().add(filename);
1597 void GuiView::openDocument(string const & fname)
1599 string initpath = lyxrc.document_path;
1601 if (documentBufferView()) {
1602 string const trypath = documentBufferView()->buffer().filePath();
1603 // If directory is writeable, use this as default.
1604 if (FileName(trypath).isDirWritable())
1610 if (fname.empty()) {
1611 FileDialog dlg(qt_("Select document to open"), LFUN_FILE_OPEN);
1612 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1613 dlg.setButton2(qt_("Examples|#E#e"),
1614 toqstr(addPath(package().system_support().absFilename(), "examples")));
1616 QStringList filter(qt_("LyX Documents (*.lyx)"));
1617 filter << qt_("LyX-1.3.x Documents (*.lyx13)")
1618 << qt_("LyX-1.4.x Documents (*.lyx14)")
1619 << qt_("LyX-1.5.x Documents (*.lyx15)")
1620 << qt_("LyX-1.6.x Documents (*.lyx16)");
1621 FileDialog::Result result =
1622 dlg.open(toqstr(initpath), filter);
1624 if (result.first == FileDialog::Later)
1627 filename = fromqstr(result.second);
1629 // check selected filename
1630 if (filename.empty()) {
1631 message(_("Canceled."));
1637 // get absolute path of file and add ".lyx" to the filename if
1639 FileName const fullname =
1640 fileSearch(string(), filename, "lyx", support::may_not_exist);
1641 if (!fullname.empty())
1642 filename = fullname.absFilename();
1644 if (!fullname.onlyPath().isDirectory()) {
1645 Alert::warning(_("Invalid filename"),
1646 bformat(_("The directory in the given path\n%1$s\ndoes not exist."),
1647 from_utf8(fullname.absFilename())));
1650 // if the file doesn't exist, let the user create one
1651 if (!fullname.exists()) {
1652 // the user specifically chose this name. Believe him.
1653 Buffer * const b = newFile(filename, string(), true);
1659 docstring const disp_fn = makeDisplayPath(filename);
1660 message(bformat(_("Opening document %1$s..."), disp_fn));
1663 Buffer * buf = loadDocument(fullname);
1665 buf->updateLabels();
1667 buf->errors("Parse");
1668 str2 = bformat(_("Document %1$s opened."), disp_fn);
1669 if (buf->lyxvc().inUse())
1670 str2 += " " + from_utf8(buf->lyxvc().versionString()) +
1671 " " + _("Version control detected.");
1673 str2 = bformat(_("Could not open document %1$s"), disp_fn);
1678 // FIXME: clean that
1679 static bool import(GuiView * lv, FileName const & filename,
1680 string const & format, ErrorList & errorList)
1682 FileName const lyxfile(support::changeExtension(filename.absFilename(), ".lyx"));
1684 string loader_format;
1685 vector<string> loaders = theConverters().loaders();
1686 if (find(loaders.begin(), loaders.end(), format) == loaders.end()) {
1687 for (vector<string>::const_iterator it = loaders.begin();
1688 it != loaders.end(); ++it) {
1689 if (!theConverters().isReachable(format, *it))
1692 string const tofile =
1693 support::changeExtension(filename.absFilename(),
1694 formats.extension(*it));
1695 if (!theConverters().convert(0, filename, FileName(tofile),
1696 filename, format, *it, errorList))
1698 loader_format = *it;
1701 if (loader_format.empty()) {
1702 frontend::Alert::error(_("Couldn't import file"),
1703 bformat(_("No information for importing the format %1$s."),
1704 formats.prettyName(format)));
1708 loader_format = format;
1710 if (loader_format == "lyx") {
1711 Buffer * buf = lv->loadDocument(lyxfile);
1714 buf->updateLabels();
1716 buf->errors("Parse");
1718 Buffer * const b = newFile(lyxfile.absFilename(), string(), true);
1722 bool as_paragraphs = loader_format == "textparagraph";
1723 string filename2 = (loader_format == format) ? filename.absFilename()
1724 : support::changeExtension(filename.absFilename(),
1725 formats.extension(loader_format));
1726 lv->currentBufferView()->insertPlaintextFile(FileName(filename2),
1728 guiApp->setCurrentView(lv);
1729 lyx::dispatch(FuncRequest(LFUN_MARK_OFF));
1736 void GuiView::importDocument(string const & argument)
1739 string filename = split(argument, format, ' ');
1741 LYXERR(Debug::INFO, format << " file: " << filename);
1743 // need user interaction
1744 if (filename.empty()) {
1745 string initpath = lyxrc.document_path;
1746 if (documentBufferView()) {
1747 string const trypath = documentBufferView()->buffer().filePath();
1748 // If directory is writeable, use this as default.
1749 if (FileName(trypath).isDirWritable())
1753 docstring const text = bformat(_("Select %1$s file to import"),
1754 formats.prettyName(format));
1756 FileDialog dlg(toqstr(text), LFUN_BUFFER_IMPORT);
1757 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1758 dlg.setButton2(qt_("Examples|#E#e"),
1759 toqstr(addPath(package().system_support().absFilename(), "examples")));
1761 docstring filter = formats.prettyName(format);
1764 filter += from_utf8(formats.extension(format));
1767 FileDialog::Result result =
1768 dlg.open(toqstr(initpath), fileFilters(toqstr(filter)));
1770 if (result.first == FileDialog::Later)
1773 filename = fromqstr(result.second);
1775 // check selected filename
1776 if (filename.empty())
1777 message(_("Canceled."));
1780 if (filename.empty())
1783 // get absolute path of file
1784 FileName const fullname(support::makeAbsPath(filename));
1786 FileName const lyxfile(support::changeExtension(fullname.absFilename(), ".lyx"));
1788 // Check if the document already is open
1789 Buffer * buf = theBufferList().getBuffer(lyxfile);
1792 if (!closeBuffer()) {
1793 message(_("Canceled."));
1798 docstring const displaypath = makeDisplayPath(lyxfile.absFilename(), 30);
1800 // if the file exists already, and we didn't do
1801 // -i lyx thefile.lyx, warn
1802 if (lyxfile.exists() && fullname != lyxfile) {
1804 docstring text = bformat(_("The document %1$s already exists.\n\n"
1805 "Do you want to overwrite that document?"), displaypath);
1806 int const ret = Alert::prompt(_("Overwrite document?"),
1807 text, 0, 1, _("&Overwrite"), _("&Cancel"));
1810 message(_("Canceled."));
1815 message(bformat(_("Importing %1$s..."), displaypath));
1816 ErrorList errorList;
1817 if (import(this, fullname, format, errorList))
1818 message(_("imported."));
1820 message(_("file not imported!"));
1822 // FIXME (Abdel 12/08/06): Is there a need to display the error list here?
1826 void GuiView::newDocument(string const & filename, bool from_template)
1828 FileName initpath(lyxrc.document_path);
1829 if (documentBufferView()) {
1830 FileName const trypath(documentBufferView()->buffer().filePath());
1831 // If directory is writeable, use this as default.
1832 if (trypath.isDirWritable())
1836 string templatefile;
1837 if (from_template) {
1838 templatefile = selectTemplateFile().absFilename();
1839 if (templatefile.empty())
1844 if (filename.empty())
1845 b = newUnnamedFile(initpath, to_utf8(_("newfile")), templatefile);
1847 b = newFile(filename, templatefile, true);
1852 // If no new document could be created, it is unsure
1853 // whether there is a valid BufferView.
1854 if (currentBufferView())
1855 // Ensure the cursor is correctly positioned on screen.
1856 currentBufferView()->showCursor();
1860 void GuiView::insertLyXFile(docstring const & fname)
1862 BufferView * bv = documentBufferView();
1867 FileName filename(to_utf8(fname));
1869 if (!filename.empty()) {
1870 bv->insertLyXFile(filename);
1874 // Launch a file browser
1876 string initpath = lyxrc.document_path;
1877 string const trypath = bv->buffer().filePath();
1878 // If directory is writeable, use this as default.
1879 if (FileName(trypath).isDirWritable())
1883 FileDialog dlg(qt_("Select LyX document to insert"), LFUN_FILE_INSERT);
1884 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1885 dlg.setButton2(qt_("Examples|#E#e"),
1886 toqstr(addPath(package().system_support().absFilename(),
1889 FileDialog::Result result = dlg.open(toqstr(initpath),
1890 QStringList(qt_("LyX Documents (*.lyx)")));
1892 if (result.first == FileDialog::Later)
1896 filename.set(fromqstr(result.second));
1898 // check selected filename
1899 if (filename.empty()) {
1900 // emit message signal.
1901 message(_("Canceled."));
1905 bv->insertLyXFile(filename);
1909 void GuiView::insertPlaintextFile(docstring const & fname,
1912 BufferView * bv = documentBufferView();
1916 if (!fname.empty() && !FileName::isAbsolute(to_utf8(fname))) {
1917 message(_("Absolute filename expected."));
1922 FileName filename(to_utf8(fname));
1924 if (!filename.empty()) {
1925 bv->insertPlaintextFile(filename, asParagraph);
1929 FileDialog dlg(qt_("Select file to insert"), (asParagraph ?
1930 LFUN_FILE_INSERT_PLAINTEXT_PARA : LFUN_FILE_INSERT_PLAINTEXT));
1932 FileDialog::Result result = dlg.open(toqstr(bv->buffer().filePath()),
1933 QStringList(qt_("All Files (*)")));
1935 if (result.first == FileDialog::Later)
1939 filename.set(fromqstr(result.second));
1941 // check selected filename
1942 if (filename.empty()) {
1943 // emit message signal.
1944 message(_("Canceled."));
1948 bv->insertPlaintextFile(filename, asParagraph);
1952 bool GuiView::renameBuffer(Buffer & b, docstring const & newname)
1954 FileName fname = b.fileName();
1955 FileName const oldname = fname;
1957 if (!newname.empty()) {
1959 fname = support::makeAbsPath(to_utf8(newname), oldname.onlyPath().absFilename());
1961 // Switch to this Buffer.
1964 // No argument? Ask user through dialog.
1966 FileDialog dlg(qt_("Choose a filename to save document as"),
1967 LFUN_BUFFER_WRITE_AS);
1968 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1969 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
1971 if (!isLyXFilename(fname.absFilename()))
1972 fname.changeExtension(".lyx");
1974 FileDialog::Result result =
1975 dlg.save(toqstr(fname.onlyPath().absFilename()),
1976 QStringList(qt_("LyX Documents (*.lyx)")),
1977 toqstr(fname.onlyFileName()));
1979 if (result.first == FileDialog::Later)
1982 fname.set(fromqstr(result.second));
1987 if (!isLyXFilename(fname.absFilename()))
1988 fname.changeExtension(".lyx");
1991 if (FileName(fname).exists()) {
1992 docstring const file = makeDisplayPath(fname.absFilename(), 30);
1993 docstring text = bformat(_("The document %1$s already "
1994 "exists.\n\nDo you want to "
1995 "overwrite that document?"),
1997 int const ret = Alert::prompt(_("Overwrite document?"),
1998 text, 0, 2, _("&Overwrite"), _("&Rename"), _("&Cancel"));
2001 case 1: return renameBuffer(b, docstring());
2002 case 2: return false;
2006 FileName oldauto = b.getAutosaveFilename();
2008 // Ok, change the name of the buffer
2009 b.setFileName(fname.absFilename());
2011 bool unnamed = b.isUnnamed();
2012 b.setUnnamed(false);
2013 b.saveCheckSum(fname);
2015 // bring the autosave file with us, just in case.
2016 b.moveAutosaveFile(oldauto);
2018 if (!saveBuffer(b)) {
2019 oldauto = b.getAutosaveFilename();
2020 b.setFileName(oldname.absFilename());
2021 b.setUnnamed(unnamed);
2022 b.saveCheckSum(oldname);
2023 b.moveAutosaveFile(oldauto);
2031 bool GuiView::saveBuffer(Buffer & b)
2033 if (workArea(b) && workArea(b)->inDialogMode())
2037 return renameBuffer(b, docstring());
2040 theSession().lastFiles().add(b.fileName());
2044 // Switch to this Buffer.
2047 // FIXME: we don't tell the user *WHY* the save failed !!
2048 docstring const file = makeDisplayPath(b.absFileName(), 30);
2049 docstring text = bformat(_("The document %1$s could not be saved.\n\n"
2050 "Do you want to rename the document and "
2051 "try again?"), file);
2052 int const ret = Alert::prompt(_("Rename and save?"),
2053 text, 0, 2, _("&Rename"), _("&Retry"), _("&Cancel"));
2056 if (!renameBuffer(b, docstring()))
2065 return saveBuffer(b);
2069 bool GuiView::hideWorkArea(GuiWorkArea * wa)
2071 return closeWorkArea(wa, false);
2075 bool GuiView::closeWorkArea(GuiWorkArea * wa)
2077 Buffer & buf = wa->bufferView().buffer();
2078 return closeWorkArea(wa, !buf.parent());
2082 bool GuiView::closeBuffer()
2084 GuiWorkArea * wa = currentMainWorkArea();
2085 Buffer & buf = wa->bufferView().buffer();
2086 return wa && closeWorkArea(wa, !buf.parent());
2090 void GuiView::writeSession() const {
2091 GuiWorkArea const * active_wa = currentMainWorkArea();
2092 for (int i = 0; i < d.splitter_->count(); ++i) {
2093 TabWorkArea * twa = d.tabWorkArea(i);
2094 for (int j = 0; j < twa->count(); ++j) {
2095 GuiWorkArea * wa = static_cast<GuiWorkArea *>(twa->widget(j));
2096 Buffer & buf = wa->bufferView().buffer();
2097 theSession().lastOpened().add(buf.fileName(), wa == active_wa);
2103 bool GuiView::closeBufferAll()
2105 // Close the workareas in all other views
2106 QList<int> const ids = guiApp->viewIds();
2107 for (int i = 0; i != ids.size(); ++i) {
2108 if (id_ != ids[i] && !guiApp->view(ids[i]).closeWorkAreaAll())
2112 // Close our own workareas
2113 if (!closeWorkAreaAll())
2116 // Now close the hidden buffers. We prevent hidden buffers from being
2117 // dirty, so we can just close them.
2118 theBufferList().closeAll();
2123 bool GuiView::closeWorkAreaAll()
2125 setCurrentWorkArea(currentMainWorkArea());
2127 // We might be in a situation that there is still a tabWorkArea, but
2128 // there are no tabs anymore. This can happen when we get here after a
2129 // TabWorkArea::lastWorkAreaRemoved() signal. Therefore we count how
2130 // many TabWorkArea's have no documents anymore.
2133 // We have to call count() each time, because it can happen that
2134 // more than one splitter will disappear in one iteration (bug 5998).
2135 for (; d.splitter_->count() > empty_twa; ) {
2136 TabWorkArea * twa = d.tabWorkArea(empty_twa);
2138 if (twa->count() == 0)
2141 setCurrentWorkArea(twa->currentWorkArea());
2142 if (!closeTabWorkArea(twa))
2150 bool GuiView::closeWorkArea(GuiWorkArea * wa, bool close_buffer)
2155 Buffer & buf = wa->bufferView().buffer();
2158 return closeBuffer(buf);
2160 if (!inMultiTabs(wa))
2161 if (!saveBufferIfNeeded(buf, true))
2169 bool GuiView::closeBuffer(Buffer & buf)
2171 // If we are in a close_event all children will be closed in some time,
2172 // so no need to do it here. This will ensure that the children end up
2173 // in the session file in the correct order. If we close the master
2174 // buffer, we can close or release the child buffers here too.
2176 vector<Buffer *> clist = buf.getChildren(false);
2177 for (vector<Buffer *>::const_iterator it = clist.begin();
2178 it != clist.end(); ++it) {
2179 // If a child is dirty, do not close
2180 // without user intervention
2181 //FIXME: should we look in other tabworkareas?
2182 Buffer * child_buf = *it;
2183 GuiWorkArea * child_wa = workArea(*child_buf);
2185 if (!closeWorkArea(child_wa, true))
2188 theBufferList().releaseChild(&buf, child_buf);
2191 // goto bookmark to update bookmark pit.
2192 //FIXME: we should update only the bookmarks related to this buffer!
2193 LYXERR(Debug::DEBUG, "GuiView::closeBuffer()");
2194 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
2195 theLyXFunc().gotoBookmark(i+1, false, false);
2197 if (saveBufferIfNeeded(buf, false)) {
2198 theBufferList().release(&buf);
2205 bool GuiView::closeTabWorkArea(TabWorkArea * twa)
2207 while (twa == d.currentTabWorkArea()) {
2208 twa->setCurrentIndex(twa->count()-1);
2210 GuiWorkArea * wa = twa->currentWorkArea();
2211 Buffer & b = wa->bufferView().buffer();
2213 // We only want to close the buffer if the same buffer is not visible
2214 // in another view, and if this is not a child and if we are closing
2215 // a view (not a tabgroup).
2216 bool const close_buffer =
2217 !inMultiViews(wa) && !b.parent() && closing_;
2219 if (!closeWorkArea(wa, close_buffer))
2226 bool GuiView::saveBufferIfNeeded(Buffer & buf, bool hiding)
2228 if (buf.isClean() || buf.paragraphs().empty())
2231 // Switch to this Buffer.
2236 if (buf.isUnnamed())
2237 file = from_utf8(buf.fileName().onlyFileName());
2239 file = buf.fileName().displayName(30);
2241 // Bring this window to top before asking questions.
2246 if (hiding && buf.isUnnamed()) {
2247 docstring const text = bformat(_("The document %1$s has not been "
2248 "saved yet.\n\nDo you want to save "
2249 "the document?"), file);
2250 ret = Alert::prompt(_("Save new document?"),
2251 text, 0, 1, _("&Save"), _("&Cancel"));
2255 docstring const text = bformat(_("The document %1$s has unsaved changes."
2256 "\n\nDo you want to save the document or discard the changes?"), file);
2257 ret = Alert::prompt(_("Save changed document?"),
2258 text, 0, 2, _("&Save"), _("&Discard"), _("&Cancel"));
2263 if (!saveBuffer(buf))
2267 // if we crash after this we could
2268 // have no autosave file but I guess
2269 // this is really improbable (Jug)
2270 buf.removeAutosaveFile();
2272 // revert all changes
2273 buf.loadLyXFile(buf.fileName());
2283 bool GuiView::inMultiTabs(GuiWorkArea * wa)
2285 Buffer & buf = wa->bufferView().buffer();
2287 for (int i = 0; i != d.splitter_->count(); ++i) {
2288 GuiWorkArea * wa_ = d.tabWorkArea(i)->workArea(buf);
2289 if (wa_ && wa_ != wa)
2292 return inMultiViews(wa);
2296 bool GuiView::inMultiViews(GuiWorkArea * wa)
2298 QList<int> const ids = guiApp->viewIds();
2299 Buffer & buf = wa->bufferView().buffer();
2302 for (int i = 0; i != ids.size() && found_twa <= 1; ++i) {
2306 if (guiApp->view(ids[i]).workArea(buf))
2313 void GuiView::gotoNextOrPreviousBuffer(NextOrPrevious np)
2315 Buffer * const curbuf = documentBufferView()
2316 ? &documentBufferView()->buffer() : 0;
2317 Buffer * nextbuf = curbuf;
2319 if (np == NEXTBUFFER)
2320 nextbuf = theBufferList().next(nextbuf);
2322 nextbuf = theBufferList().previous(nextbuf);
2323 if (nextbuf == curbuf)
2329 if (workArea(*nextbuf))
2336 /// make sure the document is saved
2337 static bool ensureBufferClean(Buffer * buffer)
2339 LASSERT(buffer, return false);
2340 if (buffer->isClean() && !buffer->isUnnamed())
2343 docstring const file = buffer->fileName().displayName(30);
2346 if (!buffer->isUnnamed()) {
2347 text = bformat(_("The document %1$s has unsaved "
2348 "changes.\n\nDo you want to save "
2349 "the document?"), file);
2350 title = _("Save changed document?");
2353 text = bformat(_("The document %1$s has not been "
2354 "saved yet.\n\nDo you want to save "
2355 "the document?"), file);
2356 title = _("Save new document?");
2358 int const ret = Alert::prompt(title, text, 0, 1, _("&Save"), _("&Cancel"));
2361 dispatch(FuncRequest(LFUN_BUFFER_WRITE));
2363 return buffer->isClean() && !buffer->isUnnamed();
2367 void GuiView::reloadBuffer()
2369 Buffer * buf = &documentBufferView()->buffer();
2374 void GuiView::reloadBuffer(Buffer * buf)
2376 FileName filename = buf->fileName();
2377 Buffer const * master = buf->masterBuffer();
2378 bool const is_child = master != buf;
2379 // The user has already confirmed that the changes, if any, should
2380 // be discarded. So we just release the Buffer and don't call closeBuffer();
2381 theBufferList().release(buf);
2382 buf = loadDocument(filename);
2383 docstring const disp_fn = makeDisplayPath(filename.absFilename());
2386 // re-allocate master if necessary
2387 if (is_child && theBufferList().isLoaded(master)
2388 && buf->masterBuffer() != master)
2389 buf->setParent(master);
2390 buf->updateLabels();
2392 buf->errors("Parse");
2393 str = bformat(_("Document %1$s reloaded."), disp_fn);
2395 str = bformat(_("Could not reload document %1$s"), disp_fn);
2401 void GuiView::checkExternallyModifiedBuffers()
2403 BufferList::iterator bit = theBufferList().begin();
2404 BufferList::iterator const bend = theBufferList().end();
2405 for (; bit != bend; ++bit) {
2406 if ((*bit)->isExternallyModified(Buffer::checksum_method)) {
2407 docstring text = bformat(_("Document \n%1$s\n has been externally modified."
2408 " Reload now? Any local changes will be lost."),
2409 from_utf8((*bit)->absFileName()));
2410 int const ret = Alert::prompt(_("Reload externally changed document?"),
2411 text, 0, 1, _("&Reload"), _("&Cancel"));
2419 void GuiView::dispatchVC(FuncRequest const & cmd)
2421 Buffer * buffer = documentBufferView()
2422 ? &(documentBufferView()->buffer()) : 0;
2424 switch (cmd.action) {
2425 case LFUN_VC_REGISTER:
2426 if (!buffer || !ensureBufferClean(buffer))
2428 if (!buffer->lyxvc().inUse()) {
2429 if (buffer->lyxvc().registrer())
2434 case LFUN_VC_CHECK_IN:
2435 if (!buffer || !ensureBufferClean(buffer))
2437 if (buffer->lyxvc().inUse() && !buffer->isReadonly()) {
2438 message(from_utf8(buffer->lyxvc().checkIn()));
2443 case LFUN_VC_CHECK_OUT:
2444 if (!buffer || !ensureBufferClean(buffer))
2446 if (buffer->lyxvc().inUse()) {
2447 message(from_utf8(buffer->lyxvc().checkOut()));
2452 case LFUN_VC_LOCKING_TOGGLE:
2453 LASSERT(buffer, return);
2454 if (!ensureBufferClean(buffer) || buffer->isReadonly())
2456 if (buffer->lyxvc().inUse()) {
2457 string res = buffer->lyxvc().lockingToggle();
2459 frontend::Alert::error(_("Revision control error."),
2460 _("Error when setting the locking property."));
2462 message(from_utf8(res));
2468 case LFUN_VC_REVERT:
2469 LASSERT(buffer, return);
2470 buffer->lyxvc().revert();
2474 case LFUN_VC_UNDO_LAST:
2475 LASSERT(buffer, return);
2476 buffer->lyxvc().undoLast();
2480 case LFUN_VC_REPO_UPDATE:
2481 LASSERT(buffer, return);
2482 if (ensureBufferClean(buffer)) {
2483 string res = buffer->lyxvc().repoUpdate();
2484 message(from_utf8(res));
2485 checkExternallyModifiedBuffers();
2489 case LFUN_VC_COMMAND: {
2490 string flag = cmd.getArg(0);
2491 if (buffer && contains(flag, 'R') && !ensureBufferClean(buffer))
2494 if (contains(flag, 'M')) {
2495 if (!Alert::askForText(message, _("LyX VC: Log Message")))
2498 string path = cmd.getArg(1);
2499 if (contains(path, "$$p") && buffer)
2500 path = subst(path, "$$p", buffer->filePath());
2501 LYXERR(Debug::LYXVC, "Directory: " << path);
2503 if (!pp.isReadableDirectory()) {
2504 lyxerr << _("Directory is not accessible.") << endl;
2507 support::PathChanger p(pp);
2509 string command = cmd.getArg(2);
2510 if (command.empty())
2513 command = subst(command, "$$i", buffer->absFileName());
2514 command = subst(command, "$$p", buffer->filePath());
2516 command = subst(command, "$$m", to_utf8(message));
2517 LYXERR(Debug::LYXVC, "Command: " << command);
2519 one.startscript(Systemcall::Wait, command);
2523 if (contains(flag, 'I'))
2524 buffer->markDirty();
2525 if (contains(flag, 'R'))
2536 void GuiView::openChildDocument(string const & fname)
2538 LASSERT(documentBufferView(), return);
2539 Buffer & buffer = documentBufferView()->buffer();
2540 FileName const filename = support::makeAbsPath(fname, buffer.filePath());
2541 documentBufferView()->saveBookmark(false);
2543 bool parsed = false;
2544 if (theBufferList().exists(filename)) {
2545 child = theBufferList().getBuffer(filename);
2547 message(bformat(_("Opening child document %1$s..."),
2548 makeDisplayPath(filename.absFilename())));
2549 child = loadDocument(filename, false);
2555 // Set the parent name of the child document.
2556 // This makes insertion of citations and references in the child work,
2557 // when the target is in the parent or another child document.
2558 child->setParent(&buffer);
2559 child->masterBuffer()->updateLabels();
2562 child->errors("Parse");
2566 bool GuiView::goToFileRow(string const & argument)
2570 istringstream is(argument);
2571 is >> file_name >> row;
2572 file_name = os::internal_path(file_name);
2574 string const abstmp = package().temp_dir().absFilename();
2575 string const realtmp = package().temp_dir().realPath();
2576 // We have to use os::path_prefix_is() here, instead of
2577 // simply prefixIs(), because the file name comes from
2578 // an external application and may need case adjustment.
2579 if (os::path_prefix_is(file_name, abstmp, os::CASE_ADJUSTED)
2580 || os::path_prefix_is(file_name, realtmp, os::CASE_ADJUSTED)) {
2581 // Needed by inverse dvi search. If it is a file
2582 // in tmpdir, call the apropriated function.
2583 // If tmpdir is a symlink, we may have the real
2584 // path passed back, so we correct for that.
2585 if (!prefixIs(file_name, abstmp))
2586 file_name = subst(file_name, realtmp, abstmp);
2587 buf = theBufferList().getBufferFromTmp(file_name);
2589 // Must replace extension of the file to be .lyx
2590 // and get full path
2591 FileName const s = fileSearch(string(),
2592 support::changeExtension(file_name, ".lyx"), "lyx");
2593 // Either change buffer or load the file
2594 if (theBufferList().exists(s))
2595 buf = theBufferList().getBuffer(s);
2596 else if (s.exists()) {
2597 buf = loadDocument(s);
2598 buf->updateLabels();
2599 buf->errors("Parse");
2602 _("File does not exist: %1$s"),
2603 makeDisplayPath(file_name)));
2608 documentBufferView()->setCursorFromRow(row);
2613 static docstring exportAndDestroy(Buffer * buffer, docstring const & format)
2615 bool const success = buffer->doExport(to_utf8(format), true);
2618 ? bformat(_("Successful export to format: %1$s."), format)
2619 : bformat(_("Error exporting to format: %1$s."), format);
2623 static docstring previewAndDestroy(Buffer * buffer, docstring const & format)
2625 bool const success = buffer->preview(to_utf8(format));
2628 ? bformat(_("Successful preview of format: %1$s."), format)
2629 : bformat(_("Error previewing format: %1$s."), format);
2633 bool GuiView::dispatch(FuncRequest const & cmd)
2635 BufferView * bv = currentBufferView();
2636 // By default we won't need any update.
2638 bv->cursor().updateFlags(Update::None);
2640 Buffer * doc_buffer = documentBufferView()
2641 ? &(documentBufferView()->buffer()) : 0;
2643 bool dispatched = true;
2645 if (cmd.origin == FuncRequest::TOC) {
2646 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
2647 toc->doDispatch(bv->cursor(), cmd);
2651 string const argument = to_utf8(cmd.argument());
2653 switch(cmd.action) {
2654 case LFUN_BUFFER_CHILD_OPEN:
2655 openChildDocument(to_utf8(cmd.argument()));
2658 case LFUN_BUFFER_IMPORT:
2659 importDocument(to_utf8(cmd.argument()));
2662 case LFUN_BUFFER_EXPORT: {
2665 if (cmd.argument() == "custom") {
2666 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "sendto"));
2669 if (doc_buffer->doExport(argument, false)) {
2670 message(bformat(_("Error exporting to format: %1$s."),
2676 case LFUN_BUFFER_UPDATE: {
2679 string format = argument;
2680 if (argument.empty())
2681 format = doc_buffer->getDefaultOutputFormat();
2682 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
2683 QFuture<docstring> f = QtConcurrent::run(exportAndDestroy,
2684 doc_buffer->clone(), cmd.argument());
2685 d.preview_watcher_.setFuture(f);
2687 doc_buffer->doExport(format, true);
2691 case LFUN_BUFFER_VIEW: {
2694 string format = argument;
2695 if (argument.empty())
2696 format = doc_buffer->getDefaultOutputFormat();
2697 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
2698 QFuture<docstring> f = QtConcurrent::run(previewAndDestroy,
2699 doc_buffer->clone(), cmd.argument());
2700 d.preview_watcher_.setFuture(f);
2702 doc_buffer->preview(format);
2706 case LFUN_MASTER_BUFFER_UPDATE: {
2709 string format = argument;
2710 Buffer const * master = doc_buffer->masterBuffer();
2711 if (argument.empty())
2712 format = master->getDefaultOutputFormat();
2713 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
2714 QFuture<docstring> f = QtConcurrent::run(exportAndDestroy,
2715 master->clone(), cmd.argument());
2716 d.preview_watcher_.setFuture(f);
2718 master->doExport(format, true);
2722 case LFUN_MASTER_BUFFER_VIEW: {
2723 string format = argument;
2724 Buffer const * master = doc_buffer->masterBuffer();
2725 if (argument.empty())
2726 format = master->getDefaultOutputFormat();
2727 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
2728 QFuture<docstring> f = QtConcurrent::run(previewAndDestroy,
2729 master->clone(), cmd.argument());
2730 d.preview_watcher_.setFuture(f);
2732 master->preview(format);
2736 case LFUN_BUFFER_SWITCH:
2737 if (FileName::isAbsolute(to_utf8(cmd.argument()))) {
2739 theBufferList().getBuffer(FileName(to_utf8(cmd.argument())));
2743 message(_("Document not loaded"));
2747 case LFUN_BUFFER_NEXT:
2748 gotoNextOrPreviousBuffer(NEXTBUFFER);
2751 case LFUN_BUFFER_PREVIOUS:
2752 gotoNextOrPreviousBuffer(PREVBUFFER);
2755 case LFUN_COMMAND_EXECUTE: {
2756 bool const show_it = cmd.argument() != "off";
2757 // FIXME: this is a hack, "minibuffer" should not be
2759 if (GuiToolbar * t = toolbar("minibuffer")) {
2760 t->setVisible(show_it);
2761 if (show_it && t->commandBuffer())
2762 t->commandBuffer()->setFocus();
2766 case LFUN_DROP_LAYOUTS_CHOICE:
2767 d.layout_->showPopup();
2770 case LFUN_MENU_OPEN:
2771 if (QMenu * menu = guiApp->menus().menu(toqstr(cmd.argument()), *this))
2772 menu->exec(QCursor::pos());
2775 case LFUN_FILE_INSERT:
2776 insertLyXFile(cmd.argument());
2778 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
2779 insertPlaintextFile(cmd.argument(), true);
2782 case LFUN_FILE_INSERT_PLAINTEXT:
2783 insertPlaintextFile(cmd.argument(), false);
2786 case LFUN_BUFFER_RELOAD: {
2787 LASSERT(doc_buffer, break);
2788 docstring const file = makeDisplayPath(doc_buffer->absFileName(), 20);
2789 docstring text = bformat(_("Any changes will be lost. Are you sure "
2790 "you want to revert to the saved version of the document %1$s?"), file);
2791 int const ret = Alert::prompt(_("Revert to saved document?"),
2792 text, 1, 1, _("&Revert"), _("&Cancel"));
2795 doc_buffer->markClean();
2801 case LFUN_BUFFER_WRITE:
2802 LASSERT(doc_buffer, break);
2803 saveBuffer(*doc_buffer);
2806 case LFUN_BUFFER_WRITE_AS:
2807 LASSERT(doc_buffer, break);
2808 renameBuffer(*doc_buffer, cmd.argument());
2811 case LFUN_BUFFER_WRITE_ALL: {
2812 Buffer * first = theBufferList().first();
2815 message(_("Saving all documents..."));
2816 // We cannot use a for loop as the buffer list cycles.
2819 if (!b->isClean()) {
2821 LYXERR(Debug::ACTION, "Saved " << b->absFileName());
2823 b = theBufferList().next(b);
2824 } while (b != first);
2825 message(_("All documents saved."));
2829 case LFUN_BUFFER_CLOSE:
2833 case LFUN_BUFFER_CLOSE_ALL:
2837 case LFUN_TOOLBAR_TOGGLE: {
2838 string const name = cmd.getArg(0);
2839 if (GuiToolbar * t = toolbar(name))
2844 case LFUN_DIALOG_UPDATE: {
2845 string const name = to_utf8(cmd.argument());
2846 if (currentBufferView()) {
2847 Inset * inset = currentBufferView()->editedInset(name);
2848 // Can only update a dialog connected to an existing inset
2851 // FIXME: get rid of this indirection; GuiView ask the inset
2852 // if he is kind enough to update itself...
2853 FuncRequest fr(LFUN_INSET_DIALOG_UPDATE, cmd.argument());
2854 inset->dispatch(currentBufferView()->cursor(), fr);
2855 } else if (name == "paragraph") {
2856 lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
2857 } else if (name == "prefs" || name == "document") {
2858 updateDialog(name, string());
2863 case LFUN_DIALOG_TOGGLE: {
2864 if (isDialogVisible(cmd.getArg(0)))
2865 dispatch(FuncRequest(LFUN_DIALOG_HIDE, cmd.argument()));
2867 dispatch(FuncRequest(LFUN_DIALOG_SHOW, cmd.argument()));
2871 case LFUN_DIALOG_DISCONNECT_INSET:
2872 disconnectDialog(to_utf8(cmd.argument()));
2875 case LFUN_DIALOG_HIDE: {
2876 guiApp->hideDialogs(to_utf8(cmd.argument()), 0);
2880 case LFUN_DIALOG_SHOW: {
2881 string const name = cmd.getArg(0);
2882 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
2884 if (name == "character") {
2885 data = freefont2string();
2887 showDialog("character", data);
2888 } else if (name == "latexlog") {
2889 Buffer::LogType type;
2890 string const logfile = doc_buffer->logName(&type);
2892 case Buffer::latexlog:
2895 case Buffer::buildlog:
2899 data += Lexer::quoteString(logfile);
2900 showDialog("log", data);
2901 } else if (name == "vclog") {
2902 string const data = "vc " +
2903 Lexer::quoteString(doc_buffer->lyxvc().getLogFile());
2904 showDialog("log", data);
2905 } else if (name == "symbols") {
2906 data = bv->cursor().getEncoding()->name();
2908 showDialog("symbols", data);
2910 } else if (name == "prefs" && isFullScreen()) {
2911 FuncRequest fr(LFUN_INSET_INSERT, "fullscreen");
2913 showDialog("prefs", data);
2915 showDialog(name, data);
2920 message(cmd.argument());
2923 case LFUN_UI_TOGGLE:
2925 // Make sure the keyboard focus stays in the work area.
2929 case LFUN_SPLIT_VIEW: {
2930 LASSERT(doc_buffer, break);
2931 string const orientation = cmd.getArg(0);
2932 d.splitter_->setOrientation(orientation == "vertical"
2933 ? Qt::Vertical : Qt::Horizontal);
2934 TabWorkArea * twa = addTabWorkArea();
2935 GuiWorkArea * wa = twa->addWorkArea(*doc_buffer, *this);
2936 setCurrentWorkArea(wa);
2939 case LFUN_CLOSE_TAB_GROUP:
2940 if (TabWorkArea * twa = d.currentTabWorkArea()) {
2941 closeTabWorkArea(twa);
2942 d.current_work_area_ = 0;
2943 twa = d.currentTabWorkArea();
2944 // Switch to the next GuiWorkArea in the found TabWorkArea.
2946 // Make sure the work area is up to date.
2947 setCurrentWorkArea(twa->currentWorkArea());
2949 setCurrentWorkArea(0);
2954 case LFUN_COMPLETION_INLINE:
2955 if (d.current_work_area_)
2956 d.current_work_area_->completer().showInline();
2959 case LFUN_COMPLETION_POPUP:
2960 if (d.current_work_area_)
2961 d.current_work_area_->completer().showPopup();
2965 case LFUN_COMPLETION_COMPLETE:
2966 if (d.current_work_area_)
2967 d.current_work_area_->completer().tab();
2970 case LFUN_COMPLETION_CANCEL:
2971 if (d.current_work_area_) {
2972 if (d.current_work_area_->completer().popupVisible())
2973 d.current_work_area_->completer().hidePopup();
2975 d.current_work_area_->completer().hideInline();
2979 case LFUN_COMPLETION_ACCEPT:
2980 if (d.current_work_area_)
2981 d.current_work_area_->completer().activate();
2984 case LFUN_BUFFER_ZOOM_IN:
2985 case LFUN_BUFFER_ZOOM_OUT:
2986 if (cmd.argument().empty()) {
2987 if (cmd.action == LFUN_BUFFER_ZOOM_IN)
2992 lyxrc.zoom += convert<int>(cmd.argument());
2994 if (lyxrc.zoom < 10)
2997 // The global QPixmapCache is used in GuiPainter to cache text
2998 // painting so we must reset it.
2999 QPixmapCache::clear();
3000 guiApp->fontLoader().update();
3001 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
3004 case LFUN_VC_REGISTER:
3005 case LFUN_VC_CHECK_IN:
3006 case LFUN_VC_CHECK_OUT:
3007 case LFUN_VC_REPO_UPDATE:
3008 case LFUN_VC_LOCKING_TOGGLE:
3009 case LFUN_VC_REVERT:
3010 case LFUN_VC_UNDO_LAST:
3011 case LFUN_VC_COMMAND:
3015 case LFUN_SERVER_GOTO_FILE_ROW:
3016 goToFileRow(to_utf8(cmd.argument()));
3024 // Part of automatic menu appearance feature.
3025 if (isFullScreen()) {
3026 if (menuBar()->isVisible() && lyxrc.full_screen_menubar)
3028 if (statusBar()->isVisible())
3029 statusBar()->hide();
3036 void GuiView::lfunUiToggle(FuncRequest const & cmd)
3038 string const arg = cmd.getArg(0);
3039 if (arg == "scrollbar") {
3040 // hide() is of no help
3041 if (d.current_work_area_->verticalScrollBarPolicy() ==
3042 Qt::ScrollBarAlwaysOff)
3044 d.current_work_area_->setVerticalScrollBarPolicy(
3045 Qt::ScrollBarAsNeeded);
3047 d.current_work_area_->setVerticalScrollBarPolicy(
3048 Qt::ScrollBarAlwaysOff);
3051 if (arg == "statusbar") {
3052 statusBar()->setVisible(!statusBar()->isVisible());
3055 if (arg == "menubar") {
3056 menuBar()->setVisible(!menuBar()->isVisible());
3059 #if QT_VERSION >= 0x040300
3060 if (arg == "frame") {
3062 getContentsMargins(&l, &t, &r, &b);
3063 //are the frames in default state?
3064 d.current_work_area_->setFrameStyle(QFrame::NoFrame);
3066 setContentsMargins(-2, -2, -2, -2);
3068 setContentsMargins(0, 0, 0, 0);
3073 if (arg == "fullscreen") {
3078 message(bformat("LFUN_UI_TOGGLE " + _("%1$s unknown command!"), from_utf8(arg)));
3082 void GuiView::toggleFullScreen()
3084 if (isFullScreen()) {
3085 for (int i = 0; i != d.splitter_->count(); ++i)
3086 d.tabWorkArea(i)->setFullScreen(false);
3087 #if QT_VERSION >= 0x040300
3088 setContentsMargins(0, 0, 0, 0);
3090 setWindowState(windowState() ^ Qt::WindowFullScreen);
3093 statusBar()->show();
3096 hideDialogs("prefs", 0);
3097 for (int i = 0; i != d.splitter_->count(); ++i)
3098 d.tabWorkArea(i)->setFullScreen(true);
3099 #if QT_VERSION >= 0x040300
3100 setContentsMargins(-2, -2, -2, -2);
3103 setWindowState(windowState() ^ Qt::WindowFullScreen);
3104 statusBar()->hide();
3105 if (lyxrc.full_screen_menubar)
3107 if (lyxrc.full_screen_toolbars) {
3108 ToolbarMap::iterator end = d.toolbars_.end();
3109 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
3114 // give dialogs like the TOC a chance to adapt
3119 Buffer const * GuiView::updateInset(Inset const * inset)
3121 if (!d.current_work_area_)
3125 d.current_work_area_->scheduleRedraw();
3127 return &d.current_work_area_->bufferView().buffer();
3131 void GuiView::restartCursor()
3133 /* When we move around, or type, it's nice to be able to see
3134 * the cursor immediately after the keypress.
3136 if (d.current_work_area_)
3137 d.current_work_area_->startBlinkingCursor();
3139 // Take this occasion to update the other GUI elements.
3145 void GuiView::updateCompletion(Cursor & cur, bool start, bool keep)
3147 if (d.current_work_area_)
3148 d.current_work_area_->completer().updateVisibility(cur, start, keep);
3153 // This list should be kept in sync with the list of insets in
3154 // src/insets/Inset.cpp. I.e., if a dialog goes with an inset, the
3155 // dialog should have the same name as the inset.
3156 // Changes should be also recorded in LFUN_DIALOG_SHOW doxygen
3157 // docs in LyXAction.cpp.
3159 char const * const dialognames[] = {
3160 "aboutlyx", "bibitem", "bibtex", "box", "branch", "changes", "character",
3161 "citation", "compare", "document", "errorlist", "ert", "external", "file",
3162 "findreplace", "findreplaceadv", "float", "graphics", "href", "include",
3163 "index", "index_print", "info", "listings", "label", "log", "mathdelimiter",
3164 "mathmatrix", "mathspace", "nomenclature", "nomencl_print", "note",
3165 "paragraph", "phantom", "prefs", "print", "ref", "sendto", "space",
3166 "spellchecker", "symbols", "tabular", "tabularcreate", "thesaurus", "texinfo",
3167 "toc", "view-source", "vspace", "wrap" };
3169 char const * const * const end_dialognames =
3170 dialognames + (sizeof(dialognames) / sizeof(char *));
3174 cmpCStr(char const * name) : name_(name) {}
3175 bool operator()(char const * other) {
3176 return strcmp(other, name_) == 0;
3183 bool isValidName(string const & name)
3185 return find_if(dialognames, end_dialognames,
3186 cmpCStr(name.c_str())) != end_dialognames;
3192 void GuiView::resetDialogs()
3194 // Make sure that no LFUN uses any LyXView.
3195 guiApp->setCurrentView(0);
3198 constructToolbars();
3199 guiApp->menus().fillMenuBar(menuBar(), this, false);
3200 d.layout_->updateContents(true);
3201 // Now update controls with current buffer.
3202 guiApp->setCurrentView(this);
3208 Dialog * GuiView::findOrBuild(string const & name, bool hide_it)
3210 if (!isValidName(name))
3213 map<string, DialogPtr>::iterator it = d.dialogs_.find(name);
3215 if (it != d.dialogs_.end()) {
3217 it->second->hideView();
3218 return it->second.get();
3221 Dialog * dialog = build(name);
3222 d.dialogs_[name].reset(dialog);
3223 if (lyxrc.allow_geometry_session)
3224 dialog->restoreSession();
3231 void GuiView::showDialog(string const & name, string const & data,
3239 Dialog * dialog = findOrBuild(name, false);
3241 dialog->showData(data);
3242 if (inset && currentBufferView())
3243 currentBufferView()->editInset(name, inset);
3246 catch (ExceptionMessage const & ex) {
3254 bool GuiView::isDialogVisible(string const & name) const
3256 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3257 if (it == d.dialogs_.end())
3259 return it->second.get()->isVisibleView() && !it->second.get()->isClosing();
3263 void GuiView::hideDialog(string const & name, Inset * inset)
3265 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3266 if (it == d.dialogs_.end())
3269 if (inset && currentBufferView()
3270 && inset != currentBufferView()->editedInset(name))
3273 Dialog * const dialog = it->second.get();
3274 if (dialog->isVisibleView())
3276 if (currentBufferView())
3277 currentBufferView()->editInset(name, 0);
3281 void GuiView::disconnectDialog(string const & name)
3283 if (!isValidName(name))
3285 if (currentBufferView())
3286 currentBufferView()->editInset(name, 0);
3290 void GuiView::hideAll() const
3292 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
3293 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3295 for(; it != end; ++it)
3296 it->second->hideView();
3300 void GuiView::updateDialogs()
3302 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
3303 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3305 for(; it != end; ++it) {
3306 Dialog * dialog = it->second.get();
3307 if (dialog && dialog->isVisibleView())
3308 dialog->checkStatus();
3315 // will be replaced by a proper factory...
3316 Dialog * createGuiAbout(GuiView & lv);
3317 Dialog * createGuiBibitem(GuiView & lv);
3318 Dialog * createGuiBibtex(GuiView & lv);
3319 Dialog * createGuiBox(GuiView & lv);
3320 Dialog * createGuiBranch(GuiView & lv);
3321 Dialog * createGuiChanges(GuiView & lv);
3322 Dialog * createGuiCharacter(GuiView & lv);
3323 Dialog * createGuiCitation(GuiView & lv);
3324 Dialog * createGuiCompare(GuiView & lv);
3325 Dialog * createGuiDelimiter(GuiView & lv);
3326 Dialog * createGuiDocument(GuiView & lv);
3327 Dialog * createGuiErrorList(GuiView & lv);
3328 Dialog * createGuiERT(GuiView & lv);
3329 Dialog * createGuiExternal(GuiView & lv);
3330 Dialog * createGuiFloat(GuiView & lv);
3331 Dialog * createGuiGraphics(GuiView & lv);
3332 Dialog * createGuiInclude(GuiView & lv);
3333 Dialog * createGuiIndex(GuiView & lv);
3334 Dialog * createGuiInfo(GuiView & lv);
3335 Dialog * createGuiLabel(GuiView & lv);
3336 Dialog * createGuiListings(GuiView & lv);
3337 Dialog * createGuiLog(GuiView & lv);
3338 Dialog * createGuiMathHSpace(GuiView & lv);
3339 Dialog * createGuiMathMatrix(GuiView & lv);
3340 Dialog * createGuiNomenclature(GuiView & lv);
3341 Dialog * createGuiNote(GuiView & lv);
3342 Dialog * createGuiParagraph(GuiView & lv);
3343 Dialog * createGuiPhantom(GuiView & lv);
3344 Dialog * createGuiPreferences(GuiView & lv);
3345 Dialog * createGuiPrint(GuiView & lv);
3346 Dialog * createGuiPrintindex(GuiView & lv);
3347 Dialog * createGuiPrintNomencl(GuiView & lv);
3348 Dialog * createGuiRef(GuiView & lv);
3349 Dialog * createGuiSearch(GuiView & lv);
3350 Dialog * createGuiSearchAdv(GuiView & lv);
3351 Dialog * createGuiSendTo(GuiView & lv);
3352 Dialog * createGuiShowFile(GuiView & lv);
3353 Dialog * createGuiSpellchecker(GuiView & lv);
3354 Dialog * createGuiSymbols(GuiView & lv);
3355 Dialog * createGuiTabularCreate(GuiView & lv);
3356 Dialog * createGuiTabular(GuiView & lv);
3357 Dialog * createGuiTexInfo(GuiView & lv);
3358 Dialog * createGuiTextHSpace(GuiView & lv);
3359 Dialog * createGuiToc(GuiView & lv);
3360 Dialog * createGuiThesaurus(GuiView & lv);
3361 Dialog * createGuiHyperlink(GuiView & lv);
3362 Dialog * createGuiVSpace(GuiView & lv);
3363 Dialog * createGuiViewSource(GuiView & lv);
3364 Dialog * createGuiWrap(GuiView & lv);
3367 Dialog * GuiView::build(string const & name)
3369 LASSERT(isValidName(name), return 0);
3371 if (name == "aboutlyx")
3372 return createGuiAbout(*this);
3373 if (name == "bibitem")
3374 return createGuiBibitem(*this);
3375 if (name == "bibtex")
3376 return createGuiBibtex(*this);
3378 return createGuiBox(*this);
3379 if (name == "branch")
3380 return createGuiBranch(*this);
3381 if (name == "changes")
3382 return createGuiChanges(*this);
3383 if (name == "character")
3384 return createGuiCharacter(*this);
3385 if (name == "citation")
3386 return createGuiCitation(*this);
3387 if (name == "compare")
3388 return createGuiCompare(*this);
3389 if (name == "document")
3390 return createGuiDocument(*this);
3391 if (name == "errorlist")
3392 return createGuiErrorList(*this);
3394 return createGuiERT(*this);
3395 if (name == "external")
3396 return createGuiExternal(*this);
3398 return createGuiShowFile(*this);
3399 if (name == "findreplace")
3400 return createGuiSearch(*this);
3401 if (name == "findreplaceadv")
3402 return createGuiSearchAdv(*this);
3403 if (name == "float")
3404 return createGuiFloat(*this);
3405 if (name == "graphics")
3406 return createGuiGraphics(*this);
3408 return createGuiHyperlink(*this);
3409 if (name == "include")
3410 return createGuiInclude(*this);
3411 if (name == "index")
3412 return createGuiIndex(*this);
3413 if (name == "index_print")
3414 return createGuiPrintindex(*this);
3416 return createGuiInfo(*this);
3417 if (name == "label")
3418 return createGuiLabel(*this);
3419 if (name == "listings")
3420 return createGuiListings(*this);
3422 return createGuiLog(*this);
3423 if (name == "mathdelimiter")
3424 return createGuiDelimiter(*this);
3425 if (name == "mathspace")
3426 return createGuiMathHSpace(*this);
3427 if (name == "mathmatrix")
3428 return createGuiMathMatrix(*this);
3429 if (name == "nomenclature")
3430 return createGuiNomenclature(*this);
3431 if (name == "nomencl_print")
3432 return createGuiPrintNomencl(*this);
3434 return createGuiNote(*this);
3435 if (name == "paragraph")
3436 return createGuiParagraph(*this);
3437 if (name == "phantom")
3438 return createGuiPhantom(*this);
3439 if (name == "prefs")
3440 return createGuiPreferences(*this);
3441 if (name == "print")
3442 return createGuiPrint(*this);
3444 return createGuiRef(*this);
3445 if (name == "sendto")
3446 return createGuiSendTo(*this);
3447 if (name == "space")
3448 return createGuiTextHSpace(*this);
3449 if (name == "spellchecker")
3450 return createGuiSpellchecker(*this);
3451 if (name == "symbols")
3452 return createGuiSymbols(*this);
3453 if (name == "tabular")
3454 return createGuiTabular(*this);
3455 if (name == "tabularcreate")
3456 return createGuiTabularCreate(*this);
3457 if (name == "texinfo")
3458 return createGuiTexInfo(*this);
3459 if (name == "thesaurus")
3460 return createGuiThesaurus(*this);
3462 return createGuiToc(*this);
3463 if (name == "view-source")
3464 return createGuiViewSource(*this);
3465 if (name == "vspace")
3466 return createGuiVSpace(*this);
3468 return createGuiWrap(*this);
3474 } // namespace frontend
3477 #include "moc_GuiView.cpp"