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