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 "GuiApplication.h"
21 #include "GuiCommandBuffer.h"
22 #include "GuiCompleter.h"
23 #include "GuiWorkArea.h"
24 #include "GuiKeySymbol.h"
25 #include "GuiToolbar.h"
29 #include "qt_helpers.h"
31 #include "frontends/alert.h"
33 #include "buffer_funcs.h"
35 #include "BufferList.h"
36 #include "BufferParams.h"
37 #include "BufferView.h"
38 #include "Converter.h"
41 #include "ErrorList.h"
43 #include "FuncStatus.h"
44 #include "FuncRequest.h"
52 #include "Paragraph.h"
53 #include "TextClass.h"
58 #include "support/lassert.h"
59 #include "support/debug.h"
60 #include "support/ExceptionMessage.h"
61 #include "support/FileName.h"
62 #include "support/filetools.h"
63 #include "support/gettext.h"
64 #include "support/ForkedCalls.h"
65 #include "support/lstrings.h"
66 #include "support/os.h"
67 #include "support/Package.h"
68 #include "support/Timeout.h"
71 #include <QApplication>
72 #include <QCloseEvent>
74 #include <QDesktopWidget>
75 #include <QDragEnterEvent>
83 #include <QPushButton>
87 #include <QStackedWidget>
94 #include <boost/bind.hpp>
96 #ifdef HAVE_SYS_TIME_H
97 # include <sys/time.h>
104 using namespace lyx::support;
111 class BackgroundWidget : public QWidget
116 LYXERR(Debug::GUI, "show banner: " << lyxrc.show_banner);
117 /// The text to be written on top of the pixmap
118 QString const text = lyx_version ?
119 qt_("version ") + lyx_version : qt_("unknown version");
120 splash_ = QPixmap(":/images/banner.png");
122 QPainter pain(&splash_);
123 pain.setPen(QColor(0, 0, 0));
125 // The font used to display the version info
126 font.setStyleHint(QFont::SansSerif);
127 font.setWeight(QFont::Bold);
128 font.setPointSize(int(toqstr(lyxrc.font_sizes[FONT_SIZE_LARGE]).toDouble()));
130 pain.drawText(260, 15, text);
133 void paintEvent(QPaintEvent *)
135 int x = (width() - splash_.width()) / 2;
136 int y = (height() - splash_.height()) / 2;
138 pain.drawPixmap(x, y, splash_);
146 /// Toolbar store providing access to individual toolbars by name.
147 typedef std::map<std::string, GuiToolbar *> ToolbarMap;
149 typedef boost::shared_ptr<Dialog> DialogPtr;
154 struct GuiView::GuiViewPrivate
157 : current_work_area_(0), current_main_work_area_(0),
158 layout_(0), autosave_timeout_(5000),
161 // hardcode here the platform specific icon size
162 smallIconSize = 14; // scaling problems
163 normalIconSize = 20; // ok, default
164 bigIconSize = 26; // better for some math icons
166 splitter_ = new QSplitter;
167 bg_widget_ = new BackgroundWidget;
168 stack_widget_ = new QStackedWidget;
169 stack_widget_->addWidget(bg_widget_);
170 stack_widget_->addWidget(splitter_);
178 delete stack_widget_;
181 QMenu * toolBarPopup(GuiView * parent)
183 // FIXME: translation
184 QMenu * menu = new QMenu(parent);
185 QActionGroup * iconSizeGroup = new QActionGroup(parent);
187 QAction * smallIcons = new QAction(iconSizeGroup);
188 smallIcons->setText(qt_("Small-sized icons"));
189 smallIcons->setCheckable(true);
190 QObject::connect(smallIcons, SIGNAL(triggered()),
191 parent, SLOT(smallSizedIcons()));
192 menu->addAction(smallIcons);
194 QAction * normalIcons = new QAction(iconSizeGroup);
195 normalIcons->setText(qt_("Normal-sized icons"));
196 normalIcons->setCheckable(true);
197 QObject::connect(normalIcons, SIGNAL(triggered()),
198 parent, SLOT(normalSizedIcons()));
199 menu->addAction(normalIcons);
201 QAction * bigIcons = new QAction(iconSizeGroup);
202 bigIcons->setText(qt_("Big-sized icons"));
203 bigIcons->setCheckable(true);
204 QObject::connect(bigIcons, SIGNAL(triggered()),
205 parent, SLOT(bigSizedIcons()));
206 menu->addAction(bigIcons);
208 unsigned int cur = parent->iconSize().width();
209 if ( cur == parent->d.smallIconSize)
210 smallIcons->setChecked(true);
211 else if (cur == parent->d.normalIconSize)
212 normalIcons->setChecked(true);
213 else if (cur == parent->d.bigIconSize)
214 bigIcons->setChecked(true);
221 stack_widget_->setCurrentWidget(bg_widget_);
222 bg_widget_->setUpdatesEnabled(true);
225 TabWorkArea * tabWorkArea(int i)
227 return dynamic_cast<TabWorkArea *>(splitter_->widget(i));
230 TabWorkArea * currentTabWorkArea()
232 if (splitter_->count() == 1)
233 // The first TabWorkArea is always the first one, if any.
234 return tabWorkArea(0);
236 for (int i = 0; i != splitter_->count(); ++i) {
237 TabWorkArea * twa = tabWorkArea(i);
238 if (current_main_work_area_ == twa->currentWorkArea())
242 // None has the focus so we just take the first one.
243 return tabWorkArea(0);
247 GuiWorkArea * current_work_area_;
248 GuiWorkArea * current_main_work_area_;
249 QSplitter * splitter_;
250 QStackedWidget * stack_widget_;
251 BackgroundWidget * bg_widget_;
253 ToolbarMap toolbars_;
254 /// The main layout box.
256 * \warning Don't Delete! The layout box is actually owned by
257 * whichever toolbar contains it. All the GuiView class needs is a
258 * means of accessing it.
260 * FIXME: replace that with a proper model so that we are not limited
261 * to only one dialog.
263 GuiLayoutBox * layout_;
266 map<string, Inset *> open_insets_;
269 map<string, DialogPtr> dialogs_;
271 unsigned int smallIconSize;
272 unsigned int normalIconSize;
273 unsigned int bigIconSize;
275 QTimer statusbar_timer_;
276 /// auto-saving of buffers
277 Timeout autosave_timeout_;
278 /// flag against a race condition due to multiclicks, see bug #1119
282 TocModels toc_models_;
286 GuiView::GuiView(int id)
287 : d(*new GuiViewPrivate), id_(id), closing_(false)
289 // GuiToolbars *must* be initialised before the menu bar.
290 normalSizedIcons(); // at least on Mac the default is 32 otherwise, which is huge
293 // set ourself as the current view. This is needed for the menu bar
294 // filling, at least for the static special menu item on Mac. Otherwise
295 // they are greyed out.
296 theLyXFunc().setLyXView(this);
298 // Fill up the menu bar.
299 guiApp->menus().fillMenuBar(menuBar(), this, true);
301 setCentralWidget(d.stack_widget_);
303 // Start autosave timer
304 if (lyxrc.autosave) {
305 d.autosave_timeout_.timeout.connect(boost::bind(&GuiView::autoSave, this));
306 d.autosave_timeout_.setTimeout(lyxrc.autosave * 1000);
307 d.autosave_timeout_.start();
309 connect(&d.statusbar_timer_, SIGNAL(timeout()),
310 this, SLOT(clearMessage()));
312 // We don't want to keep the window in memory if it is closed.
313 setAttribute(Qt::WA_DeleteOnClose, true);
315 #if (!defined(Q_WS_WIN) && !defined(Q_WS_MACX))
316 // assign an icon to main form. We do not do it under Qt/Win or Qt/Mac,
317 // since the icon is provided in the application bundle.
318 setWindowIcon(QPixmap(":/images/lyx.png"));
322 setAcceptDrops(true);
324 statusBar()->setSizeGripEnabled(true);
326 // Forbid too small unresizable window because it can happen
327 // with some window manager under X11.
328 setMinimumSize(300, 200);
330 if (lyxrc.allow_geometry_session) {
331 // Now take care of session management.
336 // no session handling, default to a sane size.
337 setGeometry(50, 50, 690, 510);
340 // clear session data if any.
342 settings.remove("views");
352 void GuiView::saveLayout() const
355 settings.beginGroup("views");
356 settings.beginGroup(QString::number(id_));
358 settings.setValue("pos", pos());
359 settings.setValue("size", size());
361 settings.setValue("geometry", saveGeometry());
363 settings.setValue("layout", saveState(0));
364 settings.setValue("icon_size", iconSize());
368 bool GuiView::restoreLayout()
371 settings.beginGroup("views");
372 settings.beginGroup(QString::number(id_));
373 QString const icon_key = "icon_size";
374 if (!settings.contains(icon_key))
377 setIconSize(settings.value(icon_key).toSize());
379 QPoint pos = settings.value("pos", QPoint(50, 50)).toPoint();
380 QSize size = settings.value("size", QSize(690, 510)).toSize();
384 if (!restoreGeometry(settings.value("geometry").toByteArray()))
385 setGeometry(50, 50, 690, 510);
387 // Make sure layout is correctly oriented.
388 setLayoutDirection(qApp->layoutDirection());
390 // Allow the toc and view-source dock widget to be restored if needed.
391 findOrBuild("toc", true);
392 findOrBuild("view-source", true);
394 if (!restoreState(settings.value("layout").toByteArray(), 0))
401 GuiToolbar * GuiView::toolbar(string const & name)
403 ToolbarMap::iterator it = d.toolbars_.find(name);
404 if (it != d.toolbars_.end())
407 LYXERR(Debug::GUI, "Toolbar::display: no toolbar named " << name);
408 message(bformat(_("Unknown toolbar \"%1$s\""), from_utf8(name)));
413 void GuiView::constructToolbars()
415 ToolbarMap::iterator it = d.toolbars_.begin();
416 for (; it != d.toolbars_.end(); ++it)
421 // extracts the toolbars from the backend
422 Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
423 Toolbars::Infos::iterator end = guiApp->toolbars().end();
424 for (; cit != end; ++cit)
425 d.toolbars_[cit->name] = new GuiToolbar(*cit, *this);
429 void GuiView::initToolbars()
431 // extracts the toolbars from the backend
432 Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
433 Toolbars::Infos::iterator end = guiApp->toolbars().end();
434 for (; cit != end; ++cit) {
435 GuiToolbar * tb = toolbar(cit->name);
438 int const visibility = guiApp->toolbars().defaultVisibility(cit->name);
440 tb->setVisible(false);
441 tb->setVisibility(visibility);
443 if (visibility & Toolbars::TOP) {
445 addToolBarBreak(Qt::TopToolBarArea);
446 addToolBar(Qt::TopToolBarArea, tb);
449 if (visibility & Toolbars::BOTTOM) {
450 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
451 #if (QT_VERSION >= 0x040202)
452 addToolBarBreak(Qt::BottomToolBarArea);
454 addToolBar(Qt::BottomToolBarArea, tb);
457 if (visibility & Toolbars::LEFT) {
458 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
459 #if (QT_VERSION >= 0x040202)
460 addToolBarBreak(Qt::LeftToolBarArea);
462 addToolBar(Qt::LeftToolBarArea, tb);
465 if (visibility & Toolbars::RIGHT) {
466 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
467 #if (QT_VERSION >= 0x040202)
468 addToolBarBreak(Qt::RightToolBarArea);
470 addToolBar(Qt::RightToolBarArea, tb);
473 if (visibility & Toolbars::ON)
474 tb->setVisible(true);
479 TocModels & GuiView::tocModels()
481 return d.toc_models_;
485 void GuiView::setFocus()
487 LYXERR(Debug::DEBUG, "GuiView::setFocus()" << this);
488 // Make sure LyXFunc points to the correct view.
489 guiApp->setCurrentView(this);
490 theLyXFunc().setLyXView(this);
491 QMainWindow::setFocus();
492 if (d.current_work_area_)
493 d.current_work_area_->setFocus();
497 QMenu * GuiView::createPopupMenu()
499 return d.toolBarPopup(this);
503 void GuiView::showEvent(QShowEvent * e)
505 LYXERR(Debug::GUI, "Passed Geometry "
506 << size().height() << "x" << size().width()
507 << "+" << pos().x() << "+" << pos().y());
509 if (d.splitter_->count() == 0)
510 // No work area, switch to the background widget.
513 QMainWindow::showEvent(e);
517 /** Destroy only all tabbed WorkAreas. Destruction of other WorkAreas
518 ** is responsibility of the container (e.g., dialog)
520 void GuiView::closeEvent(QCloseEvent * close_event)
522 LYXERR(Debug::DEBUG, "GuiView::closeEvent()");
525 // it can happen that this event arrives without selecting the view,
526 // e.g. when clicking the close button on a background window.
528 setCurrentWorkArea(currentMainWorkArea());
529 while (GuiWorkArea * wa = currentMainWorkArea()) {
530 Buffer * b = &wa->bufferView().buffer();
532 // This is a child document, just close the tab after saving
533 // but keep the file loaded.
534 if (!saveBuffer(*b)) {
536 close_event->ignore();
543 QList<int> const ids = guiApp->viewIds();
544 for (int i = 0; i != ids.size(); ++i) {
547 if (guiApp->view(ids[i]).workArea(*b)) {
548 // FIXME 1: should we put an alert box here that the buffer
549 // is viewed elsewhere?
550 // FIXME 2: should we try to save this buffer in any case?
553 // This buffer is also opened in another view, so
554 // close the associated work area...
556 // ... but don't close the buffer.
561 // closeBuffer() needs buffer workArea still alive and set as currrent one, and destroys it
562 if (b && !closeBuffer(*b, true)) {
564 close_event->ignore();
569 // Make sure that nothing will use this close to be closed View.
570 guiApp->unregisterView(this);
572 if (isFullScreen()) {
573 // Switch off fullscreen before closing.
578 // Make sure the timer time out will not trigger a statusbar update.
579 d.statusbar_timer_.stop();
581 // Saving fullscreen requires additional tweaks in the toolbar code.
582 // It wouldn't also work under linux natively.
583 if (lyxrc.allow_geometry_session) {
584 // Save this window geometry and layout.
586 // Then the toolbar private states.
587 ToolbarMap::iterator end = d.toolbars_.end();
588 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
589 it->second->saveSession();
590 // Now take care of all other dialogs:
591 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
592 for (; it!= d.dialogs_.end(); ++it)
593 it->second->saveSession();
596 close_event->accept();
600 void GuiView::dragEnterEvent(QDragEnterEvent * event)
602 if (event->mimeData()->hasUrls())
604 /// \todo Ask lyx-devel is this is enough:
605 /// if (event->mimeData()->hasFormat("text/plain"))
606 /// event->acceptProposedAction();
610 void GuiView::dropEvent(QDropEvent * event)
612 QList<QUrl> files = event->mimeData()->urls();
616 LYXERR(Debug::GUI, "GuiView::dropEvent: got URLs!");
617 for (int i = 0; i != files.size(); ++i) {
618 string const file = os::internal_path(fromqstr(
619 files.at(i).toLocalFile()));
621 // Asynchronously post the event. DropEvent usually come
622 // from the BufferView. But reloading a file might close
623 // the BufferView from within its own event handler.
624 guiApp->dispatchDelayed(FuncRequest(LFUN_FILE_OPEN, file));
631 void GuiView::message(docstring const & str)
633 if (ForkedProcess::iAmAChild())
636 statusBar()->showMessage(toqstr(str));
637 d.statusbar_timer_.stop();
638 d.statusbar_timer_.start(3000);
642 void GuiView::smallSizedIcons()
644 setIconSize(QSize(d.smallIconSize, d.smallIconSize));
648 void GuiView::normalSizedIcons()
650 setIconSize(QSize(d.normalIconSize, d.normalIconSize));
654 void GuiView::bigSizedIcons()
656 setIconSize(QSize(d.bigIconSize, d.bigIconSize));
660 void GuiView::clearMessage()
664 theLyXFunc().setLyXView(this);
665 statusBar()->showMessage(toqstr(theLyXFunc().viewStatusMessage()));
666 d.statusbar_timer_.stop();
670 void GuiView::updateWindowTitle(GuiWorkArea * wa)
672 if (wa != d.current_work_area_)
674 setWindowTitle(qt_("LyX: ") + wa->windowTitle());
675 setWindowIconText(wa->windowIconText());
679 void GuiView::on_currentWorkAreaChanged(GuiWorkArea * wa)
682 disconnectBufferView();
683 connectBufferView(wa->bufferView());
684 connectBuffer(wa->bufferView().buffer());
685 d.current_work_area_ = wa;
686 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
687 this, SLOT(updateWindowTitle(GuiWorkArea *)));
688 updateWindowTitle(wa);
692 // The document settings needs to be reinitialised.
693 updateDialog("document", "");
695 // Buffer-dependent dialogs must be updated. This is done here because
696 // some dialogs require buffer()->text.
701 void GuiView::on_lastWorkAreaRemoved()
704 // We already are in a close event. Nothing more to do.
707 if (d.splitter_->count() > 1)
708 // We have a splitter so don't close anything.
711 // Reset and updates the dialogs.
712 d.toc_models_.reset(0);
713 updateDialog("document", "");
716 resetWindowTitleAndIconText();
718 if (lyxrc.open_buffers_in_tabs)
719 // Nothing more to do, the window should stay open.
722 if (guiApp->viewIds().size() > 1) {
728 // On Mac we also close the last window because the application stay
729 // resident in memory. On other platforms we don't close the last
730 // window because this would quit the application.
736 void GuiView::updateStatusBar()
738 // let the user see the explicit message
739 if (d.statusbar_timer_.isActive())
742 theLyXFunc().setLyXView(this);
743 statusBar()->showMessage(toqstr(theLyXFunc().viewStatusMessage()));
747 bool GuiView::hasFocus() const
749 return qApp->activeWindow() == this;
753 bool GuiView::event(QEvent * e)
757 // Useful debug code:
758 //case QEvent::ActivationChange:
759 //case QEvent::WindowDeactivate:
760 //case QEvent::Paint:
761 //case QEvent::Enter:
762 //case QEvent::Leave:
763 //case QEvent::HoverEnter:
764 //case QEvent::HoverLeave:
765 //case QEvent::HoverMove:
766 //case QEvent::StatusTip:
767 //case QEvent::DragEnter:
768 //case QEvent::DragLeave:
772 case QEvent::WindowActivate: {
773 if (this == guiApp->currentView()) {
775 return QMainWindow::event(e);
777 guiApp->setCurrentView(this);
778 theLyXFunc().setLyXView(this);
779 if (d.current_work_area_) {
780 BufferView & bv = d.current_work_area_->bufferView();
781 connectBufferView(bv);
782 connectBuffer(bv.buffer());
783 // The document structure, name and dialogs might have
784 // changed in another view.
786 // The document settings needs to be reinitialised.
787 updateDialog("document", "");
790 resetWindowTitleAndIconText();
793 return QMainWindow::event(e);
796 case QEvent::ShortcutOverride: {
800 if (isFullScreen() && menuBar()->isHidden()) {
801 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
802 // FIXME: we should also try to detect special LyX shortcut such as
803 // Alt-P and Alt-M. Right now there is a hack in
804 // GuiWorkArea::processKeySym() that hides again the menubar for
806 if (ke->modifiers() & Qt::AltModifier && ke->key() != Qt::Key_Alt) {
808 return QMainWindow::event(e);
813 if (d.current_work_area_)
814 // Nothing special to do.
815 return QMainWindow::event(e);
817 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
818 // Let Qt handle menu access and the Tab keys to navigate keys to navigate
820 if (ke->modifiers() & Qt::AltModifier || ke->key() == Qt::Key_Tab
821 || ke->key() == Qt::Key_Backtab)
822 return QMainWindow::event(e);
824 // Allow processing of shortcuts that are allowed even when no Buffer
826 theLyXFunc().setLyXView(this);
828 setKeySymbol(&sym, ke);
829 theLyXFunc().processKeySym(sym, q_key_state(ke->modifiers()));
835 return QMainWindow::event(e);
839 void GuiView::resetWindowTitleAndIconText()
841 setWindowTitle(qt_("LyX"));
842 setWindowIconText(qt_("LyX"));
845 bool GuiView::focusNextPrevChild(bool /*next*/)
852 void GuiView::setBusy(bool busy)
854 if (d.current_work_area_) {
855 d.current_work_area_->setUpdatesEnabled(!busy);
857 d.current_work_area_->stopBlinkingCursor();
859 d.current_work_area_->startBlinkingCursor();
863 QApplication::setOverrideCursor(Qt::WaitCursor);
865 QApplication::restoreOverrideCursor();
869 GuiWorkArea * GuiView::workArea(Buffer & buffer)
871 if (currentWorkArea()
872 && ¤tWorkArea()->bufferView().buffer() == &buffer)
873 return (GuiWorkArea *) currentWorkArea();
874 if (TabWorkArea * twa = d.currentTabWorkArea())
875 return twa->workArea(buffer);
880 GuiWorkArea * GuiView::addWorkArea(Buffer & buffer)
882 // Automatically create a TabWorkArea if there are none yet.
883 TabWorkArea * tab_widget = d.splitter_->count()
884 ? d.currentTabWorkArea() : addTabWorkArea();
885 return tab_widget->addWorkArea(buffer, *this);
889 TabWorkArea * GuiView::addTabWorkArea()
891 TabWorkArea * twa = new TabWorkArea;
892 QObject::connect(twa, SIGNAL(currentWorkAreaChanged(GuiWorkArea *)),
893 this, SLOT(on_currentWorkAreaChanged(GuiWorkArea *)));
894 QObject::connect(twa, SIGNAL(lastWorkAreaRemoved()),
895 this, SLOT(on_lastWorkAreaRemoved()));
897 d.splitter_->addWidget(twa);
898 d.stack_widget_->setCurrentWidget(d.splitter_);
903 GuiWorkArea const * GuiView::currentWorkArea() const
905 return d.current_work_area_;
909 GuiWorkArea * GuiView::currentWorkArea()
911 return d.current_work_area_;
915 GuiWorkArea const * GuiView::currentMainWorkArea() const
917 if (d.currentTabWorkArea() == NULL)
919 return d.currentTabWorkArea()->currentWorkArea();
923 GuiWorkArea * GuiView::currentMainWorkArea()
925 if (d.currentTabWorkArea() == NULL)
927 return d.currentTabWorkArea()->currentWorkArea();
931 void GuiView::setCurrentWorkArea(GuiWorkArea * wa)
933 LYXERR(Debug::DEBUG, "Setting current wa: " << wa << endl);
935 d.current_work_area_ = NULL;
939 GuiWorkArea * old_gwa = theGuiApp()->currentView()->currentWorkArea();
943 theGuiApp()->setCurrentView(this);
944 d.current_work_area_ = wa;
945 for (int i = 0; i != d.splitter_->count(); ++i) {
946 if (d.tabWorkArea(i)->setCurrentWorkArea(wa)) {
947 //if (d.current_main_work_area_)
948 // d.current_main_work_area_->setFrameStyle(QFrame::NoFrame);
949 d.current_main_work_area_ = wa;
950 //d.current_main_work_area_->setFrameStyle(QFrame::Box | QFrame::Plain);
951 //d.current_main_work_area_->setLineWidth(2);
952 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() << ", Current main wa: " << currentMainWorkArea());
956 LYXERR(Debug::DEBUG, "This is not a tabbed wa");
957 on_currentWorkAreaChanged(wa);
958 BufferView & bv = wa->bufferView();
959 bv.cursor().fixIfBroken();
961 wa->setUpdatesEnabled(true);
962 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() << ", Current main wa: " << currentMainWorkArea());
966 void GuiView::removeWorkArea(GuiWorkArea * wa)
969 if (wa == d.current_work_area_) {
971 disconnectBufferView();
972 d.current_work_area_ = 0;
973 d.current_main_work_area_ = 0;
976 bool found_twa = false;
977 for (int i = 0; i != d.splitter_->count(); ++i) {
978 TabWorkArea * twa = d.tabWorkArea(i);
979 if (twa->removeWorkArea(wa)) {
980 // Found in this tab group, and deleted the GuiWorkArea.
982 if (twa->count() != 0) {
983 if (d.current_work_area_ == 0)
984 // This means that we are closing the current GuiWorkArea, so
985 // switch to the next GuiWorkArea in the found TabWorkArea.
986 setCurrentWorkArea(twa->currentWorkArea());
988 // No more WorkAreas in this tab group, so delete it.
995 // It is not a tabbed work area (i.e., the search work area), so it
996 // should be deleted by other means.
997 LASSERT(found_twa, /* */);
999 if (d.current_work_area_ == 0) {
1000 if (d.splitter_->count() != 0) {
1001 TabWorkArea * twa = d.currentTabWorkArea();
1002 setCurrentWorkArea(twa->currentWorkArea());
1004 // No more work areas, switch to the background widget.
1005 setCurrentWorkArea(0);
1011 void GuiView::setLayoutDialog(GuiLayoutBox * layout)
1017 void GuiView::updateLayoutList()
1020 d.layout_->updateContents(false);
1024 void GuiView::updateToolbars()
1026 ToolbarMap::iterator end = d.toolbars_.end();
1027 if (d.current_work_area_) {
1029 d.current_work_area_->bufferView().cursor().inMathed();
1031 lyx::getStatus(FuncRequest(LFUN_LAYOUT_TABULAR)).enabled();
1033 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).enabled() &&
1034 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).onoff(true);
1035 bool const mathmacrotemplate =
1036 lyx::getStatus(FuncRequest(LFUN_IN_MATHMACROTEMPLATE)).enabled();
1038 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1039 it->second->update(math, table, review, mathmacrotemplate);
1041 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1042 it->second->update(false, false, false, false);
1046 Buffer * GuiView::buffer()
1048 if (d.current_work_area_)
1049 return &d.current_work_area_->bufferView().buffer();
1054 Buffer const * GuiView::buffer() const
1056 if (d.current_work_area_)
1057 return &d.current_work_area_->bufferView().buffer();
1062 void GuiView::setBuffer(Buffer * newBuffer)
1064 LYXERR(Debug::DEBUG, "Setting buffer: " << newBuffer << std::endl);
1065 LASSERT(newBuffer, return);
1068 GuiWorkArea * wa = workArea(*newBuffer);
1070 newBuffer->masterBuffer()->updateLabels();
1071 wa = addWorkArea(*newBuffer);
1073 //Disconnect the old buffer...there's no new one.
1076 connectBuffer(*newBuffer);
1077 connectBufferView(wa->bufferView());
1078 setCurrentWorkArea(wa);
1084 void GuiView::connectBuffer(Buffer & buf)
1086 buf.setGuiDelegate(this);
1090 void GuiView::disconnectBuffer()
1092 if (d.current_work_area_)
1093 d.current_work_area_->bufferView().setGuiDelegate(0);
1097 void GuiView::connectBufferView(BufferView & bv)
1099 bv.setGuiDelegate(this);
1103 void GuiView::disconnectBufferView()
1105 if (d.current_work_area_)
1106 d.current_work_area_->bufferView().setGuiDelegate(0);
1110 void GuiView::errors(string const & error_type)
1112 ErrorList & el = buffer()->errorList(error_type);
1114 showDialog("errorlist", error_type);
1118 void GuiView::updateTocItem(std::string const & type, DocIterator const & dit)
1120 d.toc_models_.updateItem(toqstr(type), dit);
1124 void GuiView::structureChanged()
1126 d.toc_models_.reset(view());
1127 // Navigator needs more than a simple update in this case. It needs to be
1129 updateDialog("toc", "");
1133 void GuiView::updateDialog(string const & name, string const & data)
1135 if (!isDialogVisible(name))
1138 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
1139 if (it == d.dialogs_.end())
1142 Dialog * const dialog = it->second.get();
1143 if (dialog->isVisibleView())
1144 dialog->initialiseParams(data);
1148 BufferView * GuiView::view()
1150 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1154 void GuiView::autoSave()
1156 LYXERR(Debug::INFO, "Running autoSave()");
1159 view()->buffer().autoSave();
1163 void GuiView::resetAutosaveTimers()
1166 d.autosave_timeout_.restart();
1170 bool GuiView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1173 Buffer * buf = buffer();
1175 /* In LyX/Mac, when a dialog is open, the menus of the
1176 application can still be accessed without giving focus to
1177 the main window. In this case, we want to disable the menu
1178 entries that are buffer-related.
1180 Note that this code is not perfect, as bug 1941 attests:
1181 http://bugzilla.lyx.org/show_bug.cgi?id=1941#c4
1183 if (cmd.origin == FuncRequest::MENU && !hasFocus())
1186 switch(cmd.action) {
1187 case LFUN_BUFFER_WRITE:
1188 enable = buf && (buf->isUnnamed() || !buf->isClean());
1191 case LFUN_BUFFER_WRITE_AS:
1195 case LFUN_SPLIT_VIEW:
1196 if (cmd.getArg(0) == "vertical")
1197 enable = buf && (d.splitter_->count() == 1 ||
1198 d.splitter_->orientation() == Qt::Vertical);
1200 enable = buf && (d.splitter_->count() == 1 ||
1201 d.splitter_->orientation() == Qt::Horizontal);
1204 case LFUN_CLOSE_TAB_GROUP:
1205 enable = d.currentTabWorkArea();
1208 case LFUN_TOOLBAR_TOGGLE:
1209 if (GuiToolbar * t = toolbar(cmd.getArg(0)))
1210 flag.setOnOff(t->isVisible());
1213 case LFUN_UI_TOGGLE:
1214 flag.setOnOff(isFullScreen());
1217 case LFUN_DIALOG_TOGGLE:
1218 flag.setOnOff(isDialogVisible(cmd.getArg(0)));
1219 // fall through to set "enable"
1220 case LFUN_DIALOG_SHOW: {
1221 string const name = cmd.getArg(0);
1223 enable = name == "aboutlyx"
1224 || name == "file" //FIXME: should be removed.
1226 || name == "texinfo";
1227 else if (name == "print")
1228 enable = buf->isExportable("dvi")
1229 && lyxrc.print_command != "none";
1230 else if (name == "character") {
1234 InsetCode ic = view()->cursor().inset().lyxCode();
1235 enable = ic != ERT_CODE && ic != LISTINGS_CODE;
1238 else if (name == "symbols") {
1239 if (!view() || view()->cursor().inMathed())
1242 InsetCode ic = view()->cursor().inset().lyxCode();
1243 enable = ic != ERT_CODE && ic != LISTINGS_CODE;
1246 else if (name == "latexlog")
1247 enable = FileName(buf->logName()).isReadableFile();
1248 else if (name == "spellchecker")
1249 #if defined (USE_ASPELL)
1250 enable = !buf->isReadonly();
1254 else if (name == "vclog")
1255 enable = buf->lyxvc().inUse();
1259 case LFUN_DIALOG_UPDATE: {
1260 string const name = cmd.getArg(0);
1262 enable = name == "prefs";
1266 case LFUN_INSET_APPLY: {
1267 string const name = cmd.getArg(0);
1268 Inset * inset = getOpenInset(name);
1270 FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument());
1272 if (!inset->getStatus(view()->cursor(), fr, fs)) {
1273 // Every inset is supposed to handle this
1274 LASSERT(false, break);
1278 FuncRequest fr(LFUN_INSET_INSERT, cmd.argument());
1279 flag |= lyx::getStatus(fr);
1281 enable = flag.enabled();
1285 case LFUN_COMPLETION_INLINE:
1286 if (!d.current_work_area_
1287 || !d.current_work_area_->completer().inlinePossible(view()->cursor()))
1291 case LFUN_COMPLETION_POPUP:
1292 if (!d.current_work_area_
1293 || !d.current_work_area_->completer().popupPossible(view()->cursor()))
1297 case LFUN_COMPLETION_COMPLETE:
1298 if (!d.current_work_area_
1299 || !d.current_work_area_->completer().inlinePossible(view()->cursor()))
1303 case LFUN_COMPLETION_ACCEPT:
1304 if (!d.current_work_area_
1305 || (!d.current_work_area_->completer().popupVisible()
1306 && !d.current_work_area_->completer().inlineVisible()
1307 && !d.current_work_area_->completer().completionAvailable()))
1311 case LFUN_COMPLETION_CANCEL:
1312 if (!d.current_work_area_
1313 || (!d.current_work_area_->completer().popupVisible()
1314 && !d.current_work_area_->completer().inlineVisible()))
1323 flag.setEnabled(false);
1329 static FileName selectTemplateFile()
1331 FileDialog dlg(qt_("Select template file"));
1332 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1333 dlg.setButton1(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
1335 FileDialog::Result result = dlg.open(toqstr(lyxrc.template_path),
1336 QStringList(qt_("LyX Documents (*.lyx)")));
1338 if (result.first == FileDialog::Later)
1340 if (result.second.isEmpty())
1342 return FileName(fromqstr(result.second));
1346 Buffer * GuiView::loadDocument(FileName const & filename, bool tolastfiles)
1350 Buffer * newBuffer = checkAndLoadLyXFile(filename);
1353 message(_("Document not loaded."));
1358 setBuffer(newBuffer);
1360 // scroll to the position when the file was last closed
1361 if (lyxrc.use_lastfilepos) {
1362 LastFilePosSection::FilePos filepos =
1363 theSession().lastFilePos().load(filename);
1364 view()->moveToPosition(filepos.pit, filepos.pos, 0, 0);
1368 theSession().lastFiles().add(filename);
1375 void GuiView::openDocument(string const & fname)
1377 string initpath = lyxrc.document_path;
1380 string const trypath = buffer()->filePath();
1381 // If directory is writeable, use this as default.
1382 if (FileName(trypath).isDirWritable())
1388 if (fname.empty()) {
1389 FileDialog dlg(qt_("Select document to open"), LFUN_FILE_OPEN);
1390 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1391 dlg.setButton2(qt_("Examples|#E#e"),
1392 toqstr(addPath(package().system_support().absFilename(), "examples")));
1394 QStringList filter(qt_("LyX Documents (*.lyx)"));
1395 filter << qt_("LyX-1.3.x Documents (*.lyx13)")
1396 << qt_("LyX-1.4.x Documents (*.lyx14)")
1397 << qt_("LyX-1.5.x Documents (*.lyx15)")
1398 << qt_("LyX-1.6.x Documents (*.lyx16)");
1399 FileDialog::Result result =
1400 dlg.open(toqstr(initpath), filter);
1402 if (result.first == FileDialog::Later)
1405 filename = fromqstr(result.second);
1407 // check selected filename
1408 if (filename.empty()) {
1409 message(_("Canceled."));
1415 // get absolute path of file and add ".lyx" to the filename if
1417 FileName const fullname =
1418 fileSearch(string(), filename, "lyx", support::may_not_exist);
1419 if (!fullname.empty())
1420 filename = fullname.absFilename();
1422 if (!fullname.onlyPath().isDirectory()) {
1423 Alert::warning(_("Invalid filename"),
1424 bformat(_("The directory in the given path\n%1$s\ndoes not exists."),
1425 from_utf8(fullname.absFilename())));
1428 // if the file doesn't exist, let the user create one
1429 if (!fullname.exists()) {
1430 // the user specifically chose this name. Believe him.
1431 Buffer * const b = newFile(filename, string(), true);
1437 docstring const disp_fn = makeDisplayPath(filename);
1438 message(bformat(_("Opening document %1$s..."), disp_fn));
1441 Buffer * buf = loadDocument(fullname);
1443 buf->updateLabels();
1445 buf->errors("Parse");
1446 str2 = bformat(_("Document %1$s opened."), disp_fn);
1447 if (buf->lyxvc().inUse())
1448 str2 += " " + from_utf8(buf->lyxvc().versionString()) +
1449 " " + _("Version control detected.");
1451 str2 = bformat(_("Could not open document %1$s"), disp_fn);
1456 // FIXME: clean that
1457 static bool import(GuiView * lv, FileName const & filename,
1458 string const & format, ErrorList & errorList)
1460 FileName const lyxfile(support::changeExtension(filename.absFilename(), ".lyx"));
1462 string loader_format;
1463 vector<string> loaders = theConverters().loaders();
1464 if (find(loaders.begin(), loaders.end(), format) == loaders.end()) {
1465 for (vector<string>::const_iterator it = loaders.begin();
1466 it != loaders.end(); ++it) {
1467 if (!theConverters().isReachable(format, *it))
1470 string const tofile =
1471 support::changeExtension(filename.absFilename(),
1472 formats.extension(*it));
1473 if (!theConverters().convert(0, filename, FileName(tofile),
1474 filename, format, *it, errorList))
1476 loader_format = *it;
1479 if (loader_format.empty()) {
1480 frontend::Alert::error(_("Couldn't import file"),
1481 bformat(_("No information for importing the format %1$s."),
1482 formats.prettyName(format)));
1486 loader_format = format;
1488 if (loader_format == "lyx") {
1489 Buffer * buf = lv->loadDocument(lyxfile);
1492 buf->updateLabels();
1494 buf->errors("Parse");
1496 Buffer * const b = newFile(lyxfile.absFilename(), string(), true);
1500 bool as_paragraphs = loader_format == "textparagraph";
1501 string filename2 = (loader_format == format) ? filename.absFilename()
1502 : support::changeExtension(filename.absFilename(),
1503 formats.extension(loader_format));
1504 lv->view()->insertPlaintextFile(FileName(filename2), as_paragraphs);
1505 theLyXFunc().setLyXView(lv);
1506 lyx::dispatch(FuncRequest(LFUN_MARK_OFF));
1513 void GuiView::importDocument(string const & argument)
1516 string filename = split(argument, format, ' ');
1518 LYXERR(Debug::INFO, format << " file: " << filename);
1520 // need user interaction
1521 if (filename.empty()) {
1522 string initpath = lyxrc.document_path;
1524 Buffer const * buf = buffer();
1526 string const trypath = buf->filePath();
1527 // If directory is writeable, use this as default.
1528 if (FileName(trypath).isDirWritable())
1532 docstring const text = bformat(_("Select %1$s file to import"),
1533 formats.prettyName(format));
1535 FileDialog dlg(toqstr(text), LFUN_BUFFER_IMPORT);
1536 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1537 dlg.setButton2(qt_("Examples|#E#e"),
1538 toqstr(addPath(package().system_support().absFilename(), "examples")));
1540 docstring filter = formats.prettyName(format);
1543 filter += from_utf8(formats.extension(format));
1546 FileDialog::Result result =
1547 dlg.open(toqstr(initpath), fileFilters(toqstr(filter)));
1549 if (result.first == FileDialog::Later)
1552 filename = fromqstr(result.second);
1554 // check selected filename
1555 if (filename.empty())
1556 message(_("Canceled."));
1559 if (filename.empty())
1562 // get absolute path of file
1563 FileName const fullname(support::makeAbsPath(filename));
1565 FileName const lyxfile(support::changeExtension(fullname.absFilename(), ".lyx"));
1567 // Check if the document already is open
1568 Buffer * buf = theBufferList().getBuffer(lyxfile);
1571 if (!closeBuffer()) {
1572 message(_("Canceled."));
1577 docstring const displaypath = makeDisplayPath(lyxfile.absFilename(), 30);
1579 // if the file exists already, and we didn't do
1580 // -i lyx thefile.lyx, warn
1581 if (lyxfile.exists() && fullname != lyxfile) {
1583 docstring text = bformat(_("The document %1$s already exists.\n\n"
1584 "Do you want to overwrite that document?"), displaypath);
1585 int const ret = Alert::prompt(_("Overwrite document?"),
1586 text, 0, 1, _("&Overwrite"), _("&Cancel"));
1589 message(_("Canceled."));
1594 message(bformat(_("Importing %1$s..."), displaypath));
1595 ErrorList errorList;
1596 if (import(this, fullname, format, errorList))
1597 message(_("imported."));
1599 message(_("file not imported!"));
1601 // FIXME (Abdel 12/08/06): Is there a need to display the error list here?
1605 void GuiView::newDocument(string const & filename, bool from_template)
1607 FileName initpath(lyxrc.document_path);
1608 Buffer * buf = buffer();
1610 FileName const trypath(buf->filePath());
1611 // If directory is writeable, use this as default.
1612 if (trypath.isDirWritable())
1616 string templatefile = from_template ?
1617 selectTemplateFile().absFilename() : string();
1619 if (filename.empty())
1620 b = newUnnamedFile(templatefile, initpath);
1622 b = newFile(filename, templatefile, true);
1627 // If no new document could be created, it is unsure
1628 // whether there is a valid BufferView.
1630 // Ensure the cursor is correctly positioned on screen.
1631 view()->showCursor();
1635 void GuiView::insertLyXFile(docstring const & fname)
1637 BufferView * bv = view();
1642 FileName filename(to_utf8(fname));
1644 if (!filename.empty()) {
1645 bv->insertLyXFile(filename);
1649 // Launch a file browser
1651 string initpath = lyxrc.document_path;
1652 string const trypath = bv->buffer().filePath();
1653 // If directory is writeable, use this as default.
1654 if (FileName(trypath).isDirWritable())
1658 FileDialog dlg(qt_("Select LyX document to insert"), LFUN_FILE_INSERT);
1659 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1660 dlg.setButton2(qt_("Examples|#E#e"),
1661 toqstr(addPath(package().system_support().absFilename(),
1664 FileDialog::Result result = dlg.open(toqstr(initpath),
1665 QStringList(qt_("LyX Documents (*.lyx)")));
1667 if (result.first == FileDialog::Later)
1671 filename.set(fromqstr(result.second));
1673 // check selected filename
1674 if (filename.empty()) {
1675 // emit message signal.
1676 message(_("Canceled."));
1680 bv->insertLyXFile(filename);
1684 void GuiView::insertPlaintextFile(docstring const & fname,
1687 BufferView * bv = view();
1692 FileName filename(to_utf8(fname));
1694 if (!filename.empty()) {
1695 bv->insertPlaintextFile(filename, asParagraph);
1699 FileDialog dlg(qt_("Select file to insert"), (asParagraph ?
1700 LFUN_FILE_INSERT_PLAINTEXT_PARA : LFUN_FILE_INSERT_PLAINTEXT));
1702 FileDialog::Result result = dlg.open(toqstr(bv->buffer().filePath()),
1705 if (result.first == FileDialog::Later)
1709 filename.set(fromqstr(result.second));
1711 // check selected filename
1712 if (filename.empty()) {
1713 // emit message signal.
1714 message(_("Canceled."));
1718 bv->insertPlaintextFile(filename, asParagraph);
1722 bool GuiView::renameBuffer(Buffer & b, docstring const & newname)
1724 FileName fname = b.fileName();
1725 FileName const oldname = fname;
1727 if (!newname.empty()) {
1729 fname = support::makeAbsPath(to_utf8(newname), oldname.onlyPath().absFilename());
1731 // Switch to this Buffer.
1734 /// No argument? Ask user through dialog.
1736 FileDialog dlg(qt_("Choose a filename to save document as"),
1737 LFUN_BUFFER_WRITE_AS);
1738 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1739 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
1741 if (!isLyXFilename(fname.absFilename()))
1742 fname.changeExtension(".lyx");
1744 FileDialog::Result result =
1745 dlg.save(toqstr(fname.onlyPath().absFilename()),
1746 QStringList(qt_("LyX Documents (*.lyx)")),
1747 toqstr(fname.onlyFileName()));
1749 if (result.first == FileDialog::Later)
1752 fname.set(fromqstr(result.second));
1757 if (!isLyXFilename(fname.absFilename()))
1758 fname.changeExtension(".lyx");
1761 if (FileName(fname).exists()) {
1762 docstring const file = makeDisplayPath(fname.absFilename(), 30);
1763 docstring text = bformat(_("The document %1$s already "
1764 "exists.\n\nDo you want to "
1765 "overwrite that document?"),
1767 int const ret = Alert::prompt(_("Overwrite document?"),
1768 text, 0, 2, _("&Overwrite"), _("&Rename"), _("&Cancel"));
1771 case 1: return renameBuffer(b, docstring());
1772 case 2: return false;
1776 // Ok, change the name of the buffer
1777 b.setFileName(fname.absFilename());
1779 bool unnamed = b.isUnnamed();
1780 b.setUnnamed(false);
1781 b.saveCheckSum(fname);
1783 if (!saveBuffer(b)) {
1784 b.setFileName(oldname.absFilename());
1785 b.setUnnamed(unnamed);
1786 b.saveCheckSum(oldname);
1794 bool GuiView::saveBuffer(Buffer & b)
1796 if (workArea(b) && workArea(b)->inDialogMode())
1800 return renameBuffer(b, docstring());
1803 theSession().lastFiles().add(b.fileName());
1807 // Switch to this Buffer.
1810 // FIXME: we don't tell the user *WHY* the save failed !!
1811 docstring const file = makeDisplayPath(b.absFileName(), 30);
1812 docstring text = bformat(_("The document %1$s could not be saved.\n\n"
1813 "Do you want to rename the document and "
1814 "try again?"), file);
1815 int const ret = Alert::prompt(_("Rename and save?"),
1816 text, 0, 2, _("&Rename"), _("&Retry"), _("&Cancel"));
1819 if (!renameBuffer(b, docstring()))
1828 return saveBuffer(b);
1832 bool GuiView::closeBuffer()
1834 Buffer * buf = buffer();
1835 return buf && closeBuffer(*buf);
1839 bool GuiView::closeBuffer(Buffer & buf, bool tolastopened)
1841 // goto bookmark to update bookmark pit.
1842 //FIXME: we should update only the bookmarks related to this buffer!
1843 LYXERR(Debug::DEBUG, "GuiView::closeBuffer()");
1844 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
1845 theLyXFunc().gotoBookmark(i+1, false, false);
1847 if (buf.isClean() || buf.paragraphs().empty()) {
1848 if (buf.masterBuffer() == &buf && tolastopened)
1849 theSession().lastOpened().add(buf.fileName());
1851 // Don't close child documents.
1852 removeWorkArea(currentMainWorkArea());
1854 theBufferList().release(&buf);
1857 // Switch to this Buffer.
1862 if (buf.isUnnamed())
1863 file = from_utf8(buf.fileName().onlyFileName());
1865 file = buf.fileName().displayName(30);
1867 // Bring this window to top before asking questions.
1871 docstring const text = bformat(_("The document %1$s has unsaved changes."
1872 "\n\nDo you want to save the document or discard the changes?"), file);
1873 int const ret = Alert::prompt(_("Save changed document?"),
1874 text, 0, 2, _("&Save"), _("&Discard"), _("&Cancel"));
1878 if (!saveBuffer(buf))
1882 // if we crash after this we could
1883 // have no autosave file but I guess
1884 // this is really improbable (Jug)
1885 removeAutosaveFile(buf.absFileName());
1891 // save file names to .lyx/session
1892 // if master/slave are both open, do not save slave since it
1893 // will be automatically loaded when the master is loaded
1894 if (buf.masterBuffer() == &buf && tolastopened)
1895 theSession().lastOpened().add(buf.fileName());
1898 // Don't close child documents.
1899 removeWorkArea(currentMainWorkArea());
1901 theBufferList().release(&buf);
1907 bool GuiView::dispatch(FuncRequest const & cmd)
1909 BufferView * bv = view();
1910 // By default we won't need any update.
1912 bv->cursor().updateFlags(Update::None);
1913 bool dispatched = true;
1915 switch(cmd.action) {
1916 case LFUN_BUFFER_IMPORT:
1917 importDocument(to_utf8(cmd.argument()));
1920 case LFUN_BUFFER_SWITCH:
1921 setBuffer(theBufferList().getBuffer(FileName(to_utf8(cmd.argument()))));
1924 case LFUN_BUFFER_NEXT:
1925 setBuffer(theBufferList().next(buffer()));
1928 case LFUN_BUFFER_PREVIOUS:
1929 setBuffer(theBufferList().previous(buffer()));
1932 case LFUN_COMMAND_EXECUTE: {
1933 bool const show_it = cmd.argument() != "off";
1934 // FIXME: this is a hack, "minibuffer" should not be
1936 if (GuiToolbar * t = toolbar("minibuffer")) {
1937 t->setVisible(show_it);
1938 if (show_it && t->commandBuffer())
1939 t->commandBuffer()->setFocus();
1943 case LFUN_DROP_LAYOUTS_CHOICE:
1945 d.layout_->showPopup();
1948 case LFUN_MENU_OPEN:
1949 if (QMenu * menu = guiApp->menus().menu(toqstr(cmd.argument()), *this))
1950 menu->exec(QCursor::pos());
1953 case LFUN_FILE_INSERT:
1954 insertLyXFile(cmd.argument());
1956 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
1957 insertPlaintextFile(cmd.argument(), true);
1960 case LFUN_FILE_INSERT_PLAINTEXT:
1961 insertPlaintextFile(cmd.argument(), false);
1964 case LFUN_BUFFER_WRITE:
1966 saveBuffer(bv->buffer());
1969 case LFUN_BUFFER_WRITE_AS:
1971 renameBuffer(bv->buffer(), cmd.argument());
1974 case LFUN_BUFFER_WRITE_ALL: {
1975 Buffer * first = theBufferList().first();
1978 message(_("Saving all documents..."));
1979 // We cannot use a for loop as the buffer list cycles.
1982 if (!b->isClean()) {
1984 LYXERR(Debug::ACTION, "Saved " << b->absFileName());
1986 b = theBufferList().next(b);
1987 } while (b != first);
1988 message(_("All documents saved."));
1992 case LFUN_TOOLBAR_TOGGLE: {
1993 string const name = cmd.getArg(0);
1994 if (GuiToolbar * t = toolbar(name))
1999 case LFUN_DIALOG_UPDATE: {
2000 string const name = to_utf8(cmd.argument());
2001 // Can only update a dialog connected to an existing inset
2002 Inset * inset = getOpenInset(name);
2004 FuncRequest fr(LFUN_INSET_DIALOG_UPDATE, cmd.argument());
2005 inset->dispatch(view()->cursor(), fr);
2006 } else if (name == "paragraph") {
2007 lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
2008 } else if (name == "prefs" || name == "document") {
2009 updateDialog(name, string());
2014 case LFUN_DIALOG_TOGGLE: {
2015 if (isDialogVisible(cmd.getArg(0)))
2016 dispatch(FuncRequest(LFUN_DIALOG_HIDE, cmd.argument()));
2018 dispatch(FuncRequest(LFUN_DIALOG_SHOW, cmd.argument()));
2022 case LFUN_DIALOG_DISCONNECT_INSET:
2023 disconnectDialog(to_utf8(cmd.argument()));
2026 case LFUN_DIALOG_HIDE: {
2027 guiApp->hideDialogs(to_utf8(cmd.argument()), 0);
2031 case LFUN_DIALOG_SHOW: {
2032 string const name = cmd.getArg(0);
2033 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
2035 if (name == "character") {
2036 data = freefont2string();
2038 showDialog("character", data);
2039 } else if (name == "latexlog") {
2040 Buffer::LogType type;
2041 string const logfile = buffer()->logName(&type);
2043 case Buffer::latexlog:
2046 case Buffer::buildlog:
2050 data += Lexer::quoteString(logfile);
2051 showDialog("log", data);
2052 } else if (name == "vclog") {
2053 string const data = "vc " +
2054 Lexer::quoteString(buffer()->lyxvc().getLogFile());
2055 showDialog("log", data);
2056 } else if (name == "symbols") {
2057 data = bv->cursor().getEncoding()->name();
2059 showDialog("symbols", data);
2061 } else if (name == "prefs" && isFullScreen()) {
2062 FuncRequest fr(LFUN_INSET_INSERT, "fullscreen");
2064 showDialog("prefs", data);
2066 showDialog(name, data);
2070 case LFUN_INSET_APPLY: {
2071 string const name = cmd.getArg(0);
2072 Inset * inset = getOpenInset(name);
2074 // put cursor in front of inset.
2075 if (!view()->setCursorFromInset(inset)) {
2076 LASSERT(false, break);
2079 // useful if we are called from a dialog.
2080 view()->cursor().beginUndoGroup();
2081 view()->cursor().recordUndo();
2082 FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument());
2083 inset->dispatch(view()->cursor(), fr);
2084 view()->cursor().endUndoGroup();
2086 FuncRequest fr(LFUN_INSET_INSERT, cmd.argument());
2092 case LFUN_UI_TOGGLE:
2094 // Make sure the keyboard focus stays in the work area.
2098 case LFUN_SPLIT_VIEW:
2099 if (Buffer * buf = buffer()) {
2100 string const orientation = cmd.getArg(0);
2101 d.splitter_->setOrientation(orientation == "vertical"
2102 ? Qt::Vertical : Qt::Horizontal);
2103 TabWorkArea * twa = addTabWorkArea();
2104 GuiWorkArea * wa = twa->addWorkArea(*buf, *this);
2105 setCurrentWorkArea(wa);
2109 case LFUN_CLOSE_TAB_GROUP:
2110 if (TabWorkArea * twa = d.currentTabWorkArea()) {
2112 twa = d.currentTabWorkArea();
2113 // Switch to the next GuiWorkArea in the found TabWorkArea.
2115 // Make sure the work area is up to date.
2116 setCurrentWorkArea(twa->currentWorkArea());
2118 setCurrentWorkArea(0);
2123 case LFUN_COMPLETION_INLINE:
2124 if (d.current_work_area_)
2125 d.current_work_area_->completer().showInline();
2128 case LFUN_COMPLETION_POPUP:
2129 if (d.current_work_area_)
2130 d.current_work_area_->completer().showPopup();
2134 case LFUN_COMPLETION_COMPLETE:
2135 if (d.current_work_area_)
2136 d.current_work_area_->completer().tab();
2139 case LFUN_COMPLETION_CANCEL:
2140 if (d.current_work_area_) {
2141 if (d.current_work_area_->completer().popupVisible())
2142 d.current_work_area_->completer().hidePopup();
2144 d.current_work_area_->completer().hideInline();
2148 case LFUN_COMPLETION_ACCEPT:
2149 if (d.current_work_area_)
2150 d.current_work_area_->completer().activate();
2159 // Part of automatic menu appearance feature.
2160 if (isFullScreen()) {
2161 if (menuBar()->isVisible())
2163 if (statusBar()->isVisible())
2164 statusBar()->hide();
2171 void GuiView::lfunUiToggle(FuncRequest const & cmd)
2173 string const arg = cmd.getArg(0);
2174 if (arg == "scrollbar") {
2175 // hide() is of no help
2176 if (d.current_work_area_->verticalScrollBarPolicy() ==
2177 Qt::ScrollBarAlwaysOff)
2179 d.current_work_area_->setVerticalScrollBarPolicy(
2180 Qt::ScrollBarAsNeeded);
2182 d.current_work_area_->setVerticalScrollBarPolicy(
2183 Qt::ScrollBarAlwaysOff);
2186 if (arg == "statusbar") {
2187 statusBar()->setVisible(!statusBar()->isVisible());
2190 if (arg == "menubar") {
2191 menuBar()->setVisible(!menuBar()->isVisible());
2194 #if QT_VERSION >= 0x040300
2195 if (arg == "frame") {
2197 getContentsMargins(&l, &t, &r, &b);
2198 //are the frames in default state?
2199 d.current_work_area_->setFrameStyle(QFrame::NoFrame);
2201 setContentsMargins(-2, -2, -2, -2);
2203 setContentsMargins(0, 0, 0, 0);
2208 if (arg == "fullscreen") {
2213 message(bformat("LFUN_UI_TOGGLE " + _("%1$s unknown command!"), from_utf8(arg)));
2217 void GuiView::toggleFullScreen()
2219 if (isFullScreen()) {
2220 for (int i = 0; i != d.splitter_->count(); ++i)
2221 d.tabWorkArea(i)->setFullScreen(false);
2222 #if QT_VERSION >= 0x040300
2223 setContentsMargins(0, 0, 0, 0);
2225 setWindowState(windowState() ^ Qt::WindowFullScreen);
2228 statusBar()->show();
2231 hideDialogs("prefs", 0);
2232 for (int i = 0; i != d.splitter_->count(); ++i)
2233 d.tabWorkArea(i)->setFullScreen(true);
2234 #if QT_VERSION >= 0x040300
2235 setContentsMargins(-2, -2, -2, -2);
2238 setWindowState(windowState() ^ Qt::WindowFullScreen);
2239 statusBar()->hide();
2241 if (lyxrc.full_screen_toolbars) {
2242 ToolbarMap::iterator end = d.toolbars_.end();
2243 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
2248 // give dialogs like the TOC a chance to adapt
2253 Buffer const * GuiView::updateInset(Inset const * inset)
2255 if (!d.current_work_area_)
2259 d.current_work_area_->scheduleRedraw();
2261 return &d.current_work_area_->bufferView().buffer();
2265 void GuiView::restartCursor()
2267 /* When we move around, or type, it's nice to be able to see
2268 * the cursor immediately after the keypress.
2270 if (d.current_work_area_)
2271 d.current_work_area_->startBlinkingCursor();
2273 // Take this occasion to update the other GUI elements.
2279 void GuiView::updateCompletion(Cursor & cur, bool start, bool keep)
2281 if (d.current_work_area_)
2282 d.current_work_area_->completer().updateVisibility(cur, start, keep);
2287 // This list should be kept in sync with the list of insets in
2288 // src/insets/Inset.cpp. I.e., if a dialog goes with an inset, the
2289 // dialog should have the same name as the inset.
2290 // Changes should be also recorded in LFUN_DIALOG_SHOW doxygen
2291 // docs in LyXAction.cpp.
2293 char const * const dialognames[] = {
2294 "aboutlyx", "bibitem", "bibtex", "box", "branch", "changes", "character",
2295 "citation", "document", "errorlist", "ert", "external", "file",
2296 "findreplace", "float", "graphics", "include", "index", "info", "nomenclature", "label", "log",
2297 "mathdelimiter", "mathmatrix", "mathspace", "note", "paragraph", "prefs", "print",
2298 "ref", "sendto", "space", "spellchecker", "symbols", "tabular", "tabularcreate",
2300 #ifdef HAVE_LIBAIKSAURUS
2304 "texinfo", "toc", "href", "view-source", "vspace", "wrap", "listings", "findreplaceadv" };
2306 char const * const * const end_dialognames =
2307 dialognames + (sizeof(dialognames) / sizeof(char *));
2311 cmpCStr(char const * name) : name_(name) {}
2312 bool operator()(char const * other) {
2313 return strcmp(other, name_) == 0;
2320 bool isValidName(string const & name)
2322 return find_if(dialognames, end_dialognames,
2323 cmpCStr(name.c_str())) != end_dialognames;
2329 void GuiView::resetDialogs()
2331 // Make sure that no LFUN uses any LyXView.
2332 theLyXFunc().setLyXView(0);
2335 constructToolbars();
2336 guiApp->menus().fillMenuBar(menuBar(), this, false);
2338 d.layout_->updateContents(true);
2339 // Now update controls with current buffer.
2340 theLyXFunc().setLyXView(this);
2346 Dialog * GuiView::findOrBuild(string const & name, bool hide_it)
2348 if (!isValidName(name))
2351 map<string, DialogPtr>::iterator it = d.dialogs_.find(name);
2353 if (it != d.dialogs_.end()) {
2355 it->second->hideView();
2356 return it->second.get();
2359 Dialog * dialog = build(name);
2360 d.dialogs_[name].reset(dialog);
2361 if (lyxrc.allow_geometry_session)
2362 dialog->restoreSession();
2369 void GuiView::showDialog(string const & name, string const & data,
2377 Dialog * dialog = findOrBuild(name, false);
2379 dialog->showData(data);
2381 d.open_insets_[name] = inset;
2384 catch (ExceptionMessage const & ex) {
2392 bool GuiView::isDialogVisible(string const & name) const
2394 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
2395 if (it == d.dialogs_.end())
2397 return it->second.get()->isVisibleView();
2401 void GuiView::hideDialog(string const & name, Inset * inset)
2403 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
2404 if (it == d.dialogs_.end())
2407 if (inset && inset != getOpenInset(name))
2410 Dialog * const dialog = it->second.get();
2411 if (dialog->isVisibleView())
2413 d.open_insets_[name] = 0;
2417 void GuiView::disconnectDialog(string const & name)
2419 if (!isValidName(name))
2422 if (d.open_insets_.find(name) != d.open_insets_.end())
2423 d.open_insets_[name] = 0;
2427 Inset * GuiView::getOpenInset(string const & name) const
2429 if (!isValidName(name))
2432 map<string, Inset *>::const_iterator it = d.open_insets_.find(name);
2433 return it == d.open_insets_.end() ? 0 : it->second;
2437 void GuiView::hideAll() const
2439 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
2440 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
2442 for(; it != end; ++it)
2443 it->second->hideView();
2447 void GuiView::updateDialogs()
2449 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
2450 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
2452 for(; it != end; ++it) {
2453 Dialog * dialog = it->second.get();
2454 if (dialog && dialog->isVisibleView())
2455 dialog->checkStatus();
2462 // will be replaced by a proper factory...
2463 Dialog * createGuiAbout(GuiView & lv);
2464 Dialog * createGuiBibitem(GuiView & lv);
2465 Dialog * createGuiBibtex(GuiView & lv);
2466 Dialog * createGuiBox(GuiView & lv);
2467 Dialog * createGuiBranch(GuiView & lv);
2468 Dialog * createGuiChanges(GuiView & lv);
2469 Dialog * createGuiCharacter(GuiView & lv);
2470 Dialog * createGuiCitation(GuiView & lv);
2471 Dialog * createGuiDelimiter(GuiView & lv);
2472 Dialog * createGuiDocument(GuiView & lv);
2473 Dialog * createGuiErrorList(GuiView & lv);
2474 Dialog * createGuiERT(GuiView & lv);
2475 Dialog * createGuiExternal(GuiView & lv);
2476 Dialog * createGuiFloat(GuiView & lv);
2477 Dialog * createGuiGraphics(GuiView & lv);
2478 Dialog * createGuiInclude(GuiView & lv);
2479 Dialog * createGuiInfo(GuiView & lv);
2480 Dialog * createGuiLabel(GuiView & lv);
2481 Dialog * createGuiListings(GuiView & lv);
2482 Dialog * createGuiLog(GuiView & lv);
2483 Dialog * createGuiMathHSpace(GuiView & lv);
2484 Dialog * createGuiMathMatrix(GuiView & lv);
2485 Dialog * createGuiNomenclature(GuiView & lv);
2486 Dialog * createGuiNote(GuiView & lv);
2487 Dialog * createGuiParagraph(GuiView & lv);
2488 Dialog * createGuiPreferences(GuiView & lv);
2489 Dialog * createGuiPrint(GuiView & lv);
2490 Dialog * createGuiRef(GuiView & lv);
2491 Dialog * createGuiSearch(GuiView & lv);
2492 Dialog * createGuiSearchAdv(GuiView & lv);
2493 Dialog * createGuiSendTo(GuiView & lv);
2494 Dialog * createGuiShowFile(GuiView & lv);
2495 Dialog * createGuiSpellchecker(GuiView & lv);
2496 Dialog * createGuiSymbols(GuiView & lv);
2497 Dialog * createGuiTabularCreate(GuiView & lv);
2498 Dialog * createGuiTabular(GuiView & lv);
2499 Dialog * createGuiTexInfo(GuiView & lv);
2500 Dialog * createGuiTextHSpace(GuiView & lv);
2501 Dialog * createGuiToc(GuiView & lv);
2502 Dialog * createGuiThesaurus(GuiView & lv);
2503 Dialog * createGuiHyperlink(GuiView & lv);
2504 Dialog * createGuiVSpace(GuiView & lv);
2505 Dialog * createGuiViewSource(GuiView & lv);
2506 Dialog * createGuiWrap(GuiView & lv);
2509 Dialog * GuiView::build(string const & name)
2511 LASSERT(isValidName(name), return 0);
2513 if (name == "aboutlyx")
2514 return createGuiAbout(*this);
2515 if (name == "bibitem")
2516 return createGuiBibitem(*this);
2517 if (name == "bibtex")
2518 return createGuiBibtex(*this);
2520 return createGuiBox(*this);
2521 if (name == "branch")
2522 return createGuiBranch(*this);
2523 if (name == "changes")
2524 return createGuiChanges(*this);
2525 if (name == "character")
2526 return createGuiCharacter(*this);
2527 if (name == "citation")
2528 return createGuiCitation(*this);
2529 if (name == "document")
2530 return createGuiDocument(*this);
2531 if (name == "errorlist")
2532 return createGuiErrorList(*this);
2534 return createGuiERT(*this);
2535 if (name == "external")
2536 return createGuiExternal(*this);
2538 return createGuiShowFile(*this);
2539 if (name == "findreplace")
2540 return createGuiSearch(*this);
2541 if (name == "findreplaceadv")
2542 return createGuiSearchAdv(*this);
2543 if (name == "float")
2544 return createGuiFloat(*this);
2545 if (name == "graphics")
2546 return createGuiGraphics(*this);
2547 if (name == "include")
2548 return createGuiInclude(*this);
2550 return createGuiInfo(*this);
2551 if (name == "nomenclature")
2552 return createGuiNomenclature(*this);
2553 if (name == "label")
2554 return createGuiLabel(*this);
2556 return createGuiLog(*this);
2557 if (name == "view-source")
2558 return createGuiViewSource(*this);
2559 if (name == "mathdelimiter")
2560 return createGuiDelimiter(*this);
2561 if (name == "mathspace")
2562 return createGuiMathHSpace(*this);
2563 if (name == "mathmatrix")
2564 return createGuiMathMatrix(*this);
2566 return createGuiNote(*this);
2567 if (name == "paragraph")
2568 return createGuiParagraph(*this);
2569 if (name == "prefs")
2570 return createGuiPreferences(*this);
2571 if (name == "print")
2572 return createGuiPrint(*this);
2574 return createGuiRef(*this);
2575 if (name == "sendto")
2576 return createGuiSendTo(*this);
2577 if (name == "space")
2578 return createGuiTextHSpace(*this);
2579 if (name == "spellchecker")
2580 return createGuiSpellchecker(*this);
2581 if (name == "symbols")
2582 return createGuiSymbols(*this);
2583 if (name == "tabular")
2584 return createGuiTabular(*this);
2585 if (name == "tabularcreate")
2586 return createGuiTabularCreate(*this);
2587 if (name == "texinfo")
2588 return createGuiTexInfo(*this);
2589 #ifdef HAVE_LIBAIKSAURUS
2590 if (name == "thesaurus")
2591 return createGuiThesaurus(*this);
2594 return createGuiToc(*this);
2596 return createGuiHyperlink(*this);
2597 if (name == "vspace")
2598 return createGuiVSpace(*this);
2600 return createGuiWrap(*this);
2601 if (name == "listings")
2602 return createGuiListings(*this);
2608 } // namespace frontend
2611 #include "moc_GuiView.cpp"