bin.cpp 178 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
/*
Copyright (C) 2012  Till Theato <root@ttill.de>
Copyright (C) 2014  Jean-Baptiste Mardelle <jb@kdenlive.org>
This file is part of Kdenlive. See www.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) version 3 or any later version
accepted by the membership of KDE e.V. (or its successor approved
11
by the membership of KDE e.V.), which shall act as a proxy
12 13 14 15 16 17 18 19 20 21 22 23
defined in Section 14 of version 3 of the license.

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, see <http://www.gnu.org/licenses/>.
*/

#include "bin.h"
Nicolas Carion's avatar
Nicolas Carion committed
24
#include "bincommands.h"
25
#include "clipcreator.hpp"
Nicolas Carion's avatar
Nicolas Carion committed
26 27 28 29 30
#include "core.h"
#include "dialogs/clipcreationdialog.h"
#include "doc/documentchecker.h"
#include "doc/docundostack.hpp"
#include "doc/kdenlivedoc.h"
Nicolas Carion's avatar
Nicolas Carion committed
31
#include "effects/effectstack/model/effectstackmodel.hpp"
32
#include "jobs/audiothumbjob.hpp"
33 34
#include "jobs/jobmanager.h"
#include "jobs/loadjob.hpp"
35
#include "jobs/thumbjob.hpp"
36
#include "kdenlive_debug.h"
37
#include "kdenlivesettings.h"
Nicolas Carion's avatar
Nicolas Carion committed
38 39 40 41 42
#include "mainwindow.h"
#include "mlt++/Mlt.h"
#include "mltcontroller/clipcontroller.h"
#include "mltcontroller/clippropertiescontroller.h"
#include "monitor/monitor.h"
43
#include "project/dialogs/slideshowclip.h"
Nicolas Carion's avatar
Nicolas Carion committed
44
#include "project/invaliddialog.h"
45
#include "project/projectcommands.h"
Nicolas Carion's avatar
Nicolas Carion committed
46 47 48 49
#include "project/projectmanager.h"
#include "projectclip.h"
#include "projectfolder.h"
#include "projectitemmodel.h"
50
#include "projectsortproxymodel.h"
Nicolas Carion's avatar
Nicolas Carion committed
51
#include "projectsubclip.h"
52
#include "tagwidget.hpp"
Nicolas Carion's avatar
Nicolas Carion committed
53 54
#include "titler/titlewidget.h"
#include "ui_qtextclip_ui.h"
Nicolas Carion's avatar
Nicolas Carion committed
55
#include "undohelper.hpp"
56
#include "xml/xml.hpp"
57 58
#include <utils/thumbnailcache.hpp>
#include <profiles/profilemodel.hpp>
59

60
#include <KColorScheme>
61
#include <KRatingPainter>
62
#include <KMessageBox>
63
#include <KXMLGUIFactory>
64
#include <KIO/OpenFileManagerWindowJob>
65

66
#include <QToolBar>
Nicolas Carion's avatar
Nicolas Carion committed
67
#include <QCryptographicHash>
68
#include <QDrag>
Nicolas Carion's avatar
Nicolas Carion committed
69
#include <QFile>
70
#include <QMenu>
71
#include <QActionGroup>
Nicolas Carion's avatar
Nicolas Carion committed
72 73
#include <QSlider>
#include <QTimeLine>
74
#include <QUndoCommand>
Nicolas Carion's avatar
Nicolas Carion committed
75 76
#include <QUrl>
#include <QVBoxLayout>
Nicolas Carion's avatar
Nicolas Carion committed
77
#include <utility>
78

79 80 81 82 83 84 85 86 87 88
/**
 * @class BinItemDelegate
 * @brief This class is responsible for drawing items in the QTreeView.
 */

class BinItemDelegate : public QStyledItemDelegate
{
public:
    explicit BinItemDelegate(QObject *parent = nullptr)
        : QStyledItemDelegate(parent)
Nicolas Carion's avatar
Nicolas Carion committed
89

90
    {
91
        connect(this, &QStyledItemDelegate::closeEditor, [&]() { m_editorOpen = false; });
92
    }
93 94 95 96 97 98 99
    void setEditorData(QWidget *w, const QModelIndex &i) const override
    {
        if (!m_editorOpen) {
            QStyledItemDelegate::setEditorData(w, i);
            m_editorOpen = true;
        }
    }
100
    bool editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index) override
101 102
    {
        if (event->type() == QEvent::MouseButtonPress) {
Nicolas Carion's avatar
Nicolas Carion committed
103
            auto *me = (QMouseEvent *)event;
104 105 106 107 108 109 110 111
            if (index.column() == 0) {
                if (m_audioDragRect.contains(me->pos())) {
                    dragType = PlaylistState::AudioOnly;
                } else if (m_videoDragRect.contains(me->pos())) {
                    dragType = PlaylistState::VideoOnly;
                } else {
                    dragType = PlaylistState::Disabled;
                }
112 113
            } else {
                dragType = PlaylistState::Disabled;
114 115
                if (index.column() == 7) {
                    // Rating
116
                    QRect rect = option.rect;
117
                    rect.adjust(option.rect.width() / 12, 0, 0, 0);
118 119
                    int rate = 0;
                    if (me->pos().x() > rect.x()) {
120
                        rate = KRatingPainter::getRatingFromPosition(rect, Qt::AlignLeft | Qt::AlignVCenter, qApp->layoutDirection(), me->pos());
121
                    }
122 123 124 125 126 127
                    if (rate > -1) {
                        // Full star rating only
                        if (rate %2 == 1) {
                            rate++;
                        }
                        static_cast<ProjectSortProxyModel *>(model)->updateRating(index, (uint) rate);
128 129
                    }
                }
130 131 132 133 134 135 136 137
            }
        }
        event->ignore();
        return false;
    }
    void updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const override
    {
        if (index.column() != 0) {
138 139
            QStyledItemDelegate::updateEditorGeometry(editor, option, index);
            return;
140 141 142 143 144
        }
        QStyleOptionViewItem opt = option;
        initStyleOption(&opt, index);
        QRect r1 = option.rect;
        int type = index.data(AbstractProjectItem::ItemTypeRole).toInt();
145
        int decoWidth = 0;
146
        if (opt.decorationSize.height() > 0) {
147
            decoWidth += r1.height() * pCore->getCurrentDar();
148
        }
149
        int mid = 0;
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173
        if (type == AbstractProjectItem::ClipItem || type == AbstractProjectItem::SubClipItem) {
            mid = (int)((r1.height() / 2));
        }
        r1.adjust(decoWidth, 0, 0, -mid);
        QFont ft = option.font;
        ft.setBold(true);
        QFontMetricsF fm(ft);
        QRect r2 = fm.boundingRect(r1, Qt::AlignLeft | Qt::AlignTop, index.data(AbstractProjectItem::DataName).toString()).toRect();
        editor->setGeometry(r2);
    }

    QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const override
    {
        QSize hint = QStyledItemDelegate::sizeHint(option, index);
        QString text = index.data(AbstractProjectItem::DataName).toString();
        QRectF r = option.rect;
        QFont ft = option.font;
        ft.setBold(true);
        QFontMetricsF fm(ft);
        QStyle *style = option.widget ? option.widget->style() : QApplication::style();
        const int textMargin = style->pixelMetric(QStyle::PM_FocusFrameHMargin) + 1;
        int width = fm.boundingRect(r, Qt::AlignLeft | Qt::AlignTop, text).width() + option.decorationSize.width() + 2 * textMargin;
        hint.setWidth(width);
        int type = index.data(AbstractProjectItem::ItemTypeRole).toInt();
174
        if (type == AbstractProjectItem::FolderItem) {
175 176 177 178 179 180 181 182 183 184 185 186
            return QSize(hint.width(), qMin(option.fontMetrics.lineSpacing() + 4, hint.height()));
        }
        if (type == AbstractProjectItem::ClipItem) {
            return QSize(hint.width(), qMax(option.fontMetrics.lineSpacing() * 2 + 4, qMax(hint.height(), option.decorationSize.height())));
        }
        if (type == AbstractProjectItem::SubClipItem) {
            return QSize(hint.width(), qMax(option.fontMetrics.lineSpacing() * 2 + 4, qMin(hint.height(), (int)(option.decorationSize.height() / 1.5))));
        }
        QIcon icon = qvariant_cast<QIcon>(index.data(Qt::DecorationRole));
        QString line1 = index.data(Qt::DisplayRole).toString();
        QString line2 = index.data(Qt::UserRole).toString();

Vincent Pinon's avatar
Vincent Pinon committed
187
        int textW = qMax(option.fontMetrics.horizontalAdvance(line1), option.fontMetrics.horizontalAdvance(line2));
188
        QSize iconSize = icon.actualSize(option.decorationSize);
Nicolas Carion's avatar
Nicolas Carion committed
189
        return {qMax(textW, iconSize.width()) + 4, option.fontMetrics.lineSpacing() * 2 + 4};
190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205
    }

    void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const override
    {
        if (index.column() == 0 && !index.data().isNull()) {
            QRect r1 = option.rect;
            painter->save();
            painter->setClipRect(r1);
            QStyleOptionViewItem opt(option);
            initStyleOption(&opt, index);
            int type = index.data(AbstractProjectItem::ItemTypeRole).toInt();
            QStyle *style = opt.widget ? opt.widget->style() : QApplication::style();
            const int textMargin = style->pixelMetric(QStyle::PM_FocusFrameHMargin) + 1;
            // QRect r = QStyle::alignedRect(opt.direction, Qt::AlignVCenter | Qt::AlignLeft, opt.decorationSize, r1);

            style->drawPrimitive(QStyle::PE_PanelItemViewItem, &opt, painter, opt.widget);
206
            if ((option.state & static_cast<int>(QStyle::State_Selected)) != 0) {
207 208 209 210 211 212 213 214 215
                painter->setPen(option.palette.highlightedText().color());
            } else {
                painter->setPen(option.palette.text().color());
            }
            QRect r = r1;
            QFont font = painter->font();
            font.setBold(true);
            painter->setFont(font);
            if (type == AbstractProjectItem::ClipItem || type == AbstractProjectItem::SubClipItem) {
216
                int decoWidth = 0;
217
                AbstractProjectItem::CLIPSTATUS clipStatus = (AbstractProjectItem::CLIPSTATUS)index.data(AbstractProjectItem::ClipStatus).toInt();
218
                if (opt.decorationSize.height() > 0) {
219
                    r.setWidth(r.height() * pCore->getCurrentDar());
220
                    QPixmap pix = opt.icon.pixmap(opt.icon.actualSize(r.size()));
221 222 223 224 225 226
                    if (!pix.isNull()) {
                        // Draw icon
                        decoWidth += r.width() + textMargin;
                        r.setWidth(r.height() * pix.width() / pix.height());
                        painter->drawPixmap(r, pix, QRect(0, 0, pix.width(), pix.height()));
                    }
227
                    m_thumbRect = r;
228
                }
229
                // Draw frame in case of missing source
230
                int cType = index.data(AbstractProjectItem::ClipType).toInt();
231
                if (clipStatus == AbstractProjectItem::StatusMissing || clipStatus == AbstractProjectItem::StatusProxyOnly) {
232
                    painter->save();
233
                    painter->setPen(QPen(clipStatus == AbstractProjectItem::StatusProxyOnly ? Qt::yellow : Qt::red, 3));
234
                    painter->drawRect(m_thumbRect.adjusted(0, 0, -1, -1));
235
                    painter->restore();
236 237 238 239 240 241 242 243 244 245 246
                } else if (cType == ClipType::Image || cType == ClipType::SlideShow) {
                    // Draw 'photo' frame to identify image clips
                    painter->save();
                    int penWidth = m_thumbRect.height() / 14;
                    penWidth += penWidth % 2;
                    painter->setPen(QPen(QColor(255, 255, 255, 160), penWidth));
                    penWidth /= 2;
                    painter->drawRoundedRect(m_thumbRect.adjusted(penWidth, penWidth, -penWidth - 1, -penWidth - 1), 4, 4);
                    painter->setPen(QPen(Qt::black, 1));
                    painter->drawRoundedRect(m_thumbRect.adjusted(0, 0, -1, -1), 4, 4);
                    painter->restore();
247
                }
248 249 250 251 252 253 254 255 256
                int mid = (int)((r1.height() / 2));
                r1.adjust(decoWidth, 0, 0, -mid);
                QRect r2 = option.rect;
                r2.adjust(decoWidth, mid, 0, 0);
                QRectF bounding;
                painter->drawText(r1, Qt::AlignLeft | Qt::AlignTop, index.data(AbstractProjectItem::DataName).toString(), &bounding);
                font.setBold(false);
                painter->setFont(font);
                QString subText = index.data(AbstractProjectItem::DataDuration).toString();
257 258 259
                QString tags = index.data(AbstractProjectItem::DataTag).toString();
                if (!tags.isEmpty()) {
                    QStringList t = tags.split(QLatin1Char(';'));
260 261 262
                    QRectF tagRect = m_thumbRect.adjusted(2, 2, 0, 2);
                    tagRect.setWidth(r1.height() / 3.5);
                    tagRect.setHeight(tagRect.width());
263
                    for (const QString &color : t) {
264 265 266
                        painter->setBrush(QColor(color));
                        painter->drawRoundedRect(tagRect, tagRect.height() / 2, tagRect.height() / 2);
                        tagRect.moveTop(tagRect.bottom() + tagRect.height() / 4);
267 268
                    }
                }
269 270 271 272 273 274 275 276
                if (!subText.isEmpty()) {
                    r2.adjust(0, bounding.bottom() - r2.top(), 0, 0);
                    QColor subTextColor = painter->pen().color();
                    subTextColor.setAlphaF(.5);
                    painter->setPen(subTextColor);
                    // Draw usage counter
                    int usage = index.data(AbstractProjectItem::UsageCount).toInt();
                    if (usage > 0) {
Laurent Montel's avatar
Laurent Montel committed
277
                        subText.append(QString::asprintf(" [%d]", usage));
278 279
                    }
                    painter->drawText(r2, Qt::AlignLeft | Qt::AlignTop, subText, &bounding);
280
                    // Add audio/video icons for selective drag
281 282
                    bool hasAudioAndVideo = index.data(AbstractProjectItem::ClipHasAudioAndVideo).toBool();
                    if (hasAudioAndVideo && (cType == ClipType::AV || cType == ClipType::Playlist) && (opt.state & QStyle::State_MouseOver)) {
283 284 285 286 287 288 289 290 291 292 293
                        bounding.moveLeft(bounding.right() + (2 * textMargin));
                        bounding.adjust(0, textMargin, 0, -textMargin);
                        QIcon aDrag = QIcon::fromTheme(QStringLiteral("audio-volume-medium"));
                        m_audioDragRect = bounding.toRect();
                        m_audioDragRect.setWidth(m_audioDragRect.height());
                        aDrag.paint(painter, m_audioDragRect, Qt::AlignLeft);
                        m_videoDragRect = m_audioDragRect;
                        m_videoDragRect.moveLeft(m_audioDragRect.right());
                        QIcon vDrag = QIcon::fromTheme(QStringLiteral("kdenlive-show-video"));
                        vDrag.paint(painter, m_videoDragRect, Qt::AlignLeft);
                    } else {
294 295
                        //m_audioDragRect = QRect();
                        //m_videoDragRect = QRect();
296 297 298 299 300 301 302 303 304 305 306 307
                    }
                }
                if (type == AbstractProjectItem::ClipItem) {
                    // Overlay icon if necessary
                    QVariant v = index.data(AbstractProjectItem::IconOverlay);
                    if (!v.isNull()) {
                        QIcon reload = QIcon::fromTheme(v.toString());
                        r.setTop(r.bottom() - bounding.height());
                        r.setWidth(bounding.height());
                        reload.paint(painter, r);
                    }
                    int jobProgress = index.data(AbstractProjectItem::JobProgress).toInt();
Nicolas Carion's avatar
Nicolas Carion committed
308
                    auto status = index.data(AbstractProjectItem::JobStatus).value<JobManagerStatus>();
309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336
                    if (status == JobManagerStatus::Pending || status == JobManagerStatus::Running) {
                        // Draw job progress bar
                        int progressWidth = option.fontMetrics.averageCharWidth() * 8;
                        int progressHeight = option.fontMetrics.ascent() / 4;
                        QRect progress(r1.x() + 1, opt.rect.bottom() - progressHeight - 2, progressWidth, progressHeight);
                        painter->setPen(Qt::NoPen);
                        painter->setBrush(Qt::darkGray);
                        if (status == JobManagerStatus::Running) {
                            painter->drawRoundedRect(progress, 2, 2);
                            painter->setBrush((option.state & static_cast<int>((QStyle::State_Selected) != 0)) != 0 ? option.palette.text()
                                                                                                                    : option.palette.highlight());
                            progress.setWidth((progressWidth - 2) * jobProgress / 100);
                            painter->drawRoundedRect(progress, 2, 2);
                        } else {
                            // Draw kind of a pause icon
                            progress.setWidth(3);
                            painter->drawRect(progress);
                            progress.moveLeft(progress.right() + 3);
                            painter->drawRect(progress);
                        }
                    }
                    bool jobsucceeded = index.data(AbstractProjectItem::JobSuccess).toBool();
                    if (!jobsucceeded) {
                        QIcon warning = QIcon::fromTheme(QStringLiteral("process-stop"));
                        warning.paint(painter, r2);
                    }
                }
            } else {
337
                // Folder
338 339
                int decoWidth = 0;
                if (opt.decorationSize.height() > 0) {
340
                    r.setWidth(r.height() * pCore->getCurrentDar());
341
                    QPixmap pix = opt.icon.pixmap(opt.icon.actualSize(r.size()));
342
                    // Draw icon
343 344 345
                    decoWidth += r.width() + textMargin;
                    r.setWidth(r.height() * pix.width() / pix.height());
                    painter->drawPixmap(r, pix, QRect(0, 0, pix.width(), pix.height()));
346 347 348 349 350 351
                }
                r1.adjust(decoWidth, 0, 0, 0);
                QRectF bounding;
                painter->drawText(r1, Qt::AlignLeft | Qt::AlignTop, index.data(AbstractProjectItem::DataName).toString(), &bounding);
            }
            painter->restore();
352
        } else if (index.column() == 7) {
353 354 355
            QStyleOptionViewItem opt(option);
            initStyleOption(&opt, index);
            QRect r1 = opt.rect;
356 357
            // Tweak bg opacity since breeze dark star has same color as highlighted background
            painter->setOpacity(0.5);
358 359
            QStyle *style = opt.widget ? opt.widget->style() : QApplication::style();
            style->drawPrimitive(QStyle::PE_PanelItemViewItem, &opt, painter, opt.widget);
360
            painter->setOpacity(1);
361
            if (index.data(AbstractProjectItem::ItemTypeRole).toInt() != AbstractProjectItem::FolderItem) {
362
                r1.adjust(r1.width() / 12, 0, 0, 0);
363
                KRatingPainter::paintRating(painter, r1, Qt::AlignLeft | Qt::AlignVCenter, index.data().toInt());
364
            }
365 366 367 368
        } else {
            QStyledItemDelegate::paint(painter, option, index);
        }
    }
369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402

    int getFrame(QModelIndex index, int mouseX)
    {
        int type = index.data(AbstractProjectItem::ItemTypeRole).toInt();
        if ((type != AbstractProjectItem::ClipItem && type != AbstractProjectItem::SubClipItem) || mouseX < m_thumbRect.x() || mouseX > m_thumbRect.right()) {
            return 0;
        }
        return 100 * (mouseX - m_thumbRect.x()) / m_thumbRect.width();
    }

private:
    mutable bool m_editorOpen{false};
    mutable QRect m_audioDragRect;
    mutable QRect m_videoDragRect;
    mutable QRect m_thumbRect;

public:
    PlaylistState::ClipState dragType{PlaylistState::Disabled};
};

/**
 * @class BinListItemDelegate
 * @brief This class is responsible for drawing items in the QListView.
 */

class BinListItemDelegate : public QStyledItemDelegate
{
public:
    explicit BinListItemDelegate(QObject *parent = nullptr)
        : QStyledItemDelegate(parent)

    {
        connect(this, &QStyledItemDelegate::closeEditor, [&]() { m_editorOpen = false; });
    }
403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420
    bool editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index) override
    {
        Q_UNUSED(model);
        Q_UNUSED(option);
        Q_UNUSED(index);
        if (event->type() == QEvent::MouseButtonPress) {
            auto *me = (QMouseEvent *)event;
            if (m_audioDragRect.contains(me->pos())) {
                dragType = PlaylistState::AudioOnly;
            } else if (m_videoDragRect.contains(me->pos())) {
                dragType = PlaylistState::VideoOnly;
            } else {
                dragType = PlaylistState::Disabled;
            }
        }
        event->ignore();
        return false;
    }
421 422 423 424

    void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const override
    {
        if (!index.data().isNull()) {
425
            QStyleOptionViewItem opt(option);
426
            initStyleOption(&opt, index);
427
            QStyledItemDelegate::paint(painter, option, index);
428
            int adjust = (opt.rect.width() - opt.decorationSize.width()) / 2;
429
            QRect rect(opt.rect.x(), opt.rect.y(), opt.decorationSize.width(), opt.decorationSize.height());
430 431 432 433
            if (adjust > 0 && adjust < rect.width()) {
                rect.translate(adjust, 0);
            }
            m_thumbRect = rect;
434

435 436 437 438 439 440 441 442 443 444 445 446 447
            //Tags
            QString tags = index.data(AbstractProjectItem::DataTag).toString();
            if (!tags.isEmpty()) {
                QStringList t = tags.split(QLatin1Char(';'));
                QRectF tagRect = m_thumbRect.adjusted(2, 2, 0, 2);
                tagRect.setWidth(m_thumbRect.height() / 5);
                tagRect.setHeight(tagRect.width());
                for (const QString &color : t) {
                    painter->setBrush(QColor(color));
                    painter->drawRoundedRect(tagRect, tagRect.height() / 2, tagRect.height() / 2);
                    tagRect.moveTop(tagRect.bottom() + tagRect.height() / 4);
                }
            }
448

449
            // Add audio/video icons for selective drag
450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468
            int cType = index.data(AbstractProjectItem::ClipType).toInt();
            bool hasAudioAndVideo = index.data(AbstractProjectItem::ClipHasAudioAndVideo).toBool();
            if (hasAudioAndVideo && (cType == ClipType::AV || cType == ClipType::Playlist) && (opt.state & QStyle::State_MouseOver)) {
                QRect thumbRect = m_thumbRect;
                int iconSize = painter->boundingRect(thumbRect, Qt::AlignLeft, QStringLiteral("O")).height();
                thumbRect.setLeft(opt.rect.right() - iconSize - 4);
                thumbRect.setWidth(iconSize);
                thumbRect.setBottom(m_thumbRect.top() + iconSize);
                QIcon aDrag = QIcon::fromTheme(QStringLiteral("audio-volume-medium"));
                m_audioDragRect = thumbRect;
                aDrag.paint(painter, m_audioDragRect, Qt::AlignRight);
                m_videoDragRect = m_audioDragRect;
                m_videoDragRect.moveTop(thumbRect.bottom());
                QIcon vDrag = QIcon::fromTheme(QStringLiteral("kdenlive-show-video"));
                vDrag.paint(painter, m_videoDragRect, Qt::AlignRight);
            } else {
                //m_audioDragRect = QRect();
                //m_videoDragRect = QRect();
            }
469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499
            // Draw frame in case of missing source
            AbstractProjectItem::CLIPSTATUS clipStatus = (AbstractProjectItem::CLIPSTATUS)index.data(AbstractProjectItem::ClipStatus).toInt();
            if (clipStatus == AbstractProjectItem::StatusMissing || clipStatus == AbstractProjectItem::StatusProxyOnly) {
                painter->save();
                painter->setPen(QPen(clipStatus == AbstractProjectItem::StatusProxyOnly ? Qt::yellow : Qt::red, 3));
                painter->drawRect(m_thumbRect);
                painter->restore();
            } else if (cType == ClipType::Image || cType == ClipType::SlideShow) {
                // Draw 'photo' frame to identify image clips
                painter->save();
                int penWidth = m_thumbRect.height() / 14;
                penWidth += penWidth % 2;
                painter->setPen(QPen(QColor(255, 255, 255, 160), penWidth));
                penWidth /= 2;
                painter->drawRoundedRect(m_thumbRect.adjusted(penWidth, penWidth, -penWidth - 1, -penWidth + 1), 4, 4);
                painter->setPen(QPen(Qt::black, 1));
                painter->drawRoundedRect(m_thumbRect.adjusted(0, 0, -1, 1), 4, 4);
                painter->restore();
            }
            int type = index.data(AbstractProjectItem::ItemTypeRole).toInt();
            if (type == AbstractProjectItem::ClipItem) {
                // Overlay icon if necessary
                QVariant v = index.data(AbstractProjectItem::IconOverlay);
                if (!v.isNull()) {
                    QRect r = m_thumbRect;
                    QIcon reload = QIcon::fromTheme(v.toString());
                    r.setTop(r.bottom() - (opt.rect.height() - r.height()));
                    r.setWidth(r.height());
                    reload.paint(painter, r);
                }
            }
500 501 502
        }
    }

503 504 505
    int getFrame(QModelIndex index, int mouseX)
    {
        int type = index.data(AbstractProjectItem::ItemTypeRole).toInt();
506
        if ((type != AbstractProjectItem::ClipItem && type != AbstractProjectItem::SubClipItem)|| mouseX < m_thumbRect.x() || mouseX > m_thumbRect.right()) {
507 508 509 510
            return 0;
        }
        return 100 * (mouseX - m_thumbRect.x()) / m_thumbRect.width();
    }
511 512

private:
Nicolas Carion's avatar
Nicolas Carion committed
513
    mutable bool m_editorOpen{false};
514 515
    mutable QRect m_audioDragRect;
    mutable QRect m_videoDragRect;
516
    mutable QRect m_thumbRect;
517 518

public:
Nicolas Carion's avatar
Nicolas Carion committed
519
    PlaylistState::ClipState dragType{PlaylistState::Disabled};
520 521
};

522

523 524
MyListView::MyListView(QWidget *parent)
    : QListView(parent)
525 526 527 528
{
    setViewMode(QListView::IconMode);
    setMovement(QListView::Static);
    setResizeMode(QListView::Adjust);
529
    setWordWrap(true);
530 531 532 533 534 535 536 537 538
    setDragDropMode(QAbstractItemView::DragDrop);
    setAcceptDrops(true);
    setDragEnabled(true);
    viewport()->setAcceptDrops(true);
}

void MyListView::focusInEvent(QFocusEvent *event)
{
    QListView::focusInEvent(event);
539 540 541
    if (event->reason() == Qt::MouseFocusReason) {
        emit focusView();
    }
542 543
}

544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559
void MyListView::mousePressEvent(QMouseEvent *event)
{
    QListView::mousePressEvent(event);
    if (event->button() == Qt::LeftButton) {
        m_startPos = event->pos();
        QModelIndex ix = indexAt(m_startPos);
        if (ix.isValid()) {
            QAbstractItemDelegate *del = itemDelegate(ix);
            m_dragType = static_cast<BinListItemDelegate *>(del)->dragType;
        } else {
            m_dragType = PlaylistState::Disabled;
        }
        emit updateDragMode(m_dragType);
    }
}

560 561
void MyListView::mouseMoveEvent(QMouseEvent *event)
{
562
    if (KdenliveSettings::hoverPreview()) {
563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578
        QModelIndex index = indexAt(event->pos());
        if (index.isValid()) {
            QAbstractItemDelegate *del = itemDelegate(index);
            if (del) {
                auto delegate = static_cast<BinListItemDelegate *>(del);
                QRect vRect = visualRect(index);
                int frame = delegate->getFrame(index, event->pos().x() - vRect.x());
                emit displayBinFrame(index, frame);
            } else {
                qDebug()<<"<<< NO DELEGATE!!!";
            }
        }
    }
    QListView::mouseMoveEvent(event);
}

579 580
MyTreeView::MyTreeView(QWidget *parent)
    : QTreeView(parent)
581 582
{
    setEditing(false);
583
    setAcceptDrops(true);
584
}
585 586 587

void MyTreeView::mousePressEvent(QMouseEvent *event)
{
588
    QTreeView::mousePressEvent(event);
589 590
    if (event->button() == Qt::LeftButton) {
        m_startPos = event->pos();
591 592 593
        QModelIndex ix = indexAt(m_startPos);
        if (ix.isValid()) {
            QAbstractItemDelegate *del = itemDelegate(ix);
594
            m_dragType = static_cast<BinItemDelegate *>(del)->dragType;
595 596 597
        } else {
            m_dragType = PlaylistState::Disabled;
        }
598 599 600
    }
}

601 602 603
void MyTreeView::focusInEvent(QFocusEvent *event)
{
    QTreeView::focusInEvent(event);
604 605 606
    if (event->reason() == Qt::MouseFocusReason) {
        emit focusView();
    }
607 608
}

609
void MyTreeView::mouseMoveEvent(QMouseEvent *event)
610 611
{
    bool dragged = false;
612
    if ((event->buttons() & Qt::LeftButton) != 0u) {
613
        int distance = (event->pos() - m_startPos).manhattanLength();
614 615 616
        if (distance >= QApplication::startDragDistance()) {
            dragged = performDrag();
        }
617
    } else if (KdenliveSettings::hoverPreview()) {
618 619 620 621 622 623
        QModelIndex index = indexAt(event->pos());
        if (index.isValid()) {
            QAbstractItemDelegate *del = itemDelegate(index);
            int frame = static_cast<BinItemDelegate *>(del)->getFrame(index, event->pos().x());
            emit displayBinFrame(index, frame);
        }
624 625 626
    }
    if (!dragged) {
        QTreeView::mouseMoveEvent(event);
627 628 629
    }
}

630 631 632 633 634 635 636 637 638 639 640 641
void MyTreeView::closeEditor(QWidget *editor, QAbstractItemDelegate::EndEditHint hint)
{
    QAbstractItemView::closeEditor(editor, hint);
    setEditing(false);
}

void MyTreeView::editorDestroyed(QObject *editor)
{
    QAbstractItemView::editorDestroyed(editor);
    setEditing(false);
}

Laurent Montel's avatar
Laurent Montel committed
642
bool MyTreeView::isEditing() const
643
{
644
    return state() == QAbstractItemView::EditingState;
645 646 647 648
}

void MyTreeView::setEditing(bool edit)
{
649
    setState(edit ? QAbstractItemView::EditingState : QAbstractItemView::NoState);
650 651 652 653
    if (!edit) {
        // Ensure edited item is selected
        emit selectCurrent();
    }
654 655
}

656 657 658 659 660 661 662 663 664
bool MyTreeView::performDrag()
{
    QModelIndexList bases = selectedIndexes();
    QModelIndexList indexes;
    for (int i = 0; i < bases.count(); i++) {
        if (bases.at(i).column() == 0) {
            indexes << bases.at(i);
        }
    }
665 666 667
    if (indexes.isEmpty()) {
        return false;
    }
668 669
    // Check if we want audio or video only
    emit updateDragMode(m_dragType);
Nicolas Carion's avatar
Nicolas Carion committed
670
    auto *drag = new QDrag(this);
671
    drag->setMimeData(model()->mimeData(indexes));
Laurent Montel's avatar
Laurent Montel committed
672
    QModelIndex ix = indexes.constFirst();
673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694
    if (ix.isValid()) {
        QIcon icon = ix.data(AbstractProjectItem::DataThumbnail).value<QIcon>();
        QPixmap pix = icon.pixmap(iconSize());
        QSize size = pix.size();
        QImage image(size, QImage::Format_ARGB32_Premultiplied);
        image.fill(Qt::transparent);
        QPainter p(&image);
        p.setOpacity(0.7);
        p.drawPixmap(0, 0, pix);
        p.setOpacity(1);
        if (indexes.count() > 1) {
            QPalette palette;
            int radius = size.height() / 3;
            p.setBrush(palette.highlight());
            p.setPen(palette.highlightedText().color());
            p.drawEllipse(QPoint(size.width() / 2, size.height() / 2), radius, radius);
            p.drawText(size.width() / 2 - radius, size.height() / 2 - radius, 2 * radius, 2 * radius, Qt::AlignCenter, QString::number(indexes.count()));
        }
        p.end();
        drag->setPixmap(QPixmap::fromImage(image));
    }
    drag->exec();
695
    emit processDragEnd();
696 697 698
    return true;
}

699 700
SmallJobLabel::SmallJobLabel(QWidget *parent)
    : QPushButton(parent)
Nicolas Carion's avatar
Nicolas Carion committed
701

702 703 704 705
{
    setFixedWidth(0);
    setFlat(true);
    m_timeLine = new QTimeLine(500, this);
Laurent Montel's avatar
Laurent Montel committed
706 707
    QObject::connect(m_timeLine, &QTimeLine::valueChanged, this, &SmallJobLabel::slotTimeLineChanged);
    QObject::connect(m_timeLine, &QTimeLine::finished, this, &SmallJobLabel::slotTimeLineFinished);
708 709 710 711 712
    hide();
}

const QString SmallJobLabel::getStyleSheet(const QPalette &p)
{
713
    KColorScheme scheme(p.currentColorGroup(), KColorScheme::Window);
714 715
    QColor bg = scheme.background(KColorScheme::LinkBackground).color();
    QColor fg = scheme.foreground(KColorScheme::LinkText).color();
Nicolas Carion's avatar
Nicolas Carion committed
716 717 718 719 720 721 722 723
    QString style =
        QStringLiteral("QPushButton {margin:3px;padding:2px;background-color: rgb(%1, %2, %3);border-radius: 4px;border: none;color: rgb(%4, %5, %6)}")
            .arg(bg.red())
            .arg(bg.green())
            .arg(bg.blue())
            .arg(fg.red())
            .arg(fg.green())
            .arg(fg.blue());
724

725 726
    bg = scheme.background(KColorScheme::ActiveBackground).color();
    fg = scheme.foreground(KColorScheme::ActiveText).color();
Nicolas Carion's avatar
Nicolas Carion committed
727 728 729 730 731 732 733 734
    style.append(
        QStringLiteral("\nQPushButton:hover {margin:3px;padding:2px;background-color: rgb(%1, %2, %3);border-radius: 4px;border: none;color: rgb(%4, %5, %6)}")
            .arg(bg.red())
            .arg(bg.green())
            .arg(bg.blue())
            .arg(fg.red())
            .arg(fg.green())
            .arg(fg.blue()));
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
735

736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763
    return style;
}

void SmallJobLabel::setAction(QAction *action)
{
    m_action = action;
}

void SmallJobLabel::slotTimeLineChanged(qreal value)
{
    setFixedWidth(qMin(value * 2, qreal(1.0)) * sizeHint().width());
    update();
}

void SmallJobLabel::slotTimeLineFinished()
{
    if (m_timeLine->direction() == QTimeLine::Forward) {
        // Show
        m_action->setVisible(true);
    } else {
        // Hide
        m_action->setVisible(false);
        setText(QString());
    }
}

void SmallJobLabel::slotSetJobCount(int jobCount)
{
Nicolas Carion's avatar
Nicolas Carion committed
764
    QMutexLocker lk(&m_locker);
765 766 767 768
    if (jobCount > 0) {
        // prepare animation
        setText(i18np("%1 job", "%1 jobs", jobCount));
        setToolTip(i18np("%1 pending job", "%1 pending jobs", jobCount));
769

Nicolas Carion's avatar
Nicolas Carion committed
770
        if (style()->styleHint(QStyle::SH_Widget_Animate, nullptr, this) != 0) {
771 772 773 774
            setFixedWidth(sizeHint().width());
            m_action->setVisible(true);
            return;
        }
775

776 777 778 779 780
        if (m_action->isVisible()) {
            setFixedWidth(sizeHint().width());
            update();
            return;
        }
781

782 783 784 785 786 787 788 789
        setFixedWidth(0);
        m_action->setVisible(true);
        int wantedWidth = sizeHint().width();
        setGeometry(-wantedWidth, 0, wantedWidth, height());
        m_timeLine->setDirection(QTimeLine::Forward);
        if (m_timeLine->state() == QTimeLine::NotRunning) {
            m_timeLine->start();
        }
790
    } else {
Nicolas Carion's avatar
Nicolas Carion committed
791
        if (style()->styleHint(QStyle::SH_Widget_Animate, nullptr, this) != 0) {
792 793 794 795 796 797 798 799 800 801 802 803
            setFixedWidth(0);
            m_action->setVisible(false);
            return;
        }
        // hide
        m_timeLine->setDirection(QTimeLine::Backward);
        if (m_timeLine->state() == QTimeLine::NotRunning) {
            m_timeLine->start();
        }
    }
}

804 805
LineEventEater::LineEventEater(QObject *parent)
    : QObject(parent)
806 807 808 809 810
{
}

bool LineEventEater::eventFilter(QObject *obj, QEvent *event)
{
811
    switch (event->type()) {
812 813 814 815 816 817 818 819 820 821 822
    case QEvent::ShortcutOverride:
        if (((QKeyEvent *)event)->key() == Qt::Key_Escape) {
            emit clearSearchLine();
        }
        break;
    case QEvent::Resize:
        // Workaround Qt BUG 54676
        emit showClearButton(((QResizeEvent *)event)->size().width() > QFontMetrics(QApplication::font()).averageCharWidth() * 8);
        break;
    default:
        break;
823 824 825 826
    }
    return QObject::eventFilter(obj, event);
}

Nicolas Carion's avatar
Nicolas Carion committed
827
Bin::Bin(std::shared_ptr<ProjectItemModel> model, QWidget *parent)
828 829
    : QWidget(parent)
    , isLoading(false)
Nicolas Carion's avatar
Nicolas Carion committed
830
    , m_itemModel(std::move(model))
831
    , m_itemView(nullptr)
832 833
    , m_binTreeViewDelegate(nullptr)
    , m_binListViewDelegate(nullptr)
834 835 836 837 838 839 840 841 842
    , m_doc(nullptr)
    , m_extractAudioAction(nullptr)
    , m_transcodeAction(nullptr)
    , m_clipsActionsMenu(nullptr)
    , m_inTimelineAction(nullptr)
    , m_listType((BinViewType)KdenliveSettings::binMode())
    , m_iconSize(160, 90)
    , m_propertiesPanel(nullptr)
    , m_blankThumb()
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
843
    , m_filterGroup(this)
844 845
    , m_filterRateGroup(this)
    , m_filterTypeGroup(this)
846 847 848 849
    , m_invalidClipDialog(nullptr)
    , m_gainedFocus(false)
    , m_audioDuration(0)
    , m_processedAudio(0)
850
{
851
    m_layout = new QVBoxLayout(this);
852 853

    // Create toolbar for buttons
854
    m_toolbar = new QToolBar(this);
855 856 857
    int size = style()->pixelMetric(QStyle::PM_SmallIconSize);
    QSize iconSize(size, size);
    m_toolbar->setIconSize(iconSize);
858
    m_toolbar->setToolButtonStyle(Qt::ToolButtonIconOnly);
859
    m_layout->addWidget(m_toolbar);
860 861 862 863

    // Tags panel
    m_tagsWidget = new TagWidget(this);
    connect(m_tagsWidget, &TagWidget::switchTag, this, &Bin::switchTag);
864
    connect(m_tagsWidget, &TagWidget::updateProjectTags, this, &Bin::updateTags);
865 866 867
    m_tagsWidget->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Maximum);
    m_layout->addWidget(m_tagsWidget);
    m_tagsWidget->setVisible(false);
868

869 870
    m_layout->setSpacing(0);
    m_layout->setContentsMargins(0, 0, 0, 0);
871
    // Search line
872 873
    m_searchLine = new QLineEdit(this);
    m_searchLine->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Preferred);
874
    m_searchLine->setFont(QFontDatabase::systemFont(QFontDatabase::SmallestReadableFont));
Nicolas Carion's avatar
Nicolas Carion committed
875
    // m_searchLine->setClearButtonEnabled(true);
876
    m_searchLine->setPlaceholderText(i18n("Search..."));
877
    m_searchLine->setFocusPolicy(Qt::ClickFocus);
878

Nicolas Carion's avatar
Nicolas Carion committed
879
    auto *leventEater = new LineEventEater(this);
880
    m_searchLine->installEventFilter(leventEater);
Laurent Montel's avatar
Laurent Montel committed
881
    connect(leventEater, &LineEventEater::clearSearchLine, m_searchLine, &QLineEdit::clear);
882
    connect(leventEater, &LineEventEater::showClearButton, this, &Bin::showClearButton);
883

884
    setFocusPolicy(Qt::ClickFocus);
885

886
    connect(m_itemModel.get(), &ProjectItemModel::refreshPanel, this, &Bin::refreshPanel);
887
    connect(m_itemModel.get(), &ProjectItemModel::refreshClip, this, &Bin::refreshClip);
Nicolas Carion's avatar
Nicolas Carion committed
888 889 890 891
    connect(m_itemModel.get(), static_cast<void (ProjectItemModel::*)(const QStringList &, const QModelIndex &)>(&ProjectItemModel::itemDropped), this,
            static_cast<void (Bin::*)(const QStringList &, const QModelIndex &)>(&Bin::slotItemDropped));
    connect(m_itemModel.get(), static_cast<void (ProjectItemModel::*)(const QList<QUrl> &, const QModelIndex &)>(&ProjectItemModel::itemDropped), this,
            static_cast<void (Bin::*)(const QList<QUrl> &, const QModelIndex &)>(&Bin::slotItemDropped));
892
    connect(m_itemModel.get(), &ProjectItemModel::effectDropped, this, &Bin::slotEffectDropped);
893
    connect(m_itemModel.get(), &ProjectItemModel::addTag, this, &Bin::slotTagDropped);
894
    connect(m_itemModel.get(), &QAbstractItemModel::dataChanged, this, &Bin::slotItemEdited);
895
    connect(this, &Bin::refreshPanel, this, &Bin::doRefreshPanel);
896

897
    // Zoom slider
898
    QWidget *container = new QWidget(this);
Nicolas Carion's avatar
Nicolas Carion committed
899
    auto *lay = new QHBoxLayout;
900 901
    m_slider = new QSlider(Qt::Horizontal, this);
    m_slider->setMaximumWidth(100);
902
    m_slider->setMinimumWidth(40);
903
    m_slider->setRange(0, 10);
904
    m_slider->setValue(KdenliveSettings::bin_zoom());
Laurent Montel's avatar
Laurent Montel committed
905
    connect(m_slider, &QAbstractSlider::valueChanged, this, &Bin::slotSetIconSize);
Nicolas Carion's avatar
Nicolas Carion committed
906
    auto *tb1 = new QToolButton(this);
907
    tb1->setIcon(QIcon::fromTheme(QStringLiteral("zoom-in")));
908
    connect(tb1, &QToolButton::clicked, [&]() { m_slider->setValue(qMin(m_slider->value() + 1, m_slider->maximum())); });
Nicolas Carion's avatar
Nicolas Carion committed
909
    auto *tb2 = new QToolButton(this);
910
    tb2->setIcon(QIcon::fromTheme(QStringLiteral("zoom-out")));
911
    connect(tb2, &QToolButton::clicked, [&]() { m_slider->setValue(qMax(m_slider->value() - 1, m_slider->minimum())); });
912
    lay->addWidget(tb2);
913 914
    lay->addWidget(m_slider);
    lay->addWidget(tb1);
915
    container->setLayout(lay);
Nicolas Carion's avatar
Nicolas Carion committed
916
    auto *widgetslider = new QWidgetAction(this);
917
    widgetslider->setDefaultWidget(container);
918 919

    // View type
920
    KSelectAction *listType = new KSelectAction(QIcon::fromTheme(QStringLiteral("view-list-tree")), i18n("View Mode"), this);
921
    pCore->window()->actionCollection()->addAction(QStringLiteral("bin_view_mode"), listType);
922
    QAction *treeViewAction = listType->addAction(QIcon::fromTheme(QStringLiteral("view-list-tree")), i18n("Tree View"));
923
    listType->addAction(treeViewAction);
924 925 926 927
    treeViewAction->setData(BinTreeView);
    if (m_listType == treeViewAction->data().toInt()) {
        listType->setCurrentAction(treeViewAction);
    }
928
    pCore->window()->actionCollection()->addAction(QStringLiteral("bin_view_mode_tree"), treeViewAction);
929

930
    QAction *iconViewAction = listType->addAction(QIcon::fromTheme(QStringLiteral("view-list-icons")), i18n("Icon View"));
931 932 933 934
    iconViewAction->setData(BinIconView);
    if (m_listType == iconViewAction->data().toInt()) {
        listType->setCurrentAction(iconViewAction);
    }