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