]> git.sesse.net Git - kdenlive/blob - src/scopes/abstractscopewidget.cpp
a4d789d33de33d2399dce84b109cdeb60f6b0a89
[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 "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 #include <KConfigGroup>
24 #include <KGlobal>
25
26 // Uncomment for Scope debugging.
27 //#define DEBUG_ASW
28
29 #ifdef DEBUG_ASW
30 #include <QDebug>
31 #endif
32
33 const int REALTIME_FPS = 30;
34
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);
41
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);
50
51 const QString AbstractScopeWidget::directions[] =  {"North", "Northeast", "East", "Southeast"};
52
53 AbstractScopeWidget::AbstractScopeWidget(bool trackMouse, QWidget *parent) :
54         QWidget(parent)
55         , m_mousePos(0, 0)
56         , m_mouseWithinWidget(false)
57         , offset(5)
58         , m_accelFactorHUD(1)
59         , m_accelFactorScope(1)
60         , m_accelFactorBackground(1)
61         , m_semaphoreHUD(1)
62         , m_semaphoreScope(1)
63         , m_semaphoreBackground(1)
64         , initialDimensionUpdateDone(false)
65         , m_requestForcedUpdate(false)
66         , m_rescaleMinDist(4)
67         , m_rescaleVerticalThreshold(2.0f)
68         , m_rescaleActive(false)
69         , m_rescalePropertiesLocked(false)
70         , m_rescaleFirstRescaleDone(true)
71         , m_rescaleDirection(North)
72
73 {
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);
83
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);
88
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);
94
95     this->setContextMenuPolicy(Qt::CustomContextMenu);
96
97     bool b = true;
98     b &= connect(this, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(customContextMenuRequested(QPoint)));
99
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)));
105     Q_ASSERT(b);
106
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);
111 }
112
113 AbstractScopeWidget::~AbstractScopeWidget()
114 {
115     writeConfig();
116
117     delete m_menu;
118     delete m_aAutoRefresh;
119     delete m_aRealtime;
120 }
121
122 void AbstractScopeWidget::init()
123 {
124     m_widgetName = widgetName();
125     readConfig();
126 }
127
128 void AbstractScopeWidget::readConfig()
129 {
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));
134     scopeConfig.sync();
135 }
136
137 void AbstractScopeWidget::writeConfig()
138 {
139     KSharedConfigPtr config = KGlobal::config();
140     KConfigGroup scopeConfig(config, configName());
141     scopeConfig.writeEntry("autoRefresh", m_aAutoRefresh->isChecked());
142     scopeConfig.writeEntry("realtime", m_aRealtime->isChecked());
143     scopeConfig.sync();
144 }
145
146 QString AbstractScopeWidget::configName()
147 {
148     return "Scope_" + m_widgetName;
149 }
150
151 void AbstractScopeWidget::prodHUDThread()
152 {
153     if (this->visibleRegion().isEmpty()) {
154 #ifdef DEBUG_ASW
155         qDebug() << "Scope " << m_widgetName << " is not visible. Not calculating HUD.";
156 #endif
157     } else {
158         if (m_semaphoreHUD.tryAcquire(1)) {
159             Q_ASSERT(!m_threadHUD.isRunning());
160
161             m_newHUDFrames.fetchAndStoreRelaxed(0);
162             m_newHUDUpdates.fetchAndStoreRelaxed(0);
163             m_threadHUD = QtConcurrent::run(this, &AbstractScopeWidget::renderHUD, m_accelFactorHUD);
164 #ifdef DEBUG_ASW
165             qDebug() << "HUD thread started in " << m_widgetName;
166 #endif
167
168         }
169 #ifdef DEBUG_ASW
170         else {
171             qDebug() << "HUD semaphore locked, not prodding in " << m_widgetName << ". Thread running: " << m_threadHUD.isRunning();
172         }
173 #endif
174     }
175 }
176
177 void AbstractScopeWidget::prodScopeThread()
178 {
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)) {
182 #ifdef DEBUG_ASW
183         qDebug() << "Scope " << m_widgetName << " is not visible. Not calculating scope.";
184 #endif
185     } else {
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());
191
192             m_newScopeFrames.fetchAndStoreRelaxed(0);
193             m_newScopeUpdates.fetchAndStoreRelaxed(0);
194
195             Q_ASSERT(m_accelFactorScope > 0);
196
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;
201
202 #ifdef DEBUG_ASW
203             qDebug() << "Scope thread started in " << m_widgetName;
204 #endif
205
206         } else {
207 #ifdef DEBUG_ASW
208             qDebug() << "Scope semaphore locked, not prodding in " << m_widgetName << ". Thread running: " << m_threadScope.isRunning();
209 #endif
210         }
211     }
212 }
213 void AbstractScopeWidget::prodBackgroundThread()
214 {
215     if (this->visibleRegion().isEmpty()) {
216 #ifdef DEBUG_ASW
217         qDebug() << "Scope " << m_widgetName << " is not visible. Not calculating background.";
218 #endif
219     } else {
220         if (m_semaphoreBackground.tryAcquire(1)) {
221             Q_ASSERT(!m_threadBackground.isRunning());
222
223             m_newBackgroundFrames.fetchAndStoreRelaxed(0);
224             m_newBackgroundUpdates.fetchAndStoreRelaxed(0);
225             m_threadBackground = QtConcurrent::run(this, &AbstractScopeWidget::renderBackground, m_accelFactorBackground);
226
227 #ifdef DEBUG_ASW
228             qDebug() << "Background thread started in " << m_widgetName;
229 #endif
230
231         } else {
232 #ifdef DEBUG_ASW
233             qDebug() << "Background semaphore locked, not prodding in " << m_widgetName << ". Thread running: " << m_threadBackground.isRunning();
234 #endif
235         }
236     }
237 }
238
239 void AbstractScopeWidget::forceUpdate(bool doUpdate)
240 {
241 #ifdef DEBUG_ASW
242     qDebug() << "Forced update called in " << widgetName() << ". Arg: " << doUpdate;
243 #endif
244
245     if (!doUpdate) {
246         return;
247     }
248     m_requestForcedUpdate = true;
249     m_newHUDUpdates.fetchAndAddRelaxed(1);
250     m_newScopeUpdates.fetchAndAddRelaxed(1);
251     m_newBackgroundUpdates.fetchAndAddRelaxed(1);
252     prodHUDThread();
253     prodScopeThread();
254     prodBackgroundThread();
255 }
256 void AbstractScopeWidget::forceUpdateHUD()
257 {
258     m_newHUDUpdates.fetchAndAddRelaxed(1);
259     prodHUDThread();
260
261 }
262 void AbstractScopeWidget::forceUpdateScope()
263 {
264     m_newScopeUpdates.fetchAndAddRelaxed(1);
265     m_requestForcedUpdate = true;
266     prodScopeThread();
267
268 }
269 void AbstractScopeWidget::forceUpdateBackground()
270 {
271     m_newBackgroundUpdates.fetchAndAddRelaxed(1);
272     prodBackgroundThread();
273
274 }
275
276
277 ///// Events /////
278
279
280 void AbstractScopeWidget::resizeEvent(QResizeEvent *event)
281 {
282     // Update the dimension of the available rect for painting
283     m_scopeRect = scopeRect();
284     forceUpdate();
285
286     QWidget::resizeEvent(event);
287 }
288
289 void AbstractScopeWidget::showEvent(QShowEvent *event)
290 {
291     QWidget::showEvent(event);
292     m_scopeRect = scopeRect();
293 }
294
295 void AbstractScopeWidget::paintEvent(QPaintEvent *)
296 {
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);
301 }
302
303 void AbstractScopeWidget::mousePressEvent(QMouseEvent *event)
304 {
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();
312     }
313 }
314 void AbstractScopeWidget::mouseReleaseEvent(QMouseEvent *event)
315 {
316     m_rescaleActive = false;
317     m_rescalePropertiesLocked = false;
318
319     if (!m_aAutoRefresh->isChecked()) {
320         m_requestForcedUpdate = true;
321     }
322     prodHUDThread();
323     prodScopeThread();
324     prodBackgroundThread();
325     QWidget::mouseReleaseEvent(event);
326 }
327 void AbstractScopeWidget::mouseMoveEvent(QMouseEvent *event)
328 {
329     m_mousePos = event->pos();
330     m_mouseWithinWidget = true;
331     emit signalMousePositionChanged();
332
333     QPoint movement = event->pos()-m_rescaleStartPoint;
334
335     if (m_rescaleActive) {
336         if (m_rescalePropertiesLocked) {
337             // Direction is known, now adjust parameters
338
339             // Reset the starting point to make the next moveEvent relative to the current one
340             m_rescaleStartPoint = event->pos();
341
342
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
346
347                 if (movement.x() != 0) {
348                     movement.setX(movement.x() / abs(movement.x()));
349                 }
350                 if (movement.y() != 0) {
351                     movement.setY(movement.y() / abs(movement.y()));
352                 }
353
354                 m_rescaleFirstRescaleDone = true;
355             }
356
357             handleMouseDrag(movement, m_rescaleDirection, m_rescaleModifiers);
358
359
360
361         } else {
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();
366
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;
373                 } else {
374                     m_rescaleDirection = Southeast;
375                 }
376 #ifdef DEBUG_ASW
377                 qDebug() << "Diff is " << diff << "; chose " << directions[m_rescaleDirection] << " as direction";
378 #endif
379                 m_rescalePropertiesLocked = true;
380             }
381         }
382     }
383 }
384
385 void AbstractScopeWidget::leaveEvent(QEvent *)
386 {
387     m_mouseWithinWidget = false;
388     emit signalMousePositionChanged();
389 }
390
391 void AbstractScopeWidget::customContextMenuRequested(const QPoint &pos)
392 {
393     m_menu->exec(this->mapToGlobal(pos));
394 }
395
396 uint AbstractScopeWidget::calculateAccelFactorHUD(uint oldMseconds, uint)
397 {
398     return ceil((float)oldMseconds*REALTIME_FPS / 1000);
399 }
400 uint AbstractScopeWidget::calculateAccelFactorScope(uint oldMseconds, uint)
401 {
402     return ceil((float)oldMseconds*REALTIME_FPS / 1000);
403 }
404 uint AbstractScopeWidget::calculateAccelFactorBackground(uint oldMseconds, uint)
405 {
406     return ceil((float)oldMseconds*REALTIME_FPS / 1000);
407 }
408
409
410 ///// Slots /////
411
412 void AbstractScopeWidget::slotHUDRenderingFinished(uint mseconds, uint oldFactor)
413 {
414 #ifdef DEBUG_ASW
415     qDebug() << "HUD rendering has finished in " << mseconds << " ms, waiting for termination in " << m_widgetName;
416 #endif
417     m_threadHUD.waitForFinished();
418     m_imgHUD = m_threadHUD.result();
419
420     m_semaphoreHUD.release(1);
421     this->update();
422
423     int accel;
424     if (m_aRealtime->isChecked()) {
425         accel = calculateAccelFactorHUD(mseconds, oldFactor);
426         if (m_accelFactorHUD < 1) {
427             accel = 1;
428         }
429         m_accelFactorHUD = accel;
430     }
431
432     if ((m_newHUDFrames > 0 && m_aAutoRefresh->isChecked()) || m_newHUDUpdates > 0) {
433 #ifdef DEBUG_ASW
434         qDebug() << "Trying to start a new HUD thread for " << m_widgetName
435                 << ". New frames/updates: " << m_newHUDFrames << "/" << m_newHUDUpdates;
436 #endif
437         prodHUDThread();
438     }
439 }
440
441 void AbstractScopeWidget::slotScopeRenderingFinished(uint mseconds, uint oldFactor)
442 {
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.
445 #ifdef DEBUG_ASW
446     qDebug() << "Scope rendering has finished in " << mseconds << " ms, waiting for termination in " << m_widgetName;
447 #endif
448     m_threadScope.waitForFinished();
449     m_imgScope = m_threadScope.result();
450
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);
454     this->update();
455
456     // Calculate the acceleration factor hint to get «realtime» updates.
457     int accel;
458     if (m_aRealtime->isChecked()) {
459         accel = calculateAccelFactorScope(mseconds, oldFactor);
460         if (accel < 1) {
461             // If mseconds happens to be 0.
462             accel = 1;
463         }
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;
468     }
469
470     if ((m_newScopeFrames > 0 && m_aAutoRefresh->isChecked()) || m_newScopeUpdates > 0) {
471 #ifdef DEBUG_ASW
472         qDebug() << "Trying to start a new scope thread for " << m_widgetName
473                 << ". New frames/updates: " << m_newScopeFrames << "/" << m_newScopeUpdates;
474 #endif
475         prodScopeThread();
476     }
477 }
478
479 void AbstractScopeWidget::slotBackgroundRenderingFinished(uint mseconds, uint oldFactor)
480 {
481 #ifdef DEBUG_ASW
482     qDebug() << "Background rendering has finished in " << mseconds << " ms, waiting for termination in " << m_widgetName;
483 #endif
484     m_threadBackground.waitForFinished();
485     m_imgBackground = m_threadBackground.result();
486
487     m_semaphoreBackground.release(1);
488     this->update();
489
490     int accel;
491     if (m_aRealtime->isChecked()) {
492         accel = calculateAccelFactorBackground(mseconds, oldFactor);
493         if (m_accelFactorBackground < 1) {
494             accel = 1;
495         }
496         m_accelFactorBackground = accel;
497     }
498
499     if ((m_newBackgroundFrames > 0 && m_aAutoRefresh->isChecked()) || m_newBackgroundUpdates > 0) {
500 #ifdef DEBUG_ASW
501         qDebug() << "Trying to start a new background thread for " << m_widgetName
502                 << ". New frames/updates: " << m_newBackgroundFrames << "/" << m_newBackgroundUpdates;
503 #endif
504         prodBackgroundThread();;
505     }
506 }
507
508 void AbstractScopeWidget::slotRenderZoneUpdated()
509 {
510     m_newHUDFrames.fetchAndAddRelaxed(1);
511     m_newScopeFrames.fetchAndAddRelaxed(1);
512     m_newBackgroundFrames.fetchAndAddRelaxed(1);
513
514 #ifdef DEBUG_ASW
515     qDebug() << "Data incoming at " << widgetName() << ". New frames total HUD/Scope/Background: " << m_newHUDFrames
516             << "/" << m_newScopeFrames << "/" << m_newBackgroundFrames;
517 #endif
518
519     if (this->visibleRegion().isEmpty()) {
520 #ifdef DEBUG_ASW
521         qDebug() << "Scope of widget " << m_widgetName << " is not at the top, not rendering.";
522 #endif
523     } else {
524         if (m_aAutoRefresh->isChecked()) {
525             prodHUDThread();
526             prodScopeThread();
527             prodBackgroundThread();
528         }
529     }
530 }
531
532 void AbstractScopeWidget::slotResetRealtimeFactor(bool realtimeChecked)
533 {
534     if (!realtimeChecked) {
535         m_accelFactorHUD = 1;
536         m_accelFactorScope = 1;
537         m_accelFactorBackground = 1;
538     }
539 }
540
541 bool AbstractScopeWidget::autoRefreshEnabled() const
542 {
543     return m_aAutoRefresh->isChecked();
544 }
545
546 void AbstractScopeWidget::slotAutoRefreshToggled(bool autoRefresh)
547 {
548 #ifdef DEBUG_ASW
549     qDebug() << "Auto-refresh switched to " << autoRefresh << " in " << widgetName()
550             << " (Visible: " << isVisible() << "/" << this->visibleRegion().isEmpty() << ")";
551 #endif
552     if (isVisible()) {
553         // Notify listeners whether we accept new frames now
554         emit requestAutoRefresh(autoRefresh);
555     }
556     // TODO only if depends on input
557     if (autoRefresh) {
558         //forceUpdate();
559         m_requestForcedUpdate = true;
560     }
561 }
562
563 void AbstractScopeWidget::handleMouseDrag(const QPoint &, const RescaleDirection, const Qt::KeyboardModifiers) { }
564
565
566 #ifdef DEBUG_ASW
567 #undef DEBUG_ASW
568 #endif
569
570 #include "abstractscopewidget.moc"