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