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