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