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