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