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"
31 #include "qt_helpers.h"
33 #include "frontends/alert.h"
35 #include "buffer_funcs.h"
37 #include "BufferList.h"
38 #include "BufferParams.h"
39 #include "BufferView.h"
40 #include "Converter.h"
43 #include "ErrorList.h"
45 #include "FuncStatus.h"
46 #include "FuncRequest.h"
54 #include "Paragraph.h"
55 #include "SpellChecker.h"
56 #include "TextClass.h"
61 #include "support/convert.h"
62 #include "support/debug.h"
63 #include "support/ExceptionMessage.h"
64 #include "support/FileName.h"
65 #include "support/filetools.h"
66 #include "support/gettext.h"
67 #include "support/ForkedCalls.h"
68 #include "support/lassert.h"
69 #include "support/lstrings.h"
70 #include "support/os.h"
71 #include "support/Package.h"
72 #include "support/Timeout.h"
75 #include <QApplication>
76 #include <QCloseEvent>
78 #include <QDesktopWidget>
79 #include <QDragEnterEvent>
86 #include <QPixmapCache>
88 #include <QPushButton>
92 #include <QStackedWidget>
99 #include <boost/bind.hpp>
101 #ifdef HAVE_SYS_TIME_H
102 # include <sys/time.h>
109 using namespace lyx::support;
116 class BackgroundWidget : public QWidget
121 LYXERR(Debug::GUI, "show banner: " << lyxrc.show_banner);
122 /// The text to be written on top of the pixmap
123 QString const text = lyx_version ?
124 qt_("version ") + lyx_version : qt_("unknown version");
125 splash_ = getPixmap("images/", "banner", "png");
127 QPainter pain(&splash_);
128 pain.setPen(QColor(0, 0, 0));
130 // The font used to display the version info
131 font.setStyleHint(QFont::SansSerif);
132 font.setWeight(QFont::Bold);
133 font.setPointSize(int(toqstr(lyxrc.font_sizes[FONT_SIZE_LARGE]).toDouble()));
135 pain.drawText(260, 15, text);
138 void paintEvent(QPaintEvent *)
140 int x = (width() - splash_.width()) / 2;
141 int y = (height() - splash_.height()) / 2;
143 pain.drawPixmap(x, y, splash_);
151 /// Toolbar store providing access to individual toolbars by name.
152 typedef std::map<std::string, GuiToolbar *> ToolbarMap;
154 typedef boost::shared_ptr<Dialog> DialogPtr;
159 struct GuiView::GuiViewPrivate
162 : current_work_area_(0), current_main_work_area_(0),
163 layout_(0), autosave_timeout_(5000),
166 // hardcode here the platform specific icon size
167 smallIconSize = 14; // scaling problems
168 normalIconSize = 20; // ok, default
169 bigIconSize = 26; // better for some math icons
171 splitter_ = new QSplitter;
172 bg_widget_ = new BackgroundWidget;
173 stack_widget_ = new QStackedWidget;
174 stack_widget_->addWidget(bg_widget_);
175 stack_widget_->addWidget(splitter_);
183 delete stack_widget_;
186 QMenu * toolBarPopup(GuiView * parent)
188 // FIXME: translation
189 QMenu * menu = new QMenu(parent);
190 QActionGroup * iconSizeGroup = new QActionGroup(parent);
192 QAction * smallIcons = new QAction(iconSizeGroup);
193 smallIcons->setText(qt_("Small-sized icons"));
194 smallIcons->setCheckable(true);
195 QObject::connect(smallIcons, SIGNAL(triggered()),
196 parent, SLOT(smallSizedIcons()));
197 menu->addAction(smallIcons);
199 QAction * normalIcons = new QAction(iconSizeGroup);
200 normalIcons->setText(qt_("Normal-sized icons"));
201 normalIcons->setCheckable(true);
202 QObject::connect(normalIcons, SIGNAL(triggered()),
203 parent, SLOT(normalSizedIcons()));
204 menu->addAction(normalIcons);
206 QAction * bigIcons = new QAction(iconSizeGroup);
207 bigIcons->setText(qt_("Big-sized icons"));
208 bigIcons->setCheckable(true);
209 QObject::connect(bigIcons, SIGNAL(triggered()),
210 parent, SLOT(bigSizedIcons()));
211 menu->addAction(bigIcons);
213 unsigned int cur = parent->iconSize().width();
214 if ( cur == parent->d.smallIconSize)
215 smallIcons->setChecked(true);
216 else if (cur == parent->d.normalIconSize)
217 normalIcons->setChecked(true);
218 else if (cur == parent->d.bigIconSize)
219 bigIcons->setChecked(true);
226 stack_widget_->setCurrentWidget(bg_widget_);
227 bg_widget_->setUpdatesEnabled(true);
230 TabWorkArea * tabWorkArea(int i)
232 return dynamic_cast<TabWorkArea *>(splitter_->widget(i));
235 TabWorkArea * currentTabWorkArea()
237 if (splitter_->count() == 1)
238 // The first TabWorkArea is always the first one, if any.
239 return tabWorkArea(0);
241 for (int i = 0; i != splitter_->count(); ++i) {
242 TabWorkArea * twa = tabWorkArea(i);
243 if (current_main_work_area_ == twa->currentWorkArea())
247 // None has the focus so we just take the first one.
248 return tabWorkArea(0);
252 GuiWorkArea * current_work_area_;
253 GuiWorkArea * current_main_work_area_;
254 QSplitter * splitter_;
255 QStackedWidget * stack_widget_;
256 BackgroundWidget * bg_widget_;
258 ToolbarMap toolbars_;
259 /// The main layout box.
261 * \warning Don't Delete! The layout box is actually owned by
262 * whichever toolbar contains it. All the GuiView class needs is a
263 * means of accessing it.
265 * FIXME: replace that with a proper model so that we are not limited
266 * to only one dialog.
268 GuiLayoutBox * layout_;
271 map<string, Inset *> open_insets_;
274 map<string, DialogPtr> dialogs_;
276 unsigned int smallIconSize;
277 unsigned int normalIconSize;
278 unsigned int bigIconSize;
280 QTimer statusbar_timer_;
281 /// auto-saving of buffers
282 Timeout autosave_timeout_;
283 /// flag against a race condition due to multiclicks, see bug #1119
287 TocModels toc_models_;
291 GuiView::GuiView(int id)
292 : d(*new GuiViewPrivate), id_(id), closing_(false)
294 // GuiToolbars *must* be initialised before the menu bar.
295 normalSizedIcons(); // at least on Mac the default is 32 otherwise, which is huge
298 // set ourself as the current view. This is needed for the menu bar
299 // filling, at least for the static special menu item on Mac. Otherwise
300 // they are greyed out.
301 theLyXFunc().setLyXView(this);
303 // Fill up the menu bar.
304 guiApp->menus().fillMenuBar(menuBar(), this, true);
306 setCentralWidget(d.stack_widget_);
308 // Start autosave timer
309 if (lyxrc.autosave) {
310 d.autosave_timeout_.timeout.connect(boost::bind(&GuiView::autoSave, this));
311 d.autosave_timeout_.setTimeout(lyxrc.autosave * 1000);
312 d.autosave_timeout_.start();
314 connect(&d.statusbar_timer_, SIGNAL(timeout()),
315 this, SLOT(clearMessage()));
317 // We don't want to keep the window in memory if it is closed.
318 setAttribute(Qt::WA_DeleteOnClose, true);
320 #if (!defined(Q_WS_WIN) && !defined(Q_WS_MACX))
321 // assign an icon to main form. We do not do it under Qt/Win or Qt/Mac,
322 // since the icon is provided in the application bundle.
323 setWindowIcon(getPixmap("images/", "lyx", "png"));
327 setAcceptDrops(true);
329 statusBar()->setSizeGripEnabled(true);
331 // Forbid too small unresizable window because it can happen
332 // with some window manager under X11.
333 setMinimumSize(300, 200);
335 if (lyxrc.allow_geometry_session) {
336 // Now take care of session management.
341 // no session handling, default to a sane size.
342 setGeometry(50, 50, 690, 510);
345 // clear session data if any.
347 settings.remove("views");
357 void GuiView::saveLayout() const
360 settings.beginGroup("views");
361 settings.beginGroup(QString::number(id_));
363 settings.setValue("pos", pos());
364 settings.setValue("size", size());
366 settings.setValue("geometry", saveGeometry());
368 settings.setValue("layout", saveState(0));
369 settings.setValue("icon_size", iconSize());
373 bool GuiView::restoreLayout()
376 settings.beginGroup("views");
377 settings.beginGroup(QString::number(id_));
378 QString const icon_key = "icon_size";
379 if (!settings.contains(icon_key))
382 //code below is skipped when when ~/.config/LyX is (re)created
383 setIconSize(settings.value(icon_key).toSize());
385 QPoint pos = settings.value("pos", QPoint(50, 50)).toPoint();
386 QSize size = settings.value("size", QSize(690, 510)).toSize();
390 if (!restoreGeometry(settings.value("geometry").toByteArray()))
391 setGeometry(50, 50, 690, 510);
393 // Make sure layout is correctly oriented.
394 setLayoutDirection(qApp->layoutDirection());
396 // Allow the toc and view-source dock widget to be restored if needed.
398 if ((dialog = findOrBuild("toc", true)))
399 // see bug 5082. At least setup title and enabled state.
400 // Visibility will be adjusted by restoreState below.
401 dialog->prepareView();
402 if ((dialog = findOrBuild("view-source", true)))
403 dialog->prepareView();
405 if (!restoreState(settings.value("layout").toByteArray(), 0))
412 GuiToolbar * GuiView::toolbar(string const & name)
414 ToolbarMap::iterator it = d.toolbars_.find(name);
415 if (it != d.toolbars_.end())
418 LYXERR(Debug::GUI, "Toolbar::display: no toolbar named " << name);
419 message(bformat(_("Unknown toolbar \"%1$s\""), from_utf8(name)));
424 void GuiView::constructToolbars()
426 ToolbarMap::iterator it = d.toolbars_.begin();
427 for (; it != d.toolbars_.end(); ++it)
432 // extracts the toolbars from the backend
433 Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
434 Toolbars::Infos::iterator end = guiApp->toolbars().end();
435 for (; cit != end; ++cit)
436 d.toolbars_[cit->name] = new GuiToolbar(*cit, *this);
440 void GuiView::initToolbars()
442 // extracts the toolbars from the backend
443 Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
444 Toolbars::Infos::iterator end = guiApp->toolbars().end();
445 for (; cit != end; ++cit) {
446 GuiToolbar * tb = toolbar(cit->name);
449 int const visibility = guiApp->toolbars().defaultVisibility(cit->name);
451 tb->setVisible(false);
452 tb->setVisibility(visibility);
454 if (visibility & Toolbars::TOP) {
456 addToolBarBreak(Qt::TopToolBarArea);
457 addToolBar(Qt::TopToolBarArea, tb);
460 if (visibility & Toolbars::BOTTOM) {
461 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
462 #if (QT_VERSION >= 0x040202)
463 addToolBarBreak(Qt::BottomToolBarArea);
465 addToolBar(Qt::BottomToolBarArea, tb);
468 if (visibility & Toolbars::LEFT) {
469 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
470 #if (QT_VERSION >= 0x040202)
471 addToolBarBreak(Qt::LeftToolBarArea);
473 addToolBar(Qt::LeftToolBarArea, tb);
476 if (visibility & Toolbars::RIGHT) {
477 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
478 #if (QT_VERSION >= 0x040202)
479 addToolBarBreak(Qt::RightToolBarArea);
481 addToolBar(Qt::RightToolBarArea, tb);
484 if (visibility & Toolbars::ON)
485 tb->setVisible(true);
490 TocModels & GuiView::tocModels()
492 return d.toc_models_;
496 void GuiView::setFocus()
498 LYXERR(Debug::DEBUG, "GuiView::setFocus()" << this);
499 // Make sure LyXFunc points to the correct view.
500 guiApp->setCurrentView(this);
501 theLyXFunc().setLyXView(this);
502 QMainWindow::setFocus();
503 if (d.current_work_area_)
504 d.current_work_area_->setFocus();
508 QMenu * GuiView::createPopupMenu()
510 return d.toolBarPopup(this);
514 void GuiView::showEvent(QShowEvent * e)
516 LYXERR(Debug::GUI, "Passed Geometry "
517 << size().height() << "x" << size().width()
518 << "+" << pos().x() << "+" << pos().y());
520 if (d.splitter_->count() == 0)
521 // No work area, switch to the background widget.
524 QMainWindow::showEvent(e);
528 /** Destroy only all tabbed WorkAreas. Destruction of other WorkAreas
529 ** is responsibility of the container (e.g., dialog)
531 void GuiView::closeEvent(QCloseEvent * close_event)
533 LYXERR(Debug::DEBUG, "GuiView::closeEvent()");
536 // it can happen that this event arrives without selecting the view,
537 // e.g. when clicking the close button on a background window.
539 GuiWorkArea * active_wa = currentMainWorkArea();
540 setCurrentWorkArea(active_wa);
542 // We might be in a situation that there is still a tabWorkArea, but
543 // there are no tabs anymore. This can happen when we get here after a
544 // TabWorkArea::lastWorkAreaRemoved() signal. Therefore we count how
545 // many TabWorkArea's have no documents anymore.
548 // We have to call count() each time, because it can happen that
549 // more than one splitter will disappear in one iteration (bug 5998).
550 for (; d.splitter_->count() > empty_twa; ) {
551 TabWorkArea * twa = d.tabWorkArea(empty_twa);
553 int twa_count = twa->count();
554 if (twa->count() == 0)
557 for (; twa_count; --twa_count) {
558 twa->setCurrentIndex(twa_count-1);
560 GuiWorkArea * wa = twa->currentWorkArea();
561 bool const is_active_wa = active_wa == wa;
562 Buffer * b = &wa->bufferView().buffer();
564 // This is a child document, just close the tab
565 // after saving but keep the file loaded.
566 if (!closeBuffer(*b, true, is_active_wa)) {
568 close_event->ignore();
574 vector<Buffer *> clist = b->getChildren();
575 for (vector<Buffer *>::const_iterator it = clist.begin();
576 it != clist.end(); ++it) {
577 if ((*it)->isClean())
580 // If a child is dirty, do not close
581 // without user intervention
582 if (!closeBuffer(*c, false)) {
584 close_event->ignore();
589 QList<int> const ids = guiApp->viewIds();
590 for (int i = 0; i != ids.size(); ++i) {
593 if (guiApp->view(ids[i]).workArea(*b)) {
594 // FIXME 1: should we put an alert box here
595 // that the buffer is viewed elsewhere?
596 // FIXME 2: should we try to save this buffer in any case?
599 // This buffer is also opened in another view, so
600 // close the associated work area...
602 // ... but don't close the buffer.
607 // closeBuffer() needs buffer workArea still alive and
608 // set as currrent one, and destroys it
609 if (b && !closeBuffer(*b, true, is_active_wa)) {
611 close_event->ignore();
616 // Make sure that nothing will use this close to be closed View.
617 guiApp->unregisterView(this);
619 if (isFullScreen()) {
620 // Switch off fullscreen before closing.
625 // Make sure the timer time out will not trigger a statusbar update.
626 d.statusbar_timer_.stop();
628 // Saving fullscreen requires additional tweaks in the toolbar code.
629 // It wouldn't also work under linux natively.
630 if (lyxrc.allow_geometry_session) {
631 // Save this window geometry and layout.
633 // Then the toolbar private states.
634 ToolbarMap::iterator end = d.toolbars_.end();
635 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
636 it->second->saveSession();
637 // Now take care of all other dialogs:
638 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
639 for (; it!= d.dialogs_.end(); ++it)
640 it->second->saveSession();
643 close_event->accept();
647 void GuiView::dragEnterEvent(QDragEnterEvent * event)
649 if (event->mimeData()->hasUrls())
651 /// \todo Ask lyx-devel is this is enough:
652 /// if (event->mimeData()->hasFormat("text/plain"))
653 /// event->acceptProposedAction();
657 void GuiView::dropEvent(QDropEvent * event)
659 QList<QUrl> files = event->mimeData()->urls();
663 LYXERR(Debug::GUI, "GuiView::dropEvent: got URLs!");
664 for (int i = 0; i != files.size(); ++i) {
665 string const file = os::internal_path(fromqstr(
666 files.at(i).toLocalFile()));
668 // Asynchronously post the event. DropEvent usually come
669 // from the BufferView. But reloading a file might close
670 // the BufferView from within its own event handler.
671 guiApp->dispatchDelayed(FuncRequest(LFUN_FILE_OPEN, file));
678 void GuiView::message(docstring const & str)
680 if (ForkedProcess::iAmAChild())
683 statusBar()->showMessage(toqstr(str));
684 d.statusbar_timer_.stop();
685 d.statusbar_timer_.start(3000);
689 void GuiView::smallSizedIcons()
691 setIconSize(QSize(d.smallIconSize, d.smallIconSize));
695 void GuiView::normalSizedIcons()
697 setIconSize(QSize(d.normalIconSize, d.normalIconSize));
701 void GuiView::bigSizedIcons()
703 setIconSize(QSize(d.bigIconSize, d.bigIconSize));
707 void GuiView::clearMessage()
711 theLyXFunc().setLyXView(this);
712 statusBar()->showMessage(toqstr(theLyXFunc().viewStatusMessage()));
713 d.statusbar_timer_.stop();
717 void GuiView::updateWindowTitle(GuiWorkArea * wa)
719 if (wa != d.current_work_area_)
721 setWindowTitle(qt_("LyX: ") + wa->windowTitle());
722 setWindowIconText(wa->windowIconText());
726 void GuiView::on_currentWorkAreaChanged(GuiWorkArea * wa)
729 disconnectBufferView();
730 connectBufferView(wa->bufferView());
731 connectBuffer(wa->bufferView().buffer());
732 d.current_work_area_ = wa;
733 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
734 this, SLOT(updateWindowTitle(GuiWorkArea *)));
735 updateWindowTitle(wa);
739 // The document settings needs to be reinitialised.
740 updateDialog("document", "");
742 // Buffer-dependent dialogs must be updated. This is done here because
743 // some dialogs require buffer()->text.
748 void GuiView::on_lastWorkAreaRemoved()
751 // We already are in a close event. Nothing more to do.
754 if (d.splitter_->count() > 1)
755 // We have a splitter so don't close anything.
758 // Reset and updates the dialogs.
759 d.toc_models_.reset(0);
760 updateDialog("document", "");
763 resetWindowTitleAndIconText();
765 if (lyxrc.open_buffers_in_tabs)
766 // Nothing more to do, the window should stay open.
769 if (guiApp->viewIds().size() > 1) {
775 // On Mac we also close the last window because the application stay
776 // resident in memory. On other platforms we don't close the last
777 // window because this would quit the application.
783 void GuiView::updateStatusBar()
785 // let the user see the explicit message
786 if (d.statusbar_timer_.isActive())
789 theLyXFunc().setLyXView(this);
790 statusBar()->showMessage(toqstr(theLyXFunc().viewStatusMessage()));
794 bool GuiView::hasFocus() const
796 return qApp->activeWindow() == this;
800 bool GuiView::event(QEvent * e)
804 // Useful debug code:
805 //case QEvent::ActivationChange:
806 //case QEvent::WindowDeactivate:
807 //case QEvent::Paint:
808 //case QEvent::Enter:
809 //case QEvent::Leave:
810 //case QEvent::HoverEnter:
811 //case QEvent::HoverLeave:
812 //case QEvent::HoverMove:
813 //case QEvent::StatusTip:
814 //case QEvent::DragEnter:
815 //case QEvent::DragLeave:
819 case QEvent::WindowActivate: {
820 if (this == guiApp->currentView()) {
822 return QMainWindow::event(e);
824 guiApp->setCurrentView(this);
825 theLyXFunc().setLyXView(this);
826 if (d.current_work_area_) {
827 BufferView & bv = d.current_work_area_->bufferView();
828 connectBufferView(bv);
829 connectBuffer(bv.buffer());
830 // The document structure, name and dialogs might have
831 // changed in another view.
833 // The document settings needs to be reinitialised.
834 updateDialog("document", "");
837 resetWindowTitleAndIconText();
840 return QMainWindow::event(e);
843 case QEvent::ShortcutOverride: {
846 #if (!defined Q_WS_X11) || (QT_VERSION >= 0x040500)
847 if (isFullScreen() && menuBar()->isHidden()) {
848 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
849 // FIXME: we should also try to detect special LyX shortcut such as
850 // Alt-P and Alt-M. Right now there is a hack in
851 // GuiWorkArea::processKeySym() that hides again the menubar for
853 if (ke->modifiers() & Qt::AltModifier && ke->key() != Qt::Key_Alt) {
855 return QMainWindow::event(e);
860 if (d.current_work_area_)
861 // Nothing special to do.
862 return QMainWindow::event(e);
864 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
865 // Let Qt handle menu access and the Tab keys to navigate keys to navigate
867 if (ke->modifiers() & Qt::AltModifier || ke->key() == Qt::Key_Tab
868 || ke->key() == Qt::Key_Backtab)
869 return QMainWindow::event(e);
871 // Allow processing of shortcuts that are allowed even when no Buffer
873 theLyXFunc().setLyXView(this);
875 setKeySymbol(&sym, ke);
876 theLyXFunc().processKeySym(sym, q_key_state(ke->modifiers()));
882 return QMainWindow::event(e);
886 void GuiView::resetWindowTitleAndIconText()
888 setWindowTitle(qt_("LyX"));
889 setWindowIconText(qt_("LyX"));
892 bool GuiView::focusNextPrevChild(bool /*next*/)
899 void GuiView::setBusy(bool busy)
901 if (d.current_work_area_) {
902 d.current_work_area_->setUpdatesEnabled(!busy);
904 d.current_work_area_->stopBlinkingCursor();
906 d.current_work_area_->startBlinkingCursor();
910 QApplication::setOverrideCursor(Qt::WaitCursor);
912 QApplication::restoreOverrideCursor();
916 GuiWorkArea * GuiView::workArea(Buffer & buffer)
918 if (currentWorkArea()
919 && ¤tWorkArea()->bufferView().buffer() == &buffer)
920 return (GuiWorkArea *) currentWorkArea();
921 if (TabWorkArea * twa = d.currentTabWorkArea())
922 return twa->workArea(buffer);
927 GuiWorkArea * GuiView::addWorkArea(Buffer & buffer)
929 // Automatically create a TabWorkArea if there are none yet.
930 TabWorkArea * tab_widget = d.splitter_->count()
931 ? d.currentTabWorkArea() : addTabWorkArea();
932 return tab_widget->addWorkArea(buffer, *this);
936 TabWorkArea * GuiView::addTabWorkArea()
938 TabWorkArea * twa = new TabWorkArea;
939 QObject::connect(twa, SIGNAL(currentWorkAreaChanged(GuiWorkArea *)),
940 this, SLOT(on_currentWorkAreaChanged(GuiWorkArea *)));
941 QObject::connect(twa, SIGNAL(lastWorkAreaRemoved()),
942 this, SLOT(on_lastWorkAreaRemoved()));
944 d.splitter_->addWidget(twa);
945 d.stack_widget_->setCurrentWidget(d.splitter_);
950 GuiWorkArea const * GuiView::currentWorkArea() const
952 return d.current_work_area_;
956 GuiWorkArea * GuiView::currentWorkArea()
958 return d.current_work_area_;
962 GuiWorkArea const * GuiView::currentMainWorkArea() const
964 if (d.currentTabWorkArea() == NULL)
966 return d.currentTabWorkArea()->currentWorkArea();
970 GuiWorkArea * GuiView::currentMainWorkArea()
972 if (d.currentTabWorkArea() == NULL)
974 return d.currentTabWorkArea()->currentWorkArea();
978 void GuiView::setCurrentWorkArea(GuiWorkArea * wa)
980 LYXERR(Debug::DEBUG, "Setting current wa: " << wa << endl);
982 d.current_work_area_ = NULL;
986 GuiWorkArea * old_gwa = theGuiApp()->currentView()->currentWorkArea();
990 theGuiApp()->setCurrentView(this);
991 d.current_work_area_ = wa;
992 for (int i = 0; i != d.splitter_->count(); ++i) {
993 if (d.tabWorkArea(i)->setCurrentWorkArea(wa)) {
994 //if (d.current_main_work_area_)
995 // d.current_main_work_area_->setFrameStyle(QFrame::NoFrame);
996 d.current_main_work_area_ = wa;
997 //d.current_main_work_area_->setFrameStyle(QFrame::Box | QFrame::Plain);
998 //d.current_main_work_area_->setLineWidth(2);
999 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() << ", Current main wa: " << currentMainWorkArea());
1003 LYXERR(Debug::DEBUG, "This is not a tabbed wa");
1004 on_currentWorkAreaChanged(wa);
1005 BufferView & bv = wa->bufferView();
1006 bv.cursor().fixIfBroken();
1008 wa->setUpdatesEnabled(true);
1009 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() << ", Current main wa: " << currentMainWorkArea());
1013 void GuiView::removeWorkArea(GuiWorkArea * wa)
1015 LASSERT(wa, return);
1016 if (wa == d.current_work_area_) {
1018 disconnectBufferView();
1019 d.current_work_area_ = 0;
1020 d.current_main_work_area_ = 0;
1023 bool found_twa = false;
1024 for (int i = 0; i != d.splitter_->count(); ++i) {
1025 TabWorkArea * twa = d.tabWorkArea(i);
1026 if (twa->removeWorkArea(wa)) {
1027 // Found in this tab group, and deleted the GuiWorkArea.
1029 if (twa->count() != 0) {
1030 if (d.current_work_area_ == 0)
1031 // This means that we are closing the current GuiWorkArea, so
1032 // switch to the next GuiWorkArea in the found TabWorkArea.
1033 setCurrentWorkArea(twa->currentWorkArea());
1035 // No more WorkAreas in this tab group, so delete it.
1042 // It is not a tabbed work area (i.e., the search work area), so it
1043 // should be deleted by other means.
1044 LASSERT(found_twa, /* */);
1046 if (d.current_work_area_ == 0) {
1047 if (d.splitter_->count() != 0) {
1048 TabWorkArea * twa = d.currentTabWorkArea();
1049 setCurrentWorkArea(twa->currentWorkArea());
1051 // No more work areas, switch to the background widget.
1052 setCurrentWorkArea(0);
1058 void GuiView::setLayoutDialog(GuiLayoutBox * layout)
1064 void GuiView::updateLayoutList()
1067 d.layout_->updateContents(false);
1071 void GuiView::updateToolbars()
1073 ToolbarMap::iterator end = d.toolbars_.end();
1074 if (d.current_work_area_) {
1076 d.current_work_area_->bufferView().cursor().inMathed();
1078 lyx::getStatus(FuncRequest(LFUN_LAYOUT_TABULAR)).enabled();
1080 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).enabled() &&
1081 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).onoff(true);
1082 bool const mathmacrotemplate =
1083 lyx::getStatus(FuncRequest(LFUN_IN_MATHMACROTEMPLATE)).enabled();
1085 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1086 it->second->update(math, table, review, mathmacrotemplate);
1088 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1089 it->second->update(false, false, false, false);
1093 Buffer * GuiView::buffer()
1095 if (d.current_work_area_)
1096 return &d.current_work_area_->bufferView().buffer();
1101 Buffer const * GuiView::buffer() const
1103 if (d.current_work_area_)
1104 return &d.current_work_area_->bufferView().buffer();
1109 void GuiView::setBuffer(Buffer * newBuffer)
1111 LYXERR(Debug::DEBUG, "Setting buffer: " << newBuffer << std::endl);
1112 LASSERT(newBuffer, return);
1115 GuiWorkArea * wa = workArea(*newBuffer);
1117 newBuffer->masterBuffer()->updateLabels();
1118 wa = addWorkArea(*newBuffer);
1120 //Disconnect the old buffer...there's no new one.
1123 connectBuffer(*newBuffer);
1124 connectBufferView(wa->bufferView());
1125 setCurrentWorkArea(wa);
1131 void GuiView::connectBuffer(Buffer & buf)
1133 buf.setGuiDelegate(this);
1137 void GuiView::disconnectBuffer()
1139 if (d.current_work_area_)
1140 d.current_work_area_->bufferView().setGuiDelegate(0);
1144 void GuiView::connectBufferView(BufferView & bv)
1146 bv.setGuiDelegate(this);
1150 void GuiView::disconnectBufferView()
1152 if (d.current_work_area_)
1153 d.current_work_area_->bufferView().setGuiDelegate(0);
1157 void GuiView::errors(string const & error_type, bool from_master)
1159 ErrorList & el = from_master ?
1160 buffer()->masterBuffer()->errorList(error_type)
1161 : buffer()->errorList(error_type);
1162 string data = error_type;
1164 data = "from_master|" + error_type;
1166 showDialog("errorlist", data);
1170 void GuiView::updateTocItem(std::string const & type, DocIterator const & dit)
1172 d.toc_models_.updateItem(toqstr(type), dit);
1176 void GuiView::structureChanged()
1178 d.toc_models_.reset(view());
1179 // Navigator needs more than a simple update in this case. It needs to be
1181 updateDialog("toc", "");
1185 void GuiView::updateDialog(string const & name, string const & data)
1187 if (!isDialogVisible(name))
1190 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
1191 if (it == d.dialogs_.end())
1194 Dialog * const dialog = it->second.get();
1195 if (dialog->isVisibleView())
1196 dialog->initialiseParams(data);
1200 BufferView * GuiView::view()
1202 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1206 void GuiView::autoSave()
1208 LYXERR(Debug::INFO, "Running autoSave()");
1211 view()->buffer().autoSave();
1215 void GuiView::resetAutosaveTimers()
1218 d.autosave_timeout_.restart();
1222 bool GuiView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1225 Buffer * buf = buffer();
1227 if (cmd.origin == FuncRequest::TOC) {
1228 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
1230 if (toc->getStatus(view()->cursor(), cmd, fs))
1233 flag.setEnabled(false);
1237 switch(cmd.action) {
1238 case LFUN_BUFFER_WRITE:
1239 enable = buf && (buf->isUnnamed() || !buf->isClean());
1242 case LFUN_BUFFER_WRITE_AS:
1246 case LFUN_SPLIT_VIEW:
1247 if (cmd.getArg(0) == "vertical")
1248 enable = buf && (d.splitter_->count() == 1 ||
1249 d.splitter_->orientation() == Qt::Vertical);
1251 enable = buf && (d.splitter_->count() == 1 ||
1252 d.splitter_->orientation() == Qt::Horizontal);
1255 case LFUN_CLOSE_TAB_GROUP:
1256 enable = d.currentTabWorkArea();
1259 case LFUN_TOOLBAR_TOGGLE:
1260 if (GuiToolbar * t = toolbar(cmd.getArg(0)))
1261 flag.setOnOff(t->isVisible());
1264 case LFUN_UI_TOGGLE:
1265 flag.setOnOff(isFullScreen());
1268 case LFUN_DIALOG_TOGGLE:
1269 flag.setOnOff(isDialogVisible(cmd.getArg(0)));
1270 // fall through to set "enable"
1271 case LFUN_DIALOG_SHOW: {
1272 string const name = cmd.getArg(0);
1274 enable = name == "aboutlyx"
1275 || name == "file" //FIXME: should be removed.
1277 || name == "texinfo";
1278 else if (name == "print")
1279 enable = buf->isExportable("dvi")
1280 && lyxrc.print_command != "none";
1281 else if (name == "character" || name == "symbols") {
1282 if (!view() || !view()->cursor().inTexted())
1285 // FIXME we should consider passthru
1287 Inset const & in = view()->cursor().inset();
1288 enable = !in.getLayout().isPassThru();
1291 else if (name == "latexlog")
1292 enable = FileName(buf->logName()).isReadableFile();
1293 else if (name == "spellchecker")
1294 enable = theSpellChecker() && !buf->isReadonly();
1295 else if (name == "vclog")
1296 enable = buf->lyxvc().inUse();
1300 case LFUN_DIALOG_UPDATE: {
1301 string const name = cmd.getArg(0);
1303 enable = name == "prefs";
1307 case LFUN_INSET_APPLY: {
1308 string const name = cmd.getArg(0);
1309 Inset * inset = getOpenInset(name);
1311 FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument());
1313 if (!inset->getStatus(view()->cursor(), fr, fs)) {
1314 // Every inset is supposed to handle this
1315 LASSERT(false, break);
1319 FuncRequest fr(LFUN_INSET_INSERT, cmd.argument());
1320 flag |= lyx::getStatus(fr);
1322 enable = flag.enabled();
1326 case LFUN_COMPLETION_INLINE:
1327 if (!d.current_work_area_
1328 || !d.current_work_area_->completer().inlinePossible(view()->cursor()))
1332 case LFUN_COMPLETION_POPUP:
1333 if (!d.current_work_area_
1334 || !d.current_work_area_->completer().popupPossible(view()->cursor()))
1338 case LFUN_COMPLETION_COMPLETE:
1339 if (!d.current_work_area_
1340 || !d.current_work_area_->completer().inlinePossible(view()->cursor()))
1344 case LFUN_COMPLETION_ACCEPT:
1345 if (!d.current_work_area_
1346 || (!d.current_work_area_->completer().popupVisible()
1347 && !d.current_work_area_->completer().inlineVisible()
1348 && !d.current_work_area_->completer().completionAvailable()))
1352 case LFUN_COMPLETION_CANCEL:
1353 if (!d.current_work_area_
1354 || (!d.current_work_area_->completer().popupVisible()
1355 && !d.current_work_area_->completer().inlineVisible()))
1359 case LFUN_BUFFER_ZOOM_OUT:
1360 enable = buf && lyxrc.zoom > 10;
1363 case LFUN_BUFFER_ZOOM_IN:
1372 flag.setEnabled(false);
1378 static FileName selectTemplateFile()
1380 FileDialog dlg(qt_("Select template file"));
1381 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1382 dlg.setButton1(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
1384 FileDialog::Result result = dlg.open(toqstr(lyxrc.template_path),
1385 QStringList(qt_("LyX Documents (*.lyx)")));
1387 if (result.first == FileDialog::Later)
1389 if (result.second.isEmpty())
1391 return FileName(fromqstr(result.second));
1395 Buffer * GuiView::loadDocument(FileName const & filename, bool tolastfiles)
1399 Buffer * newBuffer = checkAndLoadLyXFile(filename);
1402 message(_("Document not loaded."));
1407 setBuffer(newBuffer);
1409 // scroll to the position when the file was last closed
1410 if (lyxrc.use_lastfilepos) {
1411 LastFilePosSection::FilePos filepos =
1412 theSession().lastFilePos().load(filename);
1413 view()->moveToPosition(filepos.pit, filepos.pos, 0, 0);
1417 theSession().lastFiles().add(filename);
1424 void GuiView::openDocument(string const & fname)
1426 string initpath = lyxrc.document_path;
1429 string const trypath = buffer()->filePath();
1430 // If directory is writeable, use this as default.
1431 if (FileName(trypath).isDirWritable())
1437 if (fname.empty()) {
1438 FileDialog dlg(qt_("Select document to open"), LFUN_FILE_OPEN);
1439 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1440 dlg.setButton2(qt_("Examples|#E#e"),
1441 toqstr(addPath(package().system_support().absFilename(), "examples")));
1443 QStringList filter(qt_("LyX Documents (*.lyx)"));
1444 filter << qt_("LyX-1.3.x Documents (*.lyx13)")
1445 << qt_("LyX-1.4.x Documents (*.lyx14)")
1446 << qt_("LyX-1.5.x Documents (*.lyx15)")
1447 << qt_("LyX-1.6.x Documents (*.lyx16)");
1448 FileDialog::Result result =
1449 dlg.open(toqstr(initpath), filter);
1451 if (result.first == FileDialog::Later)
1454 filename = fromqstr(result.second);
1456 // check selected filename
1457 if (filename.empty()) {
1458 message(_("Canceled."));
1464 // get absolute path of file and add ".lyx" to the filename if
1466 FileName const fullname =
1467 fileSearch(string(), filename, "lyx", support::may_not_exist);
1468 if (!fullname.empty())
1469 filename = fullname.absFilename();
1471 if (!fullname.onlyPath().isDirectory()) {
1472 Alert::warning(_("Invalid filename"),
1473 bformat(_("The directory in the given path\n%1$s\ndoes not exist."),
1474 from_utf8(fullname.absFilename())));
1477 // if the file doesn't exist, let the user create one
1478 if (!fullname.exists()) {
1479 // the user specifically chose this name. Believe him.
1480 Buffer * const b = newFile(filename, string(), true);
1486 docstring const disp_fn = makeDisplayPath(filename);
1487 message(bformat(_("Opening document %1$s..."), disp_fn));
1490 Buffer * buf = loadDocument(fullname);
1492 buf->updateLabels();
1494 buf->errors("Parse");
1495 str2 = bformat(_("Document %1$s opened."), disp_fn);
1496 if (buf->lyxvc().inUse())
1497 str2 += " " + from_utf8(buf->lyxvc().versionString()) +
1498 " " + _("Version control detected.");
1500 str2 = bformat(_("Could not open document %1$s"), disp_fn);
1505 // FIXME: clean that
1506 static bool import(GuiView * lv, FileName const & filename,
1507 string const & format, ErrorList & errorList)
1509 FileName const lyxfile(support::changeExtension(filename.absFilename(), ".lyx"));
1511 string loader_format;
1512 vector<string> loaders = theConverters().loaders();
1513 if (find(loaders.begin(), loaders.end(), format) == loaders.end()) {
1514 for (vector<string>::const_iterator it = loaders.begin();
1515 it != loaders.end(); ++it) {
1516 if (!theConverters().isReachable(format, *it))
1519 string const tofile =
1520 support::changeExtension(filename.absFilename(),
1521 formats.extension(*it));
1522 if (!theConverters().convert(0, filename, FileName(tofile),
1523 filename, format, *it, errorList))
1525 loader_format = *it;
1528 if (loader_format.empty()) {
1529 frontend::Alert::error(_("Couldn't import file"),
1530 bformat(_("No information for importing the format %1$s."),
1531 formats.prettyName(format)));
1535 loader_format = format;
1537 if (loader_format == "lyx") {
1538 Buffer * buf = lv->loadDocument(lyxfile);
1541 buf->updateLabels();
1543 buf->errors("Parse");
1545 Buffer * const b = newFile(lyxfile.absFilename(), string(), true);
1549 bool as_paragraphs = loader_format == "textparagraph";
1550 string filename2 = (loader_format == format) ? filename.absFilename()
1551 : support::changeExtension(filename.absFilename(),
1552 formats.extension(loader_format));
1553 lv->view()->insertPlaintextFile(FileName(filename2), as_paragraphs);
1554 theLyXFunc().setLyXView(lv);
1555 lyx::dispatch(FuncRequest(LFUN_MARK_OFF));
1562 void GuiView::importDocument(string const & argument)
1565 string filename = split(argument, format, ' ');
1567 LYXERR(Debug::INFO, format << " file: " << filename);
1569 // need user interaction
1570 if (filename.empty()) {
1571 string initpath = lyxrc.document_path;
1573 Buffer const * buf = buffer();
1575 string const trypath = buf->filePath();
1576 // If directory is writeable, use this as default.
1577 if (FileName(trypath).isDirWritable())
1581 docstring const text = bformat(_("Select %1$s file to import"),
1582 formats.prettyName(format));
1584 FileDialog dlg(toqstr(text), LFUN_BUFFER_IMPORT);
1585 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1586 dlg.setButton2(qt_("Examples|#E#e"),
1587 toqstr(addPath(package().system_support().absFilename(), "examples")));
1589 docstring filter = formats.prettyName(format);
1592 filter += from_utf8(formats.extension(format));
1595 FileDialog::Result result =
1596 dlg.open(toqstr(initpath), fileFilters(toqstr(filter)));
1598 if (result.first == FileDialog::Later)
1601 filename = fromqstr(result.second);
1603 // check selected filename
1604 if (filename.empty())
1605 message(_("Canceled."));
1608 if (filename.empty())
1611 // get absolute path of file
1612 FileName const fullname(support::makeAbsPath(filename));
1614 FileName const lyxfile(support::changeExtension(fullname.absFilename(), ".lyx"));
1616 // Check if the document already is open
1617 Buffer * buf = theBufferList().getBuffer(lyxfile);
1620 if (!closeBuffer()) {
1621 message(_("Canceled."));
1626 docstring const displaypath = makeDisplayPath(lyxfile.absFilename(), 30);
1628 // if the file exists already, and we didn't do
1629 // -i lyx thefile.lyx, warn
1630 if (lyxfile.exists() && fullname != lyxfile) {
1632 docstring text = bformat(_("The document %1$s already exists.\n\n"
1633 "Do you want to overwrite that document?"), displaypath);
1634 int const ret = Alert::prompt(_("Overwrite document?"),
1635 text, 0, 1, _("&Overwrite"), _("&Cancel"));
1638 message(_("Canceled."));
1643 message(bformat(_("Importing %1$s..."), displaypath));
1644 ErrorList errorList;
1645 if (import(this, fullname, format, errorList))
1646 message(_("imported."));
1648 message(_("file not imported!"));
1650 // FIXME (Abdel 12/08/06): Is there a need to display the error list here?
1654 void GuiView::newDocument(string const & filename, bool from_template)
1656 FileName initpath(lyxrc.document_path);
1657 Buffer * buf = buffer();
1659 FileName const trypath(buf->filePath());
1660 // If directory is writeable, use this as default.
1661 if (trypath.isDirWritable())
1665 string templatefile;
1666 if (from_template) {
1667 templatefile = selectTemplateFile().absFilename();
1668 if (templatefile.empty())
1673 if (filename.empty())
1674 b = newUnnamedFile(templatefile, initpath);
1676 b = newFile(filename, templatefile, true);
1681 // If no new document could be created, it is unsure
1682 // whether there is a valid BufferView.
1684 // Ensure the cursor is correctly positioned on screen.
1685 view()->showCursor();
1689 void GuiView::insertLyXFile(docstring const & fname)
1691 BufferView * bv = view();
1696 FileName filename(to_utf8(fname));
1698 if (!filename.empty()) {
1699 bv->insertLyXFile(filename);
1703 // Launch a file browser
1705 string initpath = lyxrc.document_path;
1706 string const trypath = bv->buffer().filePath();
1707 // If directory is writeable, use this as default.
1708 if (FileName(trypath).isDirWritable())
1712 FileDialog dlg(qt_("Select LyX document to insert"), LFUN_FILE_INSERT);
1713 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1714 dlg.setButton2(qt_("Examples|#E#e"),
1715 toqstr(addPath(package().system_support().absFilename(),
1718 FileDialog::Result result = dlg.open(toqstr(initpath),
1719 QStringList(qt_("LyX Documents (*.lyx)")));
1721 if (result.first == FileDialog::Later)
1725 filename.set(fromqstr(result.second));
1727 // check selected filename
1728 if (filename.empty()) {
1729 // emit message signal.
1730 message(_("Canceled."));
1734 bv->insertLyXFile(filename);
1738 void GuiView::insertPlaintextFile(docstring const & fname,
1741 BufferView * bv = view();
1745 if (!fname.empty() && !FileName::isAbsolute(to_utf8(fname))) {
1746 message(_("Absolute filename expected."));
1751 FileName filename(to_utf8(fname));
1753 if (!filename.empty()) {
1754 bv->insertPlaintextFile(filename, asParagraph);
1758 FileDialog dlg(qt_("Select file to insert"), (asParagraph ?
1759 LFUN_FILE_INSERT_PLAINTEXT_PARA : LFUN_FILE_INSERT_PLAINTEXT));
1761 FileDialog::Result result = dlg.open(toqstr(bv->buffer().filePath()),
1762 QStringList(qt_("All Files (*)")));
1764 if (result.first == FileDialog::Later)
1768 filename.set(fromqstr(result.second));
1770 // check selected filename
1771 if (filename.empty()) {
1772 // emit message signal.
1773 message(_("Canceled."));
1777 bv->insertPlaintextFile(filename, asParagraph);
1781 bool GuiView::renameBuffer(Buffer & b, docstring const & newname)
1783 FileName fname = b.fileName();
1784 FileName const oldname = fname;
1786 if (!newname.empty()) {
1788 fname = support::makeAbsPath(to_utf8(newname), oldname.onlyPath().absFilename());
1790 // Switch to this Buffer.
1793 // No argument? Ask user through dialog.
1795 FileDialog dlg(qt_("Choose a filename to save document as"),
1796 LFUN_BUFFER_WRITE_AS);
1797 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1798 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
1800 if (!isLyXFilename(fname.absFilename()))
1801 fname.changeExtension(".lyx");
1803 FileDialog::Result result =
1804 dlg.save(toqstr(fname.onlyPath().absFilename()),
1805 QStringList(qt_("LyX Documents (*.lyx)")),
1806 toqstr(fname.onlyFileName()));
1808 if (result.first == FileDialog::Later)
1811 fname.set(fromqstr(result.second));
1816 if (!isLyXFilename(fname.absFilename()))
1817 fname.changeExtension(".lyx");
1820 if (FileName(fname).exists()) {
1821 docstring const file = makeDisplayPath(fname.absFilename(), 30);
1822 docstring text = bformat(_("The document %1$s already "
1823 "exists.\n\nDo you want to "
1824 "overwrite that document?"),
1826 int const ret = Alert::prompt(_("Overwrite document?"),
1827 text, 0, 2, _("&Overwrite"), _("&Rename"), _("&Cancel"));
1830 case 1: return renameBuffer(b, docstring());
1831 case 2: return false;
1835 FileName oldauto = b.getAutosaveFilename();
1837 // Ok, change the name of the buffer
1838 b.setFileName(fname.absFilename());
1840 bool unnamed = b.isUnnamed();
1841 b.setUnnamed(false);
1842 b.saveCheckSum(fname);
1844 // bring the autosave file with us, just in case.
1845 b.moveAutosaveFile(oldauto);
1847 if (!saveBuffer(b)) {
1848 oldauto = b.getAutosaveFilename();
1849 b.setFileName(oldname.absFilename());
1850 b.setUnnamed(unnamed);
1851 b.saveCheckSum(oldname);
1852 b.moveAutosaveFile(oldauto);
1860 bool GuiView::saveBuffer(Buffer & b)
1862 if (workArea(b) && workArea(b)->inDialogMode())
1866 return renameBuffer(b, docstring());
1869 theSession().lastFiles().add(b.fileName());
1873 // Switch to this Buffer.
1876 // FIXME: we don't tell the user *WHY* the save failed !!
1877 docstring const file = makeDisplayPath(b.absFileName(), 30);
1878 docstring text = bformat(_("The document %1$s could not be saved.\n\n"
1879 "Do you want to rename the document and "
1880 "try again?"), file);
1881 int const ret = Alert::prompt(_("Rename and save?"),
1882 text, 0, 2, _("&Rename"), _("&Retry"), _("&Cancel"));
1885 if (!renameBuffer(b, docstring()))
1894 return saveBuffer(b);
1898 bool GuiView::closeBuffer()
1900 Buffer * buf = buffer();
1901 return buf && closeBuffer(*buf);
1905 bool GuiView::closeBuffer(Buffer & buf, bool tolastopened, bool mark_active)
1907 // goto bookmark to update bookmark pit.
1908 //FIXME: we should update only the bookmarks related to this buffer!
1909 LYXERR(Debug::DEBUG, "GuiView::closeBuffer()");
1910 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
1911 theLyXFunc().gotoBookmark(i+1, false, false);
1913 if (buf.isClean() || buf.paragraphs().empty()) {
1914 // save in sessions if requested
1915 // do not save childs if their master
1916 // is opened as well
1918 theSession().lastOpened().add(buf.fileName(), mark_active);
1920 // Don't close child documents.
1921 removeWorkArea(currentMainWorkArea());
1923 theBufferList().release(&buf);
1926 // Switch to this Buffer.
1931 if (buf.isUnnamed())
1932 file = from_utf8(buf.fileName().onlyFileName());
1934 file = buf.fileName().displayName(30);
1936 // Bring this window to top before asking questions.
1940 docstring const text = bformat(_("The document %1$s has unsaved changes."
1941 "\n\nDo you want to save the document or discard the changes?"), file);
1942 int const ret = Alert::prompt(_("Save changed document?"),
1943 text, 0, 2, _("&Save"), _("&Discard"), _("&Cancel"));
1947 if (!saveBuffer(buf))
1951 // if we crash after this we could
1952 // have no autosave file but I guess
1953 // this is really improbable (Jug)
1954 buf.removeAutosaveFile();
1960 // save file names to .lyx/session
1962 theSession().lastOpened().add(buf.fileName(), mark_active);
1965 // Don't close child documents.
1966 removeWorkArea(currentMainWorkArea());
1968 theBufferList().release(&buf);
1974 void GuiView::gotoNextOrPreviousBuffer(NextOrPrevious np)
1976 Buffer * const curbuf = buffer();
1977 Buffer * nextbuf = curbuf;
1979 if (np == NEXTBUFFER)
1980 nextbuf = theBufferList().next(nextbuf);
1982 nextbuf = theBufferList().previous(nextbuf);
1983 if (nextbuf == curbuf)
1989 if (workArea(*nextbuf))
1996 bool GuiView::dispatch(FuncRequest const & cmd)
1998 BufferView * bv = view();
1999 // By default we won't need any update.
2001 bv->cursor().updateFlags(Update::None);
2002 bool dispatched = true;
2004 if (cmd.origin == FuncRequest::TOC) {
2005 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
2006 toc->doDispatch(bv->cursor(), cmd);
2010 switch(cmd.action) {
2011 case LFUN_BUFFER_IMPORT:
2012 importDocument(to_utf8(cmd.argument()));
2015 case LFUN_BUFFER_SWITCH:
2016 if (FileName::isAbsolute(to_utf8(cmd.argument()))) {
2018 theBufferList().getBuffer(FileName(to_utf8(cmd.argument())));
2022 bv->cursor().message(_("Document not loaded"));
2026 case LFUN_BUFFER_NEXT:
2027 gotoNextOrPreviousBuffer(NEXTBUFFER);
2030 case LFUN_BUFFER_PREVIOUS:
2031 gotoNextOrPreviousBuffer(PREVBUFFER);
2034 case LFUN_COMMAND_EXECUTE: {
2035 bool const show_it = cmd.argument() != "off";
2036 // FIXME: this is a hack, "minibuffer" should not be
2038 if (GuiToolbar * t = toolbar("minibuffer")) {
2039 t->setVisible(show_it);
2040 if (show_it && t->commandBuffer())
2041 t->commandBuffer()->setFocus();
2045 case LFUN_DROP_LAYOUTS_CHOICE:
2047 d.layout_->showPopup();
2050 case LFUN_MENU_OPEN:
2051 if (QMenu * menu = guiApp->menus().menu(toqstr(cmd.argument()), *this))
2052 menu->exec(QCursor::pos());
2055 case LFUN_FILE_INSERT:
2056 insertLyXFile(cmd.argument());
2058 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
2059 insertPlaintextFile(cmd.argument(), true);
2062 case LFUN_FILE_INSERT_PLAINTEXT:
2063 insertPlaintextFile(cmd.argument(), false);
2066 case LFUN_BUFFER_WRITE:
2068 saveBuffer(bv->buffer());
2071 case LFUN_BUFFER_WRITE_AS:
2073 renameBuffer(bv->buffer(), cmd.argument());
2076 case LFUN_BUFFER_WRITE_ALL: {
2077 Buffer * first = theBufferList().first();
2080 message(_("Saving all documents..."));
2081 // We cannot use a for loop as the buffer list cycles.
2084 if (!b->isClean()) {
2086 LYXERR(Debug::ACTION, "Saved " << b->absFileName());
2088 b = theBufferList().next(b);
2089 } while (b != first);
2090 message(_("All documents saved."));
2094 case LFUN_TOOLBAR_TOGGLE: {
2095 string const name = cmd.getArg(0);
2096 if (GuiToolbar * t = toolbar(name))
2101 case LFUN_DIALOG_UPDATE: {
2102 string const name = to_utf8(cmd.argument());
2103 // Can only update a dialog connected to an existing inset
2104 Inset * inset = getOpenInset(name);
2106 FuncRequest fr(LFUN_INSET_DIALOG_UPDATE, cmd.argument());
2107 inset->dispatch(view()->cursor(), fr);
2108 } else if (name == "paragraph") {
2109 lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
2110 } else if (name == "prefs" || name == "document") {
2111 updateDialog(name, string());
2116 case LFUN_DIALOG_TOGGLE: {
2117 if (isDialogVisible(cmd.getArg(0)))
2118 dispatch(FuncRequest(LFUN_DIALOG_HIDE, cmd.argument()));
2120 dispatch(FuncRequest(LFUN_DIALOG_SHOW, cmd.argument()));
2124 case LFUN_DIALOG_DISCONNECT_INSET:
2125 disconnectDialog(to_utf8(cmd.argument()));
2128 case LFUN_DIALOG_HIDE: {
2129 guiApp->hideDialogs(to_utf8(cmd.argument()), 0);
2133 case LFUN_DIALOG_SHOW: {
2134 string const name = cmd.getArg(0);
2135 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
2137 if (name == "character") {
2138 data = freefont2string();
2140 showDialog("character", data);
2141 } else if (name == "latexlog") {
2142 Buffer::LogType type;
2143 string const logfile = buffer()->logName(&type);
2145 case Buffer::latexlog:
2148 case Buffer::buildlog:
2152 data += Lexer::quoteString(logfile);
2153 showDialog("log", data);
2154 } else if (name == "vclog") {
2155 string const data = "vc " +
2156 Lexer::quoteString(buffer()->lyxvc().getLogFile());
2157 showDialog("log", data);
2158 } else if (name == "symbols") {
2159 data = bv->cursor().getEncoding()->name();
2161 showDialog("symbols", data);
2163 } else if (name == "prefs" && isFullScreen()) {
2164 FuncRequest fr(LFUN_INSET_INSERT, "fullscreen");
2166 showDialog("prefs", data);
2168 showDialog(name, data);
2172 case LFUN_INSET_APPLY: {
2173 string const name = cmd.getArg(0);
2174 Inset * inset = getOpenInset(name);
2176 // put cursor in front of inset.
2177 if (!view()->setCursorFromInset(inset)) {
2178 LASSERT(false, break);
2181 // useful if we are called from a dialog.
2182 view()->cursor().beginUndoGroup();
2183 view()->cursor().recordUndo();
2184 FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument());
2185 inset->dispatch(view()->cursor(), fr);
2186 view()->cursor().endUndoGroup();
2188 FuncRequest fr(LFUN_INSET_INSERT, cmd.argument());
2194 case LFUN_UI_TOGGLE:
2196 // Make sure the keyboard focus stays in the work area.
2200 case LFUN_SPLIT_VIEW:
2201 if (Buffer * buf = buffer()) {
2202 string const orientation = cmd.getArg(0);
2203 d.splitter_->setOrientation(orientation == "vertical"
2204 ? Qt::Vertical : Qt::Horizontal);
2205 TabWorkArea * twa = addTabWorkArea();
2206 GuiWorkArea * wa = twa->addWorkArea(*buf, *this);
2207 setCurrentWorkArea(wa);
2211 case LFUN_CLOSE_TAB_GROUP:
2212 if (TabWorkArea * twa = d.currentTabWorkArea()) {
2214 twa = d.currentTabWorkArea();
2215 // Switch to the next GuiWorkArea in the found TabWorkArea.
2217 // Make sure the work area is up to date.
2218 setCurrentWorkArea(twa->currentWorkArea());
2220 setCurrentWorkArea(0);
2225 case LFUN_COMPLETION_INLINE:
2226 if (d.current_work_area_)
2227 d.current_work_area_->completer().showInline();
2230 case LFUN_COMPLETION_POPUP:
2231 if (d.current_work_area_)
2232 d.current_work_area_->completer().showPopup();
2236 case LFUN_COMPLETION_COMPLETE:
2237 if (d.current_work_area_)
2238 d.current_work_area_->completer().tab();
2241 case LFUN_COMPLETION_CANCEL:
2242 if (d.current_work_area_) {
2243 if (d.current_work_area_->completer().popupVisible())
2244 d.current_work_area_->completer().hidePopup();
2246 d.current_work_area_->completer().hideInline();
2250 case LFUN_COMPLETION_ACCEPT:
2251 if (d.current_work_area_)
2252 d.current_work_area_->completer().activate();
2255 case LFUN_BUFFER_ZOOM_IN:
2256 case LFUN_BUFFER_ZOOM_OUT:
2257 if (cmd.argument().empty()) {
2258 if (cmd.action == LFUN_BUFFER_ZOOM_IN)
2263 lyxrc.zoom += convert<int>(cmd.argument());
2265 if (lyxrc.zoom < 10)
2268 // The global QPixmapCache is used in GuiPainter to cache text
2269 // painting so we must reset it.
2270 QPixmapCache::clear();
2271 guiApp->fontLoader().update();
2272 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
2280 // Part of automatic menu appearance feature.
2281 if (isFullScreen()) {
2282 if (menuBar()->isVisible() && lyxrc.full_screen_menubar)
2284 if (statusBar()->isVisible())
2285 statusBar()->hide();
2292 void GuiView::lfunUiToggle(FuncRequest const & cmd)
2294 string const arg = cmd.getArg(0);
2295 if (arg == "scrollbar") {
2296 // hide() is of no help
2297 if (d.current_work_area_->verticalScrollBarPolicy() ==
2298 Qt::ScrollBarAlwaysOff)
2300 d.current_work_area_->setVerticalScrollBarPolicy(
2301 Qt::ScrollBarAsNeeded);
2303 d.current_work_area_->setVerticalScrollBarPolicy(
2304 Qt::ScrollBarAlwaysOff);
2307 if (arg == "statusbar") {
2308 statusBar()->setVisible(!statusBar()->isVisible());
2311 if (arg == "menubar") {
2312 menuBar()->setVisible(!menuBar()->isVisible());
2315 #if QT_VERSION >= 0x040300
2316 if (arg == "frame") {
2318 getContentsMargins(&l, &t, &r, &b);
2319 //are the frames in default state?
2320 d.current_work_area_->setFrameStyle(QFrame::NoFrame);
2322 setContentsMargins(-2, -2, -2, -2);
2324 setContentsMargins(0, 0, 0, 0);
2329 if (arg == "fullscreen") {
2334 message(bformat("LFUN_UI_TOGGLE " + _("%1$s unknown command!"), from_utf8(arg)));
2338 void GuiView::toggleFullScreen()
2340 if (isFullScreen()) {
2341 for (int i = 0; i != d.splitter_->count(); ++i)
2342 d.tabWorkArea(i)->setFullScreen(false);
2343 #if QT_VERSION >= 0x040300
2344 setContentsMargins(0, 0, 0, 0);
2346 setWindowState(windowState() ^ Qt::WindowFullScreen);
2349 statusBar()->show();
2352 hideDialogs("prefs", 0);
2353 for (int i = 0; i != d.splitter_->count(); ++i)
2354 d.tabWorkArea(i)->setFullScreen(true);
2355 #if QT_VERSION >= 0x040300
2356 setContentsMargins(-2, -2, -2, -2);
2359 setWindowState(windowState() ^ Qt::WindowFullScreen);
2360 statusBar()->hide();
2361 if (lyxrc.full_screen_menubar)
2363 if (lyxrc.full_screen_toolbars) {
2364 ToolbarMap::iterator end = d.toolbars_.end();
2365 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
2370 // give dialogs like the TOC a chance to adapt
2375 Buffer const * GuiView::updateInset(Inset const * inset)
2377 if (!d.current_work_area_)
2381 d.current_work_area_->scheduleRedraw();
2383 return &d.current_work_area_->bufferView().buffer();
2387 void GuiView::restartCursor()
2389 /* When we move around, or type, it's nice to be able to see
2390 * the cursor immediately after the keypress.
2392 if (d.current_work_area_)
2393 d.current_work_area_->startBlinkingCursor();
2395 // Take this occasion to update the other GUI elements.
2401 void GuiView::updateCompletion(Cursor & cur, bool start, bool keep)
2403 if (d.current_work_area_)
2404 d.current_work_area_->completer().updateVisibility(cur, start, keep);
2409 // This list should be kept in sync with the list of insets in
2410 // src/insets/Inset.cpp. I.e., if a dialog goes with an inset, the
2411 // dialog should have the same name as the inset.
2412 // Changes should be also recorded in LFUN_DIALOG_SHOW doxygen
2413 // docs in LyXAction.cpp.
2415 char const * const dialognames[] = {
2416 "aboutlyx", "bibitem", "bibtex", "box", "branch", "changes", "character",
2417 "citation", "document", "errorlist", "ert", "external", "file", "findreplace",
2418 "findreplaceadv", "float", "graphics", "href", "include", "index",
2419 "index_print", "info", "listings", "label", "log", "mathdelimiter",
2420 "mathmatrix", "mathspace", "nomenclature", "nomencl_print", "note",
2421 "paragraph", "phantom", "prefs", "print", "ref", "sendto", "space",
2422 "spellchecker", "symbols", "tabular", "tabularcreate", "thesaurus", "texinfo",
2423 "toc", "view-source", "vspace", "wrap" };
2425 char const * const * const end_dialognames =
2426 dialognames + (sizeof(dialognames) / sizeof(char *));
2430 cmpCStr(char const * name) : name_(name) {}
2431 bool operator()(char const * other) {
2432 return strcmp(other, name_) == 0;
2439 bool isValidName(string const & name)
2441 return find_if(dialognames, end_dialognames,
2442 cmpCStr(name.c_str())) != end_dialognames;
2448 void GuiView::resetDialogs()
2450 // Make sure that no LFUN uses any LyXView.
2451 theLyXFunc().setLyXView(0);
2454 constructToolbars();
2455 guiApp->menus().fillMenuBar(menuBar(), this, false);
2457 d.layout_->updateContents(true);
2458 // Now update controls with current buffer.
2459 theLyXFunc().setLyXView(this);
2465 Dialog * GuiView::findOrBuild(string const & name, bool hide_it)
2467 if (!isValidName(name))
2470 map<string, DialogPtr>::iterator it = d.dialogs_.find(name);
2472 if (it != d.dialogs_.end()) {
2474 it->second->hideView();
2475 return it->second.get();
2478 Dialog * dialog = build(name);
2479 d.dialogs_[name].reset(dialog);
2480 if (lyxrc.allow_geometry_session)
2481 dialog->restoreSession();
2488 void GuiView::showDialog(string const & name, string const & data,
2496 Dialog * dialog = findOrBuild(name, false);
2498 dialog->showData(data);
2500 d.open_insets_[name] = inset;
2503 catch (ExceptionMessage const & ex) {
2511 bool GuiView::isDialogVisible(string const & name) const
2513 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
2514 if (it == d.dialogs_.end())
2516 return it->second.get()->isVisibleView() && !it->second.get()->isClosing();
2520 void GuiView::hideDialog(string const & name, Inset * inset)
2522 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
2523 if (it == d.dialogs_.end())
2526 if (inset && inset != getOpenInset(name))
2529 Dialog * const dialog = it->second.get();
2530 if (dialog->isVisibleView())
2532 d.open_insets_[name] = 0;
2536 void GuiView::disconnectDialog(string const & name)
2538 if (!isValidName(name))
2541 if (d.open_insets_.find(name) != d.open_insets_.end())
2542 d.open_insets_[name] = 0;
2546 Inset * GuiView::getOpenInset(string const & name) const
2548 if (!isValidName(name))
2551 map<string, Inset *>::const_iterator it = d.open_insets_.find(name);
2552 return it == d.open_insets_.end() ? 0 : it->second;
2556 void GuiView::hideAll() const
2558 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
2559 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
2561 for(; it != end; ++it)
2562 it->second->hideView();
2566 void GuiView::updateDialogs()
2568 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
2569 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
2571 for(; it != end; ++it) {
2572 Dialog * dialog = it->second.get();
2573 if (dialog && dialog->isVisibleView())
2574 dialog->checkStatus();
2581 // will be replaced by a proper factory...
2582 Dialog * createGuiAbout(GuiView & lv);
2583 Dialog * createGuiBibitem(GuiView & lv);
2584 Dialog * createGuiBibtex(GuiView & lv);
2585 Dialog * createGuiBox(GuiView & lv);
2586 Dialog * createGuiBranch(GuiView & lv);
2587 Dialog * createGuiChanges(GuiView & lv);
2588 Dialog * createGuiCharacter(GuiView & lv);
2589 Dialog * createGuiCitation(GuiView & lv);
2590 Dialog * createGuiDelimiter(GuiView & lv);
2591 Dialog * createGuiDocument(GuiView & lv);
2592 Dialog * createGuiErrorList(GuiView & lv);
2593 Dialog * createGuiERT(GuiView & lv);
2594 Dialog * createGuiExternal(GuiView & lv);
2595 Dialog * createGuiFloat(GuiView & lv);
2596 Dialog * createGuiGraphics(GuiView & lv);
2597 Dialog * createGuiInclude(GuiView & lv);
2598 Dialog * createGuiIndex(GuiView & lv);
2599 Dialog * createGuiInfo(GuiView & lv);
2600 Dialog * createGuiLabel(GuiView & lv);
2601 Dialog * createGuiListings(GuiView & lv);
2602 Dialog * createGuiLog(GuiView & lv);
2603 Dialog * createGuiMathHSpace(GuiView & lv);
2604 Dialog * createGuiMathMatrix(GuiView & lv);
2605 Dialog * createGuiNomenclature(GuiView & lv);
2606 Dialog * createGuiNote(GuiView & lv);
2607 Dialog * createGuiParagraph(GuiView & lv);
2608 Dialog * createGuiPhantom(GuiView & lv);
2609 Dialog * createGuiPreferences(GuiView & lv);
2610 Dialog * createGuiPrint(GuiView & lv);
2611 Dialog * createGuiPrintindex(GuiView & lv);
2612 Dialog * createGuiPrintNomencl(GuiView & lv);
2613 Dialog * createGuiRef(GuiView & lv);
2614 Dialog * createGuiSearch(GuiView & lv);
2615 Dialog * createGuiSearchAdv(GuiView & lv);
2616 Dialog * createGuiSendTo(GuiView & lv);
2617 Dialog * createGuiShowFile(GuiView & lv);
2618 Dialog * createGuiSpellchecker(GuiView & lv);
2619 Dialog * createGuiSymbols(GuiView & lv);
2620 Dialog * createGuiTabularCreate(GuiView & lv);
2621 Dialog * createGuiTabular(GuiView & lv);
2622 Dialog * createGuiTexInfo(GuiView & lv);
2623 Dialog * createGuiTextHSpace(GuiView & lv);
2624 Dialog * createGuiToc(GuiView & lv);
2625 Dialog * createGuiThesaurus(GuiView & lv);
2626 Dialog * createGuiHyperlink(GuiView & lv);
2627 Dialog * createGuiVSpace(GuiView & lv);
2628 Dialog * createGuiViewSource(GuiView & lv);
2629 Dialog * createGuiWrap(GuiView & lv);
2632 Dialog * GuiView::build(string const & name)
2634 LASSERT(isValidName(name), return 0);
2636 if (name == "aboutlyx")
2637 return createGuiAbout(*this);
2638 if (name == "bibitem")
2639 return createGuiBibitem(*this);
2640 if (name == "bibtex")
2641 return createGuiBibtex(*this);
2643 return createGuiBox(*this);
2644 if (name == "branch")
2645 return createGuiBranch(*this);
2646 if (name == "changes")
2647 return createGuiChanges(*this);
2648 if (name == "character")
2649 return createGuiCharacter(*this);
2650 if (name == "citation")
2651 return createGuiCitation(*this);
2652 if (name == "document")
2653 return createGuiDocument(*this);
2654 if (name == "errorlist")
2655 return createGuiErrorList(*this);
2657 return createGuiERT(*this);
2658 if (name == "external")
2659 return createGuiExternal(*this);
2661 return createGuiShowFile(*this);
2662 if (name == "findreplace")
2663 return createGuiSearch(*this);
2664 if (name == "findreplaceadv")
2665 return createGuiSearchAdv(*this);
2666 if (name == "float")
2667 return createGuiFloat(*this);
2668 if (name == "graphics")
2669 return createGuiGraphics(*this);
2671 return createGuiHyperlink(*this);
2672 if (name == "include")
2673 return createGuiInclude(*this);
2674 if (name == "index")
2675 return createGuiIndex(*this);
2676 if (name == "index_print")
2677 return createGuiPrintindex(*this);
2679 return createGuiInfo(*this);
2680 if (name == "label")
2681 return createGuiLabel(*this);
2682 if (name == "listings")
2683 return createGuiListings(*this);
2685 return createGuiLog(*this);
2686 if (name == "mathdelimiter")
2687 return createGuiDelimiter(*this);
2688 if (name == "mathspace")
2689 return createGuiMathHSpace(*this);
2690 if (name == "mathmatrix")
2691 return createGuiMathMatrix(*this);
2692 if (name == "nomenclature")
2693 return createGuiNomenclature(*this);
2694 if (name == "nomencl_print")
2695 return createGuiPrintNomencl(*this);
2697 return createGuiNote(*this);
2698 if (name == "paragraph")
2699 return createGuiParagraph(*this);
2700 if (name == "phantom")
2701 return createGuiPhantom(*this);
2702 if (name == "prefs")
2703 return createGuiPreferences(*this);
2704 if (name == "print")
2705 return createGuiPrint(*this);
2707 return createGuiRef(*this);
2708 if (name == "sendto")
2709 return createGuiSendTo(*this);
2710 if (name == "space")
2711 return createGuiTextHSpace(*this);
2712 if (name == "spellchecker")
2713 return createGuiSpellchecker(*this);
2714 if (name == "symbols")
2715 return createGuiSymbols(*this);
2716 if (name == "tabular")
2717 return createGuiTabular(*this);
2718 if (name == "tabularcreate")
2719 return createGuiTabularCreate(*this);
2720 if (name == "texinfo")
2721 return createGuiTexInfo(*this);
2722 if (name == "thesaurus")
2723 return createGuiThesaurus(*this);
2725 return createGuiToc(*this);
2726 if (name == "view-source")
2727 return createGuiViewSource(*this);
2728 if (name == "vspace")
2729 return createGuiVSpace(*this);
2731 return createGuiWrap(*this);
2737 } // namespace frontend
2740 #include "moc_GuiView.cpp"