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