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);
44 const QString AbstractScopeWidget::directions[] = {"North", "Northeast", "East", "Southeast"};
46 AbstractScopeWidget::AbstractScopeWidget(bool trackMouse, QWidget *parent) :
49 m_mouseWithinWidget(false),
52 m_accelFactorScope(1),
53 m_accelFactorBackground(1),
56 m_semaphoreBackground(1),
57 initialDimensionUpdateDone(false),
58 m_requestForcedUpdate(false),
60 m_rescaleVerticalThreshold(2.0f)
63 m_scopePalette = QPalette();
64 m_scopePalette.setBrush(QPalette::Window, QBrush(dark2));
65 m_scopePalette.setBrush(QPalette::Base, QBrush(dark));
66 m_scopePalette.setBrush(QPalette::Button, QBrush(dark));
67 m_scopePalette.setBrush(QPalette::Text, QBrush(light));
68 m_scopePalette.setBrush(QPalette::WindowText, QBrush(light));
69 m_scopePalette.setBrush(QPalette::ButtonText, QBrush(light));
70 this->setPalette(m_scopePalette);
71 this->setAutoFillBackground(true);
73 m_aAutoRefresh = new QAction(i18n("Auto Refresh"), this);
74 m_aAutoRefresh->setCheckable(true);
75 m_aRealtime = new QAction(i18n("Realtime (with precision loss)"), this);
76 m_aRealtime->setCheckable(true);
78 m_menu = new QMenu(this);
79 m_menu->setPalette(m_scopePalette);
80 m_menu->addAction(m_aAutoRefresh);
81 m_menu->addAction(m_aRealtime);
83 this->setContextMenuPolicy(Qt::CustomContextMenu);
86 b &= connect(this, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(customContextMenuRequested(QPoint)));
88 b &= connect(this, SIGNAL(signalHUDRenderingFinished(uint, uint)), this, SLOT(slotHUDRenderingFinished(uint, uint)));
89 b &= connect(this, SIGNAL(signalScopeRenderingFinished(uint, uint)), this, SLOT(slotScopeRenderingFinished(uint, uint)));
90 b &= connect(this, SIGNAL(signalBackgroundRenderingFinished(uint, uint)), this, SLOT(slotBackgroundRenderingFinished(uint, uint)));
91 b &= connect(m_aRealtime, SIGNAL(toggled(bool)), this, SLOT(slotResetRealtimeFactor(bool)));
92 b &= connect(m_aAutoRefresh, SIGNAL(toggled(bool)), this, SLOT(slotAutoRefreshToggled(bool)));
95 // Enable mouse tracking if desired.
96 // Causes the mouseMoved signal to be emitted when the mouse moves inside the
97 // widget, even when no mouse button is pressed.
98 this->setMouseTracking(trackMouse);
101 AbstractScopeWidget::~AbstractScopeWidget()
106 delete m_aAutoRefresh;
110 void AbstractScopeWidget::init()
112 m_widgetName = widgetName();
116 void AbstractScopeWidget::readConfig()
118 KSharedConfigPtr config = KGlobal::config();
119 KConfigGroup scopeConfig(config, configName());
120 m_aAutoRefresh->setChecked(scopeConfig.readEntry("autoRefresh", true));
121 m_aRealtime->setChecked(scopeConfig.readEntry("realtime", false));
125 void AbstractScopeWidget::writeConfig()
127 KSharedConfigPtr config = KGlobal::config();
128 KConfigGroup scopeConfig(config, configName());
129 scopeConfig.writeEntry("autoRefresh", m_aAutoRefresh->isChecked());
130 scopeConfig.writeEntry("realtime", m_aRealtime->isChecked());
134 QString AbstractScopeWidget::configName()
136 return "Scope_" + m_widgetName;
139 void AbstractScopeWidget::prodHUDThread()
141 if (this->visibleRegion().isEmpty()) {
143 qDebug() << "Scope " << m_widgetName << " is not visible. Not calculating HUD.";
146 if (m_semaphoreHUD.tryAcquire(1)) {
147 Q_ASSERT(!m_threadHUD.isRunning());
149 m_newHUDFrames.fetchAndStoreRelaxed(0);
150 m_newHUDUpdates.fetchAndStoreRelaxed(0);
151 m_threadHUD = QtConcurrent::run(this, &AbstractScopeWidget::renderHUD, m_accelFactorHUD);
153 qDebug() << "HUD thread started in " << m_widgetName;
159 qDebug() << "HUD semaphore locked, not prodding in " << m_widgetName << ". Thread running: " << m_threadHUD.isRunning();
165 void AbstractScopeWidget::prodScopeThread()
167 // Only start a new thread if the scope is actually visible
168 // and not hidden by another widget on the stack and if user want the scope to update.
169 if (this->visibleRegion().isEmpty() || (!m_aAutoRefresh->isChecked() && !m_requestForcedUpdate)) {
171 qDebug() << "Scope " << m_widgetName << " is not visible. Not calculating scope.";
174 // Try to acquire the semaphore. This must only succeed if m_threadScope is not running
175 // anymore. Therefore the semaphore must NOT be released before m_threadScope ends.
176 // If acquiring the semaphore fails, the thread is still running.
177 if (m_semaphoreScope.tryAcquire(1)) {
178 Q_ASSERT(!m_threadScope.isRunning());
180 m_newScopeFrames.fetchAndStoreRelaxed(0);
181 m_newScopeUpdates.fetchAndStoreRelaxed(0);
183 Q_ASSERT(m_accelFactorScope > 0);
185 // See http://doc.qt.nokia.com/latest/qtconcurrentrun.html#run about
186 // running member functions in a thread
187 m_threadScope = QtConcurrent::run(this, &AbstractScopeWidget::renderScope, m_accelFactorScope);
188 m_requestForcedUpdate = false;
191 qDebug() << "Scope thread started in " << m_widgetName;
196 qDebug() << "Scope semaphore locked, not prodding in " << m_widgetName << ". Thread running: " << m_threadScope.isRunning();
201 void AbstractScopeWidget::prodBackgroundThread()
203 if (this->visibleRegion().isEmpty()) {
205 qDebug() << "Scope " << m_widgetName << " is not visible. Not calculating background.";
208 if (m_semaphoreBackground.tryAcquire(1)) {
209 Q_ASSERT(!m_threadBackground.isRunning());
211 m_newBackgroundFrames.fetchAndStoreRelaxed(0);
212 m_newBackgroundUpdates.fetchAndStoreRelaxed(0);
213 m_threadBackground = QtConcurrent::run(this, &AbstractScopeWidget::renderBackground, m_accelFactorBackground);
216 qDebug() << "Background thread started in " << m_widgetName;
221 qDebug() << "Background semaphore locked, not prodding in " << m_widgetName << ". Thread running: " << m_threadBackground.isRunning();
227 void AbstractScopeWidget::forceUpdate(bool doUpdate)
230 qDebug() << "Forced update called in " << widgetName() << ". Arg: " << doUpdate;
236 m_requestForcedUpdate = true;
237 m_newHUDUpdates.fetchAndAddRelaxed(1);
238 m_newScopeUpdates.fetchAndAddRelaxed(1);
239 m_newBackgroundUpdates.fetchAndAddRelaxed(1);
242 prodBackgroundThread();
244 void AbstractScopeWidget::forceUpdateHUD()
246 m_newHUDUpdates.fetchAndAddRelaxed(1);
250 void AbstractScopeWidget::forceUpdateScope()
252 m_newScopeUpdates.fetchAndAddRelaxed(1);
253 m_requestForcedUpdate = true;
257 void AbstractScopeWidget::forceUpdateBackground()
259 m_newBackgroundUpdates.fetchAndAddRelaxed(1);
260 prodBackgroundThread();
268 void AbstractScopeWidget::resizeEvent(QResizeEvent *event)
270 // Update the dimension of the available rect for painting
271 m_scopeRect = scopeRect();
274 QWidget::resizeEvent(event);
277 void AbstractScopeWidget::showEvent(QShowEvent *event)
279 QWidget::showEvent(event);
280 m_scopeRect = scopeRect();
283 void AbstractScopeWidget::paintEvent(QPaintEvent *)
285 QPainter davinci(this);
286 davinci.drawImage(m_scopeRect.topLeft(), m_imgBackground);
287 davinci.drawImage(m_scopeRect.topLeft(), m_imgScope);
288 davinci.drawImage(m_scopeRect.topLeft(), m_imgHUD);
291 void AbstractScopeWidget::mousePressEvent(QMouseEvent *event)
293 if (event->button() == Qt::LeftButton) {
294 // Rescaling mode starts
295 m_rescaleActive = true;
296 m_rescalePropertiesLocked = false;
297 m_rescaleFirstRescaleDone = false;
298 m_rescaleStartPoint = event->pos();
299 m_rescaleModifiers = event->modifiers();
302 void AbstractScopeWidget::mouseReleaseEvent(QMouseEvent *event)
304 m_rescaleActive = false;
305 m_rescalePropertiesLocked = false;
307 if (!m_aAutoRefresh->isChecked()) {
308 m_requestForcedUpdate = true;
312 prodBackgroundThread();
313 QWidget::mouseReleaseEvent(event);
315 void AbstractScopeWidget::mouseMoveEvent(QMouseEvent *event)
317 m_mousePos = event->pos();
318 m_mouseWithinWidget = true;
319 emit signalMousePositionChanged();
321 QPoint movement = event->pos()-m_rescaleStartPoint;
323 if (m_rescaleActive) {
324 if (m_rescalePropertiesLocked) {
325 // Direction is known, now adjust parameters
327 // Reset the starting point to make the next moveEvent relative to the current one
328 m_rescaleStartPoint = event->pos();
331 if (!m_rescaleFirstRescaleDone) {
332 // We have just learned the desired direction; Normalize the movement to one pixel
333 // to avoid a jump by m_rescaleMinDist
335 if (movement.x() != 0) {
336 movement.setX(movement.x() / abs(movement.x()));
338 if (movement.y() != 0) {
339 movement.setY(movement.y() / abs(movement.y()));
342 m_rescaleFirstRescaleDone = true;
345 handleMouseDrag(movement, m_rescaleDirection, m_rescaleModifiers);
350 // Detect the movement direction here.
351 // This algorithm relies on the aspect ratio of dy/dx (size and signum).
352 if (movement.manhattanLength() > m_rescaleMinDist) {
353 float diff = ((float) movement.y())/movement.x();
355 if (abs(diff) > m_rescaleVerticalThreshold || movement.x() == 0) {
356 m_rescaleDirection = North;
357 } else if (abs(diff) < 1/m_rescaleVerticalThreshold) {
358 m_rescaleDirection = East;
359 } else if (diff < 0) {
360 m_rescaleDirection = Northeast;
362 m_rescaleDirection = Southeast;
365 qDebug() << "Diff is " << diff << "; chose " << directions[m_rescaleDirection] << " as direction";
367 m_rescalePropertiesLocked = true;
373 void AbstractScopeWidget::leaveEvent(QEvent *)
375 m_mouseWithinWidget = false;
376 emit signalMousePositionChanged();
379 void AbstractScopeWidget::customContextMenuRequested(const QPoint &pos)
381 m_menu->exec(this->mapToGlobal(pos));
384 uint AbstractScopeWidget::calculateAccelFactorHUD(uint oldMseconds, uint)
386 return ceil((float)oldMseconds*REALTIME_FPS / 1000);
388 uint AbstractScopeWidget::calculateAccelFactorScope(uint oldMseconds, uint)
390 return ceil((float)oldMseconds*REALTIME_FPS / 1000);
392 uint AbstractScopeWidget::calculateAccelFactorBackground(uint oldMseconds, uint)
394 return ceil((float)oldMseconds*REALTIME_FPS / 1000);
400 void AbstractScopeWidget::slotHUDRenderingFinished(uint mseconds, uint oldFactor)
403 qDebug() << "HUD rendering has finished in " << mseconds << " ms, waiting for termination in " << m_widgetName;
405 m_threadHUD.waitForFinished();
406 m_imgHUD = m_threadHUD.result();
408 m_semaphoreHUD.release(1);
412 if (m_aRealtime->isChecked()) {
413 accel = calculateAccelFactorHUD(mseconds, oldFactor);
414 if (m_accelFactorHUD < 1) {
417 m_accelFactorHUD = accel;
420 if ((m_newHUDFrames > 0 && m_aAutoRefresh->isChecked()) || m_newHUDUpdates > 0) {
422 qDebug() << "Trying to start a new HUD thread for " << m_widgetName
423 << ". New frames/updates: " << m_newHUDFrames << "/" << m_newHUDUpdates;
429 void AbstractScopeWidget::slotScopeRenderingFinished(uint mseconds, uint oldFactor)
431 // The signal can be received before the thread has really finished. So we
432 // need to wait until it has really finished before starting a new thread.
434 qDebug() << "Scope rendering has finished in " << mseconds << " ms, waiting for termination in " << m_widgetName;
436 m_threadScope.waitForFinished();
437 m_imgScope = m_threadScope.result();
439 // The scope thread has finished. Now we can release the semaphore, allowing a new thread.
440 // See prodScopeThread where the semaphore is acquired again.
441 m_semaphoreScope.release(1);
444 // Calculate the acceleration factor hint to get «realtime» updates.
446 if (m_aRealtime->isChecked()) {
447 accel = calculateAccelFactorScope(mseconds, oldFactor);
449 // If mseconds happens to be 0.
452 // Don't directly calculate with m_accelFactorScope as we are dealing with concurrency.
453 // If m_accelFactorScope is set to 0 at the wrong moment, who knows what might happen
454 // then :) Therefore use a local variable.
455 m_accelFactorScope = accel;
458 if ((m_newScopeFrames > 0 && m_aAutoRefresh->isChecked()) || m_newScopeUpdates > 0) {
460 qDebug() << "Trying to start a new scope thread for " << m_widgetName
461 << ". New frames/updates: " << m_newScopeFrames << "/" << m_newScopeUpdates;
467 void AbstractScopeWidget::slotBackgroundRenderingFinished(uint mseconds, uint oldFactor)
470 qDebug() << "Background rendering has finished in " << mseconds << " ms, waiting for termination in " << m_widgetName;
472 m_threadBackground.waitForFinished();
473 m_imgBackground = m_threadBackground.result();
475 m_semaphoreBackground.release(1);
479 if (m_aRealtime->isChecked()) {
480 accel = calculateAccelFactorBackground(mseconds, oldFactor);
481 if (m_accelFactorBackground < 1) {
484 m_accelFactorBackground = accel;
487 if ((m_newBackgroundFrames > 0 && m_aAutoRefresh->isChecked()) || m_newBackgroundUpdates > 0) {
489 qDebug() << "Trying to start a new background thread for " << m_widgetName
490 << ". New frames/updates: " << m_newBackgroundFrames << "/" << m_newBackgroundUpdates;
492 prodBackgroundThread();;
496 void AbstractScopeWidget::slotRenderZoneUpdated()
498 m_newHUDFrames.fetchAndAddRelaxed(1);
499 m_newScopeFrames.fetchAndAddRelaxed(1);
500 m_newBackgroundFrames.fetchAndAddRelaxed(1);
503 qDebug() << "Data incoming at " << widgetName() << ". New frames total HUD/Scope/Background: " << m_newHUDFrames
504 << "/" << m_newScopeFrames << "/" << m_newBackgroundFrames;
507 if (this->visibleRegion().isEmpty()) {
509 qDebug() << "Scope of widget " << m_widgetName << " is not at the top, not rendering.";
512 if (m_aAutoRefresh->isChecked()) {
515 prodBackgroundThread();
520 void AbstractScopeWidget::slotResetRealtimeFactor(bool realtimeChecked)
522 if (!realtimeChecked) {
523 m_accelFactorHUD = 1;
524 m_accelFactorScope = 1;
525 m_accelFactorBackground = 1;
529 bool AbstractScopeWidget::autoRefreshEnabled()
531 return m_aAutoRefresh->isChecked();
534 void AbstractScopeWidget::slotAutoRefreshToggled(bool autoRefresh)
537 qDebug() << "Auto-refresh switched to " << autoRefresh << " in " << widgetName()
538 << " (Visible: " << isVisible() << "/" << this->visibleRegion().isEmpty() << ")";
541 // Notify listeners whether we accept new frames now
542 emit requestAutoRefresh(autoRefresh);
544 // TODO only if depends on input
547 m_requestForcedUpdate = true;
551 void AbstractScopeWidget::handleMouseDrag(const QPoint, const RescaleDirection, const Qt::KeyboardModifiers) { }