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