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