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