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