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