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