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