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