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