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