]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiView.cpp
Dissect closeBuffer() and saveBufferIfNeeded().
[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 "Menus.h"
29 #include "TocModel.h"
30
31 #include "qt_helpers.h"
32
33 #include "frontends/alert.h"
34
35 #include "buffer_funcs.h"
36 #include "Buffer.h"
37 #include "BufferList.h"
38 #include "BufferParams.h"
39 #include "BufferView.h"
40 #include "Converter.h"
41 #include "Cursor.h"
42 #include "CutAndPaste.h"
43 #include "Encoding.h"
44 #include "ErrorList.h"
45 #include "Format.h"
46 #include "FuncStatus.h"
47 #include "FuncRequest.h"
48 #include "Intl.h"
49 #include "Layout.h"
50 #include "Lexer.h"
51 #include "LyXFunc.h"
52 #include "LyX.h"
53 #include "LyXRC.h"
54 #include "LyXVC.h"
55 #include "Paragraph.h"
56 #include "SpellChecker.h"
57 #include "TextClass.h"
58 #include "Text.h"
59 #include "Toolbars.h"
60 #include "version.h"
61
62 #include "support/convert.h"
63 #include "support/debug.h"
64 #include "support/ExceptionMessage.h"
65 #include "support/FileName.h"
66 #include "support/filetools.h"
67 #include "support/gettext.h"
68 #include "support/ForkedCalls.h"
69 #include "support/lassert.h"
70 #include "support/lstrings.h"
71 #include "support/os.h"
72 #include "support/Package.h"
73 #include "support/Timeout.h"
74
75 #include <QAction>
76 #include <QApplication>
77 #include <QCloseEvent>
78 #include <QDebug>
79 #include <QDesktopWidget>
80 #include <QDragEnterEvent>
81 #include <QDropEvent>
82 #include <QList>
83 #include <QMenu>
84 #include <QMenuBar>
85 #include <QPainter>
86 #include <QPixmap>
87 #include <QPixmapCache>
88 #include <QPoint>
89 #include <QPushButton>
90 #include <QSettings>
91 #include <QShowEvent>
92 #include <QSplitter>
93 #include <QStackedWidget>
94 #include <QStatusBar>
95 #include <QTimer>
96 #include <QToolBar>
97 #include <QUrl>
98 #include <QScrollBar>
99
100 #include <boost/bind.hpp>
101
102 #ifdef HAVE_SYS_TIME_H
103 # include <sys/time.h>
104 #endif
105 #ifdef HAVE_UNISTD_H
106 # include <unistd.h>
107 #endif
108
109 using namespace std;
110 using namespace lyx::support;
111
112 namespace lyx {
113 namespace frontend {
114
115 namespace {
116
117 class BackgroundWidget : public QWidget
118 {
119 public:
120         BackgroundWidget()
121         {
122                 LYXERR(Debug::GUI, "show banner: " << lyxrc.show_banner);
123                 /// The text to be written on top of the pixmap
124                 QString const text = lyx_version ?
125                         qt_("version ") + lyx_version : qt_("unknown version");
126                 splash_ = getPixmap("images/", "banner", "png");
127
128                 QPainter pain(&splash_);
129                 pain.setPen(QColor(0, 0, 0));
130                 QFont font;
131                 // The font used to display the version info
132                 font.setStyleHint(QFont::SansSerif);
133                 font.setWeight(QFont::Bold);
134                 font.setPointSize(int(toqstr(lyxrc.font_sizes[FONT_SIZE_LARGE]).toDouble()));
135                 pain.setFont(font);
136                 pain.drawText(260, 15, text);
137         }
138
139         void paintEvent(QPaintEvent *)
140         {
141                 int x = (width() - splash_.width()) / 2;
142                 int y = (height() - splash_.height()) / 2;
143                 QPainter pain(this);
144                 pain.drawPixmap(x, y, splash_);
145         }
146
147 private:
148         QPixmap splash_;
149 };
150
151
152 /// Toolbar store providing access to individual toolbars by name.
153 typedef std::map<std::string, GuiToolbar *> ToolbarMap;
154
155 typedef boost::shared_ptr<Dialog> DialogPtr;
156
157 } // namespace anon
158
159
160 struct GuiView::GuiViewPrivate
161 {
162         GuiViewPrivate()
163                 : current_work_area_(0), current_main_work_area_(0),
164                 layout_(0), autosave_timeout_(5000),
165                 in_show_(false)
166         {
167                 // hardcode here the platform specific icon size
168                 smallIconSize = 14;  // scaling problems
169                 normalIconSize = 20; // ok, default
170                 bigIconSize = 26;    // better for some math icons
171
172                 splitter_ = new QSplitter;
173                 bg_widget_ = new BackgroundWidget;
174                 stack_widget_ = new QStackedWidget;
175                 stack_widget_->addWidget(bg_widget_);
176                 stack_widget_->addWidget(splitter_);
177                 setBackground();
178         }
179
180         ~GuiViewPrivate()
181         {
182                 delete splitter_;
183                 delete bg_widget_;
184                 delete stack_widget_;
185         }
186
187         QMenu * toolBarPopup(GuiView * parent)
188         {
189                 // FIXME: translation
190                 QMenu * menu = new QMenu(parent);
191                 QActionGroup * iconSizeGroup = new QActionGroup(parent);
192
193                 QAction * smallIcons = new QAction(iconSizeGroup);
194                 smallIcons->setText(qt_("Small-sized icons"));
195                 smallIcons->setCheckable(true);
196                 QObject::connect(smallIcons, SIGNAL(triggered()),
197                         parent, SLOT(smallSizedIcons()));
198                 menu->addAction(smallIcons);
199
200                 QAction * normalIcons = new QAction(iconSizeGroup);
201                 normalIcons->setText(qt_("Normal-sized icons"));
202                 normalIcons->setCheckable(true);
203                 QObject::connect(normalIcons, SIGNAL(triggered()),
204                         parent, SLOT(normalSizedIcons()));
205                 menu->addAction(normalIcons);
206
207                 QAction * bigIcons = new QAction(iconSizeGroup);
208                 bigIcons->setText(qt_("Big-sized icons"));
209                 bigIcons->setCheckable(true);
210                 QObject::connect(bigIcons, SIGNAL(triggered()),
211                         parent, SLOT(bigSizedIcons()));
212                 menu->addAction(bigIcons);
213
214                 unsigned int cur = parent->iconSize().width();
215                 if ( cur == parent->d.smallIconSize)
216                         smallIcons->setChecked(true);
217                 else if (cur == parent->d.normalIconSize)
218                         normalIcons->setChecked(true);
219                 else if (cur == parent->d.bigIconSize)
220                         bigIcons->setChecked(true);
221
222                 return menu;
223         }
224
225         void setBackground()
226         {
227                 stack_widget_->setCurrentWidget(bg_widget_);
228                 bg_widget_->setUpdatesEnabled(true);
229         }
230
231         TabWorkArea * tabWorkArea(int i)
232         {
233                 return dynamic_cast<TabWorkArea *>(splitter_->widget(i));
234         }
235
236         TabWorkArea * currentTabWorkArea()
237         {
238                 if (splitter_->count() == 1)
239                         // The first TabWorkArea is always the first one, if any.
240                         return tabWorkArea(0);
241
242                 for (int i = 0; i != splitter_->count(); ++i) {
243                         TabWorkArea * twa = tabWorkArea(i);
244                         if (current_main_work_area_ == twa->currentWorkArea())
245                                 return twa;
246                 }
247
248                 // None has the focus so we just take the first one.
249                 return tabWorkArea(0);
250         }
251
252 public:
253         GuiWorkArea * current_work_area_;
254         GuiWorkArea * current_main_work_area_;
255         QSplitter * splitter_;
256         QStackedWidget * stack_widget_;
257         BackgroundWidget * bg_widget_;
258         /// view's toolbars
259         ToolbarMap toolbars_;
260         /// The main layout box.
261         /** 
262          * \warning Don't Delete! The layout box is actually owned by
263          * whichever toolbar contains it. All the GuiView class needs is a
264          * means of accessing it.
265          *
266          * FIXME: replace that with a proper model so that we are not limited
267          * to only one dialog.
268          */
269         GuiLayoutBox * layout_;
270
271         ///
272         map<string, Inset *> open_insets_;
273
274         ///
275         map<string, DialogPtr> dialogs_;
276
277         unsigned int smallIconSize;
278         unsigned int normalIconSize;
279         unsigned int bigIconSize;
280         ///
281         QTimer statusbar_timer_;
282         /// auto-saving of buffers
283         Timeout autosave_timeout_;
284         /// flag against a race condition due to multiclicks, see bug #1119
285         bool in_show_;
286
287         ///
288         TocModels toc_models_;
289 };
290
291
292 GuiView::GuiView(int id)
293         : d(*new GuiViewPrivate), id_(id), closing_(false)
294 {
295         // GuiToolbars *must* be initialised before the menu bar.
296         normalSizedIcons(); // at least on Mac the default is 32 otherwise, which is huge
297         constructToolbars();
298
299         // set ourself as the current view. This is needed for the menu bar
300         // filling, at least for the static special menu item on Mac. Otherwise
301         // they are greyed out.
302         theLyXFunc().setLyXView(this);
303         
304         // Fill up the menu bar.
305         guiApp->menus().fillMenuBar(menuBar(), this, true);
306
307         setCentralWidget(d.stack_widget_);
308
309         // Start autosave timer
310         if (lyxrc.autosave) {
311                 d.autosave_timeout_.timeout.connect(boost::bind(&GuiView::autoSave, this));
312                 d.autosave_timeout_.setTimeout(lyxrc.autosave * 1000);
313                 d.autosave_timeout_.start();
314         }
315         connect(&d.statusbar_timer_, SIGNAL(timeout()),
316                 this, SLOT(clearMessage()));
317
318         // We don't want to keep the window in memory if it is closed.
319         setAttribute(Qt::WA_DeleteOnClose, true);
320
321 #if (!defined(Q_WS_WIN) && !defined(Q_WS_MACX))
322         // assign an icon to main form. We do not do it under Qt/Win or Qt/Mac,
323         // since the icon is provided in the application bundle.
324         setWindowIcon(getPixmap("images/", "lyx", "png"));
325 #endif
326
327         // For Drag&Drop.
328         setAcceptDrops(true);
329
330         statusBar()->setSizeGripEnabled(true);
331
332         // Forbid too small unresizable window because it can happen
333         // with some window manager under X11.
334         setMinimumSize(300, 200);
335
336         if (lyxrc.allow_geometry_session) {
337                 // Now take care of session management.
338                 if (restoreLayout())
339                         return;
340         }
341
342         // no session handling, default to a sane size.
343         setGeometry(50, 50, 690, 510);
344         initToolbars();
345
346         // clear session data if any.
347         QSettings settings;
348         settings.remove("views");
349 }
350
351
352 GuiView::~GuiView()
353 {
354         delete &d;
355 }
356
357
358 void GuiView::saveLayout() const
359 {
360         QSettings settings;
361         settings.beginGroup("views");
362         settings.beginGroup(QString::number(id_));
363 #ifdef Q_WS_X11
364         settings.setValue("pos", pos());
365         settings.setValue("size", size());
366 #else
367         settings.setValue("geometry", saveGeometry());
368 #endif
369         settings.setValue("layout", saveState(0));
370         settings.setValue("icon_size", iconSize());
371 }
372
373
374 bool GuiView::restoreLayout()
375 {
376         QSettings settings;
377         settings.beginGroup("views");
378         settings.beginGroup(QString::number(id_));
379         QString const icon_key = "icon_size";
380         if (!settings.contains(icon_key))
381                 return false;
382
383         //code below is skipped when when ~/.config/LyX is (re)created
384         setIconSize(settings.value(icon_key).toSize());
385 #ifdef Q_WS_X11
386         QPoint pos = settings.value("pos", QPoint(50, 50)).toPoint();
387         QSize size = settings.value("size", QSize(690, 510)).toSize();
388         resize(size);
389         move(pos);
390 #else
391         // Work-around for bug #6034: the window ends up in an undetermined
392         // state when trying to restore a maximized window when it is
393         // already maximized.
394         if (!(windowState() & Qt::WindowMaximized))
395                 if (!restoreGeometry(settings.value("geometry").toByteArray()))
396                         setGeometry(50, 50, 690, 510);
397 #endif
398         // Make sure layout is correctly oriented.
399         setLayoutDirection(qApp->layoutDirection());
400
401         // Allow the toc and view-source dock widget to be restored if needed.
402         Dialog * dialog;
403         if ((dialog = findOrBuild("toc", true)))
404                 // see bug 5082. At least setup title and enabled state.
405                 // Visibility will be adjusted by restoreState below.
406                 dialog->prepareView();
407         if ((dialog = findOrBuild("view-source", true)))
408                 dialog->prepareView();
409
410         if (!restoreState(settings.value("layout").toByteArray(), 0))
411                 initToolbars();
412         updateDialogs();
413         return true;
414 }
415
416
417 GuiToolbar * GuiView::toolbar(string const & name)
418 {
419         ToolbarMap::iterator it = d.toolbars_.find(name);
420         if (it != d.toolbars_.end())
421                 return it->second;
422
423         LYXERR(Debug::GUI, "Toolbar::display: no toolbar named " << name);
424         message(bformat(_("Unknown toolbar \"%1$s\""), from_utf8(name)));
425         return 0;
426 }
427
428
429 void GuiView::constructToolbars()
430 {
431         ToolbarMap::iterator it = d.toolbars_.begin();
432         for (; it != d.toolbars_.end(); ++it)
433                 delete it->second;
434         d.toolbars_.clear();
435         d.layout_ = 0;
436
437         // extracts the toolbars from the backend
438         Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
439         Toolbars::Infos::iterator end = guiApp->toolbars().end();
440         for (; cit != end; ++cit)
441                 d.toolbars_[cit->name] =  new GuiToolbar(*cit, *this);
442 }
443
444
445 void GuiView::initToolbars()
446 {
447         // extracts the toolbars from the backend
448         Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
449         Toolbars::Infos::iterator end = guiApp->toolbars().end();
450         for (; cit != end; ++cit) {
451                 GuiToolbar * tb = toolbar(cit->name);
452                 if (!tb)
453                         continue;
454                 int const visibility = guiApp->toolbars().defaultVisibility(cit->name);
455                 bool newline = true;
456                 tb->setVisible(false);
457                 tb->setVisibility(visibility);
458
459                 if (visibility & Toolbars::TOP) {
460                         if (newline)
461                                 addToolBarBreak(Qt::TopToolBarArea);
462                         addToolBar(Qt::TopToolBarArea, tb);
463                 }
464
465                 if (visibility & Toolbars::BOTTOM) {
466                         // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
467 #if (QT_VERSION >= 0x040202)
468                         addToolBarBreak(Qt::BottomToolBarArea);
469 #endif
470                         addToolBar(Qt::BottomToolBarArea, tb);
471                 }
472
473                 if (visibility & Toolbars::LEFT) {
474                         // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
475 #if (QT_VERSION >= 0x040202)
476                         addToolBarBreak(Qt::LeftToolBarArea);
477 #endif
478                         addToolBar(Qt::LeftToolBarArea, tb);
479                 }
480
481                 if (visibility & Toolbars::RIGHT) {
482                         // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
483 #if (QT_VERSION >= 0x040202)
484                         addToolBarBreak(Qt::RightToolBarArea);
485 #endif
486                         addToolBar(Qt::RightToolBarArea, tb);
487                 }
488
489                 if (visibility & Toolbars::ON)
490                         tb->setVisible(true);
491         }
492 }
493
494
495 TocModels & GuiView::tocModels()
496 {
497         return d.toc_models_;
498 }
499
500
501 void GuiView::setFocus()
502 {
503         LYXERR(Debug::DEBUG, "GuiView::setFocus()" << this);
504         // Make sure LyXFunc points to the correct view.
505         guiApp->setCurrentView(this);
506         theLyXFunc().setLyXView(this);
507         QMainWindow::setFocus();
508         if (d.current_work_area_)
509                 d.current_work_area_->setFocus();
510 }
511
512
513 QMenu * GuiView::createPopupMenu()
514 {
515         return d.toolBarPopup(this);
516 }
517
518
519 void GuiView::showEvent(QShowEvent * e)
520 {
521         LYXERR(Debug::GUI, "Passed Geometry "
522                 << size().height() << "x" << size().width()
523                 << "+" << pos().x() << "+" << pos().y());
524
525         if (d.splitter_->count() == 0)
526                 // No work area, switch to the background widget.
527                 d.setBackground();
528
529         QMainWindow::showEvent(e);
530 }
531
532
533 /** Destroy only all tabbed WorkAreas. Destruction of other WorkAreas
534  ** is responsibility of the container (e.g., dialog)
535  **/
536 void GuiView::closeEvent(QCloseEvent * close_event)
537 {
538         LYXERR(Debug::DEBUG, "GuiView::closeEvent()");
539         closing_ = true;
540
541         // it can happen that this event arrives without selecting the view,
542         // e.g. when clicking the close button on a background window.
543         setFocus();
544         if (!closeBufferAll(true)) {
545                 closing_ = false;
546                 close_event->ignore();
547                 return;
548         }
549
550         // Make sure that nothing will use this close to be closed View.
551         guiApp->unregisterView(this);
552
553         if (isFullScreen()) {
554                 // Switch off fullscreen before closing.
555                 toggleFullScreen();
556                 updateDialogs();
557         }
558
559         // Make sure the timer time out will not trigger a statusbar update.
560         d.statusbar_timer_.stop();
561
562         // Saving fullscreen requires additional tweaks in the toolbar code.
563         // It wouldn't also work under linux natively.
564         if (lyxrc.allow_geometry_session) {
565                 // Save this window geometry and layout.
566                 saveLayout();
567                 // Then the toolbar private states.
568                 ToolbarMap::iterator end = d.toolbars_.end();
569                 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
570                         it->second->saveSession();
571                 // Now take care of all other dialogs:
572                 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
573                 for (; it!= d.dialogs_.end(); ++it)
574                         it->second->saveSession();
575         }
576
577         close_event->accept();
578 }
579
580
581 bool GuiView::closeBufferAll(bool tolastopened)
582 {
583         GuiWorkArea * active_wa = currentMainWorkArea();
584         setCurrentWorkArea(active_wa);
585
586         // We might be in a situation that there is still a tabWorkArea, but
587         // there are no tabs anymore. This can happen when we get here after a 
588         // TabWorkArea::lastWorkAreaRemoved() signal. Therefore we count how
589         // many TabWorkArea's have no documents anymore.
590         int empty_twa = 0;
591
592         // We have to call count() each time, because it can happen that
593         // more than one splitter will disappear in one iteration (bug 5998).
594         for (; d.splitter_->count() > empty_twa; ) {
595                 TabWorkArea * twa = d.tabWorkArea(empty_twa);
596                                 
597                 int twa_count = twa->count();
598                 if (twa->count() == 0)
599                         ++empty_twa;
600
601                 for (; twa_count; --twa_count) {
602                         twa->setCurrentIndex(twa_count-1);
603
604                         GuiWorkArea * wa = twa->currentWorkArea();
605                         bool const is_active_wa = active_wa == wa;
606                         Buffer * b = &wa->bufferView().buffer();
607                         if (b->parent()) {
608                                 // This is a child document, just close the tab
609                                 // after saving but keep the file loaded.
610                                 if (!closeBuffer(*b, tolastopened, is_active_wa))
611                                         return false;
612                                 continue;
613                         }
614
615                         vector<Buffer *> clist = b->getChildren();
616                         for (vector<Buffer *>::const_iterator it = clist.begin();
617                                  it != clist.end(); ++it) {
618                                 if ((*it)->isClean())
619                                         continue;
620                                 Buffer * c = *it;
621                                 // If a child is dirty, do not close
622                                 // without user intervention
623                                 if (!closeBuffer(*c, false))
624                                         return false;
625                         }
626
627                         QList<int> const ids = guiApp->viewIds();
628                         for (int i = 0; i != ids.size(); ++i) {
629                                 if (id_ == ids[i])
630                                         continue;
631                                 if (guiApp->view(ids[i]).workArea(*b)) {
632                                         // FIXME 1: should we put an alert box here
633                                         // that the buffer is viewed elsewhere?
634                                         // FIXME 2: should we try to save this buffer in any case?
635                                         //saveBuffer(b);
636
637                                         // This buffer is also opened in another view, so
638                                         // close the associated work area...
639                                         removeWorkArea(wa);
640                                         // ... but don't close the buffer.
641                                         b = 0;
642                                         break;
643                                 }
644                         }
645                         // closeBuffer() needs buffer workArea still alive and
646                         // set as currrent one, and destroys it
647                         if (b && !closeBuffer(*b, tolastopened, is_active_wa))
648                                 return false;
649                 }
650         }
651         return true;
652 }
653
654
655 void GuiView::dragEnterEvent(QDragEnterEvent * event)
656 {
657         if (event->mimeData()->hasUrls())
658                 event->accept();
659         /// \todo Ask lyx-devel is this is enough:
660         /// if (event->mimeData()->hasFormat("text/plain"))
661         ///     event->acceptProposedAction();
662 }
663
664
665 void GuiView::dropEvent(QDropEvent * event)
666 {
667         QList<QUrl> files = event->mimeData()->urls();
668         if (files.isEmpty())
669                 return;
670
671         LYXERR(Debug::GUI, "GuiView::dropEvent: got URLs!");
672         for (int i = 0; i != files.size(); ++i) {
673                 string const file = os::internal_path(fromqstr(
674                         files.at(i).toLocalFile()));
675                 if (!file.empty()) {
676                         // Asynchronously post the event. DropEvent usually come
677                         // from the BufferView. But reloading a file might close
678                         // the BufferView from within its own event handler.
679                         guiApp->dispatchDelayed(FuncRequest(LFUN_FILE_OPEN, file));
680                         event->accept();
681                 }
682         }
683 }
684
685
686 void GuiView::message(docstring const & str)
687 {
688         if (ForkedProcess::iAmAChild())
689                 return;
690
691         statusBar()->showMessage(toqstr(str));
692         d.statusbar_timer_.stop();
693         d.statusbar_timer_.start(3000);
694 }
695
696
697 void GuiView::smallSizedIcons()
698 {
699         setIconSize(QSize(d.smallIconSize, d.smallIconSize));
700 }
701
702
703 void GuiView::normalSizedIcons()
704 {
705         setIconSize(QSize(d.normalIconSize, d.normalIconSize));
706 }
707
708
709 void GuiView::bigSizedIcons()
710 {
711         setIconSize(QSize(d.bigIconSize, d.bigIconSize));
712 }
713
714
715 void GuiView::clearMessage()
716 {
717         if (!hasFocus())
718                 return;
719         theLyXFunc().setLyXView(this);
720         statusBar()->showMessage(toqstr(theLyXFunc().viewStatusMessage()));
721         d.statusbar_timer_.stop();
722 }
723
724
725 void GuiView::updateWindowTitle(GuiWorkArea * wa)
726 {
727         if (wa != d.current_work_area_)
728                 return;
729         setWindowTitle(qt_("LyX: ") + wa->windowTitle());
730         setWindowIconText(wa->windowIconText());
731 }
732
733
734 void GuiView::on_currentWorkAreaChanged(GuiWorkArea * wa)
735 {
736         disconnectBuffer();
737         disconnectBufferView();
738         connectBufferView(wa->bufferView());
739         connectBuffer(wa->bufferView().buffer());
740         d.current_work_area_ = wa;
741         QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
742                 this, SLOT(updateWindowTitle(GuiWorkArea *)));
743         updateWindowTitle(wa);
744
745         structureChanged();
746
747         // The document settings needs to be reinitialised.
748         updateDialog("document", "");
749
750         // Buffer-dependent dialogs must be updated. This is done here because
751         // some dialogs require buffer()->text.
752         updateDialogs();
753 }
754
755
756 void GuiView::on_lastWorkAreaRemoved()
757 {
758         if (closing_)
759                 // We already are in a close event. Nothing more to do.
760                 return;
761
762         if (d.splitter_->count() > 1)
763                 // We have a splitter so don't close anything.
764                 return;
765
766         // Reset and updates the dialogs.
767         d.toc_models_.reset(0);
768         updateDialog("document", "");
769         updateDialogs();
770
771         resetWindowTitleAndIconText();
772
773         if (lyxrc.open_buffers_in_tabs)
774                 // Nothing more to do, the window should stay open.
775                 return;
776
777         if (guiApp->viewIds().size() > 1) {
778                 close();
779                 return;
780         }
781
782 #ifdef Q_WS_MACX
783         // On Mac we also close the last window because the application stay
784         // resident in memory. On other platforms we don't close the last
785         // window because this would quit the application.
786         close();
787 #endif
788 }
789
790
791 void GuiView::updateStatusBar()
792 {
793         // let the user see the explicit message
794         if (d.statusbar_timer_.isActive())
795                 return;
796
797         theLyXFunc().setLyXView(this);
798         statusBar()->showMessage(toqstr(theLyXFunc().viewStatusMessage()));
799 }
800
801
802 bool GuiView::hasFocus() const
803 {
804         return qApp->activeWindow() == this;
805 }
806
807
808 bool GuiView::event(QEvent * e)
809 {
810         switch (e->type())
811         {
812         // Useful debug code:
813         //case QEvent::ActivationChange:
814         //case QEvent::WindowDeactivate:
815         //case QEvent::Paint:
816         //case QEvent::Enter:
817         //case QEvent::Leave:
818         //case QEvent::HoverEnter:
819         //case QEvent::HoverLeave:
820         //case QEvent::HoverMove:
821         //case QEvent::StatusTip:
822         //case QEvent::DragEnter:
823         //case QEvent::DragLeave:
824         //case QEvent::Drop:
825         //      break;
826
827         case QEvent::WindowActivate: {
828                 if (this == guiApp->currentView()) {
829                         setFocus();
830                         return QMainWindow::event(e);
831                 }
832                 guiApp->setCurrentView(this);
833                 theLyXFunc().setLyXView(this);
834                 if (d.current_work_area_) {
835                         BufferView & bv = d.current_work_area_->bufferView();
836                         connectBufferView(bv);
837                         connectBuffer(bv.buffer());
838                         // The document structure, name and dialogs might have
839                         // changed in another view.
840                         structureChanged();
841                         // The document settings needs to be reinitialised.
842                         updateDialog("document", "");
843                         updateDialogs();
844                 } else {
845                         resetWindowTitleAndIconText();
846                 }
847                 setFocus();
848                 return QMainWindow::event(e);
849         }
850
851         case QEvent::ShortcutOverride: {
852
853 // See bug 4888
854 #if (!defined Q_WS_X11) || (QT_VERSION >= 0x040500)
855                 if (isFullScreen() && menuBar()->isHidden()) {
856                         QKeyEvent * ke = static_cast<QKeyEvent*>(e);
857                         // FIXME: we should also try to detect special LyX shortcut such as
858                         // Alt-P and Alt-M. Right now there is a hack in
859                         // GuiWorkArea::processKeySym() that hides again the menubar for
860                         // those cases.
861                         if (ke->modifiers() & Qt::AltModifier && ke->key() != Qt::Key_Alt) {
862                                 menuBar()->show();
863                                 return QMainWindow::event(e);
864                         }
865                 }
866 #endif
867
868                 if (d.current_work_area_)
869                         // Nothing special to do.
870                         return QMainWindow::event(e);
871
872                 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
873                 // Let Qt handle menu access and the Tab keys to navigate keys to navigate
874                 // between controls.
875                 if (ke->modifiers() & Qt::AltModifier || ke->key() == Qt::Key_Tab 
876                         || ke->key() == Qt::Key_Backtab)
877                         return QMainWindow::event(e);
878
879                 // Allow processing of shortcuts that are allowed even when no Buffer
880                 // is viewed.
881                 theLyXFunc().setLyXView(this);
882                 KeySymbol sym;
883                 setKeySymbol(&sym, ke);
884                 theLyXFunc().processKeySym(sym, q_key_state(ke->modifiers()));
885                 e->accept();
886                 return true;
887         }
888
889         default:
890                 return QMainWindow::event(e);
891         }
892 }
893
894 void GuiView::resetWindowTitleAndIconText()
895 {
896     setWindowTitle(qt_("LyX"));
897     setWindowIconText(qt_("LyX"));
898 }
899
900 bool GuiView::focusNextPrevChild(bool /*next*/)
901 {
902         setFocus();
903         return true;
904 }
905
906
907 void GuiView::setBusy(bool busy)
908 {
909         if (d.current_work_area_) {
910                 d.current_work_area_->setUpdatesEnabled(!busy);
911                 if (busy)
912                         d.current_work_area_->stopBlinkingCursor();
913                 else
914                         d.current_work_area_->startBlinkingCursor();
915         }
916
917         if (busy)
918                 QApplication::setOverrideCursor(Qt::WaitCursor);
919         else
920                 QApplication::restoreOverrideCursor();
921 }
922
923
924 GuiWorkArea * GuiView::workArea(Buffer & buffer)
925 {
926         if (currentWorkArea()
927             && &currentWorkArea()->bufferView().buffer() == &buffer)
928                 return (GuiWorkArea *) currentWorkArea();
929         if (TabWorkArea * twa = d.currentTabWorkArea())
930                 return twa->workArea(buffer);
931         return 0;
932 }
933
934
935 GuiWorkArea * GuiView::addWorkArea(Buffer & buffer)
936 {
937         // Automatically create a TabWorkArea if there are none yet.
938         TabWorkArea * tab_widget = d.splitter_->count() 
939                 ? d.currentTabWorkArea() : addTabWorkArea();
940         return tab_widget->addWorkArea(buffer, *this);
941 }
942
943
944 TabWorkArea * GuiView::addTabWorkArea()
945 {
946         TabWorkArea * twa = new TabWorkArea;
947         QObject::connect(twa, SIGNAL(currentWorkAreaChanged(GuiWorkArea *)),
948                 this, SLOT(on_currentWorkAreaChanged(GuiWorkArea *)));
949         QObject::connect(twa, SIGNAL(lastWorkAreaRemoved()),
950                          this, SLOT(on_lastWorkAreaRemoved()));
951
952         d.splitter_->addWidget(twa);
953         d.stack_widget_->setCurrentWidget(d.splitter_);
954         return twa;
955 }
956
957
958 GuiWorkArea const * GuiView::currentWorkArea() const
959 {
960         return d.current_work_area_;
961 }
962
963
964 GuiWorkArea * GuiView::currentWorkArea()
965 {
966         return d.current_work_area_;
967 }
968
969
970 GuiWorkArea const * GuiView::currentMainWorkArea() const
971 {
972         if (d.currentTabWorkArea() == NULL)
973                 return NULL;
974         return d.currentTabWorkArea()->currentWorkArea();
975 }
976
977
978 GuiWorkArea * GuiView::currentMainWorkArea()
979 {
980         if (d.currentTabWorkArea() == NULL)
981                 return NULL;
982         return d.currentTabWorkArea()->currentWorkArea();
983 }
984
985
986 void GuiView::setCurrentWorkArea(GuiWorkArea * wa)
987 {
988         LYXERR(Debug::DEBUG, "Setting current wa: " << wa << endl);
989         if (wa == NULL) {
990                 d.current_work_area_ = NULL;
991                 d.setBackground();
992                 return;
993         }
994         GuiWorkArea * old_gwa = theGuiApp()->currentView()->currentWorkArea();
995         if (old_gwa == wa)
996                 return;
997
998         if (view())
999                 cap::saveSelection(view()->cursor());
1000
1001         theGuiApp()->setCurrentView(this);
1002         d.current_work_area_ = wa;
1003         for (int i = 0; i != d.splitter_->count(); ++i) {
1004                 if (d.tabWorkArea(i)->setCurrentWorkArea(wa)) {
1005                         //if (d.current_main_work_area_)
1006                         //      d.current_main_work_area_->setFrameStyle(QFrame::NoFrame);
1007                         d.current_main_work_area_ = wa;
1008                         //d.current_main_work_area_->setFrameStyle(QFrame::Box | QFrame::Plain);
1009                         //d.current_main_work_area_->setLineWidth(2);
1010                         LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() << ", Current main wa: " << currentMainWorkArea());
1011                         return;
1012                 }
1013         }
1014         LYXERR(Debug::DEBUG, "This is not a tabbed wa");
1015         on_currentWorkAreaChanged(wa);
1016         BufferView & bv = wa->bufferView();
1017         bv.cursor().fixIfBroken();
1018         bv.updateMetrics();
1019         wa->setUpdatesEnabled(true);
1020         LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() << ", Current main wa: " << currentMainWorkArea());
1021 }
1022
1023
1024 void GuiView::removeWorkArea(GuiWorkArea * wa)
1025 {
1026         LASSERT(wa, return);
1027         if (wa == d.current_work_area_) {
1028                 disconnectBuffer();
1029                 disconnectBufferView();
1030                 d.current_work_area_ = 0;
1031                 d.current_main_work_area_ = 0;
1032         }
1033
1034         bool found_twa = false;
1035         for (int i = 0; i != d.splitter_->count(); ++i) {
1036                 TabWorkArea * twa = d.tabWorkArea(i);
1037                 if (twa->removeWorkArea(wa)) {
1038                         // Found in this tab group, and deleted the GuiWorkArea.
1039                         found_twa = true;
1040                         if (twa->count() != 0) {
1041                                 if (d.current_work_area_ == 0)
1042                                         // This means that we are closing the current GuiWorkArea, so
1043                                         // switch to the next GuiWorkArea in the found TabWorkArea.
1044                                         setCurrentWorkArea(twa->currentWorkArea());
1045                         } else {
1046                                 // No more WorkAreas in this tab group, so delete it.
1047                                 delete twa;
1048                         }
1049                         break;
1050                 }
1051         }
1052
1053         // It is not a tabbed work area (i.e., the search work area), so it
1054         // should be deleted by other means.
1055         LASSERT(found_twa, /* */);
1056
1057         if (d.current_work_area_ == 0) {
1058                 if (d.splitter_->count() != 0) {
1059                         TabWorkArea * twa = d.currentTabWorkArea();
1060                         setCurrentWorkArea(twa->currentWorkArea());
1061                 } else {
1062                         // No more work areas, switch to the background widget.
1063                         setCurrentWorkArea(0);
1064                 }
1065         }
1066 }
1067
1068
1069 void GuiView::setLayoutDialog(GuiLayoutBox * layout)
1070 {
1071         d.layout_ = layout;
1072 }
1073
1074
1075 void GuiView::updateLayoutList()
1076 {
1077         if (d.layout_)
1078                 d.layout_->updateContents(false);
1079 }
1080
1081
1082 void GuiView::updateToolbars()
1083 {
1084         ToolbarMap::iterator end = d.toolbars_.end();
1085         if (d.current_work_area_) {
1086                 bool const math =
1087                         d.current_work_area_->bufferView().cursor().inMathed();
1088                 bool const table =
1089                         lyx::getStatus(FuncRequest(LFUN_LAYOUT_TABULAR)).enabled();
1090                 bool const review =
1091                         lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).enabled() &&
1092                         lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).onoff(true);
1093                 bool const mathmacrotemplate =
1094                         lyx::getStatus(FuncRequest(LFUN_IN_MATHMACROTEMPLATE)).enabled();
1095
1096                 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1097                         it->second->update(math, table, review, mathmacrotemplate);
1098         } else
1099                 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1100                         it->second->update(false, false, false, false);
1101 }
1102
1103
1104 Buffer * GuiView::buffer()
1105 {
1106         if (d.current_work_area_)
1107                 return &d.current_work_area_->bufferView().buffer();
1108         return 0;
1109 }
1110
1111
1112 Buffer const * GuiView::buffer() const
1113 {
1114         if (d.current_work_area_)
1115                 return &d.current_work_area_->bufferView().buffer();
1116         return 0;
1117 }
1118
1119
1120 void GuiView::setBuffer(Buffer * newBuffer)
1121 {
1122         LYXERR(Debug::DEBUG, "Setting buffer: " << newBuffer << std::endl);
1123         LASSERT(newBuffer, return);
1124         setBusy(true);
1125
1126         GuiWorkArea * wa = workArea(*newBuffer);
1127         if (wa == 0) {
1128                 newBuffer->masterBuffer()->updateLabels();
1129                 wa = addWorkArea(*newBuffer);
1130         } else {
1131                 //Disconnect the old buffer...there's no new one.
1132                 disconnectBuffer();
1133         }
1134         connectBuffer(*newBuffer);
1135         connectBufferView(wa->bufferView());
1136         setCurrentWorkArea(wa);
1137
1138         setBusy(false);
1139 }
1140
1141
1142 void GuiView::connectBuffer(Buffer & buf)
1143 {
1144         buf.setGuiDelegate(this);
1145 }
1146
1147
1148 void GuiView::disconnectBuffer()
1149 {
1150         if (d.current_work_area_)
1151                 d.current_work_area_->bufferView().setGuiDelegate(0);
1152 }
1153
1154
1155 void GuiView::connectBufferView(BufferView & bv)
1156 {
1157         bv.setGuiDelegate(this);
1158 }
1159
1160
1161 void GuiView::disconnectBufferView()
1162 {
1163         if (d.current_work_area_)
1164                 d.current_work_area_->bufferView().setGuiDelegate(0);
1165 }
1166
1167
1168 void GuiView::errors(string const & error_type, bool from_master)
1169 {
1170         ErrorList & el = from_master ? 
1171                 buffer()->masterBuffer()->errorList(error_type)
1172                 : buffer()->errorList(error_type);
1173         string data = error_type;
1174         if (from_master)
1175                 data = "from_master|" + error_type;
1176         if (!el.empty())
1177                 showDialog("errorlist", data);
1178 }
1179
1180
1181 void GuiView::updateTocItem(std::string const & type, DocIterator const & dit)
1182 {
1183         d.toc_models_.updateItem(toqstr(type), dit);
1184 }
1185
1186
1187 void GuiView::structureChanged()
1188 {
1189         d.toc_models_.reset(view());
1190         // Navigator needs more than a simple update in this case. It needs to be
1191         // rebuilt.
1192         updateDialog("toc", "");
1193 }
1194
1195
1196 void GuiView::updateDialog(string const & name, string const & data)
1197 {
1198         if (!isDialogVisible(name))
1199                 return;
1200
1201         map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
1202         if (it == d.dialogs_.end())
1203                 return;
1204
1205         Dialog * const dialog = it->second.get();
1206         if (dialog->isVisibleView())
1207                 dialog->initialiseParams(data);
1208 }
1209
1210
1211 BufferView * GuiView::view()
1212 {
1213         return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1214 }
1215
1216
1217 void GuiView::autoSave()
1218 {
1219         LYXERR(Debug::INFO, "Running autoSave()");
1220
1221         if (buffer())
1222                 view()->buffer().autoSave();
1223 }
1224
1225
1226 void GuiView::resetAutosaveTimers()
1227 {
1228         if (lyxrc.autosave)
1229                 d.autosave_timeout_.restart();
1230 }
1231
1232
1233 bool GuiView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1234 {
1235         bool enable = true;
1236         Buffer * buf = buffer();
1237
1238         if (cmd.origin == FuncRequest::TOC) {
1239                 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
1240                 FuncStatus fs;
1241                 if (toc->getStatus(view()->cursor(), cmd, fs))
1242                         flag |= fs;
1243                 else
1244                         flag.setEnabled(false);
1245                 return true;
1246         }
1247
1248         switch(cmd.action) {
1249         case LFUN_BUFFER_WRITE:
1250                 enable = buf && (buf->isUnnamed() || !buf->isClean());
1251                 break;
1252
1253         case LFUN_BUFFER_WRITE_AS:
1254                 enable = buf;
1255                 break;
1256
1257         case LFUN_BUFFER_CLOSE_ALL: {
1258                 enable = false;
1259                 BufferList::iterator it = theBufferList().begin();
1260                 BufferList::iterator end = theBufferList().end();
1261                 int visible_buffers = 0;
1262                 for (; it != end; ++it) {
1263                         if (workArea(**it))
1264                                 ++visible_buffers;
1265                         if (visible_buffers > 1) {
1266                                 enable = true;
1267                                 break;
1268                         }
1269                 }
1270                 break;
1271         }
1272
1273         case LFUN_SPLIT_VIEW:
1274                 if (cmd.getArg(0) == "vertical")
1275                         enable = buf && (d.splitter_->count() == 1 ||
1276                                          d.splitter_->orientation() == Qt::Vertical);
1277                 else
1278                         enable = buf && (d.splitter_->count() == 1 ||
1279                                          d.splitter_->orientation() == Qt::Horizontal);
1280                 break;
1281
1282         case LFUN_CLOSE_TAB_GROUP:
1283                 enable = d.currentTabWorkArea();
1284                 break;
1285
1286         case LFUN_TOOLBAR_TOGGLE:
1287                 if (GuiToolbar * t = toolbar(cmd.getArg(0)))
1288                         flag.setOnOff(t->isVisible());
1289                 break;
1290
1291         case LFUN_UI_TOGGLE:
1292                 flag.setOnOff(isFullScreen());
1293                 break;
1294
1295         case LFUN_DIALOG_TOGGLE:
1296                 flag.setOnOff(isDialogVisible(cmd.getArg(0)));
1297                 // fall through to set "enable"
1298         case LFUN_DIALOG_SHOW: {
1299                 string const name = cmd.getArg(0);
1300                 if (!buf)
1301                         enable = name == "aboutlyx"
1302                                 || name == "file" //FIXME: should be removed.
1303                                 || name == "prefs"
1304                                 || name == "texinfo";
1305                 else if (name == "print")
1306                         enable = buf->isExportable("dvi")
1307                                 && lyxrc.print_command != "none";
1308                 else if (name == "character" || name == "symbols") {
1309                         if (buf->isReadonly() || !view() || !view()->cursor().inTexted())
1310                                 enable = false;
1311                         else {
1312                                 // FIXME we should consider passthru
1313                                 // paragraphs too.
1314                                 Inset const & in = view()->cursor().inset();
1315                                 enable = !in.getLayout().isPassThru();
1316                         }
1317                 }
1318                 else if (name == "latexlog")
1319                         enable = FileName(buf->logName()).isReadableFile();
1320                 else if (name == "spellchecker")
1321                         enable = theSpellChecker() && !buf->isReadonly();
1322                 else if (name == "vclog")
1323                         enable = buf->lyxvc().inUse();
1324                 break;
1325         }
1326
1327         case LFUN_DIALOG_UPDATE: {
1328                 string const name = cmd.getArg(0);
1329                 if (!buf)
1330                         enable = name == "prefs";
1331                 break;
1332         }
1333
1334         case LFUN_INSET_APPLY: {
1335                 string const name = cmd.getArg(0);
1336                 Inset * inset = getOpenInset(name);
1337                 if (inset) {
1338                         FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument());
1339                         FuncStatus fs;
1340                         if (!inset->getStatus(view()->cursor(), fr, fs)) {
1341                                 // Every inset is supposed to handle this
1342                                 LASSERT(false, break);
1343                         }
1344                         flag |= fs;
1345                 } else {
1346                         FuncRequest fr(LFUN_INSET_INSERT, cmd.argument());
1347                         flag |= lyx::getStatus(fr);
1348                 }
1349                 enable = flag.enabled();
1350                 break;
1351         }
1352
1353         case LFUN_COMPLETION_INLINE:
1354                 if (!d.current_work_area_
1355                     || !d.current_work_area_->completer().inlinePossible(view()->cursor()))
1356                     enable = false;
1357                 break;
1358
1359         case LFUN_COMPLETION_POPUP:
1360                 if (!d.current_work_area_
1361                     || !d.current_work_area_->completer().popupPossible(view()->cursor()))
1362                     enable = false;
1363                 break;
1364
1365         case LFUN_COMPLETION_COMPLETE:
1366                 if (!d.current_work_area_
1367                         || !d.current_work_area_->completer().inlinePossible(view()->cursor()))
1368                     enable = false;
1369                 break;
1370
1371         case LFUN_COMPLETION_ACCEPT:
1372                 if (!d.current_work_area_
1373                     || (!d.current_work_area_->completer().popupVisible()
1374                         && !d.current_work_area_->completer().inlineVisible()
1375                         && !d.current_work_area_->completer().completionAvailable()))
1376                         enable = false;
1377                 break;
1378
1379         case LFUN_COMPLETION_CANCEL:
1380                 if (!d.current_work_area_
1381                     || (!d.current_work_area_->completer().popupVisible()
1382                         && !d.current_work_area_->completer().inlineVisible()))
1383                         enable = false;
1384                 break;
1385
1386         case LFUN_BUFFER_ZOOM_OUT:
1387                 enable = buf && lyxrc.zoom > 10;
1388                 break;
1389
1390         case LFUN_BUFFER_ZOOM_IN:
1391                 enable = buf;
1392                 break;
1393
1394         default:
1395                 return false;
1396         }
1397
1398         if (!enable)
1399                 flag.setEnabled(false);
1400
1401         return true;
1402 }
1403
1404
1405 static FileName selectTemplateFile()
1406 {
1407         FileDialog dlg(qt_("Select template file"));
1408         dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1409         dlg.setButton1(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
1410
1411         FileDialog::Result result = dlg.open(toqstr(lyxrc.template_path),
1412                              QStringList(qt_("LyX Documents (*.lyx)")));
1413
1414         if (result.first == FileDialog::Later)
1415                 return FileName();
1416         if (result.second.isEmpty())
1417                 return FileName();
1418         return FileName(fromqstr(result.second));
1419 }
1420
1421
1422 Buffer * GuiView::loadDocument(FileName const & filename, bool tolastfiles)
1423 {
1424         setBusy(true);
1425
1426         Buffer * newBuffer = checkAndLoadLyXFile(filename);
1427
1428         if (!newBuffer) {
1429                 message(_("Document not loaded."));
1430                 setBusy(false);
1431                 return 0;
1432         }
1433         
1434         setBuffer(newBuffer);
1435
1436         // scroll to the position when the file was last closed
1437         if (lyxrc.use_lastfilepos) {
1438                 LastFilePosSection::FilePos filepos =
1439                         theSession().lastFilePos().load(filename);
1440                 view()->moveToPosition(filepos.pit, filepos.pos, 0, 0);
1441         }
1442
1443         if (tolastfiles)
1444                 theSession().lastFiles().add(filename);
1445
1446         setBusy(false);
1447         return newBuffer;
1448 }
1449
1450
1451 void GuiView::openDocument(string const & fname)
1452 {
1453         string initpath = lyxrc.document_path;
1454
1455         if (buffer()) {
1456                 string const trypath = buffer()->filePath();
1457                 // If directory is writeable, use this as default.
1458                 if (FileName(trypath).isDirWritable())
1459                         initpath = trypath;
1460         }
1461
1462         string filename;
1463
1464         if (fname.empty()) {
1465                 FileDialog dlg(qt_("Select document to open"), LFUN_FILE_OPEN);
1466                 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1467                 dlg.setButton2(qt_("Examples|#E#e"),
1468                                 toqstr(addPath(package().system_support().absFilename(), "examples")));
1469
1470                 QStringList filter(qt_("LyX Documents (*.lyx)"));
1471                 filter << qt_("LyX-1.3.x Documents (*.lyx13)")
1472                         << qt_("LyX-1.4.x Documents (*.lyx14)")
1473                         << qt_("LyX-1.5.x Documents (*.lyx15)")
1474                         << qt_("LyX-1.6.x Documents (*.lyx16)");
1475                 FileDialog::Result result =
1476                         dlg.open(toqstr(initpath), filter);
1477
1478                 if (result.first == FileDialog::Later)
1479                         return;
1480
1481                 filename = fromqstr(result.second);
1482
1483                 // check selected filename
1484                 if (filename.empty()) {
1485                         message(_("Canceled."));
1486                         return;
1487                 }
1488         } else
1489                 filename = fname;
1490
1491         // get absolute path of file and add ".lyx" to the filename if
1492         // necessary. 
1493         FileName const fullname = 
1494                         fileSearch(string(), filename, "lyx", support::may_not_exist);
1495         if (!fullname.empty())
1496                 filename = fullname.absFilename();
1497
1498         if (!fullname.onlyPath().isDirectory()) {
1499                 Alert::warning(_("Invalid filename"),
1500                                 bformat(_("The directory in the given path\n%1$s\ndoes not exist."),
1501                                 from_utf8(fullname.absFilename())));
1502                 return;
1503         }
1504         // if the file doesn't exist, let the user create one
1505         if (!fullname.exists()) {
1506                 // the user specifically chose this name. Believe him.
1507                 Buffer * const b = newFile(filename, string(), true);
1508                 if (b)
1509                         setBuffer(b);
1510                 return;
1511         }
1512
1513         docstring const disp_fn = makeDisplayPath(filename);
1514         message(bformat(_("Opening document %1$s..."), disp_fn));
1515
1516         docstring str2;
1517         Buffer * buf = loadDocument(fullname);
1518         if (buf) {
1519                 buf->updateLabels();
1520                 setBuffer(buf);
1521                 buf->errors("Parse");
1522                 str2 = bformat(_("Document %1$s opened."), disp_fn);
1523                 if (buf->lyxvc().inUse())
1524                         str2 += " " + from_utf8(buf->lyxvc().versionString()) +
1525                                 " " + _("Version control detected.");
1526         } else {
1527                 str2 = bformat(_("Could not open document %1$s"), disp_fn);
1528         }
1529         message(str2);
1530 }
1531
1532 // FIXME: clean that
1533 static bool import(GuiView * lv, FileName const & filename,
1534         string const & format, ErrorList & errorList)
1535 {
1536         FileName const lyxfile(support::changeExtension(filename.absFilename(), ".lyx"));
1537
1538         string loader_format;
1539         vector<string> loaders = theConverters().loaders();
1540         if (find(loaders.begin(), loaders.end(), format) == loaders.end()) {
1541                 for (vector<string>::const_iterator it = loaders.begin();
1542                      it != loaders.end(); ++it) {
1543                         if (!theConverters().isReachable(format, *it))
1544                                 continue;
1545
1546                         string const tofile =
1547                                 support::changeExtension(filename.absFilename(),
1548                                 formats.extension(*it));
1549                         if (!theConverters().convert(0, filename, FileName(tofile),
1550                                 filename, format, *it, errorList))
1551                                 return false;
1552                         loader_format = *it;
1553                         break;
1554                 }
1555                 if (loader_format.empty()) {
1556                         frontend::Alert::error(_("Couldn't import file"),
1557                                      bformat(_("No information for importing the format %1$s."),
1558                                          formats.prettyName(format)));
1559                         return false;
1560                 }
1561         } else
1562                 loader_format = format;
1563
1564         if (loader_format == "lyx") {
1565                 Buffer * buf = lv->loadDocument(lyxfile);
1566                 if (!buf)
1567                         return false;
1568                 buf->updateLabels();
1569                 lv->setBuffer(buf);
1570                 buf->errors("Parse");
1571         } else {
1572                 Buffer * const b = newFile(lyxfile.absFilename(), string(), true);
1573                 if (!b)
1574                         return false;
1575                 lv->setBuffer(b);
1576                 bool as_paragraphs = loader_format == "textparagraph";
1577                 string filename2 = (loader_format == format) ? filename.absFilename()
1578                         : support::changeExtension(filename.absFilename(),
1579                                           formats.extension(loader_format));
1580                 lv->view()->insertPlaintextFile(FileName(filename2), as_paragraphs);
1581                 theLyXFunc().setLyXView(lv);
1582                 lyx::dispatch(FuncRequest(LFUN_MARK_OFF));
1583         }
1584
1585         return true;
1586 }
1587
1588
1589 void GuiView::importDocument(string const & argument)
1590 {
1591         string format;
1592         string filename = split(argument, format, ' ');
1593
1594         LYXERR(Debug::INFO, format << " file: " << filename);
1595
1596         // need user interaction
1597         if (filename.empty()) {
1598                 string initpath = lyxrc.document_path;
1599
1600                 Buffer const * buf = buffer();
1601                 if (buf) {
1602                         string const trypath = buf->filePath();
1603                         // If directory is writeable, use this as default.
1604                         if (FileName(trypath).isDirWritable())
1605                                 initpath = trypath;
1606                 }
1607
1608                 docstring const text = bformat(_("Select %1$s file to import"),
1609                         formats.prettyName(format));
1610
1611                 FileDialog dlg(toqstr(text), LFUN_BUFFER_IMPORT);
1612                 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1613                 dlg.setButton2(qt_("Examples|#E#e"),
1614                         toqstr(addPath(package().system_support().absFilename(), "examples")));
1615
1616                 docstring filter = formats.prettyName(format);
1617                 filter += " (*.";
1618                 // FIXME UNICODE
1619                 filter += from_utf8(formats.extension(format));
1620                 filter += ')';
1621
1622                 FileDialog::Result result =
1623                         dlg.open(toqstr(initpath), fileFilters(toqstr(filter)));
1624
1625                 if (result.first == FileDialog::Later)
1626                         return;
1627
1628                 filename = fromqstr(result.second);
1629
1630                 // check selected filename
1631                 if (filename.empty())
1632                         message(_("Canceled."));
1633         }
1634
1635         if (filename.empty())
1636                 return;
1637
1638         // get absolute path of file
1639         FileName const fullname(support::makeAbsPath(filename));
1640
1641         FileName const lyxfile(support::changeExtension(fullname.absFilename(), ".lyx"));
1642
1643         // Check if the document already is open
1644         Buffer * buf = theBufferList().getBuffer(lyxfile);
1645         if (buf) {
1646                 setBuffer(buf);
1647                 if (!closeBuffer()) {
1648                         message(_("Canceled."));
1649                         return;
1650                 }
1651         }
1652
1653         docstring const displaypath = makeDisplayPath(lyxfile.absFilename(), 30);
1654
1655         // if the file exists already, and we didn't do
1656         // -i lyx thefile.lyx, warn
1657         if (lyxfile.exists() && fullname != lyxfile) {
1658
1659                 docstring text = bformat(_("The document %1$s already exists.\n\n"
1660                         "Do you want to overwrite that document?"), displaypath);
1661                 int const ret = Alert::prompt(_("Overwrite document?"),
1662                         text, 0, 1, _("&Overwrite"), _("&Cancel"));
1663
1664                 if (ret == 1) {
1665                         message(_("Canceled."));
1666                         return;
1667                 }
1668         }
1669
1670         message(bformat(_("Importing %1$s..."), displaypath));
1671         ErrorList errorList;
1672         if (import(this, fullname, format, errorList))
1673                 message(_("imported."));
1674         else
1675                 message(_("file not imported!"));
1676
1677         // FIXME (Abdel 12/08/06): Is there a need to display the error list here?
1678 }
1679
1680
1681 void GuiView::newDocument(string const & filename, bool from_template)
1682 {
1683         FileName initpath(lyxrc.document_path);
1684         Buffer * buf = buffer();
1685         if (buf) {
1686                 FileName const trypath(buf->filePath());
1687                 // If directory is writeable, use this as default.
1688                 if (trypath.isDirWritable())
1689                         initpath = trypath;
1690         }
1691
1692         string templatefile;
1693         if (from_template) {
1694                 templatefile = selectTemplateFile().absFilename();
1695                 if (templatefile.empty())
1696                         return;
1697         }
1698         
1699         Buffer * b;
1700         if (filename.empty())
1701                 b = newUnnamedFile(templatefile, initpath);
1702         else
1703                 b = newFile(filename, templatefile, true);
1704
1705         if (b)
1706                 setBuffer(b);
1707
1708         // If no new document could be created, it is unsure 
1709         // whether there is a valid BufferView.
1710         if (view())
1711                 // Ensure the cursor is correctly positioned on screen.
1712                 view()->showCursor();
1713 }
1714
1715
1716 void GuiView::insertLyXFile(docstring const & fname)
1717 {
1718         BufferView * bv = view();
1719         if (!bv)
1720                 return;
1721
1722         // FIXME UNICODE
1723         FileName filename(to_utf8(fname));
1724         
1725         if (!filename.empty()) {
1726                 bv->insertLyXFile(filename);
1727                 return;
1728         }
1729
1730         // Launch a file browser
1731         // FIXME UNICODE
1732         string initpath = lyxrc.document_path;
1733         string const trypath = bv->buffer().filePath();
1734         // If directory is writeable, use this as default.
1735         if (FileName(trypath).isDirWritable())
1736                 initpath = trypath;
1737
1738         // FIXME UNICODE
1739         FileDialog dlg(qt_("Select LyX document to insert"), LFUN_FILE_INSERT);
1740         dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1741         dlg.setButton2(qt_("Examples|#E#e"),
1742                 toqstr(addPath(package().system_support().absFilename(),
1743                 "examples")));
1744
1745         FileDialog::Result result = dlg.open(toqstr(initpath),
1746                              QStringList(qt_("LyX Documents (*.lyx)")));
1747
1748         if (result.first == FileDialog::Later)
1749                 return;
1750
1751         // FIXME UNICODE
1752         filename.set(fromqstr(result.second));
1753
1754         // check selected filename
1755         if (filename.empty()) {
1756                 // emit message signal.
1757                 message(_("Canceled."));
1758                 return;
1759         }
1760
1761         bv->insertLyXFile(filename);
1762 }
1763
1764
1765 void GuiView::insertPlaintextFile(docstring const & fname,
1766         bool asParagraph)
1767 {
1768         BufferView * bv = view();
1769         if (!bv)
1770                 return;
1771
1772         if (!fname.empty() && !FileName::isAbsolute(to_utf8(fname))) {
1773                 message(_("Absolute filename expected."));
1774                 return;
1775         }
1776
1777         // FIXME UNICODE
1778         FileName filename(to_utf8(fname));
1779         
1780         if (!filename.empty()) {
1781                 bv->insertPlaintextFile(filename, asParagraph);
1782                 return;
1783         }
1784
1785         FileDialog dlg(qt_("Select file to insert"), (asParagraph ?
1786                 LFUN_FILE_INSERT_PLAINTEXT_PARA : LFUN_FILE_INSERT_PLAINTEXT));
1787
1788         FileDialog::Result result = dlg.open(toqstr(bv->buffer().filePath()),
1789                 QStringList(qt_("All Files (*)")));
1790
1791         if (result.first == FileDialog::Later)
1792                 return;
1793
1794         // FIXME UNICODE
1795         filename.set(fromqstr(result.second));
1796
1797         // check selected filename
1798         if (filename.empty()) {
1799                 // emit message signal.
1800                 message(_("Canceled."));
1801                 return;
1802         }
1803
1804         bv->insertPlaintextFile(filename, asParagraph);
1805 }
1806
1807
1808 bool GuiView::renameBuffer(Buffer & b, docstring const & newname)
1809 {
1810         FileName fname = b.fileName();
1811         FileName const oldname = fname;
1812
1813         if (!newname.empty()) {
1814                 // FIXME UNICODE
1815                 fname = support::makeAbsPath(to_utf8(newname), oldname.onlyPath().absFilename());
1816         } else {
1817                 // Switch to this Buffer.
1818                 setBuffer(&b);
1819
1820                 // No argument? Ask user through dialog.
1821                 // FIXME UNICODE
1822                 FileDialog dlg(qt_("Choose a filename to save document as"),
1823                                    LFUN_BUFFER_WRITE_AS);
1824                 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1825                 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
1826
1827                 if (!isLyXFilename(fname.absFilename()))
1828                         fname.changeExtension(".lyx");
1829
1830                 FileDialog::Result result =
1831                         dlg.save(toqstr(fname.onlyPath().absFilename()),
1832                                QStringList(qt_("LyX Documents (*.lyx)")),
1833                                      toqstr(fname.onlyFileName()));
1834
1835                 if (result.first == FileDialog::Later)
1836                         return false;
1837
1838                 fname.set(fromqstr(result.second));
1839
1840                 if (fname.empty())
1841                         return false;
1842
1843                 if (!isLyXFilename(fname.absFilename()))
1844                         fname.changeExtension(".lyx");
1845         }
1846
1847         if (FileName(fname).exists()) {
1848                 docstring const file = makeDisplayPath(fname.absFilename(), 30);
1849                 docstring text = bformat(_("The document %1$s already "
1850                                            "exists.\n\nDo you want to "
1851                                            "overwrite that document?"), 
1852                                          file);
1853                 int const ret = Alert::prompt(_("Overwrite document?"),
1854                         text, 0, 2, _("&Overwrite"), _("&Rename"), _("&Cancel"));
1855                 switch (ret) {
1856                 case 0: break;
1857                 case 1: return renameBuffer(b, docstring());
1858                 case 2: return false;
1859                 }
1860         }
1861
1862         FileName oldauto = b.getAutosaveFilename();
1863
1864         // Ok, change the name of the buffer
1865         b.setFileName(fname.absFilename());
1866         b.markDirty();
1867         bool unnamed = b.isUnnamed();
1868         b.setUnnamed(false);
1869         b.saveCheckSum(fname);
1870
1871         // bring the autosave file with us, just in case.
1872         b.moveAutosaveFile(oldauto);
1873         
1874         if (!saveBuffer(b)) {
1875                 oldauto = b.getAutosaveFilename();
1876                 b.setFileName(oldname.absFilename());
1877                 b.setUnnamed(unnamed);
1878                 b.saveCheckSum(oldname);
1879                 b.moveAutosaveFile(oldauto);
1880                 return false;
1881         }
1882
1883         return true;
1884 }
1885
1886
1887 bool GuiView::saveBuffer(Buffer & b)
1888 {
1889         if (workArea(b) && workArea(b)->inDialogMode())
1890                 return true;
1891
1892         if (b.isUnnamed())
1893                 return renameBuffer(b, docstring());
1894
1895         if (b.save()) {
1896                 theSession().lastFiles().add(b.fileName());
1897                 return true;
1898         }
1899
1900         // Switch to this Buffer.
1901         setBuffer(&b);
1902
1903         // FIXME: we don't tell the user *WHY* the save failed !!
1904         docstring const file = makeDisplayPath(b.absFileName(), 30);
1905         docstring text = bformat(_("The document %1$s could not be saved.\n\n"
1906                                    "Do you want to rename the document and "
1907                                    "try again?"), file);
1908         int const ret = Alert::prompt(_("Rename and save?"),
1909                 text, 0, 2, _("&Rename"), _("&Retry"), _("&Cancel"));
1910         switch (ret) {
1911         case 0:
1912                 if (!renameBuffer(b, docstring()))
1913                         return false;
1914                 break;
1915         case 1:
1916                 break;
1917         case 2:
1918                 return false;
1919         }
1920
1921         return saveBuffer(b);
1922 }
1923
1924
1925 bool GuiView::closeBuffer()
1926 {
1927         Buffer * buf = buffer();
1928         return buf && closeBuffer(*buf);
1929 }
1930
1931
1932 bool GuiView::closeBuffer(Buffer & buf, bool tolastopened, bool mark_active)
1933 {
1934         // goto bookmark to update bookmark pit.
1935         //FIXME: we should update only the bookmarks related to this buffer!
1936         LYXERR(Debug::DEBUG, "GuiView::closeBuffer()");
1937         for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
1938                 theLyXFunc().gotoBookmark(i+1, false, false);
1939
1940         if (saveBufferIfNeeded(buf)) {
1941                 // save in sessions if requested
1942                 // do not save childs if their master
1943                 // is opened as well
1944                 if (tolastopened)
1945                         theSession().lastOpened().add(buf.fileName(), mark_active);
1946                 if (buf.parent())
1947                         // Don't close child documents.
1948                         removeWorkArea(currentMainWorkArea());
1949                 else
1950                         theBufferList().release(&buf);
1951                 return true;
1952         }
1953         return false;
1954 }
1955
1956
1957 bool GuiView::saveBufferIfNeeded(Buffer & buf)
1958 {
1959         if (buf.isClean() || buf.paragraphs().empty())
1960                 return true;
1961
1962         // Switch to this Buffer.
1963         setBuffer(&buf);
1964
1965         docstring file;
1966         // FIXME: Unicode?
1967         if (buf.isUnnamed())
1968                 file = from_utf8(buf.fileName().onlyFileName());
1969         else
1970                 file = buf.fileName().displayName(30);
1971
1972         // Bring this window to top before asking questions.
1973         raise();
1974         activateWindow();
1975
1976         docstring const text = bformat(_("The document %1$s has unsaved changes."
1977                 "\n\nDo you want to save the document or discard the changes?"), file);
1978         int const ret = Alert::prompt(_("Save changed document?"),
1979                 text, 0, 2, _("&Save"), _("&Discard"), _("&Cancel"));
1980
1981         switch (ret) {
1982         case 0:
1983                 if (!saveBuffer(buf))
1984                         return false;
1985                 break;
1986         case 1:
1987                 // if we crash after this we could
1988                 // have no autosave file but I guess
1989                 // this is really improbable (Jug)
1990                 buf.removeAutosaveFile();
1991                 break;
1992         case 2:
1993                 return false;
1994         }
1995         return true;
1996 }
1997
1998
1999 void GuiView::gotoNextOrPreviousBuffer(NextOrPrevious np)
2000 {
2001         Buffer * const curbuf = buffer();
2002         Buffer * nextbuf = curbuf;
2003         while (true) {
2004                 if (np == NEXTBUFFER)
2005                         nextbuf = theBufferList().next(nextbuf);
2006                 else
2007                         nextbuf = theBufferList().previous(nextbuf);
2008                 if (nextbuf == curbuf)
2009                         break;
2010                 if (nextbuf == 0) {
2011                         nextbuf = curbuf;
2012                         break;
2013                 }
2014                 if (workArea(*nextbuf))
2015                         break;
2016         }
2017         setBuffer(nextbuf);
2018 }
2019
2020
2021 bool GuiView::dispatch(FuncRequest const & cmd)
2022 {
2023         BufferView * bv = view();
2024         // By default we won't need any update.
2025         if (bv)
2026                 bv->cursor().updateFlags(Update::None);
2027         bool dispatched = true;
2028
2029         if (cmd.origin == FuncRequest::TOC) {
2030                 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
2031                 toc->doDispatch(bv->cursor(), cmd);
2032                 return true;
2033         }
2034
2035         switch(cmd.action) {
2036                 case LFUN_BUFFER_IMPORT:
2037                         importDocument(to_utf8(cmd.argument()));
2038                         break;
2039
2040                 case LFUN_BUFFER_SWITCH:
2041                         if (FileName::isAbsolute(to_utf8(cmd.argument()))) {
2042                                 Buffer * buffer = 
2043                                         theBufferList().getBuffer(FileName(to_utf8(cmd.argument())));
2044                                 if (buffer)
2045                                         setBuffer(buffer);
2046                                 else
2047                                         bv->cursor().message(_("Document not loaded"));
2048                         }
2049                         break;
2050
2051                 case LFUN_BUFFER_NEXT:
2052                         gotoNextOrPreviousBuffer(NEXTBUFFER);
2053                         break;
2054
2055                 case LFUN_BUFFER_PREVIOUS:
2056                         gotoNextOrPreviousBuffer(PREVBUFFER);
2057                         break;
2058
2059                 case LFUN_COMMAND_EXECUTE: {
2060                         bool const show_it = cmd.argument() != "off";
2061                         // FIXME: this is a hack, "minibuffer" should not be
2062                         // hardcoded.
2063                         if (GuiToolbar * t = toolbar("minibuffer")) {
2064                                 t->setVisible(show_it);
2065                                 if (show_it && t->commandBuffer())
2066                                         t->commandBuffer()->setFocus();
2067                         }
2068                         break;
2069                 }
2070                 case LFUN_DROP_LAYOUTS_CHOICE:
2071                         if (d.layout_)
2072                                 d.layout_->showPopup();
2073                         break;
2074
2075                 case LFUN_MENU_OPEN:
2076                         if (QMenu * menu = guiApp->menus().menu(toqstr(cmd.argument()), *this))
2077                                 menu->exec(QCursor::pos());
2078                         break;
2079
2080                 case LFUN_FILE_INSERT:
2081                         insertLyXFile(cmd.argument());
2082                         break;
2083                 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
2084                         insertPlaintextFile(cmd.argument(), true);
2085                         break;
2086
2087                 case LFUN_FILE_INSERT_PLAINTEXT:
2088                         insertPlaintextFile(cmd.argument(), false);
2089                         break;
2090
2091                 case LFUN_BUFFER_WRITE:
2092                         if (bv)
2093                                 saveBuffer(bv->buffer());
2094                         break;
2095
2096                 case LFUN_BUFFER_WRITE_AS:
2097                         if (bv)
2098                                 renameBuffer(bv->buffer(), cmd.argument());
2099                         break;
2100
2101                 case LFUN_BUFFER_WRITE_ALL: {
2102                         Buffer * first = theBufferList().first();
2103                         if (!first)
2104                                 break;
2105                         message(_("Saving all documents..."));
2106                         // We cannot use a for loop as the buffer list cycles.
2107                         Buffer * b = first;
2108                         do {
2109                                 if (!b->isClean()) {
2110                                         saveBuffer(*b);
2111                                         LYXERR(Debug::ACTION, "Saved " << b->absFileName());
2112                                 }
2113                                 b = theBufferList().next(b);
2114                         } while (b != first); 
2115                         message(_("All documents saved."));
2116                         break;
2117                 }
2118
2119                 case LFUN_TOOLBAR_TOGGLE: {
2120                         string const name = cmd.getArg(0);
2121                         if (GuiToolbar * t = toolbar(name))
2122                                 t->toggle();
2123                         break;
2124                 }
2125
2126                 case LFUN_DIALOG_UPDATE: {
2127                         string const name = to_utf8(cmd.argument());
2128                         // Can only update a dialog connected to an existing inset
2129                         Inset * inset = getOpenInset(name);
2130                         if (inset) {
2131                                 FuncRequest fr(LFUN_INSET_DIALOG_UPDATE, cmd.argument());
2132                                 inset->dispatch(view()->cursor(), fr);
2133                         } else if (name == "paragraph") {
2134                                 lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
2135                         } else if (name == "prefs" || name == "document") {
2136                                 updateDialog(name, string());
2137                         }
2138                         break;
2139                 }
2140
2141                 case LFUN_DIALOG_TOGGLE: {
2142                         if (isDialogVisible(cmd.getArg(0)))
2143                                 dispatch(FuncRequest(LFUN_DIALOG_HIDE, cmd.argument()));
2144                         else
2145                                 dispatch(FuncRequest(LFUN_DIALOG_SHOW, cmd.argument()));
2146                         break;
2147                 }
2148
2149                 case LFUN_DIALOG_DISCONNECT_INSET:
2150                         disconnectDialog(to_utf8(cmd.argument()));
2151                         break;
2152
2153                 case LFUN_DIALOG_HIDE: {
2154                         guiApp->hideDialogs(to_utf8(cmd.argument()), 0);
2155                         break;
2156                 }
2157
2158                 case LFUN_DIALOG_SHOW: {
2159                         string const name = cmd.getArg(0);
2160                         string data = trim(to_utf8(cmd.argument()).substr(name.size()));
2161
2162                         if (name == "character") {
2163                                 data = freefont2string();
2164                                 if (!data.empty())
2165                                         showDialog("character", data);
2166                         } else if (name == "latexlog") {
2167                                 Buffer::LogType type; 
2168                                 string const logfile = buffer()->logName(&type);
2169                                 switch (type) {
2170                                 case Buffer::latexlog:
2171                                         data = "latex ";
2172                                         break;
2173                                 case Buffer::buildlog:
2174                                         data = "literate ";
2175                                         break;
2176                                 }
2177                                 data += Lexer::quoteString(logfile);
2178                                 showDialog("log", data);
2179                         } else if (name == "vclog") {
2180                                 string const data = "vc " +
2181                                         Lexer::quoteString(buffer()->lyxvc().getLogFile());
2182                                 showDialog("log", data);
2183                         } else if (name == "symbols") {
2184                                 data = bv->cursor().getEncoding()->name();
2185                                 if (!data.empty())
2186                                         showDialog("symbols", data);
2187                         // bug 5274
2188                         } else if (name == "prefs" && isFullScreen()) {
2189                                 FuncRequest fr(LFUN_INSET_INSERT, "fullscreen");
2190                                 lfunUiToggle(fr);
2191                                 showDialog("prefs", data);
2192                         } else
2193                                 showDialog(name, data);
2194                         break;
2195                 }
2196
2197                 case LFUN_INSET_APPLY: {
2198                         string const name = cmd.getArg(0);
2199                         Inset * inset = getOpenInset(name);
2200                         if (inset) {
2201                                 // put cursor in front of inset.
2202                                 if (!view()->setCursorFromInset(inset)) {
2203                                         LASSERT(false, break);
2204                                 }
2205                                 
2206                                 // useful if we are called from a dialog.
2207                                 view()->cursor().beginUndoGroup();
2208                                 view()->cursor().recordUndo();
2209                                 FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument());
2210                                 inset->dispatch(view()->cursor(), fr);
2211                                 view()->cursor().endUndoGroup();
2212                         } else {
2213                                 FuncRequest fr(LFUN_INSET_INSERT, cmd.argument());
2214                                 lyx::dispatch(fr);
2215                         }
2216                         break;
2217                 }
2218
2219                 case LFUN_UI_TOGGLE:
2220                         lfunUiToggle(cmd);
2221                         // Make sure the keyboard focus stays in the work area.
2222                         setFocus();
2223                         break;
2224
2225                 case LFUN_SPLIT_VIEW:
2226                         if (Buffer * buf = buffer()) {
2227                                 string const orientation = cmd.getArg(0);
2228                                 d.splitter_->setOrientation(orientation == "vertical"
2229                                         ? Qt::Vertical : Qt::Horizontal);
2230                                 TabWorkArea * twa = addTabWorkArea();
2231                                 GuiWorkArea * wa = twa->addWorkArea(*buf, *this);
2232                                 setCurrentWorkArea(wa);
2233                         }
2234                         break;
2235
2236                 case LFUN_CLOSE_TAB_GROUP:
2237                         if (TabWorkArea * twa = d.currentTabWorkArea()) {
2238                                 delete twa;
2239                                 twa = d.currentTabWorkArea();
2240                                 // Switch to the next GuiWorkArea in the found TabWorkArea.
2241                                 if (twa) {
2242                                         // Make sure the work area is up to date.
2243                                         setCurrentWorkArea(twa->currentWorkArea());
2244                                 } else {
2245                                         setCurrentWorkArea(0);
2246                                 }
2247                         }
2248                         break;
2249                         
2250                 case LFUN_COMPLETION_INLINE:
2251                         if (d.current_work_area_)
2252                                 d.current_work_area_->completer().showInline();
2253                         break;
2254
2255                 case LFUN_COMPLETION_POPUP:
2256                         if (d.current_work_area_)
2257                                 d.current_work_area_->completer().showPopup();
2258                         break;
2259
2260
2261                 case LFUN_COMPLETION_COMPLETE:
2262                         if (d.current_work_area_)
2263                                 d.current_work_area_->completer().tab();
2264                         break;
2265
2266                 case LFUN_COMPLETION_CANCEL:
2267                         if (d.current_work_area_) {
2268                                 if (d.current_work_area_->completer().popupVisible())
2269                                         d.current_work_area_->completer().hidePopup();
2270                                 else
2271                                         d.current_work_area_->completer().hideInline();
2272                         }
2273                         break;
2274
2275                 case LFUN_COMPLETION_ACCEPT:
2276                         if (d.current_work_area_)
2277                                 d.current_work_area_->completer().activate();
2278                         break;
2279
2280                 case LFUN_BUFFER_ZOOM_IN:
2281                 case LFUN_BUFFER_ZOOM_OUT:
2282                         if (cmd.argument().empty()) {
2283                                 if (cmd.action == LFUN_BUFFER_ZOOM_IN)
2284                                         lyxrc.zoom += 20;
2285                                 else
2286                                         lyxrc.zoom -= 20;
2287                         } else
2288                                 lyxrc.zoom += convert<int>(cmd.argument());
2289
2290                         if (lyxrc.zoom < 10)
2291                                 lyxrc.zoom = 10;
2292                                 
2293                         // The global QPixmapCache is used in GuiPainter to cache text
2294                         // painting so we must reset it.
2295                         QPixmapCache::clear();
2296                         guiApp->fontLoader().update();
2297                         lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
2298                         break;
2299
2300                 default:
2301                         dispatched = false;
2302                         break;
2303         }
2304
2305         // Part of automatic menu appearance feature.
2306         if (isFullScreen()) {
2307                 if (menuBar()->isVisible() && lyxrc.full_screen_menubar)
2308                         menuBar()->hide();
2309                 if (statusBar()->isVisible())
2310                         statusBar()->hide();
2311         }
2312
2313         return dispatched;
2314 }
2315
2316
2317 void GuiView::lfunUiToggle(FuncRequest const & cmd)
2318 {
2319         string const arg = cmd.getArg(0);
2320         if (arg == "scrollbar") {
2321                 // hide() is of no help
2322                 if (d.current_work_area_->verticalScrollBarPolicy() ==
2323                         Qt::ScrollBarAlwaysOff)
2324
2325                         d.current_work_area_->setVerticalScrollBarPolicy(
2326                                 Qt::ScrollBarAsNeeded);
2327                 else
2328                         d.current_work_area_->setVerticalScrollBarPolicy(
2329                                 Qt::ScrollBarAlwaysOff);
2330                 return;
2331         }
2332         if (arg == "statusbar") {
2333                 statusBar()->setVisible(!statusBar()->isVisible());
2334                 return;
2335         }
2336         if (arg == "menubar") {
2337                 menuBar()->setVisible(!menuBar()->isVisible());
2338                 return;
2339         }
2340 #if QT_VERSION >= 0x040300
2341         if (arg == "frame") {
2342                 int l, t, r, b;
2343                 getContentsMargins(&l, &t, &r, &b);
2344                 //are the frames in default state?
2345                 d.current_work_area_->setFrameStyle(QFrame::NoFrame);
2346                 if (l == 0) {
2347                         setContentsMargins(-2, -2, -2, -2);
2348                 } else {
2349                         setContentsMargins(0, 0, 0, 0);
2350                 }
2351                 return;
2352         }
2353 #endif
2354         if (arg == "fullscreen") {
2355                 toggleFullScreen();
2356                 return;
2357         }
2358
2359         message(bformat("LFUN_UI_TOGGLE " + _("%1$s unknown command!"), from_utf8(arg)));
2360 }
2361
2362
2363 void GuiView::toggleFullScreen()
2364 {
2365         if (isFullScreen()) {
2366                 for (int i = 0; i != d.splitter_->count(); ++i)
2367                         d.tabWorkArea(i)->setFullScreen(false);
2368 #if QT_VERSION >= 0x040300
2369                 setContentsMargins(0, 0, 0, 0);
2370 #endif
2371                 setWindowState(windowState() ^ Qt::WindowFullScreen);
2372                 restoreLayout();
2373                 menuBar()->show();
2374                 statusBar()->show();
2375         } else {
2376                 // bug 5274
2377                 hideDialogs("prefs", 0);
2378                 for (int i = 0; i != d.splitter_->count(); ++i)
2379                         d.tabWorkArea(i)->setFullScreen(true);
2380 #if QT_VERSION >= 0x040300
2381                 setContentsMargins(-2, -2, -2, -2);
2382 #endif
2383                 saveLayout();
2384                 setWindowState(windowState() ^ Qt::WindowFullScreen);
2385                 statusBar()->hide();
2386                 if (lyxrc.full_screen_menubar)
2387                         menuBar()->hide();
2388                 if (lyxrc.full_screen_toolbars) {
2389                         ToolbarMap::iterator end = d.toolbars_.end();
2390                         for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
2391                                 it->second->hide();
2392                 }
2393         }
2394
2395         // give dialogs like the TOC a chance to adapt
2396         updateDialogs();
2397 }
2398
2399
2400 Buffer const * GuiView::updateInset(Inset const * inset)
2401 {
2402         if (!d.current_work_area_)
2403                 return 0;
2404
2405         if (inset)
2406                 d.current_work_area_->scheduleRedraw();
2407
2408         return &d.current_work_area_->bufferView().buffer();
2409 }
2410
2411
2412 void GuiView::restartCursor()
2413 {
2414         /* When we move around, or type, it's nice to be able to see
2415          * the cursor immediately after the keypress.
2416          */
2417         if (d.current_work_area_)
2418                 d.current_work_area_->startBlinkingCursor();
2419
2420         // Take this occasion to update the other GUI elements.
2421         updateDialogs();
2422         updateStatusBar();
2423 }
2424
2425
2426 void GuiView::updateCompletion(Cursor & cur, bool start, bool keep)
2427 {
2428         if (d.current_work_area_)
2429                 d.current_work_area_->completer().updateVisibility(cur, start, keep);
2430 }
2431
2432 namespace {
2433
2434 // This list should be kept in sync with the list of insets in
2435 // src/insets/Inset.cpp.  I.e., if a dialog goes with an inset, the
2436 // dialog should have the same name as the inset.
2437 // Changes should be also recorded in LFUN_DIALOG_SHOW doxygen
2438 // docs in LyXAction.cpp.
2439
2440 char const * const dialognames[] = {
2441 "aboutlyx", "bibitem", "bibtex", "box", "branch", "changes", "character",
2442 "citation", "document", "errorlist", "ert", "external", "file", "findreplace",
2443 "findreplaceadv", "float", "graphics", "href", "include", "index",
2444 "index_print", "info", "listings", "label", "log", "mathdelimiter",
2445 "mathmatrix", "mathspace", "nomenclature", "nomencl_print", "note",
2446 "paragraph", "phantom", "prefs", "print", "ref", "sendto", "space",
2447 "spellchecker", "symbols", "tabular", "tabularcreate", "thesaurus", "texinfo",
2448 "toc", "view-source", "vspace", "wrap" };
2449
2450 char const * const * const end_dialognames =
2451         dialognames + (sizeof(dialognames) / sizeof(char *));
2452
2453 class cmpCStr {
2454 public:
2455         cmpCStr(char const * name) : name_(name) {}
2456         bool operator()(char const * other) {
2457                 return strcmp(other, name_) == 0;
2458         }
2459 private:
2460         char const * name_;
2461 };
2462
2463
2464 bool isValidName(string const & name)
2465 {
2466         return find_if(dialognames, end_dialognames,
2467                             cmpCStr(name.c_str())) != end_dialognames;
2468 }
2469
2470 } // namespace anon
2471
2472
2473 void GuiView::resetDialogs()
2474 {
2475         // Make sure that no LFUN uses any LyXView.
2476         theLyXFunc().setLyXView(0);
2477         saveLayout();
2478         menuBar()->clear();
2479         constructToolbars();
2480         guiApp->menus().fillMenuBar(menuBar(), this, false);
2481         if (d.layout_)
2482                 d.layout_->updateContents(true);
2483         // Now update controls with current buffer.
2484         theLyXFunc().setLyXView(this);
2485         restoreLayout();
2486         restartCursor();
2487 }
2488
2489
2490 Dialog * GuiView::findOrBuild(string const & name, bool hide_it)
2491 {
2492         if (!isValidName(name))
2493                 return 0;
2494
2495         map<string, DialogPtr>::iterator it = d.dialogs_.find(name);
2496
2497         if (it != d.dialogs_.end()) {
2498                 if (hide_it)
2499                         it->second->hideView();
2500                 return it->second.get();
2501         }
2502
2503         Dialog * dialog = build(name);
2504         d.dialogs_[name].reset(dialog);
2505         if (lyxrc.allow_geometry_session)
2506                 dialog->restoreSession();
2507         if (hide_it)
2508                 dialog->hideView();
2509         return dialog;
2510 }
2511
2512
2513 void GuiView::showDialog(string const & name, string const & data,
2514         Inset * inset)
2515 {
2516         if (d.in_show_)
2517                 return;
2518
2519         d.in_show_ = true;
2520         try {
2521                 Dialog * dialog = findOrBuild(name, false);
2522                 if (dialog) {
2523                         dialog->showData(data);
2524                         if (inset)
2525                                 d.open_insets_[name] = inset;
2526                 }
2527         }
2528         catch (ExceptionMessage const & ex) {
2529                 d.in_show_ = false;
2530                 throw ex;
2531         }
2532         d.in_show_ = false;
2533 }
2534
2535
2536 bool GuiView::isDialogVisible(string const & name) const
2537 {
2538         map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
2539         if (it == d.dialogs_.end())
2540                 return false;
2541         return it->second.get()->isVisibleView() && !it->second.get()->isClosing();
2542 }
2543
2544
2545 void GuiView::hideDialog(string const & name, Inset * inset)
2546 {
2547         map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
2548         if (it == d.dialogs_.end())
2549                 return;
2550
2551         if (inset && inset != getOpenInset(name))
2552                 return;
2553
2554         Dialog * const dialog = it->second.get();
2555         if (dialog->isVisibleView())
2556                 dialog->hideView();
2557         d.open_insets_[name] = 0;
2558 }
2559
2560
2561 void GuiView::disconnectDialog(string const & name)
2562 {
2563         if (!isValidName(name))
2564                 return;
2565
2566         if (d.open_insets_.find(name) != d.open_insets_.end())
2567                 d.open_insets_[name] = 0;
2568 }
2569
2570
2571 Inset * GuiView::getOpenInset(string const & name) const
2572 {
2573         if (!isValidName(name))
2574                 return 0;
2575
2576         map<string, Inset *>::const_iterator it = d.open_insets_.find(name);
2577         return it == d.open_insets_.end() ? 0 : it->second;
2578 }
2579
2580
2581 void GuiView::hideAll() const
2582 {
2583         map<string, DialogPtr>::const_iterator it  = d.dialogs_.begin();
2584         map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
2585
2586         for(; it != end; ++it)
2587                 it->second->hideView();
2588 }
2589
2590
2591 void GuiView::updateDialogs()
2592 {
2593         map<string, DialogPtr>::const_iterator it  = d.dialogs_.begin();
2594         map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
2595
2596         for(; it != end; ++it) {
2597                 Dialog * dialog = it->second.get();
2598                 if (dialog && dialog->isVisibleView())
2599                         dialog->checkStatus();
2600         }
2601         updateToolbars();
2602         updateLayoutList();
2603 }
2604
2605
2606 // will be replaced by a proper factory...
2607 Dialog * createGuiAbout(GuiView & lv);
2608 Dialog * createGuiBibitem(GuiView & lv);
2609 Dialog * createGuiBibtex(GuiView & lv);
2610 Dialog * createGuiBox(GuiView & lv);
2611 Dialog * createGuiBranch(GuiView & lv);
2612 Dialog * createGuiChanges(GuiView & lv);
2613 Dialog * createGuiCharacter(GuiView & lv);
2614 Dialog * createGuiCitation(GuiView & lv);
2615 Dialog * createGuiDelimiter(GuiView & lv);
2616 Dialog * createGuiDocument(GuiView & lv);
2617 Dialog * createGuiErrorList(GuiView & lv);
2618 Dialog * createGuiERT(GuiView & lv);
2619 Dialog * createGuiExternal(GuiView & lv);
2620 Dialog * createGuiFloat(GuiView & lv);
2621 Dialog * createGuiGraphics(GuiView & lv);
2622 Dialog * createGuiInclude(GuiView & lv);
2623 Dialog * createGuiIndex(GuiView & lv);
2624 Dialog * createGuiInfo(GuiView & lv);
2625 Dialog * createGuiLabel(GuiView & lv);
2626 Dialog * createGuiListings(GuiView & lv);
2627 Dialog * createGuiLog(GuiView & lv);
2628 Dialog * createGuiMathHSpace(GuiView & lv);
2629 Dialog * createGuiMathMatrix(GuiView & lv);
2630 Dialog * createGuiNomenclature(GuiView & lv);
2631 Dialog * createGuiNote(GuiView & lv);
2632 Dialog * createGuiParagraph(GuiView & lv);
2633 Dialog * createGuiPhantom(GuiView & lv);
2634 Dialog * createGuiPreferences(GuiView & lv);
2635 Dialog * createGuiPrint(GuiView & lv);
2636 Dialog * createGuiPrintindex(GuiView & lv);
2637 Dialog * createGuiPrintNomencl(GuiView & lv);
2638 Dialog * createGuiRef(GuiView & lv);
2639 Dialog * createGuiSearch(GuiView & lv);
2640 Dialog * createGuiSearchAdv(GuiView & lv);
2641 Dialog * createGuiSendTo(GuiView & lv);
2642 Dialog * createGuiShowFile(GuiView & lv);
2643 Dialog * createGuiSpellchecker(GuiView & lv);
2644 Dialog * createGuiSymbols(GuiView & lv);
2645 Dialog * createGuiTabularCreate(GuiView & lv);
2646 Dialog * createGuiTabular(GuiView & lv);
2647 Dialog * createGuiTexInfo(GuiView & lv);
2648 Dialog * createGuiTextHSpace(GuiView & lv);
2649 Dialog * createGuiToc(GuiView & lv);
2650 Dialog * createGuiThesaurus(GuiView & lv);
2651 Dialog * createGuiHyperlink(GuiView & lv);
2652 Dialog * createGuiVSpace(GuiView & lv);
2653 Dialog * createGuiViewSource(GuiView & lv);
2654 Dialog * createGuiWrap(GuiView & lv);
2655
2656
2657 Dialog * GuiView::build(string const & name)
2658 {
2659         LASSERT(isValidName(name), return 0);
2660
2661         if (name == "aboutlyx")
2662                 return createGuiAbout(*this);
2663         if (name == "bibitem")
2664                 return createGuiBibitem(*this);
2665         if (name == "bibtex")
2666                 return createGuiBibtex(*this);
2667         if (name == "box")
2668                 return createGuiBox(*this);
2669         if (name == "branch")
2670                 return createGuiBranch(*this);
2671         if (name == "changes")
2672                 return createGuiChanges(*this);
2673         if (name == "character")
2674                 return createGuiCharacter(*this);
2675         if (name == "citation")
2676                 return createGuiCitation(*this);
2677         if (name == "document")
2678                 return createGuiDocument(*this);
2679         if (name == "errorlist")
2680                 return createGuiErrorList(*this);
2681         if (name == "ert")
2682                 return createGuiERT(*this);
2683         if (name == "external")
2684                 return createGuiExternal(*this);
2685         if (name == "file")
2686                 return createGuiShowFile(*this);
2687         if (name == "findreplace")
2688                 return createGuiSearch(*this);
2689         if (name == "findreplaceadv")
2690                 return createGuiSearchAdv(*this);
2691         if (name == "float")
2692                 return createGuiFloat(*this);
2693         if (name == "graphics")
2694                 return createGuiGraphics(*this);
2695         if (name == "href")
2696                 return createGuiHyperlink(*this);
2697         if (name == "include")
2698                 return createGuiInclude(*this);
2699         if (name == "index")
2700                 return createGuiIndex(*this);
2701         if (name == "index_print")
2702                 return createGuiPrintindex(*this);
2703         if (name == "info")
2704                 return createGuiInfo(*this);
2705         if (name == "label")
2706                 return createGuiLabel(*this);
2707         if (name == "listings")
2708                 return createGuiListings(*this);
2709         if (name == "log")
2710                 return createGuiLog(*this);
2711         if (name == "mathdelimiter")
2712                 return createGuiDelimiter(*this);
2713         if (name == "mathspace")
2714                 return createGuiMathHSpace(*this);
2715         if (name == "mathmatrix")
2716                 return createGuiMathMatrix(*this);
2717         if (name == "nomenclature")
2718                 return createGuiNomenclature(*this);
2719         if (name == "nomencl_print")
2720                 return createGuiPrintNomencl(*this);
2721         if (name == "note")
2722                 return createGuiNote(*this);
2723         if (name == "paragraph")
2724                 return createGuiParagraph(*this);
2725         if (name == "phantom")
2726                 return createGuiPhantom(*this);
2727         if (name == "prefs")
2728                 return createGuiPreferences(*this);
2729         if (name == "print")
2730                 return createGuiPrint(*this);
2731         if (name == "ref")
2732                 return createGuiRef(*this);
2733         if (name == "sendto")
2734                 return createGuiSendTo(*this);
2735         if (name == "space")
2736                 return createGuiTextHSpace(*this);
2737         if (name == "spellchecker")
2738                 return createGuiSpellchecker(*this);
2739         if (name == "symbols")
2740                 return createGuiSymbols(*this);
2741         if (name == "tabular")
2742                 return createGuiTabular(*this);
2743         if (name == "tabularcreate")
2744                 return createGuiTabularCreate(*this);
2745         if (name == "texinfo")
2746                 return createGuiTexInfo(*this);
2747         if (name == "thesaurus")
2748                 return createGuiThesaurus(*this);
2749         if (name == "toc")
2750                 return createGuiToc(*this);
2751         if (name == "view-source")
2752                 return createGuiViewSource(*this);
2753         if (name == "vspace")
2754                 return createGuiVSpace(*this);
2755         if (name == "wrap")
2756                 return createGuiWrap(*this);
2757
2758         return 0;
2759 }
2760
2761
2762 } // namespace frontend
2763 } // namespace lyx
2764
2765 #include "moc_GuiView.cpp"