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 if (!closeBufferAll(true)) {
541 close_event->ignore();
545 // Make sure that nothing will use this close to be closed View.
546 guiApp->unregisterView(this);
548 if (isFullScreen()) {
549 // Switch off fullscreen before closing.
554 // Make sure the timer time out will not trigger a statusbar update.
555 d.statusbar_timer_.stop();
557 // Saving fullscreen requires additional tweaks in the toolbar code.
558 // It wouldn't also work under linux natively.
559 if (lyxrc.allow_geometry_session) {
560 // Save this window geometry and layout.
562 // Then the toolbar private states.
563 ToolbarMap::iterator end = d.toolbars_.end();
564 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
565 it->second->saveSession();
566 // Now take care of all other dialogs:
567 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
568 for (; it!= d.dialogs_.end(); ++it)
569 it->second->saveSession();
572 close_event->accept();
576 bool GuiView::closeBufferAll(bool tolastopened)
578 GuiWorkArea * active_wa = currentMainWorkArea();
579 setCurrentWorkArea(active_wa);
581 // We might be in a situation that there is still a tabWorkArea, but
582 // there are no tabs anymore. This can happen when we get here after a
583 // TabWorkArea::lastWorkAreaRemoved() signal. Therefore we count how
584 // many TabWorkArea's have no documents anymore.
587 // We have to call count() each time, because it can happen that
588 // more than one splitter will disappear in one iteration (bug 5998).
589 for (; d.splitter_->count() > empty_twa; ) {
590 TabWorkArea * twa = d.tabWorkArea(empty_twa);
592 int twa_count = twa->count();
593 if (twa->count() == 0)
596 for (; twa_count; --twa_count) {
597 twa->setCurrentIndex(twa_count-1);
599 GuiWorkArea * wa = twa->currentWorkArea();
600 bool const is_active_wa = active_wa == wa;
601 Buffer * b = &wa->bufferView().buffer();
603 // This is a child document, just close the tab
604 // after saving but keep the file loaded.
605 if (!closeBuffer(*b, tolastopened, is_active_wa))
610 vector<Buffer *> clist = b->getChildren();
611 for (vector<Buffer *>::const_iterator it = clist.begin();
612 it != clist.end(); ++it) {
613 if ((*it)->isClean())
616 // If a child is dirty, do not close
617 // without user intervention
618 if (!closeBuffer(*c, false))
622 QList<int> const ids = guiApp->viewIds();
623 for (int i = 0; i != ids.size(); ++i) {
626 if (guiApp->view(ids[i]).workArea(*b)) {
627 // FIXME 1: should we put an alert box here
628 // that the buffer is viewed elsewhere?
629 // FIXME 2: should we try to save this buffer in any case?
632 // This buffer is also opened in another view, so
633 // close the associated work area...
635 // ... but don't close the buffer.
640 // closeBuffer() needs buffer workArea still alive and
641 // set as currrent one, and destroys it
642 if (b && !closeBuffer(*b, tolastopened, is_active_wa))
650 void GuiView::dragEnterEvent(QDragEnterEvent * event)
652 if (event->mimeData()->hasUrls())
654 /// \todo Ask lyx-devel is this is enough:
655 /// if (event->mimeData()->hasFormat("text/plain"))
656 /// event->acceptProposedAction();
660 void GuiView::dropEvent(QDropEvent * event)
662 QList<QUrl> files = event->mimeData()->urls();
666 LYXERR(Debug::GUI, "GuiView::dropEvent: got URLs!");
667 for (int i = 0; i != files.size(); ++i) {
668 string const file = os::internal_path(fromqstr(
669 files.at(i).toLocalFile()));
671 // Asynchronously post the event. DropEvent usually come
672 // from the BufferView. But reloading a file might close
673 // the BufferView from within its own event handler.
674 guiApp->dispatchDelayed(FuncRequest(LFUN_FILE_OPEN, file));
681 void GuiView::message(docstring const & str)
683 if (ForkedProcess::iAmAChild())
686 statusBar()->showMessage(toqstr(str));
687 d.statusbar_timer_.stop();
688 d.statusbar_timer_.start(3000);
692 void GuiView::smallSizedIcons()
694 setIconSize(QSize(d.smallIconSize, d.smallIconSize));
698 void GuiView::normalSizedIcons()
700 setIconSize(QSize(d.normalIconSize, d.normalIconSize));
704 void GuiView::bigSizedIcons()
706 setIconSize(QSize(d.bigIconSize, d.bigIconSize));
710 void GuiView::clearMessage()
714 theLyXFunc().setLyXView(this);
715 statusBar()->showMessage(toqstr(theLyXFunc().viewStatusMessage()));
716 d.statusbar_timer_.stop();
720 void GuiView::updateWindowTitle(GuiWorkArea * wa)
722 if (wa != d.current_work_area_)
724 setWindowTitle(qt_("LyX: ") + wa->windowTitle());
725 setWindowIconText(wa->windowIconText());
729 void GuiView::on_currentWorkAreaChanged(GuiWorkArea * wa)
732 disconnectBufferView();
733 connectBufferView(wa->bufferView());
734 connectBuffer(wa->bufferView().buffer());
735 d.current_work_area_ = wa;
736 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
737 this, SLOT(updateWindowTitle(GuiWorkArea *)));
738 updateWindowTitle(wa);
742 // The document settings needs to be reinitialised.
743 updateDialog("document", "");
745 // Buffer-dependent dialogs must be updated. This is done here because
746 // some dialogs require buffer()->text.
751 void GuiView::on_lastWorkAreaRemoved()
754 // We already are in a close event. Nothing more to do.
757 if (d.splitter_->count() > 1)
758 // We have a splitter so don't close anything.
761 // Reset and updates the dialogs.
762 d.toc_models_.reset(0);
763 updateDialog("document", "");
766 resetWindowTitleAndIconText();
768 if (lyxrc.open_buffers_in_tabs)
769 // Nothing more to do, the window should stay open.
772 if (guiApp->viewIds().size() > 1) {
778 // On Mac we also close the last window because the application stay
779 // resident in memory. On other platforms we don't close the last
780 // window because this would quit the application.
786 void GuiView::updateStatusBar()
788 // let the user see the explicit message
789 if (d.statusbar_timer_.isActive())
792 theLyXFunc().setLyXView(this);
793 statusBar()->showMessage(toqstr(theLyXFunc().viewStatusMessage()));
797 bool GuiView::hasFocus() const
799 return qApp->activeWindow() == this;
803 bool GuiView::event(QEvent * e)
807 // Useful debug code:
808 //case QEvent::ActivationChange:
809 //case QEvent::WindowDeactivate:
810 //case QEvent::Paint:
811 //case QEvent::Enter:
812 //case QEvent::Leave:
813 //case QEvent::HoverEnter:
814 //case QEvent::HoverLeave:
815 //case QEvent::HoverMove:
816 //case QEvent::StatusTip:
817 //case QEvent::DragEnter:
818 //case QEvent::DragLeave:
822 case QEvent::WindowActivate: {
823 if (this == guiApp->currentView()) {
825 return QMainWindow::event(e);
827 guiApp->setCurrentView(this);
828 theLyXFunc().setLyXView(this);
829 if (d.current_work_area_) {
830 BufferView & bv = d.current_work_area_->bufferView();
831 connectBufferView(bv);
832 connectBuffer(bv.buffer());
833 // The document structure, name and dialogs might have
834 // changed in another view.
836 // The document settings needs to be reinitialised.
837 updateDialog("document", "");
840 resetWindowTitleAndIconText();
843 return QMainWindow::event(e);
846 case QEvent::ShortcutOverride: {
849 #if (!defined Q_WS_X11) || (QT_VERSION >= 0x040500)
850 if (isFullScreen() && menuBar()->isHidden()) {
851 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
852 // FIXME: we should also try to detect special LyX shortcut such as
853 // Alt-P and Alt-M. Right now there is a hack in
854 // GuiWorkArea::processKeySym() that hides again the menubar for
856 if (ke->modifiers() & Qt::AltModifier && ke->key() != Qt::Key_Alt) {
858 return QMainWindow::event(e);
863 if (d.current_work_area_)
864 // Nothing special to do.
865 return QMainWindow::event(e);
867 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
868 // Let Qt handle menu access and the Tab keys to navigate keys to navigate
870 if (ke->modifiers() & Qt::AltModifier || ke->key() == Qt::Key_Tab
871 || ke->key() == Qt::Key_Backtab)
872 return QMainWindow::event(e);
874 // Allow processing of shortcuts that are allowed even when no Buffer
876 theLyXFunc().setLyXView(this);
878 setKeySymbol(&sym, ke);
879 theLyXFunc().processKeySym(sym, q_key_state(ke->modifiers()));
885 return QMainWindow::event(e);
889 void GuiView::resetWindowTitleAndIconText()
891 setWindowTitle(qt_("LyX"));
892 setWindowIconText(qt_("LyX"));
895 bool GuiView::focusNextPrevChild(bool /*next*/)
902 void GuiView::setBusy(bool busy)
904 if (d.current_work_area_) {
905 d.current_work_area_->setUpdatesEnabled(!busy);
907 d.current_work_area_->stopBlinkingCursor();
909 d.current_work_area_->startBlinkingCursor();
913 QApplication::setOverrideCursor(Qt::WaitCursor);
915 QApplication::restoreOverrideCursor();
919 GuiWorkArea * GuiView::workArea(Buffer & buffer)
921 if (currentWorkArea()
922 && ¤tWorkArea()->bufferView().buffer() == &buffer)
923 return (GuiWorkArea *) currentWorkArea();
924 if (TabWorkArea * twa = d.currentTabWorkArea())
925 return twa->workArea(buffer);
930 GuiWorkArea * GuiView::addWorkArea(Buffer & buffer)
932 // Automatically create a TabWorkArea if there are none yet.
933 TabWorkArea * tab_widget = d.splitter_->count()
934 ? d.currentTabWorkArea() : addTabWorkArea();
935 return tab_widget->addWorkArea(buffer, *this);
939 TabWorkArea * GuiView::addTabWorkArea()
941 TabWorkArea * twa = new TabWorkArea;
942 QObject::connect(twa, SIGNAL(currentWorkAreaChanged(GuiWorkArea *)),
943 this, SLOT(on_currentWorkAreaChanged(GuiWorkArea *)));
944 QObject::connect(twa, SIGNAL(lastWorkAreaRemoved()),
945 this, SLOT(on_lastWorkAreaRemoved()));
947 d.splitter_->addWidget(twa);
948 d.stack_widget_->setCurrentWidget(d.splitter_);
953 GuiWorkArea const * GuiView::currentWorkArea() const
955 return d.current_work_area_;
959 GuiWorkArea * GuiView::currentWorkArea()
961 return d.current_work_area_;
965 GuiWorkArea const * GuiView::currentMainWorkArea() const
967 if (d.currentTabWorkArea() == NULL)
969 return d.currentTabWorkArea()->currentWorkArea();
973 GuiWorkArea * GuiView::currentMainWorkArea()
975 if (d.currentTabWorkArea() == NULL)
977 return d.currentTabWorkArea()->currentWorkArea();
981 void GuiView::setCurrentWorkArea(GuiWorkArea * wa)
983 LYXERR(Debug::DEBUG, "Setting current wa: " << wa << endl);
985 d.current_work_area_ = NULL;
989 GuiWorkArea * old_gwa = theGuiApp()->currentView()->currentWorkArea();
993 theGuiApp()->setCurrentView(this);
994 d.current_work_area_ = wa;
995 for (int i = 0; i != d.splitter_->count(); ++i) {
996 if (d.tabWorkArea(i)->setCurrentWorkArea(wa)) {
997 //if (d.current_main_work_area_)
998 // d.current_main_work_area_->setFrameStyle(QFrame::NoFrame);
999 d.current_main_work_area_ = wa;
1000 //d.current_main_work_area_->setFrameStyle(QFrame::Box | QFrame::Plain);
1001 //d.current_main_work_area_->setLineWidth(2);
1002 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() << ", Current main wa: " << currentMainWorkArea());
1006 LYXERR(Debug::DEBUG, "This is not a tabbed wa");
1007 on_currentWorkAreaChanged(wa);
1008 BufferView & bv = wa->bufferView();
1009 bv.cursor().fixIfBroken();
1011 wa->setUpdatesEnabled(true);
1012 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() << ", Current main wa: " << currentMainWorkArea());
1016 void GuiView::removeWorkArea(GuiWorkArea * wa)
1018 LASSERT(wa, return);
1019 if (wa == d.current_work_area_) {
1021 disconnectBufferView();
1022 d.current_work_area_ = 0;
1023 d.current_main_work_area_ = 0;
1026 bool found_twa = false;
1027 for (int i = 0; i != d.splitter_->count(); ++i) {
1028 TabWorkArea * twa = d.tabWorkArea(i);
1029 if (twa->removeWorkArea(wa)) {
1030 // Found in this tab group, and deleted the GuiWorkArea.
1032 if (twa->count() != 0) {
1033 if (d.current_work_area_ == 0)
1034 // This means that we are closing the current GuiWorkArea, so
1035 // switch to the next GuiWorkArea in the found TabWorkArea.
1036 setCurrentWorkArea(twa->currentWorkArea());
1038 // No more WorkAreas in this tab group, so delete it.
1045 // It is not a tabbed work area (i.e., the search work area), so it
1046 // should be deleted by other means.
1047 LASSERT(found_twa, /* */);
1049 if (d.current_work_area_ == 0) {
1050 if (d.splitter_->count() != 0) {
1051 TabWorkArea * twa = d.currentTabWorkArea();
1052 setCurrentWorkArea(twa->currentWorkArea());
1054 // No more work areas, switch to the background widget.
1055 setCurrentWorkArea(0);
1061 void GuiView::setLayoutDialog(GuiLayoutBox * layout)
1067 void GuiView::updateLayoutList()
1070 d.layout_->updateContents(false);
1074 void GuiView::updateToolbars()
1076 ToolbarMap::iterator end = d.toolbars_.end();
1077 if (d.current_work_area_) {
1079 d.current_work_area_->bufferView().cursor().inMathed();
1081 lyx::getStatus(FuncRequest(LFUN_LAYOUT_TABULAR)).enabled();
1083 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).enabled() &&
1084 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).onoff(true);
1085 bool const mathmacrotemplate =
1086 lyx::getStatus(FuncRequest(LFUN_IN_MATHMACROTEMPLATE)).enabled();
1088 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1089 it->second->update(math, table, review, mathmacrotemplate);
1091 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1092 it->second->update(false, false, false, false);
1096 Buffer * GuiView::buffer()
1098 if (d.current_work_area_)
1099 return &d.current_work_area_->bufferView().buffer();
1104 Buffer const * GuiView::buffer() const
1106 if (d.current_work_area_)
1107 return &d.current_work_area_->bufferView().buffer();
1112 void GuiView::setBuffer(Buffer * newBuffer)
1114 LYXERR(Debug::DEBUG, "Setting buffer: " << newBuffer << std::endl);
1115 LASSERT(newBuffer, return);
1118 GuiWorkArea * wa = workArea(*newBuffer);
1120 newBuffer->masterBuffer()->updateLabels();
1121 wa = addWorkArea(*newBuffer);
1123 //Disconnect the old buffer...there's no new one.
1126 connectBuffer(*newBuffer);
1127 connectBufferView(wa->bufferView());
1128 setCurrentWorkArea(wa);
1134 void GuiView::connectBuffer(Buffer & buf)
1136 buf.setGuiDelegate(this);
1140 void GuiView::disconnectBuffer()
1142 if (d.current_work_area_)
1143 d.current_work_area_->bufferView().setGuiDelegate(0);
1147 void GuiView::connectBufferView(BufferView & bv)
1149 bv.setGuiDelegate(this);
1153 void GuiView::disconnectBufferView()
1155 if (d.current_work_area_)
1156 d.current_work_area_->bufferView().setGuiDelegate(0);
1160 void GuiView::errors(string const & error_type, bool from_master)
1162 ErrorList & el = from_master ?
1163 buffer()->masterBuffer()->errorList(error_type)
1164 : buffer()->errorList(error_type);
1165 string data = error_type;
1167 data = "from_master|" + error_type;
1169 showDialog("errorlist", data);
1173 void GuiView::updateTocItem(std::string const & type, DocIterator const & dit)
1175 d.toc_models_.updateItem(toqstr(type), dit);
1179 void GuiView::structureChanged()
1181 d.toc_models_.reset(view());
1182 // Navigator needs more than a simple update in this case. It needs to be
1184 updateDialog("toc", "");
1188 void GuiView::updateDialog(string const & name, string const & data)
1190 if (!isDialogVisible(name))
1193 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
1194 if (it == d.dialogs_.end())
1197 Dialog * const dialog = it->second.get();
1198 if (dialog->isVisibleView())
1199 dialog->initialiseParams(data);
1203 BufferView * GuiView::view()
1205 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1209 void GuiView::autoSave()
1211 LYXERR(Debug::INFO, "Running autoSave()");
1214 view()->buffer().autoSave();
1218 void GuiView::resetAutosaveTimers()
1221 d.autosave_timeout_.restart();
1225 bool GuiView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1228 Buffer * buf = buffer();
1230 if (cmd.origin == FuncRequest::TOC) {
1231 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
1233 if (toc->getStatus(view()->cursor(), cmd, fs))
1236 flag.setEnabled(false);
1240 switch(cmd.action) {
1241 case LFUN_BUFFER_WRITE:
1242 enable = buf && (buf->isUnnamed() || !buf->isClean());
1245 case LFUN_BUFFER_WRITE_AS:
1249 case LFUN_SPLIT_VIEW:
1250 if (cmd.getArg(0) == "vertical")
1251 enable = buf && (d.splitter_->count() == 1 ||
1252 d.splitter_->orientation() == Qt::Vertical);
1254 enable = buf && (d.splitter_->count() == 1 ||
1255 d.splitter_->orientation() == Qt::Horizontal);
1258 case LFUN_CLOSE_TAB_GROUP:
1259 enable = d.currentTabWorkArea();
1262 case LFUN_TOOLBAR_TOGGLE:
1263 if (GuiToolbar * t = toolbar(cmd.getArg(0)))
1264 flag.setOnOff(t->isVisible());
1267 case LFUN_UI_TOGGLE:
1268 flag.setOnOff(isFullScreen());
1271 case LFUN_DIALOG_TOGGLE:
1272 flag.setOnOff(isDialogVisible(cmd.getArg(0)));
1273 // fall through to set "enable"
1274 case LFUN_DIALOG_SHOW: {
1275 string const name = cmd.getArg(0);
1277 enable = name == "aboutlyx"
1278 || name == "file" //FIXME: should be removed.
1280 || name == "texinfo";
1281 else if (name == "print")
1282 enable = buf->isExportable("dvi")
1283 && lyxrc.print_command != "none";
1284 else if (name == "character" || name == "symbols") {
1285 if (!view() || !view()->cursor().inTexted())
1288 // FIXME we should consider passthru
1290 Inset const & in = view()->cursor().inset();
1291 enable = !in.getLayout().isPassThru();
1294 else if (name == "latexlog")
1295 enable = FileName(buf->logName()).isReadableFile();
1296 else if (name == "spellchecker")
1297 enable = theSpellChecker() && !buf->isReadonly();
1298 else if (name == "vclog")
1299 enable = buf->lyxvc().inUse();
1303 case LFUN_DIALOG_UPDATE: {
1304 string const name = cmd.getArg(0);
1306 enable = name == "prefs";
1310 case LFUN_INSET_APPLY: {
1311 string const name = cmd.getArg(0);
1312 Inset * inset = getOpenInset(name);
1314 FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument());
1316 if (!inset->getStatus(view()->cursor(), fr, fs)) {
1317 // Every inset is supposed to handle this
1318 LASSERT(false, break);
1322 FuncRequest fr(LFUN_INSET_INSERT, cmd.argument());
1323 flag |= lyx::getStatus(fr);
1325 enable = flag.enabled();
1329 case LFUN_COMPLETION_INLINE:
1330 if (!d.current_work_area_
1331 || !d.current_work_area_->completer().inlinePossible(view()->cursor()))
1335 case LFUN_COMPLETION_POPUP:
1336 if (!d.current_work_area_
1337 || !d.current_work_area_->completer().popupPossible(view()->cursor()))
1341 case LFUN_COMPLETION_COMPLETE:
1342 if (!d.current_work_area_
1343 || !d.current_work_area_->completer().inlinePossible(view()->cursor()))
1347 case LFUN_COMPLETION_ACCEPT:
1348 if (!d.current_work_area_
1349 || (!d.current_work_area_->completer().popupVisible()
1350 && !d.current_work_area_->completer().inlineVisible()
1351 && !d.current_work_area_->completer().completionAvailable()))
1355 case LFUN_COMPLETION_CANCEL:
1356 if (!d.current_work_area_
1357 || (!d.current_work_area_->completer().popupVisible()
1358 && !d.current_work_area_->completer().inlineVisible()))
1362 case LFUN_BUFFER_ZOOM_OUT:
1363 enable = buf && lyxrc.zoom > 10;
1366 case LFUN_BUFFER_ZOOM_IN:
1375 flag.setEnabled(false);
1381 static FileName selectTemplateFile()
1383 FileDialog dlg(qt_("Select template file"));
1384 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1385 dlg.setButton1(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
1387 FileDialog::Result result = dlg.open(toqstr(lyxrc.template_path),
1388 QStringList(qt_("LyX Documents (*.lyx)")));
1390 if (result.first == FileDialog::Later)
1392 if (result.second.isEmpty())
1394 return FileName(fromqstr(result.second));
1398 Buffer * GuiView::loadDocument(FileName const & filename, bool tolastfiles)
1402 Buffer * newBuffer = checkAndLoadLyXFile(filename);
1405 message(_("Document not loaded."));
1410 setBuffer(newBuffer);
1412 // scroll to the position when the file was last closed
1413 if (lyxrc.use_lastfilepos) {
1414 LastFilePosSection::FilePos filepos =
1415 theSession().lastFilePos().load(filename);
1416 view()->moveToPosition(filepos.pit, filepos.pos, 0, 0);
1420 theSession().lastFiles().add(filename);
1427 void GuiView::openDocument(string const & fname)
1429 string initpath = lyxrc.document_path;
1432 string const trypath = buffer()->filePath();
1433 // If directory is writeable, use this as default.
1434 if (FileName(trypath).isDirWritable())
1440 if (fname.empty()) {
1441 FileDialog dlg(qt_("Select document to open"), LFUN_FILE_OPEN);
1442 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1443 dlg.setButton2(qt_("Examples|#E#e"),
1444 toqstr(addPath(package().system_support().absFilename(), "examples")));
1446 QStringList filter(qt_("LyX Documents (*.lyx)"));
1447 filter << qt_("LyX-1.3.x Documents (*.lyx13)")
1448 << qt_("LyX-1.4.x Documents (*.lyx14)")
1449 << qt_("LyX-1.5.x Documents (*.lyx15)")
1450 << qt_("LyX-1.6.x Documents (*.lyx16)");
1451 FileDialog::Result result =
1452 dlg.open(toqstr(initpath), filter);
1454 if (result.first == FileDialog::Later)
1457 filename = fromqstr(result.second);
1459 // check selected filename
1460 if (filename.empty()) {
1461 message(_("Canceled."));
1467 // get absolute path of file and add ".lyx" to the filename if
1469 FileName const fullname =
1470 fileSearch(string(), filename, "lyx", support::may_not_exist);
1471 if (!fullname.empty())
1472 filename = fullname.absFilename();
1474 if (!fullname.onlyPath().isDirectory()) {
1475 Alert::warning(_("Invalid filename"),
1476 bformat(_("The directory in the given path\n%1$s\ndoes not exist."),
1477 from_utf8(fullname.absFilename())));
1480 // if the file doesn't exist, let the user create one
1481 if (!fullname.exists()) {
1482 // the user specifically chose this name. Believe him.
1483 Buffer * const b = newFile(filename, string(), true);
1489 docstring const disp_fn = makeDisplayPath(filename);
1490 message(bformat(_("Opening document %1$s..."), disp_fn));
1493 Buffer * buf = loadDocument(fullname);
1495 buf->updateLabels();
1497 buf->errors("Parse");
1498 str2 = bformat(_("Document %1$s opened."), disp_fn);
1499 if (buf->lyxvc().inUse())
1500 str2 += " " + from_utf8(buf->lyxvc().versionString()) +
1501 " " + _("Version control detected.");
1503 str2 = bformat(_("Could not open document %1$s"), disp_fn);
1508 // FIXME: clean that
1509 static bool import(GuiView * lv, FileName const & filename,
1510 string const & format, ErrorList & errorList)
1512 FileName const lyxfile(support::changeExtension(filename.absFilename(), ".lyx"));
1514 string loader_format;
1515 vector<string> loaders = theConverters().loaders();
1516 if (find(loaders.begin(), loaders.end(), format) == loaders.end()) {
1517 for (vector<string>::const_iterator it = loaders.begin();
1518 it != loaders.end(); ++it) {
1519 if (!theConverters().isReachable(format, *it))
1522 string const tofile =
1523 support::changeExtension(filename.absFilename(),
1524 formats.extension(*it));
1525 if (!theConverters().convert(0, filename, FileName(tofile),
1526 filename, format, *it, errorList))
1528 loader_format = *it;
1531 if (loader_format.empty()) {
1532 frontend::Alert::error(_("Couldn't import file"),
1533 bformat(_("No information for importing the format %1$s."),
1534 formats.prettyName(format)));
1538 loader_format = format;
1540 if (loader_format == "lyx") {
1541 Buffer * buf = lv->loadDocument(lyxfile);
1544 buf->updateLabels();
1546 buf->errors("Parse");
1548 Buffer * const b = newFile(lyxfile.absFilename(), string(), true);
1552 bool as_paragraphs = loader_format == "textparagraph";
1553 string filename2 = (loader_format == format) ? filename.absFilename()
1554 : support::changeExtension(filename.absFilename(),
1555 formats.extension(loader_format));
1556 lv->view()->insertPlaintextFile(FileName(filename2), as_paragraphs);
1557 theLyXFunc().setLyXView(lv);
1558 lyx::dispatch(FuncRequest(LFUN_MARK_OFF));
1565 void GuiView::importDocument(string const & argument)
1568 string filename = split(argument, format, ' ');
1570 LYXERR(Debug::INFO, format << " file: " << filename);
1572 // need user interaction
1573 if (filename.empty()) {
1574 string initpath = lyxrc.document_path;
1576 Buffer const * buf = buffer();
1578 string const trypath = buf->filePath();
1579 // If directory is writeable, use this as default.
1580 if (FileName(trypath).isDirWritable())
1584 docstring const text = bformat(_("Select %1$s file to import"),
1585 formats.prettyName(format));
1587 FileDialog dlg(toqstr(text), LFUN_BUFFER_IMPORT);
1588 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1589 dlg.setButton2(qt_("Examples|#E#e"),
1590 toqstr(addPath(package().system_support().absFilename(), "examples")));
1592 docstring filter = formats.prettyName(format);
1595 filter += from_utf8(formats.extension(format));
1598 FileDialog::Result result =
1599 dlg.open(toqstr(initpath), fileFilters(toqstr(filter)));
1601 if (result.first == FileDialog::Later)
1604 filename = fromqstr(result.second);
1606 // check selected filename
1607 if (filename.empty())
1608 message(_("Canceled."));
1611 if (filename.empty())
1614 // get absolute path of file
1615 FileName const fullname(support::makeAbsPath(filename));
1617 FileName const lyxfile(support::changeExtension(fullname.absFilename(), ".lyx"));
1619 // Check if the document already is open
1620 Buffer * buf = theBufferList().getBuffer(lyxfile);
1623 if (!closeBuffer()) {
1624 message(_("Canceled."));
1629 docstring const displaypath = makeDisplayPath(lyxfile.absFilename(), 30);
1631 // if the file exists already, and we didn't do
1632 // -i lyx thefile.lyx, warn
1633 if (lyxfile.exists() && fullname != lyxfile) {
1635 docstring text = bformat(_("The document %1$s already exists.\n\n"
1636 "Do you want to overwrite that document?"), displaypath);
1637 int const ret = Alert::prompt(_("Overwrite document?"),
1638 text, 0, 1, _("&Overwrite"), _("&Cancel"));
1641 message(_("Canceled."));
1646 message(bformat(_("Importing %1$s..."), displaypath));
1647 ErrorList errorList;
1648 if (import(this, fullname, format, errorList))
1649 message(_("imported."));
1651 message(_("file not imported!"));
1653 // FIXME (Abdel 12/08/06): Is there a need to display the error list here?
1657 void GuiView::newDocument(string const & filename, bool from_template)
1659 FileName initpath(lyxrc.document_path);
1660 Buffer * buf = buffer();
1662 FileName const trypath(buf->filePath());
1663 // If directory is writeable, use this as default.
1664 if (trypath.isDirWritable())
1668 string templatefile;
1669 if (from_template) {
1670 templatefile = selectTemplateFile().absFilename();
1671 if (templatefile.empty())
1676 if (filename.empty())
1677 b = newUnnamedFile(templatefile, initpath);
1679 b = newFile(filename, templatefile, true);
1684 // If no new document could be created, it is unsure
1685 // whether there is a valid BufferView.
1687 // Ensure the cursor is correctly positioned on screen.
1688 view()->showCursor();
1692 void GuiView::insertLyXFile(docstring const & fname)
1694 BufferView * bv = view();
1699 FileName filename(to_utf8(fname));
1701 if (!filename.empty()) {
1702 bv->insertLyXFile(filename);
1706 // Launch a file browser
1708 string initpath = lyxrc.document_path;
1709 string const trypath = bv->buffer().filePath();
1710 // If directory is writeable, use this as default.
1711 if (FileName(trypath).isDirWritable())
1715 FileDialog dlg(qt_("Select LyX document to insert"), LFUN_FILE_INSERT);
1716 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1717 dlg.setButton2(qt_("Examples|#E#e"),
1718 toqstr(addPath(package().system_support().absFilename(),
1721 FileDialog::Result result = dlg.open(toqstr(initpath),
1722 QStringList(qt_("LyX Documents (*.lyx)")));
1724 if (result.first == FileDialog::Later)
1728 filename.set(fromqstr(result.second));
1730 // check selected filename
1731 if (filename.empty()) {
1732 // emit message signal.
1733 message(_("Canceled."));
1737 bv->insertLyXFile(filename);
1741 void GuiView::insertPlaintextFile(docstring const & fname,
1744 BufferView * bv = view();
1748 if (!fname.empty() && !FileName::isAbsolute(to_utf8(fname))) {
1749 message(_("Absolute filename expected."));
1754 FileName filename(to_utf8(fname));
1756 if (!filename.empty()) {
1757 bv->insertPlaintextFile(filename, asParagraph);
1761 FileDialog dlg(qt_("Select file to insert"), (asParagraph ?
1762 LFUN_FILE_INSERT_PLAINTEXT_PARA : LFUN_FILE_INSERT_PLAINTEXT));
1764 FileDialog::Result result = dlg.open(toqstr(bv->buffer().filePath()),
1765 QStringList(qt_("All Files (*)")));
1767 if (result.first == FileDialog::Later)
1771 filename.set(fromqstr(result.second));
1773 // check selected filename
1774 if (filename.empty()) {
1775 // emit message signal.
1776 message(_("Canceled."));
1780 bv->insertPlaintextFile(filename, asParagraph);
1784 bool GuiView::renameBuffer(Buffer & b, docstring const & newname)
1786 FileName fname = b.fileName();
1787 FileName const oldname = fname;
1789 if (!newname.empty()) {
1791 fname = support::makeAbsPath(to_utf8(newname), oldname.onlyPath().absFilename());
1793 // Switch to this Buffer.
1796 // No argument? Ask user through dialog.
1798 FileDialog dlg(qt_("Choose a filename to save document as"),
1799 LFUN_BUFFER_WRITE_AS);
1800 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1801 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
1803 if (!isLyXFilename(fname.absFilename()))
1804 fname.changeExtension(".lyx");
1806 FileDialog::Result result =
1807 dlg.save(toqstr(fname.onlyPath().absFilename()),
1808 QStringList(qt_("LyX Documents (*.lyx)")),
1809 toqstr(fname.onlyFileName()));
1811 if (result.first == FileDialog::Later)
1814 fname.set(fromqstr(result.second));
1819 if (!isLyXFilename(fname.absFilename()))
1820 fname.changeExtension(".lyx");
1823 if (FileName(fname).exists()) {
1824 docstring const file = makeDisplayPath(fname.absFilename(), 30);
1825 docstring text = bformat(_("The document %1$s already "
1826 "exists.\n\nDo you want to "
1827 "overwrite that document?"),
1829 int const ret = Alert::prompt(_("Overwrite document?"),
1830 text, 0, 2, _("&Overwrite"), _("&Rename"), _("&Cancel"));
1833 case 1: return renameBuffer(b, docstring());
1834 case 2: return false;
1838 FileName oldauto = b.getAutosaveFilename();
1840 // Ok, change the name of the buffer
1841 b.setFileName(fname.absFilename());
1843 bool unnamed = b.isUnnamed();
1844 b.setUnnamed(false);
1845 b.saveCheckSum(fname);
1847 // bring the autosave file with us, just in case.
1848 b.moveAutosaveFile(oldauto);
1850 if (!saveBuffer(b)) {
1851 oldauto = b.getAutosaveFilename();
1852 b.setFileName(oldname.absFilename());
1853 b.setUnnamed(unnamed);
1854 b.saveCheckSum(oldname);
1855 b.moveAutosaveFile(oldauto);
1863 bool GuiView::saveBuffer(Buffer & b)
1865 if (workArea(b) && workArea(b)->inDialogMode())
1869 return renameBuffer(b, docstring());
1872 theSession().lastFiles().add(b.fileName());
1876 // Switch to this Buffer.
1879 // FIXME: we don't tell the user *WHY* the save failed !!
1880 docstring const file = makeDisplayPath(b.absFileName(), 30);
1881 docstring text = bformat(_("The document %1$s could not be saved.\n\n"
1882 "Do you want to rename the document and "
1883 "try again?"), file);
1884 int const ret = Alert::prompt(_("Rename and save?"),
1885 text, 0, 2, _("&Rename"), _("&Retry"), _("&Cancel"));
1888 if (!renameBuffer(b, docstring()))
1897 return saveBuffer(b);
1901 bool GuiView::closeBuffer()
1903 Buffer * buf = buffer();
1904 return buf && closeBuffer(*buf);
1908 bool GuiView::closeBuffer(Buffer & buf, bool tolastopened, bool mark_active)
1910 // goto bookmark to update bookmark pit.
1911 //FIXME: we should update only the bookmarks related to this buffer!
1912 LYXERR(Debug::DEBUG, "GuiView::closeBuffer()");
1913 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
1914 theLyXFunc().gotoBookmark(i+1, false, false);
1916 if (buf.isClean() || buf.paragraphs().empty()) {
1917 // save in sessions if requested
1918 // do not save childs if their master
1919 // is opened as well
1921 theSession().lastOpened().add(buf.fileName(), mark_active);
1923 // Don't close child documents.
1924 removeWorkArea(currentMainWorkArea());
1926 theBufferList().release(&buf);
1929 // Switch to this Buffer.
1934 if (buf.isUnnamed())
1935 file = from_utf8(buf.fileName().onlyFileName());
1937 file = buf.fileName().displayName(30);
1939 // Bring this window to top before asking questions.
1943 docstring const text = bformat(_("The document %1$s has unsaved changes."
1944 "\n\nDo you want to save the document or discard the changes?"), file);
1945 int const ret = Alert::prompt(_("Save changed document?"),
1946 text, 0, 2, _("&Save"), _("&Discard"), _("&Cancel"));
1950 if (!saveBuffer(buf))
1954 // if we crash after this we could
1955 // have no autosave file but I guess
1956 // this is really improbable (Jug)
1957 buf.removeAutosaveFile();
1963 // save file names to .lyx/session
1965 theSession().lastOpened().add(buf.fileName(), mark_active);
1968 // Don't close child documents.
1969 removeWorkArea(currentMainWorkArea());
1971 theBufferList().release(&buf);
1977 void GuiView::gotoNextOrPreviousBuffer(NextOrPrevious np)
1979 Buffer * const curbuf = buffer();
1980 Buffer * nextbuf = curbuf;
1982 if (np == NEXTBUFFER)
1983 nextbuf = theBufferList().next(nextbuf);
1985 nextbuf = theBufferList().previous(nextbuf);
1986 if (nextbuf == curbuf)
1992 if (workArea(*nextbuf))
1999 bool GuiView::dispatch(FuncRequest const & cmd)
2001 BufferView * bv = view();
2002 // By default we won't need any update.
2004 bv->cursor().updateFlags(Update::None);
2005 bool dispatched = true;
2007 if (cmd.origin == FuncRequest::TOC) {
2008 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
2009 toc->doDispatch(bv->cursor(), cmd);
2013 switch(cmd.action) {
2014 case LFUN_BUFFER_IMPORT:
2015 importDocument(to_utf8(cmd.argument()));
2018 case LFUN_BUFFER_SWITCH:
2019 if (FileName::isAbsolute(to_utf8(cmd.argument()))) {
2021 theBufferList().getBuffer(FileName(to_utf8(cmd.argument())));
2025 bv->cursor().message(_("Document not loaded"));
2029 case LFUN_BUFFER_NEXT:
2030 gotoNextOrPreviousBuffer(NEXTBUFFER);
2033 case LFUN_BUFFER_PREVIOUS:
2034 gotoNextOrPreviousBuffer(PREVBUFFER);
2037 case LFUN_COMMAND_EXECUTE: {
2038 bool const show_it = cmd.argument() != "off";
2039 // FIXME: this is a hack, "minibuffer" should not be
2041 if (GuiToolbar * t = toolbar("minibuffer")) {
2042 t->setVisible(show_it);
2043 if (show_it && t->commandBuffer())
2044 t->commandBuffer()->setFocus();
2048 case LFUN_DROP_LAYOUTS_CHOICE:
2050 d.layout_->showPopup();
2053 case LFUN_MENU_OPEN:
2054 if (QMenu * menu = guiApp->menus().menu(toqstr(cmd.argument()), *this))
2055 menu->exec(QCursor::pos());
2058 case LFUN_FILE_INSERT:
2059 insertLyXFile(cmd.argument());
2061 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
2062 insertPlaintextFile(cmd.argument(), true);
2065 case LFUN_FILE_INSERT_PLAINTEXT:
2066 insertPlaintextFile(cmd.argument(), false);
2069 case LFUN_BUFFER_WRITE:
2071 saveBuffer(bv->buffer());
2074 case LFUN_BUFFER_WRITE_AS:
2076 renameBuffer(bv->buffer(), cmd.argument());
2079 case LFUN_BUFFER_WRITE_ALL: {
2080 Buffer * first = theBufferList().first();
2083 message(_("Saving all documents..."));
2084 // We cannot use a for loop as the buffer list cycles.
2087 if (!b->isClean()) {
2089 LYXERR(Debug::ACTION, "Saved " << b->absFileName());
2091 b = theBufferList().next(b);
2092 } while (b != first);
2093 message(_("All documents saved."));
2097 case LFUN_TOOLBAR_TOGGLE: {
2098 string const name = cmd.getArg(0);
2099 if (GuiToolbar * t = toolbar(name))
2104 case LFUN_DIALOG_UPDATE: {
2105 string const name = to_utf8(cmd.argument());
2106 // Can only update a dialog connected to an existing inset
2107 Inset * inset = getOpenInset(name);
2109 FuncRequest fr(LFUN_INSET_DIALOG_UPDATE, cmd.argument());
2110 inset->dispatch(view()->cursor(), fr);
2111 } else if (name == "paragraph") {
2112 lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
2113 } else if (name == "prefs" || name == "document") {
2114 updateDialog(name, string());
2119 case LFUN_DIALOG_TOGGLE: {
2120 if (isDialogVisible(cmd.getArg(0)))
2121 dispatch(FuncRequest(LFUN_DIALOG_HIDE, cmd.argument()));
2123 dispatch(FuncRequest(LFUN_DIALOG_SHOW, cmd.argument()));
2127 case LFUN_DIALOG_DISCONNECT_INSET:
2128 disconnectDialog(to_utf8(cmd.argument()));
2131 case LFUN_DIALOG_HIDE: {
2132 guiApp->hideDialogs(to_utf8(cmd.argument()), 0);
2136 case LFUN_DIALOG_SHOW: {
2137 string const name = cmd.getArg(0);
2138 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
2140 if (name == "character") {
2141 data = freefont2string();
2143 showDialog("character", data);
2144 } else if (name == "latexlog") {
2145 Buffer::LogType type;
2146 string const logfile = buffer()->logName(&type);
2148 case Buffer::latexlog:
2151 case Buffer::buildlog:
2155 data += Lexer::quoteString(logfile);
2156 showDialog("log", data);
2157 } else if (name == "vclog") {
2158 string const data = "vc " +
2159 Lexer::quoteString(buffer()->lyxvc().getLogFile());
2160 showDialog("log", data);
2161 } else if (name == "symbols") {
2162 data = bv->cursor().getEncoding()->name();
2164 showDialog("symbols", data);
2166 } else if (name == "prefs" && isFullScreen()) {
2167 FuncRequest fr(LFUN_INSET_INSERT, "fullscreen");
2169 showDialog("prefs", data);
2171 showDialog(name, data);
2175 case LFUN_INSET_APPLY: {
2176 string const name = cmd.getArg(0);
2177 Inset * inset = getOpenInset(name);
2179 // put cursor in front of inset.
2180 if (!view()->setCursorFromInset(inset)) {
2181 LASSERT(false, break);
2184 // useful if we are called from a dialog.
2185 view()->cursor().beginUndoGroup();
2186 view()->cursor().recordUndo();
2187 FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument());
2188 inset->dispatch(view()->cursor(), fr);
2189 view()->cursor().endUndoGroup();
2191 FuncRequest fr(LFUN_INSET_INSERT, cmd.argument());
2197 case LFUN_UI_TOGGLE:
2199 // Make sure the keyboard focus stays in the work area.
2203 case LFUN_SPLIT_VIEW:
2204 if (Buffer * buf = buffer()) {
2205 string const orientation = cmd.getArg(0);
2206 d.splitter_->setOrientation(orientation == "vertical"
2207 ? Qt::Vertical : Qt::Horizontal);
2208 TabWorkArea * twa = addTabWorkArea();
2209 GuiWorkArea * wa = twa->addWorkArea(*buf, *this);
2210 setCurrentWorkArea(wa);
2214 case LFUN_CLOSE_TAB_GROUP:
2215 if (TabWorkArea * twa = d.currentTabWorkArea()) {
2217 twa = d.currentTabWorkArea();
2218 // Switch to the next GuiWorkArea in the found TabWorkArea.
2220 // Make sure the work area is up to date.
2221 setCurrentWorkArea(twa->currentWorkArea());
2223 setCurrentWorkArea(0);
2228 case LFUN_COMPLETION_INLINE:
2229 if (d.current_work_area_)
2230 d.current_work_area_->completer().showInline();
2233 case LFUN_COMPLETION_POPUP:
2234 if (d.current_work_area_)
2235 d.current_work_area_->completer().showPopup();
2239 case LFUN_COMPLETION_COMPLETE:
2240 if (d.current_work_area_)
2241 d.current_work_area_->completer().tab();
2244 case LFUN_COMPLETION_CANCEL:
2245 if (d.current_work_area_) {
2246 if (d.current_work_area_->completer().popupVisible())
2247 d.current_work_area_->completer().hidePopup();
2249 d.current_work_area_->completer().hideInline();
2253 case LFUN_COMPLETION_ACCEPT:
2254 if (d.current_work_area_)
2255 d.current_work_area_->completer().activate();
2258 case LFUN_BUFFER_ZOOM_IN:
2259 case LFUN_BUFFER_ZOOM_OUT:
2260 if (cmd.argument().empty()) {
2261 if (cmd.action == LFUN_BUFFER_ZOOM_IN)
2266 lyxrc.zoom += convert<int>(cmd.argument());
2268 if (lyxrc.zoom < 10)
2271 // The global QPixmapCache is used in GuiPainter to cache text
2272 // painting so we must reset it.
2273 QPixmapCache::clear();
2274 guiApp->fontLoader().update();
2275 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
2283 // Part of automatic menu appearance feature.
2284 if (isFullScreen()) {
2285 if (menuBar()->isVisible() && lyxrc.full_screen_menubar)
2287 if (statusBar()->isVisible())
2288 statusBar()->hide();
2295 void GuiView::lfunUiToggle(FuncRequest const & cmd)
2297 string const arg = cmd.getArg(0);
2298 if (arg == "scrollbar") {
2299 // hide() is of no help
2300 if (d.current_work_area_->verticalScrollBarPolicy() ==
2301 Qt::ScrollBarAlwaysOff)
2303 d.current_work_area_->setVerticalScrollBarPolicy(
2304 Qt::ScrollBarAsNeeded);
2306 d.current_work_area_->setVerticalScrollBarPolicy(
2307 Qt::ScrollBarAlwaysOff);
2310 if (arg == "statusbar") {
2311 statusBar()->setVisible(!statusBar()->isVisible());
2314 if (arg == "menubar") {
2315 menuBar()->setVisible(!menuBar()->isVisible());
2318 #if QT_VERSION >= 0x040300
2319 if (arg == "frame") {
2321 getContentsMargins(&l, &t, &r, &b);
2322 //are the frames in default state?
2323 d.current_work_area_->setFrameStyle(QFrame::NoFrame);
2325 setContentsMargins(-2, -2, -2, -2);
2327 setContentsMargins(0, 0, 0, 0);
2332 if (arg == "fullscreen") {
2337 message(bformat("LFUN_UI_TOGGLE " + _("%1$s unknown command!"), from_utf8(arg)));
2341 void GuiView::toggleFullScreen()
2343 if (isFullScreen()) {
2344 for (int i = 0; i != d.splitter_->count(); ++i)
2345 d.tabWorkArea(i)->setFullScreen(false);
2346 #if QT_VERSION >= 0x040300
2347 setContentsMargins(0, 0, 0, 0);
2349 setWindowState(windowState() ^ Qt::WindowFullScreen);
2352 statusBar()->show();
2355 hideDialogs("prefs", 0);
2356 for (int i = 0; i != d.splitter_->count(); ++i)
2357 d.tabWorkArea(i)->setFullScreen(true);
2358 #if QT_VERSION >= 0x040300
2359 setContentsMargins(-2, -2, -2, -2);
2362 setWindowState(windowState() ^ Qt::WindowFullScreen);
2363 statusBar()->hide();
2364 if (lyxrc.full_screen_menubar)
2366 if (lyxrc.full_screen_toolbars) {
2367 ToolbarMap::iterator end = d.toolbars_.end();
2368 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
2373 // give dialogs like the TOC a chance to adapt
2378 Buffer const * GuiView::updateInset(Inset const * inset)
2380 if (!d.current_work_area_)
2384 d.current_work_area_->scheduleRedraw();
2386 return &d.current_work_area_->bufferView().buffer();
2390 void GuiView::restartCursor()
2392 /* When we move around, or type, it's nice to be able to see
2393 * the cursor immediately after the keypress.
2395 if (d.current_work_area_)
2396 d.current_work_area_->startBlinkingCursor();
2398 // Take this occasion to update the other GUI elements.
2404 void GuiView::updateCompletion(Cursor & cur, bool start, bool keep)
2406 if (d.current_work_area_)
2407 d.current_work_area_->completer().updateVisibility(cur, start, keep);
2412 // This list should be kept in sync with the list of insets in
2413 // src/insets/Inset.cpp. I.e., if a dialog goes with an inset, the
2414 // dialog should have the same name as the inset.
2415 // Changes should be also recorded in LFUN_DIALOG_SHOW doxygen
2416 // docs in LyXAction.cpp.
2418 char const * const dialognames[] = {
2419 "aboutlyx", "bibitem", "bibtex", "box", "branch", "changes", "character",
2420 "citation", "document", "errorlist", "ert", "external", "file", "findreplace",
2421 "findreplaceadv", "float", "graphics", "href", "include", "index",
2422 "index_print", "info", "listings", "label", "log", "mathdelimiter",
2423 "mathmatrix", "mathspace", "nomenclature", "nomencl_print", "note",
2424 "paragraph", "phantom", "prefs", "print", "ref", "sendto", "space",
2425 "spellchecker", "symbols", "tabular", "tabularcreate", "thesaurus", "texinfo",
2426 "toc", "view-source", "vspace", "wrap" };
2428 char const * const * const end_dialognames =
2429 dialognames + (sizeof(dialognames) / sizeof(char *));
2433 cmpCStr(char const * name) : name_(name) {}
2434 bool operator()(char const * other) {
2435 return strcmp(other, name_) == 0;
2442 bool isValidName(string const & name)
2444 return find_if(dialognames, end_dialognames,
2445 cmpCStr(name.c_str())) != end_dialognames;
2451 void GuiView::resetDialogs()
2453 // Make sure that no LFUN uses any LyXView.
2454 theLyXFunc().setLyXView(0);
2457 constructToolbars();
2458 guiApp->menus().fillMenuBar(menuBar(), this, false);
2460 d.layout_->updateContents(true);
2461 // Now update controls with current buffer.
2462 theLyXFunc().setLyXView(this);
2468 Dialog * GuiView::findOrBuild(string const & name, bool hide_it)
2470 if (!isValidName(name))
2473 map<string, DialogPtr>::iterator it = d.dialogs_.find(name);
2475 if (it != d.dialogs_.end()) {
2477 it->second->hideView();
2478 return it->second.get();
2481 Dialog * dialog = build(name);
2482 d.dialogs_[name].reset(dialog);
2483 if (lyxrc.allow_geometry_session)
2484 dialog->restoreSession();
2491 void GuiView::showDialog(string const & name, string const & data,
2499 Dialog * dialog = findOrBuild(name, false);
2501 dialog->showData(data);
2503 d.open_insets_[name] = inset;
2506 catch (ExceptionMessage const & ex) {
2514 bool GuiView::isDialogVisible(string const & name) const
2516 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
2517 if (it == d.dialogs_.end())
2519 return it->second.get()->isVisibleView() && !it->second.get()->isClosing();
2523 void GuiView::hideDialog(string const & name, Inset * inset)
2525 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
2526 if (it == d.dialogs_.end())
2529 if (inset && inset != getOpenInset(name))
2532 Dialog * const dialog = it->second.get();
2533 if (dialog->isVisibleView())
2535 d.open_insets_[name] = 0;
2539 void GuiView::disconnectDialog(string const & name)
2541 if (!isValidName(name))
2544 if (d.open_insets_.find(name) != d.open_insets_.end())
2545 d.open_insets_[name] = 0;
2549 Inset * GuiView::getOpenInset(string const & name) const
2551 if (!isValidName(name))
2554 map<string, Inset *>::const_iterator it = d.open_insets_.find(name);
2555 return it == d.open_insets_.end() ? 0 : it->second;
2559 void GuiView::hideAll() const
2561 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
2562 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
2564 for(; it != end; ++it)
2565 it->second->hideView();
2569 void GuiView::updateDialogs()
2571 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
2572 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
2574 for(; it != end; ++it) {
2575 Dialog * dialog = it->second.get();
2576 if (dialog && dialog->isVisibleView())
2577 dialog->checkStatus();
2584 // will be replaced by a proper factory...
2585 Dialog * createGuiAbout(GuiView & lv);
2586 Dialog * createGuiBibitem(GuiView & lv);
2587 Dialog * createGuiBibtex(GuiView & lv);
2588 Dialog * createGuiBox(GuiView & lv);
2589 Dialog * createGuiBranch(GuiView & lv);
2590 Dialog * createGuiChanges(GuiView & lv);
2591 Dialog * createGuiCharacter(GuiView & lv);
2592 Dialog * createGuiCitation(GuiView & lv);
2593 Dialog * createGuiDelimiter(GuiView & lv);
2594 Dialog * createGuiDocument(GuiView & lv);
2595 Dialog * createGuiErrorList(GuiView & lv);
2596 Dialog * createGuiERT(GuiView & lv);
2597 Dialog * createGuiExternal(GuiView & lv);
2598 Dialog * createGuiFloat(GuiView & lv);
2599 Dialog * createGuiGraphics(GuiView & lv);
2600 Dialog * createGuiInclude(GuiView & lv);
2601 Dialog * createGuiIndex(GuiView & lv);
2602 Dialog * createGuiInfo(GuiView & lv);
2603 Dialog * createGuiLabel(GuiView & lv);
2604 Dialog * createGuiListings(GuiView & lv);
2605 Dialog * createGuiLog(GuiView & lv);
2606 Dialog * createGuiMathHSpace(GuiView & lv);
2607 Dialog * createGuiMathMatrix(GuiView & lv);
2608 Dialog * createGuiNomenclature(GuiView & lv);
2609 Dialog * createGuiNote(GuiView & lv);
2610 Dialog * createGuiParagraph(GuiView & lv);
2611 Dialog * createGuiPhantom(GuiView & lv);
2612 Dialog * createGuiPreferences(GuiView & lv);
2613 Dialog * createGuiPrint(GuiView & lv);
2614 Dialog * createGuiPrintindex(GuiView & lv);
2615 Dialog * createGuiPrintNomencl(GuiView & lv);
2616 Dialog * createGuiRef(GuiView & lv);
2617 Dialog * createGuiSearch(GuiView & lv);
2618 Dialog * createGuiSearchAdv(GuiView & lv);
2619 Dialog * createGuiSendTo(GuiView & lv);
2620 Dialog * createGuiShowFile(GuiView & lv);
2621 Dialog * createGuiSpellchecker(GuiView & lv);
2622 Dialog * createGuiSymbols(GuiView & lv);
2623 Dialog * createGuiTabularCreate(GuiView & lv);
2624 Dialog * createGuiTabular(GuiView & lv);
2625 Dialog * createGuiTexInfo(GuiView & lv);
2626 Dialog * createGuiTextHSpace(GuiView & lv);
2627 Dialog * createGuiToc(GuiView & lv);
2628 Dialog * createGuiThesaurus(GuiView & lv);
2629 Dialog * createGuiHyperlink(GuiView & lv);
2630 Dialog * createGuiVSpace(GuiView & lv);
2631 Dialog * createGuiViewSource(GuiView & lv);
2632 Dialog * createGuiWrap(GuiView & lv);
2635 Dialog * GuiView::build(string const & name)
2637 LASSERT(isValidName(name), return 0);
2639 if (name == "aboutlyx")
2640 return createGuiAbout(*this);
2641 if (name == "bibitem")
2642 return createGuiBibitem(*this);
2643 if (name == "bibtex")
2644 return createGuiBibtex(*this);
2646 return createGuiBox(*this);
2647 if (name == "branch")
2648 return createGuiBranch(*this);
2649 if (name == "changes")
2650 return createGuiChanges(*this);
2651 if (name == "character")
2652 return createGuiCharacter(*this);
2653 if (name == "citation")
2654 return createGuiCitation(*this);
2655 if (name == "document")
2656 return createGuiDocument(*this);
2657 if (name == "errorlist")
2658 return createGuiErrorList(*this);
2660 return createGuiERT(*this);
2661 if (name == "external")
2662 return createGuiExternal(*this);
2664 return createGuiShowFile(*this);
2665 if (name == "findreplace")
2666 return createGuiSearch(*this);
2667 if (name == "findreplaceadv")
2668 return createGuiSearchAdv(*this);
2669 if (name == "float")
2670 return createGuiFloat(*this);
2671 if (name == "graphics")
2672 return createGuiGraphics(*this);
2674 return createGuiHyperlink(*this);
2675 if (name == "include")
2676 return createGuiInclude(*this);
2677 if (name == "index")
2678 return createGuiIndex(*this);
2679 if (name == "index_print")
2680 return createGuiPrintindex(*this);
2682 return createGuiInfo(*this);
2683 if (name == "label")
2684 return createGuiLabel(*this);
2685 if (name == "listings")
2686 return createGuiListings(*this);
2688 return createGuiLog(*this);
2689 if (name == "mathdelimiter")
2690 return createGuiDelimiter(*this);
2691 if (name == "mathspace")
2692 return createGuiMathHSpace(*this);
2693 if (name == "mathmatrix")
2694 return createGuiMathMatrix(*this);
2695 if (name == "nomenclature")
2696 return createGuiNomenclature(*this);
2697 if (name == "nomencl_print")
2698 return createGuiPrintNomencl(*this);
2700 return createGuiNote(*this);
2701 if (name == "paragraph")
2702 return createGuiParagraph(*this);
2703 if (name == "phantom")
2704 return createGuiPhantom(*this);
2705 if (name == "prefs")
2706 return createGuiPreferences(*this);
2707 if (name == "print")
2708 return createGuiPrint(*this);
2710 return createGuiRef(*this);
2711 if (name == "sendto")
2712 return createGuiSendTo(*this);
2713 if (name == "space")
2714 return createGuiTextHSpace(*this);
2715 if (name == "spellchecker")
2716 return createGuiSpellchecker(*this);
2717 if (name == "symbols")
2718 return createGuiSymbols(*this);
2719 if (name == "tabular")
2720 return createGuiTabular(*this);
2721 if (name == "tabularcreate")
2722 return createGuiTabularCreate(*this);
2723 if (name == "texinfo")
2724 return createGuiTexInfo(*this);
2725 if (name == "thesaurus")
2726 return createGuiThesaurus(*this);
2728 return createGuiToc(*this);
2729 if (name == "view-source")
2730 return createGuiViewSource(*this);
2731 if (name == "vspace")
2732 return createGuiVSpace(*this);
2734 return createGuiWrap(*this);
2740 } // namespace frontend
2743 #include "moc_GuiView.cpp"