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