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