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