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