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