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