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