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