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