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 "abstractscopewidget.h"
15 #include <QtConcurrentRun>
19 #include <QMouseEvent>
22 #include <KConfigGroup>
24 // Uncomment for Scope debugging.
31 const int REALTIME_FPS = 30;
33 const QColor light(250, 238, 226, 255);
34 const QColor dark(40, 40, 39, 255);
35 const QColor dark2(25, 25, 23, 255);
36 const QColor AbstractScopeWidget::colHighlightLight(18, 130, 255, 255);
37 const QColor AbstractScopeWidget::colHighlightDark(255, 64, 19, 255);
38 const QColor AbstractScopeWidget::colDarkWhite(250, 250, 250);
40 const QPen AbstractScopeWidget::penThick(QBrush(AbstractScopeWidget::colDarkWhite.rgb()), 2, Qt::SolidLine);
41 const QPen AbstractScopeWidget::penThin(QBrush(AbstractScopeWidget::colDarkWhite.rgb()), 1, Qt::SolidLine);
42 const QPen AbstractScopeWidget::penLight(QBrush(QColor(200, 200, 250, 150)), 1, Qt::SolidLine);
43 const QPen AbstractScopeWidget::penLightDots(QBrush(QColor(200, 200, 250, 150)), 1, Qt::DotLine);
44 const QPen AbstractScopeWidget::penLighter(QBrush(QColor(225, 225, 250, 225)), 1, Qt::SolidLine);
45 const QPen AbstractScopeWidget::penDark(QBrush(QColor(0, 0, 20, 250)), 1, Qt::SolidLine);
46 const QPen AbstractScopeWidget::penDarkDots(QBrush(QColor(0, 0, 20, 250)), 1, Qt::DotLine);
47 const QPen AbstractScopeWidget::penBackground(QBrush(dark2), 1, Qt::SolidLine);
49 const QString AbstractScopeWidget::directions[] = {"North", "Northeast", "East", "Southeast"};
51 AbstractScopeWidget::AbstractScopeWidget(bool trackMouse, QWidget *parent) :
54 m_mouseWithinWidget(false),
57 m_accelFactorScope(1),
58 m_accelFactorBackground(1),
61 m_semaphoreBackground(1),
62 initialDimensionUpdateDone(false),
63 m_requestForcedUpdate(false),
65 m_rescaleVerticalThreshold(2.0f)
68 m_scopePalette = QPalette();
69 m_scopePalette.setBrush(QPalette::Window, QBrush(dark2));
70 m_scopePalette.setBrush(QPalette::Base, QBrush(dark));
71 m_scopePalette.setBrush(QPalette::Button, QBrush(dark));
72 m_scopePalette.setBrush(QPalette::Text, QBrush(light));
73 m_scopePalette.setBrush(QPalette::WindowText, QBrush(light));
74 m_scopePalette.setBrush(QPalette::ButtonText, QBrush(light));
75 this->setPalette(m_scopePalette);
76 this->setAutoFillBackground(true);
78 m_aAutoRefresh = new QAction(i18n("Auto Refresh"), this);
79 m_aAutoRefresh->setCheckable(true);
80 m_aRealtime = new QAction(i18n("Realtime (with precision loss)"), this);
81 m_aRealtime->setCheckable(true);
83 m_menu = new QMenu(this);
84 m_menu->setPalette(m_scopePalette);
85 m_menu->addAction(m_aAutoRefresh);
86 m_menu->addAction(m_aRealtime);
88 this->setContextMenuPolicy(Qt::CustomContextMenu);
91 b &= connect(this, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(customContextMenuRequested(QPoint)));
93 b &= connect(this, SIGNAL(signalHUDRenderingFinished(uint, uint)), this, SLOT(slotHUDRenderingFinished(uint, uint)));
94 b &= connect(this, SIGNAL(signalScopeRenderingFinished(uint, uint)), this, SLOT(slotScopeRenderingFinished(uint, uint)));
95 b &= connect(this, SIGNAL(signalBackgroundRenderingFinished(uint, uint)), this, SLOT(slotBackgroundRenderingFinished(uint, uint)));
96 b &= connect(m_aRealtime, SIGNAL(toggled(bool)), this, SLOT(slotResetRealtimeFactor(bool)));
97 b &= connect(m_aAutoRefresh, SIGNAL(toggled(bool)), this, SLOT(slotAutoRefreshToggled(bool)));
100 // Enable mouse tracking if desired.
101 // Causes the mouseMoved signal to be emitted when the mouse moves inside the
102 // widget, even when no mouse button is pressed.
103 this->setMouseTracking(trackMouse);
106 AbstractScopeWidget::~AbstractScopeWidget()
111 delete m_aAutoRefresh;
115 void AbstractScopeWidget::init()
117 m_widgetName = widgetName();
121 void AbstractScopeWidget::readConfig()
123 KSharedConfigPtr config = KGlobal::config();
124 KConfigGroup scopeConfig(config, configName());
125 m_aAutoRefresh->setChecked(scopeConfig.readEntry("autoRefresh", true));
126 m_aRealtime->setChecked(scopeConfig.readEntry("realtime", false));
130 void AbstractScopeWidget::writeConfig()
132 KSharedConfigPtr config = KGlobal::config();
133 KConfigGroup scopeConfig(config, configName());
134 scopeConfig.writeEntry("autoRefresh", m_aAutoRefresh->isChecked());
135 scopeConfig.writeEntry("realtime", m_aRealtime->isChecked());
139 QString AbstractScopeWidget::configName()
141 return "Scope_" + m_widgetName;
144 void AbstractScopeWidget::prodHUDThread()
146 if (this->visibleRegion().isEmpty()) {
148 qDebug() << "Scope " << m_widgetName << " is not visible. Not calculating HUD.";
151 if (m_semaphoreHUD.tryAcquire(1)) {
152 Q_ASSERT(!m_threadHUD.isRunning());
154 m_newHUDFrames.fetchAndStoreRelaxed(0);
155 m_newHUDUpdates.fetchAndStoreRelaxed(0);
156 m_threadHUD = QtConcurrent::run(this, &AbstractScopeWidget::renderHUD, m_accelFactorHUD);
158 qDebug() << "HUD thread started in " << m_widgetName;
164 qDebug() << "HUD semaphore locked, not prodding in " << m_widgetName << ". Thread running: " << m_threadHUD.isRunning();
170 void AbstractScopeWidget::prodScopeThread()
172 // Only start a new thread if the scope is actually visible
173 // and not hidden by another widget on the stack and if user want the scope to update.
174 if (this->visibleRegion().isEmpty() || (!m_aAutoRefresh->isChecked() && !m_requestForcedUpdate)) {
176 qDebug() << "Scope " << m_widgetName << " is not visible. Not calculating scope.";
179 // Try to acquire the semaphore. This must only succeed if m_threadScope is not running
180 // anymore. Therefore the semaphore must NOT be released before m_threadScope ends.
181 // If acquiring the semaphore fails, the thread is still running.
182 if (m_semaphoreScope.tryAcquire(1)) {
183 Q_ASSERT(!m_threadScope.isRunning());
185 m_newScopeFrames.fetchAndStoreRelaxed(0);
186 m_newScopeUpdates.fetchAndStoreRelaxed(0);
188 Q_ASSERT(m_accelFactorScope > 0);
190 // See http://doc.qt.nokia.com/latest/qtconcurrentrun.html#run about
191 // running member functions in a thread
192 m_threadScope = QtConcurrent::run(this, &AbstractScopeWidget::renderScope, m_accelFactorScope);
193 m_requestForcedUpdate = false;
196 qDebug() << "Scope thread started in " << m_widgetName;
201 qDebug() << "Scope semaphore locked, not prodding in " << m_widgetName << ". Thread running: " << m_threadScope.isRunning();
206 void AbstractScopeWidget::prodBackgroundThread()
208 if (this->visibleRegion().isEmpty()) {
210 qDebug() << "Scope " << m_widgetName << " is not visible. Not calculating background.";
213 if (m_semaphoreBackground.tryAcquire(1)) {
214 Q_ASSERT(!m_threadBackground.isRunning());
216 m_newBackgroundFrames.fetchAndStoreRelaxed(0);
217 m_newBackgroundUpdates.fetchAndStoreRelaxed(0);
218 m_threadBackground = QtConcurrent::run(this, &AbstractScopeWidget::renderBackground, m_accelFactorBackground);
221 qDebug() << "Background thread started in " << m_widgetName;
226 qDebug() << "Background semaphore locked, not prodding in " << m_widgetName << ". Thread running: " << m_threadBackground.isRunning();
232 void AbstractScopeWidget::forceUpdate(bool doUpdate)
235 qDebug() << "Forced update called in " << widgetName() << ". Arg: " << doUpdate;
241 m_requestForcedUpdate = true;
242 m_newHUDUpdates.fetchAndAddRelaxed(1);
243 m_newScopeUpdates.fetchAndAddRelaxed(1);
244 m_newBackgroundUpdates.fetchAndAddRelaxed(1);
247 prodBackgroundThread();
249 void AbstractScopeWidget::forceUpdateHUD()
251 m_newHUDUpdates.fetchAndAddRelaxed(1);
255 void AbstractScopeWidget::forceUpdateScope()
257 m_newScopeUpdates.fetchAndAddRelaxed(1);
258 m_requestForcedUpdate = true;
262 void AbstractScopeWidget::forceUpdateBackground()
264 m_newBackgroundUpdates.fetchAndAddRelaxed(1);
265 prodBackgroundThread();
273 void AbstractScopeWidget::resizeEvent(QResizeEvent *event)
275 // Update the dimension of the available rect for painting
276 m_scopeRect = scopeRect();
279 QWidget::resizeEvent(event);
282 void AbstractScopeWidget::showEvent(QShowEvent *event)
284 QWidget::showEvent(event);
285 m_scopeRect = scopeRect();
288 void AbstractScopeWidget::paintEvent(QPaintEvent *)
290 QPainter davinci(this);
291 davinci.drawImage(m_scopeRect.topLeft(), m_imgBackground);
292 davinci.drawImage(m_scopeRect.topLeft(), m_imgScope);
293 davinci.drawImage(m_scopeRect.topLeft(), m_imgHUD);
296 void AbstractScopeWidget::mousePressEvent(QMouseEvent *event)
298 if (event->button() == Qt::LeftButton) {
299 // Rescaling mode starts
300 m_rescaleActive = true;
301 m_rescalePropertiesLocked = false;
302 m_rescaleFirstRescaleDone = false;
303 m_rescaleStartPoint = event->pos();
304 m_rescaleModifiers = event->modifiers();
307 void AbstractScopeWidget::mouseReleaseEvent(QMouseEvent *event)
309 m_rescaleActive = false;
310 m_rescalePropertiesLocked = false;
312 if (!m_aAutoRefresh->isChecked()) {
313 m_requestForcedUpdate = true;
317 prodBackgroundThread();
318 QWidget::mouseReleaseEvent(event);
320 void AbstractScopeWidget::mouseMoveEvent(QMouseEvent *event)
322 m_mousePos = event->pos();
323 m_mouseWithinWidget = true;
324 emit signalMousePositionChanged();
326 QPoint movement = event->pos()-m_rescaleStartPoint;
328 if (m_rescaleActive) {
329 if (m_rescalePropertiesLocked) {
330 // Direction is known, now adjust parameters
332 // Reset the starting point to make the next moveEvent relative to the current one
333 m_rescaleStartPoint = event->pos();
336 if (!m_rescaleFirstRescaleDone) {
337 // We have just learned the desired direction; Normalize the movement to one pixel
338 // to avoid a jump by m_rescaleMinDist
340 if (movement.x() != 0) {
341 movement.setX(movement.x() / abs(movement.x()));
343 if (movement.y() != 0) {
344 movement.setY(movement.y() / abs(movement.y()));
347 m_rescaleFirstRescaleDone = true;
350 handleMouseDrag(movement, m_rescaleDirection, m_rescaleModifiers);
355 // Detect the movement direction here.
356 // This algorithm relies on the aspect ratio of dy/dx (size and signum).
357 if (movement.manhattanLength() > m_rescaleMinDist) {
358 float diff = ((float) movement.y())/movement.x();
360 if (abs(diff) > m_rescaleVerticalThreshold || movement.x() == 0) {
361 m_rescaleDirection = North;
362 } else if (abs(diff) < 1/m_rescaleVerticalThreshold) {
363 m_rescaleDirection = East;
364 } else if (diff < 0) {
365 m_rescaleDirection = Northeast;
367 m_rescaleDirection = Southeast;
370 qDebug() << "Diff is " << diff << "; chose " << directions[m_rescaleDirection] << " as direction";
372 m_rescalePropertiesLocked = true;
378 void AbstractScopeWidget::leaveEvent(QEvent *)
380 m_mouseWithinWidget = false;
381 emit signalMousePositionChanged();
384 void AbstractScopeWidget::customContextMenuRequested(const QPoint &pos)
386 m_menu->exec(this->mapToGlobal(pos));
389 uint AbstractScopeWidget::calculateAccelFactorHUD(uint oldMseconds, uint)
391 return ceil((float)oldMseconds*REALTIME_FPS / 1000);
393 uint AbstractScopeWidget::calculateAccelFactorScope(uint oldMseconds, uint)
395 return ceil((float)oldMseconds*REALTIME_FPS / 1000);
397 uint AbstractScopeWidget::calculateAccelFactorBackground(uint oldMseconds, uint)
399 return ceil((float)oldMseconds*REALTIME_FPS / 1000);
405 void AbstractScopeWidget::slotHUDRenderingFinished(uint mseconds, uint oldFactor)
408 qDebug() << "HUD rendering has finished in " << mseconds << " ms, waiting for termination in " << m_widgetName;
410 m_threadHUD.waitForFinished();
411 m_imgHUD = m_threadHUD.result();
413 m_semaphoreHUD.release(1);
417 if (m_aRealtime->isChecked()) {
418 accel = calculateAccelFactorHUD(mseconds, oldFactor);
419 if (m_accelFactorHUD < 1) {
422 m_accelFactorHUD = accel;
425 if ((m_newHUDFrames > 0 && m_aAutoRefresh->isChecked()) || m_newHUDUpdates > 0) {
427 qDebug() << "Trying to start a new HUD thread for " << m_widgetName
428 << ". New frames/updates: " << m_newHUDFrames << "/" << m_newHUDUpdates;
434 void AbstractScopeWidget::slotScopeRenderingFinished(uint mseconds, uint oldFactor)
436 // The signal can be received before the thread has really finished. So we
437 // need to wait until it has really finished before starting a new thread.
439 qDebug() << "Scope rendering has finished in " << mseconds << " ms, waiting for termination in " << m_widgetName;
441 m_threadScope.waitForFinished();
442 m_imgScope = m_threadScope.result();
444 // The scope thread has finished. Now we can release the semaphore, allowing a new thread.
445 // See prodScopeThread where the semaphore is acquired again.
446 m_semaphoreScope.release(1);
449 // Calculate the acceleration factor hint to get «realtime» updates.
451 if (m_aRealtime->isChecked()) {
452 accel = calculateAccelFactorScope(mseconds, oldFactor);
454 // If mseconds happens to be 0.
457 // Don't directly calculate with m_accelFactorScope as we are dealing with concurrency.
458 // If m_accelFactorScope is set to 0 at the wrong moment, who knows what might happen
459 // then :) Therefore use a local variable.
460 m_accelFactorScope = accel;
463 if ((m_newScopeFrames > 0 && m_aAutoRefresh->isChecked()) || m_newScopeUpdates > 0) {
465 qDebug() << "Trying to start a new scope thread for " << m_widgetName
466 << ". New frames/updates: " << m_newScopeFrames << "/" << m_newScopeUpdates;
472 void AbstractScopeWidget::slotBackgroundRenderingFinished(uint mseconds, uint oldFactor)
475 qDebug() << "Background rendering has finished in " << mseconds << " ms, waiting for termination in " << m_widgetName;
477 m_threadBackground.waitForFinished();
478 m_imgBackground = m_threadBackground.result();
480 m_semaphoreBackground.release(1);
484 if (m_aRealtime->isChecked()) {
485 accel = calculateAccelFactorBackground(mseconds, oldFactor);
486 if (m_accelFactorBackground < 1) {
489 m_accelFactorBackground = accel;
492 if ((m_newBackgroundFrames > 0 && m_aAutoRefresh->isChecked()) || m_newBackgroundUpdates > 0) {
494 qDebug() << "Trying to start a new background thread for " << m_widgetName
495 << ". New frames/updates: " << m_newBackgroundFrames << "/" << m_newBackgroundUpdates;
497 prodBackgroundThread();;
501 void AbstractScopeWidget::slotRenderZoneUpdated()
503 m_newHUDFrames.fetchAndAddRelaxed(1);
504 m_newScopeFrames.fetchAndAddRelaxed(1);
505 m_newBackgroundFrames.fetchAndAddRelaxed(1);
508 qDebug() << "Data incoming at " << widgetName() << ". New frames total HUD/Scope/Background: " << m_newHUDFrames
509 << "/" << m_newScopeFrames << "/" << m_newBackgroundFrames;
512 if (this->visibleRegion().isEmpty()) {
514 qDebug() << "Scope of widget " << m_widgetName << " is not at the top, not rendering.";
517 if (m_aAutoRefresh->isChecked()) {
520 prodBackgroundThread();
525 void AbstractScopeWidget::slotResetRealtimeFactor(bool realtimeChecked)
527 if (!realtimeChecked) {
528 m_accelFactorHUD = 1;
529 m_accelFactorScope = 1;
530 m_accelFactorBackground = 1;
534 bool AbstractScopeWidget::autoRefreshEnabled()
536 return m_aAutoRefresh->isChecked();
539 void AbstractScopeWidget::slotAutoRefreshToggled(bool autoRefresh)
542 qDebug() << "Auto-refresh switched to " << autoRefresh << " in " << widgetName()
543 << " (Visible: " << isVisible() << "/" << this->visibleRegion().isEmpty() << ")";
546 // Notify listeners whether we accept new frames now
547 emit requestAutoRefresh(autoRefresh);
549 // TODO only if depends on input
552 m_requestForcedUpdate = true;
556 void AbstractScopeWidget::handleMouseDrag(const QPoint &, const RescaleDirection, const Qt::KeyboardModifiers) { }