id
int64
0
755k
file_name
stringlengths
3
109
file_path
stringlengths
13
185
content
stringlengths
31
9.38M
size
int64
31
9.38M
language
stringclasses
1 value
extension
stringclasses
11 values
total_lines
int64
1
340k
avg_line_length
float64
2.18
149k
max_line_length
int64
7
2.22M
alphanum_fraction
float64
0
1
repo_name
stringlengths
6
65
repo_stars
int64
100
47.3k
repo_forks
int64
0
12k
repo_open_issues
int64
0
3.4k
repo_license
stringclasses
9 values
repo_extraction_date
stringclasses
92 values
exact_duplicates_redpajama
bool
2 classes
near_duplicates_redpajama
bool
2 classes
exact_duplicates_githubcode
bool
2 classes
exact_duplicates_stackv2
bool
1 class
exact_duplicates_stackv1
bool
2 classes
near_duplicates_githubcode
bool
2 classes
near_duplicates_stackv1
bool
2 classes
near_duplicates_stackv2
bool
1 class
19,033
screen.cpp
olive-editor_olive/app/node/gizmo/screen.cpp
/*** Olive - Non-Linear Video Editor Copyright (C) 2022 Olive Team 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 <http://www.gnu.org/licenses/>. ***/ #include "screen.h" namespace olive { ScreenGizmo::ScreenGizmo(QObject *parent) : DraggableGizmo{parent} { } }
829
C++
.cpp
21
36.761905
71
0.773183
olive-editor/olive
8,144
552
131
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
19,034
text.cpp
olive-editor_olive/app/node/gizmo/text.cpp
/*** Olive - Non-Linear Video Editor Copyright (C) 2022 Olive Team 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 <http://www.gnu.org/licenses/>. ***/ #include "text.h" #include "core.h" #include "undo/undocommand.h" namespace olive { TextGizmo::TextGizmo(QObject *parent) : NodeGizmo{parent}, valign_(Qt::AlignTop) { } void TextGizmo::SetRect(const QRectF &r) { rect_ = r; emit RectChanged(rect_); } void TextGizmo::UpdateInputHtml(const QString &s, const rational &time) { if (input_.IsValid()) { MultiUndoCommand *command = new MultiUndoCommand(); Node::SetValueAtTime(input_.input(), time, s, input_.track(), command, true); Core::instance()->undo_stack()->push(command, tr("Edit Text")); } } void TextGizmo::SetVerticalAlignment(Qt::Alignment va) { valign_ = va; emit VerticalAlignmentChanged(valign_); } }
1,411
C++
.cpp
42
30.97619
81
0.746125
olive-editor/olive
8,144
552
131
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
19,035
line.cpp
olive-editor_olive/app/node/gizmo/line.cpp
/*** Olive - Non-Linear Video Editor Copyright (C) 2022 Olive Team 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 <http://www.gnu.org/licenses/>. ***/ #include "line.h" namespace olive { LineGizmo::LineGizmo(QObject *parent) : NodeGizmo(parent) { } void LineGizmo::Draw(QPainter *p) const { // Draw transposed black QLineF transposed = p->transform().map(line_); transposed.translate(1, 1); transposed = p->transform().inverted().map(transposed); p->setPen(QPen(Qt::black, 0)); p->drawLine(transposed); // Draw normal white polygon p->setPen(QPen(Qt::white, 0)); p->setBrush(Qt::NoBrush); p->drawLine(line_); } }
1,201
C++
.cpp
34
32.647059
71
0.74481
olive-editor/olive
8,144
552
131
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
19,036
path.cpp
olive-editor_olive/app/node/gizmo/path.cpp
/*** Olive - Non-Linear Video Editor Copyright (C) 2022 Olive Team 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 <http://www.gnu.org/licenses/>. ***/ #include "path.h" namespace olive { PathGizmo::PathGizmo(QObject *parent) : DraggableGizmo{parent} { } void PathGizmo::Draw(QPainter *p) const { // Draw transposed black QPainterPath transposed = p->transform().map(path_); transposed.translate(1, 1); transposed = p->transform().inverted().map(transposed); p->setPen(QPen(Qt::black, 0)); p->drawPath(transposed); // Draw normal white polygon p->setPen(QPen(Qt::white, 0)); p->setBrush(Qt::NoBrush); p->drawPath(path_); } }
1,213
C++
.cpp
34
32.970588
71
0.747215
olive-editor/olive
8,144
552
131
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
19,037
colordifferencekey.cpp
olive-editor_olive/app/node/keying/colordifferencekey/colordifferencekey.cpp
/*** Olive - Non-Linear Video Editor Copyright (C) 2019 Olive Team 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 <http://www.gnu.org/licenses/>. ***/ #include "colordifferencekey.h" namespace olive { const QString ColorDifferenceKeyNode::kTextureInput = QStringLiteral("tex_in"); const QString ColorDifferenceKeyNode::kGarbageMatteInput = QStringLiteral("garbage_in"); const QString ColorDifferenceKeyNode::kCoreMatteInput = QStringLiteral("core_in"); const QString ColorDifferenceKeyNode::kColorInput = QStringLiteral("color_in"); const QString ColorDifferenceKeyNode::kShadowsInput = QStringLiteral("shadows_in"); const QString ColorDifferenceKeyNode::kHighlightsInput = QStringLiteral("highlights_in"); const QString ColorDifferenceKeyNode::kMaskOnlyInput = QStringLiteral("mask_only_in"); #define super Node ColorDifferenceKeyNode::ColorDifferenceKeyNode() { AddInput(kTextureInput, NodeValue::kTexture, InputFlags(kInputFlagNotKeyframable)); AddInput(kGarbageMatteInput, NodeValue::kTexture, InputFlags(kInputFlagNotKeyframable)); AddInput(kCoreMatteInput, NodeValue::kTexture, InputFlags(kInputFlagNotKeyframable)); AddInput(kColorInput, NodeValue::kCombo, 0); AddInput(kHighlightsInput, NodeValue::kFloat, 1.0f); SetInputProperty(kHighlightsInput, QStringLiteral("min"), 0.0); SetInputProperty(kHighlightsInput, QStringLiteral("base"), 0.01); AddInput(kShadowsInput, NodeValue::kFloat, 1.0f); SetInputProperty(kShadowsInput, QStringLiteral("min"), 0.0); SetInputProperty(kShadowsInput, QStringLiteral("base"), 0.01); AddInput(kMaskOnlyInput, NodeValue::kBoolean, false); SetFlag(kVideoEffect); SetEffectInput(kTextureInput); } QString ColorDifferenceKeyNode::Name() const { return tr("Color Difference Key"); } QString ColorDifferenceKeyNode::id() const { return QStringLiteral("org.olivevideoeditor.Olive.colordifferencekey"); } QVector<Node::CategoryID> ColorDifferenceKeyNode::Category() const { return {kCategoryKeying}; } QString ColorDifferenceKeyNode::Description() const { return tr("A simple color key based on the distance of one color from other colors."); } void ColorDifferenceKeyNode::Retranslate() { super::Retranslate(); SetInputName(kTextureInput, tr("Input")); SetInputName(kGarbageMatteInput, tr("Garbage Matte")); SetInputName(kCoreMatteInput, tr("Core Matte")); SetInputName(kColorInput, tr("Key Color")); SetComboBoxStrings(kColorInput, {tr("Green"), tr("Blue")}); SetInputName(kShadowsInput, tr("Shadows")); SetInputName(kHighlightsInput, tr("Highlights")); SetInputName(kMaskOnlyInput, tr("Show Mask Only")); } ShaderCode ColorDifferenceKeyNode::GetShaderCode(const ShaderRequest &request) const { Q_UNUSED(request) return ShaderCode(FileFunctions::ReadFileAsString(":/shaders/colordifferencekey.frag")); } void ColorDifferenceKeyNode::Value(const NodeValueRow &value, const NodeGlobals &globals, NodeValueTable *table) const { // If there's no texture, no need to run an operation if (TexturePtr tex = value[kTextureInput].toTexture()) { ShaderJob job; job.Insert(value); table->Push(NodeValue::kTexture, tex->toJob(job), this); } } } // namespace olive
3,738
C++
.cpp
83
42.60241
118
0.794992
olive-editor/olive
8,144
552
131
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
19,038
chromakey.cpp
olive-editor_olive/app/node/keying/chromakey/chromakey.cpp
/*** Olive - Non-Linear Video Editor Copyright (C) 2019 Olive Team 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 <http://www.gnu.org/licenses/>. ***/ #include "chromakey.h" #include "node/color/colormanager/colormanager.h" #include "render/colorprocessor.h" namespace olive { #define super OCIOBaseNode const QString ChromaKeyNode::kColorInput = QStringLiteral("color_key"); const QString ChromaKeyNode::kMaskOnlyInput = QStringLiteral("mask_only_in"); const QString ChromaKeyNode::kInvertInput = QStringLiteral("invert_in"); const QString ChromaKeyNode::kUpperToleranceInput = QStringLiteral("upper_tolerence_in"); const QString ChromaKeyNode::kLowerToleranceInput = QStringLiteral("lower_tolerence_in"); const QString ChromaKeyNode::kGarbageMatteInput = QStringLiteral("garbage_in"); const QString ChromaKeyNode::kCoreMatteInput = QStringLiteral("core_in"); const QString ChromaKeyNode::kShadowsInput = QStringLiteral("shadows_in"); const QString ChromaKeyNode::kHighlightsInput = QStringLiteral("highlights_in"); ChromaKeyNode::ChromaKeyNode() { AddInput(kColorInput, NodeValue::kColor, QVariant::fromValue(Color(0.0f, 1.0f, 0.0f, 1.0f))); AddInput(kLowerToleranceInput, NodeValue::kFloat, 5.0); SetInputProperty(kLowerToleranceInput, QStringLiteral("min"), 0.0); SetInputProperty(kLowerToleranceInput, QStringLiteral("base"), 0.1); AddInput(kUpperToleranceInput, NodeValue::kFloat, 25.0); SetInputProperty(kUpperToleranceInput, QStringLiteral("base"), 0.1); // FIXME: Temporarily disabled. This will break if "lower tolerance" is keyframed or connected to // something and there's currently no solution to remedy that. If there is in the future, // we can look into re-enabling this. //SetInputProperty(kUpperToleranceInput, QStringLiteral("min"), GetStandardValue(kLowerToleranceInput).toDouble()); AddInput(kGarbageMatteInput, NodeValue::kTexture, InputFlags(kInputFlagNotKeyframable)); AddInput(kCoreMatteInput, NodeValue::kTexture, InputFlags(kInputFlagNotKeyframable)); AddInput(kHighlightsInput, NodeValue::kFloat, 100.0f); SetInputProperty(kHighlightsInput, QStringLiteral("min"), 0.0); SetInputProperty(kHighlightsInput, QStringLiteral("base"), 0.1); AddInput(kShadowsInput, NodeValue::kFloat, 100.0f); SetInputProperty(kShadowsInput, QStringLiteral("min"), 0.0); SetInputProperty(kShadowsInput, QStringLiteral("base"), 0.1); AddInput(kInvertInput, NodeValue::kBoolean, false); AddInput(kMaskOnlyInput, NodeValue::kBoolean, false); } QString ChromaKeyNode::Name() const { return tr("Chroma Key"); } QString ChromaKeyNode::id() const { return QStringLiteral("org.olivevideoeditor.Olive.chromakey"); } QVector<Node::CategoryID> ChromaKeyNode::Category() const { return {kCategoryKeying}; } QString ChromaKeyNode::Description() const { return tr("A simple color key based on the distance from the chroma of a selected color."); } void ChromaKeyNode::Retranslate() { super::Retranslate(); SetInputName(kTextureInput, tr("Input")); SetInputName(kGarbageMatteInput, tr("Garbage Matte")); SetInputName(kCoreMatteInput, tr("Core Matte")); SetInputName(kColorInput, tr("Key Color")); SetInputName(kShadowsInput, tr("Shadows")); SetInputName(kHighlightsInput, tr("Highlights")); SetInputName(kUpperToleranceInput, tr("Upper Tolerance")); SetInputName(kLowerToleranceInput, tr("Lower Tolerance")); SetInputName(kInvertInput, tr("Invert Mask")); SetInputName(kMaskOnlyInput, tr("Show Mask Only")); } void ChromaKeyNode::InputValueChangedEvent(const QString &input, int element) { Q_UNUSED(element); if (input == kLowerToleranceInput) { // FIXME: Temporarily disabled. This will break if "lower tolerance" is keyframed or connected to // something and there's currently no solution to remedy that. If there is in the future, // we can look into re-enabling this. //SetInputProperty(kUpperToleranceInput, QStringLiteral("min"), GetStandardValue(kLowerToleranceInput).toDouble()); } GenerateProcessor(); } ShaderCode ChromaKeyNode::GetShaderCode(const ShaderRequest &request) const { return ShaderCode(FileFunctions::ReadFileAsString(QStringLiteral(":/shaders/chromakey.frag")).arg(request.stub)); } void ChromaKeyNode::GenerateProcessor() { if (manager()){ try { ColorTransform transform("cie_xyz_d65_interchange"); set_processor(ColorProcessor::Create(manager(), manager()->GetReferenceColorSpace(), transform)); } catch (const OCIO::Exception &e) { std::cerr << std::endl << e.what() << std::endl; } } } void ChromaKeyNode::Value(const NodeValueRow &value, const NodeGlobals &globals, NodeValueTable *table) const { if (TexturePtr tex = value[kTextureInput].toTexture()) { if (processor()) { ColorTransformJob job(value); job.SetColorProcessor(processor()); job.SetInputTexture(value[kTextureInput]); job.SetNeedsCustomShader(this); job.SetFunctionName(QStringLiteral("SceneLinearToCIEXYZ_d65")); table->Push(NodeValue::kTexture, tex->toJob(job), this); } } } void ChromaKeyNode::ConfigChanged() { GenerateProcessor(); } } // namespace olive
5,735
C++
.cpp
125
43.016
119
0.771905
olive-editor/olive
8,144
552
131
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
19,039
despill.cpp
olive-editor_olive/app/node/keying/despill/despill.cpp
/*** Olive - Non-Linear Video Editor Copyright (C) 2019 Olive Team 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 <http://www.gnu.org/licenses/>. ***/ #include "despill.h" #include "node/project.h" namespace olive { const QString DespillNode::kTextureInput = QStringLiteral("tex_in"); const QString DespillNode::kColorInput = QStringLiteral("color_in"); const QString DespillNode::kMethodInput = QStringLiteral("method_in"); const QString DespillNode::kPreserveLuminanceInput = QStringLiteral("preserve_luminance_input"); #define super Node DespillNode::DespillNode() { AddInput(kTextureInput, NodeValue::kTexture, InputFlags(kInputFlagNotKeyframable)); AddInput(kColorInput, NodeValue::kCombo, 0); AddInput(kMethodInput, NodeValue::kCombo, 0); AddInput(kPreserveLuminanceInput, NodeValue::kBoolean, false); SetFlag(kVideoEffect); SetEffectInput(kTextureInput); } QString DespillNode::Name() const { return tr("Despill"); } QString DespillNode::id() const { return QStringLiteral("org.olivevideoeditor.Olive.despill"); } QVector<Node::CategoryID> DespillNode::Category() const { return {kCategoryKeying}; } QString DespillNode::Description() const { return tr("Selection of simple depsill operations"); } void DespillNode::Retranslate() { super::Retranslate(); SetInputName(kTextureInput, tr("Input")); SetInputName(kColorInput, tr("Key Color")); SetComboBoxStrings(kColorInput, {tr("Green"), tr("Blue")}); SetInputName(kMethodInput, tr("Method")); SetComboBoxStrings(kMethodInput, {tr("Average"), tr("Double Red Average"), tr("Double Average"), tr("Limit")}); SetInputName(kPreserveLuminanceInput, tr("Preserve Luminance")); } ShaderCode DespillNode::GetShaderCode(const ShaderRequest &request) const { Q_UNUSED(request) return ShaderCode(FileFunctions::ReadFileAsString(":/shaders/despill.frag")); } void DespillNode::Value(const NodeValueRow &value, const NodeGlobals &globals, NodeValueTable *table) const { ShaderJob job; job.Insert(value); // Set luma coefficients double luma_coeffs[3] = {0.0f, 0.0f, 0.0f}; project()->color_manager()->GetDefaultLumaCoefs(luma_coeffs); job.Insert(QStringLiteral("luma_coeffs"), NodeValue(NodeValue::kVec3, QVector3D(luma_coeffs[0], luma_coeffs[1], luma_coeffs[2]))); // If there's no texture, no need to run an operation if (TexturePtr tex = job.Get(kTextureInput).toTexture()) { table->Push(NodeValue::kTexture, tex->toJob(job), this); } } } // namespace olive
3,061
C++
.cpp
75
38.12
113
0.765957
olive-editor/olive
8,144
552
131
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
19,040
cornerpindistortnode.cpp
olive-editor_olive/app/node/distort/cornerpin/cornerpindistortnode.cpp
/*** Olive - Non-Linear Video Editor Copyright (C) 2022 Olive Team 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 <http://www.gnu.org/licenses/>. ***/ #include "cornerpindistortnode.h" #include "common/lerp.h" #include "core.h" #include "widget/slider/floatslider.h" namespace olive { const QString CornerPinDistortNode::kTextureInput = QStringLiteral("tex_in"); const QString CornerPinDistortNode::kTopLeftInput = QStringLiteral("top_left_in"); const QString CornerPinDistortNode::kTopRightInput = QStringLiteral("top_right_in"); const QString CornerPinDistortNode::kBottomRightInput = QStringLiteral("bottom_right_in"); const QString CornerPinDistortNode::kBottomLeftInput = QStringLiteral("bottom_left_in"); const QString CornerPinDistortNode::kPerspectiveInput = QStringLiteral("perspective_in"); #define super Node CornerPinDistortNode::CornerPinDistortNode() { AddInput(kTextureInput, NodeValue::kTexture, InputFlags(kInputFlagNotKeyframable)); AddInput(kPerspectiveInput, NodeValue::kBoolean, true); AddInput(kTopLeftInput, NodeValue::kVec2, QVector2D(0.0, 0.0)); AddInput(kTopRightInput, NodeValue::kVec2, QVector2D(0.0, 0.0)); AddInput(kBottomRightInput, NodeValue::kVec2, QVector2D(0.0, 0.0)); AddInput(kBottomLeftInput, NodeValue::kVec2, QVector2D(0.0, 0.0)); // Initiate gizmos gizmo_whole_rect_ = AddDraggableGizmo<PolygonGizmo>(); gizmo_resize_handle_[0] = AddDraggableGizmo<PointGizmo>({NodeKeyframeTrackReference(NodeInput(this, kTopLeftInput), 0), NodeKeyframeTrackReference(NodeInput(this, kTopLeftInput), 1)}); gizmo_resize_handle_[1] = AddDraggableGizmo<PointGizmo>({NodeKeyframeTrackReference(NodeInput(this, kTopRightInput), 0), NodeKeyframeTrackReference(NodeInput(this, kTopRightInput), 1)}); gizmo_resize_handle_[2] = AddDraggableGizmo<PointGizmo>({NodeKeyframeTrackReference(NodeInput(this, kBottomRightInput), 0), NodeKeyframeTrackReference(NodeInput(this, kBottomRightInput), 1)}); gizmo_resize_handle_[3] = AddDraggableGizmo<PointGizmo>({NodeKeyframeTrackReference(NodeInput(this, kBottomLeftInput), 0), NodeKeyframeTrackReference(NodeInput(this, kBottomLeftInput), 1)}); SetFlag(kVideoEffect); SetEffectInput(kTextureInput); } void CornerPinDistortNode::Retranslate() { super::Retranslate(); SetInputName(kTextureInput, tr("Texture")); SetInputName(kPerspectiveInput, tr("Perspective")); SetInputName(kTopLeftInput, tr("Top Left")); SetInputName(kTopRightInput, tr("Top Right")); SetInputName(kBottomRightInput, tr("Bottom Right")); SetInputName(kBottomLeftInput, tr("Bottom Left")); } void CornerPinDistortNode::Value(const NodeValueRow &value, const NodeGlobals &globals, NodeValueTable *table) const { // If no texture do nothing if (TexturePtr tex = value[kTextureInput].toTexture()) { // In the special case that all sliders are in their default position just // push the texture. if (!(value[kTopLeftInput].toVec2().isNull() && value[kTopRightInput].toVec2().isNull() && value[kBottomRightInput].toVec2().isNull() && value[kBottomLeftInput].toVec2().isNull())) { ShaderJob job(value); job.Insert(QStringLiteral("resolution_in"), NodeValue(NodeValue::kVec2, tex->virtual_resolution(), this)); // Convert slider values to their pixel values and then convert to clip space (-1.0 ... 1.0) for overriding the // vertex coordinates. const QVector2D &resolution = tex->virtual_resolution(); QVector2D half_resolution = resolution * 0.5; QVector2D top_left = QVector2D(ValueToPixel(0, value, resolution)) / half_resolution - QVector2D(1.0, 1.0); QVector2D top_right = QVector2D(ValueToPixel(1, value, resolution)) / half_resolution - QVector2D(1.0, 1.0); QVector2D bottom_right = QVector2D(ValueToPixel(2, value, resolution)) / half_resolution - QVector2D(1.0, 1.0); QVector2D bottom_left = QVector2D(ValueToPixel(3, value, resolution)) / half_resolution - QVector2D(1.0, 1.0); // Override default vertex coordinates. QVector<float> adjusted_vertices = {top_left.x(), top_left.y(), 0.0f, top_right.x(), top_right.y(), 0.0f, bottom_right.x(), bottom_right.y(), 0.0f, top_left.x(), top_left.y(), 0.0f, bottom_left.x(), bottom_left.y(), 0.0f, bottom_right.x(), bottom_right.y(), 0.0f}; job.SetVertexCoordinates(adjusted_vertices); table->Push(NodeValue::kTexture, tex->toJob(job), this); } else { table->Push(value[kTextureInput]); } } } ShaderCode CornerPinDistortNode::GetShaderCode(const ShaderRequest &request) const { Q_UNUSED(request) return ShaderCode(FileFunctions::ReadFileAsString(QStringLiteral(":/shaders/cornerpin.frag")), FileFunctions::ReadFileAsString(QStringLiteral(":/shaders/cornerpin.vert"))); } QPointF CornerPinDistortNode::ValueToPixel(int value, const NodeValueRow& row, const QVector2D &resolution) const { Q_ASSERT(value >= 0 && value <= 3); QVector2D v; switch (value) { case 0: // Top left v = row[kTopLeftInput].toVec2(); return QPointF(v.x(), v.y()); case 1: // Top right v = row[kTopRightInput].toVec2(); return QPointF(resolution.x() + v.x(), v.y()); case 2: // Bottom right v = row[kBottomRightInput].toVec2(); return QPointF(resolution.x() + v.x(), resolution.y() + v.y()); case 3: //Bottom left v = row[kBottomLeftInput].toVec2(); return QPointF(v.x(), v.y() + resolution.y()); default: // We should never get here return QPointF(); } } void CornerPinDistortNode::GizmoDragMove(double x, double y, const Qt::KeyboardModifiers &modifiers) { DraggableGizmo *gizmo = static_cast<DraggableGizmo*>(sender()); if (gizmo != gizmo_whole_rect_) { gizmo->GetDraggers()[0].Drag(gizmo->GetDraggers()[0].GetStartValue().toDouble() + x); gizmo->GetDraggers()[1].Drag(gizmo->GetDraggers()[1].GetStartValue().toDouble() + y); } } void CornerPinDistortNode::UpdateGizmoPositions(const NodeValueRow &row, const NodeGlobals &globals) { if (TexturePtr tex = row[kTextureInput].toTexture()) { const QVector2D &resolution = tex->virtual_resolution(); QPointF top_left = ValueToPixel(0, row, resolution); QPointF top_right = ValueToPixel(1, row, resolution); QPointF bottom_right = ValueToPixel(2, row, resolution); QPointF bottom_left = ValueToPixel(3, row, resolution); // Add the correct offset to each slider SetInputProperty(kTopLeftInput, QStringLiteral("offset"), QVector2D(0.0, 0.0)); SetInputProperty(kTopRightInput, QStringLiteral("offset"), QVector2D(resolution.x() , 0.0)); SetInputProperty(kBottomRightInput, QStringLiteral("offset"), resolution); SetInputProperty(kBottomLeftInput, QStringLiteral("offset"), QVector2D(0.0, resolution.y())); // Draw bounding box gizmo_whole_rect_->SetPolygon(QPolygonF({top_left, top_right, bottom_right, bottom_left, top_left})); // Create handles gizmo_resize_handle_[0]->SetPoint(top_left); gizmo_resize_handle_[1]->SetPoint(top_right); gizmo_resize_handle_[2]->SetPoint(bottom_right); gizmo_resize_handle_[3]->SetPoint(bottom_left); } } }
7,854
C++
.cpp
145
49.075862
194
0.722903
olive-editor/olive
8,144
552
131
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
19,041
rippledistortnode.cpp
olive-editor_olive/app/node/distort/ripple/rippledistortnode.cpp
/*** Olive - Non-Linear Video Editor Copyright (C) 2022 Olive Team 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 <http://www.gnu.org/licenses/>. ***/ #include "rippledistortnode.h" namespace olive { const QString RippleDistortNode::kTextureInput = QStringLiteral("tex_in"); const QString RippleDistortNode::kEvolutionInput = QStringLiteral("evolution_in"); const QString RippleDistortNode::kIntensityInput = QStringLiteral("intensity_in"); const QString RippleDistortNode::kFrequencyInput = QStringLiteral("frequency_in"); const QString RippleDistortNode::kPositionInput = QStringLiteral("position_in"); const QString RippleDistortNode::kStretchInput = QStringLiteral("stretch_in"); #define super Node RippleDistortNode::RippleDistortNode() { AddInput(kTextureInput, NodeValue::kTexture, InputFlags(kInputFlagNotKeyframable)); AddInput(kEvolutionInput, NodeValue::kFloat, 0); AddInput(kIntensityInput, NodeValue::kFloat, 100); AddInput(kFrequencyInput, NodeValue::kFloat, 1); SetInputProperty(kFrequencyInput, QStringLiteral("base"), 0.01); AddInput(kPositionInput, NodeValue::kVec2, QVector2D(0, 0)); AddInput(kStretchInput, NodeValue::kBoolean, false); SetFlag(kVideoEffect); SetEffectInput(kTextureInput); gizmo_ = AddDraggableGizmo<PointGizmo>({ NodeKeyframeTrackReference(NodeInput(this, kPositionInput), 0), NodeKeyframeTrackReference(NodeInput(this, kPositionInput), 1), }); gizmo_->SetShape(PointGizmo::kAnchorPoint); } QString RippleDistortNode::Name() const { return tr("Ripple"); } QString RippleDistortNode::id() const { return QStringLiteral("org.oliveeditor.Olive.ripple"); } QVector<Node::CategoryID> RippleDistortNode::Category() const { return {kCategoryDistort}; } QString RippleDistortNode::Description() const { return tr("Distorts an image with a ripple effect."); } void RippleDistortNode::Retranslate() { super::Retranslate(); SetInputName(kTextureInput, tr("Input")); SetInputName(kFrequencyInput, tr("Frequency")); SetInputName(kIntensityInput, tr("Intensity")); SetInputName(kEvolutionInput, tr("Evolution")); SetInputName(kPositionInput, tr("Position")); SetInputName(kStretchInput, tr("Stretch")); } ShaderCode RippleDistortNode::GetShaderCode(const ShaderRequest &request) const { Q_UNUSED(request) return ShaderCode(FileFunctions::ReadFileAsString(":/shaders/ripple.frag")); } void RippleDistortNode::Value(const NodeValueRow &value, const NodeGlobals &globals, NodeValueTable *table) const { // If there's no texture, no need to run an operation if (TexturePtr tex = value[kTextureInput].toTexture()) { // Only run shader if at least one of flip or flop are selected if (!qIsNull(value[kIntensityInput].toDouble())) { ShaderJob job(value); job.Insert(QStringLiteral("resolution_in"), NodeValue(NodeValue::kVec2, tex->virtual_resolution(), this)); table->Push(NodeValue::kTexture, tex->toJob(job), this); } else { // If we're not flipping or flopping just push the texture table->Push(value[kTextureInput]); } } } void RippleDistortNode::UpdateGizmoPositions(const NodeValueRow &row, const NodeGlobals &globals) { if (TexturePtr tex = row[kTextureInput].toTexture()) { QPointF half_res(tex->virtual_resolution().x()/2, tex->virtual_resolution().y()/2); gizmo_->SetPoint(half_res + row[kPositionInput].toVec2().toPointF()); } } void RippleDistortNode::GizmoDragMove(double x, double y, const Qt::KeyboardModifiers &modifiers) { NodeInputDragger &x_drag = gizmo_->GetDraggers()[0]; NodeInputDragger &y_drag = gizmo_->GetDraggers()[1]; x_drag.Drag(x_drag.GetStartValue().toDouble() + x); y_drag.Drag(y_drag.GetStartValue().toDouble() + y); } }
4,284
C++
.cpp
101
39.623762
113
0.770212
olive-editor/olive
8,144
552
131
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
19,042
transformdistortnode.cpp
olive-editor_olive/app/node/distort/transform/transformdistortnode.cpp
/*** Olive - Non-Linear Video Editor Copyright (C) 2022 Olive Team 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 <http://www.gnu.org/licenses/>. ***/ #include "transformdistortnode.h" #include <QGuiApplication> namespace olive { const QString TransformDistortNode::kParentInput = QStringLiteral("parent_in"); const QString TransformDistortNode::kTextureInput = QStringLiteral("tex_in"); const QString TransformDistortNode::kAutoscaleInput = QStringLiteral("autoscale_in"); const QString TransformDistortNode::kInterpolationInput = QStringLiteral("interpolation_in"); #define super MatrixGenerator TransformDistortNode::TransformDistortNode() { AddInput(kParentInput, NodeValue::kMatrix); AddInput(kAutoscaleInput, NodeValue::kCombo, 0); AddInput(kInterpolationInput, NodeValue::kCombo, 2); PrependInput(kTextureInput, NodeValue::kTexture, InputFlags(kInputFlagNotKeyframable)); // Initiate gizmos rotation_gizmo_ = AddDraggableGizmo<ScreenGizmo>(); rotation_gizmo_->AddInput(NodeInput(this, kRotationInput)); rotation_gizmo_->SetDragValueBehavior(ScreenGizmo::kAbsolute); poly_gizmo_ = AddDraggableGizmo<PolygonGizmo>(); poly_gizmo_->AddInput(NodeKeyframeTrackReference(NodeInput(this, kPositionInput), 0)); poly_gizmo_->AddInput(NodeKeyframeTrackReference(NodeInput(this, kPositionInput), 1)); anchor_gizmo_ = AddDraggableGizmo<PointGizmo>(); anchor_gizmo_->SetShape(PointGizmo::kAnchorPoint); anchor_gizmo_->AddInput(NodeKeyframeTrackReference(NodeInput(this, kAnchorInput), 0)); anchor_gizmo_->AddInput(NodeKeyframeTrackReference(NodeInput(this, kAnchorInput), 1)); anchor_gizmo_->AddInput(NodeKeyframeTrackReference(NodeInput(this, kPositionInput), 0)); anchor_gizmo_->AddInput(NodeKeyframeTrackReference(NodeInput(this, kPositionInput), 1)); for (int i=0; i<kGizmoScaleCount; i++) { point_gizmo_[i] = AddDraggableGizmo<PointGizmo>(); point_gizmo_[i]->AddInput(NodeKeyframeTrackReference(NodeInput(this, kScaleInput), 0)); point_gizmo_[i]->AddInput(NodeKeyframeTrackReference(NodeInput(this, kScaleInput), 1)); point_gizmo_[i]->SetDragValueBehavior(PointGizmo::kAbsolute); } SetFlag(kVideoEffect); SetEffectInput(kTextureInput); } void TransformDistortNode::Retranslate() { super::Retranslate(); SetInputName(kParentInput, tr("Parent")); SetInputName(kAutoscaleInput, tr("Auto-Scale")); SetInputName(kTextureInput, tr("Texture")); SetInputName(kInterpolationInput, tr("Interpolation")); SetComboBoxStrings(kAutoscaleInput, {tr("None"), tr("Fit"), tr("Fill"), tr("Stretch")}); SetComboBoxStrings(kInterpolationInput, {tr("Nearest Neighbor"), tr("Bilinear"), tr("Mipmapped Bilinear")}); } void TransformDistortNode::Value(const NodeValueRow &value, const NodeGlobals &globals, NodeValueTable *table) const { // Generate matrix QMatrix4x4 generated_matrix = GenerateMatrix(value, false, false, false, value[kParentInput].toMatrix()); // Pop texture NodeValue texture_meta = value[kTextureInput]; TexturePtr job_to_push = nullptr; // If we have a texture, generate a matrix and make it happen if (TexturePtr texture = texture_meta.toTexture()) { // Adjust our matrix by the resolutions involved QMatrix4x4 real_matrix = GenerateAutoScaledMatrix(generated_matrix, value, globals, texture->params()); if (!real_matrix.isIdentity()) { // The matrix will transform things ShaderJob job; job.Insert(QStringLiteral("ove_maintex"), texture_meta); job.Insert(QStringLiteral("ove_mvpmat"), NodeValue(NodeValue::kMatrix, real_matrix, this)); job.SetInterpolation(QStringLiteral("ove_maintex"), static_cast<Texture::Interpolation>(value[kInterpolationInput].toInt())); // Use global resolution rather than texture resolution because this may result in a size change job_to_push = Texture::Job(globals.vparams(), job); } } table->Push(NodeValue::kMatrix, QVariant::fromValue(generated_matrix), this); if (!job_to_push) { // Re-push whatever value we received table->Push(texture_meta); } else { table->Push(NodeValue::kTexture, job_to_push, this); } } ShaderCode TransformDistortNode::GetShaderCode(const ShaderRequest &request) const { Q_UNUSED(request); // Returns default frag and vert shader return ShaderCode(); } void TransformDistortNode::GizmoDragStart(const NodeValueRow &row, double x, double y, const rational &time) { DraggableGizmo *gizmo = static_cast<DraggableGizmo*>(sender()); if (gizmo == anchor_gizmo_) { gizmo_inverted_transform_ = GenerateMatrix(row, true, true, false, row[kParentInput].toMatrix()).toTransform().inverted(); } else if (IsAScaleGizmo(gizmo)) { // Dragging scale handle TexturePtr tex = row[kTextureInput].toTexture(); if (!tex) { return; } gizmo_scale_uniform_ = row[kUniformScaleInput].toBool(); gizmo_anchor_pt_ = (row[kAnchorInput].toVec2() + gizmo->GetGlobals().nonsquare_resolution()/2).toPointF(); if (gizmo == point_gizmo_[kGizmoScaleTopLeft] || gizmo == point_gizmo_[kGizmoScaleTopRight] || gizmo == point_gizmo_[kGizmoScaleBottomLeft] || gizmo == point_gizmo_[kGizmoScaleBottomRight]) { gizmo_scale_axes_ = kGizmoScaleBoth; } else if (gizmo == point_gizmo_[kGizmoScaleCenterLeft] || gizmo == point_gizmo_[kGizmoScaleCenterRight]) { gizmo_scale_axes_ = kGizmoScaleXOnly; } else { gizmo_scale_axes_ = kGizmoScaleYOnly; } // Store texture size VideoParams texture_params = tex->params(); QVector2D texture_sz(texture_params.square_pixel_width(), texture_params.height()); gizmo_scale_anchor_ = row[kAnchorInput].toVec2() + texture_sz/2; if (gizmo == point_gizmo_[kGizmoScaleTopRight] || gizmo == point_gizmo_[kGizmoScaleBottomRight] || gizmo == point_gizmo_[kGizmoScaleCenterRight]) { // Right handles, flip X axis gizmo_scale_anchor_.setX(texture_sz.x() - gizmo_scale_anchor_.x()); } if (gizmo == point_gizmo_[kGizmoScaleBottomLeft] || gizmo == point_gizmo_[kGizmoScaleBottomRight] || gizmo == point_gizmo_[kGizmoScaleBottomCenter]) { // Bottom handles, flip Y axis gizmo_scale_anchor_.setY(texture_sz.y() - gizmo_scale_anchor_.y()); } // Store current matrix gizmo_inverted_transform_ = GenerateMatrix(row, true, true, true, row[kParentInput].toMatrix()).toTransform().inverted(); } else if (gizmo == rotation_gizmo_) { gizmo_anchor_pt_ = (row[kAnchorInput].toVec2() + gizmo->GetGlobals().nonsquare_resolution()/2).toPointF(); gizmo_start_angle_ = std::atan2(y - gizmo_anchor_pt_.y(), x - gizmo_anchor_pt_.x()); gizmo_last_angle_ = gizmo_start_angle_; gizmo_last_alt_angle_ = std::atan2(x - gizmo_anchor_pt_.x(), y - gizmo_anchor_pt_.y()); gizmo_rotate_wrap_ = 0; gizmo_rotate_last_dir_ = kDirectionNone; } } void TransformDistortNode::GizmoDragMove(double x, double y, const Qt::KeyboardModifiers &modifiers) { DraggableGizmo *gizmo = static_cast<DraggableGizmo*>(sender()); if (gizmo == poly_gizmo_) { NodeInputDragger &x_drag = gizmo->GetDraggers()[0]; NodeInputDragger &y_drag = gizmo->GetDraggers()[1]; x_drag.Drag(x_drag.GetStartValue().toDouble() + x); y_drag.Drag(y_drag.GetStartValue().toDouble() + y); } else if (gizmo == anchor_gizmo_) { NodeInputDragger &x_anchor_drag = gizmo->GetDraggers()[0]; NodeInputDragger &y_anchor_drag = gizmo->GetDraggers()[1]; NodeInputDragger &x_pos_drag = gizmo->GetDraggers()[2]; NodeInputDragger &y_pos_drag = gizmo->GetDraggers()[3]; QPointF inverted_movement(gizmo_inverted_transform_.map(QPointF(x, y))); x_anchor_drag.Drag(x_anchor_drag.GetStartValue().toDouble() + inverted_movement.x()); y_anchor_drag.Drag(y_anchor_drag.GetStartValue().toDouble() + inverted_movement.y()); x_pos_drag.Drag(x_pos_drag.GetStartValue().toDouble() + x); y_pos_drag.Drag(y_pos_drag.GetStartValue().toDouble() + y); } else if (gizmo == rotation_gizmo_) { double raw_angle = std::atan2(y - gizmo_anchor_pt_.y(), x - gizmo_anchor_pt_.x()); double alt_angle = std::atan2(x - gizmo_anchor_pt_.x(), y - gizmo_anchor_pt_.y()); double current_angle = raw_angle; // Detect rotation wrap around RotationDirection this_dir = GetDirectionFromAngles(gizmo_last_angle_, raw_angle); RotationDirection alt_dir = GetDirectionFromAngles(gizmo_last_alt_angle_, alt_angle); if (gizmo_rotate_last_dir_ != kDirectionNone && this_dir != gizmo_rotate_last_dir_) { if (alt_dir == gizmo_rotate_last_alt_dir_) { if ((raw_angle - gizmo_last_angle_) < 0) { gizmo_rotate_wrap_++; } else { gizmo_rotate_wrap_--; } this_dir = gizmo_rotate_last_dir_; alt_dir = gizmo_rotate_last_alt_dir_; } } gizmo_rotate_last_dir_ = this_dir; gizmo_rotate_last_alt_dir_ = alt_dir; gizmo_last_angle_ = raw_angle; gizmo_last_alt_angle_ = alt_angle; current_angle += M_PI*2*gizmo_rotate_wrap_; // Convert radians to degrees double rotation_difference = (current_angle - gizmo_start_angle_) * 57.2958; NodeInputDragger &d = gizmo->GetDraggers()[0]; d.Drag(d.GetStartValue().toDouble() + rotation_difference); } else if (IsAScaleGizmo(gizmo)) { QPointF mouse_relative = gizmo_inverted_transform_.map(QPointF(x, y) - gizmo_anchor_pt_); double x_scaled_movement = qAbs(mouse_relative.x() / gizmo_scale_anchor_.x()); double y_scaled_movement = qAbs(mouse_relative.y() / gizmo_scale_anchor_.y()); NodeInputDragger &x_drag = gizmo->GetDraggers()[0]; NodeInputDragger &y_drag = gizmo->GetDraggers()[1]; switch (gizmo_scale_axes_) { case kGizmoScaleXOnly: x_drag.Drag(x_scaled_movement); break; case kGizmoScaleYOnly: if (gizmo_scale_uniform_) { x_drag.Drag(y_scaled_movement); } else { y_drag.Drag(y_scaled_movement); } break; case kGizmoScaleBoth: if (gizmo_scale_uniform_) { double distance = std::hypot(mouse_relative.x(), mouse_relative.y()); double texture_diag = std::hypot(gizmo_scale_anchor_.x(), gizmo_scale_anchor_.y()); x_drag.Drag(qAbs(distance / texture_diag)); } else { x_drag.Drag(x_scaled_movement); y_drag.Drag(y_scaled_movement); } break; } } } QMatrix4x4 TransformDistortNode::AdjustMatrixByResolutions(const QMatrix4x4 &mat, const QVector2D &sequence_res, const QVector2D &texture_res, const QVector2D &offset, AutoScaleType autoscale_type) { // First, create an identity matrix QMatrix4x4 adjusted_matrix; // Scale it to a square based on the sequence's resolution adjusted_matrix.scale(2.0 / sequence_res.x(), 2.0 / sequence_res.y(), 1.0); // Apply offset if applicable adjusted_matrix.translate(offset.x(), offset.y()); // Adjust by the matrix we generated earlier adjusted_matrix *= mat; // Scale back out to texture size (adjusted by pixel aspect) adjusted_matrix.scale(texture_res.x() * 0.5, texture_res.y() * 0.5, 1.0); // If auto-scale is enabled, fit the texture to the sequence (without cropping) if (autoscale_type != kAutoScaleNone) { if (autoscale_type == kAutoScaleStretch) { adjusted_matrix.scale(sequence_res.x() / texture_res.x(), sequence_res.y() / texture_res.y(), 1.0); } else { double footage_real_ar = texture_res.x() / texture_res.y(); double sequence_real_ar = sequence_res.x() / sequence_res.y(); double scale_by_x = sequence_res.x() / texture_res.x(); double scale_by_y = sequence_res.y() / texture_res.y(); double autoscale_val; if ((autoscale_type == kAutoScaleFit) == (sequence_real_ar > footage_real_ar)) { // Scale by height. Either the sequence is wider than the footage or we're using fill and // cutting off the sides autoscale_val = scale_by_y; } else { // Scale by width. Either the footage is wider than the sequence or we're using fill and // cutting off the top and bottom autoscale_val = scale_by_x; } adjusted_matrix.scale(autoscale_val, autoscale_val, 1.0); } } return adjusted_matrix; } void TransformDistortNode::UpdateGizmoPositions(const NodeValueRow &row, const NodeGlobals &globals) { TexturePtr tex = row[kTextureInput].toTexture(); if (!tex) { return; } // Get the sequence resolution const QVector2D &sequence_res = globals.nonsquare_resolution(); QVector2D sequence_half_res = sequence_res * 0.5; QPointF sequence_half_res_pt = sequence_half_res.toPointF(); // GizmoTraverser just returns the sizes of the textures and no other data VideoParams tex_params = tex->params(); QVector2D tex_sz(tex_params.square_pixel_width(), tex_params.height()); QVector2D tex_offset = tex_params.offset(); // Retrieve autoscale value AutoScaleType autoscale = static_cast<AutoScaleType>(row[kAutoscaleInput].toInt()); // Fold values into a matrix for the rectangle QMatrix4x4 rectangle_matrix; rectangle_matrix.scale(sequence_half_res.x(), sequence_half_res.y()); rectangle_matrix *= AdjustMatrixByResolutions(GenerateMatrix(row, false, false, false, row[kParentInput].toMatrix()), sequence_res, tex_sz, tex_offset, autoscale); // Create rect and transform it const QVector<QPointF> points = {QPointF(-1, -1), QPointF(1, -1), QPointF(1, 1), QPointF(-1, 1), QPointF(-1, -1)}; QTransform rectangle_transform = rectangle_matrix.toTransform(); QPolygonF r = rectangle_transform.map(points); r.translate(sequence_half_res_pt); poly_gizmo_->SetPolygon(r); // Draw anchor point QMatrix4x4 anchor_matrix; anchor_matrix.scale(sequence_half_res.x(), sequence_half_res.y()); anchor_matrix *= AdjustMatrixByResolutions(GenerateMatrix(row, true, false, false, row[kParentInput].toMatrix()), sequence_res, tex_sz, tex_offset, autoscale); anchor_gizmo_->SetPoint(anchor_matrix.toTransform().map(QPointF(0, 0)) + sequence_half_res_pt); // Draw scale handles point_gizmo_[kGizmoScaleTopLeft]->SetPoint(CreateScalePoint(-1, -1, sequence_half_res_pt, rectangle_matrix)); point_gizmo_[kGizmoScaleTopCenter]->SetPoint(CreateScalePoint( 0, -1, sequence_half_res_pt, rectangle_matrix)); point_gizmo_[kGizmoScaleTopRight]->SetPoint(CreateScalePoint( 1, -1, sequence_half_res_pt, rectangle_matrix)); point_gizmo_[kGizmoScaleBottomLeft]->SetPoint(CreateScalePoint(-1, 1, sequence_half_res_pt, rectangle_matrix)); point_gizmo_[kGizmoScaleBottomCenter]->SetPoint(CreateScalePoint( 0, 1, sequence_half_res_pt, rectangle_matrix)); point_gizmo_[kGizmoScaleBottomRight]->SetPoint(CreateScalePoint( 1, 1, sequence_half_res_pt, rectangle_matrix)); point_gizmo_[kGizmoScaleCenterLeft]->SetPoint(CreateScalePoint(-1, 0, sequence_half_res_pt, rectangle_matrix)); point_gizmo_[kGizmoScaleCenterRight]->SetPoint(CreateScalePoint( 1, 0, sequence_half_res_pt, rectangle_matrix)); // Use offsets to make the appearance of values that start in the top left, even though we // really anchor around the center SetInputProperty(kPositionInput, QStringLiteral("offset"), sequence_half_res + tex_offset); SetInputProperty(kAnchorInput, QStringLiteral("offset"), tex_sz * 0.5); } QTransform TransformDistortNode::GizmoTransformation(const NodeValueRow &row, const NodeGlobals &globals) const { if (TexturePtr texture = row[kTextureInput].toTexture()) { //auto m = GenerateMatrix(row, false, false, false, row[kParentInput].toMatrix()); auto m = GenerateMatrix(row, false, false, false, QMatrix4x4()); return GenerateAutoScaledMatrix(m, row, globals, texture->params()).toTransform(); } return super::GizmoTransformation(row, globals); } QPointF TransformDistortNode::CreateScalePoint(double x, double y, const QPointF &half_res, const QMatrix4x4 &mat) { return mat.map(QPointF(x, y)) + half_res; } QMatrix4x4 TransformDistortNode::GenerateAutoScaledMatrix(const QMatrix4x4& generated_matrix, const NodeValueRow& value, const NodeGlobals &globals, const VideoParams& texture_params) const { const QVector2D &sequence_res = globals.nonsquare_resolution(); QVector2D texture_res(texture_params.square_pixel_width(), texture_params.height()); AutoScaleType autoscale = static_cast<AutoScaleType>(value[kAutoscaleInput].toInt()); return AdjustMatrixByResolutions(generated_matrix, sequence_res, texture_res, texture_params.offset(), autoscale); } bool TransformDistortNode::IsAScaleGizmo(NodeGizmo *g) const { for (int i=0; i<kGizmoScaleCount; i++) { if (point_gizmo_[i] == g) { return true; } } return false; } TransformDistortNode::RotationDirection TransformDistortNode::GetDirectionFromAngles(double last, double current) { return (current > last) ? kDirectionPositive : kDirectionNegative; } }
18,093
C++
.cpp
351
45.270655
197
0.696214
olive-editor/olive
8,144
552
131
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
19,043
tiledistortnode.cpp
olive-editor_olive/app/node/distort/tile/tiledistortnode.cpp
/*** Olive - Non-Linear Video Editor Copyright (C) 2022 Olive Team 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 <http://www.gnu.org/licenses/>. ***/ #include "tiledistortnode.h" #include "widget/slider/floatslider.h" namespace olive { const QString TileDistortNode::kTextureInput = QStringLiteral("tex_in"); const QString TileDistortNode::kScaleInput = QStringLiteral("scale_in"); const QString TileDistortNode::kPositionInput = QStringLiteral("position_in"); const QString TileDistortNode::kAnchorInput = QStringLiteral("anchor_in"); const QString TileDistortNode::kMirrorXInput = QStringLiteral("mirrorx_in"); const QString TileDistortNode::kMirrorYInput = QStringLiteral("mirrory_in"); #define super Node TileDistortNode::TileDistortNode() { AddInput(kTextureInput, NodeValue::kTexture, InputFlags(kInputFlagNotKeyframable)); AddInput(kScaleInput, NodeValue::kFloat, 0.5); SetInputProperty(kScaleInput, QStringLiteral("min"), 0); SetInputProperty(kScaleInput, QStringLiteral("view"), FloatSlider::kPercentage); AddInput(kPositionInput, NodeValue::kVec2, QVector2D(0, 0)); AddInput(kAnchorInput, NodeValue::kCombo, kMiddleCenter); AddInput(kMirrorXInput, NodeValue::kBoolean, false); AddInput(kMirrorYInput, NodeValue::kBoolean, false); SetFlag(kVideoEffect); SetEffectInput(kTextureInput); gizmo_ = AddDraggableGizmo<PointGizmo>({ NodeKeyframeTrackReference(NodeInput(this, kPositionInput), 0), NodeKeyframeTrackReference(NodeInput(this, kPositionInput), 1), }); gizmo_->SetShape(PointGizmo::kAnchorPoint); } QString TileDistortNode::Name() const { return tr("Tile"); } QString TileDistortNode::id() const { return QStringLiteral("org.oliveeditor.Olive.tile"); } QVector<Node::CategoryID> TileDistortNode::Category() const { return {kCategoryDistort}; } QString TileDistortNode::Description() const { return tr("Infinitely tile an image horizontally and vertically."); } void TileDistortNode::Retranslate() { super::Retranslate(); SetInputName(kTextureInput, tr("Input")); SetInputName(kScaleInput, tr("Scale")); SetInputName(kPositionInput, tr("Position")); SetInputName(kMirrorXInput, tr("Mirror Horizontally")); SetInputName(kMirrorYInput, tr("Mirror Vertically")); SetInputName(kAnchorInput, tr("Anchor")); SetComboBoxStrings(kAnchorInput, { tr("Top-Left"), tr("Top-Center"), tr("Top-Right"), tr("Middle-Left"), tr("Middle-Center"), tr("Middle-Right"), tr("Bottom-Left"), tr("Bottom-Center"), tr("Bottom-Right"), }); } ShaderCode TileDistortNode::GetShaderCode(const ShaderRequest &request) const { Q_UNUSED(request) return ShaderCode(FileFunctions::ReadFileAsString(":/shaders/tile.frag")); } void TileDistortNode::Value(const NodeValueRow &value, const NodeGlobals &globals, NodeValueTable *table) const { // If there's no texture, no need to run an operation if (TexturePtr tex = value[kTextureInput].toTexture()) { // Only run shader if at least one of flip or flop are selected if (!qFuzzyCompare(value[kScaleInput].toDouble(), 1.0)) { ShaderJob job(value); job.Insert(QStringLiteral("resolution_in"), NodeValue(NodeValue::kVec2, tex->virtual_resolution(), this)); table->Push(NodeValue::kTexture, tex->toJob(job), this); } else { // If we're not flipping or flopping just push the texture table->Push(value[kTextureInput]); } } } void TileDistortNode::UpdateGizmoPositions(const NodeValueRow &row, const NodeGlobals &globals) { if (TexturePtr tex = row[kTextureInput].toTexture()) { QPointF res = tex->virtual_resolution().toPointF(); QPointF pos = row[kPositionInput].toVec2().toPointF(); qreal x = pos.x(); qreal y = pos.y(); Anchor a = static_cast<Anchor>(row[kAnchorInput].toInt()); if (a == kTopLeft || a == kTopCenter || a == kTopRight) { // Do nothing } else if (a == kMiddleLeft || a == kMiddleCenter || a == kMiddleRight) { y += res.y()/2; } else if (a == kBottomLeft || a == kBottomCenter || a == kBottomRight) { y += res.y(); } if (a == kTopLeft || a == kMiddleLeft || a == kBottomLeft) { // Do nothing } else if (a == kTopCenter || a == kMiddleCenter || a == kBottomCenter) { x += res.x()/2; } else if (a == kTopRight || a == kMiddleRight || a == kBottomRight) { x += res.x(); } gizmo_->SetPoint(QPointF(x, y)); } } void TileDistortNode::GizmoDragMove(double x, double y, const Qt::KeyboardModifiers &modifiers) { NodeInputDragger &x_drag = gizmo_->GetDraggers()[0]; NodeInputDragger &y_drag = gizmo_->GetDraggers()[1]; x_drag.Drag(x_drag.GetStartValue().toDouble() + x); y_drag.Drag(y_drag.GetStartValue().toDouble() + y); } }
5,298
C++
.cpp
132
36.772727
112
0.727892
olive-editor/olive
8,144
552
131
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
19,044
cropdistortnode.cpp
olive-editor_olive/app/node/distort/crop/cropdistortnode.cpp
/*** Olive - Non-Linear Video Editor Copyright (C) 2022 Olive Team 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 <http://www.gnu.org/licenses/>. ***/ #include "cropdistortnode.h" #include "common/util.h" #include "core.h" #include "widget/slider/floatslider.h" namespace olive { const QString CropDistortNode::kTextureInput = QStringLiteral("tex_in"); const QString CropDistortNode::kLeftInput = QStringLiteral("left_in"); const QString CropDistortNode::kTopInput = QStringLiteral("top_in"); const QString CropDistortNode::kRightInput = QStringLiteral("right_in"); const QString CropDistortNode::kBottomInput = QStringLiteral("bottom_in"); const QString CropDistortNode::kFeatherInput = QStringLiteral("feather_in"); #define super Node CropDistortNode::CropDistortNode() { AddInput(kTextureInput, NodeValue::kTexture, InputFlags(kInputFlagNotKeyframable)); CreateCropSideInput(kLeftInput); CreateCropSideInput(kTopInput); CreateCropSideInput(kRightInput); CreateCropSideInput(kBottomInput); AddInput(kFeatherInput, NodeValue::kFloat, 0.0); SetInputProperty(kFeatherInput, QStringLiteral("min"), 0.0); // Initiate gizmos poly_gizmo_ = AddDraggableGizmo<PolygonGizmo>({kLeftInput, kTopInput, kRightInput, kBottomInput}); point_gizmo_[kGizmoScaleTopLeft] = AddDraggableGizmo<PointGizmo>({kLeftInput, kTopInput}); point_gizmo_[kGizmoScaleTopCenter] = AddDraggableGizmo<PointGizmo>({kTopInput}); point_gizmo_[kGizmoScaleTopRight] = AddDraggableGizmo<PointGizmo>({kRightInput, kTopInput}); point_gizmo_[kGizmoScaleBottomLeft] = AddDraggableGizmo<PointGizmo>({kLeftInput, kBottomInput}); point_gizmo_[kGizmoScaleBottomCenter] = AddDraggableGizmo<PointGizmo>({kBottomInput}); point_gizmo_[kGizmoScaleBottomRight] = AddDraggableGizmo<PointGizmo>({kRightInput, kBottomInput}); point_gizmo_[kGizmoScaleCenterLeft] = AddDraggableGizmo<PointGizmo>({kLeftInput}); point_gizmo_[kGizmoScaleCenterRight] = AddDraggableGizmo<PointGizmo>({kRightInput}); SetFlag(kVideoEffect); SetEffectInput(kTextureInput); } void CropDistortNode::Retranslate() { super::Retranslate(); SetInputName(kTextureInput, tr("Texture")); SetInputName(kLeftInput, tr("Left")); SetInputName(kTopInput, tr("Top")); SetInputName(kRightInput, tr("Right")); SetInputName(kBottomInput, tr("Bottom")); SetInputName(kFeatherInput, tr("Feather")); } void CropDistortNode::Value(const NodeValueRow &value, const NodeGlobals &globals, NodeValueTable *table) const { ShaderJob job; job.Insert(value); if (TexturePtr texture = job.Get(kTextureInput).toTexture()) { job.Insert(QStringLiteral("resolution_in"), NodeValue(NodeValue::kVec2, QVector2D(texture->params().width(), texture->params().height()), this)); if (!qIsNull(job.Get(kLeftInput).toDouble()) || !qIsNull(job.Get(kRightInput).toDouble()) || !qIsNull(job.Get(kTopInput).toDouble()) || !qIsNull(job.Get(kBottomInput).toDouble())) { table->Push(NodeValue::kTexture, texture->toJob(job), this); } else { table->Push(job.Get(kTextureInput)); } } } ShaderCode CropDistortNode::GetShaderCode(const ShaderRequest &request) const { Q_UNUSED(request) return ShaderCode(FileFunctions::ReadFileAsString(QStringLiteral(":/shaders/crop.frag"))); } void CropDistortNode::UpdateGizmoPositions(const NodeValueRow &row, const NodeGlobals &globals) { if (TexturePtr tex = row[kTextureInput].toTexture()) { const QVector2D &resolution = tex->virtual_resolution(); temp_resolution_ = resolution; double left_pt = resolution.x() * row[kLeftInput].toDouble(); double top_pt = resolution.y() * row[kTopInput].toDouble(); double right_pt = resolution.x() * (1.0 - row[kRightInput].toDouble()); double bottom_pt = resolution.y() * (1.0 - row[kBottomInput].toDouble()); double center_x_pt = mid(left_pt, right_pt); double center_y_pt = mid(top_pt, bottom_pt); point_gizmo_[kGizmoScaleTopLeft]->SetPoint(QPointF(left_pt, top_pt)); point_gizmo_[kGizmoScaleTopCenter]->SetPoint(QPointF(center_x_pt, top_pt)); point_gizmo_[kGizmoScaleTopRight]->SetPoint(QPointF(right_pt, top_pt)); point_gizmo_[kGizmoScaleBottomLeft]->SetPoint(QPointF(left_pt, bottom_pt)); point_gizmo_[kGizmoScaleBottomCenter]->SetPoint(QPointF(center_x_pt, bottom_pt)); point_gizmo_[kGizmoScaleBottomRight]->SetPoint(QPointF(right_pt, bottom_pt)); point_gizmo_[kGizmoScaleCenterLeft]->SetPoint(QPointF(left_pt, center_y_pt)); point_gizmo_[kGizmoScaleCenterRight]->SetPoint(QPointF(right_pt, center_y_pt)); poly_gizmo_->SetPolygon(QRectF(left_pt, top_pt, right_pt - left_pt, bottom_pt - top_pt)); } } void CropDistortNode::GizmoDragMove(double x_diff, double y_diff, const Qt::KeyboardModifiers &modifiers) { DraggableGizmo *gizmo = static_cast<DraggableGizmo*>(sender()); QVector2D res = temp_resolution_; x_diff /= res.x(); y_diff /= res.y(); for (int j=0; j<gizmo->GetDraggers().size(); j++) { NodeInputDragger& i = gizmo->GetDraggers()[j]; double s = i.GetStartValue().toDouble(); if (i.GetInput().input().input() == kLeftInput) { i.Drag(s + x_diff); } else if (i.GetInput().input().input() == kTopInput) { i.Drag(s + y_diff); } else if (i.GetInput().input().input() == kRightInput) { i.Drag(s - x_diff); } else if (i.GetInput().input().input() == kBottomInput) { i.Drag(s - y_diff); } } } void CropDistortNode::CreateCropSideInput(const QString &id) { AddInput(id, NodeValue::kFloat, 0.0); SetInputProperty(id, QStringLiteral("min"), 0.0); SetInputProperty(id, QStringLiteral("max"), 1.0); SetInputProperty(id, QStringLiteral("view"), FloatSlider::kPercentage); } }
6,262
C++
.cpp
129
45.100775
149
0.744674
olive-editor/olive
8,144
552
131
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
19,045
swirldistortnode.cpp
olive-editor_olive/app/node/distort/swirl/swirldistortnode.cpp
/*** Olive - Non-Linear Video Editor Copyright (C) 2022 Olive Team 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 <http://www.gnu.org/licenses/>. ***/ #include "swirldistortnode.h" namespace olive { const QString SwirlDistortNode::kTextureInput = QStringLiteral("tex_in"); const QString SwirlDistortNode::kRadiusInput = QStringLiteral("radius_in"); const QString SwirlDistortNode::kAngleInput = QStringLiteral("angle_in"); const QString SwirlDistortNode::kPositionInput = QStringLiteral("pos_in"); #define super Node SwirlDistortNode::SwirlDistortNode() { AddInput(kTextureInput, NodeValue::kTexture, InputFlags(kInputFlagNotKeyframable)); AddInput(kRadiusInput, NodeValue::kFloat, 200); SetInputProperty(kRadiusInput, QStringLiteral("min"), 0); AddInput(kAngleInput, NodeValue::kFloat, 10); SetInputProperty(kAngleInput, QStringLiteral("base"), 0.1); AddInput(kPositionInput, NodeValue::kVec2, QVector2D(0, 0)); SetFlag(kVideoEffect); SetEffectInput(kTextureInput); gizmo_ = AddDraggableGizmo<PointGizmo>({ NodeKeyframeTrackReference(NodeInput(this, kPositionInput), 0), NodeKeyframeTrackReference(NodeInput(this, kPositionInput), 1), }); gizmo_->SetShape(PointGizmo::kAnchorPoint); } QString SwirlDistortNode::Name() const { return tr("Swirl"); } QString SwirlDistortNode::id() const { return QStringLiteral("org.oliveeditor.Olive.swirl"); } QVector<Node::CategoryID> SwirlDistortNode::Category() const { return {kCategoryDistort}; } QString SwirlDistortNode::Description() const { return tr("Distorts an image along a sine wave."); } void SwirlDistortNode::Retranslate() { super::Retranslate(); SetInputName(kTextureInput, tr("Input")); SetInputName(kRadiusInput, tr("Radius")); SetInputName(kAngleInput, tr("Angle")); SetInputName(kPositionInput, tr("Position")); } ShaderCode SwirlDistortNode::GetShaderCode(const ShaderRequest &request) const { Q_UNUSED(request) return ShaderCode(FileFunctions::ReadFileAsString(":/shaders/swirl.frag")); } void SwirlDistortNode::Value(const NodeValueRow &value, const NodeGlobals &globals, NodeValueTable *table) const { // If there's no texture, no need to run an operation if (TexturePtr tex = value[kTextureInput].toTexture()) { // Only run shader if at least one of flip or flop are selected if (!qIsNull(value[kAngleInput].toDouble()) && !qIsNull(value[kRadiusInput].toDouble())) { ShaderJob job(value); job.Insert(QStringLiteral("resolution_in"), NodeValue(NodeValue::kVec2, tex->virtual_resolution(), this)); table->Push(NodeValue::kTexture, tex->toJob(job), this); } else { // If we're not flipping or flopping just push the texture table->Push(value[kTextureInput]); } } } void SwirlDistortNode::UpdateGizmoPositions(const NodeValueRow &row, const NodeGlobals &globals) { QPointF half_res(globals.square_resolution().x()/2, globals.square_resolution().y()/2); gizmo_->SetPoint(half_res + row[kPositionInput].toVec2().toPointF()); } void SwirlDistortNode::GizmoDragMove(double x, double y, const Qt::KeyboardModifiers &modifiers) { NodeInputDragger &x_drag = gizmo_->GetDraggers()[0]; NodeInputDragger &y_drag = gizmo_->GetDraggers()[1]; x_drag.Drag(x_drag.GetStartValue().toDouble() + x); y_drag.Drag(y_drag.GetStartValue().toDouble() + y); } }
3,894
C++
.cpp
94
38.638298
112
0.765376
olive-editor/olive
8,144
552
131
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
19,046
mask.cpp
olive-editor_olive/app/node/distort/mask/mask.cpp
/*** Olive - Non-Linear Video Editor Copyright (C) 2022 Olive Team 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 <http://www.gnu.org/licenses/>. ***/ #include "mask.h" #include "node/filter/blur/blur.h" namespace olive { #define super PolygonGenerator const QString MaskDistortNode::kFeatherInput = QStringLiteral("feather_in"); const QString MaskDistortNode::kInvertInput = QStringLiteral("invert_in"); MaskDistortNode::MaskDistortNode() { // Mask should always be (1.0, 1.0, 1.0) for multiply to work correctly SetInputFlag(kColorInput, kInputFlagHidden); AddInput(kInvertInput, NodeValue::kBoolean, false); AddInput(kFeatherInput, NodeValue::kFloat, 0.0); SetInputProperty(kFeatherInput, QStringLiteral("min"), 0.0); } ShaderCode MaskDistortNode::GetShaderCode(const ShaderRequest &request) const { if (request.id == QStringLiteral("mrg")) { return ShaderCode(FileFunctions::ReadFileAsString(QStringLiteral(":/shaders/multiply.frag"))); } else if (request.id == QStringLiteral("feather")) { return ShaderCode(FileFunctions::ReadFileAsString(QStringLiteral(":/shaders/blur.frag"))); } else if (request.id == QStringLiteral("invert")) { return ShaderCode(FileFunctions::ReadFileAsString(QStringLiteral(":/shaders/invertrgba.frag"))); } else { return super::GetShaderCode(request); } } void MaskDistortNode::Retranslate() { super::Retranslate(); SetInputName(kBaseInput, tr("Texture")); SetInputName(kInvertInput, tr("Invert")); SetInputName(kFeatherInput, tr("Feather")); } void MaskDistortNode::Value(const NodeValueRow &value, const NodeGlobals &globals, NodeValueTable *table) const { TexturePtr texture = value[kBaseInput].toTexture(); VideoParams job_params = texture ? texture->params() : globals.vparams(); NodeValue job(NodeValue::kTexture, Texture::Job(job_params, GetGenerateJob(value, job_params)), this); if (value[kInvertInput].toBool()) { ShaderJob invert; invert.SetShaderID(QStringLiteral("invert")); invert.Insert(QStringLiteral("tex_in"), job); job.set_value(Texture::Job(job_params, invert)); } if (texture) { // Push as merge node ShaderJob merge; merge.SetShaderID(QStringLiteral("mrg")); merge.Insert(QStringLiteral("tex_a"), value[kBaseInput]); if (value[kFeatherInput].toDouble() > 0.0) { // Nest a blur shader in there too ShaderJob feather; feather.SetShaderID(QStringLiteral("feather")); feather.Insert(BlurFilterNode::kTextureInput, job); feather.Insert(BlurFilterNode::kMethodInput, NodeValue(NodeValue::kInt, int(BlurFilterNode::kGaussian), this)); feather.Insert(BlurFilterNode::kHorizInput, NodeValue(NodeValue::kBoolean, true, this)); feather.Insert(BlurFilterNode::kVertInput, NodeValue(NodeValue::kBoolean, true, this)); feather.Insert(BlurFilterNode::kRepeatEdgePixelsInput, NodeValue(NodeValue::kBoolean, true, this)); feather.Insert(BlurFilterNode::kRadiusInput, NodeValue(NodeValue::kFloat, value[kFeatherInput].toDouble(), this)); feather.SetIterations(2, BlurFilterNode::kTextureInput); feather.Insert(QStringLiteral("resolution_in"), NodeValue(NodeValue::kVec2, texture ? texture->virtual_resolution() : globals.square_resolution(), this)); merge.Insert(QStringLiteral("tex_b"), NodeValue(NodeValue::kTexture, Texture::Job(job_params, feather), this)); } else { merge.Insert(QStringLiteral("tex_b"), job); } table->Push(NodeValue::kTexture, Texture::Job(job_params, merge), this); } else { table->Push(job); } } }
4,129
C++
.cpp
85
44.752941
160
0.749876
olive-editor/olive
8,144
552
131
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
19,047
flipdistortnode.cpp
olive-editor_olive/app/node/distort/flip/flipdistortnode.cpp
/*** Olive - Non-Linear Video Editor Copyright (C) 2022 Olive Team 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 <http://www.gnu.org/licenses/>. ***/ #include "flipdistortnode.h" namespace olive { const QString FlipDistortNode::kTextureInput = QStringLiteral("tex_in"); const QString FlipDistortNode::kHorizontalInput = QStringLiteral("horiz_in"); const QString FlipDistortNode::kVerticalInput = QStringLiteral("vert_in"); #define super Node FlipDistortNode::FlipDistortNode() { AddInput(kTextureInput, NodeValue::kTexture, InputFlags(kInputFlagNotKeyframable)); AddInput(kHorizontalInput, NodeValue::kBoolean, false); AddInput(kVerticalInput, NodeValue::kBoolean, false); SetFlag(kVideoEffect); SetEffectInput(kTextureInput); } QString FlipDistortNode::Name() const { return tr("Flip"); } QString FlipDistortNode::id() const { return QStringLiteral("org.oliveeditor.Olive.flip"); } QVector<Node::CategoryID> FlipDistortNode::Category() const { return {kCategoryDistort}; } QString FlipDistortNode::Description() const { return tr("Flips an image horizontally or vertically"); } void FlipDistortNode::Retranslate() { super::Retranslate(); SetInputName(kTextureInput, tr("Input")); SetInputName(kHorizontalInput, tr("Horizontal")); SetInputName(kVerticalInput, tr("Vertical")); } ShaderCode FlipDistortNode::GetShaderCode(const ShaderRequest &request) const { Q_UNUSED(request) return ShaderCode(FileFunctions::ReadFileAsString(":/shaders/flip.frag")); } void FlipDistortNode::Value(const NodeValueRow &value, const NodeGlobals &globals, NodeValueTable *table) const { // If there's no texture, no need to run an operation if (TexturePtr tex = value[kTextureInput].toTexture()) { // Only run shader if at least one of flip or flop are selected if (value[kHorizontalInput].toBool() || value[kVerticalInput].toBool()) { table->Push(NodeValue::kTexture, tex->toJob(ShaderJob(value)), this); } else { // If we're not flipping or flopping just push the texture table->Push(value[kTextureInput]); } } } }
2,646
C++
.cpp
70
35.142857
111
0.773688
olive-editor/olive
8,144
552
131
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
19,048
wavedistortnode.cpp
olive-editor_olive/app/node/distort/wave/wavedistortnode.cpp
/*** Olive - Non-Linear Video Editor Copyright (C) 2022 Olive Team 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 <http://www.gnu.org/licenses/>. ***/ #include "wavedistortnode.h" namespace olive { const QString WaveDistortNode::kTextureInput = QStringLiteral("tex_in"); const QString WaveDistortNode::kFrequencyInput = QStringLiteral("frequency_in"); const QString WaveDistortNode::kIntensityInput = QStringLiteral("intensity_in"); const QString WaveDistortNode::kEvolutionInput = QStringLiteral("evolution_in"); const QString WaveDistortNode::kVerticalInput = QStringLiteral("vertical_in"); #define super Node WaveDistortNode::WaveDistortNode() { AddInput(kTextureInput, NodeValue::kTexture, InputFlags(kInputFlagNotKeyframable)); AddInput(kFrequencyInput, NodeValue::kFloat, 10); AddInput(kIntensityInput, NodeValue::kFloat, 10); AddInput(kEvolutionInput, NodeValue::kFloat, 0); AddInput(kVerticalInput, NodeValue::kCombo, false); SetFlag(kVideoEffect); SetEffectInput(kTextureInput); } QString WaveDistortNode::Name() const { return tr("Wave"); } QString WaveDistortNode::id() const { return QStringLiteral("org.oliveeditor.Olive.wave"); } QVector<Node::CategoryID> WaveDistortNode::Category() const { return {kCategoryDistort}; } QString WaveDistortNode::Description() const { return tr("Distorts an image along a sine wave."); } void WaveDistortNode::Retranslate() { super::Retranslate(); SetInputName(kTextureInput, tr("Input")); SetInputName(kFrequencyInput, tr("Frequency")); SetInputName(kIntensityInput, tr("Intensity")); SetInputName(kEvolutionInput, tr("Evolution")); SetInputName(kVerticalInput, tr("Direction")); SetComboBoxStrings(kVerticalInput, {tr("Horizontal"), tr("Vertical")}); } ShaderCode WaveDistortNode::GetShaderCode(const ShaderRequest &request) const { Q_UNUSED(request) return ShaderCode(FileFunctions::ReadFileAsString(":/shaders/wave.frag")); } void WaveDistortNode::Value(const NodeValueRow &value, const NodeGlobals &globals, NodeValueTable *table) const { // If there's no texture, no need to run an operation if (TexturePtr texture = value[kTextureInput].toTexture()) { // Only run shader if at least one of flip or flop are selected if (!qIsNull(value[kIntensityInput].toDouble())) { table->Push(NodeValue::kTexture, Texture::Job(texture->params(), ShaderJob(value)), this); } else { // If we're not flipping or flopping just push the texture table->Push(value[kTextureInput]); } } } }
3,081
C++
.cpp
77
37.363636
111
0.775579
olive-editor/olive
8,144
552
131
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
19,049
mosaicfilternode.cpp
olive-editor_olive/app/node/filter/mosaic/mosaicfilternode.cpp
/*** Olive - Non-Linear Video Editor Copyright (C) 2022 Olive Team 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 <http://www.gnu.org/licenses/>. ***/ #include "mosaicfilternode.h" namespace olive { const QString MosaicFilterNode::kTextureInput = QStringLiteral("tex_in"); const QString MosaicFilterNode::kHorizInput = QStringLiteral("horiz_in"); const QString MosaicFilterNode::kVertInput = QStringLiteral("vert_in"); #define super Node MosaicFilterNode::MosaicFilterNode() { AddInput(kTextureInput, NodeValue::kTexture, InputFlags(kInputFlagNotKeyframable)); AddInput(kHorizInput, NodeValue::kFloat, 32.0); SetInputProperty(kHorizInput, QStringLiteral("min"), 1.0); AddInput(kVertInput, NodeValue::kFloat, 18.0); SetInputProperty(kVertInput, QStringLiteral("min"), 1.0); SetFlag(kVideoEffect); SetEffectInput(kTextureInput); } void MosaicFilterNode::Retranslate() { super::Retranslate(); SetInputName(kTextureInput, tr("Texture")); SetInputName(kHorizInput, tr("Horizontal")); SetInputName(kVertInput, tr("Vertical")); } void MosaicFilterNode::Value(const NodeValueRow &value, const NodeGlobals &globals, NodeValueTable *table) const { if (TexturePtr texture = value[kTextureInput].toTexture()) { if (texture && value[kHorizInput].toInt() != texture->width() && value[kVertInput].toInt() != texture->height()) { ShaderJob job(value); // Mipmapping makes this look weird, so we just use bilinear for finding the color of each block job.SetInterpolation(kTextureInput, Texture::kLinear); table->Push(NodeValue::kTexture, texture->toJob(job), this); } else { table->Push(value[kTextureInput]); } } } ShaderCode MosaicFilterNode::GetShaderCode(const ShaderRequest &request) const { Q_UNUSED(request) return ShaderCode(FileFunctions::ReadFileAsString(":/shaders/mosaic.frag")); } }
2,443
C++
.cpp
58
38.827586
112
0.762267
olive-editor/olive
8,144
552
131
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
19,050
blur.cpp
olive-editor_olive/app/node/filter/blur/blur.cpp
/*** Olive - Non-Linear Video Editor Copyright (C) 2022 Olive Team 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 <http://www.gnu.org/licenses/>. ***/ #include "blur.h" namespace olive { const QString BlurFilterNode::kTextureInput = QStringLiteral("tex_in"); const QString BlurFilterNode::kMethodInput = QStringLiteral("method_in"); const QString BlurFilterNode::kRadiusInput = QStringLiteral("radius_in"); const QString BlurFilterNode::kHorizInput = QStringLiteral("horiz_in"); const QString BlurFilterNode::kVertInput = QStringLiteral("vert_in"); const QString BlurFilterNode::kRepeatEdgePixelsInput = QStringLiteral("repeat_edge_pixels_in"); const QString BlurFilterNode::kDirectionalDegreesInput = QStringLiteral("directional_degrees_in"); const QString BlurFilterNode::kRadialCenterInput = QStringLiteral("radial_center_in"); #define super Node BlurFilterNode::BlurFilterNode() { AddInput(kTextureInput, NodeValue::kTexture, InputFlags(kInputFlagNotKeyframable)); Method default_method = kGaussian; AddInput(kMethodInput, NodeValue::kCombo, default_method, InputFlags(kInputFlagNotKeyframable | kInputFlagNotConnectable)); AddInput(kRadiusInput, NodeValue::kFloat, 10.0); SetInputProperty(kRadiusInput, QStringLiteral("min"), 0.0); { // Box and gaussian only AddInput(kHorizInput, NodeValue::kBoolean, true); AddInput(kVertInput, NodeValue::kBoolean, true); } { // Directional only AddInput(kDirectionalDegreesInput, NodeValue::kFloat, 0.0); } { // Radial only AddInput(kRadialCenterInput, NodeValue::kVec2, QVector2D(0, 0)); } UpdateInputs(default_method); AddInput(kRepeatEdgePixelsInput, NodeValue::kBoolean, true); SetFlag(kVideoEffect); SetEffectInput(kTextureInput); radial_center_gizmo_ = AddDraggableGizmo<PointGizmo>(); radial_center_gizmo_->SetShape(PointGizmo::kAnchorPoint); radial_center_gizmo_->AddInput(NodeKeyframeTrackReference(NodeInput(this, kRadialCenterInput), 0)); radial_center_gizmo_->AddInput(NodeKeyframeTrackReference(NodeInput(this, kRadialCenterInput), 1)); } QString BlurFilterNode::Name() const { return tr("Blur"); } QString BlurFilterNode::id() const { return QStringLiteral("org.olivevideoeditor.Olive.blur"); } QVector<Node::CategoryID> BlurFilterNode::Category() const { return {kCategoryFilter}; } QString BlurFilterNode::Description() const { return tr("Blurs an image."); } void BlurFilterNode::Retranslate() { super::Retranslate(); SetInputName(kTextureInput, tr("Input")); SetInputName(kMethodInput, tr("Method")); SetComboBoxStrings(kMethodInput, { tr("Box"), tr("Gaussian"), tr("Directional"), tr("Radial") }); SetInputName(kRadiusInput, tr("Radius")); SetInputName(kHorizInput, tr("Horizontal")); SetInputName(kVertInput, tr("Vertical")); SetInputName(kRepeatEdgePixelsInput, tr("Repeat Edge Pixels")); SetInputName(kDirectionalDegreesInput, tr("Direction")); SetInputName(kRadialCenterInput, tr("Center")); } ShaderCode BlurFilterNode::GetShaderCode(const ShaderRequest &request) const { Q_UNUSED(request) return ShaderCode(FileFunctions::ReadFileAsString(":/shaders/blur.frag")); } void BlurFilterNode::Value(const NodeValueRow &value, const NodeGlobals &globals, NodeValueTable *table) const { // If there's no texture, no need to run an operation if (TexturePtr tex = value[kTextureInput].toTexture()) { Method method = static_cast<Method>(value[kMethodInput].toInt()); bool can_push_job = true; int iterations = 1; // Check if radius is > 0 if (value[kRadiusInput].toDouble() > 0.0) { // Method-specific considerations switch (method) { case kBox: case kGaussian: { bool horiz = value[kHorizInput].toBool(); bool vert = value[kVertInput].toBool(); if (!horiz && !vert) { // Disable job if horiz and vert are unchecked can_push_job = false; } else if (horiz && vert) { // Set iteration count to 2 if we're blurring both horizontally and vertically iterations = 2; } break; } case kDirectional: case kRadial: break; } } else { can_push_job = false; } if (can_push_job) { ShaderJob job(value); job.Insert(QStringLiteral("resolution_in"), NodeValue(NodeValue::kVec2, tex->virtual_resolution(), this)); job.SetIterations(iterations, kTextureInput); table->Push(NodeValue::kTexture, tex->toJob(job), this); } else { // If we're not performing the blur job, just push the texture table->Push(value[kTextureInput]); } } } void BlurFilterNode::UpdateGizmoPositions(const NodeValueRow &row, const NodeGlobals &globals) { if (TexturePtr tex = row[kTextureInput].toTexture()) { if (row[kMethodInput].toInt() == kRadial) { const QVector2D &sequence_res = tex->virtual_resolution(); QVector2D sequence_half_res = sequence_res * 0.5; radial_center_gizmo_->SetVisible(true); radial_center_gizmo_->SetPoint(sequence_half_res.toPointF() + row[kRadialCenterInput].toVec2().toPointF()); SetInputProperty(kRadialCenterInput, QStringLiteral("offset"), sequence_half_res); } else{ radial_center_gizmo_->SetVisible(false); } } } void BlurFilterNode::GizmoDragMove(double x, double y, const Qt::KeyboardModifiers &modifiers) { DraggableGizmo *gizmo = static_cast<DraggableGizmo*>(sender()); if (gizmo == radial_center_gizmo_) { NodeInputDragger &x_drag = gizmo->GetDraggers()[0]; NodeInputDragger &y_drag = gizmo->GetDraggers()[1]; x_drag.Drag(x_drag.GetStartValue().toDouble() + x); y_drag.Drag(y_drag.GetStartValue().toDouble() + y); } } void BlurFilterNode::InputValueChangedEvent(const QString &input, int element) { if (input == kMethodInput) { UpdateInputs(GetMethod()); } super::InputValueChangedEvent(input, element); } void BlurFilterNode::UpdateInputs(Method method) { SetInputFlag(kHorizInput, kInputFlagHidden, !(method == kBox || method == kGaussian)); SetInputFlag(kVertInput, kInputFlagHidden, !(method == kBox || method == kGaussian)); SetInputFlag(kDirectionalDegreesInput, kInputFlagHidden, !(method == kDirectional)); SetInputFlag(kRadialCenterInput, kInputFlagHidden, !(method == kRadial)); } }
6,875
C++
.cpp
170
36.5
125
0.737569
olive-editor/olive
8,144
552
131
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
19,051
dropshadowfilter.cpp
olive-editor_olive/app/node/filter/dropshadow/dropshadowfilter.cpp
/*** Olive - Non-Linear Video Editor Copyright (C) 2022 Olive Team 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 <http://www.gnu.org/licenses/>. ***/ #include "dropshadowfilter.h" #include "widget/slider/floatslider.h" namespace olive { #define super Node const QString DropShadowFilter::kTextureInput = QStringLiteral("tex_in"); const QString DropShadowFilter::kColorInput = QStringLiteral("color_in"); const QString DropShadowFilter::kDistanceInput = QStringLiteral("distance_in"); const QString DropShadowFilter::kAngleInput = QStringLiteral("angle_in"); const QString DropShadowFilter::kSoftnessInput = QStringLiteral("radius_in"); const QString DropShadowFilter::kOpacityInput = QStringLiteral("opacity_in"); const QString DropShadowFilter::kFastInput = QStringLiteral("fast_in"); DropShadowFilter::DropShadowFilter() { AddInput(kTextureInput, NodeValue::kTexture, InputFlags(kInputFlagNotKeyframable)); AddInput(kColorInput, NodeValue::kColor, QVariant::fromValue(Color(0.0, 0.0, 0.0))); AddInput(kDistanceInput, NodeValue::kFloat, 10.0); AddInput(kAngleInput, NodeValue::kFloat, 135.0); AddInput(kSoftnessInput, NodeValue::kFloat, 10.0); SetInputProperty(kSoftnessInput, QStringLiteral("min"), 0.0); AddInput(kOpacityInput, NodeValue::kFloat, 1.0); SetInputProperty(kOpacityInput, QStringLiteral("min"), 0.0); SetInputProperty(kOpacityInput, QStringLiteral("view"), FloatSlider::kPercentage); AddInput(kFastInput, NodeValue::kBoolean, false); SetEffectInput(kTextureInput); SetFlag(kVideoEffect); } void DropShadowFilter::Retranslate() { super::Retranslate(); SetInputName(kTextureInput, tr("Texture")); SetInputName(kColorInput, tr("Color")); SetInputName(kDistanceInput, tr("Distance")); SetInputName(kAngleInput, tr("Angle")); SetInputName(kSoftnessInput, tr("Softness")); SetInputName(kOpacityInput, tr("Opacity")); SetInputName(kFastInput, tr("Faster (Lower Quality)")); } ShaderCode DropShadowFilter::GetShaderCode(const ShaderRequest &request) const { Q_UNUSED(request) return ShaderCode(FileFunctions::ReadFileAsString(":/shaders/dropshadow.frag")); } void DropShadowFilter::Value(const NodeValueRow &value, const NodeGlobals &globals, NodeValueTable *table) const { if (TexturePtr tex = value[kTextureInput].toTexture()) { ShaderJob job(value); QString iterative = QStringLiteral("previous_iteration_in"); job.Insert(QStringLiteral("resolution_in"), NodeValue(NodeValue::kVec2, tex->virtual_resolution(), this)); job.Insert(iterative, value[kTextureInput]); if (!qIsNull(value[kSoftnessInput].toDouble())) { job.SetIterations(3, iterative); } table->Push(NodeValue::kTexture, tex->toJob(job), this); } } }
3,287
C++
.cpp
70
44.057143
112
0.778997
olive-editor/olive
8,144
552
131
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
19,052
stroke.cpp
olive-editor_olive/app/node/filter/stroke/stroke.cpp
/*** Olive - Non-Linear Video Editor Copyright (C) 2022 Olive Team 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 <http://www.gnu.org/licenses/>. ***/ #include "stroke.h" #include "widget/slider/floatslider.h" namespace olive { const QString StrokeFilterNode::kTextureInput = QStringLiteral("tex_in"); const QString StrokeFilterNode::kColorInput = QStringLiteral("color_in"); const QString StrokeFilterNode::kRadiusInput = QStringLiteral("radius_in"); const QString StrokeFilterNode::kOpacityInput = QStringLiteral("opacity_in"); const QString StrokeFilterNode::kInnerInput = QStringLiteral("inner_in"); #define super Node StrokeFilterNode::StrokeFilterNode() { AddInput(kTextureInput, NodeValue::kTexture, InputFlags(kInputFlagNotKeyframable)); AddInput(kColorInput, NodeValue::kColor, QVariant::fromValue(Color(1.0f, 1.0f, 1.0f, 1.0f))); AddInput(kRadiusInput, NodeValue::kFloat, 10.0); SetInputProperty(kRadiusInput, QStringLiteral("min"), 0.0); AddInput(kOpacityInput, NodeValue::kFloat, 1.0f); SetInputProperty(kOpacityInput, QStringLiteral("view"), FloatSlider::kPercentage); SetInputProperty(kOpacityInput, QStringLiteral("min"), 0.0f); SetInputProperty(kOpacityInput, QStringLiteral("max"), 1.0f); AddInput(kInnerInput, NodeValue::kBoolean, false); SetFlag(kVideoEffect); SetEffectInput(kTextureInput); } QString StrokeFilterNode::Name() const { return tr("Stroke"); } QString StrokeFilterNode::id() const { return QStringLiteral("org.olivevideoeditor.Olive.stroke"); } QVector<Node::CategoryID> StrokeFilterNode::Category() const { return {kCategoryFilter}; } QString StrokeFilterNode::Description() const { return tr("Creates a stroke outline around an image."); } void StrokeFilterNode::Retranslate() { super::Retranslate(); SetInputName(kTextureInput, tr("Input")); SetInputName(kColorInput, tr("Color")); SetInputName(kRadiusInput, tr("Radius")); SetInputName(kOpacityInput, tr("Opacity")); SetInputName(kInnerInput, tr("Inner")); } void StrokeFilterNode::Value(const NodeValueRow &value, const NodeGlobals &globals, NodeValueTable *table) const { if (TexturePtr tex = value[kTextureInput].toTexture()) { if (value[kRadiusInput].toDouble() > 0.0 && value[kOpacityInput].toDouble() > 0.0) { ShaderJob job(value); job.Insert(QStringLiteral("resolution_in"), NodeValue(NodeValue::kVec2, tex->virtual_resolution(), this)); table->Push(NodeValue::kTexture, tex->toJob(job), this); } else { table->Push(value[kTextureInput]); } } } ShaderCode StrokeFilterNode::GetShaderCode(const ShaderRequest &request) const { Q_UNUSED(request) return ShaderCode(FileFunctions::ReadFileAsString(":/shaders/stroke.frag")); } }
3,294
C++
.cpp
81
37.888889
112
0.770631
olive-editor/olive
8,144
552
131
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
19,053
panelmanager.cpp
olive-editor_olive/app/panel/panelmanager.cpp
/*** Olive - Non-Linear Video Editor Copyright (C) 2022 Olive Team 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 <http://www.gnu.org/licenses/>. ***/ #include "panelmanager.h" #include "config/config.h" namespace olive { PanelManager* PanelManager::instance_ = nullptr; PanelManager::PanelManager(QObject *parent) : QObject(parent), suppress_changed_signal_(false) { } void PanelManager::DeleteAllPanels() { // Prevent any confusion regarding focus history by clearing it first QList<PanelWidget*> copy = focus_history_; focus_history_.clear(); qDeleteAll(copy); } const QList<PanelWidget *> &PanelManager::panels() { return focus_history_; } PanelWidget *PanelManager::CurrentlyFocused(bool enable_hover) const { // If hover focus is enabled, find the currently hovered panel and return it (if no panel is hovered, resort to // default behavior) if (enable_hover && OLIVE_CONFIG("HoverFocus").toBool()) { PanelWidget* hovered = CurrentlyHovered(); if (hovered != nullptr) { return hovered; } } if (focus_history_.isEmpty()) { return nullptr; } return focus_history_.first(); } PanelWidget *PanelManager::CurrentlyHovered() const { QPoint global_mouse = QCursor::pos(); foreach (PanelWidget* panel, focus_history_) { if (panel->rect().contains(panel->mapFromGlobal(global_mouse))) { return panel; } } return nullptr; } PanelWidget *PanelManager::GetPanelWithName(const QString &name) const { foreach (PanelWidget* panel, focus_history_) { if (panel->objectName() == name) { return panel; } } return nullptr; } void PanelManager::CreateInstance() { instance_ = new PanelManager(); } void PanelManager::DestroyInstance() { delete instance_; } PanelManager *PanelManager::instance() { return instance_; } void PanelManager::RegisterPanel(PanelWidget *panel) { // Add panel to the bottom of the focus history focus_history_.append(panel); // We're about to center the panel relative to the parent (usually the main window), but for some // reason this requires the panel to be shown first. panel->show(); if (focus_history_.size() == 1) { // This is the first panel, focus it panel->SetBorderVisible(true); emit FocusedPanelChanged(panel); } } void PanelManager::UnregisterPanel(PanelWidget *panel) { focus_history_.removeOne(panel); } void PanelManager::FocusChanged(QWidget *old, QWidget *now) { Q_UNUSED(old) QObject* parent = now; PanelWidget* panel_cast_test; // Loop through widget's parent hierarchy if (!focus_history_.empty()) { while (parent != nullptr) { // Use dynamic_cast to test if this object is a PanelWidget panel_cast_test = dynamic_cast<PanelWidget*>(parent); if (panel_cast_test) { if (focus_history_.first() != panel_cast_test) { // If so, bump this to the top of the focus history int panel_index = focus_history_.indexOf(panel_cast_test); // Disable highlight border on old panel if (!focus_history_.isEmpty()) { focus_history_.first()->SetBorderVisible(false); } // Enable new border's highlight panel_cast_test->SetBorderVisible(true); // If it's not in the focus history, prepend it, otherwise move it if (panel_index == -1) { focus_history_.prepend(panel_cast_test); } else { focus_history_.move(panel_index, 0); } if (!suppress_changed_signal_) { emit FocusedPanelChanged(panel_cast_test); } } break; } parent = parent->parent(); } } } }
4,238
C++
.cpp
134
27.320896
113
0.696776
olive-editor/olive
8,144
552
131
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
19,054
panel.cpp
olive-editor_olive/app/panel/panel.cpp
/*** Olive - Non-Linear Video Editor Copyright (C) 2022 Olive Team 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 <http://www.gnu.org/licenses/>. ***/ #include "panel.h" #include <QCloseEvent> #include <QDebug> #include <QHBoxLayout> #include <QPainter> #include <QStyle> #include <QStyleOption> #include <QVariant> #include "panel/panelmanager.h" namespace olive { #define super KDDockWidgets::DockWidget PanelWidget::PanelWidget(const QString &object_name) : super(object_name), border_visible_(false), signal_instead_of_close_(false) { setFocusPolicy(Qt::ClickFocus); connect(this, &PanelWidget::shown, this, static_cast<void(PanelWidget::*)()>(&PanelWidget::setFocus)); PanelManager::instance()->RegisterPanel(this); } PanelWidget::~PanelWidget() { PanelManager::instance()->UnregisterPanel(this); } void PanelWidget::SetBorderVisible(bool enabled) { border_visible_ = enabled; update(); } void PanelWidget::SetTitle(const QString &t) { title_ = t; UpdateTitle(); } void PanelWidget::SetSubtitle(const QString &t) { subtitle_ = t; UpdateTitle(); } void PanelWidget::paintEvent(QPaintEvent *event) { // Perform default behavior super::paintEvent(event); // Check if this panel (or a child of it) has focus using PanelFocusManager if (border_visible_) { // Draw a highlight border if so QPainter p(this); // We need to adjust the rect by 1 pixel since the bottom and right are "offscreen" QRect highlight_border = rect(); highlight_border.adjust(0, 0, -1, -1); // Set the color to the palette's highlight color p.setPen(palette().highlight().color()); // Draw the highlight border p.drawRect(highlight_border); } } void PanelWidget::UpdateTitle() { // If there's no subtitle, just use the title. Otherwise, we set a formatted combination of the two that can // differ based on translation if (subtitle_.isEmpty()) { this->setTitle(title_); } else { this->setTitle(tr("%1: %2").arg(title_, subtitle_)); } } void PanelWidget::SetSignalInsteadOfClose(bool e) { signal_instead_of_close_ = e; } void PanelWidget::closeEvent(QCloseEvent *event) { if (signal_instead_of_close_) { event->ignore(); emit CloseRequested(); } else { super::closeEvent(event); } } void PanelWidget::changeEvent(QEvent *e) { if (e->type() == QEvent::LanguageChange) { Retranslate(); } super::changeEvent(e); } void PanelWidget::Retranslate() { } void PanelWidget::SetWidgetWithPadding(QWidget *widget) { QWidget* wrapper = new QWidget(); QHBoxLayout* layout = new QHBoxLayout(wrapper); layout->setContentsMargins(layout->contentsMargins() / 2); layout->addWidget(widget); setWidget(wrapper); } }
3,284
C++
.cpp
112
26.669643
110
0.7383
olive-editor/olive
8,144
552
131
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
19,055
viewerbase.cpp
olive-editor_olive/app/panel/viewer/viewerbase.cpp
/*** Olive - Non-Linear Video Editor Copyright (C) 2022 Olive Team 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 <http://www.gnu.org/licenses/>. ***/ #include "viewerbase.h" #include "window/mainwindow/mainwindow.h" namespace olive { #define super TimeBasedPanel ViewerPanelBase::ViewerPanelBase(const QString& object_name) : super(object_name) { connect(PanelManager::instance(), &PanelManager::FocusedPanelChanged, this, &ViewerPanelBase::FocusedPanelChanged); } void ViewerPanelBase::PlayPause() { GetViewerWidget()->TogglePlayPause(); } void ViewerPanelBase::PlayInToOut() { GetViewerWidget()->Play(true); } void ViewerPanelBase::ShuttleLeft() { GetViewerWidget()->ShuttleLeft(); } void ViewerPanelBase::ShuttleStop() { GetViewerWidget()->ShuttleStop(); } void ViewerPanelBase::ShuttleRight() { GetViewerWidget()->ShuttleRight(); } void ViewerPanelBase::ConnectTimeBasedPanel(TimeBasedPanel *panel) { connect(panel, &TimeBasedPanel::PlayPauseRequested, this, &ViewerPanelBase::PlayPause); connect(panel, &TimeBasedPanel::PlayInToOutRequested, this, &ViewerPanelBase::PlayInToOut); connect(panel, &TimeBasedPanel::ShuttleLeftRequested, this, &ViewerPanelBase::ShuttleLeft); connect(panel, &TimeBasedPanel::ShuttleStopRequested, this, &ViewerPanelBase::ShuttleStop); connect(panel, &TimeBasedPanel::ShuttleRightRequested, this, &ViewerPanelBase::ShuttleRight); } void ViewerPanelBase::DisconnectTimeBasedPanel(TimeBasedPanel *panel) { disconnect(panel, &TimeBasedPanel::PlayPauseRequested, this, &ViewerPanelBase::PlayPause); disconnect(panel, &TimeBasedPanel::PlayInToOutRequested, this, &ViewerPanelBase::PlayInToOut); disconnect(panel, &TimeBasedPanel::ShuttleLeftRequested, this, &ViewerPanelBase::ShuttleLeft); disconnect(panel, &TimeBasedPanel::ShuttleStopRequested, this, &ViewerPanelBase::ShuttleStop); disconnect(panel, &TimeBasedPanel::ShuttleRightRequested, this, &ViewerPanelBase::ShuttleRight); } void ViewerPanelBase::SetFullScreen(QScreen *screen) { GetViewerWidget()->SetFullScreen(screen); } void ViewerPanelBase::SetGizmos(Node *node) { GetViewerWidget()->SetGizmos(node); } void ViewerPanelBase::CacheEntireSequence() { GetViewerWidget()->CacheEntireSequence(); } void ViewerPanelBase::CacheSequenceInOut() { GetViewerWidget()->CacheSequenceInOut(); } void ViewerPanelBase::SetViewerWidget(ViewerWidget *vw) { connect(vw, &ViewerWidget::TextureChanged, this, &ViewerPanelBase::TextureChanged); connect(vw, &ViewerWidget::ColorProcessorChanged, this, &ViewerPanelBase::ColorProcessorChanged); connect(vw, &ViewerWidget::ColorManagerChanged, this, &ViewerPanelBase::ColorManagerChanged); SetTimeBasedWidget(vw); } void ViewerPanelBase::FocusedPanelChanged(PanelWidget *panel) { if (dynamic_cast<ViewerPanelBase*>(panel)) { auto vw = GetViewerWidget(); if (vw->IsPlaying() && panel != this) { vw->Pause(); } } } }
3,485
C++
.cpp
92
35.565217
117
0.795428
olive-editor/olive
8,144
552
131
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
19,056
viewer.cpp
olive-editor_olive/app/panel/viewer/viewer.cpp
/*** Olive - Non-Linear Video Editor Copyright (C) 2022 Olive Team 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 <http://www.gnu.org/licenses/>. ***/ #include "viewer.h" namespace olive { ViewerPanel::ViewerPanel(const QString &object_name) : ViewerPanelBase(object_name) { // Set ViewerWidget as the central widget ViewerWidget* vw = new ViewerWidget(this); SetViewerWidget(vw); // Set strings Retranslate(); } void ViewerPanel::Retranslate() { ViewerPanelBase::Retranslate(); SetTitle(tr("Viewer")); } }
1,090
C++
.cpp
31
32.483871
71
0.766953
olive-editor/olive
8,144
552
131
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
19,057
timeline.cpp
olive-editor_olive/app/panel/timeline/timeline.cpp
/*** Olive - Non-Linear Video Editor Copyright (C) 2022 Olive Team 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 <http://www.gnu.org/licenses/>. ***/ #include "timeline.h" #include "panel/panelmanager.h" #include "panel/project/footagemanagementpanel.h" namespace olive { TimelinePanel::TimelinePanel(const QString &name) : TimeBasedPanel(name) { TimelineWidget* tw = new TimelineWidget(this); SetTimeBasedWidget(tw); Retranslate(); connect(tw, &TimelineWidget::BlockSelectionChanged, this, &TimelinePanel::BlockSelectionChanged); connect(tw, &TimelineWidget::RequestCaptureStart, this, &TimelinePanel::RequestCaptureStart); connect(tw, &TimelineWidget::RevealViewerInProject, this, &TimelinePanel::RevealViewerInProject); connect(tw, &TimelineWidget::RevealViewerInFootageViewer, this, &TimelinePanel::RevealViewerInFootageViewer); } void TimelinePanel::SplitAtPlayhead() { timeline_widget()->SplitAtPlayhead(); } void TimelinePanel::LoadData(const Info &info) { timeline_widget()->RestoreSplitterState(QByteArray::fromBase64(info.at("splitter").toUtf8())); } PanelWidget::Info TimelinePanel::SaveData() const { Info i; i["splitter"] = timeline_widget()->SaveSplitterState().toBase64(); return i; } void TimelinePanel::SelectAll() { timeline_widget()->SelectAll(); } void TimelinePanel::DeselectAll() { timeline_widget()->DeselectAll(); } void TimelinePanel::RippleToIn() { timeline_widget()->RippleToIn(); } void TimelinePanel::RippleToOut() { timeline_widget()->RippleToOut(); } void TimelinePanel::EditToIn() { timeline_widget()->EditToIn(); } void TimelinePanel::EditToOut() { timeline_widget()->EditToOut(); } void TimelinePanel::DeleteSelected() { timeline_widget()->DeleteSelected(false); } void TimelinePanel::RippleDelete() { timeline_widget()->DeleteSelected(true); } void TimelinePanel::IncreaseTrackHeight() { timeline_widget()->IncreaseTrackHeight(); } void TimelinePanel::DecreaseTrackHeight() { timeline_widget()->DecreaseTrackHeight(); } void TimelinePanel::ToggleLinks() { timeline_widget()->ToggleLinksOnSelected(); } void TimelinePanel::PasteInsert() { timeline_widget()->PasteInsert(); } void TimelinePanel::DeleteInToOut() { timeline_widget()->DeleteInToOut(false); } void TimelinePanel::RippleDeleteInToOut() { timeline_widget()->DeleteInToOut(true); } void TimelinePanel::ToggleSelectedEnabled() { timeline_widget()->ToggleSelectedEnabled(); } void TimelinePanel::SetColorLabel(int index) { timeline_widget()->SetColorLabel(index); } void TimelinePanel::NudgeLeft() { timeline_widget()->NudgeLeft(); } void TimelinePanel::NudgeRight() { timeline_widget()->NudgeRight(); } void TimelinePanel::MoveInToPlayhead() { timeline_widget()->MoveInToPlayhead(); } void TimelinePanel::MoveOutToPlayhead() { timeline_widget()->MoveOutToPlayhead(); } void TimelinePanel::RenameSelected() { timeline_widget()->RenameSelectedBlocks(); } void TimelinePanel::InsertFootageAtPlayhead(const QVector<ViewerOutput *> &footage) { timeline_widget()->InsertFootageAtPlayhead(footage); } void TimelinePanel::OverwriteFootageAtPlayhead(const QVector<ViewerOutput *> &footage) { timeline_widget()->OverwriteFootageAtPlayhead(footage); } void TimelinePanel::Retranslate() { TimeBasedPanel::Retranslate(); SetTitle(tr("Timeline")); } }
3,905
C++
.cpp
141
25.687943
111
0.785062
olive-editor/olive
8,144
552
131
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
19,058
historypanel.cpp
olive-editor_olive/app/panel/history/historypanel.cpp
/*** Olive - Non-Linear Video Editor Copyright (C) 2023 Olive Studios 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 <http://www.gnu.org/licenses/>. ***/ #include "historypanel.h" #include "widget/history/historywidget.h" namespace olive { HistoryPanel::HistoryPanel() : PanelWidget(QStringLiteral("HistoryPanel")) { SetWidgetWithPadding(new HistoryWidget(this)); Retranslate(); } void HistoryPanel::Retranslate() { SetTitle(tr("History")); } }
1,024
C++
.cpp
28
34
71
0.776423
olive-editor/olive
8,144
552
131
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
19,059
curve.cpp
olive-editor_olive/app/panel/curve/curve.cpp
/*** Olive - Non-Linear Video Editor Copyright (C) 2022 Olive Team 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 <http://www.gnu.org/licenses/>. ***/ #include "curve.h" namespace olive { CurvePanel::CurvePanel() : TimeBasedPanel(QStringLiteral("CurvePanel")) { // Create main widget and set it SetTimeBasedWidget(new CurveWidget(this)); // Set strings Retranslate(); } void CurvePanel::DeleteSelected() { static_cast<CurveWidget*>(GetTimeBasedWidget())->DeleteSelected(); } void CurvePanel::SelectAll() { static_cast<CurveWidget*>(GetTimeBasedWidget())->SelectAll(); } void CurvePanel::DeselectAll() { static_cast<CurveWidget*>(GetTimeBasedWidget())->DeselectAll(); } void CurvePanel::SetNodes(const QVector<Node *> &nodes) { static_cast<CurveWidget*>(GetTimeBasedWidget())->SetNodes(nodes); } void CurvePanel::IncreaseTrackHeight() { CurveWidget* c = static_cast<CurveWidget*>(GetTimeBasedWidget()); c->SetVerticalScale(c->GetVerticalScale() * 2); } void CurvePanel::DecreaseTrackHeight() { CurveWidget* c = static_cast<CurveWidget*>(GetTimeBasedWidget()); c->SetVerticalScale(c->GetVerticalScale() * 0.5); } void CurvePanel::Retranslate() { TimeBasedPanel::Retranslate(); SetTitle(tr("Curve Editor")); } }
1,812
C++
.cpp
56
30.071429
71
0.766398
olive-editor/olive
8,144
552
131
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
19,060
taskmanager.cpp
olive-editor_olive/app/panel/taskmanager/taskmanager.cpp
/*** Olive - Non-Linear Video Editor Copyright (C) 2022 Olive Team 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 <http://www.gnu.org/licenses/>. ***/ #include "taskmanager.h" #include "task/taskmanager.h" namespace olive { TaskManagerPanel::TaskManagerPanel() : PanelWidget(QStringLiteral("TaskManagerPanel")) { // Create task view view_ = new TaskView(this); // Set it as the main widget setWidget(view_); // Connect task view to the task manager connect(TaskManager::instance(), &TaskManager::TaskAdded, view_, &TaskView::AddTask); connect(TaskManager::instance(), &TaskManager::TaskRemoved, view_, &TaskView::RemoveTask); connect(TaskManager::instance(), &TaskManager::TaskFailed, view_, &TaskView::TaskFailed); connect(view_, &TaskView::TaskCancelled, TaskManager::instance(), &TaskManager::CancelTask); // Set strings Retranslate(); } void TaskManagerPanel::Retranslate() { SetTitle(tr("Task Manager")); } }
1,509
C++
.cpp
37
38.054054
94
0.760631
olive-editor/olive
8,144
552
131
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
19,061
tool.cpp
olive-editor_olive/app/panel/tool/tool.cpp
/*** Olive - Non-Linear Video Editor Copyright (C) 2022 Olive Team 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 <http://www.gnu.org/licenses/>. ***/ #include "tool.h" #include "core.h" #include "widget/toolbar/toolbar.h" namespace olive { ToolPanel::ToolPanel() : PanelWidget(QStringLiteral("ToolPanel")) { Toolbar* t = new Toolbar(this); t->SetTool(Core::instance()->tool()); t->SetSnapping(Core::instance()->snapping()); SetWidgetWithPadding(t); connect(t, &Toolbar::ToolChanged, Core::instance(), &Core::SetTool); connect(Core::instance(), &Core::ToolChanged, t, &Toolbar::SetTool); connect(t, &Toolbar::SnappingChanged, Core::instance(), &Core::SetSnapping); connect(Core::instance(), &Core::SnappingChanged, t, &Toolbar::SetSnapping); connect(t, &Toolbar::SelectedTransitionChanged, Core::instance(), &Core::SetSelectedTransitionObject); Retranslate(); } void ToolPanel::Retranslate() { SetTitle(tr("Tools")); } }
1,517
C++
.cpp
37
38.243243
104
0.749146
olive-editor/olive
8,144
552
131
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
19,062
node.cpp
olive-editor_olive/app/panel/node/node.cpp
/*** Olive - Non-Linear Video Editor Copyright (C) 2022 Olive Team 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 <http://www.gnu.org/licenses/>. ***/ #include "node.h" namespace olive { NodePanel::NodePanel() : PanelWidget(QStringLiteral("NodePanel")) { node_widget_ = new NodeWidget(this); connect(this, &NodePanel::shown, node_widget_->view(), &NodeView::CenterOnItemsBoundingRect); connect(node_widget_->view(), &NodeView::NodesSelected, this, &NodePanel::NodesSelected); connect(node_widget_->view(), &NodeView::NodesDeselected, this, &NodePanel::NodesDeselected); connect(node_widget_->view(), &NodeView::NodeSelectionChanged, this, &NodePanel::NodeSelectionChanged); connect(node_widget_->view(), &NodeView::NodeSelectionChangedWithContexts, this, &NodePanel::NodeSelectionChangedWithContexts); connect(node_widget_->view(), &NodeView::NodeGroupOpened, this, &NodePanel::NodeGroupOpened); connect(node_widget_->view(), &NodeView::NodeGroupClosed, this, &NodePanel::NodeGroupClosed); // Set it as the main widget of this panel SetWidgetWithPadding(node_widget_); // Set strings Retranslate(); } }
1,696
C++
.cpp
33
48.515152
129
0.766202
olive-editor/olive
8,144
552
131
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
19,063
timebased.cpp
olive-editor_olive/app/panel/timebased/timebased.cpp
/*** Olive - Non-Linear Video Editor Copyright (C) 2022 Olive Team 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 <http://www.gnu.org/licenses/>. ***/ #include "timebased.h" namespace olive { TimeBasedPanel::TimeBasedPanel(const QString &object_name) : PanelWidget(object_name), widget_(nullptr), show_and_raise_on_connect_(false) { } TimeBasedPanel::~TimeBasedPanel() { delete widget_; } const rational& TimeBasedPanel::timebase() { return widget_->timebase(); } void TimeBasedPanel::GoToStart() { widget_->GoToStart(); } void TimeBasedPanel::PrevFrame() { widget_->PrevFrame(); } void TimeBasedPanel::NextFrame() { widget_->NextFrame(); } void TimeBasedPanel::GoToEnd() { widget_->GoToEnd(); } void TimeBasedPanel::ZoomIn() { widget_->ZoomIn(); } void TimeBasedPanel::ZoomOut() { widget_->ZoomOut(); } void TimeBasedPanel::SetTimebase(const rational &timebase) { widget_->SetTimebase(timebase); } void TimeBasedPanel::GoToPrevCut() { widget_->GoToPrevCut(); } void TimeBasedPanel::GoToNextCut() { widget_->GoToNextCut(); } void TimeBasedPanel::PlayPause() { emit PlayPauseRequested(); } void TimeBasedPanel::PlayInToOut() { emit PlayInToOutRequested(); } void TimeBasedPanel::ShuttleLeft() { emit ShuttleLeftRequested(); } void TimeBasedPanel::ShuttleStop() { emit ShuttleStopRequested(); } void TimeBasedPanel::ShuttleRight() { emit ShuttleRightRequested(); } void TimeBasedPanel::ConnectViewerNode(ViewerOutput *node) { widget_->ConnectViewerNode(node); } void TimeBasedPanel::SetTimeBasedWidget(TimeBasedWidget *widget) { if (widget_) { disconnect(widget_, &TimeBasedWidget::ConnectedNodeChanged, this, &TimeBasedPanel::ConnectedNodeChanged); } widget_ = widget; if (widget_) { connect(widget_, &TimeBasedWidget::ConnectedNodeChanged, this, &TimeBasedPanel::ConnectedNodeChanged); } SetWidgetWithPadding(widget_); } void TimeBasedPanel::Retranslate() { if (GetTimeBasedWidget()->GetConnectedNode()) { SetSubtitle(GetTimeBasedWidget()->GetConnectedNode()->GetLabel()); } else { SetSubtitle(tr("(none)")); } } void TimeBasedPanel::ConnectedNodeChanged(ViewerOutput *old, ViewerOutput *now) { if (old) { disconnect(old, &ViewerOutput::LabelChanged, this, &TimeBasedPanel::SetSubtitle); } if (now) { connect(now, &ViewerOutput::LabelChanged, this, &TimeBasedPanel::SetSubtitle); if (show_and_raise_on_connect_) { this->show(); this->raise(); } } // Update strings Retranslate(); } void TimeBasedPanel::SetIn() { GetTimeBasedWidget()->SetInAtPlayhead(); } void TimeBasedPanel::SetOut() { GetTimeBasedWidget()->SetOutAtPlayhead(); } void TimeBasedPanel::ResetIn() { GetTimeBasedWidget()->ResetIn(); } void TimeBasedPanel::ResetOut() { GetTimeBasedWidget()->ResetOut(); } void TimeBasedPanel::ClearInOut() { GetTimeBasedWidget()->ClearInOutPoints(); } void TimeBasedPanel::SetMarker() { GetTimeBasedWidget()->SetMarker(); } void TimeBasedPanel::ToggleShowAll() { GetTimeBasedWidget()->ToggleShowAll(); } void TimeBasedPanel::GoToIn() { GetTimeBasedWidget()->GoToIn(); } void TimeBasedPanel::GoToOut() { GetTimeBasedWidget()->GoToOut(); } void TimeBasedPanel::DeleteSelected() { GetTimeBasedWidget()->DeleteSelected(); } void TimeBasedPanel::CutSelected() { GetTimeBasedWidget()->CopySelected(true); } void TimeBasedPanel::CopySelected() { GetTimeBasedWidget()->CopySelected(false); } void TimeBasedPanel::Paste() { GetTimeBasedWidget()->Paste(); } }
4,091
C++
.cpp
177
20.915254
109
0.760993
olive-editor/olive
8,144
552
131
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
19,064
multicampanel.cpp
olive-editor_olive/app/panel/multicam/multicampanel.cpp
#include "multicampanel.h" namespace olive { #define super TimeBasedPanel MulticamPanel::MulticamPanel() : super(QStringLiteral("MultiCamPanel")) { SetTimeBasedWidget(new MulticamWidget(this)); Retranslate(); } void MulticamPanel::Retranslate() { super::Retranslate(); SetTitle(tr("Multi-Cam")); } }
317
C++
.cpp
15
19
47
0.779661
olive-editor/olive
8,144
552
131
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
19,065
audiomonitor.cpp
olive-editor_olive/app/panel/audiomonitor/audiomonitor.cpp
/*** Olive - Non-Linear Video Editor Copyright (C) 2022 Olive Team 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 <http://www.gnu.org/licenses/>. ***/ #include "audiomonitor.h" #include "panel/panelmanager.h" namespace olive { #define super PanelWidget AudioMonitorPanel::AudioMonitorPanel() : super(QStringLiteral("AudioMonitor")) { audio_monitor_ = new AudioMonitor(this); SetWidgetWithPadding(audio_monitor_); Retranslate(); } void AudioMonitorPanel::Retranslate() { SetTitle(tr("Audio Monitor")); } }
1,084
C++
.cpp
30
33.533333
71
0.776923
olive-editor/olive
8,144
552
131
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
19,066
table.cpp
olive-editor_olive/app/panel/table/table.cpp
/*** Olive - Non-Linear Video Editor Copyright (C) 2022 Olive Team 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 <http://www.gnu.org/licenses/>. ***/ #include "table.h" namespace olive { NodeTablePanel::NodeTablePanel() : TimeBasedPanel(QStringLiteral("NodeTablePanel")) { SetTimeBasedWidget(new NodeTableWidget(this)); Retranslate(); } void NodeTablePanel::Retranslate() { SetTitle(tr("Table View")); } }
981
C++
.cpp
27
33.740741
71
0.774125
olive-editor/olive
8,144
552
131
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
19,067
pixelsamplerpanel.cpp
olive-editor_olive/app/panel/pixelsampler/pixelsamplerpanel.cpp
/*** Olive - Non-Linear Video Editor Copyright (C) 2022 Olive Team 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 <http://www.gnu.org/licenses/>. ***/ #include "pixelsamplerpanel.h" #include "core.h" namespace olive { PixelSamplerPanel::PixelSamplerPanel() : PanelWidget(QStringLiteral("PixelSamplerPanel")) { sampler_widget_ = new ManagedPixelSamplerWidget(this); SetWidgetWithPadding(sampler_widget_); connect(this, &PixelSamplerPanel::shown, Core::instance(), []{Core::instance()->RequestPixelSamplingInViewers(true);}); connect(this, &PixelSamplerPanel::hidden, Core::instance(), []{Core::instance()->RequestPixelSamplingInViewers(false);}); connect(Core::instance(), &Core::ColorPickerColorEmitted, this, &PixelSamplerPanel::SetValues); Retranslate(); } void PixelSamplerPanel::SetValues(const Color &reference, const Color &display) { sampler_widget_->SetValues(reference, display); } void PixelSamplerPanel::Retranslate() { SetTitle(tr("Pixel Sampler")); } }
1,553
C++
.cpp
36
40.583333
123
0.775782
olive-editor/olive
8,144
552
131
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
19,068
scope.cpp
olive-editor_olive/app/panel/scope/scope.cpp
/*** Olive - Non-Linear Video Editor Copyright (C) 2022 Olive Team 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 <http://www.gnu.org/licenses/>. ***/ #include "scope.h" #include <QVBoxLayout> #include "panel/viewer/viewer.h" namespace olive { ScopePanel::ScopePanel() : PanelWidget(QStringLiteral("ScopePanel")), viewer_(nullptr) { QWidget* central = new QWidget(this); setWidget(central); QVBoxLayout* layout = new QVBoxLayout(central); QHBoxLayout* toolbar_layout = new QHBoxLayout(); toolbar_layout->setContentsMargins(0, 0, 0, 0); scope_type_combobox_ = new QComboBox(); for (int i=0;i<ScopePanel::kTypeCount;i++) { // These strings get filled in later in Retranslate() scope_type_combobox_->addItem(QString()); } toolbar_layout->addWidget(scope_type_combobox_); toolbar_layout->addStretch(); layout->addLayout(toolbar_layout); stack_ = new QStackedWidget(); layout->addWidget(stack_); // Create waveform view waveform_view_ = new WaveformScope(); stack_->addWidget(waveform_view_); // Create histogram histogram_ = new HistogramScope(); stack_->addWidget(histogram_); connect(scope_type_combobox_, static_cast<void(QComboBox::*)(int)>(&QComboBox::currentIndexChanged), stack_, &QStackedWidget::setCurrentIndex); Retranslate(); } void ScopePanel::SetType(ScopePanel::Type t) { scope_type_combobox_->setCurrentIndex(t); } QString ScopePanel::TypeToName(ScopePanel::Type t) { switch (t) { case kTypeWaveform: return tr("Waveform"); case kTypeHistogram: return tr("Histogram"); case kTypeCount: break; } return QString(); } void ScopePanel::SetViewerPanel(ViewerPanelBase *vp) { if (viewer_ == vp) { return; } if (viewer_) { disconnect(viewer_, &ViewerPanelBase::TextureChanged, this, &ScopePanel::SetReferenceBuffer); disconnect(viewer_, &ViewerPanelBase::ColorManagerChanged, this, &ScopePanel::SetColorManager); } viewer_ = vp; if (viewer_) { // Connect viewer widget texture drawing to scope panel connect(viewer_, &ViewerPanelBase::TextureChanged, this, &ScopePanel::SetReferenceBuffer); connect(viewer_, &ViewerPanelBase::ColorManagerChanged, this, &ScopePanel::SetColorManager); SetColorManager(viewer_->GetColorManager()); viewer_->UpdateTextureFromNode(); } else { SetReferenceBuffer(nullptr); SetColorManager(nullptr); } } void ScopePanel::SetReferenceBuffer(TexturePtr frame) { histogram_->SetBuffer(frame); waveform_view_->SetBuffer(frame); } void ScopePanel::SetColorManager(ColorManager *manager) { histogram_->ConnectColorManager(manager); waveform_view_->ConnectColorManager(manager); } void ScopePanel::Retranslate() { SetTitle(tr("Scopes")); for (int i=0;i<ScopePanel::kTypeCount;i++) { scope_type_combobox_->setItemText(i, TypeToName(static_cast<Type>(i))); } } }
3,429
C++
.cpp
101
30.841584
145
0.746735
olive-editor/olive
8,144
552
131
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
19,069
param.cpp
olive-editor_olive/app/panel/param/param.cpp
/*** Olive - Non-Linear Video Editor Copyright (C) 2022 Olive Team 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 <http://www.gnu.org/licenses/>. ***/ #include "param.h" #include "window/mainwindow/mainwindow.h" namespace olive { ParamPanel::ParamPanel() : TimeBasedPanel(QStringLiteral("ParamPanel")) { NodeParamView* view = new NodeParamView(this); connect(view, &NodeParamView::FocusedNodeChanged, this, &ParamPanel::FocusedNodeChanged); connect(view, &NodeParamView::SelectedNodesChanged, this, &ParamPanel::SelectedNodesChanged); connect(view, &NodeParamView::RequestViewerToStartEditingText, this, &ParamPanel::RequestViewerToStartEditingText); connect(this, &ParamPanel::shown, view, &NodeParamView::UpdateElementY); SetTimeBasedWidget(view); Retranslate(); } void ParamPanel::DeleteSelected() { static_cast<NodeParamView*>(GetTimeBasedWidget())->DeleteSelected(); } void ParamPanel::SelectAll() { static_cast<NodeParamView*>(GetTimeBasedWidget())->SelectAll(); } void ParamPanel::DeselectAll() { static_cast<NodeParamView*>(GetTimeBasedWidget())->DeselectAll(); } void ParamPanel::SetContexts(const QVector<Node *> &contexts) { static_cast<NodeParamView*>(GetTimeBasedWidget())->SetContexts(contexts); } void ParamPanel::Retranslate() { SetTitle(tr("Parameter Editor")); } }
1,880
C++
.cpp
49
36.020408
117
0.784573
olive-editor/olive
8,144
552
131
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
19,070
project.cpp
olive-editor_olive/app/panel/project/project.cpp
/*** Olive - Non-Linear Video Editor Copyright (C) 2022 Olive Team 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 <http://www.gnu.org/licenses/>. ***/ #include "project.h" #include <QMenu> #include <QVBoxLayout> #include "core.h" #include "node/project/sequence/sequence.h" #include "panel/footageviewer/footageviewer.h" #include "panel/timeline/timeline.h" #include "panel/panelmanager.h" #include "widget/menu/menushared.h" #include "widget/projecttoolbar/projecttoolbar.h" #include "window/mainwindow/mainwindow.h" namespace olive { ProjectPanel::ProjectPanel(const QString &unique_name) : PanelWidget(unique_name) { // Create main widget and its layout QWidget* central_widget = new QWidget(this); QVBoxLayout* layout = new QVBoxLayout(central_widget); layout->setContentsMargins(0, 0, 0, 0); SetWidgetWithPadding(central_widget); // Set up project toolbar ProjectToolbar* toolbar = new ProjectToolbar(this); layout->addWidget(toolbar); // Make toolbar connections connect(toolbar, &ProjectToolbar::NewClicked, this, &ProjectPanel::ShowNewMenu); connect(toolbar, &ProjectToolbar::OpenClicked, Core::instance(), &Core::OpenProject); connect(toolbar, &ProjectToolbar::SaveClicked, this, &ProjectPanel::SaveConnectedProject); // Set up main explorer object explorer_ = new ProjectExplorer(this); layout->addWidget(explorer_); connect(explorer_, &ProjectExplorer::DoubleClickedItem, this, &ProjectPanel::ItemDoubleClickSlot); connect(explorer_, &ProjectExplorer::SelectionChanged, this, &ProjectPanel::SelectionChanged); connect(toolbar, &ProjectToolbar::SearchChanged, explorer_, &ProjectExplorer::SetSearchFilter); // Set toolbar's view to the explorer's view toolbar->SetView(explorer_->view_type()); // Connect toolbar's view change signal to the explorer's view change slot connect(toolbar, &ProjectToolbar::ViewChanged, explorer_, &ProjectExplorer::set_view_type); // Set strings Retranslate(); } Project* ProjectPanel::project() const { return explorer_->project(); } void ProjectPanel::set_project(Project* p) { if (project()) { disconnect(project(), &Project::NameChanged, this, &ProjectPanel::UpdateSubtitle); disconnect(project(), &Project::NameChanged, this, &ProjectPanel::ProjectNameChanged); } explorer_->set_project(p); if (project()) { connect(project(), &Project::NameChanged, this, &ProjectPanel::UpdateSubtitle); connect(project(), &Project::NameChanged, this, &ProjectPanel::ProjectNameChanged); } UpdateSubtitle(); emit ProjectNameChanged(); } Folder *ProjectPanel::get_root() const { return explorer_->get_root(); } void ProjectPanel::set_root(Folder *item) { explorer_->set_root(item); Retranslate(); } QVector<Node *> ProjectPanel::SelectedItems() const { return explorer_->SelectedItems(); } Folder *ProjectPanel::GetSelectedFolder() const { return explorer_->GetSelectedFolder(); } ProjectViewModel *ProjectPanel::model() const { return explorer_->model(); } void ProjectPanel::SelectAll() { explorer_->SelectAll(); } void ProjectPanel::DeselectAll() { explorer_->DeselectAll(); } void ProjectPanel::DeleteSelected() { explorer_->DeleteSelected(); } void ProjectPanel::RenameSelected() { explorer_->RenameSelectedItem(); } void ProjectPanel::Edit(Node* item) { explorer_->Edit(item); } void ProjectPanel::Retranslate() { if (project() && explorer_->get_root() != project()->root()) { SetTitle(tr("Folder")); } else { SetTitle(tr("Project")); } UpdateSubtitle(); } void ProjectPanel::ItemDoubleClickSlot(Node *item) { if (item == nullptr) { // If the user double clicks on empty space, show the import dialog Core::instance()->DialogImportShow(); } else if (dynamic_cast<Footage*>(item)) { // Open this footage in a FootageViewer auto panel = PanelManager::instance()->MostRecentlyFocused<FootageViewerPanel>(); panel->ConnectViewerNode(static_cast<Footage*>(item)); panel->raise(); panel->setFocus(); } else if (dynamic_cast<Sequence*>(item)) { // Open this sequence in the Timeline Core::instance()->main_window()->OpenSequence(static_cast<Sequence*>(item)); } } void ProjectPanel::ShowNewMenu() { Menu new_menu(this); MenuShared::instance()->AddItemsForNewMenu(&new_menu); new_menu.exec(QCursor::pos()); } void ProjectPanel::UpdateSubtitle() { if (project()) { QString project_title = QStringLiteral("%1").arg(project()->name()); if (explorer_->get_root() != project()->root()) { QString folder_path; Folder* item = explorer_->get_root(); do { folder_path.prepend(QStringLiteral("/%1").arg(item->GetLabel())); item = item->folder(); } while (item != project()->root()); project_title.append(folder_path); } SetSubtitle(project_title); } else { SetSubtitle(tr("(none)")); } } void ProjectPanel::SaveConnectedProject() { Core::instance()->SaveProject(); } QVector<ViewerOutput *> ProjectPanel::GetSelectedFootage() const { QVector<Node*> items = SelectedItems(); QVector<ViewerOutput*> footage; foreach (Node* i, items) { if (dynamic_cast<ViewerOutput*>(i)) { footage.append(static_cast<ViewerOutput*>(i)); } } return footage; } }
5,863
C++
.cpp
181
29.325967
100
0.731083
olive-editor/olive
8,144
552
131
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
19,071
sequenceviewer.cpp
olive-editor_olive/app/panel/sequenceviewer/sequenceviewer.cpp
/*** Olive - Non-Linear Video Editor Copyright (C) 2022 Olive Team 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 <http://www.gnu.org/licenses/>. ***/ #include "sequenceviewer.h" #include "panel/timeline/timeline.h" namespace olive { SequenceViewerPanel::SequenceViewerPanel() : ViewerPanel(QStringLiteral("SequenceViewerPanel")) { // Set strings Retranslate(); } void SequenceViewerPanel::StartCapture(const TimeRange &time, const Track::Reference &track) { TimelinePanel *tp = static_cast<TimelinePanel *>(sender()); static_cast<ViewerWidget*>(GetTimeBasedWidget())->StartCapture(tp->timeline_widget(), time, track); } void SequenceViewerPanel::Retranslate() { ViewerPanel::Retranslate(); SetTitle(tr("Sequence Viewer")); } }
1,309
C++
.cpp
34
36.029412
101
0.77593
olive-editor/olive
8,144
552
131
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
19,072
footageviewer.cpp
olive-editor_olive/app/panel/footageviewer/footageviewer.cpp
/*** Olive - Non-Linear Video Editor Copyright (C) 2022 Olive Team 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 <http://www.gnu.org/licenses/>. ***/ #include "footageviewer.h" namespace olive { #define super ViewerPanelBase FootageViewerPanel::FootageViewerPanel() : super(QStringLiteral("FootageViewerPanel")) { // Set ViewerWidget as the central widget FootageViewerWidget* fvw = new FootageViewerWidget(this); SetViewerWidget(fvw); // Set strings Retranslate(); // Show and raise on connect SetShowAndRaiseOnConnect(); } void FootageViewerPanel::OverrideWorkArea(const TimeRange &r) { GetFootageViewerWidget()->OverrideWorkArea(r); } QVector<ViewerOutput *> FootageViewerPanel::GetSelectedFootage() const { QVector<ViewerOutput *> list; if (GetConnectedViewer()) { list.append(GetConnectedViewer()); } return list; } void FootageViewerPanel::Retranslate() { super::Retranslate(); SetTitle(tr("Footage Viewer")); } }
1,528
C++
.cpp
46
30.565217
71
0.777322
olive-editor/olive
8,144
552
131
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
19,073
commandlineparser.cpp
olive-editor_olive/app/common/commandlineparser.cpp
/*** Olive - Non-Linear Video Editor Copyright (C) 2022 Olive Team 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 <http://www.gnu.org/licenses/>. ***/ #include "commandlineparser.h" #include <QCoreApplication> #include <QDebug> CommandLineParser::~CommandLineParser() { foreach (const KnownOption& o, options_) { delete o.option; } foreach (const KnownPositionalArgument& a, positional_args_) { delete a.option; } } const CommandLineParser::Option *CommandLineParser::AddOption(const QStringList &strings, const QString &description, bool takes_arg, const QString &arg_placeholder, bool hidden) { Option* o = new Option(); options_.append({strings, description, o, takes_arg, arg_placeholder, hidden}); return o; } const CommandLineParser::PositionalArgument *CommandLineParser::AddPositionalArgument(const QString &name, const QString &description, bool required) { PositionalArgument* a = new PositionalArgument(); positional_args_.append({name, description, a, required}); return a; } void CommandLineParser::Process(const QVector<QString> &argv) { int positional_index = 0; for (int i=1; i<argv.size(); i++) { if (argv[i][0] == '-') { // Must be an option // Skip past first dashes QString arg_basename = argv[i].mid(1); bool matched_known = false; for (int j=0; j<options_.size(); j++) { KnownOption& o = options_[j]; foreach (const QString& s, o.args) { if (!s.compare(arg_basename, Qt::CaseInsensitive)) { // Flag discovered! o.option->Set(); if (o.takes_arg && i+1 < argv.size()) { o.option->SetSetting(argv[i+1]); i++; } matched_known = true; goto found_flag; } } } found_flag: if (!matched_known) { qWarning() << "Unknown parameter:" << argv[i]; } } else { // Must be a positional flag if (positional_index < positional_args_.size()) { positional_args_[positional_index].option->SetSetting(argv[i]); positional_index++; } else { qWarning() << "Unknown parameter:" << argv[i]; } } } } void CommandLineParser::PrintHelp(const char* filename) { printf("%s %s\n", QCoreApplication::applicationName().toUtf8().constData(), QCoreApplication::applicationVersion().toUtf8().constData()); printf("Copyright (C) 2018-2022 Olive Team\n"); QString positional_args; for (int i=0; i<positional_args_.size(); i++) { if (i > 0) { positional_args.append(' '); } positional_args.append('['); positional_args.append(positional_args_.at(i).name); positional_args.append(']'); } const char* basename; #ifdef Q_OS_WINDOWS basename = strrchr(filename, '\\'); if (!basename) { basename = strrchr(filename, '/'); } #else basename = strrchr(filename, '/'); #endif if (basename) { // Slash found, increment pointer to avoid showing the slash itself basename++; } else { // If no slashes are found, assume string is already a basename basename = filename; } printf("Usage: %s [options] %s\n\n", basename, positional_args.toUtf8().constData()); foreach (const KnownOption& o, options_) { if (o.hidden) { continue; } QString all_args; for (int i=0; i<o.args.size(); i++) { if (i > 0) { all_args.append(QStringLiteral(", ")); } const QString& this_arg = o.args.at(i); all_args.append('-'); all_args.append(this_arg); } if (o.arg_placeholder.isEmpty()) { printf(" %s\n", all_args.toUtf8().constData()); } else { printf(" %s <%s>\n", all_args.toUtf8().constData(), o.arg_placeholder.toUtf8().constData()); } printf(" %s\n\n", o.description.toUtf8().constData()); } printf("\n"); }
4,449
C++
.cpp
131
28.78626
178
0.647114
olive-editor/olive
8,144
552
131
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
19,074
qtutils.cpp
olive-editor_olive/app/common/qtutils.cpp
/*** Olive - Non-Linear Video Editor Copyright (C) 2022 Olive Team 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 <http://www.gnu.org/licenses/>. ***/ #include "qtutils.h" #include <QDebug> namespace olive { int QtUtils::QFontMetricsWidth(QFontMetrics fm, const QString& s) { #if QT_VERSION < QT_VERSION_CHECK(5, 11, 0) return fm.width(s); #else return fm.horizontalAdvance(s); #endif } QFrame *QtUtils::CreateHorizontalLine() { QFrame* horizontal_line = new QFrame(); horizontal_line->setFrameShape(QFrame::HLine); horizontal_line->setFrameShadow(QFrame::Sunken); return horizontal_line; } QFrame *QtUtils::CreateVerticalLine() { QFrame *l = CreateHorizontalLine(); l->setFrameShape(QFrame::VLine); return l; } int QtUtils::MsgBox(QWidget *parent, QMessageBox::Icon icon, const QString &title, const QString &message, QMessageBox::StandardButtons buttons) { QMessageBox b(parent); b.setIcon(icon); b.setWindowModality(Qt::WindowModal); b.setWindowTitle(title); b.setText(message); uint mask = QMessageBox::FirstButton; while (mask <= QMessageBox::LastButton) { uint sb = buttons & mask; if (sb) { b.addButton(static_cast<QMessageBox::StandardButton>(sb)); } mask <<= 1; } return b.exec(); } QDateTime QtUtils::GetCreationDate(const QFileInfo &info) { #if QT_VERSION < QT_VERSION_CHECK(5, 10, 0) return info.created(); #else QDateTime t = info.birthTime(); if (!t.isValid()) { t = info.metadataChangeTime(); } return t; #endif } QString QtUtils::GetFormattedDateTime(const QDateTime &dt) { return dt.toString(Qt::TextDate); } QStringList QtUtils::WordWrapString(const QString &s, const QFontMetrics &fm, int bounding_width) { QStringList list; QStringList lines = s.split('\n'); // Iterate every line for (int i=0; i<lines.size(); i++) { QString this_line = lines.at(i); while (this_line.size() > 1 && QFontMetricsWidth(fm, this_line) >= bounding_width) { int old_size = this_line.size(); int hard_break = -1; for (int j=this_line.size()-1; j>=0; j--) { const QChar &char_test = this_line.at(j); if (char_test.isSpace() || char_test == '-') { if (QFontMetricsWidth(fm, this_line.left(j)) < bounding_width) { if (!char_test.isSpace()) { j++; } QString chopped = this_line.left(j); list.append(chopped); while (j < this_line.size() && this_line.at(j).isSpace()) { j++; } this_line.remove(0, j); break; } } else if (hard_break == -1 && QFontMetricsWidth(fm, this_line.left(j)) < bounding_width) { // In case we can't find a better place to split, split at the earliest time the line // goes under the width limit hard_break = j; } } if (old_size == this_line.size()) { if (hard_break != -1) { list.append(this_line.left(hard_break)); this_line.remove(0, hard_break); } else { qWarning() << "Failed to find anywhere to wrap. Returning full line."; break; } } } if (!this_line.isEmpty()) { list.append(this_line); } } return list; } Qt::KeyboardModifiers QtUtils::FlipControlAndShiftModifiers(Qt::KeyboardModifiers e) { if (e & Qt::ControlModifier & Qt::ShiftModifier) { return e; } if (e & Qt::ShiftModifier) { e |= Qt::ControlModifier; e &= ~Qt::ShiftModifier; } else if (e & Qt::ControlModifier) { e |= Qt::ShiftModifier; e &= ~Qt::ControlModifier; } return e; } void QtUtils::SetComboBoxData(QComboBox *cb, int data) { for (int i=0; i<cb->count(); i++) { if (cb->itemData(i).toInt() == data) { cb->setCurrentIndex(i); break; } } } void QtUtils::SetComboBoxData(QComboBox *cb, const QString &data) { for (int i=0; i<cb->count(); i++) { if (cb->itemData(i).toString() == data) { cb->setCurrentIndex(i); break; } } } QColor QtUtils::toQColor(const core::Color &i) { QColor c; // QColor only supports values from 0.0 to 1.0 and are only used for UI representations c.setRedF(std::clamp(i.red(), 0.0f, 1.0f)); c.setGreenF(std::clamp(i.green(), 0.0f, 1.0f)); c.setBlueF(std::clamp(i.blue(), 0.0f, 1.0f)); c.setAlphaF(std::clamp(i.alpha(), 0.0f, 1.0f)); return c; } namespace core { uint qHash(const core::rational &r, uint seed) { return ::qHash(r.toDouble(), seed); } uint qHash(const core::TimeRange &r, uint seed) { return qHash(r.in(), seed) ^ qHash(r.out(), seed); } } }
5,194
C++
.cpp
171
25.900585
144
0.652279
olive-editor/olive
8,144
552
131
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
19,075
oiioutils.cpp
olive-editor_olive/app/common/oiioutils.cpp
/*** Olive - Non-Linear Video Editor Copyright (C) 2022 Olive Team 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 <http://www.gnu.org/licenses/>. ***/ #include "oiioutils.h" #include <QDebug> namespace olive { void OIIOUtils::FrameToBuffer(const Frame* frame, OIIO::ImageBuf *buf) { buf->set_pixels(OIIO::ROI(), buf->spec().format, frame->const_data(), OIIO::AutoStride, frame->linesize_bytes()); } void OIIOUtils::BufferToFrame(OIIO::ImageBuf *buf, Frame* frame) { buf->get_pixels(OIIO::ROI(), buf->spec().format, frame->data(), OIIO::AutoStride, frame->linesize_bytes()); } rational OIIOUtils::GetPixelAspectRatioFromOIIO(const OIIO::ImageSpec &spec) { return rational::fromDouble(spec.get_float_attribute("PixelAspectRatio", 1)); } PixelFormat OIIOUtils::GetFormatFromOIIOBasetype(OIIO::TypeDesc::BASETYPE type) { switch (type) { case OIIO::TypeDesc::UNKNOWN: case OIIO::TypeDesc::NONE: break; case OIIO::TypeDesc::INT8: case OIIO::TypeDesc::INT16: case OIIO::TypeDesc::INT32: case OIIO::TypeDesc::UINT32: case OIIO::TypeDesc::INT64: case OIIO::TypeDesc::UINT64: case OIIO::TypeDesc::STRING: case OIIO::TypeDesc::PTR: case OIIO::TypeDesc::LASTBASE: case OIIO::TypeDesc::DOUBLE: qDebug() << "Tried to use unknown OIIO base type"; break; case OIIO::TypeDesc::UINT8: return PixelFormat::U8; case OIIO::TypeDesc::UINT16: return PixelFormat::U16; case OIIO::TypeDesc::HALF: return PixelFormat::F16; case OIIO::TypeDesc::FLOAT: return PixelFormat::F32; } return PixelFormat::INVALID; } }
2,272
C++
.cpp
67
29.089552
79
0.699863
olive-editor/olive
8,144
552
131
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
19,076
ocioutils.cpp
olive-editor_olive/app/common/ocioutils.cpp
/*** Olive - Non-Linear Video Editor Copyright (C) 2022 Olive Team 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 <http://www.gnu.org/licenses/>. ***/ #include "ocioutils.h" namespace olive { OCIO::BitDepth OCIOUtils::GetOCIOBitDepthFromPixelFormat(PixelFormat format) { switch (format) { case PixelFormat::U8: return OCIO::BIT_DEPTH_UINT8; case PixelFormat::U16: return OCIO::BIT_DEPTH_UINT16; break; case PixelFormat::F16: return OCIO::BIT_DEPTH_F16; break; case PixelFormat::F32: return OCIO::BIT_DEPTH_F32; break; case PixelFormat::INVALID: case PixelFormat::COUNT: break; } return OCIO::BIT_DEPTH_UNKNOWN; } }
1,230
C++
.cpp
37
29.972973
76
0.754015
olive-editor/olive
8,144
552
131
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
19,077
html.cpp
olive-editor_olive/app/common/html.cpp
#include "html.h" #include <QDebug> #include <QTextBlock> #include "xmlutils.h" namespace olive { const QVector<QString> Html::kBlockTags = { QStringLiteral("p"), QStringLiteral("div") }; inline bool StrEquals(const QStringView &a, const QStringView &b) { return !a.compare(b, Qt::CaseInsensitive); } QString Html::DocToHtml(const QTextDocument *doc) { QString html; QXmlStreamWriter writer(&html); //writer.setAutoFormatting(true); for (auto it=doc->begin(); it!=doc->end(); it=it.next()) { WriteBlock(&writer, it); } return html; } struct HtmlNode { QString tag; QTextCharFormat format; }; QTextCharFormat MergeHtmlFormats(const QVector<HtmlNode> &stack) { QTextCharFormat f; for (int i=0; i<stack.size(); i++) { f.merge(stack.at(i).format); } return f; } void Html::HtmlToDoc(QTextDocument *doc, const QString &html) { // Empty doc doc->clear(); bool inside_block = true; // Create cursor, which appears to be Qt's official way of inserting blocks and fragments QTextCursor c(doc); QString wrapped = QStringLiteral("<html>").append(html).append("</html>"); QXmlStreamReader reader(wrapped); QVector<HtmlNode> fmt_stack; QTextCharFormat default_fmt; default_fmt.setFontWeight(QFont::Normal); fmt_stack.append({QStringLiteral("html"), default_fmt}); QTextCharFormat current_fmt; while (!reader.atEnd()) { reader.readNext(); if (reader.tokenType() == QXmlStreamReader::StartElement) { QString tag = reader.name().toString().toLower(); fmt_stack.append({tag, ReadCharFormat(reader.attributes())}); current_fmt = MergeHtmlFormats(fmt_stack); if (kBlockTags.contains(tag)) { QTextBlockFormat block_fmt = ReadBlockFormat(reader.attributes()); if (inside_block) { c.setBlockFormat(block_fmt); c.setBlockCharFormat(current_fmt); } else { c.insertBlock(block_fmt, current_fmt); inside_block = true; } } } else if (reader.tokenType() == QXmlStreamReader::Characters) { QString characters = reader.text().toString(); c.insertText(characters, current_fmt); } else if (reader.tokenType() == QXmlStreamReader::EndElement) { QString tag = reader.name().toString().toLower(); for (int i=fmt_stack.size()-1; i>=0; i--) { if (fmt_stack.at(i).tag == tag) { fmt_stack.removeAt(i); current_fmt = MergeHtmlFormats(fmt_stack); if (kBlockTags.contains(tag)) { inside_block = false; } break; } } } } if (reader.error()) { qCritical() << "Failed to parse HTML:" << reader.errorString(); } } void Html::WriteBlock(QXmlStreamWriter *writer, const QTextBlock &block) { writer->writeStartElement(QStringLiteral("p")); const QTextBlockFormat &fmt = block.blockFormat(); // Write block alignment if (!(fmt.alignment() & Qt::AlignLeft)) { if (fmt.alignment() & Qt::AlignRight) { writer->writeAttribute(QStringLiteral("align"), QStringLiteral("right")); } else if (fmt.alignment() & Qt::AlignHCenter) { writer->writeAttribute(QStringLiteral("align"), QStringLiteral("center")); } else if (fmt.alignment() & Qt::AlignJustify) { writer->writeAttribute(QStringLiteral("align"), QStringLiteral("justify")); } } // RTL support if (block.textDirection() == Qt::RightToLeft) { writer->writeAttribute(QStringLiteral("dir"), QStringLiteral("rtl")); } // Write CSS attributes QString style; if (fmt.lineHeightType() != QTextBlockFormat::SingleHeight) { WriteCSSProperty(&style, QStringLiteral("line-height"), QStringLiteral("%1%").arg(fmt.lineHeight())); } WriteCharFormat(&style, block.charFormat()); if (!style.isEmpty()) { writer->writeAttribute(QStringLiteral("style"), style); } auto it = block.begin(); if (it != block.end()) { for (; it!=block.end(); it++) { WriteFragment(writer, it.fragment()); } } writer->writeEndElement(); // p } void Html::WriteFragment(QXmlStreamWriter *writer, const QTextFragment &fragment) { const QTextCharFormat &fmt = fragment.charFormat(); writer->writeStartElement(QStringLiteral("span")); // Write CSS attributes QString style; WriteCharFormat(&style, fmt); if (!style.isEmpty()) { writer->writeAttribute(QStringLiteral("style"), style); } QStringList lines = fragment.text().split(QChar::LineSeparator); bool first_line = true; foreach (const QString &l, lines) { if (first_line) { first_line = false; } else { writer->writeEmptyElement(QStringLiteral("br")); } writer->writeCharacters(l); } writer->writeEndElement(); // span } void Html::WriteCSSProperty(QString *style, const QString &key, const QStringList &values) { QString value; foreach (QString v, values) { if (v.contains(' ')) { v = QStringLiteral("'%1'").arg(v); } AppendStringAutoSpace(&value, v); } AppendStringAutoSpace(style, QStringLiteral("%1: %2;").arg(key, value)); } void Html::WriteCharFormat(QString *style, const QTextCharFormat &fmt) { QStringList families = fmt.fontFamilies().toStringList(); if (!families.isEmpty()) { WriteCSSProperty(style, QStringLiteral("font-family"), families.first()); } if (fmt.hasProperty(QTextFormat::FontPointSize)) { WriteCSSProperty(style, QStringLiteral("font-size"), QStringLiteral("%1pt").arg(QString::number(fmt.fontPointSize()))); } if (fmt.hasProperty(QTextFormat::FontWeight)) { WriteCSSProperty(style, QStringLiteral("font-weight"), QString::number(fmt.fontWeight() * 8)); } if (fmt.hasProperty(QTextFormat::FontItalic)) { WriteCSSProperty(style, QStringLiteral("font-style"), fmt.fontItalic() ? QStringLiteral("italic") : QStringLiteral("normal")); } if (fmt.hasProperty(QTextFormat::FontStyleName)) { WriteCSSProperty(style, QStringLiteral("-ove-font-style"), fmt.fontStyleName().toString()); } QStringList deco; if (fmt.fontUnderline()) { deco.append(QStringLiteral("underline")); } if (fmt.fontStrikeOut()) { deco.append(QStringLiteral("line-through")); } if (fmt.fontOverline()) { deco.append(QStringLiteral("overline")); } if (!deco.isEmpty()) { WriteCSSProperty(style, QStringLiteral("text-decoration"), deco); } if (fmt.foreground().style() != Qt::NoBrush) { const QColor &color = fmt.foreground().color(); QString cs; if (color.alpha() == 255) { cs = color.name(); } else if (color.alpha()) { cs = QStringLiteral("rgba(%1, %2, %3, %4)").arg(QString::number(color.red()), QString::number(color.green()), QString::number(color.blue()), QString::number(color.alphaF())); } WriteCSSProperty(style, QStringLiteral("color"), cs); } if (fmt.fontCapitalization() != QFont::MixedCase) { if (fmt.fontCapitalization() == QFont::SmallCaps) { WriteCSSProperty(style, QStringLiteral("font-variant"), QStringLiteral("small-caps")); // TODO: Add others } } if (fmt.fontLetterSpacing() != 0.0) { WriteCSSProperty(style, QStringLiteral("letter-spacing"), QStringLiteral("%1%").arg(QString::number(fmt.fontLetterSpacing()))); } if (fmt.fontStretch() != 0) { WriteCSSProperty(style, QStringLiteral("font-stretch"), QStringLiteral("%1%").arg(QString::number(fmt.fontStretch()))); } } QTextCharFormat Html::ReadCharFormat(const QXmlStreamAttributes &attributes) { QTextCharFormat fmt; foreach (const QXmlStreamAttribute &attr, attributes) { if (StrEquals(attr.name(), QStringLiteral("style"))) { auto css = GetCSSFromStyle(attr.value().toString()); for (auto it=css.begin(); it!=css.end(); it++) { const QString &first_val = it.value().first(); if (it.key() == QStringLiteral("font-family")) { fmt.setFontFamilies({first_val}); } else if (it.key() == QStringLiteral("font-size")) { if (first_val.endsWith(QStringLiteral("pt"), Qt::CaseInsensitive)) { fmt.setFontPointSize(first_val.chopped(2).toDouble()); } } else if (it.key() == QStringLiteral("font-weight")) { fmt.setFontWeight(first_val.toInt()/8); } else if (it.key() == QStringLiteral("font-style")) { fmt.setFontItalic(StrEquals(first_val, QStringLiteral("italic"))); } else if (it.key() == QStringLiteral("text-decoration")) { foreach (const QString &v, it.value()) { if (StrEquals(v, QStringLiteral("underline"))) { fmt.setFontUnderline(true); } else if (StrEquals(v, QStringLiteral("line-through"))) { fmt.setFontStrikeOut(true); } else if (StrEquals(v, QStringLiteral("overline"))) { fmt.setFontOverline(true); } } } else if (it.key() == QStringLiteral("color")) { if (first_val.startsWith(QStringLiteral("rgba"), Qt::CaseInsensitive)) { QString vals_only = first_val; vals_only.remove(QStringLiteral("rgba")); vals_only.remove(QStringLiteral("(")); vals_only.remove(QStringLiteral(")")); QStringList rgba = vals_only.split(','); if (rgba.size() == 4) { QColor c; c.setRedF(rgba.at(0).toDouble()); c.setGreenF(rgba.at(1).toDouble()); c.setBlueF(rgba.at(2).toDouble()); c.setAlphaF(rgba.at(3).toDouble()); fmt.setForeground(c); } } else { fmt.setForeground(QColor(first_val)); } } else if (it.key() == QStringLiteral("font-variant")) { if (StrEquals(first_val, QStringLiteral("small-caps"))) { fmt.setFontCapitalization(QFont::SmallCaps); } } else if (it.key() == QStringLiteral("letter-spacing")) { if (first_val.contains(QChar('%'))) { fmt.setFontLetterSpacing(first_val.chopped(1).toDouble()); } } else if (it.key() == QStringLiteral("font-stretch")) { if (first_val.contains(QChar('%'))) { fmt.setFontStretch(first_val.chopped(1).toInt()); } } else if (it.key() == QStringLiteral("-ove-font-style")) { fmt.setFontStyleName(first_val); } } } } return fmt; } QTextBlockFormat Html::ReadBlockFormat(const QXmlStreamAttributes &attributes) { QTextBlockFormat block_fmt; foreach (const QXmlStreamAttribute &attr, attributes) { if (StrEquals(attr.name(), QStringLiteral("align"))) { if (StrEquals(attr.value(), QStringLiteral("right"))) { block_fmt.setAlignment(Qt::AlignRight); } else if (StrEquals(attr.value(), QStringLiteral("center"))) { block_fmt.setAlignment(Qt::AlignHCenter); } else if (StrEquals(attr.value(), QStringLiteral("justify"))) { block_fmt.setAlignment(Qt::AlignJustify); } } else if (StrEquals(attr.name(), QStringLiteral("dir"))) { if (StrEquals(attr.value(), QStringLiteral("rtl"))) { block_fmt.setLayoutDirection(Qt::RightToLeft); } } else if (StrEquals(attr.name(), QStringLiteral("style"))) { auto css = GetCSSFromStyle(attr.value().toString()); for (auto it=css.begin(); it!=css.end(); it++) { if (it.key() == QStringLiteral("line-height")) { const QString &first_val = it.value().constFirst(); if (first_val.contains(QChar('%'))) { block_fmt.setLineHeight(first_val.chopped(1).toDouble(), QTextBlockFormat::ProportionalHeight); } } } } } return block_fmt; } void Html::AppendStringAutoSpace(QString *s, const QString &append) { if (!s->isEmpty()) { s->append(QChar(' ')); } s->append(append); } QMap<QString, QStringList> Html::GetCSSFromStyle(const QString &s) { QMap<QString, QStringList> map; QStringList list = s.split(QChar(';')); foreach (const QString &a, list) { QStringList kv = a.split(QChar(':')); if (kv.size() != 2) { continue; } // I'm sure there's regex that could do this, but I couldn't figure it out. It needs to split // by space EXCEPT within quotes OR double-quotes, and said quotes should be EXCLUDED from each // match. Also commas should be filtered out. QStringList values; const QString &val = kv.at(1); QChar in_quote(0); QString current_str; for (int i=0; i<val.size(); i++) { const QChar &current_char = val.at(i); if (!in_quote.isNull()) { // If inside quotes and character isn't quote, indiscriminately append char if (current_char == in_quote) { in_quote = QChar(0); } else { current_str.append(current_char); } } else if (current_char.isSpace() || current_char == QChar(',')) { // Dump current if (!current_str.isEmpty()) { values.append(current_str); current_str.clear(); } } else if (in_quote.isNull() && (current_char == QChar('\'') || current_char == QChar('"'))) { in_quote = current_char; } else { current_str.append(current_char); } } if (!current_str.isEmpty()) { values.append(current_str); } // Not sure if this will ever happen, but just in case, we will avoid assert failures with this if (values.isEmpty()) { values.append(QString()); } map[kv.at(0).trimmed().toLower()] = values; } return map; } }
13,507
C++
.cpp
360
31.591667
180
0.642031
olive-editor/olive
8,144
552
131
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
19,078
crashpadinterface.cpp
olive-editor_olive/app/common/crashpadinterface.cpp
/*** Olive - Non-Linear Video Editor Copyright (C) 2022 Olive Team 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 <http://www.gnu.org/licenses/>. ***/ #include "crashpadinterface.h" #ifdef USE_CRASHPAD #include <QCoreApplication> #include <QDateTime> #include <QDebug> #include <QDir> #include <QMessageBox> #include <QProcess> #include "crashpadutils.h" #include "filefunctions.h" #if BUILDFLAG(IS_WIN) #include <Windows.h> #endif crashpad::CrashpadClient *client; bool InitializeCrashpad() { QString report_path = QDir(olive::FileFunctions::GetTempFilePath()).filePath(QStringLiteral("reports")); QString handler_fn = olive::FileFunctions::GetFormattedExecutableForPlatform(QStringLiteral("crashpad_handler")); // Generate absolute path QString handler_abs_path = QDir(QCoreApplication::applicationDirPath()).filePath(handler_fn); bool status = false; if (QFileInfo::exists(handler_abs_path)) { base::FilePath handler(QSTRING_TO_BASE_STRING(handler_abs_path)); base::FilePath reports_dir(QSTRING_TO_BASE_STRING(report_path)); base::FilePath metrics_dir(QSTRING_TO_BASE_STRING(QDir(olive::FileFunctions::GetTempFilePath()).filePath(QStringLiteral("metrics")))); // Metadata that will be posted to the server with the crash report map std::map<std::string, std::string> annotations; // Disable crashpad rate limiting so that all crashes have dmp files std::vector<std::string> arguments; arguments.push_back("--no-rate-limit"); arguments.push_back("--no-upload-gzip"); // Initialize Crashpad database std::unique_ptr<crashpad::CrashReportDatabase> database = crashpad::CrashReportDatabase::Initialize(reports_dir); if (database == NULL) return false; // Disable automated crash uploads crashpad::Settings *settings = database->GetSettings(); if (settings == NULL) return false; settings->SetUploadsEnabled(false); // Start crash handler client = new crashpad::CrashpadClient(); status = client->StartHandler(handler, reports_dir, metrics_dir, "https://olivevideoeditor.org/crashpad/report.php", annotations, arguments, true, true); } // Override Crashpad exception filter with our own if (!status) { qWarning() << "Failed to start Crashpad, automatic crash reporting will be disabled"; } return status; } #endif // USE_CRASHPAD
2,979
C++
.cpp
65
41.446154
138
0.74169
olive-editor/olive
8,144
552
131
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
19,079
ffmpegutils.cpp
olive-editor_olive/app/common/ffmpegutils.cpp
/*** Olive - Non-Linear Video Editor Copyright (C) 2022 Olive Team 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 <http://www.gnu.org/licenses/>. ***/ #include "common/ffmpegutils.h" namespace olive { AVPixelFormat FFmpegUtils::GetCompatiblePixelFormat(const AVPixelFormat &pix_fmt, PixelFormat maximum) { AVPixelFormat possible_pix_fmts[3]; possible_pix_fmts[0] = AV_PIX_FMT_RGBA; if (maximum == PixelFormat::U8) { possible_pix_fmts[1] = AV_PIX_FMT_NONE; } else { possible_pix_fmts[1] = AV_PIX_FMT_RGBA64; possible_pix_fmts[2] = AV_PIX_FMT_NONE; } return avcodec_find_best_pix_fmt_of_list(possible_pix_fmts, pix_fmt, 1, nullptr); } SampleFormat FFmpegUtils::GetNativeSampleFormat(const AVSampleFormat &smp_fmt) { switch (smp_fmt) { case AV_SAMPLE_FMT_U8: return SampleFormat::U8; case AV_SAMPLE_FMT_S16: return SampleFormat::S16; case AV_SAMPLE_FMT_S32: return SampleFormat::S32; case AV_SAMPLE_FMT_S64: return SampleFormat::S64; case AV_SAMPLE_FMT_FLT: return SampleFormat::F32; case AV_SAMPLE_FMT_DBL: return SampleFormat::F64; case AV_SAMPLE_FMT_U8P : return SampleFormat::U8P; case AV_SAMPLE_FMT_S16P: return SampleFormat::S16P; case AV_SAMPLE_FMT_S32P: return SampleFormat::S32P; case AV_SAMPLE_FMT_S64P: return SampleFormat::S64P; case AV_SAMPLE_FMT_FLTP: return SampleFormat::F32P; case AV_SAMPLE_FMT_DBLP: return SampleFormat::F64P; case AV_SAMPLE_FMT_NONE: case AV_SAMPLE_FMT_NB: break; } return SampleFormat::INVALID; } AVSampleFormat FFmpegUtils::GetFFmpegSampleFormat(const SampleFormat &smp_fmt) { switch (smp_fmt) { case SampleFormat::U8: return AV_SAMPLE_FMT_U8; case SampleFormat::S16: return AV_SAMPLE_FMT_S16; case SampleFormat::S32: return AV_SAMPLE_FMT_S32; case SampleFormat::S64: return AV_SAMPLE_FMT_S64; case SampleFormat::F32: return AV_SAMPLE_FMT_FLT; case SampleFormat::F64: return AV_SAMPLE_FMT_DBL; case SampleFormat::U8P: return AV_SAMPLE_FMT_U8P; case SampleFormat::S16P: return AV_SAMPLE_FMT_S16P; case SampleFormat::S32P: return AV_SAMPLE_FMT_S32P; case SampleFormat::S64P: return AV_SAMPLE_FMT_S64P; case SampleFormat::F32P: return AV_SAMPLE_FMT_FLTP; case SampleFormat::F64P: return AV_SAMPLE_FMT_DBLP; case SampleFormat::INVALID: case SampleFormat::COUNT: break; } return AV_SAMPLE_FMT_NONE; } int FFmpegUtils::GetSwsColorspaceFromAVColorSpace(AVColorSpace cs) { switch (cs) { case AVCOL_SPC_BT709: return SWS_CS_ITU709; case AVCOL_SPC_FCC: return SWS_CS_FCC; case AVCOL_SPC_BT470BG: return SWS_CS_ITU624; case AVCOL_SPC_SMPTE170M: return SWS_CS_SMPTE170M; case AVCOL_SPC_SMPTE240M: return SWS_CS_SMPTE240M; case AVCOL_SPC_BT2020_NCL: return SWS_CS_BT2020; default: break; } return SWS_CS_DEFAULT; } AVPixelFormat FFmpegUtils::ConvertJPEGSpaceToRegularSpace(AVPixelFormat f) { switch (f) { case AV_PIX_FMT_YUVJ420P: return AV_PIX_FMT_YUV420P; case AV_PIX_FMT_YUVJ422P: return AV_PIX_FMT_YUV422P; case AV_PIX_FMT_YUVJ444P: return AV_PIX_FMT_YUV444P; case AV_PIX_FMT_YUVJ440P: return AV_PIX_FMT_YUV440P; case AV_PIX_FMT_YUVJ411P: return AV_PIX_FMT_YUV411P; default: break; } return f; } AVPixelFormat FFmpegUtils::GetFFmpegPixelFormat(const PixelFormat &pix_fmt, int channel_layout) { if (channel_layout == VideoParams::kRGBChannelCount) { switch (pix_fmt) { case PixelFormat::U8: return AV_PIX_FMT_RGB24; case PixelFormat::U16: return AV_PIX_FMT_RGB48; case PixelFormat::F16: case PixelFormat::F32: case PixelFormat::INVALID: case PixelFormat::COUNT: break; } } else if (channel_layout == VideoParams::kRGBAChannelCount) { switch (pix_fmt) { case PixelFormat::U8: return AV_PIX_FMT_RGBA; case PixelFormat::U16: return AV_PIX_FMT_RGBA64; case PixelFormat::F16: case PixelFormat::F32: case PixelFormat::INVALID: case PixelFormat::COUNT: break; } } return AV_PIX_FMT_NONE; } PixelFormat FFmpegUtils::GetCompatiblePixelFormat(const PixelFormat &pix_fmt) { switch (pix_fmt) { case PixelFormat::U8: return PixelFormat::U8; case PixelFormat::U16: case PixelFormat::F16: case PixelFormat::F32: return PixelFormat::U16; case PixelFormat::INVALID: case PixelFormat::COUNT: break; } return PixelFormat::INVALID; } }
5,153
C++
.cpp
175
25.125714
102
0.715785
olive-editor/olive
8,144
552
131
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
19,080
jobtime.cpp
olive-editor_olive/app/common/jobtime.cpp
#include "jobtime.h" #include <QMutex> namespace olive { uint64_t job_time_index = 0; QMutex job_time_mutex; JobTime::JobTime() { Acquire(); } void JobTime::Acquire() { job_time_mutex.lock(); value_ = job_time_index; job_time_index++; job_time_mutex.unlock(); } } QDebug operator<<(QDebug debug, const olive::JobTime& r) { return debug.space() << r.value(); }
381
C++
.cpp
21
16.142857
56
0.703704
olive-editor/olive
8,144
552
131
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
19,081
ratiodialog.cpp
olive-editor_olive/app/common/ratiodialog.cpp
/*** Olive - Non-Linear Video Editor Copyright (C) 2022 Olive Team 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 <http://www.gnu.org/licenses/>. ***/ #include "ratiodialog.h" #include <QCoreApplication> #include <QMessageBox> #include <QRegularExpression> namespace olive { double GetFloatRatioFromUser(QWidget* parent, const QString& title, bool* ok_in) { QString s; forever { bool ok; s = QInputDialog::getText(parent, title, QCoreApplication::translate("RatioDialog", "Enter custom ratio (e.g. \"4:3\", \"16/9\", etc.):"), QLineEdit::Normal, s, &ok); if (!ok) { // User cancelled dialog, do nothing if (ok_in) { *ok_in = false; } return qSNaN(); } QStringList ratio_components = s.split(QRegularExpression(QStringLiteral(":|;|\\/"))); if (ratio_components.size() == 1) { bool float_ok; double flt = ratio_components.at(0).toDouble(&float_ok); if (float_ok && flt > 0) { if (ok_in) { *ok_in = true; } return flt; } } else if (ratio_components.size() == 2) { bool numer_ok, denom_ok; double num = ratio_components.at(0).toDouble(&numer_ok); double den = ratio_components.at(1).toDouble(&denom_ok); if (numer_ok && denom_ok && num > 0 && den > 0) { // Exit loop and set this ratio if (ok_in) { *ok_in = true; } return num / den; } } QMessageBox::warning(parent, QCoreApplication::translate("RatioDialog", "Invalid custom ratio"), QCoreApplication::translate("RatioDialog", "Failed to parse \"%1\" into an aspect ratio. Please format a " "rational fraction with a ':' or a '/' separator.").arg(s), QMessageBox::Ok); } } }
2,682
C++
.cpp
72
27.513889
131
0.56834
olive-editor/olive
8,144
552
131
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
19,082
xmlutils.cpp
olive-editor_olive/app/common/xmlutils.cpp
/*** Olive - Non-Linear Video Editor Copyright (C) 2022 Olive Team 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 <http://www.gnu.org/licenses/>. ***/ #include "xmlutils.h" #include "node/block/block.h" #include "node/factory.h" namespace olive { bool XMLReadNextStartElement(QXmlStreamReader *reader, CancelAtom *cancel_atom) { QXmlStreamReader::TokenType token; while ((token = reader->readNext()) != QXmlStreamReader::Invalid && token != QXmlStreamReader::EndDocument && (!cancel_atom || !cancel_atom->IsCancelled())) { if (reader->isEndElement()) { return false; } else if (reader->isStartElement()) { return true; } } return false; } }
1,258
C++
.cpp
33
34.515152
79
0.735367
olive-editor/olive
8,144
552
131
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
19,083
filefunctions.cpp
olive-editor_olive/app/common/filefunctions.cpp
/*** Olive - Non-Linear Video Editor Copyright (C) 2022 Olive Team 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 <http://www.gnu.org/licenses/>. ***/ #include "filefunctions.h" #include <QCoreApplication> #include <QCryptographicHash> #include <QDateTime> #include <QDir> #include <QFileInfo> #include <QStandardPaths> #include "config/config.h" namespace olive { QString FileFunctions::GetUniqueFileIdentifier(const QString &filename) { QFileInfo info(filename); if (!info.exists()) { return QString(); } QCryptographicHash hash(QCryptographicHash::Sha1); hash.addData(info.absoluteFilePath().toUtf8()); hash.addData(QString::number(info.lastModified().toMSecsSinceEpoch()).toUtf8()); QByteArray result = hash.result(); return QString(result.toHex()); } QString FileFunctions::GetConfigurationLocation() { if (IsPortable()) { return GetApplicationPath(); } else { QString s = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation); QDir(s).mkpath("."); return s; } } bool FileFunctions::IsPortable() { return QFileInfo::exists(QDir(GetApplicationPath()).filePath("portable")); } QString FileFunctions::GetApplicationPath() { return QCoreApplication::applicationDirPath(); } QString FileFunctions::GetTempFilePath() { QString temp_path = QDir(QDir(QStandardPaths::writableLocation(QStandardPaths::TempLocation)) .filePath(QCoreApplication::organizationName())) .filePath(QCoreApplication::applicationName()); // Ensure it exists QDir(temp_path).mkpath("."); return temp_path; } bool FileFunctions::CanCopyDirectoryWithoutOverwriting(const QString& source, const QString& dest) { QFileInfoList info_list = QDir(source).entryInfoList(); foreach (const QFileInfo& info, info_list) { // QDir::NoDotAndDotDot continues to not work, so we have to check manually if (info.fileName() == QStringLiteral(".") || info.fileName() == QStringLiteral("..")) { continue; } QString dest_equivalent = QDir(dest).filePath(info.fileName()); if (info.isDir()) { if (!CanCopyDirectoryWithoutOverwriting(info.absoluteFilePath(), dest_equivalent)) { return false; } } else if (QFileInfo::exists(dest_equivalent)) { return false; } } return true; } void FileFunctions::CopyDirectory(const QString &source, const QString &dest, bool overwrite) { QDir d(source); if (!d.exists()) { qCritical() << "Failed to copy directory, source" << source << "didn't exist"; return; } QDir dest_dir(dest); if (!dest_dir.mkpath(QStringLiteral("."))) { qCritical() << "Failed to create destination directory" << dest; return; } QFileInfoList l = d.entryInfoList(); foreach (const QFileInfo& info, l) { // QDir::NoDotAndDotDot continues to not work, so we have to check manually if (info.fileName() == QStringLiteral(".") || info.fileName() == QStringLiteral("..")) { continue; } QString dest_file_path = dest_dir.filePath(info.fileName()); if (info.isDir()) { // Copy dir CopyDirectory(info.absoluteFilePath(), dest_file_path, overwrite); } else { // Copy file if (overwrite && QFile::exists(dest_file_path)) { QFile file(dest_file_path); file.setPermissions(file.permissions() | QFileDevice::WriteOwner | QFileDevice::WriteUser | QFileDevice::WriteGroup | QFileDevice::WriteOther); file.remove(); } QFile::copy(info.absoluteFilePath(), dest_file_path); } } } bool FileFunctions::DirectoryIsValid(const QDir &d, bool try_to_create_if_not_exists) { // Return whether the directory exists, or whether it could be created if it doesn't return d.exists() || d.mkpath(QStringLiteral(".")); } QString FileFunctions::EnsureFilenameExtension(QString fn, const QString &extension) { // No-op if either input is empty if (!fn.isEmpty() && !extension.isEmpty()) { QString extension_with_dot; extension_with_dot.append('.'); extension_with_dot.append(extension); if (!fn.endsWith(extension_with_dot, Qt::CaseInsensitive)) { fn.append(extension_with_dot); } } return fn; } QString FileFunctions::ReadFileAsString(const QString &filename) { QFile f(filename); QString file_data; if (f.open(QFile::ReadOnly | QFile::Text)) { QTextStream text_stream(&f); file_data = text_stream.readAll(); f.close(); } return file_data; } QString FileFunctions::GetSafeTemporaryFilename(const QString &original) { int counter = 0; QFileInfo original_info(original); QString basename = original_info.baseName(); QString complete_suffix = original_info.completeSuffix(); // If we have a complete suffix, make sure there's a period in it if (!complete_suffix.isEmpty()) { complete_suffix.prepend('.'); } QString temp_abs_path; do { temp_abs_path = original_info.dir().filePath( QStringLiteral("%1.tmp%2%3").arg(basename, QString::number(counter), complete_suffix)); counter++; } while (QFileInfo::exists(temp_abs_path)); return temp_abs_path; } bool FileFunctions::RenameFileAllowOverwrite(const QString &from, const QString &to) { if (QFileInfo::exists(to) && !QFile::remove(to)) { qCritical() << "Couldn't remove existing file" << to << "for overwrite"; return false; } // By this point, we can assume `to` either never existed or has now been deleted if (!QFile::rename(from, to)) { qCritical() << "Failed to rename file" << from << "to" << to; return false; } return true; } QString FileFunctions::GetAutoRecoveryRoot() { return QDir(QStandardPaths::writableLocation(QStandardPaths::AppLocalDataLocation)).filePath(QStringLiteral("autorecovery")); } }
6,428
C++
.cpp
182
30.983516
127
0.703746
olive-editor/olive
8,144
552
131
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
19,084
debug.cpp
olive-editor_olive/app/common/debug.cpp
/*** Olive - Non-Linear Video Editor Copyright (C) 2022 Olive Team 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 <http://www.gnu.org/licenses/>. ***/ #include "debug.h" namespace olive { void DebugHandler(QtMsgType type, const QMessageLogContext &context, const QString &msg) { QByteArray localMsg = msg.toLocal8Bit(); const char* msg_type = "UNKNOWN"; switch (type) { case QtDebugMsg: msg_type = "DEBUG"; break; case QtInfoMsg: msg_type = "INFO"; break; case QtWarningMsg: msg_type = "WARNING"; break; case QtCriticalMsg: msg_type = "ERROR"; break; case QtFatalMsg: msg_type = "FATAL"; break; } //fprintf(stderr, "[%s] %s (%s:%u)\n", msg_type, localMsg.constData(), context.function, context.line); fprintf(stderr, "[%s] %s\n", msg_type, localMsg.constData()); #ifdef Q_OS_WINDOWS // Windows still seems to buffer stderr and we want to see debug messages immediately, so here we make sure each line // is flushed fflush(stderr); #endif } }
1,577
C++
.cpp
46
31.021739
119
0.725477
olive-editor/olive
8,144
552
131
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
19,085
audiomanager.cpp
olive-editor_olive/app/audio/audiomanager.cpp
/*** Olive - Non-Linear Video Editor Copyright (C) 2022 Olive Team 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 <http://www.gnu.org/licenses/>. ***/ #include "audiomanager.h" #ifdef PA_HAS_JACK #include <pa_jack.h> #endif #include <QApplication> #include "config/config.h" namespace olive { AudioManager* AudioManager::instance_ = nullptr; void AudioManager::CreateInstance() { if (instance_ == nullptr) { instance_ = new AudioManager(); } } void AudioManager::DestroyInstance() { delete instance_; instance_ = nullptr; } AudioManager *AudioManager::instance() { return instance_; } void AudioManager::SetOutputNotifyInterval(int n) { output_buffer_->set_notify_interval(n); } int OutputCallback(const void *input, void *output, unsigned long frameCount, const PaStreamCallbackTimeInfo *timeInfo, PaStreamCallbackFlags statusFlags, void *userData) { PreviewAudioDevice *device = static_cast<PreviewAudioDevice*>(userData); qint64 max_read = frameCount * device->bytes_per_frame(); qint64 read_count = device->read(reinterpret_cast<char*>(output), max_read); if (read_count < max_read) { memset(reinterpret_cast<uint8_t*>(output) + read_count, 0, max_read - read_count); } return paContinue; } int InputCallback(const void *input, void *output, unsigned long frameCount, const PaStreamCallbackTimeInfo *timeInfo, PaStreamCallbackFlags statusFlags, void *userData) { FFmpegEncoder *f = static_cast<FFmpegEncoder*>(userData); AudioParams our_params = f->params().audio_params(); our_params.set_format(f->params().audio_params().format().to_packed_equivalent()); f->WriteAudioData(our_params, reinterpret_cast<const uint8_t**>(&input), frameCount); return paContinue; } bool AudioManager::PushToOutput(const AudioParams &params, const QByteArray &samples, QString *error) { if (output_device_ == paNoDevice) { if (error) *error = tr("No output device is set"); return false; } if (output_params_ != params || output_stream_ == nullptr) { output_params_ = params; CloseOutputStream(); PaStreamParameters p = GetPortAudioParams(params, output_device_); PaError r = Pa_OpenStream(&output_stream_, nullptr, &p, output_params_.sample_rate(), paFramesPerBufferUnspecified, paNoFlag, OutputCallback, output_buffer_); if (r != paNoError) { // Unhandled error //qCritical() << "Failed to open output stream:" << Pa_GetErrorText(r); if (error) *error = Pa_GetErrorText(r); return false; } output_buffer_->set_bytes_per_frame(output_params_.samples_to_bytes(1)); } output_buffer_->write(samples); if (!Pa_IsStreamActive(output_stream_)) { Pa_StartStream(output_stream_); } return true; } void AudioManager::ClearBufferedOutput() { output_buffer_->clear(); } PaSampleFormat AudioManager::GetPortAudioSampleFormat(SampleFormat fmt) { switch (fmt) { case SampleFormat::U8: case SampleFormat::U8P: return paUInt8; case SampleFormat::S16: case SampleFormat::S16P: return paInt16; case SampleFormat::S32: case SampleFormat::S32P: return paInt32; case SampleFormat::F32: case SampleFormat::F32P: return paFloat32; case SampleFormat::S64: case SampleFormat::S64P: case SampleFormat::F64: case SampleFormat::F64P: case SampleFormat::INVALID: case SampleFormat::COUNT: break; } return 0; } void AudioManager::CloseOutputStream() { if (output_stream_) { if (Pa_IsStreamActive(output_stream_)) { StopOutput(); } Pa_CloseStream(output_stream_); output_stream_ = nullptr; } } void AudioManager::StopOutput() { // Abort the stream so playback stops immediately if (output_stream_) { Pa_AbortStream(output_stream_); ClearBufferedOutput(); } } void AudioManager::SetOutputDevice(PaDeviceIndex device) { if (device == paNoDevice) { qInfo() << "No output device found"; } else { qInfo() << "Setting output audio device to" << Pa_GetDeviceInfo(device)->name; } output_device_ = device; CloseOutputStream(); } void AudioManager::SetInputDevice(PaDeviceIndex device) { if (device == paNoDevice) { qInfo() << "No input device found"; } else { qInfo() << "Setting input audio device to" << Pa_GetDeviceInfo(device)->name; } input_device_ = device; } void AudioManager::HardReset() { CloseOutputStream(); Pa_Terminate(); Pa_Initialize(); } bool AudioManager::StartRecording(const EncodingParams &params, QString *error_str) { if (input_device_ == paNoDevice) { return false; } input_encoder_ = new FFmpegEncoder(params); if (!input_encoder_->Open()) { qCritical() << "Failed to open encoder for recording"; return false; } PaStreamParameters p = GetPortAudioParams(params.audio_params(), input_device_); PaError r = Pa_OpenStream(&input_stream_, &p, nullptr, params.audio_params().sample_rate(), paFramesPerBufferUnspecified, paNoFlag, InputCallback, input_encoder_); if (r == paNoError) { //const PaStreamInfo* info = Pa_GetStreamInfo(input_stream_); r = Pa_StartStream(input_stream_); if (r == paNoError) { return true; } } if (error_str) { *error_str = Pa_GetErrorText(r); } StopRecording(); return false; } void AudioManager::StopRecording() { if (input_stream_) { if (Pa_IsStreamActive(input_stream_)) { Pa_StopStream(input_stream_); } Pa_CloseStream(input_stream_); input_stream_ = nullptr; } if (input_encoder_) { input_encoder_->Close(); delete input_encoder_; input_encoder_ = nullptr; } } PaDeviceIndex AudioManager::FindConfigDeviceByName(bool is_output_device) { QString entry = is_output_device ? QStringLiteral("AudioOutput") : QStringLiteral("AudioInput"); return FindDeviceByName(OLIVE_CONFIG_STR(entry).toString(), is_output_device); } PaDeviceIndex AudioManager::FindDeviceByName(const QString &s, bool is_output_device) { if (!s.isEmpty()) { for (PaDeviceIndex i=0, end=Pa_GetDeviceCount(); i<end; i++) { const PaDeviceInfo *device = Pa_GetDeviceInfo(i); if (((is_output_device && device->maxOutputChannels) || (!is_output_device && device->maxInputChannels)) && !s.compare(device->name)) { return i; } } } return is_output_device ? Pa_GetDefaultOutputDevice() : Pa_GetDefaultInputDevice(); } PaStreamParameters AudioManager::GetPortAudioParams(const AudioParams &params, PaDeviceIndex device) { PaStreamParameters p; p.channelCount = params.channel_count(); p.device = device; p.hostApiSpecificStreamInfo = nullptr; p.sampleFormat = GetPortAudioSampleFormat(params.format()); p.suggestedLatency = Pa_GetDeviceInfo(device)->defaultLowOutputLatency; return p; } AudioManager::AudioManager() : output_stream_(nullptr), input_stream_(nullptr), input_encoder_(nullptr) { #ifdef PA_HAS_JACK // PortAudio doesn't do a strcpy, so we need a const char that's readily accessible (i.e. not // a QString converted to UTF-8) PaJack_SetClientName("Olive"); #endif Pa_Initialize(); // Get device from config PaDeviceIndex output_device = FindConfigDeviceByName(true); PaDeviceIndex input_device = FindConfigDeviceByName(false); SetOutputDevice(output_device); SetInputDevice(input_device); output_buffer_ = new PreviewAudioDevice(this); output_buffer_->open(PreviewAudioDevice::ReadWrite); connect(output_buffer_, &PreviewAudioDevice::Notify, this, &AudioManager::OutputNotify); } AudioManager::~AudioManager() { CloseOutputStream(); Pa_Terminate(); } }
8,109
C++
.cpp
250
29.208
170
0.731134
olive-editor/olive
8,144
552
131
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
19,086
audioprocessor.cpp
olive-editor_olive/app/audio/audioprocessor.cpp
/*** Olive - Non-Linear Video Editor Copyright (C) 2022 Olive Team 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 <http://www.gnu.org/licenses/>. ***/ #include "audioprocessor.h" extern "C" { #include <libavfilter/buffersrc.h> #include <libavfilter/buffersink.h> } #include <QDebug> #include "common/ffmpegutils.h" namespace olive { AudioProcessor::AudioProcessor() { filter_graph_ = nullptr; in_frame_ = nullptr; out_frame_ = nullptr; } AudioProcessor::~AudioProcessor() { Close(); } bool AudioProcessor::Open(const AudioParams &from, const AudioParams &to, double tempo) { if (filter_graph_) { qWarning() << "Tried to open a processor that was already open"; return false; } filter_graph_ = avfilter_graph_alloc(); if (!filter_graph_) { qCritical() << "Failed to allocate filter graph"; return false; } from_fmt_ = FFmpegUtils::GetFFmpegSampleFormat(from.format()); to_fmt_ = FFmpegUtils::GetFFmpegSampleFormat(to.format()); // Set up audio buffer args char filter_args[200]; snprintf(filter_args, 200, "time_base=%d/%d:sample_rate=%d:sample_fmt=%d:channel_layout=0x%" PRIx64, 1, from.sample_rate(), from.sample_rate(), from_fmt_, from.channel_layout()); int r; // Create buffersrc (input) r = avfilter_graph_create_filter(&buffersrc_ctx_, avfilter_get_by_name("abuffer"), "in", filter_args, nullptr, filter_graph_); if (r < 0) { qCritical() << "Failed to create buffersrc:" << r; Close(); return false; } // Store "previous" filter for linking AVFilterContext *previous_filter = buffersrc_ctx_; // Create tempo bool create_tempo; if ((create_tempo = !qFuzzyCompare(tempo, 1.0))) { // Create audio tempo filters: FFmpeg's atempo can only be set between 0.5 and 2.0. If the requested speed is outside // those boundaries, we need to daisychain more than one together. double base = (tempo > 1.0) ? 2.0 : 0.5; double speed_log = log(tempo) / log(base); // This is the number of how many 0.5 or 2.0 tempos we need to daisychain int whole = std::floor(speed_log); // Set speed_log to the remainder speed_log -= whole; for (int i=0;i<=whole;i++) { double filter_tempo = (i == whole) ? std::pow(base, speed_log) : base; if (qFuzzyCompare(filter_tempo, 1.0)) { // This filter would do nothing continue; } previous_filter = CreateTempoFilter(filter_graph_, previous_filter, filter_tempo); if (!previous_filter) { qCritical() << "Failed to create audio tempo filter"; Close(); return false; } } } // Create conversion filter if (from.sample_rate() != to.sample_rate() || from.channel_layout() != to.channel_layout() || from.format() != to.format() || (to.format().is_planar() && create_tempo)) { // Tempo processor automatically converts to packed, // so if the desired output is planar, it'll need // to be converted snprintf(filter_args, 200, "sample_fmts=%s:sample_rates=%d:channel_layouts=0x%" PRIx64, av_get_sample_fmt_name(to_fmt_), to.sample_rate(), to.channel_layout()); AVFilterContext *c; r = avfilter_graph_create_filter(&c, avfilter_get_by_name("aformat"), "fmt", filter_args, nullptr, filter_graph_); if (r < 0) { qCritical() << "Failed to create format conversion filter:" << r << filter_args; Close(); return false; } r = avfilter_link(previous_filter, 0, c, 0); if (r < 0) { qCritical() << "Failed to link filters:" << r; Close(); return false; } previous_filter = c; } // Create buffersink (output) r = avfilter_graph_create_filter(&buffersink_ctx_, avfilter_get_by_name("abuffersink"), "out", nullptr, nullptr, filter_graph_); if (r < 0) { qCritical() << "Failed to create buffersink:" << r; Close(); return false; } r = avfilter_link(previous_filter, 0, buffersink_ctx_, 0); if (r < 0) { qCritical() << "Failed to link filters:" << r; Close(); return false; } r = avfilter_graph_config(filter_graph_, nullptr); if (r < 0) { qCritical() << "Failed to configure graph:" << r; Close(); return false; } in_frame_ = av_frame_alloc(); if (in_frame_) { in_frame_->sample_rate = from.sample_rate(); in_frame_->format = from_fmt_; in_frame_->channel_layout = from.channel_layout(); in_frame_->channels = from.channel_count(); in_frame_->pts = 0; } else { qCritical() << "Failed to allocate input frame"; Close(); return false; } out_frame_ = av_frame_alloc(); if (!out_frame_) { qCritical() << "Failed to allocate output frame"; Close(); return false; } from_ = from; to_ = to; return true; } void AudioProcessor::Close() { if (filter_graph_) { avfilter_graph_free(&filter_graph_); filter_graph_ = nullptr; buffersrc_ctx_ = nullptr; buffersink_ctx_ = nullptr; } if (in_frame_) { av_frame_free(&in_frame_); in_frame_ = nullptr; } if (out_frame_) { av_frame_free(&out_frame_); out_frame_ = nullptr; } } int AudioProcessor::Convert(float **in, int nb_in_samples, AudioProcessor::Buffer *output) { if (!IsOpen()) { qCritical() << "Tried to convert on closed processor"; return -1; } int r = 0; if (in && nb_in_samples) { // Set frame parameters in_frame_->nb_samples = nb_in_samples; for (int i=0; i<from_.channel_count(); i++) { in_frame_->data[i] = reinterpret_cast<uint8_t*>(in[i]); in_frame_->linesize[i] = from_.samples_to_bytes(nb_in_samples); } r = av_buffersrc_add_frame_flags(buffersrc_ctx_, in_frame_, AV_BUFFERSRC_FLAG_KEEP_REF); if (r < 0) { qCritical() << "Failed to add frame to buffersrc:" << r; return r; } } if (output) { int nb_channels = to_.channel_count(); if (to_.format().is_packed()) { nb_channels = 1; } AudioProcessor::Buffer &result = *output; result.resize(nb_channels); int byte_offset = 0; while (true) { av_frame_unref(out_frame_); r = av_buffersink_get_frame(buffersink_ctx_, out_frame_); if (r < 0) { if (r == AVERROR(EAGAIN)) { r = 0; } else { // Handle unexpected error qCritical() << "Failed to pull from buffersink:" << r; } break; } int nb_bytes = out_frame_->nb_samples * to_.bytes_per_sample_per_channel(); if (to_.format().is_packed()) { nb_bytes *= to_.channel_count(); } for (int i=0; i<nb_channels; i++) { result[i].resize(byte_offset + nb_bytes); memcpy(result[i].data() + byte_offset, out_frame_->data[i], nb_bytes); } byte_offset += nb_bytes; } av_frame_unref(out_frame_); } return r; } void AudioProcessor::Flush() { int r = av_buffersrc_add_frame_flags(buffersrc_ctx_, nullptr, AV_BUFFERSRC_FLAG_KEEP_REF); if (r < 0) { qCritical() << "Failed to flush:" << r; } } AVFilterContext *AudioProcessor::CreateTempoFilter(AVFilterGraph* graph, AVFilterContext* link, const double &tempo) { // Set up tempo param, which is taken as a C string char speed_param[20]; snprintf(speed_param, 20, "%f", tempo); AVFilterContext* tempo_ctx = nullptr; if (avfilter_graph_create_filter(&tempo_ctx, avfilter_get_by_name("atempo"), "atempo", speed_param, nullptr, graph) >= 0 && avfilter_link(link, 0, tempo_ctx, 0) == 0) { return tempo_ctx; } return nullptr; } }
8,323
C++
.cpp
246
28.361789
130
0.625265
olive-editor/olive
8,144
552
131
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
19,087
audiovisualwaveform.cpp
olive-editor_olive/app/audio/audiovisualwaveform.cpp
/*** Olive - Non-Linear Video Editor Copyright (C) 2022 Olive Team 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 <http://www.gnu.org/licenses/>. ***/ #include "audiovisualwaveform.h" #include <QDebug> #include <QtGlobal> #include "config/config.h" namespace olive { const rational AudioVisualWaveform::kMinimumSampleRate = rational(1, 8); const rational AudioVisualWaveform::kMaximumSampleRate = 1024; AudioVisualWaveform::AudioVisualWaveform() : channels_(0) { for (rational i=kMinimumSampleRate; i<=kMaximumSampleRate; i*=2) { mipmapped_data_.insert({i, Sample()}); } } void AudioVisualWaveform::OverwriteSamplesFromBuffer(const SampleBuffer &samples, int sample_rate, const rational &start, double target_rate, Sample& data, size_t &start_index, size_t &samples_length) { start_index = time_to_samples(start, target_rate); samples_length = time_to_samples(static_cast<double>(samples.sample_count()) / static_cast<double>(sample_rate), target_rate); size_t end_index = start_index + samples_length; if (data.size() < end_index) { data.resize(end_index); } double chunk_size = double(sample_rate) / double(target_rate); for (size_t i=0; i<samples_length; i+=channels_) { size_t src_start = qRound((double(i) * chunk_size)) / channels_; size_t src_end = qMin(size_t(qRound64((double(i + channels_) * chunk_size))) / channels_, samples.sample_count()); Sample summary = SumSamples(samples, src_start, src_end - src_start); memcpy(&data.data()[i + start_index], summary.data(), summary.size() * sizeof(SamplePerChannel)); } } void AudioVisualWaveform::OverwriteSamplesFromMipmap(const AudioVisualWaveform::Sample &input, double input_sample_rate, size_t &input_start, size_t &input_length, const rational &start, double output_rate, AudioVisualWaveform::Sample &output_data) { size_t start_index = time_to_samples(start, output_rate); size_t samples_length = time_to_samples(static_cast<double>(input_length / channels_) / input_sample_rate, output_rate); size_t end_index = start_index + samples_length; if (output_data.size() < end_index) { output_data.resize(end_index); } // We guarantee mipmaps are powers of two so integer division should be perfectly accurate here size_t chunk_size = input_sample_rate / output_rate; for (size_t i=0; i<samples_length; i+=channels_) { Sample summary = ReSumSamples(&input.data()[input_start + (i*chunk_size)], chunk_size * channels_, channels_); memcpy(&output_data.data()[i + start_index], summary.data(), summary.size() * sizeof(SamplePerChannel)); } input_start = start_index; input_length = samples_length; } void AudioVisualWaveform::ValidateVirtualStart(const rational &new_start) { if (length_ == 0) { virtual_start_ = new_start; } else if (virtual_start_ > new_start) { TrimIn(new_start - virtual_start_); } } void AudioVisualWaveform::OverwriteSamples(const SampleBuffer &samples, int sample_rate, const rational &start) { if (!channels_) { qWarning() << "Failed to write samples - channel count is zero"; return; } ValidateVirtualStart(start); // Process the largest mipmap directly for the samples auto current_mipmap = mipmapped_data_.rbegin(); size_t input_start, input_length; OverwriteSamplesFromBuffer(samples, sample_rate, start - virtual_start_, current_mipmap->first.toDouble(), current_mipmap->second, input_start, input_length); while (true) { // For each smaller mipmap, we just process from the mipmap before it, making each one // exponentially faster to create auto previous_mipmap = current_mipmap; current_mipmap++; if (current_mipmap == mipmapped_data_.rend()) { break; } OverwriteSamplesFromMipmap(previous_mipmap->second, previous_mipmap->first.toDouble(), input_start, input_length, start - virtual_start_, current_mipmap->first.toDouble(), current_mipmap->second); } rational sample_length(samples.sample_count(), sample_rate); length_ = qMax(length_, start + sample_length); } void AudioVisualWaveform::OverwriteSums(const AudioVisualWaveform &sums, const rational &dest, const rational& offset, const rational& length) { ValidateVirtualStart(dest); for (auto it=mipmapped_data_.begin(); it!=mipmapped_data_.end(); it++) { rational rate = it->first; Sample& our_arr = it->second; const Sample& their_arr = sums.mipmapped_data_.at(rate); double rate_dbl = rate.toDouble(); // Get our destination sample size_t our_start_index = time_to_samples(dest - virtual_start_, rate_dbl); // Get our source sample size_t their_start_index = time_to_samples(offset, rate_dbl); if (their_start_index >= their_arr.size()) { continue; } // Determine how much we're copying size_t copy_len = their_arr.size() - their_start_index; if (!length.isNull()) { copy_len = qMin(copy_len, time_to_samples(length, rate_dbl)); if (copy_len == 0) { continue; } } // Determine end index of our array size_t end_index = our_start_index + copy_len; if (our_arr.size() < end_index) { our_arr.resize(end_index); } memcpy(reinterpret_cast<char*>(our_arr.data()) + our_start_index * sizeof(SamplePerChannel), reinterpret_cast<const char*>(their_arr.data()) + their_start_index * sizeof(SamplePerChannel), copy_len * sizeof(SamplePerChannel)); } length_ = qMax(length_, dest + ((length.isNull()) ? sums.length() - offset : length)); } void AudioVisualWaveform::OverwriteSilence(const rational &start, const rational &length) { ValidateVirtualStart(start); for (auto it=mipmapped_data_.begin(); it!=mipmapped_data_.end(); it++) { rational rate = it->first; Sample& our_arr = it->second; double rate_dbl = rate.toDouble(); // Get our destination sample size_t our_start_index = time_to_samples(start - virtual_start_, rate_dbl); size_t our_length_index = time_to_samples(length, rate_dbl); size_t our_end_index = our_start_index + our_length_index; if (our_arr.size() < our_end_index) { our_arr.resize(our_end_index); } memset(reinterpret_cast<char*>(our_arr.data()) + our_start_index * sizeof(SamplePerChannel), 0, our_length_index * sizeof(SamplePerChannel)); } length_ = qMax(length_, start + length); } void AudioVisualWaveform::TrimIn(rational length) { if (length == 0) { return; } virtual_start_ += length; bool negative = (length < 0); if (negative) { length = -length; } for (auto it=mipmapped_data_.begin(); it!=mipmapped_data_.end(); it++) { rational rate = it->first; double rate_dbl = rate.toDouble(); Sample& data = it->second; size_t chop_length = time_to_samples(length, rate_dbl); if (chop_length == 0) { continue; } if (!negative) { data = Sample(data.begin() + chop_length, data.end()); } else { data.insert(data.begin(), chop_length, SamplePerChannel()); } } length_ = qMax(rational(0), length_ - length); } AudioVisualWaveform AudioVisualWaveform::Mid(const rational &offset) const { AudioVisualWaveform mid = *this; mid.TrimIn(offset - virtual_start_); return mid; } AudioVisualWaveform AudioVisualWaveform::Mid(const rational &offset, const rational &length) const { AudioVisualWaveform mid = *this; mid.TrimRange(offset - virtual_start_, length); return mid; } void AudioVisualWaveform::Resize(const rational &length) { if (length_ == length) { return; } for (auto it=mipmapped_data_.begin(); it!=mipmapped_data_.end(); it++) { rational rate = it->first; double rate_dbl = rate.toDouble(); Sample& data = it->second; size_t chop_length = time_to_samples(length, rate_dbl); data.resize(chop_length); } length_ = length; } void AudioVisualWaveform::TrimRange(const rational &in, const rational &length) { TrimIn(in); Resize(length); } AudioVisualWaveform::Sample AudioVisualWaveform::GetSummaryFromTime(const rational &start, const rational &length) const { // Find mipmap that requires auto using_mipmap = GetMipmapForScale(length.flipped().toDouble()); double rate_dbl = using_mipmap->first.toDouble(); size_t start_sample = time_to_samples(start - virtual_start_, rate_dbl); size_t sample_length = time_to_samples(length, rate_dbl); const Sample &mipmap_data = using_mipmap->second; // Determine if the array actually has this sample sample_length = qMin(sample_length, mipmap_data.size() - start_sample); // Based on the above `min`, if sample length <= 0, that means start_sample >= the size of the // array and nothing can be returned. if (sample_length > 0) { return ReSumSamples(&mipmap_data.data()[start_sample], sample_length, channels_); } // Return null samples return AudioVisualWaveform::Sample(channel_count(), {0, 0}); } void ExpandMinMaxChannel(const float *a, size_t length, float &min_val, float &max_val) { #if defined(Q_PROCESSOR_X86) || defined(Q_PROCESSOR_ARM) // SSE optimized // load the first 4 elements of 'a' into min and max (they are 4 * 32 = 128 bits) __m128 max = _mm_loadu_ps(a); __m128 min = _mm_loadu_ps(a); // loop over 'a' and compare current elements with min and max 4 by 4. // we need to make sure we don't read out of boundaries should 'a' length be not mod. 4 for(size_t i = 4; i < length-4; i+=4) { __m128 cur = _mm_loadu_ps(a + i); max = _mm_max_ps(max, cur); min = _mm_min_ps(min, cur); } // so we read the last 4 (or less) elements in a safe manner. __m128 cur = _mm_loadu_ps(a + length - 4); max = _mm_max_ps(max, cur); min = _mm_min_ps(min, cur); // this potentially overlaps up to the last 3 elements but it's not an issue. // min and max will contain 4 min and max. To get the absolute min and max // we need to compare the 4 values over themselves by shuffling each time. for (size_t i = 0; i < 3; i++) { max = _mm_max_ps(max, _mm_shuffle_ps(max, max, 0x93)); min = _mm_min_ps(min, _mm_shuffle_ps(min, min, 0x93)); } // now min and max contain 4 identical items each representing min and max value respectively. // and we store the first one into a float variable. _mm_store_ss(&max_val, max); _mm_store_ss(&min_val, min); // I bet you don't find annotated low level code very often. #else // Standard unoptimized function for (size_t i=0; i<length; i++) { min_val = std::min(min_val, a[i]); max_val = std::max(max_val, a[i]); } #endif } AudioVisualWaveform::Sample AudioVisualWaveform::SumSamples(const SampleBuffer &samples, size_t start_index, size_t length) { int channels = samples.audio_params().channel_count(); AudioVisualWaveform::Sample summed_samples(channels); for (int channel=0; channel<samples.audio_params().channel_count(); channel++) { ExpandMinMaxChannel(samples.data(channel) + start_index, length, summed_samples[channel].min, summed_samples[channel].max); } // for reference: this approximation is n x faster (and less accurate) for a n-tracks clip // for (size_t i=start_index; i<end_index; i++) { // ExpandMinMax(summed_samples[i%channels], samples->data(i%channels)[i]); // } return summed_samples; } AudioVisualWaveform::Sample AudioVisualWaveform::ReSumSamples(const SamplePerChannel* samples, size_t nb_samples, int nb_channels) { AudioVisualWaveform::Sample summed_samples(nb_channels); for (size_t i=0;i<nb_samples;i+=nb_channels) { for (int j=0;j<nb_channels;j++) { const AudioVisualWaveform::SamplePerChannel& sample = samples[i + j]; if (sample.min < summed_samples[j].min) { summed_samples[j].min = sample.min; } if (sample.max > summed_samples[j].max) { summed_samples[j].max = sample.max; } } } return summed_samples; } template <typename T> inline int round_away_from_zero(T t) { return (t < 0) ? std::floor(t) : std::ceil(t); } void AudioVisualWaveform::DrawSample(QPainter *painter, const Sample& sample, int x, int y, int height, bool rectified) { if (sample.empty()) { return; } int channel_height = height / sample.size(); int channel_half_height = channel_height / 2; for (size_t i=0;i<sample.size();i++) { float max = qMin(sample.at(i).max, 1.0f); float min = qMax(sample.at(i).min, -1.0f); if (rectified) { int channel_bottom = y + channel_height * (i + 1); int diff = round_away_from_zero((max - min) * channel_half_height); painter->drawLine(x, channel_bottom - diff, x, channel_bottom); } else { int channel_mid = y + channel_height * i + channel_half_height; // We subtract the sample so that positive Y values go up on the screen rather than down, // which is how waveforms are usually rendered painter->drawLine(x, channel_mid - round_away_from_zero(min * static_cast<float>(channel_half_height)), x, channel_mid - round_away_from_zero(max * static_cast<float>(channel_half_height))); } } } void AudioVisualWaveform::DrawWaveform(QPainter *painter, const QRect& rect, const double& scale, const AudioVisualWaveform &samples, const rational& start_time) { if (samples.mipmapped_data_.empty()) { return; } auto using_mipmap = samples.GetMipmapForScale(scale); rational rate = using_mipmap->first; double rate_dbl = rate.toDouble(); const Sample& arr = using_mipmap->second; size_t start_sample_index = samples.time_to_samples(start_time - samples.virtual_start_, rate_dbl); if (start_sample_index >= arr.size()) { return; } size_t next_sample_index = start_sample_index; size_t sample_index; Sample summary; size_t summary_index = -1; const QRect& viewport = painter->viewport(); QPoint top_left = painter->transform().map(viewport.topLeft()); size_t start = qMax(rect.x(), -top_left.x()); size_t end = qMin(rect.right(), -top_left.x() + viewport.width()); bool rectified = OLIVE_CONFIG("RectifiedWaveforms").toBool(); for (size_t i=start;i<end;i++) { sample_index = next_sample_index; if (sample_index == arr.size()) { break; } next_sample_index = std::min(arr.size(), size_t(start_sample_index + std::floor(rate_dbl * static_cast<double>(i - rect.x() + 1) / scale) * samples.channel_count())); if (summary_index != sample_index) { summary = AudioVisualWaveform::ReSumSamples(&arr.at(sample_index), qMax(size_t(samples.channel_count()), next_sample_index - sample_index), samples.channel_count()); summary_index = sample_index; } DrawSample(painter, summary, i, rect.y(), rect.height(), rectified); } } size_t AudioVisualWaveform::time_to_samples(const rational &time, double sample_rate) const { return time_to_samples(time.toDouble(), sample_rate); } size_t AudioVisualWaveform::time_to_samples(const double &time, double sample_rate) const { return std::floor(time * sample_rate) * channels_; } std::map<rational, AudioVisualWaveform::Sample>::const_iterator AudioVisualWaveform::GetMipmapForScale(double scale) const { // Find largest mipmap for this scale (or the largest if we don't find one sufficient) for (auto it=mipmapped_data_.cbegin(); it!=mipmapped_data_.cend(); it++) { if (it->first.toDouble() >= scale) { return it; } } // We don't have a mipmap large enough for this scale, so just return the largest we have return std::prev(mipmapped_data_.cend()); } }
16,584
C++
.cpp
388
37.569588
248
0.676244
olive-editor/olive
8,144
552
131
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
19,088
cliexportmanager.cpp
olive-editor_olive/app/cli/cliexport/cliexportmanager.cpp
/*** Olive - Non-Linear Video Editor Copyright (C) 2022 Olive Team 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 <http://www.gnu.org/licenses/>. ***/ #include "cliexportmanager.h" namespace olive { CLIExportManager::CLIExportManager() { } }
807
C++
.cpp
20
37.65
71
0.777349
olive-editor/olive
8,144
552
131
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
19,089
cliprogressdialog.cpp
olive-editor_olive/app/cli/cliprogress/cliprogressdialog.cpp
/*** Olive - Non-Linear Video Editor Copyright (C) 2022 Olive Team 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 <http://www.gnu.org/licenses/>. ***/ #include "cliprogressdialog.h" #include <iostream> namespace olive { CLIProgressDialog::CLIProgressDialog(const QString& title, QObject *parent) : QObject(parent), title_(title), progress_(-1), drawn_(false) { SetProgress(0); } void CLIProgressDialog::Update() { if (drawn_) { // We've been here before, do a carriage return back to the start of the terminal line std::cout << "\r"; } else { drawn_ = true; } // FIXME: Get real column count int columns = 80; int title_columns = columns / 2 - 1; // Print "title" text QString sized_title = title_; if (title_.size() > title_columns) { sized_title = title_.left(title_columns - 3).append(QStringLiteral("...")); } else { sized_title = title_; } std::cout << sized_title.toUtf8().constData(); // Pad out the rest of the title area if necessary for (int i=sized_title.size(); i<title_columns; i++) { std::cout << " "; } // Percentage counter " 100% " is 5 characters + the enclosing brackets [] are 2 characters int progress_bar_columns = columns / 2 - 7; std::cout << "["; // Get UI bar progress int bar_prog = qRound(progress_ * progress_bar_columns); // Draw filled in bar for (int i=0;i<bar_prog;i++) { std::cout << "="; } // Draw empty space for (int i=bar_prog;i<progress_bar_columns;i++) { std::cout << " "; } std::cout << "] "; if (progress_ < 100) { std::cout << " "; } if (progress_ < 10) { std::cout << " "; } std::cout << qRound(progress_ * 100.0) << "% " << std::endl << std::flush; } void CLIProgressDialog::SetProgress(double p) { if (progress_ != p) { progress_ = p; Update(); } } }
2,406
C++
.cpp
78
27.564103
93
0.667391
olive-editor/olive
8,144
552
131
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
19,090
clitaskdialog.cpp
olive-editor_olive/app/cli/clitask/clitaskdialog.cpp
/*** Olive - Non-Linear Video Editor Copyright (C) 2022 Olive Team 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 <http://www.gnu.org/licenses/>. ***/ #include "clitaskdialog.h" namespace olive { CLITaskDialog::CLITaskDialog(Task *task, QObject* parent) : CLIProgressDialog(task->GetTitle(), parent), task_(task) { connect(task_, &Task::ProgressChanged, this, &CLITaskDialog::SetProgress); } bool CLITaskDialog::Run() { return task_->Start(); } }
1,020
C++
.cpp
27
35.222222
76
0.765005
olive-editor/olive
8,144
552
131
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
19,091
config.cpp
olive-editor_olive/app/config/config.cpp
/*** Olive - Non-Linear Video Editor Copyright (C) 2022 Olive Team 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 <http://www.gnu.org/licenses/>. ***/ #include "config.h" #include <QCoreApplication> #include <QDebug> #include <QDir> #include <QMessageBox> #include <QStandardPaths> #include <QXmlStreamWriter> #include "codec/exportformat.h" #include "common/autoscroll.h" #include "common/filefunctions.h" #include "common/xmlutils.h" #include "core.h" #include "timeline/timelinecommon.h" #include "ui/colorcoding.h" #include "ui/style/style.h" #include "window/mainwindow/mainwindow.h" namespace olive { Config Config::current_config_; Config::Config() { SetDefaults(); } void Config::SetEntryInternal(const QString &key, NodeValue::Type type, const QVariant &data) { config_map_[key] = {type, data}; } QString Config::GetConfigFilePath() { return QDir(FileFunctions::GetConfigurationLocation()).filePath(QStringLiteral("config.xml")); } Config &Config::Current() { return current_config_; } void Config::SetDefaults() { config_map_.clear(); SetEntryInternal(QStringLiteral("Style"), NodeValue::kText, StyleManager::kDefaultStyle); SetEntryInternal(QStringLiteral("TimecodeDisplay"), NodeValue::kInt, Timecode::kTimecodeDropFrame); SetEntryInternal(QStringLiteral("DefaultStillLength"), NodeValue::kRational, QVariant::fromValue(rational(2))); SetEntryInternal(QStringLiteral("HoverFocus"), NodeValue::kBoolean, false); SetEntryInternal(QStringLiteral("AudioScrubbing"), NodeValue::kBoolean, true); SetEntryInternal(QStringLiteral("AutorecoveryEnabled"), NodeValue::kBoolean, true); SetEntryInternal(QStringLiteral("AutorecoveryInterval"), NodeValue::kInt, 1); SetEntryInternal(QStringLiteral("AutorecoveryMaximum"), NodeValue::kInt, 20); SetEntryInternal(QStringLiteral("DiskCacheSaveInterval"), NodeValue::kInt, 10000); SetEntryInternal(QStringLiteral("Language"), NodeValue::kText, QString()); SetEntryInternal(QStringLiteral("ScrollZooms"), NodeValue::kBoolean, false); SetEntryInternal(QStringLiteral("EnableSeekToImport"), NodeValue::kBoolean, false); SetEntryInternal(QStringLiteral("EditToolAlsoSeeks"), NodeValue::kBoolean, false); SetEntryInternal(QStringLiteral("EditToolSelectsLinks"), NodeValue::kBoolean, false); SetEntryInternal(QStringLiteral("EnableDragFilesToTimeline"), NodeValue::kBoolean, true); SetEntryInternal(QStringLiteral("InvertTimelineScrollAxes"), NodeValue::kBoolean, true); SetEntryInternal(QStringLiteral("SelectAlsoSeeks"), NodeValue::kBoolean, false); SetEntryInternal(QStringLiteral("PasteSeeks"), NodeValue::kBoolean, true); SetEntryInternal(QStringLiteral("SeekAlsoSelects"), NodeValue::kBoolean, false); SetEntryInternal(QStringLiteral("SetNameWithMarker"), NodeValue::kBoolean, false); SetEntryInternal(QStringLiteral("AutoSeekToBeginning"), NodeValue::kBoolean, true); SetEntryInternal(QStringLiteral("DropFileOnMediaToReplace"), NodeValue::kBoolean, false); SetEntryInternal(QStringLiteral("AddDefaultEffectsToClips"), NodeValue::kBoolean, true); SetEntryInternal(QStringLiteral("AutoscaleByDefault"), NodeValue::kBoolean, false); SetEntryInternal(QStringLiteral("Autoscroll"), NodeValue::kInt, AutoScroll::kPage); SetEntryInternal(QStringLiteral("AutoSelectDivider"), NodeValue::kBoolean, true); SetEntryInternal(QStringLiteral("SetNameWithMarker"), NodeValue::kBoolean, false); SetEntryInternal(QStringLiteral("RectifiedWaveforms"), NodeValue::kBoolean, true); SetEntryInternal(QStringLiteral("DropWithoutSequenceBehavior"), NodeValue::kInt, ImportTool::kDWSAsk); SetEntryInternal(QStringLiteral("Loop"), NodeValue::kBoolean, false); SetEntryInternal(QStringLiteral("SplitClipsCopyNodes"), NodeValue::kBoolean, true); SetEntryInternal(QStringLiteral("UseGradients"), NodeValue::kBoolean, true); SetEntryInternal(QStringLiteral("AutoMergeTracks"), NodeValue::kBoolean, true); SetEntryInternal(QStringLiteral("UseSliderLadders"), NodeValue::kBoolean, true); SetEntryInternal(QStringLiteral("ShowWelcomeDialog"), NodeValue::kBoolean, true); SetEntryInternal(QStringLiteral("ShowClipWhileDragging"), NodeValue::kBoolean, true); SetEntryInternal(QStringLiteral("StopPlaybackOnLastFrame"), NodeValue::kBoolean, false); SetEntryInternal(QStringLiteral("UseLegacyColorInInputTab"), NodeValue::kBoolean, false); SetEntryInternal(QStringLiteral("ReassocLinToNonLin"), NodeValue::kBoolean, false); SetEntryInternal(QStringLiteral("PreviewNonFloatDontAskAgain"), NodeValue::kBoolean, false); SetEntryInternal(QStringLiteral("UseGLFinish"), NodeValue::kBoolean, false); SetEntryInternal(QStringLiteral("TimelineThumbnailMode"), NodeValue::kInt, Timeline::kThumbnailInOut); SetEntryInternal(QStringLiteral("TimelineWaveformMode"), NodeValue::kInt, Timeline::kWaveformsEnabled); SetEntryInternal(QStringLiteral("DefaultVideoTransition"), NodeValue::kText, QStringLiteral("org.olivevideoeditor.Olive.crossdissolve")); SetEntryInternal(QStringLiteral("DefaultAudioTransition"), NodeValue::kText, QStringLiteral("org.olivevideoeditor.Olive.crossdissolve")); SetEntryInternal(QStringLiteral("DefaultTransitionLength"), NodeValue::kRational, QVariant::fromValue(rational(1))); SetEntryInternal(QStringLiteral("DefaultSubtitleSize"), NodeValue::kInt, 48); SetEntryInternal(QStringLiteral("DefaultSubtitleFamily"), NodeValue::kText, QString()); SetEntryInternal(QStringLiteral("DefaultSubtitleWeight"), NodeValue::kInt, QFont::Bold); SetEntryInternal(QStringLiteral("AntialiasSubtitles"), NodeValue::kBoolean, true); SetEntryInternal(QStringLiteral("AutoCacheDelay"), NodeValue::kInt, 1000); SetEntryInternal(QStringLiteral("CatColor0"), NodeValue::kInt, ColorCoding::kRed); SetEntryInternal(QStringLiteral("CatColor1"), NodeValue::kInt, ColorCoding::kMaroon); SetEntryInternal(QStringLiteral("CatColor2"), NodeValue::kInt, ColorCoding::kOrange); SetEntryInternal(QStringLiteral("CatColor3"), NodeValue::kInt, ColorCoding::kBrown); SetEntryInternal(QStringLiteral("CatColor4"), NodeValue::kInt, ColorCoding::kYellow); SetEntryInternal(QStringLiteral("CatColor5"), NodeValue::kInt, ColorCoding::kOlive); SetEntryInternal(QStringLiteral("CatColor6"), NodeValue::kInt, ColorCoding::kLime); SetEntryInternal(QStringLiteral("CatColor7"), NodeValue::kInt, ColorCoding::kGreen); SetEntryInternal(QStringLiteral("CatColor8"), NodeValue::kInt, ColorCoding::kCyan); SetEntryInternal(QStringLiteral("CatColor9"), NodeValue::kInt, ColorCoding::kTeal); SetEntryInternal(QStringLiteral("CatColor10"), NodeValue::kInt, ColorCoding::kBlue); SetEntryInternal(QStringLiteral("CatColor11"), NodeValue::kInt, ColorCoding::kNavy); SetEntryInternal(QStringLiteral("AudioOutput"), NodeValue::kText, QString()); SetEntryInternal(QStringLiteral("AudioInput"), NodeValue::kText, QString()); SetEntryInternal(QStringLiteral("AudioOutputSampleRate"), NodeValue::kInt, 48000); SetEntryInternal(QStringLiteral("AudioOutputChannelLayout"), NodeValue::kInt, AV_CH_LAYOUT_STEREO); SetEntryInternal(QStringLiteral("AudioOutputSampleFormat"), NodeValue::kText, QString::fromStdString(SampleFormat(SampleFormat::S16).to_string())); SetEntryInternal(QStringLiteral("AudioRecordingFormat"), NodeValue::kInt, ExportFormat::kFormatWAV); SetEntryInternal(QStringLiteral("AudioRecordingCodec"), NodeValue::kInt, ExportCodec::kCodecPCM); SetEntryInternal(QStringLiteral("AudioRecordingSampleRate"), NodeValue::kInt, 48000); SetEntryInternal(QStringLiteral("AudioRecordingChannelLayout"), NodeValue::kInt, AV_CH_LAYOUT_STEREO); SetEntryInternal(QStringLiteral("AudioRecordingSampleFormat"), NodeValue::kText, QString::fromStdString(SampleFormat(SampleFormat::S16).to_string())); SetEntryInternal(QStringLiteral("AudioRecordingBitRate"), NodeValue::kInt, 320); SetEntryInternal(QStringLiteral("DiskCacheBehind"), NodeValue::kRational, QVariant::fromValue(rational(0))); SetEntryInternal(QStringLiteral("DiskCacheAhead"), NodeValue::kRational, QVariant::fromValue(rational(60))); SetEntryInternal(QStringLiteral("DefaultSequenceWidth"), NodeValue::kInt, 1920); SetEntryInternal(QStringLiteral("DefaultSequenceHeight"), NodeValue::kInt, 1080); SetEntryInternal(QStringLiteral("DefaultSequencePixelAspect"), NodeValue::kRational, QVariant::fromValue(rational(1))); SetEntryInternal(QStringLiteral("DefaultSequenceFrameRate"), NodeValue::kRational, QVariant::fromValue(rational(1001, 30000))); SetEntryInternal(QStringLiteral("DefaultSequenceInterlacing"), NodeValue::kInt, VideoParams::kInterlaceNone); SetEntryInternal(QStringLiteral("DefaultSequenceAutoCache2"), NodeValue::kBoolean, false); SetEntryInternal(QStringLiteral("DefaultSequenceAudioFrequency"), NodeValue::kInt, 48000); SetEntryInternal(QStringLiteral("DefaultSequenceAudioLayout"), NodeValue::kInt, QVariant::fromValue(static_cast<int64_t>(AV_CH_LAYOUT_STEREO))); // Online/offline settings SetEntryInternal(QStringLiteral("OnlinePixelFormat"), NodeValue::kInt, PixelFormat::F32); SetEntryInternal(QStringLiteral("OfflinePixelFormat"), NodeValue::kInt, PixelFormat::F16); SetEntryInternal(QStringLiteral("MarkerColor"), NodeValue::kInt, ColorCoding::kLime); } void Config::Load() { QFile config_file(GetConfigFilePath()); if (!config_file.exists()) { return; } if (!config_file.open(QFile::ReadOnly)) { qWarning() << "Failed to load application settings. This session will use defaults."; return; } // Reset to defaults current_config_.SetDefaults(); QXmlStreamReader reader(&config_file); QString config_version; while (XMLReadNextStartElement(&reader)) { if (reader.name() == QStringLiteral("Configuration")) { while (XMLReadNextStartElement(&reader)) { QString key = reader.name().toString(); QString value = reader.readElementText(); if (key == QStringLiteral("Version")) { config_version = value; if (!value.contains(".")) { qDebug() << "CONFIG: This is a 0.1.x config file, upconvert"; } } else if (key == QStringLiteral("DefaultSequenceFrameRate") && !config_version.contains('.')) { // 0.1.x stored this value as a float while we now use rationals, we'll use a heuristic to find the closest // supported rational qDebug() << " CONFIG: Finding closest match to" << value; double config_fr = value.toDouble(); const QVector<rational>& supported_frame_rates = VideoParams::kSupportedFrameRates; rational match = supported_frame_rates.first(); double match_diff = qAbs(match.toDouble() - config_fr); for (int i=1;i<supported_frame_rates.size();i++) { double diff = qAbs(supported_frame_rates.at(i).toDouble() - config_fr); if (diff < match_diff) { match = supported_frame_rates.at(i); match_diff = diff; } } qDebug() << " CONFIG: Closest match was" << match.toDouble(); current_config_[key] = QVariant::fromValue(match.flipped()); } else { current_config_[key] = NodeValue::StringToValue(current_config_.GetConfigEntryType(key), value, false); } } //reader.skipCurrentElement(); } else { reader.skipCurrentElement(); } } if (reader.hasError()) { QMessageBox::critical(Core::instance()->main_window(), QCoreApplication::translate("Config", "Error loading settings"), QCoreApplication::translate("Config", "Failed to load application settings. This session will " "use defaults.\n\n%1").arg(reader.errorString()), QMessageBox::Ok); current_config_.SetDefaults(); } config_file.close(); } void Config::Save() { QString real_filename = GetConfigFilePath(); QString temp_filename = FileFunctions::GetSafeTemporaryFilename(real_filename); QFile config_file(temp_filename); if (!config_file.open(QFile::WriteOnly)) { QMessageBox::critical(Core::instance()->main_window(), QCoreApplication::translate("Config", "Error saving settings"), QCoreApplication::translate("Config", "Failed to save application settings. The application " "may lack write permissions for this location."), QMessageBox::Ok); return; } QXmlStreamWriter writer(&config_file); writer.setAutoFormatting(true); writer.writeStartDocument(); writer.writeStartElement("Configuration"); // Anything after the hyphen is considered "unimportant" information writer.writeTextElement("Version", QCoreApplication::applicationVersion().split('-').first()); QMapIterator<QString, ConfigEntry> iterator(current_config_.config_map_); while (iterator.hasNext()) { iterator.next(); QString value = NodeValue::ValueToString(iterator.value().type, iterator.value().data, false); if (iterator.value().type == NodeValue::kNone) { qWarning() << "Config key" << iterator.key() << "had null type and was discarded"; } else { writer.writeTextElement(iterator.key(), value); } } writer.writeEndElement(); // Configuration writer.writeEndDocument(); config_file.close(); if (!FileFunctions::RenameFileAllowOverwrite(temp_filename, real_filename)) { qWarning() << QStringLiteral("Failed to overwrite \"%1\". Config has been saved as \"%2\" instead.") .arg(real_filename, temp_filename); } } QVariant Config::operator[](const QString &key) const { return config_map_[key].data; } QVariant &Config::operator[](const QString &key) { return config_map_[key].data; } NodeValue::Type Config::GetConfigEntryType(const QString &key) const { return config_map_[key].type; } }
14,504
C++
.cpp
250
52.928
152
0.754193
olive-editor/olive
8,144
552
131
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
19,092
progress.cpp
olive-editor_olive/app/dialog/progress/progress.cpp
/*** Olive - Non-Linear Video Editor Copyright (C) 2022 Olive Team 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 <http://www.gnu.org/licenses/>. ***/ #include "progress.h" #include <QLabel> #include <QMessageBox> #include <QPushButton> #include <QVBoxLayout> #include "window/mainwindow/mainwindow.h" namespace olive { #define super QDialog ProgressDialog::ProgressDialog(const QString& message, const QString& title, QWidget *parent) : super(parent), show_progress_(true), first_show_(true) { if (!title.isEmpty()) { setWindowTitle(title); } QVBoxLayout* layout = new QVBoxLayout(this); layout->addWidget(new QLabel(message)); bar_ = new QProgressBar(); bar_->setMinimum(0); bar_->setValue(0); bar_->setMaximum(100); layout->addWidget(bar_); elapsed_timer_lbl_ = new ElapsedCounterWidget(); layout->addWidget(elapsed_timer_lbl_); QHBoxLayout* cancel_layout = new QHBoxLayout(); layout->addLayout(cancel_layout); cancel_layout->setContentsMargins(0, 0, 0, 0); cancel_layout->setSpacing(0); cancel_layout->addStretch(); QPushButton* cancel_btn = new QPushButton(tr("Cancel")); // Signal that derivatives can connect to connect(cancel_btn, &QPushButton::clicked, this, &ProgressDialog::Cancelled, Qt::DirectConnection); // Stop updating the elapsed/remaining timers connect(cancel_btn, &QPushButton::clicked, elapsed_timer_lbl_, &ElapsedCounterWidget::Stop); // Disable the button so that users know they don't need to keep clicking it connect(cancel_btn, &QPushButton::clicked, this, &ProgressDialog::DisableSenderWidget); // Prevent the progress bar from continuing to move connect(cancel_btn, &QPushButton::clicked, this, &ProgressDialog::DisableProgressWidgets); cancel_layout->addWidget(cancel_btn); cancel_layout->addStretch(); } void ProgressDialog::showEvent(QShowEvent *e) { super::showEvent(e); if (first_show_) { elapsed_timer_lbl_->Start(); Core::instance()->main_window()->SetApplicationProgressStatus(MainWindow::kProgressShow); first_show_ = false; } } void ProgressDialog::closeEvent(QCloseEvent *e) { super::closeEvent(e); Core::instance()->main_window()->SetApplicationProgressStatus(MainWindow::kProgressNone); elapsed_timer_lbl_->Stop(); first_show_ = true; } void ProgressDialog::SetProgress(double value) { if (!show_progress_) { return; } int percent = qRound(100.0 * value); bar_->setValue(percent); elapsed_timer_lbl_->SetProgress(value); Core::instance()->main_window()->SetApplicationProgressValue(percent); } void ProgressDialog::ShowErrorMessage(const QString &title, const QString &message) { Core::instance()->main_window()->SetApplicationProgressStatus(MainWindow::kProgressError); QMessageBox b(this); b.setIcon(QMessageBox::Critical); b.setWindowModality(Qt::WindowModal); b.setWindowTitle(title); b.setText(message); b.addButton(QMessageBox::Ok); b.exec(); } void ProgressDialog::DisableSenderWidget() { static_cast<QWidget*>(sender())->setEnabled(false); } void ProgressDialog::DisableProgressWidgets() { show_progress_ = false; } }
3,689
C++
.cpp
102
33.303922
101
0.756696
olive-editor/olive
8,144
552
131
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
19,093
task.cpp
olive-editor_olive/app/dialog/task/task.cpp
/*** Olive - Non-Linear Video Editor Copyright (C) 2022 Olive Team 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 <http://www.gnu.org/licenses/>. ***/ #include "task.h" #include <QtConcurrent/QtConcurrent> namespace olive { #define super ProgressDialog TaskDialog::TaskDialog(Task* task, const QString& title, QWidget *parent) : super(task->GetTitle(), title, parent), task_(task), destroy_on_close_(true), already_shown_(false) { // Clear task when this dialog is destroyed task_->setParent(this); // Connect the save manager progress signal to the progress bar update on the dialog connect(task_, &Task::ProgressChanged, this, &TaskDialog::SetProgress, Qt::QueuedConnection); // Connect cancel signal (must be a direct connection or it'll be queued after the task has // already finished) connect(this, &TaskDialog::Cancelled, task_, &Task::Cancel, Qt::DirectConnection); } void TaskDialog::showEvent(QShowEvent *e) { super::showEvent(e); if (!already_shown_) { // Create watcher for when the task finishes QFutureWatcher<bool>* task_watcher = new QFutureWatcher<bool>(); // Listen for when the task finishes connect(task_watcher, &QFutureWatcher<bool>::finished, this, &TaskDialog::TaskFinished, Qt::QueuedConnection); // Run task in another thread with QtConcurrent task_watcher->setFuture( #if QT_VERSION_MAJOR >= 6 QtConcurrent::run(&Task::Start, task_) #else QtConcurrent::run(task_, &Task::Start) #endif ); already_shown_ = true; } } void TaskDialog::closeEvent(QCloseEvent *e) { // Cancel task if it is running task_->Cancel(); // Standard close function super::closeEvent(e); // Reset shown already_shown_ = false; // Clean up this task and dialog if (destroy_on_close_) { deleteLater(); } } void TaskDialog::TaskFinished() { QFutureWatcher<bool>* task_watcher = static_cast<QFutureWatcher<bool>*>(sender()); if (task_watcher->result()) { emit TaskSucceeded(task_); } else { ShowErrorMessage(tr("Task Failed"), task_->GetError()); emit TaskFailed(task_); } task_watcher->deleteLater(); close(); } }
2,734
C++
.cpp
78
31.564103
95
0.725095
olive-editor/olive
8,144
552
131
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
19,094
configdialogbase.cpp
olive-editor_olive/app/dialog/configbase/configdialogbase.cpp
/*** Olive - Non-Linear Video Editor Copyright (C) 2022 Olive Team 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 <http://www.gnu.org/licenses/>. ***/ #include "configdialogbase.h" #include <QDialogButtonBox> #include <QSplitter> #include <QVBoxLayout> #include "core.h" namespace olive { ConfigDialogBase::ConfigDialogBase(QWidget* parent) : QDialog(parent) { QVBoxLayout* layout = new QVBoxLayout(this); QSplitter* splitter = new QSplitter(); splitter->setChildrenCollapsible(false); layout->addWidget(splitter); list_widget_ = new QListWidget(); preference_pane_stack_ = new QStackedWidget(this); splitter->addWidget(list_widget_); splitter->addWidget(preference_pane_stack_); QDialogButtonBox* button_box = new QDialogButtonBox(this); button_box->setOrientation(Qt::Horizontal); button_box->setStandardButtons(QDialogButtonBox::Cancel|QDialogButtonBox::Ok); layout->addWidget(button_box); connect(button_box, &QDialogButtonBox::accepted, this, &ConfigDialogBase::accept); connect(button_box, &QDialogButtonBox::rejected, this, &ConfigDialogBase::reject); connect(list_widget_, &QListWidget::currentRowChanged, preference_pane_stack_, &QStackedWidget::setCurrentIndex); } void ConfigDialogBase::accept() { foreach (ConfigDialogBaseTab* tab, tabs_) { if (!tab->Validate()) { return; } } MultiUndoCommand* command = new MultiUndoCommand(); foreach (ConfigDialogBaseTab* tab, tabs_) { tab->Accept(command); } Core::instance()->undo_stack()->push(command, tr("Set Configuration")); AcceptEvent(); QDialog::accept(); } void ConfigDialogBase::AddTab(ConfigDialogBaseTab *tab, const QString &title) { list_widget_->addItem(title); preference_pane_stack_->addWidget(tab); tabs_.append(tab); } }
2,374
C++
.cpp
64
33.703125
84
0.753833
olive-editor/olive
8,144
552
131
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
19,095
configdialogbasetab.cpp
olive-editor_olive/app/dialog/configbase/configdialogbasetab.cpp
/*** Olive - Non-Linear Video Editor Copyright (C) 2022 Olive Team 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 <http://www.gnu.org/licenses/>. ***/ #include "configdialogbasetab.h" namespace olive { bool ConfigDialogBaseTab::Validate() { return true; } }
824
C++
.cpp
21
36.571429
71
0.775819
olive-editor/olive
8,144
552
131
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
19,096
speeddurationdialog.cpp
olive-editor_olive/app/dialog/speedduration/speeddurationdialog.cpp
/*** Olive - Non-Linear Video Editor Copyright (C) 2023 Olive Studios 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 <http://www.gnu.org/licenses/>. ***/ #include "speeddurationdialog.h" #include <QDialogButtonBox> #include <QGridLayout> #include <QGroupBox> #include <QMessageBox> #include "core.h" #include "node/nodeundo.h" #include "timeline/timelineundopointer.h" namespace olive { #define super QDialog SpeedDurationDialog::SpeedDurationDialog(const QVector<ClipBlock *> &clips, const rational &timebase, QWidget *parent) : super(parent), clips_(clips), timebase_(timebase) { setWindowTitle(tr("Clip Properties")); QVBoxLayout *layout = new QVBoxLayout(this); { QGroupBox *speed_group = new QGroupBox(tr("Speed/Duration")); layout->addWidget(speed_group); QGridLayout *speed_layout = new QGridLayout(speed_group); int row = 0; speed_layout->addWidget(new QLabel(tr("Speed:")), row, 0); speed_slider_ = new FloatSlider(); speed_slider_->SetDisplayType(FloatSlider::kPercentage); connect(speed_slider_, &FloatSlider::ValueChanged, this, &SpeedDurationDialog::SpeedChanged); speed_layout->addWidget(speed_slider_, row, 1); row++; speed_layout->addWidget(new QLabel(tr("Duration:")), row, 0); dur_slider_ = new RationalSlider(); dur_slider_->SetTimebase(timebase); dur_slider_->SetDisplayType(RationalSlider::kTime); connect(dur_slider_, &RationalSlider::ValueChanged, this, &SpeedDurationDialog::DurationChanged); speed_layout->addWidget(dur_slider_, row, 1); row++; link_box_ = new QCheckBox(tr("Link Speed and Duration")); link_box_->setChecked(true); speed_layout->addWidget(link_box_, row, 0, 1, 2); row++; reverse_box_ = new QCheckBox(tr("Reverse")); speed_layout->addWidget(reverse_box_, row, 0, 1, 2); row++; maintain_audio_pitch_box_ = new QCheckBox(tr("Maintain Audio Pitch")); speed_layout->addWidget(maintain_audio_pitch_box_, row, 0, 1, 2); row++; ripple_box_ = new QCheckBox(tr("Ripple Trailing Clips")); speed_layout->addWidget(ripple_box_, row, 0, 1, 2); } { auto loop_box = new QGroupBox(tr("Loop")); layout->addWidget(loop_box); auto loop_layout = new QGridLayout(loop_box); int row = 0; loop_layout->addWidget(new QLabel(tr("Loop:")), row, 0); loop_combo_ = new QComboBox(); loop_combo_->addItem(tr("None"), int(LoopMode::kLoopModeOff)); loop_combo_->addItem(tr("Loop"), int(LoopMode::kLoopModeLoop)); loop_combo_->addItem(tr("Clamp"), int(LoopMode::kLoopModeClamp)); loop_layout->addWidget(loop_combo_, row, 1); } QDialogButtonBox *btns = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); btns->setCenterButtons(true); connect(btns, &QDialogButtonBox::accepted, this, &SpeedDurationDialog::accept); connect(btns, &QDialogButtonBox::rejected, this, &SpeedDurationDialog::reject); layout->addWidget(btns); // Determine which speed value to use start_speed_ = clips.first()->speed(); start_duration_ = clips.first()->length(); start_reverse_ = clips.first()->reverse(); start_maintain_audio_pitch_ = clips.first()->maintain_audio_pitch(); start_loop_ = int(clips.first()->loop_mode()); for (int i=1; i<clips.size(); i++) { ClipBlock *c = clips.at(i); if (!qIsNaN(start_speed_) && !qFuzzyCompare(start_speed_, c->speed())) { // Speed differs per clip start_speed_ = qSNaN(); } if (start_duration_ != -1 && c->length() != start_duration_) { start_duration_ = -1; } // Yes, in theory a bool should only ever be 0 or 1 anyway, but MSVC complained and it is // *possible* that a bool could be something else, so this code is safer int clip_reverse = c->reverse() ? 1 : 0; int clip_maintain_pitch = c->maintain_audio_pitch() ? 1 : 0; if (start_reverse_ != -1 && clip_reverse != start_reverse_) { start_reverse_ = -1; } if (start_maintain_audio_pitch_ != -1 && clip_maintain_pitch != start_maintain_audio_pitch_) { start_maintain_audio_pitch_ = -1; } if (start_loop_ != -1 && int(c->loop_mode()) != start_loop_) { start_loop_ = -1; } } if (qIsNaN(start_speed_)) { speed_slider_->SetTristate(); } else { speed_slider_->SetValue(start_speed_); } if (start_duration_ == -1) { dur_slider_->SetTristate(); } else { dur_slider_->SetValue(start_duration_); } if (start_reverse_ == -1) { reverse_box_->setTristate(); } else { reverse_box_->setChecked(start_reverse_); } if (start_maintain_audio_pitch_ == -1) { maintain_audio_pitch_box_->setTristate(); } else { maintain_audio_pitch_box_->setChecked(start_maintain_audio_pitch_); } if (start_loop_ == -1) { loop_combo_->setCurrentIndex(-1); } else { loop_combo_->setCurrentIndex(start_loop_); } } void SpeedDurationDialog::accept() { MultiUndoCommand *command = new MultiUndoCommand(); // Set duration values TimelineRippleDeleteGapsAtRegionsCommand::RangeList ripple_ranges; foreach (ClipBlock *c, clips_) { rational proposed_length = c->length(); if (dur_slider_->IsTristate()) { if (link_box_->isChecked() && !speed_slider_->IsTristate()) { proposed_length = GetLengthAdjustment(c->length(), c->speed(), speed_slider_->GetValue(), timebase_); } } else { proposed_length = dur_slider_->GetValue(); } if (proposed_length != c->length()) { // Clip length should ideally change, but check if there's "room" to do so if (proposed_length > c->length() && c->next()) { if (GapBlock *gap = dynamic_cast<GapBlock*>(c->next())) { proposed_length = qMin(proposed_length, gap->out() - c->in()); } else { proposed_length = c->length(); } } if (proposed_length != c->length()) { command->add_child(new BlockTrimCommand(c->track(), c, proposed_length, Timeline::kTrimOut)); ripple_ranges.append({c->track(), TimeRange(c->in() + proposed_length, c->out())}); } } } if (ripple_box_->isChecked()) { command->add_child(new TimelineRippleDeleteGapsAtRegionsCommand(clips_.first()->track()->sequence(), ripple_ranges)); } // Set speed values if (speed_slider_->IsTristate()) { if (link_box_->isChecked() && !dur_slider_->IsTristate()) { // Automatically determine speed from duration foreach (ClipBlock *c, clips_) { command->add_child(new NodeParamSetStandardValueCommand(NodeKeyframeTrackReference(NodeInput(c, ClipBlock::kSpeedInput)), GetSpeedAdjustment(c->speed(), c->length(), dur_slider_->GetValue()))); } } } else { // Set speeds to value of slider foreach (ClipBlock *c, clips_) { command->add_child(new NodeParamSetStandardValueCommand(NodeKeyframeTrackReference(NodeInput(c, ClipBlock::kSpeedInput)), speed_slider_->GetValue())); } } // Set reverse values if (!reverse_box_->isTristate()) { foreach (ClipBlock *c, clips_) { command->add_child(new NodeParamSetStandardValueCommand(NodeKeyframeTrackReference(NodeInput(c, ClipBlock::kReverseInput)), reverse_box_->isChecked())); } } // Set reverse values if (!maintain_audio_pitch_box_->isTristate()) { foreach (ClipBlock *c, clips_) { command->add_child(new NodeParamSetStandardValueCommand(NodeKeyframeTrackReference(NodeInput(c, ClipBlock::kMaintainAudioPitchInput)), maintain_audio_pitch_box_->isChecked())); } } if (loop_combo_->currentIndex() != -1) { foreach (ClipBlock *c, clips_) { command->add_child(new NodeParamSetStandardValueCommand(NodeKeyframeTrackReference(NodeInput(c, ClipBlock::kLoopModeInput)), loop_combo_->currentData())); } } QString name = (clips_.size() > 1) ? tr("Set %1 Clip Properties").arg(clips_.size()) : tr("Set Clip \"%1\" Properties").arg(clips_.first()->GetLabelOrName()); Core::instance()->undo_stack()->push(command, name); super::accept(); } rational SpeedDurationDialog::GetLengthAdjustment(const rational &original_length, double original_speed, double new_speed, const rational &timebase) { return Timecode::snap_time_to_timebase(rational::fromDouble(original_length.toDouble() / new_speed * original_speed), timebase); } double SpeedDurationDialog::GetSpeedAdjustment(double original_speed, const rational &original_length, const rational &new_length) { return original_speed / new_length.toDouble() * original_length.toDouble(); } void SpeedDurationDialog::SpeedChanged(double s) { if (!link_box_->isChecked()) { return; } if (start_duration_ == -1) { dur_slider_->SetTristate(); } else { dur_slider_->SetValue(GetLengthAdjustment(start_duration_, start_speed_, s, timebase_)); } } void SpeedDurationDialog::DurationChanged(const rational &r) { if (!link_box_->isChecked()) { return; } if (qIsNaN(start_speed_)) { speed_slider_->SetTristate(); } else { speed_slider_->SetValue(GetSpeedAdjustment(start_speed_, start_duration_, r)); } } }
9,617
C++
.cpp
232
37.073276
201
0.685012
olive-editor/olive
8,144
552
131
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
19,097
text.cpp
olive-editor_olive/app/dialog/text/text.cpp
/*** Olive - Non-Linear Video Editor Copyright (C) 2022 Olive Team 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 <http://www.gnu.org/licenses/>. ***/ #include "text.h" #include <QDebug> #include <QDialogButtonBox> #include <QHBoxLayout> #include <QPushButton> #include <QVBoxLayout> #include "ui/icons/icons.h" namespace olive { TextDialog::TextDialog(const QString &start, QWidget* parent) : QDialog(parent) { QVBoxLayout* layout = new QVBoxLayout(this); // Create text edit widget text_edit_ = new QPlainTextEdit(); text_edit_->document()->setPlainText(start); layout->addWidget(text_edit_); // Create buttons QDialogButtonBox* buttons = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); layout->addWidget(buttons); connect(buttons, &QDialogButtonBox::accepted, this, &TextDialog::accept); connect(buttons, &QDialogButtonBox::rejected, this, &TextDialog::reject); } }
1,482
C++
.cpp
37
37.459459
100
0.769553
olive-editor/olive
8,144
552
131
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
19,098
about.cpp
olive-editor_olive/app/dialog/about/about.cpp
/*** Olive - Non-Linear Video Editor Copyright (C) 2022 Olive Team 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 <http://www.gnu.org/licenses/>. ***/ #include "about.h" #include <QApplication> #include <QDialogButtonBox> #include <QLabel> #include <QVBoxLayout> #include "common/qtutils.h" #include "config/config.h" #include "patreon.h" #include "scrollinglabel.h" namespace olive { AboutDialog::AboutDialog(bool welcome_dialog, QWidget *parent) : QDialog(parent) { if (welcome_dialog) { setWindowTitle(tr("Welcome to %1").arg(QApplication::applicationName())); } else { setWindowTitle(tr("About %1").arg(QApplication::applicationName())); } QFontMetrics fm = fontMetrics(); QVBoxLayout* layout = new QVBoxLayout(this); layout->setContentsMargins(fm.height(), fm.height(), fm.height(), fm.height()); QHBoxLayout *horiz_layout = new QHBoxLayout(); horiz_layout->setContentsMargins(fm.height(), fm.height(), fm.height(), fm.height()); horiz_layout->setSpacing(fm.height()*2); QLabel* icon = new QLabel(QStringLiteral("<html><img src=':/graphics/olive-splash.png'></html>")); icon->setAlignment(Qt::AlignCenter); horiz_layout->addWidget(icon); // Construct About text QLabel* label = new QLabel(QStringLiteral("<html><head/><body>" "<p><b>%1</b> %2</p>" // AppName (version identifier) "<p><a href=\"https://www.olivevideoeditor.org/\">" "https://www.olivevideoeditor.org/" "</a></p>" "<p>%3</p>" // First statement "</body></html>").arg(QApplication::applicationName(), QApplication::applicationVersion(), tr("Olive is a free open source non-linear video editor. " "This software is licensed under the GNU GPL Version 3."))); // Set text formatting label->setAlignment(Qt::AlignLeft | Qt::AlignVCenter); label->setWordWrap(true); label->setOpenExternalLinks(true); label->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Minimum); label->setTextInteractionFlags(Qt::TextSelectableByMouse | Qt::LinksAccessibleByMouse); label->setCursor(Qt::IBeamCursor); horiz_layout->addWidget(label); layout->addLayout(horiz_layout); // Patrons where possible layout->addWidget(new QLabel()); QString opening_statement; if (welcome_dialog || patrons.isEmpty()) { opening_statement = tr("<b>Olive relies on support from the community to continue its development.</b>"); } else { opening_statement = tr("Olive wouldn't be possible without the support of gracious donations from the following people."); } QLabel* support_lbl = new QLabel(tr("<html>%1 " "If you like this project, please consider making a " "<a href='https://olivevideoeditor.org/donate.php'>one-time donation</a> or " "<a href='https://www.patreon.com/olivevideoeditor'>pledging monthly</a> to " "support its development.</html>").arg(opening_statement)); support_lbl->setWordWrap(true); support_lbl->setAlignment(Qt::AlignCenter); support_lbl->setOpenExternalLinks(true); layout->addWidget(support_lbl); if (!patrons.isEmpty()) { ScrollingLabel* scroll = new ScrollingLabel(patrons); scroll->StartAnimating(); layout->addWidget(scroll); } layout->addWidget(new QLabel()); QHBoxLayout *btn_layout = new QHBoxLayout(); btn_layout->setContentsMargins(0, 0, 0, 0); btn_layout->setSpacing(0); if (welcome_dialog) { dont_show_again_checkbox_ = new QCheckBox(tr("Don't show this message again")); btn_layout->addWidget(dont_show_again_checkbox_); } else { dont_show_again_checkbox_ = nullptr; } QDialogButtonBox* buttons = new QDialogButtonBox(QDialogButtonBox::Ok, this); if (!welcome_dialog) { buttons->setCenterButtons(true); } btn_layout->addWidget(buttons); layout->addLayout(btn_layout); connect(buttons, &QDialogButtonBox::accepted, this, &QDialog::accept); setFixedSize(sizeHint()); } void AboutDialog::accept() { if (dont_show_again_checkbox_ && dont_show_again_checkbox_->isChecked()) { OLIVE_CONFIG("ShowWelcomeDialog") = false; } QDialog::accept(); } }
5,077
C++
.cpp
111
38.117117
126
0.658087
olive-editor/olive
8,144
552
131
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
19,099
scrollinglabel.cpp
olive-editor_olive/app/dialog/about/scrollinglabel.cpp
/*** Olive - Non-Linear Video Editor Copyright (C) 2022 Olive Team 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 <http://www.gnu.org/licenses/>. ***/ #include "scrollinglabel.h" #include <QPainter> #include "common/qtutils.h" namespace olive { const int ScrollingLabel::kMinLineHeight = 10; ScrollingLabel::ScrollingLabel(QWidget *parent) : QWidget(parent), animate_(0) { timer_.setInterval(50); connect(&timer_, &QTimer::timeout, this, &ScrollingLabel::AnimationUpdate); } ScrollingLabel::ScrollingLabel(const QStringList &text, QWidget *parent) : ScrollingLabel(parent) { SetText(text); } void ScrollingLabel::SetText(const QStringList &text) { text_ = text; QFontMetrics fm = fontMetrics(); text_height_ = fm.height(); int width = 0; foreach (const QString& s, text_) { width = qMax(width, QtUtils::QFontMetricsWidth(fm, s)); } setMinimumSize(width, text_height_ * kMinLineHeight); } void ScrollingLabel::paintEvent(QPaintEvent *e) { QImage map(width(), height(), QImage::Format_RGBA8888_Premultiplied); map.fill(Qt::transparent); { QPainter p(&map); p.setPen(palette().text().color()); QFontMetrics fm = p.fontMetrics(); int half_width = width(); for (int i=0; i<text_.size(); i++) { int text_y = fm.ascent() + height() - animate_ + (fm.height()*i); int text_bottom = text_y + fm.descent(); int text_top = text_y - fm.ascent(); if (text_bottom < 0 || text_top >= height()) { continue; } const QString& s = text_.at(i); int width = QtUtils::QFontMetricsWidth(fm, s); p.drawText(half_width/2 - width/2, text_y, s); } for (int y=0; y<text_height_; y++) { double mul = double(y)/double(text_height_); SetOpacityOfScanLine(map.scanLine(y), map.width(), 4, mul); SetOpacityOfScanLine(map.scanLine(map.height()-1-y), map.width(), 4, mul); } } QPainter wp(this); wp.drawImage(0, 0, map); } void ScrollingLabel::SetOpacityOfScanLine(uchar *scan_line, int width, int channels, double mul) { for (int x=0; x<width; x++) { uchar* pixel = &scan_line[x*4]; for (int c=0; c<channels; c++) { pixel[c] *= mul; } } } void ScrollingLabel::AnimationUpdate() { animate_++; if (animate_ >= height() + text_.size() * text_height_) { animate_ = 0; } update(); } }
2,914
C++
.cpp
89
29.067416
96
0.684569
olive-editor/olive
8,144
552
131
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
19,100
diskcachedialog.cpp
olive-editor_olive/app/dialog/diskcache/diskcachedialog.cpp
/*** Olive - Non-Linear Video Editor Copyright (C) 2022 Olive Team 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 <http://www.gnu.org/licenses/>. ***/ #include "diskcachedialog.h" #include <QDialogButtonBox> #include <QGridLayout> #include <QLabel> #include <QMessageBox> #include "config/config.h" #include "core.h" namespace olive { DiskCacheDialog::DiskCacheDialog(DiskCacheFolder *folder, QWidget* parent) : QDialog(parent), folder_(folder) { QGridLayout* layout = new QGridLayout(this); int row = 0; layout->addWidget(new QLabel(tr("Disk Cache: %1").arg(folder->GetPath())), row, 0, 1, 2); setWindowTitle(tr("Disk Cache Settings")); row++; layout->addWidget(new QLabel(tr("Maximum Disk Cache:")), row, 0); maximum_cache_slider_ = new FloatSlider(); maximum_cache_slider_->SetFormat(tr("%1 GB")); maximum_cache_slider_->SetMinimum(1.0); maximum_cache_slider_->SetValue(static_cast<double>(folder->GetLimit()) / static_cast<double>(kBytesInGigabyte)); layout->addWidget(maximum_cache_slider_, row, 1); row++; clear_cache_btn_ = new QPushButton(tr("Clear Disk Cache")); connect(clear_cache_btn_, &QPushButton::clicked, this, static_cast<void(DiskCacheDialog::*)()>(&DiskCacheDialog::ClearDiskCache)); layout->addWidget(clear_cache_btn_, row, 1); row++; clear_disk_cache_ = new QCheckBox(tr("Automatically clear disk cache on close")); clear_disk_cache_->setChecked(folder->GetClearOnClose()); layout->addWidget(clear_disk_cache_, row, 1); row++; QDialogButtonBox* buttons = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); connect(buttons, &QDialogButtonBox::accepted, this, &DiskCacheDialog::accept); connect(buttons, &QDialogButtonBox::rejected, this, &DiskCacheDialog::reject); layout->addWidget(buttons, row, 0, 1, 2); } void DiskCacheDialog::accept() { qint64 new_disk_cache_limit = qRound64(maximum_cache_slider_->GetValue() * kBytesInGigabyte); if (new_disk_cache_limit != folder_->GetLimit()) { folder_->SetLimit(new_disk_cache_limit); } if (folder_->GetClearOnClose() != clear_disk_cache_->isChecked()) { folder_->SetClearOnClose(clear_disk_cache_->isChecked()); } QDialog::accept(); } void DiskCacheDialog::ClearDiskCache() { ClearDiskCache(folder_->GetPath(), this, clear_cache_btn_); } void DiskCacheDialog::ClearDiskCache(const QString &path, QWidget *parent, QPushButton *clear_btn) { if (QMessageBox::question(parent, tr("Clear Disk Cache"), tr("Are you sure you want to clear the disk cache in '%1'?").arg(path), QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) { if (clear_btn) clear_btn->setEnabled(false); if (DiskManager::instance()->ClearDiskCache(path)) { if (clear_btn) clear_btn->setText(tr("Disk Cache Cleared")); } else { QMessageBox::information(parent, tr("Clear Disk Cache"), tr("Disk cache failed to fully clear. You may have to delete the cache files manually."), QMessageBox::Ok); if (clear_btn) clear_btn->setText(tr("Disk Cache Partially Cleared")); } } } }
3,796
C++
.cpp
85
39.647059
132
0.69943
olive-editor/olive
8,144
552
131
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
19,101
projectproperties.cpp
olive-editor_olive/app/dialog/projectproperties/projectproperties.cpp
/*** Olive - Non-Linear Video Editor Copyright (C) 2020 Olive Team 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 <http://www.gnu.org/licenses/>. ***/ #include "projectproperties.h" #include <QButtonGroup> #include <QDialogButtonBox> #include <QFileDialog> #include <QGroupBox> #include <QLabel> #include <QMessageBox> #include <QPushButton> #include "common/filefunctions.h" #include "node/color/colormanager/colormanager.h" #include "render/diskmanager.h" namespace olive { #define super QDialog ProjectPropertiesDialog::ProjectPropertiesDialog(Project* p, QWidget *parent) : super(parent), working_project_(p), ocio_config_is_valid_(true) { QVBoxLayout* layout = new QVBoxLayout(this); setWindowTitle(tr("Project Properties for '%1'").arg(working_project_->name())); QTabWidget* tabs = new QTabWidget; layout->addWidget(tabs); { // Color management group QWidget* color_group = new QWidget(); QVBoxLayout* color_outer_layout = new QVBoxLayout(color_group); QGridLayout* color_layout = new QGridLayout(); color_outer_layout->addLayout(color_layout); int row = 0; color_layout->addWidget(new QLabel(tr("OpenColorIO Configuration:")), row, 0); ocio_filename_ = new QLineEdit(); ocio_filename_->setPlaceholderText(tr("(default)")); color_layout->addWidget(ocio_filename_, row, 1); row++; color_layout->addWidget(new QLabel(tr("Default Input Color Space:")), row, 0); default_input_colorspace_ = new QComboBox(); color_layout->addWidget(default_input_colorspace_, row, 1, 1, 2); row++; color_layout->addWidget(new QLabel(tr("Reference Space:")), row, 0); reference_space_ = new QComboBox(this); reference_space_->addItem(tr("Scene Linear"), OCIO::ROLE_SCENE_LINEAR); reference_space_->addItem(tr("Compositing Log"), OCIO::ROLE_COMPOSITING_LOG); QtUtils::SetComboBoxData(reference_space_, p->GetColorReferenceSpace()); color_layout->addWidget(reference_space_, row, 1, 1, 2); row++; QPushButton* browse_btn = new QPushButton(tr("Browse")); color_layout->addWidget(browse_btn, 0, 2); connect(browse_btn, &QPushButton::clicked, this, &ProjectPropertiesDialog::BrowseForOCIOConfig); ocio_filename_->setText(working_project_->color_manager()->GetConfigFilename()); connect(ocio_filename_, &QLineEdit::textChanged, this, &ProjectPropertiesDialog::OCIOFilenameUpdated); OCIOFilenameUpdated(); tabs->addTab(color_group, tr("Color Management")); color_outer_layout->addStretch(); } { // Cache group QWidget* cache_group = new QWidget(); QVBoxLayout* cache_layout = new QVBoxLayout(cache_group); QButtonGroup* disk_cache_btn_group = new QButtonGroup(); // Create radio buttons and add to widget and button group disk_cache_radios_[Project::kCacheUseDefaultLocation] = new QRadioButton(tr("Use Default Location")); disk_cache_radios_[Project::kCacheStoreAlongsideProject] = new QRadioButton(tr("Store Alongside Project")); disk_cache_radios_[Project::kCacheCustomPath] = new QRadioButton(tr("Use Custom Location:")); for (int i=0; i<kDiskCacheRadioCount; i++) { disk_cache_btn_group->addButton(disk_cache_radios_[i]); cache_layout->addWidget(disk_cache_radios_[i]); } // Create custom cache path widget custom_cache_path_ = new PathWidget(working_project_->GetCustomCachePath(), this); custom_cache_path_->setEnabled(false); cache_layout->addWidget(custom_cache_path_); // Ensure custom cache path "enabled" is tied to the radio button being checked connect(disk_cache_radios_[Project::kCacheCustomPath], &QRadioButton::toggled, custom_cache_path_, &PathWidget::setEnabled); // Check the radio button that should currently be active disk_cache_radios_[working_project_->GetCacheLocationSetting()]->setChecked(true); // Add disk cache settings button QPushButton* disk_cache_settings_btn = new QPushButton(tr("Disk Cache Settings")); connect(disk_cache_settings_btn, &QPushButton::clicked, this, &ProjectPropertiesDialog::OpenDiskCacheSettings); cache_layout->addWidget(disk_cache_settings_btn); tabs->addTab(cache_group, tr("Disk Cache")); } QDialogButtonBox* dialog_btns = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, Qt::Horizontal); layout->addWidget(dialog_btns); connect(dialog_btns, &QDialogButtonBox::accepted, this, &ProjectPropertiesDialog::accept); connect(dialog_btns, &QDialogButtonBox::rejected, this, &ProjectPropertiesDialog::reject); } void ProjectPropertiesDialog::accept() { if (!ocio_config_is_valid_) { QMessageBox mb(this); mb.setWindowModality(Qt::WindowModal); mb.setIcon(QMessageBox::Critical); mb.setWindowTitle(tr("OpenColorIO Config Error")); mb.setText(tr("Failed to set OpenColorIO configuration: %1").arg(ocio_config_error_)); mb.addButton(QMessageBox::Ok); mb.exec(); return; } if (disk_cache_radios_[Project::kCacheUseDefaultLocation]->isChecked()) { // Keep new cache path empty, which means default } else if (disk_cache_radios_[Project::kCacheStoreAlongsideProject]->isChecked()) { // Ensure alongside project path is valid if (!VerifyPathAndWarnIfBad(working_project_->get_cache_alongside_project_path())) { return; } } else { // Ensure custom path is valid if (!VerifyPathAndWarnIfBad(custom_cache_path_->text())) { return; } } if (custom_cache_path_->text() != working_project_->GetCustomCachePath()) { // Check if the user is okay with invalidating the current cache if (!DiskManager::ShowDiskCacheChangeConfirmationDialog(this)) { return; } working_project_->SetCustomCachePath(custom_cache_path_->text()); emit DiskManager::instance()->InvalidateProject(working_project_); } // This should ripple changes throughout the graph/cache that the color config has changed, and // therefore should be done after the cache path is changed if (working_project_->color_manager()->GetConfigFilename() != ocio_filename_->text()) { working_project_->color_manager()->SetConfigFilename(ocio_filename_->text()); } if (working_project_->color_manager()->GetDefaultInputColorSpace() != default_input_colorspace_->currentText()) { working_project_->color_manager()->SetDefaultInputColorSpace(default_input_colorspace_->currentText()); } if (working_project_->GetColorReferenceSpace() != reference_space_->currentData().toString()) { working_project_->SetColorReferenceSpace(reference_space_->currentData().toString()); } super::accept(); } bool ProjectPropertiesDialog::VerifyPathAndWarnIfBad(const QString &path) { if (!FileFunctions::DirectoryIsValid(path)) { QMessageBox mb(this); mb.setWindowModality(Qt::WindowModal); mb.setIcon(QMessageBox::Critical); mb.setWindowTitle(tr("Invalid path")); mb.setText(tr("The custom cache path is invalid. Please check it and try again.")); mb.addButton(QMessageBox::Ok); mb.exec(); return false; } return true; } void ProjectPropertiesDialog::BrowseForOCIOConfig() { QString fn = QFileDialog::getOpenFileName(this, tr("Browse for OpenColorIO configuration")); if (!fn.isEmpty()) { ocio_filename_->setText(fn); } } void ProjectPropertiesDialog::OCIOFilenameUpdated() { default_input_colorspace_->clear(); try { OCIO::ConstConfigRcPtr c; if (ocio_filename_->text().isEmpty()) { c = ColorManager::GetDefaultConfig(); } else { c = ColorManager::CreateConfigFromFile(ocio_filename_->text()); } ocio_filename_->setStyleSheet(QString()); ocio_config_is_valid_ = true; // List input color spaces QStringList input_cs = ColorManager::ListAvailableColorspaces(c); foreach (QString cs, input_cs) { default_input_colorspace_->addItem(cs); if (cs == working_project_->color_manager()->GetDefaultInputColorSpace()) { default_input_colorspace_->setCurrentIndex(default_input_colorspace_->count()-1); } } } catch (OCIO::Exception& e) { ocio_config_is_valid_ = false; ocio_filename_->setStyleSheet(QStringLiteral("QLineEdit {color: red;}")); ocio_config_error_ = e.what(); } } void ProjectPropertiesDialog::OpenDiskCacheSettings() { if (disk_cache_radios_[Project::kCacheUseDefaultLocation]->isChecked()) { DiskManager::instance()->ShowDiskCacheSettingsDialog(DiskManager::instance()->GetDefaultCacheFolder(), this); } else if (disk_cache_radios_[Project::kCacheStoreAlongsideProject]->isChecked()) { DiskManager::instance()->ShowDiskCacheSettingsDialog(working_project_->get_cache_alongside_project_path(), this); } else { DiskManager::instance()->ShowDiskCacheSettingsDialog(custom_cache_path_->text(), this); } } }
9,411
C++
.cpp
205
41.478049
128
0.727422
olive-editor/olive
8,144
552
131
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
19,102
sequencedialogparametertab.cpp
olive-editor_olive/app/dialog/sequence/sequencedialogparametertab.cpp
#include "sequencedialogparametertab.h" #include <QGroupBox> #include <QLabel> #include <QPushButton> #include <QVBoxLayout> #include "core.h" namespace olive { SequenceDialogParameterTab::SequenceDialogParameterTab(Sequence* sequence, QWidget* parent) : QWidget(parent) { QVBoxLayout* layout = new QVBoxLayout(this); int row = 0; // Set up video section QGroupBox* video_group = new QGroupBox(); video_group->setTitle(tr("Video")); QGridLayout *video_layout = new QGridLayout(video_group); video_layout->addWidget(new QLabel(tr("Width:")), row, 0); width_slider_ = new IntegerSlider(); width_slider_->SetMinimum(0); video_layout->addWidget(width_slider_, row, 1); row++; video_layout->addWidget(new QLabel(tr("Height:")), row, 0); height_slider_ = new IntegerSlider(); height_slider_->SetMinimum(0); video_layout->addWidget(height_slider_, row, 1); row++; video_layout->addWidget(new QLabel(tr("Frame Rate:")), row, 0); framerate_combo_ = new FrameRateComboBox(); video_layout->addWidget(framerate_combo_, row, 1); row++; video_layout->addWidget(new QLabel(tr("Pixel Aspect Ratio:")), row, 0); pixelaspect_combo_ = new PixelAspectRatioComboBox(); video_layout->addWidget(pixelaspect_combo_, row, 1); row++; video_layout->addWidget(new QLabel(tr("Interlacing:")), row, 0); interlacing_combo_ = new InterlacedComboBox(); video_layout->addWidget(interlacing_combo_, row, 1); layout->addWidget(video_group); row = 0; // Set up audio section QGroupBox* audio_group = new QGroupBox(); audio_group->setTitle(tr("Audio")); QGridLayout* audio_layout = new QGridLayout(audio_group); audio_layout->addWidget(new QLabel(tr("Sample Rate:")), row, 0); audio_sample_rate_field_ = new SampleRateComboBox(); audio_layout->addWidget(audio_sample_rate_field_, row, 1); row++; audio_layout->addWidget(new QLabel(tr("Channels:")), row, 0); audio_channels_field_ = new ChannelLayoutComboBox(); audio_layout->addWidget(audio_channels_field_, row, 1); layout->addWidget(audio_group); row = 0; // Set up preview section QGroupBox* preview_group = new QGroupBox(); preview_group->setTitle(tr("Preview")); QGridLayout* preview_layout = new QGridLayout(preview_group); preview_layout->addWidget(new QLabel(tr("Resolution:")), row, 0); preview_resolution_field_ = new VideoDividerComboBox(); preview_layout->addWidget(preview_resolution_field_, row, 1); preview_resolution_label_ = new QLabel(); preview_layout->addWidget(preview_resolution_label_, row, 2); row++; preview_layout->addWidget(new QLabel(tr("Quality:")), row, 0); preview_format_field_ = new PixelFormatComboBox(false); preview_layout->addWidget(preview_format_field_, row, 1, 1, 2); /* TEMP: Disable sequence auto-cache, wanna see if clip cache supersedes it. row++; preview_layout->addWidget(new QLabel(tr("Auto-Cache:")), row, 0); preview_layout->addWidget(preview_autocache_field_, row, 1);*/ preview_autocache_field_ = new QCheckBox(); layout->addWidget(preview_group); // Set values based on input sequence VideoParams vp = sequence->GetVideoParams(); AudioParams ap = sequence->GetAudioParams(); width_slider_->SetValue(vp.width()); height_slider_->SetValue(vp.height()); framerate_combo_->SetFrameRate(vp.time_base().flipped()); pixelaspect_combo_->SetPixelAspectRatio(vp.pixel_aspect_ratio()); interlacing_combo_->SetInterlaceMode(vp.interlacing()); preview_resolution_field_->SetDivider(vp.divider()); preview_format_field_->SetPixelFormat(vp.format()); preview_autocache_field_->setChecked(sequence->IsVideoAutoCacheEnabled()); audio_sample_rate_field_->SetSampleRate(ap.sample_rate()); audio_channels_field_->SetChannelLayout(ap.channel_layout()); connect(preview_resolution_field_, static_cast<void(QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this, &SequenceDialogParameterTab::UpdatePreviewResolutionLabel); layout->addStretch(); QPushButton* save_preset_btn = new QPushButton(tr("Save Preset")); connect(save_preset_btn, &QPushButton::clicked, this, &SequenceDialogParameterTab::SavePresetClicked); layout->addWidget(save_preset_btn); UpdatePreviewResolutionLabel(); } void SequenceDialogParameterTab::PresetChanged(const SequencePreset &preset) { width_slider_->SetValue(preset.width()); height_slider_->SetValue(preset.height()); framerate_combo_->SetFrameRate(preset.frame_rate()); pixelaspect_combo_->SetPixelAspectRatio(preset.pixel_aspect()); interlacing_combo_->SetInterlaceMode(preset.interlacing()); audio_sample_rate_field_->SetSampleRate(preset.sample_rate()); audio_channels_field_->SetChannelLayout(preset.channel_layout()); preview_resolution_field_->SetDivider(preset.preview_divider()); preview_format_field_->SetPixelFormat(preset.preview_format()); preview_autocache_field_->setChecked(preset.preview_autocache()); } void SequenceDialogParameterTab::SavePresetClicked() { emit SaveParametersAsPreset({QString(), GetSelectedVideoWidth(), GetSelectedVideoHeight(), GetSelectedVideoFrameRate(), GetSelectedVideoPixelAspect(), GetSelectedVideoInterlacingMode(), GetSelectedAudioSampleRate(), GetSelectedAudioChannelLayout(), GetSelectedPreviewResolution(), GetSelectedPreviewFormat(), GetSelectedPreviewAutoCache()}); } void SequenceDialogParameterTab::UpdatePreviewResolutionLabel() { VideoParams test_param(GetSelectedVideoWidth(), GetSelectedVideoHeight(), PixelFormat::INVALID, VideoParams::kInternalChannelCount, rational(1), VideoParams::kInterlaceNone, preview_resolution_field_->currentData().toInt()); preview_resolution_label_->setText(tr("(%1x%2)").arg(QString::number(test_param.effective_width()), QString::number(test_param.effective_height()))); } }
6,275
C++
.cpp
132
40.969697
107
0.695801
olive-editor/olive
8,144
552
131
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
19,103
sequencedialogpresettab.cpp
olive-editor_olive/app/dialog/sequence/sequencedialogpresettab.cpp
/*** Olive - Non-Linear Video Editor Copyright (C) 2022 Olive Team 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 <http://www.gnu.org/licenses/>. ***/ #include "sequencedialogpresettab.h" #include <QDir> #include <QGroupBox> #include <QInputDialog> #include <QMessageBox> #include <QVBoxLayout> #include <QSplitter> #include <QTreeWidgetItem> #include <QXmlStreamWriter> #include "common/filefunctions.h" #include "config/config.h" #include "render/videoparams.h" #include "ui/icons/icons.h" #include "widget/menu/menu.h" namespace olive { const int kDataIsPreset = Qt::UserRole; const int kDataPresetIsCustomRole = Qt::UserRole + 1; const int kDataPresetDataRole = Qt::UserRole + 2; SequenceDialogPresetTab::SequenceDialogPresetTab(QWidget* parent) : QWidget(parent), PresetManager<SequencePreset>(this, QStringLiteral("sequencepresets")) { QVBoxLayout* outer_layout = new QVBoxLayout(this); outer_layout->setContentsMargins(0, 0, 0, 0); preset_tree_ = new QTreeWidget(); preset_tree_->setColumnCount(1); preset_tree_->setHeaderLabel(tr("Preset")); preset_tree_->setContextMenuPolicy(Qt::CustomContextMenu); connect(preset_tree_, &QTreeWidget::customContextMenuRequested, this, &SequenceDialogPresetTab::ShowContextMenu); outer_layout->addWidget(preset_tree_); connect(preset_tree_, &QTreeWidget::currentItemChanged, this, &SequenceDialogPresetTab::SelectedItemChanged); connect(preset_tree_, &QTreeWidget::itemDoubleClicked, this, &SequenceDialogPresetTab::ItemDoubleClicked); // Add "my presets" folder my_presets_folder_ = CreateFolder(tr("My Presets")); preset_tree_->addTopLevelItem(my_presets_folder_); // Add presets preset_tree_->addTopLevelItem(CreateHDPresetFolder(tr("4K UHD"), 3840, 2160, 2)); preset_tree_->addTopLevelItem(CreateHDPresetFolder(tr("1080p"), 1920, 1080, 1)); preset_tree_->addTopLevelItem(CreateHDPresetFolder(tr("720p"), 1280, 720, 1)); preset_tree_->addTopLevelItem(CreateSDPresetFolder(tr("NTSC"), 720, 480, rational(30000, 1001), VideoParams::kPixelAspectNTSCStandard, VideoParams::kPixelAspectNTSCWidescreen, 1)); preset_tree_->addTopLevelItem(CreateSDPresetFolder(tr("PAL"), 720, 576, rational(25, 1), VideoParams::kPixelAspectPALStandard, VideoParams::kPixelAspectPALWidescreen, 1)); // Load custom presets for (int i=0;i<GetNumberOfPresets();i++) { AddCustomItem(my_presets_folder_, GetPreset(i), i); } } void SequenceDialogPresetTab::SaveParametersAsPreset(SequencePreset preset) { PresetPtr preset_ptr = std::make_shared<SequencePreset>(preset); // If replaced, no need to make another item. If not saved, shared ptr will delete itself if (SavePreset(preset_ptr) == kAppended) { AddCustomItem(my_presets_folder_, preset_ptr, GetNumberOfPresets() - 1); } } QTreeWidgetItem* SequenceDialogPresetTab::CreateFolder(const QString &name) { QTreeWidgetItem* folder = new QTreeWidgetItem(); folder->setText(0, name); folder->setIcon(0, icon::Folder); return folder; } QTreeWidgetItem *SequenceDialogPresetTab::CreateHDPresetFolder(const QString &name, int width, int height, int divider) { const PixelFormat default_format = static_cast<PixelFormat::Format>(OLIVE_CONFIG("OfflinePixelFormat").toInt()); const bool default_autocache = false; QTreeWidgetItem* parent = CreateFolder(name); AddStandardItem(parent, std::make_shared<SequencePreset>(tr("%1 23.976 FPS").arg(name), width, height, rational(24000, 1001), VideoParams::kPixelAspectSquare, VideoParams::kInterlaceNone, 48000, AV_CH_LAYOUT_STEREO, divider, default_format, default_autocache)); AddStandardItem(parent, std::make_shared<SequencePreset>(tr("%1 25 FPS").arg(name), width, height, rational(25, 1), VideoParams::kPixelAspectSquare, VideoParams::kInterlaceNone, 48000, AV_CH_LAYOUT_STEREO, divider, default_format, default_autocache)); AddStandardItem(parent, std::make_shared<SequencePreset>(tr("%1 29.97 FPS").arg(name), width, height, rational(30000, 1001), VideoParams::kPixelAspectSquare, VideoParams::kInterlaceNone, 48000, AV_CH_LAYOUT_STEREO, divider, default_format, default_autocache)); AddStandardItem(parent, std::make_shared<SequencePreset>(tr("%1 50 FPS").arg(name), width, height, rational(50, 1), VideoParams::kPixelAspectSquare, VideoParams::kInterlaceNone, 48000, AV_CH_LAYOUT_STEREO, divider, default_format, default_autocache)); AddStandardItem(parent, std::make_shared<SequencePreset>(tr("%1 59.94 FPS").arg(name), width, height, rational(60000, 1001), VideoParams::kPixelAspectSquare, VideoParams::kInterlaceNone, 48000, AV_CH_LAYOUT_STEREO, divider, default_format, default_autocache)); return parent; } QTreeWidgetItem *SequenceDialogPresetTab::CreateSDPresetFolder(const QString &name, int width, int height, const rational& frame_rate, const rational &standard_par, const rational &wide_par, int divider) { const PixelFormat default_format = static_cast<PixelFormat::Format>(OLIVE_CONFIG("OfflinePixelFormat").toInt()); const bool default_autocache = false; QTreeWidgetItem* parent = CreateFolder(name); preset_tree_->addTopLevelItem(parent); AddStandardItem(parent, std::make_shared<SequencePreset>(tr("%1 Standard").arg(name), width, height, frame_rate, standard_par, VideoParams::kInterlacedBottomFirst, 48000, AV_CH_LAYOUT_STEREO, divider, default_format, default_autocache)); AddStandardItem(parent, std::make_shared<SequencePreset>(tr("%1 Widescreen").arg(name), width, height, frame_rate, wide_par, VideoParams::kInterlacedBottomFirst, 48000, AV_CH_LAYOUT_STEREO, divider, default_format, default_autocache)); return parent; } QTreeWidgetItem *SequenceDialogPresetTab::GetSelectedItem() { QList<QTreeWidgetItem*> selected_items = preset_tree_->selectedItems(); if (selected_items.isEmpty()) { return nullptr; } else { return selected_items.first(); } } QTreeWidgetItem *SequenceDialogPresetTab::GetSelectedCustomPreset() { QTreeWidgetItem* sel = GetSelectedItem(); if (sel && sel->data(0, kDataIsPreset).toBool() && sel->data(0, kDataPresetIsCustomRole).toBool()) { return sel; } return nullptr; } void SequenceDialogPresetTab::AddStandardItem(QTreeWidgetItem *folder, PresetPtr preset, const QString& description) { int index = default_preset_data_.size(); default_preset_data_.append(preset); AddItemInternal(folder, preset, false, index, description); } void SequenceDialogPresetTab::AddCustomItem(QTreeWidgetItem *folder, PresetPtr preset, int index, const QString &description) { AddItemInternal(folder, preset, true, index, description); } void SequenceDialogPresetTab::AddItemInternal(QTreeWidgetItem *folder, PresetPtr preset, bool is_custom, int index, const QString &description) { QTreeWidgetItem* item = new QTreeWidgetItem(); item->setText(0, preset->GetName()); item->setIcon(0, icon::Video); item->setToolTip(0, description); item->setData(0, kDataIsPreset, true); item->setData(0, kDataPresetIsCustomRole, is_custom); item->setData(0, kDataPresetDataRole, index); folder->addChild(item); } void SequenceDialogPresetTab::SelectedItemChanged(QTreeWidgetItem* current, QTreeWidgetItem* previous) { Q_UNUSED(previous) if (current->data(0, kDataIsPreset).toBool()) { int preset_index = current->data(0, kDataPresetDataRole).toInt(); PresetPtr preset_data = (current->data(0, kDataPresetIsCustomRole).toBool()) ? GetPreset(preset_index) : default_preset_data_.at(preset_index); emit PresetChanged(*static_cast<SequencePreset*>(preset_data.get())); } } void SequenceDialogPresetTab::ItemDoubleClicked(QTreeWidgetItem *item, int column) { Q_UNUSED(column) if (item->data(0, kDataIsPreset).toBool()) { emit PresetAccepted(); } } void SequenceDialogPresetTab::ShowContextMenu() { QTreeWidgetItem* sel = GetSelectedCustomPreset(); if (sel) { Menu m(this); QAction* delete_action = m.addAction(tr("Delete Preset")); connect(delete_action, &QAction::triggered, this, &SequenceDialogPresetTab::DeleteSelectedPreset); m.exec(QCursor::pos()); } } void SequenceDialogPresetTab::DeleteSelectedPreset() { QTreeWidgetItem* sel = GetSelectedCustomPreset(); if (sel) { int preset_index = sel->data(0, kDataPresetDataRole).toInt(); // Shift all items whose index was after this preset forward for (int i=0; i<my_presets_folder_->childCount(); i++) { QTreeWidgetItem* custom_item = my_presets_folder_->child(i); int this_item_index = custom_item->data(0, kDataPresetDataRole).toInt(); if (this_item_index > preset_index) { custom_item->setData(0, kDataPresetDataRole, this_item_index - 1); } } // Remove the preset DeletePreset(preset_index); // Delete the item delete sel; } } }
12,670
C++
.cpp
259
33.486486
203
0.56208
olive-editor/olive
8,144
552
131
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
19,104
sequence.cpp
olive-editor_olive/app/dialog/sequence/sequence.cpp
/*** Olive - Non-Linear Video Editor Copyright (C) 2022 Olive Team 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 <http://www.gnu.org/licenses/>. ***/ #include "sequence.h" #include <QDialogButtonBox> #include <QGroupBox> #include <QLabel> #include <QLineEdit> #include <QMessageBox> #include <QPushButton> #include <QSplitter> #include <QVBoxLayout> #include "config/config.h" #include "core.h" #include "common/channellayout.h" #include "common/qtutils.h" #include "undo/undostack.h" namespace olive { SequenceDialog::SequenceDialog(Sequence* s, Type t, QWidget* parent) : QDialog(parent), sequence_(s), make_undoable_(true) { QVBoxLayout* layout = new QVBoxLayout(this); QSplitter* splitter = new QSplitter(); layout->addWidget(splitter); preset_tab_ = new SequenceDialogPresetTab(); splitter->addWidget(preset_tab_); parameter_tab_ = new SequenceDialogParameterTab(sequence_); splitter->addWidget(parameter_tab_); connect(preset_tab_, &SequenceDialogPresetTab::PresetChanged, parameter_tab_, &SequenceDialogParameterTab::PresetChanged); connect(preset_tab_, &SequenceDialogPresetTab::PresetAccepted, this, &SequenceDialog::accept); connect(parameter_tab_, &SequenceDialogParameterTab::SaveParametersAsPreset, preset_tab_, &SequenceDialogPresetTab::SaveParametersAsPreset); // Set up name section QHBoxLayout* name_layout = new QHBoxLayout(); name_layout->addWidget(new QLabel(tr("Name:"))); name_field_ = new QLineEdit(); name_layout->addWidget(name_field_); layout->addLayout(name_layout); // Set up dialog buttons QDialogButtonBox* buttons = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); QPushButton *default_btn = buttons->addButton(tr("Set As Default"), QDialogButtonBox::ActionRole); connect(buttons, &QDialogButtonBox::accepted, this, &SequenceDialog::accept); connect(buttons, &QDialogButtonBox::rejected, this, &SequenceDialog::reject); connect(default_btn, &QPushButton::clicked, this, &SequenceDialog::SetAsDefaultClicked); layout->addWidget(buttons); // Set window title based on type switch (t) { case kNew: setWindowTitle(tr("New Sequence")); break; case kExisting: setWindowTitle(tr("Editing \"%1\"").arg(sequence_->GetLabel())); break; } name_field_->setText(sequence_->GetLabel()); } void SequenceDialog::SetUndoable(bool u) { make_undoable_ = u; } void SequenceDialog::SetNameIsEditable(bool e) { name_field_->setEnabled(e); } void SequenceDialog::accept() { if (name_field_->isEnabled() && name_field_->text().isEmpty()) { QtUtils::MsgBox(this, QMessageBox::Critical, tr("Error editing Sequence"), tr("Please enter a name for this Sequence.")); return; } if (!VideoParams::FormatIsFloat(parameter_tab_->GetSelectedPreviewFormat()) && !OLIVE_CONFIG("PreviewNonFloatDontAskAgain").toBool()) { QMessageBox b(this); QCheckBox *dont_show_again_ = new QCheckBox(tr("Don't ask me again")); b.setIcon(QMessageBox::Warning); b.setWindowTitle(tr("Low Quality Preview")); b.setText(tr("The preview resolution has been set to a non-float format. This may cause banding and clipping artifacts in the preview.\n\n" "Do you wish to continue?")); b.setCheckBox(dont_show_again_); b.addButton(QMessageBox::Yes); b.addButton(QMessageBox::No); if (b.exec() == QMessageBox::No) { return; } if (dont_show_again_->isChecked()) { OLIVE_CONFIG("PreviewNonFloatDontAskAgain") = true; } } // Generate video and audio parameter structs from data VideoParams video_params = VideoParams(parameter_tab_->GetSelectedVideoWidth(), parameter_tab_->GetSelectedVideoHeight(), parameter_tab_->GetSelectedVideoFrameRate().flipped(), parameter_tab_->GetSelectedPreviewFormat(), VideoParams::kInternalChannelCount, parameter_tab_->GetSelectedVideoPixelAspect(), parameter_tab_->GetSelectedVideoInterlacingMode(), parameter_tab_->GetSelectedPreviewResolution()); AudioParams audio_params = AudioParams(parameter_tab_->GetSelectedAudioSampleRate(), parameter_tab_->GetSelectedAudioChannelLayout(), Sequence::kDefaultSampleFormat); if (make_undoable_) { // Make undoable command to change the parameters SequenceParamCommand* param_command = new SequenceParamCommand(sequence_, video_params, audio_params, name_field_->text(), parameter_tab_->GetSelectedPreviewAutoCache()); Core::instance()->undo_stack()->push(param_command, tr("Set Sequence Parameters For \"%1\"").arg(sequence_->GetLabel())); } else { // Set sequence values directly with no undo command sequence_->SetVideoParams(video_params); sequence_->SetAudioParams(audio_params); sequence_->SetLabel(name_field_->text()); sequence_->SetVideoAutoCacheEnabled(parameter_tab_->GetSelectedPreviewAutoCache()); } QDialog::accept(); } void SequenceDialog::SetAsDefaultClicked() { if (QtUtils::MsgBox(this, QMessageBox::Question, tr("Confirm Set As Default"), tr("Are you sure you want to set the current parameters as defaults?"), QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) { // Maybe replace with Preset system OLIVE_CONFIG("DefaultSequenceWidth") = parameter_tab_->GetSelectedVideoWidth(); OLIVE_CONFIG("DefaultSequenceHeight") = parameter_tab_->GetSelectedVideoHeight(); OLIVE_CONFIG("DefaultSequencePixelAspect") = QVariant::fromValue(parameter_tab_->GetSelectedVideoPixelAspect()); OLIVE_CONFIG("DefaultSequenceFrameRate") = QVariant::fromValue(parameter_tab_->GetSelectedVideoFrameRate().flipped()); OLIVE_CONFIG("DefaultSequenceInterlacing") = parameter_tab_->GetSelectedVideoInterlacingMode(); OLIVE_CONFIG("DefaultSequenceAudioFrequency") = parameter_tab_->GetSelectedAudioSampleRate(); OLIVE_CONFIG("DefaultSequenceAudioLayout") = QVariant::fromValue(parameter_tab_->GetSelectedAudioChannelLayout()); } } SequenceDialog::SequenceParamCommand::SequenceParamCommand(Sequence* s, const VideoParams& video_params, const AudioParams &audio_params, const QString& name, bool autocache) : sequence_(s), new_video_params_(video_params), new_audio_params_(audio_params), new_name_(name), new_autocache_(autocache), old_video_params_(s->GetVideoParams()), old_audio_params_(s->GetAudioParams()), old_name_(s->GetLabel()), old_autocache_(s->IsVideoAutoCacheEnabled()) { } Project *SequenceDialog::SequenceParamCommand::GetRelevantProject() const { return sequence_->project(); } void SequenceDialog::SequenceParamCommand::redo() { if (sequence_->GetVideoParams() != new_video_params_) { sequence_->SetVideoParams(new_video_params_); } if (sequence_->GetAudioParams() != new_audio_params_) { sequence_->SetAudioParams(new_audio_params_); } sequence_->SetLabel(new_name_); sequence_->SetVideoAutoCacheEnabled(new_autocache_); } void SequenceDialog::SequenceParamCommand::undo() { if (sequence_->GetVideoParams() != old_video_params_) { sequence_->SetVideoParams(old_video_params_); } if (sequence_->GetAudioParams() != old_audio_params_) { sequence_->SetAudioParams(old_audio_params_); } sequence_->SetLabel(old_name_); sequence_->SetVideoAutoCacheEnabled(old_autocache_); } }
8,663
C++
.cpp
189
38.042328
143
0.67457
olive-editor/olive
8,144
552
131
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
19,105
autorecoverydialog.cpp
olive-editor_olive/app/dialog/autorecovery/autorecoverydialog.cpp
/*** Olive - Non-Linear Video Editor Copyright (C) 2022 Olive Team 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 <http://www.gnu.org/licenses/>. ***/ #include "autorecoverydialog.h" #include <QDateTime> #include <QDialogButtonBox> #include <QDir> #include <QLabel> #include <QPushButton> #include <QVBoxLayout> #include "core.h" namespace olive { #define super QDialog AutoRecoveryDialog::AutoRecoveryDialog(const QString &message, const QStringList &recoveries, bool autocheck_latest, QWidget* parent) : QDialog(parent) { Init(message); PopulateTree(recoveries, autocheck_latest); } void AutoRecoveryDialog::accept() { foreach (QTreeWidgetItem* checkable, checkable_items_) { if (checkable->checkState(0) == Qt::Checked) { QString filename = checkable->data(0, kFilenameRole).toString(); Core::instance()->OpenRecoveryProject(filename); } } super::accept(); } void AutoRecoveryDialog::Init(const QString& header_text) { QVBoxLayout* layout = new QVBoxLayout(this); setWindowTitle(tr("Auto-Recovery")); layout->addWidget(new QLabel(header_text)); tree_widget_ = new QTreeWidget(); tree_widget_->setHeaderHidden(true); layout->addWidget(tree_widget_); QDialogButtonBox* buttons = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); buttons->button(QDialogButtonBox::Ok)->setText(tr("Load")); connect(buttons, &QDialogButtonBox::accepted, this, &AutoRecoveryDialog::accept); connect(buttons, &QDialogButtonBox::rejected, this, &AutoRecoveryDialog::reject); layout->addWidget(buttons); } void AutoRecoveryDialog::PopulateTree(const QStringList& recoveries, bool autocheck_latest) { // Each entry in `recoveries` is a directory with 1+ recovery projects in it QDir autorecovery_root(FileFunctions::GetAutoRecoveryRoot()); foreach (const QString& recovery_folder, recoveries) { QDir recovery_dir(autorecovery_root.filePath(recovery_folder)); QString pretty_name; { // Retrieve pretty name QFile pretty_name_file(recovery_dir.filePath(QStringLiteral("realname.txt"))); if (pretty_name_file.open(QFile::ReadOnly)) { // Read pretty name that we should have written in the autorecovery process pretty_name = QString::fromUtf8(pretty_name_file.readAll()); pretty_name_file.close(); } if (pretty_name.isEmpty()) { // Fallback to just the UUID. While it won't mean much to the user, it's better than nothing. pretty_name = recovery_dir.dirName(); } } QTreeWidgetItem* top_level = new QTreeWidgetItem(tree_widget_); top_level->setText(0, pretty_name); { // Populate with recoveries QStringList entries = recovery_dir.entryList(QDir::Files | QDir::NoDotAndDotDot, QDir::Name | QDir::Reversed); for (int i=0; i<entries.size(); i++) { const QString& entry = entries.at(i); if (entry.endsWith(QStringLiteral(".ove"), Qt::CaseInsensitive)) { QTreeWidgetItem* entry_item = new QTreeWidgetItem(top_level); bool ok; qint64 recovery_time = entry.left(entry.indexOf('.')).toLongLong(&ok); QString entry_name; if (ok) { // Set as time/date of recovery entry_name = QDateTime::fromSecsSinceEpoch(recovery_time).toString(); } else { // Fallback if we couldn't discern a date from this entry_name = entry; } entry_item->setText(0, entry_name); entry_item->setData(0, kFilenameRole, recovery_dir.filePath(entry)); // Allow to be checked, auto-checking the first entry entry_item->setCheckState(0, (autocheck_latest && top_level->childCount() == 1) ? Qt::Checked : Qt::Unchecked); checkable_items_.append(entry_item); } } } } } }
4,394
C++
.cpp
104
37
135
0.707609
olive-editor/olive
8,144
552
131
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
19,106
footagerelinkdialog.cpp
olive-editor_olive/app/dialog/footagerelink/footagerelinkdialog.cpp
/*** Olive - Non-Linear Video Editor Copyright (C) 2019 Olive Team 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 <http://www.gnu.org/licenses/>. ***/ #include "footagerelinkdialog.h" #include <QDialogButtonBox> #include <QFileDialog> #include <QFileInfo> #include <QHeaderView> #include <QLabel> #include <QPushButton> #include <QScrollBar> #include <QVBoxLayout> namespace olive { FootageRelinkDialog::FootageRelinkDialog(const QVector<Footage *> &footage, QWidget* parent) : QDialog(parent), footage_(footage) { QVBoxLayout* layout = new QVBoxLayout(this); layout->addWidget(new QLabel("The following files couldn't be found. Clips using them will be " "unplayable until they're relinked.")); table_ = new QTreeWidget(); table_->setColumnCount(3); table_->setHeaderLabels({tr("Footage"), tr("Filename"), tr("Actions")}); table_->setRootIsDecorated(false); table_->setSelectionBehavior(QAbstractItemView::SelectRows); table_->header()->setSectionsMovable(false); // Prefer stretching URL column (QHeaderView defaults to stretching the last column, which in // our case is just a browse button) table_->header()->setSectionResizeMode(1, QHeaderView::Stretch); table_->header()->setStretchLastSection(false); for (int i=0; i<footage.size(); i++) { Footage* f = footage.at(i); QTreeWidgetItem* item = new QTreeWidgetItem(); QWidget* item_actions = new QWidget(); QHBoxLayout* item_actions_layout = new QHBoxLayout(item_actions); QPushButton* item_browse_btn = new QPushButton(tr("Browse")); item_browse_btn->setProperty("index", i); connect(item_browse_btn, &QPushButton::clicked, this, &FootageRelinkDialog::BrowseForFootage); item_actions_layout->addWidget(item_browse_btn); item->setIcon(0, f->data(Node::ICON).value<QIcon>()); item->setText(0, f->GetLabel()); item->setText(1, f->filename()); table_->addTopLevelItem(item); table_->setItemWidget(item, 2, item_actions); } layout->addWidget(table_); QDialogButtonBox* buttons = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); connect(buttons, &QDialogButtonBox::accepted, this, &FootageRelinkDialog::accept); connect(buttons, &QDialogButtonBox::rejected, this, &FootageRelinkDialog::reject); layout->addWidget(buttons); setWindowTitle(tr("Relink Footage")); } void FootageRelinkDialog::UpdateFootageItem(int index) { Footage* f = footage_.at(index); QTreeWidgetItem* item = table_->topLevelItem(index); item->setIcon(0, f->data(Node::ICON).value<QIcon>()); item->setText(1, f->filename()); } void FootageRelinkDialog::BrowseForFootage() { int index = sender()->property("index").toInt(); Footage* f = footage_.at(index); QFileInfo info(f->filename()); QString new_fn = QFileDialog::getOpenFileName(this, tr("Relink \"%1\"").arg(f->GetLabel()), info.absolutePath()); // Originally, this function would attempt to filter to the exact filename of the missing file. // However, this would break on Windows if the filename had any spaces in it. The reason is // Windows separates its extensions with ';' while Qt separates them with ' '. Qt isn't // intelligent enough to determine whether it's a list of extensions or a single filename with a // space in it, it just does a global replace of ' ' to ';'. There's no way around it, outside of // bypassing Qt entirely and using Win32's GetOpenFileName() directly. As annoying as it is, I've // just disabled it for now. //QStringLiteral("%1 (\"%1\");;%2 (*)").arg(info.fileName(), tr("All Files"))); // We received a new filename if (!new_fn.isEmpty()) { // Store original dir since we might be able to use this to find other files QDir original_dir = info.dir(); QDir new_dir = QFileInfo(new_fn).dir(); // Set new filename since this was set manually by the user f->set_filename(new_fn); // Assume footage is valid here. We could do some decoder probing to ensure it's a usable file // but otherwise we assume the user knows what they're doing here. // Set footage to valid and update icon f->SetValid(); // Update item visually UpdateFootageItem(index); // Check all other footage files for matches for (int it=0; it<footage_.size(); it++) { Footage* other_footage = footage_.at(it); // Ignore current footage file and footage that's already valid of course if (index != it && !other_footage->IsValid()) { // Get footage path relative to original directory QString relative_to_original = original_dir.relativeFilePath(other_footage->filename()); QString absolute_to_new = new_dir.filePath(relative_to_original); // Second attempt. Try appending the filename to our new filepath if (!QFileInfo::exists(absolute_to_new)) { QFileInfo file_info(other_footage->filename()); absolute_to_new = new_dir.filePath(file_info.fileName()); } // Check if file exists if (QFileInfo::exists(absolute_to_new)) { other_footage->set_filename(absolute_to_new); other_footage->SetValid(); UpdateFootageItem(it); } } } } // Check where the next invalid footage is. If there is none, accept automatically. Otherwise, // jump to that footage so the user knows where it is. int next_invalid = -1; for (int i=0; i<footage_.size(); i++) { if (!footage_.at(i)->IsValid()) { next_invalid = i; break; } } if (next_invalid == -1) { // No more invalid footage, just accept this->accept(); } else { // Jump to next invalid footage QModelIndex idx = table_->model()->index(next_invalid, 0); table_->selectionModel()->select(idx, QItemSelectionModel::Select | QItemSelectionModel::Rows); table_->scrollTo(idx); } } }
6,560
C++
.cpp
142
40.795775
100
0.690764
olive-editor/olive
8,144
552
131
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
19,107
markerpropertiesdialog.cpp
olive-editor_olive/app/dialog/markerproperties/markerpropertiesdialog.cpp
/*** Olive - Non-Linear Video Editor Copyright (C) 2022 Olive Team 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 <http://www.gnu.org/licenses/>. ***/ #include "markerpropertiesdialog.h" #include <QDialogButtonBox> #include <QGridLayout> #include <QGroupBox> #include <QLabel> #include <QMessageBox> #include "core.h" namespace olive { #define super QDialog MarkerPropertiesDialog::MarkerPropertiesDialog(const std::vector<TimelineMarker *> &markers, const rational &timebase, QWidget *parent) : super(parent), markers_(markers) { QGridLayout *layout = new QGridLayout(this); int row = 0; QGroupBox *time_group = new QGroupBox(tr("Time")); QGridLayout *time_layout = new QGridLayout(time_group); { int time_row = 0; time_layout->addWidget(new QLabel(tr("In:")), time_row, 0); in_slider_ = new RationalSlider(); time_layout->addWidget(in_slider_, time_row, 1); time_row++; time_layout->addWidget(new QLabel(tr("Out:")), time_row, 0); out_slider_ = new RationalSlider(); time_layout->addWidget(out_slider_, time_row, 1); } if (markers.size() == 1) { in_slider_->SetValue(markers.front()->time().in()); in_slider_->SetDisplayType(RationalSlider::kTime); in_slider_->SetTimebase(timebase); out_slider_->SetValue(markers.front()->time().out()); out_slider_->SetDisplayType(RationalSlider::kTime); out_slider_->SetTimebase(timebase); } else { // Markers cannot be on the same time, so we disable setting time if multiple markers are selected in_slider_->setEnabled(false); in_slider_->SetTristate(); out_slider_->setEnabled(false); out_slider_->SetTristate(); } layout->addWidget(time_group, row, 0, 1, 2); row++; layout->addWidget(new QLabel(tr("Color:")), row, 0); color_menu_ = new ColorCodingComboBox(); layout->addWidget(color_menu_, row, 1); color_menu_->SetColor(markers.front()->color()); for (size_t i=1; i<markers.size(); i++) { if (markers.at(i)->color() != color_menu_->GetSelectedColor()) { color_menu_->SetColor(-1); break; } } row++; layout->addWidget(new QLabel(tr("Name:")), row, 0); label_edit_ = new LineEditWithFocusSignal(); connect(label_edit_, &LineEditWithFocusSignal::Focused, this, [this]{ label_edit_->setPlaceholderText(QString()); }); layout->addWidget(label_edit_, row, 1); // Determine what the startup label text should be label_edit_->setText(markers.front()->name()); for (size_t i=1; i<markers.size(); i++) { if (markers.at(i)->name() != label_edit_->text()) { label_edit_->clear(); label_edit_->setPlaceholderText(tr("(multiple)")); break; } } row++; QDialogButtonBox *buttons = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); connect(buttons, &QDialogButtonBox::accepted, this, &MarkerPropertiesDialog::accept); connect(buttons, &QDialogButtonBox::rejected, this, &MarkerPropertiesDialog::reject); layout->addWidget(buttons, row, 0, 1, 2); setWindowTitle(tr("Edit Markers")); label_edit_->setFocus(); } void MarkerPropertiesDialog::accept() { if (in_slider_->isEnabled() && in_slider_->GetValue() > out_slider_->GetValue()) { QMessageBox::critical(this, tr("Invalid Values"), tr("In point must be less than or equal to out point.")); return; } MultiUndoCommand *command = new MultiUndoCommand(); int color = color_menu_->GetSelectedColor(); foreach (TimelineMarker *m, markers_) { if (color != -1) { command->add_child(new MarkerChangeColorCommand(m, color)); } if (label_edit_->placeholderText().isEmpty()) { command->add_child(new MarkerChangeNameCommand(m, label_edit_->text())); } } if (markers_.size() == 1) { command->add_child(new MarkerChangeTimeCommand(markers_.front(), TimeRange(in_slider_->GetValue(), out_slider_->GetValue()))); } Core::instance()->undo_stack()->push(command, tr("Set Marker Properties")); super::accept(); } }
4,549
C++
.cpp
114
36.070175
137
0.69868
olive-editor/olive
8,144
552
131
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
19,108
keyframeproperties.cpp
olive-editor_olive/app/dialog/keyframeproperties/keyframeproperties.cpp
/*** Olive - Non-Linear Video Editor Copyright (C) 2022 Olive Team 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 <http://www.gnu.org/licenses/>. ***/ #include "keyframeproperties.h" #include <QDialogButtonBox> #include <QGridLayout> #include "core.h" #include "node/nodeundo.h" #include "widget/keyframeview/keyframeviewundo.h" namespace olive { KeyframePropertiesDialog::KeyframePropertiesDialog(const std::vector<NodeKeyframe*> &keys, const rational &timebase, QWidget *parent) : QDialog(parent), keys_(keys), timebase_(timebase) { setWindowTitle(tr("Keyframe Properties")); QGridLayout* layout = new QGridLayout(this); int row = 0; layout->addWidget(new QLabel("Time:"), row, 0); time_slider_ = new RationalSlider(); time_slider_->SetDisplayType(RationalSlider::kTime); time_slider_->SetTimebase(timebase_); layout->addWidget(time_slider_, row, 1); row++; layout->addWidget(new QLabel("Type:"), row, 0); type_select_ = new QComboBox(); connect(type_select_, SIGNAL(currentIndexChanged(int)), this, SLOT(KeyTypeChanged(int))); layout->addWidget(type_select_, row, 1); row++; // Bezier handles bezier_group_ = new QGroupBox(); QGridLayout* bezier_group_layout = new QGridLayout(bezier_group_); bezier_group_layout->addWidget(new QLabel(tr("In:")), 0, 0); bezier_in_x_slider_ = new FloatSlider(); bezier_group_layout->addWidget(bezier_in_x_slider_, 0, 1); bezier_in_y_slider_ = new FloatSlider(); bezier_group_layout->addWidget(bezier_in_y_slider_, 0, 2); bezier_group_layout->addWidget(new QLabel(tr("Out:")), 1, 0); bezier_out_x_slider_ = new FloatSlider(); bezier_group_layout->addWidget(bezier_out_x_slider_, 1, 1); bezier_out_y_slider_ = new FloatSlider(); bezier_group_layout->addWidget(bezier_out_y_slider_, 1, 2); layout->addWidget(bezier_group_, row, 0, 1, 2); bool all_same_time = true; bool can_set_time = true; bool all_same_type = true; bool all_same_bezier_in_x = true; bool all_same_bezier_in_y = true; bool all_same_bezier_out_x = true; bool all_same_bezier_out_y = true; for (size_t i=0;i<keys_.size();i++) { if (i > 0) { NodeKeyframe* prev_key = keys_.at(i-1); NodeKeyframe* this_key = keys_.at(i); // Determine if the keyframes are all the same time or not if (all_same_time) { all_same_time = (prev_key->time() == this_key->time()); } // Determine if the keyframes are all the same type if (all_same_type) { all_same_type = (prev_key->type() == this_key->type()); } // Check all four bezier control points if (all_same_bezier_in_x) { all_same_bezier_in_x = (prev_key->bezier_control_in().x() == this_key->bezier_control_in().x()); } if (all_same_bezier_in_y) { all_same_bezier_in_y = (prev_key->bezier_control_in().y() == this_key->bezier_control_in().y()); } if (all_same_bezier_out_x) { all_same_bezier_out_x = (prev_key->bezier_control_out().x() == this_key->bezier_control_out().x()); } if (all_same_bezier_out_y) { all_same_bezier_out_y = (prev_key->bezier_control_out().y() == this_key->bezier_control_out().y()); } } // Determine if any keyframes are on the same track (in which case we can't set the time) if (can_set_time) { for (size_t j=0;j<keys_.size();j++) { if (i != j && keys_.at(j)->track() == keys_.at(i)->track()) { can_set_time = false; break; } } } if (!all_same_time && !all_same_type && !can_set_time && !all_same_bezier_in_x && !all_same_bezier_in_y && !all_same_bezier_out_x && !all_same_bezier_out_y) { break; } } if (all_same_time) { time_slider_->SetValue(keys_.front()->time()); } else { time_slider_->SetTristate(); } time_slider_->setEnabled(can_set_time); if (!all_same_type) { // If all keyframes aren't the same type, add an empty item type_select_->addItem(QStringLiteral("--"), -1); // Ensure UI updates for the index being 0 KeyTypeChanged(0); } type_select_->addItem(tr("Linear"), NodeKeyframe::kLinear); type_select_->addItem(tr("Hold"), NodeKeyframe::kHold); type_select_->addItem(tr("Bezier"), NodeKeyframe::kBezier); if (all_same_type) { // If all keyframes are the same type, set it here for (int i=0;i<type_select_->count();i++) { if (type_select_->itemData(i).toInt() == keys_.front()->type()) { type_select_->setCurrentIndex(i); // Ensure UI updates for this index KeyTypeChanged(i); break; } } } SetUpBezierSlider(bezier_in_x_slider_, all_same_bezier_in_x, keys_.front()->bezier_control_in().x()); SetUpBezierSlider(bezier_in_y_slider_, all_same_bezier_in_y, keys_.front()->bezier_control_in().y()); SetUpBezierSlider(bezier_out_x_slider_, all_same_bezier_out_x, keys_.front()->bezier_control_out().x()); SetUpBezierSlider(bezier_out_y_slider_, all_same_bezier_out_y, keys_.front()->bezier_control_out().y()); row++; QDialogButtonBox* buttons = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); buttons->setCenterButtons(true); layout->addWidget(buttons, row, 0, 1, 2); connect(buttons, &QDialogButtonBox::accepted, this, &QDialog::accept); connect(buttons, &QDialogButtonBox::rejected, this, &QDialog::reject); } void KeyframePropertiesDialog::accept() { MultiUndoCommand* command = new MultiUndoCommand(); rational new_time = time_slider_->GetValue(); int new_type = type_select_->currentData().toInt(); foreach (NodeKeyframe* key, keys_) { if (time_slider_->isEnabled() && !time_slider_->IsTristate()) { command->add_child(new NodeParamSetKeyframeTimeCommand(key, new_time)); } if (new_type > -1) { command->add_child(new KeyframeSetTypeCommand(key, static_cast<NodeKeyframe::Type>(new_type))); } if (bezier_group_->isEnabled()) { command->add_child(new KeyframeSetBezierControlPoint(key, NodeKeyframe::kInHandle, QPointF(bezier_in_x_slider_->GetValue(), bezier_in_y_slider_->GetValue()))); command->add_child(new KeyframeSetBezierControlPoint(key, NodeKeyframe::kOutHandle, QPointF(bezier_out_x_slider_->GetValue(), bezier_out_y_slider_->GetValue()))); } } Core::instance()->undo_stack()->push(command, tr("Set Keyframe Properties")); QDialog::accept(); } void KeyframePropertiesDialog::SetUpBezierSlider(FloatSlider *slider, bool all_same, double value) { if (all_same) { slider->SetValue(value); } else { slider->SetTristate(); } } void KeyframePropertiesDialog::KeyTypeChanged(int index) { bezier_group_->setEnabled(type_select_->itemData(index) == NodeKeyframe::kBezier); } }
7,595
C++
.cpp
181
36.033149
137
0.651346
olive-editor/olive
8,144
552
131
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
19,109
otiopropertiesdialog.cpp
olive-editor_olive/app/dialog/otioproperties/otiopropertiesdialog.cpp
/*** Olive - Non-Linear Video Editor Copyright (C) 2019 Olive Team 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 <http://www.gnu.org/licenses/>. ***/ #include "otiopropertiesdialog.h" #include <QDialogButtonBox> #include <QFileDialog> #include <QFileInfo> #include <QHeaderView> #include <QLabel> #include <QPushButton> #include <QVBoxLayout> #include "core.h" #include "dialog/sequence/sequence.h" namespace olive { OTIOPropertiesDialog::OTIOPropertiesDialog(const QList<Sequence*>& sequences, Project* active_project, QWidget* parent) : QDialog(parent), sequences_(sequences) { QVBoxLayout* layout = new QVBoxLayout(this); QLabel *msg = new QLabel(tr("OpenTimelineIO files do not store sequence parameters (resolution, frame rate, etc.)\n\n" "Please set the correct parameters on the sequences below (they have been set to your default sequence parameters as a starting point).")); msg->setWordWrap(true); layout->addWidget(msg); table_ = new QTreeWidget(); table_->setColumnCount(2); table_->setHeaderLabels({tr("Sequence"), tr("Actions")}); table_->setRootIsDecorated(false); for (int i = 0; i < sequences.size(); i++) { QTreeWidgetItem* item = new QTreeWidgetItem(); Sequence* s = sequences.at(i); QWidget* item_actions = new QWidget(); QHBoxLayout* item_actions_layout = new QHBoxLayout(item_actions); QPushButton* item_settings_btn = new QPushButton(tr("Settings")); item_settings_btn->setProperty("index", i); connect(item_settings_btn, &QPushButton::clicked, this, &OTIOPropertiesDialog::SetupSequence); item_actions_layout->addWidget(item_settings_btn); item->setText(0, s->GetLabel()); table_->addTopLevelItem(item); table_->setItemWidget(item, 1, item_actions); } // Stretch first column to take up as much space as possible, and second column to take as little table_->header()->setSectionResizeMode(0, QHeaderView::Stretch); table_->header()->setSectionResizeMode(1, QHeaderView::Fixed); table_->header()->setStretchLastSection(false); layout->addWidget(table_); QDialogButtonBox* buttons = new QDialogButtonBox(QDialogButtonBox::Ok|QDialogButtonBox::Cancel); connect(buttons, &QDialogButtonBox::accepted, this, &OTIOPropertiesDialog::accept); connect(buttons, &QDialogButtonBox::rejected, this, &OTIOPropertiesDialog::reject); layout->addWidget(buttons); setWindowTitle(tr("Load OpenTimelineIO Project")); } void OTIOPropertiesDialog::SetupSequence() { int index = sender()->property("index").toInt(); Sequence* s = sequences_.at(index); SequenceDialog sd(s, SequenceDialog::kNew); sd.SetUndoable(false); sd.exec(); } } // namespace olive
3,266
C++
.cpp
71
42.492958
169
0.746302
olive-editor/olive
8,144
552
131
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
19,110
colordialog.cpp
olive-editor_olive/app/dialog/color/colordialog.cpp
/*** Olive - Non-Linear Video Editor Copyright (C) 2022 Olive Team 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 <http://www.gnu.org/licenses/>. ***/ #include "colordialog.h" #include <QDialogButtonBox> #include <QSplitter> #include <QVBoxLayout> #include "common/qtutils.h" namespace olive { ColorDialog::ColorDialog(ColorManager* color_manager, const ManagedColor& start, QWidget *parent) : QDialog(parent), color_manager_(color_manager) { setWindowTitle(tr("Select Color")); QVBoxLayout* layout = new QVBoxLayout(this); QSplitter* splitter = new QSplitter(Qt::Horizontal); splitter->setChildrenCollapsible(false); layout->addWidget(splitter); QWidget* graphics_area = new QWidget(); splitter->addWidget(graphics_area); QVBoxLayout *graphics_layout = new QVBoxLayout(graphics_area); QHBoxLayout* wheel_layout = new QHBoxLayout(); graphics_layout->addLayout(wheel_layout); color_wheel_ = new ColorWheelWidget(); wheel_layout->addWidget(color_wheel_); hsv_value_gradient_ = new ColorGradientWidget(Qt::Vertical); hsv_value_gradient_->setFixedWidth(QtUtils::QFontMetricsWidth(fontMetrics(), QStringLiteral("HHH"))); wheel_layout->addWidget(hsv_value_gradient_); QHBoxLayout *swatch_layout = new QHBoxLayout(); graphics_layout->addLayout(swatch_layout); swatch_layout->addStretch(); swatch_ = new ColorSwatchChooser(color_manager_); swatch_->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Maximum); swatch_layout->addWidget(swatch_); swatch_layout->addStretch(); QWidget* value_area = new QWidget(); QVBoxLayout* value_layout = new QVBoxLayout(value_area); value_layout->setSpacing(0); splitter->addWidget(value_area); color_values_widget_ = new ColorValuesWidget(color_manager_); color_values_widget_->IgnorePickFrom(this); value_layout->addWidget(color_values_widget_); chooser_ = new ColorSpaceChooser(color_manager_); value_layout->addWidget(chooser_); // Split window 50/50 splitter->setSizes({INT_MAX, INT_MAX}); connect(color_wheel_, &ColorWheelWidget::SelectedColorChanged, color_values_widget_, &ColorValuesWidget::SetColor); connect(color_wheel_, &ColorWheelWidget::SelectedColorChanged, hsv_value_gradient_, &ColorGradientWidget::SetSelectedColor); connect(color_wheel_, &ColorWheelWidget::SelectedColorChanged, swatch_, &ColorSwatchChooser::SetCurrentColor); connect(hsv_value_gradient_, &ColorGradientWidget::SelectedColorChanged, color_values_widget_, &ColorValuesWidget::SetColor); connect(hsv_value_gradient_, &ColorGradientWidget::SelectedColorChanged, color_wheel_, &ColorWheelWidget::SetSelectedColor); connect(hsv_value_gradient_, &ColorGradientWidget::SelectedColorChanged, swatch_, &ColorSwatchChooser::SetCurrentColor); connect(color_values_widget_, &ColorValuesWidget::ColorChanged, hsv_value_gradient_, &ColorGradientWidget::SetSelectedColor); connect(color_values_widget_, &ColorValuesWidget::ColorChanged, color_wheel_, &ColorWheelWidget::SetSelectedColor); connect(color_values_widget_, &ColorValuesWidget::ColorChanged, swatch_, &ColorSwatchChooser::SetCurrentColor); connect(swatch_, &ColorSwatchChooser::ColorClicked, hsv_value_gradient_, &ColorGradientWidget::SetSelectedColor); connect(swatch_, &ColorSwatchChooser::ColorClicked, color_wheel_, &ColorWheelWidget::SetSelectedColor); connect(swatch_, &ColorSwatchChooser::ColorClicked, color_values_widget_, &ColorValuesWidget::SetColor); connect(color_wheel_, &ColorWheelWidget::DiameterChanged, hsv_value_gradient_, &ColorGradientWidget::setFixedHeight); QDialogButtonBox* buttons = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); connect(buttons, &QDialogButtonBox::accepted, this, &QDialog::accept); connect(buttons, &QDialogButtonBox::rejected, this, &QDialog::reject); layout->addWidget(buttons); SetColor(start); connect(chooser_, &ColorSpaceChooser::ColorSpaceChanged, this, &ColorDialog::ColorSpaceChanged); ColorSpaceChanged(chooser_->input(), chooser_->output()); // Set default size ratio to 2:1 resize(sizeHint().height() * 2, sizeHint().height()); } void ColorDialog::SetColor(const ManagedColor &start) { chooser_->set_input(start.color_input()); chooser_->set_output(start.color_output()); Color managed_start; if (start.color_input().isEmpty()) { managed_start = start; } else { // Convert reference color to the input space ColorProcessorPtr linear_to_input = ColorProcessor::Create(color_manager_, color_manager_->GetReferenceColorSpace(), start.color_input()); managed_start = linear_to_input->ConvertColor(start); } color_wheel_->SetSelectedColor(managed_start); hsv_value_gradient_->SetSelectedColor(managed_start); color_values_widget_->SetColor(managed_start); swatch_->SetCurrentColor(managed_start); } ManagedColor ColorDialog::GetSelectedColor() const { ManagedColor selected = color_wheel_->GetSelectedColor(); // Convert to linear and return a linear color if (input_to_ref_processor_) { selected = input_to_ref_processor_->ConvertColor(selected); } selected.set_color_input(GetColorSpaceInput()); selected.set_color_output(GetColorSpaceOutput()); return selected; } QString ColorDialog::GetColorSpaceInput() const { return chooser_->input(); } ColorTransform ColorDialog::GetColorSpaceOutput() const { return chooser_->output(); } void ColorDialog::ColorSpaceChanged(const QString &input, const ColorTransform &output) { input_to_ref_processor_ = ColorProcessor::Create(color_manager_, input, color_manager_->GetReferenceColorSpace()); ColorProcessorPtr ref_to_display = ColorProcessor::Create(color_manager_, color_manager_->GetReferenceColorSpace(), output); ColorProcessorPtr ref_to_input = ColorProcessor::Create(color_manager_, color_manager_->GetReferenceColorSpace(), input); // FIXME: For some reason, using OCIO::TRANSFORM_DIR_INVERSE (wrapped by ColorProcessor::kInverse) causes OCIO to // crash. We've disabled that functionality for now (also disabling display_tab_ in ColorValuesWidget) /*ColorProcessorPtr display_to_ref = ColorProcessor::Create(color_manager_->GetConfig(), color_manager_->GetReferenceColorSpace(), display, view, look, ColorProcessor::kInverse);*/ color_wheel_->SetColorProcessor(input_to_ref_processor_, ref_to_display); hsv_value_gradient_->SetColorProcessor(input_to_ref_processor_, ref_to_display); color_values_widget_->SetColorProcessor(input_to_ref_processor_, ref_to_display, nullptr, ref_to_input); } }
7,632
C++
.cpp
138
48.405797
127
0.722581
olive-editor/olive
8,144
552
131
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
19,111
actionsearch.cpp
olive-editor_olive/app/dialog/actionsearch/actionsearch.cpp
/*** Olive - Non-Linear Video Editor Copyright (C) 2019 Olive Team 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 <http://www.gnu.org/licenses/>. ***/ #include "actionsearch.h" #include <QKeyEvent> #include <QLabel> #include <QMenuBar> #include <QVBoxLayout> namespace olive { ActionSearch::ActionSearch(QWidget *parent) : QDialog(parent), menu_bar_(nullptr) { // ActionSearch requires a parent widget Q_ASSERT(parent != nullptr); // Set styling (object name is required for CSS specific to this object) setObjectName("ASDiag"); setStyleSheet("#ASDiag{border: 2px solid #808080;}"); // Size proportionally to the parent (usually MainWindow). resize(parent->width()/3, parent->height()/3); // Show dialog as a "popup", which will make the dialog close if the user clicks out of it. setWindowFlags(Qt::Popup); QVBoxLayout* layout = new QVBoxLayout(this); // Construct the main entry text field. ActionSearchEntry* entry_field = new ActionSearchEntry(this); // Set the main entry field font size to 1.2x its standard font size. QFont entry_field_font = entry_field->font(); entry_field_font.setPointSize(qRound(entry_field_font.pointSize()*1.2)); entry_field->setFont(entry_field_font); // Set placeholder text for the main entry field entry_field->setPlaceholderText(tr("Search for action...")); // Connect signals/slots connect(entry_field, SIGNAL(textChanged(const QString&)), this, SLOT(search_update(const QString &))); connect(entry_field, SIGNAL(returnPressed()), this, SLOT(perform_action())); // moveSelectionUp() and moveSelectionDown() are emitted when the user pressed up or down on the text field. // We override it here to select the upper or lower item in the list. connect(entry_field, SIGNAL(moveSelectionUp()), this, SLOT(move_selection_up())); connect(entry_field, SIGNAL(moveSelectionDown()), this, SLOT(move_selection_down())); layout->addWidget(entry_field); // Construct list of actions list_widget = new ActionSearchList(this); // Set list's font to 1.2x its standard font size QFont list_widget_font = list_widget->font(); list_widget_font.setPointSize(qRound(list_widget_font.pointSize()*1.2)); list_widget->setFont(list_widget_font); layout->addWidget(list_widget); connect(list_widget, SIGNAL(dbl_click()), this, SLOT(perform_action())); // Instantly focus on the entry field to allow for fully keyboard operation (if this popup was initiated by keyboard // shortcut for example). entry_field->setFocus(); } void ActionSearch::SetMenuBar(QMenuBar *menu_bar) { menu_bar_ = menu_bar; } void ActionSearch::search_update(const QString &s, const QString &p, QMenu *parent) { // Do nothing if there's no menu bar to work with if (menu_bar_ == nullptr) { return; } // This function is recursive, using the `parent` parameter to loop through a menu's items. It functions in two // modes - the parent being NULL, meaning it'll get MainWindow's menubar and loop over its menus, and the parent // referring to a menu at which point it'll loop over its actions (and call itself recursively if it finds any // submenus). if (parent == nullptr) { // If parent is NULL, we'll pull from the MainWindow's menubar and call this recursively on all of its submenus // (and their submenus). // We'll clear all the current items in the list since if we're here, we're just starting. list_widget->clear(); QList<QAction*> menus = menu_bar_->actions(); // Loop through all menus from the menubar and run this function on each one. for (int i=0;i<menus.size();i++) { QMenu* menu = menus.at(i)->menu(); search_update(s, p, menu); } // Once we're here, all the recursion/item retrieval is complete. We auto-select the first item for better // keyboard-exclusive functionality. if (list_widget->count() > 0) { list_widget->item(0)->setSelected(true); } } else { // Parent was not NULL, so we loop over the actions in the menu we were given in `parent`. // The list shows a '>' delimited hierarchy of the menus in which this action came from. We construct it here by // adding the current menu's text to the existing hierarchy (passed in `p`). QString menu_text; if (!p.isEmpty()) menu_text += p + " > "; menu_text += parent->title().replace("&", ""); // Strip out any &s used in menu action names // Loop over the menu's actions QList<QAction*> actions = parent->actions(); for (int i=0;i<actions.size();i++) { QAction* a = actions.at(i); // Ignore separator actions if (!a->isSeparator()) { if (a->menu() != nullptr) { // If the action is a menu, run this function recursively on it search_update(s, menu_text, a->menu()); } else { // This is a valid non-separator non-menu action, so check it against the currently entered string. // Strip out all &s from the action's name QString comp = a->text().replace("&", ""); // See if the action's name contains any of the currently entered string if (comp.contains(s, Qt::CaseInsensitive)) { // If so, we add it to the list widget. QListWidgetItem* item = new QListWidgetItem(QStringLiteral("%1\n(%2)").arg(comp, menu_text), list_widget); // Add a pointer to the original QAction in the item's data item->setData(Qt::UserRole+1, reinterpret_cast<quintptr>(a)); list_widget->addItem(item); } } } } } } void ActionSearch::perform_action() { // Loop over all the items in the list and if we find one that's selected, we trigger it. QList<QListWidgetItem*> selected_items = list_widget->selectedItems(); if (list_widget->count() > 0 && selected_items.size() > 0) { QListWidgetItem* item = selected_items.at(0); // Get QAction pointer from item's data QAction* a = reinterpret_cast<QAction*>(item->data(Qt::UserRole+1).value<quintptr>()); a->trigger(); } // Close this popup accept(); } void ActionSearch::move_selection_up() { // Here we loop over all the items to find the currently selected one, and then select the one above it. We start // iterating at 1 (instead of 0) to efficiently ignore the first item (since the selection can't go below the very // bottom item). int lim = list_widget->count(); for (int i=1;i<lim;i++) { if (list_widget->item(i)->isSelected()) { list_widget->item(i-1)->setSelected(true); list_widget->scrollToItem(list_widget->item(i-1)); break; } } } void ActionSearch::move_selection_down() { // Here we loop over all the items to find the currently selected one, and then select the one below it. We limit it // one entry before count() to efficiently ignore the item at the end (since the selection can't go below the very // bottom item). int lim = list_widget->count()-1; for (int i=0;i<lim;i++) { if (list_widget->item(i)->isSelected()) { list_widget->item(i+1)->setSelected(true); list_widget->scrollToItem(list_widget->item(i+1)); break; } } } ActionSearchEntry::ActionSearchEntry(QWidget *parent) : QLineEdit(parent) {} bool ActionSearchEntry::event(QEvent *e) { switch (e->type()) { case QEvent::ShortcutOverride: switch (static_cast<QKeyEvent*>(e)->key()) { case Qt::Key_Up: case Qt::Key_Down: e->accept(); return true; } break; case QEvent::KeyPress: // Listen for up/down, otherwise pass the key event to the base class. switch (static_cast<QKeyEvent*>(e)->key()) { case Qt::Key_Up: e->accept(); emit moveSelectionUp(); return true; case Qt::Key_Down: e->accept(); emit moveSelectionDown(); return true; } break; default: break; } return QLineEdit::event(e); } ActionSearchList::ActionSearchList(QWidget *parent) : QListWidget(parent) {} void ActionSearchList::mouseDoubleClickEvent(QMouseEvent *) { // Indiscriminately emit a signal on any double click emit dbl_click(); } }
8,698
C++
.cpp
199
39.140704
118
0.692655
olive-editor/olive
8,144
552
131
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
19,112
footageproperties.cpp
olive-editor_olive/app/dialog/footageproperties/footageproperties.cpp
/*** Olive - Non-Linear Video Editor Copyright (C) 2020 Olive Team 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 <http://www.gnu.org/licenses/>. ***/ #include "footageproperties.h" #include <QGridLayout> #include <QLabel> #include <QComboBox> #include <QLineEdit> #include <QDialogButtonBox> #include <QTreeWidgetItem> #include <QGroupBox> #include <QListWidget> #include <QCheckBox> #include <QSpinBox> #include "core.h" #include "node/nodeundo.h" #include "streamproperties/audiostreamproperties.h" #include "streamproperties/videostreamproperties.h" namespace olive { FootagePropertiesDialog::FootagePropertiesDialog(QWidget *parent, Footage *footage) : QDialog(parent), footage_(footage) { QGridLayout* layout = new QGridLayout(this); setWindowTitle(tr("\"%1\" Properties").arg(footage_->GetLabelOrName())); setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); int row = 0; layout->addWidget(new QLabel(tr("Name:")), row, 0); footage_name_field_ = new QLineEdit(footage_->GetLabel()); layout->addWidget(footage_name_field_, row, 1); row++; layout->addWidget(new QLabel(tr("Tracks:")), row, 0, 1, 2); row++; track_list = new QListWidget(); layout->addWidget(track_list, row, 0, 1, 2); row++; stacked_widget_ = new QStackedWidget(); layout->addWidget(stacked_widget_, row, 0, 1, 2); int first_usable_stream = -1; for (int i=0; i<footage_->GetTotalStreamCount(); i++) { Track::Reference reference = footage_->GetReferenceFromRealIndex(i); QString description; bool is_enabled = false; switch (reference.type()) { case Track::kVideo: { stacked_widget_->addWidget(new VideoStreamProperties(footage_, reference.index())); VideoParams vp = footage_->GetVideoParams(reference.index()); is_enabled = vp.enabled(); description = Footage::DescribeVideoStream(vp); break; } case Track::kAudio: { stacked_widget_->addWidget(new AudioStreamProperties(footage_, reference.index())); AudioParams ap = footage_->GetAudioParams(reference.index()); is_enabled = ap.enabled(); description = Footage::DescribeAudioStream(ap); break; } case Track::kSubtitle: { SubtitleParams sp = footage_->GetSubtitleParams(reference.index()); is_enabled = sp.enabled(); // FIXME: Language? description = tr("Subtitles"); break; } default: stacked_widget_->addWidget(new StreamProperties()); description = tr("Unknown"); break; } QListWidgetItem* item = new QListWidgetItem(description, track_list); item->setFlags(item->flags() | Qt::ItemIsUserCheckable); item->setCheckState(is_enabled ? Qt::Checked : Qt::Unchecked); track_list->addItem(item); if (first_usable_stream == -1 && (reference.type() == Track::kVideo || reference.type() == Track::kAudio || reference.type() == Track::kSubtitle)) { first_usable_stream = i; } } row++; QDialogButtonBox* buttons = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); buttons->setCenterButtons(true); layout->addWidget(buttons, row, 0, 1, 2); connect(buttons, &QDialogButtonBox::accepted, this, &QDialog::accept); connect(buttons, &QDialogButtonBox::rejected, this, &QDialog::reject); connect(track_list, &QListWidget::currentRowChanged, stacked_widget_, &QStackedWidget::setCurrentIndex); // Auto-select first item that actually has properties if (first_usable_stream >= 0) { track_list->setCurrentRow(first_usable_stream); } track_list->setFocus(); } void FootagePropertiesDialog::accept() { // Perform sanity check on all pages for (int i=0;i<stacked_widget_->count();i++) { if (!static_cast<StreamProperties*>(stacked_widget_->widget(i))->SanityCheck()) { // Switch to the failed panel in question stacked_widget_->setCurrentIndex(i); // Do nothing (it's up to the property panel itself to throw the error message) return; } } MultiUndoCommand* command = new MultiUndoCommand(); if (footage_->GetLabel() != footage_name_field_->text()) { NodeRenameCommand *nrc = new NodeRenameCommand(); nrc->AddNode(footage_, footage_name_field_->text()); command->add_child(nrc); } for (int i=0; i<footage_->GetTotalStreamCount(); i++) { Track::Reference reference = footage_->GetReferenceFromRealIndex(i); bool new_stream_enabled = (track_list->item(i)->checkState() == Qt::Checked); bool old_stream_enabled = new_stream_enabled; switch (reference.type()) { case Track::kVideo: old_stream_enabled = footage_->GetVideoParams(reference.index()).enabled(); break; case Track::kAudio: old_stream_enabled = footage_->GetAudioParams(reference.index()).enabled(); break; case Track::kSubtitle: old_stream_enabled = footage_->GetSubtitleParams(reference.index()).enabled(); break; case Track::kNone: case Track::kCount: break; } if (old_stream_enabled != new_stream_enabled) { command->add_child(new StreamEnableChangeCommand(footage_, reference.type(), reference.index(), new_stream_enabled)); } } for (int i=0;i<stacked_widget_->count();i++) { static_cast<StreamProperties*>(stacked_widget_->widget(i))->Accept(command); } Core::instance()->undo_stack()->push(command, tr("Set Footage \"%1\" Properties").arg(footage_->GetLabel())); QDialog::accept(); } FootagePropertiesDialog::StreamEnableChangeCommand::StreamEnableChangeCommand(Footage *footage, Track::Type type, int index_in_type, bool enabled) : footage_(footage), type_(type), index_(index_in_type), new_enabled_(enabled) { } Project *FootagePropertiesDialog::StreamEnableChangeCommand::GetRelevantProject() const { return footage_->project(); } void FootagePropertiesDialog::StreamEnableChangeCommand::redo() { switch (type_) { case Track::kVideo: { VideoParams vp = footage_->GetVideoParams(index_); old_enabled_ = vp.enabled(); vp.set_enabled(new_enabled_); footage_->SetVideoParams(vp, index_); break; } case Track::kAudio: { AudioParams ap = footage_->GetAudioParams(index_); old_enabled_ = ap.enabled(); ap.set_enabled(new_enabled_); footage_->SetAudioParams(ap, index_); break; } case Track::kSubtitle: { SubtitleParams sp = footage_->GetSubtitleParams(index_); old_enabled_ = sp.enabled(); sp.set_enabled(new_enabled_); footage_->SetSubtitleParams(sp, index_); break; } case Track::kNone: case Track::kCount: break; } } void FootagePropertiesDialog::StreamEnableChangeCommand::undo() { switch (type_) { case Track::kVideo: { VideoParams vp = footage_->GetVideoParams(index_); vp.set_enabled(old_enabled_); footage_->SetVideoParams(vp, index_); break; } case Track::kAudio: { AudioParams ap = footage_->GetAudioParams(index_); ap.set_enabled(old_enabled_); footage_->SetAudioParams(ap, index_); break; } case Track::kSubtitle: { SubtitleParams sp = footage_->GetSubtitleParams(index_); sp.set_enabled(old_enabled_); footage_->SetSubtitleParams(sp, index_); break; } case Track::kNone: case Track::kCount: break; } } }
8,018
C++
.cpp
229
30.179039
148
0.686515
olive-editor/olive
8,144
552
131
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
19,113
videostreamproperties.cpp
olive-editor_olive/app/dialog/footageproperties/streamproperties/videostreamproperties.cpp
/*** Olive - Non-Linear Video Editor Copyright (C) 2020 Olive Team 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 <http://www.gnu.org/licenses/>. ***/ #include "videostreamproperties.h" #include <QGridLayout> #include <QGroupBox> #include <QInputDialog> #include <QLabel> #include <QMessageBox> #include "common/ocioutils.h" #include "core.h" #include "undo/undostack.h" namespace olive { VideoStreamProperties::VideoStreamProperties(Footage *footage, int video_index) : footage_(footage), video_index_(video_index), video_premultiply_alpha_(nullptr) { QGridLayout* video_layout = new QGridLayout(this); video_layout->setContentsMargins(0, 0, 0, 0); int row = 0; video_layout->addWidget(new QLabel(tr("Pixel Aspect:")), row, 0); VideoParams vp = footage_->GetVideoParams(video_index_); pixel_aspect_combo_ = new PixelAspectRatioComboBox(); pixel_aspect_combo_->SetPixelAspectRatio(vp.pixel_aspect_ratio()); video_layout->addWidget(pixel_aspect_combo_, row, 1); row++; video_layout->addWidget(new QLabel(tr("Interlacing:")), row, 0); video_interlace_combo_ = new InterlacedComboBox(); video_interlace_combo_->SetInterlaceMode(vp.interlacing()); video_layout->addWidget(video_interlace_combo_, row, 1); row++; video_layout->addWidget(new QLabel(tr("Color Space:")), row, 0); video_color_space_ = new QComboBox(); OCIO::ConstConfigRcPtr config = footage_->project()->color_manager()->GetConfig(); int number_of_colorspaces = config->getNumColorSpaces(); video_color_space_->addItem(tr("Default (%1)").arg(footage_->project()->color_manager()->GetDefaultInputColorSpace())); for (int i=0;i<number_of_colorspaces;i++) { QString colorspace = config->getColorSpaceNameByIndex(i); video_color_space_->addItem(colorspace); } video_color_space_->setCurrentText(vp.colorspace()); video_layout->addWidget(video_color_space_, row, 1); row++; video_layout->addWidget(new QLabel(tr("Color Range:")), row, 0); color_range_combo_ = new QComboBox(); color_range_combo_->addItem(tr("Limited (16-235)"), VideoParams::kColorRangeLimited); color_range_combo_->addItem(tr("Full (0-255)"), VideoParams::kColorRangeFull); color_range_combo_->setCurrentIndex(vp.color_range()); video_layout->addWidget(color_range_combo_, row, 1); if (vp.channel_count() == VideoParams::kRGBAChannelCount) { row++; video_premultiply_alpha_ = new QCheckBox(tr("Premultiplied Alpha")); video_premultiply_alpha_->setChecked(vp.premultiplied_alpha()); video_layout->addWidget(video_premultiply_alpha_, row, 0, 1, 2); } row++; if (vp.video_type() == VideoParams::kVideoTypeImageSequence) { QGroupBox* imgseq_group = new QGroupBox(tr("Image Sequence")); QGridLayout* imgseq_layout = new QGridLayout(imgseq_group); int imgseq_row = 0; imgseq_layout->addWidget(new QLabel(tr("Start Index:")), imgseq_row, 0); imgseq_start_time_ = new IntegerSlider(); imgseq_start_time_->SetMinimum(0); imgseq_start_time_->SetValue(vp.start_time()); imgseq_layout->addWidget(imgseq_start_time_, imgseq_row, 1); imgseq_row++; imgseq_layout->addWidget(new QLabel(tr("End Index:")), imgseq_row, 0); imgseq_end_time_ = new IntegerSlider(); imgseq_end_time_->SetMinimum(0); imgseq_end_time_->SetValue(vp.start_time() + vp.duration() - 1); imgseq_layout->addWidget(imgseq_end_time_, imgseq_row, 1); imgseq_row++; imgseq_layout->addWidget(new QLabel(tr("Frame Rate:")), imgseq_row, 0); imgseq_frame_rate_ = new FrameRateComboBox(); imgseq_frame_rate_->SetFrameRate(vp.frame_rate()); imgseq_layout->addWidget(imgseq_frame_rate_, imgseq_row, 1); video_layout->addWidget(imgseq_group, row, 0, 1, 2); } } void VideoStreamProperties::Accept(MultiUndoCommand *parent) { QString set_colorspace; if (video_color_space_->currentIndex() > 0) { set_colorspace = video_color_space_->currentText(); } VideoParams vp = footage_->GetVideoParams(video_index_); if ((video_premultiply_alpha_ && video_premultiply_alpha_->isChecked() != vp.premultiplied_alpha()) || set_colorspace != vp.colorspace() || static_cast<VideoParams::Interlacing>(video_interlace_combo_->currentIndex()) != vp.interlacing() || pixel_aspect_combo_->GetPixelAspectRatio() != vp.pixel_aspect_ratio() || color_range_combo_->currentData().toInt() != vp.color_range()) { parent->add_child(new VideoStreamChangeCommand(footage_, video_index_, video_premultiply_alpha_ ? video_premultiply_alpha_->isChecked() : vp.premultiplied_alpha(), set_colorspace, static_cast<VideoParams::Interlacing>(video_interlace_combo_->currentIndex()), pixel_aspect_combo_->GetPixelAspectRatio(), static_cast<VideoParams::ColorRange>(color_range_combo_->currentData().toInt()))); } if (vp.video_type() == VideoParams::kVideoTypeImageSequence) { int64_t new_dur = imgseq_end_time_->GetValue() - imgseq_start_time_->GetValue() + 1; if (vp.start_time() != imgseq_start_time_->GetValue() || vp.duration() != new_dur || vp.frame_rate() != imgseq_frame_rate_->GetFrameRate()) { parent->add_child(new ImageSequenceChangeCommand(footage_, video_index_, imgseq_start_time_->GetValue(), new_dur, imgseq_frame_rate_->GetFrameRate())); } } } bool VideoStreamProperties::SanityCheck() { if (footage_->GetVideoParams(video_index_).video_type() == VideoParams::kVideoTypeImageSequence) { if (imgseq_start_time_->GetValue() >= imgseq_end_time_->GetValue()) { QMessageBox::critical(this, tr("Invalid Configuration"), tr("Image sequence end index must be a value higher than the start index."), QMessageBox::Ok); return false; } } return true; } VideoStreamProperties::VideoStreamChangeCommand::VideoStreamChangeCommand(Footage *footage, int video_index, bool premultiplied, QString colorspace, VideoParams::Interlacing interlacing, const rational &pixel_ar, VideoParams::ColorRange range) : footage_(footage), video_index_(video_index), new_premultiplied_(premultiplied), new_colorspace_(colorspace), new_interlacing_(interlacing), new_pixel_ar_(pixel_ar), new_range_(range) { } Project *VideoStreamProperties::VideoStreamChangeCommand::GetRelevantProject() const { return footage_->project(); } void VideoStreamProperties::VideoStreamChangeCommand::redo() { VideoParams vp = footage_->GetVideoParams(video_index_); old_premultiplied_ = vp.premultiplied_alpha(); old_colorspace_ = vp.colorspace(); old_interlacing_ = vp.interlacing(); old_pixel_ar_ = vp.pixel_aspect_ratio(); old_range_ = vp.color_range(); vp.set_premultiplied_alpha(new_premultiplied_); vp.set_colorspace(new_colorspace_); vp.set_interlacing(new_interlacing_); vp.set_pixel_aspect_ratio(new_pixel_ar_); vp.set_color_range(new_range_); footage_->SetVideoParams(vp, video_index_); } void VideoStreamProperties::VideoStreamChangeCommand::undo() { VideoParams vp = footage_->GetVideoParams(video_index_); vp.set_premultiplied_alpha(old_premultiplied_); vp.set_colorspace(old_colorspace_); vp.set_interlacing(old_interlacing_); vp.set_pixel_aspect_ratio(old_pixel_ar_); vp.set_color_range(old_range_); footage_->SetVideoParams(vp, video_index_); } VideoStreamProperties::ImageSequenceChangeCommand::ImageSequenceChangeCommand(Footage *footage, int video_index, int64_t start_index, int64_t duration, const rational &frame_rate) : footage_(footage), video_index_(video_index), new_start_index_(start_index), new_duration_(duration), new_frame_rate_(frame_rate) { } Project *VideoStreamProperties::ImageSequenceChangeCommand::GetRelevantProject() const { return footage_->project(); } void VideoStreamProperties::ImageSequenceChangeCommand::redo() { VideoParams vp = footage_->GetVideoParams(video_index_); old_start_index_ = vp.start_time(); vp.set_start_time(new_start_index_); old_duration_ = vp.duration(); vp.set_duration(new_duration_); old_frame_rate_ = vp.frame_rate(); vp.set_frame_rate(new_frame_rate_); vp.set_time_base(new_frame_rate_.flipped()); footage_->SetVideoParams(vp, video_index_); } void VideoStreamProperties::ImageSequenceChangeCommand::undo() { VideoParams vp = footage_->GetVideoParams(video_index_); vp.set_start_time(old_start_index_); vp.set_duration(old_duration_); vp.set_frame_rate(old_frame_rate_); vp.set_time_base(old_frame_rate_.flipped()); footage_->SetVideoParams(vp, video_index_); } }
10,016
C++
.cpp
215
38.790698
181
0.661081
olive-editor/olive
8,144
552
131
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
19,114
audiostreamproperties.cpp
olive-editor_olive/app/dialog/footageproperties/streamproperties/audiostreamproperties.cpp
/*** Olive - Non-Linear Video Editor Copyright (C) 2020 Olive Team 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 <http://www.gnu.org/licenses/>. ***/ #include "audiostreamproperties.h" namespace olive { AudioStreamProperties::AudioStreamProperties(Footage *footage, int audio_index) : footage_(footage), audio_index_(audio_index) { } void AudioStreamProperties::Accept(MultiUndoCommand*) { Q_UNUSED(footage_) Q_UNUSED(audio_index_) } }
1,010
C++
.cpp
27
34.851852
81
0.779034
olive-editor/olive
8,144
552
131
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
19,115
streamproperties.cpp
olive-editor_olive/app/dialog/footageproperties/streamproperties/streamproperties.cpp
/*** Olive - Non-Linear Video Editor Copyright (C) 2020 Olive Team 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 <http://www.gnu.org/licenses/>. ***/ #include "streamproperties.h" namespace olive { StreamProperties::StreamProperties(QWidget *parent) : QWidget(parent) { } }
841
C++
.cpp
21
37.380952
71
0.776819
olive-editor/olive
8,144
552
131
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
19,116
rendercancel.cpp
olive-editor_olive/app/dialog/rendercancel/rendercancel.cpp
/*** Olive - Non-Linear Video Editor Copyright (C) 2022 Olive Team 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 <http://www.gnu.org/licenses/>. ***/ #include "rendercancel.h" namespace olive { RenderCancelDialog::RenderCancelDialog(QWidget *parent) : ProgressDialog(tr("Waiting for workers to finish..."), tr("Renderer"), parent), busy_workers_(0), total_workers_(0) { } void RenderCancelDialog::RunIfWorkersAreBusy() { if (busy_workers_ > 0) { waiting_workers_ = busy_workers_; exec(); } } void RenderCancelDialog::SetWorkerCount(int count) { total_workers_ = count; UpdateProgress(); } void RenderCancelDialog::WorkerStarted() { busy_workers_++; UpdateProgress(); } void RenderCancelDialog::WorkerDone() { busy_workers_--; UpdateProgress(); } void RenderCancelDialog::showEvent(QShowEvent *event) { QDialog::showEvent(event); UpdateProgress(); } void RenderCancelDialog::UpdateProgress() { if (!total_workers_ || !isVisible()) { return; } SetProgress(qRound(100.0 * static_cast<double>(waiting_workers_ - busy_workers_) / static_cast<double>(waiting_workers_))); if (busy_workers_ == 0) { accept(); } } }
1,740
C++
.cpp
60
26.333333
125
0.744565
olive-editor/olive
8,144
552
131
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
19,117
preferences.cpp
olive-editor_olive/app/dialog/preferences/preferences.cpp
/*** Olive - Non-Linear Video Editor Copyright (C) 2022 Olive Team 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 <http://www.gnu.org/licenses/>. ***/ #include "preferences.h" #include <QDialogButtonBox> #include <QListWidget> #include <QSplitter> #include <QVBoxLayout> #include "config/config.h" #include "tabs/preferencesgeneraltab.h" #include "tabs/preferencesbehaviortab.h" #include "tabs/preferencesappearancetab.h" #include "tabs/preferencesdisktab.h" #include "tabs/preferencesaudiotab.h" #include "tabs/preferenceskeyboardtab.h" #include "window/mainwindow/mainwindow.h" namespace olive { PreferencesDialog::PreferencesDialog(MainWindow *main_window) : ConfigDialogBase(main_window) { setWindowTitle(tr("Preferences")); AddTab(new PreferencesGeneralTab(), tr("General")); AddTab(new PreferencesAppearanceTab(), tr("Appearance")); AddTab(new PreferencesBehaviorTab(), tr("Behavior")); AddTab(new PreferencesDiskTab(), tr("Disk")); AddTab(new PreferencesAudioTab(), tr("Audio")); AddTab(new PreferencesKeyboardTab(main_window), tr("Keyboard")); } void PreferencesDialog::AcceptEvent() { Config::Save(); } }
1,700
C++
.cpp
44
36.386364
71
0.783323
olive-editor/olive
8,144
552
131
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
19,118
keysequenceeditor.cpp
olive-editor_olive/app/dialog/preferences/keysequenceeditor.cpp
/*** Olive - Non-Linear Video Editor Copyright (C) 2022 Olive Team 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 <http://www.gnu.org/licenses/>. ***/ #include "keysequenceeditor.h" #include <QAction> #include <QKeyEvent> namespace olive { #define super QKeySequenceEdit KeySequenceEditor::KeySequenceEditor(QWidget* parent, QAction* a) : super(parent), action(a) { setKeySequence(action->shortcut()); } void KeySequenceEditor::set_action_shortcut() { action->setShortcut(keySequence()); } void KeySequenceEditor::reset_to_default() { setKeySequence(action->property("keydefault").toString()); } QString KeySequenceEditor::action_name() { return action->property("id").toString(); } QString KeySequenceEditor::export_shortcut() { QKeySequence ks = keySequence(); if (ks != action->property("keydefault").value<QKeySequence>()) { return action->property("id").toString() + "\t" + ks.toString(); } return nullptr; } void KeySequenceEditor::keyPressEvent(QKeyEvent *e) { if (e->key() == Qt::Key_Backspace) { clear(); } else if (e->key() == Qt::Key_Escape) { e->ignore(); } else{ super::keyPressEvent(e); } } void KeySequenceEditor::keyReleaseEvent(QKeyEvent *e) { if (e->key() == Qt::Key_Backspace) { // Do nothing } else if (e->key() == Qt::Key_Escape) { e->ignore(); } else { super::keyReleaseEvent(e); } } }
1,942
C++
.cpp
60
29.65
71
0.724933
olive-editor/olive
8,144
552
131
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
19,119
preferencesappearancetab.cpp
olive-editor_olive/app/dialog/preferences/tabs/preferencesappearancetab.cpp
/*** Olive - Non-Linear Video Editor Copyright (C) 2022 Olive Team 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 <http://www.gnu.org/licenses/>. ***/ #include "preferencesappearancetab.h" #include <QColorDialog> #include <QFileDialog> #include <QGridLayout> #include <QGroupBox> #include <QLabel> #include "node/node.h" #include "widget/colorbutton/colorbutton.h" #include "widget/menu/menushared.h" #include "ui/colorcoding.h" namespace olive { PreferencesAppearanceTab::PreferencesAppearanceTab() { QVBoxLayout* layout = new QVBoxLayout(this); QGridLayout* appearance_layout = new QGridLayout(); layout->addLayout(appearance_layout); int row = 0; // Appearance -> Theme appearance_layout->addWidget(new QLabel(tr("Theme")), row, 0); style_combobox_ = new QComboBox(); { const QMap<QString, QString>& themes = StyleManager::available_themes(); QMap<QString, QString>::const_iterator i; for (i=themes.cbegin(); i!=themes.cend(); i++) { style_combobox_->addItem(i.value(), i.key()); if (StyleManager::GetStyle() == i.key()) { style_combobox_->setCurrentIndex(style_combobox_->count()-1); } } } appearance_layout->addWidget(style_combobox_, row, 1); row++; { QGroupBox* color_group = new QGroupBox(); color_group->setTitle(tr("Default Node Colors")); QGridLayout* color_layout = new QGridLayout(color_group); for (int i=0; i<Node::kCategoryCount; i++) { QString cat_name = Node::GetCategoryName(static_cast<Node::CategoryID>(i)); color_layout->addWidget(new QLabel(cat_name), i, 0); ColorCodingComboBox* ccc = new ColorCodingComboBox(); ccc->SetColor(OLIVE_CONFIG_STR(QStringLiteral("CatColor%1").arg(i)).toInt()); color_layout->addWidget(ccc, i, 1); color_btns_.append(ccc); } appearance_layout->addWidget(color_group, row, 0, 1, 2); } row++; { QGroupBox* marker_group = new QGroupBox(); marker_group->setTitle(tr("Miscellaneous")); QGridLayout* marker_layout = new QGridLayout(marker_group); marker_layout->addWidget(new QLabel("Default Marker Color"), 0, 0); marker_btn_ = new ColorCodingComboBox(); marker_btn_->SetColor(OLIVE_CONFIG("MarkerColor").toInt()); marker_layout->addWidget(marker_btn_, 0, 1); appearance_layout->addWidget(marker_group, row, 0, 1, 2); } layout->addStretch(); } void PreferencesAppearanceTab::Accept(MultiUndoCommand *command) { Q_UNUSED(command) QString style_path = style_combobox_->currentData().toString(); if (style_path != StyleManager::GetStyle()) { StyleManager::SetStyle(style_path); OLIVE_CONFIG("Style") = style_path; } for (int i=0; i<color_btns_.size(); i++) { OLIVE_CONFIG_STR(QStringLiteral("CatColor%1").arg(i)) = color_btns_.at(i)->GetSelectedColor(); } OLIVE_CONFIG("MarkerColor") = marker_btn_->GetSelectedColor(); } }
3,451
C++
.cpp
87
35.758621
98
0.713127
olive-editor/olive
8,144
552
131
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
19,120
preferencesgeneraltab.cpp
olive-editor_olive/app/dialog/preferences/tabs/preferencesgeneraltab.cpp
/*** Olive - Non-Linear Video Editor Copyright (C) 2022 Olive Team 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 <http://www.gnu.org/licenses/>. ***/ #include "preferencesgeneraltab.h" #include <QGridLayout> #include <QGroupBox> #include <QLabel> #include <QPushButton> #include "common/autoscroll.h" #include "core.h" #include "dialog/sequence/sequence.h" #include "node/project/sequence/sequence.h" namespace olive { PreferencesGeneralTab::PreferencesGeneralTab() { QVBoxLayout* layout = new QVBoxLayout(this); { QGroupBox* global_groupbox = new QGroupBox(tr("Locale")); QGridLayout* global_layout = new QGridLayout(global_groupbox); layout->addWidget(global_groupbox); int row = 0; // General -> Language global_layout->addWidget(new QLabel(tr("Language:")), row, 0); language_combobox_ = new QComboBox(); // Add default language (en-US) QDir language_dir(QStringLiteral(":/ts")); QStringList languages = language_dir.entryList(); foreach (const QString& l, languages) { AddLanguage(l); } QString current_language = OLIVE_CONFIG("Language").toString(); if (current_language.isEmpty()) { // No configured language, use system language current_language = QLocale::system().name(); // If we don't have a language for this, default to en_US if (!languages.contains(current_language)) { current_language = QStringLiteral("en_US"); } } language_combobox_->setCurrentIndex(languages.indexOf(current_language)); global_layout->addWidget(language_combobox_, row, 1); } { QGroupBox* timeline_groupbox = new QGroupBox(tr("Timeline")); QGridLayout* timeline_layout = new QGridLayout(timeline_groupbox); layout->addWidget(timeline_groupbox); int row = 0; QLabel* autoscroll_lbl = new QLabel(tr("Auto-Scroll Method:")); autoscroll_lbl->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); timeline_layout->addWidget(autoscroll_lbl, row, 0); // ComboBox indices match enum indices autoscroll_method_ = new QComboBox(); autoscroll_method_->addItem(tr("None"), AutoScroll::kNone); autoscroll_method_->addItem(tr("Page Scrolling"), AutoScroll::kPage); autoscroll_method_->addItem(tr("Smooth Scrolling"), AutoScroll::kSmooth); autoscroll_method_->setCurrentIndex(OLIVE_CONFIG("Autoscroll").toInt()); timeline_layout->addWidget(autoscroll_method_, row, 1); row++; timeline_layout->addWidget(new QLabel(tr("Rectified Waveforms:")), row, 0); rectified_waveforms_ = new QCheckBox(); rectified_waveforms_->setChecked(OLIVE_CONFIG("RectifiedWaveforms").toBool()); timeline_layout->addWidget(rectified_waveforms_, row, 1); row++; timeline_layout->addWidget(new QLabel(tr("Default Still Image Length:")), row, 0); default_still_length_ = new RationalSlider(); default_still_length_->SetMinimum(rational(100, 1000)); default_still_length_->SetTimebase(rational(100, 1000)); default_still_length_->SetFormat(tr("%1 seconds")); default_still_length_->SetValue(OLIVE_CONFIG("DefaultStillLength").value<rational>()); timeline_layout->addWidget(default_still_length_); } { QGroupBox* autorecovery_groupbox = new QGroupBox(tr("Auto-Recovery")); QGridLayout* autorecovery_layout = new QGridLayout(autorecovery_groupbox); layout->addWidget(autorecovery_groupbox); int row = 0; autorecovery_layout->addWidget(new QLabel(tr("Enable Auto-Recovery:")), row, 0); autorecovery_enabled_ = new QCheckBox(); autorecovery_enabled_->setChecked(OLIVE_CONFIG("AutorecoveryEnabled").toBool()); autorecovery_layout->addWidget(autorecovery_enabled_, row, 1); row++; autorecovery_layout->addWidget(new QLabel(tr("Auto-Recovery Interval:")), row, 0); autorecovery_interval_ = new IntegerSlider(); autorecovery_interval_->SetMinimum(1); autorecovery_interval_->SetMaximum(60); autorecovery_interval_->SetFormat(QT_TRANSLATE_N_NOOP("olive::SliderBase", "%n minute(s)"), true); autorecovery_interval_->SetValue(OLIVE_CONFIG("AutorecoveryInterval").toLongLong()); autorecovery_layout->addWidget(autorecovery_interval_, row, 1); row++; autorecovery_layout->addWidget(new QLabel(tr("Maximum Versions Per Project:")), row, 0); autorecovery_maximum_ = new IntegerSlider(); autorecovery_maximum_->SetMinimum(1); autorecovery_maximum_->SetMaximum(1000); autorecovery_maximum_->SetValue(OLIVE_CONFIG("AutorecoveryMaximum").toLongLong()); autorecovery_layout->addWidget(autorecovery_maximum_, row, 1); row++; QPushButton* browse_autorecoveries = new QPushButton(tr("Browse Auto-Recoveries")); connect(browse_autorecoveries, &QPushButton::clicked, Core::instance(), &Core::BrowseAutoRecoveries); autorecovery_layout->addWidget(browse_autorecoveries, row, 1); } layout->addStretch(); } void PreferencesGeneralTab::Accept(MultiUndoCommand *command) { Q_UNUSED(command) OLIVE_CONFIG("RectifiedWaveforms") = rectified_waveforms_->isChecked(); OLIVE_CONFIG("Autoscroll") = autoscroll_method_->currentData(); OLIVE_CONFIG("DefaultStillLength") = QVariant::fromValue(default_still_length_->GetValue()); QString set_language = language_combobox_->currentData().toString(); if (QLocale::system().name() == set_language) { // Language is set to the system, assume this is effectively "auto" set_language = QString(); } // If the language has changed, set it now if (OLIVE_CONFIG("Language").toString() != set_language) { OLIVE_CONFIG("Language") = set_language; Core::instance()->SetLanguage(set_language.isEmpty() ? QLocale::system().name() : set_language); } OLIVE_CONFIG("AutorecoveryEnabled") = autorecovery_enabled_->isChecked(); OLIVE_CONFIG("AutorecoveryInterval") = QVariant::fromValue(autorecovery_interval_->GetValue()); OLIVE_CONFIG("AutorecoveryMaximum") = QVariant::fromValue(autorecovery_maximum_->GetValue()); Core::instance()->SetAutorecoveryInterval(autorecovery_interval_->GetValue()); } void PreferencesGeneralTab::AddLanguage(const QString &locale_name) { language_combobox_->addItem(tr("%1 (%2)").arg(QLocale(locale_name).nativeLanguageName(), locale_name));; language_combobox_->setItemData(language_combobox_->count() - 1, locale_name); } }
6,946
C++
.cpp
141
44.617021
105
0.727165
olive-editor/olive
8,144
552
131
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
19,121
preferencesaudiotab.cpp
olive-editor_olive/app/dialog/preferences/tabs/preferencesaudiotab.cpp
/*** Olive - Non-Linear Video Editor Copyright (C) 2022 Olive Team 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 <http://www.gnu.org/licenses/>. ***/ #include "preferencesaudiotab.h" #include <QGridLayout> #include <QGroupBox> #include <QLabel> #include "audio/audiomanager.h" #include "config/config.h" namespace olive { PreferencesAudioTab::PreferencesAudioTab() { QVBoxLayout* audio_tab_layout = new QVBoxLayout(this); { // Backend Layout QGridLayout* main_layout = new QGridLayout(); main_layout->setContentsMargins(0, 0, 0, 0); int row = 0; main_layout->addWidget(new QLabel(tr("Backend:")), row, 0); audio_backend_combobox_ = new QComboBox(); connect(audio_backend_combobox_, static_cast<void(QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this, &PreferencesAudioTab::RefreshDevices); main_layout->addWidget(audio_backend_combobox_, row, 1); audio_tab_layout->addLayout(main_layout); } { QGroupBox* groupbox = new QGroupBox(); audio_tab_layout->addWidget(groupbox); QVBoxLayout* layout = new QVBoxLayout(groupbox); int row = 0; { // Output Group QGroupBox* output_group = new QGroupBox(); output_group->setTitle(tr("Output")); layout->addWidget(output_group); QGridLayout* output_layout = new QGridLayout(output_group); output_layout->addWidget(new QLabel(tr("Device:")), row, 0); audio_output_devices_ = new QComboBox(); output_layout->addWidget(audio_output_devices_, row, 1); row++; { int output_row = 0; QGroupBox *output_param_group = new QGroupBox(tr("Advanced")); output_layout->addWidget(output_param_group, row, 0, 1, 2); QGridLayout *output_param_layout = new QGridLayout(output_param_group); output_param_layout->addWidget(new QLabel(tr("Sample Rate:")), output_row, 0); output_rate_combo_ = new SampleRateComboBox(); output_rate_combo_->SetSampleRate(OLIVE_CONFIG("AudioOutputSampleRate").toInt()); output_param_layout->addWidget(output_rate_combo_, output_row, 1); output_row++; output_param_layout->addWidget(new QLabel(tr("Channel Layout:")), output_row, 0); output_ch_layout_combo_ = new ChannelLayoutComboBox(); output_ch_layout_combo_->SetChannelLayout(OLIVE_CONFIG("AudioOutputChannelLayout").toULongLong()); output_param_layout->addWidget(output_ch_layout_combo_, output_row, 1); output_row++; output_param_layout->addWidget(new QLabel(tr("Sample Format:")), output_row, 0); output_fmt_combo_ = new SampleFormatComboBox(); output_fmt_combo_->SetPackedFormats(); output_fmt_combo_->SetSampleFormat(SampleFormat::from_string(OLIVE_CONFIG("AudioOutputSampleFormat").toString().toStdString())); output_param_layout->addWidget(output_fmt_combo_, output_row, 1); } } row = 0; { QGroupBox* input_group = new QGroupBox(); input_group->setTitle(tr("Input")); layout->addWidget(input_group); QGridLayout* input_layout = new QGridLayout(input_group); input_layout->addWidget(new QLabel(tr("Device:")), row, 0); audio_input_devices_ = new QComboBox(); input_layout->addWidget(audio_input_devices_, row, 1); row++; QGroupBox *recording_group = new QGroupBox(tr("Recording")); input_layout->addWidget(recording_group, row, 0, 1, 2); QVBoxLayout *recording_layout = new QVBoxLayout(recording_group); QHBoxLayout *fmt_layout = new QHBoxLayout(); recording_layout->addLayout(fmt_layout); fmt_layout->addWidget(new QLabel(tr("Format:"))); record_format_combo_ = new ExportFormatComboBox(ExportFormatComboBox::kShowAudioOnly); record_format_combo_->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); record_format_combo_->SetFormat(static_cast<ExportFormat::Format>(OLIVE_CONFIG("AudioRecordingFormat").toInt())); fmt_layout->addWidget(record_format_combo_); record_options_ = new ExportAudioTab(); record_options_->SetFormat(record_format_combo_->GetFormat()); record_options_->SetCodec(static_cast<ExportCodec::Codec>(OLIVE_CONFIG("AudioRecordingCodec").toInt())); record_options_->sample_rate_combobox()->SetSampleRate(OLIVE_CONFIG("AudioRecordingSampleRate").toInt()); record_options_->channel_layout_combobox()->SetChannelLayout(OLIVE_CONFIG("AudioRecordingChannelLayout").toULongLong()); record_options_->bit_rate_slider()->SetValue(OLIVE_CONFIG("AudioRecordingBitRate").toInt()); record_options_->sample_format_combobox()->SetSampleFormat(SampleFormat::from_string(OLIVE_CONFIG("AudioRecordingSampleFormat").toString().toStdString())); recording_layout->addWidget(record_options_); connect(record_format_combo_, &ExportFormatComboBox::FormatChanged, record_options_, &ExportAudioTab::SetFormat); } QHBoxLayout* refresh_layout = new QHBoxLayout(); layout->addLayout(refresh_layout); refresh_layout->addStretch(); refresh_devices_btn_ = new QPushButton(tr("Refresh Devices")); refresh_layout->addWidget(refresh_devices_btn_); connect(refresh_devices_btn_, &QPushButton::clicked, this, &PreferencesAudioTab::HardRefreshBackends); } audio_tab_layout->addStretch(); // Populate lists RefreshBackends(); } void PreferencesAudioTab::Accept(MultiUndoCommand *command) { Q_UNUSED(command) // Get device indexes PaDeviceIndex output_device = audio_output_devices_->currentData().value<PaDeviceIndex>(); PaDeviceIndex input_device = audio_input_devices_->currentData().value<PaDeviceIndex>(); // Get device names, which seem to be the closest thing we have to a "unique identifier" for them OLIVE_CONFIG("AudioOutput") = audio_output_devices_->currentText(); OLIVE_CONFIG("AudioInput") = audio_input_devices_->currentText(); // Set devices to be used from now on AudioManager::instance()->SetOutputDevice(output_device); AudioManager::instance()->SetInputDevice(input_device); OLIVE_CONFIG("AudioOutputSampleRate") = output_rate_combo_->GetSampleRate(); OLIVE_CONFIG("AudioOutputChannelLayout") = QVariant::fromValue(output_ch_layout_combo_->GetChannelLayout()); OLIVE_CONFIG("AudioOutputSampleFormat") = QString::fromStdString(output_fmt_combo_->GetSampleFormat().to_string()); OLIVE_CONFIG("AudioRecordingFormat") = record_format_combo_->GetFormat(); OLIVE_CONFIG("AudioRecordingCodec") = record_options_->GetCodec(); OLIVE_CONFIG("AudioRecordingSampleRate") = record_options_->sample_rate_combobox()->GetSampleRate(); OLIVE_CONFIG("AudioRecordingChannelLayout") = QVariant::fromValue(record_options_->channel_layout_combobox()->GetChannelLayout()); OLIVE_CONFIG("AudioRecordingBitRate") = QVariant::fromValue(record_options_->bit_rate_slider()->GetValue()); OLIVE_CONFIG("AudioRecordingSampleFormat") = QString::fromStdString(record_options_->sample_format_combobox()->GetSampleFormat().to_string()); emit AudioManager::instance()->OutputParamsChanged(); } void PreferencesAudioTab::RefreshBackends() { audio_backend_combobox_->clear(); for (PaHostApiIndex i=0, end=Pa_GetHostApiCount(); i<end; i++) { const PaHostApiInfo *info = Pa_GetHostApiInfo(i); audio_backend_combobox_->addItem(info->name); } RefreshDevices(); AttemptToSetDevicesFromConfig(); } void PreferencesAudioTab::RefreshDevices() { if (audio_backend_combobox_->count() == 0) { return; } PaHostApiIndex host_index = audio_backend_combobox_->currentIndex(); const PaHostApiInfo *host = Pa_GetHostApiInfo(host_index); audio_output_devices_->clear(); audio_input_devices_->clear(); for (int i=0; i<host->deviceCount; i++) { PaDeviceIndex device_index = Pa_HostApiDeviceIndexToDeviceIndex(host_index, i); const PaDeviceInfo *device = Pa_GetDeviceInfo(device_index); if (device->maxOutputChannels) { audio_output_devices_->addItem(device->name, device_index); } if (device->maxInputChannels) { audio_input_devices_->addItem(device->name, device_index); } } } void PreferencesAudioTab::HardRefreshBackends() { AudioManager::instance()->HardReset(); RefreshBackends(); } void PreferencesAudioTab::AttemptToSetDevicesFromConfig() { // Load with currently active devices PaDeviceIndex current_output_index = AudioManager::instance()->GetOutputDevice(); PaDeviceIndex current_input_index = AudioManager::instance()->GetInputDevice(); const PaDeviceInfo *current_output = nullptr, *current_input = nullptr; if (current_output_index != paNoDevice) { current_output = Pa_GetDeviceInfo(current_output_index); } if (current_input_index != paNoDevice) { current_input = Pa_GetDeviceInfo(current_input_index); } if (current_output || current_input) { PaHostApiIndex host = current_output ? current_output->hostApi : current_input->hostApi; // Set backend accordingly audio_backend_combobox_->setCurrentIndex(host); // Device comboboxes should be populated correctly now if (current_output) { audio_output_devices_->setCurrentText(current_output->name); } if (current_input) { audio_input_devices_->setCurrentText(current_input->name); } } } }
9,831
C++
.cpp
197
44.928934
161
0.72753
olive-editor/olive
8,144
552
131
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
19,122
preferencesdisktab.cpp
olive-editor_olive/app/dialog/preferences/tabs/preferencesdisktab.cpp
/*** Olive - Non-Linear Video Editor Copyright (C) 2022 Olive Team 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 <http://www.gnu.org/licenses/>. ***/ #include "preferencesdisktab.h" #include <QDir> #include <QFileDialog> #include <QGridLayout> #include <QGroupBox> #include <QLabel> #include <QMessageBox> #include "common/filefunctions.h" namespace olive { PreferencesDiskTab::PreferencesDiskTab() { // Get default disk cache folder default_disk_cache_folder_ = DiskManager::instance()->GetDefaultCacheFolder(); QVBoxLayout* outer_layout = new QVBoxLayout(this); QGroupBox* disk_management_group = new QGroupBox(tr("Disk Management")); outer_layout->addWidget(disk_management_group); QGridLayout* disk_management_layout = new QGridLayout(disk_management_group); int row = 0; disk_management_layout->addWidget(new QLabel(tr("Disk Cache Location:")), row, 0); disk_cache_location_ = new PathWidget(default_disk_cache_folder_->GetPath()); disk_management_layout->addWidget(disk_cache_location_, row, 1); row++; QPushButton* disk_cache_settings_btn = new QPushButton(tr("Disk Cache Settings")); connect(disk_cache_settings_btn, &QPushButton::clicked, this, [this](){ DiskManager::instance()->ShowDiskCacheSettingsDialog(disk_cache_location_->text(), this); }); disk_management_layout->addWidget(disk_cache_settings_btn, row, 1); row++; QGroupBox* cache_behavior = new QGroupBox(tr("Cache Behavior")); outer_layout->addWidget(cache_behavior); QGridLayout* cache_behavior_layout = new QGridLayout(cache_behavior); row = 0; cache_behavior_layout->addWidget(new QLabel(tr("Cache Ahead:")), row, 0); cache_ahead_slider_ = new FloatSlider(); cache_ahead_slider_->SetFormat(tr("%1 seconds")); cache_ahead_slider_->SetMinimum(0); cache_ahead_slider_->SetValue(OLIVE_CONFIG("DiskCacheAhead").value<rational>().toDouble()); cache_behavior_layout->addWidget(cache_ahead_slider_, row, 1); cache_behavior_layout->addWidget(new QLabel(tr("Cache Behind:")), row, 2); cache_behind_slider_ = new FloatSlider(); cache_behind_slider_->SetMinimum(0); cache_behind_slider_->SetFormat(tr("%1 seconds")); cache_behind_slider_->SetValue(OLIVE_CONFIG("DiskCacheBehind").value<rational>().toDouble()); cache_behavior_layout->addWidget(cache_behind_slider_, row, 3); outer_layout->addStretch(); } bool PreferencesDiskTab::Validate() { if (disk_cache_location_->text() != default_disk_cache_folder_->GetPath()) { // Disk cache location is changing // Check if the user is okay with invalidating the current cache if (!DiskManager::ShowDiskCacheChangeConfirmationDialog(this)) { return false; } // Check validity of the new path if (!FileFunctions::DirectoryIsValid(disk_cache_location_->text())) { QMessageBox::critical(this, tr("Disk Cache"), tr("Failed to set disk cache location. Access was denied.")); return false; } } return true; } void PreferencesDiskTab::Accept(MultiUndoCommand *command) { Q_UNUSED(command) if (disk_cache_location_->text() != default_disk_cache_folder_->GetPath()) { default_disk_cache_folder_->SetPath(disk_cache_location_->text()); } OLIVE_CONFIG("DiskCacheBehind") = QVariant::fromValue(rational::fromDouble(cache_behind_slider_->GetValue())); OLIVE_CONFIG("DiskCacheAhead") = QVariant::fromValue(rational::fromDouble(cache_ahead_slider_->GetValue())); } }
4,039
C++
.cpp
88
42.056818
112
0.734491
olive-editor/olive
8,144
552
131
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
19,123
preferencesbehaviortab.cpp
olive-editor_olive/app/dialog/preferences/tabs/preferencesbehaviortab.cpp
/*** Olive - Non-Linear Video Editor Copyright (C) 2022 Olive Team 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 <http://www.gnu.org/licenses/>. ***/ #include "preferencesbehaviortab.h" #include <QCheckBox> #include <QVBoxLayout> #include "config/config.h" namespace olive { PreferencesBehaviorTab::PreferencesBehaviorTab() { QVBoxLayout* layout = new QVBoxLayout(this); behavior_tree_ = new QTreeWidget(); layout->addWidget(behavior_tree_); behavior_tree_->setHeaderLabel(tr("Behavior")); QTreeWidgetItem* general_group = AddParent(tr("General")); AddItem(tr("Enable hover focus"), QStringLiteral("HoverFocus"), tr("Panels will be considered focused when the mouse cursor is over them without having to click them."), general_group); AddItem(tr("Enable slider ladder"), QStringLiteral("UseSliderLadders"), general_group); AddItem(tr("Scrolling zooms by default"), QStringLiteral("ScrollZooms"), tr("By default, scrolling will move the view around, and holding Ctrl/Cmd will make it zoom instead. " "Enabling this will switch those, scrolling will zoom by default, and holding Ctrl/Cmd will move the view instead."), general_group); QTreeWidgetItem* audio_group = AddParent(tr("Audio")); AddItem(tr("Enable audio scrubbing"), QStringLiteral("AudioScrubbing"), audio_group); QTreeWidgetItem* timeline_group = AddParent(tr("Timeline")); AddItem(tr("Auto-Seek to Imported Clips"), QStringLiteral("EnableSeekToImport"), timeline_group); AddItem(tr("Edit Tool Also Seeks"), QStringLiteral("EditToolAlsoSeeks"), timeline_group); AddItem(tr("Edit Tool Selects Links"), QStringLiteral("EditToolSelectsLinks"), timeline_group); AddItem(tr("Enable Drag Files to Timeline"), QStringLiteral("EnableDragFilesToTimeline"), timeline_group); AddItem(tr("Invert Timeline Scroll Axes"), QStringLiteral("InvertTimelineScrollAxes"), tr("Hold ALT on any UI element to switch scrolling axes"), timeline_group); AddItem(tr("Seek Also Selects"), QStringLiteral("SeekAlsoSelects"), timeline_group); AddItem(tr("Seek to the End of Pastes"), QStringLiteral("PasteSeeks"), timeline_group); AddItem(tr("Selecting Also Seeks"), QStringLiteral("SelectAlsoSeeks"), timeline_group); QTreeWidgetItem* playback_group = AddParent(tr("Playback")); AddItem(tr("Ask For Name When Setting Marker"), QStringLiteral("SetNameWithMarker"), playback_group); AddItem(tr("Automatically rewind at the end of a sequence"), QStringLiteral("AutoSeekToBeginning"), playback_group); QTreeWidgetItem* project_group = AddParent(tr("Project")); AddItem(tr("Drop Files on Media to Replace"), QStringLiteral("DropFileOnMediaToReplace"), project_group); QTreeWidgetItem* node_group = AddParent(tr("Nodes")); AddItem(tr("Add Default Effects to New Clips"), QStringLiteral("AddDefaultEffectsToClips"), node_group); AddItem(tr("Auto-Scale By Default"), QStringLiteral("AutoscaleByDefault"), node_group); AddItem(tr("Splitting Clips Copies Dependencies"), QStringLiteral("SplitClipsCopyNodes"), tr("Multiple clips can share the same nodes. Disable this to automatically share node " "dependencies among clips when copying or splitting them."), node_group); QTreeWidgetItem* opengl_group = AddParent(tr("OpenGL")); AddItem(tr("Use glFinish"), QStringLiteral("UseGLFinish"), opengl_group); } void PreferencesBehaviorTab::Accept(MultiUndoCommand *command) { Q_UNUSED(command) for (auto iterator=config_map_.begin();iterator!=config_map_.end();iterator++) { OLIVE_CONFIG_STR(iterator.value()) = (iterator.key()->checkState(0) == Qt::Checked); } } QTreeWidgetItem* PreferencesBehaviorTab::AddItem(const QString &text, const QString &config_key, const QString& tooltip, QTreeWidgetItem* parent) { QTreeWidgetItem* item = new QTreeWidgetItem({text}); item->setToolTip(0, tooltip); item->setCheckState(0, OLIVE_CONFIG_STR(config_key).toBool() ? Qt::Checked : Qt::Unchecked); config_map_.insert(item, config_key); if (parent) { parent->addChild(item); } else { behavior_tree_->addTopLevelItem(item); } return item; } QTreeWidgetItem *PreferencesBehaviorTab::AddItem(const QString &text, const QString &config_key, QTreeWidgetItem *parent) { return AddItem(text, config_key, QString(), parent); } QTreeWidgetItem *PreferencesBehaviorTab::AddParent(const QString &text, const QString &tooltip, QTreeWidgetItem *parent) { QTreeWidgetItem* item = new QTreeWidgetItem({text}); item->setToolTip(0, tooltip); if (parent) { parent->addChild(item); } else { behavior_tree_->addTopLevelItem(item); } return item; } QTreeWidgetItem *PreferencesBehaviorTab::AddParent(const QString &text, QTreeWidgetItem *parent) { return AddParent(text, QString(), parent); } }
5,730
C++
.cpp
136
36.580882
145
0.711307
olive-editor/olive
8,144
552
131
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
19,124
preferenceskeyboardtab.cpp
olive-editor_olive/app/dialog/preferences/tabs/preferenceskeyboardtab.cpp
/*** Olive - Non-Linear Video Editor Copyright (C) 2022 Olive Team 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 <http://www.gnu.org/licenses/>. ***/ #include "preferenceskeyboardtab.h" #include <QFileDialog> #include <QHBoxLayout> #include <QLineEdit> #include <QMessageBox> #include <QPushButton> #include <QVBoxLayout> #include "window/mainwindow/mainwindow.h" namespace olive { PreferencesKeyboardTab::PreferencesKeyboardTab(MainWindow *main_window) : main_window_(main_window) { QVBoxLayout* shortcut_layout = new QVBoxLayout(this); QLineEdit* key_search_line = new QLineEdit(); key_search_line->setPlaceholderText(tr("Search for action or shortcut")); connect(key_search_line, SIGNAL(textChanged(const QString &)), this, SLOT(refine_shortcut_list(const QString &))); shortcut_layout->addWidget(key_search_line); keyboard_tree_ = new QTreeWidget(); QTreeWidgetItem* tree_header = keyboard_tree_->headerItem(); tree_header->setText(0, tr("Action")); tree_header->setText(1, tr("Shortcut")); shortcut_layout->addWidget(keyboard_tree_); QHBoxLayout* reset_shortcut_layout = new QHBoxLayout(); QPushButton* import_shortcut_button = new QPushButton(tr("Import")); reset_shortcut_layout->addWidget(import_shortcut_button); connect(import_shortcut_button, SIGNAL(clicked(bool)), this, SLOT(load_shortcut_file())); QPushButton* export_shortcut_button = new QPushButton(tr("Export")); reset_shortcut_layout->addWidget(export_shortcut_button); connect(export_shortcut_button, SIGNAL(clicked(bool)), this, SLOT(save_shortcut_file())); reset_shortcut_layout->addStretch(); QPushButton* reset_selected_shortcut_button = new QPushButton(tr("Reset Selected")); reset_shortcut_layout->addWidget(reset_selected_shortcut_button); connect(reset_selected_shortcut_button, SIGNAL(clicked(bool)), this, SLOT(reset_default_shortcut())); QPushButton* reset_all_shortcut_button = new QPushButton(tr("Reset All")); reset_shortcut_layout->addWidget(reset_all_shortcut_button); connect(reset_all_shortcut_button, SIGNAL(clicked(bool)), this, SLOT(reset_all_shortcuts())); shortcut_layout->addLayout(reset_shortcut_layout); setup_kbd_shortcuts(main_window_->menuBar()); } void PreferencesKeyboardTab::Accept(MultiUndoCommand *command) { Q_UNUSED(command) // Save keyboard shortcuts for (int i=0;i<key_shortcut_fields_.size();i++) { key_shortcut_fields_.at(i)->set_action_shortcut(); } main_window_->SaveLayout(); } void PreferencesKeyboardTab::setup_kbd_shortcuts(QMenuBar* menubar) { QList<QAction*> menus = menubar->actions(); for (int i=0;i<menus.size();i++) { QMenu* menu = menus.at(i)->menu(); QTreeWidgetItem* item = new QTreeWidgetItem(keyboard_tree_); item->setText(0, menu->title().replace("&", "")); keyboard_tree_->addTopLevelItem(item); setup_kbd_shortcut_worker(menu, item); } for (int i=0;i<key_shortcut_items_.size();i++) { if (!key_shortcut_actions_.at(i)->property("id").isNull()) { KeySequenceEditor* editor = new KeySequenceEditor(keyboard_tree_, key_shortcut_actions_.at(i)); keyboard_tree_->setItemWidget(key_shortcut_items_.at(i), 1, editor); key_shortcut_fields_.append(editor); } } } void PreferencesKeyboardTab::setup_kbd_shortcut_worker(QMenu* menu, QTreeWidgetItem* parent) { QList<QAction*> actions = menu->actions(); for (int i=0;i<actions.size();i++) { QAction* a = actions.at(i); if (!a->isSeparator() && a->property("keyignore").isNull()) { QTreeWidgetItem* item = new QTreeWidgetItem(parent); item->setText(0, a->text().replace("&", "")); parent->addChild(item); if (a->menu() != nullptr) { item->setChildIndicatorPolicy(QTreeWidgetItem::ShowIndicator); setup_kbd_shortcut_worker(a->menu(), item); } else { key_shortcut_items_.append(item); key_shortcut_actions_.append(a); } } } } void PreferencesKeyboardTab::reset_default_shortcut() { QList<QTreeWidgetItem*> items = keyboard_tree_->selectedItems(); for (int i=0;i<items.size();i++) { QTreeWidgetItem* item = keyboard_tree_->selectedItems().at(i); static_cast<KeySequenceEditor*>(keyboard_tree_->itemWidget(item, 1))->reset_to_default(); } } void PreferencesKeyboardTab::reset_all_shortcuts() { if (QMessageBox::question( this, tr("Confirm Reset All Shortcuts"), tr("Are you sure you wish to reset all keyboard shortcuts to their defaults?"), QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) { for (int i=0;i<key_shortcut_fields_.size();i++) { key_shortcut_fields_.at(i)->reset_to_default(); } } } bool PreferencesKeyboardTab::refine_shortcut_list(const QString &s, QTreeWidgetItem* parent) { if (parent == nullptr) { for (int i=0;i<keyboard_tree_->topLevelItemCount();i++) { refine_shortcut_list(s, keyboard_tree_->topLevelItem(i)); } // Return value is `all_children_are_hidden` which doesn't matter at the top level return false; } else { parent->setExpanded(!s.isEmpty()); bool all_children_are_hidden = !s.isEmpty(); for (int i=0;i<parent->childCount();i++) { QTreeWidgetItem* item = parent->child(i); if (item->childCount() > 0) { if (!refine_shortcut_list(s, item)) { all_children_are_hidden = false; } } else { item->setHidden(false); if (s.isEmpty()) { all_children_are_hidden = false; } else { QString shortcut; if (keyboard_tree_->itemWidget(item, 1) != nullptr) { shortcut = static_cast<QKeySequenceEdit*>(keyboard_tree_->itemWidget(item, 1))->keySequence().toString(); } if (item->text(0).contains(s, Qt::CaseInsensitive) || shortcut.contains(s, Qt::CaseInsensitive)) { all_children_are_hidden = false; } else { item->setHidden(true); } } } } if (parent->text(0).contains(s, Qt::CaseInsensitive)) all_children_are_hidden = false; parent->setHidden(all_children_are_hidden); return all_children_are_hidden; } } void PreferencesKeyboardTab::load_shortcut_file() { QString fn = QFileDialog::getOpenFileName(this, tr("Import Keyboard Shortcuts")); if (!fn.isEmpty()) { QFile f(fn); if (f.exists() && f.open(QFile::ReadOnly)) { QString ba = f.readAll(); f.close(); for (int i=0;i<key_shortcut_fields_.size();i++) { int index = ba.indexOf(key_shortcut_fields_.at(i)->action_name()); if (index == 0 || (index > 0 && ba.at(index-1) == '\n')) { while (index < ba.size() && ba.at(index) != '\t') index++; QString ks; index++; while (index < ba.size() && ba.at(index) != '\n') { ks.append(ba.at(index)); index++; } key_shortcut_fields_.at(i)->setKeySequence(ks); } else { key_shortcut_fields_.at(i)->reset_to_default(); } } } else { QMessageBox::critical( this, tr("Error saving shortcuts"), tr("Failed to open file for reading") ); } } } void PreferencesKeyboardTab::save_shortcut_file() { QString fn = QFileDialog::getSaveFileName(this, tr("Export Keyboard Shortcuts")); if (!fn.isEmpty()) { QFile f(fn); if (f.open(QFile::WriteOnly)) { bool start = true; for (int i=0;i<key_shortcut_fields_.size();i++) { QString s = key_shortcut_fields_.at(i)->export_shortcut(); if (!s.isEmpty()) { if (!start) f.write("\n"); f.write(s.toUtf8()); start = false; } } f.close(); QMessageBox::information(this, tr("Export Shortcuts"), tr("Shortcuts exported successfully")); } else { QMessageBox::critical(this, tr("Error saving shortcuts"), tr("Failed to open file for writing")); } } } }
8,505
C++
.cpp
206
35.791262
117
0.666545
olive-editor/olive
8,144
552
131
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
19,125
exportvideotab.cpp
olive-editor_olive/app/dialog/export/exportvideotab.cpp
/*** Olive - Non-Linear Video Editor Copyright (C) 2022 Olive Team 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 <http://www.gnu.org/licenses/>. ***/ #include "exportvideotab.h" #include <QCheckBox> #include <QGridLayout> #include <QGroupBox> #include <QLabel> #include <QPushButton> #include "core.h" #include "exportadvancedvideodialog.h" #include "node/color/colormanager/colormanager.h" namespace olive { ExportVideoTab::ExportVideoTab(ColorManager* color_manager, QWidget *parent) : QWidget(parent), color_manager_(color_manager), threads_(0), color_range_(VideoParams::kColorRangeDefault) { QVBoxLayout* outer_layout = new QVBoxLayout(this); outer_layout->addWidget(SetupResolutionSection()); outer_layout->addWidget(SetupCodecSection()); outer_layout->addWidget(SetupColorSection()); outer_layout->addStretch(); } int ExportVideoTab::SetFormat(ExportFormat::Format format) { format_ = format; QList<ExportCodec::Codec> vcodecs = ExportFormat::GetVideoCodecs(format); setEnabled(!vcodecs.isEmpty()); codec_combobox()->clear(); foreach (ExportCodec::Codec vcodec, vcodecs) { codec_combobox()->addItem(ExportCodec::GetCodecName(vcodec), vcodec); } return vcodecs.size(); } bool ExportVideoTab::IsImageSequenceSet() const { ImageSection* img_section = dynamic_cast<ImageSection*>(codec_stack_->currentWidget()); return (img_section && img_section->IsImageSequenceChecked()); } void ExportVideoTab::SetImageSequence(bool e) const { if (ImageSection* img_section = dynamic_cast<ImageSection*>(codec_stack_->currentWidget())) { img_section->SetImageSequenceChecked(e); } } QWidget* ExportVideoTab::SetupResolutionSection() { int row = 0; QGroupBox* resolution_group = new QGroupBox(); resolution_group->setTitle(tr("General")); QGridLayout* layout = new QGridLayout(resolution_group); layout->addWidget(new QLabel(tr("Width:")), row, 0); width_slider_ = new IntegerSlider(); width_slider_->SetMinimum(1); layout->addWidget(width_slider_, row, 1); row++; layout->addWidget(new QLabel(tr("Height:")), row, 0); height_slider_ = new IntegerSlider(); height_slider_->SetMinimum(1); layout->addWidget(height_slider_, row, 1); row++; layout->addWidget(new QLabel(tr("Maintain Aspect Ratio:")), row, 0); maintain_aspect_checkbox_ = new QCheckBox(); maintain_aspect_checkbox_->setChecked(true); layout->addWidget(maintain_aspect_checkbox_, row, 1); row++; layout->addWidget(new QLabel(tr("Scaling Method:")), row, 0); scaling_method_combobox_ = new QComboBox(); scaling_method_combobox_->setEnabled(false); scaling_method_combobox_->addItem(tr("Fit"), EncodingParams::kFit); scaling_method_combobox_->addItem(tr("Stretch"), EncodingParams::kStretch); scaling_method_combobox_->addItem(tr("Crop"), EncodingParams::kCrop); layout->addWidget(scaling_method_combobox_, row, 1); // Automatically enable/disable the scaling method depending on maintain aspect ratio connect(maintain_aspect_checkbox_, &QCheckBox::toggled, this, &ExportVideoTab::MaintainAspectRatioChanged); row++; layout->addWidget(new QLabel(tr("Frame Rate:")), row, 0); frame_rate_combobox_ = new FrameRateComboBox(); connect(frame_rate_combobox_, &FrameRateComboBox::FrameRateChanged, this, &ExportVideoTab::UpdateFrameRate); layout->addWidget(frame_rate_combobox_, row, 1); row++; layout->addWidget(new QLabel(tr("Pixel Aspect Ratio:")), row, 0); pixel_aspect_combobox_ = new PixelAspectRatioComboBox(); layout->addWidget(pixel_aspect_combobox_, row, 1); row++; layout->addWidget(new QLabel(tr("Interlacing:")), row, 0); interlaced_combobox_ = new InterlacedComboBox(); layout->addWidget(interlaced_combobox_, row, 1); row++; layout->addWidget(new QLabel(tr("Quality:")), row, 0); pixel_format_field_ = new PixelFormatComboBox(false); layout->addWidget(pixel_format_field_, row, 1); return resolution_group; } QWidget* ExportVideoTab::SetupColorSection() { color_space_chooser_ = new ColorSpaceChooser(color_manager_, true, false); connect(color_space_chooser_, &ColorSpaceChooser::InputColorSpaceChanged, this, &ExportVideoTab::ColorSpaceChanged); return color_space_chooser_; } QWidget *ExportVideoTab::SetupCodecSection() { int row = 0; QGroupBox* codec_group = new QGroupBox(); codec_group->setTitle(tr("Codec")); QGridLayout* codec_layout = new QGridLayout(codec_group); codec_layout->addWidget(new QLabel(tr("Codec:")), row, 0); codec_combobox_ = new QComboBox(); codec_layout->addWidget(codec_combobox_, row, 1); connect(codec_combobox_, static_cast<void(QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this, &ExportVideoTab::VideoCodecChanged); row++; codec_stack_ = new CodecStack(); codec_layout->addWidget(codec_stack_, row, 0, 1, 2); image_section_ = new ImageSection(); connect(image_section_, &ImageSection::TimeChanged, this, &ExportVideoTab::TimeChanged); codec_stack_->addWidget(image_section_); h264_section_ = new H264Section(); codec_stack_->addWidget(h264_section_); h265_section_ = new H265Section(); codec_stack_->addWidget(h265_section_); av1_section_ = new AV1Section(); codec_stack_->addWidget(av1_section_); cineform_section_ = new CineformSection(); codec_stack_->addWidget(cineform_section_); row++; QPushButton* advanced_btn = new QPushButton(tr("Advanced")); connect(advanced_btn, &QPushButton::clicked, this, &ExportVideoTab::OpenAdvancedDialog); codec_layout->addWidget(advanced_btn, row, 1); return codec_group; } void ExportVideoTab::MaintainAspectRatioChanged(bool val) { scaling_method_combobox_->setEnabled(!val); } void ExportVideoTab::OpenAdvancedDialog() { // Find export formats compatible with this encoder QStringList pixel_formats = ExportFormat::GetPixelFormatsForCodec(format_, GetSelectedCodec()); ExportAdvancedVideoDialog d(pixel_formats, this); d.set_threads(threads_); d.set_pix_fmt(pix_fmt_); d.set_yuv_range(color_range_); if (d.exec() == QDialog::Accepted) { threads_ = d.threads(); pix_fmt_ = d.pix_fmt(); color_range_ = d.yuv_range(); } } void ExportVideoTab::UpdateFrameRate(rational r) { // Convert frame rate to timebase r.flip(); for (int i=0; i<codec_stack_->count(); i++) { ImageSection* img = dynamic_cast<ImageSection*>(codec_stack_->widget(i)); if (img) { img->SetTimebase(r); } } } void ExportVideoTab::VideoCodecChanged() { ExportCodec::Codec codec = GetSelectedCodec(); switch (codec) { case ExportCodec::kCodecH264: case ExportCodec::kCodecH264rgb: SetCodecSection(h264_section_); break; case ExportCodec::kCodecH265: SetCodecSection(h265_section_); break; case ExportCodec::kCodecAV1: SetCodecSection(av1_section_); break; case ExportCodec::kCodecCineform: SetCodecSection(cineform_section_); break; default: SetCodecSection(ExportCodec::IsCodecAStillImage(codec) ? image_section_ : nullptr); } // Set default pixel format QStringList pix_fmts = ExportFormat::GetPixelFormatsForCodec(format_, codec); if (!pix_fmts.isEmpty()) { pix_fmt_ = pix_fmts.first(); } else { pix_fmt_.clear(); } } void ExportVideoTab::SetTime(const rational &time) { for (int i=0; i<codec_stack_->count(); i++) { ImageSection* img = dynamic_cast<ImageSection*>(codec_stack_->widget(i)); if (img) { img->SetTime(time); } } } }
8,074
C++
.cpp
213
34.516432
118
0.734524
olive-editor/olive
8,144
552
131
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
19,126
exportformatcombobox.cpp
olive-editor_olive/app/dialog/export/exportformatcombobox.cpp
/*** Olive - Non-Linear Video Editor Copyright (C) 2022 Olive Team 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 <http://www.gnu.org/licenses/>. ***/ #include "exportformatcombobox.h" #include <QHBoxLayout> #include <QLabel> #include "ui/icons/icons.h" namespace olive { ExportFormatComboBox::ExportFormatComboBox(Mode mode, QWidget *parent) : QComboBox(parent) { custom_menu_ = new Menu(this); // Populate combobox formats switch (mode) { case kShowAllFormats: custom_menu_->addAction(CreateHeader(icon::Video, tr("Video"))); PopulateType(Track::kVideo); custom_menu_->addSeparator(); custom_menu_->addAction(CreateHeader(icon::Audio, tr("Audio"))); PopulateType(Track::kAudio); custom_menu_->addSeparator(); custom_menu_->addAction(CreateHeader(icon::Subtitles, tr("Subtitle"))); PopulateType(Track::kSubtitle); break; case kShowAudioOnly: PopulateType(Track::kAudio); break; case kShowVideoOnly: PopulateType(Track::kVideo); break; case kShowSubtitlesOnly: PopulateType(Track::kSubtitle); break; } connect(custom_menu_, &Menu::triggered, this, &ExportFormatComboBox::HandleIndexChange); } void ExportFormatComboBox::showPopup() { custom_menu_->setMinimumWidth(this->width()); custom_menu_->exec(mapToGlobal(QPoint(0, 0))); } void ExportFormatComboBox::SetFormat(ExportFormat::Format fmt) { current_ = fmt; clear(); addItem(ExportFormat::GetName(current_)); } void ExportFormatComboBox::HandleIndexChange(QAction *a) { ExportFormat::Format f = static_cast<ExportFormat::Format>(a->data().toInt()); SetFormat(f); emit FormatChanged(f); } void ExportFormatComboBox::PopulateType(Track::Type type) { for (int i=0; i<ExportFormat::kFormatCount; i++) { ExportFormat::Format f = static_cast<ExportFormat::Format>(i); if (type == Track::kVideo && !ExportFormat::GetVideoCodecs(f).isEmpty()) { // Do nothing } else if (type == Track::kAudio && ExportFormat::GetVideoCodecs(f).isEmpty() && !ExportFormat::GetAudioCodecs(f).isEmpty()) { // Do nothing } else if (type == Track::kSubtitle && ExportFormat::GetVideoCodecs(f).isEmpty() && ExportFormat::GetAudioCodecs(f).isEmpty() && !ExportFormat::GetSubtitleCodecs(f).isEmpty()) { // Do nothing } else { continue; } QString format_name = ExportFormat::GetName(f); QAction *a = custom_menu_->addAction(format_name); a->setData(i); a->setIconVisibleInMenu(false); } } QWidgetAction *ExportFormatComboBox::CreateHeader(const QIcon &icon, const QString &title) { QWidgetAction *a = new QWidgetAction(this); QWidget *w = new QWidget(); QHBoxLayout *layout = new QHBoxLayout(w); QLabel *icon_lbl = new QLabel(); QLabel *text_lbl = new QLabel(title); text_lbl->setAlignment(Qt::AlignCenter); QFont f = text_lbl->font(); f.setWeight(QFont::Bold); text_lbl->setFont(f); icon_lbl->setPixmap(icon.pixmap(text_lbl->sizeHint())); layout->addStretch(); layout->addWidget(icon_lbl); layout->addWidget(text_lbl); layout->addStretch(); a->setDefaultWidget(w); a->setEnabled(false); return a; } }
3,785
C++
.cpp
110
30.372727
90
0.711739
olive-editor/olive
8,144
552
131
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
19,127
exportadvancedvideodialog.cpp
olive-editor_olive/app/dialog/export/exportadvancedvideodialog.cpp
#include "exportadvancedvideodialog.h" #include <QDialogButtonBox> #include <QGridLayout> #include <QGroupBox> #include <QLabel> namespace olive { ExportAdvancedVideoDialog::ExportAdvancedVideoDialog(const QList<QString> &pix_fmts, QWidget *parent) : QDialog(parent) { setWindowTitle(tr("Advanced")); QVBoxLayout* layout = new QVBoxLayout(this); { // Pixel Settings QGroupBox* pixel_group = new QGroupBox(); layout->addWidget(pixel_group); pixel_group->setTitle(tr("Pixel")); QGridLayout* pixel_layout = new QGridLayout(pixel_group); int row = 0; pixel_layout->addWidget(new QLabel(tr("Pixel Format:")), row, 0); pixel_format_combobox_ = new QComboBox(); pixel_format_combobox_->addItems(pix_fmts); pixel_layout->addWidget(pixel_format_combobox_, row, 1); row++; pixel_layout->addWidget(new QLabel(tr("YUV Color Range:")), row, 0); yuv_color_range_combobox_ = new QComboBox(); yuv_color_range_combobox_->addItems({tr("Limited (16-235)"), tr("Full (0-255)")}); pixel_layout->addWidget(yuv_color_range_combobox_, row, 1); } { // Performance Settings QGroupBox* performance_group = new QGroupBox(); layout->addWidget(performance_group); performance_group->setTitle(tr("Performance")); QGridLayout* performance_layout = new QGridLayout(performance_group); int row = 0; performance_layout->addWidget(new QLabel(tr("Threads:")), row, 0); thread_slider_ = new IntegerSlider(); thread_slider_->SetMinimum(0); thread_slider_->SetDefaultValue(0); thread_slider_->InsertLabelSubstitution(0, tr("Auto")); performance_layout->addWidget(thread_slider_, row, 1); row++; } QDialogButtonBox* buttons = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); connect(buttons, &QDialogButtonBox::accepted, this, &ExportAdvancedVideoDialog::accept); connect(buttons, &QDialogButtonBox::rejected, this, &ExportAdvancedVideoDialog::reject); layout->addWidget(buttons); } }
2,020
C++
.cpp
49
37.081633
103
0.723731
olive-editor/olive
8,144
552
131
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
19,128
exportsavepresetdialog.cpp
olive-editor_olive/app/dialog/export/exportsavepresetdialog.cpp
/*** Olive - Non-Linear Video Editor Copyright (C) 2022 Olive Team 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 <http://www.gnu.org/licenses/>. ***/ #include "exportsavepresetdialog.h" #include <QDialogButtonBox> #include <QLabel> #include <QMessageBox> #include <QVBoxLayout> namespace olive { ExportSavePresetDialog::ExportSavePresetDialog(const EncodingParams &p, QWidget *parent) : QDialog(parent), params_(p) { auto layout = new QVBoxLayout(this); name_edit_ = new QLineEdit(); // Populate existing list QStringList l = EncodingParams::GetListOfPresets(); if (!l.empty()) { auto list_widget_ = new QListWidget(); for (const QString &f : l) { list_widget_->addItem(f); } connect(list_widget_, &QListWidget::currentTextChanged, name_edit_, &QLineEdit::setText); layout->addWidget(list_widget_); } auto name_layout = new QHBoxLayout(); layout->addLayout(name_layout); name_layout->addWidget(new QLabel(tr("Name:"))); name_edit_->setFocus(); name_layout->addWidget(name_edit_); auto btns = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); connect(btns, &QDialogButtonBox::accepted, this, &ExportSavePresetDialog::accept); connect(btns, &QDialogButtonBox::rejected, this, &ExportSavePresetDialog::reject); layout->addWidget(btns); setWindowTitle(tr("Save Export Preset")); } void ExportSavePresetDialog::accept() { if (name_edit_->text().isEmpty()) { QMessageBox::critical(this, tr("Invalid Name"), tr("You must enter a name to save an export preset.")); return; } QDir d(EncodingParams::GetPresetPath()); if (!d.exists()) { d.mkpath(QStringLiteral(".")); } QFile f(d.filePath(name_edit_->text())); if (f.exists()) { if (QMessageBox::question(this, tr("Overwrite Preset"), tr("A preset with the name \"%1\" already exists. Do you wish to overwrite it?").arg(name_edit_->text()), QMessageBox::Yes | QMessageBox::No) == QMessageBox::No) { return; } } if (!f.open(QFile::WriteOnly)) { QMessageBox::critical(this, tr("Write Error"), tr("Failed to open file \"%1\" for writing.").arg(f.fileName())); return; } params_.Save(&f); f.close(); QDialog::accept(); } }
2,812
C++
.cpp
73
34.780822
165
0.710497
olive-editor/olive
8,144
552
131
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
19,129
export.cpp
olive-editor_olive/app/dialog/export/export.cpp
/*** Olive - Non-Linear Video Editor Copyright (C) 2022 Olive Team 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 <http://www.gnu.org/licenses/>. ***/ #include "export.h" #include <QCloseEvent> #include <QFileDialog> #include <QHBoxLayout> #include <QLabel> #include <QMessageBox> #include <QPushButton> #include <QScrollArea> #include <QSplitter> #include <QStandardPaths> #include "common/digit.h" #include "common/qtutils.h" #include "dialog/task/task.h" #include "exportsavepresetdialog.h" #include "node/project.h" #include "node/project/sequence/sequence.h" #include "task/taskmanager.h" #include "ui/icons/icons.h" #include "widget/timeruler/timeruler.h" namespace olive { #define super QDialog ExportDialog::ExportDialog(ViewerOutput *viewer_node, bool stills_only_mode, QWidget *parent) : super(parent), viewer_node_(viewer_node), stills_only_mode_(stills_only_mode), loading_presets_(false) { QHBoxLayout* layout = new QHBoxLayout(this); QSplitter* splitter = new QSplitter(Qt::Horizontal); splitter->setChildrenCollapsible(false); layout->addWidget(splitter); preferences_area_ = new QWidget(); QGridLayout* preferences_layout = new QGridLayout(preferences_area_); preferences_layout->setContentsMargins(0, 0, 0, 0); int row = 0; QLabel* fn_lbl = new QLabel(tr("Filename:")); fn_lbl->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Maximum); preferences_layout->addWidget(fn_lbl, row, 0); filename_edit_ = new QLineEdit(); preferences_layout->addWidget(filename_edit_, row, 1, 1, 2); QPushButton* file_browse_btn = new QPushButton(); file_browse_btn->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Maximum); file_browse_btn->setIcon(icon::Folder); file_browse_btn->setToolTip(tr("Browse for exported file filename")); connect(file_browse_btn, &QPushButton::clicked, this, &ExportDialog::BrowseFilename); preferences_layout->addWidget(file_browse_btn, row, 3); row++; QLabel* preset_lbl = new QLabel(tr("Preset:")); preset_lbl->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Maximum); preferences_layout->addWidget(preset_lbl, row, 0); preset_combobox_ = new QComboBox(); LoadPresets(); connect(preset_combobox_, static_cast<void(QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this, &ExportDialog::PresetComboBoxChanged); preferences_layout->addWidget(preset_combobox_, row, 1, 1, 2); /*QPushButton* preset_load_btn = new QPushButton(); preset_load_btn->setIcon(icon::Open); preset_load_btn->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Maximum); preferences_layout->addWidget(preset_load_btn, row, 2);*/ QPushButton* preset_save_btn = new QPushButton(); preset_save_btn->setIcon(icon::Save); preset_save_btn->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Maximum); preferences_layout->addWidget(preset_save_btn, row, 3); connect(preset_save_btn, &QPushButton::clicked, this, &ExportDialog::SavePreset); row++; preferences_layout->addWidget(QtUtils::CreateHorizontalLine(), row, 0, 1, 4); row++; preferences_layout->addWidget(new QLabel(tr("Range:")), row, 0); range_combobox_ = new QComboBox(); range_combobox_->addItem(tr("Entire Sequence")); range_combobox_->addItem(tr("In to Out")); range_combobox_->setEnabled(viewer_node_->GetWorkArea()->enabled()); preferences_layout->addWidget(range_combobox_, row, 1, 1, 3); row++; preferences_layout->addWidget(QtUtils::CreateHorizontalLine(), row, 0, 1, 4); row++; preferences_layout->addWidget(new QLabel(tr("Format:")), row, 0); format_combobox_ = new ExportFormatComboBox(); preferences_layout->addWidget(format_combobox_, row, 1, 1, 3); row++; QHBoxLayout* av_enabled_layout = new QHBoxLayout(); video_enabled_ = new QCheckBox(tr("Export Video")); av_enabled_layout->addWidget(video_enabled_); audio_enabled_ = new QCheckBox(tr("Export Audio")); av_enabled_layout->addWidget(audio_enabled_); subtitles_enabled_ = new QCheckBox(tr("Export Subtitles")); av_enabled_layout->addWidget(subtitles_enabled_); preferences_layout->addLayout(av_enabled_layout, row, 0, 1, 4); row++; preferences_tabs_ = new QTabWidget(); color_manager_ = viewer_node_->project()->color_manager(); video_tab_ = new ExportVideoTab(color_manager_); AddPreferencesTab(video_tab_, tr("Video")); // Set video tab time and make connections connect(viewer_node, &ViewerOutput::PlayheadChanged, video_tab_, &ExportVideoTab::SetTime); connect(video_tab_, &ExportVideoTab::TimeChanged, viewer_node, &ViewerOutput::SetPlayhead); video_tab_->SetTime(viewer_node->GetPlayhead()); audio_tab_ = new ExportAudioTab(); AddPreferencesTab(audio_tab_, tr("Audio")); subtitle_tab_ = new ExportSubtitlesTab(); AddPreferencesTab(subtitle_tab_, tr("Subtitles")); preferences_layout->addWidget(preferences_tabs_, row, 0, 1, 4); row++; { QGroupBox *options_group = new QGroupBox(); preferences_layout->addWidget(options_group, row, 0, 1, 4); QGridLayout *options_layout = new QGridLayout(options_group); int opt_row = 0; export_bkg_box_ = new QCheckBox(tr("Run In Background")); export_bkg_box_->setToolTip(tr("Exporting in the background allows you to continue using Olive while " "exporting, but may result in slower export speeds, and may" "severely impact editing and playback performance.")); options_layout->addWidget(export_bkg_box_, opt_row, 0); import_file_after_export_ = new QCheckBox(tr("Import Result After Export")); options_layout->addWidget(import_file_after_export_, opt_row, 1); connect(export_bkg_box_, &QCheckBox::toggled, import_file_after_export_, [this](bool e){ import_file_after_export_->setEnabled(!e); }); } row++; QHBoxLayout *btn_layout = new QHBoxLayout(); btn_layout->setContentsMargins(0, 0, 0, 0); preferences_layout->addLayout(btn_layout, row, 0, 1, 4); btn_layout->addStretch(); QPushButton *export_btn = new QPushButton(tr("Export")); btn_layout->addWidget(export_btn); connect(export_btn, &QPushButton::clicked, this, &ExportDialog::StartExport); QPushButton *cancel_btn = new QPushButton(tr("Cancel")); btn_layout->addWidget(cancel_btn); connect(cancel_btn, &QPushButton::clicked, this, &ExportDialog::reject); btn_layout->addStretch(); splitter->addWidget(preferences_area_); QWidget* preview_area = new QWidget(); QVBoxLayout* preview_layout = new QVBoxLayout(preview_area); preview_layout->addWidget(new QLabel(tr("Preview"))); preview_viewer_ = new ViewerWidget(); preview_viewer_->ruler()->SetMarkerEditingEnabled(false); preview_viewer_->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); preview_layout->addWidget(preview_viewer_); splitter->addWidget(preview_area); // Prioritize preview area splitter->setSizes({1, 99999}); // Set default filename SetDefaultFilename(); // Set defaults previously_selected_format_ = ExportFormat::kFormatMPEG4Video; connect(format_combobox_, &ExportFormatComboBox::FormatChanged, this, &ExportDialog::FormatChanged); VideoParams vp = viewer_node_->GetVideoParams(); video_aspect_ratio_ = static_cast<double>(vp.width()) / static_cast<double>(vp.height()); connect(video_tab_->width_slider(), &IntegerSlider::ValueChanged, this, &ExportDialog::ResolutionChanged); connect(video_tab_->height_slider(), &IntegerSlider::ValueChanged, this, &ExportDialog::ResolutionChanged); connect(video_tab_->scaling_method_combobox(), static_cast<void(QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this, &ExportDialog::UpdateViewerDimensions); connect(video_tab_->maintain_aspect_checkbox(), &QCheckBox::toggled, this, &ExportDialog::ResolutionChanged); connect(video_tab_, &ExportVideoTab::ColorSpaceChanged, preview_viewer_, static_cast<void(ViewerWidget::*)(const ColorTransform&)>(&ViewerWidget::SetColorTransform)); connect(video_tab_, &ExportVideoTab::ImageSequenceCheckBoxChanged, this, &ExportDialog::ImageSequenceCheckBoxChanged); // We don't check if the codec supports subtitles because we can always export to a sidecar file bool has_subtitle_tracks = SequenceHasSubtitles(); connect(subtitles_enabled_, &QCheckBox::toggled, subtitle_tab_, &QWidget::setEnabled); subtitles_enabled_->setEnabled(has_subtitle_tracks); // If the viewer already has cached params, use them if (!stills_only_mode_ && viewer_node_->GetLastUsedEncodingParams().IsValid()) { // This will automatically set the param data QtUtils::SetComboBoxData(preset_combobox_, kPresetLastUsed); } else { SetDefaults(); } // Set viewer to view the node and set its colorspace preview_viewer_->ConnectViewerNode(viewer_node_); preview_viewer_->SetColorMenuEnabled(false); preview_viewer_->SetColorTransform(video_tab_->CurrentOCIOColorSpace()); qApp->installEventFilter(this); connect(video_enabled_, &QCheckBox::toggled, video_tab_, &QWidget::setEnabled); video_tab_->setEnabled(video_enabled_->isChecked()); connect(audio_enabled_, &QCheckBox::toggled, audio_tab_, &QWidget::setEnabled); audio_tab_->setEnabled(audio_enabled_->isChecked()); connect(subtitles_enabled_, &QCheckBox::toggled, subtitle_tab_, &QWidget::setEnabled); subtitle_tab_->setEnabled(subtitles_enabled_->isChecked()); } rational ExportDialog::GetSelectedTimebase() const { return video_tab_->GetSelectedFrameRate().flipped(); } void ExportDialog::SetSelectedTimebase(const rational &r) { video_tab_->SetSelectedFrameRate(r.flipped()); } void ExportDialog::StartExport() { if (!video_enabled_->isChecked() && !audio_enabled_->isChecked() && !subtitles_enabled_->isChecked()) { QtUtils::MsgBox(this, QMessageBox::Critical, tr("Invalid parameters"), tr("Video, audio, and subtitles are disabled. There's nothing to export.")); return; } // Validate if the entered filename contains the correct extension (the extension is necessary // for both FFmpeg and OIIO to determine the output format) QString necessary_ext = QStringLiteral(".%1").arg(ExportFormat::GetExtension(format_combobox_->GetFormat())); QString proposed_filename = filename_edit_->text().trimmed(); // If it doesn't, see if the user wants to append it automatically. If not, we don't abort the export. if (!proposed_filename.endsWith(necessary_ext, Qt::CaseInsensitive)) { if (QtUtils::MsgBox(this, QMessageBox::Warning, tr("Invalid filename"), tr("The filename must contain the extension \"%1\". Would you like to append it " "automatically?").arg(necessary_ext), QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) { filename_edit_->setText(proposed_filename.append(necessary_ext)); } else { return; } } // Validate the intended path QFileInfo file_info(proposed_filename); QFileInfo dir_info(file_info.path()); // If the directory does not exist, try to create it QDir dest_dir(file_info.path()); if (!FileFunctions::DirectoryIsValid(dest_dir)) { QtUtils::MsgBox(this, QMessageBox::Critical, tr("Failed to create output directory"), tr("The intended output directory doesn't exist and Olive couldn't create it. " "Please choose a different filename.")); return; } // Validate if this is an image sequence and if the filename contains enough digits if (video_tab_->IsImageSequenceSet()) { // Ensure filename contains digits if (!Encoder::FilenameContainsDigitPlaceholder(proposed_filename)) { QtUtils::MsgBox(this, QMessageBox::Critical, tr("Invalid filename"), tr("Export is set to an image sequence, but the filename does not have a section for digits " "(formatted as [#####] where the amount of # is the amount of digits).")); return; } int64_t frame_count = GetExportLengthInTimebaseUnits(); int64_t needed_digit_count = GetDigitCount(frame_count); int current_digit_count = Encoder::GetImageSequencePlaceholderDigitCount(proposed_filename); if (current_digit_count < needed_digit_count) { QtUtils::MsgBox(this, QMessageBox::Critical, tr("Invalid filename"), tr("Filename doesn't contain enough digits for the amount of frames " "this export will need (need %1 for %n frame(s)).", nullptr, frame_count) .arg(QString::number(needed_digit_count))); return; } } // Validate if the file exists and whether the user wishes to overwrite it if (file_info.exists()) { if (QtUtils::MsgBox(this, QMessageBox::Warning, tr("Confirm Overwrite"), tr("The file \"%1\" already exists. Do you want to overwrite it?") .arg(proposed_filename), QMessageBox::Yes | QMessageBox::No) == QMessageBox::No) { return; } } // Validate video resolution if (video_enabled_->isChecked() && (video_tab_->GetSelectedCodec() == ExportCodec::kCodecH264 || video_tab_->GetSelectedCodec() == ExportCodec::kCodecH265) && (video_tab_->width_slider()->GetValue()%2 != 0 || video_tab_->height_slider()->GetValue()%2 != 0)) { QtUtils::MsgBox(this, QMessageBox::Critical, tr("Invalid Parameters"), tr("Width and height must be multiples of 2.")); return; } ExportTask* task = new ExportTask(viewer_node_, color_manager_, GenerateParams()); if (export_bkg_box_->isChecked()) { // Send to TaskManager to export in background TaskManager::instance()->AddTask(task); this->accept(); } else { // Use modal dialog box TaskDialog* td = new TaskDialog(task, tr("Export"), this); connect(td, &TaskDialog::TaskSucceeded, this, &ExportDialog::ExportFinished); td->open(); } } void ExportDialog::ExportFinished() { TaskDialog* td = static_cast<TaskDialog*>(sender()); if (td->GetTask()->IsCancelled()) { // If this task was cancelled, we stay open so the user can potentially queue another export } else { // Accept this dialog and close if (import_file_after_export_->isEnabled() && import_file_after_export_->isChecked()) { QString filename = filename_edit_->text().trimmed(); emit RequestImportFile(filename); } this->accept(); } } void ExportDialog::ImageSequenceCheckBoxChanged(bool e) { QFileInfo current_fileinfo(filename_edit_->text()); QString basename = current_fileinfo.completeBaseName(); QString suffix = current_fileinfo.suffix(); if (e) { if (!Encoder::FilenameContainsDigitPlaceholder(basename)) { basename.append(QStringLiteral("_[#####]")); } } else { basename = Encoder::FilenameRemoveDigitPlaceholder(basename); } // Set filename if (!suffix.isEmpty()) { basename.append('.'); basename.append(suffix); } filename_edit_->setText(current_fileinfo.dir().filePath(basename)); } void ExportDialog::SavePreset() { ExportSavePresetDialog d(GenerateParams(), this); if (d.exec() == QDialog::Accepted) { LoadPresets(); preset_combobox_->setCurrentText(d.GetSelectedPresetName()); } } void ExportDialog::PresetComboBoxChanged() { if (loading_presets_) { return; } QComboBox *c = static_cast<QComboBox *>(sender()); int preset_number = c->currentData().toInt(); if (preset_number == kPresetDefault) { SetDefaults(); } else if (preset_number == kPresetLastUsed) { SetParams(viewer_node_->GetLastUsedEncodingParams()); } else { SetParams(presets_.at(preset_number)); } } void ExportDialog::AddPreferencesTab(QWidget *inner_widget, const QString &title) { QScrollArea* scroll_area = new QScrollArea(); scroll_area->setWidgetResizable(true); scroll_area->setWidget(inner_widget); preferences_tabs_->addTab(scroll_area, title); } void ExportDialog::BrowseFilename() { ExportFormat::Format f = format_combobox_->GetFormat(); QString browsed_fn = QFileDialog::getSaveFileName(this, "", filename_edit_->text().trimmed(), QStringLiteral("%1 (*.%2)").arg(ExportFormat::GetName(f), ExportFormat::GetExtension(f)), nullptr, // We don't confirm overwrite here because we do it later QFileDialog::DontConfirmOverwrite); if (!browsed_fn.isEmpty()) { filename_edit_->setText(browsed_fn); } } void ExportDialog::FormatChanged(ExportFormat::Format current_format) { QString current_filename = filename_edit_->text().trimmed(); QString previously_selected_ext = ExportFormat::GetExtension(previously_selected_format_); QString currently_selected_ext = ExportFormat::GetExtension(current_format); // If the previous extension was added, remove it if (current_filename.endsWith(previously_selected_ext, Qt::CaseInsensitive)) { current_filename.resize(current_filename.size() - previously_selected_ext.size() - 1); } // Add the extension and set it current_filename.append('.'); current_filename.append(currently_selected_ext); filename_edit_->setText(current_filename); previously_selected_format_ = current_format; // Update video and audio comboboxes bool has_video_codecs = video_tab_->SetFormat(current_format); video_enabled_->setChecked(has_video_codecs); video_enabled_->setEnabled(has_video_codecs); bool has_audio_codecs = audio_tab_->SetFormat(current_format); audio_enabled_->setChecked(has_audio_codecs); audio_enabled_->setEnabled(has_audio_codecs); if (subtitles_enabled_->isEnabled()) { subtitle_tab_->SetFormat(current_format); } } void ExportDialog::ResolutionChanged() { if (video_tab_->maintain_aspect_checkbox()->isChecked()) { // Keep aspect ratio maintained if (sender() == video_tab_->height_slider()) { // Convert height to float double new_width = video_tab_->height_slider()->GetValue(); // Generate width from aspect ratio new_width *= video_aspect_ratio_; // Align to even number and set video_tab_->width_slider()->SetValue(new_width); } else { // Convert width to float double new_height = video_tab_->width_slider()->GetValue(); // Generate height from aspect ratio new_height /= video_aspect_ratio_; // Align to even number and set video_tab_->height_slider()->SetValue(new_height); } } UpdateViewerDimensions(); } void ExportDialog::LoadPresets() { loading_presets_ = true; preset_combobox_->clear(); presets_.clear(); preset_combobox_->addItem(tr("Default"), kPresetDefault); if (viewer_node_->GetLastUsedEncodingParams().IsValid()) { preset_combobox_->addItem(tr("Last Used"), kPresetLastUsed); } preset_combobox_->insertSeparator(preset_combobox_->count()); QStringList l = EncodingParams::GetListOfPresets(); presets_.reserve(l.size()); for (const QString &preset : l) { EncodingParams p; QFile f(EncodingParams::GetPresetPath().filePath(preset)); if (f.open(QFile::ReadOnly)) { if (p.Load(&f)) { preset_combobox_->addItem(preset, int(presets_.size())); presets_.push_back(p); } f.close(); } } loading_presets_ = false; } void ExportDialog::SetDefaultFilename() { Project* p = viewer_node_->project(); QDir doc_location; if (p->filename().isEmpty()) { doc_location.setPath(QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation)); } else { doc_location = QFileInfo(p->filename()).dir(); } QString file_location = doc_location.filePath(viewer_node_->GetLabel()); filename_edit_->setText(file_location); } bool ExportDialog::SequenceHasSubtitles() const { if (Sequence *s = dynamic_cast<Sequence*>(viewer_node_)) { TrackList *tl = s->track_list(Track::kSubtitle); for (Track *t : tl->GetTracks()) { if (!t->IsMuted() && !t->Blocks().empty()) { return true; } } } return false; } void ExportDialog::SetDefaults() { if (!stills_only_mode_) { format_combobox_->SetFormat(ExportFormat::kFormatMPEG4Video); } else { format_combobox_->SetFormat(ExportFormat::kFormatPNG); } FormatChanged(format_combobox_->GetFormat()); VideoParams vp = viewer_node_->GetVideoParams(); AudioParams ap = viewer_node_->GetAudioParams(); video_tab_->width_slider()->SetValue(vp.width()); video_tab_->width_slider()->SetDefaultValue(vp.width()); video_tab_->height_slider()->SetValue(vp.height()); video_tab_->height_slider()->SetDefaultValue(vp.height()); video_tab_->SetSelectedFrameRate(vp.frame_rate()); video_tab_->pixel_aspect_combobox()->SetPixelAspectRatio(vp.pixel_aspect_ratio()); video_tab_->pixel_format_field()->SetPixelFormat(static_cast<PixelFormat::Format>(OLIVE_CONFIG("OnlinePixelFormat").toInt())); video_tab_->interlaced_combobox()->SetInterlaceMode(vp.interlacing()); audio_tab_->sample_rate_combobox()->SetSampleRate(ap.sample_rate()); audio_tab_->sample_format_combobox()->SetAttemptToRestoreFormat(false); audio_tab_->channel_layout_combobox()->SetChannelLayout(ap.channel_layout()); subtitles_enabled_->setChecked(SequenceHasSubtitles()); subtitle_tab_->SetSidecarFormat(ExportFormat::kFormatSRT); } EncodingParams ExportDialog::GenerateParams() const { VideoParams video_render_params(static_cast<int>(video_tab_->width_slider()->GetValue()), static_cast<int>(video_tab_->height_slider()->GetValue()), GetSelectedTimebase(), video_tab_->pixel_format_field()->GetPixelFormat(), VideoParams::kInternalChannelCount, video_tab_->pixel_aspect_combobox()->GetPixelAspectRatio(), video_tab_->interlaced_combobox()->GetInterlaceMode(), 1); AudioParams audio_render_params(audio_tab_->sample_rate_combobox()->GetSampleRate(), audio_tab_->channel_layout_combobox()->GetChannelLayout(), audio_tab_->sample_format_combobox()->GetSampleFormat()); EncodingParams params; params.set_format(format_combobox_->GetFormat()); params.SetFilename(filename_edit_->text().trimmed()); params.SetExportLength(viewer_node_->GetLength()); if (ExportCodec::IsCodecAStillImage(video_tab_->GetSelectedCodec()) && !video_tab_->IsImageSequenceSet()) { // Exporting as image without exporting image sequence, only export one frame rational export_time = video_tab_->GetStillImageTime(); params.set_custom_range(TimeRange(export_time, export_time + GetSelectedTimebase())); } else if (range_combobox_->currentIndex() == kRangeInToOut) { // Assume if this combobox is enabled, workarea is enabled - a check that we make in this dialog's constructor params.set_custom_range(viewer_node_->GetWorkArea()->range()); } if (video_tab_->scaling_method_combobox()->isEnabled()) { params.set_video_scaling_method(static_cast<EncodingParams::VideoScalingMethod>(video_tab_->scaling_method_combobox()->currentData().toInt())); } if (video_enabled_->isChecked()) { ExportCodec::Codec video_codec = video_tab_->GetSelectedCodec(); video_render_params.set_color_range(video_tab_->color_range()); params.EnableVideo(video_render_params, video_codec); params.set_video_threads(video_tab_->threads()); if (video_tab_->isVisible()) { video_tab_->GetCodecSection()->AddOpts(&params); } params.set_color_transform(video_tab_->CurrentOCIOColorSpace()); params.set_video_pix_fmt(video_tab_->pix_fmt()); params.set_video_is_image_sequence(video_tab_->IsImageSequenceSet()); } if (audio_enabled_->isChecked()) { ExportCodec::Codec audio_codec = audio_tab_->GetCodec(); params.EnableAudio(audio_render_params, audio_codec); params.set_audio_bit_rate(audio_tab_->bit_rate_slider()->GetValue() * 1000); } if (subtitles_enabled_->isEnabled() && subtitles_enabled_->isChecked()) { if (!subtitle_tab_->GetSidecarEnabled()) { // Export subtitles embedded in container params.EnableSubtitles(subtitle_tab_->GetSubtitleCodec()); } else { // Export subtitles to a sidecar file params.EnableSidecarSubtitles(subtitle_tab_->GetSidecarFormat(), subtitle_tab_->GetSubtitleCodec()); } } return params; } void ExportDialog::SetParams(const EncodingParams &e) { format_combobox_->SetFormat(e.format()); FormatChanged(format_combobox_->GetFormat()); if (e.has_custom_range() && viewer_node_->GetWorkArea()->enabled()) { range_combobox_->setCurrentIndex(kRangeInToOut); } QtUtils::SetComboBoxData(video_tab_->scaling_method_combobox(), e.video_scaling_method()); video_enabled_->setChecked(e.video_enabled()); if (e.video_enabled()) { video_tab_->width_slider()->SetValue(e.video_params().width()); video_tab_->height_slider()->SetValue(e.video_params().height()); SetSelectedTimebase(e.video_params().time_base()); video_tab_->pixel_format_field()->SetPixelFormat(e.video_params().format()); video_tab_->pixel_aspect_combobox()->SetPixelAspectRatio(e.video_params().pixel_aspect_ratio()); video_tab_->interlaced_combobox()->SetInterlaceMode(e.video_params().interlacing()); video_tab_->SetSelectedCodec(e.video_codec()); video_tab_->SetColorRange(e.video_params().color_range()); video_tab_->SetThreads(e.video_threads()); if (video_tab_->isVisible()) { video_tab_->GetCodecSection()->SetOpts(&e); } video_tab_->SetOCIOColorSpace(e.color_transform().output()); video_tab_->SetPixFmt(e.video_pix_fmt()); video_tab_->SetImageSequence(e.video_is_image_sequence()); } audio_enabled_->setChecked(e.audio_enabled()); if (e.audio_enabled()) { audio_tab_->sample_rate_combobox()->SetSampleRate(e.audio_params().sample_rate()); audio_tab_->channel_layout_combobox()->SetChannelLayout(e.audio_params().channel_layout()); audio_tab_->sample_format_combobox()->SetSampleFormat(e.audio_params().format()); audio_tab_->SetCodec(e.audio_codec()); audio_tab_->bit_rate_slider()->SetValue(e.audio_bit_rate() / 1000); } if (subtitles_enabled_->isEnabled()) { subtitles_enabled_->setChecked(e.subtitles_enabled()); subtitle_tab_->SetSidecarEnabled(e.subtitles_are_sidecar()); if (e.subtitles_enabled()) { subtitle_tab_->SetSubtitleCodec(e.subtitles_codec()); if (e.subtitles_are_sidecar()) { subtitle_tab_->SetSidecarFormat(e.subtitle_sidecar_fmt()); } } } } bool ExportDialog::eventFilter(QObject *o, QEvent *e) { // Any parameters in scrollable areas, ignore wheel events so the user doesn't unwittingly change // them while trying to scroll through the pages if (e->type() == QEvent::Wheel) { while ((o = o->parent())) { if (o == video_tab_ || o == audio_tab_ || o == subtitle_tab_) { e->ignore(); return true; } } } return super::eventFilter(o, e); } void ExportDialog::done(int r) { preview_viewer_->ConnectViewerNode(nullptr); if (!stills_only_mode_) { viewer_node_->SetLastUsedEncodingParams(GenerateParams()); } super::done(r); } rational ExportDialog::GetExportLength() const { if (range_combobox_->currentIndex() == kRangeInToOut) { return viewer_node_->GetWorkArea()->range().length(); } else { return viewer_node_->GetLength(); } } int64_t ExportDialog::GetExportLengthInTimebaseUnits() const { return Timecode::time_to_timestamp(GetExportLength(), GetSelectedTimebase()); } void ExportDialog::UpdateViewerDimensions() { preview_viewer_->SetViewerResolution(static_cast<int>(video_tab_->width_slider()->GetValue()), static_cast<int>(video_tab_->height_slider()->GetValue())); VideoParams vp = viewer_node_->GetVideoParams(); QMatrix4x4 transform = EncodingParams::GenerateMatrix( static_cast<EncodingParams::VideoScalingMethod>(video_tab_->scaling_method_combobox()->currentData().toInt()), vp.width(), vp.height(), static_cast<int>(video_tab_->width_slider()->GetValue()), static_cast<int>(video_tab_->height_slider()->GetValue()) ); preview_viewer_->SetMatrix(transform); } }
29,514
C++
.cpp
650
39.661538
147
0.689921
olive-editor/olive
8,144
552
131
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
19,130
exportaudiotab.cpp
olive-editor_olive/app/dialog/export/exportaudiotab.cpp
/*** Olive - Non-Linear Video Editor Copyright (C) 2022 Olive Team 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 <http://www.gnu.org/licenses/>. ***/ #include "exportaudiotab.h" #include <QGridLayout> #include <QLabel> #include "core.h" namespace olive { const int ExportAudioTab::kDefaultBitRate = 320; ExportAudioTab::ExportAudioTab(QWidget* parent) : QWidget(parent) { QVBoxLayout* outer_layout = new QVBoxLayout(this); QGridLayout* layout = new QGridLayout(); outer_layout->addLayout(layout); int row = 0; layout->addWidget(new QLabel(tr("Codec:")), row, 0); codec_combobox_ = new QComboBox(); connect(codec_combobox_, static_cast<void(QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this, &ExportAudioTab::UpdateSampleFormats); connect(codec_combobox_, static_cast<void(QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this, &ExportAudioTab::UpdateBitRateEnabled); layout->addWidget(codec_combobox_, row, 1); row++; layout->addWidget(new QLabel(tr("Sample Rate:")), row, 0); sample_rate_combobox_ = new SampleRateComboBox(); layout->addWidget(sample_rate_combobox_, row, 1); row++; layout->addWidget(new QLabel(tr("Channel Layout:")), row, 0); channel_layout_combobox_ = new ChannelLayoutComboBox(); layout->addWidget(channel_layout_combobox_, row, 1); row++; layout->addWidget(new QLabel(tr("Format:")), row, 0); sample_format_combobox_ = new SampleFormatComboBox(); layout->addWidget(sample_format_combobox_, row, 1); row++; layout->addWidget(new QLabel(tr("Bit Rate:")), row, 0); bit_rate_slider_ = new IntegerSlider(); bit_rate_slider_->SetMinimum(32); bit_rate_slider_->SetMaximum(320); bit_rate_slider_->SetValue(kDefaultBitRate); bit_rate_slider_->SetFormat(tr("%1 kbps")); layout->addWidget(bit_rate_slider_, row, 1); outer_layout->addStretch(); } int ExportAudioTab::SetFormat(ExportFormat::Format format) { QList<ExportCodec::Codec> acodecs = ExportFormat::GetAudioCodecs(format); setEnabled(!acodecs.isEmpty()); codec_combobox_->blockSignals(true); codec_combobox_->clear(); foreach (ExportCodec::Codec acodec, acodecs) { codec_combobox_->addItem(ExportCodec::GetCodecName(acodec), acodec); } codec_combobox_->blockSignals(false); fmt_ = format; UpdateSampleFormats(); UpdateBitRateEnabled(); return acodecs.size(); } void ExportAudioTab::UpdateSampleFormats() { auto fmts = ExportFormat::GetSampleFormatsForCodec(fmt_, GetCodec()); sample_format_combobox_->SetAvailableFormats(fmts); } void ExportAudioTab::UpdateBitRateEnabled() { bool uses_bitrate = !ExportCodec::IsCodecLossless(GetCodec()); bit_rate_slider_->setEnabled(uses_bitrate); if (!uses_bitrate) { bit_rate_slider_->SetTristate(); } else { bit_rate_slider_->SetValue(kDefaultBitRate ); } } }
3,384
C++
.cpp
85
36.823529
143
0.746017
olive-editor/olive
8,144
552
131
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
19,131
exportsubtitlestab.cpp
olive-editor_olive/app/dialog/export/exportsubtitlestab.cpp
#include "exportsubtitlestab.h" #include <QGridLayout> namespace olive { ExportSubtitlesTab::ExportSubtitlesTab(QWidget *parent) : QWidget(parent) { QVBoxLayout* outer_layout = new QVBoxLayout(this); QGridLayout* layout = new QGridLayout(); outer_layout->addLayout(layout); int row = 0; sidecar_checkbox_ = new QCheckBox(tr("Export to sidecar file")); layout->addWidget(sidecar_checkbox_, row, 0, 1, 2); row++; sidecar_format_label_ = new QLabel(tr("Sidecar Format:")); sidecar_format_label_->setVisible(false); layout->addWidget(sidecar_format_label_, row, 0); sidecar_format_combobox_ = new ExportFormatComboBox(ExportFormatComboBox::kShowSubtitlesOnly); sidecar_format_combobox_->setVisible(true); layout->addWidget(sidecar_format_combobox_, row, 1); row++; layout->addWidget(new QLabel(tr("Codec:")), row, 0); codec_combobox_ = new QComboBox(); layout->addWidget(codec_combobox_, row, 1); outer_layout->addStretch(); connect(sidecar_checkbox_, &QCheckBox::toggled, sidecar_format_label_, &QWidget::setVisible); connect(sidecar_checkbox_, &QCheckBox::toggled, sidecar_format_combobox_, &QWidget::setVisible); } int ExportSubtitlesTab::SetFormat(ExportFormat::Format format) { auto vcodecs = ExportFormat::GetVideoCodecs(format); auto acodecs = ExportFormat::GetAudioCodecs(format); auto scodecs = ExportFormat::GetSubtitleCodecs(format); if (!scodecs.empty() && vcodecs.empty() && acodecs.empty()) { // If format supports ONLY scodecs, default this to off and disable it sidecar_checkbox_->setChecked(false); sidecar_checkbox_->setEnabled(false); } else { // If format does not support scodecs, default this to checked and disable it sidecar_checkbox_->setChecked(scodecs.empty()); sidecar_checkbox_->setEnabled(!scodecs.empty()); } scodecs = ExportFormat::GetSubtitleCodecs(sidecar_format_combobox_->GetFormat()); codec_combobox_->clear(); foreach (ExportCodec::Codec scodec, scodecs) { codec_combobox_->addItem(ExportCodec::GetCodecName(scodec), scodec); } return scodecs.size(); } }
2,102
C++
.cpp
49
39.591837
98
0.745571
olive-editor/olive
8,144
552
131
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
19,132
h264section.cpp
olive-editor_olive/app/dialog/export/codec/h264section.cpp
/*** Olive - Non-Linear Video Editor Copyright (C) 2022 Olive Team 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 <http://www.gnu.org/licenses/>. ***/ #include "h264section.h" #include <QCheckBox> #include <QComboBox> #include <QGridLayout> #include <QLabel> #include "common/qtutils.h" #include "widget/slider/integerslider.h" namespace olive { H264Section::H264Section(QWidget *parent) : H264Section(H264CRFSection::kDefaultH264CRF, parent) { } H264Section::H264Section(int default_crf, QWidget *parent) : CodecSection(parent) { QGridLayout* layout = new QGridLayout(this); layout->setContentsMargins(0, 0, 0, 0); int row = 0; layout->addWidget(new QLabel(tr("Encode Speed:")), row, 0); preset_combobox_ = new QComboBox(); preset_combobox_->setToolTip(tr("This setting allows you to tweak the ratio of export speed to compression quality. \n\n" "If using Constant Rate Factor, slower speeds will result in smaller file sizes for the same quality. \n\n" "If using Target Bit Rate or Target File Size, slower speeds will result in higher quality for the same bitrate/filesize. \n\n" "This setting is equivalent to the `preset` setting in libx264.")); preset_combobox_->addItem(tr("Ultra Fast")); preset_combobox_->addItem(tr("Super Fast")); preset_combobox_->addItem(tr("Very Fast")); preset_combobox_->addItem(tr("Faster")); preset_combobox_->addItem(tr("Fast")); preset_combobox_->addItem(tr("Medium")); preset_combobox_->addItem(tr("Slow")); preset_combobox_->addItem(tr("Slower")); preset_combobox_->addItem(tr("Very Slow")); //Default to "medium" preset_combobox_->setCurrentIndex(5); layout->addWidget(preset_combobox_, row, 1); row++; layout->addWidget(new QLabel(tr("Compression Method:")), row, 0); QComboBox* compression_box = new QComboBox(); // These items must correspond to the CompressionMethod enum compression_box->addItem(tr("Constant Rate Factor")); compression_box->addItem(tr("Target Bit Rate")); compression_box->addItem(tr("Target File Size")); layout->addWidget(compression_box, row, 1); row++; compression_method_stack_ = new QStackedWidget(); layout->addWidget(compression_method_stack_, row, 0, 1, 2); crf_section_ = new H264CRFSection(default_crf); compression_method_stack_->addWidget(crf_section_); bitrate_section_ = new H264BitRateSection(); compression_method_stack_->addWidget(bitrate_section_); filesize_section_ = new H264FileSizeSection(); compression_method_stack_->addWidget(filesize_section_); connect(compression_box, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), compression_method_stack_, &QStackedWidget::setCurrentIndex); } void H264Section::AddOpts(EncodingParams *params) { // FIXME: Implement two-pass CompressionMethod method = static_cast<CompressionMethod>(compression_method_stack_->currentIndex()); // This option is not used by the encoder (nor is anything with the ove_ prefix), it's to help us // identify which option was chosen when params are restored params->set_video_option(QStringLiteral("ove_compressionmethod"), QString::number(method)); if (method == kConstantRateFactor) { // Simply set CRF value params->set_video_option(QStringLiteral("crf"), QString::number(crf_section_->GetValue())); } else { int64_t target_rate, max_rate, min_rate; if (method == kTargetBitRate) { // Use user-supplied values for the bit rate target_rate = bitrate_section_->GetTargetBitRate(); min_rate = 0; max_rate = bitrate_section_->GetMaximumBitRate(); } else { // Calculate the bit rate from the file size divided by the sequence length in seconds (bits per second) int64_t target_fs = filesize_section_->GetFileSize(); target_rate = qRound64(static_cast<double>(target_fs) / params->GetExportLength().toDouble()); min_rate = target_rate; max_rate = target_rate; params->set_video_option(QStringLiteral("ove_targetfilesize"), QString::number(target_fs)); } // Disable CRF encoding params->set_video_option(QStringLiteral("crf"), QStringLiteral("-1")); params->set_video_bit_rate(target_rate); params->set_video_min_bit_rate(min_rate); params->set_video_max_bit_rate(max_rate); params->set_video_buffer_size(2000000); } params->set_video_option(QStringLiteral("preset"), QString::number(preset_combobox_->currentIndex())); } void H264Section::SetOpts(const EncodingParams *p) { CompressionMethod method = static_cast<CompressionMethod>(p->video_option(QStringLiteral("ove_compressionmethod")).toInt()); compression_method_stack_->setCurrentIndex(method); if (method == kConstantRateFactor) { crf_section_->SetValue(p->video_option(QStringLiteral("crf")).toInt()); } else { int64_t target_rate = p->video_bit_rate(); int64_t max_rate = p->video_max_bit_rate(); if (method == kTargetBitRate) { // Use user-supplied values for the bit rate bitrate_section_->SetTargetBitRate(target_rate); bitrate_section_->SetMaximumBitRate(max_rate); } else { // Calculate the bit rate from the file size divided by the sequence length in seconds (bits per second) filesize_section_->SetFileSize(p->video_option(QStringLiteral("ove_targetfilesize")).toLongLong()); } } } H264CRFSection::H264CRFSection(int default_crf, QWidget *parent) : QWidget(parent) { QHBoxLayout* layout = new QHBoxLayout(this); layout->setContentsMargins(0, 0, 0, 0); crf_slider_ = new QSlider(Qt::Horizontal); crf_slider_->setMinimum(kMinimumCRF); crf_slider_->setMaximum(kMaximumCRF); crf_slider_->setValue(default_crf); layout->addWidget(crf_slider_); IntegerSlider* crf_input = new IntegerSlider(); crf_input->setMaximumWidth(QtUtils::QFontMetricsWidth(crf_input->fontMetrics(), QStringLiteral("HHHH"))); crf_input->SetMinimum(kMinimumCRF); crf_input->SetMaximum(kMaximumCRF); crf_input->SetValue(default_crf); crf_input->SetDefaultValue(default_crf); layout->addWidget(crf_input); connect(crf_slider_, &QSlider::valueChanged, crf_input, &IntegerSlider::SetValue); connect(crf_input, &IntegerSlider::ValueChanged, crf_slider_, &QSlider::setValue); } int H264CRFSection::GetValue() const { return crf_slider_->value(); } void H264CRFSection::SetValue(int c) { crf_slider_->setValue(c); } H264BitRateSection::H264BitRateSection(QWidget *parent) : QWidget(parent) { QGridLayout* layout = new QGridLayout(this); layout->setContentsMargins(0, 0, 0, 0); int row = 0; layout->addWidget(new QLabel(tr("Target Bit Rate (Mbps):")), row, 0); target_rate_ = new FloatSlider(); target_rate_->SetMinimum(0); layout->addWidget(target_rate_, row, 1); row++; layout->addWidget(new QLabel(tr("Maximum Bit Rate (Mbps):")), row, 0); max_rate_ = new FloatSlider(); max_rate_->SetMinimum(0); layout->addWidget(max_rate_, row, 1); row++; layout->addWidget(new QLabel(tr("Two-Pass")), row, 0); QCheckBox* two_pass_box = new QCheckBox(); layout->addWidget(two_pass_box, row, 1); // Bit rate defaults target_rate_->SetValue(16.0); max_rate_->SetValue(32.0); } int64_t H264BitRateSection::GetTargetBitRate() const { return qRound64(target_rate_->GetValue() * 1000000.0); } void H264BitRateSection::SetTargetBitRate(int64_t b) { target_rate_->SetValue(double(b) * 0.000001); } int64_t H264BitRateSection::GetMaximumBitRate() const { return qRound64(max_rate_->GetValue() * 1000000.0); } void H264BitRateSection::SetMaximumBitRate(int64_t b) { max_rate_->SetValue(double(b) * 0.000001); } H264FileSizeSection::H264FileSizeSection(QWidget *parent) : QWidget(parent) { QGridLayout* layout = new QGridLayout(this); layout->setContentsMargins(0, 0, 0, 0); int row = 0; layout->addWidget(new QLabel(tr("Target File Size (MB):")), row, 0); file_size_ = new FloatSlider(); file_size_->SetMinimum(0); layout->addWidget(file_size_, row, 1); row++; layout->addWidget(new QLabel(tr("Two-Pass")), row, 0); QCheckBox* two_pass_box = new QCheckBox(); layout->addWidget(two_pass_box, row, 1); // File size defaults file_size_->SetValue(700.0); } int64_t H264FileSizeSection::GetFileSize() const { // Convert megabytes to BITS return qRound64(file_size_->GetValue() * 1024.0 * 1024.0 * 8.0); } void H264FileSizeSection::SetFileSize(int64_t f) { // Convert bits back to megabytes file_size_->SetValue(double(f) / 8.0 / 1024.0 / 1024.0); } H265Section::H265Section(QWidget *parent) : H264Section(H264CRFSection::kDefaultH265CRF, parent) { } }
9,192
C++
.cpp
224
37.651786
131
0.729021
olive-editor/olive
8,144
552
131
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false