]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiView.cpp
Fix the disappearing minibuffer by don't pretending we are flexible.
[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 "GuiImplementation.h"
19 #include "GuiWorkArea.h"
20 #include "GuiKeySymbol.h"
21 #include "GuiMenubar.h"
22 #include "GuiToolbar.h"
23 #include "GuiToolbars.h"
24 #include "Dialogs.h"
25 #include "Gui.h"
26
27 #include "qt_helpers.h"
28
29 #include "frontends/Application.h"
30 #include "frontends/Dialogs.h"
31 #include "frontends/Gui.h"
32
33 #include "support/filetools.h"
34 #include "support/convert.h"
35 #include "support/lstrings.h"
36 #include "support/os.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 "Cursor.h"
44 #include "debug.h"
45 #include "ErrorList.h"
46 #include "FuncRequest.h"
47 #include "gettext.h"
48 #include "Intl.h"
49 #include "Layout.h"
50 #include "LyXFunc.h"
51 #include "LyX.h"
52 #include "LyXRC.h"
53 #include "MenuBackend.h"
54 #include "Paragraph.h"
55 #include "Session.h"
56 #include "TextClass.h"
57 #include "Text.h"
58 #include "ToolbarBackend.h"
59 #include "version.h"
60
61 #include "support/lstrings.h"
62 #include "support/filetools.h" // OnlyFilename()
63 #include "support/Timeout.h"
64
65 #include <QAction>
66 #include <QApplication>
67 #include <QCloseEvent>
68 #include <QDesktopWidget>
69 #include <QDragEnterEvent>
70 #include <QDropEvent>
71 #include <QList>
72 #include <QMenu>
73 #include <QPainter>
74 #include <QPixmap>
75 #include <QPushButton>
76 #include <QSplitter>
77 #include <QStackedWidget>
78 #include <QStatusBar>
79 #include <QToolBar>
80 #include <QUrl>
81
82 #include <boost/bind.hpp>
83 #include <boost/current_function.hpp>
84
85 #ifdef HAVE_SYS_TIME_H
86 # include <sys/time.h>
87 #endif
88 #ifdef HAVE_UNISTD_H
89 # include <unistd.h>
90 #endif
91
92 using std::endl;
93 using std::string;
94 using std::vector;
95
96 namespace lyx {
97
98 extern bool quitting;
99
100 namespace frontend {
101
102 using support::bformat;
103 using support::FileName;
104 using support::makeDisplayPath;
105 using support::onlyFilename;
106
107 namespace {
108
109 int const statusbar_timer_value = 3000;
110
111 class BackgroundWidget : public QWidget
112 {
113 public:
114         BackgroundWidget(QString const & file, QString const & text)
115         {
116                 splash_ = new QPixmap(file);
117                 if (!splash_) {
118                         lyxerr << "could not load splash screen: '" << fromqstr(file) << "'" << endl;
119                         return;
120                 }
121
122                 QPainter pain(splash_);
123                 pain.setPen(QColor(255, 255, 0));
124                 QFont font;
125                 // The font used to display the version info
126                 font.setStyleHint(QFont::SansSerif);
127                 font.setWeight(QFont::Bold);
128                 font.setPointSize(convert<int>(lyxrc.font_sizes[FONT_SIZE_LARGE]));
129                 pain.setFont(font);
130                 pain.drawText(260, 270, text);
131         }
132
133         void paintEvent(QPaintEvent *)
134         {
135                 if (!splash_)
136                         return;
137
138                 int x = (width() - splash_->width()) / 2;
139                 int y = (height() - splash_->height()) / 2;
140                 QPainter pain(this);
141                 pain.drawPixmap(x, y, *splash_);
142         }
143
144 private:
145         QPixmap * splash_;
146 };
147
148 } // namespace anon
149
150
151 struct GuiView::GuiViewPrivate
152 {
153         GuiViewPrivate()
154                 : current_work_area_(0), posx_offset(0), posy_offset(0)
155         {}
156
157         ~GuiViewPrivate()
158         {
159                 delete splitter_;
160                 delete bg_widget_;
161                 delete stack_widget_;
162                 delete menubar_;
163                 delete toolbars_;
164         }
165
166         unsigned int smallIconSize;
167         unsigned int normalIconSize;
168         unsigned int bigIconSize;
169         // static needed by "New Window"
170         static unsigned int lastIconSize;
171
172         QMenu * toolBarPopup(GuiView * parent)
173         {
174                 // FIXME: translation
175                 QMenu * menu = new QMenu(parent);
176                 QActionGroup * iconSizeGroup = new QActionGroup(parent);
177
178                 QAction * smallIcons = new QAction(iconSizeGroup);
179                 smallIcons->setText(qt_("Small-sized icons"));
180                 smallIcons->setCheckable(true);
181                 QObject::connect(smallIcons, SIGNAL(triggered()),
182                         parent, SLOT(smallSizedIcons()));
183                 menu->addAction(smallIcons);
184
185                 QAction * normalIcons = new QAction(iconSizeGroup);
186                 normalIcons->setText(qt_("Normal-sized icons"));
187                 normalIcons->setCheckable(true);
188                 QObject::connect(normalIcons, SIGNAL(triggered()),
189                         parent, SLOT(normalSizedIcons()));
190                 menu->addAction(normalIcons);
191
192                 QAction * bigIcons = new QAction(iconSizeGroup);
193                 bigIcons->setText(qt_("Big-sized icons"));
194                 bigIcons->setCheckable(true);
195                 QObject::connect(bigIcons, SIGNAL(triggered()),
196                         parent, SLOT(bigSizedIcons()));
197                 menu->addAction(bigIcons);
198
199                 unsigned int cur = parent->iconSize().width();
200                 if ( cur == parent->d.smallIconSize)
201                         smallIcons->setChecked(true);
202                 else if (cur == parent->d.normalIconSize)
203                         normalIcons->setChecked(true);
204                 else if (cur == parent->d.bigIconSize)
205                         bigIcons->setChecked(true);
206
207                 return menu;
208         }
209
210         void initBackground()
211         {
212                 LYXERR(Debug::GUI) << "show banner: " << lyxrc.show_banner << endl;
213                 /// The text to be written on top of the pixmap
214                 QString const text = lyx_version ? QString(lyx_version) : qt_("unknown version");
215                 bg_widget_ = new BackgroundWidget(":/images/banner.png", text);
216         }
217
218         void setBackground()
219         {
220                 stack_widget_->setCurrentWidget(bg_widget_);
221                 bg_widget_->setUpdatesEnabled(true);
222         }
223
224         TabWorkArea * tabWorkArea(int i)
225         {
226                 return dynamic_cast<TabWorkArea *>(splitter_->widget(i));
227         }
228
229         TabWorkArea * currentTabWorkArea()
230         {
231                 if (splitter_->count() == 1)
232                         // The first TabWorkArea is always the first one, if any.
233                         return tabWorkArea(0);
234
235                 TabWorkArea * tab_widget = 0;
236                 for (int i = 0; i != splitter_->count(); ++i) {
237                         QWidget * w = splitter_->widget(i);
238                         if (!w->hasFocus())
239                                 continue;
240                         tab_widget = dynamic_cast<TabWorkArea *>(w);
241                         if (tab_widget)
242                                 break;
243                 }
244
245                 return tab_widget;
246         }
247
248 public:
249         ///
250         string cur_title;
251
252         GuiWorkArea * current_work_area_;
253         int posx_offset;
254         int posy_offset;
255
256         QSplitter * splitter_;
257         QStackedWidget * stack_widget_;
258         BackgroundWidget * bg_widget_;
259         /// view's menubar
260         GuiMenubar * menubar_;
261         /// view's toolbars
262         GuiToolbars * toolbars_;
263         ///
264         docstring current_layout;
265 };
266
267
268 unsigned int GuiView::GuiViewPrivate::lastIconSize = 0;
269
270
271 GuiView::GuiView(int id)
272         : QMainWindow(), LyXView(id),
273           d(*new GuiViewPrivate),
274                 quitting_by_menu_(false),
275                 autosave_timeout_(new Timeout(5000)),
276           dialogs_(new Dialogs(*this))
277 {
278         // Start autosave timer
279         if (lyxrc.autosave) {
280                 autosave_timeout_->timeout.connect(boost::bind(&GuiView::autoSave, this));
281                 autosave_timeout_->setTimeout(lyxrc.autosave * 1000);
282                 autosave_timeout_->start();
283         }
284
285         // Qt bug? signal lastWindowClosed does not work
286         setAttribute(Qt::WA_QuitOnClose, false);
287         setAttribute(Qt::WA_DeleteOnClose, true);
288
289         // hardcode here the platform specific icon size
290         d.smallIconSize = 14;   // scaling problems
291         d.normalIconSize = 20;  // ok, default
292         d.bigIconSize = 26;             // better for some math icons
293
294 #ifndef Q_WS_MACX
295         // assign an icon to main form. We do not do it under Qt/Mac,
296         // since the icon is provided in the application bundle.
297         setWindowIcon(QPixmap(":/images/lyx.png"));
298 #endif
299
300
301         d.splitter_ = new QSplitter;
302
303         d.initBackground();
304         LYXERR(Debug::GUI) << "stack widget!" << endl;
305         d.stack_widget_ = new QStackedWidget;
306         d.stack_widget_->addWidget(d.bg_widget_);
307         d.stack_widget_->addWidget(d.splitter_);
308         setCentralWidget(d.stack_widget_);
309
310         // For Drag&Drop.
311         setAcceptDrops(true);
312 }
313
314
315 GuiView::~GuiView()
316 {
317         delete dialogs_;
318         delete autosave_timeout_;
319         delete &d;
320 }
321
322
323 void GuiView::close()
324 {
325         quitting_by_menu_ = true;
326         d.current_work_area_ = 0;
327         for (int i = 0; i != d.splitter_->count(); ++i) {
328                 TabWorkArea * twa = d.tabWorkArea(i);
329                 if (twa)
330                         twa->closeAll();
331         }
332         QMainWindow::close();
333         quitting_by_menu_ = false;
334 }
335
336
337 void GuiView::setFocus()
338 {
339         if (d.current_work_area_)
340                 d.current_work_area_->setFocus();
341         else
342                 QWidget::setFocus();
343 }
344
345
346 QMenu* GuiView::createPopupMenu()
347 {
348         return d.toolBarPopup(this);
349 }
350
351
352 void GuiView::init()
353 {
354         // GuiToolbars *must* be initialised before GuiMenubar.
355         d.toolbars_ = new GuiToolbars(*this);
356         // FIXME: GuiToolbars::init() cannot be integrated in the ctor
357         // because LyXFunc::getStatus() needs a properly initialized
358         // GuiToolbars object (for LFUN_TOOLBAR_TOGGLE).
359         d.toolbars_->init();
360         d.menubar_ = new GuiMenubar(this, menubackend);
361
362         statusBar()->setSizeGripEnabled(true);
363
364         QObject::connect(&statusbar_timer_, SIGNAL(timeout()),
365                 this, SLOT(clearMessage()));
366
367         d.setBackground();
368 }
369
370
371 void GuiView::closeEvent(QCloseEvent * close_event)
372 {
373         // we may have been called through the close window button
374         // which bypasses the LFUN machinery.
375         if (!quitting_by_menu_ && theApp()->gui().viewIds().size() == 1) {
376                 if (!theBufferList().quitWriteAll()) {
377                         close_event->ignore();
378                         return;
379                 }
380         }
381
382         // Make sure that no LFUN use this close to be closed View.
383         theLyXFunc().setLyXView(0);
384         // Make sure the timer time out will not trigger a statusbar update.
385         statusbar_timer_.stop();
386
387         theApp()->gui().unregisterView(id());
388         if (!theApp()->gui().viewIds().empty()) {
389                 // Just close the window and do nothing else if this is not the
390                 // last window.
391                 close_event->accept();
392                 return;
393         }
394
395         quitting = true;
396
397         // this is the place where we leave the frontend.
398         // it is the only point at which we start quitting.
399         saveGeometry();
400         close_event->accept();
401         // quit the event loop
402         qApp->quit();
403 }
404
405
406 void GuiView::dragEnterEvent(QDragEnterEvent * event)
407 {
408         if (event->mimeData()->hasUrls())
409                 event->accept();
410         /// \todo Ask lyx-devel is this is enough:
411         /// if (event->mimeData()->hasFormat("text/plain"))
412         ///     event->acceptProposedAction();
413 }
414
415
416 void GuiView::dropEvent(QDropEvent* event)
417 {
418         QList<QUrl> files = event->mimeData()->urls();
419         if (files.isEmpty())
420                 return;
421
422         LYXERR(Debug::GUI) << BOOST_CURRENT_FUNCTION
423                 << " got URLs!" << endl;
424         for (int i = 0; i != files.size(); ++i) {
425                 string const file = support::os::internal_path(fromqstr(
426                         files.at(i).toLocalFile()));
427                 if (!file.empty())
428                         dispatch(FuncRequest(LFUN_FILE_OPEN, file));
429         }
430 }
431
432
433 void GuiView::saveGeometry()
434 {
435         static bool done = false;
436         if (done)
437                 return;
438         else
439                 done = true;
440
441         // FIXME:
442         // change the ifdef to 'geometry = normalGeometry();' only
443         // when Trolltech has fixed the broken normalGeometry on X11:
444         // http://www.trolltech.com/developer/task-tracker/index_html?id=119684+&method=entry
445         // Then also the moveEvent, resizeEvent, and the
446         // code for floatingGeometry_ can be removed;
447         // adjust GuiView::setGeometry()
448
449         QRect normal_geometry;
450         Maximized maximized;
451 #ifdef Q_WS_WIN
452         normal_geometry = normalGeometry();
453         if (isMaximized()) {
454                 maximized = CompletelyMaximized;
455         } else {
456                 maximized = NotMaximized;
457         }
458 #else
459         normal_geometry = updateFloatingGeometry();
460
461         QDesktopWidget& dw = *qApp->desktop();
462         QRect desk = dw.availableGeometry(dw.primaryScreen());
463         // Qt bug on Linux: load completely maximized, vert max. save-> frameGeometry().height() is wrong
464         if (isMaximized() && desk.width() <= frameGeometry().width() && desk.height() <= frameGeometry().height()) {
465                 maximized = CompletelyMaximized;
466                 // maximizing does not work when the window is allready hor. or vert. maximized
467                 // Tested only on KDE
468                 int dh = frameGeometry().height() - height();
469                 if (desk.height() <= normal_geometry.height() + dh)
470                         normal_geometry.setHeight(normal_geometry.height() - 1);
471                 int dw = frameGeometry().width() - width();
472                 if (desk.width() <= normal_geometry.width() + dw)
473                         normal_geometry.setWidth(normal_geometry.width() - 1);
474         } else if (desk.height() <= frameGeometry().height()) {
475                 maximized = VerticallyMaximized;
476         } else if (desk.width() <= frameGeometry().width()) {
477                 maximized = HorizontallyMaximized;
478         } else {
479                 maximized = NotMaximized;
480         }
481 #endif
482
483         // save windows size and position
484         SessionInfoSection & info = LyX::ref().session().sessionInfo();
485         info.save("WindowWidth", convert<string>(normal_geometry.width()));
486         info.save("WindowHeight", convert<string>(normal_geometry.height()));
487         info.save("WindowMaximized", convert<string>(int(maximized)));
488         info.save("IconSizeXY", convert<string>(iconSize().width()));
489         if (lyxrc.geometry_xysaved) {
490                 info.save("WindowPosX", convert<string>(normal_geometry.x() + d.posx_offset));
491                 info.save("WindowPosY", convert<string>(normal_geometry.y() + d.posy_offset));
492         }
493         d.toolbars_->saveToolbarInfo();
494 }
495
496
497 void GuiView::setGeometry(unsigned int width,
498                           unsigned int height,
499                           int posx, int posy,
500                           GuiView::Maximized maximized,
501                           unsigned int iconSizeXY,
502                           const string & geometryArg)
503 {
504         // use last value (not at startup)
505         if (d.lastIconSize != 0)
506                 setIconSize(d.lastIconSize);
507         else if (iconSizeXY != 0)
508                 setIconSize(iconSizeXY);
509         else
510                 setIconSize(d.normalIconSize);
511
512         // only true when the -geometry option was NOT used
513         if (width != 0 && height != 0) {
514                 if (posx != -1 && posy != -1) {
515                         // if there are startup positioning problems:
516                         // http://doc.trolltech.com/4.2/qdesktopwidget.html
517                         QDesktopWidget& dw = *qApp->desktop();
518                         if (dw.isVirtualDesktop()) {
519                                 if(!dw.geometry().contains(posx, posy)) {
520                                         posx = 50;
521                                         posy = 50;
522                                 }
523                         } else {
524                                 // Which system doesn't use a virtual desktop?
525                                 // TODO save also last screen number and check if it is still availabe.
526                         }
527 #ifdef Q_WS_WIN
528                         // FIXME: use setGeometry only when Trolltech has fixed the qt4/X11 bug
529                         QWidget::setGeometry(posx, posy, width, height);
530 #else
531                         resize(width, height);
532                         move(posx, posy);
533 #endif
534                 } else {
535                         resize(width, height);
536                 }
537
538                 // remember original size
539                 floatingGeometry_ = QRect(posx, posy, width, height);
540
541                 if (maximized != NotMaximized) {
542                         if (maximized == CompletelyMaximized) {
543                                 setWindowState(Qt::WindowMaximized);
544                         } else {
545 #ifndef Q_WS_WIN
546                                 // TODO How to set by the window manager?
547                                 //      setWindowState(Qt::WindowVerticallyMaximized);
548                                 //      is not possible
549                                 QDesktopWidget& dw = *qApp->desktop();
550                                 QRect desk = dw.availableGeometry(dw.primaryScreen());
551                                 if (maximized == VerticallyMaximized)
552                                         resize(width, desk.height());
553                                 if (maximized == HorizontallyMaximized)
554                                         resize(desk.width(), height);
555 #endif
556                         }
557                 }
558         }
559         else
560         {
561                 // FIXME: move this code into parse_geometry() (LyX.cpp)
562 #ifdef Q_WS_WIN
563                 int x, y;
564                 int w, h;
565                 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)([+-][0-9]*)){0,1}" );
566                 re.indexIn(toqstr(geometryArg.c_str()));
567                 w = re.cap(1).toInt();
568                 h = re.cap(2).toInt();
569                 x = re.cap(3).toInt();
570                 y = re.cap(4).toInt();
571                 QWidget::setGeometry( x, y, w, h );
572 #else
573                 // silence warning
574                 (void)geometryArg;
575 #endif
576         }
577         
578         d.setBackground();
579         
580         show();
581
582         // after show geometry() has changed (Qt bug?)
583         // we compensate the drift when storing the position
584         d.posx_offset = 0;
585         d.posy_offset = 0;
586         if (width != 0 && height != 0)
587                 if (posx != -1 && posy != -1) {
588 #ifdef Q_WS_WIN
589                         d.posx_offset = posx - normalGeometry().x();
590                         d.posy_offset = posy - normalGeometry().y();
591 #else
592 #ifndef Q_WS_MACX
593                         if (maximized == NotMaximized) {
594                                 d.posx_offset = posx - geometry().x();
595                                 d.posy_offset = posy - geometry().y();
596                         }
597 #endif
598 #endif
599                 }
600 }
601
602
603 void GuiView::message(docstring const & str)
604 {
605         statusBar()->showMessage(toqstr(str));
606         statusbar_timer_.stop();
607         statusbar_timer_.start(statusbar_timer_value);
608 }
609
610
611 void GuiView::setIconSize(unsigned int size)
612 {
613         d.lastIconSize = size;
614         QMainWindow::setIconSize(QSize(size, size));
615 }
616
617
618 void GuiView::smallSizedIcons()
619 {
620         setIconSize(d.smallIconSize);
621 }
622
623
624 void GuiView::normalSizedIcons()
625 {
626         setIconSize(d.normalIconSize);
627 }
628
629
630 void GuiView::bigSizedIcons()
631 {
632         setIconSize(d.bigIconSize);
633 }
634
635
636 void GuiView::clearMessage()
637 {
638         if (!hasFocus())
639                 return;
640         theLyXFunc().setLyXView(this);
641         statusBar()->showMessage(toqstr(theLyXFunc().viewStatusMessage()));
642         statusbar_timer_.stop();
643 }
644
645
646 void GuiView::updateWindowTitle(GuiWorkArea * wa)
647 {
648         if (wa != d.current_work_area_)
649                 return;
650         setWindowTitle(qt_("LyX: ") + wa->windowTitle());
651         setWindowIconText(wa->windowIconText());
652 }
653
654
655 void GuiView::on_currentWorkAreaChanged(GuiWorkArea * wa)
656 {
657         disconnectBuffer();
658         disconnectBufferView();
659         connectBufferView(wa->bufferView());
660         connectBuffer(wa->bufferView().buffer());
661         d.current_work_area_ = wa;
662         QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
663                 this, SLOT(updateWindowTitle(GuiWorkArea *)));
664         updateWindowTitle(wa);
665
666         updateToc();
667         // Buffer-dependent dialogs should be updated or
668         // hidden. This should go here because some dialogs (eg ToC)
669         // require bv_->text.
670         dialogs_->updateBufferDependent(true);
671         updateToolbars();
672         updateLayoutChoice(false);
673         updateStatusBar();
674 }
675
676
677 void GuiView::updateStatusBar()
678 {
679         // let the user see the explicit message
680         if (statusbar_timer_.isActive())
681                 return;
682
683         statusBar()->showMessage(toqstr(theLyXFunc().viewStatusMessage()));
684 }
685
686
687 bool GuiView::hasFocus() const
688 {
689         return qApp->activeWindow() == this;
690 }
691
692
693 QRect  GuiView::updateFloatingGeometry()
694 {
695         QDesktopWidget& dw = *qApp->desktop();
696         QRect desk = dw.availableGeometry(dw.primaryScreen());
697         // remember only non-maximized sizes
698         if (!isMaximized() && desk.width() > frameGeometry().width() && desk.height() > frameGeometry().height()) {
699                 floatingGeometry_ = QRect(x(), y(), width(), height());
700         }
701         return floatingGeometry_;
702 }
703
704
705 void GuiView::resizeEvent(QResizeEvent *)
706 {
707         updateFloatingGeometry();
708 }
709
710
711 void GuiView::moveEvent(QMoveEvent *)
712 {
713         updateFloatingGeometry();
714 }
715
716
717 bool GuiView::event(QEvent * e)
718 {
719         switch (e->type())
720         {
721         // Useful debug code:
722         //case QEvent::ActivationChange:
723         //case QEvent::WindowDeactivate:
724         //case QEvent::Paint:
725         //case QEvent::Enter:
726         //case QEvent::Leave:
727         //case QEvent::HoverEnter:
728         //case QEvent::HoverLeave:
729         //case QEvent::HoverMove:
730         //case QEvent::StatusTip:
731         //case QEvent::DragEnter:
732         //case QEvent::DragLeave:
733         //case QEvent::Drop:
734         //      break;
735
736         case QEvent::WindowActivate: {
737                 theApp()->setCurrentView(*this);
738                 if (d.current_work_area_) {
739                         BufferView & bv = d.current_work_area_->bufferView();
740                         connectBufferView(bv);
741                         connectBuffer(bv.buffer());
742                         // The document structure, name and dialogs might have
743                         // changed in another view.
744                         dialogs_->updateBufferDependent(true);
745                 } else {
746                         setWindowTitle(qt_("LyX"));
747                         setWindowIconText(qt_("LyX"));
748                 }
749                 return QMainWindow::event(e);
750         }
751         case QEvent::ShortcutOverride: {
752                 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
753                 if (!d.current_work_area_) {
754                         theLyXFunc().setLyXView(this);
755                         KeySymbol sym;
756                         setKeySymbol(&sym, ke);
757                         theLyXFunc().processKeySym(sym, q_key_state(ke->modifiers()));
758                         e->accept();
759                         return true;
760                 }
761                 if (ke->key() == Qt::Key_Tab || ke->key() == Qt::Key_Backtab) {
762                         KeySymbol sym;
763                         setKeySymbol(&sym, ke);
764                         d.current_work_area_->processKeySym(sym, NoModifier);
765                         e->accept();
766                         return true;
767                 }
768         }
769         default:
770                 return QMainWindow::event(e);
771         }
772 }
773
774
775 bool GuiView::focusNextPrevChild(bool /*next*/)
776 {
777         setFocus();
778         return true;
779 }
780
781
782 void GuiView::setBusy(bool yes)
783 {
784         if (d.current_work_area_) {
785                 d.current_work_area_->setUpdatesEnabled(!yes);
786                 if (yes)
787                         d.current_work_area_->stopBlinkingCursor();
788                 else
789                         d.current_work_area_->startBlinkingCursor();
790         }
791
792         if (yes)
793                 QApplication::setOverrideCursor(Qt::WaitCursor);
794         else
795                 QApplication::restoreOverrideCursor();
796 }
797
798
799 GuiToolbar * GuiView::makeToolbar(ToolbarInfo const & tbinfo, bool newline)
800 {
801         GuiToolbar * toolBar = new GuiToolbar(tbinfo, *this);
802
803         if (tbinfo.flags & ToolbarInfo::TOP) {
804                 if (newline)
805                         addToolBarBreak(Qt::TopToolBarArea);
806                 addToolBar(Qt::TopToolBarArea, toolBar);
807         }
808
809         if (tbinfo.flags & ToolbarInfo::BOTTOM) {
810 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
811 #if (QT_VERSION >= 0x040202)
812                 if (newline)
813                         addToolBarBreak(Qt::BottomToolBarArea);
814 #endif
815                 addToolBar(Qt::BottomToolBarArea, toolBar);
816         }
817
818         if (tbinfo.flags & ToolbarInfo::LEFT) {
819 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
820 #if (QT_VERSION >= 0x040202)
821                 if (newline)
822                         addToolBarBreak(Qt::LeftToolBarArea);
823 #endif
824                 addToolBar(Qt::LeftToolBarArea, toolBar);
825         }
826
827         if (tbinfo.flags & ToolbarInfo::RIGHT) {
828 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
829 #if (QT_VERSION >= 0x040202)
830                 if (newline)
831                         addToolBarBreak(Qt::RightToolBarArea);
832 #endif
833                 addToolBar(Qt::RightToolBarArea, toolBar);
834         }
835
836         // The following does not work so I cannot restore to exact toolbar location
837         /*
838         ToolbarSection::ToolbarInfo & tbinfo = LyX::ref().session().toolbars().load(tbinfo.name);
839         toolBar->move(tbinfo.posx, tbinfo.posy);
840         */
841
842         return toolBar;
843 }
844
845
846 GuiWorkArea * GuiView::workArea(Buffer & buffer)
847 {
848         for (int i = 0; i != d.splitter_->count(); ++i) {
849                 GuiWorkArea * wa = d.tabWorkArea(i)->workArea(buffer);
850                 if (wa)
851                         return wa;
852         }
853         return 0;
854 }
855
856
857 GuiWorkArea * GuiView::addWorkArea(Buffer & buffer)
858 {
859         GuiWorkArea * wa = new GuiWorkArea(buffer, *this);
860         wa->setUpdatesEnabled(false);
861
862         // Automatically create a TabWorkArea if there are none yet.
863         if (!d.splitter_->count())
864                 addTabWorkArea();
865
866         TabWorkArea * tab_widget = d.currentTabWorkArea();
867         tab_widget->addTab(wa, wa->windowTitle());
868         QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
869                 tab_widget, SLOT(updateTabText(GuiWorkArea *)));
870
871         wa->bufferView().updateMetrics();
872
873         // Hide tabbar if there's only one tab.
874         tab_widget->showBar(tab_widget->count() > 1);
875         return wa;
876 }
877
878
879 void GuiView::addTabWorkArea()
880 {
881         TabWorkArea * twa = new TabWorkArea;
882         QObject::connect(twa, SIGNAL(currentWorkAreaChanged(GuiWorkArea *)),
883                 this, SLOT(on_currentWorkAreaChanged(GuiWorkArea *)));
884         d.splitter_->addWidget(twa);
885         d.stack_widget_->setCurrentWidget(d.splitter_);
886 }
887
888
889 GuiWorkArea const * GuiView::currentWorkArea() const
890 {
891         return d.current_work_area_;
892 }
893
894
895 void GuiView::setCurrentWorkArea(GuiWorkArea * work_area)
896 {
897         BOOST_ASSERT(work_area);
898
899         // Changing work area can result from opening a file so
900         // update the toc in any case.
901         updateToc();
902
903         GuiWorkArea * wa = static_cast<GuiWorkArea *>(work_area);
904         d.current_work_area_ = wa;
905         for (int i = 0; i != d.splitter_->count(); ++i) {
906                 if (d.tabWorkArea(i)->setCurrentWorkArea(wa))
907                         return;
908         }
909 }
910
911
912 void GuiView::removeWorkArea(GuiWorkArea * work_area)
913 {
914         BOOST_ASSERT(work_area);
915         GuiWorkArea * gwa = static_cast<GuiWorkArea *>(work_area);
916         if (gwa == d.current_work_area_) {
917                 disconnectBuffer();
918                 disconnectBufferView();
919                 dialogs_->hideBufferDependent();
920                 d.current_work_area_ = 0;
921         }
922
923         // removing a work area often results from closing a file so
924         // update the toc in any case.
925         updateToc();
926
927         for (int i = 0; i != d.splitter_->count(); ++i) {
928                 TabWorkArea * twa = d.tabWorkArea(i);
929                 if (!twa->removeWorkArea(gwa))
930                         // Not found in this tab group.
931                         continue;
932
933                 // We found and removed the GuiWorkArea.
934                 if (!twa->count()) {
935                         // No more WorkAreas in this tab group, so delete it.
936                         delete twa;
937                         break;
938                 }
939
940                 if (d.current_work_area_)
941                         // This means that we are not closing the current GuiWorkArea;
942                         break;
943
944                 // Switch to the next GuiWorkArea in the found TabWorkArea.
945                 d.current_work_area_ = twa->currentWorkArea();
946                 break;
947         }
948
949         if (d.splitter_->count() == 0)
950                 // No more work area, switch to the background widget.
951                 d.setBackground();
952 }
953
954
955 void GuiView::updateLayoutChoice(bool force)
956 {
957         // Don't show any layouts without a buffer
958         if (!buffer()) {
959                 d.toolbars_->clearLayoutList();
960                 return;
961         }
962
963         // Update the layout display
964         if (d.toolbars_->updateLayoutList(buffer()->params().getTextClassPtr(), force)) {
965                 d.current_layout = buffer()->params().getTextClass().defaultLayoutName();
966         }
967
968         docstring const & layout = d.current_work_area_->bufferView().cursor().
969                 innerParagraph().layout()->name();
970
971         if (layout != d.current_layout) {
972                 d.toolbars_->setLayout(layout);
973                 d.current_layout = layout;
974         }
975 }
976
977
978 bool GuiView::isToolbarVisible(std::string const & id)
979 {
980         return d.toolbars_->visible(id);
981 }
982
983 void GuiView::updateToolbars()
984 {
985         if (d.current_work_area_) {
986                 bool const math =
987                         d.current_work_area_->bufferView().cursor().inMathed();
988                 bool const table =
989                         lyx::getStatus(FuncRequest(LFUN_LAYOUT_TABULAR)).enabled();
990                 bool const review =
991                         lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).enabled() &&
992                         lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).onoff(true);
993
994                 d.toolbars_->update(math, table, review);
995         } else
996                 d.toolbars_->update(false, false, false);
997
998         // update read-only status of open dialogs.
999         dialogs_->checkStatus();
1000 }
1001
1002
1003 Buffer * GuiView::buffer()
1004 {
1005         if (d.current_work_area_)
1006                 return &d.current_work_area_->bufferView().buffer();
1007         return 0;
1008 }
1009
1010
1011 Buffer const * GuiView::buffer() const
1012 {
1013         if (d.current_work_area_)
1014                 return &d.current_work_area_->bufferView().buffer();
1015         return 0;
1016 }
1017
1018
1019 void GuiView::setBuffer(Buffer * newBuffer)
1020 {
1021         BOOST_ASSERT(newBuffer);
1022         setBusy(true);
1023
1024         GuiWorkArea * wa = workArea(*newBuffer);
1025         if (wa == 0) {
1026                 updateLabels(*newBuffer->masterBuffer());
1027                 wa = addWorkArea(*newBuffer);
1028         } else {
1029                 //Disconnect the old buffer...there's no new one.
1030                 disconnectBuffer();
1031         }
1032         connectBuffer(*newBuffer);
1033         connectBufferView(wa->bufferView());
1034         setCurrentWorkArea(wa);
1035
1036         setBusy(false);
1037 }
1038
1039
1040 Buffer * GuiView::loadLyXFile(FileName const & filename, bool tolastfiles)
1041 {
1042         setBusy(true);
1043
1044         Buffer * newBuffer = checkAndLoadLyXFile(filename);
1045
1046         if (!newBuffer) {
1047                 message(_("Document not loaded."));
1048                 updateStatusBar();
1049                 setBusy(false);
1050                 return 0;
1051         }
1052
1053         GuiWorkArea * wa = workArea(*newBuffer);
1054         if (wa == 0)
1055                 wa = addWorkArea(*newBuffer);
1056
1057         // scroll to the position when the file was last closed
1058         if (lyxrc.use_lastfilepos) {
1059                 LastFilePosSection::FilePos filepos =
1060                         LyX::ref().session().lastFilePos().load(filename);
1061                 // if successfully move to pit (returned par_id is not zero),
1062                 // update metrics and reset font
1063                 wa->bufferView().moveToPosition(filepos.pit, filepos.pos, 0, 0);
1064         }
1065
1066         if (tolastfiles)
1067                 LyX::ref().session().lastFiles().add(filename);
1068
1069         setBusy(false);
1070         return newBuffer;
1071 }
1072
1073
1074 void GuiView::connectBuffer(Buffer & buf)
1075 {
1076         buf.setGuiDelegate(this);
1077 }
1078
1079
1080 void GuiView::disconnectBuffer()
1081 {
1082         if (d.current_work_area_)
1083                 d.current_work_area_->bufferView().setGuiDelegate(0);
1084 }
1085
1086
1087 void GuiView::connectBufferView(BufferView & bv)
1088 {
1089         bv.setGuiDelegate(this);
1090 }
1091
1092
1093 void GuiView::disconnectBufferView()
1094 {
1095         if (d.current_work_area_)
1096                 d.current_work_area_->bufferView().setGuiDelegate(0);
1097 }
1098
1099
1100 void GuiView::errors(string const & error_type)
1101 {
1102         ErrorList & el = buffer()->errorList(error_type);
1103         if (!el.empty())
1104                 dialogs_->show("errorlist", error_type);
1105 }
1106
1107
1108 void GuiView::showDialog(string const & name)
1109 {
1110         dialogs_->show(name);
1111 }
1112
1113
1114 void GuiView::showDialogWithData(string const & name, string const & data)
1115 {
1116         dialogs_->show(name, data);
1117 }
1118
1119
1120 void GuiView::showInsetDialog(string const & name, string const & data,
1121                 Inset * inset)
1122 {
1123         dialogs_->show(name, data, inset);
1124 }
1125
1126
1127 void GuiView::updateDialog(string const & name, string const & data)
1128 {
1129         if (dialogs_->visible(name))
1130                 dialogs_->update(name, data);
1131 }
1132
1133
1134 BufferView * GuiView::view()
1135 {
1136         return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1137 }
1138
1139
1140 void GuiView::updateToc()
1141 {
1142         updateDialog("toc", "");
1143 }
1144
1145
1146 void GuiView::updateEmbeddedFiles()
1147 {
1148         updateDialog("embedding", "");
1149 }
1150
1151
1152 void GuiView::autoSave()
1153 {
1154         LYXERR(Debug::INFO) << "Running autoSave()" << endl;
1155
1156         if (buffer())
1157                 view()->buffer().autoSave();
1158 }
1159
1160
1161 void GuiView::resetAutosaveTimers()
1162 {
1163         if (lyxrc.autosave)
1164                 autosave_timeout_->restart();
1165 }
1166
1167
1168 void GuiView::dispatch(FuncRequest const & cmd)
1169 {
1170         switch(cmd.action) {
1171                 case LFUN_BUFFER_SWITCH:
1172                         setBuffer(theBufferList().getBuffer(to_utf8(cmd.argument())));
1173                         break;
1174
1175                 case LFUN_COMMAND_EXECUTE: {
1176                         bool const show_it = cmd.argument() != "off";
1177                         d.toolbars_->showCommandBuffer(show_it);
1178                         break;
1179                 }
1180                 case LFUN_DROP_LAYOUTS_CHOICE:
1181                         d.toolbars_->openLayoutList();
1182                         break;
1183
1184                 case LFUN_MENU_OPEN:
1185                         d.menubar_->openByName(toqstr(cmd.argument()));
1186                         break;
1187
1188                 case LFUN_TOOLBAR_TOGGLE: {
1189                         string const name = cmd.getArg(0);
1190                         bool const allowauto = cmd.getArg(1) == "allowauto";
1191                         // it is possible to get current toolbar status like this,...
1192                         // but I decide to obey the order of ToolbarBackend::flags
1193                         // and disregard real toolbar status.
1194                         // toolbars_->saveToolbarInfo();
1195                         //
1196                         // toggle state on/off/auto
1197                         d.toolbars_->toggleToolbarState(name, allowauto);
1198                         // update toolbar
1199                         updateToolbars();
1200
1201                         ToolbarInfo * tbi = d.toolbars_->getToolbarInfo(name);
1202                         if (!tbi) {
1203                                 message(bformat(_("Unknown toolbar \"%1$s\""), from_utf8(name)));
1204                                 break;
1205                         }
1206                         docstring state;
1207                         if (tbi->flags & ToolbarInfo::ON)
1208                                 state = _("on");
1209                         else if (tbi->flags & ToolbarInfo::OFF)
1210                                 state = _("off");
1211                         else if (tbi->flags & ToolbarInfo::AUTO)
1212                                 state = _("auto");
1213
1214                         message(bformat(_("Toolbar \"%1$s\" state set to %2$s"), 
1215                                            _(tbi->gui_name), state));
1216                         break;
1217                 }
1218
1219                 default:
1220                         theLyXFunc().setLyXView(this);
1221                         lyx::dispatch(cmd);
1222         }
1223 }
1224
1225
1226 Buffer const * GuiView::updateInset(Inset const * inset)
1227 {
1228         if (!d.current_work_area_)
1229                 return 0;
1230
1231         if (inset)
1232                 d.current_work_area_->scheduleRedraw();
1233
1234         return &d.current_work_area_->bufferView().buffer();
1235 }
1236
1237
1238 void GuiView::restartCursor()
1239 {
1240         /* When we move around, or type, it's nice to be able to see
1241          * the cursor immediately after the keypress.
1242          */
1243         if (d.current_work_area_)
1244                 d.current_work_area_->startBlinkingCursor();
1245 }
1246
1247 } // namespace frontend
1248 } // namespace lyx
1249
1250 #include "GuiView_moc.cpp"