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);
35 const QColor AbstractScopeWidget::colHighlightLight(18, 130, 255, 255);
36 const QColor AbstractScopeWidget::colHighlightDark(255, 64, 19, 255);
37 const QColor AbstractScopeWidget::colDarkWhite(250, 250, 250);
39 const QPen AbstractScopeWidget::penThick(QBrush(AbstractScopeWidget::colDarkWhite.rgb()), 2, Qt::SolidLine);
40 const QPen AbstractScopeWidget::penThin(QBrush(AbstractScopeWidget::colDarkWhite.rgb()), 1, Qt::SolidLine);
41 const QPen AbstractScopeWidget::penLight(QBrush(QColor(200, 200, 250, 150)), 1, Qt::SolidLine);
42 const QPen AbstractScopeWidget::penLightDots(QBrush(QColor(200, 200, 250, 150)), 1, Qt::DotLine);
43 const QPen AbstractScopeWidget::penLighter(QBrush(QColor(225, 225, 250, 225)), 1, Qt::SolidLine);
44 const QPen AbstractScopeWidget::penDark(QBrush(QColor(0, 0, 20, 250)), 1, Qt::SolidLine);
45 const QPen AbstractScopeWidget::penDarkDots(QBrush(QColor(0, 0, 20, 250)), 1, Qt::DotLine);
46 const QPen AbstractScopeWidget::penBackground(QBrush(dark2), 1, Qt::SolidLine);
48 const QString AbstractScopeWidget::directions[] = {"North", "Northeast", "East", "Southeast"};
50 AbstractScopeWidget::AbstractScopeWidget(bool trackMouse, QWidget *parent) :
53 m_mouseWithinWidget(false),
56 m_accelFactorScope(1),
57 m_accelFactorBackground(1),
60 m_semaphoreBackground(1),
61 initialDimensionUpdateDone(false),
62 m_requestForcedUpdate(false),
64 m_rescaleVerticalThreshold(2.0f)
67 m_scopePalette = QPalette();
68 m_scopePalette.setBrush(QPalette::Window, QBrush(dark2));
69 m_scopePalette.setBrush(QPalette::Base, QBrush(dark));
70 m_scopePalette.setBrush(QPalette::Button, QBrush(dark));
71 m_scopePalette.setBrush(QPalette::Text, QBrush(light));
72 m_scopePalette.setBrush(QPalette::WindowText, QBrush(light));
73 m_scopePalette.setBrush(QPalette::ButtonText, QBrush(light));
74 this->setPalette(m_scopePalette);
75 this->setAutoFillBackground(true);
77 m_aAutoRefresh = new QAction(i18n("Auto Refresh"), this);
78 m_aAutoRefresh->setCheckable(true);
79 m_aRealtime = new QAction(i18n("Realtime (with precision loss)"), this);
80 m_aRealtime->setCheckable(true);
82 m_menu = new QMenu(this);
83 m_menu->setPalette(m_scopePalette);
84 m_menu->addAction(m_aAutoRefresh);
85 m_menu->addAction(m_aRealtime);
87 this->setContextMenuPolicy(Qt::CustomContextMenu);
90 b &= connect(this, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(customContextMenuRequested(QPoint)));
92 b &= connect(this, SIGNAL(signalHUDRenderingFinished(uint, uint)), this, SLOT(slotHUDRenderingFinished(uint, uint)));
93 b &= connect(this, SIGNAL(signalScopeRenderingFinished(uint, uint)), this, SLOT(slotScopeRenderingFinished(uint, uint)));
94 b &= connect(this, SIGNAL(signalBackgroundRenderingFinished(uint, uint)), this, SLOT(slotBackgroundRenderingFinished(uint, uint)));
95 b &= connect(m_aRealtime, SIGNAL(toggled(bool)), this, SLOT(slotResetRealtimeFactor(bool)));
96 b &= connect(m_aAutoRefresh, SIGNAL(toggled(bool)), this, SLOT(slotAutoRefreshToggled(bool)));
99 // Enable mouse tracking if desired.
100 // Causes the mouseMoved signal to be emitted when the mouse moves inside the
101 // widget, even when no mouse button is pressed.
102 this->setMouseTracking(trackMouse);
105 AbstractScopeWidget::~AbstractScopeWidget()
110 delete m_aAutoRefresh;
114 void AbstractScopeWidget::init()
116 m_widgetName = widgetName();
120 void AbstractScopeWidget::readConfig()
122 KSharedConfigPtr config = KGlobal::config();
123 KConfigGroup scopeConfig(config, configName());
124 m_aAutoRefresh->setChecked(scopeConfig.readEntry("autoRefresh", true));
125 m_aRealtime->setChecked(scopeConfig.readEntry("realtime", false));
129 void AbstractScopeWidget::writeConfig()
131 KSharedConfigPtr config = KGlobal::config();
132 KConfigGroup scopeConfig(config, configName());
133 scopeConfig.writeEntry("autoRefresh", m_aAutoRefresh->isChecked());
134 scopeConfig.writeEntry("realtime", m_aRealtime->isChecked());
138 QString AbstractScopeWidget::configName()
140 return "Scope_" + m_widgetName;
143 void AbstractScopeWidget::prodHUDThread()
145 if (this->visibleRegion().isEmpty()) {
147 qDebug() << "Scope " << m_widgetName << " is not visible. Not calculating HUD.";
150 if (m_semaphoreHUD.tryAcquire(1)) {
151 Q_ASSERT(!m_threadHUD.isRunning());
153 m_newHUDFrames.fetchAndStoreRelaxed(0);
154 m_newHUDUpdates.fetchAndStoreRelaxed(0);
155 m_threadHUD = QtConcurrent::run(this, &AbstractScopeWidget::renderHUD, m_accelFactorHUD);
157 qDebug() << "HUD thread started in " << m_widgetName;
163 qDebug() << "HUD semaphore locked, not prodding in " << m_widgetName << ". Thread running: " << m_threadHUD.isRunning();
169 void AbstractScopeWidget::prodScopeThread()
171 // Only start a new thread if the scope is actually visible
172 // and not hidden by another widget on the stack and if user want the scope to update.
173 if (this->visibleRegion().isEmpty() || (!m_aAutoRefresh->isChecked() && !m_requestForcedUpdate)) {
175 qDebug() << "Scope " << m_widgetName << " is not visible. Not calculating scope.";
178 // Try to acquire the semaphore. This must only succeed if m_threadScope is not running
179 // anymore. Therefore the semaphore must NOT be released before m_threadScope ends.
180 // If acquiring the semaphore fails, the thread is still running.
181 if (m_semaphoreScope.tryAcquire(1)) {
182 Q_ASSERT(!m_threadScope.isRunning());
184 m_newScopeFrames.fetchAndStoreRelaxed(0);
185 m_newScopeUpdates.fetchAndStoreRelaxed(0);
187 Q_ASSERT(m_accelFactorScope > 0);
189 // See http://doc.qt.nokia.com/latest/qtconcurrentrun.html#run about
190 // running member functions in a thread
191 m_threadScope = QtConcurrent::run(this, &AbstractScopeWidget::renderScope, m_accelFactorScope);
192 m_requestForcedUpdate = false;
195 qDebug() << "Scope thread started in " << m_widgetName;
200 qDebug() << "Scope semaphore locked, not prodding in " << m_widgetName << ". Thread running: " << m_threadScope.isRunning();
205 void AbstractScopeWidget::prodBackgroundThread()
207 if (this->visibleRegion().isEmpty()) {
209 qDebug() << "Scope " << m_widgetName << " is not visible. Not calculating background.";
212 if (m_semaphoreBackground.tryAcquire(1)) {
213 Q_ASSERT(!m_threadBackground.isRunning());
215 m_newBackgroundFrames.fetchAndStoreRelaxed(0);
216 m_newBackgroundUpdates.fetchAndStoreRelaxed(0);
217 m_threadBackground = QtConcurrent::run(this, &AbstractScopeWidget::renderBackground, m_accelFactorBackground);
220 qDebug() << "Background thread started in " << m_widgetName;
225 qDebug() << "Background semaphore locked, not prodding in " << m_widgetName << ". Thread running: " << m_threadBackground.isRunning();
231 void AbstractScopeWidget::forceUpdate(bool doUpdate)
234 qDebug() << "Forced update called in " << widgetName() << ". Arg: " << doUpdate;
240 m_requestForcedUpdate = true;
241 m_newHUDUpdates.fetchAndAddRelaxed(1);
242 m_newScopeUpdates.fetchAndAddRelaxed(1);
243 m_newBackgroundUpdates.fetchAndAddRelaxed(1);
246 prodBackgroundThread();
248 void AbstractScopeWidget::forceUpdateHUD()
250 m_newHUDUpdates.fetchAndAddRelaxed(1);
254 void AbstractScopeWidget::forceUpdateScope()
256 m_newScopeUpdates.fetchAndAddRelaxed(1);
257 m_requestForcedUpdate = true;
261 void AbstractScopeWidget::forceUpdateBackground()
263 m_newBackgroundUpdates.fetchAndAddRelaxed(1);
264 prodBackgroundThread();
272 void AbstractScopeWidget::resizeEvent(QResizeEvent *event)
274 // Update the dimension of the available rect for painting
275 m_scopeRect = scopeRect();
278 QWidget::resizeEvent(event);
281 void AbstractScopeWidget::showEvent(QShowEvent *event)
283 QWidget::showEvent(event);
284 m_scopeRect = scopeRect();
287 void AbstractScopeWidget::paintEvent(QPaintEvent *)
289 QPainter davinci(this);
290 davinci.drawImage(m_scopeRect.topLeft(), m_imgBackground);
291 davinci.drawImage(m_scopeRect.topLeft(), m_imgScope);
292 davinci.drawImage(m_scopeRect.topLeft(), m_imgHUD);
295 void AbstractScopeWidget::mousePressEvent(QMouseEvent *event)
297 if (event->button() == Qt::LeftButton) {
298 // Rescaling mode starts
299 m_rescaleActive = true;
300 m_rescalePropertiesLocked = false;
301 m_rescaleFirstRescaleDone = false;
302 m_rescaleStartPoint = event->pos();
303 m_rescaleModifiers = event->modifiers();
306 void AbstractScopeWidget::mouseReleaseEvent(QMouseEvent *event)
308 m_rescaleActive = false;
309 m_rescalePropertiesLocked = false;
311 if (!m_aAutoRefresh->isChecked()) {
312 m_requestForcedUpdate = true;
316 prodBackgroundThread();
317 QWidget::mouseReleaseEvent(event);
319 void AbstractScopeWidget::mouseMoveEvent(QMouseEvent *event)
321 m_mousePos = event->pos();
322 m_mouseWithinWidget = true;
323 emit signalMousePositionChanged();
325 QPoint movement = event->pos()-m_rescaleStartPoint;
327 if (m_rescaleActive) {
328 if (m_rescalePropertiesLocked) {
329 // Direction is known, now adjust parameters
331 // Reset the starting point to make the next moveEvent relative to the current one
332 m_rescaleStartPoint = event->pos();
335 if (!m_rescaleFirstRescaleDone) {
336 // We have just learned the desired direction; Normalize the movement to one pixel
337 // to avoid a jump by m_rescaleMinDist
339 if (movement.x() != 0) {
340 movement.setX(movement.x() / abs(movement.x()));
342 if (movement.y() != 0) {
343 movement.setY(movement.y() / abs(movement.y()));
346 m_rescaleFirstRescaleDone = true;
349 handleMouseDrag(movement, m_rescaleDirection, m_rescaleModifiers);
354 // Detect the movement direction here.
355 // This algorithm relies on the aspect ratio of dy/dx (size and signum).
356 if (movement.manhattanLength() > m_rescaleMinDist) {
357 float diff = ((float) movement.y())/movement.x();
359 if (abs(diff) > m_rescaleVerticalThreshold || movement.x() == 0) {
360 m_rescaleDirection = North;
361 } else if (abs(diff) < 1/m_rescaleVerticalThreshold) {
362 m_rescaleDirection = East;
363 } else if (diff < 0) {
364 m_rescaleDirection = Northeast;
366 m_rescaleDirection = Southeast;
369 qDebug() << "Diff is " << diff << "; chose " << directions[m_rescaleDirection] << " as direction";
371 m_rescalePropertiesLocked = true;
377 void AbstractScopeWidget::leaveEvent(QEvent *)
379 m_mouseWithinWidget = false;
380 emit signalMousePositionChanged();
383 void AbstractScopeWidget::customContextMenuRequested(const QPoint &pos)
385 m_menu->exec(this->mapToGlobal(pos));
388 uint AbstractScopeWidget::calculateAccelFactorHUD(uint oldMseconds, uint)
390 return ceil((float)oldMseconds*REALTIME_FPS / 1000);
392 uint AbstractScopeWidget::calculateAccelFactorScope(uint oldMseconds, uint)
394 return ceil((float)oldMseconds*REALTIME_FPS / 1000);
396 uint AbstractScopeWidget::calculateAccelFactorBackground(uint oldMseconds, uint)
398 return ceil((float)oldMseconds*REALTIME_FPS / 1000);
404 void AbstractScopeWidget::slotHUDRenderingFinished(uint mseconds, uint oldFactor)
407 qDebug() << "HUD rendering has finished in " << mseconds << " ms, waiting for termination in " << m_widgetName;
409 m_threadHUD.waitForFinished();
410 m_imgHUD = m_threadHUD.result();
412 m_semaphoreHUD.release(1);
416 if (m_aRealtime->isChecked()) {
417 accel = calculateAccelFactorHUD(mseconds, oldFactor);
418 if (m_accelFactorHUD < 1) {
421 m_accelFactorHUD = accel;
424 if ((m_newHUDFrames > 0 && m_aAutoRefresh->isChecked()) || m_newHUDUpdates > 0) {
426 qDebug() << "Trying to start a new HUD thread for " << m_widgetName
427 << ". New frames/updates: " << m_newHUDFrames << "/" << m_newHUDUpdates;
433 void AbstractScopeWidget::slotScopeRenderingFinished(uint mseconds, uint oldFactor)
435 // The signal can be received before the thread has really finished. So we
436 // need to wait until it has really finished before starting a new thread.
438 qDebug() << "Scope rendering has finished in " << mseconds << " ms, waiting for termination in " << m_widgetName;
440 m_threadScope.waitForFinished();
441 m_imgScope = m_threadScope.result();
443 // The scope thread has finished. Now we can release the semaphore, allowing a new thread.
444 // See prodScopeThread where the semaphore is acquired again.
445 m_semaphoreScope.release(1);
448 // Calculate the acceleration factor hint to get «realtime» updates.
450 if (m_aRealtime->isChecked()) {
451 accel = calculateAccelFactorScope(mseconds, oldFactor);
453 // If mseconds happens to be 0.
456 // Don't directly calculate with m_accelFactorScope as we are dealing with concurrency.
457 // If m_accelFactorScope is set to 0 at the wrong moment, who knows what might happen
458 // then :) Therefore use a local variable.
459 m_accelFactorScope = accel;
462 if ((m_newScopeFrames > 0 && m_aAutoRefresh->isChecked()) || m_newScopeUpdates > 0) {
464 qDebug() << "Trying to start a new scope thread for " << m_widgetName
465 << ". New frames/updates: " << m_newScopeFrames << "/" << m_newScopeUpdates;
471 void AbstractScopeWidget::slotBackgroundRenderingFinished(uint mseconds, uint oldFactor)
474 qDebug() << "Background rendering has finished in " << mseconds << " ms, waiting for termination in " << m_widgetName;
476 m_threadBackground.waitForFinished();
477 m_imgBackground = m_threadBackground.result();
479 m_semaphoreBackground.release(1);
483 if (m_aRealtime->isChecked()) {
484 accel = calculateAccelFactorBackground(mseconds, oldFactor);
485 if (m_accelFactorBackground < 1) {
488 m_accelFactorBackground = accel;
491 if ((m_newBackgroundFrames > 0 && m_aAutoRefresh->isChecked()) || m_newBackgroundUpdates > 0) {
493 qDebug() << "Trying to start a new background thread for " << m_widgetName
494 << ". New frames/updates: " << m_newBackgroundFrames << "/" << m_newBackgroundUpdates;
496 prodBackgroundThread();;
500 void AbstractScopeWidget::slotRenderZoneUpdated()
502 m_newHUDFrames.fetchAndAddRelaxed(1);
503 m_newScopeFrames.fetchAndAddRelaxed(1);
504 m_newBackgroundFrames.fetchAndAddRelaxed(1);
507 qDebug() << "Data incoming at " << widgetName() << ". New frames total HUD/Scope/Background: " << m_newHUDFrames
508 << "/" << m_newScopeFrames << "/" << m_newBackgroundFrames;
511 if (this->visibleRegion().isEmpty()) {
513 qDebug() << "Scope of widget " << m_widgetName << " is not at the top, not rendering.";
516 if (m_aAutoRefresh->isChecked()) {
519 prodBackgroundThread();
524 void AbstractScopeWidget::slotResetRealtimeFactor(bool realtimeChecked)
526 if (!realtimeChecked) {
527 m_accelFactorHUD = 1;
528 m_accelFactorScope = 1;
529 m_accelFactorBackground = 1;
533 bool AbstractScopeWidget::autoRefreshEnabled()
535 return m_aAutoRefresh->isChecked();
538 void AbstractScopeWidget::slotAutoRefreshToggled(bool autoRefresh)
541 qDebug() << "Auto-refresh switched to " << autoRefresh << " in " << widgetName()
542 << " (Visible: " << isVisible() << "/" << this->visibleRegion().isEmpty() << ")";
545 // Notify listeners whether we accept new frames now
546 emit requestAutoRefresh(autoRefresh);
548 // TODO only if depends on input
551 m_requestForcedUpdate = true;
555 void AbstractScopeWidget::handleMouseDrag(const QPoint, const RescaleDirection, const Qt::KeyboardModifiers) { }