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