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