]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiView.cpp
Fix bug #7314: Workareas not redrawn. This is caused because the current_workarea...
[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                 //Why would we want to stop updates only for one workarea and
1155                 //not for the others ? This leads to problems as in #7314 (vfr).
1156                 //d.current_work_area_->setUpdatesEnabled(!busy);
1157                 if (busy)
1158                         d.current_work_area_->stopBlinkingCursor();
1159                 else
1160                         d.current_work_area_->startBlinkingCursor();
1161         }
1162
1163         if (busy)
1164                 QApplication::setOverrideCursor(Qt::WaitCursor);
1165         else
1166                 QApplication::restoreOverrideCursor();
1167 }
1168
1169
1170 GuiWorkArea * GuiView::workArea(int index)
1171 {
1172         if (TabWorkArea * twa = d.currentTabWorkArea())
1173                 if (index < twa->count())
1174                         return dynamic_cast<GuiWorkArea *>(twa->widget(index));
1175         return 0;
1176 }
1177
1178
1179 GuiWorkArea * GuiView::workArea(Buffer & buffer)
1180 {
1181         if (currentWorkArea()
1182                 && &currentWorkArea()->bufferView().buffer() == &buffer)
1183                 return (GuiWorkArea *) currentWorkArea();
1184         if (TabWorkArea * twa = d.currentTabWorkArea())
1185                 return twa->workArea(buffer);
1186         return 0;
1187 }
1188
1189
1190 GuiWorkArea * GuiView::addWorkArea(Buffer & buffer)
1191 {
1192         // Automatically create a TabWorkArea if there are none yet.
1193         TabWorkArea * tab_widget = d.splitter_->count()
1194                 ? d.currentTabWorkArea() : addTabWorkArea();
1195         return tab_widget->addWorkArea(buffer, *this);
1196 }
1197
1198
1199 TabWorkArea * GuiView::addTabWorkArea()
1200 {
1201         TabWorkArea * twa = new TabWorkArea;
1202         QObject::connect(twa, SIGNAL(currentWorkAreaChanged(GuiWorkArea *)),
1203                 this, SLOT(on_currentWorkAreaChanged(GuiWorkArea *)));
1204         QObject::connect(twa, SIGNAL(lastWorkAreaRemoved()),
1205                          this, SLOT(on_lastWorkAreaRemoved()));
1206
1207         d.splitter_->addWidget(twa);
1208         d.stack_widget_->setCurrentWidget(d.splitter_);
1209         return twa;
1210 }
1211
1212
1213 GuiWorkArea const * GuiView::currentWorkArea() const
1214 {
1215         return d.current_work_area_;
1216 }
1217
1218
1219 GuiWorkArea * GuiView::currentWorkArea()
1220 {
1221         return d.current_work_area_;
1222 }
1223
1224
1225 GuiWorkArea const * GuiView::currentMainWorkArea() const
1226 {
1227         if (!d.currentTabWorkArea())
1228                 return 0;
1229         return d.currentTabWorkArea()->currentWorkArea();
1230 }
1231
1232
1233 GuiWorkArea * GuiView::currentMainWorkArea()
1234 {
1235         if (!d.currentTabWorkArea())
1236                 return 0;
1237         return d.currentTabWorkArea()->currentWorkArea();
1238 }
1239
1240
1241 void GuiView::setCurrentWorkArea(GuiWorkArea * wa)
1242 {
1243         LYXERR(Debug::DEBUG, "Setting current wa: " << wa << endl);
1244         if (!wa) {
1245                 d.current_work_area_ = 0;
1246                 d.setBackground();
1247                 return;
1248         }
1249
1250         // FIXME: I've no clue why this is here and why it accesses
1251         //  theGuiApp()->currentView, which might be 0 (bug 6464).
1252         //  See also 27525 (vfr).
1253         if (theGuiApp()->currentView() == this
1254                   && theGuiApp()->currentView()->currentWorkArea() == wa)
1255                 return;
1256
1257         if (currentBufferView())
1258                 cap::saveSelection(currentBufferView()->cursor());
1259
1260         theGuiApp()->setCurrentView(this);
1261         d.current_work_area_ = wa;
1262         
1263         // We need to reset this now, because it will need to be
1264         // right if the tabWorkArea gets reset in the for loop. We
1265         // will change it back if we aren't in that case.
1266         GuiWorkArea * const old_cmwa = d.current_main_work_area_;
1267         d.current_main_work_area_ = wa;
1268
1269         for (int i = 0; i != d.splitter_->count(); ++i) {
1270                 if (d.tabWorkArea(i)->setCurrentWorkArea(wa)) {
1271                         LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() 
1272                                 << ", Current main wa: " << currentMainWorkArea());
1273                         return;
1274                 }
1275         }
1276         
1277         d.current_main_work_area_ = old_cmwa;
1278         
1279         LYXERR(Debug::DEBUG, "This is not a tabbed wa");
1280         on_currentWorkAreaChanged(wa);
1281         BufferView & bv = wa->bufferView();
1282         bv.cursor().fixIfBroken();
1283         bv.updateMetrics();
1284         wa->setUpdatesEnabled(true);
1285         LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() << ", Current main wa: " << currentMainWorkArea());
1286 }
1287
1288
1289 void GuiView::removeWorkArea(GuiWorkArea * wa)
1290 {
1291         LASSERT(wa, return);
1292         if (wa == d.current_work_area_) {
1293                 disconnectBuffer();
1294                 disconnectBufferView();
1295                 d.current_work_area_ = 0;
1296                 d.current_main_work_area_ = 0;
1297         }
1298
1299         bool found_twa = false;
1300         for (int i = 0; i != d.splitter_->count(); ++i) {
1301                 TabWorkArea * twa = d.tabWorkArea(i);
1302                 if (twa->removeWorkArea(wa)) {
1303                         // Found in this tab group, and deleted the GuiWorkArea.
1304                         found_twa = true;
1305                         if (twa->count() != 0) {
1306                                 if (d.current_work_area_ == 0)
1307                                         // This means that we are closing the current GuiWorkArea, so
1308                                         // switch to the next GuiWorkArea in the found TabWorkArea.
1309                                         setCurrentWorkArea(twa->currentWorkArea());
1310                         } else {
1311                                 // No more WorkAreas in this tab group, so delete it.
1312                                 delete twa;
1313                         }
1314                         break;
1315                 }
1316         }
1317
1318         // It is not a tabbed work area (i.e., the search work area), so it
1319         // should be deleted by other means.
1320         LASSERT(found_twa, /* */);
1321
1322         if (d.current_work_area_ == 0) {
1323                 if (d.splitter_->count() != 0) {
1324                         TabWorkArea * twa = d.currentTabWorkArea();
1325                         setCurrentWorkArea(twa->currentWorkArea());
1326                 } else {
1327                         // No more work areas, switch to the background widget.
1328                         setCurrentWorkArea(0);
1329                 }
1330         }
1331 }
1332
1333
1334 LayoutBox * GuiView::getLayoutDialog() const
1335 {
1336         return d.layout_;
1337 }
1338
1339
1340 void GuiView::updateLayoutList()
1341 {
1342         if (d.layout_)
1343                 d.layout_->updateContents(false);
1344 }
1345
1346
1347 void GuiView::updateToolbars()
1348 {
1349         ToolbarMap::iterator end = d.toolbars_.end();
1350         if (d.current_work_area_) {
1351                 bool const math =
1352                         d.current_work_area_->bufferView().cursor().inMathed()
1353                         && !d.current_work_area_->bufferView().cursor().inRegexped();
1354                 bool const table =
1355                         lyx::getStatus(FuncRequest(LFUN_LAYOUT_TABULAR)).enabled();
1356                 bool const review =
1357                         lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).enabled() &&
1358                         lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).onOff(true);
1359                 bool const mathmacrotemplate =
1360                         lyx::getStatus(FuncRequest(LFUN_IN_MATHMACROTEMPLATE)).enabled();
1361
1362                 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1363                         it->second->update(math, table, review, mathmacrotemplate);
1364         } else
1365                 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1366                         it->second->update(false, false, false, false);
1367 }
1368
1369
1370 void GuiView::setBuffer(Buffer * newBuffer)
1371 {
1372         LYXERR(Debug::DEBUG, "Setting buffer: " << newBuffer << endl);
1373         LASSERT(newBuffer, return);
1374         
1375         GuiWorkArea * wa = workArea(*newBuffer);
1376         if (wa == 0) {
1377                 setBusy(true);
1378                 newBuffer->masterBuffer()->updateBuffer();
1379                 setBusy(false);
1380                 wa = addWorkArea(*newBuffer);
1381                 // scroll to the position when the BufferView was last closed
1382                 if (lyxrc.use_lastfilepos) {
1383                         LastFilePosSection::FilePos filepos =
1384                                 theSession().lastFilePos().load(newBuffer->fileName());
1385                         wa->bufferView().moveToPosition(filepos.pit, filepos.pos, 0, 0);
1386                 }
1387         } else {
1388                 //Disconnect the old buffer...there's no new one.
1389                 disconnectBuffer();
1390         }
1391         connectBuffer(*newBuffer);
1392         connectBufferView(wa->bufferView());
1393         setCurrentWorkArea(wa);
1394 }
1395
1396
1397 void GuiView::connectBuffer(Buffer & buf)
1398 {
1399         buf.setGuiDelegate(this);
1400 }
1401
1402
1403 void GuiView::disconnectBuffer()
1404 {
1405         if (d.current_work_area_)
1406                 d.current_work_area_->bufferView().buffer().setGuiDelegate(0);
1407 }
1408
1409
1410 void GuiView::connectBufferView(BufferView & bv)
1411 {
1412         bv.setGuiDelegate(this);
1413 }
1414
1415
1416 void GuiView::disconnectBufferView()
1417 {
1418         if (d.current_work_area_)
1419                 d.current_work_area_->bufferView().setGuiDelegate(0);
1420 }
1421
1422
1423 void GuiView::errors(string const & error_type, bool from_master)
1424 {
1425         BufferView const * const bv = currentBufferView();
1426         if (!bv)
1427                 return;
1428
1429 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
1430         // We are called with from_master == false by default, so we
1431         // have to figure out whether that is the case or not.
1432         ErrorList & el = bv->buffer().errorList(error_type);
1433         if (el.empty()) {
1434             el = bv->buffer().masterBuffer()->errorList(error_type);
1435             from_master = true;
1436         }
1437 #else
1438         ErrorList & el = from_master ?
1439                 bv->buffer().masterBuffer()->errorList(error_type) :
1440                 bv->buffer().errorList(error_type);
1441 #endif
1442
1443         if (el.empty())
1444                 return;
1445
1446         string data = error_type;
1447         if (from_master)
1448                 data = "from_master|" + error_type;
1449         showDialog("errorlist", data);
1450 }
1451
1452
1453 void GuiView::updateTocItem(string const & type, DocIterator const & dit)
1454 {
1455         d.toc_models_.updateItem(toqstr(type), dit);
1456 }
1457
1458
1459 void GuiView::structureChanged()
1460 {
1461         d.toc_models_.reset(documentBufferView());
1462         // Navigator needs more than a simple update in this case. It needs to be
1463         // rebuilt.
1464         updateDialog("toc", "");
1465 }
1466
1467
1468 void GuiView::updateDialog(string const & name, string const & data)
1469 {
1470         if (!isDialogVisible(name))
1471                 return;
1472
1473         map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
1474         if (it == d.dialogs_.end())
1475                 return;
1476
1477         Dialog * const dialog = it->second.get();
1478         if (dialog->isVisibleView())
1479                 dialog->initialiseParams(data);
1480 }
1481
1482
1483 BufferView * GuiView::documentBufferView()
1484 {
1485         return currentMainWorkArea()
1486                 ? &currentMainWorkArea()->bufferView()
1487                 : 0;
1488 }
1489
1490
1491 BufferView const * GuiView::documentBufferView() const
1492 {
1493         return currentMainWorkArea()
1494                 ? &currentMainWorkArea()->bufferView()
1495                 : 0;
1496 }
1497
1498
1499 BufferView * GuiView::currentBufferView()
1500 {
1501         return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1502 }
1503
1504
1505 BufferView const * GuiView::currentBufferView() const
1506 {
1507         return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1508 }
1509
1510
1511 #if (QT_VERSION >= 0x040400)
1512 docstring GuiView::GuiViewPrivate::autosaveAndDestroy(
1513         Buffer const * orig, Buffer * buffer)
1514 {
1515         bool const success = buffer->autoSave();
1516         delete buffer;
1517         busyBuffers.remove(orig);
1518         return success
1519                 ? _("Automatic save done.")
1520                 : _("Automatic save failed!");
1521 }
1522 #endif
1523
1524
1525 void GuiView::autoSave()
1526 {
1527         LYXERR(Debug::INFO, "Running autoSave()");
1528
1529         Buffer * buffer = documentBufferView()
1530                 ? &documentBufferView()->buffer() : 0;
1531         if (!buffer) {
1532                 resetAutosaveTimers();
1533                 return;
1534         }
1535
1536 #if (QT_VERSION >= 0x040400)
1537         GuiViewPrivate::busyBuffers.insert(buffer);
1538         QFuture<docstring> f = QtConcurrent::run(GuiViewPrivate::autosaveAndDestroy,
1539                 buffer, buffer->clone());
1540         d.autosave_watcher_.setFuture(f);
1541 #else
1542         buffer->autoSave();
1543 #endif
1544         resetAutosaveTimers();
1545 }
1546
1547
1548 void GuiView::resetAutosaveTimers()
1549 {
1550         if (lyxrc.autosave)
1551                 d.autosave_timeout_.restart();
1552 }
1553
1554
1555 bool GuiView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1556 {
1557         bool enable = true;
1558         Buffer * buf = currentBufferView()
1559                 ? &currentBufferView()->buffer() : 0;
1560         Buffer * doc_buffer = documentBufferView()
1561                 ? &(documentBufferView()->buffer()) : 0;
1562
1563         // Check whether we need a buffer
1564         if (!lyxaction.funcHasFlag(cmd.action(), LyXAction::NoBuffer) && !buf) {
1565                 // no, exit directly
1566                 flag.message(from_utf8(N_("Command not allowed with"
1567                                         "out any document open")));
1568                 flag.setEnabled(false);
1569                 return true;
1570         }
1571
1572         if (cmd.origin() == FuncRequest::TOC) {
1573                 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
1574                 if (!toc || !toc->getStatus(documentBufferView()->cursor(), cmd, flag))
1575                         flag.setEnabled(false);
1576                 return true;
1577         }
1578
1579         switch(cmd.action()) {
1580         case LFUN_BUFFER_IMPORT:
1581                 break;
1582
1583         case LFUN_MASTER_BUFFER_UPDATE:
1584         case LFUN_MASTER_BUFFER_VIEW:
1585                 enable = doc_buffer && doc_buffer->parent() != 0
1586                         && !d.processing_thread_watcher_.isRunning();
1587                 break;
1588
1589         case LFUN_BUFFER_UPDATE:
1590         case LFUN_BUFFER_VIEW: {
1591                 if (!doc_buffer || d.processing_thread_watcher_.isRunning()) {
1592                         enable = false;
1593                         break;
1594                 }
1595                 string format = to_utf8(cmd.argument());
1596                 if (cmd.argument().empty())
1597                         format = doc_buffer->getDefaultOutputFormat();
1598                 enable = doc_buffer->isExportableFormat(format);
1599                 break;
1600         }
1601
1602         case LFUN_BUFFER_RELOAD:
1603                 enable = doc_buffer && !doc_buffer->isUnnamed()
1604                         && doc_buffer->fileName().exists()
1605                         && (!doc_buffer->isClean()
1606                            || doc_buffer->isExternallyModified(Buffer::timestamp_method));
1607                 break;
1608
1609         case LFUN_BUFFER_CHILD_OPEN:
1610                 enable = doc_buffer;
1611                 break;
1612
1613         case LFUN_BUFFER_WRITE:
1614                 enable = doc_buffer && (doc_buffer->isUnnamed() || !doc_buffer->isClean());
1615                 break;
1616
1617         //FIXME: This LFUN should be moved to GuiApplication.
1618         case LFUN_BUFFER_WRITE_ALL: {
1619                 // We enable the command only if there are some modified buffers
1620                 Buffer * first = theBufferList().first();
1621                 enable = false;
1622                 if (!first)
1623                         break;
1624                 Buffer * b = first;
1625                 // We cannot use a for loop as the buffer list is a cycle.
1626                 do {
1627                         if (!b->isClean()) {
1628                                 enable = true;
1629                                 break;
1630                         }
1631                         b = theBufferList().next(b);
1632                 } while (b != first);
1633                 break;
1634         }
1635
1636         case LFUN_BUFFER_WRITE_AS:
1637                 enable = doc_buffer;
1638                 break;
1639
1640         case LFUN_BUFFER_CLOSE:
1641                 enable = doc_buffer;
1642                 break;
1643
1644         case LFUN_BUFFER_CLOSE_ALL:
1645                 enable = theBufferList().last() != theBufferList().first();
1646                 break;
1647
1648         case LFUN_SPLIT_VIEW:
1649                 if (cmd.getArg(0) == "vertical")
1650                         enable = doc_buffer && (d.splitter_->count() == 1 ||
1651                                          d.splitter_->orientation() == Qt::Vertical);
1652                 else
1653                         enable = doc_buffer && (d.splitter_->count() == 1 ||
1654                                          d.splitter_->orientation() == Qt::Horizontal);
1655                 break;
1656
1657         case LFUN_CLOSE_TAB_GROUP:
1658                 enable = d.currentTabWorkArea();
1659                 break;
1660
1661         case LFUN_TOOLBAR_TOGGLE: {
1662                 string const name = cmd.getArg(0);
1663                 if (GuiToolbar * t = toolbar(name))
1664                         flag.setOnOff(t->isVisible());
1665                 else {
1666                         enable = false;
1667                         docstring const msg =
1668                                 bformat(_("Unknown toolbar \"%1$s\""), from_utf8(name));
1669                         flag.message(msg);
1670                 }
1671                 break;
1672         }
1673
1674         case LFUN_DROP_LAYOUTS_CHOICE:
1675                 enable = buf;
1676                 break;
1677
1678         case LFUN_UI_TOGGLE:
1679                 flag.setOnOff(isFullScreen());
1680                 break;
1681
1682         case LFUN_DIALOG_DISCONNECT_INSET:
1683                 break;
1684
1685         case LFUN_DIALOG_HIDE:
1686                 // FIXME: should we check if the dialog is shown?
1687                 break;
1688
1689         case LFUN_DIALOG_TOGGLE:
1690                 flag.setOnOff(isDialogVisible(cmd.getArg(0)));
1691                 // fall through to set "enable"
1692         case LFUN_DIALOG_SHOW: {
1693                 string const name = cmd.getArg(0);
1694                 if (!doc_buffer)
1695                         enable = name == "aboutlyx"
1696                                 || name == "file" //FIXME: should be removed.
1697                                 || name == "prefs"
1698                                 || name == "texinfo"
1699                                 || name == "progress"
1700                                 || name == "compare";
1701                 else if (name == "print")
1702                         enable = doc_buffer->isExportable("dvi")
1703                                 && lyxrc.print_command != "none";
1704                 else if (name == "character" || name == "symbols") {
1705                         if (!buf || buf->isReadonly())
1706                                 enable = false;
1707                         else {
1708                                 Cursor const & cur = currentBufferView()->cursor();
1709                                 enable = !(cur.inTexted() && cur.paragraph().isPassThru());
1710                         }
1711                 }
1712                 else if (name == "latexlog")
1713                         enable = FileName(doc_buffer->logName()).isReadableFile();
1714                 else if (name == "spellchecker")
1715                         enable = theSpellChecker() && !doc_buffer->isReadonly();
1716                 else if (name == "vclog")
1717                         enable = doc_buffer->lyxvc().inUse();
1718                 break;
1719         }
1720
1721         case LFUN_DIALOG_UPDATE: {
1722                 string const name = cmd.getArg(0);
1723                 if (!buf)
1724                         enable = name == "prefs";
1725                 break;
1726         }
1727
1728         case LFUN_COMMAND_EXECUTE:
1729         case LFUN_MESSAGE:
1730         case LFUN_MENU_OPEN:
1731                 // Nothing to check.
1732                 break;
1733
1734         case LFUN_COMPLETION_INLINE:
1735                 if (!d.current_work_area_
1736                         || !d.current_work_area_->completer().inlinePossible(
1737                         currentBufferView()->cursor()))
1738                         enable = false;
1739                 break;
1740
1741         case LFUN_COMPLETION_POPUP:
1742                 if (!d.current_work_area_
1743                         || !d.current_work_area_->completer().popupPossible(
1744                         currentBufferView()->cursor()))
1745                         enable = false;
1746                 break;
1747
1748         case LFUN_COMPLETION_COMPLETE:
1749                 if (!d.current_work_area_
1750                         || !d.current_work_area_->completer().inlinePossible(
1751                         currentBufferView()->cursor()))
1752                         enable = false;
1753                 break;
1754
1755         case LFUN_COMPLETION_ACCEPT:
1756                 if (!d.current_work_area_
1757                         || (!d.current_work_area_->completer().popupVisible()
1758                         && !d.current_work_area_->completer().inlineVisible()
1759                         && !d.current_work_area_->completer().completionAvailable()))
1760                         enable = false;
1761                 break;
1762
1763         case LFUN_COMPLETION_CANCEL:
1764                 if (!d.current_work_area_
1765                         || (!d.current_work_area_->completer().popupVisible()
1766                         && !d.current_work_area_->completer().inlineVisible()))
1767                         enable = false;
1768                 break;
1769
1770         case LFUN_BUFFER_ZOOM_OUT:
1771                 enable = doc_buffer && lyxrc.zoom > 10;
1772                 break;
1773
1774         case LFUN_BUFFER_ZOOM_IN:
1775                 enable = doc_buffer;
1776                 break;
1777
1778         case LFUN_BUFFER_NEXT:
1779         case LFUN_BUFFER_PREVIOUS:
1780                 // FIXME: should we check is there is an previous or next buffer?
1781                 break;
1782         case LFUN_BUFFER_SWITCH:
1783                 // toggle on the current buffer, but do not toggle off
1784                 // the other ones (is that a good idea?)
1785                 if (doc_buffer
1786                         && to_utf8(cmd.argument()) == doc_buffer->absFileName())
1787                         flag.setOnOff(true);
1788                 break;
1789
1790         case LFUN_VC_REGISTER:
1791                 enable = doc_buffer && !doc_buffer->lyxvc().inUse();
1792                 break;
1793         case LFUN_VC_CHECK_IN:
1794                 enable = doc_buffer && doc_buffer->lyxvc().checkInEnabled();
1795                 break;
1796         case LFUN_VC_CHECK_OUT:
1797                 enable = doc_buffer && doc_buffer->lyxvc().checkOutEnabled();
1798                 break;
1799         case LFUN_VC_LOCKING_TOGGLE:
1800                 enable = doc_buffer && !doc_buffer->isReadonly()
1801                         && doc_buffer->lyxvc().lockingToggleEnabled();
1802                 flag.setOnOff(enable && doc_buffer->lyxvc().locking());
1803                 break;
1804         case LFUN_VC_REVERT:
1805                 enable = doc_buffer && doc_buffer->lyxvc().inUse() && !doc_buffer->isReadonly();
1806                 break;
1807         case LFUN_VC_UNDO_LAST:
1808                 enable = doc_buffer && doc_buffer->lyxvc().undoLastEnabled();
1809                 break;
1810         case LFUN_VC_REPO_UPDATE:
1811                 enable = doc_buffer && doc_buffer->lyxvc().repoUpdateEnabled();
1812                 break;
1813         case LFUN_VC_COMMAND: {
1814                 if (cmd.argument().empty())
1815                         enable = false;
1816                 if (!doc_buffer && contains(cmd.getArg(0), 'D'))
1817                         enable = false;
1818                 break;
1819         }
1820         case LFUN_VC_COMPARE:
1821                 enable = doc_buffer && doc_buffer->lyxvc().prepareFileRevisionEnabled();
1822                 break;
1823
1824         case LFUN_SERVER_GOTO_FILE_ROW:
1825                 break;
1826         case LFUN_FORWARD_SEARCH:
1827                 enable = !(lyxrc.forward_search_dvi.empty() && lyxrc.forward_search_pdf.empty());
1828                 break;
1829
1830         default:
1831                 return false;
1832         }
1833
1834         if (!enable)
1835                 flag.setEnabled(false);
1836
1837         return true;
1838 }
1839
1840
1841 static FileName selectTemplateFile()
1842 {
1843         FileDialog dlg(qt_("Select template file"));
1844         dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1845         dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
1846
1847         FileDialog::Result result = dlg.open(toqstr(lyxrc.template_path),
1848                                  QStringList(qt_("LyX Documents (*.lyx)")));
1849
1850         if (result.first == FileDialog::Later)
1851                 return FileName();
1852         if (result.second.isEmpty())
1853                 return FileName();
1854         return FileName(fromqstr(result.second));
1855 }
1856
1857
1858 Buffer * GuiView::loadDocument(FileName const & filename, bool tolastfiles)
1859 {
1860         setBusy(true);
1861
1862         Buffer * newBuffer = 0;
1863         try {
1864                 newBuffer = checkAndLoadLyXFile(filename);
1865         } catch (ExceptionMessage const & e) {
1866                 setBusy(false);
1867                 throw(e);
1868         }
1869         setBusy(false);
1870
1871         if (!newBuffer) {
1872                 message(_("Document not loaded."));
1873                 return 0;
1874         }
1875
1876         newBuffer->errors("Parse");
1877         setBuffer(newBuffer);
1878
1879         if (tolastfiles)
1880                 theSession().lastFiles().add(filename);
1881
1882         return newBuffer;
1883 }
1884
1885
1886 void GuiView::openDocument(string const & fname)
1887 {
1888         string initpath = lyxrc.document_path;
1889
1890         if (documentBufferView()) {
1891                 string const trypath = documentBufferView()->buffer().filePath();
1892                 // If directory is writeable, use this as default.
1893                 if (FileName(trypath).isDirWritable())
1894                         initpath = trypath;
1895         }
1896
1897         string filename;
1898
1899         if (fname.empty()) {
1900                 FileDialog dlg(qt_("Select document to open"), LFUN_FILE_OPEN);
1901                 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1902                 dlg.setButton2(qt_("Examples|#E#e"),
1903                                 toqstr(addPath(package().system_support().absFileName(), "examples")));
1904
1905                 QStringList filter(qt_("LyX Documents (*.lyx)"));
1906                 filter << qt_("LyX-1.3.x Documents (*.lyx13)")
1907                         << qt_("LyX-1.4.x Documents (*.lyx14)")
1908                         << qt_("LyX-1.5.x Documents (*.lyx15)")
1909                         << qt_("LyX-1.6.x Documents (*.lyx16)");
1910                 FileDialog::Result result =
1911                         dlg.open(toqstr(initpath), filter);
1912
1913                 if (result.first == FileDialog::Later)
1914                         return;
1915
1916                 filename = fromqstr(result.second);
1917
1918                 // check selected filename
1919                 if (filename.empty()) {
1920                         message(_("Canceled."));
1921                         return;
1922                 }
1923         } else
1924                 filename = fname;
1925
1926         // get absolute path of file and add ".lyx" to the filename if
1927         // necessary.
1928         FileName const fullname =
1929                         fileSearch(string(), filename, "lyx", support::may_not_exist);
1930         if (!fullname.empty())
1931                 filename = fullname.absFileName();
1932
1933         if (!fullname.onlyPath().isDirectory()) {
1934                 Alert::warning(_("Invalid filename"),
1935                                 bformat(_("The directory in the given path\n%1$s\ndoes not exist."),
1936                                 from_utf8(fullname.absFileName())));
1937                 return;
1938         }
1939
1940         // if the file doesn't exist and isn't already open (bug 6645),
1941         // let the user create one
1942         if (!fullname.exists() && !theBufferList().exists(fullname)) {
1943                 // the user specifically chose this name. Believe him.
1944                 Buffer * const b = newFile(filename, string(), true);
1945                 if (b)
1946                         setBuffer(b);
1947                 return;
1948         }
1949
1950         docstring const disp_fn = makeDisplayPath(filename);
1951         message(bformat(_("Opening document %1$s..."), disp_fn));
1952
1953         docstring str2;
1954         Buffer * buf = loadDocument(fullname);
1955         if (buf) {
1956                 str2 = bformat(_("Document %1$s opened."), disp_fn);
1957                 if (buf->lyxvc().inUse())
1958                         str2 += " " + from_utf8(buf->lyxvc().versionString()) +
1959                                 " " + _("Version control detected.");
1960         } else {
1961                 str2 = bformat(_("Could not open document %1$s"), disp_fn);
1962         }
1963         message(str2);
1964 }
1965
1966 // FIXME: clean that
1967 static bool import(GuiView * lv, FileName const & filename,
1968         string const & format, ErrorList & errorList)
1969 {
1970         FileName const lyxfile(support::changeExtension(filename.absFileName(), ".lyx"));
1971
1972         string loader_format;
1973         vector<string> loaders = theConverters().loaders();
1974         if (find(loaders.begin(), loaders.end(), format) == loaders.end()) {
1975                 for (vector<string>::const_iterator it = loaders.begin();
1976                          it != loaders.end(); ++it) {
1977                         if (!theConverters().isReachable(format, *it))
1978                                 continue;
1979
1980                         string const tofile =
1981                                 support::changeExtension(filename.absFileName(),
1982                                 formats.extension(*it));
1983                         if (!theConverters().convert(0, filename, FileName(tofile),
1984                                 filename, format, *it, errorList))
1985                                 return false;
1986                         loader_format = *it;
1987                         break;
1988                 }
1989                 if (loader_format.empty()) {
1990                         frontend::Alert::error(_("Couldn't import file"),
1991                                          bformat(_("No information for importing the format %1$s."),
1992                                          formats.prettyName(format)));
1993                         return false;
1994                 }
1995         } else
1996                 loader_format = format;
1997
1998         if (loader_format == "lyx") {
1999                 Buffer * buf = lv->loadDocument(lyxfile);
2000                 if (!buf)
2001                         return false;
2002         } else {
2003                 Buffer * const b = newFile(lyxfile.absFileName(), string(), true);
2004                 if (!b)
2005                         return false;
2006                 lv->setBuffer(b);
2007                 bool as_paragraphs = loader_format == "textparagraph";
2008                 string filename2 = (loader_format == format) ? filename.absFileName()
2009                         : support::changeExtension(filename.absFileName(),
2010                                           formats.extension(loader_format));
2011                 lv->currentBufferView()->insertPlaintextFile(FileName(filename2),
2012                         as_paragraphs);
2013                 guiApp->setCurrentView(lv);
2014                 lyx::dispatch(FuncRequest(LFUN_MARK_OFF));
2015         }
2016
2017         return true;
2018 }
2019
2020
2021 void GuiView::importDocument(string const & argument)
2022 {
2023         string format;
2024         string filename = split(argument, format, ' ');
2025
2026         LYXERR(Debug::INFO, format << " file: " << filename);
2027
2028         // need user interaction
2029         if (filename.empty()) {
2030                 string initpath = lyxrc.document_path;
2031                 if (documentBufferView()) {
2032                         string const trypath = documentBufferView()->buffer().filePath();
2033                         // If directory is writeable, use this as default.
2034                         if (FileName(trypath).isDirWritable())
2035                                 initpath = trypath;
2036                 }
2037
2038                 docstring const text = bformat(_("Select %1$s file to import"),
2039                         formats.prettyName(format));
2040
2041                 FileDialog dlg(toqstr(text), LFUN_BUFFER_IMPORT);
2042                 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2043                 dlg.setButton2(qt_("Examples|#E#e"),
2044                         toqstr(addPath(package().system_support().absFileName(), "examples")));
2045
2046                 docstring filter = formats.prettyName(format);
2047                 filter += " (*.";
2048                 // FIXME UNICODE
2049                 filter += from_utf8(formats.extension(format));
2050                 filter += ')';
2051
2052                 FileDialog::Result result =
2053                         dlg.open(toqstr(initpath), fileFilters(toqstr(filter)));
2054
2055                 if (result.first == FileDialog::Later)
2056                         return;
2057
2058                 filename = fromqstr(result.second);
2059
2060                 // check selected filename
2061                 if (filename.empty())
2062                         message(_("Canceled."));
2063         }
2064
2065         if (filename.empty())
2066                 return;
2067
2068         // get absolute path of file
2069         FileName const fullname(support::makeAbsPath(filename));
2070
2071         FileName const lyxfile(support::changeExtension(fullname.absFileName(), ".lyx"));
2072
2073         // Check if the document already is open
2074         Buffer * buf = theBufferList().getBuffer(lyxfile);
2075         if (buf) {
2076                 setBuffer(buf);
2077                 if (!closeBuffer()) {
2078                         message(_("Canceled."));
2079                         return;
2080                 }
2081         }
2082
2083         docstring const displaypath = makeDisplayPath(lyxfile.absFileName(), 30);
2084
2085         // if the file exists already, and we didn't do
2086         // -i lyx thefile.lyx, warn
2087         if (lyxfile.exists() && fullname != lyxfile) {
2088
2089                 docstring text = bformat(_("The document %1$s already exists.\n\n"
2090                         "Do you want to overwrite that document?"), displaypath);
2091                 int const ret = Alert::prompt(_("Overwrite document?"),
2092                         text, 0, 1, _("&Overwrite"), _("&Cancel"));
2093
2094                 if (ret == 1) {
2095                         message(_("Canceled."));
2096                         return;
2097                 }
2098         }
2099
2100         message(bformat(_("Importing %1$s..."), displaypath));
2101         ErrorList errorList;
2102         if (import(this, fullname, format, errorList))
2103                 message(_("imported."));
2104         else
2105                 message(_("file not imported!"));
2106
2107         // FIXME (Abdel 12/08/06): Is there a need to display the error list here?
2108 }
2109
2110
2111 void GuiView::newDocument(string const & filename, bool from_template)
2112 {
2113         FileName initpath(lyxrc.document_path);
2114         if (documentBufferView()) {
2115                 FileName const trypath(documentBufferView()->buffer().filePath());
2116                 // If directory is writeable, use this as default.
2117                 if (trypath.isDirWritable())
2118                         initpath = trypath;
2119         }
2120
2121         string templatefile;
2122         if (from_template) {
2123                 templatefile = selectTemplateFile().absFileName();
2124                 if (templatefile.empty())
2125                         return;
2126         }
2127
2128         Buffer * b;
2129         if (filename.empty())
2130                 b = newUnnamedFile(initpath, to_utf8(_("newfile")), templatefile);
2131         else
2132                 b = newFile(filename, templatefile, true);
2133
2134         if (b)
2135                 setBuffer(b);
2136
2137         // If no new document could be created, it is unsure
2138         // whether there is a valid BufferView.
2139         if (currentBufferView())
2140                 // Ensure the cursor is correctly positioned on screen.
2141                 currentBufferView()->showCursor();
2142 }
2143
2144
2145 void GuiView::insertLyXFile(docstring const & fname)
2146 {
2147         BufferView * bv = documentBufferView();
2148         if (!bv)
2149                 return;
2150
2151         // FIXME UNICODE
2152         FileName filename(to_utf8(fname));
2153         if (filename.empty()) {
2154                 // Launch a file browser
2155                 // FIXME UNICODE
2156                 string initpath = lyxrc.document_path;
2157                 string const trypath = bv->buffer().filePath();
2158                 // If directory is writeable, use this as default.
2159                 if (FileName(trypath).isDirWritable())
2160                         initpath = trypath;
2161
2162                 // FIXME UNICODE
2163                 FileDialog dlg(qt_("Select LyX document to insert"), LFUN_FILE_INSERT);
2164                 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2165                 dlg.setButton2(qt_("Examples|#E#e"),
2166                         toqstr(addPath(package().system_support().absFileName(),
2167                         "examples")));
2168
2169                 FileDialog::Result result = dlg.open(toqstr(initpath),
2170                                          QStringList(qt_("LyX Documents (*.lyx)")));
2171
2172                 if (result.first == FileDialog::Later)
2173                         return;
2174
2175                 // FIXME UNICODE
2176                 filename.set(fromqstr(result.second));
2177
2178                 // check selected filename
2179                 if (filename.empty()) {
2180                         // emit message signal.
2181                         message(_("Canceled."));
2182                         return;
2183                 }
2184         }
2185
2186         bv->insertLyXFile(filename);
2187         bv->buffer().errors("Parse");
2188 }
2189
2190
2191 void GuiView::insertPlaintextFile(docstring const & fname,
2192         bool asParagraph)
2193 {
2194         BufferView * bv = documentBufferView();
2195         if (!bv)
2196                 return;
2197
2198         if (!fname.empty() && !FileName::isAbsolute(to_utf8(fname))) {
2199                 message(_("Absolute filename expected."));
2200                 return;
2201         }
2202
2203         // FIXME UNICODE
2204         FileName filename(to_utf8(fname));
2205
2206         if (!filename.empty()) {
2207                 bv->insertPlaintextFile(filename, asParagraph);
2208                 return;
2209         }
2210
2211         FileDialog dlg(qt_("Select file to insert"), (asParagraph ?
2212                 LFUN_FILE_INSERT_PLAINTEXT_PARA : LFUN_FILE_INSERT_PLAINTEXT));
2213
2214         FileDialog::Result result = dlg.open(toqstr(bv->buffer().filePath()),
2215                 QStringList(qt_("All Files (*)")));
2216
2217         if (result.first == FileDialog::Later)
2218                 return;
2219
2220         // FIXME UNICODE
2221         filename.set(fromqstr(result.second));
2222
2223         // check selected filename
2224         if (filename.empty()) {
2225                 // emit message signal.
2226                 message(_("Canceled."));
2227                 return;
2228         }
2229
2230         bv->insertPlaintextFile(filename, asParagraph);
2231 }
2232
2233
2234 bool GuiView::renameBuffer(Buffer & b, docstring const & newname)
2235 {
2236         FileName fname = b.fileName();
2237         FileName const oldname = fname;
2238
2239         if (!newname.empty()) {
2240                 // FIXME UNICODE
2241                 fname = support::makeAbsPath(to_utf8(newname), oldname.onlyPath().absFileName());
2242         } else {
2243                 // Switch to this Buffer.
2244                 setBuffer(&b);
2245
2246                 // No argument? Ask user through dialog.
2247                 // FIXME UNICODE
2248                 FileDialog dlg(qt_("Choose a filename to save document as"),
2249                                    LFUN_BUFFER_WRITE_AS);
2250                 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2251                 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
2252
2253                 if (!isLyXFileName(fname.absFileName()))
2254                         fname.changeExtension(".lyx");
2255
2256                 FileDialog::Result result =
2257                         dlg.save(toqstr(fname.onlyPath().absFileName()),
2258                                    QStringList(qt_("LyX Documents (*.lyx)")),
2259                                          toqstr(fname.onlyFileName()));
2260
2261                 if (result.first == FileDialog::Later)
2262                         return false;
2263
2264                 fname.set(fromqstr(result.second));
2265
2266                 if (fname.empty())
2267                         return false;
2268
2269                 if (!isLyXFileName(fname.absFileName()))
2270                         fname.changeExtension(".lyx");
2271         }
2272
2273         // fname is now the new Buffer location.
2274         if (FileName(fname).exists()) {
2275                 docstring const file = makeDisplayPath(fname.absFileName(), 30);
2276                 docstring text = bformat(_("The document %1$s already "
2277                                            "exists.\n\nDo you want to "
2278                                            "overwrite that document?"),
2279                                          file);
2280                 int const ret = Alert::prompt(_("Overwrite document?"),
2281                         text, 0, 2, _("&Overwrite"), _("&Rename"), _("&Cancel"));
2282                 switch (ret) {
2283                 case 0: break;
2284                 case 1: return renameBuffer(b, docstring());
2285                 case 2: return false;
2286                 }
2287         }
2288
2289         return saveBuffer(b, fname);
2290 }
2291
2292
2293 bool GuiView::saveBuffer(Buffer & b) {
2294         return saveBuffer(b, FileName());
2295 }
2296
2297
2298 bool GuiView::saveBuffer(Buffer & b, FileName const & fn)
2299 {
2300         if (workArea(b) && workArea(b)->inDialogMode())
2301                 return true;
2302
2303         if (fn.empty() && b.isUnnamed())
2304                         return renameBuffer(b, docstring());
2305
2306         bool success;
2307         if (fn.empty())
2308                 success = b.save();
2309         else
2310                 success = b.saveAs(fn);
2311         
2312         if (success) {
2313                 theSession().lastFiles().add(b.fileName());
2314                 return true;
2315         }
2316
2317         // Switch to this Buffer.
2318         setBuffer(&b);
2319
2320         // FIXME: we don't tell the user *WHY* the save failed !!
2321         docstring const file = makeDisplayPath(b.absFileName(), 30);
2322         docstring text = bformat(_("The document %1$s could not be saved.\n\n"
2323                                    "Do you want to rename the document and "
2324                                    "try again?"), file);
2325         int const ret = Alert::prompt(_("Rename and save?"),
2326                 text, 0, 2, _("&Rename"), _("&Retry"), _("&Cancel"));
2327         switch (ret) {
2328         case 0:
2329                 if (!renameBuffer(b, docstring()))
2330                         return false;
2331                 break;
2332         case 1:
2333                 break;
2334         case 2:
2335                 return false;
2336         }
2337
2338         return saveBuffer(b);
2339 }
2340
2341
2342 bool GuiView::hideWorkArea(GuiWorkArea * wa)
2343 {
2344         return closeWorkArea(wa, false);
2345 }
2346
2347
2348 bool GuiView::closeWorkArea(GuiWorkArea * wa)
2349 {
2350         Buffer & buf = wa->bufferView().buffer();
2351         return closeWorkArea(wa, !buf.parent());
2352 }
2353
2354
2355 bool GuiView::closeBuffer()
2356 {
2357         GuiWorkArea * wa = currentMainWorkArea();
2358         setCurrentWorkArea(wa);
2359         Buffer & buf = wa->bufferView().buffer();
2360         return wa && closeWorkArea(wa, !buf.parent());
2361 }
2362
2363
2364 void GuiView::writeSession() const {
2365         GuiWorkArea const * active_wa = currentMainWorkArea();
2366         for (int i = 0; i < d.splitter_->count(); ++i) {
2367                 TabWorkArea * twa = d.tabWorkArea(i);
2368                 for (int j = 0; j < twa->count(); ++j) {
2369                         GuiWorkArea * wa = static_cast<GuiWorkArea *>(twa->widget(j));
2370                         Buffer & buf = wa->bufferView().buffer();
2371                         theSession().lastOpened().add(buf.fileName(), wa == active_wa);
2372                 }
2373         }
2374 }
2375
2376
2377 bool GuiView::closeBufferAll()
2378 {
2379         // Close the workareas in all other views
2380         QList<int> const ids = guiApp->viewIds();
2381         for (int i = 0; i != ids.size(); ++i) {
2382                 if (id_ != ids[i] && !guiApp->view(ids[i]).closeWorkAreaAll())
2383                         return false;
2384         }
2385
2386         // Close our own workareas
2387         if (!closeWorkAreaAll())
2388                 return false;
2389
2390         // Now close the hidden buffers. We prevent hidden buffers from being
2391         // dirty, so we can just close them.
2392         theBufferList().closeAll();
2393         return true;
2394 }
2395
2396
2397 bool GuiView::closeWorkAreaAll()
2398 {
2399         setCurrentWorkArea(currentMainWorkArea());
2400
2401         // We might be in a situation that there is still a tabWorkArea, but
2402         // there are no tabs anymore. This can happen when we get here after a
2403         // TabWorkArea::lastWorkAreaRemoved() signal. Therefore we count how
2404         // many TabWorkArea's have no documents anymore.
2405         int empty_twa = 0;
2406
2407         // We have to call count() each time, because it can happen that
2408         // more than one splitter will disappear in one iteration (bug 5998).
2409         for (; d.splitter_->count() > empty_twa; ) {
2410                 TabWorkArea * twa = d.tabWorkArea(empty_twa);
2411
2412                 if (twa->count() == 0)
2413                         ++empty_twa;
2414                 else {
2415                         setCurrentWorkArea(twa->currentWorkArea());
2416                         if (!closeTabWorkArea(twa))
2417                                 return false;
2418                 }
2419         }
2420         return true;
2421 }
2422
2423
2424 bool GuiView::closeWorkArea(GuiWorkArea * wa, bool close_buffer)
2425 {
2426         if (!wa)
2427                 return false;
2428
2429         Buffer & buf = wa->bufferView().buffer();
2430
2431         if (close_buffer && GuiViewPrivate::busyBuffers.contains(&buf)) {
2432                 Alert::warning(_("Close document"), 
2433                         _("Document could not be closed because it is being processed by LyX."));
2434                 return false;
2435         }
2436
2437         if (close_buffer)
2438                 return closeBuffer(buf);
2439         else {
2440                 if (!inMultiTabs(wa))
2441                         if (!saveBufferIfNeeded(buf, true))
2442                                 return false;
2443                 removeWorkArea(wa);
2444                 return true;
2445         }
2446 }
2447
2448
2449 bool GuiView::closeBuffer(Buffer & buf)
2450 {
2451         // If we are in a close_event all children will be closed in some time,
2452         // so no need to do it here. This will ensure that the children end up
2453         // in the session file in the correct order. If we close the master
2454         // buffer, we can close or release the child buffers here too.
2455         bool success = true;
2456         if (!closing_) {
2457                 ListOfBuffers clist = buf.getChildren();
2458                 ListOfBuffers::const_iterator it = clist.begin();
2459                 ListOfBuffers::const_iterator const bend = clist.end();
2460                 for (; it != bend; ++it) {
2461                         // If a child is dirty, do not close
2462                         // without user intervention
2463                         //FIXME: should we look in other tabworkareas?
2464                         Buffer * child_buf = *it;
2465                         GuiWorkArea * child_wa = workArea(*child_buf);
2466                         if (child_wa) {
2467                                 if (!closeWorkArea(child_wa, true)) {
2468                                         success = false;
2469                                         break;
2470                                 }
2471                         } else
2472                                 theBufferList().releaseChild(&buf, child_buf);
2473                 }
2474         }
2475         if (success) {
2476                 // goto bookmark to update bookmark pit.
2477                 //FIXME: we should update only the bookmarks related to this buffer!
2478                 LYXERR(Debug::DEBUG, "GuiView::closeBuffer()");
2479                 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
2480                         guiApp->gotoBookmark(i+1, false, false);
2481
2482                 if (saveBufferIfNeeded(buf, false)) {
2483                         buf.removeAutosaveFile();
2484                         theBufferList().release(&buf);
2485                         return true;
2486                 }
2487         }
2488         // open all children again to avoid a crash because of dangling
2489         // pointers (bug 6603)
2490         buf.updateBuffer();
2491         return false;
2492 }
2493
2494
2495 bool GuiView::closeTabWorkArea(TabWorkArea * twa)
2496 {
2497         while (twa == d.currentTabWorkArea()) {
2498                 twa->setCurrentIndex(twa->count()-1);
2499
2500                 GuiWorkArea * wa = twa->currentWorkArea();
2501                 Buffer & b = wa->bufferView().buffer();
2502
2503                 // We only want to close the buffer if the same buffer is not visible
2504                 // in another view, and if this is not a child and if we are closing
2505                 // a view (not a tabgroup).
2506                 bool const close_buffer =
2507                         !inOtherView(b) && !b.parent() && closing_;
2508
2509                 if (!closeWorkArea(wa, close_buffer))
2510                         return false;
2511         }
2512         return true;
2513 }
2514
2515
2516 bool GuiView::saveBufferIfNeeded(Buffer & buf, bool hiding)
2517 {
2518         if (buf.isClean() || buf.paragraphs().empty())
2519                 return true;
2520
2521         // Switch to this Buffer.
2522         setBuffer(&buf);
2523
2524         docstring file;
2525         // FIXME: Unicode?
2526         if (buf.isUnnamed())
2527                 file = from_utf8(buf.fileName().onlyFileName());
2528         else
2529                 file = buf.fileName().displayName(30);
2530
2531         // Bring this window to top before asking questions.
2532         raise();
2533         activateWindow();
2534
2535         int ret;
2536         if (hiding && buf.isUnnamed()) {
2537                 docstring const text = bformat(_("The document %1$s has not been "
2538                                                  "saved yet.\n\nDo you want to save "
2539                                                  "the document?"), file);
2540                 ret = Alert::prompt(_("Save new document?"),
2541                         text, 0, 1, _("&Save"), _("&Cancel"));
2542                 if (ret == 1)
2543                         ++ret;
2544         } else {
2545                 docstring const text = bformat(_("The document %1$s has unsaved changes."
2546                         "\n\nDo you want to save the document or discard the changes?"), file);
2547                 ret = Alert::prompt(_("Save changed document?"),
2548                         text, 0, 2, _("&Save"), _("&Discard"), _("&Cancel"));
2549         }
2550
2551         switch (ret) {
2552         case 0:
2553                 if (!saveBuffer(buf))
2554                         return false;
2555                 break;
2556         case 1:
2557                 // If we crash after this we could have no autosave file
2558                 // but I guess this is really improbable (Jug).
2559                 // Sometimes improbable things happen:
2560                 // - see bug http://www.lyx.org/trac/ticket/6587 (ps)
2561                 // buf.removeAutosaveFile();
2562                 if (hiding)
2563                         // revert all changes
2564                         reloadBuffer(buf);
2565                 buf.markClean();
2566                 break;
2567         case 2:
2568                 return false;
2569         }
2570         return true;
2571 }
2572
2573
2574 bool GuiView::inMultiTabs(GuiWorkArea * wa)
2575 {
2576         Buffer & buf = wa->bufferView().buffer();
2577
2578         for (int i = 0; i != d.splitter_->count(); ++i) {
2579                 GuiWorkArea * wa_ = d.tabWorkArea(i)->workArea(buf);
2580                 if (wa_ && wa_ != wa)
2581                         return true;
2582         }
2583         return inOtherView(buf);
2584 }
2585
2586
2587 bool GuiView::inOtherView(Buffer & buf)
2588 {
2589         QList<int> const ids = guiApp->viewIds();
2590
2591         for (int i = 0; i != ids.size(); ++i) {
2592                 if (id_ == ids[i])
2593                         continue;
2594
2595                 if (guiApp->view(ids[i]).workArea(buf))
2596                         return true;
2597         }
2598         return false;
2599 }
2600
2601
2602 void GuiView::gotoNextOrPreviousBuffer(NextOrPrevious np)
2603 {
2604         if (!documentBufferView())
2605                 return;
2606         
2607         if (TabWorkArea * twa = d.currentTabWorkArea()) {
2608                 Buffer * const curbuf = &documentBufferView()->buffer();
2609                 int nwa = twa->count();
2610                 for (int i = 0; i < nwa; ++i) {
2611                         if (&workArea(i)->bufferView().buffer() == curbuf) {
2612                                 int next_index;
2613                                 if (np == NEXTBUFFER)
2614                                         next_index = (i == nwa - 1 ? 0 : i + 1);
2615                                 else
2616                                         next_index = (i == 0 ? nwa - 1 : i - 1);
2617                                 setBuffer(&workArea(next_index)->bufferView().buffer());
2618                                 break;
2619                         }
2620                 }
2621         }
2622 }
2623
2624
2625 /// make sure the document is saved
2626 static bool ensureBufferClean(Buffer * buffer)
2627 {
2628         LASSERT(buffer, return false);
2629         if (buffer->isClean() && !buffer->isUnnamed())
2630                 return true;
2631
2632         docstring const file = buffer->fileName().displayName(30);
2633         docstring title;
2634         docstring text;
2635         if (!buffer->isUnnamed()) {
2636                 text = bformat(_("The document %1$s has unsaved "
2637                                                  "changes.\n\nDo you want to save "
2638                                                  "the document?"), file);
2639                 title = _("Save changed document?");
2640
2641         } else {
2642                 text = bformat(_("The document %1$s has not been "
2643                                                  "saved yet.\n\nDo you want to save "
2644                                                  "the document?"), file);
2645                 title = _("Save new document?");
2646         }
2647         int const ret = Alert::prompt(title, text, 0, 1, _("&Save"), _("&Cancel"));
2648
2649         if (ret == 0)
2650                 dispatch(FuncRequest(LFUN_BUFFER_WRITE));
2651
2652         return buffer->isClean() && !buffer->isUnnamed();
2653 }
2654
2655
2656 bool GuiView::reloadBuffer(Buffer & buf)
2657 {
2658         Buffer::ReadStatus status = buf.reload();
2659         return status == Buffer::ReadSuccess;
2660 }
2661
2662
2663 void GuiView::checkExternallyModifiedBuffers()
2664 {
2665         BufferList::iterator bit = theBufferList().begin();
2666         BufferList::iterator const bend = theBufferList().end();
2667         for (; bit != bend; ++bit) {
2668                 Buffer * buf = *bit;
2669                 if (buf->fileName().exists()
2670                         && buf->isExternallyModified(Buffer::checksum_method)) {
2671                         docstring text = bformat(_("Document \n%1$s\n has been externally modified."
2672                                         " Reload now? Any local changes will be lost."),
2673                                         from_utf8(buf->absFileName()));
2674                         int const ret = Alert::prompt(_("Reload externally changed document?"),
2675                                                 text, 0, 1, _("&Reload"), _("&Cancel"));
2676                         if (!ret)
2677                                 reloadBuffer(*buf);
2678                 }
2679         }
2680 }
2681
2682
2683 void GuiView::dispatchVC(FuncRequest const & cmd, DispatchResult & dr)
2684 {
2685         Buffer * buffer = documentBufferView()
2686                 ? &(documentBufferView()->buffer()) : 0;
2687
2688         switch (cmd.action()) {
2689         case LFUN_VC_REGISTER:
2690                 if (!buffer || !ensureBufferClean(buffer))
2691                         break;
2692                 if (!buffer->lyxvc().inUse()) {
2693                         if (buffer->lyxvc().registrer()) {
2694                                 reloadBuffer(*buffer);
2695                                 dr.suppressMessageUpdate();
2696                         }
2697                 }
2698                 break;
2699
2700         case LFUN_VC_CHECK_IN:
2701                 if (!buffer || !ensureBufferClean(buffer))
2702                         break;
2703                 if (buffer->lyxvc().inUse() && !buffer->isReadonly()) {
2704                         dr.setMessage(buffer->lyxvc().checkIn());
2705                         if (!dr.message().empty())
2706                                 reloadBuffer(*buffer);
2707                 }
2708                 break;
2709
2710         case LFUN_VC_CHECK_OUT:
2711                 if (!buffer || !ensureBufferClean(buffer))
2712                         break;
2713                 if (buffer->lyxvc().inUse()) {
2714                         dr.setMessage(buffer->lyxvc().checkOut());
2715                         reloadBuffer(*buffer);
2716                 }
2717                 break;
2718
2719         case LFUN_VC_LOCKING_TOGGLE:
2720                 LASSERT(buffer, return);
2721                 if (!ensureBufferClean(buffer) || buffer->isReadonly())
2722                         break;
2723                 if (buffer->lyxvc().inUse()) {
2724                         string res = buffer->lyxvc().lockingToggle();
2725                         if (res.empty()) {
2726                                 frontend::Alert::error(_("Revision control error."),
2727                                 _("Error when setting the locking property."));
2728                         } else {
2729                                 dr.setMessage(res);
2730                                 reloadBuffer(*buffer);
2731                         }
2732                 }
2733                 break;
2734
2735         case LFUN_VC_REVERT:
2736                 LASSERT(buffer, return);
2737                 if (buffer->lyxvc().revert()) {
2738                         reloadBuffer(*buffer);
2739                         dr.suppressMessageUpdate();
2740                 }
2741                 break;
2742
2743         case LFUN_VC_UNDO_LAST:
2744                 LASSERT(buffer, return);
2745                 buffer->lyxvc().undoLast();
2746                 reloadBuffer(*buffer);
2747                 dr.suppressMessageUpdate();
2748                 break;
2749
2750         case LFUN_VC_REPO_UPDATE:
2751                 LASSERT(buffer, return);
2752                 if (ensureBufferClean(buffer)) {
2753                         dr.setMessage(buffer->lyxvc().repoUpdate());
2754                         checkExternallyModifiedBuffers();
2755                 }
2756                 break;
2757
2758         case LFUN_VC_COMMAND: {
2759                 string flag = cmd.getArg(0);
2760                 if (buffer && contains(flag, 'R') && !ensureBufferClean(buffer))
2761                         break;
2762                 docstring message;
2763                 if (contains(flag, 'M')) {
2764                         if (!Alert::askForText(message, _("LyX VC: Log Message")))
2765                                 break;
2766                 }
2767                 string path = cmd.getArg(1);
2768                 if (contains(path, "$$p") && buffer)
2769                         path = subst(path, "$$p", buffer->filePath());
2770                 LYXERR(Debug::LYXVC, "Directory: " << path);
2771                 FileName pp(path);
2772                 if (!pp.isReadableDirectory()) {
2773                         lyxerr << _("Directory is not accessible.") << endl;
2774                         break;
2775                 }
2776                 support::PathChanger p(pp);
2777
2778                 string command = cmd.getArg(2);
2779                 if (command.empty())
2780                         break;
2781                 if (buffer) {
2782                         command = subst(command, "$$i", buffer->absFileName());
2783                         command = subst(command, "$$p", buffer->filePath());
2784                 }
2785                 command = subst(command, "$$m", to_utf8(message));
2786                 LYXERR(Debug::LYXVC, "Command: " << command);
2787                 Systemcall one;
2788                 one.startscript(Systemcall::Wait, command);
2789
2790                 if (!buffer)
2791                         break;
2792                 if (contains(flag, 'I'))
2793                         buffer->markDirty();
2794                 if (contains(flag, 'R'))
2795                         reloadBuffer(*buffer);
2796
2797                 break;
2798                 }
2799
2800         case LFUN_VC_COMPARE: {
2801
2802                 if (cmd.argument().empty()) {
2803                         lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "comparehistory"));
2804                         break;
2805                 }
2806
2807                 string rev1 = cmd.getArg(0);
2808                 string f1, f2;
2809
2810                 // f1
2811                 if (!buffer->lyxvc().prepareFileRevision(rev1, f1))
2812                         break;
2813
2814                 if (isStrInt(rev1) && convert<int>(rev1) <= 0) {
2815                         f2 = buffer->absFileName();
2816                 } else {
2817                         string rev2 = cmd.getArg(1);
2818                         if (rev2.empty())
2819                                 break;
2820                         // f2
2821                         if (!buffer->lyxvc().prepareFileRevision(rev2, f2))
2822                                 break;
2823                 }
2824
2825                 LYXERR(Debug::LYXVC, "Launching comparison for fetched revisions:\n" <<
2826                                         f1 << "\n"  << f2 << "\n" );
2827                 string par = "compare run " + quoteName(f1) + " " + quoteName(f2);
2828                 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, par));
2829                 break;
2830         }
2831
2832         default:
2833                 break;
2834         }
2835 }
2836
2837
2838 void GuiView::openChildDocument(string const & fname)
2839 {
2840         LASSERT(documentBufferView(), return);
2841         Buffer & buffer = documentBufferView()->buffer();
2842         FileName const filename = support::makeAbsPath(fname, buffer.filePath());
2843         documentBufferView()->saveBookmark(false);
2844         Buffer * child = 0;
2845         if (theBufferList().exists(filename)) {
2846                 child = theBufferList().getBuffer(filename);
2847                 setBuffer(child);
2848         } else {
2849                 message(bformat(_("Opening child document %1$s..."),
2850                         makeDisplayPath(filename.absFileName())));
2851                 child = loadDocument(filename, false);
2852         }
2853         // Set the parent name of the child document.
2854         // This makes insertion of citations and references in the child work,
2855         // when the target is in the parent or another child document.
2856         if (child)
2857                 child->setParent(&buffer);
2858 }
2859
2860
2861 bool GuiView::goToFileRow(string const & argument)
2862 {
2863         string file_name;
2864         int row;
2865         size_t i = argument.find_last_of(' ');
2866         if (i != string::npos) {
2867                 file_name = os::internal_path(trim(argument.substr(0, i)));
2868                 istringstream is(argument.substr(i + 1));
2869                 is >> row;
2870                 if (is.fail())
2871                         i = string::npos;
2872         }
2873         if (i == string::npos) {
2874                 LYXERR0("Wrong argument: " << argument);
2875                 return false;
2876         }
2877         Buffer * buf = 0;
2878         string const abstmp = package().temp_dir().absFileName();
2879         string const realtmp = package().temp_dir().realPath();
2880         // We have to use os::path_prefix_is() here, instead of
2881         // simply prefixIs(), because the file name comes from
2882         // an external application and may need case adjustment.
2883         if (os::path_prefix_is(file_name, abstmp, os::CASE_ADJUSTED)
2884                 || os::path_prefix_is(file_name, realtmp, os::CASE_ADJUSTED)) {
2885                 // Needed by inverse dvi search. If it is a file
2886                 // in tmpdir, call the apropriated function.
2887                 // If tmpdir is a symlink, we may have the real
2888                 // path passed back, so we correct for that.
2889                 if (!prefixIs(file_name, abstmp))
2890                         file_name = subst(file_name, realtmp, abstmp);
2891                 buf = theBufferList().getBufferFromTmp(file_name);
2892         } else {
2893                 // Must replace extension of the file to be .lyx
2894                 // and get full path
2895                 FileName const s = fileSearch(string(),
2896                                                   support::changeExtension(file_name, ".lyx"), "lyx");
2897                 // Either change buffer or load the file
2898                 if (theBufferList().exists(s))
2899                         buf = theBufferList().getBuffer(s);
2900                 else if (s.exists()) {
2901                         buf = loadDocument(s);
2902                         if (!buf)
2903                                 return false;
2904                 } else {
2905                         message(bformat(
2906                                         _("File does not exist: %1$s"),
2907                                         makeDisplayPath(file_name)));
2908                         return false;
2909                 }
2910         }
2911         setBuffer(buf);
2912         documentBufferView()->setCursorFromRow(row);
2913         return true;
2914 }
2915
2916
2917 #if (QT_VERSION >= 0x040400)
2918 template<class T>
2919 docstring GuiView::GuiViewPrivate::runAndDestroy(const T& func, Buffer const * orig, Buffer * buffer, string const & format, string const & msg)
2920 {
2921         bool const update_unincluded =
2922                                 buffer->params().maintain_unincluded_children
2923                                 && !buffer->params().getIncludedChildren().empty();
2924         bool const success = func(format, update_unincluded);
2925         delete buffer;
2926         busyBuffers.remove(orig);
2927         if (msg == "preview") {
2928                 return success
2929                         ? bformat(_("Successful preview of format: %1$s"), from_utf8(format))
2930                         : bformat(_("Error while previewing format: %1$s"), from_utf8(format));
2931         }
2932         return success
2933                 ? bformat(_("Successful export to format: %1$s"), from_utf8(format))
2934                 : bformat(_("Error while exporting format: %1$s"), from_utf8(format));
2935 }
2936
2937
2938 docstring GuiView::GuiViewPrivate::compileAndDestroy(Buffer const * orig, Buffer * buffer, string const & format)
2939 {
2940         bool (Buffer::* mem_func)(std::string const &, bool, bool) const = &Buffer::doExport;
2941         return runAndDestroy(bind(mem_func, buffer, _1, true, _2), orig, buffer, format, "export");
2942 }
2943
2944
2945 docstring GuiView::GuiViewPrivate::exportAndDestroy(Buffer const * orig, Buffer * buffer, string const & format)
2946 {
2947         bool (Buffer::* mem_func)(std::string const &, bool, bool) const = &Buffer::doExport;
2948         return runAndDestroy(bind(mem_func, buffer, _1, false, _2), orig, buffer, format, "export");
2949 }
2950
2951
2952 docstring GuiView::GuiViewPrivate::previewAndDestroy(Buffer const * orig, Buffer * buffer, string const & format)
2953 {
2954         bool(Buffer::* mem_func)(std::string const &, bool) const = &Buffer::preview;
2955         return runAndDestroy(bind(mem_func, buffer, _1, _2), orig, buffer, format, "preview");
2956 }
2957
2958 #else
2959
2960 // not used, but the linker needs them
2961
2962 docstring GuiView::GuiViewPrivate::compileAndDestroy(
2963                 Buffer const *, Buffer *, string const &)
2964 {
2965         return docstring();
2966 }
2967
2968
2969 docstring GuiView::GuiViewPrivate::exportAndDestroy(
2970                 Buffer const *, Buffer *, string const &)
2971 {
2972         return docstring();
2973 }
2974
2975
2976 docstring GuiView::GuiViewPrivate::previewAndDestroy(
2977                 Buffer const *, Buffer *, string const &)
2978 {
2979         return docstring();
2980 }
2981
2982 #endif
2983
2984
2985 bool GuiView::GuiViewPrivate::asyncBufferProcessing(
2986                            string const & argument,
2987                            Buffer const * used_buffer,
2988                            docstring const & msg,
2989                            docstring (*asyncFunc)(Buffer const *, Buffer *, string const &),
2990                            bool (Buffer::*syncFunc)(string const &, bool, bool) const,
2991                            bool (Buffer::*previewFunc)(string const &, bool) const)
2992 {
2993         if (!used_buffer)
2994                 return false;
2995
2996         string format = argument;
2997         if (format.empty())
2998                 format = used_buffer->getDefaultOutputFormat();
2999
3000 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
3001         if (!msg.empty()) {
3002                 progress_->clearMessages();
3003                 gv_->message(msg);
3004         }
3005         GuiViewPrivate::busyBuffers.insert(used_buffer);
3006         QFuture<docstring> f = QtConcurrent::run(
3007                                 asyncFunc,
3008                                 used_buffer,
3009                                 used_buffer->clone(),
3010                                 format);
3011         setPreviewFuture(f);
3012         last_export_format = used_buffer->bufferFormat();
3013         (void) syncFunc;
3014         (void) previewFunc;
3015         // We are asynchronous, so we don't know here anything about the success
3016         return true;
3017 #else
3018         if (syncFunc) {
3019                 // TODO check here if it breaks exporting with Qt < 4.4
3020                 bool const update_unincluded =
3021                                 used_buffer->params().maintain_unincluded_children &&
3022                                 !used_buffer->params().getIncludedChildren().empty();
3023                 return (used_buffer->*syncFunc)(format, true, update_unincluded);
3024         } else if (previewFunc) {
3025                 return (used_buffer->*previewFunc)(format, false);
3026         }
3027         (void) asyncFunc;
3028         return false;
3029 #endif
3030 }
3031
3032 void GuiView::dispatchToBufferView(FuncRequest const & cmd, DispatchResult & dr)
3033 {
3034         BufferView * bv = currentBufferView();
3035         LASSERT(bv, /**/);
3036
3037         // Let the current BufferView dispatch its own actions.
3038         bv->dispatch(cmd, dr);
3039         if (dr.dispatched())
3040                 return;
3041
3042         // Try with the document BufferView dispatch if any.
3043         BufferView * doc_bv = documentBufferView();
3044         if (doc_bv) {
3045                 doc_bv->dispatch(cmd, dr);
3046                 if (dr.dispatched())
3047                         return;
3048         }
3049
3050         // Then let the current Cursor dispatch its own actions.
3051         bv->cursor().dispatch(cmd);
3052
3053         // update completion. We do it here and not in
3054         // processKeySym to avoid another redraw just for a
3055         // changed inline completion
3056         if (cmd.origin() == FuncRequest::KEYBOARD) {
3057                 if (cmd.action() == LFUN_SELF_INSERT
3058                         || (cmd.action() == LFUN_ERT_INSERT && bv->cursor().inMathed()))
3059                         updateCompletion(bv->cursor(), true, true);
3060                 else if (cmd.action() == LFUN_CHAR_DELETE_BACKWARD)
3061                         updateCompletion(bv->cursor(), false, true);
3062                 else
3063                         updateCompletion(bv->cursor(), false, false);
3064         }
3065
3066         dr = bv->cursor().result();
3067 }
3068
3069
3070 void GuiView::dispatch(FuncRequest const & cmd, DispatchResult & dr)
3071 {
3072         BufferView * bv = currentBufferView();
3073         // By default we won't need any update.
3074         dr.screenUpdate(Update::None);
3075         // assume cmd will be dispatched
3076         dr.dispatched(true);
3077
3078         Buffer * doc_buffer = documentBufferView()
3079                 ? &(documentBufferView()->buffer()) : 0;
3080
3081         if (cmd.origin() == FuncRequest::TOC) {
3082                 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
3083                 // FIXME: do we need to pass a DispatchResult object here?
3084                 toc->doDispatch(bv->cursor(), cmd);
3085                 return;
3086         }
3087
3088         string const argument = to_utf8(cmd.argument());
3089
3090         switch(cmd.action()) {
3091                 case LFUN_BUFFER_CHILD_OPEN:
3092                         openChildDocument(to_utf8(cmd.argument()));
3093                         break;
3094
3095                 case LFUN_BUFFER_IMPORT:
3096                         importDocument(to_utf8(cmd.argument()));
3097                         break;
3098
3099                 case LFUN_BUFFER_EXPORT: {
3100                         if (!doc_buffer)
3101                                 break;
3102                         // GCC only sees strfwd.h when building merged
3103                         if (::lyx::operator==(cmd.argument(), "custom")) {
3104                                 dispatch(FuncRequest(LFUN_DIALOG_SHOW, "sendto"), dr);
3105                                 break;
3106                         }
3107 #if QT_VERSION < 0x040400
3108                         if (!doc_buffer->doExport(argument, false)) {
3109                                 dr.setError(true);
3110                                 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
3111                                         cmd.argument()));
3112                         }
3113 #else
3114                         /* TODO/Review: Is it a problem to also export the children?
3115                                         See the update_unincluded flag */
3116                         d.asyncBufferProcessing(argument,
3117                                                 doc_buffer,
3118                                                 _("Exporting ..."),
3119                                                 &GuiViewPrivate::exportAndDestroy,
3120                                                 &Buffer::doExport,
3121                                                 0);
3122                         // TODO Inform user about success
3123 #endif
3124                         break;
3125                 }
3126
3127                 case LFUN_BUFFER_UPDATE: {
3128                         d.asyncBufferProcessing(argument,
3129                                                 doc_buffer,
3130                                                 _("Exporting ..."),
3131                                                 &GuiViewPrivate::compileAndDestroy,
3132                                                 &Buffer::doExport,
3133                                                 0);
3134                         break;
3135                 }
3136                 case LFUN_BUFFER_VIEW: {
3137                         d.asyncBufferProcessing(argument,
3138                                                 doc_buffer,
3139                                                 _("Previewing ..."),
3140                                                 &GuiViewPrivate::previewAndDestroy,
3141                                                 0,
3142                                                 &Buffer::preview);
3143                         break;
3144                 }
3145                 case LFUN_MASTER_BUFFER_UPDATE: {
3146                         d.asyncBufferProcessing(argument,
3147                                                 (doc_buffer ? doc_buffer->masterBuffer() : 0),
3148                                                 docstring(),
3149                                                 &GuiViewPrivate::compileAndDestroy,
3150                                                 &Buffer::doExport,
3151                                                 0);
3152                         break;
3153                 }
3154                 case LFUN_MASTER_BUFFER_VIEW: {
3155                         d.asyncBufferProcessing(argument,
3156                                                 (doc_buffer ? doc_buffer->masterBuffer() : 0),
3157                                                 docstring(),
3158                                                 &GuiViewPrivate::previewAndDestroy,
3159                                                 0, &Buffer::preview);
3160                         break;
3161                 }
3162                 case LFUN_BUFFER_SWITCH: {
3163                         string const file_name = to_utf8(cmd.argument());
3164                         if (!FileName::isAbsolute(file_name)) {
3165                                 dr.setError(true);
3166                                 dr.setMessage(_("Absolute filename expected."));
3167                                 break;
3168                         }
3169
3170                         Buffer * buffer = theBufferList().getBuffer(FileName(file_name));
3171                         if (!buffer) {
3172                                 dr.setError(true);
3173                                 dr.setMessage(_("Document not loaded"));
3174                                 break;
3175                         }
3176
3177                         // Do we open or switch to the buffer in this view ?
3178                         if (workArea(*buffer)
3179                                   || lyxrc.open_buffers_in_tabs || !documentBufferView()) {
3180                                 setBuffer(buffer);
3181                                 break;
3182                         }
3183
3184                         // Look for the buffer in other views
3185                         QList<int> const ids = guiApp->viewIds();
3186                         int i = 0;
3187                         for (; i != ids.size(); ++i) {
3188                                 GuiView & gv = guiApp->view(ids[i]);
3189                                 if (gv.workArea(*buffer)) {
3190                                         gv.activateWindow();
3191                                         gv.setBuffer(buffer);
3192                                         break;
3193                                 }
3194                         }
3195
3196                         // If necessary, open a new window as a last resort
3197                         if (i == ids.size()) {
3198                                 lyx::dispatch(FuncRequest(LFUN_WINDOW_NEW));
3199                                 lyx::dispatch(cmd);
3200                         }
3201                         break;
3202                 }
3203
3204                 case LFUN_BUFFER_NEXT:
3205                         gotoNextOrPreviousBuffer(NEXTBUFFER);
3206                         break;
3207
3208                 case LFUN_BUFFER_PREVIOUS:
3209                         gotoNextOrPreviousBuffer(PREVBUFFER);
3210                         break;
3211
3212                 case LFUN_COMMAND_EXECUTE: {
3213                         bool const show_it = cmd.argument() != "off";
3214                         // FIXME: this is a hack, "minibuffer" should not be
3215                         // hardcoded.
3216                         if (GuiToolbar * t = toolbar("minibuffer")) {
3217                                 t->setVisible(show_it);
3218                                 if (show_it && t->commandBuffer())
3219                                         t->commandBuffer()->setFocus();
3220                         }
3221                         break;
3222                 }
3223                 case LFUN_DROP_LAYOUTS_CHOICE:
3224                         d.layout_->showPopup();
3225                         break;
3226
3227                 case LFUN_MENU_OPEN:
3228                         if (QMenu * menu = guiApp->menus().menu(toqstr(cmd.argument()), *this))
3229                                 menu->exec(QCursor::pos());
3230                         break;
3231
3232                 case LFUN_FILE_INSERT:
3233                         insertLyXFile(cmd.argument());
3234                         break;
3235
3236                 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
3237                         insertPlaintextFile(cmd.argument(), true);
3238                         break;
3239
3240                 case LFUN_FILE_INSERT_PLAINTEXT:
3241                         insertPlaintextFile(cmd.argument(), false);
3242                         break;
3243
3244                 case LFUN_BUFFER_RELOAD: {
3245                         LASSERT(doc_buffer, break);
3246
3247                         int ret = 0;
3248                         if (!doc_buffer->isClean()) {
3249                                 docstring const file =
3250                                         makeDisplayPath(doc_buffer->absFileName(), 20);
3251                                 docstring text = bformat(_("Any changes will be lost. "
3252                                         "Are you sure you want to revert to the saved version "
3253                                         "of the document %1$s?"), file);
3254                                 ret = Alert::prompt(_("Revert to saved document?"),
3255                                         text, 1, 1, _("&Revert"), _("&Cancel"));
3256                         }
3257
3258                         if (ret == 0) {
3259                                 doc_buffer->markClean();
3260                                 reloadBuffer(*doc_buffer);
3261                                 dr.forceBufferUpdate();
3262                         }
3263                         break;
3264                 }
3265
3266                 case LFUN_BUFFER_WRITE:
3267                         LASSERT(doc_buffer, break);
3268                         saveBuffer(*doc_buffer);
3269                         break;
3270
3271                 case LFUN_BUFFER_WRITE_AS:
3272                         LASSERT(doc_buffer, break);
3273                         renameBuffer(*doc_buffer, cmd.argument());
3274                         break;
3275
3276                 case LFUN_BUFFER_WRITE_ALL: {
3277                         Buffer * first = theBufferList().first();
3278                         if (!first)
3279                                 break;
3280                         message(_("Saving all documents..."));
3281                         // We cannot use a for loop as the buffer list cycles.
3282                         Buffer * b = first;
3283                         do {
3284                                 if (!b->isClean()) {
3285                                         saveBuffer(*b);
3286                                         LYXERR(Debug::ACTION, "Saved " << b->absFileName());
3287                                 }
3288                                 b = theBufferList().next(b);
3289                         } while (b != first);
3290                         dr.setMessage(_("All documents saved."));
3291                         break;
3292                 }
3293
3294                 case LFUN_BUFFER_CLOSE:
3295                         closeBuffer();
3296                         break;
3297
3298                 case LFUN_BUFFER_CLOSE_ALL:
3299                         closeBufferAll();
3300                         break;
3301
3302                 case LFUN_TOOLBAR_TOGGLE: {
3303                         string const name = cmd.getArg(0);
3304                         if (GuiToolbar * t = toolbar(name))
3305                                 t->toggle();
3306                         break;
3307                 }
3308
3309                 case LFUN_DIALOG_UPDATE: {
3310                         string const name = to_utf8(cmd.argument());
3311                         if (name == "prefs" || name == "document")
3312                                 updateDialog(name, string());
3313                         else if (name == "paragraph")
3314                                 lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
3315                         else if (currentBufferView()) {
3316                                 Inset * inset = currentBufferView()->editedInset(name);
3317                                 // Can only update a dialog connected to an existing inset
3318                                 if (inset) {
3319                                         // FIXME: get rid of this indirection; GuiView ask the inset
3320                                         // if he is kind enough to update itself...
3321                                         FuncRequest fr(LFUN_INSET_DIALOG_UPDATE, cmd.argument());
3322                                         //FIXME: pass DispatchResult here?
3323                                         inset->dispatch(currentBufferView()->cursor(), fr);
3324                                 }
3325                         }
3326                         break;
3327                 }
3328
3329                 case LFUN_DIALOG_TOGGLE: {
3330                         FuncCode const func_code = isDialogVisible(cmd.getArg(0))
3331                                 ? LFUN_DIALOG_HIDE : LFUN_DIALOG_SHOW;
3332                         dispatch(FuncRequest(func_code, cmd.argument()), dr);
3333                         break;
3334                 }
3335
3336                 case LFUN_DIALOG_DISCONNECT_INSET:
3337                         disconnectDialog(to_utf8(cmd.argument()));
3338                         break;
3339
3340                 case LFUN_DIALOG_HIDE: {
3341                         guiApp->hideDialogs(to_utf8(cmd.argument()), 0);
3342                         break;
3343                 }
3344
3345                 case LFUN_DIALOG_SHOW: {
3346                         string const name = cmd.getArg(0);
3347                         string data = trim(to_utf8(cmd.argument()).substr(name.size()));
3348
3349                         if (name == "character") {
3350                                 data = freefont2string();
3351                                 if (!data.empty())
3352                                         showDialog("character", data);
3353                         } else if (name == "latexlog") {
3354                                 Buffer::LogType type;
3355                                 string const logfile = doc_buffer->logName(&type);
3356                                 switch (type) {
3357                                 case Buffer::latexlog:
3358                                         data = "latex ";
3359                                         break;
3360                                 case Buffer::buildlog:
3361                                         data = "literate ";
3362                                         break;
3363                                 }
3364                                 data += Lexer::quoteString(logfile);
3365                                 showDialog("log", data);
3366                         } else if (name == "vclog") {
3367                                 string const data = "vc " +
3368                                         Lexer::quoteString(doc_buffer->lyxvc().getLogFile());
3369                                 showDialog("log", data);
3370                         } else if (name == "symbols") {
3371                                 data = bv->cursor().getEncoding()->name();
3372                                 if (!data.empty())
3373                                         showDialog("symbols", data);
3374                         // bug 5274
3375                         } else if (name == "prefs" && isFullScreen()) {
3376                                 lfunUiToggle("fullscreen");
3377                                 showDialog("prefs", data);
3378                         } else
3379                                 showDialog(name, data);
3380                         break;
3381                 }
3382
3383                 case LFUN_MESSAGE:
3384                         dr.setMessage(cmd.argument());
3385                         break;
3386
3387                 case LFUN_UI_TOGGLE: {
3388                         string arg = cmd.getArg(0);
3389                         if (!lfunUiToggle(arg)) {
3390                                 docstring const msg = "ui-toggle " + _("%1$s unknown command!");
3391                                 dr.setMessage(bformat(msg, from_utf8(arg)));
3392                         }
3393                         // Make sure the keyboard focus stays in the work area.
3394                         setFocus();
3395                         break;
3396                 }
3397
3398                 case LFUN_SPLIT_VIEW: {
3399                         LASSERT(doc_buffer, break);
3400                         string const orientation = cmd.getArg(0);
3401                         d.splitter_->setOrientation(orientation == "vertical"
3402                                 ? Qt::Vertical : Qt::Horizontal);
3403                         TabWorkArea * twa = addTabWorkArea();
3404                         GuiWorkArea * wa = twa->addWorkArea(*doc_buffer, *this);
3405                         setCurrentWorkArea(wa);
3406                         break;
3407                 }
3408                 case LFUN_CLOSE_TAB_GROUP:
3409                         if (TabWorkArea * twa = d.currentTabWorkArea()) {
3410                                 closeTabWorkArea(twa);
3411                                 d.current_work_area_ = 0;
3412                                 twa = d.currentTabWorkArea();
3413                                 // Switch to the next GuiWorkArea in the found TabWorkArea.
3414                                 if (twa) {
3415                                         // Make sure the work area is up to date.
3416                                         setCurrentWorkArea(twa->currentWorkArea());
3417                                 } else {
3418                                         setCurrentWorkArea(0);
3419                                 }
3420                         }
3421                         break;
3422
3423                 case LFUN_COMPLETION_INLINE:
3424                         if (d.current_work_area_)
3425                                 d.current_work_area_->completer().showInline();
3426                         break;
3427
3428                 case LFUN_COMPLETION_POPUP:
3429                         if (d.current_work_area_)
3430                                 d.current_work_area_->completer().showPopup();
3431                         break;
3432
3433
3434                 case LFUN_COMPLETION_COMPLETE:
3435                         if (d.current_work_area_)
3436                                 d.current_work_area_->completer().tab();
3437                         break;
3438
3439                 case LFUN_COMPLETION_CANCEL:
3440                         if (d.current_work_area_) {
3441                                 if (d.current_work_area_->completer().popupVisible())
3442                                         d.current_work_area_->completer().hidePopup();
3443                                 else
3444                                         d.current_work_area_->completer().hideInline();
3445                         }
3446                         break;
3447
3448                 case LFUN_COMPLETION_ACCEPT:
3449                         if (d.current_work_area_)
3450                                 d.current_work_area_->completer().activate();
3451                         break;
3452
3453                 case LFUN_BUFFER_ZOOM_IN:
3454                 case LFUN_BUFFER_ZOOM_OUT:
3455                         if (cmd.argument().empty()) {
3456                                 if (cmd.action() == LFUN_BUFFER_ZOOM_IN)
3457                                         lyxrc.zoom += 20;
3458                                 else
3459                                         lyxrc.zoom -= 20;
3460                         } else
3461                                 lyxrc.zoom += convert<int>(cmd.argument());
3462
3463                         if (lyxrc.zoom < 10)
3464                                 lyxrc.zoom = 10;
3465
3466                         // The global QPixmapCache is used in GuiPainter to cache text
3467                         // painting so we must reset it.
3468                         QPixmapCache::clear();
3469                         guiApp->fontLoader().update();
3470                         lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
3471                         break;
3472
3473                 case LFUN_VC_REGISTER:
3474                 case LFUN_VC_CHECK_IN:
3475                 case LFUN_VC_CHECK_OUT:
3476                 case LFUN_VC_REPO_UPDATE:
3477                 case LFUN_VC_LOCKING_TOGGLE:
3478                 case LFUN_VC_REVERT:
3479                 case LFUN_VC_UNDO_LAST:
3480                 case LFUN_VC_COMMAND:
3481                 case LFUN_VC_COMPARE:
3482                         dispatchVC(cmd, dr);
3483                         break;
3484
3485                 case LFUN_SERVER_GOTO_FILE_ROW:
3486                         goToFileRow(to_utf8(cmd.argument()));
3487                         break;
3488
3489                 case LFUN_FORWARD_SEARCH: {
3490                         Buffer const * doc_master = doc_buffer->masterBuffer();
3491                         FileName const path(doc_master->temppath());
3492                         string const texname = doc_master->isChild(doc_buffer)
3493                                 ? DocFileName(changeExtension(
3494                                         doc_buffer->absFileName(),
3495                                                 "tex")).mangledFileName()
3496                                 : doc_buffer->latexName();
3497                         string const mastername =
3498                                 removeExtension(doc_master->latexName());
3499                         FileName const dviname(addName(path.absFileName(),
3500                                         addExtension(mastername, "dvi")));
3501                         FileName const pdfname(addName(path.absFileName(),
3502                                         addExtension(mastername, "pdf")));
3503                         if (!dviname.exists() && !pdfname.exists()) {
3504                                 dr.setMessage(_("Please, preview the document first."));
3505                                 break;
3506                         }
3507                         string outname = dviname.onlyFileName();
3508                         string command = lyxrc.forward_search_dvi;
3509                         if (!dviname.exists() ||
3510                             pdfname.lastModified() > dviname.lastModified()) {
3511                                 outname = pdfname.onlyFileName();
3512                                 command = lyxrc.forward_search_pdf;
3513                         }
3514
3515                         int row = doc_buffer->texrow().getRowFromIdPos(bv->cursor().paragraph().id(), bv->cursor().pos());
3516                         LYXERR(Debug::ACTION, "Forward search: row:" << row
3517                                 << " id:" << bv->cursor().paragraph().id());
3518                         if (!row || command.empty()) {
3519                                 dr.setMessage(_("Couldn't proceed."));
3520                                 break;
3521                         }
3522                         string texrow = convert<string>(row);
3523
3524                         command = subst(command, "$$n", texrow);
3525                         command = subst(command, "$$t", texname);
3526                         command = subst(command, "$$o", outname);
3527
3528                         PathChanger p(path);
3529                         Systemcall one;
3530                         one.startscript(Systemcall::DontWait, command);
3531                         break;
3532                 }
3533                 default:
3534                         // The LFUN must be for one of BufferView, Buffer or Cursor;
3535                         // let's try that:
3536                         dispatchToBufferView(cmd, dr);
3537                         break;
3538         }
3539
3540         // Part of automatic menu appearance feature.
3541         if (isFullScreen()) {
3542                 if (menuBar()->isVisible() && lyxrc.full_screen_menubar)
3543                         menuBar()->hide();
3544                 if (statusBar()->isVisible())
3545                         statusBar()->hide();
3546         }
3547 }
3548
3549
3550 bool GuiView::lfunUiToggle(string const & ui_component)
3551 {
3552         if (ui_component == "scrollbar") {
3553                 // hide() is of no help
3554                 if (d.current_work_area_->verticalScrollBarPolicy() ==
3555                         Qt::ScrollBarAlwaysOff)
3556
3557                         d.current_work_area_->setVerticalScrollBarPolicy(
3558                                 Qt::ScrollBarAsNeeded);
3559                 else
3560                         d.current_work_area_->setVerticalScrollBarPolicy(
3561                                 Qt::ScrollBarAlwaysOff);
3562         } else if (ui_component == "statusbar") {
3563                 statusBar()->setVisible(!statusBar()->isVisible());
3564         } else if (ui_component == "menubar") {
3565                 menuBar()->setVisible(!menuBar()->isVisible());
3566         } else
3567 #if QT_VERSION >= 0x040300
3568         if (ui_component == "frame") {
3569                 int l, t, r, b;
3570                 getContentsMargins(&l, &t, &r, &b);
3571                 //are the frames in default state?
3572                 d.current_work_area_->setFrameStyle(QFrame::NoFrame);
3573                 if (l == 0) {
3574                         setContentsMargins(-2, -2, -2, -2);
3575                 } else {
3576                         setContentsMargins(0, 0, 0, 0);
3577                 }
3578         } else
3579 #endif
3580         if (ui_component == "fullscreen") {
3581                 toggleFullScreen();
3582         } else
3583                 return false;
3584         return true;
3585 }
3586
3587
3588 void GuiView::toggleFullScreen()
3589 {
3590         if (isFullScreen()) {
3591                 for (int i = 0; i != d.splitter_->count(); ++i)
3592                         d.tabWorkArea(i)->setFullScreen(false);
3593 #if QT_VERSION >= 0x040300
3594                 setContentsMargins(0, 0, 0, 0);
3595 #endif
3596                 setWindowState(windowState() ^ Qt::WindowFullScreen);
3597                 restoreLayout();
3598                 menuBar()->show();
3599                 statusBar()->show();
3600         } else {
3601                 // bug 5274
3602                 hideDialogs("prefs", 0);
3603                 for (int i = 0; i != d.splitter_->count(); ++i)
3604                         d.tabWorkArea(i)->setFullScreen(true);
3605 #if QT_VERSION >= 0x040300
3606                 setContentsMargins(-2, -2, -2, -2);
3607 #endif
3608                 saveLayout();
3609                 setWindowState(windowState() ^ Qt::WindowFullScreen);
3610                 statusBar()->hide();
3611                 if (lyxrc.full_screen_menubar)
3612                         menuBar()->hide();
3613                 if (lyxrc.full_screen_toolbars) {
3614                         ToolbarMap::iterator end = d.toolbars_.end();
3615                         for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
3616                                 it->second->hide();
3617                 }
3618         }
3619
3620         // give dialogs like the TOC a chance to adapt
3621         updateDialogs();
3622 }
3623
3624
3625 Buffer const * GuiView::updateInset(Inset const * inset)
3626 {
3627         if (!inset)
3628                 return 0;
3629
3630         Buffer const * inset_buffer = &(inset->buffer());
3631
3632         for (int i = 0; i != d.splitter_->count(); ++i) {
3633                 GuiWorkArea * wa = d.tabWorkArea(i)->currentWorkArea();
3634                 if (!wa)
3635                         continue;
3636                 Buffer const * buffer = &(wa->bufferView().buffer());
3637                 if (inset_buffer == buffer)
3638                         wa->scheduleRedraw();
3639         }
3640         return inset_buffer;
3641 }
3642
3643
3644 void GuiView::restartCursor()
3645 {
3646         /* When we move around, or type, it's nice to be able to see
3647          * the cursor immediately after the keypress.
3648          */
3649         if (d.current_work_area_)
3650                 d.current_work_area_->startBlinkingCursor();
3651
3652         // Take this occasion to update the other GUI elements.
3653         updateDialogs();
3654         updateStatusBar();
3655 }
3656
3657
3658 void GuiView::updateCompletion(Cursor & cur, bool start, bool keep)
3659 {
3660         if (d.current_work_area_)
3661                 d.current_work_area_->completer().updateVisibility(cur, start, keep);
3662 }
3663
3664 namespace {
3665
3666 // This list should be kept in sync with the list of insets in
3667 // src/insets/Inset.cpp.  I.e., if a dialog goes with an inset, the
3668 // dialog should have the same name as the inset.
3669 // Changes should be also recorded in LFUN_DIALOG_SHOW doxygen
3670 // docs in LyXAction.cpp.
3671
3672 char const * const dialognames[] = {
3673
3674 "aboutlyx", "bibitem", "bibtex", "box", "branch", "changes", "character",
3675 "citation", "compare", "comparehistory", "document", "errorlist", "ert",
3676 "external", "file", "findreplace", "findreplaceadv", "float", "graphics",
3677 "href", "include", "index", "index_print", "info", "listings", "label", "line",
3678 "log", "mathdelimiter", "mathmatrix", "mathspace", "nomenclature",
3679 "nomencl_print", "note", "paragraph", "phantom", "prefs", "print", "ref",
3680 "sendto", "space", "spellchecker", "symbols", "tabular", "tabularcreate",
3681 "thesaurus", "texinfo", "toc", "view-source", "vspace", "wrap", "progress"};
3682
3683 char const * const * const end_dialognames =
3684         dialognames + (sizeof(dialognames) / sizeof(char *));
3685
3686 class cmpCStr {
3687 public:
3688         cmpCStr(char const * name) : name_(name) {}
3689         bool operator()(char const * other) {
3690                 return strcmp(other, name_) == 0;
3691         }
3692 private:
3693         char const * name_;
3694 };
3695
3696
3697 bool isValidName(string const & name)
3698 {
3699         return find_if(dialognames, end_dialognames,
3700                                 cmpCStr(name.c_str())) != end_dialognames;
3701 }
3702
3703 } // namespace anon
3704
3705
3706 void GuiView::resetDialogs()
3707 {
3708         // Make sure that no LFUN uses any GuiView.
3709         guiApp->setCurrentView(0);
3710         saveLayout();
3711         saveUISettings();
3712         menuBar()->clear();
3713         constructToolbars();
3714         guiApp->menus().fillMenuBar(menuBar(), this, false);
3715         d.layout_->updateContents(true);
3716         // Now update controls with current buffer.
3717         guiApp->setCurrentView(this);
3718         restoreLayout();
3719         restartCursor();
3720 }
3721
3722
3723 Dialog * GuiView::findOrBuild(string const & name, bool hide_it)
3724 {
3725         if (!isValidName(name))
3726                 return 0;
3727
3728         map<string, DialogPtr>::iterator it = d.dialogs_.find(name);
3729
3730         if (it != d.dialogs_.end()) {
3731                 if (hide_it)
3732                         it->second->hideView();
3733                 return it->second.get();
3734         }
3735
3736         Dialog * dialog = build(name);
3737         d.dialogs_[name].reset(dialog);
3738         if (lyxrc.allow_geometry_session)
3739                 dialog->restoreSession();
3740         if (hide_it)
3741                 dialog->hideView();
3742         return dialog;
3743 }
3744
3745
3746 void GuiView::showDialog(string const & name, string const & data,
3747         Inset * inset)
3748 {
3749         triggerShowDialog(toqstr(name), toqstr(data), inset);
3750 }
3751
3752
3753 void GuiView::doShowDialog(QString const & qname, QString const & qdata,
3754         Inset * inset)
3755 {
3756         if (d.in_show_)
3757                 return;
3758
3759         const string name = fromqstr(qname);
3760         const string data = fromqstr(qdata);
3761
3762         d.in_show_ = true;
3763         try {
3764                 Dialog * dialog = findOrBuild(name, false);
3765                 if (dialog) {
3766                         bool const visible = dialog->isVisibleView();
3767                         dialog->showData(data);
3768                         if (inset && currentBufferView())
3769                                 currentBufferView()->editInset(name, inset);
3770                         // We only set the focus to the new dialog if it was not yet
3771                         // visible in order not to change the existing previous behaviour
3772                         if (visible) {
3773                                 // activateWindow is needed for floating dockviews
3774                                 dialog->asQWidget()->raise();
3775                                 dialog->asQWidget()->activateWindow();
3776                                 dialog->asQWidget()->setFocus();
3777                         }
3778                 }
3779         }
3780         catch (ExceptionMessage const & ex) {
3781                 d.in_show_ = false;
3782                 throw ex;
3783         }
3784         d.in_show_ = false;
3785 }
3786
3787
3788 bool GuiView::isDialogVisible(string const & name) const
3789 {
3790         map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3791         if (it == d.dialogs_.end())
3792                 return false;
3793         return it->second.get()->isVisibleView() && !it->second.get()->isClosing();
3794 }
3795
3796
3797 void GuiView::hideDialog(string const & name, Inset * inset)
3798 {
3799         map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3800         if (it == d.dialogs_.end())
3801                 return;
3802
3803         if (inset) {
3804                 if (!currentBufferView())
3805                         return;
3806                 if (inset != currentBufferView()->editedInset(name))
3807                         return;
3808         }
3809
3810         Dialog * const dialog = it->second.get();
3811         if (dialog->isVisibleView())
3812                 dialog->hideView();
3813         if (currentBufferView())
3814                 currentBufferView()->editInset(name, 0);
3815 }
3816
3817
3818 void GuiView::disconnectDialog(string const & name)
3819 {
3820         if (!isValidName(name))
3821                 return;
3822         if (currentBufferView())
3823                 currentBufferView()->editInset(name, 0);
3824 }
3825
3826
3827 void GuiView::hideAll() const
3828 {
3829         map<string, DialogPtr>::const_iterator it  = d.dialogs_.begin();
3830         map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3831
3832         for(; it != end; ++it)
3833                 it->second->hideView();
3834 }
3835
3836
3837 void GuiView::updateDialogs()
3838 {
3839         map<string, DialogPtr>::const_iterator it  = d.dialogs_.begin();
3840         map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3841
3842         for(; it != end; ++it) {
3843                 Dialog * dialog = it->second.get();
3844                 if (dialog) {
3845                         if (dialog->needBufferOpen() && !documentBufferView())
3846                                 hideDialog(fromqstr(dialog->name()), 0);
3847                         else if (dialog->isVisibleView())
3848                                 dialog->checkStatus();
3849                 }
3850         }
3851         updateToolbars();
3852         updateLayoutList();
3853 }
3854
3855 Dialog * createDialog(GuiView & lv, string const & name);
3856
3857 // will be replaced by a proper factory...
3858 Dialog * createGuiAbout(GuiView & lv);
3859 Dialog * createGuiBibtex(GuiView & lv);
3860 Dialog * createGuiChanges(GuiView & lv);
3861 Dialog * createGuiCharacter(GuiView & lv);
3862 Dialog * createGuiCitation(GuiView & lv);
3863 Dialog * createGuiCompare(GuiView & lv);
3864 Dialog * createGuiCompareHistory(GuiView & lv);
3865 Dialog * createGuiDelimiter(GuiView & lv);
3866 Dialog * createGuiDocument(GuiView & lv);
3867 Dialog * createGuiErrorList(GuiView & lv);
3868 Dialog * createGuiExternal(GuiView & lv);
3869 Dialog * createGuiGraphics(GuiView & lv);
3870 Dialog * createGuiInclude(GuiView & lv);
3871 Dialog * createGuiIndex(GuiView & lv);
3872 Dialog * createGuiListings(GuiView & lv);
3873 Dialog * createGuiLog(GuiView & lv);
3874 Dialog * createGuiMathMatrix(GuiView & lv);
3875 Dialog * createGuiNote(GuiView & lv);
3876 Dialog * createGuiParagraph(GuiView & lv);
3877 Dialog * createGuiPhantom(GuiView & lv);
3878 Dialog * createGuiPreferences(GuiView & lv);
3879 Dialog * createGuiPrint(GuiView & lv);
3880 Dialog * createGuiPrintindex(GuiView & lv);
3881 Dialog * createGuiRef(GuiView & lv);
3882 Dialog * createGuiSearch(GuiView & lv);
3883 Dialog * createGuiSearchAdv(GuiView & lv);
3884 Dialog * createGuiSendTo(GuiView & lv);
3885 Dialog * createGuiShowFile(GuiView & lv);
3886 Dialog * createGuiSpellchecker(GuiView & lv);
3887 Dialog * createGuiSymbols(GuiView & lv);
3888 Dialog * createGuiTabularCreate(GuiView & lv);
3889 Dialog * createGuiTexInfo(GuiView & lv);
3890 Dialog * createGuiToc(GuiView & lv);
3891 Dialog * createGuiThesaurus(GuiView & lv);
3892 Dialog * createGuiViewSource(GuiView & lv);
3893 Dialog * createGuiWrap(GuiView & lv);
3894 Dialog * createGuiProgressView(GuiView & lv);
3895
3896
3897
3898 Dialog * GuiView::build(string const & name)
3899 {
3900         LASSERT(isValidName(name), return 0);
3901
3902         Dialog * dialog = createDialog(*this, name);
3903         if (dialog)
3904                 return dialog;
3905
3906         if (name == "aboutlyx")
3907                 return createGuiAbout(*this);
3908         if (name == "bibtex")
3909                 return createGuiBibtex(*this);
3910         if (name == "changes")
3911                 return createGuiChanges(*this);
3912         if (name == "character")
3913                 return createGuiCharacter(*this);
3914         if (name == "citation")
3915                 return createGuiCitation(*this);
3916         if (name == "compare")
3917                 return createGuiCompare(*this);
3918         if (name == "comparehistory")
3919                 return createGuiCompareHistory(*this);
3920         if (name == "document")
3921                 return createGuiDocument(*this);
3922         if (name == "errorlist")
3923                 return createGuiErrorList(*this);
3924         if (name == "external")
3925                 return createGuiExternal(*this);
3926         if (name == "file")
3927                 return createGuiShowFile(*this);
3928         if (name == "findreplace")
3929                 return createGuiSearch(*this);
3930         if (name == "findreplaceadv")
3931                 return createGuiSearchAdv(*this);
3932         if (name == "graphics")
3933                 return createGuiGraphics(*this);
3934         if (name == "include")
3935                 return createGuiInclude(*this);
3936         if (name == "index")
3937                 return createGuiIndex(*this);
3938         if (name == "index_print")
3939                 return createGuiPrintindex(*this);
3940         if (name == "listings")
3941                 return createGuiListings(*this);
3942         if (name == "log")
3943                 return createGuiLog(*this);
3944         if (name == "mathdelimiter")
3945                 return createGuiDelimiter(*this);
3946         if (name == "mathmatrix")
3947                 return createGuiMathMatrix(*this);
3948         if (name == "note")
3949                 return createGuiNote(*this);
3950         if (name == "paragraph")
3951                 return createGuiParagraph(*this);
3952         if (name == "phantom")
3953                 return createGuiPhantom(*this);
3954         if (name == "prefs")
3955                 return createGuiPreferences(*this);
3956         if (name == "print")
3957                 return createGuiPrint(*this);
3958         if (name == "ref")
3959                 return createGuiRef(*this);
3960         if (name == "sendto")
3961                 return createGuiSendTo(*this);
3962         if (name == "spellchecker")
3963                 return createGuiSpellchecker(*this);
3964         if (name == "symbols")
3965                 return createGuiSymbols(*this);
3966         if (name == "tabularcreate")
3967                 return createGuiTabularCreate(*this);
3968         if (name == "texinfo")
3969                 return createGuiTexInfo(*this);
3970         if (name == "thesaurus")
3971                 return createGuiThesaurus(*this);
3972         if (name == "toc")
3973                 return createGuiToc(*this);
3974         if (name == "view-source")
3975                 return createGuiViewSource(*this);
3976         if (name == "wrap")
3977                 return createGuiWrap(*this);
3978         if (name == "progress")
3979                 return createGuiProgressView(*this);
3980
3981         return 0;
3982 }
3983
3984
3985 } // namespace frontend
3986 } // namespace lyx
3987
3988 #include "moc_GuiView.cpp"