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