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