]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiView.cpp
Whitespace and correct naming.
[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, false, 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                                 //FIXME: should buffers be closed or not?
624                                 if (!closeBuffer(*c, false, false))
625                                         return false;
626                         }
627
628                         QList<int> const ids = guiApp->viewIds();
629                         for (int i = 0; i != ids.size(); ++i) {
630                                 if (id_ == ids[i])
631                                         continue;
632                                 if (guiApp->view(ids[i]).workArea(*b)) {
633                                         // FIXME 1: should we put an alert box here
634                                         // that the buffer is viewed elsewhere?
635                                         // FIXME 2: should we try to save this buffer in any case?
636                                         //saveBuffer(b);
637
638                                         // This buffer is also opened in another view, so
639                                         // close the associated work area...
640                                         removeWorkArea(wa);
641                                         // ... but don't close the buffer.
642                                         b = 0;
643                                         break;
644                                 }
645                         }
646                         // closeBuffer() needs buffer workArea still alive and
647                         // set as currrent one, and destroys it
648                         if (b && !closeBuffer(*b, true, tolastopened, is_active_wa))
649                                 return false;
650                 }
651         }
652         return true;
653 }
654
655
656 void GuiView::dragEnterEvent(QDragEnterEvent * event)
657 {
658         if (event->mimeData()->hasUrls())
659                 event->accept();
660         /// \todo Ask lyx-devel is this is enough:
661         /// if (event->mimeData()->hasFormat("text/plain"))
662         ///     event->acceptProposedAction();
663 }
664
665
666 void GuiView::dropEvent(QDropEvent * event)
667 {
668         QList<QUrl> files = event->mimeData()->urls();
669         if (files.isEmpty())
670                 return;
671
672         LYXERR(Debug::GUI, "GuiView::dropEvent: got URLs!");
673         for (int i = 0; i != files.size(); ++i) {
674                 string const file = os::internal_path(fromqstr(
675                         files.at(i).toLocalFile()));
676                 if (!file.empty()) {
677                         // Asynchronously post the event. DropEvent usually come
678                         // from the BufferView. But reloading a file might close
679                         // the BufferView from within its own event handler.
680                         guiApp->dispatchDelayed(FuncRequest(LFUN_FILE_OPEN, file));
681                         event->accept();
682                 }
683         }
684 }
685
686
687 void GuiView::message(docstring const & str)
688 {
689         if (ForkedProcess::iAmAChild())
690                 return;
691
692         statusBar()->showMessage(toqstr(str));
693         d.statusbar_timer_.stop();
694         d.statusbar_timer_.start(3000);
695 }
696
697
698 void GuiView::smallSizedIcons()
699 {
700         setIconSize(QSize(d.smallIconSize, d.smallIconSize));
701 }
702
703
704 void GuiView::normalSizedIcons()
705 {
706         setIconSize(QSize(d.normalIconSize, d.normalIconSize));
707 }
708
709
710 void GuiView::bigSizedIcons()
711 {
712         setIconSize(QSize(d.bigIconSize, d.bigIconSize));
713 }
714
715
716 void GuiView::clearMessage()
717 {
718         if (!hasFocus())
719                 return;
720         theLyXFunc().setLyXView(this);
721         statusBar()->showMessage(toqstr(theLyXFunc().viewStatusMessage()));
722         d.statusbar_timer_.stop();
723 }
724
725
726 void GuiView::updateWindowTitle(GuiWorkArea * wa)
727 {
728         if (wa != d.current_work_area_)
729                 return;
730         setWindowTitle(qt_("LyX: ") + wa->windowTitle());
731         setWindowIconText(wa->windowIconText());
732 }
733
734
735 void GuiView::on_currentWorkAreaChanged(GuiWorkArea * wa)
736 {
737         disconnectBuffer();
738         disconnectBufferView();
739         connectBufferView(wa->bufferView());
740         connectBuffer(wa->bufferView().buffer());
741         d.current_work_area_ = wa;
742         QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
743                 this, SLOT(updateWindowTitle(GuiWorkArea *)));
744         updateWindowTitle(wa);
745
746         structureChanged();
747
748         // The document settings needs to be reinitialised.
749         updateDialog("document", "");
750
751         // Buffer-dependent dialogs must be updated. This is done here because
752         // some dialogs require buffer()->text.
753         updateDialogs();
754 }
755
756
757 void GuiView::on_lastWorkAreaRemoved()
758 {
759         if (closing_)
760                 // We already are in a close event. Nothing more to do.
761                 return;
762
763         if (d.splitter_->count() > 1)
764                 // We have a splitter so don't close anything.
765                 return;
766
767         // Reset and updates the dialogs.
768         d.toc_models_.reset(0);
769         updateDialog("document", "");
770         updateDialogs();
771
772         resetWindowTitleAndIconText();
773
774         if (lyxrc.open_buffers_in_tabs)
775                 // Nothing more to do, the window should stay open.
776                 return;
777
778         if (guiApp->viewIds().size() > 1) {
779                 close();
780                 return;
781         }
782
783 #ifdef Q_WS_MACX
784         // On Mac we also close the last window because the application stay
785         // resident in memory. On other platforms we don't close the last
786         // window because this would quit the application.
787         close();
788 #endif
789 }
790
791
792 void GuiView::updateStatusBar()
793 {
794         // let the user see the explicit message
795         if (d.statusbar_timer_.isActive())
796                 return;
797
798         theLyXFunc().setLyXView(this);
799         statusBar()->showMessage(toqstr(theLyXFunc().viewStatusMessage()));
800 }
801
802
803 bool GuiView::hasFocus() const
804 {
805         return qApp->activeWindow() == this;
806 }
807
808
809 bool GuiView::event(QEvent * e)
810 {
811         switch (e->type())
812         {
813         // Useful debug code:
814         //case QEvent::ActivationChange:
815         //case QEvent::WindowDeactivate:
816         //case QEvent::Paint:
817         //case QEvent::Enter:
818         //case QEvent::Leave:
819         //case QEvent::HoverEnter:
820         //case QEvent::HoverLeave:
821         //case QEvent::HoverMove:
822         //case QEvent::StatusTip:
823         //case QEvent::DragEnter:
824         //case QEvent::DragLeave:
825         //case QEvent::Drop:
826         //      break;
827
828         case QEvent::WindowActivate: {
829                 if (this == guiApp->currentView()) {
830                         setFocus();
831                         return QMainWindow::event(e);
832                 }
833                 guiApp->setCurrentView(this);
834                 theLyXFunc().setLyXView(this);
835                 if (d.current_work_area_) {
836                         BufferView & bv = d.current_work_area_->bufferView();
837                         connectBufferView(bv);
838                         connectBuffer(bv.buffer());
839                         // The document structure, name and dialogs might have
840                         // changed in another view.
841                         structureChanged();
842                         // The document settings needs to be reinitialised.
843                         updateDialog("document", "");
844                         updateDialogs();
845                 } else {
846                         resetWindowTitleAndIconText();
847                 }
848                 setFocus();
849                 return QMainWindow::event(e);
850         }
851
852         case QEvent::ShortcutOverride: {
853
854 // See bug 4888
855 #if (!defined Q_WS_X11) || (QT_VERSION >= 0x040500)
856                 if (isFullScreen() && menuBar()->isHidden()) {
857                         QKeyEvent * ke = static_cast<QKeyEvent*>(e);
858                         // FIXME: we should also try to detect special LyX shortcut such as
859                         // Alt-P and Alt-M. Right now there is a hack in
860                         // GuiWorkArea::processKeySym() that hides again the menubar for
861                         // those cases.
862                         if (ke->modifiers() & Qt::AltModifier && ke->key() != Qt::Key_Alt) {
863                                 menuBar()->show();
864                                 return QMainWindow::event(e);
865                         }
866                 }
867 #endif
868
869                 if (d.current_work_area_)
870                         // Nothing special to do.
871                         return QMainWindow::event(e);
872
873                 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
874                 // Let Qt handle menu access and the Tab keys to navigate keys to navigate
875                 // between controls.
876                 if (ke->modifiers() & Qt::AltModifier || ke->key() == Qt::Key_Tab 
877                         || ke->key() == Qt::Key_Backtab)
878                         return QMainWindow::event(e);
879
880                 // Allow processing of shortcuts that are allowed even when no Buffer
881                 // is viewed.
882                 theLyXFunc().setLyXView(this);
883                 KeySymbol sym;
884                 setKeySymbol(&sym, ke);
885                 theLyXFunc().processKeySym(sym, q_key_state(ke->modifiers()));
886                 e->accept();
887                 return true;
888         }
889
890         default:
891                 return QMainWindow::event(e);
892         }
893 }
894
895 void GuiView::resetWindowTitleAndIconText()
896 {
897     setWindowTitle(qt_("LyX"));
898     setWindowIconText(qt_("LyX"));
899 }
900
901 bool GuiView::focusNextPrevChild(bool /*next*/)
902 {
903         setFocus();
904         return true;
905 }
906
907
908 void GuiView::setBusy(bool busy)
909 {
910         if (d.current_work_area_) {
911                 d.current_work_area_->setUpdatesEnabled(!busy);
912                 if (busy)
913                         d.current_work_area_->stopBlinkingCursor();
914                 else
915                         d.current_work_area_->startBlinkingCursor();
916         }
917
918         if (busy)
919                 QApplication::setOverrideCursor(Qt::WaitCursor);
920         else
921                 QApplication::restoreOverrideCursor();
922 }
923
924
925 GuiWorkArea * GuiView::workArea(Buffer & buffer)
926 {
927         if (currentWorkArea()
928             && &currentWorkArea()->bufferView().buffer() == &buffer)
929                 return (GuiWorkArea *) currentWorkArea();
930         if (TabWorkArea * twa = d.currentTabWorkArea())
931                 return twa->workArea(buffer);
932         return 0;
933 }
934
935
936 GuiWorkArea * GuiView::addWorkArea(Buffer & buffer)
937 {
938         // Automatically create a TabWorkArea if there are none yet.
939         TabWorkArea * tab_widget = d.splitter_->count() 
940                 ? d.currentTabWorkArea() : addTabWorkArea();
941         return tab_widget->addWorkArea(buffer, *this);
942 }
943
944
945 TabWorkArea * GuiView::addTabWorkArea()
946 {
947         TabWorkArea * twa = new TabWorkArea;
948         QObject::connect(twa, SIGNAL(currentWorkAreaChanged(GuiWorkArea *)),
949                 this, SLOT(on_currentWorkAreaChanged(GuiWorkArea *)));
950         QObject::connect(twa, SIGNAL(lastWorkAreaRemoved()),
951                          this, SLOT(on_lastWorkAreaRemoved()));
952
953         d.splitter_->addWidget(twa);
954         d.stack_widget_->setCurrentWidget(d.splitter_);
955         return twa;
956 }
957
958
959 GuiWorkArea const * GuiView::currentWorkArea() const
960 {
961         return d.current_work_area_;
962 }
963
964
965 GuiWorkArea * GuiView::currentWorkArea()
966 {
967         return d.current_work_area_;
968 }
969
970
971 GuiWorkArea const * GuiView::currentMainWorkArea() const
972 {
973         if (d.currentTabWorkArea() == NULL)
974                 return NULL;
975         return d.currentTabWorkArea()->currentWorkArea();
976 }
977
978
979 GuiWorkArea * GuiView::currentMainWorkArea()
980 {
981         if (d.currentTabWorkArea() == NULL)
982                 return NULL;
983         return d.currentTabWorkArea()->currentWorkArea();
984 }
985
986
987 void GuiView::setCurrentWorkArea(GuiWorkArea * wa)
988 {
989         LYXERR(Debug::DEBUG, "Setting current wa: " << wa << endl);
990         if (wa == NULL) {
991                 d.current_work_area_ = NULL;
992                 d.setBackground();
993                 return;
994         }
995         GuiWorkArea * old_gwa = theGuiApp()->currentView()->currentWorkArea();
996         if (old_gwa == wa)
997                 return;
998
999         if (view())
1000                 cap::saveSelection(view()->cursor());
1001
1002         theGuiApp()->setCurrentView(this);
1003         d.current_work_area_ = wa;
1004         for (int i = 0; i != d.splitter_->count(); ++i) {
1005                 if (d.tabWorkArea(i)->setCurrentWorkArea(wa)) {
1006                         //if (d.current_main_work_area_)
1007                         //      d.current_main_work_area_->setFrameStyle(QFrame::NoFrame);
1008                         d.current_main_work_area_ = wa;
1009                         //d.current_main_work_area_->setFrameStyle(QFrame::Box | QFrame::Plain);
1010                         //d.current_main_work_area_->setLineWidth(2);
1011                         LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() << ", Current main wa: " << currentMainWorkArea());
1012                         return;
1013                 }
1014         }
1015         LYXERR(Debug::DEBUG, "This is not a tabbed wa");
1016         on_currentWorkAreaChanged(wa);
1017         BufferView & bv = wa->bufferView();
1018         bv.cursor().fixIfBroken();
1019         bv.updateMetrics();
1020         wa->setUpdatesEnabled(true);
1021         LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() << ", Current main wa: " << currentMainWorkArea());
1022 }
1023
1024
1025 void GuiView::removeWorkArea(GuiWorkArea * wa)
1026 {
1027         LASSERT(wa, return);
1028         if (wa == d.current_work_area_) {
1029                 disconnectBuffer();
1030                 disconnectBufferView();
1031                 d.current_work_area_ = 0;
1032                 d.current_main_work_area_ = 0;
1033         }
1034
1035         bool found_twa = false;
1036         for (int i = 0; i != d.splitter_->count(); ++i) {
1037                 TabWorkArea * twa = d.tabWorkArea(i);
1038                 if (twa->removeWorkArea(wa)) {
1039                         // Found in this tab group, and deleted the GuiWorkArea.
1040                         found_twa = true;
1041                         if (twa->count() != 0) {
1042                                 if (d.current_work_area_ == 0)
1043                                         // This means that we are closing the current GuiWorkArea, so
1044                                         // switch to the next GuiWorkArea in the found TabWorkArea.
1045                                         setCurrentWorkArea(twa->currentWorkArea());
1046                         } else {
1047                                 // No more WorkAreas in this tab group, so delete it.
1048                                 delete twa;
1049                         }
1050                         break;
1051                 }
1052         }
1053
1054         // It is not a tabbed work area (i.e., the search work area), so it
1055         // should be deleted by other means.
1056         LASSERT(found_twa, /* */);
1057
1058         if (d.current_work_area_ == 0) {
1059                 if (d.splitter_->count() != 0) {
1060                         TabWorkArea * twa = d.currentTabWorkArea();
1061                         setCurrentWorkArea(twa->currentWorkArea());
1062                 } else {
1063                         // No more work areas, switch to the background widget.
1064                         setCurrentWorkArea(0);
1065                 }
1066         }
1067 }
1068
1069
1070 void GuiView::setLayoutDialog(GuiLayoutBox * layout)
1071 {
1072         d.layout_ = layout;
1073 }
1074
1075
1076 void GuiView::updateLayoutList()
1077 {
1078         if (d.layout_)
1079                 d.layout_->updateContents(false);
1080 }
1081
1082
1083 void GuiView::updateToolbars()
1084 {
1085         ToolbarMap::iterator end = d.toolbars_.end();
1086         if (d.current_work_area_) {
1087                 bool const math =
1088                         d.current_work_area_->bufferView().cursor().inMathed();
1089                 bool const table =
1090                         lyx::getStatus(FuncRequest(LFUN_LAYOUT_TABULAR)).enabled();
1091                 bool const review =
1092                         lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).enabled() &&
1093                         lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).onoff(true);
1094                 bool const mathmacrotemplate =
1095                         lyx::getStatus(FuncRequest(LFUN_IN_MATHMACROTEMPLATE)).enabled();
1096
1097                 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1098                         it->second->update(math, table, review, mathmacrotemplate);
1099         } else
1100                 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1101                         it->second->update(false, false, false, false);
1102 }
1103
1104
1105 Buffer * GuiView::buffer()
1106 {
1107         if (d.current_work_area_)
1108                 return &d.current_work_area_->bufferView().buffer();
1109         return 0;
1110 }
1111
1112
1113 Buffer const * GuiView::buffer() const
1114 {
1115         if (d.current_work_area_)
1116                 return &d.current_work_area_->bufferView().buffer();
1117         return 0;
1118 }
1119
1120
1121 void GuiView::setBuffer(Buffer * newBuffer)
1122 {
1123         LYXERR(Debug::DEBUG, "Setting buffer: " << newBuffer << std::endl);
1124         LASSERT(newBuffer, return);
1125         setBusy(true);
1126
1127         GuiWorkArea * wa = workArea(*newBuffer);
1128         if (wa == 0) {
1129                 newBuffer->masterBuffer()->updateLabels();
1130                 wa = addWorkArea(*newBuffer);
1131         } else {
1132                 //Disconnect the old buffer...there's no new one.
1133                 disconnectBuffer();
1134         }
1135         connectBuffer(*newBuffer);
1136         connectBufferView(wa->bufferView());
1137         setCurrentWorkArea(wa);
1138
1139         setBusy(false);
1140 }
1141
1142
1143 void GuiView::connectBuffer(Buffer & buf)
1144 {
1145         buf.setGuiDelegate(this);
1146 }
1147
1148
1149 void GuiView::disconnectBuffer()
1150 {
1151         if (d.current_work_area_)
1152                 d.current_work_area_->bufferView().setGuiDelegate(0);
1153 }
1154
1155
1156 void GuiView::connectBufferView(BufferView & bv)
1157 {
1158         bv.setGuiDelegate(this);
1159 }
1160
1161
1162 void GuiView::disconnectBufferView()
1163 {
1164         if (d.current_work_area_)
1165                 d.current_work_area_->bufferView().setGuiDelegate(0);
1166 }
1167
1168
1169 void GuiView::errors(string const & error_type, bool from_master)
1170 {
1171         ErrorList & el = from_master ? 
1172                 buffer()->masterBuffer()->errorList(error_type)
1173                 : buffer()->errorList(error_type);
1174         string data = error_type;
1175         if (from_master)
1176                 data = "from_master|" + error_type;
1177         if (!el.empty())
1178                 showDialog("errorlist", data);
1179 }
1180
1181
1182 void GuiView::updateTocItem(std::string const & type, DocIterator const & dit)
1183 {
1184         d.toc_models_.updateItem(toqstr(type), dit);
1185 }
1186
1187
1188 void GuiView::structureChanged()
1189 {
1190         d.toc_models_.reset(view());
1191         // Navigator needs more than a simple update in this case. It needs to be
1192         // rebuilt.
1193         updateDialog("toc", "");
1194 }
1195
1196
1197 void GuiView::updateDialog(string const & name, string const & data)
1198 {
1199         if (!isDialogVisible(name))
1200                 return;
1201
1202         map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
1203         if (it == d.dialogs_.end())
1204                 return;
1205
1206         Dialog * const dialog = it->second.get();
1207         if (dialog->isVisibleView())
1208                 dialog->initialiseParams(data);
1209 }
1210
1211
1212 BufferView * GuiView::view()
1213 {
1214         return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1215 }
1216
1217
1218 void GuiView::autoSave()
1219 {
1220         LYXERR(Debug::INFO, "Running autoSave()");
1221
1222         if (buffer())
1223                 view()->buffer().autoSave();
1224 }
1225
1226
1227 void GuiView::resetAutosaveTimers()
1228 {
1229         if (lyxrc.autosave)
1230                 d.autosave_timeout_.restart();
1231 }
1232
1233
1234 bool GuiView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1235 {
1236         bool enable = true;
1237         Buffer * buf = buffer();
1238
1239         if (cmd.origin == FuncRequest::TOC) {
1240                 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
1241                 FuncStatus fs;
1242                 if (toc->getStatus(view()->cursor(), cmd, fs))
1243                         flag |= fs;
1244                 else
1245                         flag.setEnabled(false);
1246                 return true;
1247         }
1248
1249         switch(cmd.action) {
1250         case LFUN_BUFFER_WRITE:
1251                 enable = buf && (buf->isUnnamed() || !buf->isClean());
1252                 break;
1253
1254         case LFUN_BUFFER_WRITE_AS:
1255                 enable = buf;
1256                 break;
1257
1258         case LFUN_BUFFER_CLOSE_ALL: {
1259                 enable = false;
1260                 BufferList::iterator it = theBufferList().begin();
1261                 BufferList::iterator end = theBufferList().end();
1262                 int visible_buffers = 0;
1263                 for (; it != end; ++it) {
1264                         if (workArea(**it))
1265                                 ++visible_buffers;
1266                         if (visible_buffers > 1) {
1267                                 enable = true;
1268                                 break;
1269                         }
1270                 }
1271                 break;
1272         }
1273
1274         case LFUN_SPLIT_VIEW:
1275                 if (cmd.getArg(0) == "vertical")
1276                         enable = buf && (d.splitter_->count() == 1 ||
1277                                          d.splitter_->orientation() == Qt::Vertical);
1278                 else
1279                         enable = buf && (d.splitter_->count() == 1 ||
1280                                          d.splitter_->orientation() == Qt::Horizontal);
1281                 break;
1282
1283         case LFUN_CLOSE_TAB_GROUP:
1284                 enable = d.currentTabWorkArea();
1285                 break;
1286
1287         case LFUN_TOOLBAR_TOGGLE:
1288                 if (GuiToolbar * t = toolbar(cmd.getArg(0)))
1289                         flag.setOnOff(t->isVisible());
1290                 break;
1291
1292         case LFUN_UI_TOGGLE:
1293                 flag.setOnOff(isFullScreen());
1294                 break;
1295
1296         case LFUN_DIALOG_TOGGLE:
1297                 flag.setOnOff(isDialogVisible(cmd.getArg(0)));
1298                 // fall through to set "enable"
1299         case LFUN_DIALOG_SHOW: {
1300                 string const name = cmd.getArg(0);
1301                 if (!buf)
1302                         enable = name == "aboutlyx"
1303                                 || name == "file" //FIXME: should be removed.
1304                                 || name == "prefs"
1305                                 || name == "texinfo";
1306                 else if (name == "print")
1307                         enable = buf->isExportable("dvi")
1308                                 && lyxrc.print_command != "none";
1309                 else if (name == "character" || name == "symbols") {
1310                         if (buf->isReadonly() || !view() || !view()->cursor().inTexted())
1311                                 enable = false;
1312                         else {
1313                                 // FIXME we should consider passthru
1314                                 // paragraphs too.
1315                                 Inset const & in = view()->cursor().inset();
1316                                 enable = !in.getLayout().isPassThru();
1317                         }
1318                 }
1319                 else if (name == "latexlog")
1320                         enable = FileName(buf->logName()).isReadableFile();
1321                 else if (name == "spellchecker")
1322                         enable = theSpellChecker() && !buf->isReadonly();
1323                 else if (name == "vclog")
1324                         enable = buf->lyxvc().inUse();
1325                 break;
1326         }
1327
1328         case LFUN_DIALOG_UPDATE: {
1329                 string const name = cmd.getArg(0);
1330                 if (!buf)
1331                         enable = name == "prefs";
1332                 break;
1333         }
1334
1335         case LFUN_INSET_APPLY: {
1336                 string const name = cmd.getArg(0);
1337                 Inset * inset = getOpenInset(name);
1338                 if (inset) {
1339                         FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument());
1340                         FuncStatus fs;
1341                         if (!inset->getStatus(view()->cursor(), fr, fs)) {
1342                                 // Every inset is supposed to handle this
1343                                 LASSERT(false, break);
1344                         }
1345                         flag |= fs;
1346                 } else {
1347                         FuncRequest fr(LFUN_INSET_INSERT, cmd.argument());
1348                         flag |= lyx::getStatus(fr);
1349                 }
1350                 enable = flag.enabled();
1351                 break;
1352         }
1353
1354         case LFUN_COMPLETION_INLINE:
1355                 if (!d.current_work_area_
1356                     || !d.current_work_area_->completer().inlinePossible(view()->cursor()))
1357                     enable = false;
1358                 break;
1359
1360         case LFUN_COMPLETION_POPUP:
1361                 if (!d.current_work_area_
1362                     || !d.current_work_area_->completer().popupPossible(view()->cursor()))
1363                     enable = false;
1364                 break;
1365
1366         case LFUN_COMPLETION_COMPLETE:
1367                 if (!d.current_work_area_
1368                         || !d.current_work_area_->completer().inlinePossible(view()->cursor()))
1369                     enable = false;
1370                 break;
1371
1372         case LFUN_COMPLETION_ACCEPT:
1373                 if (!d.current_work_area_
1374                     || (!d.current_work_area_->completer().popupVisible()
1375                         && !d.current_work_area_->completer().inlineVisible()
1376                         && !d.current_work_area_->completer().completionAvailable()))
1377                         enable = false;
1378                 break;
1379
1380         case LFUN_COMPLETION_CANCEL:
1381                 if (!d.current_work_area_
1382                     || (!d.current_work_area_->completer().popupVisible()
1383                         && !d.current_work_area_->completer().inlineVisible()))
1384                         enable = false;
1385                 break;
1386
1387         case LFUN_BUFFER_ZOOM_OUT:
1388                 enable = buf && lyxrc.zoom > 10;
1389                 break;
1390
1391         case LFUN_BUFFER_ZOOM_IN:
1392                 enable = buf;
1393                 break;
1394
1395         default:
1396                 return false;
1397         }
1398
1399         if (!enable)
1400                 flag.setEnabled(false);
1401
1402         return true;
1403 }
1404
1405
1406 static FileName selectTemplateFile()
1407 {
1408         FileDialog dlg(qt_("Select template file"));
1409         dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1410         dlg.setButton1(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
1411
1412         FileDialog::Result result = dlg.open(toqstr(lyxrc.template_path),
1413                              QStringList(qt_("LyX Documents (*.lyx)")));
1414
1415         if (result.first == FileDialog::Later)
1416                 return FileName();
1417         if (result.second.isEmpty())
1418                 return FileName();
1419         return FileName(fromqstr(result.second));
1420 }
1421
1422
1423 Buffer * GuiView::loadDocument(FileName const & filename, bool tolastfiles)
1424 {
1425         setBusy(true);
1426
1427         Buffer * newBuffer = checkAndLoadLyXFile(filename);
1428
1429         if (!newBuffer) {
1430                 message(_("Document not loaded."));
1431                 setBusy(false);
1432                 return 0;
1433         }
1434         
1435         setBuffer(newBuffer);
1436
1437         // scroll to the position when the file was last closed
1438         if (lyxrc.use_lastfilepos) {
1439                 LastFilePosSection::FilePos filepos =
1440                         theSession().lastFilePos().load(filename);
1441                 view()->moveToPosition(filepos.pit, filepos.pos, 0, 0);
1442         }
1443
1444         if (tolastfiles)
1445                 theSession().lastFiles().add(filename);
1446
1447         setBusy(false);
1448         return newBuffer;
1449 }
1450
1451
1452 void GuiView::openDocument(string const & fname)
1453 {
1454         string initpath = lyxrc.document_path;
1455
1456         if (buffer()) {
1457                 string const trypath = buffer()->filePath();
1458                 // If directory is writeable, use this as default.
1459                 if (FileName(trypath).isDirWritable())
1460                         initpath = trypath;
1461         }
1462
1463         string filename;
1464
1465         if (fname.empty()) {
1466                 FileDialog dlg(qt_("Select document to open"), LFUN_FILE_OPEN);
1467                 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1468                 dlg.setButton2(qt_("Examples|#E#e"),
1469                                 toqstr(addPath(package().system_support().absFilename(), "examples")));
1470
1471                 QStringList filter(qt_("LyX Documents (*.lyx)"));
1472                 filter << qt_("LyX-1.3.x Documents (*.lyx13)")
1473                         << qt_("LyX-1.4.x Documents (*.lyx14)")
1474                         << qt_("LyX-1.5.x Documents (*.lyx15)")
1475                         << qt_("LyX-1.6.x Documents (*.lyx16)");
1476                 FileDialog::Result result =
1477                         dlg.open(toqstr(initpath), filter);
1478
1479                 if (result.first == FileDialog::Later)
1480                         return;
1481
1482                 filename = fromqstr(result.second);
1483
1484                 // check selected filename
1485                 if (filename.empty()) {
1486                         message(_("Canceled."));
1487                         return;
1488                 }
1489         } else
1490                 filename = fname;
1491
1492         // get absolute path of file and add ".lyx" to the filename if
1493         // necessary. 
1494         FileName const fullname = 
1495                         fileSearch(string(), filename, "lyx", support::may_not_exist);
1496         if (!fullname.empty())
1497                 filename = fullname.absFilename();
1498
1499         if (!fullname.onlyPath().isDirectory()) {
1500                 Alert::warning(_("Invalid filename"),
1501                                 bformat(_("The directory in the given path\n%1$s\ndoes not exist."),
1502                                 from_utf8(fullname.absFilename())));
1503                 return;
1504         }
1505         // if the file doesn't exist, let the user create one
1506         if (!fullname.exists()) {
1507                 // the user specifically chose this name. Believe him.
1508                 Buffer * const b = newFile(filename, string(), true);
1509                 if (b)
1510                         setBuffer(b);
1511                 return;
1512         }
1513
1514         docstring const disp_fn = makeDisplayPath(filename);
1515         message(bformat(_("Opening document %1$s..."), disp_fn));
1516
1517         docstring str2;
1518         Buffer * buf = loadDocument(fullname);
1519         if (buf) {
1520                 buf->updateLabels();
1521                 setBuffer(buf);
1522                 buf->errors("Parse");
1523                 str2 = bformat(_("Document %1$s opened."), disp_fn);
1524                 if (buf->lyxvc().inUse())
1525                         str2 += " " + from_utf8(buf->lyxvc().versionString()) +
1526                                 " " + _("Version control detected.");
1527         } else {
1528                 str2 = bformat(_("Could not open document %1$s"), disp_fn);
1529         }
1530         message(str2);
1531 }
1532
1533 // FIXME: clean that
1534 static bool import(GuiView * lv, FileName const & filename,
1535         string const & format, ErrorList & errorList)
1536 {
1537         FileName const lyxfile(support::changeExtension(filename.absFilename(), ".lyx"));
1538
1539         string loader_format;
1540         vector<string> loaders = theConverters().loaders();
1541         if (find(loaders.begin(), loaders.end(), format) == loaders.end()) {
1542                 for (vector<string>::const_iterator it = loaders.begin();
1543                      it != loaders.end(); ++it) {
1544                         if (!theConverters().isReachable(format, *it))
1545                                 continue;
1546
1547                         string const tofile =
1548                                 support::changeExtension(filename.absFilename(),
1549                                 formats.extension(*it));
1550                         if (!theConverters().convert(0, filename, FileName(tofile),
1551                                 filename, format, *it, errorList))
1552                                 return false;
1553                         loader_format = *it;
1554                         break;
1555                 }
1556                 if (loader_format.empty()) {
1557                         frontend::Alert::error(_("Couldn't import file"),
1558                                      bformat(_("No information for importing the format %1$s."),
1559                                          formats.prettyName(format)));
1560                         return false;
1561                 }
1562         } else
1563                 loader_format = format;
1564
1565         if (loader_format == "lyx") {
1566                 Buffer * buf = lv->loadDocument(lyxfile);
1567                 if (!buf)
1568                         return false;
1569                 buf->updateLabels();
1570                 lv->setBuffer(buf);
1571                 buf->errors("Parse");
1572         } else {
1573                 Buffer * const b = newFile(lyxfile.absFilename(), string(), true);
1574                 if (!b)
1575                         return false;
1576                 lv->setBuffer(b);
1577                 bool as_paragraphs = loader_format == "textparagraph";
1578                 string filename2 = (loader_format == format) ? filename.absFilename()
1579                         : support::changeExtension(filename.absFilename(),
1580                                           formats.extension(loader_format));
1581                 lv->view()->insertPlaintextFile(FileName(filename2), as_paragraphs);
1582                 theLyXFunc().setLyXView(lv);
1583                 lyx::dispatch(FuncRequest(LFUN_MARK_OFF));
1584         }
1585
1586         return true;
1587 }
1588
1589
1590 void GuiView::importDocument(string const & argument)
1591 {
1592         string format;
1593         string filename = split(argument, format, ' ');
1594
1595         LYXERR(Debug::INFO, format << " file: " << filename);
1596
1597         // need user interaction
1598         if (filename.empty()) {
1599                 string initpath = lyxrc.document_path;
1600
1601                 Buffer const * buf = buffer();
1602                 if (buf) {
1603                         string const trypath = buf->filePath();
1604                         // If directory is writeable, use this as default.
1605                         if (FileName(trypath).isDirWritable())
1606                                 initpath = trypath;
1607                 }
1608
1609                 docstring const text = bformat(_("Select %1$s file to import"),
1610                         formats.prettyName(format));
1611
1612                 FileDialog dlg(toqstr(text), LFUN_BUFFER_IMPORT);
1613                 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1614                 dlg.setButton2(qt_("Examples|#E#e"),
1615                         toqstr(addPath(package().system_support().absFilename(), "examples")));
1616
1617                 docstring filter = formats.prettyName(format);
1618                 filter += " (*.";
1619                 // FIXME UNICODE
1620                 filter += from_utf8(formats.extension(format));
1621                 filter += ')';
1622
1623                 FileDialog::Result result =
1624                         dlg.open(toqstr(initpath), fileFilters(toqstr(filter)));
1625
1626                 if (result.first == FileDialog::Later)
1627                         return;
1628
1629                 filename = fromqstr(result.second);
1630
1631                 // check selected filename
1632                 if (filename.empty())
1633                         message(_("Canceled."));
1634         }
1635
1636         if (filename.empty())
1637                 return;
1638
1639         // get absolute path of file
1640         FileName const fullname(support::makeAbsPath(filename));
1641
1642         FileName const lyxfile(support::changeExtension(fullname.absFilename(), ".lyx"));
1643
1644         // Check if the document already is open
1645         Buffer * buf = theBufferList().getBuffer(lyxfile);
1646         if (buf) {
1647                 setBuffer(buf);
1648                 if (!closeBuffer()) {
1649                         message(_("Canceled."));
1650                         return;
1651                 }
1652         }
1653
1654         docstring const displaypath = makeDisplayPath(lyxfile.absFilename(), 30);
1655
1656         // if the file exists already, and we didn't do
1657         // -i lyx thefile.lyx, warn
1658         if (lyxfile.exists() && fullname != lyxfile) {
1659
1660                 docstring text = bformat(_("The document %1$s already exists.\n\n"
1661                         "Do you want to overwrite that document?"), displaypath);
1662                 int const ret = Alert::prompt(_("Overwrite document?"),
1663                         text, 0, 1, _("&Overwrite"), _("&Cancel"));
1664
1665                 if (ret == 1) {
1666                         message(_("Canceled."));
1667                         return;
1668                 }
1669         }
1670
1671         message(bformat(_("Importing %1$s..."), displaypath));
1672         ErrorList errorList;
1673         if (import(this, fullname, format, errorList))
1674                 message(_("imported."));
1675         else
1676                 message(_("file not imported!"));
1677
1678         // FIXME (Abdel 12/08/06): Is there a need to display the error list here?
1679 }
1680
1681
1682 void GuiView::newDocument(string const & filename, bool from_template)
1683 {
1684         FileName initpath(lyxrc.document_path);
1685         Buffer * buf = buffer();
1686         if (buf) {
1687                 FileName const trypath(buf->filePath());
1688                 // If directory is writeable, use this as default.
1689                 if (trypath.isDirWritable())
1690                         initpath = trypath;
1691         }
1692
1693         string templatefile;
1694         if (from_template) {
1695                 templatefile = selectTemplateFile().absFilename();
1696                 if (templatefile.empty())
1697                         return;
1698         }
1699         
1700         Buffer * b;
1701         if (filename.empty())
1702                 b = newUnnamedFile(templatefile, initpath);
1703         else
1704                 b = newFile(filename, templatefile, true);
1705
1706         if (b)
1707                 setBuffer(b);
1708
1709         // If no new document could be created, it is unsure 
1710         // whether there is a valid BufferView.
1711         if (view())
1712                 // Ensure the cursor is correctly positioned on screen.
1713                 view()->showCursor();
1714 }
1715
1716
1717 void GuiView::insertLyXFile(docstring const & fname)
1718 {
1719         BufferView * bv = view();
1720         if (!bv)
1721                 return;
1722
1723         // FIXME UNICODE
1724         FileName filename(to_utf8(fname));
1725         
1726         if (!filename.empty()) {
1727                 bv->insertLyXFile(filename);
1728                 return;
1729         }
1730
1731         // Launch a file browser
1732         // FIXME UNICODE
1733         string initpath = lyxrc.document_path;
1734         string const trypath = bv->buffer().filePath();
1735         // If directory is writeable, use this as default.
1736         if (FileName(trypath).isDirWritable())
1737                 initpath = trypath;
1738
1739         // FIXME UNICODE
1740         FileDialog dlg(qt_("Select LyX document to insert"), LFUN_FILE_INSERT);
1741         dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1742         dlg.setButton2(qt_("Examples|#E#e"),
1743                 toqstr(addPath(package().system_support().absFilename(),
1744                 "examples")));
1745
1746         FileDialog::Result result = dlg.open(toqstr(initpath),
1747                              QStringList(qt_("LyX Documents (*.lyx)")));
1748
1749         if (result.first == FileDialog::Later)
1750                 return;
1751
1752         // FIXME UNICODE
1753         filename.set(fromqstr(result.second));
1754
1755         // check selected filename
1756         if (filename.empty()) {
1757                 // emit message signal.
1758                 message(_("Canceled."));
1759                 return;
1760         }
1761
1762         bv->insertLyXFile(filename);
1763 }
1764
1765
1766 void GuiView::insertPlaintextFile(docstring const & fname,
1767         bool asParagraph)
1768 {
1769         BufferView * bv = view();
1770         if (!bv)
1771                 return;
1772
1773         if (!fname.empty() && !FileName::isAbsolute(to_utf8(fname))) {
1774                 message(_("Absolute filename expected."));
1775                 return;
1776         }
1777
1778         // FIXME UNICODE
1779         FileName filename(to_utf8(fname));
1780         
1781         if (!filename.empty()) {
1782                 bv->insertPlaintextFile(filename, asParagraph);
1783                 return;
1784         }
1785
1786         FileDialog dlg(qt_("Select file to insert"), (asParagraph ?
1787                 LFUN_FILE_INSERT_PLAINTEXT_PARA : LFUN_FILE_INSERT_PLAINTEXT));
1788
1789         FileDialog::Result result = dlg.open(toqstr(bv->buffer().filePath()),
1790                 QStringList(qt_("All Files (*)")));
1791
1792         if (result.first == FileDialog::Later)
1793                 return;
1794
1795         // FIXME UNICODE
1796         filename.set(fromqstr(result.second));
1797
1798         // check selected filename
1799         if (filename.empty()) {
1800                 // emit message signal.
1801                 message(_("Canceled."));
1802                 return;
1803         }
1804
1805         bv->insertPlaintextFile(filename, asParagraph);
1806 }
1807
1808
1809 bool GuiView::renameBuffer(Buffer & b, docstring const & newname)
1810 {
1811         FileName fname = b.fileName();
1812         FileName const oldname = fname;
1813
1814         if (!newname.empty()) {
1815                 // FIXME UNICODE
1816                 fname = support::makeAbsPath(to_utf8(newname), oldname.onlyPath().absFilename());
1817         } else {
1818                 // Switch to this Buffer.
1819                 setBuffer(&b);
1820
1821                 // No argument? Ask user through dialog.
1822                 // FIXME UNICODE
1823                 FileDialog dlg(qt_("Choose a filename to save document as"),
1824                                    LFUN_BUFFER_WRITE_AS);
1825                 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1826                 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
1827
1828                 if (!isLyXFilename(fname.absFilename()))
1829                         fname.changeExtension(".lyx");
1830
1831                 FileDialog::Result result =
1832                         dlg.save(toqstr(fname.onlyPath().absFilename()),
1833                                QStringList(qt_("LyX Documents (*.lyx)")),
1834                                      toqstr(fname.onlyFileName()));
1835
1836                 if (result.first == FileDialog::Later)
1837                         return false;
1838
1839                 fname.set(fromqstr(result.second));
1840
1841                 if (fname.empty())
1842                         return false;
1843
1844                 if (!isLyXFilename(fname.absFilename()))
1845                         fname.changeExtension(".lyx");
1846         }
1847
1848         if (FileName(fname).exists()) {
1849                 docstring const file = makeDisplayPath(fname.absFilename(), 30);
1850                 docstring text = bformat(_("The document %1$s already "
1851                                            "exists.\n\nDo you want to "
1852                                            "overwrite that document?"), 
1853                                          file);
1854                 int const ret = Alert::prompt(_("Overwrite document?"),
1855                         text, 0, 2, _("&Overwrite"), _("&Rename"), _("&Cancel"));
1856                 switch (ret) {
1857                 case 0: break;
1858                 case 1: return renameBuffer(b, docstring());
1859                 case 2: return false;
1860                 }
1861         }
1862
1863         FileName oldauto = b.getAutosaveFilename();
1864
1865         // Ok, change the name of the buffer
1866         b.setFileName(fname.absFilename());
1867         b.markDirty();
1868         bool unnamed = b.isUnnamed();
1869         b.setUnnamed(false);
1870         b.saveCheckSum(fname);
1871
1872         // bring the autosave file with us, just in case.
1873         b.moveAutosaveFile(oldauto);
1874         
1875         if (!saveBuffer(b)) {
1876                 oldauto = b.getAutosaveFilename();
1877                 b.setFileName(oldname.absFilename());
1878                 b.setUnnamed(unnamed);
1879                 b.saveCheckSum(oldname);
1880                 b.moveAutosaveFile(oldauto);
1881                 return false;
1882         }
1883
1884         return true;
1885 }
1886
1887
1888 bool GuiView::saveBuffer(Buffer & b)
1889 {
1890         if (workArea(b) && workArea(b)->inDialogMode())
1891                 return true;
1892
1893         if (b.isUnnamed())
1894                 return renameBuffer(b, docstring());
1895
1896         if (b.save()) {
1897                 theSession().lastFiles().add(b.fileName());
1898                 return true;
1899         }
1900
1901         // Switch to this Buffer.
1902         setBuffer(&b);
1903
1904         // FIXME: we don't tell the user *WHY* the save failed !!
1905         docstring const file = makeDisplayPath(b.absFileName(), 30);
1906         docstring text = bformat(_("The document %1$s could not be saved.\n\n"
1907                                    "Do you want to rename the document and "
1908                                    "try again?"), file);
1909         int const ret = Alert::prompt(_("Rename and save?"),
1910                 text, 0, 2, _("&Rename"), _("&Retry"), _("&Cancel"));
1911         switch (ret) {
1912         case 0:
1913                 if (!renameBuffer(b, docstring()))
1914                         return false;
1915                 break;
1916         case 1:
1917                 break;
1918         case 2:
1919                 return false;
1920         }
1921
1922         return saveBuffer(b);
1923 }
1924
1925
1926 bool GuiView::closeBuffer()
1927 {
1928         Buffer * buf = buffer();
1929         return buf && closeBuffer(*buf, !buf->parent());
1930 }
1931
1932
1933 bool GuiView::closeBuffer(Buffer & buf, bool close_buffer,
1934         bool tolastopened, bool mark_active)
1935 {
1936         // goto bookmark to update bookmark pit.
1937         //FIXME: we should update only the bookmarks related to this buffer!
1938         LYXERR(Debug::DEBUG, "GuiView::closeBuffer()");
1939         for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
1940                 theLyXFunc().gotoBookmark(i+1, false, false);
1941
1942         if (saveBufferIfNeeded(buf)) {
1943                 // save in sessions if requested
1944                 // do not save childs if their master
1945                 // is opened as well
1946                 if (tolastopened)
1947                         theSession().lastOpened().add(buf.fileName(), mark_active);
1948                 if (!close_buffer)
1949                         removeWorkArea(currentMainWorkArea());
1950                 else
1951                         theBufferList().release(&buf);
1952                 return true;
1953         }
1954         return false;
1955 }
1956
1957
1958 bool GuiView::saveBufferIfNeeded(Buffer & buf)
1959 {
1960         if (buf.isClean() || buf.paragraphs().empty())
1961                 return true;
1962
1963         // Switch to this Buffer.
1964         setBuffer(&buf);
1965
1966         docstring file;
1967         // FIXME: Unicode?
1968         if (buf.isUnnamed())
1969                 file = from_utf8(buf.fileName().onlyFileName());
1970         else
1971                 file = buf.fileName().displayName(30);
1972
1973         // Bring this window to top before asking questions.
1974         raise();
1975         activateWindow();
1976
1977         docstring const text = bformat(_("The document %1$s has unsaved changes."
1978                 "\n\nDo you want to save the document or discard the changes?"), file);
1979         int const ret = Alert::prompt(_("Save changed document?"),
1980                 text, 0, 2, _("&Save"), _("&Discard"), _("&Cancel"));
1981
1982         switch (ret) {
1983         case 0:
1984                 if (!saveBuffer(buf))
1985                         return false;
1986                 break;
1987         case 1:
1988                 // if we crash after this we could
1989                 // have no autosave file but I guess
1990                 // this is really improbable (Jug)
1991                 buf.removeAutosaveFile();
1992                 break;
1993         case 2:
1994                 return false;
1995         }
1996         return true;
1997 }
1998
1999
2000 void GuiView::gotoNextOrPreviousBuffer(NextOrPrevious np)
2001 {
2002         Buffer * const curbuf = buffer();
2003         Buffer * nextbuf = curbuf;
2004         while (true) {
2005                 if (np == NEXTBUFFER)
2006                         nextbuf = theBufferList().next(nextbuf);
2007                 else
2008                         nextbuf = theBufferList().previous(nextbuf);
2009                 if (nextbuf == curbuf)
2010                         break;
2011                 if (nextbuf == 0) {
2012                         nextbuf = curbuf;
2013                         break;
2014                 }
2015                 if (workArea(*nextbuf))
2016                         break;
2017         }
2018         setBuffer(nextbuf);
2019 }
2020
2021
2022 bool GuiView::dispatch(FuncRequest const & cmd)
2023 {
2024         BufferView * bv = view();
2025         // By default we won't need any update.
2026         if (bv)
2027                 bv->cursor().updateFlags(Update::None);
2028         bool dispatched = true;
2029
2030         if (cmd.origin == FuncRequest::TOC) {
2031                 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
2032                 toc->doDispatch(bv->cursor(), cmd);
2033                 return true;
2034         }
2035
2036         switch(cmd.action) {
2037                 case LFUN_BUFFER_IMPORT:
2038                         importDocument(to_utf8(cmd.argument()));
2039                         break;
2040
2041                 case LFUN_BUFFER_SWITCH:
2042                         if (FileName::isAbsolute(to_utf8(cmd.argument()))) {
2043                                 Buffer * buffer = 
2044                                         theBufferList().getBuffer(FileName(to_utf8(cmd.argument())));
2045                                 if (buffer)
2046                                         setBuffer(buffer);
2047                                 else
2048                                         bv->cursor().message(_("Document not loaded"));
2049                         }
2050                         break;
2051
2052                 case LFUN_BUFFER_NEXT:
2053                         gotoNextOrPreviousBuffer(NEXTBUFFER);
2054                         break;
2055
2056                 case LFUN_BUFFER_PREVIOUS:
2057                         gotoNextOrPreviousBuffer(PREVBUFFER);
2058                         break;
2059
2060                 case LFUN_COMMAND_EXECUTE: {
2061                         bool const show_it = cmd.argument() != "off";
2062                         // FIXME: this is a hack, "minibuffer" should not be
2063                         // hardcoded.
2064                         if (GuiToolbar * t = toolbar("minibuffer")) {
2065                                 t->setVisible(show_it);
2066                                 if (show_it && t->commandBuffer())
2067                                         t->commandBuffer()->setFocus();
2068                         }
2069                         break;
2070                 }
2071                 case LFUN_DROP_LAYOUTS_CHOICE:
2072                         if (d.layout_)
2073                                 d.layout_->showPopup();
2074                         break;
2075
2076                 case LFUN_MENU_OPEN:
2077                         if (QMenu * menu = guiApp->menus().menu(toqstr(cmd.argument()), *this))
2078                                 menu->exec(QCursor::pos());
2079                         break;
2080
2081                 case LFUN_FILE_INSERT:
2082                         insertLyXFile(cmd.argument());
2083                         break;
2084                 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
2085                         insertPlaintextFile(cmd.argument(), true);
2086                         break;
2087
2088                 case LFUN_FILE_INSERT_PLAINTEXT:
2089                         insertPlaintextFile(cmd.argument(), false);
2090                         break;
2091
2092                 case LFUN_BUFFER_WRITE:
2093                         if (bv)
2094                                 saveBuffer(bv->buffer());
2095                         break;
2096
2097                 case LFUN_BUFFER_WRITE_AS:
2098                         if (bv)
2099                                 renameBuffer(bv->buffer(), cmd.argument());
2100                         break;
2101
2102                 case LFUN_BUFFER_WRITE_ALL: {
2103                         Buffer * first = theBufferList().first();
2104                         if (!first)
2105                                 break;
2106                         message(_("Saving all documents..."));
2107                         // We cannot use a for loop as the buffer list cycles.
2108                         Buffer * b = first;
2109                         do {
2110                                 if (!b->isClean()) {
2111                                         saveBuffer(*b);
2112                                         LYXERR(Debug::ACTION, "Saved " << b->absFileName());
2113                                 }
2114                                 b = theBufferList().next(b);
2115                         } while (b != first); 
2116                         message(_("All documents saved."));
2117                         break;
2118                 }
2119
2120                 case LFUN_TOOLBAR_TOGGLE: {
2121                         string const name = cmd.getArg(0);
2122                         if (GuiToolbar * t = toolbar(name))
2123                                 t->toggle();
2124                         break;
2125                 }
2126
2127                 case LFUN_DIALOG_UPDATE: {
2128                         string const name = to_utf8(cmd.argument());
2129                         // Can only update a dialog connected to an existing inset
2130                         Inset * inset = getOpenInset(name);
2131                         if (inset) {
2132                                 FuncRequest fr(LFUN_INSET_DIALOG_UPDATE, cmd.argument());
2133                                 inset->dispatch(view()->cursor(), fr);
2134                         } else if (name == "paragraph") {
2135                                 lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
2136                         } else if (name == "prefs" || name == "document") {
2137                                 updateDialog(name, string());
2138                         }
2139                         break;
2140                 }
2141
2142                 case LFUN_DIALOG_TOGGLE: {
2143                         if (isDialogVisible(cmd.getArg(0)))
2144                                 dispatch(FuncRequest(LFUN_DIALOG_HIDE, cmd.argument()));
2145                         else
2146                                 dispatch(FuncRequest(LFUN_DIALOG_SHOW, cmd.argument()));
2147                         break;
2148                 }
2149
2150                 case LFUN_DIALOG_DISCONNECT_INSET:
2151                         disconnectDialog(to_utf8(cmd.argument()));
2152                         break;
2153
2154                 case LFUN_DIALOG_HIDE: {
2155                         guiApp->hideDialogs(to_utf8(cmd.argument()), 0);
2156                         break;
2157                 }
2158
2159                 case LFUN_DIALOG_SHOW: {
2160                         string const name = cmd.getArg(0);
2161                         string data = trim(to_utf8(cmd.argument()).substr(name.size()));
2162
2163                         if (name == "character") {
2164                                 data = freefont2string();
2165                                 if (!data.empty())
2166                                         showDialog("character", data);
2167                         } else if (name == "latexlog") {
2168                                 Buffer::LogType type; 
2169                                 string const logfile = buffer()->logName(&type);
2170                                 switch (type) {
2171                                 case Buffer::latexlog:
2172                                         data = "latex ";
2173                                         break;
2174                                 case Buffer::buildlog:
2175                                         data = "literate ";
2176                                         break;
2177                                 }
2178                                 data += Lexer::quoteString(logfile);
2179                                 showDialog("log", data);
2180                         } else if (name == "vclog") {
2181                                 string const data = "vc " +
2182                                         Lexer::quoteString(buffer()->lyxvc().getLogFile());
2183                                 showDialog("log", data);
2184                         } else if (name == "symbols") {
2185                                 data = bv->cursor().getEncoding()->name();
2186                                 if (!data.empty())
2187                                         showDialog("symbols", data);
2188                         // bug 5274
2189                         } else if (name == "prefs" && isFullScreen()) {
2190                                 FuncRequest fr(LFUN_INSET_INSERT, "fullscreen");
2191                                 lfunUiToggle(fr);
2192                                 showDialog("prefs", data);
2193                         } else
2194                                 showDialog(name, data);
2195                         break;
2196                 }
2197
2198                 case LFUN_INSET_APPLY: {
2199                         string const name = cmd.getArg(0);
2200                         Inset * inset = getOpenInset(name);
2201                         if (inset) {
2202                                 // put cursor in front of inset.
2203                                 if (!view()->setCursorFromInset(inset)) {
2204                                         LASSERT(false, break);
2205                                 }
2206                                 
2207                                 // useful if we are called from a dialog.
2208                                 view()->cursor().beginUndoGroup();
2209                                 view()->cursor().recordUndo();
2210                                 FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument());
2211                                 inset->dispatch(view()->cursor(), fr);
2212                                 view()->cursor().endUndoGroup();
2213                         } else {
2214                                 FuncRequest fr(LFUN_INSET_INSERT, cmd.argument());
2215                                 lyx::dispatch(fr);
2216                         }
2217                         break;
2218                 }
2219
2220                 case LFUN_UI_TOGGLE:
2221                         lfunUiToggle(cmd);
2222                         // Make sure the keyboard focus stays in the work area.
2223                         setFocus();
2224                         break;
2225
2226                 case LFUN_SPLIT_VIEW:
2227                         if (Buffer * buf = buffer()) {
2228                                 string const orientation = cmd.getArg(0);
2229                                 d.splitter_->setOrientation(orientation == "vertical"
2230                                         ? Qt::Vertical : Qt::Horizontal);
2231                                 TabWorkArea * twa = addTabWorkArea();
2232                                 GuiWorkArea * wa = twa->addWorkArea(*buf, *this);
2233                                 setCurrentWorkArea(wa);
2234                         }
2235                         break;
2236
2237                 case LFUN_CLOSE_TAB_GROUP:
2238                         if (TabWorkArea * twa = d.currentTabWorkArea()) {
2239                                 delete twa;
2240                                 twa = d.currentTabWorkArea();
2241                                 // Switch to the next GuiWorkArea in the found TabWorkArea.
2242                                 if (twa) {
2243                                         // Make sure the work area is up to date.
2244                                         setCurrentWorkArea(twa->currentWorkArea());
2245                                 } else {
2246                                         setCurrentWorkArea(0);
2247                                 }
2248                         }
2249                         break;
2250                         
2251                 case LFUN_COMPLETION_INLINE:
2252                         if (d.current_work_area_)
2253                                 d.current_work_area_->completer().showInline();
2254                         break;
2255
2256                 case LFUN_COMPLETION_POPUP:
2257                         if (d.current_work_area_)
2258                                 d.current_work_area_->completer().showPopup();
2259                         break;
2260
2261
2262                 case LFUN_COMPLETION_COMPLETE:
2263                         if (d.current_work_area_)
2264                                 d.current_work_area_->completer().tab();
2265                         break;
2266
2267                 case LFUN_COMPLETION_CANCEL:
2268                         if (d.current_work_area_) {
2269                                 if (d.current_work_area_->completer().popupVisible())
2270                                         d.current_work_area_->completer().hidePopup();
2271                                 else
2272                                         d.current_work_area_->completer().hideInline();
2273                         }
2274                         break;
2275
2276                 case LFUN_COMPLETION_ACCEPT:
2277                         if (d.current_work_area_)
2278                                 d.current_work_area_->completer().activate();
2279                         break;
2280
2281                 case LFUN_BUFFER_ZOOM_IN:
2282                 case LFUN_BUFFER_ZOOM_OUT:
2283                         if (cmd.argument().empty()) {
2284                                 if (cmd.action == LFUN_BUFFER_ZOOM_IN)
2285                                         lyxrc.zoom += 20;
2286                                 else
2287                                         lyxrc.zoom -= 20;
2288                         } else
2289                                 lyxrc.zoom += convert<int>(cmd.argument());
2290
2291                         if (lyxrc.zoom < 10)
2292                                 lyxrc.zoom = 10;
2293                                 
2294                         // The global QPixmapCache is used in GuiPainter to cache text
2295                         // painting so we must reset it.
2296                         QPixmapCache::clear();
2297                         guiApp->fontLoader().update();
2298                         lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
2299                         break;
2300
2301                 default:
2302                         dispatched = false;
2303                         break;
2304         }
2305
2306         // Part of automatic menu appearance feature.
2307         if (isFullScreen()) {
2308                 if (menuBar()->isVisible() && lyxrc.full_screen_menubar)
2309                         menuBar()->hide();
2310                 if (statusBar()->isVisible())
2311                         statusBar()->hide();
2312         }
2313
2314         return dispatched;
2315 }
2316
2317
2318 void GuiView::lfunUiToggle(FuncRequest const & cmd)
2319 {
2320         string const arg = cmd.getArg(0);
2321         if (arg == "scrollbar") {
2322                 // hide() is of no help
2323                 if (d.current_work_area_->verticalScrollBarPolicy() ==
2324                         Qt::ScrollBarAlwaysOff)
2325
2326                         d.current_work_area_->setVerticalScrollBarPolicy(
2327                                 Qt::ScrollBarAsNeeded);
2328                 else
2329                         d.current_work_area_->setVerticalScrollBarPolicy(
2330                                 Qt::ScrollBarAlwaysOff);
2331                 return;
2332         }
2333         if (arg == "statusbar") {
2334                 statusBar()->setVisible(!statusBar()->isVisible());
2335                 return;
2336         }
2337         if (arg == "menubar") {
2338                 menuBar()->setVisible(!menuBar()->isVisible());
2339                 return;
2340         }
2341 #if QT_VERSION >= 0x040300
2342         if (arg == "frame") {
2343                 int l, t, r, b;
2344                 getContentsMargins(&l, &t, &r, &b);
2345                 //are the frames in default state?
2346                 d.current_work_area_->setFrameStyle(QFrame::NoFrame);
2347                 if (l == 0) {
2348                         setContentsMargins(-2, -2, -2, -2);
2349                 } else {
2350                         setContentsMargins(0, 0, 0, 0);
2351                 }
2352                 return;
2353         }
2354 #endif
2355         if (arg == "fullscreen") {
2356                 toggleFullScreen();
2357                 return;
2358         }
2359
2360         message(bformat("LFUN_UI_TOGGLE " + _("%1$s unknown command!"), from_utf8(arg)));
2361 }
2362
2363
2364 void GuiView::toggleFullScreen()
2365 {
2366         if (isFullScreen()) {
2367                 for (int i = 0; i != d.splitter_->count(); ++i)
2368                         d.tabWorkArea(i)->setFullScreen(false);
2369 #if QT_VERSION >= 0x040300
2370                 setContentsMargins(0, 0, 0, 0);
2371 #endif
2372                 setWindowState(windowState() ^ Qt::WindowFullScreen);
2373                 restoreLayout();
2374                 menuBar()->show();
2375                 statusBar()->show();
2376         } else {
2377                 // bug 5274
2378                 hideDialogs("prefs", 0);
2379                 for (int i = 0; i != d.splitter_->count(); ++i)
2380                         d.tabWorkArea(i)->setFullScreen(true);
2381 #if QT_VERSION >= 0x040300
2382                 setContentsMargins(-2, -2, -2, -2);
2383 #endif
2384                 saveLayout();
2385                 setWindowState(windowState() ^ Qt::WindowFullScreen);
2386                 statusBar()->hide();
2387                 if (lyxrc.full_screen_menubar)
2388                         menuBar()->hide();
2389                 if (lyxrc.full_screen_toolbars) {
2390                         ToolbarMap::iterator end = d.toolbars_.end();
2391                         for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
2392                                 it->second->hide();
2393                 }
2394         }
2395
2396         // give dialogs like the TOC a chance to adapt
2397         updateDialogs();
2398 }
2399
2400
2401 Buffer const * GuiView::updateInset(Inset const * inset)
2402 {
2403         if (!d.current_work_area_)
2404                 return 0;
2405
2406         if (inset)
2407                 d.current_work_area_->scheduleRedraw();
2408
2409         return &d.current_work_area_->bufferView().buffer();
2410 }
2411
2412
2413 void GuiView::restartCursor()
2414 {
2415         /* When we move around, or type, it's nice to be able to see
2416          * the cursor immediately after the keypress.
2417          */
2418         if (d.current_work_area_)
2419                 d.current_work_area_->startBlinkingCursor();
2420
2421         // Take this occasion to update the other GUI elements.
2422         updateDialogs();
2423         updateStatusBar();
2424 }
2425
2426
2427 void GuiView::updateCompletion(Cursor & cur, bool start, bool keep)
2428 {
2429         if (d.current_work_area_)
2430                 d.current_work_area_->completer().updateVisibility(cur, start, keep);
2431 }
2432
2433 namespace {
2434
2435 // This list should be kept in sync with the list of insets in
2436 // src/insets/Inset.cpp.  I.e., if a dialog goes with an inset, the
2437 // dialog should have the same name as the inset.
2438 // Changes should be also recorded in LFUN_DIALOG_SHOW doxygen
2439 // docs in LyXAction.cpp.
2440
2441 char const * const dialognames[] = {
2442 "aboutlyx", "bibitem", "bibtex", "box", "branch", "changes", "character",
2443 "citation", "document", "errorlist", "ert", "external", "file", "findreplace",
2444 "findreplaceadv", "float", "graphics", "href", "include", "index",
2445 "index_print", "info", "listings", "label", "log", "mathdelimiter",
2446 "mathmatrix", "mathspace", "nomenclature", "nomencl_print", "note",
2447 "paragraph", "phantom", "prefs", "print", "ref", "sendto", "space",
2448 "spellchecker", "symbols", "tabular", "tabularcreate", "thesaurus", "texinfo",
2449 "toc", "view-source", "vspace", "wrap" };
2450
2451 char const * const * const end_dialognames =
2452         dialognames + (sizeof(dialognames) / sizeof(char *));
2453
2454 class cmpCStr {
2455 public:
2456         cmpCStr(char const * name) : name_(name) {}
2457         bool operator()(char const * other) {
2458                 return strcmp(other, name_) == 0;
2459         }
2460 private:
2461         char const * name_;
2462 };
2463
2464
2465 bool isValidName(string const & name)
2466 {
2467         return find_if(dialognames, end_dialognames,
2468                             cmpCStr(name.c_str())) != end_dialognames;
2469 }
2470
2471 } // namespace anon
2472
2473
2474 void GuiView::resetDialogs()
2475 {
2476         // Make sure that no LFUN uses any LyXView.
2477         theLyXFunc().setLyXView(0);
2478         saveLayout();
2479         menuBar()->clear();
2480         constructToolbars();
2481         guiApp->menus().fillMenuBar(menuBar(), this, false);
2482         if (d.layout_)
2483                 d.layout_->updateContents(true);
2484         // Now update controls with current buffer.
2485         theLyXFunc().setLyXView(this);
2486         restoreLayout();
2487         restartCursor();
2488 }
2489
2490
2491 Dialog * GuiView::findOrBuild(string const & name, bool hide_it)
2492 {
2493         if (!isValidName(name))
2494                 return 0;
2495
2496         map<string, DialogPtr>::iterator it = d.dialogs_.find(name);
2497
2498         if (it != d.dialogs_.end()) {
2499                 if (hide_it)
2500                         it->second->hideView();
2501                 return it->second.get();
2502         }
2503
2504         Dialog * dialog = build(name);
2505         d.dialogs_[name].reset(dialog);
2506         if (lyxrc.allow_geometry_session)
2507                 dialog->restoreSession();
2508         if (hide_it)
2509                 dialog->hideView();
2510         return dialog;
2511 }
2512
2513
2514 void GuiView::showDialog(string const & name, string const & data,
2515         Inset * inset)
2516 {
2517         if (d.in_show_)
2518                 return;
2519
2520         d.in_show_ = true;
2521         try {
2522                 Dialog * dialog = findOrBuild(name, false);
2523                 if (dialog) {
2524                         dialog->showData(data);
2525                         if (inset)
2526                                 d.open_insets_[name] = inset;
2527                 }
2528         }
2529         catch (ExceptionMessage const & ex) {
2530                 d.in_show_ = false;
2531                 throw ex;
2532         }
2533         d.in_show_ = false;
2534 }
2535
2536
2537 bool GuiView::isDialogVisible(string const & name) const
2538 {
2539         map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
2540         if (it == d.dialogs_.end())
2541                 return false;
2542         return it->second.get()->isVisibleView() && !it->second.get()->isClosing();
2543 }
2544
2545
2546 void GuiView::hideDialog(string const & name, Inset * inset)
2547 {
2548         map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
2549         if (it == d.dialogs_.end())
2550                 return;
2551
2552         if (inset && inset != getOpenInset(name))
2553                 return;
2554
2555         Dialog * const dialog = it->second.get();
2556         if (dialog->isVisibleView())
2557                 dialog->hideView();
2558         d.open_insets_[name] = 0;
2559 }
2560
2561
2562 void GuiView::disconnectDialog(string const & name)
2563 {
2564         if (!isValidName(name))
2565                 return;
2566
2567         if (d.open_insets_.find(name) != d.open_insets_.end())
2568                 d.open_insets_[name] = 0;
2569 }
2570
2571
2572 Inset * GuiView::getOpenInset(string const & name) const
2573 {
2574         if (!isValidName(name))
2575                 return 0;
2576
2577         map<string, Inset *>::const_iterator it = d.open_insets_.find(name);
2578         return it == d.open_insets_.end() ? 0 : it->second;
2579 }
2580
2581
2582 void GuiView::hideAll() const
2583 {
2584         map<string, DialogPtr>::const_iterator it  = d.dialogs_.begin();
2585         map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
2586
2587         for(; it != end; ++it)
2588                 it->second->hideView();
2589 }
2590
2591
2592 void GuiView::updateDialogs()
2593 {
2594         map<string, DialogPtr>::const_iterator it  = d.dialogs_.begin();
2595         map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
2596
2597         for(; it != end; ++it) {
2598                 Dialog * dialog = it->second.get();
2599                 if (dialog && dialog->isVisibleView())
2600                         dialog->checkStatus();
2601         }
2602         updateToolbars();
2603         updateLayoutList();
2604 }
2605
2606
2607 // will be replaced by a proper factory...
2608 Dialog * createGuiAbout(GuiView & lv);
2609 Dialog * createGuiBibitem(GuiView & lv);
2610 Dialog * createGuiBibtex(GuiView & lv);
2611 Dialog * createGuiBox(GuiView & lv);
2612 Dialog * createGuiBranch(GuiView & lv);
2613 Dialog * createGuiChanges(GuiView & lv);
2614 Dialog * createGuiCharacter(GuiView & lv);
2615 Dialog * createGuiCitation(GuiView & lv);
2616 Dialog * createGuiDelimiter(GuiView & lv);
2617 Dialog * createGuiDocument(GuiView & lv);
2618 Dialog * createGuiErrorList(GuiView & lv);
2619 Dialog * createGuiERT(GuiView & lv);
2620 Dialog * createGuiExternal(GuiView & lv);
2621 Dialog * createGuiFloat(GuiView & lv);
2622 Dialog * createGuiGraphics(GuiView & lv);
2623 Dialog * createGuiInclude(GuiView & lv);
2624 Dialog * createGuiIndex(GuiView & lv);
2625 Dialog * createGuiInfo(GuiView & lv);
2626 Dialog * createGuiLabel(GuiView & lv);
2627 Dialog * createGuiListings(GuiView & lv);
2628 Dialog * createGuiLog(GuiView & lv);
2629 Dialog * createGuiMathHSpace(GuiView & lv);
2630 Dialog * createGuiMathMatrix(GuiView & lv);
2631 Dialog * createGuiNomenclature(GuiView & lv);
2632 Dialog * createGuiNote(GuiView & lv);
2633 Dialog * createGuiParagraph(GuiView & lv);
2634 Dialog * createGuiPhantom(GuiView & lv);
2635 Dialog * createGuiPreferences(GuiView & lv);
2636 Dialog * createGuiPrint(GuiView & lv);
2637 Dialog * createGuiPrintindex(GuiView & lv);
2638 Dialog * createGuiPrintNomencl(GuiView & lv);
2639 Dialog * createGuiRef(GuiView & lv);
2640 Dialog * createGuiSearch(GuiView & lv);
2641 Dialog * createGuiSearchAdv(GuiView & lv);
2642 Dialog * createGuiSendTo(GuiView & lv);
2643 Dialog * createGuiShowFile(GuiView & lv);
2644 Dialog * createGuiSpellchecker(GuiView & lv);
2645 Dialog * createGuiSymbols(GuiView & lv);
2646 Dialog * createGuiTabularCreate(GuiView & lv);
2647 Dialog * createGuiTabular(GuiView & lv);
2648 Dialog * createGuiTexInfo(GuiView & lv);
2649 Dialog * createGuiTextHSpace(GuiView & lv);
2650 Dialog * createGuiToc(GuiView & lv);
2651 Dialog * createGuiThesaurus(GuiView & lv);
2652 Dialog * createGuiHyperlink(GuiView & lv);
2653 Dialog * createGuiVSpace(GuiView & lv);
2654 Dialog * createGuiViewSource(GuiView & lv);
2655 Dialog * createGuiWrap(GuiView & lv);
2656
2657
2658 Dialog * GuiView::build(string const & name)
2659 {
2660         LASSERT(isValidName(name), return 0);
2661
2662         if (name == "aboutlyx")
2663                 return createGuiAbout(*this);
2664         if (name == "bibitem")
2665                 return createGuiBibitem(*this);
2666         if (name == "bibtex")
2667                 return createGuiBibtex(*this);
2668         if (name == "box")
2669                 return createGuiBox(*this);
2670         if (name == "branch")
2671                 return createGuiBranch(*this);
2672         if (name == "changes")
2673                 return createGuiChanges(*this);
2674         if (name == "character")
2675                 return createGuiCharacter(*this);
2676         if (name == "citation")
2677                 return createGuiCitation(*this);
2678         if (name == "document")
2679                 return createGuiDocument(*this);
2680         if (name == "errorlist")
2681                 return createGuiErrorList(*this);
2682         if (name == "ert")
2683                 return createGuiERT(*this);
2684         if (name == "external")
2685                 return createGuiExternal(*this);
2686         if (name == "file")
2687                 return createGuiShowFile(*this);
2688         if (name == "findreplace")
2689                 return createGuiSearch(*this);
2690         if (name == "findreplaceadv")
2691                 return createGuiSearchAdv(*this);
2692         if (name == "float")
2693                 return createGuiFloat(*this);
2694         if (name == "graphics")
2695                 return createGuiGraphics(*this);
2696         if (name == "href")
2697                 return createGuiHyperlink(*this);
2698         if (name == "include")
2699                 return createGuiInclude(*this);
2700         if (name == "index")
2701                 return createGuiIndex(*this);
2702         if (name == "index_print")
2703                 return createGuiPrintindex(*this);
2704         if (name == "info")
2705                 return createGuiInfo(*this);
2706         if (name == "label")
2707                 return createGuiLabel(*this);
2708         if (name == "listings")
2709                 return createGuiListings(*this);
2710         if (name == "log")
2711                 return createGuiLog(*this);
2712         if (name == "mathdelimiter")
2713                 return createGuiDelimiter(*this);
2714         if (name == "mathspace")
2715                 return createGuiMathHSpace(*this);
2716         if (name == "mathmatrix")
2717                 return createGuiMathMatrix(*this);
2718         if (name == "nomenclature")
2719                 return createGuiNomenclature(*this);
2720         if (name == "nomencl_print")
2721                 return createGuiPrintNomencl(*this);
2722         if (name == "note")
2723                 return createGuiNote(*this);
2724         if (name == "paragraph")
2725                 return createGuiParagraph(*this);
2726         if (name == "phantom")
2727                 return createGuiPhantom(*this);
2728         if (name == "prefs")
2729                 return createGuiPreferences(*this);
2730         if (name == "print")
2731                 return createGuiPrint(*this);
2732         if (name == "ref")
2733                 return createGuiRef(*this);
2734         if (name == "sendto")
2735                 return createGuiSendTo(*this);
2736         if (name == "space")
2737                 return createGuiTextHSpace(*this);
2738         if (name == "spellchecker")
2739                 return createGuiSpellchecker(*this);
2740         if (name == "symbols")
2741                 return createGuiSymbols(*this);
2742         if (name == "tabular")
2743                 return createGuiTabular(*this);
2744         if (name == "tabularcreate")
2745                 return createGuiTabularCreate(*this);
2746         if (name == "texinfo")
2747                 return createGuiTexInfo(*this);
2748         if (name == "thesaurus")
2749                 return createGuiThesaurus(*this);
2750         if (name == "toc")
2751                 return createGuiToc(*this);
2752         if (name == "view-source")
2753                 return createGuiViewSource(*this);
2754         if (name == "vspace")
2755                 return createGuiVSpace(*this);
2756         if (name == "wrap")
2757                 return createGuiWrap(*this);
2758
2759         return 0;
2760 }
2761
2762
2763 } // namespace frontend
2764 } // namespace lyx
2765
2766 #include "moc_GuiView.cpp"