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