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