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