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