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