source: trunk/demos/qtdemo/mainwindow.cpp@ 280

Last change on this file since 280 was 2, checked in by Dmitry A. Kuminov, 16 years ago

Initially imported qt-all-opensource-src-4.5.1 from Trolltech.

File size: 15.3 KB
Line 
1/****************************************************************************
2**
3** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
4** Contact: Qt Software Information ([email protected])
5**
6** This file is part of the demonstration applications of the Qt Toolkit.
7**
8** $QT_BEGIN_LICENSE:LGPL$
9** Commercial Usage
10** Licensees holding valid Qt Commercial licenses may use this file in
11** accordance with the Qt Commercial License Agreement provided with the
12** Software or, alternatively, in accordance with the terms contained in
13** a written agreement between you and Nokia.
14**
15** GNU Lesser General Public License Usage
16** Alternatively, this file may be used under the terms of the GNU Lesser
17** General Public License version 2.1 as published by the Free Software
18** Foundation and appearing in the file LICENSE.LGPL included in the
19** packaging of this file. Please review the following information to
20** ensure the GNU Lesser General Public License version 2.1 requirements
21** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
22**
23** In addition, as a special exception, Nokia gives you certain
24** additional rights. These rights are described in the Nokia Qt LGPL
25** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
26** package.
27**
28** GNU General Public License Usage
29** Alternatively, this file may be used under the terms of the GNU
30** General Public License version 3.0 as published by the Free Software
31** Foundation and appearing in the file LICENSE.GPL included in the
32** packaging of this file. Please review the following information to
33** ensure the GNU General Public License version 3.0 requirements will be
34** met: http://www.gnu.org/copyleft/gpl.html.
35**
36** If you are unsure which license is appropriate for your use, please
37** contact the sales department at [email protected].
38** $QT_END_LICENSE$
39**
40****************************************************************************/
41
42#include "mainwindow.h"
43#include "menumanager.h"
44#include "colors.h"
45#include "dockitem.h"
46#include "demotextitem.h"
47#include "imageitem.h"
48#include "demoitem.h"
49#include "demoscene.h"
50
51#ifndef QT_NO_OPENGL
52 #include <QGLWidget>
53#endif
54//#define QT_NO_OPENGL
55
56MainWindow::MainWindow(QWidget *parent) : QGraphicsView(parent), updateTimer(this)
57{
58 this->currentFps = Colors::fps;
59 this->loop = false;
60 this->fpsMedian = -1;
61 this->fpsLabel = 0;
62 this->pausedLabel = 0;
63 this->doneAdapt = false;
64 this->useTimer = false;
65 this->updateTimer.setSingleShot(true);
66 this->trolltechLogo = 0;
67 this->qtLogo = 0;
68 this->setupWidget();
69 this->setupScene();
70 this->setupSceneItems();
71 this->drawBackgroundToPixmap();
72}
73
74MainWindow::~MainWindow()
75{
76 delete this->trolltechLogo;
77 delete this->qtLogo;
78}
79
80void MainWindow::setupWidget()
81{
82 QRect screenRect = QApplication::desktop()->screenGeometry(QApplication::desktop()->primaryScreen());
83 QRect windowRect(0, 0, 800, 600);
84 if (screenRect.width() < 800)
85 windowRect.setWidth(screenRect.width());
86 if (screenRect.height() < 600)
87 windowRect.setHeight(screenRect.height());
88 windowRect.moveCenter(screenRect.center());
89 this->setGeometry(windowRect);
90 this->setMinimumSize(80, 60);
91 setWindowTitle(tr("Qt Examples and Demos"));
92 setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
93 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
94 setFrameStyle(QFrame::NoFrame);
95 this->setRenderingSystem();
96 connect(&this->updateTimer, SIGNAL(timeout()), this, SLOT(tick()));
97}
98
99void MainWindow::setRenderingSystem()
100{
101 QWidget *viewport = 0;
102
103 if (Colors::direct3dRendering){
104 viewport->setAttribute(Qt::WA_MSWindowsUseDirect3D);
105 setCacheMode(QGraphicsView::CacheNone);
106 if (Colors::verbose)
107 qDebug() << "- using Direct3D";
108 }
109#ifndef QT_NO_OPENGL
110 else if (Colors::openGlRendering){
111 QGLWidget *glw = new QGLWidget(QGLFormat(QGL::SampleBuffers));
112 if (Colors::noScreenSync)
113 glw->format().setSwapInterval(0);
114 glw->setAutoFillBackground(false);
115 viewport = glw;
116 setCacheMode(QGraphicsView::CacheNone);
117 if (Colors::verbose)
118 qDebug() << "- using OpenGL";
119 }
120#endif
121 else{ // software rendering
122 viewport = new QWidget;
123 setCacheMode(QGraphicsView::CacheBackground);
124 if (Colors::verbose)
125 qDebug() << "- using software rendering";
126 }
127
128 setViewport(viewport);
129}
130
131void MainWindow::start()
132{
133 this->switchTimerOnOff(true);
134 this->demoStartTime.restart();
135 MenuManager::instance()->itemSelected(MenuManager::ROOT, Colors::rootMenuName);
136 if (Colors::verbose)
137 qDebug("- starting demo");
138}
139
140void MainWindow::enableMask(bool enable)
141{
142 if (!enable || Colors::noWindowMask)
143 this->clearMask();
144 else {
145 QPolygon region;
146 region.setPoints(9,
147 // north side:
148 0, 0,
149 800, 0,
150 // east side:
151 // 800, 70,
152 // 790, 90,
153 // 790, 480,
154 // 800, 500,
155 800, 600,
156 // south side:
157 700, 600,
158 670, 590,
159 130, 590,
160 100, 600,
161 0, 600,
162 // west side:
163 // 0, 550,
164 // 10, 530,
165 // 10, 520,
166 // 0, 520,
167 0, 0);
168 this->setMask(QRegion(region));
169 }
170}
171
172void MainWindow::setupScene()
173{
174 this->scene = new DemoScene(this);
175 this->scene->setSceneRect(0, 0, 800, 600);
176 setScene(this->scene);
177 this->scene->setItemIndexMethod(QGraphicsScene::NoIndex);
178}
179
180void MainWindow::drawItems(QPainter *painter, int numItems, QGraphicsItem **items, const QStyleOptionGraphicsItem* options)
181{
182 QGraphicsView::drawItems(painter, numItems, items, options);
183}
184
185void MainWindow::switchTimerOnOff(bool on)
186{
187 bool ticker = MenuManager::instance()->ticker && MenuManager::instance()->ticker->scene();
188 if (ticker)
189 MenuManager::instance()->ticker->tickOnPaint = !on || Colors::noTimerUpdate;
190
191 if (on && !Colors::noTimerUpdate){
192 this->useTimer = true;
193 this->setViewportUpdateMode(QGraphicsView::NoViewportUpdate);
194 this->fpsTime = QTime::currentTime();
195 this->updateTimer.start(int(1000 / Colors::fps));
196 }
197 else{
198 this->useTimer = false;
199 this->updateTimer.stop();
200 if (Colors::softwareRendering)
201 if (Colors::noTicker)
202 this->setViewportUpdateMode(QGraphicsView::MinimalViewportUpdate);
203 else
204 this->setViewportUpdateMode(QGraphicsView::SmartViewportUpdate);
205 else
206 this->setViewportUpdateMode(QGraphicsView::FullViewportUpdate);
207 }
208}
209
210bool MainWindow::measureFps()
211{
212 // Calculate time diff:
213 float t = this->fpsTime.msecsTo(QTime::currentTime());
214 if (t == 0)
215 t = 0.01f;
216 this->currentFps = (1000.0f / t);
217 this->fpsHistory += this->currentFps;
218 this->fpsTime = QTime::currentTime();
219
220 // Calculate median:
221 int size = this->fpsHistory.size();
222 if (size == 10){
223 qSort(this->fpsHistory.begin(), this->fpsHistory.end());
224 this->fpsMedian = this->fpsHistory.at(int(size/2));
225 if (this->fpsMedian == 0)
226 this->fpsMedian = 0.01f;
227 this->fpsHistory.clear();
228 return true;
229 }
230 return false;
231}
232
233/**
234 Used for adaption in case things are so slow
235 that no median yet has been calculated
236*/
237void MainWindow::forceFpsMedianCalculation()
238{
239 if (this->fpsMedian != -1)
240 return;
241
242 int size = this->fpsHistory.size();
243 if (size == 0){
244 this->fpsMedian = 0.01f;
245 return;
246 }
247
248 qSort(this->fpsHistory.begin(), this->fpsHistory.end());
249 this->fpsMedian = this->fpsHistory.at(int(size/2));
250 if (this->fpsMedian == 0)
251 this->fpsMedian = 0.01f;
252}
253
254void MainWindow::tick()
255{
256 bool medianChanged = this->measureFps();
257 this->checkAdapt();
258
259 if (medianChanged && this->fpsLabel && Colors::showFps)
260 this->fpsLabel->setText(QString("FPS: ") + QString::number(int(this->currentFps)));
261
262 if (MenuManager::instance()->ticker)
263 MenuManager::instance()->ticker->tick();
264
265 this->viewport()->update();
266 if (Colors::softwareRendering)
267 QApplication::syncX();
268
269 if (this->useTimer)
270 this->updateTimer.start(int(1000 / Colors::fps));
271}
272
273void MainWindow::setupSceneItems()
274{
275 if (Colors::showFps){
276 this->fpsLabel = new DemoTextItem(QString("FPS: --"), Colors::buttonFont(), Qt::white, -1, this->scene, 0, DemoTextItem::DYNAMIC_TEXT);
277 this->fpsLabel->setZValue(100);
278 this->fpsLabel->setPos(Colors::stageStartX, 600 - QFontMetricsF(Colors::buttonFont()).height() - 5);
279 }
280
281 this->trolltechLogo = new ImageItem(QImage(":/images/trolltech-logo.png"), 1000, 1000, this->scene, 0, true, 0.5f);
282 this->qtLogo = new ImageItem(QImage(":/images/qtlogo_small.png"), 1000, 1000, this->scene, 0, true, 0.5f);
283 this->trolltechLogo->setZValue(100);
284 this->qtLogo->setZValue(100);
285 this->pausedLabel = new DemoTextItem(QString("PAUSED"), Colors::buttonFont(), Qt::white, -1, this->scene, 0);
286 this->pausedLabel->setZValue(100);
287 QFontMetricsF fm(Colors::buttonFont());
288 this->pausedLabel->setPos(Colors::stageWidth - fm.width("PAUSED"), 590 - fm.height());
289 this->pausedLabel->setRecursiveVisible(false);
290}
291
292void MainWindow::checkAdapt()
293{
294 if (this->doneAdapt
295 || Colors::noTimerUpdate
296 || this->demoStartTime.elapsed() < 2000)
297 return;
298
299 this->doneAdapt = true;
300 this->forceFpsMedianCalculation();
301 Colors::benchmarkFps = this->fpsMedian;
302 if (Colors::verbose)
303 qDebug() << "- benchmark:" << QString::number(Colors::benchmarkFps) << "FPS";
304
305 if (Colors::noAdapt)
306 return;
307
308 if (this->fpsMedian < 30){
309 if (MenuManager::instance()->ticker && MenuManager::instance()->ticker->scene()){
310 this->scene->removeItem(MenuManager::instance()->ticker);
311 Colors::noTimerUpdate = true;
312 this->switchTimerOnOff(false);
313 if (this->fpsLabel)
314 this->fpsLabel->setText(QString("FPS: (") + QString::number(this->fpsMedian) + QString(")"));
315 if (Colors::verbose)
316 qDebug() << "- benchmark adaption: removed ticker (fps < 30)";
317 }
318
319 if (this->fpsMedian < 20){
320 Colors::noAnimations = true;
321 if (Colors::verbose)
322 qDebug() << "- benchmark adaption: animations switched off (fps < 20)";
323 }
324
325 Colors::adapted = true;
326 }
327}
328
329int MainWindow::performBenchmark()
330{
331/*
332 QTime time;
333 time.restart();
334 while (time.elapsed() < 2000)
335 QCoreApplication::processEvents(QEventLoop::AllEvents, 50);
336*/
337 return 0;
338}
339
340void MainWindow::drawBackgroundToPixmap()
341{
342 const QRectF r = this->scene->sceneRect();
343 this->background = QPixmap(qRound(r.width()), qRound(r.height()));
344 this->background.fill(Qt::black);
345 QPainter painter(&this->background);
346
347 if (false && Colors::useEightBitPalette){
348 painter.fillRect(r, Colors::sceneBg1);
349 } else {
350 QImage bg(":/images/demobg.png");
351 painter.drawImage(0, 0, bg);
352 }
353}
354
355void MainWindow::drawBackground(QPainter *painter, const QRectF &rect)
356{
357 Q_UNUSED(rect);
358 painter->drawPixmap(QPoint(0, 0), this->background);
359}
360
361void MainWindow::showEvent(QShowEvent * event)
362{
363 Q_UNUSED(event);
364 QGraphicsView::showEvent(event);
365}
366
367void MainWindow::toggleFullscreen()
368{
369 if (this->isFullScreen()){
370 this->enableMask(true);
371 this->showNormal();
372 if (MenuManager::instance()->ticker)
373 MenuManager::instance()->ticker->pause(false);
374 }
375 else {
376 this->enableMask(false);
377 this->showFullScreen();
378 }
379}
380
381void MainWindow::keyPressEvent(QKeyEvent *event)
382{
383 if (event->key() == Qt::Key_Escape){
384 this->loop = false;
385 QApplication::quit();
386 }
387 else if (event->key() == Qt::Key_1){
388 QString s("");
389 s += "Rendering system: ";
390 if (Colors::openGlRendering)
391 s += "OpenGL";
392 else if (Colors::direct3dRendering)
393 s += "Direct3D";
394 else
395 s += "software";
396
397 s += "\nAdapt: ";
398 s += Colors::noAdapt ? "off" : "on";
399 s += "\nAdaption occured: ";
400 s += Colors::adapted ? "yes" : "no";
401 s += "\nOpenGL version: ";
402 s += Colors::glVersion;
403 QWidget w;
404 s += "\nColor bit depth: ";
405 s += QString::number(w.depth());
406 s += "\nWanted FPS: ";
407 s += QString::number(Colors::fps);
408 s += "\nBenchmarked FPS: ";
409 s += Colors::benchmarkFps != -1 ? QString::number(Colors::benchmarkFps) : "not calculated";
410 s += "\nAnimations: ";
411 s += Colors::noAnimations ? "off" : "on";
412 s += "\nBlending: ";
413 s += Colors::useEightBitPalette ? "off" : "on";
414 s += "\nTicker: ";
415 s += Colors::noTicker ? "off" : "on";
416 s += "\nPixmaps: ";
417 s += Colors::usePixmaps ? "on" : "off";
418 s += "\nRescale images on resize: ";
419 s += Colors::noRescale ? "off" : "on";
420 s += "\nTimer based updates: ";
421 s += Colors::noTimerUpdate ? "off" : "on";
422 s += "\nSeparate loop: ";
423 s += Colors::useLoop ? "yes" : "no";
424 s += "\nScreen sync: ";
425 s += Colors::noScreenSync ? "no" : "yes";
426 QMessageBox::information(0, QString("Current configuration"), s);
427 }
428}
429
430void MainWindow::focusInEvent(QFocusEvent *)
431{
432 if (!Colors::pause)
433 return;
434
435 if (MenuManager::instance()->ticker)
436 MenuManager::instance()->ticker->pause(false);
437
438 int code = MenuManager::instance()->currentMenuCode;
439 if (code == MenuManager::ROOT || code == MenuManager::MENU1)
440 this->switchTimerOnOff(true);
441
442 this->pausedLabel->setRecursiveVisible(false);
443}
444
445void MainWindow::focusOutEvent(QFocusEvent *)
446{
447 if (!Colors::pause)
448 return;
449
450 if (MenuManager::instance()->ticker)
451 MenuManager::instance()->ticker->pause(true);
452
453 int code = MenuManager::instance()->currentMenuCode;
454 if (code == MenuManager::ROOT || code == MenuManager::MENU1)
455 this->switchTimerOnOff(false);
456
457 this->pausedLabel->setRecursiveVisible(true);
458}
459
460void MainWindow::resizeEvent(QResizeEvent *event)
461{
462 Q_UNUSED(event);
463
464 this->resetMatrix();
465 this->scale(event->size().width() / 800.0, event->size().height() / 600.0);
466 QGraphicsView::resizeEvent(event);
467 DemoItem::setMatrix(this->matrix());
468
469 if (this->trolltechLogo){
470 const QRectF r = this->scene->sceneRect();
471 QRectF ttb = this->trolltechLogo->boundingRect();
472 this->trolltechLogo->setPos(int((r.width() - ttb.width()) / 2), 595 - ttb.height());
473 QRectF qtb = this->qtLogo->boundingRect();
474 this->qtLogo->setPos(802 - qtb.width(), 0);
475 }
476
477 // Changing size will almost always
478 // hurt FPS during the changing. So
479 // ignore it.
480 this->fpsHistory.clear();
481}
482
483
Note: See TracBrowser for help on using the repository browser.