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