]> git.sesse.net Git - kdenlive/blob - src/abstractscopewidget.cpp
Using #ifdef for debugging instead of commenting out in 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::penDark(QBrush(QColor(0, 0, 20, 250)),      1, Qt::SolidLine);
41 const QPen AbstractScopeWidget::penDarkDots(QBrush(QColor(0, 0, 20, 250)),      1, Qt::DotLine);
42
43 AbstractScopeWidget::AbstractScopeWidget(bool trackMouse, QWidget *parent) :
44         QWidget(parent),
45         m_mousePos(0, 0),
46         m_mouseWithinWidget(false),
47         offset(5),
48         m_accelFactorHUD(1),
49         m_accelFactorScope(1),
50         m_accelFactorBackground(1),
51         m_semaphoreHUD(1),
52         m_semaphoreScope(1),
53         m_semaphoreBackground(1),
54         initialDimensionUpdateDone(false),
55         m_requestForcedUpdate(false)
56
57 {
58     m_scopePalette = QPalette();
59     m_scopePalette.setBrush(QPalette::Window, QBrush(dark2));
60     m_scopePalette.setBrush(QPalette::Base, QBrush(dark));
61     m_scopePalette.setBrush(QPalette::Button, QBrush(dark));
62     m_scopePalette.setBrush(QPalette::Text, QBrush(light));
63     m_scopePalette.setBrush(QPalette::WindowText, QBrush(light));
64     m_scopePalette.setBrush(QPalette::ButtonText, QBrush(light));
65     this->setPalette(m_scopePalette);
66     this->setAutoFillBackground(true);
67
68     m_aAutoRefresh = new QAction(i18n("Auto Refresh"), this);
69     m_aAutoRefresh->setCheckable(true);
70     m_aRealtime = new QAction(i18n("Realtime (with precision loss)"), this);
71     m_aRealtime->setCheckable(true);
72
73     m_menu = new QMenu(this);
74     m_menu->setPalette(m_scopePalette);
75     m_menu->addAction(m_aAutoRefresh);
76     m_menu->addAction(m_aRealtime);
77
78     this->setContextMenuPolicy(Qt::CustomContextMenu);
79
80     bool b = true;
81     b &= connect(this, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(customContextMenuRequested(QPoint)));
82
83     b &= connect(this, SIGNAL(signalHUDRenderingFinished(uint, uint)), this, SLOT(slotHUDRenderingFinished(uint, uint)));
84     b &= connect(this, SIGNAL(signalScopeRenderingFinished(uint, uint)), this, SLOT(slotScopeRenderingFinished(uint, uint)));
85     b &= connect(this, SIGNAL(signalBackgroundRenderingFinished(uint, uint)), this, SLOT(slotBackgroundRenderingFinished(uint, uint)));
86     b &= connect(m_aRealtime, SIGNAL(toggled(bool)), this, SLOT(slotResetRealtimeFactor(bool)));
87     b &= connect(m_aAutoRefresh, SIGNAL(toggled(bool)), this, SLOT(slotAutoRefreshToggled(bool)));
88     Q_ASSERT(b);
89
90     // Enable mouse tracking if desired.
91     // Causes the mouseMoved signal to be emitted when the mouse moves inside the
92     // widget, even when no mouse button is pressed.
93     this->setMouseTracking(trackMouse);
94 }
95
96 AbstractScopeWidget::~AbstractScopeWidget()
97 {
98     writeConfig();
99
100     delete m_menu;
101     delete m_aAutoRefresh;
102     delete m_aRealtime;
103 }
104
105 void AbstractScopeWidget::init()
106 {
107     m_widgetName = widgetName();
108     readConfig();
109 }
110
111 void AbstractScopeWidget::readConfig()
112 {
113     KSharedConfigPtr config = KGlobal::config();
114     KConfigGroup scopeConfig(config, configName());
115     m_aAutoRefresh->setChecked(scopeConfig.readEntry("autoRefresh", true));
116     m_aRealtime->setChecked(scopeConfig.readEntry("realtime", false));
117     scopeConfig.sync();
118 }
119
120 void AbstractScopeWidget::writeConfig()
121 {
122     KSharedConfigPtr config = KGlobal::config();
123     KConfigGroup scopeConfig(config, configName());
124     scopeConfig.writeEntry("autoRefresh", m_aAutoRefresh->isChecked());
125     scopeConfig.writeEntry("realtime", m_aRealtime->isChecked());
126     scopeConfig.sync();
127 }
128
129 QString AbstractScopeWidget::configName()
130 {
131     return "Scope_" + m_widgetName;
132 }
133
134 void AbstractScopeWidget::prodHUDThread()
135 {
136     if (this->visibleRegion().isEmpty()) {
137 #ifdef DEBUG_ASW
138         qDebug() << "Scope " << m_widgetName << " is not visible. Not calculating HUD.";
139 #endif
140     } else {
141         if (m_semaphoreHUD.tryAcquire(1)) {
142             Q_ASSERT(!m_threadHUD.isRunning());
143
144             m_newHUDFrames.fetchAndStoreRelaxed(0);
145             m_newHUDUpdates.fetchAndStoreRelaxed(0);
146             m_threadHUD = QtConcurrent::run(this, &AbstractScopeWidget::renderHUD, m_accelFactorHUD);
147 #ifdef DEBUG_ASW
148             qDebug() << "HUD thread started in " << m_widgetName;
149 #endif
150
151         }
152 #ifdef DEBUG_ASW
153         else {
154             qDebug() << "HUD semaphore locked, not prodding in " << m_widgetName << ". Thread running: " << m_threadHUD.isRunning();
155         }
156 #endif
157     }
158 }
159
160 void AbstractScopeWidget::prodScopeThread()
161 {
162     // Only start a new thread if the scope is actually visible
163     // and not hidden by another widget on the stack and if user want the scope to update.
164     if (this->visibleRegion().isEmpty() || (!m_aAutoRefresh->isChecked() && !m_requestForcedUpdate)) {
165 #ifdef DEBUG_ASW
166         qDebug() << "Scope " << m_widgetName << " is not visible. Not calculating scope.";
167 #endif
168     } else {
169         // Try to acquire the semaphore. This must only succeed if m_threadScope is not running
170         // anymore. Therefore the semaphore must NOT be released before m_threadScope ends.
171         // If acquiring the semaphore fails, the thread is still running.
172         if (m_semaphoreScope.tryAcquire(1)) {
173             Q_ASSERT(!m_threadScope.isRunning());
174
175             m_newScopeFrames.fetchAndStoreRelaxed(0);
176             m_newScopeUpdates.fetchAndStoreRelaxed(0);
177
178             Q_ASSERT(m_accelFactorScope > 0);
179
180             // See http://doc.qt.nokia.com/latest/qtconcurrentrun.html#run about
181             // running member functions in a thread
182             m_threadScope = QtConcurrent::run(this, &AbstractScopeWidget::renderScope, m_accelFactorScope);
183             m_requestForcedUpdate = false;
184
185 #ifdef DEBUG_ASW
186             qDebug() << "Scope thread started in " << m_widgetName;
187 #endif
188
189         } else {
190 #ifdef DEBUG_ASW
191             qDebug() << "Scope semaphore locked, not prodding in " << m_widgetName << ". Thread running: " << m_threadScope.isRunning();
192 #endif
193         }
194     }
195 }
196 void AbstractScopeWidget::prodBackgroundThread()
197 {
198     if (this->visibleRegion().isEmpty()) {
199 #ifdef DEBUG_ASW
200         qDebug() << "Scope " << m_widgetName << " is not visible. Not calculating background.";
201 #endif
202     } else {
203         if (m_semaphoreBackground.tryAcquire(1)) {
204             Q_ASSERT(!m_threadBackground.isRunning());
205
206             m_newBackgroundFrames.fetchAndStoreRelaxed(0);
207             m_newBackgroundUpdates.fetchAndStoreRelaxed(0);
208             m_threadBackground = QtConcurrent::run(this, &AbstractScopeWidget::renderBackground, m_accelFactorBackground);
209
210 #ifdef DEBUG_ASW
211             qDebug() << "Background thread started in " << m_widgetName;
212 #endif
213
214         } else {
215 #ifdef DEBUG_ASW
216             qDebug() << "Background semaphore locked, not prodding in " << m_widgetName << ". Thread running: " << m_threadBackground.isRunning();
217 #endif
218         }
219     }
220 }
221
222 void AbstractScopeWidget::forceUpdate(bool doUpdate)
223 {
224 #ifdef DEBUG_ASW
225     qDebug() << "Force update called in " << widgetName() << ". Arg: " << doUpdate;
226 #endif
227
228     if (!doUpdate) {
229         return;
230     }
231     m_requestForcedUpdate = true;
232     m_newHUDUpdates.fetchAndAddRelaxed(1);
233     m_newScopeUpdates.fetchAndAddRelaxed(1);
234     m_newBackgroundUpdates.fetchAndAddRelaxed(1);
235     prodHUDThread();
236     prodScopeThread();
237     prodBackgroundThread();
238 }
239 void AbstractScopeWidget::forceUpdateHUD()
240 {
241     m_newHUDUpdates.fetchAndAddRelaxed(1);
242     prodHUDThread();
243
244 }
245 void AbstractScopeWidget::forceUpdateScope()
246 {
247     m_newScopeUpdates.fetchAndAddRelaxed(1);
248     m_requestForcedUpdate = true;
249     prodScopeThread();
250
251 }
252 void AbstractScopeWidget::forceUpdateBackground()
253 {
254     m_newBackgroundUpdates.fetchAndAddRelaxed(1);
255     prodBackgroundThread();
256
257 }
258
259
260 ///// Events /////
261
262 void AbstractScopeWidget::mouseReleaseEvent(QMouseEvent *event)
263 {
264     if (!m_aAutoRefresh->isChecked()) {
265         m_requestForcedUpdate = true;
266     }
267     prodHUDThread();
268     prodScopeThread();
269     prodBackgroundThread();
270     QWidget::mouseReleaseEvent(event);
271 }
272
273 void AbstractScopeWidget::resizeEvent(QResizeEvent *event)
274 {
275     // Update the dimension of the available rect for painting
276     m_scopeRect = scopeRect();
277     forceUpdate();
278
279     QWidget::resizeEvent(event);
280 }
281
282 void AbstractScopeWidget::showEvent(QShowEvent *event)
283 {
284     QWidget::showEvent(event);
285     m_scopeRect = scopeRect();
286 }
287
288 void AbstractScopeWidget::paintEvent(QPaintEvent *)
289 {
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);
294 }
295
296 void AbstractScopeWidget::mouseMoveEvent(QMouseEvent *event)
297 {
298     m_mousePos = event->pos();
299     m_mouseWithinWidget = true;
300     emit signalMousePositionChanged();
301 }
302 void AbstractScopeWidget::leaveEvent(QEvent *)
303 {
304     m_mouseWithinWidget = false;
305     emit signalMousePositionChanged();
306 }
307
308 void AbstractScopeWidget::customContextMenuRequested(const QPoint &pos)
309 {
310     m_menu->exec(this->mapToGlobal(pos));
311 }
312
313 uint AbstractScopeWidget::calculateAccelFactorHUD(uint oldMseconds, uint)
314 {
315     return ceil((float)oldMseconds*REALTIME_FPS / 1000);
316 }
317 uint AbstractScopeWidget::calculateAccelFactorScope(uint oldMseconds, uint)
318 {
319     return ceil((float)oldMseconds*REALTIME_FPS / 1000);
320 }
321 uint AbstractScopeWidget::calculateAccelFactorBackground(uint oldMseconds, uint)
322 {
323     return ceil((float)oldMseconds*REALTIME_FPS / 1000);
324 }
325
326
327 ///// Slots /////
328
329 void AbstractScopeWidget::slotHUDRenderingFinished(uint mseconds, uint oldFactor)
330 {
331 //    qDebug() << "HUD rendering has finished, waiting for termination in " << m_widgetName;
332     m_threadHUD.waitForFinished();
333     m_imgHUD = m_threadHUD.result();
334
335     m_semaphoreHUD.release(1);
336     this->update();
337
338     int accel;
339     if (m_aRealtime->isChecked()) {
340         accel = calculateAccelFactorHUD(mseconds, oldFactor);
341         if (m_accelFactorHUD < 1) {
342             accel = 1;
343         }
344         m_accelFactorHUD = accel;
345     }
346
347     if ((m_newHUDFrames > 0 && m_aAutoRefresh->isChecked()) || m_newHUDUpdates > 0) {
348 #ifdef DEBUG_ASW
349         qDebug() << "Trying to start a new HUD thread for " << m_widgetName
350                 << ". New frames/updates: " << m_newHUDFrames << "/" << m_newHUDUpdates;
351 #endif
352         prodHUDThread();;
353     }
354 }
355
356 void AbstractScopeWidget::slotScopeRenderingFinished(uint mseconds, uint oldFactor)
357 {
358     // The signal can be received before the thread has really finished. So we
359     // need to wait until it has really finished before starting a new thread.
360 #ifdef DEBUG_ASW
361     qDebug() << "Scope rendering has finished, waiting for termination in " << m_widgetName;
362 #endif
363     m_threadScope.waitForFinished();
364     m_imgScope = m_threadScope.result();
365
366     // The scope thread has finished. Now we can release the semaphore, allowing a new thread.
367     // See prodScopeThread where the semaphore is acquired again.
368     m_semaphoreScope.release(1);
369     this->update();
370
371     // Calculate the acceleration factor hint to get «realtime» updates.
372     int accel;
373     if (m_aRealtime->isChecked()) {
374         accel = calculateAccelFactorScope(mseconds, oldFactor);
375         if (accel < 1) {
376             // If mseconds happens to be 0.
377             accel = 1;
378         }
379         // Don't directly calculate with m_accelFactorScope as we are dealing with concurrency.
380         // If m_accelFactorScope is set to 0 at the wrong moment, who knows what might happen
381         // then :) Therefore use a local variable.
382         m_accelFactorScope = accel;
383     }
384
385     if ((m_newScopeFrames > 0 && m_aAutoRefresh->isChecked()) || m_newScopeUpdates > 0) {
386 #ifdef DEBUG_ASW
387         qDebug() << "Trying to start a new scope thread for " << m_widgetName
388                 << ". New frames/updates: " << m_newScopeFrames << "/" << m_newScopeUpdates;
389 #endif
390         prodScopeThread();
391     }
392 }
393
394 void AbstractScopeWidget::slotBackgroundRenderingFinished(uint mseconds, uint oldFactor)
395 {
396 #ifdef DEBUG_ASW
397     qDebug() << "Background rendering has finished, waiting for termination in " << m_widgetName;
398 #endif
399     m_threadBackground.waitForFinished();
400     m_imgBackground = m_threadBackground.result();
401
402     m_semaphoreBackground.release(1);
403     this->update();
404
405     int accel;
406     if (m_aRealtime->isChecked()) {
407         accel = calculateAccelFactorBackground(mseconds, oldFactor);
408         if (m_accelFactorBackground < 1) {
409             accel = 1;
410         }
411         m_accelFactorBackground = accel;
412     }
413
414     if ((m_newBackgroundFrames > 0 && m_aAutoRefresh->isChecked()) || m_newBackgroundUpdates > 0) {
415 #ifdef DEBUG_ASW
416         qDebug() << "Trying to start a new background thread for " << m_widgetName
417                 << ". New frames/updates: " << m_newBackgroundFrames << "/" << m_newBackgroundUpdates;
418 #endif
419         prodBackgroundThread();;
420     }
421 }
422
423 void AbstractScopeWidget::slotRenderZoneUpdated()
424 {
425     m_newHUDFrames.fetchAndAddRelaxed(1);
426     m_newScopeFrames.fetchAndAddRelaxed(1);
427     m_newBackgroundFrames.fetchAndAddRelaxed(1);
428
429 #ifdef DEBUG_ASW
430     qDebug() << "Monitor incoming. New frames total HUD/Scope/Background: " << m_newHUDFrames
431             << "/" << m_newScopeFrames << "/" << m_newBackgroundFrames;
432 #endif
433
434     if (this->visibleRegion().isEmpty()) {
435 #ifdef DEBUG_ASW
436         qDebug() << "Scope of widget " << m_widgetName << " is not at the top, not rendering.";
437 #endif
438     } else {
439         if (m_aAutoRefresh->isChecked()) {
440             prodHUDThread();
441             prodScopeThread();
442             prodBackgroundThread();
443         }
444     }
445 }
446
447 void AbstractScopeWidget::slotRenderZoneUpdated(QImage frame)
448 {
449     m_scopeImage = frame;
450     slotRenderZoneUpdated();
451 }
452
453 void AbstractScopeWidget::slotResetRealtimeFactor(bool realtimeChecked)
454 {
455     if (!realtimeChecked) {
456         m_accelFactorHUD = 1;
457         m_accelFactorScope = 1;
458         m_accelFactorBackground = 1;
459     }
460 }
461
462 bool AbstractScopeWidget::autoRefreshEnabled()
463 {
464     return m_aAutoRefresh->isChecked();
465 }
466
467 void AbstractScopeWidget::slotAutoRefreshToggled(bool autoRefresh)
468 {
469     if (isVisible()) {
470         emit requestAutoRefresh(autoRefresh);
471     }
472     // TODO only if depends on input
473     if (autoRefresh) {
474         //forceUpdate();
475         m_requestForcedUpdate = true;
476     }
477 }
478
479
480 #ifdef DEBUG_ASW
481 #undef DEBUG_ASW
482 #endif