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