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