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