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