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