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