]> git.sesse.net Git - kdenlive/blob - src/scopes/abstractscopewidget.cpp
Fix includes
[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 "QtCore/qtconcurrentrun.h"
12
13 #include "abstractscopewidget.h"
14 #include "renderer.h"
15 #include "monitor.h"
16
17 #include <QColor>
18 #include <QMenu>
19 #include <QMouseEvent>
20 #include <QPainter>
21
22 #include <KConfigGroup>
23 #include <KGlobal>
24
25 // Uncomment for Scope debugging.
26 //#define DEBUG_ASW
27
28 #ifdef DEBUG_ASW
29 #include <QDebug>
30 #endif
31
32 const int REALTIME_FPS = 30;
33
34 const QColor light(250, 238, 226, 255);
35 const QColor dark(40,  40,  39, 255);
36 const QColor dark2(25,  25,  23, 255);
37 const QColor AbstractScopeWidget::colHighlightLight(18, 130, 255, 255);
38 const QColor AbstractScopeWidget::colHighlightDark(255, 64, 19, 255);
39 const QColor AbstractScopeWidget::colDarkWhite(250, 250, 250);
40
41 const QPen AbstractScopeWidget::penThick(QBrush(AbstractScopeWidget::colDarkWhite.rgb()),           2, Qt::SolidLine);
42 const QPen AbstractScopeWidget::penThin(QBrush(AbstractScopeWidget::colDarkWhite.rgb()),            1, Qt::SolidLine);
43 const QPen AbstractScopeWidget::penLight(QBrush(QColor(200, 200, 250, 150)),                        1, Qt::SolidLine);
44 const QPen AbstractScopeWidget::penLightDots(QBrush(QColor(200, 200, 250, 150)),                    1, Qt::DotLine);
45 const QPen AbstractScopeWidget::penLighter(QBrush(QColor(225, 225, 250, 225)),                      1, Qt::SolidLine);
46 const QPen AbstractScopeWidget::penDark(QBrush(QColor(0, 0, 20, 250)),                              1, Qt::SolidLine);
47 const QPen AbstractScopeWidget::penDarkDots(QBrush(QColor(0, 0, 20, 250)),                          1, Qt::DotLine);
48 const QPen AbstractScopeWidget::penBackground(QBrush(dark2),                                        1, Qt::SolidLine);
49
50 const QString AbstractScopeWidget::directions[] =  {"North", "Northeast", "East", "Southeast"};
51
52 AbstractScopeWidget::AbstractScopeWidget(bool trackMouse, QWidget *parent) :
53         QWidget(parent)
54         , m_mousePos(0, 0)
55         , m_mouseWithinWidget(false)
56         , offset(5)
57         , m_accelFactorHUD(1)
58         , m_accelFactorScope(1)
59         , m_accelFactorBackground(1)
60         , m_semaphoreHUD(1)
61         , m_semaphoreScope(1)
62         , m_semaphoreBackground(1)
63         , initialDimensionUpdateDone(false)
64         , m_requestForcedUpdate(false)
65         , m_rescaleMinDist(4)
66         , m_rescaleVerticalThreshold(2.0f)
67         , m_rescaleActive(false)
68         , m_rescalePropertiesLocked(false)
69         , m_rescaleFirstRescaleDone(true)
70         , m_rescaleDirection(North)
71
72 {
73     m_scopePalette = QPalette();
74     m_scopePalette.setBrush(QPalette::Window, QBrush(dark2));
75     m_scopePalette.setBrush(QPalette::Base, QBrush(dark));
76     m_scopePalette.setBrush(QPalette::Button, QBrush(dark));
77     m_scopePalette.setBrush(QPalette::Text, QBrush(light));
78     m_scopePalette.setBrush(QPalette::WindowText, QBrush(light));
79     m_scopePalette.setBrush(QPalette::ButtonText, QBrush(light));
80     this->setPalette(m_scopePalette);
81     this->setAutoFillBackground(true);
82
83     m_aAutoRefresh = new QAction(i18n("Auto Refresh"), this);
84     m_aAutoRefresh->setCheckable(true);
85     m_aRealtime = new QAction(i18n("Realtime (with precision loss)"), this);
86     m_aRealtime->setCheckable(true);
87
88     m_menu = new QMenu(this);
89     // Disabled dark palette on menus since it breaks up with some themes: kdenlive issue #2950
90     //m_menu->setPalette(m_scopePalette);
91     m_menu->addAction(m_aAutoRefresh);
92     m_menu->addAction(m_aRealtime);
93
94     this->setContextMenuPolicy(Qt::CustomContextMenu);
95
96     bool b = true;
97     b &= connect(this, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(customContextMenuRequested(QPoint)));
98
99     b &= connect(this, SIGNAL(signalHUDRenderingFinished(uint,uint)), this, SLOT(slotHUDRenderingFinished(uint,uint)));
100     b &= connect(this, SIGNAL(signalScopeRenderingFinished(uint,uint)), this, SLOT(slotScopeRenderingFinished(uint,uint)));
101     b &= connect(this, SIGNAL(signalBackgroundRenderingFinished(uint,uint)), this, SLOT(slotBackgroundRenderingFinished(uint,uint)));
102     b &= connect(m_aRealtime, SIGNAL(toggled(bool)), this, SLOT(slotResetRealtimeFactor(bool)));
103     b &= connect(m_aAutoRefresh, SIGNAL(toggled(bool)), this, SLOT(slotAutoRefreshToggled(bool)));
104     Q_ASSERT(b);
105
106     // Enable mouse tracking if desired.
107     // Causes the mouseMoved signal to be emitted when the mouse moves inside the
108     // widget, even when no mouse button is pressed.
109     this->setMouseTracking(trackMouse);
110 }
111
112 AbstractScopeWidget::~AbstractScopeWidget()
113 {
114     writeConfig();
115
116     delete m_menu;
117     delete m_aAutoRefresh;
118     delete m_aRealtime;
119 }
120
121 void AbstractScopeWidget::init()
122 {
123     m_widgetName = widgetName();
124     readConfig();
125 }
126
127 void AbstractScopeWidget::readConfig()
128 {
129     KSharedConfigPtr config = KGlobal::config();
130     KConfigGroup scopeConfig(config, configName());
131     m_aAutoRefresh->setChecked(scopeConfig.readEntry("autoRefresh", true));
132     m_aRealtime->setChecked(scopeConfig.readEntry("realtime", false));
133     scopeConfig.sync();
134 }
135
136 void AbstractScopeWidget::writeConfig()
137 {
138     KSharedConfigPtr config = KGlobal::config();
139     KConfigGroup scopeConfig(config, configName());
140     scopeConfig.writeEntry("autoRefresh", m_aAutoRefresh->isChecked());
141     scopeConfig.writeEntry("realtime", m_aRealtime->isChecked());
142     scopeConfig.sync();
143 }
144
145 QString AbstractScopeWidget::configName()
146 {
147     return "Scope_" + m_widgetName;
148 }
149
150 void AbstractScopeWidget::prodHUDThread()
151 {
152     if (this->visibleRegion().isEmpty()) {
153 #ifdef DEBUG_ASW
154         qDebug() << "Scope " << m_widgetName << " is not visible. Not calculating HUD.";
155 #endif
156     } else {
157         if (m_semaphoreHUD.tryAcquire(1)) {
158             Q_ASSERT(!m_threadHUD.isRunning());
159
160             m_newHUDFrames.fetchAndStoreRelaxed(0);
161             m_newHUDUpdates.fetchAndStoreRelaxed(0);
162             m_threadHUD = QtConcurrent::run(this, &AbstractScopeWidget::renderHUD, m_accelFactorHUD);
163 #ifdef DEBUG_ASW
164             qDebug() << "HUD thread started in " << m_widgetName;
165 #endif
166
167         }
168 #ifdef DEBUG_ASW
169         else {
170             qDebug() << "HUD semaphore locked, not prodding in " << m_widgetName << ". Thread running: " << m_threadHUD.isRunning();
171         }
172 #endif
173     }
174 }
175
176 void AbstractScopeWidget::prodScopeThread()
177 {
178     // Only start a new thread if the scope is actually visible
179     // and not hidden by another widget on the stack and if user want the scope to update.
180     if (this->visibleRegion().isEmpty() || (!m_aAutoRefresh->isChecked() && !m_requestForcedUpdate)) {
181 #ifdef DEBUG_ASW
182         qDebug() << "Scope " << m_widgetName << " is not visible. Not calculating scope.";
183 #endif
184     } else {
185         // Try to acquire the semaphore. This must only succeed if m_threadScope is not running
186         // anymore. Therefore the semaphore must NOT be released before m_threadScope ends.
187         // If acquiring the semaphore fails, the thread is still running.
188         if (m_semaphoreScope.tryAcquire(1)) {
189             Q_ASSERT(!m_threadScope.isRunning());
190
191             m_newScopeFrames.fetchAndStoreRelaxed(0);
192             m_newScopeUpdates.fetchAndStoreRelaxed(0);
193
194             Q_ASSERT(m_accelFactorScope > 0);
195
196             // See http://doc.qt.nokia.com/latest/qtconcurrentrun.html#run about
197             // running member functions in a thread
198             m_threadScope = QtConcurrent::run(this, &AbstractScopeWidget::renderScope, m_accelFactorScope);
199             m_requestForcedUpdate = false;
200
201 #ifdef DEBUG_ASW
202             qDebug() << "Scope thread started in " << m_widgetName;
203 #endif
204
205         } else {
206 #ifdef DEBUG_ASW
207             qDebug() << "Scope semaphore locked, not prodding in " << m_widgetName << ". Thread running: " << m_threadScope.isRunning();
208 #endif
209         }
210     }
211 }
212 void AbstractScopeWidget::prodBackgroundThread()
213 {
214     if (this->visibleRegion().isEmpty()) {
215 #ifdef DEBUG_ASW
216         qDebug() << "Scope " << m_widgetName << " is not visible. Not calculating background.";
217 #endif
218     } else {
219         if (m_semaphoreBackground.tryAcquire(1)) {
220             Q_ASSERT(!m_threadBackground.isRunning());
221
222             m_newBackgroundFrames.fetchAndStoreRelaxed(0);
223             m_newBackgroundUpdates.fetchAndStoreRelaxed(0);
224             m_threadBackground = QtConcurrent::run(this, &AbstractScopeWidget::renderBackground, m_accelFactorBackground);
225
226 #ifdef DEBUG_ASW
227             qDebug() << "Background thread started in " << m_widgetName;
228 #endif
229
230         } else {
231 #ifdef DEBUG_ASW
232             qDebug() << "Background semaphore locked, not prodding in " << m_widgetName << ". Thread running: " << m_threadBackground.isRunning();
233 #endif
234         }
235     }
236 }
237
238 void AbstractScopeWidget::forceUpdate(bool doUpdate)
239 {
240 #ifdef DEBUG_ASW
241     qDebug() << "Forced update called in " << widgetName() << ". Arg: " << doUpdate;
242 #endif
243
244     if (!doUpdate) {
245         return;
246     }
247     m_requestForcedUpdate = true;
248     m_newHUDUpdates.fetchAndAddRelaxed(1);
249     m_newScopeUpdates.fetchAndAddRelaxed(1);
250     m_newBackgroundUpdates.fetchAndAddRelaxed(1);
251     prodHUDThread();
252     prodScopeThread();
253     prodBackgroundThread();
254 }
255 void AbstractScopeWidget::forceUpdateHUD()
256 {
257     m_newHUDUpdates.fetchAndAddRelaxed(1);
258     prodHUDThread();
259
260 }
261 void AbstractScopeWidget::forceUpdateScope()
262 {
263     m_newScopeUpdates.fetchAndAddRelaxed(1);
264     m_requestForcedUpdate = true;
265     prodScopeThread();
266
267 }
268 void AbstractScopeWidget::forceUpdateBackground()
269 {
270     m_newBackgroundUpdates.fetchAndAddRelaxed(1);
271     prodBackgroundThread();
272
273 }
274
275
276 ///// Events /////
277
278
279 void AbstractScopeWidget::resizeEvent(QResizeEvent *event)
280 {
281     // Update the dimension of the available rect for painting
282     m_scopeRect = scopeRect();
283     forceUpdate();
284
285     QWidget::resizeEvent(event);
286 }
287
288 void AbstractScopeWidget::showEvent(QShowEvent *event)
289 {
290     QWidget::showEvent(event);
291     m_scopeRect = scopeRect();
292 }
293
294 void AbstractScopeWidget::paintEvent(QPaintEvent *)
295 {
296     QPainter davinci(this);
297     davinci.drawImage(m_scopeRect.topLeft(), m_imgBackground);
298     davinci.drawImage(m_scopeRect.topLeft(), m_imgScope);
299     davinci.drawImage(m_scopeRect.topLeft(), m_imgHUD);
300 }
301
302 void AbstractScopeWidget::mousePressEvent(QMouseEvent *event)
303 {
304     if (event->button() == Qt::LeftButton) {
305         // Rescaling mode starts
306         m_rescaleActive = true;
307         m_rescalePropertiesLocked = false;
308         m_rescaleFirstRescaleDone = false;
309         m_rescaleStartPoint = event->pos();
310         m_rescaleModifiers = event->modifiers();
311     }
312 }
313 void AbstractScopeWidget::mouseReleaseEvent(QMouseEvent *event)
314 {
315     m_rescaleActive = false;
316     m_rescalePropertiesLocked = false;
317
318     if (!m_aAutoRefresh->isChecked()) {
319         m_requestForcedUpdate = true;
320     }
321     prodHUDThread();
322     prodScopeThread();
323     prodBackgroundThread();
324     QWidget::mouseReleaseEvent(event);
325 }
326 void AbstractScopeWidget::mouseMoveEvent(QMouseEvent *event)
327 {
328     m_mousePos = event->pos();
329     m_mouseWithinWidget = true;
330     emit signalMousePositionChanged();
331
332     QPoint movement = event->pos()-m_rescaleStartPoint;
333
334     if (m_rescaleActive) {
335         if (m_rescalePropertiesLocked) {
336             // Direction is known, now adjust parameters
337
338             // Reset the starting point to make the next moveEvent relative to the current one
339             m_rescaleStartPoint = event->pos();
340
341
342             if (!m_rescaleFirstRescaleDone) {
343                 // We have just learned the desired direction; Normalize the movement to one pixel
344                 // to avoid a jump by m_rescaleMinDist
345
346                 if (movement.x() != 0) {
347                     movement.setX(movement.x() / abs(movement.x()));
348                 }
349                 if (movement.y() != 0) {
350                     movement.setY(movement.y() / abs(movement.y()));
351                 }
352
353                 m_rescaleFirstRescaleDone = true;
354             }
355
356             handleMouseDrag(movement, m_rescaleDirection, m_rescaleModifiers);
357
358
359
360         } else {
361             // Detect the movement direction here.
362             // This algorithm relies on the aspect ratio of dy/dx (size and signum).
363             if (movement.manhattanLength() > m_rescaleMinDist) {
364                 float diff = ((float) movement.y())/movement.x();
365
366                 if (abs(diff) > m_rescaleVerticalThreshold || movement.x() == 0) {
367                     m_rescaleDirection = North;
368                 } else if (abs(diff) < 1/m_rescaleVerticalThreshold) {
369                     m_rescaleDirection = East;
370                 } else if (diff < 0) {
371                     m_rescaleDirection = Northeast;
372                 } else {
373                     m_rescaleDirection = Southeast;
374                 }
375 #ifdef DEBUG_ASW
376                 qDebug() << "Diff is " << diff << "; chose " << directions[m_rescaleDirection] << " as direction";
377 #endif
378                 m_rescalePropertiesLocked = true;
379             }
380         }
381     }
382 }
383
384 void AbstractScopeWidget::leaveEvent(QEvent *)
385 {
386     m_mouseWithinWidget = false;
387     emit signalMousePositionChanged();
388 }
389
390 void AbstractScopeWidget::customContextMenuRequested(const QPoint &pos)
391 {
392     m_menu->exec(this->mapToGlobal(pos));
393 }
394
395 uint AbstractScopeWidget::calculateAccelFactorHUD(uint oldMseconds, uint)
396 {
397     return ceil((float)oldMseconds*REALTIME_FPS / 1000);
398 }
399 uint AbstractScopeWidget::calculateAccelFactorScope(uint oldMseconds, uint)
400 {
401     return ceil((float)oldMseconds*REALTIME_FPS / 1000);
402 }
403 uint AbstractScopeWidget::calculateAccelFactorBackground(uint oldMseconds, uint)
404 {
405     return ceil((float)oldMseconds*REALTIME_FPS / 1000);
406 }
407
408
409 ///// Slots /////
410
411 void AbstractScopeWidget::slotHUDRenderingFinished(uint mseconds, uint oldFactor)
412 {
413 #ifdef DEBUG_ASW
414     qDebug() << "HUD rendering has finished in " << mseconds << " ms, waiting for termination in " << m_widgetName;
415 #endif
416     m_threadHUD.waitForFinished();
417     m_imgHUD = m_threadHUD.result();
418
419     m_semaphoreHUD.release(1);
420     this->update();
421
422     int accel;
423     if (m_aRealtime->isChecked()) {
424         accel = calculateAccelFactorHUD(mseconds, oldFactor);
425         if (m_accelFactorHUD < 1) {
426             accel = 1;
427         }
428         m_accelFactorHUD = accel;
429     }
430
431     if ((m_newHUDFrames > 0 && m_aAutoRefresh->isChecked()) || m_newHUDUpdates > 0) {
432 #ifdef DEBUG_ASW
433         qDebug() << "Trying to start a new HUD thread for " << m_widgetName
434                 << ". New frames/updates: " << m_newHUDFrames << "/" << m_newHUDUpdates;
435 #endif
436         prodHUDThread();
437     }
438 }
439
440 void AbstractScopeWidget::slotScopeRenderingFinished(uint mseconds, uint oldFactor)
441 {
442     // The signal can be received before the thread has really finished. So we
443     // need to wait until it has really finished before starting a new thread.
444 #ifdef DEBUG_ASW
445     qDebug() << "Scope rendering has finished in " << mseconds << " ms, waiting for termination in " << m_widgetName;
446 #endif
447     m_threadScope.waitForFinished();
448     m_imgScope = m_threadScope.result();
449
450     // The scope thread has finished. Now we can release the semaphore, allowing a new thread.
451     // See prodScopeThread where the semaphore is acquired again.
452     m_semaphoreScope.release(1);
453     this->update();
454
455     // Calculate the acceleration factor hint to get «realtime» updates.
456     int accel;
457     if (m_aRealtime->isChecked()) {
458         accel = calculateAccelFactorScope(mseconds, oldFactor);
459         if (accel < 1) {
460             // If mseconds happens to be 0.
461             accel = 1;
462         }
463         // Don't directly calculate with m_accelFactorScope as we are dealing with concurrency.
464         // If m_accelFactorScope is set to 0 at the wrong moment, who knows what might happen
465         // then :) Therefore use a local variable.
466         m_accelFactorScope = accel;
467     }
468
469     if ((m_newScopeFrames > 0 && m_aAutoRefresh->isChecked()) || m_newScopeUpdates > 0) {
470 #ifdef DEBUG_ASW
471         qDebug() << "Trying to start a new scope thread for " << m_widgetName
472                 << ". New frames/updates: " << m_newScopeFrames << "/" << m_newScopeUpdates;
473 #endif
474         prodScopeThread();
475     }
476 }
477
478 void AbstractScopeWidget::slotBackgroundRenderingFinished(uint mseconds, uint oldFactor)
479 {
480 #ifdef DEBUG_ASW
481     qDebug() << "Background rendering has finished in " << mseconds << " ms, waiting for termination in " << m_widgetName;
482 #endif
483     m_threadBackground.waitForFinished();
484     m_imgBackground = m_threadBackground.result();
485
486     m_semaphoreBackground.release(1);
487     this->update();
488
489     int accel;
490     if (m_aRealtime->isChecked()) {
491         accel = calculateAccelFactorBackground(mseconds, oldFactor);
492         if (m_accelFactorBackground < 1) {
493             accel = 1;
494         }
495         m_accelFactorBackground = accel;
496     }
497
498     if ((m_newBackgroundFrames > 0 && m_aAutoRefresh->isChecked()) || m_newBackgroundUpdates > 0) {
499 #ifdef DEBUG_ASW
500         qDebug() << "Trying to start a new background thread for " << m_widgetName
501                 << ". New frames/updates: " << m_newBackgroundFrames << "/" << m_newBackgroundUpdates;
502 #endif
503         prodBackgroundThread();;
504     }
505 }
506
507 void AbstractScopeWidget::slotRenderZoneUpdated()
508 {
509     m_newHUDFrames.fetchAndAddRelaxed(1);
510     m_newScopeFrames.fetchAndAddRelaxed(1);
511     m_newBackgroundFrames.fetchAndAddRelaxed(1);
512
513 #ifdef DEBUG_ASW
514     qDebug() << "Data incoming at " << widgetName() << ". New frames total HUD/Scope/Background: " << m_newHUDFrames
515             << "/" << m_newScopeFrames << "/" << m_newBackgroundFrames;
516 #endif
517
518     if (this->visibleRegion().isEmpty()) {
519 #ifdef DEBUG_ASW
520         qDebug() << "Scope of widget " << m_widgetName << " is not at the top, not rendering.";
521 #endif
522     } else {
523         if (m_aAutoRefresh->isChecked()) {
524             prodHUDThread();
525             prodScopeThread();
526             prodBackgroundThread();
527         }
528     }
529 }
530
531 void AbstractScopeWidget::slotResetRealtimeFactor(bool realtimeChecked)
532 {
533     if (!realtimeChecked) {
534         m_accelFactorHUD = 1;
535         m_accelFactorScope = 1;
536         m_accelFactorBackground = 1;
537     }
538 }
539
540 bool AbstractScopeWidget::autoRefreshEnabled() const
541 {
542     return m_aAutoRefresh->isChecked();
543 }
544
545 void AbstractScopeWidget::slotAutoRefreshToggled(bool autoRefresh)
546 {
547 #ifdef DEBUG_ASW
548     qDebug() << "Auto-refresh switched to " << autoRefresh << " in " << widgetName()
549             << " (Visible: " << isVisible() << "/" << this->visibleRegion().isEmpty() << ")";
550 #endif
551     if (isVisible()) {
552         // Notify listeners whether we accept new frames now
553         emit requestAutoRefresh(autoRefresh);
554     }
555     // TODO only if depends on input
556     if (autoRefresh) {
557         //forceUpdate();
558         m_requestForcedUpdate = true;
559     }
560 }
561
562 void AbstractScopeWidget::handleMouseDrag(const QPoint &, const RescaleDirection, const Qt::KeyboardModifiers) { }
563
564
565 #ifdef DEBUG_ASW
566 #undef DEBUG_ASW
567 #endif
568
569 #include "abstractscopewidget.moc"