monitor.cpp 88.6 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/***************************************************************************
 *   Copyright (C) 2007 by Jean-Baptiste Mardelle (jb@kdenlive.org)        *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA          *
 ***************************************************************************/

Vincent Pinon's avatar
Vincent Pinon committed
20
#include "monitor.h"
Nicolas Carion's avatar
Nicolas Carion committed
21
#include "bin/bin.h"
22
#include "bin/projectclip.h"
23
#include "lib/localeHandling.h"
Nicolas Carion's avatar
Nicolas Carion committed
24
25
26
27
#include "core.h"
#include "dialogs/profilesdialog.h"
#include "doc/kdenlivedoc.h"
#include "doc/kthumb.h"
28
#include "glwidget.h"
Nicolas Carion's avatar
Nicolas Carion committed
29
30
31
32
#include "kdenlivesettings.h"
#include "lib/audio/audioStreamInfo.h"
#include "mainwindow.h"
#include "mltcontroller/clipcontroller.h"
33
#include "monitorproxy.h"
34
#include "profiles/profilemodel.hpp"
Nicolas Carion's avatar
Nicolas Carion committed
35
#include "project/projectmanager.h"
36
#include "qmlmanager.h"
37
#include "recmanager.h"
38
39
#include "jobs/jobmanager.h"
#include "jobs/cutclipjob.h"
40
#include "scopes/monitoraudiolevel.h"
41
#include "timeline2/model/snapmodel.hpp"
42
#include "transitions/transitionsrepository.hpp"
43
#include "utils/thumbnailcache.hpp"
44

45
#include "klocalizedstring.h"
46
#include <KDualAction>
Nicolas Carion's avatar
Nicolas Carion committed
47
#include <KFileWidget>
Nicolas Carion's avatar
Nicolas Carion committed
48
#include <KMessageWidget>
49
#include <KMessageBox>
Nicolas Carion's avatar
Nicolas Carion committed
50
51
#include <KRecentDirs>
#include <KSelectAction>
52
#include <KWindowConfig>
Vincent Pinon's avatar
Vincent Pinon committed
53
#include <kio_version.h>
54

Laurent Montel's avatar
Laurent Montel committed
55
#include "kdenlive_debug.h"
Vincent Pinon's avatar
Vincent Pinon committed
56
#include <QScreen>
57
#include <QDrag>
Nicolas Carion's avatar
Nicolas Carion committed
58
#include <QMenu>
59
#include <QMimeData>
Nicolas Carion's avatar
Nicolas Carion committed
60
#include <QMouseEvent>
61
#include <QQuickItem>
62
#include <QScrollBar>
Nicolas Carion's avatar
Nicolas Carion committed
63
64
65
66
#include <QSlider>
#include <QToolBar>
#include <QToolButton>
#include <QVBoxLayout>
67
#include <QWidgetAction>
Nicolas Carion's avatar
Nicolas Carion committed
68
#include <utility>
69
70
#define SEEK_INACTIVE (-1)

71
72
QuickEventEater::QuickEventEater(QObject *parent)
    : QObject(parent)
73
74
75
76
77
{
}

bool QuickEventEater::eventFilter(QObject *obj, QEvent *event)
{
78
    switch (event->type()) {
Laurent Montel's avatar
Laurent Montel committed
79
    case QEvent::DragEnter: {
Nicolas Carion's avatar
Nicolas Carion committed
80
        auto *ev = reinterpret_cast<QDragEnterEvent *>(event);
81
        if (ev->mimeData()->hasFormat(QStringLiteral("kdenlive/effect"))) {
Laurent Montel's avatar
Laurent Montel committed
82
83
            ev->acceptProposedAction();
            return true;
84
        }
Laurent Montel's avatar
Laurent Montel committed
85
86
87
        break;
    }
    case QEvent::DragMove: {
Nicolas Carion's avatar
Nicolas Carion committed
88
        auto *ev = reinterpret_cast<QDragEnterEvent *>(event);
89
        if (ev->mimeData()->hasFormat(QStringLiteral("kdenlive/effect"))) {
Laurent Montel's avatar
Laurent Montel committed
90
91
            ev->acceptProposedAction();
            return true;
92
        }
Laurent Montel's avatar
Laurent Montel committed
93
94
95
        break;
    }
    case QEvent::Drop: {
Nicolas Carion's avatar
Nicolas Carion committed
96
        auto *ev = static_cast<QDropEvent *>(event);
Laurent Montel's avatar
Laurent Montel committed
97
        if (ev) {
98
99
100
101
102
            QStringList effectData;
            effectData << QString::fromUtf8(ev->mimeData()->data(QStringLiteral("kdenlive/effect")));
            QStringList source = QString::fromUtf8(ev->mimeData()->data(QStringLiteral("kdenlive/effectsource"))).split(QLatin1Char('-'));
            effectData << source;
            emit addEffect(effectData);
Laurent Montel's avatar
Laurent Montel committed
103
104
            ev->accept();
            return true;
105
        }
Laurent Montel's avatar
Laurent Montel committed
106
107
        break;
    }
108
    if (event->type() == QEvent::KeyPress) {
Nicolas Carion's avatar
Nicolas Carion committed
109
        auto *ev = static_cast<QKeyEvent *>(event);
110
111
112
113
114
        if (ev) {
            emit doKeyPressEvent(ev);
            return true;
        }
    }
115
116
117
    default:
        break;
    }
118
119
    return QObject::eventFilter(obj, event);
}
120

Nicolas Carion's avatar
Nicolas Carion committed
121
Monitor::Monitor(Kdenlive::MonitorId id, MonitorManager *manager, QWidget *parent)
122
123
124
    : AbstractMonitor(id, manager, parent)
    , m_controller(nullptr)
    , m_glMonitor(nullptr)
125
    , m_snaps(new SnapModel())
126
127
128
129
130
131
    , m_splitEffect(nullptr)
    , m_splitProducer(nullptr)
    , m_dragStarted(false)
    , m_recManager(nullptr)
    , m_loopClipAction(nullptr)
    , m_contextMenu(nullptr)
132
    , m_markerMenu(nullptr)
133
    , m_audioChannels(nullptr)
134
135
136
    , m_loopClipTransition(true)
    , m_editMarker(nullptr)
    , m_forceSizeFactor(0)
137
    , m_offset(id == Kdenlive::ProjectMonitor ? TimelineModel::seekDuration : 0)
138
    , m_lastMonitorSceneType(MonitorSceneDefault)
Nicolas Carion's avatar
Nicolas Carion committed
139
{
Nicolas Carion's avatar
Nicolas Carion committed
140
    auto *layout = new QVBoxLayout;
141
    layout->setContentsMargins(0, 0, 0, 0);
142
    layout->setSpacing(0);
143
144
    // Create container widget
    m_glWidget = new QWidget;
145
    m_glWidget->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding);
Nicolas Carion's avatar
Nicolas Carion committed
146
    auto *glayout = new QGridLayout(m_glWidget);
147
148
149
    glayout->setSpacing(0);
    glayout->setContentsMargins(0, 0, 0, 0);
    // Create QML OpenGL widget
Vincent Pinon's avatar
Vincent Pinon committed
150
    m_glMonitor = new GLWidget(id);
Laurent Montel's avatar
Laurent Montel committed
151
    connect(m_glMonitor, &GLWidget::passKeyEvent, this, &Monitor::doKeyPressEvent);
152
    connect(m_glMonitor, &GLWidget::panView, this, &Monitor::panView);
153
    connect(m_glMonitor->getControllerProxy(), &MonitorProxy::requestSeek, this, &Monitor::processSeek, Qt::DirectConnection);
154
    connect(m_glMonitor->getControllerProxy(), &MonitorProxy::positionChanged, this, &Monitor::slotSeekPosition);
155

Laurent Montel's avatar
Laurent Montel committed
156
    m_videoWidget = QWidget::createWindowContainer(qobject_cast<QWindow *>(m_glMonitor));
157
    m_videoWidget->setAcceptDrops(true);
Nicolas Carion's avatar
Nicolas Carion committed
158
    auto *leventEater = new QuickEventEater(this);
159
    m_videoWidget->installEventFilter(leventEater);
160
    connect(leventEater, &QuickEventEater::addEffect, this, &Monitor::slotAddEffect);
161
    connect(leventEater, &QuickEventEater::doKeyPressEvent, this, &Monitor::doKeyPressEvent);
162

163
164
165
    m_qmlManager = new QmlManager(m_glMonitor);
    connect(m_qmlManager, &QmlManager::effectChanged, this, &Monitor::effectChanged);
    connect(m_qmlManager, &QmlManager::effectPointsChanged, this, &Monitor::effectPointsChanged);
166
    connect(m_qmlManager, &QmlManager::activateTrack, this, &Monitor::activateTrack);
167

168
    glayout->addWidget(m_videoWidget, 0, 0);
169
170
171
172
173
174
    m_verticalScroll = new QScrollBar(Qt::Vertical);
    glayout->addWidget(m_verticalScroll, 0, 1);
    m_verticalScroll->hide();
    m_horizontalScroll = new QScrollBar(Qt::Horizontal);
    glayout->addWidget(m_horizontalScroll, 1, 0);
    m_horizontalScroll->hide();
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
175
176
    connect(m_horizontalScroll, &QAbstractSlider::valueChanged, this, &Monitor::setOffsetX);
    connect(m_verticalScroll, &QAbstractSlider::valueChanged, this, &Monitor::setOffsetY);
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
177
    connect(m_glMonitor, &GLWidget::frameDisplayed, this, &Monitor::onFrameDisplayed, Qt::DirectConnection);
178
    connect(m_glMonitor, &GLWidget::mouseSeek, this, &Monitor::slotMouseSeek);
Vincent Pinon's avatar
Vincent Pinon committed
179
    connect(m_glMonitor, &GLWidget::monitorPlay, this, &Monitor::slotPlay);
Laurent Montel's avatar
Laurent Montel committed
180
    connect(m_glMonitor, &GLWidget::startDrag, this, &Monitor::slotStartDrag);
Vincent Pinon's avatar
Vincent Pinon committed
181
    connect(m_glMonitor, &GLWidget::switchFullScreen, this, &Monitor::slotSwitchFullScreen);
Laurent Montel's avatar
Laurent Montel committed
182
    connect(m_glMonitor, &GLWidget::zoomChanged, this, &Monitor::setZoom);
183
    connect(m_glMonitor, SIGNAL(lockMonitor(bool)), this, SLOT(slotLockMonitor(bool)), Qt::DirectConnection);
Laurent Montel's avatar
Laurent Montel committed
184
    connect(m_glMonitor, &GLWidget::showContextMenu, this, &Monitor::slotShowMenu);
185
    connect(m_glMonitor, &GLWidget::gpuNotSupported, this, &Monitor::gpuError);
186

187
188
    m_glWidget->setMinimumSize(QSize(320, 180));
    layout->addWidget(m_glWidget, 10);
189
190
191
    layout->addStretch();

    // Tool bar buttons
192
    m_toolbar = new QToolBar(this);
193
194
195
    int size = style()->pixelMetric(QStyle::PM_SmallIconSize);
    QSize iconSize(size, size);
    m_toolbar->setIconSize(iconSize);
196

197
    auto *scalingAction = new QComboBox(this);
198
199
200
    scalingAction->setToolTip(i18n("Preview resolution - lower resolution means faster preview"));
    // Combobox padding is bad, so manually add a space before text
    scalingAction->addItems({QStringLiteral(" ") + i18n("1:1"),QStringLiteral(" ") + i18n("720p"),QStringLiteral(" ") + i18n("540p"),QStringLiteral(" ") + i18n("360p"),QStringLiteral(" ") + i18n("270p")});
Vincent Pinon's avatar
Vincent Pinon committed
201
    connect(scalingAction, QOverload<int>::of(&QComboBox::activated), this, [this] (int index) {
202
203
204
205
        switch (index) {
            case 1:
                KdenliveSettings::setPreviewScaling(2);
                break;
206
207
208
            case 2:
                KdenliveSettings::setPreviewScaling(4);
                break;
209
            case 3:
210
211
                KdenliveSettings::setPreviewScaling(8);
                break;
212
            case 4:
213
214
215
                KdenliveSettings::setPreviewScaling(16);
                break;
            default:
216
                KdenliveSettings::setPreviewScaling(0);
217
        }
Vincent Pinon's avatar
Vincent Pinon committed
218
219
        emit m_monitorManager->scalingChanged();
        emit m_monitorManager->updatePreviewScaling();
220
    });
221

Vincent Pinon's avatar
Vincent Pinon committed
222
    connect(manager, &MonitorManager::updatePreviewScaling, this, [this, scalingAction]() {
223
        bool scalingChanged = m_glMonitor->updateScaling();
224
225
        switch (KdenliveSettings::previewScaling()) {
            case 2:
226
                scalingAction->setCurrentIndex(1);
227
228
                break;
            case 4:
229
                scalingAction->setCurrentIndex(2);
230
231
                break;
            case 8:
232
                scalingAction->setCurrentIndex(3);
233
234
                break;
            case 16:
235
                scalingAction->setCurrentIndex(4);
236
237
                break;
            default:
238
                scalingAction->setCurrentIndex(0);
239
240
                break;
        }
241
242
243
        if (scalingChanged) {
            refreshMonitorIfActive();
        }
244
    });
245
246
247
248
    scalingAction->setFrame(false);
    scalingAction->setFont(QFontDatabase::systemFont(QFontDatabase::SmallestReadableFont));
    m_toolbar->addWidget(scalingAction);
    m_toolbar->addSeparator();
249

250
251
    if (id == Kdenlive::ClipMonitor) {
        // Add options for recording
252
        m_recManager = new RecManager(this);
Vincent Pinon's avatar
Vincent Pinon committed
253
        connect(m_recManager, &RecManager::warningMessage, this, &Monitor::warningMessage);
254
        connect(m_recManager, &RecManager::addClipToProject, this, &Monitor::addClipToProject);
255

256
        m_toolbar->addAction(manager->getAction(QStringLiteral("insert_project_tree")));
257
        m_toolbar->setToolTip(i18n("Insert Zone to Project Bin"));
258
        m_toolbar->addSeparator();
259
260
261
262
        m_streamsButton = new QToolButton(this);
        m_streamsButton->setPopupMode(QToolButton::InstantPopup);
        m_streamsButton->setIcon(QIcon::fromTheme(QStringLiteral("speaker")));
        m_streamAction = m_toolbar->addWidget(m_streamsButton);
263
        m_audioChannels = new QMenu(this);
264
265
        m_streamsButton->setMenu(m_audioChannels);
        m_streamAction->setVisible(false);
Vincent Pinon's avatar
Vincent Pinon committed
266
        connect(m_audioChannels, &QMenu::triggered, this, [this] (QAction *ac) {
267
            //m_audioChannels->show();
268
269
            QList <QAction*> actions = m_audioChannels->actions();
            QMap <int, QString> enabledStreams;
270
271
272
273
274
275
            if (ac->data().toInt() == INT_MAX) {
                // Merge stream selected, clear all others
                enabledStreams.clear();
                enabledStreams.insert(INT_MAX, i18n("Merged streams"));
                // Disable all other streams
                QSignalBlocker bk(m_audioChannels);
Vincent Pinon's avatar
Vincent Pinon committed
276
                for (auto act : qAsConst(actions)) {
277
278
279
280
281
                    if (act->isChecked() && act != ac) {
                        act->setChecked(false);
                    }
                }
            } else {
Vincent Pinon's avatar
Vincent Pinon committed
282
                for (auto act : qAsConst(actions)) {
283
284
285
286
287
288
289
290
291
                    if (act->isChecked()) {
                        // Audio stream is selected
                        if (act->data().toInt() == INT_MAX) {
                            QSignalBlocker bk(m_audioChannels);
                            act->setChecked(false);
                        } else {
                            enabledStreams.insert(act->data().toInt(), act->text().remove(QLatin1Char('&')));
                        }
                    }
292
293
294
295
296
297
298
299
                }
            }
            if (!enabledStreams.isEmpty()) {
                // Only 1 stream wanted, easy
                QMap <QString, QString> props;
                props.insert(QStringLiteral("audio_index"), QString::number(enabledStreams.firstKey()));
                QList <int> streams = enabledStreams.keys();
                QStringList astreams;
Vincent Pinon's avatar
Vincent Pinon committed
300
                for (const int st : qAsConst(streams)) {
301
302
303
304
305
306
307
308
309
310
311
312
                    astreams << QString::number(st);
                }
                props.insert(QStringLiteral("kdenlive:active_streams"), astreams.join(QLatin1Char(';')));
                m_controller->setProperties(props, true);
            } else {
                // No active stream
                QMap <QString, QString> props;
                props.insert(QStringLiteral("audio_index"), QStringLiteral("-1"));
                props.insert(QStringLiteral("kdenlive:active_streams"), QStringLiteral("-1"));
                m_controller->setProperties(props, true);
            }
        });
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
313
    } else if (id == Kdenlive::ProjectMonitor) {
314
        connect(m_glMonitor, &GLWidget::paused, m_monitorManager, &MonitorManager::cleanMixer);
315
316
    }

317
    if (id != Kdenlive::DvdMonitor) {
318
319
320
321
        QAction *markIn = new QAction(QIcon::fromTheme(QStringLiteral("zone-in")), i18n("Set Zone In"), this);
        QAction *markOut = new QAction(QIcon::fromTheme(QStringLiteral("zone-out")), i18n("Set Zone Out"), this);
        m_toolbar->addAction(markIn);
        m_toolbar->addAction(markOut);
Vincent Pinon's avatar
Vincent Pinon committed
322
        connect(markIn, &QAction::triggered, this, [&, manager]() {
323
324
325
            m_monitorManager->activateMonitor(m_id);
            manager->getAction(QStringLiteral("mark_in"))->trigger();
        });
Vincent Pinon's avatar
Vincent Pinon committed
326
        connect(markOut, &QAction::triggered, this, [&, manager]() {
327
328
329
            m_monitorManager->activateMonitor(m_id);
            manager->getAction(QStringLiteral("mark_out"))->trigger();
        });
330
    }
331
332
333
334
    // Per monitor rewind action
    QAction *rewind = new QAction(QIcon::fromTheme(QStringLiteral("media-seek-backward")), i18n("Rewind"), this);
    m_toolbar->addAction(rewind);
    connect(rewind, &QAction::triggered, this, &Monitor::slotRewind);
335

Nicolas Carion's avatar
Nicolas Carion committed
336
    auto *playButton = new QToolButton(m_toolbar);
337
    m_playMenu = new QMenu(i18n("Play..."), this);
338
    connect(m_playMenu, &QMenu::aboutToShow, this, &Monitor::slotActivateMonitor);
Laurent Montel's avatar
Laurent Montel committed
339
    QAction *originalPlayAction = static_cast<KDualAction *>(manager->getAction(QStringLiteral("monitor_play")));
340
    m_playAction = new KDualAction(i18n("Play"), i18n("Pause"), this);
341
342
    m_playAction->setInactiveIcon(QIcon::fromTheme(QStringLiteral("media-playback-start")));
    m_playAction->setActiveIcon(QIcon::fromTheme(QStringLiteral("media-playback-pause")));
343

Laurent Montel's avatar
Laurent Montel committed
344
    QString strippedTooltip = m_playAction->toolTip().remove(QRegExp(QStringLiteral("\\s\\(.*\\)")));
345
346
    // append shortcut if it exists for action
    if (originalPlayAction->shortcut() == QKeySequence(0)) {
Laurent Montel's avatar
Laurent Montel committed
347
348
        m_playAction->setToolTip(strippedTooltip);
    } else {
349
        m_playAction->setToolTip(strippedTooltip + QStringLiteral(" (") + originalPlayAction->shortcut().toString() + QLatin1Char(')'));
350
    }
351
    m_playMenu->addAction(m_playAction);
352
    connect(m_playAction, &QAction::triggered, this, &Monitor::slotSwitchPlay);
353
354
355

    playButton->setMenu(m_playMenu);
    playButton->setPopupMode(QToolButton::MenuButtonPopup);
356
    m_toolbar->addWidget(playButton);
357
358
359
360

    // Per monitor forward action
    QAction *forward = new QAction(QIcon::fromTheme(QStringLiteral("media-seek-forward")), i18n("Forward"), this);
    m_toolbar->addAction(forward);
Vincent Pinon's avatar
Vincent Pinon committed
361
    connect(forward, &QAction::triggered, this, [this]() {
362
363
        Monitor::slotForward();
    });
364
365

    playButton->setDefaultAction(m_playAction);
366
    m_configMenu = new QMenu(i18n("Misc..."), this);
367

368
369
    if (id != Kdenlive::DvdMonitor) {
        if (id == Kdenlive::ClipMonitor) {
370
            m_markerMenu = new QMenu(i18n("Go to marker..."), this);
371
372
        } else {
            m_markerMenu = new QMenu(i18n("Go to guide..."), this);
373
        }
374
375
        m_markerMenu->setEnabled(false);
        m_configMenu->addMenu(m_markerMenu);
Laurent Montel's avatar
Laurent Montel committed
376
        connect(m_markerMenu, &QMenu::triggered, this, &Monitor::slotGoToMarker);
377
        m_forceSize = new KSelectAction(QIcon::fromTheme(QStringLiteral("transform-scale")), i18n("Force Monitor Size"), this);
378
379
380
381
382
383
384
385
        QAction *fullAction = m_forceSize->addAction(QIcon(), i18n("Force 100%"));
        fullAction->setData(100);
        QAction *halfAction = m_forceSize->addAction(QIcon(), i18n("Force 50%"));
        halfAction->setData(50);
        QAction *freeAction = m_forceSize->addAction(QIcon(), i18n("Free Resize"));
        freeAction->setData(0);
        m_configMenu->addAction(m_forceSize);
        m_forceSize->setCurrentAction(freeAction);
Nicolas Carion's avatar
Nicolas Carion committed
386
        connect(m_forceSize, static_cast<void (KSelectAction::*)(QAction *)>(&KSelectAction::triggered), this, &Monitor::slotForceSize);
387
    }
388

389
390
391
    // Create Volume slider popup
    m_audioSlider = new QSlider(Qt::Vertical);
    m_audioSlider->setRange(0, 100);
392
    m_audioSlider->setValue(KdenliveSettings::volume());
393
    connect(m_audioSlider, &QSlider::valueChanged, this, &Monitor::slotSetVolume);
Nicolas Carion's avatar
Nicolas Carion committed
394
    auto *widgetslider = new QWidgetAction(this);
395
396
    widgetslider->setText(i18n("Audio volume"));
    widgetslider->setDefaultWidget(m_audioSlider);
397
398
    auto *menu = new QMenu(i18n("Volume"), this);
    menu->setIcon(QIcon::fromTheme(QStringLiteral("audio-volume-medium")));
399
    menu->addAction(widgetslider);
400
    m_configMenu->addMenu(menu);
401

402
    /*QIcon icon;
Laurent Montel's avatar
Laurent Montel committed
403
    if (KdenliveSettings::volume() == 0) {
404
        icon = QIcon::fromTheme(QStringLiteral("audio-volume-muted"));
Laurent Montel's avatar
Laurent Montel committed
405
    } else {
406
        icon = QIcon::fromTheme(QStringLiteral("audio-volume-medium"));
Laurent Montel's avatar
Laurent Montel committed
407
    }
408
    m_audioButton->setIcon(icon);*/
409

410
    setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Expanding);
411
412
    setLayout(layout);
    setMinimumHeight(200);
413

414
415
    connect(this, &Monitor::scopesClear, m_glMonitor, &GLWidget::releaseAnalyse, Qt::DirectConnection);
    connect(m_glMonitor, &GLWidget::analyseFrame, this, &Monitor::frameUpdated);
416
    m_timePos = new TimecodeDisplay(pCore->timecode(), this);
417

418
    if (id == Kdenlive::ProjectMonitor) {
Nicolas Carion's avatar
linting    
Nicolas Carion committed
419
420
        // TODO: reimplement
        // connect(render, &Render::durationChanged, this, &Monitor::durationChanged);
421
        connect(m_glMonitor->getControllerProxy(), &MonitorProxy::saveZone, this, &Monitor::zoneUpdated);
422
        connect(m_glMonitor->getControllerProxy(), &MonitorProxy::saveZoneWithUndo, this, &Monitor::zoneUpdatedWithUndo);
423
    } else if (id == Kdenlive::ClipMonitor) {
424
        connect(m_glMonitor->getControllerProxy(), &MonitorProxy::saveZone, this, &Monitor::updateClipZone);
425
    }
426
    m_glMonitor->getControllerProxy()->setTimeCode(m_timePos);
427
    connect(m_glMonitor->getControllerProxy(), &MonitorProxy::triggerAction, pCore.get(), &Core::triggerAction);
428
429
430
    connect(m_glMonitor->getControllerProxy(), &MonitorProxy::seekNextKeyframe, this, &Monitor::seekToNextKeyframe);
    connect(m_glMonitor->getControllerProxy(), &MonitorProxy::seekPreviousKeyframe, this, &Monitor::seekToPreviousKeyframe);
    connect(m_glMonitor->getControllerProxy(), &MonitorProxy::addRemoveKeyframe, this, &Monitor::addRemoveKeyframe);
431
    connect(m_glMonitor->getControllerProxy(), &MonitorProxy::seekToKeyframe, this, &Monitor::slotSeekToKeyFrame);
432

433
    m_toolbar->addAction(manager->getAction(QStringLiteral("monitor_editmode")));
434

435
436
437
    m_toolbar->addSeparator();
    m_toolbar->addWidget(m_timePos);

Nicolas Carion's avatar
Nicolas Carion committed
438
    auto *configButton = new QToolButton(m_toolbar);
439
    configButton->setIcon(QIcon::fromTheme(QStringLiteral("kdenlive-menu")));
440
    configButton->setToolTip(i18n("Options"));
441
    configButton->setMenu(m_configMenu);
442
    configButton->setPopupMode(QToolButton::InstantPopup);
443
    m_toolbar->addWidget(configButton);
444
    m_toolbar->addSeparator();
445
446
    QMargins mrg = m_toolbar->contentsMargins();
    m_audioMeterWidget = new MonitorAudioLevel(m_toolbar->height() - mrg.top() - mrg.bottom(), this);
447
    m_toolbar->addWidget(m_audioMeterWidget);
448
    if (!m_audioMeterWidget->isValid) {
449
450
451
452
        KdenliveSettings::setMonitoraudio(0x01);
        m_audioMeterWidget->setVisibility(false);
    } else {
        m_audioMeterWidget->setVisibility((KdenliveSettings::monitoraudio() & m_id) != 0);
453
    }
454

455
    connect(m_timePos, SIGNAL(timeCodeEditingFinished()), this, SLOT(slotSeek()));
456
    layout->addWidget(m_toolbar);
Laurent Montel's avatar
Laurent Montel committed
457
458
459
    if (m_recManager) {
        layout->addWidget(m_recManager->toolbar());
    }
460
461

    // Load monitor overlay qml
462
    loadQmlScene(MonitorSceneDefault);
463

464
465
466
467
468
    // Monitor dropped fps timer
    m_droppedTimer.setInterval(1000);
    m_droppedTimer.setSingleShot(false);
    connect(&m_droppedTimer, &QTimer::timeout, this, &Monitor::checkDrops);

469
470
471
472
    // Info message widget
    m_infoMessage = new KMessageWidget(this);
    layout->addWidget(m_infoMessage);
    m_infoMessage->hide();
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
473
474
}

475
476
Monitor::~Monitor()
{
477
    delete m_audioMeterWidget;
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
478
    delete m_glMonitor;
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
479
480
    delete m_videoWidget;
    delete m_glWidget;
481
482
483
    delete m_timePos;
}

484
485
486
487
488
489
490
491
492
493
void Monitor::setOffsetX(int x)
{
    m_glMonitor->setOffsetX(x, m_horizontalScroll->maximum());
}

void Monitor::setOffsetY(int y)
{
    m_glMonitor->setOffsetY(y, m_verticalScroll->maximum());
}

494
void Monitor::slotGetCurrentImage(bool request)
495
{
496
    m_glMonitor->sendFrameForAnalysis = request;
497
    Kdenlive::MonitorId id = m_monitorManager->activeMonitor()->id();
498
    m_monitorManager->activateMonitor(m_id);
499
    refreshMonitorIfActive(true);
500
501
    if (request) {
        // Update analysis state
Laurent Montel's avatar
Laurent Montel committed
502
        QTimer::singleShot(500, m_monitorManager, &MonitorManager::checkScopes);
503
504
505
    } else {
        m_glMonitor->releaseAnalyse();
    }
506
    m_monitorManager->activateMonitor(id);
507
508
}

509
void Monitor::slotAddEffect(const QStringList &effect)
510
511
{
    if (m_id == Kdenlive::ClipMonitor) {
Laurent Montel's avatar
Laurent Montel committed
512
        if (m_controller) {
513
            emit addMasterEffect(m_controller->AbstractProjectItem::clipId(), effect);
Laurent Montel's avatar
Laurent Montel committed
514
515
516
        }
    } else {
        emit addEffect(effect);
517
518
519
    }
}

520
521
522
523
524
525
void Monitor::refreshIcons()
{
    QList<QAction *> allMenus = this->findChildren<QAction *>();
    for (int i = 0; i < allMenus.count(); i++) {
        QAction *m = allMenus.at(i);
        QIcon ic = m->icon();
Laurent Montel's avatar
Laurent Montel committed
526
527
528
        if (ic.isNull() || ic.name().isEmpty()) {
            continue;
        }
529
        QIcon newIcon = QIcon::fromTheme(ic.name());
530
531
532
533
534
535
        m->setIcon(newIcon);
    }
    QList<KDualAction *> allButtons = this->findChildren<KDualAction *>();
    for (int i = 0; i < allButtons.count(); i++) {
        KDualAction *m = allButtons.at(i);
        QIcon ic = m->activeIcon();
Laurent Montel's avatar
Laurent Montel committed
536
537
538
        if (ic.isNull() || ic.name().isEmpty()) {
            continue;
        }
539
        QIcon newIcon = QIcon::fromTheme(ic.name());
540
541
        m->setActiveIcon(newIcon);
        ic = m->inactiveIcon();
Laurent Montel's avatar
Laurent Montel committed
542
543
544
        if (ic.isNull() || ic.name().isEmpty()) {
            continue;
        }
545
        newIcon = QIcon::fromTheme(ic.name());
546
547
548
549
        m->setInactiveIcon(newIcon);
    }
}

550
QAction *Monitor::recAction()
551
{
Laurent Montel's avatar
Laurent Montel committed
552
    if (m_recManager) {
553
        return m_recManager->recAction();
Laurent Montel's avatar
Laurent Montel committed
554
    }
Laurent Montel's avatar
Laurent Montel committed
555
    return nullptr;
556
557
}

558
559
560
561
562
void Monitor::slotLockMonitor(bool lock)
{
    m_monitorManager->lockMonitor(m_id, lock);
}

563
void Monitor::setupMenu(QMenu *goMenu, QMenu *overlayMenu, QAction *playZone, QAction *loopZone, QMenu *markerMenu, QAction *loopClip)
564
{
565
    delete m_contextMenu;
566
    m_contextMenu = new QMenu(this);
567
    m_contextMenu->addMenu(m_playMenu);
Laurent Montel's avatar
Laurent Montel committed
568
    if (goMenu) {
569
        m_contextMenu->addMenu(goMenu);
Laurent Montel's avatar
Laurent Montel committed
570
    }
571

572
    if (markerMenu) {
573
        m_contextMenu->addMenu(markerMenu);
Nicolas Carion's avatar
Nicolas Carion committed
574
        QList<QAction *> list = markerMenu->actions();
575
        for (int i = 0; i < list.count(); ++i) {
576
            if (list.at(i)->objectName() == QLatin1String("edit_marker")) {
577
578
579
580
581
                m_editMarker = list.at(i);
                break;
            }
        }
    }
582

583
584
    m_playMenu->addAction(playZone);
    m_playMenu->addAction(loopZone);
585
586
587
588
    if (loopClip) {
        m_loopClipAction = loopClip;
        m_playMenu->addAction(loopClip);
    }
589

590
    m_contextMenu->addMenu(m_markerMenu);
591
    if (m_id == Kdenlive::ClipMonitor) {
592
        //m_contextMenu->addAction(QIcon::fromTheme(QStringLiteral("document-save")), i18n("Save zone"), this, SLOT(slotSaveZone()));
Nicolas Carion's avatar
Nicolas Carion committed
593
        QAction *extractZone =
594
            m_configMenu->addAction(QIcon::fromTheme(QStringLiteral("document-new")), i18n("Extract Zone"), this, SLOT(slotExtractCurrentZone()));
595
        m_contextMenu->addAction(extractZone);
596
        m_contextMenu->addAction(m_monitorManager->getAction(QStringLiteral("insert_project_tree")));
597
    }
598
599
    m_contextMenu->addAction(m_monitorManager->getAction(QStringLiteral("extract_frame")));
    m_contextMenu->addAction(m_monitorManager->getAction(QStringLiteral("extract_frame_to_project")));
600
    m_contextMenu->addAction(m_monitorManager->getAction(QStringLiteral("add_project_note")));
601

Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
602
    if (m_id == Kdenlive::ProjectMonitor) {
603
        m_contextMenu->addAction(m_monitorManager->getAction(QStringLiteral("monitor_multitrack")));
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
604
    } else if (m_id == Kdenlive::ClipMonitor) {
605
606
        QAction *setThumbFrame =
            m_contextMenu->addAction(QIcon::fromTheme(QStringLiteral("document-new")), i18n("Set current image as thumbnail"), this, SLOT(slotSetThumbFrame()));
607
        m_configMenu->addAction(setThumbFrame);
608
609
610
        QAction *alwaysShowAudio =
            new QAction(QIcon::fromTheme(QStringLiteral("kdenlive-show-audiothumb")), i18n("Always show audio thumbnails"), this);
        alwaysShowAudio->setCheckable(true);
Vincent Pinon's avatar
Vincent Pinon committed
611
        connect(alwaysShowAudio, &QAction::triggered, this, [this](bool checked) {
612
613
614
615
616
617
            KdenliveSettings::setAlwaysShowMonitorAudio(checked);
            m_glMonitor->rootObject()->setProperty("permanentAudiothumb", checked);
        });
        alwaysShowAudio->setChecked(KdenliveSettings::alwaysShowMonitorAudio());
        m_contextMenu->addAction(alwaysShowAudio);
        m_configMenu->addAction(alwaysShowAudio);
618
619
    }

Laurent Montel's avatar
Laurent Montel committed
620
    if (overlayMenu) {
621
        m_contextMenu->addMenu(overlayMenu);
Laurent Montel's avatar
Laurent Montel committed
622
    }
623

624
625
    QAction *switchAudioMonitor = m_configMenu->addAction(i18n("Show Audio Levels"), this, SLOT(slotSwitchAudioMonitor()));
    switchAudioMonitor->setCheckable(true);
Nicolas Carion's avatar
Nicolas Carion committed
626
    switchAudioMonitor->setChecked((KdenliveSettings::monitoraudio() & m_id) != 0);
627
628
    
    if (m_id == Kdenlive::ClipMonitor) {
629
        QAction *recordTimecode = new QAction(i18n("Show Source Timecode"), this);
630
631
632
633
634
        recordTimecode->setCheckable(true);
        connect(recordTimecode, &QAction::triggered, this, &Monitor::slotSwitchRecTimecode);
        recordTimecode->setChecked(KdenliveSettings::rectimecode());
        m_configMenu->addAction(recordTimecode);
    }
635

636
637
638
    // For some reason, the frame in QAbstracSpinBox (base class of TimeCodeDisplay) needs to be displayed once, then hidden
    // or it will never appear (supposed to appear on hover).
    m_timePos->setFrame(false);
639
640
}

641
642
643
644
645
646
void Monitor::slotGoToMarker(QAction *action)
{
    int pos = action->data().toInt();
    slotSeek(pos);
}

647
void Monitor::slotForceSize(QAction *a)
648
{
649
650
651
652
653
    int resizeType = a->data().toInt();
    int profileWidth = 320;
    int profileHeight = 200;
    if (resizeType > 0) {
        // calculate size
Vincent Pinon's avatar
Vincent Pinon committed
654
        QRect r = QApplication::primaryScreen()->geometry();
655
        profileHeight = m_glMonitor->profileSize().height() * resizeType / 100;
Vincent Pinon's avatar
Vincent Pinon committed
656
        profileWidth = int(pCore->getCurrentProfile()->dar() * profileHeight);
657
658
        if (profileWidth > r.width() * 0.8 || profileHeight > r.height() * 0.7) {
            // reset action to free resize
Nicolas Carion's avatar
format    
Nicolas Carion committed
659
            const QList<QAction *> list = m_forceSize->actions();
660
            for (QAction *ac : list) {
661
                if (ac->data().toInt() == m_forceSizeFactor) {
662
663
664
665
                    m_forceSize->setCurrentAction(ac);
                    break;
                }
            }
666
            warningMessage(i18n("Your screen resolution is not sufficient for this action"));
667
668
            return;
        }
669
    }
670
    switch (resizeType) {
Laurent Montel's avatar
Laurent Montel committed
671
672
673
674
    case 100:
    case 50:
        // resize full size
        setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding);
675
        profileHeight += m_glMonitor->m_displayRulerHeight;
Laurent Montel's avatar
Laurent Montel committed
676
677
        m_videoWidget->setMinimumSize(profileWidth, profileHeight);
        m_videoWidget->setMaximumSize(profileWidth, profileHeight);
678
        setMinimumSize(QSize(profileWidth, profileHeight + m_toolbar->height()));
Laurent Montel's avatar
Laurent Montel committed
679
680
        break;
    default:
681
682
        // Free resize
        m_videoWidget->setMinimumSize(profileWidth, profileHeight);
683
        m_videoWidget->setMaximumSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX);
684
        setMinimumSize(QSize(profileWidth, profileHeight + m_toolbar->height() + m_glMonitor->getControllerProxy()->rulerHeight()));
685
        setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Expanding);
686
        break;
687
    }
688
    m_forceSizeFactor = resizeType;
689
690
691
    updateGeometry();
}

692

693
void Monitor::updateMarkers()
694
{
695
    if (m_controller) {
696
        m_markerMenu->clear();
697
        QList<CommentedTime> markers = m_controller->getMarkerModel()->getAllMarkers();
698
        if (!markers.isEmpty()) {
699
            for (int i = 0; i < markers.count(); ++i) {
Vincent Pinon's avatar
Vincent Pinon committed
700
                int pos = markers.at(i).time().frames(pCore->getCurrentFps());
701
                QString position = pCore->timecode().getTimecode(markers.at(i).time()) + QLatin1Char(' ') + markers.at(i).comment();
702
703
704
                QAction *go = m_markerMenu->addAction(position);
                go->setData(pos);
            }
705
        }
706
707
708
709
        m_markerMenu->setEnabled(!m_markerMenu->isEmpty());
    }
}

Laurent Montel's avatar
Laurent Montel committed
710
void Monitor::setGuides(const QMap<double, QString> &guides)
711
{
Nicolas Carion's avatar
linting    
Nicolas Carion committed
712
    // TODO: load guides model
713
714
    m_markerMenu->clear();
    QMapIterator<double, QString> i(guides);
Laurent Montel's avatar
Laurent Montel committed
715
    QList<CommentedTime> guidesList;
716
717
718
719
    while (i.hasNext()) {
        i.next();
        CommentedTime timeGuide(GenTime(i.key()), i.value());
        guidesList << timeGuide;
Vincent Pinon's avatar
Vincent Pinon committed
720
        int pos = timeGuide.time().frames(pCore->getCurrentFps());
721
        QString position = pCore->timecode().getTimecode(timeGuide.time()) + QLatin1Char(' ') + timeGuide.comment();
722
723
724
        QAction *go = m_markerMenu->addAction(position);
        go->setData(pos);
    }
Nicolas Carion's avatar
linting    
Nicolas Carion committed
725
    // m_ruler->setMarkers(guidesList);
726
727
728
729
    m_markerMenu->setEnabled(!m_markerMenu->isEmpty());
    checkOverlay();
}

730
731
void Monitor::slotSeekToPreviousSnap()
{
Laurent Montel's avatar
Laurent Montel committed
732
    if (m_controller) {
733
        m_glMonitor->getControllerProxy()->setPosition(getSnapForPos(true).frames(pCore->getCurrentFps()));
Laurent Montel's avatar
Laurent Montel committed
734
    }
735
736
}

737
738
void Monitor::slotSeekToNextSnap()
{
Laurent Montel's avatar
Laurent Montel committed
739
    if (m_controller) {
740
        m_glMonitor->getControllerProxy()->setPosition(getSnapForPos(false).frames(pCore->getCurrentFps()));
Laurent Montel's avatar
Laurent Montel committed
741
    }
742
743
}

744
int Monitor::position()
745
{
746
    return m_glMonitor->getControllerProxy()->getPosition();
747
748
}

749
750
GenTime Monitor::getSnapForPos(bool previous)
{
751
    int frame = previous ? m_snaps->getPreviousPoint(m_glMonitor->getCurrentPos()) : m_snaps->getNextPoint(m_glMonitor->getCurrentPos());
Nicolas Carion's avatar
Nicolas Carion committed
752
    return {frame, pCore->getCurrentFps()};
753
754
}

755
void Monitor::slotLoadClipZone(const QPoint &zone)
756
{
757
    m_glMonitor->getControllerProxy()->setZone(zone.x(), zone.y(), false);
758
    checkOverlay();
759
760
}

761
762
void Monitor::slotSetZoneStart()
{
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
    QPoint oldZone = m_glMonitor->getControllerProxy()->zone();
    int currentIn = m_glMonitor->getCurrentPos();
    int updatedZoneOut = -1;
    if (currentIn > oldZone.y()) {
        updatedZoneOut = qMin(m_glMonitor->duration(), currentIn + (oldZone.y() - oldZone.x()));
    }
    
    Fun undo_zone = [this, oldZone, updatedZoneOut]() {
            m_glMonitor->getControllerProxy()->setZoneIn(oldZone.x());
            if (updatedZoneOut > -1) {
                m_glMonitor->getControllerProxy()->setZoneOut(oldZone.y());
            }
            checkOverlay();
            return true;
    };
    Fun redo_zone = [this, currentIn, updatedZoneOut]() {
            if (updatedZoneOut > -1) {
                m_glMonitor->getControllerProxy()->setZoneOut(updatedZoneOut);
            }
            m_glMonitor->getControllerProxy()->setZoneIn(currentIn);
            checkOverlay();
            return true;
    };
    redo_zone();
    pCore->pushUndo(undo_zone, redo_zone, i18n("Set Zone"));
788
789
}

790
void Monitor::slotSetZoneEnd()
791
{
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
    QPoint oldZone = m_glMonitor->getControllerProxy()->zone();
    int currentOut = m_glMonitor->getCurrentPos() + 1;
    int updatedZoneIn = -1;
    if (currentOut < oldZone.x()) {
        updatedZoneIn = qMax(0, currentOut - (oldZone.y() - oldZone.x()));
    }
    Fun undo_zone = [this, oldZone, updatedZoneIn]() {
            m_glMonitor->getControllerProxy()->setZoneOut(oldZone.y());
            if (updatedZoneIn > -1) {
                m_glMonitor->getControllerProxy()->setZoneIn(oldZone.x());
            }
            checkOverlay();
            return true;
    };
    
    Fun redo_zone = [this, currentOut, updatedZoneIn]() {
            if (updatedZoneIn > -1) {
                m_glMonitor->getControllerProxy()->setZoneIn(updatedZoneIn);
            }
            m_glMonitor->getControllerProxy()->setZoneOut(currentOut);
            checkOverlay();
            return true;
    };
    redo_zone();
    pCore->pushUndo(undo_zone, redo_zone, i18n("Set Zone"));
817
818
}

819
// virtual
Laurent Montel's avatar
Laurent Montel committed
820
void Monitor::mousePressEvent