]> git.sesse.net Git - kdenlive/blob - src/abstractscopewidget.cpp
Abstract Scopes:
[kdenlive] / src / abstractscopewidget.cpp
1 /***************************************************************************
2  *   Copyright (C) 2010 by Simon Andreas Eugster (simon.eu@gmail.com)      *
3  *   This file is part of kdenlive. See www.kdenlive.org.                  *
4  *                                                                         *
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  ***************************************************************************/
10
11 #include "qtconcurrentrun.h"
12
13 #include "abstractscopewidget.h"
14 #include "renderer.h"
15 #include "monitor.h"
16
17 #include <QFuture>
18 #include <QColor>
19 #include <QMenu>
20 #include <QMouseEvent>
21 #include <QPainter>
22
23 // Uncomment for Scope debugging.
24 //#define DEBUG_ASW
25
26 #ifdef DEBUG_ASW
27 #include <QDebug>
28 #endif
29
30 const int REALTIME_FPS = 30;
31
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
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
44 const QString AbstractScopeWidget::directions[] =  {"North", "Northeast", "East", "Southeast"};
45
46 AbstractScopeWidget::AbstractScopeWidget(bool trackMouse, QWidget *parent) :
47         QWidget(parent),
48         m_mousePos(0, 0),
49         m_mouseWithinWidget(false),
50         offset(5),
51         m_accelFactorHUD(1),
52         m_accelFactorScope(1),
53         m_accelFactorBackground(1),
54         m_semaphoreHUD(1),
55         m_semaphoreScope(1),
56         m_semaphoreBackground(1),
57         initialDimensionUpdateDone(false),
58         m_requestForcedUpdate(false),
59         m_rescaleMinDist(4),
60         m_rescaleVerticalThreshold(2.0f)
61
62 {
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);
72
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);
77
78     m_menu = new QMenu(this);
79     m_menu->setPalette(m_scopePalette);
80     m_menu->addAction(m_aAutoRefresh);
81     m_menu->addAction(m_aRealtime);
82
83     this->setContextMenuPolicy(Qt::CustomContextMenu);
84
85     bool b = true;
86     b &= connect(this, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(customContextMenuRequested(QPoint)));
87
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)));
93     Q_ASSERT(b);
94
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);
99 }
100
101 AbstractScopeWidget::~AbstractScopeWidget()
102 {
103     writeConfig();
104
105     delete m_menu;
106     delete m_aAutoRefresh;
107     delete m_aRealtime;
108 }
109
110 void AbstractScopeWidget::init()
111 {
112     m_widgetName = widgetName();
113     readConfig();
114 }
115
116 void AbstractScopeWidget::readConfig()
117 {
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));
122     scopeConfig.sync();
123 }
124
125 void AbstractScopeWidget::writeConfig()
126 {
127     KSharedConfigPtr config = KGlobal::config();
128     KConfigGroup scopeConfig(config, configName());
129     scopeConfig.writeEntry("autoRefresh", m_aAutoRefresh->isChecked());
130     scopeConfig.writeEntry("realtime", m_aRealtime->isChecked());
131     scopeConfig.sync();
132 }
133
134 QString AbstractScopeWidget::configName()
135 {
136     return "Scope_" + m_widgetName;
137 }
138
139 void AbstractScopeWidget::prodHUDThread()
140 {
141     if (this->visibleRegion().isEmpty()) {
142 #ifdef DEBUG_ASW
143         qDebug() << "Scope " << m_widgetName << " is not visible. Not calculating HUD.";
144 #endif
145     } else {
146         if (m_semaphoreHUD.tryAcquire(1)) {
147             Q_ASSERT(!m_threadHUD.isRunning());
148
149             m_newHUDFrames.fetchAndStoreRelaxed(0);
150             m_newHUDUpdates.fetchAndStoreRelaxed(0);
151             m_threadHUD = QtConcurrent::run(this, &AbstractScopeWidget::renderHUD, m_accelFactorHUD);
152 #ifdef DEBUG_ASW
153             qDebug() << "HUD thread started in " << m_widgetName;
154 #endif
155
156         }
157 #ifdef DEBUG_ASW
158         else {
159             qDebug() << "HUD semaphore locked, not prodding in " << m_widgetName << ". Thread running: " << m_threadHUD.isRunning();
160         }
161 #endif
162     }
163 }
164
165 void AbstractScopeWidget::prodScopeThread()
166 {
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)) {
170 #ifdef DEBUG_ASW
171         qDebug() << "Scope " << m_widgetName << " is not visible. Not calculating scope.";
172 #endif
173     } else {
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());
179
180             m_newScopeFrames.fetchAndStoreRelaxed(0);
181             m_newScopeUpdates.fetchAndStoreRelaxed(0);
182
183             Q_ASSERT(m_accelFactorScope > 0);
184
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;
189
190 #ifdef DEBUG_ASW
191             qDebug() << "Scope thread started in " << m_widgetName;
192 #endif
193
194         } else {
195 #ifdef DEBUG_ASW
196             qDebug() << "Scope semaphore locked, not prodding in " << m_widgetName << ". Thread running: " << m_threadScope.isRunning();
197 #endif
198         }
199     }
200 }
201 void AbstractScopeWidget::prodBackgroundThread()
202 {
203     if (this->visibleRegion().isEmpty()) {
204 #ifdef DEBUG_ASW
205         qDebug() << "Scope " << m_widgetName << " is not visible. Not calculating background.";
206 #endif
207     } else {
208         if (m_semaphoreBackground.tryAcquire(1)) {
209             Q_ASSERT(!m_threadBackground.isRunning());
210
211             m_newBackgroundFrames.fetchAndStoreRelaxed(0);
212             m_newBackgroundUpdates.fetchAndStoreRelaxed(0);
213             m_threadBackground = QtConcurrent::run(this, &AbstractScopeWidget::renderBackground, m_accelFactorBackground);
214
215 #ifdef DEBUG_ASW
216             qDebug() << "Background thread started in " << m_widgetName;
217 #endif
218
219         } else {
220 #ifdef DEBUG_ASW
221             qDebug() << "Background semaphore locked, not prodding in " << m_widgetName << ". Thread running: " << m_threadBackground.isRunning();
222 #endif
223         }
224     }
225 }
226
227 void AbstractScopeWidget::forceUpdate(bool doUpdate)
228 {
229 #ifdef DEBUG_ASW
230     qDebug() << "Forced update called in " << widgetName() << ". Arg: " << doUpdate;
231 #endif
232
233     if (!doUpdate) {
234         return;
235     }
236     m_requestForcedUpdate = true;
237     m_newHUDUpdates.fetchAndAddRelaxed(1);
238     m_newScopeUpdates.fetchAndAddRelaxed(1);
239     m_newBackgroundUpdates.fetchAndAddRelaxed(1);
240     prodHUDThread();
241     prodScopeThread();
242     prodBackgroundThread();
243 }
244 void AbstractScopeWidget::forceUpdateHUD()
245 {
246     m_newHUDUpdates.fetchAndAddRelaxed(1);
247     prodHUDThread();
248
249 }
250 void AbstractScopeWidget::forceUpdateScope()
251 {
252     m_newScopeUpdates.fetchAndAddRelaxed(1);
253     m_requestForcedUpdate = true;
254     prodScopeThread();
255
256 }
257 void AbstractScopeWidget::forceUpdateBackground()
258 {
259     m_newBackgroundUpdates.fetchAndAddRelaxed(1);
260     prodBackgroundThread();
261
262 }
263
264
265 ///// Events /////
266
267
268 void AbstractScopeWidget::resizeEvent(QResizeEvent *event)
269 {
270     // Update the dimension of the available rect for painting
271     m_scopeRect = scopeRect();
272     forceUpdate();
273
274     QWidget::resizeEvent(event);
275 }
276
277 void AbstractScopeWidget::showEvent(QShowEvent *event)
278 {
279     QWidget::showEvent(event);
280     m_scopeRect = scopeRect();
281 }
282
283 void AbstractScopeWidget::paintEvent(QPaintEvent *)
284 {
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);
289 }
290
291 void AbstractScopeWidget::mousePressEvent(QMouseEvent *event)
292 {
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();
300     }
301 }
302 void AbstractScopeWidget::mouseReleaseEvent(QMouseEvent *event)
303 {
304     m_rescaleActive = false;
305     m_rescalePropertiesLocked = false;
306
307     if (!m_aAutoRefresh->isChecked()) {
308         m_requestForcedUpdate = true;
309     }
310     prodHUDThread();
311     prodScopeThread();
312     prodBackgroundThread();
313     QWidget::mouseReleaseEvent(event);
314 }
315 void AbstractScopeWidget::mouseMoveEvent(QMouseEvent *event)
316 {
317     m_mousePos = event->pos();
318     m_mouseWithinWidget = true;
319     emit signalMousePositionChanged();
320
321     QPoint movement = event->pos()-m_rescaleStartPoint;
322
323     if (m_rescaleActive) {
324         if (m_rescalePropertiesLocked) {
325             // Direction is known, now adjust parameters
326
327             // Reset the starting point to make the next moveEvent relative to the current one
328             m_rescaleStartPoint = event->pos();
329
330
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
334
335                 if (movement.x() != 0) {
336                     movement.setX(movement.x() / abs(movement.x()));
337                 }
338                 if (movement.y() != 0) {
339                     movement.setY(movement.y() / abs(movement.y()));
340                 }
341
342                 m_rescaleFirstRescaleDone = true;
343             }
344
345             handleMouseDrag(movement, m_rescaleDirection, m_rescaleModifiers);
346
347
348
349         } else {
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();
354
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;
361                 } else {
362                     m_rescaleDirection = Southeast;
363                 }
364 #ifdef DEBUG_ASW
365                 qDebug() << "Diff is " << diff << "; chose " << directions[m_rescaleDirection] << " as direction";
366 #endif
367                 m_rescalePropertiesLocked = true;
368             }
369         }
370     }
371 }
372
373 void AbstractScopeWidget::leaveEvent(QEvent *)
374 {
375     m_mouseWithinWidget = false;
376     emit signalMousePositionChanged();
377 }
378
379 void AbstractScopeWidget::customContextMenuRequested(const QPoint &pos)
380 {
381     m_menu->exec(this->mapToGlobal(pos));
382 }
383
384 uint AbstractScopeWidget::calculateAccelFactorHUD(uint oldMseconds, uint)
385 {
386     return ceil((float)oldMseconds*REALTIME_FPS / 1000);
387 }
388 uint AbstractScopeWidget::calculateAccelFactorScope(uint oldMseconds, uint)
389 {
390     return ceil((float)oldMseconds*REALTIME_FPS / 1000);
391 }
392 uint AbstractScopeWidget::calculateAccelFactorBackground(uint oldMseconds, uint)
393 {
394     return ceil((float)oldMseconds*REALTIME_FPS / 1000);
395 }
396
397
398 ///// Slots /////
399
400 void AbstractScopeWidget::slotHUDRenderingFinished(uint mseconds, uint oldFactor)
401 {
402 #ifdef DEBUG_ASW
403     qDebug() << "HUD rendering has finished in " << mseconds << " ms, waiting for termination in " << m_widgetName;
404 #endif
405     m_threadHUD.waitForFinished();
406     m_imgHUD = m_threadHUD.result();
407
408     m_semaphoreHUD.release(1);
409     this->update();
410
411     int accel;
412     if (m_aRealtime->isChecked()) {
413         accel = calculateAccelFactorHUD(mseconds, oldFactor);
414         if (m_accelFactorHUD < 1) {
415             accel = 1;
416         }
417         m_accelFactorHUD = accel;
418     }
419
420     if ((m_newHUDFrames > 0 && m_aAutoRefresh->isChecked()) || m_newHUDUpdates > 0) {
421 #ifdef DEBUG_ASW
422         qDebug() << "Trying to start a new HUD thread for " << m_widgetName
423                 << ". New frames/updates: " << m_newHUDFrames << "/" << m_newHUDUpdates;
424 #endif
425         prodHUDThread();;
426     }
427 }
428
429 void AbstractScopeWidget::slotScopeRenderingFinished(uint mseconds, uint oldFactor)
430 {
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.
433 #ifdef DEBUG_ASW
434     qDebug() << "Scope rendering has finished in " << mseconds << " ms, waiting for termination in " << m_widgetName;
435 #endif
436     m_threadScope.waitForFinished();
437     m_imgScope = m_threadScope.result();
438
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);
442     this->update();
443
444     // Calculate the acceleration factor hint to get «realtime» updates.
445     int accel;
446     if (m_aRealtime->isChecked()) {
447         accel = calculateAccelFactorScope(mseconds, oldFactor);
448         if (accel < 1) {
449             // If mseconds happens to be 0.
450             accel = 1;
451         }
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;
456     }
457
458     if ((m_newScopeFrames > 0 && m_aAutoRefresh->isChecked()) || m_newScopeUpdates > 0) {
459 #ifdef DEBUG_ASW
460         qDebug() << "Trying to start a new scope thread for " << m_widgetName
461                 << ". New frames/updates: " << m_newScopeFrames << "/" << m_newScopeUpdates;
462 #endif
463         prodScopeThread();
464     }
465 }
466
467 void AbstractScopeWidget::slotBackgroundRenderingFinished(uint mseconds, uint oldFactor)
468 {
469 #ifdef DEBUG_ASW
470     qDebug() << "Background rendering has finished in " << mseconds << " ms, waiting for termination in " << m_widgetName;
471 #endif
472     m_threadBackground.waitForFinished();
473     m_imgBackground = m_threadBackground.result();
474
475     m_semaphoreBackground.release(1);
476     this->update();
477
478     int accel;
479     if (m_aRealtime->isChecked()) {
480         accel = calculateAccelFactorBackground(mseconds, oldFactor);
481         if (m_accelFactorBackground < 1) {
482             accel = 1;
483         }
484         m_accelFactorBackground = accel;
485     }
486
487     if ((m_newBackgroundFrames > 0 && m_aAutoRefresh->isChecked()) || m_newBackgroundUpdates > 0) {
488 #ifdef DEBUG_ASW
489         qDebug() << "Trying to start a new background thread for " << m_widgetName
490                 << ". New frames/updates: " << m_newBackgroundFrames << "/" << m_newBackgroundUpdates;
491 #endif
492         prodBackgroundThread();;
493     }
494 }
495
496 void AbstractScopeWidget::slotRenderZoneUpdated()
497 {
498     m_newHUDFrames.fetchAndAddRelaxed(1);
499     m_newScopeFrames.fetchAndAddRelaxed(1);
500     m_newBackgroundFrames.fetchAndAddRelaxed(1);
501
502 #ifdef DEBUG_ASW
503     qDebug() << "Data incoming at " << widgetName() << ". New frames total HUD/Scope/Background: " << m_newHUDFrames
504             << "/" << m_newScopeFrames << "/" << m_newBackgroundFrames;
505 #endif
506
507     if (this->visibleRegion().isEmpty()) {
508 #ifdef DEBUG_ASW
509         qDebug() << "Scope of widget " << m_widgetName << " is not at the top, not rendering.";
510 #endif
511     } else {
512         if (m_aAutoRefresh->isChecked()) {
513             prodHUDThread();
514             prodScopeThread();
515             prodBackgroundThread();
516         }
517     }
518 }
519
520 void AbstractScopeWidget::slotResetRealtimeFactor(bool realtimeChecked)
521 {
522     if (!realtimeChecked) {
523         m_accelFactorHUD = 1;
524         m_accelFactorScope = 1;
525         m_accelFactorBackground = 1;
526     }
527 }
528
529 bool AbstractScopeWidget::autoRefreshEnabled()
530 {
531     return m_aAutoRefresh->isChecked();
532 }
533
534 void AbstractScopeWidget::slotAutoRefreshToggled(bool autoRefresh)
535 {
536 #ifdef DEBUG_ASW
537     qDebug() << "Auto-refresh switched to " << autoRefresh << " in " << widgetName()
538             << " (Visible: " << isVisible() << "/" << this->visibleRegion().isEmpty() << ")";
539 #endif
540     if (isVisible()) {
541         // Notify listeners whether we accept new frames now
542         emit requestAutoRefresh(autoRefresh);
543     }
544     // TODO only if depends on input
545     if (autoRefresh) {
546         //forceUpdate();
547         m_requestForcedUpdate = true;
548     }
549 }
550
551 void AbstractScopeWidget::handleMouseDrag(const QPoint, const RescaleDirection, const Qt::KeyboardModifiers) { }
552
553
554 #ifdef DEBUG_ASW
555 #undef DEBUG_ASW
556 #endif