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