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