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