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