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