1 /***************************************************************************
2 * Copyright (C) 2010 by Simon Andreas Eugster (simon.eu@gmail.com) *
3 * This file is part of kdenlive. See www.kdenlive.org. *
5 * This program is free software; you can redistribute it and/or modify *
6 * it under the terms of the GNU General Public License as published by *
7 * the Free Software Foundation; either version 2 of the License, or *
8 * (at your option) any later version. *
9 ***************************************************************************/
11 #include "qtconcurrentrun.h"
13 #include "abstractscopewidget.h"
20 #include <QMouseEvent>
23 // Uncomment for Scope debugging.
30 const int REALTIME_FPS = 30;
32 const QColor light(250, 238, 226, 255);
33 const QColor dark(40, 40, 39, 255);
34 const QColor dark2(25, 25, 23, 255);
36 const QPen AbstractScopeWidget::penThick(QBrush(QColor(250, 250, 250)), 2, Qt::SolidLine);
37 const QPen AbstractScopeWidget::penThin(QBrush(QColor(250, 250, 250)), 1, Qt::SolidLine);
38 const QPen AbstractScopeWidget::penLight(QBrush(QColor(200, 200, 250, 150)), 1, Qt::SolidLine);
39 const QPen AbstractScopeWidget::penLightDots(QBrush(QColor(200, 200, 250, 150)), 1, Qt::DotLine);
40 const QPen AbstractScopeWidget::penLighter(QBrush(QColor(225, 225, 250, 225)), 1, Qt::SolidLine);
41 const QPen AbstractScopeWidget::penDark(QBrush(QColor(0, 0, 20, 250)), 1, Qt::SolidLine);
42 const QPen AbstractScopeWidget::penDarkDots(QBrush(QColor(0, 0, 20, 250)), 1, Qt::DotLine);
43 const QPen AbstractScopeWidget::penBackground(QBrush(dark2), 1, Qt::SolidLine);
45 const QString AbstractScopeWidget::directions[] = {"North", "Northeast", "East", "Southeast"};
47 AbstractScopeWidget::AbstractScopeWidget(bool trackMouse, QWidget *parent) :
50 m_mouseWithinWidget(false),
53 m_accelFactorScope(1),
54 m_accelFactorBackground(1),
57 m_semaphoreBackground(1),
58 initialDimensionUpdateDone(false),
59 m_requestForcedUpdate(false),
61 m_rescaleVerticalThreshold(2.0f)
64 m_scopePalette = QPalette();
65 m_scopePalette.setBrush(QPalette::Window, QBrush(dark2));
66 m_scopePalette.setBrush(QPalette::Base, QBrush(dark));
67 m_scopePalette.setBrush(QPalette::Button, QBrush(dark));
68 m_scopePalette.setBrush(QPalette::Text, QBrush(light));
69 m_scopePalette.setBrush(QPalette::WindowText, QBrush(light));
70 m_scopePalette.setBrush(QPalette::ButtonText, QBrush(light));
71 this->setPalette(m_scopePalette);
72 this->setAutoFillBackground(true);
74 m_aAutoRefresh = new QAction(i18n("Auto Refresh"), this);
75 m_aAutoRefresh->setCheckable(true);
76 m_aRealtime = new QAction(i18n("Realtime (with precision loss)"), this);
77 m_aRealtime->setCheckable(true);
79 m_menu = new QMenu(this);
80 m_menu->setPalette(m_scopePalette);
81 m_menu->addAction(m_aAutoRefresh);
82 m_menu->addAction(m_aRealtime);
84 this->setContextMenuPolicy(Qt::CustomContextMenu);
87 b &= connect(this, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(customContextMenuRequested(QPoint)));
89 b &= connect(this, SIGNAL(signalHUDRenderingFinished(uint, uint)), this, SLOT(slotHUDRenderingFinished(uint, uint)));
90 b &= connect(this, SIGNAL(signalScopeRenderingFinished(uint, uint)), this, SLOT(slotScopeRenderingFinished(uint, uint)));
91 b &= connect(this, SIGNAL(signalBackgroundRenderingFinished(uint, uint)), this, SLOT(slotBackgroundRenderingFinished(uint, uint)));
92 b &= connect(m_aRealtime, SIGNAL(toggled(bool)), this, SLOT(slotResetRealtimeFactor(bool)));
93 b &= connect(m_aAutoRefresh, SIGNAL(toggled(bool)), this, SLOT(slotAutoRefreshToggled(bool)));
96 // Enable mouse tracking if desired.
97 // Causes the mouseMoved signal to be emitted when the mouse moves inside the
98 // widget, even when no mouse button is pressed.
99 this->setMouseTracking(trackMouse);
102 AbstractScopeWidget::~AbstractScopeWidget()
107 delete m_aAutoRefresh;
111 void AbstractScopeWidget::init()
113 m_widgetName = widgetName();
117 void AbstractScopeWidget::readConfig()
119 KSharedConfigPtr config = KGlobal::config();
120 KConfigGroup scopeConfig(config, configName());
121 m_aAutoRefresh->setChecked(scopeConfig.readEntry("autoRefresh", true));
122 m_aRealtime->setChecked(scopeConfig.readEntry("realtime", false));
126 void AbstractScopeWidget::writeConfig()
128 KSharedConfigPtr config = KGlobal::config();
129 KConfigGroup scopeConfig(config, configName());
130 scopeConfig.writeEntry("autoRefresh", m_aAutoRefresh->isChecked());
131 scopeConfig.writeEntry("realtime", m_aRealtime->isChecked());
135 QString AbstractScopeWidget::configName()
137 return "Scope_" + m_widgetName;
140 void AbstractScopeWidget::prodHUDThread()
142 if (this->visibleRegion().isEmpty()) {
144 qDebug() << "Scope " << m_widgetName << " is not visible. Not calculating HUD.";
147 if (m_semaphoreHUD.tryAcquire(1)) {
148 Q_ASSERT(!m_threadHUD.isRunning());
150 m_newHUDFrames.fetchAndStoreRelaxed(0);
151 m_newHUDUpdates.fetchAndStoreRelaxed(0);
152 m_threadHUD = QtConcurrent::run(this, &AbstractScopeWidget::renderHUD, m_accelFactorHUD);
154 qDebug() << "HUD thread started in " << m_widgetName;
160 qDebug() << "HUD semaphore locked, not prodding in " << m_widgetName << ". Thread running: " << m_threadHUD.isRunning();
166 void AbstractScopeWidget::prodScopeThread()
168 // Only start a new thread if the scope is actually visible
169 // and not hidden by another widget on the stack and if user want the scope to update.
170 if (this->visibleRegion().isEmpty() || (!m_aAutoRefresh->isChecked() && !m_requestForcedUpdate)) {
172 qDebug() << "Scope " << m_widgetName << " is not visible. Not calculating scope.";
175 // Try to acquire the semaphore. This must only succeed if m_threadScope is not running
176 // anymore. Therefore the semaphore must NOT be released before m_threadScope ends.
177 // If acquiring the semaphore fails, the thread is still running.
178 if (m_semaphoreScope.tryAcquire(1)) {
179 Q_ASSERT(!m_threadScope.isRunning());
181 m_newScopeFrames.fetchAndStoreRelaxed(0);
182 m_newScopeUpdates.fetchAndStoreRelaxed(0);
184 Q_ASSERT(m_accelFactorScope > 0);
186 // See http://doc.qt.nokia.com/latest/qtconcurrentrun.html#run about
187 // running member functions in a thread
188 m_threadScope = QtConcurrent::run(this, &AbstractScopeWidget::renderScope, m_accelFactorScope);
189 m_requestForcedUpdate = false;
192 qDebug() << "Scope thread started in " << m_widgetName;
197 qDebug() << "Scope semaphore locked, not prodding in " << m_widgetName << ". Thread running: " << m_threadScope.isRunning();
202 void AbstractScopeWidget::prodBackgroundThread()
204 if (this->visibleRegion().isEmpty()) {
206 qDebug() << "Scope " << m_widgetName << " is not visible. Not calculating background.";
209 if (m_semaphoreBackground.tryAcquire(1)) {
210 Q_ASSERT(!m_threadBackground.isRunning());
212 m_newBackgroundFrames.fetchAndStoreRelaxed(0);
213 m_newBackgroundUpdates.fetchAndStoreRelaxed(0);
214 m_threadBackground = QtConcurrent::run(this, &AbstractScopeWidget::renderBackground, m_accelFactorBackground);
217 qDebug() << "Background thread started in " << m_widgetName;
222 qDebug() << "Background semaphore locked, not prodding in " << m_widgetName << ". Thread running: " << m_threadBackground.isRunning();
228 void AbstractScopeWidget::forceUpdate(bool doUpdate)
231 qDebug() << "Forced update called in " << widgetName() << ". Arg: " << doUpdate;
237 m_requestForcedUpdate = true;
238 m_newHUDUpdates.fetchAndAddRelaxed(1);
239 m_newScopeUpdates.fetchAndAddRelaxed(1);
240 m_newBackgroundUpdates.fetchAndAddRelaxed(1);
243 prodBackgroundThread();
245 void AbstractScopeWidget::forceUpdateHUD()
247 m_newHUDUpdates.fetchAndAddRelaxed(1);
251 void AbstractScopeWidget::forceUpdateScope()
253 m_newScopeUpdates.fetchAndAddRelaxed(1);
254 m_requestForcedUpdate = true;
258 void AbstractScopeWidget::forceUpdateBackground()
260 m_newBackgroundUpdates.fetchAndAddRelaxed(1);
261 prodBackgroundThread();
269 void AbstractScopeWidget::resizeEvent(QResizeEvent *event)
271 // Update the dimension of the available rect for painting
272 m_scopeRect = scopeRect();
275 QWidget::resizeEvent(event);
278 void AbstractScopeWidget::showEvent(QShowEvent *event)
280 QWidget::showEvent(event);
281 m_scopeRect = scopeRect();
284 void AbstractScopeWidget::paintEvent(QPaintEvent *)
286 QPainter davinci(this);
287 davinci.drawImage(m_scopeRect.topLeft(), m_imgBackground);
288 davinci.drawImage(m_scopeRect.topLeft(), m_imgScope);
289 davinci.drawImage(m_scopeRect.topLeft(), m_imgHUD);
292 void AbstractScopeWidget::mousePressEvent(QMouseEvent *event)
294 if (event->button() == Qt::LeftButton) {
295 // Rescaling mode starts
296 m_rescaleActive = true;
297 m_rescalePropertiesLocked = false;
298 m_rescaleFirstRescaleDone = false;
299 m_rescaleStartPoint = event->pos();
300 m_rescaleModifiers = event->modifiers();
303 void AbstractScopeWidget::mouseReleaseEvent(QMouseEvent *event)
305 m_rescaleActive = false;
306 m_rescalePropertiesLocked = false;
308 if (!m_aAutoRefresh->isChecked()) {
309 m_requestForcedUpdate = true;
313 prodBackgroundThread();
314 QWidget::mouseReleaseEvent(event);
316 void AbstractScopeWidget::mouseMoveEvent(QMouseEvent *event)
318 m_mousePos = event->pos();
319 m_mouseWithinWidget = true;
320 emit signalMousePositionChanged();
322 QPoint movement = event->pos()-m_rescaleStartPoint;
324 if (m_rescaleActive) {
325 if (m_rescalePropertiesLocked) {
326 // Direction is known, now adjust parameters
328 // Reset the starting point to make the next moveEvent relative to the current one
329 m_rescaleStartPoint = event->pos();
332 if (!m_rescaleFirstRescaleDone) {
333 // We have just learned the desired direction; Normalize the movement to one pixel
334 // to avoid a jump by m_rescaleMinDist
336 if (movement.x() != 0) {
337 movement.setX(movement.x() / abs(movement.x()));
339 if (movement.y() != 0) {
340 movement.setY(movement.y() / abs(movement.y()));
343 m_rescaleFirstRescaleDone = true;
346 handleMouseDrag(movement, m_rescaleDirection, m_rescaleModifiers);
351 // Detect the movement direction here.
352 // This algorithm relies on the aspect ratio of dy/dx (size and signum).
353 if (movement.manhattanLength() > m_rescaleMinDist) {
354 float diff = ((float) movement.y())/movement.x();
356 if (abs(diff) > m_rescaleVerticalThreshold || movement.x() == 0) {
357 m_rescaleDirection = North;
358 } else if (abs(diff) < 1/m_rescaleVerticalThreshold) {
359 m_rescaleDirection = East;
360 } else if (diff < 0) {
361 m_rescaleDirection = Northeast;
363 m_rescaleDirection = Southeast;
366 qDebug() << "Diff is " << diff << "; chose " << directions[m_rescaleDirection] << " as direction";
368 m_rescalePropertiesLocked = true;
374 void AbstractScopeWidget::leaveEvent(QEvent *)
376 m_mouseWithinWidget = false;
377 emit signalMousePositionChanged();
380 void AbstractScopeWidget::customContextMenuRequested(const QPoint &pos)
382 m_menu->exec(this->mapToGlobal(pos));
385 uint AbstractScopeWidget::calculateAccelFactorHUD(uint oldMseconds, uint)
387 return ceil((float)oldMseconds*REALTIME_FPS / 1000);
389 uint AbstractScopeWidget::calculateAccelFactorScope(uint oldMseconds, uint)
391 return ceil((float)oldMseconds*REALTIME_FPS / 1000);
393 uint AbstractScopeWidget::calculateAccelFactorBackground(uint oldMseconds, uint)
395 return ceil((float)oldMseconds*REALTIME_FPS / 1000);
401 void AbstractScopeWidget::slotHUDRenderingFinished(uint mseconds, uint oldFactor)
404 qDebug() << "HUD rendering has finished in " << mseconds << " ms, waiting for termination in " << m_widgetName;
406 m_threadHUD.waitForFinished();
407 m_imgHUD = m_threadHUD.result();
409 m_semaphoreHUD.release(1);
413 if (m_aRealtime->isChecked()) {
414 accel = calculateAccelFactorHUD(mseconds, oldFactor);
415 if (m_accelFactorHUD < 1) {
418 m_accelFactorHUD = accel;
421 if ((m_newHUDFrames > 0 && m_aAutoRefresh->isChecked()) || m_newHUDUpdates > 0) {
423 qDebug() << "Trying to start a new HUD thread for " << m_widgetName
424 << ". New frames/updates: " << m_newHUDFrames << "/" << m_newHUDUpdates;
430 void AbstractScopeWidget::slotScopeRenderingFinished(uint mseconds, uint oldFactor)
432 // The signal can be received before the thread has really finished. So we
433 // need to wait until it has really finished before starting a new thread.
435 qDebug() << "Scope rendering has finished in " << mseconds << " ms, waiting for termination in " << m_widgetName;
437 m_threadScope.waitForFinished();
438 m_imgScope = m_threadScope.result();
440 // The scope thread has finished. Now we can release the semaphore, allowing a new thread.
441 // See prodScopeThread where the semaphore is acquired again.
442 m_semaphoreScope.release(1);
445 // Calculate the acceleration factor hint to get «realtime» updates.
447 if (m_aRealtime->isChecked()) {
448 accel = calculateAccelFactorScope(mseconds, oldFactor);
450 // If mseconds happens to be 0.
453 // Don't directly calculate with m_accelFactorScope as we are dealing with concurrency.
454 // If m_accelFactorScope is set to 0 at the wrong moment, who knows what might happen
455 // then :) Therefore use a local variable.
456 m_accelFactorScope = accel;
459 if ((m_newScopeFrames > 0 && m_aAutoRefresh->isChecked()) || m_newScopeUpdates > 0) {
461 qDebug() << "Trying to start a new scope thread for " << m_widgetName
462 << ". New frames/updates: " << m_newScopeFrames << "/" << m_newScopeUpdates;
468 void AbstractScopeWidget::slotBackgroundRenderingFinished(uint mseconds, uint oldFactor)
471 qDebug() << "Background rendering has finished in " << mseconds << " ms, waiting for termination in " << m_widgetName;
473 m_threadBackground.waitForFinished();
474 m_imgBackground = m_threadBackground.result();
476 m_semaphoreBackground.release(1);
480 if (m_aRealtime->isChecked()) {
481 accel = calculateAccelFactorBackground(mseconds, oldFactor);
482 if (m_accelFactorBackground < 1) {
485 m_accelFactorBackground = accel;
488 if ((m_newBackgroundFrames > 0 && m_aAutoRefresh->isChecked()) || m_newBackgroundUpdates > 0) {
490 qDebug() << "Trying to start a new background thread for " << m_widgetName
491 << ". New frames/updates: " << m_newBackgroundFrames << "/" << m_newBackgroundUpdates;
493 prodBackgroundThread();;
497 void AbstractScopeWidget::slotRenderZoneUpdated()
499 m_newHUDFrames.fetchAndAddRelaxed(1);
500 m_newScopeFrames.fetchAndAddRelaxed(1);
501 m_newBackgroundFrames.fetchAndAddRelaxed(1);
504 qDebug() << "Data incoming at " << widgetName() << ". New frames total HUD/Scope/Background: " << m_newHUDFrames
505 << "/" << m_newScopeFrames << "/" << m_newBackgroundFrames;
508 if (this->visibleRegion().isEmpty()) {
510 qDebug() << "Scope of widget " << m_widgetName << " is not at the top, not rendering.";
513 if (m_aAutoRefresh->isChecked()) {
516 prodBackgroundThread();
521 void AbstractScopeWidget::slotResetRealtimeFactor(bool realtimeChecked)
523 if (!realtimeChecked) {
524 m_accelFactorHUD = 1;
525 m_accelFactorScope = 1;
526 m_accelFactorBackground = 1;
530 bool AbstractScopeWidget::autoRefreshEnabled()
532 return m_aAutoRefresh->isChecked();
535 void AbstractScopeWidget::slotAutoRefreshToggled(bool autoRefresh)
538 qDebug() << "Auto-refresh switched to " << autoRefresh << " in " << widgetName()
539 << " (Visible: " << isVisible() << "/" << this->visibleRegion().isEmpty() << ")";
542 // Notify listeners whether we accept new frames now
543 emit requestAutoRefresh(autoRefresh);
545 // TODO only if depends on input
548 m_requestForcedUpdate = true;
552 void AbstractScopeWidget::handleMouseDrag(const QPoint, const RescaleDirection, const Qt::KeyboardModifiers) { }