]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiView.cpp
Whitespace.
[lyx.git] / src / frontends / qt4 / GuiView.cpp
1 /**
2  * \file GuiView.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Lars Gullik Bjønnes
7  * \author John Levon
8  * \author Abdelrazak Younes
9  * \author Peter Kümmel
10  *
11  * Full author contact details are available in file CREDITS.
12  */
13
14 #include <config.h>
15
16 #include "GuiView.h"
17
18 #include "Dialog.h"
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"
26 #include "GuiToc.h"
27 #include "GuiToolbar.h"
28 #include "GuiWorkArea.h"
29 #include "LayoutBox.h"
30 #include "Menus.h"
31 #include "TocModel.h"
32
33 #include "qt_helpers.h"
34
35 #include "frontends/alert.h"
36
37 #include "buffer_funcs.h"
38 #include "Buffer.h"
39 #include "BufferList.h"
40 #include "BufferParams.h"
41 #include "BufferView.h"
42 #include "Compare.h"
43 #include "Converter.h"
44 #include "Cursor.h"
45 #include "CutAndPaste.h"
46 #include "Encoding.h"
47 #include "ErrorList.h"
48 #include "Format.h"
49 #include "FuncStatus.h"
50 #include "FuncRequest.h"
51 #include "Intl.h"
52 #include "Layout.h"
53 #include "Lexer.h"
54 #include "LyXAction.h"
55 #include "LyX.h"
56 #include "LyXRC.h"
57 #include "LyXVC.h"
58 #include "Paragraph.h"
59 #include "SpellChecker.h"
60 #include "TexRow.h"
61 #include "TextClass.h"
62 #include "Text.h"
63 #include "Toolbars.h"
64 #include "version.h"
65
66 #include "support/convert.h"
67 #include "support/debug.h"
68 #include "support/ExceptionMessage.h"
69 #include "support/FileName.h"
70 #include "support/filetools.h"
71 #include "support/gettext.h"
72 #include "support/filetools.h"
73 #include "support/ForkedCalls.h"
74 #include "support/lassert.h"
75 #include "support/lstrings.h"
76 #include "support/os.h"
77 #include "support/Package.h"
78 #include "support/Path.h"
79 #include "support/Systemcall.h"
80 #include "support/Timeout.h"
81 #include "support/ProgressInterface.h"
82 #include "GuiProgress.h"
83
84 #include <QAction>
85 #include <QApplication>
86 #include <QCloseEvent>
87 #include <QDebug>
88 #include <QDesktopWidget>
89 #include <QDragEnterEvent>
90 #include <QDropEvent>
91 #include <QList>
92 #include <QMenu>
93 #include <QMenuBar>
94 #include <QPainter>
95 #include <QPixmap>
96 #include <QPixmapCache>
97 #include <QPoint>
98 #include <QPushButton>
99 #include <QSettings>
100 #include <QShowEvent>
101 #include <QSplitter>
102 #include <QStackedWidget>
103 #include <QStatusBar>
104 #include <QTime>
105 #include <QTimer>
106 #include <QToolBar>
107 #include <QUrl>
108 #include <QScrollBar>
109
110
111
112 #define EXPORT_in_THREAD 1
113
114 // QtConcurrent was introduced in Qt 4.4
115 #if (QT_VERSION >= 0x040400)
116 #include <QFuture>
117 #include <QFutureWatcher>
118 #include <QtConcurrentRun>
119 #endif
120
121 #include "support/bind.h"
122
123 #include <sstream>
124
125 #ifdef HAVE_SYS_TIME_H
126 # include <sys/time.h>
127 #endif
128 #ifdef HAVE_UNISTD_H
129 # include <unistd.h>
130 #endif
131
132 using namespace std;
133 using namespace lyx::support;
134
135 namespace lyx {
136 namespace frontend {
137
138 namespace {
139
140 class BackgroundWidget : public QWidget
141 {
142 public:
143         BackgroundWidget()
144         {
145                 LYXERR(Debug::GUI, "show banner: " << lyxrc.show_banner);
146                 if (!lyxrc.show_banner)
147                         return;
148                 /// The text to be written on top of the pixmap
149                 QString const text = lyx_version ?
150                         qt_("version ") + lyx_version : qt_("unknown version");
151                 splash_ = getPixmap("images/", "banner", "png");
152
153                 QPainter pain(&splash_);
154                 pain.setPen(QColor(0, 0, 0));
155                 QFont font;
156                 // The font used to display the version info
157                 font.setStyleHint(QFont::SansSerif);
158                 font.setWeight(QFont::Bold);
159                 font.setPointSize(int(toqstr(lyxrc.font_sizes[FONT_SIZE_LARGE]).toDouble()));
160                 int width = QFontMetrics(font).width(text);
161                 pain.setFont(font);
162                 pain.drawText(397 - width, 15, text);
163                 setFocusPolicy(Qt::StrongFocus);
164         }
165
166         void paintEvent(QPaintEvent *)
167         {
168                 int x = (width() - splash_.width()) / 2;
169                 int y = (height() - splash_.height()) / 2;
170                 QPainter pain(this);
171                 pain.drawPixmap(x, y, splash_);
172         }
173
174         void keyPressEvent(QKeyEvent * ev)
175         {
176                 KeySymbol sym;
177                 setKeySymbol(&sym, ev);
178                 if (sym.isOK()) {
179                         guiApp->processKeySym(sym, q_key_state(ev->modifiers()));
180                         ev->accept();
181                 } else {
182                         ev->ignore();
183                 }
184         }
185
186 private:
187         QPixmap splash_;
188 };
189
190
191 /// Toolbar store providing access to individual toolbars by name.
192 typedef map<string, GuiToolbar *> ToolbarMap;
193
194 typedef shared_ptr<Dialog> DialogPtr;
195
196 } // namespace anon
197
198
199 struct GuiView::GuiViewPrivate
200 {
201         GuiViewPrivate(GuiView * gv)
202                 : gv_(gv), current_work_area_(0), current_main_work_area_(0),
203                 layout_(0), autosave_timeout_(5000),
204                 in_show_(false)
205         {
206                 // hardcode here the platform specific icon size
207                 smallIconSize = 14;  // scaling problems
208                 normalIconSize = 20; // ok, default
209                 bigIconSize = 26;       // better for some math icons
210
211                 splitter_ = new QSplitter;
212                 bg_widget_ = new BackgroundWidget;
213                 stack_widget_ = new QStackedWidget;
214                 stack_widget_->addWidget(bg_widget_);
215                 stack_widget_->addWidget(splitter_);
216                 setBackground();
217
218                 // TODO cleanup, remove the singleton, handle multiple Windows?
219                 progress_ = ProgressInterface::instance();
220                 if (!dynamic_cast<GuiProgress*>(progress_)) {
221                         progress_ = new GuiProgress();  // TODO who deletes it
222                         ProgressInterface::setInstance(progress_);
223                 }
224                 QObject::connect(
225                                 dynamic_cast<GuiProgress*>(progress_),
226                                 SIGNAL(updateStatusBarMessage(QString const&)),
227                                 gv, SLOT(updateStatusBarMessage(QString const&)));
228                 QObject::connect(
229                                 dynamic_cast<GuiProgress*>(progress_),
230                                 SIGNAL(clearMessageText()),
231                                 gv, SLOT(clearMessageText()));
232         }
233
234         ~GuiViewPrivate()
235         {
236                 delete splitter_;
237                 delete bg_widget_;
238                 delete stack_widget_;
239         }
240
241         QMenu * toolBarPopup(GuiView * parent)
242         {
243                 // FIXME: translation
244                 QMenu * menu = new QMenu(parent);
245                 QActionGroup * iconSizeGroup = new QActionGroup(parent);
246
247                 QAction * smallIcons = new QAction(iconSizeGroup);
248                 smallIcons->setText(qt_("Small-sized icons"));
249                 smallIcons->setCheckable(true);
250                 QObject::connect(smallIcons, SIGNAL(triggered()),
251                         parent, SLOT(smallSizedIcons()));
252                 menu->addAction(smallIcons);
253
254                 QAction * normalIcons = new QAction(iconSizeGroup);
255                 normalIcons->setText(qt_("Normal-sized icons"));
256                 normalIcons->setCheckable(true);
257                 QObject::connect(normalIcons, SIGNAL(triggered()),
258                         parent, SLOT(normalSizedIcons()));
259                 menu->addAction(normalIcons);
260
261                 QAction * bigIcons = new QAction(iconSizeGroup);
262                 bigIcons->setText(qt_("Big-sized icons"));
263                 bigIcons->setCheckable(true);
264                 QObject::connect(bigIcons, SIGNAL(triggered()),
265                         parent, SLOT(bigSizedIcons()));
266                 menu->addAction(bigIcons);
267
268                 unsigned int cur = parent->iconSize().width();
269                 if ( cur == parent->d.smallIconSize)
270                         smallIcons->setChecked(true);
271                 else if (cur == parent->d.normalIconSize)
272                         normalIcons->setChecked(true);
273                 else if (cur == parent->d.bigIconSize)
274                         bigIcons->setChecked(true);
275
276                 return menu;
277         }
278
279         void setBackground()
280         {
281                 stack_widget_->setCurrentWidget(bg_widget_);
282                 bg_widget_->setUpdatesEnabled(true);
283                 bg_widget_->setFocus();
284         }
285
286         TabWorkArea * tabWorkArea(int i)
287         {
288                 return dynamic_cast<TabWorkArea *>(splitter_->widget(i));
289         }
290
291         TabWorkArea * currentTabWorkArea()
292         {
293                 if (splitter_->count() == 1)
294                         // The first TabWorkArea is always the first one, if any.
295                         return tabWorkArea(0);
296
297                 for (int i = 0; i != splitter_->count(); ++i) {
298                         TabWorkArea * twa = tabWorkArea(i);
299                         if (current_main_work_area_ == twa->currentWorkArea())
300                                 return twa;
301                 }
302
303                 // None has the focus so we just take the first one.
304                 return tabWorkArea(0);
305         }
306
307 #if (QT_VERSION >= 0x040400)
308         void setPreviewFuture(QFuture<docstring> const & f)
309         {
310                 if (preview_watcher_.isRunning()) {
311                         // we prefer to cancel this preview in order to keep a snappy
312                         // interface.
313                         return;
314                 }
315                 preview_watcher_.setFuture(f);
316         }
317 #endif
318
319 public:
320         GuiView * gv_;
321         GuiWorkArea * current_work_area_;
322         GuiWorkArea * current_main_work_area_;
323         QSplitter * splitter_;
324         QStackedWidget * stack_widget_;
325         BackgroundWidget * bg_widget_;
326         /// view's toolbars
327         ToolbarMap toolbars_;
328         ProgressInterface* progress_;
329         /// The main layout box.
330         /**
331          * \warning Don't Delete! The layout box is actually owned by
332          * whichever toolbar contains it. All the GuiView class needs is a
333          * means of accessing it.
334          *
335          * FIXME: replace that with a proper model so that we are not limited
336          * to only one dialog.
337          */
338         LayoutBox * layout_;
339
340         ///
341         map<string, DialogPtr> dialogs_;
342
343         unsigned int smallIconSize;
344         unsigned int normalIconSize;
345         unsigned int bigIconSize;
346         ///
347         QTimer statusbar_timer_;
348         /// auto-saving of buffers
349         Timeout autosave_timeout_;
350         /// flag against a race condition due to multiclicks, see bug #1119
351         bool in_show_;
352
353         ///
354         TocModels toc_models_;
355
356 #if (QT_VERSION >= 0x040400)
357         ///
358         QFutureWatcher<docstring> autosave_watcher_;
359         QFutureWatcher<docstring> preview_watcher_;
360         ///
361         string last_export_format;
362 #else
363         struct DummyWatcher { bool isRunning(){return false;} };
364         DummyWatcher preview_watcher_;
365 #endif
366
367         static QSet<Buffer const *> busyBuffers;
368         static docstring previewAndDestroy(Buffer const * orig, Buffer * buffer, string const & format);
369         static docstring exportAndDestroy(Buffer const * orig, Buffer * buffer, string const & format);
370         static docstring saveAndDestroy(Buffer const * orig, Buffer * buffer, FileName const & fname);
371
372 };
373
374 QSet<Buffer const *> GuiView::GuiViewPrivate::busyBuffers;
375
376
377 GuiView::GuiView(int id)
378         : d(*new GuiViewPrivate(this)), id_(id), closing_(false)
379 {
380         // GuiToolbars *must* be initialised before the menu bar.
381         normalSizedIcons(); // at least on Mac the default is 32 otherwise, which is huge
382         constructToolbars();
383
384         // set ourself as the current view. This is needed for the menu bar
385         // filling, at least for the static special menu item on Mac. Otherwise
386         // they are greyed out.
387         guiApp->setCurrentView(this);
388
389         // Fill up the menu bar.
390         guiApp->menus().fillMenuBar(menuBar(), this, true);
391
392         setCentralWidget(d.stack_widget_);
393
394         // Start autosave timer
395         if (lyxrc.autosave) {
396                 d.autosave_timeout_.timeout.connect(bind(&GuiView::autoSave, this));
397                 d.autosave_timeout_.setTimeout(lyxrc.autosave * 1000);
398                 d.autosave_timeout_.start();
399         }
400         connect(&d.statusbar_timer_, SIGNAL(timeout()),
401                 this, SLOT(clearMessage()));
402
403         // We don't want to keep the window in memory if it is closed.
404         setAttribute(Qt::WA_DeleteOnClose, true);
405
406 #if (!defined(Q_WS_WIN) && !defined(Q_WS_MACX))
407         // assign an icon to main form. We do not do it under Qt/Win or Qt/Mac,
408         // since the icon is provided in the application bundle.
409         setWindowIcon(getPixmap("images/", "lyx", "png"));
410 #endif
411
412 #if (QT_VERSION >= 0x040300)
413         // use tabbed dock area for multiple docks
414         // (such as "source" and "messages")
415         setDockOptions(QMainWindow::ForceTabbedDocks);
416 #endif
417
418         // For Drag&Drop.
419         setAcceptDrops(true);
420
421         statusBar()->setSizeGripEnabled(true);
422         updateStatusBar();
423
424 #if (QT_VERSION >= 0x040400)
425         connect(&d.autosave_watcher_, SIGNAL(finished()), this,
426                 SLOT(threadFinished()));
427         connect(&d.preview_watcher_, SIGNAL(finished()), this,
428                 SLOT(threadFinished()));
429 #endif
430
431         connect(this, SIGNAL(triggerShowDialog(QString const &, QString const &, Inset *)),
432                 SLOT(doShowDialog(QString const &, QString const &, Inset *)));
433
434         // Forbid too small unresizable window because it can happen
435         // with some window manager under X11.
436         setMinimumSize(300, 200);
437
438         if (lyxrc.allow_geometry_session) {
439                 // Now take care of session management.
440                 if (restoreLayout())
441                         return;
442         }
443
444         // no session handling, default to a sane size.
445         setGeometry(50, 50, 690, 510);
446         initToolbars();
447
448         // clear session data if any.
449         QSettings settings;
450         settings.remove("views");
451 }
452
453
454 GuiView::~GuiView()
455 {
456         delete &d;
457 }
458
459
460 void GuiView::threadFinished()
461 {
462 #if (QT_VERSION >= 0x040400)
463         QFutureWatcher<docstring> const * watcher =
464                 static_cast<QFutureWatcher<docstring> const *>(sender());
465         message(watcher->result());
466         updateToolbars();
467         errors(d.last_export_format);
468 #endif
469 }
470
471
472 void GuiView::saveLayout() const
473 {
474         QSettings settings;
475         settings.beginGroup("views");
476         settings.beginGroup(QString::number(id_));
477 #ifdef Q_WS_X11
478         settings.setValue("pos", pos());
479         settings.setValue("size", size());
480 #else
481         settings.setValue("geometry", saveGeometry());
482 #endif
483         settings.setValue("layout", saveState(0));
484         settings.setValue("icon_size", iconSize());
485 }
486
487
488 bool GuiView::restoreLayout()
489 {
490         QSettings settings;
491         settings.beginGroup("views");
492         settings.beginGroup(QString::number(id_));
493         QString const icon_key = "icon_size";
494         if (!settings.contains(icon_key))
495                 return false;
496
497         //code below is skipped when when ~/.config/LyX is (re)created
498         setIconSize(settings.value(icon_key).toSize());
499 #ifdef Q_WS_X11
500         QPoint pos = settings.value("pos", QPoint(50, 50)).toPoint();
501         QSize size = settings.value("size", QSize(690, 510)).toSize();
502         resize(size);
503         move(pos);
504 #else
505         // Work-around for bug #6034: the window ends up in an undetermined
506         // state when trying to restore a maximized window when it is
507         // already maximized.
508         if (!(windowState() & Qt::WindowMaximized))
509                 if (!restoreGeometry(settings.value("geometry").toByteArray()))
510                         setGeometry(50, 50, 690, 510);
511 #endif
512         // Make sure layout is correctly oriented.
513         setLayoutDirection(qApp->layoutDirection());
514
515         // Allow the toc and view-source dock widget to be restored if needed.
516         Dialog * dialog;
517         if ((dialog = findOrBuild("toc", true)))
518                 // see bug 5082. At least setup title and enabled state.
519                 // Visibility will be adjusted by restoreState below.
520                 dialog->prepareView();
521         if ((dialog = findOrBuild("view-source", true)))
522                 dialog->prepareView();
523         if ((dialog = findOrBuild("progress", true)))
524                 dialog->prepareView();
525
526         if (!restoreState(settings.value("layout").toByteArray(), 0))
527                 initToolbars();
528         updateDialogs();
529         return true;
530 }
531
532
533 GuiToolbar * GuiView::toolbar(string const & name)
534 {
535         ToolbarMap::iterator it = d.toolbars_.find(name);
536         if (it != d.toolbars_.end())
537                 return it->second;
538
539         LYXERR(Debug::GUI, "Toolbar::display: no toolbar named " << name);
540         return 0;
541 }
542
543
544 void GuiView::constructToolbars()
545 {
546         ToolbarMap::iterator it = d.toolbars_.begin();
547         for (; it != d.toolbars_.end(); ++it)
548                 delete it->second;
549         d.toolbars_.clear();
550
551         // I don't like doing this here, but the standard toolbar
552         // destroys this object when it's destroyed itself (vfr)
553         d.layout_ = new LayoutBox(*this);
554         d.stack_widget_->addWidget(d.layout_);
555         d.layout_->move(0,0);
556
557         // extracts the toolbars from the backend
558         Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
559         Toolbars::Infos::iterator end = guiApp->toolbars().end();
560         for (; cit != end; ++cit)
561                 d.toolbars_[cit->name] =  new GuiToolbar(*cit, *this);
562 }
563
564
565 void GuiView::initToolbars()
566 {
567         // extracts the toolbars from the backend
568         Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
569         Toolbars::Infos::iterator end = guiApp->toolbars().end();
570         for (; cit != end; ++cit) {
571                 GuiToolbar * tb = toolbar(cit->name);
572                 if (!tb)
573                         continue;
574                 int const visibility = guiApp->toolbars().defaultVisibility(cit->name);
575                 bool newline = !(visibility & Toolbars::SAMEROW);
576                 tb->setVisible(false);
577                 tb->setVisibility(visibility);
578
579                 if (visibility & Toolbars::TOP) {
580                         if (newline)
581                                 addToolBarBreak(Qt::TopToolBarArea);
582                         addToolBar(Qt::TopToolBarArea, tb);
583                 }
584
585                 if (visibility & Toolbars::BOTTOM) {
586                         // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
587 #if (QT_VERSION >= 0x040202)
588                         if (newline)
589                                 addToolBarBreak(Qt::BottomToolBarArea);
590 #endif
591                         addToolBar(Qt::BottomToolBarArea, tb);
592                 }
593
594                 if (visibility & Toolbars::LEFT) {
595                         // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
596 #if (QT_VERSION >= 0x040202)
597                         if (newline)
598                                 addToolBarBreak(Qt::LeftToolBarArea);
599 #endif
600                         addToolBar(Qt::LeftToolBarArea, tb);
601                 }
602
603                 if (visibility & Toolbars::RIGHT) {
604                         // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
605 #if (QT_VERSION >= 0x040202)
606                         if (newline)
607                                 addToolBarBreak(Qt::RightToolBarArea);
608 #endif
609                         addToolBar(Qt::RightToolBarArea, tb);
610                 }
611
612                 if (visibility & Toolbars::ON)
613                         tb->setVisible(true);
614         }
615 }
616
617
618 TocModels & GuiView::tocModels()
619 {
620         return d.toc_models_;
621 }
622
623
624 void GuiView::setFocus()
625 {
626         LYXERR(Debug::DEBUG, "GuiView::setFocus()" << this);
627         QMainWindow::setFocus();
628 }
629
630
631 void GuiView::focusInEvent(QFocusEvent * e)
632 {
633         LYXERR(Debug::DEBUG, "GuiView::focusInEvent()" << this);
634         QMainWindow::focusInEvent(e);
635         // Make sure guiApp points to the correct view.
636         guiApp->setCurrentView(this);
637         if (currentMainWorkArea())
638                 currentMainWorkArea()->setFocus();
639         else if (currentWorkArea())
640                 currentWorkArea()->setFocus();
641         else
642                 d.bg_widget_->setFocus();
643 }
644
645
646 QMenu * GuiView::createPopupMenu()
647 {
648         return d.toolBarPopup(this);
649 }
650
651
652 void GuiView::showEvent(QShowEvent * e)
653 {
654         LYXERR(Debug::GUI, "Passed Geometry "
655                 << size().height() << "x" << size().width()
656                 << "+" << pos().x() << "+" << pos().y());
657
658         if (d.splitter_->count() == 0)
659                 // No work area, switch to the background widget.
660                 d.setBackground();
661
662         QMainWindow::showEvent(e);
663 }
664
665
666 bool GuiView::closeScheduled()
667 {
668         closing_ = true;
669         return close();
670 }
671
672
673 /** Destroy only all tabbed WorkAreas. Destruction of other WorkAreas
674  ** is responsibility of the container (e.g., dialog)
675  **/
676 void GuiView::closeEvent(QCloseEvent * close_event)
677 {
678         LYXERR(Debug::DEBUG, "GuiView::closeEvent()");
679
680         if (!GuiViewPrivate::busyBuffers.isEmpty()) {
681                 Alert::warning(_("Exit LyX"), _("LyX could not be closed because documents are processed by LyX."));
682                 close_event->setAccepted(false);
683                 return;
684         }
685
686         // If the user pressed the x (so we didn't call closeView
687         // programmatically), we want to clear all existing entries.
688         if (!closing_)
689                 theSession().lastOpened().clear();
690         closing_ = true;
691
692         writeSession();
693
694         // it can happen that this event arrives without selecting the view,
695         // e.g. when clicking the close button on a background window.
696         setFocus();
697         if (!closeWorkAreaAll()) {
698                 closing_ = false;
699                 close_event->ignore();
700                 return;
701         }
702
703         // Make sure that nothing will use this to be closed View.
704         guiApp->unregisterView(this);
705
706         if (isFullScreen()) {
707                 // Switch off fullscreen before closing.
708                 toggleFullScreen();
709                 updateDialogs();
710         }
711
712         // Make sure the timer time out will not trigger a statusbar update.
713         d.statusbar_timer_.stop();
714
715         // Saving fullscreen requires additional tweaks in the toolbar code.
716         // It wouldn't also work under linux natively.
717         if (lyxrc.allow_geometry_session) {
718                 // Save this window geometry and layout.
719                 saveLayout();
720                 // Then the toolbar private states.
721                 ToolbarMap::iterator end = d.toolbars_.end();
722                 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
723                         it->second->saveSession();
724                 // Now take care of all other dialogs:
725                 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
726                 for (; it!= d.dialogs_.end(); ++it)
727                         it->second->saveSession();
728         }
729
730         close_event->accept();
731 }
732
733
734 void GuiView::dragEnterEvent(QDragEnterEvent * event)
735 {
736         if (event->mimeData()->hasUrls())
737                 event->accept();
738         /// \todo Ask lyx-devel is this is enough:
739         /// if (event->mimeData()->hasFormat("text/plain"))
740         ///     event->acceptProposedAction();
741 }
742
743
744 void GuiView::dropEvent(QDropEvent * event)
745 {
746         QList<QUrl> files = event->mimeData()->urls();
747         if (files.isEmpty())
748                 return;
749
750         LYXERR(Debug::GUI, "GuiView::dropEvent: got URLs!");
751         for (int i = 0; i != files.size(); ++i) {
752                 string const file = os::internal_path(fromqstr(
753                         files.at(i).toLocalFile()));
754                 if (file.empty())
755                         continue;
756
757                 string const ext = support::getExtension(file);
758                 vector<const Format *> found_formats;
759
760                 // Find all formats that have the correct extension.
761                 vector<const Format *> const & import_formats
762                         = theConverters().importableFormats();
763                 vector<const Format *>::const_iterator it = import_formats.begin();
764                 for (; it != import_formats.end(); ++it)
765                         if ((*it)->extension() == ext)
766                                 found_formats.push_back(*it);
767
768                 FuncRequest cmd;
769                 if (found_formats.size() >= 1) {
770                         if (found_formats.size() > 1) {
771                                 //FIXME: show a dialog to choose the correct importable format
772                                 LYXERR(Debug::FILES,
773                                         "Multiple importable formats found, selecting first");
774                         }
775                         string const arg = found_formats[0]->name() + " " + file;
776                         cmd = FuncRequest(LFUN_BUFFER_IMPORT, arg);
777                 }
778                 else {
779                         //FIXME: do we have to explicitly check whether it's a lyx file?
780                         LYXERR(Debug::FILES,
781                                 "No formats found, trying to open it as a lyx file");
782                         cmd = FuncRequest(LFUN_FILE_OPEN, file);
783                 }
784
785                 // Asynchronously post the event. DropEvent usually comes
786                 // from the BufferView. But reloading a file might close
787                 // the BufferView from within its own event handler.
788                 guiApp->dispatchDelayed(cmd);
789                 event->accept();
790         }
791 }
792
793
794 void GuiView::message(docstring const & str)
795 {
796         if (ForkedProcess::iAmAChild())
797                 return;
798
799         // call is moved to GUI-thread by GuiProgress
800         d.progress_->appendMessage(toqstr(str));
801 }
802
803
804 void GuiView::clearMessageText()
805 {
806         message(docstring());
807 }
808
809
810 void GuiView::updateStatusBarMessage(QString const & str)
811 {
812         statusBar()->showMessage(str);
813         d.statusbar_timer_.stop();
814         d.statusbar_timer_.start(3000);
815 }
816
817
818 void GuiView::smallSizedIcons()
819 {
820         setIconSize(QSize(d.smallIconSize, d.smallIconSize));
821 }
822
823
824 void GuiView::normalSizedIcons()
825 {
826         setIconSize(QSize(d.normalIconSize, d.normalIconSize));
827 }
828
829
830 void GuiView::bigSizedIcons()
831 {
832         setIconSize(QSize(d.bigIconSize, d.bigIconSize));
833 }
834
835
836 void GuiView::clearMessage()
837 {
838         // FIXME: This code was introduced in r19643 to fix bug #4123. However,
839         // the hasFocus function mostly returns false, even if the focus is on
840         // a workarea in this view.
841         //if (!hasFocus())
842         //      return;
843         showMessage();
844         d.statusbar_timer_.stop();
845 }
846
847
848 void GuiView::updateWindowTitle(GuiWorkArea * wa)
849 {
850         if (wa != d.current_work_area_
851                 || wa->bufferView().buffer().isInternal())
852                 return;
853         setWindowTitle(qt_("LyX: ") + wa->windowTitle());
854         setWindowIconText(wa->windowIconText());
855 }
856
857
858 void GuiView::on_currentWorkAreaChanged(GuiWorkArea * wa)
859 {
860         disconnectBuffer();
861         disconnectBufferView();
862         connectBufferView(wa->bufferView());
863         connectBuffer(wa->bufferView().buffer());
864         d.current_work_area_ = wa;
865         QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
866                 this, SLOT(updateWindowTitle(GuiWorkArea *)));
867         updateWindowTitle(wa);
868
869         structureChanged();
870
871         // The document settings needs to be reinitialised.
872         updateDialog("document", "");
873
874         // Buffer-dependent dialogs must be updated. This is done here because
875         // some dialogs require buffer()->text.
876         updateDialogs();
877 }
878
879
880 void GuiView::on_lastWorkAreaRemoved()
881 {
882         if (closing_)
883                 // We already are in a close event. Nothing more to do.
884                 return;
885
886         if (d.splitter_->count() > 1)
887                 // We have a splitter so don't close anything.
888                 return;
889
890         // Reset and updates the dialogs.
891         d.toc_models_.reset(0);
892         updateDialog("document", "");
893         updateDialogs();
894
895         resetWindowTitleAndIconText();
896         updateStatusBar();
897
898         if (lyxrc.open_buffers_in_tabs)
899                 // Nothing more to do, the window should stay open.
900                 return;
901
902         if (guiApp->viewIds().size() > 1) {
903                 close();
904                 return;
905         }
906
907 #ifdef Q_WS_MACX
908         // On Mac we also close the last window because the application stay
909         // resident in memory. On other platforms we don't close the last
910         // window because this would quit the application.
911         close();
912 #endif
913 }
914
915
916 void GuiView::updateStatusBar()
917 {
918         // let the user see the explicit message
919         if (d.statusbar_timer_.isActive())
920                 return;
921
922         showMessage();
923 }
924
925
926 void GuiView::showMessage()
927 {
928         QString msg = toqstr(theGuiApp()->viewStatusMessage());
929         if (msg.isEmpty()) {
930                 BufferView const * bv = currentBufferView();
931                 if (bv)
932                         msg = toqstr(bv->cursor().currentState());
933                 else
934                         msg = qt_("Welcome to LyX!");
935         }
936         statusBar()->showMessage(msg);
937 }
938
939
940 bool GuiView::event(QEvent * e)
941 {
942         switch (e->type())
943         {
944         // Useful debug code:
945         //case QEvent::ActivationChange:
946         //case QEvent::WindowDeactivate:
947         //case QEvent::Paint:
948         //case QEvent::Enter:
949         //case QEvent::Leave:
950         //case QEvent::HoverEnter:
951         //case QEvent::HoverLeave:
952         //case QEvent::HoverMove:
953         //case QEvent::StatusTip:
954         //case QEvent::DragEnter:
955         //case QEvent::DragLeave:
956         //case QEvent::Drop:
957         //      break;
958
959         case QEvent::WindowActivate: {
960                 GuiView * old_view = guiApp->currentView();
961                 if (this == old_view) {
962                         setFocus();
963                         return QMainWindow::event(e);
964                 }
965                 if (old_view && old_view->currentBufferView()) {
966                         // save current selection to the selection buffer to allow
967                         // middle-button paste in this window.
968                         cap::saveSelection(old_view->currentBufferView()->cursor());
969                 }
970                 guiApp->setCurrentView(this);
971                 if (d.current_work_area_) {
972                         BufferView & bv = d.current_work_area_->bufferView();
973                         connectBufferView(bv);
974                         connectBuffer(bv.buffer());
975                         // The document structure, name and dialogs might have
976                         // changed in another view.
977                         structureChanged();
978                         // The document settings needs to be reinitialised.
979                         updateDialog("document", "");
980                         updateDialogs();
981                 } else {
982                         resetWindowTitleAndIconText();
983                 }
984                 setFocus();
985                 return QMainWindow::event(e);
986         }
987
988         case QEvent::ShortcutOverride: {
989
990 // See bug 4888
991 #if (!defined Q_WS_X11) || (QT_VERSION >= 0x040500)
992                 if (isFullScreen() && menuBar()->isHidden()) {
993                         QKeyEvent * ke = static_cast<QKeyEvent*>(e);
994                         // FIXME: we should also try to detect special LyX shortcut such as
995                         // Alt-P and Alt-M. Right now there is a hack in
996                         // GuiWorkArea::processKeySym() that hides again the menubar for
997                         // those cases.
998                         if (ke->modifiers() & Qt::AltModifier && ke->key() != Qt::Key_Alt) {
999                                 menuBar()->show();
1000                                 return QMainWindow::event(e);
1001                         }
1002                 }
1003 #endif
1004                 return QMainWindow::event(e);
1005         }
1006
1007         default:
1008                 return QMainWindow::event(e);
1009         }
1010 }
1011
1012 void GuiView::resetWindowTitleAndIconText()
1013 {
1014         setWindowTitle(qt_("LyX"));
1015         setWindowIconText(qt_("LyX"));
1016 }
1017
1018 bool GuiView::focusNextPrevChild(bool /*next*/)
1019 {
1020         setFocus();
1021         return true;
1022 }
1023
1024
1025 bool GuiView::busy() const
1026 {
1027         return busy_;
1028 }
1029
1030
1031 void GuiView::setBusy(bool busy)
1032 {
1033         busy_ = busy;
1034         if (d.current_work_area_) {
1035                 d.current_work_area_->setUpdatesEnabled(!busy);
1036                 if (busy)
1037                         d.current_work_area_->stopBlinkingCursor();
1038                 else
1039                         d.current_work_area_->startBlinkingCursor();
1040         }
1041
1042         if (busy)
1043                 QApplication::setOverrideCursor(Qt::WaitCursor);
1044         else
1045                 QApplication::restoreOverrideCursor();
1046 }
1047
1048
1049 GuiWorkArea * GuiView::workArea(Buffer & buffer)
1050 {
1051         if (currentWorkArea()
1052                 && &currentWorkArea()->bufferView().buffer() == &buffer)
1053                 return (GuiWorkArea *) currentWorkArea();
1054         if (TabWorkArea * twa = d.currentTabWorkArea())
1055                 return twa->workArea(buffer);
1056         return 0;
1057 }
1058
1059
1060 GuiWorkArea * GuiView::addWorkArea(Buffer & buffer)
1061 {
1062         // Automatically create a TabWorkArea if there are none yet.
1063         TabWorkArea * tab_widget = d.splitter_->count()
1064                 ? d.currentTabWorkArea() : addTabWorkArea();
1065         return tab_widget->addWorkArea(buffer, *this);
1066 }
1067
1068
1069 TabWorkArea * GuiView::addTabWorkArea()
1070 {
1071         TabWorkArea * twa = new TabWorkArea;
1072         QObject::connect(twa, SIGNAL(currentWorkAreaChanged(GuiWorkArea *)),
1073                 this, SLOT(on_currentWorkAreaChanged(GuiWorkArea *)));
1074         QObject::connect(twa, SIGNAL(lastWorkAreaRemoved()),
1075                          this, SLOT(on_lastWorkAreaRemoved()));
1076
1077         d.splitter_->addWidget(twa);
1078         d.stack_widget_->setCurrentWidget(d.splitter_);
1079         return twa;
1080 }
1081
1082
1083 GuiWorkArea const * GuiView::currentWorkArea() const
1084 {
1085         return d.current_work_area_;
1086 }
1087
1088
1089 GuiWorkArea * GuiView::currentWorkArea()
1090 {
1091         return d.current_work_area_;
1092 }
1093
1094
1095 GuiWorkArea const * GuiView::currentMainWorkArea() const
1096 {
1097         if (!d.currentTabWorkArea())
1098                 return 0;
1099         return d.currentTabWorkArea()->currentWorkArea();
1100 }
1101
1102
1103 GuiWorkArea * GuiView::currentMainWorkArea()
1104 {
1105         if (!d.currentTabWorkArea())
1106                 return 0;
1107         return d.currentTabWorkArea()->currentWorkArea();
1108 }
1109
1110
1111 void GuiView::setCurrentWorkArea(GuiWorkArea * wa)
1112 {
1113         LYXERR(Debug::DEBUG, "Setting current wa: " << wa << endl);
1114         if (!wa) {
1115                 d.current_work_area_ = 0;
1116                 d.setBackground();
1117                 return;
1118         }
1119
1120         // FIXME: I've no clue why this is here and why it accesses
1121         //  theGuiApp()->currentView, which might be 0 (bug 6464).
1122         //  See also 27525 (vfr).
1123         if (theGuiApp()->currentView() == this
1124                   && theGuiApp()->currentView()->currentWorkArea() == wa)
1125                 return;
1126
1127         if (currentBufferView())
1128                 cap::saveSelection(currentBufferView()->cursor());
1129
1130         theGuiApp()->setCurrentView(this);
1131         d.current_work_area_ = wa;
1132         for (int i = 0; i != d.splitter_->count(); ++i) {
1133                 if (d.tabWorkArea(i)->setCurrentWorkArea(wa)) {
1134                         //if (d.current_main_work_area_)
1135                         //      d.current_main_work_area_->setFrameStyle(QFrame::NoFrame);
1136                         d.current_main_work_area_ = wa;
1137                         //d.current_main_work_area_->setFrameStyle(QFrame::Box | QFrame::Plain);
1138                         //d.current_main_work_area_->setLineWidth(2);
1139                         LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() << ", Current main wa: " << currentMainWorkArea());
1140                         return;
1141                 }
1142         }
1143         LYXERR(Debug::DEBUG, "This is not a tabbed wa");
1144         on_currentWorkAreaChanged(wa);
1145         BufferView & bv = wa->bufferView();
1146         bv.cursor().fixIfBroken();
1147         bv.updateMetrics();
1148         wa->setUpdatesEnabled(true);
1149         LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() << ", Current main wa: " << currentMainWorkArea());
1150 }
1151
1152
1153 void GuiView::removeWorkArea(GuiWorkArea * wa)
1154 {
1155         LASSERT(wa, return);
1156         if (wa == d.current_work_area_) {
1157                 disconnectBuffer();
1158                 disconnectBufferView();
1159                 d.current_work_area_ = 0;
1160                 d.current_main_work_area_ = 0;
1161         }
1162
1163         bool found_twa = false;
1164         for (int i = 0; i != d.splitter_->count(); ++i) {
1165                 TabWorkArea * twa = d.tabWorkArea(i);
1166                 if (twa->removeWorkArea(wa)) {
1167                         // Found in this tab group, and deleted the GuiWorkArea.
1168                         found_twa = true;
1169                         if (twa->count() != 0) {
1170                                 if (d.current_work_area_ == 0)
1171                                         // This means that we are closing the current GuiWorkArea, so
1172                                         // switch to the next GuiWorkArea in the found TabWorkArea.
1173                                         setCurrentWorkArea(twa->currentWorkArea());
1174                         } else {
1175                                 // No more WorkAreas in this tab group, so delete it.
1176                                 delete twa;
1177                         }
1178                         break;
1179                 }
1180         }
1181
1182         // It is not a tabbed work area (i.e., the search work area), so it
1183         // should be deleted by other means.
1184         LASSERT(found_twa, /* */);
1185
1186         if (d.current_work_area_ == 0) {
1187                 if (d.splitter_->count() != 0) {
1188                         TabWorkArea * twa = d.currentTabWorkArea();
1189                         setCurrentWorkArea(twa->currentWorkArea());
1190                 } else {
1191                         // No more work areas, switch to the background widget.
1192                         setCurrentWorkArea(0);
1193                 }
1194         }
1195 }
1196
1197
1198 LayoutBox * GuiView::getLayoutDialog() const
1199 {
1200         return d.layout_;
1201 }
1202
1203
1204 void GuiView::updateLayoutList()
1205 {
1206         if (d.layout_)
1207                 d.layout_->updateContents(false);
1208 }
1209
1210
1211 void GuiView::updateToolbars()
1212 {
1213         ToolbarMap::iterator end = d.toolbars_.end();
1214         if (d.current_work_area_) {
1215                 bool const math =
1216                         d.current_work_area_->bufferView().cursor().inMathed()
1217                         && !d.current_work_area_->bufferView().cursor().inRegexped();
1218                 bool const table =
1219                         lyx::getStatus(FuncRequest(LFUN_LAYOUT_TABULAR)).enabled();
1220                 bool const review =
1221                         lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).enabled() &&
1222                         lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).onOff(true);
1223                 bool const mathmacrotemplate =
1224                         lyx::getStatus(FuncRequest(LFUN_IN_MATHMACROTEMPLATE)).enabled();
1225
1226                 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1227                         it->second->update(math, table, review, mathmacrotemplate);
1228         } else
1229                 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1230                         it->second->update(false, false, false, false);
1231 }
1232
1233
1234 void GuiView::setBuffer(Buffer * newBuffer)
1235 {
1236         LYXERR(Debug::DEBUG, "Setting buffer: " << newBuffer << endl);
1237         LASSERT(newBuffer, return);
1238         setBusy(true);
1239
1240         GuiWorkArea * wa = workArea(*newBuffer);
1241         if (wa == 0) {
1242                 newBuffer->masterBuffer()->updateBuffer();
1243                 wa = addWorkArea(*newBuffer);
1244         } else {
1245                 //Disconnect the old buffer...there's no new one.
1246                 disconnectBuffer();
1247         }
1248         connectBuffer(*newBuffer);
1249         connectBufferView(wa->bufferView());
1250         setCurrentWorkArea(wa);
1251
1252         setBusy(false);
1253 }
1254
1255
1256 void GuiView::connectBuffer(Buffer & buf)
1257 {
1258         buf.setGuiDelegate(this);
1259 }
1260
1261
1262 void GuiView::disconnectBuffer()
1263 {
1264         if (d.current_work_area_)
1265                 d.current_work_area_->bufferView().buffer().setGuiDelegate(0);
1266 }
1267
1268
1269 void GuiView::connectBufferView(BufferView & bv)
1270 {
1271         bv.setGuiDelegate(this);
1272 }
1273
1274
1275 void GuiView::disconnectBufferView()
1276 {
1277         if (d.current_work_area_)
1278                 d.current_work_area_->bufferView().setGuiDelegate(0);
1279 }
1280
1281
1282 void GuiView::errors(string const & error_type, bool from_master)
1283 {
1284         ErrorList & el = from_master ?
1285                 currentBufferView()->buffer().masterBuffer()->errorList(error_type)
1286                 : currentBufferView()->buffer().errorList(error_type);
1287         string data = error_type;
1288         if (from_master)
1289                 data = "from_master|" + error_type;
1290         if (!el.empty())
1291                 showDialog("errorlist", data);
1292 }
1293
1294
1295 void GuiView::updateTocItem(string const & type, DocIterator const & dit)
1296 {
1297         d.toc_models_.updateItem(toqstr(type), dit);
1298 }
1299
1300
1301 void GuiView::structureChanged()
1302 {
1303         d.toc_models_.reset(documentBufferView());
1304         // Navigator needs more than a simple update in this case. It needs to be
1305         // rebuilt.
1306         updateDialog("toc", "");
1307 }
1308
1309
1310 void GuiView::updateDialog(string const & name, string const & data)
1311 {
1312         if (!isDialogVisible(name))
1313                 return;
1314
1315         map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
1316         if (it == d.dialogs_.end())
1317                 return;
1318
1319         Dialog * const dialog = it->second.get();
1320         if (dialog->isVisibleView())
1321                 dialog->initialiseParams(data);
1322 }
1323
1324
1325 BufferView * GuiView::documentBufferView()
1326 {
1327         return currentMainWorkArea()
1328                 ? &currentMainWorkArea()->bufferView()
1329                 : 0;
1330 }
1331
1332
1333 BufferView const * GuiView::documentBufferView() const
1334 {
1335         return currentMainWorkArea()
1336                 ? &currentMainWorkArea()->bufferView()
1337                 : 0;
1338 }
1339
1340
1341 BufferView * GuiView::currentBufferView()
1342 {
1343         return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1344 }
1345
1346
1347 BufferView const * GuiView::currentBufferView() const
1348 {
1349         return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1350 }
1351
1352
1353 #if (QT_VERSION >= 0x040400)
1354 docstring GuiView::GuiViewPrivate::saveAndDestroy(Buffer const * orig, Buffer * buffer, FileName const & fname)
1355 {
1356         bool failed = true;
1357         FileName const tmp_ret = FileName::tempName("lyxauto");
1358         if (!tmp_ret.empty()) {
1359                 if (buffer->writeFile(tmp_ret))
1360                         failed = !tmp_ret.moveTo(fname);
1361         }
1362         if (failed) {
1363                 // failed to write/rename tmp_ret so try writing direct
1364                 failed = buffer->writeFile(fname);
1365         }
1366         delete buffer;
1367         busyBuffers.remove(orig);
1368         return failed
1369                 ? _("Automatic save failed!")
1370                 : _("Automatic save done.");
1371 }
1372 #endif
1373
1374
1375 void GuiView::autoSave()
1376 {
1377         LYXERR(Debug::INFO, "Running autoSave()");
1378
1379         Buffer * buffer = documentBufferView()
1380                 ? &documentBufferView()->buffer() : 0;
1381         if (!buffer)
1382                 return;
1383
1384 #if (QT_VERSION >= 0x040400)
1385         GuiViewPrivate::busyBuffers.insert(buffer);
1386         QFuture<docstring> f = QtConcurrent::run(GuiViewPrivate::saveAndDestroy, buffer, buffer->clone(),
1387                 buffer->getAutosaveFileName());
1388         d.autosave_watcher_.setFuture(f);
1389 #else
1390         buffer->autoSave();
1391 #endif
1392 }
1393
1394
1395 void GuiView::resetAutosaveTimers()
1396 {
1397         if (lyxrc.autosave)
1398                 d.autosave_timeout_.restart();
1399 }
1400
1401
1402 bool GuiView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1403 {
1404         bool enable = true;
1405         Buffer * buf = currentBufferView()
1406                 ? &currentBufferView()->buffer() : 0;
1407         Buffer * doc_buffer = documentBufferView()
1408                 ? &(documentBufferView()->buffer()) : 0;
1409
1410         // Check whether we need a buffer
1411         if (!lyxaction.funcHasFlag(cmd.action(), LyXAction::NoBuffer) && !buf) {
1412                 // no, exit directly
1413                 flag.message(from_utf8(N_("Command not allowed with"
1414                                         "out any document open")));
1415                 flag.setEnabled(false);
1416                 return true;
1417         }
1418
1419         if (cmd.origin() == FuncRequest::TOC) {
1420                 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
1421                 if (!toc || !toc->getStatus(documentBufferView()->cursor(), cmd, flag))
1422                         flag.setEnabled(false);
1423                 return true;
1424         }
1425
1426         switch(cmd.action()) {
1427         case LFUN_BUFFER_IMPORT:
1428                 break;
1429
1430         case LFUN_MASTER_BUFFER_UPDATE:
1431         case LFUN_MASTER_BUFFER_VIEW:
1432                 enable = doc_buffer && doc_buffer->parent() != 0
1433                         && !d.preview_watcher_.isRunning();
1434                 break;
1435
1436         case LFUN_BUFFER_UPDATE:
1437         case LFUN_BUFFER_VIEW: {
1438                 if (!doc_buffer || d.preview_watcher_.isRunning()) {
1439                         enable = false;
1440                         break;
1441                 }
1442                 string format = to_utf8(cmd.argument());
1443                 if (cmd.argument().empty())
1444                         format = doc_buffer->getDefaultOutputFormat();
1445                 enable = doc_buffer->isExportableFormat(format);
1446                 break;
1447         }
1448
1449         case LFUN_BUFFER_RELOAD:
1450                 enable = doc_buffer && !doc_buffer->isUnnamed()
1451                         && doc_buffer->fileName().exists()
1452                         && (!doc_buffer->isClean()
1453                            || doc_buffer->isExternallyModified(Buffer::timestamp_method));
1454                 break;
1455
1456         case LFUN_BUFFER_CHILD_OPEN:
1457                 enable = doc_buffer;
1458                 break;
1459
1460         case LFUN_BUFFER_WRITE:
1461                 enable = doc_buffer && (doc_buffer->isUnnamed() || !doc_buffer->isClean());
1462                 break;
1463
1464         //FIXME: This LFUN should be moved to GuiApplication.
1465         case LFUN_BUFFER_WRITE_ALL: {
1466                 // We enable the command only if there are some modified buffers
1467                 Buffer * first = theBufferList().first();
1468                 enable = false;
1469                 if (!first)
1470                         break;
1471                 Buffer * b = first;
1472                 // We cannot use a for loop as the buffer list is a cycle.
1473                 do {
1474                         if (!b->isClean()) {
1475                                 enable = true;
1476                                 break;
1477                         }
1478                         b = theBufferList().next(b);
1479                 } while (b != first);
1480                 break;
1481         }
1482
1483         case LFUN_BUFFER_WRITE_AS:
1484                 enable = doc_buffer;
1485                 break;
1486
1487         case LFUN_BUFFER_CLOSE:
1488                 enable = doc_buffer;
1489                 break;
1490
1491         case LFUN_BUFFER_CLOSE_ALL:
1492                 enable = theBufferList().last() != theBufferList().first();
1493                 break;
1494
1495         case LFUN_SPLIT_VIEW:
1496                 if (cmd.getArg(0) == "vertical")
1497                         enable = doc_buffer && (d.splitter_->count() == 1 ||
1498                                          d.splitter_->orientation() == Qt::Vertical);
1499                 else
1500                         enable = doc_buffer && (d.splitter_->count() == 1 ||
1501                                          d.splitter_->orientation() == Qt::Horizontal);
1502                 break;
1503
1504         case LFUN_CLOSE_TAB_GROUP:
1505                 enable = d.currentTabWorkArea();
1506                 break;
1507
1508         case LFUN_TOOLBAR_TOGGLE: {
1509                 string const name = cmd.getArg(0);
1510                 if (GuiToolbar * t = toolbar(name))
1511                         flag.setOnOff(t->isVisible());
1512                 else {
1513                         enable = false;
1514                         docstring const msg =
1515                                 bformat(_("Unknown toolbar \"%1$s\""), from_utf8(name));
1516                         flag.message(msg);
1517                 }
1518                 break;
1519         }
1520
1521         case LFUN_DROP_LAYOUTS_CHOICE:
1522                 enable = buf;
1523                 break;
1524
1525         case LFUN_UI_TOGGLE:
1526                 flag.setOnOff(isFullScreen());
1527                 break;
1528
1529         case LFUN_DIALOG_DISCONNECT_INSET:
1530                 break;
1531
1532         case LFUN_DIALOG_HIDE:
1533                 // FIXME: should we check if the dialog is shown?
1534                 break;
1535
1536         case LFUN_DIALOG_TOGGLE:
1537                 flag.setOnOff(isDialogVisible(cmd.getArg(0)));
1538                 // fall through to set "enable"
1539         case LFUN_DIALOG_SHOW: {
1540                 string const name = cmd.getArg(0);
1541                 if (!doc_buffer)
1542                         enable = name == "aboutlyx"
1543                                 || name == "file" //FIXME: should be removed.
1544                                 || name == "prefs"
1545                                 || name == "texinfo"
1546                                 || name == "progress"
1547                                 || name == "compare";
1548                 else if (name == "print")
1549                         enable = doc_buffer->isExportable("dvi")
1550                                 && lyxrc.print_command != "none";
1551                 else if (name == "character" || name == "symbols") {
1552                         if (!buf || buf->isReadonly())
1553                                 enable = false;
1554                         else {
1555                                 // FIXME we should consider passthru
1556                                 // paragraphs too.
1557                                 Inset const & in = currentBufferView()->cursor().inset();
1558                                 enable = !in.getLayout().isPassThru();
1559                         }
1560                 }
1561                 else if (name == "latexlog")
1562                         enable = FileName(doc_buffer->logName()).isReadableFile();
1563                 else if (name == "spellchecker")
1564                         enable = theSpellChecker() && !doc_buffer->isReadonly();
1565                 else if (name == "vclog")
1566                         enable = doc_buffer->lyxvc().inUse();
1567                 break;
1568         }
1569
1570         case LFUN_DIALOG_UPDATE: {
1571                 string const name = cmd.getArg(0);
1572                 if (!buf)
1573                         enable = name == "prefs";
1574                 break;
1575         }
1576
1577         case LFUN_COMMAND_EXECUTE:
1578         case LFUN_MESSAGE:
1579         case LFUN_MENU_OPEN:
1580                 // Nothing to check.
1581                 break;
1582
1583         case LFUN_COMPLETION_INLINE:
1584                 if (!d.current_work_area_
1585                         || !d.current_work_area_->completer().inlinePossible(
1586                         currentBufferView()->cursor()))
1587                         enable = false;
1588                 break;
1589
1590         case LFUN_COMPLETION_POPUP:
1591                 if (!d.current_work_area_
1592                         || !d.current_work_area_->completer().popupPossible(
1593                         currentBufferView()->cursor()))
1594                         enable = false;
1595                 break;
1596
1597         case LFUN_COMPLETION_COMPLETE:
1598                 if (!d.current_work_area_
1599                         || !d.current_work_area_->completer().inlinePossible(
1600                         currentBufferView()->cursor()))
1601                         enable = false;
1602                 break;
1603
1604         case LFUN_COMPLETION_ACCEPT:
1605                 if (!d.current_work_area_
1606                         || (!d.current_work_area_->completer().popupVisible()
1607                         && !d.current_work_area_->completer().inlineVisible()
1608                         && !d.current_work_area_->completer().completionAvailable()))
1609                         enable = false;
1610                 break;
1611
1612         case LFUN_COMPLETION_CANCEL:
1613                 if (!d.current_work_area_
1614                         || (!d.current_work_area_->completer().popupVisible()
1615                         && !d.current_work_area_->completer().inlineVisible()))
1616                         enable = false;
1617                 break;
1618
1619         case LFUN_BUFFER_ZOOM_OUT:
1620                 enable = doc_buffer && lyxrc.zoom > 10;
1621                 break;
1622
1623         case LFUN_BUFFER_ZOOM_IN:
1624                 enable = doc_buffer;
1625                 break;
1626
1627         case LFUN_BUFFER_NEXT:
1628         case LFUN_BUFFER_PREVIOUS:
1629                 // FIXME: should we check is there is an previous or next buffer?
1630                 break;
1631         case LFUN_BUFFER_SWITCH:
1632                 // toggle on the current buffer, but do not toggle off
1633                 // the other ones (is that a good idea?)
1634                 if (doc_buffer
1635                         && to_utf8(cmd.argument()) == doc_buffer->absFileName())
1636                         flag.setOnOff(true);
1637                 break;
1638
1639         case LFUN_VC_REGISTER:
1640                 enable = doc_buffer && !doc_buffer->lyxvc().inUse();
1641                 break;
1642         case LFUN_VC_CHECK_IN:
1643                 enable = doc_buffer && doc_buffer->lyxvc().checkInEnabled();
1644                 break;
1645         case LFUN_VC_CHECK_OUT:
1646                 enable = doc_buffer && doc_buffer->lyxvc().checkOutEnabled();
1647                 break;
1648         case LFUN_VC_LOCKING_TOGGLE:
1649                 enable = doc_buffer && !doc_buffer->isReadonly()
1650                         && doc_buffer->lyxvc().lockingToggleEnabled();
1651                 flag.setOnOff(enable && doc_buffer->lyxvc().locking());
1652                 break;
1653         case LFUN_VC_REVERT:
1654                 enable = doc_buffer && doc_buffer->lyxvc().inUse() && !doc_buffer->isReadonly();
1655                 break;
1656         case LFUN_VC_UNDO_LAST:
1657                 enable = doc_buffer && doc_buffer->lyxvc().undoLastEnabled();
1658                 break;
1659         case LFUN_VC_REPO_UPDATE:
1660                 enable = doc_buffer && doc_buffer->lyxvc().repoUpdateEnabled();
1661                 break;
1662         case LFUN_VC_COMMAND: {
1663                 if (cmd.argument().empty())
1664                         enable = false;
1665                 if (!doc_buffer && contains(cmd.getArg(0), 'D'))
1666                         enable = false;
1667                 break;
1668         }
1669         case LFUN_VC_COMPARE:
1670                 enable = doc_buffer && doc_buffer->lyxvc().prepareFileRevisionEnabled();
1671                 break;
1672
1673         case LFUN_SERVER_GOTO_FILE_ROW:
1674                 break;
1675         case LFUN_FORWARD_SEARCH:
1676                 enable = !(lyxrc.forward_search_dvi.empty() && lyxrc.forward_search_pdf.empty());
1677                 break;
1678
1679         default:
1680                 return false;
1681         }
1682
1683         if (!enable)
1684                 flag.setEnabled(false);
1685
1686         return true;
1687 }
1688
1689
1690 static FileName selectTemplateFile()
1691 {
1692         FileDialog dlg(qt_("Select template file"));
1693         dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1694         dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
1695
1696         FileDialog::Result result = dlg.open(toqstr(lyxrc.template_path),
1697                                  QStringList(qt_("LyX Documents (*.lyx)")));
1698
1699         if (result.first == FileDialog::Later)
1700                 return FileName();
1701         if (result.second.isEmpty())
1702                 return FileName();
1703         return FileName(fromqstr(result.second));
1704 }
1705
1706
1707 Buffer * GuiView::loadDocument(FileName const & filename, bool tolastfiles)
1708 {
1709         setBusy(true);
1710
1711         Buffer * newBuffer = checkAndLoadLyXFile(filename);
1712
1713         if (!newBuffer) {
1714                 message(_("Document not loaded."));
1715                 setBusy(false);
1716                 return 0;
1717         }
1718
1719         setBuffer(newBuffer);
1720
1721         // scroll to the position when the file was last closed
1722         if (lyxrc.use_lastfilepos) {
1723                 LastFilePosSection::FilePos filepos =
1724                         theSession().lastFilePos().load(filename);
1725                 documentBufferView()->moveToPosition(filepos.pit, filepos.pos, 0, 0);
1726         }
1727
1728         if (tolastfiles)
1729                 theSession().lastFiles().add(filename);
1730
1731         setBusy(false);
1732         return newBuffer;
1733 }
1734
1735
1736 void GuiView::openDocument(string const & fname)
1737 {
1738         string initpath = lyxrc.document_path;
1739
1740         if (documentBufferView()) {
1741                 string const trypath = documentBufferView()->buffer().filePath();
1742                 // If directory is writeable, use this as default.
1743                 if (FileName(trypath).isDirWritable())
1744                         initpath = trypath;
1745         }
1746
1747         string filename;
1748
1749         if (fname.empty()) {
1750                 FileDialog dlg(qt_("Select document to open"), LFUN_FILE_OPEN);
1751                 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1752                 dlg.setButton2(qt_("Examples|#E#e"),
1753                                 toqstr(addPath(package().system_support().absFileName(), "examples")));
1754
1755                 QStringList filter(qt_("LyX Documents (*.lyx)"));
1756                 filter << qt_("LyX-1.3.x Documents (*.lyx13)")
1757                         << qt_("LyX-1.4.x Documents (*.lyx14)")
1758                         << qt_("LyX-1.5.x Documents (*.lyx15)")
1759                         << qt_("LyX-1.6.x Documents (*.lyx16)");
1760                 FileDialog::Result result =
1761                         dlg.open(toqstr(initpath), filter);
1762
1763                 if (result.first == FileDialog::Later)
1764                         return;
1765
1766                 filename = fromqstr(result.second);
1767
1768                 // check selected filename
1769                 if (filename.empty()) {
1770                         message(_("Canceled."));
1771                         return;
1772                 }
1773         } else
1774                 filename = fname;
1775
1776         // get absolute path of file and add ".lyx" to the filename if
1777         // necessary.
1778         FileName const fullname =
1779                         fileSearch(string(), filename, "lyx", support::may_not_exist);
1780         if (!fullname.empty())
1781                 filename = fullname.absFileName();
1782
1783         if (!fullname.onlyPath().isDirectory()) {
1784                 Alert::warning(_("Invalid filename"),
1785                                 bformat(_("The directory in the given path\n%1$s\ndoes not exist."),
1786                                 from_utf8(fullname.absFileName())));
1787                 return;
1788         }
1789
1790         // if the file doesn't exist and isn't already open (bug 6645),
1791         // let the user create one
1792         if (!fullname.exists() && !theBufferList().exists(fullname)) {
1793                 // the user specifically chose this name. Believe him.
1794                 Buffer * const b = newFile(filename, string(), true);
1795                 if (b)
1796                         setBuffer(b);
1797                 return;
1798         }
1799
1800         docstring const disp_fn = makeDisplayPath(filename);
1801         message(bformat(_("Opening document %1$s..."), disp_fn));
1802
1803         docstring str2;
1804         Buffer * buf = loadDocument(fullname);
1805         if (buf) {
1806                 // I don't think this is needed, since it will be done in setBuffer().
1807                 // buf->updateBuffer();
1808                 setBuffer(buf);
1809                 buf->errors("Parse");
1810                 str2 = bformat(_("Document %1$s opened."), disp_fn);
1811                 if (buf->lyxvc().inUse())
1812                         str2 += " " + from_utf8(buf->lyxvc().versionString()) +
1813                                 " " + _("Version control detected.");
1814         } else {
1815                 str2 = bformat(_("Could not open document %1$s"), disp_fn);
1816         }
1817         message(str2);
1818 }
1819
1820 // FIXME: clean that
1821 static bool import(GuiView * lv, FileName const & filename,
1822         string const & format, ErrorList & errorList)
1823 {
1824         FileName const lyxfile(support::changeExtension(filename.absFileName(), ".lyx"));
1825
1826         string loader_format;
1827         vector<string> loaders = theConverters().loaders();
1828         if (find(loaders.begin(), loaders.end(), format) == loaders.end()) {
1829                 for (vector<string>::const_iterator it = loaders.begin();
1830                          it != loaders.end(); ++it) {
1831                         if (!theConverters().isReachable(format, *it))
1832                                 continue;
1833
1834                         string const tofile =
1835                                 support::changeExtension(filename.absFileName(),
1836                                 formats.extension(*it));
1837                         if (!theConverters().convert(0, filename, FileName(tofile),
1838                                 filename, format, *it, errorList))
1839                                 return false;
1840                         loader_format = *it;
1841                         break;
1842                 }
1843                 if (loader_format.empty()) {
1844                         frontend::Alert::error(_("Couldn't import file"),
1845                                          bformat(_("No information for importing the format %1$s."),
1846                                          formats.prettyName(format)));
1847                         return false;
1848                 }
1849         } else
1850                 loader_format = format;
1851
1852         if (loader_format == "lyx") {
1853                 Buffer * buf = lv->loadDocument(lyxfile);
1854                 if (!buf)
1855                         return false;
1856                 // I don't think this is needed, since it will be done in setBuffer().
1857                 // buf->updateBuffer();
1858                 lv->setBuffer(buf);
1859                 buf->errors("Parse");
1860         } else {
1861                 Buffer * const b = newFile(lyxfile.absFileName(), string(), true);
1862                 if (!b)
1863                         return false;
1864                 lv->setBuffer(b);
1865                 bool as_paragraphs = loader_format == "textparagraph";
1866                 string filename2 = (loader_format == format) ? filename.absFileName()
1867                         : support::changeExtension(filename.absFileName(),
1868                                           formats.extension(loader_format));
1869                 lv->currentBufferView()->insertPlaintextFile(FileName(filename2),
1870                         as_paragraphs);
1871                 guiApp->setCurrentView(lv);
1872                 lyx::dispatch(FuncRequest(LFUN_MARK_OFF));
1873         }
1874
1875         return true;
1876 }
1877
1878
1879 void GuiView::importDocument(string const & argument)
1880 {
1881         string format;
1882         string filename = split(argument, format, ' ');
1883
1884         LYXERR(Debug::INFO, format << " file: " << filename);
1885
1886         // need user interaction
1887         if (filename.empty()) {
1888                 string initpath = lyxrc.document_path;
1889                 if (documentBufferView()) {
1890                         string const trypath = documentBufferView()->buffer().filePath();
1891                         // If directory is writeable, use this as default.
1892                         if (FileName(trypath).isDirWritable())
1893                                 initpath = trypath;
1894                 }
1895
1896                 docstring const text = bformat(_("Select %1$s file to import"),
1897                         formats.prettyName(format));
1898
1899                 FileDialog dlg(toqstr(text), LFUN_BUFFER_IMPORT);
1900                 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1901                 dlg.setButton2(qt_("Examples|#E#e"),
1902                         toqstr(addPath(package().system_support().absFileName(), "examples")));
1903
1904                 docstring filter = formats.prettyName(format);
1905                 filter += " (*.";
1906                 // FIXME UNICODE
1907                 filter += from_utf8(formats.extension(format));
1908                 filter += ')';
1909
1910                 FileDialog::Result result =
1911                         dlg.open(toqstr(initpath), fileFilters(toqstr(filter)));
1912
1913                 if (result.first == FileDialog::Later)
1914                         return;
1915
1916                 filename = fromqstr(result.second);
1917
1918                 // check selected filename
1919                 if (filename.empty())
1920                         message(_("Canceled."));
1921         }
1922
1923         if (filename.empty())
1924                 return;
1925
1926         // get absolute path of file
1927         FileName const fullname(support::makeAbsPath(filename));
1928
1929         FileName const lyxfile(support::changeExtension(fullname.absFileName(), ".lyx"));
1930
1931         // Check if the document already is open
1932         Buffer * buf = theBufferList().getBuffer(lyxfile);
1933         if (buf) {
1934                 setBuffer(buf);
1935                 if (!closeBuffer()) {
1936                         message(_("Canceled."));
1937                         return;
1938                 }
1939         }
1940
1941         docstring const displaypath = makeDisplayPath(lyxfile.absFileName(), 30);
1942
1943         // if the file exists already, and we didn't do
1944         // -i lyx thefile.lyx, warn
1945         if (lyxfile.exists() && fullname != lyxfile) {
1946
1947                 docstring text = bformat(_("The document %1$s already exists.\n\n"
1948                         "Do you want to overwrite that document?"), displaypath);
1949                 int const ret = Alert::prompt(_("Overwrite document?"),
1950                         text, 0, 1, _("&Overwrite"), _("&Cancel"));
1951
1952                 if (ret == 1) {
1953                         message(_("Canceled."));
1954                         return;
1955                 }
1956         }
1957
1958         message(bformat(_("Importing %1$s..."), displaypath));
1959         ErrorList errorList;
1960         if (import(this, fullname, format, errorList))
1961                 message(_("imported."));
1962         else
1963                 message(_("file not imported!"));
1964
1965         // FIXME (Abdel 12/08/06): Is there a need to display the error list here?
1966 }
1967
1968
1969 void GuiView::newDocument(string const & filename, bool from_template)
1970 {
1971         FileName initpath(lyxrc.document_path);
1972         if (documentBufferView()) {
1973                 FileName const trypath(documentBufferView()->buffer().filePath());
1974                 // If directory is writeable, use this as default.
1975                 if (trypath.isDirWritable())
1976                         initpath = trypath;
1977         }
1978
1979         string templatefile;
1980         if (from_template) {
1981                 templatefile = selectTemplateFile().absFileName();
1982                 if (templatefile.empty())
1983                         return;
1984         }
1985
1986         Buffer * b;
1987         if (filename.empty())
1988                 b = newUnnamedFile(initpath, to_utf8(_("newfile")), templatefile);
1989         else
1990                 b = newFile(filename, templatefile, true);
1991
1992         if (b)
1993                 setBuffer(b);
1994
1995         // If no new document could be created, it is unsure
1996         // whether there is a valid BufferView.
1997         if (currentBufferView())
1998                 // Ensure the cursor is correctly positioned on screen.
1999                 currentBufferView()->showCursor();
2000 }
2001
2002
2003 void GuiView::insertLyXFile(docstring const & fname)
2004 {
2005         BufferView * bv = documentBufferView();
2006         if (!bv)
2007                 return;
2008
2009         // FIXME UNICODE
2010         FileName filename(to_utf8(fname));
2011
2012         if (!filename.empty()) {
2013                 bv->insertLyXFile(filename);
2014                 return;
2015         }
2016
2017         // Launch a file browser
2018         // FIXME UNICODE
2019         string initpath = lyxrc.document_path;
2020         string const trypath = bv->buffer().filePath();
2021         // If directory is writeable, use this as default.
2022         if (FileName(trypath).isDirWritable())
2023                 initpath = trypath;
2024
2025         // FIXME UNICODE
2026         FileDialog dlg(qt_("Select LyX document to insert"), LFUN_FILE_INSERT);
2027         dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2028         dlg.setButton2(qt_("Examples|#E#e"),
2029                 toqstr(addPath(package().system_support().absFileName(),
2030                 "examples")));
2031
2032         FileDialog::Result result = dlg.open(toqstr(initpath),
2033                                  QStringList(qt_("LyX Documents (*.lyx)")));
2034
2035         if (result.first == FileDialog::Later)
2036                 return;
2037
2038         // FIXME UNICODE
2039         filename.set(fromqstr(result.second));
2040
2041         // check selected filename
2042         if (filename.empty()) {
2043                 // emit message signal.
2044                 message(_("Canceled."));
2045                 return;
2046         }
2047
2048         bv->insertLyXFile(filename);
2049 }
2050
2051
2052 void GuiView::insertPlaintextFile(docstring const & fname,
2053         bool asParagraph)
2054 {
2055         BufferView * bv = documentBufferView();
2056         if (!bv)
2057                 return;
2058
2059         if (!fname.empty() && !FileName::isAbsolute(to_utf8(fname))) {
2060                 message(_("Absolute filename expected."));
2061                 return;
2062         }
2063
2064         // FIXME UNICODE
2065         FileName filename(to_utf8(fname));
2066
2067         if (!filename.empty()) {
2068                 bv->insertPlaintextFile(filename, asParagraph);
2069                 return;
2070         }
2071
2072         FileDialog dlg(qt_("Select file to insert"), (asParagraph ?
2073                 LFUN_FILE_INSERT_PLAINTEXT_PARA : LFUN_FILE_INSERT_PLAINTEXT));
2074
2075         FileDialog::Result result = dlg.open(toqstr(bv->buffer().filePath()),
2076                 QStringList(qt_("All Files (*)")));
2077
2078         if (result.first == FileDialog::Later)
2079                 return;
2080
2081         // FIXME UNICODE
2082         filename.set(fromqstr(result.second));
2083
2084         // check selected filename
2085         if (filename.empty()) {
2086                 // emit message signal.
2087                 message(_("Canceled."));
2088                 return;
2089         }
2090
2091         bv->insertPlaintextFile(filename, asParagraph);
2092 }
2093
2094
2095 bool GuiView::renameBuffer(Buffer & b, docstring const & newname)
2096 {
2097         FileName fname = b.fileName();
2098         FileName const oldname = fname;
2099
2100         if (!newname.empty()) {
2101                 // FIXME UNICODE
2102                 fname = support::makeAbsPath(to_utf8(newname), oldname.onlyPath().absFileName());
2103         } else {
2104                 // Switch to this Buffer.
2105                 setBuffer(&b);
2106
2107                 // No argument? Ask user through dialog.
2108                 // FIXME UNICODE
2109                 FileDialog dlg(qt_("Choose a filename to save document as"),
2110                                    LFUN_BUFFER_WRITE_AS);
2111                 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2112                 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
2113
2114                 if (!isLyXFileName(fname.absFileName()))
2115                         fname.changeExtension(".lyx");
2116
2117                 FileDialog::Result result =
2118                         dlg.save(toqstr(fname.onlyPath().absFileName()),
2119                                    QStringList(qt_("LyX Documents (*.lyx)")),
2120                                          toqstr(fname.onlyFileName()));
2121
2122                 if (result.first == FileDialog::Later)
2123                         return false;
2124
2125                 fname.set(fromqstr(result.second));
2126
2127                 if (fname.empty())
2128                         return false;
2129
2130                 if (!isLyXFileName(fname.absFileName()))
2131                         fname.changeExtension(".lyx");
2132         }
2133
2134         // fname is now the new Buffer location.
2135         if (FileName(fname).exists()) {
2136                 docstring const file = makeDisplayPath(fname.absFileName(), 30);
2137                 docstring text = bformat(_("The document %1$s already "
2138                                            "exists.\n\nDo you want to "
2139                                            "overwrite that document?"),
2140                                          file);
2141                 int const ret = Alert::prompt(_("Overwrite document?"),
2142                         text, 0, 2, _("&Overwrite"), _("&Rename"), _("&Cancel"));
2143                 switch (ret) {
2144                 case 0: break;
2145                 case 1: return renameBuffer(b, docstring());
2146                 case 2: return false;
2147                 }
2148         }
2149
2150         FileName oldauto = b.getAutosaveFileName();
2151
2152         // Ok, change the name of the buffer
2153         b.setFileName(fname.absFileName());
2154         b.markDirty();
2155         bool unnamed = b.isUnnamed();
2156         b.setUnnamed(false);
2157         b.saveCheckSum(fname);
2158
2159         // bring the autosave file with us, just in case.
2160         b.moveAutosaveFile(oldauto);
2161
2162         if (!saveBuffer(b)) {
2163                 oldauto = b.getAutosaveFileName();
2164                 b.setFileName(oldname.absFileName());
2165                 b.setUnnamed(unnamed);
2166                 b.saveCheckSum(oldname);
2167                 b.moveAutosaveFile(oldauto);
2168                 return false;
2169         }
2170
2171         // the file has now been saved to the new location.
2172         // we need to check that the locations of child buffers
2173         // are still valid.
2174         b.checkChildBuffers();
2175
2176         return true;
2177 }
2178
2179
2180 bool GuiView::saveBuffer(Buffer & b)
2181 {
2182         if (workArea(b) && workArea(b)->inDialogMode())
2183                 return true;
2184
2185         if (b.isUnnamed())
2186                 return renameBuffer(b, docstring());
2187
2188         if (b.save()) {
2189                 theSession().lastFiles().add(b.fileName());
2190                 return true;
2191         }
2192
2193         // Switch to this Buffer.
2194         setBuffer(&b);
2195
2196         // FIXME: we don't tell the user *WHY* the save failed !!
2197         docstring const file = makeDisplayPath(b.absFileName(), 30);
2198         docstring text = bformat(_("The document %1$s could not be saved.\n\n"
2199                                    "Do you want to rename the document and "
2200                                    "try again?"), file);
2201         int const ret = Alert::prompt(_("Rename and save?"),
2202                 text, 0, 2, _("&Rename"), _("&Retry"), _("&Cancel"));
2203         switch (ret) {
2204         case 0:
2205                 if (!renameBuffer(b, docstring()))
2206                         return false;
2207                 break;
2208         case 1:
2209                 break;
2210         case 2:
2211                 return false;
2212         }
2213
2214         return saveBuffer(b);
2215 }
2216
2217
2218 bool GuiView::hideWorkArea(GuiWorkArea * wa)
2219 {
2220         return closeWorkArea(wa, false);
2221 }
2222
2223
2224 bool GuiView::closeWorkArea(GuiWorkArea * wa)
2225 {
2226         Buffer & buf = wa->bufferView().buffer();
2227         return closeWorkArea(wa, !buf.parent());
2228 }
2229
2230
2231 bool GuiView::closeBuffer()
2232 {
2233         GuiWorkArea * wa = currentMainWorkArea();
2234         setCurrentWorkArea(wa);
2235         Buffer & buf = wa->bufferView().buffer();
2236         return wa && closeWorkArea(wa, !buf.parent());
2237 }
2238
2239
2240 void GuiView::writeSession() const {
2241         GuiWorkArea const * active_wa = currentMainWorkArea();
2242         for (int i = 0; i < d.splitter_->count(); ++i) {
2243                 TabWorkArea * twa = d.tabWorkArea(i);
2244                 for (int j = 0; j < twa->count(); ++j) {
2245                         GuiWorkArea * wa = static_cast<GuiWorkArea *>(twa->widget(j));
2246                         Buffer & buf = wa->bufferView().buffer();
2247                         theSession().lastOpened().add(buf.fileName(), wa == active_wa);
2248                 }
2249         }
2250 }
2251
2252
2253 bool GuiView::closeBufferAll()
2254 {
2255         // Close the workareas in all other views
2256         QList<int> const ids = guiApp->viewIds();
2257         for (int i = 0; i != ids.size(); ++i) {
2258                 if (id_ != ids[i] && !guiApp->view(ids[i]).closeWorkAreaAll())
2259                         return false;
2260         }
2261
2262         // Close our own workareas
2263         if (!closeWorkAreaAll())
2264                 return false;
2265
2266         // Now close the hidden buffers. We prevent hidden buffers from being
2267         // dirty, so we can just close them.
2268         theBufferList().closeAll();
2269         return true;
2270 }
2271
2272
2273 bool GuiView::closeWorkAreaAll()
2274 {
2275         setCurrentWorkArea(currentMainWorkArea());
2276
2277         // We might be in a situation that there is still a tabWorkArea, but
2278         // there are no tabs anymore. This can happen when we get here after a
2279         // TabWorkArea::lastWorkAreaRemoved() signal. Therefore we count how
2280         // many TabWorkArea's have no documents anymore.
2281         int empty_twa = 0;
2282
2283         // We have to call count() each time, because it can happen that
2284         // more than one splitter will disappear in one iteration (bug 5998).
2285         for (; d.splitter_->count() > empty_twa; ) {
2286                 TabWorkArea * twa = d.tabWorkArea(empty_twa);
2287
2288                 if (twa->count() == 0)
2289                         ++empty_twa;
2290                 else {
2291                         setCurrentWorkArea(twa->currentWorkArea());
2292                         if (!closeTabWorkArea(twa))
2293                                 return false;
2294                 }
2295         }
2296         return true;
2297 }
2298
2299
2300 bool GuiView::closeWorkArea(GuiWorkArea * wa, bool close_buffer)
2301 {
2302         if (!wa)
2303                 return false;
2304
2305         Buffer & buf = wa->bufferView().buffer();
2306
2307         if (close_buffer && GuiViewPrivate::busyBuffers.contains(&buf)) {
2308                 Alert::warning(_("Close document "), _("Document could not be closed because it is processed by LyX."));
2309                 return false;
2310         }
2311
2312         if (close_buffer)
2313                 return closeBuffer(buf);
2314         else {
2315                 if (!inMultiTabs(wa))
2316                         if (!saveBufferIfNeeded(buf, true))
2317                                 return false;
2318                 removeWorkArea(wa);
2319                 return true;
2320         }
2321 }
2322
2323
2324 bool GuiView::closeBuffer(Buffer & buf)
2325 {
2326         // If we are in a close_event all children will be closed in some time,
2327         // so no need to do it here. This will ensure that the children end up
2328         // in the session file in the correct order. If we close the master
2329         // buffer, we can close or release the child buffers here too.
2330         if (!closing_) {
2331                 ListOfBuffers clist = buf.getChildren();
2332                 ListOfBuffers::const_iterator it = clist.begin();
2333                 ListOfBuffers::const_iterator const bend = clist.end();
2334                 for (; it != bend; ++it) {
2335                         // If a child is dirty, do not close
2336                         // without user intervention
2337                         //FIXME: should we look in other tabworkareas?
2338                         Buffer * child_buf = *it;
2339                         GuiWorkArea * child_wa = workArea(*child_buf);
2340                         if (child_wa) {
2341                                 if (!closeWorkArea(child_wa, true))
2342                                         return false;
2343                         } else
2344                                 theBufferList().releaseChild(&buf, child_buf);
2345                 }
2346         }
2347         // goto bookmark to update bookmark pit.
2348         //FIXME: we should update only the bookmarks related to this buffer!
2349         LYXERR(Debug::DEBUG, "GuiView::closeBuffer()");
2350         for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
2351                 guiApp->gotoBookmark(i+1, false, false);
2352
2353         if (saveBufferIfNeeded(buf, false)) {
2354                 buf.removeAutosaveFile();
2355                 theBufferList().release(&buf);
2356                 return true;
2357         }
2358         return false;
2359 }
2360
2361
2362 bool GuiView::closeTabWorkArea(TabWorkArea * twa)
2363 {
2364         while (twa == d.currentTabWorkArea()) {
2365                 twa->setCurrentIndex(twa->count()-1);
2366
2367                 GuiWorkArea * wa = twa->currentWorkArea();
2368                 Buffer & b = wa->bufferView().buffer();
2369
2370                 // We only want to close the buffer if the same buffer is not visible
2371                 // in another view, and if this is not a child and if we are closing
2372                 // a view (not a tabgroup).
2373                 bool const close_buffer =
2374                         !inMultiViews(wa) && !b.parent() && closing_;
2375
2376                 if (!closeWorkArea(wa, close_buffer))
2377                         return false;
2378         }
2379         return true;
2380 }
2381
2382
2383 bool GuiView::saveBufferIfNeeded(Buffer & buf, bool hiding)
2384 {
2385         if (buf.isClean() || buf.paragraphs().empty())
2386                 return true;
2387
2388         // Switch to this Buffer.
2389         setBuffer(&buf);
2390
2391         docstring file;
2392         // FIXME: Unicode?
2393         if (buf.isUnnamed())
2394                 file = from_utf8(buf.fileName().onlyFileName());
2395         else
2396                 file = buf.fileName().displayName(30);
2397
2398         // Bring this window to top before asking questions.
2399         raise();
2400         activateWindow();
2401
2402         int ret;
2403         if (hiding && buf.isUnnamed()) {
2404                 docstring const text = bformat(_("The document %1$s has not been "
2405                                                  "saved yet.\n\nDo you want to save "
2406                                                  "the document?"), file);
2407                 ret = Alert::prompt(_("Save new document?"),
2408                         text, 0, 1, _("&Save"), _("&Cancel"));
2409                 if (ret == 1)
2410                         ++ret;
2411         } else {
2412                 docstring const text = bformat(_("The document %1$s has unsaved changes."
2413                         "\n\nDo you want to save the document or discard the changes?"), file);
2414                 ret = Alert::prompt(_("Save changed document?"),
2415                         text, 0, 2, _("&Save"), _("&Discard"), _("&Cancel"));
2416         }
2417
2418         switch (ret) {
2419         case 0:
2420                 if (!saveBuffer(buf))
2421                         return false;
2422                 break;
2423         case 1:
2424                 // if we crash after this we could
2425                 // have no autosave file but I guess
2426                 // this is really improbable (Jug)
2427                 // Sometime improbable things happen, bug 6857 (ps)
2428                 // buf.removeAutosaveFile();
2429                 if (hiding)
2430                         // revert all changes
2431                         buf.reload();
2432                 buf.markClean();
2433                 break;
2434         case 2:
2435                 return false;
2436         }
2437         return true;
2438 }
2439
2440
2441 bool GuiView::inMultiTabs(GuiWorkArea * wa)
2442 {
2443         Buffer & buf = wa->bufferView().buffer();
2444
2445         for (int i = 0; i != d.splitter_->count(); ++i) {
2446                 GuiWorkArea * wa_ = d.tabWorkArea(i)->workArea(buf);
2447                 if (wa_ && wa_ != wa)
2448                         return true;
2449         }
2450         return inMultiViews(wa);
2451 }
2452
2453
2454 bool GuiView::inMultiViews(GuiWorkArea * wa)
2455 {
2456         QList<int> const ids = guiApp->viewIds();
2457         Buffer & buf = wa->bufferView().buffer();
2458
2459         int found_twa = 0;
2460         for (int i = 0; i != ids.size() && found_twa <= 1; ++i) {
2461                 if (id_ == ids[i])
2462                         continue;
2463
2464                 if (guiApp->view(ids[i]).workArea(buf))
2465                         return true;
2466         }
2467         return false;
2468 }
2469
2470
2471 void GuiView::gotoNextOrPreviousBuffer(NextOrPrevious np)
2472 {
2473         Buffer * const curbuf = documentBufferView()
2474                 ? &documentBufferView()->buffer() : 0;
2475         Buffer * nextbuf = curbuf;
2476         while (true) {
2477                 if (np == NEXTBUFFER)
2478                         nextbuf = theBufferList().next(nextbuf);
2479                 else
2480                         nextbuf = theBufferList().previous(nextbuf);
2481                 if (nextbuf == curbuf)
2482                         break;
2483                 if (nextbuf == 0) {
2484                         nextbuf = curbuf;
2485                         break;
2486                 }
2487                 if (workArea(*nextbuf))
2488                         break;
2489         }
2490         setBuffer(nextbuf);
2491 }
2492
2493
2494 /// make sure the document is saved
2495 static bool ensureBufferClean(Buffer * buffer)
2496 {
2497         LASSERT(buffer, return false);
2498         if (buffer->isClean() && !buffer->isUnnamed())
2499                 return true;
2500
2501         docstring const file = buffer->fileName().displayName(30);
2502         docstring title;
2503         docstring text;
2504         if (!buffer->isUnnamed()) {
2505                 text = bformat(_("The document %1$s has unsaved "
2506                                                  "changes.\n\nDo you want to save "
2507                                                  "the document?"), file);
2508                 title = _("Save changed document?");
2509
2510         } else {
2511                 text = bformat(_("The document %1$s has not been "
2512                                                  "saved yet.\n\nDo you want to save "
2513                                                  "the document?"), file);
2514                 title = _("Save new document?");
2515         }
2516         int const ret = Alert::prompt(title, text, 0, 1, _("&Save"), _("&Cancel"));
2517
2518         if (ret == 0)
2519                 dispatch(FuncRequest(LFUN_BUFFER_WRITE));
2520
2521         return buffer->isClean() && !buffer->isUnnamed();
2522 }
2523
2524
2525 void GuiView::reloadBuffer()
2526 {
2527         Buffer * buf = &documentBufferView()->buffer();
2528         buf->reload();
2529 }
2530
2531
2532 void GuiView::checkExternallyModifiedBuffers()
2533 {
2534         BufferList::iterator bit = theBufferList().begin();
2535         BufferList::iterator const bend = theBufferList().end();
2536         for (; bit != bend; ++bit) {
2537                 if ((*bit)->fileName().exists()
2538                         && (*bit)->isExternallyModified(Buffer::checksum_method)) {
2539                         docstring text = bformat(_("Document \n%1$s\n has been externally modified."
2540                                         " Reload now? Any local changes will be lost."),
2541                                         from_utf8((*bit)->absFileName()));
2542                         int const ret = Alert::prompt(_("Reload externally changed document?"),
2543                                                 text, 0, 1, _("&Reload"), _("&Cancel"));
2544                         if (!ret)
2545                                 (*bit)->reload();
2546                 }
2547         }
2548 }
2549
2550
2551 //FIXME use a DispatchResult object to transmit messages
2552 void GuiView::dispatchVC(FuncRequest const & cmd)
2553 {
2554         // message for statusbar
2555         string msg;
2556         Buffer * buffer = documentBufferView()
2557                 ? &(documentBufferView()->buffer()) : 0;
2558
2559         switch (cmd.action()) {
2560         case LFUN_VC_REGISTER:
2561                 if (!buffer || !ensureBufferClean(buffer))
2562                         break;
2563                 if (!buffer->lyxvc().inUse()) {
2564                         if (buffer->lyxvc().registrer())
2565                                 reloadBuffer();
2566                 }
2567                 break;
2568
2569         case LFUN_VC_CHECK_IN:
2570                 if (!buffer || !ensureBufferClean(buffer))
2571                         break;
2572                 if (buffer->lyxvc().inUse() && !buffer->isReadonly()) {
2573                         msg = buffer->lyxvc().checkIn();
2574                         if (!msg.empty())
2575                                 reloadBuffer();
2576                 }
2577                 break;
2578
2579         case LFUN_VC_CHECK_OUT:
2580                 if (!buffer || !ensureBufferClean(buffer))
2581                         break;
2582                 if (buffer->lyxvc().inUse()) {
2583                         msg = buffer->lyxvc().checkOut();
2584                         reloadBuffer();
2585                 }
2586                 break;
2587
2588         case LFUN_VC_LOCKING_TOGGLE:
2589                 LASSERT(buffer, return);
2590                 if (!ensureBufferClean(buffer) || buffer->isReadonly())
2591                         break;
2592                 if (buffer->lyxvc().inUse()) {
2593                         string res = buffer->lyxvc().lockingToggle();
2594                         if (res.empty()) {
2595                                 frontend::Alert::error(_("Revision control error."),
2596                                 _("Error when setting the locking property."));
2597                         } else {
2598                                 msg = res;
2599                                 reloadBuffer();
2600                         }
2601                 }
2602                 break;
2603
2604         case LFUN_VC_REVERT:
2605                 LASSERT(buffer, return);
2606                 buffer->lyxvc().revert();
2607                 reloadBuffer();
2608                 break;
2609
2610         case LFUN_VC_UNDO_LAST:
2611                 LASSERT(buffer, return);
2612                 buffer->lyxvc().undoLast();
2613                 reloadBuffer();
2614                 break;
2615
2616         case LFUN_VC_REPO_UPDATE:
2617                 LASSERT(buffer, return);
2618                 if (ensureBufferClean(buffer)) {
2619                         msg = buffer->lyxvc().repoUpdate();
2620                         checkExternallyModifiedBuffers();
2621                 }
2622                 break;
2623
2624         case LFUN_VC_COMMAND: {
2625                 string flag = cmd.getArg(0);
2626                 if (buffer && contains(flag, 'R') && !ensureBufferClean(buffer))
2627                         break;
2628                 docstring message;
2629                 if (contains(flag, 'M')) {
2630                         if (!Alert::askForText(message, _("LyX VC: Log Message")))
2631                                 break;
2632                 }
2633                 string path = cmd.getArg(1);
2634                 if (contains(path, "$$p") && buffer)
2635                         path = subst(path, "$$p", buffer->filePath());
2636                 LYXERR(Debug::LYXVC, "Directory: " << path);
2637                 FileName pp(path);
2638                 if (!pp.isReadableDirectory()) {
2639                         lyxerr << _("Directory is not accessible.") << endl;
2640                         break;
2641                 }
2642                 support::PathChanger p(pp);
2643
2644                 string command = cmd.getArg(2);
2645                 if (command.empty())
2646                         break;
2647                 if (buffer) {
2648                         command = subst(command, "$$i", buffer->absFileName());
2649                         command = subst(command, "$$p", buffer->filePath());
2650                 }
2651                 command = subst(command, "$$m", to_utf8(message));
2652                 LYXERR(Debug::LYXVC, "Command: " << command);
2653                 Systemcall one;
2654                 one.startscript(Systemcall::Wait, command);
2655
2656                 if (!buffer)
2657                         break;
2658                 if (contains(flag, 'I'))
2659                         buffer->markDirty();
2660                 if (contains(flag, 'R'))
2661                         reloadBuffer();
2662
2663                 break;
2664                 }
2665
2666         case LFUN_VC_COMPARE: {
2667
2668                 if (cmd.argument().empty()) {
2669                         lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "comparehistory"));
2670                         break;
2671                 }
2672
2673                 string rev1 = cmd.getArg(0);
2674                 string f1, f2;
2675
2676                 // f1
2677                 if (!buffer->lyxvc().prepareFileRevision(rev1, f1))
2678                         break;
2679
2680                 if (isStrInt(rev1) && convert<int>(rev1) <= 0) {
2681                         f2 = buffer->absFileName();
2682                 } else {
2683                         string rev2 = cmd.getArg(1);
2684                         if (rev2.empty())
2685                                 break;
2686                         // f2
2687                         if (!buffer->lyxvc().prepareFileRevision(rev2, f2))
2688                                 break;
2689                 }
2690
2691                 LYXERR(Debug::LYXVC, "Launching comparison for fetched revisions:\n" <<
2692                                         f1 << "\n"  << f2 << "\n" );
2693                 string par = "compare run " + quoteName(f1) + " " + quoteName(f2);
2694                 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, par));
2695                 break;
2696         }
2697
2698         default:
2699                 break;
2700         }
2701
2702         if (!msg.empty())
2703                 message(from_utf8(msg));
2704 }
2705
2706
2707 void GuiView::openChildDocument(string const & fname)
2708 {
2709         LASSERT(documentBufferView(), return);
2710         Buffer & buffer = documentBufferView()->buffer();
2711         FileName const filename = support::makeAbsPath(fname, buffer.filePath());
2712         documentBufferView()->saveBookmark(false);
2713         Buffer * child = 0;
2714         bool parsed = false;
2715         if (theBufferList().exists(filename)) {
2716                 child = theBufferList().getBuffer(filename);
2717         } else {
2718                 message(bformat(_("Opening child document %1$s..."),
2719                 makeDisplayPath(filename.absFileName())));
2720                 child = loadDocument(filename, false);
2721                 parsed = true;
2722         }
2723         if (!child)
2724                 return;
2725
2726         // Set the parent name of the child document.
2727         // This makes insertion of citations and references in the child work,
2728         // when the target is in the parent or another child document.
2729         child->setParent(&buffer);
2730
2731         // I don't think this is needed, since it will be called in
2732         // setBuffer().
2733         //      child->masterBuffer()->updateBuffer();
2734         setBuffer(child);
2735         if (parsed)
2736                 child->errors("Parse");
2737 }
2738
2739
2740 bool GuiView::goToFileRow(string const & argument)
2741 {
2742         string file_name;
2743         int row;
2744         size_t i = argument.find_last_of(' ');
2745         if (i != string::npos) {
2746                 file_name = os::internal_path(trim(argument.substr(0, i)));
2747                 istringstream is(argument.substr(i + 1));
2748                 is >> row;
2749                 if (is.fail())
2750                         i = string::npos;
2751         }
2752         if (i == string::npos) {
2753                 LYXERR0("Wrong argument: " << argument);
2754                 return false;
2755         }
2756         Buffer * buf = 0;
2757         string const abstmp = package().temp_dir().absFileName();
2758         string const realtmp = package().temp_dir().realPath();
2759         // We have to use os::path_prefix_is() here, instead of
2760         // simply prefixIs(), because the file name comes from
2761         // an external application and may need case adjustment.
2762         if (os::path_prefix_is(file_name, abstmp, os::CASE_ADJUSTED)
2763                 || os::path_prefix_is(file_name, realtmp, os::CASE_ADJUSTED)) {
2764                 // Needed by inverse dvi search. If it is a file
2765                 // in tmpdir, call the apropriated function.
2766                 // If tmpdir is a symlink, we may have the real
2767                 // path passed back, so we correct for that.
2768                 if (!prefixIs(file_name, abstmp))
2769                         file_name = subst(file_name, realtmp, abstmp);
2770                 buf = theBufferList().getBufferFromTmp(file_name);
2771         } else {
2772                 // Must replace extension of the file to be .lyx
2773                 // and get full path
2774                 FileName const s = fileSearch(string(),
2775                                                   support::changeExtension(file_name, ".lyx"), "lyx");
2776                 // Either change buffer or load the file
2777                 if (theBufferList().exists(s))
2778                         buf = theBufferList().getBuffer(s);
2779                 else if (s.exists()) {
2780                         buf = loadDocument(s);
2781                         if (!buf)
2782                                 return false;
2783                         // I don't think this is needed. loadDocument() calls
2784                         // setBuffer(), which calls updateBuffer().
2785                         // buf->updateBuffer();
2786                         buf->errors("Parse");
2787                 } else {
2788                         message(bformat(
2789                                         _("File does not exist: %1$s"),
2790                                         makeDisplayPath(file_name)));
2791                         return false;
2792                 }
2793         }
2794         setBuffer(buf);
2795         documentBufferView()->setCursorFromRow(row);
2796         return true;
2797 }
2798
2799
2800 #if (QT_VERSION >= 0x040400)
2801 docstring GuiView::GuiViewPrivate::exportAndDestroy(Buffer const * orig, Buffer * buffer, string const & format)
2802 {
2803         bool const update_unincluded =
2804                                 buffer->params().maintain_unincluded_children
2805                                 && !buffer->params().getIncludedChildren().empty();
2806         bool const success = buffer->doExport(format, true, update_unincluded);
2807         delete buffer;
2808         busyBuffers.remove(orig);
2809         return success
2810                 ? bformat(_("Successful export to format: %1$s"), from_utf8(format))
2811                 : bformat(_("Error exporting to format: %1$s"), from_utf8(format));
2812 }
2813
2814
2815 docstring GuiView::GuiViewPrivate::previewAndDestroy(Buffer const * orig, Buffer * buffer, string const & format)
2816 {
2817         bool const update_unincluded =
2818                                 buffer->params().maintain_unincluded_children
2819                                 && !buffer->params().getIncludedChildren().empty();
2820         bool const success = buffer->preview(format, update_unincluded);
2821         delete buffer;
2822         busyBuffers.remove(orig);
2823         return success
2824                 ? bformat(_("Successful preview of format: %1$s"), from_utf8(format))
2825                 : bformat(_("Error previewing format: %1$s"), from_utf8(format));
2826 }
2827 #endif
2828
2829
2830 void GuiView::dispatch(FuncRequest const & cmd, DispatchResult & dr)
2831 {
2832         BufferView * bv = currentBufferView();
2833         // By default we won't need any update.
2834         dr.screenUpdate(Update::None);
2835         // assume cmd will be dispatched
2836         dr.dispatched(true);
2837
2838         Buffer * doc_buffer = documentBufferView()
2839                 ? &(documentBufferView()->buffer()) : 0;
2840
2841         if (cmd.origin() == FuncRequest::TOC) {
2842                 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
2843                 // FIXME: do we need to pass a DispatchResult object here?
2844                 toc->doDispatch(bv->cursor(), cmd);
2845                 return;
2846         }
2847
2848         string const argument = to_utf8(cmd.argument());
2849
2850         switch(cmd.action()) {
2851                 case LFUN_BUFFER_CHILD_OPEN:
2852                         openChildDocument(to_utf8(cmd.argument()));
2853                         break;
2854
2855                 case LFUN_BUFFER_IMPORT:
2856                         importDocument(to_utf8(cmd.argument()));
2857                         break;
2858
2859                 case LFUN_BUFFER_EXPORT: {
2860                         if (!doc_buffer)
2861                                 break;
2862                         // GCC only sees strfwd.h when building merged
2863                         if (::lyx::operator==(cmd.argument(), "custom")) {
2864                                 dispatch(FuncRequest(LFUN_DIALOG_SHOW, "sendto"),
2865                                          dr);
2866                                 break;
2867                         }
2868                         if (!doc_buffer->doExport(argument, false)) {
2869                                 dr.setError(true);
2870                                 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
2871                                         cmd.argument()));
2872                         }
2873                         break;
2874                 }
2875
2876                 case LFUN_BUFFER_UPDATE: {
2877                         if (!doc_buffer)
2878                                 break;
2879                         string format = argument;
2880                         if (argument.empty())
2881                                 format = doc_buffer->getDefaultOutputFormat();
2882 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
2883                         d.progress_->clearMessages();
2884                         message(_("Exporting ..."));
2885                         GuiViewPrivate::busyBuffers.insert(doc_buffer);
2886                         QFuture<docstring> f = QtConcurrent::run(GuiViewPrivate::exportAndDestroy,
2887                                 doc_buffer, doc_buffer->clone(), format);
2888                         d.setPreviewFuture(f);
2889                         d.last_export_format = doc_buffer->bufferFormat();
2890 #else
2891                         bool const update_unincluded =
2892                                 doc_buffer->params().maintain_unincluded_children
2893                                 && !doc_buffer->params().getIncludedChildren().empty();
2894                         doc_buffer->doExport(format, true, update_unincluded);
2895 #endif
2896                         break;
2897                 }
2898                 case LFUN_BUFFER_VIEW: {
2899                         if (!doc_buffer)
2900                                 break;
2901                         string format = argument;
2902                         if (argument.empty())
2903                                 format = doc_buffer->getDefaultOutputFormat();
2904 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
2905                         d.progress_->clearMessages();
2906                         message(_("Previewing ..."));
2907                         GuiViewPrivate::busyBuffers.insert(doc_buffer);
2908                         QFuture<docstring> f = QtConcurrent::run(GuiViewPrivate::previewAndDestroy,
2909                                 doc_buffer, doc_buffer->clone(), format);
2910                         d.setPreviewFuture(f);
2911                         d.last_export_format = doc_buffer->bufferFormat();
2912 #else
2913                         bool const update_unincluded =
2914                                 doc_buffer->params().maintain_unincluded_children
2915                                 && !doc_buffer->params().getIncludedChildren().empty();
2916                         doc_buffer->preview(format, update_unincluded);
2917 #endif
2918                         break;
2919                 }
2920                 case LFUN_MASTER_BUFFER_UPDATE: {
2921                         if (!doc_buffer)
2922                                 break;
2923                         string format = argument;
2924                         Buffer const * master = doc_buffer->masterBuffer();
2925                         if (argument.empty())
2926                                 format = master->getDefaultOutputFormat();
2927 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
2928                         GuiViewPrivate::busyBuffers.insert(master);
2929                         QFuture<docstring> f = QtConcurrent::run(GuiViewPrivate::exportAndDestroy,
2930                                 master, master->clone(), format);
2931                         d.setPreviewFuture(f);
2932                         d.last_export_format = doc_buffer->bufferFormat();
2933 #else
2934                         bool const update_unincluded =
2935                                 master->params().maintain_unincluded_children
2936                                 && !master->params().getIncludedChildren().empty();
2937                         master->doExport(format, true);
2938 #endif
2939                         break;
2940                 }
2941                 case LFUN_MASTER_BUFFER_VIEW: {
2942                         string format = argument;
2943                         Buffer const * master = doc_buffer->masterBuffer();
2944                         if (argument.empty())
2945                                 format = master->getDefaultOutputFormat();
2946 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
2947                         GuiViewPrivate::busyBuffers.insert(master);
2948                         QFuture<docstring> f = QtConcurrent::run(GuiViewPrivate::previewAndDestroy,
2949                                 master, master->clone(), format);
2950                         d.setPreviewFuture(f);
2951                         d.last_export_format = doc_buffer->bufferFormat();
2952 #else
2953                         master->preview(format);
2954 #endif
2955                         break;
2956                 }
2957                 case LFUN_BUFFER_SWITCH: {
2958                         string const file_name = to_utf8(cmd.argument());
2959                         if (!FileName::isAbsolute(file_name)) {
2960                                 dr.setError(true);
2961                                 dr.setMessage(_("Absolute filename expected."));
2962                                 break;
2963                         }
2964
2965                         Buffer * buffer = theBufferList().getBuffer(FileName(file_name));
2966                         if (!buffer) {
2967                                 dr.setError(true);
2968                                 dr.setMessage(_("Document not loaded"));
2969                                 break;
2970                         }
2971
2972                         // Do we open or switch to the buffer in this view ?
2973                         if (workArea(*buffer)
2974                                   || lyxrc.open_buffers_in_tabs || !documentBufferView()) {
2975                                 setBuffer(buffer);
2976                                 break;
2977                         }
2978
2979                         // Look for the buffer in other views
2980                         QList<int> const ids = guiApp->viewIds();
2981                         int i = 0;
2982                         for (; i != ids.size(); ++i) {
2983                                 GuiView & gv = guiApp->view(ids[i]);
2984                                 if (gv.workArea(*buffer)) {
2985                                         gv.activateWindow();
2986                                         gv.setBuffer(buffer);
2987                                         break;
2988                                 }
2989                         }
2990
2991                         // If necessary, open a new window as a last resort
2992                         if (i == ids.size()) {
2993                                 lyx::dispatch(FuncRequest(LFUN_WINDOW_NEW));
2994                                 lyx::dispatch(cmd);
2995                         }
2996                         break;
2997                 }
2998
2999                 case LFUN_BUFFER_NEXT:
3000                         gotoNextOrPreviousBuffer(NEXTBUFFER);
3001                         break;
3002
3003                 case LFUN_BUFFER_PREVIOUS:
3004                         gotoNextOrPreviousBuffer(PREVBUFFER);
3005                         break;
3006
3007                 case LFUN_COMMAND_EXECUTE: {
3008                         bool const show_it = cmd.argument() != "off";
3009                         // FIXME: this is a hack, "minibuffer" should not be
3010                         // hardcoded.
3011                         if (GuiToolbar * t = toolbar("minibuffer")) {
3012                                 t->setVisible(show_it);
3013                                 if (show_it && t->commandBuffer())
3014                                         t->commandBuffer()->setFocus();
3015                         }
3016                         break;
3017                 }
3018                 case LFUN_DROP_LAYOUTS_CHOICE:
3019                         d.layout_->showPopup();
3020                         break;
3021
3022                 case LFUN_MENU_OPEN:
3023                         if (QMenu * menu = guiApp->menus().menu(toqstr(cmd.argument()), *this))
3024                                 menu->exec(QCursor::pos());
3025                         break;
3026
3027                 case LFUN_FILE_INSERT:
3028                         insertLyXFile(cmd.argument());
3029                         break;
3030                 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
3031                         insertPlaintextFile(cmd.argument(), true);
3032                         break;
3033
3034                 case LFUN_FILE_INSERT_PLAINTEXT:
3035                         insertPlaintextFile(cmd.argument(), false);
3036                         break;
3037
3038                 case LFUN_BUFFER_RELOAD: {
3039                         LASSERT(doc_buffer, break);
3040                         docstring const file = makeDisplayPath(doc_buffer->absFileName(), 20);
3041                         docstring text = bformat(_("Any changes will be lost. Are you sure "
3042                                                                  "you want to revert to the saved version of the document %1$s?"), file);
3043                         int const ret = Alert::prompt(_("Revert to saved document?"),
3044                                 text, 1, 1, _("&Revert"), _("&Cancel"));
3045
3046                         if (ret == 0) {
3047                                 doc_buffer->markClean();
3048                                 reloadBuffer();
3049                                 dr.forceBufferUpdate();
3050                         }
3051                         break;
3052                 }
3053
3054                 case LFUN_BUFFER_WRITE:
3055                         LASSERT(doc_buffer, break);
3056                         saveBuffer(*doc_buffer);
3057                         break;
3058
3059                 case LFUN_BUFFER_WRITE_AS:
3060                         LASSERT(doc_buffer, break);
3061                         renameBuffer(*doc_buffer, cmd.argument());
3062                         break;
3063
3064                 case LFUN_BUFFER_WRITE_ALL: {
3065                         Buffer * first = theBufferList().first();
3066                         if (!first)
3067                                 break;
3068                         message(_("Saving all documents..."));
3069                         // We cannot use a for loop as the buffer list cycles.
3070                         Buffer * b = first;
3071                         do {
3072                                 if (!b->isClean()) {
3073                                         saveBuffer(*b);
3074                                         LYXERR(Debug::ACTION, "Saved " << b->absFileName());
3075                                 }
3076                                 b = theBufferList().next(b);
3077                         } while (b != first);
3078                         dr.setMessage(_("All documents saved."));
3079                         break;
3080                 }
3081
3082                 case LFUN_BUFFER_CLOSE:
3083                         closeBuffer();
3084                         break;
3085
3086                 case LFUN_BUFFER_CLOSE_ALL:
3087                         closeBufferAll();
3088                         break;
3089
3090                 case LFUN_TOOLBAR_TOGGLE: {
3091                         string const name = cmd.getArg(0);
3092                         if (GuiToolbar * t = toolbar(name))
3093                                 t->toggle();
3094                         break;
3095                 }
3096
3097                 case LFUN_DIALOG_UPDATE: {
3098                         string const name = to_utf8(cmd.argument());
3099                         if (currentBufferView()) {
3100                                 Inset * inset = currentBufferView()->editedInset(name);
3101                                 // Can only update a dialog connected to an existing inset
3102                                 if (!inset)
3103                                         break;
3104                                 // FIXME: get rid of this indirection; GuiView ask the inset
3105                                 // if he is kind enough to update itself...
3106                                 FuncRequest fr(LFUN_INSET_DIALOG_UPDATE, cmd.argument());
3107                                 //FIXME: pass DispatchResult here?
3108                                 inset->dispatch(currentBufferView()->cursor(), fr);
3109                         } else if (name == "paragraph") {
3110                                 lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
3111                         } else if (name == "prefs" || name == "document") {
3112                                 updateDialog(name, string());
3113                         }
3114                         break;
3115                 }
3116
3117                 case LFUN_DIALOG_TOGGLE: {
3118                         if (isDialogVisible(cmd.getArg(0)))
3119                                 dispatch(FuncRequest(LFUN_DIALOG_HIDE, cmd.argument()), dr);
3120                         else
3121                                 dispatch(FuncRequest(LFUN_DIALOG_SHOW, cmd.argument()), dr);
3122                         break;
3123                 }
3124
3125                 case LFUN_DIALOG_DISCONNECT_INSET:
3126                         disconnectDialog(to_utf8(cmd.argument()));
3127                         break;
3128
3129                 case LFUN_DIALOG_HIDE: {
3130                         guiApp->hideDialogs(to_utf8(cmd.argument()), 0);
3131                         break;
3132                 }
3133
3134                 case LFUN_DIALOG_SHOW: {
3135                         string const name = cmd.getArg(0);
3136                         string data = trim(to_utf8(cmd.argument()).substr(name.size()));
3137
3138                         if (name == "character") {
3139                                 data = freefont2string();
3140                                 if (!data.empty())
3141                                         showDialog("character", data);
3142                         } else if (name == "latexlog") {
3143                                 Buffer::LogType type;
3144                                 string const logfile = doc_buffer->logName(&type);
3145                                 switch (type) {
3146                                 case Buffer::latexlog:
3147                                         data = "latex ";
3148                                         break;
3149                                 case Buffer::buildlog:
3150                                         data = "literate ";
3151                                         break;
3152                                 }
3153                                 data += Lexer::quoteString(logfile);
3154                                 showDialog("log", data);
3155                         } else if (name == "vclog") {
3156                                 string const data = "vc " +
3157                                         Lexer::quoteString(doc_buffer->lyxvc().getLogFile());
3158                                 showDialog("log", data);
3159                         } else if (name == "symbols") {
3160                                 data = bv->cursor().getEncoding()->name();
3161                                 if (!data.empty())
3162                                         showDialog("symbols", data);
3163                         // bug 5274
3164                         } else if (name == "prefs" && isFullScreen()) {
3165                                 lfunUiToggle("fullscreen");
3166                                 showDialog("prefs", data);
3167                         } else
3168                                 showDialog(name, data);
3169                         break;
3170                 }
3171
3172                 case LFUN_MESSAGE:
3173                         dr.setMessage(cmd.argument());
3174                         break;
3175
3176                 case LFUN_UI_TOGGLE: {
3177                         string arg = cmd.getArg(0);
3178                         if (!lfunUiToggle(arg)) {
3179                                 docstring const msg = "ui-toggle " + _("%1$s unknown command!");
3180                                 dr.setMessage(bformat(msg, from_utf8(arg)));
3181                         }
3182                         // Make sure the keyboard focus stays in the work area.
3183                         setFocus();
3184                         break;
3185                 }
3186
3187                 case LFUN_SPLIT_VIEW: {
3188                         LASSERT(doc_buffer, break);
3189                         string const orientation = cmd.getArg(0);
3190                         d.splitter_->setOrientation(orientation == "vertical"
3191                                 ? Qt::Vertical : Qt::Horizontal);
3192                         TabWorkArea * twa = addTabWorkArea();
3193                         GuiWorkArea * wa = twa->addWorkArea(*doc_buffer, *this);
3194                         setCurrentWorkArea(wa);
3195                         break;
3196                 }
3197                 case LFUN_CLOSE_TAB_GROUP:
3198                         if (TabWorkArea * twa = d.currentTabWorkArea()) {
3199                                 closeTabWorkArea(twa);
3200                                 d.current_work_area_ = 0;
3201                                 twa = d.currentTabWorkArea();
3202                                 // Switch to the next GuiWorkArea in the found TabWorkArea.
3203                                 if (twa) {
3204                                         // Make sure the work area is up to date.
3205                                         setCurrentWorkArea(twa->currentWorkArea());
3206                                 } else {
3207                                         setCurrentWorkArea(0);
3208                                 }
3209                         }
3210                         break;
3211
3212                 case LFUN_COMPLETION_INLINE:
3213                         if (d.current_work_area_)
3214                                 d.current_work_area_->completer().showInline();
3215                         break;
3216
3217                 case LFUN_COMPLETION_POPUP:
3218                         if (d.current_work_area_)
3219                                 d.current_work_area_->completer().showPopup();
3220                         break;
3221
3222
3223                 case LFUN_COMPLETION_COMPLETE:
3224                         if (d.current_work_area_)
3225                                 d.current_work_area_->completer().tab();
3226                         break;
3227
3228                 case LFUN_COMPLETION_CANCEL:
3229                         if (d.current_work_area_) {
3230                                 if (d.current_work_area_->completer().popupVisible())
3231                                         d.current_work_area_->completer().hidePopup();
3232                                 else
3233                                         d.current_work_area_->completer().hideInline();
3234                         }
3235                         break;
3236
3237                 case LFUN_COMPLETION_ACCEPT:
3238                         if (d.current_work_area_)
3239                                 d.current_work_area_->completer().activate();
3240                         break;
3241
3242                 case LFUN_BUFFER_ZOOM_IN:
3243                 case LFUN_BUFFER_ZOOM_OUT:
3244                         if (cmd.argument().empty()) {
3245                                 if (cmd.action() == LFUN_BUFFER_ZOOM_IN)
3246                                         lyxrc.zoom += 20;
3247                                 else
3248                                         lyxrc.zoom -= 20;
3249                         } else
3250                                 lyxrc.zoom += convert<int>(cmd.argument());
3251
3252                         if (lyxrc.zoom < 10)
3253                                 lyxrc.zoom = 10;
3254
3255                         // The global QPixmapCache is used in GuiPainter to cache text
3256                         // painting so we must reset it.
3257                         QPixmapCache::clear();
3258                         guiApp->fontLoader().update();
3259                         lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
3260                         break;
3261
3262                 case LFUN_VC_REGISTER:
3263                 case LFUN_VC_CHECK_IN:
3264                 case LFUN_VC_CHECK_OUT:
3265                 case LFUN_VC_REPO_UPDATE:
3266                 case LFUN_VC_LOCKING_TOGGLE:
3267                 case LFUN_VC_REVERT:
3268                 case LFUN_VC_UNDO_LAST:
3269                 case LFUN_VC_COMMAND:
3270                 case LFUN_VC_COMPARE:
3271                         dispatchVC(cmd);
3272                         break;
3273
3274                 case LFUN_SERVER_GOTO_FILE_ROW:
3275                         goToFileRow(to_utf8(cmd.argument()));
3276                         break;
3277
3278                 case LFUN_FORWARD_SEARCH: {
3279                         FileName const path(doc_buffer->temppath());
3280                         string const texname = doc_buffer->latexName();
3281                         FileName const dviname(addName(path.absFileName(),
3282                                     support::changeExtension(texname, "dvi")));
3283                         FileName const pdfname(addName(path.absFileName(),
3284                                     support::changeExtension(texname, "pdf")));
3285                         if (!dviname.exists() && !pdfname.exists()) {
3286                                 dr.setMessage(_("Please, preview the document first."));
3287                                 break;
3288                         }
3289                         string outname = dviname.onlyFileName();
3290                         string command = lyxrc.forward_search_dvi;
3291                         if (!dviname.exists() ||
3292                             pdfname.lastModified() > dviname.lastModified()) {
3293                                 outname = pdfname.onlyFileName();
3294                                 command = lyxrc.forward_search_pdf;
3295                         }
3296
3297                         int row = doc_buffer->texrow().getRowFromIdPos(bv->cursor().paragraph().id(), bv->cursor().pos());
3298                         LYXERR(Debug::ACTION, "Forward search: row:" << row
3299                                 << " id:" << bv->cursor().paragraph().id());
3300                         if (!row || command.empty()) {
3301                                 dr.setMessage(_("Couldn't proceed."));
3302                                 break;
3303                         }
3304                         string texrow = convert<string>(row);
3305
3306                         command = subst(command, "$$n", texrow);
3307                         command = subst(command, "$$t", texname);
3308                         command = subst(command, "$$o", outname);
3309
3310                         PathChanger p(path);
3311                         Systemcall one;
3312                         one.startscript(Systemcall::DontWait, command);
3313                         break;
3314                 }
3315                 default:
3316                         dr.dispatched(false);
3317                         break;
3318         }
3319
3320         // Part of automatic menu appearance feature.
3321         if (isFullScreen()) {
3322                 if (menuBar()->isVisible() && lyxrc.full_screen_menubar)
3323                         menuBar()->hide();
3324                 if (statusBar()->isVisible())
3325                         statusBar()->hide();
3326         }
3327
3328         return;
3329 }
3330
3331
3332 bool GuiView::lfunUiToggle(string const & ui_component)
3333 {
3334         if (ui_component == "scrollbar") {
3335                 // hide() is of no help
3336                 if (d.current_work_area_->verticalScrollBarPolicy() ==
3337                         Qt::ScrollBarAlwaysOff)
3338
3339                         d.current_work_area_->setVerticalScrollBarPolicy(
3340                                 Qt::ScrollBarAsNeeded);
3341                 else
3342                         d.current_work_area_->setVerticalScrollBarPolicy(
3343                                 Qt::ScrollBarAlwaysOff);
3344         } else if (ui_component == "statusbar") {
3345                 statusBar()->setVisible(!statusBar()->isVisible());
3346         } else if (ui_component == "menubar") {
3347                 menuBar()->setVisible(!menuBar()->isVisible());
3348         } else
3349 #if QT_VERSION >= 0x040300
3350         if (ui_component == "frame") {
3351                 int l, t, r, b;
3352                 getContentsMargins(&l, &t, &r, &b);
3353                 //are the frames in default state?
3354                 d.current_work_area_->setFrameStyle(QFrame::NoFrame);
3355                 if (l == 0) {
3356                         setContentsMargins(-2, -2, -2, -2);
3357                 } else {
3358                         setContentsMargins(0, 0, 0, 0);
3359                 }
3360         } else
3361 #endif
3362         if (ui_component == "fullscreen") {
3363                 toggleFullScreen();
3364         } else
3365                 return false;
3366         return true;
3367 }
3368
3369
3370 void GuiView::toggleFullScreen()
3371 {
3372         if (isFullScreen()) {
3373                 for (int i = 0; i != d.splitter_->count(); ++i)
3374                         d.tabWorkArea(i)->setFullScreen(false);
3375 #if QT_VERSION >= 0x040300
3376                 setContentsMargins(0, 0, 0, 0);
3377 #endif
3378                 setWindowState(windowState() ^ Qt::WindowFullScreen);
3379                 restoreLayout();
3380                 menuBar()->show();
3381                 statusBar()->show();
3382         } else {
3383                 // bug 5274
3384                 hideDialogs("prefs", 0);
3385                 for (int i = 0; i != d.splitter_->count(); ++i)
3386                         d.tabWorkArea(i)->setFullScreen(true);
3387 #if QT_VERSION >= 0x040300
3388                 setContentsMargins(-2, -2, -2, -2);
3389 #endif
3390                 saveLayout();
3391                 setWindowState(windowState() ^ Qt::WindowFullScreen);
3392                 statusBar()->hide();
3393                 if (lyxrc.full_screen_menubar)
3394                         menuBar()->hide();
3395                 if (lyxrc.full_screen_toolbars) {
3396                         ToolbarMap::iterator end = d.toolbars_.end();
3397                         for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
3398                                 it->second->hide();
3399                 }
3400         }
3401
3402         // give dialogs like the TOC a chance to adapt
3403         updateDialogs();
3404 }
3405
3406
3407 Buffer const * GuiView::updateInset(Inset const * inset)
3408 {
3409         if (!inset)
3410                 return 0;
3411
3412         Buffer const * inset_buffer = &(inset->buffer());
3413
3414         for (int i = 0; i != d.splitter_->count(); ++i) {
3415                 GuiWorkArea * wa = d.tabWorkArea(i)->currentWorkArea();
3416                 if (!wa)
3417                         continue;
3418                 Buffer const * buffer = &(wa->bufferView().buffer());
3419                 if (inset_buffer == buffer)
3420                         wa->scheduleRedraw();
3421         }
3422         return inset_buffer;
3423 }
3424
3425
3426 void GuiView::restartCursor()
3427 {
3428         /* When we move around, or type, it's nice to be able to see
3429          * the cursor immediately after the keypress.
3430          */
3431         if (d.current_work_area_)
3432                 d.current_work_area_->startBlinkingCursor();
3433
3434         // Take this occasion to update the other GUI elements.
3435         updateDialogs();
3436         updateStatusBar();
3437 }
3438
3439
3440 void GuiView::updateCompletion(Cursor & cur, bool start, bool keep)
3441 {
3442         if (d.current_work_area_)
3443                 d.current_work_area_->completer().updateVisibility(cur, start, keep);
3444 }
3445
3446 namespace {
3447
3448 // This list should be kept in sync with the list of insets in
3449 // src/insets/Inset.cpp.  I.e., if a dialog goes with an inset, the
3450 // dialog should have the same name as the inset.
3451 // Changes should be also recorded in LFUN_DIALOG_SHOW doxygen
3452 // docs in LyXAction.cpp.
3453
3454 char const * const dialognames[] = {
3455
3456 "aboutlyx", "bibitem", "bibtex", "box", "branch", "changes", "character",
3457 "citation", "compare", "comparehistory", "document", "errorlist", "ert",
3458 "external", "file", "findreplace", "findreplaceadv", "float", "graphics",
3459 "href", "include", "index", "index_print", "info", "listings", "label", "line",
3460 "log", "mathdelimiter", "mathmatrix", "mathspace", "nomenclature",
3461 "nomencl_print", "note", "paragraph", "phantom", "prefs", "print", "ref",
3462 "sendto", "space", "spellchecker", "symbols", "tabular", "tabularcreate",
3463 "thesaurus", "texinfo", "toc", "view-source", "vspace", "wrap", "progress"};
3464
3465 char const * const * const end_dialognames =
3466         dialognames + (sizeof(dialognames) / sizeof(char *));
3467
3468 class cmpCStr {
3469 public:
3470         cmpCStr(char const * name) : name_(name) {}
3471         bool operator()(char const * other) {
3472                 return strcmp(other, name_) == 0;
3473         }
3474 private:
3475         char const * name_;
3476 };
3477
3478
3479 bool isValidName(string const & name)
3480 {
3481         return find_if(dialognames, end_dialognames,
3482                                 cmpCStr(name.c_str())) != end_dialognames;
3483 }
3484
3485 } // namespace anon
3486
3487
3488 void GuiView::resetDialogs()
3489 {
3490         // Make sure that no LFUN uses any GuiView.
3491         guiApp->setCurrentView(0);
3492         saveLayout();
3493         menuBar()->clear();
3494         constructToolbars();
3495         guiApp->menus().fillMenuBar(menuBar(), this, false);
3496         d.layout_->updateContents(true);
3497         // Now update controls with current buffer.
3498         guiApp->setCurrentView(this);
3499         restoreLayout();
3500         restartCursor();
3501 }
3502
3503
3504 Dialog * GuiView::findOrBuild(string const & name, bool hide_it)
3505 {
3506         if (!isValidName(name))
3507                 return 0;
3508
3509         map<string, DialogPtr>::iterator it = d.dialogs_.find(name);
3510
3511         if (it != d.dialogs_.end()) {
3512                 if (hide_it)
3513                         it->second->hideView();
3514                 return it->second.get();
3515         }
3516
3517         Dialog * dialog = build(name);
3518         d.dialogs_[name].reset(dialog);
3519         if (lyxrc.allow_geometry_session)
3520                 dialog->restoreSession();
3521         if (hide_it)
3522                 dialog->hideView();
3523         return dialog;
3524 }
3525
3526
3527 void GuiView::showDialog(string const & name, string const & data,
3528         Inset * inset)
3529 {
3530         triggerShowDialog(toqstr(name), toqstr(data), inset);
3531 }
3532
3533
3534 void GuiView::doShowDialog(QString const & qname, QString const & qdata,
3535         Inset * inset)
3536 {
3537         if (d.in_show_)
3538                 return;
3539
3540         const string name = fromqstr(qname);
3541         const string data = fromqstr(qdata);
3542
3543         d.in_show_ = true;
3544         try {
3545                 Dialog * dialog = findOrBuild(name, false);
3546                 if (dialog) {
3547                         bool const visible = dialog->isVisibleView();
3548                         dialog->showData(data);
3549                         if (inset && currentBufferView())
3550                                 currentBufferView()->editInset(name, inset);
3551                         // We only set the focus to the new dialog if it was not yet
3552                         // visible in order not to change the existing previous behaviour
3553                         if (visible) {
3554                                 // activateWindow is needed for floating dockviews
3555                                 dialog->asQWidget()->raise();
3556                                 dialog->asQWidget()->activateWindow();
3557                                 dialog->asQWidget()->setFocus();
3558                         }
3559                 }
3560         }
3561         catch (ExceptionMessage const & ex) {
3562                 d.in_show_ = false;
3563                 throw ex;
3564         }
3565         d.in_show_ = false;
3566 }
3567
3568
3569 bool GuiView::isDialogVisible(string const & name) const
3570 {
3571         map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3572         if (it == d.dialogs_.end())
3573                 return false;
3574         return it->second.get()->isVisibleView() && !it->second.get()->isClosing();
3575 }
3576
3577
3578 void GuiView::hideDialog(string const & name, Inset * inset)
3579 {
3580         map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3581         if (it == d.dialogs_.end())
3582                 return;
3583
3584         if (inset && currentBufferView()
3585                 && inset != currentBufferView()->editedInset(name))
3586                 return;
3587
3588         Dialog * const dialog = it->second.get();
3589         if (dialog->isVisibleView())
3590                 dialog->hideView();
3591         if (currentBufferView())
3592                 currentBufferView()->editInset(name, 0);
3593 }
3594
3595
3596 void GuiView::disconnectDialog(string const & name)
3597 {
3598         if (!isValidName(name))
3599                 return;
3600         if (currentBufferView())
3601                 currentBufferView()->editInset(name, 0);
3602 }
3603
3604
3605 void GuiView::hideAll() const
3606 {
3607         map<string, DialogPtr>::const_iterator it  = d.dialogs_.begin();
3608         map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3609
3610         for(; it != end; ++it)
3611                 it->second->hideView();
3612 }
3613
3614
3615 void GuiView::updateDialogs()
3616 {
3617         map<string, DialogPtr>::const_iterator it  = d.dialogs_.begin();
3618         map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3619
3620         for(; it != end; ++it) {
3621                 Dialog * dialog = it->second.get();
3622                 if (dialog) {
3623                         if (dialog->needBufferOpen() && !documentBufferView())
3624                                 hideDialog(fromqstr(dialog->name()), 0);
3625                         else if (dialog->isVisibleView())
3626                                 dialog->checkStatus();
3627                 }
3628         }
3629         updateToolbars();
3630         updateLayoutList();
3631 }
3632
3633 Dialog * createDialog(GuiView & lv, string const & name);
3634
3635 // will be replaced by a proper factory...
3636 Dialog * createGuiAbout(GuiView & lv);
3637 Dialog * createGuiBibtex(GuiView & lv);
3638 Dialog * createGuiChanges(GuiView & lv);
3639 Dialog * createGuiCharacter(GuiView & lv);
3640 Dialog * createGuiCitation(GuiView & lv);
3641 Dialog * createGuiCompare(GuiView & lv);
3642 Dialog * createGuiCompareHistory(GuiView & lv);
3643 Dialog * createGuiDelimiter(GuiView & lv);
3644 Dialog * createGuiDocument(GuiView & lv);
3645 Dialog * createGuiErrorList(GuiView & lv);
3646 Dialog * createGuiExternal(GuiView & lv);
3647 Dialog * createGuiGraphics(GuiView & lv);
3648 Dialog * createGuiInclude(GuiView & lv);
3649 Dialog * createGuiIndex(GuiView & lv);
3650 Dialog * createGuiLabel(GuiView & lv);
3651 Dialog * createGuiListings(GuiView & lv);
3652 Dialog * createGuiLog(GuiView & lv);
3653 Dialog * createGuiMathMatrix(GuiView & lv);
3654 Dialog * createGuiNomenclature(GuiView & lv);
3655 Dialog * createGuiNote(GuiView & lv);
3656 Dialog * createGuiParagraph(GuiView & lv);
3657 Dialog * createGuiPhantom(GuiView & lv);
3658 Dialog * createGuiPreferences(GuiView & lv);
3659 Dialog * createGuiPrint(GuiView & lv);
3660 Dialog * createGuiPrintindex(GuiView & lv);
3661 Dialog * createGuiPrintNomencl(GuiView & lv);
3662 Dialog * createGuiRef(GuiView & lv);
3663 Dialog * createGuiSearch(GuiView & lv);
3664 Dialog * createGuiSearchAdv(GuiView & lv);
3665 Dialog * createGuiSendTo(GuiView & lv);
3666 Dialog * createGuiShowFile(GuiView & lv);
3667 Dialog * createGuiSpellchecker(GuiView & lv);
3668 Dialog * createGuiSymbols(GuiView & lv);
3669 Dialog * createGuiTabularCreate(GuiView & lv);
3670 Dialog * createGuiTexInfo(GuiView & lv);
3671 Dialog * createGuiToc(GuiView & lv);
3672 Dialog * createGuiThesaurus(GuiView & lv);
3673 Dialog * createGuiHyperlink(GuiView & lv);
3674 Dialog * createGuiViewSource(GuiView & lv);
3675 Dialog * createGuiWrap(GuiView & lv);
3676 Dialog * createGuiProgressView(GuiView & lv);
3677
3678
3679
3680 Dialog * GuiView::build(string const & name)
3681 {
3682         LASSERT(isValidName(name), return 0);
3683
3684         Dialog * dialog = createDialog(*this, name);
3685         if (dialog)
3686                 return dialog;
3687
3688         if (name == "aboutlyx")
3689                 return createGuiAbout(*this);
3690         if (name == "bibtex")
3691                 return createGuiBibtex(*this);
3692         if (name == "changes")
3693                 return createGuiChanges(*this);
3694         if (name == "character")
3695                 return createGuiCharacter(*this);
3696         if (name == "citation")
3697                 return createGuiCitation(*this);
3698         if (name == "compare")
3699                 return createGuiCompare(*this);
3700         if (name == "comparehistory")
3701                 return createGuiCompareHistory(*this);
3702         if (name == "document")
3703                 return createGuiDocument(*this);
3704         if (name == "errorlist")
3705                 return createGuiErrorList(*this);
3706         if (name == "external")
3707                 return createGuiExternal(*this);
3708         if (name == "file")
3709                 return createGuiShowFile(*this);
3710         if (name == "findreplace")
3711                 return createGuiSearch(*this);
3712         if (name == "findreplaceadv")
3713                 return createGuiSearchAdv(*this);
3714         if (name == "graphics")
3715                 return createGuiGraphics(*this);
3716         if (name == "href")
3717                 return createGuiHyperlink(*this);
3718         if (name == "include")
3719                 return createGuiInclude(*this);
3720         if (name == "index")
3721                 return createGuiIndex(*this);
3722         if (name == "index_print")
3723                 return createGuiPrintindex(*this);
3724         if (name == "label")
3725                 return createGuiLabel(*this);
3726         if (name == "listings")
3727                 return createGuiListings(*this);
3728         if (name == "log")
3729                 return createGuiLog(*this);
3730         if (name == "mathdelimiter")
3731                 return createGuiDelimiter(*this);
3732         if (name == "mathmatrix")
3733                 return createGuiMathMatrix(*this);
3734         if (name == "nomenclature")
3735                 return createGuiNomenclature(*this);
3736         if (name == "nomencl_print")
3737                 return createGuiPrintNomencl(*this);
3738         if (name == "note")
3739                 return createGuiNote(*this);
3740         if (name == "paragraph")
3741                 return createGuiParagraph(*this);
3742         if (name == "phantom")
3743                 return createGuiPhantom(*this);
3744         if (name == "prefs")
3745                 return createGuiPreferences(*this);
3746         if (name == "print")
3747                 return createGuiPrint(*this);
3748         if (name == "ref")
3749                 return createGuiRef(*this);
3750         if (name == "sendto")
3751                 return createGuiSendTo(*this);
3752         if (name == "spellchecker")
3753                 return createGuiSpellchecker(*this);
3754         if (name == "symbols")
3755                 return createGuiSymbols(*this);
3756         if (name == "tabularcreate")
3757                 return createGuiTabularCreate(*this);
3758         if (name == "texinfo")
3759                 return createGuiTexInfo(*this);
3760         if (name == "thesaurus")
3761                 return createGuiThesaurus(*this);
3762         if (name == "toc")
3763                 return createGuiToc(*this);
3764         if (name == "view-source")
3765                 return createGuiViewSource(*this);
3766         if (name == "wrap")
3767                 return createGuiWrap(*this);
3768         if (name == "progress")
3769                 return createGuiProgressView(*this);
3770
3771         return 0;
3772 }
3773
3774
3775 } // namespace frontend
3776 } // namespace lyx
3777
3778 #include "moc_GuiView.cpp"