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