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