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