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