]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiView.cpp
I assume this was a c&p error
[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() && !doc_buffer->isReadonly();
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().repoUpdateEnabled();
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.setButton2(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                 ListOfBuffers clist = buf.getChildren();
2332                 ListOfBuffers::const_iterator it = clist.begin();
2333                 ListOfBuffers::const_iterator const bend = clist.end();
2334                 for (; it != bend; ++it) {
2335                         // If a child is dirty, do not close
2336                         // without user intervention
2337                         //FIXME: should we look in other tabworkareas?
2338                         Buffer * child_buf = *it;
2339                         GuiWorkArea * child_wa = workArea(*child_buf);
2340                         if (child_wa) {
2341                                 if (!closeWorkArea(child_wa, true))
2342                                         return false;
2343                         } else
2344                                 theBufferList().releaseChild(&buf, child_buf);
2345                 }
2346         }
2347         // goto bookmark to update bookmark pit.
2348         //FIXME: we should update only the bookmarks related to this buffer!
2349         LYXERR(Debug::DEBUG, "GuiView::closeBuffer()");
2350         for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
2351                 guiApp->gotoBookmark(i+1, false, false);
2352
2353         if (saveBufferIfNeeded(buf, false)) {
2354                 buf.removeAutosaveFile();
2355                 theBufferList().release(&buf);
2356                 return true;
2357         }
2358         return false;
2359 }
2360
2361
2362 bool GuiView::closeTabWorkArea(TabWorkArea * twa)
2363 {
2364         while (twa == d.currentTabWorkArea()) {
2365                 twa->setCurrentIndex(twa->count()-1);
2366
2367                 GuiWorkArea * wa = twa->currentWorkArea();
2368                 Buffer & b = wa->bufferView().buffer();
2369
2370                 // We only want to close the buffer if the same buffer is not visible
2371                 // in another view, and if this is not a child and if we are closing
2372                 // a view (not a tabgroup).
2373                 bool const close_buffer =
2374                         !inMultiViews(wa) && !b.parent() && closing_;
2375
2376                 if (!closeWorkArea(wa, close_buffer))
2377                         return false;
2378         }
2379         return true;
2380 }
2381
2382
2383 bool GuiView::saveBufferIfNeeded(Buffer & buf, bool hiding)
2384 {
2385         if (buf.isClean() || buf.paragraphs().empty())
2386                 return true;
2387
2388         // Switch to this Buffer.
2389         setBuffer(&buf);
2390
2391         docstring file;
2392         // FIXME: Unicode?
2393         if (buf.isUnnamed())
2394                 file = from_utf8(buf.fileName().onlyFileName());
2395         else
2396                 file = buf.fileName().displayName(30);
2397
2398         // Bring this window to top before asking questions.
2399         raise();
2400         activateWindow();
2401
2402         int ret;
2403         if (hiding && buf.isUnnamed()) {
2404                 docstring const text = bformat(_("The document %1$s has not been "
2405                                                  "saved yet.\n\nDo you want to save "
2406                                                  "the document?"), file);
2407                 ret = Alert::prompt(_("Save new document?"),
2408                         text, 0, 1, _("&Save"), _("&Cancel"));
2409                 if (ret == 1)
2410                         ++ret;
2411         } else {
2412                 docstring const text = bformat(_("The document %1$s has unsaved changes."
2413                         "\n\nDo you want to save the document or discard the changes?"), file);
2414                 ret = Alert::prompt(_("Save changed document?"),
2415                         text, 0, 2, _("&Save"), _("&Discard"), _("&Cancel"));
2416         }
2417
2418         switch (ret) {
2419         case 0:
2420                 if (!saveBuffer(buf))
2421                         return false;
2422                 break;
2423         case 1:
2424                 // if we crash after this we could
2425                 // have no autosave file but I guess
2426                 // this is really improbable (Jug)
2427                 // Sometime improbable things happen, bug 6857 (ps)
2428                 // buf.removeAutosaveFile();
2429                 if (hiding)
2430                         // revert all changes
2431                         buf.reload();
2432                 buf.markClean();
2433                 break;
2434         case 2:
2435                 return false;
2436         }
2437         return true;
2438 }
2439
2440
2441 bool GuiView::inMultiTabs(GuiWorkArea * wa)
2442 {
2443         Buffer & buf = wa->bufferView().buffer();
2444
2445         for (int i = 0; i != d.splitter_->count(); ++i) {
2446                 GuiWorkArea * wa_ = d.tabWorkArea(i)->workArea(buf);
2447                 if (wa_ && wa_ != wa)
2448                         return true;
2449         }
2450         return inMultiViews(wa);
2451 }
2452
2453
2454 bool GuiView::inMultiViews(GuiWorkArea * wa)
2455 {
2456         QList<int> const ids = guiApp->viewIds();
2457         Buffer & buf = wa->bufferView().buffer();
2458
2459         int found_twa = 0;
2460         for (int i = 0; i != ids.size() && found_twa <= 1; ++i) {
2461                 if (id_ == ids[i])
2462                         continue;
2463
2464                 if (guiApp->view(ids[i]).workArea(buf))
2465                         return true;
2466         }
2467         return false;
2468 }
2469
2470
2471 void GuiView::gotoNextOrPreviousBuffer(NextOrPrevious np)
2472 {
2473         Buffer * const curbuf = documentBufferView()
2474                 ? &documentBufferView()->buffer() : 0;
2475         Buffer * nextbuf = curbuf;
2476         while (true) {
2477                 if (np == NEXTBUFFER)
2478                         nextbuf = theBufferList().next(nextbuf);
2479                 else
2480                         nextbuf = theBufferList().previous(nextbuf);
2481                 if (nextbuf == curbuf)
2482                         break;
2483                 if (nextbuf == 0) {
2484                         nextbuf = curbuf;
2485                         break;
2486                 }
2487                 if (workArea(*nextbuf))
2488                         break;
2489         }
2490         setBuffer(nextbuf);
2491 }
2492
2493
2494 /// make sure the document is saved
2495 static bool ensureBufferClean(Buffer * buffer)
2496 {
2497         LASSERT(buffer, return false);
2498         if (buffer->isClean() && !buffer->isUnnamed())
2499                 return true;
2500
2501         docstring const file = buffer->fileName().displayName(30);
2502         docstring title;
2503         docstring text;
2504         if (!buffer->isUnnamed()) {
2505                 text = bformat(_("The document %1$s has unsaved "
2506                                                  "changes.\n\nDo you want to save "
2507                                                  "the document?"), file);
2508                 title = _("Save changed document?");
2509
2510         } else {
2511                 text = bformat(_("The document %1$s has not been "
2512                                                  "saved yet.\n\nDo you want to save "
2513                                                  "the document?"), file);
2514                 title = _("Save new document?");
2515         }
2516         int const ret = Alert::prompt(title, text, 0, 1, _("&Save"), _("&Cancel"));
2517
2518         if (ret == 0)
2519                 dispatch(FuncRequest(LFUN_BUFFER_WRITE));
2520
2521         return buffer->isClean() && !buffer->isUnnamed();
2522 }
2523
2524
2525 bool GuiView::reloadBuffer()
2526 {
2527         Buffer * buf = &documentBufferView()->buffer();
2528         return buf->reload();
2529 }
2530
2531
2532 void GuiView::checkExternallyModifiedBuffers()
2533 {
2534         BufferList::iterator bit = theBufferList().begin();
2535         BufferList::iterator const bend = theBufferList().end();
2536         for (; bit != bend; ++bit) {
2537                 if ((*bit)->fileName().exists()
2538                         && (*bit)->isExternallyModified(Buffer::checksum_method)) {
2539                         docstring text = bformat(_("Document \n%1$s\n has been externally modified."
2540                                         " Reload now? Any local changes will be lost."),
2541                                         from_utf8((*bit)->absFileName()));
2542                         int const ret = Alert::prompt(_("Reload externally changed document?"),
2543                                                 text, 0, 1, _("&Reload"), _("&Cancel"));
2544                         if (!ret)
2545                                 (*bit)->reload();
2546                 }
2547         }
2548 }
2549
2550
2551 void GuiView::dispatchVC(FuncRequest const & cmd, DispatchResult & dr)
2552 {
2553         Buffer * buffer = documentBufferView()
2554                 ? &(documentBufferView()->buffer()) : 0;
2555
2556         switch (cmd.action()) {
2557         case LFUN_VC_REGISTER:
2558                 if (!buffer || !ensureBufferClean(buffer))
2559                         break;
2560                 if (!buffer->lyxvc().inUse()) {
2561                         if (buffer->lyxvc().registrer()) {
2562                                 reloadBuffer();
2563                                 dr.suppressMessageUpdate();
2564                         }
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                         dr.setMessage(buffer->lyxvc().checkIn());
2573                         if (!dr.message().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                         dr.setMessage(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                                 dr.setMessage(res);
2598                                 reloadBuffer();
2599                         }
2600                 }
2601                 break;
2602
2603         case LFUN_VC_REVERT:
2604                 LASSERT(buffer, return);
2605                 buffer->lyxvc().revert();
2606                 reloadBuffer();
2607                 dr.suppressMessageUpdate();
2608                 break;
2609
2610         case LFUN_VC_UNDO_LAST:
2611                 LASSERT(buffer, return);
2612                 buffer->lyxvc().undoLast();
2613                 reloadBuffer();
2614                 dr.suppressMessageUpdate();
2615                 break;
2616
2617         case LFUN_VC_REPO_UPDATE:
2618                 LASSERT(buffer, return);
2619                 if (ensureBufferClean(buffer)) {
2620                         dr.setMessage(buffer->lyxvc().repoUpdate());
2621                         checkExternallyModifiedBuffers();
2622                 }
2623                 break;
2624
2625         case LFUN_VC_COMMAND: {
2626                 string flag = cmd.getArg(0);
2627                 if (buffer && contains(flag, 'R') && !ensureBufferClean(buffer))
2628                         break;
2629                 docstring message;
2630                 if (contains(flag, 'M')) {
2631                         if (!Alert::askForText(message, _("LyX VC: Log Message")))
2632                                 break;
2633                 }
2634                 string path = cmd.getArg(1);
2635                 if (contains(path, "$$p") && buffer)
2636                         path = subst(path, "$$p", buffer->filePath());
2637                 LYXERR(Debug::LYXVC, "Directory: " << path);
2638                 FileName pp(path);
2639                 if (!pp.isReadableDirectory()) {
2640                         lyxerr << _("Directory is not accessible.") << endl;
2641                         break;
2642                 }
2643                 support::PathChanger p(pp);
2644
2645                 string command = cmd.getArg(2);
2646                 if (command.empty())
2647                         break;
2648                 if (buffer) {
2649                         command = subst(command, "$$i", buffer->absFileName());
2650                         command = subst(command, "$$p", buffer->filePath());
2651                 }
2652                 command = subst(command, "$$m", to_utf8(message));
2653                 LYXERR(Debug::LYXVC, "Command: " << command);
2654                 Systemcall one;
2655                 one.startscript(Systemcall::Wait, command);
2656
2657                 if (!buffer)
2658                         break;
2659                 if (contains(flag, 'I'))
2660                         buffer->markDirty();
2661                 if (contains(flag, 'R'))
2662                         reloadBuffer();
2663
2664                 break;
2665                 }
2666
2667         case LFUN_VC_COMPARE: {
2668
2669                 if (cmd.argument().empty()) {
2670                         lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "comparehistory"));
2671                         break;
2672                 }
2673
2674                 string rev1 = cmd.getArg(0);
2675                 string f1, f2;
2676
2677                 // f1
2678                 if (!buffer->lyxvc().prepareFileRevision(rev1, f1))
2679                         break;
2680
2681                 if (isStrInt(rev1) && convert<int>(rev1) <= 0) {
2682                         f2 = buffer->absFileName();
2683                 } else {
2684                         string rev2 = cmd.getArg(1);
2685                         if (rev2.empty())
2686                                 break;
2687                         // f2
2688                         if (!buffer->lyxvc().prepareFileRevision(rev2, f2))
2689                                 break;
2690                 }
2691
2692                 LYXERR(Debug::LYXVC, "Launching comparison for fetched revisions:\n" <<
2693                                         f1 << "\n"  << f2 << "\n" );
2694                 string par = "compare run " + quoteName(f1) + " " + quoteName(f2);
2695                 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, par));
2696                 break;
2697         }
2698
2699         default:
2700                 break;
2701         }
2702 }
2703
2704
2705 void GuiView::openChildDocument(string const & fname)
2706 {
2707         LASSERT(documentBufferView(), return);
2708         Buffer & buffer = documentBufferView()->buffer();
2709         FileName const filename = support::makeAbsPath(fname, buffer.filePath());
2710         documentBufferView()->saveBookmark(false);
2711         Buffer * child = 0;
2712         bool parsed = false;
2713         if (theBufferList().exists(filename)) {
2714                 child = theBufferList().getBuffer(filename);
2715         } else {
2716                 message(bformat(_("Opening child document %1$s..."),
2717                 makeDisplayPath(filename.absFileName())));
2718                 child = loadDocument(filename, false);
2719                 parsed = true;
2720         }
2721         if (!child)
2722                 return;
2723
2724         // Set the parent name of the child document.
2725         // This makes insertion of citations and references in the child work,
2726         // when the target is in the parent or another child document.
2727         child->setParent(&buffer);
2728
2729         // I don't think this is needed, since it will be called in
2730         // setBuffer().
2731         //      child->masterBuffer()->updateBuffer();
2732         setBuffer(child);
2733         if (parsed)
2734                 child->errors("Parse");
2735 }
2736
2737
2738 bool GuiView::goToFileRow(string const & argument)
2739 {
2740         string file_name;
2741         int row;
2742         size_t i = argument.find_last_of(' ');
2743         if (i != string::npos) {
2744                 file_name = os::internal_path(trim(argument.substr(0, i)));
2745                 istringstream is(argument.substr(i + 1));
2746                 is >> row;
2747                 if (is.fail())
2748                         i = string::npos;
2749         }
2750         if (i == string::npos) {
2751                 LYXERR0("Wrong argument: " << argument);
2752                 return false;
2753         }
2754         Buffer * buf = 0;
2755         string const abstmp = package().temp_dir().absFileName();
2756         string const realtmp = package().temp_dir().realPath();
2757         // We have to use os::path_prefix_is() here, instead of
2758         // simply prefixIs(), because the file name comes from
2759         // an external application and may need case adjustment.
2760         if (os::path_prefix_is(file_name, abstmp, os::CASE_ADJUSTED)
2761                 || os::path_prefix_is(file_name, realtmp, os::CASE_ADJUSTED)) {
2762                 // Needed by inverse dvi search. If it is a file
2763                 // in tmpdir, call the apropriated function.
2764                 // If tmpdir is a symlink, we may have the real
2765                 // path passed back, so we correct for that.
2766                 if (!prefixIs(file_name, abstmp))
2767                         file_name = subst(file_name, realtmp, abstmp);
2768                 buf = theBufferList().getBufferFromTmp(file_name);
2769         } else {
2770                 // Must replace extension of the file to be .lyx
2771                 // and get full path
2772                 FileName const s = fileSearch(string(),
2773                                                   support::changeExtension(file_name, ".lyx"), "lyx");
2774                 // Either change buffer or load the file
2775                 if (theBufferList().exists(s))
2776                         buf = theBufferList().getBuffer(s);
2777                 else if (s.exists()) {
2778                         buf = loadDocument(s);
2779                         if (!buf)
2780                                 return false;
2781                         // I don't think this is needed. loadDocument() calls
2782                         // setBuffer(), which calls updateBuffer().
2783                         // buf->updateBuffer();
2784                         buf->errors("Parse");
2785                 } else {
2786                         message(bformat(
2787                                         _("File does not exist: %1$s"),
2788                                         makeDisplayPath(file_name)));
2789                         return false;
2790                 }
2791         }
2792         setBuffer(buf);
2793         documentBufferView()->setCursorFromRow(row);
2794         return true;
2795 }
2796
2797
2798 #if (QT_VERSION >= 0x040400)
2799 docstring GuiView::GuiViewPrivate::exportAndDestroy(Buffer const * orig, Buffer * buffer, string const & format)
2800 {
2801         bool const update_unincluded =
2802                                 buffer->params().maintain_unincluded_children
2803                                 && !buffer->params().getIncludedChildren().empty();
2804         bool const success = buffer->doExport(format, true, update_unincluded);
2805         delete buffer;
2806         busyBuffers.remove(orig);
2807         return success
2808                 ? bformat(_("Successful export to format: %1$s"), from_utf8(format))
2809                 : bformat(_("Error exporting to format: %1$s"), from_utf8(format));
2810 }
2811
2812
2813 docstring GuiView::GuiViewPrivate::previewAndDestroy(Buffer const * orig, Buffer * buffer, string const & format)
2814 {
2815         bool const update_unincluded =
2816                                 buffer->params().maintain_unincluded_children
2817                                 && !buffer->params().getIncludedChildren().empty();
2818         bool const success = buffer->preview(format, update_unincluded);
2819         delete buffer;
2820         busyBuffers.remove(orig);
2821         return success
2822                 ? bformat(_("Successful preview of format: %1$s"), from_utf8(format))
2823                 : bformat(_("Error previewing format: %1$s"), from_utf8(format));
2824 }
2825 #endif
2826
2827
2828
2829 void GuiView::dispatch(FuncRequest const & cmd, DispatchResult & dr)
2830 {
2831         BufferView * bv = currentBufferView();
2832         // By default we won't need any update.
2833         dr.screenUpdate(Update::None);
2834         // assume cmd will be dispatched
2835         dr.dispatched(true);
2836
2837         Buffer * doc_buffer = documentBufferView()
2838                 ? &(documentBufferView()->buffer()) : 0;
2839
2840         if (cmd.origin() == FuncRequest::TOC) {
2841                 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
2842                 // FIXME: do we need to pass a DispatchResult object here?
2843                 toc->doDispatch(bv->cursor(), cmd);
2844                 return;
2845         }
2846
2847         string const argument = to_utf8(cmd.argument());
2848
2849         switch(cmd.action()) {
2850                 case LFUN_BUFFER_CHILD_OPEN:
2851                         openChildDocument(to_utf8(cmd.argument()));
2852                         break;
2853
2854                 case LFUN_BUFFER_IMPORT:
2855                         importDocument(to_utf8(cmd.argument()));
2856                         break;
2857
2858                 case LFUN_BUFFER_EXPORT: {
2859                         if (!doc_buffer)
2860                                 break;
2861                         // GCC only sees strfwd.h when building merged
2862                         if (::lyx::operator==(cmd.argument(), "custom")) {
2863                                 dispatch(FuncRequest(LFUN_DIALOG_SHOW, "sendto"),
2864                                          dr);
2865                                 break;
2866                         }
2867                         if (!doc_buffer->doExport(argument, false)) {
2868                                 dr.setError(true);
2869                                 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
2870                                         cmd.argument()));
2871                         }
2872                         break;
2873                 }
2874
2875                 case LFUN_BUFFER_UPDATE: {
2876                         if (!doc_buffer)
2877                                 break;
2878                         docstring msg = _("Exporting ...");
2879                         Buffer const * used_buffer = doc_buffer;
2880                         string format = argument;
2881                         if (format.empty())
2882                                 format = used_buffer->getDefaultOutputFormat();
2883 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
2884                         if (!msg.empty()) {
2885                                 d.progress_->clearMessages();
2886                                 message(msg);
2887                         }
2888                         GuiViewPrivate::busyBuffers.insert(used_buffer);
2889                         QFuture<docstring> f = QtConcurrent::run(
2890                                     GuiViewPrivate::exportAndDestroy,
2891                                     used_buffer,
2892                                     used_buffer->clone(),
2893                                     format);
2894                         d.setPreviewFuture(f);
2895                         d.last_export_format = used_buffer->bufferFormat();
2896 #else
2897                         bool const update_unincluded =
2898                                 used_buffer->params().maintain_unincluded_children &&
2899                                 !used_buffer->params().getIncludedChildren().empty();
2900                         used_buffer->doExport(format, true, update_unincluded);
2901 #endif
2902                         break;
2903                 }
2904                 case LFUN_BUFFER_VIEW: {
2905                         if (!doc_buffer)
2906                                 break;
2907                         docstring msg = _("Previewing ...");
2908                         Buffer const * used_buffer = doc_buffer;
2909                         string format = argument;
2910                         if (format.empty())
2911                                 format = used_buffer->getDefaultOutputFormat();
2912 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
2913                         if (!msg.empty()) {
2914                                 d.progress_->clearMessages();
2915                                 message(msg);
2916                         }
2917                         GuiViewPrivate::busyBuffers.insert(used_buffer);
2918                         QFuture<docstring> f = QtConcurrent::run(
2919                                     GuiViewPrivate::previewAndDestroy,
2920                                     used_buffer,
2921                                     used_buffer->clone(),
2922                                     format);
2923                         d.setPreviewFuture(f);
2924                         d.last_export_format = used_buffer->bufferFormat();
2925 #else
2926                         bool const update_unincluded =
2927                                 used_buffer->params().maintain_unincluded_children &&
2928                                 !used_buffer->params().getIncludedChildren().empty();
2929                         used_buffer->preview(format, update_unincluded);
2930 #endif
2931                         break;
2932                 }
2933                 case LFUN_MASTER_BUFFER_UPDATE: {
2934                         if (!doc_buffer)
2935                                 break;
2936                         Buffer const * used_buffer = doc_buffer->masterBuffer();
2937                         string format = argument;
2938                         if (format.empty())
2939                                 format = used_buffer->getDefaultOutputFormat();
2940 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
2941                         GuiViewPrivate::busyBuffers.insert(used_buffer);
2942                         QFuture<docstring> f = QtConcurrent::run(
2943                                     GuiViewPrivate::exportAndDestroy,
2944                                     used_buffer,
2945                                     used_buffer->clone(),
2946                                     format);
2947                         d.setPreviewFuture(f);
2948                         d.last_export_format = used_buffer->bufferFormat();
2949 #else
2950                         bool const update_unincluded =
2951                                 used_buffer->params().maintain_unincluded_children &&
2952                                 !used_buffer->params().getIncludedChildren().empty();
2953                         used_buffer->doExport(format, update_unincluded);
2954 #endif
2955                         break;
2956                 }
2957                 case LFUN_MASTER_BUFFER_VIEW: {
2958                         if (!doc_buffer)
2959                                 break;
2960                         Buffer const * used_buffer = doc_buffer->masterBuffer();
2961                         string format = argument;
2962                         if (format.empty())
2963                                 format = used_buffer->getDefaultOutputFormat();
2964 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
2965                         GuiViewPrivate::busyBuffers.insert(used_buffer);
2966                         QFuture<docstring> f = QtConcurrent::run(
2967                                     GuiViewPrivate::previewAndDestroy,
2968                                     used_buffer, 
2969                                     used_buffer->clone(), 
2970                                     format);
2971                         d.setPreviewFuture(f);
2972                         // TODO doc_buffer was used used? Was this this a copy & paste error?
2973                         d.last_export_format = used_buffer->bufferFormat();
2974 #else
2975                         used_buffer->preview(format);
2976 #endif
2977                         break;
2978                 }
2979                 case LFUN_BUFFER_SWITCH: {
2980                         string const file_name = to_utf8(cmd.argument());
2981                         if (!FileName::isAbsolute(file_name)) {
2982                                 dr.setError(true);
2983                                 dr.setMessage(_("Absolute filename expected."));
2984                                 break;
2985                         }
2986
2987                         Buffer * buffer = theBufferList().getBuffer(FileName(file_name));
2988                         if (!buffer) {
2989                                 dr.setError(true);
2990                                 dr.setMessage(_("Document not loaded"));
2991                                 break;
2992                         }
2993
2994                         // Do we open or switch to the buffer in this view ?
2995                         if (workArea(*buffer)
2996                                   || lyxrc.open_buffers_in_tabs || !documentBufferView()) {
2997                                 setBuffer(buffer);
2998                                 break;
2999                         }
3000
3001                         // Look for the buffer in other views
3002                         QList<int> const ids = guiApp->viewIds();
3003                         int i = 0;
3004                         for (; i != ids.size(); ++i) {
3005                                 GuiView & gv = guiApp->view(ids[i]);
3006                                 if (gv.workArea(*buffer)) {
3007                                         gv.activateWindow();
3008                                         gv.setBuffer(buffer);
3009                                         break;
3010                                 }
3011                         }
3012
3013                         // If necessary, open a new window as a last resort
3014                         if (i == ids.size()) {
3015                                 lyx::dispatch(FuncRequest(LFUN_WINDOW_NEW));
3016                                 lyx::dispatch(cmd);
3017                         }
3018                         break;
3019                 }
3020
3021                 case LFUN_BUFFER_NEXT:
3022                         gotoNextOrPreviousBuffer(NEXTBUFFER);
3023                         break;
3024
3025                 case LFUN_BUFFER_PREVIOUS:
3026                         gotoNextOrPreviousBuffer(PREVBUFFER);
3027                         break;
3028
3029                 case LFUN_COMMAND_EXECUTE: {
3030                         bool const show_it = cmd.argument() != "off";
3031                         // FIXME: this is a hack, "minibuffer" should not be
3032                         // hardcoded.
3033                         if (GuiToolbar * t = toolbar("minibuffer")) {
3034                                 t->setVisible(show_it);
3035                                 if (show_it && t->commandBuffer())
3036                                         t->commandBuffer()->setFocus();
3037                         }
3038                         break;
3039                 }
3040                 case LFUN_DROP_LAYOUTS_CHOICE:
3041                         d.layout_->showPopup();
3042                         break;
3043
3044                 case LFUN_MENU_OPEN:
3045                         if (QMenu * menu = guiApp->menus().menu(toqstr(cmd.argument()), *this))
3046                                 menu->exec(QCursor::pos());
3047                         break;
3048
3049                 case LFUN_FILE_INSERT:
3050                         insertLyXFile(cmd.argument());
3051                         break;
3052                 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
3053                         insertPlaintextFile(cmd.argument(), true);
3054                         break;
3055
3056                 case LFUN_FILE_INSERT_PLAINTEXT:
3057                         insertPlaintextFile(cmd.argument(), false);
3058                         break;
3059
3060                 case LFUN_BUFFER_RELOAD: {
3061                         LASSERT(doc_buffer, break);
3062                         docstring const file = makeDisplayPath(doc_buffer->absFileName(), 20);
3063                         docstring text = bformat(_("Any changes will be lost. Are you sure "
3064                                                                  "you want to revert to the saved version of the document %1$s?"), file);
3065                         int const ret = Alert::prompt(_("Revert to saved document?"),
3066                                 text, 1, 1, _("&Revert"), _("&Cancel"));
3067
3068                         if (ret == 0) {
3069                                 doc_buffer->markClean();
3070                                 reloadBuffer();
3071                                 dr.forceBufferUpdate();
3072                         }
3073                         break;
3074                 }
3075
3076                 case LFUN_BUFFER_WRITE:
3077                         LASSERT(doc_buffer, break);
3078                         saveBuffer(*doc_buffer);
3079                         break;
3080
3081                 case LFUN_BUFFER_WRITE_AS:
3082                         LASSERT(doc_buffer, break);
3083                         renameBuffer(*doc_buffer, cmd.argument());
3084                         break;
3085
3086                 case LFUN_BUFFER_WRITE_ALL: {
3087                         Buffer * first = theBufferList().first();
3088                         if (!first)
3089                                 break;
3090                         message(_("Saving all documents..."));
3091                         // We cannot use a for loop as the buffer list cycles.
3092                         Buffer * b = first;
3093                         do {
3094                                 if (!b->isClean()) {
3095                                         saveBuffer(*b);
3096                                         LYXERR(Debug::ACTION, "Saved " << b->absFileName());
3097                                 }
3098                                 b = theBufferList().next(b);
3099                         } while (b != first);
3100                         dr.setMessage(_("All documents saved."));
3101                         break;
3102                 }
3103
3104                 case LFUN_BUFFER_CLOSE:
3105                         closeBuffer();
3106                         break;
3107
3108                 case LFUN_BUFFER_CLOSE_ALL:
3109                         closeBufferAll();
3110                         break;
3111
3112                 case LFUN_TOOLBAR_TOGGLE: {
3113                         string const name = cmd.getArg(0);
3114                         if (GuiToolbar * t = toolbar(name))
3115                                 t->toggle();
3116                         break;
3117                 }
3118
3119                 case LFUN_DIALOG_UPDATE: {
3120                         string const name = to_utf8(cmd.argument());
3121                         if (currentBufferView()) {
3122                                 Inset * inset = currentBufferView()->editedInset(name);
3123                                 // Can only update a dialog connected to an existing inset
3124                                 if (!inset)
3125                                         break;
3126                                 // FIXME: get rid of this indirection; GuiView ask the inset
3127                                 // if he is kind enough to update itself...
3128                                 FuncRequest fr(LFUN_INSET_DIALOG_UPDATE, cmd.argument());
3129                                 //FIXME: pass DispatchResult here?
3130                                 inset->dispatch(currentBufferView()->cursor(), fr);
3131                         } else if (name == "paragraph") {
3132                                 lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
3133                         } else if (name == "prefs" || name == "document") {
3134                                 updateDialog(name, string());
3135                         }
3136                         break;
3137                 }
3138
3139                 case LFUN_DIALOG_TOGGLE: {
3140                         if (isDialogVisible(cmd.getArg(0)))
3141                                 dispatch(FuncRequest(LFUN_DIALOG_HIDE, cmd.argument()), dr);
3142                         else
3143                                 dispatch(FuncRequest(LFUN_DIALOG_SHOW, cmd.argument()), dr);
3144                         break;
3145                 }
3146
3147                 case LFUN_DIALOG_DISCONNECT_INSET:
3148                         disconnectDialog(to_utf8(cmd.argument()));
3149                         break;
3150
3151                 case LFUN_DIALOG_HIDE: {
3152                         guiApp->hideDialogs(to_utf8(cmd.argument()), 0);
3153                         break;
3154                 }
3155
3156                 case LFUN_DIALOG_SHOW: {
3157                         string const name = cmd.getArg(0);
3158                         string data = trim(to_utf8(cmd.argument()).substr(name.size()));
3159
3160                         if (name == "character") {
3161                                 data = freefont2string();
3162                                 if (!data.empty())
3163                                         showDialog("character", data);
3164                         } else if (name == "latexlog") {
3165                                 Buffer::LogType type;
3166                                 string const logfile = doc_buffer->logName(&type);
3167                                 switch (type) {
3168                                 case Buffer::latexlog:
3169                                         data = "latex ";
3170                                         break;
3171                                 case Buffer::buildlog:
3172                                         data = "literate ";
3173                                         break;
3174                                 }
3175                                 data += Lexer::quoteString(logfile);
3176                                 showDialog("log", data);
3177                         } else if (name == "vclog") {
3178                                 string const data = "vc " +
3179                                         Lexer::quoteString(doc_buffer->lyxvc().getLogFile());
3180                                 showDialog("log", data);
3181                         } else if (name == "symbols") {
3182                                 data = bv->cursor().getEncoding()->name();
3183                                 if (!data.empty())
3184                                         showDialog("symbols", data);
3185                         // bug 5274
3186                         } else if (name == "prefs" && isFullScreen()) {
3187                                 lfunUiToggle("fullscreen");
3188                                 showDialog("prefs", data);
3189                         } else
3190                                 showDialog(name, data);
3191                         break;
3192                 }
3193
3194                 case LFUN_MESSAGE:
3195                         dr.setMessage(cmd.argument());
3196                         break;
3197
3198                 case LFUN_UI_TOGGLE: {
3199                         string arg = cmd.getArg(0);
3200                         if (!lfunUiToggle(arg)) {
3201                                 docstring const msg = "ui-toggle " + _("%1$s unknown command!");
3202                                 dr.setMessage(bformat(msg, from_utf8(arg)));
3203                         }
3204                         // Make sure the keyboard focus stays in the work area.
3205                         setFocus();
3206                         break;
3207                 }
3208
3209                 case LFUN_SPLIT_VIEW: {
3210                         LASSERT(doc_buffer, break);
3211                         string const orientation = cmd.getArg(0);
3212                         d.splitter_->setOrientation(orientation == "vertical"
3213                                 ? Qt::Vertical : Qt::Horizontal);
3214                         TabWorkArea * twa = addTabWorkArea();
3215                         GuiWorkArea * wa = twa->addWorkArea(*doc_buffer, *this);
3216                         setCurrentWorkArea(wa);
3217                         break;
3218                 }
3219                 case LFUN_CLOSE_TAB_GROUP:
3220                         if (TabWorkArea * twa = d.currentTabWorkArea()) {
3221                                 closeTabWorkArea(twa);
3222                                 d.current_work_area_ = 0;
3223                                 twa = d.currentTabWorkArea();
3224                                 // Switch to the next GuiWorkArea in the found TabWorkArea.
3225                                 if (twa) {
3226                                         // Make sure the work area is up to date.
3227                                         setCurrentWorkArea(twa->currentWorkArea());
3228                                 } else {
3229                                         setCurrentWorkArea(0);
3230                                 }
3231                         }
3232                         break;
3233
3234                 case LFUN_COMPLETION_INLINE:
3235                         if (d.current_work_area_)
3236                                 d.current_work_area_->completer().showInline();
3237                         break;
3238
3239                 case LFUN_COMPLETION_POPUP:
3240                         if (d.current_work_area_)
3241                                 d.current_work_area_->completer().showPopup();
3242                         break;
3243
3244
3245                 case LFUN_COMPLETION_COMPLETE:
3246                         if (d.current_work_area_)
3247                                 d.current_work_area_->completer().tab();
3248                         break;
3249
3250                 case LFUN_COMPLETION_CANCEL:
3251                         if (d.current_work_area_) {
3252                                 if (d.current_work_area_->completer().popupVisible())
3253                                         d.current_work_area_->completer().hidePopup();
3254                                 else
3255                                         d.current_work_area_->completer().hideInline();
3256                         }
3257                         break;
3258
3259                 case LFUN_COMPLETION_ACCEPT:
3260                         if (d.current_work_area_)
3261                                 d.current_work_area_->completer().activate();
3262                         break;
3263
3264                 case LFUN_BUFFER_ZOOM_IN:
3265                 case LFUN_BUFFER_ZOOM_OUT:
3266                         if (cmd.argument().empty()) {
3267                                 if (cmd.action() == LFUN_BUFFER_ZOOM_IN)
3268                                         lyxrc.zoom += 20;
3269                                 else
3270                                         lyxrc.zoom -= 20;
3271                         } else
3272                                 lyxrc.zoom += convert<int>(cmd.argument());
3273
3274                         if (lyxrc.zoom < 10)
3275                                 lyxrc.zoom = 10;
3276
3277                         // The global QPixmapCache is used in GuiPainter to cache text
3278                         // painting so we must reset it.
3279                         QPixmapCache::clear();
3280                         guiApp->fontLoader().update();
3281                         lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
3282                         break;
3283
3284                 case LFUN_VC_REGISTER:
3285                 case LFUN_VC_CHECK_IN:
3286                 case LFUN_VC_CHECK_OUT:
3287                 case LFUN_VC_REPO_UPDATE:
3288                 case LFUN_VC_LOCKING_TOGGLE:
3289                 case LFUN_VC_REVERT:
3290                 case LFUN_VC_UNDO_LAST:
3291                 case LFUN_VC_COMMAND:
3292                 case LFUN_VC_COMPARE:
3293                         dispatchVC(cmd, dr);
3294                         break;
3295
3296                 case LFUN_SERVER_GOTO_FILE_ROW:
3297                         goToFileRow(to_utf8(cmd.argument()));
3298                         break;
3299
3300                 case LFUN_FORWARD_SEARCH: {
3301                         FileName const path(doc_buffer->temppath());
3302                         string const texname = doc_buffer->latexName();
3303                         FileName const dviname(addName(path.absFileName(),
3304                                     support::changeExtension(texname, "dvi")));
3305                         FileName const pdfname(addName(path.absFileName(),
3306                                     support::changeExtension(texname, "pdf")));
3307                         if (!dviname.exists() && !pdfname.exists()) {
3308                                 dr.setMessage(_("Please, preview the document first."));
3309                                 break;
3310                         }
3311                         string outname = dviname.onlyFileName();
3312                         string command = lyxrc.forward_search_dvi;
3313                         if (!dviname.exists() ||
3314                             pdfname.lastModified() > dviname.lastModified()) {
3315                                 outname = pdfname.onlyFileName();
3316                                 command = lyxrc.forward_search_pdf;
3317                         }
3318
3319                         int row = doc_buffer->texrow().getRowFromIdPos(bv->cursor().paragraph().id(), bv->cursor().pos());
3320                         LYXERR(Debug::ACTION, "Forward search: row:" << row
3321                                 << " id:" << bv->cursor().paragraph().id());
3322                         if (!row || command.empty()) {
3323                                 dr.setMessage(_("Couldn't proceed."));
3324                                 break;
3325                         }
3326                         string texrow = convert<string>(row);
3327
3328                         command = subst(command, "$$n", texrow);
3329                         command = subst(command, "$$t", texname);
3330                         command = subst(command, "$$o", outname);
3331
3332                         PathChanger p(path);
3333                         Systemcall one;
3334                         one.startscript(Systemcall::DontWait, command);
3335                         break;
3336                 }
3337                 default:
3338                         dr.dispatched(false);
3339                         break;
3340         }
3341
3342         // Part of automatic menu appearance feature.
3343         if (isFullScreen()) {
3344                 if (menuBar()->isVisible() && lyxrc.full_screen_menubar)
3345                         menuBar()->hide();
3346                 if (statusBar()->isVisible())
3347                         statusBar()->hide();
3348         }
3349
3350         return;
3351 }
3352
3353
3354 bool GuiView::lfunUiToggle(string const & ui_component)
3355 {
3356         if (ui_component == "scrollbar") {
3357                 // hide() is of no help
3358                 if (d.current_work_area_->verticalScrollBarPolicy() ==
3359                         Qt::ScrollBarAlwaysOff)
3360
3361                         d.current_work_area_->setVerticalScrollBarPolicy(
3362                                 Qt::ScrollBarAsNeeded);
3363                 else
3364                         d.current_work_area_->setVerticalScrollBarPolicy(
3365                                 Qt::ScrollBarAlwaysOff);
3366         } else if (ui_component == "statusbar") {
3367                 statusBar()->setVisible(!statusBar()->isVisible());
3368         } else if (ui_component == "menubar") {
3369                 menuBar()->setVisible(!menuBar()->isVisible());
3370         } else
3371 #if QT_VERSION >= 0x040300
3372         if (ui_component == "frame") {
3373                 int l, t, r, b;
3374                 getContentsMargins(&l, &t, &r, &b);
3375                 //are the frames in default state?
3376                 d.current_work_area_->setFrameStyle(QFrame::NoFrame);
3377                 if (l == 0) {
3378                         setContentsMargins(-2, -2, -2, -2);
3379                 } else {
3380                         setContentsMargins(0, 0, 0, 0);
3381                 }
3382         } else
3383 #endif
3384         if (ui_component == "fullscreen") {
3385                 toggleFullScreen();
3386         } else
3387                 return false;
3388         return true;
3389 }
3390
3391
3392 void GuiView::toggleFullScreen()
3393 {
3394         if (isFullScreen()) {
3395                 for (int i = 0; i != d.splitter_->count(); ++i)
3396                         d.tabWorkArea(i)->setFullScreen(false);
3397 #if QT_VERSION >= 0x040300
3398                 setContentsMargins(0, 0, 0, 0);
3399 #endif
3400                 setWindowState(windowState() ^ Qt::WindowFullScreen);
3401                 restoreLayout();
3402                 menuBar()->show();
3403                 statusBar()->show();
3404         } else {
3405                 // bug 5274
3406                 hideDialogs("prefs", 0);
3407                 for (int i = 0; i != d.splitter_->count(); ++i)
3408                         d.tabWorkArea(i)->setFullScreen(true);
3409 #if QT_VERSION >= 0x040300
3410                 setContentsMargins(-2, -2, -2, -2);
3411 #endif
3412                 saveLayout();
3413                 setWindowState(windowState() ^ Qt::WindowFullScreen);
3414                 statusBar()->hide();
3415                 if (lyxrc.full_screen_menubar)
3416                         menuBar()->hide();
3417                 if (lyxrc.full_screen_toolbars) {
3418                         ToolbarMap::iterator end = d.toolbars_.end();
3419                         for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
3420                                 it->second->hide();
3421                 }
3422         }
3423
3424         // give dialogs like the TOC a chance to adapt
3425         updateDialogs();
3426 }
3427
3428
3429 Buffer const * GuiView::updateInset(Inset const * inset)
3430 {
3431         if (!inset)
3432                 return 0;
3433
3434         Buffer const * inset_buffer = &(inset->buffer());
3435
3436         for (int i = 0; i != d.splitter_->count(); ++i) {
3437                 GuiWorkArea * wa = d.tabWorkArea(i)->currentWorkArea();
3438                 if (!wa)
3439                         continue;
3440                 Buffer const * buffer = &(wa->bufferView().buffer());
3441                 if (inset_buffer == buffer)
3442                         wa->scheduleRedraw();
3443         }
3444         return inset_buffer;
3445 }
3446
3447
3448 void GuiView::restartCursor()
3449 {
3450         /* When we move around, or type, it's nice to be able to see
3451          * the cursor immediately after the keypress.
3452          */
3453         if (d.current_work_area_)
3454                 d.current_work_area_->startBlinkingCursor();
3455
3456         // Take this occasion to update the other GUI elements.
3457         updateDialogs();
3458         updateStatusBar();
3459 }
3460
3461
3462 void GuiView::updateCompletion(Cursor & cur, bool start, bool keep)
3463 {
3464         if (d.current_work_area_)
3465                 d.current_work_area_->completer().updateVisibility(cur, start, keep);
3466 }
3467
3468 namespace {
3469
3470 // This list should be kept in sync with the list of insets in
3471 // src/insets/Inset.cpp.  I.e., if a dialog goes with an inset, the
3472 // dialog should have the same name as the inset.
3473 // Changes should be also recorded in LFUN_DIALOG_SHOW doxygen
3474 // docs in LyXAction.cpp.
3475
3476 char const * const dialognames[] = {
3477
3478 "aboutlyx", "bibitem", "bibtex", "box", "branch", "changes", "character",
3479 "citation", "compare", "comparehistory", "document", "errorlist", "ert",
3480 "external", "file", "findreplace", "findreplaceadv", "float", "graphics",
3481 "href", "include", "index", "index_print", "info", "listings", "label", "line",
3482 "log", "mathdelimiter", "mathmatrix", "mathspace", "nomenclature",
3483 "nomencl_print", "note", "paragraph", "phantom", "prefs", "print", "ref",
3484 "sendto", "space", "spellchecker", "symbols", "tabular", "tabularcreate",
3485 "thesaurus", "texinfo", "toc", "view-source", "vspace", "wrap", "progress"};
3486
3487 char const * const * const end_dialognames =
3488         dialognames + (sizeof(dialognames) / sizeof(char *));
3489
3490 class cmpCStr {
3491 public:
3492         cmpCStr(char const * name) : name_(name) {}
3493         bool operator()(char const * other) {
3494                 return strcmp(other, name_) == 0;
3495         }
3496 private:
3497         char const * name_;
3498 };
3499
3500
3501 bool isValidName(string const & name)
3502 {
3503         return find_if(dialognames, end_dialognames,
3504                                 cmpCStr(name.c_str())) != end_dialognames;
3505 }
3506
3507 } // namespace anon
3508
3509
3510 void GuiView::resetDialogs()
3511 {
3512         // Make sure that no LFUN uses any GuiView.
3513         guiApp->setCurrentView(0);
3514         saveLayout();
3515         menuBar()->clear();
3516         constructToolbars();
3517         guiApp->menus().fillMenuBar(menuBar(), this, false);
3518         d.layout_->updateContents(true);
3519         // Now update controls with current buffer.
3520         guiApp->setCurrentView(this);
3521         restoreLayout();
3522         restartCursor();
3523 }
3524
3525
3526 Dialog * GuiView::findOrBuild(string const & name, bool hide_it)
3527 {
3528         if (!isValidName(name))
3529                 return 0;
3530
3531         map<string, DialogPtr>::iterator it = d.dialogs_.find(name);
3532
3533         if (it != d.dialogs_.end()) {
3534                 if (hide_it)
3535                         it->second->hideView();
3536                 return it->second.get();
3537         }
3538
3539         Dialog * dialog = build(name);
3540         d.dialogs_[name].reset(dialog);
3541         if (lyxrc.allow_geometry_session)
3542                 dialog->restoreSession();
3543         if (hide_it)
3544                 dialog->hideView();
3545         return dialog;
3546 }
3547
3548
3549 void GuiView::showDialog(string const & name, string const & data,
3550         Inset * inset)
3551 {
3552         triggerShowDialog(toqstr(name), toqstr(data), inset);
3553 }
3554
3555
3556 void GuiView::doShowDialog(QString const & qname, QString const & qdata,
3557         Inset * inset)
3558 {
3559         if (d.in_show_)
3560                 return;
3561
3562         const string name = fromqstr(qname);
3563         const string data = fromqstr(qdata);
3564
3565         d.in_show_ = true;
3566         try {
3567                 Dialog * dialog = findOrBuild(name, false);
3568                 if (dialog) {
3569                         bool const visible = dialog->isVisibleView();
3570                         dialog->showData(data);
3571                         if (inset && currentBufferView())
3572                                 currentBufferView()->editInset(name, inset);
3573                         // We only set the focus to the new dialog if it was not yet
3574                         // visible in order not to change the existing previous behaviour
3575                         if (visible) {
3576                                 // activateWindow is needed for floating dockviews
3577                                 dialog->asQWidget()->raise();
3578                                 dialog->asQWidget()->activateWindow();
3579                                 dialog->asQWidget()->setFocus();
3580                         }
3581                 }
3582         }
3583         catch (ExceptionMessage const & ex) {
3584                 d.in_show_ = false;
3585                 throw ex;
3586         }
3587         d.in_show_ = false;
3588 }
3589
3590
3591 bool GuiView::isDialogVisible(string const & name) const
3592 {
3593         map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3594         if (it == d.dialogs_.end())
3595                 return false;
3596         return it->second.get()->isVisibleView() && !it->second.get()->isClosing();
3597 }
3598
3599
3600 void GuiView::hideDialog(string const & name, Inset * inset)
3601 {
3602         map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3603         if (it == d.dialogs_.end())
3604                 return;
3605
3606         if (inset && currentBufferView()
3607                 && inset != currentBufferView()->editedInset(name))
3608                 return;
3609
3610         Dialog * const dialog = it->second.get();
3611         if (dialog->isVisibleView())
3612                 dialog->hideView();
3613         if (currentBufferView())
3614                 currentBufferView()->editInset(name, 0);
3615 }
3616
3617
3618 void GuiView::disconnectDialog(string const & name)
3619 {
3620         if (!isValidName(name))
3621                 return;
3622         if (currentBufferView())
3623                 currentBufferView()->editInset(name, 0);
3624 }
3625
3626
3627 void GuiView::hideAll() const
3628 {
3629         map<string, DialogPtr>::const_iterator it  = d.dialogs_.begin();
3630         map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3631
3632         for(; it != end; ++it)
3633                 it->second->hideView();
3634 }
3635
3636
3637 void GuiView::updateDialogs()
3638 {
3639         map<string, DialogPtr>::const_iterator it  = d.dialogs_.begin();
3640         map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3641
3642         for(; it != end; ++it) {
3643                 Dialog * dialog = it->second.get();
3644                 if (dialog) {
3645                         if (dialog->needBufferOpen() && !documentBufferView())
3646                                 hideDialog(fromqstr(dialog->name()), 0);
3647                         else if (dialog->isVisibleView())
3648                                 dialog->checkStatus();
3649                 }
3650         }
3651         updateToolbars();
3652         updateLayoutList();
3653 }
3654
3655 Dialog * createDialog(GuiView & lv, string const & name);
3656
3657 // will be replaced by a proper factory...
3658 Dialog * createGuiAbout(GuiView & lv);
3659 Dialog * createGuiBibtex(GuiView & lv);
3660 Dialog * createGuiChanges(GuiView & lv);
3661 Dialog * createGuiCharacter(GuiView & lv);
3662 Dialog * createGuiCitation(GuiView & lv);
3663 Dialog * createGuiCompare(GuiView & lv);
3664 Dialog * createGuiCompareHistory(GuiView & lv);
3665 Dialog * createGuiDelimiter(GuiView & lv);
3666 Dialog * createGuiDocument(GuiView & lv);
3667 Dialog * createGuiErrorList(GuiView & lv);
3668 Dialog * createGuiExternal(GuiView & lv);
3669 Dialog * createGuiGraphics(GuiView & lv);
3670 Dialog * createGuiInclude(GuiView & lv);
3671 Dialog * createGuiIndex(GuiView & lv);
3672 Dialog * createGuiLabel(GuiView & lv);
3673 Dialog * createGuiListings(GuiView & lv);
3674 Dialog * createGuiLog(GuiView & lv);
3675 Dialog * createGuiMathMatrix(GuiView & lv);
3676 Dialog * createGuiNomenclature(GuiView & lv);
3677 Dialog * createGuiNote(GuiView & lv);
3678 Dialog * createGuiParagraph(GuiView & lv);
3679 Dialog * createGuiPhantom(GuiView & lv);
3680 Dialog * createGuiPreferences(GuiView & lv);
3681 Dialog * createGuiPrint(GuiView & lv);
3682 Dialog * createGuiPrintindex(GuiView & lv);
3683 Dialog * createGuiPrintNomencl(GuiView & lv);
3684 Dialog * createGuiRef(GuiView & lv);
3685 Dialog * createGuiSearch(GuiView & lv);
3686 Dialog * createGuiSearchAdv(GuiView & lv);
3687 Dialog * createGuiSendTo(GuiView & lv);
3688 Dialog * createGuiShowFile(GuiView & lv);
3689 Dialog * createGuiSpellchecker(GuiView & lv);
3690 Dialog * createGuiSymbols(GuiView & lv);
3691 Dialog * createGuiTabularCreate(GuiView & lv);
3692 Dialog * createGuiTexInfo(GuiView & lv);
3693 Dialog * createGuiToc(GuiView & lv);
3694 Dialog * createGuiThesaurus(GuiView & lv);
3695 Dialog * createGuiHyperlink(GuiView & lv);
3696 Dialog * createGuiViewSource(GuiView & lv);
3697 Dialog * createGuiWrap(GuiView & lv);
3698 Dialog * createGuiProgressView(GuiView & lv);
3699
3700
3701
3702 Dialog * GuiView::build(string const & name)
3703 {
3704         LASSERT(isValidName(name), return 0);
3705
3706         Dialog * dialog = createDialog(*this, name);
3707         if (dialog)
3708                 return dialog;
3709
3710         if (name == "aboutlyx")
3711                 return createGuiAbout(*this);
3712         if (name == "bibtex")
3713                 return createGuiBibtex(*this);
3714         if (name == "changes")
3715                 return createGuiChanges(*this);
3716         if (name == "character")
3717                 return createGuiCharacter(*this);
3718         if (name == "citation")
3719                 return createGuiCitation(*this);
3720         if (name == "compare")
3721                 return createGuiCompare(*this);
3722         if (name == "comparehistory")
3723                 return createGuiCompareHistory(*this);
3724         if (name == "document")
3725                 return createGuiDocument(*this);
3726         if (name == "errorlist")
3727                 return createGuiErrorList(*this);
3728         if (name == "external")
3729                 return createGuiExternal(*this);
3730         if (name == "file")
3731                 return createGuiShowFile(*this);
3732         if (name == "findreplace")
3733                 return createGuiSearch(*this);
3734         if (name == "findreplaceadv")
3735                 return createGuiSearchAdv(*this);
3736         if (name == "graphics")
3737                 return createGuiGraphics(*this);
3738         if (name == "href")
3739                 return createGuiHyperlink(*this);
3740         if (name == "include")
3741                 return createGuiInclude(*this);
3742         if (name == "index")
3743                 return createGuiIndex(*this);
3744         if (name == "index_print")
3745                 return createGuiPrintindex(*this);
3746         if (name == "label")
3747                 return createGuiLabel(*this);
3748         if (name == "listings")
3749                 return createGuiListings(*this);
3750         if (name == "log")
3751                 return createGuiLog(*this);
3752         if (name == "mathdelimiter")
3753                 return createGuiDelimiter(*this);
3754         if (name == "mathmatrix")
3755                 return createGuiMathMatrix(*this);
3756         if (name == "nomenclature")
3757                 return createGuiNomenclature(*this);
3758         if (name == "nomencl_print")
3759                 return createGuiPrintNomencl(*this);
3760         if (name == "note")
3761                 return createGuiNote(*this);
3762         if (name == "paragraph")
3763                 return createGuiParagraph(*this);
3764         if (name == "phantom")
3765                 return createGuiPhantom(*this);
3766         if (name == "prefs")
3767                 return createGuiPreferences(*this);
3768         if (name == "print")
3769                 return createGuiPrint(*this);
3770         if (name == "ref")
3771                 return createGuiRef(*this);
3772         if (name == "sendto")
3773                 return createGuiSendTo(*this);
3774         if (name == "spellchecker")
3775                 return createGuiSpellchecker(*this);
3776         if (name == "symbols")
3777                 return createGuiSymbols(*this);
3778         if (name == "tabularcreate")
3779                 return createGuiTabularCreate(*this);
3780         if (name == "texinfo")
3781                 return createGuiTexInfo(*this);
3782         if (name == "thesaurus")
3783                 return createGuiThesaurus(*this);
3784         if (name == "toc")
3785                 return createGuiToc(*this);
3786         if (name == "view-source")
3787                 return createGuiViewSource(*this);
3788         if (name == "wrap")
3789                 return createGuiWrap(*this);
3790         if (name == "progress")
3791                 return createGuiProgressView(*this);
3792
3793         return 0;
3794 }
3795
3796
3797 } // namespace frontend
3798 } // namespace lyx
3799
3800 #include "moc_GuiView.cpp"