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