]> git.sesse.net Git - kdenlive/blob - src/abstractscopewidget.cpp
7109704c8f4ffc2f84bbfecbf4e3ca8801233453
[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 const int REALTIME_FPS = 30;
24
25 const QColor light(250, 238, 226, 255);
26 const QColor dark(40,  40,  39, 255);
27 const QColor dark2(25,  25,  23, 255);
28
29 const QPen AbstractScopeWidget::penThick(QBrush(QColor(250, 250, 250)),     2, Qt::SolidLine);
30 const QPen AbstractScopeWidget::penThin(QBrush(QColor(250, 250, 250)),     1, Qt::SolidLine);
31 const QPen AbstractScopeWidget::penLight(QBrush(QColor(200, 200, 250, 150)), 1, Qt::SolidLine);
32 const QPen AbstractScopeWidget::penLightDots(QBrush(QColor(200, 200, 250, 150)), 1, Qt::DotLine);
33 const QPen AbstractScopeWidget::penDark(QBrush(QColor(0, 0, 20, 250)),      1, Qt::SolidLine);
34 const QPen AbstractScopeWidget::penDarkDots(QBrush(QColor(0, 0, 20, 250)),      1, Qt::DotLine);
35
36 AbstractScopeWidget::AbstractScopeWidget(Monitor *projMonitor, Monitor *clipMonitor, bool trackMouse, QWidget *parent) :
37         QWidget(parent),
38         m_projMonitor(projMonitor),
39         m_clipMonitor(clipMonitor),
40         m_mousePos(0, 0),
41         m_mouseWithinWidget(false),
42         offset(5),
43         m_accelFactorHUD(1),
44         m_accelFactorScope(1),
45         m_accelFactorBackground(1),
46         m_semaphoreHUD(1),
47         m_semaphoreScope(1),
48         m_semaphoreBackground(1),
49         initialDimensionUpdateDone(false),
50         m_requestForcedUpdate(false)
51
52 {
53     m_scopePalette = QPalette();
54     m_scopePalette.setBrush(QPalette::Window, QBrush(dark2));
55     m_scopePalette.setBrush(QPalette::Base, QBrush(dark));
56     m_scopePalette.setBrush(QPalette::Button, QBrush(dark));
57     m_scopePalette.setBrush(QPalette::Text, QBrush(light));
58     m_scopePalette.setBrush(QPalette::WindowText, QBrush(light));
59     m_scopePalette.setBrush(QPalette::ButtonText, QBrush(light));
60     this->setPalette(m_scopePalette);
61     this->setAutoFillBackground(true);
62
63     m_aAutoRefresh = new QAction(i18n("Auto Refresh"), this);
64     m_aAutoRefresh->setCheckable(true);
65     m_aRealtime = new QAction(i18n("Realtime (with precision loss)"), this);
66     m_aRealtime->setCheckable(true);
67
68     m_menu = new QMenu(this);
69     m_menu->setPalette(m_scopePalette);
70     m_menu->addAction(m_aAutoRefresh);
71     m_menu->addAction(m_aRealtime);
72
73     this->setContextMenuPolicy(Qt::CustomContextMenu);
74
75     m_activeRender = (m_clipMonitor->isActive()) ? m_clipMonitor->render : m_projMonitor->render;
76
77     bool b = true;
78     b &= connect(this, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(customContextMenuRequested(QPoint)));
79
80     //b &= connect(m_activeRender, SIGNAL(rendererPosition(int)), this, SLOT(slotRenderZoneUpdated()));
81     b &= connect(m_activeRender, SIGNAL(frameUpdated(QImage)), this, SLOT(slotRenderZoneUpdated(QImage)));
82
83     b &= connect(this, SIGNAL(signalHUDRenderingFinished(uint, uint)), this, SLOT(slotHUDRenderingFinished(uint, uint)));
84     b &= connect(this, SIGNAL(signalScopeRenderingFinished(uint, uint)), this, SLOT(slotScopeRenderingFinished(uint, uint)));
85     b &= connect(this, SIGNAL(signalBackgroundRenderingFinished(uint, uint)), this, SLOT(slotBackgroundRenderingFinished(uint, uint)));
86     b &= connect(m_aRealtime, SIGNAL(toggled(bool)), this, SLOT(slotResetRealtimeFactor(bool)));
87     b &= connect(m_aAutoRefresh, SIGNAL(toggled(bool)), this, SLOT(slotAutoRefreshToggled(bool)));
88     Q_ASSERT(b);
89
90     // Enable mouse tracking if desired.
91     // Causes the mouseMoved signal to be emitted when the mouse moves inside the
92     // widget, even when no mouse button is pressed.
93     this->setMouseTracking(trackMouse);
94 }
95
96 AbstractScopeWidget::~AbstractScopeWidget()
97 {
98     writeConfig();
99
100     delete m_menu;
101     delete m_aAutoRefresh;
102     delete m_aRealtime;
103 }
104
105 void AbstractScopeWidget::init()
106 {
107     m_widgetName = widgetName();
108     readConfig();
109 }
110
111 void AbstractScopeWidget::readConfig()
112 {
113     KSharedConfigPtr config = KGlobal::config();
114     KConfigGroup scopeConfig(config, configName());
115     m_aAutoRefresh->setChecked(scopeConfig.readEntry("autoRefresh", true));
116     m_aRealtime->setChecked(scopeConfig.readEntry("realtime", false));
117     scopeConfig.sync();
118 }
119
120 void AbstractScopeWidget::writeConfig()
121 {
122     KSharedConfigPtr config = KGlobal::config();
123     KConfigGroup scopeConfig(config, configName());
124     scopeConfig.writeEntry("autoRefresh", m_aAutoRefresh->isChecked());
125     scopeConfig.writeEntry("realtime", m_aRealtime->isChecked());
126     scopeConfig.sync();
127 }
128
129 QString AbstractScopeWidget::configName()
130 {
131     return "Scope_" + m_widgetName;
132 }
133
134 void AbstractScopeWidget::prodHUDThread()
135 {
136     if (this->visibleRegion().isEmpty()) {
137 //        qDebug() << "Scope " << m_widgetName << " is not visible. Not calculating HUD.";
138     } else {
139         if (m_semaphoreHUD.tryAcquire(1)) {
140             Q_ASSERT(!m_threadHUD.isRunning());
141
142             m_newHUDFrames.fetchAndStoreRelaxed(0);
143             m_newHUDUpdates.fetchAndStoreRelaxed(0);
144             m_threadHUD = QtConcurrent::run(this, &AbstractScopeWidget::renderHUD, m_accelFactorHUD);
145 //            qDebug() << "HUD thread started in " << m_widgetName;
146
147         } else {
148 //            qDebug() << "HUD semaphore locked, not prodding in " << m_widgetName << ". Thread running: " << m_threadHUD.isRunning();
149         }
150     }
151 }
152
153 void AbstractScopeWidget::prodScopeThread()
154 {
155     // Only start a new thread if the scope is actually visible
156     // and not hidden by another widget on the stack and if user want the scope to update.
157     if (this->visibleRegion().isEmpty() || (!m_aAutoRefresh->isChecked() && !m_requestForcedUpdate)) {
158 //        qDebug() << "Scope " << m_widgetName << " is not visible. Not calculating scope.";
159     } else {
160         // Try to acquire the semaphore. This must only succeed if m_threadScope is not running
161         // anymore. Therefore the semaphore must NOT be released before m_threadScope ends.
162         // If acquiring the semaphore fails, the thread is still running.
163         if (m_semaphoreScope.tryAcquire(1)) {
164             Q_ASSERT(!m_threadScope.isRunning());
165
166             m_newScopeFrames.fetchAndStoreRelaxed(0);
167             m_newScopeUpdates.fetchAndStoreRelaxed(0);
168
169             Q_ASSERT(m_accelFactorScope > 0);
170
171             // See http://doc.qt.nokia.com/latest/qtconcurrentrun.html#run about
172             // running member functions in a thread
173             m_threadScope = QtConcurrent::run(this, &AbstractScopeWidget::renderScope, m_accelFactorScope, m_scopeImage);
174             m_requestForcedUpdate = false;
175
176 //            qDebug() << "Scope thread started in " << m_widgetName;
177
178         } else {
179 //            qDebug() << "Scope semaphore locked, not prodding in " << m_widgetName << ". Thread running: " << m_threadScope.isRunning();
180         }
181     }
182 }
183 void AbstractScopeWidget::prodBackgroundThread()
184 {
185     if (this->visibleRegion().isEmpty()) {
186 //        qDebug() << "Scope " << m_widgetName << " is not visible. Not calculating background.";
187     } else {
188         if (m_semaphoreBackground.tryAcquire(1)) {
189             Q_ASSERT(!m_threadBackground.isRunning());
190
191             m_newBackgroundFrames.fetchAndStoreRelaxed(0);
192             m_newBackgroundUpdates.fetchAndStoreRelaxed(0);
193             m_threadBackground = QtConcurrent::run(this, &AbstractScopeWidget::renderBackground, m_accelFactorBackground);
194 //            qDebug() << "Background thread started in " << m_widgetName;
195
196         } else {
197 //            qDebug() << "Background semaphore locked, not prodding in " << m_widgetName << ". Thread running: " << m_threadBackground.isRunning();
198         }
199     }
200 }
201
202 void AbstractScopeWidget::forceUpdate(bool doUpdate)
203 {
204 //    qDebug() << "Force update called in " << widgetName() << ". Arg: " << doUpdate;
205     if (!doUpdate) {
206         return;
207     }
208     m_requestForcedUpdate = true;
209     m_newHUDUpdates.fetchAndAddRelaxed(1);
210     m_newScopeUpdates.fetchAndAddRelaxed(1);
211     m_newBackgroundUpdates.fetchAndAddRelaxed(1);
212     prodHUDThread();
213     prodScopeThread();
214     prodBackgroundThread();
215 }
216 void AbstractScopeWidget::forceUpdateHUD()
217 {
218     m_newHUDUpdates.fetchAndAddRelaxed(1);
219     prodHUDThread();
220
221 }
222 void AbstractScopeWidget::forceUpdateScope()
223 {
224     m_newScopeUpdates.fetchAndAddRelaxed(1);
225     m_requestForcedUpdate = true;
226     prodScopeThread();
227
228 }
229 void AbstractScopeWidget::forceUpdateBackground()
230 {
231     m_newBackgroundUpdates.fetchAndAddRelaxed(1);
232     prodBackgroundThread();
233
234 }
235
236
237 ///// Events /////
238
239 void AbstractScopeWidget::mouseReleaseEvent(QMouseEvent *event)
240 {
241     if (!m_aAutoRefresh->isChecked()) {
242         m_requestForcedUpdate = true;
243         m_activeRender->sendFrameUpdate();
244     }
245     prodHUDThread();
246     prodScopeThread();
247     prodBackgroundThread();
248     QWidget::mouseReleaseEvent(event);
249 }
250
251 void AbstractScopeWidget::resizeEvent(QResizeEvent *event)
252 {
253     // Update the dimension of the available rect for painting
254     m_scopeRect = scopeRect();
255     forceUpdate();
256
257     QWidget::resizeEvent(event);
258 }
259
260 void AbstractScopeWidget::showEvent(QShowEvent *event)
261 {
262     QWidget::showEvent(event);
263     m_scopeRect = scopeRect();
264 }
265
266 void AbstractScopeWidget::paintEvent(QPaintEvent *)
267 {
268     QPainter davinci(this);
269     davinci.drawImage(m_scopeRect.topLeft(), m_imgBackground);
270     davinci.drawImage(m_scopeRect.topLeft(), m_imgScope);
271     davinci.drawImage(m_scopeRect.topLeft(), m_imgHUD);
272 }
273
274 void AbstractScopeWidget::mouseMoveEvent(QMouseEvent *event)
275 {
276     m_mousePos = event->pos();
277     m_mouseWithinWidget = true;
278     emit signalMousePositionChanged();
279 }
280 void AbstractScopeWidget::leaveEvent(QEvent *)
281 {
282     m_mouseWithinWidget = false;
283     emit signalMousePositionChanged();
284 }
285
286 void AbstractScopeWidget::customContextMenuRequested(const QPoint &pos)
287 {
288     m_menu->exec(this->mapToGlobal(pos));
289 }
290
291 uint AbstractScopeWidget::calculateAccelFactorHUD(uint oldMseconds, uint)
292 {
293     return ceil((float)oldMseconds*REALTIME_FPS / 1000);
294 }
295 uint AbstractScopeWidget::calculateAccelFactorScope(uint oldMseconds, uint)
296 {
297     return ceil((float)oldMseconds*REALTIME_FPS / 1000);
298 }
299 uint AbstractScopeWidget::calculateAccelFactorBackground(uint oldMseconds, uint)
300 {
301     return ceil((float)oldMseconds*REALTIME_FPS / 1000);
302 }
303
304
305 ///// Slots /////
306
307 void AbstractScopeWidget::slotHUDRenderingFinished(uint mseconds, uint oldFactor)
308 {
309 //    qDebug() << "HUD rendering has finished, waiting for termination in " << m_widgetName;
310     m_threadHUD.waitForFinished();
311     m_imgHUD = m_threadHUD.result();
312
313     m_semaphoreHUD.release(1);
314     this->update();
315
316     int accel;
317     if (m_aRealtime->isChecked()) {
318         accel = calculateAccelFactorHUD(mseconds, oldFactor);
319         if (m_accelFactorHUD < 1) {
320             accel = 1;
321         }
322         m_accelFactorHUD = accel;
323     }
324
325     if ((m_newHUDFrames > 0 && m_aAutoRefresh->isChecked()) || m_newHUDUpdates > 0) {
326 //        qDebug() << "Trying to start a new HUD thread for " << m_widgetName
327 //                << ". New frames/updates: " << m_newHUDFrames << "/" << m_newHUDUpdates;
328         prodHUDThread();;
329     }
330 }
331
332 void AbstractScopeWidget::slotScopeRenderingFinished(uint mseconds, uint oldFactor)
333 {
334     // The signal can be received before the thread has really finished. So we
335     // need to wait until it has really finished before starting a new thread.
336 //    qDebug() << "Scope rendering has finished, waiting for termination in " << m_widgetName;
337     m_threadScope.waitForFinished();
338     m_imgScope = m_threadScope.result();
339
340     // The scope thread has finished. Now we can release the semaphore, allowing a new thread.
341     // See prodScopeThread where the semaphore is acquired again.
342     m_semaphoreScope.release(1);
343     this->update();
344
345     // Calculate the acceleration factor hint to get «realtime» updates.
346     int accel;
347     if (m_aRealtime->isChecked()) {
348         accel = calculateAccelFactorScope(mseconds, oldFactor);
349         if (accel < 1) {
350             // If mseconds happens to be 0.
351             accel = 1;
352         }
353         // Don't directly calculate with m_accelFactorScope as we are dealing with concurrency.
354         // If m_accelFactorScope is set to 0 at the wrong moment, who knows what might happen
355         // then :) Therefore use a local variable.
356         m_accelFactorScope = accel;
357     }
358
359     if ((m_newScopeFrames > 0 && m_aAutoRefresh->isChecked()) || m_newScopeUpdates > 0) {
360 //        qDebug() << "Trying to start a new scope thread for " << m_widgetName
361 //                << ". New frames/updates: " << m_newScopeFrames << "/" << m_newScopeUpdates;
362         prodScopeThread();
363     }
364 }
365
366 void AbstractScopeWidget::slotBackgroundRenderingFinished(uint mseconds, uint oldFactor)
367 {
368 //    qDebug() << "Background rendering has finished, waiting for termination in " << m_widgetName;
369     m_threadBackground.waitForFinished();
370     m_imgBackground = m_threadBackground.result();
371
372     m_semaphoreBackground.release(1);
373     this->update();
374
375     int accel;
376     if (m_aRealtime->isChecked()) {
377         accel = calculateAccelFactorBackground(mseconds, oldFactor);
378         if (m_accelFactorBackground < 1) {
379             accel = 1;
380         }
381         m_accelFactorBackground = accel;
382     }
383
384     if ((m_newBackgroundFrames > 0 && m_aAutoRefresh->isChecked()) || m_newBackgroundUpdates > 0) {
385 //        qDebug() << "Trying to start a new background thread for " << m_widgetName
386 //                << ". New frames/updates: " << m_newBackgroundFrames << "/" << m_newBackgroundUpdates;
387         prodBackgroundThread();;
388     }
389 }
390
391 void AbstractScopeWidget::slotActiveMonitorChanged(bool isClipMonitor)
392 {
393 //    qDebug() << "Active monitor has changed in " << m_widgetName << ". Is the clip monitor active now? " << isClipMonitor;
394
395     bool b = m_activeRender->disconnect(this);
396     Q_ASSERT(b);
397
398     m_activeRender = (isClipMonitor) ? m_clipMonitor->render : m_projMonitor->render;
399
400     //b &= connect(m_activeRender, SIGNAL(rendererPosition(int)), this, SLOT(slotRenderZoneUpdated()));
401     b &= connect(m_activeRender, SIGNAL(frameUpdated(QImage)), this, SLOT(slotRenderZoneUpdated(QImage)));
402     Q_ASSERT(b);
403
404     // Update the scope for the new monitor.
405     prodHUDThread();
406     prodScopeThread();
407     prodBackgroundThread();
408 }
409
410 void AbstractScopeWidget::slotRenderZoneUpdated()
411 {
412     m_newHUDFrames.fetchAndAddRelaxed(1);
413     m_newScopeFrames.fetchAndAddRelaxed(1);
414     m_newBackgroundFrames.fetchAndAddRelaxed(1);
415
416 //    qDebug() << "Monitor incoming. New frames total HUD/Scope/Background: " << m_newHUDFrames
417 //            << "/" << m_newScopeFrames << "/" << m_newBackgroundFrames;
418
419     if (this->visibleRegion().isEmpty()) {
420 //        qDebug() << "Scope of widget " << m_widgetName << " is not at the top, not rendering.";
421     } else {
422         if (m_aAutoRefresh->isChecked()) {
423             prodHUDThread();
424             prodScopeThread();
425             prodBackgroundThread();
426         }
427     }
428 }
429
430 void AbstractScopeWidget::slotRenderZoneUpdated(QImage frame)
431 {
432     m_scopeImage = frame;
433     slotRenderZoneUpdated();
434 }
435
436 void AbstractScopeWidget::slotResetRealtimeFactor(bool realtimeChecked)
437 {
438     if (!realtimeChecked) {
439         m_accelFactorHUD = 1;
440         m_accelFactorScope = 1;
441         m_accelFactorBackground = 1;
442     }
443 }
444
445 bool AbstractScopeWidget::autoRefreshEnabled()
446 {
447     return m_aAutoRefresh->isChecked();
448 }
449
450 void AbstractScopeWidget::slotAutoRefreshToggled(bool autoRefresh)
451 {
452     if (isVisible()) emit requestAutoRefresh(autoRefresh);
453     // TODO only if depends on input
454     if (autoRefresh) {
455         //forceUpdate();
456         m_requestForcedUpdate = true;
457         m_activeRender->sendFrameUpdate();
458     }
459 }