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