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