]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiView.cpp
Transfer geometry related session code from LyX::newLyXView() to GuiView::setGeometry().
[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(string const & geometryArg)
498 {
499         // *******************************************
500         // Beginning of the session handling stuff
501
502         //FIXME: Instead of the stuff below, we should use QSettings:
503         /*
504         QSettings settings;
505         QString key = "view " + QString::number(id) + "/geometry";
506         view.restoreGeometry(settings.value(key).toByteArray());
507         */
508
509         // determine windows size and position, from lyxrc and/or session
510         // initial geometry
511         unsigned int width = 690;
512         unsigned int height = 510;
513         // default icon size, will be overwritten by  stored session value
514         unsigned int iconSizeXY = 0;
515         Maximized maximized = NotMaximized;
516         SessionInfoSection & session = LyX::ref().session().sessionInfo();
517
518         // first try lyxrc
519         if (lyxrc.geometry_width != 0 && lyxrc.geometry_height != 0 ) {
520                 width = lyxrc.geometry_width;
521                 height = lyxrc.geometry_height;
522         }
523         // if lyxrc returns (0,0), then use session info
524         else {
525                 string val = session.load("WindowWidth");
526                 if (!val.empty())
527                         width = convert<unsigned int>(val);
528                 val = session.load("WindowHeight");
529                 if (!val.empty())
530                         height = convert<unsigned int>(val);
531                 val = session.load("WindowMaximized");
532                 if (!val.empty())
533                         maximized = GuiView::Maximized(convert<int>(val));
534                 val = session.load("IconSizeXY");
535                 if (!val.empty())
536                         iconSizeXY = convert<unsigned int>(val);
537         }
538
539         // if user wants to restore window position
540         int posx = -1;
541         int posy = -1;
542         if (lyxrc.geometry_xysaved) {
543                 string val = session.load("WindowPosX");
544                 if (!val.empty())
545                         posx = convert<int>(val);
546                 val = session.load("WindowPosY");
547                 if (!val.empty())
548                         posy = convert<int>(val);
549         }
550
551         if (!geometryArg.empty())
552         {
553                 width = 0;
554                 height = 0;
555         }
556
557         // End of the sesssion handling stuff
558         // *******************************************
559
560         // use last value (not at startup)
561         if (d.lastIconSize != 0)
562                 setIconSize(d.lastIconSize);
563         else if (iconSizeXY != 0)
564                 setIconSize(iconSizeXY);
565         else
566                 setIconSize(d.normalIconSize);
567
568         // only true when the -geometry option was NOT used
569         if (width != 0 && height != 0) {
570                 if (posx != -1 && posy != -1) {
571                         // if there are startup positioning problems:
572                         // http://doc.trolltech.com/4.2/qdesktopwidget.html
573                         QDesktopWidget& dw = *qApp->desktop();
574                         if (dw.isVirtualDesktop()) {
575                                 if(!dw.geometry().contains(posx, posy)) {
576                                         posx = 50;
577                                         posy = 50;
578                                 }
579                         } else {
580                                 // Which system doesn't use a virtual desktop?
581                                 // TODO save also last screen number and check if it is still availabe.
582                         }
583 #ifdef Q_WS_WIN
584                         // FIXME: use setGeometry only when Trolltech has fixed the qt4/X11 bug
585                         QWidget::setGeometry(posx, posy, width, height);
586 #else
587                         resize(width, height);
588                         move(posx, posy);
589 #endif
590                 } else {
591                         resize(width, height);
592                 }
593
594                 // remember original size
595                 floatingGeometry_ = QRect(posx, posy, width, height);
596
597                 if (maximized != NotMaximized) {
598                         if (maximized == CompletelyMaximized) {
599                                 setWindowState(Qt::WindowMaximized);
600                         } else {
601 #ifndef Q_WS_WIN
602                                 // TODO How to set by the window manager?
603                                 //      setWindowState(Qt::WindowVerticallyMaximized);
604                                 //      is not possible
605                                 QDesktopWidget& dw = *qApp->desktop();
606                                 QRect desk = dw.availableGeometry(dw.primaryScreen());
607                                 if (maximized == VerticallyMaximized)
608                                         resize(width, desk.height());
609                                 if (maximized == HorizontallyMaximized)
610                                         resize(desk.width(), height);
611 #endif
612                         }
613                 }
614         }
615         else
616         {
617                 // FIXME: move this code into parse_geometry() (LyX.cpp)
618 #ifdef Q_WS_WIN
619                 int x, y;
620                 int w, h;
621                 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)([+-][0-9]*)){0,1}" );
622                 re.indexIn(toqstr(geometryArg.c_str()));
623                 w = re.cap(1).toInt();
624                 h = re.cap(2).toInt();
625                 x = re.cap(3).toInt();
626                 y = re.cap(4).toInt();
627                 QWidget::setGeometry( x, y, w, h );
628 #else
629                 // silence warning
630                 (void)geometryArg;
631 #endif
632         }
633         
634         d.setBackground();
635         
636         show();
637
638         // after show geometry() has changed (Qt bug?)
639         // we compensate the drift when storing the position
640         d.posx_offset = 0;
641         d.posy_offset = 0;
642         if (width != 0 && height != 0)
643                 if (posx != -1 && posy != -1) {
644 #ifdef Q_WS_WIN
645                         d.posx_offset = posx - normalGeometry().x();
646                         d.posy_offset = posy - normalGeometry().y();
647 #else
648 #ifndef Q_WS_MACX
649                         if (maximized == NotMaximized) {
650                                 d.posx_offset = posx - geometry().x();
651                                 d.posy_offset = posy - geometry().y();
652                         }
653 #endif
654 #endif
655                 }
656 }
657
658
659 void GuiView::message(docstring const & str)
660 {
661         statusBar()->showMessage(toqstr(str));
662         statusbar_timer_.stop();
663         statusbar_timer_.start(statusbar_timer_value);
664 }
665
666
667 void GuiView::setIconSize(unsigned int size)
668 {
669         d.lastIconSize = size;
670         QMainWindow::setIconSize(QSize(size, size));
671 }
672
673
674 void GuiView::smallSizedIcons()
675 {
676         setIconSize(d.smallIconSize);
677 }
678
679
680 void GuiView::normalSizedIcons()
681 {
682         setIconSize(d.normalIconSize);
683 }
684
685
686 void GuiView::bigSizedIcons()
687 {
688         setIconSize(d.bigIconSize);
689 }
690
691
692 void GuiView::clearMessage()
693 {
694         if (!hasFocus())
695                 return;
696         theLyXFunc().setLyXView(this);
697         statusBar()->showMessage(toqstr(theLyXFunc().viewStatusMessage()));
698         statusbar_timer_.stop();
699 }
700
701
702 void GuiView::updateWindowTitle(GuiWorkArea * wa)
703 {
704         if (wa != d.current_work_area_)
705                 return;
706         setWindowTitle(qt_("LyX: ") + wa->windowTitle());
707         setWindowIconText(wa->windowIconText());
708 }
709
710
711 void GuiView::on_currentWorkAreaChanged(GuiWorkArea * wa)
712 {
713         disconnectBuffer();
714         disconnectBufferView();
715         connectBufferView(wa->bufferView());
716         connectBuffer(wa->bufferView().buffer());
717         d.current_work_area_ = wa;
718         QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
719                 this, SLOT(updateWindowTitle(GuiWorkArea *)));
720         updateWindowTitle(wa);
721
722         updateToc();
723         // Buffer-dependent dialogs should be updated or
724         // hidden. This should go here because some dialogs (eg ToC)
725         // require bv_->text.
726         dialogs_->updateBufferDependent(true);
727         updateToolbars();
728         updateLayoutChoice(false);
729         updateStatusBar();
730 }
731
732
733 void GuiView::updateStatusBar()
734 {
735         // let the user see the explicit message
736         if (statusbar_timer_.isActive())
737                 return;
738
739         statusBar()->showMessage(toqstr(theLyXFunc().viewStatusMessage()));
740 }
741
742
743 bool GuiView::hasFocus() const
744 {
745         return qApp->activeWindow() == this;
746 }
747
748
749 QRect  GuiView::updateFloatingGeometry()
750 {
751         QDesktopWidget& dw = *qApp->desktop();
752         QRect desk = dw.availableGeometry(dw.primaryScreen());
753         // remember only non-maximized sizes
754         if (!isMaximized() && desk.width() > frameGeometry().width() && desk.height() > frameGeometry().height()) {
755                 floatingGeometry_ = QRect(x(), y(), width(), height());
756         }
757         return floatingGeometry_;
758 }
759
760
761 void GuiView::resizeEvent(QResizeEvent *)
762 {
763         updateFloatingGeometry();
764 }
765
766
767 void GuiView::moveEvent(QMoveEvent *)
768 {
769         updateFloatingGeometry();
770 }
771
772
773 bool GuiView::event(QEvent * e)
774 {
775         switch (e->type())
776         {
777         // Useful debug code:
778         //case QEvent::ActivationChange:
779         //case QEvent::WindowDeactivate:
780         //case QEvent::Paint:
781         //case QEvent::Enter:
782         //case QEvent::Leave:
783         //case QEvent::HoverEnter:
784         //case QEvent::HoverLeave:
785         //case QEvent::HoverMove:
786         //case QEvent::StatusTip:
787         //case QEvent::DragEnter:
788         //case QEvent::DragLeave:
789         //case QEvent::Drop:
790         //      break;
791
792         case QEvent::WindowActivate: {
793                 theApp()->setCurrentView(*this);
794                 if (d.current_work_area_) {
795                         BufferView & bv = d.current_work_area_->bufferView();
796                         connectBufferView(bv);
797                         connectBuffer(bv.buffer());
798                         // The document structure, name and dialogs might have
799                         // changed in another view.
800                         dialogs_->updateBufferDependent(true);
801                 } else {
802                         setWindowTitle(qt_("LyX"));
803                         setWindowIconText(qt_("LyX"));
804                 }
805                 return QMainWindow::event(e);
806         }
807         case QEvent::ShortcutOverride: {
808                 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
809                 if (!d.current_work_area_) {
810                         theLyXFunc().setLyXView(this);
811                         KeySymbol sym;
812                         setKeySymbol(&sym, ke);
813                         theLyXFunc().processKeySym(sym, q_key_state(ke->modifiers()));
814                         e->accept();
815                         return true;
816                 }
817                 if (ke->key() == Qt::Key_Tab || ke->key() == Qt::Key_Backtab) {
818                         KeySymbol sym;
819                         setKeySymbol(&sym, ke);
820                         d.current_work_area_->processKeySym(sym, NoModifier);
821                         e->accept();
822                         return true;
823                 }
824         }
825         default:
826                 return QMainWindow::event(e);
827         }
828 }
829
830
831 bool GuiView::focusNextPrevChild(bool /*next*/)
832 {
833         setFocus();
834         return true;
835 }
836
837
838 void GuiView::setBusy(bool yes)
839 {
840         if (d.current_work_area_) {
841                 d.current_work_area_->setUpdatesEnabled(!yes);
842                 if (yes)
843                         d.current_work_area_->stopBlinkingCursor();
844                 else
845                         d.current_work_area_->startBlinkingCursor();
846         }
847
848         if (yes)
849                 QApplication::setOverrideCursor(Qt::WaitCursor);
850         else
851                 QApplication::restoreOverrideCursor();
852 }
853
854
855 GuiToolbar * GuiView::makeToolbar(ToolbarInfo const & tbinfo, bool newline)
856 {
857         GuiToolbar * toolBar = new GuiToolbar(tbinfo, *this);
858
859         if (tbinfo.flags & ToolbarInfo::TOP) {
860                 if (newline)
861                         addToolBarBreak(Qt::TopToolBarArea);
862                 addToolBar(Qt::TopToolBarArea, toolBar);
863         }
864
865         if (tbinfo.flags & ToolbarInfo::BOTTOM) {
866 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
867 #if (QT_VERSION >= 0x040202)
868                 if (newline)
869                         addToolBarBreak(Qt::BottomToolBarArea);
870 #endif
871                 addToolBar(Qt::BottomToolBarArea, toolBar);
872         }
873
874         if (tbinfo.flags & ToolbarInfo::LEFT) {
875 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
876 #if (QT_VERSION >= 0x040202)
877                 if (newline)
878                         addToolBarBreak(Qt::LeftToolBarArea);
879 #endif
880                 addToolBar(Qt::LeftToolBarArea, toolBar);
881         }
882
883         if (tbinfo.flags & ToolbarInfo::RIGHT) {
884 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
885 #if (QT_VERSION >= 0x040202)
886                 if (newline)
887                         addToolBarBreak(Qt::RightToolBarArea);
888 #endif
889                 addToolBar(Qt::RightToolBarArea, toolBar);
890         }
891
892         // The following does not work so I cannot restore to exact toolbar location
893         /*
894         ToolbarSection::ToolbarInfo & tbinfo = LyX::ref().session().toolbars().load(tbinfo.name);
895         toolBar->move(tbinfo.posx, tbinfo.posy);
896         */
897
898         return toolBar;
899 }
900
901
902 GuiWorkArea * GuiView::workArea(Buffer & buffer)
903 {
904         for (int i = 0; i != d.splitter_->count(); ++i) {
905                 GuiWorkArea * wa = d.tabWorkArea(i)->workArea(buffer);
906                 if (wa)
907                         return wa;
908         }
909         return 0;
910 }
911
912
913 GuiWorkArea * GuiView::addWorkArea(Buffer & buffer)
914 {
915         GuiWorkArea * wa = new GuiWorkArea(buffer, *this);
916         wa->setUpdatesEnabled(false);
917
918         // Automatically create a TabWorkArea if there are none yet.
919         if (!d.splitter_->count())
920                 addTabWorkArea();
921
922         TabWorkArea * tab_widget = d.currentTabWorkArea();
923         tab_widget->addTab(wa, wa->windowTitle());
924         QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
925                 tab_widget, SLOT(updateTabText(GuiWorkArea *)));
926
927         wa->bufferView().updateMetrics();
928
929         // Hide tabbar if there's only one tab.
930         tab_widget->showBar(tab_widget->count() > 1);
931         return wa;
932 }
933
934
935 void GuiView::addTabWorkArea()
936 {
937         TabWorkArea * twa = new TabWorkArea;
938         QObject::connect(twa, SIGNAL(currentWorkAreaChanged(GuiWorkArea *)),
939                 this, SLOT(on_currentWorkAreaChanged(GuiWorkArea *)));
940         d.splitter_->addWidget(twa);
941         d.stack_widget_->setCurrentWidget(d.splitter_);
942 }
943
944
945 GuiWorkArea const * GuiView::currentWorkArea() const
946 {
947         return d.current_work_area_;
948 }
949
950
951 void GuiView::setCurrentWorkArea(GuiWorkArea * work_area)
952 {
953         BOOST_ASSERT(work_area);
954
955         // Changing work area can result from opening a file so
956         // update the toc in any case.
957         updateToc();
958
959         GuiWorkArea * wa = static_cast<GuiWorkArea *>(work_area);
960         d.current_work_area_ = wa;
961         for (int i = 0; i != d.splitter_->count(); ++i) {
962                 if (d.tabWorkArea(i)->setCurrentWorkArea(wa))
963                         return;
964         }
965 }
966
967
968 void GuiView::removeWorkArea(GuiWorkArea * work_area)
969 {
970         BOOST_ASSERT(work_area);
971         GuiWorkArea * gwa = static_cast<GuiWorkArea *>(work_area);
972         if (gwa == d.current_work_area_) {
973                 disconnectBuffer();
974                 disconnectBufferView();
975                 dialogs_->hideBufferDependent();
976                 d.current_work_area_ = 0;
977         }
978
979         // removing a work area often results from closing a file so
980         // update the toc in any case.
981         updateToc();
982
983         for (int i = 0; i != d.splitter_->count(); ++i) {
984                 TabWorkArea * twa = d.tabWorkArea(i);
985                 if (!twa->removeWorkArea(gwa))
986                         // Not found in this tab group.
987                         continue;
988
989                 // We found and removed the GuiWorkArea.
990                 if (!twa->count()) {
991                         // No more WorkAreas in this tab group, so delete it.
992                         delete twa;
993                         break;
994                 }
995
996                 if (d.current_work_area_)
997                         // This means that we are not closing the current GuiWorkArea;
998                         break;
999
1000                 // Switch to the next GuiWorkArea in the found TabWorkArea.
1001                 d.current_work_area_ = twa->currentWorkArea();
1002                 break;
1003         }
1004
1005         if (d.splitter_->count() == 0)
1006                 // No more work area, switch to the background widget.
1007                 d.setBackground();
1008 }
1009
1010
1011 void GuiView::updateLayoutChoice(bool force)
1012 {
1013         // Don't show any layouts without a buffer
1014         if (!buffer()) {
1015                 d.toolbars_->clearLayoutList();
1016                 return;
1017         }
1018
1019         // Update the layout display
1020         if (d.toolbars_->updateLayoutList(buffer()->params().getTextClassPtr(), force)) {
1021                 d.current_layout = buffer()->params().getTextClass().defaultLayoutName();
1022         }
1023
1024         docstring const & layout = d.current_work_area_->bufferView().cursor().
1025                 innerParagraph().layout()->name();
1026
1027         if (layout != d.current_layout) {
1028                 d.toolbars_->setLayout(layout);
1029                 d.current_layout = layout;
1030         }
1031 }
1032
1033
1034 bool GuiView::isToolbarVisible(std::string const & id)
1035 {
1036         return d.toolbars_->visible(id);
1037 }
1038
1039 void GuiView::updateToolbars()
1040 {
1041         if (d.current_work_area_) {
1042                 bool const math =
1043                         d.current_work_area_->bufferView().cursor().inMathed();
1044                 bool const table =
1045                         lyx::getStatus(FuncRequest(LFUN_LAYOUT_TABULAR)).enabled();
1046                 bool const review =
1047                         lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).enabled() &&
1048                         lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).onoff(true);
1049
1050                 d.toolbars_->update(math, table, review);
1051         } else
1052                 d.toolbars_->update(false, false, false);
1053
1054         // update read-only status of open dialogs.
1055         dialogs_->checkStatus();
1056 }
1057
1058
1059 Buffer * GuiView::buffer()
1060 {
1061         if (d.current_work_area_)
1062                 return &d.current_work_area_->bufferView().buffer();
1063         return 0;
1064 }
1065
1066
1067 Buffer const * GuiView::buffer() const
1068 {
1069         if (d.current_work_area_)
1070                 return &d.current_work_area_->bufferView().buffer();
1071         return 0;
1072 }
1073
1074
1075 void GuiView::setBuffer(Buffer * newBuffer)
1076 {
1077         BOOST_ASSERT(newBuffer);
1078         setBusy(true);
1079
1080         GuiWorkArea * wa = workArea(*newBuffer);
1081         if (wa == 0) {
1082                 updateLabels(*newBuffer->masterBuffer());
1083                 wa = addWorkArea(*newBuffer);
1084         } else {
1085                 //Disconnect the old buffer...there's no new one.
1086                 disconnectBuffer();
1087         }
1088         connectBuffer(*newBuffer);
1089         connectBufferView(wa->bufferView());
1090         setCurrentWorkArea(wa);
1091
1092         setBusy(false);
1093 }
1094
1095
1096 Buffer * GuiView::loadLyXFile(FileName const & filename, bool tolastfiles)
1097 {
1098         setBusy(true);
1099
1100         Buffer * newBuffer = checkAndLoadLyXFile(filename);
1101
1102         if (!newBuffer) {
1103                 message(_("Document not loaded."));
1104                 updateStatusBar();
1105                 setBusy(false);
1106                 return 0;
1107         }
1108
1109         GuiWorkArea * wa = workArea(*newBuffer);
1110         if (wa == 0)
1111                 wa = addWorkArea(*newBuffer);
1112
1113         // scroll to the position when the file was last closed
1114         if (lyxrc.use_lastfilepos) {
1115                 LastFilePosSection::FilePos filepos =
1116                         LyX::ref().session().lastFilePos().load(filename);
1117                 // if successfully move to pit (returned par_id is not zero),
1118                 // update metrics and reset font
1119                 wa->bufferView().moveToPosition(filepos.pit, filepos.pos, 0, 0);
1120         }
1121
1122         if (tolastfiles)
1123                 LyX::ref().session().lastFiles().add(filename);
1124
1125         setBusy(false);
1126         return newBuffer;
1127 }
1128
1129
1130 void GuiView::connectBuffer(Buffer & buf)
1131 {
1132         buf.setGuiDelegate(this);
1133 }
1134
1135
1136 void GuiView::disconnectBuffer()
1137 {
1138         if (d.current_work_area_)
1139                 d.current_work_area_->bufferView().setGuiDelegate(0);
1140 }
1141
1142
1143 void GuiView::connectBufferView(BufferView & bv)
1144 {
1145         bv.setGuiDelegate(this);
1146 }
1147
1148
1149 void GuiView::disconnectBufferView()
1150 {
1151         if (d.current_work_area_)
1152                 d.current_work_area_->bufferView().setGuiDelegate(0);
1153 }
1154
1155
1156 void GuiView::errors(string const & error_type)
1157 {
1158         ErrorList & el = buffer()->errorList(error_type);
1159         if (!el.empty())
1160                 dialogs_->show("errorlist", error_type);
1161 }
1162
1163
1164 void GuiView::showDialog(string const & name)
1165 {
1166         dialogs_->show(name);
1167 }
1168
1169
1170 void GuiView::showDialogWithData(string const & name, string const & data)
1171 {
1172         dialogs_->show(name, data);
1173 }
1174
1175
1176 void GuiView::showInsetDialog(string const & name, string const & data,
1177                 Inset * inset)
1178 {
1179         dialogs_->show(name, data, inset);
1180 }
1181
1182
1183 void GuiView::updateDialog(string const & name, string const & data)
1184 {
1185         if (dialogs_->visible(name))
1186                 dialogs_->update(name, data);
1187 }
1188
1189
1190 BufferView * GuiView::view()
1191 {
1192         return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1193 }
1194
1195
1196 void GuiView::updateToc()
1197 {
1198         updateDialog("toc", "");
1199 }
1200
1201
1202 void GuiView::updateEmbeddedFiles()
1203 {
1204         updateDialog("embedding", "");
1205 }
1206
1207
1208 void GuiView::autoSave()
1209 {
1210         LYXERR(Debug::INFO) << "Running autoSave()" << endl;
1211
1212         if (buffer())
1213                 view()->buffer().autoSave();
1214 }
1215
1216
1217 void GuiView::resetAutosaveTimers()
1218 {
1219         if (lyxrc.autosave)
1220                 autosave_timeout_->restart();
1221 }
1222
1223
1224 void GuiView::dispatch(FuncRequest const & cmd)
1225 {
1226         switch(cmd.action) {
1227                 case LFUN_BUFFER_SWITCH:
1228                         setBuffer(theBufferList().getBuffer(to_utf8(cmd.argument())));
1229                         break;
1230
1231                 case LFUN_COMMAND_EXECUTE: {
1232                         bool const show_it = cmd.argument() != "off";
1233                         d.toolbars_->showCommandBuffer(show_it);
1234                         break;
1235                 }
1236                 case LFUN_DROP_LAYOUTS_CHOICE:
1237                         d.toolbars_->openLayoutList();
1238                         break;
1239
1240                 case LFUN_MENU_OPEN:
1241                         d.menubar_->openByName(toqstr(cmd.argument()));
1242                         break;
1243
1244                 case LFUN_TOOLBAR_TOGGLE: {
1245                         string const name = cmd.getArg(0);
1246                         bool const allowauto = cmd.getArg(1) == "allowauto";
1247                         // it is possible to get current toolbar status like this,...
1248                         // but I decide to obey the order of ToolbarBackend::flags
1249                         // and disregard real toolbar status.
1250                         // toolbars_->saveToolbarInfo();
1251                         //
1252                         // toggle state on/off/auto
1253                         d.toolbars_->toggleToolbarState(name, allowauto);
1254                         // update toolbar
1255                         updateToolbars();
1256
1257                         ToolbarInfo * tbi = d.toolbars_->getToolbarInfo(name);
1258                         if (!tbi) {
1259                                 message(bformat(_("Unknown toolbar \"%1$s\""), from_utf8(name)));
1260                                 break;
1261                         }
1262                         docstring state;
1263                         if (tbi->flags & ToolbarInfo::ON)
1264                                 state = _("on");
1265                         else if (tbi->flags & ToolbarInfo::OFF)
1266                                 state = _("off");
1267                         else if (tbi->flags & ToolbarInfo::AUTO)
1268                                 state = _("auto");
1269
1270                         message(bformat(_("Toolbar \"%1$s\" state set to %2$s"), 
1271                                            _(tbi->gui_name), state));
1272                         break;
1273                 }
1274
1275                 default:
1276                         theLyXFunc().setLyXView(this);
1277                         lyx::dispatch(cmd);
1278         }
1279 }
1280
1281
1282 Buffer const * GuiView::updateInset(Inset const * inset)
1283 {
1284         if (!d.current_work_area_)
1285                 return 0;
1286
1287         if (inset)
1288                 d.current_work_area_->scheduleRedraw();
1289
1290         return &d.current_work_area_->bufferView().buffer();
1291 }
1292
1293
1294 void GuiView::restartCursor()
1295 {
1296         /* When we move around, or type, it's nice to be able to see
1297          * the cursor immediately after the keypress.
1298          */
1299         if (d.current_work_area_)
1300                 d.current_work_area_->startBlinkingCursor();
1301 }
1302
1303 } // namespace frontend
1304 } // namespace lyx
1305
1306 #include "GuiView_moc.cpp"