]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiView.C
* LyXView::updateInset(): schedule a redraw instead of redraw immediately.
[lyx.git] / src / frontends / qt4 / GuiView.C
1 /**
2  * \file GuiView.C
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 "QLyXKeySym.h"
21 #include "QLMenubar.h"
22 #include "QLToolbar.h"
23 #include "QCommandBuffer.h"
24 #include "qt_helpers.h"
25
26 #include "frontends/Application.h"
27 #include "frontends/Gui.h"
28 #include "frontends/WorkArea.h"
29
30 #include "support/filetools.h"
31 #include "support/convert.h"
32 #include "support/lstrings.h"
33
34 #include "BufferView.h"
35 #include "bufferlist.h"
36 #include "debug.h"
37 #include "funcrequest.h"
38 #include "lyx_cb.h"
39 #include "lyxrc.h"
40 #include "lyx_main.h"
41 #include "session.h"
42 #include "lyxfunc.h"
43 #include "MenuBackend.h"
44 #include "buffer.h"
45 #include "bufferlist.h"
46
47 #include <QAction>
48 #include <QApplication>
49 #include <QCloseEvent>
50 #include <QPixmap>
51 #include <QStatusBar>
52 #include <QToolBar>
53 #include <QTabBar>
54 #include <QDesktopWidget>
55 #include <QVBoxLayout>
56
57 #include <boost/bind.hpp>
58 #include <boost/shared_ptr.hpp>
59
60 using std::endl;
61 using std::string;
62 using std::vector;
63
64 namespace lyx {
65
66 using support::FileName;
67 using support::onlyFilename;
68 using support::subst;
69 using support::libFileSearch;
70
71 namespace frontend {
72
73 namespace {
74
75 int const statusbar_timer_value = 3000;
76
77 } // namespace anon
78
79
80 class WidgetWithTabBar : public QWidget
81 {
82 public:
83         QTabBar* tabbar;
84         WidgetWithTabBar(QWidget* w)
85         {
86                 tabbar = new QTabBar;
87                 QVBoxLayout* l = new QVBoxLayout;
88                 l->addWidget(tabbar);
89                 l->addWidget(w);
90                 l->setMargin(0);
91                 setLayout(l);
92         }
93 };
94
95
96 struct GuiView::GuiViewPrivate
97 {
98         typedef std::map<int, FuncRequest> FuncMap;
99         typedef std::pair<int, FuncRequest> FuncMapPair;
100         typedef std::map<string, QString> NameMap;
101         typedef std::pair<string, QString> NameMapPair;
102
103         FuncMap funcmap;
104         NameMap namemap;
105         WidgetWithTabBar* wt;
106
107         int posx_offset;
108         int posy_offset;
109
110         GuiViewPrivate() : wt(0), posx_offset(0), posy_offset(0)
111         {}
112
113         unsigned int smallIconSize;
114         unsigned int normalIconSize;
115         unsigned int bigIconSize;
116         // static needed by "New Window"
117         static unsigned int lastIconSize;
118
119         QMenu* toolBarPopup(GuiView *parent)
120         {
121                 // FIXME: translation 
122                 QMenu* menu = new QMenu(parent);
123                 QActionGroup *iconSizeGroup = new QActionGroup(parent);
124
125                 QAction *smallIcons = new QAction(iconSizeGroup);
126                 smallIcons->setText("Small sized icons");
127                 smallIcons->setCheckable(true);
128                 QObject::connect(smallIcons, SIGNAL(triggered()), parent, SLOT(smallSizedIcons()));
129                 menu->addAction(smallIcons);
130
131                 QAction *normalIcons = new QAction(iconSizeGroup);
132                 normalIcons->setText("Normal sized icons");
133                 normalIcons->setCheckable(true);
134                 QObject::connect(normalIcons, SIGNAL(triggered()), parent, SLOT(normalSizedIcons()));
135                 menu->addAction(normalIcons);
136
137
138                 QAction *bigIcons = new QAction(iconSizeGroup);
139                 bigIcons->setText("Big sized icons");
140                 bigIcons->setCheckable(true);
141                 QObject::connect(bigIcons, SIGNAL(triggered()), parent, SLOT(bigSizedIcons()));
142                 menu->addAction(bigIcons);
143
144                 unsigned int cur = parent->iconSize().width();
145                 if ( cur == parent->d.smallIconSize)
146                         smallIcons->setChecked(true);
147                 else if (cur == parent->d.normalIconSize)
148                         normalIcons->setChecked(true);
149                 else if (cur == parent->d.bigIconSize)
150                         bigIcons->setChecked(true);
151
152                 return menu;
153         }
154 };
155
156
157 unsigned int GuiView::GuiViewPrivate::lastIconSize = 0;
158
159
160 GuiView::GuiView(int id)
161         : QMainWindow(), LyXView(id), commandbuffer_(0), quitting_by_menu_(false),
162           d(*new GuiViewPrivate)
163 {
164         // Qt bug? signal lastWindowClosed does not work
165         setAttribute(Qt::WA_QuitOnClose, false);
166         setAttribute(Qt::WA_DeleteOnClose, true);
167
168         // hardcode here the platform specific icon size
169         d.smallIconSize = 14;   // scaling problems
170         d.normalIconSize = 20;  // ok, default
171         d.bigIconSize = 26;             // better for some math icons
172
173 #ifndef Q_WS_MACX
174         //  assign an icon to main form. We do not do it under Qt/Mac,
175         //  since the icon is provided in the application bundle.
176         FileName const iconname = libFileSearch("images", "lyx", "xpm");
177         if (!iconname.empty())
178                 setWindowIcon(QPixmap(toqstr(iconname.absFilename())));
179 #endif
180 }
181
182
183 GuiView::~GuiView()
184 {
185         menubar_.reset();
186         delete &d;
187 }
188
189
190 void GuiView::close()
191 {
192         quitting_by_menu_ = true;
193         QMainWindow::close();
194         quitting_by_menu_ = false;
195 }
196
197
198 void GuiView::setFocus()
199 {
200         BOOST_ASSERT(work_area_);
201         static_cast<GuiWorkArea *>(work_area_)->setFocus();
202 }
203
204
205 QMenu* GuiView::createPopupMenu()
206 {
207         return d.toolBarPopup(this);
208 }
209
210
211 void GuiView::init()
212 {
213         menubar_.reset(new QLMenubar(this, menubackend));
214         QObject::connect(menuBar(), SIGNAL(triggered(QAction *)),
215                 this, SLOT(updateMenu(QAction *)));
216
217         getToolbars().init();
218
219         statusBar()->setSizeGripEnabled(false);
220
221         QObject::connect(&statusbar_timer_, SIGNAL(timeout()),
222                 this, SLOT(update_view_state_qt()));
223
224         BOOST_ASSERT(work_area_);
225         if (!work_area_->bufferView().buffer() && !theBufferList().empty())
226                 setBuffer(theBufferList().first());
227
228         // make sure the buttons are disabled if needed
229         updateToolbars();
230         updateLayoutChoice();
231         updateMenubar();
232 }
233
234
235 void GuiView::closeEvent(QCloseEvent * close_event)
236 {
237         // we may have been called through the close window button
238         // which bypasses the LFUN machinery.
239         if (!quitting_by_menu_) {
240                 if (!theBufferList().quitWriteAll()) {
241                         close_event->ignore();
242                         return;
243                 }
244         }
245         if (view()->buffer()) {
246                 // save cursor position for opened files to .lyx/session
247                 LyX::ref().session().lastFilePos().save(
248                         FileName(buffer()->fileName()),
249                         boost::tie(view()->cursor().pit(),
250                         view()->cursor().pos()));
251         }
252         theApp()->gui().unregisterView(id());   
253         if (theApp()->gui().viewIds().empty())
254         {
255                 // this is the place where we leave the frontend.
256                 // it is the only point at which we start quitting.
257                 saveGeometry();
258                 close_event->accept();
259                 // quit the event loop
260                 qApp->quit();
261         }
262         close_event->accept();
263 }
264
265
266 void GuiView::saveGeometry()
267 {
268         static bool done = false;
269         if (done)
270                 return;
271         else
272                 done = true;
273
274         // FIXME:
275         // change the ifdef to 'geometry = normalGeometry();' only
276         // when Trolltech has fixed the broken normalGeometry on X11:
277         // http://www.trolltech.com/developer/task-tracker/index_html?id=119684+&method=entry
278         // Then also the moveEvent, resizeEvent, and the
279         // code for floatingGeometry_ can be removed;
280         // adjust GuiView::setGeometry()
281 #ifdef Q_WS_WIN
282         QRect geometry = normalGeometry();
283 #else
284         updateFloatingGeometry();
285         QRect geometry = floatingGeometry_;
286 #endif
287
288         // save windows size and position
289         Session & session = LyX::ref().session();
290         session.sessionInfo().save("WindowWidth", convert<string>(geometry.width()));
291         session.sessionInfo().save("WindowHeight", convert<string>(geometry.height()));
292         session.sessionInfo().save("WindowIsMaximized", (isMaximized() ? "yes" : "no"));
293         session.sessionInfo().save("IconSizeXY", convert<string>(iconSize().width()));
294         if (lyxrc.geometry_xysaved) {
295                 session.sessionInfo().save("WindowPosX", convert<string>(geometry.x() + d.posx_offset));
296                 session.sessionInfo().save("WindowPosY", convert<string>(geometry.y() + d.posy_offset));
297         }
298         getToolbars().saveToolbarInfo();
299 }
300                                                   
301
302 void GuiView::setGeometry(unsigned int width,
303                                                                   unsigned int height,
304                                                                   int posx, int posy,
305                                                                   bool maximize,
306                                                                   unsigned int iconSizeXY,
307                                                                   const std::string & geometryArg)
308 {
309         // use last value (not at startup)
310         if (d.lastIconSize != 0)
311                 setIconSize(d.lastIconSize);
312         else if (iconSizeXY != 0)
313                 setIconSize(iconSizeXY);
314         else
315                 setIconSize(d.normalIconSize);
316
317         // only true when the -geometry option was NOT used
318         if (width != 0 && height != 0) {
319                 if (posx != -1 && posy != -1) {
320                         // if there are ever startup positioning problems 
321                         // on a virtual desktop then check the 6 lines below
322                         // http://doc.trolltech.com/4.2/qdesktopwidget.html 
323                         QDesktopWidget& dw = *qApp->desktop();
324                         QRect desk = dw.availableGeometry(dw.primaryScreen());
325                         (posx >= desk.width() ? posx = 50 : true);
326                         (posy >= desk.height()? posy = 50 : true);
327 #ifdef Q_WS_WIN
328                         // FIXME: use setGeometry only when Trolltech has fixed the qt4/X11 bug
329                         QWidget::setGeometry(posx, posy, width, height);
330 #else
331                         resize(width, height);
332                         move(posx, posy);
333 #endif
334                 } else {
335                         resize(width, height);
336                 }
337
338                 if (maximize)
339                         setWindowState(Qt::WindowMaximized);
340         }
341         else
342         {
343                 // FIXME: move this code into parse_geometry() (lyx_main.C)
344 #ifdef Q_WS_WIN
345                 int x, y;
346                 int w, h;
347                 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)([+-][0-9]*)){0,1}" );
348                 re.indexIn( toqstr(geometryArg.c_str()));
349                 w = re.cap( 1 ).toInt();
350                 h = re.cap( 2 ).toInt();
351                 x = re.cap( 3 ).toInt();
352                 y = re.cap( 4 ).toInt();
353                 QWidget::setGeometry( x, y, w, h );
354 #endif
355         }
356
357         show();
358
359         // For an unknown reason, the Window title update is not effective for
360         // the second windows up until it is shown on screen (Qt bug?).
361         updateWindowTitle();
362
363         // after show geometry() has changed (Qt bug?)
364         // we compensate the drift when storing the position
365         d.posx_offset = 0;
366         d.posy_offset = 0;
367         if (width != 0 && height != 0) 
368                 if (posx != -1 && posy != -1) {
369 #ifdef Q_WS_WIN
370                         d.posx_offset = posx - normalGeometry().x();
371                         d.posy_offset = posy - normalGeometry().y();
372 #else
373 #ifndef Q_WS_MACX
374                         if (!maximize) {
375                                 d.posx_offset = posx - geometry().x();
376                                 d.posy_offset = posy - geometry().y();
377                         }
378 #endif
379 #endif
380                 }
381 }
382
383
384 void GuiView::updateMenu(QAction * /*action*/)
385 {
386         menubar_->update();
387 }
388
389
390 void GuiView::setWindowTitle(docstring const & t, docstring const & it)
391 {
392         QString title = windowTitle();
393         QString new_title = toqstr(t);
394         if (title != new_title) {
395                 QMainWindow::setWindowTitle(new_title);
396                 QMainWindow::setWindowIconText(toqstr(it));
397         }
398 }
399
400
401 void GuiView::addCommandBuffer(QToolBar * toolbar)
402 {
403         commandbuffer_ = new QCommandBuffer(this, *controlcommand_);
404         focus_command_buffer.connect(boost::bind(&GuiView::focus_command_widget, this));
405         toolbar->addWidget(commandbuffer_);
406 }
407
408
409 void GuiView::message(docstring const & str)
410 {
411         statusBar()->showMessage(toqstr(str));
412         statusbar_timer_.stop();
413         statusbar_timer_.start(statusbar_timer_value);
414 }
415
416
417 void GuiView::clearMessage()
418 {
419         update_view_state_qt();
420 }
421
422
423 void GuiView::setIconSize(unsigned int size)
424 {
425         d.lastIconSize = size;
426         QMainWindow::setIconSize(QSize(size, size));
427 }
428
429
430 void GuiView::smallSizedIcons()
431 {
432         setIconSize(d.smallIconSize);
433 }
434
435
436 void GuiView::normalSizedIcons()
437 {
438         setIconSize(d.normalIconSize);
439 }
440
441
442 void GuiView::bigSizedIcons()
443 {
444         setIconSize(d.bigIconSize);
445 }
446
447
448 void GuiView::focus_command_widget()
449 {
450         if (commandbuffer_)
451                 commandbuffer_->focus_command();
452 }
453
454
455 void GuiView::update_view_state_qt()
456 {
457         statusBar()->showMessage(toqstr(theLyXFunc().viewStatusMessage()));
458         statusbar_timer_.stop();
459 }
460
461
462 void GuiView::initTab(QWidget* workarea)
463 {
464         d.wt = new WidgetWithTabBar(workarea);
465         setCentralWidget(d.wt);
466         QObject::connect(d.wt->tabbar, SIGNAL(currentChanged(int)),
467                         this, SLOT(currentTabChanged(int)));
468 }
469
470
471 void GuiView::updateTab()
472 {
473         QTabBar& tb = *d.wt->tabbar;
474
475         // update when all  is done
476         tb.blockSignals(true);
477
478         typedef std::vector<string> Strings;
479         Strings const names = theBufferList().getFileNames();
480         size_t n_size = names.size();
481
482         Strings addtab;
483         // show tabs only when there is more 
484         // than one file opened
485         if (n_size > 1)
486         {
487                 for (size_t i = 0; i != n_size; i++) 
488                         if (d.namemap.find(names[i]) == d.namemap.end())
489                                 addtab.push_back(names.at(i));
490         }
491
492         for(size_t i = 0; i<addtab.size(); i++)
493         {
494                 QString tab_name = lyx::toqstr(onlyFilename(addtab.at(i))); 
495                 d.namemap.insert(GuiViewPrivate::NameMapPair(addtab.at(i), tab_name));
496                 tb.addTab(tab_name);
497         }
498
499         // check if all names showed by the tabs
500         // are also in the current bufferlist
501         Strings removetab;
502         bool notall = true;
503         if (n_size < 2)
504                 notall = false;
505         std::map<string, QString>::iterator tabit = d.namemap.begin();
506         for (;tabit != d.namemap.end(); ++tabit)
507         {
508                 bool found = false;
509                 for (size_t i = 0; i != n_size; i++) 
510                         if (tabit->first == names.at(i) && notall)
511                                 found = true;
512                 if (!found)
513                         removetab.push_back(tabit->first);
514         }
515         
516
517         // remove tabs
518         for(size_t i = 0; i<removetab.size(); i++)
519         {
520                 if (d.namemap.find(removetab.at(i)) != d.namemap.end())
521                 {
522                         tabit = d.namemap.find(removetab.at(i));
523                         for (int i = 0; i < tb.count(); i++)
524                                 if (tb.tabText(i) == tabit->second)
525                                 {
526                                         tb.removeTab(i);
527                                         break;
528                                 }
529                         d.namemap.erase(tabit);
530                 }
531         }
532
533         // rebuild func map
534         if (removetab.size() > 0 || addtab.size() > 0)
535         {
536                 d.funcmap.clear();
537                 tabit = d.namemap.begin();
538                 for (;tabit != d.namemap.end(); ++tabit)
539                 {
540                         QTabBar& tb = *d.wt->tabbar;
541                         for (int i = 0; i < tb.count(); i++)
542                         {
543                                 if (tb.tabText(i) == tabit->second)
544                                 {
545                                         FuncRequest func(LFUN_BUFFER_SWITCH, tabit->first);
546                                         d.funcmap.insert(GuiViewPrivate::FuncMapPair(i, func));
547                                         break;
548                                 }
549                         }
550                 }
551         }
552
553         // set current tab
554         if (view()->buffer()) 
555         {
556                 string cur_title = view()->buffer()->fileName();
557                 if (d.namemap.find(cur_title) != d.namemap.end())
558                 {
559                         QString tabname = d.namemap.find(cur_title)->second;
560                         for (int i = 0; i < tb.count(); i++)
561                                 if (tb.tabText(i) == tabname)
562                                 {
563                                         tb.setCurrentIndex(i);
564                                         break;
565                                 }
566                 }
567         }
568
569         tb.blockSignals(false);
570         d.wt->update();
571 }
572
573
574 void GuiView::currentTabChanged (int index)
575 {
576         std::map<int, FuncRequest>::const_iterator it = d.funcmap.find(index);
577         if (it != d.funcmap.end())
578                 activated(it->second);
579 }
580
581
582 void GuiView::updateStatusBar()
583 {
584         // let the user see the explicit message
585         if (statusbar_timer_.isActive())
586                 return;
587
588         statusBar()->showMessage(toqstr(theLyXFunc().viewStatusMessage()));
589 }
590
591
592 void GuiView::activated(FuncRequest const & func)
593 {
594         dispatch(func);
595 }
596
597
598 bool GuiView::hasFocus() const
599 {
600         return qApp->activeWindow() == this;
601 }
602
603
604 void  GuiView::updateFloatingGeometry()
605 {
606         if (!isMaximized())
607                 floatingGeometry_ = QRect(x(), y(), width(), height());
608 }
609
610
611 void GuiView::resizeEvent(QResizeEvent *)
612 {
613         updateFloatingGeometry();
614 }
615
616
617 void GuiView::moveEvent(QMoveEvent *)
618 {
619         updateFloatingGeometry();
620 }
621
622
623 bool GuiView::event(QEvent * e)
624 {
625         // Useful debug code:
626         /*
627         switch (e->type())
628         {
629         case QEvent::WindowActivate:
630         case QEvent::ActivationChange:
631         case QEvent::WindowDeactivate:
632         case QEvent::Paint:
633         case QEvent::Enter:
634         case QEvent::Leave:
635         case QEvent::HoverEnter:
636         case QEvent::HoverLeave:
637         case QEvent::HoverMove:
638         case QEvent::StatusTip:
639                 break;
640         default:
641         */
642
643         if (e->type() == QEvent::ShortcutOverride) {
644                 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
645                 if (ke->key() == Qt::Key_Tab || ke->key() == Qt::Key_Backtab) {
646                         boost::shared_ptr<QLyXKeySym> sym(new QLyXKeySym);
647                         sym->set(ke);
648                         BOOST_ASSERT(work_area_);
649                         work_area_->processKeySym(sym, key_modifier::none);
650                         e->accept();
651                         return true;
652                 }
653         }
654         //} for the debug switch above.
655
656         return QMainWindow::event(e);
657 }
658
659
660 bool GuiView::focusNextPrevChild(bool /*next*/)
661 {
662         setFocus();
663         return true;
664 }
665
666
667 void GuiView::show()
668 {
669         QMainWindow::setWindowTitle(qt_("LyX"));
670         QMainWindow::show();
671         updateFloatingGeometry();
672 }
673
674
675 void GuiView::busy(bool yes)
676 {
677         BOOST_ASSERT(work_area_);
678         static_cast<GuiWorkArea *>(work_area_)->setUpdatesEnabled(!yes);
679
680         if (yes) {
681                 work_area_->stopBlinkingCursor();
682                 QApplication::setOverrideCursor(Qt::WaitCursor);
683         }
684         else {
685                 work_area_->startBlinkingCursor();
686                 QApplication::restoreOverrideCursor();
687         }
688 }
689
690
691 Toolbars::ToolbarPtr GuiView::makeToolbar(ToolbarBackend::Toolbar const & tbb)
692 {
693         QLToolbar * Tb = new QLToolbar(tbb, *this);
694         //static QLToolbar * lastTb = 0;
695
696         if (tbb.flags & ToolbarBackend::TOP) {
697                         addToolBar(Qt::TopToolBarArea, Tb);
698                         addToolBarBreak(Qt::TopToolBarArea);
699         }
700         if (tbb.flags & ToolbarBackend::BOTTOM) {
701                 addToolBar(Qt::BottomToolBarArea, Tb);
702                 /*
703                 // Qt bug:
704                 // http://www.trolltech.com/developer/task-tracker/index_html?id=137015&method=entry
705                 // Doesn't work because the toolbar will evtl. be hidden.
706                 if (lastTb)
707                         insertToolBarBreak(lastTb);
708                 lastTb = Tb;
709                 */
710         }
711         if (tbb.flags & ToolbarBackend::LEFT) {
712                 addToolBar(Qt::LeftToolBarArea, Tb);
713         }
714         if (tbb.flags & ToolbarBackend::RIGHT) {
715                 addToolBar(Qt::RightToolBarArea, Tb);
716         }
717
718         return Toolbars::ToolbarPtr(Tb);
719 }
720
721 } // namespace frontend
722 } // namespace lyx
723
724 #include "GuiView_moc.cpp"