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