From 0d05708d97615ec03f3ae2f959a75cf2448de25e Mon Sep 17 00:00:00 2001 From: Brian Matherly Date: Thu, 20 Feb 2025 20:39:13 -0600 Subject: [PATCH 1/5] Replace astyle with clang-format Use the same format rules as MLT --- .astylerc | 13 ----- .clang-format | 110 ++++++++++++++++++++++++++++++++++++ CMakeLists.txt | 28 +++++++-- cmake/FindClangFormat.cmake | 91 +++++++++++++++++++++++++++++ 4 files changed, 225 insertions(+), 17 deletions(-) delete mode 100644 .astylerc create mode 100644 .clang-format create mode 100644 cmake/FindClangFormat.cmake diff --git a/.astylerc b/.astylerc deleted file mode 100644 index e03507ebbe..0000000000 --- a/.astylerc +++ /dev/null @@ -1,13 +0,0 @@ ---style=kr ---indent=spaces=4 ---align-pointer=name ---align-reference=name ---convert-tabs ---attach-namespaces ---max-code-length=100 ---max-continuation-indent=120 ---pad-header ---pad-oper ---suffix=none ---exclude="CuteLogger" ---exclude="src/spatialmedia" diff --git a/.clang-format b/.clang-format new file mode 100644 index 0000000000..3f5bbe8b79 --- /dev/null +++ b/.clang-format @@ -0,0 +1,110 @@ +# .clang-format for MLT +# +# Adapted from https://github.com/qt-creator/qt-creator/blob/master/.clang-format +# +# The configuration below follows the Qt Creator Coding Rules [1] as closely as +# possible. For documentation of the options, see [2]. +# +# +# [1] https://doc-snapshots.qt.io/qtcreator-extending/coding-style.html +# [2] https://clang.llvm.org/docs/ClangFormatStyleOptions.html +# +--- +AccessModifierOffset: -4 +AlignAfterOpenBracket: Align +AlignConsecutiveAssignments: false +AlignConsecutiveDeclarations: false +AlignEscapedNewlines: DontAlign +AlignOperands: true +AlignTrailingComments: true +AllowAllParametersOfDeclarationOnNextLine: true +AllowShortBlocksOnASingleLine: Never +AllowShortCaseLabelsOnASingleLine: false +AllowShortFunctionsOnASingleLine: Inline +AllowShortIfStatementsOnASingleLine: false +AllowShortLoopsOnASingleLine: false +AlwaysBreakAfterReturnType: None +AlwaysBreakBeforeMultilineStrings: false +AlwaysBreakTemplateDeclarations: Yes +BinPackArguments: false +BinPackParameters: false +BraceWrapping: + AfterClass: true + AfterControlStatement: Never + AfterEnum: false + AfterFunction: true + AfterNamespace: false + AfterObjCDeclaration: false + AfterStruct: true + AfterUnion: false + BeforeCatch: false + BeforeElse: false + IndentBraces: false + SplitEmptyFunction: false + SplitEmptyRecord: false + SplitEmptyNamespace: false +BreakBeforeBinaryOperators: All +BreakBeforeBraces: Custom +BreakBeforeInheritanceComma: false +BreakBeforeTernaryOperators: true +BreakConstructorInitializersBeforeComma: false +BreakConstructorInitializers: BeforeComma +BreakAfterJavaFieldAnnotations: false +BreakStringLiterals: true +ColumnLimit: 100 +CommentPragmas: '^ IWYU pragma:' +CompactNamespaces: false +ConstructorInitializerAllOnOneLineOrOnePerLine: false +ConstructorInitializerIndentWidth: 4 +ContinuationIndentWidth: 4 +Cpp11BracedListStyle: true +DerivePointerAlignment: false +DisableFormat: false +ExperimentalAutoDetectBinPacking: false +FixNamespaceComments: true +ForEachMacros: + - forever # avoids { wrapped to next line + - foreach + - Q_FOREACH + - BOOST_FOREACH +IncludeCategories: + - Regex: '^ Date: Thu, 20 Feb 2025 21:49:09 -0600 Subject: [PATCH 2/5] Apply clang-format --- src/abstractproducerwidget.cpp | 18 +- src/abstractproducerwidget.h | 5 +- src/actions.cpp | 6 +- src/actions.h | 7 +- src/autosavefile.cpp | 7 +- src/autosavefile.h | 5 +- src/commands/filtercommands.cpp | 135 +- src/commands/filtercommands.h | 109 +- src/commands/markercommands.cpp | 18 +- src/commands/markercommands.h | 13 +- src/commands/playlistcommands.cpp | 55 +- src/commands/playlistcommands.h | 66 +- src/commands/subtitlecommands.cpp | 34 +- src/commands/subtitlecommands.h | 49 +- src/commands/timelinecommands.cpp | 494 ++++--- src/commands/timelinecommands.h | 318 +++-- src/commands/undohelper.cpp | 82 +- src/commands/undohelper.h | 19 +- src/controllers/filtercontroller.cpp | 89 +- src/controllers/filtercontroller.h | 27 +- src/controllers/scopecontroller.cpp | 11 +- src/controllers/scopecontroller.h | 7 +- src/database.cpp | 33 +- src/database.h | 2 +- src/dataqueue.h | 20 +- src/dialogs/actionsdialog.cpp | 119 +- src/dialogs/addencodepresetdialog.cpp | 6 +- src/dialogs/alignaudiodialog.cpp | 113 +- src/dialogs/alignaudiodialog.h | 4 +- src/dialogs/alignmentarray.cpp | 41 +- src/dialogs/alignmentarray.h | 6 +- src/dialogs/bitratedialog.cpp | 366 ++--- src/dialogs/bitratedialog.h | 68 +- src/dialogs/customprofiledialog.cpp | 25 +- src/dialogs/durationdialog.cpp | 6 +- src/dialogs/editmarkerdialog.cpp | 4 +- src/dialogs/editmarkerdialog.h | 4 +- src/dialogs/filedatedialog.cpp | 23 +- src/dialogs/listselectiondialog.cpp | 13 +- src/dialogs/longuitask.cpp | 1 + src/dialogs/longuitask.h | 4 +- src/dialogs/multifileexportdialog.cpp | 41 +- src/dialogs/multifileexportdialog.h | 8 +- src/dialogs/resourcedialog.cpp | 15 +- src/dialogs/saveimagedialog.cpp | 23 +- src/dialogs/saveimagedialog.h | 5 +- src/dialogs/slideshowgeneratordialog.h | 1 - src/dialogs/subtitletrackdialog.cpp | 11 +- src/dialogs/systemsyncdialog.cpp | 12 +- src/dialogs/textviewerdialog.cpp | 22 +- src/dialogs/transcodedialog.cpp | 21 +- src/dialogs/transcodedialog.h | 10 +- src/dialogs/transcribeaudiodialog.cpp | 51 +- src/dialogs/unlinkedfilesdialog.cpp | 32 +- src/dialogs/unlinkedfilesdialog.h | 2 +- src/docks/encodedock.cpp | 591 ++++---- src/docks/encodedock.h | 25 +- src/docks/filesdock.cpp | 354 ++--- src/docks/filesdock.h | 9 +- src/docks/filtersdock.cpp | 95 +- src/docks/filtersdock.h | 19 +- src/docks/jobsdock.cpp | 59 +- src/docks/keyframesdock.cpp | 343 +++-- src/docks/keyframesdock.h | 14 +- src/docks/markersdock.cpp | 95 +- src/docks/markersdock.h | 3 +- src/docks/notesdock.cpp | 33 +- src/docks/playlistdock.cpp | 541 ++++--- src/docks/playlistdock.h | 10 +- src/docks/recentdock.cpp | 16 +- src/docks/recentdock.h | 2 +- src/docks/scopedock.cpp | 16 +- src/docks/scopedock.h | 3 +- src/docks/subtitlesdock.cpp | 192 +-- src/docks/subtitlesdock.h | 7 +- src/docks/timelinedock.cpp | 959 +++++++------ src/docks/timelinedock.h | 119 +- src/jobqueue.cpp | 26 +- src/jobqueue.h | 15 +- src/jobs/abstractjob.cpp | 17 +- src/jobs/abstractjob.h | 28 +- src/jobs/bitrateviewerjob.cpp | 135 +- src/jobs/bitrateviewerjob.h | 83 +- src/jobs/encodejob.cpp | 60 +- src/jobs/encodejob.h | 6 +- src/jobs/ffmpegjob.cpp | 17 +- src/jobs/ffmpegjob.h | 5 +- src/jobs/ffprobejob.cpp | 14 +- src/jobs/ffprobejob.h | 1 + src/jobs/gopro2gpxjob.cpp | 9 +- src/jobs/gopro2gpxjob.h | 3 +- src/jobs/meltjob.cpp | 38 +- src/jobs/meltjob.h | 23 +- src/jobs/postjobaction.cpp | 12 +- src/jobs/postjobaction.h | 18 +- src/jobs/qimagejob.cpp | 6 +- src/jobs/qimagejob.h | 1 + src/jobs/videoqualityjob.cpp | 21 +- src/jobs/videoqualityjob.h | 7 +- src/jobs/whisperjob.cpp | 14 +- src/jobs/whisperjob.h | 9 +- src/main.cpp | 143 +- src/mainwindow.cpp | 1265 ++++++++++------- src/mainwindow.h | 67 +- src/mltcontroller.cpp | 390 ++--- src/mltcontroller.h | 111 +- src/mltxmlchecker.cpp | 93 +- src/mltxmlchecker.h | 64 +- src/models/actionsmodel.cpp | 45 +- src/models/actionsmodel.h | 3 +- src/models/alignclipsmodel.cpp | 31 +- src/models/alignclipsmodel.h | 4 +- src/models/attachedfiltersmodel.cpp | 140 +- src/models/attachedfiltersmodel.h | 16 +- src/models/audiolevelstask.cpp | 81 +- src/models/audiolevelstask.h | 11 +- src/models/keyframesmodel.cpp | 169 ++- src/models/keyframesmodel.h | 39 +- src/models/markersmodel.cpp | 165 ++- src/models/markersmodel.h | 10 +- src/models/metadatamodel.cpp | 67 +- src/models/metadatamodel.h | 28 +- src/models/motiontrackermodel.cpp | 102 +- src/models/motiontrackermodel.h | 21 +- src/models/multitrackmodel.cpp | 426 +++--- src/models/multitrackmodel.h | 106 +- src/models/playlistmodel.cpp | 181 ++- src/models/playlistmodel.h | 29 +- src/models/resourcemodel.cpp | 141 +- src/models/resourcemodel.h | 3 - src/models/subtitles.h | 3 +- src/models/subtitlesmodel.cpp | 137 +- src/models/subtitlesmodel.h | 14 +- src/models/subtitlesselectionmodel.cpp | 36 +- src/models/subtitlesselectionmodel.h | 2 +- src/openotherdialog.cpp | 15 +- src/openotherdialog.h | 7 +- src/player.cpp | 247 ++-- src/player.h | 24 +- src/proxymanager.cpp | 441 +++--- src/proxymanager.h | 20 +- src/qmltypes/colordialog.cpp | 6 +- src/qmltypes/colordialog.h | 14 +- src/qmltypes/colorpickeritem.cpp | 25 +- src/qmltypes/colorwheelitem.cpp | 50 +- src/qmltypes/colorwheelitem.h | 3 +- src/qmltypes/filedialog.cpp | 1 + src/qmltypes/filedialog.h | 12 +- src/qmltypes/fontdialog.cpp | 3 +- src/qmltypes/fontdialog.h | 7 +- src/qmltypes/messagedialog.cpp | 6 +- src/qmltypes/messagedialog.h | 23 +- src/qmltypes/qmlapplication.cpp | 47 +- src/qmltypes/qmlapplication.h | 4 +- src/qmltypes/qmleditmenu.cpp | 3 +- src/qmltypes/qmlfile.cpp | 28 +- src/qmltypes/qmlfile.h | 3 +- src/qmltypes/qmlfilter.cpp | 289 ++-- src/qmltypes/qmlfilter.h | 100 +- src/qmltypes/qmlmarkermenu.cpp | 46 +- src/qmltypes/qmlmetadata.cpp | 13 +- src/qmltypes/qmlmetadata.h | 210 +-- src/qmltypes/qmlproducer.cpp | 52 +- src/qmltypes/qmlproducer.h | 28 +- src/qmltypes/qmlprofile.cpp | 8 +- src/qmltypes/qmlrichtext.cpp | 65 +- src/qmltypes/qmlrichtext.h | 35 +- src/qmltypes/qmlrichtextmenu.cpp | 3 +- src/qmltypes/qmlutilities.cpp | 38 +- src/qmltypes/qmlutilities.h | 2 +- src/qmltypes/qmlview.cpp | 7 +- src/qmltypes/thumbnailprovider.cpp | 33 +- src/qmltypes/thumbnailprovider.h | 9 +- src/qmltypes/timelineitems.cpp | 19 +- src/scrubbar.cpp | 58 +- src/scrubbar.h | 17 +- src/settings.cpp | 60 +- src/settings.h | 57 +- src/sharedframe.cpp | 52 +- src/sharedframe.h | 6 +- src/spatialmedia/spatialmedia.cpp | 2 +- src/transcoder.cpp | 145 +- src/transcoder.h | 6 +- src/util.cpp | 220 ++- src/util.h | 19 +- src/videowidget.cpp | 99 +- src/videowidget.h | 73 +- src/widgets/alsawidget.cpp | 11 +- src/widgets/alsawidget.h | 3 +- src/widgets/audiometerwidget.cpp | 51 +- src/widgets/audiometerwidget.h | 7 +- src/widgets/audioscale.cpp | 12 +- src/widgets/audioscale.h | 1 - src/widgets/avformatproducerwidget.cpp | 526 ++++--- src/widgets/avformatproducerwidget.h | 11 +- src/widgets/avfoundationproducerwidget.cpp | 48 +- src/widgets/avfoundationproducerwidget.h | 3 +- src/widgets/blipproducerwidget.cpp | 10 +- src/widgets/blipproducerwidget.h | 3 +- src/widgets/colorbarswidget.cpp | 21 +- src/widgets/colorbarswidget.h | 3 +- src/widgets/colorproducerwidget.cpp | 47 +- src/widgets/colorproducerwidget.h | 3 +- src/widgets/colorwheel.cpp | 29 +- src/widgets/colorwheel.h | 6 +- src/widgets/countproducerwidget.cpp | 20 +- src/widgets/countproducerwidget.h | 3 +- src/widgets/d3dvideowidget.cpp | 70 +- src/widgets/d3dvideowidget.h | 12 +- src/widgets/decklinkproducerwidget.cpp | 21 +- src/widgets/decklinkproducerwidget.h | 3 +- src/widgets/directshowvideowidget.cpp | 56 +- src/widgets/directshowvideowidget.h | 2 +- src/widgets/docktoolbar.cpp | 11 +- src/widgets/editmarkerwidget.cpp | 31 +- src/widgets/editmarkerwidget.h | 4 +- src/widgets/exportpresetstreeview.cpp | 4 +- src/widgets/fixx11h.h | 23 +- src/widgets/frameratewidget.cpp | 4 +- src/widgets/glaxnimateproducerwidget.cpp | 159 ++- src/widgets/glaxnimateproducerwidget.h | 17 +- src/widgets/iecscale.h | 2 +- src/widgets/imageproducerwidget.cpp | 87 +- src/widgets/imageproducerwidget.h | 7 +- src/widgets/isingwidget.cpp | 9 +- src/widgets/isingwidget.h | 3 +- src/widgets/lineeditclear.cpp | 21 +- src/widgets/lineeditclear.h | 1 - src/widgets/lissajouswidget.cpp | 9 +- src/widgets/lissajouswidget.h | 3 +- src/widgets/lumamixtransition.cpp | 43 +- src/widgets/lumamixtransition.h | 2 +- src/widgets/metalvideowidget.mm | 2 +- src/widgets/mltclipproducerwidget.cpp | 23 +- src/widgets/mltclipproducerwidget.h | 2 +- src/widgets/networkproducerwidget.cpp | 7 +- src/widgets/networkproducerwidget.h | 3 +- src/widgets/newprojectfolder.cpp | 67 +- src/widgets/newprojectfolder.h | 4 +- src/widgets/noisewidget.cpp | 9 +- src/widgets/noisewidget.h | 3 +- src/widgets/openglvideowidget.cpp | 117 +- src/widgets/openglvideowidget.h | 6 +- src/widgets/plasmawidget.cpp | 13 +- src/widgets/plasmawidget.h | 3 +- src/widgets/playlisticonview.cpp | 58 +- src/widgets/playlisticonview.h | 16 +- src/widgets/playlistlistview.cpp | 4 +- src/widgets/playlisttable.cpp | 8 +- src/widgets/producerpreviewwidget.cpp | 32 +- src/widgets/producerpreviewwidget.h | 4 +- src/widgets/pulseaudiowidget.cpp | 9 +- src/widgets/pulseaudiowidget.h | 3 +- src/widgets/resourcewidget.cpp | 10 +- src/widgets/resourcewidget.h | 1 - .../scopes/audioloudnessscopewidget.cpp | 122 +- src/widgets/scopes/audioloudnessscopewidget.h | 5 +- .../scopes/audiopeakmeterscopewidget.cpp | 40 +- .../scopes/audiopeakmeterscopewidget.h | 3 +- .../scopes/audiospectrumscopewidget.cpp | 118 +- src/widgets/scopes/audiospectrumscopewidget.h | 2 +- .../scopes/audiosurroundscopewidget.cpp | 25 +- src/widgets/scopes/audiosurroundscopewidget.h | 3 +- src/widgets/scopes/audiovectorscopewidget.cpp | 13 +- src/widgets/scopes/audiovectorscopewidget.h | 3 +- .../scopes/audiowaveformscopewidget.cpp | 52 +- src/widgets/scopes/audiowaveformscopewidget.h | 3 +- src/widgets/scopes/scopewidget.cpp | 8 +- src/widgets/scopes/scopewidget.h | 15 +- .../scopes/videohistogramscopewidget.cpp | 27 +- .../scopes/videohistogramscopewidget.h | 9 +- .../scopes/videorgbparadescopewidget.cpp | 21 +- .../scopes/videorgbparadescopewidget.h | 3 +- .../scopes/videorgbwaveformscopewidget.cpp | 19 +- .../scopes/videorgbwaveformscopewidget.h | 3 +- src/widgets/scopes/videovectorscopewidget.cpp | 65 +- src/widgets/scopes/videovectorscopewidget.h | 7 +- .../scopes/videowaveformscopewidget.cpp | 19 +- src/widgets/scopes/videowaveformscopewidget.h | 3 +- src/widgets/scopes/videozoomscopewidget.cpp | 71 +- src/widgets/scopes/videozoomwidget.cpp | 91 +- src/widgets/scopes/videozoomwidget.h | 11 +- src/widgets/screenselector.cpp | 15 +- src/widgets/screenselector.h | 5 +- src/widgets/servicepresetwidget.cpp | 12 +- src/widgets/servicepresetwidget.h | 2 +- src/widgets/slideshowgeneratorwidget.cpp | 88 +- src/widgets/slideshowgeneratorwidget.h | 6 +- src/widgets/statuslabelwidget.cpp | 15 +- src/widgets/statuslabelwidget.h | 4 +- src/widgets/textproducerwidget.cpp | 84 +- src/widgets/textproducerwidget.h | 3 +- src/widgets/timelinepropertieswidget.cpp | 18 +- src/widgets/timelinepropertieswidget.h | 2 +- src/widgets/timespinbox.cpp | 20 +- src/widgets/timespinbox.h | 2 +- src/widgets/toneproducerwidget.cpp | 13 +- src/widgets/toneproducerwidget.h | 3 +- src/widgets/trackpropertieswidget.cpp | 19 +- src/widgets/trackpropertieswidget.h | 2 +- src/widgets/video4linuxwidget.cpp | 41 +- src/widgets/video4linuxwidget.h | 3 +- src/windowstools.cpp | 4 +- src/windowstools.h | 3 +- 304 files changed, 9113 insertions(+), 7500 deletions(-) mode change 100755 => 100644 src/docks/encodedock.cpp mode change 100755 => 100644 src/docks/encodedock.h diff --git a/src/abstractproducerwidget.cpp b/src/abstractproducerwidget.cpp index 7dc04c5d10..6db8202784 100644 --- a/src/abstractproducerwidget.cpp +++ b/src/abstractproducerwidget.cpp @@ -16,15 +16,12 @@ */ #include "abstractproducerwidget.h" + #include -AbstractProducerWidget::AbstractProducerWidget() -{ -} +AbstractProducerWidget::AbstractProducerWidget() {} -AbstractProducerWidget::~AbstractProducerWidget() -{ -} +AbstractProducerWidget::~AbstractProducerWidget() {} void AbstractProducerWidget::setProducer(Mlt::Producer *producer) { @@ -39,10 +36,9 @@ void AbstractProducerWidget::setProducer(Mlt::Producer *producer) bool AbstractProducerWidget::isDevice(const QWidget *widget) { auto name = widget->objectName(); - return "AlsaWidget" == name || "alsaWidget" == name - || "AvfoundationProducerWidget" == name || "avfoundationWidget" == name - || "DecklinkProducerWidget" == name || "decklinkWidget" == name - || "DirectShowVideoWidget" == name || "dshowVideoWidget" == name - || "PulseAudioWidget" == name || "pulseWidget" == name + return "AlsaWidget" == name || "alsaWidget" == name || "AvfoundationProducerWidget" == name + || "avfoundationWidget" == name || "DecklinkProducerWidget" == name + || "decklinkWidget" == name || "DirectShowVideoWidget" == name + || "dshowVideoWidget" == name || "PulseAudioWidget" == name || "pulseWidget" == name || "Video4LinuxWidget" == name || "v4lWidget" == name; } diff --git a/src/abstractproducerwidget.h b/src/abstractproducerwidget.h index 317b4b6605..338228ccbc 100644 --- a/src/abstractproducerwidget.h +++ b/src/abstractproducerwidget.h @@ -36,10 +36,7 @@ class AbstractProducerWidget return p; } virtual void loadPreset(Mlt::Properties &) {} - Mlt::Producer *producer() const - { - return m_producer.data(); - } + Mlt::Producer *producer() const { return m_producer.data(); } static bool isDevice(const QWidget *widget); protected: diff --git a/src/actions.cpp b/src/actions.cpp index 0764107705..c026fff34d 100644 --- a/src/actions.cpp +++ b/src/actions.cpp @@ -17,7 +17,7 @@ #include "actions.h" -#include +#include "Logger.h" #include "settings.h" #include @@ -51,7 +51,7 @@ void ShotcutActions::add(const QString &key, QAction *action, QString group) if (group.isEmpty()) { group = tr("Other"); } - action->setProperty(displayProperty, group + " > " + action->iconText()); + action->setProperty(displayProperty, group + " > " + action->iconText()); QList sequences = action->shortcuts(); if (sequences.size() > 0) @@ -93,7 +93,7 @@ void ShotcutActions::loadFromMenu(QMenu *menu, QString group) } } -QAction *ShotcutActions::operator [](const QString &key) +QAction *ShotcutActions::operator[](const QString &key) { auto iterator = m_actions.find(key); if (iterator != m_actions.end()) { diff --git a/src/actions.h b/src/actions.h index c5d5853000..34561f169f 100644 --- a/src/actions.h +++ b/src/actions.h @@ -29,7 +29,6 @@ class ShotcutActions : public QObject Q_OBJECT public: - static const char *hardKeyProperty; static const char *displayProperty; static const char *defaultKey1Property; @@ -37,11 +36,13 @@ class ShotcutActions : public QObject static const char *defaultToolTipProperty; static ShotcutActions &singleton(); - explicit ShotcutActions() : QObject() {} + explicit ShotcutActions() + : QObject() + {} void add(const QString &name, QAction *action, QString group = ""); void loadFromMenu(QMenu *menu, const QString group = ""); - QAction *operator [](const QString &key); + QAction *operator[](const QString &key); QList keys(); void overrideShortcuts(const QString &key, QList shortcuts); void initializeShortcuts(); diff --git a/src/autosavefile.cpp b/src/autosavefile.cpp index 699284c5b7..4ef6f7555e 100644 --- a/src/autosavefile.cpp +++ b/src/autosavefile.cpp @@ -19,18 +19,19 @@ */ #include "autosavefile.h" + #include "settings.h" -#include #include +#include static const QLatin1String subdir("/autosave"); static const QLatin1String extension(".mlt"); static QString hashName(const QString &name) { - return QString::fromLatin1(QCryptographicHash::hash(name.toUtf8(), - QCryptographicHash::Md5).toHex()); + return QString::fromLatin1( + QCryptographicHash::hash(name.toUtf8(), QCryptographicHash::Md5).toHex()); } AutoSaveFile::AutoSaveFile(const QString &filename, QObject *parent) diff --git a/src/autosavefile.h b/src/autosavefile.h index 5d59b6708c..b907c56a80 100644 --- a/src/autosavefile.h +++ b/src/autosavefile.h @@ -31,10 +31,7 @@ class AutoSaveFile : public QFile explicit AutoSaveFile(const QString &filename, QObject *parent = 0); ~AutoSaveFile(); - QString managedFileName() const - { - return m_managedFile; - } + QString managedFileName() const { return m_managedFile; } void changeManagedFile(const QString &filename); virtual bool open(OpenMode openmode); diff --git a/src/commands/filtercommands.cpp b/src/commands/filtercommands.cpp index 14e9132abc..be92a98f23 100644 --- a/src/commands/filtercommands.cpp +++ b/src/commands/filtercommands.cpp @@ -16,11 +16,12 @@ */ #include "filtercommands.h" -#include "qmltypes/qmlmetadata.h" + +#include "Logger.h" #include "controllers/filtercontroller.h" #include "mainwindow.h" #include "mltcontroller.h" -#include +#include "qmltypes/qmlmetadata.h" class FindProducerParser : public Mlt::Parser { @@ -34,15 +35,9 @@ class FindProducerParser : public Mlt::Parser , m_uuid(uuid) {} - Mlt::Producer producer() - { - return m_producer; - } + Mlt::Producer producer() { return m_producer; } - int on_start_filter(Mlt::Filter *) - { - return 0; - } + int on_start_filter(Mlt::Filter *) { return 0; } int on_start_producer(Mlt::Producer *producer) { if (MLT.uuid(*producer) == m_uuid) { @@ -51,70 +46,22 @@ class FindProducerParser : public Mlt::Parser } return 0; } - int on_end_producer(Mlt::Producer *) - { - return 0; - } - int on_start_playlist(Mlt::Playlist *playlist) - { - return on_start_producer(playlist); - } - int on_end_playlist(Mlt::Playlist *) - { - return 0; - } - int on_start_tractor(Mlt::Tractor *tractor) - { - return on_start_producer(tractor); - } - int on_end_tractor(Mlt::Tractor *) - { - return 0; - } - int on_start_multitrack(Mlt::Multitrack *) - { - return 0; - } - int on_end_multitrack(Mlt::Multitrack *) - { - return 0; - } - int on_start_track() - { - return 0; - } - int on_end_track() - { - return 0; - } - int on_end_filter(Mlt::Filter *) - { - return 0; - } - int on_start_transition(Mlt::Transition *) - { - return 0; - } - int on_end_transition(Mlt::Transition *) - { - return 0; - } - int on_start_chain(Mlt::Chain *chain) - { - return on_start_producer(chain); - } - int on_end_chain(Mlt::Chain *) - { - return 0; - } - int on_start_link(Mlt::Link *) - { - return 0; - } - int on_end_link(Mlt::Link *) - { - return 0; - } + int on_end_producer(Mlt::Producer *) { return 0; } + int on_start_playlist(Mlt::Playlist *playlist) { return on_start_producer(playlist); } + int on_end_playlist(Mlt::Playlist *) { return 0; } + int on_start_tractor(Mlt::Tractor *tractor) { return on_start_producer(tractor); } + int on_end_tractor(Mlt::Tractor *) { return 0; } + int on_start_multitrack(Mlt::Multitrack *) { return 0; } + int on_end_multitrack(Mlt::Multitrack *) { return 0; } + int on_start_track() { return 0; } + int on_end_track() { return 0; } + int on_end_filter(Mlt::Filter *) { return 0; } + int on_start_transition(Mlt::Transition *) { return 0; } + int on_end_transition(Mlt::Transition *) { return 0; } + int on_start_chain(Mlt::Chain *chain) { return on_start_producer(chain); } + int on_end_chain(Mlt::Chain *) { return 0; } + int on_start_link(Mlt::Link *) { return 0; } + int on_end_link(Mlt::Link *) { return 0; } }; static Mlt::Producer findProducer(const QUuid &uuid) @@ -144,8 +91,12 @@ static Mlt::Producer findProducer(const QUuid &uuid) namespace Filter { -AddCommand::AddCommand(AttachedFiltersModel &model, const QString &name, Mlt::Service &service, - int row, AddCommand::AddType type, QUndoCommand *parent) +AddCommand::AddCommand(AttachedFiltersModel &model, + const QString &name, + Mlt::Service &service, + int row, + AddCommand::AddType type, + QUndoCommand *parent) : QUndoCommand(parent) , m_model(model) , m_producer(*model.producer()) @@ -204,8 +155,11 @@ bool AddCommand::mergeWith(const QUndoCommand *other) return true; } -RemoveCommand::RemoveCommand(AttachedFiltersModel &model, const QString &name, - Mlt::Service &service, int row, QUndoCommand *parent) +RemoveCommand::RemoveCommand(AttachedFiltersModel &model, + const QString &name, + Mlt::Service &service, + int row, + QUndoCommand *parent) : QUndoCommand(parent) , m_model(model) , m_row(row) @@ -238,8 +192,8 @@ void RemoveCommand::undo() m_model.doAddService(producer, m_service, m_row); } -MoveCommand::MoveCommand(AttachedFiltersModel &model, const QString &name, - int fromRow, int toRow, QUndoCommand *parent) +MoveCommand::MoveCommand( + AttachedFiltersModel &model, const QString &name, int fromRow, int toRow, QUndoCommand *parent) : QUndoCommand(parent) , m_model(model) , m_fromRow(fromRow) @@ -277,8 +231,8 @@ void MoveCommand::undo() } } -DisableCommand::DisableCommand(AttachedFiltersModel &model, const QString &name, int row, - bool disabled, QUndoCommand *parent) +DisableCommand::DisableCommand( + AttachedFiltersModel &model, const QString &name, int row, bool disabled, QUndoCommand *parent) : QUndoCommand(parent) , m_model(model) , m_row(row) @@ -337,8 +291,12 @@ bool DisableCommand::mergeWith(const QUndoCommand *other) */ } -UndoParameterCommand::UndoParameterCommand(const QString &name, FilterController *controller, - int row, Mlt::Properties &before, const QString &desc, QUndoCommand *parent) +UndoParameterCommand::UndoParameterCommand(const QString &name, + FilterController *controller, + int row, + Mlt::Properties &before, + const QString &desc, + QUndoCommand *parent) : QUndoCommand(parent) , m_filterController(controller) , m_row(row) @@ -370,7 +328,8 @@ void UndoParameterCommand::redo() Mlt::Producer producer = findProducer(m_producerUuid); Q_ASSERT(producer.is_valid()); if (producer.is_valid() && m_filterController) { - Mlt::Service service = m_filterController->attachedModel()->doGetService(producer, m_row); + Mlt::Service service = m_filterController->attachedModel()->doGetService(producer, + m_row); service.inherit(m_after); m_filterController->onUndoOrRedo(service); } @@ -391,11 +350,11 @@ void UndoParameterCommand::undo() bool UndoParameterCommand::mergeWith(const QUndoCommand *other) { - UndoParameterCommand *that = const_cast - (static_cast(other)); + UndoParameterCommand *that = const_cast( + static_cast(other)); LOG_DEBUG() << "this filter" << m_row << "that filter" << that->m_row; if (that->id() != id() || that->m_row != m_row || that->m_producerUuid != m_producerUuid - || that->text() != text()) + || that->text() != text()) return false; m_after = that->m_after; return true; diff --git a/src/commands/filtercommands.h b/src/commands/filtercommands.h index bbd8fc0099..68f465130d 100644 --- a/src/commands/filtercommands.h +++ b/src/commands/filtercommands.h @@ -19,10 +19,11 @@ #define FILTERCOMMANDS_H #include "models/attachedfiltersmodel.h" -#include + #include -#include +#include #include +#include #include class QmlMetadata; @@ -48,16 +49,19 @@ class AddCommand : public QUndoCommand AddSet, AddSetLast, } AddType; - AddCommand(AttachedFiltersModel &model, const QString &name, Mlt::Service &service, int row, - AddCommand::AddType type = AddCommand::AddSingle, QUndoCommand *parent = 0); + AddCommand(AttachedFiltersModel &model, + const QString &name, + Mlt::Service &service, + int row, + AddCommand::AddType type = AddCommand::AddSingle, + QUndoCommand *parent = 0); void redo(); void undo(); + protected: - int id() const - { - return UndoIdAdd; - } + int id() const { return UndoIdAdd; } bool mergeWith(const QUndoCommand *other); + private: AttachedFiltersModel &m_model; std::vector m_rows; @@ -70,10 +74,14 @@ class AddCommand : public QUndoCommand class RemoveCommand : public QUndoCommand { public: - RemoveCommand(AttachedFiltersModel &model, const QString &name, Mlt::Service &service, int row, + RemoveCommand(AttachedFiltersModel &model, + const QString &name, + Mlt::Service &service, + int row, QUndoCommand *parent = 0); void redo(); void undo(); + private: AttachedFiltersModel &m_model; int m_index; @@ -86,15 +94,17 @@ class RemoveCommand : public QUndoCommand class MoveCommand : public QUndoCommand { public: - MoveCommand(AttachedFiltersModel &model, const QString &name, int fromRow, int toRow, + MoveCommand(AttachedFiltersModel &model, + const QString &name, + int fromRow, + int toRow, QUndoCommand *parent = 0); void redo(); void undo(); + protected: - int id() const - { - return UndoIdMove; - } + int id() const { return UndoIdMove; } + private: AttachedFiltersModel &m_model; int m_fromRow; @@ -106,16 +116,18 @@ class MoveCommand : public QUndoCommand class DisableCommand : public QUndoCommand { public: - DisableCommand(AttachedFiltersModel &model, const QString &name, int row, bool disabled, + DisableCommand(AttachedFiltersModel &model, + const QString &name, + int row, + bool disabled, QUndoCommand *parent = 0); void redo(); void undo(); + protected: - int id() const - { - return UndoIdDisable; - } + int id() const { return UndoIdDisable; } bool mergeWith(const QUndoCommand *other); + private: AttachedFiltersModel &m_model; int m_row; @@ -127,17 +139,20 @@ class DisableCommand : public QUndoCommand class UndoParameterCommand : public QUndoCommand { public: - UndoParameterCommand(const QString &name, FilterController *controller, int row, - Mlt::Properties &before, const QString &desc = QString(), QUndoCommand *parent = 0); + UndoParameterCommand(const QString &name, + FilterController *controller, + int row, + Mlt::Properties &before, + const QString &desc = QString(), + QUndoCommand *parent = 0); void update(const QString &propertyName); void redo(); void undo(); + protected: - int id() const - { - return UndoIdChangeParameter; - } + int id() const { return UndoIdChangeParameter; } bool mergeWith(const QUndoCommand *other); + private: int m_row; QUuid m_producerUuid; @@ -150,53 +165,49 @@ class UndoParameterCommand : public QUndoCommand class UndoAddKeyframeCommand : public UndoParameterCommand { public: - UndoAddKeyframeCommand(const QString &name, FilterController *controller, int row, + UndoAddKeyframeCommand(const QString &name, + FilterController *controller, + int row, Mlt::Properties &before) : UndoParameterCommand(name, controller, row, before, QObject::tr("add keyframe")) {} + protected: - int id() const - { - return UndoIdChangeAddKeyframe; - } - bool mergeWith(const QUndoCommand *other) - { - return false; - } + int id() const { return UndoIdChangeAddKeyframe; } + bool mergeWith(const QUndoCommand *other) { return false; } }; class UndoRemoveKeyframeCommand : public UndoParameterCommand { public: - UndoRemoveKeyframeCommand(const QString &name, FilterController *controller, int row, + UndoRemoveKeyframeCommand(const QString &name, + FilterController *controller, + int row, Mlt::Properties &before) : UndoParameterCommand(name, controller, row, before, QObject::tr("remove keyframe")) {} + protected: - int id() const - { - return UndoIdChangeRemoveKeyframe; - } - bool mergeWith(const QUndoCommand *other) - { - return false; - } + int id() const { return UndoIdChangeRemoveKeyframe; } + bool mergeWith(const QUndoCommand *other) { return false; } }; class UndoModifyKeyframeCommand : public UndoParameterCommand { public: - UndoModifyKeyframeCommand(const QString &name, FilterController *controller, int row, - Mlt::Properties &before, int paramIndex, int keyframeIndex) + UndoModifyKeyframeCommand(const QString &name, + FilterController *controller, + int row, + Mlt::Properties &before, + int paramIndex, + int keyframeIndex) : UndoParameterCommand(name, controller, row, before, QObject::tr("modify keyframe")) , m_paramIndex(paramIndex) , m_keyframeIndex(keyframeIndex) {} + protected: - int id() const - { - return UndoIdChangeRemoveKeyframe; - } + int id() const { return UndoIdChangeRemoveKeyframe; } bool mergeWith(const QUndoCommand *other) { auto *that = dynamic_cast(other); diff --git a/src/commands/markercommands.cpp b/src/commands/markercommands.cpp index d72533315f..bacba446cd 100644 --- a/src/commands/markercommands.cpp +++ b/src/commands/markercommands.cpp @@ -16,7 +16,8 @@ */ #include "markercommands.h" -#include + +#include "Logger.h" namespace Markers { @@ -58,8 +59,9 @@ void AppendCommand::undo() m_model.doRemove(m_index); } - -UpdateCommand::UpdateCommand(MarkersModel &model, const Marker &newMarker, const Marker &oldMarker, +UpdateCommand::UpdateCommand(MarkersModel &model, + const Marker &newMarker, + const Marker &oldMarker, int index) : QUndoCommand(0) , m_model(model) @@ -91,16 +93,16 @@ bool UpdateCommand::mergeWith(const QUndoCommand *other) if (that->id() != id() || that->m_index != m_index) return false; bool merge = false; - if (that->m_newMarker.text == m_oldMarker.text && - that->m_newMarker.color == m_oldMarker.color) { + if (that->m_newMarker.text == m_oldMarker.text && that->m_newMarker.color == m_oldMarker.color) { // Only start/end change. Merge with previous move command. merge = true; - } else if (that->m_newMarker.end == m_oldMarker.end && - that->m_newMarker.start == m_oldMarker.start) { + } else if (that->m_newMarker.end == m_oldMarker.end + && that->m_newMarker.start == m_oldMarker.start) { // Only text/color change. Merge with previous edit command. merge = true; } - if (!merge) return false; + if (!merge) + return false; m_newMarker = that->m_newMarker; return true; } diff --git a/src/commands/markercommands.h b/src/commands/markercommands.h index 3420679200..faf9589fa4 100644 --- a/src/commands/markercommands.h +++ b/src/commands/markercommands.h @@ -19,6 +19,7 @@ #define MARKERCOMMANDS_H #include "models/markersmodel.h" + #include namespace Markers { @@ -33,6 +34,7 @@ class DeleteCommand : public QUndoCommand DeleteCommand(MarkersModel &model, const Marker &delMarker, int index); void redo(); void undo(); + private: MarkersModel &m_model; Marker m_delMarker; @@ -45,6 +47,7 @@ class AppendCommand : public QUndoCommand AppendCommand(MarkersModel &model, const Marker &newMarker, int index); void redo(); void undo(); + private: MarkersModel &m_model; Marker m_newMarker; @@ -57,12 +60,11 @@ class UpdateCommand : public QUndoCommand UpdateCommand(MarkersModel &model, const Marker &newMarker, const Marker &oldMarker, int index); void redo(); void undo(); + protected: - int id() const - { - return UndoIdUpdate; - } + int id() const { return UndoIdUpdate; } bool mergeWith(const QUndoCommand *other); + private: MarkersModel &m_model; Marker m_newMarker; @@ -76,11 +78,12 @@ class ClearCommand : public QUndoCommand ClearCommand(MarkersModel &model, QList &clearMarkers); void redo(); void undo(); + private: MarkersModel &m_model; QList m_clearMarkers; }; -} +} // namespace Markers #endif // MARKERCOMMANDS_H diff --git a/src/commands/playlistcommands.cpp b/src/commands/playlistcommands.cpp index 889bdc9652..14b2a1763f 100644 --- a/src/commands/playlistcommands.cpp +++ b/src/commands/playlistcommands.cpp @@ -16,16 +16,19 @@ */ #include "playlistcommands.h" +#include "Logger.h" #include "docks/playlistdock.h" -#include "mltcontroller.h" #include "mainwindow.h" +#include "mltcontroller.h" #include "shotcut_mlt_properties.h" -#include + #include namespace Playlist { -AppendCommand::AppendCommand(PlaylistModel &model, const QString &xml, bool emitModified, +AppendCommand::AppendCommand(PlaylistModel &model, + const QString &xml, + bool emitModified, QUndoCommand *parent) : QUndoCommand(parent) , m_model(model) @@ -53,8 +56,7 @@ void AppendCommand::undo() m_model.remove(m_model.rowCount() - 1); } -InsertCommand::InsertCommand(PlaylistModel &model, const QString &xml, int row, - QUndoCommand *parent) +InsertCommand::InsertCommand(PlaylistModel &model, const QString &xml, int row, QUndoCommand *parent) : QUndoCommand(parent) , m_model(model) , m_xml(xml) @@ -81,8 +83,7 @@ void InsertCommand::undo() m_model.remove(m_row); } -UpdateCommand::UpdateCommand(PlaylistModel &model, const QString &xml, int row, - QUndoCommand *parent) +UpdateCommand::UpdateCommand(PlaylistModel &model, const QString &xml, int row, QUndoCommand *parent) : QUndoCommand(parent) , m_model(model) , m_newXml(xml) @@ -172,7 +173,8 @@ void ClearCommand::redo() void ClearCommand::undo() { LOG_DEBUG() << ""; - Mlt::Producer *producer = new Mlt::Producer(MLT.profile(), "xml-string", + Mlt::Producer *producer = new Mlt::Producer(MLT.profile(), + "xml-string", m_xml.toUtf8().constData()); if (producer->is_valid()) { producer->set("resource", ""); @@ -213,8 +215,7 @@ void MoveCommand::undo() m_model.move(m_to, m_from); } -SortCommand::SortCommand(PlaylistModel &model, int column, Qt::SortOrder order, - QUndoCommand *parent) +SortCommand::SortCommand(PlaylistModel &model, int column, Qt::SortOrder order, QUndoCommand *parent) : QUndoCommand(parent) , m_model(model) , m_column(column) @@ -240,7 +241,8 @@ void SortCommand::redo() void SortCommand::undo() { LOG_DEBUG() << ""; - Mlt::Producer *producer = new Mlt::Producer(MLT.profile(), "xml-string", + Mlt::Producer *producer = new Mlt::Producer(MLT.profile(), + "xml-string", m_xml.toUtf8().constData()); if (producer->is_valid()) { producer->set("resource", ""); @@ -336,7 +338,9 @@ bool TrimClipOutCommand::mergeWith(const QUndoCommand *other) return true; } -ReplaceCommand::ReplaceCommand(PlaylistModel &model, const QString &xml, int row, +ReplaceCommand::ReplaceCommand(PlaylistModel &model, + const QString &xml, + int row, QUndoCommand *parent) : QUndoCommand(parent) , m_model(model) @@ -365,7 +369,9 @@ void ReplaceCommand::undo() MLT.setUuid(producer, m_uuid); } -NewBinCommand::NewBinCommand(PlaylistModel &model, QTreeWidget *tree, const QString &bin, +NewBinCommand::NewBinCommand(PlaylistModel &model, + QTreeWidget *tree, + const QString &bin, QUndoCommand *parent) : QUndoCommand(parent) , m_model(model) @@ -382,8 +388,7 @@ NewBinCommand::NewBinCommand(PlaylistModel &model, QTreeWidget *tree, const QStr void NewBinCommand::redo() { auto item = new QTreeWidgetItem(m_binTree, {m_bin}); - auto icon = QIcon::fromTheme("folder", - QIcon(":/icons/oxygen/32x32/places/folder.png")); + auto icon = QIcon::fromTheme("folder", QIcon(":/icons/oxygen/32x32/places/folder.png")); item->setIcon(0, icon); PlaylistDock::sortBins(m_binTree); @@ -409,8 +414,11 @@ void NewBinCommand::undo() RenameBinCommand::rebuildBinList(m_model, m_binTree); } -MoveToBinCommand::MoveToBinCommand(PlaylistModel &model, QTreeWidget *tree, const QString &bin, - const QList &rows, QUndoCommand *parent) +MoveToBinCommand::MoveToBinCommand(PlaylistModel &model, + QTreeWidget *tree, + const QString &bin, + const QList &rows, + QUndoCommand *parent) : QUndoCommand(parent) , m_model(model) , m_binTree(tree) @@ -439,8 +447,11 @@ void MoveToBinCommand::undo() } } -RenameBinCommand::RenameBinCommand(PlaylistModel &model, QTreeWidget *tree, const QString &bin, - const QString &newName, QUndoCommand *parent) +RenameBinCommand::RenameBinCommand(PlaylistModel &model, + QTreeWidget *tree, + const QString &bin, + const QString &newName, + QUndoCommand *parent) : QUndoCommand(parent) , m_model(model) , m_binTree(tree) @@ -498,15 +509,15 @@ void RenameBinCommand::undo() if (m_newName.isEmpty()) { // Undo remove auto item = new QTreeWidgetItem(m_binTree, {m_bin}); - auto icon = QIcon::fromTheme("folder", - QIcon(":/icons/oxygen/32x32/places/folder.png")); + auto icon = QIcon::fromTheme("folder", QIcon(":/icons/oxygen/32x32/places/folder.png")); item->setIcon(0, icon); PlaylistDock::sortBins(m_binTree); // Restore bin property on playlist items for (auto row : m_removedRows) { - m_model.playlist()->get_clip(row)->parent().set(kShotcutBinsProperty, m_bin.toUtf8().constData()); + m_model.playlist()->get_clip(row)->parent().set(kShotcutBinsProperty, + m_bin.toUtf8().constData()); } m_model.renameBin(m_bin); rebuildBinList(m_model, m_binTree); diff --git a/src/commands/playlistcommands.h b/src/commands/playlistcommands.h index 7e3c4a69b6..a671698eaf 100644 --- a/src/commands/playlistcommands.h +++ b/src/commands/playlistcommands.h @@ -19,27 +19,27 @@ #define PLAYLISTCOMMANDS_H #include "models/playlistmodel.h" -#include + #include +#include #include class QTreeWidget; namespace Playlist { -enum { - UndoIdTrimClipIn = 0, - UndoIdTrimClipOut, - UndoIdUpdate -}; +enum { UndoIdTrimClipIn = 0, UndoIdTrimClipOut, UndoIdUpdate }; class AppendCommand : public QUndoCommand { public: - AppendCommand(PlaylistModel &model, const QString &xml, bool emitModified = true, + AppendCommand(PlaylistModel &model, + const QString &xml, + bool emitModified = true, QUndoCommand *parent = 0); void redo(); void undo(); + private: PlaylistModel &m_model; QString m_xml; @@ -53,6 +53,7 @@ class InsertCommand : public QUndoCommand InsertCommand(PlaylistModel &model, const QString &xml, int row, QUndoCommand *parent = 0); void redo(); void undo(); + private: PlaylistModel &m_model; QString m_xml; @@ -66,12 +67,11 @@ class UpdateCommand : public QUndoCommand UpdateCommand(PlaylistModel &model, const QString &xml, int row, QUndoCommand *parent = 0); void redo(); void undo(); + protected: - int id() const - { - return UndoIdUpdate; - } + int id() const { return UndoIdUpdate; } bool mergeWith(const QUndoCommand *other); + private: PlaylistModel &m_model; QString m_newXml; @@ -86,6 +86,7 @@ class RemoveCommand : public QUndoCommand RemoveCommand(PlaylistModel &model, int row, QUndoCommand *parent = 0); void redo(); void undo(); + private: PlaylistModel &m_model; QString m_xml; @@ -99,6 +100,7 @@ class MoveCommand : public QUndoCommand MoveCommand(PlaylistModel &model, int from, int to, QUndoCommand *parent = 0); void redo(); void undo(); + private: PlaylistModel &m_model; int m_from; @@ -111,6 +113,7 @@ class ClearCommand : public QUndoCommand ClearCommand(PlaylistModel &model, QUndoCommand *parent = 0); void redo(); void undo(); + private: PlaylistModel &m_model; QString m_xml; @@ -123,6 +126,7 @@ class SortCommand : public QUndoCommand SortCommand(PlaylistModel &model, int column, Qt::SortOrder order, QUndoCommand *parent = 0); void redo(); void undo(); + private: PlaylistModel &m_model; int m_column; @@ -137,12 +141,11 @@ class TrimClipInCommand : public QUndoCommand TrimClipInCommand(PlaylistModel &model, int row, int in, QUndoCommand *parent = nullptr); void redo(); void undo(); + protected: - int id() const - { - return UndoIdTrimClipIn; - } + int id() const { return UndoIdTrimClipIn; } bool mergeWith(const QUndoCommand *other); + private: PlaylistModel &m_model; int m_row; @@ -157,12 +160,11 @@ class TrimClipOutCommand : public QUndoCommand TrimClipOutCommand(PlaylistModel &model, int row, int out, QUndoCommand *parent = nullptr); void redo(); void undo(); + protected: - int id() const - { - return UndoIdTrimClipOut; - } + int id() const { return UndoIdTrimClipOut; } bool mergeWith(const QUndoCommand *other); + private: PlaylistModel &m_model; int m_row; @@ -177,6 +179,7 @@ class ReplaceCommand : public QUndoCommand ReplaceCommand(PlaylistModel &model, const QString &xml, int row, QUndoCommand *parent = 0); void redo(); void undo(); + private: PlaylistModel &m_model; QString m_newXml; @@ -188,10 +191,13 @@ class ReplaceCommand : public QUndoCommand class NewBinCommand : public QUndoCommand { public: - NewBinCommand(PlaylistModel &model, QTreeWidget *tree, const QString &bin, + NewBinCommand(PlaylistModel &model, + QTreeWidget *tree, + const QString &bin, QUndoCommand *parent = 0); void redo(); void undo(); + private: PlaylistModel &m_model; QTreeWidget *m_binTree; @@ -202,8 +208,11 @@ class NewBinCommand : public QUndoCommand class MoveToBinCommand : public QUndoCommand { public: - MoveToBinCommand(PlaylistModel &model, QTreeWidget *tree, const QString &bin, - const QList &rows, QUndoCommand *parent = 0); + MoveToBinCommand(PlaylistModel &model, + QTreeWidget *tree, + const QString &bin, + const QList &rows, + QUndoCommand *parent = 0); void redo(); void undo(); @@ -212,7 +221,8 @@ class MoveToBinCommand : public QUndoCommand QTreeWidget *m_binTree; QString m_bin; - typedef struct { + typedef struct + { int row; QString bin; } oldData; @@ -222,8 +232,11 @@ class MoveToBinCommand : public QUndoCommand class RenameBinCommand : public QUndoCommand { public: - RenameBinCommand(PlaylistModel &model, QTreeWidget *tree, const QString &bin, - const QString &newName = QString(), QUndoCommand *parent = 0); + RenameBinCommand(PlaylistModel &model, + QTreeWidget *tree, + const QString &bin, + const QString &newName = QString(), + QUndoCommand *parent = 0); void redo(); void undo(); static void rebuildBinList(PlaylistModel &model, QTreeWidget *binTree); @@ -234,9 +247,8 @@ class RenameBinCommand : public QUndoCommand QString m_bin; QString m_newName; QList m_removedRows; - }; -} +} // namespace Playlist #endif // PLAYLISTCOMMANDS_H diff --git a/src/commands/subtitlecommands.cpp b/src/commands/subtitlecommands.cpp index 96dafc87f1..aa183c1460 100644 --- a/src/commands/subtitlecommands.cpp +++ b/src/commands/subtitlecommands.cpp @@ -17,15 +17,16 @@ #include "subtitlecommands.h" -#include -#include +#include "Logger.h" +#include "mainwindow.h" #include namespace Subtitles { InsertTrackCommand::InsertTrackCommand(SubtitlesModel &model, - const SubtitlesModel::SubtitleTrack &track, int index) + const SubtitlesModel::SubtitleTrack &track, + int index) : QUndoCommand(0) , m_model(model) , m_track(track) @@ -71,7 +72,8 @@ void RemoveTrackCommand::undo() } EditTrackCommand::EditTrackCommand(SubtitlesModel &model, - const SubtitlesModel::SubtitleTrack &track, int index) + const SubtitlesModel::SubtitleTrack &track, + int index) : QUndoCommand(0) , m_model(model) , m_newTrack(track) @@ -92,7 +94,8 @@ void EditTrackCommand::undo() m_model.doEditTrack(m_oldTrack, m_index); } -OverwriteSubtitlesCommand::OverwriteSubtitlesCommand(SubtitlesModel &model, int trackIndex, +OverwriteSubtitlesCommand::OverwriteSubtitlesCommand(SubtitlesModel &model, + int trackIndex, const QList &items) : QUndoCommand(0) , m_model(model) @@ -114,8 +117,8 @@ OverwriteSubtitlesCommand::OverwriteSubtitlesCommand(SubtitlesModel &model, int int count = m_model.itemCount(m_trackIndex); for (int i = 0; i < count; i++) { auto item = m_model.getItem(m_trackIndex, i); - if ((item.start >= startPosition && item.start < endPosition) || (item.end > startPosition - && item.end < endPosition)) { + if ((item.start >= startPosition && item.start < endPosition) + || (item.end > startPosition && item.end < endPosition)) { m_saveSubtitles.push_back(item); } } @@ -145,7 +148,8 @@ void OverwriteSubtitlesCommand::undo() } } -RemoveSubtitlesCommand::RemoveSubtitlesCommand(SubtitlesModel &model, int trackIndex, +RemoveSubtitlesCommand::RemoveSubtitlesCommand(SubtitlesModel &model, + int trackIndex, const QList &items) : QUndoCommand(0) , m_model(model) @@ -173,7 +177,9 @@ void RemoveSubtitlesCommand::undo() } } -SetTextCommand::SetTextCommand(SubtitlesModel &model, int trackIndex, int itemIndex, +SetTextCommand::SetTextCommand(SubtitlesModel &model, + int trackIndex, + int itemIndex, const QString &text) : QUndoCommand(0) , m_model(model) @@ -206,7 +212,9 @@ bool SetTextCommand::mergeWith(const QUndoCommand *other) return true; } -SetStartCommand::SetStartCommand(SubtitlesModel &model, int trackIndex, int itemIndex, +SetStartCommand::SetStartCommand(SubtitlesModel &model, + int trackIndex, + int itemIndex, int64_t msTime) : QUndoCommand(0) , m_model(model) @@ -275,8 +283,10 @@ bool SetEndCommand::mergeWith(const QUndoCommand *other) return true; } -MoveSubtitlesCommand::MoveSubtitlesCommand(SubtitlesModel &model, int trackIndex, - const QList &items, int64_t msTime) +MoveSubtitlesCommand::MoveSubtitlesCommand(SubtitlesModel &model, + int trackIndex, + const QList &items, + int64_t msTime) : QUndoCommand(0) , m_model(model) , m_trackIndex(trackIndex) diff --git a/src/commands/subtitlecommands.h b/src/commands/subtitlecommands.h index e60dd7edac..931b3ce424 100644 --- a/src/commands/subtitlecommands.h +++ b/src/commands/subtitlecommands.h @@ -19,6 +19,7 @@ #define SUBTITLECOMMANDS_H #include "models/subtitlesmodel.h" + #include namespace Subtitles { @@ -36,6 +37,7 @@ class InsertTrackCommand : public QUndoCommand InsertTrackCommand(SubtitlesModel &model, const SubtitlesModel::SubtitleTrack &track, int index); void redo(); void undo(); + private: SubtitlesModel &m_model; SubtitlesModel::SubtitleTrack m_track; @@ -48,6 +50,7 @@ class RemoveTrackCommand : public QUndoCommand RemoveTrackCommand(SubtitlesModel &model, int trackIndex); void redo(); void undo(); + private: SubtitlesModel &m_model; int m_trackIndex; @@ -61,6 +64,7 @@ class EditTrackCommand : public QUndoCommand EditTrackCommand(SubtitlesModel &model, const SubtitlesModel::SubtitleTrack &track, int index); void redo(); void undo(); + private: SubtitlesModel &m_model; SubtitlesModel::SubtitleTrack m_oldTrack; @@ -71,12 +75,15 @@ class EditTrackCommand : public QUndoCommand class OverwriteSubtitlesCommand : public QUndoCommand { public: - OverwriteSubtitlesCommand(SubtitlesModel &model, int trackIndex, + OverwriteSubtitlesCommand(SubtitlesModel &model, + int trackIndex, const QList &items); void redo(); void undo(); + protected: QList m_newSubtitles; + private: SubtitlesModel &m_model; int m_trackIndex; @@ -86,10 +93,12 @@ class OverwriteSubtitlesCommand : public QUndoCommand class RemoveSubtitlesCommand : public QUndoCommand { public: - RemoveSubtitlesCommand(SubtitlesModel &model, int trackIndex, + RemoveSubtitlesCommand(SubtitlesModel &model, + int trackIndex, const QList &items); void redo(); void undo(); + private: SubtitlesModel &m_model; int m_trackIndex; @@ -102,12 +111,11 @@ class SetTextCommand : public QUndoCommand SetTextCommand(SubtitlesModel &model, int trackIndex, int itemIndex, const QString &text); void redo(); void undo(); + protected: - int id() const - { - return UndoIdSubText; - } + int id() const { return UndoIdSubText; } bool mergeWith(const QUndoCommand *other); + private: SubtitlesModel &m_model; int m_trackIndex; @@ -122,12 +130,11 @@ class SetStartCommand : public QUndoCommand SetStartCommand(SubtitlesModel &model, int trackIndex, int itemIndex, int64_t msTime); void redo(); void undo(); + protected: - int id() const - { - return UndoIdSubStart; - } + int id() const { return UndoIdSubStart; } bool mergeWith(const QUndoCommand *other); + private: SubtitlesModel &m_model; int m_trackIndex; @@ -142,12 +149,11 @@ class SetEndCommand : public QUndoCommand SetEndCommand(SubtitlesModel &model, int trackIndex, int itemIndex, int64_t msTime); void redo(); void undo(); + protected: - int id() const - { - return UndoIdSubEnd; - } + int id() const { return UndoIdSubEnd; } bool mergeWith(const QUndoCommand *other); + private: SubtitlesModel &m_model; int m_trackIndex; @@ -159,16 +165,17 @@ class SetEndCommand : public QUndoCommand class MoveSubtitlesCommand : public QUndoCommand { public: - MoveSubtitlesCommand(SubtitlesModel &model, int trackIndex, - const QList &items, int64_t msTime); + MoveSubtitlesCommand(SubtitlesModel &model, + int trackIndex, + const QList &items, + int64_t msTime); void redo(); void undo(); + protected: - int id() const - { - return UndoIdSubMove; - } + int id() const { return UndoIdSubMove; } bool mergeWith(const QUndoCommand *other); + private: SubtitlesModel &m_model; int m_trackIndex; @@ -176,6 +183,6 @@ class MoveSubtitlesCommand : public QUndoCommand QList m_newSubtitles; }; -} +} // namespace Subtitles #endif // SUBTITLECOMMANDS_H diff --git a/src/commands/timelinecommands.cpp b/src/commands/timelinecommands.cpp index e3f68e2c8e..620e45a233 100644 --- a/src/commands/timelinecommands.cpp +++ b/src/commands/timelinecommands.cpp @@ -15,19 +15,18 @@ * along with this program. If not, see . */ -#include "dialogs/longuitask.h" #include "timelinecommands.h" + +#include "Logger.h" +#include "controllers/filtercontroller.h" +#include "dialogs/longuitask.h" #include "mainwindow.h" #include "mltcontroller.h" -#include "shotcut_mlt_properties.h" -#include "settings.h" #include "proxymanager.h" -#include "dialogs/longuitask.h" -#include "controllers/filtercontroller.h" #include "qmltypes/qmlmetadata.h" +#include "settings.h" +#include "shotcut_mlt_properties.h" #include "util.h" -#include - #include @@ -64,8 +63,12 @@ int getUniqueGroupNumber(MultitrackModel &model) return 0; } -AppendCommand::AppendCommand(MultitrackModel &model, int trackIndex, const QString &xml, - bool skipProxy, bool seek, QUndoCommand *parent) +AppendCommand::AppendCommand(MultitrackModel &model, + int trackIndex, + const QString &xml, + bool skipProxy, + bool seek, + QUndoCommand *parent) : QUndoCommand(parent) , m_model(model) , m_trackIndex(qBound(0, trackIndex, qMax(model.rowCount() - 1, 0))) @@ -82,7 +85,7 @@ void AppendCommand::redo() LOG_DEBUG() << "trackIndex" << m_trackIndex; LongUiTask longTask(QObject::tr("Append to Timeline")); m_undoHelper.recordBeforeState(); - Mlt::Producer *producer = longTask.runAsync(QObject::tr("Preparing"), [ = ]() { + Mlt::Producer *producer = longTask.runAsync(QObject::tr("Preparing"), [=]() { return deserializeProducer(m_xml); }); if (producer->type() == mlt_service_playlist_type) { @@ -92,13 +95,15 @@ void AppendCommand::redo() longTask.reportProgress(QObject::tr("Appending"), i, count); QScopedPointer info(playlist.clip_info(i)); Mlt::Producer clip = Mlt::Producer(info->producer); - if (!m_skipProxy) ProxyManager::generateIfNotExists(clip); + if (!m_skipProxy) + ProxyManager::generateIfNotExists(clip); clip.set_in_and_out(info->frame_in, info->frame_out); bool lastClip = i == (count - 1); m_model.appendClip(m_trackIndex, clip, false, lastClip); } } else { - if (!m_skipProxy) ProxyManager::generateIfNotExists(*producer); + if (!m_skipProxy) + ProxyManager::generateIfNotExists(*producer); m_model.appendClip(m_trackIndex, *producer, m_seek); } longTask.reportProgress(QObject::tr("Finishing"), 0, 0); @@ -112,8 +117,13 @@ void AppendCommand::undo() m_undoHelper.undoChanges(); } -InsertCommand::InsertCommand(MultitrackModel &model, MarkersModel &markersModel, int trackIndex, - int position, const QString &xml, bool seek, QUndoCommand *parent) +InsertCommand::InsertCommand(MultitrackModel &model, + MarkersModel &markersModel, + int trackIndex, + int position, + const QString &xml, + bool seek, + QUndoCommand *parent) : QUndoCommand(parent) , m_model(model) , m_markersModel(markersModel) @@ -144,7 +154,9 @@ void InsertCommand::redo() while (i--) { QScopedPointer info(playlist.clip_info(i)); clip = Mlt::Producer(info->producer); - longTask.reportProgress(QFileInfo(ProxyManager::resource(clip)).fileName(), n - i - 1, n); + longTask.reportProgress(QFileInfo(ProxyManager::resource(clip)).fileName(), + n - i - 1, + n); ProxyManager::generateIfNotExists(clip); clip.set_in_and_out(info->frame_in, info->frame_out); bool lastClip = i == 0; @@ -172,8 +184,12 @@ void InsertCommand::undo() } } -OverwriteCommand::OverwriteCommand(MultitrackModel &model, int trackIndex, - int position, const QString &xml, bool seek, QUndoCommand *parent) +OverwriteCommand::OverwriteCommand(MultitrackModel &model, + int trackIndex, + int position, + const QString &xml, + bool seek, + QUndoCommand *parent) : QUndoCommand(parent) , m_model(model) , m_trackIndex(qBound(0, trackIndex, qMax(model.rowCount() - 1, 0))) @@ -219,8 +235,7 @@ void OverwriteCommand::undo() m_undoHelper.undoChanges(); } -LiftCommand::LiftCommand(MultitrackModel &model, int trackIndex, - int clipIndex, QUndoCommand *parent) +LiftCommand::LiftCommand(MultitrackModel &model, int trackIndex, int clipIndex, QUndoCommand *parent) : QUndoCommand(parent) , m_model(model) , m_trackIndex(qBound(0, trackIndex, qMax(model.rowCount() - 1, 0))) @@ -245,8 +260,11 @@ void LiftCommand::undo() m_undoHelper.undoChanges(); } -RemoveCommand::RemoveCommand(MultitrackModel &model, MarkersModel &markersModel, int trackIndex, - int clipIndex, QUndoCommand *parent) +RemoveCommand::RemoveCommand(MultitrackModel &model, + MarkersModel &markersModel, + int trackIndex, + int clipIndex, + QUndoCommand *parent) : QUndoCommand(parent) , m_model(model) , m_markersModel(markersModel) @@ -283,8 +301,7 @@ void RemoveCommand::redo() QList newMarkers = m_markers; for (int i = 0; i < newMarkers.size(); i++) { Markers::Marker &marker = newMarkers[i]; - if (marker.start >= m_markerRemoveStart && - marker.start <= m_markerRemoveEnd) { + if (marker.start >= m_markerRemoveStart && marker.start <= m_markerRemoveEnd) { // This marker is in the removed segment. Remove it newMarkers.removeAt(i); i--; @@ -323,8 +340,7 @@ void RemoveCommand::undo() GroupCommand::GroupCommand(MultitrackModel &model, QUndoCommand *parent) : QUndoCommand(parent) , m_model(model) -{ -} +{} void GroupCommand::addToGroup(int trackIndex, int clipIndex) { @@ -346,8 +362,12 @@ void GroupCommand::redo() auto clipInfo = m_model.getClipInfo(clip.trackIndex, clip.clipIndex); if (clipInfo && clipInfo->cut) { clipInfo->cut->set(kShotcutGroupProperty, groupNumber); - QModelIndex modelIndex = m_model.index(clip.clipIndex, 0, m_model.index(clip.trackIndex)); - emit m_model.dataChanged(modelIndex, modelIndex, QVector() << MultitrackModel::GroupRole); + QModelIndex modelIndex = m_model.index(clip.clipIndex, + 0, + m_model.index(clip.trackIndex)); + emit m_model.dataChanged(modelIndex, + modelIndex, + QVector() << MultitrackModel::GroupRole); } } } @@ -362,8 +382,12 @@ void GroupCommand::undo() } else { clipInfo->cut->Mlt::Properties::clear(kShotcutGroupProperty); } - QModelIndex modelIndex = m_model.index(clip.clipIndex, 0, m_model.index(clip.trackIndex)); - emit m_model.dataChanged(modelIndex, modelIndex, QVector() << MultitrackModel::GroupRole); + QModelIndex modelIndex = m_model.index(clip.clipIndex, + 0, + m_model.index(clip.trackIndex)); + emit m_model.dataChanged(modelIndex, + modelIndex, + QVector() << MultitrackModel::GroupRole); } } } @@ -371,8 +395,7 @@ void GroupCommand::undo() UngroupCommand::UngroupCommand(MultitrackModel &model, QUndoCommand *parent) : QUndoCommand(parent) , m_model(model) -{ -} +{} void UngroupCommand::removeFromGroup(int trackIndex, int clipIndex) { @@ -392,8 +415,12 @@ void UngroupCommand::redo() auto clipInfo = m_model.getClipInfo(clip.trackIndex, clip.clipIndex); if (clipInfo && clipInfo->cut) { clipInfo->cut->Mlt::Properties::clear(kShotcutGroupProperty); - QModelIndex modelIndex = m_model.index(clip.clipIndex, 0, m_model.index(clip.trackIndex)); - emit m_model.dataChanged(modelIndex, modelIndex, QVector() << MultitrackModel::GroupRole); + QModelIndex modelIndex = m_model.index(clip.clipIndex, + 0, + m_model.index(clip.trackIndex)); + emit m_model.dataChanged(modelIndex, + modelIndex, + QVector() << MultitrackModel::GroupRole); } } } @@ -404,14 +431,20 @@ void UngroupCommand::undo() auto clipInfo = m_model.getClipInfo(clip.trackIndex, clip.clipIndex); if (clipInfo && clipInfo->cut) { clipInfo->cut->set(kShotcutGroupProperty, m_prevGroups[clip]); - QModelIndex modelIndex = m_model.index(clip.clipIndex, 0, m_model.index(clip.trackIndex)); - emit m_model.dataChanged(modelIndex, modelIndex, QVector() << MultitrackModel::GroupRole); + QModelIndex modelIndex = m_model.index(clip.clipIndex, + 0, + m_model.index(clip.trackIndex)); + emit m_model.dataChanged(modelIndex, + modelIndex, + QVector() << MultitrackModel::GroupRole); } } } -NameTrackCommand::NameTrackCommand(MultitrackModel &model, int trackIndex, - const QString &name, QUndoCommand *parent) +NameTrackCommand::NameTrackCommand(MultitrackModel &model, + int trackIndex, + const QString &name, + QUndoCommand *parent) : QUndoCommand(parent) , m_model(model) , m_trackIndex(qBound(0, trackIndex, qMax(model.rowCount() - 1, 0))) @@ -433,7 +466,9 @@ void NameTrackCommand::undo() m_model.setTrackName(m_trackIndex, m_oldName); } -MergeCommand::MergeCommand(MultitrackModel &model, int trackIndex, int clipIndex, +MergeCommand::MergeCommand(MultitrackModel &model, + int trackIndex, + int clipIndex, QUndoCommand *parent) : QUndoCommand(parent) , m_model(model) @@ -458,7 +493,6 @@ void MergeCommand::undo() m_undoHelper.undoChanges(); } - MuteTrackCommand::MuteTrackCommand(MultitrackModel &model, int trackIndex, QUndoCommand *parent) : QUndoCommand(parent) , m_model(model) @@ -501,7 +535,9 @@ void HideTrackCommand::undo() m_model.setTrackHidden(m_trackIndex, m_oldValue); } -CompositeTrackCommand::CompositeTrackCommand(MultitrackModel &model, int trackIndex, bool value, +CompositeTrackCommand::CompositeTrackCommand(MultitrackModel &model, + int trackIndex, + bool value, QUndoCommand *parent) : QUndoCommand(parent) , m_model(model) @@ -524,7 +560,9 @@ void CompositeTrackCommand::undo() m_model.setTrackComposite(m_trackIndex, m_oldValue); } -LockTrackCommand::LockTrackCommand(MultitrackModel &model, int trackIndex, bool value, +LockTrackCommand::LockTrackCommand(MultitrackModel &model, + int trackIndex, + bool value, QUndoCommand *parent) : QUndoCommand(parent) , m_model(model) @@ -547,8 +585,8 @@ void LockTrackCommand::undo() m_model.setTrackLock(m_trackIndex, m_oldValue); } -MoveClipCommand::MoveClipCommand(TimelineDock &timeline, int trackDelta, int positionDelta, - bool ripple, QUndoCommand *parent) +MoveClipCommand::MoveClipCommand( + TimelineDock &timeline, int trackDelta, int positionDelta, bool ripple, QUndoCommand *parent) : QUndoCommand(parent) , m_timeline(timeline) , m_model(*timeline.model()) @@ -608,8 +646,8 @@ void MoveClipCommand::redo() auto targetIndex = playlist.get_clip_index_at(newStart); auto clipIndex = m_clips.first().clipIndex; if (targetIndex >= clipIndex || // pushing clips on same track - // pulling clips on same track - (playlist.is_blank_at(newStart) && targetIndex == clipIndex - 1)) { + // pulling clips on same track + (playlist.is_blank_at(newStart) && targetIndex == clipIndex - 1)) { bool done = true; if (targetIndex == clipIndex && m_model.isTransition(playlist, clipIndex - 1)) { // Increase duration of transition @@ -618,7 +656,11 @@ void MoveClipCommand::redo() m_model.trimClipIn(trackIndex, clipIndex + 1, m_positionDelta, true, false); } else if (m_ripple) { // Push or pull clips on the same track - m_model.moveClip(trackIndex, trackIndex, clipIndex, newStart, m_ripple, + m_model.moveClip(trackIndex, + trackIndex, + clipIndex, + newStart, + m_ripple, m_rippleAllTracks); } else if (m_model.isTransition(playlist, clipIndex + 1)) { // Increase duration of transition @@ -633,7 +675,8 @@ void MoveClipCommand::redo() m_undoHelper.recordAfterState(); } redoMarkers(); - selection = m_timeline.uuidsToSelection(QVector() << m_clips.first().uuid); + selection = m_timeline.uuidsToSelection(QVector() + << m_clips.first().uuid); m_timeline.setSelection(selection); return; } @@ -683,7 +726,8 @@ void MoveClipCommand::redo() return; } Mlt::Producer &producer = producers.front(); - int newTrackIndex = qBound(0, clip.trackIndex + m_trackDelta, + int newTrackIndex = qBound(0, + clip.trackIndex + m_trackDelta, qMax(int(m_model.trackList().size()) - 1, 0)); int newStart = clip.start + m_positionDelta; producer.set_in_and_out(clip.frame_in, clip.frame_out); @@ -697,8 +741,12 @@ void MoveClipCommand::redo() if (clipInfo && clipInfo->cut) { if (clip.group >= 0) { clipInfo->cut->set(kShotcutGroupProperty, clip.group); - QModelIndex modelIndex = m_model.index(newClipIndex, 0, m_model.index(newTrackIndex)); - emit m_model.dataChanged(modelIndex, modelIndex, QVector() << MultitrackModel::GroupRole); + QModelIndex modelIndex = m_model.index(newClipIndex, + 0, + m_model.index(newTrackIndex)); + emit m_model.dataChanged(modelIndex, + modelIndex, + QVector() << MultitrackModel::GroupRole); } MLT.setUuid(*clipInfo->producer, clip.uuid); uuids << clip.uuid; @@ -735,9 +783,8 @@ bool MoveClipCommand::mergeWith(const QUndoCommand *other) { const MoveClipCommand *that = static_cast(other); LOG_DEBUG() << "this delta" << m_positionDelta << "that delta" << that->m_positionDelta; - if (that->id() != id() || that->m_clips.size() != m_clips.size() - || that->m_ripple != m_ripple || that->m_rippleAllTracks != m_rippleAllTracks - || that->m_rippleMarkers != m_rippleMarkers) + if (that->id() != id() || that->m_clips.size() != m_clips.size() || that->m_ripple != m_ripple + || that->m_rippleAllTracks != m_rippleAllTracks || that->m_rippleMarkers != m_rippleMarkers) return false; if (that->m_undoHelper.affectedTracks() != m_undoHelper.affectedTracks()) { return false; @@ -763,8 +810,8 @@ void MoveClipCommand::redoMarkers() bool markersModified = false; for (int i = 0; i < newMarkers.size(); i++) { Markers::Marker &marker = newMarkers[i]; - if (marker.start < m_earliestStart && - marker.start > (m_earliestStart + m_positionDelta)) { + if (marker.start < m_earliestStart + && marker.start > (m_earliestStart + m_positionDelta)) { // This marker is in the overwritten segment. Remove it newMarkers.removeAt(i); i--; @@ -784,8 +831,14 @@ void MoveClipCommand::redoMarkers() } } -TrimClipInCommand::TrimClipInCommand(MultitrackModel &model, MarkersModel &markersModel, - int trackIndex, int clipIndex, int delta, bool ripple, bool redo, QUndoCommand *parent) +TrimClipInCommand::TrimClipInCommand(MultitrackModel &model, + MarkersModel &markersModel, + int trackIndex, + int clipIndex, + int delta, + bool ripple, + bool redo, + QUndoCommand *parent) : TrimCommand(parent) , m_model(model) , m_markersModel(markersModel) @@ -819,8 +872,7 @@ void TrimClipInCommand::redo() QList newMarkers = m_markers; for (int i = 0; i < newMarkers.size(); i++) { Markers::Marker &marker = newMarkers[i]; - if (marker.start >= m_markerRemoveStart && - marker.start <= m_markerRemoveEnd) { + if (marker.start >= m_markerRemoveStart && marker.start <= m_markerRemoveEnd) { // This marker is in the removed segment. Remove it newMarkers.removeAt(i); i--; @@ -843,7 +895,8 @@ void TrimClipInCommand::redo() } if (m_redo) { - LOG_DEBUG() << "trackIndex" << m_trackIndex << "clipIndex" << m_clipIndex << "delta" << m_delta; + LOG_DEBUG() << "trackIndex" << m_trackIndex << "clipIndex" << m_clipIndex << "delta" + << m_delta; m_undoHelper.reset(new UndoHelper(m_model)); if (m_ripple) { m_undoHelper->setHints(UndoHelper::SkipXML); @@ -875,8 +928,8 @@ bool TrimClipInCommand::mergeWith(const QUndoCommand *other) const TrimClipInCommand *that = static_cast(other); LOG_DEBUG() << "this clipIndex" << m_clipIndex << "that clipIndex" << that->m_clipIndex; if (that->id() != id() || that->m_trackIndex != m_trackIndex || that->m_clipIndex != m_clipIndex - || that->m_ripple != m_ripple || that->m_rippleAllTracks != m_rippleAllTracks - || that->m_rippleMarkers != m_rippleMarkers) + || that->m_ripple != m_ripple || that->m_rippleAllTracks != m_rippleAllTracks + || that->m_rippleMarkers != m_rippleMarkers) return false; Q_ASSERT(m_undoHelper); m_undoHelper->recordAfterState(); @@ -884,8 +937,14 @@ bool TrimClipInCommand::mergeWith(const QUndoCommand *other) return true; } -TrimClipOutCommand::TrimClipOutCommand(MultitrackModel &model, MarkersModel &markersModel, - int trackIndex, int clipIndex, int delta, bool ripple, bool redo, QUndoCommand *parent) +TrimClipOutCommand::TrimClipOutCommand(MultitrackModel &model, + MarkersModel &markersModel, + int trackIndex, + int clipIndex, + int delta, + bool ripple, + bool redo, + QUndoCommand *parent) : TrimCommand(parent) , m_model(model) , m_markersModel(markersModel) @@ -911,8 +970,8 @@ void TrimClipOutCommand::redo() QScopedPointer track(m_model.tractor()->track(mlt_index)); if (track && track->is_valid()) { Mlt::Playlist playlist(*track); - m_markerRemoveStart = playlist.clip_start(m_clipIndex) + playlist.clip_length( - m_clipIndex) - m_delta; + m_markerRemoveStart = playlist.clip_start(m_clipIndex) + + playlist.clip_length(m_clipIndex) - m_delta; if (!m_redo) { // For the first redo, the clip has already been trimmed by the timeline dock. // So remove the delta that has already been applied @@ -925,8 +984,7 @@ void TrimClipOutCommand::redo() QList newMarkers = m_markers; for (int i = 0; i < newMarkers.size(); i++) { Markers::Marker &marker = newMarkers[i]; - if (marker.start >= m_markerRemoveStart && - marker.start < m_markerRemoveEnd) { + if (marker.start >= m_markerRemoveStart && marker.start < m_markerRemoveEnd) { // This marker is in the removed segment. Remove it newMarkers.removeAt(i); i--; @@ -953,7 +1011,8 @@ void TrimClipOutCommand::redo() if (!m_ripple) m_undoHelper->setHints(UndoHelper::SkipXML); m_undoHelper->recordBeforeState(); - m_clipIndex = m_model.trimClipOut(m_trackIndex, m_clipIndex, m_delta, m_ripple, m_rippleAllTracks); + m_clipIndex + = m_model.trimClipOut(m_trackIndex, m_clipIndex, m_delta, m_ripple, m_rippleAllTracks); m_undoHelper->recordAfterState(); } else { Q_ASSERT(m_undoHelper); @@ -976,8 +1035,8 @@ bool TrimClipOutCommand::mergeWith(const QUndoCommand *other) { const TrimClipOutCommand *that = static_cast(other); if (that->id() != id() || that->m_trackIndex != m_trackIndex || that->m_clipIndex != m_clipIndex - || that->m_ripple != m_ripple || that->m_rippleAllTracks != m_rippleAllTracks - || that->m_rippleMarkers != m_rippleMarkers) + || that->m_ripple != m_ripple || that->m_rippleAllTracks != m_rippleAllTracks + || that->m_rippleMarkers != m_rippleMarkers) return false; Q_ASSERT(m_undoHelper); m_undoHelper->recordAfterState(); @@ -985,8 +1044,11 @@ bool TrimClipOutCommand::mergeWith(const QUndoCommand *other) return true; } -SplitCommand::SplitCommand(MultitrackModel &model, const std::vector &trackIndex, - const std::vector &clipIndex, int position, QUndoCommand *parent) +SplitCommand::SplitCommand(MultitrackModel &model, + const std::vector &trackIndex, + const std::vector &clipIndex, + int position, + QUndoCommand *parent) : QUndoCommand(parent) , m_model(model) , m_trackIndex(trackIndex) @@ -1004,8 +1066,8 @@ SplitCommand::SplitCommand(MultitrackModel &model, const std::vector &track void SplitCommand::redo() { - LOG_DEBUG() << "trackIndex" << m_trackIndex[0] << "clipIndex" << m_clipIndex[0] << "position" << - m_position; + LOG_DEBUG() << "trackIndex" << m_trackIndex[0] << "clipIndex" << m_clipIndex[0] << "position" + << m_position; m_undoHelper.recordBeforeState(); for (int i = 0; i < m_trackIndex.size(); i++) { m_model.splitClip(m_trackIndex[i], m_clipIndex[i], m_position); @@ -1015,13 +1077,13 @@ void SplitCommand::redo() void SplitCommand::undo() { - LOG_DEBUG() << "trackIndex" << m_trackIndex[0] << "clipIndex" << m_clipIndex[0] << "position" << - m_position; + LOG_DEBUG() << "trackIndex" << m_trackIndex[0] << "clipIndex" << m_clipIndex[0] << "position" + << m_position; m_undoHelper.undoChanges(); } -FadeInCommand::FadeInCommand(MultitrackModel &model, int trackIndex, int clipIndex, int duration, - QUndoCommand *parent) +FadeInCommand::FadeInCommand( + MultitrackModel &model, int trackIndex, int clipIndex, int duration, QUndoCommand *parent) : QUndoCommand(parent) , m_model(model) , m_trackIndex(qBound(0, trackIndex, qMax(model.rowCount() - 1, 0))) @@ -1040,8 +1102,8 @@ void FadeInCommand::redo() void FadeInCommand::undo() { - LOG_DEBUG() << "trackIndex" << m_trackIndex << "clipIndex" << m_clipIndex << "duration" << - m_duration; + LOG_DEBUG() << "trackIndex" << m_trackIndex << "clipIndex" << m_clipIndex << "duration" + << m_duration; m_model.fadeIn(m_trackIndex, m_clipIndex, m_previous); } @@ -1049,14 +1111,14 @@ bool FadeInCommand::mergeWith(const QUndoCommand *other) { const FadeInCommand *that = static_cast(other); if (that->id() != id() || that->m_trackIndex != m_trackIndex || that->m_clipIndex != m_clipIndex - || (!that->m_duration && m_duration != that->m_duration)) + || (!that->m_duration && m_duration != that->m_duration)) return false; m_duration = static_cast(other)->m_duration; return true; } -FadeOutCommand::FadeOutCommand(MultitrackModel &model, int trackIndex, int clipIndex, int duration, - QUndoCommand *parent) +FadeOutCommand::FadeOutCommand( + MultitrackModel &model, int trackIndex, int clipIndex, int duration, QUndoCommand *parent) : QUndoCommand(parent) , m_model(model) , m_trackIndex(qBound(0, trackIndex, qMax(model.rowCount() - 1, 0))) @@ -1075,8 +1137,8 @@ void FadeOutCommand::redo() void FadeOutCommand::undo() { - LOG_DEBUG() << "trackIndex" << m_trackIndex << "clipIndex" << m_clipIndex << "duration" << - m_duration; + LOG_DEBUG() << "trackIndex" << m_trackIndex << "clipIndex" << m_clipIndex << "duration" + << m_duration; m_model.fadeOut(m_trackIndex, m_clipIndex, m_previous); } @@ -1084,14 +1146,18 @@ bool FadeOutCommand::mergeWith(const QUndoCommand *other) { const FadeOutCommand *that = static_cast(other); if (that->id() != id() || that->m_trackIndex != m_trackIndex || that->m_clipIndex != m_clipIndex - || (!that->m_duration && m_duration != that->m_duration)) + || (!that->m_duration && m_duration != that->m_duration)) return false; m_duration = static_cast(other)->m_duration; return true; } -AddTransitionCommand::AddTransitionCommand(TimelineDock &timeline, int trackIndex, int clipIndex, - int position, bool ripple, QUndoCommand *parent) +AddTransitionCommand::AddTransitionCommand(TimelineDock &timeline, + int trackIndex, + int clipIndex, + int position, + bool ripple, + QUndoCommand *parent) : QUndoCommand(parent) , m_timeline(timeline) , m_model(*m_timeline.model()) @@ -1112,8 +1178,8 @@ AddTransitionCommand::AddTransitionCommand(TimelineDock &timeline, int trackInde void AddTransitionCommand::redo() { - LOG_DEBUG() << "trackIndex" << m_trackIndex << "clipIndex" << m_clipIndex << "position" << - m_position; + LOG_DEBUG() << "trackIndex" << m_trackIndex << "clipIndex" << m_clipIndex << "position" + << m_position; if (m_rippleMarkers) { // Calculate the marker delta before moving anything @@ -1127,8 +1193,8 @@ void AddTransitionCommand::redo() } m_undoHelper.recordBeforeState(); - m_transitionIndex = m_model.addTransition(m_trackIndex, m_clipIndex, m_position, m_ripple, - m_rippleAllTracks); + m_transitionIndex + = m_model.addTransition(m_trackIndex, m_clipIndex, m_position, m_ripple, m_rippleAllTracks); LOG_DEBUG() << "m_transitionIndex" << m_transitionIndex; m_undoHelper.recordAfterState(); @@ -1140,8 +1206,7 @@ void AddTransitionCommand::redo() int startDelta = m_markerNewStart - m_markerOldStart; for (int i = 0; i < newMarkers.size(); i++) { Markers::Marker &marker = newMarkers[i]; - if (marker.start <= m_markerOldStart && - marker.start > m_markerNewStart) { + if (marker.start <= m_markerOldStart && marker.start > m_markerNewStart) { // This marker is in the overwritten segment. Remove it newMarkers.removeAt(i); i--; @@ -1166,8 +1231,8 @@ void AddTransitionCommand::redo() void AddTransitionCommand::undo() { if (m_transitionIndex >= 0) { - LOG_DEBUG() << "trackIndex" << m_trackIndex << "clipIndex" << m_clipIndex << "position" << - m_position; + LOG_DEBUG() << "trackIndex" << m_trackIndex << "clipIndex" << m_clipIndex << "position" + << m_position; m_undoHelper.undoChanges(); m_timeline.setSelection(QList() << QPoint(m_clipIndex, m_trackIndex)); @@ -1177,8 +1242,12 @@ void AddTransitionCommand::undo() } } -TrimTransitionInCommand::TrimTransitionInCommand(MultitrackModel &model, int trackIndex, - int clipIndex, int delta, bool redo, QUndoCommand *parent) +TrimTransitionInCommand::TrimTransitionInCommand(MultitrackModel &model, + int trackIndex, + int clipIndex, + int delta, + bool redo, + QUndoCommand *parent) : TrimCommand(parent) , m_model(model) , m_trackIndex(qBound(0, trackIndex, qMax(model.rowCount() - 1, 0))) @@ -1208,7 +1277,8 @@ void TrimTransitionInCommand::undo() m_model.trimTransitionIn(m_trackIndex, m_clipIndex, -m_delta); m_model.notifyClipIn(m_trackIndex, m_clipIndex); m_notify = true; - } else LOG_WARNING() << "invalid clip index" << m_clipIndex; + } else + LOG_WARNING() << "invalid clip index" << m_clipIndex; } bool TrimTransitionInCommand::mergeWith(const QUndoCommand *other) @@ -1220,8 +1290,12 @@ bool TrimTransitionInCommand::mergeWith(const QUndoCommand *other) return true; } -TrimTransitionOutCommand::TrimTransitionOutCommand(MultitrackModel &model, int trackIndex, - int clipIndex, int delta, bool redo, QUndoCommand *parent) +TrimTransitionOutCommand::TrimTransitionOutCommand(MultitrackModel &model, + int trackIndex, + int clipIndex, + int delta, + bool redo, + QUndoCommand *parent) : TrimCommand(parent) , m_model(model) , m_trackIndex(qBound(0, trackIndex, qMax(model.rowCount() - 1, 0))) @@ -1248,11 +1322,13 @@ void TrimTransitionOutCommand::redo() void TrimTransitionOutCommand::undo() { if (m_clipIndex >= 0) { - LOG_DEBUG() << "trackIndex" << m_trackIndex << "clipIndex" << m_clipIndex << "delta" << m_delta; + LOG_DEBUG() << "trackIndex" << m_trackIndex << "clipIndex" << m_clipIndex << "delta" + << m_delta; m_model.trimTransitionOut(m_trackIndex, m_clipIndex, -m_delta); m_model.notifyClipOut(m_trackIndex, m_clipIndex); m_notify = true; - } else LOG_WARNING() << "invalid clip index" << m_clipIndex; + } else + LOG_WARNING() << "invalid clip index" << m_clipIndex; } bool TrimTransitionOutCommand::mergeWith(const QUndoCommand *other) @@ -1264,8 +1340,13 @@ bool TrimTransitionOutCommand::mergeWith(const QUndoCommand *other) return true; } -AddTransitionByTrimInCommand::AddTransitionByTrimInCommand(TimelineDock &timeline, int trackIndex, - int clipIndex, int duration, int trimDelta, bool redo, QUndoCommand *parent) +AddTransitionByTrimInCommand::AddTransitionByTrimInCommand(TimelineDock &timeline, + int trackIndex, + int clipIndex, + int duration, + int trimDelta, + bool redo, + QUndoCommand *parent) : TrimCommand(parent) , m_timeline(timeline) , m_trackIndex(qBound(0, trackIndex, qMax(timeline.model()->rowCount() - 1, 0))) @@ -1281,8 +1362,8 @@ AddTransitionByTrimInCommand::AddTransitionByTrimInCommand(TimelineDock &timelin void AddTransitionByTrimInCommand::redo() { if (m_redo) { - LOG_DEBUG() << "trackIndex" << m_trackIndex << "clipIndex" << m_clipIndex << "delta" << m_trimDelta - << "duration" << m_duration; + LOG_DEBUG() << "trackIndex" << m_trackIndex << "clipIndex" << m_clipIndex << "delta" + << m_trimDelta << "duration" << m_duration; if (m_trimDelta) m_timeline.model()->trimClipIn(m_trackIndex, m_clipIndex + 1, m_trimDelta, false, false); m_timeline.model()->addTransitionByTrimIn(m_trackIndex, m_clipIndex, m_duration); @@ -1297,24 +1378,32 @@ void AddTransitionByTrimInCommand::redo() void AddTransitionByTrimInCommand::undo() { if (m_clipIndex > 0) { - LOG_DEBUG() << "trackIndex" << m_trackIndex << "clipIndex" << m_clipIndex << "delta" << m_trimDelta; + LOG_DEBUG() << "trackIndex" << m_trackIndex << "clipIndex" << m_clipIndex << "delta" + << m_trimDelta; m_timeline.model()->removeTransitionByTrimIn(m_trackIndex, m_clipIndex, -m_trimDelta); m_notify = true; m_timeline.setSelection(QList() << QPoint(m_clipIndex, m_trackIndex)); - } else LOG_WARNING() << "invalid clip index" << m_clipIndex; + } else + LOG_WARNING() << "invalid clip index" << m_clipIndex; } bool AddTransitionByTrimInCommand::mergeWith(const QUndoCommand *other) { - const AddTransitionByTrimInCommand *that = static_cast(other); - if (that->id() != id() || that->m_trackIndex != m_trackIndex || - (that->m_clipIndex != m_clipIndex && m_clipIndex != that->m_clipIndex - 1)) + const AddTransitionByTrimInCommand *that = static_cast( + other); + if (that->id() != id() || that->m_trackIndex != m_trackIndex + || (that->m_clipIndex != m_clipIndex && m_clipIndex != that->m_clipIndex - 1)) return false; return true; } RemoveTransitionByTrimInCommand::RemoveTransitionByTrimInCommand(MultitrackModel &model, - int trackIndex, int clipIndex, int delta, QString xml, bool redo, QUndoCommand *parent) + int trackIndex, + int clipIndex, + int delta, + QString xml, + bool redo, + QUndoCommand *parent) : TrimCommand(parent) , m_model(model) , m_trackIndex(qBound(0, trackIndex, qMax(model.rowCount() - 1, 0))) @@ -1343,17 +1432,21 @@ void RemoveTransitionByTrimInCommand::redo() void RemoveTransitionByTrimInCommand::undo() { if (m_clipIndex > 0) { - LOG_DEBUG() << "trackIndex" << m_trackIndex << "clipIndex" << m_clipIndex << "delta" << m_delta; + LOG_DEBUG() << "trackIndex" << m_trackIndex << "clipIndex" << m_clipIndex << "delta" + << m_delta; m_model.addTransitionByTrimOut(m_trackIndex, m_clipIndex - 1, m_delta); // Copy properties from old transition to new transition auto clipInfo = m_model.getClipInfo(m_trackIndex, m_clipIndex); - Mlt::Service oldService = Mlt::Producer(MLT.profile(), "xml-string", m_xml.toUtf8().constData()); + Mlt::Service oldService = Mlt::Producer(MLT.profile(), + "xml-string", + m_xml.toUtf8().constData()); while (oldService.is_valid()) { if (oldService.type() == mlt_service_transition_type) { Mlt::Service newService(clipInfo->producer); while (newService.is_valid()) { - if (newService.type() == mlt_service_transition_type && - QString(oldService.get("mlt_service")) == QString(newService.get("mlt_service"))) { + if (newService.type() == mlt_service_transition_type + && QString(oldService.get("mlt_service")) + == QString(newService.get("mlt_service"))) { newService.inherit(oldService); break; } @@ -1367,11 +1460,17 @@ void RemoveTransitionByTrimInCommand::undo() delete tmpOldService; } m_model.notifyClipIn(m_trackIndex, m_clipIndex + 1); - } else LOG_WARNING() << "invalid clip index" << m_clipIndex; + } else + LOG_WARNING() << "invalid clip index" << m_clipIndex; } RemoveTransitionByTrimOutCommand::RemoveTransitionByTrimOutCommand(MultitrackModel &model, - int trackIndex, int clipIndex, int delta, QString xml, bool redo, QUndoCommand *parent) + int trackIndex, + int clipIndex, + int delta, + QString xml, + bool redo, + QUndoCommand *parent) : TrimCommand(parent) , m_model(model) , m_trackIndex(qBound(0, trackIndex, qMax(model.rowCount() - 1, 0))) @@ -1400,17 +1499,21 @@ void RemoveTransitionByTrimOutCommand::redo() void RemoveTransitionByTrimOutCommand::undo() { if (m_clipIndex > 0) { - LOG_DEBUG() << "trackIndex" << m_trackIndex << "clipIndex" << m_clipIndex << "delta" << m_delta; + LOG_DEBUG() << "trackIndex" << m_trackIndex << "clipIndex" << m_clipIndex << "delta" + << m_delta; m_model.addTransitionByTrimIn(m_trackIndex, m_clipIndex, m_delta); // Copy properties from old transition to new transition auto clipInfo = m_model.getClipInfo(m_trackIndex, m_clipIndex); - Mlt::Service oldService = Mlt::Producer(MLT.profile(), "xml-string", m_xml.toUtf8().constData()); + Mlt::Service oldService = Mlt::Producer(MLT.profile(), + "xml-string", + m_xml.toUtf8().constData()); while (oldService.is_valid()) { if (oldService.type() == mlt_service_transition_type) { Mlt::Service newService(clipInfo->producer); while (newService.is_valid()) { - if (newService.type() == mlt_service_transition_type && - QString(oldService.get("mlt_service")) == QString(newService.get("mlt_service"))) { + if (newService.type() == mlt_service_transition_type + && QString(oldService.get("mlt_service")) + == QString(newService.get("mlt_service"))) { newService.inherit(oldService); break; } @@ -1424,11 +1527,17 @@ void RemoveTransitionByTrimOutCommand::undo() delete tmpOldService; } m_model.notifyClipOut(m_trackIndex, m_clipIndex - 1); - } else LOG_WARNING() << "invalid clip index" << m_clipIndex; + } else + LOG_WARNING() << "invalid clip index" << m_clipIndex; } -AddTransitionByTrimOutCommand::AddTransitionByTrimOutCommand(MultitrackModel &model, int trackIndex, - int clipIndex, int duration, int trimDelta, bool redo, QUndoCommand *parent) +AddTransitionByTrimOutCommand::AddTransitionByTrimOutCommand(MultitrackModel &model, + int trackIndex, + int clipIndex, + int duration, + int trimDelta, + bool redo, + QUndoCommand *parent) : TrimCommand(parent) , m_model(model) , m_trackIndex(qBound(0, trackIndex, qMax(model.rowCount() - 1, 0))) @@ -1444,8 +1553,8 @@ AddTransitionByTrimOutCommand::AddTransitionByTrimOutCommand(MultitrackModel &mo void AddTransitionByTrimOutCommand::redo() { if (m_redo) { - LOG_DEBUG() << "trackIndex" << m_trackIndex << "clipIndex" << m_clipIndex << "delta" << m_trimDelta - << "duration" << m_duration; + LOG_DEBUG() << "trackIndex" << m_trackIndex << "clipIndex" << m_clipIndex << "delta" + << m_trimDelta << "duration" << m_duration; if (m_trimDelta) m_model.trimClipOut(m_trackIndex, m_clipIndex, m_trimDelta, false, false); m_model.addTransitionByTrimOut(m_trackIndex, m_clipIndex, m_duration); @@ -1459,16 +1568,18 @@ void AddTransitionByTrimOutCommand::redo() void AddTransitionByTrimOutCommand::undo() { if (m_clipIndex + 2 < m_model.rowCount(m_model.index(m_trackIndex))) { - LOG_DEBUG() << "trackIndex" << m_trackIndex << "clipIndex" << m_clipIndex << "delta" << m_trimDelta; + LOG_DEBUG() << "trackIndex" << m_trackIndex << "clipIndex" << m_clipIndex << "delta" + << m_trimDelta; m_model.removeTransitionByTrimOut(m_trackIndex, m_clipIndex, -m_trimDelta); m_notify = true; - } else LOG_WARNING() << "invalid clip index" << m_clipIndex; + } else + LOG_WARNING() << "invalid clip index" << m_clipIndex; } bool AddTransitionByTrimOutCommand::mergeWith(const QUndoCommand *other) { - const AddTransitionByTrimOutCommand *that = static_cast - (other); + const AddTransitionByTrimOutCommand *that = static_cast( + other); if (that->id() != id() || that->m_trackIndex != m_trackIndex || that->m_clipIndex != m_clipIndex) return false; return true; @@ -1512,7 +1623,9 @@ void AddTrackCommand::undo() m_model.removeTrack(m_trackIndex); } -InsertTrackCommand::InsertTrackCommand(MultitrackModel &model, int trackIndex, TrackType trackType, +InsertTrackCommand::InsertTrackCommand(MultitrackModel &model, + int trackIndex, + TrackType trackType, QUndoCommand *parent) : QUndoCommand(parent) , m_model(model) @@ -1520,8 +1633,8 @@ InsertTrackCommand::InsertTrackCommand(MultitrackModel &model, int trackIndex, T , m_trackType(trackType) { if (trackType != AudioTrackType && trackType != VideoTrackType) { - m_trackType = model.trackList().size() > 0 ? model.trackList().at(m_trackIndex).type : - VideoTrackType; + m_trackType = model.trackList().size() > 0 ? model.trackList().at(m_trackIndex).type + : VideoTrackType; } if (m_trackType == AudioTrackType) setText(QObject::tr("Insert audio track")); @@ -1531,8 +1644,8 @@ InsertTrackCommand::InsertTrackCommand(MultitrackModel &model, int trackIndex, T void InsertTrackCommand::redo() { - LOG_DEBUG() << "trackIndex" << m_trackIndex << "type" << (m_trackType == AudioTrackType ? "audio" : - "video"); + LOG_DEBUG() << "trackIndex" << m_trackIndex << "type" + << (m_trackType == AudioTrackType ? "audio" : "video"); m_model.insertTrack(m_trackIndex, m_trackType); int mlt_index = m_model.trackList().at(m_trackIndex).mlt_index; std::unique_ptr multitrack(m_model.tractor()->multitrack()); @@ -1550,8 +1663,8 @@ void InsertTrackCommand::redo() void InsertTrackCommand::undo() { - LOG_DEBUG() << "trackIndex" << m_trackIndex << "type" << (m_trackType == AudioTrackType ? "audio" : - "video"); + LOG_DEBUG() << "trackIndex" << m_trackIndex << "type" + << (m_trackType == AudioTrackType ? "audio" : "video"); m_model.removeTrack(m_trackIndex); } @@ -1586,8 +1699,8 @@ RemoveTrackCommand::RemoveTrackCommand(MultitrackModel &model, int trackIndex, Q void RemoveTrackCommand::redo() { - LOG_DEBUG() << "trackIndex" << m_trackIndex << "type" << (m_trackType == AudioTrackType ? "audio" : - "video"); + LOG_DEBUG() << "trackIndex" << m_trackIndex << "type" + << (m_trackType == AudioTrackType ? "audio" : "video"); m_undoHelper.recordBeforeState(); int mlt_index = m_model.trackList().at(m_trackIndex).mlt_index; QScopedPointer producer(m_model.tractor()->track(mlt_index)); @@ -1603,8 +1716,8 @@ void RemoveTrackCommand::redo() void RemoveTrackCommand::undo() { - LOG_DEBUG() << "trackIndex" << m_trackIndex << "type" << (m_trackType == AudioTrackType ? "audio" : - "video"); + LOG_DEBUG() << "trackIndex" << m_trackIndex << "type" + << (m_trackType == AudioTrackType ? "audio" : "video"); m_model.insertTrack(m_trackIndex, m_trackType); m_model.setTrackName(m_trackIndex, m_trackName); @@ -1615,15 +1728,19 @@ void RemoveTrackCommand::undo() int mlt_index = m_model.trackList().at(m_trackIndex).mlt_index; QScopedPointer producer(m_model.tractor()->track(mlt_index)); Mlt::Playlist playlist(*producer); - if (playlist.is_valid() && m_filtersProducer && m_filtersProducer->is_valid()) { + if (playlist.is_valid() && m_filtersProducer && m_filtersProducer->is_valid()) { MLT.setUuid(playlist, m_uuid); MLT.copyFilters(*m_filtersProducer, playlist); QModelIndex modelIndex = m_model.index(m_trackIndex); - emit m_model.dataChanged(modelIndex, modelIndex, QVector() << MultitrackModel::IsFilteredRole); + emit m_model.dataChanged(modelIndex, + modelIndex, + QVector() << MultitrackModel::IsFilteredRole); } } -MoveTrackCommand::MoveTrackCommand(MultitrackModel &model, int fromTrackIndex, int toTrackIndex, +MoveTrackCommand::MoveTrackCommand(MultitrackModel &model, + int fromTrackIndex, + int toTrackIndex, QUndoCommand *parent) : QUndoCommand(parent) , m_model(model) @@ -1649,7 +1766,9 @@ void MoveTrackCommand::undo() } ChangeBlendModeCommand::ChangeBlendModeCommand(Mlt::Transition &transition, - const QString &propertyName, const QString &mode, QUndoCommand *parent) + const QString &propertyName, + const QString &mode, + QUndoCommand *parent) : QUndoCommand(parent) , m_transition(transition) , m_propertyName(propertyName) @@ -1685,8 +1804,8 @@ void ChangeBlendModeCommand::undo() emit modeChanged(m_oldMode); } -UpdateCommand::UpdateCommand(TimelineDock &timeline, int trackIndex, int clipIndex, - int position, QUndoCommand *parent) +UpdateCommand::UpdateCommand( + TimelineDock &timeline, int trackIndex, int clipIndex, int position, QUndoCommand *parent) : QUndoCommand(parent) , m_timeline(timeline) , m_trackIndex(trackIndex) @@ -1726,8 +1845,8 @@ void UpdateCommand::setRippleAllTracks(bool ripple) void UpdateCommand::redo() { - LOG_DEBUG() << "trackIndex" << m_trackIndex << "clipIndex" << m_clipIndex << "position" << - m_position; + LOG_DEBUG() << "trackIndex" << m_trackIndex << "clipIndex" << m_clipIndex << "position" + << m_position; if (!m_isFirstRedo) m_undoHelper.recordBeforeState(); Mlt::Producer clip(MLT.profile(), "xml-string", m_xmlAfter.toUtf8().constData()); @@ -1743,15 +1862,19 @@ void UpdateCommand::redo() void UpdateCommand::undo() { - LOG_DEBUG() << "trackIndex" << m_trackIndex << "clipIndex" << m_clipIndex << "position" << - m_position; + LOG_DEBUG() << "trackIndex" << m_trackIndex << "clipIndex" << m_clipIndex << "position" + << m_position; m_undoHelper.undoChanges(); m_timeline.setSelection(QList() << QPoint(m_clipIndex, m_trackIndex)); m_isFirstRedo = false; } -DetachAudioCommand::DetachAudioCommand(TimelineDock &timeline, int trackIndex, int clipIndex, - int position, const QString &xml, QUndoCommand *parent) +DetachAudioCommand::DetachAudioCommand(TimelineDock &timeline, + int trackIndex, + int clipIndex, + int position, + const QString &xml, + QUndoCommand *parent) : QUndoCommand(parent) , m_timeline(timeline) , m_trackIndex(qBound(0, trackIndex, qMax(timeline.model()->rowCount() - 1, 0))) @@ -1767,8 +1890,8 @@ DetachAudioCommand::DetachAudioCommand(TimelineDock &timeline, int trackIndex, i void DetachAudioCommand::redo() { - LOG_DEBUG() << "trackIndex" << m_trackIndex << "clipIndex" << m_clipIndex << "position" << - m_position; + LOG_DEBUG() << "trackIndex" << m_trackIndex << "clipIndex" << m_clipIndex << "position" + << m_position; Mlt::Producer audioClip(MLT.profile(), "xml-string", m_xml.toUtf8().constData()); Mlt::Producer videoClip(MLT.profile(), "xml-string", m_xml.toUtf8().constData()); int groupNumber = -1; @@ -1779,7 +1902,7 @@ void DetachAudioCommand::redo() { auto videoClipInfo = model->getClipInfo(m_trackIndex, m_clipIndex); if (videoClipInfo && videoClipInfo->cut - && videoClipInfo->cut->property_exists(kShotcutGroupProperty)) { + && videoClipInfo->cut->property_exists(kShotcutGroupProperty)) { groupNumber = videoClipInfo->cut->get_int(kShotcutGroupProperty); } } @@ -1791,7 +1914,7 @@ void DetachAudioCommand::redo() for (int i = 0; i < videoClip.filter_count(); i++) { Mlt::Filter *filter = videoClip.filter(i); if (filter && filter->is_valid() && !filter->get_int("_loader") - && !filter->get_int(kShotcutHiddenProperty)) { + && !filter->get_int(kShotcutHiddenProperty)) { QmlMetadata *newMeta = MAIN.filterController()->metadataForService(filter); if (newMeta && newMeta->isAudio()) { videoClip.detach(*filter); @@ -1808,7 +1931,7 @@ void DetachAudioCommand::redo() for (int i = 0; i < audioClip.filter_count(); i++) { Mlt::Filter *filter = audioClip.filter(i); if (filter && filter->is_valid() && !filter->get_int("_loader") - && !filter->get_int(kShotcutHiddenProperty)) { + && !filter->get_int(kShotcutHiddenProperty)) { QmlMetadata *newMeta = MAIN.filterController()->metadataForService(filter); if (newMeta && !newMeta->isAudio()) { audioClip.detach(*filter); @@ -1821,7 +1944,8 @@ void DetachAudioCommand::redo() // Add an audio track if needed. int n = model->trackList().size(); for (int i = 0; i < n; i++) { - QScopedPointer track(model->tractor()->track(model->trackList()[i].mlt_index)); + QScopedPointer track( + model->tractor()->track(model->trackList()[i].mlt_index)); if (!track->is_valid()) continue; if (track->get(kAudioTrackProperty)) { @@ -1829,7 +1953,8 @@ void DetachAudioCommand::redo() int out = videoClip.get_playtime() - 1; // If the audio track is blank in the target region. if (playlist.is_blank_at(m_position) && playlist.is_blank_at(m_position + out) - && playlist.get_clip_index_at(m_position) == playlist.get_clip_index_at(m_position + out)) { + && playlist.get_clip_index_at(m_position) + == playlist.get_clip_index_at(m_position + out)) { // Save the target track index. m_targetTrackIndex = i; break; @@ -1870,8 +1995,10 @@ void DetachAudioCommand::redo() } m_undoHelper.recordAfterState(); QModelIndex modelIndex = model->makeIndex(m_trackIndex, m_clipIndex); - emit model->dataChanged(modelIndex, modelIndex, - QVector() << MultitrackModel::AudioIndexRole << MultitrackModel::GroupRole); + emit model->dataChanged(modelIndex, + modelIndex, + QVector() << MultitrackModel::AudioIndexRole + << MultitrackModel::GroupRole); m_timeline.setSelection(QList() << QPoint(m_clipIndex, m_trackIndex)); } } @@ -1879,8 +2006,8 @@ void DetachAudioCommand::redo() void DetachAudioCommand::undo() { - LOG_DEBUG() << "trackIndex" << m_trackIndex << "clipIndex" << m_clipIndex << "position" << - m_position; + LOG_DEBUG() << "trackIndex" << m_trackIndex << "clipIndex" << m_clipIndex << "position" + << m_position; auto model = m_timeline.model(); m_undoHelper.undoChanges(); if (m_trackAdded) { @@ -1891,14 +2018,16 @@ void DetachAudioCommand::undo() Mlt::Producer originalClip(MLT.profile(), "xml-string", m_xml.toUtf8().constData()); model->overwrite(m_trackIndex, originalClip, m_position, true); QModelIndex modelIndex = model->makeIndex(m_trackIndex, m_clipIndex); - emit model->dataChanged(modelIndex, modelIndex, - QVector() << MultitrackModel::AudioIndexRole << MultitrackModel::AudioLevelsRole << - MultitrackModel::GroupRole); + emit model->dataChanged(modelIndex, + modelIndex, + QVector() + << MultitrackModel::AudioIndexRole + << MultitrackModel::AudioLevelsRole << MultitrackModel::GroupRole); m_timeline.setSelection(QList() << QPoint(m_clipIndex, m_trackIndex)); } -ReplaceCommand::ReplaceCommand(MultitrackModel &model, int trackIndex, int clipIndex, - const QString &xml, QUndoCommand *parent) +ReplaceCommand::ReplaceCommand( + MultitrackModel &model, int trackIndex, int clipIndex, const QString &xml, QUndoCommand *parent) : QUndoCommand(parent) , m_model(model) , m_trackIndex(qBound(0, trackIndex, qMax(model.rowCount() - 1, 0))) @@ -1951,7 +2080,8 @@ void AlignClipsCommand::addAlignment(QUuid uuid, int offset, double speed) void AlignClipsCommand::redo() { LOG_DEBUG() << "Alignment Clips:" << m_alignments.size(); - struct ClipItem { + struct ClipItem + { Mlt::Producer *clip; int track; int start; @@ -2009,7 +2139,8 @@ void AlignClipsCommand::undo() m_undoHelper.undoChanges(); } -ApplyFiltersCommand::ApplyFiltersCommand(MultitrackModel &model, const QString &filterProducerXml, +ApplyFiltersCommand::ApplyFiltersCommand(MultitrackModel &model, + const QString &filterProducerXml, QUndoCommand *parent) : QUndoCommand(parent) , m_model(model) @@ -2021,7 +2152,7 @@ ApplyFiltersCommand::ApplyFiltersCommand(MultitrackModel &model, const QString & void ApplyFiltersCommand::addClip(int trackIndex, int clipIndex) { auto clipInfo = m_model.getClipInfo(trackIndex, clipIndex); - if (clipInfo && clipInfo->producer && !clipInfo->cut->is_blank() ) { + if (clipInfo && clipInfo->producer && !clipInfo->cut->is_blank()) { ClipPosition position(trackIndex, clipIndex); m_prevFilters.insert(position, MLT.XML(clipInfo->producer)); } @@ -2033,7 +2164,7 @@ void ApplyFiltersCommand::redo() Mlt::Producer filtersProducer(MLT.profile(), "xml-string", m_xml.toUtf8().constData()); if (!filtersProducer.is_valid() || filtersProducer.filter_count() < 1 - || !filtersProducer.get_int(kShotcutFiltersClipboard)) { + || !filtersProducer.get_int(kShotcutFiltersClipboard)) { LOG_ERROR() << "Invalid filters producer"; return; } @@ -2043,7 +2174,7 @@ void ApplyFiltersCommand::redo() for (int i = 0; i < filtersProducer.filter_count(); i++) { Mlt::Filter *filter = filtersProducer.filter(i); if (filter && filter->is_valid() && !filter->get_int("_loader") - && !filter->get_int(kShotcutHiddenProperty)) { + && !filter->get_int(kShotcutHiddenProperty)) { m_applyMeta.append(MAIN.filterController()->metadataForService(filter)); } delete filter; @@ -2056,7 +2187,7 @@ void ApplyFiltersCommand::redo() for (int i = 0; i < clipInfo->producer->filter_count(); i++) { Mlt::Filter *filter = clipInfo->producer->filter(i); if (filter && filter->is_valid() && !filter->get_int("_loader") - && !filter->get_int(kShotcutHiddenProperty)) { + && !filter->get_int(kShotcutHiddenProperty)) { QmlMetadata *currentMeta = MAIN.filterController()->metadataForService(filter); for (int j = 0; j < m_applyMeta.size(); j++) { if (m_applyMeta[j] == currentMeta) { @@ -2088,14 +2219,15 @@ void ApplyFiltersCommand::undo() for (int i = 0; i < clipInfo->producer->filter_count(); i++) { Mlt::Filter *filter = clipInfo->producer->filter(i); if (filter && filter->is_valid() && !filter->get_int("_loader") - && !filter->get_int(kShotcutHiddenProperty)) { + && !filter->get_int(kShotcutHiddenProperty)) { clipInfo->producer->detach(*filter); i--; } delete filter; } // Copy the previous filters - Mlt::Producer previousProducer(MLT.profile(), "xml-string", + Mlt::Producer previousProducer(MLT.profile(), + "xml-string", m_prevFilters[clip].toUtf8().constData()); if (previousProducer.is_valid()) { // Apply the previous filters @@ -2111,6 +2243,6 @@ void ApplyFiltersCommand::undo() } } -} // namespace +} // namespace Timeline #include "moc_timelinecommands.cpp" diff --git a/src/commands/timelinecommands.h b/src/commands/timelinecommands.h index 8e32d5b7ff..988d6e8821 100644 --- a/src/commands/timelinecommands.h +++ b/src/commands/timelinecommands.h @@ -18,16 +18,17 @@ #ifndef COMMANDS_H #define COMMANDS_H -#include "models/multitrackmodel.h" -#include "models/markersmodel.h" #include "docks/timelinedock.h" +#include "models/markersmodel.h" +#include "models/multitrackmodel.h" #include "undohelper.h" -#include -#include + +#include +#include #include +#include +#include #include -#include -#include #include @@ -46,14 +47,15 @@ enum { UndoIdMoveClip }; -struct ClipPosition { +struct ClipPosition +{ ClipPosition(int track, int clip) { trackIndex = track; clipIndex = clip; } - bool operator < (const ClipPosition &rhs) const + bool operator<(const ClipPosition &rhs) const { if (trackIndex == rhs.trackIndex) { return clipIndex < rhs.clipIndex; @@ -69,10 +71,15 @@ struct ClipPosition { class AppendCommand : public QUndoCommand { public: - AppendCommand(MultitrackModel &model, int trackIndex, const QString &xml, bool skipProxy = false, - bool seek = true, QUndoCommand *parent = 0); + AppendCommand(MultitrackModel &model, + int trackIndex, + const QString &xml, + bool skipProxy = false, + bool seek = true, + QUndoCommand *parent = 0); void redo(); void undo(); + private: MultitrackModel &m_model; int m_trackIndex; @@ -85,10 +92,16 @@ class AppendCommand : public QUndoCommand class InsertCommand : public QUndoCommand { public: - InsertCommand(MultitrackModel &model, MarkersModel &markersModel, int trackIndex, int position, - const QString &xml, bool seek = true, QUndoCommand *parent = 0); + InsertCommand(MultitrackModel &model, + MarkersModel &markersModel, + int trackIndex, + int position, + const QString &xml, + bool seek = true, + QUndoCommand *parent = 0); void redo(); void undo(); + private: MultitrackModel &m_model; MarkersModel &m_markersModel; @@ -106,10 +119,15 @@ class InsertCommand : public QUndoCommand class OverwriteCommand : public QUndoCommand { public: - OverwriteCommand(MultitrackModel &model, int trackIndex, int position, const QString &xml, - bool seek = true, QUndoCommand *parent = 0); + OverwriteCommand(MultitrackModel &model, + int trackIndex, + int position, + const QString &xml, + bool seek = true, + QUndoCommand *parent = 0); void redo(); void undo(); + private: MultitrackModel &m_model; int m_trackIndex; @@ -125,6 +143,7 @@ class LiftCommand : public QUndoCommand LiftCommand(MultitrackModel &model, int trackIndex, int clipIndex, QUndoCommand *parent = 0); void redo(); void undo(); + private: MultitrackModel &m_model; int m_trackIndex; @@ -135,10 +154,14 @@ class LiftCommand : public QUndoCommand class RemoveCommand : public QUndoCommand { public: - RemoveCommand(MultitrackModel &model, MarkersModel &markersModel, int trackIndex, int clipIndex, + RemoveCommand(MultitrackModel &model, + MarkersModel &markersModel, + int trackIndex, + int clipIndex, QUndoCommand *parent = 0); void redo(); void undo(); + private: MultitrackModel &m_model; MarkersModel &m_markersModel; @@ -159,6 +182,7 @@ class GroupCommand : public QUndoCommand void addToGroup(int trackIndex, int clipIndex); void redo(); void undo(); + private: MultitrackModel &m_model; QList m_clips; @@ -172,6 +196,7 @@ class UngroupCommand : public QUndoCommand void removeFromGroup(int trackIndex, int clipIndex); void redo(); void undo(); + private: MultitrackModel &m_model; QMap m_prevGroups; @@ -180,10 +205,13 @@ class UngroupCommand : public QUndoCommand class NameTrackCommand : public QUndoCommand { public: - NameTrackCommand(MultitrackModel &model, int trackIndex, const QString &name, + NameTrackCommand(MultitrackModel &model, + int trackIndex, + const QString &name, QUndoCommand *parent = 0); void redo(); void undo(); + private: MultitrackModel &m_model; int m_trackIndex; @@ -197,6 +225,7 @@ class MergeCommand : public QUndoCommand MergeCommand(MultitrackModel &model, int trackIndex, int clipIndex, QUndoCommand *parent = 0); void redo(); void undo(); + private: MultitrackModel &m_model; int m_trackIndex; @@ -210,6 +239,7 @@ class MuteTrackCommand : public QUndoCommand MuteTrackCommand(MultitrackModel &model, int trackIndex, QUndoCommand *parent = 0); void redo(); void undo(); + private: MultitrackModel &m_model; int m_trackIndex; @@ -222,6 +252,7 @@ class HideTrackCommand : public QUndoCommand HideTrackCommand(MultitrackModel &model, int trackIndex, QUndoCommand *parent = 0); void redo(); void undo(); + private: MultitrackModel &m_model; int m_trackIndex; @@ -231,9 +262,13 @@ class HideTrackCommand : public QUndoCommand class CompositeTrackCommand : public QUndoCommand { public: - CompositeTrackCommand(MultitrackModel &model, int trackIndex, bool value, QUndoCommand *parent = 0); + CompositeTrackCommand(MultitrackModel &model, + int trackIndex, + bool value, + QUndoCommand *parent = 0); void redo(); void undo(); + private: MultitrackModel &m_model; int m_trackIndex; @@ -247,6 +282,7 @@ class LockTrackCommand : public QUndoCommand LockTrackCommand(MultitrackModel &model, int trackIndex, bool value, QUndoCommand *parent = 0); void redo(); void undo(); + private: MultitrackModel &m_model; int m_trackIndex; @@ -257,17 +293,19 @@ class LockTrackCommand : public QUndoCommand class MoveClipCommand : public QUndoCommand { public: - MoveClipCommand(TimelineDock &timeline, int trackDelta, int positionDelta, bool ripple, + MoveClipCommand(TimelineDock &timeline, + int trackDelta, + int positionDelta, + bool ripple, QUndoCommand *parent = 0); void addClip(int trackIndex, int clipIndex); void redo(); void undo(); + protected: - int id() const - { - return UndoIdMoveClip; - } + int id() const { return UndoIdMoveClip; } bool mergeWith(const QUndoCommand *other); + private: void redoMarkers(); @@ -275,7 +313,8 @@ class MoveClipCommand : public QUndoCommand MultitrackModel &m_model; MarkersModel &m_markersModel; - struct Info { + struct Info + { int trackIndex; int clipIndex; int frame_in; @@ -309,11 +348,10 @@ class MoveClipCommand : public QUndoCommand class TrimCommand : public QUndoCommand { public: - explicit TrimCommand(QUndoCommand *parent = 0) : QUndoCommand(parent) {} - void setUndoHelper(UndoHelper *helper) - { - m_undoHelper.reset(helper); - } + explicit TrimCommand(QUndoCommand *parent = 0) + : QUndoCommand(parent) + {} + void setUndoHelper(UndoHelper *helper) { m_undoHelper.reset(helper); } protected: QScopedPointer m_undoHelper; @@ -322,16 +360,21 @@ class TrimCommand : public QUndoCommand class TrimClipInCommand : public TrimCommand { public: - TrimClipInCommand(MultitrackModel &model, MarkersModel &markersModel, int trackIndex, int clipIndex, - int delta, bool ripple, bool redo = true, QUndoCommand *parent = 0); + TrimClipInCommand(MultitrackModel &model, + MarkersModel &markersModel, + int trackIndex, + int clipIndex, + int delta, + bool ripple, + bool redo = true, + QUndoCommand *parent = 0); void redo(); void undo(); + protected: - int id() const - { - return UndoIdTrimClipIn; - } + int id() const { return UndoIdTrimClipIn; } bool mergeWith(const QUndoCommand *other); + private: MultitrackModel &m_model; MarkersModel &m_markersModel; @@ -350,16 +393,21 @@ class TrimClipInCommand : public TrimCommand class TrimClipOutCommand : public TrimCommand { public: - TrimClipOutCommand(MultitrackModel &model, MarkersModel &markersModel, int trackIndex, - int clipIndex, int delta, bool ripple, bool redo = true, QUndoCommand *parent = 0); + TrimClipOutCommand(MultitrackModel &model, + MarkersModel &markersModel, + int trackIndex, + int clipIndex, + int delta, + bool ripple, + bool redo = true, + QUndoCommand *parent = 0); void redo(); void undo(); + protected: - int id() const - { - return UndoIdTrimClipOut; - } + int id() const { return UndoIdTrimClipOut; } bool mergeWith(const QUndoCommand *other); + private: MultitrackModel &m_model; MarkersModel &m_markersModel; @@ -378,12 +426,14 @@ class TrimClipOutCommand : public TrimCommand class SplitCommand : public QUndoCommand { public: - SplitCommand(MultitrackModel &model, const std::vector &trackIndex, + SplitCommand(MultitrackModel &model, + const std::vector &trackIndex, const std::vector &clipIndex, int position, QUndoCommand *parent = 0); void redo(); void undo(); + private: MultitrackModel &m_model; std::vector m_trackIndex; @@ -395,16 +445,18 @@ class SplitCommand : public QUndoCommand class FadeInCommand : public QUndoCommand { public: - FadeInCommand(MultitrackModel &model, int trackIndex, int clipIndex, int duration, + FadeInCommand(MultitrackModel &model, + int trackIndex, + int clipIndex, + int duration, QUndoCommand *parent = 0); void redo(); void undo(); + protected: - int id() const - { - return UndoIdFadeIn; - } + int id() const { return UndoIdFadeIn; } bool mergeWith(const QUndoCommand *other); + private: MultitrackModel &m_model; int m_trackIndex; @@ -416,16 +468,18 @@ class FadeInCommand : public QUndoCommand class FadeOutCommand : public QUndoCommand { public: - FadeOutCommand(MultitrackModel &model, int trackIndex, int clipIndex, int duration, + FadeOutCommand(MultitrackModel &model, + int trackIndex, + int clipIndex, + int duration, QUndoCommand *parent = 0); void redo(); void undo(); + protected: - int id() const - { - return UndoIdFadeOut; - } + int id() const { return UndoIdFadeOut; } bool mergeWith(const QUndoCommand *other); + private: MultitrackModel &m_model; int m_trackIndex; @@ -437,14 +491,16 @@ class FadeOutCommand : public QUndoCommand class AddTransitionCommand : public QUndoCommand { public: - AddTransitionCommand(TimelineDock &timeline, int trackIndex, int clipIndex, int position, - bool ripple, QUndoCommand *parent = 0); + AddTransitionCommand(TimelineDock &timeline, + int trackIndex, + int clipIndex, + int position, + bool ripple, + QUndoCommand *parent = 0); void redo(); void undo(); - int getTransitionIndex() const - { - return m_transitionIndex; - } + int getTransitionIndex() const { return m_transitionIndex; } + private: TimelineDock &m_timeline; MultitrackModel &m_model; @@ -465,16 +521,19 @@ class AddTransitionCommand : public QUndoCommand class TrimTransitionInCommand : public TrimCommand { public: - TrimTransitionInCommand(MultitrackModel &model, int trackIndex, int clipIndex, int delta, - bool redo = true, QUndoCommand *parent = 0); + TrimTransitionInCommand(MultitrackModel &model, + int trackIndex, + int clipIndex, + int delta, + bool redo = true, + QUndoCommand *parent = 0); void redo(); void undo(); + protected: - int id() const - { - return UndoIdTrimTransitionIn; - } + int id() const { return UndoIdTrimTransitionIn; } bool mergeWith(const QUndoCommand *other); + private: MultitrackModel &m_model; int m_trackIndex; @@ -487,16 +546,19 @@ class TrimTransitionInCommand : public TrimCommand class TrimTransitionOutCommand : public TrimCommand { public: - TrimTransitionOutCommand(MultitrackModel &model, int trackIndex, int clipIndex, int delta, - bool redo = true, QUndoCommand *parent = 0); + TrimTransitionOutCommand(MultitrackModel &model, + int trackIndex, + int clipIndex, + int delta, + bool redo = true, + QUndoCommand *parent = 0); void redo(); void undo(); + protected: - int id() const - { - return UndoIdTrimTransitionOut; - } + int id() const { return UndoIdTrimTransitionOut; } bool mergeWith(const QUndoCommand *other); + private: MultitrackModel &m_model; int m_trackIndex; @@ -509,16 +571,20 @@ class TrimTransitionOutCommand : public TrimCommand class AddTransitionByTrimInCommand : public TrimCommand { public: - AddTransitionByTrimInCommand(TimelineDock &timeline, int trackIndex, int clipIndex, int duration, - int trimDelta, bool redo = true, QUndoCommand *parent = 0); + AddTransitionByTrimInCommand(TimelineDock &timeline, + int trackIndex, + int clipIndex, + int duration, + int trimDelta, + bool redo = true, + QUndoCommand *parent = 0); void redo(); void undo(); + protected: - int id() const - { - return UndoIdAddTransitionByTrimIn; - } + int id() const { return UndoIdAddTransitionByTrimIn; } bool mergeWith(const QUndoCommand *other); + private: TimelineDock &m_timeline; int m_trackIndex; @@ -532,10 +598,16 @@ class AddTransitionByTrimInCommand : public TrimCommand class RemoveTransitionByTrimInCommand : public TrimCommand { public: - RemoveTransitionByTrimInCommand(MultitrackModel &model, int trackIndex, int clipIndex, int delta, - QString xml, bool redo = true, QUndoCommand *parent = 0); + RemoveTransitionByTrimInCommand(MultitrackModel &model, + int trackIndex, + int clipIndex, + int delta, + QString xml, + bool redo = true, + QUndoCommand *parent = 0); void redo(); void undo(); + private: MultitrackModel &m_model; int m_trackIndex; @@ -548,10 +620,16 @@ class RemoveTransitionByTrimInCommand : public TrimCommand class RemoveTransitionByTrimOutCommand : public TrimCommand { public: - RemoveTransitionByTrimOutCommand(MultitrackModel &model, int trackIndex, int clipIndex, int delta, - QString xml, bool redo = true, QUndoCommand *parent = 0); + RemoveTransitionByTrimOutCommand(MultitrackModel &model, + int trackIndex, + int clipIndex, + int delta, + QString xml, + bool redo = true, + QUndoCommand *parent = 0); void redo(); void undo(); + private: MultitrackModel &m_model; int m_trackIndex; @@ -564,16 +642,20 @@ class RemoveTransitionByTrimOutCommand : public TrimCommand class AddTransitionByTrimOutCommand : public TrimCommand { public: - AddTransitionByTrimOutCommand(MultitrackModel &model, int trackIndex, int clipIndex, int duration, - int trimDelta, bool redo = true, QUndoCommand *parent = 0); + AddTransitionByTrimOutCommand(MultitrackModel &model, + int trackIndex, + int clipIndex, + int duration, + int trimDelta, + bool redo = true, + QUndoCommand *parent = 0); void redo(); void undo(); + protected: - int id() const - { - return UndoIdAddTransitionByTrimOut; - } + int id() const { return UndoIdAddTransitionByTrimOut; } bool mergeWith(const QUndoCommand *other); + private: MultitrackModel &m_model; int m_trackIndex; @@ -584,12 +666,13 @@ class AddTransitionByTrimOutCommand : public TrimCommand bool m_redo; }; -class AddTrackCommand: public QUndoCommand +class AddTrackCommand : public QUndoCommand { public: AddTrackCommand(MultitrackModel &model, bool isVideo, QUndoCommand *parent = 0); void redo(); void undo(); + private: MultitrackModel &m_model; int m_trackIndex; @@ -600,10 +683,13 @@ class AddTrackCommand: public QUndoCommand class InsertTrackCommand : public QUndoCommand { public: - InsertTrackCommand(MultitrackModel &model, int trackIndex, TrackType trackType = PlaylistTrackType, + InsertTrackCommand(MultitrackModel &model, + int trackIndex, + TrackType trackType = PlaylistTrackType, QUndoCommand *parent = 0); void redo(); void undo(); + private: MultitrackModel &m_model; int m_trackIndex; @@ -617,6 +703,7 @@ class RemoveTrackCommand : public QUndoCommand RemoveTrackCommand(MultitrackModel &model, int trackIndex, QUndoCommand *parent = 0); void redo(); void undo(); + private: MultitrackModel &m_model; int m_trackIndex; @@ -630,10 +717,13 @@ class RemoveTrackCommand : public QUndoCommand class MoveTrackCommand : public QUndoCommand { public: - MoveTrackCommand(MultitrackModel &model, int fromTrackIndex, int toTrackIndex, + MoveTrackCommand(MultitrackModel &model, + int fromTrackIndex, + int toTrackIndex, QUndoCommand *parent = 0); void redo(); void undo(); + private: MultitrackModel &m_model; int m_fromTrackIndex; @@ -644,12 +734,15 @@ class ChangeBlendModeCommand : public QObject, public QUndoCommand { Q_OBJECT public: - ChangeBlendModeCommand(Mlt::Transition &transition, const QString &propertyName, - const QString &mode, QUndoCommand *parent = 0); + ChangeBlendModeCommand(Mlt::Transition &transition, + const QString &propertyName, + const QString &mode, + QUndoCommand *parent = 0); void redo(); void undo(); signals: void modeChanged(QString &mode); + private: Mlt::Transition m_transition; QString m_propertyName; @@ -660,25 +753,20 @@ class ChangeBlendModeCommand : public QObject, public QUndoCommand class UpdateCommand : public QUndoCommand { public: - UpdateCommand(TimelineDock &timeline, int trackIndex, int clipIndex, int position, + UpdateCommand(TimelineDock &timeline, + int trackIndex, + int clipIndex, + int position, QUndoCommand *parent = 0); void setXmlAfter(const QString &xml); void setPosition(int trackIndex, int clipIndex, int position); void setRippleAllTracks(bool); - int trackIndex() const - { - return m_trackIndex; - } - int clipIndex() const - { - return m_clipIndex; - } - int position() const - { - return m_position; - } + int trackIndex() const { return m_trackIndex; } + int clipIndex() const { return m_clipIndex; } + int position() const { return m_position; } void redo(); void undo(); + private: TimelineDock &m_timeline; int m_trackIndex; @@ -691,13 +779,18 @@ class UpdateCommand : public QUndoCommand bool m_rippleAllTracks; }; -class DetachAudioCommand: public QUndoCommand +class DetachAudioCommand : public QUndoCommand { public: - DetachAudioCommand(TimelineDock &timeline, int trackIndex, int clipIndex, int position, - const QString &xml, QUndoCommand *parent = 0); + DetachAudioCommand(TimelineDock &timeline, + int trackIndex, + int clipIndex, + int position, + const QString &xml, + QUndoCommand *parent = 0); void redo(); void undo(); + private: TimelineDock &m_timeline; int m_trackIndex; @@ -713,10 +806,14 @@ class DetachAudioCommand: public QUndoCommand class ReplaceCommand : public QUndoCommand { public: - ReplaceCommand(MultitrackModel &model, int trackIndex, int clipIndex, const QString &xml, + ReplaceCommand(MultitrackModel &model, + int trackIndex, + int clipIndex, + const QString &xml, QUndoCommand *parent = nullptr); void redo(); void undo(); + private: MultitrackModel &m_model; int m_trackIndex; @@ -726,7 +823,6 @@ class ReplaceCommand : public QUndoCommand UndoHelper m_undoHelper; }; - class AlignClipsCommand : public QUndoCommand { public: @@ -739,7 +835,8 @@ class AlignClipsCommand : public QUndoCommand MultitrackModel &m_model; UndoHelper m_undoHelper; bool m_redo; - struct Alignment { + struct Alignment + { QUuid uuid; int offset; double speed; @@ -750,7 +847,8 @@ class AlignClipsCommand : public QUndoCommand class ApplyFiltersCommand : public QUndoCommand { public: - ApplyFiltersCommand(MultitrackModel &model, const QString &filterProducerXml, + ApplyFiltersCommand(MultitrackModel &model, + const QString &filterProducerXml, QUndoCommand *parent = 0); void addClip(int trackIndex, int clipIndex); void redo(); diff --git a/src/commands/undohelper.cpp b/src/commands/undohelper.cpp index 91ee644583..97c6f60b20 100644 --- a/src/commands/undohelper.cpp +++ b/src/commands/undohelper.cpp @@ -16,24 +16,27 @@ */ #include "undohelper.h" + +#include "Logger.h" #include "mltcontroller.h" #include "models/audiolevelstask.h" #include "shotcut_mlt_properties.h" -#include + #include #include #ifdef UNDOHELPER_DEBUG #define UNDOLOG LOG_DEBUG() #else -#define UNDOLOG if (false) LOG_DEBUG() +#define UNDOLOG \ + if (false) \ + LOG_DEBUG() #endif UndoHelper::UndoHelper(MultitrackModel &model) : m_model(model) , m_hints(NoHints) -{ -} +{} void UndoHelper::recordBeforeState() { @@ -103,11 +106,10 @@ void UndoHelper::recordAfterState() info.newClipIndex = j; /* Indices have changed; these are moved */ - if (info.oldTrackIndex != info.newTrackIndex || info.oldClipIndex != info.newClipIndex) { - UNDOLOG << "Clip" << uid << "moved from" - << info.oldTrackIndex << info.oldClipIndex - << "to" - << info.newTrackIndex << info.newClipIndex; + if (info.oldTrackIndex != info.newTrackIndex + || info.oldClipIndex != info.newClipIndex) { + UNDOLOG << "Clip" << uid << "moved from" << info.oldTrackIndex + << info.oldClipIndex << "to" << info.newTrackIndex << info.newClipIndex; info.changes |= Moved; m_affectedTracks << info.oldTrackIndex; m_affectedTracks << info.newTrackIndex; @@ -166,21 +168,23 @@ void UndoHelper::undoChanges() * the current index are as they were originally before we move on to the next one */ foreach (QUuid uid, m_insertedOrder) { const Info &info = m_state[uid]; - UNDOLOG << "Handling uid" << uid << "on track" << info.oldTrackIndex << "index" << - info.oldClipIndex; + UNDOLOG << "Handling uid" << uid << "on track" << info.oldTrackIndex << "index" + << info.oldClipIndex; int trackIndex = m_model.trackList()[info.oldTrackIndex].mlt_index; QScopedPointer trackProducer(m_model.tractor()->track(trackIndex)); Mlt::Playlist playlist(*trackProducer); /* This is the index in the track we're currently restoring */ - int currentIndex = qMin(info.oldClipIndex + indexAdjustment[trackIndex], playlist.count() - 1); + int currentIndex = qMin(info.oldClipIndex + indexAdjustment[trackIndex], + playlist.count() - 1); /* Clips that were moved are simply searched for using the uid, and moved in place. We * do not use the indices directly because they become invalid once the playlist is * modified. */ if (info.changes & Moved) { - Q_ASSERT(info.newTrackIndex == info.oldTrackIndex && "cross-track moves are unsupported so far"); + Q_ASSERT(info.newTrackIndex == info.oldTrackIndex + && "cross-track moves are unsupported so far"); int clipCurrentlyAt = -1; for (int i = 0; i < playlist.count(); ++i) { QScopedPointer clip(playlist.get_clip(i)); @@ -192,11 +196,14 @@ void UndoHelper::undoChanges() Q_ASSERT(clipCurrentlyAt != -1 && "Moved clip could not be found"); UNDOLOG << "Found clip with uid" << uid << "at index" << clipCurrentlyAt; - if (clipCurrentlyAt != info.oldClipIndex && - (currentIndex < clipCurrentlyAt || currentIndex > clipCurrentlyAt + 1)) { + if (clipCurrentlyAt != info.oldClipIndex + && (currentIndex < clipCurrentlyAt || currentIndex > clipCurrentlyAt + 1)) { UNDOLOG << "moving from" << clipCurrentlyAt << "to" << currentIndex; QModelIndex modelIndex = m_model.createIndex(clipCurrentlyAt, 0, info.oldTrackIndex); - m_model.beginMoveRows(modelIndex.parent(), clipCurrentlyAt, clipCurrentlyAt, modelIndex.parent(), + m_model.beginMoveRows(modelIndex.parent(), + clipCurrentlyAt, + clipCurrentlyAt, + modelIndex.parent(), currentIndex); playlist.move(clipCurrentlyAt, currentIndex); m_model.endMoveRows(); @@ -214,7 +221,9 @@ void UndoHelper::undoChanges() UNDOLOG << "inserting clip at " << currentIndex << uid; Q_ASSERT(!(m_hints & SkipXML) && "Cannot restore clip without stored XML"); Q_ASSERT(!info.xml.isEmpty()); - Mlt::Producer restoredClip(MLT.profile(), "xml-string", info.xml.toUtf8().constData()); + Mlt::Producer restoredClip(MLT.profile(), + "xml-string", + info.xml.toUtf8().constData()); if (restoredClip.type() == mlt_service_tractor_type) { // transition restoredClip.set("mlt_type", "mlt_producer"); } else { @@ -246,7 +255,8 @@ void UndoHelper::undoChanges() QScopedPointer clip(playlist.get_clip(currentIndex)); if (clip && clip->is_valid()) { - UNDOLOG << "resizing clip at" << currentIndex << "in" << info.frame_in << "out" << info.frame_out; + UNDOLOG << "resizing clip at" << currentIndex << "in" << info.frame_in << "out" + << info.frame_out; if (clip->parent().get_data("mlt_mix")) clip->parent().set("mlt_mix", nullptr, 0); if (clip->get_data("mix_in")) @@ -254,7 +264,11 @@ void UndoHelper::undoChanges() if (clip->get_data("mix_out")) clip->set("mix_out", nullptr, 0); playlist.resize_clip(currentIndex, info.frame_in, info.frame_out); - MLT.adjustClipFilters(clip->parent(), filterIn, filterOut, info.in_delta, info.out_delta, + MLT.adjustClipFilters(clip->parent(), + filterIn, + filterOut, + info.in_delta, + info.out_delta, info.in_delta); } @@ -324,9 +338,12 @@ void UndoHelper::debugPrintState(const QString &title) if (info.producer->is_blank() && info.cut) { uid = MLT.uuid(*info.cut); } - trackStr += QStringLiteral(" [ %5 %1 -> %2 (%3 frames) %4]").arg(info.frame_in).arg( - info.frame_out).arg( - info.frame_count).arg(info.cut->is_blank() ? "blank " : "clip").arg(uid.toString()); + trackStr += QStringLiteral(" [ %5 %1 -> %2 (%3 frames) %4]") + .arg(info.frame_in) + .arg(info.frame_out) + .arg(info.frame_count) + .arg(info.cut->is_blank() ? "blank " : "clip") + .arg(uid.toString()); } LOG_DEBUG() << qPrintable(trackStr); } @@ -353,8 +370,8 @@ void UndoHelper::restoreAffectedTracks() for (const auto &uid : std::as_const(m_insertedOrder)) { const Info &info = m_state[uid]; if (m_affectedTracks.contains(info.oldTrackIndex)) { - UNDOLOG << "Handling uid" << uid << "on track" << info.oldTrackIndex << "index" << - info.oldClipIndex; + UNDOLOG << "Handling uid" << uid << "on track" << info.oldTrackIndex << "index" + << info.oldClipIndex; // Clips are restored using their stored XML. int mltIndex = m_model.trackList()[info.oldTrackIndex].mlt_index; QScopedPointer trackProducer(m_model.tractor()->track(mltIndex)); @@ -369,7 +386,9 @@ void UndoHelper::restoreAffectedTracks() UNDOLOG << "appending clip at" << currentIndex; Q_ASSERT(!(m_hints & SkipXML) && "Cannot restore clip without stored XML"); Q_ASSERT(!info.xml.isEmpty()); - Mlt::Producer restoredClip(MLT.profile(), "xml-string", info.xml.toUtf8().constData()); + Mlt::Producer restoredClip(MLT.profile(), + "xml-string", + info.xml.toUtf8().constData()); if (restoredClip.type() == mlt_service_tractor_type) { // transition restoredClip.set("mlt_type", "mlt_producer"); } @@ -413,9 +432,7 @@ void UndoHelper::fixTransitions(Mlt::Playlist playlist, int clipIndex, Mlt::Prod return; } int transitionIndex = 0; - for (auto currentIndex : { - clipIndex + 1, clipIndex - 1 - }) { + for (auto currentIndex : {clipIndex + 1, clipIndex - 1}) { // Connect a transition on the right/left to the new producer. Mlt::Producer producer(playlist.get_clip(currentIndex)); if (producer.is_valid() && producer.parent().get(kShotcutTransitionProperty)) { @@ -423,10 +440,11 @@ void UndoHelper::fixTransitions(Mlt::Playlist playlist, int clipIndex, Mlt::Prod if (transition.is_valid()) { QScopedPointer transitionClip(transition.track(transitionIndex)); if (transitionClip->is_valid() - && transitionClip->parent().get_service() != clip.parent().get_service()) { - UNDOLOG << "Fixing transition at clip index" << currentIndex << "transition index" << - transitionIndex; - transitionClip.reset(clip.cut(transitionClip->get_in(), transitionClip->get_out())); + && transitionClip->parent().get_service() != clip.parent().get_service()) { + UNDOLOG << "Fixing transition at clip index" << currentIndex + << "transition index" << transitionIndex; + transitionClip.reset( + clip.cut(transitionClip->get_in(), transitionClip->get_out())); transition.set_track(*transitionClip.data(), transitionIndex); } } diff --git a/src/commands/undohelper.h b/src/commands/undohelper.h index fe61c99607..0c5240af90 100644 --- a/src/commands/undohelper.h +++ b/src/commands/undohelper.h @@ -19,30 +19,24 @@ #define UNDOHELPER_H #include "models/multitrackmodel.h" + #include -#include -#include #include +#include #include +#include class UndoHelper { public: - enum OptimizationHints { - NoHints, - SkipXML, - RestoreTracks - }; + enum OptimizationHints { NoHints, SkipXML, RestoreTracks }; UndoHelper(MultitrackModel &model); void recordBeforeState(); void recordAfterState(); void undoChanges(); void setHints(OptimizationHints hints); - QSet affectedTracks() const - { - return m_affectedTracks; - } + QSet affectedTracks() const { return m_affectedTracks; } private: void debugPrintState(const QString &title); @@ -57,7 +51,8 @@ class UndoHelper Removed = 0x8 }; - struct Info { + struct Info + { int oldTrackIndex; int oldClipIndex; int newTrackIndex; diff --git a/src/controllers/filtercontroller.cpp b/src/controllers/filtercontroller.cpp index 8765a7d1e6..bff7f8c01e 100644 --- a/src/controllers/filtercontroller.cpp +++ b/src/controllers/filtercontroller.cpp @@ -15,38 +15,50 @@ * along with this program. If not, see . */ -#include "shotcut_mlt_properties.h" #include "filtercontroller.h" -#include -#include -#include -#include -#include + +#include "Logger.h" #include "mltcontroller.h" -#include "settings.h" +#include "qmltypes/qmlapplication.h" +#include "qmltypes/qmlfilter.h" #include "qmltypes/qmlmetadata.h" #include "qmltypes/qmlutilities.h" -#include "qmltypes/qmlfilter.h" -#include "qmltypes/qmlapplication.h" +#include "settings.h" +#include "shotcut_mlt_properties.h" #include +#include +#include +#include +#include -FilterController::FilterController(QObject *parent) : QObject(parent), - m_metadataModel(this), - m_attachedModel(this), - m_currentFilterIndex(QmlFilter::NoCurrentFilter) +FilterController::FilterController(QObject *parent) + : QObject(parent) + , m_metadataModel(this) + , m_attachedModel(this) + , m_currentFilterIndex(QmlFilter::NoCurrentFilter) { startTimer(0); connect(&m_attachedModel, SIGNAL(changed()), this, SLOT(handleAttachedModelChange())); - connect(&m_attachedModel, SIGNAL(modelAboutToBeReset()), this, + connect(&m_attachedModel, + SIGNAL(modelAboutToBeReset()), + this, SLOT(handleAttachedModelAboutToReset())); - connect(&m_attachedModel, SIGNAL(rowsAboutToBeRemoved(const QModelIndex &, int, int)), this, + connect(&m_attachedModel, + SIGNAL(rowsAboutToBeRemoved(const QModelIndex &, int, int)), + this, SLOT(handleAttachedRowsAboutToBeRemoved(const QModelIndex &, int, int))); - connect(&m_attachedModel, SIGNAL(rowsRemoved(const QModelIndex &, int, int)), this, + connect(&m_attachedModel, + SIGNAL(rowsRemoved(const QModelIndex &, int, int)), + this, SLOT(handleAttachedRowsRemoved(const QModelIndex &, int, int))); - connect(&m_attachedModel, SIGNAL(rowsInserted(const QModelIndex &, int, int)), this, + connect(&m_attachedModel, + SIGNAL(rowsInserted(const QModelIndex &, int, int)), + this, SLOT(handleAttachedRowsInserted(const QModelIndex &, int, int))); - connect(&m_attachedModel, SIGNAL(duplicateAddFailed(int)), this, + connect(&m_attachedModel, + SIGNAL(duplicateAddFailed(int)), + this, SLOT(handleAttachDuplicateFailed(int))); } @@ -57,7 +69,8 @@ void FilterController::loadFilterMetadata() QScopedPointer mltProducers(MLT.repository()->producers()); QDir dir = QmlUtilities::qmlDir(); dir.cd("filters"); - foreach (QString dirName, dir.entryList(QDir::AllDirs | QDir::NoDotAndDotDot | QDir::Executable)) { + foreach (QString dirName, + dir.entryList(QDir::AllDirs | QDir::NoDotAndDotDot | QDir::Executable)) { QDir subdir = dir; subdir.cd(dirName); subdir.setFilter(QDir::Files | QDir::NoDotAndDotDot | QDir::Readable); @@ -67,8 +80,9 @@ void FilterController::loadFilterMetadata() QQmlComponent component(QmlUtilities::sharedEngine(), subdir.absoluteFilePath(fileName)); QmlMetadata *meta = qobject_cast(component.create()); if (meta) { - QScopedPointer mltMetadata(MLT.repository()->metadata(mlt_service_filter_type, - meta->mlt_service().toLatin1().constData())); + QScopedPointer mltMetadata( + MLT.repository()->metadata(mlt_service_filter_type, + meta->mlt_service().toLatin1().constData())); QString version; if (mltMetadata && mltMetadata->is_valid() && mltMetadata->get("version")) { version = QString::fromLatin1(mltMetadata->get("version")); @@ -78,9 +92,9 @@ void FilterController::loadFilterMetadata() // Check if mlt_service is available. if (mltFilters->get_data(meta->mlt_service().toLatin1().constData()) && - // Check if MLT glaxnimate producer is available if needed - ("maskGlaxnimate" != meta->objectName() || mltProducers->get_data("glaxnimate")) && - (version.isEmpty() || meta->isMltVersion(version))) { + // Check if MLT glaxnimate producer is available if needed + ("maskGlaxnimate" != meta->objectName() || mltProducers->get_data("glaxnimate")) + && (version.isEmpty() || meta->isMltVersion(version))) { LOG_DEBUG() << "added filter" << meta->name(); meta->loadSettings(); meta->setPath(subdir); @@ -184,10 +198,12 @@ void FilterController::onUndoOrRedo(Mlt::Service &service) { MLT.refreshConsumer(); if (m_currentFilter && m_mltService.is_valid() - && service.get_service() == m_mltService.get_service()) { + && service.get_service() == m_mltService.get_service()) { emit undoOrRedo(); - QMetaObject::invokeMethod(this, "setCurrentFilter", Qt::QueuedConnection, Q_ARG(int, - m_currentFilterIndex)); + QMetaObject::invokeMethod(this, + "setCurrentFilter", + Qt::QueuedConnection, + Q_ARG(int, m_currentFilterIndex)); } } @@ -243,7 +259,8 @@ void FilterController::setCurrentFilter(int attachedIndex) if (meta) { emit currentFilterChanged(nullptr, nullptr, QmlFilter::NoCurrentFilter); m_mltService = m_attachedModel.getService(m_currentFilterIndex); - if (!m_mltService.is_valid()) return; + if (!m_mltService.is_valid()) + return; filter = new QmlFilter(m_mltService, meta); filter->setIsNew(m_mltService.get_int(kNewFilterProperty)); m_mltService.clear(kNewFilterProperty); @@ -281,16 +298,16 @@ void FilterController::onFadeOutChanged() void FilterController::onServiceInChanged(int delta, Mlt::Service *service) { - if (delta && m_currentFilter && (!service - || m_currentFilter->service().get_service() == service->get_service())) { + if (delta && m_currentFilter + && (!service || m_currentFilter->service().get_service() == service->get_service())) { emit m_currentFilter->inChanged(delta); } } void FilterController::onServiceOutChanged(int delta, Mlt::Service *service) { - if (delta && m_currentFilter && (!service - || m_currentFilter->service().get_service() == service->get_service())) { + if (delta && m_currentFilter + && (!service || m_currentFilter->service().get_service() == service->get_service())) { emit m_currentFilter->outChanged(delta); } } @@ -351,7 +368,8 @@ void FilterController::addMetadata(QmlMetadata *meta) m_metadataModel.add(meta); } -void FilterController::handleAttachedRowsAboutToBeRemoved(const QModelIndex &parent, int first, +void FilterController::handleAttachedRowsAboutToBeRemoved(const QModelIndex &parent, + int first, int last) { auto filter = m_attachedModel.getService(first); @@ -360,12 +378,13 @@ void FilterController::handleAttachedRowsAboutToBeRemoved(const QModelIndex &par void FilterController::addOrEditFilter(Mlt::Filter *filter, const QStringList &key_properties) { - int rows = m_attachedModel.rowCount(); + int rows = m_attachedModel.rowCount(); int serviceIndex = -1; for (int i = 0; i < rows; i++) { QScopedPointer service(m_attachedModel.getService(i)); bool servicesMatch = true; - if (metadataForService(service.data())->uniqueId() != metadataForService(filter)->uniqueId()) { + if (metadataForService(service.data())->uniqueId() + != metadataForService(filter)->uniqueId()) { continue; } for (auto &k : key_properties) { diff --git a/src/controllers/filtercontroller.h b/src/controllers/filtercontroller.h index 4086bfb5e4..9698fecab2 100644 --- a/src/controllers/filtercontroller.h +++ b/src/controllers/filtercontroller.h @@ -18,17 +18,17 @@ #ifndef FILTERCONTROLLER_H #define FILTERCONTROLLER_H -#include -#include -#include +#include "models/attachedfiltersmodel.h" #include "models/metadatamodel.h" #include "models/motiontrackermodel.h" -#include "models/attachedfiltersmodel.h" -#include "qmltypes/qmlmetadata.h" #include "qmltypes/qmlfilter.h" +#include "qmltypes/qmlmetadata.h" -class QTimerEvent; +#include +#include +#include +class QTimerEvent; class FilterController : public QObject { @@ -37,24 +37,15 @@ class FilterController : public QObject public: explicit FilterController(QObject *parent = 0); MetadataModel *metadataModel(); - MotionTrackerModel *motionTrackerModel() - { - return &m_motionTrackerModel; - } + MotionTrackerModel *motionTrackerModel() { return &m_motionTrackerModel; } AttachedFiltersModel *attachedModel(); QmlMetadata *metadata(const QString &id); QmlMetadata *metadataForService(Mlt::Service *service); - QmlFilter *currentFilter() const - { - return m_currentFilter.data(); - } + QmlFilter *currentFilter() const { return m_currentFilter.data(); } bool isOutputTrackSelected() const; void onUndoOrRedo(Mlt::Service &service); - int currentIndex() const - { - return m_currentFilterIndex; - } + int currentIndex() const { return m_currentFilterIndex; } void addOrEditFilter(Mlt::Filter *filter, const QStringList &key_properties); protected: diff --git a/src/controllers/scopecontroller.cpp b/src/controllers/scopecontroller.cpp index 4abd582867..8c73fac33e 100644 --- a/src/controllers/scopecontroller.cpp +++ b/src/controllers/scopecontroller.cpp @@ -15,6 +15,9 @@ * along with this program. If not, see . */ #include "scopecontroller.h" + +#include "Logger.h" +#include "docks/scopedock.h" #include "widgets/scopes/audioloudnessscopewidget.h" #include "widgets/scopes/audiopeakmeterscopewidget.h" #include "widgets/scopes/audiospectrumscopewidget.h" @@ -27,8 +30,7 @@ #include "widgets/scopes/videovectorscopewidget.h" #include "widgets/scopes/videowaveformscopewidget.h" #include "widgets/scopes/videozoomscopewidget.h" -#include "docks/scopedock.h" -#include + #include #include @@ -52,8 +54,8 @@ ScopeController::ScopeController(QMainWindow *mainWindow, QMenu *menu) LOG_DEBUG() << "end"; } -template void ScopeController::createScopeDock(QMainWindow *mainWindow, - QMenu *menu) +template +void ScopeController::createScopeDock(QMainWindow *mainWindow, QMenu *menu) { ScopeWidget *scopeWidget = new ScopeTYPE(); ScopeDock *scopeDock = new ScopeDock(this, scopeWidget); @@ -61,4 +63,3 @@ template void ScopeController::createScopeDock(QMainWindow * menu->addAction(scopeDock->toggleViewAction()); mainWindow->addDockWidget(Qt::RightDockWidgetArea, scopeDock); } - diff --git a/src/controllers/scopecontroller.h b/src/controllers/scopecontroller.h index b1e3b9c5bb..afc901866b 100644 --- a/src/controllers/scopecontroller.h +++ b/src/controllers/scopecontroller.h @@ -19,9 +19,10 @@ #ifndef SCOPECONTROLLER_H #define SCOPECONTROLLER_H +#include "sharedframe.h" + #include #include -#include "sharedframe.h" class QMainWindow; class QMenu; @@ -38,8 +39,8 @@ class ScopeController Q_DECL_FINAL : public QObject void newFrame(const SharedFrame &frame); private: - template void createScopeDock(QMainWindow *mainWindow, QMenu *menu); - + template + void createScopeDock(QMainWindow *mainWindow, QMenu *menu); }; #endif // SCOPECONTROLLER_H diff --git a/src/database.cpp b/src/database.cpp index a09426cf58..83a37a1f5b 100644 --- a/src/database.cpp +++ b/src/database.cpp @@ -16,20 +16,23 @@ */ #include "database.h" -#include "settings.h" + +#include "Logger.h" #include "dialogs/longuitask.h" -#include +#include "settings.h" + +#include #include #include -#include -#include +#include static QMutex g_mutex; static Database *instance = nullptr; static const int kMaxThumbnailCount = 5000; static const int kDeleteThumbnailsTimeoutMs = 60000; -Database::Database(QObject *parent) : QObject(parent) +Database::Database(QObject *parent) + : QObject(parent) { m_deleteTimer.setInterval(kDeleteThumbnailsTimeoutMs); connect(&m_deleteTimer, SIGNAL(timeout()), this, SLOT(deleteOldThumbnails())); @@ -49,7 +52,7 @@ Database &Database::singleton(QObject *parent) static QString toFileName(const QString &s) { QString result = s; - return result.replace(':', '-') + + ".png"; + return result.replace(':', '-') + +".png"; } QDir Database::thumbnailsDir() @@ -74,20 +77,24 @@ QDir Database::thumbnailsDir() if (query.exec("SELECT COUNT(*) FROM thumbnails;") && query.next()) { n = query.value(0).toInt(); } - query.exec( - QStringLiteral("SELECT hash, accessed, image FROM thumbnails ORDER BY accessed DESC LIMIT %1").arg( - kMaxThumbnailCount)); + query.exec(QStringLiteral("SELECT hash, accessed, image FROM thumbnails ORDER BY " + "accessed DESC LIMIT %1") + .arg(kMaxThumbnailCount)); for (int i = 0; query.next(); i++) { QString fileName = toFileName(query.value(0).toString()); longTask.reportProgress( - QObject::tr("Please wait for this one-time update to the thumbnail cache..."), i, n); + QObject::tr( + "Please wait for this one-time update to the thumbnail cache..."), + i, + n); if (img.loadFromData(query.value(2).toByteArray(), "PNG")) { img.save(dir.filePath(fileName)); auto accessed = query.value(1).toDateTime(); auto offset = accessed.timeZone().offsetFromUtc(accessed); - struct utimbuf utimes { + struct utimbuf utimes + { static_cast(accessed.toSecsSinceEpoch() + offset), - static_cast(accessed.toSecsSinceEpoch() + offset) + static_cast(accessed.toSecsSinceEpoch() + offset) }; ::utime(dir.filePath(fileName).toUtf8().constData(), &utimes); } @@ -114,7 +121,7 @@ QImage Database::getThumbnail(const QString &hash) void Database::deleteOldThumbnails() { - auto result = QtConcurrent::run([ = ]() { + auto result = QtConcurrent::run([=]() { QDir dir = thumbnailsDir(); auto ls = dir.entryList(QDir::Files | QDir::NoDotAndDotDot | QDir::Readable, QDir::Time); if (ls.size() - kMaxThumbnailCount > 0) diff --git a/src/database.h b/src/database.h index 277f4c523f..fe68fdd0c1 100644 --- a/src/database.h +++ b/src/database.h @@ -18,8 +18,8 @@ #ifndef DATABASE_H #define DATABASE_H -#include #include +#include #include class Database : public QObject diff --git a/src/dataqueue.h b/src/dataqueue.h index 2069daa786..93fe6972f7 100644 --- a/src/dataqueue.h +++ b/src/dataqueue.h @@ -20,8 +20,8 @@ #define DATAQUEUE_H #include -#include #include +#include #include @@ -44,7 +44,7 @@ between objects operating in different thread contexts. */ -template +template class DataQueue { public: @@ -94,7 +94,7 @@ class DataQueue QWaitCondition m_notFullCondition; }; -template +template DataQueue::DataQueue(int maxSize, OverflowMode mode) : m_queue() , m_maxSize(maxSize) @@ -102,15 +102,13 @@ DataQueue::DataQueue(int maxSize, OverflowMode mode) , m_mutex() , m_notEmptyCondition() , m_notFullCondition() -{ -} +{} -template +template DataQueue::~DataQueue() -{ -} +{} -template +template void DataQueue::push(const T &item) { m_mutex.lock(); @@ -137,7 +135,7 @@ void DataQueue::push(const T &item) m_mutex.unlock(); } -template +template T DataQueue::pop() { T retVal; @@ -154,7 +152,7 @@ T DataQueue::pop() return retVal; } -template +template int DataQueue::count() const { QMutexLocker locker(&m_mutex); diff --git a/src/dialogs/actionsdialog.cpp b/src/dialogs/actionsdialog.cpp index 26d5a0709e..684eb7ec78 100644 --- a/src/dialogs/actionsdialog.cpp +++ b/src/dialogs/actionsdialog.cpp @@ -19,19 +19,19 @@ #include "widgets/statuslabelwidget.h" +#include #include #include #include +#include #include #include +#include #include #include #include #include #include -#include -#include -#include static const unsigned int editorWidth = 180; @@ -53,18 +53,16 @@ class ShortcutEditor : public QWidget layout->addWidget(seqEdit); QToolButton *applyButton = new QToolButton(); - applyButton->setIcon(QIcon::fromTheme("dialog-ok", - QIcon(":/icons/oxygen/32x32/actions/dialog-ok.png"))); + applyButton->setIcon( + QIcon::fromTheme("dialog-ok", QIcon(":/icons/oxygen/32x32/actions/dialog-ok.png"))); applyButton->setText(tr("Apply")); applyButton->setToolTip(tr("Apply")); - connect(applyButton, &QToolButton::clicked, this, [this]() { - emit applied(); - }); + connect(applyButton, &QToolButton::clicked, this, [this]() { emit applied(); }); layout->addWidget(applyButton); QToolButton *defaultButton = new QToolButton(); - defaultButton->setIcon(QIcon::fromTheme("edit-undo", - QIcon(":/icons/oxygen/32x32/actions/edit-undo.png"))); + defaultButton->setIcon( + QIcon::fromTheme("edit-undo", QIcon(":/icons/oxygen/32x32/actions/edit-undo.png"))); defaultButton->setText(tr("Set to default")); defaultButton->setToolTip(tr("Set to default")); connect(defaultButton, &QToolButton::clicked, this, [&]() { @@ -73,13 +71,11 @@ class ShortcutEditor : public QWidget layout->addWidget(defaultButton); QToolButton *clearButton = new QToolButton(); - clearButton->setIcon(QIcon::fromTheme("edit-clear", - QIcon(":/icons/oxygen/32x32/actions/edit-clear.png"))); + clearButton->setIcon( + QIcon::fromTheme("edit-clear", QIcon(":/icons/oxygen/32x32/actions/edit-clear.png"))); clearButton->setText(tr("Clear shortcut")); clearButton->setToolTip(tr("Clear shortcut")); - connect(clearButton, &QToolButton::clicked, this, [&]() { - seqEdit->clear(); - }); + connect(clearButton, &QToolButton::clicked, this, [&]() { seqEdit->clear(); }); layout->addWidget(clearButton); setLayout(layout); @@ -101,15 +97,15 @@ class ShortcutItemDelegate : public QStyledItemDelegate public: ShortcutItemDelegate(QObject *parent = nullptr) : QStyledItemDelegate(parent) - { - } + {} - QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, + QWidget *createEditor(QWidget *parent, + const QStyleOptionViewItem &option, const QModelIndex &index) const { - if (index.column() == ActionsModel::COLUMN_SEQUENCE1 || - (index.column() == ActionsModel::COLUMN_SEQUENCE2 - && !index.data(ActionsModel::HardKeyRole).isValid() )) { + if (index.column() == ActionsModel::COLUMN_SEQUENCE1 + || (index.column() == ActionsModel::COLUMN_SEQUENCE2 + && !index.data(ActionsModel::HardKeyRole).isValid())) { // Hard key shortcuts are in column 2 and are not editable. m_currentEditor = new ShortcutEditor(parent); connect(m_currentEditor, &ShortcutEditor::applied, this, [this]() { @@ -142,10 +138,7 @@ class ShortcutItemDelegate : public QStyledItemDelegate model->setData(index, newSeq); } - ShortcutEditor *currentEditor() const - { - return m_currentEditor; - } + ShortcutEditor *currentEditor() const { return m_currentEditor; } private: mutable ShortcutEditor *m_currentEditor = nullptr; @@ -155,15 +148,17 @@ class KeyPressFilter : public QObject { Q_OBJECT public: - KeyPressFilter(QObject *parent = 0) : QObject(parent) {} + KeyPressFilter(QObject *parent = 0) + : QObject(parent) + {} protected: bool eventFilter(QObject *obj, QEvent *event) override { if (event->type() == QEvent::KeyPress) { auto keyEvent = static_cast(event); - if (!keyEvent->modifiers() && (keyEvent->key() == Qt::Key_Return - || keyEvent->key() == Qt::Key_Enter)) { + if (!keyEvent->modifiers() + && (keyEvent->key() == Qt::Key_Return || keyEvent->key() == Qt::Key_Enter)) { auto window = static_cast(parent()); window->close(); } @@ -176,15 +171,18 @@ class PrivateTreeView : public QTreeView { Q_OBJECT public: - PrivateTreeView(QWidget *parent = nullptr) : QTreeView(parent) {} + PrivateTreeView(QWidget *parent = nullptr) + : QTreeView(parent) + {} - virtual bool edit(const QModelIndex &index, QAbstractItemView::EditTrigger trigger, + virtual bool edit(const QModelIndex &index, + QAbstractItemView::EditTrigger trigger, QEvent *event) override { bool editInProgress = QTreeView::edit(index, trigger, event); - if (editInProgress && trigger == QAbstractItemView::AllEditTriggers && - (index.column() == ActionsModel::COLUMN_SEQUENCE1 - || index.column() == ActionsModel::COLUMN_SEQUENCE2)) { + if (editInProgress && trigger == QAbstractItemView::AllEditTriggers + && (index.column() == ActionsModel::COLUMN_SEQUENCE1 + || index.column() == ActionsModel::COLUMN_SEQUENCE2)) { if (state() != QAbstractItemView::EditingState) emit editRejected(); } @@ -196,7 +194,7 @@ class PrivateTreeView : public QTreeView { if (event->key() == Qt::Key_Return || event->key() == Qt::Key_Enter) { emit activated(currentIndex()); - } else if (event->key() == Qt::Key_F2) { + } else if (event->key() == Qt::Key_F2) { edit(currentIndex(), QAbstractItemView::EditKeyPressed, event); } else { QAbstractItemView::keyPressEvent(event); @@ -212,7 +210,9 @@ class SearchKeyPressFilter : public QObject { Q_OBJECT public: - SearchKeyPressFilter(QObject *parent = 0) : QObject(parent) {} + SearchKeyPressFilter(QObject *parent = 0) + : QObject(parent) + {} protected: bool eventFilter(QObject *obj, QEvent *event) override @@ -229,7 +229,6 @@ class SearchKeyPressFilter : public QObject } }; - // Include this so that ShortcutItemDelegate can be declared in the source file. #include "actionsdialog.moc" @@ -237,7 +236,7 @@ ActionsDialog::ActionsDialog(QWidget *parent) : QDialog(parent) { setWindowTitle(tr("Actions and Shortcuts")); - setSizeGripEnabled(true) ; + setSizeGripEnabled(true); QVBoxLayout *vlayout = new QVBoxLayout(); @@ -246,7 +245,7 @@ ActionsDialog::ActionsDialog(QWidget *parent) m_searchField = new QLineEdit(this); m_searchField->setPlaceholderText(tr("search")); m_searchField->installEventFilter(new SearchKeyPressFilter(this)); - connect(m_searchField, &QLineEdit::textChanged, this, [&](const QString & text) { + connect(m_searchField, &QLineEdit::textChanged, this, [&](const QString &text) { if (m_proxyModel) { m_proxyModel->setFilterCaseSensitivity(Qt::CaseInsensitive); m_proxyModel->setFilterFixedString(text); @@ -255,8 +254,8 @@ ActionsDialog::ActionsDialog(QWidget *parent) connect(m_searchField, &QLineEdit::returnPressed, this, &ActionsDialog::focusSearchResults); searchLayout->addWidget(m_searchField); QToolButton *clearSearchButton = new QToolButton(this); - clearSearchButton->setIcon(QIcon::fromTheme("edit-clear", - QIcon(":/icons/oxygen/32x32/actions/edit-clear.png"))); + clearSearchButton->setIcon( + QIcon::fromTheme("edit-clear", QIcon(":/icons/oxygen/32x32/actions/edit-clear.png"))); clearSearchButton->setMaximumSize(22, 22); clearSearchButton->setToolTip(tr("Clear search")); clearSearchButton->setAutoRaise(true); @@ -289,26 +288,34 @@ ActionsDialog::ActionsDialog(QWidget *parent) m_table->header()->resizeSection(2, editorWidth); m_table->sortByColumn(ActionsModel::COLUMN_ACTION, Qt::AscendingOrder); m_table->installEventFilter(new KeyPressFilter(this)); - connect(m_table->selectionModel(), &QItemSelectionModel::selectionChanged, - this, [&](const QItemSelection & selected, const QItemSelection & deselected) { - m_status->showText(tr("Click on the selected shortcut to show the editor"), 5, nullptr, - QPalette::AlternateBase); - }); + connect(m_table->selectionModel(), + &QItemSelectionModel::selectionChanged, + this, + [&](const QItemSelection &selected, const QItemSelection &deselected) { + m_status->showText(tr("Click on the selected shortcut to show the editor"), + 5, + nullptr, + QPalette::AlternateBase); + }); connect(m_table, &PrivateTreeView::editRejected, this, [&]() { - m_status->showText(tr("Reserved shortcuts can not be edited"), 5, nullptr, + m_status->showText(tr("Reserved shortcuts can not be edited"), + 5, + nullptr, QPalette::AlternateBase); }); - connect(m_table->selectionModel(), &QItemSelectionModel::currentChanged, - this, [&](const QModelIndex & current) { - if (current.column() == 0) { - m_table->setCurrentIndex(m_proxyModel->index(current.row(), 1)); - } - }); + connect(m_table->selectionModel(), + &QItemSelectionModel::currentChanged, + this, + [&](const QModelIndex ¤t) { + if (current.column() == 0) { + m_table->setCurrentIndex(m_proxyModel->index(current.row(), 1)); + } + }); vlayout->addWidget(m_table); QHBoxLayout *hlayout = new QHBoxLayout(); m_status = new StatusLabelWidget(); - connect(&m_model, &ActionsModel::editError, this, [&](const QString & message) { + connect(&m_model, &ActionsModel::editError, this, [&](const QString &message) { m_status->showText(message, 5, nullptr); }); hlayout->addWidget(m_status); @@ -322,7 +329,7 @@ ActionsDialog::ActionsDialog(QWidget *parent) vlayout->addLayout(hlayout); setLayout(vlayout); - connect(m_table, &QAbstractItemView::activated, this, [&](const QModelIndex & index) { + connect(m_table, &QAbstractItemView::activated, this, [&](const QModelIndex &index) { auto action = m_model.action(m_proxyModel->mapToSource(index)); if (action && action->isEnabled()) { action->trigger(); @@ -338,8 +345,8 @@ ActionsDialog::ActionsDialog(QWidget *parent) void ActionsDialog::saveCurrentEditor() { - auto delegate = static_cast(m_table->itemDelegateForColumn( - m_table->currentIndex().column())); + auto delegate = static_cast( + m_table->itemDelegateForColumn(m_table->currentIndex().column())); if (delegate) { auto editor = delegate->currentEditor(); if (editor && editor->seqEdit) { diff --git a/src/dialogs/addencodepresetdialog.cpp b/src/dialogs/addencodepresetdialog.cpp index 568ca3df4d..fc67103d78 100644 --- a/src/dialogs/addencodepresetdialog.cpp +++ b/src/dialogs/addencodepresetdialog.cpp @@ -18,9 +18,9 @@ #include "addencodepresetdialog.h" #include "ui_addencodepresetdialog.h" -AddEncodePresetDialog::AddEncodePresetDialog(QWidget *parent) : - QDialog(parent), - ui(new Ui::AddEncodePresetDialog) +AddEncodePresetDialog::AddEncodePresetDialog(QWidget *parent) + : QDialog(parent) + , ui(new Ui::AddEncodePresetDialog) { ui->setupUi(this); } diff --git a/src/dialogs/alignaudiodialog.cpp b/src/dialogs/alignaudiodialog.cpp index b01462b278..a9536f00cd 100644 --- a/src/dialogs/alignaudiodialog.cpp +++ b/src/dialogs/alignaudiodialog.cpp @@ -17,18 +17,18 @@ #include "alignaudiodialog.h" -#include "mainwindow.h" +#include "Logger.h" #include "commands/timelinecommands.h" #include "dialogs/alignmentarray.h" #include "dialogs/longuitask.h" +#include "mainwindow.h" #include "mltcontroller.h" +#include "models/multitrackmodel.h" #include "proxymanager.h" +#include "qmltypes/qmlapplication.h" #include "settings.h" #include "shotcut_mlt_properties.h" #include "util.h" -#include "models/multitrackmodel.h" -#include "qmltypes/qmlapplication.h" -#include #include #include @@ -55,18 +55,14 @@ class AudioReader : public QObject , m_array(array) , m_in(in) , m_out(out) - { - } + {} - void init(int maxLength) - { - m_array->init(maxLength); - } + void init(int maxLength) { m_array->init(maxLength); } void process() { - QScopedPointer producer(new Mlt::Producer(MLT.profile(), "xml-string", - m_producerXml.toUtf8().constData())); + QScopedPointer producer( + new Mlt::Producer(MLT.profile(), "xml-string", m_producerXml.toUtf8().constData())); if (m_in >= 0) { producer->set_in_and_out(m_in, m_out); } @@ -79,8 +75,11 @@ class AudioReader : public QObject mlt_audio_format format = mlt_audio_s16; std::unique_ptr frame(producer->get_frame(i)); mlt_position position = mlt_frame_get_position(frame->get_frame()); - int samples = mlt_audio_calculate_frame_samples(float(producer->get_fps()), frequency, position); - int16_t *data = static_cast(frame->get_audio(format, frequency, channels, samples)); + int samples = mlt_audio_calculate_frame_samples(float(producer->get_fps()), + frequency, + position); + int16_t *data = static_cast( + frame->get_audio(format, frequency, channels, samples)); double sampleTotal = 0; // Add all values from the frame for (int k = 0; k < samples; ++k) { @@ -120,20 +119,11 @@ class ClipAudioReader : public QObject connect(&m_reader, SIGNAL(progressUpdate(int)), this, SLOT(onReaderProgressUpdate(int))); } - void init(int maxLength) - { - m_reader.init(maxLength); - } + void init(int maxLength) { m_reader.init(maxLength); } - void start() - { - m_future = QtConcurrent::run(&ClipAudioReader::process, this); - } + void start() { m_future = QtConcurrent::run(&ClipAudioReader::process, this); } - bool isFinished() - { - return m_future.isFinished(); - } + bool isFinished() { return m_future.isFinished(); } void process() { @@ -144,7 +134,10 @@ class ClipAudioReader : public QObject double quality; double speedRange = Settings.audioReferenceSpeedRange(); if (speedRange != 0.0) { - quality = m_referenceArray.calculateOffsetAndSpeed(m_clipArray, &speed, &offset, speedRange); + quality = m_referenceArray.calculateOffsetAndSpeed(m_clipArray, + &speed, + &offset, + speedRange); } else { quality = m_referenceArray.calculateOffset(m_clipArray, &offset); } @@ -192,15 +185,19 @@ class AlignTableDelegate : public QStyledItemDelegate } case AlignClipsModel::COLUMN_NAME: { int progress = model->getProgress(index.row()); - if (progress > 0 ) { + if (progress > 0) { QStyleOptionProgressBar progressBarOption; progressBarOption.rect = option.rect; progressBarOption.minimum = 0; progressBarOption.maximum = 100; progressBarOption.progress = progress; - QApplication::style()->drawControl(QStyle::CE_ProgressBar, &progressBarOption, painter); + QApplication::style()->drawControl(QStyle::CE_ProgressBar, + &progressBarOption, + painter); } - painter->drawText(option.rect, Qt::AlignLeft | Qt::AlignVCenter, index.data().toString() ); + painter->drawText(option.rect, + Qt::AlignLeft | Qt::AlignVCenter, + index.data().toString()); break; } case AlignClipsModel::COLUMN_OFFSET: @@ -217,8 +214,10 @@ class AlignTableDelegate : public QStyledItemDelegate // Include this so that AlignTableDelegate can be declared in the source file. #include "alignaudiodialog.moc" -AlignAudioDialog::AlignAudioDialog(QString title, MultitrackModel *model, - const QVector &uuids, QWidget *parent) +AlignAudioDialog::AlignAudioDialog(QString title, + MultitrackModel *model, + const QVector &uuids, + QWidget *parent) : QDialog(parent) , m_model(model) , m_uuids(uuids) @@ -242,7 +241,9 @@ AlignAudioDialog::AlignAudioDialog(QString title, MultitrackModel *model, if (defaultTrack < trackCount) { m_trackCombo->setCurrentIndex(defaultTrack); } - if (!connect(m_trackCombo, QOverload::of(&QComboBox::activated), this, + if (!connect(m_trackCombo, + QOverload::of(&QComboBox::activated), + this, &AlignAudioDialog::rebuildClipList)) connect(m_trackCombo, SIGNAL(activated(const QString &)), SLOT(rebuildClipList())); glayout->addWidget(m_trackCombo, row++, 1, Qt::AlignLeft); @@ -251,9 +252,9 @@ AlignAudioDialog::AlignAudioDialog(QString title, MultitrackModel *model, m_speedCombo = new QComboBox(); m_speedCombo->setToolTip("Larger speed adjustment ranges take longer to process."); m_speedCombo->addItem(tr("None") + QStringLiteral(" (%L1%)").arg(0), QVariant(0)); - m_speedCombo->addItem(tr("Narrow") + QStringLiteral(" (%L1%)").arg((double)0.1, 0, 'g', 2), + m_speedCombo->addItem(tr("Narrow") + QStringLiteral(" (%L1%)").arg((double) 0.1, 0, 'g', 2), QVariant(0.001)); - m_speedCombo->addItem(tr("Normal") + QStringLiteral(" (%L1%)").arg((double)0.5, 0, 'g', 2), + m_speedCombo->addItem(tr("Normal") + QStringLiteral(" (%L1%)").arg((double) 0.5, 0, 'g', 2), QVariant(0.005)); m_speedCombo->addItem(tr("Wide") + QStringLiteral(" (%L1%)").arg(1), QVariant(0.01)); m_speedCombo->addItem(tr("Very wide") + QStringLiteral(" (%L1%)").arg(5), QVariant(0.05)); @@ -264,7 +265,9 @@ AlignAudioDialog::AlignAudioDialog(QString title, MultitrackModel *model, break; } } - if (!connect(m_speedCombo, QOverload::of(&QComboBox::activated), this, + if (!connect(m_speedCombo, + QOverload::of(&QComboBox::activated), + this, &AlignAudioDialog::rebuildClipList)) connect(m_speedCombo, SIGNAL(activated(const QString &)), SLOT(rebuildClipList())); glayout->addWidget(m_speedCombo, row++, 1, Qt::AlignLeft); @@ -287,7 +290,8 @@ AlignAudioDialog::AlignAudioDialog(QString title, MultitrackModel *model, m_table->header()->setSectionResizeMode(AlignClipsModel::COLUMN_NAME, QHeaderView::Stretch); m_table->header()->setSectionResizeMode(AlignClipsModel::COLUMN_OFFSET, QHeaderView::Fixed); m_table->setColumnWidth(AlignClipsModel::COLUMN_OFFSET, - fontMetrics().horizontalAdvance("-00:00:00:00") * devicePixelRatioF() + 8); + fontMetrics().horizontalAdvance("-00:00:00:00") * devicePixelRatioF() + + 8); m_table->header()->setSectionResizeMode(AlignClipsModel::COLUMN_SPEED, QHeaderView::ResizeToContents); glayout->addWidget(m_table, row++, 0, 1, 2); @@ -306,7 +310,7 @@ AlignAudioDialog::AlignAudioDialog(QString title, MultitrackModel *model, QDialogButtonBox::AcceptRole); connect(m_processAndApplyButton, SIGNAL(pressed()), this, SLOT(processAndApply())); - this->setLayout (glayout); + this->setLayout(glayout); this->setModal(true); rebuildClipList(); @@ -348,8 +352,10 @@ void AlignAudioDialog::rebuildClipList() if (!service.startsWith("avformat") && !shotcutProducer.startsWith("avformat")) error = tr("This item can not be aligned."); } - m_alignClipsModel.addClip(clipName, AlignClipsModel::INVALID_OFFSET, - AlignClipsModel::INVALID_OFFSET, error); + m_alignClipsModel.addClip(clipName, + AlignClipsModel::INVALID_OFFSET, + AlignClipsModel::INVALID_OFFSET, + error); } } } @@ -383,11 +389,19 @@ void AlignAudioDialog::process() m_clipReaders.append(nullptr); } else { QString xml = MLT.XML(info->cut); - ClipAudioReader *clipReader = new ClipAudioReader(xml, trackArray, m_clipReaders.size(), - info->frame_in, info->frame_out); - connect(clipReader, SIGNAL(progressUpdate(int, int)), this, SLOT(updateClipProgress(int, int))); - connect(clipReader, SIGNAL(finished(int, int, double, double)), this, SLOT(clipFinished(int, int, - double, double))); + ClipAudioReader *clipReader = new ClipAudioReader(xml, + trackArray, + m_clipReaders.size(), + info->frame_in, + info->frame_out); + connect(clipReader, + SIGNAL(progressUpdate(int, int)), + this, + SLOT(updateClipProgress(int, int))); + connect(clipReader, + SIGNAL(finished(int, int, double, double)), + this, + SLOT(clipFinished(int, int, double, double))); m_clipReaders.append(clipReader); maxLength = qMax(maxLength, info->frame_count); validClip = true; @@ -402,12 +416,14 @@ void AlignAudioDialog::process() trackReader.init(maxLength); for (const auto &clipReader : m_clipReaders) { - if (clipReader) clipReader->init(maxLength); + if (clipReader) + clipReader->init(maxLength); } trackReader.process(); for (const auto &clipReader : m_clipReaders) { - if (clipReader) clipReader->start(); + if (clipReader) + clipReader->start(); } for (const auto &clipReader : m_clipReaders) { @@ -478,7 +494,8 @@ void AlignAudioDialog::updateClipProgress(int index, int percent) void AlignAudioDialog::clipFinished(int index, int offset, double speed, double quality) { QString error; - LOG_INFO() << "Clip" << index << "Offset:" << offset << "Speed:" << speed << "Quality:" << quality; + LOG_INFO() << "Clip" << index << "Offset:" << offset << "Speed:" << speed + << "Quality:" << quality; if (quality < 0.01) { error = tr("Alignment not found."); offset = AlignClipsModel::INVALID_OFFSET; diff --git a/src/dialogs/alignaudiodialog.h b/src/dialogs/alignaudiodialog.h index fa2eaade6d..e78c623d5d 100644 --- a/src/dialogs/alignaudiodialog.h +++ b/src/dialogs/alignaudiodialog.h @@ -39,7 +39,9 @@ class AlignAudioDialog : public QDialog { Q_OBJECT public: - explicit AlignAudioDialog(QString title, MultitrackModel *model, const QVector &uuids, + explicit AlignAudioDialog(QString title, + MultitrackModel *model, + const QVector &uuids, QWidget *parent = 0); virtual ~AlignAudioDialog(); diff --git a/src/dialogs/alignmentarray.cpp b/src/dialogs/alignmentarray.cpp index d45944d3e0..25d1acef7d 100644 --- a/src/dialogs/alignmentarray.cpp +++ b/src/dialogs/alignmentarray.cpp @@ -23,8 +23,8 @@ #include #include -#include #include +#include #include #include @@ -36,8 +36,7 @@ AlignmentArray::AlignmentArray() , m_backwardBuf(nullptr) , m_autocorrelationMax(std::numeric_limits::min()) , m_isTransformed(false) -{ -} +{} AlignmentArray::AlignmentArray(size_t minimum_size) : AlignmentArray() @@ -84,9 +83,9 @@ double AlignmentArray::calculateOffset(AlignmentArray &from, int *offset) // Create a destination for the correlation values s_fftwPlanningMutex.lock(); fftw_complex *buf = fftw_alloc_complex(m_actualComplexSize); - std::complex *correlationBuf = reinterpret_cast*>(buf); - fftw_plan correlationPlan = fftw_plan_dft_1d(m_actualComplexSize, buf, buf, FFTW_BACKWARD, - FFTW_ESTIMATE); + std::complex *correlationBuf = reinterpret_cast *>(buf); + fftw_plan correlationPlan + = fftw_plan_dft_1d(m_actualComplexSize, buf, buf, FFTW_BACKWARD, FFTW_ESTIMATE); std::fill(correlationBuf, correlationBuf + m_actualComplexSize, std::complex(0)); s_fftwPlanningMutex.unlock(); @@ -111,8 +110,8 @@ double AlignmentArray::calculateOffset(AlignmentArray &from, int *offset) } } - if ( 2 * *offset > (int)m_actualComplexSize ) { - *offset -= ((int)m_actualComplexSize); + if (2 * *offset > (int) m_actualComplexSize) { + *offset -= ((int) m_actualComplexSize); } s_fftwPlanningMutex.lock(); @@ -126,12 +125,14 @@ double AlignmentArray::calculateOffset(AlignmentArray &from, int *offset) return max / correlationCoefficient; } -double AlignmentArray::calculateOffsetAndSpeed(AlignmentArray &from, double *speed, int *offset, +double AlignmentArray::calculateOffsetAndSpeed(AlignmentArray &from, + double *speed, + int *offset, double speedRange) { // The minimum speed step results in one frame of stretch. // Do not try to compensate for more than 1 frame of speed difference. - double minimumSpeedStep = 1.0 / (double)from.m_values.size(); + double minimumSpeedStep = 1.0 / (double) from.m_values.size(); double speedStep = 0.0005; double bestSpeed = 1.0; int bestOffset = 0; @@ -147,7 +148,7 @@ double AlignmentArray::calculateOffsetAndSpeed(AlignmentArray &from, double *spe } // Stretch the original values to simulate a speed compensation double factor = 1.0 / s; - size_t stretchedSize = std::floor((double)from.m_values.size() * factor); + size_t stretchedSize = std::floor((double) from.m_values.size() * factor); std::vector strechedValues(stretchedSize); // Nearest neighbor interpolation for (size_t i = 0; i < stretchedSize; i++) { @@ -181,30 +182,30 @@ void AlignmentArray::transform() fftw_complex *buf = nullptr; // Allocate the forward buffer and plan buf = fftw_alloc_complex(m_actualComplexSize); - m_forwardBuf = reinterpret_cast*>(buf); - m_forwardPlan = fftw_plan_dft_1d(m_actualComplexSize, buf, buf, FFTW_FORWARD, FFTW_ESTIMATE); + m_forwardBuf = reinterpret_cast *>(buf); + m_forwardPlan + = fftw_plan_dft_1d(m_actualComplexSize, buf, buf, FFTW_FORWARD, FFTW_ESTIMATE); // Allocate the backward buffer and plan buf = fftw_alloc_complex(m_actualComplexSize); - m_backwardBuf = reinterpret_cast*>(buf); - m_backwardPlan = fftw_plan_dft_1d(m_actualComplexSize, buf, buf, FFTW_BACKWARD, FFTW_ESTIMATE); + m_backwardBuf = reinterpret_cast *>(buf); + m_backwardPlan + = fftw_plan_dft_1d(m_actualComplexSize, buf, buf, FFTW_BACKWARD, FFTW_ESTIMATE); s_fftwPlanningMutex.unlock(); } std::fill(m_forwardBuf, m_forwardBuf + m_actualComplexSize, std::complex(0)); std::fill(m_backwardBuf, m_backwardBuf + m_actualComplexSize, std::complex(0)); // Calculate the mean and standard deviation to be used to normalize the values. double accum = 0.0; - std::for_each (m_values.begin(), m_values.end(), [&](const double d) { - accum += d; - }); + std::for_each(m_values.begin(), m_values.end(), [&](const double d) { accum += d; }); double mean = accum / m_values.size(); accum = 0; - std::for_each (m_values.begin(), m_values.end(), [&](const double d) { + std::for_each(m_values.begin(), m_values.end(), [&](const double d) { accum += (d - mean) * (d - mean); }); double stddev = sqrt(accum / (m_values.size() - 1)); // Fill the transform array // Normalize the input values: Subtract the mean and divide by the standard deviation. - for ( size_t i = 0; i < m_values.size(); i++ ) { + for (size_t i = 0; i < m_values.size(); i++) { m_forwardBuf[i] = (m_values[i] - mean) / stddev; } // Perform the forward DFT diff --git a/src/dialogs/alignmentarray.h b/src/dialogs/alignmentarray.h index 197b3eb245..84e841b4b0 100644 --- a/src/dialogs/alignmentarray.h +++ b/src/dialogs/alignmentarray.h @@ -36,7 +36,10 @@ class AlignmentArray void init(size_t minimum_size); void setValues(const std::vector &values); double calculateOffset(AlignmentArray &from, int *offset); - double calculateOffsetAndSpeed(AlignmentArray &from, double *speed, int *offset, double speedRange); + double calculateOffsetAndSpeed(AlignmentArray &from, + double *speed, + int *offset, + double speedRange); private: void transform(); @@ -53,4 +56,3 @@ class AlignmentArray }; #endif - diff --git a/src/dialogs/bitratedialog.cpp b/src/dialogs/bitratedialog.cpp index 4aaca92c2c..06242c090b 100644 --- a/src/dialogs/bitratedialog.cpp +++ b/src/dialogs/bitratedialog.cpp @@ -1,180 +1,186 @@ -/* - * Copyright (c) 2023-2024 Meltytech, LLC - * - * 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 3 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, see . - */ - -#include "bitratedialog.h" -#include "settings.h" -#include "dialogs/saveimagedialog.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -static const auto kSlidingWindowSize = 30; - -BitrateDialog::BitrateDialog(const QString &resource, double fps, const QJsonArray &data, - QWidget *parent) - : QDialog(parent) -{ - setMinimumSize(400, 200); - setModal(true); - setWindowTitle(tr("Bitrate Viewer")); - setSizeGripEnabled(true); - - double time = 0.0; - double maxSize = 0.0; - double firstTime = 0.0; - double keySubtotal = 0.0; - double interSubtotal = 0.0; - double totalKbps = 0.0; - double minKbps = std::numeric_limits().max(); - double maxKbps = 0.0; - int periodCount = 0; - double previousSecond = 0.0; - - QQueue window; - auto barSeries = new QStackedBarSeries; - auto averageLine = new QSplineSeries; - QBarSet *interSet = nullptr; - auto keySet = new QBarSet(fps > 0.0 ? "I" : tr("Audio")); - - barSeries->setBarWidth(1.0); - if (fps > 0.0) { - interSet = new QBarSet("P/B"); - barSeries->append(interSet); - } - barSeries->append(keySet); - averageLine->setName(tr("Average")); - - for (int i = 0; i < data.size(); ++i) { - auto o = data[i].toObject(); - auto pts = o["pts_time"].toString().toDouble(); - auto duration = o["duration_time"].toString().toDouble(); - auto size = o["size"].toString().toDouble() * 8.0 / 1000.0; // Kb - - if (pts > 0.0) - time = pts + qMax(0.0, duration); - if (i == 0) - firstTime = time; - time -= firstTime; - if (o["flags"].toString()[0] == 'K') { - keySubtotal += size; - } else { - interSubtotal += size; - } - totalKbps += size; - - // Every second as the period - if (time >= (previousSecond + 1.0) || (i + 1) == data.size()) { - // For the min, max, and overall average - auto kbps = interSubtotal + keySubtotal; - if (kbps < minKbps) - minKbps = kbps; - if (kbps > maxKbps) - maxKbps = kbps; - - // Add a bar to the graph for each period - int n = qMax(1, int(time - previousSecond)); - for (int j = 0; j < n; ++j) { - if (interSet) - interSet->append(interSubtotal); - keySet->append(keySubtotal); - ++periodCount; - } - - // For the smoothed average - while (window.size() >= kSlidingWindowSize) - window.dequeue(); - window.enqueue(kbps); - double sum = 0.0; - for (auto &v : window) - sum += v; - // subtract 0.5 from the time because the X axis tick marks are centered - // under the bar such that "0s" is actually at 0.5s - averageLine->append(time - 0.5, sum / window.size()); - - // Reset counters - interSubtotal = 0.0; - keySubtotal = 0.0; - previousSecond = std::floor(time); - } - } - - auto chart = new QChart(); - chart->addSeries(barSeries); - chart->addSeries(averageLine); - chart->setTheme(Settings.theme() == "dark" ? QChart::ChartThemeDark : QChart::ChartThemeLight); - averageLine->setColor(Qt::yellow); - chart->setTitle(tr("Bitrates for %1 ~~ Avg. %2 Min. %3 Max. %4 Kb/s").arg(resource) - .arg(qRound(totalKbps / time)).arg(qRound(minKbps)).arg(qRound(maxKbps))); - - auto axisX = new QValueAxis(); - chart->addAxis(axisX, Qt::AlignBottom); - barSeries->attachAxis(axisX); - averageLine->attachAxis(axisX); - axisX->setRange(0.0, time); - axisX->setLabelFormat("%.0f s"); - axisX->setTickType(QValueAxis::TicksDynamic); - axisX->setTickInterval(periodCount > 100 ? 10.0 : 5.0); - - QValueAxis *axisY = new QValueAxis(); - chart->addAxis(axisY, Qt::AlignLeft); - barSeries->attachAxis(axisY); - averageLine->attachAxis(axisY); - axisY->setRange(0.0, maxKbps); - axisY->setLabelFormat("%.0f Kb/s"); - - chart->legend()->setVisible(true); - chart->legend()->setAlignment(Qt::AlignBottom); - - QChartView *chartView = new QChartView(chart); - chartView->setRenderHint(QPainter::Antialiasing); - - setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); - auto layout = new QVBoxLayout(this); - layout->setContentsMargins(0, 0, 8, 8); - layout->setSpacing(8); - auto scrollArea = new QScrollArea(this); - scrollArea->setWidget(chartView); - layout->addWidget(scrollArea); - auto buttons = new QDialogButtonBox(QDialogButtonBox::Save | QDialogButtonBox::Close, this); - buttons->button(QDialogButtonBox::Close)->setDefault(true); - layout->addWidget(buttons); - connect(buttons, &QDialogButtonBox::accepted, this, [ = ] { - QImage image(chartView->size(), QImage::Format_RGB32); - QPainter painter(&image); - painter.setRenderHint(QPainter::Antialiasing); - chartView->render(&painter); - painter.end(); - SaveImageDialog(this, tr("Save Bitrate Graph"), image).exec(); - }); - connect(buttons, &QDialogButtonBox::rejected, this, &QDialog::reject); - chartView->setMinimumWidth(qMax(1010, periodCount * 5)); - chartView->setMinimumHeight(520); - resize(1024, 576); - show(); -} +/* + * Copyright (c) 2023-2024 Meltytech, LLC + * + * 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 3 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, see . + */ + +#include "bitratedialog.h" + +#include "dialogs/saveimagedialog.h" +#include "settings.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static const auto kSlidingWindowSize = 30; + +BitrateDialog::BitrateDialog(const QString &resource, + double fps, + const QJsonArray &data, + QWidget *parent) + : QDialog(parent) +{ + setMinimumSize(400, 200); + setModal(true); + setWindowTitle(tr("Bitrate Viewer")); + setSizeGripEnabled(true); + + double time = 0.0; + double maxSize = 0.0; + double firstTime = 0.0; + double keySubtotal = 0.0; + double interSubtotal = 0.0; + double totalKbps = 0.0; + double minKbps = std::numeric_limits().max(); + double maxKbps = 0.0; + int periodCount = 0; + double previousSecond = 0.0; + + QQueue window; + auto barSeries = new QStackedBarSeries; + auto averageLine = new QSplineSeries; + QBarSet *interSet = nullptr; + auto keySet = new QBarSet(fps > 0.0 ? "I" : tr("Audio")); + + barSeries->setBarWidth(1.0); + if (fps > 0.0) { + interSet = new QBarSet("P/B"); + barSeries->append(interSet); + } + barSeries->append(keySet); + averageLine->setName(tr("Average")); + + for (int i = 0; i < data.size(); ++i) { + auto o = data[i].toObject(); + auto pts = o["pts_time"].toString().toDouble(); + auto duration = o["duration_time"].toString().toDouble(); + auto size = o["size"].toString().toDouble() * 8.0 / 1000.0; // Kb + + if (pts > 0.0) + time = pts + qMax(0.0, duration); + if (i == 0) + firstTime = time; + time -= firstTime; + if (o["flags"].toString()[0] == 'K') { + keySubtotal += size; + } else { + interSubtotal += size; + } + totalKbps += size; + + // Every second as the period + if (time >= (previousSecond + 1.0) || (i + 1) == data.size()) { + // For the min, max, and overall average + auto kbps = interSubtotal + keySubtotal; + if (kbps < minKbps) + minKbps = kbps; + if (kbps > maxKbps) + maxKbps = kbps; + + // Add a bar to the graph for each period + int n = qMax(1, int(time - previousSecond)); + for (int j = 0; j < n; ++j) { + if (interSet) + interSet->append(interSubtotal); + keySet->append(keySubtotal); + ++periodCount; + } + + // For the smoothed average + while (window.size() >= kSlidingWindowSize) + window.dequeue(); + window.enqueue(kbps); + double sum = 0.0; + for (auto &v : window) + sum += v; + // subtract 0.5 from the time because the X axis tick marks are centered + // under the bar such that "0s" is actually at 0.5s + averageLine->append(time - 0.5, sum / window.size()); + + // Reset counters + interSubtotal = 0.0; + keySubtotal = 0.0; + previousSecond = std::floor(time); + } + } + + auto chart = new QChart(); + chart->addSeries(barSeries); + chart->addSeries(averageLine); + chart->setTheme(Settings.theme() == "dark" ? QChart::ChartThemeDark : QChart::ChartThemeLight); + averageLine->setColor(Qt::yellow); + chart->setTitle(tr("Bitrates for %1 ~~ Avg. %2 Min. %3 Max. %4 Kb/s") + .arg(resource) + .arg(qRound(totalKbps / time)) + .arg(qRound(minKbps)) + .arg(qRound(maxKbps))); + + auto axisX = new QValueAxis(); + chart->addAxis(axisX, Qt::AlignBottom); + barSeries->attachAxis(axisX); + averageLine->attachAxis(axisX); + axisX->setRange(0.0, time); + axisX->setLabelFormat("%.0f s"); + axisX->setTickType(QValueAxis::TicksDynamic); + axisX->setTickInterval(periodCount > 100 ? 10.0 : 5.0); + + QValueAxis *axisY = new QValueAxis(); + chart->addAxis(axisY, Qt::AlignLeft); + barSeries->attachAxis(axisY); + averageLine->attachAxis(axisY); + axisY->setRange(0.0, maxKbps); + axisY->setLabelFormat("%.0f Kb/s"); + + chart->legend()->setVisible(true); + chart->legend()->setAlignment(Qt::AlignBottom); + + QChartView *chartView = new QChartView(chart); + chartView->setRenderHint(QPainter::Antialiasing); + + setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); + auto layout = new QVBoxLayout(this); + layout->setContentsMargins(0, 0, 8, 8); + layout->setSpacing(8); + auto scrollArea = new QScrollArea(this); + scrollArea->setWidget(chartView); + layout->addWidget(scrollArea); + auto buttons = new QDialogButtonBox(QDialogButtonBox::Save | QDialogButtonBox::Close, this); + buttons->button(QDialogButtonBox::Close)->setDefault(true); + layout->addWidget(buttons); + connect(buttons, &QDialogButtonBox::accepted, this, [=] { + QImage image(chartView->size(), QImage::Format_RGB32); + QPainter painter(&image); + painter.setRenderHint(QPainter::Antialiasing); + chartView->render(&painter); + painter.end(); + SaveImageDialog(this, tr("Save Bitrate Graph"), image).exec(); + }); + connect(buttons, &QDialogButtonBox::rejected, this, &QDialog::reject); + chartView->setMinimumWidth(qMax(1010, periodCount * 5)); + chartView->setMinimumHeight(520); + resize(1024, 576); + show(); +} diff --git a/src/dialogs/bitratedialog.h b/src/dialogs/bitratedialog.h index dfbffb4e7a..7c8356187d 100644 --- a/src/dialogs/bitratedialog.h +++ b/src/dialogs/bitratedialog.h @@ -1,33 +1,35 @@ -/* - * Copyright (c) 2023 Meltytech, LLC - * - * 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 3 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, see . - */ - -#ifndef BITRATEDIALOG_H -#define BITRATEDIALOG_H - -#include -#include -#include - -class BitrateDialog : public QDialog -{ - Q_OBJECT -public: - explicit BitrateDialog(const QString &resource, double fps, const QJsonArray &data, - QWidget *parent = nullptr); -}; - -#endif // BITRATEDIALOG_H +/* + * Copyright (c) 2023 Meltytech, LLC + * + * 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 3 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, see . + */ + +#ifndef BITRATEDIALOG_H +#define BITRATEDIALOG_H + +#include +#include +#include + +class BitrateDialog : public QDialog +{ + Q_OBJECT +public: + explicit BitrateDialog(const QString &resource, + double fps, + const QJsonArray &data, + QWidget *parent = nullptr); +}; + +#endif // BITRATEDIALOG_H diff --git a/src/dialogs/customprofiledialog.cpp b/src/dialogs/customprofiledialog.cpp index 7ae18022d0..fde165dd56 100644 --- a/src/dialogs/customprofiledialog.cpp +++ b/src/dialogs/customprofiledialog.cpp @@ -17,17 +17,19 @@ #include "customprofiledialog.h" #include "ui_customprofiledialog.h" + #include "mltcontroller.h" #include "settings.h" #include "util.h" -#include + #include +#include #include -CustomProfileDialog::CustomProfileDialog(QWidget *parent) : - QDialog(parent), - ui(new Ui::CustomProfileDialog), - m_fps(0.0) +CustomProfileDialog::CustomProfileDialog(QWidget *parent) + : QDialog(parent) + , ui(new Ui::CustomProfileDialog) + , m_fps(0.0) { ui->setupUi(this); ui->widthSpinner->setValue(MLT.profile().width()); @@ -48,8 +50,8 @@ QString CustomProfileDialog::profileName() const { // Replace characters that are not allowed in Windows file names QString filename = ui->nameEdit->text(); - static QRegularExpression re("[" + QRegularExpression::escape( "\\/:*?\"<>|" ) + "]"); - filename = filename.replace(re, QStringLiteral( "_" )); + static QRegularExpression re("[" + QRegularExpression::escape("\\/:*?\"<>|") + "]"); + filename = filename.replace(re, QStringLiteral("_")); return filename; } @@ -125,13 +127,15 @@ void CustomProfileDialog::on_fpsSpinner_editingFinished() void CustomProfileDialog::on_fpsComboBox_textActivated(const QString &arg1) { - if (arg1.isEmpty()) return; + if (arg1.isEmpty()) + return; ui->fpsSpinner->setValue(arg1.toDouble()); } void CustomProfileDialog::on_resolutionComboBox_textActivated(const QString &arg1) { - if (arg1.isEmpty()) return; + if (arg1.isEmpty()) + return; auto parts = arg1.split(' '); ui->widthSpinner->setValue(parts[0].toInt()); ui->heightSpinner->setValue(parts[2].toInt()); @@ -139,7 +143,8 @@ void CustomProfileDialog::on_resolutionComboBox_textActivated(const QString &arg void CustomProfileDialog::on_aspectRatioComboBox_textActivated(const QString &arg1) { - if (arg1.isEmpty()) return; + if (arg1.isEmpty()) + return; auto parts = arg1.split(' ')[0].split(':'); ui->aspectNumSpinner->setValue(parts[0].toInt()); ui->aspectDenSpinner->setValue(parts[1].toInt()); diff --git a/src/dialogs/durationdialog.cpp b/src/dialogs/durationdialog.cpp index 4fb22caff9..51656b9acb 100644 --- a/src/dialogs/durationdialog.cpp +++ b/src/dialogs/durationdialog.cpp @@ -18,9 +18,9 @@ #include "durationdialog.h" #include "ui_durationdialog.h" -DurationDialog::DurationDialog(QWidget *parent) : - QDialog(parent), - ui(new Ui::DurationDialog) +DurationDialog::DurationDialog(QWidget *parent) + : QDialog(parent) + , ui(new Ui::DurationDialog) { ui->setupUi(this); connect(ui->spinBox, &TimeSpinBox::accepted, this, &QDialog::accept); diff --git a/src/dialogs/editmarkerdialog.cpp b/src/dialogs/editmarkerdialog.cpp index b8406336a5..b9bd7e2801 100644 --- a/src/dialogs/editmarkerdialog.cpp +++ b/src/dialogs/editmarkerdialog.cpp @@ -24,8 +24,8 @@ #include #include -EditMarkerDialog::EditMarkerDialog(QWidget *parent, const QString &text, const QColor &color, - int start, int end, int maxEnd) +EditMarkerDialog::EditMarkerDialog( + QWidget *parent, const QString &text, const QColor &color, int start, int end, int maxEnd) : QDialog(parent) { setWindowTitle(tr("Edit Marker")); diff --git a/src/dialogs/editmarkerdialog.h b/src/dialogs/editmarkerdialog.h index 19b9c82104..765721fd23 100644 --- a/src/dialogs/editmarkerdialog.h +++ b/src/dialogs/editmarkerdialog.h @@ -29,8 +29,8 @@ class EditMarkerDialog : public QDialog Q_OBJECT public: - explicit EditMarkerDialog(QWidget *parent, const QString &text, const QColor &color, int start, - int end, int maxEnd); + explicit EditMarkerDialog( + QWidget *parent, const QString &text, const QColor &color, int start, int end, int maxEnd); QString getText(); QColor getColor(); int getStart(); diff --git a/src/dialogs/filedatedialog.cpp b/src/dialogs/filedatedialog.cpp index 59f181d223..511eaba5c9 100644 --- a/src/dialogs/filedatedialog.cpp +++ b/src/dialogs/filedatedialog.cpp @@ -17,12 +17,12 @@ #include "filedatedialog.h" -#include -#include "shotcut_mlt_properties.h" +#include "Logger.h" #include "mltcontroller.h" -#include "MltProducer.h" #include "proxymanager.h" +#include "shotcut_mlt_properties.h" +#include #include #include #include @@ -46,7 +46,7 @@ FileDateDialog::FileDateDialog(QString title, Mlt::Producer *producer, QWidget * setWindowTitle(tr("%1 File Date").arg(title)); int64_t milliseconds = producer->get_creation_time(); QDateTime creation_time; - if (!milliseconds ) { + if (!milliseconds) { creation_time = QDateTime::currentDateTime(); } else { // Set the date to the current producer date. @@ -72,21 +72,21 @@ FileDateDialog::FileDateDialog(QString title, Mlt::Producer *producer, QWidget * connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept())); connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject())); - this->setLayout (VLayout); + this->setLayout(VLayout); this->setModal(true); } void FileDateDialog::accept() { - m_producer->set_creation_time((int64_t)m_dtEdit->dateTime().toTimeSpec( - Qt::LocalTime).toMSecsSinceEpoch()); + m_producer->set_creation_time( + (int64_t) m_dtEdit->dateTime().toTimeSpec(Qt::LocalTime).toMSecsSinceEpoch()); QDialog::accept(); } void FileDateDialog::dateSelected(int index) { LOG_DEBUG() << index; - if ( index > -1 ) { + if (index > -1) { m_dtEdit->setDateTime(m_dtCombo->itemData(index).toDateTime()); } } @@ -97,7 +97,7 @@ void FileDateDialog::populateDateOptions(Mlt::Producer *producer) // Add current value int64_t milliseconds = producer->get_creation_time(); - if ( milliseconds ) { + if (milliseconds) { dateTime = QDateTime::fromMSecsSinceEpoch(milliseconds); addDateToCombo(m_dtCombo, tr("Current Value"), dateTime); } @@ -123,8 +123,9 @@ void FileDateDialog::populateDateOptions(Mlt::Producer *producer) addDateToCombo(m_dtCombo, tr("Metadata - Creation Time"), dateTime); } // Quicktime create date - dateTime = QDateTime::fromString( - tmpProducer.get("meta.attr.com.apple.quicktime.creationdate.markup"), Qt::ISODateWithMs); + dateTime = QDateTime::fromString(tmpProducer.get( + "meta.attr.com.apple.quicktime.creationdate.markup"), + Qt::ISODateWithMs); if (dateTime.isValid()) { addDateToCombo(m_dtCombo, tr("Metadata - QuickTime date"), dateTime); } diff --git a/src/dialogs/listselectiondialog.cpp b/src/dialogs/listselectiondialog.cpp index 313073ee81..d48bf7fae2 100644 --- a/src/dialogs/listselectiondialog.cpp +++ b/src/dialogs/listselectiondialog.cpp @@ -17,18 +17,20 @@ #include "listselectiondialog.h" #include "ui_listselectiondialog.h" + #include -ListSelectionDialog::ListSelectionDialog(const QStringList &list, QWidget *parent) : - QDialog(parent), - ui(new Ui::ListSelectionDialog) +ListSelectionDialog::ListSelectionDialog(const QStringList &list, QWidget *parent) + : QDialog(parent) + , ui(new Ui::ListSelectionDialog) { ui->setupUi(this); for (auto &text : list) { QListWidgetItem *item = new QListWidgetItem(text, ui->listWidget); item->setFlags(Qt::ItemIsUserCheckable | Qt::ItemIsEnabled | Qt::ItemIsSelectable); item->setCheckState(Qt::Unchecked); - connect(ui->listWidget, SIGNAL(itemActivated(QListWidgetItem *)), + connect(ui->listWidget, + SIGNAL(itemActivated(QListWidgetItem *)), SLOT(onItemActivated(QListWidgetItem *))); } } @@ -45,7 +47,8 @@ void ListSelectionDialog::setColors(const QStringList &list) for (auto &text : list) { QListWidgetItem *item = new QListWidgetItem(text, ui->listWidget); item->setFlags(Qt::ItemIsUserCheckable | Qt::ItemIsEnabled | Qt::ItemIsSelectable); - connect(ui->listWidget, SIGNAL(itemActivated(QListWidgetItem *)), + connect(ui->listWidget, + SIGNAL(itemActivated(QListWidgetItem *)), SLOT(onItemActivated(QListWidgetItem *))); QColor color(text); item->setCheckState(Qt::Checked); diff --git a/src/dialogs/longuitask.cpp b/src/dialogs/longuitask.cpp index fcd6951489..5320ac3018 100644 --- a/src/dialogs/longuitask.cpp +++ b/src/dialogs/longuitask.cpp @@ -16,6 +16,7 @@ */ #include "longuitask.h" + #include "mainwindow.h" static QMutex g_mutex; diff --git a/src/dialogs/longuitask.h b/src/dialogs/longuitask.h index b1fe7cc352..c988fba80b 100644 --- a/src/dialogs/longuitask.h +++ b/src/dialogs/longuitask.h @@ -28,7 +28,7 @@ class LongUiTask : public QProgressDialog explicit LongUiTask(QString title); ~LongUiTask(); - template + template Ret wait(QString text, const QFuture &future) { setLabelText(text); @@ -41,7 +41,7 @@ class LongUiTask : public QProgressDialog return future.result(); } - template + template Ret runAsync(QString text, Func &&f, Args &&...args) { QFuture future = QtConcurrent::run(f, std::forward(args)...); diff --git a/src/dialogs/multifileexportdialog.cpp b/src/dialogs/multifileexportdialog.cpp index 7b4c382cd3..fbc78a25ef 100644 --- a/src/dialogs/multifileexportdialog.cpp +++ b/src/dialogs/multifileexportdialog.cpp @@ -19,18 +19,17 @@ #include "mainwindow.h" #include "proxymanager.h" +#include "qmltypes/qmlapplication.h" #include "shotcut_mlt_properties.h" #include "util.h" -#include "qmltypes/qmlapplication.h" #include - #include #include #include #include -#include #include +#include #include #include #include @@ -44,8 +43,12 @@ enum { NAME_FIELD_HASH, }; -MultiFileExportDialog::MultiFileExportDialog(QString title, Mlt::Playlist *playlist, - const QString &directory, const QString &prefix, const QString &extension, QWidget *parent) +MultiFileExportDialog::MultiFileExportDialog(QString title, + Mlt::Playlist *playlist, + const QString &directory, + const QString &prefix, + const QString &extension, + QWidget *parent) : QDialog(parent) , m_playlist(playlist) { @@ -62,8 +65,8 @@ MultiFileExportDialog::MultiFileExportDialog(QString title, Mlt::Playlist *playl m_dir = new QLineEdit(QDir::toNativeSeparators(directory)); m_dir->setReadOnly(true); QPushButton *browseButton = new QPushButton(this); - browseButton->setIcon(QIcon::fromTheme("document-open", - QIcon(":/icons/oxygen/32x32/actions/document-open.png"))); + browseButton->setIcon( + QIcon::fromTheme("document-open", QIcon(":/icons/oxygen/32x32/actions/document-open.png"))); if (!connect(browseButton, &QAbstractButton::clicked, this, &MultiFileExportDialog::browse)) connect(browseButton, SIGNAL(clicked()), SLOT(browse())); dirHbox->addWidget(m_dir); @@ -79,7 +82,9 @@ MultiFileExportDialog::MultiFileExportDialog(QString title, Mlt::Playlist *playl glayout->addWidget(new QLabel(tr("Field 1")), col, 0, Qt::AlignRight); m_field1 = new QComboBox(); fillCombo(m_field1); - if (!connect(m_field1, QOverload::of(&QComboBox::activated), this, + if (!connect(m_field1, + QOverload::of(&QComboBox::activated), + this, &MultiFileExportDialog::rebuildList)) connect(m_field1, SIGNAL(activated(const QString &)), SLOT(rebuildList())); glayout->addWidget(m_field1, col++, 1, Qt::AlignLeft); @@ -87,7 +92,9 @@ MultiFileExportDialog::MultiFileExportDialog(QString title, Mlt::Playlist *playl glayout->addWidget(new QLabel(tr("Field 2")), col, 0, Qt::AlignRight); m_field2 = new QComboBox(); fillCombo(m_field2); - if (!connect(m_field2, QOverload::of(&QComboBox::activated), this, + if (!connect(m_field2, + QOverload::of(&QComboBox::activated), + this, &MultiFileExportDialog::rebuildList)) connect(m_field2, SIGNAL(activated(const QString &)), SLOT(rebuildList())); glayout->addWidget(m_field2, col++, 1, Qt::AlignLeft); @@ -96,7 +103,9 @@ MultiFileExportDialog::MultiFileExportDialog(QString title, Mlt::Playlist *playl m_field3 = new QComboBox(); fillCombo(m_field3); m_field3->setCurrentIndex(NAME_FIELD_INDEX); - if (!connect(m_field3, QOverload::of(&QComboBox::activated), this, + if (!connect(m_field3, + QOverload::of(&QComboBox::activated), + this, &MultiFileExportDialog::rebuildList)) connect(m_field3, SIGNAL(activated(const QString &)), SLOT(rebuildList())); glayout->addWidget(m_field3, col++, 1, Qt::AlignLeft); @@ -125,9 +134,10 @@ MultiFileExportDialog::MultiFileExportDialog(QString title, Mlt::Playlist *playl connect(m_buttonBox, SIGNAL(rejected()), this, SLOT(reject())); glayout->setColumnMinimumWidth(1, - fontMetrics().horizontalAdvance(m_dir->text()) + browseButton->width()); + fontMetrics().horizontalAdvance(m_dir->text()) + + browseButton->width()); - this->setLayout (glayout); + this->setLayout(glayout); this->setModal(true); rebuildList(); @@ -266,8 +276,11 @@ void MultiFileExportDialog::rebuildList() void MultiFileExportDialog::browse() { - QString directory = QDir::toNativeSeparators(QFileDialog::getExistingDirectory(this, - tr("Export Directory"), m_dir->text(), Util::getFileDialogOptions())); + QString directory = QDir::toNativeSeparators( + QFileDialog::getExistingDirectory(this, + tr("Export Directory"), + m_dir->text(), + Util::getFileDialogOptions())); if (!directory.isEmpty()) { m_dir->setText(directory); rebuildList(); diff --git a/src/dialogs/multifileexportdialog.h b/src/dialogs/multifileexportdialog.h index b84868cd7d..9b21fdcb9f 100644 --- a/src/dialogs/multifileexportdialog.h +++ b/src/dialogs/multifileexportdialog.h @@ -34,8 +34,12 @@ class MultiFileExportDialog : public QDialog { Q_OBJECT public: - explicit MultiFileExportDialog(QString title, Mlt::Playlist *playlist, const QString &directory, - const QString &prefix, const QString &extension, QWidget *parent = 0); + explicit MultiFileExportDialog(QString title, + Mlt::Playlist *playlist, + const QString &directory, + const QString &prefix, + const QString &extension, + QWidget *parent = 0); QStringList getExportFiles(); private slots: diff --git a/src/dialogs/resourcedialog.cpp b/src/dialogs/resourcedialog.cpp index 0206ce0ad4..e6490efa55 100644 --- a/src/dialogs/resourcedialog.cpp +++ b/src/dialogs/resourcedialog.cpp @@ -26,14 +26,14 @@ #include #include -#include #include +#include ResourceDialog::ResourceDialog(QWidget *parent) : QDialog(parent) { setWindowTitle(tr("Resources")); - setSizeGripEnabled(true) ; + setSizeGripEnabled(true); QVBoxLayout *vlayout = new QVBoxLayout(); m_resourceWidget = new ResourceWidget(this); @@ -99,11 +99,12 @@ void ResourceDialog::convert() return; } - TranscodeDialog dialog( - tr("Choose an edit-friendly format below and then click OK to choose a file name. " - "After choosing a file name, a job is created. " - "When it is done, double-click the job to open it.\n"), - MLT.profile().progressive(), this); + TranscodeDialog + dialog(tr("Choose an edit-friendly format below and then click OK to choose a file name. " + "After choosing a file name, a job is created. " + "When it is done, double-click the job to open it.\n"), + MLT.profile().progressive(), + this); dialog.setWindowTitle(tr("Convert...")); dialog.setWindowModality(QmlApplication::dialogModality()); Transcoder transcoder; diff --git a/src/dialogs/saveimagedialog.cpp b/src/dialogs/saveimagedialog.cpp index 5dbf48664f..6d4768b81b 100644 --- a/src/dialogs/saveimagedialog.cpp +++ b/src/dialogs/saveimagedialog.cpp @@ -17,10 +17,10 @@ #include "saveimagedialog.h" +#include "Logger.h" #include "mltcontroller.h" #include "settings.h" #include "util.h" -#include #include #include @@ -28,7 +28,7 @@ static QString suffixFromFilter(const QString &filterText) { QString suffix = filterText.section("*", 1, 1).section(")", 0, 0).section(" ", 0, 0); - if (!suffix.startsWith(".") ) { + if (!suffix.startsWith(".")) { suffix.clear(); } return suffix; @@ -44,8 +44,8 @@ SaveImageDialog::SaveImageDialog(QWidget *parent, const QString &caption, QImage setOptions(Util::getFileDialogOptions()); setDirectory(Settings.savePath()); - QString nameFilter = - tr("PNG (*.png);;BMP (*.bmp);;JPEG (*.jpg *.jpeg);;PPM (*.ppm);;TIFF (*.tif *.tiff);;WebP (*.webp);;All Files (*)"); + QString nameFilter = tr("PNG (*.png);;BMP (*.bmp);;JPEG (*.jpg *.jpeg);;PPM (*.ppm);;TIFF " + "(*.tif *.tiff);;WebP (*.webp);;All Files (*)"); setNameFilter(nameFilter); QStringList nameFilters = nameFilter.split(";;"); @@ -60,8 +60,8 @@ SaveImageDialog::SaveImageDialog(QWidget *parent, const QString &caption, QImage selectNameFilter(selectedNameFilter); // Use the current player time as a suggested file name - QString nameSuggestion = QStringLiteral("Shotcut_%1").arg(MLT.producer()->frame_time( - mlt_time_clock)); + QString nameSuggestion + = QStringLiteral("Shotcut_%1").arg(MLT.producer()->frame_time(mlt_time_clock)); nameSuggestion = nameSuggestion.replace(":", "_"); nameSuggestion = nameSuggestion.replace(".", "_"); nameSuggestion += suffix; @@ -69,7 +69,8 @@ SaveImageDialog::SaveImageDialog(QWidget *parent, const QString &caption, QImage #if !defined(Q_OS_WIN) if (!connect(this, &QFileDialog::filterSelected, this, &SaveImageDialog::onFilterSelected)) - connect(this, SIGNAL(filterSelected(const QString &)), + connect(this, + SIGNAL(filterSelected(const QString &)), SLOT(const onFilterSelected(const QString &))); #endif if (!connect(this, &QFileDialog::fileSelected, this, &SaveImageDialog::onFileSelected)) @@ -110,7 +111,7 @@ void SaveImageDialog::onFileSelected(const QString &file) QFileInfo fi(m_saveFile); if (fi.suffix().isEmpty()) { QString suffix = suffixFromFilter(selectedNameFilter()); - if ( suffix.isEmpty() ) { + if (suffix.isEmpty()) { suffix = ".png"; } m_saveFile += suffix; @@ -121,8 +122,10 @@ void SaveImageDialog::onFileSelected(const QString &file) // Convert to square pixels if needed. qreal aspectRatio = (qreal) m_image.width() / m_image.height(); if (qFloor(aspectRatio * 1000) != qFloor(MLT.profile().dar() * 1000)) { - m_image = m_image.scaled(qRound(m_image.height() * MLT.profile().dar()), m_image.height(), - Qt::IgnoreAspectRatio, Qt::SmoothTransformation); + m_image = m_image.scaled(qRound(m_image.height() * MLT.profile().dar()), + m_image.height(), + Qt::IgnoreAspectRatio, + Qt::SmoothTransformation); } m_image.save(m_saveFile, Q_NULLPTR, (fi.suffix() == "webp") ? 80 : -1); Settings.setSavePath(fi.path()); diff --git a/src/dialogs/saveimagedialog.h b/src/dialogs/saveimagedialog.h index 47d5ebeccb..fa8d8f19ca 100644 --- a/src/dialogs/saveimagedialog.h +++ b/src/dialogs/saveimagedialog.h @@ -28,10 +28,7 @@ class SaveImageDialog : public QFileDialog public: explicit SaveImageDialog(QWidget *parent, const QString &caption, QImage &image); - QString saveFile() - { - return m_saveFile; - } + QString saveFile() { return m_saveFile; } private slots: void onFilterSelected(const QString &filter); diff --git a/src/dialogs/slideshowgeneratordialog.h b/src/dialogs/slideshowgeneratordialog.h index 0a8629d000..5721e4a0d8 100644 --- a/src/dialogs/slideshowgeneratordialog.h +++ b/src/dialogs/slideshowgeneratordialog.h @@ -19,7 +19,6 @@ #define SLIDESHOWGENERATORDIALOG_H #include - #include class SlideshowGeneratorWidget; diff --git a/src/dialogs/subtitletrackdialog.cpp b/src/dialogs/subtitletrackdialog.cpp index ac710b7454..0f5ec88461 100644 --- a/src/dialogs/subtitletrackdialog.cpp +++ b/src/dialogs/subtitletrackdialog.cpp @@ -17,19 +17,18 @@ #include "subtitletrackdialog.h" -#include - #include +#include +#include #include #include #include #include -#include -#include static void fillLanguages(QComboBox *combo) { - QList allLocales = QLocale::matchingLocales(QLocale::AnyLanguage, QLocale::AnyScript, + QList allLocales = QLocale::matchingLocales(QLocale::AnyLanguage, + QLocale::AnyScript, QLocale::AnyTerritory); QMap iso639_2LanguageCodes; for (const QLocale &locale : allLocales) { @@ -43,7 +42,7 @@ static void fillLanguages(QComboBox *combo) } } for (auto it = iso639_2LanguageCodes.keyValueBegin(); it != iso639_2LanguageCodes.keyValueEnd(); - ++it) { + ++it) { QString text = QStringLiteral("%1 (%2)").arg(it->first).arg(it->second); combo->addItem(text, it->second); } diff --git a/src/dialogs/systemsyncdialog.cpp b/src/dialogs/systemsyncdialog.cpp index 74f9567aaa..def9d77ecb 100644 --- a/src/dialogs/systemsyncdialog.cpp +++ b/src/dialogs/systemsyncdialog.cpp @@ -17,13 +17,14 @@ #include "systemsyncdialog.h" #include "ui_systemsyncdialog.h" -#include "settings.h" + #include "mltcontroller.h" +#include "settings.h" -SystemSyncDialog::SystemSyncDialog(QWidget *parent) : - QDialog(parent), - ui(new Ui::SystemSyncDialog), - m_oldValue(Settings.playerVideoDelayMs()) +SystemSyncDialog::SystemSyncDialog(QWidget *parent) + : QDialog(parent) + , ui(new Ui::SystemSyncDialog) + , m_oldValue(Settings.playerVideoDelayMs()) { ui->setupUi(this); ui->syncSlider->setValue(Settings.playerVideoDelayMs()); @@ -75,5 +76,4 @@ void SystemSyncDialog::setDelay(int delay) MLT.consumerChanged(); } ui->applyButton->hide(); - } diff --git a/src/dialogs/textviewerdialog.cpp b/src/dialogs/textviewerdialog.cpp index 266260ec0f..26663084ce 100644 --- a/src/dialogs/textviewerdialog.cpp +++ b/src/dialogs/textviewerdialog.cpp @@ -17,18 +17,19 @@ #include "textviewerdialog.h" #include "ui_textviewerdialog.h" + #include "settings.h" #include "util.h" +#include #include #include -#include #include -TextViewerDialog::TextViewerDialog(QWidget *parent, bool forMltXml) : - QDialog(parent), - ui(new Ui::TextViewerDialog), - m_forMltXml(forMltXml) +TextViewerDialog::TextViewerDialog(QWidget *parent, bool forMltXml) + : QDialog(parent) + , ui(new Ui::TextViewerDialog) + , m_forMltXml(forMltXml) { ui->setupUi(this); auto button = ui->buttonBox->addButton(tr("Copy"), QDialogButtonBox::ActionRole); @@ -47,7 +48,8 @@ void TextViewerDialog::setText(const QString &s, bool scroll) if (s != ui->plainTextEdit->toPlainText()) { ui->plainTextEdit->setPlainText(s); if (scroll) - ui->plainTextEdit->verticalScrollBar()->setValue(ui->plainTextEdit->verticalScrollBar()->maximum()); + ui->plainTextEdit->verticalScrollBar()->setValue( + ui->plainTextEdit->verticalScrollBar()->maximum()); } } @@ -64,8 +66,12 @@ void TextViewerDialog::on_buttonBox_accepted() if (m_forMltXml) { nameFilter = tr("MLT XML (*.mlt);;All Files (*)"); } - QString filename = QFileDialog::getSaveFileName(this, caption, path, nameFilter, - nullptr, Util::getFileDialogOptions()); + QString filename = QFileDialog::getSaveFileName(this, + caption, + path, + nameFilter, + nullptr, + Util::getFileDialogOptions()); if (!filename.isEmpty()) { QFileInfo fi(filename); if (fi.suffix().isEmpty()) { diff --git a/src/dialogs/transcodedialog.cpp b/src/dialogs/transcodedialog.cpp index 06898dc7e6..27b73f4dea 100644 --- a/src/dialogs/transcodedialog.cpp +++ b/src/dialogs/transcodedialog.cpp @@ -17,17 +17,18 @@ #include "transcodedialog.h" #include "ui_transcodedialog.h" + #include "mltcontroller.h" #include "settings.h" #include -TranscodeDialog::TranscodeDialog(const QString &message, bool isProgressive, QWidget *parent) : - QDialog(parent), - ui(new Ui::TranscodeDialog), - m_format(0), - m_isChecked(false), - m_isProgressive(isProgressive) +TranscodeDialog::TranscodeDialog(const QString &message, bool isProgressive, QWidget *parent) + : QDialog(parent) + , ui(new Ui::TranscodeDialog) + , m_format(0) + , m_isChecked(false) + , m_isProgressive(isProgressive) { ui->setupUi(this); setWindowTitle(tr("Convert to Edit-friendly...")); @@ -109,9 +110,9 @@ void TranscodeDialog::set709Convert(bool enable) QString TranscodeDialog::sampleRate() const { QString sampleRate; - if ( ui->sampleRateComboBox->currentIndex() == 1 ) { + if (ui->sampleRateComboBox->currentIndex() == 1) { sampleRate = "44100"; - } else if ( ui->sampleRateComboBox->currentIndex() == 2 ) { + } else if (ui->sampleRateComboBox->currentIndex() == 2) { sampleRate = "48000"; } return sampleRate; @@ -145,8 +146,8 @@ void TranscodeDialog::on_horizontalSlider_valueChanged(int position) ui->formatLabel->setText(tr("Lossy: I-frame–only %1").arg("H.264/AC-3 MP4")); break; case 1: - ui->formatLabel->setText(tr("Intermediate: %1").arg(m_isProgressive ? "DNxHR/PCM MOV" : - "ProRes/PCM MOV")); + ui->formatLabel->setText( + tr("Intermediate: %1").arg(m_isProgressive ? "DNxHR/PCM MOV" : "ProRes/PCM MOV")); break; case 2: ui->formatLabel->setText(tr("Lossless: %1").arg("Ut Video/PCM MKV")); diff --git a/src/dialogs/transcodedialog.h b/src/dialogs/transcodedialog.h index c844511e5f..d6f0bb04d2 100644 --- a/src/dialogs/transcodedialog.h +++ b/src/dialogs/transcodedialog.h @@ -31,15 +31,9 @@ class TranscodeDialog : public QDialog public: explicit TranscodeDialog(const QString &message, bool isProgressive, QWidget *parent = nullptr); ~TranscodeDialog(); - int format() const - { - return m_format; - } + int format() const { return m_format; } void showCheckBox(); - bool isCheckBoxChecked() const - { - return m_isChecked; - } + bool isCheckBoxChecked() const { return m_isChecked; } bool deinterlace() const; bool fpsOverride() const; double fps() const; diff --git a/src/dialogs/transcribeaudiodialog.cpp b/src/dialogs/transcribeaudiodialog.cpp index 1b678844a2..1ed04ed318 100644 --- a/src/dialogs/transcribeaudiodialog.cpp +++ b/src/dialogs/transcribeaudiodialog.cpp @@ -17,12 +17,12 @@ #include "transcribeaudiodialog.h" -#include "docks/timelinedock.h" #include "Logger.h" +#include "docks/timelinedock.h" #include "mainwindow.h" +#include "qmltypes/qmlapplication.h" #include "shotcut_mlt_properties.h" #include "util.h" -#include "qmltypes/qmlapplication.h" #include #include @@ -38,15 +38,12 @@ // List of supported languages from whispercpp static const std::vector whisperLanguages = { - "en", "zh", "de", "es", "ru", "ko", "fr", "ja", "pt", "tr", - "pl", "ca", "nl", "ar", "sv", "it", "id", "hi", "fi", "vi", - "he", "uk", "el", "ms", "cs", "ro", "da", "hu", "ta", "no", - "th", "ur", "hr", "bg", "lt", "la", "mi", "ml", "cy", "sk", - "te", "fa", "lv", "bn", "sr", "az", "sl", "kn", "et", "mk", - "br", "eu", "is", "hy", "ne", "mn", "bs", "kk", "sq", "sw", - "gl", "mr", "pa", "si", "km", "sn", "yo", "so", "af", "oc", - "ka", "be", "tg", "sd", "gu", "am", "yi", "lo", "uz", "fo", - "ht", "ps", "tk", "nn", "mt", "sa", "lb", "my", "bo", "tl", + "en", "zh", "de", "es", "ru", "ko", "fr", "ja", "pt", "tr", "pl", "ca", "nl", "ar", "sv", + "it", "id", "hi", "fi", "vi", "he", "uk", "el", "ms", "cs", "ro", "da", "hu", "ta", "no", + "th", "ur", "hr", "bg", "lt", "la", "mi", "ml", "cy", "sk", "te", "fa", "lv", "bn", "sr", + "az", "sl", "kn", "et", "mk", "br", "eu", "is", "hy", "ne", "mn", "bs", "kk", "sq", "sw", + "gl", "mr", "pa", "si", "km", "sn", "yo", "so", "af", "oc", "ka", "be", "tg", "sd", "gu", + "am", "yi", "lo", "uz", "fo", "ht", "ps", "tk", "nn", "mt", "sa", "lb", "my", "bo", "tl", "mg", "as", "tt", "haw", "ln", "ha", "ba", "jw", "su", "yue", }; @@ -186,14 +183,16 @@ TranscribeAudioDialog::TranscribeAudioDialog(const QString &trackName, QWidget * m_exeLabel->setReadOnly(true); configLayout->addWidget(m_exeLabel, 1, 1, Qt::AlignLeft); QPushButton *exeBrowseButton = new QPushButton(this); - exeBrowseButton->setIcon(QIcon::fromTheme("document-open", - QIcon(":/icons/oxygen/32x32/actions/document-open.png"))); + exeBrowseButton->setIcon( + QIcon::fromTheme("document-open", QIcon(":/icons/oxygen/32x32/actions/document-open.png"))); connect(exeBrowseButton, &QAbstractButton::clicked, this, [&] { - auto path = QFileDialog::getOpenFileName(this, tr("Find Whisper.cpp"), Settings.whisperExe(), + auto path = QFileDialog::getOpenFileName(this, + tr("Find Whisper.cpp"), + Settings.whisperExe(), QString(), - nullptr, Util::getFileDialogOptions()); - if (QFileInfo(path).isExecutable()) - { + nullptr, + Util::getFileDialogOptions()); + if (QFileInfo(path).isExecutable()) { Settings.setWhisperExe(path); updateWhisperStatus(); } @@ -207,19 +206,20 @@ TranscribeAudioDialog::TranscribeAudioDialog(const QString &trackName, QWidget * m_modelLabel->setReadOnly(true); configLayout->addWidget(m_modelLabel, 2, 1, Qt::AlignLeft); QPushButton *modelBrowseButton = new QPushButton(this); - modelBrowseButton->setIcon(QIcon::fromTheme("document-open", - QIcon(":/icons/oxygen/32x32/actions/document-open.png"))); + modelBrowseButton->setIcon( + QIcon::fromTheme("document-open", QIcon(":/icons/oxygen/32x32/actions/document-open.png"))); connect(modelBrowseButton, &QAbstractButton::clicked, this, [&] { - auto path = QFileDialog::getOpenFileName(this, tr("Find Whisper.cpp"), Settings.whisperModel(), + auto path = QFileDialog::getOpenFileName(this, + tr("Find Whisper.cpp"), + Settings.whisperModel(), "*.bin", - nullptr, Util::getFileDialogOptions()); - if (QFileInfo(path).exists()) - { + nullptr, + Util::getFileDialogOptions()); + if (QFileInfo(path).exists()) { LOG_INFO() << "Model found" << path; Settings.setWhisperModel(path); updateWhisperStatus(); - } else - { + } else { LOG_INFO() << "Model not found" << path; } }); @@ -279,7 +279,6 @@ void TranscribeAudioDialog::clicked(QAbstractButton *button) } } - QString TranscribeAudioDialog::name() { return m_name->text(); diff --git a/src/dialogs/unlinkedfilesdialog.cpp b/src/dialogs/unlinkedfilesdialog.cpp index 3d2cb4f494..e6e2be96bb 100644 --- a/src/dialogs/unlinkedfilesdialog.cpp +++ b/src/dialogs/unlinkedfilesdialog.cpp @@ -16,17 +16,18 @@ */ #include "unlinkedfilesdialog.h" -#include "ui_unlinkedfilesdialog.h" -#include "settings.h" +#include "Logger.h" #include "mltxmlchecker.h" +#include "settings.h" +#include "ui_unlinkedfilesdialog.h" #include "util.h" -#include + #include #include -UnlinkedFilesDialog::UnlinkedFilesDialog(QWidget *parent) : - QDialog(parent), - ui(new Ui::UnlinkedFilesDialog) +UnlinkedFilesDialog::UnlinkedFilesDialog(QWidget *parent) + : QDialog(parent) + , ui(new Ui::UnlinkedFilesDialog) { ui->setupUi(this); } @@ -53,8 +54,12 @@ void UnlinkedFilesDialog::on_tableView_doubleClicked(const QModelIndex &index) #ifdef Q_OS_MAC path.append("/*"); #endif - QStringList filenames = QFileDialog::getOpenFileNames(this, tr("Open File"), path, - QString(), nullptr, Util::getFileDialogOptions()); + QStringList filenames = QFileDialog::getOpenFileNames(this, + tr("Open File"), + path, + QString(), + nullptr, + Util::getFileDialogOptions()); if (filenames.length() > 0) { QAbstractItemModel *model = ui->tableView->model(); @@ -96,14 +101,15 @@ bool UnlinkedFilesDialog::lookInDir(const QDir &dir, bool recurse) } if (outstanding) { for (const auto &fileName : - dir.entryList(QDir::Files | QDir::Readable | QDir::NoDotAndDotDot)) { + dir.entryList(QDir::Files | QDir::Readable | QDir::NoDotAndDotDot)) { QString hash = Util::getFileHash(dir.absoluteFilePath(fileName)); for (int row = 0; row < model->rowCount(); row++) { QModelIndex replacementIndex = model->index(row, MltXmlChecker::ReplacementColumn); if (model->data(replacementIndex, MltXmlChecker::ShotcutHashRole).isNull()) { QModelIndex missingIndex = model->index(row, MltXmlChecker::MissingColumn); QFileInfo missingInfo(model->data(missingIndex).toString()); - QString missingHash = model->data(missingIndex, MltXmlChecker::ShotcutHashRole).toString(); + QString missingHash + = model->data(missingIndex, MltXmlChecker::ShotcutHashRole).toString(); if (hash == missingHash || fileName == missingInfo.fileName()) { if (hash == missingHash) { QIcon icon(":/icons/oxygen/32x32/status/task-complete.png"); @@ -128,7 +134,7 @@ bool UnlinkedFilesDialog::lookInDir(const QDir &dir, bool recurse) } if (outstanding && recurse) { for (const QString &dirName : - dir.entryList(QDir::Dirs | QDir::Executable | QDir::NoDotAndDotDot)) { + dir.entryList(QDir::Dirs | QDir::Executable | QDir::NoDotAndDotDot)) { if (!lookInDir(dir.absoluteFilePath(dirName), true)) break; } @@ -138,7 +144,9 @@ bool UnlinkedFilesDialog::lookInDir(const QDir &dir, bool recurse) void UnlinkedFilesDialog::on_searchFolderButton_clicked() { - QString dirName = QFileDialog::getExistingDirectory(this, windowTitle(), Settings.openPath(), + QString dirName = QFileDialog::getExistingDirectory(this, + windowTitle(), + Settings.openPath(), Util::getFileDialogOptions()); if (!dirName.isEmpty()) { Settings.setOpenPath(dirName); diff --git a/src/dialogs/unlinkedfilesdialog.h b/src/dialogs/unlinkedfilesdialog.h index 84482b7caa..1f3dcf0ae8 100644 --- a/src/dialogs/unlinkedfilesdialog.h +++ b/src/dialogs/unlinkedfilesdialog.h @@ -19,8 +19,8 @@ #define UNLINKEDFILESDIALOG_H #include -#include #include +#include namespace Ui { class UnlinkedFilesDialog; diff --git a/src/docks/encodedock.cpp b/src/docks/encodedock.cpp old mode 100755 new mode 100644 index 8e2eec2e72..46eb81cc78 --- a/src/docks/encodedock.cpp +++ b/src/docks/encodedock.cpp @@ -17,28 +17,29 @@ #include "encodedock.h" #include "ui_encodedock.h" + +#include "Logger.h" #include "dialogs/addencodepresetdialog.h" +#include "dialogs/listselectiondialog.h" #include "dialogs/multifileexportdialog.h" #include "jobqueue.h" -#include "mltcontroller.h" +#include "jobs/encodejob.h" #include "mainwindow.h" -#include "settings.h" +#include "mltcontroller.h" +#include "models/markersmodel.h" #include "qmltypes/qmlapplication.h" -#include "jobs/encodejob.h" +#include "qmltypes/qmlfilter.h" +#include "settings.h" #include "shotcut_mlt_properties.h" #include "util.h" -#include "dialogs/listselectiondialog.h" -#include "qmltypes/qmlfilter.h" -#include "models/markersmodel.h" -#include -#include -#include -#include -#include #include #include #include +#include +#include +#include +#include // formulas to map absolute value ranges to percentages as int #define TO_ABSOLUTE(min, max, rel) qRound(float(min) + float((max) - (min)) * float(rel) / 100.0f) @@ -58,20 +59,21 @@ static Mlt::Filter getReframeFilter(Mlt::Service *service) if (service && service->is_valid()) for (auto i = 0; i < service->filter_count(); ++i) { std::unique_ptr filter(service->filter(i)); - if (filter && filter->is_valid() && !::qstrcmp("reframe", filter->get(kShotcutFilterProperty))) + if (filter && filter->is_valid() + && !::qstrcmp("reframe", filter->get(kShotcutFilterProperty))) return Mlt::Filter(filter->get_filter()); } return Mlt::Filter(); } -EncodeDock::EncodeDock(QWidget *parent) : - QDockWidget(parent), - ui(new Ui::EncodeDock), - m_presets(Mlt::Repository::presets()), - m_immediateJob(0), - m_profiles(Mlt::Profile::list()), - m_isDefaultSettings(true), - m_fps(0.0) +EncodeDock::EncodeDock(QWidget *parent) + : QDockWidget(parent) + , ui(new Ui::EncodeDock) + , m_presets(Mlt::Repository::presets()) + , m_immediateJob(0) + , m_profiles(Mlt::Profile::list()) + , m_isDefaultSettings(true) + , m_fps(0.0) { LOG_DEBUG() << "begin"; initSpecialCodecLists(); @@ -100,9 +102,13 @@ EncodeDock::EncodeDock(QWidget *parent) : ui->parallelCheckbox->setHidden(true); toggleViewAction()->setIcon(windowIcon()); - connect(ui->videoBitrateCombo, SIGNAL(currentIndexChanged(int)), this, + connect(ui->videoBitrateCombo, + SIGNAL(currentIndexChanged(int)), + this, SLOT(on_videoBufferDurationChanged())); - connect(ui->videoBufferSizeSpinner, SIGNAL(valueChanged(double)), this, + connect(ui->videoBufferSizeSpinner, + SIGNAL(valueChanged(double)), + this, SLOT(on_videoBufferDurationChanged())); m_presetsModel.setSourceModel(new QStandardItemModel(this)); @@ -138,8 +144,8 @@ EncodeDock::EncodeDock(QWidget *parent) : p = new Mlt::Properties(c.get_data("vcodec")); for (int i = 0; i < p->count(); i++) { - if (qstrcmp("nvenc", p->get(i)) // redundant codec names nvenc_... - && qstrcmp("wrapped_avframe", p->get(i))) // not usable + if (qstrcmp("nvenc", p->get(i)) // redundant codec names nvenc_... + && qstrcmp("wrapped_avframe", p->get(i))) // not usable ui->videoCodecCombo->addItem(p->get(i)); } delete p; @@ -175,9 +181,9 @@ void EncodeDock::loadPresetFromProperties(Mlt::Properties &preset) if (ui->hwencodeCheckBox->isChecked()) { foreach (const QString &hw, Settings.encodeHardware()) { if ((vcodec == "libx264" && hw.startsWith("h264")) - || (vcodec == "libx265" && hw.startsWith("hevc")) - || (vcodec == "libvpx-vp9" && hw.startsWith("vp9")) - || (vcodec == "libsvtav1" && hw.startsWith("av1"))) { + || (vcodec == "libx265" && hw.startsWith("hevc")) + || (vcodec == "libvpx-vp9" && hw.startsWith("vp9")) + || (vcodec == "libsvtav1" && hw.startsWith("av1"))) { vcodec = hw; break; } @@ -198,7 +204,8 @@ void EncodeDock::loadPresetFromProperties(Mlt::Properties &preset) other.append("vtag=hvc1"); } } - bool qmin_nvenc_amf = preset.get("qmin") && (vcodec.contains("nvenc") || vcodec.endsWith("_amf")); + bool qmin_nvenc_amf = preset.get("qmin") + && (vcodec.contains("nvenc") || vcodec.endsWith("_amf")); for (int i = 0; i < preset.count(); i++) { QString name(preset.get_name(i)); @@ -225,14 +232,14 @@ void EncodeDock::loadPresetFromProperties(Mlt::Properties &preset) if (ui->videoCodecCombo->itemText(j) == vcodec) ui->videoCodecCombo->setCurrentIndex(j); } else if (name == "channels") { - setAudioChannels( preset.get_int("channels") ); + setAudioChannels(preset.get_int("channels")); } else if (name == "ar") { ui->sampleRateCombo->lineEdit()->setText(value); } else if (name == "ab") { ui->audioBitrateCombo->lineEdit()->setText(value); } else if (name == "vb") { - ui->videoRateControlCombo->setCurrentIndex((preset.get_int("vb") > 0) ? RateControlAverage : - RateControlQuality); + ui->videoRateControlCombo->setCurrentIndex( + (preset.get_int("vb") > 0) ? RateControlAverage : RateControlQuality); ui->videoBitrateCombo->lineEdit()->setText(value); } else if (name == "g") { ui->gopSpinner->setValue(preset.get_int("g")); @@ -281,7 +288,8 @@ void EncodeDock::loadPresetFromProperties(Mlt::Properties &preset) ui->fpsSpinner->setValue(preset.get_double("r")); } else if (name == "frame_rate_num") { if (preset.get_int("frame_rate_den")) - ui->fpsSpinner->setValue(preset.get_double("frame_rate_num") / preset.get_double("frame_rate_den")); + ui->fpsSpinner->setValue(preset.get_double("frame_rate_num") + / preset.get_double("frame_rate_den")); } else if (name == "pix_fmt") { // Handle 10 bit encoding with hardware encoder and GPU Effects if (value.contains("p10le")) { @@ -296,7 +304,7 @@ void EncodeDock::loadPresetFromProperties(Mlt::Properties &preset) } // Hardware encoder if (vcodec.endsWith("_nvenc") || vcodec.endsWith("_qsv") - || vcodec.endsWith("_vaapi") || vcodec.endsWith("_videotoolbox")) { + || vcodec.endsWith("_vaapi") || vcodec.endsWith("_videotoolbox")) { value = "p010le"; } } @@ -327,12 +335,13 @@ void EncodeDock::loadPresetFromProperties(Mlt::Properties &preset) || (name == "qmin" && qmin_nvenc_amf) || name == "cq" || name == "crf") { // On macOS videotoolbox, constant quality is only on Apple Silicon #if defined(Q_OS_MAC) && !defined(Q_PROCESSOR_ARM) - ui->videoRateControlCombo->setCurrentIndex(preset.get("vbufsize") ? RateControlConstrained - : vcodec.endsWith("_videotoolbox") ? RateControlAverage : - RateControlQuality); + ui->videoRateControlCombo->setCurrentIndex( + preset.get("vbufsize") ? RateControlConstrained + : vcodec.endsWith("_videotoolbox") ? RateControlAverage + : RateControlQuality); #else - ui->videoRateControlCombo->setCurrentIndex(preset.get("vbufsize") ? RateControlConstrained : - RateControlQuality); + ui->videoRateControlCombo->setCurrentIndex( + preset.get("vbufsize") ? RateControlConstrained : RateControlQuality); #endif videoQuality = preset.get_int(name.toUtf8().constData()); } else if (name == "bufsize" || name == "vbufsize") { @@ -351,7 +360,8 @@ void EncodeDock::loadPresetFromProperties(Mlt::Properties &preset) } else if (name == "meta.preset.extension") { m_extension = value; } else if (name == "deinterlace_method" || name == "deinterlacer") { - name = preset.get("deinterlacer") ? preset.get("deinterlacer") : preset.get("deinterlace_method"); + name = preset.get("deinterlacer") ? preset.get("deinterlacer") + : preset.get("deinterlace_method"); if (name == "onefield") ui->deinterlacerCombo->setCurrentIndex(0); else if (name == "linearblend") @@ -375,8 +385,9 @@ void EncodeDock::loadPresetFromProperties(Mlt::Properties &preset) ui->rangeComboBox->setCurrentIndex(1); } else { if (name != "an" && name != "vn" && name != "threads" - && !(name == "frame_rate_den" && preset.property_exists("frame_rate_num")) - && !name.startsWith('_') && !name.startsWith("qp_") && !name.startsWith("meta.preset.")) { + && !(name == "frame_rate_den" && preset.property_exists("frame_rate_num")) + && !name.startsWith('_') && !name.startsWith("qp_") + && !name.startsWith("meta.preset.")) { other.append(QStringLiteral("%1=%2").arg(name, value)); } } @@ -390,7 +401,8 @@ void EncodeDock::loadPresetFromProperties(Mlt::Properties &preset) const QString &acodec = ui->audioCodecCombo->currentText(); if (acodec == "libmp3lame") // 0 (best) - 9 (worst) ui->audioQualitySpinner->setValue(TO_RELATIVE(9, 0, audioQuality)); - if (acodec == "libvorbis" || acodec == "vorbis" || acodec == "libopus") // 0 (worst) - 10 (best) + if (acodec == "libvorbis" || acodec == "vorbis" + || acodec == "libopus") // 0 (worst) - 10 (best) ui->audioQualitySpinner->setValue(TO_RELATIVE(0, 10, audioQuality)); else // aac: 0 (worst) - 500 (best) @@ -399,24 +411,25 @@ void EncodeDock::loadPresetFromProperties(Mlt::Properties &preset) if (acodec == "vorbis" || acodec == "libvorbis") ui->audioRateControlCombo->setCurrentIndex(RateControlAverage); if ((ui->videoRateControlCombo->currentIndex() == RateControlQuality - || ui->videoRateControlCombo->currentIndex() == RateControlConstrained) - && videoQuality > -1) { + || ui->videoRateControlCombo->currentIndex() == RateControlConstrained) + && videoQuality > -1) { //val = min + (max - min) * paramval; if (vcodec.startsWith("libx264") || vcodec == "libx265" || vcodec.contains("nvenc") - || vcodec.endsWith("_amf") || vcodec.endsWith("_vaapi")) { + || vcodec.endsWith("_amf") || vcodec.endsWith("_vaapi")) { // 0 (best, 100%) - 51 (worst) ui->videoQualitySpinner->setValue(TO_RELATIVE(51, 0, videoQuality)); } else if (vcodec.endsWith("_videotoolbox")) { #if defined(Q_OS_MAC) && defined(Q_PROCESSOR_ARM) - ui->videoQualitySpinner->setValue(ui->hwencodeCheckBox->isChecked() ? videoQuality * 55.0 / 23.0 : - videoQuality); + ui->videoQualitySpinner->setValue( + ui->hwencodeCheckBox->isChecked() ? videoQuality * 55.0 / 23.0 : videoQuality); #else ui->videoQualitySpinner->setValue(videoQuality); #endif } else if (vcodec.endsWith("_qsv")) { // 1 (best, 100%) - 51 (worst) ui->videoQualitySpinner->setValue(TO_RELATIVE(51, 1, videoQuality)); - } else if (vcodec.startsWith("libvpx") || vcodec.startsWith("libaom-") || vcodec == "libsvtav1") { + } else if (vcodec.startsWith("libvpx") || vcodec.startsWith("libaom-") + || vcodec == "libsvtav1") { // 0 (best, 100%) - 63 (worst) ui->videoQualitySpinner->setValue(TO_RELATIVE(63, 0, videoQuality)); } else if (vcodec.startsWith("libwebp") || vcodec.endsWith("_mf")) { @@ -458,7 +471,7 @@ void EncodeDock::onProducerOpened() if (MLT.isClip() && !MLT.isClosedClip()) { ui->fromCombo->addItem(tr("Source"), "clip"); if (MLT.producer()->get_int(kBackgroundCaptureProperty) - || MLT.producer()->get_int(kExportFromProperty)) + || MLT.producer()->get_int(kExportFromProperty)) index = ui->fromCombo->count() - 1; } else if (MLT.savedProducer() && MLT.savedProducer()->is_valid() && !MLT.isClosedClip(MLT.savedProducer())) { @@ -485,8 +498,8 @@ void EncodeDock::onProducerOpened() ui->fromCombo->setCurrentIndex(index); on_fromCombo_currentIndexChanged(index); } - ui->otherTipLabel->setText(tr("You must enter numeric values using '%1' as the decimal point.").arg( - MLT.decimalPoint())); + ui->otherTipLabel->setText(tr("You must enter numeric values using '%1' as the decimal point.") + .arg(MLT.decimalPoint())); } void EncodeDock::loadPresets() @@ -539,7 +552,8 @@ void EncodeDock::loadPresets() for (int j = 0; j < m_presets->count(); j++) { QString name(m_presets->get_name(j)); if (name.startsWith(prefix)) { - Mlt::Properties preset((mlt_properties) m_presets->get_data(name.toLatin1().constData())); + Mlt::Properties preset( + (mlt_properties) m_presets->get_data(name.toLatin1().constData())); if (preset.get_int("meta.preset.hidden")) continue; if (preset.get("meta.preset.name")) @@ -581,8 +595,8 @@ void EncodeDock::loadPresets() QStandardItem *item = new QStandardItem(nameParts.join('/')); item->setData(QString(m_presets->get_name(j))); if (preset.get("meta.preset.note")) - item->setToolTip(QStringLiteral("

%1

").arg(QString::fromUtf8( - preset.get("meta.preset.note")))); + item->setToolTip(QStringLiteral("

%1

") + .arg(QString::fromUtf8(preset.get("meta.preset.note")))); parentItem->appendRow(item); } } @@ -630,17 +644,20 @@ Mlt::Properties *EncodeDock::collectProperties(int realtime, bool includeProfile } setIfNotSet(p, "ar", ui->sampleRateCombo->currentText().toLatin1().constData()); if (ui->audioRateControlCombo->currentIndex() == RateControlAverage - || ui->audioRateControlCombo->currentIndex() == RateControlConstant) { + || ui->audioRateControlCombo->currentIndex() == RateControlConstant) { setIfNotSet(p, "ab", ui->audioBitrateCombo->currentText().toLatin1().constData()); if (RateControlConstant == ui->audioRateControlCombo->currentIndex()) setIfNotSet(p, "vbr", "off"); else setIfNotSet(p, "vbr", "constrained"); - if (acodec == "libmp3lame" && ui->audioRateControlCombo->currentIndex() == RateControlAverage) + if (acodec == "libmp3lame" + && ui->audioRateControlCombo->currentIndex() == RateControlAverage) setIfNotSet(p, "abr", "1"); } else if (acodec == "libopus") { setIfNotSet(p, "vbr", "on"); - setIfNotSet(p, "compression_level", TO_ABSOLUTE(0, 10, ui->audioQualitySpinner->value())); + setIfNotSet(p, + "compression_level", + TO_ABSOLUTE(0, 10, ui->audioQualitySpinner->value())); } else { setIfNotSet(p, "vbr", "on"); double aq = ui->audioQualitySpinner->value(); @@ -677,20 +694,26 @@ Mlt::Properties *EncodeDock::collectProperties(int realtime, bool includeProfile QString x265params = QString::fromUtf8(p->get("x265-params")); switch (ui->videoRateControlCombo->currentIndex()) { case RateControlAverage: - setIfNotSet(p, "vb", ui->videoBitrateCombo->currentText().toLatin1().constData()); + setIfNotSet(p, + "vb", + ui->videoBitrateCombo->currentText().toLatin1().constData()); break; case RateControlConstant: { QString b = ui->videoBitrateCombo->currentText(); // x265 does not expect bitrate suffixes and requires Kb/s b.replace('k', "").replace('M', "000"); x265params = QStringLiteral("bitrate=%1:vbv-bufsize=%2:vbv-maxrate=%3:%4") - .arg(b).arg(int(ui->videoBufferSizeSpinner->value() * 8)).arg(b).arg(x265params); + .arg(b) + .arg(int(ui->videoBufferSizeSpinner->value() * 8)) + .arg(b) + .arg(x265params); setIfNotSet(p, "vb", b.toLatin1().constData()); setIfNotSet(p, "vbufsize", int(ui->videoBufferSizeSpinner->value() * 8 * 1024)); break; } case RateControlQuality: { - x265params = QStringLiteral("crf=%1:%2").arg(TO_ABSOLUTE(51, 0, vq)).arg(x265params); + x265params + = QStringLiteral("crf=%1:%2").arg(TO_ABSOLUTE(51, 0, vq)).arg(x265params); // Also set crf property so that custom presets can be interpreted properly. setIfNotSet(p, "crf", TO_ABSOLUTE(51, 0, vq)); break; @@ -700,24 +723,31 @@ Mlt::Properties *EncodeDock::collectProperties(int realtime, bool includeProfile // x265 does not expect bitrate suffixes and requires Kb/s b.replace('k', "").replace('M', "000"); x265params = QStringLiteral("crf=%1:vbv-bufsize=%2:vbv-maxrate=%3:%4") - .arg(TO_ABSOLUTE(51, 0, vq)).arg(int(ui->videoBufferSizeSpinner->value() * 8)).arg(b).arg( - x265params); + .arg(TO_ABSOLUTE(51, 0, vq)) + .arg(int(ui->videoBufferSizeSpinner->value() * 8)) + .arg(b) + .arg(x265params); // Also set properties so that custom presets can be interpreted properly. setIfNotSet(p, "crf", TO_ABSOLUTE(51, 0, vq)); setIfNotSet(p, "vbufsize", int(ui->videoBufferSizeSpinner->value() * 8 * 1024)); - setIfNotSet(p, "vmaxrate", ui->videoBitrateCombo->currentText().toLatin1().constData()); + setIfNotSet(p, + "vmaxrate", + ui->videoBitrateCombo->currentText().toLatin1().constData()); break; } } - x265params = QStringLiteral("keyint=%1:bframes=%2:%3").arg(ui->gopSpinner->value()) - .arg(ui->bFramesSpinner->value()).arg(x265params); + x265params = QStringLiteral("keyint=%1:bframes=%2:%3") + .arg(ui->gopSpinner->value()) + .arg(ui->bFramesSpinner->value()) + .arg(x265params); if (ui->strictGopCheckBox->isChecked()) { x265params = QStringLiteral("scenecut=0:%1").arg(x265params); setIfNotSet(p, "sc_threshold", 0); } if (ui->scanModeCombo->currentIndex() == 0 && !x265params.contains("interlace=")) { - x265params = QStringLiteral("interlace=%1:%2").arg( - ui->fieldOrderCombo->currentIndex() ? "tff" : "bff", x265params); + x265params = QStringLiteral("interlace=%1:%2") + .arg(ui->fieldOrderCombo->currentIndex() ? "tff" : "bff", + x265params); } // Also set some properties so that custom presets can be interpreted properly. setIfNotSet(p, "g", ui->gopSpinner->value()); @@ -725,7 +755,8 @@ Mlt::Properties *EncodeDock::collectProperties(int realtime, bool includeProfile p->set("x265-params", x265params.toUtf8().constData()); } else if (vcodec == "libsvtav1") { QString bitrate_text = ui->videoBitrateCombo->currentText(); - int bitrate_kbps = qMax(QString(bitrate_text).replace('k', "").replace('M', "000").toInt(), 1); + int bitrate_kbps + = qMax(QString(bitrate_text).replace('k', "").replace('M', "000").toInt(), 1); int buffer_bits = qRound(ui->videoBufferSizeSpinner->value() * 1024.0 * 8.0); int buffer_ms = qRound(float(buffer_bits) / float(bitrate_kbps)); QStringList encParams; @@ -750,7 +781,9 @@ Mlt::Properties *EncodeDock::collectProperties(int realtime, bool includeProfile case RateControlConstrained: { setIfNotSet(p, "crf", TO_ABSOLUTE(63, 0, vq)); setIfNotSet(p, "vmaxrate", bitrate_text.toLatin1().constData()); - setIfNotSet(p, "vbufsize", buffer_bits); // For UI only; not used by svtav1-params + setIfNotSet(p, + "vbufsize", + buffer_bits); // For UI only; not used by svtav1-params break; } } @@ -789,7 +822,9 @@ Mlt::Properties *EncodeDock::collectProperties(int realtime, bool includeProfile } else if (vcodec.contains("nvenc")) { switch (ui->videoRateControlCombo->currentIndex()) { case RateControlAverage: - setIfNotSet(p, "vb", ui->videoBitrateCombo->currentText().toLatin1().constData()); + setIfNotSet(p, + "vb", + ui->videoBitrateCombo->currentText().toLatin1().constData()); break; case RateControlConstant: { const QString &b = ui->videoBitrateCombo->currentText(); @@ -828,7 +863,9 @@ Mlt::Properties *EncodeDock::collectProperties(int realtime, bool includeProfile } else if (vcodec.endsWith("_amf")) { switch (ui->videoRateControlCombo->currentIndex()) { case RateControlAverage: - setIfNotSet(p, "vb", ui->videoBitrateCombo->currentText().toLatin1().constData()); + setIfNotSet(p, + "vb", + ui->videoBitrateCombo->currentText().toLatin1().constData()); break; case RateControlConstant: { const QString &b = ui->videoBitrateCombo->currentText(); @@ -869,7 +906,9 @@ Mlt::Properties *EncodeDock::collectProperties(int realtime, bool includeProfile switch (ui->videoRateControlCombo->currentIndex()) { case RateControlAverage: setIfNotSet(p, "rate_control", "vbr"); - setIfNotSet(p, "vb", ui->videoBitrateCombo->currentText().toLatin1().constData()); + setIfNotSet(p, + "vb", + ui->videoBitrateCombo->currentText().toLatin1().constData()); break; case RateControlConstant: { const QString &b = ui->videoBitrateCombo->currentText(); @@ -918,7 +957,9 @@ Mlt::Properties *EncodeDock::collectProperties(int realtime, bool includeProfile } else { switch (ui->videoRateControlCombo->currentIndex()) { case RateControlAverage: - setIfNotSet(p, "vb", ui->videoBitrateCombo->currentText().toLatin1().constData()); + setIfNotSet(p, + "vb", + ui->videoBitrateCombo->currentText().toLatin1().constData()); break; case RateControlConstant: { const QString &b = ui->videoBitrateCombo->currentText(); @@ -933,7 +974,9 @@ Mlt::Properties *EncodeDock::collectProperties(int realtime, bool includeProfile setIfNotSet(p, "crf", TO_ABSOLUTE(51, 0, vq)); } else if (vcodec.startsWith("libvpx") || vcodec.startsWith("libaom-")) { setIfNotSet(p, "crf", TO_ABSOLUTE(63, 0, vq)); - setIfNotSet(p, "vb", 0); // VP9 needs this to prevent constrained quality mode. + setIfNotSet(p, + "vb", + 0); // VP9 needs this to prevent constrained quality mode. } else if (vcodec.endsWith("_vaapi")) { setIfNotSet(p, "vglobal_quality", TO_ABSOLUTE(51, 0, vq)); setIfNotSet(p, "vq", TO_ABSOLUTE(51, 0, vq)); @@ -995,17 +1038,19 @@ Mlt::Properties *EncodeDock::collectProperties(int realtime, bool includeProfile setIfNotSet(p, "height", ui->heightSpinner->value()); } if (ui->previewScaleCheckBox->isChecked() && !p->get("scale") - && Settings.playerPreviewScale() > 0) { + && Settings.playerPreviewScale() > 0) { p->set("scale", double(Settings.playerPreviewScale()) / MLT.profile().height()); } - if (includeProfile || - ui->aspectNumSpinner->value() != MLT.profile().display_aspect_num() || - ui->aspectDenSpinner->value() != MLT.profile().display_aspect_den() || - ui->widthSpinner->value() != MLT.profile().width() || - ui->heightSpinner->value() != MLT.profile().height()) { + if (includeProfile + || ui->aspectNumSpinner->value() != MLT.profile().display_aspect_num() + || ui->aspectDenSpinner->value() != MLT.profile().display_aspect_den() + || ui->widthSpinner->value() != MLT.profile().width() + || ui->heightSpinner->value() != MLT.profile().height()) { if (ui->aspectNumSpinner->isEnabled()) - setIfNotSet(p, "aspect", double(ui->aspectNumSpinner->value()) / double( - ui->aspectDenSpinner->value())); + setIfNotSet(p, + "aspect", + double(ui->aspectNumSpinner->value()) + / double(ui->aspectDenSpinner->value())); } if (includeProfile || ui->scanModeCombo->currentIndex() != MLT.profile().progressive()) { setIfNotSet(p, "progressive", ui->scanModeCombo->currentIndex()); @@ -1043,10 +1088,12 @@ Mlt::Properties *EncodeDock::collectProperties(int realtime, bool includeProfile break; } // If the frame rate is not specified in Other. - if (!p->get("r") && !(p->get("frame_rate_num") && p->get("frame_rate_den")) - // Only if the frame rate spinner does not match the profile. - && (includeProfile - || qRound(ui->fpsSpinner->value() * 1000000.0) != qRound(MLT.profile().fps() * 1000000.0))) { + if (!p->get("r") + && !(p->get("frame_rate_num") && p->get("frame_rate_den")) + // Only if the frame rate spinner does not match the profile. + && (includeProfile + || qRound(ui->fpsSpinner->value() * 1000000.0) + != qRound(MLT.profile().fps() * 1000000.0))) { int numerator, denominator; Util::normalizeFrameRate(ui->fpsSpinner->value(), numerator, denominator); p->set("frame_rate_num", numerator); @@ -1065,12 +1112,12 @@ Mlt::Properties *EncodeDock::collectProperties(int realtime, bool includeProfile else setIfNotSet(p, "threads", ui->videoCodecThreadsSpinner->value()); if (ui->videoRateControlCombo->currentIndex() != RateControlQuality - && !vcodec.contains("nvenc") && !vcodec.endsWith("_amf") && !vcodec.endsWith("_qsv") - && !vcodec.endsWith("_videotoolbox") && !vcodec.endsWith("_vaapi") && - ui->dualPassCheckbox->isEnabled() && ui->dualPassCheckbox->isChecked()) + && !vcodec.contains("nvenc") && !vcodec.endsWith("_amf") && !vcodec.endsWith("_qsv") + && !vcodec.endsWith("_videotoolbox") && !vcodec.endsWith("_vaapi") + && ui->dualPassCheckbox->isEnabled() && ui->dualPassCheckbox->isChecked()) setIfNotSet(p, "pass", 1); if (ui->scanModeCombo->currentIndex() == 0 && ui->fieldOrderCombo->currentIndex() == 0 - && vcodec.startsWith("libx264")) { + && vcodec.startsWith("libx264")) { QString x264params = QString::fromUtf8(p->get("x264-params")); if (!x264params.contains("bff=") && !x264params.contains("tff=")) { x264params.prepend("bff=1:"); @@ -1101,8 +1148,8 @@ void EncodeDock::setSubtitleProperties(QDomElement &node, Mlt::Producer *service int subIndex = 0; for (int i = 0; i < service->filter_count(); i++) { QScopedPointer filter(service->filter(i)); - if (filter && filter->is_valid() - && filter->get("mlt_service") == QStringLiteral("subtitle_feed")) { + if (filter && filter->is_valid() + && filter->get("mlt_service") == QStringLiteral("subtitle_feed")) { QString key = QStringLiteral("subtitle.%1.feed").arg(subIndex); node.setAttribute(key, filter->get("feed")); key = QStringLiteral("subtitle.%1.lang").arg(subIndex); @@ -1112,8 +1159,8 @@ void EncodeDock::setSubtitleProperties(QDomElement &node, Mlt::Producer *service } } -QPoint EncodeDock::addConsumerElement(Mlt::Producer *service, QDomDocument &dom, - const QString &target, int realtime, int pass) +QPoint EncodeDock::addConsumerElement( + Mlt::Producer *service, QDomDocument &dom, const QString &target, int realtime, int pass) { QDomElement consumerNode = dom.createElement("consumer"); QDomNodeList profiles = dom.elementsByTagName("profile"); @@ -1128,7 +1175,9 @@ QPoint EncodeDock::addConsumerElement(Mlt::Producer *service, QDomDocument &dom, if (pass == 1 || pass == 2) { QString x265params = consumerNode.attribute("x265-params"); x265params = QStringLiteral("pass=%1:stats=%2:%3") - .arg(pass).arg(QString(target).replace(":", "\\:") + "_2pass.log").arg(x265params); + .arg(pass) + .arg(QString(target).replace(":", "\\:") + "_2pass.log") + .arg(x265params); consumerNode.setAttribute("x265-params", x265params); } } else if ("libsvtav1" == ui->videoCodecCombo->currentText()) { @@ -1136,7 +1185,8 @@ QPoint EncodeDock::addConsumerElement(Mlt::Producer *service, QDomDocument &dom, QStringList encParams; encParams << QStringLiteral("passes=2"); encParams << QStringLiteral("pass=%1").arg(pass); - encParams << QStringLiteral("stats=%1").arg(QString(target).replace(":", "\\:") + "_2pass.log"); + encParams << QStringLiteral("stats=%1") + .arg(QString(target).replace(":", "\\:") + "_2pass.log"); QString origParams = consumerNode.attribute("svtav1-params"); if (!origParams.isEmpty()) encParams << origParams; @@ -1155,43 +1205,53 @@ QPoint EncodeDock::addConsumerElement(Mlt::Producer *service, QDomDocument &dom, consumerNode.removeAttribute("fastfirstpass"); } } - if (ui->formatCombo->currentIndex() == 0 && - ui->audioCodecCombo->currentIndex() == 0 && - (target.endsWith(".mp4") || target.endsWith(".mov"))) + if (ui->formatCombo->currentIndex() == 0 && ui->audioCodecCombo->currentIndex() == 0 + && (target.endsWith(".mp4") || target.endsWith(".mov"))) consumerNode.setAttribute("strict", "experimental"); if (!ui->disableSubtitlesCheckbox->isChecked()) setSubtitleProperties(consumerNode, service); - return QPoint(consumerNode.hasAttribute("frame_rate_num") ? - consumerNode.attribute("frame_rate_num").toInt() : MLT.profile().frame_rate_num(), - consumerNode.hasAttribute("frame_rate_den") ? - consumerNode.attribute("frame_rate_den").toInt() : MLT.profile().frame_rate_den()); + return QPoint(consumerNode.hasAttribute("frame_rate_num") + ? consumerNode.attribute("frame_rate_num").toInt() + : MLT.profile().frame_rate_num(), + consumerNode.hasAttribute("frame_rate_den") + ? consumerNode.attribute("frame_rate_den").toInt() + : MLT.profile().frame_rate_den()); } -MeltJob *EncodeDock::convertReframe(Mlt::Producer *service, QTemporaryFile *tmp, - const QString &target, int realtime, int pass, const QThread::Priority priority) +MeltJob *EncodeDock::convertReframe(Mlt::Producer *service, + QTemporaryFile *tmp, + const QString &target, + int realtime, + int pass, + const QThread::Priority priority) { MeltJob *job = nullptr; // Look for the reframe filter for (auto i = 0; !job && i < service->filter_count(); ++i) { Mlt::Filter filter(service->filter(i)); - if (!::qstrcmp("reframe", filter.get(kShotcutFilterProperty)) && !filter.get_int("disable")) { + if (!::qstrcmp("reframe", filter.get(kShotcutFilterProperty)) + && !filter.get_int("disable")) { // If it exists, make another XML with new profile based on reframe rect width and height auto rect = filter.anim_get_rect("rect", 0); LOG_DEBUG() << "Found Reframe" << rect.w << "x" << rect.h << tmp->fileName(); Mlt::Profile reframeProfile; reframeProfile.set_explicit(1); reframeProfile.set_colorspace(MLT.profile().colorspace()); - reframeProfile.set_frame_rate(MLT.profile().frame_rate_num(), MLT.profile().frame_rate_den()); + reframeProfile.set_frame_rate(MLT.profile().frame_rate_num(), + MLT.profile().frame_rate_den()); reframeProfile.set_sample_aspect(1, 1); reframeProfile.set_width(rect.w); reframeProfile.set_height(rect.h); auto gcd = Util::greatestCommonDivisor(rect.w, rect.h); reframeProfile.set_display_aspect(rect.w / gcd, rect.h / gcd); - LOG_DEBUG() << "reframe profile" << reframeProfile.width() << "x" << reframeProfile.height(); - Mlt::Producer producer(reframeProfile, "consumer", - (QStringLiteral("xml:%1").arg(tmp->fileName())).toUtf8().constData()); + LOG_DEBUG() << "reframe profile" << reframeProfile.width() << "x" + << reframeProfile.height(); + Mlt::Producer + producer(reframeProfile, + "consumer", + (QStringLiteral("xml:%1").arg(tmp->fileName())).toUtf8().constData()); Mlt::Filter affine; auto rectPropertyName("rect"); // TODO: GPU filters on the tractor do not work yet @@ -1247,7 +1307,10 @@ MeltJob *EncodeDock::convertReframe(Mlt::Producer *service, QTemporaryFile *tmp, dom.setContent(&xmlReader, false); auto fps = addConsumerElement(service, dom, target, realtime, pass); - job = new EncodeJob(QDir::toNativeSeparators(target), dom.toString(2), fps.x(), fps.y(), + job = new EncodeJob(QDir::toNativeSeparators(target), + dom.toString(2), + fps.x(), + fps.y(), priority); tmp->setParent(job); // job gets ownership to delete object and temp file } @@ -1255,8 +1318,11 @@ MeltJob *EncodeDock::convertReframe(Mlt::Producer *service, QTemporaryFile *tmp, return job; } -MeltJob *EncodeDock::createMeltJob(Mlt::Producer *service, const QString &target, int realtime, - int pass, const QThread::Priority priority) +MeltJob *EncodeDock::createMeltJob(Mlt::Producer *service, + const QString &target, + int realtime, + int pass, + const QThread::Priority priority) { QString caption = tr("Export File"); if (Util::warnIfNotWritable(target, this, caption)) @@ -1273,12 +1339,13 @@ MeltJob *EncodeDock::createMeltJob(Mlt::Producer *service, const QString &target QString mytarget = target; if (!ui->disableVideoCheckbox->isChecked()) { const QString &codec = ui->videoCodecCombo->currentText(); - if (codec == "bmp" || codec == "dpx" || codec == "png" || codec == "ppm" || (codec == "libwebp" - && ui->formatCombo->currentText() == "image2") || - codec == "targa" || codec == "tiff" || (codec == "mjpeg" - && ui->formatCombo->currentText() == "image2")) { + if (codec == "bmp" || codec == "dpx" || codec == "png" || codec == "ppm" + || (codec == "libwebp" && ui->formatCombo->currentText() == "image2") + || codec == "targa" || codec == "tiff" + || (codec == "mjpeg" && ui->formatCombo->currentText() == "image2")) { QFileInfo fi(mytarget); - mytarget = QStringLiteral("%1/%2-%05d.%3").arg(fi.path(), fi.baseName(), fi.completeSuffix()); + mytarget + = QStringLiteral("%1/%2-%05d.%3").arg(fi.path(), fi.baseName(), fi.completeSuffix()); } } @@ -1286,9 +1353,10 @@ MeltJob *EncodeDock::createMeltJob(Mlt::Producer *service, const QString &target QScopedPointer tempProducer; if (MLT.isSeekable(service) && service->type() != mlt_service_chain_type) if (ui->fromCombo->currentData().toString() == "clip" - || ui->fromCombo->currentData().toString() == "batch") { + || ui->fromCombo->currentData().toString() == "batch") { QString xml = MLT.XML(service); - tempProducer.reset(new Mlt::Producer(MLT.profile(), "xml-string", xml.toUtf8().constData())); + tempProducer.reset( + new Mlt::Producer(MLT.profile(), "xml-string", xml.toUtf8().constData())); service = tempProducer.data(); int producerIn = tempProducer->get_in(); if (producerIn > 0) { @@ -1296,13 +1364,14 @@ MeltJob *EncodeDock::createMeltJob(Mlt::Producer *service, const QString &target for (int i = 0; i < n; i++) { QScopedPointer filter(tempProducer->filter(i)); if (filter->get_in() > 0) - filter->set_in_and_out(filter->get_in() - producerIn, filter->get_out() - producerIn); + filter->set_in_and_out(filter->get_in() - producerIn, + filter->get_out() - producerIn); } } } // get temp filename - auto tmp = new QTemporaryFile {Util::writableTemporaryFile(target)}; + auto tmp = new QTemporaryFile{Util::writableTemporaryFile(target)}; tmp->open(); QString fileName = tmp->fileName(); auto isProxy = ui->previewScaleCheckBox->isChecked() && Settings.proxyEnabled(); @@ -1320,7 +1389,8 @@ MeltJob *EncodeDock::createMeltJob(Mlt::Producer *service, const QString &target // Check if the target file is a member of the project. QString xml = dom.toString(0); if (xml.contains(QDir::fromNativeSeparators(target))) { - QMessageBox::warning(this, caption, + QMessageBox::warning(this, + caption, tr("You cannot write to a file that is in your project.\n" "Try again with a different folder or file name.")); return nullptr; @@ -1335,15 +1405,19 @@ MeltJob *EncodeDock::createMeltJob(Mlt::Producer *service, const QString &target if (!job) { auto fps = addConsumerElement(service, dom, mytarget, realtime, pass); - job = new EncodeJob(QDir::toNativeSeparators(target), dom.toString(2), fps.x(), fps.y(), + job = new EncodeJob(QDir::toNativeSeparators(target), + dom.toString(2), + fps.x(), + fps.y(), priority); - job->setUseMultiConsumer( - ui->widthSpinner->value() != MLT.profile().width() || - ui->heightSpinner->value() != MLT.profile().height() || - double(ui->aspectNumSpinner->value()) / double(ui->aspectDenSpinner->value()) != MLT.profile().dar() - || - (ui->fromCombo->currentData().toString() != "clip" - && qFloor(ui->fpsSpinner->value() * 10000.0) != qFloor(MLT.profile().fps() * 10000.0))); + job->setUseMultiConsumer(ui->widthSpinner->value() != MLT.profile().width() + || ui->heightSpinner->value() != MLT.profile().height() + || double(ui->aspectNumSpinner->value()) + / double(ui->aspectDenSpinner->value()) + != MLT.profile().dar() + || (ui->fromCombo->currentData().toString() != "clip" + && qFloor(ui->fpsSpinner->value() * 10000.0) + != qFloor(MLT.profile().fps() * 10000.0))); delete tmp; } @@ -1372,7 +1446,8 @@ void EncodeDock::runMelt(const QString &target, int realtime) if (playlist && playlist->is_valid() && playlist->count() > 0) { // Use the first playlist item. QScopedPointer info(playlist->clip_info(0)); - if (!info) return; + if (!info) + return; QString xml = MLT.XML(info->producer); QScopedPointer producer( new Mlt::Producer(MLT.profile(), "xml-string", xml.toUtf8().constData())); @@ -1380,7 +1455,9 @@ void EncodeDock::runMelt(const QString &target, int realtime) m_immediateJob.reset(createMeltJob(producer.data(), target, realtime)); if (m_immediateJob) { m_immediateJob->setIsStreaming(true); - connect(m_immediateJob.data(), SIGNAL(finished(AbstractJob *, bool, QString)), this, + connect(m_immediateJob.data(), + SIGNAL(finished(AbstractJob *, bool, QString)), + this, SLOT(onFinished(AbstractJob *, bool))); m_immediateJob->start(); } @@ -1392,7 +1469,9 @@ void EncodeDock::runMelt(const QString &target, int realtime) m_immediateJob.reset(createMeltJob(service, target, realtime)); if (m_immediateJob) { m_immediateJob->setIsStreaming(true); - connect(m_immediateJob.data(), SIGNAL(finished(AbstractJob *, bool, QString)), this, + connect(m_immediateJob.data(), + SIGNAL(finished(AbstractJob *, bool, QString)), + this, SLOT(onFinished(AbstractJob *, bool))); m_immediateJob->start(); } @@ -1405,13 +1484,11 @@ class FindAnalysisFilterParser : public Mlt::Parser QList m_filters; public: - FindAnalysisFilterParser() : Mlt::Parser() + FindAnalysisFilterParser() + : Mlt::Parser() {} - QList &filters() - { - return m_filters; - } + QList &filters() { return m_filters; } int on_start_filter(Mlt::Filter *filter) { @@ -1443,74 +1520,23 @@ class FindAnalysisFilterParser : public Mlt::Parser } return 0; } - int on_start_producer(Mlt::Producer *) - { - return 0; - } - int on_end_producer(Mlt::Producer *) - { - return 0; - } - int on_start_playlist(Mlt::Playlist *) - { - return 0; - } - int on_end_playlist(Mlt::Playlist *) - { - return 0; - } - int on_start_tractor(Mlt::Tractor *) - { - return 0; - } - int on_end_tractor(Mlt::Tractor *) - { - return 0; - } - int on_start_multitrack(Mlt::Multitrack *) - { - return 0; - } - int on_end_multitrack(Mlt::Multitrack *) - { - return 0; - } - int on_start_track() - { - return 0; - } - int on_end_track() - { - return 0; - } - int on_end_filter(Mlt::Filter *) - { - return 0; - } - int on_start_transition(Mlt::Transition *) - { - return 0; - } - int on_end_transition(Mlt::Transition *) - { - return 0; - } - int on_start_chain(Mlt::Chain *) - { - return 0; - } - int on_end_chain(Mlt::Chain *) - { - return 0; - } - int on_start_link(Mlt::Link *) - { - return 0; - } - int on_end_link(Mlt::Link *) - { - return 0; - } + int on_start_producer(Mlt::Producer *) { return 0; } + int on_end_producer(Mlt::Producer *) { return 0; } + int on_start_playlist(Mlt::Playlist *) { return 0; } + int on_end_playlist(Mlt::Playlist *) { return 0; } + int on_start_tractor(Mlt::Tractor *) { return 0; } + int on_end_tractor(Mlt::Tractor *) { return 0; } + int on_start_multitrack(Mlt::Multitrack *) { return 0; } + int on_end_multitrack(Mlt::Multitrack *) { return 0; } + int on_start_track() { return 0; } + int on_end_track() { return 0; } + int on_end_filter(Mlt::Filter *) { return 0; } + int on_start_transition(Mlt::Transition *) { return 0; } + int on_end_transition(Mlt::Transition *) { return 0; } + int on_start_chain(Mlt::Chain *) { return 0; } + int on_end_chain(Mlt::Chain *) { return 0; } + int on_start_link(Mlt::Link *) { return 0; } + int on_end_link(Mlt::Link *) { return 0; } }; void EncodeDock::enqueueAnalysis() @@ -1522,12 +1548,13 @@ void EncodeDock::enqueueAnalysis() parser.start(*producer); // If there are Filters show a dialog. if (parser.filters().size() > 0) { - QMessageBox dialog(QMessageBox::Question, - windowTitle(), - tr("Shotcut found filters that require analysis jobs that have not run.\n" - "Do you want to run the analysis jobs now?"), - QMessageBox::No | QMessageBox::Yes, - this); + QMessageBox + dialog(QMessageBox::Question, + windowTitle(), + tr("Shotcut found filters that require analysis jobs that have not run.\n" + "Do you want to run the analysis jobs now?"), + QMessageBox::No | QMessageBox::Yes, + this); dialog.setDefaultButton(QMessageBox::Yes); dialog.setEscapeButton(QMessageBox::No); dialog.setWindowModality(QmlApplication::dialogModality()); @@ -1554,7 +1581,9 @@ void EncodeDock::enqueueMelt(const QStringList &targets, int realtime) && !ui->videoCodecCombo->currentText().endsWith("_qsv") && !ui->videoCodecCombo->currentText().endsWith("_videotoolbox") && !ui->videoCodecCombo->currentText().endsWith("_vaapi") - && ui->dualPassCheckbox->isEnabled() && ui->dualPassCheckbox->isChecked()) ? 1 : 0; + && ui->dualPassCheckbox->isEnabled() && ui->dualPassCheckbox->isChecked()) + ? 1 + : 0; if (!service) { // For each playlist item. auto playlist = MAIN.binPlaylist(); @@ -1562,7 +1591,8 @@ void EncodeDock::enqueueMelt(const QStringList &targets, int realtime) int n = playlist->count(); for (int i = 0; i < n; i++) { QScopedPointer info(playlist->clip_info(i)); - if (!info) continue; + if (!info) + continue; QString xml = MLT.XML(info->producer); QScopedPointer producer( new Mlt::Producer(MLT.profile(), "xml-string", xml.toUtf8().constData())); @@ -1605,12 +1635,12 @@ void EncodeDock::encode(const QString &target) Mlt::Properties *p = collectProperties(-1); if (p && p->is_valid()) { for (int i = 0; i < p->count(); i++) - MLT.consumer()->set(QStringLiteral("1.%1").arg(p->get_name(i)).toLatin1().constData(), p->get(i)); + MLT.consumer()->set(QStringLiteral("1.%1").arg(p->get_name(i)).toLatin1().constData(), + p->get(i)); } delete p; - if (ui->formatCombo->currentIndex() == 0 && - ui->audioCodecCombo->currentIndex() == 0 && - (target.endsWith(".mp4") || target.endsWith(".mov"))) + if (ui->formatCombo->currentIndex() == 0 && ui->audioCodecCombo->currentIndex() == 0 + && (target.endsWith(".mp4") || target.endsWith(".mov"))) MLT.consumer()->set("1.strict", "experimental"); MLT.setVolume(volume); MLT.play(); @@ -1750,7 +1780,8 @@ void EncodeDock::onVideoCodecComboChanged(int index, bool ignorePreset, bool res ui->dualPassCheckbox->setChecked(false); ui->dualPassCheckbox->setEnabled(false); } else if (vcodec.endsWith("_qsv")) { - if (vcodec.startsWith("hevc_") && !ui->advancedTextEdit->toPlainText().contains("load_plugin=")) + if (vcodec.startsWith("hevc_") + && !ui->advancedTextEdit->toPlainText().contains("load_plugin=")) ui->advancedTextEdit->appendPlainText("\nload_plugin=hevc_hw\n"); if (resetBframes && vcodec.startsWith("av1_")) ui->bFramesSpinner->setValue(0); @@ -1781,8 +1812,10 @@ static double getBufferSize(Mlt::Properties &preset, const char *property) double size = preset.get_double(property); const QString &s = preset.get(property); // evaluate suffix - if (s.endsWith('k')) size *= 1000; - if (s.endsWith('M')) size *= 1000000; + if (s.endsWith('k')) + size *= 1000; + if (s.endsWith('M')) + size *= 1000000; // convert to KiB return double(qRound(size / 1024 / 8 * 100)) / 100; } @@ -1795,7 +1828,7 @@ void EncodeDock::on_presetsTree_clicked(const QModelIndex &index) if (!name.isEmpty()) { Mlt::Properties *preset; if (m_presetsModel.data(index.parent()).toString() == tr("Custom") - || m_presetsModel.data(index.parent().parent()).toString() == tr("Custom")) { + || m_presetsModel.data(index.parent().parent()).toString() == tr("Custom")) { ui->removePresetButton->setEnabled(true); preset = new Mlt::Properties(); QDir dir(Settings.appDataLocation()); @@ -1803,7 +1836,8 @@ void EncodeDock::on_presetsTree_clicked(const QModelIndex &index) preset->load(dir.absoluteFilePath(name).toLatin1().constData()); } else { ui->removePresetButton->setEnabled(false); - preset = new Mlt::Properties((mlt_properties) m_presets->get_data(name.toLatin1().constData())); + preset = new Mlt::Properties( + (mlt_properties) m_presets->get_data(name.toLatin1().constData())); } if (preset->is_valid()) { QStringList textParts = name.split('/'); @@ -1866,8 +1900,12 @@ void EncodeDock::on_encodeButton_clicked() QString caption = seekable ? tr("Export File") : tr("Capture File"); if (ui->fromCombo->currentData().toString() == "batch") { caption = tr("Export Files"); - MultiFileExportDialog dialog(tr("Export Each Playlist Bin Item"), MAIN.binPlaylist(), - directory, projectBaseName, m_extension, this); + MultiFileExportDialog dialog(tr("Export Each Playlist Bin Item"), + MAIN.binPlaylist(), + directory, + projectBaseName, + m_extension, + this); if (dialog.exec() != QDialog::Accepted) { return; } @@ -1875,7 +1913,8 @@ void EncodeDock::on_encodeButton_clicked() } else { QString nameFilter; if (!m_extension.isEmpty()) - nameFilter = tr("%1 (*.%2);;All Files (*)").arg(ui->formatCombo->currentText(), m_extension); + nameFilter + = tr("%1 (*.%2);;All Files (*)").arg(ui->formatCombo->currentText(), m_extension); else nameFilter = tr("Determined by Export (*)"); if (!m_extension.isEmpty()) { @@ -1885,8 +1924,12 @@ void EncodeDock::on_encodeButton_clicked() } else if (!MAIN.fileName().isEmpty()) { directory += "/" + projectBaseName; } - QString newName = QFileDialog::getSaveFileName(this, caption, directory, nameFilter, - nullptr, Util::getFileDialogOptions()); + QString newName = QFileDialog::getSaveFileName(this, + caption, + directory, + nameFilter, + nullptr, + Util::getFileDialogOptions()); if (!newName.isEmpty() && !m_extension.isEmpty()) { QFileInfo fi(newName); if (fi.suffix().isEmpty()) { @@ -1933,7 +1976,9 @@ void EncodeDock::on_encodeButton_clicked() MAIN.hideProducer(); m_immediateJob->setIsStreaming(true); - connect(m_immediateJob.data(), SIGNAL(finished(AbstractJob *, bool, QString)), this, + connect(m_immediateJob.data(), + SIGNAL(finished(AbstractJob *, bool, QString)), + this, SLOT(onFinished(AbstractJob *, bool))); ui->encodeButton->setText(tr("Stop Capture")); @@ -2023,8 +2068,8 @@ void EncodeDock::onReframeChanged() // If reframe is on and its resolution changed if (enabled) { auto rect = reframe.anim_get_rect("rect", 0); - if (rect.w > 0 && rect.h > 0 && (rect.w != ui->widthSpinner->value() - || rect.h != ui->heightSpinner->value())) { + if (rect.w > 0 && rect.h > 0 + && (rect.w != ui->widthSpinner->value() || rect.h != ui->heightSpinner->value())) { ui->widthSpinner->setValue(rect.w); ui->heightSpinner->setValue(rect.h); auto gcd = Util::greatestCommonDivisor(rect.w, rect.h); @@ -2090,7 +2135,6 @@ void EncodeDock::on_addPresetButton_clicked() AddEncodePresetDialog dialog(this); QStringList ls; - if (data && data->is_valid()) { // Revert collectProperties() overwriting user-specified advanced options (x265-params). foreach (QString line, ui->advancedTextEdit->toPlainText().split("\n")) @@ -2270,9 +2314,9 @@ void EncodeDock::on_audioRateControlCombo_activated(int index) void EncodeDock::on_scanModeCombo_currentIndexChanged(int index) { - if (index == 0) { // Interlaced + if (index == 0) { // Interlaced ui->fieldOrderCombo->removeItem(2); // None, if it exists - } else { // Progressive + } else { // Progressive if (ui->fieldOrderCombo->count() < 3) ui->fieldOrderCombo->addItem(tr("None")); ui->fieldOrderCombo->setCurrentIndex(ui->fieldOrderCombo->count() - 1); @@ -2293,10 +2337,14 @@ bool PresetsProxyModel::filterAcceptsRow(int source_row, const QModelIndex &sour // Show categories with descendants that match. for (int i = 0; i < sourceModel()->rowCount(index); i++) - if (filterAcceptsRow(i, index)) return true; + if (filterAcceptsRow(i, index)) + return true; - return sourceModel()->data(index).toString().contains(filterRegularExpression()) || - sourceModel()->data(index, Qt::ToolTipRole).toString().contains(filterRegularExpression()); + return sourceModel()->data(index).toString().contains(filterRegularExpression()) + || sourceModel() + ->data(index, Qt::ToolTipRole) + .toString() + .contains(filterRegularExpression()); } void EncodeDock::on_resetButton_clicked() @@ -2324,7 +2372,7 @@ void EncodeDock::on_videoBufferDurationChanged() { QString vb = ui->videoBitrateCombo->currentText(); vb.replace('k', "").replace('M', "000"); - double duration = (double)ui->videoBufferSizeSpinner->value() * 8.0 / vb.toDouble(); + double duration = (double) ui->videoBufferSizeSpinner->value() * 8.0 / vb.toDouble(); QString label = tr("KiB (%1s)").arg(duration); ui->videoBufferSizeSuffixLabel->setText(label); } @@ -2370,7 +2418,7 @@ void EncodeDock::on_audioCodecCombo_currentIndexChanged(int index) on_audioQualitySpinner_valueChanged(ui->audioQualitySpinner->value()); } -void EncodeDock::setAudioChannels( int channels ) +void EncodeDock::setAudioChannels(int channels) { switch (channels) { case 1: @@ -2448,7 +2496,7 @@ void EncodeDock::on_hwencodeCheckBox_clicked(bool checked) ui->hwencodeCheckBox->setChecked(false); } Settings.setEncodeUseHardware(ui->hwencodeCheckBox->isChecked()); - std::unique_ptr properties {collectProperties(0, true)}; + std::unique_ptr properties{collectProperties(0, true)}; resetOptions(); if (properties && properties->is_valid()) { QString value = QString::fromLatin1(properties->get("vcodec")); @@ -2524,7 +2572,8 @@ void EncodeDock::on_videoQualitySpinner_valueChanged(int vq) QString s; if (vcodec.startsWith("libx264") || vcodec == "libx265") { s = QStringLiteral("crf=%1").arg(TO_ABSOLUTE(51, 0, vq)); - } else if (vcodec.startsWith("libvpx") || vcodec.startsWith("libaom-") || vcodec == "libsvtav1") { + } else if (vcodec.startsWith("libvpx") || vcodec.startsWith("libaom-") + || vcodec == "libsvtav1") { s = QStringLiteral("crf=%1").arg(TO_ABSOLUTE(63, 0, vq)); } else if (vcodec.contains("nvenc")) { vq = TO_ABSOLUTE(51, 0, vq); @@ -2582,17 +2631,35 @@ bool EncodeDock::detectHardwareEncoders() LOG_INFO() << "checking for" << codec; QProcess proc; QStringList args; - args << "-hide_banner" << "-f" << "lavfi" << "-i" << "color=s=640x360" << "-frames" << "1" << "-an"; + args << "-hide_banner" + << "-f" + << "lavfi" + << "-i" + << "color=s=640x360" + << "-frames" + << "1" + << "-an"; if (codec.endsWith("_vaapi")) - args << "-init_hw_device" << "vaapi=vaapi0:" << "-filter_hw_device" << "vaapi0" << "-vf" << - "format=nv12,hwupload"; + args << "-init_hw_device" + << "vaapi=vaapi0:" + << "-filter_hw_device" + << "vaapi0" + << "-vf" + << "format=nv12,hwupload"; else if (codec == "hevc_qsv") - args << "-load_plugin" << "hevc_hw"; + args << "-load_plugin" + << "hevc_hw"; else if (codec.endsWith("_videotoolbox")) - args << "-pix_fmt" << "nv12"; + args << "-pix_fmt" + << "nv12"; else if (codec.endsWith("_mf")) - args << "-pix_fmt" << "nv12" << "-hw_encoding" << "true"; - args << "-c:v" << codec << "-f" << "rawvideo" << "pipe:"; + args << "-pix_fmt" + << "nv12" + << "-hw_encoding" + << "true"; + args << "-c:v" << codec << "-f" + << "rawvideo" + << "pipe:"; LOG_DEBUG() << ffmpegPath.absoluteFilePath() + " " + args.join(' '); proc.setStandardOutputFile(QProcess::nullDevice()); proc.setReadChannel(QProcess::StandardError); @@ -2608,7 +2675,8 @@ bool EncodeDock::detectHardwareEncoders() hwlist << codec; } else { QString output = proc.readAll(); - foreach (const QString &line, output.split(QRegularExpression("[\r\n]"), Qt::SkipEmptyParts)) + foreach (const QString &line, + output.split(QRegularExpression("[\r\n]"), Qt::SkipEmptyParts)) LOG_DEBUG() << line; } } @@ -2627,7 +2695,8 @@ QString &EncodeDock::defaultFormatExtension() QFileInfo ffmpegPath(qApp->applicationDirPath(), "ffmpeg"); QProcess proc; QStringList args; - args << "-hide_banner" << "-h" << format.prepend("muxer="); + args << "-hide_banner" + << "-h" << format.prepend("muxer="); LOG_DEBUG() << ffmpegPath.absoluteFilePath() << args.join(' '); proc.setStandardErrorFile(QProcess::nullDevice()); proc.setReadChannel(QProcess::StandardOutput); @@ -2818,11 +2887,12 @@ bool EncodeDock::checkForMissingFiles() } QScopedPointer tmp; if (MAIN.fileName().isEmpty()) { - tmp.reset(Util::writableTemporaryFile(QStandardPaths::writableLocation( - QStandardPaths::AppDataLocation) + "/")); + tmp.reset(Util::writableTemporaryFile( + QStandardPaths::writableLocation(QStandardPaths::AppDataLocation) + "/")); } else { QFileInfo info(MAIN.fileName()); - QString templateFileName = QStringLiteral("%1.XXXXXX").arg(QCoreApplication::applicationName()); + QString templateFileName + = QStringLiteral("%1.XXXXXX").arg(QCoreApplication::applicationName()); tmp.reset(new QTemporaryFile(info.dir().filePath(templateFileName))); } tmp->open(); @@ -2853,7 +2923,8 @@ bool EncodeDock::checkForMissingFiles() void EncodeDock::on_resolutionComboBox_activated(int arg1) { - if (ui->resolutionComboBox->itemText(arg1).isEmpty()) return; + if (ui->resolutionComboBox->itemText(arg1).isEmpty()) + return; auto parts = ui->resolutionComboBox->itemText(arg1).split(' '); ui->widthSpinner->setValue(parts[0].toInt()); ui->heightSpinner->setValue(parts[2].toInt()); @@ -2881,9 +2952,10 @@ void EncodeDock::on_reframeButton_clicked() void EncodeDock::on_aspectNumSpinner_valueChanged(int value) { if (!MLT.isClosedClip() && ui->widthSpinner->isEnabled() - && double(ui->aspectNumSpinner->value()) / double(ui->aspectDenSpinner->value()) != - MLT.profile().dar()) - showResampleWarning(tr("Aspect ratio does not match project Video Mode, which causes black bars.")); + && double(ui->aspectNumSpinner->value()) / double(ui->aspectDenSpinner->value()) + != MLT.profile().dar()) + showResampleWarning( + tr("Aspect ratio does not match project Video Mode, which causes black bars.")); else hideResampleWarning(); } @@ -2893,7 +2965,6 @@ void EncodeDock::on_aspectDenSpinner_valueChanged(int value) on_aspectNumSpinner_valueChanged(value); } - void EncodeDock::setReframeEnabled(bool enabled) { ui->widthSpinner->setDisabled(enabled); @@ -2920,7 +2991,7 @@ void EncodeDock::hideResampleWarning(bool hide) void EncodeDock::checkFrameRate() { if (!MLT.isClosedClip() && ui->fromCombo->currentData().toString() != "clip" - && qFloor(ui->fpsSpinner->value() * 10000.0) > qFloor(MLT.profile().fps() * 10000.0)) + && qFloor(ui->fpsSpinner->value() * 10000.0) > qFloor(MLT.profile().fps() * 10000.0)) showResampleWarning( tr("Frame rate is higher than project Video Mode, which causes frames to repeat.")); else diff --git a/src/docks/encodedock.h b/src/docks/encodedock.h old mode 100755 new mode 100644 index 892a67fe74..b08466a870 --- a/src/docks/encodedock.h +++ b/src/docks/encodedock.h @@ -20,12 +20,12 @@ #include "settings.h" +#include #include #include -#include #include +#include #include -#include class QTreeWidgetItem; class QTemporaryFile; @@ -38,7 +38,7 @@ namespace Mlt { class Service; class Producer; class Filter; -} +} // namespace Mlt class PresetsProxyModel : public QSortFilterProxyModel { @@ -109,7 +109,7 @@ private slots: void on_audioCodecCombo_currentIndexChanged(int index); - void setAudioChannels( int channels ); + void setAudioChannels(int channels); void on_widthSpinner_editingFinished(); @@ -169,11 +169,18 @@ private slots: Mlt::Properties *collectProperties(int realtime, bool includeProfile = false); void collectProperties(QDomElement &node, int realtime); void setSubtitleProperties(QDomElement &node, Mlt::Producer *service); - QPoint addConsumerElement(Mlt::Producer *service, QDomDocument &dom, const QString &target, - int realtime, int pass); - MeltJob *convertReframe(Mlt::Producer *service, QTemporaryFile *tmp, const QString &target, - int realtime, int pass, const QThread::Priority priority); - MeltJob *createMeltJob(Mlt::Producer *service, const QString &target, int realtime, int pass = 0, + QPoint addConsumerElement( + Mlt::Producer *service, QDomDocument &dom, const QString &target, int realtime, int pass); + MeltJob *convertReframe(Mlt::Producer *service, + QTemporaryFile *tmp, + const QString &target, + int realtime, + int pass, + const QThread::Priority priority); + MeltJob *createMeltJob(Mlt::Producer *service, + const QString &target, + int realtime, + int pass = 0, const QThread::Priority priority = Settings.jobPriority()); void runMelt(const QString &target, int realtime = -1); void enqueueAnalysis(); diff --git a/src/docks/filesdock.cpp b/src/docks/filesdock.cpp index 7e70febad8..7f1bd5c573 100644 --- a/src/docks/filesdock.cpp +++ b/src/docks/filesdock.cpp @@ -17,49 +17,50 @@ #include "filesdock.h" #include "ui_filesdock.h" + +#include "Logger.h" #include "actions.h" +#include "database.h" +#include "dialogs/listselectiondialog.h" #include "mainwindow.h" +#include "models/playlistmodel.h" +#include "qmltypes/qmlapplication.h" #include "settings.h" +#include "util.h" #include "widgets/docktoolbar.h" +#include "widgets/lineeditclear.h" #include "widgets/playlisticonview.h" -#include "widgets/playlisttable.h" #include "widgets/playlistlistview.h" -#include "util.h" -#include "qmltypes/qmlapplication.h" -#include "widgets/lineeditclear.h" -#include "models/playlistmodel.h" -#include "database.h" -#include "dialogs/listselectiondialog.h" -#include +#include "widgets/playlisttable.h" +#include +#include +#include +#include +#include +#include +#include #include +#include #include -#include -#include +#include +#include #include -#include -#include -#include -#include -#include -#include -#include +#include #include -#include -#include #include +#include +#include +#include #include -#include -#include -#include -#include +#include static const auto kTilePaddingPx = 10; static const auto kTreeViewWidthPx = 150; static const auto kDetailedMode = QLatin1String("detailed"); static const auto kIconsMode = QLatin1String("icons"); static const auto kTiledMode = QLatin1String("tiled"); -static const QSet kAudioExtensions { +static const QSet kAudioExtensions{ QLatin1String("m4a"), QLatin1String("wav"), QLatin1String("mp3"), @@ -70,7 +71,7 @@ static const QSet kAudioExtensions { QLatin1String("wma"), QLatin1String("mka"), }; -static const QSet kImageExtensions { +static const QSet kImageExtensions{ QLatin1String("jpg"), QLatin1String("jpeg"), QLatin1String("png"), @@ -82,29 +83,14 @@ static const QSet kImageExtensions { QLatin1String("gif"), QLatin1String("tga"), }; -static const QSet kOtherExtensions { - QLatin1String("mlt"), - QLatin1String("xml"), - QLatin1String("txt"), - QLatin1String("pdf"), - QLatin1String("doc"), - QLatin1String("gpx"), - QLatin1String("rawr"), - QLatin1String("stab"), - QLatin1String("srt"), - QLatin1String("so"), - QLatin1String("dll"), - QLatin1String("exe"), - QLatin1String("zip"), - QLatin1String("edl"), - QLatin1String("kdenlive"), - QLatin1String("osp"), - QLatin1String("blend"), - QLatin1String("swf"), - QLatin1String("cube"), - QLatin1String("json"), +static const QSet kOtherExtensions{ + QLatin1String("mlt"), QLatin1String("xml"), QLatin1String("txt"), QLatin1String("pdf"), + QLatin1String("doc"), QLatin1String("gpx"), QLatin1String("rawr"), QLatin1String("stab"), + QLatin1String("srt"), QLatin1String("so"), QLatin1String("dll"), QLatin1String("exe"), + QLatin1String("zip"), QLatin1String("edl"), QLatin1String("kdenlive"), QLatin1String("osp"), + QLatin1String("blend"), QLatin1String("swf"), QLatin1String("cube"), QLatin1String("json"), }; -static const QSet kVideoExtensions { +static const QSet kVideoExtensions{ QLatin1String("mp4"), QLatin1String("m4v"), QLatin1String("avi"), @@ -123,9 +109,13 @@ static const QSet kVideoExtensions { QLatin1String("wmv"), }; -static void cacheMediaType(FilesModel *model, const QString &filePath, int mediaType, +static void cacheMediaType(FilesModel *model, + const QString &filePath, + int mediaType, const QModelIndex &index); -static void cacheThumbnail(FilesModel *model, const QString &filePath, QImage &image, +static void cacheThumbnail(FilesModel *model, + const QString &filePath, + QImage &image, const QModelIndex &index); class FilesMediaTypeTask : public QRunnable @@ -140,13 +130,12 @@ class FilesMediaTypeTask : public QRunnable , m_model(model) , m_filePath(filePath) , m_index(index) - { - } + {} public: void run() { - static Mlt::Profile profile {"atsc_720p_60"}; + static Mlt::Profile profile{"atsc_720p_60"}; Mlt::Producer producer(profile, m_filePath.toUtf8().constData()); auto mediaType = PlaylistModel::Other; if (producer.is_valid()) { @@ -156,7 +145,7 @@ class FilesMediaTypeTask : public QRunnable auto service = QString::fromLatin1(producer.get("mlt_service")); if (service.startsWith(QLatin1String("avformat"))) { if (producer.get_int("video_index") > -1 - && Util::getSuggestedFrameRate(&producer) != 90000) + && Util::getSuggestedFrameRate(&producer) != 90000) mediaType = PlaylistModel::Video; else if (producer.get_int("audio_index") > -1) mediaType = PlaylistModel::Audio; @@ -180,8 +169,7 @@ class FilesThumbnailTask : public QRunnable , m_model(model) , m_filePath(filePath) , m_index(index) - { - } + {} static QString cacheKey(const QString &filePath) { @@ -195,10 +183,8 @@ class FilesThumbnailTask : public QRunnable { if (producer.is_valid()) { auto service = QString::fromLatin1(producer.get("mlt_service")); - return (service.startsWith("avformat") || - service == "qimage" || - service == "pixbuf" || - service == "glaxnimate"); + return (service.startsWith("avformat") || service == "qimage" || service == "pixbuf" + || service == "glaxnimate"); } return false; } @@ -208,7 +194,7 @@ class FilesThumbnailTask : public QRunnable { LOG_DEBUG() << "Mlt::Producer" << m_filePath; QImage image; - static Mlt::Profile profile {"atsc_720p_60"}; + static Mlt::Profile profile{"atsc_720p_60"}; Mlt::Producer producer(profile, "abnormal", m_filePath.toUtf8().constData()); if (isValidService(producer)) { Mlt::Filter scaler(profile, "swscale"); @@ -241,8 +227,7 @@ class FilesModel : public QFileSystemModel explicit FilesModel(FilesDock *parent = nullptr) : QFileSystemModel(parent) , m_dock(parent) - { - } + {} QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override { @@ -342,9 +327,9 @@ class FilesModel : public QFileSystemModel image = QImage(64, 64, QImage::Format_ARGB32); image.fill(Qt::transparent); if (index.isValid()) { - const auto pixmap = QFileSystemModel::data(index, - Qt::DecorationRole).value().pixmap({16, 16}, - m_dock->devicePixelRatioF()); + const auto pixmap = QFileSystemModel::data(index, Qt::DecorationRole) + .value() + .pixmap({16, 16}, m_dock->devicePixelRatioF()); QPainter painter(&image); QIcon(pixmap).paint(&painter, image.rect()); } @@ -356,33 +341,34 @@ class FilesModel : public QFileSystemModel } }; -static void cacheMediaType(FilesModel *model, const QString &filePath, int mediaType, +static void cacheMediaType(FilesModel *model, + const QString &filePath, + int mediaType, const QModelIndex &index) { model->cacheMediaType(filePath, mediaType, index); } -static void cacheThumbnail(FilesModel *model, const QString &filePath, QImage &image, +static void cacheThumbnail(FilesModel *model, + const QString &filePath, + QImage &image, const QModelIndex &index) { model->cacheThumbnail(filePath, image, index); } - class FilesTileDelegate : public QStyledItemDelegate { Q_OBJECT public: FilesTileDelegate(QAbstractItemView *view, QWidget *parent = nullptr) - : QStyledItemDelegate(parent), - m_view(view) + : QStyledItemDelegate(parent) + , m_view(view) { - connect(&Settings, SIGNAL(playlistThumbnailsChanged()), - SLOT(emitSizeHintChanged())); + connect(&Settings, SIGNAL(playlistThumbnailsChanged()), SLOT(emitSizeHintChanged())); } - void paint(QPainter *painter, - const QStyleOptionViewItem &option, const QModelIndex &index) const + void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { const QImage thumb = index.data(FilesModel::ThumbnailRole).value(); const int lineHeight = painter->fontMetrics().height(); @@ -413,12 +399,17 @@ class FilesTileDelegate : public QStyledItemDelegate textPoint.setY(textPoint.y() + lineHeight); painter->setFont(boldFont); painter->drawText(textPoint, - painter->fontMetrics().elidedText(fileInfo.fileName(), Qt::ElideMiddle, textRect.width())); + painter->fontMetrics().elidedText(fileInfo.fileName(), + Qt::ElideMiddle, + textRect.width())); painter->setFont(oldFont); textPoint.setY(textPoint.y() + lineHeight); - painter->drawText(textPoint, tr("Date: %1").arg( - index.data(FilesModel::DateRole).toDateTime().toString("yyyy-MM-dd HH:mm:ss"))); + painter->drawText(textPoint, + tr("Date: %1") + .arg(index.data(FilesModel::DateRole) + .toDateTime() + .toString("yyyy-MM-dd HH:mm:ss"))); textPoint.setY(textPoint.y() + lineHeight); if (!fileInfo.isDir()) { // Get the text of the second (size) column @@ -436,14 +427,10 @@ class FilesTileDelegate : public QStyledItemDelegate } private slots: - void emitSizeHintChanged() - { - emit sizeHintChanged(QModelIndex()); - } + void emitSizeHintChanged() { emit sizeHintChanged(QModelIndex()); } private: QAbstractItemView *m_view; - }; class FilesProxyModel : public QSortFilterProxyModel @@ -451,8 +438,7 @@ class FilesProxyModel : public QSortFilterProxyModel public: explicit FilesProxyModel(QObject *parent = nullptr) : QSortFilterProxyModel(parent) - { - } + {} void setMediaTypes(QList types) { @@ -473,7 +459,9 @@ class FilesProxyModel : public QSortFilterProxyModel } // Text search - return index.data(QFileSystemModel::FileNameRole).toString().contains(filterRegularExpression()); + return index.data(QFileSystemModel::FileNameRole) + .toString() + .contains(filterRegularExpression()); } bool lessThan(const QModelIndex &left, const QModelIndex &right) const override @@ -510,28 +498,33 @@ FilesDock::FilesDock(QWidget *parent) const auto ls = QStandardPaths::standardLocations(QStandardPaths::HomeLocation); ui->locationsCombo->addItem(tr("Home", "The user's home folder in the file system"), ls.first()); ui->locationsCombo->addItem(tr("Current Project"), ""); - ui->locationsCombo->addItem(tr("Documents"), - QStandardPaths::standardLocations(QStandardPaths::DocumentsLocation).first()); + ui->locationsCombo + ->addItem(tr("Documents"), + QStandardPaths::standardLocations(QStandardPaths::DocumentsLocation).first()); #if defined(Q_OS_MAC) - ui->locationsCombo->addItem(tr("Movies", - "The system-provided videos folder called Movies on macOS"), - QStandardPaths::standardLocations(QStandardPaths::MoviesLocation).first()); + ui->locationsCombo + ->addItem(tr("Movies", "The system-provided videos folder called Movies on macOS"), + QStandardPaths::standardLocations(QStandardPaths::MoviesLocation).first()); #endif - ui->locationsCombo->addItem(tr("Music"), - QStandardPaths::standardLocations(QStandardPaths::MusicLocation).first()); - ui->locationsCombo->addItem(tr("Pictures", "The system-provided photos folder"), - QStandardPaths::standardLocations(QStandardPaths::PicturesLocation).first()); + ui->locationsCombo + ->addItem(tr("Music"), + QStandardPaths::standardLocations(QStandardPaths::MusicLocation).first()); + ui->locationsCombo + ->addItem(tr("Pictures", "The system-provided photos folder"), + QStandardPaths::standardLocations(QStandardPaths::PicturesLocation).first()); #if defined(Q_OS_MAC) - ui->locationsCombo->addItem(tr("Volumes", - "The macOS file system location where external drives and network shares are mounted"), - "/Volumes"); + ui->locationsCombo->addItem( + tr("Volumes", + "The macOS file system location where external drives and network shares are mounted"), + "/Volumes"); #else - ui->locationsCombo->addItem(tr("Videos"), - QStandardPaths::standardLocations(QStandardPaths::MoviesLocation).first()); + ui->locationsCombo + ->addItem(tr("Videos"), + QStandardPaths::standardLocations(QStandardPaths::MoviesLocation).first()); #endif ui->removeLocationButton->setDisabled(true); auto n = ui->locationsCombo->count(); - connect(ui->locationsCombo, &QComboBox::currentIndexChanged, this, [ = ](int index) { + connect(ui->locationsCombo, &QComboBox::currentIndexChanged, this, [=](int index) { ui->removeLocationButton->setEnabled(index >= n); }); @@ -542,7 +535,9 @@ FilesDock::FilesDock(QWidget *parent) ui->locationsCombo->addItem(name, path); } ui->locationsCombo->setEditText(QDir::toNativeSeparators(Settings.filesCurrentDir())); - connect(ui->locationsCombo->lineEdit(), &QLineEdit::editingFinished, this, + connect(ui->locationsCombo->lineEdit(), + &QLineEdit::editingFinished, + this, &FilesDock::onLocationsEditingFinished); m_filesModel = new FilesModel(this); @@ -558,7 +553,9 @@ FilesDock::FilesDock(QWidget *parent) m_filesProxyModel->setSortCaseSensitivity(Qt::CaseInsensitive); m_filesProxyModel->setRecursiveFilteringEnabled(true); m_selectionModel = new QItemSelectionModel(m_filesProxyModel, this); - connect(m_selectionModel, &QItemSelectionModel::selectionChanged, this, + connect(m_selectionModel, + &QItemSelectionModel::selectionChanged, + this, &FilesDock::selectionChanged); m_dirsModel.reset(new QFileSystemModel); @@ -581,14 +578,12 @@ FilesDock::FilesDock(QWidget *parent) ui->treeView->setExpanded(homeIndex, true); ui->treeView->scrollTo(homeIndex); ui->treeView->setCurrentIndex(homeIndex); - QTimer::singleShot(0, this, [ = ]() { - ui->treeView->setVisible(Settings.filesFoldersOpen()); - }); - connect(ui->treeView, &QWidget::customContextMenuRequested, this, [ = ](const QPoint & pos) { + QTimer::singleShot(0, this, [=]() { ui->treeView->setVisible(Settings.filesFoldersOpen()); }); + connect(ui->treeView, &QWidget::customContextMenuRequested, this, [=](const QPoint &pos) { QMenu menu(this); menu.exec(mapToGlobal(pos)); }); - connect(ui->treeView, &QAbstractItemView::clicked, this, [ = ](const QModelIndex & index) { + connect(ui->treeView, &QAbstractItemView::clicked, this, [=](const QModelIndex &index) { auto filePath = m_dirsModel->filePath(index); LOG_DEBUG() << "clicked" << filePath; auto sourceIndex = m_filesModel->setRootPath(filePath); @@ -613,8 +608,8 @@ FilesDock::FilesDock(QWidget *parent) DockToolBar *toolbar = new DockToolBar(tr("Files Controls")); toolbar->setAreaHint(Qt::BottomToolBarArea); QToolButton *menuButton = new QToolButton(); - menuButton->setIcon(QIcon::fromTheme("show-menu", - QIcon(":/icons/oxygen/32x32/actions/show-menu.png"))); + menuButton->setIcon( + QIcon::fromTheme("show-menu", QIcon(":/icons/oxygen/32x32/actions/show-menu.png"))); menuButton->setToolTip(tr("Files Menu")); menuButton->setAutoRaise(true); menuButton->setPopupMode(QToolButton::QToolButton::InstantPopup); @@ -639,33 +634,35 @@ FilesDock::FilesDock(QWidget *parent) ui->filtersLayout->addWidget(toolbar); auto toolbar2 = new QToolBar(tr("Files Filters")); - QString styleSheet = QStringLiteral( - "QToolButton {" - " background-color: palette(background);" - " border-style: solid;" - " border-width: 1px;" - " border-radius: 3px;" - " border-color: palette(shadow);" - " color: palette(button-text);" - "}" - "QToolButton:checked {" - " color:palette(highlighted-text);" - " background-color:palette(highlight);" - " border-color: palette(highlight);" - "}" - ); + QString styleSheet = QStringLiteral("QToolButton {" + " background-color: palette(background);" + " border-style: solid;" + " border-width: 1px;" + " border-radius: 3px;" + " border-color: palette(shadow);" + " color: palette(button-text);" + "}" + "QToolButton:checked {" + " color:palette(highlighted-text);" + " background-color:palette(highlight);" + " border-color: palette(highlight);" + "}"); toolbar2->setStyleSheet(styleSheet); - ui->filtersLayout->addItem(new QSpacerItem(20, 20, QSizePolicy::Expanding, QSizePolicy::Minimum)); - toolbar2->addActions({Actions["filesFiltersVideo"], Actions["filesFiltersAudio"], Actions["filesFiltersImage"], Actions["filesFiltersOther"]}); + ui->filtersLayout->addItem( + new QSpacerItem(20, 20, QSizePolicy::Expanding, QSizePolicy::Minimum)); + toolbar2->addActions({Actions["filesFiltersVideo"], + Actions["filesFiltersAudio"], + Actions["filesFiltersImage"], + Actions["filesFiltersOther"]}); ui->filtersLayout->addWidget(toolbar2); m_searchField = new LineEditClear(this); m_searchField->setToolTip(tr("Only show files whose name contains some text")); m_searchField->setPlaceholderText(tr("search")); - connect(m_searchField, &QLineEdit::textChanged, this, [ = ](const QString & search) { + connect(m_searchField, &QLineEdit::textChanged, this, [=](const QString &search) { m_filesProxyModel->setFilterFixedString(search); if (search.isEmpty()) { - changeFilesDirectory(m_filesProxyModel->mapFromSource(m_filesModel->index( - m_filesModel->rootPath()))); + changeFilesDirectory( + m_filesProxyModel->mapFromSource(m_filesModel->index(m_filesModel->rootPath()))); } m_view->scrollToTop(); }); @@ -684,7 +681,7 @@ FilesDock::FilesDock(QWidget *parent) ui->tableView->sortByColumn(0, Qt::AscendingOrder); ui->tableView->horizontalHeader()->setSectionsMovable(true); ui->tableView->setColumnWidth(1, 100); - connect(ui->tableView, &QAbstractItemView::activated, this, [ = ] (const QModelIndex & index) { + connect(ui->tableView, &QAbstractItemView::activated, this, [=](const QModelIndex &index) { auto sourceIndex = m_filesProxyModel->mapToSource(index); auto filePath = m_filesModel->filePath(sourceIndex); @@ -704,13 +701,21 @@ FilesDock::FilesDock(QWidget *parent) if (!MAIN.open(filePath)) openClip(filePath); }); - connect(ui->tableView->horizontalHeader(), &QHeaderView::sortIndicatorChanged, - this, [ = ](int column, Qt::SortOrder order) { - LOG_DEBUG() << "sort by column" << column; - ui->tableView->sortByColumn(column, order); - }); - connect(ui->listView, &QAbstractItemView::activated, ui->tableView, &QAbstractItemView::activated); - connect(m_iconsView, &QAbstractItemView::activated, ui->tableView, &QAbstractItemView::activated); + connect(ui->tableView->horizontalHeader(), + &QHeaderView::sortIndicatorChanged, + this, + [=](int column, Qt::SortOrder order) { + LOG_DEBUG() << "sort by column" << column; + ui->tableView->sortByColumn(column, order); + }); + connect(ui->listView, + &QAbstractItemView::activated, + ui->tableView, + &QAbstractItemView::activated); + connect(m_iconsView, + &QAbstractItemView::activated, + ui->tableView, + &QAbstractItemView::activated); QList views; views << ui->tableView; @@ -720,7 +725,8 @@ FilesDock::FilesDock(QWidget *parent) view->setDragDropMode(QAbstractItemView::DragOnly); view->setAcceptDrops(false); view->setAlternatingRowColors(true); - connect(view, SIGNAL(customContextMenuRequested(QPoint)), + connect(view, + SIGNAL(customContextMenuRequested(QPoint)), SLOT(viewCustomContextMenuRequested(QPoint))); } @@ -807,28 +813,28 @@ void FilesDock::setupActions() action->setToolTip(tr("Open the clip in the Source player")); action->setEnabled(false); connect(action, &QAction::triggered, this, &FilesDock::onOpenActionTriggered); - connect(m_selectionModel, &QItemSelectionModel::selectionChanged, action, [ = ]() { + connect(m_selectionModel, &QItemSelectionModel::selectionChanged, action, [=]() { action->setEnabled(!m_selectionModel->selection().isEmpty()); }); Actions.add("filesOpenAction", action); action = new QAction(tr("System Default"), this); action->setEnabled(false); - connect(action, &QAction::triggered, this, [ = ]() { + connect(action, &QAction::triggered, this, [=]() { auto filePath = firstSelectedFilePath(); if (filePath.isEmpty()) filePath = m_filesModel->rootPath(); LOG_DEBUG() << filePath; openClip(filePath); }); - connect(m_selectionModel, &QItemSelectionModel::selectionChanged, action, [ = ]() { + connect(m_selectionModel, &QItemSelectionModel::selectionChanged, action, [=]() { action->setEnabled(!m_selectionModel->selection().isEmpty()); }); Actions.add("filesOpenDefaultAction", action); action = new QAction(tr("Other..."), this); action->setEnabled(false); - connect(m_selectionModel, &QItemSelectionModel::selectionChanged, action, [ = ]() { + connect(m_selectionModel, &QItemSelectionModel::selectionChanged, action, [=]() { action->setEnabled(!m_selectionModel->selection().isEmpty()); }); connect(action, &QAction::triggered, this, &FilesDock::onOpenOtherAdd); @@ -836,14 +842,14 @@ void FilesDock::setupActions() action = new QAction(tr("Remove..."), this); action->setEnabled(false); - connect(m_selectionModel, &QItemSelectionModel::selectionChanged, action, [ = ]() { + connect(m_selectionModel, &QItemSelectionModel::selectionChanged, action, [=]() { action->setEnabled(!m_selectionModel->selection().isEmpty()); }); connect(action, &QAction::triggered, this, &FilesDock::onOpenOtherRemove); Actions.add("filesOpenWithRemoveAction", action); action = new QAction(tr("Show In File Manager"), this); - connect(action, &QAction::triggered, this, [ = ]() { + connect(action, &QAction::triggered, this, [=]() { auto filePath = firstSelectedFilePath(); if (filePath.isEmpty()) filePath = m_filesModel->rootPath(); @@ -855,7 +861,7 @@ void FilesDock::setupActions() action = new QAction(tr("Update Thumbnails"), this); action->setEnabled(false); connect(action, &QAction::triggered, this, &FilesDock::onUpdateThumbnailsActionTriggered); - connect(m_selectionModel, &QItemSelectionModel::selectionChanged, action, [ = ]() { + connect(m_selectionModel, &QItemSelectionModel::selectionChanged, action, [=]() { action->setEnabled(!m_selectionModel->selection().isEmpty()); }); Actions.add("filesUpdateThumbnailsAction", action); @@ -863,21 +869,21 @@ void FilesDock::setupActions() action = new QAction(tr("Select All"), this); // action->setShortcut(QKeySequence(Qt::CTRL | Qt::ALT | Qt::Key_A)); connect(action, &QAction::triggered, this, &FilesDock::onSelectAllActionTriggered); - connect(m_filesProxyModel, &QAbstractItemModel::rowsInserted, this, [ = ]() { + connect(m_filesProxyModel, &QAbstractItemModel::rowsInserted, this, [=]() { action->setEnabled(m_filesProxyModel->rowCount() > 0); }); - connect(m_filesProxyModel, &QAbstractItemModel::rowsRemoved, this, [ = ]() { + connect(m_filesProxyModel, &QAbstractItemModel::rowsRemoved, this, [=]() { action->setEnabled(m_filesProxyModel->rowCount() > 0); }); Actions.add("filesSelectAllAction", action); action = new QAction(tr("Select None"), this); // action->setShortcut(QKeySequence(Qt::CTRL | Qt::ALT | Qt::Key_D)); - connect(action, &QAction::triggered, this, [ = ]() { + connect(action, &QAction::triggered, this, [=]() { m_view->setCurrentIndex(QModelIndex()); m_selectionModel->clearSelection(); }); - connect(m_selectionModel, &QItemSelectionModel::selectionChanged, action, [ = ]() { + connect(m_selectionModel, &QItemSelectionModel::selectionChanged, action, [=]() { action->setEnabled(!m_selectionModel->selection().isEmpty()); }); Actions.add("filesSelectNoneAction", action); @@ -885,11 +891,11 @@ void FilesDock::setupActions() action = new QAction(tr("Open Previous"), this); // action->setShortcut(QKeySequence(Qt::ALT | Qt::Key_Up)); action->setEnabled(false); - connect(action, &QAction::triggered, this, [ = ]() { + connect(action, &QAction::triggered, this, [=]() { raise(); incrementIndex(-1); }); - connect(m_selectionModel, &QItemSelectionModel::selectionChanged, action, [ = ]() { + connect(m_selectionModel, &QItemSelectionModel::selectionChanged, action, [=]() { action->setEnabled(!m_selectionModel->selection().isEmpty()); }); Actions.add("filesOpenPreviousAction", action); @@ -897,11 +903,11 @@ void FilesDock::setupActions() action = new QAction(tr("Open Next"), this); // action->setShortcut(QKeySequence(Qt::ALT | Qt::Key_Down)); action->setEnabled(false); - connect(action, &QAction::triggered, this, [ = ]() { + connect(action, &QAction::triggered, this, [=]() { raise(); incrementIndex(1); }); - connect(m_selectionModel, &QItemSelectionModel::selectionChanged, action, [ = ]() { + connect(m_selectionModel, &QItemSelectionModel::selectionChanged, action, [=]() { action->setEnabled(!m_selectionModel->selection().isEmpty()); }); Actions.add("filesOpenNextAction", action); @@ -932,12 +938,11 @@ void FilesDock::setupActions() action = new QAction(tr("Folders"), this); action->setToolTip(tr("Hide or show the list of folders")); - icon = QIcon::fromTheme("view-choose", - QIcon(":/icons/oxygen/32x32/actions/view-choose.png")); + icon = QIcon::fromTheme("view-choose", QIcon(":/icons/oxygen/32x32/actions/view-choose.png")); action->setIcon(icon); action->setCheckable(true); action->setChecked(Settings.filesFoldersOpen()); - connect(action, &QAction::triggered, this, [ = ](bool checked) { + connect(action, &QAction::triggered, this, [=](bool checked) { ui->treeView->setVisible(checked); Settings.setFilesFoldersOpen(checked); }); @@ -946,10 +951,9 @@ void FilesDock::setupActions() action = new QAction(tr("Go Up"), this); action->setToolTip(tr("Show the parent folder")); action->setShortcut({Qt::ALT | Qt::Key_Backspace}); - icon = QIcon::fromTheme("lift", - QIcon(":/icons/oxygen/32x32/actions/lift.png")); + icon = QIcon::fromTheme("lift", QIcon(":/icons/oxygen/32x32/actions/lift.png")); action->setIcon(icon); - connect(action, &QAction::triggered, this, [ = ]() { + connect(action, &QAction::triggered, this, [=]() { auto dir = QDir(m_filesModel->rootPath()); dir.cdUp(); const auto filePath = dir.absolutePath(); @@ -964,10 +968,9 @@ void FilesDock::setupActions() Actions.add("filesGoUp", action); action = new QAction(tr("Refresh Folders"), this); - icon = QIcon::fromTheme("view-refresh", - QIcon(":/icons/oxygen/32x32/actions/view-refresh.png")); + icon = QIcon::fromTheme("view-refresh", QIcon(":/icons/oxygen/32x32/actions/view-refresh.png")); action->setIcon(icon); - connect(action, &QAction::triggered, this, [ = ]() { + connect(action, &QAction::triggered, this, [=]() { const auto cd = m_dirsModel->filePath(ui->treeView->currentIndex()); m_dirsModel.reset(new QFileSystemModel); m_dirsModel->setReadOnly(true); @@ -987,7 +990,7 @@ void FilesDock::setupActions() action = new QAction(tr("Search"), this); action->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_F)); - connect(action, &QAction::triggered, this, [ = ]() { + connect(action, &QAction::triggered, this, [=]() { setVisible(true); raise(); m_searchField->setFocus(); @@ -1015,7 +1018,7 @@ void FilesDock::addOpenWithMenu(QMenu *menu) // custom options auto programs = Settings.filesOpenOther(firstSelectedMediaType()); for (const auto &program : programs) { - auto action = subMenu->addAction(QFileInfo(program).baseName(), this, [ = ]() { + auto action = subMenu->addAction(QFileInfo(program).baseName(), this, [=]() { const auto filePath = firstSelectedFilePath(); LOG_DEBUG() << program << filePath; QProcess::startDetached(program, {QDir::toNativeSeparators(filePath)}); @@ -1111,7 +1114,7 @@ void FilesDock::changeDirectory(const QString &filePath, bool updateLocation) if (info.isDir()) { m_view->scrollToTop(); } else { - QTimer::singleShot(2000, this, [ = ]() { + QTimer::singleShot(2000, this, [=]() { const auto index = m_filesProxyModel->mapFromSource(m_filesModel->index(filePath)); m_view->scrollTo(index); m_view->setCurrentIndex(index); @@ -1165,8 +1168,8 @@ void FilesDock::updateViewMode() } else { m_view = m_iconsView; } - m_view->setRootIndex(m_filesProxyModel->mapFromSource(m_filesModel->index( - m_filesModel->rootPath()))); + m_view->setRootIndex( + m_filesProxyModel->mapFromSource(m_filesModel->index(m_filesModel->rootPath()))); m_iconsView->updateSizes(); m_view->show(); } @@ -1251,7 +1254,8 @@ void FilesDock::onOpenOtherAdd() { LOG_DEBUG(); const auto filePath = firstSelectedFilePath(); - if (filePath.isEmpty()) return; + if (filePath.isEmpty()) + return; QString dir("/usr/bin"); QString filter; @@ -1261,9 +1265,12 @@ void FilesDock::onOpenOtherAdd() #elif defined(Q_OS_MAC) dir = QStringLiteral("/Applications"); #endif - const auto program = QFileDialog::getOpenFileName(MAIN.window(), tr("Choose Executable"), dir, + const auto program = QFileDialog::getOpenFileName(MAIN.window(), + tr("Choose Executable"), + dir, filter, - nullptr, Util::getFileDialogOptions()); + nullptr, + Util::getFileDialogOptions()); if (!program.isEmpty()) { if (QProcess::startDetached(program, {QDir::toNativeSeparators(filePath)})) { Settings.setFilesOpenOther(firstSelectedMediaType(), program); @@ -1278,7 +1285,7 @@ void FilesDock::onOpenOtherRemove() auto ls = Settings.filesOpenOther(mediaType); ls.sort(Qt::CaseInsensitive); QStringList programs; - std::for_each(ls.begin(), ls.end(), [&](const QString & s) { + std::for_each(ls.begin(), ls.end(), [&](const QString &s) { programs << QDir::toNativeSeparators(s); }); ListSelectionDialog dialog(programs, this); @@ -1338,8 +1345,9 @@ void FilesDock::on_locationsCombo_activated(int index) void FilesDock::on_addLocationButton_clicked() { - const auto path = m_filesProxyModel->mapToSource(m_view->rootIndex()).data( - QFileSystemModel::FilePathRole).toString(); + const auto path = m_filesProxyModel->mapToSource(m_view->rootIndex()) + .data(QFileSystemModel::FilePathRole) + .toString(); if (path.isEmpty()) return; QInputDialog dialog(this); diff --git a/src/docks/filesdock.h b/src/docks/filesdock.h index 45ce494a6b..8d6f621973 100644 --- a/src/docks/filesdock.h +++ b/src/docks/filesdock.h @@ -19,11 +19,11 @@ #define FILESDOCK_H #include -#include -#include #include #include #include +#include +#include namespace Ui { class FilesDock; @@ -47,8 +47,9 @@ class FilesDock : public QDockWidget explicit FilesDock(QWidget *parent = 0); ~FilesDock(); - struct CacheItem { - int mediaType {-1}; // -1 = unknown + struct CacheItem + { + int mediaType{-1}; // -1 = unknown }; int getCacheMediaType(const QString &key); diff --git a/src/docks/filtersdock.cpp b/src/docks/filtersdock.cpp index d1c72a61d1..4df35ad22d 100644 --- a/src/docks/filtersdock.cpp +++ b/src/docks/filtersdock.cpp @@ -16,36 +16,39 @@ */ #include "filtersdock.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include +#include "Logger.h" #include "actions.h" -#include "mainwindow.h" #include "controllers/filtercontroller.h" +#include "mainwindow.h" +#include "mltcontroller.h" +#include "models/attachedfiltersmodel.h" +#include "models/metadatamodel.h" +#include "models/motiontrackermodel.h" +#include "models/subtitlesmodel.h" #include "qmltypes/qmlapplication.h" #include "qmltypes/qmlfilter.h" #include "qmltypes/qmlutilities.h" #include "qmltypes/qmlview.h" -#include "models/metadatamodel.h" -#include "models/motiontrackermodel.h" -#include "models/subtitlesmodel.h" -#include "models/attachedfiltersmodel.h" -#include "mltcontroller.h" -FiltersDock::FiltersDock(MetadataModel *metadataModel, AttachedFiltersModel *attachedModel, - MotionTrackerModel *motionTrackerModel, SubtitlesModel *subtitlesModel, - QWidget *parent) : - QDockWidget(tr("Filters"), parent), - m_qview(QmlUtilities::sharedEngine(), this) +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +FiltersDock::FiltersDock(MetadataModel *metadataModel, + AttachedFiltersModel *attachedModel, + MotionTrackerModel *motionTrackerModel, + SubtitlesModel *subtitlesModel, + QWidget *parent) + : QDockWidget(tr("Filters"), parent) + , m_qview(QmlUtilities::sharedEngine(), this) { LOG_DEBUG() << "begin"; setObjectName("FiltersDock"); @@ -73,7 +76,10 @@ FiltersDock::FiltersDock(MetadataModel *metadataModel, AttachedFiltersModel *att connect(&m_producer, SIGNAL(seeked(int)), SIGNAL(seeked(int))); connect(this, SIGNAL(producerInChanged(int)), &m_producer, SIGNAL(inChanged(int))); connect(this, SIGNAL(producerOutChanged(int)), &m_producer, SIGNAL(outChanged(int))); - connect(m_qview.quickWindow(), &QQuickWindow::sceneGraphInitialized, this, &FiltersDock::load, + connect(m_qview.quickWindow(), + &QQuickWindow::sceneGraphInitialized, + this, + &FiltersDock::load, Qt::QueuedConnection); setCurrentFilter(0, 0, QmlFilter::NoCurrentFilter); @@ -86,7 +92,7 @@ void FiltersDock::setCurrentFilter(QmlFilter *filter, QmlMetadata *meta, int ind if (filter && filter->producer().is_valid()) { m_producer.setProducer(filter->producer()); if (mlt_service_playlist_type != filter->producer().type() && MLT.producer() - && MLT.producer()->is_valid()) + && MLT.producer()->is_valid()) m_producer.seek(MLT.producer()->position()); } else { Mlt::Producer emptyProducer(mlt_producer(0)); @@ -98,15 +104,16 @@ void FiltersDock::setCurrentFilter(QmlFilter *filter, QmlMetadata *meta, int ind connect(filter, SIGNAL(changed(QString)), SIGNAL(changed())); else disconnect(this, SIGNAL(changed())); - QMetaObject::invokeMethod(m_qview.rootObject(), "setCurrentFilter", Q_ARG(QVariant, - QVariant(index))); + QMetaObject::invokeMethod(m_qview.rootObject(), + "setCurrentFilter", + Q_ARG(QVariant, QVariant(index))); } bool FiltersDock::event(QEvent *event) { bool result = QDockWidget::event(event); if (event->type() == QEvent::PaletteChange || event->type() == QEvent::StyleChange - || event->type() == QEvent::Show) { + || event->type() == QEvent::Show) { load(); } return result; @@ -161,7 +168,7 @@ void FiltersDock::showCopyFilterMenu() void FiltersDock::onServiceInChanged(int delta, Mlt::Service *service) { if (delta && service && m_producer.producer().is_valid() - && service->get_service() == m_producer.producer().get_service()) { + && service->get_service() == m_producer.producer().get_service()) { emit producerInChanged(delta); } } @@ -173,7 +180,8 @@ void FiltersDock::load() QTimer::singleShot(300, this, &FiltersDock::load); } - LOG_DEBUG() << "begin" << "isVisible" << isVisible() << "qview.status" << m_qview.status(); + LOG_DEBUG() << "begin" + << "isVisible" << isVisible() << "qview.status" << m_qview.status(); emit currentFilterRequested(QmlFilter::NoCurrentFilter); @@ -191,9 +199,11 @@ void FiltersDock::load() QUrl source = QUrl::fromLocalFile(viewPath.absoluteFilePath("filterview.qml")); m_qview.setSource(source); - QObject::connect(m_qview.rootObject(), SIGNAL(currentFilterRequested(int)), + QObject::connect(m_qview.rootObject(), + SIGNAL(currentFilterRequested(int)), SIGNAL(currentFilterRequested(int))); - QObject::connect(m_qview.rootObject(), SIGNAL(copyFilterRequested()), + QObject::connect(m_qview.rootObject(), + SIGNAL(copyFilterRequested()), SLOT(showCopyFilterMenu())); } @@ -205,10 +215,9 @@ void FiltersDock::setupActions() action = new QAction(tr("Add"), this); action->setShortcut(QKeySequence(Qt::Key_F)); action->setToolTip(tr("Choose a filter to add")); - icon = QIcon::fromTheme("list-add", - QIcon(":/icons/oxygen/32x32/actions/list-add.png")); + icon = QIcon::fromTheme("list-add", QIcon(":/icons/oxygen/32x32/actions/list-add.png")); action->setIcon(icon); - connect(action, &QAction::triggered, this, [ = ]() { + connect(action, &QAction::triggered, this, [=]() { show(); raise(); m_qview.setFocus(); @@ -220,18 +229,15 @@ void FiltersDock::setupActions() action = new QAction(tr("Remove"), this); action->setShortcut(QKeySequence(Qt::SHIFT | Qt::Key_F)); action->setToolTip(tr("Remove selected filter")); - icon = QIcon::fromTheme("list-remove", - QIcon(":/icons/oxygen/32x32/actions/list-remove.png")); + icon = QIcon::fromTheme("list-remove", QIcon(":/icons/oxygen/32x32/actions/list-remove.png")); action->setIcon(icon); - connect(action, &QAction::triggered, this, [ = ]() { - MAIN.filterController()->removeCurrent(); - }); + connect(action, &QAction::triggered, this, [=]() { MAIN.filterController()->removeCurrent(); }); addAction(action); Actions.add("filtersRemoveFilterAction", action, windowTitle()); action = new QAction(tr("Copy Enabled"), this); action->setToolTip(tr("Copy checked filters to the clipboard")); - connect(action, &QAction::triggered, this, [ = ]() { + connect(action, &QAction::triggered, this, [=]() { QmlApplication::singleton().copyEnabledFilters(); }); addAction(action); @@ -239,7 +245,7 @@ void FiltersDock::setupActions() action = new QAction(tr("Copy Current"), this); action->setToolTip(tr("Copy current filter to the clipboard")); - connect(action, &QAction::triggered, this, [ = ]() { + connect(action, &QAction::triggered, this, [=]() { QmlApplication::singleton().copyCurrentFilter(); }); addAction(action); @@ -247,7 +253,7 @@ void FiltersDock::setupActions() action = new QAction(tr("Copy All"), this); action->setToolTip(tr("Copy all filters to the clipboard")); - connect(action, &QAction::triggered, this, [ = ]() { + connect(action, &QAction::triggered, this, [=]() { QmlApplication::singleton().copyAllFilters(); }); addAction(action); @@ -255,10 +261,9 @@ void FiltersDock::setupActions() action = new QAction(tr("Paste Filters"), this); action->setToolTip(tr("Paste the filters from the clipboard")); - icon = QIcon::fromTheme("edit-paste", - QIcon(":/icons/oxygen/32x32/actions/edit-paste.png")); + icon = QIcon::fromTheme("edit-paste", QIcon(":/icons/oxygen/32x32/actions/edit-paste.png")); action->setIcon(icon); - connect(action, &QAction::triggered, this, [ = ]() { + connect(action, &QAction::triggered, this, [=]() { QmlApplication::singleton().pasteFilters(); }); addAction(action); diff --git a/src/docks/filtersdock.h b/src/docks/filtersdock.h index 78d14df5d0..ea976020f9 100644 --- a/src/docks/filtersdock.h +++ b/src/docks/filtersdock.h @@ -18,14 +18,14 @@ #ifndef FILTERSDOCK_H #define FILTERSDOCK_H +#include "qmltypes/qmlproducer.h" +#include "sharedframe.h" + #include #include #include #include -#include "sharedframe.h" -#include "qmltypes/qmlproducer.h" - class QmlFilter; class QmlMetadata; class MetadataModel; @@ -38,14 +38,13 @@ class FiltersDock : public QDockWidget Q_OBJECT public: - explicit FiltersDock(MetadataModel *metadataModel, AttachedFiltersModel *attachedModel, - MotionTrackerModel *motionTrackerModel, SubtitlesModel *subtitlesModel, + explicit FiltersDock(MetadataModel *metadataModel, + AttachedFiltersModel *attachedModel, + MotionTrackerModel *motionTrackerModel, + SubtitlesModel *subtitlesModel, QWidget *parent = 0); - QmlProducer *qmlProducer() - { - return &m_producer; - } + QmlProducer *qmlProducer() { return &m_producer; } signals: void currentFilterRequested(int attachedIndex); @@ -71,7 +70,7 @@ public slots: void setupActions(); QQuickWidget m_qview; QmlProducer m_producer; - unsigned loadTries {0}; + unsigned loadTries{0}; }; #endif // FILTERSDOCK_H diff --git a/src/docks/jobsdock.cpp b/src/docks/jobsdock.cpp index 9e26678000..d28ca00321 100644 --- a/src/docks/jobsdock.cpp +++ b/src/docks/jobsdock.cpp @@ -17,14 +17,16 @@ #include "jobsdock.h" #include "ui_jobsdock.h" + +#include "Logger.h" +#include "dialogs/textviewerdialog.h" #include "jobqueue.h" + #include -#include -#include "dialogs/textviewerdialog.h" -JobsDock::JobsDock(QWidget *parent) : - QDockWidget(parent), - ui(new Ui::JobsDock) +JobsDock::JobsDock(QWidget *parent) + : QDockWidget(parent) + , ui(new Ui::JobsDock) { LOG_DEBUG() << "begin"; ui->setupUi(this); @@ -49,7 +51,8 @@ JobsDock::~JobsDock() AbstractJob *JobsDock::currentJob() const { QModelIndex index = ui->treeView->currentIndex(); - if (!index.isValid()) return 0; + if (!index.isValid()) + return 0; return JOBS.jobFromIndex(index); } @@ -68,9 +71,12 @@ void JobsDock::onJobAdded() ui->treeView->setIndexWidget(index, progressBar); ui->treeView->resizeColumnToContents(JobQueue::COLUMN_STATUS); label->setToolTip(JOBS.data(index).toString()); - label->setText(label->fontMetrics().elidedText( - JOBS.data(index).toString(), Qt::ElideMiddle, ui->treeView->columnWidth(JobQueue::COLUMN_OUTPUT))); - connect(JOBS.jobFromIndex(index), SIGNAL(progressUpdated(QStandardItem *, int)), + label->setText( + label->fontMetrics().elidedText(JOBS.data(index).toString(), + Qt::ElideMiddle, + ui->treeView->columnWidth(JobQueue::COLUMN_OUTPUT))); + connect(JOBS.jobFromIndex(index), + SIGNAL(progressUpdated(QStandardItem *, int)), SLOT(onProgressUpdated(QStandardItem *, int))); show(); raise(); @@ -90,10 +96,11 @@ void JobsDock::resizeEvent(QResizeEvent *event) { QDockWidget::resizeEvent(event); foreach (QLabel *label, ui->treeView->findChildren()) { - label->setText(label->fontMetrics().elidedText( - label->toolTip(), Qt::ElideMiddle, ui->treeView->columnWidth(JobQueue::COLUMN_OUTPUT))); + label->setText( + label->fontMetrics().elidedText(label->toolTip(), + Qt::ElideMiddle, + ui->treeView->columnWidth(JobQueue::COLUMN_OUTPUT))); } - } void JobsDock::on_treeView_customContextMenuRequested(const QPoint &pos) @@ -103,7 +110,7 @@ void JobsDock::on_treeView_customContextMenuRequested(const QPoint &pos) AbstractJob *job = index.isValid() ? JOBS.jobFromIndex(index) : nullptr; if (job) { if (job->ran() && job->state() == QProcess::NotRunning - && job->exitStatus() == QProcess::NormalExit) { + && job->exitStatus() == QProcess::NormalExit) { menu.addActions(job->successActions()); } if (job->stopped() || (JOBS.isPaused() && !job->ran())) @@ -128,15 +135,18 @@ void JobsDock::on_treeView_customContextMenuRequested(const QPoint &pos) void JobsDock::on_actionStopJob_triggered() { QModelIndex index = ui->treeView->currentIndex(); - if (!index.isValid()) return; + if (!index.isValid()) + return; AbstractJob *job = JOBS.jobFromIndex(index); - if (job) job->stop(); + if (job) + job->stop(); } void JobsDock::on_actionViewLog_triggered() { QModelIndex index = ui->treeView->currentIndex(); - if (!index.isValid()) return; + if (!index.isValid()) + return; AbstractJob *job = JOBS.jobFromIndex(index); if (job) { TextViewerDialog dialog(this); @@ -161,9 +171,11 @@ void JobsDock::on_pauseButton_toggled(bool checked) void JobsDock::on_actionRun_triggered() { QModelIndex index = ui->treeView->currentIndex(); - if (!index.isValid()) return; + if (!index.isValid()) + return; AbstractJob *job = JOBS.jobFromIndex(index); - if (job) job->start(); + if (job) + job->start(); } void JobsDock::on_menuButton_clicked() @@ -175,7 +187,7 @@ void JobsDock::on_treeView_doubleClicked(const QModelIndex &index) { AbstractJob *job = JOBS.jobFromIndex(index); if (job && job->ran() && job->state() == QProcess::NotRunning - && job->exitStatus() == QProcess::NormalExit) { + && job->exitStatus() == QProcess::NormalExit) { foreach (QAction *action, job->successActions()) { if (action->data() == "Open") { action->trigger(); @@ -188,7 +200,8 @@ void JobsDock::on_treeView_doubleClicked(const QModelIndex &index) void JobsDock::on_actionRemove_triggered() { QModelIndex index = ui->treeView->currentIndex(); - if (!index.isValid()) return; + if (!index.isValid()) + return; JOBS.remove(index); } @@ -201,8 +214,10 @@ void JobsDock::on_JobsDock_visibilityChanged(bool visible) { if (visible) { foreach (QLabel *label, ui->treeView->findChildren()) { - label->setText(label->fontMetrics().elidedText( - label->toolTip(), Qt::ElideMiddle, ui->treeView->columnWidth(JobQueue::COLUMN_OUTPUT))); + label->setText(label->fontMetrics().elidedText(label->toolTip(), + Qt::ElideMiddle, + ui->treeView->columnWidth( + JobQueue::COLUMN_OUTPUT))); } } } diff --git a/src/docks/keyframesdock.cpp b/src/docks/keyframesdock.cpp index 7944ec971e..4f71820b45 100644 --- a/src/docks/keyframesdock.cpp +++ b/src/docks/keyframesdock.cpp @@ -17,28 +17,28 @@ #include "keyframesdock.h" +#include "Logger.h" #include "actions.h" +#include "mainwindow.h" #include "qmltypes/qmlproducer.h" #include "qmltypes/qmlutilities.h" #include "qmltypes/qmlview.h" -#include "widgets/docktoolbar.h" -#include "mainwindow.h" #include "settings.h" -#include +#include "widgets/docktoolbar.h" #include +#include #include #include #include -#include -#include #include #include #include #include #include #include -#include +#include +#include #include @@ -52,7 +52,8 @@ KeyframesDock::KeyframesDock(QmlProducer *qmlProducer, QWidget *parent) { LOG_DEBUG() << "begin"; setObjectName("KeyframesDock"); - QIcon icon = QIcon::fromTheme("chronometer", QIcon(":/icons/oxygen/32x32/actions/chronometer.png")); + QIcon icon = QIcon::fromTheme("chronometer", + QIcon(":/icons/oxygen/32x32/actions/chronometer.png")); setWindowIcon(icon); toggleViewAction()->setIcon(windowIcon()); setMinimumSize(200, 50); @@ -80,7 +81,7 @@ KeyframesDock::KeyframesDock(QmlProducer *qmlProducer, QWidget *parent) m_keyTypePrevMenu->addAction(Actions["keyframesTypePrevHoldAction"]); m_keyTypePrevMenu->addAction(Actions["keyframesTypePrevLinearAction"]); m_keyTypePrevMenu->addAction(Actions["keyframesTypePrevSmoothNaturalAction"]); -#if LIBMLT_VERSION_INT >= ((7<<16)+(21<<8)) +#if LIBMLT_VERSION_INT >= ((7 << 16) + (21 << 8)) QMenu *keyEaseOutMenu = new QMenu(tr("Ease Out"), this); icon = QIcon::fromTheme("keyframe-ease-out", QIcon(":/icons/oxygen/32x32/actions/keyframe-ease-out.png")); @@ -102,7 +103,7 @@ KeyframesDock::KeyframesDock(QmlProducer *qmlProducer, QWidget *parent) m_keyTypeNextMenu->addAction(Actions["keyframesTypeHoldAction"]); m_keyTypeNextMenu->addAction(Actions["keyframesTypeLinearAction"]); m_keyTypeNextMenu->addAction(Actions["keyframesTypeSmoothNaturalAction"]); -#if LIBMLT_VERSION_INT >= ((7<<16)+(21<<8)) +#if LIBMLT_VERSION_INT >= ((7 << 16) + (21 << 8)) QMenu *keyEaseInMenu = new QMenu(tr("Ease In"), this); icon = QIcon::fromTheme("keyframe-ease-in", QIcon(":/icons/oxygen/32x32/actions/keyframe-ease-in.png")); @@ -148,8 +149,8 @@ KeyframesDock::KeyframesDock(QmlProducer *qmlProducer, QWidget *parent) DockToolBar *toolbar = new DockToolBar(tr("Keyframes Controls")); QToolButton *menuButton = new QToolButton(); - menuButton->setIcon(QIcon::fromTheme("show-menu", - QIcon(":/icons/oxygen/32x32/actions/show-menu.png"))); + menuButton->setIcon( + QIcon::fromTheme("show-menu", QIcon(":/icons/oxygen/32x32/actions/show-menu.png"))); menuButton->setToolTip(tr("Keyframes Menu")); menuButton->setAutoRaise(true); menuButton->setPopupMode(QToolButton::QToolButton::InstantPopup); @@ -173,10 +174,11 @@ KeyframesDock::KeyframesDock(QmlProducer *qmlProducer, QWidget *parent) zoomSlider->setValue(100); zoomSlider->setTracking(false); connect(zoomSlider, &QSlider::valueChanged, this, [&](int value) { - if (!isVisible() || !m_qview.rootObject()) return; + if (!isVisible() || !m_qview.rootObject()) + return; emit setZoom(value / 100.0); }); - connect(this, &KeyframesDock::timeScaleChanged, zoomSlider, [ = ]() { + connect(this, &KeyframesDock::timeScaleChanged, zoomSlider, [=]() { double value = round(pow(m_timeScale - 0.01, 1.0 / 3.0) * 100.0); zoomSlider->setValue(value); }); @@ -230,7 +232,7 @@ void KeyframesDock::setupActions() m_model.trimFilterIn(i); } }); - connect(this, &KeyframesDock::newFilter, action, [ = ]() { + connect(this, &KeyframesDock::newFilter, action, [=]() { bool enabled = false; if (m_filter && m_filter->allowTrim()) enabled = true; @@ -249,7 +251,7 @@ void KeyframesDock::setupActions() m_model.trimFilterOut(i); } }); - connect(this, &KeyframesDock::newFilter, action, [ = ]() { + connect(this, &KeyframesDock::newFilter, action, [=]() { bool enabled = false; if (m_filter && m_filter->allowTrim()) enabled = true; @@ -268,7 +270,7 @@ void KeyframesDock::setupActions() m_filter->setAnimateIn(i); } }); - connect(this, &KeyframesDock::newFilter, action, [ = ]() { + connect(this, &KeyframesDock::newFilter, action, [=]() { bool enabled = false; if (m_filter && m_filter->allowAnimateIn()) enabled = true; @@ -287,7 +289,7 @@ void KeyframesDock::setupActions() m_filter->setAnimateOut(i); } }); - connect(this, &KeyframesDock::newFilter, action, [ = ]() { + connect(this, &KeyframesDock::newFilter, action, [=]() { bool enabled = false; if (m_filter && m_filter->allowAnimateOut()) enabled = true; @@ -296,37 +298,36 @@ void KeyframesDock::setupActions() Actions.add("keyframesAnimateOutAction", action); action = new QAction(tr("Scrub While Dragging"), this); - icon = QIcon::fromTheme("scrub_drag", - QIcon(":/icons/oxygen/32x32/actions/scrub_drag.png")); + icon = QIcon::fromTheme("scrub_drag", QIcon(":/icons/oxygen/32x32/actions/scrub_drag.png")); action->setIcon(icon); action->setCheckable(true); action->setChecked(Settings.keyframesDragScrub()); connect(action, &QAction::triggered, this, [&](bool checked) { Settings.setKeyframesDragScrub(checked); }); - connect(&Settings, &ShotcutSettings::keyframesDragScrubChanged, action, [ = ]() { + connect(&Settings, &ShotcutSettings::keyframesDragScrubChanged, action, [=]() { action->setChecked(Settings.keyframesDragScrub()); }); Actions.add("keyframesScrubDragAction", action); action = new QAction(tr("Zoom Keyframes Out"), this); action->setShortcut(QKeySequence(Qt::ALT | Qt::Key_Minus)); - icon = QIcon::fromTheme("zoom-out", - QIcon(":/icons/oxygen/32x32/actions/zoom-out.png")); + icon = QIcon::fromTheme("zoom-out", QIcon(":/icons/oxygen/32x32/actions/zoom-out.png")); action->setIcon(icon); connect(action, &QAction::triggered, this, [&]() { - if (!isVisible() || !m_qview.rootObject()) return; + if (!isVisible() || !m_qview.rootObject()) + return; emit zoomOut(); }); Actions.add("keyframesZoomOutAction", action); action = new QAction(tr("Zoom Keyframes In"), this); action->setShortcut(QKeySequence(Qt::ALT | Qt::Key_Plus)); - icon = QIcon::fromTheme("zoom-in", - QIcon(":/icons/oxygen/32x32/actions/zoom-in.png")); + icon = QIcon::fromTheme("zoom-in", QIcon(":/icons/oxygen/32x32/actions/zoom-in.png")); action->setIcon(icon); connect(action, &QAction::triggered, this, [&]() { - if (!isVisible() || !m_qview.rootObject()) return; + if (!isVisible() || !m_qview.rootObject()) + return; emit zoomIn(); }); Actions.add("keyframesZoomInAction", action); @@ -337,7 +338,8 @@ void KeyframesDock::setupActions() QIcon(":/icons/oxygen/32x32/actions/zoom-fit-best.png")); action->setIcon(icon); connect(action, &QAction::triggered, this, [&]() { - if (!isVisible() || !m_qview.rootObject()) return; + if (!isVisible() || !m_qview.rootObject()) + return; emit zoomToFit(); }); Actions.add("keyframesZoomFitAction", action); @@ -348,10 +350,12 @@ void KeyframesDock::setupActions() action = new QAction(tr("Hold"), this); connect(action, &QAction::triggered, this, [&]() { - if (!isVisible() || !m_qview.rootObject()) return; + if (!isVisible() || !m_qview.rootObject()) + return; int currentTrack = m_qview.rootObject()->property("currentTrack").toInt(); for (auto keyframeIndex : m_qview.rootObject()->property("selection").toList()) { - m_model.setInterpolation(currentTrack, keyframeIndex.toInt() - 1, + m_model.setInterpolation(currentTrack, + keyframeIndex.toInt() - 1, KeyframesModel::DiscreteInterpolation); } }); @@ -363,10 +367,12 @@ void KeyframesDock::setupActions() action = new QAction(tr("Linear"), this); connect(action, &QAction::triggered, this, [&]() { - if (!isVisible() || !m_qview.rootObject()) return; + if (!isVisible() || !m_qview.rootObject()) + return; int currentTrack = m_qview.rootObject()->property("currentTrack").toInt(); for (auto keyframeIndex : m_qview.rootObject()->property("selection").toList()) { - m_model.setInterpolation(currentTrack, keyframeIndex.toInt() - 1, + m_model.setInterpolation(currentTrack, + keyframeIndex.toInt() - 1, KeyframesModel::LinearInterpolation); } }); @@ -378,11 +384,13 @@ void KeyframesDock::setupActions() action = new QAction(tr("Smooth"), this); connect(action, &QAction::triggered, this, [&]() { - if (!isVisible() || !m_qview.rootObject()) return; + if (!isVisible() || !m_qview.rootObject()) + return; int currentTrack = m_qview.rootObject()->property("currentTrack").toInt(); for (auto keyframeIndex : m_qview.rootObject()->property("selection").toList()) { -#if LIBMLT_VERSION_INT >= ((7<<16)+(21<<8)) - m_model.setInterpolation(currentTrack, keyframeIndex.toInt() - 1, +#if LIBMLT_VERSION_INT >= ((7 << 16) + (21 << 8)) + m_model.setInterpolation(currentTrack, + keyframeIndex.toInt() - 1, KeyframesModel::SmoothNaturalInterpolation); #else m_model.setInterpolation(currentTrack, keyframeIndex.toInt() - 1, @@ -398,10 +406,12 @@ void KeyframesDock::setupActions() action = new QAction(tr("Ease Out Sinusoidal"), this); connect(action, &QAction::triggered, this, [&]() { - if (!isVisible() || !m_qview.rootObject()) return; + if (!isVisible() || !m_qview.rootObject()) + return; int currentTrack = m_qview.rootObject()->property("currentTrack").toInt(); for (auto keyframeIndex : m_qview.rootObject()->property("selection").toList()) { - m_model.setInterpolation(currentTrack, keyframeIndex.toInt() - 1, + m_model.setInterpolation(currentTrack, + keyframeIndex.toInt() - 1, KeyframesModel::EaseOutSinusoidal); } }); @@ -413,10 +423,12 @@ void KeyframesDock::setupActions() action = new QAction(tr("Ease Out Quadratic"), this); connect(action, &QAction::triggered, this, [&]() { - if (!isVisible() || !m_qview.rootObject()) return; + if (!isVisible() || !m_qview.rootObject()) + return; int currentTrack = m_qview.rootObject()->property("currentTrack").toInt(); for (auto keyframeIndex : m_qview.rootObject()->property("selection").toList()) { - m_model.setInterpolation(currentTrack, keyframeIndex.toInt() - 1, + m_model.setInterpolation(currentTrack, + keyframeIndex.toInt() - 1, KeyframesModel::EaseOutQuadratic); } }); @@ -428,10 +440,12 @@ void KeyframesDock::setupActions() action = new QAction(tr("Ease Out Cubic"), this); connect(action, &QAction::triggered, this, [&]() { - if (!isVisible() || !m_qview.rootObject()) return; + if (!isVisible() || !m_qview.rootObject()) + return; int currentTrack = m_qview.rootObject()->property("currentTrack").toInt(); for (auto keyframeIndex : m_qview.rootObject()->property("selection").toList()) { - m_model.setInterpolation(currentTrack, keyframeIndex.toInt() - 1, + m_model.setInterpolation(currentTrack, + keyframeIndex.toInt() - 1, KeyframesModel::EaseOutCubic); } }); @@ -443,10 +457,12 @@ void KeyframesDock::setupActions() action = new QAction(tr("Ease Out Quartic"), this); connect(action, &QAction::triggered, this, [&]() { - if (!isVisible() || !m_qview.rootObject()) return; + if (!isVisible() || !m_qview.rootObject()) + return; int currentTrack = m_qview.rootObject()->property("currentTrack").toInt(); for (auto keyframeIndex : m_qview.rootObject()->property("selection").toList()) { - m_model.setInterpolation(currentTrack, keyframeIndex.toInt() - 1, + m_model.setInterpolation(currentTrack, + keyframeIndex.toInt() - 1, KeyframesModel::EaseOutQuartic); } }); @@ -458,10 +474,12 @@ void KeyframesDock::setupActions() action = new QAction(tr("Ease Out Quintic"), this); connect(action, &QAction::triggered, this, [&]() { - if (!isVisible() || !m_qview.rootObject()) return; + if (!isVisible() || !m_qview.rootObject()) + return; int currentTrack = m_qview.rootObject()->property("currentTrack").toInt(); for (auto keyframeIndex : m_qview.rootObject()->property("selection").toList()) { - m_model.setInterpolation(currentTrack, keyframeIndex.toInt() - 1, + m_model.setInterpolation(currentTrack, + keyframeIndex.toInt() - 1, KeyframesModel::EaseOutQuintic); } }); @@ -473,10 +491,12 @@ void KeyframesDock::setupActions() action = new QAction(tr("Ease Out Exponential"), this); connect(action, &QAction::triggered, this, [&]() { - if (!isVisible() || !m_qview.rootObject()) return; + if (!isVisible() || !m_qview.rootObject()) + return; int currentTrack = m_qview.rootObject()->property("currentTrack").toInt(); for (auto keyframeIndex : m_qview.rootObject()->property("selection").toList()) { - m_model.setInterpolation(currentTrack, keyframeIndex.toInt() - 1, + m_model.setInterpolation(currentTrack, + keyframeIndex.toInt() - 1, KeyframesModel::EaseOutExponential); } }); @@ -488,10 +508,12 @@ void KeyframesDock::setupActions() action = new QAction(tr("Ease Out Circular"), this); connect(action, &QAction::triggered, this, [&]() { - if (!isVisible() || !m_qview.rootObject()) return; + if (!isVisible() || !m_qview.rootObject()) + return; int currentTrack = m_qview.rootObject()->property("currentTrack").toInt(); for (auto keyframeIndex : m_qview.rootObject()->property("selection").toList()) { - m_model.setInterpolation(currentTrack, keyframeIndex.toInt() - 1, + m_model.setInterpolation(currentTrack, + keyframeIndex.toInt() - 1, KeyframesModel::EaseOutCircular); } }); @@ -503,14 +525,16 @@ void KeyframesDock::setupActions() action = new QAction(tr("Ease Out Back"), this); connect(action, &QAction::triggered, this, [&]() { - if (!isVisible() || !m_qview.rootObject()) return; + if (!isVisible() || !m_qview.rootObject()) + return; int currentTrack = m_qview.rootObject()->property("currentTrack").toInt(); for (auto keyframeIndex : m_qview.rootObject()->property("selection").toList()) { - m_model.setInterpolation(currentTrack, keyframeIndex.toInt() - 1, + m_model.setInterpolation(currentTrack, + keyframeIndex.toInt() - 1, KeyframesModel::EaseOutBack); } }); - connect(this, &KeyframesDock::newFilter, action, [ = ]() { + connect(this, &KeyframesDock::newFilter, action, [=]() { bool enabled = true; if (m_metadata && m_metadata->keyframes() && !m_metadata->keyframes()->allowOvershoot()) { enabled = false; @@ -526,14 +550,16 @@ void KeyframesDock::setupActions() action = new QAction(tr("Ease Out Elastic"), this); connect(action, &QAction::triggered, this, [&]() { - if (!isVisible() || !m_qview.rootObject()) return; + if (!isVisible() || !m_qview.rootObject()) + return; int currentTrack = m_qview.rootObject()->property("currentTrack").toInt(); for (auto keyframeIndex : m_qview.rootObject()->property("selection").toList()) { - m_model.setInterpolation(currentTrack, keyframeIndex.toInt() - 1, + m_model.setInterpolation(currentTrack, + keyframeIndex.toInt() - 1, KeyframesModel::EaseOutElastic); } }); - connect(this, &KeyframesDock::newFilter, action, [ = ]() { + connect(this, &KeyframesDock::newFilter, action, [=]() { bool enabled = true; if (m_metadata && m_metadata->keyframes() && !m_metadata->keyframes()->allowOvershoot()) { enabled = false; @@ -549,10 +575,12 @@ void KeyframesDock::setupActions() action = new QAction(tr("Ease Out Bounce"), this); connect(action, &QAction::triggered, this, [&]() { - if (!isVisible() || !m_qview.rootObject()) return; + if (!isVisible() || !m_qview.rootObject()) + return; int currentTrack = m_qview.rootObject()->property("currentTrack").toInt(); for (auto keyframeIndex : m_qview.rootObject()->property("selection").toList()) { - m_model.setInterpolation(currentTrack, keyframeIndex.toInt() - 1, + m_model.setInterpolation(currentTrack, + keyframeIndex.toInt() - 1, KeyframesModel::EaseOutBounce); } }); @@ -568,10 +596,12 @@ void KeyframesDock::setupActions() action = new QAction(tr("Hold"), this); connect(action, &QAction::triggered, this, [&]() { - if (!isVisible() || !m_qview.rootObject()) return; + if (!isVisible() || !m_qview.rootObject()) + return; int currentTrack = m_qview.rootObject()->property("currentTrack").toInt(); for (auto keyframeIndex : m_qview.rootObject()->property("selection").toList()) { - m_model.setInterpolation(currentTrack, keyframeIndex.toInt(), + m_model.setInterpolation(currentTrack, + keyframeIndex.toInt(), KeyframesModel::DiscreteInterpolation); } }); @@ -583,10 +613,13 @@ void KeyframesDock::setupActions() action = new QAction(tr("Linear"), this); connect(action, &QAction::triggered, this, [&]() { - if (!isVisible() || !m_qview.rootObject()) return; + if (!isVisible() || !m_qview.rootObject()) + return; int currentTrack = m_qview.rootObject()->property("currentTrack").toInt(); for (auto keyframeIndex : m_qview.rootObject()->property("selection").toList()) { - m_model.setInterpolation(currentTrack, keyframeIndex.toInt(), KeyframesModel::LinearInterpolation); + m_model.setInterpolation(currentTrack, + keyframeIndex.toInt(), + KeyframesModel::LinearInterpolation); } }); icon = QIcon::fromTheme("keyframe-linear", @@ -597,11 +630,13 @@ void KeyframesDock::setupActions() action = new QAction(tr("Smooth"), this); connect(action, &QAction::triggered, this, [&]() { - if (!isVisible() || !m_qview.rootObject()) return; + if (!isVisible() || !m_qview.rootObject()) + return; int currentTrack = m_qview.rootObject()->property("currentTrack").toInt(); for (auto keyframeIndex : m_qview.rootObject()->property("selection").toList()) { -#if LIBMLT_VERSION_INT >= ((7<<16)+(21<<8)) - m_model.setInterpolation(currentTrack, keyframeIndex.toInt(), +#if LIBMLT_VERSION_INT >= ((7 << 16) + (21 << 8)) + m_model.setInterpolation(currentTrack, + keyframeIndex.toInt(), KeyframesModel::SmoothNaturalInterpolation); #else m_model.setInterpolation(currentTrack, keyframeIndex.toInt(), @@ -617,119 +652,128 @@ void KeyframesDock::setupActions() action = new QAction(tr("Ease In Sinusoidal"), this); connect(action, &QAction::triggered, this, [&]() { - if (!isVisible() || !m_qview.rootObject()) return; + if (!isVisible() || !m_qview.rootObject()) + return; int currentTrack = m_qview.rootObject()->property("currentTrack").toInt(); for (auto keyframeIndex : m_qview.rootObject()->property("selection").toList()) { - m_model.setInterpolation(currentTrack, keyframeIndex.toInt(), + m_model.setInterpolation(currentTrack, + keyframeIndex.toInt(), KeyframesModel::EaseInSinusoidal); } }); - icon = QIcon::fromTheme("ease-in-sinu", - QIcon(":/icons/oxygen/32x32/actions/ease-in-sinu.png")); + icon = QIcon::fromTheme("ease-in-sinu", QIcon(":/icons/oxygen/32x32/actions/ease-in-sinu.png")); action->setIcon(icon); keyframeTypeActionGroup->addAction(action); Actions.add("keyframesTypeEaseInSinuAction", action); action = new QAction(tr("Ease In Quadratic"), this); connect(action, &QAction::triggered, this, [&]() { - if (!isVisible() || !m_qview.rootObject()) return; + if (!isVisible() || !m_qview.rootObject()) + return; int currentTrack = m_qview.rootObject()->property("currentTrack").toInt(); for (auto keyframeIndex : m_qview.rootObject()->property("selection").toList()) { - m_model.setInterpolation(currentTrack, keyframeIndex.toInt(), + m_model.setInterpolation(currentTrack, + keyframeIndex.toInt(), KeyframesModel::EaseInQuadratic); } }); - icon = QIcon::fromTheme("ease-in-quad", - QIcon(":/icons/oxygen/32x32/actions/ease-in-quad.png")); + icon = QIcon::fromTheme("ease-in-quad", QIcon(":/icons/oxygen/32x32/actions/ease-in-quad.png")); action->setIcon(icon); keyframeTypeActionGroup->addAction(action); Actions.add("keyframesTypeEaseInQuadAction", action); action = new QAction(tr("Ease In Cubic"), this); connect(action, &QAction::triggered, this, [&]() { - if (!isVisible() || !m_qview.rootObject()) return; + if (!isVisible() || !m_qview.rootObject()) + return; int currentTrack = m_qview.rootObject()->property("currentTrack").toInt(); for (auto keyframeIndex : m_qview.rootObject()->property("selection").toList()) { - m_model.setInterpolation(currentTrack, keyframeIndex.toInt(), + m_model.setInterpolation(currentTrack, + keyframeIndex.toInt(), KeyframesModel::EaseInCubic); } }); - icon = QIcon::fromTheme("ease-in-cube", - QIcon(":/icons/oxygen/32x32/actions/ease-in-cube.png")); + icon = QIcon::fromTheme("ease-in-cube", QIcon(":/icons/oxygen/32x32/actions/ease-in-cube.png")); action->setIcon(icon); keyframeTypeActionGroup->addAction(action); Actions.add("keyframesTypeEaseInCubeAction", action); action = new QAction(tr("Ease In Quartic"), this); connect(action, &QAction::triggered, this, [&]() { - if (!isVisible() || !m_qview.rootObject()) return; + if (!isVisible() || !m_qview.rootObject()) + return; int currentTrack = m_qview.rootObject()->property("currentTrack").toInt(); for (auto keyframeIndex : m_qview.rootObject()->property("selection").toList()) { - m_model.setInterpolation(currentTrack, keyframeIndex.toInt(), + m_model.setInterpolation(currentTrack, + keyframeIndex.toInt(), KeyframesModel::EaseInQuartic); } }); - icon = QIcon::fromTheme("ease-in-quar", - QIcon(":/icons/oxygen/32x32/actions/ease-in-quar.png")); + icon = QIcon::fromTheme("ease-in-quar", QIcon(":/icons/oxygen/32x32/actions/ease-in-quar.png")); action->setIcon(icon); keyframeTypeActionGroup->addAction(action); Actions.add("keyframesTypeEaseInQuartAction", action); action = new QAction(tr("Ease In Quintic"), this); connect(action, &QAction::triggered, this, [&]() { - if (!isVisible() || !m_qview.rootObject()) return; + if (!isVisible() || !m_qview.rootObject()) + return; int currentTrack = m_qview.rootObject()->property("currentTrack").toInt(); for (auto keyframeIndex : m_qview.rootObject()->property("selection").toList()) { - m_model.setInterpolation(currentTrack, keyframeIndex.toInt(), + m_model.setInterpolation(currentTrack, + keyframeIndex.toInt(), KeyframesModel::EaseInQuintic); } }); - icon = QIcon::fromTheme("ease-in-quin", - QIcon(":/icons/oxygen/32x32/actions/ease-in-quin.png")); + icon = QIcon::fromTheme("ease-in-quin", QIcon(":/icons/oxygen/32x32/actions/ease-in-quin.png")); action->setIcon(icon); keyframeTypeActionGroup->addAction(action); Actions.add("keyframesTypeEaseInQuintAction", action); action = new QAction(tr("Ease In Exponential"), this); connect(action, &QAction::triggered, this, [&]() { - if (!isVisible() || !m_qview.rootObject()) return; + if (!isVisible() || !m_qview.rootObject()) + return; int currentTrack = m_qview.rootObject()->property("currentTrack").toInt(); for (auto keyframeIndex : m_qview.rootObject()->property("selection").toList()) { - m_model.setInterpolation(currentTrack, keyframeIndex.toInt(), + m_model.setInterpolation(currentTrack, + keyframeIndex.toInt(), KeyframesModel::EaseInExponential); } }); - icon = QIcon::fromTheme("ease-in-expo", - QIcon(":/icons/oxygen/32x32/actions/ease-in-expo.png")); + icon = QIcon::fromTheme("ease-in-expo", QIcon(":/icons/oxygen/32x32/actions/ease-in-expo.png")); action->setIcon(icon); keyframeTypeActionGroup->addAction(action); Actions.add("keyframesTypeEaseInExpoAction", action); action = new QAction(tr("Ease In Circular"), this); connect(action, &QAction::triggered, this, [&]() { - if (!isVisible() || !m_qview.rootObject()) return; + if (!isVisible() || !m_qview.rootObject()) + return; int currentTrack = m_qview.rootObject()->property("currentTrack").toInt(); for (auto keyframeIndex : m_qview.rootObject()->property("selection").toList()) { - m_model.setInterpolation(currentTrack, keyframeIndex.toInt(), + m_model.setInterpolation(currentTrack, + keyframeIndex.toInt(), KeyframesModel::EaseInCircular); } }); - icon = QIcon::fromTheme("ease-in-circ", - QIcon(":/icons/oxygen/32x32/actions/ease-in-circ.png")); + icon = QIcon::fromTheme("ease-in-circ", QIcon(":/icons/oxygen/32x32/actions/ease-in-circ.png")); action->setIcon(icon); keyframeTypeActionGroup->addAction(action); Actions.add("keyframesTypeEaseInCircAction", action); action = new QAction(tr("Ease In Back"), this); connect(action, &QAction::triggered, this, [&]() { - if (!isVisible() || !m_qview.rootObject()) return; + if (!isVisible() || !m_qview.rootObject()) + return; int currentTrack = m_qview.rootObject()->property("currentTrack").toInt(); for (auto keyframeIndex : m_qview.rootObject()->property("selection").toList()) { - m_model.setInterpolation(currentTrack, keyframeIndex.toInt(), + m_model.setInterpolation(currentTrack, + keyframeIndex.toInt(), KeyframesModel::EaseInBack); } }); - connect(this, &KeyframesDock::newFilter, action, [ = ]() { + connect(this, &KeyframesDock::newFilter, action, [=]() { bool enabled = true; if (m_metadata && m_metadata->keyframes() && !m_metadata->keyframes()->allowOvershoot()) { enabled = false; @@ -737,22 +781,23 @@ void KeyframesDock::setupActions() action->setVisible(enabled); action->setEnabled(enabled); }); - icon = QIcon::fromTheme("ease-in-back", - QIcon(":/icons/oxygen/32x32/actions/ease-in-back.png")); + icon = QIcon::fromTheme("ease-in-back", QIcon(":/icons/oxygen/32x32/actions/ease-in-back.png")); action->setIcon(icon); keyframeTypeActionGroup->addAction(action); Actions.add("keyframesTypeEaseInBackAction", action); action = new QAction(tr("Ease In Elastic"), this); connect(action, &QAction::triggered, this, [&]() { - if (!isVisible() || !m_qview.rootObject()) return; + if (!isVisible() || !m_qview.rootObject()) + return; int currentTrack = m_qview.rootObject()->property("currentTrack").toInt(); for (auto keyframeIndex : m_qview.rootObject()->property("selection").toList()) { - m_model.setInterpolation(currentTrack, keyframeIndex.toInt(), + m_model.setInterpolation(currentTrack, + keyframeIndex.toInt(), KeyframesModel::EaseInElastic); } }); - connect(this, &KeyframesDock::newFilter, action, [ = ]() { + connect(this, &KeyframesDock::newFilter, action, [=]() { bool enabled = true; if (m_metadata && m_metadata->keyframes() && !m_metadata->keyframes()->allowOvershoot()) { enabled = false; @@ -760,33 +805,35 @@ void KeyframesDock::setupActions() action->setVisible(enabled); action->setEnabled(enabled); }); - icon = QIcon::fromTheme("ease-in-elas", - QIcon(":/icons/oxygen/32x32/actions/ease-in-elas.png")); + icon = QIcon::fromTheme("ease-in-elas", QIcon(":/icons/oxygen/32x32/actions/ease-in-elas.png")); action->setIcon(icon); keyframeTypeActionGroup->addAction(action); Actions.add("keyframesTypeEaseInElasAction", action); action = new QAction(tr("Ease In Bounce"), this); connect(action, &QAction::triggered, this, [&]() { - if (!isVisible() || !m_qview.rootObject()) return; + if (!isVisible() || !m_qview.rootObject()) + return; int currentTrack = m_qview.rootObject()->property("currentTrack").toInt(); for (auto keyframeIndex : m_qview.rootObject()->property("selection").toList()) { - m_model.setInterpolation(currentTrack, keyframeIndex.toInt(), + m_model.setInterpolation(currentTrack, + keyframeIndex.toInt(), KeyframesModel::EaseInBounce); } }); - icon = QIcon::fromTheme("ease-in-boun", - QIcon(":/icons/oxygen/32x32/actions/ease-in-boun.png")); + icon = QIcon::fromTheme("ease-in-boun", QIcon(":/icons/oxygen/32x32/actions/ease-in-boun.png")); action->setIcon(icon); keyframeTypeActionGroup->addAction(action); Actions.add("keyframesTypeEaseInBounAction", action); action = new QAction(tr("Ease In/Out Sinusoidal"), this); connect(action, &QAction::triggered, this, [&]() { - if (!isVisible() || !m_qview.rootObject()) return; + if (!isVisible() || !m_qview.rootObject()) + return; int currentTrack = m_qview.rootObject()->property("currentTrack").toInt(); for (auto keyframeIndex : m_qview.rootObject()->property("selection").toList()) { - m_model.setInterpolation(currentTrack, keyframeIndex.toInt(), + m_model.setInterpolation(currentTrack, + keyframeIndex.toInt(), KeyframesModel::EaseInOutSinusoidal); } }); @@ -798,10 +845,12 @@ void KeyframesDock::setupActions() action = new QAction(tr("Ease In/Out Quadratic"), this); connect(action, &QAction::triggered, this, [&]() { - if (!isVisible() || !m_qview.rootObject()) return; + if (!isVisible() || !m_qview.rootObject()) + return; int currentTrack = m_qview.rootObject()->property("currentTrack").toInt(); for (auto keyframeIndex : m_qview.rootObject()->property("selection").toList()) { - m_model.setInterpolation(currentTrack, keyframeIndex.toInt(), + m_model.setInterpolation(currentTrack, + keyframeIndex.toInt(), KeyframesModel::EaseInOutQuadratic); } }); @@ -813,10 +862,12 @@ void KeyframesDock::setupActions() action = new QAction(tr("Ease In/Out Cubic"), this); connect(action, &QAction::triggered, this, [&]() { - if (!isVisible() || !m_qview.rootObject()) return; + if (!isVisible() || !m_qview.rootObject()) + return; int currentTrack = m_qview.rootObject()->property("currentTrack").toInt(); for (auto keyframeIndex : m_qview.rootObject()->property("selection").toList()) { - m_model.setInterpolation(currentTrack, keyframeIndex.toInt(), + m_model.setInterpolation(currentTrack, + keyframeIndex.toInt(), KeyframesModel::EaseInOutCubic); } }); @@ -828,10 +879,12 @@ void KeyframesDock::setupActions() action = new QAction(tr("Ease In/Out Quartic"), this); connect(action, &QAction::triggered, this, [&]() { - if (!isVisible() || !m_qview.rootObject()) return; + if (!isVisible() || !m_qview.rootObject()) + return; int currentTrack = m_qview.rootObject()->property("currentTrack").toInt(); for (auto keyframeIndex : m_qview.rootObject()->property("selection").toList()) { - m_model.setInterpolation(currentTrack, keyframeIndex.toInt(), + m_model.setInterpolation(currentTrack, + keyframeIndex.toInt(), KeyframesModel::EaseInOutQuartic); } }); @@ -843,10 +896,12 @@ void KeyframesDock::setupActions() action = new QAction(tr("Ease In/Out Quintic"), this); connect(action, &QAction::triggered, this, [&]() { - if (!isVisible() || !m_qview.rootObject()) return; + if (!isVisible() || !m_qview.rootObject()) + return; int currentTrack = m_qview.rootObject()->property("currentTrack").toInt(); for (auto keyframeIndex : m_qview.rootObject()->property("selection").toList()) { - m_model.setInterpolation(currentTrack, keyframeIndex.toInt(), + m_model.setInterpolation(currentTrack, + keyframeIndex.toInt(), KeyframesModel::EaseInOutQuintic); } }); @@ -858,10 +913,12 @@ void KeyframesDock::setupActions() action = new QAction(tr("Ease In/Out Exponential"), this); connect(action, &QAction::triggered, this, [&]() { - if (!isVisible() || !m_qview.rootObject()) return; + if (!isVisible() || !m_qview.rootObject()) + return; int currentTrack = m_qview.rootObject()->property("currentTrack").toInt(); for (auto keyframeIndex : m_qview.rootObject()->property("selection").toList()) { - m_model.setInterpolation(currentTrack, keyframeIndex.toInt(), + m_model.setInterpolation(currentTrack, + keyframeIndex.toInt(), KeyframesModel::EaseInOutExponential); } }); @@ -873,10 +930,12 @@ void KeyframesDock::setupActions() action = new QAction(tr("Ease In/Out Circular"), this); connect(action, &QAction::triggered, this, [&]() { - if (!isVisible() || !m_qview.rootObject()) return; + if (!isVisible() || !m_qview.rootObject()) + return; int currentTrack = m_qview.rootObject()->property("currentTrack").toInt(); for (auto keyframeIndex : m_qview.rootObject()->property("selection").toList()) { - m_model.setInterpolation(currentTrack, keyframeIndex.toInt(), + m_model.setInterpolation(currentTrack, + keyframeIndex.toInt(), KeyframesModel::EaseInOutCircular); } }); @@ -888,14 +947,16 @@ void KeyframesDock::setupActions() action = new QAction(tr("Ease In/Out Back"), this); connect(action, &QAction::triggered, this, [&]() { - if (!isVisible() || !m_qview.rootObject()) return; + if (!isVisible() || !m_qview.rootObject()) + return; int currentTrack = m_qview.rootObject()->property("currentTrack").toInt(); for (auto keyframeIndex : m_qview.rootObject()->property("selection").toList()) { - m_model.setInterpolation(currentTrack, keyframeIndex.toInt(), + m_model.setInterpolation(currentTrack, + keyframeIndex.toInt(), KeyframesModel::EaseInOutBack); } }); - connect(this, &KeyframesDock::newFilter, action, [ = ]() { + connect(this, &KeyframesDock::newFilter, action, [=]() { bool enabled = true; if (m_metadata && m_metadata->keyframes() && !m_metadata->keyframes()->allowOvershoot()) { enabled = false; @@ -911,14 +972,16 @@ void KeyframesDock::setupActions() action = new QAction(tr("Ease In/Out Elastic"), this); connect(action, &QAction::triggered, this, [&]() { - if (!isVisible() || !m_qview.rootObject()) return; + if (!isVisible() || !m_qview.rootObject()) + return; int currentTrack = m_qview.rootObject()->property("currentTrack").toInt(); for (auto keyframeIndex : m_qview.rootObject()->property("selection").toList()) { - m_model.setInterpolation(currentTrack, keyframeIndex.toInt(), + m_model.setInterpolation(currentTrack, + keyframeIndex.toInt(), KeyframesModel::EaseInOutElastic); } }); - connect(this, &KeyframesDock::newFilter, action, [ = ]() { + connect(this, &KeyframesDock::newFilter, action, [=]() { bool enabled = true; if (m_metadata && m_metadata->keyframes() && !m_metadata->keyframes()->allowOvershoot()) { enabled = false; @@ -934,10 +997,12 @@ void KeyframesDock::setupActions() action = new QAction(tr("Ease In/Out Bounce"), this); connect(action, &QAction::triggered, this, [&]() { - if (!isVisible() || !m_qview.rootObject()) return; + if (!isVisible() || !m_qview.rootObject()) + return; int currentTrack = m_qview.rootObject()->property("currentTrack").toInt(); for (auto keyframeIndex : m_qview.rootObject()->property("selection").toList()) { - m_model.setInterpolation(currentTrack, keyframeIndex.toInt(), + m_model.setInterpolation(currentTrack, + keyframeIndex.toInt(), KeyframesModel::EaseInOutBounce); } }); @@ -949,7 +1014,8 @@ void KeyframesDock::setupActions() action = new QAction(tr("Remove"), this); connect(action, &QAction::triggered, this, [&]() { - if (!isVisible() || !m_qview.rootObject()) return; + if (!isVisible() || !m_qview.rootObject()) + return; int currentTrack = m_qview.rootObject()->property("currentTrack").toInt(); for (auto keyframeIndex : m_qview.rootObject()->property("selection").toList()) { m_model.remove(currentTrack, keyframeIndex.toInt()); @@ -964,7 +1030,7 @@ void KeyframesDock::setupActions() m_qmlProducer->remakeAudioLevels(); } }); - connect(&Settings, &ShotcutSettings::timelineShowWaveformsChanged, action, [ = ]() { + connect(&Settings, &ShotcutSettings::timelineShowWaveformsChanged, action, [=]() { action->setEnabled(Settings.timelineShowWaveforms()); }); Actions.add("keyframesRebuildAudioWaveformAction", action); @@ -980,7 +1046,7 @@ void KeyframesDock::setupActions() emit seekPreviousSimple(); } }); - connect(this, &KeyframesDock::newFilter, action, [ = ]() { + connect(this, &KeyframesDock::newFilter, action, [=]() { action->setEnabled(m_qmlProducer && m_filter); }); Actions.add("keyframesSeekPreviousAction", action); @@ -996,7 +1062,7 @@ void KeyframesDock::setupActions() emit seekNextSimple(); } }); - connect(this, &KeyframesDock::newFilter, action, [ = ]() { + connect(this, &KeyframesDock::newFilter, action, [=]() { action->setEnabled(m_qmlProducer && m_filter); }); Actions.add("keyframesSeekNextAction", action); @@ -1016,7 +1082,7 @@ void KeyframesDock::setupActions() } } }); - connect(this, &KeyframesDock::newFilter, action, [ = ]() { + connect(this, &KeyframesDock::newFilter, action, [=]() { action->setEnabled(m_qmlProducer && m_filter); }); Actions.add("keyframesToggleKeyframeAction", action); @@ -1026,7 +1092,8 @@ int KeyframesDock::seekPrevious() { if (m_qmlProducer) { int position = m_model.previousKeyframePosition(currentParameter(), - m_qmlProducer->position() + m_qmlProducer->in()); + m_qmlProducer->position() + + m_qmlProducer->in()); position -= m_qmlProducer->in(); m_qmlProducer->setPosition(position); return m_model.keyframeIndex(currentParameter(), @@ -1123,10 +1190,12 @@ void KeyframesDock::load(bool force) m_qview.quickWindow()->setColor(palette().window().color()); QUrl source = QUrl::fromLocalFile(viewPath.absoluteFilePath("keyframes.qml")); m_qview.setSource(source); - connect(m_qview.rootObject(), SIGNAL(rightClicked()), this, SLOT(onDockRightClicked())); - connect(m_qview.rootObject(), SIGNAL(keyframeRightClicked()), this, + connect(m_qview.rootObject(), SIGNAL(rightClicked()), this, SLOT(onDockRightClicked())); + connect(m_qview.rootObject(), + SIGNAL(keyframeRightClicked()), + this, SLOT(onKeyframeRightClicked())); - connect(m_qview.rootObject(), SIGNAL(clipRightClicked()), this, SLOT(onClipRightClicked())); + connect(m_qview.rootObject(), SIGNAL(clipRightClicked()), this, SLOT(onClipRightClicked())); emit timeScaleChanged(); } } @@ -1159,7 +1228,7 @@ void KeyframesDock::onKeyframeRightClicked() if (keyIndex == 0) { firstKey = true; } - if (keyIndex >= m_model.keyframeCount(currentParameter()) - 1) { + if (keyIndex >= m_model.keyframeCount(currentParameter()) - 1) { lastKey = true; } } diff --git a/src/docks/keyframesdock.h b/src/docks/keyframesdock.h index f68c61281a..c909098b6f 100644 --- a/src/docks/keyframesdock.h +++ b/src/docks/keyframesdock.h @@ -18,8 +18,8 @@ #ifndef KEYFRAMESDOCK_H #define KEYFRAMESDOCK_H -#include "qmltypes/qmlfilter.h" #include "models/keyframesmodel.h" +#include "qmltypes/qmlfilter.h" #include #include @@ -39,17 +39,11 @@ class KeyframesDock : public QDockWidget public: explicit KeyframesDock(QmlProducer *qmlProducer, QWidget *parent = 0); - KeyframesModel &model() - { - return m_model; - } + KeyframesModel &model() { return m_model; } Q_INVOKABLE int seekPrevious(); Q_INVOKABLE int seekNext(); int currentParameter() const; - double timeScale() const - { - return m_timeScale; - } + double timeScale() const { return m_timeScale; } void setTimeScale(double value); signals: @@ -93,7 +87,7 @@ private slots: QMenu *m_keyTypePrevMenu; QMenu *m_keyTypeNextMenu; QMenu *m_clipMenu; - double m_timeScale {1.0}; + double m_timeScale{1.0}; }; #endif // KEYFRAMESDOCK_H diff --git a/src/docks/markersdock.cpp b/src/docks/markersdock.cpp index 01f1de3fed..f6d51c306d 100644 --- a/src/docks/markersdock.cpp +++ b/src/docks/markersdock.cpp @@ -17,14 +17,14 @@ #include "markersdock.h" +#include "Logger.h" #include "actions.h" #include "mainwindow.h" #include "models/markersmodel.h" #include "settings.h" +#include "util.h" #include "widgets/docktoolbar.h" #include "widgets/editmarkerwidget.h" -#include "util.h" -#include #include #include @@ -34,14 +34,14 @@ #include #include #include +#include #include #include -#include +#include #include +#include #include #include -#include -#include class ColorItemDelegate : public QStyledItemDelegate { @@ -50,17 +50,16 @@ class ColorItemDelegate : public QStyledItemDelegate ColorItemDelegate(QAbstractItemView *view, QWidget *parent = nullptr) : QStyledItemDelegate(parent) , m_view(view) - { - } + {} - void paint(QPainter *painter, - const QStyleOptionViewItem &option, const QModelIndex &index) const + void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { const auto color = index.data(MarkersModel::ColorRole).value(); const auto textColor(Util::textColor(color)); painter->fillRect(option.rect, color); - const auto point = option.rect.topLeft() + QPoint(2 * m_view->devicePixelRatioF(), - option.fontMetrics.ascent() + m_view->devicePixelRatioF()); + const auto point = option.rect.topLeft() + + QPoint(2 * m_view->devicePixelRatioF(), + option.fontMetrics.ascent() + m_view->devicePixelRatioF()); painter->setPen(textColor); painter->drawText(point, color.name()); } @@ -74,7 +73,6 @@ class ColorItemDelegate : public QStyledItemDelegate private: QAbstractItemView *m_view; - }; class MarkerTreeView : public QTreeView @@ -84,10 +82,7 @@ class MarkerTreeView : public QTreeView public: // Make this function public using QTreeView::selectedIndexes; - void blockSelectionEvent(bool block) - { - m_blockSelectionEvent = block; - } + void blockSelectionEvent(bool block) { m_blockSelectionEvent = block; } signals: void rowClicked(const QModelIndex &index); @@ -122,8 +117,8 @@ class MarkerTreeView : public QTreeView // Include this so that MarkerTreeView can be declared in the source file. #include "markersdock.moc" -MarkersDock::MarkersDock(QWidget *parent) : - QDockWidget(parent) +MarkersDock::MarkersDock(QWidget *parent) + : QDockWidget(parent) , m_model(nullptr) , m_proxyModel(nullptr) , m_editInProgress(false) @@ -150,9 +145,13 @@ MarkersDock::MarkersDock(QWidget *parent) : m_treeView->setRootIsDecorated(false); m_treeView->setUniformRowHeights(true); m_treeView->setSortingEnabled(true); - connect(m_treeView, SIGNAL(markerSelected(QModelIndex &)), this, + connect(m_treeView, + SIGNAL(markerSelected(QModelIndex &)), + this, SLOT(onSelectionChanged(QModelIndex &))); - connect(m_treeView, SIGNAL(rowClicked(const QModelIndex &)), this, + connect(m_treeView, + SIGNAL(rowClicked(const QModelIndex &)), + this, SLOT(onRowClicked(const QModelIndex &))); vboxLayout->addWidget(m_treeView, 1); @@ -187,8 +186,8 @@ MarkersDock::MarkersDock(QWidget *parent) : DockToolBar *toolbar = new DockToolBar(tr("Markers Controls")); toolbar->setAreaHint(Qt::BottomToolBarArea); QToolButton *menuButton = new QToolButton(this); - menuButton->setIcon(QIcon::fromTheme("show-menu", - QIcon(":/icons/oxygen/32x32/actions/show-menu.png"))); + menuButton->setIcon( + QIcon::fromTheme("show-menu", QIcon(":/icons/oxygen/32x32/actions/show-menu.png"))); menuButton->setToolTip(tr("Markers Menu")); menuButton->setAutoRaise(true); menuButton->setMenu(mainMenu); @@ -196,8 +195,8 @@ MarkersDock::MarkersDock(QWidget *parent) : toolbar->addWidget(menuButton); m_addButton = new QToolButton(this); - m_addButton->setIcon(QIcon::fromTheme("list-add", - QIcon(":/icons/oxygen/32x32/actions/list-add.png"))); + m_addButton->setIcon( + QIcon::fromTheme("list-add", QIcon(":/icons/oxygen/32x32/actions/list-add.png"))); m_addButton->setToolTip(tr("Add a marker at the current time")); m_addButton->setAutoRaise(true); if (!connect(m_addButton, &QAbstractButton::clicked, this, &MarkersDock::onAddRequested)) @@ -205,8 +204,8 @@ MarkersDock::MarkersDock(QWidget *parent) : toolbar->addWidget(m_addButton); m_removeButton = new QToolButton(this); - m_removeButton->setIcon(QIcon::fromTheme("list-remove", - QIcon(":/icons/oxygen/32x32/actions/list-remove.png"))); + m_removeButton->setIcon( + QIcon::fromTheme("list-remove", QIcon(":/icons/oxygen/32x32/actions/list-remove.png"))); m_removeButton->setToolTip(tr("Remove the selected marker")); m_removeButton->setAutoRaise(true); if (!connect(m_removeButton, &QAbstractButton::clicked, this, &MarkersDock::onRemoveRequested)) @@ -214,11 +213,13 @@ MarkersDock::MarkersDock(QWidget *parent) : toolbar->addWidget(m_removeButton); m_clearButton = new QToolButton(this); - m_clearButton->setIcon(QIcon::fromTheme("window-close", - QIcon(":/icons/oxygen/32x32/actions/window-close.png"))); + m_clearButton->setIcon( + QIcon::fromTheme("window-close", QIcon(":/icons/oxygen/32x32/actions/window-close.png"))); m_clearButton->setToolTip(tr("Deselect the marker")); m_clearButton->setAutoRaise(true); - if (!connect(m_clearButton, &QAbstractButton::clicked, this, + if (!connect(m_clearButton, + &QAbstractButton::clicked, + this, &MarkersDock::onClearSelectionRequested)) connect(m_clearButton, SIGNAL(clicked()), SLOT(onClearSelectionRequested())); toolbar->addWidget(m_clearButton); @@ -230,8 +231,8 @@ MarkersDock::MarkersDock(QWidget *parent) : toolbar->addWidget(m_searchField); m_clearSearchButton = new QToolButton(this); - m_clearSearchButton->setIcon(QIcon::fromTheme("edit-clear", - QIcon(":/icons/oxygen/32x32/actions/edit-clear.png"))); + m_clearSearchButton->setIcon( + QIcon::fromTheme("edit-clear", QIcon(":/icons/oxygen/32x32/actions/edit-clear.png"))); m_clearSearchButton->setToolTip(tr("Clear search")); m_clearSearchButton->setAutoRaise(true); if (!connect(m_clearSearchButton, &QAbstractButton::clicked, m_searchField, &QLineEdit::clear)) @@ -251,9 +252,7 @@ MarkersDock::MarkersDock(QWidget *parent) : LOG_DEBUG() << "end"; } -MarkersDock::~MarkersDock() -{ -} +MarkersDock::~MarkersDock() {} void MarkersDock::setModel(MarkersModel *model) { @@ -269,13 +268,18 @@ void MarkersDock::setModel(MarkersModel *model) m_treeView->setColumnHidden(3, !Settings.markersShowColumn("end")); m_treeView->setColumnHidden(4, !Settings.markersShowColumn("duration")); m_treeView->sortByColumn(Settings.getMarkerSortColumn(), Settings.getMarkerSortOrder()); - connect(m_model, SIGNAL(rowsInserted(const QModelIndex &, int, int)), this, + connect(m_model, + SIGNAL(rowsInserted(const QModelIndex &, int, int)), + this, SLOT(onRowsInserted(const QModelIndex &, int, int))); - connect(m_model, SIGNAL(dataChanged(const QModelIndex &, const QModelIndex &, - const QVector &)), this, SLOT(onDataChanged(const QModelIndex &, const QModelIndex &, - const QVector &))); + connect(m_model, + SIGNAL(dataChanged(const QModelIndex &, const QModelIndex &, const QVector &)), + this, + SLOT(onDataChanged(const QModelIndex &, const QModelIndex &, const QVector &))); connect(m_model, SIGNAL(modelReset()), this, SLOT(onModelReset())); - connect(m_treeView->header(), SIGNAL(sortIndicatorChanged(int, Qt::SortOrder)), this, + connect(m_treeView->header(), + SIGNAL(sortIndicatorChanged(int, Qt::SortOrder)), + this, SLOT(onSortIndicatorChanged(int, Qt::SortOrder))); m_treeView->blockSelectionEvent(false); } @@ -298,7 +302,10 @@ void MarkersDock::onSelectionChanged(QModelIndex &index) enableButtons(true); m_editMarkerWidget->setVisible(true); QSignalBlocker editBlocker(m_editMarkerWidget); - m_editMarkerWidget->setValues(marker.text, marker.color, marker.start, marker.end, + m_editMarkerWidget->setValues(marker.text, + marker.color, + marker.start, + marker.end, MAIN.multitrack()->get_length() - 1); return; } @@ -393,7 +400,8 @@ void MarkersDock::onRowsInserted(const QModelIndex &parent, int first, int last) m_treeView->setCurrentIndex(insertedIndex); } -void MarkersDock::onDataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight, +void MarkersDock::onDataChanged(const QModelIndex &topLeft, + const QModelIndex &bottomRight, const QVector &roles) { Q_UNUSED(topLeft); @@ -407,7 +415,10 @@ void MarkersDock::onDataChanged(const QModelIndex &topLeft, const QModelIndex &b Markers::Marker marker = m_model->getMarker(realIndex.row()); m_editMarkerWidget->setVisible(true); QSignalBlocker editBlocker(m_editMarkerWidget); - m_editMarkerWidget->setValues(marker.text, marker.color, marker.start, marker.end, + m_editMarkerWidget->setValues(marker.text, + marker.color, + marker.start, + marker.end, MAIN.multitrack()->get_length() - 1); return; } diff --git a/src/docks/markersdock.h b/src/docks/markersdock.h index 3620c99e65..3b0eb8f8e6 100644 --- a/src/docks/markersdock.h +++ b/src/docks/markersdock.h @@ -59,7 +59,8 @@ private slots: void onEndColumnToggled(bool checked); void onDurationColumnToggled(bool checked); void onRowsInserted(const QModelIndex &parent, int first, int last); - void onDataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight, + void onDataChanged(const QModelIndex &topLeft, + const QModelIndex &bottomRight, const QVector &roles = QVector()); void onValuesChanged(); void onModelReset(); diff --git a/src/docks/notesdock.cpp b/src/docks/notesdock.cpp index 15a28ea215..1433538291 100644 --- a/src/docks/notesdock.cpp +++ b/src/docks/notesdock.cpp @@ -16,22 +16,23 @@ */ #include "notesdock.h" + +#include "Logger.h" #include "actions.h" #include "settings.h" -#include - #include -#include -#include #include +#include #include +#include #include -class TextEditor: public QPlainTextEdit +class TextEditor : public QPlainTextEdit { public: - explicit TextEditor(QWidget *parent = nullptr) : QPlainTextEdit() + explicit TextEditor(QWidget *parent = nullptr) + : QPlainTextEdit() { zoomIn(Settings.notesZoom()); setTabChangesFocus(false); @@ -41,18 +42,14 @@ class TextEditor: public QPlainTextEdit action->setShortcut(Qt::CTRL | Qt::ALT | Qt::Key_Minus); addAction(action); Actions.add("notesDecreaseTextSize", action, tr("Notes")); - connect(action, &QAction::triggered, this, [ = ]() { - setZoom(-4); - }); + connect(action, &QAction::triggered, this, [=]() { setZoom(-4); }); action = new QAction(tr("Increase Text Size"), this); action->setShortcut(Qt::CTRL | Qt::ALT | Qt::Key_Equal); addAction(action); Actions.add("notesIncreaseTextSize", action, tr("Notes")); - connect(action, &QAction::triggered, this, [ = ]() { - setZoom(4); - }); - connect(this, &QWidget::customContextMenuRequested, this, [ = ](const QPoint & pos) { - std::unique_ptr menu {createStandardContextMenu()}; + connect(action, &QAction::triggered, this, [=]() { setZoom(4); }); + connect(this, &QWidget::customContextMenuRequested, this, [=](const QPoint &pos) { + std::unique_ptr menu{createStandardContextMenu()}; actions().at(0)->setEnabled(Settings.notesZoom() > 0); menu->addActions(actions()); menu->exec(mapToGlobal(pos)); @@ -78,10 +75,10 @@ class TextEditor: public QPlainTextEdit } }; -NotesDock::NotesDock(QWidget *parent) : - QDockWidget(tr("Notes"), parent), - m_textEdit(new TextEditor(this)), - m_blockUpdate(false) +NotesDock::NotesDock(QWidget *parent) + : QDockWidget(tr("Notes"), parent) + , m_textEdit(new TextEditor(this)) + , m_blockUpdate(false) { LOG_DEBUG() << "begin"; setObjectName("NotesDock"); diff --git a/src/docks/playlistdock.cpp b/src/docks/playlistdock.cpp index d0372892d3..b6bff4d28a 100644 --- a/src/docks/playlistdock.cpp +++ b/src/docks/playlistdock.cpp @@ -16,43 +16,44 @@ */ #include "playlistdock.h" -#include "ui_playlistdock.h" + +#include "Logger.h" #include "actions.h" +#include "commands/playlistcommands.h" #include "dialogs/durationdialog.h" #include "dialogs/filedatedialog.h" #include "dialogs/longuitask.h" #include "dialogs/resourcedialog.h" #include "dialogs/slideshowgeneratordialog.h" #include "mainwindow.h" +#include "proxymanager.h" +#include "qmltypes/qmlapplication.h" #include "settings.h" #include "shotcut_mlt_properties.h" +#include "ui_playlistdock.h" +#include "util.h" #include "widgets/docktoolbar.h" +#include "widgets/lineeditclear.h" #include "widgets/playlisticonview.h" -#include "widgets/playlisttable.h" #include "widgets/playlistlistview.h" -#include "util.h" -#include "commands/playlistcommands.h" -#include "proxymanager.h" -#include "qmltypes/qmlapplication.h" -#include "widgets/lineeditclear.h" -#include +#include "widgets/playlisttable.h" -#include -#include -#include -#include -#include +#include +#include +#include #include -#include -#include #include #include -#include -#include -#include -#include +#include #include -#include +#include +#include +#include +#include +#include +#include +#include +#include static const auto kInOutChangedTimeoutMs = 100; static const auto kTilePaddingPx = 10; @@ -66,15 +67,13 @@ class TiledItemDelegate : public QStyledItemDelegate Q_OBJECT public: TiledItemDelegate(QAbstractItemView *view, QWidget *parent = nullptr) - : QStyledItemDelegate(parent), - m_view(view) + : QStyledItemDelegate(parent) + , m_view(view) { - connect(&Settings, SIGNAL(playlistThumbnailsChanged()), - SLOT(emitSizeHintChanged())); + connect(&Settings, SIGNAL(playlistThumbnailsChanged()), SLOT(emitSizeHintChanged())); } - void paint(QPainter *painter, - const QStyleOptionViewItem &option, const QModelIndex &index) const + void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { const QImage thumb = index.data(Qt::DecorationRole).value(); const QString setting = Settings.playlistThumbnails(); @@ -102,13 +101,16 @@ class TiledItemDelegate : public QStyledItemDelegate centeredTextRect.moveCenter(option.rect.center()); QRect textRect = centeredTextRect; - textRect.setLeft(thumb.width() + (("hidden" == setting) ? PlaylistModel::THUMBNAIL_HEIGHT : 10)); + textRect.setLeft(thumb.width() + + (("hidden" == setting) ? PlaylistModel::THUMBNAIL_HEIGHT : 10)); QPoint textPoint = textRect.topLeft(); textPoint.setY(textPoint.y() + lineHeight); painter->setFont(boldFont); painter->drawText(textPoint, - painter->fontMetrics().elidedText(nameParts.first(), Qt::ElideMiddle, textRect.width())); + painter->fontMetrics().elidedText(nameParts.first(), + Qt::ElideMiddle, + textRect.width())); painter->setFont(oldFont); if (nameParts.size() > 1) { textPoint.setY(textPoint.y() + lineHeight); @@ -116,16 +118,17 @@ class TiledItemDelegate : public QStyledItemDelegate } textPoint.setY(textPoint.y() + lineHeight); - painter->drawText(textPoint, tr("Duration: %1").arg(index.data( - PlaylistModel::FIELD_DURATION).toString())); + painter->drawText(textPoint, + tr("Duration: %1") + .arg(index.data(PlaylistModel::FIELD_DURATION).toString())); if (roomEnoughForAllDetails) { textPoint.setY(textPoint.y() + lineHeight); - painter->drawText(textPoint, tr("Date: %1").arg(index.data(PlaylistModel::FIELD_DATE).toString())); + painter->drawText(textPoint, + tr("Date: %1").arg(index.data(PlaylistModel::FIELD_DATE).toString())); } } - QSize sizeHint(const QStyleOptionViewItem &option, - const QModelIndex &index) const + QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const { Q_UNUSED(option); Q_UNUSED(index); @@ -136,18 +139,13 @@ class TiledItemDelegate : public QStyledItemDelegate } private slots: - void emitSizeHintChanged() - { - emit sizeHintChanged(QModelIndex()); - } + void emitSizeHintChanged() { emit sizeHintChanged(QModelIndex()); } private: QAbstractItemView *m_view; - }; - -class ProducerHashesParser: public Mlt::Parser +class ProducerHashesParser : public Mlt::Parser { private: std::vector m_hashes; @@ -165,80 +163,29 @@ class ProducerHashesParser: public Mlt::Parser return m_hashes; } - int on_start_filter(Mlt::Filter *) - { - return 0; - } + int on_start_filter(Mlt::Filter *) { return 0; } int on_start_producer(Mlt::Producer *producer) { if (producer->is_cut()) m_hashes.push_back(Util::getHash(producer->parent()).toStdString()); return 0; } - int on_end_producer(Mlt::Producer *) - { - return 0; - } - int on_start_playlist(Mlt::Playlist *) - { - return 0; - } - int on_end_playlist(Mlt::Playlist *) - { - return 0; - } - int on_start_tractor(Mlt::Tractor *) - { - return 0; - } - int on_end_tractor(Mlt::Tractor *) - { - return 0; - } - int on_start_multitrack(Mlt::Multitrack *) - { - return 0; - } - int on_end_multitrack(Mlt::Multitrack *) - { - return 0; - } - int on_start_track() - { - return 0; - } - int on_end_track() - { - return 0; - } - int on_end_filter(Mlt::Filter *) - { - return 0; - } - int on_start_transition(Mlt::Transition *) - { - return 0; - } - int on_end_transition(Mlt::Transition *) - { - return 0; - } - int on_start_chain(Mlt::Chain *) - { - return 0; - } - int on_end_chain(Mlt::Chain *) - { - return 0; - } - int on_start_link(Mlt::Link *) - { - return 0; - } - int on_end_link(Mlt::Link *) - { - return 0; - } + int on_end_producer(Mlt::Producer *) { return 0; } + int on_start_playlist(Mlt::Playlist *) { return 0; } + int on_end_playlist(Mlt::Playlist *) { return 0; } + int on_start_tractor(Mlt::Tractor *) { return 0; } + int on_end_tractor(Mlt::Tractor *) { return 0; } + int on_start_multitrack(Mlt::Multitrack *) { return 0; } + int on_end_multitrack(Mlt::Multitrack *) { return 0; } + int on_start_track() { return 0; } + int on_end_track() { return 0; } + int on_end_filter(Mlt::Filter *) { return 0; } + int on_start_transition(Mlt::Transition *) { return 0; } + int on_end_transition(Mlt::Transition *) { return 0; } + int on_start_chain(Mlt::Chain *) { return 0; } + int on_end_chain(Mlt::Chain *) { return 0; } + int on_start_link(Mlt::Link *) { return 0; } + int on_end_link(Mlt::Link *) { return 0; } }; class PlaylistProxyModel : public QSortFilterProxyModel @@ -250,12 +197,10 @@ class PlaylistProxyModel : public QSortFilterProxyModel : QSortFilterProxyModel(parent) { // All - m_functors.push_back([](int row, const QModelIndex & index) { - return true; - }); + m_functors.push_back([](int row, const QModelIndex &index) { return true; }); // Duplicates - m_functors.push_back([this](int row, const QModelIndex & index) { + m_functors.push_back([this](int row, const QModelIndex &index) { // m_hashes contains the duplicates auto clip = MAIN.playlist()->get_clip(row); if (clip && clip->is_valid()) { @@ -266,7 +211,7 @@ class PlaylistProxyModel : public QSortFilterProxyModel }); // Not In Timeline - m_functors.push_back([this](int row, const QModelIndex & index) { + m_functors.push_back([this](int row, const QModelIndex &index) { // m_hashes contains the unique hashes in the timeline auto clip = MAIN.playlist()->get_clip(row); if (clip && clip->is_valid()) { @@ -308,7 +253,10 @@ class PlaylistProxyModel : public QSortFilterProxyModel std::sort(hashes.begin(), hashes.end()); std::set unique(hashes.begin(), hashes.end()); m_hashes.clear(); - std::set_difference(hashes.begin(), hashes.end(), unique.begin(), unique.end(), + std::set_difference(hashes.begin(), + hashes.end(), + unique.begin(), + unique.end(), std::back_inserter(m_hashes)); LOG_INFO() << "Duplicates smart bin found" << m_hashes.size() << "items"; break; @@ -329,18 +277,11 @@ class PlaylistProxyModel : public QSortFilterProxyModel invalidateFilter(); } - enum PlaylistDock::SmartBin smartBin() const - { - return m_smartBin; - } + enum PlaylistDock::SmartBin smartBin() const { return m_smartBin; } static QString smartBinName(int index) { - QString names[] = { - tr("All"), - tr("Duplicates"), - tr("Not In Timeline") - }; + QString names[] = {tr("All"), tr("Duplicates"), tr("Not In Timeline")}; return names[index]; } @@ -364,24 +305,23 @@ class PlaylistProxyModel : public QSortFilterProxyModel } auto filter = filterRegularExpression(); - return index.data(Qt::DisplayRole).toString().contains(filter) || - index.data(Qt::ToolTipRole).toString().contains(filter) || - index.data(PlaylistModel::FIELD_COMMENT).toString().contains(filter); + return index.data(Qt::DisplayRole).toString().contains(filter) + || index.data(Qt::ToolTipRole).toString().contains(filter) + || index.data(PlaylistModel::FIELD_COMMENT).toString().contains(filter); } private: QList m_mediaTypes; QString m_bin; - enum PlaylistDock::SmartBin m_smartBin { PlaylistDock::SmartBinNone }; + enum PlaylistDock::SmartBin m_smartBin{PlaylistDock::SmartBinNone}; std::vector> m_functors; std::vector m_hashes; }; - -PlaylistDock::PlaylistDock(QWidget *parent) : - QDockWidget(parent), - ui(new Ui::PlaylistDock), - m_blockResizeColumnsToContents(false) +PlaylistDock::PlaylistDock(QWidget *parent) + : QDockWidget(parent) + , ui(new Ui::PlaylistDock) + , m_blockResizeColumnsToContents(false) { LOG_DEBUG() << "begin"; ui->setupUi(this); @@ -393,7 +333,9 @@ PlaylistDock::PlaylistDock(QWidget *parent) : m_proxyModel->setFilterKeyColumn(-1); m_selectionModel = new QItemSelectionModel(m_proxyModel, this); - connect(m_selectionModel, &QItemSelectionModel::selectionChanged, this, + connect(m_selectionModel, + &QItemSelectionModel::selectionChanged, + this, &PlaylistDock::selectionChanged); ui->splitter->setSizes({kTreeViewWidthPx, this->width() - kTreeViewWidthPx}); @@ -403,18 +345,17 @@ PlaylistDock::PlaylistDock(QWidget *parent) : ui->treeWidget->viewport()->setAcceptDrops(true); ui->treeWidget->setDragDropMode(QAbstractItemView::DropOnly); ui->treeWidget->setContextMenuPolicy(Qt::CustomContextMenu); - connect(ui->treeWidget, &QWidget::customContextMenuRequested, this, [ = ](const QPoint & pos) { + connect(ui->treeWidget, &QWidget::customContextMenuRequested, this, [=](const QPoint &pos) { QMenu menu(this); menu.addAction(Actions["playlistNewBin"]); menu.addAction(Actions["playlistRemoveBin"]); menu.addAction(Actions["playlistRenameBin"]); menu.exec(mapToGlobal(pos)); }); - connect(ui->treeWidget, &BinTree::copied, this, [ = ](const QString & filePath) { + connect(ui->treeWidget, &BinTree::copied, this, [=](const QString &filePath) { addFiles(-1, {filePath}); }); - connect(ui->treeWidget, &BinTree::moved, this, [ = ](const QList &rows, - const QPointF & point) { + connect(ui->treeWidget, &BinTree::moved, this, [=](const QList &rows, const QPointF &point) { auto item = ui->treeWidget->itemAt(point.x(), point.y()); if (!item) return; @@ -495,8 +436,8 @@ PlaylistDock::PlaylistDock(QWidget *parent) : DockToolBar *toolbar = new DockToolBar(tr("Playlist Controls")); toolbar->setAreaHint(Qt::BottomToolBarArea); QToolButton *menuButton = new QToolButton(); - menuButton->setIcon(QIcon::fromTheme("show-menu", - QIcon(":/icons/oxygen/32x32/actions/show-menu.png"))); + menuButton->setIcon( + QIcon::fromTheme("show-menu", QIcon(":/icons/oxygen/32x32/actions/show-menu.png"))); menuButton->setToolTip(tr("Playlist Menu")); menuButton->setAutoRaise(true); menuButton->setPopupMode(QToolButton::QToolButton::InstantPopup); @@ -522,29 +463,32 @@ PlaylistDock::PlaylistDock(QWidget *parent) : ui->filtersLayout->addWidget(toolbar); auto toolbar2 = new QToolBar(tr("Playlist Filters")); - QString styleSheet = QStringLiteral( - "QToolButton {" - " background-color: palette(background);" - " border-style: solid;" - " border-width: 1px;" - " border-radius: 3px;" - " border-color: palette(shadow);" - " color: palette(button-text);" - "}" - "QToolButton:checked {" - " color:palette(highlighted-text);" - " background-color:palette(highlight);" - " border-color: palette(highlight);" - "}" - ); + QString styleSheet = QStringLiteral("QToolButton {" + " background-color: palette(background);" + " border-style: solid;" + " border-width: 1px;" + " border-radius: 3px;" + " border-color: palette(shadow);" + " color: palette(button-text);" + "}" + "QToolButton:checked {" + " color:palette(highlighted-text);" + " background-color:palette(highlight);" + " border-color: palette(highlight);" + "}"); toolbar2->setStyleSheet(styleSheet); - ui->filtersLayout->addItem(new QSpacerItem(20, 20, QSizePolicy::Expanding, QSizePolicy::Minimum)); - toolbar2->addActions({Actions["playlistFiltersVideo"], Actions["playlistFiltersAudio"], Actions["playlistFiltersImage"], Actions["playlistFiltersOther"]}); + ui->filtersLayout->addItem( + new QSpacerItem(20, 20, QSizePolicy::Expanding, QSizePolicy::Minimum)); + toolbar2->addActions({Actions["playlistFiltersVideo"], + Actions["playlistFiltersAudio"], + Actions["playlistFiltersImage"], + Actions["playlistFiltersOther"]}); ui->filtersLayout->addWidget(toolbar2); m_searchField = new LineEditClear(this); - m_searchField->setToolTip(tr("Only show files whose name, path, or comment contains some text")); + m_searchField->setToolTip( + tr("Only show files whose name, path, or comment contains some text")); m_searchField->setPlaceholderText(tr("search")); - connect(m_searchField, &QLineEdit::textChanged, this, [ = ](const QString & search) { + connect(m_searchField, &QLineEdit::textChanged, this, [=](const QString &search) { m_proxyModel->setFilterFixedString(search); }); ui->filtersLayout->addWidget(m_searchField, 1); @@ -572,7 +516,8 @@ PlaylistDock::PlaylistDock(QWidget *parent) : view->setAcceptDrops(true); view->setDefaultDropAction(Qt::MoveAction); view->setAlternatingRowColors(true); - connect(view, SIGNAL(customContextMenuRequested(QPoint)), + connect(view, + SIGNAL(customContextMenuRequested(QPoint)), SLOT(viewCustomContextMenuRequested(QPoint))); connect(view, SIGNAL(doubleClicked(QModelIndex)), SLOT(viewDoubleClicked(QModelIndex))); } @@ -584,8 +529,10 @@ PlaylistDock::PlaylistDock(QWidget *parent) : connect(&m_model, SIGNAL(created()), this, SLOT(onPlaylistCreated())); connect(&m_model, SIGNAL(loaded()), this, SLOT(onPlaylistLoaded())); connect(&m_model, SIGNAL(modified()), this, SLOT(onPlaylistModified())); - connect(&m_model, SIGNAL(dropped(const QMimeData *, int)), this, SLOT(onDropped(const QMimeData *, - int))); + connect(&m_model, + SIGNAL(dropped(const QMimeData *, int)), + this, + SLOT(onDropped(const QMimeData *, int))); connect(&m_model, SIGNAL(moveClip(int, int)), SLOT(onMoveClip(int, int))); m_defaultRowHeight = ui->tableView->verticalHeader()->defaultSectionSize(); @@ -633,8 +580,7 @@ void PlaylistDock::setupActions() action = new QAction(tr("Append"), this); action->setShortcut(QKeySequence(Qt::SHIFT | Qt::Key_A)); action->setToolTip(tr("Add the Source to the playlist")); - icon = QIcon::fromTheme("list-add", - QIcon(":/icons/oxygen/32x32/actions/list-add.png")); + icon = QIcon::fromTheme("list-add", QIcon(":/icons/oxygen/32x32/actions/list-add.png")); action->setIcon(icon); connect(action, &QAction::triggered, this, &PlaylistDock::onAppendCutActionTriggered); Actions.add("playlistAppendCutAction", action); @@ -645,12 +591,11 @@ void PlaylistDock::setupActions() removeShortcuts << QKeySequence(Qt::SHIFT | Qt::Key_Z); action->setShortcuts(removeShortcuts); action->setToolTip(tr("Remove cut")); - icon = QIcon::fromTheme("list-remove", - QIcon(":/icons/oxygen/32x32/actions/list-remove.png")); + icon = QIcon::fromTheme("list-remove", QIcon(":/icons/oxygen/32x32/actions/list-remove.png")); action->setIcon(icon); action->setEnabled(false); connect(action, &QAction::triggered, this, &PlaylistDock::onRemoveActionTriggered); - connect(this, &PlaylistDock::selectionChanged, action, [ = ]() { + connect(this, &PlaylistDock::selectionChanged, action, [=]() { action->setEnabled(m_view->selectionModel()->selectedIndexes().size() > 0); }); Actions.add("playlistRemoveCutAction", action); @@ -665,8 +610,7 @@ void PlaylistDock::setupActions() action = new QAction(tr("Update"), this); action->setShortcut(QKeySequence(Qt::SHIFT | Qt::Key_B)); - icon = QIcon::fromTheme("dialog-ok", - QIcon(":/icons/oxygen/32x32/actions/dialog-ok.png")); + icon = QIcon::fromTheme("dialog-ok", QIcon(":/icons/oxygen/32x32/actions/dialog-ok.png")); action->setIcon(icon); connect(action, &QAction::triggered, this, &PlaylistDock::onUpdateActionTriggered); connect(this, &PlaylistDock::enableUpdate, action, &QAction::setEnabled); @@ -719,7 +663,7 @@ void PlaylistDock::setupActions() action->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_Return)); action->setEnabled(false); connect(action, &QAction::triggered, this, &PlaylistDock::onOpenActionTriggered); - connect(this, &PlaylistDock::selectionChanged, action, [ = ]() { + connect(this, &PlaylistDock::selectionChanged, action, [=]() { action->setEnabled(m_view->currentIndex().isValid() && m_model.playlist()); }); Actions.add("playlistOpenAction", action); @@ -735,7 +679,7 @@ void PlaylistDock::setupActions() action->setShortcut(QKeySequence(Qt::SHIFT | Qt::Key_C)); action->setEnabled(false); connect(action, &QAction::triggered, this, &PlaylistDock::onCopyActionTriggered); - connect(this, &PlaylistDock::selectionChanged, action, [ = ]() { + connect(this, &PlaylistDock::selectionChanged, action, [=]() { action->setEnabled(m_view->currentIndex().isValid() && m_model.playlist()); }); Actions.add("playlistCopyAction", action); @@ -749,7 +693,7 @@ void PlaylistDock::setupActions() action = new QAction(tr("Update Thumbnails"), this); action->setEnabled(false); connect(action, &QAction::triggered, this, &PlaylistDock::onUpdateThumbnailsActionTriggered); - connect(this, &PlaylistDock::selectionChanged, action, [ = ]() { + connect(this, &PlaylistDock::selectionChanged, action, [=]() { action->setEnabled(m_proxyModel->rowCount() > 0); }); Actions.add("playlistUpdateThumbnailsAction", action); @@ -757,7 +701,7 @@ void PlaylistDock::setupActions() action = new QAction(tr("Set Creation Time..."), this); action->setEnabled(false); connect(action, &QAction::triggered, this, &PlaylistDock::onSetFileDateActionTriggered); - connect(this, &PlaylistDock::selectionChanged, action, [ = ]() { + connect(this, &PlaylistDock::selectionChanged, action, [=]() { action->setEnabled(m_view->currentIndex().isValid() && m_model.playlist()); }); Actions.add("playlistSetFileDateAction", action); @@ -777,45 +721,45 @@ void PlaylistDock::setupActions() action = new QAction(tr("Select None"), this); action->setShortcut(QKeySequence(Qt::CTRL | Qt::SHIFT | Qt::Key_D)); connect(action, &QAction::triggered, m_selectionModel, &QItemSelectionModel::clearSelection); - connect(this, &PlaylistDock::selectionChanged, action, [ = ]() { + connect(this, &PlaylistDock::selectionChanged, action, [=]() { action->setEnabled(m_selectionModel->selection().size() > 0); }); Actions.add("playlistSelectNoneAction", action); action = new QAction(tr("Move Up"), this); action->setShortcut(QKeySequence(Qt::CTRL | Qt::SHIFT | Qt::Key_Up)); - connect(action, &QAction::triggered, m_selectionModel, [ = ]() { + connect(action, &QAction::triggered, m_selectionModel, [=]() { raise(); moveClipUp(); incrementIndex(-1); }); - connect(this, &PlaylistDock::selectionChanged, action, [ = ]() { + connect(this, &PlaylistDock::selectionChanged, action, [=]() { action->setEnabled(m_view->currentIndex().isValid() && m_model.playlist()); }); Actions.add("playlistMoveUpAction", action); action = new QAction(tr("Move Down"), this); action->setShortcut(QKeySequence(Qt::CTRL | Qt::SHIFT | Qt::Key_Down)); - connect(action, &QAction::triggered, m_selectionModel, [ = ]() { + connect(action, &QAction::triggered, m_selectionModel, [=]() { raise(); moveClipDown(); incrementIndex(1); }); - connect(this, &PlaylistDock::selectionChanged, action, [ = ]() { + connect(this, &PlaylistDock::selectionChanged, action, [=]() { action->setEnabled(m_view->currentIndex().isValid() && m_model.playlist()); }); Actions.add("playlistMoveDownAction", action); action = new QAction(tr("Add Selected to Timeline"), this); connect(action, &QAction::triggered, this, &PlaylistDock::onAddToTimelineActionTriggered); - connect(this, &PlaylistDock::selectionChanged, action, [ = ]() { + connect(this, &PlaylistDock::selectionChanged, action, [=]() { action->setEnabled(m_selectionModel->selection().size() > 0); }); Actions.add("playlistAddToTimelineAction", action); action = new QAction(tr("Add Selected to Slideshow"), this); connect(action, &QAction::triggered, this, &PlaylistDock::onAddToSlideshowActionTriggered); - connect(this, &PlaylistDock::selectionChanged, action, [ = ]() { + connect(this, &PlaylistDock::selectionChanged, action, [=]() { action->setEnabled(m_selectionModel->selection().size() > 0); }); Actions.add("playlistAddToSlideshowAction", action); @@ -823,16 +767,16 @@ void PlaylistDock::setupActions() action = new QAction(tr("Sort By Name"), this); connect(action, &QAction::triggered, this, [&](bool checked) { resetPlaylistIndex(); - MAIN.undoStack()->push(new Playlist::SortCommand(m_model, PlaylistModel::COLUMN_RESOURCE, - Qt::AscendingOrder)); + MAIN.undoStack()->push( + new Playlist::SortCommand(m_model, PlaylistModel::COLUMN_RESOURCE, Qt::AscendingOrder)); }); Actions.add("playlistSortByNameAction", action); action = new QAction(tr("Sort By Date"), this); connect(action, &QAction::triggered, this, [&](bool checked) { resetPlaylistIndex(); - MAIN.undoStack()->push(new Playlist::SortCommand(m_model, PlaylistModel::COLUMN_DATE, - Qt::AscendingOrder)); + MAIN.undoStack()->push( + new Playlist::SortCommand(m_model, PlaylistModel::COLUMN_DATE, Qt::AscendingOrder)); }); Actions.add("playlistSortByDateAction", action); @@ -857,7 +801,8 @@ void PlaylistDock::setupActions() if (checked) { bool refreshThumbs = Settings.playlistThumbnails() != "tall"; Settings.setPlaylistThumbnails("wide"); - if (refreshThumbs) m_model.refreshThumbnails(); + if (refreshThumbs) + m_model.refreshThumbnails(); ui->tableView->setColumnHidden(PlaylistModel::COLUMN_THUMBNAIL, false); ui->tableView->verticalHeader()->setDefaultSectionSize(PlaylistModel::THUMBNAIL_HEIGHT); ui->tableView->resizeColumnToContents(PlaylistModel::COLUMN_THUMBNAIL); @@ -872,9 +817,11 @@ void PlaylistDock::setupActions() if (checked) { bool refreshThumbs = Settings.playlistThumbnails() != "wide"; Settings.setPlaylistThumbnails("tall"); - if (refreshThumbs) m_model.refreshThumbnails(); + if (refreshThumbs) + m_model.refreshThumbnails(); ui->tableView->setColumnHidden(PlaylistModel::COLUMN_THUMBNAIL, false); - ui->tableView->verticalHeader()->setDefaultSectionSize(PlaylistModel::THUMBNAIL_HEIGHT * 2); + ui->tableView->verticalHeader()->setDefaultSectionSize(PlaylistModel::THUMBNAIL_HEIGHT + * 2); ui->tableView->resizeColumnToContents(PlaylistModel::COLUMN_THUMBNAIL); } }); @@ -887,7 +834,8 @@ void PlaylistDock::setupActions() if (checked) { bool refreshThumbs = Settings.playlistThumbnails() == "hidden"; Settings.setPlaylistThumbnails("small"); - if (refreshThumbs) m_model.refreshThumbnails(); + if (refreshThumbs) + m_model.refreshThumbnails(); ui->tableView->setColumnHidden(PlaylistModel::COLUMN_THUMBNAIL, false); ui->tableView->verticalHeader()->setDefaultSectionSize(PlaylistModel::THUMBNAIL_HEIGHT); ui->tableView->resizeColumnToContents(PlaylistModel::COLUMN_THUMBNAIL); @@ -902,9 +850,11 @@ void PlaylistDock::setupActions() if (checked) { bool refreshThumbs = Settings.playlistThumbnails() == "hidden"; Settings.setPlaylistThumbnails("large"); - if (refreshThumbs) m_model.refreshThumbnails(); + if (refreshThumbs) + m_model.refreshThumbnails(); ui->tableView->setColumnHidden(PlaylistModel::COLUMN_THUMBNAIL, false); - ui->tableView->verticalHeader()->setDefaultSectionSize(PlaylistModel::THUMBNAIL_HEIGHT * 2); + ui->tableView->verticalHeader()->setDefaultSectionSize(PlaylistModel::THUMBNAIL_HEIGHT + * 2); ui->tableView->resizeColumnToContents(PlaylistModel::COLUMN_THUMBNAIL); } }); @@ -922,12 +872,12 @@ void PlaylistDock::setupActions() action = new QAction(tr("Open Previous"), this); action->setShortcut(QKeySequence(Qt::ALT | Qt::Key_Up)); action->setEnabled(false); - connect(action, &QAction::triggered, this, [ = ]() { + connect(action, &QAction::triggered, this, [=]() { raise(); incrementIndex(-1); onOpenActionTriggered(); }); - connect(this, &PlaylistDock::selectionChanged, action, [ = ]() { + connect(this, &PlaylistDock::selectionChanged, action, [=]() { action->setEnabled(m_view->currentIndex().isValid() && m_model.playlist()); }); Actions.add("playlistOpenPreviousAction", action); @@ -935,12 +885,12 @@ void PlaylistDock::setupActions() action = new QAction(tr("Open Next"), this); action->setShortcut(QKeySequence(Qt::ALT | Qt::Key_Down)); action->setEnabled(false); - connect(action, &QAction::triggered, this, [ = ]() { + connect(action, &QAction::triggered, this, [=]() { raise(); incrementIndex(1); onOpenActionTriggered(); }); - connect(this, &PlaylistDock::selectionChanged, action, [ = ]() { + connect(this, &PlaylistDock::selectionChanged, action, [=]() { action->setEnabled(m_view->currentIndex().isValid() && m_model.playlist()); }); Actions.add("playlistOpenNextAction", action); @@ -948,24 +898,23 @@ void PlaylistDock::setupActions() action = new QAction(tr("Select Clip 1"), this); action->setShortcut(QKeySequence(Qt::Key_1)); action->setEnabled(false); - connect(action, &QAction::triggered, this, [ = ]() { + connect(action, &QAction::triggered, this, [=]() { raise(); setIndex(0); }); - connect(this, &PlaylistDock::selectionChanged, action, [ = ]() { + connect(this, &PlaylistDock::selectionChanged, action, [=]() { action->setEnabled(m_proxyModel->rowCount() > 0); }); Actions.add("playlistSelectClip1Action", action); - \ action = new QAction(tr("Select Clip 2"), this); action->setShortcut(QKeySequence(Qt::Key_2)); action->setEnabled(false); - connect(action, &QAction::triggered, this, [ = ]() { + connect(action, &QAction::triggered, this, [=]() { raise(); setIndex(1); }); - connect(this, &PlaylistDock::selectionChanged, action, [ = ]() { + connect(this, &PlaylistDock::selectionChanged, action, [=]() { action->setEnabled(m_proxyModel->rowCount() > 1); }); Actions.add("playlistSelectClip2Action", action); @@ -973,11 +922,11 @@ void PlaylistDock::setupActions() action = new QAction(tr("Select Clip 3"), this); action->setShortcut(QKeySequence(Qt::Key_3)); action->setEnabled(false); - connect(action, &QAction::triggered, this, [ = ]() { + connect(action, &QAction::triggered, this, [=]() { raise(); setIndex(2); }); - connect(this, &PlaylistDock::selectionChanged, action, [ = ]() { + connect(this, &PlaylistDock::selectionChanged, action, [=]() { action->setEnabled(m_proxyModel->rowCount() > 2); }); Actions.add("playlistSelectClip3Action", action); @@ -985,11 +934,11 @@ void PlaylistDock::setupActions() action = new QAction(tr("Select Clip 4"), this); action->setShortcut(QKeySequence(Qt::Key_4)); action->setEnabled(false); - connect(action, &QAction::triggered, this, [ = ]() { + connect(action, &QAction::triggered, this, [=]() { raise(); setIndex(3); }); - connect(this, &PlaylistDock::selectionChanged, action, [ = ]() { + connect(this, &PlaylistDock::selectionChanged, action, [=]() { action->setEnabled(m_proxyModel->rowCount() > 3); }); Actions.add("playlistSelectClip4Action", action); @@ -997,11 +946,11 @@ void PlaylistDock::setupActions() action = new QAction(tr("Select Clip 5"), this); action->setShortcut(QKeySequence(Qt::Key_5)); action->setEnabled(false); - connect(action, &QAction::triggered, this, [ = ]() { + connect(action, &QAction::triggered, this, [=]() { raise(); setIndex(4); }); - connect(this, &PlaylistDock::selectionChanged, action, [ = ]() { + connect(this, &PlaylistDock::selectionChanged, action, [=]() { action->setEnabled(m_proxyModel->rowCount() > 4); }); Actions.add("playlistSelectClip5Action", action); @@ -1009,11 +958,11 @@ void PlaylistDock::setupActions() action = new QAction(tr("Select Clip 6"), this); action->setShortcut(QKeySequence(Qt::Key_6)); action->setEnabled(false); - connect(action, &QAction::triggered, this, [ = ]() { + connect(action, &QAction::triggered, this, [=]() { raise(); setIndex(5); }); - connect(this, &PlaylistDock::selectionChanged, action, [ = ]() { + connect(this, &PlaylistDock::selectionChanged, action, [=]() { action->setEnabled(m_proxyModel->rowCount() > 5); }); Actions.add("playlistSelectClip6Action", action); @@ -1021,11 +970,11 @@ void PlaylistDock::setupActions() action = new QAction(tr("Select Clip 7"), this); action->setShortcut(QKeySequence(Qt::Key_7)); action->setEnabled(false); - connect(action, &QAction::triggered, this, [ = ]() { + connect(action, &QAction::triggered, this, [=]() { raise(); setIndex(6); }); - connect(this, &PlaylistDock::selectionChanged, action, [ = ]() { + connect(this, &PlaylistDock::selectionChanged, action, [=]() { action->setEnabled(m_proxyModel->rowCount() > 6); }); Actions.add("playlistSelectClip7Action", action); @@ -1033,11 +982,11 @@ void PlaylistDock::setupActions() action = new QAction(tr("Select Clip 8"), this); action->setShortcut(QKeySequence(Qt::Key_8)); action->setEnabled(false); - connect(action, &QAction::triggered, this, [ = ]() { + connect(action, &QAction::triggered, this, [=]() { raise(); setIndex(7); }); - connect(this, &PlaylistDock::selectionChanged, action, [ = ]() { + connect(this, &PlaylistDock::selectionChanged, action, [=]() { action->setEnabled(m_proxyModel->rowCount() > 7); }); Actions.add("playlistSelectClip8Action", action); @@ -1045,11 +994,11 @@ void PlaylistDock::setupActions() action = new QAction(tr("Select Clip 9"), this); action->setShortcut(QKeySequence(Qt::Key_9)); action->setEnabled(false); - connect(action, &QAction::triggered, this, [ = ]() { + connect(action, &QAction::triggered, this, [=]() { raise(); setIndex(8); }); - connect(this, &PlaylistDock::selectionChanged, action, [ = ]() { + connect(this, &PlaylistDock::selectionChanged, action, [=]() { action->setEnabled(m_proxyModel->rowCount() > 8); }); Actions.add("playlistSelectClip9Action", action); @@ -1057,7 +1006,7 @@ void PlaylistDock::setupActions() action = new QAction(tr("Thumbnails"), this); action->setChecked(Settings.playlistShowColumn("thumbnails")); action->setCheckable(true); - connect(action, &QAction::triggered, this, [ = ](bool checked) { + connect(action, &QAction::triggered, this, [=](bool checked) { Settings.setPlaylistShowColumn("thumbnails", checked); ui->tableView->setColumnHidden(PlaylistModel::COLUMN_THUMBNAIL, !checked); }); @@ -1066,7 +1015,7 @@ void PlaylistDock::setupActions() action = new QAction(tr("Clip"), this); action->setChecked(Settings.playlistShowColumn("clip")); action->setCheckable(true); - connect(action, &QAction::triggered, this, [ = ](bool checked) { + connect(action, &QAction::triggered, this, [=](bool checked) { Settings.setPlaylistShowColumn("clip", checked); ui->tableView->setColumnHidden(PlaylistModel::COLUMN_RESOURCE, !checked); }); @@ -1075,7 +1024,7 @@ void PlaylistDock::setupActions() action = new QAction(tr("In"), this); action->setChecked(Settings.playlistShowColumn("in")); action->setCheckable(true); - connect(action, &QAction::triggered, this, [ = ](bool checked) { + connect(action, &QAction::triggered, this, [=](bool checked) { Settings.setPlaylistShowColumn("in", checked); ui->tableView->setColumnHidden(PlaylistModel::COLUMN_IN, !checked); }); @@ -1084,7 +1033,7 @@ void PlaylistDock::setupActions() action = new QAction(tr("Duration"), this); action->setChecked(Settings.playlistShowColumn("duration")); action->setCheckable(true); - connect(action, &QAction::triggered, this, [ = ](bool checked) { + connect(action, &QAction::triggered, this, [=](bool checked) { Settings.setPlaylistShowColumn("duration", checked); ui->tableView->setColumnHidden(PlaylistModel::COLUMN_DURATION, !checked); }); @@ -1093,7 +1042,7 @@ void PlaylistDock::setupActions() action = new QAction(tr("Start"), this); action->setChecked(Settings.playlistShowColumn("start")); action->setCheckable(true); - connect(action, &QAction::triggered, this, [ = ](bool checked) { + connect(action, &QAction::triggered, this, [=](bool checked) { Settings.setPlaylistShowColumn("start", checked); ui->tableView->setColumnHidden(PlaylistModel::COLUMN_START, !checked); }); @@ -1102,7 +1051,7 @@ void PlaylistDock::setupActions() action = new QAction(tr("Date"), this); action->setChecked(Settings.playlistShowColumn("date")); action->setCheckable(true); - connect(action, &QAction::triggered, this, [ = ](bool checked) { + connect(action, &QAction::triggered, this, [=](bool checked) { Settings.setPlaylistShowColumn("date", checked); ui->tableView->setColumnHidden(PlaylistModel::COLUMN_DATE, !checked); }); @@ -1111,7 +1060,7 @@ void PlaylistDock::setupActions() action = new QAction(tr("Type"), this); action->setChecked(Settings.playlistShowColumn("type")); action->setCheckable(true); - connect(action, &QAction::triggered, this, [ = ](bool checked) { + connect(action, &QAction::triggered, this, [=](bool checked) { Settings.setPlaylistShowColumn("type", checked); ui->tableView->setColumnHidden(PlaylistModel::COLUMN_MEDIA_TYPE, !checked); }); @@ -1143,11 +1092,10 @@ void PlaylistDock::setupActions() action = new QAction(tr("New Bin"), this); action->setToolTip(tr("New Bin")); - icon = QIcon::fromTheme("folder-new", - QIcon(":/icons/oxygen/32x32/actions/folder-new.png")); + icon = QIcon::fromTheme("folder-new", QIcon(":/icons/oxygen/32x32/actions/folder-new.png")); action->setIcon(icon); Actions.add("playlistNewBin", action, windowTitle()); - connect(action, &QAction::triggered, this, [ = ]() { + connect(action, &QAction::triggered, this, [=]() { if (!m_model.playlist() || !m_model.playlist()->is_valid()) return; ui->treeWidget->setVisible(true); @@ -1166,11 +1114,10 @@ void PlaylistDock::setupActions() action = new QAction(tr("Bins"), this); action->setToolTip(tr("Show or hide the list of bins")); - icon = QIcon::fromTheme("view-choose", - QIcon(":/icons/oxygen/32x32/actions/view-choose.png")); + icon = QIcon::fromTheme("view-choose", QIcon(":/icons/oxygen/32x32/actions/view-choose.png")); action->setIcon(icon); action->setCheckable(true); - connect(action, &QAction::triggered, this, [ = ](bool checked) { + connect(action, &QAction::triggered, this, [=](bool checked) { ui->treeWidget->setVisible(checked); }); Actions.add("playlistBinView", action, windowTitle()); @@ -1179,7 +1126,7 @@ void PlaylistDock::setupActions() action->setToolTip(tr("Remove Bin")); action->setDisabled(true); Actions.add("playlistRemoveBin", action, windowTitle()); - connect(action, &QAction::triggered, this, [ = ]() { + connect(action, &QAction::triggered, this, [=]() { auto items = ui->treeWidget->selectedItems(); if (!items.isEmpty()) { auto bin = ui->treeWidget->selectedItems().first()->text(0); @@ -1191,7 +1138,7 @@ void PlaylistDock::setupActions() action->setToolTip(tr("Rename Bin")); action->setDisabled(true); Actions.add("playlistRenameBin", action, windowTitle()); - connect(action, &QAction::triggered, this, [ = ]() { + connect(action, &QAction::triggered, this, [=]() { QInputDialog dialog(this); dialog.setInputMode(QInputDialog::TextInput); dialog.setWindowTitle(action->text()); @@ -1203,14 +1150,15 @@ void PlaylistDock::setupActions() auto items = ui->treeWidget->selectedItems(); if (!items.isEmpty()) { auto bin = ui->treeWidget->selectedItems().first()->text(0); - MAIN.undoStack()->push(new Playlist::RenameBinCommand(m_model, ui->treeWidget, bin, name)); + MAIN.undoStack()->push( + new Playlist::RenameBinCommand(m_model, ui->treeWidget, bin, name)); } } }); action = new QAction(tr("Search"), this); action->setShortcut(QKeySequence(Qt::CTRL | Qt::ALT | Qt::Key_F)); - connect(action, &QAction::triggered, this, [ = ]() { + connect(action, &QAction::triggered, this, [=]() { setVisible(true); raise(); m_searchField->setFocus(); @@ -1224,7 +1172,8 @@ int PlaylistDock::position() QModelIndex index = m_proxyModel->mapToSource(m_view->currentIndex()); if (index.isValid() && m_model.playlist()) { Mlt::ClipInfo *i = m_model.playlist()->clip_info(index.row()); - if (i) result = i->start; + if (i) + result = i->start; delete i; } return result; @@ -1247,7 +1196,8 @@ void PlaylistDock::replaceClipsWithHash(const QString &hash, Mlt::Producer &prod for (auto &clip : producers) { Util::applyCustomProperties(producer, clip.parent(), clip.get_in(), clip.get_out()); MAIN.undoStack()->push( - new Playlist::ReplaceCommand(m_model, MLT.XML(&producer), + new Playlist::ReplaceCommand(m_model, + MLT.XML(&producer), clip.get_int(kPlaylistIndexProperty) - 1)); } if (n > 1) { @@ -1259,7 +1209,7 @@ void PlaylistDock::getSelectionRange(int *start, int *end) { Mlt::Playlist *playlist = m_model.playlist(); if (!playlist || !m_view->selectionModel() - || !m_view->selectionModel()->selectedIndexes().size() ) { + || !m_view->selectionModel()->selectedIndexes().size()) { *start = -1; *end = -1; return; @@ -1291,7 +1241,8 @@ Mlt::Playlist *PlaylistDock::binPlaylist() for (int i = 0; i < count; ++i) { Mlt::ClipInfo info; m_model.playlist()->clip_info(i, &info); - if (info.producer && info.producer->is_valid() && bin == info.producer->get(kShotcutBinsProperty)) + if (info.producer && info.producer->is_valid() + && bin == info.producer->get(kShotcutBinsProperty)) m_binPlaylist.append(*info.producer, info.frame_in, info.frame_out); longTask.reportProgress(tr("Appending"), i, count); } @@ -1345,7 +1296,8 @@ void PlaylistDock::addFiles(int row, const QList &urls) QStringList fileNames = Util::sortedFileList(Util::expandDirectories(urls)); qsizetype i = 0, count = fileNames.size(); for (auto &path : fileNames) { - if (MAIN.isSourceClipMyProject(path)) continue; + if (MAIN.isSourceClipMyProject(path)) + continue; longTask.reportProgress(Util::baseName(path), i++, count); if (MLT.checkFile(path)) { emit showStatusMessage(tr("Failed to open ").append(path)); @@ -1389,7 +1341,8 @@ void PlaylistDock::addFiles(int row, const QList &urls) if (row == -1) MAIN.undoStack()->push(new Playlist::AppendCommand(m_model, MLT.XML(producer))); else - MAIN.undoStack()->push(new Playlist::InsertCommand(m_model, MLT.XML(producer), insertNextAt++)); + MAIN.undoStack()->push( + new Playlist::InsertCommand(m_model, MLT.XML(producer), insertNextAt++)); } else { LongUiTask::cancel(); DurationDialog durationDialog(this); @@ -1398,9 +1351,11 @@ void PlaylistDock::addFiles(int row, const QList &urls) producer->set_in_and_out(0, durationDialog.duration() - 1); assignToBin(*producer); if (row == -1) - MAIN.undoStack()->push(new Playlist::AppendCommand(m_model, MLT.XML(producer))); + MAIN.undoStack()->push( + new Playlist::AppendCommand(m_model, MLT.XML(producer))); else - MAIN.undoStack()->push(new Playlist::InsertCommand(m_model, MLT.XML(producer), insertNextAt++)); + MAIN.undoStack()->push( + new Playlist::InsertCommand(m_model, MLT.XML(producer), insertNextAt++)); } } if (first) { @@ -1490,8 +1445,8 @@ void PlaylistDock::onInsertCutActionTriggered() show(); raise(); QMimeData mimeData; - mimeData.setData(Mlt::XmlMimeType, MLT.XML( - MLT.isClip() ? nullptr : MLT.savedProducer()).toUtf8()); + mimeData.setData(Mlt::XmlMimeType, + MLT.XML(MLT.isClip() ? nullptr : MLT.savedProducer()).toUtf8()); auto index = m_proxyModel->mapToSource(m_view->currentIndex()); onDropped(&mimeData, index.row()); } @@ -1504,8 +1459,7 @@ void PlaylistDock::onAppendCutActionTriggered() if (!MLT.isLiveProducer(&producer)) { ProxyManager::generateIfNotExists(producer); assignToBin(producer); - MAIN.undoStack()->push( - new Playlist::AppendCommand(m_model, MLT.XML(&producer))); + MAIN.undoStack()->push(new Playlist::AppendCommand(m_model, MLT.XML(&producer))); setPlaylistIndex(&producer, m_model.playlist()->count() - 1); emit enableUpdate(true); } else { @@ -1527,16 +1481,19 @@ void PlaylistDock::onAppendCutActionTriggered() void PlaylistDock::onUpdateActionTriggered() { QModelIndex index = m_proxyModel->mapToSource(m_view->currentIndex()); - if (!index.isValid() || !m_model.playlist() || MAIN.isSourceClipMyProject()) return; + if (!index.isValid() || !m_model.playlist() || MAIN.isSourceClipMyProject()) + return; QScopedPointer info(m_model.playlist()->clip_info(index.row())); Mlt::Producer producer(MLT.isClip() ? MLT.producer() : MLT.savedProducer()); - if (!info || !producer.is_valid()) return; + if (!info || !producer.is_valid()) + return; if (producer.type() != mlt_service_playlist_type) { show(); raise(); if (!MLT.isLiveProducer(&producer)) { ProxyManager::generateIfNotExists(producer); - MAIN.undoStack()->push(new Playlist::UpdateCommand(m_model, MLT.XML(&producer), index.row())); + MAIN.undoStack()->push( + new Playlist::UpdateCommand(m_model, MLT.XML(&producer), index.row())); setPlaylistIndex(&producer, index.row()); emit enableUpdate(true); } else { @@ -1560,7 +1517,8 @@ void PlaylistDock::onUpdateActionTriggered() void PlaylistDock::onRemoveActionTriggered() { - if (!m_model.playlist() || !m_view->selectionModel()) return; + if (!m_model.playlist() || !m_view->selectionModel()) + return; show(); raise(); QList rowsRemoved; @@ -1595,9 +1553,11 @@ void PlaylistDock::onRemoveActionTriggered() void PlaylistDock::onSetFileDateActionTriggered() { QModelIndex index = m_proxyModel->mapToSource(m_view->currentIndex()); - if (!index.isValid() || !m_model.playlist()) return; + if (!index.isValid() || !m_model.playlist()) + return; int count = m_model.playlist()->count(); - if (count == 0) return; + if (count == 0) + return; int i = index.row() >= count ? count - 1 : index.row(); QScopedPointer info(m_model.playlist()->clip_info(i)); if (info && info->producer && info->producer->is_valid()) { @@ -1622,7 +1582,8 @@ void PlaylistDock::onProducerOpened() if (row < 0 && m_model.rowCount() > 0) { resetPlaylistIndex(); emit m_model.dataChanged(m_model.createIndex(0, PlaylistModel::COLUMN_THUMBNAIL), - m_model.createIndex(m_model.playlist()->count() - 1, PlaylistModel::COLUMN_THUMBNAIL), + m_model.createIndex(m_model.playlist()->count() - 1, + PlaylistModel::COLUMN_THUMBNAIL), QVector() << PlaylistModel::COLUMN_THUMBNAIL); } } @@ -1652,7 +1613,8 @@ void PlaylistDock::onOutChanged() void PlaylistDock::onOpenActionTriggered() { QModelIndex index = m_proxyModel->mapToSource(m_view->currentIndex()); - if (!index.isValid() || !m_model.playlist()) return; + if (!index.isValid() || !m_model.playlist()) + return; Mlt::ClipInfo *i = m_model.playlist()->clip_info(index.row()); if (i) { Mlt::Producer *p = new Mlt::Producer(i->producer); @@ -1681,10 +1643,10 @@ void PlaylistDock::viewCustomContextMenuRequested(const QPoint &pos) } } - void PlaylistDock::viewDoubleClicked(const QModelIndex &index) { - if (!m_model.playlist()) return; + if (!m_model.playlist()) + return; auto sourceIndex = m_proxyModel->mapToSource(index); Mlt::ClipInfo *i = m_model.playlist()->clip_info(sourceIndex.row()); if (i) { @@ -1779,9 +1741,7 @@ void PlaylistDock::onDropped(const QMimeData *data, int row) if (data && data->hasUrls()) { // Use QTimer to workaround stupid drag from Windows Explorer bug const auto &urls = data->urls(); - QTimer::singleShot(0, this, [ = ]() { - addFiles(row, urls); - }); + QTimer::singleShot(0, this, [=]() { addFiles(row, urls); }); } else if (data && data->hasFormat(Mlt::XmlMimeType)) { if (MLT.producer() && MLT.producer()->is_valid()) { if (MLT.producer()->type() == mlt_service_playlist_type) { @@ -1789,7 +1749,9 @@ void PlaylistDock::onDropped(const QMimeData *data, int row) } else if (MAIN.isSourceClipMyProject()) { return; } else if (!MLT.isLiveProducer()) { - Mlt::Producer p(MLT.profile(), "xml-string", data->data(Mlt::XmlMimeType).constData()); + Mlt::Producer p(MLT.profile(), + "xml-string", + data->data(Mlt::XmlMimeType).constData()); assignToBin(p); ProxyManager::generateIfNotExists(p); if (row == -1) { @@ -1806,7 +1768,8 @@ void PlaylistDock::onDropped(const QMimeData *data, int row) dialog.setDuration(MLT.profile().fps() * 5); if (dialog.exec() == QDialog::Accepted) { MLT.producer()->set_in_and_out(0, dialog.duration() - 1); - if (MLT.producer()->get("mlt_service") && !strcmp(MLT.producer()->get("mlt_service"), "avformat")) + if (MLT.producer()->get("mlt_service") + && !strcmp(MLT.producer()->get("mlt_service"), "avformat")) MLT.producer()->set("mlt_service", "avformat-novalidate"); assignToBin(*MLT.producer()); if (row == -1) @@ -1837,7 +1800,8 @@ void PlaylistDock::onAddToTimelineActionTriggered() const QModelIndexList &indexes = m_view->selectionModel()->selectedIndexes(); Mlt::Playlist playlist(MLT.profile()); for (const auto &index : indexes) { - if (index.column()) continue; + if (index.column()) + continue; auto row = m_proxyModel->mapToSource(index).row(); QScopedPointer info(m_model.playlist()->clip_info(row)); if (info && info->producer) { @@ -1853,25 +1817,28 @@ void PlaylistDock::onAddToSlideshowActionTriggered() const QModelIndexList &indexes = m_view->selectionModel()->selectedIndexes(); Mlt::Playlist playlist(MLT.profile()); for (const auto &index : indexes) { - if (index.column()) continue; + if (index.column()) + continue; auto row = m_proxyModel->mapToSource(index).row(); QScopedPointer info(m_model.playlist()->clip_info(row)); if (info && info->producer) { playlist.append(*info->producer, info->frame_in, info->frame_out); } } - if (playlist.count() <= 0 ) { + if (playlist.count() <= 0) { return; } SlideshowGeneratorDialog dialog(this, playlist); dialog.setWindowModality(QmlApplication::dialogModality()); - if (dialog.exec() == QDialog::Accepted ) { + if (dialog.exec() == QDialog::Accepted) { LongUiTask longTask(QObject::tr("Generate Slideshow")); - Mlt::Playlist *slideshow = longTask.runAsync(tr("Generating"), - &SlideshowGeneratorDialog::getSlideshow, &dialog); + Mlt::Playlist *slideshow + = longTask.runAsync(tr("Generating"), + &SlideshowGeneratorDialog::getSlideshow, + &dialog); if (slideshow) { - if ( slideshow->count() > 0 ) { + if (slideshow->count() > 0) { emit addAllTimeline(slideshow, /* skipProxy */ true); } delete slideshow; @@ -1885,7 +1852,7 @@ void PlaylistDock::onProducerChanged(Mlt::Producer *producer) return; int index = producer->get_int(kPlaylistIndexProperty) - 1; if (index < 0 || !m_model.playlist() || !m_model.playlist()->is_valid() - || index >= m_model.playlist()->count()) + || index >= m_model.playlist()->count()) return; MAIN.undoStack()->push(new Playlist::UpdateCommand(m_model, MLT.XML(producer), index)); emit enableUpdate(false); @@ -1917,8 +1884,10 @@ void PlaylistDock::updateViewMode() ui->tableView->setColumnHidden(PlaylistModel::COLUMN_IN, !Settings.playlistShowColumn("in")); ui->tableView->setColumnHidden(PlaylistModel::COLUMN_DURATION, !Settings.playlistShowColumn("duration")); - ui->tableView->setColumnHidden(PlaylistModel::COLUMN_START, !Settings.playlistShowColumn("start")); - ui->tableView->setColumnHidden(PlaylistModel::COLUMN_DATE, !Settings.playlistShowColumn("date")); + ui->tableView->setColumnHidden(PlaylistModel::COLUMN_START, + !Settings.playlistShowColumn("start")); + ui->tableView->setColumnHidden(PlaylistModel::COLUMN_DATE, + !Settings.playlistShowColumn("date")); ui->tableView->setColumnHidden(PlaylistModel::COLUMN_MEDIA_TYPE, !Settings.playlistShowColumn("type")); ui->tableView->resizeColumnsToContents(); @@ -1954,7 +1923,8 @@ void PlaylistDock::resetPlaylistIndex() void PlaylistDock::emitDataChanged(const QVector &roles) { auto row = MLT.producer()->get_int(kPlaylistIndexProperty) - 1; - if (row < 0 || row >= m_model.rowCount()) return; + if (row < 0 || row >= m_model.rowCount()) + return; auto index = m_model.createIndex(row, PlaylistModel::COLUMN_RESOURCE); emit m_model.dataChanged(index, index, roles); } @@ -1983,10 +1953,10 @@ void PlaylistDock::onInTimerFired() if (index < 0 || !m_model.playlist() || !m_model.playlist()->is_valid()) return; QScopedPointer info(m_model.playlist()->clip_info(index)); - if (info && info->producer - && info->producer->get_producer() == MLT.producer()->get_producer() - && info->frame_in != MLT.producer()->get_in()) { - MAIN.undoStack()->push(new Playlist::TrimClipInCommand(m_model, index, MLT.producer()->get_in())); + if (info && info->producer && info->producer->get_producer() == MLT.producer()->get_producer() + && info->frame_in != MLT.producer()->get_in()) { + MAIN.undoStack()->push( + new Playlist::TrimClipInCommand(m_model, index, MLT.producer()->get_in())); emit enableUpdate(false); } } @@ -1997,10 +1967,10 @@ void PlaylistDock::onOutTimerFired() if (index < 0 || !m_model.playlist() || !m_model.playlist()->is_valid()) return; QScopedPointer info(m_model.playlist()->clip_info(index)); - if (info && info->producer - && info->producer->get_producer() == MLT.producer()->get_producer() - && info->frame_out != MLT.producer()->get_out()) { - MAIN.undoStack()->push(new Playlist::TrimClipOutCommand(m_model, index, MLT.producer()->get_out())); + if (info && info->producer && info->producer->get_producer() == MLT.producer()->get_producer() + && info->frame_out != MLT.producer()->get_out()) { + MAIN.undoStack()->push( + new Playlist::TrimClipOutCommand(m_model, index, MLT.producer()->get_out())); emit enableUpdate(false); } } @@ -2024,7 +1994,8 @@ void PlaylistDock::keyReleaseEvent(QKeyEvent *event) void PlaylistDock::onCopyActionTriggered() { QModelIndex index = m_proxyModel->mapToSource(m_view->currentIndex()); - if (!index.isValid() || !m_model.playlist()) return; + if (!index.isValid() || !m_model.playlist()) + return; Mlt::ClipInfo *i = m_model.playlist()->clip_info(index.row()); if (i) { show(); @@ -2053,7 +2024,8 @@ void PlaylistDock::onSelectAllActionTriggered() void PlaylistDock::onUpdateThumbnailsActionTriggered() { - if (!m_model.playlist()) return; + if (!m_model.playlist()) + return; m_view->selectionModel()->clearSelection(); for (auto i = 0; i < m_model.rowCount(); i++) { m_model.updateThumbnails(i); @@ -2062,7 +2034,8 @@ void PlaylistDock::onUpdateThumbnailsActionTriggered() void PlaylistDock::onProducerModified() { - if (!m_model.playlist()) return; + if (!m_model.playlist()) + return; emit enableUpdate(true); // The clip name may have changed. @@ -2079,8 +2052,12 @@ void PlaylistDock::onAddFilesActionTriggered() path.append("/*"); #endif LOG_DEBUG() << Util::getFileDialogOptions(); - QStringList filenames = QFileDialog::getOpenFileNames(this, tr("Open File"), path, - tr("All Files (*);;MLT XML (*.mlt)"), nullptr, Util::getFileDialogOptions()); + QStringList filenames = QFileDialog::getOpenFileNames(this, + tr("Open File"), + path, + tr("All Files (*);;MLT XML (*.mlt)"), + nullptr, + Util::getFileDialogOptions()); if (filenames.length() > 0) { Settings.setOpenPath(QFileInfo(filenames.first()).path()); @@ -2119,9 +2096,7 @@ void PlaylistDock::on_treeWidget_itemSelectionChanged() m_proxyModel->setBin(items.first()->text(0)); } if (ui->treeWidget->topLevelItemCount() >= SmartBinCount) - for (auto action : { - Actions["playlistRemoveBin"], Actions["playlistRenameBin"] - }) { + for (auto action : {Actions["playlistRemoveBin"], Actions["playlistRenameBin"]}) { action->setEnabled(true); for (int i = 0; i < SmartBinCount; ++i) { if (ui->treeWidget->topLevelItem(i)->isSelected()) { diff --git a/src/docks/playlistdock.h b/src/docks/playlistdock.h index 4d1f9b2979..578b6699cb 100644 --- a/src/docks/playlistdock.h +++ b/src/docks/playlistdock.h @@ -18,11 +18,12 @@ #ifndef PLAYLISTDOCK_H #define PLAYLISTDOCK_H +#include "models/playlistmodel.h" + #include -#include #include #include -#include "models/playlistmodel.h" +#include namespace Ui { class PlaylistDock; @@ -67,10 +68,7 @@ class PlaylistDock : public QDockWidget explicit PlaylistDock(QWidget *parent = 0); ~PlaylistDock(); - PlaylistModel *model() - { - return &m_model; - } + PlaylistModel *model() { return &m_model; } int position(); void replaceClipsWithHash(const QString &hash, Mlt::Producer &producer); void getSelectionRange(int *start, int *end); diff --git a/src/docks/recentdock.cpp b/src/docks/recentdock.cpp index f0f17d6a24..47635b035e 100644 --- a/src/docks/recentdock.cpp +++ b/src/docks/recentdock.cpp @@ -15,22 +15,23 @@ * along with this program. If not, see . */ -#include "docks/recentdock.h" -#include "settings.h" +#include "recentdock.h" #include "ui_recentdock.h" + +#include "Logger.h" +#include "settings.h" #include "util.h" #include #include #include #include -#include static const int MaxItems = 200; -RecentDock::RecentDock(QWidget *parent) : - QDockWidget(parent), - ui(new Ui::RecentDock) +RecentDock::RecentDock(QWidget *parent) + : QDockWidget(parent) + , ui(new Ui::RecentDock) { LOG_DEBUG() << "begin"; ui->setupUi(this); @@ -80,7 +81,8 @@ void RecentDock::add(const QString &s) return; QString filePath = QDir::fromNativeSeparators(s); - if (filePath.startsWith(QDir::tempPath())) return; + if (filePath.startsWith(QDir::tempPath())) + return; QString name = remove(s); QStandardItem *item = new QStandardItem(name); item->setToolTip(QDir::toNativeSeparators(s)); diff --git a/src/docks/recentdock.h b/src/docks/recentdock.h index dfa0fc0d14..08186e39bd 100644 --- a/src/docks/recentdock.h +++ b/src/docks/recentdock.h @@ -19,8 +19,8 @@ #define RECENTDOCK_H #include -#include #include +#include namespace Ui { class RecentDock; diff --git a/src/docks/scopedock.cpp b/src/docks/scopedock.cpp index 9387ec5d08..b9a733c47d 100644 --- a/src/docks/scopedock.cpp +++ b/src/docks/scopedock.cpp @@ -17,15 +17,15 @@ #include "scopedock.h" +#include "Logger.h" #include "controllers/scopecontroller.h" #include "mltcontroller.h" -#include -#include #include +#include -ScopeDock::ScopeDock(ScopeController *scopeController, ScopeWidget *scopeWidget) : - QDockWidget() +ScopeDock::ScopeDock(ScopeController *scopeController, ScopeWidget *scopeWidget) + : QDockWidget() , m_scopeController(scopeController) , m_scopeWidget(scopeWidget) { @@ -56,11 +56,15 @@ void ScopeDock::resizeEvent(QResizeEvent *e) void ScopeDock::onActionToggled(bool checked) { if (checked) { - connect(m_scopeController, SIGNAL(newFrame(const SharedFrame &)), m_scopeWidget, + connect(m_scopeController, + SIGNAL(newFrame(const SharedFrame &)), + m_scopeWidget, SLOT(onNewFrame(const SharedFrame &))); MLT.refreshConsumer(); } else { - disconnect(m_scopeController, SIGNAL(newFrame(const SharedFrame &)), m_scopeWidget, + disconnect(m_scopeController, + SIGNAL(newFrame(const SharedFrame &)), + m_scopeWidget, SLOT(onNewFrame(const SharedFrame &))); } } diff --git a/src/docks/scopedock.h b/src/docks/scopedock.h index e989761875..ab8d75bc78 100644 --- a/src/docks/scopedock.h +++ b/src/docks/scopedock.h @@ -20,6 +20,7 @@ #define SCOPEDOCK_H #include "widgets/scopes/scopewidget.h" + #include #include @@ -39,7 +40,7 @@ class ScopeDock Q_DECL_FINAL : public QDockWidget ScopeController *m_scopeController; ScopeWidget *m_scopeWidget; - void setWidget(QWidget *widget); // Private to disallow use + void setWidget(QWidget *widget); // Private to disallow use private slots: void onActionToggled(bool checked); diff --git a/src/docks/subtitlesdock.cpp b/src/docks/subtitlesdock.cpp index 50a5829939..ee544724fb 100644 --- a/src/docks/subtitlesdock.cpp +++ b/src/docks/subtitlesdock.cpp @@ -17,24 +17,23 @@ #include "subtitlesdock.h" +#include "Logger.h" #include "actions.h" -#include "mainwindow.h" -#include "settings.h" -#include "shotcut_mlt_properties.h" -#include "util.h" #include "dialogs/subtitletrackdialog.h" #include "dialogs/transcribeaudiodialog.h" #include "jobqueue.h" #include "jobs/meltjob.h" #include "jobs/whisperjob.h" +#include "mainwindow.h" #include "models/subtitlesmodel.h" #include "models/subtitlesselectionmodel.h" -#include "widgets/docktoolbar.h" #include "qmltypes/qmlapplication.h" -#include - -#include "MltPlaylist.h" +#include "settings.h" +#include "shotcut_mlt_properties.h" +#include "util.h" +#include "widgets/docktoolbar.h" +#include #include #include #include @@ -52,8 +51,8 @@ #include #include #include -#include #include +#include #include #include @@ -70,7 +69,8 @@ static mlt_position msToPosition(int64_t ms) return ms * MLT.profile().frame_rate_num() / MLT.profile().frame_rate_den() / 1000; } -static QList readSrtFile(const QString &path, int64_t timeOffset, +static QList readSrtFile(const QString &path, + int64_t timeOffset, bool includeNonspoken) { QList items; @@ -97,9 +97,9 @@ static QList readSrtFile(const QString &path, int64_t t line = line.remove(0, 1).simplified(); } // Remove unspoken sounds if requested - if (!includeNonspoken && - ((line.startsWith("[") && line.endsWith("]")) || - (line.startsWith("(") && line.endsWith(")")))) { + if (!includeNonspoken + && ((line.startsWith("[") && line.endsWith("]")) + || (line.startsWith("(") && line.endsWith(")")))) { continue; } if (i != 0) { @@ -119,8 +119,8 @@ static QList readSrtFile(const QString &path, int64_t t return items; } -SubtitlesDock::SubtitlesDock(QWidget *parent) : - QDockWidget(parent) +SubtitlesDock::SubtitlesDock(QWidget *parent) + : QDockWidget(parent) , m_model(nullptr) , m_pos(-1) , m_textEditInProgress(false) @@ -129,7 +129,8 @@ SubtitlesDock::SubtitlesDock(QWidget *parent) : setObjectName("SubtitlesDock"); QDockWidget::setWindowTitle(tr("Subtitles")); - QIcon filterIcon = QIcon::fromTheme("subtitle", QIcon(":/icons/oxygen/32x32/actions/subtitle.png")); + QIcon filterIcon = QIcon::fromTheme("subtitle", + QIcon(":/icons/oxygen/32x32/actions/subtitle.png")); setWindowIcon(filterIcon); toggleViewAction()->setIcon(windowIcon()); @@ -211,8 +212,8 @@ SubtitlesDock::SubtitlesDock(QWidget *parent) : toolbar->setAreaHint(Qt::BottomToolBarArea); auto button = new QToolButton; - button->setIcon(QIcon::fromTheme("show-menu", - QIcon(":/icons/oxygen/32x32/actions/show-menu.png"))); + button->setIcon( + QIcon::fromTheme("show-menu", QIcon(":/icons/oxygen/32x32/actions/show-menu.png"))); button->setToolTip(tr("Subtitles Menu")); button->setAutoRaise(true); button->setMenu(mainMenu); @@ -294,17 +295,15 @@ SubtitlesDock::SubtitlesDock(QWidget *parent) : LOG_DEBUG() << "end"; } -SubtitlesDock::~SubtitlesDock() -{ -} +SubtitlesDock::~SubtitlesDock() {} void SubtitlesDock::setupActions() { QAction *action; action = new QAction(tr("Add Subtitle Track"), this); - action->setIcon(QIcon::fromTheme("list-add", - QIcon(":/icons/oxygen/32x32/actions/list-add.png"))); + action->setIcon( + QIcon::fromTheme("list-add", QIcon(":/icons/oxygen/32x32/actions/list-add.png"))); action->setToolTip(tr("Add a subtitle track")); connect(action, &QAction::triggered, this, [&]() { show(); @@ -314,8 +313,8 @@ void SubtitlesDock::setupActions() Actions.add("subtitleAddTrackAction", action); action = new QAction(tr("Remove Subtitle Track"), this); - action->setIcon(QIcon::fromTheme("list-remove", - QIcon(":/icons/oxygen/32x32/actions/list-remove.png"))); + action->setIcon( + QIcon::fromTheme("list-remove", QIcon(":/icons/oxygen/32x32/actions/list-remove.png"))); action->setToolTip(tr("Remove this subtitle track")); connect(action, &QAction::triggered, this, [&]() { show(); @@ -325,8 +324,8 @@ void SubtitlesDock::setupActions() Actions.add("subtitleRemoveTrackAction", action); action = new QAction(tr("Edit Subtitle Track"), this); - action->setIcon(QIcon::fromTheme("document-edit", - QIcon(":/icons/oxygen/32x32/actions/document-edit.png"))); + action->setIcon( + QIcon::fromTheme("document-edit", QIcon(":/icons/oxygen/32x32/actions/document-edit.png"))); action->setToolTip(tr("Edit this subtitle track")); connect(action, &QAction::triggered, this, [&]() { show(); @@ -359,57 +358,57 @@ void SubtitlesDock::setupActions() action = new QAction(tr("Create/Edit Subtitle"), this); action->setShortcut(QKeySequence(Qt::SHIFT | Qt::Key_Q)); - action->setIcon(QIcon::fromTheme("subtitle", - QIcon(":/icons/oxygen/32x32/actions/subtitle.png"))); + action->setIcon( + QIcon::fromTheme("subtitle", QIcon(":/icons/oxygen/32x32/actions/subtitle.png"))); action->setToolTip(tr("Create or Edit a subtitle at the cursor position.")); connect(action, &QAction::triggered, this, &SubtitlesDock::onCreateOrEditRequested); Actions.add("subtitleCreateEditItemAction", action, windowTitle()); action = new QAction(tr("Add Subtitle Item"), this); action->setShortcut(QKeySequence(Qt::SHIFT | Qt::Key_W)); - action->setIcon(QIcon::fromTheme("list-add", - QIcon(":/icons/oxygen/32x32/actions/list-add.png"))); + action->setIcon( + QIcon::fromTheme("list-add", QIcon(":/icons/oxygen/32x32/actions/list-add.png"))); action->setToolTip(tr("Add a subtitle at the cursor position")); connect(action, &QAction::triggered, this, &SubtitlesDock::onAddRequested); Actions.add("subtitleAddItemAction", action, windowTitle()); action = new QAction(tr("Remove Subtitle Item"), this); action->setShortcut(QKeySequence(Qt::SHIFT | Qt::Key_E)); - action->setIcon(QIcon::fromTheme("list-remove", - QIcon(":/icons/oxygen/32x32/actions/list-remove.png"))); + action->setIcon( + QIcon::fromTheme("list-remove", QIcon(":/icons/oxygen/32x32/actions/list-remove.png"))); action->setToolTip(tr("Remove the selected subtitle item")); connect(action, &QAction::triggered, this, &SubtitlesDock::onRemoveRequested); Actions.add("subtitleRemoveItemAction", action, windowTitle()); action = new QAction(tr("Set Subtitle Start"), this); action->setShortcut(QKeySequence(Qt::SHIFT | Qt::Key_R)); - action->setIcon(QIcon::fromTheme("keyframes-filter-in", - QIcon(":/icons/oxygen/32x32/actions/keyframes-filter-in.png"))); + action->setIcon( + QIcon::fromTheme("keyframes-filter-in", + QIcon(":/icons/oxygen/32x32/actions/keyframes-filter-in.png"))); action->setToolTip(tr("Set the selected subtitle to start at the cursor position")); connect(action, &QAction::triggered, this, &SubtitlesDock::onSetStartRequested); Actions.add("subtitleSetStartAction", action, windowTitle()); action = new QAction(tr("Set Subtitle End"), this); action->setShortcut(QKeySequence(Qt::SHIFT | Qt::Key_T)); - action->setIcon(QIcon::fromTheme("keyframes-filter-out", - QIcon(":/icons/oxygen/32x32/actions/keyframes-filter-out.png"))); + action->setIcon( + QIcon::fromTheme("keyframes-filter-out", + QIcon(":/icons/oxygen/32x32/actions/keyframes-filter-out.png"))); action->setToolTip(tr("Set the selected subtitle to end at the cursor position")); connect(action, &QAction::triggered, this, &SubtitlesDock::onSetEndRequested); Actions.add("subtitleSetEndAction", action, windowTitle()); action = new QAction(tr("Move Subtitles"), this); action->setShortcut(QKeySequence(Qt::SHIFT | Qt::Key_Y)); - action->setIcon(QIcon::fromTheme("4-direction", - QIcon(":/icons/oxygen/32x32/actions/4-direction.png"))); + action->setIcon( + QIcon::fromTheme("4-direction", QIcon(":/icons/oxygen/32x32/actions/4-direction.png"))); action->setToolTip(tr("Move the selected subtitles to the cursor position")); connect(action, &QAction::triggered, this, &SubtitlesDock::onMoveRequested); Actions.add("subtitleMoveAction", action, windowTitle()); action = new QAction(tr("Burn In Subtitles on Output"), this); - action->setToolTip( - tr("Create or edit a Burn In Subtitles filter on the timeline output.")); - action->setIcon(QIcon::fromTheme("font", - QIcon(":/icons/oxygen/32x32/actions/font.png"))); + action->setToolTip(tr("Create or edit a Burn In Subtitles filter on the timeline output.")); + action->setIcon(QIcon::fromTheme("font", QIcon(":/icons/oxygen/32x32/actions/font.png"))); connect(action, &QAction::triggered, this, &SubtitlesDock::burnInOnTimeline); Actions.add("subtitleBurnInAction", action, windowTitle()); @@ -420,8 +419,7 @@ void SubtitlesDock::setupActions() Actions.add("subtitleGenerateTextAction", action, windowTitle()); action = new QAction(tr("Speech to Text..."), this); - action->setToolTip( - tr("Detect speech and transcribe to a new subtitle track.")); + action->setToolTip(tr("Detect speech and transcribe to a new subtitle track.")); action->setIcon(QIcon::fromTheme("speech-to-text", QIcon(":/icons/oxygen/32x32/actions/speech-to-text.png"))); connect(action, &QAction::triggered, this, &SubtitlesDock::speechToText); @@ -460,9 +458,13 @@ void SubtitlesDock::setModel(SubtitlesModel *model, SubtitlesSelectionModel *sel m_treeView->setColumnHidden(2, !Settings.subtitlesShowColumn("start")); m_treeView->setColumnHidden(3, !Settings.subtitlesShowColumn("end")); m_treeView->setColumnHidden(4, !Settings.subtitlesShowColumn("duration")); - connect(m_selectionModel, &QItemSelectionModel::currentChanged, this, + connect(m_selectionModel, + &QItemSelectionModel::currentChanged, + this, &SubtitlesDock::refreshWidgets); - connect(m_selectionModel, &SubtitlesSelectionModel::selectedTrackModelIndexChanged, m_treeView, + connect(m_selectionModel, + &SubtitlesSelectionModel::selectedTrackModelIndexChanged, + m_treeView, &QTreeView::setRootIndex); connect(m_treeView, &QTreeView::doubleClicked, this, &SubtitlesDock::onItemDoubleClicked); connect(m_model, &QAbstractItemModel::modelReset, this, &SubtitlesDock::onModelReset); @@ -470,18 +472,22 @@ void SubtitlesDock::setModel(SubtitlesModel *model, SubtitlesSelectionModel *sel connect(m_model, &QAbstractItemModel::dataChanged, this, &SubtitlesDock::refreshWidgets); connect(m_model, &QAbstractItemModel::rowsInserted, this, &SubtitlesDock::refreshWidgets); connect(m_model, &QAbstractItemModel::rowsMoved, this, &SubtitlesDock::refreshWidgets); - connect(m_model, &QAbstractItemModel::rowsRemoved, this, [&](const QModelIndex & parent, int first, - int last) { - if (parent.isValid()) { - refreshWidgets(); - } - }); + connect(m_model, + &QAbstractItemModel::rowsRemoved, + this, + [&](const QModelIndex &parent, int first, int last) { + if (parent.isValid()) { + refreshWidgets(); + } + }); refreshTracksCombo(); refreshWidgets(); } -void SubtitlesDock::importSrtFromFile(const QString &srtPath, const QString &trackName, - const QString &lang, bool includeNonspoken) +void SubtitlesDock::importSrtFromFile(const QString &srtPath, + const QString &trackName, + const QString &lang, + bool includeNonspoken) { QList items = readSrtFile(srtPath, 0, includeNonspoken); if (items.size() == 0) { @@ -529,13 +535,16 @@ void SubtitlesDock::removeSubtitleTrack() if (multitrack && multitrack->is_valid()) { for (int i = 0; i < multitrack->filter_count(); i++) { QScopedPointer filter(multitrack->filter(i)); - if (!filter || !filter->is_valid() || filter->get("mlt_service") != QStringLiteral("subtitle")) { + if (!filter || !filter->is_valid() + || filter->get("mlt_service") != QStringLiteral("subtitle")) { continue; } if (name == filter->get("feed")) { - QMessageBox::warning(this, tr("Remove Subtitle Track"), - tr("This track is in use by a subtitle filter.\n" - "Remove the subtitle filter before removing this track.")); + QMessageBox::warning( + this, + tr("Remove Subtitle Track"), + tr("This track is in use by a subtitle filter.\n" + "Remove the subtitle filter before removing this track.")); return; } } @@ -578,10 +587,13 @@ void SubtitlesDock::editSubtitleTrack() void SubtitlesDock::importSubtitles() { // Get the file name from the user. - QString subtitlePath = QFileDialog::getOpenFileName(&MAIN, tr("Import Subtitle File"), - Settings.openPath(), - tr("Subtitle Files (*.srt *.SRT *.vtt *.VTT *.ass *.ASS *.ssa *.SSA)"), - nullptr, Util::getFileDialogOptions()); + QString subtitlePath = QFileDialog::getOpenFileName( + &MAIN, + tr("Import Subtitle File"), + Settings.openPath(), + tr("Subtitle Files (*.srt *.SRT *.vtt *.VTT *.ass *.ASS *.ssa *.SSA)"), + nullptr, + Util::getFileDialogOptions()); if (subtitlePath.isEmpty()) { return; } @@ -602,14 +614,17 @@ void SubtitlesDock::importSubtitles() QProcess proc; QFileInfo ffmpegPath(qApp->applicationDirPath(), "ffmpeg"); QStringList args; - args << "-y" << "-hide_banner" << "-i" << subtitleFi.absoluteFilePath() << tmpFileName; + args << "-y" + << "-hide_banner" + << "-i" << subtitleFi.absoluteFilePath() << tmpFileName; LOG_INFO() << ffmpegPath.absoluteFilePath() << args; MAIN.showStatusMessage(QObject::tr("Importing subtitles...")); proc.setStandardOutputFile(QProcess::nullDevice()); proc.setReadChannel(QProcess::StandardError); proc.start(ffmpegPath.absoluteFilePath(), args, QIODevice::ReadOnly); QCoreApplication::processEvents(); - if (!proc.waitForFinished(8000) || proc.exitStatus() != QProcess::NormalExit || proc.exitCode()) { + if (!proc.waitForFinished(8000) || proc.exitStatus() != QProcess::NormalExit + || proc.exitCode()) { QString output = proc.readAll(); foreach (const QString &line, output.split(QRegularExpression("[\r\n]"), Qt::SkipEmptyParts)) LOG_INFO() << line; @@ -631,9 +646,12 @@ void SubtitlesDock::exportSubtitles() { auto track = m_model->getTrack(m_trackCombo->currentIndex()); QString suggestedPath = QStringLiteral("%1/%2.srt").arg(Settings.savePath()).arg(track.name); - QString srtPath = QFileDialog::getSaveFileName(&MAIN, tr("Export SRT File"), suggestedPath, + QString srtPath = QFileDialog::getSaveFileName(&MAIN, + tr("Export SRT File"), + suggestedPath, tr("SRT Files (*.srt *.SRT)"), - nullptr, Util::getFileDialogOptions()); + nullptr, + Util::getFileDialogOptions()); if (srtPath.isEmpty()) { return; } @@ -659,7 +677,8 @@ void SubtitlesDock::refreshTracksCombo() QList tracks = m_model->getTracks(); m_trackCombo->clear(); for (auto &track : tracks) { - m_trackCombo->addItem(QStringLiteral("%1 (%2)").arg(track.name).arg(track.lang), track.name); + m_trackCombo->addItem(QStringLiteral("%1 (%2)").arg(track.name).arg(track.lang), + track.name); } if (tracks.size() > 0) { m_trackCombo->setCurrentIndex(0); @@ -841,7 +860,7 @@ void SubtitlesDock::onItemDoubleClicked(const QModelIndex &index) if (index.parent().isValid()) { const Subtitles::SubtitleItem item = m_model->getItem(index.parent().row(), index.row()); int64_t position = msToPosition(item.start); - emit seekRequested((int)position); + emit seekRequested((int) position); } } @@ -883,7 +902,7 @@ void SubtitlesDock::updateTextWidgets() int trackIndex = currentIndex.parent().row(); int itemIndex = currentIndex.row(); if (trackIndex >= 0 && trackIndex < m_model->trackCount() && itemIndex >= 0 - && itemIndex < m_model->itemCount(trackIndex)) { + && itemIndex < m_model->itemCount(trackIndex)) { item = m_model->getItem(trackIndex, itemIndex); m_text->setPlainText(QString::fromStdString(item.text)); m_text->setReadOnly(false); @@ -953,7 +972,6 @@ void SubtitlesDock::updateTextWidgets() void SubtitlesDock::updateActionAvailablity() { - if (!m_model || !m_model->isValid()) { // Disable all actions m_addToTimelineLabel->setVisible(true); @@ -1140,7 +1158,8 @@ void SubtitlesDock::generateTextOnTimeline() presetFile.close(); if (isYaml) { // Load from YAML file. - Mlt::Properties *properties = Mlt::Properties::parse_yaml(presetFilePath.toUtf8().constData()); + Mlt::Properties *properties = Mlt::Properties::parse_yaml( + presetFilePath.toUtf8().constData()); filterProperties = *properties; delete properties; } else { @@ -1212,8 +1231,8 @@ void SubtitlesDock::speechToText() // Make a copy of the timeline producer QString xml = MLT.XML(MAIN.multitrack()); - std::unique_ptr tempProducer(new Mlt::Producer(MLT.profile(), "xml-string", - xml.toUtf8().constData())); + std::unique_ptr tempProducer( + new Mlt::Producer(MLT.profile(), "xml-string", xml.toUtf8().constData())); // Mute tracks as requested Mlt::Tractor tractor(*tempProducer.get()); @@ -1251,9 +1270,15 @@ void SubtitlesDock::speechToText() // Make the wav file from the timeline QStringList args; - args << "-consumer" << "avformat:" + tmpWav->fileName() << "video_off=1" << "ar=16000" << "ac=1"; + args << "-consumer" + << "avformat:" + tmpWav->fileName() << "video_off=1" + << "ar=16000" + << "ac=1"; QString jobName = tr("Extracting Audio"); - MeltJob *wavJob = new MeltJob(jobName, wavXml, args, MLT.profile().frame_rate_num(), + MeltJob *wavJob = new MeltJob(jobName, + wavXml, + args, + MLT.profile().frame_rate_num(), MLT.profile().frame_rate_den()); tmpWav->setParent(wavJob); JOBS.add(wavJob); @@ -1268,16 +1293,23 @@ void SubtitlesDock::speechToText() // Run speech transcription on the wav file jobName = tr("Speech to Text"); - WhisperJob *whisperJob = new WhisperJob(jobName, tmpWav->fileName(), tmpSrt->fileName(), - dialog.language(), dialog.translate(), dialog.maxLineLength()); + WhisperJob *whisperJob = new WhisperJob(jobName, + tmpWav->fileName(), + tmpSrt->fileName(), + dialog.language(), + dialog.translate(), + dialog.maxLineLength()); // Ensure the language code is 3 character (part 2) QString langCode = dialog.language(); QLocale::Language lang = QLocale::codeToLanguage(langCode); if (lang != QLocale::AnyLanguage) { langCode = QLocale::languageToCode(lang, QLocale::ISO639Part2); } - whisperJob->setPostJobAction(new ImportSrtPostJobAction(tmpSrt->fileName(), dialog.name(), langCode, - dialog.includeNonspoken(), this)); + whisperJob->setPostJobAction(new ImportSrtPostJobAction(tmpSrt->fileName(), + dialog.name(), + langCode, + dialog.includeNonspoken(), + this)); tmpSrt->setParent(whisperJob); JOBS.add(whisperJob); } diff --git a/src/docks/subtitlesdock.h b/src/docks/subtitlesdock.h index 585d636260..be7b743e72 100644 --- a/src/docks/subtitlesdock.h +++ b/src/docks/subtitlesdock.h @@ -18,8 +18,7 @@ #ifndef SUBTITLESDOCK_H #define SUBTITLESDOCK_H -#include "MltPlaylist.h" - +#include #include class SubtitlesModel; @@ -38,7 +37,9 @@ class SubtitlesDock : public QDockWidget explicit SubtitlesDock(QWidget *parent = 0); ~SubtitlesDock(); void setModel(SubtitlesModel *model, SubtitlesSelectionModel *selectionModel); - void importSrtFromFile(const QString &srtPath, const QString &trackName, const QString &lang, + void importSrtFromFile(const QString &srtPath, + const QString &trackName, + const QString &lang, bool includeNonspoken); signals: diff --git a/src/docks/timelinedock.cpp b/src/docks/timelinedock.cpp index 9ef54f233c..ac4e1cac84 100644 --- a/src/docks/timelinedock.cpp +++ b/src/docks/timelinedock.cpp @@ -17,27 +17,30 @@ #include "timelinedock.h" +#include "Logger.h" #include "actions.h" +#include "commands/timelinecommands.h" +#include "dialogs/alignaudiodialog.h" +#include "dialogs/editmarkerdialog.h" +#include "dialogs/longuitask.h" +#include "dialogs/resourcedialog.h" +#include "mainwindow.h" #include "models/audiolevelstask.h" #include "models/multitrackmodel.h" -#include "qmltypes/thumbnailprovider.h" -#include "mainwindow.h" -#include "commands/timelinecommands.h" +#include "proxymanager.h" #include "qmltypes/qmlapplication.h" #include "qmltypes/qmlutilities.h" #include "qmltypes/qmlview.h" -#include "shotcut_mlt_properties.h" +#include "qmltypes/thumbnailprovider.h" #include "settings.h" +#include "shotcut_mlt_properties.h" #include "util.h" -#include "proxymanager.h" -#include "dialogs/alignaudiodialog.h" -#include "dialogs/editmarkerdialog.h" -#include "dialogs/longuitask.h" -#include "dialogs/resourcedialog.h" #include "widgets/docktoolbar.h" #include #include +#include +#include #include #include #include @@ -45,9 +48,6 @@ #include #include #include -#include -#include -#include #include #include @@ -55,15 +55,15 @@ static const char *kFileUrlProtocol = "file://"; static const char *kFilesUrlDelimiter = ",file://"; static const int kRecordingTimerIntervalMs = 1000; -TimelineDock::TimelineDock(QWidget *parent) : - QDockWidget(parent), - m_quickView(QmlUtilities::sharedEngine(), this), - m_position(-1), - m_ignoreNextPositionChange(false), - m_trimDelta(0), - m_transitionDelta(0), - m_subtitlesModel(), - m_subtitlesSelectionModel(&m_subtitlesModel) +TimelineDock::TimelineDock(QWidget *parent) + : QDockWidget(parent) + , m_quickView(QmlUtilities::sharedEngine(), this) + , m_position(-1) + , m_ignoreNextPositionChange(false) + , m_trimDelta(0) + , m_transitionDelta(0) + , m_subtitlesModel() + , m_subtitlesSelectionModel(&m_subtitlesModel) { LOG_DEBUG() << "begin"; m_selection.selectedTrack = -1; @@ -169,8 +169,8 @@ TimelineDock::TimelineDock(QWidget *parent) : DockToolBar *toolbar = new DockToolBar(tr("Timeline Controls")); QToolButton *menuButton = new QToolButton(); - menuButton->setIcon(QIcon::fromTheme("show-menu", - QIcon(":/icons/oxygen/32x32/actions/show-menu.png"))); + menuButton->setIcon( + QIcon::fromTheme("show-menu", QIcon(":/icons/oxygen/32x32/actions/show-menu.png"))); menuButton->setToolTip(tr("Timeline Menu")); menuButton->setAutoRaise(true); menuButton->setPopupMode(QToolButton::QToolButton::InstantPopup); @@ -206,10 +206,11 @@ TimelineDock::TimelineDock(QWidget *parent) : zoomSlider->setValue(100); zoomSlider->setTracking(false); connect(zoomSlider, &QSlider::valueChanged, this, [&](int value) { - if (!isVisible() || !m_quickView.rootObject()) return; + if (!isVisible() || !m_quickView.rootObject()) + return; emit setZoom(value / 100.0); }); - connect(&m_model, &MultitrackModel::scaleFactorChanged, zoomSlider, [ = ]() { + connect(&m_model, &MultitrackModel::scaleFactorChanged, zoomSlider, [=]() { double value = round(pow(m_model.scaleFactor() - 0.01, 1.0 / 3.0) * 100.0); zoomSlider->blockSignals(true); zoomSlider->setValue(value); @@ -252,11 +253,16 @@ TimelineDock::TimelineDock(QWidget *parent) : }); connect(&m_quickView, &QQuickWidget::statusChanged, this, [&]() { - if ( m_quickView.status() == QQuickWidget::Ready) { + if (m_quickView.status() == QQuickWidget::Ready) { connect(m_quickView.rootObject(), SIGNAL(clipClicked()), this, SIGNAL(clipClicked())); - connect(m_quickView.rootObject(), SIGNAL(timelineRightClicked()), this, + connect(m_quickView.rootObject(), + SIGNAL(timelineRightClicked()), + this, SLOT(onTimelineRightClicked())); - connect(m_quickView.rootObject(), SIGNAL(clipRightClicked()), this, SLOT(onClipRightClicked())); + connect(m_quickView.rootObject(), + SIGNAL(clipRightClicked()), + this, + SLOT(onClipRightClicked())); } }); @@ -268,21 +274,30 @@ TimelineDock::TimelineDock(QWidget *parent) : connect(&m_model, &MultitrackModel::rowsInserted, this, &TimelineDock::onRowsInserted); connect(&m_model, &MultitrackModel::rowsRemoved, this, &TimelineDock::onRowsRemoved); connect(&m_model, &MultitrackModel::rowsMoved, this, &TimelineDock::onRowsMoved); - connect(&m_model, &MultitrackModel::noMoreEmptyTracks, this, &TimelineDock::onNoMoreEmptyTracks, + connect(&m_model, + &MultitrackModel::noMoreEmptyTracks, + this, + &TimelineDock::onNoMoreEmptyTracks, Qt::QueuedConnection); reloadTimelineModels(); }); connect(&m_model, &MultitrackModel::aboutToClose, this, [&]() { setSelection(); - disconnect(&m_model, &MultitrackModel::modified, this, &TimelineDock::clearSelectionIfInvalid); + disconnect(&m_model, + &MultitrackModel::modified, + this, + &TimelineDock::clearSelectionIfInvalid); disconnect(&m_model, &MultitrackModel::appended, this, &TimelineDock::selectClip); disconnect(&m_model, &MultitrackModel::inserted, this, &TimelineDock::selectClip); disconnect(&m_model, &MultitrackModel::overWritten, this, &TimelineDock::selectClip); disconnect(&m_model, &MultitrackModel::rowsInserted, this, &TimelineDock::onRowsInserted); disconnect(&m_model, &MultitrackModel::rowsRemoved, this, &TimelineDock::onRowsRemoved); disconnect(&m_model, &MultitrackModel::rowsMoved, this, &TimelineDock::onRowsMoved); - disconnect(&m_model, &MultitrackModel::noMoreEmptyTracks, this, &TimelineDock::onNoMoreEmptyTracks); + disconnect(&m_model, + &MultitrackModel::noMoreEmptyTracks, + this, + &TimelineDock::onNoMoreEmptyTracks); }); connect(&m_model, &MultitrackModel::closed, this, [&]() { @@ -292,11 +307,17 @@ TimelineDock::TimelineDock(QWidget *parent) : vboxLayout->addWidget(&m_quickView); - connect(this, SIGNAL(clipMoved(int, int, int, int, bool)), SLOT(onClipMoved(int, int, int, int, - bool)), Qt::QueuedConnection); - connect(this, SIGNAL(transitionAdded(int, int, int, bool)), SLOT(onTransitionAdded(int, int, int, - bool)), Qt::QueuedConnection); - connect(MLT.videoWidget(), SIGNAL(frameDisplayed(const SharedFrame &)), this, + connect(this, + SIGNAL(clipMoved(int, int, int, int, bool)), + SLOT(onClipMoved(int, int, int, int, bool)), + Qt::QueuedConnection); + connect(this, + SIGNAL(transitionAdded(int, int, int, bool)), + SLOT(onTransitionAdded(int, int, int, bool)), + Qt::QueuedConnection); + connect(MLT.videoWidget(), + SIGNAL(frameDisplayed(const SharedFrame &)), + this, SLOT(onShowFrame(const SharedFrame &))); connect(this, SIGNAL(topLevelChanged(bool)), this, SLOT(onTopLevelChanged(bool))); connect(this, SIGNAL(warnTrackLocked(int)), SLOT(onWarnTrackLocked())); @@ -321,9 +342,7 @@ TimelineDock::TimelineDock(QWidget *parent) : LOG_DEBUG() << "end"; } -TimelineDock::~TimelineDock() -{ -} +TimelineDock::~TimelineDock() {} void TimelineDock::setupActions() { @@ -360,7 +379,8 @@ void TimelineDock::setupActions() action = new QAction(tr("Remove Track"), this); action->setShortcut(QKeySequence(Qt::CTRL | Qt::ALT | Qt::Key_U)); connect(action, &QAction::triggered, this, [&]() { - if (!isMultitrackValid()) return; + if (!isMultitrackValid()) + return; show(); raise(); removeTrack(); @@ -370,7 +390,8 @@ void TimelineDock::setupActions() action = new QAction(tr("Move Track Up"), this); action->setShortcut(QKeySequence(Qt::SHIFT | Qt::ALT | Qt::Key_Up)); connect(action, &QAction::triggered, this, [&]() { - if (!isMultitrackValid()) return; + if (!isMultitrackValid()) + return; show(); raise(); moveTrackUp(); @@ -380,7 +401,8 @@ void TimelineDock::setupActions() action = new QAction(tr("Move Track Down"), this); action->setShortcut(QKeySequence(Qt::SHIFT | Qt::ALT | Qt::Key_Down)); connect(action, &QAction::triggered, this, [&]() { - if (!isMultitrackValid()) return; + if (!isMultitrackValid()) + return; show(); raise(); moveTrackDown(); @@ -395,7 +417,8 @@ void TimelineDock::setupActions() action->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_H)); #endif connect(action, &QAction::triggered, this, [&]() { - if (!isMultitrackValid()) return; + if (!isMultitrackValid()) + return; show(); raise(); toggleTrackHidden(currentTrack()); @@ -413,7 +436,8 @@ void TimelineDock::setupActions() action->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_L)); #endif connect(action, &QAction::triggered, this, [&]() { - if (!isMultitrackValid()) return; + if (!isMultitrackValid()) + return; show(); raise(); setTrackLock(currentTrack(), !isTrackLocked(currentTrack())); @@ -428,7 +452,8 @@ void TimelineDock::setupActions() action->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_M)); #endif connect(action, &QAction::triggered, this, [&]() { - if (!isMultitrackValid()) return; + if (!isMultitrackValid()) + return; show(); raise(); toggleTrackMute(currentTrack()); @@ -438,13 +463,16 @@ void TimelineDock::setupActions() action = new QAction(tr("Blend/Unblend Selected Track"), this); action->setShortcut(QKeySequence(Qt::CTRL | Qt::ALT | Qt::Key_B)); connect(action, &QAction::triggered, this, [&]() { - if (!isMultitrackValid()) return; + if (!isMultitrackValid()) + return; show(); raise(); int trackIndex = currentTrack(); if (trackIndex != model()->bottomVideoTrackIndex()) { - bool isComposite = model()->data(model()->index(trackIndex), - MultitrackModel::IsCompositeRole).toBool(); + bool isComposite = model() + ->data(model()->index(trackIndex), + MultitrackModel::IsCompositeRole) + .toBool(); setTrackComposite(trackIndex, !isComposite); } }); @@ -453,7 +481,8 @@ void TimelineDock::setupActions() action = new QAction(tr("Make Tracks Shorter"), this); action->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_Minus)); connect(action, &QAction::triggered, this, [&]() { - if (!isMultitrackValid() || !isVisible()) return; + if (!isMultitrackValid() || !isVisible()) + return; m_model.setTrackHeight(std::max(10, m_model.trackHeight() - 20)); }); Actions.add("timelineTracksShorterAction", action); @@ -461,7 +490,8 @@ void TimelineDock::setupActions() action = new QAction(tr("Make Tracks Taller"), this); action->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_Plus)); connect(action, &QAction::triggered, this, [&]() { - if (!isMultitrackValid() || !isVisible()) return; + if (!isMultitrackValid() || !isVisible()) + return; m_model.setTrackHeight(m_model.trackHeight() + 20); }); Actions.add("timelineTracksTallerAction", action); @@ -469,7 +499,8 @@ void TimelineDock::setupActions() action = new QAction(tr("Reset Track Height"), this); action->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_Equal)); connect(action, &QAction::triggered, this, [&]() { - if (!isMultitrackValid() || !isVisible()) return; + if (!isMultitrackValid() || !isVisible()) + return; m_model.setTrackHeight(50); }); Actions.add("timelineResetTrackHeightAction", action); @@ -477,7 +508,8 @@ void TimelineDock::setupActions() action = new QAction(tr("Select All"), this); action->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_A)); connect(action, &QAction::triggered, this, [&]() { - if (!isMultitrackValid()) return; + if (!isMultitrackValid()) + return; show(); raise(); selectAll(); @@ -487,7 +519,8 @@ void TimelineDock::setupActions() action = new QAction(tr("Select All On Current Track"), this); action->setShortcut(QKeySequence(Qt::CTRL | Qt::ALT | Qt::Key_A)); connect(action, &QAction::triggered, this, [&]() { - if (!isMultitrackValid()) return; + if (!isMultitrackValid()) + return; show(); raise(); selectAllOnCurrentTrack(); @@ -497,7 +530,8 @@ void TimelineDock::setupActions() action = new QAction(tr("Select None"), this); action->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_D)); connect(action, &QAction::triggered, this, [&]() { - if (!isMultitrackValid()) return; + if (!isMultitrackValid()) + return; show(); raise(); setSelection(); @@ -508,7 +542,8 @@ void TimelineDock::setupActions() action = new QAction(tr("Select Next Clip"), this); action->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_Right)); connect(action, &QAction::triggered, this, [&]() { - if (!isMultitrackValid() || !isVisible()) return; + if (!isMultitrackValid() || !isVisible()) + return; if (selection().isEmpty()) { selectClipUnderPlayhead(); } else if (selection().size() == 1) { @@ -522,7 +557,8 @@ void TimelineDock::setupActions() action = new QAction(tr("Select Previous Clip"), this); action->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_Left)); connect(action, &QAction::triggered, this, [&]() { - if (!isMultitrackValid() || !isVisible()) return; + if (!isMultitrackValid() || !isVisible()) + return; if (selection().isEmpty()) { selectClipUnderPlayhead(); } else if (selection().size() == 1) { @@ -536,14 +572,14 @@ void TimelineDock::setupActions() action = new QAction(tr("Select Clip Above"), this); action->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_Up)); connect(action, &QAction::triggered, this, [&]() { - if (!isMultitrackValid() || !isVisible()) return; + if (!isMultitrackValid() || !isVisible()) + return; if (selection().isEmpty()) selectClipUnderPlayhead(); int newClipIndex = -1; int trackIndex = currentTrack() - 1; if (!selection().isEmpty() && trackIndex > -1 && !selection().isEmpty()) { - int navigationPosition = centerOfClip(selection().first().y(), - selection().first().x()); + int navigationPosition = centerOfClip(selection().first().y(), selection().first().x()); newClipIndex = clipIndexAtPosition(trackIndex, navigationPosition); } incrementCurrentTrack(-1); @@ -557,14 +593,14 @@ void TimelineDock::setupActions() action = new QAction(tr("Select Clip Below"), this); action->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_Down)); connect(action, &QAction::triggered, this, [&]() { - if (!isMultitrackValid() || !isVisible()) return; + if (!isMultitrackValid() || !isVisible()) + return; if (selection().isEmpty()) selectClipUnderPlayhead(); int newClipIndex = -1; int trackIndex = currentTrack() + 1; if (trackIndex < model()->trackList().count() && !selection().isEmpty()) { - int navigationPosition = centerOfClip(selection().first().y(), - selection().first().x()); + int navigationPosition = centerOfClip(selection().first().y(), selection().first().x()); newClipIndex = clipIndexAtPosition(trackIndex, navigationPosition); } incrementCurrentTrack(1); @@ -578,7 +614,8 @@ void TimelineDock::setupActions() action = new QAction(tr("Set Current Track Above"), this); action->setShortcut(QKeySequence(Qt::CTRL | Qt::ALT | Qt::Key_Up)); connect(action, &QAction::triggered, this, [&]() { - if (!isMultitrackValid() || !isVisible()) return; + if (!isMultitrackValid() || !isVisible()) + return; incrementCurrentTrack(-1); }); Actions.add("timelineCurrentTrackAboveAction", action); @@ -586,7 +623,8 @@ void TimelineDock::setupActions() action = new QAction(tr("Set Current Track Below"), this); action->setShortcut(QKeySequence(Qt::CTRL | Qt::ALT | Qt::Key_Down)); connect(action, &QAction::triggered, this, [&]() { - if (!isMultitrackValid() || !isVisible()) return; + if (!isMultitrackValid() || !isVisible()) + return; incrementCurrentTrack(1); }); Actions.add("timelineCurrentTrackBelowAction", action); @@ -600,15 +638,15 @@ void TimelineDock::setupActions() #endif action->setShortcuts(clipUnderPlayheadShortcuts); connect(action, &QAction::triggered, this, [&]() { - if (!isMultitrackValid() || !isVisible()) return; + if (!isMultitrackValid() || !isVisible()) + return; selectClipUnderPlayhead(); }); Actions.add("timelineSelectClipUnderPlayheadAction", action); action = new QAction(tr("Cu&t"), this); action->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_X)); - icon = QIcon::fromTheme("edit-cut", - QIcon(":/icons/oxygen/32x32/actions/edit-cut.png")); + icon = QIcon::fromTheme("edit-cut", QIcon(":/icons/oxygen/32x32/actions/edit-cut.png")); action->setIcon(icon); action->setEnabled(false); connect(action, &QAction::triggered, this, [&]() { @@ -616,7 +654,7 @@ void TimelineDock::setupActions() raise(); removeSelection(true); }); - connect(this, &TimelineDock::selectionChanged, action, [ = ]() { + connect(this, &TimelineDock::selectionChanged, action, [=]() { bool enabled = m_selection.selectedClips.length() > 0; if (enabled && !selection().isEmpty()) { int trackIndex = selection().first().y(); @@ -632,8 +670,7 @@ void TimelineDock::setupActions() copyShortcuts << QKeySequence(Qt::CTRL | Qt::Key_C); copyShortcuts << QKeySequence(Qt::Key_C); action->setShortcuts(copyShortcuts); - icon = QIcon::fromTheme("edit-copy", - QIcon(":/icons/oxygen/32x32/actions/edit-copy.png")); + icon = QIcon::fromTheme("edit-copy", QIcon(":/icons/oxygen/32x32/actions/edit-copy.png")); action->setIcon(icon); action->setEnabled(false); connect(action, &QAction::triggered, this, [&]() { @@ -646,7 +683,7 @@ void TimelineDock::setupActions() copy(selected.y(), selected.x()); } }); - connect(this, &TimelineDock::selectionChanged, action, [ = ]() { + connect(this, &TimelineDock::selectionChanged, action, [=]() { bool enabled = m_selection.selectedClips.length() > 0; if (enabled && !selection().isEmpty()) { int trackIndex = selection().first().y(); @@ -662,8 +699,7 @@ void TimelineDock::setupActions() pasteShortcuts << QKeySequence(Qt::CTRL | Qt::Key_V); pasteShortcuts << QKeySequence(Qt::Key_V); action->setShortcuts(pasteShortcuts); - icon = QIcon::fromTheme("edit-paste", - QIcon(":/icons/oxygen/32x32/actions/edit-paste.png")); + icon = QIcon::fromTheme("edit-paste", QIcon(":/icons/oxygen/32x32/actions/edit-paste.png")); action->setIcon(icon); connect(action, &QAction::triggered, this, [&]() { show(); @@ -683,17 +719,22 @@ void TimelineDock::setupActions() bool valid = clipIndex > 0 && !isTransition(trackIndex, clipIndex) && !isBlank(trackIndex, clipIndex); if (valid && !Settings.timelineRipple()) { - valid = (clipIndex == clipCount(trackIndex) - 1) || isBlank(trackIndex, clipIndex + 1); + valid = (clipIndex == clipCount(trackIndex) - 1) + || isBlank(trackIndex, clipIndex + 1); } if (!valid) { emit showStatusMessage(tr("Nudge Forward is not available")); return; } auto clipInfo = m_model.getClipInfo(trackIndex, clipIndex); - moveClip(trackIndex, trackIndex, clipIndex, clipInfo->start + 1, Settings.timelineRipple()); + moveClip(trackIndex, + trackIndex, + clipIndex, + clipInfo->start + 1, + Settings.timelineRipple()); } }); - connect(this, &TimelineDock::selectionChanged, action, [ = ]() { + connect(this, &TimelineDock::selectionChanged, action, [=]() { auto selectedClips = selection(); bool enabled = selectedClips.size() == 1; if (enabled) { @@ -712,16 +753,20 @@ void TimelineDock::setupActions() if (selectedClips.size() == 1) { int trackIndex = selectedClips.first().y(); int clipIndex = selectedClips.first().x(); - if (clipIndex <= 0 || isTransition(trackIndex, clipIndex) || isBlank(trackIndex, clipIndex) - || !isBlank(trackIndex, clipIndex - 1)) { + if (clipIndex <= 0 || isTransition(trackIndex, clipIndex) + || isBlank(trackIndex, clipIndex) || !isBlank(trackIndex, clipIndex - 1)) { emit showStatusMessage(tr("Nudge Backward is not available")); return; } auto clipInfo = m_model.getClipInfo(trackIndex, clipIndex); - moveClip(trackIndex, trackIndex, clipIndex, clipInfo->start - 1, Settings.timelineRipple()); + moveClip(trackIndex, + trackIndex, + clipIndex, + clipInfo->start - 1, + Settings.timelineRipple()); } }); - connect(this, &TimelineDock::selectionChanged, action, [ = ]() { + connect(this, &TimelineDock::selectionChanged, action, [=]() { auto selectedClips = selection(); bool enabled = selectedClips.size() == 1; if (enabled) { @@ -734,8 +779,7 @@ void TimelineDock::setupActions() action = new QAction(tr("Append"), this); action->setShortcut(QKeySequence(Qt::Key_A)); - icon = QIcon::fromTheme("list-add", - QIcon(":/icons/oxygen/32x32/actions/list-add.png")); + icon = QIcon::fromTheme("list-add", QIcon(":/icons/oxygen/32x32/actions/list-add.png")); action->setIcon(icon); connect(action, &QAction::triggered, this, [&]() { show(); @@ -750,11 +794,11 @@ void TimelineDock::setupActions() deleteShortcuts << QKeySequence(Qt::SHIFT | Qt::Key_Backspace); deleteShortcuts << QKeySequence(Qt::SHIFT | Qt::Key_Delete); action->setShortcuts(deleteShortcuts); - icon = QIcon::fromTheme("list-remove", - QIcon(":/icons/oxygen/32x32/actions/list-remove.png")); + icon = QIcon::fromTheme("list-remove", QIcon(":/icons/oxygen/32x32/actions/list-remove.png")); action->setIcon(icon); connect(action, &QAction::triggered, this, [&]() { - if (!isMultitrackValid()) return; + if (!isMultitrackValid()) + return; show(); raise(); removeSelection(); @@ -768,11 +812,11 @@ void TimelineDock::setupActions() liftShortcuts << QKeySequence(Qt::Key_Backspace); liftShortcuts << QKeySequence(Qt::Key_Delete); action->setShortcuts(liftShortcuts); - icon = QIcon::fromTheme("lift", - QIcon(":/icons/oxygen/32x32/actions/lift.png")); + icon = QIcon::fromTheme("lift", QIcon(":/icons/oxygen/32x32/actions/lift.png")); action->setIcon(icon); connect(action, &QAction::triggered, this, [&]() { - if (!isMultitrackValid()) return; + if (!isMultitrackValid()) + return; show(); raise(); liftSelection(); @@ -781,11 +825,11 @@ void TimelineDock::setupActions() action = new QAction(tr("Overwrite"), this); action->setShortcut(QKeySequence(Qt::Key_B)); - icon = QIcon::fromTheme("overwrite", - QIcon(":/icons/oxygen/32x32/actions/overwrite.png")); + icon = QIcon::fromTheme("overwrite", QIcon(":/icons/oxygen/32x32/actions/overwrite.png")); action->setIcon(icon); connect(action, &QAction::triggered, this, [&]() { - if (!isMultitrackValid()) return; + if (!isMultitrackValid()) + return; show(); raise(); overwrite(currentTrack()); @@ -794,11 +838,11 @@ void TimelineDock::setupActions() action = new QAction(tr("Split At Playhead"), this); action->setShortcut(QKeySequence(Qt::Key_S)); - icon = QIcon::fromTheme("slice", - QIcon(":/icons/oxygen/32x32/actions/slice.png")); + icon = QIcon::fromTheme("slice", QIcon(":/icons/oxygen/32x32/actions/slice.png")); action->setIcon(icon); connect(action, &QAction::triggered, this, [&]() { - if (!isMultitrackValid()) return; + if (!isMultitrackValid()) + return; show(); raise(); int clipIndex = -1; @@ -811,10 +855,11 @@ void TimelineDock::setupActions() for (auto c : selected) { clipIndex = c.x(); trackIndex = c.y(); - if (clipIndexAtPlayhead(trackIndex) == clipIndex && !isBlank(trackIndex, clipIndex) - && !isTransition(trackIndex, clipIndex)) { + if (clipIndexAtPlayhead(trackIndex) == clipIndex && !isBlank(trackIndex, clipIndex) + && !isTransition(trackIndex, clipIndex)) { auto info = m_model.getClipInfo(trackIndex, clipIndex); - if (info && m_position > info->start && m_position < info->start + info->frame_count) { + if (info && m_position > info->start + && m_position < info->start + info->frame_count) { tracks.push_back(trackIndex); clips.push_back(clipIndex); } @@ -828,7 +873,7 @@ void TimelineDock::setupActions() chooseClipAtPosition(m_position, trackIndex, clipIndex); if (trackIndex < 0 || clipIndex < 0) { return; - } else if (isBlank(trackIndex, clipIndex)) { + } else if (isBlank(trackIndex, clipIndex)) { return; } else if (isTransition(trackIndex, clipIndex)) { emit showStatusMessage(tr("You cannot split a transition.")); @@ -851,7 +896,8 @@ void TimelineDock::setupActions() action = new QAction(tr("Split All Tracks At Playhead"), this); action->setShortcut(QKeySequence(Qt::SHIFT | Qt::Key_S)); connect(action, &QAction::triggered, this, [&]() { - if (!isMultitrackValid()) return; + if (!isMultitrackValid()) + return; show(); raise(); std::vector tracks; @@ -881,7 +927,8 @@ void TimelineDock::setupActions() action = new QAction(tr("Replace"), this); action->setShortcut(QKeySequence(Qt::Key_R)); connect(action, &QAction::triggered, this, [&]() { - if (!isMultitrackValid()) return; + if (!isMultitrackValid()) + return; show(); raise(); if (MLT.isClip() || selection().isEmpty()) { @@ -891,18 +938,18 @@ void TimelineDock::setupActions() replace(selected.y(), selected.x()); } }); - connect(this, &TimelineDock::selectionChanged, action, [ = ]() { + connect(this, &TimelineDock::selectionChanged, action, [=]() { action->setEnabled(m_selection.selectedClips.length() > 0); }); Actions.add("timelineReplaceAction", action); action = new QAction(tr("Create/Edit Marker"), this); action->setShortcut(QKeySequence(Qt::Key_M)); - icon = QIcon::fromTheme("marker", - QIcon(":/icons/oxygen/32x32/actions/marker.png")); + icon = QIcon::fromTheme("marker", QIcon(":/icons/oxygen/32x32/actions/marker.png")); action->setIcon(icon); connect(action, &QAction::triggered, this, [&]() { - if (!isMultitrackValid()) return; + if (!isMultitrackValid()) + return; show(); raise(); createOrEditMarker(); @@ -915,7 +962,8 @@ void TimelineDock::setupActions() QIcon(":/icons/oxygen/32x32/actions/format-indent-less.png")); action->setIcon(icon); connect(action, &QAction::triggered, this, [&]() { - if (!isMultitrackValid()) return; + if (!isMultitrackValid()) + return; show(); raise(); seekPrevMarker(); @@ -928,7 +976,8 @@ void TimelineDock::setupActions() QIcon(":/icons/oxygen/32x32/actions/format-indent-more.png")); action->setIcon(icon); connect(action, &QAction::triggered, this, [&]() { - if (!isMultitrackValid()) return; + if (!isMultitrackValid()) + return; show(); raise(); seekNextMarker(); @@ -938,7 +987,8 @@ void TimelineDock::setupActions() action = new QAction(tr("Delete Marker"), this); action->setShortcut(QKeySequence(Qt::CTRL | Qt::SHIFT | Qt::Key_M)); connect(action, &QAction::triggered, this, [&]() { - if (!isMultitrackValid()) return; + if (!isMultitrackValid()) + return; show(); raise(); deleteMarker(); @@ -964,7 +1014,8 @@ void TimelineDock::setupActions() action = new QAction(tr("Create Marker Around Selected Clip"), this); action->setShortcut(QKeySequence(Qt::ALT | Qt::Key_M)); connect(action, &QAction::triggered, this, [&]() { - if (!isMultitrackValid()) return; + if (!isMultitrackValid()) + return; show(); raise(); createOrEditSelectionMarker(); @@ -977,7 +1028,7 @@ void TimelineDock::setupActions() connect(action, &QAction::triggered, this, [&](bool checked) { Settings.setTimelineRectangleSelect(checked); }); - connect(&Settings, &ShotcutSettings::timelineRectangleSelectChanged, action, [ = ]() { + connect(&Settings, &ShotcutSettings::timelineRectangleSelectChanged, action, [=]() { action->setChecked(Settings.timelineRectangleSelect()); }); Actions.add("timelineRectangleSelectAction", action); @@ -988,66 +1039,62 @@ void TimelineDock::setupActions() connect(action, &QAction::triggered, this, [&](bool checked) { Settings.setTimelineAutoAddTracks(checked); }); - connect(&Settings, &ShotcutSettings::timelineAutoAddTracksChanged, action, [ = ]() { + connect(&Settings, &ShotcutSettings::timelineAutoAddTracksChanged, action, [=]() { action->setChecked(Settings.timelineAutoAddTracks()); }); Actions.add("timelineAutoAddTracksAction", action); action = new QAction(tr("Snap"), this); action->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_P)); - icon = QIcon::fromTheme("snap", - QIcon(":/icons/oxygen/32x32/actions/snap.png")); + icon = QIcon::fromTheme("snap", QIcon(":/icons/oxygen/32x32/actions/snap.png")); action->setIcon(icon); action->setCheckable(true); action->setChecked(Settings.timelineSnap()); connect(action, &QAction::triggered, this, [&](bool checked) { Settings.setTimelineSnap(checked); }); - connect(&Settings, &ShotcutSettings::timelineSnapChanged, action, [ = ]() { + connect(&Settings, &ShotcutSettings::timelineSnapChanged, action, [=]() { action->setChecked(Settings.timelineSnap()); }); Actions.add("timelineSnapAction", action); action = new QAction(tr("Scrub While Dragging"), this); - icon = QIcon::fromTheme("scrub_drag", - QIcon(":/icons/oxygen/32x32/actions/scrub_drag.png")); + icon = QIcon::fromTheme("scrub_drag", QIcon(":/icons/oxygen/32x32/actions/scrub_drag.png")); action->setIcon(icon); action->setCheckable(true); action->setChecked(Settings.timelineDragScrub()); connect(action, &QAction::triggered, this, [&](bool checked) { Settings.setTimelineDragScrub(checked); }); - connect(&Settings, &ShotcutSettings::timelineDragScrubChanged, action, [ = ]() { + connect(&Settings, &ShotcutSettings::timelineDragScrubChanged, action, [=]() { action->setChecked(Settings.timelineDragScrub()); }); Actions.add("timelineScrubDragAction", action); action = new QAction(tr("Ripple"), this); action->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_R)); - icon = QIcon::fromTheme("target", - QIcon(":/icons/oxygen/32x32/actions/target.png")); + icon = QIcon::fromTheme("target", QIcon(":/icons/oxygen/32x32/actions/target.png")); action->setIcon(icon); action->setCheckable(true); action->setChecked(Settings.timelineRipple()); connect(action, &QAction::triggered, this, [&](bool checked) { Settings.setTimelineRipple(checked); }); - connect(&Settings, &ShotcutSettings::timelineRippleChanged, action, [ = ]() { + connect(&Settings, &ShotcutSettings::timelineRippleChanged, action, [=]() { action->setChecked(Settings.timelineRipple()); }); Actions.add("timelineRippleAction", action); action = new QAction(tr("Ripple All Tracks"), this); action->setShortcut(QKeySequence(Qt::CTRL | Qt::ALT | Qt::Key_R)); - icon = QIcon::fromTheme("ripple-all", - QIcon(":/icons/oxygen/32x32/actions/ripple-all.png")); + icon = QIcon::fromTheme("ripple-all", QIcon(":/icons/oxygen/32x32/actions/ripple-all.png")); action->setIcon(icon); action->setCheckable(true); action->setChecked(Settings.timelineRippleAllTracks()); connect(action, &QAction::triggered, this, [&](bool checked) { Settings.setTimelineRippleAllTracks(checked); }); - connect(&Settings, &ShotcutSettings::timelineRippleAllTracksChanged, action, [ = ]() { + connect(&Settings, &ShotcutSettings::timelineRippleAllTracksChanged, action, [=]() { action->setChecked(Settings.timelineRippleAllTracks()); }); Actions.add("timelineRippleAllTracksAction", action); @@ -1062,7 +1109,7 @@ void TimelineDock::setupActions() connect(action, &QAction::triggered, this, [&](bool checked) { Settings.setTimelineRippleMarkers(checked); }); - connect(&Settings, &ShotcutSettings::timelineRippleMarkersChanged, action, [ = ]() { + connect(&Settings, &ShotcutSettings::timelineRippleMarkersChanged, action, [=]() { action->setChecked(Settings.timelineRippleMarkers()); }); Actions.add("timelineRippleMarkersAction", action); @@ -1089,10 +1136,11 @@ void TimelineDock::setupActions() action->setChecked(Settings.timelineShowWaveforms()); connect(action, &QAction::triggered, this, [&](bool checked) { Settings.setTimelineShowWaveforms(checked); - if (!isVisible() || !m_quickView.rootObject()) return; + if (!isVisible() || !m_quickView.rootObject()) + return; emit refreshWaveforms(); }); - connect(&Settings, &ShotcutSettings::timelineShowWaveformsChanged, action, [ = ]() { + connect(&Settings, &ShotcutSettings::timelineShowWaveformsChanged, action, [=]() { action->setChecked(Settings.timelineShowWaveforms()); }); Actions.add("timelineShowWaveformsAction", action); @@ -1102,12 +1150,13 @@ void TimelineDock::setupActions() action->setChecked(Settings.timelineFramebufferWaveform()); connect(action, &QAction::triggered, this, [&](bool checked) { Settings.setTimelineFramebufferWaveform(checked); - if (!isVisible() || !m_quickView.rootObject()) return; + if (!isVisible() || !m_quickView.rootObject()) + return; if (Settings.timelineFramebufferWaveform()) { m_model.reload(); } }); - connect(&Settings, &ShotcutSettings::timelineFramebufferWaveformChanged, action, [ = ]() { + connect(&Settings, &ShotcutSettings::timelineFramebufferWaveformChanged, action, [=]() { action->setChecked(Settings.timelineFramebufferWaveform()); }); Actions.add("timelinePerformanceWaveformsAction", action); @@ -1118,18 +1167,19 @@ void TimelineDock::setupActions() connect(action, &QAction::triggered, this, [&](bool checked) { Settings.setTimelineShowThumbnails(checked); }); - connect(&Settings, &ShotcutSettings::timelineShowThumbnailsChanged, action, [ = ]() { + connect(&Settings, &ShotcutSettings::timelineShowThumbnailsChanged, action, [=]() { action->setChecked(Settings.timelineShowThumbnails()); }); Actions.add("timelineShowThumbnailsAction", action); action = new QAction(tr("No"), this); action->setCheckable(true); - action->setChecked(ShotcutSettings::TimelineScrolling::NoScrolling == Settings.timelineScrolling()); + action->setChecked(ShotcutSettings::TimelineScrolling::NoScrolling + == Settings.timelineScrolling()); connect(action, &QAction::triggered, this, [&](bool checked) { Settings.setTimelineScrolling(ShotcutSettings::TimelineScrolling::NoScrolling); }); - connect(&Settings, &ShotcutSettings::timelineScrollingChanged, action, [ = ]() { + connect(&Settings, &ShotcutSettings::timelineScrollingChanged, action, [=]() { if (ShotcutSettings::TimelineScrolling::NoScrolling == Settings.timelineScrolling()) action->setChecked(true); }); @@ -1137,12 +1187,12 @@ void TimelineDock::setupActions() action = new QAction(tr("Page"), this); action->setCheckable(true); - action->setChecked(ShotcutSettings::TimelineScrolling::PageScrolling == - Settings.timelineScrolling()); + action->setChecked(ShotcutSettings::TimelineScrolling::PageScrolling + == Settings.timelineScrolling()); connect(action, &QAction::triggered, this, [&](bool checked) { Settings.setTimelineScrolling(ShotcutSettings::TimelineScrolling::PageScrolling); }); - connect(&Settings, &ShotcutSettings::timelineScrollingChanged, action, [ = ]() { + connect(&Settings, &ShotcutSettings::timelineScrollingChanged, action, [=]() { if (ShotcutSettings::TimelineScrolling::PageScrolling == Settings.timelineScrolling()) action->setChecked(true); }); @@ -1150,12 +1200,12 @@ void TimelineDock::setupActions() action = new QAction(tr("Smooth"), this); action->setCheckable(true); - action->setChecked(ShotcutSettings::TimelineScrolling::SmoothScrolling == - Settings.timelineScrolling()); + action->setChecked(ShotcutSettings::TimelineScrolling::SmoothScrolling + == Settings.timelineScrolling()); connect(action, &QAction::triggered, this, [&](bool checked) { Settings.setTimelineScrolling(ShotcutSettings::TimelineScrolling::SmoothScrolling); }); - connect(&Settings, &ShotcutSettings::timelineScrollingChanged, action, [ = ]() { + connect(&Settings, &ShotcutSettings::timelineScrollingChanged, action, [=]() { if (ShotcutSettings::TimelineScrolling::SmoothScrolling == Settings.timelineScrolling()) action->setChecked(true); }); @@ -1164,12 +1214,12 @@ void TimelineDock::setupActions() action = new QAction(tr("Center the Playhead"), this); action->setShortcut(QKeySequence(Qt::CTRL | Qt::SHIFT | Qt::Key_P)); action->setCheckable(true); - action->setChecked(ShotcutSettings::TimelineScrolling::CenterPlayhead == - Settings.timelineScrolling()); + action->setChecked(ShotcutSettings::TimelineScrolling::CenterPlayhead + == Settings.timelineScrolling()); connect(action, &QAction::triggered, this, [&](bool checked) { Settings.setTimelineScrolling(ShotcutSettings::TimelineScrolling::CenterPlayhead); }); - connect(&Settings, &ShotcutSettings::timelineScrollingChanged, action, [ = ]() { + connect(&Settings, &ShotcutSettings::timelineScrollingChanged, action, [=]() { if (ShotcutSettings::TimelineScrolling::CenterPlayhead == Settings.timelineScrolling()) action->setChecked(true); }); @@ -1182,29 +1232,29 @@ void TimelineDock::setupActions() connect(action, &QAction::triggered, this, [&](bool checked) { Settings.setTimelineScrollZoom(checked); }); - connect(&Settings, &ShotcutSettings::timelineScrollZoomChanged, action, [ = ]() { + connect(&Settings, &ShotcutSettings::timelineScrollZoomChanged, action, [=]() { action->setChecked(Settings.timelineScrollZoom()); }); Actions.add("timelineScrollZoomAction", action); action = new QAction(tr("Zoom Timeline Out"), this); action->setShortcut(QKeySequence(Qt::Key_Minus)); - icon = QIcon::fromTheme("zoom-out", - QIcon(":/icons/oxygen/32x32/actions/zoom-out.png")); + icon = QIcon::fromTheme("zoom-out", QIcon(":/icons/oxygen/32x32/actions/zoom-out.png")); action->setIcon(icon); connect(action, &QAction::triggered, this, [&]() { - if (!isVisible() || !m_quickView.rootObject()) return; + if (!isVisible() || !m_quickView.rootObject()) + return; emit zoomOut(); }); Actions.add("timelineZoomOutAction", action); action = new QAction(tr("Zoom Timeline In"), this); action->setShortcut(QKeySequence(Qt::Key_Plus)); - icon = QIcon::fromTheme("zoom-in", - QIcon(":/icons/oxygen/32x32/actions/zoom-in.png")); + icon = QIcon::fromTheme("zoom-in", QIcon(":/icons/oxygen/32x32/actions/zoom-in.png")); action->setIcon(icon); connect(action, &QAction::triggered, this, [&]() { - if (!isVisible() || !m_quickView.rootObject()) return; + if (!isVisible() || !m_quickView.rootObject()) + return; emit zoomIn(); }); Actions.add("timelineZoomInAction", action); @@ -1215,7 +1265,8 @@ void TimelineDock::setupActions() QIcon(":/icons/oxygen/32x32/actions/zoom-fit-best.png")); action->setIcon(icon); connect(action, &QAction::triggered, this, [&]() { - if (!isVisible()) return; + if (!isVisible()) + return; emit zoomToFit(); }); Actions.add("timelineZoomFitAction", action); @@ -1232,16 +1283,14 @@ void TimelineDock::setupActions() else recordAudio(); }); - connect(this, &TimelineDock::isRecordingChanged, action, [ = ]() { + connect(this, &TimelineDock::isRecordingChanged, action, [=]() { action->setChecked(isRecording()); }); Actions.add("timelineRecordAudioAction", action); action = new QAction(tr("Properties"), this); - connect(action, &QAction::triggered, this, [&](bool checked) { - openProperties(); - }); - connect(this, &TimelineDock::selectionChanged, action, [ = ]() { + connect(action, &QAction::triggered, this, [&](bool checked) { openProperties(); }); + connect(this, &TimelineDock::selectionChanged, action, [=]() { action->setEnabled(!blankIsSelected()); }); Actions.add("timelinePropertiesAction", action); @@ -1253,7 +1302,7 @@ void TimelineDock::setupActions() mergeClipWithNext(selection().first().y(), selection().first().x(), false); } }); - connect(this, &TimelineDock::selectionChanged, action, [ = ]() { + connect(this, &TimelineDock::selectionChanged, action, [=]() { bool enabled = false; if (m_selection.selectedClips.length() == 1 && !selection().isEmpty()) { enabled = mergeClipWithNext(selection().first().y(), selection().first().x(), true); @@ -1269,7 +1318,7 @@ void TimelineDock::setupActions() detachAudio(selection().first().y(), selection().first().x()); } }); - connect(this, &TimelineDock::selectionChanged, action, [ = ]() { + connect(this, &TimelineDock::selectionChanged, action, [=]() { bool enabled = false; if (m_selection.selectedClips.length() == 1 && !selection().isEmpty()) { int trackIndex = selection().first().y(); @@ -1281,7 +1330,8 @@ void TimelineDock::setupActions() && !modelIndex.data(MultitrackModel::IsTransitionRole).toBool() && !modelIndex.data(MultitrackModel::IsAudioRole).toBool() && (modelIndex.data(MultitrackModel::AudioIndexRole).toInt() > -1 - || modelIndex.data(MultitrackModel::AudioIndexRole).toString() == "all"); + || modelIndex.data(MultitrackModel::AudioIndexRole).toString() + == "all"); } } } @@ -1296,7 +1346,7 @@ void TimelineDock::setupActions() alignSelectedClips(); } }); - connect(this, &TimelineDock::selectionChanged, action, [ = ]() { + connect(this, &TimelineDock::selectionChanged, action, [=]() { bool enabled = false; foreach (auto point, selection()) { // At least one selected item must be a valid clip @@ -1316,7 +1366,7 @@ void TimelineDock::setupActions() applyCopiedFiltersToSelectdClips(); } }); - connect(this, &TimelineDock::selectionChanged, action, [ = ]() { + connect(this, &TimelineDock::selectionChanged, action, [=]() { bool enabled = false; foreach (auto point, selection()) { // At least one selected item must be a valid clip @@ -1342,7 +1392,7 @@ void TimelineDock::setupActions() } } }); - connect(this, &TimelineDock::selectionChanged, action, [ = ]() { + connect(this, &TimelineDock::selectionChanged, action, [=]() { bool enabled = false; if (Settings.timelineShowThumbnails()) { foreach (auto point, selection()) { @@ -1366,7 +1416,7 @@ void TimelineDock::setupActions() } } }); - connect(this, &TimelineDock::selectionChanged, action, [ = ]() { + connect(this, &TimelineDock::selectionChanged, action, [=]() { bool enabled = false; if (Settings.timelineShowWaveforms()) { foreach (auto point, selection()) { @@ -1421,7 +1471,7 @@ void TimelineDock::setupActions() MAIN.undoStack()->push(groupCommand); } }); - connect(this, &TimelineDock::selectionChanged, action, [ = ]() { + connect(this, &TimelineDock::selectionChanged, action, [=]() { action->setEnabled(selection().size() > 1); }); Actions.add("timelineGroupAction", action); @@ -1435,7 +1485,8 @@ int TimelineDock::addTrackIfNeeded(TrackType trackType) // Hunt for next available track while (addTrack && trackIndex >= 0 && trackIndex < m_model.trackList().size()) { auto clipIndex = clipIndexAtPosition(trackIndex, position()); - if (clipIndex == -1 || (isBlank(trackIndex, clipIndex) && clipIndex >= clipCount(trackIndex) - 1)) { + if (clipIndex == -1 + || (isBlank(trackIndex, clipIndex) && clipIndex >= clipCount(trackIndex) - 1)) { // This track is available if correct type addTrack = m_model.trackList().at(trackIndex).type != trackType; } @@ -1478,7 +1529,8 @@ void TimelineDock::getSelectionRange(int *start, int *end) void TimelineDock::setPosition(int position) { - if (!m_model.tractor()) return; + if (!m_model.tractor()) + return; if (position <= m_model.tractor()->get_length()) { emit seeked(position); } else { @@ -1522,9 +1574,10 @@ int TimelineDock::clipIndexAtPosition(int trackIndex, int position) bool TimelineDock::isBlank(int trackIndex, int clipIndex) { - return trackIndex >= 0 && clipIndex >= 0 && - m_model.index(clipIndex, 0, m_model.index(trackIndex)) - .data(MultitrackModel::IsBlankRole).toBool(); + return trackIndex >= 0 && clipIndex >= 0 + && m_model.index(clipIndex, 0, m_model.index(trackIndex)) + .data(MultitrackModel::IsBlankRole) + .toBool(); } bool TimelineDock::clipsAreSelected() @@ -1548,9 +1601,10 @@ bool TimelineDock::nothingIsSelected() bool TimelineDock::isTransition(int trackIndex, int clipIndex) { - return trackIndex >= 0 && clipIndex >= 0 && - m_model.index(clipIndex, 0, m_model.index(trackIndex)) - .data(MultitrackModel::IsTransitionRole).toBool(); + return trackIndex >= 0 && clipIndex >= 0 + && m_model.index(clipIndex, 0, m_model.index(trackIndex)) + .data(MultitrackModel::IsTransitionRole) + .toBool(); } void TimelineDock::onWarnTrackLocked() @@ -1569,8 +1623,8 @@ void TimelineDock::addTrackIfNeeded(int trackIndex, Mlt::Producer *srcTrack) if (trackIndex >= n) { if (m_selection.selectedTrack != -1) setSelection(); - if (srcTrack->get_int(kAudioTrackProperty) || (n > 0 - && m_model.trackList()[n - 1].type == AudioTrackType)) { + if (srcTrack->get_int(kAudioTrackProperty) + || (n > 0 && m_model.trackList()[n - 1].type == AudioTrackType)) { MAIN.undoStack()->push( new Timeline::InsertTrackCommand(m_model, trackIndex, AudioTrackType)); } else { @@ -1661,11 +1715,10 @@ void TimelineDock::setSelectionFromJS(const QVariantList &list) void TimelineDock::setSelection(QList newSelection, int trackIndex, bool isMultitrack) { - if (newSelection != selection() - || trackIndex != m_selection.selectedTrack - || isMultitrack != m_selection.isMultitrackSelected) { - LOG_DEBUG() << "Changing selection to" << newSelection << " trackIndex" << trackIndex << - "isMultitrack" << isMultitrack; + if (newSelection != selection() || trackIndex != m_selection.selectedTrack + || isMultitrack != m_selection.isMultitrackSelected) { + LOG_DEBUG() << "Changing selection to" << newSelection << " trackIndex" << trackIndex + << "isMultitrack" << isMultitrack; m_selection.selectedClips = newSelection; m_selection.selectedTrack = trackIndex; m_selection.isMultitrackSelected = isMultitrack; @@ -1707,8 +1760,8 @@ const QVector TimelineDock::selectionUuids() const QList TimelineDock::uuidsToSelection(QVector uuids) const { QList points; - for (int trackIndex = 0; trackIndex < m_model.trackList().size() - && uuids.size() > 0; trackIndex++) { + for (int trackIndex = 0; trackIndex < m_model.trackList().size() && uuids.size() > 0; + trackIndex++) { int i = m_model.trackList().at(trackIndex).mlt_index; QScopedPointer track(m_model.tractor()->track(i)); if (track) { @@ -1716,8 +1769,9 @@ const QList TimelineDock::uuidsToSelection(QVector uuids) const for (int clipIndex = 0; clipIndex < playlist.count() && uuids.size() > 0; clipIndex++) { Mlt::ClipInfo *info; if ((info = playlist.clip_info(clipIndex))) { - for (int i = 0; i < uuids.size(); i++ ) { - if (MLT.uuid(*info->producer) == uuids[i] || MLT.uuid(*info->cut) == uuids[i]) { + for (int i = 0; i < uuids.size(); i++) { + if (MLT.uuid(*info->producer) == uuids[i] + || MLT.uuid(*info->cut) == uuids[i]) { points << QPoint(clipIndex, trackIndex); uuids.removeAt(i); break; @@ -1768,7 +1822,7 @@ QVariantList TimelineDock::getGroupForClip(int trackIndex, int clipIndex) for (int clipIndex = 0; clipIndex < playlist.count(); clipIndex++) { QScopedPointer info(playlist.clip_info(clipIndex)); if (info && info->cut && info->cut->property_exists(kShotcutGroupProperty) - && info->cut->get_int(kShotcutGroupProperty) == group) { + && info->cut->get_int(kShotcutGroupProperty) == group) { result << QPoint(clipIndex, trackIndex); } } @@ -1834,22 +1888,30 @@ void TimelineDock::trimClipAtPlayhead(TrimLocation location, bool ripple) return; if (location == TrimInPoint) { - MAIN.undoStack()->push( - new Timeline::TrimClipInCommand(m_model, m_markersModel, trackIndex, clipIndex, - m_position - info->start, ripple)); + MAIN.undoStack()->push(new Timeline::TrimClipInCommand(m_model, + m_markersModel, + trackIndex, + clipIndex, + m_position - info->start, + ripple)); if (ripple) setPosition(info->start); if (m_updateCommand && m_updateCommand->trackIndex() == trackIndex - && m_updateCommand->clipIndex() == clipIndex) - m_updateCommand->setPosition(trackIndex, clipIndex, + && m_updateCommand->clipIndex() == clipIndex) + m_updateCommand->setPosition(trackIndex, + clipIndex, m_updateCommand->position() + m_position - info->start); emit MAIN.serviceInChanged(m_position - info->start, info->producer); } else { MAIN.undoStack()->push( - new Timeline::TrimClipOutCommand(m_model, m_markersModel, trackIndex, clipIndex, - info->start + info->frame_count - m_position, ripple)); + new Timeline::TrimClipOutCommand(m_model, + m_markersModel, + trackIndex, + clipIndex, + info->start + info->frame_count - m_position, + ripple)); if (m_updateCommand && m_updateCommand->trackIndex() == trackIndex - && m_updateCommand->clipIndex() == clipIndex) + && m_updateCommand->clipIndex() == clipIndex) m_updateCommand->setPosition(trackIndex, clipIndex, -1); } } @@ -1884,8 +1946,7 @@ void TimelineDock::insertTrack() { if (m_selection.selectedTrack != -1) setSelection(); - MAIN.undoStack()->push( - new Timeline::InsertTrackCommand(m_model, currentTrack())); + MAIN.undoStack()->push(new Timeline::InsertTrackCommand(m_model, currentTrack())); } void TimelineDock::insertAudioTrack() @@ -1908,8 +1969,7 @@ void TimelineDock::removeTrack() { if (m_model.trackList().size() > 0) { int trackIndex = currentTrack(); - MAIN.undoStack()->push( - new Timeline::RemoveTrackCommand(m_model, trackIndex)); + MAIN.undoStack()->push(new Timeline::RemoveTrackCommand(m_model, trackIndex)); if (trackIndex >= m_model.trackList().count()) setCurrentTrack(m_model.trackList().count() - 1); } @@ -1951,7 +2011,8 @@ void TimelineDock::moveTrackUp() } } if (topVideo) { - MAIN.showStatusMessage(tr("Track %1 was not moved").arg(m_model.getTrackName(trackIndex))); + MAIN.showStatusMessage( + tr("Track %1 was not moved").arg(m_model.getTrackName(trackIndex))); return; } } @@ -1984,7 +2045,8 @@ void TimelineDock::moveTrackDown() } } if (bottomAudio) { - MAIN.showStatusMessage(tr("Track %1 was not moved").arg(m_model.getTrackName(trackIndex))); + MAIN.showStatusMessage( + tr("Track %1 was not moved").arg(m_model.getTrackName(trackIndex))); return; } } @@ -1997,8 +2059,7 @@ bool TimelineDock::mergeClipWithNext(int trackIndex, int clipIndex, bool dryrun) if (dryrun) return m_model.mergeClipWithNext(trackIndex, clipIndex, true); - MAIN.undoStack()->push( - new Timeline::MergeCommand(m_model, trackIndex, clipIndex)); + MAIN.undoStack()->push(new Timeline::MergeCommand(m_model, trackIndex, clipIndex)); return true; } @@ -2027,8 +2088,11 @@ void TimelineDock::onProducerChanged(Mlt::Producer *after) QString oldServiceName = info->producer->get("mlt_service"); QString newServiceName = after->get("mlt_service"); if (oldServiceName == "timewarp" || newServiceName == "timewarp") { - double oldSpeed = oldServiceName != "timewarp" ? 1.0 : info->producer->get_double("warp_speed"); - double newSpeed = newServiceName != "timewarp" ? 1.0 : after->get_double("warp_speed"); + double oldSpeed = oldServiceName != "timewarp" + ? 1.0 + : info->producer->get_double("warp_speed"); + double newSpeed = newServiceName != "timewarp" ? 1.0 + : after->get_double("warp_speed"); double speedRatio = oldSpeed / newSpeed; int length = qRound(info->length * speedRatio); int in = qMin(qRound(info->frame_in * speedRatio), length - 1); @@ -2036,15 +2100,20 @@ void TimelineDock::onProducerChanged(Mlt::Producer *after) if (!Settings.timelineRipple() && (clipIndex + 1) < playlist.count()) { // limit the out point to what fits before the next clip if (playlist.is_blank(clipIndex + 1)) { - out = qMin(out, in + info->frame_count - 1 + playlist.clip_length(clipIndex + 1)); + out = qMin(out, + in + info->frame_count - 1 + playlist.clip_length(clipIndex + 1)); } else { out = qMin(out, in + info->frame_count - 1); } } after->set_in_and_out(in, out); // Adjust filters. - MLT.adjustClipFilters(*after, info->frame_in, info->frame_out, in - info->frame_in, - info->frame_out - out, 0); + MLT.adjustClipFilters(*after, + info->frame_in, + info->frame_out, + in - info->frame_in, + info->frame_out - out, + 0); resetRippleAll = false; } else if (newServiceName == "qimage" || newServiceName == "pixbuf") { int oldLength = info->frame_out - info->frame_in; @@ -2056,14 +2125,21 @@ void TimelineDock::onProducerChanged(Mlt::Producer *after) if (!Settings.timelineRipple() && (clipIndex + 1) < playlist.count()) { // limit the out point to what fits before the next clip if (playlist.is_blank(clipIndex + 1)) { - out = qMin(out, in + info->frame_count - 1 + playlist.clip_length(clipIndex + 1)); + out = qMin(out, + in + info->frame_count - 1 + + playlist.clip_length(clipIndex + 1)); } else { out = qMin(out, in + info->frame_count - 1); } } after->set_in_and_out(in, out); // Adjust filters. - MLT.adjustClipFilters(*after, info->frame_in, info->frame_out, 0, -lengthDelta, 0); + MLT.adjustClipFilters(*after, + info->frame_in, + info->frame_out, + 0, + -lengthDelta, + 0); } } else { after->set_in_and_out(info->frame_in, info->frame_out); @@ -2082,8 +2158,7 @@ int TimelineDock::addAudioTrack() { if (m_selection.selectedTrack != -1) setSelection(); - MAIN.undoStack()->push( - new Timeline::AddTrackCommand(m_model, false)); + MAIN.undoStack()->push(new Timeline::AddTrackCommand(m_model, false)); return m_model.trackList().size() - 1; } @@ -2091,8 +2166,7 @@ int TimelineDock::addVideoTrack() { if (m_selection.selectedTrack != -1) setSelection(); - MAIN.undoStack()->push( - new Timeline::AddTrackCommand(m_model, true)); + MAIN.undoStack()->push(new Timeline::AddTrackCommand(m_model, true)); return 0; } @@ -2143,7 +2217,6 @@ void TimelineDock::onSeeked(int position) } } - static bool isSystemClipboardValid(const QString &xml) { return MLT.isMltXml(xml) && MAIN.isClipboardNewer() && !xml.contains(kShotcutFiltersClipboard); @@ -2157,7 +2230,8 @@ void TimelineDock::append(int trackIndex) emit warnTrackLocked(trackIndex); return; } - if (MAIN.isSourceClipMyProject()) return; + if (MAIN.isSourceClipMyProject()) + return; // Use MLT XML on the clipboard if it exists and is newer than source clip. QString xmlToUse = QGuiApplication::clipboard()->text(); @@ -2186,7 +2260,7 @@ void TimelineDock::append(int trackIndex) // No need to create a track in an empty timeline. // This can be a macro of QUndoCommands. if (producer.is_valid() && producer.type() == mlt_service_tractor_type - && producer.get_int(kShotcutXmlProperty)) { + && producer.get_int(kShotcutXmlProperty)) { Mlt::Tractor tractor(producer); Mlt::ClipInfo info; MAIN.undoStack()->beginMacro(tr("Append multiple to timeline")); @@ -2206,9 +2280,13 @@ void TimelineDock::append(int trackIndex) playlist.clip_info(mltClipIndex, &info); Mlt::Producer clip(info.producer); clip.set_in_and_out(info.frame_in, info.frame_out); - bool lastClip = mltTrackIndex == tractor.count() - 1 && mltClipIndex == playlist.count() - 1; - MAIN.undoStack()->push( - new Timeline::AppendCommand(m_model, trackIndex, MLT.XML(&clip), false, lastClip)); + bool lastClip = mltTrackIndex == tractor.count() - 1 + && mltClipIndex == playlist.count() - 1; + MAIN.undoStack()->push(new Timeline::AppendCommand(m_model, + trackIndex, + MLT.XML(&clip), + false, + lastClip)); } } } @@ -2221,8 +2299,7 @@ void TimelineDock::append(int trackIndex) addVideoTrack(); } - MAIN.undoStack()->push( - new Timeline::AppendCommand(m_model, trackIndex, xmlToUse)); + MAIN.undoStack()->push(new Timeline::AppendCommand(m_model, trackIndex, xmlToUse)); } if (m_position < 0) { @@ -2242,7 +2319,8 @@ void TimelineDock::remove(int trackIndex, int clipIndex, bool ignoreTransition) emit warnTrackLocked(trackIndex); return; } - if (trackIndex < 0 || clipIndex < 0) return; + if (trackIndex < 0 || clipIndex < 0) + return; if (!ignoreTransition && isTransition(trackIndex, clipIndex)) { MAIN.undoStack()->beginMacro(tr("Ripple delete transition")); @@ -2255,16 +2333,22 @@ void TimelineDock::remove(int trackIndex, int clipIndex, bool ignoreTransition) std::unique_ptr transitionClip(transition.track(1)); auto neighborClip = producerForClip(trackIndex, clipIndex); if (neighborClip.is_valid() && transitionClip && neighborClip.same_clip(*transitionClip)) - MAIN.undoStack()->push( - new Timeline::TrimClipInCommand(m_model, m_markersModel, trackIndex, clipIndex, - -info->frame_count, true)); + MAIN.undoStack()->push(new Timeline::TrimClipInCommand(m_model, + m_markersModel, + trackIndex, + clipIndex, + -info->frame_count, + true)); // verify the clip before belongs to transition transitionClip.reset(transition.track(0)); neighborClip = producerForClip(trackIndex, clipIndex - 1); if (neighborClip.is_valid() && transitionClip && neighborClip.same_clip(*transitionClip)) - MAIN.undoStack()->push( - new Timeline::TrimClipOutCommand(m_model, m_markersModel, trackIndex, clipIndex - 1, - -info->frame_count, true)); + MAIN.undoStack()->push(new Timeline::TrimClipOutCommand(m_model, + m_markersModel, + trackIndex, + clipIndex - 1, + -info->frame_count, + true)); } MAIN.undoStack()->endMacro(); } else { @@ -2284,13 +2368,14 @@ void TimelineDock::lift(int trackIndex, int clipIndex, bool ignoreTransition) emit warnTrackLocked(trackIndex); return; } - if (trackIndex < 0 || clipIndex < 0) return; + if (trackIndex < 0 || clipIndex < 0) + return; if (!ignoreTransition && isTransition(trackIndex, clipIndex)) { MAIN.undoStack()->beginMacro(tr("Lift transition")); auto info = m_model.getClipInfo(trackIndex, clipIndex); - if (clipIndex > 0 && clipIndex + 1 < m_model.rowCount(m_model.index(trackIndex)) && info->producer - && info->producer->is_valid()) { + if (clipIndex > 0 && clipIndex + 1 < m_model.rowCount(m_model.index(trackIndex)) + && info->producer && info->producer->is_valid()) { // verify the clip after belongs to transition Mlt::Tractor transition(*info->producer); std::unique_ptr transitionClip(transition.track(1)); @@ -2298,27 +2383,32 @@ void TimelineDock::lift(int trackIndex, int clipIndex, bool ignoreTransition) auto clipAfter = producerForClip(trackIndex, clipIndex + 1); auto duration = info->frame_count; - MAIN.undoStack()->push( - new Timeline::LiftCommand(m_model, trackIndex, clipIndex)); + MAIN.undoStack()->push(new Timeline::LiftCommand(m_model, trackIndex, clipIndex)); - if (clipBefore.is_valid() && clipAfter.is_valid() - && !clipBefore.is_blank() && !clipAfter.is_blank()) + if (clipBefore.is_valid() && clipAfter.is_valid() && !clipBefore.is_blank() + && !clipAfter.is_blank()) duration /= 2; if (clipAfter.is_valid() && transitionClip && clipAfter.same_clip(*transitionClip)) MAIN.undoStack()->push( - new Timeline::TrimClipInCommand(m_model, m_markersModel, trackIndex, - clipIndex + (clipBefore.is_blank() ? 0 : 1), -duration, false)); + new Timeline::TrimClipInCommand(m_model, + m_markersModel, + trackIndex, + clipIndex + (clipBefore.is_blank() ? 0 : 1), + -duration, + false)); // verify the clip before belongs to transition transitionClip.reset(transition.track(0)); if (duration < info->frame_count) duration += info->frame_count % 2; if (clipBefore.is_valid() && transitionClip && clipBefore.same_clip(*transitionClip)) - MAIN.undoStack()->push( - new Timeline::TrimClipOutCommand(m_model, m_markersModel, trackIndex, clipIndex - 1, - -duration, false)); + MAIN.undoStack()->push(new Timeline::TrimClipOutCommand(m_model, + m_markersModel, + trackIndex, + clipIndex - 1, + -duration, + false)); } else { - MAIN.undoStack()->push( - new Timeline::LiftCommand(m_model, trackIndex, clipIndex)); + MAIN.undoStack()->push(new Timeline::LiftCommand(m_model, trackIndex, clipIndex)); } MAIN.undoStack()->endMacro(); } else { @@ -2326,8 +2416,7 @@ void TimelineDock::lift(int trackIndex, int clipIndex, bool ignoreTransition) if (clip.is_valid()) { if (clip.is_blank()) return; - MAIN.undoStack()->push( - new Timeline::LiftCommand(m_model, trackIndex, clipIndex)); + MAIN.undoStack()->push(new Timeline::LiftCommand(m_model, trackIndex, clipIndex)); setSelection(); } } @@ -2415,7 +2504,6 @@ void TimelineDock::selectMultitrack() setSelection(QList(), -1, true); } - template static void insertSorted(std::vector &vec, T const &item) { @@ -2451,7 +2539,8 @@ void TimelineDock::copy(int trackIndex, int clipIndex) minY = std::min(minY, a.y()); maxY = std::max(maxY, a.y()); auto info = m_model.getClipInfo(a.y(), a.x()); - if (info) minStart = std::min(minStart, info->start); + if (info) + minStart = std::min(minStart, info->start); } // Create the tracks Mlt::Tractor tractor(MLT.profile()); @@ -2470,7 +2559,10 @@ void TimelineDock::copy(int trackIndex, int clipIndex) std::vector clipIndices; for (auto &a : selected) { if (a.y() == trackIndex) { - clipIndices.insert(std::upper_bound(clipIndices.begin(), clipIndices.end(), a.x()), a.x()); + clipIndices.insert(std::upper_bound(clipIndices.begin(), + clipIndices.end(), + a.x()), + a.x()); } } @@ -2511,13 +2603,13 @@ void TimelineDock::emitSelectedFromSelection() // can get information about the cut while still applying filters // to the cut parent. int trackIndex = clip.y(); - int clipIndex = clip.x(); + int clipIndex = clip.x(); auto info = m_model.getClipInfo(trackIndex, clipIndex); if (!info) continue; auto info2 = m_model.getClipInfo(trackIndex, clipIndex - 1); if (info2 && info2->producer && info2->producer->is_valid() - && info2->producer->get(kShotcutTransitionProperty)) { + && info2->producer->get(kShotcutTransitionProperty)) { // Factor in a transition left of the clip. info->producer->set(kFilterInProperty, info->frame_in - info2->frame_count); info->producer->set(kPlaylistStartProperty, info2->start); @@ -2527,14 +2619,15 @@ void TimelineDock::emitSelectedFromSelection() } info2 = m_model.getClipInfo(trackIndex, clipIndex + 1); if (info2 && info2->producer && info2->producer->is_valid() - && info2->producer->get(kShotcutTransitionProperty)) { + && info2->producer->get(kShotcutTransitionProperty)) { // Factor in a transition right of the clip. info->producer->set(kFilterOutProperty, info->frame_out + info2->frame_count); } else { info->producer->set(kFilterOutProperty, info->frame_out); } - info->producer->set(kMultitrackItemProperty, - QStringLiteral("%1:%2").arg(clipIndex).arg(trackIndex).toLatin1().constData()); + info->producer + ->set(kMultitrackItemProperty, + QStringLiteral("%1:%2").arg(clipIndex).arg(trackIndex).toLatin1().constData()); } if (selection().size() > 1 || nothingIsSelected()) { @@ -2543,9 +2636,9 @@ void TimelineDock::emitSelectedFromSelection() } if (selection().isEmpty() && m_selection.selectedTrack > -1 - && m_selection.selectedTrack < m_model.trackList().count()) { + && m_selection.selectedTrack < m_model.trackList().count()) { int i = m_model.trackList().at(m_selection.selectedTrack).mlt_index; - std::unique_ptrproducer(m_model.tractor()->track(i)); + std::unique_ptr producer(m_model.tractor()->track(i)); if (producer && producer->is_valid()) { producer->set(kTrackIndexProperty, m_selection.selectedTrack); emit selected(producer.get()); @@ -2560,10 +2653,11 @@ void TimelineDock::emitSelectedFromSelection() } int trackIndex = selection().isEmpty() ? currentTrack() : selection().first().y(); - int clipIndex = selection().isEmpty() ? 0 : selection().first().x(); + int clipIndex = selection().isEmpty() ? 0 : selection().first().x(); auto info = m_model.getClipInfo(trackIndex, clipIndex); if (info && info->producer && info->producer->is_valid()) { - m_updateCommand.reset(new Timeline::UpdateCommand(*this, trackIndex, clipIndex, info->start)); + m_updateCommand.reset( + new Timeline::UpdateCommand(*this, trackIndex, clipIndex, info->start)); m_ignoreNextPositionChange = true; emit selected(info->producer); } @@ -2585,7 +2679,8 @@ void TimelineDock::remakeAudioLevels(int trackIndex, int clipIndex, bool force) void TimelineDock::commitTrimCommand() { if (m_trimCommand && (m_trimDelta || m_transitionDelta)) { - if (m_undoHelper) m_trimCommand->setUndoHelper(m_undoHelper.release()); + if (m_undoHelper) + m_trimCommand->setUndoHelper(m_undoHelper.release()); MAIN.undoStack()->push(m_trimCommand.release()); } m_trimDelta = 0; @@ -2655,8 +2750,8 @@ void TimelineDock::onRowsRemoved(const QModelIndex &parent, int first, int last) } } -void TimelineDock::onRowsMoved(const QModelIndex &parent, int start, int end, - const QModelIndex &destination, int row) +void TimelineDock::onRowsMoved( + const QModelIndex &parent, int start, int end, const QModelIndex &destination, int row) { Q_UNUSED(parent) Q_UNUSED(start) @@ -2677,14 +2772,19 @@ void TimelineDock::detachAudio(int trackIndex, int clipIndex) Q_ASSERT(trackIndex >= 0 && clipIndex >= 0); auto info = m_model.getClipInfo(trackIndex, clipIndex); if (info && info->producer && info->producer->is_valid() && !info->producer->is_blank() - && info->producer->get("audio_index") && info->producer->get_int("audio_index") >= 0) { + && info->producer->get("audio_index") && info->producer->get_int("audio_index") >= 0) { if (!info->producer->property_exists(kDefaultAudioIndexProperty)) { info->producer->set(kDefaultAudioIndexProperty, info->producer->get_int("audio_index")); } - Mlt::Producer clip(MLT.profile(), "xml-string", MLT.XML(info->producer).toUtf8().constData()); + Mlt::Producer clip(MLT.profile(), + "xml-string", + MLT.XML(info->producer).toUtf8().constData()); clip.set_in_and_out(info->frame_in, info->frame_out); - MAIN.undoStack()->push( - new Timeline::DetachAudioCommand(*this, trackIndex, clipIndex, info->start, MLT.XML(&clip))); + MAIN.undoStack()->push(new Timeline::DetachAudioCommand(*this, + trackIndex, + clipIndex, + info->start, + MLT.XML(&clip))); } } @@ -2743,7 +2843,7 @@ void TimelineDock::replace(int trackIndex, int clipIndex, const QString &xml) if (MLT.isSeekableClip() || MLT.savedProducer() || !xml.isEmpty()) { Q_ASSERT(trackIndex >= 0 && clipIndex >= 0); QString xmlToUse = !xml.isEmpty() ? xml - : MLT.XML(MLT.isClip() ? nullptr : MLT.savedProducer()); + : MLT.XML(MLT.isClip() ? nullptr : MLT.savedProducer()); MAIN.undoStack()->push( new Timeline::ReplaceCommand(m_model, trackIndex, clipIndex, xmlToUse)); } else if (!MLT.isSeekableClip()) { @@ -2809,13 +2909,17 @@ void TimelineDock::createMarker() marker.end = position(); m_markersModel.append(marker); emit showStatusMessage(tr("Added marker: \"%1\". Hold %2 and drag to create a range") - .arg(marker.text, QmlApplication::OS() == "macOS" ? "⌘" : "Ctrl")); + .arg(marker.text, QmlApplication::OS() == "macOS" ? "⌘" : "Ctrl")); } void TimelineDock::editMarker(int markerIndex) { Markers::Marker marker = m_markersModel.getMarker(markerIndex); - EditMarkerDialog dialog(this, marker.text, marker.color, marker.start, marker.end, + EditMarkerDialog dialog(this, + marker.text, + marker.color, + marker.start, + marker.end, m_model.tractor()->get_length() - 1); dialog.setWindowModality(QmlApplication::dialogModality()); if (dialog.exec() == QDialog::Accepted) { @@ -2892,7 +2996,7 @@ void TimelineDock::handleDrop(int trackIndex, int position, QString xmlOrUrls) } // Use QTimer to workaround stupid drag from Windows Explorer bug - QTimer::singleShot(0, this, [ = ]() { + QTimer::singleShot(0, this, [=]() { auto xml = xmlOrUrls; int i = 0, count = urls.size(); @@ -2909,7 +3013,8 @@ void TimelineDock::handleDrop(int trackIndex, int position, QString xmlOrUrls) Mlt::Playlist playlist(MLT.profile()); ResourceDialog dialog(this); for (const auto &path : Util::sortedFileList(urls)) { - if (MAIN.isSourceClipMyProject(path, /* withDialog */ false)) continue; + if (MAIN.isSourceClipMyProject(path, /* withDialog */ false)) + continue; if (MLT.checkFile(path)) { MAIN.showStatusMessage(QObject::tr("Failed to open ").append(path)); continue; @@ -2927,7 +3032,8 @@ void TimelineDock::handleDrop(int trackIndex, int position, QString xmlOrUrls) } if (p.is_valid()) { if (!qstrcmp(p.get("mlt_service"), "avformat") && !p.get_int("seekable")) { - MAIN.showStatusMessage(QObject::tr("Not adding non-seekable file: ") + Util::baseName(path)); + MAIN.showStatusMessage(QObject::tr("Not adding non-seekable file: ") + + Util::baseName(path)); continue; } Mlt::Producer *producer = MLT.setupNewProducer(&p); @@ -2939,7 +3045,8 @@ void TimelineDock::handleDrop(int trackIndex, int position, QString xmlOrUrls) } } xml = MLT.XML(&playlist); - if (Settings.showConvertClipDialog() && dialog.producerCount() > 1 && dialog.hasTroubleClips()) { + if (Settings.showConvertClipDialog() && dialog.producerCount() > 1 + && dialog.hasTroubleClips()) { dialog.selectTroubleClips(); dialog.setWindowTitle(tr("Dropped Files")); longTask.cancel(); @@ -2989,32 +3096,27 @@ void TimelineDock::onLoopChanged(int start, int end) void TimelineDock::setTrackName(int trackIndex, const QString &value) { - MAIN.undoStack()->push( - new Timeline::NameTrackCommand(m_model, trackIndex, value)); + MAIN.undoStack()->push(new Timeline::NameTrackCommand(m_model, trackIndex, value)); } void TimelineDock::toggleTrackMute(int trackIndex) { - MAIN.undoStack()->push( - new Timeline::MuteTrackCommand(m_model, trackIndex)); + MAIN.undoStack()->push(new Timeline::MuteTrackCommand(m_model, trackIndex)); } void TimelineDock::toggleTrackHidden(int trackIndex) { - MAIN.undoStack()->push( - new Timeline::HideTrackCommand(m_model, trackIndex)); + MAIN.undoStack()->push(new Timeline::HideTrackCommand(m_model, trackIndex)); } void TimelineDock::setTrackComposite(int trackIndex, bool composite) { - MAIN.undoStack()->push( - new Timeline::CompositeTrackCommand(m_model, trackIndex, composite)); + MAIN.undoStack()->push(new Timeline::CompositeTrackCommand(m_model, trackIndex, composite)); } void TimelineDock::setTrackLock(int trackIndex, bool lock) { - MAIN.undoStack()->push( - new Timeline::LockTrackCommand(m_model, trackIndex, lock)); + MAIN.undoStack()->push(new Timeline::LockTrackCommand(m_model, trackIndex, lock)); } bool TimelineDock::moveClip(int fromTrack, int toTrack, int clipIndex, int position, bool ripple) @@ -3031,14 +3133,15 @@ bool TimelineDock::moveClip(int fromTrack, int toTrack, int clipIndex, int posit track.reset((m_model.tractor()->track(i))); if (track->is_valid()) { Mlt::Playlist playlist(*track.data()); - if (m_model.isTransition(playlist, playlist.get_clip_index_at(position)) || - m_model.isTransition(playlist, playlist.get_clip_index_at(position + length - 1))) { + if (m_model.isTransition(playlist, playlist.get_clip_index_at(position)) + || m_model.isTransition(playlist, + playlist.get_clip_index_at(position + length - 1))) { return false; } } } if (selection().size() <= 1 - && m_model.addTransitionValid(fromTrack, toTrack, clipIndex, position, ripple)) { + && m_model.addTransitionValid(fromTrack, toTrack, clipIndex, position, ripple)) { emit transitionAdded(fromTrack, clipIndex, position, ripple); if (m_updateCommand) m_updateCommand->setPosition(toTrack, clipIndex, position); @@ -3089,13 +3192,15 @@ void TimelineDock::onClipMoved(int fromTrack, int toTrack, int clipIndex, int po disconnect(&m_model, &MultitrackModel::noMoreEmptyTracks, this, nullptr); MAIN.undoStack()->push(command); if (fromTrack == toTrack) - connect(&m_model, &MultitrackModel::noMoreEmptyTracks, this, &TimelineDock::onNoMoreEmptyTracks, + connect(&m_model, + &MultitrackModel::noMoreEmptyTracks, + this, + &TimelineDock::onNoMoreEmptyTracks, Qt::QueuedConnection); } } -bool TimelineDock::trimClipIn(int trackIndex, int clipIndex, int oldClipIndex, int delta, - bool ripple) +bool TimelineDock::trimClipIn(int trackIndex, int clipIndex, int oldClipIndex, int delta, bool ripple) { if (dynamic_cast(m_trimCommand.get())) { if (delta < 0) { @@ -3114,33 +3219,44 @@ bool TimelineDock::trimClipIn(int trackIndex, int clipIndex, int oldClipIndex, i if (!ripple && m_model.addTransitionByTrimInValid(trackIndex, clipIndex, delta)) { clipIndex = m_model.addTransitionByTrimIn(trackIndex, clipIndex, delta); m_transitionDelta += delta; - m_trimCommand.reset(new Timeline::AddTransitionByTrimInCommand(*this, trackIndex, clipIndex - 1, - m_transitionDelta, m_trimDelta, false)); + m_trimCommand.reset(new Timeline::AddTransitionByTrimInCommand(*this, + trackIndex, + clipIndex - 1, + m_transitionDelta, + m_trimDelta, + false)); if (m_updateCommand && m_updateCommand->trackIndex() == trackIndex - && m_updateCommand->clipIndex() == clipIndex) + && m_updateCommand->clipIndex() == clipIndex) m_updateCommand->setPosition(trackIndex, clipIndex, -1); } else if (!ripple && m_model.removeTransitionByTrimInValid(trackIndex, clipIndex, delta)) { Q_ASSERT(trackIndex >= 0 && clipIndex >= 0); std::unique_ptr clipInfo = m_model.getClipInfo(trackIndex, clipIndex - 1); QString xml = MLT.XML(clipInfo->producer); m_model.liftClip(trackIndex, clipIndex - 1); - if (delta < 0 ) { + if (delta < 0) { m_model.trimClipIn(trackIndex, clipIndex, -clipInfo->length, false, false); m_trimDelta += -clipInfo->length; } else if (delta > 0) { m_model.trimClipOut(trackIndex, clipIndex - 2, -clipInfo->length, false, false); m_transitionDelta = 0; } - m_trimCommand.reset(new Timeline::RemoveTransitionByTrimInCommand(m_model, trackIndex, - clipIndex - 1, m_trimDelta, xml, false)); + m_trimCommand.reset(new Timeline::RemoveTransitionByTrimInCommand(m_model, + trackIndex, + clipIndex - 1, + m_trimDelta, + xml, + false)); if (m_updateCommand && m_updateCommand->trackIndex() == trackIndex - && m_updateCommand->clipIndex() == clipIndex) + && m_updateCommand->clipIndex() == clipIndex) m_updateCommand->setPosition(trackIndex, clipIndex - 1, -1); } else if (!ripple && m_model.trimTransitionOutValid(trackIndex, clipIndex, delta)) { m_model.trimTransitionOut(trackIndex, clipIndex, delta); m_trimDelta += delta; - m_trimCommand.reset(new Timeline::TrimTransitionOutCommand(m_model, trackIndex, clipIndex, - m_trimDelta, false)); + m_trimCommand.reset(new Timeline::TrimTransitionOutCommand(m_model, + trackIndex, + clipIndex, + m_trimDelta, + false)); } else if (m_model.trimClipInValid(trackIndex, clipIndex, delta, ripple)) { if (!m_undoHelper) { m_undoHelper.reset(new UndoHelper(m_model)); @@ -3151,16 +3267,20 @@ bool TimelineDock::trimClipIn(int trackIndex, int clipIndex, int oldClipIndex, i } m_undoHelper->recordBeforeState(); } - clipIndex = m_model.trimClipIn(trackIndex, clipIndex, delta, ripple, + clipIndex = m_model.trimClipIn(trackIndex, + clipIndex, + delta, + ripple, Settings.timelineRippleAllTracks()); m_trimDelta += delta; - m_trimCommand.reset(new Timeline::TrimClipInCommand(m_model, m_markersModel, trackIndex, - oldClipIndex, m_trimDelta, ripple, false)); + m_trimCommand.reset(new Timeline::TrimClipInCommand( + m_model, m_markersModel, trackIndex, oldClipIndex, m_trimDelta, ripple, false)); if (m_updateCommand && m_updateCommand->trackIndex() == trackIndex - && m_updateCommand->clipIndex() == clipIndex) + && m_updateCommand->clipIndex() == clipIndex) m_updateCommand->setPosition(trackIndex, clipIndex, m_updateCommand->position() + delta); - } else return false; + } else + return false; // Update duration in properties auto info = m_model.getClipInfo(trackIndex, clipIndex); @@ -3188,48 +3308,61 @@ bool TimelineDock::trimClipOut(int trackIndex, int clipIndex, int delta, bool ri if (!ripple && m_model.addTransitionByTrimOutValid(trackIndex, clipIndex, delta)) { m_model.addTransitionByTrimOut(trackIndex, clipIndex, delta); m_transitionDelta += delta; - m_trimCommand.reset(new Timeline::AddTransitionByTrimOutCommand(m_model, trackIndex, clipIndex, - m_transitionDelta, m_trimDelta, false)); + m_trimCommand.reset(new Timeline::AddTransitionByTrimOutCommand(m_model, + trackIndex, + clipIndex, + m_transitionDelta, + m_trimDelta, + false)); if (m_updateCommand && m_updateCommand->trackIndex() == trackIndex - && m_updateCommand->clipIndex() == clipIndex) + && m_updateCommand->clipIndex() == clipIndex) m_updateCommand->setPosition(trackIndex, clipIndex, -1); } else if (!ripple && m_model.removeTransitionByTrimOutValid(trackIndex, clipIndex, delta)) { Q_ASSERT(trackIndex >= 0 && clipIndex >= 0); std::unique_ptr clipInfo = m_model.getClipInfo(trackIndex, clipIndex + 1); QString xml = MLT.XML(clipInfo->producer); m_model.liftClip(trackIndex, clipIndex + 1); - if (delta < 0 ) { + if (delta < 0) { m_model.trimClipOut(trackIndex, clipIndex, -clipInfo->length, false, false); m_trimDelta += -clipInfo->length; } else if (delta > 0) { m_model.trimClipIn(trackIndex, clipIndex + 2, -clipInfo->length, false, false); m_transitionDelta = 0; } - m_trimCommand.reset(new Timeline::RemoveTransitionByTrimOutCommand(m_model, trackIndex, - clipIndex + 1, m_trimDelta, xml, false)); + m_trimCommand.reset(new Timeline::RemoveTransitionByTrimOutCommand(m_model, + trackIndex, + clipIndex + 1, + m_trimDelta, + xml, + false)); if (m_updateCommand && m_updateCommand->trackIndex() == trackIndex - && m_updateCommand->clipIndex() == clipIndex) + && m_updateCommand->clipIndex() == clipIndex) m_updateCommand->setPosition(trackIndex, clipIndex, -1); } else if (!ripple && m_model.trimTransitionInValid(trackIndex, clipIndex, delta)) { m_model.trimTransitionIn(trackIndex, clipIndex, delta); m_trimDelta += delta; - m_trimCommand.reset(new Timeline::TrimTransitionInCommand(m_model, trackIndex, clipIndex, - m_trimDelta, false)); + m_trimCommand.reset(new Timeline::TrimTransitionInCommand(m_model, + trackIndex, + clipIndex, + m_trimDelta, + false)); } else if (m_model.trimClipOutValid(trackIndex, clipIndex, delta, ripple)) { if (!m_undoHelper) { m_undoHelper.reset(new UndoHelper(m_model)); - if (!ripple) m_undoHelper->setHints(UndoHelper::SkipXML); + if (!ripple) + m_undoHelper->setHints(UndoHelper::SkipXML); m_undoHelper->recordBeforeState(); } m_model.trimClipOut(trackIndex, clipIndex, delta, ripple, Settings.timelineRippleAllTracks()); m_trimDelta += delta; - m_trimCommand.reset(new Timeline::TrimClipOutCommand(m_model, m_markersModel, trackIndex, clipIndex, - m_trimDelta, ripple, false)); + m_trimCommand.reset(new Timeline::TrimClipOutCommand( + m_model, m_markersModel, trackIndex, clipIndex, m_trimDelta, ripple, false)); if (m_updateCommand && m_updateCommand->trackIndex() == trackIndex - && m_updateCommand->clipIndex() == clipIndex) + && m_updateCommand->clipIndex() == clipIndex) m_updateCommand->setPosition(trackIndex, clipIndex, -1); - } else return false; + } else + return false; // Update duration in properties auto info = m_model.getClipInfo(trackIndex, clipIndex); @@ -3248,7 +3381,8 @@ void TimelineDock::insert(int trackIndex, int position, const QString &xml, bool emit warnTrackLocked(trackIndex); return; } - if (xml.contains(MAIN.fileName()) && MAIN.isSourceClipMyProject()) return; + if (xml.contains(MAIN.fileName()) && MAIN.isSourceClipMyProject()) + return; // Use MLT XML on the clipboard if it exists and is newer than source clip. QString xmlToUse = QGuiApplication::clipboard()->text(); @@ -3282,7 +3416,7 @@ void TimelineDock::insert(int trackIndex, int position, const QString &xml, bool // No need to create a track in an empty timeline. // This can be a macro of QUndoCommands. if (producer.is_valid() && producer.type() == mlt_service_tractor_type - && producer.get_int(kShotcutXmlProperty)) { + && producer.get_int(kShotcutXmlProperty)) { Mlt::Tractor tractor(producer); Mlt::ClipInfo info; MAIN.undoStack()->beginMacro(tr("Insert multiple into timeline")); @@ -3302,10 +3436,14 @@ void TimelineDock::insert(int trackIndex, int position, const QString &xml, bool playlist.clip_info(mltClipIndex, &info); Mlt::Producer clip(info.producer); clip.set_in_and_out(info.frame_in, info.frame_out); - bool lastClip = mltTrackIndex == tractor.count() - 1 && mltClipIndex == playlist.count() - 1; - MAIN.undoStack()->push( - new Timeline::InsertCommand(m_model, m_markersModel, trackIndex, position + info.start, - MLT.XML(&clip), lastClip)); + bool lastClip = mltTrackIndex == tractor.count() - 1 + && mltClipIndex == playlist.count() - 1; + MAIN.undoStack()->push(new Timeline::InsertCommand(m_model, + m_markersModel, + trackIndex, + position + info.start, + MLT.XML(&clip), + lastClip)); } } } @@ -3317,8 +3455,12 @@ void TimelineDock::insert(int trackIndex, int position, const QString &xml, bool position = 0; addVideoTrack(); } - MAIN.undoStack()->push( - new Timeline::InsertCommand(m_model, m_markersModel, trackIndex, position, xmlToUse, seek)); + MAIN.undoStack()->push(new Timeline::InsertCommand(m_model, + m_markersModel, + trackIndex, + position, + xmlToUse, + seek)); } if (m_position < 0) { // This happens when pasting in a new session @@ -3360,7 +3502,8 @@ void TimelineDock::overwrite(int trackIndex, int position, const QString &xml, b emit warnTrackLocked(trackIndex); return; } - if (xml.contains(MAIN.fileName()) && MAIN.isSourceClipMyProject()) return; + if (xml.contains(MAIN.fileName()) && MAIN.isSourceClipMyProject()) + return; // Use MLT XML on the clipboard if it exists and is newer than source clip. QString xmlToUse = QGuiApplication::clipboard()->text(); @@ -3391,7 +3534,7 @@ void TimelineDock::overwrite(int trackIndex, int position, const QString &xml, b // No need to create a track in an empty timeline. // This can be a macro of QUndoCommands. if (producer.is_valid() && producer.type() == mlt_service_tractor_type - && producer.get_int(kShotcutXmlProperty)) { + && producer.get_int(kShotcutXmlProperty)) { Mlt::Tractor tractor(producer); Mlt::ClipInfo info; MAIN.undoStack()->beginMacro(tr("Overwrite multiple onto timeline")); @@ -3411,9 +3554,14 @@ void TimelineDock::overwrite(int trackIndex, int position, const QString &xml, b playlist.clip_info(mltClipIndex, &info); Mlt::Producer clip(info.producer); clip.set_in_and_out(info.frame_in, info.frame_out); - bool lastClip = mltTrackIndex == tractor.count() - 1 && mltClipIndex == playlist.count() - 1; + bool lastClip = mltTrackIndex == tractor.count() - 1 + && mltClipIndex == playlist.count() - 1; MAIN.undoStack()->push( - new Timeline::OverwriteCommand(m_model, trackIndex, position + info.start, MLT.XML(&clip), false)); + new Timeline::OverwriteCommand(m_model, + trackIndex, + position + info.start, + MLT.XML(&clip), + false)); } } } @@ -3473,7 +3621,10 @@ void TimelineDock::appendFromPlaylist(Mlt::Playlist *playlist, bool skipProxy, b Settings.setTimelineAutoAddTracks(false); MAIN.undoStack()->push( new Timeline::AppendCommand(m_model, trackIndex, MLT.XML(playlist), skipProxy)); - connect(&m_model, &MultitrackModel::appended, this, &TimelineDock::selectClip, + connect(&m_model, + &MultitrackModel::appended, + this, + &TimelineDock::selectClip, Qt::QueuedConnection); Settings.setTimelineAutoAddTracks(autoAddTracks); m_model.checkForEmptyTracks(trackIndex); @@ -3485,10 +3636,10 @@ void TimelineDock::fadeIn(int trackIndex, int clipIndex, int duration) emit warnTrackLocked(trackIndex); return; } - if (duration < 0) return; + if (duration < 0) + return; Q_ASSERT(trackIndex >= 0 && clipIndex >= 0); - MAIN.undoStack()->push( - new Timeline::FadeInCommand(m_model, trackIndex, clipIndex, duration)); + MAIN.undoStack()->push(new Timeline::FadeInCommand(m_model, trackIndex, clipIndex, duration)); emit fadeInChanged(duration); } @@ -3498,17 +3649,19 @@ void TimelineDock::fadeOut(int trackIndex, int clipIndex, int duration) emit warnTrackLocked(trackIndex); return; } - if (duration < 0) return; + if (duration < 0) + return; Q_ASSERT(trackIndex >= 0 && clipIndex >= 0); - MAIN.undoStack()->push( - new Timeline::FadeOutCommand(m_model, trackIndex, clipIndex, duration)); + MAIN.undoStack()->push(new Timeline::FadeOutCommand(m_model, trackIndex, clipIndex, duration)); emit fadeOutChanged(duration); } void TimelineDock::seekPreviousEdit() { - if (!MLT.isMultitrack()) return; - if (!m_model.tractor()) return; + if (!MLT.isMultitrack()) + return; + if (!m_model.tractor()) + return; int newPosition = -1; int n = m_model.tractor()->count(); @@ -3529,8 +3682,10 @@ void TimelineDock::seekPreviousEdit() void TimelineDock::seekNextEdit() { - if (!MLT.isMultitrack()) return; - if (!m_model.tractor()) return; + if (!MLT.isMultitrack()) + return; + if (!m_model.tractor()) + return; int newPosition = std::numeric_limits::max(); int n = m_model.tractor()->count(); @@ -3542,7 +3697,8 @@ void TimelineDock::seekNextEdit() if (clipIndex < playlist.count()) newPosition = qMin(newPosition, playlist.clip_start(clipIndex)); else if (clipIndex == playlist.count()) - newPosition = qMin(newPosition, playlist.clip_start(clipIndex) + playlist.clip_length(clipIndex)); + newPosition = qMin(newPosition, + playlist.clip_start(clipIndex) + playlist.clip_length(clipIndex)); } } if (newPosition != m_position) @@ -3551,9 +3707,12 @@ void TimelineDock::seekNextEdit() void TimelineDock::seekInPoint(int clipIndex) { - if (!MLT.isMultitrack()) return; - if (!m_model.tractor()) return; - if (clipIndex < 0) return; + if (!MLT.isMultitrack()) + return; + if (!m_model.tractor()) + return; + if (clipIndex < 0) + return; int mltTrackIndex = m_model.trackList().at(currentTrack()).mlt_index; QScopedPointer track(m_model.tractor()->track(mltTrackIndex)); @@ -3646,8 +3805,8 @@ void TimelineDock::onTopLevelChanged(bool floating) void TimelineDock::onTransitionAdded(int trackIndex, int clipIndex, int position, bool ripple) { setSelection(); // cleared - Timeline::AddTransitionCommand *command = new Timeline::AddTransitionCommand(*this, trackIndex, - clipIndex, position, ripple); + Timeline::AddTransitionCommand *command + = new Timeline::AddTransitionCommand(*this, trackIndex, clipIndex, position, ripple); MAIN.undoStack()->push(command); // Select the transition. setSelection(QList() << QPoint(command->getTransitionIndex(), trackIndex)); @@ -3687,85 +3846,31 @@ class FindProducersByHashParser : public Mlt::Parser , m_hash(hash) {} - QList &producers() - { - return m_producers; - } + QList &producers() { return m_producers; } - int on_start_filter(Mlt::Filter *) - { - return 0; - } + int on_start_filter(Mlt::Filter *) { return 0; } int on_start_producer(Mlt::Producer *producer) { if (producer->is_cut() && Util::getHash(producer->parent()) == m_hash) m_producers << Mlt::Producer(producer); return 0; } - int on_end_producer(Mlt::Producer *) - { - return 0; - } - int on_start_playlist(Mlt::Playlist *) - { - return 0; - } - int on_end_playlist(Mlt::Playlist *) - { - return 0; - } - int on_start_tractor(Mlt::Tractor *) - { - return 0; - } - int on_end_tractor(Mlt::Tractor *) - { - return 0; - } - int on_start_multitrack(Mlt::Multitrack *) - { - return 0; - } - int on_end_multitrack(Mlt::Multitrack *) - { - return 0; - } - int on_start_track() - { - return 0; - } - int on_end_track() - { - return 0; - } - int on_end_filter(Mlt::Filter *) - { - return 0; - } - int on_start_transition(Mlt::Transition *) - { - return 0; - } - int on_end_transition(Mlt::Transition *) - { - return 0; - } - int on_start_chain(Mlt::Chain *) - { - return 0; - } - int on_end_chain(Mlt::Chain *) - { - return 0; - } - int on_start_link(Mlt::Link *) - { - return 0; - } - int on_end_link(Mlt::Link *) - { - return 0; - } + int on_end_producer(Mlt::Producer *) { return 0; } + int on_start_playlist(Mlt::Playlist *) { return 0; } + int on_end_playlist(Mlt::Playlist *) { return 0; } + int on_start_tractor(Mlt::Tractor *) { return 0; } + int on_end_tractor(Mlt::Tractor *) { return 0; } + int on_start_multitrack(Mlt::Multitrack *) { return 0; } + int on_end_multitrack(Mlt::Multitrack *) { return 0; } + int on_start_track() { return 0; } + int on_end_track() { return 0; } + int on_end_filter(Mlt::Filter *) { return 0; } + int on_start_transition(Mlt::Transition *) { return 0; } + int on_end_transition(Mlt::Transition *) { return 0; } + int on_start_chain(Mlt::Chain *) { return 0; } + int on_end_chain(Mlt::Chain *) { return 0; } + int on_start_link(Mlt::Link *) { return 0; } + int on_end_link(Mlt::Link *) { return 0; } }; void TimelineDock::replaceClipsWithHash(const QString &hash, Mlt::Producer &producer) @@ -3779,17 +3884,19 @@ void TimelineDock::replaceClipsWithHash(const QString &hash, Mlt::Producer &prod int trackIndex = -1; int clipIndex = -1; // lookup the current track and clip index by UUID - auto info = m_model.findClipByUuid(QUuid::fromString(clip.parent().get(kUuidProperty)), trackIndex, + auto info = m_model.findClipByUuid(QUuid::fromString(clip.parent().get(kUuidProperty)), + trackIndex, clipIndex); if (info && info->producer->is_valid() && trackIndex >= 0 && clipIndex >= 0 - && info->producer->type() != mlt_service_tractor_type) { + && info->producer->type() != mlt_service_tractor_type) { if (producer.get_int(kIsProxyProperty) && info->producer->get_int(kIsProxyProperty)) { // Not much to do on a proxy clip but change its resource info->producer->set(kOriginalResourceProperty, producer.get("resource")); auto caption = Util::baseName(ProxyManager::resource(*info->producer), true); if (!::qstrcmp(info->producer->get("mlt_service"), "timewarp")) { - caption = QStringLiteral("%1 (%2x)").arg(caption, info->producer->get("warp_speed")); + caption + = QStringLiteral("%1 (%2x)").arg(caption, info->producer->get("warp_speed")); } info->producer->set(kShotcutCaptionProperty, caption.toUtf8().constData()); } else { @@ -3799,13 +3906,13 @@ void TimelineDock::replaceClipsWithHash(const QString &hash, Mlt::Producer &prod // Factor in a transition left of the clip. auto info2 = m_model.getClipInfo(trackIndex, clipIndex - 1); if (info2 && info2->producer && info2->producer->is_valid() - && info2->producer->get(kShotcutTransitionProperty)) { + && info2->producer->get(kShotcutTransitionProperty)) { in -= info2->frame_count; } // Factor in a transition right of the clip. info2 = m_model.getClipInfo(trackIndex, clipIndex + 1); if (info2 && info2->producer && info2->producer->is_valid() - && info2->producer->get(kShotcutTransitionProperty)) { + && info2->producer->get(kShotcutTransitionProperty)) { out += info2->frame_count; } Util::applyCustomProperties(producer, *info->producer, in, out); @@ -3827,8 +3934,12 @@ void TimelineDock::recordAudio() path.append("/%1.opus"); path = path.arg(tr("voiceover")); auto nameFilter = tr("Opus (*.opus);;All Files (*)"); - filename = QFileDialog::getSaveFileName(this, tr("Record Audio"), path, nameFilter, - nullptr, Util::getFileDialogOptions()); + filename = QFileDialog::getSaveFileName(this, + tr("Record Audio"), + path, + nameFilter, + nullptr, + Util::getFileDialogOptions()); } if (filename.isEmpty()) { return; @@ -3855,18 +3966,21 @@ void TimelineDock::recordAudio() // Start ffmpeg background job. auto priority = QThread::HighPriority; #if defined(Q_OS_MAC) - QStringList args {"-f", "avfoundation", "-i", "none:" + Settings.audioInput()}; + QStringList args{"-f", "avfoundation", "-i", "none:" + Settings.audioInput()}; priority = QThread::NormalPriority; #elif defined(Q_OS_WIN) - QStringList args {"-f", "dshow", "-i", "audio=" + Settings.audioInput()}; + QStringList args{"-f", "dshow", "-i", "audio=" + Settings.audioInput()}; #else - QStringList args {"-f", "pulse", "-name", "Shotcut", "-i", Settings.audioInput()}; + QStringList args{"-f", "pulse", "-name", "Shotcut", "-i", Settings.audioInput()}; #endif - args << "-flush_packets" << "1" << "-y" << filename; + args << "-flush_packets" + << "1" + << "-y" << filename; m_recordJob.reset(new FfmpegJob("vo", args, false, priority)); m_recordJob->setTarget(filename); connect(m_recordJob.get(), SIGNAL(started()), SLOT(onRecordStarted())); - connect(m_recordJob.get(), SIGNAL(finished(AbstractJob *, bool)), + connect(m_recordJob.get(), + SIGNAL(finished(AbstractJob *, bool)), SLOT(onRecordFinished(AbstractJob *, bool))); m_recordJob->start(); m_isRecording = true; @@ -3909,7 +4023,8 @@ void TimelineDock::onRecordFinished(AbstractJob *, bool success) #if defined(Q_OS_UNIX) && !defined(Q_OS_MAC) emit showStatusMessage(tr("Record Audio error: check PulseAudio settings")); #else - emit showStatusMessage(tr("Record Audio error: choose File > Open Other > Audio/Video Device")); + emit showStatusMessage( + tr("Record Audio error: choose File > Open Other > Audio/Video Device")); #endif } } diff --git a/src/docks/timelinedock.h b/src/docks/timelinedock.h index bae6ff8eb8..4670ba65e8 100644 --- a/src/docks/timelinedock.h +++ b/src/docks/timelinedock.h @@ -18,22 +18,23 @@ #ifndef TIMELINEDOCK_H #define TIMELINEDOCK_H -#include -#include -#include -#include -#include +#include "jobs/ffmpegjob.h" #include "models/markersmodel.h" #include "models/multitrackmodel.h" #include "models/subtitlesmodel.h" #include "models/subtitlesselectionmodel.h" #include "sharedframe.h" -#include "jobs/ffmpegjob.h" + +#include +#include +#include +#include +#include namespace Timeline { class UpdateCommand; class TrimCommand; -} +} // namespace Timeline class UndoHelper; class QMenu; @@ -42,8 +43,8 @@ class TimelineDock : public QDockWidget Q_OBJECT Q_PROPERTY(int position READ position WRITE setPosition NOTIFY positionChanged) Q_PROPERTY(int currentTrack READ currentTrack WRITE setCurrentTrack NOTIFY currentTrackChanged) - Q_PROPERTY(QVariantList selection READ selectionForJS WRITE setSelectionFromJS NOTIFY - selectionChanged) + Q_PROPERTY( + QVariantList selection READ selectionForJS WRITE setSelectionFromJS NOTIFY selectionChanged) Q_PROPERTY(bool isRecording READ isRecording NOTIFY isRecordingChanged) Q_PROPERTY(int loopStart READ loopStart NOTIFY loopChanged) Q_PROPERTY(int loopEnd READ loopEnd NOTIFY loopChanged) @@ -52,31 +53,13 @@ class TimelineDock : public QDockWidget explicit TimelineDock(QWidget *parent = 0); ~TimelineDock(); - enum TrimLocation { - TrimInPoint, - TrimOutPoint - }; + enum TrimLocation { TrimInPoint, TrimOutPoint }; - MultitrackModel *model() - { - return &m_model; - } - MarkersModel *markersModel() - { - return & m_markersModel; - } - SubtitlesModel *subtitlesModel() - { - return & m_subtitlesModel; - } - SubtitlesSelectionModel *subtitlesSelectionModel() - { - return & m_subtitlesSelectionModel; - } - int position() const - { - return m_position; - } + MultitrackModel *model() { return &m_model; } + MarkersModel *markersModel() { return &m_markersModel; } + SubtitlesModel *subtitlesModel() { return &m_subtitlesModel; } + SubtitlesSelectionModel *subtitlesSelectionModel() { return &m_subtitlesSelectionModel; } + int position() const { return m_position; } void setPosition(int position); Mlt::Producer producerForClip(int trackIndex, int clipIndex); int clipIndexAtPlayhead(int trackIndex = -1); @@ -86,7 +69,8 @@ class TimelineDock : public QDockWidget int currentTrack() const; int clipCount(int trackIndex) const; void setSelectionFromJS(const QVariantList &list); - void setSelection(QList selection = QList(), int trackIndex = -1, + void setSelection(QList selection = QList(), + int trackIndex = -1, bool isMultitrack = false); QVariantList selectionForJS() const; const QList selection() const; @@ -99,37 +83,19 @@ class TimelineDock : public QDockWidget int centerOfClip(int trackIndex, int clipIndex); bool isTrackLocked(int trackIndex) const; void trimClipAtPlayhead(TrimLocation location, bool ripple); - Q_INVOKABLE bool isMultitrackSelected() const - { - return m_selection.isMultitrackSelected; - } - Q_INVOKABLE int selectedTrack() const - { - return m_selection.selectedTrack; - } - Q_INVOKABLE bool isFloating() const - { - return QDockWidget::isFloating(); - } + Q_INVOKABLE bool isMultitrackSelected() const { return m_selection.isMultitrackSelected; } + Q_INVOKABLE int selectedTrack() const { return m_selection.selectedTrack; } + Q_INVOKABLE bool isFloating() const { return QDockWidget::isFloating(); } Q_INVOKABLE static void openProperties(); void emitSelectedChanged(const QVector &roles); void replaceClipsWithHash(const QString &hash, Mlt::Producer &producer); Q_INVOKABLE void recordAudio(); Q_INVOKABLE void stopRecording(); - bool isRecording() const - { - return m_isRecording; - } + bool isRecording() const { return m_isRecording; } int addTrackIfNeeded(TrackType trackType); void getSelectionRange(int *start, int *end); - int loopStart() const - { - return m_loopStart; - } - int loopEnd() const - { - return m_loopEnd; - } + int loopStart() const { return m_loopStart; } + int loopEnd() const { return m_loopEnd; } signals: void currentTrackChanged(); @@ -189,7 +155,10 @@ public slots: bool trimClipIn(int trackIndex, int clipIndex, int oldClipIndex, int delta, bool ripple); bool trimClipOut(int trackIndex, int clipIndex, int delta, bool ripple); void insert(int trackIndex, int position = -1, const QString &xml = QString(), bool seek = true); - void overwrite(int trackIndex, int position = -1, const QString &xml = QString(), bool seek = true); + void overwrite(int trackIndex, + int position = -1, + const QString &xml = QString(), + bool seek = true); void appendFromPlaylist(Mlt::Playlist *playlist, bool skipProxy, bool emptyTrack); void fadeIn(int trackIndex, int clipIndex = -1, int duration = -1); void fadeOut(int trackIndex, int clipIndex = -1, int duration = -1); @@ -210,8 +179,8 @@ public slots: void commitTrimCommand(); void onRowsInserted(const QModelIndex &parent, int first, int last); void onRowsRemoved(const QModelIndex &parent, int first, int last); - void onRowsMoved(const QModelIndex &parent, int start, int end, const QModelIndex &destination, - int row); + void onRowsMoved( + const QModelIndex &parent, int start, int end, const QModelIndex &destination, int row); void detachAudio(int trackIndex, int clipIndex); void selectAll(); void selectAllOnCurrentTrack(); @@ -249,10 +218,7 @@ public slots: void emitNonSeekableWarning(); void addTrackIfNeeded(int mltTrackIndex, Mlt::Producer *srcTrack); void setupActions(); - bool isMultitrackValid() - { - return m_model.tractor() && !m_model.trackList().empty(); - } + bool isMultitrackValid() { return m_model.tractor() && !m_model.trackList().empty(); } void reportSelectionChange(); void applyCopiedFiltersToSelectdClips(); void insertOrOverwriteDrop(int trackIndex, int position, const QString &xml); @@ -265,31 +231,32 @@ public slots: int m_position; std::unique_ptr m_updateCommand; bool m_ignoreNextPositionChange; - struct Selection { + struct Selection + { QList selectedClips; // x is the clip index, y is the track index int selectedTrack; bool isMultitrackSelected; }; Selection m_selection; - int m_savedSelectedTrack {-1}; - bool m_savedIsMultitrackSelected {false}; + int m_savedSelectedTrack{-1}; + bool m_savedIsMultitrackSelected{false}; QVector m_savedSelectionUuids; QTimer m_selectionSignalTimer; std::unique_ptr m_trimCommand; std::unique_ptr m_undoHelper; int m_trimDelta; int m_transitionDelta; - bool m_isRecording {false}; + bool m_isRecording{false}; std::unique_ptr m_recordJob; QTimer m_recordingTimer; QDateTime m_recordingTime; - int m_recordingTrackIndex {-1}; - int m_recordingClipIndex {-1}; - int m_currentTrack {0}; - QMenu *m_mainMenu {nullptr}; - QMenu *m_clipMenu {nullptr}; - int m_loopStart {-1}; - int m_loopEnd {-1}; + int m_recordingTrackIndex{-1}; + int m_recordingClipIndex{-1}; + int m_currentTrack{0}; + QMenu *m_mainMenu{nullptr}; + QMenu *m_clipMenu{nullptr}; + int m_loopStart{-1}; + int m_loopEnd{-1}; private slots: void load(bool force); diff --git a/src/jobqueue.cpp b/src/jobqueue.cpp index 5331efb350..e2bca10207 100644 --- a/src/jobqueue.cpp +++ b/src/jobqueue.cpp @@ -16,17 +16,18 @@ */ #include "jobqueue.h" + +#include "Logger.h" + #include -#include #if defined(Q_OS_WIN) && (QT_VERSION < QT_VERSION_CHECK(6, 0, 0)) #include "windowstools.h" #endif -JobQueue::JobQueue(QObject *parent) : - QStandardItemModel(0, COLUMN_COUNT, parent), - m_paused(false) -{ -} +JobQueue::JobQueue(QObject *parent) + : QStandardItemModel(0, COLUMN_COUNT, parent) + , m_paused(false) +{} JobQueue &JobQueue::singleton(QObject *parent) { @@ -64,10 +65,12 @@ AbstractJob *JobQueue::add(AbstractJob *job) appendRow(items); job->setParent(this); job->setStandardItem(item); - connect(job, SIGNAL(progressUpdated(QStandardItem *, int)), SLOT(onProgressUpdated(QStandardItem *, - int))); - connect(job, SIGNAL(finished(AbstractJob *, bool, QString)), SLOT(onFinished(AbstractJob *, bool, - QString))); + connect(job, + SIGNAL(progressUpdated(QStandardItem *, int)), + SLOT(onProgressUpdated(QStandardItem *, int))); + connect(job, + SIGNAL(finished(AbstractJob *, bool, QString)), + SLOT(onFinished(AbstractJob *, bool, QString))); m_mutex.lock(); m_jobs.append(job); m_mutex.unlock(); @@ -143,7 +146,8 @@ void JobQueue::onFinished(AbstractJob *job, bool isSuccess, QString time) void JobQueue::startNextJob() { - if (m_paused) return; + if (m_paused) + return; QMutexLocker locker(&m_mutex); if (!m_jobs.isEmpty()) { foreach (AbstractJob *job, m_jobs) { diff --git a/src/jobqueue.h b/src/jobqueue.h index fcbe0bd96b..ab36a7acc0 100644 --- a/src/jobqueue.h +++ b/src/jobqueue.h @@ -19,8 +19,9 @@ #define JOBQUEUE_H #include "jobs/abstractjob.h" -#include + #include +#include class JobQueue : public QStandardItemModel { @@ -30,12 +31,7 @@ class JobQueue : public QStandardItemModel void startNextJob(); public: - enum ColumnRole { - COLUMN_ICON, - COLUMN_OUTPUT, - COLUMN_STATUS, - COLUMN_COUNT - }; + enum ColumnRole { COLUMN_ICON, COLUMN_OUTPUT, COLUMN_STATUS, COLUMN_COUNT }; static JobQueue &singleton(QObject *parent = 0); void cleanup(); @@ -49,10 +45,7 @@ class JobQueue : public QStandardItemModel bool hasIncomplete() const; void remove(const QModelIndex &index); void removeFinished(); - QList jobs() const - { - return m_jobs; - } + QList jobs() const { return m_jobs; } bool targetIsInProgress(const QString &target); signals: diff --git a/src/jobs/abstractjob.cpp b/src/jobs/abstractjob.cpp index 32bdfc479c..01969c3ff6 100644 --- a/src/jobs/abstractjob.cpp +++ b/src/jobs/abstractjob.cpp @@ -16,12 +16,14 @@ */ #include "abstractjob.h" + +#include "Logger.h" #include "postjobaction.h" +#include #include #include -#include -#include + #ifdef Q_OS_WIN #include #else @@ -39,12 +41,15 @@ AbstractJob::AbstractJob(const QString &name, QThread::Priority priority) , m_isPaused(false) { setObjectName(name); - connect(this, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(onFinished(int, - QProcess::ExitStatus))); + connect(this, + SIGNAL(finished(int, QProcess::ExitStatus)), + this, + SLOT(onFinished(int, QProcess::ExitStatus))); connect(this, SIGNAL(readyRead()), this, SLOT(onReadyRead())); connect(this, SIGNAL(started()), this, SLOT(onStarted())); - connect(this, SIGNAL(progressUpdated(QStandardItem *, int)), SLOT(onProgressUpdated(QStandardItem *, - int))); + connect(this, + SIGNAL(progressUpdated(QStandardItem *, int)), + SLOT(onProgressUpdated(QStandardItem *, int))); m_actionPause = new QAction(tr("Pause This Job"), this); m_standardActions << m_actionPause; m_actionPause->setEnabled(false); diff --git a/src/jobs/abstractjob.h b/src/jobs/abstractjob.h index 33cfdacbf7..5cb45001f6 100644 --- a/src/jobs/abstractjob.h +++ b/src/jobs/abstractjob.h @@ -21,10 +21,10 @@ #include "postjobaction.h" #include "settings.h" -#include -#include -#include #include +#include +#include +#include #include class QAction; @@ -47,24 +47,12 @@ class AbstractJob : public QProcess } void appendToLog(const QString &); QString log() const; - QString label() const - { - return m_label; - } + QString label() const { return m_label; } void setLabel(const QString &label); - QList standardActions() const - { - return m_standardActions; - } - QList successActions() const - { - return m_successActions; - } + QList standardActions() const { return m_standardActions; } + QList successActions() const { return m_successActions; } QTime estimateRemaining(int percent); - QElapsedTimer time() const - { - return m_totalTime; - } + QElapsedTimer time() const { return m_totalTime; } void setPostJobAction(PostJobAction *action); bool paused() const; void setTarget(const QString & target) @@ -90,7 +78,7 @@ public slots: protected: QList m_standardActions; QList m_successActions; - QStandardItem *m_item; + QStandardItem *m_item; protected slots: virtual void onFinished(int exitCode, QProcess::ExitStatus exitStatus = QProcess::NormalExit); diff --git a/src/jobs/bitrateviewerjob.cpp b/src/jobs/bitrateviewerjob.cpp index 7410a2fde8..157744b0f7 100644 --- a/src/jobs/bitrateviewerjob.cpp +++ b/src/jobs/bitrateviewerjob.cpp @@ -1,69 +1,66 @@ -/* - * Copyright (c) 2023 Meltytech, LLC - * - * 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 3 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, see . - */ - -#include "bitrateviewerjob.h" -#include "dialogs/bitratedialog.h" -#include "mainwindow.h" -#include "util.h" -#include "Logger.h" - -#include -#include -#include -#include - -BitrateViewerJob::BitrateViewerJob(const QString &name, const QStringList &args, double fps) - : FfprobeJob(name, args) - , m_resource(args.last()) - , m_fps(fps) -{ - QAction *action = new QAction(tr("Open"), this); - action->setData("Open"); - connect(action, &QAction::triggered, this, &BitrateViewerJob::onOpenTriggered); - m_successActions << action; -} - -BitrateViewerJob::~BitrateViewerJob() -{ - -} - -void BitrateViewerJob::onFinished(int exitCode, ExitStatus exitStatus) -{ - AbstractJob::onFinished(exitCode, exitStatus); - if (exitStatus == QProcess::NormalExit && exitCode == 0) { - QJsonParseError error; - auto s = log(); - s = s.left(s.lastIndexOf('}') + 1); - auto doc = QJsonDocument::fromJson(s.toUtf8(), &error); - if (QJsonParseError::NoError == error.error && doc.isObject()) { - auto v = doc.object().value("packets"); - if (v.isArray()) { - m_data = v.toArray(); - onOpenTriggered(); - } - } else { - LOG_ERROR() << "JSON parsing error:" << error.errorString(); - } - } -} - -void BitrateViewerJob::onOpenTriggered() -{ - BitrateDialog dialog(Util::baseName(m_resource), m_fps, m_data, &MAIN); - dialog.exec(); -} +/* + * Copyright (c) 2023 Meltytech, LLC + * + * 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 3 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, see . + */ + +#include "bitrateviewerjob.h" + +#include "Logger.h" +#include "dialogs/bitratedialog.h" +#include "mainwindow.h" +#include "util.h" + +#include +#include +#include + +BitrateViewerJob::BitrateViewerJob(const QString &name, const QStringList &args, double fps) + : FfprobeJob(name, args) + , m_resource(args.last()) + , m_fps(fps) +{ + QAction *action = new QAction(tr("Open"), this); + action->setData("Open"); + connect(action, &QAction::triggered, this, &BitrateViewerJob::onOpenTriggered); + m_successActions << action; +} + +BitrateViewerJob::~BitrateViewerJob() {} + +void BitrateViewerJob::onFinished(int exitCode, ExitStatus exitStatus) +{ + AbstractJob::onFinished(exitCode, exitStatus); + if (exitStatus == QProcess::NormalExit && exitCode == 0) { + QJsonParseError error; + auto s = log(); + s = s.left(s.lastIndexOf('}') + 1); + auto doc = QJsonDocument::fromJson(s.toUtf8(), &error); + if (QJsonParseError::NoError == error.error && doc.isObject()) { + auto v = doc.object().value("packets"); + if (v.isArray()) { + m_data = v.toArray(); + onOpenTriggered(); + } + } else { + LOG_ERROR() << "JSON parsing error:" << error.errorString(); + } + } +} + +void BitrateViewerJob::onOpenTriggered() +{ + BitrateDialog dialog(Util::baseName(m_resource), m_fps, m_data, &MAIN); + dialog.exec(); +} diff --git a/src/jobs/bitrateviewerjob.h b/src/jobs/bitrateviewerjob.h index b624115ad0..a21c72719f 100644 --- a/src/jobs/bitrateviewerjob.h +++ b/src/jobs/bitrateviewerjob.h @@ -1,41 +1,42 @@ -/* - * Copyright (c) 2023 Meltytech, LLC - * - * 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 3 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, see . - */ - -#ifndef BITRATEVIEWERJOB_H -#define BITRATEVIEWERJOB_H - -#include "ffprobejob.h" -#include - -class BitrateViewerJob : public FfprobeJob -{ - Q_OBJECT -public: - BitrateViewerJob(const QString &name, const QStringList &args, double fps); - virtual ~BitrateViewerJob(); - -private slots: - virtual void onFinished(int exitCode, QProcess::ExitStatus exitStatus); - void onOpenTriggered(); - -private: - QString m_resource; - double m_fps {0.0}; - QJsonArray m_data; -}; - -#endif // BITRATEVIEWERJOB_H +/* + * Copyright (c) 2023 Meltytech, LLC + * + * 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 3 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, see . + */ + +#ifndef BITRATEVIEWERJOB_H +#define BITRATEVIEWERJOB_H + +#include "ffprobejob.h" + +#include + +class BitrateViewerJob : public FfprobeJob +{ + Q_OBJECT +public: + BitrateViewerJob(const QString &name, const QStringList &args, double fps); + virtual ~BitrateViewerJob(); + +private slots: + virtual void onFinished(int exitCode, QProcess::ExitStatus exitStatus); + void onOpenTriggered(); + +private: + QString m_resource; + double m_fps{0.0}; + QJsonArray m_data; +}; + +#endif // BITRATEVIEWERJOB_H diff --git a/src/jobs/encodejob.cpp b/src/jobs/encodejob.cpp index df53f18041..0f16772384 100644 --- a/src/jobs/encodejob.cpp +++ b/src/jobs/encodejob.cpp @@ -16,25 +16,30 @@ */ #include "encodejob.h" + +#include "jobqueue.h" +#include "jobs/videoqualityjob.h" +#include "mainwindow.h" +#include "settings.h" +#include "spatialmedia/spatialmedia.h" +#include "util.h" + #include -#include #include -#include -#include -#include #include #include +#include +#include +#include #include -#include "mainwindow.h" -#include "settings.h" -#include "jobqueue.h" -#include "jobs/videoqualityjob.h" -#include "util.h" -#include "spatialmedia/spatialmedia.h" +#include -#include +#include "Logger.h" -EncodeJob::EncodeJob(const QString &name, const QString &xml, int frameRateNum, int frameRateDen, +EncodeJob::EncodeJob(const QString &name, + const QString &xml, + int frameRateNum, + int frameRateDen, QThread::Priority priority) : MeltJob(name, xml, frameRateNum, frameRateDen, priority) { @@ -69,8 +74,12 @@ void EncodeJob::onVideoQualityTriggered() QString directory = Settings.encodePath(); QString caption = tr("Video Quality Report"); QString nameFilter = tr("Text Documents (*.txt);;All Files (*)"); - QString reportPath = QFileDialog::getSaveFileName(&MAIN, caption, directory, nameFilter, - nullptr, Util::getFileDialogOptions()); + QString reportPath = QFileDialog::getSaveFileName(&MAIN, + caption, + directory, + nameFilter, + nullptr, + Util::getFileDialogOptions()); if (!reportPath.isEmpty()) { QFileInfo fi(reportPath); if (fi.suffix().isEmpty()) @@ -114,8 +123,11 @@ void EncodeJob::onVideoQualityTriggered() consumerNode.setAttribute("terminate_on_pause", 1); // Create job and add it to the queue. - JOBS.add(new VideoQualityJob(objectName(), dom.toString(2), reportPath, - MLT.profile().frame_rate_num(), MLT.profile().frame_rate_den())); + JOBS.add(new VideoQualityJob(objectName(), + dom.toString(2), + reportPath, + MLT.profile().frame_rate_num(), + MLT.profile().frame_rate_den())); } } } @@ -126,11 +138,15 @@ void EncodeJob::onSpatialMediaTriggered() QString caption = tr("Set Equirectangular Projection"); QFileInfo info(objectName()); QString directory = QStringLiteral("%1/%2 - ERP.%3") - .arg(Settings.encodePath()) - .arg(info.completeBaseName()) - .arg(info.suffix()); - QString filePath = QFileDialog::getSaveFileName(&MAIN, caption, directory, QString(), - nullptr, Util::getFileDialogOptions()); + .arg(Settings.encodePath()) + .arg(info.completeBaseName()) + .arg(info.suffix()); + QString filePath = QFileDialog::getSaveFileName(&MAIN, + caption, + directory, + QString(), + nullptr, + Util::getFileDialogOptions()); if (!filePath.isEmpty()) { if (SpatialMedia::injectSpherical(objectName().toStdString(), filePath.toStdString())) { MAIN.showStatusMessage(tr("Successfully wrote %1").arg(QFileInfo(filePath).fileName())); @@ -154,7 +170,7 @@ void EncodeJob::onFinished(int exitCode, QProcess::ExitStatus exitStatus) // Locate the consumer element. QDomNodeList consumers = dom.elementsByTagName("consumer"); - for (int i = 0; i < consumers.length(); i++ ) { + for (int i = 0; i < consumers.length(); i++) { QDomElement consumer = consumers.at(i).toElement(); // If real_time is set for parallel. if (consumer.attribute("real_time").toInt() < -1) { diff --git a/src/jobs/encodejob.h b/src/jobs/encodejob.h index a29e593e37..96da3b1518 100644 --- a/src/jobs/encodejob.h +++ b/src/jobs/encodejob.h @@ -19,13 +19,17 @@ #define ENCODEJOB_H #include "meltjob.h" + #include class EncodeJob : public MeltJob { Q_OBJECT public: - EncodeJob(const QString &name, const QString &xml, int frameRateNum, int frameRateDen, + EncodeJob(const QString &name, + const QString &xml, + int frameRateNum, + int frameRateDen, const QThread::Priority priority); private slots: diff --git a/src/jobs/ffmpegjob.cpp b/src/jobs/ffmpegjob.cpp index fe390d3e5b..d3b9144ced 100644 --- a/src/jobs/ffmpegjob.cpp +++ b/src/jobs/ffmpegjob.cpp @@ -16,21 +16,24 @@ */ #include "ffmpegjob.h" -#include "mainwindow.h" + +#include "Logger.h" #include "dialogs/textviewerdialog.h" +#include "mainwindow.h" #include "util.h" -#include +#include #include #include -#include #include +#include #include -#include #include -FfmpegJob::FfmpegJob(const QString &name, const QStringList &args, bool isOpenLog, +FfmpegJob::FfmpegJob(const QString &name, + const QStringList &args, + bool isOpenLog, QThread::Priority priority) : AbstractJob(name, priority) , m_duration(0.0) @@ -64,9 +67,7 @@ void FfmpegJob::start() void FfmpegJob::stop() { write("q"); - QTimer::singleShot(3000, this, [this]() { - AbstractJob::stop(); - }); + QTimer::singleShot(3000, this, [this]() { AbstractJob::stop(); }); } void FfmpegJob::onOpenTriggered() diff --git a/src/jobs/ffmpegjob.h b/src/jobs/ffmpegjob.h index fe7d9d48b7..ae1b7e9985 100644 --- a/src/jobs/ffmpegjob.h +++ b/src/jobs/ffmpegjob.h @@ -19,13 +19,16 @@ #define FFMPEGJOB_H #include "abstractjob.h" + #include class FfmpegJob : public AbstractJob { Q_OBJECT public: - FfmpegJob(const QString &name, const QStringList &args, bool isOpenLog = true, + FfmpegJob(const QString &name, + const QStringList &args, + bool isOpenLog = true, QThread::Priority priority = Settings.jobPriority()); virtual ~FfmpegJob(); void start(); diff --git a/src/jobs/ffprobejob.cpp b/src/jobs/ffprobejob.cpp index 3de28025c6..1e5f94cb33 100644 --- a/src/jobs/ffprobejob.cpp +++ b/src/jobs/ffprobejob.cpp @@ -16,15 +16,16 @@ */ #include "ffprobejob.h" -#include "mainwindow.h" + +#include "Logger.h" #include "dialogs/textviewerdialog.h" +#include "mainwindow.h" #include "util.h" #include #include -#include #include -#include +#include FfprobeJob::FfprobeJob(const QString &name, const QStringList &args) : AbstractJob(name) @@ -32,17 +33,14 @@ FfprobeJob::FfprobeJob(const QString &name, const QStringList &args) m_args.append(args); } -FfprobeJob::~FfprobeJob() -{ - -} +FfprobeJob::~FfprobeJob() {} void FfprobeJob::start() { QString shotcutPath = qApp->applicationDirPath(); QFileInfo ffprobePath(shotcutPath, "ffprobe"); setReadChannel(QProcess::StandardOutput); - LOG_DEBUG() << ffprobePath.absoluteFilePath() + " " + m_args.join(' '); + LOG_DEBUG() << ffprobePath.absoluteFilePath() + " " + m_args.join(' '); AbstractJob::start(ffprobePath.absoluteFilePath(), m_args); } diff --git a/src/jobs/ffprobejob.h b/src/jobs/ffprobejob.h index 6e586f7884..baf7b8dd33 100644 --- a/src/jobs/ffprobejob.h +++ b/src/jobs/ffprobejob.h @@ -19,6 +19,7 @@ #define FFPROBEJOB_H #include "abstractjob.h" + #include class FfprobeJob : public AbstractJob diff --git a/src/jobs/gopro2gpxjob.cpp b/src/jobs/gopro2gpxjob.cpp index 52b048874f..973d724461 100644 --- a/src/jobs/gopro2gpxjob.cpp +++ b/src/jobs/gopro2gpxjob.cpp @@ -16,15 +16,16 @@ */ #include "gopro2gpxjob.h" -#include "mainwindow.h" + +#include "Logger.h" #include "dialogs/textviewerdialog.h" +#include "mainwindow.h" #include "util.h" #include #include -#include #include -#include +#include GoPro2GpxJob::GoPro2GpxJob(const QString &name, const QStringList &args) : AbstractJob(name) @@ -38,6 +39,6 @@ void GoPro2GpxJob::start() QString shotcutPath = qApp->applicationDirPath(); QFileInfo gopro2gpxPath(shotcutPath, "gopro2gpx"); setReadChannel(QProcess::StandardOutput); - LOG_DEBUG() << gopro2gpxPath.absoluteFilePath() + " " + m_args.join(' '); + LOG_DEBUG() << gopro2gpxPath.absoluteFilePath() + " " + m_args.join(' '); AbstractJob::start(gopro2gpxPath.absoluteFilePath(), m_args); } diff --git a/src/jobs/gopro2gpxjob.h b/src/jobs/gopro2gpxjob.h index 0d59146fc6..139ad16bf9 100644 --- a/src/jobs/gopro2gpxjob.h +++ b/src/jobs/gopro2gpxjob.h @@ -19,6 +19,7 @@ #define GOPRO2GPXJOB_H #include "abstractjob.h" + #include class GoPro2GpxJob : public AbstractJob @@ -26,7 +27,7 @@ class GoPro2GpxJob : public AbstractJob Q_OBJECT public: GoPro2GpxJob(const QString &name, const QStringList &args); - virtual ~GoPro2GpxJob() {}; + virtual ~GoPro2GpxJob(){}; void start(); private: diff --git a/src/jobs/meltjob.cpp b/src/jobs/meltjob.cpp index 78ba93fd70..7a1ba6f515 100644 --- a/src/jobs/meltjob.cpp +++ b/src/jobs/meltjob.cpp @@ -16,21 +16,25 @@ */ #include "meltjob.h" -#include -#include -#include -#include -#include + +#include "Logger.h" +#include "dialogs/textviewerdialog.h" +#include "mainwindow.h" +#include "util.h" + #include +#include #include #include +#include +#include +#include #include -#include -#include "mainwindow.h" -#include "dialogs/textviewerdialog.h" -#include "util.h" -MeltJob::MeltJob(const QString &name, const QString &xml, int frameRateNum, int frameRateDen, +MeltJob::MeltJob(const QString &name, + const QString &xml, + int frameRateNum, + int frameRateDen, QThread::Priority priority) : AbstractJob(name, priority) , m_isStreaming(false) @@ -85,7 +89,10 @@ void MeltJob::onShowInFilesTriggered() MAIN.showInFiles(objectName()); } -MeltJob::MeltJob(const QString &name, const QString &xml, const QStringList &args, int frameRateNum, +MeltJob::MeltJob(const QString &name, + const QString &xml, + const QStringList &args, + int frameRateNum, int frameRateDen) : MeltJob(name, xml, frameRateNum, frameRateDen) { @@ -109,9 +116,7 @@ void MeltJob::start() AbstractJob::start(); LOG_ERROR() << "the job XML is empty!"; appendToLog("Error: the job XML is empty!\n"); - QTimer::singleShot(0, this, [ = ]() { - emit finished(this, false); - }); + QTimer::singleShot(0, this, [=]() { emit finished(this, false); }); return; } QString shotcutPath = qApp->applicationDirPath(); @@ -141,7 +146,7 @@ void MeltJob::start() if (m_out > -1) { args << QStringLiteral("out=%1").arg(m_out); } - LOG_DEBUG() << meltPath.absoluteFilePath() + " " + args.join(' '); + LOG_DEBUG() << meltPath.absoluteFilePath() + " " + args.join(' '); #ifndef Q_OS_MAC QProcessEnvironment env = QProcessEnvironment::systemEnvironment(); // These environment variables fix rich text rendering for high DPI @@ -151,7 +156,8 @@ void MeltJob::start() setProcessEnvironment(env); #endif #ifdef Q_OS_WIN - if (m_isStreaming) args << "-getc"; + if (m_isStreaming) + args << "-getc"; #endif AbstractJob::start(meltPath.absoluteFilePath(), args); } diff --git a/src/jobs/meltjob.h b/src/jobs/meltjob.h index b45646c890..ee8270f6ce 100644 --- a/src/jobs/meltjob.h +++ b/src/jobs/meltjob.h @@ -19,24 +19,28 @@ #define MELTJOB_H #include "abstractjob.h" -#include + #include +#include class MeltJob : public AbstractJob { Q_OBJECT public: - MeltJob(const QString &name, const QString &xml, int frameRateNum, int frameRateDen, + MeltJob(const QString &name, + const QString &xml, + int frameRateNum, + int frameRateDen, QThread::Priority priority = Settings.jobPriority()); MeltJob(const QString &name, const QStringList &args, int frameRateNum, int frameRateDen); - MeltJob(const QString &name, const QString &xml, const QStringList &args, int frameRateNum, + MeltJob(const QString &name, + const QString &xml, + const QStringList &args, + int frameRateNum, int frameRateDen); virtual ~MeltJob(); QString xml(); - QString xmlPath() const - { - return m_xml->fileName(); - } + QString xmlPath() const { return m_xml->fileName(); } void setIsStreaming(bool streaming); void setUseMultiConsumer(bool multi = true); void setInAndOut(int in, int out); @@ -56,15 +60,14 @@ protected slots: QScopedPointer m_xml; private: - bool m_isStreaming; int m_previousPercent; QStringList m_args; int m_currentFrame; Mlt::Profile m_profile; bool m_useMultiConsumer; - int m_in {-1}; - int m_out {-1}; + int m_in{-1}; + int m_out{-1}; }; #endif // MELTJOB_H diff --git a/src/jobs/postjobaction.cpp b/src/jobs/postjobaction.cpp index f64943b88d..1397705557 100644 --- a/src/jobs/postjobaction.cpp +++ b/src/jobs/postjobaction.cpp @@ -16,17 +16,18 @@ */ #include "postjobaction.h" -#include "mainwindow.h" + +#include "Logger.h" #include "docks/playlistdock.h" #include "docks/subtitlesdock.h" +#include "mainwindow.h" #include "shotcut_mlt_properties.h" -#include + +#include // For file time functions in FilePropertiesPostJobAction::doAction(); -#include #include - -#include +#include void FilePropertiesPostJobAction::doAction() { @@ -119,7 +120,6 @@ void ProxyFinalizePostJobAction::doAction() } } - void ImportSrtPostJobAction::doAction() { m_dock->importSrtFromFile(m_srtFile, m_trackName, m_lang, m_includeNonspoken); diff --git a/src/jobs/postjobaction.h b/src/jobs/postjobaction.h index 2544dbe6c9..846c9458e0 100644 --- a/src/jobs/postjobaction.h +++ b/src/jobs/postjobaction.h @@ -46,7 +46,9 @@ class FilePropertiesPostJobAction : public PostJobAction class OpenPostJobAction : public FilePropertiesPostJobAction { public: - OpenPostJobAction(const QString &srcFile, const QString &dstFile, const QString &fileNameToRemove) + OpenPostJobAction(const QString &srcFile, + const QString &dstFile, + const QString &fileNameToRemove) : FilePropertiesPostJobAction(srcFile, dstFile) , m_fileNameToRemove(fileNameToRemove) {} @@ -59,8 +61,11 @@ class OpenPostJobAction : public FilePropertiesPostJobAction class ReplaceOnePostJobAction : public FilePropertiesPostJobAction { public: - ReplaceOnePostJobAction(const QString &srcFile, const QString &dstFile, - const QString &fileNameToRemove, const QUuid &srcUuid, int in) + ReplaceOnePostJobAction(const QString &srcFile, + const QString &dstFile, + const QString &fileNameToRemove, + const QUuid &srcUuid, + int in) : FilePropertiesPostJobAction(srcFile, dstFile) , m_fileNameToRemove(fileNameToRemove) , m_uuid(srcUuid) @@ -122,8 +127,11 @@ class SubtitlesDock; class ImportSrtPostJobAction : public PostJobAction { public: - ImportSrtPostJobAction(const QString &srtFile, const QString &trackName, const QString &lang, - bool includeNonspoken, SubtitlesDock *dock) + ImportSrtPostJobAction(const QString &srtFile, + const QString &trackName, + const QString &lang, + bool includeNonspoken, + SubtitlesDock *dock) : m_srtFile(srtFile) , m_trackName(trackName) , m_lang(lang) diff --git a/src/jobs/qimagejob.cpp b/src/jobs/qimagejob.cpp index cac7d9949c..68c0d7a75c 100644 --- a/src/jobs/qimagejob.cpp +++ b/src/jobs/qimagejob.cpp @@ -16,6 +16,7 @@ */ #include "qimagejob.h" + #include "util.h" #include @@ -43,7 +44,7 @@ QImageJob::~QImageJob() void QImageJob::start() { AbstractJob::start(); - auto result = QtConcurrent::run([ = ]() { + auto result = QtConcurrent::run([=]() { appendToLog(QStringLiteral("Reading source image \"%1\"\n").arg(m_srcFilePath)); QImageReader reader; reader.setAutoTransform(true); @@ -53,7 +54,8 @@ void QImageJob::start() if (!image.isNull()) { image = image.scaledToHeight(m_height, Qt::SmoothTransformation); if (image.save(m_destFilePath)) { - appendToLog(QStringLiteral("Successfully saved image as \"%1\"\n").arg(m_destFilePath)); + appendToLog( + QStringLiteral("Successfully saved image as \"%1\"\n").arg(m_destFilePath)); QMetaObject::invokeMethod(this, "onFinished", Qt::QueuedConnection, Q_ARG(int, 0)); } else { appendToLog(QStringLiteral("Failed to save image as \"%1\"\n").arg(m_destFilePath)); diff --git a/src/jobs/qimagejob.h b/src/jobs/qimagejob.h index 8350a77f91..c41ca132c2 100644 --- a/src/jobs/qimagejob.h +++ b/src/jobs/qimagejob.h @@ -19,6 +19,7 @@ #define QIMAGEJOB_H #include "abstractjob.h" + #include class QImageJob : public AbstractJob diff --git a/src/jobs/videoqualityjob.cpp b/src/jobs/videoqualityjob.cpp index b2100b1e2c..c9824c8a16 100644 --- a/src/jobs/videoqualityjob.cpp +++ b/src/jobs/videoqualityjob.cpp @@ -16,18 +16,23 @@ */ #include "videoqualityjob.h" + +#include "dialogs/textviewerdialog.h" +#include "mainwindow.h" + #include -#include +#include #include -#include +#include #include +#include #include -#include -#include "mainwindow.h" -#include "dialogs/textviewerdialog.h" -VideoQualityJob::VideoQualityJob(const QString &name, const QString &xml, - const QString &reportPath, int frameRateNum, int frameRateDen) +VideoQualityJob::VideoQualityJob(const QString &name, + const QString &xml, + const QString &reportPath, + int frameRateNum, + int frameRateDen) : MeltJob(name, xml, frameRateNum, frameRateDen) , m_reportPath(reportPath) { @@ -64,7 +69,7 @@ void VideoQualityJob::onOpenTiggered() // Locate the VQM transition. QDomNodeList transitions = dom.elementsByTagName("transition"); - for (int i = 0; i < transitions.length(); i++ ) { + for (int i = 0; i < transitions.length(); i++) { QDomElement property = transitions.at(i).firstChildElement("property"); while (!property.isNull()) { // Change the render property to 1. diff --git a/src/jobs/videoqualityjob.h b/src/jobs/videoqualityjob.h index cad55e4568..897e914066 100644 --- a/src/jobs/videoqualityjob.h +++ b/src/jobs/videoqualityjob.h @@ -24,8 +24,11 @@ class VideoQualityJob : public MeltJob { Q_OBJECT public: - VideoQualityJob(const QString &name, const QString &xml, - const QString &reportPath, int frameRateNum, int frameRateDen); + VideoQualityJob(const QString &name, + const QString &xml, + const QString &reportPath, + int frameRateNum, + int frameRateDen); private slots: void onOpenTiggered(); diff --git a/src/jobs/whisperjob.cpp b/src/jobs/whisperjob.cpp index bdabafc89c..64c3714ee1 100644 --- a/src/jobs/whisperjob.cpp +++ b/src/jobs/whisperjob.cpp @@ -17,18 +17,22 @@ #include "whisperjob.h" +#include "Logger.h" #include "dialogs/textviewerdialog.h" -#include #include "mainwindow.h" #include #include #include -#include #include +#include -WhisperJob::WhisperJob(const QString &name, const QString &iWavFile, const QString &oSrtFile, - const QString &lang, bool translate, int maxLength, +WhisperJob::WhisperJob(const QString &name, + const QString &iWavFile, + const QString &oSrtFile, + const QString &lang, + bool translate, + int maxLength, QThread::Priority priority) : AbstractJob(name, priority) , m_iWavFile(iWavFile) @@ -76,7 +80,7 @@ void WhisperJob::start() #endif args << "-t" << QString::number(threadCount); - LOG_DEBUG() << whisperPath + " " + args.join(' '); + LOG_DEBUG() << whisperPath + " " + args.join(' '); AbstractJob::start(whisperPath, args); emit progressUpdated(m_item, 0); } diff --git a/src/jobs/whisperjob.h b/src/jobs/whisperjob.h index 90aa13676d..f59336412f 100644 --- a/src/jobs/whisperjob.h +++ b/src/jobs/whisperjob.h @@ -19,14 +19,19 @@ #define WHISPERJOB_H #include "abstractjob.h" + #include class WhisperJob : public AbstractJob { Q_OBJECT public: - WhisperJob(const QString &name, const QString &iWavFile, const QString &oSrtFile, - const QString &lang, bool translate, int maxLength, + WhisperJob(const QString &name, + const QString &iWavFile, + const QString &oSrtFile, + const QString &lang, + bool translate, + int maxLength, QThread::Priority priority = Settings.jobPriority()); virtual ~WhisperJob(); diff --git a/src/main.cpp b/src/main.cpp index a17182d363..a0ac195f1a 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -15,20 +15,21 @@ * along with this program. If not, see . */ -#include -#include +#include "ConsoleAppender.h" +#include "FileAppender.h" +#include "Logger.h" #include "mainwindow.h" #include "settings.h" -#include -#include -#include -#include -#include -#include + #include +#include #include +#include #include #include +#include +#include +#include #ifdef Q_OS_MAC #include "macos.h" @@ -37,13 +38,12 @@ #ifdef Q_OS_WIN #include #if defined(QT_DEBUG) && !defined(__ARM_ARCH) -# include +#include #endif -extern "C" -{ - // Inform the driver we could make use of the discrete gpu - __declspec(dllexport) DWORD NvOptimusEnablement = 0x00000001; - __declspec(dllexport) DWORD AmdPowerXpressRequestHighPerformance = 0x00000001; +extern "C" { +// Inform the driver we could make use of the discrete gpu +__declspec(dllexport) DWORD NvOptimusEnablement = 0x00000001; +__declspec(dllexport) DWORD AmdPowerXpressRequestHighPerformance = 0x00000001; } #endif @@ -81,7 +81,7 @@ static void mlt_log_handler(void *service, int mlt_level, const char *format, va char *service_name = mlt_properties_get(properties, "mlt_service"); char *resource = mlt_properties_get(properties, "resource"); if (!resource || resource[0] != '<' || resource[strlen(resource) - 1] != '>') - mlt_type = mlt_properties_get(properties, "mlt_type" ); + mlt_type = mlt_properties_get(properties, "mlt_type"); if (service_name) message = QStringLiteral("[%1 %2] ").arg(mlt_type, service_name); else @@ -94,14 +94,18 @@ static void mlt_log_handler(void *service, int mlt_level, const char *format, va message = QString::vasprintf(format, args); message.replace('\n', ""); } - cuteLogger->write(cuteLoggerLevel, __FILE__, __LINE__, "MLT", - cuteLogger->defaultCategory().toLatin1().constData(), message); + cuteLogger->write(cuteLoggerLevel, + __FILE__, + __LINE__, + "MLT", + cuteLogger->defaultCategory().toLatin1().constData(), + message); } class Application : public QApplication { public: - MainWindow *mainWindow {nullptr}; + MainWindow *mainWindow{nullptr}; QTranslator qtTranslator; QTranslator qtBaseTranslator; QTranslator shotcutTranslator; @@ -145,54 +149,71 @@ class Application : public QApplication parser.addHelpOption(); parser.addVersionOption(); #ifndef Q_OS_WIN - QCommandLineOption fullscreenOption("fullscreen", - QCoreApplication::translate("main", "Fill the screen with the Shotcut window.")); + QCommandLineOption fullscreenOption( + "fullscreen", + QCoreApplication::translate("main", "Fill the screen with the Shotcut window.")); parser.addOption(fullscreenOption); #endif - QCommandLineOption noupgradeOption("noupgrade", - QCoreApplication::translate("main", "Hide upgrade prompt and menu item.")); + QCommandLineOption noupgradeOption( + "noupgrade", QCoreApplication::translate("main", "Hide upgrade prompt and menu item.")); parser.addOption(noupgradeOption); - QCommandLineOption glaxnimateOption("glaxnimate", - QCoreApplication::translate("main", "Run Glaxnimate instead of Shotcut.")); + QCommandLineOption + glaxnimateOption("glaxnimate", + QCoreApplication::translate("main", + "Run Glaxnimate instead of Shotcut.")); parser.addOption(glaxnimateOption); QCommandLineOption gpuOption("gpu", QCoreApplication::translate("main", "Use GPU processing.")); parser.addOption(gpuOption); QCommandLineOption clearRecentOption("clear-recent", - QCoreApplication::translate("main", "Clear Recent on Exit")); + QCoreApplication::translate("main", + "Clear Recent on Exit")); parser.addOption(clearRecentOption); - QCommandLineOption appDataOption("appdata", - QCoreApplication::translate("main", "The directory for app configuration and data."), - QCoreApplication::translate("main", "directory")); + QCommandLineOption appDataOption( + "appdata", + QCoreApplication::translate("main", "The directory for app configuration and data."), + QCoreApplication::translate("main", "directory")); parser.addOption(appDataOption); - QCommandLineOption scaleOption("QT_SCALE_FACTOR", - QCoreApplication::translate("main", "The scale factor for a high-DPI screen"), - QCoreApplication::translate("main", "number")); + QCommandLineOption + scaleOption("QT_SCALE_FACTOR", + QCoreApplication::translate("main", + "The scale factor for a high-DPI screen"), + QCoreApplication::translate("main", "number")); parser.addOption(scaleOption); - scaleOption = QCommandLineOption("QT_SCREEN_SCALE_FACTORS", - QCoreApplication::translate("main", "A semicolon-separated list of scale factors for each screen"), - QCoreApplication::translate("main", "list")); + scaleOption + = QCommandLineOption("QT_SCREEN_SCALE_FACTORS", + QCoreApplication::translate( + "main", + "A semicolon-separated list of scale factors for each screen"), + QCoreApplication::translate("main", "list")); parser.addOption(scaleOption); - QCommandLineOption scalePolicyOption("QT_SCALE_FACTOR_ROUNDING_POLICY", - QCoreApplication::translate("main", "How to handle a fractional display scale: %1") - .arg("Round, Ceil, Floor, RoundPreferFloor, PassThrough"), - QCoreApplication::translate("main", "string"), "PassThrough"); + QCommandLineOption scalePolicyOption( + "QT_SCALE_FACTOR_ROUNDING_POLICY", + QCoreApplication::translate("main", "How to handle a fractional display scale: %1") + .arg("Round, Ceil, Floor, RoundPreferFloor, PassThrough"), + QCoreApplication::translate("main", "string"), + "PassThrough"); parser.addOption(scalePolicyOption); #if defined(Q_OS_WIN) - QCommandLineOption sdlAudioDriverOption("SDL_AUDIODRIVER", - QCoreApplication::translate("main", "Which operating system audio API to use: %1") - .arg("directsound, wasapi, winmm"), - QCoreApplication::translate("main", "string"), "wasapi"); + QCommandLineOption sdlAudioDriverOption( + "SDL_AUDIODRIVER", + QCoreApplication::translate("main", "Which operating system audio API to use: %1") + .arg("directsound, wasapi, winmm"), + QCoreApplication::translate("main", "string"), + "wasapi"); parser.addOption(sdlAudioDriverOption); #elif defined(Q_OS_LINUX) - QCommandLineOption sdlAudioDriverOption("SDL_AUDIODRIVER", - QCoreApplication::translate("main", "Which operating system audio API to use: %1") - .arg("alsa, arts, dsp, esd, jack, pipewire, pulseaudio"), - QCoreApplication::translate("main", "string"), "pulseaudio"); + QCommandLineOption sdlAudioDriverOption( + "SDL_AUDIODRIVER", + QCoreApplication::translate("main", "Which operating system audio API to use: %1") + .arg("alsa, arts, dsp, esd, jack, pipewire, pulseaudio"), + QCoreApplication::translate("main", "string"), + "pulseaudio"); parser.addOption(sdlAudioDriverOption); #endif - parser.addPositionalArgument("[FILE]...", - QCoreApplication::translate("main", "Zero or more files or folders to open")); + parser.addPositionalArgument( + "[FILE]...", + QCoreApplication::translate("main", "Zero or more files or folders to open")); parser.process(arguments()); if (parser.isSet(glaxnimateOption)) { QStringList args = arguments(); @@ -222,7 +243,8 @@ class Application : public QApplication // Startup logging. dir.setPath(Settings.appDataLocation()); - if (!dir.exists()) dir.mkpath(dir.path()); + if (!dir.exists()) + dir.mkpath(dir.path()); const auto logFileName = dir.filePath("shotcut-log.txt"); if (QFile::exists(logFileName)) { const auto previousLogName = dir.filePath("shotcut-log.bak"); @@ -301,7 +323,8 @@ class Application : public QApplication QFileOpenEvent *openEvent = static_cast(event); resourceArg << openEvent->file(); return true; - } else return QApplication::event(event); + } else + return QApplication::event(event); } }; @@ -314,7 +337,8 @@ int main(int argc, char **argv) ::qputenv("QT_LOGGING_RULES", "*.warning=false"); #endif for (int i = 1; i + 1 < argc; i++) { - if (!::qstrcmp("--QT_SCALE_FACTOR", argv[i]) || !::qstrcmp("--QT_SCREEN_SCALE_FACTORS", argv[i])) { + if (!::qstrcmp("--QT_SCALE_FACTOR", argv[i]) + || !::qstrcmp("--QT_SCREEN_SCALE_FACTORS", argv[i])) { QByteArray value(argv[i + 1]); ::qputenv("QT_AUTO_SCREEN_SCALE_FACTOR", "0"); ::qputenv(value.contains(';') ? "QT_SCREEN_SCALE_FACTORS" : "QT_SCALE_FACTOR", value); @@ -362,7 +386,8 @@ int main(int argc, char **argv) if (QProcessEnvironment::systemEnvironment().value(MLT_LC_NAME).isEmpty()) { qputenv(MLT_LC_NAME, QLocale().name().toUtf8()); - QLocale localeByName(QLocale(QLocale().language(), QLocale().script(), QLocale().territory())); + QLocale localeByName( + QLocale(QLocale().language(), QLocale().script(), QLocale().territory())); if (QLocale().decimalPoint() != localeByName.decimalPoint()) { // If region's numeric format does not match the language's, then we run // into problems because we told MLT and libc to use a different numeric @@ -398,9 +423,10 @@ int main(int argc, char **argv) #if defined(Q_OS_WIN) LOG_INFO() << "Windows version" << QSysInfo::productVersion(); #elif defined(Q_OS_MAC) - LOG_INFO() << "macOS version" << QSysInfo::productVersion(); + LOG_INFO() << "macOS version" << QSysInfo::productVersion(); #else - LOG_INFO() << "Linux version" << QSysInfo::productVersion();; + LOG_INFO() << "Linux version" << QSysInfo::productVersion(); + ; #endif LOG_INFO() << "number of logical cores =" << QThread::idealThreadCount(); LOG_INFO() << "locale =" << QLocale(); @@ -412,11 +438,13 @@ int main(int argc, char **argv) Qt::AlignRight | Qt::AlignVCenter); splash.show(); a.processEvents(); - auto dir = QDir(QStandardPaths::standardLocations(QStandardPaths::CacheLocation).constFirst()); + auto dir = QDir( + QStandardPaths::standardLocations(QStandardPaths::CacheLocation).constFirst()); if (dir.exists() && dir.cd("qmlcache")) { auto ls = dir.entryList(QDir::Files | QDir::Readable | QDir::NoDotAndDotDot, QDir::Time); if (qMax(0, ls.size() - kMaxCacheCount) > 0) { - LOG_INFO() << "removing" << qMax(0, ls.size() - kMaxCacheCount) << "from" << dir.path(); + LOG_INFO() << "removing" << qMax(0, ls.size() - kMaxCacheCount) << "from" + << dir.path(); } for (int i = kMaxCacheCount; i < ls.size(); i++) { QString filePath = dir.filePath(ls[i]); @@ -464,7 +492,8 @@ int main(int argc, char **argv) #if defined(Q_OS_UNIX) && !defined(Q_OS_MAC) ::qputenv("LIBGL_ALWAYS_SOFTWARE", Settings.drawMethod() == Qt::AA_UseSoftwareOpenGL && !Settings.playerGPU() - ? "1" : "0"); + ? "1" + : "0"); #endif QProcess *restart = new QProcess; QStringList args = a.arguments(); diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 45aeb2dfe3..abbae4b2e6 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -17,90 +17,92 @@ #include "mainwindow.h" #include "ui_mainwindow.h" + +#include "Logger.h" #include "actions.h" +#include "autosavefile.h" +#include "commands/playlistcommands.h" +#include "controllers/filtercontroller.h" +#include "controllers/scopecontroller.h" +#include "database.h" +#include "defaultlayouts.h" +#include "dialogs/actionsdialog.h" +#include "dialogs/customprofiledialog.h" +#include "dialogs/listselectiondialog.h" +#include "dialogs/longuitask.h" +#include "dialogs/resourcedialog.h" +#include "dialogs/saveimagedialog.h" +#include "dialogs/systemsyncdialog.h" +#include "dialogs/textviewerdialog.h" +#include "dialogs/unlinkedfilesdialog.h" +#include "docks/encodedock.h" +#include "docks/filesdock.h" +#include "docks/filtersdock.h" +#include "docks/jobsdock.h" +#include "docks/keyframesdock.h" +#include "docks/markersdock.h" +#include "docks/notesdock.h" +#include "docks/playlistdock.h" +#include "docks/recentdock.h" +#include "docks/subtitlesdock.h" +#include "docks/timelinedock.h" +#include "jobqueue.h" +#include "models/audiolevelstask.h" +#include "models/keyframesmodel.h" +#include "models/motiontrackermodel.h" #include "openotherdialog.h" #include "player.h" -#include "defaultlayouts.h" +#include "proxymanager.h" +#include "qmltypes/qmlapplication.h" +#include "qmltypes/qmlprofile.h" +#include "qmltypes/qmlutilities.h" +#include "settings.h" +#include "shotcut_mlt_properties.h" +#include "util.h" +#include "videowidget.h" #include "widgets/alsawidget.h" +#include "widgets/avformatproducerwidget.h" +#include "widgets/avfoundationproducerwidget.h" +#include "widgets/blipproducerwidget.h" #include "widgets/colorbarswidget.h" #include "widgets/colorproducerwidget.h" #include "widgets/countproducerwidget.h" #include "widgets/decklinkproducerwidget.h" #include "widgets/directshowvideowidget.h" #include "widgets/glaxnimateproducerwidget.h" +#include "widgets/imageproducerwidget.h" #include "widgets/isingwidget.h" -#include "widgets/toneproducerwidget.h" #include "widgets/lissajouswidget.h" +#include "widgets/lumamixtransition.h" +#include "widgets/mltclipproducerwidget.h" +#include "widgets/newprojectfolder.h" #include "widgets/noisewidget.h" #include "widgets/plasmawidget.h" #include "widgets/pulseaudiowidget.h" -#include "widgets/video4linuxwidget.h" -#include "widgets/avformatproducerwidget.h" -#include "widgets/imageproducerwidget.h" -#include "widgets/blipproducerwidget.h" -#include "widgets/newprojectfolder.h" -#include "docks/recentdock.h" -#include "docks/encodedock.h" -#include "docks/jobsdock.h" -#include "jobqueue.h" -#include "docks/playlistdock.h" -#include "videowidget.h" -#include "controllers/filtercontroller.h" -#include "controllers/scopecontroller.h" -#include "docks/filtersdock.h" -#include "dialogs/actionsdialog.h" -#include "dialogs/customprofiledialog.h" -#include "dialogs/resourcedialog.h" -#include "dialogs/saveimagedialog.h" -#include "settings.h" -#include "database.h" -#include "docks/timelinedock.h" -#include "widgets/lumamixtransition.h" -#include "widgets/mltclipproducerwidget.h" -#include "qmltypes/qmlutilities.h" -#include "qmltypes/qmlapplication.h" -#include "autosavefile.h" -#include "commands/playlistcommands.h" -#include "shotcut_mlt_properties.h" -#include "widgets/avfoundationproducerwidget.h" -#include "dialogs/textviewerdialog.h" -#include "models/audiolevelstask.h" -#include "widgets/trackpropertieswidget.h" -#include "widgets/timelinepropertieswidget.h" -#include "dialogs/unlinkedfilesdialog.h" -#include "docks/keyframesdock.h" -#include "docks/filesdock.h" -#include "docks/markersdock.h" -#include "docks/notesdock.h" -#include "docks/subtitlesdock.h" -#include "util.h" -#include "models/keyframesmodel.h" -#include "dialogs/listselectiondialog.h" #include "widgets/textproducerwidget.h" -#include "qmltypes/qmlprofile.h" -#include "dialogs/longuitask.h" -#include "dialogs/systemsyncdialog.h" -#include "proxymanager.h" -#include "models/motiontrackermodel.h" +#include "widgets/timelinepropertieswidget.h" +#include "widgets/toneproducerwidget.h" +#include "widgets/trackpropertieswidget.h" +#include "widgets/video4linuxwidget.h" #if defined(Q_OS_WIN) && (QT_VERSION < QT_VERSION_CHECK(6, 0, 0)) #include "windowstools.h" #endif -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include #include #include -#include -#include -#include -#include #include +#include #include -#include -#include -#include +#include +#include +#include + #include #define SHOTCUT_THEME @@ -122,8 +124,9 @@ static bool eventDebugCallback(void **data) static const int AUTOSAVE_TIMEOUT_MS = 60000; static const char *kReservedLayoutPrefix = "__%1"; static const char *kLayoutSwitcherName("layoutSwitcherGrid"); -static QRegularExpression -kBackupFileRegex("^(.+) ([0-9]{4})-(1[0-2]|0[1-9])-(3[01]|0[1-9]|[12][0-9])T(2[0-3]|[01][0-9])-([0-5][0-9])-([0-5][0-9]).mlt$"); +static QRegularExpression kBackupFileRegex("^(.+) " + "([0-9]{4})-(1[0-2]|0[1-9])-(3[01]|0[1-9]|[12][0-9])T(2[" + "0-3]|[01][0-9])-([0-5][0-9])-([0-5][0-9]).mlt$"); MainWindow::MainWindow() : QMainWindow(0) @@ -141,8 +144,11 @@ MainWindow::MainWindow() #if defined(Q_OS_UNIX) && !defined(Q_OS_MAC) QLibrary libSDL("libSDL2-2.0.so.0"); if (!libSDL.load()) { - QMessageBox::critical(this, qApp->applicationName(), - tr("Error: This program requires the SDL 2 library.\n\nPlease install it using your package manager. It may be named libsdl2-2.0-0, SDL2, or similar.")); + QMessageBox::critical( + this, + qApp->applicationName(), + tr("Error: This program requires the SDL 2 library.\n\nPlease install it using your " + "package manager. It may be named libsdl2-2.0-0, SDL2, or similar.")); ::exit(EXIT_FAILURE); } else { libSDL.unload(); @@ -210,15 +216,16 @@ MainWindow::MainWindow() setFocus(); setCurrentFile(""); - connect(&m_network, SIGNAL(finished(QNetworkReply *)), + connect(&m_network, + SIGNAL(finished(QNetworkReply *)), SLOT(onUpgradeCheckFinished(QNetworkReply *))); resetSourceUpdated(); m_clipboardUpdatedAt.setSecsSinceEpoch(0); onClipboardChanged(); connect(QGuiApplication::clipboard(), SIGNAL(dataChanged()), this, SLOT(onClipboardChanged())); - QThreadPool::globalInstance()->setMaxThreadCount(qMin(4, - QThreadPool::globalInstance()->maxThreadCount())); + QThreadPool::globalInstance()->setMaxThreadCount( + qMin(4, QThreadPool::globalInstance()->maxThreadCount())); QThreadPool::globalInstance()->setThreadPriority(QThread::LowPriority); QImageReader::setAllocationLimit(1024); @@ -230,12 +237,9 @@ MainWindow::MainWindow() void MainWindow::connectFocusSignals() { if (!qgetenv("OBSERVE_FOCUS").isEmpty()) { - connect(qApp, &QApplication::focusChanged, - this, &MainWindow::onFocusChanged); - connect(qApp, &QGuiApplication::focusObjectChanged, - this, &MainWindow::onFocusObjectChanged); - connect(qApp, &QGuiApplication::focusWindowChanged, - this, &MainWindow::onFocusWindowChanged); + connect(qApp, &QApplication::focusChanged, this, &MainWindow::onFocusChanged); + connect(qApp, &QGuiApplication::focusObjectChanged, this, &MainWindow::onFocusObjectChanged); + connect(qApp, &QGuiApplication::focusWindowChanged, this, &MainWindow::onFocusWindowChanged); } } @@ -250,7 +254,9 @@ void MainWindow::connectUISignals() connect(ui->actionOpen, SIGNAL(triggered()), this, SLOT(openVideo())); connect(ui->actionAbout_Qt, SIGNAL(triggered()), qApp, SLOT(aboutQt())); connect(this, &MainWindow::producerOpened, this, &MainWindow::onProducerOpened); - connect(ui->mainToolBar, SIGNAL(visibilityChanged(bool)), SLOT(onToolbarVisibilityChanged(bool))); + connect(ui->mainToolBar, + SIGNAL(visibilityChanged(bool)), + SLOT(onToolbarVisibilityChanged(bool))); ui->actionSave->setEnabled(false); connect(this, &MainWindow::audioChannelsChanged, this, &MainWindow::updateWindowTitle); connect(this, &MainWindow::producerOpened, this, &MainWindow::updateWindowTitle); @@ -263,10 +269,10 @@ void MainWindow::setupAndConnectUndoStack() m_undoStack->setUndoLimit(Settings.undoLimit()); QAction *undoAction = m_undoStack->createUndoAction(this); QAction *redoAction = m_undoStack->createRedoAction(this); - undoAction->setIcon(QIcon::fromTheme("edit-undo", - QIcon(":/icons/oxygen/32x32/actions/edit-undo.png"))); - redoAction->setIcon(QIcon::fromTheme("edit-redo", - QIcon(":/icons/oxygen/32x32/actions/edit-redo.png"))); + undoAction->setIcon( + QIcon::fromTheme("edit-undo", QIcon(":/icons/oxygen/32x32/actions/edit-undo.png"))); + redoAction->setIcon( + QIcon::fromTheme("edit-redo", QIcon(":/icons/oxygen/32x32/actions/edit-redo.png"))); undoAction->setShortcut(QString::fromLatin1("Ctrl+Z")); #ifdef Q_OS_WIN redoAction->setShortcut(QString::fromLatin1("Ctrl+Y")); @@ -384,7 +390,9 @@ void MainWindow::setupAndConnectDocks() QDockWidget *audioMeterDock = findChild("AudioPeakMeterDock"); if (audioMeterDock) { audioMeterDock->toggleViewAction()->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_1)); - connect(ui->actionAudioMeter, SIGNAL(triggered()), audioMeterDock->toggleViewAction(), + connect(ui->actionAudioMeter, + SIGNAL(triggered()), + audioMeterDock->toggleViewAction(), SLOT(trigger())); } @@ -399,7 +407,9 @@ void MainWindow::setupAndConnectDocks() scroll->setWidgetResizable(true); m_propertiesDock->setWidget(scroll); ui->menuView->addAction(m_propertiesDock->toggleViewAction()); - connect(m_propertiesDock->toggleViewAction(), SIGNAL(triggered(bool)), this, + connect(m_propertiesDock->toggleViewAction(), + SIGNAL(triggered(bool)), + this, SLOT(onPropertiesDockTriggered(bool))); connect(ui->actionProperties, SIGNAL(triggered()), this, SLOT(onPropertiesDockTriggered())); @@ -408,24 +418,35 @@ void MainWindow::setupAndConnectDocks() m_recentDock->toggleViewAction()->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_3)); ui->menuView->addAction(m_recentDock->toggleViewAction()); connect(m_recentDock, SIGNAL(itemActivated(QString)), this, SLOT(open(QString))); - connect(m_recentDock->toggleViewAction(), SIGNAL(triggered(bool)), this, + connect(m_recentDock->toggleViewAction(), + SIGNAL(triggered(bool)), + this, SLOT(onRecentDockTriggered(bool))); connect(ui->actionRecent, SIGNAL(triggered()), this, SLOT(onRecentDockTriggered())); connect(this, SIGNAL(openFailed(QString)), m_recentDock, SLOT(remove(QString))); - connect(m_recentDock, &RecentDock::deleted, m_player->projectWidget(), + connect(m_recentDock, + &RecentDock::deleted, + m_player->projectWidget(), &NewProjectFolder::updateRecentProjects); m_playlistDock = new PlaylistDock(this); m_playlistDock->hide(); m_playlistDock->toggleViewAction()->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_4)); ui->menuView->addAction(m_playlistDock->toggleViewAction()); - connect(m_playlistDock->toggleViewAction(), SIGNAL(triggered(bool)), this, + connect(m_playlistDock->toggleViewAction(), + SIGNAL(triggered(bool)), + this, SLOT(onPlaylistDockTriggered(bool))); connect(ui->actionPlaylist, SIGNAL(triggered()), this, SLOT(onPlaylistDockTriggered())); - connect(m_playlistDock, SIGNAL(clipOpened(Mlt::Producer *, bool)), this, + connect(m_playlistDock, + SIGNAL(clipOpened(Mlt::Producer *, bool)), + this, SLOT(openCut(Mlt::Producer *, bool))); connect(m_playlistDock, SIGNAL(itemActivated(int)), this, SLOT(seekPlaylist(int))); - connect(m_playlistDock, SIGNAL(showStatusMessage(QString)), this, SLOT(showStatusMessage(QString))); + connect(m_playlistDock, + SIGNAL(showStatusMessage(QString)), + this, + SLOT(showStatusMessage(QString))); connect(m_playlistDock->model(), SIGNAL(created()), this, SLOT(onPlaylistCreated())); connect(m_playlistDock->model(), SIGNAL(cleared()), this, SLOT(onPlaylistCleared())); connect(m_playlistDock->model(), SIGNAL(closed()), this, SLOT(onPlaylistClosed())); @@ -436,8 +457,13 @@ void MainWindow::setupAndConnectDocks() connect(m_playlistDock->model(), SIGNAL(loaded()), this, SLOT(updateThumbnails())); connect(m_player, &Player::inChanged, m_playlistDock, &PlaylistDock::onInChanged); connect(m_player, &Player::outChanged, m_playlistDock, &PlaylistDock::onOutChanged); - connect(m_playlistDock->model(), &PlaylistModel::inChanged, this, &MainWindow::onPlaylistInChanged); - connect(m_playlistDock->model(), &PlaylistModel::outChanged, this, + connect(m_playlistDock->model(), + &PlaylistModel::inChanged, + this, + &MainWindow::onPlaylistInChanged); + connect(m_playlistDock->model(), + &PlaylistModel::outChanged, + this, &MainWindow::onPlaylistOutChanged); QMenu *viewModeMenu = ui->menuPlaylist->addMenu(tr("View mode")); viewModeMenu->addAction(Actions["playlistViewDetailsAction"]); @@ -453,10 +479,13 @@ void MainWindow::setupAndConnectDocks() m_filesDock = new FilesDock(this); m_filesDock->hide(); - m_filesDock->toggleViewAction()->setShortcuts({QKeySequence(Qt::CTRL | Qt::SHIFT | Qt::Key_4), QKeySequence(Qt::Key_F10)}); + m_filesDock->toggleViewAction()->setShortcuts( + {QKeySequence(Qt::CTRL | Qt::SHIFT | Qt::Key_4), QKeySequence(Qt::Key_F10)}); ui->menuView->addAction(m_filesDock->toggleViewAction()); // connect(m_filesDock, SIGNAL(itemActivated(QString)), this, SLOT(open(QString))); - connect(m_filesDock->toggleViewAction(), SIGNAL(triggered(bool)), this, + connect(m_filesDock->toggleViewAction(), + SIGNAL(triggered(bool)), + this, SLOT(onFilesDockTriggered(bool))); connect(ui->actionFiles, SIGNAL(triggered()), this, SLOT(onFilesDockTriggered())); @@ -464,37 +493,54 @@ void MainWindow::setupAndConnectDocks() m_timelineDock->hide(); m_timelineDock->toggleViewAction()->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_5)); ui->menuView->addAction(m_timelineDock->toggleViewAction()); - connect(m_timelineDock->toggleViewAction(), SIGNAL(triggered(bool)), this, + connect(m_timelineDock->toggleViewAction(), + SIGNAL(triggered(bool)), + this, SLOT(onTimelineDockTriggered(bool))); connect(ui->actionTimeline, SIGNAL(triggered()), SLOT(onTimelineDockTriggered())); connect(m_player, SIGNAL(seeked(int)), m_timelineDock, SLOT(onSeeked(int))); connect(m_timelineDock, SIGNAL(seeked(int)), SLOT(seekTimeline(int))); connect(m_timelineDock, SIGNAL(clipClicked()), SLOT(onTimelineClipSelected())); - connect(m_timelineDock, SIGNAL(showStatusMessage(QString)), this, SLOT(showStatusMessage(QString))); - connect(m_timelineDock->model(), SIGNAL(showStatusMessage(QString)), this, + connect(m_timelineDock, + SIGNAL(showStatusMessage(QString)), + this, + SLOT(showStatusMessage(QString))); + connect(m_timelineDock->model(), + SIGNAL(showStatusMessage(QString)), + this, SLOT(showStatusMessage(QString))); connect(m_timelineDock->model(), SIGNAL(created()), SLOT(onMultitrackCreated())); connect(m_timelineDock->model(), SIGNAL(closed()), SLOT(onMultitrackClosed())); connect(m_timelineDock->model(), SIGNAL(modified()), SLOT(onMultitrackModified())); - connect(m_timelineDock->model(), &QAbstractItemModel::rowsInserted, m_playlistDock, + connect(m_timelineDock->model(), + &QAbstractItemModel::rowsInserted, + m_playlistDock, &PlaylistDock::refreshTimelineSmartBins); - connect(m_timelineDock->model(), &QAbstractItemModel::rowsRemoved, m_playlistDock, + connect(m_timelineDock->model(), + &QAbstractItemModel::rowsRemoved, + m_playlistDock, &PlaylistDock::refreshTimelineSmartBins); connect(m_timelineDock->model(), SIGNAL(durationChanged()), SLOT(onMultitrackDurationChanged())); connect(m_timelineDock, SIGNAL(clipOpened(Mlt::Producer *)), SLOT(openCut(Mlt::Producer *))); connect(m_timelineDock->model(), &MultitrackModel::seeked, this, &MainWindow::seekTimeline); connect(m_timelineDock->markersModel(), SIGNAL(modified()), SLOT(onMultitrackModified())); - connect(m_timelineDock, SIGNAL(selected(Mlt::Producer *)), + connect(m_timelineDock, + SIGNAL(selected(Mlt::Producer *)), SLOT(loadProducerWidget(Mlt::Producer *))); connect(m_timelineDock, SIGNAL(clipCopied()), SLOT(onClipCopied())); connect(m_timelineDock, SIGNAL(filteredClicked()), SLOT(onFiltersDockTriggered())); - connect(m_playlistDock, SIGNAL(addAllTimeline(Mlt::Playlist *)), SLOT(onTimelineDockTriggered())); - connect(m_playlistDock, SIGNAL(addAllTimeline(Mlt::Playlist *, bool, bool)), + connect(m_playlistDock, + SIGNAL(addAllTimeline(Mlt::Playlist *)), + SLOT(onTimelineDockTriggered())); + connect(m_playlistDock, + SIGNAL(addAllTimeline(Mlt::Playlist *, bool, bool)), SLOT(onAddAllToTimeline(Mlt::Playlist *, bool, bool))); connect(m_player, SIGNAL(previousSought()), m_timelineDock, SLOT(seekPreviousEdit())); connect(m_player, SIGNAL(nextSought()), m_timelineDock, SLOT(seekNextEdit())); connect(m_player, SIGNAL(loopChanged(int, int)), m_timelineDock, SLOT(onLoopChanged(int, int))); - connect(m_timelineDock, SIGNAL(isRecordingChanged(bool)), m_player, + connect(m_timelineDock, + SIGNAL(isRecordingChanged(bool)), + m_player, SLOT(onMuteButtonToggled(bool))); connect(m_player, SIGNAL(trimIn()), m_timelineDock, SLOT(trimClipIn())); connect(m_player, SIGNAL(trimOut()), m_timelineDock, SLOT(trimClipOut())); @@ -536,51 +582,88 @@ void MainWindow::setupAndConnectDocks() m_filtersDock->hide(); m_filtersDock->toggleViewAction()->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_6)); ui->menuView->addAction(m_filtersDock->toggleViewAction()); - connect(m_filtersDock, SIGNAL(currentFilterRequested(int)), m_filterController, - SLOT(setCurrentFilter(int)), Qt::QueuedConnection); - connect(m_filtersDock->toggleViewAction(), SIGNAL(triggered(bool)), this, + connect(m_filtersDock, + SIGNAL(currentFilterRequested(int)), + m_filterController, + SLOT(setCurrentFilter(int)), + Qt::QueuedConnection); + connect(m_filtersDock->toggleViewAction(), + SIGNAL(triggered(bool)), + this, SLOT(onFiltersDockTriggered(bool))); connect(ui->actionFilters, SIGNAL(triggered()), this, SLOT(onFiltersDockTriggered())); - connect(m_filterController, SIGNAL(currentFilterChanged(QmlFilter *, QmlMetadata *, int)), - m_filtersDock, SLOT(setCurrentFilter(QmlFilter *, QmlMetadata *, int))); + connect(m_filterController, + SIGNAL(currentFilterChanged(QmlFilter *, QmlMetadata *, int)), + m_filtersDock, + SLOT(setCurrentFilter(QmlFilter *, QmlMetadata *, int))); connect(m_filterController, &FilterController::undoOrRedo, m_filtersDock, &FiltersDock::load); connect(this, SIGNAL(producerOpened()), m_filterController, SLOT(setProducer())); connect(m_filterController->attachedModel(), SIGNAL(changed()), SLOT(onFilterModelChanged())); connect(m_filtersDock, SIGNAL(changed()), SLOT(onFilterModelChanged())); - connect(m_filterController, SIGNAL(filterChanged(Mlt::Service *)), - m_timelineDock->model(), SLOT(onFilterChanged(Mlt::Service *))); - connect(m_filterController->attachedModel(), SIGNAL(changed()), m_timelineDock, + connect(m_filterController, + SIGNAL(filterChanged(Mlt::Service *)), + m_timelineDock->model(), + SLOT(onFilterChanged(Mlt::Service *))); + connect(m_filterController->attachedModel(), + SIGNAL(changed()), + m_timelineDock, SLOT(onFilterModelChanged())); connect(m_filtersDock, SIGNAL(changed()), m_timelineDock, SLOT(onFilterModelChanged())); - connect(m_filterController->attachedModel(), SIGNAL(addedOrRemoved(Mlt::Producer *)), - m_timelineDock->model(), SLOT(filterAddedOrRemoved(Mlt::Producer *))); - connect(&QmlApplication::singleton(), SIGNAL(filtersPasted(Mlt::Producer *)), - m_timelineDock->model(), SLOT(filterAddedOrRemoved(Mlt::Producer *))); - connect(&QmlApplication::singleton(), &QmlApplication::filtersPasted, - this, &MainWindow::onProducerModified); - connect(m_filterController, SIGNAL(statusChanged(QString)), this, SLOT(showStatusMessage(QString))); + connect(m_filterController->attachedModel(), + SIGNAL(addedOrRemoved(Mlt::Producer *)), + m_timelineDock->model(), + SLOT(filterAddedOrRemoved(Mlt::Producer *))); + connect(&QmlApplication::singleton(), + SIGNAL(filtersPasted(Mlt::Producer *)), + m_timelineDock->model(), + SLOT(filterAddedOrRemoved(Mlt::Producer *))); + connect(&QmlApplication::singleton(), + &QmlApplication::filtersPasted, + this, + &MainWindow::onProducerModified); + connect(m_filterController, + SIGNAL(statusChanged(QString)), + this, + SLOT(showStatusMessage(QString))); connect(m_timelineDock, SIGNAL(fadeInChanged(int)), m_filterController, SLOT(onFadeInChanged())); - connect(m_timelineDock, SIGNAL(fadeOutChanged(int)), m_filterController, SLOT(onFadeOutChanged())); - connect(m_timelineDock, SIGNAL(selected(Mlt::Producer *)), m_filterController, + connect(m_timelineDock, + SIGNAL(fadeOutChanged(int)), + m_filterController, + SLOT(onFadeOutChanged())); + connect(m_timelineDock, + SIGNAL(selected(Mlt::Producer *)), + m_filterController, SLOT(setProducer(Mlt::Producer *))); connect(m_player, SIGNAL(seeked(int)), m_filtersDock, SLOT(onSeeked(int)), Qt::QueuedConnection); connect(m_filtersDock, SIGNAL(seeked(int)), SLOT(seekKeyframes(int))); - connect(MLT.videoWidget(), SIGNAL(frameDisplayed(const SharedFrame &)), m_filtersDock, + connect(MLT.videoWidget(), + SIGNAL(frameDisplayed(const SharedFrame &)), + m_filtersDock, SLOT(onShowFrame(const SharedFrame &))); connect(m_player, SIGNAL(inChanged(int)), m_filtersDock, SIGNAL(producerInChanged(int))); - connect(this, SIGNAL(serviceInChanged(int, Mlt::Service *)), m_filtersDock, + connect(this, + SIGNAL(serviceInChanged(int, Mlt::Service *)), + m_filtersDock, SLOT(onServiceInChanged(int, Mlt::Service *))); connect(m_player, SIGNAL(outChanged(int)), m_filtersDock, SIGNAL(producerOutChanged(int))); connect(m_player, SIGNAL(inChanged(int)), m_filterController, SLOT(onServiceInChanged(int))); connect(m_player, SIGNAL(outChanged(int)), m_filterController, SLOT(onServiceOutChanged(int))); - connect(this, SIGNAL(serviceInChanged(int, Mlt::Service *)), m_filterController, + connect(this, + SIGNAL(serviceInChanged(int, Mlt::Service *)), + m_filterController, SLOT(onServiceInChanged(int, Mlt::Service *))); - connect(this, SIGNAL(serviceOutChanged(int, Mlt::Service *)), m_filterController, + connect(this, + SIGNAL(serviceOutChanged(int, Mlt::Service *)), + m_filterController, SLOT(onServiceOutChanged(int, Mlt::Service *))); - connect(m_playlistDock->model(), &PlaylistModel::removing, - m_filterController->motionTrackerModel(), &MotionTrackerModel::removeFromService); - connect(m_timelineDock->model(), &MultitrackModel::removing, - m_filterController->motionTrackerModel(), &MotionTrackerModel::removeFromService); + connect(m_playlistDock->model(), + &PlaylistModel::removing, + m_filterController->motionTrackerModel(), + &MotionTrackerModel::removeFromService); + connect(m_timelineDock->model(), + &MultitrackModel::removing, + m_filterController->motionTrackerModel(), + &MotionTrackerModel::removeFromService); connect(this, SIGNAL(audioChannelsChanged()), m_filterController, SLOT(setProducer())); m_markersDock = new MarkersDock(this); @@ -588,28 +671,43 @@ void MainWindow::setupAndConnectDocks() m_markersDock->toggleViewAction()->setShortcut(QKeySequence(Qt::CTRL | Qt::SHIFT | Qt::Key_6)); m_markersDock->setModel(m_timelineDock->markersModel()); ui->menuView->addAction(m_markersDock->toggleViewAction()); - connect(m_markersDock->toggleViewAction(), SIGNAL(triggered(bool)), this, + connect(m_markersDock->toggleViewAction(), + SIGNAL(triggered(bool)), + this, SLOT(onMarkersDockTriggered(bool))); connect(ui->actionMarkers, SIGNAL(triggered()), this, SLOT(onMarkersDockTriggered())); connect(m_markersDock, SIGNAL(seekRequested(int)), SLOT(seekTimeline(int))); connect(m_markersDock, SIGNAL(addRequested()), m_timelineDock, SLOT(createMarker())); - connect(m_markersDock, SIGNAL(addAroundSelectionRequested()), m_timelineDock, + connect(m_markersDock, + SIGNAL(addAroundSelectionRequested()), + m_timelineDock, SLOT(createOrEditSelectionMarker())); - connect(m_timelineDock, SIGNAL(markerSeeked(int)), m_markersDock, + connect(m_timelineDock, + SIGNAL(markerSeeked(int)), + m_markersDock, SLOT(onMarkerSelectionRequest(int))); m_keyframesDock = new KeyframesDock(m_filtersDock->qmlProducer(), this); m_keyframesDock->hide(); m_keyframesDock->toggleViewAction()->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_7)); ui->menuView->addAction(m_keyframesDock->toggleViewAction()); - connect(m_keyframesDock->toggleViewAction(), SIGNAL(triggered(bool)), this, + connect(m_keyframesDock->toggleViewAction(), + SIGNAL(triggered(bool)), + this, SLOT(onKeyframesDockTriggered(bool))); connect(ui->actionKeyframes, SIGNAL(triggered()), this, SLOT(onKeyframesDockTriggered())); - connect(m_filterController, SIGNAL(currentFilterChanged(QmlFilter *, QmlMetadata *, int)), - m_keyframesDock, SLOT(setCurrentFilter(QmlFilter *, QmlMetadata *))); - connect(m_keyframesDock, SIGNAL(visibilityChanged(bool)), m_filtersDock->qmlProducer(), + connect(m_filterController, + SIGNAL(currentFilterChanged(QmlFilter *, QmlMetadata *, int)), + m_keyframesDock, + SLOT(setCurrentFilter(QmlFilter *, QmlMetadata *))); + connect(m_keyframesDock, + SIGNAL(visibilityChanged(bool)), + m_filtersDock->qmlProducer(), SLOT(remakeAudioLevels(bool))); - connect(m_filterController, &FilterController::undoOrRedo, m_keyframesDock, &KeyframesDock::reload); + connect(m_filterController, + &FilterController::undoOrRedo, + m_keyframesDock, + &KeyframesDock::reload); m_historyDock = new QDockWidget(tr("History"), this); m_historyDock->hide(); @@ -619,7 +717,9 @@ void MainWindow::setupAndConnectDocks() m_historyDock->toggleViewAction()->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_8)); m_historyDock->setMinimumWidth(150); ui->menuView->addAction(m_historyDock->toggleViewAction()); - connect(m_historyDock->toggleViewAction(), SIGNAL(triggered(bool)), this, + connect(m_historyDock->toggleViewAction(), + SIGNAL(triggered(bool)), + this, SLOT(onHistoryDockTriggered(bool))); connect(ui->actionHistory, SIGNAL(triggered()), this, SLOT(onHistoryDockTriggered())); QUndoView *undoView = new QUndoView(m_undoStack, m_historyDock); @@ -636,20 +736,44 @@ void MainWindow::setupAndConnectDocks() ui->menuView->addAction(m_encodeDock->toggleViewAction()); connect(this, SIGNAL(producerOpened()), m_encodeDock, SLOT(onProducerOpened())); connect(ui->actionEncode, SIGNAL(triggered()), this, SLOT(onEncodeTriggered())); - connect(ui->actionExportVideo, SIGNAL(triggered()), m_encodeDock, SLOT(on_encodeButton_clicked())); - connect(m_encodeDock->toggleViewAction(), SIGNAL(triggered(bool)), this, + connect(ui->actionExportVideo, + SIGNAL(triggered()), + m_encodeDock, + SLOT(on_encodeButton_clicked())); + connect(m_encodeDock->toggleViewAction(), + SIGNAL(triggered(bool)), + this, SLOT(onEncodeTriggered(bool))); - connect(m_encodeDock, SIGNAL(captureStateChanged(bool)), m_player, + connect(m_encodeDock, + SIGNAL(captureStateChanged(bool)), + m_player, SLOT(onCaptureStateChanged(bool))); - connect(m_encodeDock, SIGNAL(captureStateChanged(bool)), m_propertiesDock, SLOT(setDisabled(bool))); + connect(m_encodeDock, + SIGNAL(captureStateChanged(bool)), + m_propertiesDock, + SLOT(setDisabled(bool))); connect(m_encodeDock, SIGNAL(captureStateChanged(bool)), m_recentDock, SLOT(setDisabled(bool))); connect(m_encodeDock, SIGNAL(captureStateChanged(bool)), m_filtersDock, SLOT(setDisabled(bool))); - connect(m_encodeDock, SIGNAL(captureStateChanged(bool)), m_keyframesDock, SLOT(setDisabled(bool))); - connect(m_encodeDock, SIGNAL(captureStateChanged(bool)), ui->actionOpen, SLOT(setDisabled(bool))); - connect(m_encodeDock, SIGNAL(captureStateChanged(bool)), ui->actionOpenOther, + connect(m_encodeDock, + SIGNAL(captureStateChanged(bool)), + m_keyframesDock, + SLOT(setDisabled(bool))); + connect(m_encodeDock, + SIGNAL(captureStateChanged(bool)), + ui->actionOpen, + SLOT(setDisabled(bool))); + connect(m_encodeDock, + SIGNAL(captureStateChanged(bool)), + ui->actionOpenOther, SLOT(setDisabled(bool))); - connect(m_encodeDock, SIGNAL(captureStateChanged(bool)), ui->actionExit, SLOT(setDisabled(bool))); - connect(m_encodeDock, SIGNAL(captureStateChanged(bool)), this, SLOT(onCaptureStateChanged(bool))); + connect(m_encodeDock, + SIGNAL(captureStateChanged(bool)), + ui->actionExit, + SLOT(setDisabled(bool))); + connect(m_encodeDock, + SIGNAL(captureStateChanged(bool)), + this, + SLOT(onCaptureStateChanged(bool))); connect(m_encodeDock, SIGNAL(captureStateChanged(bool)), m_historyDock, SLOT(setDisabled(bool))); connect(this, SIGNAL(profileChanged()), m_encodeDock, SLOT(onProfileChanged())); connect(this, SIGNAL(profileChanged()), SLOT(onProfileChanged())); @@ -658,24 +782,29 @@ void MainWindow::setupAndConnectDocks() connect(m_playlistDock->model(), SIGNAL(modified()), m_encodeDock, SLOT(onProducerOpened())); connect(m_timelineDock, SIGNAL(clipCopied()), m_encodeDock, SLOT(onProducerOpened())); connect(m_timelineDock, SIGNAL(markerRangesChanged()), m_encodeDock, SLOT(onProducerOpened())); - connect(m_timelineDock->model(), &MultitrackModel::filteredChanged, m_encodeDock, + connect(m_timelineDock->model(), + &MultitrackModel::filteredChanged, + m_encodeDock, &EncodeDock::onProfileChanged); - connect(m_filterController, &FilterController::filterChanged, this, [&](Mlt::Service * filter) { - if (filter && filter->is_valid() && !::qstrcmp("reframe", filter->get(kShotcutFilterProperty))) { + connect(m_filterController, &FilterController::filterChanged, this, [&](Mlt::Service *filter) { + if (filter && filter->is_valid() + && !::qstrcmp("reframe", filter->get(kShotcutFilterProperty))) { m_encodeDock->onReframeChanged(); } }); - connect(m_filterController->attachedModel(), &AttachedFiltersModel::addedOrRemoved, - this, [&](Mlt::Producer * producer) { - m_encodeDock->onReframeChanged(); - }); + connect(m_filterController->attachedModel(), + &AttachedFiltersModel::addedOrRemoved, + this, + [&](Mlt::Producer *producer) { m_encodeDock->onReframeChanged(); }); m_jobsDock = new JobsDock(this); m_jobsDock->hide(); m_jobsDock->toggleViewAction()->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_0)); ui->menuView->addAction(m_jobsDock->toggleViewAction()); connect(&JOBS, SIGNAL(jobAdded()), m_jobsDock, SLOT(onJobAdded())); - connect(m_jobsDock->toggleViewAction(), SIGNAL(triggered(bool)), this, + connect(m_jobsDock->toggleViewAction(), + SIGNAL(triggered(bool)), + this, SLOT(onJobsDockTriggered(bool))); connect(ui->actionJobs, SIGNAL(triggered()), this, SLOT(onJobsDockTriggered())); @@ -683,7 +812,9 @@ void MainWindow::setupAndConnectDocks() m_notesDock->hide(); m_notesDock->toggleViewAction()->setShortcut(QKeySequence(Qt::CTRL | Qt::SHIFT | Qt::Key_3)); ui->menuView->insertAction(m_playlistDock->toggleViewAction(), m_notesDock->toggleViewAction()); - connect(m_notesDock->toggleViewAction(), SIGNAL(triggered(bool)), this, + connect(m_notesDock->toggleViewAction(), + SIGNAL(triggered(bool)), + this, SLOT(onNotesDockTriggered(bool))); connect(ui->actionNotes, SIGNAL(triggered()), this, SLOT(onNotesDockTriggered())); connect(m_notesDock, SIGNAL(modified()), this, SLOT(onNoteModified())); @@ -694,19 +825,29 @@ void MainWindow::setupAndConnectDocks() m_subtitlesDock->setModel(m_timelineDock->subtitlesModel(), m_timelineDock->subtitlesSelectionModel()); ui->menuView->addAction(m_subtitlesDock->toggleViewAction()); - connect(m_subtitlesDock->toggleViewAction(), SIGNAL(triggered(bool)), this, + connect(m_subtitlesDock->toggleViewAction(), + SIGNAL(triggered(bool)), + this, SLOT(onSubtitlesDockTriggered(bool))); connect(ui->actionSubtitles, SIGNAL(triggered()), this, SLOT(onSubtitlesDockTriggered())); connect(m_subtitlesDock, SIGNAL(seekRequested(int)), SLOT(seekTimeline(int))); - connect(m_timelineDock, SIGNAL(positionChanged(int)), m_subtitlesDock, + connect(m_timelineDock, + SIGNAL(positionChanged(int)), + m_subtitlesDock, SLOT(onPositionChanged(int))); - connect(m_subtitlesDock, SIGNAL(addAllTimeline(Mlt::Playlist *, bool, bool)), + connect(m_subtitlesDock, + SIGNAL(addAllTimeline(Mlt::Playlist *, bool, bool)), SLOT(onTimelineDockTriggered())); - connect(m_subtitlesDock, SIGNAL(addAllTimeline(Mlt::Playlist *, bool, bool)), + connect(m_subtitlesDock, + SIGNAL(addAllTimeline(Mlt::Playlist *, bool, bool)), SLOT(onAddAllToTimeline(Mlt::Playlist *, bool, bool))); - connect(m_subtitlesDock, &SubtitlesDock::createOrEditFilterOnOutput, this, + connect(m_subtitlesDock, + &SubtitlesDock::createOrEditFilterOnOutput, + this, &MainWindow::onCreateOrEditFilterOnOutput); - connect(m_encodeDock, &EncodeDock::createOrEditFilterOnOutput, this, + connect(m_encodeDock, + &EncodeDock::createOrEditFilterOnOutput, + this, &MainWindow::onCreateOrEditFilterOnOutput); connect(m_timelineDock->subtitlesModel(), SIGNAL(modified()), this, SLOT(onSubtitleModified())); @@ -755,19 +896,20 @@ void MainWindow::setupMenuFile() filters << match.captured(1) + "*.mlt"; else filters << QFileInfo(m_currentFile).baseName().split(" - ").first() + "*.mlt"; - for (auto &fileInfo : dir.entryInfoList(filters, QDir::Files, QDir::Time)) - { + for (auto &fileInfo : dir.entryInfoList(filters, QDir::Files, QDir::Time)) { auto filename = fileInfo.fileName(); if (filename != name) { auto text = filename; if (!kBackupFileRegex.match(filename).hasMatch()) - text += QString::fromLatin1("%1(%2)").arg(sep, fileInfo.lastModified().toString(Qt::ISODate)); + text += QString::fromLatin1("%1(%2)").arg(sep, + fileInfo.lastModified().toString( + Qt::ISODate)); ui->menuOtherVersions->addAction(text)->setData(dir.filePath(filename)); } } QCoreApplication::processEvents(); }); - connect(ui->menuOtherVersions, &QMenu::triggered, this, [&](QAction * action) { + connect(ui->menuOtherVersions, &QMenu::triggered, this, [&](QAction *action) { open(action->data().toString()); }); } @@ -782,23 +924,43 @@ void MainWindow::setupMenuView() void MainWindow::connectVideoWidgetSignals() { auto videoWidget = static_cast(&MLT); - connect(videoWidget, &Mlt::VideoWidget::dragStarted, m_playlistDock, + connect(videoWidget, + &Mlt::VideoWidget::dragStarted, + m_playlistDock, &PlaylistDock::onPlayerDragStarted); connect(videoWidget, &Mlt::VideoWidget::seekTo, m_player, &Player::seek); connect(videoWidget, &Mlt::VideoWidget::gpuNotSupported, this, &MainWindow::onGpuNotSupported); - connect(videoWidget->quickWindow(), &QQuickWindow::sceneGraphInitialized, videoWidget, - &Mlt::VideoWidget::initialize, Qt::DirectConnection); - connect(videoWidget->quickWindow(), &QQuickWindow::beforeRendering, videoWidget, - &Mlt::VideoWidget::beforeRendering, Qt::DirectConnection); - connect(videoWidget->quickWindow(), &QQuickWindow::beforeRenderPassRecording, videoWidget, - &Mlt::VideoWidget::renderVideo, Qt::DirectConnection); - connect(videoWidget->quickWindow(), &QQuickWindow::sceneGraphInitialized, this, - &MainWindow::onSceneGraphInitialized, Qt::QueuedConnection); - connect(videoWidget->quickWindow(), &QQuickWindow::sceneGraphInitialized, m_timelineDock, + connect(videoWidget->quickWindow(), + &QQuickWindow::sceneGraphInitialized, + videoWidget, + &Mlt::VideoWidget::initialize, + Qt::DirectConnection); + connect(videoWidget->quickWindow(), + &QQuickWindow::beforeRendering, + videoWidget, + &Mlt::VideoWidget::beforeRendering, + Qt::DirectConnection); + connect(videoWidget->quickWindow(), + &QQuickWindow::beforeRenderPassRecording, + videoWidget, + &Mlt::VideoWidget::renderVideo, + Qt::DirectConnection); + connect(videoWidget->quickWindow(), + &QQuickWindow::sceneGraphInitialized, + this, + &MainWindow::onSceneGraphInitialized, + Qt::QueuedConnection); + connect(videoWidget->quickWindow(), + &QQuickWindow::sceneGraphInitialized, + m_timelineDock, &TimelineDock::initLoad); - connect(videoWidget, &Mlt::VideoWidget::frameDisplayed, m_scopeController, + connect(videoWidget, + &Mlt::VideoWidget::frameDisplayed, + m_scopeController, &ScopeController::newFrame); - connect(m_filterController, &FilterController::currentFilterChanged, videoWidget, + connect(m_filterController, + &FilterController::currentFilterChanged, + videoWidget, &Mlt::VideoWidget::setCurrentFilter); } @@ -884,15 +1046,14 @@ void MainWindow::setupSettingsMenu() for (auto a : group->actions()) { a->setCheckable(true); const auto data = a->data().toString(); - if (data == Settings.playerAudioDriver()) + if (data == Settings.playerAudioDriver()) a->setChecked(true); - if ((data == "directsound" && Settings.playerAudioChannels() > 2) || - (data == "winmm" && Settings.playerAudioChannels() <= 2) || - (data == "pulseaudio")) { + if ((data == "directsound" && Settings.playerAudioChannels() > 2) + || (data == "winmm" && Settings.playerAudioChannels() <= 2) || (data == "pulseaudio")) { a->setText(a->text() + QString::fromLatin1(" (%1)").arg(tr("default"))); } } - connect(group, &QActionGroup::triggered, this, [&](QAction * action) { + connect(group, &QActionGroup::triggered, this, [&](QAction *action) { Settings.setPlayerAudioDriver(action->data().toString()); QMessageBox dialog(QMessageBox::Information, qApp->applicationName(), @@ -924,7 +1085,7 @@ void MainWindow::setupSettingsMenu() if (Settings.backupPeriod() == a->data().toInt()) a->setChecked(true); } - connect(group, &QActionGroup::triggered, this, [&](QAction * action) { + connect(group, &QActionGroup::triggered, this, [&](QAction *action) { Settings.setBackupPeriod(action->data().toInt()); }); @@ -957,7 +1118,7 @@ void MainWindow::setupSettingsMenu() ui->actionTimeNDF->setChecked(true); break; } - connect(group, &QActionGroup::triggered, this, [&](QAction * action) { + connect(group, &QActionGroup::triggered, this, [&](QAction *action) { Settings.setTimeFormat(action->data().toInt()); }); @@ -969,7 +1130,10 @@ void MainWindow::setupSettingsMenu() m_profileGroup = new QActionGroup(this); m_profileGroup->addAction(ui->actionProfileAutomatic); ui->actionProfileAutomatic->setData(QString()); - buildVideoModeMenu(ui->menuProfile, m_customProfileMenu, m_profileGroup, ui->actionAddCustomProfile, + buildVideoModeMenu(ui->menuProfile, + m_customProfileMenu, + m_profileGroup, + ui->actionAddCustomProfile, ui->actionProfileRemove); // Add the SDI and HDMI devices to the Settings menu. @@ -981,10 +1145,13 @@ void MainWindow::setupSettingsMenu() QList screens = QGuiApplication::screens(); int n = screens.size(); for (int i = 0; n > 1 && i < n; i++) { - QAction *action = new QAction(tr("Screen %1 (%2 x %3 @ %4 Hz)").arg(i) - .arg(screens[i]->size().width() * screens[i]->devicePixelRatio()) - .arg(screens[i]->size().height() * screens[i]->devicePixelRatio()) - .arg(screens[i]->refreshRate()), this); + QAction *action + = new QAction(tr("Screen %1 (%2 x %3 @ %4 Hz)") + .arg(i) + .arg(screens[i]->size().width() * screens[i]->devicePixelRatio()) + .arg(screens[i]->size().height() * screens[i]->devicePixelRatio()) + .arg(screens[i]->refreshRate()), + this); action->setCheckable(true); action->setData(i); m_externalGroup->addAction(action); @@ -1031,7 +1198,10 @@ void MainWindow::setupSettingsMenu() m_keyerMenu->setDisabled(true); connect(m_keyerGroup, SIGNAL(triggered(QAction *)), this, SLOT(onKeyerTriggered(QAction *))); } - connect(m_externalGroup, SIGNAL(triggered(QAction *)), this, SLOT(onExternalTriggered(QAction *))); + connect(m_externalGroup, + SIGNAL(triggered(QAction *)), + this, + SLOT(onExternalTriggered(QAction *))); connect(m_profileGroup, SIGNAL(triggered(QAction *)), this, SLOT(onProfileTriggered(QAction *))); // Setup the language menu actions @@ -1046,10 +1216,12 @@ void MainWindow::setupSettingsMenu() a = new QAction(QLocale::languageToString(QLocale::Catalan), m_languagesGroup); a->setCheckable(true); a->setData("ca"); - a = new QAction(QLocale::languageToString(QLocale::Chinese).append(" (China)"), m_languagesGroup); + a = new QAction(QLocale::languageToString(QLocale::Chinese).append(" (China)"), + m_languagesGroup); a->setCheckable(true); a->setData("zh_CN"); - a = new QAction(QLocale::languageToString(QLocale::Chinese).append(" (Taiwan)"), m_languagesGroup); + a = new QAction(QLocale::languageToString(QLocale::Chinese).append(" (Taiwan)"), + m_languagesGroup); a->setCheckable(true); a->setData("zh_TW"); a = new QAction(QLocale::languageToString(QLocale::Czech), m_languagesGroup); @@ -1166,7 +1338,10 @@ void MainWindow::setupSettingsMenu() break; } } - connect(m_languagesGroup, SIGNAL(triggered(QAction *)), this, SLOT(onLanguageTriggered(QAction *))); + connect(m_languagesGroup, + SIGNAL(triggered(QAction *)), + this, + SLOT(onLanguageTriggered(QAction *))); // Setup the themes actions #if defined(SHOTCUT_THEME) @@ -1207,7 +1382,10 @@ void MainWindow::setupSettingsMenu() group->addAction(ui->actionDrawingOpenGL); ui->actionDrawingSoftware->setData(Qt::AA_UseSoftwareOpenGL); group->addAction(ui->actionDrawingSoftware); - connect(group, SIGNAL(triggered(QAction *)), this, SLOT(onDrawingMethodTriggered(QAction *))); + connect(group, + SIGNAL(triggered(QAction *)), + this, + SLOT(onDrawingMethodTriggered(QAction *))); switch (Settings.drawMethod()) { case Qt::AA_UseDesktopOpenGL: ui->actionDrawingOpenGL->setChecked(true); @@ -1256,7 +1434,6 @@ void MainWindow::setupSettingsMenu() ui->actionClearRecentOnExit->setChecked(Settings.clearRecent()); } - // Initialize the proxy submenu ui->actionUseProxy->setChecked(Settings.proxyEnabled()); ui->actionProxyUseProjectFolder->setChecked(Settings.proxyUseProjectFolder()); @@ -1277,41 +1454,48 @@ void MainWindow::setupOpenOtherMenu() if (mltProducers->get_data("color")) { otherMenu->addAction(tr("Color"), this, SLOT(onOpenOtherTriggered()))->setObjectName("color"); if (mltProducers->get_data("qtext") && mltFilters->get_data("dynamictext")) - otherMenu->addAction(tr("Text"), this, SLOT(onOpenOtherTriggered()))->setObjectName("text"); + otherMenu->addAction(tr("Text"), this, SLOT(onOpenOtherTriggered())) + ->setObjectName("text"); } if (mltProducers->get_data("glaxnimate")) - otherMenu->addAction(tr("Animation") + " (Glaxnimate)", this, - SLOT(onOpenOtherTriggered()))->setObjectName("glaxnimate"); + otherMenu->addAction(tr("Animation") + " (Glaxnimate)", this, SLOT(onOpenOtherTriggered())) + ->setObjectName("glaxnimate"); if (mltProducers->get_data("noise")) otherMenu->addAction(tr("Noise"), this, SLOT(onOpenOtherTriggered()))->setObjectName("noise"); if (mltProducers->get_data("frei0r.ising0r")) - otherMenu->addAction(tr("Ising"), this, SLOT(onOpenOtherTriggered()))->setObjectName("ising0r"); + otherMenu->addAction(tr("Ising"), this, SLOT(onOpenOtherTriggered())) + ->setObjectName("ising0r"); if (mltProducers->get_data("frei0r.lissajous0r")) - otherMenu->addAction(tr("Lissajous"), this, - SLOT(onOpenOtherTriggered()))->setObjectName("lissajous0r"); + otherMenu->addAction(tr("Lissajous"), this, SLOT(onOpenOtherTriggered())) + ->setObjectName("lissajous0r"); if (mltProducers->get_data("frei0r.plasma")) - otherMenu->addAction(tr("Plasma"), this, SLOT(onOpenOtherTriggered()))->setObjectName("plasma"); + otherMenu->addAction(tr("Plasma"), this, SLOT(onOpenOtherTriggered())) + ->setObjectName("plasma"); if (mltProducers->get_data("frei0r.test_pat_B")) - otherMenu->addAction(tr("Color Bars"), this, - SLOT(onOpenOtherTriggered()))->setObjectName("test_pat_B"); + otherMenu->addAction(tr("Color Bars"), this, SLOT(onOpenOtherTriggered())) + ->setObjectName("test_pat_B"); if (mltProducers->get_data("tone")) - otherMenu->addAction(tr("Audio Tone"), this, SLOT(onOpenOtherTriggered()))->setObjectName("tone"); + otherMenu->addAction(tr("Audio Tone"), this, SLOT(onOpenOtherTriggered())) + ->setObjectName("tone"); if (mltProducers->get_data("count")) otherMenu->addAction(tr("Count"), this, SLOT(onOpenOtherTriggered()))->setObjectName("count"); if (mltProducers->get_data("blipflash")) - otherMenu->addAction(tr("Blip Flash"), this, - SLOT(onOpenOtherTriggered()))->setObjectName("blipflash"); + otherMenu->addAction(tr("Blip Flash"), this, SLOT(onOpenOtherTriggered())) + ->setObjectName("blipflash"); #if defined(Q_OS_UNIX) && !defined(Q_OS_MAC) - otherMenu->addAction(tr("Video4Linux"), this, SLOT(onOpenOtherTriggered()))->setObjectName("v4l2"); - otherMenu->addAction(tr("PulseAudio"), this, SLOT(onOpenOtherTriggered()))->setObjectName("pulse"); + otherMenu->addAction(tr("Video4Linux"), this, SLOT(onOpenOtherTriggered())) + ->setObjectName("v4l2"); + otherMenu->addAction(tr("PulseAudio"), this, SLOT(onOpenOtherTriggered())) + ->setObjectName("pulse"); otherMenu->addAction(tr("ALSA Audio"), this, SLOT(onOpenOtherTriggered()))->setObjectName("alsa"); #elif defined(Q_OS_WIN) || defined(Q_OS_MAC) - otherMenu->addAction(tr("Audio/Video Device"), this, - SLOT(onOpenOtherTriggered()))->setObjectName("device"); + otherMenu->addAction(tr("Audio/Video Device"), this, SLOT(onOpenOtherTriggered())) + ->setObjectName("device"); #endif if (mltProducers->get_data("decklink")) - otherMenu->addAction(tr("SDI/HDMI"), this, SLOT(onOpenOtherTriggered()))->setObjectName("decklink"); + otherMenu->addAction(tr("SDI/HDMI"), this, SLOT(onOpenOtherTriggered())) + ->setObjectName("decklink"); } QAction *MainWindow::addProfile(QActionGroup *actionGroup, const QString &desc, const QString &name) @@ -1337,12 +1521,12 @@ void MainWindow::open(Mlt::Producer *producer) else if (producer->get_int("error")) showStatusMessage(tr("Failed to open ") + producer->get("resource")); -// bool ok = false; -// int screen = Settings.playerExternal().toInt(&ok); -// if (ok && screen < QGuiApplication::screens().count() -// && QGuiApplication::screens().at(screen) != this->screen()) { -// m_player->moveVideoToScreen(screen); -// } + // bool ok = false; + // int screen = Settings.playerExternal().toInt(&ok); + // if (ok && screen < QGuiApplication::screens().count() + // && QGuiApplication::screens().at(screen) != this->screen()) { + // m_player->moveVideoToScreen(screen); + // } // no else here because open() will delete the producer if open fails if (!MLT.setProducer(producer)) { @@ -1365,11 +1549,12 @@ bool MainWindow::isCompatibleWithGpuMode(MltXmlChecker &checker) { if (checker.needsGPU() && !Settings.playerGPU()) { LOG_INFO() << "file uses GPU but GPU not enabled"; - QMessageBox dialog(QMessageBox::Warning, - qApp->applicationName(), - tr("The file you opened uses GPU effects, but GPU effects are not enabled."), - QMessageBox::Ok, - this); + QMessageBox + dialog(QMessageBox::Warning, + qApp->applicationName(), + tr("The file you opened uses GPU effects, but GPU effects are not enabled."), + QMessageBox::Ok, + this); dialog.setWindowModality(QmlApplication::dialogModality()); dialog.setDefaultButton(QMessageBox::Ok); dialog.setEscapeButton(QMessageBox::Ok); @@ -1379,10 +1564,10 @@ bool MainWindow::isCompatibleWithGpuMode(MltXmlChecker &checker) LOG_INFO() << "file uses GPU incompatible filters but GPU is enabled"; QMessageBox dialog(QMessageBox::Question, qApp->applicationName(), - tr("The file you opened uses CPU effects that are incompatible with GPU effects, but GPU effects are enabled.\n" + tr("The file you opened uses CPU effects that are incompatible with GPU " + "effects, but GPU effects are enabled.\n" "Do you want to disable GPU effects and restart?"), - QMessageBox::No | - QMessageBox::Yes, + QMessageBox::No | QMessageBox::Yes, this); dialog.setWindowModality(QmlApplication::dialogModality()); dialog.setDefaultButton(QMessageBox::Yes); @@ -1401,12 +1586,15 @@ bool MainWindow::isCompatibleWithGpuMode(MltXmlChecker &checker) bool MainWindow::saveRepairedXmlFile(MltXmlChecker &checker, QString &fileName) { QFileInfo fi(fileName); - auto filename = QStringLiteral("%1/%2 - %3.%4").arg(fi.path(), fi.completeBaseName(), - tr("Repaired"), - fi.suffix()); + auto filename = QStringLiteral("%1/%2 - %3.%4") + .arg(fi.path(), fi.completeBaseName(), tr("Repaired"), fi.suffix()); auto caption = tr("Save Repaired XML"); - filename = QFileDialog::getSaveFileName(this, caption, filename, - tr("MLT XML (*.mlt)"), nullptr, Util::getFileDialogOptions()); + filename = QFileDialog::getSaveFileName(this, + caption, + filename, + tr("MLT XML (*.mlt)"), + nullptr, + Util::getFileDialogOptions()); if (!filename.isEmpty()) { QFile repaired(filename); repaired.open(QIODevice::WriteOnly); @@ -1454,8 +1642,7 @@ bool MainWindow::isXmlRepaired(MltXmlChecker &checker, QString &fileName) "Do you want Shotcut to try to repair it?\n\n" "If you choose Yes, Shotcut will create a copy of your project\n" "with \"- Repaired\" in the file name and open it."), - QMessageBox::No | - QMessageBox::Yes, + QMessageBox::No | QMessageBox::Yes, this); dialog.setWindowModality(QmlApplication::dialogModality()); dialog.setDefaultButton(QMessageBox::Yes); @@ -1484,9 +1671,11 @@ bool MainWindow::checkAutoSave(QString &url) // check whether autosave files exist: QSharedPointer stale(AutoSaveFile::getFile(url)); if (stale) { - QMessageBox dialog(QMessageBox::Question, qApp->applicationName(), + QMessageBox dialog(QMessageBox::Question, + qApp->applicationName(), tr("Auto-saved files exist. Do you want to recover them now?"), - QMessageBox::No | QMessageBox::Yes, this); + QMessageBox::No | QMessageBox::Yes, + this); dialog.setWindowModality(QmlApplication::dialogModality()); dialog.setDefaultButton(QMessageBox::Yes); dialog.setEscapeButton(QMessageBox::No); @@ -1535,7 +1724,8 @@ void MainWindow::setFullScreen(bool isFullScreen) QString MainWindow::untitledFileName() const { QDir dir = Settings.appDataLocation(); - if (!dir.exists()) dir.mkpath(dir.path()); + if (!dir.exists()) + dir.mkpath(dir.path()); return dir.filePath("__untitled__.mlt"); } @@ -1549,7 +1739,7 @@ void MainWindow::setProfile(const QString &profile_name) bool MainWindow::isSourceClipMyProject(QString resource, bool withDialog) { if (m_player->tabIndex() == Player::ProjectTabIndex && MLT.savedProducer() - && MLT.savedProducer()->is_valid()) + && MLT.savedProducer()->is_valid()) resource = QString::fromUtf8(MLT.savedProducer()->get("resource")); if (!resource.isEmpty() && QDir(resource) == QDir(fileName())) { if (withDialog) { @@ -1629,14 +1819,13 @@ void MainWindow::setVideoModeMenu() for (const auto action : m_profileGroup->actions()) { auto s = action->data().toString(); Mlt::Profile profile(s.toUtf8().constData()); - if (MLT.profile().width() == profile.width() && - MLT.profile().height() == profile.height() && - MLT.profile().sample_aspect_num() == profile.sample_aspect_num() && - MLT.profile().sample_aspect_den() == profile.sample_aspect_den() && - MLT.profile().frame_rate_num() == profile.frame_rate_num() && - MLT.profile().frame_rate_den() == profile.frame_rate_den() && - MLT.profile().colorspace() == profile.colorspace() && - MLT.profile().progressive() == profile.progressive()) { + if (MLT.profile().width() == profile.width() && MLT.profile().height() == profile.height() + && MLT.profile().sample_aspect_num() == profile.sample_aspect_num() + && MLT.profile().sample_aspect_den() == profile.sample_aspect_den() + && MLT.profile().frame_rate_num() == profile.frame_rate_num() + && MLT.profile().frame_rate_den() == profile.frame_rate_den() + && MLT.profile().colorspace() == profile.colorspace() + && MLT.profile().progressive() == profile.progressive()) { // Select it action->setChecked(true); return; @@ -1671,7 +1860,8 @@ void MainWindow::showIncompatibleProjectMessage(const QString &shotcutVersion) QMessageBox dialog(QMessageBox::Information, qApp->applicationName(), tr("This project file requires a newer version!\n\n" - "It was made with version ") + shotcutVersion, + "It was made with version ") + + shotcutVersion, QMessageBox::Ok, this); dialog.setDefaultButton(QMessageBox::Ok); @@ -1697,13 +1887,14 @@ void MainWindow::onAutosaveTimeout() } static QMessageBox *dialog = nullptr; if (!dialog) { - dialog = new QMessageBox(QMessageBox::Critical, - qApp->applicationName(), - tr("You are running low on available memory!\n\n" - "Please close other applications or web browser tabs and retry.\n" - "Or save and restart Shotcut."), - QMessageBox::Retry | QMessageBox::Save | QMessageBox::Ignore, - this); + dialog + = new QMessageBox(QMessageBox::Critical, + qApp->applicationName(), + tr("You are running low on available memory!\n\n" + "Please close other applications or web browser tabs and retry.\n" + "Or save and restart Shotcut."), + QMessageBox::Retry | QMessageBox::Save | QMessageBox::Ignore, + this); dialog->setDefaultButton(QMessageBox::Retry); dialog->setEscapeButton(QMessageBox::Ignore); dialog->setWindowModality(QmlApplication::dialogModality()); @@ -1808,12 +1999,15 @@ bool MainWindow::open(QString url, const Mlt::Properties *properties, bool play, sourceUpdated(); MLT.resetURL(); // Return to automatic video mode if selected. - if (m_profileGroup->checkedAction() && m_profileGroup->checkedAction()->data().toString().isEmpty()) + if (m_profileGroup->checkedAction() + && m_profileGroup->checkedAction()->data().toString().isEmpty()) MLT.profile().set_explicit(false); } QString urlToOpen = checker.isUpdated() ? checker.tempFile().fileName() : url; - if (!MLT.open(QDir::fromNativeSeparators(urlToOpen), QDir::fromNativeSeparators(url), skipConvert) - && MLT.producer() && MLT.producer()->is_valid()) { + if (!MLT.open(QDir::fromNativeSeparators(urlToOpen), + QDir::fromNativeSeparators(url), + skipConvert) + && MLT.producer() && MLT.producer()->is_valid()) { Mlt::Properties *props = const_cast(properties); if (props && props->is_valid()) mlt_properties_inherit(MLT.producer()->get_properties(), props->get_properties()); @@ -1884,8 +2078,12 @@ void MainWindow::openVideo() path.append("/*"); #endif LOG_DEBUG() << Util::getFileDialogOptions(); - QStringList filenames = QFileDialog::getOpenFileNames(this, tr("Open File"), path, - tr("All Files (*);;MLT XML (*.mlt)"), nullptr, Util::getFileDialogOptions()); + QStringList filenames = QFileDialog::getOpenFileNames(this, + tr("Open File"), + path, + tr("All Files (*);;MLT XML (*.mlt)"), + nullptr, + Util::getFileDialogOptions()); if (filenames.length() > 0) { Settings.setOpenPath(QFileInfo(filenames.first()).path()); @@ -1944,7 +2142,8 @@ void MainWindow::showStatusMessage(QAction *action, int timeoutSeconds) m_player->setStatusLabel(action->text(), timeoutSeconds, action); } -void MainWindow::showStatusMessage(const QString &message, int timeoutSeconds, +void MainWindow::showStatusMessage(const QString &message, + int timeoutSeconds, QPalette::ColorRole role) { LOG_INFO() << message; @@ -1961,10 +2160,11 @@ void MainWindow::onStatusMessageClicked() void MainWindow::seekPlaylist(int start) { - if (!playlist()) return; + if (!playlist()) + return; // we bypass this->open() to prevent sending producerOpened signal to self, which causes to reload playlist if (!MLT.producer() - || (void *) MLT.producer()->get_producer() != (void *) playlist()->get_playlist()) + || (void *) MLT.producer()->get_producer() != (void *) playlist()->get_playlist()) MLT.setProducer(new Mlt::Producer(*playlist())); m_player->setIn(-1); m_player->setOut(-1); @@ -1981,10 +2181,11 @@ void MainWindow::seekPlaylist(int start) void MainWindow::seekTimeline(int position, bool seekPlayer) { - if (!multitrack()) return; + if (!multitrack()) + return; // we bypass this->open() to prevent sending producerOpened signal to self, which causes to reload playlist if (MLT.producer() - && (void *) MLT.producer()->get_producer() != (void *) multitrack()->get_producer()) { + && (void *) MLT.producer()->get_producer() != (void *) multitrack()->get_producer()) { MLT.setProducer(new Mlt::Producer(*multitrack())); m_player->setIn(-1); m_player->setOut(-1); @@ -2179,7 +2380,7 @@ void MainWindow::setupActions() Actions.loadFromMenu(ui->menuSettings); Actions.loadFromMenu(ui->menuHelp); - auto shortcuts {ui->actionKeyboardShortcuts->shortcuts()}; + auto shortcuts{ui->actionKeyboardShortcuts->shortcuts()}; shortcuts << QKeySequence(Qt::Key_Slash); ui->actionKeyboardShortcuts->setShortcuts(shortcuts); @@ -2309,56 +2510,66 @@ void MainWindow::updateWindowTitle() shownName = QFileInfo(m_currentFile).filePath(); shownName = fontMetrics().elidedText(shownName, Qt::ElideLeft, width() / 4); } - QString profileText = tr("%1x%2 %3fps %4ch").arg( - QString::number(MLT.profile().width(), 'f', 0), - QString::number(MLT.profile().height(), 'f', 0), - QString::number(MLT.profile().fps(), 'g', 2), - QString::number(Settings.playerAudioChannels(), 'f', 0)); + QString profileText = tr("%1x%2 %3fps %4ch") + .arg(QString::number(MLT.profile().width(), 'f', 0), + QString::number(MLT.profile().height(), 'f', 0), + QString::number(MLT.profile().fps(), 'g', 2), + QString::number(Settings.playerAudioChannels(), 'f', 0)); #ifdef Q_OS_MAC - setWindowTitle(QStringLiteral("%1 - %2 - %3").arg(shownName).arg(profileText).arg( - qApp->applicationName())); + setWindowTitle( + QStringLiteral("%1 - %2 - %3").arg(shownName).arg(profileText).arg(qApp->applicationName())); #else - setWindowTitle(QStringLiteral("%1[*] - %2 - %3").arg(shownName).arg(profileText).arg( - qApp->applicationName())); + setWindowTitle(QStringLiteral("%1[*] - %2 - %3") + .arg(shownName) + .arg(profileText) + .arg(qApp->applicationName())); #endif } void MainWindow::on_actionAbout_Shotcut_triggered() { - const auto copyright = - QStringLiteral("Copyright © 2011-2025 Meltytech, LLC"); - const auto license = - QStringLiteral("GNU General Public License v3.0"); + const auto copyright = QStringLiteral( + "Copyright © 2011-2025 Meltytech, LLC"); + const auto license = QStringLiteral( + "GNU General Public License v3.0"); const auto url = QStringLiteral("https://www.shotcut.org/"); - QMessageBox::about(this, tr("About %1").arg(qApp->applicationName()), - QStringLiteral("

Shotcut version %2

" - "

%1 is a free, open source, cross platform video editor.

" - "

%4

" - "

Licensed under the %5

" - "

This program proudly uses the following projects:

    " - "
  • Qt application and UI framework
  • " - "
  • MLT multimedia authoring framework
  • " - "
  • FFmpeg multimedia format and codec libraries
  • " - "
  • x264 H.264 encoder
  • " - "
  • dav1d AV1 decoder
  • " - "
  • SVT-AV1 AV1 encoder
  • " - "
  • Opus audio codec
  • " - "
  • Frei0r video plugins
  • " - "
  • LADSPA audio plugins
  • " - "
  • Glaxnimate vector animation program
  • " - "

" - "

The source code used to build this program can be downloaded from " - "%3.

" - "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.
" - ).arg(qApp->applicationName(), qApp->applicationVersion(), url, copyright, license)); + QMessageBox::about( + this, + tr("About %1").arg(qApp->applicationName()), + QStringLiteral( + "

Shotcut version %2

" + "

%1 is a free, open source, cross platform video editor.

" + "

%4

" + "

Licensed under the %5

" + "

This program proudly uses the following projects:

    " + "
  • Qt application and UI framework
  • " + "
  • MLT multimedia authoring " + "framework
  • " + "
  • FFmpeg multimedia format and codec " + "libraries
  • " + "
  • x264 H.264 " + "encoder
  • " + "
  • dav1d AV1 " + "decoder
  • " + "
  • SVT-AV1 AV1 encoder
  • " + "
  • Opus audio codec
  • " + "
  • Frei0r video plugins
  • " + "
  • LADSPA audio plugins
  • " + "
  • Glaxnimate vector animation " + "program
  • " + "

" + "

The source code used to build this program can be downloaded from " + "%3.

" + "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.
") + .arg(qApp->applicationName(), qApp->applicationVersion(), url, copyright, license)); } - void MainWindow::keyPressEvent(QKeyEvent *event) { - if (event->isAccepted()) return; + if (event->isAccepted()) + return; bool handled = true; @@ -2424,8 +2635,11 @@ QAction *MainWindow::actionProfileRemove() const return ui->actionProfileRemove; } -void MainWindow::buildVideoModeMenu(QMenu *topMenu, QMenu *&customMenu, QActionGroup *group, - QAction *addAction, QAction *removeAction) +void MainWindow::buildVideoModeMenu(QMenu *topMenu, + QMenu *&customMenu, + QActionGroup *group, + QAction *addAction, + QAction *removeAction) { topMenu->addAction(addProfile(group, "HD 720p 50 fps", "atsc_720p_50")); topMenu->addAction(addProfile(group, "HD 720p 59.94 fps", "atsc_720p_5994")); @@ -2510,7 +2724,9 @@ void MainWindow::newProject(const QString &filename, bool isProjectFolder) } } -void MainWindow::addCustomProfile(const QString &name, QMenu *menu, QAction *action, +void MainWindow::addCustomProfile(const QString &name, + QMenu *menu, + QAction *action, QActionGroup *group) { // Add new profile to the menu. @@ -2529,7 +2745,9 @@ void MainWindow::addCustomProfile(const QString &name, QMenu *menu, QAction *act } } -void MainWindow::removeCustomProfiles(const QStringList &profiles, QDir &dir, QMenu *menu, +void MainWindow::removeCustomProfiles(const QStringList &profiles, + QDir &dir, + QMenu *menu, QAction *action) { foreach (const QString &profile, profiles) { @@ -2582,8 +2800,8 @@ bool MainWindow::eventFilter(QObject *target, QEvent *event) #if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)) qApp->sendEvent(focusedQuickWidget->quickWindow()->activeFocusItem(), event); #else - focusedQuickWidget->quickWindow()->sendEvent(focusedQuickWidget->quickWindow()->activeFocusItem(), - event); + focusedQuickWidget->quickWindow() + ->sendEvent(focusedQuickWidget->quickWindow()->activeFocusItem(), event); #endif QWidget *w = focusedQuickWidget->parentWidget(); if (!event->isAccepted()) @@ -2624,11 +2842,10 @@ void MainWindow::dropEvent(QDropEvent *event) } else if (mimeData->hasUrls()) { // Use QTimer to workaround stupid drag from Windows Explorer bug const auto &urls = mimeData->urls(); - QTimer::singleShot(0, this, [ = ]() { - openMultiple(urls); - }); + QTimer::singleShot(0, this, [=]() { openMultiple(urls); }); event->acceptProposedAction(); - } else if (mimeData->hasFormat(Mlt::XmlMimeType) && MLT.XML() != mimeData->data(Mlt::XmlMimeType)) { + } else if (mimeData->hasFormat(Mlt::XmlMimeType) + && MLT.XML() != mimeData->data(Mlt::XmlMimeType)) { m_playlistDock->onOpenActionTriggered(); event->acceptProposedAction(); } @@ -2696,7 +2913,7 @@ void MainWindow::showEvent(QShowEvent *event) #endif onAutosaveTimeout(); - QTimer::singleShot(400, this, [ = ]() { + QTimer::singleShot(400, this, [=]() { Database::singleton(this); #if defined(Q_OS_WIN) || defined(Q_OS_MAC) this->setProperty("windowOpacity", 1.0); @@ -2773,7 +2990,7 @@ void MainWindow::onProducerChanged() { MLT.refreshConsumer(); if (playlist() && MLT.producer() && MLT.producer()->is_valid() - && MLT.producer()->get_int(kPlaylistIndexProperty)) { + && MLT.producer()->get_int(kPlaylistIndexProperty)) { emit m_playlistDock->enableUpdate(true); } sourceUpdated(); @@ -2809,8 +3026,12 @@ bool MainWindow::on_actionSave_As_triggered() if (!m_currentFile.isEmpty()) path = m_currentFile; QString caption = tr("Save XML"); - QString filename = QFileDialog::getSaveFileName(this, caption, path, - tr("MLT XML (*.mlt)"), nullptr, Util::getFileDialogOptions()); + QString filename = QFileDialog::getSaveFileName(this, + caption, + path, + tr("MLT XML (*.mlt)"), + nullptr, + Util::getFileDialogOptions()); if (!filename.isEmpty()) { QFileInfo fi(filename); Settings.setSavePath(fi.path()); @@ -2866,7 +3087,9 @@ void MainWindow::cropSource(const QRectF &rect) auto newHeight = Util::coerceMultiple(rect.height()); QMessageBox dialog(QMessageBox::Question, qApp->applicationName(), - tr("Do you also want to change the Video Mode to %1 x %2?").arg(newWidth).arg(newHeight), + tr("Do you also want to change the Video Mode to %1 x %2?") + .arg(newWidth) + .arg(newHeight), QMessageBox::No | QMessageBox::Yes, this); dialog.setWindowModality(QmlApplication::dialogModality()); @@ -2948,9 +3171,7 @@ bool MainWindow::continueModified() qApp->applicationName(), tr("The project has been modified.\n" "Do you want to save your changes?"), - QMessageBox::No | - QMessageBox::Cancel | - QMessageBox::Yes, + QMessageBox::No | QMessageBox::Cancel | QMessageBox::Yes, this); dialog.setWindowModality(QmlApplication::dialogModality()); dialog.setDefaultButton(QMessageBox::Yes); @@ -2977,8 +3198,7 @@ bool MainWindow::continueJobsRunning() qApp->applicationName(), tr("There are incomplete jobs.\n" "Do you still want to exit?"), - QMessageBox::No | - QMessageBox::Yes, + QMessageBox::No | QMessageBox::Yes, this); dialog.setWindowModality(QmlApplication::dialogModality()); dialog.setDefaultButton(QMessageBox::Yes); @@ -2990,8 +3210,7 @@ bool MainWindow::continueJobsRunning() qApp->applicationName(), tr("An export is in progress.\n" "Do you still want to exit?"), - QMessageBox::No | - QMessageBox::Yes, + QMessageBox::No | QMessageBox::Yes, this); dialog.setWindowModality(QmlApplication::dialogModality()); dialog.setDefaultButton(QMessageBox::Yes); @@ -3017,7 +3236,7 @@ void MainWindow::onEncodeTriggered(bool checked) void MainWindow::onCaptureStateChanged(bool started) { if (started && MLT.resource().startsWith("avfoundation") - && !MLT.producer()->get_int(kBackgroundCaptureProperty)) + && !MLT.producer()->get_int(kBackgroundCaptureProperty)) showMinimized(); } @@ -3119,7 +3338,8 @@ void MainWindow::onFilesDockTriggered(bool checked) void MainWindow::onPlaylistCreated() { - if (!playlist() || playlist()->count() == 0) return; + if (!playlist() || playlist()->count() == 0) + return; m_player->enableTab(Player::ProjectTabIndex, true); } @@ -3156,7 +3376,7 @@ void MainWindow::onPlaylistModified() { setWindowModified(true); if (MLT.producer() && playlist() - && (void *) MLT.producer()->get_producer() == (void *) playlist()->get_playlist()) + && (void *) MLT.producer()->get_producer() == (void *) playlist()->get_playlist()) m_player->onDurationChanged(); updateMarkers(); m_player->enableTab(Player::ProjectTabIndex, true); @@ -3197,7 +3417,7 @@ void MainWindow::onMultitrackModified() int expected = info->frame_in; auto info2 = m_timelineDock->model()->getClipInfo(trackIndex, clipIndex - 1); if (info2 && info2->producer && info2->producer->is_valid() - && info2->producer->get(kShotcutTransitionProperty)) { + && info2->producer->get(kShotcutTransitionProperty)) { // Factor in a transition left of the clip. expected -= info2->frame_count; info->producer->set(kPlaylistStartProperty, info2->start); @@ -3212,7 +3432,7 @@ void MainWindow::onMultitrackModified() expected = info->frame_out; info2 = m_timelineDock->model()->getClipInfo(trackIndex, clipIndex + 1); if (info2 && info2->producer && info2->producer->is_valid() - && info2->producer->get(kShotcutTransitionProperty)) { + && info2->producer->get(kShotcutTransitionProperty)) { // Factor in a transition right of the clip. expected += info2->frame_count; } @@ -3229,7 +3449,7 @@ void MainWindow::onMultitrackModified() void MainWindow::onMultitrackDurationChanged() { if (MLT.producer() - && (void *) MLT.producer()->get_producer() == (void *) multitrack()->get_producer()) + && (void *) MLT.producer()->get_producer() == (void *) multitrack()->get_producer()) m_player->onDurationChanged(); } @@ -3321,8 +3541,12 @@ bool MainWindow::saveXML(const QString &filename, bool withRelativePaths) result = MLT.saveXML(filename, playlist(), withRelativePaths, nullptr, false, notes); MLT.producer()->set_in_and_out(in, out); } else if (MLT.producer() && MLT.producer()->is_valid()) { - result = MLT.saveXML(filename, (MLT.isMultitrack() - || MLT.isPlaylist()) ? MLT.savedProducer() : 0, withRelativePaths, nullptr, false, notes); + result = MLT.saveXML(filename, + (MLT.isMultitrack() || MLT.isPlaylist()) ? MLT.savedProducer() : 0, + withRelativePaths, + nullptr, + false, + notes); } else { // Save an empty playlist, which is accepted by both MLT and Shotcut. Mlt::Playlist playlist(MLT.profile()); @@ -3338,21 +3562,21 @@ void MainWindow::changeTheme(const QString &theme) #if !defined(SHOTCUT_THEME) // Workaround Quick Controls not using our custom palette - temporarily? - std::unique_ptr style {QStyleFactory::create("fusion")}; + std::unique_ptr style{QStyleFactory::create("fusion")}; auto brightness = style->standardPalette().color(QPalette::Text).lightnessF(); LOG_DEBUG() << brightness; mytheme = brightness < 0.5f ? "light" : "dark"; QApplication::setStyle("Fusion"); QIcon::setThemeName(mytheme); -# if defined(Q_OS_MAC) +#if defined(Q_OS_MAC) if (mytheme == "dark") { auto palette = QGuiApplication::palette(); palette.setColor(QPalette::AlternateBase, palette.color(QPalette::Base).lighter()); QGuiApplication::setPalette(palette); } -# elif defined(Q_OS_WIN) +#elif defined(Q_OS_WIN) QGuiApplication::setPalette(style->standardPalette()); -# endif +#endif #else if (mytheme == "dark") { QApplication::setStyle("Fusion"); @@ -3415,22 +3639,22 @@ void MainWindow::changeTheme(const QString &theme) } #endif -// auto pal = QGuiApplication::palette(); -// LOG_INFO() << "altBase" << pal.alternateBase().color().name(); -// LOG_INFO() << "base" << pal.base().color().name(); -// LOG_INFO() << "window" << pal.window().color().name(); -// LOG_INFO() << "windowText" << pal.windowText().color().name(); -// LOG_INFO() << "toolTipBase" << pal.toolTipBase().color().name(); -// LOG_INFO() << "toolTipText" << pal.toolTipText().color().name(); -// LOG_INFO() << "text" << pal.text().color().name(); -// LOG_INFO() << "button" << pal.button().color().name(); -// LOG_INFO() << "buttonText" << pal.buttonText().color().name(); -// LOG_INFO() << "placeholderText" << pal.placeholderText().color().name(); -// LOG_INFO() << "brightText" << pal.brightText().color().name(); -// LOG_INFO() << "highlight" << pal.highlight().color().name(); -// LOG_INFO() << "highlightedText" << pal.highlightedText().color().name(); -// LOG_INFO() << "link" << pal.link().color().name(); -// LOG_INFO() << "linkVisited" << pal.linkVisited().color().name(); + // auto pal = QGuiApplication::palette(); + // LOG_INFO() << "altBase" << pal.alternateBase().color().name(); + // LOG_INFO() << "base" << pal.base().color().name(); + // LOG_INFO() << "window" << pal.window().color().name(); + // LOG_INFO() << "windowText" << pal.windowText().color().name(); + // LOG_INFO() << "toolTipBase" << pal.toolTipBase().color().name(); + // LOG_INFO() << "toolTipText" << pal.toolTipText().color().name(); + // LOG_INFO() << "text" << pal.text().color().name(); + // LOG_INFO() << "button" << pal.button().color().name(); + // LOG_INFO() << "buttonText" << pal.buttonText().color().name(); + // LOG_INFO() << "placeholderText" << pal.placeholderText().color().name(); + // LOG_INFO() << "brightText" << pal.brightText().color().name(); + // LOG_INFO() << "highlight" << pal.highlight().color().name(); + // LOG_INFO() << "highlightedText" << pal.highlightedText().color().name(); + // LOG_INFO() << "link" << pal.link().color().name(); + // LOG_INFO() << "linkVisited" << pal.linkVisited().color().name(); LOG_DEBUG() << "end"; } @@ -3441,8 +3665,7 @@ Mlt::Playlist *MainWindow::playlist() const bool MainWindow::isPlaylistValid() const { - return m_playlistDock->model()->playlist() - && m_playlistDock->model()->rowCount() > 0; + return m_playlistDock->model()->playlist() && m_playlistDock->model()->rowCount() > 0; } Mlt::Producer *MainWindow::multitrack() const @@ -3452,8 +3675,7 @@ Mlt::Producer *MainWindow::multitrack() const bool MainWindow::isMultitrackValid() const { - return m_timelineDock->model()->tractor() - && !m_timelineDock->model()->trackList().empty(); + return m_timelineDock->model()->tractor() && !m_timelineDock->model()->trackList().empty(); } QWidget *MainWindow::loadProducerWidget(Mlt::Producer *producer) @@ -3464,7 +3686,7 @@ QWidget *MainWindow::loadProducerWidget(Mlt::Producer *producer) if (!producer || !producer->is_valid()) { if (scrollArea->widget()) scrollArea->widget()->deleteLater(); - return w; + return w; } else { scrollArea->show(); } @@ -3474,7 +3696,7 @@ QWidget *MainWindow::loadProducerWidget(Mlt::Producer *producer) QString shotcutProducer(producer->get(kShotcutProducerProperty)); if (resource.startsWith("video4linux2:") - || QString::fromUtf8(producer->get("resource1")).startsWith("video4linux2:")) + || QString::fromUtf8(producer->get("resource1")).startsWith("video4linux2:")) w = new Video4LinuxWidget(this); else if (resource.startsWith("pulse:")) w = new PulseAudioWidget(this); @@ -3526,8 +3748,10 @@ QWidget *MainWindow::loadProducerWidget(Mlt::Producer *producer) return w; } else if (mlt_service_playlist_type == producer->type()) { int trackIndex = m_timelineDock->currentTrack(); - bool isBottomVideo = m_timelineDock->model()->data(m_timelineDock->model()->index(trackIndex), - MultitrackModel::IsBottomVideoRole).toBool(); + bool isBottomVideo = m_timelineDock->model() + ->data(m_timelineDock->model()->index(trackIndex), + MultitrackModel::IsBottomVideoRole) + .toBool(); if (!isBottomVideo) { w = new TrackPropertiesWidget(*producer, this); scrollArea->setWidget(w); @@ -3549,12 +3773,18 @@ QWidget *MainWindow::loadProducerWidget(Mlt::Producer *producer) } if (-1 != w->metaObject()->indexOfSignal("producerChanged(Mlt::Producer*)")) { connect(w, SIGNAL(producerChanged(Mlt::Producer *)), SLOT(onProducerChanged())); - connect(w, SIGNAL(producerChanged(Mlt::Producer *)), m_filterController, + connect(w, + SIGNAL(producerChanged(Mlt::Producer *)), + m_filterController, SLOT(setProducer(Mlt::Producer *))); - connect(w, SIGNAL(producerChanged(Mlt::Producer *)), m_playlistDock, + connect(w, + SIGNAL(producerChanged(Mlt::Producer *)), + m_playlistDock, SLOT(onProducerChanged(Mlt::Producer *))); if (producer->get(kMultitrackItemProperty)) - connect(w, SIGNAL(producerChanged(Mlt::Producer *)), m_timelineDock, + connect(w, + SIGNAL(producerChanged(Mlt::Producer *)), + m_timelineDock, SLOT(onProducerChanged(Mlt::Producer *))); } if (-1 != w->metaObject()->indexOfSignal("modified()")) { @@ -3575,8 +3805,11 @@ QWidget *MainWindow::loadProducerWidget(Mlt::Producer *producer) connect(this, SIGNAL(renameRequested()), w, SLOT(rename())); } if (-1 != w->metaObject()->indexOfSlot("offerConvert(QString)")) { - connect(m_filterController->attachedModel(), SIGNAL(requestConvert(QString, bool, bool)), w, - SLOT(offerConvert(QString, bool)), Qt::QueuedConnection); + connect(m_filterController->attachedModel(), + SIGNAL(requestConvert(QString, bool, bool)), + w, + SLOT(offerConvert(QString, bool)), + Qt::QueuedConnection); } scrollArea->setWidget(w); onProducerChanged(); @@ -3606,8 +3839,7 @@ void MainWindow::onGpuNotSupported() ui->actionGPU->setDisabled(true); } LOG_WARNING() << ""; - QMessageBox::critical(this, qApp->applicationName(), - tr("GPU effects are not supported")); + QMessageBox::critical(this, qApp->applicationName(), tr("GPU effects are not supported")); } void MainWindow::onShuttle(float x) @@ -3641,7 +3873,6 @@ void MainWindow::on_actionRealtime_triggered(bool checked) if (MLT.consumer()) { MLT.restart(); } - } void MainWindow::on_actionProgressive_triggered(bool checked) @@ -3753,7 +3984,8 @@ void MainWindow::processMultipleFiles() longTask.reportProgress(QFileInfo(filename).fileName(), i, count); Mlt::Producer p(MLT.profile(), filename.toUtf8().constData()); if (p.is_valid()) { - if (QDir::toNativeSeparators(filename) == QDir::toNativeSeparators(MAIN.fileName())) { + if (QDir::toNativeSeparators(filename) + == QDir::toNativeSeparators(MAIN.fileName())) { MAIN.showStatusMessage(QObject::tr("You cannot add a project to itself!")); continue; } @@ -3761,7 +3993,8 @@ void MainWindow::processMultipleFiles() Mlt::Producer *producer = MLT.setupNewProducer(&p); ProxyManager::generateIfNotExists(*producer); producer->set(kShotcutSkipConvertProperty, true); - undoStack()->push(new Playlist::AppendCommand(*m_playlistDock->model(), MLT.XML(producer), false)); + undoStack()->push( + new Playlist::AppendCommand(*m_playlistDock->model(), MLT.XML(producer), false)); m_recentDock->add(filename.toUtf8().constData()); dialog.add(producer); delete producer; @@ -3784,7 +4017,7 @@ void MainWindow::processMultipleFiles() void MainWindow::processSingleFile() { if (!m_multipleFilesLoading && Settings.showConvertClipDialog() - && !MLT.producer()->get_int(kShotcutSkipConvertProperty)) { + && !MLT.producer()->get_int(kShotcutSkipConvertProperty)) { QString convertAdvice = Util::getConversionAdvice(MLT.producer()); if (!convertAdvice.isEmpty()) { MLT.producer()->set(kShotcutSkipConvertProperty, true); @@ -3840,8 +4073,10 @@ void MainWindow::on_actionJack_triggered(bool checked) if (ui->actionJack) ui->actionJack->setChecked(false); Settings.setPlayerJACK(false); - QMessageBox::warning(this, qApp->applicationName(), - tr("Failed to connect to JACK.\nPlease verify that JACK is installed and running.")); + QMessageBox::warning( + this, + qApp->applicationName(), + tr("Failed to connect to JACK.\nPlease verify that JACK is installed and running.")); } } @@ -3850,8 +4085,10 @@ void MainWindow::on_actionGPU_triggered(bool checked) if (checked) { QMessageBox dialog(QMessageBox::Warning, qApp->applicationName(), - tr("GPU effects are experimental and do not work good on all computers. Plan to do some testing after turning this on.\n" - "At this time, a project created with GPU effects cannot be converted to a CPU-only project later." + tr("GPU effects are experimental and do not work good on all computers. " + "Plan to do some testing after turning this on.\n" + "At this time, a project created with GPU effects cannot be " + "converted to a CPU-only project later." "\n\n" "Do you want to enable GPU effects and restart Shotcut?"), QMessageBox::No | QMessageBox::Yes, @@ -3923,9 +4160,8 @@ void MainWindow::onExternalTriggered(QAction *action) // Disable progressive option when SDI/HDMI ui->actionProgressive->setEnabled(!isExternal); - bool isProgressive = isExternal - ? MLT.profile().progressive() - : ui->actionProgressive->isChecked(); + bool isProgressive = isExternal ? MLT.profile().progressive() + : ui->actionProgressive->isChecked(); MLT.videoWidget()->setProperty("progressive", isProgressive); if (MLT.consumer()) { MLT.consumer()->set("progressive", isProgressive); @@ -3983,8 +4219,8 @@ void MainWindow::onProfileTriggered(QAction *action) void MainWindow::onProfileChanged() { - if (multitrack() && MLT.isMultitrack() && - (m_timelineDock->selection().isEmpty() || m_timelineDock->currentTrack() == -1)) { + if (multitrack() && MLT.isMultitrack() + && (m_timelineDock->selection().isEmpty() || m_timelineDock->currentTrack() == -1)) { emit m_timelineDock->selected(multitrack()); } } @@ -4022,14 +4258,15 @@ void MainWindow::restartAfterChangeTheme() QMessageBox dialog(QMessageBox::Information, qApp->applicationName(), tr("You must restart %1 to switch to the new theme.\n" - "Do you want to restart now?").arg(qApp->applicationName()), + "Do you want to restart now?") + .arg(qApp->applicationName()), QMessageBox::No | QMessageBox::Yes, this); dialog.setDefaultButton(QMessageBox::Yes); dialog.setEscapeButton(QMessageBox::No); dialog.setWindowModality(QmlApplication::dialogModality()); if (dialog.exec() == QMessageBox::Yes) { -// m_exitCode = EXIT_RESTART; + // m_exitCode = EXIT_RESTART; QApplication::closeAllWindows(); } } @@ -4039,10 +4276,10 @@ void MainWindow::backup() QFileInfo info(m_currentFile); auto dateTime = info.lastModified().toString(Qt::ISODate); dateTime.replace(':', '-'); - auto filename = QStringLiteral("%1/%2 %3.mlt").arg(info.canonicalPath(), info.completeBaseName(), - dateTime); + auto filename = QStringLiteral("%1/%2 %3.mlt") + .arg(info.canonicalPath(), info.completeBaseName(), dateTime); if (!QFile::exists(filename) && !Util::warnIfNotWritable(filename, this, tr("Save XML")) - && QFile::copy(m_currentFile, filename)) { + && QFile::copy(m_currentFile, filename)) { showStatusMessage(tr("Saved backup %1").arg(filename)); } } @@ -4051,7 +4288,7 @@ void MainWindow::backupPeriodically() { auto dateTime = QFileInfo(m_currentFile).lastModified(); if (Settings.backupPeriod() > 0 && !kBackupFileRegex.match(m_currentFile).hasMatch() - && dateTime.secsTo(QDateTime::currentDateTime()) / 60 > Settings.backupPeriod()) { + && dateTime.secsTo(QDateTime::currentDateTime()) / 60 > Settings.backupPeriod()) { backup(); } } @@ -4064,16 +4301,20 @@ bool MainWindow::confirmProfileChange() QMessageBox dialog(QMessageBox::Warning, QCoreApplication::applicationName(), tr("

Please review your entire project after making this change.

" - "

Shotcut does not automatically adjust things that are sensitive to size and position if you change resolution or aspect ratio.The timing of edits and keyframes may be slightly different if you change frame rate.

" - "

It is a good idea to use File > Backup and Save before or after this operation.

" + "

Shotcut does not automatically adjust things that are sensitive to " + "size and position if you change resolution or aspect ratio.The timing of edits and keyframes may be slightly different if you " + "change frame rate.

" + "

It is a good idea to use File > Backup and Save before or " + "after this operation.

" "

Do you want to change the Video Mode now?

"), - QMessageBox::No | QMessageBox::Yes, &MAIN); + QMessageBox::No | QMessageBox::Yes, + &MAIN); dialog.setWindowModality(QmlApplication::dialogModality()); dialog.setDefaultButton(QMessageBox::Yes); dialog.setEscapeButton(QMessageBox::No); - dialog.setCheckBox(new QCheckBox(tr("Do not show this anymore.", - "Change video mode warning dialog"))); + dialog.setCheckBox( + new QCheckBox(tr("Do not show this anymore.", "Change video mode warning dialog"))); auto result = QMessageBox::Yes == dialog.exec(); if (dialog.checkBox()->isChecked()) Settings.setAskChangeVideoMode(false); @@ -4149,7 +4390,7 @@ void MainWindow::on_actionRestoreLayout_triggered() void MainWindow::on_actionShowTitleBars_triggered(bool checked) { - QList docks = findChildren(); + QList docks = findChildren(); for (int i = 0; i < docks.count(); i++) { QDockWidget *dock = docks.at(i); if (checked) { @@ -4187,7 +4428,7 @@ void MainWindow::on_menuExternal_aboutToShow() Settings.setPlayerExternal(QString()); } action->setDisabled(true); - } else { + } else { action->setEnabled(true); } } @@ -4201,14 +4442,13 @@ void MainWindow::on_actionUpgrade_triggered() QMessageBox dialog(QMessageBox::Question, qApp->applicationName(), tr("Do you want to automatically check for updates in the future?"), - QMessageBox::No | - QMessageBox::Yes, + QMessageBox::No | QMessageBox::Yes, this); dialog.setWindowModality(QmlApplication::dialogModality()); dialog.setDefaultButton(QMessageBox::Yes); dialog.setEscapeButton(QMessageBox::No); - dialog.setCheckBox(new QCheckBox(tr("Do not show this anymore.", - "Automatic upgrade check dialog"))); + dialog.setCheckBox( + new QCheckBox(tr("Do not show this anymore.", "Automatic upgrade check dialog"))); Settings.setCheckUpgradeAutomatic(dialog.exec() == QMessageBox::Yes); if (dialog.checkBox()->isChecked()) Settings.setAskUpgradeAutomatic(false); @@ -4223,8 +4463,12 @@ void MainWindow::on_actionOpenXML_triggered() #ifdef Q_OS_MAC path.append("/*"); #endif - QStringList filenames = QFileDialog::getOpenFileNames(this, tr("Open File"), path, - tr("MLT XML (*.mlt);;All Files (*)"), nullptr, Util::getFileDialogOptions()); + QStringList filenames = QFileDialog::getOpenFileNames(this, + tr("Open File"), + path, + tr("MLT XML (*.mlt);;All Files (*)"), + nullptr, + Util::getFileDialogOptions()); if (filenames.length() > 0) { QString url = filenames.first(); MltXmlChecker checker; @@ -4257,7 +4501,7 @@ void MainWindow::on_actionShowProjectFolder_triggered() Util::showInFolder(m_currentFile); } -void MainWindow::onFocusChanged(QWidget *, QWidget * ) const +void MainWindow::onFocusChanged(QWidget *, QWidget *) const { LOG_DEBUG() << "Focuswidget changed"; LOG_DEBUG() << "Current focusWidget:" << QApplication::focusWidget(); @@ -4368,9 +4612,9 @@ void MainWindow::onUpgradeCheckFinished(QNetworkReply *reply) if (!json.isNull() && json.object().value("version_string").type() == QJsonValue::String) { QString latest = json.object().value("version_string").toString(); if (current != "adhoc" - && QVersionNumber::fromString(current) < QVersionNumber::fromString(latest)) { - QAction *action = new QAction(tr("Shotcut version %1 is available! Click here to get it.").arg( - latest), 0); + && QVersionNumber::fromString(current) < QVersionNumber::fromString(latest)) { + QAction *action = new QAction( + tr("Shotcut version %1 is available! Click here to get it.").arg(latest), 0); connect(action, SIGNAL(triggered(bool)), SLOT(onUpgradeTriggered())); if (!json.object().value("url").isUndefined()) m_upgradeUrl = json.object().value("url").toString(); @@ -4411,8 +4655,12 @@ void MainWindow::on_actionExportEDL_triggered() // Dialog to get export file name. QString path = Settings.savePath(); QString caption = tr("Export EDL"); - QString saveFileName = QFileDialog::getSaveFileName(this, caption, path, - tr("EDL (*.edl);;All Files (*)"), nullptr, Util::getFileDialogOptions()); + QString saveFileName = QFileDialog::getSaveFileName(this, + caption, + path, + tr("EDL (*.edl);;All Files (*)"), + nullptr, + Util::getFileDialogOptions()); if (!saveFileName.isEmpty()) { QFileInfo fi(saveFileName); if (fi.suffix() != "edl") @@ -4455,8 +4703,7 @@ void MainWindow::on_actionExportEDL_triggered() } } if (result.isError()) { - LOG_ERROR() << "Uncaught exception at line" - << result.property("lineNumber").toInt() + LOG_ERROR() << "Uncaught exception at line" << result.property("lineNumber").toInt() << ":" << result.toString(); showStatusMessage(tr("A JavaScript error occurred during export.")); } @@ -4468,7 +4715,8 @@ void MainWindow::on_actionExportEDL_triggered() void MainWindow::on_actionExportFrame_triggered() { - if (!MLT.producer() || !MLT.producer()->is_valid()) return; + if (!MLT.producer() || !MLT.producer()->is_valid()) + return; filterController()->setCurrentFilter(QmlFilter::DeselectCurrentFilter); auto *videoWidget = qobject_cast(MLT.videoWidget()); connect(videoWidget, &Mlt::VideoWidget::imageReady, this, &MainWindow::onVideoWidgetImageReady); @@ -4485,16 +4733,17 @@ void MainWindow::onVideoWidgetImageReady() if (Settings.playerGPU() || Settings.playerPreviewScale()) { MLT.setPreviewScale(Settings.playerPreviewScale()); } - if (!image.isNull() && - (videoWidget->imageIsProxy() || (MLT.isMultitrack() && Settings.proxyEnabled())) - - ) { - QMessageBox dialog(QMessageBox::Question, - tr("Export frame from proxy?"), - tr("This frame may be from a lower resolution proxy instead of the original source.\n\n" - "Do you still want to continue?"), - QMessageBox::No | QMessageBox::Yes, - this); + if (!image.isNull() + && (videoWidget->imageIsProxy() || (MLT.isMultitrack() && Settings.proxyEnabled())) + + ) { + QMessageBox dialog( + QMessageBox::Question, + tr("Export frame from proxy?"), + tr("This frame may be from a lower resolution proxy instead of the original source.\n\n" + "Do you still want to continue?"), + QMessageBox::No | QMessageBox::Yes, + this); dialog.setDefaultButton(QMessageBox::Yes); dialog.setEscapeButton(QMessageBox::No); dialog.setWindowModality(QmlApplication::dialogModality()); @@ -4524,9 +4773,11 @@ void MainWindow::on_actionAppDataSet_triggered() dialog.setDefaultButton(QMessageBox::Yes); dialog.setEscapeButton(QMessageBox::No); dialog.setWindowModality(QmlApplication::dialogModality()); - if (dialog.exec() != QMessageBox::Yes) return; + if (dialog.exec() != QMessageBox::Yes) + return; - QString dirName = QFileDialog::getExistingDirectory(this, tr("Data Directory"), + QString dirName = QFileDialog::getExistingDirectory(this, + tr("Data Directory"), Settings.appDataLocation(), Util::getFileDialogOptions()); if (!dirName.isEmpty()) { @@ -4537,10 +4788,12 @@ void MainWindow::on_actionAppDataSet_triggered() if (!QFile::exists(dirName + "/" + it.fileName())) { if (it.fileInfo().isDir()) { if (!QFile::rename(it.filePath(), dirName + "/" + it.fileName())) - LOG_WARNING() << "Failed to move" << it.filePath() << "to" << dirName + "/" + it.fileName(); + LOG_WARNING() << "Failed to move" << it.filePath() << "to" + << dirName + "/" + it.fileName(); } else { if (!QFile::copy(it.filePath(), dirName + "/" + it.fileName())) - LOG_WARNING() << "Failed to copy" << it.filePath() << "to" << dirName + "/" + it.fileName(); + LOG_WARNING() << "Failed to copy" << it.filePath() << "to" + << dirName + "/" + it.fileName(); } } } @@ -4581,20 +4834,21 @@ void MainWindow::on_actionKeyboardShortcuts_triggered() void MainWindow::on_actionLayoutLogging_triggered() { - Settings.setLayout(QString(kReservedLayoutPrefix).arg(Settings.layoutMode()), QByteArray(), + Settings.setLayout(QString(kReservedLayoutPrefix).arg(Settings.layoutMode()), + QByteArray(), saveState()); Settings.setLayoutMode(LayoutMode::Logging); auto state = Settings.layoutState(QString(kReservedLayoutPrefix).arg(LayoutMode::Logging)); if (state.isEmpty()) { restoreState(kLayoutLoggingDefault); -// setCorner(Qt::TopLeftCorner, Qt::LeftDockWidgetArea); -// setCorner(Qt::TopRightCorner, Qt::RightDockWidgetArea); -// setCorner(Qt::BottomLeftCorner, Qt::LeftDockWidgetArea); -// setCorner(Qt::BottomRightCorner, Qt::RightDockWidgetArea); -// resizeDocks({m_playlistDock, m_propertiesDock}, -// {qFloor(width() * 0.25), qFloor(width() * 0.25)}, Qt::Horizontal); + // setCorner(Qt::TopLeftCorner, Qt::LeftDockWidgetArea); + // setCorner(Qt::TopRightCorner, Qt::RightDockWidgetArea); + // setCorner(Qt::BottomLeftCorner, Qt::LeftDockWidgetArea); + // setCorner(Qt::BottomRightCorner, Qt::RightDockWidgetArea); + // resizeDocks({m_playlistDock, m_propertiesDock}, + // {qFloor(width() * 0.25), qFloor(width() * 0.25)}, Qt::Horizontal); } else { -// LOG_DEBUG() << state.toBase64(); + // LOG_DEBUG() << state.toBase64(); restoreState(state); } Settings.setWindowState(saveState()); @@ -4602,15 +4856,16 @@ void MainWindow::on_actionLayoutLogging_triggered() void MainWindow::on_actionLayoutEditing_triggered() { - Settings.setLayout(QString(kReservedLayoutPrefix).arg(Settings.layoutMode()), QByteArray(), + Settings.setLayout(QString(kReservedLayoutPrefix).arg(Settings.layoutMode()), + QByteArray(), saveState()); Settings.setLayoutMode(LayoutMode::Editing); auto state = Settings.layoutState(QString(kReservedLayoutPrefix).arg(LayoutMode::Editing)); if (state.isEmpty()) { restoreState(kLayoutEditingDefault); -// resetDockCorners(); + // resetDockCorners(); } else { -// LOG_DEBUG() << state.toBase64(); + // LOG_DEBUG() << state.toBase64(); restoreState(state); } Settings.setWindowState(saveState()); @@ -4618,15 +4873,16 @@ void MainWindow::on_actionLayoutEditing_triggered() void MainWindow::on_actionLayoutEffects_triggered() { - Settings.setLayout(QString(kReservedLayoutPrefix).arg(Settings.layoutMode()), QByteArray(), + Settings.setLayout(QString(kReservedLayoutPrefix).arg(Settings.layoutMode()), + QByteArray(), saveState()); Settings.setLayoutMode(LayoutMode::Effects); auto state = Settings.layoutState(QString(kReservedLayoutPrefix).arg(LayoutMode::Effects)); if (state.isEmpty()) { restoreState(kLayoutEffectsDefault); -// resetDockCorners(); + // resetDockCorners(); } else { -// LOG_DEBUG() << state.toBase64(); + // LOG_DEBUG() << state.toBase64(); restoreState(state); } Settings.setWindowState(saveState()); @@ -4634,18 +4890,19 @@ void MainWindow::on_actionLayoutEffects_triggered() void MainWindow::on_actionLayoutColor_triggered() { - Settings.setLayout(QString(kReservedLayoutPrefix).arg(Settings.layoutMode()), QByteArray(), + Settings.setLayout(QString(kReservedLayoutPrefix).arg(Settings.layoutMode()), + QByteArray(), saveState()); Settings.setLayoutMode(LayoutMode::Color); auto state = Settings.layoutState(QString(kReservedLayoutPrefix).arg(LayoutMode::Color)); if (state.isEmpty()) { restoreState(kLayoutColorDefault); -// setCorner(Qt::TopLeftCorner, Qt::LeftDockWidgetArea); -// setCorner(Qt::TopRightCorner, Qt::RightDockWidgetArea); -// setCorner(Qt::BottomLeftCorner, Qt::BottomDockWidgetArea); -// setCorner(Qt::BottomRightCorner, Qt::RightDockWidgetArea); + // setCorner(Qt::TopLeftCorner, Qt::LeftDockWidgetArea); + // setCorner(Qt::TopRightCorner, Qt::RightDockWidgetArea); + // setCorner(Qt::BottomLeftCorner, Qt::BottomDockWidgetArea); + // setCorner(Qt::BottomRightCorner, Qt::RightDockWidgetArea); } else { -// LOG_DEBUG() << state.toBase64(); + // LOG_DEBUG() << state.toBase64(); restoreState(state); } Settings.setWindowState(saveState()); @@ -4653,18 +4910,19 @@ void MainWindow::on_actionLayoutColor_triggered() void MainWindow::on_actionLayoutAudio_triggered() { - Settings.setLayout(QString(kReservedLayoutPrefix).arg(Settings.layoutMode()), QByteArray(), + Settings.setLayout(QString(kReservedLayoutPrefix).arg(Settings.layoutMode()), + QByteArray(), saveState()); Settings.setLayoutMode(LayoutMode::Audio); auto state = Settings.layoutState(QString(kReservedLayoutPrefix).arg(LayoutMode::Audio)); if (state.isEmpty()) { restoreState(kLayoutAudioDefault); -// setCorner(Qt::TopLeftCorner, Qt::LeftDockWidgetArea); -// setCorner(Qt::TopRightCorner, Qt::RightDockWidgetArea); -// setCorner(Qt::BottomLeftCorner, Qt::BottomDockWidgetArea); -// setCorner(Qt::BottomRightCorner, Qt::RightDockWidgetArea); + // setCorner(Qt::TopLeftCorner, Qt::LeftDockWidgetArea); + // setCorner(Qt::TopRightCorner, Qt::RightDockWidgetArea); + // setCorner(Qt::BottomLeftCorner, Qt::BottomDockWidgetArea); + // setCorner(Qt::BottomRightCorner, Qt::RightDockWidgetArea); } else { -// LOG_DEBUG() << state.toBase64(); + // LOG_DEBUG() << state.toBase64(); restoreState(state); } Settings.setWindowState(saveState()); @@ -4676,15 +4934,16 @@ void MainWindow::on_actionLayoutPlayer_triggered() // Clearing selection causes Filters to clear, which prevents showing a filter's VUI m_timelineDock->setSelection(); } - Settings.setLayout(QString(kReservedLayoutPrefix).arg(Settings.layoutMode()), QByteArray(), + Settings.setLayout(QString(kReservedLayoutPrefix).arg(Settings.layoutMode()), + QByteArray(), saveState()); Settings.setLayoutMode(LayoutMode::PlayerOnly); auto state = Settings.layoutState(QString(kReservedLayoutPrefix).arg(LayoutMode::PlayerOnly)); if (state.isEmpty()) { restoreState(kLayoutPlayerDefault); -// resetDockCorners(); + // resetDockCorners(); } else { -// LOG_DEBUG() << state.toBase64(); + // LOG_DEBUG() << state.toBase64(); restoreState(state); } Settings.setWindowState(saveState()); @@ -4693,7 +4952,8 @@ void MainWindow::on_actionLayoutPlayer_triggered() void MainWindow::on_actionLayoutPlaylist_triggered() { if (Settings.layoutMode() != LayoutMode::Custom) { - Settings.setLayout(QString(kReservedLayoutPrefix).arg(Settings.layoutMode()), QByteArray(), + Settings.setLayout(QString(kReservedLayoutPrefix).arg(Settings.layoutMode()), + QByteArray(), saveState()); Settings.setLayoutMode(LayoutMode::Custom); } @@ -4709,7 +4969,8 @@ void MainWindow::on_actionLayoutPlaylist_triggered() void MainWindow::on_actionLayoutClip_triggered() { if (Settings.layoutMode() != LayoutMode::Custom) { - Settings.setLayout(QString(kReservedLayoutPrefix).arg(Settings.layoutMode()), QByteArray(), + Settings.setLayout(QString(kReservedLayoutPrefix).arg(Settings.layoutMode()), + QByteArray(), saveState()); Settings.setLayoutMode(LayoutMode::Custom); } @@ -4748,7 +5009,8 @@ void MainWindow::on_actionLayoutAdd_triggered() void MainWindow::onLayoutTriggered(QAction *action) { if (Settings.layoutMode() != LayoutMode::Custom) { - Settings.setLayout(QString(kReservedLayoutPrefix).arg(Settings.layoutMode()), QByteArray(), + Settings.setLayout(QString(kReservedLayoutPrefix).arg(Settings.layoutMode()), + QByteArray(), saveState()); Settings.setLayoutMode(LayoutMode::Custom); } @@ -4769,7 +5031,10 @@ void MainWindow::on_actionProfileRemove_triggered() // Show the dialog. if (dialog.exec() == QDialog::Accepted) { - removeCustomProfiles(dialog.selection(), dir, customProfileMenu(), actionProfileRemove()); + removeCustomProfiles(dialog.selection(), + dir, + customProfileMenu(), + actionProfileRemove()); } } } @@ -4817,8 +5082,8 @@ void MainWindow::on_actionLayoutRemove_triggered() void MainWindow::on_actionOpenOther2_triggered() { - ui->actionOpenOther2->menu()->popup(mapToGlobal(ui->mainToolBar->geometry().bottomLeft()) + QPoint( - 64, 0)); + ui->actionOpenOther2->menu()->popup(mapToGlobal(ui->mainToolBar->geometry().bottomLeft()) + + QPoint(64, 0)); } void MainWindow::onOpenOtherTriggered(QWidget *widget) @@ -4834,9 +5099,7 @@ void MainWindow::onOpenOtherTriggered(QWidget *widget) buttonBox->setStandardButtons(QDialogButtonBox::Cancel | QDialogButtonBox::Open); if (!AbstractProducerWidget::isDevice(widget)) { auto button = buttonBox->addButton(tr("Add To Timeline"), QDialogButtonBox::ApplyRole); - connect(button, &QPushButton::clicked, this, [ = ]() { - dialog->done(-1); - }); + connect(button, &QPushButton::clicked, this, [=]() { dialog->done(-1); }); } vlayout->addWidget(buttonBox); connect(buttonBox, &QDialogButtonBox::accepted, dialog, &QDialog::accept); @@ -4852,8 +5115,8 @@ void MainWindow::onOpenOtherFinished(int result) if (AbstractProducerWidget::isDevice(m_producerWidget.get()) && !Settings.playerGPU()) closeProducer(); auto &profile = MLT.profile(); - auto producer = dynamic_cast( - m_producerWidget.get())->newProducer(profile); + auto producer + = dynamic_cast(m_producerWidget.get())->newProducer(profile); if (!(producer && producer->is_valid())) { delete producer; m_producerWidget.reset(); @@ -4873,8 +5136,8 @@ void MainWindow::onOpenOtherFinished(int result) // Mlt::Controller owns the producer now } else { m_player->switchToTab(Player::ProjectTabIndex); - auto trackType = ("ToneProducerWidget" == name || "toneWidget" == name) - ? AudioTrackType : VideoTrackType; + auto trackType = ("ToneProducerWidget" == name || "toneWidget" == name) ? AudioTrackType + : VideoTrackType; auto trackIndex = m_timelineDock->addTrackIfNeeded(trackType); m_timelineDock->overwrite(trackIndex, -1, MLT.XML(producer), true); delete producer; @@ -4944,7 +5207,8 @@ void MainWindow::onSceneGraphInitialized() if (Settings.playerGPU() && Settings.playerWarnGPU()) { QMessageBox dialog(QMessageBox::Warning, qApp->applicationName(), - tr("GPU effects are EXPERIMENTAL, UNSTABLE and UNSUPPORTED! Unsupported means do not report bugs about it.\n\n" + tr("GPU effects are EXPERIMENTAL, UNSTABLE and UNSUPPORTED! Unsupported " + "means do not report bugs about it.\n\n" "Do you want to disable GPU effects and restart Shotcut?"), QMessageBox::No | QMessageBox::Yes, this); @@ -4961,7 +5225,7 @@ void MainWindow::onSceneGraphInitialized() } else { ui->actionGPU->setVisible(true); } - auto videoWidget = (Mlt::VideoWidget *) & (MLT); + auto videoWidget = (Mlt::VideoWidget *) &(MLT); videoWidget->setBlankScene(); } @@ -5046,7 +5310,10 @@ void MainWindow::replaceInTimeline(const QUuid &uuid, Mlt::Producer &producer) if (info && trackIndex >= 0 && clipIndex >= 0) { Util::getHash(producer); - Util::applyCustomProperties(producer, *info->producer, producer.get_in(), producer.get_out()); + Util::applyCustomProperties(producer, + *info->producer, + producer.get_in(), + producer.get_out()); m_timelineDock->replace(trackIndex, clipIndex, MLT.XML(&producer)); } } @@ -5057,14 +5324,19 @@ void MainWindow::replaceAllByHash(const QString &hash, Mlt::Producer &producer, if (!isProxy) m_recentDock->add(producer.get("resource")); if (MLT.isClip() && Util::getHash(*MLT.producer()) == hash) { - Util::applyCustomProperties(producer, *MLT.producer(), MLT.producer()->get_in(), + Util::applyCustomProperties(producer, + *MLT.producer(), + MLT.producer()->get_in(), MLT.producer()->get_out()); MLT.copyFilters(*MLT.producer(), producer); MLT.close(); m_player->setPauseAfterOpen(true); - open(new Mlt::Producer(MLT.profile(), "xml-string", MLT.XML(&producer).toUtf8().constData())); + open( + new Mlt::Producer(MLT.profile(), "xml-string", MLT.XML(&producer).toUtf8().constData())); } else if (MLT.savedProducer() && Util::getHash(*MLT.savedProducer()) == hash) { - Util::applyCustomProperties(producer, *MLT.savedProducer(), MLT.savedProducer()->get_in(), + Util::applyCustomProperties(producer, + *MLT.savedProducer(), + MLT.savedProducer()->get_in(), MLT.savedProducer()->get_out()); MLT.copyFilters(*MLT.savedProducer(), producer); MLT.setSavedProducer(&producer); @@ -5137,8 +5409,9 @@ void MainWindow::on_actionUseProxy_triggered(bool checked) int result = 0; { LongUiTask longTask(checked ? tr("Turn Proxy On") : tr("Turn Proxy Off")); - QFuture future = QtConcurrent::run([ = ]() { - return MLT.open(QDir::fromNativeSeparators(fileName), QDir::fromNativeSeparators(m_currentFile)); + QFuture future = QtConcurrent::run([=]() { + return MLT.open(QDir::fromNativeSeparators(fileName), + QDir::fromNativeSeparators(m_currentFile)); }); result = longTask.wait(tr("Converting"), future); } @@ -5153,10 +5426,14 @@ void MainWindow::on_actionUseProxy_triggered(bool checked) if (checked && (isPlaylistValid() || isMultitrackValid())) { // Prompt user if they want to create missing proxies - QMessageBox dialog(QMessageBox::Question, qApp->applicationName(), - tr("Do you want to create missing proxies for every file in this project?\n\n" - "You must reopen your project after all proxy jobs are finished."), - QMessageBox::No | QMessageBox::Yes, this); + QMessageBox dialog( + QMessageBox::Question, + qApp->applicationName(), + tr("Do you want to create missing proxies for every file in this " + "project?\n\n" + "You must reopen your project after all proxy jobs are finished."), + QMessageBox::No | QMessageBox::Yes, + this); dialog.setWindowModality(QmlApplication::dialogModality()); dialog.setDefaultButton(QMessageBox::Yes); dialog.setEscapeButton(QMessageBox::No); @@ -5189,7 +5466,8 @@ void MainWindow::on_actionUseProxy_triggered(bool checked) void MainWindow::on_actionProxyStorageSet_triggered() { // Present folder dialog just like App Data Directory - QString dirName = QFileDialog::getExistingDirectory(this, tr("Proxy Folder"), + QString dirName = QFileDialog::getExistingDirectory(this, + tr("Proxy Folder"), Settings.proxyFolder(), Util::getFileDialogOptions()); if (!dirName.isEmpty() && dirName != Settings.proxyFolder()) { @@ -5204,9 +5482,12 @@ void MainWindow::on_actionProxyStorageSet_triggered() if (count > 0) { // Prompt user if they want to create missing proxies - QMessageBox dialog(QMessageBox::Question, qApp->applicationName(), - tr("Do you want to move all files from the old folder to the new folder?"), - QMessageBox::No | QMessageBox::Yes, this); + QMessageBox + dialog(QMessageBox::Question, + qApp->applicationName(), + tr("Do you want to move all files from the old folder to the new folder?"), + QMessageBox::No | QMessageBox::Yes, + this); dialog.setWindowModality(QmlApplication::dialogModality()); dialog.setDefaultButton(QMessageBox::Yes); dialog.setEscapeButton(QMessageBox::No); @@ -5216,7 +5497,8 @@ void MainWindow::on_actionProxyStorageSet_triggered() int i = 0; for (const auto &fileName : dirList) { if (!fileName.isEmpty() && !QFile::exists(dirName + "/" + fileName)) { - LOG_DEBUG() << "moving" << oldDir.filePath(fileName) << "to" << dirName + "/" + fileName; + LOG_DEBUG() << "moving" << oldDir.filePath(fileName) << "to" + << dirName + "/" + fileName; longTask.reportProgress(fileName, i++, count); if (!QFile::rename(oldDir.filePath(fileName), dirName + "/" + fileName)) LOG_WARNING() << "Failed to move" << oldDir.filePath(fileName); @@ -5354,7 +5636,7 @@ void MainWindow::on_actionExportChapters_triggered() if (uniqueColors.isEmpty()) { return; } - std::sort(uniqueColors.begin(), uniqueColors.end(), [ = ](const QColor & a, const QColor & b) { + std::sort(uniqueColors.begin(), uniqueColors.end(), [=](const QColor &a, const QColor &b) { if (a.hue() == b.hue()) { if (a.saturation() == b.saturation()) { return a.value() <= b.value(); @@ -5392,8 +5674,12 @@ void MainWindow::on_actionExportChapters_triggered() // Dialog to get export file name QString path = Settings.savePath(); QString caption = tr("Export Chapters"); - QString saveFileName = QFileDialog::getSaveFileName(this, caption, path, - tr("Text (*.txt);;All Files (*)"), nullptr, Util::getFileDialogOptions()); + QString saveFileName = QFileDialog::getSaveFileName(this, + caption, + path, + tr("Text (*.txt);;All Files (*)"), + nullptr, + Util::getFileDialogOptions()); if (!saveFileName.isEmpty()) { QFileInfo fi(saveFileName); if (fi.suffix() != "txt") @@ -5441,8 +5727,7 @@ void MainWindow::on_actionExportChapters_triggered() } } if (result.isError()) { - LOG_ERROR() << "Uncaught exception at line" - << result.property("lineNumber").toInt() + LOG_ERROR() << "Uncaught exception at line" << result.property("lineNumber").toInt() << ":" << result.toString(); showStatusMessage(tr("A JavaScript error occurred during export.")); } @@ -5485,12 +5770,13 @@ void MainWindow::on_actionAudioVideoDevice_triggered() void MainWindow::on_actionReset_triggered() { - QMessageBox dialog(QMessageBox::Question, - qApp->applicationName(), - tr("This will reset all settings, and Shotcut must restart afterwards.\n" - "Do you want to reset and restart now?"), - QMessageBox::No | QMessageBox::Yes, - this); + QMessageBox + dialog(QMessageBox::Question, + qApp->applicationName(), + tr("This will reset all settings, and Shotcut must restart afterwards.\n" + "Do you want to reset and restart now?"), + QMessageBox::No | QMessageBox::Yes, + this); dialog.setDefaultButton(QMessageBox::Yes); dialog.setEscapeButton(QMessageBox::No); dialog.setWindowModality(QmlApplication::dialogModality()); @@ -5501,8 +5787,7 @@ void MainWindow::on_actionReset_triggered() } } -void MainWindow::onCreateOrEditFilterOnOutput(Mlt::Filter *filter, - const QStringList &key_properties) +void MainWindow::onCreateOrEditFilterOnOutput(Mlt::Filter *filter, const QStringList &key_properties) { m_timelineDock->selectMultitrack(); onFiltersDockTriggered(); diff --git a/src/mainwindow.h b/src/mainwindow.h index 35a4495ded..9fcaa3d95b 100644 --- a/src/mainwindow.h +++ b/src/mainwindow.h @@ -18,16 +18,17 @@ #ifndef MAINWINDOW_H #define MAINWINDOW_H +#include "mltcontroller.h" +#include "mltxmlchecker.h" + +#include #include #include -#include -#include #include #include #include -#include -#include "mltcontroller.h" -#include "mltxmlchecker.h" +#include +#include #define EXIT_RESTART (42) #define EXIT_RESET (43) @@ -59,15 +60,7 @@ class MainWindow : public QMainWindow Q_OBJECT public: - enum LayoutMode { - Custom = 0, - Logging, - Editing, - Effects, - Color, - Audio, - PlayerOnly - }; + enum LayoutMode { Custom = 0, Logging, Editing, Effects, Color, Audio, PlayerOnly }; static MainWindow &singleton(); ~MainWindow(); @@ -77,18 +70,9 @@ class MainWindow : public QMainWindow QUndoStack *undoStack() const; bool saveXML(const QString &filename, bool withRelativePaths = true); static void changeTheme(const QString &theme); - PlaylistDock *playlistDock() const - { - return m_playlistDock; - } - TimelineDock *timelineDock() const - { - return m_timelineDock; - } - FilterController *filterController() const - { - return m_filterController; - } + PlaylistDock *playlistDock() const { return m_playlistDock; } + TimelineDock *timelineDock() const { return m_timelineDock; } + FilterController *filterController() const { return m_filterController; } Mlt::Playlist *playlist() const; bool isPlaylistValid() const; Mlt::Producer *multitrack() const; @@ -97,27 +81,20 @@ class MainWindow : public QMainWindow void setFullScreen(bool isFullScreen); QString untitledFileName() const; void setProfile(const QString &profile_name); - QString fileName() const - { - return m_currentFile; - } + QString fileName() const { return m_currentFile; } bool isSourceClipMyProject(QString resource = MLT.resource(), bool withDialog = true); bool keyframesDockIsVisible() const; void keyPressEvent(QKeyEvent *); void keyReleaseEvent(QKeyEvent *); void hideSetDataDirectory(); - QMenu *customProfileMenu() const - { - return m_customProfileMenu; - } + QMenu *customProfileMenu() const { return m_customProfileMenu; } QAction *actionAddCustomProfile() const; QAction *actionProfileRemove() const; - QActionGroup *profileGroup() const - { - return m_profileGroup; - } - void buildVideoModeMenu(QMenu *topMenu, QMenu *&customMenu, QActionGroup *group, + QActionGroup *profileGroup() const { return m_profileGroup; } + void buildVideoModeMenu(QMenu *topMenu, + QMenu *&customMenu, + QActionGroup *group, QAction *addAction, QAction *removeAction); void newProject(const QString &filename, bool isProjectFolder = false); @@ -126,10 +103,7 @@ class MainWindow : public QMainWindow QUuid timelineClipUuid(int trackIndex, int clipIndex); void replaceInTimeline(const QUuid &uuid, Mlt::Producer &producer); void replaceAllByHash(const QString &hash, Mlt::Producer &producer, bool isProxy = false); - bool isClipboardNewer() const - { - return m_clipboardUpdatedAt > m_sourceUpdatedAt; - } + bool isClipboardNewer() const { return m_clipboardUpdatedAt > m_sourceUpdatedAt; } int mltIndexForTrack(int trackIndex) const; int bottomVideoTrackIndex() const; void cropSource(const QRectF &rect); @@ -242,7 +216,9 @@ class MainWindow : public QMainWindow public slots: bool isCompatibleWithGpuMode(MltXmlChecker &checker); bool isXmlRepaired(MltXmlChecker &checker, QString &fileName); - bool open(QString url, const Mlt::Properties * = nullptr, bool play = true, + bool open(QString url, + const Mlt::Properties * = nullptr, + bool play = true, bool skipConvert = false); void openMultiple(const QStringList &paths); void openMultiple(const QList &urls); @@ -251,7 +227,8 @@ public slots: void hideProducer(); void closeProducer(); void showStatusMessage(QAction *action, int timeoutSeconds = 5); - void showStatusMessage(const QString &message, int timeoutSeconds = 5, + void showStatusMessage(const QString &message, + int timeoutSeconds = 5, QPalette::ColorRole role = QPalette::ToolTipBase); void onStatusMessageClicked(); void seekPlaylist(int start); diff --git a/src/mltcontroller.cpp b/src/mltcontroller.cpp index 4e97cec07a..a129c24871 100644 --- a/src/mltcontroller.cpp +++ b/src/mltcontroller.cpp @@ -16,29 +16,15 @@ */ #include "mltcontroller.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "settings.h" -#include "shotcut_mlt_properties.h" -#include "mainwindow.h" +#include "Logger.h" #include "controllers/filtercontroller.h" +#include "mainwindow.h" +#include "proxymanager.h" #include "qmltypes/qmlmetadata.h" +#include "settings.h" +#include "shotcut_mlt_properties.h" #include "util.h" -#include "proxymanager.h" #if defined(Q_OS_WIN) #include "widgets/d3dvideowidget.h" #include "widgets/openglvideowidget.h" @@ -48,6 +34,22 @@ #include "widgets/openglvideowidget.h" #endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + namespace Mlt { static const int kThumbnailOutSeekFactor = 5; @@ -155,16 +157,16 @@ int Controller::open(const QString &url, const QString &urlToSave, bool skipConv channels = 2; m_audioChannels = channels; } - if (Util::isFpsDifferent(profile().fps(), fps) || (Settings.playerGPU() - && !profile().is_explicit())) { + if (Util::isFpsDifferent(profile().fps(), fps) + || (Settings.playerGPU() && !profile().is_explicit())) { // Reload with correct FPS or with Movit normalizing filters attached. delete newProducer; newProducer = new Mlt::Producer(profile(), myUrl.toUtf8().constData()); } if (m_url.isEmpty() && QString(newProducer->get("xml")) == "was here") { - if (newProducer->get_int("_original_type") != mlt_service_tractor_type || - (newProducer->get_int("_original_type") == mlt_service_tractor_type - && newProducer->get(kShotcutXmlProperty))) + if (newProducer->get_int("_original_type") != mlt_service_tractor_type + || (newProducer->get_int("_original_type") == mlt_service_tractor_type + && newProducer->get(kShotcutXmlProperty))) m_url = urlToSave; } Producer *producer = setupNewProducer(newProducer); @@ -383,8 +385,12 @@ bool Controller::enableJack(bool enable) m_consumer->attach(*m_jackFilter); m_consumer->set("audio_off", 1); if (isSeekable()) { - m_jackFilter->listen("jack-started", this, reinterpret_cast(on_jack_started)); - m_jackFilter->listen("jack-stopped", this, reinterpret_cast(on_jack_stopped)); + m_jackFilter->listen("jack-started", + this, + reinterpret_cast(on_jack_started)); + m_jackFilter->listen("jack-stopped", + this, + reinterpret_cast(on_jack_stopped)); } } else { m_jackFilter.reset(); @@ -400,7 +406,6 @@ bool Controller::enableJack(bool enable) return true; } - void Controller::setVolume(double volume, bool muteOnPause) { m_volume = volume; @@ -417,7 +422,6 @@ void Controller::setVolume(double volume, bool muteOnPause) m_consumer->set("volume", volume); } } - } double Controller::volume() const @@ -465,8 +469,12 @@ void Controller::refreshConsumer(bool scrubAudio) } } -bool Controller::saveXML(const QString &filename, Service *service, bool withRelativePaths, - QTemporaryFile *tempFile, bool proxy, QString projectNote) +bool Controller::saveXML(const QString &filename, + Service *service, + bool withRelativePaths, + QTemporaryFile *tempFile, + bool proxy, + QString projectNote) { QMutexLocker locker(&m_saveXmlMutex); QFileInfo fi(filename); @@ -489,7 +497,8 @@ bool Controller::saveXML(const QString &filename, Service *service, bool withRel c.set("store", "shotcut"); c.set("root", root.toUtf8().constData()); c.set("no_root", 1); - c.set("title", QStringLiteral("Shotcut version ").append(SHOTCUT_VERSION).toUtf8().constData()); + c.set("title", + QStringLiteral("Shotcut version ").append(SHOTCUT_VERSION).toUtf8().constData()); c.connect(s); c.start(); if (ignore) @@ -501,8 +510,8 @@ bool Controller::saveXML(const QString &filename, Service *service, bool withRel stream.setEncoding(QStringConverter::Utf8); stream << xml; if (tempFile->error() != QFileDevice::NoError) { - LOG_ERROR() << "error while writing MLT XML file" << tempFile->fileName() << ":" << - tempFile->errorString(); + LOG_ERROR() << "error while writing MLT XML file" << tempFile->fileName() << ":" + << tempFile->errorString(); return false; } } else { @@ -516,7 +525,8 @@ bool Controller::saveXML(const QString &filename, Service *service, bool withRel stream.setEncoding(QStringConverter::Utf8); stream << xml; if (file.error() != QFileDevice::NoError) { - LOG_ERROR() << "error while writing MLT XML file" << filename << ":" << file.errorString(); + LOG_ERROR() << "error while writing MLT XML file" << filename << ":" + << file.errorString(); return false; } return file.commit(); @@ -529,8 +539,9 @@ bool Controller::saveXML(const QString &filename, Service *service, bool withRel QString Controller::XML(Service *service, bool withProfile, bool withMetadata) { Consumer c(profile(), "xml", kMltXmlPropertyName); - Service s(service ? service->get_service() : (m_producer - && m_producer->is_valid()) ? m_producer->get_service() : nullptr); + Service s(service ? service->get_service() + : (m_producer && m_producer->is_valid()) ? m_producer->get_service() + : nullptr); if (!s.is_valid()) return ""; int ignore = s.get_int("ignore_points"); @@ -636,8 +647,9 @@ bool Controller::isSeekable(Producer *p) const // These generators can take an out point to define their length. // TODO: Currently, these max out at 15000 frames, which is arbitrary. QString service(producer->get("mlt_service")); - seekable = (service == "color") || service.startsWith("frei0r.") || (service == "tone") - || (service == "count") || (service == "noise") || (service == "consumer"); + seekable = (service == "color") || service.startsWith("frei0r.") + || (service == "tone") || (service == "count") || (service == "noise") + || (service == "consumer"); } } } @@ -662,9 +674,9 @@ bool Controller::isClosedClip(Producer *producer) const { if (!producer) producer = m_producer.data(); - return (!producer || !producer->is_valid() || - (!qstrcmp(producer->get("mlt_service"), "color") && - !qstrcmp(producer->get("resource"), "_hide"))); + return (!producer || !producer->is_valid() + || (!qstrcmp(producer->get("mlt_service"), "color") + && !qstrcmp(producer->get("resource"), "_hide"))); } bool Controller::isSeekableClip() @@ -674,16 +686,16 @@ bool Controller::isSeekableClip() bool Controller::isPlaylist() const { - return m_producer && m_producer->is_valid() && - !m_producer->get_int(kShotcutVirtualClip) && - (m_producer->get_int("_original_type") == mlt_service_playlist_type || resource() == ""); + return m_producer && m_producer->is_valid() && !m_producer->get_int(kShotcutVirtualClip) + && (m_producer->get_int("_original_type") == mlt_service_playlist_type + || resource() == ""); } bool Controller::isMultitrack() const { - return m_producer && m_producer->is_valid() - && !m_producer->get_int(kShotcutVirtualClip) - && (m_producer->get_int("_original_type") == mlt_service_tractor_type || resource() == "") + return m_producer && m_producer->is_valid() && !m_producer->get_int(kShotcutVirtualClip) + && (m_producer->get_int("_original_type") == mlt_service_tractor_type + || resource() == "") && (m_producer->get(kShotcutXmlProperty)); } @@ -700,11 +712,8 @@ bool Controller::isFileProducer(Service *service) const { if (service && service->is_valid()) { QString serviceName = service->get("mlt_service"); - return (serviceName == "pixbuf" || - serviceName == "qimage" || - serviceName == "glaxnimate" || - serviceName.startsWith("avformat") || - serviceName.startsWith("timewarp")); + return (serviceName == "pixbuf" || serviceName == "qimage" || serviceName == "glaxnimate" + || serviceName.startsWith("avformat") || serviceName.startsWith("timewarp")); } return false; } @@ -755,7 +764,8 @@ void Controller::fastForward(bool forceChangeDirection) void Controller::previous(int currentPosition) { - if (isMultitrack()) return; + if (isMultitrack()) + return; if (currentPosition > m_producer->get_out()) seek(MLT.producer()->get_out()); else if (currentPosition <= m_producer->get_in()) @@ -766,7 +776,8 @@ void Controller::previous(int currentPosition) void Controller::next(int currentPosition) { - if (isMultitrack()) return; + if (isMultitrack()) + return; if (currentPosition < m_producer->get_in()) seek(m_producer->get_in()); else if (currentPosition >= m_producer->get_out()) @@ -804,84 +815,38 @@ void Controller::setOut(int out) class FixLengthPropertiesParser : public Mlt::Parser { public: - FixLengthPropertiesParser() : Mlt::Parser() {} + FixLengthPropertiesParser() + : Mlt::Parser() + {} - int on_start_filter(Mlt::Filter *) - { - return 0; - } - int on_start_producer(Mlt::Producer *) - { - return 0; - } + int on_start_filter(Mlt::Filter *) { return 0; } + int on_start_producer(Mlt::Producer *) { return 0; } int on_end_producer(Mlt::Producer *s) { if (!::strchr(s->get("length"), ':')) s->set("length", s->frames_to_time(s->get_int("length"), mlt_time_clock)); return 0; } - int on_start_playlist(Mlt::Playlist *) - { - return 0; - } - int on_end_playlist(Mlt::Playlist *) - { - return 0; - } - int on_start_tractor(Mlt::Tractor *) - { - return 0; - } - int on_end_tractor(Mlt::Tractor *) - { - return 0; - } - int on_start_multitrack(Mlt::Multitrack *) - { - return 0; - } - int on_end_multitrack(Mlt::Multitrack *) - { - return 0; - } - int on_start_track() - { - return 0; - } - int on_end_track() - { - return 0; - } - int on_end_filter(Mlt::Filter *) - { - return 0; - } - int on_start_transition(Mlt::Transition *) - { - return 0; - } - int on_end_transition(Mlt::Transition *) - { - return 0; - } - int on_start_chain(Mlt::Chain *) - { - return 0; - } + int on_start_playlist(Mlt::Playlist *) { return 0; } + int on_end_playlist(Mlt::Playlist *) { return 0; } + int on_start_tractor(Mlt::Tractor *) { return 0; } + int on_end_tractor(Mlt::Tractor *) { return 0; } + int on_start_multitrack(Mlt::Multitrack *) { return 0; } + int on_end_multitrack(Mlt::Multitrack *) { return 0; } + int on_start_track() { return 0; } + int on_end_track() { return 0; } + int on_end_filter(Mlt::Filter *) { return 0; } + int on_start_transition(Mlt::Transition *) { return 0; } + int on_end_transition(Mlt::Transition *) { return 0; } + int on_start_chain(Mlt::Chain *) { return 0; } int on_end_chain(Mlt::Chain *s) { if (!::strchr(s->get("length"), ':')) s->set("length", s->frames_to_time(s->get_int("length"), mlt_time_clock)); return 0; } - int on_start_link(Mlt::Link *) - { - return 0; - } - int on_end_link(Mlt::Link *) - { - return 0; - } + int on_start_link(Mlt::Link *) { return 0; } + int on_end_link(Mlt::Link *) { return 0; } }; void Controller::fixLengthProperties(Service &service) @@ -962,8 +927,8 @@ void Controller::updateAvformatCaching(int trackCount) bool Controller::isAudioFilter(const QString &name) { - QScopedPointer metadata(m_repo->metadata(mlt_service_filter_type, - name.toLatin1().constData())); + QScopedPointer metadata( + m_repo->metadata(mlt_service_filter_type, name.toLatin1().constData())); if (metadata->is_valid()) { Properties tags(metadata->get_data("tags")); if (tags.is_valid()) { @@ -1000,8 +965,9 @@ void Controller::setImageDurationFromDefault(Service *service) const if (service && service->is_valid()) { if (isImageProducer(service) && !service->get_int("shotcut_sequence")) { service->set("ttl", 1); - service->set("length", service->frames_to_time(qRound(m_profile.fps() * kMaxImageDurationSecs), - mlt_time_clock)); + service->set("length", + service->frames_to_time(qRound(m_profile.fps() * kMaxImageDurationSecs), + mlt_time_clock)); service->set("out", qRound(m_profile.fps() * Settings.imageDuration()) - 1); } } @@ -1013,8 +979,9 @@ void Controller::setDurationFromDefault(Producer *producer) const int out = qRound(m_profile.fps() * Settings.imageDuration()) - 1; if (out >= producer->get_length()) producer->set("length", producer->frames_to_time(out + 1, mlt_time_clock)); - producer->set("length", producer->frames_to_time(qRound(m_profile.fps() * kMaxImageDurationSecs), - mlt_time_clock)); + producer->set("length", + producer->frames_to_time(qRound(m_profile.fps() * kMaxImageDurationSecs), + mlt_time_clock)); producer->set("out", out); } } @@ -1078,8 +1045,7 @@ QUuid Controller::uuid(Mlt::Properties &properties) const void Controller::setUuid(Mlt::Properties &properties, QUuid uid) const { - properties.set(kUuidProperty, - (uid.toByteArray() + '\n').data()); + properties.set(kUuidProperty, (uid.toByteArray() + '\n').data()); } QUuid Controller::ensureHasUuid(Mlt::Properties &properties) const @@ -1097,8 +1063,7 @@ static int indexOfFirstNonGpu(Producer &toProducer) for (int i = 0; i < toProducer.filter_count(); i++) { QScopedPointer filter(toProducer.filter(i)); if (filter && filter->is_valid() && !filter->get_int("_loader") - && !filter->get_int(kShotcutHiddenProperty) - && filter->get("mlt_service")) { + && !filter->get_int(kShotcutHiddenProperty) && filter->get("mlt_service")) { if (!QString::fromLatin1(filter->get("mlt_service")).startsWith("movit.")) return i; } @@ -1107,8 +1072,7 @@ static int indexOfFirstNonGpu(Producer &toProducer) for (int i = 0; i < toChain.link_count(); i++) { QScopedPointer link(toChain.link(i)); if (link && link->is_valid() && !link->get_int("_loader") - && !link->get_int(kShotcutHiddenProperty) - && link->get("mlt_service")) { + && !link->get_int(kShotcutHiddenProperty) && link->get("mlt_service")) { if (!QString::fromLatin1(link->get("mlt_service")).startsWith("movit.")) return i; } @@ -1116,13 +1080,15 @@ static int indexOfFirstNonGpu(Producer &toProducer) return -1; } -void Controller::copyFilters(Producer &fromProducer, Producer &toProducer, bool fromClipboard, +void Controller::copyFilters(Producer &fromProducer, + Producer &toProducer, + bool fromClipboard, int filterIndex) { - int in = fromProducer.get(kFilterInProperty) ? fromProducer.get_int(kFilterInProperty) : - fromProducer.get_in(); - int out = fromProducer.get(kFilterOutProperty) ? fromProducer.get_int( - kFilterOutProperty) : fromProducer.get_out(); + int in = fromProducer.get(kFilterInProperty) ? fromProducer.get_int(kFilterInProperty) + : fromProducer.get_in(); + int out = fromProducer.get(kFilterOutProperty) ? fromProducer.get_int(kFilterOutProperty) + : fromProducer.get_out(); int count = fromProducer.filter_count(); int filterCount = 0; @@ -1132,9 +1098,7 @@ void Controller::copyFilters(Producer &fromProducer, Producer &toProducer, bool for (int i = 0; i < count; i++) { QScopedPointer fromFilter(fromProducer.filter(i)); if (fromFilter && fromFilter->is_valid() && !fromFilter->get_int("_loader") - && !fromFilter->get_int(kShotcutHiddenProperty) - && fromFilter->get("mlt_service")) { - + && !fromFilter->get_int(kShotcutHiddenProperty) && fromFilter->get("mlt_service")) { filterCount++; if (filterIndex >= 0 && filterIndex != (filterCount - 1)) { continue; @@ -1151,7 +1115,8 @@ void Controller::copyFilters(Producer &fromProducer, Producer &toProducer, bool continue; } if (!metadata->allowMultiple()) { - std::unique_ptr existing(getFilter(metadata->uniqueId(), &toProducer)); + std::unique_ptr existing( + getFilter(metadata->uniqueId(), &toProducer)); if (existing && !existing->get_int("_loader")) { continue; } @@ -1171,21 +1136,23 @@ void Controller::copyFilters(Producer &fromProducer, Producer &toProducer, bool if (!fromClipboard) { toFilter.set(kFilterInProperty, fromFilter->get_in() - in); if (fromFilter->get_out() != out) { - toFilter.set(kFilterOutProperty, fromFilter->get_out() - fromFilter->get_in()); + toFilter.set(kFilterOutProperty, + fromFilter->get_out() - fromFilter->get_in()); } } } } } - if (fromProducer.type() == mlt_service_chain_type && toProducer.type() == mlt_service_chain_type) { + if (fromProducer.type() == mlt_service_chain_type + && toProducer.type() == mlt_service_chain_type) { Mlt::Chain fromChain(fromProducer); Mlt::Chain toChain(toProducer); count = fromChain.link_count(); for (int i = 0; i < count; i++) { QScopedPointer fromLink(fromChain.link(i)); if (fromLink && fromLink->is_valid() && fromLink->get("mlt_service") - && !fromLink->get_int("_loader")) { + && !fromLink->get_int("_loader")) { filterCount++; if (filterIndex != -1 && filterIndex != (filterCount - 1)) { continue; @@ -1195,7 +1162,7 @@ void Controller::copyFilters(Producer &fromProducer, Producer &toProducer, bool toLink.inherit(*fromLink); toChain.attach(toLink); if (firstNonGpuService >= 0 - && QString::fromLatin1(fromLink->get("mlt_service")).startsWith("movit.")) + && QString::fromLatin1(fromLink->get("mlt_service")).startsWith("movit.")) toChain.move_link(toChain.link_count(), firstNonGpuService++); } } @@ -1216,9 +1183,9 @@ void Controller::copyFilters(Mlt::Producer *producer, int filterIndex) void Controller::pasteFilters(Mlt::Producer *producer, Producer *fromProducer) { - Mlt::Producer *targetProducer = (producer && producer->is_valid()) ? producer + Mlt::Producer *targetProducer = (producer && producer->is_valid()) ? producer : (m_producer && m_producer->is_valid()) ? m_producer.data() - : nullptr; + : nullptr; if (targetProducer) { int j = targetProducer->filter_count(); if (fromProducer && fromProducer->is_valid()) { @@ -1233,9 +1200,10 @@ void Controller::pasteFilters(Mlt::Producer *producer, Producer *fromProducer) void Controller::adjustFilters(Producer &producer, int index) { bool changed = false; - int in = producer.get(kFilterInProperty) ? producer.get_int(kFilterInProperty) : producer.get_in(); - int out = producer.get(kFilterOutProperty) ? producer.get_int(kFilterOutProperty) : - producer.get_out(); + int in = producer.get(kFilterInProperty) ? producer.get_int(kFilterInProperty) + : producer.get_in(); + int out = producer.get(kFilterOutProperty) ? producer.get_int(kFilterOutProperty) + : producer.get_out(); int n = producer.filter_count(); for (; index < n; index++) { @@ -1263,16 +1231,25 @@ void Controller::adjustFilters(Producer &producer, int index) if (filterName == "fadeOutBrightness") { const char *key = filter->get_int("alpha") != 1 ? "alpha" : "level"; filter->clear(key); - filter->anim_set(key, 1, filter->get_length() - filter->get_int(kShotcutAnimOutProperty)); + filter->anim_set(key, + 1, + filter->get_length() + - filter->get_int(kShotcutAnimOutProperty)); filter->anim_set(key, 0, filter->get_length() - 1); } else if (filterName == "fadeOutMovit") { filter->clear("opacity"); - filter->anim_set("opacity", 1, filter->get_length() - filter->get_int(kShotcutAnimOutProperty), 0, + filter->anim_set("opacity", + 1, + filter->get_length() - filter->get_int(kShotcutAnimOutProperty), + 0, mlt_keyframe_smooth); filter->anim_set("opacity", 0, filter->get_length() - 1); } else if (filterName == "fadeOutVolume") { filter->clear("level"); - filter->anim_set("level", 0, filter->get_length() - filter->get_int(kShotcutAnimOutProperty)); + filter->anim_set("level", + 0, + filter->get_length() + - filter->get_int(kShotcutAnimOutProperty)); filter->anim_set("level", -60, filter->get_length() - 1); } else if (filter->get_int(kShotcutAnimOutProperty) > 0) { // Update simple keyframes. @@ -1282,16 +1259,24 @@ void Controller::adjustFilters(Producer &producer, int index) if (!filter->get_animation(name.toUtf8().constData())) { // Cause a string property to be interpreted as animated value. if (meta->keyframes()->parameter(name)->isColor()) - filter->anim_get_color(name.toUtf8().constData(), 0, filter->get_length()); + filter->anim_get_color(name.toUtf8().constData(), + 0, + filter->get_length()); else - filter->anim_get_double(name.toUtf8().constData(), 0, filter->get_length()); + filter->anim_get_double(name.toUtf8().constData(), + 0, + filter->get_length()); } - Mlt::Animation animation = filter->get_animation(name.toUtf8().constData()); + Mlt::Animation animation = filter->get_animation( + name.toUtf8().constData()); if (animation.is_valid()) { int n = animation.key_count(); if (n > 1) { animation.set_length(filter->get_length()); - animation.key_set_frame(n - 2, filter->get_length() - filter->get_int(kShotcutAnimOutProperty)); + animation.key_set_frame(n - 2, + filter->get_length() + - filter->get_int( + kShotcutAnimOutProperty)); animation.key_set_frame(n - 1, filter->get_length() - 1); } } @@ -1377,8 +1362,8 @@ static void shiftKeyframes(Mlt::Service *service, QmlMetadata *meta, int delta) } } -void Controller::adjustFilter(Mlt::Filter *filter, int in, int out, int inDelta, int outDelta, - int keyframeDelta) +void Controller::adjustFilter( + Mlt::Filter *filter, int in, int out, int inDelta, int outDelta, int keyframeDelta) { if (!filter || !filter->is_valid()) { return; @@ -1396,9 +1381,9 @@ void Controller::adjustFilter(Mlt::Filter *filter, int in, int out, int inDelta, inDelta = -in; } if (keyframeDelta - && filter->get_int(kShotcutAnimInProperty) == filter->get_int(kShotcutAnimOutProperty)) { + && filter->get_int(kShotcutAnimInProperty) == filter->get_int(kShotcutAnimOutProperty)) { // Shift all keyframes proportional to the in delta if they are not simple keyframes - shiftKeyframes(filter, meta, keyframeDelta); + shiftKeyframes(filter, meta, keyframeDelta); } if (filterName.startsWith("fadeIn")) { if (!filter->get(kShotcutAnimInProperty)) { @@ -1416,16 +1401,23 @@ void Controller::adjustFilter(Mlt::Filter *filter, int in, int out, int inDelta, if (filterName == "fadeOutBrightness") { const char *key = filter->get_int("alpha") != 1 ? "alpha" : "level"; filter->clear(key); - filter->anim_set(key, 1, filter->get_length() - filter->get_int(kShotcutAnimOutProperty)); + filter->anim_set(key, + 1, + filter->get_length() - filter->get_int(kShotcutAnimOutProperty)); filter->anim_set(key, 0, filter->get_length() - 1); } else if (filterName == "fadeOutMovit") { filter->clear("opacity"); - filter->anim_set("opacity", 1, filter->get_length() - filter->get_int(kShotcutAnimOutProperty), 0, + filter->anim_set("opacity", + 1, + filter->get_length() - filter->get_int(kShotcutAnimOutProperty), + 0, mlt_keyframe_smooth); filter->anim_set("opacity", 0, filter->get_length() - 1); } else if (filterName == "fadeOutVolume") { filter->clear("level"); - filter->anim_set("level", 0, filter->get_length() - filter->get_int(kShotcutAnimOutProperty)); + filter->anim_set("level", + 0, + filter->get_length() - filter->get_int(kShotcutAnimOutProperty)); filter->anim_set("level", -60, filter->get_length() - 1); } emit MAIN.serviceInChanged(inDelta, filter); @@ -1446,16 +1438,23 @@ void Controller::adjustFilter(Mlt::Filter *filter, int in, int out, int inDelta, if (filterName == "fadeOutBrightness") { const char *key = filter->get_int("alpha") != 1 ? "alpha" : "level"; filter->clear(key); - filter->anim_set(key, 1, filter->get_length() - filter->get_int(kShotcutAnimOutProperty)); + filter->anim_set(key, + 1, + filter->get_length() - filter->get_int(kShotcutAnimOutProperty)); filter->anim_set(key, 0, filter->get_length() - 1); } else if (filterName == "fadeOutMovit") { filter->clear("opacity"); - filter->anim_set("opacity", 1, filter->get_length() - filter->get_int(kShotcutAnimOutProperty), 0, + filter->anim_set("opacity", + 1, + filter->get_length() - filter->get_int(kShotcutAnimOutProperty), + 0, mlt_keyframe_smooth); filter->anim_set("opacity", 0, filter->get_length() - 1); } else if (filterName == "fadeOutVolume") { filter->clear("level"); - filter->anim_set("level", 0, filter->get_length() - filter->get_int(kShotcutAnimOutProperty)); + filter->anim_set("level", + 0, + filter->get_length() - filter->get_int(kShotcutAnimOutProperty)); filter->anim_set("level", -60, filter->get_length() - 1); } emit MAIN.serviceOutChanged(outDelta, filter); @@ -1465,15 +1464,19 @@ void Controller::adjustFilter(Mlt::Filter *filter, int in, int out, int inDelta, emit MAIN.serviceOutChanged(outDelta, filter); // Update simple keyframes - if ((filter->get_int(kShotcutAnimInProperty) || filter->get_int(kShotcutAnimOutProperty)) && meta - && meta->keyframes()) { + if ((filter->get_int(kShotcutAnimInProperty) || filter->get_int(kShotcutAnimOutProperty)) + && meta && meta->keyframes()) { for (const QString &name : meta->keyframes()->simpleProperties()) { if (!filter->get_animation(name.toUtf8().constData())) { // Cause a string property to be interpreted as animated value. if (meta->keyframes()->parameter(name)->isColor()) - filter->anim_get_color(name.toUtf8().constData(), 0, filter->get_length()); + filter->anim_get_color(name.toUtf8().constData(), + 0, + filter->get_length()); else - filter->anim_get_double(name.toUtf8().constData(), 0, filter->get_length()); + filter->anim_get_double(name.toUtf8().constData(), + 0, + filter->get_length()); } Mlt::Animation animation = filter->get_animation(name.toUtf8().constData()); if (animation.is_valid()) { @@ -1483,7 +1486,10 @@ void Controller::adjustFilter(Mlt::Filter *filter, int in, int out, int inDelta, if (filter->get_int(kShotcutAnimInProperty) > filter->get_length() - 1) { animation.key_set_frame(n - 1, filter->get_length() - 1); } else if (filter->get_int(kShotcutAnimOutProperty)) { - animation.key_set_frame(n - 2, filter->get_length() - filter->get_int(kShotcutAnimOutProperty)); + animation.key_set_frame(n - 2, + filter->get_length() + - filter->get_int( + kShotcutAnimOutProperty)); animation.key_set_frame(n - 1, filter->get_length() - 1); } } @@ -1494,8 +1500,8 @@ void Controller::adjustFilter(Mlt::Filter *filter, int in, int out, int inDelta, } } -void Controller::adjustClipFilters(Mlt::Producer &producer, int in, int out, int inDelta, - int outDelta, int keyframeDelta) +void Controller::adjustClipFilters( + Mlt::Producer &producer, int in, int out, int inDelta, int outDelta, int keyframeDelta) { for (int j = 0; j < producer.filter_count(); j++) { QScopedPointer filter(producer.filter(j)); @@ -1511,7 +1517,7 @@ void Controller::adjustClipFilters(Mlt::Producer &producer, int in, int out, int QmlMetadata *meta = MAIN.filterController()->metadataForService(link.data()); if (link && link->is_valid()) { if (keyframeDelta) { - shiftKeyframes(link.data(), meta, keyframeDelta); + shiftKeyframes(link.data(), meta, keyframeDelta); } if (link->get_out() >= out) { link->set_in_and_out(link->get_in(), out - outDelta); @@ -1582,7 +1588,7 @@ int Controller::filterIn(Playlist &playlist, int clipIndex) if (info) { QScopedPointer info2(playlist.clip_info(clipIndex - 1)); if (info2 && info2->producer && info2->producer->is_valid() - && info2->producer->get(kShotcutTransitionProperty)) { + && info2->producer->get(kShotcutTransitionProperty)) { // Factor in a transition left of the clip. result = info->frame_in - info2->frame_count; } else { @@ -1599,7 +1605,7 @@ int Controller::filterOut(Playlist &playlist, int clipIndex) if (info) { QScopedPointer info2(playlist.clip_info(clipIndex + 1)); if (info2 && info2->producer && info2->producer->is_valid() - && info2->producer->get(kShotcutTransitionProperty)) { + && info2->producer->get(kShotcutTransitionProperty)) { // Factor in a transition right of the clip. result = info->frame_out + info2->frame_count; } else { @@ -1615,9 +1621,11 @@ void Controller::setPreviewScale(int scale) auto height = m_profile.height(); if (scale > 0) { height = MIN(scale, m_profile.height()); - width = (height == m_profile.height()) ? m_profile.width() : - Util::coerceMultiple(height * m_profile.display_aspect_num() / m_profile.display_aspect_den() - * m_profile.sample_aspect_den() / m_profile.sample_aspect_num()); + width = (height == m_profile.height()) + ? m_profile.width() + : Util::coerceMultiple( + height * m_profile.display_aspect_num() / m_profile.display_aspect_den() + * m_profile.sample_aspect_den() / m_profile.sample_aspect_num()); } LOG_DEBUG() << width << "x" << height; m_previewProfile.set_width(width); @@ -1636,7 +1644,8 @@ void Controller::updatePreviewProfile() m_previewProfile.set_height(Util::coerceMultiple(m_profile.height())); m_previewProfile.set_progressive(m_profile.progressive()); m_previewProfile.set_sample_aspect(m_profile.sample_aspect_num(), m_profile.sample_aspect_den()); - m_previewProfile.set_display_aspect(m_profile.display_aspect_num(), m_profile.display_aspect_den()); + m_previewProfile.set_display_aspect(m_profile.display_aspect_num(), + m_profile.display_aspect_den()); m_previewProfile.set_explicit(true); } @@ -1669,16 +1678,16 @@ bool Controller::fullRange(Producer &producer) bool Controller::isTrackProducer(Producer &producer) { mlt_service_type service_type = producer.type(); - return service_type == mlt_service_playlist_type || - (service_type == mlt_service_tractor_type && producer.get_int(kShotcutXmlProperty)); + return service_type == mlt_service_playlist_type + || (service_type == mlt_service_tractor_type && producer.get_int(kShotcutXmlProperty)); } int Controller::checkFile(const QString &path) { int error = 0; if (path.endsWith(".json") || path.endsWith(".rawr") || path.endsWith(".lottie") - || path.endsWith(".riv") || path.endsWith(".tgs") || path.endsWith(".avd") - || path.endsWith(".aep")) { + || path.endsWith(".riv") || path.endsWith(".tgs") || path.endsWith(".avd") + || path.endsWith(".aep")) { QString shotcutPath = qApp->applicationDirPath(); #if defined(Q_OS_UNIX) && !defined(Q_OS_MAC) QFileInfo meltPath(shotcutPath, "melt-7"); @@ -1686,9 +1695,14 @@ int Controller::checkFile(const QString &path) QFileInfo meltPath(shotcutPath, "melt"); #endif QStringList args; - args << "-quiet" << "-consumer" << "null" << "real_time=0" << "out=0" << "terminate_on_pause=1" << - "glaxnimate:" + path; - LOG_DEBUG() << meltPath.absoluteFilePath() + " " + args.join(' '); + args << "-quiet" + << "-consumer" + << "null" + << "real_time=0" + << "out=0" + << "terminate_on_pause=1" + << "glaxnimate:" + path; + LOG_DEBUG() << meltPath.absoluteFilePath() + " " + args.join(' '); error = QProcess::execute(meltPath.absoluteFilePath(), args); } return error; @@ -1750,4 +1764,4 @@ void TransportControl::setOut(int out) MLT.setOut(out); } -} // namespace +} // namespace Mlt diff --git a/src/mltcontroller.h b/src/mltcontroller.h index ae639a2f77..ed18b3cd1e 100644 --- a/src/mltcontroller.h +++ b/src/mltcontroller.h @@ -18,22 +18,23 @@ #ifndef MLTCONTROLLER_H #define MLTCONTROLLER_H +#include "transportcontrol.h" + +#include #include -#include -#include +#include #include +#include #include -#include -#include -#include "transportcontrol.h" +#include // forward declarations class QQuickView; #define MLT_LC_CATEGORY LC_ALL -#define MLT_LC_NAME "LC_ALL" +#define MLT_LC_NAME "LC_ALL" -#if LIBMLT_VERSION_INT >= ((7<<16)+(19<<8)) +#if LIBMLT_VERSION_INT >= ((7 << 16) + (19 << 8)) #define kAudioIndexProperty "astream" #define kVideoIndexProperty "vstream" #else @@ -97,8 +98,12 @@ class Controller void onWindowResize(); virtual void seek(int position); virtual void refreshConsumer(bool scrubAudio = false); - bool saveXML(const QString &filename, Service *service = nullptr, bool withRelativePaths = true, - QTemporaryFile *tempFile = nullptr, bool proxy = false, QString projectNote = QString()); + bool saveXML(const QString &filename, + Service *service = nullptr, + bool withRelativePaths = true, + QTemporaryFile *tempFile = nullptr, + bool proxy = false, + QString projectNote = QString()); QString XML(Service *service = nullptr, bool withProfile = false, bool withMetadata = true); int consumerChanged(); void setProfile(const QString &profile_name); @@ -134,66 +139,35 @@ class Controller QUuid uuid(Mlt::Properties &properties) const; void setUuid(Mlt::Properties &properties, QUuid uid) const; QUuid ensureHasUuid(Mlt::Properties &properties) const; - static void copyFilters(Mlt::Producer &fromProducer, Mlt::Producer &toProducer, - bool fromClipboard = false, int filterIndex = FILTER_INDEX_ENABLED); + static void copyFilters(Mlt::Producer &fromProducer, + Mlt::Producer &toProducer, + bool fromClipboard = false, + int filterIndex = FILTER_INDEX_ENABLED); void copyFilters(Mlt::Producer *producer = nullptr, int filterIndex = FILTER_INDEX_ENABLED); void pasteFilters(Mlt::Producer *producer = nullptr, Mlt::Producer *fromProducer = nullptr); static void adjustFilters(Mlt::Producer &producer, int startIndex = 0); - static void adjustFilter(Mlt::Filter *filter, int in, int out, int inDelta, int outDelta, - int keyframeDelta); - static void adjustClipFilters(Mlt::Producer &producer, int in, int out, int inDelta, int outDelta, - int keyframeDelta); + static void adjustFilter( + Mlt::Filter *filter, int in, int out, int inDelta, int outDelta, int keyframeDelta); + static void adjustClipFilters( + Mlt::Producer &producer, int in, int out, int inDelta, int outDelta, int keyframeDelta); bool hasFiltersOnClipboard() const { return m_filtersClipboard->is_valid() && m_filtersClipboard->filter_count() > 0; } - QString filtersClipboardXML() - { - return XML(m_filtersClipboard.get()); - } - - int audioChannels() const - { - return m_audioChannels; - } - Mlt::Repository *repository() const - { - return m_repo; - } - Mlt::Profile &profile() - { - return m_profile; - } - Mlt::Profile &previewProfile() - { - return m_previewProfile; - } - Mlt::Producer *producer() const - { - return m_producer.data(); - } - Mlt::Consumer *consumer() const - { - return m_consumer.data(); - } - const QString &URL() const - { - return m_url; - } - const TransportControllable *transportControl() const - { - return &m_transportControl; - } - Mlt::Producer *savedProducer() const - { - return m_savedProducer.data(); - } + QString filtersClipboardXML() { return XML(m_filtersClipboard.get()); } + + int audioChannels() const { return m_audioChannels; } + Mlt::Repository *repository() const { return m_repo; } + Mlt::Profile &profile() { return m_profile; } + Mlt::Profile &previewProfile() { return m_previewProfile; } + Mlt::Producer *producer() const { return m_producer.data(); } + Mlt::Consumer *consumer() const { return m_consumer.data(); } + const QString &URL() const { return m_url; } + const TransportControllable *transportControl() const { return &m_transportControl; } + Mlt::Producer *savedProducer() const { return m_savedProducer.data(); } void setSavedProducer(Mlt::Producer *producer); static Mlt::Filter *getFilter(const QString &name, Mlt::Service *service); - QString projectFolder() const - { - return m_projectFolder; - } + QString projectFolder() const { return m_projectFolder; } void setProjectFolder(const QString &folderName); QChar decimalPoint(); static void resetLocale(); @@ -203,10 +177,7 @@ class Controller void updatePreviewProfile(); static void purgeMemoryPool(); static bool fullRange(Mlt::Producer &producer); - static bool isMltXml(const QString &s) - { - return s.contains(" -#include #include -#include +#include +#include #include -#include +#include + #include #include @@ -35,11 +37,9 @@ static QString getPrefix(const QString &name, const QString &value); static bool isMltClass(const QString &name) { - return name == "profile" || name == "producer" || - name == "filter" || name == "playlist" || - name == "tractor" || name == "track" || - name == "transition" || name == "consumer" || - name == "chain" || name == "link"; + return name == "profile" || name == "producer" || name == "filter" || name == "playlist" + || name == "tractor" || name == "track" || name == "transition" || name == "consumer" + || name == "chain" || name == "link"; } static bool isNetworkResource(const QString &string) @@ -53,8 +53,7 @@ static bool isNetworkResource(const QString &string) static bool isNumericProperty(const QString &name) { - return name == "length" || name == "geometry" || - name == "rect" || name == "warp_speed"; + return name == "length" || name == "geometry" || name == "rect" || name == "warp_speed"; } MltXmlChecker::MltXmlChecker() @@ -74,8 +73,7 @@ QXmlStreamReader::Error MltXmlChecker::check(const QString &fileName) LOG_DEBUG() << "begin"; QFile file(fileName); - m_tempFile.reset(new QTemporaryFile( - QFileInfo(fileName).dir().filePath("shotcut-XXXXXX.mlt"))); + m_tempFile.reset(new QTemporaryFile(QFileInfo(fileName).dir().filePath("shotcut-XXXXXX.mlt"))); if (file.open(QIODevice::ReadOnly | QIODevice::Text) && m_tempFile->open()) { m_tempFile->resize(0); m_fileInfo = QFileInfo(fileName); @@ -97,7 +95,8 @@ QXmlStreamReader::Error MltXmlChecker::check(const QString &fileName) } else if (a.name().toString().toLower() == "version") { m_mltVersion = QVersionNumber::fromString(a.value()); } else if (a.name().toString().toLower() == "title") { - m_newXml.writeAttribute(a.name().toString(), "Shotcut version " SHOTCUT_VERSION); + m_newXml.writeAttribute(a.name().toString(), + "Shotcut version " SHOTCUT_VERSION); auto parts = a.value().split(' '); LOG_DEBUG() << parts; if (parts.size() > 2 && parts[1].toString() == "version") { @@ -125,9 +124,9 @@ QXmlStreamReader::Error MltXmlChecker::check(const QString &fileName) m_tempFile->close(); // Useful for debugging -// m_tempFile->open(); -// LOG_DEBUG() << m_tempFile->readAll().constData(); -// m_tempFile->close(); + // m_tempFile->open(); + // LOG_DEBUG() << m_tempFile->readAll().constData(); + // m_tempFile->close(); } LOG_DEBUG() << "end" << m_xml.errorString(); return m_xml.error(); @@ -163,7 +162,8 @@ void MltXmlChecker::readMlt() m_xml.processingInstructionData().toString()); break; case QXmlStreamReader::StartDocument: - m_newXml.writeStartDocument(m_xml.documentVersion().toString(), m_xml.isStandaloneDocument()); + m_newXml.writeStartDocument(m_xml.documentVersion().toString(), + m_xml.isStandaloneDocument()); break; case QXmlStreamReader::EndDocument: m_newXml.writeEndDocument(); @@ -235,13 +235,13 @@ void MltXmlChecker::processProperties() } if (mlt_class == "filter" || mlt_class == "transition" || mlt_class == "producer" - || mlt_class == "chain" || mlt_class == "link") { + || mlt_class == "chain" || mlt_class == "link") { checkGpuEffects(mlt_service); checkCpuEffects(mlt_service); checkUnlinkedFile(mlt_service); checkIncludesSelf(newProperties); checkLumaAlphaOver(mlt_service, newProperties); -#if LIBMLT_VERSION_INT >= ((6<<16)+(23<<8)) +#if LIBMLT_VERSION_INT >= ((6 << 16) + (23 << 8)) replaceWebVfxCropFilters(mlt_service, newProperties); replaceWebVfxChoppyFilter(mlt_service, newProperties); #endif @@ -277,12 +277,9 @@ void MltXmlChecker::processProperties() } else if (relinkMismatch && p.first.startsWith("meta.")) { // Remove meta properties if re-linked file is different. p.second.clear(); - } else if ((proxyEnabled - && m_resource.notProxyMeta - && p.first.startsWith("meta.")) || - (!proxyEnabled - && m_resource.isProxy - && (p.first == kIsProxyProperty || p.first.startsWith("meta.")))) { + } else if ((proxyEnabled && m_resource.notProxyMeta && p.first.startsWith("meta.")) + || (!proxyEnabled && m_resource.isProxy + && (p.first == kIsProxyProperty || p.first.startsWith("meta.")))) { // Remove meta properties if they misrepresent proxy/original p.second.clear(); m_isUpdated = true; @@ -323,8 +320,7 @@ void MltXmlChecker::checkInAndOutPoints() bool MltXmlChecker::checkNumericString(QString &value) { // Determine if there is a decimal point inconsistent with locale. - if (!value.contains(m_decimalPoint) && - (value.contains('.') || value.contains(','))) { + if (!value.contains(m_decimalPoint) && (value.contains('.') || value.contains(','))) { value.replace(',', m_decimalPoint); value.replace('.', m_decimalPoint); m_numericValueChanged = true; @@ -408,11 +404,10 @@ static QString getSuffix(const QString &name, const QString &value) bool MltXmlChecker::readResourceProperty(const QString &name, QString &value) { if (mlt_class == "filter" || mlt_class == "transition" || mlt_class == "producer" - || mlt_class == "chain" || mlt_class == "link") - if (name == "resource" || name == "src" || name == "filename" - || name == "luma" || name == "luma.resource" || name == "composite.luma" - || name == "producer.resource" || name == "av.file" || name == "warp_resource") { - + || mlt_class == "chain" || mlt_class == "link") + if (name == "resource" || name == "src" || name == "filename" || name == "luma" + || name == "luma.resource" || name == "composite.luma" || name == "producer.resource" + || name == "av.file" || name == "warp_resource") { // Handle special prefix such as "plain:" or speed. m_resource.prefix = getPrefix(name, value); m_resource.suffix = getSuffix(name, value); @@ -420,7 +415,8 @@ bool MltXmlChecker::readResourceProperty(const QString &name, QString &value) filePath = filePath.left(filePath.size() - m_resource.suffix.size()); // Save the resource name (minus prefix) for later check for unlinked files. m_resource.info.setFile(filePath); - if (!isNetworkResource(value) && m_resource.info.isRelative() && !Util::hasDriveLetter(value)) + if (!isNetworkResource(value) && m_resource.info.isRelative() + && !Util::hasDriveLetter(value)) m_resource.info.setFile(m_fileInfo.canonicalPath(), m_resource.info.filePath()); return true; } @@ -460,16 +456,23 @@ void MltXmlChecker::checkUnlinkedFile(const QString &mlt_service) // not an invalid blank if (mlt_service != "blank" || fileName != "blank") // not a URL - if (!m_resource.info.filePath().isEmpty() && !isNetworkResource(m_resource.info.filePath())) + if (!m_resource.info.filePath().isEmpty() + && !isNetworkResource(m_resource.info.filePath())) // not an image sequence - if ((mlt_service != "pixbuf" && mlt_service != "qimage") || fileName.indexOf('%') == -1) + if ((mlt_service != "pixbuf" && mlt_service != "qimage") + || fileName.indexOf('%') == -1) // file does not exist if (!m_resource.info.exists()) // not already in the model - if (m_unlinkedFilesModel.findItems(filePath, - Qt::MatchFixedString | Qt::MatchCaseSensitive).isEmpty()) { - LOG_ERROR() << "file not found: " << m_resource.info.filePath(); - QIcon icon(":/icons/oxygen/32x32/status/task-reject.png"); + if (m_unlinkedFilesModel + .findItems(filePath, + Qt::MatchFixedString + | Qt::MatchCaseSensitive) + .isEmpty()) { + LOG_ERROR() + << "file not found: " << m_resource.info.filePath(); + QIcon icon( + ":/icons/oxygen/32x32/status/task-reject.png"); QStandardItem *item = new QStandardItem(icon, filePath); item->setToolTip(item->text()); item->setData(m_resource.hash, ShotcutHashRole); @@ -482,9 +485,9 @@ bool MltXmlChecker::fixUnlinkedFile(QString &value) // Replace unlinked files if model is populated with replacements. for (int row = 0; row < m_unlinkedFilesModel.rowCount(); ++row) { const QStandardItem *replacement = m_unlinkedFilesModel.item(row, ReplacementColumn); - if (replacement && !replacement->text().isEmpty() && - m_unlinkedFilesModel.item(row, - MissingColumn)->text() == QDir::toNativeSeparators(m_resource.info.filePath())) { + if (replacement && !replacement->text().isEmpty() + && m_unlinkedFilesModel.item(row, MissingColumn)->text() + == QDir::toNativeSeparators(m_resource.info.filePath())) { m_resource.info.setFile(replacement->text()); m_resource.newDetail = replacement->text(); m_resource.newHash = replacement->data(ShotcutHashRole).toString(); diff --git a/src/mltxmlchecker.h b/src/mltxmlchecker.h index 407dfcb5ad..c420c2f2cb 100644 --- a/src/mltxmlchecker.h +++ b/src/mltxmlchecker.h @@ -18,67 +18,36 @@ #ifndef MLTXMLCHECKER_H #define MLTXMLCHECKER_H -#include -#include -#include -#include #include +#include #include +#include +#include #include -#include #include +#include +#include class QUIDevice; class MltXmlChecker { public: + enum { ShotcutHashRole = Qt::UserRole + 1 }; - enum { - ShotcutHashRole = Qt::UserRole + 1 - }; - - enum { - MissingColumn = 0, - ReplacementColumn, - ColumnCount - }; + enum { MissingColumn = 0, ReplacementColumn, ColumnCount }; MltXmlChecker(); QXmlStreamReader::Error check(const QString &fileName); QString errorString() const; - bool needsGPU() const - { - return m_needsGPU; - } - bool needsCPU() const - { - return m_needsCPU; - } - bool hasEffects() const - { - return m_hasEffects; - } - bool isCorrected() const - { - return m_isCorrected; - } - bool isUpdated() const - { - return m_isUpdated; - } - QTemporaryFile &tempFile() const - { - return *m_tempFile; - } - QStandardItemModel &unlinkedFilesModel() - { - return m_unlinkedFilesModel; - } - QString shotcutVersion() const - { - return m_shotcutVersion; - } + bool needsGPU() const { return m_needsGPU; } + bool needsCPU() const { return m_needsCPU; } + bool hasEffects() const { return m_hasEffects; } + bool isCorrected() const { return m_isCorrected; } + bool isUpdated() const { return m_isUpdated; } + QTemporaryFile &tempFile() const { return *m_tempFile; } + QStandardItemModel &unlinkedFilesModel() { return m_unlinkedFilesModel; } + QString shotcutVersion() const { return m_shotcutVersion; } private: typedef QPair MltProperty; @@ -116,7 +85,8 @@ class MltXmlChecker QStandardItemModel m_unlinkedFilesModel; QString mlt_class; QVector m_properties; - struct MltXmlResource { + struct MltXmlResource + { QFileInfo info; QString hash; QString newHash; diff --git a/src/models/actionsmodel.cpp b/src/models/actionsmodel.cpp index cca218d567..84df09443a 100644 --- a/src/models/actionsmodel.cpp +++ b/src/models/actionsmodel.cpp @@ -17,14 +17,14 @@ #include "actionsmodel.h" +#include "Logger.h" #include "actions.h" -#include #include +#include #include #include #include -#include ActionsModel::ActionsModel(QObject *parent) : QAbstractItemModel(parent) @@ -70,7 +70,7 @@ QVariant ActionsModel::data(const QModelIndex &index, int role) const } if (!index.isValid() || index.column() < 0 || index.column() >= COLUMN_COUNT || index.row() < 0 - || index.row() >= m_actions.size()) { + || index.row() >= m_actions.size()) { LOG_ERROR() << "Invalid Index: " << index.row() << index.column() << role; return result; } @@ -87,8 +87,7 @@ QVariant ActionsModel::data(const QModelIndex &index, int role) const QList sequences = action->shortcuts(); if (sequences.size() > 0) result = sequences[0].toString(QKeySequence::NativeText); - } - break; + } break; case COLUMN_SEQUENCE2: { result = action->property(Actions.hardKeyProperty); if (result.toString().isEmpty()) { @@ -96,8 +95,7 @@ QVariant ActionsModel::data(const QModelIndex &index, int role) const if (sequences.size() > 1) result = sequences[1].toString(QKeySequence::NativeText); } - } - break; + } break; default: LOG_ERROR() << "Invalid Column" << index.column() << role; break; @@ -110,7 +108,8 @@ QVariant ActionsModel::data(const QModelIndex &index, int role) const if (index.column() == COLUMN_SEQUENCE1) { QFont font; QList sequences = action->shortcuts(); - if (sequences.size() > 0 && sequences[0] != action->property(Actions.defaultKey1Property)) { + if (sequences.size() > 0 + && sequences[0] != action->property(Actions.defaultKey1Property)) { font.setBold(true); } result = font; @@ -119,15 +118,17 @@ QVariant ActionsModel::data(const QModelIndex &index, int role) const QList sequences = action->shortcuts(); if (action->property(Actions.hardKeyProperty).isValid()) { font.setItalic(true); - } else if (sequences.size() > 1 && sequences[1] != action->property(Actions.defaultKey2Property)) { + } else if (sequences.size() > 1 + && sequences[1] != action->property(Actions.defaultKey2Property)) { font.setBold(true); } - result = font; + result = font; } break; case Qt::ForegroundRole: - if (index.column() == COLUMN_SEQUENCE2 && action->property(Actions.hardKeyProperty).isValid()) { - result = QGuiApplication::palette().color(QPalette::Disabled, QPalette::Text); + if (index.column() == COLUMN_SEQUENCE2 + && action->property(Actions.hardKeyProperty).isValid()) { + result = QGuiApplication::palette().color(QPalette::Disabled, QPalette::Text); } break; case ActionsModel::HardKeyRole: @@ -155,7 +156,7 @@ QVariant ActionsModel::data(const QModelIndex &index, int role) const bool ActionsModel::setData(const QModelIndex &index, const QVariant &value, int role) { - if (!index.isValid() ) + if (!index.isValid()) return false; if (role != Qt::EditRole) @@ -184,8 +185,9 @@ bool ActionsModel::setData(const QModelIndex &index, const QVariant &value, int for (int i = 0; i < sequences.size(); i++) { if (sequences[i] == ks) { if (a != action) { - QString error = tr("Shortcut %1 is used by %2").arg(ks.toString(), a->property( - Actions.displayProperty).toString()); + QString error = tr("Shortcut %1 is used by %2") + .arg(ks.toString(), + a->property(Actions.displayProperty).toString()); emit editError(error); } return false; @@ -193,8 +195,9 @@ bool ActionsModel::setData(const QModelIndex &index, const QVariant &value, int } QString hardKey = a->property(Actions.hardKeyProperty).toString(); if (!hardKey.isEmpty() && hardKey == ks.toString()) { - QString error = tr("Shortcut %1 is reserved for use by %2").arg(ks.toString(), a->property( - Actions.displayProperty).toString()); + QString error = tr("Shortcut %1 is reserved for use by %2") + .arg(ks.toString(), + a->property(Actions.displayProperty).toString()); emit editError(error); return false; } @@ -208,7 +211,7 @@ bool ActionsModel::setData(const QModelIndex &index, const QVariant &value, int if (oldShortcuts.size() > 1 && oldShortcuts[1] != ks) { newShortcuts << oldShortcuts[1]; } - } else if (index.column() == COLUMN_SEQUENCE2) { + } else if (index.column() == COLUMN_SEQUENCE2) { if (oldShortcuts.size() > 0 && oldShortcuts[0] != ks) { newShortcuts << oldShortcuts[0]; } @@ -217,8 +220,8 @@ bool ActionsModel::setData(const QModelIndex &index, const QVariant &value, int Actions.overrideShortcuts(action->objectName(), newShortcuts); - emit dataChanged(this->index(index.row(), COLUMN_SEQUENCE1), this->index(index.row(), - COLUMN_SEQUENCE2)); + emit dataChanged(this->index(index.row(), COLUMN_SEQUENCE1), + this->index(index.row(), COLUMN_SEQUENCE2)); return true; } @@ -246,7 +249,7 @@ QModelIndex ActionsModel::index(int row, int column, const QModelIndex &parent) Q_UNUSED(parent) if (column < 0 || column >= COLUMN_COUNT || row < 0 || row >= m_actions.size()) return QModelIndex(); - return createIndex(row, column, (int)0); + return createIndex(row, column, (int) 0); } QModelIndex ActionsModel::parent(const QModelIndex &index) const diff --git a/src/models/actionsmodel.h b/src/models/actionsmodel.h index 6334b683e5..1bbb7ad068 100644 --- a/src/models/actionsmodel.h +++ b/src/models/actionsmodel.h @@ -51,7 +51,8 @@ class ActionsModel : public QAbstractItemModel QVariant data(const QModelIndex &index, int role) const override; bool setData(const QModelIndex &index, const QVariant &value, int role) override; QVariant headerData(int section, Qt::Orientation orientation, int role) const override; - QModelIndex index(int row, int column = 0, + QModelIndex index(int row, + int column = 0, const QModelIndex &parent = QModelIndex()) const override; QModelIndex parent(const QModelIndex &index) const override; Qt::ItemFlags flags(const QModelIndex &index) const override; diff --git a/src/models/alignclipsmodel.cpp b/src/models/alignclipsmodel.cpp index 171dbde585..9781999ffc 100644 --- a/src/models/alignclipsmodel.cpp +++ b/src/models/alignclipsmodel.cpp @@ -16,19 +16,16 @@ */ #include "alignclipsmodel.h" -#include "settings.h" -#include +#include "Logger.h" #include "mltcontroller.h" +#include "settings.h" AlignClipsModel::AlignClipsModel(QObject *parent) : QAbstractItemModel(parent) -{ -} +{} -AlignClipsModel::~AlignClipsModel() -{ -} +AlignClipsModel::~AlignClipsModel() {} void AlignClipsModel::clear() { @@ -54,7 +51,7 @@ void AlignClipsModel::updateProgress(int row, int percent) { QModelIndex modelIndex = index(row, COLUMN_NAME); if (!modelIndex.isValid() || modelIndex.column() < 0 || modelIndex.column() >= COLUMN_COUNT - || modelIndex.row() < 0 || modelIndex.row() >= m_clips.size()) { + || modelIndex.row() < 0 || modelIndex.row() >= m_clips.size()) { LOG_ERROR() << "Invalid Index: " << modelIndex.row() << modelIndex.column(); return; } @@ -133,7 +130,7 @@ QVariant AlignClipsModel::data(const QModelIndex &index, int role) const } if (!index.isValid() || index.column() < 0 || index.column() >= COLUMN_COUNT || index.row() < 0 - || index.row() >= m_clips.size()) { + || index.row() >= m_clips.size()) { LOG_ERROR() << "Invalid Index: " << index.row() << index.column() << role; return result; } @@ -150,11 +147,13 @@ QVariant AlignClipsModel::data(const QModelIndex &index, int role) const break; case COLUMN_OFFSET: if (clip.progress != 0 && clip.offset != INVALID_OFFSET && MLT.producer() - && MLT.producer()->is_valid()) { + && MLT.producer()->is_valid()) { if (clip.offset >= 0) { - result = QString::fromLatin1(MLT.producer()->frames_to_time(clip.offset, Settings.timeFormat())); + result = QString::fromLatin1( + MLT.producer()->frames_to_time(clip.offset, Settings.timeFormat())); } else { - result = QStringLiteral("-") + MLT.producer()->frames_to_time(-clip.offset, Settings.timeFormat()); + result = QStringLiteral("-") + + MLT.producer()->frames_to_time(-clip.offset, Settings.timeFormat()); } } break; @@ -163,7 +162,8 @@ QVariant AlignClipsModel::data(const QModelIndex &index, int role) const result = QLocale().toString(clip.speed * 100.0, 'g', 4); break; default: - LOG_ERROR() << "Invalid Column" << index.row() << index.column() << roleNames()[role] << role; + LOG_ERROR() << "Invalid Column" << index.row() << index.column() << roleNames()[role] + << role; break; } break; @@ -180,7 +180,8 @@ QVariant AlignClipsModel::data(const QModelIndex &index, int role) const result = Qt::AlignCenter; break; default: - LOG_ERROR() << "Invalid Column" << index.row() << index.column() << roleNames()[role] << role; + LOG_ERROR() << "Invalid Column" << index.row() << index.column() << roleNames()[role] + << role; break; } break; @@ -215,7 +216,7 @@ QModelIndex AlignClipsModel::index(int row, int column, const QModelIndex &paren Q_UNUSED(parent) if (column < 0 || column >= COLUMN_COUNT || row < 0 || row >= m_clips.size()) return QModelIndex(); - return createIndex(row, column, (int)0); + return createIndex(row, column, (int) 0); } QModelIndex AlignClipsModel::parent(const QModelIndex &index) const diff --git a/src/models/alignclipsmodel.h b/src/models/alignclipsmodel.h index 04e6fe05be..26a2986c9d 100644 --- a/src/models/alignclipsmodel.h +++ b/src/models/alignclipsmodel.h @@ -27,7 +27,6 @@ class AlignClipsModel : public QAbstractItemModel Q_OBJECT public: - enum Columns { COLUMN_ERROR = 0, COLUMN_NAME, @@ -57,7 +56,8 @@ class AlignClipsModel : public QAbstractItemModel QModelIndex parent(const QModelIndex &index) const; private: - typedef struct { + typedef struct + { QString name; int offset; double speed; diff --git a/src/models/attachedfiltersmodel.cpp b/src/models/attachedfiltersmodel.cpp index c21a2e8ca9..acc79ae6e4 100644 --- a/src/models/attachedfiltersmodel.cpp +++ b/src/models/attachedfiltersmodel.cpp @@ -16,25 +16,25 @@ */ #include "attachedfiltersmodel.h" -#include "mltcontroller.h" -#include "mainwindow.h" + +#include "Logger.h" #include "commands/filtercommands.h" #include "controllers/filtercontroller.h" +#include "mainwindow.h" +#include "mltcontroller.h" +#include "qmltypes/qmlapplication.h" #include "qmltypes/qmlmetadata.h" +#include "settings.h" #include "shotcut_mlt_properties.h" #include "util.h" -#include "qmltypes/qmlapplication.h" -#include "settings.h" +#include +#include #include +#include +#include #include #include -#include -#include - -#include -#include -#include static int sortOrder(const QmlMetadata *meta) { @@ -60,7 +60,8 @@ static int normalFilterCount(Mlt::Producer *producer) if (producer && producer->is_valid()) { for (int i = 0; i < producer->filter_count(); i++) { Mlt::Filter *filter = producer->filter(i); - if (filter->is_valid() && (filter->get_int("_loader") || filter->get_int(kShotcutHiddenProperty))) { + if (filter->is_valid() + && (filter->get_int("_loader") || filter->get_int(kShotcutHiddenProperty))) { count++; } else { i = producer->filter_count(); @@ -124,8 +125,7 @@ static int mltLinkIndex(Mlt::Producer *producer, int row) AttachedFiltersModel::AttachedFiltersModel(QObject *parent) : QAbstractListModel(parent) , m_dropRow(-1) -{ -} +{} Mlt::Service *AttachedFiltersModel::getService(int row) const { @@ -177,7 +177,7 @@ bool AttachedFiltersModel::isProducerSelected() const bool AttachedFiltersModel::supportsLinks() const { if (!m_producer.isNull() && m_producer->is_valid() - && m_producer->type() == mlt_service_chain_type ) { + && m_producer->type() == mlt_service_chain_type) { return true; } return false; @@ -216,10 +216,9 @@ Qt::ItemFlags AttachedFiltersModel::flags(const QModelIndex &index) const QVariant AttachedFiltersModel::data(const QModelIndex &index, int role) const { - if (!m_producer || !m_producer->is_valid() - || index.row() >= m_metaList.size()) + if (!m_producer || !m_producer->is_valid() || index.row() >= m_metaList.size()) return QVariant(); - switch (role ) { + switch (role) { case Qt::DisplayRole: return name(index.row()); case Qt::CheckStateRole: { @@ -229,8 +228,7 @@ QVariant AttachedFiltersModel::data(const QModelIndex &index, int role) const result = Qt::Checked; delete service; return result; - } - break; + } break; case TypeDisplayRole: { QVariant result; const QmlMetadata *meta = m_metaList[index.row()]; @@ -249,8 +247,7 @@ QVariant AttachedFiltersModel::data(const QModelIndex &index, int role) const const QmlMetadata *meta = m_metaList[index.row()]; QVariant result = meta ? meta->type() : QmlMetadata::Filter; return result; - } - break; + } break; default: break; } @@ -269,8 +266,8 @@ bool AttachedFiltersModel::setData(const QModelIndex &index, const QVariant &, i if (isSourceClip()) { doSetDisabled(*m_producer.data(), index.row(), !disabled); } else { - MAIN.undoStack()->push(new Filter::DisableCommand(*this, name(index.row()), index.row(), - !disabled)); + MAIN.undoStack()->push( + new Filter::DisableCommand(*this, name(index.row()), index.row(), !disabled)); } } else { LOG_ERROR() << "Invalid filter index" << index.row(); @@ -363,8 +360,11 @@ bool AttachedFiltersModel::removeRows(int row, int, const QModelIndex &parent) } } -bool AttachedFiltersModel::moveRows(const QModelIndex &sourceParent, int sourceRow, int count, - const QModelIndex &destinationParent, int destinationRow) +bool AttachedFiltersModel::moveRows(const QModelIndex &sourceParent, + int sourceRow, + int count, + const QModelIndex &destinationParent, + int destinationRow) { if (!m_producer || !m_producer->is_valid() || sourceParent != destinationParent || count != 1) { return false; @@ -377,7 +377,8 @@ bool AttachedFiltersModel::moveRows(const QModelIndex &sourceParent, int sourceR if (isSourceClip()) { doMoveService(*m_producer, sourceRow, destinationRow); } else { - MAIN.undoStack()->push(new Filter::MoveCommand(*this, name(sourceRow), sourceRow, destinationRow)); + MAIN.undoStack()->push( + new Filter::MoveCommand(*this, name(sourceRow), sourceRow, destinationRow)); } return true; @@ -442,7 +443,8 @@ void AttachedFiltersModel::doMoveService(Mlt::Producer &producer, int fromRow, i int AttachedFiltersModel::add(QmlMetadata *meta) { int insertRow = -1; - if (!m_producer) return -1; + if (!m_producer) + return -1; if (!meta->allowMultiple()) { for (int i = 0; i < m_metaList.count(); i++) { @@ -454,7 +456,7 @@ int AttachedFiltersModel::add(QmlMetadata *meta) } } if (m_producer->is_valid() && mlt_service_tractor_type != m_producer->type() - && !QmlApplication::confirmOutputFilter()) { + && !QmlApplication::confirmOutputFilter()) { return -1; } @@ -466,26 +468,30 @@ int AttachedFiltersModel::add(QmlMetadata *meta) filter.set(kNewFilterProperty, 1); if (!meta->objectName().isEmpty()) filter.set(kShotcutFilterProperty, meta->objectName().toUtf8().constData()); - filter.set_in_and_out( - m_producer->get(kFilterInProperty) ? m_producer->get_int(kFilterInProperty) : m_producer->get_in(), - m_producer->get(kFilterOutProperty) ? m_producer->get_int(kFilterOutProperty) : - m_producer->get_out()); + filter.set_in_and_out(m_producer->get(kFilterInProperty) + ? m_producer->get_int(kFilterInProperty) + : m_producer->get_in(), + m_producer->get(kFilterOutProperty) + ? m_producer->get_int(kFilterOutProperty) + : m_producer->get_out()); if (isSourceClip()) { doAddService(*m_producer, filter, insertRow); } else { - MAIN.undoStack()->push(new Filter::AddCommand(*this, meta->name(), filter, insertRow)); + MAIN.undoStack()->push( + new Filter::AddCommand(*this, meta->name(), filter, insertRow)); } } - } - break; + } break; case QmlMetadata::Link: { if (m_producer->type() != mlt_service_chain_type) { LOG_ERROR() << "Not a chain"; return -1; } if (meta->seekReverse() && m_producer->get_int("meta.media.has_b_frames") != 0) { - emit requestConvert(tr("This file has B-frames, which is not supported by %1.").arg(meta->name()), - false, true); + emit requestConvert(tr("This file has B-frames, which is not supported by %1.") + .arg(meta->name()), + false, + true); return -1; } Mlt::Link link(meta->mlt_service().toUtf8().constData()); @@ -494,18 +500,19 @@ int AttachedFiltersModel::add(QmlMetadata *meta) link.set(kNewFilterProperty, 1); if (!meta->objectName().isEmpty()) link.set(kShotcutFilterProperty, meta->objectName().toUtf8().constData()); - link.set_in_and_out( - m_producer->get(kFilterInProperty) ? m_producer->get_int(kFilterInProperty) : m_producer->get_in(), - m_producer->get(kFilterOutProperty) ? m_producer->get_int(kFilterOutProperty) : - m_producer->get_out()); + link.set_in_and_out(m_producer->get(kFilterInProperty) + ? m_producer->get_int(kFilterInProperty) + : m_producer->get_in(), + m_producer->get(kFilterOutProperty) + ? m_producer->get_int(kFilterOutProperty) + : m_producer->get_out()); if (isSourceClip()) { doAddService(*m_producer, link, insertRow); } else { MAIN.undoStack()->push(new Filter::AddCommand(*this, meta->name(), link, insertRow)); } } - } - break; + } break; case QmlMetadata::FilterSet: { Mlt::Producer filterSetProducer = getFilterSetProducer(meta); if (!filterSetProducer.is_valid() || filterSetProducer.filter_count() == 0) { @@ -514,15 +521,18 @@ int AttachedFiltersModel::add(QmlMetadata *meta) } for (int i = 0; i < filterSetProducer.filter_count(); i++) { Mlt::Filter *filter = filterSetProducer.filter(i); - if (filter->is_valid() && !filter->get_int("_loader") && !filter->get_int(kShotcutHiddenProperty)) { + if (filter->is_valid() && !filter->get_int("_loader") + && !filter->get_int(kShotcutHiddenProperty)) { QmlMetadata *tmpMeta = MAIN.filterController()->metadataForService(filter); insertRow = findInsertRow(tmpMeta); if (!meta->objectName().isEmpty()) filter->set(kShotcutFilterProperty, meta->objectName().toUtf8().constData()); - filter->set_in_and_out( - m_producer->get(kFilterInProperty) ? m_producer->get_int(kFilterInProperty) : m_producer->get_in(), - m_producer->get(kFilterOutProperty) ? m_producer->get_int(kFilterOutProperty) : - m_producer->get_out()); + filter->set_in_and_out(m_producer->get(kFilterInProperty) + ? m_producer->get_int(kFilterInProperty) + : m_producer->get_in(), + m_producer->get(kFilterOutProperty) + ? m_producer->get_int(kFilterOutProperty) + : m_producer->get_out()); if (isSourceClip()) { doAddService(*m_producer, *filter, insertRow); } else { @@ -530,13 +540,13 @@ int AttachedFiltersModel::add(QmlMetadata *meta) if (i == filterSetProducer.filter_count() - 1) { type = Filter::AddCommand::AddSetLast; } - MAIN.undoStack()->push(new Filter::AddCommand(*this, meta->name(), *filter, insertRow, type)); + MAIN.undoStack()->push( + new Filter::AddCommand(*this, meta->name(), *filter, insertRow, type)); } } delete filter; } - } - break; + } break; default: LOG_ERROR() << "Unknown type" << meta->type(); break; @@ -548,7 +558,8 @@ int AttachedFiltersModel::add(QmlMetadata *meta) int AttachedFiltersModel::addService(Mlt::Service *service) { int insertRow = -1; - if (!m_producer) return -1; + if (!m_producer) + return -1; QmlMetadata *meta = MAIN.filterController()->metadataForService(service); if (!meta->allowMultiple()) { @@ -566,10 +577,12 @@ int AttachedFiltersModel::addService(Mlt::Service *service) insertRow = findInsertRow(meta); if (!meta->objectName().isEmpty()) filter.set(kShotcutFilterProperty, meta->objectName().toUtf8().constData()); - filter.set_in_and_out( - m_producer->get(kFilterInProperty) ? m_producer->get_int(kFilterInProperty) : m_producer->get_in(), - m_producer->get(kFilterOutProperty) ? m_producer->get_int(kFilterOutProperty) : - m_producer->get_out()); + filter.set_in_and_out(m_producer->get(kFilterInProperty) + ? m_producer->get_int(kFilterInProperty) + : m_producer->get_in(), + m_producer->get(kFilterOutProperty) + ? m_producer->get_int(kFilterOutProperty) + : m_producer->get_out()); if (isSourceClip()) { doAddService(*m_producer, filter, insertRow); } else { @@ -619,8 +632,7 @@ void AttachedFiltersModel::doAddService(Mlt::Producer &producer, Mlt::Service &s producer.move_filter(producer.filter_count() - 1, mltIndex); } emit changed(); - } - break; + } break; case mlt_service_link_type: { if (producer.type() != mlt_service_chain_type) { LOG_ERROR() << "Not a chain"; @@ -647,8 +659,7 @@ void AttachedFiltersModel::doAddService(Mlt::Producer &producer, Mlt::Service &s chain.move_link(chain.link_count() - 1, mltIndex); } emit changed(); - } - break; + } break; default: LOG_ERROR() << "invalid service type" << service.type(); break; @@ -683,7 +694,7 @@ void AttachedFiltersModel::doRemoveService(Mlt::Producer &producer, int row) int filterIndex = mltFilterIndex(&producer, row); int linkIndex = mltLinkIndex(&producer, row); LOG_DEBUG() << row << filterIndex << linkIndex; - if (linkIndex >= 0 ) { + if (linkIndex >= 0) { Mlt::Chain chain(producer); Mlt::Link *link = chain.link(linkIndex); if (isProducerLoaded(producer)) { @@ -741,8 +752,9 @@ void AttachedFiltersModel::reset(Mlt::Producer *producer) m_metaList.clear(); if (m_producer && m_producer->is_valid()) { - Mlt::Event *event = m_producer->listen("service-changed", this, - (mlt_listener)AttachedFiltersModel::producerChanged); + Mlt::Event *event = m_producer->listen("service-changed", + this, + (mlt_listener) AttachedFiltersModel::producerChanged); m_event.reset(event); int count = 0; if (m_producer->type() == mlt_service_chain_type) { @@ -763,7 +775,7 @@ void AttachedFiltersModel::reset(Mlt::Producer *producer) for (int i = 0; i < count; i++) { Mlt::Filter *filter = m_producer->filter(i); if (filter && filter->is_valid() && !filter->get_int("_loader") - && !filter->get_int(kShotcutHiddenProperty)) { + && !filter->get_int(kShotcutHiddenProperty)) { QmlMetadata *newMeta = MAIN.filterController()->metadataForService(filter); m_metaList.append(newMeta); } diff --git a/src/models/attachedfiltersmodel.h b/src/models/attachedfiltersmodel.h index 51c80f18cd..5c9306a708 100644 --- a/src/models/attachedfiltersmodel.h +++ b/src/models/attachedfiltersmodel.h @@ -18,10 +18,10 @@ #ifndef ATTACHEDFILTERSMODEL_H #define ATTACHEDFILTERSMODEL_H -#include +#include #include #include -#include +#include class QmlMetadata; @@ -46,10 +46,7 @@ class AttachedFiltersModel : public QAbstractListModel bool isProducerSelected() const; bool isSourceClip() const; bool supportsLinks() const; - Mlt::Producer *producer() const - { - return m_producer.data(); - } + Mlt::Producer *producer() const { return m_producer.data(); } QString name(int row) const; // The below are used by QUndoCommands @@ -68,8 +65,11 @@ class AttachedFiltersModel : public QAbstractListModel Qt::DropActions supportedDropActions() const; bool insertRows(int row, int count, const QModelIndex &parent); bool removeRows(int row, int count, const QModelIndex &parent); - bool moveRows(const QModelIndex &sourceParent, int sourceRow, int count, - const QModelIndex &destinationParent, int destinationRow); + bool moveRows(const QModelIndex &sourceParent, + int sourceRow, + int count, + const QModelIndex &destinationParent, + int destinationRow); signals: void changed(); diff --git a/src/models/audiolevelstask.cpp b/src/models/audiolevelstask.cpp index ad871b9769..7869b702d9 100644 --- a/src/models/audiolevelstask.cpp +++ b/src/models/audiolevelstask.cpp @@ -16,21 +16,23 @@ */ #include "audiolevelstask.h" + +#include "Logger.h" #include "database.h" -#include "shotcut_mlt_properties.h" -#include "settings.h" #include "mainwindow.h" +#include "settings.h" +#include "shotcut_mlt_properties.h" #include "util.h" -#include -#include -#include + #include +#include +#include +#include #include +#include #include -#include #include -#include -#include +#include static QList tasksList; static QMutex tasksListMutex; @@ -55,15 +57,17 @@ AudioLevelsTask::~AudioLevelsTask() delete p.first; } -void AudioLevelsTask::start(Mlt::Producer &producer, QObject *object, const QModelIndex &index, +void AudioLevelsTask::start(Mlt::Producer &producer, + QObject *object, + const QModelIndex &index, bool force) { if (Settings.timelineShowWaveforms() && producer.is_valid()) { - QString serviceName = producer.get("mlt_service"); - if (serviceName == "pixbuf" || serviceName == "qimage" || serviceName == "webvfx" || - serviceName == "color" || serviceName.startsWith("frei0r") || serviceName == "glaxnimate" || - (serviceName.startsWith("avformat") && producer.get_int("audio_index") == -1)) { + if (serviceName == "pixbuf" || serviceName == "qimage" || serviceName == "webvfx" + || serviceName == "color" || serviceName.startsWith("frei0r") + || serviceName == "glaxnimate" + || (serviceName.startsWith("avformat") && producer.get_int("audio_index") == -1)) { return; } @@ -122,8 +126,8 @@ Mlt::Producer *AudioLevelsTask::tempProducer() service = "avformat"; else if (service.startsWith("xml")) service = "xml-nogl"; - m_tempProducer.reset(new Mlt::Producer(m_profile, service.toUtf8().constData(), - producer->get("resource"))); + m_tempProducer.reset( + new Mlt::Producer(m_profile, service.toUtf8().constData(), producer->get("resource"))); if (m_tempProducer->is_valid()) { Mlt::Filter channels(m_profile, "audiochannels"); Mlt::Filter converter(m_profile, "audioconvert"); @@ -154,8 +158,10 @@ QString AudioLevelsTask::cacheKey() } if (producer->get("audio_index")) { // Add the audio index only if different than default to avoid cache miss. - if (m_isForce || (producer->get(kDefaultAudioIndexProperty) && - producer->get_int("audio_index") != producer->get_int(kDefaultAudioIndexProperty))) { + if (m_isForce + || (producer->get(kDefaultAudioIndexProperty) + && producer->get_int("audio_index") + != producer->get_int(kDefaultAudioIndexProperty))) { key += QStringLiteral(" %1").arg(producer->get("audio_index")); } } @@ -168,14 +174,15 @@ void AudioLevelsTask::run() QVariantList levels; QImage image = DB.getThumbnail(cacheKey()); if (image.isNull() || m_isForce) { - const char *key[2] = { "meta.media.audio_level.0", "meta.media.audio_level.1"}; + const char *key[2] = {"meta.media.audio_level.0", "meta.media.audio_level.1"}; QElapsedTimer updateTime; updateTime.start(); // TODO: use project channel count int channels = 2; auto message = QStringLiteral("%1 %2").arg(QObject::tr("generating audio waveforms for"), - Util::baseName(tempProducer()->get("resource"), true)); + Util::baseName(tempProducer()->get("resource"), + true)); if (tempProducer()->get("audio_index")) { LOG_DEBUG() << message << " with audio_index =" << tempProducer()->get("audio_index"); } else { @@ -189,7 +196,9 @@ void AudioLevelsTask::run() if (frame && frame->is_valid() && !frame->get_int("test_audio")) { mlt_audio_format format = mlt_audio_s16; int frequency = 48000; - int samples = mlt_audio_calculate_frame_samples(m_producers.first().first->get_fps(), frequency, i); + int samples = mlt_audio_calculate_frame_samples(m_producers.first().first->get_fps(), + frequency, + i); frame->get_audio(format, frequency, channels, samples); // for each channel for (int channel = 0; channel < channels; channel++) @@ -208,11 +217,17 @@ void AudioLevelsTask::run() foreach (ProducerAndIndex p, m_producers) { QVariantList *levelsCopy = new QVariantList(levels); p.first->lock(); - p.first->set(kAudioLevelsProperty, levelsCopy, 0, (mlt_destructor) deleteQVariantList); + p.first->set(kAudioLevelsProperty, + levelsCopy, + 0, + (mlt_destructor) deleteQVariantList); p.first->unlock(); - if (-1 != m_object->metaObject()->indexOfMethod("audioLevelsReady(QPersistentModelIndex)")) - QMetaObject::invokeMethod(m_object, "audioLevelsReady", Q_ARG(const QPersistentModelIndex &, - p.second)); + if (-1 + != m_object->metaObject()->indexOfMethod( + "audioLevelsReady(QPersistentModelIndex)")) + QMetaObject::invokeMethod(m_object, + "audioLevelsReady", + Q_ARG(const QPersistentModelIndex &, p.second)); } } } @@ -221,10 +236,12 @@ void AudioLevelsTask::run() int count = levels.size(); QImage image((count + 3) / 4 / channels, channels, QImage::Format_ARGB32); n = image.width() * image.height(); - for (int i = 0; i < n; i ++) { + for (int i = 0; i < n; i++) { QRgb p; if ((4 * i + 3) < count) { - p = qRgba(levels.at(4 * i).toInt(), levels.at(4 * i + 1).toInt(), levels.at(4 * i + 2).toInt(), + p = qRgba(levels.at(4 * i).toInt(), + levels.at(4 * i + 1).toInt(), + levels.at(4 * i + 2).toInt(), levels.at(4 * i + 3).toInt()); } else { int last = levels.last().toInt(); @@ -247,7 +264,9 @@ void AudioLevelsTask::run() } } message = QStringLiteral("%1 %2").arg(QObject::tr("Done"), message); - QMetaObject::invokeMethod(&MAIN, "showStatusMessage", Qt::QueuedConnection, + QMetaObject::invokeMethod(&MAIN, + "showStatusMessage", + Qt::QueuedConnection, Q_ARG(QString, message)); } else if (!m_isCanceled && !image.isNull()) { // convert cached image @@ -278,9 +297,11 @@ void AudioLevelsTask::run() p.first->lock(); p.first->set(kAudioLevelsProperty, levelsCopy, 0, (mlt_destructor) deleteQVariantList); p.first->unlock(); - if (-1 != m_object->metaObject()->indexOfMethod("audioLevelsReady(QPersistentModelIndex)")) - QMetaObject::invokeMethod(m_object, "audioLevelsReady", Q_ARG(const QPersistentModelIndex &, - p.second)); + if (-1 + != m_object->metaObject()->indexOfMethod("audioLevelsReady(QPersistentModelIndex)")) + QMetaObject::invokeMethod(m_object, + "audioLevelsReady", + Q_ARG(const QPersistentModelIndex &, p.second)); } } } diff --git a/src/models/audiolevelstask.h b/src/models/audiolevelstask.h index c315d04d6f..460a801067 100644 --- a/src/models/audiolevelstask.h +++ b/src/models/audiolevelstask.h @@ -20,18 +20,21 @@ #define AUDIOLEVELSTASK_H #include "multitrackmodel.h" -#include -#include -#include + #include #include +#include +#include +#include class AudioLevelsTask : public QRunnable { public: AudioLevelsTask(Mlt::Producer &producer, QObject *object, const QModelIndex &index); virtual ~AudioLevelsTask(); - static void start(Mlt::Producer &producer, QObject *object, const QModelIndex &index, + static void start(Mlt::Producer &producer, + QObject *object, + const QModelIndex &index, bool force = false); static void closeAll(); bool operator==(AudioLevelsTask &b); diff --git a/src/models/keyframesmodel.cpp b/src/models/keyframesmodel.cpp index 1b7084c755..882b2fb507 100644 --- a/src/models/keyframesmodel.cpp +++ b/src/models/keyframesmodel.cpp @@ -16,28 +16,23 @@ */ #include "keyframesmodel.h" + +#include "Logger.h" +#include "mltcontroller.h" #include "qmltypes/qmlapplication.h" -#include "qmltypes/qmlmetadata.h" #include "qmltypes/qmlfilter.h" -#include "mltcontroller.h" - -#include +#include "qmltypes/qmlmetadata.h" -#include #include +#include static const quintptr NO_PARENT_ID = quintptr(-1); KeyframesModel::KeyframesModel(QObject *parent) : QAbstractItemModel(parent) -{ - -} +{} -KeyframesModel::~KeyframesModel() -{ - -} +KeyframesModel::~KeyframesModel() {} int KeyframesModel::rowCount(const QModelIndex &parent) const { @@ -62,7 +57,7 @@ QVariant KeyframesModel::data(const QModelIndex &index, int role) const if (!m_metadata || !index.isValid()) return QVariant(); if (index.parent().isValid()) { -// LOG_DEBUG() << "keyframe" << index.internalId() << index.row() << role; + // LOG_DEBUG() << "keyframe" << index.internalId() << index.row() << role; // keyframes if (m_filter && index.internalId() < quintptr(m_propertyNames.count())) { QString name = m_propertyNames[index.internalId()]; @@ -78,7 +73,7 @@ QVariant KeyframesModel::data(const QModelIndex &index, int role) const case mlt_keyframe_discrete: type = tr("Hold"); break; -#if LIBMLT_VERSION_INT >= ((7<<16)+(21<<8)) +#if LIBMLT_VERSION_INT >= ((7 << 16) + (21 << 8)) case mlt_keyframe_smooth_loose: case mlt_keyframe_smooth_natural: case mlt_keyframe_smooth_tight: @@ -183,10 +178,14 @@ QVariant KeyframesModel::data(const QModelIndex &index, int role) const break; } double value = m_filter->getDouble(name, position); - QString units = m_metadata->keyframes()->parameter(m_metadataIndex[index.internalId()])->units(); - return QStringLiteral("%1 - %2\n%3%4").arg(QmlApplication::singleton().timeFromFrames( - position)).arg( - type).arg(value).arg(units); + QString units = m_metadata->keyframes() + ->parameter(m_metadataIndex[index.internalId()]) + ->units(); + return QStringLiteral("%1 - %2\n%3%4") + .arg(QmlApplication::singleton().timeFromFrames(position)) + .arg(type) + .arg(value) + .arg(units); } case FrameNumberRole: return position; @@ -211,7 +210,7 @@ QVariant KeyframesModel::data(const QModelIndex &index, int role) const result += 1; } -// LOG_DEBUG() << "keyframeIndex" << index.row() << "minimumFrame" << result; + // LOG_DEBUG() << "keyframeIndex" << index.row() << "minimumFrame" << result; return result; } case MaximumFrameRole: { @@ -222,7 +221,7 @@ QVariant KeyframesModel::data(const QModelIndex &index, int role) const } else { result -= 1; } -// LOG_DEBUG() << "keyframeIndex" << index.row() << "maximumFrame" << result; + // LOG_DEBUG() << "keyframeIndex" << index.row() << "maximumFrame" << result; return result; } default: @@ -232,7 +231,7 @@ QVariant KeyframesModel::data(const QModelIndex &index, int role) const } } } else if (index.row() < m_metadata->keyframes()->parameterCount()) { -// LOG_DEBUG() << "parameter" << index.row() << role; + // LOG_DEBUG() << "parameter" << index.row() << role; // parameters switch (role) { case Qt::DisplayRole: @@ -243,7 +242,8 @@ QVariant KeyframesModel::data(const QModelIndex &index, int role) const case IsCurveRole: return m_metadata->keyframes()->parameter(m_metadataIndex[index.row()])->isCurve(); case MinimumValueRole: { - QmlKeyframesParameter *param = m_metadata->keyframes()->parameter(m_metadataIndex[index.row()]); + QmlKeyframesParameter *param = m_metadata->keyframes()->parameter( + m_metadataIndex[index.row()]); if (param->rangeType() == QmlKeyframesParameter::MinMax) { return m_metadata->keyframes()->parameter(m_metadataIndex[index.row()])->minimum(); } else if (param->rangeType() == QmlKeyframesParameter::ClipLength) { @@ -252,17 +252,19 @@ QVariant KeyframesModel::data(const QModelIndex &index, int role) const return 0.0; } case MaximumValueRole: { - QmlKeyframesParameter *param = m_metadata->keyframes()->parameter(m_metadataIndex[index.row()]); + QmlKeyframesParameter *param = m_metadata->keyframes()->parameter( + m_metadataIndex[index.row()]); if (param->rangeType() == QmlKeyframesParameter::MinMax) { return m_metadata->keyframes()->parameter(m_metadataIndex[index.row()])->maximum(); } else if (param->rangeType() == QmlKeyframesParameter::ClipLength) { int length = m_filter->producer().get_length() - m_filter->in(); - return (double)length / MLT.profile().fps(); + return (double) length / MLT.profile().fps(); } return 0.0; } case LowestValueRole: { - QmlKeyframesParameter *param = m_metadata->keyframes()->parameter(m_metadataIndex[index.row()]); + QmlKeyframesParameter *param = m_metadata->keyframes()->parameter( + m_metadataIndex[index.row()]); Mlt::Animation animation = m_filter->getAnimation(param->property()); double min = std::numeric_limits::max(); if (animation.is_valid()) { @@ -270,15 +272,18 @@ QVariant KeyframesModel::data(const QModelIndex &index, int role) const int frame = animation.key_get_frame(i); if (frame >= 0) { double value = m_filter->getDouble(param->property(), frame); - if (value < min) min = value; + if (value < min) + min = value; } } } - if (min == std::numeric_limits::max()) min = 0; + if (min == std::numeric_limits::max()) + min = 0; return min; } case HighestValueRole: { - QmlKeyframesParameter *param = m_metadata->keyframes()->parameter(m_metadataIndex[index.row()]); + QmlKeyframesParameter *param = m_metadata->keyframes()->parameter( + m_metadataIndex[index.row()]); Mlt::Animation animation = m_filter->getAnimation(param->property()); double max = std::numeric_limits::lowest(); if (animation.is_valid()) { @@ -286,11 +291,13 @@ QVariant KeyframesModel::data(const QModelIndex &index, int role) const int frame = animation.key_get_frame(i); if (frame >= 0) { double value = m_filter->getDouble(param->property(), frame); - if (value > max) max = value; + if (value > max) + max = value; } } } - if (max == std::numeric_limits::lowest()) max = 0; + if (max == std::numeric_limits::lowest()) + max = 0; return max; } default: @@ -325,14 +332,14 @@ QModelIndex KeyframesModel::parent(const QModelIndex &index) const QHash KeyframesModel::roleNames() const { QHash roles; - roles[NameRole] = "name"; + roles[NameRole] = "name"; roles[PropertyNameRole] = "property"; - roles[IsCurveRole] = "isCurve"; + roles[IsCurveRole] = "isCurve"; roles[MinimumValueRole] = "minimum"; roles[MaximumValueRole] = "maximum"; roles[LowestValueRole] = "lowest"; roles[HighestValueRole] = "highest"; - roles[FrameNumberRole] = "frame"; + roles[FrameNumberRole] = "frame"; roles[KeyframeTypeRole] = "interpolation"; roles[PrevKeyframeTypeRole] = "prevInterpolation"; roles[NumericValueRole] = "value"; @@ -355,7 +362,7 @@ void KeyframesModel::load(QmlFilter *filter, QmlMetadata *meta) m_propertyNames << m_metadata->keyframes()->parameter(i)->property(); m_keyframeCounts << keyframeCount(m_propertyNames.count() - 1); m_metadataIndex << i; -// LOG_DEBUG() << m_propertyNames.last() << m_filter->get(m_propertyNames.last()) << keyframeCount(i); + // LOG_DEBUG() << m_propertyNames.last() << m_filter->get(m_propertyNames.last()) << keyframeCount(i); } } endResetModel(); @@ -398,7 +405,8 @@ bool KeyframesModel::remove(int parameterIndex, int keyframeIndex) modelIndex = index(keyframeIndex, 0, index(parameterIndex)); emit dataChanged(modelIndex, modelIndex, QVector() << MinimumFrameRole); } - emit dataChanged(index(parameterIndex), index(parameterIndex), + emit dataChanged(index(parameterIndex), + index(parameterIndex), QVector() << LowestValueRole << HighestValueRole); emit m_filter->changed(name.toUtf8().constData()); m_filter->endUndoCommand(); @@ -416,8 +424,10 @@ int KeyframesModel::previousKeyframePosition(int parameterIndex, int currentPosi Mlt::Animation animation = m_filter->getAnimation(name); if (animation.is_valid()) { currentPosition -= m_filter->in(); - bool error = animation.previous_key(animation.is_key(currentPosition) ? currentPosition - 1 : - currentPosition, result); + bool error = animation.previous_key(animation.is_key(currentPosition) + ? currentPosition - 1 + : currentPosition, + result); if (!error) result += m_filter->in(); } @@ -433,8 +443,9 @@ int KeyframesModel::nextKeyframePosition(int parameterIndex, int currentPosition Mlt::Animation animation = m_filter->getAnimation(name); if (animation.is_valid()) { currentPosition -= m_filter->in(); - bool error = animation.next_key(animation.is_key(currentPosition) ? currentPosition + 1 : - currentPosition, result); + bool error = animation.next_key(animation.is_key(currentPosition) ? currentPosition + 1 + : currentPosition, + result); if (!error) result += m_filter->in(); } @@ -474,7 +485,7 @@ bool KeyframesModel::setInterpolation(int parameterIndex, int keyframeIndex, Int Mlt::Animation animation = m_filter->getAnimation(name); if (animation.is_valid()) { if (!animation.key_set_type(keyframeIndex, mlt_keyframe_type(type))) { -// LOG_DEBUG() << "keyframe index" << keyframeIndex << "keyframe type" << type; + // LOG_DEBUG() << "keyframe index" << keyframeIndex << "keyframe type" << type; m_filter->startUndoModifyKeyframeCommand(parameterIndex, keyframeIndex); m_filter->updateUndoCommand(name); for (auto &key : gangedProperties(parameterIndex)) { @@ -487,9 +498,13 @@ bool KeyframesModel::setInterpolation(int parameterIndex, int keyframeIndex, Int mlt_event_data eventData = mlt_event_data_from_string(name.toUtf8().constData()); mlt_events_fire(m_filter->service().get_properties(), "property-changed", eventData); QModelIndex modelIndex = index(keyframeIndex, 0, index(parameterIndex)); - emit dataChanged(modelIndex, modelIndex, QVector() << KeyframeTypeRole << NameRole); + emit dataChanged(modelIndex, + modelIndex, + QVector() << KeyframeTypeRole << NameRole); QModelIndex nextModelIndex = index(keyframeIndex + 1, 0, index(parameterIndex)); - emit dataChanged(nextModelIndex, nextModelIndex, QVector() << PrevKeyframeTypeRole); + emit dataChanged(nextModelIndex, + nextModelIndex, + QVector() << PrevKeyframeTypeRole); error = false; emit m_filter->changed(name.toUtf8().constData()); emit m_filter->propertyChanged(name.toUtf8().constData()); @@ -498,8 +513,9 @@ bool KeyframesModel::setInterpolation(int parameterIndex, int keyframeIndex, Int } } if (error) - LOG_ERROR() << "failed to set keyframe" << "at parameter index" << parameterIndex << "keyframeIndex" - << keyframeIndex << "to type" << type; + LOG_ERROR() << "failed to set keyframe" + << "at parameter index" << parameterIndex << "keyframeIndex" << keyframeIndex + << "to type" << type; return error; } @@ -562,16 +578,18 @@ void KeyframesModel::setKeyframePosition(int parameterIndex, int keyframeIndex, m_filter->endUndoCommand(); } -void KeyframesModel::addKeyframe(int parameterIndex, double value, int position, +void KeyframesModel::addKeyframe(int parameterIndex, + double value, + int position, KeyframesModel::InterpolationType type) { if (m_filter && parameterIndex < m_propertyNames.count()) { QString name = m_propertyNames[parameterIndex]; m_filter->startUndoAddKeyframeCommand(); - m_filter->set(name, value, position, mlt_keyframe_type(type)); + m_filter->set(name, value, position, mlt_keyframe_type(type)); m_filter->updateUndoCommand(name); for (auto &key : gangedProperties(parameterIndex)) { - m_filter->set(key, value, position, mlt_keyframe_type(type)); + m_filter->set(key, value, position, mlt_keyframe_type(type)); m_filter->updateUndoCommand(key); } m_filter->endUndoCommand(); @@ -588,7 +606,9 @@ void KeyframesModel::addKeyframe(int parameterIndex, int position) auto value = m_filter->getRect(name, position); Mlt::Animation anim = m_filter->getAnimation(name); if (anim.is_valid() && !anim.is_key(position)) { - mlt_keyframe_type keyframeType = m_filter->getKeyframeType(anim, position, mlt_keyframe_type(-1)); + mlt_keyframe_type keyframeType = m_filter->getKeyframeType(anim, + position, + mlt_keyframe_type(-1)); m_filter->blockSignals(true); m_filter->set(name, value, position, keyframeType); m_filter->blockSignals(false); @@ -601,7 +621,9 @@ void KeyframesModel::addKeyframe(int parameterIndex, int position) auto value = m_filter->getColor(name, position); Mlt::Animation anim = m_filter->getAnimation(name); if (anim.is_valid() && !anim.is_key(position)) { - mlt_keyframe_type keyframeType = m_filter->getKeyframeType(anim, position, mlt_keyframe_type(-1)); + mlt_keyframe_type keyframeType = m_filter->getKeyframeType(anim, + position, + mlt_keyframe_type(-1)); m_filter->blockSignals(true); m_filter->set(name, value, position, keyframeType); for (auto &key : parameter->gangedProperties()) { @@ -618,7 +640,9 @@ void KeyframesModel::addKeyframe(int parameterIndex, int position) double value = m_filter->getDouble(name, position); Mlt::Animation anim = m_filter->getAnimation(name); if (anim.is_valid() && !anim.is_key(position)) { - mlt_keyframe_type keyframeType = m_filter->getKeyframeType(anim, position, mlt_keyframe_type(-1)); + mlt_keyframe_type keyframeType = m_filter->getKeyframeType(anim, + position, + mlt_keyframe_type(-1)); // Simply adding a keyframe does not change the current value of // the filter parameter. So, no need to trigger a bunch of signals // and refresh the consumer. Besides, refreshing the consumer is @@ -674,23 +698,33 @@ void KeyframesModel::setKeyframeValue(int parameterIndex, int keyframeIndex, dou } m_filter->startUndoModifyKeyframeCommand(parameterIndex, keyframeIndex); mlt_keyframe_type type = animation.key_get_type(keyframeIndex); - m_filter->service().anim_set(name.toUtf8().constData(), value, position, m_filter->duration(), + m_filter->service().anim_set(name.toUtf8().constData(), + value, + position, + m_filter->duration(), type); m_filter->updateUndoCommand(name); for (auto &key : gangedProperties(parameterIndex)) { - m_filter->service().anim_set(key.toUtf8().constData(), value, position, m_filter->duration(), type); + m_filter->service().anim_set(key.toUtf8().constData(), + value, + position, + m_filter->duration(), + type); m_filter->updateUndoCommand(key); } emit m_filter->changed(name.toUtf8().constData()); emit m_filter->propertyChanged(name.toUtf8().constData()); QModelIndex modelIndex = index(keyframeIndex, 0, index(parameterIndex)); emit dataChanged(modelIndex, modelIndex, QVector() << NumericValueRole << NameRole); - emit dataChanged(index(parameterIndex), index(parameterIndex), + emit dataChanged(index(parameterIndex), + index(parameterIndex), QVector() << LowestValueRole << HighestValueRole); m_filter->endUndoCommand(); } -void KeyframesModel::setKeyframeValuePosition(int parameterIndex, int keyframeIndex, double value, +void KeyframesModel::setKeyframeValuePosition(int parameterIndex, + int keyframeIndex, + double value, int position) { if (!m_filter) { @@ -738,11 +772,18 @@ void KeyframesModel::setKeyframeValuePosition(int parameterIndex, int keyframeIn } mlt_keyframe_type type = animation.key_get_type(keyframeIndex); - m_filter->service().anim_set(name.toUtf8().constData(), value, position, m_filter->duration(), + m_filter->service().anim_set(name.toUtf8().constData(), + value, + position, + m_filter->duration(), type); m_filter->updateUndoCommand(name); for (auto &key : gangedProperties(parameterIndex)) { - m_filter->service().anim_set(key.toUtf8().constData(), value, position, m_filter->duration(), type); + m_filter->service().anim_set(key.toUtf8().constData(), + value, + position, + m_filter->duration(), + type); m_filter->updateUndoCommand(key); } emit m_filter->changed(name.toUtf8().constData()); @@ -750,7 +791,8 @@ void KeyframesModel::setKeyframeValuePosition(int parameterIndex, int keyframeIn roles << NumericValueRole << NameRole; QModelIndex modelIndex = index(keyframeIndex, 0, index(parameterIndex)); emit dataChanged(modelIndex, modelIndex, roles); - emit dataChanged(index(parameterIndex), index(parameterIndex), + emit dataChanged(index(parameterIndex), + index(parameterIndex), QVector() << LowestValueRole << HighestValueRole); m_filter->endUndoCommand(); } @@ -899,7 +941,8 @@ void KeyframesModel::reload() void KeyframesModel::onFilterChanged(const QString &property) { bool isKeyframeProperty = false; - for (int p = 0; p < m_metadata->keyframes()->parameterCount() && isKeyframeProperty == false; p++) { + for (int p = 0; p < m_metadata->keyframes()->parameterCount() && isKeyframeProperty == false; + p++) { if (m_metadata->keyframes()->parameter(p)->property() == property) { isKeyframeProperty = true; break; @@ -934,7 +977,8 @@ void KeyframesModel::onFilterChanged(const QString &property) } else { // Keyframe count is unchanged. A value must have changed. emit dataChanged(index(i), index(i), QVector() << LowestValueRole << HighestValueRole); - emit dataChanged(index(0, 0, index(i)), index(m_keyframeCounts[i] - 1, 0, index(i)), + emit dataChanged(index(0, 0, index(i)), + index(m_keyframeCounts[i] - 1, 0, index(i)), QVector() << NumericValueRole << NameRole); } } @@ -944,13 +988,16 @@ void KeyframesModel::onFilterInChanged(int /*delta*/) QTimer::singleShot(0, this, SLOT(reload())); } - void KeyframesModel::trimFilterIn(int in) { Mlt::Service &service = m_filter->service(); if (service.is_valid() && service.type() == mlt_service_filter_type) { Mlt::Filter filter = service; - MLT.adjustFilter(&filter, filter.get_in(), filter.get_out(), in - filter.get_in(), 0, + MLT.adjustFilter(&filter, + filter.get_in(), + filter.get_out(), + in - filter.get_in(), + 0, in - filter.get_in()); m_filter->updateUndoCommand("in"); } diff --git a/src/models/keyframesmodel.h b/src/models/keyframesmodel.h index d08df78db0..c48d1638cd 100644 --- a/src/models/keyframesmodel.h +++ b/src/models/keyframesmodel.h @@ -18,10 +18,10 @@ #ifndef KEYFRAMESMODEL_H #define KEYFRAMESMODEL_H +#include +#include #include #include -#include -#include class QmlMetadata; class QmlFilter; @@ -73,18 +73,18 @@ class KeyframesModel : public QAbstractItemModel /// Two level model: parameters and keyframes on parameters enum Roles { NameRole = Qt::UserRole + 1, /// parameter or keyframe - PropertyNameRole, /// parameter only - IsCurveRole, /// parameter only - MinimumValueRole, /// parameter only - MaximumValueRole, /// parameter only - LowestValueRole, /// parameter only - HighestValueRole, /// parameter only - FrameNumberRole, /// keyframe only - KeyframeTypeRole, /// keyframe only - PrevKeyframeTypeRole, /// keyframe only - NumericValueRole, /// keyframe only - MinimumFrameRole, /// keyframe only - MaximumFrameRole /// keyframe only + PropertyNameRole, /// parameter only + IsCurveRole, /// parameter only + MinimumValueRole, /// parameter only + MaximumValueRole, /// parameter only + LowestValueRole, /// parameter only + HighestValueRole, /// parameter only + FrameNumberRole, /// keyframe only + KeyframeTypeRole, /// keyframe only + PrevKeyframeTypeRole, /// keyframe only + NumericValueRole, /// keyframe only + MinimumFrameRole, /// keyframe only + MaximumFrameRole /// keyframe only }; explicit KeyframesModel(QObject *parent = 0); @@ -93,8 +93,7 @@ class KeyframesModel : public QAbstractItemModel int rowCount(const QModelIndex &parent) const; int columnCount(const QModelIndex &parent) const; QVariant data(const QModelIndex &index, int role) const; - QModelIndex index(int row, int column = 0, - const QModelIndex &parent = QModelIndex()) const; + QModelIndex index(int row, int column = 0, const QModelIndex &parent = QModelIndex()) const; QModelIndex parent(const QModelIndex &index) const; QHash roleNames() const; void load(QmlFilter *, QmlMetadata *); @@ -105,11 +104,15 @@ class KeyframesModel : public QAbstractItemModel Q_INVOKABLE int parameterIndex(const QString &propertyName) const; Q_INVOKABLE bool setInterpolation(int parameterIndex, int keyframeIndex, InterpolationType type); Q_INVOKABLE void setKeyframePosition(int parameterIndex, int keyframeIndex, int position); - Q_INVOKABLE void addKeyframe(int parameterIndex, double value, int position, + Q_INVOKABLE void addKeyframe(int parameterIndex, + double value, + int position, InterpolationType type); Q_INVOKABLE void addKeyframe(int parameterIndex, int position); Q_INVOKABLE void setKeyframeValue(int parameterIndex, int keyframeIndex, double value); - Q_INVOKABLE void setKeyframeValuePosition(int parameterIndex, int keyframeIndex, double value, + Q_INVOKABLE void setKeyframeValuePosition(int parameterIndex, + int keyframeIndex, + double value, int position); Q_INVOKABLE bool isKeyframe(int parameterIndex, int position); Q_INVOKABLE bool advancedKeyframesInUse(); diff --git a/src/models/markersmodel.cpp b/src/models/markersmodel.cpp index 780ee39ab0..9d519ca7eb 100644 --- a/src/models/markersmodel.cpp +++ b/src/models/markersmodel.cpp @@ -17,13 +17,12 @@ #include "markersmodel.h" +#include "Logger.h" #include "commands/markercommands.h" #include "mainwindow.h" #include "settings.h" #include "shotcut_mlt_properties.h" -#include - enum Columns { COLUMN_COLOR = 0, COLUMN_NAME, @@ -33,18 +32,22 @@ enum Columns { COLUMN_COUNT }; -static void markerToProperties(const Markers::Marker &marker, Mlt::Properties *properties, +static void markerToProperties(const Markers::Marker &marker, + Mlt::Properties *properties, Mlt::Producer *producer) { properties->set("text", qUtf8Printable(marker.text)); properties->set("start", producer->frames_to_time(marker.start, mlt_time_clock)); properties->set("end", producer->frames_to_time(marker.end, mlt_time_clock)); - auto s = QString::asprintf("#%02X%02X%02X", marker.color.red(), marker.color.green(), + auto s = QString::asprintf("#%02X%02X%02X", + marker.color.red(), + marker.color.green(), marker.color.blue()); properties->set("color", s.toLatin1().constData()); } -static void propertiesToMarker(Mlt::Properties *properties, Markers::Marker &marker, +static void propertiesToMarker(Mlt::Properties *properties, + Markers::Marker &marker, Mlt::Producer *producer) { marker.text = QString::fromUtf8(properties->get("text")); @@ -57,12 +60,9 @@ static void propertiesToMarker(Mlt::Properties *properties, Markers::Marker &mar MarkersModel::MarkersModel(QObject *parent) : QAbstractItemModel(parent) , m_producer(nullptr) -{ -} +{} -MarkersModel::~MarkersModel() -{ -} +MarkersModel::~MarkersModel() {} void MarkersModel::load(Mlt::Producer *producer) { @@ -71,7 +71,7 @@ void MarkersModel::load(Mlt::Producer *producer) m_keys.clear(); if (m_producer) { Mlt::Properties *markerList = m_producer->get_props(kShotcutMarkersProperty); - if (markerList && markerList->is_valid()) { + if (markerList && markerList->is_valid()) { int count = markerList->count(); for (int i = 0; i < count; i++) { Mlt::Properties *markerProperties = markerList->get_props_at(i); @@ -145,13 +145,14 @@ void MarkersModel::doRemove(int markerIndex) markersListProperties->clear(qUtf8Printable(QString::number(m_keys[modelIndex.row()]))); m_keys.removeAt(modelIndex.row()); endRemoveRows(); - if (marker.end > marker.start) emit rangesChanged(); + if (marker.end > marker.start) + emit rangesChanged(); delete markersListProperties; emit modified(); } -void MarkersModel::doInsert(int markerIndex, const Markers::Marker &marker ) +void MarkersModel::doInsert(int markerIndex, const Markers::Marker &marker) { if (!m_producer) { LOG_ERROR() << "No producer"; @@ -161,7 +162,7 @@ void MarkersModel::doInsert(int markerIndex, const Markers::Marker &marker ) QModelIndex modelIndex; if (markerIndex == markerCount()) // Allow inserting after the last marker - modelIndex = createIndex(markerIndex, 0, (int)0); + modelIndex = createIndex(markerIndex, 0, (int) 0); else modelIndex = index(markerIndex, 0); if (!modelIndex.isValid()) { @@ -185,13 +186,14 @@ void MarkersModel::doInsert(int markerIndex, const Markers::Marker &marker ) m_keys.insert(modelIndex.row(), key); endInsertRows(); updateRecentColors(marker.color); - if (marker.end > marker.start) emit rangesChanged(); + if (marker.end > marker.start) + emit rangesChanged(); delete markersListProperties; emit modified(); } -void MarkersModel::append( const Markers::Marker &marker ) +void MarkersModel::append(const Markers::Marker &marker) { if (!m_producer) { LOG_ERROR() << "No producer"; @@ -201,7 +203,7 @@ void MarkersModel::append( const Markers::Marker &marker ) MAIN.undoStack()->push(command); } -void MarkersModel::doAppend( const Markers::Marker &marker ) +void MarkersModel::doAppend(const Markers::Marker &marker) { if (!m_producer) { LOG_ERROR() << "No producer"; @@ -225,13 +227,14 @@ void MarkersModel::doAppend( const Markers::Marker &marker ) m_keys.append(key); updateRecentColors(marker.color); endInsertRows(); - if (marker.end > marker.start) emit rangesChanged(); + if (marker.end > marker.start) + emit rangesChanged(); delete markersListProperties; emit modified(); } -void MarkersModel::update(int markerIndex, const Markers::Marker &marker) +void MarkersModel::update(int markerIndex, const Markers::Marker &marker) { Mlt::Properties *markerProperties = getMarkerProperties(markerIndex); if (!markerProperties || !markerProperties->is_valid()) { @@ -242,12 +245,13 @@ void MarkersModel::update(int markerIndex, const Markers::Marker &marker) Markers::Marker oldMarker; propertiesToMarker(markerProperties, oldMarker, m_producer); - Markers::UpdateCommand *command = new Markers::UpdateCommand(*this, marker, oldMarker, markerIndex); + Markers::UpdateCommand *command + = new Markers::UpdateCommand(*this, marker, oldMarker, markerIndex); MAIN.undoStack()->push(command); delete markerProperties; } -void MarkersModel::doUpdate(int markerIndex, const Markers::Marker &marker) +void MarkersModel::doUpdate(int markerIndex, const Markers::Marker &marker) { QModelIndex startIndex = index(markerIndex, 0); QModelIndex endIndex = index(markerIndex, COLUMN_COUNT - 1); @@ -268,11 +272,13 @@ void MarkersModel::doUpdate(int markerIndex, const Markers::Marker &marker) delete markerProperties; updateRecentColors(marker.color); - emit dataChanged(startIndex, endIndex, - QVector() << Qt::DisplayRole << TextRole << StartRole << EndRole << ColorRole); - if ((markerBefore.end == markerBefore.start && marker.end > marker.start) || - (markerBefore.end != markerBefore.start && marker.end == marker.start) || - (markerBefore.text != marker.text)) { + emit dataChanged(startIndex, + endIndex, + QVector() + << Qt::DisplayRole << TextRole << StartRole << EndRole << ColorRole); + if ((markerBefore.end == markerBefore.start && marker.end > marker.start) + || (markerBefore.end != markerBefore.start && marker.end == marker.start) + || (markerBefore.text != marker.text)) { emit rangesChanged(); } emit modified(); @@ -327,10 +333,10 @@ void MarkersModel::doShift(int shiftPosition, int shiftAmount) int minIndex = -1; int maxIndex = -1; QScopedPointer markerList(m_producer->get_props(kShotcutMarkersProperty)); - if (markerList && markerList->is_valid()) { + if (markerList && markerList->is_valid()) { for (const auto i : std::as_const(m_keys)) { - QScopedPointer markerProperties(markerList->get_props(qUtf8Printable( - QString::number(i)))); + QScopedPointer markerProperties( + markerList->get_props(qUtf8Printable(QString::number(i)))); if (markerProperties && markerProperties->is_valid()) { Markers::Marker marker; propertiesToMarker(markerProperties.data(), marker, m_producer); @@ -339,10 +345,11 @@ void MarkersModel::doShift(int shiftPosition, int shiftAmount) marker.end += shiftAmount; markerToProperties(marker, markerProperties.data(), m_producer); int markerIndex = m_keys[i]; - if (minIndex == -1 || markerIndex < minIndex) minIndex = markerIndex; - if (maxIndex == -1 || markerIndex > maxIndex) maxIndex = markerIndex; + if (minIndex == -1 || markerIndex < minIndex) + minIndex = markerIndex; + if (maxIndex == -1 || markerIndex > maxIndex) + maxIndex = markerIndex; } - } } } @@ -350,7 +357,9 @@ void MarkersModel::doShift(int shiftPosition, int shiftAmount) if (minIndex != -1) { QModelIndex startIndex = index(minIndex, COLUMN_START); QModelIndex endIndex = index(maxIndex, COLUMN_END); - emit dataChanged(startIndex, endIndex, QVector() << Qt::DisplayRole << StartRole << EndRole); + emit dataChanged(startIndex, + endIndex, + QVector() << Qt::DisplayRole << StartRole << EndRole); emit modified(); emit rangesChanged(); } @@ -370,8 +379,8 @@ void MarkersModel::move(int markerIndex, int start, int end) newMarker.start = start; newMarker.end = end; - Markers::UpdateCommand *command = new Markers::UpdateCommand(*this, newMarker, oldMarker, - markerIndex); + Markers::UpdateCommand *command + = new Markers::UpdateCommand(*this, newMarker, oldMarker, markerIndex); MAIN.undoStack()->push(command); } @@ -388,8 +397,8 @@ void MarkersModel::setColor(int markerIndex, const QColor &color) Markers::Marker newMarker = oldMarker; newMarker.color = color; - Markers::UpdateCommand *command = new Markers::UpdateCommand(*this, newMarker, oldMarker, - markerIndex); + Markers::UpdateCommand *command + = new Markers::UpdateCommand(*this, newMarker, oldMarker, markerIndex); MAIN.undoStack()->push(command); } @@ -454,12 +463,13 @@ int MarkersModel::uniqueKey() const int MarkersModel::markerIndexForPosition(int position) { QScopedPointer markerList(m_producer->get_props(kShotcutMarkersProperty)); - if (markerList && markerList->is_valid()) { + if (markerList && markerList->is_valid()) { for (const auto i : std::as_const(m_keys)) { - QScopedPointer marker(markerList->get_props(qUtf8Printable(QString::number(i)))); + QScopedPointer marker( + markerList->get_props(qUtf8Printable(QString::number(i)))); if (marker && marker->is_valid()) { - if (position == m_producer->time_to_frames(marker->get("start")) || - position == m_producer->time_to_frames(marker->get("end"))) + if (position == m_producer->time_to_frames(marker->get("start")) + || position == m_producer->time_to_frames(marker->get("end"))) return keyIndex(i); } } @@ -470,12 +480,13 @@ int MarkersModel::markerIndexForPosition(int position) int MarkersModel::markerIndexForRange(int start, int end) { QScopedPointer markerList(m_producer->get_props(kShotcutMarkersProperty)); - if (markerList && markerList->is_valid()) { + if (markerList && markerList->is_valid()) { for (const auto i : std::as_const(m_keys)) { - QScopedPointer marker(markerList->get_props(qUtf8Printable(QString::number(i)))); + QScopedPointer marker( + markerList->get_props(qUtf8Printable(QString::number(i)))); if (marker && marker->is_valid()) { - if (start == m_producer->time_to_frames(marker->get("start")) && - end == m_producer->time_to_frames(marker->get("end"))) + if (start == m_producer->time_to_frames(marker->get("start")) + && end == m_producer->time_to_frames(marker->get("end"))) return keyIndex(i); } } @@ -486,9 +497,10 @@ int MarkersModel::markerIndexForRange(int start, int end) int MarkersModel::rangeMarkerIndexForPosition(int position) { QScopedPointer markerList(m_producer->get_props(kShotcutMarkersProperty)); - if (markerList && markerList->is_valid()) { + if (markerList && markerList->is_valid()) { for (const auto i : std::as_const(m_keys)) { - QScopedPointer marker(markerList->get_props(qUtf8Printable(QString::number(i)))); + QScopedPointer marker( + markerList->get_props(qUtf8Printable(QString::number(i)))); if (marker && marker->is_valid()) { int start = m_producer->time_to_frames(marker->get("start")); int end = m_producer->time_to_frames(marker->get("end")); @@ -508,16 +520,19 @@ int MarkersModel::nextMarkerPosition(int position) return nextPosition; } QScopedPointer markerList(m_producer->get_props(kShotcutMarkersProperty)); - if (markerList && markerList->is_valid()) { + if (markerList && markerList->is_valid()) { for (const auto i : std::as_const(m_keys)) { - QScopedPointer marker(markerList->get_props(qUtf8Printable(QString::number(i)))); + QScopedPointer marker( + markerList->get_props(qUtf8Printable(QString::number(i)))); if (marker && marker->is_valid()) { int markerPosition = m_producer->time_to_frames(marker->get("start")); - if (markerPosition > position && (nextPosition == -1 || markerPosition < nextPosition)) { + if (markerPosition > position + && (nextPosition == -1 || markerPosition < nextPosition)) { nextPosition = markerPosition; } markerPosition = m_producer->time_to_frames(marker->get("end")); - if (markerPosition > position && (nextPosition == -1 || markerPosition < nextPosition)) { + if (markerPosition > position + && (nextPosition == -1 || markerPosition < nextPosition)) { nextPosition = markerPosition; } } @@ -534,16 +549,19 @@ int MarkersModel::prevMarkerPosition(int position) return prevPosition; } QScopedPointer markerList(m_producer->get_props(kShotcutMarkersProperty)); - if (markerList && markerList->is_valid()) { + if (markerList && markerList->is_valid()) { for (const auto i : std::as_const(m_keys)) { - QScopedPointer marker(markerList->get_props(qUtf8Printable(QString::number(i)))); + QScopedPointer marker( + markerList->get_props(qUtf8Printable(QString::number(i)))); if (marker && marker->is_valid()) { int markerPosition = m_producer->time_to_frames(marker->get("start")); - if (markerPosition < position && (prevPosition == -1 || markerPosition > prevPosition)) { + if (markerPosition < position + && (prevPosition == -1 || markerPosition > prevPosition)) { prevPosition = markerPosition; } markerPosition = m_producer->time_to_frames(marker->get("end")); - if (markerPosition < position && (prevPosition == -1 || markerPosition > prevPosition)) { + if (markerPosition < position + && (prevPosition == -1 || markerPosition > prevPosition)) { prevPosition = markerPosition; } } @@ -561,9 +579,10 @@ QMap MarkersModel::ranges() { QMap result; QScopedPointer markerList(m_producer->get_props(kShotcutMarkersProperty)); - if (markerList && markerList->is_valid()) { + if (markerList && markerList->is_valid()) { for (const auto i : std::as_const(m_keys)) { - QScopedPointer marker(markerList->get_props(qUtf8Printable(QString::number(i)))); + QScopedPointer marker( + markerList->get_props(qUtf8Printable(QString::number(i)))); if (marker && marker->is_valid()) { Markers::Marker m; propertiesToMarker(marker.get(), m, m_producer); @@ -587,9 +606,10 @@ QList MarkersModel::getMarkers() const if (!m_producer || !m_producer->is_valid()) return markers; QScopedPointer markerList(m_producer->get_props(kShotcutMarkersProperty)); - if (markerList && markerList->is_valid()) { + if (markerList && markerList->is_valid()) { for (const auto i : std::as_const(m_keys)) { - QScopedPointer marker(markerList->get_props(qUtf8Printable(QString::number(i)))); + QScopedPointer marker( + markerList->get_props(qUtf8Printable(QString::number(i)))); if (marker && marker->is_valid()) { Markers::Marker m; propertiesToMarker(marker.get(), m, m_producer); @@ -627,8 +647,8 @@ Mlt::Properties *MarkersModel::getMarkerProperties(int markerIndex) if (!markersListProperties || !markersListProperties->is_valid()) { LOG_ERROR() << "No Markers"; } else { - markerProperties = markersListProperties->get_props(qUtf8Printable(QString::number( - m_keys[modelIndex.row()]))); + markerProperties = markersListProperties->get_props( + qUtf8Printable(QString::number(m_keys[modelIndex.row()]))); if (!markerProperties || !markerProperties->is_valid()) { LOG_ERROR() << "Marker does not exist" << modelIndex.row(); delete markerProperties; @@ -678,7 +698,7 @@ QVariant MarkersModel::data(const QModelIndex &index, int role) const return result; } if (!index.isValid() || index.column() < 0 || index.column() >= COLUMN_COUNT || index.row() < 0 - || index.row() >= markerCount()) { + || index.row() >= markerCount()) { LOG_ERROR() << "Invalid Index: " << index.row() << index.column() << role; return result; } @@ -688,11 +708,11 @@ QVariant MarkersModel::data(const QModelIndex &index, int role) const delete markersListProperties; return result; } - Mlt::Properties *markerProperties = markersListProperties->get_props(qUtf8Printable(QString::number( - m_keys[index.row()]))); + Mlt::Properties *markerProperties = markersListProperties->get_props( + qUtf8Printable(QString::number(m_keys[index.row()]))); if (!markerProperties || !markerProperties->is_valid()) { - LOG_DEBUG() << "Marker does not exist: " << index.row() << index.column() << role << - m_keys[index.row()]; + LOG_DEBUG() << "Marker does not exist: " << index.row() << index.column() << role + << m_keys[index.row()]; delete markerProperties; delete markersListProperties; return result; @@ -716,7 +736,8 @@ QVariant MarkersModel::data(const QModelIndex &index, int role) const result = QString(m_producer->frames_to_time(marker.end, Settings.timeFormat())); break; case COLUMN_DURATION: - result = QString(m_producer->frames_to_time(marker.end - marker.start + 1, Settings.timeFormat())); + result = QString( + m_producer->frames_to_time(marker.end - marker.start + 1, Settings.timeFormat())); break; default: LOG_ERROR() << "Invalid Column" << index.column() << role; @@ -785,7 +806,7 @@ QModelIndex MarkersModel::index(int row, int column, const QModelIndex &parent) Q_UNUSED(parent) if (column < 0 || column >= COLUMN_COUNT || row < 0 || row >= markerCount()) return QModelIndex(); - return createIndex(row, column, (int)0); + return createIndex(row, column, (int) 0); } QModelIndex MarkersModel::parent(const QModelIndex &index) const @@ -797,9 +818,9 @@ QModelIndex MarkersModel::parent(const QModelIndex &index) const QHash MarkersModel::roleNames() const { QHash roles = QAbstractItemModel::roleNames(); - roles[TextRole] = "text"; - roles[StartRole] = "start"; - roles[EndRole] = "end"; - roles[ColorRole] = "color"; + roles[TextRole] = "text"; + roles[StartRole] = "start"; + roles[EndRole] = "end"; + roles[ColorRole] = "color"; return roles; } diff --git a/src/models/markersmodel.h b/src/models/markersmodel.h index c80bf7e635..582e1fe474 100644 --- a/src/models/markersmodel.h +++ b/src/models/markersmodel.h @@ -19,7 +19,6 @@ #define MARKERSMODEL_H #include - #include #include #include @@ -30,12 +29,12 @@ class Marker { public: QString text; - int start {-1}; - int end {-1}; + int start{-1}; + int end{-1}; QColor color; }; -} +} // namespace Markers class MarkersModel : public QAbstractItemModel { @@ -43,7 +42,6 @@ class MarkersModel : public QAbstractItemModel Q_PROPERTY(QStringList recentColors READ recentColors NOTIFY recentColorsChanged) public: - enum Roles { TextRole = Qt::UserRole + 1, StartRole, @@ -72,7 +70,7 @@ class MarkersModel : public QAbstractItemModel void doRemove(int markerIndex); void doInsert(int markerIndex, const Markers::Marker &marker); void doAppend(const Markers::Marker &marker); - void doUpdate(int markerIndex, const Markers::Marker &marker); + void doUpdate(int markerIndex, const Markers::Marker &marker); void doClear(); void doReplace(QList &markers); void doShift(int shiftPosition, int shiftAmount); diff --git a/src/models/metadatamodel.cpp b/src/models/metadatamodel.cpp index 41169f2435..bf42b09eac 100644 --- a/src/models/metadatamodel.cpp +++ b/src/models/metadatamodel.cpp @@ -16,14 +16,15 @@ */ #include "metadatamodel.h" + +#include "Logger.h" #include "controllers/filtercontroller.h" #include "mainwindow.h" #include "qmltypes/qmlmetadata.h" #include "settings.h" -#include -#include #include +#include #include MetadataModel::MetadataModel(QObject *parent) @@ -92,7 +93,8 @@ QVariant InternalMetadataModel::data(const QModelIndex &index, int role) const bool InternalMetadataModel::setData(const QModelIndex &index, const QVariant &value, int role) { - if (!index.isValid()) return false; + if (!index.isValid()) + return false; switch (role) { case MetadataModel::FavoriteRole: { QmlMetadata *meta = m_list.at(index.row()); @@ -132,8 +134,8 @@ void MetadataModel::add(QmlMetadata *data) void InternalMetadataModel::add(QmlMetadata *data) { int i = 0; - for ( i = 0; i < m_list.size(); i++ ) { - if (m_list[i]->name().toLower() > data->name().toLower() ) { + for (i = 0; i < m_list.size(); i++) { + if (m_list[i]->name().toLower() > data->name().toLower()) { break; } } @@ -192,29 +194,36 @@ bool MetadataModel::filterAcceptsRow(int sourceRow, const QModelIndex &sourcePar if (meta->filterMask & m_filterMask) { return false; } - if (Settings.playerGPU() && meta->needsGPU() && MAIN.filterController()->isOutputTrackSelected()) { + if (Settings.playerGPU() && meta->needsGPU() + && MAIN.filterController()->isOutputTrackSelected()) { return false; } if (m_search.isEmpty()) { switch (m_filter) { case FavoritesFilter: - if (!meta->isFavorite()) return false; + if (!meta->isFavorite()) + return false; break; case VideoFilter: if (meta->isAudio() || meta->needsGPU() || meta->type() == QmlMetadata::Link - || meta->type() == QmlMetadata::FilterSet) return false; + || meta->type() == QmlMetadata::FilterSet) + return false; break; case AudioFilter: - if (!meta->isAudio()) return false; + if (!meta->isAudio()) + return false; break; case LinkFilter: - if (meta->type() != QmlMetadata::Link) return false; + if (meta->type() != QmlMetadata::Link) + return false; break; case FilterSetFilter: - if (meta->type() != QmlMetadata::FilterSet) return false; + if (meta->type() != QmlMetadata::FilterSet) + return false; break; case GPUFilter: - if (!meta->needsGPU()) return false; + if (!meta->needsGPU()) + return false; break; default: break; @@ -226,8 +235,10 @@ bool MetadataModel::filterAcceptsRow(int sourceRow, const QModelIndex &sourcePar return true; } -void MetadataModel::updateFilterMask(bool isClipProducer, bool isChainProducer, - bool isTrackProducer, bool isOutputProducer, +void MetadataModel::updateFilterMask(bool isClipProducer, + bool isChainProducer, + bool isTrackProducer, + bool isOutputProducer, bool isReverseSupported) { beginResetModel(); @@ -267,14 +278,22 @@ void MetadataModel::updateFilterMask(bool isClipProducer, bool isChainProducer, unsigned InternalMetadataModel::computeFilterMask(const QmlMetadata *meta) { unsigned mask = 0; - if (meta->isHidden()) mask |= MetadataModel::HiddenMaskBit; - if (meta->isClipOnly()) mask |= MetadataModel::clipOnlyMaskBit; - if (meta->isTrackOnly()) mask |= MetadataModel::trackOnlyMaskBit; - if (meta->isOutputOnly()) mask |= MetadataModel::outputOnlyMaskBit; - if (!meta->isGpuCompatible()) mask |= MetadataModel::gpuIncompatibleMaskBit; - if (meta->needsGPU()) mask |= MetadataModel::needsGPUMaskBit; - if (meta->type() == QmlMetadata::Link) mask |= MetadataModel::linkMaskBit; - if (meta->seekReverse()) mask |= MetadataModel::reverseMaskBit; + if (meta->isHidden()) + mask |= MetadataModel::HiddenMaskBit; + if (meta->isClipOnly()) + mask |= MetadataModel::clipOnlyMaskBit; + if (meta->isTrackOnly()) + mask |= MetadataModel::trackOnlyMaskBit; + if (meta->isOutputOnly()) + mask |= MetadataModel::outputOnlyMaskBit; + if (!meta->isGpuCompatible()) + mask |= MetadataModel::gpuIncompatibleMaskBit; + if (meta->needsGPU()) + mask |= MetadataModel::needsGPUMaskBit; + if (meta->type() == QmlMetadata::Link) + mask |= MetadataModel::linkMaskBit; + if (meta->seekReverse()) + mask |= MetadataModel::reverseMaskBit; return mask; } @@ -302,8 +321,8 @@ void MetadataModel::saveFilterSet(const QString &name) stream.setEncoding(QStringConverter::Utf8); stream << QGuiApplication::clipboard()->text(); if (file.error() != QFileDevice::NoError) { - LOG_ERROR() << "error while writing filter set file" << file.fileName() << ":" << - file.errorString(); + LOG_ERROR() << "error while writing filter set file" << file.fileName() << ":" + << file.errorString(); return; } if (file.commit() && !exists) { diff --git a/src/models/metadatamodel.h b/src/models/metadatamodel.h index 840d681df3..70ed793e71 100644 --- a/src/models/metadatamodel.h +++ b/src/models/metadatamodel.h @@ -18,8 +18,8 @@ #ifndef METADATAMODEL_H #define METADATAMODEL_H -#include #include +#include class QmlMetadata; @@ -31,7 +31,6 @@ class MetadataModel : public QSortFilterProxyModel Q_PROPERTY(QString search READ search WRITE setSearch NOTIFY searchChanged) public: - enum ModelRoles { NameRole = Qt::UserRole + 1, HiddenRole, @@ -73,17 +72,14 @@ class MetadataModel : public QSortFilterProxyModel QmlMetadata *getFromSource(int index) const; Q_INVOKABLE void saveFilterSet(const QString &name); Q_INVOKABLE void deleteFilterSet(const QString &name); - MetadataFilter filter() const - { - return m_filter; - } + MetadataFilter filter() const { return m_filter; } void setFilter(MetadataFilter); - void updateFilterMask(bool isClipProducer, bool isChainProducer, bool isTrackProducer, - bool isOutputProducer, bool isReverseSupported); - QString search() const - { - return m_search; - } + void updateFilterMask(bool isClipProducer, + bool isChainProducer, + bool isTrackProducer, + bool isOutputProducer, + bool isReverseSupported); + QString search() const { return m_search; } void setSearch(const QString &search); signals: @@ -107,7 +103,8 @@ class MetadataModel : public QSortFilterProxyModel class InternalMetadataModel : public QAbstractListModel { public: - explicit InternalMetadataModel(QObject *parent = 0) : QAbstractListModel(parent) {}; + explicit InternalMetadataModel(QObject *parent = 0) + : QAbstractListModel(parent){}; // Implement QAbstractListModel int rowCount(const QModelIndex &parent = QModelIndex()) const; @@ -119,10 +116,7 @@ class InternalMetadataModel : public QAbstractListModel // Direct access to QmlMetadata void add(QmlMetadata *data); QmlMetadata *get(int index) const; - QList &list() - { - return m_list; - } + QList &list() { return m_list; } void remove(int index); private: diff --git a/src/models/motiontrackermodel.cpp b/src/models/motiontrackermodel.cpp index 2f52f940f0..b1d585f043 100644 --- a/src/models/motiontrackermodel.cpp +++ b/src/models/motiontrackermodel.cpp @@ -16,13 +16,14 @@ */ #include "motiontrackermodel.h" -#include "shotcut_mlt_properties.h" -#include "qmltypes/qmlfilter.h" + +#include "Logger.h" #include "mltcontroller.h" +#include "qmltypes/qmlfilter.h" +#include "shotcut_mlt_properties.h" -#include #include -#include +#include // This is hard-coded for now (minimum viable product). static const int KEYFRAME_INTERVAL_FRAMES = 5; @@ -56,74 +57,23 @@ class FindTrackersParser : public Mlt::Parser } return 0; } - int on_start_producer(Mlt::Producer *) - { - return 0; - } - int on_end_producer(Mlt::Producer *) - { - return 0; - } - int on_start_playlist(Mlt::Playlist *) - { - return 0; - } - int on_end_playlist(Mlt::Playlist *) - { - return 0; - } - int on_start_tractor(Mlt::Tractor *) - { - return 0; - } - int on_end_tractor(Mlt::Tractor *) - { - return 0; - } - int on_start_multitrack(Mlt::Multitrack *) - { - return 0; - } - int on_end_multitrack(Mlt::Multitrack *) - { - return 0; - } - int on_start_track() - { - return 0; - } - int on_end_track() - { - return 0; - } - int on_end_filter(Mlt::Filter *) - { - return 0; - } - int on_start_transition(Mlt::Transition *) - { - return 0; - } - int on_end_transition(Mlt::Transition *) - { - return 0; - } - int on_start_chain(Mlt::Chain *) - { - return 0; - } - int on_end_chain(Mlt::Chain *) - { - return 0; - } - int on_start_link(Mlt::Link *) - { - return 0; - } - int on_end_link(Mlt::Link *) - { - return 0; - } + int on_start_producer(Mlt::Producer *) { return 0; } + int on_end_producer(Mlt::Producer *) { return 0; } + int on_start_playlist(Mlt::Playlist *) { return 0; } + int on_end_playlist(Mlt::Playlist *) { return 0; } + int on_start_tractor(Mlt::Tractor *) { return 0; } + int on_end_tractor(Mlt::Tractor *) { return 0; } + int on_start_multitrack(Mlt::Multitrack *) { return 0; } + int on_end_multitrack(Mlt::Multitrack *) { return 0; } + int on_start_track() { return 0; } + int on_end_track() { return 0; } + int on_end_filter(Mlt::Filter *) { return 0; } + int on_start_transition(Mlt::Transition *) { return 0; } + int on_end_transition(Mlt::Transition *) { return 0; } + int on_start_chain(Mlt::Chain *) { return 0; } + int on_end_chain(Mlt::Chain *) { return 0; } + int on_start_link(Mlt::Link *) { return 0; } + int on_end_link(Mlt::Link *) { return 0; } }; MotionTrackerModel::MotionTrackerModel(QObject *parent) @@ -134,7 +84,8 @@ MotionTrackerModel::MotionTrackerModel(QObject *parent) void MotionTrackerModel::load(Mlt::Producer *producer, bool reset) { - if (!producer) producer = MLT.producer(); + if (!producer) + producer = MLT.producer(); if (reset) { beginResetModel(); m_data.clear(); @@ -152,7 +103,8 @@ void MotionTrackerModel::load(Mlt::Producer *producer, bool reset) } } } - if (reset) endResetModel(); + if (reset) + endResetModel(); } QString MotionTrackerModel::add(const QString &name, const QString &data) @@ -268,7 +220,7 @@ QList MotionTrackerModel::trackingData(const Q QList result; auto s = m_data.value(key, {}).trackingData; auto l = s.split(';'); - bool ok {false}; + bool ok{false}; Mlt::Properties props; for (const auto &i : l) { diff --git a/src/models/motiontrackermodel.h b/src/models/motiontrackermodel.h index 9187679b10..cf4a11f6ec 100644 --- a/src/models/motiontrackermodel.h +++ b/src/models/motiontrackermodel.h @@ -20,10 +20,10 @@ #include #include -#include -#include #include +#include #include +#include class QmlFilter; namespace Mlt { @@ -37,7 +37,8 @@ class MotionTrackerModel : public QAbstractListModel Q_PROPERTY(QString operationProperty READ trackerOperationProperty CONSTANT) public: - struct TrackingItem { + struct TrackingItem + { int frame; QRectF rect; }; @@ -59,10 +60,10 @@ class MotionTrackerModel : public QAbstractListModel int rowCount(const QModelIndex &parent = QModelIndex()) const override; QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; - bool setData(const QModelIndex &index, const QVariant &value, - int role = Qt::EditRole) override; + bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole) override; Qt::ItemFlags flags(const QModelIndex &index) const override; - Q_INVOKABLE static void undo(QmlFilter *filter = nullptr, const QString &propertyName = QString()); + Q_INVOKABLE static void undo(QmlFilter *filter = nullptr, + const QString &propertyName = QString()); static QString trackerNameProperty() { return QString::fromLatin1("shotcut:motionTracker.name"); @@ -76,12 +77,10 @@ public slots: void removeFromService(Mlt::Service *service); private: - enum Roles { - IdentifierRole = Qt::UserRole, - TrackingDataRole = Qt::UserRole + 1 - }; + enum Roles { IdentifierRole = Qt::UserRole, TrackingDataRole = Qt::UserRole + 1 }; - struct Item { + struct Item + { QString name; QString trackingData; int intervalFrames; diff --git a/src/models/multitrackmodel.cpp b/src/models/multitrackmodel.cpp index ef122909fc..33ea407e16 100644 --- a/src/models/multitrackmodel.cpp +++ b/src/models/multitrackmodel.cpp @@ -16,25 +16,25 @@ */ #include "multitrackmodel.h" -#include "mltcontroller.h" -#include "mainwindow.h" -#include "settings.h" -#include "docks/playlistdock.h" -#include "util.h" + +#include "Logger.h" #include "audiolevelstask.h" -#include "shotcut_mlt_properties.h" #include "controllers/filtercontroller.h" -#include "qmltypes/qmlmetadata.h" -#include "proxymanager.h" #include "dialogs/longuitask.h" +#include "docks/playlistdock.h" +#include "mainwindow.h" +#include "mltcontroller.h" +#include "proxymanager.h" +#include "qmltypes/qmlmetadata.h" +#include "settings.h" +#include "shotcut_mlt_properties.h" +#include "util.h" -#include #include -#include -#include #include - -#include +#include +#include +#include static const quintptr NO_PARENT_ID = quintptr(-1); static const char *kShotcutDefaultTransition = "lumaMix"; @@ -68,7 +68,7 @@ int MultitrackModel::rowCount(const QModelIndex &parent) const if (track) { Mlt::Playlist playlist(*track); int n = playlist.count(); -// LOG_DEBUG() << __FUNCTION__ << parent << i << n; + // LOG_DEBUG() << __FUNCTION__ << parent << i << n; return n; } else { return 0; @@ -93,7 +93,7 @@ QVariant MultitrackModel::data(const QModelIndex &index, int role) const QScopedPointer track(m_tractor->track(i)); if (track) { Mlt::Playlist playlist(*track); -// LOG_DEBUG() << __FUNCTION__ << index.row(); + // LOG_DEBUG() << __FUNCTION__ << index.row(); QScopedPointer info(playlist.clip_info(index.row())); if (info) switch (role) { @@ -127,8 +127,8 @@ QVariant MultitrackModel::data(const QModelIndex &index, int role) const case ResourceRole: case Qt::DisplayRole: { QString result = QString::fromUtf8(info->resource); - if (result == "" && info->producer - && info->producer->is_valid() && info->producer->get("mlt_service")) + if (result == "" && info->producer && info->producer->is_valid() + && info->producer->get("mlt_service")) result = QString::fromUtf8(info->producer->get("mlt_service")); return result; } @@ -155,7 +155,8 @@ QVariant MultitrackModel::data(const QModelIndex &index, int role) const if (info->producer && info->producer->is_valid()) { info->producer->lock(); if (info->producer->get_data(kAudioLevelsProperty)) { - result = QVariant::fromValue(*((QVariantList *) info->producer->get_data(kAudioLevelsProperty))); + result = QVariant::fromValue( + *((QVariantList *) info->producer->get_data(kAudioLevelsProperty))); } info->producer->unlock(); } @@ -239,7 +240,8 @@ QVariant MultitrackModel::data(const QModelIndex &index, int role) const case IsFilteredRole: return isFiltered(track.data()); case IsTopVideoRole: - if (m_trackList[index.row()].type == AudioTrackType) return false; + if (m_trackList[index.row()].type == AudioTrackType) + return false; foreach (const Track &t, m_trackList) { if (t.type == VideoTrackType && t.number > m_trackList[index.row()].number) { return false; @@ -247,11 +249,14 @@ QVariant MultitrackModel::data(const QModelIndex &index, int role) const } return true; case IsBottomVideoRole: - return m_trackList[index.row()].number == 0 && m_trackList[index.row()].type == VideoTrackType; + return m_trackList[index.row()].number == 0 + && m_trackList[index.row()].type == VideoTrackType; case IsTopAudioRole: - return m_trackList[index.row()].number == 0 && m_trackList[index.row()].type == AudioTrackType; + return m_trackList[index.row()].number == 0 + && m_trackList[index.row()].type == AudioTrackType; case IsBottomAudioRole: - if (m_trackList[index.row()].type == VideoTrackType) return false; + if (m_trackList[index.row()].type == VideoTrackType) + return false; foreach (const Track &t, m_trackList) { if (t.type == AudioTrackType && t.number > m_trackList[index.row()].number) { return false; @@ -270,7 +275,7 @@ QModelIndex MultitrackModel::index(int row, int column, const QModelIndex &paren { if (column > 0) return QModelIndex(); -// LOG_DEBUG() << __FUNCTION__ << row << column << parent; + // LOG_DEBUG() << __FUNCTION__ << row << column << parent; QModelIndex result; if (parent.isValid()) { int i = m_trackList.at(parent.row()).mlt_index; @@ -293,7 +298,7 @@ QModelIndex MultitrackModel::makeIndex(int trackIndex, int clipIndex) const QModelIndex MultitrackModel::parent(const QModelIndex &index) const { -// LOG_DEBUG() << __FUNCTION__ << index; + // LOG_DEBUG() << __FUNCTION__ << index; if (!index.isValid() || index.internalId() == NO_PARENT_ID) return QModelIndex(); else @@ -450,8 +455,8 @@ bool MultitrackModel::trimClipInValid(int trackIndex, int clipIndex, int delta, return result; } -int MultitrackModel::trimClipIn(int trackIndex, int clipIndex, int delta, bool ripple, - bool rippleAllTracks) +int MultitrackModel::trimClipIn( + int trackIndex, int clipIndex, int delta, bool ripple, bool rippleAllTracks) { int result = clipIndex; QList otherTracksToRipple; @@ -502,10 +507,10 @@ int MultitrackModel::trimClipIn(int trackIndex, int clipIndex, int delta, bool r // clamp to clip start delta = -info->frame_in; if (clipIndex > 0 && playlist.is_blank(clipIndex - 1) - && -delta > playlist.clip_length(clipIndex - 1)) + && -delta > playlist.clip_length(clipIndex - 1)) // clamp to duration of blank space delta = -playlist.clip_length(clipIndex - 1); -// LOG_DEBUG() << "delta" << delta; + // LOG_DEBUG() << "delta" << delta; playlist.resize_clip(clipIndex, info->frame_in + delta, info->frame_out); @@ -588,7 +593,7 @@ bool MultitrackModel::trimClipOutValid(int trackIndex, int clipIndex, int delta, Mlt::Playlist playlist(*track); QScopedPointer info(playlist.clip_info(clipIndex)); if (!info || (info->frame_out - delta) >= info->length - || (info->frame_out - delta) < info->frame_in) + || (info->frame_out - delta) < info->frame_in) result = false; else if (!ripple && delta < 0 && (clipIndex + 1) < playlist.count() && !playlist.is_blank(clipIndex + 1)) @@ -602,7 +607,8 @@ bool MultitrackModel::trimClipOutValid(int trackIndex, int clipIndex, int delta, int MultitrackModel::trackHeight() const { - int result = m_tractor ? m_tractor->get_int(kTrackHeightProperty) : Settings.timelineTrackHeight(); + int result = m_tractor ? m_tractor->get_int(kTrackHeightProperty) + : Settings.timelineTrackHeight(); return qBound(10, result ? result : Settings.timelineTrackHeight(), 150); } @@ -629,8 +635,8 @@ void MultitrackModel::setScaleFactor(double scale) } } -int MultitrackModel::trimClipOut(int trackIndex, int clipIndex, int delta, bool ripple, - bool rippleAllTracks) +int MultitrackModel::trimClipOut( + int trackIndex, int clipIndex, int delta, bool ripple, bool rippleAllTracks) { QList otherTracksToRipple; int result = clipIndex; @@ -669,13 +675,14 @@ int MultitrackModel::trimClipOut(int trackIndex, int clipIndex, int delta, bool // clamp to clip duration delta = info->frame_out - info->length + 1; if ((clipIndex + 1) < playlist.count() && playlist.is_blank(clipIndex + 1) - && -delta > playlist.clip_length(clipIndex + 1)) + && -delta > playlist.clip_length(clipIndex + 1)) delta = -playlist.clip_length(clipIndex + 1); -// LOG_DEBUG() << "delta" << delta; + // LOG_DEBUG() << "delta" << delta; if (!ripple) { // Adjust right of the clip. - if (clipIndex >= 0 && (clipIndex + 1) < playlist.count() && playlist.is_blank(clipIndex + 1)) { + if (clipIndex >= 0 && (clipIndex + 1) < playlist.count() + && playlist.is_blank(clipIndex + 1)) { int out = playlist.clip_length(clipIndex + 1) + delta - 1; if (out < 0) { // LOG_DEBUG() << "remove blank at right"; @@ -691,7 +698,7 @@ int MultitrackModel::trimClipOut(int trackIndex, int clipIndex, int delta, bool roles << DurationRole; emit dataChanged(index, index, roles); } - } else if (delta > 0 && (clipIndex + 1) < playlist.count()) { + } else if (delta > 0 && (clipIndex + 1) < playlist.count()) { // Add blank to right. // LOG_DEBUG() << "add blank on right duration" << (delta - 1); int newIndex = clipIndex + 1; @@ -744,10 +751,10 @@ void MultitrackModel::notifyClipOut(int trackIndex, int clipIndex) m_isMakingTransition = false; } -bool MultitrackModel::moveClip(int fromTrack, int toTrack, int clipIndex, - int position, bool ripple, bool rippleAllTracks) +bool MultitrackModel::moveClip( + int fromTrack, int toTrack, int clipIndex, int position, bool ripple, bool rippleAllTracks) { -// LOG_DEBUG() << __FUNCTION__ << clipIndex << "fromTrack" << fromTrack << "toTrack" << toTrack; + // LOG_DEBUG() << __FUNCTION__ << clipIndex << "fromTrack" << fromTrack << "toTrack" << toTrack; bool result = false; int i = m_trackList.at(fromTrack).mlt_index; QScopedPointer track(m_tractor->track(i)); @@ -790,8 +797,10 @@ bool MultitrackModel::moveClip(int fromTrack, int toTrack, int clipIndex, insertOrAdjustBlankAt(trackList, clipStart, duration); consolidateBlanks(playlist, fromTrack); emit modified(); - } else if (fromTrack == toTrack && (playlist.is_blank_at(position) || targetIndex == clipIndex) && - (playlist.is_blank_at(position + length - 1) || targetIndexEnd == clipIndex)) { + } else if (fromTrack == toTrack + && (playlist.is_blank_at(position) || targetIndex == clipIndex) + && (playlist.is_blank_at(position + length - 1) + || targetIndexEnd == clipIndex)) { // Reposition the clip within its current blank spot. moveClipInBlank(playlist, toTrack, clipIndex, position, ripple, rippleAllTracks); emit modified(); @@ -863,7 +872,7 @@ int MultitrackModel::overwriteClip(int trackIndex, Mlt::Producer &clip, int posi if (track) { Mlt::Playlist playlist(*track); if (position >= playlist.get_playtime() - 1) { -// LOG_DEBUG() << __FUNCTION__ << "appending"; + // LOG_DEBUG() << __FUNCTION__ << "appending"; removeBlankPlaceholder(playlist, trackIndex); int n = playlist.count(); int length = position - playlist.clip_start(n - 1) - playlist.clip_length(n - 1); @@ -887,9 +896,9 @@ int MultitrackModel::overwriteClip(int trackIndex, Mlt::Producer &clip, int posi result = playlist.count() - 1; } else if (position + clip.get_playtime() > playlist.get_playtime() // Handle straddling - new clip larger than another with blanks on both sides. - || playlist.get_clip_index_at(position) == playlist.get_clip_index_at( - position + clip.get_playtime() - 1)) { -// LOG_DEBUG() << __FUNCTION__ << "overwriting blank space" << clip.get_playtime(); + || playlist.get_clip_index_at(position) + == playlist.get_clip_index_at(position + clip.get_playtime() - 1)) { + // LOG_DEBUG() << __FUNCTION__ << "overwriting blank space" << clip.get_playtime(); int targetIndex = playlist.get_clip_index_at(position); if (position > playlist.clip_start(targetIndex)) { @@ -915,7 +924,7 @@ int MultitrackModel::overwriteClip(int trackIndex, Mlt::Producer &clip, int posi // Adjust clip on right. int duration = playlist.clip_length(targetIndex) - clip.get_playtime(); if (duration > 0) { -// LOG_DEBUG() << "adjust item on right" << (targetIndex) << " to" << duration; + // LOG_DEBUG() << "adjust item on right" << (targetIndex) << " to" << duration; playlist.resize_clip(targetIndex, 0, duration - 1); QModelIndex modelIndex = createIndex(targetIndex, 0, trackIndex); // Notify clip on right was adjusted. @@ -924,7 +933,7 @@ int MultitrackModel::overwriteClip(int trackIndex, Mlt::Producer &clip, int posi emit dataChanged(modelIndex, modelIndex, roles); AudioLevelsTask::start(clip.parent(), this, modelIndex); } else { -// LOG_DEBUG() << "remove item on right"; + // LOG_DEBUG() << "remove item on right"; clearMixReferences(trackIndex, targetIndex); beginRemoveRows(index(trackIndex), targetIndex, targetIndex); playlist.remove(targetIndex); @@ -950,8 +959,8 @@ int MultitrackModel::overwriteClip(int trackIndex, Mlt::Producer &clip, int posi return result; } -QString MultitrackModel::overwrite(int trackIndex, Mlt::Producer &clip, int position, bool seek, - bool notify) +QString MultitrackModel::overwrite( + int trackIndex, Mlt::Producer &clip, int position, bool seek, bool notify) { createIfNeeded(); Mlt::Playlist result(MLT.profile()); @@ -962,7 +971,7 @@ QString MultitrackModel::overwrite(int trackIndex, Mlt::Producer &clip, int posi removeBlankPlaceholder(playlist, trackIndex); int targetIndex = playlist.get_clip_index_at(position); if (position >= playlist.get_playtime() - 1) { -// LOG_DEBUG() << __FUNCTION__ << "appending"; + // LOG_DEBUG() << __FUNCTION__ << "appending"; int n = playlist.count(); int length = position - playlist.clip_start(n - 1) - playlist.clip_length(n - 1); @@ -984,8 +993,8 @@ QString MultitrackModel::overwrite(int trackIndex, Mlt::Producer &clip, int posi targetIndex = playlist.count() - 1; } else { int lastIndex = playlist.get_clip_index_at(position + clip.get_playtime()); -// LOG_DEBUG() << __FUNCTION__ << "overwriting with duration" << clip.get_playtime() -// << "from" << targetIndex << "to" << lastIndex; + // LOG_DEBUG() << __FUNCTION__ << "overwriting with duration" << clip.get_playtime() + // << "from" << targetIndex << "to" << lastIndex; // Add affected clips to result playlist. int i = targetIndex; @@ -999,7 +1008,7 @@ QString MultitrackModel::overwrite(int trackIndex, Mlt::Producer &clip, int posi } if (position > playlist.clip_start(targetIndex)) { -// LOG_DEBUG() << "split starting item" << targetIndex; + // LOG_DEBUG() << "split starting item" << targetIndex; splitClip(trackIndex, targetIndex, position); ++targetIndex; } else if (position < 0) { @@ -1016,12 +1025,12 @@ QString MultitrackModel::overwrite(int trackIndex, Mlt::Producer &clip, int posi int length = clip.get_playtime(); while (length > 0 && targetIndex < playlist.count()) { if (playlist.clip_length(targetIndex) > length) { -// LOG_DEBUG() << "split last item" << targetIndex; + // LOG_DEBUG() << "split last item" << targetIndex; splitClip(trackIndex, targetIndex, position + length); } -// LOG_DEBUG() << "length" << length << "item length" << playlist.clip_length(targetIndex); + // LOG_DEBUG() << "length" << length << "item length" << playlist.clip_length(targetIndex); length -= playlist.clip_length(targetIndex); -// LOG_DEBUG() << "delete item" << targetIndex; + // LOG_DEBUG() << "delete item" << targetIndex; clearMixReferences(trackIndex, targetIndex); beginRemoveRows(index(trackIndex), targetIndex, targetIndex); playlist.remove(targetIndex); @@ -1047,8 +1056,8 @@ QString MultitrackModel::overwrite(int trackIndex, Mlt::Producer &clip, int posi return MLT.XML(&result); } -int MultitrackModel::insertClip(int trackIndex, Mlt::Producer &clip, int position, - bool rippleAllTracks, bool seek, bool notify) +int MultitrackModel::insertClip( + int trackIndex, Mlt::Producer &clip, int position, bool rippleAllTracks, bool seek, bool notify) { createIfNeeded(); int result = -1; @@ -1058,7 +1067,7 @@ int MultitrackModel::insertClip(int trackIndex, Mlt::Producer &clip, int positio if (track) { Mlt::Playlist playlist(*track); if (position >= playlist.get_playtime() - 1) { -// LOG_DEBUG() << __FUNCTION__ << "appending"; + // LOG_DEBUG() << __FUNCTION__ << "appending"; removeBlankPlaceholder(playlist, trackIndex); int n = playlist.count(); int length = position - playlist.clip_start(n - 1) - playlist.clip_length(n - 1); @@ -1080,7 +1089,7 @@ int MultitrackModel::insertClip(int trackIndex, Mlt::Producer &clip, int positio endInsertRows(); result = playlist.count() - 1; } else { -// LOG_DEBUG() << __FUNCTION__ << "inserting" << position << MLT.XML(&clip); + // LOG_DEBUG() << __FUNCTION__ << "inserting" << position << MLT.XML(&clip); int targetIndex = playlist.get_clip_index_at(position); if (position > playlist.clip_start(targetIndex)) { @@ -1293,7 +1302,8 @@ void MultitrackModel::splitClip(int trackIndex, int clipIndex, int position) endInsertRows(); } else { // Make copy of clip. - Mlt::Producer producer(MLT.profile(), "xml-string", + Mlt::Producer producer(MLT.profile(), + "xml-string", MLT.XML(info->producer).toUtf8().constData()); // Connect a transition on the left to the new producer. @@ -1354,12 +1364,14 @@ void MultitrackModel::splitClip(int trackIndex, int clipIndex, int position) void MultitrackModel::joinClips(int trackIndex, int clipIndex) { - if (clipIndex < 0) return; + if (clipIndex < 0) + return; int i = m_trackList.at(trackIndex).mlt_index; QScopedPointer track(m_tractor->track(i)); if (track) { Mlt::Playlist playlist(*track); - if (clipIndex >= playlist.count() - 1) return; + if (clipIndex >= playlist.count() - 1) + return; QScopedPointer info(playlist.clip_info(clipIndex)); int in = info->frame_in; int out = info->frame_out; @@ -1406,7 +1418,7 @@ static void moveBeforeFirstAudioFilter(Mlt::Producer *producer) for (; index < n; index++) { QScopedPointer filter(producer->filter(index)); if (filter && filter->is_valid() && !filter->get_int("_loader") - && !filter->get_int(kShotcutHiddenProperty)) { + && !filter->get_int(kShotcutHiddenProperty)) { QmlMetadata *meta = MAIN.filterController()->metadataForService(filter.data()); if (meta && meta->isAudio()) { break; @@ -1429,9 +1441,9 @@ void MultitrackModel::fadeIn(int trackIndex, int clipIndex, int duration) duration = qBound(0, duration, info->frame_count); if (m_trackList[trackIndex].type == VideoTrackType - // If video track index is not None. - && (!info->producer->get("video_index") || info->producer->get_int("video_index") != -1)) { - + // If video track index is not None. + && (!info->producer->get("video_index") + || info->producer->get_int("video_index") != -1)) { // Get video filter. if (Settings.playerGPU()) filter.reset(getFilter("fadeInMovit", info->producer)); @@ -1467,7 +1479,7 @@ void MultitrackModel::fadeIn(int trackIndex, int clipIndex, int duration) if (Settings.playerGPU()) { // Special handling for animation keyframes on movit.opacity. filter->clear("opacity"); -#if LIBMLT_VERSION_INT >= ((7<<16)+(21<<8)) +#if LIBMLT_VERSION_INT >= ((7 << 16) + (21 << 8)) filter->anim_set("opacity", 0, 0, 0, mlt_keyframe_smooth_natural); #else filter->anim_set("opacity", 0, 0, 0, mlt_keyframe_smooth); @@ -1492,12 +1504,13 @@ void MultitrackModel::fadeIn(int trackIndex, int clipIndex, int duration) } // If audio track index is not None. - if (!info->producer->get("audio_index") || info->producer->get_int("audio_index") != -1) { + if (!info->producer->get("audio_index") + || info->producer->get_int("audio_index") != -1) { // Get audio filter. filter.reset(getFilter("fadeInVolume", info->producer)); if (duration > 0) { - mlt_keyframe_type type = (mlt_keyframe_type)Settings.audioInCurve(); + mlt_keyframe_type type = (mlt_keyframe_type) Settings.audioInCurve(); // Add audio filter if needed. if (!filter) { Mlt::Filter f(MLT.profile(), "volume"); @@ -1554,9 +1567,9 @@ void MultitrackModel::fadeOut(int trackIndex, int clipIndex, int duration) bool isChanged = false; if (m_trackList[trackIndex].type == VideoTrackType - // If video track index is not None. - && (!info->producer->get("video_index") || info->producer->get_int("video_index") != -1)) { - + // If video track index is not None. + && (!info->producer->get("video_index") + || info->producer->get_int("video_index") != -1)) { // Get video filter. if (Settings.playerGPU()) filter.reset(getFilter("fadeOutMovit", info->producer)); @@ -1592,10 +1605,18 @@ void MultitrackModel::fadeOut(int trackIndex, int clipIndex, int duration) if (Settings.playerGPU()) { // Special handling for animation keyframes on movit.opacity. filter->clear("opacity"); -#if LIBMLT_VERSION_INT >= ((7<<16)+(21<<8)) - filter->anim_set("opacity", 1, info->frame_count - duration, 0, mlt_keyframe_smooth_natural); +#if LIBMLT_VERSION_INT >= ((7 << 16) + (21 << 8)) + filter->anim_set("opacity", + 1, + info->frame_count - duration, + 0, + mlt_keyframe_smooth_natural); #else - filter->anim_set("opacity", 1, info->frame_count - duration, 0, mlt_keyframe_smooth); + filter->anim_set("opacity", + 1, + info->frame_count - duration, + 0, + mlt_keyframe_smooth); #endif filter->anim_set("opacity", 0, info->frame_count - 1); } else { @@ -1617,12 +1638,13 @@ void MultitrackModel::fadeOut(int trackIndex, int clipIndex, int duration) } // If audio track index is not None. - if (!info->producer->get("audio_index") || info->producer->get_int("audio_index") != -1) { + if (!info->producer->get("audio_index") + || info->producer->get_int("audio_index") != -1) { // Get audio filter. filter.reset(getFilter("fadeOutVolume", info->producer)); if (duration > 0) { - mlt_keyframe_type type = (mlt_keyframe_type)Settings.audioOutCurve(); + mlt_keyframe_type type = (mlt_keyframe_type) Settings.audioOutCurve(); // Add audio filter if needed. if (!filter) { Mlt::Filter f(MLT.profile(), "volume"); @@ -1666,8 +1688,8 @@ void MultitrackModel::fadeOut(int trackIndex, int clipIndex, int duration) } } -bool MultitrackModel::addTransitionValid(int fromTrack, int toTrack, int clipIndex, int position, - bool ripple) +bool MultitrackModel::addTransitionValid( + int fromTrack, int toTrack, int clipIndex, int position, bool ripple) { bool result = false; int i = m_trackList.at(toTrack).mlt_index; @@ -1678,8 +1700,8 @@ bool MultitrackModel::addTransitionValid(int fromTrack, int toTrack, int clipInd int targetIndex = playlist.get_clip_index_at(position); int previousIndex = clipIndex - 1 - (playlist.is_blank(clipIndex - 1) ? 1 : 0); int nextIndex = clipIndex + 1 + (playlist.is_blank(clipIndex + 1) ? 1 : 0); - int endOfPreviousClip = playlist.clip_start(previousIndex) + playlist.clip_length( - previousIndex) - 1; + int endOfPreviousClip = playlist.clip_start(previousIndex) + + playlist.clip_length(previousIndex) - 1; int endOfCurrentClip = position + playlist.clip_length(clipIndex) - 1; int startOfNextClip = playlist.clip_start(nextIndex); auto isBlankAtPosition = playlist.is_blank_at(position); @@ -1688,11 +1710,10 @@ bool MultitrackModel::addTransitionValid(int fromTrack, int toTrack, int clipInd auto isTransitionAtNextIndex = isTransition(playlist, nextIndex); if ((targetIndex < clipIndex && (endOfCurrentClip > endOfPreviousClip) - && (position > playlist.clip_start(previousIndex)) && !isBlankAtPosition - && !isTransitionAtPreviousIndex) - || - (!ripple && (targetIndex >= clipIndex) && (position < startOfNextClip) - && !isBlankAtEndOfCurrentClip && !isTransitionAtNextIndex)) { + && (position > playlist.clip_start(previousIndex)) && !isBlankAtPosition + && !isTransitionAtPreviousIndex) + || (!ripple && (targetIndex >= clipIndex) && (position < startOfNextClip) + && !isBlankAtEndOfCurrentClip && !isTransitionAtNextIndex)) { result = true; } } @@ -1700,8 +1721,8 @@ bool MultitrackModel::addTransitionValid(int fromTrack, int toTrack, int clipInd return result; } -int MultitrackModel::addTransition(int trackIndex, int clipIndex, int position, bool ripple, - bool rippleAllTracks) +int MultitrackModel::addTransition( + int trackIndex, int clipIndex, int position, bool ripple, bool rippleAllTracks) { int i = m_trackList.at(trackIndex).mlt_index; QScopedPointer track(m_tractor->track(i)); @@ -1710,13 +1731,13 @@ int MultitrackModel::addTransition(int trackIndex, int clipIndex, int position, int targetIndex = playlist.get_clip_index_at(position); int previousIndex = clipIndex - 1 - (playlist.is_blank(clipIndex - 1) ? 1 : 0); int nextIndex = clipIndex + 1 + (playlist.is_blank(clipIndex + 1) ? 1 : 0); - int endOfPreviousClip = playlist.clip_start(previousIndex) + playlist.clip_length( - previousIndex) - 1; + int endOfPreviousClip = playlist.clip_start(previousIndex) + + playlist.clip_length(previousIndex) - 1; int endOfCurrentClip = position + playlist.clip_length(clipIndex) - 1; int startOfNextClip = playlist.clip_start(nextIndex); if ((targetIndex < clipIndex && endOfCurrentClip > endOfPreviousClip) || // dragged left - (targetIndex >= clipIndex && position < startOfNextClip)) { // dragged right + (targetIndex >= clipIndex && position < startOfNextClip)) { // dragged right int duration = qAbs(position - playlist.clip_start(clipIndex)); // Remove a blank duration from the transition duration. @@ -1726,7 +1747,13 @@ int MultitrackModel::addTransition(int trackIndex, int clipIndex, int position, duration -= playlist.clip_length(clipIndex + 1); // Adjust/insert blanks - moveClipInBlank(playlist, trackIndex, clipIndex, position, ripple, rippleAllTracks, duration); + moveClipInBlank(playlist, + trackIndex, + clipIndex, + position, + ripple, + rippleAllTracks, + duration); targetIndex = playlist.get_clip_index_at(position); // Create mix @@ -1739,7 +1766,8 @@ int MultitrackModel::addTransition(int trackIndex, int clipIndex, int position, endInsertRows(); // Add transitions - Mlt::Transition dissolve(MLT.profile(), Settings.playerGPU() ? "movit.luma_mix" : "luma"); + Mlt::Transition dissolve(MLT.profile(), + Settings.playerGPU() ? "movit.luma_mix" : "luma"); Mlt::Transition crossFade(MLT.profile(), "mix:-1"); if (!Settings.playerGPU()) { dissolve.set("alpha_over", 1); @@ -1851,7 +1879,8 @@ void MultitrackModel::removeTransitionByTrimOut(int trackIndex, int clipIndex, i bool MultitrackModel::trimTransitionInValid(int trackIndex, int clipIndex, int delta) { - if (m_isMakingTransition) return false; + if (m_isMakingTransition) + return false; bool result = false; int i = m_trackList.at(trackIndex).mlt_index; QScopedPointer track(m_tractor->track(i)); @@ -1860,7 +1889,8 @@ bool MultitrackModel::trimTransitionInValid(int trackIndex, int clipIndex, int d if (clipIndex + 2 < playlist.count()) { Mlt::ClipInfo info; // Check if there is already a transition and its new length valid. - if (isTransition(playlist, clipIndex + 1) && playlist.clip_length(clipIndex + 1) + delta > 0) { + if (isTransition(playlist, clipIndex + 1) + && playlist.clip_length(clipIndex + 1) + delta > 0) { // Check clip A out point. playlist.clip_info(clipIndex, &info); info.frame_out -= delta; @@ -1879,7 +1909,7 @@ bool MultitrackModel::trimTransitionInValid(int trackIndex, int clipIndex, int d void MultitrackModel::trimTransitionIn(int trackIndex, int clipIndex, int delta, bool slip) { -// LOG_DEBUG() << "clipIndex" << clipIndex << "delta" << delta; + // LOG_DEBUG() << "clipIndex" << clipIndex << "delta" << delta; int i = m_trackList.at(trackIndex).mlt_index; QScopedPointer track(m_tractor->track(i)); if (track) { @@ -1929,14 +1959,16 @@ void MultitrackModel::trimTransitionIn(int trackIndex, int clipIndex, int delta, roles << OutPointRole; roles << DurationRole; emit dataChanged(createIndex(clipIndex, 0, trackIndex), - createIndex(clipIndex + 1, 0, trackIndex), roles); + createIndex(clipIndex + 1, 0, trackIndex), + roles); emit modified(); } } bool MultitrackModel::trimTransitionOutValid(int trackIndex, int clipIndex, int delta) { - if (m_isMakingTransition) return false; + if (m_isMakingTransition) + return false; bool result = false; int i = m_trackList.at(trackIndex).mlt_index; QScopedPointer track(m_tractor->track(i)); @@ -1964,7 +1996,7 @@ bool MultitrackModel::trimTransitionOutValid(int trackIndex, int clipIndex, int void MultitrackModel::trimTransitionOut(int trackIndex, int clipIndex, int delta, bool slip) { -// LOG_DEBUG() << "clipIndex" << clipIndex << "delta" << delta; + // LOG_DEBUG() << "clipIndex" << clipIndex << "delta" << delta; int i = m_trackList.at(trackIndex).mlt_index; QScopedPointer track(m_tractor->track(i)); if (track) { @@ -2013,13 +2045,15 @@ void MultitrackModel::trimTransitionOut(int trackIndex, int clipIndex, int delta roles << OutPointRole; roles << DurationRole; emit dataChanged(createIndex(clipIndex - 1, 0, trackIndex), - createIndex(clipIndex - 1, 0, trackIndex), roles); + createIndex(clipIndex - 1, 0, trackIndex), + roles); roles.clear(); roles << InPointRole; roles << OutPointRole; roles << DurationRole; emit dataChanged(createIndex(clipIndex, 0, trackIndex), - createIndex(clipIndex, 0, trackIndex), roles); + createIndex(clipIndex, 0, trackIndex), + roles); emit modified(); } } @@ -2036,7 +2070,7 @@ bool MultitrackModel::addTransitionByTrimInValid(int trackIndex, int clipIndex, // Check if preceding clip is not blank, not already a transition, // and there is enough frames before in point of current clip. if (!m_isMakingTransition && delta < 0 && !playlist.is_blank(clipIndex - 1) - && !isTransition(playlist, clipIndex - 1)) { + && !isTransition(playlist, clipIndex - 1)) { Mlt::ClipInfo info; playlist.clip_info(clipIndex, &info); if (info.frame_in >= -delta) @@ -2082,7 +2116,8 @@ int MultitrackModel::addTransitionByTrimIn(int trackIndex, int clipIndex, int de endInsertRows(); // Add transitions. - Mlt::Transition dissolve(MLT.profile(), Settings.playerGPU() ? "movit.luma_mix" : "luma"); + Mlt::Transition dissolve(MLT.profile(), + Settings.playerGPU() ? "movit.luma_mix" : "luma"); Mlt::Transition crossFade(MLT.profile(), "mix:-1"); if (!Settings.playerGPU()) { dissolve.set("alpha_over", 1); @@ -2121,16 +2156,16 @@ bool MultitrackModel::addTransitionByTrimOutValid(int trackIndex, int clipIndex, // Check if following clip is not blank, not already a transition, // and there is enough frames after out point of current clip. if (!m_isMakingTransition && delta < 0 && !playlist.is_blank(clipIndex + 1) - && !isTransition(playlist, clipIndex + 1)) { + && !isTransition(playlist, clipIndex + 1)) { Mlt::ClipInfo info; playlist.clip_info(clipIndex, &info); -// LOG_DEBUG() << "(info.length" << info.length << " - info.frame_out" << info.frame_out << ") =" << (info.length - info.frame_out) << " >= -delta" << -delta; + // LOG_DEBUG() << "(info.length" << info.length << " - info.frame_out" << info.frame_out << ") =" << (info.length - info.frame_out) << " >= -delta" << -delta; if ((info.length - info.frame_out) >= -delta) result = true; } else if (m_isMakingTransition && isTransition(playlist, clipIndex + 1)) { // Invalid if transition length will be 0 or less. auto newTransitionDuration = playlist.clip_length(clipIndex + 1) - delta; -// LOG_DEBUG() << "playlist.clip_length(clipIndex + 1)" << playlist.clip_length(clipIndex + 1) << "- delta" << delta << "=" << (playlist.clip_length(clipIndex + 1) - delta); + // LOG_DEBUG() << "playlist.clip_length(clipIndex + 1)" << playlist.clip_length(clipIndex + 1) << "- delta" << delta << "=" << (playlist.clip_length(clipIndex + 1) - delta); result = newTransitionDuration > 0; if (result && clipIndex + 2 < playlist.count()) { QScopedPointer info(playlist.clip_info(clipIndex)); @@ -2169,7 +2204,8 @@ void MultitrackModel::addTransitionByTrimOut(int trackIndex, int clipIndex, int endInsertRows(); // Add transitions. - Mlt::Transition dissolve(MLT.profile(), Settings.playerGPU() ? "movit.luma_mix" : "luma"); + Mlt::Transition dissolve(MLT.profile(), + Settings.playerGPU() ? "movit.luma_mix" : "luma"); Mlt::Transition crossFade(MLT.profile(), "mix:-1"); if (!Settings.playerGPU()) { dissolve.set("alpha_over", 1); @@ -2189,8 +2225,8 @@ void MultitrackModel::addTransitionByTrimOut(int trackIndex, int clipIndex, int } else if (m_isMakingTransition) { // Adjust a transition addition already in progress. // m_isMakingTransition will be set false when mouse button released via notifyClipIn(). - delta = playlist.clip_start(clipIndex + 1) - (playlist.clip_start(clipIndex) + playlist.clip_length( - clipIndex) + delta); + delta = playlist.clip_start(clipIndex + 1) + - (playlist.clip_start(clipIndex) + playlist.clip_length(clipIndex) + delta); trimTransitionOut(trackIndex, clipIndex + 2, delta); } } @@ -2206,8 +2242,8 @@ bool MultitrackModel::removeTransitionByTrimInValid(int trackIndex, int clipInde if (clipIndex > 1) { // Check if there is a transition and its new length is 0 or less. if (isTransition(playlist, clipIndex - 1) - && playlist.clip_length(clipIndex - 1) - qAbs(delta) <= 0 - && ((delta < 0 && !m_isMakingTransition) || (delta > 0 && m_isMakingTransition))) { + && playlist.clip_length(clipIndex - 1) - qAbs(delta) <= 0 + && ((delta < 0 && !m_isMakingTransition) || (delta > 0 && m_isMakingTransition))) { result = true; m_isMakingTransition = false; } @@ -2225,10 +2261,10 @@ bool MultitrackModel::removeTransitionByTrimOutValid(int trackIndex, int clipInd Mlt::Playlist playlist(*track); if (clipIndex + 2 < playlist.count()) { // Check if there is a transition and its new length is 0 or less. -// LOG_DEBUG() << "transition length" << playlist.clip_length(clipIndex + 1) << "delta" << delta << playlist.clip_length(clipIndex + 1) - qAbs(delta); + // LOG_DEBUG() << "transition length" << playlist.clip_length(clipIndex + 1) << "delta" << delta << playlist.clip_length(clipIndex + 1) - qAbs(delta); if (isTransition(playlist, clipIndex + 1) - && playlist.clip_length(clipIndex + 1) - qAbs(delta) <= 0 - && ((delta < 0 && !m_isMakingTransition) || (delta > 0 && m_isMakingTransition))) { + && playlist.clip_length(clipIndex + 1) - qAbs(delta) <= 0 + && ((delta < 0 && !m_isMakingTransition) || (delta > 0 && m_isMakingTransition))) { result = true; m_isMakingTransition = false; } @@ -2257,7 +2293,8 @@ void MultitrackModel::filterAddedOrRemoved(Mlt::Producer *producer) roles << FadeOutRole; emit dataChanged(modelIndex, modelIndex, roles); } - } else for (int i = 0; i < m_trackList.size(); i++) { + } else + for (int i = 0; i < m_trackList.size(); i++) { // Check if it was on one of the tracks. QScopedPointer track(m_tractor->track(m_trackList[i].mlt_index)); if (service == track.data()->get_service()) { @@ -2281,13 +2318,11 @@ void MultitrackModel::onFilterChanged(Mlt::Service *filter) QModelIndex modelIndex = createIndex(parts[0].toInt(), 0, parts[1].toInt()); QVector roles; const char *name = filter->get(kShotcutFilterProperty); - if (!qstrcmp("fadeInMovit", name) || - !qstrcmp("fadeInBrightness", name) || - !qstrcmp("fadeInVolume", name)) + if (!qstrcmp("fadeInMovit", name) || !qstrcmp("fadeInBrightness", name) + || !qstrcmp("fadeInVolume", name)) roles << FadeInRole; - if (!qstrcmp("fadeOutMovit", name) || - !qstrcmp("fadeOutBrightness", name) || - !qstrcmp("fadeOutVolume", name)) + if (!qstrcmp("fadeOutMovit", name) || !qstrcmp("fadeOutBrightness", name) + || !qstrcmp("fadeOutVolume", name)) roles << FadeOutRole; if (roles.length()) emit dataChanged(modelIndex, modelIndex, roles); @@ -2296,8 +2331,12 @@ void MultitrackModel::onFilterChanged(Mlt::Service *filter) } } -void MultitrackModel::moveClipToEnd(Mlt::Playlist &playlist, int trackIndex, int clipIndex, - int position, bool ripple, bool rippleAllTracks) +void MultitrackModel::moveClipToEnd(Mlt::Playlist &playlist, + int trackIndex, + int clipIndex, + int position, + bool ripple, + bool rippleAllTracks) { int n = playlist.count(); int length = position - playlist.clip_start(n - 1) - playlist.clip_length(n - 1); @@ -2308,7 +2347,7 @@ void MultitrackModel::moveClipToEnd(Mlt::Playlist &playlist, int trackIndex, int if (clipIndex > 0 && playlist.is_blank(clipIndex - 1)) { // If there was a blank on the left adjust it. int duration = playlist.clip_length(clipIndex - 1) + playlist.clip_length(clipIndex); -// LOG_DEBUG() << "adjust blank on left to" << duration; + // LOG_DEBUG() << "adjust blank on left to" << duration; playlist.resize_clip(clipIndex - 1, 0, duration - 1); QModelIndex index = createIndex(clipIndex - 1, 0, trackIndex); @@ -2318,7 +2357,7 @@ void MultitrackModel::moveClipToEnd(Mlt::Playlist &playlist, int trackIndex, int } else if ((clipIndex + 1) < n && playlist.is_blank(clipIndex + 1)) { // If there was a blank on the right adjust it. int duration = playlist.clip_length(clipIndex + 1) + playlist.clip_length(clipIndex); -// LOG_DEBUG() << "adjust blank on right to" << duration; + // LOG_DEBUG() << "adjust blank on right to" << duration; playlist.resize_clip(clipIndex + 1, 0, duration - 1); QModelIndex index = createIndex(clipIndex + 1, 0, trackIndex); @@ -2366,8 +2405,13 @@ void MultitrackModel::moveClipToEnd(Mlt::Playlist &playlist, int trackIndex, int } } -void MultitrackModel::moveClipInBlank(Mlt::Playlist &playlist, int trackIndex, int clipIndex, - int position, bool ripple, bool rippleAllTracks, int duration) +void MultitrackModel::moveClipInBlank(Mlt::Playlist &playlist, + int trackIndex, + int clipIndex, + int position, + bool ripple, + bool rippleAllTracks, + int duration) { int clipPlaytime = duration ? duration : playlist.clip_length(clipIndex); int clipStart = playlist.clip_start(clipIndex); @@ -2377,7 +2421,7 @@ void MultitrackModel::moveClipInBlank(Mlt::Playlist &playlist, int trackIndex, i // Adjust blank on left. int duration = playlist.clip_length(clipIndex - 1) + delta; if (duration > 0) { -// LOG_DEBUG() << "adjust blank on left" << (clipIndex - 1) << "to" << duration; + // LOG_DEBUG() << "adjust blank on left" << (clipIndex - 1) << "to" << duration; playlist.resize_clip(clipIndex - 1, 0, duration - 1); QModelIndex index = createIndex(clipIndex - 1, 0, trackIndex); @@ -2385,7 +2429,7 @@ void MultitrackModel::moveClipInBlank(Mlt::Playlist &playlist, int trackIndex, i roles << DurationRole; emit dataChanged(index, index, roles); } else { -// LOG_DEBUG() << "remove blank on left"; + // LOG_DEBUG() << "remove blank on left"; int i = clipIndex - 1; beginRemoveRows(index(trackIndex), i, i); playlist.remove(i); @@ -2394,7 +2438,7 @@ void MultitrackModel::moveClipInBlank(Mlt::Playlist &playlist, int trackIndex, i --clipIndex; } } else if (delta > 0) { -// LOG_DEBUG() << "add blank on left with duration" << delta; + // LOG_DEBUG() << "add blank on left with duration" << delta; // Add blank to left. int i = qMax(clipIndex, 0); beginInsertRows(index(trackIndex), i, i); @@ -2407,7 +2451,7 @@ void MultitrackModel::moveClipInBlank(Mlt::Playlist &playlist, int trackIndex, i // Adjust blank to right. int duration = playlist.clip_length(clipIndex + 1) - delta; if (duration > 0) { -// LOG_DEBUG() << "adjust blank on right" << (clipIndex + 1) << "to" << duration; + // LOG_DEBUG() << "adjust blank on right" << (clipIndex + 1) << "to" << duration; playlist.resize_clip(clipIndex + 1, 0, duration - 1); QModelIndex index = createIndex(clipIndex + 1, 0, trackIndex); @@ -2415,7 +2459,7 @@ void MultitrackModel::moveClipInBlank(Mlt::Playlist &playlist, int trackIndex, i roles << DurationRole; emit dataChanged(index, index, roles); } else { -// LOG_DEBUG() << "remove blank on right"; + // LOG_DEBUG() << "remove blank on right"; int i = clipIndex + 1; beginRemoveRows(index(trackIndex), i, i); playlist.remove(i); @@ -2424,7 +2468,7 @@ void MultitrackModel::moveClipInBlank(Mlt::Playlist &playlist, int trackIndex, i } } else if (!ripple && delta < 0 && (clipIndex + 1) < playlist.count()) { // Add blank to right. -// LOG_DEBUG() << "add blank on right with duration" << -delta; + // LOG_DEBUG() << "add blank on right with duration" << -delta; beginInsertRows(index(trackIndex), clipIndex + 1, clipIndex + 1); playlist.insert_blank(clipIndex + 1, (-delta - 1)); endInsertRows(); @@ -2484,7 +2528,8 @@ void MultitrackModel::consolidateBlanks(Mlt::Playlist &playlist, int trackIndex) void MultitrackModel::consolidateBlanksAllTracks() { - if (!m_tractor) return; + if (!m_tractor) + return; int i = 0; foreach (Track t, m_trackList) { std::unique_ptr track(m_tractor->track(t.mlt_index)); @@ -2535,7 +2580,8 @@ void MultitrackModel::addBackgroundTrack() void MultitrackModel::adjustBackgroundDuration() { - if (!m_tractor) return; + if (!m_tractor) + return; int duration = getDuration(); std::unique_ptr track(m_tractor->track(0)); if (track && track->is_valid()) { @@ -2543,7 +2589,8 @@ void MultitrackModel::adjustBackgroundDuration() std::unique_ptr clip(playlist.get_clip(0)); if (clip && clip->is_valid()) { if (duration != clip->parent().get_length()) { - clip->parent().set("length", clip->parent().frames_to_time(duration, mlt_time_clock)); + clip->parent().set("length", + clip->parent().frames_to_time(duration, mlt_time_clock)); clip->parent().set_in_and_out(0, duration - 1); clip->set("length", clip->parent().frames_to_time(duration, mlt_time_clock)); clip->set_in_and_out(0, duration - 1); @@ -2563,7 +2610,7 @@ void MultitrackModel::adjustServiceFilterDurations(Mlt::Service &service, int du for (int i = 0; i < n; i++) { QScopedPointer filter(service.filter(i)); if (filter && filter->is_valid() && !filter->get_int("_loader") - && !filter->get_int(kShotcutHiddenProperty)) { + && !filter->get_int(kShotcutHiddenProperty)) { int in = filter->get_in(); int out = filter->get_out(); // Only change out if it is pinned (same as old track duration) @@ -2583,9 +2630,12 @@ bool MultitrackModel::warnIfInvalid(Mlt::Service &service) const char *plugin = Settings.playerGPU() ? "Movit overlay" : "frei0r cairoblend"; const char *plugins = Settings.playerGPU() ? "Movit" : "frei0r"; LongUiTask::cancel(); - QMessageBox::critical(&MAIN, qApp->applicationName(), + QMessageBox::critical(&MAIN, + qApp->applicationName(), tr("Error: Shotcut could not find the %1 plugin on your system.\n\n" - "Please install the %2 plugins.").arg(plugin).arg(plugins)); + "Please install the %2 plugins.") + .arg(plugin) + .arg(plugins)); return true; } return false; @@ -2678,7 +2728,8 @@ bool MultitrackModel::checkForEmptyTracks(int trackIndex) void MultitrackModel::adjustTrackFilters() { - if (!m_tractor) return; + if (!m_tractor) + return; int duration = getDuration(); // Adjust filters on the tractor. @@ -2692,7 +2743,8 @@ void MultitrackModel::adjustTrackFilters() } } -std::unique_ptr MultitrackModel::findClipByUuid(const QUuid &uuid, int &trackIndex, +std::unique_ptr MultitrackModel::findClipByUuid(const QUuid &uuid, + int &trackIndex, int &clipIndex) { if (uuid.isNull()) { @@ -2889,15 +2941,15 @@ void MultitrackModel::removeTrack(int trackIndex) if (transition && transition->is_valid()) field->disconnect_service(*transition); -// foreach (Track t, m_trackList) LOG_DEBUG() << (t.type == VideoTrackType?"Video":"Audio") << "track number" << t.number << "mlt_index" << t.mlt_index; -// LOG_DEBUG() << trackIndex << "mlt_index" << track.mlt_index; + // foreach (Track t, m_trackList) LOG_DEBUG() << (t.type == VideoTrackType?"Video":"Audio") << "track number" << t.number << "mlt_index" << t.mlt_index; + // LOG_DEBUG() << trackIndex << "mlt_index" << track.mlt_index; // Remove track. beginRemoveRows(QModelIndex(), trackIndex, trackIndex); m_tractor->remove_track(track.mlt_index); m_trackList.removeAt(trackIndex); -// foreach (Track t, m_trackList) LOG_DEBUG() << (t.type == VideoTrackType?"Video":"Audio") << "track number" << t.number << "mlt_index" << t.mlt_index; + // foreach (Track t, m_trackList) LOG_DEBUG() << (t.type == VideoTrackType?"Video":"Audio") << "track number" << t.number << "mlt_index" << t.mlt_index; // Renumber other tracks. int row = 0; @@ -2913,13 +2965,15 @@ void MultitrackModel::removeTrack(int trackIndex) QScopedPointer transition(getVideoBlendTransition(1)); if (transition && transition->is_valid()) transition->set("disable", 1); - emit dataChanged(modelIndex, modelIndex, QVector() << IsBottomVideoRole << IsCompositeRole); + emit dataChanged(modelIndex, + modelIndex, + QVector() << IsBottomVideoRole << IsCompositeRole); } // Rename default track names. QScopedPointer mltTrack(m_tractor->track(m_trackList[row].mlt_index)); - QString trackNameTemplate = (t.type == VideoTrackType) ? QStringLiteral("V%1") : - QStringLiteral("A%1"); + QString trackNameTemplate = (t.type == VideoTrackType) ? QStringLiteral("V%1") + : QStringLiteral("A%1"); QString trackName = trackNameTemplate.arg(t.number + 1); if (mltTrack && mltTrack->get(kTrackNameProperty) == trackName) { trackName = trackNameTemplate.arg(m_trackList[row].number + 1); @@ -2931,7 +2985,7 @@ void MultitrackModel::removeTrack(int trackIndex) } endRemoveRows(); MLT.updateAvformatCaching(m_tractor->count()); -// foreach (Track t, m_trackList) LOG_DEBUG() << (t.type == VideoTrackType?"Video":"Audio") << "track number" << t.number << "mlt_index" << t.mlt_index; + // foreach (Track t, m_trackList) LOG_DEBUG() << (t.type == VideoTrackType?"Video":"Audio") << "track number" << t.number << "mlt_index" << t.mlt_index; } emit modified(); } @@ -3008,7 +3062,7 @@ bool MultitrackModel::isTransition(Mlt::Playlist &playlist, int clipIndex) const { QScopedPointer producer(playlist.get_clip(clipIndex)); if (producer && producer->is_valid() && producer->parent().is_valid() - && producer->parent().get(kShotcutTransitionProperty)) + && producer->parent().get(kShotcutTransitionProperty)) return true; return false; } @@ -3033,7 +3087,8 @@ void MultitrackModel::insertTrack(int trackIndex, TrackType type) lowerVideoTransition.reset(getVideoBlendTransition(currentTrack.mlt_index)); // Handle special case of insert bottom video track. - if ((trackIndex > 0 && currentTrack.type == AudioTrackType) || trackIndex >= m_trackList.count()) { + if ((trackIndex > 0 && currentTrack.type == AudioTrackType) + || trackIndex >= m_trackList.count()) { Track &upperTrack = m_trackList[qBound(0, trackIndex - 1, m_trackList.count() - 1)]; if (upperTrack.type == VideoTrackType) { new_mlt_index = 1; @@ -3053,8 +3108,8 @@ void MultitrackModel::insertTrack(int trackIndex, TrackType type) } } -// foreach (Track t, m_trackList) LOG_DEBUG() << (t.type == VideoTrackType?"Video":"Audio") << "track number" << t.number << "mlt_index" << t.mlt_index; -// LOG_DEBUG() << "trackIndex" << trackIndex << "mlt_index" << i; + // foreach (Track t, m_trackList) LOG_DEBUG() << (t.type == VideoTrackType?"Video":"Audio") << "track number" << t.number << "mlt_index" << t.mlt_index; + // LOG_DEBUG() << "trackIndex" << trackIndex << "mlt_index" << i; // Compute new track numbers. int videoTrackCount = 0; @@ -3062,12 +3117,13 @@ void MultitrackModel::insertTrack(int trackIndex, TrackType type) int row = 0; foreach (Track t, m_trackList) { if (t.type == type) { - if ((t.type == VideoTrackType && (t.number > currentTrackNumber || isInsertBottomVideoTrack)) || - (t.type == AudioTrackType && t.number >= currentTrackNumber)) { + if ((t.type == VideoTrackType + && (t.number > currentTrackNumber || isInsertBottomVideoTrack)) + || (t.type == AudioTrackType && t.number >= currentTrackNumber)) { // Rename default track names. QScopedPointer mltTrack(m_tractor->track(t.mlt_index)); - QString trackNameTemplate = (t.type == VideoTrackType) ? QStringLiteral("V%1") : - QStringLiteral("A%1"); + QString trackNameTemplate = (t.type == VideoTrackType) ? QStringLiteral("V%1") + : QStringLiteral("A%1"); QString trackName = trackNameTemplate.arg(++t.number); if (mltTrack && mltTrack->get(kTrackNameProperty) == trackName) { trackName = trackNameTemplate.arg(t.number + 1); @@ -3089,7 +3145,7 @@ void MultitrackModel::insertTrack(int trackIndex, TrackType type) ++row; } -// foreach (Track t, m_trackList) LOG_DEBUG() << (t.type == VideoTrackType?"Video":"Audio") << "track number" << t.number << "mlt_index" << t.mlt_index; + // foreach (Track t, m_trackList) LOG_DEBUG() << (t.type == VideoTrackType?"Video":"Audio") << "track number" << t.number << "mlt_index" << t.mlt_index; // Create the MLT track. Mlt::Playlist playlist(MLT.profile()); @@ -3131,7 +3187,9 @@ void MultitrackModel::insertTrack(int trackIndex, TrackType type) if (lowerProducer->is_valid()) { composite.connect(*lowerProducer, 0, new_mlt_index); Mlt::Transition t((mlt_transition) lowerProducer->get_service()); - lowerVideoTransition->connect(composite, new_mlt_index, t.get_int("b_track")); + lowerVideoTransition->connect(composite, + new_mlt_index, + t.get_int("b_track")); } } else { LOG_DEBUG() << "inserting transition" << last_mlt_index << new_mlt_index; @@ -3171,7 +3229,7 @@ void MultitrackModel::insertTrack(int trackIndex, TrackType type) refreshVideoBlendTransitions(); endInsertRows(); emit modified(); -// foreach (Track t, m_trackList) LOG_DEBUG() << (t.type == VideoTrackType?"Video":"Audio") << "track number" << t.number << "mlt_index" << t.mlt_index; + // foreach (Track t, m_trackList) LOG_DEBUG() << (t.type == VideoTrackType?"Video":"Audio") << "track number" << t.number << "mlt_index" << t.mlt_index; } void MultitrackModel::moveTrack(int fromTrackIndex, int toTrackIndex) @@ -3179,7 +3237,7 @@ void MultitrackModel::moveTrack(int fromTrackIndex, int toTrackIndex) LOG_DEBUG() << "From: " << fromTrackIndex << "To: " << toTrackIndex; MLT.pause(); if (fromTrackIndex >= m_trackList.count() || fromTrackIndex < 0 - || toTrackIndex >= m_trackList.count() || toTrackIndex < 0) { + || toTrackIndex >= m_trackList.count() || toTrackIndex < 0) { LOG_DEBUG() << "Invalid track index" << fromTrackIndex << toTrackIndex; return; } @@ -3213,7 +3271,7 @@ void MultitrackModel::moveTrack(int fromTrackIndex, int toTrackIndex) newBTrack++; } } - if (service->get("mlt_service") != QStringLiteral("mix") ) { + if (service->get("mlt_service") != QStringLiteral("mix")) { videoTransitions[newBTrack] = *service; } else { audioTransitions[newBTrack] = *service; @@ -3222,7 +3280,6 @@ void MultitrackModel::moveTrack(int fromTrackIndex, int toTrackIndex) service.reset(service->producer()); } - if (toTrackIndex > fromTrackIndex) { beginMoveRows(QModelIndex(), fromTrackIndex, fromTrackIndex, QModelIndex(), toTrackIndex + 1); } else { @@ -3232,8 +3289,8 @@ void MultitrackModel::moveTrack(int fromTrackIndex, int toTrackIndex) // Clear all default track names (will regenerate in refreshTrackList) foreach (const Track &t, m_trackList) { QScopedPointer mltTrack(m_tractor->track(t.mlt_index)); - QString trackNameTemplate = (t.type == VideoTrackType) ? QStringLiteral("V%1") : - QStringLiteral("A%1"); + QString trackNameTemplate = (t.type == VideoTrackType) ? QStringLiteral("V%1") + : QStringLiteral("A%1"); QString trackName = trackNameTemplate.arg(t.number + 1); if (mltTrack && mltTrack->get(kTrackNameProperty) == trackName) { mltTrack->Mlt::Properties::clear(kTrackNameProperty); @@ -3262,12 +3319,12 @@ void MultitrackModel::moveTrack(int fromTrackIndex, int toTrackIndex) int bTrack = *i; int aTrack = 0; if (audioTransitions[bTrack].is_valid()) { - Mlt::Transition aTransition (MLT.profile(), audioTransitions[bTrack].get("mlt_service")); + Mlt::Transition aTransition(MLT.profile(), audioTransitions[bTrack].get("mlt_service")); aTransition.inherit(audioTransitions[bTrack]); m_tractor->plant_transition(aTransition, aTrack, bTrack); } if (videoTransitions[bTrack].is_valid()) { - Mlt::Transition vTransition (MLT.profile(), videoTransitions[bTrack].get("mlt_service")); + Mlt::Transition vTransition(MLT.profile(), videoTransitions[bTrack].get("mlt_service")); vTransition.set("1", videoTransitions[bTrack].get("1")); if (bTrack == 1) { vTransition.set("disable", 1); @@ -3289,9 +3346,10 @@ void MultitrackModel::moveTrack(int fromTrackIndex, int toTrackIndex) refreshTrackList(); endMoveRows(); - emit dataChanged(index(0), index(m_trackList.size() - 1), - QVector() << IsTopVideoRole << IsBottomVideoRole << IsTopAudioRole << IsBottomAudioRole << - IsCompositeRole << NameRole); + emit dataChanged(index(0), + index(m_trackList.size() - 1), + QVector() << IsTopVideoRole << IsBottomVideoRole << IsTopAudioRole + << IsBottomAudioRole << IsCompositeRole << NameRole); emit modified(); } @@ -3358,7 +3416,12 @@ bool MultitrackModel::mergeClipWithNext(int trackIndex, int clipIndex, bool dryr return true; // Consolidate filters - QStringList filters {"fadeInVolume", "fadeOutVolume", "fadeInBrightness", "fadeOutBrightness", "fadeInMovit", "fadeOutMovit"}; + QStringList filters{"fadeInVolume", + "fadeOutVolume", + "fadeInBrightness", + "fadeOutBrightness", + "fadeInMovit", + "fadeOutMovit"}; for (const auto &s : filters) { QScopedPointer filter(getFilter(s, clip1.producer)); if (filter && filter->is_valid()) { @@ -3391,7 +3454,7 @@ bool MultitrackModel::isFiltered(Mlt::Producer *producer) const for (int i = 0; i < count; i++) { QScopedPointer filter(producer->filter(i)); if (filter && filter->is_valid() && !filter->get_int("_loader") - && !filter->get_int(kShotcutHiddenProperty)) + && !filter->get_int(kShotcutHiddenProperty)) return true; } } @@ -3475,17 +3538,19 @@ void MultitrackModel::replace(int trackIndex, int clipIndex, Mlt::Producer &clip int i = m_trackList.at(trackIndex).mlt_index; QScopedPointer track(m_tractor->track(i)); if (track->is_valid()) { -// LOG_DEBUG() << __FUNCTION__ << "replace" << position << MLT.XML(&clip); + // LOG_DEBUG() << __FUNCTION__ << "replace" << position << MLT.XML(&clip); Mlt::Playlist playlist(*track.data()); int in = clip.get_in(); int out = clip.get_out(); Mlt::Producer oldClip(playlist.get_clip(clipIndex)); Q_ASSERT(oldClip.is_valid()); int clipPlaytime = oldClip.get_playtime(); - int transitionIn = oldClip.parent().get(kFilterInProperty) ? oldClip.get_in() - - oldClip.parent().get_int(kFilterInProperty) : 0; - int transitionOut = oldClip.parent().get(kFilterOutProperty) ? oldClip.parent().get_int( - kFilterOutProperty) - oldClip.get_out() : 0; + int transitionIn = oldClip.parent().get(kFilterInProperty) + ? oldClip.get_in() - oldClip.parent().get_int(kFilterInProperty) + : 0; + int transitionOut = oldClip.parent().get(kFilterOutProperty) + ? oldClip.parent().get_int(kFilterOutProperty) - oldClip.get_out() + : 0; in += transitionIn; out -= transitionOut; @@ -3533,7 +3598,7 @@ void MultitrackModel::replace(int trackIndex, int clipIndex, Mlt::Producer &clip QScopedPointer track(tractor.track(0)); if (!qstrcmp(track->parent().get(kShotcutHashProperty), oldClip.parent().get(kShotcutHashProperty))) { - QScopedPointer cut(clip.cut(out + 1, out + transitionOut)); + QScopedPointer cut(clip.cut(out + 1, out + transitionOut)); tractor.set_track(*cut.data(), 0); } } @@ -3543,7 +3608,8 @@ void MultitrackModel::replace(int trackIndex, int clipIndex, Mlt::Producer &clip void MultitrackModel::close() { - if (!m_tractor) return; + if (!m_tractor) + return; emit aboutToClose(); AudioLevelsTask::closeAll(); beginResetModel(); @@ -3633,7 +3699,7 @@ void MultitrackModel::refreshTrackList() trackName = QStringLiteral("A%1").arg(a); track->set(kTrackNameProperty, trackName.toUtf8().constData()); m_trackList.append(t); -// LOG_DEBUG() << __FUNCTION__ << QString(track->get("id")) << i; + // LOG_DEBUG() << __FUNCTION__ << QString(track->get("id")) << i; } } } diff --git a/src/models/multitrackmodel.h b/src/models/multitrackmodel.h index aeef9ae1a2..41feb3fd7f 100644 --- a/src/models/multitrackmodel.h +++ b/src/models/multitrackmodel.h @@ -18,11 +18,12 @@ #ifndef MULTITRACKMODEL_H #define MULTITRACKMODEL_H +#include +#include #include #include #include -#include -#include + #include typedef enum { @@ -33,7 +34,8 @@ typedef enum { VideoTrackType } TrackType; -typedef struct { +typedef struct +{ TrackType type; int number; int mlt_index; @@ -52,52 +54,45 @@ class MultitrackModel : public QAbstractItemModel /// Two level model: tracks and clips on track enum { NameRole = Qt::UserRole + 1, - CommentRole, /// clip only - ResourceRole, /// clip only - ServiceRole, /// clip only - IsBlankRole, /// clip only - StartRole, /// clip only + CommentRole, /// clip only + ResourceRole, /// clip only + ServiceRole, /// clip only + IsBlankRole, /// clip only + StartRole, /// clip only DurationRole, - InPointRole, /// clip only - OutPointRole, /// clip only - FramerateRole, /// clip only - IsMuteRole, /// track only - IsHiddenRole, /// track only + InPointRole, /// clip only + OutPointRole, /// clip only + FramerateRole, /// clip only + IsMuteRole, /// track only + IsHiddenRole, /// track only IsAudioRole, - AudioLevelsRole, /// clip only - IsCompositeRole, /// track only - IsLockedRole, /// track only - FadeInRole, /// clip only - FadeOutRole, /// clip only - IsTransitionRole,/// clip only - FileHashRole, /// clip only - SpeedRole, /// clip only + AudioLevelsRole, /// clip only + IsCompositeRole, /// track only + IsLockedRole, /// track only + FadeInRole, /// clip only + FadeOutRole, /// clip only + IsTransitionRole, /// clip only + FileHashRole, /// clip only + SpeedRole, /// clip only IsFilteredRole, - IsTopVideoRole, /// track only - IsBottomVideoRole,/// track only - IsTopAudioRole, /// track only - IsBottomAudioRole,/// track only - AudioIndexRole, /// clip only - GroupRole, /// clip only + IsTopVideoRole, /// track only + IsBottomVideoRole, /// track only + IsTopAudioRole, /// track only + IsBottomAudioRole, /// track only + AudioIndexRole, /// clip only + GroupRole, /// clip only }; explicit MultitrackModel(QObject *parent = 0); ~MultitrackModel(); - Mlt::Tractor *tractor() const - { - return m_tractor; - } - const TrackList &trackList() const - { - return m_trackList; - } + Mlt::Tractor *tractor() const { return m_tractor; } + const TrackList &trackList() const { return m_trackList; } int rowCount(const QModelIndex &parent = QModelIndex()) const; int columnCount(const QModelIndex &parent) const; QVariant data(const QModelIndex &index, int role) const; - QModelIndex index(int row, int column = 0, - const QModelIndex &parent = QModelIndex()) const; + QModelIndex index(int row, int column = 0, const QModelIndex &parent = QModelIndex()) const; QModelIndex makeIndex(int trackIndex, int clipIndex) const; QModelIndex parent(const QModelIndex &index) const; QHash roleNames() const; @@ -121,7 +116,9 @@ class MultitrackModel : public QAbstractItemModel void moveTrack(int fromTrackIndex, int toTrackIndex); void insertOrAdjustBlankAt(QList tracks, int position, int length); bool mergeClipWithNext(int trackIndex, int clipIndex, bool dryrun); - std::unique_ptr findClipByUuid(const QUuid &uuid, int &trackIndex, int &clipIndex); + std::unique_ptr findClipByUuid(const QUuid &uuid, + int &trackIndex, + int &clipIndex); std::unique_ptr getClipInfo(int trackIndex, int clipIndex); QString getTrackName(int trackIndex); int bottomVideoTrackIndex() const; @@ -157,13 +154,17 @@ public slots: void notifyClipIn(int trackIndex, int clipIndex); int trimClipOut(int trackIndex, int clipIndex, int delta, bool ripple, bool rippleAllTracks); void notifyClipOut(int trackIndex, int clipIndex); - bool moveClip(int fromTrack, int toTrack, int clipIndex, int position, bool ripple, - bool rippleAllTracks); + bool moveClip( + int fromTrack, int toTrack, int clipIndex, int position, bool ripple, bool rippleAllTracks); int overwriteClip(int trackIndex, Mlt::Producer &clip, int position, bool seek = true); - QString overwrite(int trackIndex, Mlt::Producer &clip, int position, bool seek = true, - bool notify = true); - int insertClip(int trackIndex, Mlt::Producer &clip, int position, bool rippleAllTracks, - bool seek = true, bool notify = true); + QString overwrite( + int trackIndex, Mlt::Producer &clip, int position, bool seek = true, bool notify = true); + int insertClip(int trackIndex, + Mlt::Producer &clip, + int position, + bool rippleAllTracks, + bool seek = true, + bool notify = true); int appendClip(int trackIndex, Mlt::Producer &clip, bool seek = true, bool notify = true); void removeClip(int trackIndex, int clipIndex, bool rippleAllTracks); void liftClip(int trackIndex, int clipIndex); @@ -196,10 +197,19 @@ public slots: TrackList m_trackList; bool m_isMakingTransition; - void moveClipToEnd(Mlt::Playlist &playlist, int trackIndex, int clipIndex, int position, - bool ripple, bool rippleAllTracks); - void moveClipInBlank(Mlt::Playlist &playlist, int trackIndex, int clipIndex, int position, - bool ripple, bool rippleAllTracks, int duration = 0); + void moveClipToEnd(Mlt::Playlist &playlist, + int trackIndex, + int clipIndex, + int position, + bool ripple, + bool rippleAllTracks); + void moveClipInBlank(Mlt::Playlist &playlist, + int trackIndex, + int clipIndex, + int position, + bool ripple, + bool rippleAllTracks, + int duration = 0); void consolidateBlanks(Mlt::Playlist &playlist, int trackIndex); void consolidateBlanksAllTracks(); void getAudioLevels(); diff --git a/src/models/playlistmodel.cpp b/src/models/playlistmodel.cpp index 9e76dc6814..e6e06ce1fe 100644 --- a/src/models/playlistmodel.cpp +++ b/src/models/playlistmodel.cpp @@ -16,25 +16,26 @@ */ #include "playlistmodel.h" -#include "util.h" + +#include "Logger.h" +#include "database.h" +#include "mainwindow.h" +#include "proxymanager.h" +#include "settings.h" #include "shotcut_mlt_properties.h" +#include "util.h" + +#include +#include +#include #include -#include +#include #include -#include #include -#include -#include -#include #include -#include #include -#include - -#include "settings.h" -#include "database.h" -#include "mainwindow.h" -#include "proxymanager.h" +#include +#include static void deleteQImage(QImage *image) { @@ -53,8 +54,8 @@ class UpdateThumbnailTask : public QRunnable bool m_force; public: - UpdateThumbnailTask(PlaylistModel *model, Mlt::Producer &producer, int in, int out, int row, - bool force = false) + UpdateThumbnailTask( + PlaylistModel *model, Mlt::Producer &producer, int in, int out, int row, bool force = false) : QRunnable() , m_model(model) , m_producer(producer) @@ -66,10 +67,7 @@ class UpdateThumbnailTask : public QRunnable , m_force(force) {} - ~UpdateThumbnailTask() - { - delete m_tempProducer; - } + ~UpdateThumbnailTask() { delete m_tempProducer; } Mlt::Producer *tempProducer() { @@ -80,9 +78,12 @@ class UpdateThumbnailTask : public QRunnable else if (service.startsWith("xml")) service = "xml-nogl"; if (service == "count") { - m_tempProducer = new Mlt::Producer(m_profile, service.toUtf8().constData(), "loader-nogl"); + m_tempProducer = new Mlt::Producer(m_profile, + service.toUtf8().constData(), + "loader-nogl"); } else if (!Settings.playerGPU() || (service != "xml-nogl" && service != "consumer")) { - m_tempProducer = new Mlt::Producer(m_profile, service.toUtf8().constData(), + m_tempProducer = new Mlt::Producer(m_profile, + service.toUtf8().constData(), m_producer.get("resource")); } if (m_tempProducer && m_tempProducer->is_valid()) { @@ -107,9 +108,9 @@ class UpdateThumbnailTask : public QRunnable QString resource = m_producer.get(kShotcutHashProperty); if (resource.isEmpty()) { key = QStringLiteral("%1 %2 %3") - .arg(m_producer.get("mlt_service")) - .arg(m_producer.get("resource")) - .arg(time); + .arg(m_producer.get("mlt_service")) + .arg(m_producer.get("resource")) + .arg(time); QCryptographicHash hash(QCryptographicHash::Sha1); hash.addData(key.toUtf8()); key = hash.result().toHex(); @@ -132,10 +133,18 @@ class UpdateThumbnailTask : public QRunnable QImage image = DB.getThumbnail(cacheKey(inPoint)); if (m_force || image.isNull()) { image = makeThumbnail(inPoint); - m_producer.set(kThumbnailInProperty, new QImage(image), 0, (mlt_destructor) deleteQImage, NULL); + m_producer.set(kThumbnailInProperty, + new QImage(image), + 0, + (mlt_destructor) deleteQImage, + NULL); DB.putThumbnail(cacheKey(inPoint), image); } else { - m_producer.set(kThumbnailInProperty, new QImage(image), 0, (mlt_destructor) deleteQImage, NULL); + m_producer.set(kThumbnailInProperty, + new QImage(image), + 0, + (mlt_destructor) deleteQImage, + NULL); } m_model->showThumbnail(m_row); @@ -143,10 +152,18 @@ class UpdateThumbnailTask : public QRunnable image = DB.getThumbnail(cacheKey(outPoint)); if (m_force || image.isNull()) { image = makeThumbnail(outPoint); - m_producer.set(kThumbnailOutProperty, new QImage(image), 0, (mlt_destructor) deleteQImage, NULL); + m_producer.set(kThumbnailOutProperty, + new QImage(image), + 0, + (mlt_destructor) deleteQImage, + NULL); DB.putThumbnail(cacheKey(outPoint), image); } else { - m_producer.set(kThumbnailOutProperty, new QImage(image), 0, (mlt_destructor) deleteQImage, NULL); + m_producer.set(kThumbnailOutProperty, + new QImage(image), + 0, + (mlt_destructor) deleteQImage, + NULL); } m_model->showThumbnail(m_row); } @@ -171,8 +188,10 @@ PlaylistModel::PlaylistModel(QObject *parent) , m_dropRow(-1) , m_mode(Invalid) { - qRegisterMetaType >("QVector"); - connect(this, &QAbstractItemModel::rowsAboutToBeRemoved, this, + qRegisterMetaType>("QVector"); + connect(this, + &QAbstractItemModel::rowsAboutToBeRemoved, + this, &PlaylistModel::onRowsAboutToBeRemoved); } @@ -278,20 +297,22 @@ QVariant PlaylistModel::data(const QModelIndex &index, int role) const } case FIELD_IN: if (info->producer && info->producer->is_valid()) { - return QString::fromLatin1(info->producer->frames_to_time(info->frame_in, Settings.timeFormat())); + return QString::fromLatin1( + info->producer->frames_to_time(info->frame_in, Settings.timeFormat())); } else { return ""; } case FIELD_DURATION: if (info->producer && info->producer->is_valid()) { - return QString::fromLatin1(info->producer->frames_to_time(info->frame_count, - Settings.timeFormat())); + return QString::fromLatin1( + info->producer->frames_to_time(info->frame_count, Settings.timeFormat())); } else { return ""; } case FIELD_START: if (info->producer && info->producer->is_valid()) { - return QString::fromLatin1(info->producer->frames_to_time(info->start, Settings.timeFormat())); + return QString::fromLatin1( + info->producer->frames_to_time(info->start, Settings.timeFormat())); } else { return ""; } @@ -338,7 +359,8 @@ QVariant PlaylistModel::data(const QModelIndex &index, int role) const } painter.drawImage(rect, *thumb); - if ((setting == "wide" || setting == "tall") && parent.get_data(kThumbnailOutProperty)) { + if ((setting == "wide" || setting == "tall") + && parent.get_data(kThumbnailOutProperty)) { // draw the out thumbnail thumb = (QImage *) parent.get_data(kThumbnailOutProperty); if (setting == "wide") { @@ -376,7 +398,7 @@ QVariant PlaylistModel::data(const QModelIndex &index, int role) const auto service = QString::fromLatin1(info->producer->get("mlt_service")); if (service.startsWith("avformat")) { if (info->producer->get_int("video_index") > -1 - && Util::getSuggestedFrameRate(info->producer) != 90000) + && Util::getSuggestedFrameRate(info->producer) != 90000) type = Video; else if (info->producer->get_int("audio_index") > -1) type = Audio; @@ -503,7 +525,8 @@ bool PlaylistModel::insertRows(int row, int count, const QModelIndex &parent) { Q_UNUSED(count) Q_UNUSED(parent) - if (!m_playlist) return false; + if (!m_playlist) + return false; if (m_dropRow == -1) m_dropRow = row; return true; @@ -513,7 +536,8 @@ bool PlaylistModel::removeRows(int row, int count, const QModelIndex &parent) { Q_UNUSED(count) Q_UNUSED(parent) - if (!m_playlist || m_dropRow == -1 ) return false; + if (!m_playlist || m_dropRow == -1) + return false; if (row < m_dropRow) { if (!m_rowsRemoved.contains(row)) { int adjustment = 0; @@ -539,8 +563,8 @@ bool PlaylistModel::removeRows(int row, int count, const QModelIndex &parent) return true; } -bool PlaylistModel::moveRows(const QModelIndex &, int sourceRow, int count, const QModelIndex &, - int destinationChild) +bool PlaylistModel::moveRows( + const QModelIndex &, int sourceRow, int count, const QModelIndex &, int destinationChild) { Q_ASSERT(count == 1); move(sourceRow, destinationChild); @@ -549,11 +573,13 @@ bool PlaylistModel::moveRows(const QModelIndex &, int sourceRow, int count, cons void PlaylistModel::sort(int column, Qt::SortOrder order) { - if (!m_playlist) return; + if (!m_playlist) + return; int index = 0; int count = rowCount(); - if (count < 2) return; + if (count < 2) + return; // Create a list mapping values to their original index. QVector> indexMap(count); @@ -598,12 +624,14 @@ QMimeData *PlaylistModel::mimeData(const QModelIndexList &indexes) const QMimeData *mimeData = new QMimeData; int count = 0; foreach (auto index, indexes) { - if (index.column()) continue; + if (index.column()) + continue; count += m_playlist->clip_length(index.row()); } Mlt::Playlist playlist(MLT.profile()); foreach (auto index, indexes) { - if (m_mode == Detailed && index.column() != COLUMN_RESOURCE) continue; + if (m_mode == Detailed && index.column() != COLUMN_RESOURCE) + continue; QScopedPointer info(m_playlist->clip_info(index.row())); if (info && info->producer) { playlist.append(*info->producer, info->frame_in, info->frame_out); @@ -616,8 +644,8 @@ QMimeData *PlaylistModel::mimeData(const QModelIndexList &indexes) const return mimeData; } -bool PlaylistModel::dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, - const QModelIndex &parent) +bool PlaylistModel::dropMimeData( + const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent) { Q_UNUSED(column) Q_UNUSED(parent) @@ -670,7 +698,8 @@ QModelIndex PlaylistModel::createIndex(int row, int column) const void PlaylistModel::clear() { - if (!m_playlist) return; + if (!m_playlist) + return; if (rowCount()) { beginRemoveRows(QModelIndex(), 0, rowCount() - 1); m_playlist->clear(); @@ -717,8 +746,7 @@ void PlaylistModel::append(Mlt::Producer &producer, bool emitModified) int in = producer.get_in(); int out = producer.get_out(); producer.set_in_and_out(0, producer.get_length() - 1); - QThreadPool::globalInstance()->start( - new UpdateThumbnailTask(this, producer, in, out, count), 1); + QThreadPool::globalInstance()->start(new UpdateThumbnailTask(this, producer, in, out, count), 1); beginInsertRows(QModelIndex(), count, count); m_playlist->append(producer, in, out); endInsertRows(); @@ -732,8 +760,7 @@ void PlaylistModel::insert(Mlt::Producer &producer, int row) int in = producer.get_in(); int out = producer.get_out(); producer.set_in_and_out(0, producer.get_length() - 1); - QThreadPool::globalInstance()->start( - new UpdateThumbnailTask(this, producer, in, out, row), 1); + QThreadPool::globalInstance()->start(new UpdateThumbnailTask(this, producer, in, out, row), 1); beginInsertRows(QModelIndex(), row, row); m_playlist->insert(producer, row, in, out); endInsertRows(); @@ -742,7 +769,8 @@ void PlaylistModel::insert(Mlt::Producer &producer, int row) void PlaylistModel::remove(int row) { - if (!m_playlist) return; + if (!m_playlist) + return; beginRemoveRows(QModelIndex(), row, row); m_playlist->remove(row); endRemoveRows(); @@ -754,12 +782,12 @@ void PlaylistModel::remove(int row) void PlaylistModel::update(int row, Mlt::Producer &producer, bool copyFilters) { - if (!m_playlist) return; + if (!m_playlist) + return; int in = producer.get_in(); int out = producer.get_out(); producer.set_in_and_out(0, producer.get_length() - 1); - QThreadPool::globalInstance()->start( - new UpdateThumbnailTask(this, producer, in, out, row), 1); + QThreadPool::globalInstance()->start(new UpdateThumbnailTask(this, producer, in, out, row), 1); if (copyFilters) { Mlt::Producer oldClip(m_playlist->get_clip(row)); Q_ASSERT(oldClip.is_valid()); @@ -774,12 +802,18 @@ void PlaylistModel::update(int row, Mlt::Producer &producer, bool copyFilters) void PlaylistModel::updateThumbnails(int row) { - if (!m_playlist) return; + if (!m_playlist) + return; QScopedPointer info(m_playlist->clip_info(row)); - if (!info || !info->producer->is_valid()) return; - QThreadPool::globalInstance()->start( - new UpdateThumbnailTask(this, *info->producer, info->frame_in, info->frame_out, row, - true /* force */), 1); + if (!info || !info->producer->is_valid()) + return; + QThreadPool::globalInstance()->start(new UpdateThumbnailTask(this, + *info->producer, + info->frame_in, + info->frame_out, + row, + true /* force */), + 1); } void PlaylistModel::appendBlank(int frames) @@ -803,7 +837,8 @@ void PlaylistModel::insertBlank(int frames, int row) void PlaylistModel::close() { - if (!m_playlist) return; + if (!m_playlist) + return; clear(); delete m_playlist; m_playlist = nullptr; @@ -812,7 +847,8 @@ void PlaylistModel::close() void PlaylistModel::move(int from, int to) { - if (!m_playlist) return; + if (!m_playlist) + return; beginResetModel(); m_playlist->move(from, to); endResetModel(); @@ -849,8 +885,12 @@ void PlaylistModel::refreshThumbnails() for (int i = 0; i < m_playlist->count(); i++) { Mlt::ClipInfo *info = m_playlist->clip_info(i); if (info && info->producer && info->producer->is_valid()) { - QThreadPool::globalInstance()->start( - new UpdateThumbnailTask(this, *info->producer, info->frame_in, info->frame_out, i), 1); + QThreadPool::globalInstance()->start(new UpdateThumbnailTask(this, + *info->producer, + info->frame_in, + info->frame_out, + i), + 1); } delete info; } @@ -888,7 +928,8 @@ void PlaylistModel::setPlaylist(Mlt::Playlist &playlist) void PlaylistModel::setInOut(int row, int in, int out) { - if (!m_playlist || row < 0 || row >= m_playlist->count()) return; + if (!m_playlist || row < 0 || row >= m_playlist->count()) + return; bool inChanged = false, outChanged = false; QScopedPointer info(m_playlist->clip_info(row)); if (info && info->producer && info->producer->is_valid()) { @@ -897,11 +938,13 @@ void PlaylistModel::setInOut(int row, int in, int out) outChanged = info->frame_out != out; } m_playlist->resize_clip(row, in, out); - QThreadPool::globalInstance()->start( - new UpdateThumbnailTask(this, *info->producer, in, out, row), 1); + QThreadPool::globalInstance() + ->start(new UpdateThumbnailTask(this, *info->producer, in, out, row), 1); emit dataChanged(createIndex(row, COLUMN_IN), createIndex(row, COLUMN_START)); emit modified(); - if (inChanged) emit this->inChanged(in); - if (outChanged) emit this->outChanged(out); + if (inChanged) + emit this->inChanged(in); + if (outChanged) + emit this->outChanged(out); } } diff --git a/src/models/playlistmodel.h b/src/models/playlistmodel.h index dda9408d6e..1672b29632 100644 --- a/src/models/playlistmodel.h +++ b/src/models/playlistmodel.h @@ -18,12 +18,10 @@ #ifndef PLAYLISTMODEL_H #define PLAYLISTMODEL_H +#include #include #include #include -#include "MltPlaylist.h" - - class PlaylistModel : public QAbstractTableModel { @@ -36,13 +34,7 @@ class PlaylistModel : public QAbstractTableModel Icons, }; - enum MediaType { - Video, - Image, - Audio, - Other, - Pending - }; + enum MediaType { Video, Image, Audio, Other, Pending }; enum Columns { COLUMN_INDEX = 0, @@ -84,22 +76,25 @@ class PlaylistModel : public QAbstractTableModel Qt::DropActions supportedDropActions() const; bool insertRows(int row, int count, const QModelIndex &parent = QModelIndex()); bool removeRows(int row, int count, const QModelIndex &parent = QModelIndex()); - bool moveRows(const QModelIndex &sourceParent, int sourceRow, int count, - const QModelIndex &destinationParent, int destinationChild); + bool moveRows(const QModelIndex &sourceParent, + int sourceRow, + int count, + const QModelIndex &destinationParent, + int destinationChild); void sort(int column, Qt::SortOrder order = Qt::AscendingOrder); Qt::ItemFlags flags(const QModelIndex &index) const; QStringList mimeTypes() const; QMimeData *mimeData(const QModelIndexList &indexes) const; - bool dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, + bool dropMimeData(const QMimeData *data, + Qt::DropAction action, + int row, + int column, const QModelIndex &parent); QModelIndex createIndex(int row, int column) const; void createIfNeeded(); void showThumbnail(int row); void refreshThumbnails(); - Mlt::Playlist *playlist() - { - return m_playlist; - } + Mlt::Playlist *playlist() { return m_playlist; } void setPlaylist(Mlt::Playlist &playlist); void setInOut(int row, int in, int out); diff --git a/src/models/resourcemodel.cpp b/src/models/resourcemodel.cpp index 731b0e6bef..5912d2bf10 100644 --- a/src/models/resourcemodel.cpp +++ b/src/models/resourcemodel.cpp @@ -17,9 +17,9 @@ #include "resourcemodel.h" -#include -#include "util.h" +#include "Logger.h" #include "shotcut_mlt_properties.h" +#include "util.h" #include @@ -33,7 +33,8 @@ class ProducerFinder : public Mlt::Parser int on_start_producer(Mlt::Producer *producer) { - if (!m_isBackgroundTrack && producer->parent().get("resource") != QStringLiteral("")) { + if (!m_isBackgroundTrack + && producer->parent().get("resource") != QStringLiteral("")) { if (!m_isTransition) m_clipIndex++; if (!producer->is_blank()) { @@ -42,9 +43,13 @@ class ProducerFinder : public Mlt::Parser location = QObject::tr("Playlist Clip: %1").arg(m_clipIndex + 1); } else { if (m_isTransition) { - location = QObject::tr("Track: %1, Clip: %2 (transition)").arg(m_trackName).arg(m_clipIndex + 1); + location = QObject::tr("Track: %1, Clip: %2 (transition)") + .arg(m_trackName) + .arg(m_clipIndex + 1); } else { - location = QObject::tr("Track: %1, Clip: %2").arg(m_trackName).arg(m_clipIndex + 1); + location = QObject::tr("Track: %1, Clip: %2") + .arg(m_trackName) + .arg(m_clipIndex + 1); } } m_model->add(producer, location); @@ -53,14 +58,8 @@ class ProducerFinder : public Mlt::Parser return 0; } - int on_start_filter(Mlt::Filter *) - { - return 0; - } - int on_end_producer(Mlt::Producer *) - { - return 0; - } + int on_start_filter(Mlt::Filter *) { return 0; } + int on_end_producer(Mlt::Producer *) { return 0; } int on_start_playlist(Mlt::Playlist *playlist) { if (playlist->get("id") == QStringLiteral("background")) { @@ -92,14 +91,8 @@ class ProducerFinder : public Mlt::Parser m_isTransition = false; return 0; } - int on_start_multitrack(Mlt::Multitrack *) - { - return 0; - } - int on_end_multitrack(Mlt::Multitrack *) - { - return 0; - } + int on_start_multitrack(Mlt::Multitrack *) { return 0; } + int on_end_multitrack(Mlt::Multitrack *) { return 0; } int on_start_track() { if (!m_isTransition) { @@ -108,38 +101,15 @@ class ProducerFinder : public Mlt::Parser } return 0; } - int on_end_track() - { - return 0; - } - int on_end_filter(Mlt::Filter *) - { - return 0; - } - int on_start_transition(Mlt::Transition *) - { - return 0; - } - int on_end_transition(Mlt::Transition *) - { - return 0; - } - int on_start_chain(Mlt::Chain *) - { - return 0; - } - int on_end_chain(Mlt::Chain *) - { - return 0; - } - int on_start_link(Mlt::Link *) - { - return 0; - } - int on_end_link(Mlt::Link *) - { - return 0; - } + int on_end_track() { return 0; } + int on_end_filter(Mlt::Filter *) { return 0; } + int on_start_transition(Mlt::Transition *) { return 0; } + int on_end_transition(Mlt::Transition *) { return 0; } + int on_start_chain(Mlt::Chain *) { return 0; } + int on_end_chain(Mlt::Chain *) { return 0; } + int on_start_link(Mlt::Link *) { return 0; } + int on_end_link(Mlt::Link *) { return 0; } + private: ResourceModel *m_model; bool m_isTimeline = false; @@ -161,12 +131,9 @@ QString appendLocation(QString ¤tLocations, const QString &location) ResourceModel::ResourceModel(QObject *parent) : QAbstractItemModel(parent) -{ -} +{} -ResourceModel::~ResourceModel() -{ -} +ResourceModel::~ResourceModel() {} void ResourceModel::search(Mlt::Producer *producer) { @@ -176,9 +143,11 @@ void ResourceModel::search(Mlt::Producer *producer) ProducerFinder parser(this); beginResetModel(); parser.start(*producer); - std::sort(m_producers.begin(), m_producers.end(), [ & ](Mlt::Producer & a, Mlt::Producer & b) { - return Util::GetFilenameFromProducer(&a, true).compare(Util::GetFilenameFromProducer(&b, true), - Qt::CaseInsensitive) < 0; + std::sort(m_producers.begin(), m_producers.end(), [&](Mlt::Producer &a, Mlt::Producer &b) { + return Util::GetFilenameFromProducer(&a, true).compare(Util::GetFilenameFromProducer(&b, + true), + Qt::CaseInsensitive) + < 0; }); endResetModel(); } @@ -225,7 +194,7 @@ QList ResourceModel::getProducers(const QModelIndexList &indices) bool ResourceModel::exists(const QString &hash) { - for ( int i = 0; i < m_producers.count(); ++i ) { + for (int i = 0; i < m_producers.count(); ++i) { if (Util::getHash(m_producers[i]) == hash) { return true; } @@ -273,12 +242,12 @@ QVariant ResourceModel::data(const QModelIndex &index, int role) const } if (!index.isValid() || index.column() < 0 || index.column() >= COLUMN_COUNT || index.row() < 0 - || index.row() >= m_producers.size()) { + || index.row() >= m_producers.size()) { LOG_ERROR() << "Invalid Index: " << index.row() << index.column() << role; return result; } - Mlt::Producer *producer = const_cast(&m_producers[index.row()] ); + Mlt::Producer *producer = const_cast(&m_producers[index.row()]); switch (role) { case Qt::DisplayRole: switch (index.column()) { @@ -293,7 +262,7 @@ QVariant ResourceModel::data(const QModelIndex &index, int role) const case COLUMN_SIZE: { QString path = Util::GetFilenameFromProducer(producer, true); QFileInfo info(path); - double size = (double)info.size() / (double)(1024 * 1024); + double size = (double) info.size() / (double) (1024 * 1024); result = tr("%1MB").arg(QLocale().toString(size, 'f', 2)); break; } @@ -303,23 +272,21 @@ QVariant ResourceModel::data(const QModelIndex &index, int role) const if (producer->get_int("video_index") >= 0) { double frame_rate_num = producer->get_double("meta.media.frame_rate_num"); double frame_rate_den = producer->get_double("meta.media.frame_rate_den"); - if ( width && height && frame_rate_num && frame_rate_den - && (frame_rate_num / frame_rate_den) < 1000) { + if (width && height && frame_rate_num && frame_rate_den + && (frame_rate_num / frame_rate_den) < 1000) { int index = producer->get_int("video_index"); QString key = QStringLiteral("meta.media.%1.codec.name").arg(index); QString codec(producer->get(key.toLatin1().constData())); double frame_rate = frame_rate_num / frame_rate_den; result = tr("%1 %2x%3 %4fps") - .arg(codec) - .arg(width) - .arg(height) - .arg(QLocale().toString(frame_rate, 'f', 2)); + .arg(codec) + .arg(width) + .arg(height) + .arg(QLocale().toString(frame_rate, 'f', 2)); } } - if (result.isNull() && width > 0 && height > 0 ) { - result = QString(QObject::tr("%1x%2")) - .arg(width) - .arg(height); + if (result.isNull() && width > 0 && height > 0) { + result = QString(QObject::tr("%1x%2")).arg(width).arg(height); } break; } @@ -334,16 +301,16 @@ QVariant ResourceModel::data(const QModelIndex &index, int role) const key = QStringLiteral("meta.media.%1.codec.sample_rate").arg(index); QString sampleRate(producer->get(key.toLatin1().constData())); result = QStringLiteral("%1 %2ch %3KHz") - .arg(codec) - .arg(channels) - .arg(sampleRate.toDouble() / 1000); + .arg(codec) + .arg(channels) + .arg(sampleRate.toDouble() / 1000); } } break; } default: - LOG_ERROR() << "Invalid DisplayRole Column" << index.row() << index.column() << roleNames()[role] << - role; + LOG_ERROR() << "Invalid DisplayRole Column" << index.row() << index.column() + << roleNames()[role] << role; break; } break; @@ -367,8 +334,8 @@ QVariant ResourceModel::data(const QModelIndex &index, int role) const break; } default: - LOG_ERROR() << "Invalid ToolTipRole Column" << index.row() << index.column() << roleNames()[role] << - role; + LOG_ERROR() << "Invalid ToolTipRole Column" << index.row() << index.column() + << roleNames()[role] << role; break; } break; @@ -384,8 +351,8 @@ QVariant ResourceModel::data(const QModelIndex &index, int role) const result = Qt::AlignRight; break; default: - LOG_ERROR() << "Invalid TextAlignmentRole Column" << index.row() << index.column() << - roleNames()[role] << role; + LOG_ERROR() << "Invalid TextAlignmentRole Column" << index.row() << index.column() + << roleNames()[role] << role; break; } break; @@ -404,8 +371,8 @@ QVariant ResourceModel::data(const QModelIndex &index, int role) const case COLUMN_SIZE: break; default: - LOG_ERROR() << "Invalid DecorationRole Column" << index.row() << index.column() << roleNames()[role] - << role; + LOG_ERROR() << "Invalid DecorationRole Column" << index.row() << index.column() + << roleNames()[role] << role; break; } break; @@ -455,7 +422,7 @@ QModelIndex ResourceModel::index(int row, int column, const QModelIndex &parent) Q_UNUSED(parent) if (column < 0 || column >= COLUMN_COUNT || row < 0 || row >= m_producers.size()) return QModelIndex(); - return createIndex(row, column, (int)0); + return createIndex(row, column, (int) 0); } QModelIndex ResourceModel::parent(const QModelIndex &index) const diff --git a/src/models/resourcemodel.h b/src/models/resourcemodel.h index e7f8b64ac8..aaa71f9a3a 100644 --- a/src/models/resourcemodel.h +++ b/src/models/resourcemodel.h @@ -19,7 +19,6 @@ #define RESOURCEMODEL_H #include - #include class ResourceModel : public QAbstractItemModel @@ -27,7 +26,6 @@ class ResourceModel : public QAbstractItemModel Q_OBJECT public: - enum Columns { COLUMN_INFO = 0, COLUMN_NAME, @@ -54,7 +52,6 @@ class ResourceModel : public QAbstractItemModel QModelIndex parent(const QModelIndex &index) const; private: - QList m_producers; QMap m_locations; }; diff --git a/src/models/subtitles.h b/src/models/subtitles.h index 7f5178902d..26411a6231 100644 --- a/src/models/subtitles.h +++ b/src/models/subtitles.h @@ -24,7 +24,8 @@ namespace Subtitles { -struct SubtitleItem { +struct SubtitleItem +{ int64_t start; int64_t end; std::string text; diff --git a/src/models/subtitlesmodel.cpp b/src/models/subtitlesmodel.cpp index f0f3057fa5..69f650c33c 100644 --- a/src/models/subtitlesmodel.cpp +++ b/src/models/subtitlesmodel.cpp @@ -17,12 +17,12 @@ #include "subtitlesmodel.h" -#include +#include "Logger.h" +#include "commands/subtitlecommands.h" #include "mainwindow.h" #include "mltcontroller.h" #include "settings.h" #include "shotcut_mlt_properties.h" -#include "commands/subtitlecommands.h" #include @@ -30,13 +30,7 @@ static const quintptr NO_PARENT_ID = quintptr(-1); -enum Columns { - COLUMN_TEXT = 0, - COLUMN_START, - COLUMN_END, - COLUMN_DURATION, - COLUMN_COUNT -}; +enum Columns { COLUMN_TEXT = 0, COLUMN_START, COLUMN_END, COLUMN_DURATION, COLUMN_COUNT }; SubtitlesModel::SubtitlesModel(QObject *parent) : QAbstractItemModel(parent) @@ -64,9 +58,7 @@ SubtitlesModel::SubtitlesModel(QObject *parent) }); } -SubtitlesModel::~SubtitlesModel() -{ -} +SubtitlesModel::~SubtitlesModel() {} void SubtitlesModel::load(Mlt::Producer *producer) { @@ -81,7 +73,7 @@ void SubtitlesModel::load(Mlt::Producer *producer) continue; } if (!::qstrcmp(filter->get("mlt_service"), "subtitle_feed") - && filter->property_exists("text")) { + && filter->property_exists("text")) { SubtitleTrack track; track.name = QString::fromUtf8(filter->get("feed")); track.lang = QString::fromUtf8(filter->get("lang")); @@ -105,7 +97,7 @@ int64_t SubtitlesModel::maxTime() const { int64_t maxTime = 0; if (m_producer && m_producer->is_valid()) { - maxTime = std::floor((double)m_producer->get_playtime() * 1000.0 / m_producer->get_fps()); + maxTime = std::floor((double) m_producer->get_playtime() * 1000.0 / m_producer->get_fps()); } return maxTime; } @@ -182,7 +174,8 @@ void SubtitlesModel::commitToFeed(int trackIndex) } if (filter->get("mlt_service") == QStringLiteral("subtitle_feed")) { if (feedFilterIndex == trackIndex) { - Subtitles::SubtitleVector items(m_items[trackIndex].constBegin(), m_items[trackIndex].constEnd()); + Subtitles::SubtitleVector items(m_items[trackIndex].constBegin(), + m_items[trackIndex].constEnd()); std::string text; Subtitles::writeToSrtString(text, items); filter->set("text", text.c_str()); @@ -200,7 +193,8 @@ void SubtitlesModel::addTrack(SubtitlesModel::SubtitleTrack &track) LOG_DEBUG() << "No producer"; return; } - Subtitles::InsertTrackCommand *command = new Subtitles::InsertTrackCommand(*this, track, + Subtitles::InsertTrackCommand *command = new Subtitles::InsertTrackCommand(*this, + track, m_tracks.size()); MAIN.undoStack()->push(command); } @@ -280,7 +274,7 @@ int SubtitlesModel::itemIndexBeforeTime(int trackIndex, int64_t msTime) const } } if (ret == -1 && m_items[trackIndex].size() > 0 - && m_items[trackIndex][itemCount - 1].end < msTime) { + && m_items[trackIndex][itemCount - 1].end < msTime) { ret = itemCount - 1; } return ret; @@ -304,15 +298,16 @@ const Subtitles::SubtitleItem &SubtitlesModel::getItem(int trackIndex, int itemI return m_items[trackIndex][itemIndex]; } -void SubtitlesModel::importSubtitles(int trackIndex, int64_t msTime, +void SubtitlesModel::importSubtitles(int trackIndex, + int64_t msTime, QList &items) { if (!m_producer) { LOG_DEBUG() << "No producer"; return; } - Subtitles::OverwriteSubtitlesCommand *command = new Subtitles::OverwriteSubtitlesCommand(*this, - trackIndex, items); + Subtitles::OverwriteSubtitlesCommand *command + = new Subtitles::OverwriteSubtitlesCommand(*this, trackIndex, items); command->setText(QObject::tr("Import %1 subtitle items").arg(items.size())); MAIN.undoStack()->push(command); @@ -330,12 +325,13 @@ void SubtitlesModel::importSubtitlesToNewTrack(SubtitlesModel::SubtitleTrack &tr MAIN.undoStack()->beginMacro(QObject::tr("Import %1 subtitle items").arg(items.size())); - Subtitles::InsertTrackCommand *trackCommand = new Subtitles::InsertTrackCommand(*this, track, + Subtitles::InsertTrackCommand *trackCommand = new Subtitles::InsertTrackCommand(*this, + track, trackIndex); MAIN.undoStack()->push(trackCommand); - Subtitles::OverwriteSubtitlesCommand *overwriteCommand = new Subtitles::OverwriteSubtitlesCommand( - *this, trackIndex, items); + Subtitles::OverwriteSubtitlesCommand *overwriteCommand + = new Subtitles::OverwriteSubtitlesCommand(*this, trackIndex, items); MAIN.undoStack()->push(overwriteCommand); MAIN.undoStack()->endMacro(); @@ -347,7 +343,8 @@ void SubtitlesModel::exportSubtitles(const QString &filePath, int trackIndex) co LOG_DEBUG() << "No producer"; return; } - Subtitles::SubtitleVector items(m_items[trackIndex].constBegin(), m_items[trackIndex].constEnd()); + Subtitles::SubtitleVector items(m_items[trackIndex].constBegin(), + m_items[trackIndex].constEnd()); Subtitles::writeToSrtFile(filePath.toUtf8().toStdString(), items); } @@ -355,8 +352,8 @@ void SubtitlesModel::overwriteItem(int trackIndex, const Subtitles::SubtitleItem { QList items; items.append(item); - Subtitles::OverwriteSubtitlesCommand *command = new Subtitles::OverwriteSubtitlesCommand(*this, - trackIndex, items); + Subtitles::OverwriteSubtitlesCommand *command + = new Subtitles::OverwriteSubtitlesCommand(*this, trackIndex, items); MAIN.undoStack()->push(command); } @@ -364,8 +361,8 @@ void SubtitlesModel::appendItem(int trackIndex, const Subtitles::SubtitleItem &i { QList items; items.append(item); - Subtitles::OverwriteSubtitlesCommand *command = new Subtitles::OverwriteSubtitlesCommand(*this, - trackIndex, items); + Subtitles::OverwriteSubtitlesCommand *command + = new Subtitles::OverwriteSubtitlesCommand(*this, trackIndex, items); command->setText(QObject::tr("Append subtitle")); MAIN.undoStack()->push(command); } @@ -373,7 +370,8 @@ void SubtitlesModel::appendItem(int trackIndex, const Subtitles::SubtitleItem &i void SubtitlesModel::removeItems(int trackIndex, int firstItemIndex, int lastItemIndex) { int count = m_items[trackIndex].size(); - if (firstItemIndex < 0 || firstItemIndex >= count || lastItemIndex < 0 || lastItemIndex >= count) { + if (firstItemIndex < 0 || firstItemIndex >= count || lastItemIndex < 0 + || lastItemIndex >= count) { LOG_ERROR() << "Invalid index to remove" << firstItemIndex << lastItemIndex; } QList items; @@ -381,7 +379,8 @@ void SubtitlesModel::removeItems(int trackIndex, int firstItemIndex, int lastIte items.append(m_items[trackIndex][i]); } Subtitles::RemoveSubtitlesCommand *command = new Subtitles::RemoveSubtitlesCommand(*this, - trackIndex, items); + trackIndex, + items); MAIN.undoStack()->push(command); } @@ -396,16 +395,17 @@ void SubtitlesModel::setItemStart(int trackIndex, int itemIndex, int64_t msTime) return; } if (msTime >= m_items[trackIndex][itemIndex].end) { - LOG_ERROR() << "Start can not be greater than end" << msTime << m_items[trackIndex][itemIndex].end; + LOG_ERROR() << "Start can not be greater than end" << msTime + << m_items[trackIndex][itemIndex].end; return; } if (itemIndex > 0 && msTime < m_items[trackIndex][itemIndex - 1].end) { - LOG_ERROR() << "Start can not precede previous end" << msTime << m_items[trackIndex][itemIndex - - 1].end; + LOG_ERROR() << "Start can not precede previous end" << msTime + << m_items[trackIndex][itemIndex - 1].end; return; } - Subtitles::SetStartCommand *command = new Subtitles::SetStartCommand(*this, trackIndex, itemIndex, - msTime); + Subtitles::SetStartCommand *command + = new Subtitles::SetStartCommand(*this, trackIndex, itemIndex, msTime); MAIN.undoStack()->push(command); } @@ -420,40 +420,41 @@ void SubtitlesModel::setItemEnd(int trackIndex, int itemIndex, int64_t msTime) return; } if (msTime <= m_items[trackIndex][itemIndex].start) { - LOG_ERROR() << "End can not be less than start" << msTime << m_items[trackIndex][itemIndex].start; + LOG_ERROR() << "End can not be less than start" << msTime + << m_items[trackIndex][itemIndex].start; return; } if (itemIndex < (m_items[trackIndex].size() - 1) - && msTime > m_items[trackIndex][itemIndex + 1].start) { - LOG_ERROR() << "End can not be greater than next start" << msTime << m_items[trackIndex][itemIndex + - 1].start; + && msTime > m_items[trackIndex][itemIndex + 1].start) { + LOG_ERROR() << "End can not be greater than next start" << msTime + << m_items[trackIndex][itemIndex + 1].start; return; } - Subtitles::SetEndCommand *command = new Subtitles::SetEndCommand(*this, trackIndex, itemIndex, - msTime); + Subtitles::SetEndCommand *command + = new Subtitles::SetEndCommand(*this, trackIndex, itemIndex, msTime); MAIN.undoStack()->push(command); } void SubtitlesModel::setText(int trackIndex, int itemIndex, const QString &text) { - Subtitles::SetTextCommand *command = new Subtitles::SetTextCommand(*this, trackIndex, itemIndex, - text); + Subtitles::SetTextCommand *command + = new Subtitles::SetTextCommand(*this, trackIndex, itemIndex, text); MAIN.undoStack()->push(command); } -void SubtitlesModel::moveItems(int trackIndex, int firstItemIndex, int lastItemIndex, - int64_t msTime) +void SubtitlesModel::moveItems(int trackIndex, int firstItemIndex, int lastItemIndex, int64_t msTime) { int count = m_items[trackIndex].size(); - if (firstItemIndex < 0 || firstItemIndex >= count || lastItemIndex < 0 || lastItemIndex >= count) { + if (firstItemIndex < 0 || firstItemIndex >= count || lastItemIndex < 0 + || lastItemIndex >= count) { LOG_ERROR() << "Invalid index to move" << firstItemIndex << lastItemIndex; } QList items; for (int i = firstItemIndex; i <= lastItemIndex; i++) { items.append(m_items[trackIndex][i]); } - Subtitles::MoveSubtitlesCommand *command = new Subtitles::MoveSubtitlesCommand(*this, trackIndex, - items, msTime); + Subtitles::MoveSubtitlesCommand *command + = new Subtitles::MoveSubtitlesCommand(*this, trackIndex, items, msTime); MAIN.undoStack()->push(command); } @@ -475,7 +476,7 @@ bool SubtitlesModel::validateMove(const QModelIndexList &items, int64_t msTime) int64_t newEndTime = msTime + duration; int itemCount = m_items[trackIndex].size(); int gapItemIndex = itemIndexAtTime(trackIndex, msTime); - if (gapItemIndex == - 1) { + if (gapItemIndex == -1) { gapItemIndex = itemIndexAfterTime(trackIndex, msTime); } if (gapItemIndex >= 0) { @@ -484,9 +485,9 @@ bool SubtitlesModel::validateMove(const QModelIndexList &items, int64_t msTime) auto gapItem = m_items[trackIndex][gapItemIndex]; if (gapItem.start >= newEndTime) { break; - } else if ((msTime >= gapItem.start && msTime < gapItem.end) || - (newEndTime > gapItem.start && newEndTime <= gapItem.end) || - (gapItem.start <= msTime && gapItem.end >= newEndTime)) { + } else if ((msTime >= gapItem.start && msTime < gapItem.end) + || (newEndTime > gapItem.start && newEndTime <= gapItem.end) + || (gapItem.start <= msTime && gapItem.end >= newEndTime)) { return false; } } @@ -669,7 +670,8 @@ void SubtitlesModel::doSetText(int trackIndex, int itemIndex, const QString &tex m_items[trackIndex][itemIndex].text = text.toStdString(); requestFeedCommit(trackIndex); QModelIndex parent = index(trackIndex); - emit dataChanged(index(itemIndex, COLUMN_TEXT, parent), index(itemIndex, COLUMN_TEXT, parent)); + emit dataChanged(index(itemIndex, COLUMN_TEXT, parent), + index(itemIndex, COLUMN_TEXT, parent)); } else { LOG_ERROR() << "Invalid index" << itemIndex; } @@ -686,7 +688,8 @@ void SubtitlesModel::doSetTime(int trackIndex, int itemIndex, int64_t startTime, m_items[trackIndex][itemIndex].end = endTime; requestFeedCommit(trackIndex); QModelIndex parent = index(trackIndex); - emit dataChanged(index(itemIndex, COLUMN_START, parent), index(itemIndex, COLUMN_DURATION, parent)); + emit dataChanged(index(itemIndex, COLUMN_START, parent), + index(itemIndex, COLUMN_DURATION, parent)); } else { LOG_ERROR() << "Invalid index" << itemIndex; } @@ -743,7 +746,7 @@ QVariant SubtitlesModel::data(const QModelIndex &index, int role) const // Subtitle item if (!index.isValid() || index.column() < 0 || index.column() >= COLUMN_COUNT || index.row() < 0 - || index.row() >= itemCount(index.parent().row())) { + || index.row() >= itemCount(index.parent().row())) { LOG_ERROR() << "Invalid Index: " << index.row() << index.column() << role; return result; } @@ -780,22 +783,22 @@ QVariant SubtitlesModel::data(const QModelIndex &index, int role) const result = QString::fromStdString(item.text); break; case StartRole: - result = (qlonglong)item.start; + result = (qlonglong) item.start; break; case EndRole: - result = (qlonglong)item.end; + result = (qlonglong) item.end; break; case DurationRole: - result = (qlonglong)(item.end - item.start); + result = (qlonglong) (item.end - item.start); break; case SimpleText: result = QString::fromStdString(item.text).replace('\n', ' '); break; case StartFrameRole: - result = (int)std::round(item.start * MLT.profile().fps() / 1000); + result = (int) std::round(item.start * MLT.profile().fps() / 1000); break; case EndFrameRole: - result = (int)std::round(item.end * MLT.profile().fps() / 1000); + result = (int) std::round(item.end * MLT.profile().fps() / 1000); break; case SiblingCountRole: result = m_items[index.parent().row()].size(); @@ -850,13 +853,13 @@ QModelIndex SubtitlesModel::parent(const QModelIndex &index) const QHash SubtitlesModel::roleNames() const { QHash roles = QAbstractItemModel::roleNames(); - roles[TextRole] = "text"; - roles[StartRole] = "start"; - roles[EndRole] = "end"; - roles[DurationRole] = "duration"; - roles[SimpleText] = "simpleText"; - roles[StartFrameRole] = "startFrame"; - roles[EndFrameRole] = "endFrame"; + roles[TextRole] = "text"; + roles[StartRole] = "start"; + roles[EndRole] = "end"; + roles[DurationRole] = "duration"; + roles[SimpleText] = "simpleText"; + roles[StartFrameRole] = "startFrame"; + roles[EndFrameRole] = "endFrame"; roles[SiblingCountRole] = "siblingCount"; return roles; } diff --git a/src/models/subtitlesmodel.h b/src/models/subtitlesmodel.h index 865707757c..1426e714cd 100644 --- a/src/models/subtitlesmodel.h +++ b/src/models/subtitlesmodel.h @@ -18,13 +18,12 @@ #ifndef SUBTITLESMODEL_H #define SUBTITLESMODEL_H -#include - #include "models/subtitles.h" +#include #include -#include #include +#include #include @@ -34,7 +33,6 @@ class SubtitlesModel : public QAbstractItemModel Q_PROPERTY(int trackCount READ trackCount NOTIFY tracksChanged) public: - enum Roles { TextRole = Qt::UserRole + 1, StartRole, @@ -46,7 +44,8 @@ class SubtitlesModel : public QAbstractItemModel SiblingCountRole, }; - struct SubtitleTrack { + struct SubtitleTrack + { QString name; QString lang; }; @@ -87,7 +86,10 @@ class SubtitlesModel : public QAbstractItemModel void setItemStart(int trackIndex, int itemIndex, int64_t msTime); void setItemEnd(int trackIndex, int itemIndex, int64_t msTime); void setText(int trackIndex, int itemIndex, const QString &text); - Q_INVOKABLE void moveItems(int trackIndex, int firstItemIndex, int lastItemIndex, int64_t msTime); + Q_INVOKABLE void moveItems(int trackIndex, + int firstItemIndex, + int lastItemIndex, + int64_t msTime); Q_INVOKABLE bool validateMove(const QModelIndexList &items, int64_t msTime); // Only to be called by subtitle commands diff --git a/src/models/subtitlesselectionmodel.cpp b/src/models/subtitlesselectionmodel.cpp index d39b127cec..922205b9c2 100644 --- a/src/models/subtitlesselectionmodel.cpp +++ b/src/models/subtitlesselectionmodel.cpp @@ -23,18 +23,20 @@ SubtitlesSelectionModel::SubtitlesSelectionModel(QAbstractItemModel *model) : QItemSelectionModel(model) , m_selectedTrackIndex(-1) { - connect(this, &QItemSelectionModel::selectionChanged, this, [&](const QItemSelection & selected, - const QItemSelection & deselected) { - QVariantList result; - foreach (auto modelIndex, selectedRows()) { - result << modelIndex.row(); - } - m_selectedItems = result; - if (selectedRows().size() == 1) { - m_lastSingleSelection = selectedRows()[0].row(); - } - emit selectedItemsChanged(); - }); + connect(this, + &QItemSelectionModel::selectionChanged, + this, + [&](const QItemSelection &selected, const QItemSelection &deselected) { + QVariantList result; + foreach (auto modelIndex, selectedRows()) { + result << modelIndex.row(); + } + m_selectedItems = result; + if (selectedRows().size() == 1) { + m_lastSingleSelection = selectedRows()[0].row(); + } + emit selectedItemsChanged(); + }); } QModelIndex SubtitlesSelectionModel::selectedTrackModelIndex() @@ -95,14 +97,16 @@ void SubtitlesSelectionModel::selectRange(int itemIndex) } qDebug() << m_lastSingleSelection << itemIndex; if (m_lastSingleSelection == -1) { - select(itemModelIndex, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::SelectCurrent | - QItemSelectionModel::Rows); + select(itemModelIndex, + QItemSelectionModel::ClearAndSelect | QItemSelectionModel::SelectCurrent + | QItemSelectionModel::Rows); } else { QModelIndex firstItemModelIndex = smodel->itemModelIndex(m_selectedTrackIndex, m_lastSingleSelection); QItemSelection newSelection(firstItemModelIndex, itemModelIndex); - select(newSelection, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::SelectCurrent | - QItemSelectionModel::Rows); + select(newSelection, + QItemSelectionModel::ClearAndSelect | QItemSelectionModel::SelectCurrent + | QItemSelectionModel::Rows); } setCurrentIndex(itemModelIndex, QItemSelectionModel::NoUpdate); } diff --git a/src/models/subtitlesselectionmodel.h b/src/models/subtitlesselectionmodel.h index 8908480dee..c7f9628a52 100644 --- a/src/models/subtitlesselectionmodel.h +++ b/src/models/subtitlesselectionmodel.h @@ -24,7 +24,7 @@ class SubtitlesSelectionModel : public QItemSelectionModel { Q_OBJECT Q_PROPERTY(QModelIndex selectedTrackModelIndex READ selectedTrackModelIndex NOTIFY - selectedTrackModelIndexChanged) + selectedTrackModelIndexChanged) Q_PROPERTY(QVariantList selectedItems READ selectedItems NOTIFY selectedItemsChanged) public: explicit SubtitlesSelectionModel(QAbstractItemModel *model); diff --git a/src/openotherdialog.cpp b/src/openotherdialog.cpp index f609419c18..0b8cc4f1c0 100644 --- a/src/openotherdialog.cpp +++ b/src/openotherdialog.cpp @@ -17,20 +17,21 @@ #include "openotherdialog.h" #include "ui_openotherdialog.h" + #include "mltcontroller.h" + #include #include -OpenOtherDialog::OpenOtherDialog(QWidget *parent) : - QDialog(parent), - ui(new Ui::OpenOtherDialog) +OpenOtherDialog::OpenOtherDialog(QWidget *parent) + : QDialog(parent) + , ui(new Ui::OpenOtherDialog) { ui->setupUi(this); m_current = ui->networkWidget; - m_addTimelineButton = ui->buttonBox->addButton(tr("Add To Timeline"), QDialogButtonBox::ApplyRole); - connect(m_addTimelineButton, &QPushButton::clicked, this, [ = ]() { - done(-1); - }); + m_addTimelineButton = ui->buttonBox->addButton(tr("Add To Timeline"), + QDialogButtonBox::ApplyRole); + connect(m_addTimelineButton, &QPushButton::clicked, this, [=]() { done(-1); }); QScopedPointer mltProducers(MLT.repository()->producers()); QScopedPointer mltFilters(MLT.repository()->filters()); diff --git a/src/openotherdialog.h b/src/openotherdialog.h index 8e6079b0ea..7fae0d6e2c 100644 --- a/src/openotherdialog.h +++ b/src/openotherdialog.h @@ -28,7 +28,7 @@ namespace Mlt { class Properties; class Producer; class Profile; -} +} // namespace Mlt class QPushButton; class OpenOtherDialog : public QDialog @@ -41,10 +41,7 @@ class OpenOtherDialog : public QDialog Mlt::Producer *newProducer(Mlt::Profile &) const; void load(Mlt::Producer *); - QWidget *currentWidget() const - { - return m_current; - } + QWidget *currentWidget() const { return m_current; } private slots: void on_treeWidget_currentItemChanged(QTreeWidgetItem *current, QTreeWidgetItem *previous); diff --git a/src/player.cpp b/src/player.cpp index 43f95b1080..30006b8a98 100644 --- a/src/player.cpp +++ b/src/player.cpp @@ -17,20 +17,21 @@ #include "player.h" +#include "Logger.h" #include "actions.h" -#include "scrubbar.h" -#include "mainwindow.h" #include "dialogs/durationdialog.h" -#include "widgets/statuslabelwidget.h" -#include "widgets/timespinbox.h" -#include "widgets/audioscale.h" -#include "settings.h" -#include "widgets/newprojectfolder.h" +#include "mainwindow.h" #include "proxymanager.h" +#include "scrubbar.h" +#include "settings.h" +#include "widgets/audioscale.h" #include "widgets/docktoolbar.h" -#include +#include "widgets/newprojectfolder.h" +#include "widgets/statuslabelwidget.h" +#include "widgets/timespinbox.h" #include + #include #define VOLUME_KNEE (88) @@ -39,10 +40,7 @@ class NoWheelTabBar : public QTabBar { - void wheelEvent(QWheelEvent *event) - { - event->ignore(); - }; + void wheelEvent(QWheelEvent *event) { event->ignore(); }; }; QString blankTime() @@ -138,7 +136,8 @@ Player::Player(QWidget *parent) m_volumePopup = new QFrame(this, Qt::Popup); QVBoxLayout *volumeLayoutV = new QVBoxLayout(m_volumePopup); volumeLayoutV->setContentsMargins(0, 0, 0, 0); - volumeLayoutV->addSpacerItem(new QSpacerItem(0, 0, QSizePolicy::Minimum, QSizePolicy::Expanding)); + volumeLayoutV->addSpacerItem( + new QSpacerItem(0, 0, QSizePolicy::Minimum, QSizePolicy::Expanding)); QBoxLayout *volumeLayoutH = new QHBoxLayout; volumeLayoutH->setSpacing(0); volumeLayoutH->setContentsMargins(0, 0, 0, 0); @@ -172,8 +171,9 @@ Player::Player(QWidget *parent) m_muteButton = new QPushButton(this); m_muteButton->setFocusPolicy(Qt::NoFocus); m_muteButton->setObjectName(QString::fromUtf8("muteButton")); - m_muteButton->setIcon(QIcon::fromTheme("audio-volume-muted", - QIcon(":/icons/oxygen/32x32/status/audio-volume-muted.png"))); + m_muteButton->setIcon( + QIcon::fromTheme("audio-volume-muted", + QIcon(":/icons/oxygen/32x32/status/audio-volume-muted.png"))); m_muteButton->setToolTip(tr("Silence the audio")); m_muteButton->setCheckable(true); m_muteButton->setChecked(Settings.playerMuted()); @@ -236,39 +236,74 @@ Player::Player(QWidget *parent) // Zoom button m_zoomButton = new QToolButton; m_zoomMenu = new QMenu(this); - m_zoomMenu->addAction( - QIcon::fromTheme("zoom-fit-best", QIcon(":/icons/oxygen/32x32/actions/zoom-fit-best")), - tr("Zoom Fit"), this, SLOT(onZoomTriggered()))->setData(0.0f); - m_zoomMenu->addAction( - QIcon::fromTheme("zoom-out", QIcon(":/icons/oxygen/32x32/actions/zoom-out")), - tr("Zoom 10%"), this, SLOT(onZoomTriggered()))->setData(0.1f); - m_zoomMenu->addAction( - QIcon::fromTheme("zoom-out", QIcon(":/icons/oxygen/32x32/actions/zoom-out")), - tr("Zoom 25%"), this, SLOT(onZoomTriggered()))->setData(0.25f); - m_zoomMenu->addAction( - QIcon::fromTheme("zoom-out", QIcon(":/icons/oxygen/32x32/actions/zoom-out")), - tr("Zoom 50%"), this, SLOT(onZoomTriggered()))->setData(0.5f); - m_zoomMenu->addAction( - QIcon::fromTheme("zoom-original", QIcon(":/icons/oxygen/32x32/actions/zoom-original")), - tr("Zoom 100%"), this, SLOT(onZoomTriggered()))->setData(1.0f); - m_zoomMenu->addAction( - QIcon::fromTheme("zoom-in", QIcon(":/icons/oxygen/32x32/actions/zoom-in")), - tr("Zoom 200%"), this, SLOT(onZoomTriggered()))->setData(2.0f); - m_zoomMenu->addAction( - QIcon::fromTheme("zoom-in", QIcon(":/icons/oxygen/32x32/actions/zoom-in")), - tr("Zoom 300%"), this, SLOT(onZoomTriggered()))->setData(3.0f); - m_zoomMenu->addAction( - QIcon::fromTheme("zoom-in", QIcon(":/icons/oxygen/32x32/actions/zoom-in")), - tr("Zoom 400%"), this, SLOT(onZoomTriggered()))->setData(4.0f); - m_zoomMenu->addAction( - QIcon::fromTheme("zoom-in", QIcon(":/icons/oxygen/32x32/actions/zoom-in")), - tr("Zoom 500%"), this, SLOT(onZoomTriggered()))->setData(5.0f); - m_zoomMenu->addAction( - QIcon::fromTheme("zoom-in", QIcon(":/icons/oxygen/32x32/actions/zoom-in")), - tr("Zoom 750%"), this, SLOT(onZoomTriggered()))->setData(7.5f); - m_zoomMenu->addAction( - QIcon::fromTheme("zoom-in", QIcon(":/icons/oxygen/32x32/actions/zoom-in")), - tr("Zoom 1000%"), this, SLOT(onZoomTriggered()))->setData(10.0f); + m_zoomMenu + ->addAction(QIcon::fromTheme("zoom-fit-best", + QIcon(":/icons/oxygen/32x32/actions/zoom-fit-best")), + tr("Zoom Fit"), + this, + SLOT(onZoomTriggered())) + ->setData(0.0f); + m_zoomMenu + ->addAction(QIcon::fromTheme("zoom-out", QIcon(":/icons/oxygen/32x32/actions/zoom-out")), + tr("Zoom 10%"), + this, + SLOT(onZoomTriggered())) + ->setData(0.1f); + m_zoomMenu + ->addAction(QIcon::fromTheme("zoom-out", QIcon(":/icons/oxygen/32x32/actions/zoom-out")), + tr("Zoom 25%"), + this, + SLOT(onZoomTriggered())) + ->setData(0.25f); + m_zoomMenu + ->addAction(QIcon::fromTheme("zoom-out", QIcon(":/icons/oxygen/32x32/actions/zoom-out")), + tr("Zoom 50%"), + this, + SLOT(onZoomTriggered())) + ->setData(0.5f); + m_zoomMenu + ->addAction(QIcon::fromTheme("zoom-original", + QIcon(":/icons/oxygen/32x32/actions/zoom-original")), + tr("Zoom 100%"), + this, + SLOT(onZoomTriggered())) + ->setData(1.0f); + m_zoomMenu + ->addAction(QIcon::fromTheme("zoom-in", QIcon(":/icons/oxygen/32x32/actions/zoom-in")), + tr("Zoom 200%"), + this, + SLOT(onZoomTriggered())) + ->setData(2.0f); + m_zoomMenu + ->addAction(QIcon::fromTheme("zoom-in", QIcon(":/icons/oxygen/32x32/actions/zoom-in")), + tr("Zoom 300%"), + this, + SLOT(onZoomTriggered())) + ->setData(3.0f); + m_zoomMenu + ->addAction(QIcon::fromTheme("zoom-in", QIcon(":/icons/oxygen/32x32/actions/zoom-in")), + tr("Zoom 400%"), + this, + SLOT(onZoomTriggered())) + ->setData(4.0f); + m_zoomMenu + ->addAction(QIcon::fromTheme("zoom-in", QIcon(":/icons/oxygen/32x32/actions/zoom-in")), + tr("Zoom 500%"), + this, + SLOT(onZoomTriggered())) + ->setData(5.0f); + m_zoomMenu + ->addAction(QIcon::fromTheme("zoom-in", QIcon(":/icons/oxygen/32x32/actions/zoom-in")), + tr("Zoom 750%"), + this, + SLOT(onZoomTriggered())) + ->setData(7.5f); + m_zoomMenu + ->addAction(QIcon::fromTheme("zoom-in", QIcon(":/icons/oxygen/32x32/actions/zoom-in")), + tr("Zoom 1000%"), + this, + SLOT(onZoomTriggered())) + ->setData(10.0f); connect(m_zoomButton, SIGNAL(toggled(bool)), SLOT(toggleZoom(bool))); m_zoomButton->setMenu(m_zoomMenu); m_zoomButton->setPopupMode(QToolButton::MenuButtonPopup); @@ -320,8 +355,8 @@ Player::Player(QWidget *parent) connect(action, SIGNAL(toggled(bool)), MLT.videoWidget(), SLOT(setSnapToGrid(bool))); connect(m_gridButton, SIGNAL(toggled(bool)), SLOT(toggleGrid(bool))); m_gridButton->setMenu(gridMenu); - m_gridButton->setIcon(QIcon::fromTheme("view-grid", - QIcon(":/icons/oxygen/32x32/actions/view-grid"))); + m_gridButton->setIcon( + QIcon::fromTheme("view-grid", QIcon(":/icons/oxygen/32x32/actions/view-grid"))); m_gridButton->setPopupMode(QToolButton::MenuButtonPopup); m_gridButton->setCheckable(true); m_gridButton->setToolTip(tr("Toggle grid display on the player")); @@ -329,8 +364,8 @@ Player::Player(QWidget *parent) // Add volume control to toolbar. m_volumeButton = new QToolButton; m_volumeButton->setObjectName(QString::fromUtf8("volumeButton")); - m_volumeButton->setIcon(QIcon::fromTheme("player-volume", - QIcon(":/icons/oxygen/32x32/actions/player-volume.png"))); + m_volumeButton->setIcon( + QIcon::fromTheme("player-volume", QIcon(":/icons/oxygen/32x32/actions/player-volume.png"))); m_volumeButton->setText(tr("Volume")); m_volumeButton->setToolTip(tr("Show the volume control")); connect(m_volumeButton, SIGNAL(clicked()), this, SLOT(onVolumeTriggered())); @@ -367,7 +402,9 @@ Player::Player(QWidget *parent) onMuteButtonToggled(Settings.playerMuted()); - connect(MLT.videoWidget(), SIGNAL(frameDisplayed(const SharedFrame &)), this, + connect(MLT.videoWidget(), + SIGNAL(frameDisplayed(const SharedFrame &)), + this, SLOT(onFrameDisplayed(const SharedFrame &))); connect(m_scrubber, SIGNAL(seeked(int)), this, SLOT(seek(int))); connect(m_scrubber, SIGNAL(paused(int)), this, SLOT(pause(int))); @@ -379,7 +416,8 @@ Player::Player(QWidget *parent) connect(this, SIGNAL(zoomChanged(float)), MLT.videoWidget(), SLOT(setZoom(float))); connect(m_horizontalScroll, SIGNAL(valueChanged(int)), MLT.videoWidget(), SLOT(setOffsetX(int))); connect(m_verticalScroll, SIGNAL(valueChanged(int)), MLT.videoWidget(), SLOT(setOffsetY(int))); - connect(MLT.videoWidget(), SIGNAL(offsetChanged(const QPoint &)), + connect(MLT.videoWidget(), + SIGNAL(offsetChanged(const QPoint &)), SLOT(onOffsetChanged(const QPoint &))); connect(&Settings, &ShotcutSettings::timeFormatChanged, this, [&]() { @@ -394,7 +432,8 @@ Player::Player(QWidget *parent) void Player::connectTransport(const TransportControllable *receiver) { - if (receiver == m_currentTransport) return; + if (receiver == m_currentTransport) + return; if (m_currentTransport) disconnect(m_currentTransport); m_currentTransport = receiver; @@ -437,13 +476,12 @@ void Player::setupActions() action = new QAction(tr("Loop"), this); action->setShortcut(QKeySequence(Qt::Key_Backslash)); - action->setIcon(QIcon::fromTheme("media-playback-loop", - QIcon(":/icons/oxygen/32x32/actions/media-playback-loop.png"))); + action->setIcon( + QIcon::fromTheme("media-playback-loop", + QIcon(":/icons/oxygen/32x32/actions/media-playback-loop.png"))); action->setCheckable(true); action->setToolTip(tr("Toggle player looping")); - connect(action, &QAction::toggled, this, [&]() { - setLoopRange(m_loopStart, m_loopEnd); - }); + connect(action, &QAction::toggled, this, [&]() { setLoopRange(m_loopStart, m_loopEnd); }); Actions.add("playerLoopAction", action); action = new QAction(tr("Loop All"), this); @@ -574,9 +612,7 @@ void Player::setupActions() action = new QAction(tr("Seek Start"), this); action->setShortcut(QKeySequence(Qt::Key_Home)); - connect(action, &QAction::triggered, this, [&]() { - seek(0); - }); + connect(action, &QAction::triggered, this, [&]() { seek(0); }); Actions.add("playerSeekStartAction", action); action = new QAction(tr("Seek End"), this); @@ -697,7 +733,7 @@ void Player::setupActions() DurationDialog dialog(this); dialog.setDuration(qRound(MLT.profile().fps() * Settings.playerJumpSeconds())); if (dialog.exec() == QDialog::Accepted) { - Settings.setPlayerJumpSeconds((double)dialog.duration() / MLT.profile().fps()); + Settings.setPlayerJumpSeconds((double) dialog.duration() / MLT.profile().fps()); } }); Actions.add("playerSetJumpAction", action); @@ -764,9 +800,7 @@ void Player::setupActions() action = new QAction(tr("Focus Player"), this); action->setProperty(Actions.hardKeyProperty, "Shift+Esc"); - connect(action, &QAction::triggered, this, [&]() { - setFocus(); - }); + connect(action, &QAction::triggered, this, [&]() { setFocus(); }); Actions.add("playerFocus", action, tr("Player")); } @@ -944,7 +978,7 @@ void Player::onProducerOpened(bool play) if (play || (MLT.isClip() && !MLT.isClosedClip())) { if (m_pauseAfterOpen) { m_pauseAfterOpen = false; - QTimer::singleShot(500, this, [ = ]() { + QTimer::singleShot(500, this, [=]() { if (MLT.producer()) pause(MLT.producer()->position()); }); @@ -1020,8 +1054,8 @@ void Player::updateSelection() { if (MLT.producer() && MLT.producer()->get_in() > 0) { m_inPointLabel->setText(QString(MLT.producer()->get_time("in", Settings.timeFormat()))); - m_selectedLabel->setText(MLT.producer()->frames_to_time(MLT.producer()->get_playtime(), - Settings.timeFormat())); + m_selectedLabel->setText( + MLT.producer()->frames_to_time(MLT.producer()->get_playtime(), Settings.timeFormat())); } else { m_inPointLabel->setText(blankTime()); if (MLT.isClip() && MLT.producer()->get_out() < m_duration - 1) { @@ -1102,7 +1136,7 @@ void Player::onTabBarClicked(int index) switch (index) { case SourceTabIndex: if (MLT.savedProducer() && MLT.savedProducer()->is_valid() && MLT.producer() - && MLT.producer()->get_producer() != MLT.savedProducer()->get_producer()) { + && MLT.producer()->get_producer() != MLT.savedProducer()->get_producer()) { m_pauseAfterOpen = true; MAIN.open(new Mlt::Producer(MLT.savedProducer())); } @@ -1119,7 +1153,9 @@ void Player::onTabBarClicked(int index) } } -void Player::setStatusLabel(const QString &text, int timeoutSeconds, QAction *action, +void Player::setStatusLabel(const QString &text, + int timeoutSeconds, + QAction *action, QPalette::ColorRole role) { m_statusLabel->setWidth(m_scrubber->width() - m_tabs->width()); @@ -1190,9 +1226,9 @@ void Player::setLoopRange(int start, int end) void Player::layoutToolbars() { - int totalWidth = m_currentDurationToolBar->sizeHint().width() + - m_controlsToolBar->sizeHint().width() + m_optionsToolBar->sizeHint().width() + - m_inSelectedToolBar->sizeHint().width() + 20; + int totalWidth = m_currentDurationToolBar->sizeHint().width() + + m_controlsToolBar->sizeHint().width() + m_optionsToolBar->sizeHint().width() + + m_inSelectedToolBar->sizeHint().width() + 20; bool twoRowsInUse = m_toolRow2->count() > 0; if (m_toolRow1->count() > 0) { @@ -1261,13 +1297,19 @@ void Player::layoutToolbars() void Player::showIdleStatus() { if (Settings.proxyEnabled() && Settings.playerPreviewScale() > 0) { - setStatusLabel(tr("Proxy and preview scaling are ON at %1p").arg(ProxyManager::resolution()), -1, - nullptr, QPalette::AlternateBase); + setStatusLabel(tr("Proxy and preview scaling are ON at %1p").arg(ProxyManager::resolution()), + -1, + nullptr, + QPalette::AlternateBase); } else if (Settings.proxyEnabled()) { - setStatusLabel(tr("Proxy is ON at %1p").arg(ProxyManager::resolution()), -1, nullptr, + setStatusLabel(tr("Proxy is ON at %1p").arg(ProxyManager::resolution()), + -1, + nullptr, QPalette::AlternateBase); } else if (Settings.playerPreviewScale() > 0) { - setStatusLabel(tr("Preview scaling is ON at %1p").arg(Settings.playerPreviewScale()), -1, nullptr, + setStatusLabel(tr("Preview scaling is ON at %1p").arg(Settings.playerPreviewScale()), + -1, + nullptr, QPalette::AlternateBase); } else { setStatusLabel("", -1, nullptr); @@ -1281,10 +1323,12 @@ void Player::focusPositionSpinner() const void Player::moveVideoToScreen(int screen) { - if (screen == m_monitorScreen) return; + if (screen == m_monitorScreen) + return; if (screen == -2) { // -2 = embedded - if (!m_videoScrollWidget->isFullScreen()) return; + if (!m_videoScrollWidget->isFullScreen()) + return; m_videoScrollWidget->showNormal(); m_videoLayout->insertWidget(0, m_videoScrollWidget, 10); } else if (QGuiApplication::screens().size() > 1) { @@ -1315,19 +1359,19 @@ Player::TabIndex Player::tabIndex() const //---------------------------------------------------------------------------- // IEC standard dB scaling -- as borrowed from meterbridge (c) Steve Harris -static inline float IEC_dB ( float fScale ) +static inline float IEC_dB(float fScale) { float dB = 0.0f; - if (fScale < 0.025f) // IEC_Scale(-60.0f) + if (fScale < 0.025f) // IEC_Scale(-60.0f) dB = (fScale / 0.0025f) - 70.0f; - else if (fScale < 0.075f) // IEC_Scale(-50.0f) + else if (fScale < 0.075f) // IEC_Scale(-50.0f) dB = (fScale - 0.025f) / 0.005f - 60.0f; - else if (fScale < 0.15f) // IEC_Scale(-40.0f) + else if (fScale < 0.15f) // IEC_Scale(-40.0f) dB = (fScale - 0.075f) / 0.0075f - 50.0f; - else if (fScale < 0.3f) // IEC_Scale(-30.0f) + else if (fScale < 0.3f) // IEC_Scale(-30.0f) dB = (fScale - 0.15f) / 0.015f - 40.0f; - else if (fScale < 0.5f) // IEC_Scale(-20.0f) + else if (fScale < 0.5f) // IEC_Scale(-20.0f) dB = (fScale - 0.3f) / 0.02f - 30.0f; else /* if (fScale < 1.0f) // IED_Scale(0.0f)) */ dB = (fScale - 0.5f) / 0.025f - 20.0f; @@ -1342,10 +1386,11 @@ void Player::onVolumeChanged(int volume) Settings.setPlayerVolume(volume); Settings.setPlayerMuted(false); m_muteButton->setChecked(false); - m_volumeButton->setIcon(QIcon::fromTheme("player-volume", - QIcon(":/icons/oxygen/32x32/actions/player-volume.png"))); - m_muteButton->setIcon(QIcon::fromTheme("audio-volume-muted", - QIcon(":/icons/oxygen/32x32/status/audio-volume-muted.png"))); + m_volumeButton->setIcon( + QIcon::fromTheme("player-volume", QIcon(":/icons/oxygen/32x32/actions/player-volume.png"))); + m_muteButton->setIcon( + QIcon::fromTheme("audio-volume-muted", + QIcon(":/icons/oxygen/32x32/status/audio-volume-muted.png"))); m_muteButton->setToolTip(tr("Mute")); } @@ -1371,17 +1416,21 @@ void Player::onMuteButtonToggled(bool checked) if (checked) { m_savedVolume = MLT.volume(); MLT.setVolume(0); - m_volumeButton->setIcon(QIcon::fromTheme("audio-volume-muted", - QIcon(":/icons/oxygen/32x32/status/audio-volume-muted.png"))); - m_muteButton->setIcon(QIcon::fromTheme("audio-volume-high", - QIcon(":/icons/oxygen/32x32/status/audio-volume-high.png"))); + m_volumeButton->setIcon( + QIcon::fromTheme("audio-volume-muted", + QIcon(":/icons/oxygen/32x32/status/audio-volume-muted.png"))); + m_muteButton->setIcon( + QIcon::fromTheme("audio-volume-high", + QIcon(":/icons/oxygen/32x32/status/audio-volume-high.png"))); m_muteButton->setToolTip(tr("Unmute")); } else { MLT.setVolume(m_savedVolume); - m_volumeButton->setIcon(QIcon::fromTheme("player-volume", - QIcon(":/icons/oxygen/32x32/actions/player-volume.png"))); - m_muteButton->setIcon(QIcon::fromTheme("audio-volume-muted", - QIcon(":/icons/oxygen/32x32/status/audio-volume-muted.png"))); + m_volumeButton->setIcon( + QIcon::fromTheme("player-volume", + QIcon(":/icons/oxygen/32x32/actions/player-volume.png"))); + m_muteButton->setIcon( + QIcon::fromTheme("audio-volume-muted", + QIcon(":/icons/oxygen/32x32/status/audio-volume-muted.png"))); m_muteButton->setToolTip(tr("Mute")); } Settings.setPlayerMuted(checked); diff --git a/src/player.h b/src/player.h index 7e8f5bf397..2633320af8 100644 --- a/src/player.h +++ b/src/player.h @@ -18,10 +18,11 @@ #ifndef PLAYER_H #define PLAYER_H -#include +#include "sharedframe.h" + #include #include -#include "sharedframe.h" +#include class DockToolBar; class ScrubBar; @@ -48,10 +49,7 @@ class Player : public QWidget { Q_OBJECT public: - typedef enum { - SourceTabIndex = 0, - ProjectTabIndex - } TabIndex; + typedef enum { SourceTabIndex = 0, ProjectTabIndex } TabIndex; explicit Player(QWidget *parent = 0); void connectTransport(const TransportControllable *); @@ -59,14 +57,8 @@ class Player : public QWidget void setOut(int); void setMarkers(const QList &); QSize videoSize() const; - int position() const - { - return m_position; - } - NewProjectFolder *projectWidget() const - { - return m_projectWidget; - } + int position() const { return m_position; } + NewProjectFolder *projectWidget() const { return m_projectWidget; } void moveVideoToScreen(int screen = -1); void setPauseAfterOpen(bool pause); TabIndex tabIndex() const; @@ -113,7 +105,9 @@ public slots: void switchToTab(TabIndex index); void enableTab(TabIndex index, bool enabled = true); void onTabBarClicked(int index); - void setStatusLabel(const QString &text, int timeoutSeconds, QAction *action, + void setStatusLabel(const QString &text, + int timeoutSeconds, + QAction *action, QPalette::ColorRole role = QPalette::ToolTipBase); void showIdleStatus(); void focusPositionSpinner() const; diff --git a/src/proxymanager.cpp b/src/proxymanager.cpp index 15f16d58ba..c5227ef60a 100644 --- a/src/proxymanager.cpp +++ b/src/proxymanager.cpp @@ -16,21 +16,23 @@ */ #include "proxymanager.h" -#include "mltcontroller.h" -#include "settings.h" -#include "shotcut_mlt_properties.h" + +#include "Logger.h" #include "jobqueue.h" #include "jobs/ffmpegjob.h" #include "jobs/qimagejob.h" +#include "mltcontroller.h" +#include "settings.h" +#include "shotcut_mlt_properties.h" #include "util.h" +#include +#include #include #include #include #include -#include -#include -#include + #include static const char *kProxySubfolder = "proxies"; @@ -41,17 +43,18 @@ static const char *kProxyPendingVideoExtension = ".pending.mp4"; static const char *kProxyImageExtension = ".jpg"; static const char *kProxyPendingImageExtension = ".pending.jpg"; static const float kProxyResolutionRatio = 1.3f; -static const int kFallbackProxyResolution = 540; -static const QStringList kPixFmtsWithAlpha = {"pal8", "argb", "rgba", "abgr", - "bgra", "yuva420p", "yuva422p", "yuva444p", "yuva420p9be", "yuva420p9le", - "yuva422p9be", "yuva422p9le", "yuva444p9be", "yuva444p9le", "yuva420p10be", - "yuva420p10le", "yuva422p10be", "yuva422p10le", "yuva444p10be", "yuva444p10le", - "yuva420p16be", "yuva420p16le", "yuva422p16be", "yuva422p16le", "yuva444p16be", - "yuva444p16le", "rgba64be", "rgba64le", "bgra64be", "bgra64le", "ya8", - "ya16le", "ya16be", "gbrap", "gbrap16le", "gbrap16be", "ayuv64le", "ayuv64be", - "gbrap12le", "gbrap12be", "gbrap10le", "gbrap10be", "gbrapf32be", - "gbrapf32le", "yuva422p12be", "yuva422p12le", "yuva444p12be", "yuva444p12le" - }; +static const int kFallbackProxyResolution = 540; +static const QStringList kPixFmtsWithAlpha + = {"pal8", "argb", "rgba", "abgr", "bgra", + "yuva420p", "yuva422p", "yuva444p", "yuva420p9be", "yuva420p9le", + "yuva422p9be", "yuva422p9le", "yuva444p9be", "yuva444p9le", "yuva420p10be", + "yuva420p10le", "yuva422p10be", "yuva422p10le", "yuva444p10be", "yuva444p10le", + "yuva420p16be", "yuva420p16le", "yuva422p16be", "yuva422p16le", "yuva444p16be", + "yuva444p16le", "rgba64be", "rgba64le", "bgra64be", "bgra64le", + "ya8", "ya16le", "ya16be", "gbrap", "gbrap16le", + "gbrap16be", "ayuv64le", "ayuv64be", "gbrap12le", "gbrap12be", + "gbrap10le", "gbrap10be", "gbrapf32be", "gbrapf32le", "yuva422p12be", + "yuva422p12le", "yuva444p12be", "yuva444p12le"}; QDir ProxyManager::dir() { @@ -80,8 +83,11 @@ QString ProxyManager::resource(Mlt::Service &producer) return resource; } -void ProxyManager::generateVideoProxy(Mlt::Producer &producer, bool fullRange, ScanMode scanMode, - const QPoint &aspectRatio, bool replace) +void ProxyManager::generateVideoProxy(Mlt::Producer &producer, + bool fullRange, + ScanMode scanMode, + const QPoint &aspectRatio, + bool replace) { // Always regenerate per preview scaling or 540 if not specified QString resource = ProxyManager::resource(producer); @@ -103,152 +109,251 @@ void ProxyManager::generateVideoProxy(Mlt::Producer &producer, bool fullRange, S file.resize(0); file.close(); - args << "-loglevel" << "verbose"; + args << "-loglevel" + << "verbose"; args << "-noautorotate"; args << "-i" << resource; - args << "-max_muxing_queue_size" << "9999"; + args << "-max_muxing_queue_size" + << "9999"; // transcode all streams except data, subtitles, and attachments - auto audioIndex = producer.property_exists(kDefaultAudioIndexProperty) ? producer.get_int( - kDefaultAudioIndexProperty) : producer.get_int("audio_index"); + auto audioIndex = producer.property_exists(kDefaultAudioIndexProperty) + ? producer.get_int(kDefaultAudioIndexProperty) + : producer.get_int("audio_index"); if (producer.get_int("video_index") < audioIndex) { // iPhone 16 Pro has a 4 channel (spatial) audio stream with codec "apac" that causes failure. // This is not limited to only iPhone 16 Pro, but I think most iPhones only record one usable audio track. if (!::qstrcmp(producer.get("meta.media.1.stream.type"), "audio") - && QString(producer.get("meta.attr.com.apple.quicktime.model.markup")).contains("iPhone")) - args << "-map" << "0:V?" << "-map" << "0:a:0"; + && QString(producer.get("meta.attr.com.apple.quicktime.model.markup")).contains("iPhone")) + args << "-map" + << "0:V?" + << "-map" + << "0:a:0"; else - args << "-map" << "0:V?" << "-map" << "0:a?"; + args << "-map" + << "0:V?" + << "-map" + << "0:a?"; } else { - args << "-map" << "0:a?" << "-map" << "0:V?"; - } - args << "-map_metadata" << "0" << "-ignore_unknown"; + args << "-map" + << "0:a?" + << "-map" + << "0:V?"; + } + args << "-map_metadata" + << "0" + << "-ignore_unknown"; args << "-vf"; if (scanMode == Automatic) { filters = QStringLiteral("yadif=deint=interlaced,"); } else if (scanMode != Progressive) { - filters = QStringLiteral("yadif=parity=%1,").arg(scanMode == InterlacedTopFieldFirst ? "tff" : - "bff"); + filters = QStringLiteral("yadif=parity=%1,") + .arg(scanMode == InterlacedTopFieldFirst ? "tff" : "bff"); } filters += QStringLiteral("scale=width=-2:height=%1").arg(resolution()); - if (Settings.proxyUseHardware() && (hwCodecs.contains("hevc_vaapi") - || hwCodecs.contains("h264_vaapi"))) { + if (Settings.proxyUseHardware() + && (hwCodecs.contains("hevc_vaapi") || hwCodecs.contains("h264_vaapi"))) { hwFilters = ",format=nv12,hwupload"; } if (fullRange) { args << filters + ":in_range=full:out_range=full" + hwFilters; - args << "-color_range" << "jpeg"; + args << "-color_range" + << "jpeg"; } else { args << filters + ":in_range=mpeg:out_range=mpeg" + hwFilters; - args << "-color_range" << "mpeg"; + args << "-color_range" + << "mpeg"; } switch (producer.get_int("meta.media.colorspace")) { case 601: if (producer.get_int("meta.media.height") == 576) { - args << "-color_primaries" << "bt470bg"; - args << "-color_trc" << "smpte170m"; - args << "-colorspace" << "bt470bg"; + args << "-color_primaries" + << "bt470bg"; + args << "-color_trc" + << "smpte170m"; + args << "-colorspace" + << "bt470bg"; } else { - args << "-color_primaries" << "smpte170m"; - args << "-color_trc" << "smpte170m"; - args << "-colorspace" << "smpte170m"; + args << "-color_primaries" + << "smpte170m"; + args << "-color_trc" + << "smpte170m"; + args << "-colorspace" + << "smpte170m"; } break; case 170: - args << "-color_primaries" << "smpte170m"; - args << "-color_trc" << "smpte170m"; - args << "-colorspace" << "smpte170m"; + args << "-color_primaries" + << "smpte170m"; + args << "-color_trc" + << "smpte170m"; + args << "-colorspace" + << "smpte170m"; break; case 240: - args << "-color_primaries" << "smpte240m"; - args << "-color_trc" << "smpte240m"; - args << "-colorspace" << "smpte240m"; + args << "-color_primaries" + << "smpte240m"; + args << "-color_trc" + << "smpte240m"; + args << "-colorspace" + << "smpte240m"; break; case 470: - args << "-color_primaries" << "bt470bg"; - args << "-color_trc" << "bt470bg"; - args << "-colorspace" << "bt470bg"; + args << "-color_primaries" + << "bt470bg"; + args << "-color_trc" + << "bt470bg"; + args << "-colorspace" + << "bt470bg"; break; default: - args << "-color_primaries" << "bt709"; - args << "-color_trc" << "bt709"; - args << "-colorspace" << "bt709"; + args << "-color_primaries" + << "bt709"; + args << "-color_trc" + << "bt709"; + args << "-colorspace" + << "bt709"; break; } if (!aspectRatio.isNull()) { args << "-aspect" << QStringLiteral("%1:%2").arg(aspectRatio.x()).arg(aspectRatio.y()); } - args << "-f" << "mp4" << "-codec:a" << "ac3" << "-b:a" << "256k"; - args << "-pix_fmt" << "yuv420p"; + args << "-f" + << "mp4" + << "-codec:a" + << "ac3" + << "-b:a" + << "256k"; + args << "-pix_fmt" + << "yuv420p"; if (Settings.proxyUseHardware()) { if (hwCodecs.contains("hevc_nvenc")) { - args << "-codec:v" << "hevc_nvenc"; - args << "-rc" << "constqp"; - args << "-qp:v" << "37"; - args << "-b_ref_mode" << "0"; + args << "-codec:v" + << "hevc_nvenc"; + args << "-rc" + << "constqp"; + args << "-qp:v" + << "37"; + args << "-b_ref_mode" + << "0"; } else if (hwCodecs.contains("hevc_qsv")) { - args << "-load_plugin" << "hevc_hw"; - args << "-codec:v" << "hevc_qsv"; - args << "-q:v" << "36"; + args << "-load_plugin" + << "hevc_hw"; + args << "-codec:v" + << "hevc_qsv"; + args << "-q:v" + << "36"; } else if (hwCodecs.contains("hevc_amf")) { - args << "-codec:v" << "hevc_amf"; - args << "-rc" << "1"; - args << "-qp_i" << "32" << "-qp_p" << "32"; + args << "-codec:v" + << "hevc_amf"; + args << "-rc" + << "1"; + args << "-qp_i" + << "32" + << "-qp_p" + << "32"; } else if (hwCodecs.contains("hevc_vaapi")) { - args << "-init_hw_device" << "vaapi=vaapi0:" << "-filter_hw_device" << "vaapi0"; - args << "-codec:v" << "hevc_vaapi"; - args << "-qp" << "37"; + args << "-init_hw_device" + << "vaapi=vaapi0:" + << "-filter_hw_device" + << "vaapi0"; + args << "-codec:v" + << "hevc_vaapi"; + args << "-qp" + << "37"; } else if (hwCodecs.contains("hevc_mf")) { - args << "-codec:v" << "hevc_mf"; - args << "-rate_control" << "quality"; - args << "-quality" << "27"; - args << "-hw_encoding" << "true" << "-pix_fmt" << "nv12"; + args << "-codec:v" + << "hevc_mf"; + args << "-rate_control" + << "quality"; + args << "-quality" + << "27"; + args << "-hw_encoding" + << "true" + << "-pix_fmt" + << "nv12"; } else if (hwCodecs.contains("h264_nvenc")) { - args << "-codec:v" << "h264_nvenc"; - args << "-rc" << "constqp"; - args << "-qp:v" << "37"; - args << "-b_ref_mode" << "0"; + args << "-codec:v" + << "h264_nvenc"; + args << "-rc" + << "constqp"; + args << "-qp:v" + << "37"; + args << "-b_ref_mode" + << "0"; } else if (hwCodecs.contains("h264_vaapi")) { - args << "-init_hw_device" << "vaapi=vaapi0:" << "-filter_hw_device" << "vaapi0"; - args << "-codec:v" << "h264_vaapi"; - args << "-qp" << "30"; + args << "-init_hw_device" + << "vaapi=vaapi0:" + << "-filter_hw_device" + << "vaapi0"; + args << "-codec:v" + << "h264_vaapi"; + args << "-qp" + << "30"; #if (defined(Q_OS_MAC) && defined(Q_PROCESSOR_ARM)) } else if (!fullRange && hwCodecs.contains("hevc_videotoolbox")) { - args << "-codec:v" << "hevc_videotoolbox"; - args << "-q:v" << "45"; + args << "-codec:v" + << "hevc_videotoolbox"; + args << "-q:v" + << "45"; } else if (!fullRange && hwCodecs.contains("h264_videotoolbox")) { - args << "-codec:v" << "h264_videotoolbox"; - args << "-q:v" << "45"; + args << "-codec:v" + << "h264_videotoolbox"; + args << "-q:v" + << "45"; #else } else if (hwCodecs.contains("hevc_videotoolbox")) { - args << "-codec:v" << "hevc_videotoolbox"; - args << "-b:v" << "5M"; + args << "-codec:v" + << "hevc_videotoolbox"; + args << "-b:v" + << "5M"; } else if (hwCodecs.contains("h264_videotoolbox")) { - args << "-codec:v" << "h264_videotoolbox"; - args << "-b:v" << "8M"; + args << "-codec:v" + << "h264_videotoolbox"; + args << "-b:v" + << "8M"; #endif } else if (hwCodecs.contains("h264_qsv")) { - args << "-codec:v" << "h264_qsv"; - args << "-q:v" << "36"; + args << "-codec:v" + << "h264_qsv"; + args << "-q:v" + << "36"; } else if (hwCodecs.contains("h264_amf")) { - args << "-codec:v" << "h264_amf"; - args << "-rc" << "1"; - args << "-qp_i" << "32" << "-qp_p" << "32"; + args << "-codec:v" + << "h264_amf"; + args << "-rc" + << "1"; + args << "-qp_i" + << "32" + << "-qp_p" + << "32"; } else if (hwCodecs.contains("h264_mf")) { - args << "-codec:v" << "h264_mf"; - args << "-rate_control" << "quality"; - args << "-quality" << "41"; - args << "-hw_encoding" << "true" << "-pix_fmt" << "nv12"; + args << "-codec:v" + << "h264_mf"; + args << "-rate_control" + << "quality"; + args << "-quality" + << "41"; + args << "-hw_encoding" + << "true" + << "-pix_fmt" + << "nv12"; } } if (!args.contains("-codec:v")) { - args << "-codec:v" << "libx264"; - args << "-preset" << "veryfast"; - args << "-crf" << "23"; - } - args << "-g" << QString::fromLatin1(hwCodecs.contains("hevc_nvenc") ? "0" : - hwCodecs.contains("h264_nvenc") ? "2" : "1"); - args << "-bf" << "0"; + args << "-codec:v" + << "libx264"; + args << "-preset" + << "veryfast"; + args << "-crf" + << "23"; + } + args << "-g" + << QString::fromLatin1(hwCodecs.contains("hevc_nvenc") ? "0" + : hwCodecs.contains("h264_nvenc") ? "2" + : "1"); + args << "-bf" + << "0"; args << "-y" << fileName; FfmpegJob *job = new FfmpegJob(fileName, args, true); @@ -286,7 +391,8 @@ void ProxyManager::generateImageProxy(Mlt::Producer &producer, bool replace) typedef QPair MltProperty; -static void processProperties(QXmlStreamWriter &newXml, QVector &properties, +static void processProperties(QXmlStreamWriter &newXml, + QVector &properties, const QString &root) { // Determine if this is a proxy resource @@ -319,7 +425,8 @@ static void processProperties(QXmlStreamWriter &newXml, QVector &pr newResource = newResource.mid(root.size()); } if (service == "timewarp") { - newProperties << MltProperty(p.first, QStringLiteral("%1:%2").arg(speed, newResource)); + newProperties << MltProperty(p.first, + QStringLiteral("%1:%2").arg(speed, newResource)); } else { newProperties << MltProperty(p.first, newResource); } @@ -417,7 +524,7 @@ bool ProxyManager::filterXML(QString &xmlString, QString root) } // Useful for debugging -// LOG_DEBUG() << output; + // LOG_DEBUG() << output; if (!xml.hasError()) { xmlString = output; @@ -445,7 +552,8 @@ bool ProxyManager::fileExists(Mlt::Producer &producer) } else { return false; } - return (projectDir.cd(kProxySubfolder) && projectDir.exists(fileName)) || proxyDir.exists(fileName); + return (projectDir.cd(kProxySubfolder) && projectDir.exists(fileName)) + || proxyDir.exists(fileName); } bool ProxyManager::filePending(Mlt::Producer &producer) @@ -461,13 +569,15 @@ bool ProxyManager::filePending(Mlt::Producer &producer) } else { return false; } - return (projectDir.cd(kProxySubfolder) && projectDir.exists(fileName)) || proxyDir.exists(fileName); + return (projectDir.cd(kProxySubfolder) && projectDir.exists(fileName)) + || proxyDir.exists(fileName); } bool ProxyManager::isValidImage(Mlt::Producer &producer) { QString service = QString::fromLatin1(producer.get("mlt_service")); - if ((service == "qimage" || service == "pixbuf") && !producer.get_int(kShotcutSequenceProperty)) { + if ((service == "qimage" || service == "pixbuf") + && !producer.get_int(kShotcutSequenceProperty)) { QImageReader reader; reader.setDecideFormatFromContent(true); reader.setFileName(ProxyManager::resource(producer)); @@ -499,8 +609,8 @@ bool ProxyManager::isValidVideo(Mlt::Producer producer) bool coverArt = codec_name == "mjpeg" && frame_rate == "90000"; key = QStringLiteral("meta.attr.%1.stream.alpha_mode.markup").arg(video_index); bool alpha_mode = producer.get_int(key.toLatin1().constData()); - LOG_DEBUG() << "pix_fmt =" << pix_fmt << " codec.frame_rate =" << frame_rate << " alpha_mode =" << - alpha_mode; + LOG_DEBUG() << "pix_fmt =" << pix_fmt << " codec.frame_rate =" << frame_rate + << " alpha_mode =" << alpha_mode; return !kPixFmtsWithAlpha.contains(pix_fmt) && !alpha_mode && !coverArt; } return false; @@ -510,7 +620,7 @@ bool ProxyManager::isValidVideo(Mlt::Producer producer) bool ProxyManager::generateIfNotExists(Mlt::Producer &producer, bool replace) { if (Settings.proxyEnabled() && producer.is_valid() && !producer.get_int(kDisableProxyProperty) - && !producer.get_int(kIsProxyProperty)) { + && !producer.get_int(kIsProxyProperty)) { if (ProxyManager::fileExists(producer)) { QString service = QString::fromLatin1(producer.get("mlt_service")); QDir projectDir(MLT.projectFolder()); @@ -555,20 +665,24 @@ bool ProxyManager::generateIfNotExists(Mlt::Producer &producer, bool replace) // Tag this producer so we do not try to generate proxy again in this session delete producer.get_frame(); auto threshold = qRound(kProxyResolutionRatio * resolution()); - LOG_DEBUG() << producer.get_int("meta.media.width") << "x" << producer.get_int("meta.media.height") - << "threshold" << threshold; + LOG_DEBUG() << producer.get_int("meta.media.width") << "x" + << producer.get_int("meta.media.height") << "threshold" << threshold; if (producer.get_int("meta.media.width") > threshold - && producer.get_int("meta.media.height") > threshold) { - ProxyManager::generateVideoProxy(producer, MLT.fullRange(producer), Automatic, QPoint(), replace); + && producer.get_int("meta.media.height") > threshold) { + ProxyManager::generateVideoProxy(producer, + MLT.fullRange(producer), + Automatic, + QPoint(), + replace); } } else if (isValidImage(producer)) { // Tag this producer so we do not try to generate proxy again in this session delete producer.get_frame(); auto threshold = qRound(kProxyResolutionRatio * resolution()); - LOG_DEBUG() << producer.get_int("meta.media.width") << "x" << producer.get_int("meta.media.height") - << "threshold" << threshold; + LOG_DEBUG() << producer.get_int("meta.media.width") << "x" + << producer.get_int("meta.media.height") << "threshold" << threshold; if (producer.get_int("meta.media.width") > threshold - && producer.get_int("meta.media.height") > threshold) { + && producer.get_int("meta.media.height") > threshold) { ProxyManager::generateImageProxy(producer, replace); } } @@ -609,89 +723,40 @@ class FindNonProxyProducersParser : public Mlt::Parser QList m_producers; public: - FindNonProxyProducersParser() : Mlt::Parser() {} + FindNonProxyProducersParser() + : Mlt::Parser() + {} - QList &producers() - { - return m_producers; - } + QList &producers() { return m_producers; } - int on_start_filter(Mlt::Filter *) - { - return 0; - } + int on_start_filter(Mlt::Filter *) { return 0; } int on_start_producer(Mlt::Producer *producer) { if (!producer->parent().get_int(kIsProxyProperty)) m_producers << Mlt::Producer(producer); return 0; } - int on_end_producer(Mlt::Producer *) - { - return 0; - } - int on_start_playlist(Mlt::Playlist *) - { - return 0; - } - int on_end_playlist(Mlt::Playlist *) - { - return 0; - } - int on_start_tractor(Mlt::Tractor *) - { - return 0; - } - int on_end_tractor(Mlt::Tractor *) - { - return 0; - } - int on_start_multitrack(Mlt::Multitrack *) - { - return 0; - } - int on_end_multitrack(Mlt::Multitrack *) - { - return 0; - } - int on_start_track() - { - return 0; - } - int on_end_track() - { - return 0; - } - int on_end_filter(Mlt::Filter *) - { - return 0; - } - int on_start_transition(Mlt::Transition *) - { - return 0; - } - int on_end_transition(Mlt::Transition *) - { - return 0; - } + int on_end_producer(Mlt::Producer *) { return 0; } + int on_start_playlist(Mlt::Playlist *) { return 0; } + int on_end_playlist(Mlt::Playlist *) { return 0; } + int on_start_tractor(Mlt::Tractor *) { return 0; } + int on_end_tractor(Mlt::Tractor *) { return 0; } + int on_start_multitrack(Mlt::Multitrack *) { return 0; } + int on_end_multitrack(Mlt::Multitrack *) { return 0; } + int on_start_track() { return 0; } + int on_end_track() { return 0; } + int on_end_filter(Mlt::Filter *) { return 0; } + int on_start_transition(Mlt::Transition *) { return 0; } + int on_end_transition(Mlt::Transition *) { return 0; } int on_start_chain(Mlt::Chain *chain) { if (!chain->parent().get_int(kIsProxyProperty)) m_producers << Mlt::Producer(chain); return 0; } - int on_end_chain(Mlt::Chain *) - { - return 0; - } - int on_start_link(Mlt::Link *) - { - return 0; - } - int on_end_link(Mlt::Link *) - { - return 0; - } + int on_end_chain(Mlt::Chain *) { return 0; } + int on_start_link(Mlt::Link *) { return 0; } + int on_end_link(Mlt::Link *) { return 0; } }; void ProxyManager::generateIfNotExistsAll(Mlt::Producer &producer) diff --git a/src/proxymanager.h b/src/proxymanager.h index ed7fe477fa..6cc264cf0a 100644 --- a/src/proxymanager.h +++ b/src/proxymanager.h @@ -19,31 +19,29 @@ #define PROXYMANAGER_H #include -#include #include +#include namespace Mlt { class Producer; class Service; -} +} // namespace Mlt class ProxyManager { private: - ProxyManager() {}; + ProxyManager(){}; public: - enum ScanMode { - Automatic, - Progressive, - InterlacedTopFieldFirst, - InterlacedBottomFieldFirst - }; + enum ScanMode { Automatic, Progressive, InterlacedTopFieldFirst, InterlacedBottomFieldFirst }; static QDir dir(); static QString resource(Mlt::Service &producer); - static void generateVideoProxy(Mlt::Producer &producer, bool fullRange, - ScanMode scanMode = Automatic, const QPoint &aspectRatio = QPoint(), bool replace = true); + static void generateVideoProxy(Mlt::Producer &producer, + bool fullRange, + ScanMode scanMode = Automatic, + const QPoint &aspectRatio = QPoint(), + bool replace = true); static void generateImageProxy(Mlt::Producer &producer, bool replace = true); static bool filterXML(QString &xml, QString root); static bool fileExists(Mlt::Producer &producer); diff --git a/src/qmltypes/colordialog.cpp b/src/qmltypes/colordialog.cpp index 35ec485d63..1d81af2b23 100644 --- a/src/qmltypes/colordialog.cpp +++ b/src/qmltypes/colordialog.cpp @@ -21,8 +21,7 @@ ColorDialog::ColorDialog(QObject *parent) : QObject{parent} -{ -} +{} void ColorDialog::open() { @@ -36,7 +35,8 @@ void ColorDialog::open() auto rgb = newColor; auto transparent = QColor(0, 0, 0, 0); rgb.setAlpha(color.alpha()); - if (newColor.alpha() == 0 && (rgb != color || (newColor == transparent && color == transparent))) { + if (newColor.alpha() == 0 + && (rgb != color || (newColor == transparent && color == transparent))) { newColor.setAlpha(255); } setSelectedColor(newColor); diff --git a/src/qmltypes/colordialog.h b/src/qmltypes/colordialog.h index fbae012802..1ae8441b64 100644 --- a/src/qmltypes/colordialog.h +++ b/src/qmltypes/colordialog.h @@ -24,8 +24,8 @@ class ColorDialog : public QObject { Q_OBJECT - Q_PROPERTY(QColor selectedColor READ selectedColor WRITE setSelectedColor NOTIFY - selectedColorChanged) + Q_PROPERTY( + QColor selectedColor READ selectedColor WRITE setSelectedColor NOTIFY selectedColorChanged) Q_PROPERTY(QString title READ title WRITE setTitle NOTIFY titleChanged) public: @@ -42,15 +42,9 @@ class ColorDialog : public QObject QColor m_color; QString m_title; - QColor selectedColor() const - { - return m_color; - } + QColor selectedColor() const { return m_color; } void setSelectedColor(const QColor &color); - QString title() const - { - return m_title; - } + QString title() const { return m_title; } void setTitle(const QString &title); }; diff --git a/src/qmltypes/colorpickeritem.cpp b/src/qmltypes/colorpickeritem.cpp index 52288fa56a..11958972ca 100644 --- a/src/qmltypes/colorpickeritem.cpp +++ b/src/qmltypes/colorpickeritem.cpp @@ -18,7 +18,7 @@ */ #include "colorpickeritem.h" -#include +#include "Logger.h" #include #include @@ -64,9 +64,11 @@ void ColorPickerItem::screenSelected(const QRect &rect) void ColorPickerItem::grabColor() { QScreen *screen = QGuiApplication::screenAt(m_selectedRect.topLeft()); - QPixmap screenGrab = screen->grabWindow(0, m_selectedRect.x() - screen->geometry().x(), + QPixmap screenGrab = screen->grabWindow(0, + m_selectedRect.x() - screen->geometry().x(), m_selectedRect.y() - screen->geometry().y(), - m_selectedRect.width(), m_selectedRect.height()); + m_selectedRect.width(), + m_selectedRect.height()); QImage image = screenGrab.toImage(); int numPixel = qMax(image.width() * image.height(), 1); int sumR = 0; @@ -111,19 +113,24 @@ const QDBusArgument &operator>>(const QDBusArgument &arg, QColor &color) void ColorPickerItem::grabColorDBus() { - QDBusMessage message = QDBusMessage::createMethodCall( - QLatin1String("org.freedesktop.portal.Desktop"), QLatin1String("/org/freedesktop/portal/desktop"), - QLatin1String("org.freedesktop.portal.Screenshot"), QLatin1String("PickColor")); + QDBusMessage message + = QDBusMessage::createMethodCall(QLatin1String("org.freedesktop.portal.Desktop"), + QLatin1String("/org/freedesktop/portal/desktop"), + QLatin1String("org.freedesktop.portal.Screenshot"), + QLatin1String("PickColor")); message << QLatin1String("x11:") << QVariantMap{}; QDBusPendingCall pendingCall = QDBusConnection::sessionBus().asyncCall(message); QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(pendingCall); - connect(watcher, &QDBusPendingCallWatcher::finished, [ = ](QDBusPendingCallWatcher * watcher) { + connect(watcher, &QDBusPendingCallWatcher::finished, [=](QDBusPendingCallWatcher *watcher) { QDBusPendingReply reply = *watcher; if (reply.isError()) { LOG_WARNING() << "Unable to get DBus reply: " << reply.error().message(); } else { - QDBusConnection::sessionBus().connect(QString(), reply.value().path(), - QLatin1String("org.freedesktop.portal.Request"), QLatin1String("Response"), this, + QDBusConnection::sessionBus().connect(QString(), + reply.value().path(), + QLatin1String("org.freedesktop.portal.Request"), + QLatin1String("Response"), + this, SLOT(gotColorResponse(uint, QVariantMap))); } }); diff --git a/src/qmltypes/colorwheelitem.cpp b/src/qmltypes/colorwheelitem.cpp index 93168918ec..9f2452598f 100644 --- a/src/qmltypes/colorwheelitem.cpp +++ b/src/qmltypes/colorwheelitem.cpp @@ -21,9 +21,11 @@ #include "colorwheelitem.h" #include "mainwindow.h" -#include + #include +#include #include + #include static const qreal WHEEL_SLIDER_RATIO = 10.0; @@ -154,13 +156,14 @@ void ColorWheelItem::setStep(qreal step) int ColorWheelItem::wheelSize() const { - qreal ws = (qreal)width() / (1.0 + 1.0 / WHEEL_SLIDER_RATIO); + qreal ws = (qreal) width() / (1.0 + 1.0 / WHEEL_SLIDER_RATIO); return qMin(ws, height()); } QColor ColorWheelItem::colorForPoint(const QPoint &point) { - if (! m_image.valid(point)) return QColor(); + if (!m_image.valid(point)) + return QColor(); if (m_isInWheel) { qreal w = wheelSize() - m_margin * 2; qreal xf = qreal(point.x() - m_margin) / w; @@ -173,11 +176,11 @@ QColor ColorWheelItem::colorForPoint(const QPoint &point) if (theta < 0.0) theta += 2.0 * M_PI; qreal hue = (theta * 180.0 / M_PI) / 360.0; - return QColor::fromHsvF( hue, rad, m_color.valueF() ); + return QColor::fromHsvF(hue, rad, m_color.valueF()); } if (m_isInSquare) { qreal value = 1.0 - qreal(point.y() - m_margin) / (wheelSize() - m_margin * 2); - return QColor::fromHsvF( m_color.hueF(), m_color.saturationF(), value); + return QColor::fromHsvF(m_color.hueF(), m_color.saturationF(), value); } return QColor(); } @@ -205,7 +208,8 @@ void ColorWheelItem::mouseMoveEvent(QMouseEvent *event) { updateCursor(event->pos()); - if (!m_isMouseDown) return; + if (!m_isMouseDown) + return; m_lastPoint = event->pos(); if (m_wheelRegion.contains(m_lastPoint) && m_isInWheel) { QColor color = colorForPoint(m_lastPoint); @@ -233,27 +237,33 @@ void ColorWheelItem::hoverMoveEvent(QHoverEvent *event) void ColorWheelItem::wheelEvent(QWheelEvent *event) { QPoint steps = event->angleDelta() / 8 / 15; - qreal delta = (qreal)steps.y() * m_step; + qreal delta = (qreal) steps.y() * m_step; QColor currentColor = color(); qreal c; // Increment/decrement RGB values by delta c = currentColor.redF(); c += delta; - if (c < 0) c = 0; - if (c > 1) c = 1; + if (c < 0) + c = 0; + if (c > 1) + c = 1; currentColor.setRedF(c); c = currentColor.greenF(); c += delta; - if (c < 0) c = 0; - if (c > 1) c = 1; + if (c < 0) + c = 0; + if (c > 1) + c = 1; currentColor.setGreenF(c); c = currentColor.blueF(); c += delta; - if (c < 0) c = 0; - if (c > 1) c = 1; + if (c < 0) + c = 0; + if (c > 1) + c = 1; currentColor.setBlueF(c); setColor(currentColor); @@ -263,9 +273,9 @@ void ColorWheelItem::wheelEvent(QWheelEvent *event) void ColorWheelItem::paint(QPainter *painter) { - QSize size( width(), height() ); + QSize size(width(), height()); - if ( m_size != size ) { + if (m_size != size) { m_image = QImage(QSize(width(), height()), QImage::Format_ARGB32_Premultiplied); m_image.fill(qRgba(0, 0, 0, 0)); drawWheel(); @@ -287,13 +297,13 @@ void ColorWheelItem::drawWheel() m_image.fill(0); // transparent QConicalGradient conicalGradient; - conicalGradient.setColorAt( 0.0, Qt::red); - conicalGradient.setColorAt( 60.0 / 360.0, Qt::yellow); + conicalGradient.setColorAt(0.0, Qt::red); + conicalGradient.setColorAt(60.0 / 360.0, Qt::yellow); conicalGradient.setColorAt(135.0 / 360.0, Qt::green); conicalGradient.setColorAt(180.0 / 360.0, Qt::cyan); conicalGradient.setColorAt(240.0 / 360.0, Qt::blue); conicalGradient.setColorAt(315.0 / 360.0, Qt::magenta); - conicalGradient.setColorAt( 1.0, Qt::red); + conicalGradient.setColorAt(1.0, Qt::red); QRadialGradient radialGradient(0.0, 0.0, r / 2); radialGradient.setColorAt(0.0, Qt::white); @@ -333,7 +343,7 @@ void ColorWheelItem::drawSliderBar(QPainter &painter) { qreal value = 1.0 - m_color.valueF(); int ws = wheelSize() * MAIN.devicePixelRatioF(); - int w = (qreal)ws / WHEEL_SLIDER_RATIO; + int w = (qreal) ws / WHEEL_SLIDER_RATIO; int h = ws - m_margin * 2; QPen pen(Qt::white); pen.setWidth(qRound(2 * MAIN.devicePixelRatioF())); @@ -349,7 +359,7 @@ void ColorWheelItem::drawSlider() QPainter painter(&m_image); painter.setRenderHint(QPainter::Antialiasing); int ws = wheelSize(); - int w = (qreal)ws / WHEEL_SLIDER_RATIO; + int w = (qreal) ws / WHEEL_SLIDER_RATIO; int h = ws - m_margin * 2; QLinearGradient gradient(0, 0, w, h); gradient.setColorAt(0.0, Qt::white); diff --git a/src/qmltypes/colorwheelitem.h b/src/qmltypes/colorwheelitem.h index 4c8c88ade4..6daf97e41e 100644 --- a/src/qmltypes/colorwheelitem.h +++ b/src/qmltypes/colorwheelitem.h @@ -20,8 +20,8 @@ #ifndef COLORWHEELITEM_H #define COLORWHEELITEM_H -#include #include +#include class ColorWheelItem : public QQuickPaintedItem { @@ -53,7 +53,6 @@ class ColorWheelItem : public QQuickPaintedItem qreal step(); void setStep(qreal blue); - signals: void colorChanged(const QColor &color); diff --git a/src/qmltypes/filedialog.cpp b/src/qmltypes/filedialog.cpp index 66c84ab74e..891146a2ae 100644 --- a/src/qmltypes/filedialog.cpp +++ b/src/qmltypes/filedialog.cpp @@ -16,6 +16,7 @@ */ #include "filedialog.h" + #include "mainwindow.h" #include "settings.h" #include "util.h" diff --git a/src/qmltypes/filedialog.h b/src/qmltypes/filedialog.h index 526dbde982..b6c8b2c1ad 100644 --- a/src/qmltypes/filedialog.h +++ b/src/qmltypes/filedialog.h @@ -25,18 +25,16 @@ class FileDialog : public QObject Q_OBJECT Q_PROPERTY(FileDialog::FileMode fileMode READ fileMode WRITE setFileMode NOTIFY fileModeChanged) Q_PROPERTY(QString title READ title WRITE setTitle NOTIFY titleChanged) - Q_PROPERTY(QStringList nameFilters READ nameFilters WRITE setNameFilters NOTIFY nameFiltersChanged) + Q_PROPERTY( + QStringList nameFilters READ nameFilters WRITE setNameFilters NOTIFY nameFiltersChanged) Q_PROPERTY(QString selectedFile READ selectedFile NOTIFY fileSelected) public: - enum FileMode {OpenFile, SaveFile}; + enum FileMode { OpenFile, SaveFile }; Q_ENUM(FileMode) explicit FileDialog(QObject *parent = nullptr); - FileDialog::FileMode fileMode() const - { - return m_fileMode; - } + FileDialog::FileMode fileMode() const { return m_fileMode; } void setFileMode(FileDialog::FileMode mode); QString title() const; void setTitle(const QString &title); @@ -55,7 +53,7 @@ class FileDialog : public QObject void rejected(); private: - FileDialog::FileMode m_fileMode {FileDialog::OpenFile}; + FileDialog::FileMode m_fileMode{FileDialog::OpenFile}; std::unique_ptr m_fileDialog; }; diff --git a/src/qmltypes/fontdialog.cpp b/src/qmltypes/fontdialog.cpp index eb54d59988..ab5ca259bb 100644 --- a/src/qmltypes/fontdialog.cpp +++ b/src/qmltypes/fontdialog.cpp @@ -21,8 +21,7 @@ FontDialog::FontDialog(QObject *parent) : QObject{parent} -{ -} +{} void FontDialog::open() { diff --git a/src/qmltypes/fontdialog.h b/src/qmltypes/fontdialog.h index f5305463c0..832751cedb 100644 --- a/src/qmltypes/fontdialog.h +++ b/src/qmltypes/fontdialog.h @@ -18,8 +18,8 @@ #ifndef FONTDIALOG_H #define FONTDIALOG_H -#include #include +#include class FontDialog : public QObject { @@ -39,10 +39,7 @@ class FontDialog : public QObject private: QFont m_font; - QFont selectedFont() const - { - return m_font; - } + QFont selectedFont() const { return m_font; } void setSelectedFont(const QFont &font); }; diff --git a/src/qmltypes/messagedialog.cpp b/src/qmltypes/messagedialog.cpp index 874c9cc187..0623001fb6 100644 --- a/src/qmltypes/messagedialog.cpp +++ b/src/qmltypes/messagedialog.cpp @@ -16,16 +16,16 @@ */ #include "messagedialog.h" + +#include "Logger.h" #include "qmlapplication.h" -#include #include MessageDialog::MessageDialog(QObject *parent) : QObject{parent} , m_buttons{0} -{ -} +{} void MessageDialog::open() { diff --git a/src/qmltypes/messagedialog.h b/src/qmltypes/messagedialog.h index 96b0a262bb..7a154dc1d9 100644 --- a/src/qmltypes/messagedialog.h +++ b/src/qmltypes/messagedialog.h @@ -28,10 +28,10 @@ class MessageDialog : public QObject public: enum StandardButtons { - Ok = QMessageBox::Ok, - Yes = QMessageBox::Yes, - No = QMessageBox::No, - Cancel = QMessageBox::Cancel + Ok = QMessageBox::Ok, + Yes = QMessageBox::Yes, + No = QMessageBox::No, + Cancel = QMessageBox::Cancel }; Q_ENUM(StandardButtons) explicit MessageDialog(QObject *parent = nullptr); @@ -50,20 +50,11 @@ class MessageDialog : public QObject QString m_text; int m_buttons; - QString title() const - { - return m_title; - } + QString title() const { return m_title; } void setTitle(const QString &title); - QString text() const - { - return m_text; - } + QString text() const { return m_text; } void setText(const QString &text); - int buttons() const - { - return m_buttons; - } + int buttons() const { return m_buttons; } void setButtons(int buttons); }; diff --git a/src/qmltypes/qmlapplication.cpp b/src/qmltypes/qmlapplication.cpp index 2548dc6279..a6cf4d8e29 100644 --- a/src/qmltypes/qmlapplication.cpp +++ b/src/qmltypes/qmlapplication.cpp @@ -16,22 +16,24 @@ */ #include "qmlapplication.h" + +#include "controllers/filtercontroller.h" #include "mainwindow.h" #include "mltcontroller.h" -#include "controllers/filtercontroller.h" #include "models/attachedfiltersmodel.h" -#include "videowidget.h" #include "settings.h" #include "util.h" +#include "videowidget.h" + #include -#include +#include +#include #include -#include -#include #include #include -#include -#include +#include +#include +#include #ifdef Q_OS_WIN #include #else @@ -45,10 +47,9 @@ QmlApplication &QmlApplication::singleton() return instance; } -QmlApplication::QmlApplication() : - QObject() -{ -} +QmlApplication::QmlApplication() + : QObject() +{} Qt::WindowModality QmlApplication::dialogModality() { @@ -109,8 +110,8 @@ bool QmlApplication::hasFiltersOnClipboard() void QmlApplication::copyEnabledFilters() { - QScopedPointer producer(new Mlt::Producer( - MAIN.filterController()->attachedModel()->producer())); + QScopedPointer producer( + new Mlt::Producer(MAIN.filterController()->attachedModel()->producer())); MLT.copyFilters(producer.data(), MLT.FILTER_INDEX_ENABLED); QGuiApplication::clipboard()->setText(MLT.filtersClipboardXML()); emit QmlApplication::singleton().filtersCopied(); @@ -118,8 +119,8 @@ void QmlApplication::copyEnabledFilters() void QmlApplication::copyAllFilters() { - QScopedPointer producer(new Mlt::Producer( - MAIN.filterController()->attachedModel()->producer())); + QScopedPointer producer( + new Mlt::Producer(MAIN.filterController()->attachedModel()->producer())); MLT.copyFilters(producer.data(), MLT.FILTER_INDEX_ENABLED); QGuiApplication::clipboard()->setText(MLT.filtersClipboardXML()); emit QmlApplication::singleton().filtersCopied(); @@ -132,8 +133,8 @@ void QmlApplication::copyCurrentFilter() MAIN.showStatusMessage(tr("Select a filter to copy")); return; } - QScopedPointer producer(new Mlt::Producer( - MAIN.filterController()->attachedModel()->producer())); + QScopedPointer producer( + new Mlt::Producer(MAIN.filterController()->attachedModel()->producer())); MLT.copyFilters(producer.data(), currentIndex); QGuiApplication::clipboard()->setText(MLT.filtersClipboardXML()); emit QmlApplication::singleton().filtersCopied(); @@ -141,15 +142,15 @@ void QmlApplication::copyCurrentFilter() void QmlApplication::pasteFilters() { - QScopedPointer producer(new Mlt::Producer( - MAIN.filterController()->attachedModel()->producer())); + QScopedPointer producer( + new Mlt::Producer(MAIN.filterController()->attachedModel()->producer())); if (confirmOutputFilter()) { QString s = QGuiApplication::clipboard()->text(); if (MLT.isMltXml(s)) { Mlt::Profile profile(kDefaultMltProfile); Mlt::Producer filtersProducer(profile, "xml-string", s.toUtf8().constData()); if (filtersProducer.is_valid() && filtersProducer.filter_count() > 0 - && filtersProducer.get_int(kShotcutFiltersClipboard)) { + && filtersProducer.get_int(kShotcutFiltersClipboard)) { MLT.pasteFilters(producer.get(), &filtersProducer); } else { MLT.pasteFilters(producer.data()); @@ -235,11 +236,13 @@ bool QmlApplication::confirmOutputFilter() "

Timeline > Output is currently selected. " "Adding filters to Output affects ALL clips in the " "timeline including new ones that will be added.

"), - QMessageBox::No | QMessageBox::Yes, &MAIN); + QMessageBox::No | QMessageBox::Yes, + &MAIN); dialog.setWindowModality(dialogModality()); dialog.setDefaultButton(QMessageBox::No); dialog.setEscapeButton(QMessageBox::Yes); - dialog.setCheckBox(new QCheckBox(tr("Do not show this anymore.", "confirm output filters dialog"))); + dialog.setCheckBox( + new QCheckBox(tr("Do not show this anymore.", "confirm output filters dialog"))); result = dialog.exec() == QMessageBox::Yes; if (dialog.checkBox()->isChecked()) { Settings.setAskOutputFilter(false); diff --git a/src/qmltypes/qmlapplication.h b/src/qmltypes/qmlapplication.h index ef883bf544..26dbad24a1 100644 --- a/src/qmltypes/qmlapplication.h +++ b/src/qmltypes/qmlapplication.h @@ -18,10 +18,10 @@ #ifndef QMLAPPLICATION_H #define QMLAPPLICATION_H -#include +#include #include +#include #include -#include #include namespace Mlt { diff --git a/src/qmltypes/qmleditmenu.cpp b/src/qmltypes/qmleditmenu.cpp index d795bc2681..ebe42d1f41 100644 --- a/src/qmltypes/qmleditmenu.cpp +++ b/src/qmltypes/qmleditmenu.cpp @@ -23,8 +23,7 @@ QmlEditMenu::QmlEditMenu(QObject *parent) : QObject(parent) , m_showPastePlain(false) , m_readOnly(false) -{ -} +{} void QmlEditMenu::popup() { diff --git a/src/qmltypes/qmlfile.cpp b/src/qmltypes/qmlfile.cpp index d2832c1902..37f8bc4c37 100644 --- a/src/qmltypes/qmlfile.cpp +++ b/src/qmltypes/qmlfile.cpp @@ -16,22 +16,23 @@ */ #include "qmlfile.h" -#include -#include + +#include "Logger.h" + #include -#include +#include +#include QmlFile::QmlFile(QObject *parent) : QObject(parent) , m_url() -{ -} +{} QString QmlFile::getUrl() { auto s = QUrl::fromPercentEncoding(m_url.toString().toUtf8()); #ifdef Q_OS_WIN - if (s.size() > 2 && s[1] == ':' && s[2] == '/') { + if (s.size() > 2 && s[1] == ':' && s[2] == '/') { s[0] = s[0].toUpper(); } #endif @@ -41,14 +42,11 @@ QString QmlFile::getUrl() void QmlFile::setUrl(QString text) { QUrl url = text.replace('\\', "/"); - QString s = url.toString();; - QUrl::FormattingOptions options = - QUrl::RemoveScheme | - QUrl::RemovePassword | - QUrl::RemoveUserInfo | - QUrl::RemovePort | - QUrl::RemoveAuthority | - QUrl::RemoveQuery; + QString s = url.toString(); + ; + QUrl::FormattingOptions options = QUrl::RemoveScheme | QUrl::RemovePassword + | QUrl::RemoveUserInfo | QUrl::RemovePort + | QUrl::RemoveAuthority | QUrl::RemoveQuery; if (s.startsWith("file://") && s.size() > 9 && s[9] != ':') { // QUrl removes the host from a UNC path when removing the scheme. @@ -69,7 +67,7 @@ void QmlFile::setUrl(QString text) // If there is a slash before a drive letter. // On Windows, file URLs look like file:///C:/Users/.... // The scheme is removed but only "://" (not 3 slashes) between scheme and path. - if (s.size() > 2 && s[0] == '/' && s[2] == ':') { + if (s.size() > 2 && s[0] == '/' && s[2] == ':') { // Remove the leading slash. s = s.mid(1); } diff --git a/src/qmltypes/qmlfile.h b/src/qmltypes/qmlfile.h index 29820304a0..cbc7a8d5e8 100644 --- a/src/qmltypes/qmlfile.h +++ b/src/qmltypes/qmlfile.h @@ -18,9 +18,10 @@ #ifndef QMLFILE_H #define QMLFILE_H +#include #include #include -#include + #include class QmlFile : public QObject diff --git a/src/qmltypes/qmlfilter.cpp b/src/qmltypes/qmlfilter.cpp index dfcd3dfaf3..b0c674bc27 100644 --- a/src/qmltypes/qmlfilter.cpp +++ b/src/qmltypes/qmlfilter.cpp @@ -16,26 +16,27 @@ */ #include "qmlfilter.h" -#include "mltcontroller.h" -#include "mainwindow.h" + +#include "Logger.h" #include "commands/filtercommands.h" #include "controllers/filtercontroller.h" #include "jobqueue.h" #include "jobs/encodejob.h" -#include "shotcut_mlt_properties.h" +#include "mainwindow.h" +#include "mltcontroller.h" +#include "proxymanager.h" #include "settings.h" +#include "shotcut_mlt_properties.h" #include "util.h" -#include "proxymanager.h" -#include +#include +#include #include +#include +#include #include #include -#include #include -#include -#include -#include QmlFilter::QmlFilter() : QObject(nullptr) @@ -60,16 +61,16 @@ QmlFilter::QmlFilter(Mlt::Service &mltService, const QmlMetadata *metadata, QObj { if (m_service.type() == mlt_service_filter_type) { // Every attached filter has a service property that points to the service to which it is attached. - m_producer = Mlt::Producer(mlt_producer(m_service.is_valid() ? m_service.get_data("service") : 0)); + m_producer = Mlt::Producer( + mlt_producer(m_service.is_valid() ? m_service.get_data("service") : 0)); } else if (m_service.type() == mlt_service_link_type) { // Every attached link has a chain property that points to the chain to which it is attached. - m_producer = Mlt::Producer(mlt_producer(m_service.is_valid() ? m_service.get_data("chain") : 0)); + m_producer = Mlt::Producer( + mlt_producer(m_service.is_valid() ? m_service.get_data("chain") : 0)); } } -QmlFilter::~QmlFilter() -{ -} +QmlFilter::~QmlFilter() {} QString QmlFilter::get(QString name, int position) { @@ -109,7 +110,8 @@ double QmlFilter::getDouble(QString name, int position) QRectF QmlFilter::getRect(QString name, int position) { - if (!m_service.is_valid()) return QRectF(); + if (!m_service.is_valid()) + return QRectF(); const char *s = m_service.get(qUtf8Printable(name)); if (s) { mlt_rect rect; @@ -134,7 +136,8 @@ QRectF QmlFilter::getRect(QString name, int position) void QmlFilter::removeRectPercents(QString name) { // This method iterates over each keyframe and converts the percentage values to absolute. - if (!m_service.is_valid()) return; + if (!m_service.is_valid()) + return; const char *s = m_service.get(qUtf8Printable(name)); if (s && ::strchr(s, '%')) { m_service.anim_get_rect(qUtf8Printable(name), 0, duration()); @@ -175,10 +178,11 @@ QStringList QmlFilter::getGradient(QString name) void QmlFilter::set(QString name, QString value, int position) { - if (!m_service.is_valid()) return; + if (!m_service.is_valid()) + return; if (position < 0) { - if (qstrcmp(m_service.get(qUtf8Printable(name)), qUtf8Printable(value))) { - m_service.set_string(qUtf8Printable(name), qUtf8Printable(value)) ; + if (qstrcmp(m_service.get(qUtf8Printable(name)), qUtf8Printable(value))) { + m_service.set_string(qUtf8Printable(name), qUtf8Printable(value)); emit changed(name); updateUndoCommand(name); } @@ -186,7 +190,7 @@ void QmlFilter::set(QString name, QString value, int position) // Only set an animation keyframe if it does not already exist with the same value. Mlt::Animation animation(m_service.get_animation(qUtf8Printable(name))); if (!animation.is_valid() || !animation.is_key(position) - || value != m_service.anim_get(qUtf8Printable(name), position, duration())) { + || value != m_service.anim_get(qUtf8Printable(name), position, duration())) { m_service.anim_set(qUtf8Printable(name), qUtf8Printable(value), position, duration()); emit changed(name); updateUndoCommand(name); @@ -196,11 +200,12 @@ void QmlFilter::set(QString name, QString value, int position) void QmlFilter::set(QString name, const QColor &value, int position, mlt_keyframe_type keyframeType) { - if (!m_service.is_valid()) return; + if (!m_service.is_valid()) + return; if (position < 0) { auto mltColor = m_service.get_color(qUtf8Printable(name)); if (!m_service.get(qUtf8Printable(name)) - || value != QColor(mltColor.r, mltColor.g, mltColor.b, mltColor.a)) { + || value != QColor(mltColor.r, mltColor.g, mltColor.b, mltColor.a)) { m_service.set(qUtf8Printable(name), Util::mltColorFromQColor(value)); emit changed(name); updateUndoCommand(name); @@ -210,8 +215,11 @@ void QmlFilter::set(QString name, const QColor &value, int position, mlt_keyfram Mlt::Animation animation(m_service.get_animation(qUtf8Printable(name))); auto mltColor = m_service.anim_get_color(qUtf8Printable(name), position, duration()); if (!animation.is_valid() || !animation.is_key(position) - || value != QColor(mltColor.r, mltColor.g, mltColor.b, mltColor.a)) { - m_service.anim_set(qUtf8Printable(name), Util::mltColorFromQColor(value), position, duration()); + || value != QColor(mltColor.r, mltColor.g, mltColor.b, mltColor.a)) { + m_service.anim_set(qUtf8Printable(name), + Util::mltColorFromQColor(value), + position, + duration()); emit changed(name); updateUndoCommand(name); } @@ -220,10 +228,11 @@ void QmlFilter::set(QString name, const QColor &value, int position, mlt_keyfram void QmlFilter::set(QString name, double value, int position, mlt_keyframe_type keyframeType) { - if (!m_service.is_valid()) return; + if (!m_service.is_valid()) + return; if (position < 0) { if (!m_service.get(qUtf8Printable(name)) - || m_service.get_double(qUtf8Printable(name)) != value) { + || m_service.get_double(qUtf8Printable(name)) != value) { double delta = value - m_service.get_double(qUtf8Printable(name)); m_service.set(qUtf8Printable(name), value); emit changed(name); @@ -238,7 +247,7 @@ void QmlFilter::set(QString name, double value, int position, mlt_keyframe_type // Only set an animation keyframe if it does not already exist with the same value. Mlt::Animation animation(m_service.get_animation(qUtf8Printable(name))); if (!animation.is_valid() || !animation.is_key(position) - || value != m_service.anim_get_double(qUtf8Printable(name), position, duration())) { + || value != m_service.anim_get_double(qUtf8Printable(name), position, duration())) { mlt_keyframe_type type = getKeyframeType(animation, position, keyframeType); m_service.anim_set(qUtf8Printable(name), value, position, duration(), type); emit changed(name); @@ -249,10 +258,11 @@ void QmlFilter::set(QString name, double value, int position, mlt_keyframe_type void QmlFilter::set(QString name, int value, int position, mlt_keyframe_type keyframeType) { - if (!m_service.is_valid()) return; + if (!m_service.is_valid()) + return; if (position < 0) { if (!m_service.get(qUtf8Printable(name)) - || m_service.get_int(qUtf8Printable(name)) != value) { + || m_service.get_int(qUtf8Printable(name)) != value) { int delta = value - m_service.get_int(qUtf8Printable(name)); m_service.set(qUtf8Printable(name), value); emit changed(name); @@ -267,7 +277,7 @@ void QmlFilter::set(QString name, int value, int position, mlt_keyframe_type key // Only set an animation keyframe if it does not already exist with the same value. Mlt::Animation animation(m_service.get_animation(qUtf8Printable(name))); if (!animation.is_valid() || !animation.is_key(position) - || value != m_service.anim_get_int(qUtf8Printable(name), position, duration())) { + || value != m_service.anim_get_int(qUtf8Printable(name), position, duration())) { mlt_keyframe_type type = getKeyframeType(animation, position, keyframeType); m_service.anim_set(qUtf8Printable(name), value, position, duration(), type); emit changed(name); @@ -281,14 +291,21 @@ void QmlFilter::set(QString name, bool value, int position, mlt_keyframe_type ke set(name, value ? 1 : 0, position, keyframeType); } -void QmlFilter::set(QString name, double x, double y, double width, double height, double opacity, - int position, mlt_keyframe_type keyframeType) +void QmlFilter::set(QString name, + double x, + double y, + double width, + double height, + double opacity, + int position, + mlt_keyframe_type keyframeType) { - if (!m_service.is_valid()) return; + if (!m_service.is_valid()) + return; if (position < 0) { mlt_rect rect = m_service.get_rect(qUtf8Printable(name)); - if (!m_service.get(qUtf8Printable(name)) || x != rect.x || y != rect.y - || width != rect.w || height != rect.h || opacity != rect.o) { + if (!m_service.get(qUtf8Printable(name)) || x != rect.x || y != rect.y || width != rect.w + || height != rect.h || opacity != rect.o) { m_service.set(qUtf8Printable(name), x, y, width, height, opacity); emit changed(name); updateUndoCommand(name); @@ -297,8 +314,8 @@ void QmlFilter::set(QString name, double x, double y, double width, double heigh mlt_rect rect = m_service.anim_get_rect(qUtf8Printable(name), position, duration()); // Only set an animation keyframe if it does not already exist with the same value. Mlt::Animation animation(m_service.get_animation(qUtf8Printable(name))); - if (!animation.is_valid() || !animation.is_key(position) - || x != rect.x || y != rect.y || width != rect.w || height != rect.h || opacity != rect.o) { + if (!animation.is_valid() || !animation.is_key(position) || x != rect.x || y != rect.y + || width != rect.w || height != rect.h || opacity != rect.o) { if (animation.key_count() < 1) { // Clear the string value when setting animation for the first time m_service.clear(qUtf8Printable(name)); @@ -318,7 +335,7 @@ void QmlFilter::set(QString name, double x, double y, double width, double heigh void QmlFilter::setGradient(QString name, const QStringList &gradient) { - for (int i = 1; i <= 10; i++) { + for (int i = 1; i <= 10; i++) { QString colorName = name + "." + QString::number(i); if (i <= gradient.length()) { m_service.set(qUtf8Printable(colorName), qUtf8Printable(gradient[i - 1])); @@ -374,8 +391,8 @@ int QmlFilter::savePreset(const QStringList &propertyNames, const QString &name) if (dir.mkdir(objectNameOrService())) dir.cd(objectNameOrService()); } - QString preset = name.isEmpty() ? tr("(defaults)") : QString::fromUtf8(QUrl::toPercentEncoding( - name)); + QString preset = name.isEmpty() ? tr("(defaults)") + : QString::fromUtf8(QUrl::toPercentEncoding(name)); // Convert properties to YAML string. char *yamlStr = properties.serialise_yaml(); QString yaml = yamlStr; @@ -405,7 +422,8 @@ void QmlFilter::deletePreset(const QString &name) void QmlFilter::analyze(bool isAudio, bool deferJob) { // Analyze is only supported for filters, not links. - if (m_service.type() != mlt_service_filter_type) return; + if (m_service.type() != mlt_service_filter_type) + return; Mlt::Filter mltFilter(m_service); Mlt::Service service(mlt_service(mltFilter.get_data("service"))); @@ -420,7 +438,8 @@ void QmlFilter::analyze(bool isAudio, bool deferJob) mltFilter.clear("results"); int disable = mltFilter.get_int("disable"); mltFilter.set("disable", 0); - if (!isAudio) mltFilter.set("analyze", 1); + if (!isAudio) + mltFilter.set("analyze", 1); // Tag the filter with a UUID stored in a shotcut property to uniquely find it later auto uuid = QUuid::createUuid(); @@ -437,7 +456,8 @@ void QmlFilter::analyze(bool isAudio, bool deferJob) for (int i = 0; i < n; i++) { Mlt::Filter filter(*producer.filter(i)); if (filter.get_in() > 0) - filter.set_in_and_out(filter.get_in() - producerIn, filter.get_out() - producerIn); + filter.set_in_and_out(filter.get_in() - producerIn, + filter.get_out() - producerIn); } } } else { @@ -456,7 +476,8 @@ void QmlFilter::analyze(bool isAudio, bool deferJob) service.set("out", out); } - if (!isAudio) mltFilter.set("analyze", 0); + if (!isAudio) + mltFilter.set("analyze", 0); mltFilter.set("disable", disable); // get temp filename for output xml @@ -486,8 +507,10 @@ void QmlFilter::analyze(bool isAudio, bool deferJob) consumerNode.setAttribute("audio_off", 1); consumerNode.setAttribute("resource", tmpTarget->fileName()); - AbstractJob *job = new MeltJob(tmpTarget->fileName(), dom.toString(2), - MLT.profile().frame_rate_num(), MLT.profile().frame_rate_den()); + AbstractJob *job = new MeltJob(tmpTarget->fileName(), + dom.toString(2), + MLT.profile().frame_rate_num(), + MLT.profile().frame_rate_den()); if (job) { AnalyzeDelegate *delegate = new AnalyzeDelegate(mltFilter); connect(job, &AbstractJob::finished, delegate, &AnalyzeDelegate::onAnalyzeFinished); @@ -503,9 +526,7 @@ void QmlFilter::analyze(bool isAudio, bool deferJob) file.write(""); } if (deferJob) { - QTimer::singleShot(0, this, [ = ]() { - JOBS.add(job); - }); + QTimer::singleShot(0, this, [=]() { JOBS.add(job); }); } else { JOBS.add(job); } @@ -530,8 +551,9 @@ int QmlFilter::in() { int result = 0; if (m_service.is_valid()) { - if (m_service.type() == mlt_service_link_type || - (m_service.get_int("in") == 0 && m_service.get_int("out") == 0)) { // undefined/always-on + if (m_service.type() == mlt_service_link_type + || (m_service.get_int("in") == 0 + && m_service.get_int("out") == 0)) { // undefined/always-on if (!m_producer.is_valid()) { result = 0; } else if (m_producer.get(kFilterInProperty)) { @@ -553,8 +575,9 @@ int QmlFilter::out() { int result = 0; if (m_service.is_valid()) { - if (m_service.type() == mlt_service_link_type || - (m_service.get_int("in") == 0 && m_service.get_int("out") == 0)) { // undefined/always-on + if (m_service.type() == mlt_service_link_type + || (m_service.get_int("in") == 0 + && m_service.get_int("out") == 0)) { // undefined/always-on if (!m_producer.is_valid()) { result = 0; } else if (m_producer.get(kFilterOutProperty)) { @@ -692,7 +715,8 @@ void QmlFilter::clearSimpleAnimation(const QString &name) void QmlFilter::preset(const QString &name) { - if (!m_service.is_valid()) return; + if (!m_service.is_valid()) + return; QDir dir(Settings.appDataLocation()); if (!dir.cd("presets") || !dir.cd(objectNameOrService())) @@ -721,7 +745,8 @@ void QmlFilter::preset(const QString &name) if (isYaml) { // Load from YAML file. - QScopedPointer properties(Mlt::Properties::parse_yaml(qUtf8Printable(fileName))); + QScopedPointer properties( + Mlt::Properties::parse_yaml(qUtf8Printable(fileName))); if (properties && properties->is_valid()) { QChar decimalPoint = MLT.decimalPoint(); for (int i = 0; i < properties->count(); i++) { @@ -745,7 +770,8 @@ void QmlFilter::preset(const QString &name) QString QmlFilter::objectNameOrService() { - return m_metadata->objectName().isEmpty() ? m_metadata->mlt_service() : m_metadata->objectName(); + return m_metadata->objectName().isEmpty() ? m_metadata->mlt_service() + : m_metadata->objectName(); } int QmlFilter::keyframeIndex(Mlt::Animation &animation, int position) @@ -778,56 +804,62 @@ void QmlFilter::startUndoTracking() void QmlFilter::startUndoParameterCommand(const QString &desc) { if (!m_previousState.count()) { -// LOG_DEBUG() << "Undo tracking has not started yet"; + // LOG_DEBUG() << "Undo tracking has not started yet"; return; } m_changeInProgress++; if (m_changeInProgress > 1) { -// LOG_DEBUG() << "Nested change command" << m_changeInProgress; + // LOG_DEBUG() << "Nested change command" << m_changeInProgress; return; } auto command = new Filter::UndoParameterCommand(m_metadata->name(), - MAIN.filterController(), MAIN.filterController()->currentIndex(), m_previousState, desc); + MAIN.filterController(), + MAIN.filterController()->currentIndex(), + m_previousState, + desc); MAIN.undoStack()->push(command); } void QmlFilter::startUndoAddKeyframeCommand() { if (!m_previousState.count()) { -// LOG_DEBUG() << "Undo tracking has not started yet"; + // LOG_DEBUG() << "Undo tracking has not started yet"; return; } m_changeInProgress++; if (m_changeInProgress > 1) { -// LOG_DEBUG() << "Nested change command" << m_changeInProgress; + // LOG_DEBUG() << "Nested change command" << m_changeInProgress; return; } auto command = new Filter::UndoAddKeyframeCommand(m_metadata->name(), - MAIN.filterController(), MAIN.filterController()->currentIndex(), m_previousState); + MAIN.filterController(), + MAIN.filterController()->currentIndex(), + m_previousState); MAIN.undoStack()->push(command); } void QmlFilter::startUndoRemoveKeyframeCommand() { if (!m_previousState.count()) { -// LOG_DEBUG() << "Undo tracking has not started yet"; + // LOG_DEBUG() << "Undo tracking has not started yet"; return; } m_changeInProgress++; if (m_changeInProgress > 1) { -// LOG_DEBUG() << "Nested change command" << m_changeInProgress; + // LOG_DEBUG() << "Nested change command" << m_changeInProgress; return; } - auto command = new Filter::UndoRemoveKeyframeCommand( - m_metadata->name(), MAIN.filterController(), MAIN.filterController()->currentIndex(), - m_previousState); + auto command = new Filter::UndoRemoveKeyframeCommand(m_metadata->name(), + MAIN.filterController(), + MAIN.filterController()->currentIndex(), + m_previousState); MAIN.undoStack()->push(command); } void QmlFilter::startUndoModifyKeyframeCommand(int paramIndex, int keyframeIndex) { if (!m_previousState.count()) { -// LOG_DEBUG() << "Undo tracking has not started yet"; + // LOG_DEBUG() << "Undo tracking has not started yet"; return; } m_changeInProgress++; @@ -835,16 +867,19 @@ void QmlFilter::startUndoModifyKeyframeCommand(int paramIndex, int keyframeIndex // LOG_DEBUG() << "Nested change command" << m_changeInProgress; return; } - auto command = new Filter::UndoModifyKeyframeCommand( - m_metadata->name(), MAIN.filterController(), MAIN.filterController()->currentIndex(), - m_previousState, paramIndex, keyframeIndex); + auto command = new Filter::UndoModifyKeyframeCommand(m_metadata->name(), + MAIN.filterController(), + MAIN.filterController()->currentIndex(), + m_previousState, + paramIndex, + keyframeIndex); MAIN.undoStack()->push(command); } void QmlFilter::updateUndoCommand(const QString &name) { if (!m_previousState.count()) { -// LOG_DEBUG() << "Undo tracking has not started yet"; + // LOG_DEBUG() << "Undo tracking has not started yet"; return; } if (!m_changeInProgress) { @@ -852,8 +887,8 @@ void QmlFilter::updateUndoCommand(const QString &name) } const QUndoCommand *lastCommand = MAIN.undoStack()->command(MAIN.undoStack()->count() - 1); - Filter::UndoParameterCommand *command = dynamic_cast - (const_cast(lastCommand)); + Filter::UndoParameterCommand *command = dynamic_cast( + const_cast(lastCommand)); if (command) { // Update the change that is already in progress command->update(name); @@ -867,7 +902,7 @@ void QmlFilter::updateUndoCommand(const QString &name) void QmlFilter::endUndoCommand() { if (!m_previousState.count()) { -// LOG_DEBUG() << "Undo tracking has not started yet"; + // LOG_DEBUG() << "Undo tracking has not started yet"; return; } if (!m_changeInProgress) { @@ -877,7 +912,8 @@ void QmlFilter::endUndoCommand() m_changeInProgress--; } -mlt_keyframe_type QmlFilter::getKeyframeType(Mlt::Animation &animation, int position, +mlt_keyframe_type QmlFilter::getKeyframeType(Mlt::Animation &animation, + int position, mlt_keyframe_type defaultType) { mlt_keyframe_type result = mlt_keyframe_linear; @@ -900,13 +936,13 @@ mlt_keyframe_type QmlFilter::getKeyframeType(Mlt::Animation &animation, int posi int QmlFilter::getKeyFrameType(const QString &name, int keyIndex) { Mlt::Animation animation = getAnimation(name); - return (int)animation.key_get_type(keyIndex); + return (int) animation.key_get_type(keyIndex); } void QmlFilter::setKeyFrameType(const QString &name, int keyIndex, int type) { Mlt::Animation animation = getAnimation(name); - animation.key_set_type(keyIndex, (mlt_keyframe_type)type); + animation.key_set_type(keyIndex, (mlt_keyframe_type) type); } int QmlFilter::getNextKeyframePosition(const QString &name, int position) @@ -1000,8 +1036,7 @@ void QmlFilter::crop(const QRectF &rect) AnalyzeDelegate::AnalyzeDelegate(Mlt::Filter &filter) : QObject(nullptr) , m_uuid(filter.get(kShotcutHashProperty)) -{ -} +{} class FindFilterParser : public Mlt::Parser { @@ -1015,10 +1050,7 @@ class FindFilterParser : public Mlt::Parser , m_uuid(uuid) {} - QList &filters() - { - return m_filters; - } + QList &filters() { return m_filters; } int on_start_filter(Mlt::Filter *filter) { @@ -1027,74 +1059,23 @@ class FindFilterParser : public Mlt::Parser m_filters << Mlt::Filter(*filter); return 0; } - int on_start_producer(Mlt::Producer *) - { - return 0; - } - int on_end_producer(Mlt::Producer *) - { - return 0; - } - int on_start_playlist(Mlt::Playlist *) - { - return 0; - } - int on_end_playlist(Mlt::Playlist *) - { - return 0; - } - int on_start_tractor(Mlt::Tractor *) - { - return 0; - } - int on_end_tractor(Mlt::Tractor *) - { - return 0; - } - int on_start_multitrack(Mlt::Multitrack *) - { - return 0; - } - int on_end_multitrack(Mlt::Multitrack *) - { - return 0; - } - int on_start_track() - { - return 0; - } - int on_end_track() - { - return 0; - } - int on_end_filter(Mlt::Filter *) - { - return 0; - } - int on_start_transition(Mlt::Transition *) - { - return 0; - } - int on_end_transition(Mlt::Transition *) - { - return 0; - } - int on_start_chain(Mlt::Chain *) - { - return 0; - } - int on_end_chain(Mlt::Chain *) - { - return 0; - } - int on_start_link(Mlt::Link *) - { - return 0; - } - int on_end_link(Mlt::Link *) - { - return 0; - } + int on_start_producer(Mlt::Producer *) { return 0; } + int on_end_producer(Mlt::Producer *) { return 0; } + int on_start_playlist(Mlt::Playlist *) { return 0; } + int on_end_playlist(Mlt::Playlist *) { return 0; } + int on_start_tractor(Mlt::Tractor *) { return 0; } + int on_end_tractor(Mlt::Tractor *) { return 0; } + int on_start_multitrack(Mlt::Multitrack *) { return 0; } + int on_end_multitrack(Mlt::Multitrack *) { return 0; } + int on_start_track() { return 0; } + int on_end_track() { return 0; } + int on_end_filter(Mlt::Filter *) { return 0; } + int on_start_transition(Mlt::Transition *) { return 0; } + int on_end_transition(Mlt::Transition *) { return 0; } + int on_start_chain(Mlt::Chain *) { return 0; } + int on_end_chain(Mlt::Chain *) { return 0; } + int on_start_link(Mlt::Link *) { return 0; } + int on_end_link(Mlt::Link *) { return 0; } }; void AnalyzeDelegate::updateJob(EncodeJob *job, const QString &results) @@ -1118,7 +1099,7 @@ void AnalyzeDelegate::updateJob(EncodeJob *job, const QString &results) for (int j = 0; j < properties.size(); j++) { QDomNode propertyNode = properties.at(j); if (propertyNode.attributes().namedItem("name").toAttr().value() == kShotcutHashProperty - && propertyNode.toElement().text() == m_uuid.toString()) { + && propertyNode.toElement().text() == m_uuid.toString()) { // found a matching filter found = true; break; @@ -1216,7 +1197,7 @@ QString AnalyzeDelegate::resultsFromXml(const QString &fileName) for (int j = 0; j < properties.size(); j++) { QDomNode propertyNode = properties.at(j); if (propertyNode.attributes().namedItem("name").toAttr().value() == kShotcutHashProperty - && propertyNode.toElement().text() == m_uuid.toString()) { + && propertyNode.toElement().text() == m_uuid.toString()) { found = true; break; } diff --git a/src/qmltypes/qmlfilter.h b/src/qmltypes/qmlfilter.h index e71ef75bd5..c1df1579cd 100644 --- a/src/qmltypes/qmlfilter.h +++ b/src/qmltypes/qmlfilter.h @@ -18,18 +18,18 @@ #ifndef FILTER_H #define FILTER_H +#include "qmlmetadata.h" +#include "shotcut_mlt_properties.h" + +#include +#include +#include +#include #include -#include -#include #include +#include #include -#include -#include -#include -#include - -#include "qmlmetadata.h" -#include "shotcut_mlt_properties.h" +#include class AbstractJob; class EncodeJob; @@ -50,25 +50,17 @@ class QmlFilter : public QObject Q_PROPERTY(bool blockSignals READ signalsBlocked WRITE blockSignals) public: - enum CurrentFilterIndex { - NoCurrentFilter = -1, - DeselectCurrentFilter = -2 - }; + enum CurrentFilterIndex { NoCurrentFilter = -1, DeselectCurrentFilter = -2 }; Q_ENUM(CurrentFilterIndex) explicit QmlFilter(); - explicit QmlFilter(Mlt::Service &mltService, const QmlMetadata *metadata, + explicit QmlFilter(Mlt::Service &mltService, + const QmlMetadata *metadata, QObject *parent = nullptr); ~QmlFilter(); - bool isNew() const - { - return m_isNew; - } - void setIsNew(bool isNew) - { - m_isNew = isNew; - } + bool isNew() const { return m_isNew; } + void setIsNew(bool isNew) { m_isNew = isNew; } Q_INVOKABLE QString get(QString name, int position = -1); Q_INVOKABLE QColor getColor(QString name, int position = -1); @@ -77,45 +69,48 @@ class QmlFilter : public QObject Q_INVOKABLE void removeRectPercents(QString name); Q_INVOKABLE QStringList getGradient(QString name); Q_INVOKABLE void set(QString name, QString value, int position = -1); - Q_INVOKABLE void set(QString name, const QColor &value, - int position = -1, mlt_keyframe_type keyframeType = mlt_keyframe_type(-1)); - Q_INVOKABLE void set(QString name, double value, - int position = -1, mlt_keyframe_type keyframeType = mlt_keyframe_type(-1)); - Q_INVOKABLE void set(QString name, int value, - int position = -1, mlt_keyframe_type keyframeType = mlt_keyframe_type(-1)); - Q_INVOKABLE void set(QString name, bool value, - int position = -1, mlt_keyframe_type keyframeType = mlt_keyframe_type(-1)); - Q_INVOKABLE void set(QString name, double x, double y, double width, double height, + Q_INVOKABLE void set(QString name, + const QColor &value, + int position = -1, + mlt_keyframe_type keyframeType = mlt_keyframe_type(-1)); + Q_INVOKABLE void set(QString name, + double value, + int position = -1, + mlt_keyframe_type keyframeType = mlt_keyframe_type(-1)); + Q_INVOKABLE void set(QString name, + int value, + int position = -1, + mlt_keyframe_type keyframeType = mlt_keyframe_type(-1)); + Q_INVOKABLE void set(QString name, + bool value, + int position = -1, + mlt_keyframe_type keyframeType = mlt_keyframe_type(-1)); + Q_INVOKABLE void set(QString name, + double x, + double y, + double width, + double height, double opacity = 1.0, - int position = -1, mlt_keyframe_type keyframeType = mlt_keyframe_type(-1)); - Q_INVOKABLE void set(QString name, const QRectF &rect, - int position = -1, mlt_keyframe_type keyframeType = mlt_keyframe_type(-1)); + int position = -1, + mlt_keyframe_type keyframeType = mlt_keyframe_type(-1)); + Q_INVOKABLE void set(QString name, + const QRectF &rect, + int position = -1, + mlt_keyframe_type keyframeType = mlt_keyframe_type(-1)); Q_INVOKABLE void setGradient(QString name, const QStringList &gradient); - QString path() const - { - return m_path; - } + QString path() const { return m_path; } Q_INVOKABLE void loadPresets(); - QStringList presets() const - { - return m_presets; - } + QStringList presets() const { return m_presets; } /// returns the index of the new preset - Q_INVOKABLE int savePreset(const QStringList &propertyNames, const QString &name = QString()); + Q_INVOKABLE int savePreset(const QStringList &propertyNames, const QString &name = QString()); Q_INVOKABLE void deletePreset(const QString &name); Q_INVOKABLE void analyze(bool isAudio = false, bool deferJob = true); Q_INVOKABLE static int framesFromTime(const QString &time); Q_INVOKABLE void getHash(); - Mlt::Producer &producer() - { - return m_producer; - } + Mlt::Producer &producer() { return m_producer; } int in(); int out(); - Mlt::Service &service() - { - return m_service; - } + Mlt::Service &service() { return m_service; } int animateIn(); void setAnimateIn(int value); int animateOut(); @@ -126,7 +121,8 @@ class QmlFilter : public QObject Q_INVOKABLE void clearSimpleAnimation(const QString &name); Mlt::Animation getAnimation(const QString &name); Q_INVOKABLE int keyframeCount(const QString &name); - mlt_keyframe_type getKeyframeType(Mlt::Animation &animation, int position, + mlt_keyframe_type getKeyframeType(Mlt::Animation &animation, + int position, mlt_keyframe_type defaultType); Q_INVOKABLE int getKeyFrameType(const QString &name, int keyIndex); Q_INVOKABLE void setKeyFrameType(const QString &name, int keyIndex, int type); diff --git a/src/qmltypes/qmlmarkermenu.cpp b/src/qmltypes/qmlmarkermenu.cpp index 3b3796f316..960f572b6f 100644 --- a/src/qmltypes/qmlmarkermenu.cpp +++ b/src/qmltypes/qmlmarkermenu.cpp @@ -31,8 +31,7 @@ QmlMarkerMenu::QmlMarkerMenu(QObject *parent) : QObject(parent) , m_timeline(nullptr) , m_index(-1) -{ -} +{} QObject *QmlMarkerMenu::target() { @@ -62,16 +61,12 @@ void QmlMarkerMenu::popup() QAction editAction(tr("Edit...")); editAction.setShortcut(Actions["timelineMarkerAction"]->shortcut()); - connect(&editAction, &QAction::triggered, this, [&]() { - m_timeline->editMarker(m_index); - }); + connect(&editAction, &QAction::triggered, this, [&]() { m_timeline->editMarker(m_index); }); menu.addAction(&editAction); QAction deleteAction(tr("Delete")); deleteAction.setShortcut(Actions["timelineDeleteMarkerAction"]->shortcut()); - connect(&deleteAction, &QAction::triggered, this, [&]() { - m_timeline->deleteMarker(m_index); - }); + connect(&deleteAction, &QAction::triggered, this, [&]() { m_timeline->deleteMarker(m_index); }); menu.addAction(&deleteAction); QAction colorAction(tr("Choose Color...")); @@ -96,24 +91,25 @@ void QmlMarkerMenu::popup() QToolButton *colorButton = new QToolButton(); colorButton->setText(colors[c]); QString textColor = QmlApplication::contrastingColor(colors[c]).name(); - QString styleSheet = QString( - "QToolButton {" - " background-color: %1;" - " border-style: solid;" - " border-width: 3px;" - " border-color: %1;" - " color: %2" - "}" - "QToolButton:hover {" - " background-color: %1;" - " border-style: solid;" - " border-width: 3px;" - " border-color: %3;" - " color: %2" - "}" - ).arg(colors[c]).arg(textColor).arg(highlightColor); + QString styleSheet = QString("QToolButton {" + " background-color: %1;" + " border-style: solid;" + " border-width: 3px;" + " border-color: %1;" + " color: %2" + "}" + "QToolButton:hover {" + " background-color: %1;" + " border-style: solid;" + " border-width: 3px;" + " border-color: %3;" + " color: %2" + "}") + .arg(colors[c]) + .arg(textColor) + .arg(highlightColor); colorButton->setStyleSheet(styleSheet); - connect(colorButton, &QToolButton::clicked, this, [ &, colorButton]() { + connect(colorButton, &QToolButton::clicked, this, [&, colorButton]() { m_timeline->markersModel()->setColor(m_index, colorButton->text()); menu.close(); }); diff --git a/src/qmltypes/qmlmetadata.cpp b/src/qmltypes/qmlmetadata.cpp index 8100754784..24fdd55a38 100644 --- a/src/qmltypes/qmlmetadata.cpp +++ b/src/qmltypes/qmlmetadata.cpp @@ -16,8 +16,10 @@ */ #include "qmlmetadata.h" + +#include "Logger.h" #include "settings.h" -#include + #include QmlMetadata::QmlMetadata(QObject *parent) @@ -37,8 +39,7 @@ QmlMetadata::QmlMetadata(QObject *parent) , m_isGpuCompatible(true) , m_isDeprecated(false) , m_seekReverse(false) -{ -} +{} void QmlMetadata::loadSettings() { @@ -191,8 +192,7 @@ QmlKeyframesMetadata::QmlKeyframesMetadata(QObject *parent) , m_allowAnimateOut(false) , m_enabled(true) , m_allowOvershoot(true) -{ -} +{} QmlKeyframesParameter *QmlKeyframesMetadata::parameter(const QString &propertyName) const { @@ -226,5 +226,4 @@ QmlKeyframesParameter::QmlKeyframesParameter(QObject *parent) , m_isRectangle(false) , m_rangeType(MinMax) , m_isColor(false) -{ -} +{} diff --git a/src/qmltypes/qmlmetadata.h b/src/qmltypes/qmlmetadata.h index caf15e9f5b..29c2f40820 100644 --- a/src/qmltypes/qmlmetadata.h +++ b/src/qmltypes/qmlmetadata.h @@ -18,11 +18,11 @@ #ifndef QMLMETADATA_H #define QMLMETADATA_H +#include #include +#include #include -#include #include -#include class QmlKeyframesParameter : public QObject { @@ -46,46 +46,16 @@ class QmlKeyframesParameter : public QObject Q_ENUM(RangeType) explicit QmlKeyframesParameter(QObject *parent = 0); - QString name() const - { - return m_name; - } - QString property() const - { - return m_property; - } - QStringList gangedProperties() const - { - return m_gangedProperties; - } - bool isCurve() const - { - return m_isCurve; - } - double minimum() const - { - return m_minimum; - } - double maximum() const - { - return m_maximum; - } - QString units() const - { - return m_units; - } - bool isRectangle() const - { - return m_isRectangle; - } - RangeType rangeType() const - { - return m_rangeType; - } - bool isColor() const - { - return m_isColor; - } + QString name() const { return m_name; } + QString property() const { return m_property; } + QStringList gangedProperties() const { return m_gangedProperties; } + bool isCurve() const { return m_isCurve; } + double minimum() const { return m_minimum; } + double maximum() const { return m_maximum; } + QString units() const { return m_units; } + bool isRectangle() const { return m_isRectangle; } + RangeType rangeType() const { return m_rangeType; } + bool isColor() const { return m_isColor; } signals: void changed(); @@ -119,38 +89,17 @@ class QmlKeyframesMetadata : public QObject public: explicit QmlKeyframesMetadata(QObject *parent = 0); - bool allowTrim() const - { - return m_allowTrim; - } - bool allowAnimateIn() const - { - return m_allowAnimateIn; - } - bool allowAnimateOut() const - { - return m_allowAnimateOut; - } - QList simpleProperties() const - { - return m_simpleProperties; - } - bool allowOvershoot() const - { - return m_allowOvershoot; - } + bool allowTrim() const { return m_allowTrim; } + bool allowAnimateIn() const { return m_allowAnimateIn; } + bool allowAnimateOut() const { return m_allowAnimateOut; } + QList simpleProperties() const { return m_simpleProperties; } + bool allowOvershoot() const { return m_allowOvershoot; } QQmlListProperty parameters() { return QQmlListProperty(this, &m_parameters); } - int parameterCount() const - { - return m_parameters.count(); - } - QmlKeyframesParameter *parameter(int index) const - { - return m_parameters[index]; - } + int parameterCount() const { return m_parameters.count(); } + QmlKeyframesParameter *parameter(int index) const { return m_parameters[index]; } Q_INVOKABLE QmlKeyframesParameter *parameter(const QString &propertyName) const; void checkVersion(const QString &version); void setDisabled(); @@ -169,7 +118,6 @@ class QmlKeyframesMetadata : public QObject bool m_allowOvershoot; }; - class QmlMetadata : public QObject { Q_OBJECT @@ -211,123 +159,55 @@ class QmlMetadata : public QObject explicit QmlMetadata(QObject *parent = 0); void loadSettings(); - PluginType type() const - { - return m_type; - } + PluginType type() const { return m_type; } void setType(PluginType); - QString name() const - { - return m_name; - } + QString name() const { return m_name; } void setName(const QString &); - QString mlt_service() const - { - return m_mlt_service; - } + QString mlt_service() const { return m_mlt_service; } void set_mlt_service(const QString &); QString uniqueId() const; - bool needsGPU() const - { - return m_needsGPU; - } + bool needsGPU() const { return m_needsGPU; } void setNeedsGPU(bool); - QString qmlFileName() const - { - return m_qmlFileName; - } + QString qmlFileName() const { return m_qmlFileName; } void setQmlFileName(const QString &); - QString vuiFileName() const - { - return m_vuiFileName; - } + QString vuiFileName() const { return m_vuiFileName; } void setVuiFileName(const QString &); - QDir path() const - { - return m_path; - } + QDir path() const { return m_path; } void setPath(const QDir &path); QUrl qmlFilePath() const; QUrl vuiFilePath() const; QString iconFilePath() const { - return (m_icon.isEmpty() || m_icon.startsWith("qrc:")) ? m_icon : - QUrl::fromLocalFile(m_path.absoluteFilePath(m_icon)).toString(); + return (m_icon.isEmpty() || m_icon.startsWith("qrc:")) + ? m_icon + : QUrl::fromLocalFile(m_path.absoluteFilePath(m_icon)).toString(); } void setIconFileName(const QString &); - bool isAudio() const - { - return m_isAudio; - } + bool isAudio() const { return m_isAudio; } void setIsAudio(bool isAudio); - bool isHidden() const - { - return m_isHidden; - } + bool isHidden() const { return m_isHidden; } void setIsHidden(bool isHidden); - bool isFavorite() const - { - return m_isFavorite; - } + bool isFavorite() const { return m_isFavorite; } void setIsFavorite(bool isFavorite); - QString gpuAlt() const - { - return m_gpuAlt; - } + QString gpuAlt() const { return m_gpuAlt; } void setGpuAlt(const QString &); - bool allowMultiple() const - { - return m_allowMultiple; - } + bool allowMultiple() const { return m_allowMultiple; } void setAllowMultiple(bool allowMultiple); - bool isClipOnly() const - { - return m_isClipOnly; - } + bool isClipOnly() const { return m_isClipOnly; } void setIsClipOnly(bool isClipOnly); - bool isTrackOnly() const - { - return m_isTrackOnly; - } + bool isTrackOnly() const { return m_isTrackOnly; } void setIsTrackOnly(bool isTrackOnly); - bool isOutputOnly() const - { - return m_isOutputOnly; - } + bool isOutputOnly() const { return m_isOutputOnly; } void setIsOutputOnly(bool isOutputOnly); - bool isGpuCompatible() const - { - return m_isGpuCompatible; - } - void setIsGpuCompatible(bool isCompatible) - { - m_isGpuCompatible = isCompatible; - } - QmlKeyframesMetadata *keyframes() - { - return &m_keyframes; - } - const QmlKeyframesMetadata *keyframes() const - { - return &m_keyframes; - } - bool isDeprecated() const - { - return m_isDeprecated; - } - void setIsDeprecated(bool deprecated) - { - m_isDeprecated = deprecated; - } + bool isGpuCompatible() const { return m_isGpuCompatible; } + void setIsGpuCompatible(bool isCompatible) { m_isGpuCompatible = isCompatible; } + QmlKeyframesMetadata *keyframes() { return &m_keyframes; } + const QmlKeyframesMetadata *keyframes() const { return &m_keyframes; } + bool isDeprecated() const { return m_isDeprecated; } + void setIsDeprecated(bool deprecated) { m_isDeprecated = deprecated; } bool isMltVersion(const QString &version); - QString keywords() const - { - return m_keywords; - } - bool seekReverse() const - { - return m_seekReverse; - } + QString keywords() const { return m_keywords; } + bool seekReverse() const { return m_seekReverse; } signals: void changed(); diff --git a/src/qmltypes/qmlproducer.cpp b/src/qmltypes/qmlproducer.cpp index f8dec6b41c..8aa6eb9597 100644 --- a/src/qmltypes/qmlproducer.cpp +++ b/src/qmltypes/qmlproducer.cpp @@ -16,21 +16,21 @@ */ #include "qmlproducer.h" + +#include "Logger.h" +#include "mainwindow.h" #include "mltcontroller.h" -#include "util.h" #include "models/audiolevelstask.h" -#include "mainwindow.h" #include "qmltypes/qmlapplication.h" -#include "widgets/glaxnimateproducerwidget.h" #include "settings.h" -#include +#include "util.h" +#include "widgets/glaxnimateproducerwidget.h" static const char *kWidthProperty = "meta.media.width"; static const char *kHeightProperty = "meta.media.height"; static const char *kAspectNumProperty = "meta.media.sample_aspect_num"; static const char *kAspectDenProperty = "meta.media.sample_aspect_den"; - QmlProducer::QmlProducer(QObject *parent) : QObject(parent) { @@ -40,7 +40,8 @@ QmlProducer::QmlProducer(QObject *parent) int QmlProducer::in() { - if (!m_producer.is_valid()) return 0; + if (!m_producer.is_valid()) + return 0; if (m_producer.get(kFilterInProperty)) // Shots on the timeline will set the producer to the cut parent. // However, we want time-based filters such as fade in/out to use @@ -52,7 +53,8 @@ int QmlProducer::in() int QmlProducer::out() { - if (!m_producer.is_valid()) return 0; + if (!m_producer.is_valid()) + return 0; if (m_producer.get(kFilterOutProperty)) // Shots on the timeline will set the producer to the cut parent. // However, we want time-based filters such as fade in/out to use @@ -64,12 +66,13 @@ int QmlProducer::out() double QmlProducer::aspectRatio() { - if (!m_producer.is_valid()) return 1.0; + if (!m_producer.is_valid()) + return 1.0; if (m_producer.get(kHeightProperty)) { double sar = 1.0; if (m_producer.get(kAspectDenProperty)) { - sar = m_producer.get_double(kAspectNumProperty) / - m_producer.get_double(kAspectDenProperty); + sar = m_producer.get_double(kAspectNumProperty) + / m_producer.get_double(kAspectDenProperty); } return sar * m_producer.get_double(kWidthProperty) / m_producer.get_double(kHeightProperty); } @@ -78,7 +81,8 @@ double QmlProducer::aspectRatio() QString QmlProducer::resource() { - if (!m_producer.is_valid()) return QString(); + if (!m_producer.is_valid()) + return QString(); QString result = QString::fromUtf8(m_producer.get("resource")); if (result == "" && m_producer.get("mlt_service")) result = QString::fromUtf8(m_producer.get("mlt_service")); @@ -92,7 +96,8 @@ QString QmlProducer::name() QVariant QmlProducer::audioLevels() { - if (!m_producer.is_valid()) return QVariant(); + if (!m_producer.is_valid()) + return QVariant(); if (m_producer.get_data(kAudioLevelsProperty)) return QVariant::fromValue(*((QVariantList *) m_producer.get_data(kAudioLevelsProperty))); else @@ -101,7 +106,8 @@ QVariant QmlProducer::audioLevels() int QmlProducer::fadeIn() { - if (!m_producer.is_valid()) return 0; + if (!m_producer.is_valid()) + return 0; QScopedPointer filter(MLT.getFilter("fadeInVolume", &m_producer)); if (!filter || !filter->is_valid()) filter.reset(MLT.getFilter("fadeInBrightness", &m_producer)); @@ -112,7 +118,8 @@ int QmlProducer::fadeIn() int QmlProducer::fadeOut() { - if (!m_producer.is_valid()) return 0; + if (!m_producer.is_valid()) + return 0; QScopedPointer filter(MLT.getFilter("fadeOutVolume", &m_producer)); if (!filter || !filter->is_valid()) filter.reset(MLT.getFilter("fadeOutBrightness", &m_producer)); @@ -124,7 +131,8 @@ int QmlProducer::fadeOut() double QmlProducer::speed() { double result = 1.0; - if (!m_producer.is_valid()) return result; + if (!m_producer.is_valid()) + return result; if (m_producer.is_valid()) { if (!qstrcmp("timewarp", m_producer.get("mlt_service"))) result = m_producer.get_double("warp_speed"); @@ -134,7 +142,8 @@ double QmlProducer::speed() void QmlProducer::setPosition(int position) { - if (!m_producer.is_valid()) return; + if (!m_producer.is_valid()) + return; int length = duration(); if (position < length) { if (MLT.isMultitrack()) @@ -194,8 +203,8 @@ double QmlProducer::displayAspectRatio() if (m_producer.is_valid() && m_producer.get(kHeightProperty)) { double sar = 1.0; if (m_producer.get(kAspectDenProperty)) { - sar = m_producer.get_double(kAspectNumProperty) / - m_producer.get_double(kAspectDenProperty); + sar = m_producer.get_double(kAspectNumProperty) + / m_producer.get_double(kAspectDenProperty); } return sar * m_producer.get_double(kWidthProperty) / m_producer.get_double(kHeightProperty); } @@ -208,7 +217,8 @@ QString QmlProducer::get(QString name, int position) if (position < 0) return QString::fromUtf8(m_producer.get(name.toUtf8().constData())); else - return QString::fromUtf8(m_producer.anim_get(name.toUtf8().constData(), position, duration())); + return QString::fromUtf8( + m_producer.anim_get(name.toUtf8().constData(), position, duration())); } else { return QString(); } @@ -228,7 +238,8 @@ double QmlProducer::getDouble(QString name, int position) QRectF QmlProducer::getRect(QString name, int position) { - if (!m_producer.is_valid()) return QRectF(); + if (!m_producer.is_valid()) + return QRectF(); QString s = QString::fromUtf8(m_producer.get(name.toUtf8().constData())); if (!s.isEmpty()) { mlt_rect rect; @@ -263,4 +274,3 @@ void QmlProducer::setProducer(Mlt::Producer &producer) emit outChanged(0); emit lengthChanged(); } - diff --git a/src/qmltypes/qmlproducer.h b/src/qmltypes/qmlproducer.h index 08bb7acad6..be8b07d3de 100644 --- a/src/qmltypes/qmlproducer.h +++ b/src/qmltypes/qmlproducer.h @@ -18,13 +18,13 @@ #ifndef QMLPRODUCER_H #define QMLPRODUCER_H +#include "shotcut_mlt_properties.h" + +#include #include +#include #include #include -#include - -#include -#include "shotcut_mlt_properties.h" class QmlProducer : public QObject { @@ -51,14 +51,8 @@ class QmlProducer : public QObject int in(); int out(); double aspectRatio(); - int duration() - { - return m_producer.is_valid() ? out() - in() + 1 : 0; - } - int length() - { - return m_producer.is_valid() ? m_producer.get_length() : 0; - } + int duration() { return m_producer.is_valid() ? out() - in() + 1 : 0; } + int length() { return m_producer.is_valid() ? m_producer.get_length() : 0; } QString resource(); QString mlt_service() { @@ -73,16 +67,10 @@ class QmlProducer : public QObject int fadeIn(); int fadeOut(); double speed(); - int position() const - { - return m_position; - } + int position() const { return m_position; } void setPosition(int position); void seek(int position); - Mlt::Producer &producer() - { - return m_producer; - } + Mlt::Producer &producer() { return m_producer; } Q_INVOKABLE void audioLevelsReady(const QPersistentModelIndex &index); Q_INVOKABLE void remakeAudioLevels(); double displayAspectRatio(); diff --git a/src/qmltypes/qmlprofile.cpp b/src/qmltypes/qmlprofile.cpp index e3d0b0c9e4..2443c85525 100644 --- a/src/qmltypes/qmlprofile.cpp +++ b/src/qmltypes/qmlprofile.cpp @@ -17,6 +17,7 @@ */ #include "qmlprofile.h" + #include "mltcontroller.h" QmlProfile &QmlProfile::singleton() @@ -25,10 +26,9 @@ QmlProfile &QmlProfile::singleton() return instance; } -QmlProfile::QmlProfile() : - QObject() -{ -} +QmlProfile::QmlProfile() + : QObject() +{} int QmlProfile::width() const { diff --git a/src/qmltypes/qmlrichtext.cpp b/src/qmltypes/qmlrichtext.cpp index 338226ac47..d362e0ceb1 100644 --- a/src/qmltypes/qmlrichtext.cpp +++ b/src/qmltypes/qmlrichtext.cpp @@ -32,16 +32,17 @@ ****************************************************************************/ #include "qmlrichtext.h" -#include -#include -#include -#include -#include -#include +#include "Logger.h" + #include +#include #include #include +#include +#include +#include +#include QmlRichText::QmlRichText() : m_target(0) @@ -49,8 +50,7 @@ QmlRichText::QmlRichText() , m_cursorPosition(-1) , m_selectionStart(0) , m_selectionEnd(0) -{ -} +{} void QmlRichText::setTarget(QQuickItem *target) { @@ -80,25 +80,29 @@ void QmlRichText::setFileUrl(const QUrl &arg) if (file.open(QFile::ReadOnly)) { QByteArray data = file.readAll(); if (Qt::mightBeRichText(data)) { - auto decoder = QStringDecoder(QStringConverter::encodingForHtml(data).value_or( - QStringConverter::Utf8)); + auto decoder = QStringDecoder( + QStringConverter::encodingForHtml(data).value_or(QStringConverter::Utf8)); setText(decoder(data)); } else { - auto decoder = QStringDecoder(QStringConverter::encodingForData(data).value_or( - QStringConverter::Utf8)); - setText(QStringLiteral("" - "") - % QString(decoder(data)) - % QStringLiteral("")); + % QString(decoder(data)) % QStringLiteral("")); } if (m_doc) m_doc->setModified(false); @@ -149,17 +153,18 @@ void QmlRichText::insertTable(int rows, int columns, int border) if (cursor.isNull()) return; QString color = textColor().name(QColor::HexArgb); - QString html = QString( - "" - "") - .arg(color) - .arg(italic() ? "italic" : "normal").arg(bold() ? "bold" : "normal").arg(fontSize()).arg( - fontFamily()) - .arg(border); + QString html = QString("" + "
") + .arg(color) + .arg(italic() ? "italic" : "normal") + .arg(bold() ? "bold" : "normal") + .arg(fontSize()) + .arg(fontFamily()) + .arg(border); for (auto i = 0; i < rows; ++i) { html += ""; for (auto j = 0; j < columns; ++j) { diff --git a/src/qmltypes/qmlrichtext.h b/src/qmltypes/qmlrichtext.h index c7424874e6..628e3a9efc 100644 --- a/src/qmltypes/qmlrichtext.h +++ b/src/qmltypes/qmlrichtext.h @@ -35,9 +35,7 @@ #define QMLRICHTEXT_H #include - #include - #include QT_BEGIN_NAMESPACE @@ -51,10 +49,10 @@ class QmlRichText : public QObject Q_ENUMS(HAlignment) Q_PROPERTY(QQuickItem *target READ target WRITE setTarget NOTIFY targetChanged) - Q_PROPERTY(int cursorPosition READ cursorPosition WRITE setCursorPosition NOTIFY - cursorPositionChanged) - Q_PROPERTY(int selectionStart READ selectionStart WRITE setSelectionStart NOTIFY - selectionStartChanged) + Q_PROPERTY( + int cursorPosition READ cursorPosition WRITE setCursorPosition NOTIFY cursorPositionChanged) + Q_PROPERTY( + int selectionStart READ selectionStart WRITE setSelectionStart NOTIFY selectionStartChanged) Q_PROPERTY(int selectionEnd READ selectionEnd WRITE setSelectionEnd NOTIFY selectionEndChanged) Q_PROPERTY(QColor textColor READ textColor WRITE setTextColor NOTIFY textColorChanged) Q_PROPERTY(QString fontFamily READ fontFamily WRITE setFontFamily NOTIFY fontFamilyChanged) @@ -70,26 +68,14 @@ class QmlRichText : public QObject public: QmlRichText(); - QQuickItem *target() - { - return m_target; - } + QQuickItem *target() { return m_target; } void setTarget(QQuickItem *target); void setCursorPosition(int position); void setSelectionStart(int position); void setSelectionEnd(int position); - int cursorPosition() const - { - return m_cursorPosition; - } - int selectionStart() const - { - return m_selectionStart; - } - int selectionEnd() const - { - return m_selectionEnd; - } + int cursorPosition() const { return m_cursorPosition; } + int selectionStart() const { return m_selectionStart; } + int selectionEnd() const { return m_selectionEnd; } QString fontFamily() const; QColor textColor() const; Qt::Alignment alignment() const; @@ -100,10 +86,7 @@ class QmlRichText : public QObject int fontSize() const; QUrl fileUrl() const; QString text() const; - QSizeF size() const - { - return m_doc->size(); - } + QSizeF size() const { return m_doc->size(); } public slots: void setBold(bool arg); diff --git a/src/qmltypes/qmlrichtextmenu.cpp b/src/qmltypes/qmlrichtextmenu.cpp index 3c351fc8d1..89bdc6e3e7 100644 --- a/src/qmltypes/qmlrichtextmenu.cpp +++ b/src/qmltypes/qmlrichtextmenu.cpp @@ -21,8 +21,7 @@ QmlRichTextMenu::QmlRichTextMenu(QObject *parent) : QObject(parent) -{ -} +{} void QmlRichTextMenu::popup() { diff --git a/src/qmltypes/qmlutilities.cpp b/src/qmltypes/qmlutilities.cpp index 4e06725bab..3cd3b1ca8f 100644 --- a/src/qmltypes/qmlutilities.cpp +++ b/src/qmltypes/qmlutilities.cpp @@ -15,39 +15,39 @@ * along with this program. If not, see . */ -#include "qmltypes/qmlapplication.h" +#include "qmltypes/qmlutilities.h" +#include "models/keyframesmodel.h" +#include "models/metadatamodel.h" +#include "models/subtitlesmodel.h" +#include "models/subtitlesselectionmodel.h" #include "qmltypes/colordialog.h" #include "qmltypes/colorpickeritem.h" #include "qmltypes/colorwheelitem.h" #include "qmltypes/filedialog.h" #include "qmltypes/fontdialog.h" #include "qmltypes/messagedialog.h" +#include "qmltypes/qmlapplication.h" #include "qmltypes/qmleditmenu.h" -#include "qmltypes/qmlprofile.h" -#include "qmltypes/qmlutilities.h" #include "qmltypes/qmlfile.h" #include "qmltypes/qmlfilter.h" #include "qmltypes/qmlmarkermenu.h" #include "qmltypes/qmlmetadata.h" +#include "qmltypes/qmlprofile.h" #include "qmltypes/qmlrichtext.h" #include "qmltypes/qmlrichtextmenu.h" #include "qmltypes/timelineitems.h" #include "settings.h" -#include "models/metadatamodel.h" -#include "models/keyframesmodel.h" -#include "models/subtitlesmodel.h" -#include "models/subtitlesselectionmodel.h" + #include -#include #include -#include -#include #include +#include +#include +#include -QmlUtilities::QmlUtilities(QObject *parent) : - QObject(parent) -{ -} +QmlUtilities::QmlUtilities(QObject *parent) + : QObject(parent) +{} void QmlUtilities::registerCommonTypes() { @@ -62,9 +62,15 @@ void QmlUtilities::registerCommonTypes() qmlRegisterType("org.shotcut.qml", 1, 0, "SubtitlesSelectionModel"); qmlRegisterType("org.shotcut.qml", 1, 0, "Utilities"); // MetadataModel is registered to access its MetadataFilter enum. - qmlRegisterUncreatableType("org.shotcut.qml", 1, 0, "MetadataModel", + qmlRegisterUncreatableType("org.shotcut.qml", + 1, + 0, + "MetadataModel", "You cannot create a MetadataModel from QML."); - qmlRegisterUncreatableType("org.shotcut.qml", 1, 0, "Settings", + qmlRegisterUncreatableType("org.shotcut.qml", + 1, + 0, + "Settings", "You cannot create a Settings from QML."); qmlRegisterType("Shotcut.Controls", 1, 0, "ColorPickerItem"); qmlRegisterType("Shotcut.Controls", 1, 0, "ColorWheelItem"); diff --git a/src/qmltypes/qmlutilities.h b/src/qmltypes/qmlutilities.h index 8c1d4a80d8..5b9eb56dbb 100644 --- a/src/qmltypes/qmlutilities.h +++ b/src/qmltypes/qmlutilities.h @@ -19,8 +19,8 @@ #ifndef QMLUTILITIES_H #define QMLUTILITIES_H -#include #include +#include #include #include diff --git a/src/qmltypes/qmlview.cpp b/src/qmltypes/qmlview.cpp index bc7e12ecca..b1239e841a 100644 --- a/src/qmltypes/qmlview.cpp +++ b/src/qmltypes/qmlview.cpp @@ -17,14 +17,15 @@ */ #include "qmlview.h" + +#include "Logger.h" + #include -#include QmlView::QmlView(QWidget *qview) : QObject(qview) , m_qview(qview) -{ -} +{} QPoint QmlView::pos() { diff --git a/src/qmltypes/thumbnailprovider.cpp b/src/qmltypes/thumbnailprovider.cpp index 2e0d8fb3ec..e834fca792 100644 --- a/src/qmltypes/thumbnailprovider.cpp +++ b/src/qmltypes/thumbnailprovider.cpp @@ -16,22 +16,22 @@ */ #include "thumbnailprovider.h" -#include -#include + +#include "Logger.h" +#include "database.h" #include "mltcontroller.h" #include "models/playlistmodel.h" -#include "database.h" -#include "util.h" #include "settings.h" +#include "util.h" -#include +#include +#include ThumbnailProvider::ThumbnailProvider() : QQuickImageProvider(QQmlImageProviderBase::Image, QQmlImageProviderBase::ForceAsynchronousImageLoading) , m_profile("atsc_720p_60") -{ -} +{} QImage ThumbnailProvider::requestImage(const QString &id, QSize *size, const QSize &requestedSize) { @@ -70,7 +70,9 @@ QImage ThumbnailProvider::requestImage(const QString &id, QSize *size, const QSi if (service == "count") { producer = Mlt::Producer(m_profile, service.toUtf8().constData(), "loader-nogl"); } else if (!Settings.playerGPU() || (service != "xml-nogl" && service != "consumer")) { - producer = Mlt::Producer(m_profile, service.toUtf8().constData(), resource.toUtf8().constData()); + producer = Mlt::Producer(m_profile, + service.toUtf8().constData(), + resource.toUtf8().constData()); } if (producer.is_valid()) { result = makeThumbnail(producer, frameNumber, requestedSize); @@ -87,8 +89,11 @@ QImage ThumbnailProvider::requestImage(const QString &id, QSize *size, const QSi return result; } -QString ThumbnailProvider::cacheKey(Mlt::Properties &properties, const QString &service, - const QString &resource, const QString &hash, int frameNumber) +QString ThumbnailProvider::cacheKey(Mlt::Properties &properties, + const QString &service, + const QString &resource, + const QString &hash, + int frameNumber) { QString time = properties.frames_to_time(frameNumber, mlt_time_clock); // Reduce the precision to centiseconds to increase chance for cache hit @@ -96,10 +101,7 @@ QString ThumbnailProvider::cacheKey(Mlt::Properties &properties, const QString & time = time.left(time.size() - 1); QString key; if (hash.isEmpty()) { - key = QStringLiteral("%1 %2 %3") - .arg(service) - .arg(resource) - .arg(time); + key = QStringLiteral("%1 %2 %3").arg(service).arg(resource).arg(time); QCryptographicHash hash(QCryptographicHash::Sha1); hash.addData(key.toUtf8()); key = hash.result().toHex(); @@ -109,7 +111,8 @@ QString ThumbnailProvider::cacheKey(Mlt::Properties &properties, const QString & return key; } -QImage ThumbnailProvider::makeThumbnail(Mlt::Producer &producer, int frameNumber, +QImage ThumbnailProvider::makeThumbnail(Mlt::Producer &producer, + int frameNumber, const QSize &requestedSize) { Mlt::Filter scaler(m_profile, "swscale"); diff --git a/src/qmltypes/thumbnailprovider.h b/src/qmltypes/thumbnailprovider.h index cca0dcdc9d..647eab9e0a 100644 --- a/src/qmltypes/thumbnailprovider.h +++ b/src/qmltypes/thumbnailprovider.h @@ -19,9 +19,9 @@ #ifndef THUMBNAILPROVIDER_H #define THUMBNAILPROVIDER_H -#include #include #include +#include class ThumbnailProvider : public QQuickImageProvider { @@ -30,8 +30,11 @@ class ThumbnailProvider : public QQuickImageProvider QImage requestImage(const QString &id, QSize *size, const QSize &requestedSize); private: - QString cacheKey(Mlt::Properties &properties, const QString &service, - const QString &resource, const QString &hash, int frameNumber); + QString cacheKey(Mlt::Properties &properties, + const QString &service, + const QString &resource, + const QString &hash, + int frameNumber); QImage makeThumbnail(Mlt::Producer &, int frameNumber, const QSize &requestedSize); Mlt::Profile m_profile; }; diff --git a/src/qmltypes/timelineitems.cpp b/src/qmltypes/timelineitems.cpp index a02b1ef294..960b7e306d 100644 --- a/src/qmltypes/timelineitems.cpp +++ b/src/qmltypes/timelineitems.cpp @@ -16,15 +16,16 @@ */ #include "timelineitems.h" + +#include "Logger.h" #include "mltcontroller.h" #include "settings.h" -#include -#include +#include #include -#include #include -#include +#include +#include class TimelineTransition : public QQuickPaintedItem { @@ -77,10 +78,7 @@ class TimelinePlayhead : public QQuickPaintedItem class TimelineTriangle : public QQuickPaintedItem { public: - TimelineTriangle() - { - setAntialiasing(true); - } + TimelineTriangle() { setAntialiasing(true); } void paint(QPainter *painter) { QPainterPath path; @@ -125,7 +123,7 @@ class TimelineWaveform : public QQuickPaintedItem const int outPoint = qRound(m_outPoint / MLT.profile().fps() * 25.0); const qreal indicesPrPixel = qreal(outPoint - inPoint) / width(); -// LOG_DEBUG() << "In/out points" << inPoint << "/" << outPoint; + // LOG_DEBUG() << "In/out points" << inPoint << "/" << outPoint; QPainterPath path; path.moveTo(-1, height()); @@ -155,7 +153,7 @@ class TimelineWaveform : public QQuickPaintedItem int m_inPoint; int m_outPoint; QColor m_color; - bool m_isActive {true}; + bool m_isActive{true}; }; class MarkerStart : public QQuickPaintedItem @@ -217,7 +215,6 @@ class MarkerEnd : public QQuickPaintedItem QColor m_color; }; - void registerTimelineItems() { qmlRegisterType("Shotcut.Controls", 1, 0, "TimelineTransition"); diff --git a/src/scrubbar.cpp b/src/scrubbar.cpp index 0ecb50db50..0945bec30a 100644 --- a/src/scrubbar.cpp +++ b/src/scrubbar.cpp @@ -16,6 +16,7 @@ */ #include "scrubbar.h" + #include "mltcontroller.h" #include "settings.h" @@ -24,7 +25,7 @@ static const int selectionSize = 14; /// the height of the top bar #ifndef CLAMP -#define CLAMP(x, min, max) (((x) < (min))? (min) : ((x) > (max))? (max) : (x)) +#define CLAMP(x, min, max) (((x) < (min)) ? (min) : ((x) > (max)) ? (max) : (x)) #endif ScrubBar::ScrubBar(QWidget *parent) @@ -48,15 +49,16 @@ ScrubBar::ScrubBar(QWidget *parent) void ScrubBar::setScale(int maximum) { if (!m_timecodeWidth) { - const int fontSize = font().pointSize() - (font().pointSize() > 10 ? 2 : - (font().pointSize() > 8 ? 1 : 0)); + const int fontSize = font().pointSize() + - (font().pointSize() > 10 ? 2 : (font().pointSize() > 8 ? 1 : 0)); setFont(QFont(font().family(), fontSize * devicePixelRatioF())); m_timecodeWidth = fontMetrics().horizontalAdvance("00:00:00:00") / devicePixelRatioF(); } m_max = maximum; /// m_scale is the pixels per frame ratio m_scale = (double) (width() - 2 * m_margin) / (double) maximum; - if (m_scale == 0) m_scale = -1; + if (m_scale == 0) + m_scale = -1; m_secondsPerTick = qMax(qRound(double(m_timecodeWidth * 1.8) / m_scale / m_fps), 1); if (m_secondsPerTick > 3600) // force to a multiple of one hour @@ -176,7 +178,8 @@ void ScrubBar::mouseMoveEvent(QMouseEvent *event) emit paused(pos); emit seeked(pos); } else if (event->buttons() == Qt::NoButton && MLT.producer()) { - QString text = QString::fromLatin1(MLT.producer()->frames_to_time(pos, Settings.timeFormat())); + QString text = QString::fromLatin1( + MLT.producer()->frames_to_time(pos, Settings.timeFormat())); QToolTip::showText(event->globalPosition().toPoint(), text); } } @@ -202,7 +205,8 @@ void ScrubBar::paintEvent(QPaintEvent *e) p.setClipRect(r); p.drawPixmap(0, 0, width(), height(), m_pixmap); - if (!isEnabled()) return; + if (!isEnabled()) + return; // draw pointer QPolygon pa(3); @@ -221,7 +225,12 @@ void ScrubBar::paintEvent(QPaintEvent *e) // draw in point if (m_in > -1) { const int in = m_margin + m_in * m_scale; - pa.setPoints(3, in - selectionSize / 2, 0, in - selectionSize / 2, selectionSize - 1, in - 1, + pa.setPoints(3, + in - selectionSize / 2, + 0, + in - selectionSize / 2, + selectionSize - 1, + in - 1, selectionSize / 2); p.setBrush(palette().text().color()); p.setPen(Qt::NoPen); @@ -233,7 +242,12 @@ void ScrubBar::paintEvent(QPaintEvent *e) // draw out point if (m_out > -1) { const int out = m_margin + m_out * m_scale; - pa.setPoints(3, out + selectionSize / 2, 0, out + selectionSize / 2, selectionSize - 1, out, + pa.setPoints(3, + out + selectionSize / 2, + 0, + out + selectionSize / 2, + selectionSize - 1, + out, selectionSize / 2); p.setBrush(palette().text().color()); p.setPen(Qt::NoPen); @@ -287,7 +301,8 @@ void ScrubBar::updatePixmap() const int in = m_in * m_scale * ratio; const int out = m_out * m_scale * ratio; p.fillRect(l_margin + in, 0, out - in, l_selectionSize, Qt::red); - p.fillRect(l_margin + in + (2 + ratio), ratio, // 2 for the in point line + p.fillRect(l_margin + in + (2 + ratio), + ratio, // 2 for the in point line out - in - 2 * (2 + ratio) - qFloor(0.5 * ratio), l_selectionSize - ratio * 2, palette().highlight().color()); @@ -301,11 +316,20 @@ void ScrubBar::updatePixmap() for (int x = l_margin; x < l_width - l_margin; x += l_interval) { p.drawLine(x, l_selectionSize, x, l_height - 1); if (x + l_interval / 4 < l_width - l_margin) - p.drawLine(x + l_interval / 4, l_height - 3 * ratio, x + l_interval / 4, l_height - 1); + p.drawLine(x + l_interval / 4, + l_height - 3 * ratio, + x + l_interval / 4, + l_height - 1); if (x + l_interval / 2 < l_width - l_margin) - p.drawLine(x + l_interval / 2, l_height - 7 * ratio, x + l_interval / 2, l_height - 1); + p.drawLine(x + l_interval / 2, + l_height - 7 * ratio, + x + l_interval / 2, + l_height - 1); if (x + l_interval * 3 / 4 < l_width - l_margin) - p.drawLine(x + l_interval * 3 / 4, l_height - 3 * ratio, x + l_interval * 3 / 4, l_height - 1); + p.drawLine(x + l_interval * 3 / 4, + l_height - 3 * ratio, + x + l_interval * 3 / 4, + l_height - 1); } } @@ -316,7 +340,9 @@ void ScrubBar::updatePixmap() for (int i = 0; x < l_width - l_margin - l_timecodeWidth; i++, x += l_interval) { int y = l_selectionSize + fontMetrics().ascent() - 2 * ratio; int frames = qRound(i * m_fps * m_secondsPerTick); - p.drawText(x + 2 * ratio, y, QString(MLT.producer()->frames_to_time(frames, timeFormat)).left(8)); + p.drawText(x + 2 * ratio, + y, + QString(MLT.producer()->frames_to_time(frames, timeFormat)).left(8)); } } @@ -328,7 +354,11 @@ void ScrubBar::updatePixmap() QString s = QString::number(i++); int markerWidth = fontMetrics().horizontalAdvance(s) * 1.5; p.fillRect(x, 0, 1, l_height, palette().highlight().color()); - p.fillRect(x - markerWidth / 2, 0, markerWidth, markerHeight, palette().highlight().color()); + p.fillRect(x - markerWidth / 2, + 0, + markerWidth, + markerHeight, + palette().highlight().color()); p.drawText(x - markerWidth / 3, markerHeight - 2 * ratio, s); } } diff --git a/src/scrubbar.h b/src/scrubbar.h index 08f836e083..e15b93eb25 100644 --- a/src/scrubbar.h +++ b/src/scrubbar.h @@ -24,12 +24,7 @@ class ScrubBar : public QWidget { Q_OBJECT - enum controls { - CONTROL_NONE, - CONTROL_HEAD, - CONTROL_IN, - CONTROL_OUT - }; + enum controls { CONTROL_NONE, CONTROL_HEAD, CONTROL_IN, CONTROL_OUT }; public: explicit ScrubBar(QWidget *parent = 0); @@ -43,14 +38,8 @@ class ScrubBar : public QWidget void setInPoint(int in); void setOutPoint(int out); void setMarkers(const QList &); - QList markers() const - { - return m_markers; - } - void setMargin(int margin) - { - m_margin = margin; - } + QList markers() const { return m_markers; } + void setMargin(int margin) { m_margin = margin; } void setLoopRange(int start, int end); signals: diff --git a/src/settings.cpp b/src/settings.cpp index fb8e0d6e35..17f2a28ea2 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -17,17 +17,17 @@ #include "settings.h" +#include "Logger.h" #include "qmltypes/qmlapplication.h" #include +#include #include -#include -#include -#include #include +#include +#include #include -#include -#include +#include #include static const QString APP_DATA_DIR_KEY("appdatadir"); @@ -45,8 +45,10 @@ ShotcutSettings &ShotcutSettings::singleton() if (appDataForSession.isEmpty()) { instance.reset(new ShotcutSettings); if (instance->settings.value(APP_DATA_DIR_KEY).isValid() - && QFile::exists(instance->settings.value(APP_DATA_DIR_KEY).toString() + SHOTCUT_INI_FILENAME) ) - instance.reset(new ShotcutSettings(instance->settings.value(APP_DATA_DIR_KEY).toString())); + && QFile::exists(instance->settings.value(APP_DATA_DIR_KEY).toString() + + SHOTCUT_INI_FILENAME)) + instance.reset( + new ShotcutSettings(instance->settings.value(APP_DATA_DIR_KEY).toString())); } else { instance.reset(new ShotcutSettings(appDataForSession)); } @@ -88,7 +90,7 @@ void ShotcutSettings::migrateRecent() } setRecent(newRecents); m_recent.sync(); -// settings.remove("recent"); + // settings.remove("recent"); settings.sync(); } } @@ -117,7 +119,7 @@ void ShotcutSettings::log() LOG_INFO() << "audio channels" << playerAudioChannels(); #if defined(Q_OS_WIN) || defined(Q_OS_LINUX) if (::qEnvironmentVariableIsSet("SDL_AUDIODRIVER")) { - LOG_INFO() << "audio driver" <<::qgetenv("SDL_AUDIODRIVER"); + LOG_INFO() << "audio driver" << ::qgetenv("SDL_AUDIODRIVER"); } else { LOG_INFO() << "audio driver" << playerAudioDriver(); } @@ -149,8 +151,9 @@ void ShotcutSettings::setImageDuration(double d) QString ShotcutSettings::openPath() const { - return settings.value("openPath", - QStandardPaths::standardLocations(QStandardPaths::MoviesLocation)).toString(); + return settings + .value("openPath", QStandardPaths::standardLocations(QStandardPaths::MoviesLocation)) + .toString(); } void ShotcutSettings::setOpenPath(const QString &s) @@ -161,8 +164,9 @@ void ShotcutSettings::setOpenPath(const QString &s) QString ShotcutSettings::savePath() const { - return settings.value("savePath", - QStandardPaths::standardLocations(QStandardPaths::DocumentsLocation)).toString(); + return settings + .value("savePath", QStandardPaths::standardLocations(QStandardPaths::DocumentsLocation)) + .toString(); } void ShotcutSettings::setSavePath(const QString &s) @@ -446,8 +450,9 @@ void ShotcutSettings::setExportFrameSuffix(const QString &exportFrameSuffix) QString ShotcutSettings::encodePath() const { - return settings.value("encode/path", - QStandardPaths::standardLocations(QStandardPaths::MoviesLocation)).toString(); + return settings + .value("encode/path", QStandardPaths::standardLocations(QStandardPaths::MoviesLocation)) + .toString(); } void ShotcutSettings::setEncodePath(const QString &s) @@ -918,11 +923,11 @@ void ShotcutSettings::setTimelineScrolling(ShotcutSettings::TimelineScrolling va ShotcutSettings::TimelineScrolling ShotcutSettings::timelineScrolling() const { if (settings.contains("timeline/centerPlayhead") - && settings.value("timeline/centerPlayhead").toBool()) + && settings.value("timeline/centerPlayhead").toBool()) return ShotcutSettings::TimelineScrolling::CenterPlayhead; else - return ShotcutSettings::TimelineScrolling(settings.value("timeline/scrolling", - PageScrolling).toInt()); + return ShotcutSettings::TimelineScrolling( + settings.value("timeline/scrolling", PageScrolling).toInt()); } bool ShotcutSettings::timelineAutoAddTracks() const @@ -980,7 +985,6 @@ void ShotcutSettings::setAudioOutDuration(double d) emit audioOutDurationChanged(); } - double ShotcutSettings::videoInDuration() const { return settings.value("filter/videoInDuration", 1.0).toDouble(); @@ -1079,7 +1083,7 @@ int ShotcutSettings::getMarkerSortColumn() Qt::SortOrder ShotcutSettings::getMarkerSortOrder() { - return (Qt::SortOrder)settings.value("markers/sortOrder", Qt::AscendingOrder).toInt(); + return (Qt::SortOrder) settings.value("markers/sortOrder", Qt::AscendingOrder).toInt(); } int ShotcutSettings::drawMethod() const @@ -1187,7 +1191,8 @@ QStringList ShotcutSettings::layouts() const return result; } -bool ShotcutSettings::setLayout(const QString &name, const QByteArray &geometry, +bool ShotcutSettings::setLayout(const QString &name, + const QByteArray &geometry, const QByteArray &state) { bool isNew = false; @@ -1253,8 +1258,9 @@ void ShotcutSettings::setClearRecent(bool b) QString ShotcutSettings::projectsFolder() const { - return settings.value("projectsFolder", - QStandardPaths::standardLocations(QStandardPaths::MoviesLocation)).toString(); + return settings + .value("projectsFolder", QStandardPaths::standardLocations(QStandardPaths::MoviesLocation)) + .toString(); } void ShotcutSettings::setProjectsFolder(const QString &path) @@ -1264,7 +1270,7 @@ void ShotcutSettings::setProjectsFolder(const QString &path) QString ShotcutSettings::audioInput() const { - QString defaultValue = "default"; + QString defaultValue = "default"; #if defined(Q_OS_MAC) || defined(Q_OS_WIN) for (const auto &deviceInfo : QMediaDevices::audioInputs()) { defaultValue = deviceInfo.description(); @@ -1511,8 +1517,8 @@ QString ShotcutSettings::whisperModel() { QDir dataPath = QmlApplication::dataDir(); dataPath.cd("shotcut/whisper_models"); - return settings.value("subtitles/whisperModel", - dataPath.absoluteFilePath("ggml-base-q5_1.bin")).toString(); + return settings.value("subtitles/whisperModel", dataPath.absoluteFilePath("ggml-base-q5_1.bin")) + .toString(); } void ShotcutSettings::setNotesZoom(int zoom) @@ -1554,7 +1560,7 @@ void ShotcutSettings::setBackupPeriod(int minutes) mlt_time_format ShotcutSettings::timeFormat() const { - return (mlt_time_format)settings.value("timeFormat", mlt_time_smpte_df).toInt(); + return (mlt_time_format) settings.value("timeFormat", mlt_time_smpte_df).toInt(); } void ShotcutSettings::setTimeFormat(int format) diff --git a/src/settings.h b/src/settings.h index 575b73784f..13efc43603 100644 --- a/src/settings.h +++ b/src/settings.h @@ -19,73 +19,66 @@ #define SETTINGS_H #include - +#include #include #include #include #include -#include #include class ShotcutSettings : public QObject { Q_OBJECT Q_PROPERTY(bool timelineDragScrub READ timelineDragScrub WRITE setTimelineDragScrub NOTIFY - timelineDragScrubChanged) + timelineDragScrubChanged) Q_PROPERTY(bool timelineShowWaveforms READ timelineShowWaveforms WRITE setTimelineShowWaveforms - NOTIFY timelineShowWaveformsChanged) - Q_PROPERTY(bool timelineShowThumbnails READ timelineShowThumbnails WRITE setTimelineShowThumbnails - NOTIFY timelineShowThumbnailsChanged) + NOTIFY timelineShowWaveformsChanged) + Q_PROPERTY(bool timelineShowThumbnails READ timelineShowThumbnails WRITE + setTimelineShowThumbnails NOTIFY timelineShowThumbnailsChanged) Q_PROPERTY(bool timelineRipple READ timelineRipple WRITE setTimelineRipple NOTIFY - timelineRippleChanged) + timelineRippleChanged) Q_PROPERTY(bool timelineRippleAllTracks READ timelineRippleAllTracks WRITE - setTimelineRippleAllTracks NOTIFY timelineRippleAllTracksChanged) + setTimelineRippleAllTracks NOTIFY timelineRippleAllTracksChanged) Q_PROPERTY(bool timelineRippleMarkers READ timelineRippleMarkers WRITE setTimelineRippleMarkers - NOTIFY timelineRippleMarkersChanged) + NOTIFY timelineRippleMarkersChanged) Q_PROPERTY(bool timelineSnap READ timelineSnap WRITE setTimelineSnap NOTIFY timelineSnapChanged) Q_PROPERTY(bool timelineScrollZoom READ timelineScrollZoom WRITE setTimelineScrollZoom NOTIFY - timelineScrollZoomChanged) + timelineScrollZoomChanged) Q_PROPERTY(bool timelineFramebufferWaveform READ timelineFramebufferWaveform WRITE - setTimelineFramebufferWaveform NOTIFY timelineFramebufferWaveformChanged) + setTimelineFramebufferWaveform NOTIFY timelineFramebufferWaveformChanged) Q_PROPERTY(QString openPath READ openPath WRITE setOpenPath NOTIFY openPathChanged) Q_PROPERTY(QString savePath READ savePath WRITE setSavePath NOTIFY savePathChanged) Q_PROPERTY(QString playlistThumbnails READ playlistThumbnails WRITE setPlaylistThumbnails NOTIFY - playlistThumbnailsChanged) + playlistThumbnailsChanged) Q_PROPERTY(QString viewMode READ viewMode WRITE setViewMode NOTIFY viewModeChanged) Q_PROPERTY(int playerAudioChannels READ playerAudioChannels NOTIFY playerAudioChannelsChanged) Q_PROPERTY(bool playerGPU READ playerGPU NOTIFY playerGpuChanged) Q_PROPERTY(double audioInDuration READ audioInDuration WRITE setAudioInDuration NOTIFY - audioInDurationChanged) + audioInDurationChanged) Q_PROPERTY(double audioOutDuration READ audioOutDuration WRITE setAudioOutDuration NOTIFY - audioOutDurationChanged) + audioOutDurationChanged) Q_PROPERTY(double videoInDuration READ videoInDuration WRITE setVideoInDuration NOTIFY - videoInDurationChanged) + videoInDurationChanged) Q_PROPERTY(double videoOutDuration READ videoOutDuration WRITE setVideoOutDuration NOTIFY - videoOutDurationChanged) - Q_PROPERTY(double audioInCurve READ audioInCurve WRITE setAudioInCurve NOTIFY - audioInCurveChanged) - Q_PROPERTY(double audioOutCurve READ audioOutCurve WRITE setAudioOutCurve NOTIFY - audioOutCurveChanged) + videoOutDurationChanged) + Q_PROPERTY(double audioInCurve READ audioInCurve WRITE setAudioInCurve NOTIFY audioInCurveChanged) + Q_PROPERTY( + double audioOutCurve READ audioOutCurve WRITE setAudioOutCurve NOTIFY audioOutCurveChanged) Q_PROPERTY(bool smallIcons READ smallIcons WRITE setSmallIcons NOTIFY smallIconsChanged) Q_PROPERTY(bool askOutputFilter READ askOutputFilter WRITE setAskOutputFilter NOTIFY - askOutputFilterChanged) + askOutputFilterChanged) Q_PROPERTY(QString appDataLocation READ appDataLocation CONSTANT) Q_PROPERTY(TimelineScrolling timelineScrolling READ timelineScrolling WRITE setTimelineScrolling - NOTIFY timelineScrollingChanged) + NOTIFY timelineScrollingChanged) Q_ENUMS(TimelineScrolling) Q_PROPERTY(bool timelineRectangleSelect READ timelineRectangleSelect WRITE - setTimelineRectangleSelect NOTIFY timelineRectangleSelectChanged) - Q_PROPERTY(bool keyframesDragScrub READ keyframesDragScrub WRITE setKeyframesDragScrub - NOTIFY keyframesDragScrubChanged) + setTimelineRectangleSelect NOTIFY timelineRectangleSelectChanged) + Q_PROPERTY(bool keyframesDragScrub READ keyframesDragScrub WRITE setKeyframesDragScrub NOTIFY + keyframesDragScrubChanged) public: - static const qsizetype MaxPath {32767}; - enum TimelineScrolling { - NoScrolling, - CenterPlayhead, - PageScrolling, - SmoothScrolling - }; + static const qsizetype MaxPath{32767}; + enum TimelineScrolling { NoScrolling, CenterPlayhead, PageScrolling, SmoothScrolling }; static ShotcutSettings &singleton(); void log(); diff --git a/src/sharedframe.cpp b/src/sharedframe.cpp index 1f25b0c84a..9b3f537fdb 100644 --- a/src/sharedframe.cpp +++ b/src/sharedframe.cpp @@ -27,34 +27,32 @@ void destroyFrame(void *p) class FrameData : public QSharedData { public: - FrameData() : f(nullptr) {}; - FrameData(Mlt::Frame &frame) : f(frame) {}; - ~FrameData() {}; + FrameData() + : f(nullptr){}; + FrameData(Mlt::Frame &frame) + : f(frame){}; + ~FrameData(){}; Mlt::Frame f; std::mutex m; + private: Q_DISABLE_COPY(FrameData) }; SharedFrame::SharedFrame() : d(new FrameData()) -{ -} +{} SharedFrame::SharedFrame(Mlt::Frame &frame) : d(new FrameData(frame)) -{ -} +{} SharedFrame::SharedFrame(const SharedFrame &other) : d(other.d) -{ -} +{} -SharedFrame::~SharedFrame() -{ -} +SharedFrame::~SharedFrame() {} SharedFrame &SharedFrame::operator=(const SharedFrame &other) { @@ -76,7 +74,7 @@ Mlt::Frame SharedFrame::clone(bool audio, bool image, bool alpha) const void *data = 0; void *copy = 0; int size = 0; - Mlt::Frame cloneFrame(mlt_frame_init( NULL )); + Mlt::Frame cloneFrame(mlt_frame_init(NULL)); cloneFrame.inherit(d->f); cloneFrame.set("_producer", d->f.get_data("_producer", size), size); cloneFrame.set("movit.convert", d->f.get_data("movit.convert", size), size); @@ -102,7 +100,7 @@ Mlt::Frame SharedFrame::clone(bool audio, bool image, bool alpha) const cloneFrame.set("audio_samples", 0); } - data = d->f.get_data("image", size ); + data = d->f.get_data("image", size); if (image && data) { if (!size) { size = mlt_image_format_size(get_image_format(), @@ -120,7 +118,7 @@ Mlt::Frame SharedFrame::clone(bool audio, bool image, bool alpha) const cloneFrame.set("height", 0); } - data = d->f.get_data("alpha", size ); + data = d->f.get_data("alpha", size); if (alpha && data && d->f.get_int("format") != mlt_image_rgba) { if (!size) { size = get_image_width() * get_image_height(); @@ -160,17 +158,17 @@ int SharedFrame::get_position() const mlt_image_format SharedFrame::get_image_format() const { - return (mlt_image_format)d->f.get_int( "format" ); + return (mlt_image_format) d->f.get_int("format"); } int SharedFrame::get_image_width() const { - return d->f.get_int( "width" ); + return d->f.get_int("width"); } int SharedFrame::get_image_height() const { - return d->f.get_int( "height" ); + return d->f.get_int("height"); } const uint8_t *SharedFrame::get_image(mlt_image_format format) const @@ -186,10 +184,10 @@ const uint8_t *SharedFrame::get_image(mlt_image_format format) const if (format == native_format) { // Native format is requested. Return frame image. - image = (uint8_t *)d->f.get_image(format, width, height, 0); + image = (uint8_t *) d->f.get_image(format, width, height, 0); } else { // Non-native format is requested. Return a cached converted image. - const char *formatName = mlt_image_format_name( format ); + const char *formatName = mlt_image_format_name(format); // Convert to non-const so that the cache can be accessed/modified while // under lock. FrameData *nonConstData = const_cast(d.data()); @@ -206,7 +204,7 @@ const uint8_t *SharedFrame::get_image(mlt_image_format format) const cacheFrame = new Mlt::Frame(cloneFrame); // Release the reference on the clone // (now it is owned by the cache frame) - mlt_frame_close( cloneFrame ); + mlt_frame_close(cloneFrame); // Save the cache frame as a property under the name of the image // format for later use. nonConstData->f.set(formatName, static_cast(cacheFrame), 0, destroyFrame); @@ -216,7 +214,7 @@ const uint8_t *SharedFrame::get_image(mlt_image_format format) const // Get the image from the cache frame. // This will cause a conversion if it was just created. - image = (uint8_t *)cacheFrame->get_image(format, width, height, 0); + image = (uint8_t *) cacheFrame->get_image(format, width, height, 0); nonConstData->m.unlock(); } @@ -225,22 +223,22 @@ const uint8_t *SharedFrame::get_image(mlt_image_format format) const mlt_audio_format SharedFrame::get_audio_format() const { - return (mlt_audio_format)d->f.get_int( "audio_format" ); + return (mlt_audio_format) d->f.get_int("audio_format"); } int SharedFrame::get_audio_channels() const { - return d->f.get_int( "audio_channels" ); + return d->f.get_int("audio_channels"); } int SharedFrame::get_audio_frequency() const { - return d->f.get_int( "audio_frequency" ); + return d->f.get_int("audio_frequency"); } int SharedFrame::get_audio_samples() const { - return d->f.get_int( "audio_samples" ); + return d->f.get_int("audio_samples"); } const int16_t *SharedFrame::get_audio() const @@ -249,7 +247,7 @@ const int16_t *SharedFrame::get_audio() const int frequency = get_audio_frequency(); int channels = get_audio_channels(); int samples = get_audio_samples(); - return (int16_t *)d->f.get_audio(format, frequency, channels, samples); + return (int16_t *) d->f.get_audio(format, frequency, channels, samples); } Mlt::Producer *SharedFrame::get_original_producer() diff --git a/src/sharedframe.h b/src/sharedframe.h index 32120e9966..a74554b5e3 100644 --- a/src/sharedframe.h +++ b/src/sharedframe.h @@ -19,9 +19,10 @@ #ifndef SHAREDFRAME_H #define SHAREDFRAME_H -#include -#include #include +#include +#include + #include class FrameData; @@ -70,6 +71,7 @@ class SharedFrame int get_audio_samples() const; const int16_t *get_audio() const; Mlt::Producer *get_original_producer(); + private: QExplicitlySharedDataPointer d; }; diff --git a/src/spatialmedia/spatialmedia.cpp b/src/spatialmedia/spatialmedia.cpp index db16895fbb..f30d2400e5 100644 --- a/src/spatialmedia/spatialmedia.cpp +++ b/src/spatialmedia/spatialmedia.cpp @@ -25,7 +25,7 @@ #include #include #include -#include +#include "Logger.h" static const uint8_t SPHERICAL_UUID_ID[] = {0xff, 0xcc, 0x82, 0x63, 0xf8, 0x55, 0x4a, 0x93, 0x88, 0x14, 0x58, 0x7a, 0x02, 0x52, 0x1f, 0xdd }; // "\xff\xcc\x82\x63\xf8\x55\x4a\x93\x88\x14\x58\x7a\x02\x52\x1f\xdd") diff --git a/src/transcoder.cpp b/src/transcoder.cpp index e486629588..87951f892f 100644 --- a/src/transcoder.cpp +++ b/src/transcoder.cpp @@ -20,9 +20,9 @@ #include "jobqueue.h" #include "jobs/ffmpegjob.h" #include "mainwindow.h" -#include "util.h" #include "settings.h" #include "shotcut_mlt_properties.h" +#include "util.h" #include #include @@ -82,16 +82,20 @@ void Transcoder::convert(TranscodeDialog &dialog) if (dialog.isSubClip()) { filename = Util::getNextFile(path); } - filename = QFileDialog::getSaveFileName(MAIN.centralWidget(), dialog.windowTitle(), filename, + filename = QFileDialog::getSaveFileName(MAIN.centralWidget(), + dialog.windowTitle(), + filename, nameFilter, - nullptr, Util::getFileDialogOptions()); + nullptr, + Util::getFileDialogOptions()); if (!filename.isEmpty()) { if (filename == QDir::toNativeSeparators(resource)) { - QMessageBox::warning(MAIN.centralWidget(), dialog.windowTitle(), + QMessageBox::warning(MAIN.centralWidget(), + dialog.windowTitle(), QObject::tr("Unable to write file %1\n" "Perhaps you do not have permission.\n" "Try again with a different folder.") - .arg(fi.fileName())); + .arg(fi.fileName())); return; } if (JOBS.targetIsInProgress(filename)) { @@ -108,7 +112,9 @@ void Transcoder::convert(TranscodeDialog &dialog) } convertProducer(&m_producers[0], dialog, filename); } else if (m_producers.length() > 1) { - path = QFileDialog::getExistingDirectory(MAIN.centralWidget(), dialog.windowTitle(), path, + path = QFileDialog::getExistingDirectory(MAIN.centralWidget(), + dialog.windowTitle(), + path, Util::getFileDialogOptions()); if (path.isEmpty()) { MAIN.showStatusMessage(tr("Convert canceled")); @@ -145,9 +151,11 @@ void Transcoder::convertProducer(Mlt::Producer *producer, TranscodeDialog &dialo QStringList args; int in = -1; - args << "-loglevel" << "verbose"; + args << "-loglevel" + << "verbose"; args << "-i" << resource; - args << "-max_muxing_queue_size" << "9999"; + args << "-max_muxing_queue_size" + << "9999"; if (dialog.isSubClip()) { if (Settings.proxyEnabled()) { @@ -162,31 +170,44 @@ void Transcoder::convertProducer(Mlt::Producer *producer, TranscodeDialog &dialo args << "-ss" << s.replace(',', '.'); in -= ss; } else { - args << "-ss" << QString::fromLatin1(producer->get_time("in", mlt_time_clock)).replace(',', - '.').replace(',', '.'); + args << "-ss" + << QString::fromLatin1(producer->get_time("in", mlt_time_clock)) + .replace(',', '.') + .replace(',', '.'); } if (producer->get(kFilterOutProperty)) { int out = producer->get_int(kFilterOutProperty); - int to = qMin(producer->get_playtime() - 1, out + qRound(producer->get_fps() * kHandleSeconds)); + int to = qMin(producer->get_playtime() - 1, + out + qRound(producer->get_fps() * kHandleSeconds)); auto s = QString::fromLatin1(producer->frames_to_time(to, mlt_time_clock)); args << "-to" << s.replace(',', '.'); } else { - args << "-to" << QString::fromLatin1(producer->get_time("out", mlt_time_clock)).replace(',', '.'); + args << "-to" + << QString::fromLatin1(producer->get_time("out", mlt_time_clock)).replace(',', '.'); } } // transcode all streams except data, subtitles, and attachments - auto audioIndex = producer->property_exists(kDefaultAudioIndexProperty) ? producer->get_int( - kDefaultAudioIndexProperty) : producer->get_int("audio_index"); + auto audioIndex = producer->property_exists(kDefaultAudioIndexProperty) + ? producer->get_int(kDefaultAudioIndexProperty) + : producer->get_int("audio_index"); if (producer->get_int("video_index") < audioIndex) { - args << "-map" << "0:V?" << "-map" << "0:a?"; + args << "-map" + << "0:V?" + << "-map" + << "0:a?"; } else { - args << "-map" << "0:a?" << "-map" << "0:V?"; + args << "-map" + << "0:a?" + << "-map" + << "0:V?"; } - args << "-map_metadata" << "0" << "-ignore_unknown"; + args << "-map_metadata" + << "0" + << "-ignore_unknown"; // Set Sample rate if different than source - if (!dialog.sampleRate().isEmpty() ) { + if (!dialog.sampleRate().isEmpty()) { args << "-ar" << dialog.sampleRate(); } @@ -219,13 +240,17 @@ void Transcoder::convertProducer(Mlt::Producer *producer, TranscodeDialog &dialo } if (dialog.get709Convert()) { - QString convertFilter = - QStringLiteral("zscale=t=linear:npl=100,format=gbrpf32le,zscale=p=bt709,tonemap=tonemap=hable:desat=0,zscale=t=bt709:m=bt709:r=tv,format=yuv422p,"); + QString convertFilter = QStringLiteral( + "zscale=t=linear:npl=100,format=gbrpf32le,zscale=p=bt709,tonemap=tonemap=hable:desat=0," + "zscale=t=bt709:m=bt709:r=tv,format=yuv422p,"); filterString = filterString + convertFilter; } - filterString = filterString + - QStringLiteral("scale=flags=accurate_rnd+full_chroma_inp+full_chroma_int:in_range=%1:out_range=%2").arg( - color_range).arg(color_range); + filterString + = filterString + + QStringLiteral( + "scale=flags=accurate_rnd+full_chroma_inp+full_chroma_int:in_range=%1:out_range=%2") + .arg(color_range) + .arg(color_range); auto fps = dialog.fpsOverride() ? dialog.fps() : Util::getSuggestedFrameRate(producer); auto fpsStr = QStringLiteral("%1").arg(fps, 0, 'f', 6); int numerator, denominator; @@ -233,50 +258,88 @@ void Transcoder::convertProducer(Mlt::Producer *producer, TranscodeDialog &dialo if (denominator == 1001) { fpsStr = QStringLiteral("%1/%2").arg(numerator).arg(denominator); } - QString minterpFilter = - QStringLiteral(",minterpolate='mi_mode=%1:mc_mode=aobmc:me_mode=bidir:vsbmc=1:fps=%2'").arg( - dialog.frc(), - fpsStr); + QString minterpFilter + = QStringLiteral(",minterpolate='mi_mode=%1:mc_mode=aobmc:me_mode=bidir:vsbmc=1:fps=%2'") + .arg(dialog.frc(), fpsStr); filterString = filterString + minterpFilter; args << filterString; // Specify color range if (color_range == "full") { - args << "-color_range" << "2"; + args << "-color_range" + << "2"; } else { - args << "-color_range" << "1"; + args << "-color_range" + << "1"; } int progressive = producer->get_int("meta.media.progressive") || producer->get_int("force_progressive"); if (!dialog.deinterlace() && !progressive) { int tff = producer->get_int("meta.media.top_field_first") || producer->get_int("force_tff"); - args << "-flags" << "+ildct+ilme" << "-top" << QString::number(tff); + args << "-flags" + << "+ildct+ilme" + << "-top" << QString::number(tff); } switch (dialog.format()) { case 0: - args << "-f" << "mp4" << "-codec:a" << "ac3" << "-b:a" << "512k" << "-codec:v" << "libx264"; - args << "-preset" << "medium" << "-g" << "1" << "-crf" << "15"; + args << "-f" + << "mp4" + << "-codec:a" + << "ac3" + << "-b:a" + << "512k" + << "-codec:v" + << "libx264"; + args << "-preset" + << "medium" + << "-g" + << "1" + << "-crf" + << "15"; break; case 1: - args << "-f" << "mov" << "-codec:a" << "pcm_f32le"; + args << "-f" + << "mov" + << "-codec:a" + << "pcm_f32le"; if (dialog.deinterlace() || progressive) { - args << "-codec:v" << "dnxhd" << "-profile:v" << "dnxhr_hq" << "-pix_fmt" << "yuv422p"; + args << "-codec:v" + << "dnxhd" + << "-profile:v" + << "dnxhr_hq" + << "-pix_fmt" + << "yuv422p"; } else { // interlaced - args << "-codec:v" << "prores_ks" << "-profile:v" << "standard"; + args << "-codec:v" + << "prores_ks" + << "-profile:v" + << "standard"; } break; case 2: - args << "-f" << "matroska" << "-codec:a" << "pcm_f32le" << "-codec:v" << "utvideo"; - args << "-pix_fmt" << "yuv422p"; + args << "-f" + << "matroska" + << "-codec:a" + << "pcm_f32le" + << "-codec:v" + << "utvideo"; + args << "-pix_fmt" + << "yuv422p"; break; } if (dialog.get709Convert()) { - args << "-colorspace" << "bt709" << "-color_primaries" << "bt709" << "-color_trc" << "bt709"; + args << "-colorspace" + << "bt709" + << "-color_primaries" + << "bt709" + << "-color_trc" + << "bt709"; } else if (dialog.format() == 2 && producer->get_int("meta.media.colorspace") == 709) { // Work around a limitation that FFMpeg does not pass colorspace for utvideo - args << "-colorspace" << "bt709"; + args << "-colorspace" + << "bt709"; } args << "-y" << filename; @@ -294,8 +357,8 @@ void Transcoder::convertProducer(Mlt::Producer *producer, TranscodeDialog &dialo int trackIndex = parts[1].toInt(); QUuid uuid = MAIN.timelineClipUuid(trackIndex, clipIndex); if (!uuid.isNull()) { - job->setPostJobAction(new ReplaceOnePostJobAction(resource, filename, QString(), uuid, - in)); + job->setPostJobAction( + new ReplaceOnePostJobAction(resource, filename, QString(), uuid, in)); JOBS.add(job); } } diff --git a/src/transcoder.h b/src/transcoder.h index 8d21261a47..c30b8338bc 100644 --- a/src/transcoder.h +++ b/src/transcoder.h @@ -21,7 +21,6 @@ #include "dialogs/transcodedialog.h" #include - #include #include @@ -30,8 +29,9 @@ class Transcoder : public QObject Q_OBJECT public: - - explicit Transcoder() : QObject() {} + explicit Transcoder() + : QObject() + {} void setProducers(QList &producers); void addProducer(Mlt::Producer &producer); void addProducer(Mlt::Producer *producer); diff --git a/src/util.cpp b/src/util.cpp index 7a3e379fde..91950c1c7b 100644 --- a/src/util.cpp +++ b/src/util.cpp @@ -17,37 +17,36 @@ #include "util.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include +#include "Logger.h" #include "dialogs/transcodedialog.h" #include "mainwindow.h" -#include "shotcut_mlt_properties.h" -#include "qmltypes/qmlapplication.h" #include "proxymanager.h" +#include "qmltypes/qmlapplication.h" #include "settings.h" +#include "shotcut_mlt_properties.h" #include "transcoder.h" +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include #include @@ -78,18 +77,16 @@ QString Util::baseName(const QString &filePath, bool trimQuery) void Util::setColorsToHighlight(QWidget *widget, QPalette::ColorRole role) { if (role == QPalette::Base) { - widget->setStyleSheet( - "QLineEdit {" - "font-weight: bold;" - "background-color: palette(highlight);" - "color: palette(highlighted-text);" - "selection-background-color: palette(alternate-base);" - "selection-color: palette(text);" - "}" - "QLineEdit:hover {" - "border: 2px solid palette(button-text);" - "}" - ); + widget->setStyleSheet("QLineEdit {" + "font-weight: bold;" + "background-color: palette(highlight);" + "color: palette(highlighted-text);" + "selection-background-color: palette(alternate-base);" + "selection-color: palette(text);" + "}" + "QLineEdit:hover {" + "border: 2px solid palette(button-text);" + "}"); } else { QPalette palette = QApplication::palette(); palette.setColor(role, palette.color(palette.Highlight)); @@ -140,11 +137,12 @@ bool Util::warnIfNotWritable(const QString &filePath, QWidget *parent, const QSt } if (!info.isWritable()) { info = QFileInfo(filePath); - QMessageBox::warning(parent, caption, + QMessageBox::warning(parent, + caption, QObject::tr("Unable to write file %1\n" "Perhaps you do not have permission.\n" "Try again with a different folder.") - .arg(info.fileName())); + .arg(info.fileName())); return true; } } @@ -155,7 +153,8 @@ QString Util::producerTitle(const Mlt::Producer &producer) { QString result; Mlt::Producer &p = const_cast(producer); - if (!p.is_valid() || p.is_blank()) return result; + if (!p.is_valid() || p.is_blank()) + return result; if (p.get(kShotcutTransitionProperty)) return QObject::tr("Transition"); if (p.get(kTrackNameProperty)) @@ -179,19 +178,19 @@ QString Util::removeFileScheme(QUrl &url, bool fromPercentEncoding) static inline bool isValidGoProFirstFilePrefix(const QFileInfo &info) { - QStringList list {"GOPR", "GH01", "GL01", "GM01", "GS01", "GX01"}; + QStringList list{"GOPR", "GH01", "GL01", "GM01", "GS01", "GX01"}; return list.contains(info.baseName().left(4).toUpper()); } static inline bool isValidGoProPrefix(const QFileInfo &info) { - QStringList list {"GP", "GH", "GL", "GM", "GS", "GX"}; + QStringList list{"GP", "GH", "GL", "GM", "GS", "GX"}; return list.contains(info.baseName().left(2).toUpper()); } static inline bool isValidGoProSuffix(const QFileInfo &info) { - QStringList list {"MP4", "LRV", "360", "WAV"}; + QStringList list{"MP4", "LRV", "360", "WAV"}; return list.contains(info.suffix().toUpper()); } @@ -211,7 +210,7 @@ const QStringList Util::sortedFileList(const QList &urls) foreach (QUrl url, urls) { QFileInfo fi(removeFileScheme(url, false)); if (fi.baseName().size() == 8 && isValidGoProSuffix(fi) && isValidGoProPrefix(fi) - && !isValidGoProFirstFilePrefix(fi)) { + && !isValidGoProFirstFilePrefix(fi)) { QString goproNumber = fi.baseName().mid(4); // Only if there is a matching main GoPro file. if (goproFiles.contains(goproNumber) && goproFiles[goproNumber].size()) { @@ -232,8 +231,8 @@ const QStringList Util::sortedFileList(const QList &urls) // Add all the non-GoPro files. for (auto url : urls) { QFileInfo fi(removeFileScheme(url, false)); - if (fi.baseName().size() == 8 && isValidGoProSuffix(fi) && - (isValidGoProFirstFilePrefix(fi) || isValidGoProPrefix(fi))) { + if (fi.baseName().size() == 8 && isValidGoProSuffix(fi) + && (isValidGoProFirstFilePrefix(fi) || isValidGoProPrefix(fi))) { QString goproNumber = fi.baseName().mid(4); if (goproFiles.contains(goproNumber) && goproFiles[goproNumber].contains(fi.filePath())) continue; @@ -268,18 +267,16 @@ QList Util::expandDirectories(const QList &urls) bool Util::isDecimalPoint(QChar ch) { // See https://en.wikipedia.org/wiki/Decimal_separator#Unicode_characters - return ch == '.' || ch == ',' || ch == '\'' || ch == ' ' - || ch == QChar(0x00B7) || ch == QChar(0x2009) || ch == QChar(0x202F) - || ch == QChar(0x02D9) || ch == QChar(0x066B) || ch == QChar(0x066C) - || ch == QChar(0x2396); + return ch == '.' || ch == ',' || ch == '\'' || ch == ' ' || ch == QChar(0x00B7) + || ch == QChar(0x2009) || ch == QChar(0x202F) || ch == QChar(0x02D9) + || ch == QChar(0x066B) || ch == QChar(0x066C) || ch == QChar(0x2396); } bool Util::isNumeric(QString &str) { for (int i = 0; i < str.size(); ++i) { auto ch = str[i]; - if (ch != '+' && ch != '-' && ch.toLower() != 'e' - && !isDecimalPoint(ch) && !ch.isDigit()) + if (ch != '+' && ch != '-' && ch.toLower() != 'e' && !isDecimalPoint(ch) && !ch.isDigit()) return false; } return true; @@ -318,15 +315,19 @@ bool Util::convertDecimalPoints(QString &str, QChar decimalPoint) return result; } -void Util::showFrameRateDialog(const QString &caption, int numerator, QDoubleSpinBox *spinner, +void Util::showFrameRateDialog(const QString &caption, + int numerator, + QDoubleSpinBox *spinner, QWidget *parent) { double fps = numerator / 1001.0; - QMessageBox dialog(QMessageBox::Question, caption, + QMessageBox dialog(QMessageBox::Question, + caption, QObject::tr("The value you entered is very similar to the common,\n" "more standard %1 = %2/1001.\n\n" "Do you want to use %1 = %2/1001 instead?") - .arg(fps, 0, 'f', 6).arg(numerator), + .arg(fps, 0, 'f', 6) + .arg(numerator), QMessageBox::No | QMessageBox::Yes, parent); dialog.setDefaultButton(QMessageBox::Yes); @@ -341,8 +342,10 @@ QTemporaryFile *Util::writableTemporaryFile(const QString &filePath, const QStri { // filePath should already be checked writable. QFileInfo info(filePath); - QString templateFileName = templateName.isEmpty() ? - QStringLiteral("%1.XXXXXX").arg(QCoreApplication::applicationName()) : templateName; + QString templateFileName + = templateName.isEmpty() + ? QStringLiteral("%1.XXXXXX").arg(QCoreApplication::applicationName()) + : templateName; // First, try the system temp dir. QString templateFilePath = QDir(QDir::tempPath()).filePath(templateFileName); @@ -377,18 +380,13 @@ void Util::applyCustomProperties(Mlt::Producer &destination, Mlt::Producer &sour p.clear(kOriginalOutProperty); if (!p.get_int(kIsProxyProperty)) p.clear(kOriginalResourceProperty); - destination.pass_list(source, - "mlt_service, audio_index, video_index, astream, vstream, force_progressive, force_tff," - "force_aspect_ratio, video_delay, color_range, warp_speed, warp_pitch, rotate," - kAspectRatioNumerator "," - kAspectRatioDenominator "," - kCommentProperty "," - kShotcutProducerProperty "," - kDefaultAudioIndexProperty "," - kOriginalInProperty "," - kOriginalOutProperty "," - kOriginalResourceProperty "," - kDisableProxyProperty); + destination.pass_list( + source, + "mlt_service, audio_index, video_index, astream, vstream, force_progressive, force_tff," + "force_aspect_ratio, video_delay, color_range, warp_speed, warp_pitch, " + "rotate," kAspectRatioNumerator "," kAspectRatioDenominator "," kCommentProperty + "," kShotcutProducerProperty "," kDefaultAudioIndexProperty "," kOriginalInProperty + "," kOriginalOutProperty "," kOriginalResourceProperty "," kDisableProxyProperty); if (!destination.get("_shotcut:resource")) { destination.set("_shotcut:resource", destination.get("resource")); destination.set("_shotcut:length", destination.get("length")); @@ -523,8 +521,8 @@ bool Util::isMemoryLow() unsigned int availableKB = UINT_MAX; QFile meminfo("/proc/meminfo"); if (meminfo.open(QIODevice::ReadOnly)) { - for (auto line = meminfo.readLine(1024); availableKB == UINT_MAX - && !line.isEmpty(); line = meminfo.readLine(1024)) { + for (auto line = meminfo.readLine(1024); availableKB == UINT_MAX && !line.isEmpty(); + line = meminfo.readLine(1024)) { if (line.startsWith("MemAvailable")) { const auto &fields = line.split(' '); for (const auto &s : fields) { @@ -550,7 +548,7 @@ QString Util::removeQueryString(const QString &s) if (i < 0) { i = s.lastIndexOf("%5C?"); } - if (i > 0 ) { + if (i > 0) { return s.left(i); } return s; @@ -619,7 +617,7 @@ void Util::cameraFrameRateSize(const QByteArray &deviceName, qreal &frameRate, Q camera->setCameraFormat(currentFormat); for (const auto &format : camera->cameraDevice().videoFormats()) { if (format.resolution().width() > currentFormat.resolution().width() - && format.resolution().height() > currentFormat.resolution().height()) { + && format.resolution().height() > currentFormat.resolution().height()) { camera->setCameraFormat(format); currentFormat = format; } @@ -691,20 +689,15 @@ QString Util::updateCaption(Mlt::Producer *producer) void Util::passProducerProperties(Mlt::Producer *src, Mlt::Producer *dst) { - dst->pass_list(*src, "audio_index, video_index, astream, vstream, force_aspect_ratio," - "video_delay, force_progressive, force_tff, force_full_range, color_range, warp_pitch, rotate," - kAspectRatioNumerator "," - kAspectRatioDenominator "," - kShotcutHashProperty "," - kPlaylistIndexProperty "," - kShotcutSkipConvertProperty "," - kCommentProperty "," - kDefaultAudioIndexProperty "," - kShotcutCaptionProperty "," - kOriginalResourceProperty "," - kDisableProxyProperty "," - kIsProxyProperty "," - kShotcutProducerProperty); + dst->pass_list(*src, + "audio_index, video_index, astream, vstream, force_aspect_ratio," + "video_delay, force_progressive, force_tff, force_full_range, color_range, " + "warp_pitch, rotate," kAspectRatioNumerator "," kAspectRatioDenominator + "," kShotcutHashProperty "," kPlaylistIndexProperty + "," kShotcutSkipConvertProperty "," kCommentProperty + "," kDefaultAudioIndexProperty "," kShotcutCaptionProperty + "," kOriginalResourceProperty "," kDisableProxyProperty "," kIsProxyProperty + "," kShotcutProducerProperty); QString shotcutProducer(src->get(kShotcutProducerProperty)); QString service(src->get("mlt_service")); if (service.startsWith("avformat") || shotcutProducer == "avformat") @@ -718,16 +711,17 @@ bool Util::warnIfLowDiskSpace(const QString &path) QStorageInfo si(QFileInfo(path).path()); LOG_DEBUG() << si.bytesAvailable() << "bytes available on" << si.displayName(); if (si.isValid() && si.bytesAvailable() < kFreeSpaceThesholdGB) { - QMessageBox dialog(QMessageBox::Question, QApplication::applicationDisplayName(), + QMessageBox dialog(QMessageBox::Question, + QApplication::applicationDisplayName(), QObject::tr("The drive you chose only has %1 MiB of free space.\n" "Do you still want to continue?") - .arg(si.bytesAvailable() / 1024 / 1024), + .arg(si.bytesAvailable() / 1024 / 1024), QMessageBox::No | QMessageBox::Yes); dialog.setWindowModality(QmlApplication::dialogModality()); dialog.setDefaultButton(QMessageBox::Yes); dialog.setEscapeButton(QMessageBox::No); - dialog.setCheckBox(new QCheckBox(QObject::tr("Do not show this anymore.", - "Export free disk space warning dialog"))); + dialog.setCheckBox(new QCheckBox( + QObject::tr("Do not show this anymore.", "Export free disk space warning dialog"))); int result = dialog.exec(); if (dialog.checkBox()->isChecked()) Settings.setEncodeFreeSpaceCheck(false); @@ -817,11 +811,13 @@ QString Util::getConversionAdvice(Mlt::Producer *producer) if (!Util::trcIsCompatible(trc)) { QString trcString = Util::trcString(trc); LOG_INFO() << resource << "Probable HDR" << trcString; - advice = QObject::tr("This file uses color transfer characteristics %1, which may result in incorrect colors or brightness in Shotcut.").arg( - trcString); + advice = QObject::tr("This file uses color transfer characteristics %1, which may result " + "in incorrect colors or brightness in Shotcut.") + .arg(trcString); } else if (producer->get_int("meta.media.variable_frame_rate")) { LOG_INFO() << resource << "is variable frame rate"; - advice = QObject::tr("This file is variable frame rate, which is not reliable for editing."); + advice = QObject::tr( + "This file is variable frame rate, which is not reliable for editing."); } else if (QFile::exists(resource) && !MLT.isSeekable(producer)) { LOG_INFO() << resource << "is not seekable"; advice = QObject::tr("This file does not support seeking and cannot be used for editing."); @@ -834,28 +830,29 @@ QString Util::getConversionAdvice(Mlt::Producer *producer) mlt_color Util::mltColorFromQColor(const QColor &color) { - return mlt_color { - static_cast(color.red()), - static_cast(color.green()), - static_cast(color.blue()), - static_cast(color.alpha()) - }; + return mlt_color{static_cast(color.red()), + static_cast(color.green()), + static_cast(color.blue()), + static_cast(color.alpha())}; } void Util::offerSingleFileConversion(QString &message, Mlt::Producer *producer, QWidget *parent) { - TranscodeDialog dialog(message.append( - QObject::tr(" Do you want to convert it to an edit-friendly format?\n\n" - "If yes, choose a format below and then click OK to choose a file name. " - "After choosing a file name, a job is created. " - "When it is done, it automatically replaces clips, or you can double-click the job to open it.\n")), - producer->get_int("progressive"), parent); + TranscodeDialog + dialog(message.append(QObject::tr( + " Do you want to convert it to an edit-friendly format?\n\n" + "If yes, choose a format below and then click OK to choose a file name. " + "After choosing a file name, a job is created. " + "When it is done, it automatically replaces clips, or you can double-click the " + "job to open it.\n")), + producer->get_int("progressive"), + parent); dialog.setWindowModality(QmlApplication::dialogModality()); dialog.showCheckBox(); dialog.set709Convert(!Util::trcIsCompatible(producer->get_int("meta.media.color_trc"))); dialog.showSubClipCheckBox(); - LOG_DEBUG() << "in" << producer->get_in() << "out" << producer->get_out() << "length" << - producer->get_length() - 1; + LOG_DEBUG() << "in" << producer->get_in() << "out" << producer->get_out() << "length" + << producer->get_length() - 1; dialog.setSubClipChecked(producer->get_in() > 0 || producer->get_out() < producer->get_length() - 1); auto fps = Util::getAndroidFrameRate(producer); @@ -894,8 +891,9 @@ Mlt::Producer Util::openMltVirtualClip(const QString &path) Mlt::Producer xmlProducer(nullptr, "xml-clip", path.toUtf8().constData()); QScopedPointer testProfile(xmlProducer.profile()); if (Settings.playerGPU() && MLT.profile().is_explicit()) { - if (testProfile->width() != MLT.profile().width() || testProfile->height() != MLT.profile().height() - || Util::isFpsDifferent(MLT.profile().fps(), testProfile->fps())) { + if (testProfile->width() != MLT.profile().width() + || testProfile->height() != MLT.profile().height() + || Util::isFpsDifferent(MLT.profile().fps(), testProfile->fps())) { return Mlt::Producer(); } } diff --git a/src/util.h b/src/util.h index da009161bc..65777d4ab1 100644 --- a/src/util.h +++ b/src/util.h @@ -18,11 +18,11 @@ #ifndef UTIL_H #define UTIL_H -#include +#include +#include #include +#include #include -#include -#include class QWidget; class QDoubleSpinBox; @@ -36,6 +36,7 @@ class Util { private: Util() {} + public: static QString baseName(const QString &filePath, bool trimQuery = false); static void setColorsToHighlight(QWidget *widget, QPalette::ColorRole role = QPalette::Window); @@ -50,11 +51,15 @@ class Util static bool isNumeric(QString &str); static bool convertNumericString(QString &str, QChar decimalPoint); static bool convertDecimalPoints(QString &str, QChar decimalPoint); - static void showFrameRateDialog(const QString &caption, int numerator, QDoubleSpinBox *spinner, + static void showFrameRateDialog(const QString &caption, + int numerator, + QDoubleSpinBox *spinner, QWidget *parent = Q_NULLPTR); static QTemporaryFile *writableTemporaryFile(const QString &filePath = QString(), const QString &templateName = QString()); - static void applyCustomProperties(Mlt::Producer &destination, Mlt::Producer &source, int in, + static void applyCustomProperties(Mlt::Producer &destination, + Mlt::Producer &source, + int in, int out); static QString getFileHash(const QString &path); static QString getHash(Mlt::Properties &properties); @@ -78,7 +83,9 @@ class Util static bool trcIsCompatible(int trc); static QString getConversionAdvice(Mlt::Producer *producer); static mlt_color mltColorFromQColor(const QColor &color); - static void offerSingleFileConversion(QString &message, Mlt::Producer *producer, QWidget *parent); + static void offerSingleFileConversion(QString &message, + Mlt::Producer *producer, + QWidget *parent); static double getAndroidFrameRate(Mlt::Producer *producer); static double getSuggestedFrameRate(Mlt::Producer *producer); static Mlt::Producer openMltVirtualClip(const QString &path); diff --git a/src/videowidget.cpp b/src/videowidget.cpp index ca1ff58b57..3bf2a3c564 100644 --- a/src/videowidget.cpp +++ b/src/videowidget.cpp @@ -15,19 +15,21 @@ * along with this program. If not, see . */ -#include -#include +#include "videowidget.h" + +#include "Logger.h" +#include "mainwindow.h" +#include "qmltypes/qmlfilter.h" +#include "qmltypes/qmlutilities.h" +#include "settings.h" + +#include #include #include -#include #include -#include -#include -#include "videowidget.h" -#include "settings.h" -#include "qmltypes/qmlutilities.h" -#include "qmltypes/qmlfilter.h" -#include "mainwindow.h" +#include +#include +#include using namespace Mlt; @@ -62,7 +64,10 @@ VideoWidget::VideoWidget(QObject *parent) m_glslManager.reset(); } - connect(quickWindow(), &QQuickWindow::visibilityChanged, this, &VideoWidget::setBlankScene, + connect(quickWindow(), + &QQuickWindow::visibilityChanged, + this, + &VideoWidget::setBlankScene, Qt::QueuedConnection); connect(&m_refreshTimer, &QTimer::timeout, this, &VideoWidget::onRefreshTimeout); connect(this, &VideoWidget::rectChanged, this, &VideoWidget::zoomChanged); @@ -85,19 +90,23 @@ void VideoWidget::initialize() { LOG_DEBUG() << "begin"; m_frameRenderer = new FrameRenderer(); - connect(m_frameRenderer, &FrameRenderer::frameDisplayed, this, - &VideoWidget::onFrameDisplayed, Qt::QueuedConnection); - connect(m_frameRenderer, &FrameRenderer::frameDisplayed, this, - &VideoWidget::frameDisplayed, Qt::QueuedConnection); + connect(m_frameRenderer, + &FrameRenderer::frameDisplayed, + this, + &VideoWidget::onFrameDisplayed, + Qt::QueuedConnection); + connect(m_frameRenderer, + &FrameRenderer::frameDisplayed, + this, + &VideoWidget::frameDisplayed, + Qt::QueuedConnection); connect(m_frameRenderer, SIGNAL(imageReady()), SIGNAL(imageReady())); m_initSem.release(); m_isInitialized = true; LOG_DEBUG() << "end"; } -void VideoWidget::renderVideo() -{ -} +void VideoWidget::renderVideo() {} void VideoWidget::setBlankScene() { @@ -147,7 +156,8 @@ void VideoWidget::onRefreshTimeout() void VideoWidget::mousePressEvent(QMouseEvent *event) { QQuickWidget::mousePressEvent(event); - if (event->isAccepted()) return; + if (event->isAccepted()) + return; if (event->button() == Qt::LeftButton) m_dragStart = event->pos(); else if (event->button() == Qt::MiddleButton) @@ -159,7 +169,8 @@ void VideoWidget::mousePressEvent(QMouseEvent *event) void VideoWidget::mouseMoveEvent(QMouseEvent *event) { QQuickWidget::mouseMoveEvent(event); - if (event->isAccepted()) return; + if (event->isAccepted()) + return; if (event->buttons() & Qt::MiddleButton) { emit offsetChanged(m_offset + m_mousePosition - event->pos()); m_mousePosition = event->pos(); @@ -195,7 +206,8 @@ void VideoWidget::mouseMoveEvent(QMouseEvent *event) mimeData->setText(QString::number(MLT.producer()->get_playtime())); if (m_frameRenderer && m_frameRenderer->getDisplayFrame().is_valid()) { Mlt::Frame displayFrame(m_frameRenderer->getDisplayFrame().clone(false, true)); - QImage displayImage = MLT.image(&displayFrame, 45 * MLT.profile().dar(), 45).scaledToHeight(45); + QImage displayImage + = MLT.image(&displayFrame, 45 * MLT.profile().dar(), 45).scaledToHeight(45); drag->setPixmap(QPixmap::fromImage(displayImage)); } drag->setHotSpot(QPoint(0, 0)); @@ -205,7 +217,8 @@ void VideoWidget::mouseMoveEvent(QMouseEvent *event) void VideoWidget::keyPressEvent(QKeyEvent *event) { QQuickWidget::keyPressEvent(event); - if (event->isAccepted()) return; + if (event->isAccepted()) + return; MAIN.keyPressEvent(event); } @@ -256,7 +269,9 @@ static void onThreadCreate(mlt_properties owner, VideoWidget *self, mlt_event_da Q_UNUSED(owner) auto threadData = (mlt_event_data_thread *) Mlt::EventData(data).to_object(); if (threadData) { - self->createThread((RenderThread **) threadData->thread, threadData->function, threadData->data); + self->createThread((RenderThread **) threadData->thread, + threadData->function, + threadData->data); } } @@ -301,7 +316,7 @@ void VideoWidget::stopGlsl() //Technically, this should be the correct thing to do, but it appears //some changes in the 15.01 and 15.03 releases have created regression //with respect to restarting the consumer in GPU mode. -// m_glslManager->fire_event("close glsl"); + // m_glslManager->fire_event("close glsl"); } static void onThreadStopped(mlt_properties owner, VideoWidget *self) @@ -328,7 +343,8 @@ int VideoWidget::reconfigure(bool isMulti) if (isMulti) m_consumer.reset(new Mlt::FilteredConsumer(previewProfile(), "multi")); else - m_consumer.reset(new Mlt::FilteredConsumer(previewProfile(), serviceName.toLatin1().constData())); + m_consumer.reset( + new Mlt::FilteredConsumer(previewProfile(), serviceName.toLatin1().constData())); m_threadStartEvent.reset(); m_threadStopEvent.reset(); @@ -341,7 +357,8 @@ int VideoWidget::reconfigure(bool isMulti) // Make an event handler for when a frame's image should be displayed m_consumer->listen("consumer-frame-show", this, (mlt_listener) on_frame_show); m_consumer->set("real_time", MLT.realTime()); - m_consumer->set("mlt_image_format", serviceName.startsWith("decklink") ? "yuv422p" : "yuv420p"); + m_consumer->set("mlt_image_format", + serviceName.startsWith("decklink") ? "yuv422p" : "yuv420p"); m_consumer->set("channels", property("audio_channels").toInt()); if (property("audio_channels").toInt() == 4) { m_consumer->set("channel_layout", "quad"); @@ -392,16 +409,19 @@ int VideoWidget::reconfigure(bool isMulti) } if (m_glslManager) { if (!m_threadCreateEvent) - m_threadCreateEvent.reset(m_consumer->listen("consumer-thread-create", this, + m_threadCreateEvent.reset(m_consumer->listen("consumer-thread-create", + this, (mlt_listener) onThreadCreate)); if (!m_threadJoinEvent) - m_threadJoinEvent.reset(m_consumer->listen("consumer-thread-join", this, - (mlt_listener) onThreadJoin)); + m_threadJoinEvent.reset( + m_consumer->listen("consumer-thread-join", this, (mlt_listener) onThreadJoin)); if (!m_threadStartEvent) - m_threadStartEvent.reset(m_consumer->listen("consumer-thread-started", this, + m_threadStartEvent.reset(m_consumer->listen("consumer-thread-started", + this, (mlt_listener) onThreadStarted)); if (!m_threadStopEvent) - m_threadStopEvent.reset(m_consumer->listen("consumer-thread-stopped", this, + m_threadStopEvent.reset(m_consumer->listen("consumer-thread-stopped", + this, (mlt_listener) onThreadStopped)); } else { emit started(); @@ -427,7 +447,7 @@ QPoint VideoWidget::offset() const if (m_zoom == 0.0) { return QPoint(0, 0); } else { - return QPoint(m_offset.x() - (MLT.profile().width() * m_zoom - width()) / 2, + return QPoint(m_offset.x() - (MLT.profile().width() * m_zoom - width()) / 2, m_offset.y() - (MLT.profile().height() * m_zoom - height()) / 2); } } @@ -514,7 +534,7 @@ void VideoWidget::setOffsetY(int y) void VideoWidget::setCurrentFilter(QmlFilter *filter, QmlMetadata *meta) { if (meta && meta->type() == QmlMetadata::Filter - && QFile::exists(meta->vuiFilePath().toLocalFile())) { + && QFile::exists(meta->vuiFilePath().toLocalFile())) { filter->producer().set(kShotcutVuiMetaProperty, 1); rootContext()->setContextProperty("filter", filter); setSource(meta->vuiFilePath()); @@ -536,8 +556,11 @@ void VideoWidget::on_frame_show(mlt_consumer, VideoWidget *widget, mlt_event_dat auto frame = Mlt::EventData(data).to_frame(); if (frame.is_valid() && frame.get_int("rendered")) { int timeout = (widget->consumer()->get_int("real_time") > 0) ? 0 : 1000; - if (widget->m_frameRenderer && widget->m_frameRenderer->semaphore()->tryAcquire(1, timeout)) { - QMetaObject::invokeMethod(widget->m_frameRenderer, "showFrame", Qt::QueuedConnection, + if (widget->m_frameRenderer + && widget->m_frameRenderer->semaphore()->tryAcquire(1, timeout)) { + QMetaObject::invokeMethod(widget->m_frameRenderer, + "showFrame", + Qt::QueuedConnection, Q_ARG(Mlt::Frame, frame)); } else if (!Settings.playerRealtime()) { LOG_WARNING() << "VideoWidget dropped frame" << frame.get_position(); @@ -550,7 +573,7 @@ RenderThread::RenderThread(thread_function_t function, void *data) , m_function{function} , m_data{data} , m_context{new QOpenGLContext} -, m_surface{new QOffscreenSurface} + , m_surface{new QOffscreenSurface} { QSurfaceFormat format; format.setProfile(QSurfaceFormat::CoreProfile); @@ -588,9 +611,7 @@ FrameRenderer::FrameRenderer() start(); } -FrameRenderer::~FrameRenderer() -{ -} +FrameRenderer::~FrameRenderer() {} void FrameRenderer::showFrame(Mlt::Frame frame) { diff --git a/src/videowidget.h b/src/videowidget.h index aac129d47f..6af1a9e418 100644 --- a/src/videowidget.h +++ b/src/videowidget.h @@ -18,14 +18,15 @@ #ifndef VIDEOWIDGET_H #define VIDEOWIDGET_H -#include -#include +#include "mltcontroller.h" +#include "sharedframe.h" + #include -#include +#include #include +#include +#include #include -#include "mltcontroller.h" -#include "sharedframe.h" class QmlFilter; class QmlMetadata; @@ -38,7 +39,7 @@ class Filter; class RenderThread; class FrameRenderer; -typedef void *(*thread_function_t )( void * ); +typedef void *(*thread_function_t)(void *); class VideoWidget : public QQuickWidget, public Controller { @@ -62,8 +63,10 @@ class VideoWidget : public QQuickWidget, public Controller void play(double speed = 1.0) { Controller::play(speed); - if (speed == 0) emit paused(); - else emit playing(); + if (speed == 0) + emit paused(); + else + emit playing(); } void seek(int position) { @@ -76,43 +79,19 @@ class VideoWidget : public QQuickWidget, public Controller Controller::pause(); emit paused(); } - int displayWidth() const - { - return m_rect.width(); - } - int displayHeight() const - { - return m_rect.height(); - } + int displayWidth() const { return m_rect.width(); } + int displayHeight() const { return m_rect.height(); } - QObject *videoWidget() - { - return this; - } - QRectF rect() const - { - return m_rect; - } - int grid() const - { - return m_grid; - } - float zoom() const - { - return m_zoom * MLT.profile().width() / m_rect.width(); - } + QObject *videoWidget() { return this; } + QRectF rect() const { return m_rect; } + int grid() const { return m_grid; } + float zoom() const { return m_zoom * MLT.profile().width() / m_rect.width(); } QPoint offset() const; QImage image() const; bool imageIsProxy() const; void requestImage() const; - bool snapToGrid() const - { - return m_snapToGrid; - } - int maxTextureSize() const - { - return m_maxTextureSize; - } + bool snapToGrid() const { return m_snapToGrid; } + int maxTextureSize() const { return m_maxTextureSize; } public slots: void setGrid(int grid); @@ -123,7 +102,7 @@ public slots: void setCurrentFilter(QmlFilter *filter, QmlMetadata *meta); void setSnapToGrid(bool snap); virtual void initialize(); - virtual void beforeRendering() {}; + virtual void beforeRendering(){}; virtual void renderVideo(); virtual void onFrameDisplayed(const SharedFrame &frame); @@ -206,17 +185,11 @@ class FrameRenderer : public QThread public: FrameRenderer(); ~FrameRenderer(); - QSemaphore *semaphore() - { - return &m_semaphore; - } + QSemaphore *semaphore() { return &m_semaphore; } SharedFrame getDisplayFrame(); Q_INVOKABLE void showFrame(Mlt::Frame frame); void requestImage(); - QImage image() const - { - return m_image; - } + QImage image() const { return m_image; } signals: void frameDisplayed(const SharedFrame &frame); @@ -229,6 +202,6 @@ class FrameRenderer : public QThread QImage m_image; }; -} // namespace +} // namespace Mlt #endif diff --git a/src/widgets/alsawidget.cpp b/src/widgets/alsawidget.cpp index 574e520b20..823dd8ce8a 100644 --- a/src/widgets/alsawidget.cpp +++ b/src/widgets/alsawidget.cpp @@ -17,14 +17,15 @@ #include "alsawidget.h" #include "ui_alsawidget.h" + #include "mltcontroller.h" -#include "util.h" -#include "shotcut_mlt_properties.h" #include "settings.h" +#include "shotcut_mlt_properties.h" +#include "util.h" -AlsaWidget::AlsaWidget(QWidget *parent) : - QWidget(parent), - ui(new Ui::AlsaWidget) +AlsaWidget::AlsaWidget(QWidget *parent) + : QWidget(parent) + , ui(new Ui::AlsaWidget) { ui->setupUi(this); Util::setColorsToHighlight(ui->label_2); diff --git a/src/widgets/alsawidget.h b/src/widgets/alsawidget.h index 8fea010206..0f391513ae 100644 --- a/src/widgets/alsawidget.h +++ b/src/widgets/alsawidget.h @@ -18,9 +18,10 @@ #ifndef ALSAWIDGET_H #define ALSAWIDGET_H -#include #include "abstractproducerwidget.h" +#include + namespace Ui { class AlsaWidget; } diff --git a/src/widgets/audiometerwidget.cpp b/src/widgets/audiometerwidget.cpp index e8262cf47b..cceee02ab6 100644 --- a/src/widgets/audiometerwidget.cpp +++ b/src/widgets/audiometerwidget.cpp @@ -16,19 +16,22 @@ */ #include "audiometerwidget.h" + #include "iecscale.h" -#include + #include -#include +#include #include +#include static const int TEXT_PAD = 2; -AudioMeterWidget::AudioMeterWidget(QWidget *parent): QWidget(parent) +AudioMeterWidget::AudioMeterWidget(QWidget *parent) + : QWidget(parent) { const QFont &font = QWidget::font(); - const int fontSize = font.pointSize() - (font.pointSize() > 10 ? 2 : (font.pointSize() > 8 ? 1 : - 0)); + const int fontSize = font.pointSize() + - (font.pointSize() > 10 ? 2 : (font.pointSize() > 8 ? 1 : 0)); QWidget::setFont(QFont(font.family(), fontSize)); QWidget::setMouseTracking(true); } @@ -128,7 +131,7 @@ void AudioMeterWidget::calcGraphRect() m_gradient.setColorAt(IEC_ScaleMax(-12.0, m_maxDb), Qt::green); m_gradient.setColorAt(IEC_ScaleMax(-6.0, m_maxDb), Qt::yellow); m_gradient.setColorAt(IEC_ScaleMax(0.0, m_maxDb), Qt::red); - if (m_maxDb > 0.0 ) { + if (m_maxDb > 0.0) { m_gradient.setColorAt(IEC_ScaleMax(m_maxDb, m_maxDb), Qt::darkRed); } } @@ -140,7 +143,8 @@ void AudioMeterWidget::drawDbLabels(QPainter &p) int x = 0; int y = 0; - if (dbLabelCount == 0) return; + if (dbLabelCount == 0) + return; p.setPen(palette().text().color().rgb()); @@ -152,7 +156,8 @@ void AudioMeterWidget::drawDbLabels(QPainter &p) int value = m_dbLabels[i]; QString label = QString::asprintf("%d", value); int labelWidth = fontMetrics().horizontalAdvance(label); - x = m_graphRect.left() + IEC_ScaleMax(value, m_maxDb) * m_graphRect.width() - labelWidth / 2; + x = m_graphRect.left() + IEC_ScaleMax(value, m_maxDb) * m_graphRect.width() + - labelWidth / 2; if (x + labelWidth > width()) { x = width() - labelWidth; } @@ -168,8 +173,9 @@ void AudioMeterWidget::drawDbLabels(QPainter &p) int value = m_dbLabels[i]; QString label = QString::asprintf("%d", value); x = m_graphRect.left() - fontMetrics().horizontalAdvance(label) - TEXT_PAD; - y = m_graphRect.bottom() - qRound(IEC_ScaleMax(value, - m_maxDb) * (double)m_graphRect.height() - (double)textHeight / 2.0); + y = m_graphRect.bottom() + - qRound(IEC_ScaleMax(value, m_maxDb) * (double) m_graphRect.height() + - (double) textHeight / 2.0); if (y - textHeight < 0) { y = textHeight; } @@ -189,24 +195,25 @@ void AudioMeterWidget::drawChanLabels(QPainter &p) int x = 0; int y = 0; - if (chanLabelCount == 0) return; + if (chanLabelCount == 0) + return; p.setPen(palette().text().color().rgb()); if (m_orient == Qt::Horizontal) { // Channel labels are vertical along the left side. - while ( textHeight * chanLabelCount / stride > m_graphRect.width() ) { + while (textHeight * chanLabelCount / stride > m_graphRect.width()) { stride++; } int prevY = m_graphRect.top(); for (int i = 0; i < chanLabelCount; i += stride) { const QString &label = m_chanLabels[i]; - y = m_graphRect.bottom() - (chanLabelCount - 1 - i) * m_barSize.height() - m_barSize.height() / 2 + - textHeight / 2; + y = m_graphRect.bottom() - (chanLabelCount - 1 - i) * m_barSize.height() + - m_barSize.height() / 2 + textHeight / 2; x = m_graphRect.left() - fontMetrics().horizontalAdvance(label) - TEXT_PAD; - if ( y - prevY >= TEXT_PAD) { + if (y - prevY >= TEXT_PAD) { p.drawText(x, y, label); prevY = y - textHeight; } @@ -221,7 +228,7 @@ void AudioMeterWidget::drawChanLabels(QPainter &p) chanLabelWidth = width > chanLabelWidth ? width : chanLabelWidth; } - while ( chanLabelWidth * chanLabelCount / stride > m_graphRect.width() ) { + while (chanLabelWidth * chanLabelCount / stride > m_graphRect.width()) { stride++; } @@ -229,8 +236,8 @@ void AudioMeterWidget::drawChanLabels(QPainter &p) y = m_graphRect.bottom() + textHeight + TEXT_PAD; for (int i = 0; i < chanLabelCount; i += stride) { QString label = m_chanLabels[i]; - x = m_graphRect.left() + i * m_barSize.width() + m_barSize.width() / 2 - - fontMetrics().horizontalAdvance(label) / 2; + x = m_graphRect.left() + i * m_barSize.width() + m_barSize.width() / 2 + - fontMetrics().horizontalAdvance(label) / 2; if (x > prevX) { p.drawText(x, y, label); prevX = x + fontMetrics().horizontalAdvance(label); @@ -259,7 +266,7 @@ void AudioMeterWidget::drawBars(QPainter &p) bar.setLeft(m_graphRect.left() + i * m_barSize.width() + 1); bar.setRight(bar.left() + m_barSize.width() - 1); bar.setBottom(m_graphRect.bottom()); - bar.setTop(bar.bottom() - qRound((double)m_barSize.height() * level)); + bar.setTop(bar.bottom() - qRound((double) m_barSize.height() * level)); p.drawRoundedRect(bar, 3, 3); } } @@ -308,12 +315,12 @@ void AudioMeterWidget::updateToolTip() if (this->rect().contains(mousePos)) { if (m_orient == Qt::Horizontal) { if (mousePos.y() <= m_graphRect.bottom() && mousePos.y() >= m_graphRect.top()) { - chan = (int)(m_graphRect.bottom() - mousePos.y()) / (int)m_barSize.height(); + chan = (int) (m_graphRect.bottom() - mousePos.y()) / (int) m_barSize.height(); chan = m_levels.size() - 1 - chan; } } else { if (mousePos.x() >= m_graphRect.left() && mousePos.x() <= m_graphRect.right()) { - chan = (int)(mousePos.x() - m_graphRect.left()) / (int)m_barSize.width(); + chan = (int) (mousePos.x() - m_graphRect.left()) / (int) m_barSize.width(); } } } @@ -342,7 +349,7 @@ void AudioMeterWidget::paintEvent(QPaintEvent * /*e*/) return; QPainter p(this); - p.setRenderHints( QPainter::Antialiasing ); + p.setRenderHints(QPainter::Antialiasing); drawDbLabels(p); drawChanLabels(p); diff --git a/src/widgets/audiometerwidget.h b/src/widgets/audiometerwidget.h index c1d97736c3..ab37e9d5f2 100644 --- a/src/widgets/audiometerwidget.h +++ b/src/widgets/audiometerwidget.h @@ -19,10 +19,11 @@ #ifndef AUDIOMETERWIDGET_H #define AUDIOMETERWIDGET_H -#include -#include -#include #include +#include +#include +#include + #include class QLabel; diff --git a/src/widgets/audioscale.cpp b/src/widgets/audioscale.cpp index a6a63f83a6..5ae3002e9b 100644 --- a/src/widgets/audioscale.cpp +++ b/src/widgets/audioscale.cpp @@ -16,17 +16,19 @@ */ #include "audioscale.h" + +#include "Logger.h" #include "iecscale.h" + #include #include -#include -AudioScale::AudioScale(QWidget *parent) : - QWidget(parent) +AudioScale::AudioScale(QWidget *parent) + : QWidget(parent) { const QFont &font = QWidget::font(); - const int fontSize = font.pointSize() - (font.pointSize() > 10 ? 2 : (font.pointSize() > 8 ? 1 : - 0)); + const int fontSize = font.pointSize() + - (font.pointSize() > 10 ? 2 : (font.pointSize() > 8 ? 1 : 0)); setFont(QFont(font.family(), fontSize)); setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Expanding); setMinimumWidth(fontMetrics().horizontalAdvance("-60")); diff --git a/src/widgets/audioscale.h b/src/widgets/audioscale.h index c5948f4609..c53f0fa7a6 100644 --- a/src/widgets/audioscale.h +++ b/src/widgets/audioscale.h @@ -32,7 +32,6 @@ class AudioScale : public QWidget private: QVector dbscale; - }; #endif // AUDIOSCALE_H diff --git a/src/widgets/avformatproducerwidget.cpp b/src/widgets/avformatproducerwidget.cpp index dc96c979b6..b5a3dc8fd1 100644 --- a/src/widgets/avformatproducerwidget.cpp +++ b/src/widgets/avformatproducerwidget.cpp @@ -17,28 +17,30 @@ #include "avformatproducerwidget.h" #include "ui_avformatproducerwidget.h" -#include "util.h" -#include "mltcontroller.h" -#include "shotcut_mlt_properties.h" + +#include "Logger.h" #include "dialogs/filedatedialog.h" #include "dialogs/listselectiondialog.h" +#include "dialogs/longuitask.h" #include "jobqueue.h" -#include "jobs/ffprobejob.h" +#include "jobs/bitrateviewerjob.h" #include "jobs/ffmpegjob.h" +#include "jobs/ffprobejob.h" +#include "jobs/gopro2gpxjob.h" #include "jobs/meltjob.h" #include "jobs/postjobaction.h" -#include "jobs/gopro2gpxjob.h" -#include "settings.h" #include "mainwindow.h" -#include "Logger.h" -#include "qmltypes/qmlapplication.h" +#include "mltcontroller.h" #include "proxymanager.h" -#include "dialogs/longuitask.h" +#include "qmltypes/qmlapplication.h" +#include "settings.h" +#include "shotcut_mlt_properties.h" #include "spatialmedia/spatialmedia.h" #include "transcoder.h" -#include "jobs/bitrateviewerjob.h" +#include "util.h" #include + #include static const auto kHandleSeconds = 15.0; @@ -55,7 +57,9 @@ AvformatProducerWidget::AvformatProducerWidget(QWidget *parent) ui->filenameLabel->setFrame(true); Util::setColorsToHighlight(ui->filenameLabel, QPalette::Base); connect(ui->applySpeedButton, SIGNAL(clicked()), SLOT(on_speedSpinBox_editingFinished())); - connect(this, SIGNAL(producerChanged(Mlt::Producer *)), SLOT(onProducerChanged(Mlt::Producer *))); + connect(this, + SIGNAL(producerChanged(Mlt::Producer *)), + SLOT(onProducerChanged(Mlt::Producer *))); } AvformatProducerWidget::~AvformatProducerWidget() @@ -66,8 +70,9 @@ AvformatProducerWidget::~AvformatProducerWidget() Mlt::Producer *AvformatProducerWidget::newProducer(Mlt::Profile &profile) { Mlt::Producer *p = 0; - if ( ui->speedSpinBox->value() == 1.0 ) { - p = new Mlt::Chain(profile, Util::GetFilenameFromProducer(producer(), false).toUtf8().constData()); + if (ui->speedSpinBox->value() == 1.0) { + p = new Mlt::Chain(profile, + Util::GetFilenameFromProducer(producer(), false).toUtf8().constData()); } else { // If the system language's numeric format and region's numeric format differ, then MLT // uses the language's numeric format while Qt is using the region's. Thus, to @@ -100,10 +105,11 @@ void AvformatProducerWidget::setProducer(Mlt::Producer *p) void AvformatProducerWidget::updateDuration() { if (m_producer->get(kFilterInProperty) && m_producer->get(kFilterOutProperty)) { - auto duration = m_producer->get_int(kFilterOutProperty) - m_producer->get_int( - kFilterInProperty) + 1; + auto duration = m_producer->get_int(kFilterOutProperty) + - m_producer->get_int(kFilterInProperty) + 1; ui->timelineDurationLabel->show(); - ui->timelineDurationText->setText(m_producer->frames_to_time(duration, Settings.timeFormat())); + ui->timelineDurationText->setText( + m_producer->frames_to_time(duration, Settings.timeFormat())); ui->timelineDurationText->show(); } else { ui->timelineDurationLabel->hide(); @@ -123,22 +129,26 @@ void AvformatProducerWidget::offerConvert(QString message, bool set709Convert, b m_producer->set(kShotcutSkipConvertProperty, true); LongUiTask::cancel(); MLT.pause(); - TranscodeDialog dialog(message.append( - tr(" Do you want to convert it to an edit-friendly format?\n\n" - "If yes, choose a format below and then click OK to choose a file name. " - "After choosing a file name, a job is created. " - "When it is done, it automatically replaces clips, or you can double-click the job to open it.\n")), - ui->scanComboBox->currentIndex(), this); + TranscodeDialog + dialog(message.append( + tr(" Do you want to convert it to an edit-friendly format?\n\n" + "If yes, choose a format below and then click OK to choose a file name. " + "After choosing a file name, a job is created. " + "When it is done, it automatically replaces clips, or you can double-click " + "the job to open it.\n")), + ui->scanComboBox->currentIndex(), + this); dialog.setWindowModality(QmlApplication::dialogModality()); if (!setSubClip) { dialog.showCheckBox(); } dialog.set709Convert(set709Convert); dialog.showSubClipCheckBox(); - LOG_DEBUG() << "in" << m_producer->get_in() << "out" << m_producer->get_out() << "length" << - m_producer->get_length() - 1; - dialog.setSubClipChecked(setSubClip && (m_producer->get_in() > 0 - || m_producer->get_out() < m_producer->get_length() - 1)); + LOG_DEBUG() << "in" << m_producer->get_in() << "out" << m_producer->get_out() << "length" + << m_producer->get_length() - 1; + dialog.setSubClipChecked( + setSubClip + && (m_producer->get_in() > 0 || m_producer->get_out() < m_producer->get_length() - 1)); auto fps = Util::getAndroidFrameRate(m_producer.get()); if (fps > 0.0) dialog.setFrameRate(fps); @@ -149,8 +159,8 @@ void AvformatProducerWidget::offerConvert(QString message, bool set709Convert, b void AvformatProducerWidget::keyPressEvent(QKeyEvent *event) { - if (ui->speedSpinBox->hasFocus() && - (event->key() == Qt::Key_Enter || event->key() == Qt::Key_Return)) { + if (ui->speedSpinBox->hasFocus() + && (event->key() == Qt::Key_Enter || event->key() == Qt::Key_Return)) { ui->speedSpinBox->clearFocus(); } else { QWidget::keyPressEvent(event); @@ -159,12 +169,15 @@ void AvformatProducerWidget::keyPressEvent(QKeyEvent *event) void AvformatProducerWidget::onProducerChanged(Mlt::Producer *producer) { - if ( producer->get_producer() == m_producer->get_producer() ) { + if (producer->get_producer() == m_producer->get_producer()) { if (Settings.playerGPU()) { QTimer::singleShot(50, this, &AvformatProducerWidget::reloadProducerValues); } else { auto task = new ProbeTask(producer); - connect(task, &ProbeTask::probeFinished, this, &AvformatProducerWidget::reloadProducerValues, + connect(task, + &ProbeTask::probeFinished, + this, + &AvformatProducerWidget::reloadProducerValues, Qt::QueuedConnection); QThreadPool::globalInstance()->start(task, 10); } @@ -178,7 +191,7 @@ void AvformatProducerWidget::reopen(Mlt::Producer *p) int position = m_producer->position(); double speed = m_producer->get_speed(); - if ( m_recalcDuration ) { + if (m_recalcDuration) { double oldSpeed = Util::GetSpeedFromProducer(producer()); double newSpeed = ui->speedSpinBox->value(); double speedRatio = oldSpeed / newSpeed; @@ -313,8 +326,8 @@ void AvformatProducerWidget::reloadProducerValues() int videoIndex = 0; int audioIndex = 0; int totalAudioChannels = 0; - bool populateTrackCombos = (ui->videoTrackComboBox->count() == 0 && - ui->audioTrackComboBox->count() == 0); + bool populateTrackCombos = (ui->videoTrackComboBox->count() == 0 + && ui->audioTrackComboBox->count() == 0); int color_range = !qstrcmp(m_producer->get("meta.media.color_range"), "full"); for (int i = 0; i < n; i++) { @@ -328,14 +341,14 @@ void AvformatProducerWidget::reloadProducerValues() key = QStringLiteral("meta.media.%1.codec.height").arg(i); QString height(m_producer->get(key.toLatin1().constData())); QString name = QStringLiteral("%1: %2x%3 %4") - .arg(videoIndex + 1) - .arg(width) - .arg(height) - .arg(codec); + .arg(videoIndex + 1) + .arg(width) + .arg(height) + .arg(codec); if (populateTrackCombos) { if (ui->videoTrackComboBox->count() == 0) ui->videoTrackComboBox->addItem(tr("None"), -1); -#if LIBMLT_VERSION_INT >= ((7<<16)+(19<<8)) +#if LIBMLT_VERSION_INT >= ((7 << 16) + (19 << 8)) ui->videoTrackComboBox->addItem(name, videoIndex); } if (videoIndex == m_producer->get_int(kVideoIndexProperty)) { @@ -356,9 +369,9 @@ void AvformatProducerWidget::reloadProducerValues() ui->rangeComboBox->setEnabled(false); } key = QStringLiteral("meta.media.%1.codec.rotate").arg(i); - int rotation = m_producer->property_exists("rotate") ? - m_producer->get_int("rotate") : - m_producer->get_int(key.toLatin1().constData()); + int rotation = m_producer->property_exists("rotate") + ? m_producer->get_int("rotate") + : m_producer->get_int(key.toLatin1().constData()); ui->rotationComboBox->setCurrentIndex(rotation / 90); ui->videoTableWidget->setItem(3, 1, new QTableWidgetItem(pix_fmt)); key = QStringLiteral("meta.media.%1.codec.colorspace").arg(i); @@ -399,14 +412,14 @@ void AvformatProducerWidget::reloadProducerValues() key = QStringLiteral("meta.media.%1.codec.sample_rate").arg(i); QString sampleRate(m_producer->get(key.toLatin1().constData())); QString name = QStringLiteral("%1: %2 ch %3 KHz %4") - .arg(audioIndex + 1) - .arg(channels) - .arg(sampleRate.toDouble() / 1000) - .arg(codec); + .arg(audioIndex + 1) + .arg(channels) + .arg(sampleRate.toDouble() / 1000) + .arg(codec); if (populateTrackCombos) { if (ui->audioTrackComboBox->count() == 0) ui->audioTrackComboBox->addItem(tr("None"), -1); -#if LIBMLT_VERSION_INT >= ((7<<16)+(19<<8)) +#if LIBMLT_VERSION_INT >= ((7 << 16) + (19 << 8)) ui->audioTrackComboBox->addItem(name, audioIndex); } if (QString::number(audioIndex) == m_producer->get(kAudioIndexProperty)) { @@ -421,13 +434,16 @@ void AvformatProducerWidget::reloadProducerValues() key = QStringLiteral("meta.media.%1.codec.layout").arg(i); QString layout(m_producer->get(key.toLatin1().constData())); if (layout.isEmpty()) { - layout = mlt_audio_channel_layout_name(mlt_audio_channel_layout_default(channels)); + layout = mlt_audio_channel_layout_name( + mlt_audio_channel_layout_default(channels)); } QString channelsStr = QStringLiteral("%1 (%2)").arg(channels).arg(layout); ui->audioTableWidget->setItem(1, 1, new QTableWidgetItem(channelsStr)); ui->audioTableWidget->setItem(2, 1, new QTableWidgetItem(sampleRate)); key = QStringLiteral("meta.media.%1.codec.sample_fmt").arg(i); - ui->audioTableWidget->setItem(3, 1, new QTableWidgetItem( + ui->audioTableWidget->setItem(3, + 1, + new QTableWidgetItem( m_producer->get(key.toLatin1().constData()))); ui->audioTrackComboBox->setCurrentIndex(audioIndex + 1); } @@ -447,7 +463,9 @@ void AvformatProducerWidget::reloadProducerValues() } else if (m_producer->get(kAbsoluteAudioIndex) == QStringLiteral("all")) { ui->audioTrackComboBox->setCurrentIndex(ui->audioTrackComboBox->count() - 1); ui->audioTableWidget->setItem(0, 1, new QTableWidgetItem("")); - ui->audioTableWidget->setItem(1, 1, new QTableWidgetItem(QString::number(totalAudioChannels))); + ui->audioTableWidget->setItem(1, + 1, + new QTableWidgetItem(QString::number(totalAudioChannels))); ui->audioTableWidget->setItem(2, 1, new QTableWidgetItem("")); ui->audioTableWidget->setItem(3, 1, new QTableWidgetItem("")); } @@ -473,10 +491,14 @@ void AvformatProducerWidget::reloadProducerValues() int width = m_producer->get_int("meta.media.width"); int height = m_producer->get_int("meta.media.height"); if (width || height) { - bool isProxy = m_producer->get_int(kIsProxyProperty) && m_producer->get(kOriginalResourceProperty); - ui->videoTableWidget->setItem(1, 1, - new QTableWidgetItem(QStringLiteral("%1x%2 %3").arg(width).arg(height) - .arg(isProxy ? tr("(PROXY)") : ""))); + bool isProxy = m_producer->get_int(kIsProxyProperty) + && m_producer->get(kOriginalResourceProperty); + ui->videoTableWidget->setItem(1, + 1, + new QTableWidgetItem(QStringLiteral("%1x%2 %3") + .arg(width) + .arg(height) + .arg(isProxy ? tr("(PROXY)") : ""))); } double sar = m_producer->get_double("meta.media.sample_aspect_num"); @@ -513,10 +535,13 @@ void AvformatProducerWidget::reloadProducerValues() ui->aspectDenSpinBox->blockSignals(false); bool isVariableFrameRate = m_producer->get_int("meta.media.variable_frame_rate"); - if (fps() != 0.0 ) { - ui->videoTableWidget->setItem(2, 1, new QTableWidgetItem(QStringLiteral("%L1 %2").arg(fps(), 0, 'f', - 6) - .arg(isVariableFrameRate ? tr("(variable)") : ""))); + if (fps() != 0.0) { + ui->videoTableWidget->setItem(2, + 1, + new QTableWidgetItem( + QStringLiteral("%L1 %2") + .arg(fps(), 0, 'f', 6) + .arg(isVariableFrameRate ? tr("(variable)") : ""))); } int progressive = m_producer->get_int("meta.media.progressive"); @@ -544,7 +569,7 @@ void AvformatProducerWidget::reloadProducerValues() ui->metadataTable->setItem(row, 0, new QTableWidgetItem(name.section('.', -2, -2))); ui->metadataTable->setItem(row, 1, new QTableWidgetItem(m_producer->get(i))); if (ui->metadataTable->item(row, 0)->text() == "handler_name" - && QString(m_producer->get(i)).contains("GoPro")) { + && QString(m_producer->get(i)).contains("GoPro")) { ui->actionExportGPX->setEnabled(true); } ui->tabWidget->setTabEnabled(2, true); @@ -604,15 +629,18 @@ void AvformatProducerWidget::on_fieldOrderComboBox_activated(int index) void AvformatProducerWidget::on_aspectNumSpinBox_valueChanged(int) { if (m_producer) { - double new_sar = double(ui->aspectNumSpinBox->value() * m_producer->get_int("meta.media.height")) / - double(ui->aspectDenSpinBox->value() * m_producer->get_int("meta.media.width")); + double new_sar + = double(ui->aspectNumSpinBox->value() * m_producer->get_int("meta.media.height")) + / double(ui->aspectDenSpinBox->value() * m_producer->get_int("meta.media.width")); double sar = m_producer->get_double("meta.media.sample_aspect_num"); if (m_producer->get_double("meta.media.sample_aspect_den") > 0) sar /= m_producer->get_double("meta.media.sample_aspect_den"); if (m_producer->get("force_aspect_ratio") || new_sar != sar) { m_producer->set("force_aspect_ratio", QString::number(new_sar).toLatin1().constData()); - m_producer->set(kAspectRatioNumerator, ui->aspectNumSpinBox->text().toLatin1().constData()); - m_producer->set(kAspectRatioDenominator, ui->aspectDenSpinBox->text().toLatin1().constData()); + m_producer->set(kAspectRatioNumerator, + ui->aspectNumSpinBox->text().toLatin1().constData()); + m_producer->set(kAspectRatioDenominator, + ui->aspectDenSpinBox->text().toLatin1().constData()); } emit producerChanged(producer()); } @@ -632,7 +660,6 @@ void AvformatProducerWidget::on_durationSpinBox_editingFinished() recreateProducer(); } - void AvformatProducerWidget::on_speedSpinBox_editingFinished() { if (!m_producer) @@ -690,7 +717,7 @@ void AvformatProducerWidget::on_menuButton_clicked() menu.addAction(ui->actionExtractSubtitles); menu.addAction(ui->actionSetFileDate); if (Util::GetFilenameFromProducer(producer()).toLower().endsWith(".mp4") - || Util::GetFilenameFromProducer(producer()).toLower().endsWith(".mov")) { + || Util::GetFilenameFromProducer(producer()).toLower().endsWith(".mov")) { menu.addAction(ui->actionSetEquirectangular); } menu.addAction(ui->actionFFmpegVideoQuality); @@ -719,10 +746,15 @@ void AvformatProducerWidget::on_notesTextEdit_textChanged() void AvformatProducerWidget::on_actionFFmpegInfo_triggered() { QStringList args; - args << "-v" << "quiet"; - args << "-print_format" << "ini"; + args << "-v" + << "quiet"; + args << "-print_format" + << "ini"; args << "-pretty"; - args << "-show_format" << "-show_programs" << "-show_streams" << "-find_stream_info"; + args << "-show_format" + << "-show_programs" + << "-show_streams" + << "-find_stream_info"; args << Util::GetFilenameFromProducer(producer()); AbstractJob *job = new FfprobeJob(args.last(), args); job->start(); @@ -733,21 +765,27 @@ void AvformatProducerWidget::on_actionFFmpegIntegrityCheck_triggered() QString resource = Util::GetFilenameFromProducer(producer()); QStringList args; args << "-xerror"; - args << "-err_detect" << "+explode"; - args << "-v" << "info"; + args << "-err_detect" + << "+explode"; + args << "-v" + << "info"; args << "-i" << resource; - args << "-map" << "0"; - args << "-f" << "null" << "pipe:"; + args << "-map" + << "0"; + args << "-f" + << "null" + << "pipe:"; JOBS.add(new FfmpegJob(resource, args)); } void AvformatProducerWidget::on_actionFFmpegConvert_triggered() { - TranscodeDialog dialog( - tr("Choose an edit-friendly format below and then click OK to choose a file name. " - "After choosing a file name, a job is created. " - "When it is done, double-click the job to open it.\n"), - ui->scanComboBox->currentIndex(), this); + TranscodeDialog + dialog(tr("Choose an edit-friendly format below and then click OK to choose a file name. " + "After choosing a file name, a job is created. " + "When it is done, double-click the job to open it.\n"), + ui->scanComboBox->currentIndex(), + this); dialog.setWindowModality(QmlApplication::dialogModality()); dialog.set709Convert(ui->videoTableWidget->item(5, 1)->data(Qt::UserRole).toInt() > 7); dialog.showSubClipCheckBox(); @@ -795,8 +833,8 @@ bool AvformatProducerWidget::revertToOriginalResource() void AvformatProducerWidget::setSyncVisibility() { - bool visible = ui->tabWidget->isTabEnabled(0) && ui->tabWidget->isTabEnabled(1) && - m_producer->get_int("video_index") != -1; + bool visible = ui->tabWidget->isTabEnabled(0) && ui->tabWidget->isTabEnabled(1) + && m_producer->get_int("video_index") != -1; ui->syncSlider->setVisible(visible); ui->syncLabel->setVisible(visible); ui->syncSpinBox->setVisible(visible); @@ -817,11 +855,12 @@ void AvformatProducerWidget::on_reverseButton_clicked() if (revertToOriginalResource()) return; - TranscodeDialog dialog( - tr("Choose an edit-friendly format below and then click OK to choose a file name. " - "After choosing a file name, a job is created. " - "When it is done, double-click the job to open it.\n"), - ui->scanComboBox->currentIndex(), this); + TranscodeDialog + dialog(tr("Choose an edit-friendly format below and then click OK to choose a file name. " + "After choosing a file name, a job is created. " + "When it is done, double-click the job to open it.\n"), + ui->scanComboBox->currentIndex(), + this); dialog.setWindowTitle(tr("Reverse...")); dialog.setWindowModality(QmlApplication::dialogModality()); int result = dialog.exec(); @@ -842,17 +881,21 @@ void AvformatProducerWidget::on_reverseButton_clicked() } else { // Save these properties for revertToOriginalResource() m_producer->set(kOriginalResourceProperty, resource.toUtf8().constData()); - m_producer->set(kOriginalInProperty, m_producer->get(kFilterInProperty) ? - m_producer->get_time(kFilterInProperty, mlt_time_clock) : m_producer->get_time("in", - mlt_time_clock)); - m_producer->set(kOriginalOutProperty, m_producer->get(kFilterOutProperty) ? - m_producer->get_time(kFilterOutProperty, mlt_time_clock) : m_producer->get_time("out", - mlt_time_clock)); + m_producer->set(kOriginalInProperty, + m_producer->get(kFilterInProperty) + ? m_producer->get_time(kFilterInProperty, mlt_time_clock) + : m_producer->get_time("in", mlt_time_clock)); + m_producer->set(kOriginalOutProperty, + m_producer->get(kFilterOutProperty) + ? m_producer->get_time(kFilterOutProperty, mlt_time_clock) + : m_producer->get_time("out", mlt_time_clock)); } - ffmpegArgs << "-loglevel" << "verbose"; + ffmpegArgs << "-loglevel" + << "verbose"; ffmpegArgs << "-i" << resource; - ffmpegArgs << "-max_muxing_queue_size" << "9999"; + ffmpegArgs << "-max_muxing_queue_size" + << "9999"; // set trim options if (m_producer->get(kFilterInProperty)) { @@ -861,37 +904,54 @@ void AvformatProducerWidget::on_reverseButton_clicked() auto s = QString::fromLatin1(m_producer->frames_to_time(ss, mlt_time_clock)); ffmpegArgs << "-ss" << s.replace(',', '.'); } else { - ffmpegArgs << "-ss" << QString::fromLatin1(m_producer->get_time("in", mlt_time_clock)).replace(',', - '.').replace(',', '.'); + ffmpegArgs << "-ss" + << QString::fromLatin1(m_producer->get_time("in", mlt_time_clock)) + .replace(',', '.') + .replace(',', '.'); } if (m_producer->get(kFilterOutProperty)) { int out = m_producer->get_int(kFilterOutProperty); - int to = qMin(m_producer->get_playtime() - 1, out + qRound(m_producer->get_fps() * kHandleSeconds)); + int to = qMin(m_producer->get_playtime() - 1, + out + qRound(m_producer->get_fps() * kHandleSeconds)); in = to - out - 1; auto s = QString::fromLatin1(m_producer->frames_to_time(to, mlt_time_clock)); ffmpegArgs << "-to" << s.replace(',', '.'); } else { - ffmpegArgs << "-to" << QString::fromLatin1(m_producer->get_time("out", mlt_time_clock)).replace(',', - '.'); + ffmpegArgs << "-to" + << QString::fromLatin1(m_producer->get_time("out", mlt_time_clock)) + .replace(',', '.'); } // transcode all streams except data, subtitles, and attachments - ffmpegArgs << "-map" << "0:V?" << "-map" << "0:a?" << "-map_metadata" << "0" << "-ignore_unknown"; + ffmpegArgs << "-map" + << "0:V?" + << "-map" + << "0:a?" + << "-map_metadata" + << "0" + << "-ignore_unknown"; if (ui->rangeComboBox->currentIndex()) - ffmpegArgs << "-vf" << - "scale=flags=accurate_rnd+full_chroma_inp+full_chroma_int:in_range=full:out_range=full" << - "-color_range" << "jpeg"; + ffmpegArgs << "-vf" + << "scale=flags=accurate_rnd+full_chroma_inp+full_chroma_int:in_range=full:" + "out_range=full" + << "-color_range" + << "jpeg"; else - ffmpegArgs << "-vf" << - "scale=flags=accurate_rnd+full_chroma_inp+full_chroma_int:in_range=mpeg:out_range=mpeg" << - "-color_range" << "mpeg"; + ffmpegArgs << "-vf" + << "scale=flags=accurate_rnd+full_chroma_inp+full_chroma_int:in_range=mpeg:" + "out_range=mpeg" + << "-color_range" + << "mpeg"; if (!ui->scanComboBox->currentIndex()) - ffmpegArgs << "-flags" << "+ildct+ilme" << "-top" << QString::number( - ui->fieldOrderComboBox->currentIndex()); + ffmpegArgs << "-flags" + << "+ildct+ilme" + << "-top" << QString::number(ui->fieldOrderComboBox->currentIndex()); - meltArgs << "-consumer" << "avformat"; + meltArgs << "-consumer" + << "avformat"; if (m_producer->get_int(kAbsoluteAudioIndex) == -1) { - meltArgs << "an=1" << "audio_off=1"; + meltArgs << "an=1" + << "audio_off=1"; } else if (qstrcmp(m_producer->get(kAbsoluteAudioIndex), "all")) { int index = m_producer->get_int(kAbsoluteAudioIndex); QString key = QStringLiteral("meta.media.%1.codec.channels").arg(index); @@ -899,43 +959,78 @@ void AvformatProducerWidget::on_reverseButton_clicked() meltArgs << QStringLiteral("channels=").append(channels); } if (m_producer->get_int("video_index") == -1) - meltArgs << "vn=1" << "video_off=1"; + meltArgs << "vn=1" + << "video_off=1"; - ffmpegArgs << "-f" << "mov" << "-codec:a" << "pcm_f32le"; + ffmpegArgs << "-f" + << "mov" + << "-codec:a" + << "pcm_f32le"; switch (dialog.format()) { case 0: path.append("/%1 - %2.mp4"); nameFilter = tr("MP4 (*.mp4);;All Files (*)"); if (ui->scanComboBox->currentIndex()) { // progressive - ffmpegArgs << "-codec:v" << "dnxhd" << "-profile:v" << "dnxhr_hq" << "-pix_fmt" << "yuv422p"; + ffmpegArgs << "-codec:v" + << "dnxhd" + << "-profile:v" + << "dnxhr_hq" + << "-pix_fmt" + << "yuv422p"; } else { // interlaced - ffmpegArgs << "-codec:v" << "prores_ks" << "-profile:v" << "standard"; - meltArgs << "top_field_first=" + QString::number(ui->fieldOrderComboBox->currentIndex()); + ffmpegArgs << "-codec:v" + << "prores_ks" + << "-profile:v" + << "standard"; + meltArgs << "top_field_first=" + + QString::number(ui->fieldOrderComboBox->currentIndex()); } - meltArgs << "acodec=ac3" << "ab=512k" << "vcodec=libx264"; - meltArgs << "vpreset=medium" << "g=1" << "crf=11"; + meltArgs << "acodec=ac3" + << "ab=512k" + << "vcodec=libx264"; + meltArgs << "vpreset=medium" + << "g=1" + << "crf=11"; break; case 1: meltArgs << "acodec=alac"; if (ui->scanComboBox->currentIndex()) { // progressive - ffmpegArgs << "-codec:v" << "dnxhd" << "-profile:v" << "dnxhr_hq" << "-pix_fmt" << "yuv422p"; - meltArgs << "vcodec=dnxhd" << "vprofile=dnxhr_hq"; + ffmpegArgs << "-codec:v" + << "dnxhd" + << "-profile:v" + << "dnxhr_hq" + << "-pix_fmt" + << "yuv422p"; + meltArgs << "vcodec=dnxhd" + << "vprofile=dnxhr_hq"; } else { // interlaced - ffmpegArgs << "-codec:v" << "prores_ks" << "-profile:v" << "standard"; - meltArgs << "top_field_first=" + QString::number(ui->fieldOrderComboBox->currentIndex()); - meltArgs << "vcodec=prores_ks" << "vprofile=standard"; + ffmpegArgs << "-codec:v" + << "prores_ks" + << "-profile:v" + << "standard"; + meltArgs << "top_field_first=" + + QString::number(ui->fieldOrderComboBox->currentIndex()); + meltArgs << "vcodec=prores_ks" + << "vprofile=standard"; } path.append("/%1 - %2.mov"); nameFilter = tr("MOV (*.mov);;All Files (*)"); break; case 2: - ffmpegArgs << "-codec:v" << "utvideo" << "-pix_fmt" << "yuv422p"; + ffmpegArgs << "-codec:v" + << "utvideo" + << "-pix_fmt" + << "yuv422p"; if (!ui->scanComboBox->currentIndex()) { // interlaced - meltArgs << "field_order=" + QString::fromLatin1(ui->fieldOrderComboBox->currentIndex() ? "tt" : - "bb"); + meltArgs << "field_order=" + + QString::fromLatin1( + ui->fieldOrderComboBox->currentIndex() ? "tt" : "bb"); } - meltArgs << "acodec=pcm_f32le" << "vcodec=utvideo" << "mlt_audio_format=f32le" << "pix_fmt=yuv422p"; + meltArgs << "acodec=pcm_f32le" + << "vcodec=utvideo" + << "mlt_audio_format=f32le" + << "pix_fmt=yuv422p"; path.append("/%1 - %2.mkv"); nameFilter = tr("MKV (*.mkv);;All Files (*)"); break; @@ -944,16 +1039,21 @@ void AvformatProducerWidget::on_reverseButton_clicked() path = path.arg(fi.completeBaseName()).arg(tr("Reversed")); QString filename = QmlApplication::getNextProjectFile(path); if (filename.isEmpty()) { - filename = QFileDialog::getSaveFileName(this, dialog.windowTitle(), path, nameFilter, - nullptr, Util::getFileDialogOptions()); + filename = QFileDialog::getSaveFileName(this, + dialog.windowTitle(), + path, + nameFilter, + nullptr, + Util::getFileDialogOptions()); } if (!filename.isEmpty()) { if (filename == QDir::toNativeSeparators(resource)) { - QMessageBox::warning(this, dialog.windowTitle(), + QMessageBox::warning(this, + dialog.windowTitle(), QObject::tr("Unable to write file %1\n" "Perhaps you do not have permission.\n" "Try again with a different folder.") - .arg(fi.fileName())); + .arg(fi.fileName())); return; } if (JOBS.targetIsInProgress(filename)) { @@ -974,9 +1074,10 @@ void AvformatProducerWidget::on_reverseButton_clicked() // Make a temporary file name for the ffmpeg job. QFileInfo fi(filename); - QString tmpFileName = QStringLiteral("%1/%2 - XXXXXX.%3").arg(fi.path()).arg( - fi.completeBaseName()).arg( - ffmpegSuffix); + QString tmpFileName = QStringLiteral("%1/%2 - XXXXXX.%3") + .arg(fi.path()) + .arg(fi.completeBaseName()) + .arg(ffmpegSuffix); QTemporaryFile tmp(tmpFileName); tmp.setAutoRemove(false); tmp.open(); @@ -992,8 +1093,10 @@ void AvformatProducerWidget::on_reverseButton_clicked() // Run the melt job to convert the intermediate file to the reversed clip. meltArgs.prepend(QStringLiteral("timewarp:-1.0:").append(tmpFileName)); meltArgs << QStringLiteral("target=").append(filename); - MeltJob *meltJob = new MeltJob(filename, meltArgs, - m_producer->get_int("meta.media.frame_rate_num"), m_producer->get_int("meta.media.frame_rate_den")); + MeltJob *meltJob = new MeltJob(filename, + meltArgs, + m_producer->get_int("meta.media.frame_rate_num"), + m_producer->get_int("meta.media.frame_rate_den")); meltJob->setLabel(tr("Reverse %1").arg(Util::baseName(resource))); meltJob->setTarget(filename); @@ -1005,8 +1108,8 @@ void AvformatProducerWidget::on_reverseButton_clicked() int trackIndex = parts[1].toInt(); QUuid uuid = MAIN.timelineClipUuid(trackIndex, clipIndex); if (!uuid.isNull()) { - meltJob->setPostJobAction(new ReplaceOnePostJobAction(resource, filename, tmpFileName, - uuid, in)); + meltJob->setPostJobAction( + new ReplaceOnePostJobAction(resource, filename, tmpFileName, uuid, in)); JOBS.add(meltJob); return; } @@ -1018,7 +1121,6 @@ void AvformatProducerWidget::on_reverseButton_clicked() } } - void AvformatProducerWidget::on_actionExtractSubclip_triggered() { QString resource = Util::GetFilenameFromProducer(producer()); @@ -1029,16 +1131,21 @@ void AvformatProducerWidget::on_actionExtractSubclip_triggered() path = path.arg(fi.completeBaseName()).arg(tr("Sub-clip")).arg(fi.suffix()); QString caption = tr("Extract Sub-clip..."); QString nameFilter = tr("%1 (*.%2);;All Files (*)").arg(fi.suffix()).arg(fi.suffix()); - QString filename = QFileDialog::getSaveFileName(this, caption, path, nameFilter, - nullptr, Util::getFileDialogOptions()); + QString filename = QFileDialog::getSaveFileName(this, + caption, + path, + nameFilter, + nullptr, + Util::getFileDialogOptions()); if (!filename.isEmpty()) { if (filename == QDir::toNativeSeparators(resource)) { - QMessageBox::warning(this, caption, + QMessageBox::warning(this, + caption, QObject::tr("Unable to write file %1\n" "Perhaps you do not have permission.\n" "Try again with a different folder.") - .arg(fi.fileName())); + .arg(fi.fileName())); return; } if (JOBS.targetIsInProgress(filename)) { @@ -1054,27 +1161,44 @@ void AvformatProducerWidget::on_actionExtractSubclip_triggered() QStringList ffmpegArgs; // Build the ffmpeg command line. - ffmpegArgs << "-loglevel" << "verbose"; + ffmpegArgs << "-loglevel" + << "verbose"; ffmpegArgs << "-i" << resource; // set trim options if (m_producer->get_int(kFilterInProperty) || m_producer->get_int("in")) { if (m_producer->get(kFilterInProperty)) - ffmpegArgs << "-ss" << QString::fromLatin1(m_producer->get_time(kFilterInProperty, - mlt_time_clock)).replace(',', '.'); + ffmpegArgs << "-ss" + << QString::fromLatin1( + m_producer->get_time(kFilterInProperty, mlt_time_clock)) + .replace(',', '.'); else - ffmpegArgs << "-ss" << QString::fromLatin1(m_producer->get_time("in", mlt_time_clock)).replace(',', - '.').replace(',', '.'); + ffmpegArgs << "-ss" + << QString::fromLatin1(m_producer->get_time("in", mlt_time_clock)) + .replace(',', '.') + .replace(',', '.'); } if (m_producer->get(kFilterOutProperty)) - ffmpegArgs << "-to" << QString::fromLatin1(m_producer->get_time(kFilterOutProperty, - mlt_time_clock)).replace(',', '.'); + ffmpegArgs << "-to" + << QString::fromLatin1( + m_producer->get_time(kFilterOutProperty, mlt_time_clock)) + .replace(',', '.'); else - ffmpegArgs << "-to" << QString::fromLatin1(m_producer->get_time("out", mlt_time_clock)).replace(',', - '.'); - ffmpegArgs << "-avoid_negative_ts" << "make_zero" - << "-map" << "0:V?" << "-map" << "0:a?" << "-map" << "0:s?" - << "-map_metadata" << "0" - << "-codec" << "copy" << "-y" << filename; + ffmpegArgs << "-to" + << QString::fromLatin1(m_producer->get_time("out", mlt_time_clock)) + .replace(',', '.'); + ffmpegArgs << "-avoid_negative_ts" + << "make_zero" + << "-map" + << "0:V?" + << "-map" + << "0:a?" + << "-map" + << "0:s?" + << "-map_metadata" + << "0" + << "-codec" + << "copy" + << "-y" << filename; // Run the ffmpeg job. FfmpegJob *ffmpegJob = new FfmpegJob(filename, ffmpegArgs, false); @@ -1123,7 +1247,9 @@ void AvformatProducerWidget::on_actionExtractSubtitles_triggered() // Prompt the user for the directory to save the file(s) QString resource = Util::GetFilenameFromProducer(producer()); QFileInfo fi(resource); - QString pathTemplate = QFileDialog::getExistingDirectory(this, caption, Settings.savePath(), + QString pathTemplate = QFileDialog::getExistingDirectory(this, + caption, + Settings.savePath(), Util::getFileDialogOptions()); if (pathTemplate.isEmpty()) { LOG_WARNING() << "No path specified"; @@ -1156,7 +1282,8 @@ void AvformatProducerWidget::on_actionExtractSubtitles_triggered() // Make an FFMpeg job QStringList ffmpegArgs; QString streamSelect = QStringLiteral("0:s:%1").arg(subtitleCount - 1); - ffmpegArgs << "-loglevel" << "verbose"; + ffmpegArgs << "-loglevel" + << "verbose"; ffmpegArgs << "-i" << resource; ffmpegArgs << "-map" << streamSelect; ffmpegArgs << "-y" << path; @@ -1237,7 +1364,7 @@ void AvformatProducerWidget::on_actionMakeProxy_triggered() ProxyManager::ScanMode scan = ProxyManager::Progressive; if (!ui->scanComboBox->currentIndex()) scan = ui->fieldOrderComboBox->currentIndex() ? ProxyManager::InterlacedTopFieldFirst - : ProxyManager::InterlacedBottomFieldFirst; + : ProxyManager::InterlacedBottomFieldFirst; // If rotation is 90 or 270, swap aspect ratio since auto-rotate is turned off if (ui->rotationComboBox->currentIndex() % 2 == 1) @@ -1272,9 +1399,10 @@ void AvformatProducerWidget::on_actionDeleteProxy_triggered() void AvformatProducerWidget::on_actionCopyHashCode_triggered() { qApp->clipboard()->setText(Util::getHash(*producer())); - QMessageBox::information(this, qApp->applicationName(), - tr("The hash code below is already copied to your clipboard:\n\n") + - Util::getHash(*producer()), + QMessageBox::information(this, + qApp->applicationName(), + tr("The hash code below is already copied to your clipboard:\n\n") + + Util::getHash(*producer()), QMessageBox::Ok); } @@ -1320,11 +1448,15 @@ void AvformatProducerWidget::on_actionSetEquirectangular_triggered() QString caption = tr("Set Equirectangular Projection"); QFileInfo info(Util::GetFilenameFromProducer(producer())); QString directory = QStringLiteral("%1/%2 - ERP.%3") - .arg(info.path()) - .arg(info.completeBaseName()) - .arg(info.suffix()); - QString filePath = QFileDialog::getSaveFileName(&MAIN, caption, directory, QString(), - nullptr, Util::getFileDialogOptions()); + .arg(info.path()) + .arg(info.completeBaseName()) + .arg(info.suffix()); + QString filePath = QFileDialog::getSaveFileName(&MAIN, + caption, + directory, + QString(), + nullptr, + Util::getFileDialogOptions()); if (!filePath.isEmpty()) { if (SpatialMedia::injectSpherical(info.filePath().toStdString(), filePath.toStdString())) { MAIN.showStatusMessage(tr("Successfully wrote %1").arg(QFileInfo(filePath).fileName())); @@ -1338,10 +1470,14 @@ void AvformatProducerWidget::on_actionFFmpegVideoQuality_triggered() { QString caption = tr("Choose the Other Video"); QFileInfo info(Util::GetFilenameFromProducer(producer())); - QString directory = QStringLiteral("%1/%2 - ERP.%3").arg(info.path(), info.completeBaseName(), - info.suffix()); - QString filePath = QFileDialog::getOpenFileName(&MAIN, caption, directory, QString(), - nullptr, Util::getFileDialogOptions()); + QString directory + = QStringLiteral("%1/%2 - ERP.%3").arg(info.path(), info.completeBaseName(), info.suffix()); + QString filePath = QFileDialog::getOpenFileName(&MAIN, + caption, + directory, + QString(), + nullptr, + Util::getFileDialogOptions()); if (!filePath.isEmpty()) { QString resource = Util::GetFilenameFromProducer(producer()); QDir dir = QmlApplication::dataDir(); @@ -1359,21 +1495,30 @@ void AvformatProducerWidget::on_actionFFmpegVideoQuality_triggered() #ifdef Q_OS_WIN auto logPath = "con\\:"; - auto modelPath = (width < 3840 - && height < 2160) ? "share/vmaf/vmaf_v0.6.1.json" : "share/vmaf/vmaf_4k_v0.6.1.json"; + auto modelPath = (width < 3840 && height < 2160) ? "share/vmaf/vmaf_v0.6.1.json" + : "share/vmaf/vmaf_4k_v0.6.1.json"; #else auto logPath = "/dev/stderr"; - auto modelPath = (width < 3840 - && height < 2160) ? dir.filePath("vmaf_v0.6.1.json") : dir.filePath("vmaf_4k_v0.6.1.json"); + auto modelPath = (width < 3840 && height < 2160) ? dir.filePath("vmaf_v0.6.1.json") + : dir.filePath("vmaf_4k_v0.6.1.json"); #endif - args << QStringLiteral("[0:v]scale=out_range=%6,fps=%4/%5,setpts=PTS-STARTPTS[reference];[1:v]scale=%1:%2:out_range=%6:flags=bicubic,fps=%4/%5,setpts=PTS-STARTPTS[distorted];[distorted][reference]libvmaf=log_fmt=csv:log_path='%8':feature='name=psnr|name=float_ssim':shortest=true:n_threads=%7:model='path=%3'") - .arg(width).arg(height) - .arg(modelPath) - .arg(frameRateNum).arg(frameRateDen) - .arg(colorRange) - .arg(qRound(QThread::idealThreadCount() / 2.)) - .arg(logPath); - args << "-f" << "null" << "pipe:"; + args << QStringLiteral("[0:v]scale=out_range=%6,fps=%4/" + "%5,setpts=PTS-STARTPTS[reference];[1:v]scale=%1:%2:out_range=%6:" + "flags=bicubic,fps=%4/" + "%5,setpts=PTS-STARTPTS[distorted];[distorted][reference]libvmaf=" + "log_fmt=csv:log_path='%8':feature='name=psnr|name=float_ssim':" + "shortest=true:n_threads=%7:model='path=%3'") + .arg(width) + .arg(height) + .arg(modelPath) + .arg(frameRateNum) + .arg(frameRateDen) + .arg(colorRange) + .arg(qRound(QThread::idealThreadCount() / 2.)) + .arg(logPath); + args << "-f" + << "null" + << "pipe:"; FfmpegJob *job = new FfmpegJob(resource, args); job->setWorkingDirectory(qApp->applicationDirPath()); job->setLabel(tr("Measure %1").arg(Util::baseName(filePath))); @@ -1401,7 +1546,8 @@ void AvformatProducerWidget::on_actionExportGPX_triggered() void AvformatProducerWidget::on_speedComboBox_textActivated(const QString &arg1) { - if (arg1.isEmpty()) return; + if (arg1.isEmpty()) + return; ui->speedSpinBox->setValue(arg1.toDouble()); on_speedSpinBox_editingFinished(); } @@ -1410,8 +1556,7 @@ ProbeTask::ProbeTask(Mlt::Producer *producer) : QObject(0) , QRunnable() , m_producer(*producer) -{ -} +{} void ProbeTask::run() { @@ -1422,15 +1567,18 @@ void ProbeTask::run() void AvformatProducerWidget::on_actionBitrateViewer_triggered() { QStringList args; - args << "-v" << "quiet"; - args << "-print_format" << "json=compact=1"; + args << "-v" + << "quiet"; + args << "-print_format" + << "json=compact=1"; if (m_producer->get_int("video_index") >= 0) - args << "-select_streams" << QString::fromLatin1("V:%1").arg(m_producer->get_int( - kVideoIndexProperty)); + args << "-select_streams" + << QString::fromLatin1("V:%1").arg(m_producer->get_int(kVideoIndexProperty)); else - args << "-select_streams" << QString::fromLatin1("a:%1").arg(m_producer->get_int( - kAudioIndexProperty)); - args << "-show_entries" << "packet=size,duration_time,pts_time,flags"; + args << "-select_streams" + << QString::fromLatin1("a:%1").arg(m_producer->get_int(kAudioIndexProperty)); + args << "-show_entries" + << "packet=size,duration_time,pts_time,flags"; args << Util::GetFilenameFromProducer(producer()); auto job = new BitrateViewerJob(args.last(), args, fps()); job->setLabel(tr("Bitrate %1").arg(Util::baseName(args.last()))); diff --git a/src/widgets/avformatproducerwidget.h b/src/widgets/avformatproducerwidget.h index 8dbe0f6a95..d222947056 100644 --- a/src/widgets/avformatproducerwidget.h +++ b/src/widgets/avformatproducerwidget.h @@ -18,11 +18,13 @@ #ifndef AVFORMATPRODUCERWIDGET_H #define AVFORMATPRODUCERWIDGET_H -#include -#include #include "abstractproducerwidget.h" + #include "dialogs/transcodedialog.h" +#include +#include + namespace Ui { class AvformatProducerWidget; } @@ -65,9 +67,9 @@ private slots: void on_fieldOrderComboBox_activated(int index); - void on_aspectNumSpinBox_valueChanged(int ); + void on_aspectNumSpinBox_valueChanged(int); - void on_aspectDenSpinBox_valueChanged(int ); + void on_aspectDenSpinBox_valueChanged(int); void on_durationSpinBox_editingFinished(); @@ -155,6 +157,7 @@ class ProbeTask : public QObject, public QRunnable signals: void probeFinished(); + private: Mlt::Producer m_producer; }; diff --git a/src/widgets/avfoundationproducerwidget.cpp b/src/widgets/avfoundationproducerwidget.cpp index a8c2ddcf56..6d407d663d 100644 --- a/src/widgets/avfoundationproducerwidget.cpp +++ b/src/widgets/avfoundationproducerwidget.cpp @@ -17,22 +17,24 @@ #include "avfoundationproducerwidget.h" #include "ui_avfoundationproducerwidget.h" + +#include "Logger.h" #include "mltcontroller.h" -#include "util.h" #include "settings.h" -#include -#include +#include "shotcut_mlt_properties.h" +#include "util.h" + +#include #include +#include +#include #include -#include -#include "shotcut_mlt_properties.h" -#include #define ENABLE_SCREEN_CAPTURE (0) -AvfoundationProducerWidget::AvfoundationProducerWidget(QWidget *parent) : - QWidget(parent), - ui(new Ui::AvfoundationProducerWidget) +AvfoundationProducerWidget::AvfoundationProducerWidget(QWidget *parent) + : QWidget(parent) + , ui(new Ui::AvfoundationProducerWidget) { ui->setupUi(this); Util::setColorsToHighlight(ui->label); @@ -73,27 +75,31 @@ Mlt::Producer *AvfoundationProducerWidget::newProducer(Mlt::Profile &profile) { QString resource; qreal frameRate = 30.0; - QSize size {1280, 720}; + QSize size{1280, 720}; Util::cameraFrameRateSize(ui->videoCombo->currentData().toByteArray(), frameRate, size); if (ui->videoCombo->currentIndex()) { - resource = QStringLiteral("avfoundation:%1:%2?pixel_format=yuyv422&framerate=%3&video_size=%4x%5") - .arg(ui->videoCombo->currentText().replace(tr("None"), "none")) - .arg(ui->audioCombo->currentText().replace(tr("None"), "none")) - .arg(frameRate).arg(size.width()).arg(size.height()); + resource = QStringLiteral( + "avfoundation:%1:%2?pixel_format=yuyv422&framerate=%3&video_size=%4x%5") + .arg(ui->videoCombo->currentText().replace(tr("None"), "none")) + .arg(ui->audioCombo->currentText().replace(tr("None"), "none")) + .arg(frameRate) + .arg(size.width()) + .arg(size.height()); } else { - resource = QStringLiteral("avfoundation:none:%1").arg(ui->audioCombo->currentText().replace( - tr("None"), - "none")); + resource = QStringLiteral("avfoundation:none:%1") + .arg(ui->audioCombo->currentText().replace(tr("None"), "none")); } LOG_DEBUG() << resource; Mlt::Producer *p = new Mlt::Producer(profile, resource.toUtf8().constData()); if (!p || !p->is_valid()) { delete p; p = new Mlt::Producer(profile, "color:"); - p->set("resource", QStringLiteral("avfoundation:%1:%2") - .arg(ui->videoCombo->currentText().replace(tr("None"), "none")) - .arg(ui->audioCombo->currentText()) - .toUtf8().constData()); + p->set("resource", + QStringLiteral("avfoundation:%1:%2") + .arg(ui->videoCombo->currentText().replace(tr("None"), "none")) + .arg(ui->audioCombo->currentText()) + .toUtf8() + .constData()); p->set("error", 1); } p->set("force_seekable", 0); diff --git a/src/widgets/avfoundationproducerwidget.h b/src/widgets/avfoundationproducerwidget.h index ed459b1743..b5624e0013 100644 --- a/src/widgets/avfoundationproducerwidget.h +++ b/src/widgets/avfoundationproducerwidget.h @@ -19,9 +19,10 @@ #ifndef AVFOUNDATIONPRODUCERWIDGET_H #define AVFOUNDATIONPRODUCERWIDGET_H -#include #include "abstractproducerwidget.h" +#include + namespace Ui { class AvfoundationProducerWidget; } diff --git a/src/widgets/blipproducerwidget.cpp b/src/widgets/blipproducerwidget.cpp index 7177a42a63..2354810250 100644 --- a/src/widgets/blipproducerwidget.cpp +++ b/src/widgets/blipproducerwidget.cpp @@ -15,15 +15,17 @@ * along with this program. If not, see . */ -#include "shotcut_mlt_properties.h" #include "blipproducerwidget.h" + +#include "shotcut_mlt_properties.h" #include "ui_blipproducerwidget.h" #include "util.h" + #include -BlipProducerWidget::BlipProducerWidget(QWidget *parent) : - QWidget(parent), - ui(new Ui::BlipProducerWidget) +BlipProducerWidget::BlipProducerWidget(QWidget *parent) + : QWidget(parent) + , ui(new Ui::BlipProducerWidget) { ui->setupUi(this); Util::setColorsToHighlight(ui->nameLabel); diff --git a/src/widgets/blipproducerwidget.h b/src/widgets/blipproducerwidget.h index 54829ed4c9..cc04033590 100644 --- a/src/widgets/blipproducerwidget.h +++ b/src/widgets/blipproducerwidget.h @@ -18,9 +18,10 @@ #ifndef BLIPPRODUCERWIDGET_H #define BLIPPRODUCERWIDGET_H -#include #include "abstractproducerwidget.h" +#include + namespace Ui { class BlipProducerWidget; } diff --git a/src/widgets/colorbarswidget.cpp b/src/widgets/colorbarswidget.cpp index cb3c3f5f19..efbc454f16 100644 --- a/src/widgets/colorbarswidget.cpp +++ b/src/widgets/colorbarswidget.cpp @@ -15,28 +15,23 @@ * along with this program. If not, see . */ -#include "shotcut_mlt_properties.h" #include "colorbarswidget.h" #include "ui_colorbarswidget.h" -#include "util.h" + #include "mltcontroller.h" +#include "shotcut_mlt_properties.h" +#include "util.h" + #include static const char *kParamType = "0"; static const char *kParamAspect = "1"; -enum { - ASPECT_SQUARE = 0, - ASPECT_PAL, - ASPECT_PAL_WIDE, - ASPECT_NTSC, - ASPECT_NTSC_WIDE, - ASPECT_HDV -}; +enum { ASPECT_SQUARE = 0, ASPECT_PAL, ASPECT_PAL_WIDE, ASPECT_NTSC, ASPECT_NTSC_WIDE, ASPECT_HDV }; -ColorBarsWidget::ColorBarsWidget(QWidget *parent) : - QWidget(parent), - ui(new Ui::ColorBarsWidget) +ColorBarsWidget::ColorBarsWidget(QWidget *parent) + : QWidget(parent) + , ui(new Ui::ColorBarsWidget) { ui->setupUi(this); ui->comboBox->setCurrentIndex(4); diff --git a/src/widgets/colorbarswidget.h b/src/widgets/colorbarswidget.h index 369fc668a2..f43be55ad7 100644 --- a/src/widgets/colorbarswidget.h +++ b/src/widgets/colorbarswidget.h @@ -18,9 +18,10 @@ #ifndef COLORBARSWIDGET_H #define COLORBARSWIDGET_H -#include #include "abstractproducerwidget.h" +#include + namespace Ui { class ColorBarsWidget; } diff --git a/src/widgets/colorproducerwidget.cpp b/src/widgets/colorproducerwidget.cpp index d38820b3d7..b7d1c9d6c9 100644 --- a/src/widgets/colorproducerwidget.cpp +++ b/src/widgets/colorproducerwidget.cpp @@ -15,26 +15,28 @@ * along with this program. If not, see . */ -#include -#include #include "colorproducerwidget.h" #include "ui_colorproducerwidget.h" -#include "shotcut_mlt_properties.h" -#include "util.h" + +#include "Logger.h" #include "mltcontroller.h" #include "qmltypes/qmlapplication.h" -#include "Logger.h" +#include "shotcut_mlt_properties.h" +#include "util.h" + +#include +#include static const QString kTransparent = QObject::tr("transparent", "Open Other > Color"); static QString colorToString(const QColor &color) { return (color == QColor(0, 0, 0, 0)) ? kTransparent - : QString::asprintf("#%02X%02X%02X%02X", - qAlpha(color.rgba()), - qRed(color.rgba()), - qGreen(color.rgba()), - qBlue(color.rgba())); + : QString::asprintf("#%02X%02X%02X%02X", + qAlpha(color.rgba()), + qRed(color.rgba()), + qGreen(color.rgba()), + qBlue(color.rgba())); } static QString colorStringToResource(const QString &s) @@ -42,9 +44,9 @@ static QString colorStringToResource(const QString &s) return (s == kTransparent) ? "#00000000" : s; } -ColorProducerWidget::ColorProducerWidget(QWidget *parent) : - QWidget(parent), - ui(new Ui::ColorProducerWidget) +ColorProducerWidget::ColorProducerWidget(QWidget *parent) + : QWidget(parent) + , ui(new Ui::ColorProducerWidget) { ui->setupUi(this); m_title = ui->lineEdit->text(); @@ -81,17 +83,19 @@ void ColorProducerWidget::on_colorButton_clicked() auto rgb = newColor; auto transparent = QColor(0, 0, 0, 0); rgb.setAlpha(color.alpha()); - if (newColor.alpha() == 0 && (rgb != color || - (newColor == transparent && color == transparent))) { + if (newColor.alpha() == 0 + && (rgb != color || (newColor == transparent && color == transparent))) { newColor.setAlpha(255); } ui->colorLabel->setText(colorToString(newColor)); ui->colorLabel->setStyleSheet(QStringLiteral("color: %1; background-color: %2") - .arg(Util::textColor(newColor), newColor.name())); + .arg(Util::textColor(newColor), newColor.name())); if (m_producer) { - m_producer->set("resource", colorStringToResource(ui->colorLabel->text()).toLatin1().constData()); + m_producer->set("resource", + colorStringToResource(ui->colorLabel->text()).toLatin1().constData()); if (ui->lineEdit->text().isEmpty() || ui->lineEdit->text() == m_title) { - m_producer->set(kShotcutCaptionProperty, ui->colorLabel->text().toLatin1().constData()); + m_producer->set(kShotcutCaptionProperty, + ui->colorLabel->text().toLatin1().constData()); } else { m_producer->set(kShotcutCaptionProperty, ui->lineEdit->text().toUtf8().constData()); } @@ -128,11 +132,12 @@ void ColorProducerWidget::loadPreset(Mlt::Properties &p) { QColor color(QFileInfo(p.get("resource")).baseName()); ui->colorLabel->setText(colorToString(color)); - ui->colorLabel->setStyleSheet(QStringLiteral("color: %1; background-color: %2") - .arg(Util::textColor(color), color.name())); + ui->colorLabel->setStyleSheet( + QStringLiteral("color: %1; background-color: %2").arg(Util::textColor(color), color.name())); QString caption, detail; if (m_producer) { - m_producer->set("resource", colorStringToResource(ui->colorLabel->text()).toLatin1().constData()); + m_producer->set("resource", + colorStringToResource(ui->colorLabel->text()).toLatin1().constData()); caption = m_producer->get(kShotcutCaptionProperty); detail = m_producer->get(kShotcutDetailProperty); diff --git a/src/widgets/colorproducerwidget.h b/src/widgets/colorproducerwidget.h index 895588261a..84557a4fbe 100644 --- a/src/widgets/colorproducerwidget.h +++ b/src/widgets/colorproducerwidget.h @@ -18,9 +18,10 @@ #ifndef COLORPRODUCERWIDGET_H #define COLORPRODUCERWIDGET_H -#include #include "abstractproducerwidget.h" +#include + namespace Ui { class ColorProducerWidget; } diff --git a/src/widgets/colorwheel.cpp b/src/widgets/colorwheel.cpp index 7eb1ef7833..4828febd1d 100644 --- a/src/widgets/colorwheel.cpp +++ b/src/widgets/colorwheel.cpp @@ -19,6 +19,7 @@ */ #include "colorwheel.h" + #include ColorWheel::ColorWheel(QWidget *parent) @@ -54,7 +55,8 @@ int ColorWheel::wheelSize() const QColor ColorWheel::colorForPoint(const QPoint &point) { - if (! m_image.valid(point)) return QColor(); + if (!m_image.valid(point)) + return QColor(); if (m_isInWheel) { qreal w = wheelSize(); qreal xf = qreal(point.x()) / w; @@ -67,20 +69,20 @@ QColor ColorWheel::colorForPoint(const QPoint &point) if (theta < 0.0) theta += 2.0 * M_PI; qreal hue = (theta * 180.0 / M_PI) / 360.0; - return QColor::fromHsvF( hue, rad, m_color.valueF() ); + return QColor::fromHsvF(hue, rad, m_color.valueF()); } if (m_isInSquare) { qreal value = 1.0 - qreal(point.y() - m_margin) / (wheelSize() - m_margin * 2); - return QColor::fromHsvF( m_color.hueF(), m_color.saturationF(), value); + return QColor::fromHsvF(m_color.hueF(), m_color.saturationF(), value); } return QColor(); } -QSize ColorWheel::sizeHint () const +QSize ColorWheel::sizeHint() const { return QSize(height(), height()); } -QSize ColorWheel::minimumSizeHint () const +QSize ColorWheel::minimumSizeHint() const { return QSize(100, 100); } @@ -105,7 +107,8 @@ void ColorWheel::mousePressEvent(QMouseEvent *event) void ColorWheel::mouseMoveEvent(QMouseEvent *event) { m_lastPoint = event->pos(); - if (!m_isMouseDown) return; + if (!m_isMouseDown) + return; if (m_wheelRegion.contains(m_lastPoint) && m_isInWheel) { QColor color = colorForPoint(m_lastPoint); changeColor(color); @@ -137,13 +140,13 @@ void ColorWheel::paintEvent(QPaintEvent *event) { Q_UNUSED(event) QPainter painter(this); -// QStyleOption opt; -// opt.init(this); + // QStyleOption opt; + // opt.init(this); painter.setRenderHint(QPainter::Antialiasing); painter.drawImage(0, 0, m_image); drawWheelDot(painter); drawSliderBar(painter); -// style()->drawPrimitive(QStyle::PE_Widget, &opt, &painter, this); + // style()->drawPrimitive(QStyle::PE_Widget, &opt, &painter, this); } void ColorWheel::drawWheel() @@ -154,13 +157,13 @@ void ColorWheel::drawWheel() m_image.fill(0); // transparent QConicalGradient conicalGradient; - conicalGradient.setColorAt( 0.0, Qt::red); - conicalGradient.setColorAt( 60.0 / 360.0, Qt::yellow); + conicalGradient.setColorAt(0.0, Qt::red); + conicalGradient.setColorAt(60.0 / 360.0, Qt::yellow); conicalGradient.setColorAt(135.0 / 360.0, Qt::green); conicalGradient.setColorAt(180.0 / 360.0, Qt::cyan); conicalGradient.setColorAt(240.0 / 360.0, Qt::blue); conicalGradient.setColorAt(315.0 / 360.0, Qt::magenta); - conicalGradient.setColorAt( 1.0, Qt::red); + conicalGradient.setColorAt(1.0, Qt::red); QRadialGradient radialGradient(0.0, 0.0, r / 2); radialGradient.setColorAt(0.0, Qt::white); @@ -211,7 +214,7 @@ void ColorWheel::drawWheelDot(QPainter &painter) painter.translate(r, r); painter.rotate(360.0 - m_color.hue()); painter.rotate(-105); -// r -= margin; + // r -= margin; painter.drawEllipse(QPointF(m_color.saturationF() * r, 0.0), 4, 4); painter.resetTransform(); } diff --git a/src/widgets/colorwheel.h b/src/widgets/colorwheel.h index 636addfc67..608ff7b5e3 100644 --- a/src/widgets/colorwheel.h +++ b/src/widgets/colorwheel.h @@ -19,9 +19,9 @@ #ifndef COLORWHEEL_H #define COLORWHEEL_H -#include #include #include +#include class ColorWheel : public QWidget { @@ -29,8 +29,8 @@ class ColorWheel : public QWidget public: explicit ColorWheel(QWidget *parent = 0); - virtual QSize sizeHint () const; - virtual QSize minimumSizeHint () const; + virtual QSize sizeHint() const; + virtual QSize minimumSizeHint() const; QColor color(); void setColor(const QColor &color); diff --git a/src/widgets/countproducerwidget.cpp b/src/widgets/countproducerwidget.cpp index df9e7d3be8..45002feed9 100644 --- a/src/widgets/countproducerwidget.cpp +++ b/src/widgets/countproducerwidget.cpp @@ -15,11 +15,13 @@ * along with this program. If not, see . */ -#include "shotcut_mlt_properties.h" #include "countproducerwidget.h" #include "ui_countproducerwidget.h" -#include "util.h" + #include "mltcontroller.h" +#include "shotcut_mlt_properties.h" +#include "util.h" + #include void setLength(Mlt::Properties *p, int length) @@ -29,9 +31,9 @@ void setLength(Mlt::Properties *p, int length) p->set("in", 0); } -CountProducerWidget::CountProducerWidget(QWidget *parent) : - QWidget(parent), - ui(new Ui::CountProducerWidget) +CountProducerWidget::CountProducerWidget(QWidget *parent) + : QWidget(parent) + , ui(new Ui::CountProducerWidget) { ui->setupUi(this); Util::setColorsToHighlight(ui->nameLabel); @@ -117,7 +119,8 @@ Mlt::Properties CountProducerWidget::getPreset() const void CountProducerWidget::loadPreset(Mlt::Properties &p) { - if (!p.get("direction") || !p.get("style")) return; + if (!p.get("direction") || !p.get("style")) + return; int index = -1; index = ui->directionCombo->findData(QVariant(QString::fromLatin1(p.get("direction")))); @@ -219,6 +222,7 @@ void CountProducerWidget::on_preset_saveClicked() QString CountProducerWidget::detail() const { - return tr("Count: %1 %2").arg(ui->directionCombo->currentText()).arg( - ui->styleCombo->currentText()); + return tr("Count: %1 %2") + .arg(ui->directionCombo->currentText()) + .arg(ui->styleCombo->currentText()); } diff --git a/src/widgets/countproducerwidget.h b/src/widgets/countproducerwidget.h index 3e89d65653..789ae64e41 100644 --- a/src/widgets/countproducerwidget.h +++ b/src/widgets/countproducerwidget.h @@ -18,9 +18,10 @@ #ifndef COUNTPRODUCERWIDGET_H #define COUNTPRODUCERWIDGET_H -#include #include "abstractproducerwidget.h" +#include + namespace Ui { class CountProducerWidget; } diff --git a/src/widgets/d3dvideowidget.cpp b/src/widgets/d3dvideowidget.cpp index d33ff4e039..90572bebc2 100644 --- a/src/widgets/d3dvideowidget.cpp +++ b/src/widgets/d3dvideowidget.cpp @@ -16,10 +16,10 @@ */ #include "d3dvideowidget.h" -#include -#include +#include "Logger.h" +#include D3DVideoWidget::D3DVideoWidget(QObject *parent) : Mlt::VideoWidget{parent} @@ -58,11 +58,11 @@ void D3DVideoWidget::initialize() // We are not prepared for anything other than running with the RHI and its D3D11 backend. Q_ASSERT(rif->graphicsApi() == QSGRendererInterface::Direct3D11); - m_device = reinterpret_cast(rif->getResource(quickWindow(), - QSGRendererInterface::DeviceResource)); + m_device = reinterpret_cast( + rif->getResource(quickWindow(), QSGRendererInterface::DeviceResource)); Q_ASSERT(m_device); - m_context = reinterpret_cast(rif->getResource(quickWindow(), - QSGRendererInterface::DeviceContextResource)); + m_context = reinterpret_cast( + rif->getResource(quickWindow(), QSGRendererInterface::DeviceContextResource)); Q_ASSERT(m_context); if (m_vert.isEmpty()) @@ -99,10 +99,19 @@ void D3DVideoWidget::initialize() qFatal("Failed to create buffer: 0x%x", uint(hr)); const D3D11_INPUT_ELEMENT_DESC inputDesc[] = { - { "VERTEX", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }, - { "TEXCOORD", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, sizeof(DirectX::XMFLOAT2), D3D11_INPUT_PER_VERTEX_DATA, 0 }, + {"VERTEX", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0}, + {"TEXCOORD", + 0, + DXGI_FORMAT_R32G32B32_FLOAT, + 0, + sizeof(DirectX::XMFLOAT2), + D3D11_INPUT_PER_VERTEX_DATA, + 0}, }; - hr = m_device->CreateInputLayout(inputDesc, ARRAYSIZE(inputDesc), vs.constData(), vs.size(), + hr = m_device->CreateInputLayout(inputDesc, + ARRAYSIZE(inputDesc), + vs.constData(), + vs.size(), &m_inputLayout); if (FAILED(hr)) qFatal("Failed to create input layout: 0x%x", uint(hr)); @@ -132,11 +141,24 @@ void D3DVideoWidget::beforeRendering() // Provide vertices of triangle strip float width = rect().width() * devicePixelRatioF() / 2.0f; float height = rect().height() * devicePixelRatioF() / 2.0f; - float vertexData[] = { // x,y plus u,v texture coordinates - width, -height, 1.f, 1.f, // bottom left - -width, -height, 0.f, 1.f, // bottom right - width, height, 1.f, 0.f, // top left - -width, height, 0.f, 0.f // top right + float vertexData[] = { + // x,y plus u,v texture coordinates + width, + -height, + 1.f, + 1.f, // bottom left + -width, + -height, + 0.f, + 1.f, // bottom right + width, + height, + 1.f, + 0.f, // top left + -width, + height, + 0.f, + 0.f // top right }; // Setup an orthographic projection @@ -177,7 +199,8 @@ void D3DVideoWidget::beforeRendering() } m_texture[0] = initTexture(image, iwidth, iheight); m_texture[1] = initTexture(image + iwidth * iheight, iwidth / 2, iheight / 2); - m_texture[2] = initTexture(image + iwidth * iheight + iwidth / 2 * iheight / 2, iwidth / 2, + m_texture[2] = initTexture(image + iwidth * iheight + iwidth / 2 * iheight / 2, + iwidth / 2, iheight / 2); m_mutex.unlock(); @@ -289,7 +312,8 @@ void D3DVideoWidget::prepareShader(Stage stage) } } -QByteArray D3DVideoWidget::compileShader(Stage stage, const QByteArray &source, +QByteArray D3DVideoWidget::compileShader(Stage stage, + const QByteArray &source, const QByteArray &entryPoint) { const char *target; @@ -307,9 +331,17 @@ QByteArray D3DVideoWidget::compileShader(Stage stage, const QByteArray &source, ID3DBlob *bytecode = nullptr; ID3DBlob *errors = nullptr; - HRESULT hr = D3DCompile(source.constData(), source.size(), - nullptr, nullptr, nullptr, - entryPoint.constData(), target, 0, 0, &bytecode, &errors); + HRESULT hr = D3DCompile(source.constData(), + source.size(), + nullptr, + nullptr, + nullptr, + entryPoint.constData(), + target, + 0, + 0, + &bytecode, + &errors); if (FAILED(hr) || !bytecode) { qWarning("HLSL shader compilation failed: 0x%x", uint(hr)); if (errors) { diff --git a/src/widgets/d3dvideowidget.h b/src/widgets/d3dvideowidget.h index ae4ff8e38c..f9528e55b6 100644 --- a/src/widgets/d3dvideowidget.h +++ b/src/widgets/d3dvideowidget.h @@ -36,14 +36,9 @@ public slots: virtual void renderVideo(); private: - enum Stage { - VertexStage, - FragmentStage - }; + enum Stage { VertexStage, FragmentStage }; void prepareShader(Stage stage); - QByteArray compileShader(Stage stage, - const QByteArray &source, - const QByteArray &entryPoint); + QByteArray compileShader(Stage stage, const QByteArray &source, const QByteArray &entryPoint); ID3D11ShaderResourceView *initTexture(const void *p, int width, int height); ID3D11Device *m_device = nullptr; @@ -63,7 +58,8 @@ public slots: ID3D11DepthStencilState *m_dsState = nullptr; ID3D11ShaderResourceView *m_texture[3] = {nullptr, nullptr, nullptr}; - struct ConstantBuffer { + struct ConstantBuffer + { int32_t colorspace; }; diff --git a/src/widgets/decklinkproducerwidget.cpp b/src/widgets/decklinkproducerwidget.cpp index 5cfbc2d094..118b5eb904 100644 --- a/src/widgets/decklinkproducerwidget.cpp +++ b/src/widgets/decklinkproducerwidget.cpp @@ -17,13 +17,14 @@ #include "decklinkproducerwidget.h" #include "ui_decklinkproducerwidget.h" + #include "mltcontroller.h" -#include "util.h" #include "shotcut_mlt_properties.h" +#include "util.h" -DecklinkProducerWidget::DecklinkProducerWidget(QWidget *parent) : - QWidget(parent), - ui(new Ui::DecklinkProducerWidget) +DecklinkProducerWidget::DecklinkProducerWidget(QWidget *parent) + : QWidget(parent) + , ui(new Ui::DecklinkProducerWidget) { ui->setupUi(this); Util::setColorsToHighlight(ui->label); @@ -70,10 +71,16 @@ DecklinkProducerWidget::~DecklinkProducerWidget() Mlt::Producer *DecklinkProducerWidget::newProducer(Mlt::Profile &profile) { Mlt::Producer *p = new Mlt::Producer(profile, - QStringLiteral("consumer:decklink:%1").arg(ui->deviceCombo->currentIndex()).toLatin1().constData()); + QStringLiteral("consumer:decklink:%1") + .arg(ui->deviceCombo->currentIndex()) + .toLatin1() + .constData()); if (p->is_valid()) { - p->set("profile", ui->profileCombo->itemData( - ui->profileCombo->currentIndex()).toString().toLatin1().constData()); + p->set("profile", + ui->profileCombo->itemData(ui->profileCombo->currentIndex()) + .toString() + .toLatin1() + .constData()); p->set(kBackgroundCaptureProperty, 2); p->set(kShotcutCaptionProperty, tr("SDI/HDMI").toUtf8().constData()); } diff --git a/src/widgets/decklinkproducerwidget.h b/src/widgets/decklinkproducerwidget.h index 0aac35d8b8..3fa351a528 100644 --- a/src/widgets/decklinkproducerwidget.h +++ b/src/widgets/decklinkproducerwidget.h @@ -18,9 +18,10 @@ #ifndef DECKLINKPRODUCERWIDGET_H #define DECKLINKPRODUCERWIDGET_H -#include #include "abstractproducerwidget.h" +#include + namespace Ui { class DecklinkProducerWidget; } diff --git a/src/widgets/directshowvideowidget.cpp b/src/widgets/directshowvideowidget.cpp index a636a22846..e6dc959417 100644 --- a/src/widgets/directshowvideowidget.cpp +++ b/src/widgets/directshowvideowidget.cpp @@ -17,20 +17,22 @@ #include "directshowvideowidget.h" #include "ui_directshowvideowidget.h" + +#include "Logger.h" #include "mltcontroller.h" -#include "util.h" -#include "shotcut_mlt_properties.h" #include "settings.h" -#include -#include +#include "shotcut_mlt_properties.h" +#include "util.h" + #include #include #include #include +#include -DirectShowVideoWidget::DirectShowVideoWidget(QWidget *parent) : - QWidget(parent), - ui(new Ui::DirectShowVideoWidget) +DirectShowVideoWidget::DirectShowVideoWidget(QWidget *parent) + : QWidget(parent) + , ui(new Ui::DirectShowVideoWidget) { ui->setupUi(this); Util::setColorsToHighlight(ui->label); @@ -38,7 +40,13 @@ DirectShowVideoWidget::DirectShowVideoWidget(QWidget *parent) : QFileInfo ffmpegPath(qApp->applicationDirPath(), "ffmpeg"); QProcess proc; QStringList args; - args << "-hide_banner" << "-list_devices" << "true" << "-f" << "dshow" << "-i" << "dummy"; + args << "-hide_banner" + << "-list_devices" + << "true" + << "-f" + << "dshow" + << "-i" + << "dummy"; LOG_DEBUG() << ffmpegPath.absoluteFilePath() << args; proc.setStandardOutputFile(QProcess::nullDevice()); proc.setReadChannel(QProcess::StandardError); @@ -58,7 +66,8 @@ DirectShowVideoWidget::DirectShowVideoWidget(QWidget *parent) : auto currentAudio = 1; if (started && finished && proc.exitStatus() == QProcess::NormalExit) { QString output = proc.readAll(); - foreach (const QString &line, output.split(QRegularExpression("[\r\n]"), Qt::SkipEmptyParts)) { + foreach (const QString &line, + output.split(QRegularExpression("[\r\n]"), Qt::SkipEmptyParts)) { auto i = line.indexOf("] \""); if (i > -1) { auto j = line.indexOf("\" ("); @@ -105,14 +114,18 @@ Mlt::Producer *DirectShowVideoWidget::newProducer(Mlt::Profile &profile) Mlt::Producer *p = 0; if (ui->videoCombo->currentIndex() > 0) { LOG_DEBUG() << ui->videoCombo->currentData().toString(); - p = new Mlt::Producer(profile, QStringLiteral("dshow:video=%1") - .arg(ui->videoCombo->currentData().toString()) - .toUtf8().constData()); + p = new Mlt::Producer(profile, + QStringLiteral("dshow:video=%1") + .arg(ui->videoCombo->currentData().toString()) + .toUtf8() + .constData()); } if (ui->audioCombo->currentIndex() > 0) { Mlt::Producer *audio = new Mlt::Producer(profile, - QStringLiteral("dshow:audio=%1").arg(ui->audioCombo->currentData().toString()) - .toLatin1().constData()); + QStringLiteral("dshow:audio=%1") + .arg(ui->audioCombo->currentData().toString()) + .toLatin1() + .constData()); if (p && p->is_valid() && audio->is_valid()) { Mlt::Tractor *tractor = new Mlt::Tractor; tractor->set("_profile", profile.get_profile(), 0); @@ -131,12 +144,15 @@ Mlt::Producer *DirectShowVideoWidget::newProducer(Mlt::Profile &profile) delete p; p = new Mlt::Producer(profile, "color:"); if (ui->videoCombo->currentIndex() > 0) { - p->set("resource", QStringLiteral("dshow:video=%1") - .arg(ui->videoCombo->currentData().toString()) - .toUtf8().constData()); + p->set("resource", + QStringLiteral("dshow:video=%1") + .arg(ui->videoCombo->currentData().toString()) + .toUtf8() + .constData()); } if (ui->audioCombo->currentIndex() > 0) { - QString resource = QStringLiteral("dshow:audio=%1").arg(ui->audioCombo->currentData().toString()); + QString resource + = QStringLiteral("dshow:audio=%1").arg(ui->audioCombo->currentData().toString()); if (ui->videoCombo->currentIndex() > 0) { p->set("resource2", resource.toUtf8().constData()); } else { @@ -159,8 +175,8 @@ Mlt::Producer *DirectShowVideoWidget::newProducer(Mlt::Profile &profile) void DirectShowVideoWidget::setProducer(Mlt::Producer *producer) { - QString resource = producer->get("resource1") ? QString(producer->get("resource1")) : QString( - producer->get("resource")); + QString resource = producer->get("resource1") ? QString(producer->get("resource1")) + : QString(producer->get("resource")); QString resource2 = QString(producer->get("resource2")); LOG_DEBUG() << "resource" << resource; LOG_DEBUG() << "resource2" << resource2; diff --git a/src/widgets/directshowvideowidget.h b/src/widgets/directshowvideowidget.h index 485df6f2f6..4ad75ade61 100644 --- a/src/widgets/directshowvideowidget.h +++ b/src/widgets/directshowvideowidget.h @@ -19,8 +19,8 @@ #ifndef DIRECTSHOWVIDEOWIDGET_H #define DIRECTSHOWVIDEOWIDGET_H -#include #include "abstractproducerwidget.h" +#include namespace Ui { class DirectShowVideoWidget; diff --git a/src/widgets/docktoolbar.cpp b/src/widgets/docktoolbar.cpp index 8de6090fcd..38ff66ecca 100644 --- a/src/widgets/docktoolbar.cpp +++ b/src/widgets/docktoolbar.cpp @@ -23,8 +23,6 @@ #include #include -#include - DockToolBar::DockToolBar(const QString &title, QWidget *parent) : QToolBar(title, parent) , m_area(Qt::TopToolBarArea) @@ -45,8 +43,8 @@ void DockToolBar::setAreaHint(Qt::ToolBarArea area) void DockToolBar::paintEvent(QPaintEvent *event) { QPainter p(this); - QLinearGradient gradient = QLinearGradient(rect().left(), rect().center().y(), - rect().right(), rect().center().y()); + QLinearGradient gradient + = QLinearGradient(rect().left(), rect().center().y(), rect().right(), rect().center().y()); gradient.setColorAt(0, palette().window().color().lighter(104)); gradient.setColorAt(1, palette().window().color()); p.fillRect(rect(), gradient); @@ -71,7 +69,7 @@ void DockToolBar::updateStyle() } setFixedHeight(height); setIconSize(QSize(height - 9, height - 9)); - QString styleSheet = QString::fromUtf8( " \ + QString styleSheet = QString::fromUtf8(" \ QToolButton { \ width:%1px; \ height:%1px; \ @@ -87,6 +85,7 @@ void DockToolBar::updateStyle() spacing:3px; \ padding:1px; \ } \ - ").arg(height - 9); + ") + .arg(height - 9); setStyleSheet(styleSheet); } diff --git a/src/widgets/editmarkerwidget.cpp b/src/widgets/editmarkerwidget.cpp index 91171bcbd0..672321a61d 100644 --- a/src/widgets/editmarkerwidget.cpp +++ b/src/widgets/editmarkerwidget.cpp @@ -19,9 +19,9 @@ #include "mltcontroller.h" #include "qmltypes/qmlapplication.h" -#include "widgets/timespinbox.h" -#include "util.h" #include "settings.h" +#include "util.h" +#include "widgets/timespinbox.h" #include #include @@ -32,8 +32,8 @@ #include #include -EditMarkerWidget::EditMarkerWidget(QWidget *parent, const QString &text, const QColor &color, - int start, int end, int maxEnd) +EditMarkerWidget::EditMarkerWidget( + QWidget *parent, const QString &text, const QColor &color, int start, int end, int maxEnd) : QWidget(parent) { QGridLayout *grid = new QGridLayout(); @@ -50,8 +50,8 @@ EditMarkerWidget::EditMarkerWidget(QWidget *parent, const QString &text, const Q connect(m_colorButton, SIGNAL(clicked()), SLOT(on_colorButton_clicked())); grid->addWidget(m_colorButton, 1, 0, Qt::AlignRight); m_colorLabel = new QLabel(color.name(QColor::HexRgb)); - m_colorLabel->setStyleSheet(QStringLiteral("color: %1; background-color: %2") - .arg(Util::textColor(color), color.name())); + m_colorLabel->setStyleSheet( + QStringLiteral("color: %1; background-color: %2").arg(Util::textColor(color), color.name())); grid->addWidget(m_colorLabel, 1, 1); grid->addWidget(new QLabel(tr("Start")), 2, 0, Qt::AlignRight); @@ -60,7 +60,10 @@ EditMarkerWidget::EditMarkerWidget(QWidget *parent, const QString &text, const Q m_startSpinner->setMaximum(end); m_startSpinner->setValue(start); m_startSpinner->setToolTip(tr("Set the start time for this marker.")); - connect(m_startSpinner, SIGNAL(valueChanged(int)), this, SLOT(on_startSpinner_valueChanged(int))); + connect(m_startSpinner, + SIGNAL(valueChanged(int)), + this, + SLOT(on_startSpinner_valueChanged(int))); grid->addWidget(m_startSpinner, 2, 1); grid->addWidget(new QLabel(tr("End")), 3, 0, Qt::AlignRight); @@ -78,9 +81,7 @@ EditMarkerWidget::EditMarkerWidget(QWidget *parent, const QString &text, const Q grid->addWidget(m_durationLabel, 4, 1); } -EditMarkerWidget::~EditMarkerWidget() -{ -} +EditMarkerWidget::~EditMarkerWidget() {} QString EditMarkerWidget::getText() { @@ -102,8 +103,8 @@ int EditMarkerWidget::getEnd() return m_endSpinner->value(); } -void EditMarkerWidget::setValues(const QString &text, const QColor &color, int start, int end, - int maxEnd) +void EditMarkerWidget::setValues( + const QString &text, const QColor &color, int start, int end, int maxEnd) { QSignalBlocker textBlocker(m_textField); QSignalBlocker colorBlocker(m_colorLabel); @@ -111,8 +112,8 @@ void EditMarkerWidget::setValues(const QString &text, const QColor &color, int s QSignalBlocker endBlocker(m_endSpinner); m_textField->setText(text); m_colorLabel->setText(color.name(QColor::HexRgb)); - m_colorLabel->setStyleSheet(QStringLiteral("color: %1; background-color: %2") - .arg(Util::textColor(color), color.name())); + m_colorLabel->setStyleSheet( + QStringLiteral("color: %1; background-color: %2").arg(Util::textColor(color), color.name())); m_startSpinner->setMinimum(0); m_startSpinner->setMaximum(end); m_startSpinner->setValue(start); @@ -135,7 +136,7 @@ void EditMarkerWidget::on_colorButton_clicked() auto newColor = dialog.currentColor(); m_colorLabel->setText(newColor.name(QColor::HexRgb)); m_colorLabel->setStyleSheet(QStringLiteral("color: %1; background-color: %2") - .arg(Util::textColor(newColor), newColor.name())); + .arg(Util::textColor(newColor), newColor.name())); } emit valuesChanged(); } diff --git a/src/widgets/editmarkerwidget.h b/src/widgets/editmarkerwidget.h index 17f8cb643b..c950278da8 100644 --- a/src/widgets/editmarkerwidget.h +++ b/src/widgets/editmarkerwidget.h @@ -31,8 +31,8 @@ class EditMarkerWidget : public QWidget public: EditMarkerWidget(QWidget *parent); - EditMarkerWidget(QWidget *parent, const QString &text, const QColor &color, int start, int end, - int maxEnd); + EditMarkerWidget( + QWidget *parent, const QString &text, const QColor &color, int start, int end, int maxEnd); virtual ~EditMarkerWidget(); QString getText(); QColor getColor(); diff --git a/src/widgets/exportpresetstreeview.cpp b/src/widgets/exportpresetstreeview.cpp index e2f604548a..a0c06a4d2a 100644 --- a/src/widgets/exportpresetstreeview.cpp +++ b/src/widgets/exportpresetstreeview.cpp @@ -19,9 +19,7 @@ ExportPresetsTreeView::ExportPresetsTreeView(QWidget *parent) : QTreeView(parent) -{ - -} +{} void ExportPresetsTreeView::currentChanged(const QModelIndex ¤t, const QModelIndex &previous) { diff --git a/src/widgets/fixx11h.h b/src/widgets/fixx11h.h index f3db4bff70..b5debda83c 100644 --- a/src/widgets/fixx11h.h +++ b/src/widgets/fixx11h.h @@ -22,7 +22,6 @@ DEALINGS IN THE SOFTWARE. ****************************************************************************/ - //#ifdef don't do this, this file is supposed to be included //#define multiple times @@ -253,16 +252,14 @@ const int NormalState = XNormalState; #ifdef index #ifndef FIXX11H_index #define FIXX11H_index -inline -const char *Xindex( const char *s, int c ) +inline const char *Xindex(const char *s, int c) { - return index( s, c ); + return index(s, c); } #undef index -inline -const char *index( const char *s, int c ) +inline const char *index(const char *s, int c) { - return Xindex( s, c ); + return Xindex(s, c); } #endif #undef index @@ -273,21 +270,19 @@ const char *index( const char *s, int c ) // Affects: Should be without side effects. #ifndef FIXX11H_rindex #define FIXX11H_rindex -inline -const char *Xrindex( const char *s, int c ) +inline const char *Xrindex(const char *s, int c) { - return rindex( s, c ); + return rindex(s, c); } #undef rindex -inline -const char *rindex( const char *s, int c ) +inline const char *rindex(const char *s, int c) { - return Xrindex( s, c ); + return Xrindex(s, c); } #endif #undef rindex #endif -} +} // namespace X using namespace X; diff --git a/src/widgets/frameratewidget.cpp b/src/widgets/frameratewidget.cpp index ca73bf5f99..82db992834 100644 --- a/src/widgets/frameratewidget.cpp +++ b/src/widgets/frameratewidget.cpp @@ -51,7 +51,9 @@ FrameRateWidget::FrameRateWidget(QWidget *parent) m_fpsComboBox->addItem("50"); m_fpsComboBox->addItem("59.940060"); m_fpsComboBox->addItem("60"); - connect(m_fpsComboBox, SIGNAL(currentTextChanged(const QString &)), this, + connect(m_fpsComboBox, + SIGNAL(currentTextChanged(const QString &)), + this, SLOT(on_fpsComboBox_activated(const QString &))); layout->addWidget(m_fpsComboBox); } diff --git a/src/widgets/glaxnimateproducerwidget.cpp b/src/widgets/glaxnimateproducerwidget.cpp index 28637d0e6f..d5b98dd594 100644 --- a/src/widgets/glaxnimateproducerwidget.cpp +++ b/src/widgets/glaxnimateproducerwidget.cpp @@ -15,39 +15,41 @@ * along with this program. If not, see . */ -#include -#include #include "glaxnimateproducerwidget.h" +#include "ui_glaxnimateproducerwidget.h" + +#include "Logger.h" +#include "dialogs/longuitask.h" #include "mainwindow.h" +#include "mltcontroller.h" +#include "qmltypes/qmlapplication.h" #include "settings.h" -#include "ui_glaxnimateproducerwidget.h" #include "shotcut_mlt_properties.h" #include "util.h" -#include "mltcontroller.h" -#include "qmltypes/qmlapplication.h" -#include "dialogs/longuitask.h" #include "videowidget.h" -#include -#include + +#include #include +#include +#include +#include +#include #include #include -#include -#include #include +#include #include -#include static const QString kTransparent = QObject::tr("transparent", "Open Other > Animation"); static QString colorToString(const QColor &color) { return (color == QColor(0, 0, 0, 0)) ? kTransparent - : QString::asprintf("#%02X%02X%02X%02X", - qAlpha(color.rgba()), - qRed(color.rgba()), - qGreen(color.rgba()), - qBlue(color.rgba())); + : QString::asprintf("#%02X%02X%02X%02X", + qAlpha(color.rgba()), + qRed(color.rgba()), + qGreen(color.rgba()), + qBlue(color.rgba())); } static QString colorStringToResource(const QString &s) @@ -55,9 +57,9 @@ static QString colorStringToResource(const QString &s) return (s == kTransparent) ? "#00000000" : s; } -GlaxnimateProducerWidget::GlaxnimateProducerWidget(QWidget *parent) : - QWidget(parent), - ui(new Ui::GlaxnimateProducerWidget) +GlaxnimateProducerWidget::GlaxnimateProducerWidget(QWidget *parent) + : QWidget(parent) + , ui(new Ui::GlaxnimateProducerWidget) { ui->setupUi(this); m_title = ui->lineEdit->text(); @@ -98,15 +100,16 @@ void GlaxnimateProducerWidget::on_colorButton_clicked() auto rgb = newColor; auto transparent = QColor(0, 0, 0, 0); rgb.setAlpha(color.alpha()); - if (newColor.alpha() == 0 && (rgb != color || - (newColor == transparent && color == transparent))) { + if (newColor.alpha() == 0 + && (rgb != color || (newColor == transparent && color == transparent))) { newColor.setAlpha(255); } ui->colorLabel->setText(colorToString(newColor)); ui->colorLabel->setStyleSheet(QStringLiteral("color: %1; background-color: %2") - .arg(Util::textColor(newColor), newColor.name())); + .arg(Util::textColor(newColor), newColor.name())); if (m_producer) { - m_producer->set("background", colorStringToResource(ui->colorLabel->text()).toLatin1().constData()); + m_producer->set("background", + colorStringToResource(ui->colorLabel->text()).toLatin1().constData()); emit producerChanged(m_producer.get()); } } @@ -122,16 +125,19 @@ static void modifyJsonValue(QJsonValue &destValue, const QString &path, const QJ const int indexOfSquareBracketClose = path.indexOf(']'); const int arrayIndex = path.mid(indexOfSquareBracketOpen + 1, - indexOfSquareBracketClose - indexOfSquareBracketOpen - 1).toInt(); + indexOfSquareBracketClose - indexOfSquareBracketOpen - 1) + .toInt(); const QString squareBracketPropertyName = path.left(indexOfSquareBracketOpen); - const QString squareBracketSubPath = indexOfSquareBracketClose > 0 ? (path.mid( - indexOfSquareBracketClose + 1)[0] == '.' ? path.mid(indexOfSquareBracketClose + 2) : path.mid( - indexOfSquareBracketClose + 1)) : QString(); + const QString squareBracketSubPath = indexOfSquareBracketClose > 0 + ? (path.mid(indexOfSquareBracketClose + 1)[0] == '.' + ? path.mid(indexOfSquareBracketClose + 2) + : path.mid(indexOfSquareBracketClose + 1)) + : QString(); // determine what is first in path. dot or bracket bool useDot = true; - if (indexOfDot >= 0) { // there is a dot in path + if (indexOfDot >= 0) { // there is a dot in path if (indexOfSquareBracketOpen >= 0) { // there is squarebracket in path if (indexOfDot > indexOfSquareBracketOpen) useDot = false; @@ -188,7 +194,6 @@ static void modifyJsonValue(QJsonValue &destValue, const QString &path, const QJ } } - Mlt::Producer *GlaxnimateProducerWidget::newProducer(Mlt::Profile &profile) { // Get the file name. @@ -198,8 +203,12 @@ Mlt::Producer *GlaxnimateProducerWidget::newProducer(Mlt::Profile &profile) path.append("/%1.rawr"); path = path.arg(tr("animation")); auto nameFilter = tr("Glaxnimate (*.rawr);;All Files (*)"); - filename = QFileDialog::getSaveFileName(this, tr("New Animation"), path, nameFilter, - nullptr, Util::getFileDialogOptions()); + filename = QFileDialog::getSaveFileName(this, + tr("New Animation"), + path, + nameFilter, + nullptr, + Util::getFileDialogOptions()); } if (filename.isEmpty()) { return nullptr; @@ -212,8 +221,9 @@ Mlt::Producer *GlaxnimateProducerWidget::newProducer(Mlt::Profile &profile) GlaxnimateIpcServer::instance().newFile(filename, ui->durationSpinBox->value()); - Mlt::Producer *p = new Mlt::Producer(profile, - QStringLiteral("glaxnimate:").append(filename).toUtf8().constData()); + Mlt::Producer *p + = new Mlt::Producer(profile, + QStringLiteral("glaxnimate:").append(filename).toUtf8().constData()); p->set("background", colorStringToResource(ui->colorLabel->text()).toLatin1().constData()); m_title = info.fileName(); @@ -221,7 +231,9 @@ Mlt::Producer *GlaxnimateProducerWidget::newProducer(Mlt::Profile &profile) p->set(kShotcutDetailProperty, filename.toUtf8().constData()); m_watcher.reset(new QFileSystemWatcher({filename})); - connect(m_watcher.get(), &QFileSystemWatcher::fileChanged, this, + connect(m_watcher.get(), + &QFileSystemWatcher::fileChanged, + this, &GlaxnimateProducerWidget::onFileChanged); GlaxnimateIpcServer::instance().launch(p); @@ -246,7 +258,9 @@ void GlaxnimateProducerWidget::setProducer(Mlt::Producer *p) ui->durationSpinBox->setValue(p->get_length()); m_watcher.reset(new QFileSystemWatcher({filename})); - connect(m_watcher.get(), &QFileSystemWatcher::fileChanged, this, + connect(m_watcher.get(), + &QFileSystemWatcher::fileChanged, + this, &GlaxnimateProducerWidget::onFileChanged); } @@ -262,10 +276,11 @@ void GlaxnimateProducerWidget::loadPreset(Mlt::Properties &p) { QColor color(QFileInfo(p.get("background")).baseName()); ui->colorLabel->setText(colorToString(color)); - ui->colorLabel->setStyleSheet(QStringLiteral("color: %1; background-color: %2") - .arg(Util::textColor(color), color.name())); + ui->colorLabel->setStyleSheet( + QStringLiteral("color: %1; background-color: %2").arg(Util::textColor(color), color.name())); if (m_producer) { - m_producer->set("background", colorStringToResource(ui->colorLabel->text()).toLatin1().constData()); + m_producer->set("background", + colorStringToResource(ui->colorLabel->text()).toLatin1().constData()); emit producerChanged(m_producer.get()); } } @@ -359,7 +374,8 @@ void GlaxnimateProducerWidget::on_reloadButton_clicked() void GlaxnimateProducerWidget::on_durationSpinBox_editingFinished() { if (m_producer && m_producer->is_valid()) { - m_producer->set("length", m_producer->frames_to_time(ui->durationSpinBox->value(), mlt_time_clock)); + m_producer->set("length", + m_producer->frames_to_time(ui->durationSpinBox->value(), mlt_time_clock)); emit producerChanged(m_producer.get()); } } @@ -372,8 +388,8 @@ void GlaxnimateIpcServer::ParentResources::setProducer(const Mlt::Producer &prod return; m_profile.reset(new Mlt::Profile(::mlt_profile_clone(MLT.profile().get_profile()))); m_profile->set_progressive(Settings.playerProgressive()); - m_glaxnimateProducer.reset(new Mlt::Producer(*m_profile, "xml-string", - MLT.XML().toUtf8().constData())); + m_glaxnimateProducer.reset( + new Mlt::Producer(*m_profile, "xml-string", MLT.XML().toUtf8().constData())); if (m_glaxnimateProducer && m_glaxnimateProducer->is_valid()) { m_frameNum = -1; // hide this clip's video track and upper ones @@ -417,7 +433,8 @@ void GlaxnimateIpcServer::ParentResources::setProducer(const Mlt::Producer &prod for (int i = 0; i < count; i++) { std::unique_ptr filter(info->producer->filter(i)); if (filter && filter->is_valid()) { - if (found || !qstrcmp(filter->get(kShotcutFilterProperty), "maskGlaxnimate")) { + if (found + || !qstrcmp(filter->get(kShotcutFilterProperty), "maskGlaxnimate")) { found = true; filter->set("disable", 1); } @@ -434,7 +451,10 @@ void GlaxnimateIpcServer::onConnect() LOG_DEBUG() << ""; m_socket = m_server->nextPendingConnection(); connect(m_socket.data(), &QLocalSocket::readyRead, this, &GlaxnimateIpcServer::onReadyRead); - connect(m_socket.data(), &QLocalSocket::errorOccurred, this, &GlaxnimateIpcServer::onSocketError); + connect(m_socket.data(), + &QLocalSocket::errorOccurred, + this, + &GlaxnimateIpcServer::onSocketError); m_stream.reset(new QDataStream(m_socket.data())); m_stream->setVersion(QDataStream::Qt_5_15); *m_stream << QStringLiteral("hello"); @@ -446,7 +466,8 @@ void GlaxnimateIpcServer::onConnect() int GlaxnimateIpcServer::toMltFps(float frame) const { if (parent->m_producer.get_double("meta.media.frame_rate") > 0) { - return qRound(frame / parent->m_producer.get_double("meta.media.frame_rate") * MLT.profile().fps()); + return qRound(frame / parent->m_producer.get_double("meta.media.frame_rate") + * MLT.profile().fps()); } return frame; } @@ -472,14 +493,13 @@ void GlaxnimateIpcServer::onReadyRead() } // Only if the frame number is different - int frameNum = parent->m_producer.get_int(kPlaylistStartProperty) + toMltFps( - time) - parent->m_producer.get_int("first_frame"); + int frameNum = parent->m_producer.get_int(kPlaylistStartProperty) + toMltFps(time) + - parent->m_producer.get_int("first_frame"); if (frameNum != parent->m_frameNum) { LOG_DEBUG() << "glaxnimate time =" << time << "=> Shotcut frameNum =" << frameNum; if (!parent || !parent->m_glaxnimateProducer - || !parent->m_glaxnimateProducer->is_valid() - || time < 0.0) { + || !parent->m_glaxnimateProducer->is_valid() || time < 0.0) { MLT.seek(frameNum); return; } @@ -494,11 +514,14 @@ void GlaxnimateIpcServer::onReadyRead() int scale = Settings.playerPreviewScale() ? Settings.playerPreviewScale() : 2160; #endif auto height = qMin(scale, MLT.profile().height()); - auto width = (height == MLT.profile().height()) ? MLT.profile().width() : - Util::coerceMultiple(height * MLT.profile().display_aspect_num() / - MLT.profile().display_aspect_den() - * MLT.profile().sample_aspect_den() / MLT.profile().sample_aspect_num()); - frame->set("consumer.deinterlacer", Settings.playerDeinterlacer().toLatin1().constData()); + auto width = (height == MLT.profile().height()) + ? MLT.profile().width() + : Util::coerceMultiple(height * MLT.profile().display_aspect_num() + / MLT.profile().display_aspect_den() + * MLT.profile().sample_aspect_den() + / MLT.profile().sample_aspect_num()); + frame->set("consumer.deinterlacer", + Settings.playerDeinterlacer().toLatin1().constData()); frame->set("consumer.top_field_first", -1); mlt_image_format format = mlt_image_rgb; const uchar *image = frame->get_image(format, width, height); @@ -510,7 +533,10 @@ void GlaxnimateIpcServer::onReadyRead() if (MLT.profile().sar() - 1.0 > 0.0001) { // Use QImage to convert to square pixels width = qRound(width * MLT.profile().sar()); - temp = temp.scaled(width, height, Qt::IgnoreAspectRatio, Qt::SmoothTransformation); + temp = temp.scaled(width, + height, + Qt::IgnoreAspectRatio, + Qt::SmoothTransformation); } if (copyToShared(temp)) { parent->m_frameNum = frameNum; @@ -535,7 +561,7 @@ void GlaxnimateIpcServer::onSocketError(QLocalSocket::LocalSocketError socketErr void GlaxnimateIpcServer::onFrameDisplayed(const SharedFrame &frame) { - auto image = frame.get_image(mlt_image_rgb); + auto image = frame.get_image(mlt_image_rgb); if (image) { auto width = frame.get_image_width(); auto height = frame.get_image_height(); @@ -565,7 +591,9 @@ void GlaxnimateIpcServer::newFile(const QString &filename, int duration) QJsonValue jsonValue(json); modifyJsonValue(jsonValue, "animation.name", QFileInfo(filename).completeBaseName()); - modifyJsonValue(jsonValue, "animation.width", qRound(MLT.profile().width() * MLT.profile().sar())); + modifyJsonValue(jsonValue, + "animation.width", + qRound(MLT.profile().width() * MLT.profile().sar())); modifyJsonValue(jsonValue, "animation.height", MLT.profile().height()); modifyJsonValue(jsonValue, "animation.fps", MLT.profile().fps()); modifyJsonValue(jsonValue, "animation.animation.last_frame", duration); @@ -587,15 +615,18 @@ void GlaxnimateIpcServer::reset() parent.reset(); } -void GlaxnimateIpcServer::launch(const Mlt::Producer &producer, QString filename, +void GlaxnimateIpcServer::launch(const Mlt::Producer &producer, + QString filename, bool hideCurrentTrack) { parent.reset(new ParentResources); if (Settings.playerGPU()) { parent->m_producer = producer; - connect(qobject_cast(MLT.videoWidget()), &Mlt::VideoWidget::frameDisplayed, - this, &GlaxnimateIpcServer::onFrameDisplayed); + connect(qobject_cast(MLT.videoWidget()), + &Mlt::VideoWidget::frameDisplayed, + this, + &GlaxnimateIpcServer::onFrameDisplayed); } else { LongUiTask longTask(QObject::tr("Edit With Glaxnimate")); auto future = QtConcurrent::run([this, &producer, &hideCurrentTrack]() { @@ -634,7 +665,7 @@ void GlaxnimateIpcServer::launch(const Mlt::Producer &producer, QString filename args.clear(); args << filename; // Run without --ipc - } else { + } else { childProcess.setArguments(args); if (childProcess.startDetached()) { LOG_DEBUG() << Settings.glaxnimatePath() << args.join(' '); @@ -664,8 +695,12 @@ void GlaxnimateIpcServer::launch(const Mlt::Producer &producer, QString filename dialog.setEscapeButton(QMessageBox::Cancel); dialog.setWindowModality(QmlApplication::dialogModality()); if (dialog.exec() == QMessageBox::Ok) { - auto path = QFileDialog::getOpenFileName(MAIN.window(), tr("Find Glaxnimate"), QString(), QString(), - nullptr, Util::getFileDialogOptions()); + auto path = QFileDialog::getOpenFileName(MAIN.window(), + tr("Find Glaxnimate"), + QString(), + QString(), + nullptr, + Util::getFileDialogOptions()); if (!path.isEmpty()) { args.clear(); args << "--ipc" << name << filename; diff --git a/src/widgets/glaxnimateproducerwidget.h b/src/widgets/glaxnimateproducerwidget.h index ffb84a0028..015654d279 100644 --- a/src/widgets/glaxnimateproducerwidget.h +++ b/src/widgets/glaxnimateproducerwidget.h @@ -18,15 +18,15 @@ #ifndef GLAXNIMATEPRODUCERWIDGET_H #define GLAXNIMATEPRODUCERWIDGET_H -#include -#include -#include -#include -#include -#include +#include "abstractproducerwidget.h" #include "sharedframe.h" -#include "abstractproducerwidget.h" +#include +#include +#include +#include +#include +#include class GlaxnimateIpcServer : public QObject { @@ -54,7 +54,8 @@ class GlaxnimateIpcServer : public QObject static GlaxnimateIpcServer &instance(); static void newFile(const QString &filename, int duration); void reset(); - void launch(const Mlt::Producer &producer, QString filename = QString(), + void launch(const Mlt::Producer &producer, + QString filename = QString(), bool hideCurrentTrack = true); private slots: diff --git a/src/widgets/iecscale.h b/src/widgets/iecscale.h index 747c878c4b..a386c3efb1 100644 --- a/src/widgets/iecscale.h +++ b/src/widgets/iecscale.h @@ -37,7 +37,7 @@ static inline double IEC_Scale(double dB) fScale = (dB + 40.0f) * 0.015f + 0.15f; else if (dB < -20.0f) fScale = (dB + 30.0f) * 0.02f + 0.3f; - else if (dB < -0.001f || dB > 0.001f) /* if (dB < 0.0f) */ + else if (dB < -0.001f || dB > 0.001f) /* if (dB < 0.0f) */ fScale = (dB + 20.0f) * 0.025f + 0.5f; return fScale; diff --git a/src/widgets/imageproducerwidget.cpp b/src/widgets/imageproducerwidget.cpp index 25e5efd235..ee820eb03c 100644 --- a/src/widgets/imageproducerwidget.cpp +++ b/src/widgets/imageproducerwidget.cpp @@ -17,27 +17,29 @@ #include "imageproducerwidget.h" #include "ui_imageproducerwidget.h" -#include "settings.h" -#include "mainwindow.h" -#include "shotcut_mlt_properties.h" -#include "util.h" + +#include "Logger.h" #include "dialogs/filedatedialog.h" +#include "mainwindow.h" #include "proxymanager.h" #include "qmltypes/qmlapplication.h" -#include -#include +#include "settings.h" +#include "shotcut_mlt_properties.h" +#include "util.h" + +#include #include +#include #include -#include #include // This legacy property is only used in this widget. #define kShotcutResourceProperty "shotcut_resource" -ImageProducerWidget::ImageProducerWidget(QWidget *parent) : - QWidget(parent), - ui(new Ui::ImageProducerWidget), - m_defaultDuration(-1) +ImageProducerWidget::ImageProducerWidget(QWidget *parent) + : QWidget(parent) + , ui(new Ui::ImageProducerWidget) + , m_defaultDuration(-1) { ui->setupUi(this); Util::setColorsToHighlight(ui->filenameLabel, QPalette::Base); @@ -84,15 +86,17 @@ void ImageProducerWidget::setProducer(Mlt::Producer *p) caption = name; m_producer->set(kShotcutCaptionProperty, caption.toUtf8().constData()); } - ui->filenameLabel->setText(ui->filenameLabel->fontMetrics().elidedText(caption, Qt::ElideLeft, - width() - 30)); + ui->filenameLabel->setText( + ui->filenameLabel->fontMetrics().elidedText(caption, Qt::ElideLeft, width() - 30)); updateDuration(); resource = QDir::toNativeSeparators(resource); ui->filenameLabel->setToolTip(resource); - bool isProxy = m_producer->get_int(kIsProxyProperty) && m_producer->get(kOriginalResourceProperty); - ui->resolutionLabel->setText(QStringLiteral("%1x%2 %3").arg(p->get("meta.media.width")).arg( - p->get("meta.media.height")) - .arg(isProxy ? tr("(PROXY)") : "")); + bool isProxy = m_producer->get_int(kIsProxyProperty) + && m_producer->get(kOriginalResourceProperty); + ui->resolutionLabel->setText(QStringLiteral("%1x%2 %3") + .arg(p->get("meta.media.width")) + .arg(p->get("meta.media.height")) + .arg(isProxy ? tr("(PROXY)") : "")); ui->aspectNumSpinBox->blockSignals(true); if (p->get(kAspectRatioNumerator) && p->get(kAspectRatioDenominator)) { ui->aspectNumSpinBox->setValue(p->get_int(kAspectRatioNumerator)); @@ -122,8 +126,8 @@ void ImageProducerWidget::setProducer(Mlt::Producer *p) void ImageProducerWidget::updateDuration() { if (m_producer->get(kFilterOutProperty)) - ui->durationSpinBox->setValue(m_producer->get_int(kFilterOutProperty) - m_producer->get_int( - kFilterInProperty) + 1); + ui->durationSpinBox->setValue(m_producer->get_int(kFilterOutProperty) + - m_producer->get_int(kFilterInProperty) + 1); else ui->durationSpinBox->setValue(m_producer->get_playtime()); } @@ -171,10 +175,12 @@ void ImageProducerWidget::recreateProducer() } } Mlt::Producer *p = newProducer(MLT.profile()); - p->pass_list(*m_producer, "force_aspect_ratio," kAspectRatioNumerator "," kAspectRatioDenominator - ", begin, ttl," kShotcutResourceProperty ", autolength, length," kShotcutSequenceProperty ", " - kPlaylistIndexProperty - ", " kCommentProperty "," kOriginalResourceProperty "," kDisableProxyProperty "," kIsProxyProperty); + p->pass_list(*m_producer, + "force_aspect_ratio," kAspectRatioNumerator "," kAspectRatioDenominator + ", begin, ttl," kShotcutResourceProperty + ", autolength, length," kShotcutSequenceProperty ", " kPlaylistIndexProperty + ", " kCommentProperty "," kOriginalResourceProperty "," kDisableProxyProperty + "," kIsProxyProperty); Mlt::Controller::copyFilters(*m_producer, *p); if (m_producer->get(kMultitrackItemProperty)) { emit producerChanged(p); @@ -209,13 +215,15 @@ void ImageProducerWidget::on_resetButton_clicked() void ImageProducerWidget::on_aspectNumSpinBox_valueChanged(int) { if (m_producer) { - double new_sar = double(ui->aspectNumSpinBox->value()) / - double(ui->aspectDenSpinBox->value()); + double new_sar = double(ui->aspectNumSpinBox->value()) + / double(ui->aspectDenSpinBox->value()); double sar = m_producer->get_double("aspect_ratio"); if (m_producer->get("force_aspect_ratio") || new_sar != sar) { m_producer->set("force_aspect_ratio", QString::number(new_sar).toLatin1().constData()); - m_producer->set(kAspectRatioNumerator, ui->aspectNumSpinBox->text().toLatin1().constData()); - m_producer->set(kAspectRatioDenominator, ui->aspectDenSpinBox->text().toLatin1().constData()); + m_producer->set(kAspectRatioNumerator, + ui->aspectNumSpinBox->text().toLatin1().constData()); + m_producer->set(kAspectRatioDenominator, + ui->aspectDenSpinBox->text().toLatin1().constData()); } emit producerChanged(producer()); } @@ -239,7 +247,7 @@ void ImageProducerWidget::on_sequenceCheckBox_clicked(bool checked) { QString resource = m_producer->get("resource"); if (checked && m_producer->get_int(kIsProxyProperty) - && m_producer->get(kOriginalResourceProperty)) { + && m_producer->get(kOriginalResourceProperty)) { // proxy is not currently supported for image sequence, disable it resource = m_producer->get(kOriginalResourceProperty); m_producer->set(kDisableProxyProperty, 1); @@ -260,7 +268,8 @@ void ImageProducerWidget::on_sequenceCheckBox_clicked(bool checked) int count = 0; // find the last numeric digit - for (; i && !name[i - 1].isDigit(); i--) {}; + for (; i && !name[i - 1].isDigit(); i--) { + }; // count the digits and build the begin value for (; i && name[i - 1].isDigit(); i--, count++) begin.prepend(name[i - 1]); @@ -288,14 +297,15 @@ void ImageProducerWidget::on_sequenceCheckBox_clicked(bool checked) imageCount++; gap = 0; } else { - gap ++; + gap++; } i++; if (i % 100 == 0) QCoreApplication::processEvents(); } - m_producer->set("length", m_producer->frames_to_time(imageCount * m_producer->get_int("ttl"), - mlt_time_clock)); + m_producer->set("length", + m_producer->frames_to_time(imageCount * m_producer->get_int("ttl"), + mlt_time_clock)); ui->durationSpinBox->setValue(imageCount); ui->durationSpinBox->setEnabled(false); MAIN.showStatusMessage(tr("Reloading image sequence...")); @@ -305,8 +315,10 @@ void ImageProducerWidget::on_sequenceCheckBox_clicked(bool checked) m_producer->Mlt::Properties::clear(kDisableProxyProperty); m_producer->Mlt::Properties::clear("begin"); m_producer->set("resource", m_producer->get(kShotcutResourceProperty)); - m_producer->set("length", m_producer->frames_to_time(qRound(MLT.profile().fps() * - Mlt::kMaxImageDurationSecs), mlt_time_clock)); + m_producer->set("length", + m_producer->frames_to_time(qRound(MLT.profile().fps() + * Mlt::kMaxImageDurationSecs), + mlt_time_clock)); ui->durationSpinBox->setValue(qRound(MLT.profile().fps() * Settings.imageDuration())); ui->durationSpinBox->setEnabled(true); } @@ -449,9 +461,10 @@ void ImageProducerWidget::on_actionDeleteProxy_triggered() void ImageProducerWidget::on_actionCopyHashCode_triggered() { qApp->clipboard()->setText(Util::getHash(*producer())); - QMessageBox::information(this, qApp->applicationName(), - tr("The hash code below is already copied to your clipboard:\n\n") + - Util::getHash(*producer()), + QMessageBox::information(this, + qApp->applicationName(), + tr("The hash code below is already copied to your clipboard:\n\n") + + Util::getHash(*producer()), QMessageBox::Ok); } diff --git a/src/widgets/imageproducerwidget.h b/src/widgets/imageproducerwidget.h index 3276a1eb9d..227959520c 100644 --- a/src/widgets/imageproducerwidget.h +++ b/src/widgets/imageproducerwidget.h @@ -18,9 +18,10 @@ #ifndef IMAGEPRODUCERWIDGET_H #define IMAGEPRODUCERWIDGET_H -#include #include "abstractproducerwidget.h" +#include + namespace Ui { class ImageProducerWidget; } @@ -50,9 +51,9 @@ public slots: private slots: void on_resetButton_clicked(); - void on_aspectNumSpinBox_valueChanged(int ); + void on_aspectNumSpinBox_valueChanged(int); - void on_aspectDenSpinBox_valueChanged(int ); + void on_aspectDenSpinBox_valueChanged(int); void on_durationSpinBox_editingFinished(); diff --git a/src/widgets/isingwidget.cpp b/src/widgets/isingwidget.cpp index 0a4470748a..a4e8313c35 100644 --- a/src/widgets/isingwidget.cpp +++ b/src/widgets/isingwidget.cpp @@ -15,18 +15,19 @@ * along with this program. If not, see . */ -#include "shotcut_mlt_properties.h" #include "isingwidget.h" #include "ui_isingwidget.h" + +#include "shotcut_mlt_properties.h" #include "util.h" static const char *kParamTemperature = "0"; static const char *kParamBorderGrowth = "1"; static const char *kParamSpontaneous = "2"; -IsingWidget::IsingWidget(QWidget *parent) : - QWidget(parent), - ui(new Ui::IsingWidget) +IsingWidget::IsingWidget(QWidget *parent) + : QWidget(parent) + , ui(new Ui::IsingWidget) { ui->setupUi(this); Util::setColorsToHighlight(ui->nameLabel); diff --git a/src/widgets/isingwidget.h b/src/widgets/isingwidget.h index d4059f6da4..0497292d9c 100644 --- a/src/widgets/isingwidget.h +++ b/src/widgets/isingwidget.h @@ -18,9 +18,10 @@ #ifndef ISINGWIDGET_H #define ISINGWIDGET_H -#include #include "abstractproducerwidget.h" +#include + namespace Ui { class IsingWidget; } diff --git a/src/widgets/lineeditclear.cpp b/src/widgets/lineeditclear.cpp index 7276984e58..8f1d2da2d0 100644 --- a/src/widgets/lineeditclear.cpp +++ b/src/widgets/lineeditclear.cpp @@ -9,24 +9,28 @@ ****************************************************************************/ #include "lineeditclear.h" -#include -#include + #include +#include +#include LineEditClear::LineEditClear(QWidget *parent) : QLineEdit(parent) { clearButton = new QToolButton(this); - clearButton->setIcon(QIcon::fromTheme("edit-clear", - QIcon(":/icons/oxygen/32x32/actions/edit-clear.png"))); -// clearButton->setIconSize(QSize(16, 16)); + clearButton->setIcon( + QIcon::fromTheme("edit-clear", QIcon(":/icons/oxygen/32x32/actions/edit-clear.png"))); + // clearButton->setIconSize(QSize(16, 16)); clearButton->setCursor(Qt::ArrowCursor); clearButton->setStyleSheet("QToolButton { border: none; padding: 0px; }"); clearButton->hide(); connect(clearButton, SIGNAL(clicked()), this, SLOT(clear())); - connect(this, SIGNAL(textChanged(const QString &)), this, SLOT(updateCloseButton(const QString &))); + connect(this, + SIGNAL(textChanged(const QString &)), + this, + SLOT(updateCloseButton(const QString &))); int frameWidth = style()->pixelMetric(QStyle::PM_DefaultFrameWidth); -// setStyleSheet(QStringLiteral("QLineEdit { padding-right: %1px; } ").arg(clearButton->sizeHint().width() + frameWidth + 1)); + // setStyleSheet(QStringLiteral("QLineEdit { padding-right: %1px; } ").arg(clearButton->sizeHint().width() + frameWidth + 1)); QSize msz = minimumSizeHint(); setMinimumSize(qMax(msz.width(), clearButton->sizeHint().height() + frameWidth * 2 + 2), qMax(msz.height(), clearButton->sizeHint().height() + frameWidth * 2 + 2)); @@ -43,7 +47,8 @@ void LineEditClear::resizeEvent(QResizeEvent *) bool LineEditClear::eventFilter(QObject *target, QEvent *event) { - if (QEvent::KeyPress == event->type() && Qt::Key_Escape == static_cast(event)->key()) { + if (QEvent::KeyPress == event->type() + && Qt::Key_Escape == static_cast(event)->key()) { clear(); } return QLineEdit::eventFilter(target, event); diff --git a/src/widgets/lineeditclear.h b/src/widgets/lineeditclear.h index 445b905288..fc6d723f23 100644 --- a/src/widgets/lineeditclear.h +++ b/src/widgets/lineeditclear.h @@ -34,4 +34,3 @@ private slots: }; #endif // LIENEDIT_H - diff --git a/src/widgets/lissajouswidget.cpp b/src/widgets/lissajouswidget.cpp index 67f5fd227e..652f32086f 100644 --- a/src/widgets/lissajouswidget.cpp +++ b/src/widgets/lissajouswidget.cpp @@ -15,17 +15,18 @@ * along with this program. If not, see . */ -#include "shotcut_mlt_properties.h" #include "lissajouswidget.h" #include "ui_lissajouswidget.h" + +#include "shotcut_mlt_properties.h" #include "util.h" static const char *kParamRatioX = "0"; static const char *kParamRatioY = "1"; -LissajousWidget::LissajousWidget(QWidget *parent) : - QWidget(parent), - ui(new Ui::LissajousWidget) +LissajousWidget::LissajousWidget(QWidget *parent) + : QWidget(parent) + , ui(new Ui::LissajousWidget) { ui->setupUi(this); Util::setColorsToHighlight(ui->nameLabel); diff --git a/src/widgets/lissajouswidget.h b/src/widgets/lissajouswidget.h index a0c10efd9b..4f8909a6a7 100644 --- a/src/widgets/lissajouswidget.h +++ b/src/widgets/lissajouswidget.h @@ -18,9 +18,10 @@ #ifndef LISSAJOUSWIDGET_H #define LISSAJOUSWIDGET_H -#include #include "abstractproducerwidget.h" +#include + namespace Mlt { class Producer; } diff --git a/src/widgets/lumamixtransition.cpp b/src/widgets/lumamixtransition.cpp index 7c176e77ee..cf66577091 100644 --- a/src/widgets/lumamixtransition.cpp +++ b/src/widgets/lumamixtransition.cpp @@ -17,15 +17,16 @@ #include "lumamixtransition.h" #include "ui_lumamixtransition.h" -#include "settings.h" + +#include "Logger.h" #include "mltcontroller.h" +#include "qmltypes/qmlapplication.h" +#include "settings.h" #include "util.h" #include "widgets/producerpreviewwidget.h" -#include "qmltypes/qmlapplication.h" #include #include -#include static const int kLumaComboDissolveIndex = 0; static const int kLumaComboCutIndex = 1; @@ -56,7 +57,8 @@ LumaMixTransition::LumaMixTransition(Mlt::Producer &producer, QWidget *parent) QString resource = transition->get("resource"); ui->lumaCombo->blockSignals(true); if (!resource.isEmpty() && resource.indexOf("%luma") != -1) { - ui->lumaCombo->setCurrentRow(resource.mid(resource.indexOf("%luma") + 5).left(2).toInt() + 2); + ui->lumaCombo->setCurrentRow(resource.mid(resource.indexOf("%luma") + 5).left(2).toInt() + + 2); } else if (!resource.isEmpty() && resource.startsWith("color:")) { ui->lumaCombo->setCurrentRow(kLumaComboCutIndex); ui->softnessLabel->setText(tr("Position")); @@ -105,8 +107,8 @@ LumaMixTransition::LumaMixTransition(Mlt::Producer &producer, QWidget *parent) ui->horizontalLayout->addWidget(m_preview, 0, Qt::AlignCenter); connect(this, SIGNAL(modified()), this, SLOT(startPreview()), Qt::QueuedConnection); ui->getCustomLabel->setText( - QString::fromLatin1("%1").arg( - ui->getCustomLabel->text())); + QString::fromLatin1("%1") + .arg(ui->getCustomLabel->text())); } LumaMixTransition::~LumaMixTransition() @@ -190,7 +192,8 @@ Mlt::Transition *LumaMixTransition::getTransition(const QString &name) Mlt::Transition transition(*service); if (name == transition.get("mlt_service")) return new Mlt::Transition(transition); - else if (name == "luma" && QStringLiteral("movit.luma_mix") == transition.get("mlt_service")) + else if (name == "luma" + && QStringLiteral("movit.luma_mix") == transition.get("mlt_service")) return new Mlt::Transition(transition); } service.reset(service->producer()); @@ -205,7 +208,7 @@ void LumaMixTransition::updateCustomLumaLabel(Mlt::Transition &transition) ui->customLumaLabel->setToolTip(QString()); QString resource = transition.get("resource"); if (resource.isEmpty() || resource.indexOf("%luma") != -1 || resource.startsWith("color:") - || ui->lumaCombo->currentRow() > m_maxStockIndex) { + || ui->lumaCombo->currentRow() > m_maxStockIndex) { } else if (!resource.isEmpty() && !resource.startsWith("color:")) { ui->customLumaLabel->setText(QFileInfo(transition.get("resource")).fileName()); ui->customLumaLabel->setToolTip(transition.get("resource")); @@ -220,8 +223,8 @@ void LumaMixTransition::on_lumaCombo_currentRowChanged(int index) on_invertCheckBox_clicked(false); ui->invertCheckBox->setChecked(false); } - ui->invertCheckBox->setEnabled( index != kLumaComboDissolveIndex && index != kLumaComboCutIndex); - ui->softnessSlider->setEnabled( index != kLumaComboDissolveIndex); + ui->invertCheckBox->setEnabled(index != kLumaComboDissolveIndex && index != kLumaComboCutIndex); + ui->softnessSlider->setEnabled(index != kLumaComboDissolveIndex); ui->softnessSpinner->setEnabled(index != kLumaComboDissolveIndex); QScopedPointer transition(getTransition("luma")); @@ -240,8 +243,12 @@ void LumaMixTransition::on_lumaCombo_currentRowChanged(int index) #ifdef Q_OS_MAC path.append("/*"); #endif - QString filename = QFileDialog::getOpenFileName(this, tr("Open File"), path, - QString(), nullptr, Util::getFileDialogOptions()); + QString filename = QFileDialog::getOpenFileName(this, + tr("Open File"), + path, + QString(), + nullptr, + Util::getFileDialogOptions()); activateWindow(); if (!filename.isEmpty()) { transition->set("resource", filename.toUtf8().constData()); @@ -256,8 +263,11 @@ void LumaMixTransition::on_lumaCombo_currentRowChanged(int index) Util::getHash(*transition); } else { ui->softnessLabel->setText(tr("Softness")); - transition->set("resource", QStringLiteral("%luma%1.pgm").arg(index - 2, 2, 10, - QChar('0')).toLatin1().constData()); + transition->set("resource", + QStringLiteral("%luma%1.pgm") + .arg(index - 2, 2, 10, QChar('0')) + .toLatin1() + .constData()); } if (qstrcmp(transition->get("resource"), "")) { transition->set("progressive", 1); @@ -279,7 +289,8 @@ void LumaMixTransition::startPreview() { if (Settings.timelinePreviewTransition() && m_producer.is_valid() && MLT.isPaused()) { m_preview->stop(); - m_previewProducer = new Mlt::Producer(MLT.profile(), "xml-string", + m_previewProducer = new Mlt::Producer(MLT.profile(), + "xml-string", MLT.XML(&m_producer).toUtf8().constData()); m_preview->start(m_previewProducer); } @@ -293,7 +304,6 @@ void LumaMixTransition::on_previewCheckBox_clicked(bool checked) } } - void LumaMixTransition::on_favoriteButton_clicked() { QmlApplication::addWipe(ui->customLumaLabel->toolTip()); @@ -303,4 +313,3 @@ void LumaMixTransition::on_favoriteButton_clicked() dir.mkdir(transitions); } } - diff --git a/src/widgets/lumamixtransition.h b/src/widgets/lumamixtransition.h index 959704f862..8dc9a4561e 100644 --- a/src/widgets/lumamixtransition.h +++ b/src/widgets/lumamixtransition.h @@ -18,9 +18,9 @@ #ifndef LUMAMIXTRANSITION_H #define LUMAMIXTRANSITION_H -#include #include #include +#include namespace Ui { class LumaMixTransition; diff --git a/src/widgets/metalvideowidget.mm b/src/widgets/metalvideowidget.mm index 7e4d39eb87..aa0bb4de2b 100644 --- a/src/widgets/metalvideowidget.mm +++ b/src/widgets/metalvideowidget.mm @@ -17,7 +17,7 @@ #include "metalvideowidget.h" -#include +#include "Logger.h" #include diff --git a/src/widgets/mltclipproducerwidget.cpp b/src/widgets/mltclipproducerwidget.cpp index e88e965b08..d5acd98e7f 100644 --- a/src/widgets/mltclipproducerwidget.cpp +++ b/src/widgets/mltclipproducerwidget.cpp @@ -26,8 +26,8 @@ #include #include -MltClipProducerWidget::MltClipProducerWidget(QWidget *parent) : - QWidget(parent) +MltClipProducerWidget::MltClipProducerWidget(QWidget *parent) + : QWidget(parent) { qDebug(); QVBoxLayout *vlayout = new QVBoxLayout(); @@ -93,12 +93,10 @@ MltClipProducerWidget::MltClipProducerWidget(QWidget *parent) : vlayout->addLayout(glayout); - this->setLayout (vlayout); + this->setLayout(vlayout); } -MltClipProducerWidget::~MltClipProducerWidget() -{ -} +MltClipProducerWidget::~MltClipProducerWidget() {} Mlt::Producer *MltClipProducerWidget::newProducer(Mlt::Profile &) { @@ -131,7 +129,7 @@ void MltClipProducerWidget::setProducer(Mlt::Producer *p) int dar_num = width * sar_num; int dar_den = height * sar_den; if (dar_den > 0) { - switch (int((double)dar_num / (double)dar_den * 100.0)) { + switch (int((double) dar_num / (double) dar_den * 100.0)) { case 133: dar_num = 4; dar_den = 3; @@ -148,7 +146,7 @@ void MltClipProducerWidget::setProducer(Mlt::Producer *p) m_aspectRatioLabel->setText(QString("%1 : %2").arg(dar_num).arg(dar_den)); int frame_rate_num = m_producer->get_int("meta.media.frame_rate_num"); int frame_rate_den = m_producer->get_int("meta.media.frame_rate_den"); - double fps = (double)frame_rate_num / (double)frame_rate_den; + double fps = (double) frame_rate_num / (double) frame_rate_den; m_frameRateLabel->setText(tr("%L1 fps").arg(fps, 0, 'f', 6)); int progressive = m_producer->get_int("meta.media.progressive"); if (progressive) @@ -170,8 +168,7 @@ void MltClipProducerWidget::setProducer(Mlt::Producer *p) mismatchPalette.setColor(this->foregroundRole(), Qt::red); QScopedPointer profile(m_producer->profile()); - if (profile->width() == width && - profile->height() == height) { + if (profile->width() == width && profile->height() == height) { m_resolutionLabel->setPalette(standardPalette); } else { mismatch = true; @@ -183,7 +180,7 @@ void MltClipProducerWidget::setProducer(Mlt::Producer *p) mismatch = true; m_frameRateLabel->setPalette(mismatchPalette); } - double darDiff = profile->dar() - ((double)dar_num / (double)dar_den); + double darDiff = profile->dar() - ((double) dar_num / (double) dar_den); if (fabs(darDiff) < 0.01) { m_aspectRatioLabel->setPalette(standardPalette); } else { @@ -200,8 +197,8 @@ void MltClipProducerWidget::setProducer(Mlt::Producer *p) if (mismatch) { QIcon icon = QIcon(":/icons/oxygen/32x32/status/task-attempt.png"); m_errorIcon->setPixmap(icon.pixmap(QSize(24, 24))); - m_errorText->setText( - tr("Subclip profile does not match project profile.\nThis may provide unexpected results")); + m_errorText->setText(tr("Subclip profile does not match project profile.\nThis may provide " + "unexpected results")); } else { QIcon icon = QIcon(":/icons/oxygen/32x32/status/task-complete.png"); m_errorIcon->setPixmap(icon.pixmap(QSize(24, 24))); diff --git a/src/widgets/mltclipproducerwidget.h b/src/widgets/mltclipproducerwidget.h index 1acc9ddb85..5d5c1b9b93 100644 --- a/src/widgets/mltclipproducerwidget.h +++ b/src/widgets/mltclipproducerwidget.h @@ -20,8 +20,8 @@ #include "abstractproducerwidget.h" -#include #include +#include class QLabel; diff --git a/src/widgets/networkproducerwidget.cpp b/src/widgets/networkproducerwidget.cpp index d7fb8b7e27..c8c64f506d 100644 --- a/src/widgets/networkproducerwidget.cpp +++ b/src/widgets/networkproducerwidget.cpp @@ -17,12 +17,13 @@ #include "networkproducerwidget.h" #include "ui_networkproducerwidget.h" + #include "mltcontroller.h" #include "util.h" -NetworkProducerWidget::NetworkProducerWidget(QWidget *parent) : - QWidget(parent), - ui(new Ui::NetworkProducerWidget) +NetworkProducerWidget::NetworkProducerWidget(QWidget *parent) + : QWidget(parent) + , ui(new Ui::NetworkProducerWidget) { ui->setupUi(this); Util::setColorsToHighlight(ui->label_2); diff --git a/src/widgets/networkproducerwidget.h b/src/widgets/networkproducerwidget.h index d05c05179d..740a21579b 100644 --- a/src/widgets/networkproducerwidget.h +++ b/src/widgets/networkproducerwidget.h @@ -19,9 +19,10 @@ #ifndef NETWORKPRODUCERWIDGET_H #define NETWORKPRODUCERWIDGET_H -#include #include "abstractproducerwidget.h" +#include + namespace Ui { class NetworkProducerWidget; } diff --git a/src/widgets/newprojectfolder.cpp b/src/widgets/newprojectfolder.cpp index 89d726a0b2..05ca636b23 100644 --- a/src/widgets/newprojectfolder.cpp +++ b/src/widgets/newprojectfolder.cpp @@ -17,25 +17,26 @@ #include "newprojectfolder.h" #include "ui_newprojectfolder.h" -#include "settings.h" -#include "mainwindow.h" -#include "util.h" + +#include "Logger.h" #include "dialogs/customprofiledialog.h" #include "dialogs/listselectiondialog.h" +#include "mainwindow.h" #include "qmltypes/qmlapplication.h" -#include +#include "settings.h" +#include "util.h" +#include #include #include #include -#include #include -#include +#include -NewProjectFolder::NewProjectFolder(QWidget *parent) : - QWidget(parent), - ui(new Ui::NewProjectFolder), - m_isOpening(false) +NewProjectFolder::NewProjectFolder(QWidget *parent) + : QWidget(parent) + , ui(new Ui::NewProjectFolder) + , m_isOpening(false) { ui->setupUi(this); setColors(); @@ -79,8 +80,11 @@ void NewProjectFolder::showEvent(QShowEvent *) m_profileGroup->addAction(ui->actionProfileAutomatic); m_videoModeMenu.addAction(ui->actionProfileAutomatic); } - MAIN.buildVideoModeMenu(&m_videoModeMenu, m_customProfileMenu, m_profileGroup, - ui->actionAddCustomProfile, ui->actionProfileRemove); + MAIN.buildVideoModeMenu(&m_videoModeMenu, + m_customProfileMenu, + m_profileGroup, + ui->actionAddCustomProfile, + ui->actionProfileRemove); // Check the current menu item. foreach (QAction *a, m_profileGroup->actions()) { @@ -122,7 +126,8 @@ void NewProjectFolder::updateRecentProjects() void NewProjectFolder::on_projectsFolderButton_clicked() { - QString dirName = QFileDialog::getExistingDirectory(this, tr("Projects Folder"), + QString dirName = QFileDialog::getExistingDirectory(this, + tr("Projects Folder"), Settings.projectsFolder(), Util::getFileDialogOptions()); if (!dirName.isEmpty()) { @@ -150,8 +155,13 @@ void NewProjectFolder::on_actionAddCustomProfile_triggered() QString name = dialog.profileName(); if (!name.isEmpty()) { ui->videoModeButton->setText(name); - MAIN.addCustomProfile(name, m_customProfileMenu, ui->actionProfileRemove, m_profileGroup); - MAIN.addCustomProfile(name, MAIN.customProfileMenu(), MAIN.actionProfileRemove(), + MAIN.addCustomProfile(name, + m_customProfileMenu, + ui->actionProfileRemove, + m_profileGroup); + MAIN.addCustomProfile(name, + MAIN.customProfileMenu(), + MAIN.actionProfileRemove(), MAIN.profileGroup()); } else if (m_profileGroup->checkedAction()) { ui->videoModeButton->setText(tr("Custom")); @@ -175,8 +185,13 @@ void NewProjectFolder::on_actionProfileRemove_triggered() // Show the dialog. if (dialog.exec() == QDialog::Accepted) { - MAIN.removeCustomProfiles(dialog.selection(), dir, m_customProfileMenu, ui->actionProfileRemove); - MAIN.removeCustomProfiles(dialog.selection(), dir, MAIN.customProfileMenu(), + MAIN.removeCustomProfiles(dialog.selection(), + dir, + m_customProfileMenu, + ui->actionProfileRemove); + MAIN.removeCustomProfiles(dialog.selection(), + dir, + MAIN.customProfileMenu(), MAIN.actionProfileRemove()); if (dialog.selection().indexOf(ui->videoModeButton->text()) >= 0) { ui->actionProfileAutomatic->setChecked(true); @@ -193,7 +208,8 @@ void NewProjectFolder::on_startButton_clicked() QString fileName = projectName; if (projectName.contains('/') || projectName.contains('\\')) { - QMessageBox::warning(this, ui->newProjectLabel->text(), + QMessageBox::warning(this, + ui->newProjectLabel->text(), tr("The project name cannot include a slash.")); ui->startButton->setDisabled(true); return; @@ -208,7 +224,8 @@ void NewProjectFolder::on_startButton_clicked() if (dir.cd(projectName)) { // Check if the project file exists. if (dir.exists(fileName)) { - QMessageBox::warning(this, ui->newProjectLabel->text(), + QMessageBox::warning(this, + ui->newProjectLabel->text(), tr("There is already a project with that name.\n" "Try again with a different name.")); return; @@ -216,10 +233,12 @@ void NewProjectFolder::on_startButton_clicked() } else { // Create the project folder if needed. if (!dir.mkpath(projectName)) { - QMessageBox::warning(this, ui->newProjectLabel->text(), + QMessageBox::warning(this, + ui->newProjectLabel->text(), tr("Unable to create folder %1\n" "Perhaps you do not have permission.\n" - "Try again with a different folder.").arg(projectName)); + "Try again with a different folder.") + .arg(projectName)); return; } dir.cd(projectName); @@ -280,8 +299,8 @@ void NewProjectFolder::setColors() void NewProjectFolder::setProjectFolderButtonText(const QString &text) { auto path = QDir::toNativeSeparators(text); - QString elidedText = ui->projectsFolderButton->fontMetrics().elidedText(path, Qt::ElideLeft, - ui->recentListView->width() / 1.5); + QString elidedText = ui->projectsFolderButton->fontMetrics() + .elidedText(path, Qt::ElideLeft, ui->recentListView->width() / 1.5); ui->projectsFolderButton->setText(elidedText); if (path != elidedText) ui->projectsFolderButton->setToolTip(path); @@ -303,7 +322,6 @@ void NewProjectFolder::on_recentListView_customContextMenuRequested(const QPoint } } - void NewProjectFolder::on_actionRecentRemove_triggered() { if (ui->recentListView->currentIndex().isValid()) { @@ -321,4 +339,3 @@ void NewProjectFolder::on_actionRecentRemove_triggered() } } } - diff --git a/src/widgets/newprojectfolder.h b/src/widgets/newprojectfolder.h index a9274f7905..cfceab13d3 100644 --- a/src/widgets/newprojectfolder.h +++ b/src/widgets/newprojectfolder.h @@ -18,11 +18,11 @@ #ifndef NEWPROJECTFOLDER_H #define NEWPROJECTFOLDER_H -#include +#include #include #include -#include #include +#include namespace Ui { class NewProjectFolder; diff --git a/src/widgets/noisewidget.cpp b/src/widgets/noisewidget.cpp index 3db61d2067..f927137d4b 100644 --- a/src/widgets/noisewidget.cpp +++ b/src/widgets/noisewidget.cpp @@ -16,14 +16,15 @@ * along with this program. If not, see . */ -#include "shotcut_mlt_properties.h" #include "noisewidget.h" #include "ui_noisewidget.h" + +#include "shotcut_mlt_properties.h" #include "util.h" -NoiseWidget::NoiseWidget(QWidget *parent) : - QWidget(parent), - ui(new Ui::NoiseWidget) +NoiseWidget::NoiseWidget(QWidget *parent) + : QWidget(parent) + , ui(new Ui::NoiseWidget) { ui->setupUi(this); Util::setColorsToHighlight(ui->nameLabel); diff --git a/src/widgets/noisewidget.h b/src/widgets/noisewidget.h index cf0d25a0af..1a13005227 100644 --- a/src/widgets/noisewidget.h +++ b/src/widgets/noisewidget.h @@ -19,9 +19,10 @@ #ifndef NOISEWIDGET_H #define NOISEWIDGET_H -#include #include "abstractproducerwidget.h" +#include + namespace Ui { class NoiseWidget; } diff --git a/src/widgets/openglvideowidget.cpp b/src/widgets/openglvideowidget.cpp index 35bbf2d3fc..d47b12aa4a 100644 --- a/src/widgets/openglvideowidget.cpp +++ b/src/widgets/openglvideowidget.cpp @@ -19,16 +19,26 @@ */ #include "openglvideowidget.h" -#include -#include + +#include "Logger.h" + +#include #include #include -#include +#include #ifdef QT_NO_DEBUG -#define check_error(fn) {} +#define check_error(fn) \ + {} #else -#define check_error(fn) { int err = fn->glGetError(); if (err != GL_NO_ERROR) { LOG_ERROR() << "GL error" << Qt::hex << err << Qt::dec << "at" << __FILE__ << ":" << __LINE__; } } +#define check_error(fn) \ + { \ + int err = fn->glGetError(); \ + if (err != GL_NO_ERROR) { \ + LOG_ERROR() << "GL error" << Qt::hex << err << Qt::dec << "at" << __FILE__ << ":" \ + << __LINE__; \ + } \ + } #endif OpenGLVideoWidget::OpenGLVideoWidget(QObject *parent) @@ -55,8 +65,9 @@ OpenGLVideoWidget::~OpenGLVideoWidget() void OpenGLVideoWidget::initialize() { LOG_DEBUG() << "begin"; - auto context = static_cast(quickWindow()->rendererInterface()->getResource( - quickWindow(), QSGRendererInterface::OpenGLContextResource)); + auto context = static_cast( + quickWindow()->rendererInterface()->getResource(quickWindow(), + QSGRendererInterface::OpenGLContextResource)); m_quickContext = context; if (!m_offscreenSurface.isValid()) { @@ -95,29 +106,30 @@ void OpenGLVideoWidget::createShader() " gl_Position = projection * modelView * vertex;" " coordinates = texCoord;" "}"); - m_shader->addShaderFromSourceCode(QOpenGLShader::Fragment, - "uniform sampler2D Ytex, Utex, Vtex;" - "uniform lowp int colorspace;" - "varying highp vec2 coordinates;" - "void main(void) {" - " mediump vec3 texel;" - " texel.r = texture2D(Ytex, coordinates).r - 16.0/255.0;" // Y - " texel.g = texture2D(Utex, coordinates).r - 128.0/255.0;" // U - " texel.b = texture2D(Vtex, coordinates).r - 128.0/255.0;" // V - " mediump mat3 coefficients;" - " if (colorspace == 601) {" - " coefficients = mat3(" - " 1.1643, 1.1643, 1.1643," // column 1 - " 0.0, -0.39173, 2.017," // column 2 - " 1.5958, -0.8129, 0.0);" // column 3 - " } else {" // ITU-R 709 - " coefficients = mat3(" - " 1.1643, 1.1643, 1.1643," // column 1 - " 0.0, -0.213, 2.112," // column 2 - " 1.793, -0.533, 0.0);" // column 3 - " }" - " gl_FragColor = vec4(coefficients * texel, 1.0);" - "}"); + m_shader + ->addShaderFromSourceCode(QOpenGLShader::Fragment, + "uniform sampler2D Ytex, Utex, Vtex;" + "uniform lowp int colorspace;" + "varying highp vec2 coordinates;" + "void main(void) {" + " mediump vec3 texel;" + " texel.r = texture2D(Ytex, coordinates).r - 16.0/255.0;" // Y + " texel.g = texture2D(Utex, coordinates).r - 128.0/255.0;" // U + " texel.b = texture2D(Vtex, coordinates).r - 128.0/255.0;" // V + " mediump mat3 coefficients;" + " if (colorspace == 601) {" + " coefficients = mat3(" + " 1.1643, 1.1643, 1.1643," // column 1 + " 0.0, -0.39173, 2.017," // column 2 + " 1.5958, -0.8129, 0.0);" // column 3 + " } else {" // ITU-R 709 + " coefficients = mat3(" + " 1.1643, 1.1643, 1.1643," // column 1 + " 0.0, -0.213, 2.112," // column 2 + " 1.793, -0.533, 0.0);" // column 3 + " }" + " gl_FragColor = vec4(coefficients * texel, 1.0);" + "}"); m_shader->link(); m_textureLocation[0] = m_shader->uniformLocation("Ytex"); m_textureLocation[1] = m_shader->uniformLocation("Utex"); @@ -146,7 +158,7 @@ static void uploadTextures(QOpenGLContext *context, const SharedFrame &frame, GL f->glGenTextures(3, texture); check_error(f); - f->glBindTexture (GL_TEXTURE_2D, texture[0]); + f->glBindTexture(GL_TEXTURE_2D, texture[0]); check_error(f); f->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); check_error(f); @@ -156,11 +168,18 @@ static void uploadTextures(QOpenGLContext *context, const SharedFrame &frame, GL check_error(f); f->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); check_error(f); - f->glTexImage2D (GL_TEXTURE_2D, 0, GL_LUMINANCE, width, height, 0, - GL_LUMINANCE, GL_UNSIGNED_BYTE, image); + f->glTexImage2D(GL_TEXTURE_2D, + 0, + GL_LUMINANCE, + width, + height, + 0, + GL_LUMINANCE, + GL_UNSIGNED_BYTE, + image); check_error(f); - f->glBindTexture (GL_TEXTURE_2D, texture[1]); + f->glBindTexture(GL_TEXTURE_2D, texture[1]); check_error(f); f->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); check_error(f); @@ -170,11 +189,18 @@ static void uploadTextures(QOpenGLContext *context, const SharedFrame &frame, GL check_error(f); f->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); check_error(f); - f->glTexImage2D (GL_TEXTURE_2D, 0, GL_LUMINANCE, width / 2, height / 2, 0, - GL_LUMINANCE, GL_UNSIGNED_BYTE, image + width * height); + f->glTexImage2D(GL_TEXTURE_2D, + 0, + GL_LUMINANCE, + width / 2, + height / 2, + 0, + GL_LUMINANCE, + GL_UNSIGNED_BYTE, + image + width * height); check_error(f); - f->glBindTexture (GL_TEXTURE_2D, texture[2]); + f->glBindTexture(GL_TEXTURE_2D, texture[2]); check_error(f); f->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); check_error(f); @@ -184,15 +210,23 @@ static void uploadTextures(QOpenGLContext *context, const SharedFrame &frame, GL check_error(f); f->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); check_error(f); - f->glTexImage2D (GL_TEXTURE_2D, 0, GL_LUMINANCE, width / 2, height / 2, 0, - GL_LUMINANCE, GL_UNSIGNED_BYTE, image + width * height + width / 2 * height / 2); + f->glTexImage2D(GL_TEXTURE_2D, + 0, + GL_LUMINANCE, + width / 2, + height / 2, + 0, + GL_LUMINANCE, + GL_UNSIGNED_BYTE, + image + width * height + width / 2 * height / 2); check_error(f); } void OpenGLVideoWidget::renderVideo() { - auto context = static_cast(quickWindow()->rendererInterface()->getResource( - quickWindow(), QSGRendererInterface::OpenGLContextResource)); + auto context = static_cast( + quickWindow()->rendererInterface()->getResource(quickWindow(), + QSGRendererInterface::OpenGLContextResource)); if (!m_quickContext) { LOG_ERROR() << "No quickContext"; return; @@ -337,4 +371,3 @@ void OpenGLVideoWidget::onFrameDisplayed(const SharedFrame &frame) } Mlt::VideoWidget::onFrameDisplayed(frame); } - diff --git a/src/widgets/openglvideowidget.h b/src/widgets/openglvideowidget.h index 10700efcbb..d214bceefe 100644 --- a/src/widgets/openglvideowidget.h +++ b/src/widgets/openglvideowidget.h @@ -20,11 +20,11 @@ #include "videowidget.h" +#include +#include +#include #include #include -#include -#include -#include class OpenGLVideoWidget : public Mlt::VideoWidget, protected QOpenGLFunctions { diff --git a/src/widgets/plasmawidget.cpp b/src/widgets/plasmawidget.cpp index 7c9c295721..3603b98f7d 100644 --- a/src/widgets/plasmawidget.cpp +++ b/src/widgets/plasmawidget.cpp @@ -16,21 +16,22 @@ * along with this program. If not, see . */ -#include "shotcut_mlt_properties.h" #include "plasmawidget.h" #include "ui_plasmawidget.h" + +#include "shotcut_mlt_properties.h" #include "util.h" static const char *kParamSpeed1 = "0"; static const char *kParamSpeed2 = "1"; static const char *kParamSpeed3 = "2"; static const char *kParamSpeed4 = "3"; -static const char *kParamMove1 = "4"; -static const char *kParamMove2 = "5"; +static const char *kParamMove1 = "4"; +static const char *kParamMove2 = "5"; -PlasmaWidget::PlasmaWidget(QWidget *parent) : - QWidget(parent), - ui(new Ui::PlasmaWidget) +PlasmaWidget::PlasmaWidget(QWidget *parent) + : QWidget(parent) + , ui(new Ui::PlasmaWidget) { ui->setupUi(this); Util::setColorsToHighlight(ui->nameLabel); diff --git a/src/widgets/plasmawidget.h b/src/widgets/plasmawidget.h index fbfc50bd79..876a265973 100644 --- a/src/widgets/plasmawidget.h +++ b/src/widgets/plasmawidget.h @@ -19,9 +19,10 @@ #ifndef PLASMAWIDGET_H #define PLASMAWIDGET_H -#include #include +#include + namespace Ui { class PlasmaWidget; } diff --git a/src/widgets/playlisticonview.cpp b/src/widgets/playlisticonview.cpp index da2f8a8de6..5f504861e8 100644 --- a/src/widgets/playlisticonview.cpp +++ b/src/widgets/playlisticonview.cpp @@ -17,16 +17,16 @@ #include "playlisticonview.h" +#include "Logger.h" #include "models/playlistmodel.h" #include "settings.h" -#include #include -#include #include -#include +#include #include #include +#include static const auto kPaddingPx = 10; static const auto kFilesSizeFactor = 1.5f; @@ -50,8 +50,10 @@ QRect PlaylistIconView::visualRect(const QModelIndex &index) const return QRect(); int row = index.row() / m_itemsPerRow; int col = index.row() % m_itemsPerRow; - return QRect(col * m_gridSize.width(), row * m_gridSize.height(), - m_gridSize.width(), m_gridSize.height()); + return QRect(col * m_gridSize.width(), + row * m_gridSize.height(), + m_gridSize.width(), + m_gridSize.height()); } void PlaylistIconView::rowsInserted(const QModelIndex &parent, int start, int end) @@ -66,7 +68,8 @@ void PlaylistIconView::rowsAboutToBeRemoved(const QModelIndex &parent, int start updateSizes(); } -void PlaylistIconView::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight, +void PlaylistIconView::dataChanged(const QModelIndex &topLeft, + const QModelIndex &bottomRight, const QVector &roles) { QAbstractItemView::dataChanged(topLeft, bottomRight, roles); @@ -184,8 +187,10 @@ void PlaylistIconView::paintEvent(QPaintEvent *) if (!idx.isValid()) break; - QRect itemRect(col * m_gridSize.width(), row * m_gridSize.height() - verticalScrollBar()->value(), - m_gridSize.width(), m_gridSize.height()); + QRect itemRect(col * m_gridSize.width(), + row * m_gridSize.height() - verticalScrollBar()->value(), + m_gridSize.width(), + m_gridSize.height()); if (itemRect.bottom() < 0 || itemRect.top() > this->height()) continue; @@ -196,7 +201,8 @@ void PlaylistIconView::paintEvent(QPaintEvent *) if (m_iconRole != Qt::DecorationRole) { // Files thumb = thumb.scaled(PlaylistModel::THUMBNAIL_WIDTH * kFilesSizeFactor, PlaylistModel::THUMBNAIL_HEIGHT * kFilesSizeFactor, - Qt::KeepAspectRatio, Qt::SmoothTransformation); + Qt::KeepAspectRatio, + Qt::SmoothTransformation); } QRect imageBoundingRect = itemRect; @@ -227,7 +233,8 @@ void PlaylistIconView::paintEvent(QPaintEvent *) } painter.drawImage(imageRect, thumb); - QStringList nameParts = proxyModel->mapToSource(idx).data(Qt::DisplayRole).toString().split('\n'); + QStringList nameParts + = proxyModel->mapToSource(idx).data(Qt::DisplayRole).toString().split('\n'); if (nameParts.size() > 1) { const auto indexPos = imageRect.topLeft() + QPoint(5, 15); painter.setFont(boldFont); @@ -238,17 +245,23 @@ void PlaylistIconView::paintEvent(QPaintEvent *) painter.setFont(oldFont); } painter.setPen(pal.color(QPalette::WindowText)); - painter.drawText(textRect, Qt::AlignCenter, - painter.fontMetrics().elidedText(nameParts.first(), Qt::ElideMiddle, textRect.width())); + painter.drawText(textRect, + Qt::AlignCenter, + painter.fontMetrics().elidedText(nameParts.first(), + Qt::ElideMiddle, + textRect.width())); if (!m_draggingOverPos.isNull() && itemRect.contains(m_draggingOverPos)) { - QAbstractItemView::DropIndicatorPosition dropPos = - position(m_draggingOverPos, itemRect, idx); + QAbstractItemView::DropIndicatorPosition dropPos = position(m_draggingOverPos, + itemRect, + idx); dragIndicator.setSize(QSize(4, itemRect.height())); if (dropPos == QAbstractItemView::AboveItem) - dragIndicator.moveTopLeft(itemRect.topLeft() - QPoint(dragIndicator.width() / 2, 0)); + dragIndicator.moveTopLeft(itemRect.topLeft() + - QPoint(dragIndicator.width() / 2, 0)); else - dragIndicator.moveTopLeft(itemRect.topRight() - QPoint(dragIndicator.width() / 2 - 1, 0)); + dragIndicator.moveTopLeft(itemRect.topRight() + - QPoint(dragIndicator.width() / 2 - 1, 0)); } } } @@ -288,8 +301,9 @@ void PlaylistIconView::dropEvent(QDropEvent *event) QModelIndex index = indexAt(event->position().toPoint()); QRect rectAtDropPoint = visualRect(index); - QAbstractItemView::DropIndicatorPosition dropPos = - position(event->position().toPoint(), rectAtDropPoint, index); + QAbstractItemView::DropIndicatorPosition dropPos = position(event->position().toPoint(), + rectAtDropPoint, + index); if (dropPos == QAbstractItemView::BelowItem) index = index.sibling(index.row() + 1, index.column()); @@ -331,7 +345,8 @@ void PlaylistIconView::keyReleaseEvent(QKeyEvent *event) } QAbstractItemView::DropIndicatorPosition PlaylistIconView::position(const QPoint &pos, - const QRect &rect, const QModelIndex &index) const + const QRect &rect, + const QModelIndex &index) const { Q_UNUSED(index); if (pos.x() < rect.center().x()) @@ -369,8 +384,9 @@ void PlaylistIconView::updateSizes() return; verticalScrollBar()->setRange(0, - m_gridSize.height() * model()->rowCount(rootIndex()) / m_itemsPerRow - height() + - m_gridSize.height()); + m_gridSize.height() * model()->rowCount(rootIndex()) + / m_itemsPerRow + - height() + m_gridSize.height()); viewport()->update(); } diff --git a/src/widgets/playlisticonview.h b/src/widgets/playlisticonview.h index f028acac0a..a662646ba0 100644 --- a/src/widgets/playlisticonview.h +++ b/src/widgets/playlisticonview.h @@ -31,11 +31,13 @@ class PlaylistIconView : public QAbstractItemView QRect visualRect(const QModelIndex &index) const Q_DECL_OVERRIDE; void scrollTo(const QModelIndex &index, ScrollHint hint = EnsureVisible) Q_DECL_OVERRIDE; QModelIndex indexAt(const QPoint &point) const Q_DECL_OVERRIDE; - QModelIndex moveCursor(CursorAction cursorAction, Qt::KeyboardModifiers modifiers) Q_DECL_OVERRIDE; + QModelIndex moveCursor(CursorAction cursorAction, + Qt::KeyboardModifiers modifiers) Q_DECL_OVERRIDE; int horizontalOffset() const Q_DECL_OVERRIDE; int verticalOffset() const Q_DECL_OVERRIDE; bool isIndexHidden(const QModelIndex &index) const Q_DECL_OVERRIDE; - void setSelection(const QRect &rect, QItemSelectionModel::SelectionFlags command) Q_DECL_OVERRIDE; + void setSelection(const QRect &rect, + QItemSelectionModel::SelectionFlags command) Q_DECL_OVERRIDE; QRegion visualRegionForSelection(const QItemSelection &selection) const Q_DECL_OVERRIDE; void currentChanged(const QModelIndex ¤t, const QModelIndex &previous) Q_DECL_OVERRIDE; @@ -51,7 +53,8 @@ class PlaylistIconView : public QAbstractItemView void rowsInserted(const QModelIndex &parent, int start, int end) Q_DECL_OVERRIDE; void rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end) Q_DECL_OVERRIDE; - void dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight, + void dataChanged(const QModelIndex &topLeft, + const QModelIndex &bottomRight, const QVector &roles = QVector()) Q_DECL_OVERRIDE; public slots: @@ -63,14 +66,15 @@ protected slots: private: int rowWidth() const; - QAbstractItemView::DropIndicatorPosition position(const QPoint &pos, const QRect &rect, + QAbstractItemView::DropIndicatorPosition position(const QPoint &pos, + const QRect &rect, const QModelIndex &index) const; QSize m_gridSize; QPoint m_draggingOverPos; int m_itemsPerRow; - bool m_isToggleSelect {false}; - bool m_isRangeSelect {false}; + bool m_isToggleSelect{false}; + bool m_isRangeSelect{false}; QModelIndex m_pendingSelect; int m_iconRole; }; diff --git a/src/widgets/playlistlistview.cpp b/src/widgets/playlistlistview.cpp index 7e2028e0b3..779abfbcf9 100644 --- a/src/widgets/playlistlistview.cpp +++ b/src/widgets/playlistlistview.cpp @@ -16,12 +16,12 @@ */ #include "playlistlistview.h" + #include PlaylistListView::PlaylistListView(QWidget *parent) : QListView(parent) -{ -} +{} void PlaylistListView::dropEvent(QDropEvent *event) { diff --git a/src/widgets/playlisttable.cpp b/src/widgets/playlisttable.cpp index 117a080e60..2b9ba43469 100644 --- a/src/widgets/playlisttable.cpp +++ b/src/widgets/playlisttable.cpp @@ -16,14 +16,14 @@ */ #include "playlisttable.h" -#include + +#include "Logger.h" + #include PlaylistTable::PlaylistTable(QWidget *parent) : QTableView(parent) -{ - -} +{} void PlaylistTable::keyPressEvent(QKeyEvent *event) { diff --git a/src/widgets/producerpreviewwidget.cpp b/src/widgets/producerpreviewwidget.cpp index e328e3ac2a..7d226df2ba 100644 --- a/src/widgets/producerpreviewwidget.cpp +++ b/src/widgets/producerpreviewwidget.cpp @@ -17,17 +17,17 @@ #include "widgets/producerpreviewwidget.h" -#include -#include "scrubbar.h" +#include "Logger.h" #include "mltcontroller.h" +#include "scrubbar.h" #include "settings.h" -#include #include #include #include #include #include +#include ProducerPreviewWidget::ProducerPreviewWidget(double dar, int width) : QWidget() @@ -39,7 +39,7 @@ ProducerPreviewWidget::ProducerPreviewWidget(double dar, int width) , m_isLooping(true) { LOG_DEBUG() << "begin"; - int height = lrint((double)width / dar); + int height = lrint((double) width / dar); height -= height % 2; if (height > width) { height = width; @@ -103,12 +103,12 @@ void ProducerPreviewWidget::start(const Mlt::Producer &producer) void ProducerPreviewWidget::ProducerPreviewWidget::stop(bool releaseProducer) { - if ( m_timerId ) { + if (m_timerId) { killTimer(m_timerId); m_timerId = 0; } m_generateFrames = false; - while ( m_queue.count() > 0 ) { + while (m_queue.count() > 0) { m_queue.pop(); } m_future.waitForFinished(); @@ -116,7 +116,7 @@ void ProducerPreviewWidget::ProducerPreviewWidget::stop(bool releaseProducer) m_producer = Mlt::Producer(); m_scrubber->setScale(0); } - while ( m_queue.count() > 0 ) { + while (m_queue.count() > 0) { m_queue.pop(); } m_seekTo = 0; @@ -157,14 +157,15 @@ void ProducerPreviewWidget::seeked(int position) void ProducerPreviewWidget::timerEvent(QTimerEvent *) { - if ( m_queue.count() > 0 ) { + if (m_queue.count() > 0) { QueueItem item = m_queue.pop(); m_imageLabel->setPixmap(item.pixmap); m_scrubber->onSeek(item.position); m_posLabel->setText(item.positionText); } else if (!m_generateFrames && m_timerId) { stop(false); - m_posLabel->setText(QStringLiteral("

%1

").arg(tr("Play"))); + m_posLabel->setText( + QStringLiteral("

%1

").arg(tr("Play"))); } } @@ -181,7 +182,7 @@ void ProducerPreviewWidget::generateFrame() if (m_seekTo != -1) { m_producer.seek(m_seekTo); m_seekTo = -1; - while ( m_queue.count() > 1 ) { + while (m_queue.count() > 1) { m_queue.pop(); } } @@ -192,17 +193,16 @@ void ProducerPreviewWidget::generateFrame() int height = m_previewSize.height(); mlt_image_format format = mlt_image_rgb; std::unique_ptr frame(m_producer.get_frame()); - frame->set( "rescale.interp", "bilinear" ); - uint8_t *mltImage = frame->get_image( format, width, height, 0 ); - QImage image( mltImage, width, height, QImage::Format_RGB888 ); - + frame->set("rescale.interp", "bilinear"); + uint8_t *mltImage = frame->get_image(format, width, height, 0); + QImage image(mltImage, width, height, QImage::Format_RGB888); // Send the image and status in the queue QueueItem item; item.pixmap.convertFromImage(image); item.position = position; - item.positionText = QString::fromLatin1(m_producer.frame_time()) + QStringLiteral(" / ") + - QString::fromLatin1(m_producer.get_length_time()); + item.positionText = QString::fromLatin1(m_producer.frame_time()) + QStringLiteral(" / ") + + QString::fromLatin1(m_producer.get_length_time()); m_queue.push(item); // Seek to the next frame (every other frame with repeat) diff --git a/src/widgets/producerpreviewwidget.h b/src/widgets/producerpreviewwidget.h index 14c40bf7d6..dfd15c2947 100644 --- a/src/widgets/producerpreviewwidget.h +++ b/src/widgets/producerpreviewwidget.h @@ -21,7 +21,6 @@ #include "dataqueue.h" #include - #include #include #include @@ -60,7 +59,8 @@ private slots: int m_seekTo; int m_timerId; Mlt::Producer m_producer; - struct QueueItem { + struct QueueItem + { QPixmap pixmap; int position; QString positionText; diff --git a/src/widgets/pulseaudiowidget.cpp b/src/widgets/pulseaudiowidget.cpp index d30b272499..516e9e8401 100644 --- a/src/widgets/pulseaudiowidget.cpp +++ b/src/widgets/pulseaudiowidget.cpp @@ -18,12 +18,13 @@ #include "pulseaudiowidget.h" #include "ui_pulseaudiowidget.h" -#include "util.h" + #include "shotcut_mlt_properties.h" +#include "util.h" -PulseAudioWidget::PulseAudioWidget(QWidget *parent) : - QWidget(parent), - ui(new Ui::PulseAudioWidget) +PulseAudioWidget::PulseAudioWidget(QWidget *parent) + : QWidget(parent) + , ui(new Ui::PulseAudioWidget) { ui->setupUi(this); Util::setColorsToHighlight(ui->label); diff --git a/src/widgets/pulseaudiowidget.h b/src/widgets/pulseaudiowidget.h index 7bbd68dae4..8fb7f761fc 100644 --- a/src/widgets/pulseaudiowidget.h +++ b/src/widgets/pulseaudiowidget.h @@ -19,9 +19,10 @@ #ifndef PULSEAUDIOWIDGET_H #define PULSEAUDIOWIDGET_H -#include #include "abstractproducerwidget.h" +#include + namespace Ui { class PulseAudioWidget; } diff --git a/src/widgets/resourcewidget.cpp b/src/widgets/resourcewidget.cpp index 3d8bd2f41b..40f2332b27 100644 --- a/src/widgets/resourcewidget.cpp +++ b/src/widgets/resourcewidget.cpp @@ -52,7 +52,7 @@ ResourceWidget::ResourceWidget(QWidget *parent) QHeaderView::Interactive); m_table->header()->setSectionResizeMode(ResourceModel::COLUMN_AUD_DESCRIPTION, QHeaderView::Interactive); - connect(m_table->selectionModel(), &QItemSelectionModel::currentChanged, this, [ = ]() { + connect(m_table->selectionModel(), &QItemSelectionModel::currentChanged, this, [=]() { m_table->selectionModel()->clearCurrentIndex(); }); vlayout->addWidget(m_table); @@ -60,9 +60,7 @@ ResourceWidget::ResourceWidget(QWidget *parent) setLayout(vlayout); } -ResourceWidget::~ResourceWidget() -{ -} +ResourceWidget::~ResourceWidget() {} void ResourceWidget::search(Mlt::Producer *producer) { @@ -80,7 +78,9 @@ void ResourceWidget::selectTroubleClips() for (int i = 0; i < m_model->rowCount(QModelIndex()); i++) { QModelIndex index = m_model->index(i, ResourceModel::COLUMN_INFO); if (!m_model->data(index, Qt::ToolTipRole).toString().isEmpty()) { - m_table->selectionModel()->select(index, QItemSelectionModel::Select | QItemSelectionModel::Rows); + m_table->selectionModel()->select(index, + QItemSelectionModel::Select + | QItemSelectionModel::Rows); } } } diff --git a/src/widgets/resourcewidget.h b/src/widgets/resourcewidget.h index 68be1e4934..3d1d75852c 100644 --- a/src/widgets/resourcewidget.h +++ b/src/widgets/resourcewidget.h @@ -19,7 +19,6 @@ #define RESOURCEWIDGET_H #include - #include class ResourceModel; diff --git a/src/widgets/scopes/audioloudnessscopewidget.cpp b/src/widgets/scopes/audioloudnessscopewidget.cpp index 2ebf5f7fa6..fb6160bba5 100644 --- a/src/widgets/scopes/audioloudnessscopewidget.cpp +++ b/src/widgets/scopes/audioloudnessscopewidget.cpp @@ -16,26 +16,29 @@ */ #include "audioloudnessscopewidget.h" -#include -#include -#include + +#include "Logger.h" +#include "mltcontroller.h" +#include "qmltypes/qmlutilities.h" +#include "settings.h" + +#include #include -#include -#include -#include -#include -#include #include +#include +#include +#include +#include +#include #include -#include +#include +#include + #include -#include "qmltypes/qmlutilities.h" -#include "mltcontroller.h" -#include "settings.h" -static double onedec( double in ) +static double onedec(double in) { - return round( in * 10.0 ) / 10.0; + return round(in * 10.0) / 10.0; } AudioLoudnessScopeWidget::AudioLoudnessScopeWidget() @@ -44,7 +47,7 @@ AudioLoudnessScopeWidget::AudioLoudnessScopeWidget() , m_peak(-100) , m_true_peak(-100) , m_newData(false) - , m_orientation((Qt::Orientation) - 1) + , m_orientation((Qt::Orientation) -1) , m_qview(new QQuickWidget(QmlUtilities::sharedEngine(), this)) , m_timeLabel(new QLabel(this)) { @@ -101,8 +104,8 @@ AudioLoudnessScopeWidget::AudioLoudnessScopeWidget() // Add config button QToolButton *configButton = new QToolButton(this); configButton->setToolTip(tr("Configure Graphs")); - configButton->setIcon(QIcon::fromTheme("show-menu", - QIcon(":/icons/oxygen/32x32/actions/show-menu.png"))); + configButton->setIcon( + QIcon::fromTheme("show-menu", QIcon(":/icons/oxygen/32x32/actions/show-menu.png"))); configButton->setPopupMode(QToolButton::InstantPopup); configButton->setMenu(configMenu); hlayout->addWidget(configButton); @@ -151,10 +154,10 @@ void AudioLoudnessScopeWidget::refreshScope(const QSize & /*size*/, bool /*full* Mlt::Frame mFrame = sFrame.clone(true, false, false); m_loudnessFilter->process(mFrame); mFrame.get_audio(format, frequency, channels, samples); - if ( m_peak < m_loudnessFilter->get_double("peak") ) { + if (m_peak < m_loudnessFilter->get_double("peak")) { m_peak = m_loudnessFilter->get_double("peak"); } - if ( m_true_peak < m_loudnessFilter->get_double("true_peak") ) { + if (m_true_peak < m_loudnessFilter->get_double("true_peak")) { m_true_peak = m_loudnessFilter->get_double("true_peak"); } m_newData = true; @@ -164,8 +167,10 @@ void AudioLoudnessScopeWidget::refreshScope(const QSize & /*size*/, bool /*full* // Update the time with every frame. QString time = m_loudnessFilter->get_time("frames_processed"); - QMetaObject::invokeMethod(m_timeLabel, "setText", Qt::QueuedConnection, Q_ARG(const QString &, - time)); + QMetaObject::invokeMethod(m_timeLabel, + "setText", + Qt::QueuedConnection, + Q_ARG(const QString &, time)); } QString AudioLoudnessScopeWidget::getTitle() @@ -185,12 +190,18 @@ void AudioLoudnessScopeWidget::setOrientation(Qt::Orientation orientation, bool // Calculate the minimum width int x = 0; const int meterWidth = 54; - if (Settings.loudnessScopeShowMeter("momentary")) x += meterWidth; - if (Settings.loudnessScopeShowMeter("shortterm")) x += meterWidth; - if (Settings.loudnessScopeShowMeter("integrated")) x += meterWidth; - if (Settings.loudnessScopeShowMeter("range")) x += meterWidth; - if (Settings.loudnessScopeShowMeter("peak")) x += meterWidth; - if (Settings.loudnessScopeShowMeter("truepeak")) x += meterWidth; + if (Settings.loudnessScopeShowMeter("momentary")) + x += meterWidth; + if (Settings.loudnessScopeShowMeter("shortterm")) + x += meterWidth; + if (Settings.loudnessScopeShowMeter("integrated")) + x += meterWidth; + if (Settings.loudnessScopeShowMeter("range")) + x += meterWidth; + if (Settings.loudnessScopeShowMeter("peak")) + x += meterWidth; + if (Settings.loudnessScopeShowMeter("truepeak")) + x += meterWidth; x = std::max(x, 200); setMinimumSize(x, 250); setMaximumSize(x, 600); @@ -198,12 +209,18 @@ void AudioLoudnessScopeWidget::setOrientation(Qt::Orientation orientation, bool // Calculate the minimum height int y = 32; const int meterHeight = 47; - if (Settings.loudnessScopeShowMeter("momentary")) y += meterHeight; - if (Settings.loudnessScopeShowMeter("shortterm")) y += meterHeight; - if (Settings.loudnessScopeShowMeter("integrated")) y += meterHeight; - if (Settings.loudnessScopeShowMeter("range")) y += meterHeight; - if (Settings.loudnessScopeShowMeter("peak")) y += meterHeight; - if (Settings.loudnessScopeShowMeter("truepeak")) y += meterHeight; + if (Settings.loudnessScopeShowMeter("momentary")) + y += meterHeight; + if (Settings.loudnessScopeShowMeter("shortterm")) + y += meterHeight; + if (Settings.loudnessScopeShowMeter("integrated")) + y += meterHeight; + if (Settings.loudnessScopeShowMeter("range")) + y += meterHeight; + if (Settings.loudnessScopeShowMeter("peak")) + y += meterHeight; + if (Settings.loudnessScopeShowMeter("truepeak")) + y += meterHeight; y = std::max(y, 80); setMinimumSize(250, y); setMaximumSize(600, y); @@ -217,7 +234,7 @@ void AudioLoudnessScopeWidget::setOrientation(Qt::Orientation orientation, bool void AudioLoudnessScopeWidget::onResetButtonClicked() { m_loudnessFilter->set("reset", 1); - m_timeLabel->setText( "00:00:00:00" ); + m_timeLabel->setText("00:00:00:00"); setOrientation(m_orientation, true); resetQview(); } @@ -272,18 +289,22 @@ void AudioLoudnessScopeWidget::onTruePeakToggled(bool checked) void AudioLoudnessScopeWidget::updateMeters(void) { - if (!m_newData || !m_qview->rootObject()) return; - if (m_loudnessFilter->get_int("calc_program") ) - m_qview->rootObject()->setProperty("integrated", onedec(m_loudnessFilter->get_double("program"))); - if (m_loudnessFilter->get_int("calc_shortterm") ) - m_qview->rootObject()->setProperty("shortterm", onedec(m_loudnessFilter->get_double("shortterm"))); - if (m_loudnessFilter->get_int("calc_momentary") ) - m_qview->rootObject()->setProperty("momentary", onedec(m_loudnessFilter->get_double("momentary"))); - if (m_loudnessFilter->get_int("calc_range") ) + if (!m_newData || !m_qview->rootObject()) + return; + if (m_loudnessFilter->get_int("calc_program")) + m_qview->rootObject()->setProperty("integrated", + onedec(m_loudnessFilter->get_double("program"))); + if (m_loudnessFilter->get_int("calc_shortterm")) + m_qview->rootObject()->setProperty("shortterm", + onedec(m_loudnessFilter->get_double("shortterm"))); + if (m_loudnessFilter->get_int("calc_momentary")) + m_qview->rootObject()->setProperty("momentary", + onedec(m_loudnessFilter->get_double("momentary"))); + if (m_loudnessFilter->get_int("calc_range")) m_qview->rootObject()->setProperty("range", onedec(m_loudnessFilter->get_double("range"))); - if (m_loudnessFilter->get_int("calc_peak") ) + if (m_loudnessFilter->get_int("calc_peak")) m_qview->rootObject()->setProperty("peak", onedec(m_peak)); - if (m_loudnessFilter->get_int("calc_true_peak") ) + if (m_loudnessFilter->get_int("calc_true_peak")) m_qview->rootObject()->setProperty("truePeak", onedec(m_true_peak)); m_peak = -100; m_true_peak = -100; @@ -301,8 +322,8 @@ bool AudioLoudnessScopeWidget::event(QEvent *event) void AudioLoudnessScopeWidget::resetQview() { - LOG_DEBUG() << "begin" << "isSceneGraphInitialized" << - m_qview->quickWindow()->isSceneGraphInitialized(); + LOG_DEBUG() << "begin" + << "isSceneGraphInitialized" << m_qview->quickWindow()->isSceneGraphInitialized(); if (!m_qview->quickWindow()->isSceneGraphInitialized()) { return; } @@ -328,10 +349,13 @@ void AudioLoudnessScopeWidget::resetQview() m_qview->rootObject()->setProperty("orientation", m_orientation); m_qview->rootObject()->setProperty("enableIntegrated", Settings.loudnessScopeShowMeter("integrated")); - m_qview->rootObject()->setProperty("enableShortterm", Settings.loudnessScopeShowMeter("shortterm")); - m_qview->rootObject()->setProperty("enableMomentary", Settings.loudnessScopeShowMeter("momentary")); + m_qview->rootObject()->setProperty("enableShortterm", + Settings.loudnessScopeShowMeter("shortterm")); + m_qview->rootObject()->setProperty("enableMomentary", + Settings.loudnessScopeShowMeter("momentary")); m_qview->rootObject()->setProperty("enableRange", Settings.loudnessScopeShowMeter("range")); m_qview->rootObject()->setProperty("enablePeak", Settings.loudnessScopeShowMeter("peak")); - m_qview->rootObject()->setProperty("enableTruePeak", Settings.loudnessScopeShowMeter("truepeak")); + m_qview->rootObject()->setProperty("enableTruePeak", + Settings.loudnessScopeShowMeter("truepeak")); } } diff --git a/src/widgets/scopes/audioloudnessscopewidget.h b/src/widgets/scopes/audioloudnessscopewidget.h index f76666475d..8e89cab6f3 100644 --- a/src/widgets/scopes/audioloudnessscopewidget.h +++ b/src/widgets/scopes/audioloudnessscopewidget.h @@ -20,10 +20,11 @@ #define AUDIOLOUDNESSSCOPEWIDGET_H #include "scopewidget.h" -#include + +#include #include +#include #include -#include class QQuickWidget; class QLabel; diff --git a/src/widgets/scopes/audiopeakmeterscopewidget.cpp b/src/widgets/scopes/audiopeakmeterscopewidget.cpp index aa553a658b..23c70baed8 100644 --- a/src/widgets/scopes/audiopeakmeterscopewidget.cpp +++ b/src/widgets/scopes/audiopeakmeterscopewidget.cpp @@ -16,21 +16,24 @@ */ #include "audiopeakmeterscopewidget.h" + +#include "Logger.h" +#include "mltcontroller.h" #include "settings.h" -#include -#include #include "widgets/audiometerwidget.h" -#include "mltcontroller.h" + +#include + #include // log10() AudioPeakMeterScopeWidget::AudioPeakMeterScopeWidget() : ScopeWidget("AudioPeakMeter") , m_audioMeter(0) - , m_orientation((Qt::Orientation) - 1) - , m_channels( Settings.playerAudioChannels() ) + , m_orientation((Qt::Orientation) -1) + , m_channels(Settings.playerAudioChannels()) { LOG_DEBUG() << "begin"; - qRegisterMetaType< QVector >("QVector"); + qRegisterMetaType>("QVector"); setAutoFillBackground(true); QVBoxLayout *vlayout = new QVBoxLayout(this); vlayout->setContentsMargins(4, 4, 4, 4); @@ -53,21 +56,26 @@ void AudioPeakMeterScopeWidget::refreshScope(const QSize & /*size*/, bool /*full int samples = sFrame.get_audio_samples(); QVector levels; const int16_t *audio = sFrame.get_audio(); - for ( int c = 0; c < channels; c++ ) { + for (int c = 0; c < channels; c++) { int16_t peak = 0; const int16_t *p = audio + c; - for ( int s = 0; s < samples; s++ ) { - int16_t sample = abs(*p ); - if (sample > peak) peak = sample; + for (int s = 0; s < samples; s++) { + int16_t sample = abs(*p); + if (sample > peak) + peak = sample; p += channels; } if (peak == 0) { levels << -100.0; } else { - levels << 20 * log10((double)peak / (double)std::numeric_limits::max()); + levels << 20 + * log10((double) peak + / (double) std::numeric_limits::max()); } } - QMetaObject::invokeMethod(m_audioMeter, "showAudio", Qt::QueuedConnection, + QMetaObject::invokeMethod(m_audioMeter, + "showAudio", + Qt::QueuedConnection, Q_ARG(const QVector &, levels)); if (m_channels != channels) { m_channels = channels; @@ -95,16 +103,16 @@ void AudioPeakMeterScopeWidget::reconfigureMeter() { // Set the bar labels. QStringList channelLabels; - if (m_channels == 2 ) + if (m_channels == 2) channelLabels << tr("L") << tr("R"); - if (m_channels == 4 ) + if (m_channels == 4) channelLabels << tr("L") << tr("R") << tr("Ls") << tr("Rs"); - else if (m_channels == 6 ) + else if (m_channels == 6) channelLabels << tr("L") << tr("R") << tr("C") << tr("LF") << tr("Ls") << tr("Rs"); m_audioMeter->setChannelLabels(channelLabels); // Set the size constraints. - int spaceNeeded = ( m_channels * 16 ) + 17; + int spaceNeeded = (m_channels * 16) + 17; if (m_orientation == Qt::Vertical) { m_audioMeter->setMinimumSize(spaceNeeded, 250); setMinimumSize(spaceNeeded + 8, 258); diff --git a/src/widgets/scopes/audiopeakmeterscopewidget.h b/src/widgets/scopes/audiopeakmeterscopewidget.h index 9305cd5579..075f2edbca 100644 --- a/src/widgets/scopes/audiopeakmeterscopewidget.h +++ b/src/widgets/scopes/audiopeakmeterscopewidget.h @@ -19,8 +19,9 @@ #define AUDIOPEAKMETERSCOPEWIDGET_H #include "scopewidget.h" -#include + #include +#include #include class AudioMeterWidget; diff --git a/src/widgets/scopes/audiospectrumscopewidget.cpp b/src/widgets/scopes/audiospectrumscopewidget.cpp index f1d27e56fb..0fb15524c4 100644 --- a/src/widgets/scopes/audiospectrumscopewidget.cpp +++ b/src/widgets/scopes/audiospectrumscopewidget.cpp @@ -17,17 +17,21 @@ */ #include "audiospectrumscopewidget.h" + +#include "Logger.h" #include "widgets/audiometerwidget.h" -#include + +#include #include -#include #include -#include +#include + #include static const int WINDOW_SIZE = 8000; // 6 Hz FFT bins at 48kHz -struct band { +struct band +{ float low; // Low frequency float center; // Center frequency float high; // High frequency @@ -36,51 +40,51 @@ struct band { // Preferred frequencies from ISO R 266-1997 / ANSI S1.6-1984 static const band BAND_TAB[] = { -// Low Preferred High Band -// Freq Center Freq Label Num - { 1.12, 1.25, 1.41, "1.25" }, // 1 - { 1.41, 1.60, 1.78, "1.6" }, // 2 - { 1.78, 2.00, 2.24, "2.0" }, // 3 - { 2.24, 2.50, 2.82, "2.5" }, // 4 - { 2.82, 3.15, 3.55, "3.15" }, // 5 - { 3.55, 4.00, 4.44, "4.0" }, // 6 - { 4.44, 5.00, 6.00, "5.0" }, // 7 - { 6.00, 6.30, 7.00, "6.3" }, // 8 - { 7.00, 8.00, 9.00, "8.0" }, // 9 - { 9.00, 10.00, 11.00, "10" }, // 10 - { 11.00, 12.50, 14.00, "12.5" }, // 11 - { 14.00, 16.00, 18.00, "16" }, // 12 - { 18.00, 20.00, 22.00, "20" }, // 13 - First in audible range - { 22.00, 25.00, 28.00, "25" }, // 14 - { 28.00, 31.50, 35.00, "31" }, // 15 - { 35.00, 40.00, 45.00, "40" }, // 16 - { 45.00, 50.00, 56.00, "50" }, // 17 - { 56.00, 63.00, 71.00, "63" }, // 18 - { 71.00, 80.00, 90.00, "80" }, // 19 - { 90.00, 100.00, 112.00, "100" }, // 20 - { 112.00, 125.00, 140.00, "125" }, // 21 - { 140.00, 160.00, 179.00, "160" }, // 22 - { 179.00, 200.00, 224.00, "200" }, // 23 - { 224.00, 250.00, 282.00, "250" }, // 24 - { 282.00, 315.00, 353.00, "315" }, // 25 - { 353.00, 400.00, 484.00, "400" }, // 26 - { 484.00, 500.00, 560.00, "500" }, // 27 - { 560.00, 630.00, 706.00, "630" }, // 28 - { 706.00, 800.00, 897.00, "800" }, // 29 - { 897.00, 1000.00, 1121.00, "1k" }, // 30 - { 1121.00, 1250.00, 1401.00, "1.3k" }, // 31 - { 1401.00, 1600.00, 1794.00, "1.6k" }, // 32 - { 1794.00, 2000.00, 2242.00, "2k" }, // 33 - { 2242.00, 2500.00, 2803.00, "2.5k" }, // 34 - { 2803.00, 3150.00, 3531.00, "3.2k" }, // 35 - { 3531.00, 4000.00, 4484.00, "4k" }, // 36 - { 4484.00, 5000.00, 5605.00, "5k" }, // 37 - { 5605.00, 6300.00, 7062.00, "6.3k" }, // 38 - { 7062.00, 8000.00, 8908.00, "8k" }, // 39 - { 8908.00, 10000.00, 11210.00, "10k" }, // 40 - { 11210.00, 12500.00, 14012.00, "13k" }, // 41 - { 14012.00, 16000.00, 17936.00, "16k" }, // 42 - { 17936.00, 20000.00, 22421.00, "20k" }, // 43 - Last in audible range + // Low Preferred High Band + // Freq Center Freq Label Num + {1.12, 1.25, 1.41, "1.25"}, // 1 + {1.41, 1.60, 1.78, "1.6"}, // 2 + {1.78, 2.00, 2.24, "2.0"}, // 3 + {2.24, 2.50, 2.82, "2.5"}, // 4 + {2.82, 3.15, 3.55, "3.15"}, // 5 + {3.55, 4.00, 4.44, "4.0"}, // 6 + {4.44, 5.00, 6.00, "5.0"}, // 7 + {6.00, 6.30, 7.00, "6.3"}, // 8 + {7.00, 8.00, 9.00, "8.0"}, // 9 + {9.00, 10.00, 11.00, "10"}, // 10 + {11.00, 12.50, 14.00, "12.5"}, // 11 + {14.00, 16.00, 18.00, "16"}, // 12 + {18.00, 20.00, 22.00, "20"}, // 13 - First in audible range + {22.00, 25.00, 28.00, "25"}, // 14 + {28.00, 31.50, 35.00, "31"}, // 15 + {35.00, 40.00, 45.00, "40"}, // 16 + {45.00, 50.00, 56.00, "50"}, // 17 + {56.00, 63.00, 71.00, "63"}, // 18 + {71.00, 80.00, 90.00, "80"}, // 19 + {90.00, 100.00, 112.00, "100"}, // 20 + {112.00, 125.00, 140.00, "125"}, // 21 + {140.00, 160.00, 179.00, "160"}, // 22 + {179.00, 200.00, 224.00, "200"}, // 23 + {224.00, 250.00, 282.00, "250"}, // 24 + {282.00, 315.00, 353.00, "315"}, // 25 + {353.00, 400.00, 484.00, "400"}, // 26 + {484.00, 500.00, 560.00, "500"}, // 27 + {560.00, 630.00, 706.00, "630"}, // 28 + {706.00, 800.00, 897.00, "800"}, // 29 + {897.00, 1000.00, 1121.00, "1k"}, // 30 + {1121.00, 1250.00, 1401.00, "1.3k"}, // 31 + {1401.00, 1600.00, 1794.00, "1.6k"}, // 32 + {1794.00, 2000.00, 2242.00, "2k"}, // 33 + {2242.00, 2500.00, 2803.00, "2.5k"}, // 34 + {2803.00, 3150.00, 3531.00, "3.2k"}, // 35 + {3531.00, 4000.00, 4484.00, "4k"}, // 36 + {4484.00, 5000.00, 5605.00, "5k"}, // 37 + {5605.00, 6300.00, 7062.00, "6.3k"}, // 38 + {7062.00, 8000.00, 8908.00, "8k"}, // 39 + {8908.00, 10000.00, 11210.00, "10k"}, // 40 + {11210.00, 12500.00, 14012.00, "13k"}, // 41 + {14012.00, 16000.00, 17936.00, "16k"}, // 42 + {17936.00, 20000.00, 22421.00, "20k"}, // 43 - Last in audible range }; static const int FIRST_AUDIBLE_BAND_INDEX = 12; @@ -94,7 +98,7 @@ AudioSpectrumScopeWidget::AudioSpectrumScopeWidget() LOG_DEBUG() << "begin"; // Setup this widget - qRegisterMetaType< QVector >("QVector"); + qRegisterMetaType>("QVector"); // Create the FFT filter Mlt::Profile profile; @@ -135,7 +139,7 @@ AudioSpectrumScopeWidget::~AudioSpectrumScopeWidget() void AudioSpectrumScopeWidget::processSpectrum() { QVector bands(AUDIBLE_BAND_COUNT); - float *bins = (float *)m_filter->get_data("bins"); + float *bins = (float *) m_filter->get_data("bins"); int bin_count = m_filter->get_int("bin_count"); double bin_width = m_filter->get_double("bin_width"); @@ -144,7 +148,7 @@ void AudioSpectrumScopeWidget::processSpectrum() for (int bin = 0; bin < bin_count; bin++) { // Loop through all the FFT bins and align bin frequencies with // band frequencies. - double F = bin_width * (double)bin; + double F = bin_width * (double) bin; if (!firstBandFound) { // Skip bins that come before the first band. @@ -162,7 +166,7 @@ void AudioSpectrumScopeWidget::processSpectrum() break; } bands[band] = bins[bin]; - } else if (bands[band] < bins[bin] ) { + } else if (bands[band] < bins[bin]) { // Pick the highest bin level within this band to represent the // whole band. bands[band] = bins[bin]; @@ -173,12 +177,14 @@ void AudioSpectrumScopeWidget::processSpectrum() // band. Convert to dB. for (band = 0; band < bands.size(); band++) { double mag = bands[band]; - double dB = mag > 0.0 ? 20 * log10( mag ) : -1000.0; + double dB = mag > 0.0 ? 20 * log10(mag) : -1000.0; bands[band] = dB; } // Update the audio signal widget - QMetaObject::invokeMethod(m_audioMeter, "showAudio", Qt::QueuedConnection, + QMetaObject::invokeMethod(m_audioMeter, + "showAudio", + Qt::QueuedConnection, Q_ARG(const QVector &, bands)); } @@ -196,7 +202,7 @@ void AudioSpectrumScopeWidget::refreshScope(const QSize & /*size*/, bool /*full* int samples = sFrame.get_audio_samples(); Mlt::Frame mFrame = sFrame.clone(true, false, false); m_filter->process(mFrame); - mFrame.get_audio( format, frequency, channels, samples ); + mFrame.get_audio(format, frequency, channels, samples); refresh = true; } } diff --git a/src/widgets/scopes/audiospectrumscopewidget.h b/src/widgets/scopes/audiospectrumscopewidget.h index 62db76bd72..02b43b148d 100644 --- a/src/widgets/scopes/audiospectrumscopewidget.h +++ b/src/widgets/scopes/audiospectrumscopewidget.h @@ -19,8 +19,8 @@ #ifndef AUDIOSPECTRUMSCOPEWIDGET_H #define AUDIOSPECTRUMSCOPEWIDGET_H - #include "scopewidget.h" + #include class AudioMeterWidget; diff --git a/src/widgets/scopes/audiosurroundscopewidget.cpp b/src/widgets/scopes/audiosurroundscopewidget.cpp index 784deb14b8..49ba83e39e 100644 --- a/src/widgets/scopes/audiosurroundscopewidget.cpp +++ b/src/widgets/scopes/audiosurroundscopewidget.cpp @@ -17,12 +17,12 @@ #include "audiosurroundscopewidget.h" -#include +#include "Logger.h" #include "settings.h" #include "widgets/iecscale.h" -#include #include +#include #include @@ -63,9 +63,7 @@ AudioSurroundScopeWidget::AudioSurroundScopeWidget() LOG_DEBUG() << "end"; } -AudioSurroundScopeWidget::~AudioSurroundScopeWidget() -{ -} +AudioSurroundScopeWidget::~AudioSurroundScopeWidget() {} QString AudioSurroundScopeWidget::getTitle() { @@ -98,19 +96,20 @@ void AudioSurroundScopeWidget::refreshScope(const QSize &size, bool full) int samples = m_frame.get_audio_samples(); QVector levels; const int16_t *audio = m_frame.get_audio(); - for ( int c = 0; c < channels; c++ ) { + for (int c = 0; c < channels; c++) { int16_t peak = 0; const int16_t *p = audio + c; - for ( int s = 0; s < samples; s++ ) { - int16_t sample = abs(*p ); - if (sample > peak) peak = sample; + for (int s = 0; s < samples; s++) { + int16_t sample = abs(*p); + if (sample > peak) + peak = sample; p += channels; } double levelDb = 0.0; if (peak == 0) { levelDb = -100.0; } else { - levelDb = 20 * log10((double)peak / (double)std::numeric_limits::max()); + levelDb = 20 * log10((double) peak / (double) std::numeric_limits::max()); } levels << IEC_ScaleMax(levelDb, 0); } @@ -129,7 +128,7 @@ void AudioSurroundScopeWidget::refreshScope(const QSize &size, bool full) insideRect.setY(insideRect.x()); insideRect.setWidth(rect.width() - 2 * insideRect.x()); insideRect.setHeight(insideRect.width()); - qreal maxCornerLength = sqrt( 2 * pow(insideRect.width() / 2, 2) ); + qreal maxCornerLength = sqrt(2 * pow(insideRect.width() / 2, 2)); // Draw the inside lines from center pen.setColor(palette().color(QPalette::Active, QPalette::Highlight)); @@ -137,7 +136,7 @@ void AudioSurroundScopeWidget::refreshScope(const QSize &size, bool full) p.setPen(pen); // Left if (channels > 1) { - qreal magnitude = levels[0] * maxCornerLength; + qreal magnitude = levels[0] * maxCornerLength; QPointF point = vectorToPoint(135, magnitude); point = mapFromCenter(point, center); p.drawLine(center, point); @@ -158,7 +157,7 @@ void AudioSurroundScopeWidget::refreshScope(const QSize &size, bool full) } // Right if (channels > 1) { - qreal magnitude = levels[1] * maxCornerLength; + qreal magnitude = levels[1] * maxCornerLength; QPointF point = vectorToPoint(45, magnitude); point = mapFromCenter(point, center); p.drawLine(center, point); diff --git a/src/widgets/scopes/audiosurroundscopewidget.h b/src/widgets/scopes/audiosurroundscopewidget.h index 0edbe29eb5..253d62e3fb 100644 --- a/src/widgets/scopes/audiosurroundscopewidget.h +++ b/src/widgets/scopes/audiosurroundscopewidget.h @@ -20,8 +20,8 @@ #include "scopewidget.h" -#include #include +#include class AudioSurroundScopeWidget Q_DECL_FINAL : public ScopeWidget { @@ -33,7 +33,6 @@ class AudioSurroundScopeWidget Q_DECL_FINAL : public ScopeWidget QString getTitle() Q_DECL_OVERRIDE; private: - // Called in scope thread void refreshScope(const QSize &size, bool full) Q_DECL_OVERRIDE; void drawGraticule(QPainter &p, qreal lineWidth); diff --git a/src/widgets/scopes/audiovectorscopewidget.cpp b/src/widgets/scopes/audiovectorscopewidget.cpp index d66ff225d0..39b46fdc9d 100644 --- a/src/widgets/scopes/audiovectorscopewidget.cpp +++ b/src/widgets/scopes/audiovectorscopewidget.cpp @@ -17,7 +17,7 @@ #include "audiovectorscopewidget.h" -#include +#include "Logger.h" #include "settings.h" #include @@ -25,6 +25,7 @@ #include #include #include + #include static const qreal MAX_AMPLITUDE = 32768.0; @@ -78,9 +79,7 @@ AudioVectorScopeWidget::AudioVectorScopeWidget() LOG_DEBUG() << "end"; } -AudioVectorScopeWidget::~AudioVectorScopeWidget() -{ -} +AudioVectorScopeWidget::~AudioVectorScopeWidget() {} void AudioVectorScopeWidget::setComboBoxOptions() { @@ -180,7 +179,7 @@ void AudioVectorScopeWidget::refreshScope(const QSize &size, bool full) int samples = m_frame.get_audio_samples(); // Find the max value to be used for scaling - const int16_t *a = (int16_t *)m_frame.get_audio(); + const int16_t *a = (int16_t *) m_frame.get_audio(); int16_t maxSampleValue = 0; for (int s = 0; s < samples; s++) { if (std::abs(a[c1]) > maxSampleValue) { @@ -192,11 +191,11 @@ void AudioVectorScopeWidget::refreshScope(const QSize &size, bool full) a += channels; } - a = (int16_t *)m_frame.get_audio(); + a = (int16_t *) m_frame.get_audio(); qreal maxPoint = sqrt(side * side + side * side) / 4; qreal scaleFactor = maxPoint / maxSampleValue; for (int s = 0; s < samples; s++) { - QPointF point((qreal)a[c1] * scaleFactor, (qreal)a[c2] * scaleFactor); + QPointF point((qreal) a[c1] * scaleFactor, (qreal) a[c2] * scaleFactor); p.drawPoint(point); a += channels; } diff --git a/src/widgets/scopes/audiovectorscopewidget.h b/src/widgets/scopes/audiovectorscopewidget.h index 712110a029..0f0203b472 100644 --- a/src/widgets/scopes/audiovectorscopewidget.h +++ b/src/widgets/scopes/audiovectorscopewidget.h @@ -20,8 +20,8 @@ #include "scopewidget.h" -#include #include +#include class QComboBox; class QLabel; @@ -57,7 +57,6 @@ class AudioVectorScopeWidget Q_DECL_FINAL : public ScopeWidget QImage m_displayImg; int m_c1Index; int m_c2Index; - }; #endif // AUDIOVECTORSCOPEWIDGET_H diff --git a/src/widgets/scopes/audiowaveformscopewidget.cpp b/src/widgets/scopes/audiowaveformscopewidget.cpp index 623500845b..30d1dbc85c 100644 --- a/src/widgets/scopes/audiowaveformscopewidget.cpp +++ b/src/widgets/scopes/audiowaveformscopewidget.cpp @@ -17,12 +17,13 @@ #include "audiowaveformscopewidget.h" -#include +#include "Logger.h" #include #include #include #include + #include static const qreal MAX_AMPLITUDE = 32768.0; @@ -68,9 +69,7 @@ AudioWaveformScopeWidget::AudioWaveformScopeWidget() LOG_DEBUG() << "end"; } -AudioWaveformScopeWidget::~AudioWaveformScopeWidget() -{ -} +AudioWaveformScopeWidget::~AudioWaveformScopeWidget() {} void AudioWaveformScopeWidget::refreshScope(const QSize &size, bool full) { @@ -111,9 +110,9 @@ void AudioWaveformScopeWidget::refreshScope(const QSize &size, bool full) if (m_frame.is_valid() && m_frame.get_audio_samples() > 0) { int samples = m_frame.get_audio_samples(); - int16_t *audio = (int16_t *)m_frame.get_audio(); + int16_t *audio = (int16_t *) m_frame.get_audio(); int waveAmplitude = graphHeight(size, m_channels, m_graphTopPadding) / 2; - qreal scaleFactor = (qreal)waveAmplitude / (qreal)MAX_AMPLITUDE; + qreal scaleFactor = (qreal) waveAmplitude / (qreal) MAX_AMPLITUDE; for (int c = 0; c < m_channels; c++) { p.save(); @@ -133,7 +132,7 @@ void AudioWaveformScopeWidget::refreshScope(const QSize &size, bool full) qreal min = value; for (int i = 0; i <= samples; i++) { - int x = ( i * size.width() ) / samples; + int x = (i * size.width()) / samples; if (x != lastX) { // The min and max have been determined for the previous x // So draw the line @@ -155,8 +154,10 @@ void AudioWaveformScopeWidget::refreshScope(const QSize &size, bool full) min = tmp; } - if (value > max) max = value; - if (value < min) min = value; + if (value > max) + max = value; + if (value < min) + min = value; q += m_channels; value = *q * -1; } @@ -179,7 +180,7 @@ void AudioWaveformScopeWidget::createGrid(const QSize &size) QFontMetrics fm(font); QString zeroLabel = tr("0"); QString infinityLabel = tr("-inf"); - QRect textRect = fm.tightBoundingRect( infinityLabel ); + QRect textRect = fm.tightBoundingRect(infinityLabel); int labelHeight = textRect.height(); m_graphTopPadding = fm.height(); m_graphLeftPadding = textRect.width() + 6; @@ -201,7 +202,7 @@ void AudioWaveformScopeWidget::createGrid(const QSize &size) y = graphBottomY(size, c, m_channels, m_graphTopPadding); textLoc.setY(y + labelHeight / 2); textLoc.setX((m_graphLeftPadding - fm.horizontalAdvance(zeroLabel)) / 2); - p.drawText( textLoc, zeroLabel ); + p.drawText(textLoc, zeroLabel); lineBegin.setY(y); lineEnd.setY(y); p.drawLine(lineBegin, lineEnd); @@ -209,7 +210,7 @@ void AudioWaveformScopeWidget::createGrid(const QSize &size) y = graphCenterY(size, c, m_channels, m_graphTopPadding); textLoc.setY(y + labelHeight / 2); textLoc.setX((m_graphLeftPadding - fm.horizontalAdvance(infinityLabel)) / 2); - p.drawText( textLoc, infinityLabel ); + p.drawText(textLoc, infinityLabel); lineBegin.setY(y); lineEnd.setY(y); p.drawLine(lineBegin, lineEnd); @@ -217,7 +218,7 @@ void AudioWaveformScopeWidget::createGrid(const QSize &size) y = graphTopY(size, c, m_channels, m_graphTopPadding); textLoc.setY(y + labelHeight / 2); textLoc.setX((m_graphLeftPadding - fm.horizontalAdvance(zeroLabel)) / 2); - p.drawText( textLoc, zeroLabel ); + p.drawText(textLoc, zeroLabel); lineBegin.setY(y); lineEnd.setY(y); p.drawLine(lineBegin, lineEnd); @@ -250,25 +251,30 @@ void AudioWaveformScopeWidget::paintEvent(QPaintEvent *) void AudioWaveformScopeWidget::mouseMoveEvent(QMouseEvent *event) { QMutexLocker locker(&m_mutex); - if (!m_frame.is_valid()) return; + if (!m_frame.is_valid()) + return; int channels = m_frame.get_audio_channels(); int samples = m_frame.get_audio_samples(); - int16_t *audio = (int16_t *)m_frame.get_audio(); - if (samples < 10 || channels < 1) return; + int16_t *audio = (int16_t *) m_frame.get_audio(); + if (samples < 10 || channels < 1) + return; - qreal position = (qreal)event->pos().x() / (qreal)width(); - int sample = (qreal)samples * position; + qreal position = (qreal) event->pos().x() / (qreal) width(); + int sample = (qreal) samples * position; QString text = tr("Sample: %1\n").arg(sample + 1); for (int c = 0; c < channels; c++) { const int16_t *q = audio + (channels * sample) + c; - qreal scaledValue = (qreal) * q / MAX_AMPLITUDE; + qreal scaledValue = (qreal) *q / MAX_AMPLITUDE; qreal dbValue = 20 * log(fabs(scaledValue)); - if (dbValue < 0.01 && dbValue > -0.01) dbValue = 0.0; - text += tr("Ch: %1: %2 (%3 dBFS)").arg(c + 1).arg(scaledValue, 0, 'f', 2) - .arg(dbValue, 0, 'f', 2); - if ( c != channels - 1 ) { + if (dbValue < 0.01 && dbValue > -0.01) + dbValue = 0.0; + text += tr("Ch: %1: %2 (%3 dBFS)") + .arg(c + 1) + .arg(scaledValue, 0, 'f', 2) + .arg(dbValue, 0, 'f', 2); + if (c != channels - 1) { text += "\n"; } } diff --git a/src/widgets/scopes/audiowaveformscopewidget.h b/src/widgets/scopes/audiowaveformscopewidget.h index 35f418cdef..28628e7e16 100644 --- a/src/widgets/scopes/audiowaveformscopewidget.h +++ b/src/widgets/scopes/audiowaveformscopewidget.h @@ -19,8 +19,9 @@ #define AUDIOWAVEFORMSCOPEWIDGET_H #include "scopewidget.h" -#include + #include +#include class AudioWaveformScopeWidget Q_DECL_FINAL : public ScopeWidget { diff --git a/src/widgets/scopes/scopewidget.cpp b/src/widgets/scopes/scopewidget.cpp index a7cca391da..2a433a2272 100644 --- a/src/widgets/scopes/scopewidget.cpp +++ b/src/widgets/scopes/scopewidget.cpp @@ -16,7 +16,9 @@ */ #include "scopewidget.h" -#include + +#include "Logger.h" + #include ScopeWidget::ScopeWidget(const QString &name) @@ -33,9 +35,7 @@ ScopeWidget::ScopeWidget(const QString &name) LOG_DEBUG() << "end"; } -ScopeWidget::~ScopeWidget() -{ -} +ScopeWidget::~ScopeWidget() {} void ScopeWidget::onNewFrame(const SharedFrame &frame) { diff --git a/src/widgets/scopes/scopewidget.h b/src/widgets/scopes/scopewidget.h index 0eff4d3a99..bd20abbb1b 100644 --- a/src/widgets/scopes/scopewidget.h +++ b/src/widgets/scopes/scopewidget.h @@ -18,14 +18,15 @@ #ifndef SCOPEWIDGET_H #define SCOPEWIDGET_H -#include -#include -#include -#include +#include "Logger.h" +#include "dataqueue.h" +#include "sharedframe.h" + #include #include -#include "sharedframe.h" -#include "dataqueue.h" +#include +#include +#include /*! \class ScopeWidget @@ -79,7 +80,7 @@ class ScopeWidget : public QWidget Sets the preferred orientation on the scope. This virtual function may be reimplemented by subclasses. */ - virtual void setOrientation(Qt::Orientation) {}; + virtual void setOrientation(Qt::Orientation){}; public slots: //! Provides a new frame to the scope. Should be called by the application. diff --git a/src/widgets/scopes/videohistogramscopewidget.cpp b/src/widgets/scopes/videohistogramscopewidget.cpp index cc2fea0790..45e49db38d 100644 --- a/src/widgets/scopes/videohistogramscopewidget.cpp +++ b/src/widgets/scopes/videohistogramscopewidget.cpp @@ -16,7 +16,9 @@ */ #include "videohistogramscopewidget.h" -#include + +#include "Logger.h" + #include #include #include @@ -120,8 +122,12 @@ void VideoHistogramScopeWidget::paintEvent(QPaintEvent *) p.end(); } -void VideoHistogramScopeWidget::drawHistogram(QPainter &p, QString title, QColor color, - QColor outline, QVector &bins, QRect rect) +void VideoHistogramScopeWidget::drawHistogram(QPainter &p, + QString title, + QColor color, + QColor outline, + QVector &bins, + QRect rect) { unsigned int binCount = bins.size(); unsigned int *pBins = bins.data(); @@ -154,7 +160,8 @@ void VideoHistogramScopeWidget::drawHistogram(QPainter &p, QString title, QColor p.drawText(textpad, rect.y() + fm.height() + textpad, text); // Nothing to draw. - if (maxLevel < minValue) return; + if (maxLevel < minValue) + return; // Set histogram background gradient. QLinearGradient gradient = QLinearGradient(rect.left(), rect.top(), rect.right(), rect.top()); @@ -171,17 +178,17 @@ void VideoHistogramScopeWidget::drawHistogram(QPainter &p, QString title, QColor p.setPen(pen); QPainterPath histPath; - histPath.moveTo( rect.bottomLeft() ); - qreal lineWidth = (qreal)rect.width() / 256.0; + histPath.moveTo(rect.bottomLeft()); + qreal lineWidth = (qreal) rect.width() / 256.0; for (unsigned int i = 0; i < binCount; i++) { - qreal xPos = (qreal)rect.width() * i / binCount; - qreal yPos = (qreal)rect.bottom() - (histHeight * pBins[i] / maxLevel); + qreal xPos = (qreal) rect.width() * i / binCount; + qreal yPos = (qreal) rect.bottom() - (histHeight * pBins[i] / maxLevel); histPath.lineTo(xPos, yPos); histPath.lineTo(xPos + lineWidth, yPos); } - histPath.lineTo( rect.bottomRight() ); + histPath.lineTo(rect.bottomRight()); histPath.closeSubpath(); - p.drawPath( histPath ); + p.drawPath(histPath); } void VideoHistogramScopeWidget::mouseMoveEvent(QMouseEvent *event) diff --git a/src/widgets/scopes/videohistogramscopewidget.h b/src/widgets/scopes/videohistogramscopewidget.h index 9e76d35ed6..aa256d8e28 100644 --- a/src/widgets/scopes/videohistogramscopewidget.h +++ b/src/widgets/scopes/videohistogramscopewidget.h @@ -19,6 +19,7 @@ #define VIDEOHISTOGRAMSCOPEWIDGET_H #include "scopewidget.h" + #include #include @@ -33,8 +34,12 @@ class VideoHistogramScopeWidget Q_DECL_FINAL : public ScopeWidget private: void refreshScope(const QSize &size, bool full) Q_DECL_OVERRIDE; void paintEvent(QPaintEvent *) Q_DECL_OVERRIDE; - void drawHistogram(QPainter &p, QString title, QColor color, QColor outline, - QVector &bins, QRect rect); + void drawHistogram(QPainter &p, + QString title, + QColor color, + QColor outline, + QVector &bins, + QRect rect); void mouseMoveEvent(QMouseEvent *event) Q_DECL_OVERRIDE; SharedFrame m_frame; diff --git a/src/widgets/scopes/videorgbparadescopewidget.cpp b/src/widgets/scopes/videorgbparadescopewidget.cpp index f662d276f7..92c4cd3885 100644 --- a/src/widgets/scopes/videorgbparadescopewidget.cpp +++ b/src/widgets/scopes/videorgbparadescopewidget.cpp @@ -16,6 +16,7 @@ */ #include "videorgbparadescopewidget.h" + #include #include #include @@ -34,7 +35,6 @@ VideoRgbParadeScopeWidget::VideoRgbParadeScopeWidget() LOG_DEBUG() << "end"; } - void VideoRgbParadeScopeWidget::refreshScope(const QSize &size, bool full) { Q_UNUSED(size) @@ -53,7 +53,7 @@ void VideoRgbParadeScopeWidget::refreshScope(const QSize &size, bool full) m_renderImg = QImage(imgWidth, 256, QImage::QImage::Format_RGBX8888); } - QColor bgColor( 0, 0, 0, 0xff ); + QColor bgColor(0, 0, 0, 0xff); m_renderImg.fill(bgColor); const uint8_t *src = m_frame.get_image(mlt_image_rgb); @@ -85,8 +85,9 @@ void VideoRgbParadeScopeWidget::refreshScope(const QSize &size, bool full) } } - QImage scaledImage = m_renderImg.scaled(size, Qt::IgnoreAspectRatio, - Qt::SmoothTransformation).convertToFormat(QImage::Format_RGB32); + QImage scaledImage = m_renderImg + .scaled(size, Qt::IgnoreAspectRatio, Qt::SmoothTransformation) + .convertToFormat(QImage::Format_RGB32); m_mutex.lock(); m_displayImg.swap(m_renderImg); @@ -130,15 +131,15 @@ void VideoRgbParadeScopeWidget::paintEvent(QPaintEvent *) p.drawLine(QPointF(0, y), QPointF(width(), y)); p.drawText(textpad, textheight + textpad, tr("255")); // 191 - y = (qreal)height() - 191.0 / 255.0 * (qreal)height(); + y = (qreal) height() - 191.0 / 255.0 * (qreal) height(); p.drawLine(0, y, width(), y); p.drawText(textpad, height() / 4 - textpad, tr("191")); // 127 - y = (qreal)height() - 127.0 / 255.0 * (qreal)height(); + y = (qreal) height() - 127.0 / 255.0 * (qreal) height(); p.drawLine(0, y, width(), y); p.drawText(textpad, height() / 2 - textpad, tr("127")); // 64 - y = (qreal)height() - 64.0 / 255.0 * (qreal)height(); + y = (qreal) height() - 64.0 / 255.0 * (qreal) height(); p.drawLine(0, y, width(), y); p.drawText(textpad, height() * 3 / 4 - textpad, tr("64")); // 0 @@ -151,7 +152,7 @@ void VideoRgbParadeScopeWidget::mouseMoveEvent(QMouseEvent *event) { QString text; qreal channelWidth = width() / 3.0; - qreal channelX = event->pos().x() % (int)channelWidth; + qreal channelX = event->pos().x() % (int) channelWidth; QString channelLabel; if (event->pos().x() < channelWidth) { channelLabel = tr("Red"); @@ -169,9 +170,9 @@ void VideoRgbParadeScopeWidget::mouseMoveEvent(QMouseEvent *event) if (frameWidth != 0) { int pixel = frameWidth * channelX / channelWidth; - text = tr("Channel: %1\nPixel: %2\nValue: %3").arg(channelLabel).arg(pixel).arg(value); + text = tr("Channel: %1\nPixel: %2\nValue: %3").arg(channelLabel).arg(pixel).arg(value); } else { - text = tr("Channel: %1\nValue: %2").arg(channelLabel).arg(value); + text = tr("Channel: %1\nValue: %2").arg(channelLabel).arg(value); } QToolTip::showText(event->globalPosition().toPoint(), text); } diff --git a/src/widgets/scopes/videorgbparadescopewidget.h b/src/widgets/scopes/videorgbparadescopewidget.h index d40eefc0c5..d62fb4114f 100644 --- a/src/widgets/scopes/videorgbparadescopewidget.h +++ b/src/widgets/scopes/videorgbparadescopewidget.h @@ -19,8 +19,9 @@ #define VIDEORGBPARADESCOPEWIDGET_H #include "scopewidget.h" -#include + #include +#include class VideoRgbParadeScopeWidget Q_DECL_FINAL : public ScopeWidget { diff --git a/src/widgets/scopes/videorgbwaveformscopewidget.cpp b/src/widgets/scopes/videorgbwaveformscopewidget.cpp index b7c0e26f16..6e6bf2f74c 100644 --- a/src/widgets/scopes/videorgbwaveformscopewidget.cpp +++ b/src/widgets/scopes/videorgbwaveformscopewidget.cpp @@ -16,6 +16,7 @@ */ #include "videorgbwaveformscopewidget.h" + #include #include #include @@ -34,7 +35,6 @@ VideoRgbWaveformScopeWidget::VideoRgbWaveformScopeWidget() LOG_DEBUG() << "end"; } - void VideoRgbWaveformScopeWidget::refreshScope(const QSize &size, bool full) { Q_UNUSED(size) @@ -52,7 +52,7 @@ void VideoRgbWaveformScopeWidget::refreshScope(const QSize &size, bool full) m_renderImg = QImage(width, 256, QImage::QImage::Format_RGBX8888); } - QColor bgColor( 0, 0, 0, 0xff ); + QColor bgColor(0, 0, 0, 0xff); m_renderImg.fill(bgColor); const uint8_t *src = m_frame.get_image(mlt_image_rgb); @@ -81,8 +81,9 @@ void VideoRgbWaveformScopeWidget::refreshScope(const QSize &size, bool full) } } - QImage scaledImage = m_renderImg.scaled(size, Qt::IgnoreAspectRatio, - Qt::SmoothTransformation).convertToFormat(QImage::Format_RGB32); + QImage scaledImage = m_renderImg + .scaled(size, Qt::IgnoreAspectRatio, Qt::SmoothTransformation) + .convertToFormat(QImage::Format_RGB32); m_mutex.lock(); m_displayImg.swap(m_renderImg); @@ -126,15 +127,15 @@ void VideoRgbWaveformScopeWidget::paintEvent(QPaintEvent *) p.drawLine(QPointF(0, y), QPointF(width(), y)); p.drawText(textpad, textheight + textpad, tr("255")); // 191 - y = (qreal)height() - 191.0 / 255.0 * (qreal)height(); + y = (qreal) height() - 191.0 / 255.0 * (qreal) height(); p.drawLine(0, y, width(), y); p.drawText(textpad, height() / 4 - textpad, tr("191")); // 127 - y = (qreal)height() - 127.0 / 255.0 * (qreal)height(); + y = (qreal) height() - 127.0 / 255.0 * (qreal) height(); p.drawLine(0, y, width(), y); p.drawText(textpad, height() / 2 - textpad, tr("127")); // 64 - y = (qreal)height() - 64.0 / 255.0 * (qreal)height(); + y = (qreal) height() - 64.0 / 255.0 * (qreal) height(); p.drawLine(0, y, width(), y); p.drawText(textpad, height() * 3 / 4 - textpad, tr("64")); // 0 @@ -155,9 +156,9 @@ void VideoRgbWaveformScopeWidget::mouseMoveEvent(QMouseEvent *event) if (frameWidth != 0) { int pixel = frameWidth * event->pos().x() / width(); - text = tr("Pixel: %1\nValue: %2").arg(pixel).arg(value); + text = tr("Pixel: %1\nValue: %2").arg(pixel).arg(value); } else { - text = tr("Value: %1").arg(value); + text = tr("Value: %1").arg(value); } QToolTip::showText(event->globalPosition().toPoint(), text); } diff --git a/src/widgets/scopes/videorgbwaveformscopewidget.h b/src/widgets/scopes/videorgbwaveformscopewidget.h index 3d96ea3c98..5470e88703 100644 --- a/src/widgets/scopes/videorgbwaveformscopewidget.h +++ b/src/widgets/scopes/videorgbwaveformscopewidget.h @@ -19,8 +19,9 @@ #define VIDEORGBWAVEFORMSCOPEWIDGET_H #include "scopewidget.h" -#include + #include +#include class VideoRgbWaveformScopeWidget Q_DECL_FINAL : public ScopeWidget { diff --git a/src/widgets/scopes/videovectorscopewidget.cpp b/src/widgets/scopes/videovectorscopewidget.cpp index 893ed33b2c..ab4e53643d 100644 --- a/src/widgets/scopes/videovectorscopewidget.cpp +++ b/src/widgets/scopes/videovectorscopewidget.cpp @@ -17,14 +17,14 @@ #include "videovectorscopewidget.h" +#include "Logger.h" #include "mltcontroller.h" #include "qmltypes/qmlprofile.h" -#include #include #include -#include #include +#include static const QColor LINE_COLOR = {255, 255, 255, 127}; @@ -61,7 +61,6 @@ void VideoVectorScopeWidget::refreshScope(const QSize &size, bool full) QSize squareSize = QSize(side, side); if (m_graticuleImg.size() != size || m_profileChanged) { - m_graticuleImg = QImage(squareSize, QImage::Format_RGB32); m_graticuleImg.fill(0); QPainter p(&m_graticuleImg); @@ -172,8 +171,8 @@ void VideoVectorScopeWidget::drawGraticuleLines(QPainter &p, qreal lineWidth) void VideoVectorScopeWidget::drawSkinToneLine(QPainter &p, qreal lineWidth) { // Draw a skin tone line 33 degrees counter clockwise from the red vector - qreal angle = qRadiansToDegrees(qAtan((qreal)(m_points[RED_100].x() - 128) / (qreal)( - m_points[RED_100].y() - 128))); + qreal angle = qRadiansToDegrees( + qAtan((qreal) (m_points[RED_100].x() - 128) / (qreal) (m_points[RED_100].y() - 128))); angle += 270; angle -= 33; @@ -191,14 +190,14 @@ void VideoVectorScopeWidget::drawSkinToneLine(QPainter &p, qreal lineWidth) p.drawLine(skinToneLine); } -void VideoVectorScopeWidget::drawGraticuleMark(QPainter &p, const QPoint &point, QColor color, - qreal lineWidth, qreal LineLength) +void VideoVectorScopeWidget::drawGraticuleMark( + QPainter &p, const QPoint &point, QColor color, qreal lineWidth, qreal LineLength) { color = color.darker(100); p.setBrush(color); p.setPen(QPen(color, lineWidth, Qt::SolidLine, Qt::RoundCap)); QLineF angleline; - qreal angle = qAtan((qreal)(point.x() - 128) / (qreal)(point.y() - 128)); + qreal angle = qAtan((qreal) (point.x() - 128) / (qreal) (point.y() - 128)); angle = qRadiansToDegrees(angle); angleline.setP1(point); angleline.setLength(LineLength / 2); @@ -237,11 +236,11 @@ void VideoVectorScopeWidget::mouseMoveEvent(QMouseEvent *event) QToolTip::hideText(); return; } - qreal realX = (qreal)event->pos().x() - ((qreal)width() - squareRect.width()) / 2; - qreal realY = (qreal)event->pos().y() - ((qreal)height() - squareRect.height()) / 2; + qreal realX = (qreal) event->pos().x() - ((qreal) width() - squareRect.width()) / 2; + qreal realY = (qreal) event->pos().y() - ((qreal) height() - squareRect.height()) / 2; qreal u = realX * 255.0 / squareRect.width(); qreal v = (squareRect.height() - realY) * 255.0 / squareRect.height(); - QString text = tr("U: %1\nV: %2").arg(qRound(u)).arg(qRound(v)); + QString text = tr("U: %1\nV: %2").arg(qRound(u)).arg(qRound(v)); QToolTip::showText(event->globalPosition().toPoint(), text); } @@ -265,32 +264,32 @@ void VideoVectorScopeWidget::profileChanged() m_mutex.lock(); switch (MLT.profile().colorspace()) { case 601: - m_points[BLUE_75] = QPoint(212, 114); - m_points[CYAN_75] = QPoint(156, 44); - m_points[GREEN_75] = QPoint(72, 58); - m_points[YELLOW_75] = QPoint(44, 142); - m_points[RED_75] = QPoint(100, 212); - m_points[MAGENTA_75] = QPoint(184, 198); - m_points[BLUE_100] = QPoint(240, 110); - m_points[CYAN_100] = QPoint(166, 16); - m_points[GREEN_100] = QPoint(54, 34); - m_points[YELLOW_100] = QPoint(16, 146); - m_points[RED_100] = QPoint(90, 240); + m_points[BLUE_75] = QPoint(212, 114); + m_points[CYAN_75] = QPoint(156, 44); + m_points[GREEN_75] = QPoint(72, 58); + m_points[YELLOW_75] = QPoint(44, 142); + m_points[RED_75] = QPoint(100, 212); + m_points[MAGENTA_75] = QPoint(184, 198); + m_points[BLUE_100] = QPoint(240, 110); + m_points[CYAN_100] = QPoint(166, 16); + m_points[GREEN_100] = QPoint(54, 34); + m_points[YELLOW_100] = QPoint(16, 146); + m_points[RED_100] = QPoint(90, 240); m_points[MAGENTA_100] = QPoint(202, 222); break; default: case 709: - m_points[BLUE_75] = QPoint(212, 120); - m_points[CYAN_75] = QPoint(147, 44); - m_points[GREEN_75] = QPoint(63, 52); - m_points[YELLOW_75] = QPoint(44, 136); - m_points[RED_75] = QPoint(109, 212); - m_points[MAGENTA_75] = QPoint(193, 204); - m_points[BLUE_100] = QPoint(240, 118); - m_points[CYAN_100] = QPoint(154, 16); - m_points[GREEN_100] = QPoint(42, 26); - m_points[YELLOW_100] = QPoint(16, 138); - m_points[RED_100] = QPoint(102, 240); + m_points[BLUE_75] = QPoint(212, 120); + m_points[CYAN_75] = QPoint(147, 44); + m_points[GREEN_75] = QPoint(63, 52); + m_points[YELLOW_75] = QPoint(44, 136); + m_points[RED_75] = QPoint(109, 212); + m_points[MAGENTA_75] = QPoint(193, 204); + m_points[BLUE_100] = QPoint(240, 118); + m_points[CYAN_100] = QPoint(154, 16); + m_points[GREEN_100] = QPoint(42, 26); + m_points[YELLOW_100] = QPoint(16, 138); + m_points[RED_100] = QPoint(102, 240); m_points[MAGENTA_100] = QPoint(214, 230); break; } diff --git a/src/widgets/scopes/videovectorscopewidget.h b/src/widgets/scopes/videovectorscopewidget.h index ae778f238f..1541cc73db 100644 --- a/src/widgets/scopes/videovectorscopewidget.h +++ b/src/widgets/scopes/videovectorscopewidget.h @@ -19,8 +19,9 @@ #define VIDEOVECTORSCOPEWIDGET_H #include "scopewidget.h" -#include + #include +#include class VideoVectorScopeWidget Q_DECL_FINAL : public ScopeWidget { @@ -52,8 +53,8 @@ class VideoVectorScopeWidget Q_DECL_FINAL : public ScopeWidget void refreshScope(const QSize &size, bool full) Q_DECL_OVERRIDE; void drawGraticuleLines(QPainter &p, qreal lineWidth); void drawSkinToneLine(QPainter &p, qreal lineWidth); - void drawGraticuleMark(QPainter &p, const QPoint &point, QColor color, qreal lineWidth, - qreal LineLength); + void drawGraticuleMark( + QPainter &p, const QPoint &point, QColor color, qreal lineWidth, qreal LineLength); // Called in UI thread void paintEvent(QPaintEvent *) Q_DECL_OVERRIDE; diff --git a/src/widgets/scopes/videowaveformscopewidget.cpp b/src/widgets/scopes/videowaveformscopewidget.cpp index 6fb379f7ce..81faaa9bfc 100644 --- a/src/widgets/scopes/videowaveformscopewidget.cpp +++ b/src/widgets/scopes/videowaveformscopewidget.cpp @@ -16,7 +16,9 @@ */ #include "videowaveformscopewidget.h" -#include + +#include "Logger.h" + #include #include #include @@ -25,7 +27,6 @@ static const qreal IRE0 = 16; static const qreal IRE100 = 235; static const QColor TEXT_COLOR = {255, 255, 255, 127}; - VideoWaveformScopeWidget::VideoWaveformScopeWidget() : ScopeWidget("VideoWaveform") , m_frame() @@ -38,7 +39,6 @@ VideoWaveformScopeWidget::VideoWaveformScopeWidget() LOG_DEBUG() << "end"; } - void VideoWaveformScopeWidget::refreshScope(const QSize &size, bool full) { Q_UNUSED(size) @@ -56,7 +56,7 @@ void VideoWaveformScopeWidget::refreshScope(const QSize &size, bool full) m_renderImg = QImage(width, 256, QImage::Format_RGBX8888); } - QColor bgColor( 0, 0, 0, 0xff ); + QColor bgColor(0, 0, 0, 0xff); m_renderImg.fill(bgColor); const uint8_t *src = m_frame.get_image(mlt_image_yuv420p); @@ -71,12 +71,13 @@ void VideoWaveformScopeWidget::refreshScope(const QSize &size, bool full) dst[dIndex + 1] += 0x0f; dst[dIndex + 2] += 0x0f; } - src ++; + src++; } } - QImage scaledImage = m_renderImg.scaled(size, Qt::IgnoreAspectRatio, - Qt::SmoothTransformation).convertToFormat(QImage::Format_RGB32); + QImage scaledImage = m_renderImg + .scaled(size, Qt::IgnoreAspectRatio, Qt::SmoothTransformation) + .convertToFormat(QImage::Format_RGB32); m_mutex.lock(); m_displayImg.swap(scaledImage); @@ -140,9 +141,9 @@ void VideoWaveformScopeWidget::mouseMoveEvent(QMouseEvent *event) if (frameWidth != 0) { int pixel = frameWidth * event->pos().x() / width(); - text = tr("Pixel: %1\nIRE: %2").arg(pixel).arg(ire); + text = tr("Pixel: %1\nIRE: %2").arg(pixel).arg(ire); } else { - text = tr("IRE: %1").arg(ire); + text = tr("IRE: %1").arg(ire); } QToolTip::showText(event->globalPosition().toPoint(), text); } diff --git a/src/widgets/scopes/videowaveformscopewidget.h b/src/widgets/scopes/videowaveformscopewidget.h index b668c40550..bbffc46f04 100644 --- a/src/widgets/scopes/videowaveformscopewidget.h +++ b/src/widgets/scopes/videowaveformscopewidget.h @@ -19,8 +19,9 @@ #define VIDEOWAVEFORMSCOPEWIDGET_H #include "scopewidget.h" -#include + #include +#include class VideoWaveformScopeWidget Q_DECL_FINAL : public ScopeWidget { diff --git a/src/widgets/scopes/videozoomscopewidget.cpp b/src/widgets/scopes/videozoomscopewidget.cpp index 75e68191d4..1c690fdc84 100644 --- a/src/widgets/scopes/videozoomscopewidget.cpp +++ b/src/widgets/scopes/videozoomscopewidget.cpp @@ -20,11 +20,11 @@ #include "videowidget.h" #include "videozoomwidget.h" +#include +#include #include #include #include -#include -#include #include @@ -35,7 +35,7 @@ QWidget *getSeparator() separator->setGeometry(0, 0, 300, 300); separator->setMinimumSize(1, 1); QPalette pal = separator->palette(); -// pal.setColor(QPalette::Background, pal.color(QPalette::WindowText)); + // pal.setColor(QPalette::Background, pal.color(QPalette::WindowText)); separator->setAutoFillBackground(true); separator->setPalette(pal); return separator; @@ -48,18 +48,18 @@ QRect getPlayerBoundingRect(Mlt::VideoWidget *videoWidget) // so that all of the image is available and it fills the widget in one // direction. QRect rect; - double widgetAr = (double)videoWidget->width() / (double)videoWidget->height(); + double widgetAr = (double) videoWidget->width() / (double) videoWidget->height(); double vidAr = MLT.profile().dar(); if (widgetAr > vidAr) { - double width = (double)videoWidget->height() * vidAr; - rect.setX((round((double)videoWidget->width() - width) / 2)); + double width = (double) videoWidget->height() * vidAr; + rect.setX((round((double) videoWidget->width() - width) / 2)); rect.setY(0); rect.setWidth(round(width)); rect.setHeight(videoWidget->height()); } else { double height = videoWidget->width() / vidAr; rect.setX(0); - rect.setY((round((double)videoWidget->height() - height) / 2)); + rect.setY((round((double) videoWidget->height() - height) / 2)); rect.setWidth(videoWidget->width()); rect.setHeight(round(height)); } @@ -70,8 +70,10 @@ QPoint pixelToPlayerPos(const QRect &playerRect, const QPoint &pixel) { // Convert a pixel index to the corresponding global screen position of that // pixel in the player. - double xOffset = (double)playerRect.width() * (double)pixel.x() / (double)MLT.profile().width(); - double yOffset = (double)playerRect.height() * (double)pixel.y() / (double)MLT.profile().height(); + double xOffset = (double) playerRect.width() * (double) pixel.x() + / (double) MLT.profile().width(); + double yOffset = (double) playerRect.height() * (double) pixel.y() + / (double) MLT.profile().height(); return playerRect.topLeft() + QPoint(round(xOffset), round(yOffset)); } @@ -80,8 +82,10 @@ QPoint playerPosToPixel(const QRect &playerRect, const QPoint &pos) // Convert the global position of a point in the player to the corresponding // pixel index. QPoint offset = pos - playerRect.topLeft(); - double xOffset = (double)MLT.profile().width() * (double)offset.x() / (double)playerRect.width(); - double yOffset = (double)MLT.profile().height() * (double)offset.y() / (double)playerRect.height(); + double xOffset = (double) MLT.profile().width() * (double) offset.x() + / (double) playerRect.width(); + double yOffset = (double) MLT.profile().height() * (double) offset.y() + / (double) playerRect.height(); return QPoint(round(xOffset), round(yOffset)); } @@ -134,7 +138,11 @@ VideoZoomScopeWidget::VideoZoomScopeWidget() glayout->addWidget(m_uLabel, 10, 1, Qt::AlignRight); glayout->addWidget(new QLabel(tr("V")), 11, 0, Qt::AlignLeft); glayout->addWidget(m_vLabel, 11, 1, Qt::AlignRight); - glayout->addItem(new QSpacerItem(0, 0, QSizePolicy::Minimum, QSizePolicy::Expanding), 12, 0, 1, 2); + glayout->addItem(new QSpacerItem(0, 0, QSizePolicy::Minimum, QSizePolicy::Expanding), + 12, + 0, + 1, + 2); updateLabels(); onZoomChanged(m_zoomWidget->getZoom()); @@ -147,15 +155,15 @@ VideoZoomScopeWidget::VideoZoomScopeWidget() // Add pixel picker button QToolButton *pickButton = new QToolButton(this); pickButton->setToolTip(tr("Pick a pixel from the source player")); - pickButton->setIcon(QIcon::fromTheme("zoom-select", - QIcon(":/icons/oxygen/32x32/actions/zoom-select"))); + pickButton->setIcon( + QIcon::fromTheme("zoom-select", QIcon(":/icons/oxygen/32x32/actions/zoom-select"))); toolLayout->addWidget(pickButton); connect(pickButton, SIGNAL(clicked()), this, SLOT(onScreenSelectStarted())); // Add pixel lock button m_lockButton->setToolTip(tr("Lock/Unlock the selected pixel")); - m_lockButton->setIcon(QIcon::fromTheme("object-unlocked", - QIcon(":/icons/oxygen/32x32/status/object-unlocked"))); + m_lockButton->setIcon( + QIcon::fromTheme("object-unlocked", QIcon(":/icons/oxygen/32x32/status/object-unlocked"))); m_lockButton->setCheckable(true); m_lockButton->setChecked(false); toolLayout->addWidget(m_lockButton); @@ -172,12 +180,18 @@ VideoZoomScopeWidget::VideoZoomScopeWidget() hlayout->addLayout(glayout); hlayout->addWidget(m_zoomWidget); - connect(m_zoomWidget, SIGNAL(pixelSelected(const QPoint &)), this, + connect(m_zoomWidget, + SIGNAL(pixelSelected(const QPoint &)), + this, SLOT(onPixelSelected(const QPoint &))); connect(m_zoomWidget, SIGNAL(zoomChanged(int)), this, SLOT(onZoomChanged(int))); - connect(&m_selector, SIGNAL(screenSelected(const QRect &)), this, + connect(&m_selector, + SIGNAL(screenSelected(const QRect &)), + this, SLOT(onScreenRectSelected(const QRect &))); - connect(&m_selector, SIGNAL(pointSelected(const QPoint &)), this, + connect(&m_selector, + SIGNAL(pointSelected(const QPoint &)), + this, SLOT(onScreenPointSelected(const QPoint &))); LOG_DEBUG() << "end"; } @@ -199,10 +213,12 @@ void VideoZoomScopeWidget::onScreenSelectStarted() // Calculate the size of the zoom window to show over the image. QSize selectionSize; - selectionSize.setWidth((double)boundingRect.width() * (((double)m_zoomWidget->width() / - (double)m_zoomWidget->getZoom()) / (double)MLT.profile().width())); - selectionSize.setHeight((double)boundingRect.height() * (((double)m_zoomWidget->height() / - (double)m_zoomWidget->getZoom()) / (double)MLT.profile().height())); + selectionSize.setWidth((double) boundingRect.width() + * (((double) m_zoomWidget->width() / (double) m_zoomWidget->getZoom()) + / (double) MLT.profile().width())); + selectionSize.setHeight((double) boundingRect.height() + * (((double) m_zoomWidget->height() / (double) m_zoomWidget->getZoom()) + / (double) MLT.profile().height())); m_selector.setFixedSize(selectionSize); // Calculate the global position of the zoom window. @@ -221,11 +237,12 @@ void VideoZoomScopeWidget::onLockToggled(bool enabled) { m_zoomWidget->lock(enabled); if (enabled) { - m_lockButton->setIcon(QIcon::fromTheme("object-locked", - QIcon(":/icons/oxygen/32x32/status/object-locked"))); + m_lockButton->setIcon( + QIcon::fromTheme("object-locked", QIcon(":/icons/oxygen/32x32/status/object-locked"))); } else { - m_lockButton->setIcon(QIcon::fromTheme("object-unlocked", - QIcon(":/icons/oxygen/32x32/status/object-unlocked"))); + m_lockButton->setIcon( + QIcon::fromTheme("object-unlocked", + QIcon(":/icons/oxygen/32x32/status/object-unlocked"))); } } diff --git a/src/widgets/scopes/videozoomwidget.cpp b/src/widgets/scopes/videozoomwidget.cpp index 957009cd67..192eff1e17 100644 --- a/src/widgets/scopes/videozoomwidget.cpp +++ b/src/widgets/scopes/videozoomwidget.cpp @@ -17,7 +17,7 @@ #include "videozoomwidget.h" -#include +#include "Logger.h" #include #include @@ -30,7 +30,7 @@ const int DEFAULT_ZOOM = 10; QColor getHighContrastColor(const QColor &color) { - if (color.value() > 128 ) { + if (color.value() > 128) { return QColor(Qt::black); } return QColor(Qt::white); @@ -52,7 +52,8 @@ VideoZoomWidget::VideoZoomWidget() void VideoZoomWidget::putFrame(SharedFrame frame) { - if (!frame.is_valid()) return; + if (!frame.is_valid()) + return; // Make sure the images are pre-cached for the UI thread frame.get_image(mlt_image_yuv420p); @@ -73,11 +74,16 @@ QPoint VideoZoomWidget::getSelectedPixel() void VideoZoomWidget::setSelectedPixel(QPoint pixel) { QMutexLocker locker(&m_mutex); - if (!m_frame.is_valid()) return; - if (pixel.x() < 0) return; - if (pixel.x() >= m_frame.get_image_width()) return; - if (pixel.y() < 0) return; - if (pixel.y() >= m_frame.get_image_height()) return; + if (!m_frame.is_valid()) + return; + if (pixel.x() < 0) + return; + if (pixel.x() >= m_frame.get_image_width()) + return; + if (pixel.y() < 0) + return; + if (pixel.y() >= m_frame.get_image_height()) + return; m_selectedPixel = pixel; update(); locker.unlock(); @@ -103,11 +109,16 @@ VideoZoomWidget::PixelValues VideoZoomWidget::getPixelValues(const QPoint &pixel void VideoZoomWidget::setOffset(QPoint offset) { QMutexLocker locker(&m_mutex); - if (!m_frame.is_valid()) return; - if (offset.x() < 0) return; - if (offset.x() >= m_frame.get_image_width()) return; - if (offset.y() < 0) return; - if (offset.y() >= m_frame.get_image_height()) return; + if (!m_frame.is_valid()) + return; + if (offset.x() < 0) + return; + if (offset.x() >= m_frame.get_image_width()) + return; + if (offset.y() < 0) + return; + if (offset.y() >= m_frame.get_image_height()) + return; m_imageOffset = offset; update(); } @@ -124,10 +135,12 @@ QSize VideoZoomWidget::sizeHint() const void VideoZoomWidget::paintEvent(QPaintEvent *) { - if (!isVisible()) return; + if (!isVisible()) + return; QMutexLocker locker(&m_mutex); - if (!m_frame.is_valid()) return; + if (!m_frame.is_valid()) + return; // Create the painter QPainter p(this); @@ -145,17 +158,15 @@ void VideoZoomWidget::paintEvent(QPaintEvent *) for (int y = 0; y < wHeight && iy < iHeight; y += m_zoom) { const uint8_t *pPixel = pImg + ((iy * iWidth) + ix) * 3; for (int x = 0; x < wWidth; x += m_zoom) { - p.fillRect(x, y, m_zoom, m_zoom, QColor(pPixel[0], pPixel[1], pPixel[2], 255 )); + p.fillRect(x, y, m_zoom, m_zoom, QColor(pPixel[0], pPixel[1], pPixel[2], 255)); pPixel += 3; } iy++; } // Outline the selected pixel - if (m_selectedPixel.x() >= 0 && - m_selectedPixel.y() >= 0 && - m_selectedPixel.x() < iWidth && - m_selectedPixel.y() < iHeight) { + if (m_selectedPixel.x() >= 0 && m_selectedPixel.y() >= 0 && m_selectedPixel.x() < iWidth + && m_selectedPixel.y() < iHeight) { const uint8_t *pPixel = pImg + ((m_selectedPixel.y() * iWidth) + m_selectedPixel.x()) * 3; int posX = (m_selectedPixel.x() - m_imageOffset.x()) * m_zoom; int posY = (m_selectedPixel.y() - m_imageOffset.y()) * m_zoom; @@ -168,14 +179,19 @@ void VideoZoomWidget::paintEvent(QPaintEvent *) void VideoZoomWidget::mouseMoveEvent(QMouseEvent *event) { QMutexLocker locker(&m_mutex); - if (!m_frame.is_valid()) return; + if (!m_frame.is_valid()) + return; int iWidth = m_frame.get_image_width(); int iHeight = m_frame.get_image_height(); QPoint currMousePixel = posToPixel(event->pos()); - if (currMousePixel.x() < 0) return; - if (currMousePixel.x() >= iWidth) return; - if (currMousePixel.y() < 0) return; - if (currMousePixel.y() >= iHeight) return; + if (currMousePixel.x() < 0) + return; + if (currMousePixel.x() >= iWidth) + return; + if (currMousePixel.y() < 0) + return; + if (currMousePixel.y() >= iHeight) + return; locker.unlock(); if (event->buttons() & Qt::LeftButton) { @@ -184,9 +200,9 @@ void VideoZoomWidget::mouseMoveEvent(QMouseEvent *event) int maxOffsetY = iHeight - (height() / m_zoom); // Calculate the new image offset QPoint newImageOffset; - newImageOffset.setX((int)m_mouseGrabPixel.x() - ((int)event->pos().x() / m_zoom)); + newImageOffset.setX((int) m_mouseGrabPixel.x() - ((int) event->pos().x() / m_zoom)); newImageOffset.setX(qBound(0, newImageOffset.x(), maxOffsetX)); - newImageOffset.setY((int)m_mouseGrabPixel.y() - ((int)event->pos().y() / m_zoom)); + newImageOffset.setY((int) m_mouseGrabPixel.y() - ((int) event->pos().y() / m_zoom)); newImageOffset.setY(qBound(0, newImageOffset.y(), maxOffsetY)); // Apply the offset if it has changed @@ -221,7 +237,8 @@ void VideoZoomWidget::mousePressEvent(QMouseEvent *event) { if (event->buttons() & Qt::LeftButton) { QMutexLocker locker(&m_mutex); - if (!m_frame.is_valid()) return; + if (!m_frame.is_valid()) + return; QPoint currMousePixel = posToPixel(event->pos()); m_selectedPixel = currMousePixel; m_mouseGrabPixel = currMousePixel; @@ -235,7 +252,8 @@ void VideoZoomWidget::mousePressEvent(QMouseEvent *event) void VideoZoomWidget::wheelEvent(QWheelEvent *event) { QMutexLocker locker(&m_mutex); - if (!m_frame.is_valid()) return; + if (!m_frame.is_valid()) + return; QPoint steps = event->angleDelta() / 8 / 15; int newZoom = qBound(MIN_ZOOM, m_zoom + steps.y(), MAX_ZOOM); @@ -265,15 +283,15 @@ void VideoZoomWidget::wheelEvent(QWheelEvent *event) QPoint VideoZoomWidget::pixelToPos(const QPoint &pixel) { - int x = ((int)pixel.x() - (int)m_imageOffset.x()) * m_zoom; - int y = ((int)pixel.y() - (int)m_imageOffset.y()) * m_zoom; + int x = ((int) pixel.x() - (int) m_imageOffset.x()) * m_zoom; + int y = ((int) pixel.y() - (int) m_imageOffset.y()) * m_zoom; return QPoint(x, y); } QPoint VideoZoomWidget::posToPixel(const QPoint &pos) { - int x = ((int)pos.x() / m_zoom) + (int)m_imageOffset.x(); - int y = ((int)pos.y() / m_zoom) + (int)m_imageOffset.y(); + int x = ((int) pos.x() / m_zoom) + (int) m_imageOffset.x(); + int y = ((int) pos.y() / m_zoom) + (int) m_imageOffset.y(); return QPoint(x, y); } @@ -286,9 +304,10 @@ VideoZoomWidget::PixelValues VideoZoomWidget::pixelToValues(const QPoint &pixel) const uint8_t *pRgb = m_frame.get_image(mlt_image_rgb) + imageOffset * 3; const uint8_t *pYuv = m_frame.get_image(mlt_image_yuv420p); const uint8_t *pY = pYuv + imageOffset; - const uint8_t *pU = pYuv + (iWidth * iHeight) + (iWidth / 2 * (pixel.y() / 2)) + (pixel.x() / 2); - const uint8_t *pV = pYuv + (iWidth * iHeight * 5 / 4) + (iWidth / 2 * (pixel.y() / 2)) + - (pixel.x() / 2); + const uint8_t *pU = pYuv + (iWidth * iHeight) + (iWidth / 2 * (pixel.y() / 2)) + + (pixel.x() / 2); + const uint8_t *pV = pYuv + (iWidth * iHeight * 5 / 4) + (iWidth / 2 * (pixel.y() / 2)) + + (pixel.x() / 2); values.y = *pY; values.u = *pU; values.v = *pV; diff --git a/src/widgets/scopes/videozoomwidget.h b/src/widgets/scopes/videozoomwidget.h index 4223400654..58fe47611d 100644 --- a/src/widgets/scopes/videozoomwidget.h +++ b/src/widgets/scopes/videozoomwidget.h @@ -20,15 +20,16 @@ #include "sharedframe.h" -#include #include +#include class VideoZoomWidget : public QWidget { Q_OBJECT public: - struct PixelValues { + struct PixelValues + { uint8_t y; uint8_t u; uint8_t v; @@ -60,9 +61,9 @@ public slots: virtual QSize sizeHint() const Q_DECL_OVERRIDE; void paintEvent(QPaintEvent *) Q_DECL_OVERRIDE; - void mouseMoveEvent(QMouseEvent *event)Q_DECL_OVERRIDE; - void mousePressEvent(QMouseEvent *event)Q_DECL_OVERRIDE; - void wheelEvent(QWheelEvent *event)Q_DECL_OVERRIDE; + void mouseMoveEvent(QMouseEvent *event) Q_DECL_OVERRIDE; + void mousePressEvent(QMouseEvent *event) Q_DECL_OVERRIDE; + void wheelEvent(QWheelEvent *event) Q_DECL_OVERRIDE; QPoint pixelToPos(const QPoint &pixel); QPoint posToPixel(const QPoint &pos); diff --git a/src/widgets/screenselector.cpp b/src/widgets/screenselector.cpp index dd84c13318..054941120c 100644 --- a/src/widgets/screenselector.cpp +++ b/src/widgets/screenselector.cpp @@ -127,10 +127,13 @@ bool ScreenSelector::onMousePressEvent(QMouseEvent *event) bool ScreenSelector::onMouseMoveEvent(QMouseEvent *event) { - if (m_boundingRect.x() > -1 && - !m_boundingRect.contains(event->globalPosition().toPoint())) { - int x = qBound(m_boundingRect.left(), qRound(event->globalPosition().x()), m_boundingRect.right()); - int y = qBound(m_boundingRect.top(), qRound(event->globalPosition().y()), m_boundingRect.bottom()); + if (m_boundingRect.x() > -1 && !m_boundingRect.contains(event->globalPosition().toPoint())) { + int x = qBound(m_boundingRect.left(), + qRound(event->globalPosition().x()), + m_boundingRect.right()); + int y = qBound(m_boundingRect.top(), + qRound(event->globalPosition().y()), + m_boundingRect.bottom()); QCursor::setPos(x, y); return true; } @@ -139,7 +142,7 @@ bool ScreenSelector::onMouseMoveEvent(QMouseEvent *event) if (m_fixedSize.width() > -1) { // Center the selection around the cursor int x = qRound(event->globalPosition().x()) - m_fixedSize.width() / 2; - int y = qRound(event->globalPosition().y()) - m_fixedSize.height() / 2; + int y = qRound(event->globalPosition().y()) - m_fixedSize.height() / 2; if (m_boundingRect.x() > -1) { x = qBound(m_boundingRect.left(), x, m_boundingRect.right() - m_fixedSize.width()); y = qBound(m_boundingRect.top(), y, m_boundingRect.bottom() - m_fixedSize.height()); @@ -166,7 +169,7 @@ bool ScreenSelector::onMouseMoveEvent(QMouseEvent *event) bool ScreenSelector::onMouseReleaseEvent(QMouseEvent *event) { - if (event->button() == Qt::LeftButton && m_selectionInProgress == true ) { + if (event->button() == Qt::LeftButton && m_selectionInProgress == true) { release(); emit screenSelected(m_selectionRect); } diff --git a/src/widgets/screenselector.h b/src/widgets/screenselector.h index d4235a4fe0..f9d4cb63e6 100644 --- a/src/widgets/screenselector.h +++ b/src/widgets/screenselector.h @@ -28,10 +28,7 @@ class ScreenSelector : public QFrame void setFixedSize(const QSize &size); void setBoundingRect(const QRect &rect); void setSelectedRect(const QRect &rect); - bool useDBus() const - { - return m_useDBus; - } + bool useDBus() const { return m_useDBus; } public slots: void startSelection(QPoint initialPos = QPoint(-1, -1)); diff --git a/src/widgets/servicepresetwidget.cpp b/src/widgets/servicepresetwidget.cpp index 0a0eea04d1..1ea72078c3 100644 --- a/src/widgets/servicepresetwidget.cpp +++ b/src/widgets/servicepresetwidget.cpp @@ -17,19 +17,19 @@ #include "servicepresetwidget.h" #include "ui_servicepresetwidget.h" + +#include "Logger.h" #include "qmltypes/qmlapplication.h" #include "settings.h" -#include - #include #include #include -ServicePresetWidget::ServicePresetWidget(QWidget *parent) : - QWidget(parent), - ui(new Ui::ServicePresetWidget), - m_widgetName(parent->objectName()) +ServicePresetWidget::ServicePresetWidget(QWidget *parent) + : QWidget(parent) + , ui(new Ui::ServicePresetWidget) + , m_widgetName(parent->objectName()) { ui->setupUi(this); } diff --git a/src/widgets/servicepresetwidget.h b/src/widgets/servicepresetwidget.h index bf3f43b1cc..cbce138e1c 100644 --- a/src/widgets/servicepresetwidget.h +++ b/src/widgets/servicepresetwidget.h @@ -18,8 +18,8 @@ #ifndef SERVICEPRESETWIDGET_H #define SERVICEPRESETWIDGET_H -#include #include +#include namespace Ui { class ServicePresetWidget; diff --git a/src/widgets/slideshowgeneratorwidget.cpp b/src/widgets/slideshowgeneratorwidget.cpp index 2148718c8f..49788030f8 100644 --- a/src/widgets/slideshowgeneratorwidget.cpp +++ b/src/widgets/slideshowgeneratorwidget.cpp @@ -19,10 +19,10 @@ #include "Logger.h" #include "mltcontroller.h" +#include "qmltypes/qmlapplication.h" #include "settings.h" #include "shotcut_mlt_properties.h" #include "widgets/producerpreviewwidget.h" -#include "qmltypes/qmlapplication.h" #include #include @@ -78,9 +78,11 @@ SlideshowGeneratorWidget::SlideshowGeneratorWidget(Mlt::Playlist *clips, QWidget } } m_aspectConversionCombo->setToolTip(tr("Choose an aspect ratio conversion method.")); - m_aspectConversionCombo->setCurrentIndex(Settings.slideshowAspectConversion( - ASPECT_CONVERSION_CROP_CENTER)); - connect(m_aspectConversionCombo, SIGNAL(currentIndexChanged(int)), this, + m_aspectConversionCombo->setCurrentIndex( + Settings.slideshowAspectConversion(ASPECT_CONVERSION_CROP_CENTER)); + connect(m_aspectConversionCombo, + SIGNAL(currentIndexChanged(int)), + this, SLOT(on_parameterChanged())); grid->addWidget(m_aspectConversionCombo, 1, 1); @@ -98,13 +100,16 @@ SlideshowGeneratorWidget::SlideshowGeneratorWidget(Mlt::Playlist *clips, QWidget grid->addWidget(new QLabel(tr("Transition duration")), 3, 0, Qt::AlignRight); m_transitionDurationSpinner = new QDoubleSpinBox(); m_transitionDurationSpinner->setToolTip( - tr("Set the duration of the transition.\nMay not be longer than half the duration of the clip.\nIf the duration is 0, no transition will be created.")); + tr("Set the duration of the transition.\nMay not be longer than half the duration of the " + "clip.\nIf the duration is 0, no transition will be created.")); m_transitionDurationSpinner->setSuffix(" s"); m_transitionDurationSpinner->setDecimals(1); m_transitionDurationSpinner->setMinimum(0); m_transitionDurationSpinner->setMaximum(10); m_transitionDurationSpinner->setValue(Settings.slideshowTransitionDuration(2.0)); - connect(m_transitionDurationSpinner, SIGNAL(valueChanged(double)), this, + connect(m_transitionDurationSpinner, + SIGNAL(valueChanged(double)), + this, SLOT(on_parameterChanged())); grid->addWidget(m_transitionDurationSpinner, 3, 1); @@ -141,7 +146,9 @@ SlideshowGeneratorWidget::SlideshowGeneratorWidget(Mlt::Playlist *clips, QWidget } m_transitionStyleCombo->setToolTip(tr("Choose a transition effect.")); m_transitionStyleCombo->setCurrentIndex(Settings.slideshowTransitionStyle(dissolveIndex)); - connect(m_transitionStyleCombo, SIGNAL(currentIndexChanged(int)), this, + connect(m_transitionStyleCombo, + SIGNAL(currentIndexChanged(int)), + this, SLOT(on_parameterChanged())); grid->addWidget(m_transitionStyleCombo, 4, 1); @@ -187,7 +194,9 @@ Mlt::Playlist *SlideshowGeneratorWidget::getSlideshow() auto out = c->frame_in + framesPerClip - 1; if (QString::fromLatin1(c->producer->get("mlt_service")).startsWith("avformat")) out = qMin(c->frame_out, out); - Mlt::Producer producer(MLT.profile(), "xml-string", MLT.XML(c->producer).toUtf8().constData()); + Mlt::Producer producer(MLT.profile(), + "xml-string", + MLT.XML(c->producer).toUtf8().constData()); slideshow->append(producer, c->frame_in, out); } } @@ -197,7 +206,8 @@ Mlt::Playlist *SlideshowGeneratorWidget::getSlideshow() Mlt::ClipInfo *c = slideshow->clip_info(i, &info); if (c && c->producer) { if (!c->producer->property_exists("meta.media.width")) { - delete c->producer->get_frame(); // makes avformat producer set meta.media.width and .height + delete c->producer + ->get_frame(); // makes avformat producer set meta.media.width and .height } attachAffineFilter(config, c->producer, c->frame_count - 1); attachBlurFilter(config, c->producer); @@ -228,7 +238,7 @@ Mlt::Playlist *SlideshowGeneratorWidget::getSlideshow() // Create playlist mix slideshow->mix(i, framesPerTransition); QScopedPointer producer(slideshow->get_clip(i + 1)); - if ( producer.isNull() ) { + if (producer.isNull()) { break; } producer->parent().set(kShotcutTransitionProperty, "lumaMix"); @@ -257,12 +267,12 @@ Mlt::Playlist *SlideshowGeneratorWidget::getSlideshow() return slideshow; } -void SlideshowGeneratorWidget::attachAffineFilter(SlideshowConfig &config, Mlt::Producer *producer, +void SlideshowGeneratorWidget::attachAffineFilter(SlideshowConfig &config, + Mlt::Producer *producer, int endPosition) { - if (config.zoomPercent == 0 && - config.aspectConversion != ASPECT_CONVERSION_CROP_CENTER && - config.aspectConversion != ASPECT_CONVERSION_CROP_PAN) { + if (config.zoomPercent == 0 && config.aspectConversion != ASPECT_CONVERSION_CROP_CENTER + && config.aspectConversion != ASPECT_CONVERSION_CROP_PAN) { return; } @@ -295,50 +305,50 @@ void SlideshowGeneratorWidget::attachAffineFilter(SlideshowConfig &config, Mlt:: return; } - if (config.aspectConversion == ASPECT_CONVERSION_CROP_CENTER || - config.aspectConversion == ASPECT_CONVERSION_CROP_PAN) { + if (config.aspectConversion == ASPECT_CONVERSION_CROP_CENTER + || config.aspectConversion == ASPECT_CONVERSION_CROP_PAN) { if (sourceDar > destDar) { // Crop sides to fit height - beginRect.w = (double)MLT.profile().width() * sourceDar / destDar; + beginRect.w = (double) MLT.profile().width() * sourceDar / destDar; beginRect.h = MLT.profile().height(); beginRect.y = 0; endRect.w = beginRect.w; endRect.h = beginRect.h; endRect.y = beginRect.y; if (config.aspectConversion == ASPECT_CONVERSION_CROP_CENTER) { - beginRect.x = ((double)MLT.profile().width() - beginRect.w) / 2.0; + beginRect.x = ((double) MLT.profile().width() - beginRect.w) / 2.0; endRect.x = beginRect.x; } else { beginRect.x = 0; - endRect.x = (double)MLT.profile().width() - endRect.w; + endRect.x = (double) MLT.profile().width() - endRect.w; } } else if (destDar > sourceDar) { // Crop top and bottom to fit width. beginRect.w = MLT.profile().width(); - beginRect.h = (double)MLT.profile().height() * destDar / sourceDar; + beginRect.h = (double) MLT.profile().height() * destDar / sourceDar; beginRect.x = 0; endRect.w = beginRect.w; endRect.h = beginRect.h; endRect.x = beginRect.x; if (config.aspectConversion == ASPECT_CONVERSION_CROP_CENTER) { - beginRect.y = ((double)MLT.profile().height() - beginRect.h) / 2.0; + beginRect.y = ((double) MLT.profile().height() - beginRect.h) / 2.0; endRect.y = beginRect.y; } else { beginRect.y = 0; - endRect.y = (double)MLT.profile().height() - endRect.h; + endRect.y = (double) MLT.profile().height() - endRect.h; } } } else { // Pad: modify rect to fit the aspect ratio of the source if (sourceDar > destDar) { beginRect.w = MLT.profile().width(); - beginRect.h = (double)MLT.profile().height() * destDar / sourceDar; + beginRect.h = (double) MLT.profile().height() * destDar / sourceDar; beginRect.x = 0; - beginRect.y = ((double)MLT.profile().height() - beginRect.h) / 2.0; + beginRect.y = ((double) MLT.profile().height() - beginRect.h) / 2.0; } else if (destDar > sourceDar) { - beginRect.w = (double)MLT.profile().width() * sourceDar / destDar; + beginRect.w = (double) MLT.profile().width() * sourceDar / destDar; beginRect.h = MLT.profile().height(); - beginRect.x = ((double)MLT.profile().width() - beginRect.w) / 2.0; + beginRect.x = ((double) MLT.profile().width() - beginRect.w) / 2.0; beginRect.y = 0; } endRect.w = beginRect.w; @@ -348,13 +358,13 @@ void SlideshowGeneratorWidget::attachAffineFilter(SlideshowConfig &config, Mlt:: } if (config.zoomPercent > 0) { - double endScale = (double)config.zoomPercent / 100.0; + double endScale = (double) config.zoomPercent / 100.0; endRect.x = endRect.x - (endScale * endRect.w / 2.0); endRect.y = endRect.y - (endScale * endRect.h / 2.0); endRect.w = endRect.w + (endScale * endRect.w); endRect.h = endRect.h + (endScale * endRect.h); } else if (config.zoomPercent < 0) { - double beginScale = -1.0 * (double)config.zoomPercent / 100.0; + double beginScale = -1.0 * (double) config.zoomPercent / 100.0; beginRect.x = beginRect.x - (beginScale * beginRect.w / 2.0); beginRect.y = beginRect.y - (beginScale * beginRect.h / 2.0); beginRect.w = beginRect.w + (beginScale * beginRect.w); @@ -406,7 +416,7 @@ void SlideshowGeneratorWidget::attachBlurFilter(SlideshowConfig &config, Mlt::Pr sourceAr = producer->get_double("aspect_ratio"); } double sourceDar = destDar; - if ( sourceW && sourceH && sourceAr ) { + if (sourceW && sourceH && sourceAr) { sourceDar = sourceW * sourceAr / sourceH; } if (sourceDar == destDar) { @@ -417,11 +427,11 @@ void SlideshowGeneratorWidget::attachBlurFilter(SlideshowConfig &config, Mlt::Pr if (sourceDar > destDar) { // Blur top/bottom to pad. rect.h = MLT.profile().height() * destDar / sourceDar; - rect.y = ((double)MLT.profile().height() - rect.h) / 2.0; + rect.y = ((double) MLT.profile().height() - rect.h) / 2.0; } else if (destDar > sourceDar) { // Blur sides to pad. rect.w = MLT.profile().width() * sourceDar / destDar; - rect.x = ((double)MLT.profile().width() - rect.w) / 2.0; + rect.x = ((double) MLT.profile().width() - rect.w) / 2.0; } Mlt::Filter filter(MLT.profile(), "pillar_echo"); @@ -448,11 +458,15 @@ void SlideshowGeneratorWidget::applyLumaTransitionProperties(Mlt::Transition *lu luma->set("resource", ""); luma->set("softness", 0); } else if (index <= 24) { - luma->set("resource", QStringLiteral("%luma%1.pgm").arg(index - 2, 2, 10, - QChar('0')).toLatin1().constData()); + luma->set("resource", + QStringLiteral("%luma%1.pgm") + .arg(index - 2, 2, 10, QChar('0')) + .toLatin1() + .constData()); luma->set("softness", config.transitionSoftness / 100.0); } else { - luma->set("resource", m_transitionStyleCombo->itemData(index).toString().toUtf8().constData()); + luma->set("resource", + m_transitionStyleCombo->itemData(index).toString().toUtf8().constData()); luma->set("softness", config.transitionSoftness / 100.0); } luma->set("progressive", 1); @@ -464,7 +478,7 @@ void SlideshowGeneratorWidget::applyLumaTransitionProperties(Mlt::Transition *lu void SlideshowGeneratorWidget::on_parameterChanged() { - if (m_transitionDurationSpinner->value() > m_clipDurationSpinner->value() / 2 ) { + if (m_transitionDurationSpinner->value() > m_clipDurationSpinner->value() / 2) { m_transitionDurationSpinner->setValue(m_clipDurationSpinner->value() / 2); } if (m_transitionDurationSpinner->value() == randomIndex) { @@ -482,8 +496,8 @@ void SlideshowGeneratorWidget::on_parameterChanged() } m_preview->stop(); - m_preview->showText(Settings.playerGPU() ? tr("Preview is not available with GPU Effects") : - tr("Generating Preview...")); + m_preview->showText(Settings.playerGPU() ? tr("Preview is not available with GPU Effects") + : tr("Generating Preview...")); m_mutex.lock(); m_refreshPreview = true; m_config.clipDuration = m_clipDurationSpinner->value(); diff --git a/src/widgets/slideshowgeneratorwidget.h b/src/widgets/slideshowgeneratorwidget.h index 206ab43efd..bd588afc45 100644 --- a/src/widgets/slideshowgeneratorwidget.h +++ b/src/widgets/slideshowgeneratorwidget.h @@ -19,7 +19,6 @@ #define SLIDESHOWGENERATORWIDGET_H #include - #include #include #include @@ -32,7 +31,7 @@ namespace Mlt { class Filter; class Playlist; class Transition; -} +} // namespace Mlt class ProducerPreviewWidget; class SlideshowGeneratorWidget : public QWidget @@ -49,7 +48,8 @@ private slots: void on_parameterChanged(); private: - struct SlideshowConfig { + struct SlideshowConfig + { double clipDuration; int aspectConversion; int zoomPercent; diff --git a/src/widgets/statuslabelwidget.cpp b/src/widgets/statuslabelwidget.cpp index 8427bfbaa9..2f1e8e37b0 100644 --- a/src/widgets/statuslabelwidget.cpp +++ b/src/widgets/statuslabelwidget.cpp @@ -56,7 +56,10 @@ StatusLabelWidget::StatusLabelWidget(QWidget *parent) m_fadeOut->setEasingCurve(QEasingCurve::OutBack); m_timer.setSingleShot(true); connect(&m_timer, SIGNAL(timeout()), m_fadeOut, SLOT(start())); - connect(m_fadeOut, &QPropertyAnimation::finished, this, &StatusLabelWidget::onFadeOutFinished); + connect(m_fadeOut, + &QPropertyAnimation::finished, + this, + &StatusLabelWidget::onFadeOutFinished); m_fadeOut->start(); } else { connect(&m_timer, &QTimer::timeout, this, &StatusLabelWidget::onFadeOutFinished); @@ -64,21 +67,21 @@ StatusLabelWidget::StatusLabelWidget(QWidget *parent) setLayout(m_layout); } -StatusLabelWidget::~StatusLabelWidget() -{ -} +StatusLabelWidget::~StatusLabelWidget() {} void StatusLabelWidget::setWidth(int width) { m_width = width; } -void StatusLabelWidget::showText(const QString &text, int timeoutSeconds, QAction *action, +void StatusLabelWidget::showText(const QString &text, + int timeoutSeconds, + QAction *action, QPalette::ColorRole role) { auto width = m_width ? m_width : m_layout->maximumSize().width(); QString s = QStringLiteral(" %1 ").arg( - m_label->fontMetrics().elidedText(text, Qt::ElideRight, width - 30)); + m_label->fontMetrics().elidedText(text, Qt::ElideRight, width - 30)); m_label->setText(s); m_label->setToolTip(text); auto palette = QApplication::palette(); diff --git a/src/widgets/statuslabelwidget.h b/src/widgets/statuslabelwidget.h index 98622cb190..f77cc8ba26 100644 --- a/src/widgets/statuslabelwidget.h +++ b/src/widgets/statuslabelwidget.h @@ -33,7 +33,9 @@ class StatusLabelWidget : public QWidget StatusLabelWidget(QWidget *parent = nullptr); virtual ~StatusLabelWidget(); void setWidth(int width); - void showText(const QString &text, int timeoutSeconds = -1, QAction *action = nullptr, + void showText(const QString &text, + int timeoutSeconds = -1, + QAction *action = nullptr, QPalette::ColorRole role = QPalette::ToolTipBase); signals: diff --git a/src/widgets/textproducerwidget.cpp b/src/widgets/textproducerwidget.cpp index f186c5edaa..c626312576 100644 --- a/src/widgets/textproducerwidget.cpp +++ b/src/widgets/textproducerwidget.cpp @@ -15,14 +15,16 @@ * along with this program. If not, see . */ -#include -#include -#include #include "textproducerwidget.h" #include "ui_textproducerwidget.h" + +#include "mltcontroller.h" #include "shotcut_mlt_properties.h" #include "util.h" -#include "mltcontroller.h" + +#include +#include +#include static const QString kTransparent = QObject::tr("transparent", "Open Other > Color"); static const char *kSimpleFilterName = "dynamicText"; @@ -32,11 +34,11 @@ static const int kPointSize = 60; static QString colorToString(const QColor &color) { return (color == QColor(0, 0, 0, 0)) ? kTransparent - : QString::asprintf("#%02X%02X%02X%02X", - qAlpha(color.rgba()), - qRed(color.rgba()), - qGreen(color.rgba()), - qBlue(color.rgba())); + : QString::asprintf("#%02X%02X%02X%02X", + qAlpha(color.rgba()), + qRed(color.rgba()), + qGreen(color.rgba()), + qBlue(color.rgba())); } static QString colorStringToResource(const QString &s) @@ -44,9 +46,9 @@ static QString colorStringToResource(const QString &s) return (s == kTransparent) ? "#00000000" : s; } -TextProducerWidget::TextProducerWidget(QWidget *parent) : - QWidget(parent), - ui(new Ui::TextProducerWidget) +TextProducerWidget::TextProducerWidget(QWidget *parent) + : QWidget(parent) + , ui(new Ui::TextProducerWidget) { ui->setupUi(this); ui->colorLabel->setText(kTransparent); @@ -80,15 +82,16 @@ void TextProducerWidget::on_colorButton_clicked() auto rgb = newColor; auto transparent = QColor(0, 0, 0, 0); rgb.setAlpha(color.alpha()); - if (newColor.alpha() == 0 && (rgb != color || - (newColor == transparent && color == transparent))) { + if (newColor.alpha() == 0 + && (rgb != color || (newColor == transparent && color == transparent))) { newColor.setAlpha(255); } ui->colorLabel->setText(colorToString(newColor)); ui->colorLabel->setStyleSheet(QStringLiteral("color: %1; background-color: %2") - .arg(Util::textColor(newColor), newColor.name())); + .arg(Util::textColor(newColor), newColor.name())); if (m_producer) { - m_producer->set("resource", colorStringToResource(ui->colorLabel->text()).toLatin1().constData()); + m_producer->set("resource", + colorStringToResource(ui->colorLabel->text()).toLatin1().constData()); m_producer->set(kShotcutCaptionProperty, ui->colorLabel->text().toLatin1().constData()); m_producer->set(kShotcutDetailProperty, ui->colorLabel->text().toLatin1().constData()); emit producerChanged(m_producer.data()); @@ -126,8 +129,8 @@ void TextProducerWidget::loadPreset(Mlt::Properties &p) { QColor color(QFileInfo(p.get("resource")).baseName()); ui->colorLabel->setText(colorToString(color)); - ui->colorLabel->setStyleSheet(QStringLiteral("color: %1; background-color: %2") - .arg(Util::textColor(color), color.name())); + ui->colorLabel->setStyleSheet( + QStringLiteral("color: %1; background-color: %2").arg(Util::textColor(color), color.name())); if (qstrcmp("", p.get("html"))) { ui->plainTextEdit->setPlainText(QString::fromUtf8(p.get("html"))); ui->richRadioButton->setChecked(true); @@ -136,7 +139,8 @@ void TextProducerWidget::loadPreset(Mlt::Properties &p) ui->simpleRadioButton->setChecked(true); } if (m_producer) { - m_producer->set("resource", colorStringToResource(ui->colorLabel->text()).toLatin1().constData()); + m_producer->set("resource", + colorStringToResource(ui->colorLabel->text()).toLatin1().constData()); m_producer->set(kShotcutCaptionProperty, ui->colorLabel->text().toLatin1().constData()); m_producer->set(kShotcutDetailProperty, ui->colorLabel->text().toLatin1().constData()); QScopedPointer filter; @@ -173,17 +177,28 @@ Mlt::Filter *TextProducerWidget::createFilter(Mlt::Profile &profile, Mlt::Produc QString text = ui->plainTextEdit->toPlainText(); if (text.isEmpty()) text = tr("Edit your text using the Filters panel."); - QString html = "" - "" + QString html + = "" + "" #if defined(Q_OS_WIN) - "

%1

"; + "

%1

"; #elif defined(Q_OS_MAC) - "

%1

"; + "

%1

"; #else - "

%1

"; + "

%1

"; #endif html = html.arg(text); filter->set("html", html.toUtf8().constData()); @@ -193,7 +208,8 @@ Mlt::Filter *TextProducerWidget::createFilter(Mlt::Profile &profile, Mlt::Produc if (!ui->plainTextEdit->toPlainText().isEmpty()) filter->set("argument", ui->plainTextEdit->toPlainText().toUtf8().constData()); else - filter->set("argument", tr("Edit your text using the Filters panel.").toUtf8().constData()); + filter->set("argument", + tr("Edit your text using the Filters panel.").toUtf8().constData()); } #if defined(Q_OS_WIN) filter->set("family", "Verdana"); @@ -210,11 +226,13 @@ Mlt::Filter *TextProducerWidget::createFilter(Mlt::Profile &profile, Mlt::Produc filter->set("shotcut:pointSize", kPointSize); QFont font(filter->get("family"), kPointSize, filter->get_int("weight")); filter->set("size", QFontInfo(font).pixelSize()); - filter->set("geometry", QStringLiteral("0 %1 %2 %3 1") - .arg(qRound(0.75 * profile.height())) - .arg(profile.width()) - .arg(profile.height() * 0.25) - .toUtf8().constData()); + filter->set("geometry", + QStringLiteral("0 %1 %2 %3 1") + .arg(qRound(0.75 * profile.height())) + .arg(profile.width()) + .arg(profile.height() * 0.25) + .toUtf8() + .constData()); filter->set("valign", "top"); filter->set("halign", "center"); filter->set_in_and_out(p->get_in(), p->get_out()); diff --git a/src/widgets/textproducerwidget.h b/src/widgets/textproducerwidget.h index 2e4250bbca..08995caf7b 100644 --- a/src/widgets/textproducerwidget.h +++ b/src/widgets/textproducerwidget.h @@ -18,9 +18,10 @@ #ifndef TEXTPRODUCERWIDGET_H #define TEXTPRODUCERWIDGET_H -#include #include "abstractproducerwidget.h" +#include + namespace Ui { class TextProducerWidget; } diff --git a/src/widgets/timelinepropertieswidget.cpp b/src/widgets/timelinepropertieswidget.cpp index 9d4ff3a7e9..38b9bcea2e 100644 --- a/src/widgets/timelinepropertieswidget.cpp +++ b/src/widgets/timelinepropertieswidget.cpp @@ -17,22 +17,25 @@ #include "timelinepropertieswidget.h" #include "ui_timelinepropertieswidget.h" + #include "mltcontroller.h" #include "util.h" -TimelinePropertiesWidget::TimelinePropertiesWidget(Mlt::Service &service, QWidget *parent) : - QWidget(parent), - ui(new Ui::TimelinePropertiesWidget), - m_service(service) +TimelinePropertiesWidget::TimelinePropertiesWidget(Mlt::Service &service, QWidget *parent) + : QWidget(parent) + , ui(new Ui::TimelinePropertiesWidget) + , m_service(service) { ui->setupUi(this); connect(ui->editButton, &QAbstractButton::clicked, this, &TimelinePropertiesWidget::editProfile); Util::setColorsToHighlight(ui->nameLabel); if (m_service.is_valid()) { Mlt::Profile &profile = MLT.profile(); - ui->resolutionLabel->setText(QStringLiteral("%1 x %2").arg(profile.width()).arg(profile.height())); - ui->aspectRatioLabel->setText(QStringLiteral("%1 : %2").arg(profile.display_aspect_num()).arg( - profile.display_aspect_den())); + ui->resolutionLabel->setText( + QStringLiteral("%1 x %2").arg(profile.width()).arg(profile.height())); + ui->aspectRatioLabel->setText(QStringLiteral("%1 : %2") + .arg(profile.display_aspect_num()) + .arg(profile.display_aspect_den())); ui->frameRateLabel->setText(tr("%L1 fps").arg(profile.fps(), 0, 'f', 6)); if (profile.progressive()) ui->scanModeLabel->setText(tr("Progressive")); @@ -51,4 +54,3 @@ TimelinePropertiesWidget::~TimelinePropertiesWidget() { delete ui; } - diff --git a/src/widgets/timelinepropertieswidget.h b/src/widgets/timelinepropertieswidget.h index ce2094446c..97db6fa6f8 100644 --- a/src/widgets/timelinepropertieswidget.h +++ b/src/widgets/timelinepropertieswidget.h @@ -18,8 +18,8 @@ #ifndef TIMELINEPROPERTIESWIDGET_H #define TIMELINEPROPERTIESWIDGET_H -#include #include +#include namespace Ui { class TimelinePropertiesWidget; diff --git a/src/widgets/timespinbox.cpp b/src/widgets/timespinbox.cpp index 1e5a7cfd42..6ea407cc57 100644 --- a/src/widgets/timespinbox.cpp +++ b/src/widgets/timespinbox.cpp @@ -16,12 +16,14 @@ */ #include "timespinbox.h" + #include "mltcontroller.h" #include "settings.h" -#include -#include + #include #include +#include +#include TimeSpinBox::TimeSpinBox(QWidget *parent) : QSpinBox(parent) @@ -29,17 +31,16 @@ TimeSpinBox::TimeSpinBox(QWidget *parent) setLineEdit(new TimeSpinBoxLineEdit); setRange(0, INT_MAX); setAlignment(Qt::AlignRight); - m_validator = new QRegularExpressionValidator( - QRegularExpression("^\\s*(\\d*:){0,2}(\\d*[.;:])?\\d*\\s*$"), this); + m_validator = new QRegularExpressionValidator(QRegularExpression( + "^\\s*(\\d*:){0,2}(\\d*[.;:])?\\d*\\s*$"), + this); setValue(0); QFont font = QFontDatabase::systemFont(QFontDatabase::FixedFont); font.setPointSize(QGuiApplication::font().pointSize()); setFont(font); setFixedWidth(fontMetrics().boundingRect("_HHH:MM:SS;FFF_").width()); - connect(&Settings, &ShotcutSettings::timeFormatChanged, this, [&]() { - setValue(value()); - }); + connect(&Settings, &ShotcutSettings::timeFormatChanged, this, [&]() { setValue(value()); }); } QValidator::State TimeSpinBox::validate(QString &input, int &pos) const @@ -81,12 +82,10 @@ void TimeSpinBox::keyPressEvent(QKeyEvent *event) } } - TimeSpinBoxLineEdit::TimeSpinBoxLineEdit(QWidget *parent) : QLineEdit(parent) , m_selectOnMousePress(false) -{ -} +{} void TimeSpinBoxLineEdit::focusInEvent(QFocusEvent *event) { @@ -111,4 +110,3 @@ void TimeSpinBoxLineEdit::mousePressEvent(QMouseEvent *event) m_selectOnMousePress = false; } } - diff --git a/src/widgets/timespinbox.h b/src/widgets/timespinbox.h index d7c5e6d7cf..67bf6f2b87 100644 --- a/src/widgets/timespinbox.h +++ b/src/widgets/timespinbox.h @@ -18,8 +18,8 @@ #ifndef TIMESPINBOX_H #define TIMESPINBOX_H -#include #include +#include class QRegularExpressionValidator; diff --git a/src/widgets/toneproducerwidget.cpp b/src/widgets/toneproducerwidget.cpp index 33ebe7c9c9..e4291b98f9 100644 --- a/src/widgets/toneproducerwidget.cpp +++ b/src/widgets/toneproducerwidget.cpp @@ -15,15 +15,17 @@ * along with this program. If not, see . */ -#include "shotcut_mlt_properties.h" #include "toneproducerwidget.h" #include "ui_toneproducerwidget.h" + +#include "shotcut_mlt_properties.h" #include "util.h" + #include -ToneProducerWidget::ToneProducerWidget(QWidget *parent) : - QWidget(parent), - ui(new Ui::ToneProducerWidget) +ToneProducerWidget::ToneProducerWidget(QWidget *parent) + : QWidget(parent) + , ui(new Ui::ToneProducerWidget) { ui->setupUi(this); Util::setColorsToHighlight(ui->nameLabel); @@ -93,6 +95,5 @@ void ToneProducerWidget::on_preset_saveClicked() QString ToneProducerWidget::detail() const { - return tr("Tone: %1Hz %2dB").arg(ui->frequencySpinBox->value()).arg( - ui->levelSpinBox->value()); + return tr("Tone: %1Hz %2dB").arg(ui->frequencySpinBox->value()).arg(ui->levelSpinBox->value()); } diff --git a/src/widgets/toneproducerwidget.h b/src/widgets/toneproducerwidget.h index 4096e2c192..b07f0fbbfc 100644 --- a/src/widgets/toneproducerwidget.h +++ b/src/widgets/toneproducerwidget.h @@ -18,9 +18,10 @@ #ifndef TONEPRODUCERWIDGET_H #define TONEPRODUCERWIDGET_H -#include #include "abstractproducerwidget.h" +#include + namespace Ui { class ToneProducerWidget; } diff --git a/src/widgets/trackpropertieswidget.cpp b/src/widgets/trackpropertieswidget.cpp index a5f16ff5e4..9e1cefdb8e 100644 --- a/src/widgets/trackpropertieswidget.cpp +++ b/src/widgets/trackpropertieswidget.cpp @@ -17,19 +17,21 @@ #include "trackpropertieswidget.h" #include "ui_trackpropertieswidget.h" -#include "shotcut_mlt_properties.h" + #include "commands/timelinecommands.h" #include "mainwindow.h" +#include "shotcut_mlt_properties.h" #include "util.h" + #include #include static const char *BLEND_PROPERTY_CAIROBLEND = "1"; -TrackPropertiesWidget::TrackPropertiesWidget(Mlt::Producer &track, QWidget *parent) : - QWidget(parent), - ui(new Ui::TrackPropertiesWidget), - m_track(track) +TrackPropertiesWidget::TrackPropertiesWidget(Mlt::Producer &track, QWidget *parent) + : QWidget(parent) + , ui(new Ui::TrackPropertiesWidget) + , m_track(track) { ui->setupUi(this); Util::setColorsToHighlight(ui->nameLabel); @@ -123,8 +125,11 @@ void TrackPropertiesWidget::on_blendModeCombo_currentIndexChanged(int index) if (!transition) transition.reset(getTransition("movit.overlay")); if (transition && transition->is_valid()) { - Timeline::ChangeBlendModeCommand *command = new Timeline::ChangeBlendModeCommand( - *transition, BLEND_PROPERTY_CAIROBLEND, ui->blendModeCombo->itemData(index).toString()); + Timeline::ChangeBlendModeCommand *command + = new Timeline::ChangeBlendModeCommand(*transition, + BLEND_PROPERTY_CAIROBLEND, + ui->blendModeCombo->itemData(index) + .toString()); connect(command, SIGNAL(modeChanged(QString &)), SLOT(onModeChanged(QString &))); MAIN.undoStack()->push(command); } diff --git a/src/widgets/trackpropertieswidget.h b/src/widgets/trackpropertieswidget.h index bb74b27d80..75fb369abe 100644 --- a/src/widgets/trackpropertieswidget.h +++ b/src/widgets/trackpropertieswidget.h @@ -19,8 +19,8 @@ #ifndef TRACKPROPERTIESWIDGET_H #define TRACKPROPERTIESWIDGET_H -#include #include +#include namespace Ui { class TrackPropertiesWidget; diff --git a/src/widgets/video4linuxwidget.cpp b/src/widgets/video4linuxwidget.cpp index 51ebbeaa59..b59b86f723 100644 --- a/src/widgets/video4linuxwidget.cpp +++ b/src/widgets/video4linuxwidget.cpp @@ -17,18 +17,20 @@ #include "video4linuxwidget.h" #include "ui_video4linuxwidget.h" -#include "pulseaudiowidget.h" + #include "alsawidget.h" #include "mltcontroller.h" -#include "util.h" -#include "shotcut_mlt_properties.h" +#include "pulseaudiowidget.h" #include "settings.h" +#include "shotcut_mlt_properties.h" +#include "util.h" + #include -Video4LinuxWidget::Video4LinuxWidget(QWidget *parent) : - QWidget(parent), - ui(new Ui::Video4LinuxWidget), - m_audioWidget(0) +Video4LinuxWidget::Video4LinuxWidget(QWidget *parent) + : QWidget(parent) + , ui(new Ui::Video4LinuxWidget) + , m_audioWidget(0) { ui->setupUi(this); Util::setColorsToHighlight(ui->label_3); @@ -46,9 +48,9 @@ Video4LinuxWidget::~Video4LinuxWidget() QString Video4LinuxWidget::URL() const { QString s = QStringLiteral("video4linux2:%1?width=%2&height=%3") - .arg(ui->v4lLineEdit->text()) - .arg(ui->v4lWidthSpinBox->value()) - .arg(ui->v4lHeightSpinBox->value()); + .arg(ui->v4lLineEdit->text()) + .arg(ui->v4lWidthSpinBox->value()) + .arg(ui->v4lHeightSpinBox->value()); if (ui->v4lFramerateSpinBox->value() > 0) s += QStringLiteral("&framerate=%1").arg(ui->v4lFramerateSpinBox->value()); if (ui->v4lStandardCombo->currentIndex() > 0) @@ -64,14 +66,16 @@ Mlt::Producer *Video4LinuxWidget::newProducer(Mlt::Profile &profile) Mlt::Profile ntscProfile("dv_ntsc"); Mlt::Profile palProfile("dv_pal"); if (ui->v4lWidthSpinBox->value() == ntscProfile.width() - && ui->v4lHeightSpinBox->value() == ntscProfile.height()) { - profile.set_sample_aspect(ntscProfile.sample_aspect_num(), ntscProfile.sample_aspect_den()); + && ui->v4lHeightSpinBox->value() == ntscProfile.height()) { + profile.set_sample_aspect(ntscProfile.sample_aspect_num(), + ntscProfile.sample_aspect_den()); profile.set_progressive(ntscProfile.progressive()); profile.set_colorspace(ntscProfile.colorspace()); profile.set_frame_rate(ntscProfile.frame_rate_num(), ntscProfile.frame_rate_den()); } else if (ui->v4lWidthSpinBox->value() == palProfile.width() && ui->v4lHeightSpinBox->value() == palProfile.height()) { - profile.set_sample_aspect(palProfile.sample_aspect_num(), palProfile.sample_aspect_den()); + profile.set_sample_aspect(palProfile.sample_aspect_num(), + palProfile.sample_aspect_den()); profile.set_progressive(palProfile.progressive()); profile.set_colorspace(palProfile.colorspace()); profile.set_frame_rate(palProfile.frame_rate_num(), palProfile.frame_rate_den()); @@ -90,11 +94,12 @@ Mlt::Producer *Video4LinuxWidget::newProducer(Mlt::Profile &profile) if (!p->is_valid()) { delete p; p = new Mlt::Producer(profile, "color:"); - p->set("resource1", QStringLiteral("video4linux2:%1") - .arg(ui->v4lLineEdit->text()).toLatin1().constData()); + p->set("resource1", + QStringLiteral("video4linux2:%1").arg(ui->v4lLineEdit->text()).toLatin1().constData()); p->set("error", 1); } else if (m_audioWidget) { - Mlt::Producer *audio = dynamic_cast(m_audioWidget)->newProducer(profile); + Mlt::Producer *audio + = dynamic_cast(m_audioWidget)->newProducer(profile); Mlt::Tractor *tractor = new Mlt::Tractor; tractor->set("_profile", profile.get_profile(), 0); tractor->set_track(*p, 0); @@ -103,8 +108,8 @@ Mlt::Producer *Video4LinuxWidget::newProducer(Mlt::Profile &profile) delete audio; p = new Mlt::Producer(tractor->get_producer()); delete tractor; - p->set("resource1", QStringLiteral("video4linux2:%1") - .arg(ui->v4lLineEdit->text()).toLatin1().constData()); + p->set("resource1", + QStringLiteral("video4linux2:%1").arg(ui->v4lLineEdit->text()).toLatin1().constData()); } p->set("device", ui->v4lLineEdit->text().toLatin1().constData()); p->set("width", ui->v4lWidthSpinBox->value()); diff --git a/src/widgets/video4linuxwidget.h b/src/widgets/video4linuxwidget.h index e92f28c432..f8e390667e 100644 --- a/src/widgets/video4linuxwidget.h +++ b/src/widgets/video4linuxwidget.h @@ -19,9 +19,10 @@ #ifndef VIDEO4LINUXWIDGET_H #define VIDEO4LINUXWIDGET_H -#include #include "abstractproducerwidget.h" +#include + namespace Ui { class Video4LinuxWidget; } diff --git a/src/windowstools.cpp b/src/windowstools.cpp index 60c212ae0b..4d9449a150 100644 --- a/src/windowstools.cpp +++ b/src/windowstools.cpp @@ -17,9 +17,7 @@ #include "windowstools.h" -WindowsTaskbarButton::WindowsTaskbarButton() -{ -} +WindowsTaskbarButton::WindowsTaskbarButton() {} WindowsTaskbarButton &WindowsTaskbarButton::getInstance() { diff --git a/src/windowstools.h b/src/windowstools.h index 46d01dc506..1d906a185d 100644 --- a/src/windowstools.h +++ b/src/windowstools.h @@ -15,9 +15,9 @@ * along with this program. If not, see . */ +#include #include #include -#include class WindowsTaskbarButton { @@ -27,6 +27,7 @@ class WindowsTaskbarButton void setParentWindow(QWidget *parent); void setProgress(int progress); void resetProgress(); + private: WindowsTaskbarButton(); From f3b648f00f7f9803cbceea99c6913bb9e75f2ce0 Mon Sep 17 00:00:00 2001 From: Brian Matherly Date: Wed, 26 Feb 2025 21:47:01 -0600 Subject: [PATCH 3/5] Use clang-format for github workflow --- .clang-format | 2 +- .github/workflows/check-code-format.yml | 26 ++++++++++++++++--------- 2 files changed, 18 insertions(+), 10 deletions(-) diff --git a/.clang-format b/.clang-format index 3f5bbe8b79..75eab30ff3 100644 --- a/.clang-format +++ b/.clang-format @@ -1,4 +1,4 @@ -# .clang-format for MLT +# .clang-format for Shotcut # # Adapted from https://github.com/qt-creator/qt-creator/blob/master/.clang-format # diff --git a/.github/workflows/check-code-format.yml b/.github/workflows/check-code-format.yml index 6f94f617b7..b9bd88e5bb 100644 --- a/.github/workflows/check-code-format.yml +++ b/.github/workflows/check-code-format.yml @@ -3,30 +3,38 @@ name: check-code-format on: workflow_dispatch: pull_request: - types: [opened, reopened] + types: [opened, reopened, synchronize] push: jobs: - astyle: + clang-format: runs-on: ubuntu-latest steps: - name: Checkout code uses: actions/checkout@v4 - - name: Install Artistic Style - run: sudo apt-get install -y astyle grep + - name: Install clang-format + run: sudo apt-get install -y clang-format-14 - name: Check style run: | - results="$(astyle --project=.astylerc --dry-run --recursive "./*.cpp,*.h" | awk '/^Formatted/')" - if [ -z "$results" ] + FILES=`find . -type f -name "*.h" -o -name "*.c" -o -name "*.cpp"` + FILTERED_FILES=() + for file in ${FILES[@]}; + do + [[ $file =~ "./src/" ]] && + [[ ! $file =~ "spatialmedia" ]] && + [[ ! $file =~ "defaultlayouts.h" ]] && + [[ ! $file =~ "_autogen" ]] && + FILTERED_FILES+=($file) + done + clang-format-14 --verbose --dry-run --Werror -style=file -i ${FILTERED_FILES[@]} + if [ $? -eq 0 ] then echo "SUCCESS: All files are formatted correctly" exit 0 else - count=`wc -l <<< "$results"` - echo "FAILURE: $count files are formatted incorrectly" - echo "${results//'Formatted '/' '}" + echo "FAILURE: some files are formatted incorrectly" exit 99 fi From 0d61f73697b0e383220aed1b9978b8878973279a Mon Sep 17 00:00:00 2001 From: Brian Matherly Date: Wed, 26 Feb 2025 22:07:41 -0600 Subject: [PATCH 4/5] Apply clang-format --- src/docks/encodedock.cpp | 6 +++--- src/jobs/abstractjob.h | 15 +++------------ src/widgets/avformatproducerwidget.cpp | 12 ++++++------ 3 files changed, 12 insertions(+), 21 deletions(-) diff --git a/src/docks/encodedock.cpp b/src/docks/encodedock.cpp index 46eb81cc78..61086c0195 100644 --- a/src/docks/encodedock.cpp +++ b/src/docks/encodedock.cpp @@ -1329,9 +1329,9 @@ MeltJob *EncodeDock::createMeltJob(Mlt::Producer *service, return nullptr; if (JOBS.targetIsInProgress(target)) { - QMessageBox::warning(this, windowTitle(), - QObject::tr("A job already exists for %1") - .arg(target)); + QMessageBox::warning(this, + windowTitle(), + QObject::tr("A job already exists for %1").arg(target)); return nullptr; } diff --git a/src/jobs/abstractjob.h b/src/jobs/abstractjob.h index 5cb45001f6..8a7d89f0c1 100644 --- a/src/jobs/abstractjob.h +++ b/src/jobs/abstractjob.h @@ -41,10 +41,7 @@ class AbstractJob : public QProcess QStandardItem *standardItem(); bool ran() const; bool stopped() const; - bool isFinished() const - { - return (ran() && state() != QProcess::Running); - } + bool isFinished() const { return (ran() && state() != QProcess::Running); } void appendToLog(const QString &); QString log() const; QString label() const { return m_label; } @@ -55,14 +52,8 @@ class AbstractJob : public QProcess QElapsedTimer time() const { return m_totalTime; } void setPostJobAction(PostJobAction *action); bool paused() const; - void setTarget(const QString & target) - { - m_target = target; - } - QString target() - { - return m_target; - } + void setTarget(const QString &target) { m_target = target; } + QString target() { return m_target; } public slots: void start(const QString &program, const QStringList &arguments); diff --git a/src/widgets/avformatproducerwidget.cpp b/src/widgets/avformatproducerwidget.cpp index b5a3dc8fd1..287f8bc72f 100644 --- a/src/widgets/avformatproducerwidget.cpp +++ b/src/widgets/avformatproducerwidget.cpp @@ -1057,9 +1057,9 @@ void AvformatProducerWidget::on_reverseButton_clicked() return; } if (JOBS.targetIsInProgress(filename)) { - QMessageBox::warning(this, dialog.windowTitle(), - QObject::tr("A job already exists for %1") - .arg(filename)); + QMessageBox::warning(this, + dialog.windowTitle(), + QObject::tr("A job already exists for %1").arg(filename)); return; } if (Util::warnIfNotWritable(filename, this, dialog.windowTitle())) @@ -1149,9 +1149,9 @@ void AvformatProducerWidget::on_actionExtractSubclip_triggered() return; } if (JOBS.targetIsInProgress(filename)) { - QMessageBox::warning(this, caption, - QObject::tr("A job already exists for %1") - .arg(filename)); + QMessageBox::warning(this, + caption, + QObject::tr("A job already exists for %1").arg(filename)); return; } if (Util::warnIfNotWritable(filename, this, caption)) From dd63632445808fbe87a4a28a573a50bf9ef71073 Mon Sep 17 00:00:00 2001 From: Brian Matherly Date: Wed, 26 Feb 2025 22:08:44 -0600 Subject: [PATCH 5/5] remove synchronize type from workflow --- .github/workflows/check-code-format.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/check-code-format.yml b/.github/workflows/check-code-format.yml index b9bd88e5bb..c1ae17694c 100644 --- a/.github/workflows/check-code-format.yml +++ b/.github/workflows/check-code-format.yml @@ -3,7 +3,7 @@ name: check-code-format on: workflow_dispatch: pull_request: - types: [opened, reopened, synchronize] + types: [opened, reopened] push: jobs: