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 "QtCore/qtconcurrentrun.h"
13 #include "abstractscopewidget.h"
19 #include <QMouseEvent>
22 #include <KConfigGroup>
24 #include <KSharedConfig>
26 // Uncomment for Scope debugging.
33 const int REALTIME_FPS = 30;
35 const QColor light(250, 238, 226, 255);
36 const QColor dark(40, 40, 39, 255);
37 const QColor dark2(25, 25, 23, 255);
38 const QColor AbstractScopeWidget::colHighlightLight(18, 130, 255, 255);
39 const QColor AbstractScopeWidget::colHighlightDark(255, 64, 19, 255);
40 const QColor AbstractScopeWidget::colDarkWhite(250, 250, 250);
42 const QPen AbstractScopeWidget::penThick(QBrush(AbstractScopeWidget::colDarkWhite.rgb()), 2, Qt::SolidLine);
43 const QPen AbstractScopeWidget::penThin(QBrush(AbstractScopeWidget::colDarkWhite.rgb()), 1, Qt::SolidLine);
44 const QPen AbstractScopeWidget::penLight(QBrush(QColor(200, 200, 250, 150)), 1, Qt::SolidLine);
45 const QPen AbstractScopeWidget::penLightDots(QBrush(QColor(200, 200, 250, 150)), 1, Qt::DotLine);
46 const QPen AbstractScopeWidget::penLighter(QBrush(QColor(225, 225, 250, 225)), 1, Qt::SolidLine);
47 const QPen AbstractScopeWidget::penDark(QBrush(QColor(0, 0, 20, 250)), 1, Qt::SolidLine);
48 const QPen AbstractScopeWidget::penDarkDots(QBrush(QColor(0, 0, 20, 250)), 1, Qt::DotLine);
49 const QPen AbstractScopeWidget::penBackground(QBrush(dark2), 1, Qt::SolidLine);
51 const QString AbstractScopeWidget::directions[] = {"North", "Northeast", "East", "Southeast"};
53 AbstractScopeWidget::AbstractScopeWidget(bool trackMouse, QWidget *parent) :
56 , m_mouseWithinWidget(false)
59 , m_accelFactorScope(1)
60 , m_accelFactorBackground(1)
63 , m_semaphoreBackground(1)
64 , initialDimensionUpdateDone(false)
65 , m_requestForcedUpdate(false)
67 , m_rescaleVerticalThreshold(2.0f)
68 , m_rescaleActive(false)
69 , m_rescalePropertiesLocked(false)
70 , m_rescaleFirstRescaleDone(true)
71 , m_rescaleDirection(North)
74 m_scopePalette = QPalette();
75 m_scopePalette.setBrush(QPalette::Window, QBrush(dark2));
76 m_scopePalette.setBrush(QPalette::Base, QBrush(dark));
77 m_scopePalette.setBrush(QPalette::Button, QBrush(dark));
78 m_scopePalette.setBrush(QPalette::Text, QBrush(light));
79 m_scopePalette.setBrush(QPalette::WindowText, QBrush(light));
80 m_scopePalette.setBrush(QPalette::ButtonText, QBrush(light));
81 this->setPalette(m_scopePalette);
82 this->setAutoFillBackground(true);
84 m_aAutoRefresh = new QAction(i18n("Auto Refresh"), this);
85 m_aAutoRefresh->setCheckable(true);
86 m_aRealtime = new QAction(i18n("Realtime (with precision loss)"), this);
87 m_aRealtime->setCheckable(true);
89 m_menu = new QMenu(this);
90 // Disabled dark palette on menus since it breaks up with some themes: kdenlive issue #2950
91 //m_menu->setPalette(m_scopePalette);
92 m_menu->addAction(m_aAutoRefresh);
93 m_menu->addAction(m_aRealtime);
95 this->setContextMenuPolicy(Qt::CustomContextMenu);
98 b &= connect(this, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(customContextMenuRequested(QPoint)));
100 b &= connect(this, SIGNAL(signalHUDRenderingFinished(uint,uint)), this, SLOT(slotHUDRenderingFinished(uint,uint)));
101 b &= connect(this, SIGNAL(signalScopeRenderingFinished(uint,uint)), this, SLOT(slotScopeRenderingFinished(uint,uint)));
102 b &= connect(this, SIGNAL(signalBackgroundRenderingFinished(uint,uint)), this, SLOT(slotBackgroundRenderingFinished(uint,uint)));
103 b &= connect(m_aRealtime, SIGNAL(toggled(bool)), this, SLOT(slotResetRealtimeFactor(bool)));
104 b &= connect(m_aAutoRefresh, SIGNAL(toggled(bool)), this, SLOT(slotAutoRefreshToggled(bool)));
107 // Enable mouse tracking if desired.
108 // Causes the mouseMoved signal to be emitted when the mouse moves inside the
109 // widget, even when no mouse button is pressed.
110 this->setMouseTracking(trackMouse);
113 AbstractScopeWidget::~AbstractScopeWidget()
118 delete m_aAutoRefresh;
122 void AbstractScopeWidget::init()
124 m_widgetName = widgetName();
128 void AbstractScopeWidget::readConfig()
130 KSharedConfigPtr config = KGlobal::config();
131 KConfigGroup scopeConfig(config, configName());
132 m_aAutoRefresh->setChecked(scopeConfig.readEntry("autoRefresh", true));
133 m_aRealtime->setChecked(scopeConfig.readEntry("realtime", false));
137 void AbstractScopeWidget::writeConfig()
139 KSharedConfigPtr config = KGlobal::config();
140 KConfigGroup scopeConfig(config, configName());
141 scopeConfig.writeEntry("autoRefresh", m_aAutoRefresh->isChecked());
142 scopeConfig.writeEntry("realtime", m_aRealtime->isChecked());
146 QString AbstractScopeWidget::configName()
148 return "Scope_" + m_widgetName;
151 void AbstractScopeWidget::prodHUDThread()
153 if (this->visibleRegion().isEmpty()) {
155 qDebug() << "Scope " << m_widgetName << " is not visible. Not calculating HUD.";
158 if (m_semaphoreHUD.tryAcquire(1)) {
159 Q_ASSERT(!m_threadHUD.isRunning());
161 m_newHUDFrames.fetchAndStoreRelaxed(0);
162 m_newHUDUpdates.fetchAndStoreRelaxed(0);
163 m_threadHUD = QtConcurrent::run(this, &AbstractScopeWidget::renderHUD, m_accelFactorHUD);
165 qDebug() << "HUD thread started in " << m_widgetName;
171 qDebug() << "HUD semaphore locked, not prodding in " << m_widgetName << ". Thread running: " << m_threadHUD.isRunning();
177 void AbstractScopeWidget::prodScopeThread()
179 // Only start a new thread if the scope is actually visible
180 // and not hidden by another widget on the stack and if user want the scope to update.
181 if (this->visibleRegion().isEmpty() || (!m_aAutoRefresh->isChecked() && !m_requestForcedUpdate)) {
183 qDebug() << "Scope " << m_widgetName << " is not visible. Not calculating scope.";
186 // Try to acquire the semaphore. This must only succeed if m_threadScope is not running
187 // anymore. Therefore the semaphore must NOT be released before m_threadScope ends.
188 // If acquiring the semaphore fails, the thread is still running.
189 if (m_semaphoreScope.tryAcquire(1)) {
190 Q_ASSERT(!m_threadScope.isRunning());
192 m_newScopeFrames.fetchAndStoreRelaxed(0);
193 m_newScopeUpdates.fetchAndStoreRelaxed(0);
195 Q_ASSERT(m_accelFactorScope > 0);
197 // See http://doc.qt.nokia.com/latest/qtconcurrentrun.html#run about
198 // running member functions in a thread
199 m_threadScope = QtConcurrent::run(this, &AbstractScopeWidget::renderScope, m_accelFactorScope);
200 m_requestForcedUpdate = false;
203 qDebug() << "Scope thread started in " << m_widgetName;
208 qDebug() << "Scope semaphore locked, not prodding in " << m_widgetName << ". Thread running: " << m_threadScope.isRunning();
213 void AbstractScopeWidget::prodBackgroundThread()
215 if (this->visibleRegion().isEmpty()) {
217 qDebug() << "Scope " << m_widgetName << " is not visible. Not calculating background.";
220 if (m_semaphoreBackground.tryAcquire(1)) {
221 Q_ASSERT(!m_threadBackground.isRunning());
223 m_newBackgroundFrames.fetchAndStoreRelaxed(0);
224 m_newBackgroundUpdates.fetchAndStoreRelaxed(0);
225 m_threadBackground = QtConcurrent::run(this, &AbstractScopeWidget::renderBackground, m_accelFactorBackground);
228 qDebug() << "Background thread started in " << m_widgetName;
233 qDebug() << "Background semaphore locked, not prodding in " << m_widgetName << ". Thread running: " << m_threadBackground.isRunning();
239 void AbstractScopeWidget::forceUpdate(bool doUpdate)
242 qDebug() << "Forced update called in " << widgetName() << ". Arg: " << doUpdate;
248 m_requestForcedUpdate = true;
249 m_newHUDUpdates.fetchAndAddRelaxed(1);
250 m_newScopeUpdates.fetchAndAddRelaxed(1);
251 m_newBackgroundUpdates.fetchAndAddRelaxed(1);
254 prodBackgroundThread();
256 void AbstractScopeWidget::forceUpdateHUD()
258 m_newHUDUpdates.fetchAndAddRelaxed(1);
262 void AbstractScopeWidget::forceUpdateScope()
264 m_newScopeUpdates.fetchAndAddRelaxed(1);
265 m_requestForcedUpdate = true;
269 void AbstractScopeWidget::forceUpdateBackground()
271 m_newBackgroundUpdates.fetchAndAddRelaxed(1);
272 prodBackgroundThread();
280 void AbstractScopeWidget::resizeEvent(QResizeEvent *event)
282 // Update the dimension of the available rect for painting
283 m_scopeRect = scopeRect();
286 QWidget::resizeEvent(event);
289 void AbstractScopeWidget::showEvent(QShowEvent *event)
291 QWidget::showEvent(event);
292 m_scopeRect = scopeRect();
295 void AbstractScopeWidget::paintEvent(QPaintEvent *)
297 QPainter davinci(this);
298 davinci.drawImage(m_scopeRect.topLeft(), m_imgBackground);
299 davinci.drawImage(m_scopeRect.topLeft(), m_imgScope);
300 davinci.drawImage(m_scopeRect.topLeft(), m_imgHUD);
303 void AbstractScopeWidget::mousePressEvent(QMouseEvent *event)
305 if (event->button() == Qt::LeftButton) {
306 // Rescaling mode starts
307 m_rescaleActive = true;
308 m_rescalePropertiesLocked = false;
309 m_rescaleFirstRescaleDone = false;
310 m_rescaleStartPoint = event->pos();
311 m_rescaleModifiers = event->modifiers();
314 void AbstractScopeWidget::mouseReleaseEvent(QMouseEvent *event)
316 m_rescaleActive = false;
317 m_rescalePropertiesLocked = false;
319 if (!m_aAutoRefresh->isChecked()) {
320 m_requestForcedUpdate = true;
324 prodBackgroundThread();
325 QWidget::mouseReleaseEvent(event);
327 void AbstractScopeWidget::mouseMoveEvent(QMouseEvent *event)
329 m_mousePos = event->pos();
330 m_mouseWithinWidget = true;
331 emit signalMousePositionChanged();
333 QPoint movement = event->pos()-m_rescaleStartPoint;
335 if (m_rescaleActive) {
336 if (m_rescalePropertiesLocked) {
337 // Direction is known, now adjust parameters
339 // Reset the starting point to make the next moveEvent relative to the current one
340 m_rescaleStartPoint = event->pos();
343 if (!m_rescaleFirstRescaleDone) {
344 // We have just learned the desired direction; Normalize the movement to one pixel
345 // to avoid a jump by m_rescaleMinDist
347 if (movement.x() != 0) {
348 movement.setX(movement.x() / abs(movement.x()));
350 if (movement.y() != 0) {
351 movement.setY(movement.y() / abs(movement.y()));
354 m_rescaleFirstRescaleDone = true;
357 handleMouseDrag(movement, m_rescaleDirection, m_rescaleModifiers);
362 // Detect the movement direction here.
363 // This algorithm relies on the aspect ratio of dy/dx (size and signum).
364 if (movement.manhattanLength() > m_rescaleMinDist) {
365 float diff = ((float) movement.y())/movement.x();
367 if (abs(diff) > m_rescaleVerticalThreshold || movement.x() == 0) {
368 m_rescaleDirection = North;
369 } else if (abs(diff) < 1/m_rescaleVerticalThreshold) {
370 m_rescaleDirection = East;
371 } else if (diff < 0) {
372 m_rescaleDirection = Northeast;
374 m_rescaleDirection = Southeast;
377 qDebug() << "Diff is " << diff << "; chose " << directions[m_rescaleDirection] << " as direction";
379 m_rescalePropertiesLocked = true;
385 void AbstractScopeWidget::leaveEvent(QEvent *)
387 m_mouseWithinWidget = false;
388 emit signalMousePositionChanged();
391 void AbstractScopeWidget::customContextMenuRequested(const QPoint &pos)
393 m_menu->exec(this->mapToGlobal(pos));
396 uint AbstractScopeWidget::calculateAccelFactorHUD(uint oldMseconds, uint)
398 return ceil((float)oldMseconds*REALTIME_FPS / 1000);
400 uint AbstractScopeWidget::calculateAccelFactorScope(uint oldMseconds, uint)
402 return ceil((float)oldMseconds*REALTIME_FPS / 1000);
404 uint AbstractScopeWidget::calculateAccelFactorBackground(uint oldMseconds, uint)
406 return ceil((float)oldMseconds*REALTIME_FPS / 1000);
412 void AbstractScopeWidget::slotHUDRenderingFinished(uint mseconds, uint oldFactor)
415 qDebug() << "HUD rendering has finished in " << mseconds << " ms, waiting for termination in " << m_widgetName;
417 m_threadHUD.waitForFinished();
418 m_imgHUD = m_threadHUD.result();
420 m_semaphoreHUD.release(1);
424 if (m_aRealtime->isChecked()) {
425 accel = calculateAccelFactorHUD(mseconds, oldFactor);
426 if (m_accelFactorHUD < 1) {
429 m_accelFactorHUD = accel;
432 if ((m_newHUDFrames > 0 && m_aAutoRefresh->isChecked()) || m_newHUDUpdates > 0) {
434 qDebug() << "Trying to start a new HUD thread for " << m_widgetName
435 << ". New frames/updates: " << m_newHUDFrames << "/" << m_newHUDUpdates;
441 void AbstractScopeWidget::slotScopeRenderingFinished(uint mseconds, uint oldFactor)
443 // The signal can be received before the thread has really finished. So we
444 // need to wait until it has really finished before starting a new thread.
446 qDebug() << "Scope rendering has finished in " << mseconds << " ms, waiting for termination in " << m_widgetName;
448 m_threadScope.waitForFinished();
449 m_imgScope = m_threadScope.result();
451 // The scope thread has finished. Now we can release the semaphore, allowing a new thread.
452 // See prodScopeThread where the semaphore is acquired again.
453 m_semaphoreScope.release(1);
456 // Calculate the acceleration factor hint to get «realtime» updates.
458 if (m_aRealtime->isChecked()) {
459 accel = calculateAccelFactorScope(mseconds, oldFactor);
461 // If mseconds happens to be 0.
464 // Don't directly calculate with m_accelFactorScope as we are dealing with concurrency.
465 // If m_accelFactorScope is set to 0 at the wrong moment, who knows what might happen
466 // then :) Therefore use a local variable.
467 m_accelFactorScope = accel;
470 if ((m_newScopeFrames > 0 && m_aAutoRefresh->isChecked()) || m_newScopeUpdates > 0) {
472 qDebug() << "Trying to start a new scope thread for " << m_widgetName
473 << ". New frames/updates: " << m_newScopeFrames << "/" << m_newScopeUpdates;
479 void AbstractScopeWidget::slotBackgroundRenderingFinished(uint mseconds, uint oldFactor)
482 qDebug() << "Background rendering has finished in " << mseconds << " ms, waiting for termination in " << m_widgetName;
484 m_threadBackground.waitForFinished();
485 m_imgBackground = m_threadBackground.result();
487 m_semaphoreBackground.release(1);
491 if (m_aRealtime->isChecked()) {
492 accel = calculateAccelFactorBackground(mseconds, oldFactor);
493 if (m_accelFactorBackground < 1) {
496 m_accelFactorBackground = accel;
499 if ((m_newBackgroundFrames > 0 && m_aAutoRefresh->isChecked()) || m_newBackgroundUpdates > 0) {
501 qDebug() << "Trying to start a new background thread for " << m_widgetName
502 << ". New frames/updates: " << m_newBackgroundFrames << "/" << m_newBackgroundUpdates;
504 prodBackgroundThread();;
508 void AbstractScopeWidget::slotRenderZoneUpdated()
510 m_newHUDFrames.fetchAndAddRelaxed(1);
511 m_newScopeFrames.fetchAndAddRelaxed(1);
512 m_newBackgroundFrames.fetchAndAddRelaxed(1);
515 qDebug() << "Data incoming at " << widgetName() << ". New frames total HUD/Scope/Background: " << m_newHUDFrames
516 << "/" << m_newScopeFrames << "/" << m_newBackgroundFrames;
519 if (this->visibleRegion().isEmpty()) {
521 qDebug() << "Scope of widget " << m_widgetName << " is not at the top, not rendering.";
524 if (m_aAutoRefresh->isChecked()) {
527 prodBackgroundThread();
532 void AbstractScopeWidget::slotResetRealtimeFactor(bool realtimeChecked)
534 if (!realtimeChecked) {
535 m_accelFactorHUD = 1;
536 m_accelFactorScope = 1;
537 m_accelFactorBackground = 1;
541 bool AbstractScopeWidget::autoRefreshEnabled() const
543 return m_aAutoRefresh->isChecked();
546 void AbstractScopeWidget::slotAutoRefreshToggled(bool autoRefresh)
549 qDebug() << "Auto-refresh switched to " << autoRefresh << " in " << widgetName()
550 << " (Visible: " << isVisible() << "/" << this->visibleRegion().isEmpty() << ")";
553 // Notify listeners whether we accept new frames now
554 emit requestAutoRefresh(autoRefresh);
556 // TODO only if depends on input
559 m_requestForcedUpdate = true;
563 void AbstractScopeWidget::handleMouseDrag(const QPoint &, const RescaleDirection, const Qt::KeyboardModifiers) { }
570 #include "abstractscopewidget.moc"