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