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