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 "DispatchResult.h"
20 #include "FileDialog.h"
21 #include "FontLoader.h"
22 #include "GuiApplication.h"
23 #include "GuiCommandBuffer.h"
24 #include "GuiCompleter.h"
25 #include "GuiKeySymbol.h"
27 #include "GuiToolbar.h"
28 #include "GuiWorkArea.h"
29 #include "LayoutBox.h"
32 #include "GuiProgress.h"
33 #include "qt_helpers.h"
35 #include "frontends/alert.h"
37 #include "buffer_funcs.h"
39 #include "BufferList.h"
40 #include "BufferParams.h"
41 #include "BufferView.h"
43 #include "Converter.h"
45 #include "CutAndPaste.h"
47 #include "ErrorList.h"
49 #include "FuncStatus.h"
50 #include "FuncRequest.h"
54 #include "LyXAction.h"
58 #include "Paragraph.h"
59 #include "SpellChecker.h"
61 #include "TextClass.h"
65 #include "GuiEncryptionDialog.h"
67 #include "support/convert.h"
68 #include "support/debug.h"
69 #include "support/ExceptionMessage.h"
70 #include "support/FileName.h"
71 #include "support/filetools.h"
72 #include "support/gettext.h"
73 #include "support/filetools.h"
74 #include "support/ForkedCalls.h"
75 #include "support/lassert.h"
76 #include "support/lstrings.h"
77 #include "support/os.h"
78 #include "support/Package.h"
79 #include "support/Path.h"
80 #include "support/Systemcall.h"
81 #include "support/Timeout.h"
82 #include "support/ProgressInterface.h"
83 #include "support/CryptographicEncryption.h"
87 #include <QApplication>
88 #include <QCloseEvent>
90 #include <QDesktopWidget>
91 #include <QDragEnterEvent>
98 #include <QPixmapCache>
100 #include <QPushButton>
102 #include <QShowEvent>
104 #include <QStackedWidget>
105 #include <QStatusBar>
110 #include <QScrollBar>
112 #include <QHBoxLayout>
116 #define EXPORT_in_THREAD 1
118 // QtConcurrent was introduced in Qt 4.4
119 #if (QT_VERSION >= 0x040400)
121 #include <QFutureWatcher>
122 #include <QtConcurrentRun>
125 #include "support/bind.h"
129 #ifdef HAVE_SYS_TIME_H
130 # include <sys/time.h>
137 using namespace lyx::support;
144 class BackgroundWidget : public QWidget
149 LYXERR(Debug::GUI, "show banner: " << lyxrc.show_banner);
150 if (!lyxrc.show_banner)
152 /// The text to be written on top of the pixmap
153 QString const text = lyx_version ?
154 qt_("version ") + lyx_version : qt_("unknown version");
155 splash_ = getPixmap("images/", "banner", "png");
157 QPainter pain(&splash_);
158 pain.setPen(QColor(0, 0, 0));
160 // The font used to display the version info
161 font.setStyleHint(QFont::SansSerif);
162 font.setWeight(QFont::Bold);
163 font.setPointSize(int(toqstr(lyxrc.font_sizes[FONT_SIZE_LARGE]).toDouble()));
164 int width = QFontMetrics(font).width(text);
166 pain.drawText(397 - width, 15, text);
167 setFocusPolicy(Qt::StrongFocus);
170 void paintEvent(QPaintEvent *)
172 int x = (width() - splash_.width()) / 2;
173 int y = (height() - splash_.height()) / 2;
175 pain.drawPixmap(x, y, splash_);
178 void keyPressEvent(QKeyEvent * ev)
181 setKeySymbol(&sym, ev);
183 guiApp->processKeySym(sym, q_key_state(ev->modifiers()));
195 /// Toolbar store providing access to individual toolbars by name.
196 typedef map<string, GuiToolbar *> ToolbarMap;
198 typedef shared_ptr<Dialog> DialogPtr;
203 struct GuiView::GuiViewPrivate
205 GuiViewPrivate(GuiView * gv)
206 : gv_(gv), current_work_area_(0), current_main_work_area_(0),
207 layout_(0), autosave_timeout_(5000),
210 // hardcode here the platform specific icon size
211 smallIconSize = 14; // scaling problems
212 normalIconSize = 20; // ok, default
213 bigIconSize = 26; // better for some math icons
215 splitter_ = new QSplitter;
216 bg_widget_ = new BackgroundWidget;
217 stack_widget_ = new QStackedWidget;
218 stack_widget_->addWidget(bg_widget_);
219 stack_widget_->addWidget(splitter_);
222 // TODO cleanup, remove the singleton, handle multiple Windows?
223 progress_ = ProgressInterface::instance();
224 if (!dynamic_cast<GuiProgress*>(progress_)) {
225 progress_ = new GuiProgress(); // TODO who deletes it
226 ProgressInterface::setInstance(progress_);
229 dynamic_cast<GuiProgress*>(progress_),
230 SIGNAL(updateStatusBarMessage(QString const&)),
231 gv, SLOT(updateStatusBarMessage(QString const&)));
233 dynamic_cast<GuiProgress*>(progress_),
234 SIGNAL(clearMessageText()),
235 gv, SLOT(clearMessageText()));
242 delete stack_widget_;
245 QMenu * toolBarPopup(GuiView * parent)
247 // FIXME: translation
248 QMenu * menu = new QMenu(parent);
249 QActionGroup * iconSizeGroup = new QActionGroup(parent);
251 QAction * smallIcons = new QAction(iconSizeGroup);
252 smallIcons->setText(qt_("Small-sized icons"));
253 smallIcons->setCheckable(true);
254 QObject::connect(smallIcons, SIGNAL(triggered()),
255 parent, SLOT(smallSizedIcons()));
256 menu->addAction(smallIcons);
258 QAction * normalIcons = new QAction(iconSizeGroup);
259 normalIcons->setText(qt_("Normal-sized icons"));
260 normalIcons->setCheckable(true);
261 QObject::connect(normalIcons, SIGNAL(triggered()),
262 parent, SLOT(normalSizedIcons()));
263 menu->addAction(normalIcons);
265 QAction * bigIcons = new QAction(iconSizeGroup);
266 bigIcons->setText(qt_("Big-sized icons"));
267 bigIcons->setCheckable(true);
268 QObject::connect(bigIcons, SIGNAL(triggered()),
269 parent, SLOT(bigSizedIcons()));
270 menu->addAction(bigIcons);
272 unsigned int cur = parent->iconSize().width();
273 if ( cur == parent->d.smallIconSize)
274 smallIcons->setChecked(true);
275 else if (cur == parent->d.normalIconSize)
276 normalIcons->setChecked(true);
277 else if (cur == parent->d.bigIconSize)
278 bigIcons->setChecked(true);
285 stack_widget_->setCurrentWidget(bg_widget_);
286 bg_widget_->setUpdatesEnabled(true);
287 bg_widget_->setFocus();
290 TabWorkArea * tabWorkArea(int i)
292 return dynamic_cast<TabWorkArea *>(splitter_->widget(i));
295 TabWorkArea * currentTabWorkArea()
297 if (splitter_->count() == 1)
298 // The first TabWorkArea is always the first one, if any.
299 return tabWorkArea(0);
301 for (int i = 0; i != splitter_->count(); ++i) {
302 TabWorkArea * twa = tabWorkArea(i);
303 if (current_main_work_area_ == twa->currentWorkArea())
307 // None has the focus so we just take the first one.
308 return tabWorkArea(0);
311 #if (QT_VERSION >= 0x040400)
312 void setPreviewFuture(QFuture<docstring> const & f)
314 if (preview_watcher_.isRunning()) {
315 // we prefer to cancel this preview in order to keep a snappy
319 preview_watcher_.setFuture(f);
325 GuiWorkArea * current_work_area_;
326 GuiWorkArea * current_main_work_area_;
327 QSplitter * splitter_;
328 QStackedWidget * stack_widget_;
329 BackgroundWidget * bg_widget_;
331 ToolbarMap toolbars_;
332 ProgressInterface* progress_;
333 /// The main layout box.
335 * \warning Don't Delete! The layout box is actually owned by
336 * whichever toolbar contains it. All the GuiView class needs is a
337 * means of accessing it.
339 * FIXME: replace that with a proper model so that we are not limited
340 * to only one dialog.
345 map<string, DialogPtr> dialogs_;
347 unsigned int smallIconSize;
348 unsigned int normalIconSize;
349 unsigned int bigIconSize;
351 QTimer statusbar_timer_;
352 /// auto-saving of buffers
353 Timeout autosave_timeout_;
354 /// flag against a race condition due to multiclicks, see bug #1119
358 TocModels toc_models_;
360 #if (QT_VERSION >= 0x040400)
362 QFutureWatcher<docstring> autosave_watcher_;
363 QFutureWatcher<docstring> preview_watcher_;
365 string last_export_format;
367 struct DummyWatcher { bool isRunning(){return false;} };
368 DummyWatcher preview_watcher_;
371 static QSet<Buffer const *> busyBuffers;
372 static docstring previewAndDestroy(Buffer const * orig, Buffer * buffer, string const & format);
373 static docstring exportAndDestroy(Buffer const * orig, Buffer * buffer, string const & format);
374 static docstring saveAndDestroy(Buffer const * orig, Buffer * buffer, FileName const & fname);
378 QSet<Buffer const *> GuiView::GuiViewPrivate::busyBuffers;
381 GuiView::GuiView(int id)
382 : d(*new GuiViewPrivate(this)), id_(id), closing_(false)
384 // GuiToolbars *must* be initialised before the menu bar.
385 normalSizedIcons(); // at least on Mac the default is 32 otherwise, which is huge
388 // set ourself as the current view. This is needed for the menu bar
389 // filling, at least for the static special menu item on Mac. Otherwise
390 // they are greyed out.
391 guiApp->setCurrentView(this);
393 // Fill up the menu bar.
394 guiApp->menus().fillMenuBar(menuBar(), this, true);
396 setCentralWidget(d.stack_widget_);
398 // Start autosave timer
399 if (lyxrc.autosave) {
400 d.autosave_timeout_.timeout.connect(bind(&GuiView::autoSave, this));
401 d.autosave_timeout_.setTimeout(lyxrc.autosave * 1000);
402 d.autosave_timeout_.start();
404 connect(&d.statusbar_timer_, SIGNAL(timeout()),
405 this, SLOT(clearMessage()));
407 // We don't want to keep the window in memory if it is closed.
408 setAttribute(Qt::WA_DeleteOnClose, true);
410 #if (!defined(Q_WS_WIN) && !defined(Q_WS_MACX))
411 // assign an icon to main form. We do not do it under Qt/Win or Qt/Mac,
412 // since the icon is provided in the application bundle.
413 setWindowIcon(getPixmap("images/", "lyx", "png"));
416 #if (QT_VERSION >= 0x040300)
417 // use tabbed dock area for multiple docks
418 // (such as "source" and "messages")
419 setDockOptions(QMainWindow::ForceTabbedDocks);
423 setAcceptDrops(true);
425 statusBar()->setSizeGripEnabled(true);
428 #if (QT_VERSION >= 0x040400)
429 connect(&d.autosave_watcher_, SIGNAL(finished()), this,
430 SLOT(threadFinished()));
431 connect(&d.preview_watcher_, SIGNAL(finished()), this,
432 SLOT(threadFinished()));
435 connect(this, SIGNAL(triggerShowDialog(QString const &, QString const &, Inset *)),
436 SLOT(doShowDialog(QString const &, QString const &, Inset *)));
438 // Forbid too small unresizable window because it can happen
439 // with some window manager under X11.
440 setMinimumSize(300, 200);
442 if (lyxrc.allow_geometry_session) {
443 // Now take care of session management.
448 // no session handling, default to a sane size.
449 setGeometry(50, 50, 690, 510);
452 // clear session data if any.
454 settings.remove("views");
464 void GuiView::threadFinished()
466 #if (QT_VERSION >= 0x040400)
467 QFutureWatcher<docstring> const * watcher =
468 static_cast<QFutureWatcher<docstring> const *>(sender());
469 message(watcher->result());
471 errors(d.last_export_format);
476 void GuiView::saveLayout() const
479 settings.beginGroup("views");
480 settings.beginGroup(QString::number(id_));
482 settings.setValue("pos", pos());
483 settings.setValue("size", size());
485 settings.setValue("geometry", saveGeometry());
487 settings.setValue("layout", saveState(0));
488 settings.setValue("icon_size", iconSize());
492 bool GuiView::restoreLayout()
495 settings.beginGroup("views");
496 settings.beginGroup(QString::number(id_));
497 QString const icon_key = "icon_size";
498 if (!settings.contains(icon_key))
501 //code below is skipped when when ~/.config/LyX is (re)created
502 setIconSize(settings.value(icon_key).toSize());
504 QPoint pos = settings.value("pos", QPoint(50, 50)).toPoint();
505 QSize size = settings.value("size", QSize(690, 510)).toSize();
509 // Work-around for bug #6034: the window ends up in an undetermined
510 // state when trying to restore a maximized window when it is
511 // already maximized.
512 if (!(windowState() & Qt::WindowMaximized))
513 if (!restoreGeometry(settings.value("geometry").toByteArray()))
514 setGeometry(50, 50, 690, 510);
516 // Make sure layout is correctly oriented.
517 setLayoutDirection(qApp->layoutDirection());
519 // Allow the toc and view-source dock widget to be restored if needed.
521 if ((dialog = findOrBuild("toc", true)))
522 // see bug 5082. At least setup title and enabled state.
523 // Visibility will be adjusted by restoreState below.
524 dialog->prepareView();
525 if ((dialog = findOrBuild("view-source", true)))
526 dialog->prepareView();
527 if ((dialog = findOrBuild("progress", true)))
528 dialog->prepareView();
530 if (!restoreState(settings.value("layout").toByteArray(), 0))
537 GuiToolbar * GuiView::toolbar(string const & name)
539 ToolbarMap::iterator it = d.toolbars_.find(name);
540 if (it != d.toolbars_.end())
543 LYXERR(Debug::GUI, "Toolbar::display: no toolbar named " << name);
548 void GuiView::constructToolbars()
550 ToolbarMap::iterator it = d.toolbars_.begin();
551 for (; it != d.toolbars_.end(); ++it)
555 // I don't like doing this here, but the standard toolbar
556 // destroys this object when it's destroyed itself (vfr)
557 d.layout_ = new LayoutBox(*this);
558 d.stack_widget_->addWidget(d.layout_);
559 d.layout_->move(0,0);
561 // extracts the toolbars from the backend
562 Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
563 Toolbars::Infos::iterator end = guiApp->toolbars().end();
564 for (; cit != end; ++cit)
565 d.toolbars_[cit->name] = new GuiToolbar(*cit, *this);
569 void GuiView::initToolbars()
571 // extracts the toolbars from the backend
572 Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
573 Toolbars::Infos::iterator end = guiApp->toolbars().end();
574 for (; cit != end; ++cit) {
575 GuiToolbar * tb = toolbar(cit->name);
578 int const visibility = guiApp->toolbars().defaultVisibility(cit->name);
579 bool newline = !(visibility & Toolbars::SAMEROW);
580 tb->setVisible(false);
581 tb->setVisibility(visibility);
583 if (visibility & Toolbars::TOP) {
585 addToolBarBreak(Qt::TopToolBarArea);
586 addToolBar(Qt::TopToolBarArea, tb);
589 if (visibility & Toolbars::BOTTOM) {
590 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
591 #if (QT_VERSION >= 0x040202)
593 addToolBarBreak(Qt::BottomToolBarArea);
595 addToolBar(Qt::BottomToolBarArea, tb);
598 if (visibility & Toolbars::LEFT) {
599 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
600 #if (QT_VERSION >= 0x040202)
602 addToolBarBreak(Qt::LeftToolBarArea);
604 addToolBar(Qt::LeftToolBarArea, tb);
607 if (visibility & Toolbars::RIGHT) {
608 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
609 #if (QT_VERSION >= 0x040202)
611 addToolBarBreak(Qt::RightToolBarArea);
613 addToolBar(Qt::RightToolBarArea, tb);
616 if (visibility & Toolbars::ON)
617 tb->setVisible(true);
622 TocModels & GuiView::tocModels()
624 return d.toc_models_;
628 void GuiView::setFocus()
630 LYXERR(Debug::DEBUG, "GuiView::setFocus()" << this);
631 QMainWindow::setFocus();
635 void GuiView::focusInEvent(QFocusEvent * e)
637 LYXERR(Debug::DEBUG, "GuiView::focusInEvent()" << this);
638 QMainWindow::focusInEvent(e);
639 // Make sure guiApp points to the correct view.
640 guiApp->setCurrentView(this);
641 if (currentMainWorkArea())
642 currentMainWorkArea()->setFocus();
643 else if (currentWorkArea())
644 currentWorkArea()->setFocus();
646 d.bg_widget_->setFocus();
650 QMenu * GuiView::createPopupMenu()
652 return d.toolBarPopup(this);
656 void GuiView::showEvent(QShowEvent * e)
658 LYXERR(Debug::GUI, "Passed Geometry "
659 << size().height() << "x" << size().width()
660 << "+" << pos().x() << "+" << pos().y());
662 if (d.splitter_->count() == 0)
663 // No work area, switch to the background widget.
666 QMainWindow::showEvent(e);
670 bool GuiView::closeScheduled()
677 /** Destroy only all tabbed WorkAreas. Destruction of other WorkAreas
678 ** is responsibility of the container (e.g., dialog)
680 void GuiView::closeEvent(QCloseEvent * close_event)
682 LYXERR(Debug::DEBUG, "GuiView::closeEvent()");
684 if (!GuiViewPrivate::busyBuffers.isEmpty()) {
685 Alert::warning(_("Exit LyX"), _("LyX could not be closed because documents are processed by LyX."));
686 close_event->setAccepted(false);
690 // If the user pressed the x (so we didn't call closeView
691 // programmatically), we want to clear all existing entries.
693 theSession().lastOpened().clear();
698 // it can happen that this event arrives without selecting the view,
699 // e.g. when clicking the close button on a background window.
701 if (!closeWorkAreaAll()) {
703 close_event->ignore();
707 // Make sure that nothing will use this to be closed View.
708 guiApp->unregisterView(this);
710 if (isFullScreen()) {
711 // Switch off fullscreen before closing.
716 // Make sure the timer time out will not trigger a statusbar update.
717 d.statusbar_timer_.stop();
719 // Saving fullscreen requires additional tweaks in the toolbar code.
720 // It wouldn't also work under linux natively.
721 if (lyxrc.allow_geometry_session) {
722 // Save this window geometry and layout.
724 // Then the toolbar private states.
725 ToolbarMap::iterator end = d.toolbars_.end();
726 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
727 it->second->saveSession();
728 // Now take care of all other dialogs:
729 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
730 for (; it!= d.dialogs_.end(); ++it)
731 it->second->saveSession();
734 close_event->accept();
738 void GuiView::dragEnterEvent(QDragEnterEvent * event)
740 if (event->mimeData()->hasUrls())
742 /// \todo Ask lyx-devel is this is enough:
743 /// if (event->mimeData()->hasFormat("text/plain"))
744 /// event->acceptProposedAction();
748 void GuiView::dropEvent(QDropEvent * event)
750 QList<QUrl> files = event->mimeData()->urls();
754 LYXERR(Debug::GUI, "GuiView::dropEvent: got URLs!");
755 for (int i = 0; i != files.size(); ++i) {
756 string const file = os::internal_path(fromqstr(
757 files.at(i).toLocalFile()));
761 string const ext = support::getExtension(file);
762 vector<const Format *> found_formats;
764 // Find all formats that have the correct extension.
765 vector<const Format *> const & import_formats
766 = theConverters().importableFormats();
767 vector<const Format *>::const_iterator it = import_formats.begin();
768 for (; it != import_formats.end(); ++it)
769 if ((*it)->extension() == ext)
770 found_formats.push_back(*it);
773 if (found_formats.size() >= 1) {
774 if (found_formats.size() > 1) {
775 //FIXME: show a dialog to choose the correct importable format
777 "Multiple importable formats found, selecting first");
779 string const arg = found_formats[0]->name() + " " + file;
780 cmd = FuncRequest(LFUN_BUFFER_IMPORT, arg);
783 //FIXME: do we have to explicitly check whether it's a lyx file?
785 "No formats found, trying to open it as a lyx file");
786 cmd = FuncRequest(LFUN_FILE_OPEN, file);
789 // Asynchronously post the event. DropEvent usually comes
790 // from the BufferView. But reloading a file might close
791 // the BufferView from within its own event handler.
792 guiApp->dispatchDelayed(cmd);
798 void GuiView::message(docstring const & str)
800 if (ForkedProcess::iAmAChild())
803 // call is moved to GUI-thread by GuiProgress
804 d.progress_->appendMessage(toqstr(str));
808 void GuiView::clearMessageText()
810 message(docstring());
814 void GuiView::updateStatusBarMessage(QString const & str)
816 statusBar()->showMessage(str);
817 d.statusbar_timer_.stop();
818 d.statusbar_timer_.start(3000);
822 void GuiView::smallSizedIcons()
824 setIconSize(QSize(d.smallIconSize, d.smallIconSize));
828 void GuiView::normalSizedIcons()
830 setIconSize(QSize(d.normalIconSize, d.normalIconSize));
834 void GuiView::bigSizedIcons()
836 setIconSize(QSize(d.bigIconSize, d.bigIconSize));
840 void GuiView::clearMessage()
842 // FIXME: This code was introduced in r19643 to fix bug #4123. However,
843 // the hasFocus function mostly returns false, even if the focus is on
844 // a workarea in this view.
848 d.statusbar_timer_.stop();
852 void GuiView::updateWindowTitle(GuiWorkArea * wa)
854 if (wa != d.current_work_area_
855 || wa->bufferView().buffer().isInternal())
857 setWindowTitle(qt_("LyX: ") + wa->windowTitle());
858 setWindowIconText(wa->windowIconText());
862 void GuiView::on_currentWorkAreaChanged(GuiWorkArea * wa)
865 disconnectBufferView();
866 connectBufferView(wa->bufferView());
867 connectBuffer(wa->bufferView().buffer());
868 d.current_work_area_ = wa;
869 QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
870 this, SLOT(updateWindowTitle(GuiWorkArea *)));
871 updateWindowTitle(wa);
875 // The document settings needs to be reinitialised.
876 updateDialog("document", "");
878 // Buffer-dependent dialogs must be updated. This is done here because
879 // some dialogs require buffer()->text.
884 void GuiView::on_lastWorkAreaRemoved()
887 // We already are in a close event. Nothing more to do.
890 if (d.splitter_->count() > 1)
891 // We have a splitter so don't close anything.
894 // Reset and updates the dialogs.
895 d.toc_models_.reset(0);
896 updateDialog("document", "");
899 resetWindowTitleAndIconText();
902 if (lyxrc.open_buffers_in_tabs)
903 // Nothing more to do, the window should stay open.
906 if (guiApp->viewIds().size() > 1) {
912 // On Mac we also close the last window because the application stay
913 // resident in memory. On other platforms we don't close the last
914 // window because this would quit the application.
920 void GuiView::updateStatusBar()
922 // let the user see the explicit message
923 if (d.statusbar_timer_.isActive())
930 void GuiView::showMessage()
932 QString msg = toqstr(theGuiApp()->viewStatusMessage());
934 BufferView const * bv = currentBufferView();
936 msg = toqstr(bv->cursor().currentState());
938 msg = qt_("Welcome to LyX!");
940 statusBar()->showMessage(msg);
944 bool GuiView::event(QEvent * e)
948 // Useful debug code:
949 //case QEvent::ActivationChange:
950 //case QEvent::WindowDeactivate:
951 //case QEvent::Paint:
952 //case QEvent::Enter:
953 //case QEvent::Leave:
954 //case QEvent::HoverEnter:
955 //case QEvent::HoverLeave:
956 //case QEvent::HoverMove:
957 //case QEvent::StatusTip:
958 //case QEvent::DragEnter:
959 //case QEvent::DragLeave:
963 case QEvent::WindowActivate: {
964 GuiView * old_view = guiApp->currentView();
965 if (this == old_view) {
967 return QMainWindow::event(e);
969 if (old_view && old_view->currentBufferView()) {
970 // save current selection to the selection buffer to allow
971 // middle-button paste in this window.
972 cap::saveSelection(old_view->currentBufferView()->cursor());
974 guiApp->setCurrentView(this);
975 if (d.current_work_area_) {
976 BufferView & bv = d.current_work_area_->bufferView();
977 connectBufferView(bv);
978 connectBuffer(bv.buffer());
979 // The document structure, name and dialogs might have
980 // changed in another view.
982 // The document settings needs to be reinitialised.
983 updateDialog("document", "");
986 resetWindowTitleAndIconText();
989 return QMainWindow::event(e);
992 case QEvent::ShortcutOverride: {
995 #if (!defined Q_WS_X11) || (QT_VERSION >= 0x040500)
996 if (isFullScreen() && menuBar()->isHidden()) {
997 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
998 // FIXME: we should also try to detect special LyX shortcut such as
999 // Alt-P and Alt-M. Right now there is a hack in
1000 // GuiWorkArea::processKeySym() that hides again the menubar for
1002 if (ke->modifiers() & Qt::AltModifier && ke->key() != Qt::Key_Alt) {
1004 return QMainWindow::event(e);
1008 return QMainWindow::event(e);
1012 return QMainWindow::event(e);
1016 void GuiView::resetWindowTitleAndIconText()
1018 setWindowTitle(qt_("LyX"));
1019 setWindowIconText(qt_("LyX"));
1022 bool GuiView::focusNextPrevChild(bool /*next*/)
1029 bool GuiView::busy() const
1035 void GuiView::setBusy(bool busy)
1038 if (d.current_work_area_) {
1039 d.current_work_area_->setUpdatesEnabled(!busy);
1041 d.current_work_area_->stopBlinkingCursor();
1043 d.current_work_area_->startBlinkingCursor();
1047 QApplication::setOverrideCursor(Qt::WaitCursor);
1049 QApplication::restoreOverrideCursor();
1053 GuiWorkArea * GuiView::workArea(Buffer & buffer)
1055 if (currentWorkArea()
1056 && ¤tWorkArea()->bufferView().buffer() == &buffer)
1057 return (GuiWorkArea *) currentWorkArea();
1058 if (TabWorkArea * twa = d.currentTabWorkArea())
1059 return twa->workArea(buffer);
1064 GuiWorkArea * GuiView::addWorkArea(Buffer & buffer)
1066 // Automatically create a TabWorkArea if there are none yet.
1067 TabWorkArea * tab_widget = d.splitter_->count()
1068 ? d.currentTabWorkArea() : addTabWorkArea();
1069 return tab_widget->addWorkArea(buffer, *this);
1073 TabWorkArea * GuiView::addTabWorkArea()
1075 TabWorkArea * twa = new TabWorkArea;
1076 QObject::connect(twa, SIGNAL(currentWorkAreaChanged(GuiWorkArea *)),
1077 this, SLOT(on_currentWorkAreaChanged(GuiWorkArea *)));
1078 QObject::connect(twa, SIGNAL(lastWorkAreaRemoved()),
1079 this, SLOT(on_lastWorkAreaRemoved()));
1081 d.splitter_->addWidget(twa);
1082 d.stack_widget_->setCurrentWidget(d.splitter_);
1087 GuiWorkArea const * GuiView::currentWorkArea() const
1089 return d.current_work_area_;
1093 GuiWorkArea * GuiView::currentWorkArea()
1095 return d.current_work_area_;
1099 GuiWorkArea const * GuiView::currentMainWorkArea() const
1101 if (!d.currentTabWorkArea())
1103 return d.currentTabWorkArea()->currentWorkArea();
1107 GuiWorkArea * GuiView::currentMainWorkArea()
1109 if (!d.currentTabWorkArea())
1111 return d.currentTabWorkArea()->currentWorkArea();
1115 void GuiView::setCurrentWorkArea(GuiWorkArea * wa)
1117 LYXERR(Debug::DEBUG, "Setting current wa: " << wa << endl);
1119 d.current_work_area_ = 0;
1124 // FIXME: I've no clue why this is here and why it accesses
1125 // theGuiApp()->currentView, which might be 0 (bug 6464).
1126 // See also 27525 (vfr).
1127 if (theGuiApp()->currentView() == this
1128 && theGuiApp()->currentView()->currentWorkArea() == wa)
1131 if (currentBufferView())
1132 cap::saveSelection(currentBufferView()->cursor());
1134 theGuiApp()->setCurrentView(this);
1135 d.current_work_area_ = wa;
1136 for (int i = 0; i != d.splitter_->count(); ++i) {
1137 if (d.tabWorkArea(i)->setCurrentWorkArea(wa)) {
1138 //if (d.current_main_work_area_)
1139 // d.current_main_work_area_->setFrameStyle(QFrame::NoFrame);
1140 d.current_main_work_area_ = wa;
1141 //d.current_main_work_area_->setFrameStyle(QFrame::Box | QFrame::Plain);
1142 //d.current_main_work_area_->setLineWidth(2);
1143 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() << ", Current main wa: " << currentMainWorkArea());
1147 LYXERR(Debug::DEBUG, "This is not a tabbed wa");
1148 on_currentWorkAreaChanged(wa);
1149 BufferView & bv = wa->bufferView();
1150 bv.cursor().fixIfBroken();
1152 wa->setUpdatesEnabled(true);
1153 LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() << ", Current main wa: " << currentMainWorkArea());
1157 void GuiView::removeWorkArea(GuiWorkArea * wa)
1159 LASSERT(wa, return);
1160 if (wa == d.current_work_area_) {
1162 disconnectBufferView();
1163 d.current_work_area_ = 0;
1164 d.current_main_work_area_ = 0;
1167 bool found_twa = false;
1168 for (int i = 0; i != d.splitter_->count(); ++i) {
1169 TabWorkArea * twa = d.tabWorkArea(i);
1170 if (twa->removeWorkArea(wa)) {
1171 // Found in this tab group, and deleted the GuiWorkArea.
1173 if (twa->count() != 0) {
1174 if (d.current_work_area_ == 0)
1175 // This means that we are closing the current GuiWorkArea, so
1176 // switch to the next GuiWorkArea in the found TabWorkArea.
1177 setCurrentWorkArea(twa->currentWorkArea());
1179 // No more WorkAreas in this tab group, so delete it.
1186 // It is not a tabbed work area (i.e., the search work area), so it
1187 // should be deleted by other means.
1188 LASSERT(found_twa, /* */);
1190 if (d.current_work_area_ == 0) {
1191 if (d.splitter_->count() != 0) {
1192 TabWorkArea * twa = d.currentTabWorkArea();
1193 setCurrentWorkArea(twa->currentWorkArea());
1195 // No more work areas, switch to the background widget.
1196 setCurrentWorkArea(0);
1202 LayoutBox * GuiView::getLayoutDialog() const
1208 void GuiView::updateLayoutList()
1211 d.layout_->updateContents(false);
1215 void GuiView::updateToolbars()
1217 ToolbarMap::iterator end = d.toolbars_.end();
1218 if (d.current_work_area_) {
1220 d.current_work_area_->bufferView().cursor().inMathed()
1221 && !d.current_work_area_->bufferView().cursor().inRegexped();
1223 lyx::getStatus(FuncRequest(LFUN_LAYOUT_TABULAR)).enabled();
1225 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).enabled() &&
1226 lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).onOff(true);
1227 bool const mathmacrotemplate =
1228 lyx::getStatus(FuncRequest(LFUN_IN_MATHMACROTEMPLATE)).enabled();
1230 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1231 it->second->update(math, table, review, mathmacrotemplate);
1233 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1234 it->second->update(false, false, false, false);
1238 void GuiView::setBuffer(Buffer * newBuffer)
1240 LYXERR(Debug::DEBUG, "Setting buffer: " << newBuffer << endl);
1241 LASSERT(newBuffer, return);
1244 GuiWorkArea * wa = workArea(*newBuffer);
1246 newBuffer->masterBuffer()->updateBuffer();
1247 wa = addWorkArea(*newBuffer);
1249 //Disconnect the old buffer...there's no new one.
1252 connectBuffer(*newBuffer);
1253 connectBufferView(wa->bufferView());
1254 setCurrentWorkArea(wa);
1260 void GuiView::connectBuffer(Buffer & buf)
1262 buf.setGuiDelegate(this);
1266 void GuiView::disconnectBuffer()
1268 if (d.current_work_area_)
1269 d.current_work_area_->bufferView().buffer().setGuiDelegate(0);
1273 void GuiView::connectBufferView(BufferView & bv)
1275 bv.setGuiDelegate(this);
1279 void GuiView::disconnectBufferView()
1281 if (d.current_work_area_)
1282 d.current_work_area_->bufferView().setGuiDelegate(0);
1286 void GuiView::errors(string const & error_type, bool from_master)
1288 ErrorList & el = from_master ?
1289 currentBufferView()->buffer().masterBuffer()->errorList(error_type)
1290 : currentBufferView()->buffer().errorList(error_type);
1291 string data = error_type;
1293 data = "from_master|" + error_type;
1295 showDialog("errorlist", data);
1299 void GuiView::updateTocItem(string const & type, DocIterator const & dit)
1301 d.toc_models_.updateItem(toqstr(type), dit);
1305 void GuiView::structureChanged()
1307 d.toc_models_.reset(documentBufferView());
1308 // Navigator needs more than a simple update in this case. It needs to be
1310 updateDialog("toc", "");
1314 void GuiView::updateDialog(string const & name, string const & data)
1316 if (!isDialogVisible(name))
1319 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
1320 if (it == d.dialogs_.end())
1323 Dialog * const dialog = it->second.get();
1324 if (dialog->isVisibleView())
1325 dialog->initialiseParams(data);
1329 BufferView * GuiView::documentBufferView()
1331 return currentMainWorkArea()
1332 ? ¤tMainWorkArea()->bufferView()
1337 BufferView const * GuiView::documentBufferView() const
1339 return currentMainWorkArea()
1340 ? ¤tMainWorkArea()->bufferView()
1345 BufferView * GuiView::currentBufferView()
1347 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1351 BufferView const * GuiView::currentBufferView() const
1353 return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1357 #if (QT_VERSION >= 0x040400)
1358 docstring GuiView::GuiViewPrivate::saveAndDestroy(Buffer const * orig, Buffer * buffer, FileName const & fname)
1361 FileName const tmp_ret = FileName::tempName("lyxauto");
1362 if (!tmp_ret.empty()) {
1363 if (buffer->writeFile(tmp_ret))
1364 failed = !tmp_ret.moveTo(fname);
1367 // failed to write/rename tmp_ret so try writing direct
1368 failed = buffer->writeFile(fname);
1371 busyBuffers.remove(orig);
1373 ? _("Automatic save failed!")
1374 : _("Automatic save done.");
1379 void GuiView::autoSave()
1381 LYXERR(Debug::INFO, "Running autoSave()");
1383 Buffer * buffer = documentBufferView()
1384 ? &documentBufferView()->buffer() : 0;
1388 #if (QT_VERSION >= 0x040400)
1389 GuiViewPrivate::busyBuffers.insert(buffer);
1390 QFuture<docstring> f = QtConcurrent::run(GuiViewPrivate::saveAndDestroy, buffer, buffer->clone(),
1391 buffer->getAutosaveFileName());
1392 d.autosave_watcher_.setFuture(f);
1399 void GuiView::resetAutosaveTimers()
1402 d.autosave_timeout_.restart();
1406 bool GuiView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1409 Buffer * buf = currentBufferView()
1410 ? ¤tBufferView()->buffer() : 0;
1411 Buffer * doc_buffer = documentBufferView()
1412 ? &(documentBufferView()->buffer()) : 0;
1414 // Check whether we need a buffer
1415 if (!lyxaction.funcHasFlag(cmd.action(), LyXAction::NoBuffer) && !buf) {
1416 // no, exit directly
1417 flag.message(from_utf8(N_("Command not allowed with"
1418 "out any document open")));
1419 flag.setEnabled(false);
1423 if (cmd.origin() == FuncRequest::TOC) {
1424 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
1425 if (!toc || !toc->getStatus(documentBufferView()->cursor(), cmd, flag))
1426 flag.setEnabled(false);
1430 switch(cmd.action()) {
1431 case LFUN_BUFFER_IMPORT:
1434 case LFUN_MASTER_BUFFER_UPDATE:
1435 case LFUN_MASTER_BUFFER_VIEW:
1436 enable = doc_buffer && doc_buffer->parent() != 0
1437 && !d.preview_watcher_.isRunning();
1440 case LFUN_BUFFER_UPDATE:
1441 case LFUN_BUFFER_VIEW: {
1442 if (!doc_buffer || d.preview_watcher_.isRunning()) {
1446 string format = to_utf8(cmd.argument());
1447 if (cmd.argument().empty())
1448 format = doc_buffer->getDefaultOutputFormat();
1449 enable = doc_buffer->isExportableFormat(format);
1453 case LFUN_BUFFER_RELOAD:
1454 enable = doc_buffer && !doc_buffer->isUnnamed()
1455 && doc_buffer->fileName().exists()
1456 && (!doc_buffer->isClean()
1457 || doc_buffer->isExternallyModified(Buffer::timestamp_method));
1460 case LFUN_BUFFER_CHILD_OPEN:
1461 enable = doc_buffer;
1464 case LFUN_BUFFER_WRITE:
1465 enable = doc_buffer && (doc_buffer->isUnnamed() || !doc_buffer->isClean());
1468 //FIXME: This LFUN should be moved to GuiApplication.
1469 case LFUN_BUFFER_WRITE_ALL: {
1470 // We enable the command only if there are some modified buffers
1471 Buffer * first = theBufferList().first();
1476 // We cannot use a for loop as the buffer list is a cycle.
1478 if (!b->isClean()) {
1482 b = theBufferList().next(b);
1483 } while (b != first);
1487 case LFUN_BUFFER_WRITE_ENCRYPTED:
1488 enable = doc_buffer;
1491 case LFUN_BUFFER_WRITE_AS:
1492 enable = doc_buffer;
1495 case LFUN_BUFFER_CLOSE:
1496 enable = doc_buffer;
1499 case LFUN_BUFFER_CLOSE_ALL:
1500 enable = theBufferList().last() != theBufferList().first();
1503 case LFUN_SPLIT_VIEW:
1504 if (cmd.getArg(0) == "vertical")
1505 enable = doc_buffer && (d.splitter_->count() == 1 ||
1506 d.splitter_->orientation() == Qt::Vertical);
1508 enable = doc_buffer && (d.splitter_->count() == 1 ||
1509 d.splitter_->orientation() == Qt::Horizontal);
1512 case LFUN_CLOSE_TAB_GROUP:
1513 enable = d.currentTabWorkArea();
1516 case LFUN_TOOLBAR_TOGGLE: {
1517 string const name = cmd.getArg(0);
1518 if (GuiToolbar * t = toolbar(name))
1519 flag.setOnOff(t->isVisible());
1522 docstring const msg =
1523 bformat(_("Unknown toolbar \"%1$s\""), from_utf8(name));
1529 case LFUN_DROP_LAYOUTS_CHOICE:
1533 case LFUN_UI_TOGGLE:
1534 flag.setOnOff(isFullScreen());
1537 case LFUN_DIALOG_DISCONNECT_INSET:
1540 case LFUN_DIALOG_HIDE:
1541 // FIXME: should we check if the dialog is shown?
1544 case LFUN_DIALOG_TOGGLE:
1545 flag.setOnOff(isDialogVisible(cmd.getArg(0)));
1546 // fall through to set "enable"
1547 case LFUN_DIALOG_SHOW: {
1548 string const name = cmd.getArg(0);
1550 enable = name == "aboutlyx"
1551 || name == "file" //FIXME: should be removed.
1553 || name == "texinfo"
1554 || name == "progress"
1555 || name == "compare";
1556 else if (name == "print")
1557 enable = doc_buffer->isExportable("dvi")
1558 && lyxrc.print_command != "none";
1559 else if (name == "character" || name == "symbols") {
1560 if (!buf || buf->isReadonly())
1563 // FIXME we should consider passthru
1565 Inset const & in = currentBufferView()->cursor().inset();
1566 enable = !in.getLayout().isPassThru();
1569 else if (name == "latexlog")
1570 enable = FileName(doc_buffer->logName()).isReadableFile();
1571 else if (name == "spellchecker")
1572 enable = theSpellChecker() && !doc_buffer->isReadonly();
1573 else if (name == "vclog")
1574 enable = doc_buffer->lyxvc().inUse();
1578 case LFUN_DIALOG_UPDATE: {
1579 string const name = cmd.getArg(0);
1581 enable = name == "prefs";
1585 case LFUN_COMMAND_EXECUTE:
1587 case LFUN_MENU_OPEN:
1588 // Nothing to check.
1591 case LFUN_COMPLETION_INLINE:
1592 if (!d.current_work_area_
1593 || !d.current_work_area_->completer().inlinePossible(
1594 currentBufferView()->cursor()))
1598 case LFUN_COMPLETION_POPUP:
1599 if (!d.current_work_area_
1600 || !d.current_work_area_->completer().popupPossible(
1601 currentBufferView()->cursor()))
1605 case LFUN_COMPLETION_COMPLETE:
1606 if (!d.current_work_area_
1607 || !d.current_work_area_->completer().inlinePossible(
1608 currentBufferView()->cursor()))
1612 case LFUN_COMPLETION_ACCEPT:
1613 if (!d.current_work_area_
1614 || (!d.current_work_area_->completer().popupVisible()
1615 && !d.current_work_area_->completer().inlineVisible()
1616 && !d.current_work_area_->completer().completionAvailable()))
1620 case LFUN_COMPLETION_CANCEL:
1621 if (!d.current_work_area_
1622 || (!d.current_work_area_->completer().popupVisible()
1623 && !d.current_work_area_->completer().inlineVisible()))
1627 case LFUN_BUFFER_ZOOM_OUT:
1628 enable = doc_buffer && lyxrc.zoom > 10;
1631 case LFUN_BUFFER_ZOOM_IN:
1632 enable = doc_buffer;
1635 case LFUN_BUFFER_NEXT:
1636 case LFUN_BUFFER_PREVIOUS:
1637 // FIXME: should we check is there is an previous or next buffer?
1639 case LFUN_BUFFER_SWITCH:
1640 // toggle on the current buffer, but do not toggle off
1641 // the other ones (is that a good idea?)
1643 && to_utf8(cmd.argument()) == doc_buffer->absFileName())
1644 flag.setOnOff(true);
1647 case LFUN_VC_REGISTER:
1648 enable = doc_buffer && !doc_buffer->lyxvc().inUse();
1650 case LFUN_VC_CHECK_IN:
1651 enable = doc_buffer && doc_buffer->lyxvc().checkInEnabled();
1653 case LFUN_VC_CHECK_OUT:
1654 enable = doc_buffer && doc_buffer->lyxvc().checkOutEnabled();
1656 case LFUN_VC_LOCKING_TOGGLE:
1657 enable = doc_buffer && !doc_buffer->isReadonly()
1658 && doc_buffer->lyxvc().lockingToggleEnabled();
1659 flag.setOnOff(enable && doc_buffer->lyxvc().locking());
1661 case LFUN_VC_REVERT:
1662 enable = doc_buffer && doc_buffer->lyxvc().inUse();
1664 case LFUN_VC_UNDO_LAST:
1665 enable = doc_buffer && doc_buffer->lyxvc().undoLastEnabled();
1667 case LFUN_VC_REPO_UPDATE:
1668 enable = doc_buffer && doc_buffer->lyxvc().inUse();
1670 case LFUN_VC_COMMAND: {
1671 if (cmd.argument().empty())
1673 if (!doc_buffer && contains(cmd.getArg(0), 'D'))
1677 case LFUN_VC_COMPARE:
1678 enable = doc_buffer && !cmd.argument().empty()
1679 && doc_buffer->lyxvc().prepareFileRevisionEnabled();
1682 case LFUN_SERVER_GOTO_FILE_ROW:
1684 case LFUN_FORWARD_SEARCH:
1685 enable = !(lyxrc.forward_search_dvi.empty() && lyxrc.forward_search_pdf.empty());
1693 flag.setEnabled(false);
1699 static FileName selectTemplateFile()
1701 FileDialog dlg(qt_("Select template file"));
1702 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1703 dlg.setButton1(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
1705 FileDialog::Result result = dlg.open(toqstr(lyxrc.template_path),
1706 QStringList(qt_("LyX Documents (*.lyx)")));
1708 if (result.first == FileDialog::Later)
1710 if (result.second.isEmpty())
1712 return FileName(fromqstr(result.second));
1715 /// checks if the file is encrypted and creates a decrypted tmp file
1716 #define LYX_ENC_VERSION 1
1717 static FileName decryptedFileName(FileName const & filename)
1719 if (!filename.isEncryptedFile()) {
1723 int encVersion = filename.encryptionVersion();
1724 if (encVersion < 0 || encVersion > LYX_ENC_VERSION) {
1725 Alert::error(_("Encryption"), _("This LyX program is to old to read encrypted file."));
1729 QByteArray encrypted;
1730 QFile file(toqstr(filename.absFileName()));
1731 if (file.open(QIODevice::ReadOnly)) {
1732 encrypted = file.readAll();
1738 CryptographicEncryption enc;
1740 int keytype = filename.encryptionKeytype();
1741 if (keytype == CryptographicEncryption::Password) {
1742 GuiEncryptionDialog dlg;
1743 dlg.setWindowTitle(qt_("Enter Password"));
1745 QString pwd = dlg.password();
1746 key = enc.stringToKey(pwd);
1748 Alert::error(_("Encryption"), _("Don't know how to generate decryption key."));
1752 // remove the encryption prefix
1753 encrypted.remove(0, FileName::encryptionPrefix(LYX_ENC_VERSION, 1).size());
1755 QByteArray decrypted;
1756 if (!enc.decyrpt(encrypted, &decrypted, key)) {
1757 Alert::error(_("Encryption"), _("Error when decryting file."));
1761 // TODO decrypt in memory
1762 // TODO find a better solution than showing the
1763 // generated filename
1764 FileName tempDecrypted = FileName::tempName();
1765 QFile defile(toqstr(tempDecrypted.absFileName()));
1766 if (defile.open(QIODevice::WriteOnly)) {
1767 defile.write(decrypted);
1770 return tempDecrypted;
1774 Buffer * GuiView::loadDocument(FileName const & filenameIn, bool tolastfiles)
1778 FileName filename = decryptedFileName(filenameIn);
1780 Buffer * newBuffer = checkAndLoadLyXFile(filename);
1783 message(_("Document not loaded."));
1788 setBuffer(newBuffer);
1790 // scroll to the position when the file was last closed
1791 if (lyxrc.use_lastfilepos) {
1792 LastFilePosSection::FilePos filepos =
1793 theSession().lastFilePos().load(filename);
1794 documentBufferView()->moveToPosition(filepos.pit, filepos.pos, 0, 0);
1798 theSession().lastFiles().add(filename);
1805 void GuiView::openDocument(string const & fname)
1807 string initpath = lyxrc.document_path;
1809 if (documentBufferView()) {
1810 string const trypath = documentBufferView()->buffer().filePath();
1811 // If directory is writeable, use this as default.
1812 if (FileName(trypath).isDirWritable())
1818 if (fname.empty()) {
1819 FileDialog dlg(qt_("Select document to open"), LFUN_FILE_OPEN);
1820 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1821 dlg.setButton2(qt_("Examples|#E#e"),
1822 toqstr(addPath(package().system_support().absFileName(), "examples")));
1824 QStringList filter(qt_("LyX Documents (*.lyx)"));
1825 filter << qt_("LyX-1.3.x Documents (*.lyx13)")
1826 << qt_("LyX-1.4.x Documents (*.lyx14)")
1827 << qt_("LyX-1.5.x Documents (*.lyx15)")
1828 << qt_("LyX-1.6.x Documents (*.lyx16)");
1829 FileDialog::Result result =
1830 dlg.open(toqstr(initpath), filter);
1832 if (result.first == FileDialog::Later)
1835 filename = fromqstr(result.second);
1837 // check selected filename
1838 if (filename.empty()) {
1839 message(_("Canceled."));
1845 // get absolute path of file and add ".lyx" to the filename if
1847 FileName const fullname =
1848 fileSearch(string(), filename, "lyx", support::may_not_exist);
1849 if (!fullname.empty())
1850 filename = fullname.absFileName();
1852 if (!fullname.onlyPath().isDirectory()) {
1853 Alert::warning(_("Invalid filename"),
1854 bformat(_("The directory in the given path\n%1$s\ndoes not exist."),
1855 from_utf8(fullname.absFileName())));
1859 // if the file doesn't exist and isn't already open (bug 6645),
1860 // let the user create one
1861 if (!fullname.exists() && !theBufferList().exists(fullname)) {
1862 // the user specifically chose this name. Believe him.
1863 Buffer * const b = newFile(filename, string(), true);
1869 docstring const disp_fn = makeDisplayPath(filename);
1870 message(bformat(_("Opening document %1$s..."), disp_fn));
1873 Buffer * buf = loadDocument(fullname);
1875 // I don't think this is needed, since it will be done in setBuffer().
1876 // buf->updateBuffer();
1878 buf->errors("Parse");
1879 str2 = bformat(_("Document %1$s opened."), disp_fn);
1880 if (buf->lyxvc().inUse())
1881 str2 += " " + from_utf8(buf->lyxvc().versionString()) +
1882 " " + _("Version control detected.");
1884 str2 = bformat(_("Could not open document %1$s"), disp_fn);
1889 // FIXME: clean that
1890 static bool import(GuiView * lv, FileName const & filename,
1891 string const & format, ErrorList & errorList)
1893 FileName const lyxfile(support::changeExtension(filename.absFileName(), ".lyx"));
1895 string loader_format;
1896 vector<string> loaders = theConverters().loaders();
1897 if (find(loaders.begin(), loaders.end(), format) == loaders.end()) {
1898 for (vector<string>::const_iterator it = loaders.begin();
1899 it != loaders.end(); ++it) {
1900 if (!theConverters().isReachable(format, *it))
1903 string const tofile =
1904 support::changeExtension(filename.absFileName(),
1905 formats.extension(*it));
1906 if (!theConverters().convert(0, filename, FileName(tofile),
1907 filename, format, *it, errorList))
1909 loader_format = *it;
1912 if (loader_format.empty()) {
1913 frontend::Alert::error(_("Couldn't import file"),
1914 bformat(_("No information for importing the format %1$s."),
1915 formats.prettyName(format)));
1919 loader_format = format;
1921 if (loader_format == "lyx") {
1922 Buffer * buf = lv->loadDocument(lyxfile);
1925 // I don't think this is needed, since it will be done in setBuffer().
1926 // buf->updateBuffer();
1928 buf->errors("Parse");
1930 Buffer * const b = newFile(lyxfile.absFileName(), string(), true);
1934 bool as_paragraphs = loader_format == "textparagraph";
1935 string filename2 = (loader_format == format) ? filename.absFileName()
1936 : support::changeExtension(filename.absFileName(),
1937 formats.extension(loader_format));
1938 lv->currentBufferView()->insertPlaintextFile(FileName(filename2),
1940 guiApp->setCurrentView(lv);
1941 lyx::dispatch(FuncRequest(LFUN_MARK_OFF));
1948 void GuiView::importDocument(string const & argument)
1951 string filename = split(argument, format, ' ');
1953 LYXERR(Debug::INFO, format << " file: " << filename);
1955 // need user interaction
1956 if (filename.empty()) {
1957 string initpath = lyxrc.document_path;
1958 if (documentBufferView()) {
1959 string const trypath = documentBufferView()->buffer().filePath();
1960 // If directory is writeable, use this as default.
1961 if (FileName(trypath).isDirWritable())
1965 docstring const text = bformat(_("Select %1$s file to import"),
1966 formats.prettyName(format));
1968 FileDialog dlg(toqstr(text), LFUN_BUFFER_IMPORT);
1969 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1970 dlg.setButton2(qt_("Examples|#E#e"),
1971 toqstr(addPath(package().system_support().absFileName(), "examples")));
1973 docstring filter = formats.prettyName(format);
1976 filter += from_utf8(formats.extension(format));
1979 FileDialog::Result result =
1980 dlg.open(toqstr(initpath), fileFilters(toqstr(filter)));
1982 if (result.first == FileDialog::Later)
1985 filename = fromqstr(result.second);
1987 // check selected filename
1988 if (filename.empty())
1989 message(_("Canceled."));
1992 if (filename.empty())
1995 // get absolute path of file
1996 FileName const fullname(support::makeAbsPath(filename));
1998 FileName const lyxfile(support::changeExtension(fullname.absFileName(), ".lyx"));
2000 // Check if the document already is open
2001 Buffer * buf = theBufferList().getBuffer(lyxfile);
2004 if (!closeBuffer()) {
2005 message(_("Canceled."));
2010 docstring const displaypath = makeDisplayPath(lyxfile.absFileName(), 30);
2012 // if the file exists already, and we didn't do
2013 // -i lyx thefile.lyx, warn
2014 if (lyxfile.exists() && fullname != lyxfile) {
2016 docstring text = bformat(_("The document %1$s already exists.\n\n"
2017 "Do you want to overwrite that document?"), displaypath);
2018 int const ret = Alert::prompt(_("Overwrite document?"),
2019 text, 0, 1, _("&Overwrite"), _("&Cancel"));
2022 message(_("Canceled."));
2027 message(bformat(_("Importing %1$s..."), displaypath));
2028 ErrorList errorList;
2029 if (import(this, fullname, format, errorList))
2030 message(_("imported."));
2032 message(_("file not imported!"));
2034 // FIXME (Abdel 12/08/06): Is there a need to display the error list here?
2038 void GuiView::newDocument(string const & filename, bool from_template)
2040 FileName initpath(lyxrc.document_path);
2041 if (documentBufferView()) {
2042 FileName const trypath(documentBufferView()->buffer().filePath());
2043 // If directory is writeable, use this as default.
2044 if (trypath.isDirWritable())
2048 string templatefile;
2049 if (from_template) {
2050 templatefile = selectTemplateFile().absFileName();
2051 if (templatefile.empty())
2056 if (filename.empty())
2057 b = newUnnamedFile(initpath, to_utf8(_("newfile")), templatefile);
2059 b = newFile(filename, templatefile, true);
2064 // If no new document could be created, it is unsure
2065 // whether there is a valid BufferView.
2066 if (currentBufferView())
2067 // Ensure the cursor is correctly positioned on screen.
2068 currentBufferView()->showCursor();
2072 void GuiView::insertLyXFile(docstring const & fname)
2074 BufferView * bv = documentBufferView();
2079 FileName filename(to_utf8(fname));
2081 if (!filename.empty()) {
2082 bv->insertLyXFile(filename);
2086 // Launch a file browser
2088 string initpath = lyxrc.document_path;
2089 string const trypath = bv->buffer().filePath();
2090 // If directory is writeable, use this as default.
2091 if (FileName(trypath).isDirWritable())
2095 FileDialog dlg(qt_("Select LyX document to insert"), LFUN_FILE_INSERT);
2096 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2097 dlg.setButton2(qt_("Examples|#E#e"),
2098 toqstr(addPath(package().system_support().absFileName(),
2101 FileDialog::Result result = dlg.open(toqstr(initpath),
2102 QStringList(qt_("LyX Documents (*.lyx)")));
2104 if (result.first == FileDialog::Later)
2108 filename.set(fromqstr(result.second));
2110 // check selected filename
2111 if (filename.empty()) {
2112 // emit message signal.
2113 message(_("Canceled."));
2117 bv->insertLyXFile(filename);
2121 void GuiView::insertPlaintextFile(docstring const & fname,
2124 BufferView * bv = documentBufferView();
2128 if (!fname.empty() && !FileName::isAbsolute(to_utf8(fname))) {
2129 message(_("Absolute filename expected."));
2134 FileName filename(to_utf8(fname));
2136 if (!filename.empty()) {
2137 bv->insertPlaintextFile(filename, asParagraph);
2141 FileDialog dlg(qt_("Select file to insert"), (asParagraph ?
2142 LFUN_FILE_INSERT_PLAINTEXT_PARA : LFUN_FILE_INSERT_PLAINTEXT));
2144 FileDialog::Result result = dlg.open(toqstr(bv->buffer().filePath()),
2145 QStringList(qt_("All Files (*)")));
2147 if (result.first == FileDialog::Later)
2151 filename.set(fromqstr(result.second));
2153 // check selected filename
2154 if (filename.empty()) {
2155 // emit message signal.
2156 message(_("Canceled."));
2160 bv->insertPlaintextFile(filename, asParagraph);
2164 bool GuiView::renameBuffer(Buffer & b, docstring const & newname)
2166 FileName fname = b.fileName();
2167 FileName const oldname = fname;
2169 if (!newname.empty()) {
2171 fname = support::makeAbsPath(to_utf8(newname), oldname.onlyPath().absFileName());
2173 // Switch to this Buffer.
2176 // No argument? Ask user through dialog.
2178 FileDialog dlg(qt_("Choose a filename to save document as"),
2179 LFUN_BUFFER_WRITE_AS);
2180 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2181 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
2183 if (!isLyXFileName(fname.absFileName()))
2184 fname.changeExtension(".lyx");
2186 FileDialog::Result result =
2187 dlg.save(toqstr(fname.onlyPath().absFileName()),
2188 QStringList(qt_("LyX Documents (*.lyx)")),
2189 toqstr(fname.onlyFileName()));
2191 if (result.first == FileDialog::Later)
2194 fname.set(fromqstr(result.second));
2199 if (!isLyXFileName(fname.absFileName()))
2200 fname.changeExtension(".lyx");
2203 // fname is now the new Buffer location.
2204 if (FileName(fname).exists()) {
2205 docstring const file = makeDisplayPath(fname.absFileName(), 30);
2206 docstring text = bformat(_("The document %1$s already "
2207 "exists.\n\nDo you want to "
2208 "overwrite that document?"),
2210 int const ret = Alert::prompt(_("Overwrite document?"),
2211 text, 0, 2, _("&Overwrite"), _("&Rename"), _("&Cancel"));
2214 case 1: return renameBuffer(b, docstring());
2215 case 2: return false;
2219 FileName oldauto = b.getAutosaveFileName();
2221 // Ok, change the name of the buffer
2222 b.setFileName(fname.absFileName());
2224 bool unnamed = b.isUnnamed();
2225 b.setUnnamed(false);
2226 b.saveCheckSum(fname);
2228 // bring the autosave file with us, just in case.
2229 b.moveAutosaveFile(oldauto);
2231 if (!saveBuffer(b)) {
2232 oldauto = b.getAutosaveFileName();
2233 b.setFileName(oldname.absFileName());
2234 b.setUnnamed(unnamed);
2235 b.saveCheckSum(oldname);
2236 b.moveAutosaveFile(oldauto);
2240 // the file has now been saved to the new location.
2241 // we need to check that the locations of child buffers
2243 b.checkChildBuffers();
2249 bool GuiView::saveBuffer(Buffer & b, ostream* stream)
2251 if (workArea(b) && workArea(b)->inDialogMode())
2255 return renameBuffer(b, docstring());
2257 if ( (stream ? b.write(*stream) : b.save()) ) {
2258 theSession().lastFiles().add(b.fileName());
2262 // Switch to this Buffer.
2265 // FIXME: we don't tell the user *WHY* the save failed !!
2266 docstring const file = makeDisplayPath(b.absFileName(), 30);
2267 docstring text = bformat(_("The document %1$s could not be saved.\n\n"
2268 "Do you want to rename the document and "
2269 "try again?"), file);
2270 int const ret = Alert::prompt(_("Rename and save?"),
2271 text, 0, 2, _("&Rename"), _("&Retry"), _("&Cancel"));
2274 if (!renameBuffer(b, docstring()))
2283 return saveBuffer(b, stream);
2287 bool GuiView::saveBufferEncrypted(Buffer & b)
2289 FileName fname = b.fileName();
2291 // Switch to this Buffer.
2294 // No argument? Ask user through dialog.
2296 FileDialog dlg(qt_("Choose a filename to export document"),
2297 LFUN_BUFFER_WRITE_AS);
2298 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2299 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
2301 if (!isLyXFileName(fname.absFileName()))
2302 fname.changeExtension(".lyx");
2304 FileDialog::Result result =
2305 dlg.save(toqstr(fname.onlyPath().absFileName()),
2306 QStringList(qt_("LyX Documents (*.lyx)")),
2307 toqstr(fname.onlyFileName()));
2309 if (result.first == FileDialog::Later)
2312 fname.set(fromqstr(result.second));
2317 if (!isLyXFileName(fname.absFileName()))
2318 fname.changeExtension(".lyx");
2321 // fname is now the new Buffer location.
2322 if (FileName(fname).exists()) {
2323 docstring const file = makeDisplayPath(fname.absFileName(), 30);
2324 docstring text = bformat(_("The document %1$s already "
2325 "exists.\n\nDo you want to "
2326 "overwrite that document?"),
2328 int const ret = Alert::prompt(_("Overwrite document?"),
2329 text, 0, 2, _("&Overwrite"), _("&Rename"), _("&Cancel"));
2333 case 2: return false;
2337 FileName oldauto = b.getAutosaveFileName();
2339 // bring the autosave file with us, just in case.
2340 b.moveAutosaveFile(oldauto);
2342 stringbuf stringBuffer(ios::out|ios::trunc);
2343 ostream stream(&stringBuffer);
2344 if (!saveBuffer(b, &stream)) {
2348 // the file has now been saved to the new location.
2349 // we need to check that the locations of child buffers
2351 b.checkChildBuffers();
2354 GuiEncryptionDialog pwddlg;
2355 pwddlg.setWindowTitle(qt_("Enter Password"));
2357 if (pwddlg.result() != QDialog::Accepted)
2359 QString pwd = pwddlg.password();
2361 pwddlg.setWindowTitle(qt_("Enter Password again"));
2362 pwddlg.clearPassword();
2364 if (pwddlg.result() != QDialog::Accepted)
2366 QString pwd2 = pwddlg.password();
2369 Alert::error(_("Password"), _("Passwords do not match"));
2373 string fileString = stringBuffer.str();
2374 QByteArray data(fileString.c_str(), fileString.size());
2376 CryptographicEncryption enc;
2377 QByteArray key = enc.stringToKey(pwd);
2379 QByteArray encrypted;
2380 if (!enc.encyrpt(data, &encrypted, key)) {
2381 Alert::error(_("Encryption"), _("Error when encrypting file"));
2386 QByteArray decrypted;
2387 if (!enc.decyrpt(encrypted, &decrypted, key) || data != decrypted) {
2388 Alert::error(_("Encryption"), _("Error when verifying encrypted file"));
2392 QString guessStr = toqstr(FileName::encryptionPrefix(LYX_ENC_VERSION, CryptographicEncryption::Password));
2393 QByteArray bytestoSave = guessStr.toAscii() + encrypted;
2395 QFile file(toqstr(fname.absFileName()));
2396 if (file.open(QIODevice::WriteOnly)) {
2397 file.write(bytestoSave);
2403 bool GuiView::hideWorkArea(GuiWorkArea * wa)
2405 return closeWorkArea(wa, false);
2409 bool GuiView::closeWorkArea(GuiWorkArea * wa)
2411 Buffer & buf = wa->bufferView().buffer();
2412 return closeWorkArea(wa, !buf.parent());
2416 bool GuiView::closeBuffer()
2418 GuiWorkArea * wa = currentMainWorkArea();
2419 setCurrentWorkArea(wa);
2420 Buffer & buf = wa->bufferView().buffer();
2421 return wa && closeWorkArea(wa, !buf.parent());
2425 void GuiView::writeSession() const {
2426 GuiWorkArea const * active_wa = currentMainWorkArea();
2427 for (int i = 0; i < d.splitter_->count(); ++i) {
2428 TabWorkArea * twa = d.tabWorkArea(i);
2429 for (int j = 0; j < twa->count(); ++j) {
2430 GuiWorkArea * wa = static_cast<GuiWorkArea *>(twa->widget(j));
2431 Buffer & buf = wa->bufferView().buffer();
2432 theSession().lastOpened().add(buf.fileName(), wa == active_wa);
2438 bool GuiView::closeBufferAll()
2440 // Close the workareas in all other views
2441 QList<int> const ids = guiApp->viewIds();
2442 for (int i = 0; i != ids.size(); ++i) {
2443 if (id_ != ids[i] && !guiApp->view(ids[i]).closeWorkAreaAll())
2447 // Close our own workareas
2448 if (!closeWorkAreaAll())
2451 // Now close the hidden buffers. We prevent hidden buffers from being
2452 // dirty, so we can just close them.
2453 theBufferList().closeAll();
2458 bool GuiView::closeWorkAreaAll()
2460 setCurrentWorkArea(currentMainWorkArea());
2462 // We might be in a situation that there is still a tabWorkArea, but
2463 // there are no tabs anymore. This can happen when we get here after a
2464 // TabWorkArea::lastWorkAreaRemoved() signal. Therefore we count how
2465 // many TabWorkArea's have no documents anymore.
2468 // We have to call count() each time, because it can happen that
2469 // more than one splitter will disappear in one iteration (bug 5998).
2470 for (; d.splitter_->count() > empty_twa; ) {
2471 TabWorkArea * twa = d.tabWorkArea(empty_twa);
2473 if (twa->count() == 0)
2476 setCurrentWorkArea(twa->currentWorkArea());
2477 if (!closeTabWorkArea(twa))
2485 bool GuiView::closeWorkArea(GuiWorkArea * wa, bool close_buffer)
2490 Buffer & buf = wa->bufferView().buffer();
2492 if (close_buffer && GuiViewPrivate::busyBuffers.contains(&buf)) {
2493 Alert::warning(_("Close document "), _("Document could not be closed because it is processed by LyX."));
2498 return closeBuffer(buf);
2500 if (!inMultiTabs(wa))
2501 if (!saveBufferIfNeeded(buf, true))
2509 bool GuiView::closeBuffer(Buffer & buf)
2511 // If we are in a close_event all children will be closed in some time,
2512 // so no need to do it here. This will ensure that the children end up
2513 // in the session file in the correct order. If we close the master
2514 // buffer, we can close or release the child buffers here too.
2516 vector<Buffer *> clist = buf.getChildren(false);
2517 for (vector<Buffer *>::const_iterator it = clist.begin();
2518 it != clist.end(); ++it) {
2519 // If a child is dirty, do not close
2520 // without user intervention
2521 //FIXME: should we look in other tabworkareas?
2522 Buffer * child_buf = *it;
2523 GuiWorkArea * child_wa = workArea(*child_buf);
2525 if (!closeWorkArea(child_wa, true))
2528 theBufferList().releaseChild(&buf, child_buf);
2531 // goto bookmark to update bookmark pit.
2532 //FIXME: we should update only the bookmarks related to this buffer!
2533 LYXERR(Debug::DEBUG, "GuiView::closeBuffer()");
2534 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
2535 guiApp->gotoBookmark(i+1, false, false);
2537 if (saveBufferIfNeeded(buf, false)) {
2538 buf.removeAutosaveFile();
2539 theBufferList().release(&buf);
2546 bool GuiView::closeTabWorkArea(TabWorkArea * twa)
2548 while (twa == d.currentTabWorkArea()) {
2549 twa->setCurrentIndex(twa->count()-1);
2551 GuiWorkArea * wa = twa->currentWorkArea();
2552 Buffer & b = wa->bufferView().buffer();
2554 // We only want to close the buffer if the same buffer is not visible
2555 // in another view, and if this is not a child and if we are closing
2556 // a view (not a tabgroup).
2557 bool const close_buffer =
2558 !inMultiViews(wa) && !b.parent() && closing_;
2560 if (!closeWorkArea(wa, close_buffer))
2567 bool GuiView::saveBufferIfNeeded(Buffer & buf, bool hiding)
2569 if (buf.isClean() || buf.paragraphs().empty())
2572 // Switch to this Buffer.
2577 if (buf.isUnnamed())
2578 file = from_utf8(buf.fileName().onlyFileName());
2580 file = buf.fileName().displayName(30);
2582 // Bring this window to top before asking questions.
2587 if (hiding && buf.isUnnamed()) {
2588 docstring const text = bformat(_("The document %1$s has not been "
2589 "saved yet.\n\nDo you want to save "
2590 "the document?"), file);
2591 ret = Alert::prompt(_("Save new document?"),
2592 text, 0, 1, _("&Save"), _("&Cancel"));
2596 docstring const text = bformat(_("The document %1$s has unsaved changes."
2597 "\n\nDo you want to save the document or discard the changes?"), file);
2598 ret = Alert::prompt(_("Save changed document?"),
2599 text, 0, 2, _("&Save"), _("&Discard"), _("&Cancel"));
2604 if (!saveBuffer(buf))
2608 // if we crash after this we could
2609 // have no autosave file but I guess
2610 // this is really improbable (Jug)
2611 // Sometime improbable things happen, bug 6857 (ps)
2612 // buf.removeAutosaveFile();
2614 // revert all changes
2625 bool GuiView::inMultiTabs(GuiWorkArea * wa)
2627 Buffer & buf = wa->bufferView().buffer();
2629 for (int i = 0; i != d.splitter_->count(); ++i) {
2630 GuiWorkArea * wa_ = d.tabWorkArea(i)->workArea(buf);
2631 if (wa_ && wa_ != wa)
2634 return inMultiViews(wa);
2638 bool GuiView::inMultiViews(GuiWorkArea * wa)
2640 QList<int> const ids = guiApp->viewIds();
2641 Buffer & buf = wa->bufferView().buffer();
2644 for (int i = 0; i != ids.size() && found_twa <= 1; ++i) {
2648 if (guiApp->view(ids[i]).workArea(buf))
2655 void GuiView::gotoNextOrPreviousBuffer(NextOrPrevious np)
2657 Buffer * const curbuf = documentBufferView()
2658 ? &documentBufferView()->buffer() : 0;
2659 Buffer * nextbuf = curbuf;
2661 if (np == NEXTBUFFER)
2662 nextbuf = theBufferList().next(nextbuf);
2664 nextbuf = theBufferList().previous(nextbuf);
2665 if (nextbuf == curbuf)
2671 if (workArea(*nextbuf))
2678 /// make sure the document is saved
2679 static bool ensureBufferClean(Buffer * buffer)
2681 LASSERT(buffer, return false);
2682 if (buffer->isClean() && !buffer->isUnnamed())
2685 docstring const file = buffer->fileName().displayName(30);
2688 if (!buffer->isUnnamed()) {
2689 text = bformat(_("The document %1$s has unsaved "
2690 "changes.\n\nDo you want to save "
2691 "the document?"), file);
2692 title = _("Save changed document?");
2695 text = bformat(_("The document %1$s has not been "
2696 "saved yet.\n\nDo you want to save "
2697 "the document?"), file);
2698 title = _("Save new document?");
2700 int const ret = Alert::prompt(title, text, 0, 1, _("&Save"), _("&Cancel"));
2703 dispatch(FuncRequest(LFUN_BUFFER_WRITE));
2705 return buffer->isClean() && !buffer->isUnnamed();
2709 void GuiView::reloadBuffer()
2711 Buffer * buf = &documentBufferView()->buffer();
2716 void GuiView::checkExternallyModifiedBuffers()
2718 BufferList::iterator bit = theBufferList().begin();
2719 BufferList::iterator const bend = theBufferList().end();
2720 for (; bit != bend; ++bit) {
2721 if ((*bit)->fileName().exists()
2722 && (*bit)->isExternallyModified(Buffer::checksum_method)) {
2723 docstring text = bformat(_("Document \n%1$s\n has been externally modified."
2724 " Reload now? Any local changes will be lost."),
2725 from_utf8((*bit)->absFileName()));
2726 int const ret = Alert::prompt(_("Reload externally changed document?"),
2727 text, 0, 1, _("&Reload"), _("&Cancel"));
2735 //FIXME use a DispatchResult object to transmit messages
2736 void GuiView::dispatchVC(FuncRequest const & cmd)
2738 // message for statusbar
2740 Buffer * buffer = documentBufferView()
2741 ? &(documentBufferView()->buffer()) : 0;
2743 switch (cmd.action()) {
2744 case LFUN_VC_REGISTER:
2745 if (!buffer || !ensureBufferClean(buffer))
2747 if (!buffer->lyxvc().inUse()) {
2748 if (buffer->lyxvc().registrer())
2753 case LFUN_VC_CHECK_IN:
2754 if (!buffer || !ensureBufferClean(buffer))
2756 if (buffer->lyxvc().inUse() && !buffer->isReadonly()) {
2757 msg = buffer->lyxvc().checkIn();
2763 case LFUN_VC_CHECK_OUT:
2764 if (!buffer || !ensureBufferClean(buffer))
2766 if (buffer->lyxvc().inUse()) {
2767 msg = buffer->lyxvc().checkOut();
2772 case LFUN_VC_LOCKING_TOGGLE:
2773 LASSERT(buffer, return);
2774 if (!ensureBufferClean(buffer) || buffer->isReadonly())
2776 if (buffer->lyxvc().inUse()) {
2777 string res = buffer->lyxvc().lockingToggle();
2779 frontend::Alert::error(_("Revision control error."),
2780 _("Error when setting the locking property."));
2788 case LFUN_VC_REVERT:
2789 LASSERT(buffer, return);
2790 buffer->lyxvc().revert();
2794 case LFUN_VC_UNDO_LAST:
2795 LASSERT(buffer, return);
2796 buffer->lyxvc().undoLast();
2800 case LFUN_VC_REPO_UPDATE:
2801 LASSERT(buffer, return);
2802 if (ensureBufferClean(buffer)) {
2803 msg = buffer->lyxvc().repoUpdate();
2804 checkExternallyModifiedBuffers();
2808 case LFUN_VC_COMMAND: {
2809 string flag = cmd.getArg(0);
2810 if (buffer && contains(flag, 'R') && !ensureBufferClean(buffer))
2813 if (contains(flag, 'M')) {
2814 if (!Alert::askForText(message, _("LyX VC: Log Message")))
2817 string path = cmd.getArg(1);
2818 if (contains(path, "$$p") && buffer)
2819 path = subst(path, "$$p", buffer->filePath());
2820 LYXERR(Debug::LYXVC, "Directory: " << path);
2822 if (!pp.isReadableDirectory()) {
2823 lyxerr << _("Directory is not accessible.") << endl;
2826 support::PathChanger p(pp);
2828 string command = cmd.getArg(2);
2829 if (command.empty())
2832 command = subst(command, "$$i", buffer->absFileName());
2833 command = subst(command, "$$p", buffer->filePath());
2835 command = subst(command, "$$m", to_utf8(message));
2836 LYXERR(Debug::LYXVC, "Command: " << command);
2838 one.startscript(Systemcall::Wait, command);
2842 if (contains(flag, 'I'))
2843 buffer->markDirty();
2844 if (contains(flag, 'R'))
2850 case LFUN_VC_COMPARE: {
2852 string rev1 = cmd.getArg(0);
2856 if (!buffer->lyxvc().prepareFileRevision(rev1, f1))
2859 if (isStrInt(rev1) && convert<int>(rev1) <= 0) {
2860 f2 = buffer->absFileName();
2862 string rev2 = cmd.getArg(1);
2866 if (!buffer->lyxvc().prepareFileRevision(rev2, f2))
2869 // FIXME We need to call comparison feature here.
2870 // This is quick and dirty code for testing VC.
2871 // We need that comparison feature has some LFUN_COMPARE <FLAG> file1 file1
2872 // where <FLAG> specifies whether we want GUI dialog or just launch
2873 // running with defaults.
2875 FileName initpath(lyxrc.document_path);
2876 Buffer * dest = newUnnamedFile(initpath, to_utf8(_("differences")));
2877 CompareOptions options;
2878 Compare * compare = new Compare(loadIfNeeded(FileName(f1)), loadIfNeeded(FileName(f2)), dest, options);
2879 compare->start(QThread::LowPriority);
2880 Sleep::millisec(200);
2881 lyx::dispatch(FuncRequest(LFUN_BUFFER_SWITCH, dest->absFileName()));
2891 message(from_utf8(msg));
2895 void GuiView::openChildDocument(string const & fname)
2897 LASSERT(documentBufferView(), return);
2898 Buffer & buffer = documentBufferView()->buffer();
2899 FileName const filename = support::makeAbsPath(fname, buffer.filePath());
2900 documentBufferView()->saveBookmark(false);
2902 bool parsed = false;
2903 if (theBufferList().exists(filename)) {
2904 child = theBufferList().getBuffer(filename);
2906 message(bformat(_("Opening child document %1$s..."),
2907 makeDisplayPath(filename.absFileName())));
2908 child = loadDocument(filename, false);
2914 // Set the parent name of the child document.
2915 // This makes insertion of citations and references in the child work,
2916 // when the target is in the parent or another child document.
2917 child->setParent(&buffer);
2919 // I don't think this is needed, since it will be called in
2921 // child->masterBuffer()->updateBuffer();
2924 child->errors("Parse");
2928 bool GuiView::goToFileRow(string const & argument)
2932 size_t i = argument.find_last_of(' ');
2933 if (i != string::npos) {
2934 file_name = os::internal_path(trim(argument.substr(0, i)));
2935 istringstream is(argument.substr(i + 1));
2940 if (i == string::npos) {
2941 LYXERR0("Wrong argument: " << argument);
2945 string const abstmp = package().temp_dir().absFileName();
2946 string const realtmp = package().temp_dir().realPath();
2947 // We have to use os::path_prefix_is() here, instead of
2948 // simply prefixIs(), because the file name comes from
2949 // an external application and may need case adjustment.
2950 if (os::path_prefix_is(file_name, abstmp, os::CASE_ADJUSTED)
2951 || os::path_prefix_is(file_name, realtmp, os::CASE_ADJUSTED)) {
2952 // Needed by inverse dvi search. If it is a file
2953 // in tmpdir, call the apropriated function.
2954 // If tmpdir is a symlink, we may have the real
2955 // path passed back, so we correct for that.
2956 if (!prefixIs(file_name, abstmp))
2957 file_name = subst(file_name, realtmp, abstmp);
2958 buf = theBufferList().getBufferFromTmp(file_name);
2960 // Must replace extension of the file to be .lyx
2961 // and get full path
2962 FileName const s = fileSearch(string(),
2963 support::changeExtension(file_name, ".lyx"), "lyx");
2964 // Either change buffer or load the file
2965 if (theBufferList().exists(s))
2966 buf = theBufferList().getBuffer(s);
2967 else if (s.exists()) {
2968 buf = loadDocument(s);
2971 // I don't think this is needed. loadDocument() calls
2972 // setBuffer(), which calls updateBuffer().
2973 // buf->updateBuffer();
2974 buf->errors("Parse");
2977 _("File does not exist: %1$s"),
2978 makeDisplayPath(file_name)));
2983 documentBufferView()->setCursorFromRow(row);
2988 #if (QT_VERSION >= 0x040400)
2989 docstring GuiView::GuiViewPrivate::exportAndDestroy(Buffer const * orig, Buffer * buffer, string const & format)
2991 bool const update_unincluded =
2992 buffer->params().maintain_unincluded_children
2993 && !buffer->params().getIncludedChildren().empty();
2994 bool const success = buffer->doExport(format, true, update_unincluded);
2996 busyBuffers.remove(orig);
2998 ? bformat(_("Successful export to format: %1$s"), from_utf8(format))
2999 : bformat(_("Error exporting to format: %1$s"), from_utf8(format));
3003 docstring GuiView::GuiViewPrivate::previewAndDestroy(Buffer const * orig, Buffer * buffer, string const & format)
3005 bool const update_unincluded =
3006 buffer->params().maintain_unincluded_children
3007 && !buffer->params().getIncludedChildren().empty();
3008 bool const success = buffer->preview(format, update_unincluded);
3010 busyBuffers.remove(orig);
3012 ? bformat(_("Successful preview of format: %1$s"), from_utf8(format))
3013 : bformat(_("Error previewing format: %1$s"), from_utf8(format));
3018 void GuiView::dispatch(FuncRequest const & cmd, DispatchResult & dr)
3020 BufferView * bv = currentBufferView();
3021 // By default we won't need any update.
3022 dr.update(Update::None);
3023 // assume cmd will be dispatched
3024 dr.dispatched(true);
3026 Buffer * doc_buffer = documentBufferView()
3027 ? &(documentBufferView()->buffer()) : 0;
3029 if (cmd.origin() == FuncRequest::TOC) {
3030 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
3031 // FIXME: do we need to pass a DispatchResult object here?
3032 toc->doDispatch(bv->cursor(), cmd);
3036 string const argument = to_utf8(cmd.argument());
3038 switch(cmd.action()) {
3039 case LFUN_BUFFER_CHILD_OPEN:
3040 openChildDocument(to_utf8(cmd.argument()));
3043 case LFUN_BUFFER_IMPORT:
3044 importDocument(to_utf8(cmd.argument()));
3047 case LFUN_BUFFER_EXPORT: {
3050 // GCC only sees strfwd.h when building merged
3051 if (::lyx::operator==(cmd.argument(), "custom")) {
3052 dispatch(FuncRequest(LFUN_DIALOG_SHOW, "sendto"),
3056 if (!doc_buffer->doExport(argument, false)) {
3058 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
3064 case LFUN_BUFFER_UPDATE: {
3067 string format = argument;
3068 if (argument.empty())
3069 format = doc_buffer->getDefaultOutputFormat();
3070 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
3071 d.progress_->clearMessages();
3072 message(_("Exporting ..."));
3073 GuiViewPrivate::busyBuffers.insert(doc_buffer);
3074 QFuture<docstring> f = QtConcurrent::run(GuiViewPrivate::exportAndDestroy,
3075 doc_buffer, doc_buffer->clone(), format);
3076 d.setPreviewFuture(f);
3077 d.last_export_format = doc_buffer->bufferFormat();
3079 bool const update_unincluded =
3080 doc_buffer->params().maintain_unincluded_children
3081 && !doc_buffer->params().getIncludedChildren().empty();
3082 doc_buffer->doExport(format, true, update_unincluded);
3086 case LFUN_BUFFER_VIEW: {
3089 string format = argument;
3090 if (argument.empty())
3091 format = doc_buffer->getDefaultOutputFormat();
3092 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
3093 d.progress_->clearMessages();
3094 message(_("Previewing ..."));
3095 GuiViewPrivate::busyBuffers.insert(doc_buffer);
3096 QFuture<docstring> f = QtConcurrent::run(GuiViewPrivate::previewAndDestroy,
3097 doc_buffer, doc_buffer->clone(), format);
3098 d.setPreviewFuture(f);
3099 d.last_export_format = doc_buffer->bufferFormat();
3101 bool const update_unincluded =
3102 doc_buffer->params().maintain_unincluded_children
3103 && !doc_buffer->params().getIncludedChildren().empty();
3104 doc_buffer->preview(format, update_unincluded);
3108 case LFUN_MASTER_BUFFER_UPDATE: {
3111 string format = argument;
3112 Buffer const * master = doc_buffer->masterBuffer();
3113 if (argument.empty())
3114 format = master->getDefaultOutputFormat();
3115 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
3116 GuiViewPrivate::busyBuffers.insert(master);
3117 QFuture<docstring> f = QtConcurrent::run(GuiViewPrivate::exportAndDestroy,
3118 master, master->clone(), format);
3119 d.setPreviewFuture(f);
3120 d.last_export_format = doc_buffer->bufferFormat();
3122 bool const update_unincluded =
3123 master->params().maintain_unincluded_children
3124 && !master->params().getIncludedChildren().empty();
3125 master->doExport(format, true);
3129 case LFUN_MASTER_BUFFER_VIEW: {
3130 string format = argument;
3131 Buffer const * master = doc_buffer->masterBuffer();
3132 if (argument.empty())
3133 format = master->getDefaultOutputFormat();
3134 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
3135 GuiViewPrivate::busyBuffers.insert(master);
3136 QFuture<docstring> f = QtConcurrent::run(GuiViewPrivate::previewAndDestroy,
3137 master, master->clone(), format);
3138 d.setPreviewFuture(f);
3139 d.last_export_format = doc_buffer->bufferFormat();
3141 master->preview(format);
3145 case LFUN_BUFFER_SWITCH: {
3146 string const file_name = to_utf8(cmd.argument());
3147 if (!FileName::isAbsolute(file_name)) {
3149 dr.setMessage(_("Absolute filename expected."));
3153 Buffer * buffer = theBufferList().getBuffer(FileName(file_name));
3156 dr.setMessage(_("Document not loaded"));
3160 // Do we open or switch to the buffer in this view ?
3161 if (workArea(*buffer)
3162 || lyxrc.open_buffers_in_tabs || !documentBufferView()) {
3167 // Look for the buffer in other views
3168 QList<int> const ids = guiApp->viewIds();
3170 for (; i != ids.size(); ++i) {
3171 GuiView & gv = guiApp->view(ids[i]);
3172 if (gv.workArea(*buffer)) {
3173 gv.activateWindow();
3174 gv.setBuffer(buffer);
3179 // If necessary, open a new window as a last resort
3180 if (i == ids.size()) {
3181 lyx::dispatch(FuncRequest(LFUN_WINDOW_NEW));
3187 case LFUN_BUFFER_NEXT:
3188 gotoNextOrPreviousBuffer(NEXTBUFFER);
3191 case LFUN_BUFFER_PREVIOUS:
3192 gotoNextOrPreviousBuffer(PREVBUFFER);
3195 case LFUN_COMMAND_EXECUTE: {
3196 bool const show_it = cmd.argument() != "off";
3197 // FIXME: this is a hack, "minibuffer" should not be
3199 if (GuiToolbar * t = toolbar("minibuffer")) {
3200 t->setVisible(show_it);
3201 if (show_it && t->commandBuffer())
3202 t->commandBuffer()->setFocus();
3206 case LFUN_DROP_LAYOUTS_CHOICE:
3207 d.layout_->showPopup();
3210 case LFUN_MENU_OPEN:
3211 if (QMenu * menu = guiApp->menus().menu(toqstr(cmd.argument()), *this))
3212 menu->exec(QCursor::pos());
3215 case LFUN_FILE_INSERT:
3216 insertLyXFile(cmd.argument());
3218 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
3219 insertPlaintextFile(cmd.argument(), true);
3222 case LFUN_FILE_INSERT_PLAINTEXT:
3223 insertPlaintextFile(cmd.argument(), false);
3226 case LFUN_BUFFER_RELOAD: {
3227 LASSERT(doc_buffer, break);
3228 docstring const file = makeDisplayPath(doc_buffer->absFileName(), 20);
3229 docstring text = bformat(_("Any changes will be lost. Are you sure "
3230 "you want to revert to the saved version of the document %1$s?"), file);
3231 int const ret = Alert::prompt(_("Revert to saved document?"),
3232 text, 1, 1, _("&Revert"), _("&Cancel"));
3235 doc_buffer->markClean();
3237 dr.forceBufferUpdate();
3242 case LFUN_BUFFER_WRITE:
3243 LASSERT(doc_buffer, break);
3244 saveBuffer(*doc_buffer);
3247 case LFUN_BUFFER_WRITE_ENCRYPTED:
3248 LASSERT(doc_buffer, break);
3249 saveBufferEncrypted(*doc_buffer);
3252 case LFUN_BUFFER_WRITE_AS:
3253 LASSERT(doc_buffer, break);
3254 renameBuffer(*doc_buffer, cmd.argument());
3257 case LFUN_BUFFER_WRITE_ALL: {
3258 Buffer * first = theBufferList().first();
3261 message(_("Saving all documents..."));
3262 // We cannot use a for loop as the buffer list cycles.
3265 if (!b->isClean()) {
3267 LYXERR(Debug::ACTION, "Saved " << b->absFileName());
3269 b = theBufferList().next(b);
3270 } while (b != first);
3271 dr.setMessage(_("All documents saved."));
3275 case LFUN_BUFFER_CLOSE:
3279 case LFUN_BUFFER_CLOSE_ALL:
3283 case LFUN_TOOLBAR_TOGGLE: {
3284 string const name = cmd.getArg(0);
3285 if (GuiToolbar * t = toolbar(name))
3290 case LFUN_DIALOG_UPDATE: {
3291 string const name = to_utf8(cmd.argument());
3292 if (currentBufferView()) {
3293 Inset * inset = currentBufferView()->editedInset(name);
3294 // Can only update a dialog connected to an existing inset
3297 // FIXME: get rid of this indirection; GuiView ask the inset
3298 // if he is kind enough to update itself...
3299 FuncRequest fr(LFUN_INSET_DIALOG_UPDATE, cmd.argument());
3300 //FIXME: pass DispatchResult here?
3301 inset->dispatch(currentBufferView()->cursor(), fr);
3302 } else if (name == "paragraph") {
3303 lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
3304 } else if (name == "prefs" || name == "document") {
3305 updateDialog(name, string());
3310 case LFUN_DIALOG_TOGGLE: {
3311 if (isDialogVisible(cmd.getArg(0)))
3312 dispatch(FuncRequest(LFUN_DIALOG_HIDE, cmd.argument()), dr);
3314 dispatch(FuncRequest(LFUN_DIALOG_SHOW, cmd.argument()), dr);
3318 case LFUN_DIALOG_DISCONNECT_INSET:
3319 disconnectDialog(to_utf8(cmd.argument()));
3322 case LFUN_DIALOG_HIDE: {
3323 guiApp->hideDialogs(to_utf8(cmd.argument()), 0);
3327 case LFUN_DIALOG_SHOW: {
3328 string const name = cmd.getArg(0);
3329 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
3331 if (name == "character") {
3332 data = freefont2string();
3334 showDialog("character", data);
3335 } else if (name == "latexlog") {
3336 Buffer::LogType type;
3337 string const logfile = doc_buffer->logName(&type);
3339 case Buffer::latexlog:
3342 case Buffer::buildlog:
3346 data += Lexer::quoteString(logfile);
3347 showDialog("log", data);
3348 } else if (name == "vclog") {
3349 string const data = "vc " +
3350 Lexer::quoteString(doc_buffer->lyxvc().getLogFile());
3351 showDialog("log", data);
3352 } else if (name == "symbols") {
3353 data = bv->cursor().getEncoding()->name();
3355 showDialog("symbols", data);
3357 } else if (name == "prefs" && isFullScreen()) {
3358 lfunUiToggle("fullscreen");
3359 showDialog("prefs", data);
3361 showDialog(name, data);
3366 dr.setMessage(cmd.argument());
3369 case LFUN_UI_TOGGLE: {
3370 string arg = cmd.getArg(0);
3371 if (!lfunUiToggle(arg)) {
3372 docstring const msg = "ui-toggle " + _("%1$s unknown command!");
3373 dr.setMessage(bformat(msg, from_utf8(arg)));
3375 // Make sure the keyboard focus stays in the work area.
3380 case LFUN_SPLIT_VIEW: {
3381 LASSERT(doc_buffer, break);
3382 string const orientation = cmd.getArg(0);
3383 d.splitter_->setOrientation(orientation == "vertical"
3384 ? Qt::Vertical : Qt::Horizontal);
3385 TabWorkArea * twa = addTabWorkArea();
3386 GuiWorkArea * wa = twa->addWorkArea(*doc_buffer, *this);
3387 setCurrentWorkArea(wa);
3390 case LFUN_CLOSE_TAB_GROUP:
3391 if (TabWorkArea * twa = d.currentTabWorkArea()) {
3392 closeTabWorkArea(twa);
3393 d.current_work_area_ = 0;
3394 twa = d.currentTabWorkArea();
3395 // Switch to the next GuiWorkArea in the found TabWorkArea.
3397 // Make sure the work area is up to date.
3398 setCurrentWorkArea(twa->currentWorkArea());
3400 setCurrentWorkArea(0);
3405 case LFUN_COMPLETION_INLINE:
3406 if (d.current_work_area_)
3407 d.current_work_area_->completer().showInline();
3410 case LFUN_COMPLETION_POPUP:
3411 if (d.current_work_area_)
3412 d.current_work_area_->completer().showPopup();
3416 case LFUN_COMPLETION_COMPLETE:
3417 if (d.current_work_area_)
3418 d.current_work_area_->completer().tab();
3421 case LFUN_COMPLETION_CANCEL:
3422 if (d.current_work_area_) {
3423 if (d.current_work_area_->completer().popupVisible())
3424 d.current_work_area_->completer().hidePopup();
3426 d.current_work_area_->completer().hideInline();
3430 case LFUN_COMPLETION_ACCEPT:
3431 if (d.current_work_area_)
3432 d.current_work_area_->completer().activate();
3435 case LFUN_BUFFER_ZOOM_IN:
3436 case LFUN_BUFFER_ZOOM_OUT:
3437 if (cmd.argument().empty()) {
3438 if (cmd.action() == LFUN_BUFFER_ZOOM_IN)
3443 lyxrc.zoom += convert<int>(cmd.argument());
3445 if (lyxrc.zoom < 10)
3448 // The global QPixmapCache is used in GuiPainter to cache text
3449 // painting so we must reset it.
3450 QPixmapCache::clear();
3451 guiApp->fontLoader().update();
3452 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
3455 case LFUN_VC_REGISTER:
3456 case LFUN_VC_CHECK_IN:
3457 case LFUN_VC_CHECK_OUT:
3458 case LFUN_VC_REPO_UPDATE:
3459 case LFUN_VC_LOCKING_TOGGLE:
3460 case LFUN_VC_REVERT:
3461 case LFUN_VC_UNDO_LAST:
3462 case LFUN_VC_COMMAND:
3463 case LFUN_VC_COMPARE:
3467 case LFUN_SERVER_GOTO_FILE_ROW:
3468 goToFileRow(to_utf8(cmd.argument()));
3471 case LFUN_FORWARD_SEARCH: {
3472 FileName const path(doc_buffer->temppath());
3473 string const texname = doc_buffer->latexName();
3474 FileName const dviname(addName(path.absFileName(),
3475 support::changeExtension(texname, "dvi")));
3476 FileName const pdfname(addName(path.absFileName(),
3477 support::changeExtension(texname, "pdf")));
3478 if (!dviname.exists() && !pdfname.exists()) {
3479 dr.setMessage(_("Please, preview the document first."));
3482 string outname = dviname.onlyFileName();
3483 string command = lyxrc.forward_search_dvi;
3484 if (!dviname.exists() ||
3485 pdfname.lastModified() > dviname.lastModified()) {
3486 outname = pdfname.onlyFileName();
3487 command = lyxrc.forward_search_pdf;
3490 int row = doc_buffer->texrow().getRowFromIdPos(bv->cursor().paragraph().id(), bv->cursor().pos());
3491 LYXERR(Debug::ACTION, "Forward search: row:" << row
3492 << " id:" << bv->cursor().paragraph().id());
3493 if (!row || command.empty()) {
3494 dr.setMessage(_("Couldn't proceed."));
3497 string texrow = convert<string>(row);
3499 command = subst(command, "$$n", texrow);
3500 command = subst(command, "$$t", texname);
3501 command = subst(command, "$$o", outname);
3503 PathChanger p(path);
3505 one.startscript(Systemcall::DontWait, command);
3509 dr.dispatched(false);
3513 // Part of automatic menu appearance feature.
3514 if (isFullScreen()) {
3515 if (menuBar()->isVisible() && lyxrc.full_screen_menubar)
3517 if (statusBar()->isVisible())
3518 statusBar()->hide();
3525 bool GuiView::lfunUiToggle(string const & ui_component)
3527 if (ui_component == "scrollbar") {
3528 // hide() is of no help
3529 if (d.current_work_area_->verticalScrollBarPolicy() ==
3530 Qt::ScrollBarAlwaysOff)
3532 d.current_work_area_->setVerticalScrollBarPolicy(
3533 Qt::ScrollBarAsNeeded);
3535 d.current_work_area_->setVerticalScrollBarPolicy(
3536 Qt::ScrollBarAlwaysOff);
3537 } else if (ui_component == "statusbar") {
3538 statusBar()->setVisible(!statusBar()->isVisible());
3539 } else if (ui_component == "menubar") {
3540 menuBar()->setVisible(!menuBar()->isVisible());
3542 #if QT_VERSION >= 0x040300
3543 if (ui_component == "frame") {
3545 getContentsMargins(&l, &t, &r, &b);
3546 //are the frames in default state?
3547 d.current_work_area_->setFrameStyle(QFrame::NoFrame);
3549 setContentsMargins(-2, -2, -2, -2);
3551 setContentsMargins(0, 0, 0, 0);
3555 if (ui_component == "fullscreen") {
3563 void GuiView::toggleFullScreen()
3565 if (isFullScreen()) {
3566 for (int i = 0; i != d.splitter_->count(); ++i)
3567 d.tabWorkArea(i)->setFullScreen(false);
3568 #if QT_VERSION >= 0x040300
3569 setContentsMargins(0, 0, 0, 0);
3571 setWindowState(windowState() ^ Qt::WindowFullScreen);
3574 statusBar()->show();
3577 hideDialogs("prefs", 0);
3578 for (int i = 0; i != d.splitter_->count(); ++i)
3579 d.tabWorkArea(i)->setFullScreen(true);
3580 #if QT_VERSION >= 0x040300
3581 setContentsMargins(-2, -2, -2, -2);
3584 setWindowState(windowState() ^ Qt::WindowFullScreen);
3585 statusBar()->hide();
3586 if (lyxrc.full_screen_menubar)
3588 if (lyxrc.full_screen_toolbars) {
3589 ToolbarMap::iterator end = d.toolbars_.end();
3590 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
3595 // give dialogs like the TOC a chance to adapt
3600 Buffer const * GuiView::updateInset(Inset const * inset)
3605 Buffer const * inset_buffer = &(inset->buffer());
3607 for (int i = 0; i != d.splitter_->count(); ++i) {
3608 GuiWorkArea * wa = d.tabWorkArea(i)->currentWorkArea();
3611 Buffer const * buffer = &(wa->bufferView().buffer());
3612 if (inset_buffer == buffer)
3613 wa->scheduleRedraw();
3615 return inset_buffer;
3619 void GuiView::restartCursor()
3621 /* When we move around, or type, it's nice to be able to see
3622 * the cursor immediately after the keypress.
3624 if (d.current_work_area_)
3625 d.current_work_area_->startBlinkingCursor();
3627 // Take this occasion to update the other GUI elements.
3633 void GuiView::updateCompletion(Cursor & cur, bool start, bool keep)
3635 if (d.current_work_area_)
3636 d.current_work_area_->completer().updateVisibility(cur, start, keep);
3641 // This list should be kept in sync with the list of insets in
3642 // src/insets/Inset.cpp. I.e., if a dialog goes with an inset, the
3643 // dialog should have the same name as the inset.
3644 // Changes should be also recorded in LFUN_DIALOG_SHOW doxygen
3645 // docs in LyXAction.cpp.
3647 char const * const dialognames[] = {
3648 "aboutlyx", "bibitem", "bibtex", "box", "branch", "changes", "character",
3649 "citation", "compare", "document", "errorlist", "ert", "external", "file",
3650 "findreplace", "findreplaceadv", "float", "graphics", "href", "include",
3651 "index", "index_print", "info", "listings", "label", "log", "mathdelimiter",
3652 "mathmatrix", "mathspace", "nomenclature", "nomencl_print", "note",
3653 "paragraph", "phantom", "prefs", "print", "ref", "sendto", "space",
3654 "spellchecker", "symbols", "tabular", "tabularcreate", "thesaurus", "texinfo",
3655 "toc", "view-source", "vspace", "wrap", "progress"};
3657 char const * const * const end_dialognames =
3658 dialognames + (sizeof(dialognames) / sizeof(char *));
3662 cmpCStr(char const * name) : name_(name) {}
3663 bool operator()(char const * other) {
3664 return strcmp(other, name_) == 0;
3671 bool isValidName(string const & name)
3673 return find_if(dialognames, end_dialognames,
3674 cmpCStr(name.c_str())) != end_dialognames;
3680 void GuiView::resetDialogs()
3682 // Make sure that no LFUN uses any GuiView.
3683 guiApp->setCurrentView(0);
3686 constructToolbars();
3687 guiApp->menus().fillMenuBar(menuBar(), this, false);
3688 d.layout_->updateContents(true);
3689 // Now update controls with current buffer.
3690 guiApp->setCurrentView(this);
3696 Dialog * GuiView::findOrBuild(string const & name, bool hide_it)
3698 if (!isValidName(name))
3701 map<string, DialogPtr>::iterator it = d.dialogs_.find(name);
3703 if (it != d.dialogs_.end()) {
3705 it->second->hideView();
3706 return it->second.get();
3709 Dialog * dialog = build(name);
3710 d.dialogs_[name].reset(dialog);
3711 if (lyxrc.allow_geometry_session)
3712 dialog->restoreSession();
3719 void GuiView::showDialog(string const & name, string const & data,
3722 triggerShowDialog(toqstr(name), toqstr(data), inset);
3726 void GuiView::doShowDialog(QString const & qname, QString const & qdata,
3732 const string name = fromqstr(qname);
3733 const string data = fromqstr(qdata);
3737 Dialog * dialog = findOrBuild(name, false);
3739 bool const visible = dialog->isVisibleView();
3740 dialog->showData(data);
3741 if (inset && currentBufferView())
3742 currentBufferView()->editInset(name, inset);
3743 // We only set the focus to the new dialog if it was not yet
3744 // visible in order not to change the existing previous behaviour
3746 // activateWindow is needed for floating dockviews
3747 dialog->asQWidget()->raise();
3748 dialog->asQWidget()->activateWindow();
3749 dialog->asQWidget()->setFocus();
3753 catch (ExceptionMessage const & ex) {
3761 bool GuiView::isDialogVisible(string const & name) const
3763 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3764 if (it == d.dialogs_.end())
3766 return it->second.get()->isVisibleView() && !it->second.get()->isClosing();
3770 void GuiView::hideDialog(string const & name, Inset * inset)
3772 map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3773 if (it == d.dialogs_.end())
3776 if (inset && currentBufferView()
3777 && inset != currentBufferView()->editedInset(name))
3780 Dialog * const dialog = it->second.get();
3781 if (dialog->isVisibleView())
3783 if (currentBufferView())
3784 currentBufferView()->editInset(name, 0);
3788 void GuiView::disconnectDialog(string const & name)
3790 if (!isValidName(name))
3792 if (currentBufferView())
3793 currentBufferView()->editInset(name, 0);
3797 void GuiView::hideAll() const
3799 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
3800 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3802 for(; it != end; ++it)
3803 it->second->hideView();
3807 void GuiView::updateDialogs()
3809 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
3810 map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3812 for(; it != end; ++it) {
3813 Dialog * dialog = it->second.get();
3815 if (dialog->needBufferOpen() && !documentBufferView())
3816 hideDialog(fromqstr(dialog->name()), 0);
3817 else if (dialog->isVisibleView())
3818 dialog->checkStatus();
3825 Dialog * createDialog(GuiView & lv, string const & name);
3827 // will be replaced by a proper factory...
3828 Dialog * createGuiAbout(GuiView & lv);
3829 Dialog * createGuiBibtex(GuiView & lv);
3830 Dialog * createGuiChanges(GuiView & lv);
3831 Dialog * createGuiCharacter(GuiView & lv);
3832 Dialog * createGuiCitation(GuiView & lv);
3833 Dialog * createGuiCompare(GuiView & lv);
3834 Dialog * createGuiDelimiter(GuiView & lv);
3835 Dialog * createGuiDocument(GuiView & lv);
3836 Dialog * createGuiErrorList(GuiView & lv);
3837 Dialog * createGuiExternal(GuiView & lv);
3838 Dialog * createGuiGraphics(GuiView & lv);
3839 Dialog * createGuiInclude(GuiView & lv);
3840 Dialog * createGuiIndex(GuiView & lv);
3841 Dialog * createGuiLabel(GuiView & lv);
3842 Dialog * createGuiListings(GuiView & lv);
3843 Dialog * createGuiLog(GuiView & lv);
3844 Dialog * createGuiMathMatrix(GuiView & lv);
3845 Dialog * createGuiNomenclature(GuiView & lv);
3846 Dialog * createGuiNote(GuiView & lv);
3847 Dialog * createGuiParagraph(GuiView & lv);
3848 Dialog * createGuiPhantom(GuiView & lv);
3849 Dialog * createGuiPreferences(GuiView & lv);
3850 Dialog * createGuiPrint(GuiView & lv);
3851 Dialog * createGuiPrintindex(GuiView & lv);
3852 Dialog * createGuiPrintNomencl(GuiView & lv);
3853 Dialog * createGuiRef(GuiView & lv);
3854 Dialog * createGuiSearch(GuiView & lv);
3855 Dialog * createGuiSearchAdv(GuiView & lv);
3856 Dialog * createGuiSendTo(GuiView & lv);
3857 Dialog * createGuiShowFile(GuiView & lv);
3858 Dialog * createGuiSpellchecker(GuiView & lv);
3859 Dialog * createGuiSymbols(GuiView & lv);
3860 Dialog * createGuiTabularCreate(GuiView & lv);
3861 Dialog * createGuiTexInfo(GuiView & lv);
3862 Dialog * createGuiToc(GuiView & lv);
3863 Dialog * createGuiThesaurus(GuiView & lv);
3864 Dialog * createGuiHyperlink(GuiView & lv);
3865 Dialog * createGuiViewSource(GuiView & lv);
3866 Dialog * createGuiWrap(GuiView & lv);
3867 Dialog * createGuiProgressView(GuiView & lv);
3871 Dialog * GuiView::build(string const & name)
3873 LASSERT(isValidName(name), return 0);
3875 Dialog * dialog = createDialog(*this, name);
3879 if (name == "aboutlyx")
3880 return createGuiAbout(*this);
3881 if (name == "bibtex")
3882 return createGuiBibtex(*this);
3883 if (name == "changes")
3884 return createGuiChanges(*this);
3885 if (name == "character")
3886 return createGuiCharacter(*this);
3887 if (name == "citation")
3888 return createGuiCitation(*this);
3889 if (name == "compare")
3890 return createGuiCompare(*this);
3891 if (name == "document")
3892 return createGuiDocument(*this);
3893 if (name == "errorlist")
3894 return createGuiErrorList(*this);
3895 if (name == "external")
3896 return createGuiExternal(*this);
3898 return createGuiShowFile(*this);
3899 if (name == "findreplace")
3900 return createGuiSearch(*this);
3901 if (name == "findreplaceadv")
3902 return createGuiSearchAdv(*this);
3903 if (name == "graphics")
3904 return createGuiGraphics(*this);
3906 return createGuiHyperlink(*this);
3907 if (name == "include")
3908 return createGuiInclude(*this);
3909 if (name == "index")
3910 return createGuiIndex(*this);
3911 if (name == "index_print")
3912 return createGuiPrintindex(*this);
3913 if (name == "label")
3914 return createGuiLabel(*this);
3915 if (name == "listings")
3916 return createGuiListings(*this);
3918 return createGuiLog(*this);
3919 if (name == "mathdelimiter")
3920 return createGuiDelimiter(*this);
3921 if (name == "mathmatrix")
3922 return createGuiMathMatrix(*this);
3923 if (name == "nomenclature")
3924 return createGuiNomenclature(*this);
3925 if (name == "nomencl_print")
3926 return createGuiPrintNomencl(*this);
3928 return createGuiNote(*this);
3929 if (name == "paragraph")
3930 return createGuiParagraph(*this);
3931 if (name == "phantom")
3932 return createGuiPhantom(*this);
3933 if (name == "prefs")
3934 return createGuiPreferences(*this);
3935 if (name == "print")
3936 return createGuiPrint(*this);
3938 return createGuiRef(*this);
3939 if (name == "sendto")
3940 return createGuiSendTo(*this);
3941 if (name == "spellchecker")
3942 return createGuiSpellchecker(*this);
3943 if (name == "symbols")
3944 return createGuiSymbols(*this);
3945 if (name == "tabularcreate")
3946 return createGuiTabularCreate(*this);
3947 if (name == "texinfo")
3948 return createGuiTexInfo(*this);
3949 if (name == "thesaurus")
3950 return createGuiThesaurus(*this);
3952 return createGuiToc(*this);
3953 if (name == "view-source")
3954 return createGuiViewSource(*this);
3956 return createGuiWrap(*this);
3957 if (name == "progress")
3958 return createGuiProgressView(*this);
3964 } // namespace frontend
3967 #include "moc_GuiView.cpp"