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
13,036
InputEvents.h
xournalpp_xournalpp/src/core/gui/inputdevices/InputEvents.h
/* * Xournal++ * * [Header description] * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <memory> // for shared_ptr #include <string> // for string #include <gdk/gdk.h> // for GdkEvent, gdk_event_free, gdk_event_copy #include <glib.h> // for gdouble, gchar, guint, guint32 #include "model/Point.h" // for Point, Point::NO_PRESSURE #include "DeviceId.h" class Settings; enum InputEventType { UNKNOWN, BUTTON_PRESS_EVENT, BUTTON_2_PRESS_EVENT, BUTTON_3_PRESS_EVENT, BUTTON_RELEASE_EVENT, MOTION_EVENT, ENTER_EVENT, LEAVE_EVENT, PROXIMITY_IN_EVENT, PROXIMITY_OUT_EVENT, SCROLL_EVENT, GRAB_BROKEN_EVENT, KEY_PRESS_EVENT, KEY_RELEASE_EVENT }; enum InputDeviceClass { INPUT_DEVICE_MOUSE, INPUT_DEVICE_PEN, INPUT_DEVICE_ERASER, INPUT_DEVICE_TOUCHSCREEN, INPUT_DEVICE_KEYBOARD, INPUT_DEVICE_MOUSE_KEYBOARD_COMBO, INPUT_DEVICE_IGNORE }; struct GdkEventGuard { static inline GdkEvent* safeRef(GdkEvent* source) { return gdk_event_copy(source); } GdkEventGuard() = default; [[maybe_unused]] explicit GdkEventGuard(GdkEvent* source): event(safeRef(source), &gdk_event_free) {} GdkEventGuard& operator=(GdkEvent* source) { event = {safeRef(source), &gdk_event_free}; return *this; } operator GdkEvent*() const { return event.get(); } // it's more performant to manage the GdkEvent over C++ than over gdk // Since the gdk_copy is extreme expansive std::shared_ptr<GdkEvent> event{}; }; struct InputEvent final { /*explicit(false)*/ explicit operator bool() const { return !!sourceEvent.event; } GdkEventGuard sourceEvent; InputEventType type{UNKNOWN}; InputDeviceClass deviceClass{INPUT_DEVICE_IGNORE}; const gchar* deviceName{}; gdouble absoluteX{0}; gdouble absoluteY{0}; gdouble relativeX{0}; gdouble relativeY{0}; guint button{0}; GdkModifierType state{}; gdouble pressure{Point::NO_PRESSURE}; GdkEventSequence* sequence{}; guint32 timestamp{0}; DeviceId deviceId; }; struct KeyEvent final { guint keyval{0}; GdkModifierType state{}; ///< Consumed modifiers have been masked out GdkEventGuard sourceEvent; ///< Original GdkEvent. Avoid using if possible. }; class InputEvents { static InputEventType translateEventType(GdkEventType type); public: static InputDeviceClass translateDeviceType(GdkDevice* device, Settings* settings); static InputDeviceClass translateDeviceType(const std::string& name, GdkInputSource source, Settings* settings); static InputEvent translateEvent(GdkEvent* sourceEvent, Settings* settings); };
2,760
C++
.h
85
28.411765
116
0.720921
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
13,037
CompassInputHandler.h
xournalpp_xournalpp/src/core/gui/inputdevices/CompassInputHandler.h
/* * Xournal++ * * Input handler for the compass. * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include "GeometryToolInputHandler.h" class Stroke; class GeometryToolController; struct InputEvent; /** * @brief Input handler for the compass * * Only the pointer handling (mouse / stylus) is defined in this class. * The rest comes from the GeometryToolHandler * */ class CompassInputHandler: public GeometryToolInputHandler { public: explicit CompassInputHandler(XournalView* xournalView, GeometryToolController* controller); ~CompassInputHandler() noexcept override; private: /** * @brief handles input from mouse and stylus for the compass */ bool handlePointer(InputEvent const& event) override; double lastProj = NAN; double getMinHeight() const override; double getMaxHeight() const override; };
930
C++
.h
34
24.588235
95
0.760135
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
13,038
SetsquareInputHandler.h
xournalpp_xournalpp/src/core/gui/inputdevices/SetsquareInputHandler.h
/* * Xournal++ * * Input handler for the setsquare. * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include "GeometryToolInputHandler.h" class Stroke; class GeometryToolController; struct InputEvent; /** * @brief Input handler for the setsquare * * Only the pointer handling (mouse / stylus) is defined in this class. * The rest comes from the GeometryToolInputHandler * */ class SetsquareInputHandler: public GeometryToolInputHandler { public: explicit SetsquareInputHandler(XournalView* xournalView, GeometryToolController* controller); ~SetsquareInputHandler() noexcept override; private: /** * @brief handles input from mouse and stylus for the setsquare */ bool handlePointer(InputEvent const& event) override; double getMinHeight() const override; double getMaxHeight() const override; };
919
C++
.h
33
25.181818
97
0.767918
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
13,039
AbstractInputHandler.h
xournalpp_xournalpp/src/core/gui/inputdevices/AbstractInputHandler.h
/* * Xournal++ * * [Header description] * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include "PositionInputData.h" // for PositionInputData class InputContext; class XojPageView; struct InputEvent; /** * Abstract class for a specific input state */ class AbstractInputHandler { private: bool blocked = false; protected: InputContext* inputContext; bool inputRunning = false; protected: XojPageView* getPageAtCurrentPosition(InputEvent const& event) const; PositionInputData getInputDataRelativeToCurrentPage(XojPageView* page, InputEvent const& event) const; public: explicit AbstractInputHandler(InputContext* inputContext); virtual ~AbstractInputHandler(); void block(bool block); bool isBlocked() const; virtual void onBlock(); virtual void onUnblock(); bool handle(InputEvent const& event); virtual bool handleImpl(InputEvent const& event) = 0; };
996
C++
.h
37
24
106
0.763407
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
13,040
KeyboardInputHandler.h
xournalpp_xournalpp/src/core/gui/inputdevices/KeyboardInputHandler.h
/* * Xournal++ * * [Header description] * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once class InputContext; struct KeyEvent; class KeyboardInputHandler final { private: public: explicit KeyboardInputHandler(InputContext* inputContext); ~KeyboardInputHandler(); bool keyPressed(KeyEvent e) const; bool keyReleased(KeyEvent e) const; private: InputContext* inputContext; };
473
C++
.h
23
18.130435
62
0.76009
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
13,041
TouchDrawingInputHandler.h
xournalpp_xournalpp/src/core/gui/inputdevices/TouchDrawingInputHandler.h
/* * Xournal++ * * [Header description] * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <gdk/gdk.h> // for GdkEventSequence #include "PenInputHandler.h" // for PenInputHandler class InputContext; struct InputEvent; class TouchDrawingInputHandler: public PenInputHandler { private: GdkEventSequence* primarySequence = nullptr; GdkEventSequence* secondarySequence = nullptr; public: explicit TouchDrawingInputHandler(InputContext* inputContext); ~TouchDrawingInputHandler() override; bool handleImpl(InputEvent const& event) override; protected: /** * @brief Change the tool according to Touch Settings * * @param event some Inputevent * @return true if tool was changed successfully * @return false if tool was not changed successfully */ bool changeTool(InputEvent const& event) override; private: void updateKineticScrollingEnabled(); };
998
C++
.h
35
25.228571
66
0.754717
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
13,042
PositionInputData.h
xournalpp_xournalpp/src/core/gui/inputdevices/PositionInputData.h
/* * Xournal++ * * Base class for device input handling * Data to do an input * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <gdk/gdk.h> // for GdkModifierType #include <glib.h> // for guint32 #include "DeviceId.h" class PositionInputData { public: bool isShiftDown() const; bool isControlDown() const; bool isAltDown() const; public: double x; double y; double pressure; guint32 timestamp; DeviceId deviceId; /** * State flags from GDKevent (Shift down etc.) */ GdkModifierType state; };
638
C++
.h
31
17.451613
50
0.685524
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
13,043
InputContext.h
xournalpp_xournalpp/src/core/gui/inputdevices/InputContext.h
/* * Xournal++ * * [Header description] * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <memory> // for unique_ptr #include <set> // for set #include <string> // for string #include <gdk/gdk.h> // for GdkEvent, GdkModifierType #include <glib.h> // for gulong #include <gtk/gtk.h> // for GtkWidget #include "gui/widgets/XournalWidget.h" // for GtkXournal class GeometryToolInputHandler; class KeyboardInputHandler; class MouseInputHandler; class ScrollHandling; class Settings; class StylusInputHandler; class ToolHandler; class TouchDrawingInputHandler; class TouchInputHandler; class XournalView; class InputContext final { private: gulong signal_id{0}; StylusInputHandler* stylusHandler; MouseInputHandler* mouseHandler; TouchDrawingInputHandler* touchDrawingHandler; KeyboardInputHandler* keyboardHandler; TouchInputHandler* touchHandler; std::unique_ptr<GeometryToolInputHandler> geometryToolInputHandler; GtkWidget* widget = nullptr; XournalView* view; ScrollHandling* scrollHandling; GdkModifierType modifierState = (GdkModifierType)0; std::set<std::string> knownDevices; public: enum DeviceType { MOUSE, STYLUS, TOUCHSCREEN, }; public: InputContext(XournalView* view, ScrollHandling* scrollHandling); ~InputContext(); private: /** * Callback used by Glib to notify for new events * @param widget The widget the event happened in * @param event The event * @param self A pointer to our handler * @return Whether the event was handled */ static bool eventCallback(GtkWidget* widget, GdkEvent* event, InputContext* self); /** * Handle the events * @param event The event to handle * @return Whether the event was handled */ bool handle(GdkEvent* event); /** * Print debug output */ void printDebug(GdkEvent* event); public: /** * Connect the input handling to the window to receive events */ void connect(GtkWidget* widget); GtkXournal* getXournal(); XournalView* getView(); ToolHandler* getToolHandler(); Settings* getSettings(); ScrollHandling* getScrollHandling(); void setGeometryToolInputHandler(std::unique_ptr<GeometryToolInputHandler> handler); GeometryToolInputHandler* getGeometryToolInputHandler() const; void resetGeometryToolInputHandler(); GdkModifierType getModifierState(); void focusWidget(); void blockDevice(DeviceType deviceType); void unblockDevice(DeviceType deviceType); bool isBlocked(DeviceType deviceType); };
2,700
C++
.h
89
26.303371
88
0.736497
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
13,044
GeometryToolInputHandler.h
xournalpp_xournalpp/src/core/gui/inputdevices/GeometryToolInputHandler.h
/* * Xournal++ * * Input handler for the geometry tool. * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <map> // for map #include <vector> // for vector #include <gdk/gdk.h> // for GdkEventSequence #include "util/DispatchPool.h" // for xoj::util::Listener #include "util/Point.h" // for Point #include "InputContext.h" // for InputContext::DeviceType, InputContext class Stroke; class GeometryToolController; struct InputEvent; struct KeyEvent; /** * @brief Input handler for the geometry tool * * The geometry tool is designed to be used with touch/keyboard with one hand and mouse/stylus with the other hand * Keyboard and Touch are used to move the geometry tool (and the page), to rotate it and change its size, whereas * Stylus/Mouse are used to draw/annotate. * * The touch handling part is adopted from the TouchInputHandler class */ class GeometryToolInputHandler: public xoj::util::Listener<GeometryToolInputHandler> { protected: /** * @brief the XournalView attached to this handler */ XournalView* xournal; /** * @brief the geometry tool controller * */ GeometryToolController* controller; double height; double rotation = 0.; double translationX; double translationY; /** * @brief saves which devices are blocked, so they don't need to be handled * This is currently used for the automatic hand recognition, that can be turned on in the settings */ std::map<InputContext::DeviceType, bool> isBlocked{}; /** * @brief the touch event sequence corresponding to the first finger touching the screen */ GdkEventSequence* primarySequence{}; /** * @brief the touch event sequence corresponding to the second finger touching the screen */ GdkEventSequence* secondarySequence{}; /** * @brief the distance between the two fingers touching the screen at the start of a zoom sequence */ double startZoomDistance{0.0}; /** * @brief the previous mid point between the two fingers in a zoom sequence */ xoj::util::Point<double> lastZoomScrollCenter{}; /** * @brief The current positions of the first (primary) finger and second (secondary) finger in page coordinates */ xoj::util::Point<double> priLastPageRel{-1.0, -1.0}; xoj::util::Point<double> secLastPageRel{-1.0, -1.0}; /** * @brief The previous angle between the line through the positions of the two fingers and the x-axis */ double lastAngle{0.0}; /** * @brief The previous distance between the two fingers touching the screen */ double lastDist{1.0}; /** * @brief whether resizing the geometry tool can be blocked, because the distance between the fingers hasn't changed * enough */ bool canBlockZoom{false}; /** * @brief whether a scrolling for the hand tool takes place (after touching the geometry tool with the hand tool) */ bool handScrolling{false}; /** * @brief the line segments (strokes with two points) of the current layer, that are used for rotation snapping the * geometry tool */ std::vector<Stroke*> lines; protected: /** * @brief initializes an input sequence (right after the first or second finger is put onto the screen) * @param event the input event initializing the sequence */ void sequenceStart(InputEvent const& event); /** * @brief scrolling method * @param event the current input event */ void scrollMotion(InputEvent const& event); /** * @brief start rotating and zooming (after the second finger is put onto the screen) * only zooms, when zoom gestures are enabled */ void rotateAndZoomStart(); /** * @brief rotation and zooming method, only zooms when zoom gestures are enabled * @param event the current input event */ void rotateAndZoomMotion(InputEvent const& event); /** * @brief handles input from the touchscreen for the geometry tool */ bool handleTouchscreen(InputEvent const& event); /** * @brief handles input from mouse and stylus for the geometry tool */ virtual bool handlePointer(InputEvent const& event) = 0; /** * @brief the document coordinates derived from an input event * @param event an input event */ xoj::util::Point<double> getCoords(InputEvent const& event); virtual double getMinHeight() const = 0; virtual double getMaxHeight() const = 0; public: explicit GeometryToolInputHandler(XournalView* xournalView, GeometryToolController* controller, double h, double tx, double ty); virtual ~GeometryToolInputHandler(); bool handle(InputEvent const& event); void blockDevice(InputContext::DeviceType deviceType); void unblockDevice(InputContext::DeviceType deviceType); bool keyPressed(KeyEvent const& event); // bool keyReleased(KeyEvent const& event); // Implement if needed /** * Listener interface */ static constexpr struct UpdateValuesRequest { } UPDATE_VALUES = {}; void on(UpdateValuesRequest, double h, double rot, double tx, double ty); };
5,332
C++
.h
145
31.813793
120
0.697575
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
13,045
TouchDisableInterface.h
xournalpp_xournalpp/src/core/gui/inputdevices/touchdisable/TouchDisableInterface.h
/* * Xournal++ * * Interface for touch disable implementations * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once class TouchDisableInterface { public: TouchDisableInterface(); virtual ~TouchDisableInterface(); public: virtual void enableTouch() = 0; virtual void disableTouch() = 0; virtual void init(); private: };
416
C++
.h
21
17.190476
46
0.725641
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
13,046
TouchDisableCustom.h
xournalpp_xournalpp/src/core/gui/inputdevices/touchdisable/TouchDisableCustom.h
/* * Xournal++ * * Interface for touch disable implementations * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <string> // for string #include "TouchDisableInterface.h" // for TouchDisableInterface class TouchDisableCustom: public TouchDisableInterface { public: TouchDisableCustom(std::string enableCommand, std::string disableCommand); ~TouchDisableCustom() override; public: void enableTouch() override; void disableTouch() override; private: std::string enableCommand; std::string disableCommand; };
623
C++
.h
24
23.291667
78
0.763514
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
13,047
TouchDisableX11.h
xournalpp_xournalpp/src/core/gui/inputdevices/touchdisable/TouchDisableX11.h
/* * Xournal++ * * Interface for touch disable implementations * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #ifdef X11_ENABLED #include <X11/X.h> // for Atom, None #include <X11/Xlib.h> // for Display #include <X11/extensions/XInput.h> // for XDevice, XDeviceInfo #include "TouchDisableInterface.h" // for TouchDisableInterface class TouchDisableX11: public TouchDisableInterface { public: TouchDisableX11(); virtual ~TouchDisableX11(); public: virtual void enableTouch(); virtual void disableTouch(); virtual void init(); private: /** * X11 Display */ Display* display = nullptr; /** * Touch device ID */ Atom touchAtom = None; /** * Touch device */ XDeviceInfo* touch = nullptr; /** * Touch device */ XDevice* touchdev = nullptr; /** * Enable flag */ Atom enabledAtom = None; }; #endif
1,024
C++
.h
47
17.978723
64
0.639004
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
13,048
SetsquareView.h
xournalpp_xournalpp/src/core/view/SetsquareView.h
/* * Xournal++ * * A setsquare view * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <cmath> #include <cairo.h> // for cairo_t #include "model/Setsquare.h" // for Setsquare #include "util/DispatchPool.h" #include "view/overlays/BaseStrokeToolView.h" #include "GeometryToolView.h" class Stroke; class OverlayBase; class ZoomControl; /** * @brief A class that renders a setsquare * * The setsquare has vertical, horizontal and angular marks. * The intersection angle with the x-axis is displayed as well. * * See the file development/documentation/Setsquare_Readme.md for * details how the setsquare is rendered. * * A temporary stroke is displayed when it is created near the * longest side of the setsquare or from a point to the mid point * of the longest side of the setsquare. */ namespace xoj::view { class Repaintable; class SetsquareView: public GeometryToolView { public: SetsquareView(const Setsquare* s, Repaintable* parent, ZoomControl* zoomControl); ~SetsquareView() noexcept override; void on(FlagDirtyRegionRequest, const Range& rg) override; void on(UpdateValuesRequest, double h, double rot, cairo_matrix_t m) override; void deleteOn(FinalizationRequest, const Range& rg) override; private: void drawGeometryTool(cairo_t* cr) const override; void drawDisplays(cairo_t* cr) const override; double height = Setsquare::INITIAL_HEIGHT; double rotation = 0.; cairo_matrix_t matrix{CM, 0., 0., CM, 0., 0.}; /** * @brief the radius of the semi-circle for the angular marks */ double radius = 4.5; /** * @brief the distance of the circle containing the rotation angle display from the mid point of the longest side of * the setsquare */ double circlePos = 6.0; /** * @brief the distance (in cm) of the vertical marks from the symmetry axis of the setsquare */ double horPosVmarks = 2.5; /** * @brief the index of the first vertical mark which should be drawn (which should not overlap with the measuring * marks) */ int minVmark = 3; /** * @brief the index of the last vertical mark to be drawn */ int maxVmark = 35; /** * @brief the number of angular marks that are left away on both ends (in order not to overlap with the measuring * marks) */ int offset = 4; /** * @brief the index of the last horizontal mark to be drawn */ int maxHmark = 70; void drawVerticalMarks(cairo_t* cr) const; void drawHorizontalMarks(cairo_t* cr) const; void drawAngularMarks(cairo_t* cr) const; void drawOutline(cairo_t* cr) const; void drawRotation(cairo_t* cr) const; void clipVerticalStripes(cairo_t* cr) const; void clipHorizontalStripes(cairo_t* cr) const; public: static constexpr double LINE_WIDTH_IN_CM = .02; }; }; // namespace xoj::view
2,972
C++
.h
90
29.166667
120
0.709339
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
13,049
TexImageView.h
xournalpp_xournalpp/src/core/view/TexImageView.h
/* * Xournal++ * * Displays a TexImage Element * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include "View.h" class TexImage; class xoj::view::TexImageView: public xoj::view::ElementView { public: TexImageView(const TexImage* texImage); virtual ~TexImageView(); /** * Draws a TexImage model */ void draw(const Context& ctx) const override; private: const TexImage* texImage; };
494
C++
.h
24
17.708333
62
0.702586
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
13,050
ImageView.h
xournalpp_xournalpp/src/core/view/ImageView.h
/* * Xournal++ * * Displays a Image Element * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include "View.h" class Image; class xoj::view::ImageView: public xoj::view::ElementView { public: ImageView(const Image* image); virtual ~ImageView(); /** * Draws an Image element */ void draw(const Context& ctx) const override; private: const Image* image; };
467
C++
.h
24
16.583333
59
0.684211
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
13,051
CompassView.h
xournalpp_xournalpp/src/core/view/CompassView.h
/* * Xournal++ * * A Compass view * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <cairo.h> // for cairo_t #include "model/Compass.h" // for Compass #include "util/DispatchPool.h" #include "util/safe_casts.h" // for floor_cast #include "view/overlays/BaseStrokeToolView.h" #include "GeometryToolView.h" class Stroke; class OverlayBase; class ZoomControl; /** * @brief A class that renders a compass * * The compass has vertical, horizontal and angular marks. * The intersection angle with the x-axis is displayed as well. * * See the file development/documentation/Compass_Readme.md for * details how the Compass is rendered. * * A temporary stroke is displayed when it is created near the * outline of the Compass or at the marked radius (with angle 0). */ namespace xoj::view { class Repaintable; class CompassView: public GeometryToolView { public: CompassView(const Compass* s, Repaintable* parent, ZoomControl* zoomControl); ~CompassView() noexcept override; void on(FlagDirtyRegionRequest, const Range& rg) override; void on(UpdateValuesRequest, double h, double rot, cairo_matrix_t m) override; void deleteOn(FinalizationRequest, const Range& rg) override; private: void drawGeometryTool(cairo_t* cr) const override; void drawDisplays(cairo_t* cr) const override; double height = Compass::INITIAL_HEIGHT; double rotation = 0.; cairo_matrix_t matrix{CM, 0., 0., CM, 0., 0.}; /** * @brief the distance of the circle containing the rotation angle display from the center * of the compass */ double circlePos = 2.; /** * @brief the distance of the angular captions (written numbers) for certain angles */ double angularCaptionPos = .9; /** * @brief the index of the last horizontal mark to be drawn */ int maxHmark = floor_cast<int>(10. * Compass::INITIAL_HEIGHT); /** * @brief after how many degrees should a new small angular mark be drawn */ int angularOffset = 1; /** * @brief after how many degrees should a new big angular mark be drawn and a number be added */ int angularCaptionOffset = 30; /** * @brief should the numbers along the measuring marks be drawn */ bool drawRadialCaption = true; /** * @brief should the display of the rotation be drawn */ bool drawRotationDisplay = true; void drawHorizontalMarks(cairo_t* cr) const; void drawAngularMarks(cairo_t* cr) const; void drawOutline(cairo_t* cr) const; void drawRotation(cairo_t* cr) const; public: static constexpr double LINE_WIDTH_IN_CM = .02; }; }; // namespace xoj::view
2,756
C++
.h
84
29.047619
97
0.709921
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
13,052
TextView.h
xournalpp_xournalpp/src/core/view/TextView.h
/* * Xournal++ * * Displays a text Element * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <string> // for string #include <vector> // for vector #include <pango/pangocairo.h> // for PangoLayout, cairo_t #include "util/raii/GObjectSPtr.h" #include "View.h" // for ElementView class Text; class xoj::view::TextView: public xoj::view::ElementView { public: TextView(const Text* t); virtual ~TextView(); /** * Draws a Text model to a cairo surface */ void draw(const Context& ctx) const override; /** * Initialize a Pango layout */ static xoj::util::GObjectSPtr<PangoLayout> initPango(cairo_t* cr, const Text* t); private: const Text* text; };
789
C++
.h
32
21.5625
85
0.682731
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
13,053
StrokeViewHelper.h
xournalpp_xournalpp/src/core/view/StrokeViewHelper.h
/* * Xournal++ * * Draw stroke * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <vector> #include <cairo.h> class LineStyle; class Point; namespace xoj::view::StrokeViewHelper { /** * @brief Simply adds the points to a cairo context, as a single path */ void pathToCairo(cairo_t* cr, const std::vector<Point>& pts); /** * @brief No pressure sensitivity, one line is drawn, with given width and line style (dashes) */ void drawNoPressure(cairo_t* cr, const std::vector<Point>& pts, const double strokeWidth, const LineStyle& lineStyle, double dashOffset = 0); /** * @brief Draw a stroke with pressure, for this multiple lines with different widths needs to be drawn. * @return New dash offset, if one wants to keep on drawing the same stroke. * Effectively, the return value equals dashOffset + length of the path. */ double drawWithPressure(cairo_t* cr, const std::vector<Point>& pts, const LineStyle& lineStyle, double dashOffset = 0); }; // namespace xoj::view::StrokeViewHelper
1,108
C++
.h
32
32.21875
119
0.727528
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
13,054
GeometryToolView.h
xournalpp_xournalpp/src/core/view/GeometryToolView.h
/* * Xournal++ * * A GeometryTool view * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <cmath> #include <cairo.h> // for cairo_t #include "control/zoom/ZoomListener.h" #include "model/GeometryTool.h" // for GeometryTool #include "view/overlays/BaseStrokeToolView.h" #include "Mask.h" class Stroke; class OverlayBase; class ZoomControl; /** * @brief A class that renders a geometry tool */ namespace xoj::view { class Repaintable; constexpr double rad(double n) { return n * M_PI / 180.; } constexpr double rad(int n) { return rad(static_cast<double>(n)); } constexpr double deg(double a) { return a * 180.0 / M_PI; } inline double cathete(double h, double o) { return std::sqrt(std::pow(h, 2) - std::pow(o, 2)); } class GeometryToolView: public ToolView, public ZoomListener, public xoj::util::Listener<GeometryToolView> { public: GeometryToolView(const GeometryTool* geometryTool, Repaintable* parent, ZoomControl* zoomControl); virtual ~GeometryToolView(); /** * Zoom interface */ void zoomChanged() override; /** * Listener interface */ static constexpr struct FlagDirtyRegionRequest { } FLAG_DIRTY_REGION = {}; virtual void on(FlagDirtyRegionRequest, const Range& rg) = 0; static constexpr struct UpdateValuesRequest { } UPDATE_VALUES = {}; virtual void on(UpdateValuesRequest, double h, double rot, cairo_matrix_t m) = 0; static constexpr struct FinalizationRequest { } FINALIZATION_REQUEST = {}; /** * @brief Called before the corresponding GeometryTool's destruction * @param rg The bounding box of the entire geometry tool */ virtual void deleteOn(FinalizationRequest, const Range& rg) = 0; static constexpr struct ResetMaskRequest { } RESET_MASK = {}; void on(ResetMaskRequest); /** * @brief draws the geometry tool and temporary stroke to a cairo context * @param cr the cairo context */ void draw(cairo_t* cr) const override; bool isViewOf(const OverlayBase* overlay) const override; private: /** * @brief draws the GeometryTool to a cairo context * @param cr the cairo context drawn to */ virtual void drawGeometryTool(cairo_t* cr) const = 0; /** * @brief draws displays (that may change with rotation and/or translation) * of the geometry tool * * @param cr the cairo context drawn to */ virtual void drawDisplays(cairo_t* cr) const = 0; /** * @brief draws the temporary stroke to a cairo context * @param cr the cairo context drawn to */ void drawTemporaryStroke(cairo_t* cr) const; /** * @brief Creates a mask for caching the drawing of the geometry tool (without stroke) */ Mask createMask(cairo_t* targetCr) const; protected: /** * @brief the underlying GeometryTool */ const GeometryTool* geometryTool; /** * @brief The stroke drawn aligned to the longest side of the GeometryTool or ending at the midpoint of the longest * side of the GeometryTool */ Stroke* stroke = nullptr; /** * @brief renders text centered and possibly rotated at the current position on a cairo context * @param cr the cairo context * @param text the text string * @param angle the rotation angle */ void showTextCenteredAndRotated(cairo_t* cr, const std::string& text, double angle) const; private: mutable Mask mask; ZoomControl* zoomControl; }; }; // namespace xoj::view
3,595
C++
.h
106
29.622642
119
0.697171
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
13,055
ElementContainerView.h
xournalpp_xournalpp/src/core/view/ElementContainerView.h
/* * Xournal++ * * Displays the content of a selection * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once class ElementContainer; namespace xoj::view { class Context; class ElementContainerView { public: ElementContainerView(const ElementContainer* container); /** * @brief Draws the container to the given context */ void draw(const Context& ctx) const; private: const ElementContainer* container; }; }; // namespace xoj::view
535
C++
.h
25
18.76
60
0.730159
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
13,056
Mask.h
xournalpp_xournalpp/src/core/view/Mask.h
/* * Xournal++ * * Virtual class for showing overlays (e.g. active tools, selections and so on) * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <cairo.h> #include <gdk/gdk.h> #include "util/raii/CairoWrappers.h" class Range; namespace xoj::view { /** * @brief Mask class: a cairo surface and its context to draw on, with the later purpose of blitting or using as a * buffer. */ class Mask { public: Mask() = default; /** * @brief Create a mask tailored for the specified target * @param target A cairo surface similar to that on which the mask will be used * @param extent The extent of the mask, in local coordinates (i.e. in the coordinates of the cairo context(s) on * which the mask will be used). * @param zoom The local zoom ratio (zoom ratio of the cairo context(s) on which the mask will be used). * @param contentType The intended content of the mask */ Mask(cairo_surface_t* target, const Range& extent, double zoom, cairo_content_t contentType = CAIRO_CONTENT_ALPHA); /** * @brief Create a mask tailored for the specified target * @param DPIScaling The DPI scaling of the targeted use monitor * @param extent The extent of the mask, in local coordinates (i.e. in the coordinates of the cairo context(s) on * which the mask will be used). * @param zoom The local zoom ratio (zoom ratio of the cairo context(s) on which the mask will be used). * @param contentType The intended content of the mask */ Mask(int DPIScaling, const Range& extent, double zoom, cairo_content_t contentType = CAIRO_CONTENT_ALPHA); cairo_t* get(); bool isInitialized() const; /** * @brief Use the surface as a mask */ void blitTo(cairo_t* targetCr) const; /** * @brief Paint the content of the surface to the target cairo context */ void paintTo(cairo_t* targetCr) const; /** * @brief Erase all the surface's content */ void wipe(); /** * @brief Erase part the surface's content * @param rg The part to erase, in Page coordinates */ void wipeRange(const Range& rg); /** * @brief Delete the mask */ void reset(); inline double getZoom() const { return zoom; } private: template <typename DPIInfoType> void constructorImpl(DPIInfoType dpiInfo, const Range& extent, double zoom, cairo_content_t contentType); xoj::util::CairoSPtr cr; int xOffset = 0; int yOffset = 0; double zoom = 1.0; }; }; // namespace xoj::view
2,622
C++
.h
74
31.108108
119
0.683629
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
13,057
DocumentView.h
xournalpp_xournalpp/src/core/view/DocumentView.h
/* * Xournal++ * * Paints a page to a cairo context * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <cairo.h> // for cairo_t #include "model/PageRef.h" // for PageRef #include "util/ElementRange.h" #include "view/background/BackgroundFlags.h" class PdfCache; namespace xoj::view { struct BackgroundFlags; }; class DocumentView { public: DocumentView() = default; virtual ~DocumentView() = default; public: /** * Draw the full page, usually you would like to call this method * @param page The page to draw * @param cr Draw to thgis context * @param dontRenderEditingStroke false to draw currently drawing stroke * @param flags show/hide various background components */ void drawPage(PageRef page, cairo_t* cr, bool dontRenderEditingStroke, xoj::view::BackgroundFlags flags = xoj::view::BACKGROUND_SHOW_ALL); /** * Only draws the prescribed layers of the given page, regardless of the layer's current visibility. * @param layerRange Range of layers to draw * @param page The page to draw * @param cr Draw to this context * @param dontRenderEditingStroke false to draw currently drawing stroke * @param flags show/hide various background components */ void drawLayersOfPage(const LayerRangeVector& layerRange, PageRef page, cairo_t* cr, bool dontRenderEditingStroke, xoj::view::BackgroundFlags flags = xoj::view::BACKGROUND_SHOW_ALL); /** * Mark stroke with Audio */ void setMarkAudioStroke(bool markAudioStroke); // API for special drawing, usually you won't call this methods public: void setPdfCache(PdfCache* cache); /** * Drawing first step * @param page The page to draw * @param cr Draw to thgis context * @param dontRenderEditingStroke false to draw currently drawing stroke */ void initDrawing(PageRef page, cairo_t* cr, bool dontRenderEditingStroke); /** * Draw the background */ void drawBackground(xoj::view::BackgroundFlags bgFlags) const; /** * Draw background if there is no background shown, like in GIMP etc. */ void drawTransparentBackgroundPattern(); /** * Last step in drawing */ void finializeDrawing(); private: cairo_t* cr = nullptr; PageRef page = nullptr; PdfCache* pdfCache = nullptr; bool dontRenderEditingStroke = false; bool markAudioStroke = false; };
2,551
C++
.h
76
28.736842
118
0.699065
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
13,058
View.h
xournalpp_xournalpp/src/core/view/View.h
/* * Xournal++ * * Namespace for view related classes * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <memory> #include <gtk/gtk.h> class Element; namespace xoj { namespace view { enum NonAudioTreatment : bool { FADE_OUT_NON_AUDIO_ = true, NORMAL_NON_AUDIO = false }; enum EditionTreatment : bool { SHOW_CURRENT_EDITING = true, HIDE_CURRENT_EDITING = false }; enum ColorTreatment : bool { COLORBLIND = true, NORMAL_COLOR = false }; class Context { public: cairo_t* cr; NonAudioTreatment fadeOutNonAudio; EditionTreatment showCurrentEdition; ColorTreatment noColor; static Context createDefault(cairo_t* cr) { return {cr, NORMAL_NON_AUDIO, HIDE_CURRENT_EDITING, NORMAL_COLOR}; } static Context createColorBlind(cairo_t* cr) { return {cr, NORMAL_NON_AUDIO, HIDE_CURRENT_EDITING, COLORBLIND}; } }; class ElementView { public: virtual ~ElementView() = default; virtual void draw(const Context& ctx) const = 0; static std::unique_ptr<ElementView> createFromElement(const Element* e); }; class TexImageView; class ImageView; class StrokeView; class TextView; constexpr double OPACITY_NO_AUDIO = 0.3; }; // namespace view }; // namespace xoj
1,270
C++
.h
41
28.609756
117
0.745484
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
13,059
LayerView.h
xournalpp_xournalpp/src/core/view/LayerView.h
/* * Xournal++ * * Displays a Layer * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once class Layer; namespace xoj::view { class Context; class LayerView { public: LayerView(const Layer* layer); /** * @brief Draws the entire Layer */ void draw(const Context& ctx) const; const Layer* getLayer() const; private: const Layer* layer; }; }; // namespace xoj::view
470
C++
.h
26
15.346154
41
0.678082
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
13,060
Repaintable.h
xournalpp_xournalpp/src/core/view/Repaintable.h
/* * Xournal++ * * * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once class Range; class ZoomControl; namespace xoj::util { template <typename T> class Rectangle; }; namespace xoj::view { class OverlayView; class ToolView; class Repaintable { public: Repaintable() = default; virtual ~Repaintable() = default; Repaintable(const Repaintable&) = delete; Repaintable(Repaintable&&) = delete; /** * @brief Get the Repaintable's visible part, in local coordinates * @return A range. It could be empty. */ virtual Range getVisiblePart() const = 0; // Get the current zoom. virtual double getZoom() const = 0; virtual ZoomControl* getZoomControl() const = 0; // Width and height, in local coordinates virtual double getWidth() const = 0; virtual double getHeight() const = 0; // Convert a rectangle from local coordinates to global coordinates virtual xoj::util::Rectangle<double> toWindowCoordinates(const xoj::util::Rectangle<double>& r) const = 0; /** * @brief Flag a region as dirty. Dirty regions will get redrawn at the next screen refresh. */ virtual void flagDirtyRegion(const Range& rg) const = 0; /** * @brief Draw the ToolView to the repaintable buffer (if any), remove a tool view and repaint the given range * Called just before the tool sequence ends and the handler is deleted. */ virtual void drawAndDeleteToolView(ToolView* v, const Range& rg) = 0; /** * @brief Remove a overlay view and repaint the given range * The given range is supposed to be big enough so that repainting this area will indeed erase the overlay from * the display */ virtual void deleteOverlayView(OverlayView* v, const Range& rg) = 0; }; }; // namespace xoj::view
1,885
C++
.h
56
29.785714
120
0.700605
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
13,061
StrokeView.h
xournalpp_xournalpp/src/core/view/StrokeView.h
/* * Xournal++ * * Draw stroke * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <cairo.h> // for cairo_t, CAIRO_LINE_CAP_BUTT, CAIRO_LINE_CAP_ROUND #include "View.h" // for ElementView class Stroke; class xoj::view::StrokeView: public xoj::view::ElementView { public: StrokeView(const Stroke* s); ~StrokeView() = default; public: /** * @brief Paint the given stroke. * @param dontRenderEditingStroke If true, and if the stroke is currently being (partially) erased, then render only * the not-yet-erased parts. (Typically set to true, except for previews and export jobs) * @param markAudioStroke If true, the stroke is faded out if it has no audio playback attached. * @param noColor If true, paint as if on a colorblind mask (only the alpha values are painted). */ void draw(const Context& ctx) const override; private: const Stroke* s; public: static constexpr double OPACITY_HIGHLIGHTER = 0.47; static constexpr double MINIMAL_ALPHA = 0.04; // Must match the enum StrokeCapStyle in Stroke.h static constexpr cairo_line_cap_t CAIRO_LINE_CAP[] = {CAIRO_LINE_CAP_ROUND, CAIRO_LINE_CAP_BUTT, CAIRO_LINE_CAP_SQUARE}; };
1,340
C++
.h
36
32.277778
120
0.685714
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
13,062
ErasableStrokeView.h
xournalpp_xournalpp/src/core/view/ErasableStrokeView.h
/* * Xournal++ * * Draw stroke * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <utility> // for pair #include <cairo.h> // for cairo_t class ErasableStroke; class Range; namespace xoj { namespace view { class Mask; class ErasableStrokeView { public: ErasableStrokeView(const ErasableStroke& erasableStroke); ~ErasableStrokeView() = default; /** * @brief Draw the erasable stroke assuming the cairo context is all set * @param cr The cairo context to draw to */ void draw(cairo_t* cr) const; /** * @brief Draw the filling of the erasable stroke assuming the cairo context is all set * @param cr The cairo context */ void drawFilling(cairo_t* cr) const; /** * @brief Paint the erasable stroke, after setting up the cairo context, assuming the stroke is filled and made with * the highlighter tool * @param cr The cairo context */ void paintFilledHighlighter(cairo_t* cr) const; private: /** * @brief Create a cairo mask for a given rectangle and sets up a context for drawing on it * @param target A cairo context on which the mask would be used * @param box The range delimiting the mask * @param zoom A zoom ratio to apply to the mask */ xoj::view::Mask createMask(cairo_t* target, const Range& box, double zoom) const; private: const ErasableStroke& erasableStroke; }; }; // namespace view }; // namespace xoj
1,532
C++
.h
51
26.313725
120
0.698639
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
13,063
DebugShowRepaintBounds.h
xournalpp_xournalpp/src/core/view/DebugShowRepaintBounds.h
#pragma once #include "config-debug.h" #ifdef DEBUG_SHOW_REPAINT_BOUNDS #define IF_DEBUG_REPAINT(f) f #else #define IF_DEBUG_REPAINT(f) #endif
145
C++
.h
7
19.428571
32
0.794118
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
13,064
LinedBackgroundView.h
xournalpp_xournalpp/src/core/view/background/LinedBackgroundView.h
/* * Xournal++ * * Class for lined backgrounds (= ruled + vertical margin line) * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <cairo.h> // for cairo_t #include "model/BackgroundConfig.h" // for BackgroundConfig #include "util/Color.h" // for Color #include "RuledBackgroundView.h" // for RuledBackgroundView namespace xoj::view { class LinedBackgroundView: public RuledBackgroundView { public: LinedBackgroundView(double pageWidth, double pageHeight, Color backgroundColor, const BackgroundConfig& config); virtual ~LinedBackgroundView() = default; virtual void draw(cairo_t* cr) const override; protected: Color vLineColor; double margin = 72.0; // default = 1 inch. Negative values put the margin on the right hand side. constexpr static Color DEFAULT_V_LINE_COLOR = Colors::xopp_deeppink; constexpr static Color ALT_DEFAULT_V_LINE_COLOR = Colors::xopp_midnightblue; }; }; // namespace xoj::view
1,040
C++
.h
28
34.535714
116
0.741036
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
13,065
GraphBackgroundView.h
xournalpp_xournalpp/src/core/view/background/GraphBackgroundView.h
/* * Xournal++ * * Class for graph backgrounds * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <cairo.h> // for cairo_t #include "util/Color.h" // for Color #include "OneColorBackgroundView.h" // for OneColorBackgroundView class BackgroundConfig; namespace xoj::view { class GraphBackgroundView: public OneColorBackgroundView { public: GraphBackgroundView(double pageWidth, double pageHeight, Color backgroundColor, const BackgroundConfig& config); virtual ~GraphBackgroundView() = default; virtual void draw(cairo_t* cr) const override; protected: bool roundUpMargin = false; double margin = 0.0; double squareSize = 14.17; // 5mm constexpr static Color DEFAULT_LINE_COLOR = Colors::xopp_silver; constexpr static Color ALT_DEFAULT_LINE_COLOR = Colors::xopp_darkslategray; constexpr static double DEFAULT_LINE_WIDTH = 0.5; }; }; // namespace xoj::view
988
C++
.h
30
30.133333
116
0.750263
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
13,066
BackgroundView.h
xournalpp_xournalpp/src/core/view/background/BackgroundView.h
/* * Xournal++ * * Displays a background * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <memory> // for unique_ptr #include <cairo.h> // for cairo_t #include "model/PageRef.h" // for PageRef #include "util/Color.h" // for Color #include "BackgroundFlags.h" class PdfCache; class PageType; namespace xoj { namespace view { class BackgroundView { public: BackgroundView(double pageWidth, double pageHeight): pageWidth(pageWidth), pageHeight(pageHeight) {} virtual ~BackgroundView() = default; /** * @brief Draws the background on the entire mask represented by the cairo context cr * * Does nothing in the base class - used when the background drawing is suppressed. */ virtual void draw(cairo_t* cr) const {} [[nodiscard]] static std::unique_ptr<BackgroundView> createRuled(double width, double height, Color backgroundColor, const PageType& pt, double lineWidthFactor = 1.0); [[nodiscard]] static std::unique_ptr<BackgroundView> createForPage(PageRef page, xoj::view::BackgroundFlags bgFlags, PdfCache* pdfCache = nullptr); protected: double pageWidth; double pageHeight; }; }; // namespace view }; // namespace xoj
1,415
C++
.h
40
29.075
120
0.656158
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
13,067
OneColorBackgroundView.h
xournalpp_xournalpp/src/core/view/background/OneColorBackgroundView.h
/* * Xournal++ * * Class for backgrounds with lineWidth and a line color * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <string> // for string #include "util/Color.h" // for Color #include "PlainBackgroundView.h" // for PlainBackgroundView class BackgroundConfig; namespace xoj::view { class OneColorBackgroundView: public PlainBackgroundView { public: OneColorBackgroundView(double pageWidth, double pageHeight, Color backgroundColor, const BackgroundConfig& config, double defaultLineWidth, Color defaultLineColor, Color altDefaultLineColor); virtual ~OneColorBackgroundView() = default; void multiplyLineWidth(double factor); protected: /** * @brief Get the config's Hex value associated to the config string and make it a color. * Fallback to defaultColor if the value does not exist in config. */ static Color getColorOr(const BackgroundConfig& config, const std::string& str, const Color& defaultColor); protected: Color foregroundColor; double lineWidth; }; }; // namespace xoj::view
1,161
C++
.h
33
31.515152
118
0.747096
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
13,068
IsoDottedBackgroundView.h
xournalpp_xournalpp/src/core/view/background/IsoDottedBackgroundView.h
/* * Xournal++ * * Class for isometric graph backgrounds * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <cairo.h> // for cairo_t #include "util/Color.h" // for Color #include "BaseIsometricBackgroundView.h" // for BaseIsometricBackgroundView class BackgroundConfig; namespace xoj::view { class IsoDottedBackgroundView: public BaseIsometricBackgroundView { public: IsoDottedBackgroundView(double pageWidth, double pageHeight, Color backgroundColor, const BackgroundConfig& config); virtual ~IsoDottedBackgroundView() = default; protected: virtual void paintGrid(cairo_t* cr, int cols, int rows, double xstep, double ystep, double xOffset, double yOffset) const override; protected: constexpr static double DEFAULT_LINE_WIDTH = 1.5; }; }; // namespace xoj::view
902
C++
.h
27
30.185185
120
0.750865
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
13,069
ImageBackgroundView.h
xournalpp_xournalpp/src/core/view/background/ImageBackgroundView.h
/* * Xournal++ * * Displays a background image * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <cairo.h> // for cairo_t #include "BackgroundView.h" // for BackgroundView struct BackgroundImage; namespace xoj::view { class ImageBackgroundView: public BackgroundView { public: ImageBackgroundView(double pageWidth, double pageHeight, const BackgroundImage& image); /** * @brief Draws the background on the entire mask represented by the cairo context ctx.cr */ virtual void draw(cairo_t* cr) const override; private: const BackgroundImage& image; }; }; // namespace xoj::view
696
C++
.h
26
24.153846
93
0.739065
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
13,070
BaseIsometricBackgroundView.h
xournalpp_xournalpp/src/core/view/background/BaseIsometricBackgroundView.h
/* * Xournal++ * * Base class for isometric backgrounds * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <cairo.h> // for cairo_t #include "util/Color.h" // for Color #include "OneColorBackgroundView.h" // for OneColorBackgroundView class BackgroundConfig; namespace xoj::view { class BaseIsometricBackgroundView: public OneColorBackgroundView { public: BaseIsometricBackgroundView(double pageWidth, double pageHeight, Color backgroundColor, const BackgroundConfig& config, double defaultLineWidth); virtual ~BaseIsometricBackgroundView() = default; virtual void draw(cairo_t* cr) const override; protected: virtual void paintGrid(cairo_t* cr, int cols, int rows, double xstep, double ystep, double xOffset, double yOffset) const = 0; protected: double triangleSize = 14.17; // 5mm constexpr static Color DEFAULT_LINE_COLOR = Colors::xopp_silver; constexpr static Color ALT_DEFAULT_LINE_COLOR = Colors::xopp_darkslategray; }; }; // namespace xoj::view
1,139
C++
.h
31
32.322581
103
0.726776
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
13,071
StavesBackgroundView.h
xournalpp_xournalpp/src/core/view/background/StavesBackgroundView.h
/* * Xournal++ * * Class for staves backgrounds * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <cairo.h> // for cairo_t #include "util/Color.h" // for Color #include "OneColorBackgroundView.h" // for OneColorBackgroundView class BackgroundConfig; namespace xoj::view { class StavesBackgroundView: public OneColorBackgroundView { public: StavesBackgroundView(double pageWidth, double pageHeight, Color backgroundColor, const BackgroundConfig& config); virtual ~StavesBackgroundView() = default; virtual void draw(cairo_t* cr) const override; protected: constexpr static Color DEFAULT_LINE_COLOR = Colors::black; constexpr static Color ALT_DEFAULT_LINE_COLOR = Colors::white; constexpr static double DEFAULT_LINE_WIDTH = 0.5; constexpr static double HEADER_SIZE = 80.0; constexpr static double FOOTER_SIZE = 60.0; constexpr static double MARGIN = 50.0; constexpr static double STAVES_SPACING = 40.0; // Between two staves constexpr static double LINES_SPACING = 5.0; // Between two lines within a staff }; }; // namespace xoj::view
1,178
C++
.h
32
33.875
117
0.75022
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
13,072
TransparentCheckerboardBackgroundView.h
xournalpp_xournalpp/src/core/view/background/TransparentCheckerboardBackgroundView.h
/* * Xournal++ * * Class for transparent backgrounds (checkerboard pattern) * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <cairo.h> // for cairo_pattern_t, cairo_t #include "util/Color.h" // for Color #include "BackgroundView.h" // for BackgroundView namespace xoj::view { class TransparentCheckerboardBackgroundView: public BackgroundView { public: TransparentCheckerboardBackgroundView(double pageWidth, double pageHeight); virtual ~TransparentCheckerboardBackgroundView() noexcept; void draw(cairo_t* cr) const override; private: cairo_pattern_t* pattern = nullptr; protected: static cairo_pattern_t* createPattern(); static constexpr int CHECKER_SIZE = 8; static constexpr Color DARK_GREY{Colors::gray}; static constexpr Color LIGHT_GREY{Colors::silver}; }; }; // namespace xoj::view
920
C++
.h
29
29.034483
79
0.757644
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
13,073
PlainBackgroundView.h
xournalpp_xournalpp/src/core/view/background/PlainBackgroundView.h
/* * Xournal++ * * Class for plain backgrounds * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <utility> // for pair #include <cairo.h> // for cairo_t #include "util/Color.h" // for Color #include "BackgroundView.h" // for BackgroundView namespace xoj::view { class PlainBackgroundView: public BackgroundView { public: PlainBackgroundView(double pageWidth, double pageHeight, Color backgroundColor); virtual ~PlainBackgroundView() = default; virtual void draw(cairo_t* cr) const override; protected: Color backgroundColor; static std::pair<int, int> getIndexBounds(double min, double max, double step, double margin, double length); }; }; // namespace xoj::view
782
C++
.h
26
27.615385
113
0.741633
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
13,074
PdfBackgroundView.h
xournalpp_xournalpp/src/core/view/background/PdfBackgroundView.h
/* * Xournal++ * * Displays a pdf background * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <cstddef> // for size_t #include <cairo.h> // for cairo_t #include "BackgroundView.h" // for BackgroundView class PdfCache; namespace xoj { namespace view { class PdfBackgroundView: public BackgroundView { public: PdfBackgroundView(double pageWidth, double pageHeight, size_t pageNo, PdfCache* pdfCache = nullptr); virtual ~PdfBackgroundView() = default; /** * @brief Draws the background on the entire mask represented by the cairo context cr */ void draw(cairo_t* cr) const override; private: size_t pageNo; PdfCache* pdfCache = nullptr; }; }; // namespace view }; // namespace xoj
812
C++
.h
31
23.483871
104
0.719844
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
13,075
IsoGraphBackgroundView.h
xournalpp_xournalpp/src/core/view/background/IsoGraphBackgroundView.h
/* * Xournal++ * * Class for isometric graph backgrounds * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <cairo.h> // for cairo_t #include "util/Color.h" // for Color #include "BaseIsometricBackgroundView.h" // for BaseIsometricBackgroundView class BackgroundConfig; namespace xoj::view { class IsoGraphBackgroundView: public BaseIsometricBackgroundView { public: IsoGraphBackgroundView(double pageWidth, double pageHeight, Color backgroundColor, const BackgroundConfig& config); virtual ~IsoGraphBackgroundView() = default; protected: virtual void paintGrid(cairo_t* cr, int cols, int rows, double xstep, double ystep, double xOffset, double yOffset) const override; protected: constexpr static double DEFAULT_LINE_WIDTH = 1.0; }; }; // namespace xoj::view
899
C++
.h
27
30.074074
119
0.75
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
13,076
RuledBackgroundView.h
xournalpp_xournalpp/src/core/view/background/RuledBackgroundView.h
/* * Xournal++ * * Class for ruled backgrounds * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <cairo.h> // for cairo_t #include "util/Color.h" // for Color #include "OneColorBackgroundView.h" // for OneColorBackgroundView class BackgroundConfig; namespace xoj::view { class RuledBackgroundView: public OneColorBackgroundView { public: RuledBackgroundView(double pageWidth, double pageHeight, Color backgroundColor, const BackgroundConfig& config); virtual ~RuledBackgroundView() = default; virtual void draw(cairo_t* cr) const override; protected: double lineSpacing = 24.0; // Between two horizontal lines constexpr static Color DEFAULT_H_LINE_COLOR = Colors::xopp_dodgerblue; constexpr static Color ALT_DEFAULT_H_LINE_COLOR = Colors::xopp_darkslategray; constexpr static double DEFAULT_LINE_WIDTH = 0.5; constexpr static double HEADER_SIZE = 80.0; constexpr static double FOOTER_SIZE = 60.0; }; }; // namespace xoj::view
1,061
C++
.h
30
32.533333
116
0.756121
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
13,077
DottedBackgroundView.h
xournalpp_xournalpp/src/core/view/background/DottedBackgroundView.h
/* * Xournal++ * * Class for graph backgrounds * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <cairo.h> // for cairo_t #include "util/Color.h" // for Color #include "OneColorBackgroundView.h" // for OneColorBackgroundView class BackgroundConfig; namespace xoj::view { class DottedBackgroundView: public OneColorBackgroundView { public: DottedBackgroundView(double pageWidth, double pageHeight, Color backgroundColor, const BackgroundConfig& config); virtual ~DottedBackgroundView() = default; virtual void draw(cairo_t* cr) const override; protected: double squareSize = 14.17; // 5mm constexpr static Color DEFAULT_LINE_COLOR = Colors::xopp_silver; constexpr static Color ALT_DEFAULT_LINE_COLOR = Colors::xopp_darkslategray; constexpr static double DEFAULT_LINE_WIDTH = 1.5; }; }; // namespace xoj::view
934
C++
.h
28
30.714286
117
0.756968
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
13,078
BackgroundFlags.h
xournalpp_xournalpp/src/core/view/background/BackgroundFlags.h
/* * Xournal++ * * Flags for background painting * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once namespace xoj::view { enum PDFBackgroundTreatment : bool { SHOW_PDF_BACKGROUND = true, HIDE_PDF_BACKGROUND = false }; enum ImageBackgroundTreatment : bool { SHOW_IMAGE_BACKGROUND = true, HIDE_IMAGE_BACKGROUND = false }; enum RulingBackgroundTreatment : bool { SHOW_RULING_BACKGROUND = true, HIDE_RULING_BACKGROUND = false }; enum BackgroundColorTreatment : bool { FORCE_AT_LEAST_BACKGROUND_COLOR = true, DONT_FORCE_BACKGROUND_COLOR = false }; enum VisibilityTreatment : bool { FORCE_VISIBLE = true, USE_DOCUMENT_VISIBILITY = false }; struct BackgroundFlags { PDFBackgroundTreatment showPDF; ImageBackgroundTreatment showImage; RulingBackgroundTreatment showRuling; BackgroundColorTreatment forceBackgroundColor = DONT_FORCE_BACKGROUND_COLOR; VisibilityTreatment forceVisible = USE_DOCUMENT_VISIBILITY; }; static constexpr BackgroundFlags BACKGROUND_SHOW_ALL = {SHOW_PDF_BACKGROUND, SHOW_IMAGE_BACKGROUND, SHOW_RULING_BACKGROUND, DONT_FORCE_BACKGROUND_COLOR, USE_DOCUMENT_VISIBILITY}; static constexpr BackgroundFlags BACKGROUND_FORCE_PAINT_BACKGROUND_COLOR_ONLY = { HIDE_PDF_BACKGROUND, HIDE_IMAGE_BACKGROUND, HIDE_RULING_BACKGROUND, FORCE_AT_LEAST_BACKGROUND_COLOR, FORCE_VISIBLE}; } // namespace xoj::view
1,537
C++
.h
31
43.322581
117
0.727333
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
13,079
ShapeToolView.h
xournalpp_xournalpp/src/core/view/overlays/ShapeToolView.h
/* * Xournal++ * * View active shape tools (rectangle, ellipse and so on) * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <cairo.h> // for cairo_t #include "util/DispatchPool.h" // for Listener #include "BaseShapeOrSplineToolView.h" class BaseShapeHandler; class OverlayBase; class Range; namespace xoj::view { class Repaintable; class ShapeToolView final: public BaseShapeOrSplineToolView, public xoj::util::Listener<ShapeToolView> { public: ShapeToolView(const BaseShapeHandler* handler, Repaintable* parent); ~ShapeToolView() noexcept override; /** * @brief Draws the overlay to the given context */ void draw(cairo_t* cr) const override; bool isViewOf(const OverlayBase* overlay) const override; /** * Listener interface */ static constexpr struct FlagDirtyRegionRequest { } FLAG_DIRTY_REGION = {}; void on(FlagDirtyRegionRequest, const Range& rg); static constexpr struct FinalizationRequest { } FINALIZATION_REQUEST = {}; /** * @brief Called before the corresponding BaseShapeHandler's destruction * @param rg The bounding box of the entire stroke */ void deleteOn(FinalizationRequest, const Range& rg); private: const BaseShapeHandler* toolHandler; }; }; // namespace xoj::view
1,378
C++
.h
45
27.111111
104
0.731818
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
13,080
SplineToolView.h
xournalpp_xournalpp/src/core/view/overlays/SplineToolView.h
/* * Xournal++ * * View active spline tool * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <cairo.h> #include "control/zoom/ZoomListener.h" #include "util/Color.h" #include "util/DispatchPool.h" #include "BaseShapeOrSplineToolView.h" class SplineHandler; struct SplineHandlerData; class OverlayBase; class Range; class ZoomControl; namespace xoj::view { class Repaintable; class SplineToolView: public BaseShapeOrSplineToolView, public ZoomListener, public xoj::util::Listener<SplineToolView> { public: SplineToolView(const SplineHandler* splineHandler, Repaintable* parent); virtual ~SplineToolView() noexcept; /** * @brief Draws the overlay to the given context */ void draw(cairo_t* cr) const override; void drawWithoutDrawingAids(cairo_t* cr) const override; bool isViewOf(const OverlayBase* overlay) const override; /** * Zoom interface */ void zoomChanged() override; /** * Listener interface */ static constexpr struct FlagDirtyRegionRequest { } FLAG_DIRTY_REGION = {}; void on(FlagDirtyRegionRequest, Range rg); /** * @brief Called before the corresponding SplineHandler's destruction * @param rg The bounding box of the entire spline + drawing aids, to be repainted */ static constexpr struct FinalizationRequest { } FINALIZATION_REQUEST = {}; void deleteOn(FinalizationRequest, Range rg); private: void drawSpline(cairo_t* cr, const SplineHandlerData& data) const; const SplineHandler* splineHandler; public: static constexpr double LINE_WIDTH_WITHOUT_ZOOM = 2.0; // for tangent vectors & dynamic spline seg. static constexpr Color NODE_CIRCLE_COLOR = Colors::gray; static constexpr Color FIRST_NODE_CIRCLE_COLOR = Colors::red; static constexpr Color TANGENT_VECTOR_COLOR = Colors::lawngreen; static constexpr Color DYNAMIC_OBJECTS_COLOR = Colors::gray; }; }; // namespace xoj::view
2,057
C++
.h
64
28.25
104
0.733064
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
13,081
ImageSizeSelectionView.h
xournalpp_xournalpp/src/core/view/overlays/ImageSizeSelectionView.h
/* * Xournal++ * * Displays a Rectangle to see while selecting space for an image * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <array> // for std::array #include "util/Color.h" // for Color #include "util/DispatchPool.h" // for Listener #include "OverlayView.h" // for OverlayView class ImageSizeSelection; class Range; namespace xoj::view { class Repaintable; class ImageSizeSelectionView: public OverlayView, public xoj::util::Listener<ImageSizeSelectionView> { public: ImageSizeSelectionView(const ImageSizeSelection* imageSizeSelection, Repaintable* parent, Color selectionColor); virtual ~ImageSizeSelectionView() noexcept; /** * @brief Draws the overlay to the given context */ void draw(cairo_t* cr) const override; auto isViewOf(const OverlayBase* overlay) const -> bool override; // Listener static constexpr struct FlagDirtyRegionRequest { } FLAG_DIRTY_REGION = {}; void on(FlagDirtyRegionRequest, Range rg); static constexpr struct FinalizationRequest { } FINALIZATION_REQUEST = {}; void deleteOn(FinalizationRequest, Range rg); private: const ImageSizeSelection* imageSizeSelection; const Color selectionColor; static constexpr int BORDER_WIDTH_IN_PIXELS = 1; static constexpr double OPACITY_FOR_FILL = 0.1; static constexpr std::array<const double, 2> DASH_PATTERN = {6.0, 4.0}; }; }; // namespace xoj::view
1,512
C++
.h
43
31.860465
116
0.740563
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
13,082
PdfElementSelectionView.h
xournalpp_xournalpp/src/core/view/overlays/PdfElementSelectionView.h
/* * Xournal++ * * View pdf selections * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <cairo.h> // for cairo_t #include "util/Color.h" #include "util/DispatchPool.h" // for Listener #include "view/overlays/OverlayView.h" class OverlayBase; class PdfElemSelection; class Range; namespace xoj::view { class Repaintable; class PdfElementSelectionView final: public OverlayView, public xoj::util::Listener<PdfElementSelectionView> { public: PdfElementSelectionView(const PdfElemSelection* selection, Repaintable* parent, Color selectionColor); ~PdfElementSelectionView() noexcept override; /** * @brief Draws the overlay to the given context */ void draw(cairo_t* cr) const override; bool isViewOf(const OverlayBase* overlay) const override; /** * Listener interface */ static constexpr struct CancelSelectionRequest { } CANCEL_SELECTION_REQUEST = {}; void deleteOn(CancelSelectionRequest, const Range& rg); static constexpr struct FlagDirtyRegionRequest { } FLAG_DIRTY_REGION_REQUEST = {}; void on(FlagDirtyRegionRequest, const Range& rg) const; private: const PdfElemSelection* selection; const Color selectionColor; public: // Opacity of the background static constexpr double SELECTION_OPACITY = 0.3; }; }; // namespace xoj::view
1,415
C++
.h
46
27.5
110
0.74595
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
13,083
BaseShapeOrSplineToolView.h
xournalpp_xournalpp/src/core/view/overlays/BaseShapeOrSplineToolView.h
/* * Xournal++ * * Base view for shapes or spline tools * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <cairo.h> #include "util/Range.h" #include "view/Mask.h" #include "BaseStrokeToolView.h" class InputHandler; namespace xoj::view { class Repaintable; class BaseShapeOrSplineToolView: public BaseStrokeToolView { public: BaseShapeOrSplineToolView(const InputHandler* handler, Repaintable* parent); ~BaseShapeOrSplineToolView() noexcept override; protected: cairo_t* prepareContext(cairo_t* cr) const; void commitDrawing(cairo_t* cr) const; const double fillingAlpha; // The mask is only for filled highlighter strokes, to avoid artefacts as in // https://github.com/xournalpp/xournalpp/issues/3709 mutable Mask mask; const bool needMask; /// @brief The part of the mask that needs to be wiped to ensure the filling is correctly drawn. mutable Range maskWipeExtent; }; }; // namespace xoj::view
1,038
C++
.h
34
27.647059
100
0.755287
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
13,084
OverlayView.h
xournalpp_xournalpp/src/core/view/overlays/OverlayView.h
/* * Xournal++ * * Virtual class for showing overlays (e.g. active tools, selections and so on) * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <cairo.h> class OverlayBase; namespace xoj::view { class Repaintable; class OverlayView { public: OverlayView(Repaintable* parent): parent(parent) {} virtual ~OverlayView() = default; /** * @brief Draws the overlay to the given context */ virtual void draw(cairo_t* cr) const = 0; virtual bool isViewOf(const OverlayBase* overlay) const = 0; protected: Repaintable* parent; }; class ToolView: public OverlayView { public: ToolView(Repaintable* parent): OverlayView(parent) {} /** * @brief Draws without putative drawing aids (e.g. spline knots and tangents, text frame) */ virtual void drawWithoutDrawingAids(cairo_t* cr) const { this->draw(cr); } }; }; // namespace xoj::view
973
C++
.h
36
23.972222
94
0.705819
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
13,085
SearchResultView.h
xournalpp_xournalpp/src/core/view/overlays/SearchResultView.h
/* * Xournal++ * * View highlighting search results * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <cairo.h> // for cairo_t #include "util/Color.h" #include "util/DispatchPool.h" // for Listener #include "view/overlays/OverlayView.h" class OverlayBase; class SearchControl; namespace xoj::view { class Repaintable; class SearchResultView final: public OverlayView, public xoj::util::Listener<SearchResultView> { public: SearchResultView(const SearchControl* searchControl, Repaintable* parent, Color frameColor, Color frameHighlightColor); ~SearchResultView() noexcept override; /** * @brief Draws the overlay to the given context */ void draw(cairo_t* cr) const override; bool isViewOf(const OverlayBase* overlay) const override; /** * Listener interface */ static constexpr struct SearchChangedNotification { } SEARCH_CHANGED_NOTIFICATION = {}; void on(SearchChangedNotification); private: const SearchControl* searchControl; const Color frameColor; const Color frameHighlightColor; public: // Width of the line delimiting moved elements static constexpr int BORDER_WIDTH_IN_PIXELS = 1; // Opacity of the background static constexpr double BACKGROUND_OPACITY = 0.3; }; }; // namespace xoj::view
1,403
C++
.h
46
26.782609
96
0.734027
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
13,086
VerticalToolView.h
xournalpp_xournalpp/src/core/view/overlays/VerticalToolView.h
/* * Xournal++ * * View active VerticalTool (move elements up and down) * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <cairo.h> // for cairo_t #include "control/tools/VerticalToolHandler.h" // for Side #include "control/zoom/ZoomListener.h" #include "util/Color.h" #include "util/DispatchPool.h" // for Listener #include "view/Mask.h" #include "view/overlays/OverlayView.h" class OverlayBase; class Range; class Settings; class ZoomControl; namespace xoj::view { class Repaintable; class VerticalToolView final: public ToolView, public ZoomListener, public xoj::util::Listener<VerticalToolView> { public: VerticalToolView(const VerticalToolHandler* handler, Repaintable* parent, ZoomControl* zoomControl, const Settings* settings); ~VerticalToolView() noexcept override; /** * @brief Draws the overlay to the given context */ void draw(cairo_t* cr) const override; void drawWithoutDrawingAids(cairo_t* cr) const override; bool isViewOf(const OverlayBase* overlay) const override; /** * Zoom interface */ void zoomChanged() override; /** * Listener interface */ static constexpr struct SetVerticalShiftRequest { } SET_VERTICAL_SHIFT_REQUEST = {}; void on(SetVerticalShiftRequest, double shift); static constexpr struct SwitchDirectionRequest { } SWITCH_DIRECTION_REQUEST = {}; void on(SwitchDirectionRequest); static constexpr struct FinalizationRequest { } FINALIZATION_REQUEST = {}; void deleteOn(FinalizationRequest); private: Mask createMask(cairo_t* tgtcr) const; private: const VerticalToolHandler* toolHandler; ZoomControl* zoomControl; double lastShift = 0.0; const Color aidColor; mutable Mask mask; public: // Width of the line delimiting moved elements static constexpr int BORDER_WIDTH_IN_PIXELS = 1; // Opacity of the background static constexpr double BACKGROUND_OPACITY = 0.3; }; }; // namespace xoj::view
2,091
C++
.h
66
27.833333
114
0.731707
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
13,087
StrokeToolFilledHighlighterView.h
xournalpp_xournalpp/src/core/view/overlays/StrokeToolFilledHighlighterView.h
/* * Xournal++ * * View active stroke tool -- for filled highlighter only * In this case, the mask needs to be wiped at every iteration, and repainted to avoid artefacts like in * https://github.com/xournalpp/xournalpp/issues/3709 * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include "StrokeToolFilledView.h" namespace xoj::view { class StrokeToolFilledHighlighterView: public StrokeToolFilledView { public: StrokeToolFilledHighlighterView(const StrokeHandler* strokeHandler, const Stroke& stroke, Repaintable* parent); virtual ~StrokeToolFilledHighlighterView() noexcept; void draw(cairo_t* cr) const override; }; }; // namespace xoj::view
754
C++
.h
22
32.090909
115
0.759945
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
13,088
StrokeToolFilledView.h
xournalpp_xournalpp/src/core/view/overlays/StrokeToolFilledView.h
/* * Xournal++ * * View active stroke tool -- filled strokes, but not filled highlighter. * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <vector> #include <cairo.h> #include "model/Point.h" #include "util/Point.h" #include "StrokeToolView.h" namespace xoj::view { class StrokeToolFilledHighlighterView; /** * @brief View active stroke tool -- with a filling * * In draw, the filling is painted directly, while the stroke itself is blitted from the mask */ class StrokeToolFilledView: public StrokeToolView { public: StrokeToolFilledView(const StrokeHandler* strokeHandler, const Stroke& stroke, Repaintable* parent); virtual ~StrokeToolFilledView() noexcept; void drawFilling(cairo_t* cr, const std::vector<Point>& pts) const override; void on(AddPointRequest, const Point& p) override; void on(StrokeReplacementRequest, const Stroke& newStroke) override; protected: class FillingData { public: FillingData(double alpha, const Point& p): alpha(alpha), firstPoint(p.x, p.y), contour{p} {} const double alpha; xoj::util::Point<double> firstPoint; // Store a copy for safe concurrent access void appendSegments(const std::vector<Point>& pts); /** * @brief Filling contour (i.e. the stroke's entire path) */ std::vector<Point> contour; }; mutable FillingData filling; }; }; // namespace xoj::view
1,502
C++
.h
45
29.511111
104
0.715177
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
13,089
BaseStrokeToolView.h
xournalpp_xournalpp/src/core/view/overlays/BaseStrokeToolView.h
/* * Xournal++ * * Virtual class for showing overlays (e.g. active tools, selections and so on) * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <cairo.h> #include "model/LineStyle.h" #include "util/Color.h" #include "view/overlays/OverlayView.h" class Stroke; namespace xoj::view { class Mask; class Repaintable; class BaseStrokeToolView: public ToolView { protected: BaseStrokeToolView(Repaintable* parent, const Stroke& stroke); ~BaseStrokeToolView() noexcept override; /** * @brief Creates a mask corresponding to the parent's visible area. * The mask is optimized (?) to be blitted to a surface of the same type as cairo_get_target(targetCr). * If targetCr == nullptr, the surface is of CAIRO_SURFACE_TYPE_IMAGE. */ Mask createMask(cairo_t* targetCr) const; /** * @brief Helper function to get a color whose alpha value depends on the tool's properties */ static Color strokeColorWithAlpha(const Stroke& s); /** * @brief All that's required to draw a stroke in cairo */ const cairo_operator_t cairoOp; const Color strokeColor; const LineStyle lineStyle; double strokeWidth; }; }; // namespace xoj::view
1,287
C++
.h
42
27.214286
107
0.718447
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
13,090
StrokeToolView.h
xournalpp_xournalpp/src/core/view/overlays/StrokeToolView.h
/* * Xournal++ * * View active stroke tool - abstract base class * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <vector> #include <cairo.h> #include "util/DispatchPool.h" #include "view/Mask.h" #include "BaseStrokeToolView.h" class StrokeHandler; class Point; class Range; class Stroke; class OverlayBase; namespace xoj::view { class Repaintable; class StrokeToolView: public BaseStrokeToolView, public xoj::util::Listener<StrokeToolView> { public: StrokeToolView(const StrokeHandler* strokeHandler, const Stroke& stroke, Repaintable* parent); virtual ~StrokeToolView() noexcept; bool isViewOf(const OverlayBase* overlay) const override; void draw(cairo_t* cr) const override; /** * Listener interface */ static constexpr struct AddPointRequest { } ADD_POINT_REQUEST = {}; virtual void on(AddPointRequest, const Point& p); static constexpr struct ThickenFirstPointRequest { } THICKEN_FIRST_POINT_REQUEST = {}; void on(ThickenFirstPointRequest, double newPressure); static constexpr struct StrokeReplacementRequest { } STROKE_REPLACEMENT_REQUEST = {}; virtual void on(StrokeReplacementRequest, const Stroke& newStroke); static constexpr struct CancellationRequest { } CANCELLATION_REQUEST = {}; void deleteOn(CancellationRequest, const Range& rg); /** * @brief Called before the corresponding StrokeHandler's destruction */ static constexpr struct FinalizationRequest { } FINALIZATION_REQUEST = {}; void deleteOn(FinalizationRequest, const Range& rg); protected: /** * @brief Compute the bounding box of the given segment, taking stroke width into account. */ auto getRepaintRange(const Point& lastPoint, const Point& addedPoint) const -> Range; void drawDot(cairo_t* cr, const Point& p) const; /** * @brief (Thread-safe) Flush the communication buffer and returns its content. */ std::vector<Point> flushBuffer() const; // Nothing in the base class virtual void drawFilling(cairo_t*, const std::vector<Point>&) const {} protected: const StrokeHandler* strokeHandler; protected: bool singleDot = true; /** * @brief offset for drawing dashes (if any) * In effect, this stores the length of the path already drawn to the mask. */ mutable double dashOffset = 0; /** * @brief Controller/View communication buffer * Those are in the same thread. Add mutex protection if this changes */ mutable std::vector<Point> pointBuffer; // Todo: implement a lock-free fifo? /** * @brief Drawing mask. * * The stroke is drawn to the mask and the mask is then blitted wherever needed. * Upon calls to draw(), the buffer is flushed and the corresponding part of stroke is added to the mask. */ mutable Mask mask; }; }; // namespace xoj::view
2,983
C++
.h
85
30.905882
109
0.716522
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
13,091
SelectionView.h
xournalpp_xournalpp/src/core/view/overlays/SelectionView.h
/* * Xournal++ * * Displays the content of a selection * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include "util/Color.h" #include "util/DispatchPool.h" #include "OverlayView.h" #include "cairo.h" class Selection; class Range; namespace xoj::view { class Repaintable; class SelectionView: public OverlayView, public xoj::util::Listener<SelectionView> { public: SelectionView(const Selection* selection, Repaintable* parent, Color selectionColor); virtual ~SelectionView() noexcept; /** * @brief Draws the container to the given context */ void draw(cairo_t* cr) const override; bool isViewOf(const OverlayBase* overlay) const override; static constexpr struct FlagDirtyRegionRequest { } FLAG_DIRTY_REGION = {}; void on(FlagDirtyRegionRequest, Range rg); static constexpr struct DeleteViewsRequest { } DELETE_VIEWS_REQUEST = {}; void deleteOn(DeleteViewsRequest, Range rg); private: const Selection* selection; Color selectionColor; static constexpr double BORDER_WIDTH_IN_PIXELS = 1; static constexpr double FILLING_OPACITY = 0.3; }; }; // namespace xoj::view
1,223
C++
.h
41
26.658537
89
0.740614
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
13,092
TextEditionView.h
xournalpp_xournalpp/src/core/view/overlays/TextEditionView.h
/* * Xournal++ * * View active text edition * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <cairo.h> // for cairo_t #include "util/DispatchPool.h" // for Listener #include "view/overlays/OverlayView.h" class OverlayBase; class TextEditor; class Range; namespace xoj::util { template <typename T> class Rectangle; }; namespace xoj::view { class Repaintable; class TextEditionView final: public ToolView, public xoj::util::Listener<TextEditionView> { public: TextEditionView(const TextEditor* handler, Repaintable* parent); ~TextEditionView() noexcept override; /** * @brief Draws the overlay to the given context */ void draw(cairo_t* cr) const override; void drawWithoutDrawingAids(cairo_t* cr) const override; bool isViewOf(const OverlayBase* overlay) const override; xoj::util::Rectangle<double> toWindowCoordinates(const xoj::util::Rectangle<double>& r) const; /** * Listener interface */ static constexpr struct FlagDirtyRegionRequest { } FLAG_DIRTY_REGION = {}; void on(FlagDirtyRegionRequest, Range rg); static constexpr struct FinalizationRequest { } FINALIZATION_REQUEST = {}; void deleteOn(FinalizationRequest, Range rg); private: const TextEditor* textEditor; public: // Padding between the text logical box and the frame static constexpr int PADDING_IN_PIXELS = 5; // Width of the lines making the frame static constexpr int BORDER_WIDTH_IN_PIXELS = 1; // Width of the cursor in insertion mode (or at the end of a line) static constexpr int INSERTION_CURSOR_WIDTH_IN_PIXELS = 2; }; }; // namespace xoj::view
1,727
C++
.h
54
28.62963
98
0.733574
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
13,093
Action.enum.h
xournalpp_xournalpp/src/core/enums/Action.enum.h
/* * Xournal++ * * Enum for all actions * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <string> #include <glib.h> // for g_warning #include "util/Assert.h" #include "util/StringUtils.h" #include "util/safe_casts.h" // for to_underlying Todo(cpp20) remove /****************************************************************************** ******************************************************************************* RUN THE GENERATOR IF YOU CHANGE THIS FILE! php generateConvertNEW.php ******************************************************************************* ******************************************************************************/ enum class Action : size_t { // Menu file NEW_FILE, OPEN, ANNOTATE_PDF, SAVE, SAVE_AS, EXPORT_AS_PDF, EXPORT_AS, PRINT, QUIT, // Menu edit ARRANGE_SELECTION_ORDER, UNDO, REDO, CUT, COPY, PASTE, SEARCH, SELECT_ALL, DELETE, MOVE_SELECTION_LAYER_UP, MOVE_SELECTION_LAYER_DOWN, ROTATION_SNAPPING, GRID_SNAPPING, PREFERENCES, // Menu View PAIRED_PAGES_MODE, PAIRED_PAGES_OFFSET, PRESENTATION_MODE, FULLSCREEN, SHOW_SIDEBAR, SHOW_TOOLBAR, SET_LAYOUT_VERTICAL, SET_LAYOUT_RIGHT_TO_LEFT, SET_LAYOUT_BOTTOM_TO_TOP, SET_COLUMNS_OR_ROWS, MANAGE_TOOLBAR, CUSTOMIZE_TOOLBAR, SHOW_MENUBAR, ZOOM_IN, ZOOM_OUT, ZOOM_100, ZOOM_FIT, ZOOM, ///< Action whose state is the current zoom value // Menu navigation GOTO_FIRST, GOTO_PREVIOUS, GOTO_PAGE, GOTO_NEXT, GOTO_LAST, GOTO_NEXT_ANNOTATED_PAGE, GOTO_PREVIOUS_ANNOTATED_PAGE, // Menu Journal NEW_PAGE_BEFORE, NEW_PAGE_AFTER, NEW_PAGE_AT_END, DUPLICATE_PAGE, MOVE_PAGE_TOWARDS_BEGINNING, MOVE_PAGE_TOWARDS_END, APPEND_NEW_PDF_PAGES, CONFIGURE_PAGE_TEMPLATE, DELETE_PAGE, PAPER_FORMAT, PAPER_BACKGROUND_COLOR, // Menu Tools SELECT_TOOL, SELECT_DEFAULT_TOOL, TOOL_DRAW_SHAPE_RECOGNIZER, TOOL_DRAW_RECTANGLE, TOOL_DRAW_ELLIPSE, TOOL_DRAW_ARROW, TOOL_DRAW_DOUBLE_ARROW, TOOL_DRAW_COORDINATE_SYSTEM, TOOL_DRAW_LINE, TOOL_DRAW_SPLINE, SETSQUARE, COMPASS, TOOL_PEN_SIZE, TOOL_PEN_LINE_STYLE, TOOL_PEN_FILL, TOOL_PEN_FILL_OPACITY, TOOL_ERASER_SIZE, TOOL_ERASER_TYPE, TOOL_HIGHLIGHTER_SIZE, TOOL_HIGHLIGHTER_FILL, TOOL_HIGHLIGHTER_FILL_OPACITY, TOOL_SELECT_PDF_TEXT_MARKER_OPACITY, AUDIO_RECORD, AUDIO_PAUSE_PLAYBACK, AUDIO_STOP_PLAYBACK, AUDIO_SEEK_FORWARDS, AUDIO_SEEK_BACKWARDS, SELECT_FONT, FONT, ///< Action whose state is the font's description TEX, // Plugin Menu PLUGIN_MANAGER, // Menu Help HELP, ABOUT, // Generic tool config, for the toolbar TOOL_SIZE, TOOL_FILL, TOOL_FILL_OPACITY, TOOL_COLOR, ///< Action whose state is the current color with alpha set to 0xff (in ARGB as a uint32_t) SELECT_COLOR, ///< Pops up a color chooser dialog // Layer handling LAYER_SHOW_ALL, LAYER_HIDE_ALL, LAYER_NEW, LAYER_COPY, LAYER_MOVE_UP, LAYER_MOVE_DOWN, LAYER_DELETE, LAYER_MERGE_DOWN, LAYER_RENAME, LAYER_GOTO_NEXT, LAYER_GOTO_PREVIOUS, LAYER_GOTO_TOP, LAYER_ACTIVE, ///< Action whose state is the current layer index // Miscellaneous POSITION_HIGHLIGHTING, // Keep this last value ENUMERATOR_COUNT }; #include "generated/Action.NameMap.generated.h" constexpr auto Action_toString(Action value) -> const char* { xoj_assert(value < Action::ENUMERATOR_COUNT); return ACTION_NAMES[static_cast<size_t>(value)]; } constexpr auto Action_fromString(const std::string_view value) -> Action { for (size_t n = 0; n < xoj::to_underlying(Action::ENUMERATOR_COUNT); n++) { if (value == ACTION_NAMES[n]) { return static_cast<Action>(n); } } return Action::NEW_FILE; }
4,088
C++
.h
161
20.776398
110
0.614674
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
13,094
Action.NameMap.generated.h
xournalpp_xournalpp/src/core/enums/generated/Action.NameMap.generated.h
// ** THIS FILE IS GENERATED ** // ** use generateConvert.php to update this file ** #pragma once constexpr const char* ACTION_NAMES[] = { // Action to string conversion map "new-file", "open", "annotate-pdf", "save", "save-as", "export-as-pdf", "export-as", "print", "quit", "arrange-selection-order", "undo", "redo", "cut", "copy", "paste", "search", "select-all", "delete", "move-selection-layer-up", "move-selection-layer-down", "rotation-snapping", "grid-snapping", "preferences", "paired-pages-mode", "paired-pages-offset", "presentation-mode", "fullscreen", "show-sidebar", "show-toolbar", "set-layout-vertical", "set-layout-right-to-left", "set-layout-bottom-to-top", "set-columns-or-rows", "manage-toolbar", "customize-toolbar", "show-menubar", "zoom-in", "zoom-out", "zoom-100", "zoom-fit", "zoom", "goto-first", "goto-previous", "goto-page", "goto-next", "goto-last", "goto-next-annotated-page", "goto-previous-annotated-page", "new-page-before", "new-page-after", "new-page-at-end", "duplicate-page", "move-page-towards-beginning", "move-page-towards-end", "append-new-pdf-pages", "configure-page-template", "delete-page", "paper-format", "paper-background-color", "select-tool", "select-default-tool", "tool-draw-shape-recognizer", "tool-draw-rectangle", "tool-draw-ellipse", "tool-draw-arrow", "tool-draw-double-arrow", "tool-draw-coordinate-system", "tool-draw-line", "tool-draw-spline", "setsquare", "compass", "tool-pen-size", "tool-pen-line-style", "tool-pen-fill", "tool-pen-fill-opacity", "tool-eraser-size", "tool-eraser-type", "tool-highlighter-size", "tool-highlighter-fill", "tool-highlighter-fill-opacity", "tool-select-pdf-text-marker-opacity", "audio-record", "audio-pause-playback", "audio-stop-playback", "audio-seek-forwards", "audio-seek-backwards", "select-font", "font", "tex", "plugin-manager", "help", "about", "tool-size", "tool-fill", "tool-fill-opacity", "tool-color", "select-color", "layer-show-all", "layer-hide-all", "layer-new", "layer-copy", "layer-move-up", "layer-move-down", "layer-delete", "layer-merge-down", "layer-rename", "layer-goto-next", "layer-goto-previous", "layer-goto-top", "layer-active", "position-highlighting"};
3,068
C++
.h
115
17.930435
76
0.51322
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
13,095
setup-env.h
xournalpp_xournalpp/src/exe/osx/setup-env.h
#pragma once /** * Sets up all environment variables. */ void setupEnvironment();
85
C++
.h
5
15.4
37
0.746835
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
13,096
console.h
xournalpp_xournalpp/src/exe/win32/console.h
#pragma once /** * Allocates a new (hidden) console and associates the standard input and output handles with it. */ void attachConsole();
142
C++
.h
5
26.8
97
0.764706
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
13,101
FileAppender.cpp
mltframework_shotcut/CuteLogger/src/FileAppender.cpp
/* Copyright (c) 2010 Boris Moiseev (cyberbobs at gmail dot com) This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License version 2.1 as published by the Free Software Foundation and appearing in the file LICENSE.LGPL included in the packaging of this file. 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 Lesser General Public License for more details. */ // Local #include "FileAppender.h" // STL #include <iostream> /** * \class FileAppender * * \brief Simple appender that writes the log records to the plain text file. */ //! Constructs the new file appender assigned to file with the given name. FileAppender::FileAppender(const QString& fileName) : m_flushOnWrite(false) { setFileName(fileName); } FileAppender::~FileAppender() { closeFile(); } //! Returns the name set by setFileName() or to the FileAppender constructor. /** * \sa setFileName() */ QString FileAppender::fileName() const { QMutexLocker locker(&m_logFileMutex); return m_logFile.fileName(); } //! Sets the name of the file. The name can have no path, a relative path, or an absolute path. /** * \sa fileName() */ void FileAppender::setFileName(const QString& s) { if (s.isEmpty()) std::cerr << "<FileAppender::FileAppender> File name is empty. The appender will do nothing" << std::endl; QMutexLocker locker(&m_logFileMutex); if (m_logFile.isOpen()) m_logFile.close(); m_logFile.setFileName(s); } bool FileAppender::flushOnWrite() const { return m_flushOnWrite; } //! Allows FileAppender to flush file immediately after writing a log record. /** * Default value is false. This could result in substantial app slowdown when writing massive amount of log records * with FileAppender on a rather slow file system due to FileAppender blocking until the data would be phisically * written. * * Leaving this as is may result in some log data not being written if the application crashes. */ void FileAppender::setFlushOnWrite(bool flush) { m_flushOnWrite = flush; } //! Force-flush any remaining buffers to file system. Returns true if successful, otherwise returns false. bool FileAppender::flush() { QMutexLocker locker(&m_logFileMutex); if (m_logFile.isOpen()) return m_logFile.flush(); else return true; } bool FileAppender::reopenFile() { closeFile(); return openFile(); } bool FileAppender::openFile() { if (m_logFile.fileName().isEmpty()) return false; bool isOpen = m_logFile.isOpen(); if (!isOpen) { isOpen = m_logFile.open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text); if (isOpen) m_logStream.setDevice(&m_logFile); else std::cerr << "<FileAppender::append> Cannot open the log file " << qPrintable(m_logFile.fileName()) << std::endl; } return isOpen; } //! Write the log record to the file. /** * \sa fileName() * \sa AbstractStringAppender::format() */ void FileAppender::append(const QDateTime& timeStamp, Logger::LogLevel logLevel, const char* file, int line, const char* function, const QString& category, const QString& message) { QMutexLocker locker(&m_logFileMutex); if (openFile()) { m_logStream << formattedString(timeStamp, logLevel, file, line, function, category, message); m_logStream.flush(); if (m_flushOnWrite) m_logFile.flush(); } } void FileAppender::closeFile() { QMutexLocker locker(&m_logFileMutex); m_logFile.close(); }
3,662
C++
.cpp
119
28.016807
119
0.738116
mltframework/shotcut
10,796
1,118
50
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
13,105
mltxmlchecker.cpp
mltframework_shotcut/src/mltxmlchecker.cpp
/* * Copyright (c) 2014-2024 Meltytech, LLC * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "mltxmlchecker.h" #include "mltcontroller.h" #include "shotcut_mlt_properties.h" #include "util.h" #include "proxymanager.h" #include "settings.h" #include <QLocale> #include <QDir> #include <QCoreApplication> #include <QUrl> #include <QRegularExpression> #include <Logger.h> #include <clocale> #include <utime.h> static QString getPrefix(const QString &name, const QString &value); static bool isMltClass(const QString &name) { return name == "profile" || name == "producer" || name == "filter" || name == "playlist" || name == "tractor" || name == "track" || name == "transition" || name == "consumer" || name == "chain" || name == "link"; } static bool isNetworkResource(const QString &string) { // Check if it looks like a qualified URL. Try parsing it and see. QRegularExpression schemaTest(QLatin1String("^[a-zA-Z]{2,}\\:.*")); // Not actually checking network URL due to latency and transience. return (schemaTest.match(string).hasMatch() && QUrl(string).isValid() && !string.startsWith("plain:")); } static bool isNumericProperty(const QString &name) { return name == "length" || name == "geometry" || name == "rect" || name == "warp_speed"; } MltXmlChecker::MltXmlChecker() : m_needsGPU(false) , m_needsCPU(false) , m_hasEffects(false) , m_isCorrected(false) , m_isUpdated(false) , m_decimalPoint('.') , m_numericValueChanged(false) { m_unlinkedFilesModel.setColumnCount(ColumnCount); } QXmlStreamReader::Error MltXmlChecker::check(const QString &fileName) { LOG_DEBUG() << "begin"; QFile file(fileName); m_tempFile.reset(new QTemporaryFile( QFileInfo(fileName).dir().filePath("shotcut-XXXXXX.mlt"))); if (file.open(QIODevice::ReadOnly | QIODevice::Text) && m_tempFile->open()) { m_tempFile->resize(0); m_fileInfo = QFileInfo(fileName); m_xml.setDevice(&file); m_newXml.setDevice(m_tempFile.data()); m_newXml.setAutoFormatting(true); m_newXml.setAutoFormattingIndent(2); if (m_xml.readNextStartElement()) { if (m_xml.name().toString() == "mlt") { m_newXml.writeStartDocument(); m_newXml.writeCharacters("\n"); m_newXml.writeStartElement("mlt"); foreach (QXmlStreamAttribute a, m_xml.attributes()) { if (a.name().toString().toUpper() == "LC_NUMERIC") { QString value = a.value().toString().toUpper(); m_newXml.writeAttribute("LC_NUMERIC", "C"); MLT.resetLocale(); m_decimalPoint = '.'; } else if (a.name().toString().toLower() == "version") { m_mltVersion = QVersionNumber::fromString(a.value()); } else if (a.name().toString().toLower() == "title") { m_newXml.writeAttribute(a.name().toString(), "Shotcut version " SHOTCUT_VERSION); auto parts = a.value().split(' '); LOG_DEBUG() << parts; if (parts.size() > 2 && parts[1].toString() == "version") { m_shotcutVersion = parts[2].toString(); } } else { m_newXml.writeAttribute(a); } } if (!checkMltVersion()) { return QXmlStreamReader::CustomError; } readMlt(); m_newXml.writeEndElement(); m_newXml.writeEndDocument(); m_isCorrected = m_isCorrected || m_numericValueChanged; } else { m_xml.raiseError(QObject::tr("The file is not a MLT XML file.")); } } } LOG_DEBUG() << m_tempFile->fileName(); if (m_tempFile->isOpen()) { m_tempFile->close(); // Useful for debugging // m_tempFile->open(); // LOG_DEBUG() << m_tempFile->readAll().constData(); // m_tempFile->close(); } LOG_DEBUG() << "end" << m_xml.errorString(); return m_xml.error(); } QString MltXmlChecker::errorString() const { return m_xml.errorString(); } void MltXmlChecker::readMlt() { Q_ASSERT(m_xml.isStartElement() && m_xml.name().toString() == "mlt"); bool isPropertyElement = false; while (!m_xml.atEnd()) { switch (m_xml.readNext()) { case QXmlStreamReader::Characters: if (!isPropertyElement) m_newXml.writeCharacters(m_xml.text().toString()); break; case QXmlStreamReader::Comment: m_newXml.writeComment(m_xml.text().toString()); break; case QXmlStreamReader::DTD: m_newXml.writeDTD(m_xml.text().toString()); break; case QXmlStreamReader::EntityReference: m_newXml.writeEntityReference(m_xml.name().toString()); break; case QXmlStreamReader::ProcessingInstruction: m_newXml.writeProcessingInstruction(m_xml.processingInstructionTarget().toString(), m_xml.processingInstructionData().toString()); break; case QXmlStreamReader::StartDocument: m_newXml.writeStartDocument(m_xml.documentVersion().toString(), m_xml.isStandaloneDocument()); break; case QXmlStreamReader::EndDocument: m_newXml.writeEndDocument(); break; case QXmlStreamReader::StartElement: { const QString element = m_xml.name().toString(); isPropertyElement = false; if (element == "property") { isPropertyElement = true; if (isMltClass(mlt_class)) { const QString name = m_xml.attributes().value("name").toString(); m_properties << MltProperty(name, m_xml.readElementText()); } } else { processProperties(); m_newXml.writeStartElement(m_xml.namespaceUri().toString(), element); if (isMltClass(m_xml.name().toString())) mlt_class = element; checkInAndOutPoints(); // This also copies the attributes. } break; } case QXmlStreamReader::EndElement: if (m_xml.name().toString() != "property") { processProperties(); m_newXml.writeEndElement(); if (isMltClass(m_xml.name().toString())) { mlt_class.clear(); } } break; default: break; } } } void MltXmlChecker::processProperties() { QString mlt_service; QVector<MltProperty> newProperties; m_resource.clear(); // First pass: collect information about mlt_service and resource. foreach (MltProperty p, m_properties) { // Get the name of the MLT service. if (p.first == "mlt_service") { mlt_service = p.second; } else if (p.first == kShotcutHashProperty) { m_resource.hash = p.second; } else if (p.first.startsWith(kIsProxyProperty)) { m_resource.isProxy = true; } else if (isNumericProperty(p.first)) { checkNumericString(p.second); } else if (p.first == "resource" && mlt_service == "webvfx" && fixWebVfxPath(p.second)) { } else if (readResourceProperty(p.first, p.second)) { #ifdef Q_OS_WIN fixVersion1701WindowsPathBug(p.second); #endif // Check timewarp producer's resource property prefix. QString prefix = getPrefix(p.first, p.second); if (!prefix.isEmpty() && prefix != "plain:") { if (checkNumericString(prefix)) p.second = prefix + p.second.mid(p.second.indexOf(':') + 1); } fixUnlinkedFile(p.second); } newProperties << MltProperty(p.first, p.second); } if (mlt_class == "filter" || mlt_class == "transition" || mlt_class == "producer" || mlt_class == "chain" || mlt_class == "link") { checkGpuEffects(mlt_service); checkCpuEffects(mlt_service); checkUnlinkedFile(mlt_service); checkIncludesSelf(newProperties); checkLumaAlphaOver(mlt_service, newProperties); #if LIBMLT_VERSION_INT >= ((6<<16)+(23<<8)) replaceWebVfxCropFilters(mlt_service, newProperties); replaceWebVfxChoppyFilter(mlt_service, newProperties); #endif bool proxyEnabled = Settings.proxyEnabled(); if (proxyEnabled) checkForProxy(mlt_service, newProperties); // Second pass: amend property values. bool relinkMismatch = !m_resource.hash.isEmpty() && !m_resource.newHash.isEmpty() && m_resource.hash != m_resource.newHash; m_properties = newProperties; newProperties.clear(); foreach (MltProperty p, m_properties) { // Fix some properties if re-linked file. if (p.first == kShotcutHashProperty) { if (!m_resource.newHash.isEmpty()) p.second = m_resource.newHash; } else if (p.first == kShotcutCaptionProperty) { if (!m_resource.newDetail.isEmpty()) p.second = Util::baseName(m_resource.newDetail); } else if (p.first == kShotcutDetailProperty) { // We no longer save this (leaks absolute paths). p.second.clear(); } else if (relinkMismatch && p.first == "audio_index") { // Reset stream index properties if re-linked file is different. p.second = QString::number(m_resource.audio_index); } else if (relinkMismatch && p.first == "astream") { p.second = "0"; } else if (relinkMismatch && p.first == "video_index") { p.second = QString::number(m_resource.video_index); } else if (relinkMismatch && p.first == "vstream") { p.second = "0"; } else if (relinkMismatch && p.first.startsWith("meta.")) { // Remove meta properties if re-linked file is different. p.second.clear(); } else if ((proxyEnabled && m_resource.notProxyMeta && p.first.startsWith("meta.")) || (!proxyEnabled && m_resource.isProxy && (p.first == kIsProxyProperty || p.first.startsWith("meta.")))) { // Remove meta properties if they misrepresent proxy/original p.second.clear(); m_isUpdated = true; } if (!p.second.isEmpty()) newProperties << MltProperty(p.first, p.second); } } // Write all of the properties. foreach (MltProperty p, newProperties) { m_newXml.writeStartElement("property"); m_newXml.writeAttribute("name", p.first); m_newXml.writeCharacters(p.second); m_newXml.writeEndElement(); } m_properties.clear(); } void MltXmlChecker::checkInAndOutPoints() { Q_ASSERT(m_xml.isStartElement()); // Fix numeric values of in and out point attributes. foreach (QXmlStreamAttribute a, m_xml.attributes()) { if (a.name().toString() == "in" || a.name().toString() == "out") { QString value = a.value().toString(); if (checkNumericString(value)) { m_newXml.writeAttribute(a.name().toString(), value); continue; } } m_newXml.writeAttribute(a); } } bool MltXmlChecker::checkNumericString(QString &value) { // Determine if there is a decimal point inconsistent with locale. if (!value.contains(m_decimalPoint) && (value.contains('.') || value.contains(','))) { value.replace(',', m_decimalPoint); value.replace('.', m_decimalPoint); m_numericValueChanged = true; return true; } return false; } bool MltXmlChecker::fixWebVfxPath(QString &resource) { // The path, if absolute, should start with the Shotcut executable path. QFileInfo fi(resource); if (fi.isAbsolute() || Util::hasDriveLetter(resource)) { QDir appPath(QCoreApplication::applicationDirPath()); #if defined(Q_OS_MAC) // Leave the MacOS directory appPath.cdUp(); #elif defined(Q_OS_UNIX) && !defined(Q_OS_MAC) // Leave the bin directory on Linux. appPath.cdUp(); #endif if (!resource.startsWith(appPath.path())) { // Locate "share/shotcut" and replace the front of it with appPath. int i = resource.indexOf("/share/shotcut/"); #if defined(Q_OS_MAC) if (i == -1) i = resource.indexOf("/Resources/shotcut/"); #endif if (i >= 0) { resource.replace(0, i, appPath.path()); m_isUpdated = true; return true; } } } return false; } static QString getPrefix(const QString &name, const QString &value) { int length = 0; // Webvfx and timewarp are only using "resource". if (name == "resource") { const QString plain("plain:"); // webvfx "plain:" if (value.startsWith(plain)) { return plain; } else { // timewarp speed parameter length = value.indexOf(':'); if (length > 0) { bool isNumeric = true; for (int i = 0; i < length && isNumeric; i++) { if (!value[i].isDigit() && value[i] != '.' && value[i] != ',') isNumeric = false; } if (isNumeric) return value.left(length + 1); // include the colon } } } return QString(); } static QString getSuffix(const QString &name, const QString &value) { // avformat is only using "resource" if (name == "resource") { const QString queryDelimiter("\\?"); const auto i = value.lastIndexOf(queryDelimiter); // webvfx "plain:" if (i > 0) { return value.mid(i); } } return QString(); } bool MltXmlChecker::readResourceProperty(const QString &name, QString &value) { if (mlt_class == "filter" || mlt_class == "transition" || mlt_class == "producer" || mlt_class == "chain" || mlt_class == "link") if (name == "resource" || name == "src" || name == "filename" || name == "luma" || name == "luma.resource" || name == "composite.luma" || name == "producer.resource" || name == "av.file" || name == "warp_resource") { // Handle special prefix such as "plain:" or speed. m_resource.prefix = getPrefix(name, value); m_resource.suffix = getSuffix(name, value); auto filePath = value.mid(m_resource.prefix.size()); filePath = filePath.left(filePath.size() - m_resource.suffix.size()); // Save the resource name (minus prefix) for later check for unlinked files. m_resource.info.setFile(filePath); if (!isNetworkResource(value) && m_resource.info.isRelative() && !Util::hasDriveLetter(value)) m_resource.info.setFile(m_fileInfo.canonicalPath(), m_resource.info.filePath()); return true; } return false; } void MltXmlChecker::checkGpuEffects(const QString &mlt_service) { // Check for GPU effects. if (!MLT.isAudioFilter(mlt_service)) m_hasEffects = true; if (mlt_service.startsWith("movit.") || mlt_service.startsWith("glsl.")) m_needsGPU = true; } void MltXmlChecker::checkCpuEffects(const QString &mlt_service) { if (mlt_service.startsWith("frei0r.cairoblend") || mlt_service.startsWith("choppy")) m_needsCPU = true; } void MltXmlChecker::checkUnlinkedFile(const QString &mlt_service) { // Check for an unlinked file. const QString fileName = m_resource.info.fileName(); const QString filePath = QDir::toNativeSeparators(m_resource.info.filePath()); // not the color producer if (!mlt_service.isEmpty() && mlt_service != "color" && mlt_service != "colour") // not a builtin luma wipe file if ((mlt_service != "luma" && mlt_service != "movit.luma_mix") || !fileName.startsWith('%')) // not a Stabilize filter without Analyze results if (fileName != "vidstab.trf") // not the generic <producer> resource if (fileName != "<producer>") // not an invalid <tractor> if (fileName != "<tractor>") // not an invalid blank if (mlt_service != "blank" || fileName != "blank") // not a URL if (!m_resource.info.filePath().isEmpty() && !isNetworkResource(m_resource.info.filePath())) // not an image sequence if ((mlt_service != "pixbuf" && mlt_service != "qimage") || fileName.indexOf('%') == -1) // file does not exist if (!m_resource.info.exists()) // not already in the model if (m_unlinkedFilesModel.findItems(filePath, Qt::MatchFixedString | Qt::MatchCaseSensitive).isEmpty()) { LOG_ERROR() << "file not found: " << m_resource.info.filePath(); QIcon icon(":/icons/oxygen/32x32/status/task-reject.png"); QStandardItem *item = new QStandardItem(icon, filePath); item->setToolTip(item->text()); item->setData(m_resource.hash, ShotcutHashRole); m_unlinkedFilesModel.appendRow(item); } } bool MltXmlChecker::fixUnlinkedFile(QString &value) { // Replace unlinked files if model is populated with replacements. for (int row = 0; row < m_unlinkedFilesModel.rowCount(); ++row) { const QStandardItem *replacement = m_unlinkedFilesModel.item(row, ReplacementColumn); if (replacement && !replacement->text().isEmpty() && m_unlinkedFilesModel.item(row, MissingColumn)->text() == QDir::toNativeSeparators(m_resource.info.filePath())) { m_resource.info.setFile(replacement->text()); m_resource.newDetail = replacement->text(); m_resource.newHash = replacement->data(ShotcutHashRole).toString(); value = QDir::fromNativeSeparators(replacement->text()); // Convert to relative path if possible. if (value.startsWith(m_fileInfo.canonicalPath() + "/")) value = value.mid(m_fileInfo.canonicalPath().size() + 1); // Restore special prefix such as "plain:" or speed value. value.prepend(m_resource.prefix); value.append(m_resource.suffix); m_isCorrected = true; Mlt::Producer producer(MLT.profile(), m_resource.info.filePath().toUtf8().constData()); if (producer.is_valid() && !::qstrcmp(producer.get("mlt_service"), "avformat")) { m_resource.audio_index = producer.get_int("audio_index"); m_resource.video_index = producer.get_int("video_index"); } return true; } } return false; } bool MltXmlChecker::fixVersion1701WindowsPathBug(QString &value) { if (value.size() >= 3 && value[0] == '/' && value[2] == ':') { value.remove(0, 1); m_isCorrected = true; return true; } return false; } void MltXmlChecker::checkIncludesSelf(QVector<MltProperty> &properties) { if (m_resource.info.canonicalFilePath() == m_fileInfo.canonicalFilePath()) { LOG_WARNING() << "This project tries to include itself; breaking that!"; for (auto &p : properties) { if (p.first == "mlt_service") p.second.clear(); else if (p.first == "resource") p.second = "+INVALID.txt"; } properties << MltProperty(kShotcutCaptionProperty, "INVALID"); m_isCorrected = true; } } void MltXmlChecker::checkLumaAlphaOver(const QString &mlt_service, QVector<MltXmlChecker::MltProperty> &properties) { if (mlt_service == "luma") { bool found = false; for (auto &p : properties) { if (p.first == "alpha_over") { found = true; } } if (!found) { properties << MltProperty("alpha_over", "1"); m_isUpdated = true; } } } void MltXmlChecker::replaceWebVfxCropFilters(QString &mlt_service, QVector<MltXmlChecker::MltProperty> &properties) { if (mlt_service == "webvfx") { auto isCrop = false; for (auto &p : properties) { if (p.first == "shotcut:filter" && p.second == "webvfxCircularFrame") { p.second = "cropCircle"; properties << MltProperty("circle", "1"); m_isUpdated = isCrop = true; break; } if (p.first == "shotcut:filter" && p.second == "webvfxClip") { p.second = "cropRectangle"; m_isUpdated = isCrop = true; break; } } if (isCrop) { mlt_service = "qtcrop"; for (auto &p : properties) { if (p.first == "resource") { properties.removeOne(p); break; } } for (auto &p : properties) { if (p.first == "mlt_service") { p.second = "qtcrop"; break; } } } } } void MltXmlChecker::replaceWebVfxChoppyFilter(QString &mlt_service, QVector<MltXmlChecker::MltProperty> &properties) { if (mlt_service == "webvfx") { auto isChoppy = false; QString shotcutFilter; for (auto &p : properties) { if (p.first == "shotcut:filter") { shotcutFilter = p.second; if (p.second == "webvfxChoppy") { properties.removeOne(p); m_isUpdated = isChoppy = true; break; } } } if (isChoppy) { mlt_service = "choppy"; for (auto &p : properties) { if (p.first == "resource") { properties.removeOne(p); break; } } for (auto &p : properties) { if (p.first == "mlt_service") { p.second = "choppy"; break; } } } else if (shotcutFilter.isEmpty()) { mlt_service = "qtext"; m_isUpdated = true; for (auto &p : properties) { if (p.first == "resource") { auto pathName = p.second; auto plain = QLatin1String("plain:"); if (pathName.startsWith(plain)) { pathName = pathName.mid(plain.size()); } if (QFileInfo(pathName).isRelative()) { QDir projectDir(QFileInfo(m_tempFile->fileName()).dir()); pathName = projectDir.filePath(pathName); } QFile file(pathName); if (file.open(QIODevice::ReadOnly)) { p.first = "html"; p.second = QString::fromUtf8(file.readAll()); } break; } } for (auto &p : properties) { if (p.first == "mlt_service") { p.second = "qtext"; break; } } properties << MltProperty("shotcut:filter", "richText"); } } } void MltXmlChecker::checkForProxy(const QString &mlt_service, QVector<MltXmlChecker::MltProperty> &properties) { bool isTimewarp = mlt_service == "timewarp"; if (mlt_service.startsWith("avformat") || isTimewarp) { QString resource; QString hash; QString speed = "1"; for (auto &p : properties) { if ((!isTimewarp && p.first == "resource") || p.first == "warp_resource") { QFileInfo info(p.second); if (info.isRelative()) info.setFile(m_fileInfo.canonicalPath(), p.second); resource = info.filePath(); } else if (p.first == kShotcutHashProperty) { hash = p.second; } else if (p.first == "warp_speed") { speed = p.second; } else if (p.first == kDisableProxyProperty && p.second == "1") { return; } } // Use GoPro LRV if available if (QFile::exists(ProxyManager::GoProProxyFilePath(resource))) { for (auto &p : properties) { if (p.first == "resource") { p.second = ProxyManager::GoProProxyFilePath(resource); if (isTimewarp) { p.second = QStringLiteral("%1:%2").arg(speed, p.second); } properties << MltProperty(kIsProxyProperty, "1"); properties << MltProperty(kMetaProxyProperty, "1"); properties << MltProperty(kOriginalResourceProperty, resource); m_resource.notProxyMeta = !m_resource.isProxy; m_isUpdated = true; return; } } } // Use DJI LRF if available if (QFile::exists(ProxyManager::DJIProxyFilePath(resource))) { for (auto &p : properties) { if (p.first == "resource") { p.second = ProxyManager::DJIProxyFilePath(resource); if (isTimewarp) { p.second = QStringLiteral("%1:%2").arg(speed, p.second); } properties << MltProperty(kIsProxyProperty, "1"); properties << MltProperty(kMetaProxyProperty, "1"); properties << MltProperty(kOriginalResourceProperty, resource); m_resource.notProxyMeta = !m_resource.isProxy; m_isUpdated = true; return; } } } QDir proxyDir(Settings.proxyFolder()); QDir projectDir(QFileInfo(m_tempFile->fileName()).dir()); QString fileName = hash + ProxyManager::videoFilenameExtension(); projectDir.cd("proxies"); if (proxyDir.exists(fileName) || projectDir.exists(fileName)) { ::utime(proxyDir.filePath(fileName).toUtf8().constData(), nullptr); ::utime(projectDir.filePath(fileName).toUtf8().constData(), nullptr); for (auto &p : properties) { if (p.first == "resource") { if (projectDir.exists(fileName)) { p.second = projectDir.filePath(fileName); } else { p.second = proxyDir.filePath(fileName); } if (isTimewarp) { p.second = QStringLiteral("%1:%2").arg(speed, p.second); } break; } } properties << MltProperty(kIsProxyProperty, "1"); properties << MltProperty(kMetaProxyProperty, "1"); properties << MltProperty(kOriginalResourceProperty, resource); m_resource.notProxyMeta = !m_resource.isProxy; m_isUpdated = true; } } else if ((mlt_service == "qimage" || mlt_service == "pixbuf") && !properties.contains(MltProperty(kShotcutSequenceProperty, "1"))) { QString resource; QString hash; for (auto &p : properties) { if (p.first == "resource") { QFileInfo info(p.second); if (info.isRelative()) info.setFile(m_fileInfo.canonicalPath(), p.second); resource = info.filePath(); } else if (p.first == kShotcutHashProperty) { hash = p.second; } else if (p.first == kDisableProxyProperty && p.second == "1") { return; } } QDir proxyDir(Settings.proxyFolder()); QDir projectDir(QFileInfo(m_tempFile->fileName()).dir()); QString fileName = hash + ProxyManager::imageFilenameExtension(); projectDir.cd("proxies"); if (proxyDir.exists(fileName) || projectDir.exists(fileName)) { ::utime(proxyDir.filePath(fileName).toUtf8().constData(), nullptr); ::utime(projectDir.filePath(fileName).toUtf8().constData(), nullptr); for (auto &p : properties) { if (p.first == "resource") { if (projectDir.exists(fileName)) { p.second = projectDir.filePath(fileName); } else { p.second = proxyDir.filePath(fileName); } break; } } properties << MltProperty(kIsProxyProperty, "1"); properties << MltProperty(kMetaProxyProperty, "1"); properties << MltProperty(kOriginalResourceProperty, resource); m_resource.notProxyMeta = !m_resource.isProxy; m_isUpdated = true; } } } bool MltXmlChecker::checkMltVersion() { if (m_mltVersion.majorVersion() > 7) { return false; } return true; }
31,284
C++
.cpp
740
30.148649
134
0.537591
mltframework/shotcut
10,796
1,118
50
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
13,106
jobqueue.cpp
mltframework_shotcut/src/jobqueue.cpp
/* * Copyright (c) 2012-2024 Meltytech, LLC * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "jobqueue.h" #include <QtWidgets> #include <Logger.h> #if defined(Q_OS_WIN) && (QT_VERSION < QT_VERSION_CHECK(6, 0, 0)) #include "windowstools.h" #endif JobQueue::JobQueue(QObject *parent) : QStandardItemModel(0, COLUMN_COUNT, parent), m_paused(false) { } JobQueue &JobQueue::singleton(QObject *parent) { static JobQueue *instance = 0; if (!instance) instance = new JobQueue(parent); return *instance; } void JobQueue::cleanup() { QMutexLocker locker(&m_mutex); foreach (AbstractJob *job, m_jobs) { if (job->state() == QProcess::Running) { job->stop(); break; } } qDeleteAll(m_jobs); } AbstractJob *JobQueue::add(AbstractJob *job) { QList<QStandardItem *> items; QIcon icon = QIcon::fromTheme("run-build", QIcon(":/icons/oxygen/32x32/actions/run-build.png")); items << new QStandardItem(icon, ""); QStandardItem *item = new QStandardItem(job->label()); items << item; item = new QStandardItem(tr("pending")); QFont font = QFontDatabase::systemFont(QFontDatabase::FixedFont); font.setPointSize(QGuiApplication::font().pointSize()); item->setFont(font); item->setToolTip(tr("Estimated Hours:Minutes:Seconds")); items << item; appendRow(items); job->setParent(this); job->setStandardItem(item); connect(job, SIGNAL(progressUpdated(QStandardItem *, int)), SLOT(onProgressUpdated(QStandardItem *, int))); connect(job, SIGNAL(finished(AbstractJob *, bool, QString)), SLOT(onFinished(AbstractJob *, bool, QString))); m_mutex.lock(); m_jobs.append(job); m_mutex.unlock(); emit jobAdded(); startNextJob(); return job; } void JobQueue::onProgressUpdated(QStandardItem *standardItem, int percent) { if (standardItem) { AbstractJob *job = m_jobs.at(standardItem->row()); if (job) { QString remaining("--:--:--"); QIcon icon(":/icons/oxygen/32x32/actions/run-build.png"); if (job->paused()) { icon = QIcon(":/icons/oxygen/32x32/actions/media-playback-pause.png"); remaining = tr("paused"); } else if (percent > 0) { auto time = job->estimateRemaining(percent); if (percent > 2 && QTime(0, 0).secsTo(time) > 0) remaining = time.toString(); remaining = QStringLiteral("%1% (%2)").arg(percent).arg(remaining); } standardItem->setText(remaining); standardItem = JOBS.item(standardItem->row(), JobQueue::COLUMN_ICON); if (standardItem) standardItem->setIcon(icon); } } #if defined(Q_OS_WIN) && (QT_VERSION < QT_VERSION_CHECK(6, 0, 0)) WindowsTaskbarButton::getInstance().setProgress(percent); #endif } void JobQueue::onFinished(AbstractJob *job, bool isSuccess, QString time) { QStandardItem *item = job->standardItem(); if (item) { QIcon icon; if (isSuccess) { const QTime &time = QTime::fromMSecsSinceStartOfDay(job->time().elapsed()); item->setText(time.toString()); item->setToolTip(tr("Elapsed Hours:Minutes:Seconds")); icon = QIcon(":/icons/oxygen/32x32/status/task-complete.png"); } else if (job->stopped()) { item->setText(tr("stopped")); icon = QIcon(":/icons/oxygen/32x32/status/task-attempt.png"); } else { item->setText(tr("failed").append(' ').append(time)); icon = QIcon(":/icons/oxygen/32x32/status/task-reject.png"); } // Remove any touched or incomplete pending proxy files if (job->stopped() || !isSuccess) if (job->objectName().contains("proxies") && job->objectName().contains(".pending")) { QFile::remove(job->objectName()); } item = JOBS.item(item->row(), JobQueue::COLUMN_ICON); if (item) item->setIcon(icon); } #if defined(Q_OS_WIN) && (QT_VERSION < QT_VERSION_CHECK(6, 0, 0)) WindowsTaskbarButton::getInstance().resetProgress(); #endif startNextJob(); } void JobQueue::startNextJob() { if (m_paused) return; QMutexLocker locker(&m_mutex); if (!m_jobs.isEmpty()) { foreach (AbstractJob *job, m_jobs) { // if there is already a job started or running, then exit if (job->ran() && job->state() != QProcess::NotRunning) break; // otherwise, start first non-started job and exit if (!job->ran()) { job->start(); break; } } } } AbstractJob *JobQueue::jobFromIndex(const QModelIndex &index) const { return m_jobs.at(index.row()); } void JobQueue::pause() { m_paused = true; } void JobQueue::pauseCurrent() { for (auto job : m_jobs) { if (job->state() == QProcess::Running) { job->pause(); break; } } } void JobQueue::resume() { m_paused = false; startNextJob(); } void JobQueue::resumeCurrent() { for (auto job : m_jobs) { if (job->state() == QProcess::Running) { job->resume(); break; } } } bool JobQueue::isPaused() const { return m_paused; } bool JobQueue::hasIncomplete() const { foreach (AbstractJob *job, m_jobs) { if (!job->ran() || job->state() == QProcess::Running) return true; } return false; } void JobQueue::remove(const QModelIndex &index) { int row = index.row(); removeRow(index.row()); m_mutex.lock(); AbstractJob *job = m_jobs.at(row); m_jobs.removeOne(job); delete job; m_mutex.unlock(); } void JobQueue::removeFinished() { QMutexLocker locker(&m_mutex); auto row = 0; foreach (AbstractJob *job, m_jobs) { if (job->ran() && job->state() != QProcess::Running) { removeRow(row); m_jobs.removeOne(job); delete job; } else { ++row; } } }
6,915
C++
.cpp
213
25.502347
103
0.598143
mltframework/shotcut
10,796
1,118
50
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
13,107
openotherdialog.cpp
mltframework_shotcut/src/openotherdialog.cpp
/* * Copyright (c) 2012-2023 Meltytech, LLC * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "openotherdialog.h" #include "ui_openotherdialog.h" #include "mltcontroller.h" #include <Mlt.h> #include <QtWidgets> #define ENABLE_SCREEN_CAPTURE (0) OpenOtherDialog::OpenOtherDialog(QWidget *parent) : QDialog(parent), ui(new Ui::OpenOtherDialog) { ui->setupUi(this); m_current = ui->networkWidget; m_addTimelineButton = ui->buttonBox->addButton(tr("Add To Timeline"), QDialogButtonBox::ApplyRole); connect(m_addTimelineButton, &QPushButton::clicked, this, [ = ]() { done(-1); }); QScopedPointer<Mlt::Properties> mltProducers(MLT.repository()->producers()); QScopedPointer<Mlt::Properties> mltFilters(MLT.repository()->filters()); QTreeWidgetItem *group = new QTreeWidgetItem(ui->treeWidget, QStringList(tr("Network"))); group->setData(0, Qt::UserRole, ui->networkTab->objectName()); ui->treeWidget->setCurrentItem(group); // populate the device group group = new QTreeWidgetItem(ui->treeWidget, QStringList(tr("Device"))); if (mltProducers->get_data("decklink")) { QTreeWidgetItem *item = new QTreeWidgetItem(group, QStringList(tr("SDI/HDMI"))); item->setData(0, Qt::UserRole, ui->decklinkTab->objectName()); } #if defined(Q_OS_UNIX) && !defined(Q_OS_MAC) QTreeWidgetItem *item = new QTreeWidgetItem(group, QStringList(tr("Video4Linux"))); item->setData(0, Qt::UserRole, ui->v4lTab->objectName()); item = new QTreeWidgetItem(group, QStringList(tr("PulseAudio"))); item->setData(0, Qt::UserRole, ui->pulseTab->objectName()); item = new QTreeWidgetItem(group, QStringList(tr("JACK Audio"))); item->setData(0, Qt::UserRole, ui->jackTab->objectName()); item = new QTreeWidgetItem(group, QStringList(tr("ALSA Audio"))); item->setData(0, Qt::UserRole, ui->alsaTab->objectName()); #if ENABLE_SCREEN_CAPTURE item = new QTreeWidgetItem(group, QStringList(tr("Screen"))); item->setData(0, Qt::UserRole, ui->x11grabTab->objectName()); #endif #elif defined(Q_OS_WIN) QTreeWidgetItem *item = new QTreeWidgetItem(group, QStringList(tr("Audio/Video Device"))); item->setData(0, Qt::UserRole, ui->dshowVideoTab->objectName()); #if ENABLE_SCREEN_CAPTURE item = new QTreeWidgetItem(group, QStringList(tr("Screen"))); item->setData(0, Qt::UserRole, ui->gdigrabTab->objectName()); #endif #elif defined(Q_OS_MAC) QTreeWidgetItem *item = new QTreeWidgetItem(group, QStringList(tr("Audio/Video Device"))); item->setData(0, Qt::UserRole, ui->avfoundationTab->objectName()); #endif // populate the generators group = new QTreeWidgetItem(ui->treeWidget, QStringList(tr("Generator"))); if (mltProducers->get_data("color")) { QTreeWidgetItem *item = new QTreeWidgetItem(group, QStringList(tr("Color"))); item->setData(0, Qt::UserRole, ui->colorTab->objectName()); if (mltProducers->get_data("qtext") && mltFilters->get_data("dynamictext")) { QTreeWidgetItem *item = new QTreeWidgetItem(group, QStringList(tr("Text"))); item->setData(0, Qt::UserRole, ui->textTab->objectName()); } } if (mltProducers->get_data("glaxnimate")) { QTreeWidgetItem *item = new QTreeWidgetItem(group, QStringList(tr("Animation"))); item->setData(0, Qt::UserRole, ui->glaxnimateTab->objectName()); } if (mltProducers->get_data("noise")) { QTreeWidgetItem *item = new QTreeWidgetItem(group, QStringList(tr("Noise"))); item->setData(0, Qt::UserRole, ui->noiseTab->objectName()); } if (mltProducers->get_data("frei0r.ising0r")) { QTreeWidgetItem *item = new QTreeWidgetItem(group, QStringList(tr("Ising"))); item->setData(0, Qt::UserRole, ui->isingTab->objectName()); } if (mltProducers->get_data("frei0r.lissajous0r")) { QTreeWidgetItem *item = new QTreeWidgetItem(group, QStringList(tr("Lissajous"))); item->setData(0, Qt::UserRole, ui->lissajousTab->objectName()); } if (mltProducers->get_data("frei0r.plasma")) { QTreeWidgetItem *item = new QTreeWidgetItem(group, QStringList(tr("Plasma"))); item->setData(0, Qt::UserRole, ui->plasmaTab->objectName()); } if (mltProducers->get_data("frei0r.test_pat_B")) { QTreeWidgetItem *item = new QTreeWidgetItem(group, QStringList(tr("Color Bars"))); item->setData(0, Qt::UserRole, ui->colorbarsTab->objectName()); } if (mltProducers->get_data("tone")) { QTreeWidgetItem *item = new QTreeWidgetItem(group, QStringList(tr("Audio Tone"))); item->setData(0, Qt::UserRole, ui->toneTab->objectName()); } if (mltProducers->get_data("count")) { QTreeWidgetItem *item = new QTreeWidgetItem(group, QStringList(tr("Count"))); item->setData(0, Qt::UserRole, ui->countTab->objectName()); } if (mltProducers->get_data("blipflash")) { QTreeWidgetItem *item = new QTreeWidgetItem(group, QStringList(tr("Blip Flash"))); item->setData(0, Qt::UserRole, ui->blipTab->objectName()); } ui->treeWidget->expandAll(); } OpenOtherDialog::~OpenOtherDialog() { delete ui; } Mlt::Producer *OpenOtherDialog::newProducer(Mlt::Profile &profile, QObject *widget) const { return dynamic_cast<AbstractProducerWidget *>(widget)->newProducer(profile); } Mlt::Producer *OpenOtherDialog::newProducer(Mlt::Profile &profile) const { return newProducer(profile, m_current); } void OpenOtherDialog::load(Mlt::Producer *producer) { if (producer && producer->is_valid()) { QString service(producer->get("mlt_service")); QString resource(MLT.resource()); if (resource.startsWith("video4linux2:")) selectTreeWidget(tr("Video4Linux")); else if (resource.startsWith("pulse:")) selectTreeWidget(tr("PulseAudio")); else if (resource.startsWith("jack:")) selectTreeWidget(tr("JACK Audio")); else if (resource.startsWith("alsa:")) selectTreeWidget(tr("ALSA Audio")); else if (resource.startsWith("dshow:")) selectTreeWidget(tr("Audio/Video Device")); else if (resource.startsWith("x11grab:") || resource.startsWith("gdigrab:")) selectTreeWidget(tr("Screen")); else if (service.startsWith("avformat")) selectTreeWidget(tr("Network")); else if (service == "decklink" || resource.contains("decklink")) selectTreeWidget(tr("SDI/HDMI")); else if (service == "color") selectTreeWidget(tr("Color")); else if (service == "glaxnimate") selectTreeWidget(tr("Animation")); else if (service == "noise") selectTreeWidget(tr("Noise")); else if (service == "frei0r.ising0r") selectTreeWidget(tr("Ising")); else if (service == "frei0r.lissajous0r") selectTreeWidget(tr("Lissajous")); else if (service == "frei0r.plasma") selectTreeWidget(tr("Plasma")); else if (service == "frei0r.test_pat_B") selectTreeWidget(tr("Color Bars")); else if (service == "tone") selectTreeWidget(tr("Audio Tone")); else if (service == "count") selectTreeWidget(tr("Count")); else if (service == "blipflash") selectTreeWidget(tr("Blip Flash")); dynamic_cast<AbstractProducerWidget *>(m_current)->loadPreset(*producer); } } void OpenOtherDialog::selectTreeWidget(const QString &s) { for (int j = 0; j < ui->treeWidget->topLevelItemCount(); j++) { QTreeWidgetItem *group = ui->treeWidget->topLevelItem(j); for (int i = 0; i < group->childCount(); i++) { if (group->child(i)->text(0) == s) { ui->treeWidget->setCurrentItem(group->child(i)); return; } } } } void OpenOtherDialog::on_treeWidget_currentItemChanged(QTreeWidgetItem *current, QTreeWidgetItem *) { if (current->data(0, Qt::UserRole).isValid()) { QString currentData(current->data(0, Qt::UserRole).toString()); m_addTimelineButton->setVisible(true); for (int i = 0; i < ui->methodTabWidget->count(); i++) { QString tabName(ui->methodTabWidget->widget(i)->objectName()); if (currentData == tabName) { ui->methodTabWidget->setCurrentIndex(i); QWidget *w = ui->methodTabWidget->currentWidget(); if (w == ui->networkTab) { m_current = ui->networkWidget; m_addTimelineButton->setVisible(false); } else if (w == ui->decklinkTab) { m_current = ui->decklinkWidget; m_addTimelineButton->setVisible(false); } else if (w == ui->v4lTab) { m_current = ui->v4lWidget; m_addTimelineButton->setVisible(false); } else if (w == ui->colorTab) { m_current = ui->colorWidget; } else if (w == ui->textTab) { m_current = ui->textWidget; } else if (w == ui->glaxnimateTab) { m_current = ui->glaxnimateWidget; } else if (w == ui->noiseTab) { m_current = ui->noiseWidget; } else if (w == ui->isingTab) { m_current = ui->isingWidget; } else if (w == ui->lissajousTab) { m_current = ui->lissajousWidget; } else if (w == ui->plasmaTab) { m_current = ui->plasmaWidget; } else if (w == ui->colorbarsTab) { m_current = ui->colorbarsWidget; } else if (w == ui->pulseTab) { m_current = ui->pulseWidget; m_addTimelineButton->setVisible(false); } else if (w == ui->jackTab) { m_current = ui->jackWidget; m_addTimelineButton->setVisible(false); } else if (w == ui->alsaTab) { m_current = ui->alsaWidget; m_addTimelineButton->setVisible(false); } else if (w == ui->x11grabTab) { m_current = ui->x11grabWidget; m_addTimelineButton->setVisible(false); } else if (w == ui->gdigrabTab) { m_current = ui->gdigrabWidget; m_addTimelineButton->setVisible(false); } else if (w == ui->dshowVideoTab) { m_current = ui->dshowVideoWidget; m_addTimelineButton->setVisible(false); } else if (w == ui->toneTab) { m_current = ui->toneWidget; } else if (w == ui->countTab) { m_current = ui->countWidget; } else if (w == ui->avfoundationTab) { m_current = ui->avfoundationWidget; m_addTimelineButton->setVisible(false); } else if (w == ui->blipTab) { m_current = ui->blipWidget; } break; } } } }
11,846
C++
.cpp
251
37.988048
103
0.611207
mltframework/shotcut
10,796
1,118
50
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
13,108
util.cpp
mltframework_shotcut/src/util.cpp
/* * Copyright (c) 2014-2024 Meltytech, LLC * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "util.h" #include <QFileInfo> #include <QWidget> #include <QStringList> #include <QFileInfo> #include <QDir> #include <QProcess> #include <QUrl> #include <QDesktopServices> #include <QMessageBox> #include <QMap> #include <QDoubleSpinBox> #include <QTemporaryFile> #include <QApplication> #include <QCryptographicHash> #include <QtGlobal> #include <QMediaDevices> #include <QCamera> #include <QCameraDevice> #include <QStorageInfo> #include <QCheckBox> #include <MltChain.h> #include <MltProducer.h> #include <Logger.h> #include "dialogs/transcodedialog.h" #include "mainwindow.h" #include "shotcut_mlt_properties.h" #include "qmltypes/qmlapplication.h" #include "proxymanager.h" #include "settings.h" #include "transcoder.h" #include <math.h> #include <memory> #ifdef Q_OS_WIN #include <windows.h> #endif #ifdef Q_OS_MAC static const unsigned int kLowMemoryThresholdPercent = 10U; #else static const unsigned int kLowMemoryThresholdKB = 256U * 1024U; #endif static const qint64 kFreeSpaceThesholdGB = 25LL * 1024 * 1024 * 1024; QString Util::baseName(const QString &filePath, bool trimQuery) { QString s = filePath; // Only if absolute path and not a URI. if (s.startsWith('/') || s.mid(1, 2) == ":/" || s.mid(1, 2) == ":\\") s = QFileInfo(s).fileName(); if (trimQuery) { return removeQueryString(s); } return s; } void Util::setColorsToHighlight(QWidget *widget, QPalette::ColorRole role) { if (role == QPalette::Base) { widget->setStyleSheet( "QLineEdit {" "font-weight: bold;" "background-color: palette(highlight);" "color: palette(highlighted-text);" "selection-background-color: palette(alternate-base);" "selection-color: palette(text);" "}" "QLineEdit:hover {" "border: 2px solid palette(button-text);" "}" ); } else { QPalette palette = QApplication::palette(); palette.setColor(role, palette.color(palette.Highlight)); palette.setColor(role == QPalette::Button ? QPalette::ButtonText : QPalette::WindowText, palette.color(palette.HighlightedText)); widget->setPalette(palette); widget->setAutoFillBackground(true); } } void Util::showInFolder(const QString &path) { QFileInfo info(removeQueryString(path)); #if defined(Q_OS_WIN) QStringList args; if (!info.isDir()) args << "/select,"; args << QDir::toNativeSeparators(path); if (QProcess::startDetached("explorer", args)) return; #elif defined(Q_OS_MAC) QStringList args; args << "-e"; args << "tell application \"Finder\""; args << "-e"; args << "activate"; args << "-e"; args << "select POSIX file \"" + path + "\""; args << "-e"; args << "end tell"; #if !defined(QT_DEBUG) args << "-e"; args << "return"; #endif if (!QProcess::execute("/usr/bin/osascript", args)) return; #endif QDesktopServices::openUrl(QUrl::fromLocalFile(info.isDir() ? path : info.path())); } bool Util::warnIfNotWritable(const QString &filePath, QWidget *parent, const QString &caption) { // Returns true if not writable. if (!filePath.isEmpty() && !filePath.contains("://")) { QFileInfo info(filePath); if (!info.isDir()) { info = QFileInfo(info.dir().path()); } if (!info.isWritable()) { info = QFileInfo(filePath); QMessageBox::warning(parent, caption, QObject::tr("Unable to write file %1\n" "Perhaps you do not have permission.\n" "Try again with a different folder.") .arg(info.fileName())); return true; } } return false; } QString Util::producerTitle(const Mlt::Producer &producer) { QString result; Mlt::Producer &p = const_cast<Mlt::Producer &>(producer); if (!p.is_valid() || p.is_blank()) return result; if (p.get(kShotcutTransitionProperty)) return QObject::tr("Transition"); if (p.get(kTrackNameProperty)) return QObject::tr("Track: %1").arg(QString::fromUtf8(p.get(kTrackNameProperty))); if (mlt_service_tractor_type == p.type()) return QObject::tr("Output"); if (p.get(kShotcutCaptionProperty)) return QString::fromUtf8(p.get(kShotcutCaptionProperty)); return Util::baseName(ProxyManager::resource(p)); } QString Util::removeFileScheme(QUrl &url, bool fromPercentEncoding) { QString path = url.url(); if (url.scheme() == "file") path = url.toString(QUrl::PreferLocalFile); if (fromPercentEncoding) return QUrl::fromPercentEncoding(path.toUtf8()); return path; } static inline bool isValidGoProFirstFilePrefix(const QFileInfo &info) { QStringList list {"GOPR", "GH01", "GL01", "GM01", "GS01", "GX01"}; return list.contains(info.baseName().left(4).toUpper()); } static inline bool isValidGoProPrefix(const QFileInfo &info) { QStringList list {"GP", "GH", "GL", "GM", "GS", "GX"}; return list.contains(info.baseName().left(2).toUpper()); } static inline bool isValidGoProSuffix(const QFileInfo &info) { QStringList list {"MP4", "LRV", "360", "WAV"}; return list.contains(info.suffix().toUpper()); } const QStringList Util::sortedFileList(const QList<QUrl> &urls) { QStringList result; QMap<QString, QStringList> goproFiles; // First look for GoPro main files. foreach (QUrl url, urls) { QFileInfo fi(removeFileScheme(url, false)); if (fi.baseName().size() == 8 && isValidGoProSuffix(fi) && isValidGoProFirstFilePrefix(fi)) { goproFiles[fi.baseName().mid(4)] << fi.filePath(); } } // Then, look for GoPro split files. foreach (QUrl url, urls) { QFileInfo fi(removeFileScheme(url, false)); if (fi.baseName().size() == 8 && isValidGoProSuffix(fi) && isValidGoProPrefix(fi) && !isValidGoProFirstFilePrefix(fi)) { QString goproNumber = fi.baseName().mid(4); // Only if there is a matching main GoPro file. if (goproFiles.contains(goproNumber) && goproFiles[goproNumber].size()) { goproFiles[goproNumber] << fi.filePath(); } } } // Next, sort the GoPro files. auto keys = goproFiles.keys(); for (auto &goproNumber : keys) { goproFiles[goproNumber].sort(Qt::CaseSensitive); } // Finally, build the list of all files. // Add all the GoPro files first. for (auto &paths : goproFiles) { result << paths; } // Add all the non-GoPro files. for (auto url : urls) { QFileInfo fi(removeFileScheme(url, false)); if (fi.baseName().size() == 8 && isValidGoProSuffix(fi) && (isValidGoProFirstFilePrefix(fi) || isValidGoProPrefix(fi))) { QString goproNumber = fi.baseName().mid(4); if (goproFiles.contains(goproNumber) && goproFiles[goproNumber].contains(fi.filePath())) continue; } result << fi.filePath(); } return result; } int Util::coerceMultiple(int value, int multiple) { return (value + multiple - 1) / multiple * multiple; } QList<QUrl> Util::expandDirectories(const QList<QUrl> &urls) { QList<QUrl> result; foreach (QUrl url, urls) { QString path = Util::removeFileScheme(url, false); QFileInfo fi(path); if (fi.isDir()) { QDir dir(path); foreach (QFileInfo fi, dir.entryInfoList(QDir::Files | QDir::Readable, QDir::Name)) result << fi.filePath(); } else { result << url; } } return result; } bool Util::isDecimalPoint(QChar ch) { // See https://en.wikipedia.org/wiki/Decimal_separator#Unicode_characters return ch == '.' || ch == ',' || ch == '\'' || ch == ' ' || ch == QChar(0x00B7) || ch == QChar(0x2009) || ch == QChar(0x202F) || ch == QChar(0x02D9) || ch == QChar(0x066B) || ch == QChar(0x066C) || ch == QChar(0x2396); } bool Util::isNumeric(QString &str) { for (int i = 0; i < str.size(); ++i) { auto ch = str[i]; if (ch != '+' && ch != '-' && ch.toLower() != 'e' && !isDecimalPoint(ch) && !ch.isDigit()) return false; } return true; } bool Util::convertNumericString(QString &str, QChar decimalPoint) { // Returns true if the string was changed. bool result = false; if (isNumeric(str)) { for (int i = 0; i < str.size(); ++i) { auto ch = str[i]; if (ch != decimalPoint && isDecimalPoint(ch)) { ch = decimalPoint; result = true; } } } return result; } bool Util::convertDecimalPoints(QString &str, QChar decimalPoint) { // Returns true if the string was changed. bool result = false; if (!str.contains(decimalPoint)) { for (int i = 0; i < str.size(); ++i) { auto ch = str[i]; // Space is used as a delimiter for rect fields and possibly elsewhere. if (ch != decimalPoint && ch != ' ' && isDecimalPoint(ch)) { ch = decimalPoint; result = true; } } } return result; } void Util::showFrameRateDialog(const QString &caption, int numerator, QDoubleSpinBox *spinner, QWidget *parent) { double fps = numerator / 1001.0; QMessageBox dialog(QMessageBox::Question, caption, QObject::tr("The value you entered is very similar to the common,\n" "more standard %1 = %2/1001.\n\n" "Do you want to use %1 = %2/1001 instead?") .arg(fps, 0, 'f', 6).arg(numerator), QMessageBox::No | QMessageBox::Yes, parent); dialog.setDefaultButton(QMessageBox::Yes); dialog.setEscapeButton(QMessageBox::No); dialog.setWindowModality(QmlApplication::dialogModality()); if (dialog.exec() == QMessageBox::Yes) { spinner->setValue(fps); } } QTemporaryFile *Util::writableTemporaryFile(const QString &filePath, const QString &templateName) { // filePath should already be checked writable. QFileInfo info(filePath); QString templateFileName = templateName.isEmpty() ? QStringLiteral("%1.XXXXXX").arg(QCoreApplication::applicationName()) : templateName; // First, try the system temp dir. QString templateFilePath = QDir(QDir::tempPath()).filePath(templateFileName); std::unique_ptr<QTemporaryFile> tmp(new QTemporaryFile(templateFilePath)); if (!tmp->open() || tmp->write("") < 0) { // Otherwise, use the directory provided. return new QTemporaryFile(info.dir().filePath(templateFileName)); } else { return tmp.release(); } } void Util::applyCustomProperties(Mlt::Producer &destination, Mlt::Producer &source, int in, int out) { Mlt::Properties p(destination); p.clear("force_progressive"); p.clear("force_tff"); p.clear("force_aspect_ratio"); p.clear("video_delay"); p.clear("color_range"); p.clear("speed"); p.clear("warp_speed"); p.clear("warp_pitch"); p.clear("rotate"); p.clear(kAspectRatioNumerator); p.clear(kAspectRatioDenominator); p.clear(kCommentProperty); p.clear(kShotcutProducerProperty); p.clear(kDefaultAudioIndexProperty); p.clear(kOriginalInProperty); p.clear(kOriginalOutProperty); if (!p.get_int(kIsProxyProperty)) p.clear(kOriginalResourceProperty); destination.pass_list(source, "mlt_service, audio_index, video_index, astream, vstream, force_progressive, force_tff," "force_aspect_ratio, video_delay, color_range, warp_speed, warp_pitch, rotate," kAspectRatioNumerator "," kAspectRatioDenominator "," kCommentProperty "," kShotcutProducerProperty "," kDefaultAudioIndexProperty "," kOriginalInProperty "," kOriginalOutProperty "," kOriginalResourceProperty "," kDisableProxyProperty); if (!destination.get("_shotcut:resource")) { destination.set("_shotcut:resource", destination.get("resource")); destination.set("_shotcut:length", destination.get("length")); } QString resource = ProxyManager::resource(destination); if (!qstrcmp("timewarp", source.get("mlt_service"))) { auto speed = qAbs(source.get_double("warp_speed")); auto caption = QStringLiteral("%1 (%2x)").arg(Util::baseName(resource, true)).arg(speed); destination.set(kShotcutCaptionProperty, caption.toUtf8().constData()); resource = destination.get("_shotcut:resource"); destination.set("warp_resource", resource.toUtf8().constData()); resource = QStringLiteral("%1:%2:%3").arg("timewarp", source.get("warp_speed"), resource); destination.set("resource", resource.toUtf8().constData()); double speedRatio = 1.0 / speed; int length = qRound(destination.get_length() * speedRatio); destination.set("length", destination.frames_to_time(length, mlt_time_clock)); } else { auto caption = Util::baseName(resource, true); destination.set(kShotcutCaptionProperty, caption.toUtf8().constData()); p.clear("warp_resource"); destination.set("resource", destination.get("_shotcut:resource")); destination.set("length", destination.get("_shotcut:length")); } destination.set_in_and_out(in, out); } QString Util::getFileHash(const QString &path) { // This routine is intentionally copied from Kdenlive. QFile file(removeQueryString(path)); if (file.open(QIODevice::ReadOnly)) { QByteArray fileData; // 1 MB = 1 second per 450 files (or faster) // 10 MB = 9 seconds per 450 files (or faster) if (file.size() > 1000000 * 2) { fileData = file.read(1000000); if (file.seek(file.size() - 1000000)) fileData.append(file.readAll()); } else { fileData = file.readAll(); } file.close(); return QCryptographicHash::hash(fileData, QCryptographicHash::Md5).toHex(); } return QString(); } QString Util::getHash(Mlt::Properties &properties) { QString hash = properties.get(kShotcutHashProperty); if (hash.isEmpty()) { QString service = properties.get("mlt_service"); QString resource = QString::fromUtf8(properties.get("resource")); if (properties.get_int(kIsProxyProperty) && properties.get(kOriginalResourceProperty)) resource = QString::fromUtf8(properties.get(kOriginalResourceProperty)); else if (service == "timewarp") resource = QString::fromUtf8(properties.get("warp_resource")); else if (service == "vidstab") resource = QString::fromUtf8(properties.get("filename")); hash = getFileHash(resource); if (!hash.isEmpty()) properties.set(kShotcutHashProperty, hash.toLatin1().constData()); } return hash; } bool Util::hasDriveLetter(const QString &path) { auto driveSeparators = path.mid(1, 2); return driveSeparators == ":/" || driveSeparators == ":\\"; } QFileDialog::Options Util::getFileDialogOptions() { #if defined(Q_OS_UNIX) && !defined(Q_OS_MAC) if (qEnvironmentVariableIsSet("SNAP") || qEnvironmentVariableIsSet("GNOME_SHELL_SESSION_MODE")) { return QFileDialog::DontUseNativeDialog; } #endif return QFileDialog::Options(); } bool Util::isMemoryLow() { #if defined(Q_OS_WIN) unsigned int availableKB = UINT_MAX; MEMORYSTATUSEX memory_status; ZeroMemory(&memory_status, sizeof(MEMORYSTATUSEX)); memory_status.dwLength = sizeof(MEMORYSTATUSEX); if (GlobalMemoryStatusEx(&memory_status)) { availableKB = memory_status.ullAvailPhys / 1024UL; } LOG_INFO() << "available RAM = " << availableKB << "KB"; return availableKB < kLowMemoryThresholdKB; #elif defined(Q_OS_MAC) QProcess p; p.start("memory_pressure", QStringList()); p.waitForFinished(); auto lines = p.readAllStandardOutput(); p.close(); for (auto &line : lines.split('\n')) { if (line.startsWith("System-wide memory free")) { const auto fields = line.split(':'); for (auto s : fields) { bool ok = false; auto percentage = s.replace('%', "").toUInt(&ok); if (ok) { LOG_INFO() << percentage << '%'; return percentage <= kLowMemoryThresholdPercent; } } } } return false; #elif defined(__FreeBSD__) || defined(__OpenBSD__) QProcess p; p.start("sysctl -n hw.usermem"); p.waitForFinished(); auto lines = p.readAllStandardOutput(); p.close(); bool ok = false; auto availableKB = lines.toUInt(&ok); if (ok) { return availableKB < kLowMemoryThresholdKB; } return false; #elif defined(Q_OS_LINUX) unsigned int availableKB = UINT_MAX; QFile meminfo("/proc/meminfo"); if (meminfo.open(QIODevice::ReadOnly)) { for (auto line = meminfo.readLine(1024); availableKB == UINT_MAX && !line.isEmpty(); line = meminfo.readLine(1024)) { if (line.startsWith("MemAvailable")) { const auto &fields = line.split(' '); for (const auto &s : fields) { bool ok = false; auto kB = s.toUInt(&ok); if (ok) { availableKB = kB; break; } } } } } meminfo.close(); LOG_INFO() << "available RAM = " << availableKB << "KB"; return availableKB < kLowMemoryThresholdKB; #endif } QString Util::removeQueryString(const QString &s) { auto i = s.lastIndexOf("\\?"); if (i < 0) { i = s.lastIndexOf("%5C?"); } if (i > 0 ) { return s.left(i); } return s; } int Util::greatestCommonDivisor(int m, int n) { int gcd, remainder; while (n) { remainder = m % n; m = n; n = remainder; } gcd = m; return gcd; } void Util::normalizeFrameRate(double fps, int &numerator, int &denominator) { // Convert some common non-integer frame rates to fractions. if (qRound(fps * 1000000.0) == 23976024) { numerator = 24000; denominator = 1001; } else if (qRound(fps * 100000.0) == 2997003) { numerator = 30000; denominator = 1001; } else if (qRound(fps * 1000000.0) == 47952048) { numerator = 48000; denominator = 1001; } else if (qRound(fps * 100000.0) == 5994006) { numerator = 60000; denominator = 1001; } else { // Workaround storing QDoubleSpinBox::value() loses precision. numerator = qRound(fps * 1000000.0); denominator = 1000000; auto gcd = greatestCommonDivisor(numerator, denominator); numerator /= gcd; denominator /= gcd; } } QString Util::textColor(const QColor &color) { return (color.value() < 150) ? "white" : "black"; } void Util::cameraFrameRateSize(const QByteArray &deviceName, qreal &frameRate, QSize &size) { std::unique_ptr<QCamera> camera; for (const QCameraDevice &cameraDevice : QMediaDevices::videoInputs()) { if (cameraDevice.id() == deviceName) { camera.reset(new QCamera(cameraDevice)); break; } } if (camera) { auto currentFormat = camera->cameraDevice().videoFormats().first(); QList<QSize> resolutions; for (const auto &format : camera->cameraDevice().videoFormats()) { resolutions << format.resolution(); } if (resolutions.size() > 0) { LOG_INFO() << "resolutions:" << resolutions; // Get the highest resolution camera->setCameraFormat(currentFormat); for (const auto &format : camera->cameraDevice().videoFormats()) { if (format.resolution().width() > currentFormat.resolution().width() && format.resolution().height() > currentFormat.resolution().height()) { camera->setCameraFormat(format); currentFormat = format; } } } if (currentFormat.maxFrameRate() > 0) { frameRate = currentFormat.maxFrameRate(); } if (currentFormat.resolution().width() > 0) { size = currentFormat.resolution(); } } } bool Util::ProducerIsTimewarp(Mlt::Producer *producer) { return QString::fromUtf8(producer->get("mlt_service")) == "timewarp"; } QString Util::GetFilenameFromProducer(Mlt::Producer *producer, bool useOriginal) { QString resource; if (useOriginal && producer->get(kOriginalResourceProperty)) { resource = QString::fromUtf8(producer->get(kOriginalResourceProperty)); } else if (ProducerIsTimewarp(producer)) { resource = QString::fromUtf8(producer->get("resource")); auto i = resource.indexOf(':'); if (producer->get_int(kIsProxyProperty) && i > 0) { resource = resource.mid(i + 1); } else { resource = QString::fromUtf8(producer->get("warp_resource")); } } else { resource = QString::fromUtf8(producer->get("resource")); } if (QFileInfo(resource).isRelative()) { QString basePath = QFileInfo(MAIN.fileName()).canonicalPath(); QFileInfo fi(basePath, resource); resource = fi.filePath(); } return resource; } double Util::GetSpeedFromProducer(Mlt::Producer *producer) { double speed = 1.0; if (ProducerIsTimewarp(producer)) { speed = fabs(producer->get_double("warp_speed")); } return speed; } QString Util::updateCaption(Mlt::Producer *producer) { double warpSpeed = GetSpeedFromProducer(producer); QString resource = GetFilenameFromProducer(producer); QString name = Util::baseName(resource, true); QString caption = producer->get(kShotcutCaptionProperty); if (caption.isEmpty() || caption.startsWith(name)) { // compute the caption if (warpSpeed != 1.0) caption = QStringLiteral("%1 (%2x)").arg(name).arg(warpSpeed); else caption = name; producer->set(kShotcutCaptionProperty, caption.toUtf8().constData()); } return caption; } void Util::passProducerProperties(Mlt::Producer *src, Mlt::Producer *dst) { dst->pass_list(*src, "audio_index, video_index, astream, vstream, force_aspect_ratio," "video_delay, force_progressive, force_tff, force_full_range, color_range, warp_pitch, rotate," kAspectRatioNumerator "," kAspectRatioDenominator "," kShotcutHashProperty "," kPlaylistIndexProperty "," kShotcutSkipConvertProperty "," kCommentProperty "," kDefaultAudioIndexProperty "," kShotcutCaptionProperty "," kOriginalResourceProperty "," kDisableProxyProperty "," kIsProxyProperty "," kShotcutProducerProperty); QString shotcutProducer(src->get(kShotcutProducerProperty)); QString service(src->get("mlt_service")); if (service.startsWith("avformat") || shotcutProducer == "avformat") dst->set(kShotcutProducerProperty, "avformat"); } bool Util::warnIfLowDiskSpace(const QString &path) { // Check if the drive this file will be on is getting low on space. if (Settings.encodeFreeSpaceCheck()) { QStorageInfo si(QFileInfo(path).path()); LOG_DEBUG() << si.bytesAvailable() << "bytes available on" << si.displayName(); if (si.isValid() && si.bytesAvailable() < kFreeSpaceThesholdGB) { QMessageBox dialog(QMessageBox::Question, QApplication::applicationDisplayName(), QObject::tr("The drive you chose only has %1 MiB of free space.\n" "Do you still want to continue?") .arg(si.bytesAvailable() / 1024 / 1024), QMessageBox::No | QMessageBox::Yes); dialog.setWindowModality(QmlApplication::dialogModality()); dialog.setDefaultButton(QMessageBox::Yes); dialog.setEscapeButton(QMessageBox::No); dialog.setCheckBox(new QCheckBox(QObject::tr("Do not show this anymore.", "Export free disk space warning dialog"))); int result = dialog.exec(); if (dialog.checkBox()->isChecked()) Settings.setEncodeFreeSpaceCheck(false); if (result == QMessageBox::No) { return true; } } } return false; } bool Util::isFpsDifferent(double a, double b) { return qAbs(a - b) > 0.001; } QString Util::getNextFile(const QString &filePath) { QFileInfo info(filePath); QString basename = info.completeBaseName(); QString extension = info.suffix(); if (extension.isEmpty()) { extension = basename; basename = QString(); } for (unsigned i = 1; i < std::numeric_limits<unsigned>::max(); i++) { QString filename = QString::fromLatin1("%1%2.%3").arg(basename).arg(i).arg(extension); if (!info.dir().exists(filename)) return info.dir().filePath(filename); } return filePath; } QString Util::trcString(int trc) { QString trcString = QObject::tr("unknown (%1)").arg(trc); switch (trc) { case 0: trcString = QObject::tr("NA"); break; case 1: trcString = "ITU-R BT.709"; break; case 6: trcString = "ITU-R BT.601"; break; case 7: trcString = "SMPTE ST240"; break; case 11: trcString = "IEC 61966-2-4"; break; case 13: trcString = "sRGB"; break; case 14: trcString = "ITU-R BT.2020"; break; case 15: trcString = "ITU-R BT.2020"; break; case 16: trcString = "SMPTE ST2084 (PQ)"; break; case 17: trcString = "SMPTE ST428"; break; case 18: trcString = "ARIB B67 (HLG)"; break; } return trcString; } bool Util::trcIsCompatible(int trc) { // Transfer characteristics > SMPTE240M Probably need conversion except IEC61966-2-4 is OK return trc <= 7 || trc == 11 || trc == 13 || trc == 18; } QString Util::getConversionAdvice(Mlt::Producer *producer) { QString advice; producer->probe(); QString resource = Util::GetFilenameFromProducer(producer); int trc = producer->get_int("meta.media.color_trc"); if (!Util::trcIsCompatible(trc)) { QString trcString = Util::trcString(trc); LOG_INFO() << resource << "Probable HDR" << trcString; advice = QObject::tr("This file uses color transfer characteristics %1, which may result in incorrect colors or brightness in Shotcut.").arg( trcString); } else if (producer->get_int("meta.media.variable_frame_rate")) { LOG_INFO() << resource << "is variable frame rate"; advice = QObject::tr("This file is variable frame rate, which is not reliable for editing."); } else if (QFile::exists(resource) && !MLT.isSeekable(producer)) { LOG_INFO() << resource << "is not seekable"; advice = QObject::tr("This file does not support seeking and cannot be used for editing."); } else if (QFile::exists(resource) && resource.endsWith(".m2t")) { LOG_INFO() << resource << "is HDV"; advice = QObject::tr("This file format (HDV) is not reliable for editing."); } return advice; } mlt_color Util::mltColorFromQColor(const QColor &color) { return mlt_color { static_cast<uint8_t>(color.red()), static_cast<uint8_t>(color.green()), static_cast<uint8_t>(color.blue()), static_cast<uint8_t>(color.alpha()) }; } void Util::offerSingleFileConversion(QString &message, Mlt::Producer *producer, QWidget *parent) { TranscodeDialog dialog(message.append( QObject::tr(" Do you want to convert it to an edit-friendly format?\n\n" "If yes, choose a format below and then click OK to choose a file name. " "After choosing a file name, a job is created. " "When it is done, it automatically replaces clips, or you can double-click the job to open it.\n")), producer->get_int("progressive"), parent); dialog.setWindowModality(QmlApplication::dialogModality()); dialog.showCheckBox(); dialog.set709Convert(!Util::trcIsCompatible(producer->get_int("meta.media.color_trc"))); dialog.showSubClipCheckBox(); LOG_DEBUG() << "in" << producer->get_in() << "out" << producer->get_out() << "length" << producer->get_length() - 1; dialog.setSubClipChecked(producer->get_in() > 0 || producer->get_out() < producer->get_length() - 1); auto fps = Util::getAndroidFrameRate(producer); if (fps > 0.0) dialog.setFrameRate(fps); Transcoder transcoder; transcoder.addProducer(producer); transcoder.convert(dialog); } double Util::getAndroidFrameRate(Mlt::Producer *producer) { auto fps = producer->get_double("meta.attr.com.android.capture.fps.markup"); if (!qIsFinite(fps)) fps = 0.0; return fps; } double Util::getSuggestedFrameRate(Mlt::Producer *producer) { auto fps = producer->get_double("meta.attr.com.android.capture.fps.markup"); if (!qIsFinite(fps)) fps = 0.0; if (fps <= 0.0) { fps = producer->get_double("meta.media.frame_rate_num"); if (producer->get_double("meta.media.frame_rate_den") > 0) fps /= producer->get_double("meta.media.frame_rate_den"); if (producer->get("force_fps")) fps = producer->get_double("fps"); } return fps; }
31,432
C++
.cpp
833
30.048019
149
0.612632
mltframework/shotcut
10,796
1,118
50
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
13,109
main.cpp
mltframework_shotcut/src/main.cpp
/* * Copyright (c) 2011-2024 Meltytech, LLC * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <QtWidgets> #include <QtGlobal> #include "mainwindow.h" #include "settings.h" #include <Logger.h> #include <FileAppender.h> #include <ConsoleAppender.h> #include <QSysInfo> #include <QProcess> #include <QCommandLineParser> #include <framework/mlt_log.h> #include <QFile> #include <QQuickStyle> #include <QQuickWindow> #ifdef Q_OS_MAC #include "macos.h" #endif #ifdef Q_OS_WIN #include <windows.h> #if defined(QT_DEBUG) && !defined(__ARM_ARCH) # include <exchndl.h> #endif extern "C" { // Inform the driver we could make use of the discrete gpu __declspec(dllexport) DWORD NvOptimusEnablement = 0x00000001; __declspec(dllexport) DWORD AmdPowerXpressRequestHighPerformance = 0x00000001; } #endif static const int kMaxCacheCount = 5000; static void mlt_log_handler(void *service, int mlt_level, const char *format, va_list args) { if (mlt_level > mlt_log_get_level()) return; enum Logger::LogLevel cuteLoggerLevel = Logger::Fatal; switch (mlt_level) { case MLT_LOG_DEBUG: cuteLoggerLevel = Logger::Trace; break; case MLT_LOG_ERROR: case MLT_LOG_FATAL: case MLT_LOG_PANIC: cuteLoggerLevel = Logger::Error; break; case MLT_LOG_INFO: cuteLoggerLevel = Logger::Info; break; case MLT_LOG_VERBOSE: cuteLoggerLevel = Logger::Debug; break; case MLT_LOG_WARNING: cuteLoggerLevel = Logger::Warning; break; } QString message; mlt_properties properties = service ? MLT_SERVICE_PROPERTIES((mlt_service) service) : NULL; if (properties) { char *mlt_type = mlt_properties_get(properties, "mlt_type"); char *service_name = mlt_properties_get(properties, "mlt_service"); char *resource = mlt_properties_get(properties, "resource"); if (!resource || resource[0] != '<' || resource[strlen(resource) - 1] != '>') mlt_type = mlt_properties_get(properties, "mlt_type" ); if (service_name) message = QStringLiteral("[%1 %2] ").arg(mlt_type, service_name); else message = QString::asprintf("[%s %p] ", mlt_type, service); if (resource) message.append(QStringLiteral("\"%1\" ").arg(resource)); message.append(QString::vasprintf(format, args)); message.replace('\n', ""); } else { message = QString::vasprintf(format, args); message.replace('\n', ""); } cuteLogger->write(cuteLoggerLevel, __FILE__, __LINE__, "MLT", cuteLogger->defaultCategory().toLatin1().constData(), message); } class Application : public QApplication { public: MainWindow *mainWindow {nullptr}; QTranslator qtTranslator; QTranslator qtBaseTranslator; QTranslator shotcutTranslator; QStringList resourceArg; bool isFullScreen; QString appDirArg; Application(int &argc, char **argv) : QApplication(argc, argv) { auto appPath = applicationDirPath(); QDir dir(appPath); #ifdef Q_OS_WIN #include <winbase.h> SetDllDirectoryA(appPath.toLocal8Bit()); CreateMutexA(NULL, FALSE, "Meltytech Shotcut Running Mutex"); #else dir.cdUp(); #endif #ifdef Q_OS_MAC dir.cd("PlugIns"); dir.cd("qt"); #else dir.cd("lib"); dir.cd("qt6"); #endif addLibraryPath(dir.absolutePath()); setOrganizationName("Meltytech"); #if defined(Q_OS_UNIX) && !defined(Q_OS_MAC) setOrganizationDomain("shotcut.org"); setDesktopFileName("org.shotcut.Shotcut"); #else setOrganizationDomain("meltytech.com"); #endif setApplicationName("Shotcut"); setApplicationVersion(SHOTCUT_VERSION); // Process command line options. QCommandLineParser parser; parser.addHelpOption(); parser.addVersionOption(); #ifndef Q_OS_WIN QCommandLineOption fullscreenOption("fullscreen", QCoreApplication::translate("main", "Fill the screen with the Shotcut window.")); parser.addOption(fullscreenOption); #endif QCommandLineOption noupgradeOption("noupgrade", QCoreApplication::translate("main", "Hide upgrade prompt and menu item.")); parser.addOption(noupgradeOption); QCommandLineOption glaxnimateOption("glaxnimate", QCoreApplication::translate("main", "Run Glaxnimate instead of Shotcut.")); parser.addOption(glaxnimateOption); QCommandLineOption gpuOption("gpu", QCoreApplication::translate("main", "Use GPU processing.")); parser.addOption(gpuOption); QCommandLineOption clearRecentOption("clear-recent", QCoreApplication::translate("main", "Clear Recent on Exit")); parser.addOption(clearRecentOption); QCommandLineOption appDataOption("appdata", QCoreApplication::translate("main", "The directory for app configuration and data."), QCoreApplication::translate("main", "directory")); parser.addOption(appDataOption); QCommandLineOption scaleOption("QT_SCALE_FACTOR", QCoreApplication::translate("main", "The scale factor for a high-DPI screen"), QCoreApplication::translate("main", "number")); parser.addOption(scaleOption); scaleOption = QCommandLineOption("QT_SCREEN_SCALE_FACTORS", QCoreApplication::translate("main", "A semicolon-separated list of scale factors for each screen"), QCoreApplication::translate("main", "list")); parser.addOption(scaleOption); QCommandLineOption scalePolicyOption("QT_SCALE_FACTOR_ROUNDING_POLICY", QCoreApplication::translate("main", "How to handle a fractional display scale: %1") .arg("Round, Ceil, Floor, RoundPreferFloor, PassThrough"), QCoreApplication::translate("main", "string"), "PassThrough"); parser.addOption(scalePolicyOption); #if defined(Q_OS_WIN) QCommandLineOption sdlAudioDriverOption("SDL_AUDIODRIVER", QCoreApplication::translate("main", "Which operating system audio API to use: %1") .arg("directsound, wasapi, winmm"), QCoreApplication::translate("main", "string"), "wasapi"); parser.addOption(sdlAudioDriverOption); #elif defined(Q_OS_LINUX) QCommandLineOption sdlAudioDriverOption("SDL_AUDIODRIVER", QCoreApplication::translate("main", "Which operating system audio API to use: %1") .arg("alsa, arts, dsp, esd, jack, pipewire, pulseaudio"), QCoreApplication::translate("main", "string"), "pulseaudio"); parser.addOption(sdlAudioDriverOption); #endif parser.addPositionalArgument("[FILE]...", QCoreApplication::translate("main", "Zero or more files or folders to open")); parser.process(arguments()); if (parser.isSet(glaxnimateOption)) { QStringList args = arguments(); if (!args.isEmpty()) args.removeFirst(); args.removeAll("--glaxnimate"); QProcess child; if (child.startDetached(Settings.glaxnimatePath(), args)) ::exit(EXIT_SUCCESS); } #ifdef Q_OS_WIN isFullScreen = false; #else isFullScreen = parser.isSet(fullscreenOption); #endif setProperty("noupgrade", parser.isSet(noupgradeOption)); setProperty("clearRecent", parser.isSet(clearRecentOption)); if (!parser.value(appDataOption).isEmpty()) { appDirArg = parser.value(appDataOption); ShotcutSettings::setAppDataForSession(appDirArg); } if (parser.isSet(gpuOption)) Settings.setPlayerGPU(true); if (!parser.positionalArguments().isEmpty()) resourceArg = parser.positionalArguments(); // Startup logging. dir.setPath(Settings.appDataLocation()); if (!dir.exists()) dir.mkpath(dir.path()); auto previousLogName = dir.filePath("shotcut-log.bak"); QFile::remove(previousLogName); QFile::copy(dir.filePath("shotcut-log.txt"), previousLogName); const QString logFileName = dir.filePath("shotcut-log.txt"); QFile::remove(logFileName); FileAppender *fileAppender = new FileAppender(logFileName); fileAppender->setFormat("[%{type:-7}] <%{function}> %{message}\n"); cuteLogger->registerAppender(fileAppender); #ifndef NDEBUG // Only log to console in dev debug builds. ConsoleAppender *consoleAppender = new ConsoleAppender(); consoleAppender->setFormat(fileAppender->format()); cuteLogger->registerAppender(consoleAppender); mlt_log_set_level(MLT_LOG_VERBOSE); #else mlt_log_set_level(MLT_LOG_INFO); #endif mlt_log_set_callback(mlt_log_handler); cuteLogger->logToGlobalInstance("qml", true); #if defined(Q_OS_WIN) dir.setPath(appPath); #elif !defined(Q_OS_MAC) if (Settings.drawMethod() == Qt::AA_UseSoftwareOpenGL && !Settings.playerGPU()) { ::qputenv("LIBGL_ALWAYS_SOFTWARE", "1"); } #endif // Load translations QString locale = Settings.language(); dir.setPath(appPath); #if defined(Q_OS_MAC) dir.cdUp(); dir.cd("Resources"); dir.cd("shotcut"); dir.cd("translations"); #elif defined(Q_OS_WIN) dir.cd("share"); dir.cd("translations"); #else dir.cdUp(); dir.cd("share"); dir.cd("shotcut"); dir.cd("translations"); #endif if (locale.startsWith("pt_")) locale = "pt"; else if (locale.startsWith("en_")) locale = "en"; if (qtTranslator.load("qt_" + locale, QLibraryInfo::path(QLibraryInfo::TranslationsPath))) installTranslator(&qtTranslator); else if (qtTranslator.load("qt_" + locale, dir.absolutePath())) installTranslator(&qtTranslator); if (qtBaseTranslator.load("qtbase_" + locale, QLibraryInfo::path(QLibraryInfo::TranslationsPath))) installTranslator(&qtBaseTranslator); else if (qtBaseTranslator.load("qtbase_" + locale, dir.absolutePath())) installTranslator(&qtBaseTranslator); if (shotcutTranslator.load("shotcut_" + Settings.language(), dir.absolutePath())) installTranslator(&shotcutTranslator); } ~Application() { delete mainWindow; LOG_DEBUG() << "exiting"; } protected: bool event(QEvent *event) { if (event->type() == QEvent::FileOpen) { QFileOpenEvent *openEvent = static_cast<QFileOpenEvent *>(event); resourceArg << openEvent->file(); return true; } else return QApplication::event(event); } }; int main(int argc, char **argv) { #if defined(Q_OS_WIN) && defined(QT_DEBUG) && !defined(__ARM_ARCH) ExcHndlInit(); #endif #ifndef QT_DEBUG ::qputenv("QT_LOGGING_RULES", "*.warning=false"); #endif for (int i = 1; i + 1 < argc; i++) { if (!::qstrcmp("--QT_SCALE_FACTOR", argv[i]) || !::qstrcmp("--QT_SCREEN_SCALE_FACTORS", argv[i])) { QByteArray value(argv[i + 1]); ::qputenv("QT_AUTO_SCREEN_SCALE_FACTOR", "0"); ::qputenv(value.contains(';') ? "QT_SCREEN_SCALE_FACTORS" : "QT_SCALE_FACTOR", value); break; } } if (!::qEnvironmentVariableIsSet("QT_SCALE_FACTOR_ROUNDING_POLICY")) { for (int i = 1; i + 1 < argc; i++) { if (!::qstrcmp("--QT_SCALE_FACTOR_ROUNDING_POLICY", argv[i])) { ::qputenv("QT_SCALE_FACTOR_ROUNDING_POLICY", argv[i + 1]); break; } } } #if defined(Q_OS_WIN) || defined(Q_OS_LINUX) for (int i = 1; i + 1 < argc; i++) { if (!::qstrcmp("--SDL_AUDIODRIVER", argv[i])) { ::qputenv("SDL_AUDIODRIVER", argv[i + 1]); break; } } #endif // The ffmpeg backend (default as of Qt 6.5) is likely using a different version of FFmpeg. if (!qEnvironmentVariableIsSet("QT_MEDIA_BACKEND")) #if defined(Q_OS_MAC) qputenv("QT_MEDIA_BACKEND", "darwin"); #elif defined(Q_OS_WIN) qputenv("QT_MEDIA_BACKEND", "windows"); if (!qEnvironmentVariableIsSet("QT_QPA_PLATFORM")) qputenv("QT_QPA_PLATFORM", "windows:altgr"); // The modern Windows style adopted in Qt 6.7 changes spinboxes to have // larger arrow buttons side-by-side thus making the numeric area // smaller and incompatible with every other combination of style and OS. if (!qEnvironmentVariableIsSet("QT_STYLE_OVERRIDE")) qputenv("QT_STYLE_OVERRIDE", "windowsvista"); #else ; #endif #ifdef Q_OS_MAC // Launcher and Spotlight on macOS are not setting this environment // variable needed by setlocale() as used by MLT. if (QProcessEnvironment::systemEnvironment().value(MLT_LC_NAME).isEmpty()) { qputenv(MLT_LC_NAME, QLocale().name().toUtf8()); QLocale localeByName(QLocale(QLocale().language(), QLocale().script(), QLocale().territory())); if (QLocale().decimalPoint() != localeByName.decimalPoint()) { // If region's numeric format does not match the language's, then we run // into problems because we told MLT and libc to use a different numeric // locale than actually in use by Qt because it is unable to give numeric // locale as a set of ISO-639 codes. QLocale::setDefault(localeByName); qputenv("LANG", QLocale().name().toUtf8()); } } removeMacosTabBar(); #endif #if defined(Q_OS_WIN) // Windows can use Direct3D or OpenGL #elif defined(Q_OS_MAC) QQuickWindow::setGraphicsApi(QSGRendererInterface::Metal); QCoreApplication::setAttribute(Qt::AA_DontShowIconsInMenus); #else QQuickWindow::setGraphicsApi(QSGRendererInterface::OpenGL); QCoreApplication::setAttribute(Qt::AA_UseDesktopOpenGL); QCoreApplication::setAttribute(Qt::AA_DontCreateNativeWidgetSiblings); #endif Application a(argc, argv); int result = EXIT_SUCCESS; #ifdef Q_OS_WIN if (::qEnvironmentVariableIsSet("QSG_RHI_BACKEND")) { #endif QSplashScreen splash(QPixmap(":/icons/shotcut-logo-320x320.png")); // Log some basic info. LOG_INFO() << "Starting Shotcut version" << SHOTCUT_VERSION; #if defined(Q_OS_WIN) LOG_INFO() << "Windows version" << QSysInfo::productVersion(); #elif defined(Q_OS_MAC) LOG_INFO() << "macOS version" << QSysInfo::productVersion(); #else LOG_INFO() << "Linux version" << QSysInfo::productVersion();; #endif LOG_INFO() << "number of logical cores =" << QThread::idealThreadCount(); LOG_INFO() << "locale =" << QLocale(); LOG_INFO() << "install dir =" << a.applicationDirPath(); Settings.log(); // Expire old items from the qmlcache splash.showMessage(QCoreApplication::translate("main", "Expiring cache..."), Qt::AlignRight | Qt::AlignVCenter); splash.show(); a.processEvents(); auto dir = QDir(QStandardPaths::standardLocations(QStandardPaths::CacheLocation).constFirst()); if (dir.exists() && dir.cd("qmlcache")) { auto ls = dir.entryList(QDir::Files | QDir::Readable | QDir::NoDotAndDotDot, QDir::Time); if (qMax(0, ls.size() - kMaxCacheCount) > 0) { LOG_INFO() << "removing" << qMax(0, ls.size() - kMaxCacheCount) << "from" << dir.path(); } for (int i = kMaxCacheCount; i < ls.size(); i++) { QString filePath = dir.filePath(ls[i]); if (!QFile::remove(filePath)) { LOG_WARNING() << "failed to delete" << filePath; } if (i % 1000 == 0) { a.processEvents(); } } } splash.showMessage(QCoreApplication::translate("main", "Loading plugins..."), Qt::AlignRight | Qt::AlignVCenter); a.processEvents(); a.setProperty("system-style", a.style()->objectName()); MainWindow::changeTheme(Settings.theme()); QQuickStyle::setStyle("Fusion"); a.mainWindow = &MAIN; if (!a.appDirArg.isEmpty()) a.mainWindow->hideSetDataDirectory(); #if defined(Q_OS_WIN) || defined(Q_OS_MAC) a.mainWindow->setProperty("windowOpacity", 0.0); #endif a.mainWindow->show(); a.processEvents(); a.mainWindow->setFullScreen(a.isFullScreen); splash.finish(a.mainWindow); if (!a.resourceArg.isEmpty()) { QStringList ls; for (auto &s : a.resourceArg) ls << QFileInfo(QDir::currentPath(), s).filePath(); a.mainWindow->openMultiple(ls); } else { a.mainWindow->open(a.mainWindow->untitledFileName()); } result = a.exec(); if (EXIT_RESTART == result || EXIT_RESET == result) { LOG_DEBUG() << "restarting app"; #if defined(Q_OS_UNIX) && !defined(Q_OS_MAC) ::qputenv("LIBGL_ALWAYS_SOFTWARE", Settings.drawMethod() == Qt::AA_UseSoftwareOpenGL && !Settings.playerGPU() ? "1" : "0"); #endif QProcess *restart = new QProcess; QStringList args = a.arguments(); if (!args.isEmpty()) args.removeFirst(); restart->start(a.applicationFilePath(), args, QIODevice::NotOpen); result = EXIT_SUCCESS; } #ifdef Q_OS_WIN } else { // if (::qEnvironmentVariableIsSet("QSG_RHI_BACKEND")) // Run as a parent process to check if the child crashes on startup QProcess *child = new QProcess; QStringList args = a.arguments(); if (!args.isEmpty()) args.removeFirst(); ::qputenv("QSG_RHI_BACKEND", "d3d11"); child->start(a.applicationFilePath(), args, QIODevice::NotOpen); child->waitForFinished(); if (QProcess::CrashExit == child->exitStatus() || child->exitCode()) { LOG_WARNING() << "child process failed, restarting in OpenGL mode"; ::qputenv("QSG_RHI_BACKEND", "opengl"); child->start(a.applicationFilePath(), args, QIODevice::NotOpen); } } #endif return result; }
19,734
C++
.cpp
460
33.671739
140
0.611767
mltframework/shotcut
10,796
1,118
50
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
13,110
sharedframe.cpp
mltframework_shotcut/src/sharedframe.cpp
/* * Copyright (c) 2015-2023 Meltytech, LLC * Author: Brian Matherly <code@brianmatherly.com> * * 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 "sharedframe.h" #include <mutex> void destroyFrame(void *p) { delete static_cast<Mlt::Frame *>(p); } class FrameData : public QSharedData { public: FrameData() : f(nullptr) {}; FrameData(Mlt::Frame &frame) : f(frame) {}; ~FrameData() {}; Mlt::Frame f; std::mutex m; private: Q_DISABLE_COPY(FrameData) }; SharedFrame::SharedFrame() : d(new FrameData()) { } SharedFrame::SharedFrame(Mlt::Frame &frame) : d(new FrameData(frame)) { } SharedFrame::SharedFrame(const SharedFrame &other) : d(other.d) { } SharedFrame::~SharedFrame() { } SharedFrame &SharedFrame::operator=(const SharedFrame &other) { d = other.d; return *this; } bool SharedFrame::is_valid() const { return d && d->f.is_valid(); } Mlt::Frame SharedFrame::clone(bool audio, bool image, bool alpha) const { // TODO: Consider moving this implementation into MLT. // It could be added to mlt_frame as an alternative to: // mlt_frame mlt_frame_clone( mlt_frame self, int is_deep ); // It could also be added to Mlt::Frame as a const function. void *data = 0; void *copy = 0; int size = 0; Mlt::Frame cloneFrame(mlt_frame_init( NULL )); cloneFrame.inherit(d->f); cloneFrame.set("_producer", d->f.get_data("_producer", size), size); cloneFrame.set("movit.convert", d->f.get_data("movit.convert", size), size); cloneFrame.set("_movit cpu_convert", d->f.get_data("_movit cpu_convert", size), size); cloneFrame.get_frame()->convert_image = d->f.get_frame()->convert_image; cloneFrame.get_frame()->convert_audio = d->f.get_frame()->convert_audio; data = d->f.get_data("audio", size); if (audio && data) { if (!size) { size = mlt_audio_format_size(get_audio_format(), get_audio_samples(), get_audio_channels()); } copy = mlt_pool_alloc(size); memcpy(copy, data, size); cloneFrame.set("audio", copy, size, mlt_pool_release); } else { cloneFrame.set("audio", 0); cloneFrame.set("audio_format", mlt_audio_none); cloneFrame.set("audio_channels", 0); cloneFrame.set("audio_frequency", 0); cloneFrame.set("audio_samples", 0); } data = d->f.get_data("image", size ); if (image && data) { if (!size) { size = mlt_image_format_size(get_image_format(), get_image_width(), get_image_height(), 0); } copy = mlt_pool_alloc(size); memcpy(copy, data, size); cloneFrame.set("image", copy, size, mlt_pool_release); } else { cloneFrame.set("image", 0); cloneFrame.set("format", mlt_image_none); cloneFrame.set("width", 0); cloneFrame.set("height", 0); } data = d->f.get_data("alpha", size ); if (alpha && data && d->f.get_int("format") != mlt_image_rgba) { if (!size) { size = get_image_width() * get_image_height(); } copy = mlt_pool_alloc(size); memcpy(copy, data, size); cloneFrame.set("alpha", copy, size, mlt_pool_release); } else { cloneFrame.set("alpha", 0); } // Release the reference on the initial frame so that the returned frame // only has one reference. mlt_frame_close(cloneFrame.get_frame()); return cloneFrame; } int SharedFrame::get_int(const char *name) const { return d->f.get_int(name); } int64_t SharedFrame::get_int64(const char *name) const { return d->f.get_int64(name); } double SharedFrame::get_double(const char *name) const { return d->f.get_double(name); } int SharedFrame::get_position() const { return d->f.get_position(); } mlt_image_format SharedFrame::get_image_format() const { return (mlt_image_format)d->f.get_int( "format" ); } int SharedFrame::get_image_width() const { return d->f.get_int( "width" ); } int SharedFrame::get_image_height() const { return d->f.get_int( "height" ); } const uint8_t *SharedFrame::get_image(mlt_image_format format) const { mlt_image_format native_format = get_image_format(); int width = get_image_width(); int height = get_image_height(); uint8_t *image = nullptr; if (format == mlt_image_none) { format = native_format; } if (format == native_format) { // Native format is requested. Return frame image. image = (uint8_t *)d->f.get_image(format, width, height, 0); } else { // Non-native format is requested. Return a cached converted image. const char *formatName = mlt_image_format_name( format ); // Convert to non-const so that the cache can be accessed/modified while // under lock. FrameData *nonConstData = const_cast<FrameData *>(d.data()); nonConstData->m.lock(); Mlt::Frame *cacheFrame = static_cast<Mlt::Frame *>(nonConstData->f.get_data(formatName)); if (cacheFrame == nullptr) { // A cached image does not exist, create one. // Make a non-deep clone of the frame (including convert function) mlt_frame cloneFrame = mlt_frame_clone(nonConstData->f.get_frame(), 0); cloneFrame->convert_image = nonConstData->f.get_frame()->convert_image; // Create a new cache frame cacheFrame = new Mlt::Frame(cloneFrame); // Release the reference on the clone // (now it is owned by the cache frame) mlt_frame_close( cloneFrame ); // Save the cache frame as a property under the name of the image // format for later use. nonConstData->f.set(formatName, static_cast<void *>(cacheFrame), 0, destroyFrame); // Break a circular reference cacheFrame->clear("_cloned_frame"); } // Get the image from the cache frame. // This will cause a conversion if it was just created. image = (uint8_t *)cacheFrame->get_image(format, width, height, 0); nonConstData->m.unlock(); } return image; } mlt_audio_format SharedFrame::get_audio_format() const { return (mlt_audio_format)d->f.get_int( "audio_format" ); } int SharedFrame::get_audio_channels() const { return d->f.get_int( "audio_channels" ); } int SharedFrame::get_audio_frequency() const { return d->f.get_int( "audio_frequency" ); } int SharedFrame::get_audio_samples() const { return d->f.get_int( "audio_samples" ); } const int16_t *SharedFrame::get_audio() const { mlt_audio_format format = get_audio_format(); int frequency = get_audio_frequency(); int channels = get_audio_channels(); int samples = get_audio_samples(); return (int16_t *)d->f.get_audio(format, frequency, channels, samples); } Mlt::Producer *SharedFrame::get_original_producer() { return d->f.get_original_producer(); }
7,748
C++
.cpp
223
28.955157
97
0.632176
mltframework/shotcut
10,796
1,118
50
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
13,111
settings.cpp
mltframework_shotcut/src/settings.cpp
/* * Copyright (c) 2013-2024 Meltytech, LLC * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "settings.h" #include "qmltypes/qmlapplication.h" #include <QApplication> #include <QColor> #include <QLocale> #include <QStandardPaths> #include <QFile> #include <QDir> #include <QMediaDevices> #include <QAudioDevice> #include <Logger.h> static const QString APP_DATA_DIR_KEY("appdatadir"); static const QString SHOTCUT_INI_FILENAME("/shotcut.ini"); static const QString RECENT_INI_FILENAME("recent.ini"); static QScopedPointer<ShotcutSettings> instance; static QString appDataForSession; static const int kMaximumTrackHeight = 125; static const QString kRecentKey("recent"); static const QString kProjectsKey("projects"); ShotcutSettings &ShotcutSettings::singleton() { if (!instance) { if (appDataForSession.isEmpty()) { instance.reset(new ShotcutSettings); if (instance->settings.value(APP_DATA_DIR_KEY).isValid() && QFile::exists(instance->settings.value(APP_DATA_DIR_KEY).toString() + SHOTCUT_INI_FILENAME) ) instance.reset(new ShotcutSettings(instance->settings.value(APP_DATA_DIR_KEY).toString())); } else { instance.reset(new ShotcutSettings(appDataForSession)); } } return *instance; } ShotcutSettings::ShotcutSettings() : QObject() , m_recent(QDir(appDataLocation()).filePath(RECENT_INI_FILENAME), QSettings::IniFormat) { migrateLayout(); migrateRecent(); } ShotcutSettings::ShotcutSettings(const QString &appDataLocation) : QObject() , settings(appDataLocation + SHOTCUT_INI_FILENAME, QSettings::IniFormat) , m_appDataLocation(appDataLocation) , m_recent(QDir(appDataLocation).filePath(RECENT_INI_FILENAME), QSettings::IniFormat) { migrateLayout(); migrateRecent(); } void ShotcutSettings::migrateRecent() { // Migrate recent to separate INI file auto oldRecents = settings.value(kRecentKey).toStringList(); if (recent().isEmpty() && !oldRecents.isEmpty()) { auto newRecents = recent(); for (const auto &a : oldRecents) { if (a.size() < ShotcutSettings::MaxPath && !newRecents.contains(a)) { while (newRecents.size() > 100) { newRecents.removeFirst(); } newRecents.append(a); } } setRecent(newRecents); m_recent.sync(); // settings.remove("recent"); settings.sync(); } } void ShotcutSettings::migrateLayout() { // Migrate old startup layout to a custom layout and start fresh if (!settings.contains("geometry2")) { auto geometry = settings.value("geometry").toByteArray(); auto windowState = settings.value("windowState").toByteArray(); setLayout(tr("Old (before v23) Layout"), geometry, windowState); setLayoutMode(2); settings.sync(); } } void ShotcutSettings::log() { LOG_INFO() << "language" << language(); LOG_INFO() << "deinterlacer" << playerDeinterlacer(); LOG_INFO() << "external monitor" << playerExternal(); LOG_INFO() << "GPU processing" << playerGPU(); LOG_INFO() << "interpolation" << playerInterpolation(); LOG_INFO() << "video mode" << playerProfile(); LOG_INFO() << "realtime" << playerRealtime(); LOG_INFO() << "audio channels" << playerAudioChannels(); #if defined(Q_OS_WIN) || defined(Q_OS_LINUX) if (::qEnvironmentVariableIsSet("SDL_AUDIODRIVER")) { LOG_INFO() << "audio driver" <<::qgetenv("SDL_AUDIODRIVER"); } else { LOG_INFO() << "audio driver" << playerAudioDriver(); } #endif } QString ShotcutSettings::language() const { QString language = settings.value("language", QLocale().name()).toString(); if (language == "en") language = "en_US"; return language; } void ShotcutSettings::setLanguage(const QString &s) { settings.setValue("language", s); } double ShotcutSettings::imageDuration() const { return settings.value("imageDuration", 4.0).toDouble(); } void ShotcutSettings::setImageDuration(double d) { settings.setValue("imageDuration", d); } QString ShotcutSettings::openPath() const { return settings.value("openPath", QStandardPaths::standardLocations(QStandardPaths::MoviesLocation)).toString(); } void ShotcutSettings::setOpenPath(const QString &s) { settings.setValue("openPath", s); emit savePathChanged(); } QString ShotcutSettings::savePath() const { return settings.value("savePath", QStandardPaths::standardLocations(QStandardPaths::DocumentsLocation)).toString(); } void ShotcutSettings::setSavePath(const QString &s) { settings.setValue("savePath", s); emit savePathChanged(); } QStringList ShotcutSettings::recent() const { return m_recent.value(kRecentKey).toStringList(); } void ShotcutSettings::setRecent(const QStringList &ls) { if (ls.isEmpty()) m_recent.remove(kRecentKey); else if (!clearRecent()) m_recent.setValue(kRecentKey, ls); } QStringList ShotcutSettings::projects() { auto ls = m_recent.value(kProjectsKey).toStringList(); if (ls.isEmpty()) { for (auto &r : recent()) { if (r.endsWith(".mlt")) ls << r; } // Prevent entering this block repeatedly if (ls.isEmpty()) ls << QString(); setProjects(ls); } return ls; } void ShotcutSettings::setProjects(const QStringList &ls) { if (ls.isEmpty()) m_recent.remove(kProjectsKey); else if (!clearRecent()) m_recent.setValue(kProjectsKey, ls); } QString ShotcutSettings::theme() const { return settings.value("theme", "dark").toString(); } void ShotcutSettings::setTheme(const QString &s) { settings.setValue("theme", s); } QThread::Priority ShotcutSettings::jobPriority() const { const auto priority = settings.value("jobPriority", "low").toString(); if (priority == "low") { return QThread::LowPriority; } return QThread::NormalPriority; } void ShotcutSettings::setJobPriority(const QString &s) { settings.setValue("jobPriority", s); } bool ShotcutSettings::showTitleBars() const { return settings.value("titleBars", true).toBool(); } void ShotcutSettings::setShowTitleBars(bool b) { settings.setValue("titleBars", b); } bool ShotcutSettings::showToolBar() const { return settings.value("toolBar", true).toBool(); } void ShotcutSettings::setShowToolBar(bool b) { settings.setValue("toolBar", b); } bool ShotcutSettings::textUnderIcons() const { return settings.value("textUnderIcons", true).toBool(); } void ShotcutSettings::setTextUnderIcons(bool b) { settings.setValue("textUnderIcons", b); } bool ShotcutSettings::smallIcons() const { return settings.value("smallIcons", false).toBool(); } void ShotcutSettings::setSmallIcons(bool b) { settings.setValue("smallIcons", b); emit smallIconsChanged(); } QByteArray ShotcutSettings::windowGeometry() const { return settings.value("geometry2").toByteArray(); } void ShotcutSettings::setWindowGeometry(const QByteArray &a) { settings.setValue("geometry2", a); } QByteArray ShotcutSettings::windowGeometryDefault() const { return settings.value("geometryDefault").toByteArray(); } void ShotcutSettings::setWindowGeometryDefault(const QByteArray &a) { settings.setValue("geometryDefault", a); } QByteArray ShotcutSettings::windowState() const { return settings.value("windowState2").toByteArray(); } void ShotcutSettings::setWindowState(const QByteArray &a) { settings.setValue("windowState2", a); } QByteArray ShotcutSettings::windowStateDefault() const { return settings.value("windowStateDefault").toByteArray(); } void ShotcutSettings::setWindowStateDefault(const QByteArray &a) { settings.setValue("windowStateDefault", a); } QString ShotcutSettings::viewMode() const { return settings.value("playlist/viewMode").toString(); } void ShotcutSettings::setViewMode(const QString &viewMode) { settings.setValue("playlist/viewMode", viewMode); emit viewModeChanged(); } QString ShotcutSettings::exportFrameSuffix() const { return settings.value("exportFrameSuffix", ".png").toString(); } void ShotcutSettings::setExportFrameSuffix(const QString &exportFrameSuffix) { settings.setValue("exportFrameSuffix", exportFrameSuffix); } QString ShotcutSettings::encodePath() const { return settings.value("encode/path", QStandardPaths::standardLocations(QStandardPaths::MoviesLocation)).toString(); } void ShotcutSettings::setEncodePath(const QString &s) { settings.setValue("encode/path", s); } bool ShotcutSettings::encodeFreeSpaceCheck() const { return settings.value("encode/freeSpaceCheck", true).toBool(); } void ShotcutSettings::setEncodeFreeSpaceCheck(bool b) { settings.setValue("encode/freeSpaceCheck", b); } bool ShotcutSettings::encodeUseHardware() const { return settings.value("encode/useHardware").toBool(); } void ShotcutSettings::setEncodeUseHardware(bool b) { settings.setValue("encode/useHardware", b); } QStringList ShotcutSettings::encodeHardware() const { return settings.value("encode/hardware").toStringList(); } void ShotcutSettings::setEncodeHardware(const QStringList &ls) { if (ls.isEmpty()) settings.remove("encode/hardware"); else settings.setValue("encode/hardware", ls); } bool ShotcutSettings::encodeAdvanced() const { return settings.value("encode/advanced", false).toBool(); } void ShotcutSettings::setEncodeAdvanced(bool b) { settings.setValue("encode/advanced", b); } bool ShotcutSettings::convertAdvanced() const { return settings.value("convertAdvanced", false).toBool(); } void ShotcutSettings::setConvertAdvanced(bool b) { settings.setValue("convertAdvanced", b); } bool ShotcutSettings::showConvertClipDialog() const { return settings.value("showConvertClipDialog", true).toBool(); } void ShotcutSettings::setShowConvertClipDialog(bool b) { settings.setValue("showConvertClipDialog", b); } bool ShotcutSettings::encodeParallelProcessing() const { return settings.value("encode/parallelProcessing", false).toBool(); } void ShotcutSettings::setEncodeParallelProcessing(bool b) { settings.setValue("encode/parallelProcessing", b); } int ShotcutSettings::playerAudioChannels() const { return settings.value("player/audioChannels", 2).toInt(); } void ShotcutSettings::setPlayerAudioChannels(int i) { settings.setValue("player/audioChannels", i); emit playerAudioChannelsChanged(i); } QString ShotcutSettings::playerDeinterlacer() const { QString result = settings.value("player/deinterlacer", "onefield").toString(); //XXX workaround yadif crashing with mlt_transition if (result == "yadif" || result == "yadif-nospatial") result = "onefield"; return result; } void ShotcutSettings::setPlayerDeinterlacer(const QString &s) { settings.setValue("player/deinterlacer", s); } QString ShotcutSettings::playerExternal() const { auto result = settings.value("player/external", "").toString(); // "sdi" is no longer supported DVEO VidPort return result == "sdi" ? "" : result; } void ShotcutSettings::setPlayerExternal(const QString &s) { settings.setValue("player/external", s); } void ShotcutSettings::setPlayerGPU(bool b) { settings.setValue("player/gpu2", b); emit playerGpuChanged(); } bool ShotcutSettings::playerJACK() const { return settings.value("player/jack", false).toBool(); } QString ShotcutSettings::playerInterpolation() const { return settings.value("player/interpolation", "bilinear").toString(); } void ShotcutSettings::setPlayerInterpolation(const QString &s) { settings.setValue("player/interpolation", s); } bool ShotcutSettings::playerGPU() const { return settings.value("player/gpu2", false).toBool(); } bool ShotcutSettings::playerWarnGPU() const { return false; //settings.value("player/warnGPU", false).toBool(); } void ShotcutSettings::setPlayerJACK(bool b) { settings.setValue("player/jack", b); } int ShotcutSettings::playerKeyerMode() const { return settings.value("player/keyer", 0).toInt(); } void ShotcutSettings::setPlayerKeyerMode(int i) { settings.setValue("player/keyer", i); } bool ShotcutSettings::playerMuted() const { return settings.value("player/muted", false).toBool(); } void ShotcutSettings::setPlayerMuted(bool b) { settings.setValue("player/muted", b); } QString ShotcutSettings::playerProfile() const { return settings.value("player/profile", "").toString(); } void ShotcutSettings::setPlayerProfile(const QString &s) { settings.setValue("player/profile", s); } bool ShotcutSettings::playerProgressive() const { return settings.value("player/progressive", true).toBool(); } void ShotcutSettings::setPlayerProgressive(bool b) { settings.setValue("player/progressive", b); } bool ShotcutSettings::playerRealtime() const { return settings.value("player/realtime", true).toBool(); } void ShotcutSettings::setPlayerRealtime(bool b) { settings.setValue("player/realtime", b); } bool ShotcutSettings::playerScrubAudio() const { return settings.value("player/scrubAudio", true).toBool(); } void ShotcutSettings::setPlayerScrubAudio(bool b) { settings.setValue("player/scrubAudio", b); } int ShotcutSettings::playerVolume() const { return settings.value("player/volume", 88).toInt(); } void ShotcutSettings::setPlayerVolume(int i) { settings.setValue("player/volume", i); } float ShotcutSettings::playerZoom() const { return settings.value("player/zoom", 0.0f).toFloat(); } void ShotcutSettings::setPlayerZoom(float f) { settings.setValue("player/zoom", f); } int ShotcutSettings::playerPreviewScale() const { return settings.value("player/previewScale", 0).toInt(); } void ShotcutSettings::setPlayerPreviewScale(int i) { settings.setValue("player/previewScale", i); } int ShotcutSettings::playerVideoDelayMs() const { return settings.value("player/videoDelayMs", 0).toInt(); } void ShotcutSettings::setPlayerVideoDelayMs(int i) { settings.setValue("player/videoDelayMs", i); } double ShotcutSettings::playerJumpSeconds() const { return settings.value("player/jumpSeconds", 60.0).toDouble(); } void ShotcutSettings::setPlayerJumpSeconds(double i) { settings.setValue("player/jumpSeconds", i); } QString ShotcutSettings::playerAudioDriver() const { #if defined(Q_OS_WIN) auto s = playerAudioChannels() > 2 ? "directsound" : "winmm"; #else auto s = "pulseaudio"; #endif if (::qEnvironmentVariableIsSet("SDL_AUDIODRIVER")) { return ::qgetenv("SDL_AUDIODRIVER"); } else { return settings.value("player/audioDriver", s).toString(); } } void ShotcutSettings::setPlayerAudioDriver(const QString &s) { settings.setValue("player/audioDriver", s); } QString ShotcutSettings::playlistThumbnails() const { return settings.value("playlist/thumbnails", "small").toString(); } void ShotcutSettings::setPlaylistThumbnails(const QString &s) { settings.setValue("playlist/thumbnails", s); emit playlistThumbnailsChanged(); } bool ShotcutSettings::playlistAutoplay() const { return settings.value("playlist/autoplay", true).toBool(); } void ShotcutSettings::setPlaylistAutoplay(bool b) { settings.setValue("playlist/autoplay", b); } bool ShotcutSettings::playlistShowColumn(const QString &column) { return settings.value("playlist/columns/" + column, true).toBool(); } void ShotcutSettings::setPlaylistShowColumn(const QString &column, bool b) { settings.setValue("playlist/columns/" + column, b); } bool ShotcutSettings::timelineDragScrub() const { return settings.value("timeline/dragScrub", false).toBool(); } void ShotcutSettings::setTimelineDragScrub(bool b) { settings.setValue("timeline/dragScrub", b); emit timelineDragScrubChanged(); } bool ShotcutSettings::timelineShowWaveforms() const { return settings.value("timeline/waveforms", true).toBool(); } void ShotcutSettings::setTimelineShowWaveforms(bool b) { settings.setValue("timeline/waveforms", b); emit timelineShowWaveformsChanged(); } bool ShotcutSettings::timelineShowThumbnails() const { return settings.value("timeline/thumbnails", true).toBool(); } void ShotcutSettings::setTimelineShowThumbnails(bool b) { settings.setValue("timeline/thumbnails", b); emit timelineShowThumbnailsChanged(); } bool ShotcutSettings::timelineRipple() const { return settings.value("timeline/ripple", false).toBool(); } void ShotcutSettings::setTimelineRipple(bool b) { settings.setValue("timeline/ripple", b); emit timelineRippleChanged(); } bool ShotcutSettings::timelineRippleAllTracks() const { return settings.value("timeline/rippleAllTracks", false).toBool(); } void ShotcutSettings::setTimelineRippleAllTracks(bool b) { settings.setValue("timeline/rippleAllTracks", b); emit timelineRippleAllTracksChanged(); } bool ShotcutSettings::timelineRippleMarkers() const { return settings.value("timeline/rippleMarkers", false).toBool(); } void ShotcutSettings::setTimelineRippleMarkers(bool b) { settings.setValue("timeline/rippleMarkers", b); emit timelineRippleMarkersChanged(); } bool ShotcutSettings::timelineSnap() const { return settings.value("timeline/snap", true).toBool(); } void ShotcutSettings::setTimelineSnap(bool b) { settings.setValue("timeline/snap", b); emit timelineSnapChanged(); } int ShotcutSettings::timelineTrackHeight() const { return qMin(settings.value("timeline/trackHeight", 50).toInt(), kMaximumTrackHeight); } void ShotcutSettings::setTimelineTrackHeight(int n) { settings.setValue("timeline/trackHeight", qMin(n, kMaximumTrackHeight)); } bool ShotcutSettings::timelineScrollZoom() const { return settings.value("timeline/scrollZoom", true).toBool(); } void ShotcutSettings::setTimelineScrollZoom(bool b) { settings.setValue("timeline/scrollZoom", b); emit timelineScrollZoomChanged(); } bool ShotcutSettings::timelineFramebufferWaveform() const { return settings.value("timeline/framebufferWaveform", true).toBool(); } void ShotcutSettings::setTimelineFramebufferWaveform(bool b) { settings.setValue("timeline/framebufferWaveform", b); emit timelineFramebufferWaveformChanged(); } int ShotcutSettings::audioReferenceTrack() const { return settings.value("timeline/audioReferenceTrack", 0).toInt(); } void ShotcutSettings::setAudioReferenceTrack(int track) { settings.setValue("timeline/audioReferenceTrack", track); } double ShotcutSettings::audioReferenceSpeedRange() const { return settings.value("timeline/audioReferenceSpeedRange", 0).toDouble(); } void ShotcutSettings::setAudioReferenceSpeedRange(double range) { settings.setValue("timeline/audioReferenceSpeedRange", range); } bool ShotcutSettings::timelinePreviewTransition() const { return settings.value("timeline/previewTransition", true).toBool(); } void ShotcutSettings::setTimelinePreviewTransition(bool b) { settings.setValue("timeline/previewTransition", b); } void ShotcutSettings::setTimelineScrolling(ShotcutSettings::TimelineScrolling value) { settings.remove("timeline/centerPlayhead"); settings.setValue("timeline/scrolling", value); emit timelineScrollingChanged(); } ShotcutSettings::TimelineScrolling ShotcutSettings::timelineScrolling() const { if (settings.contains("timeline/centerPlayhead") && settings.value("timeline/centerPlayhead").toBool()) return ShotcutSettings::TimelineScrolling::CenterPlayhead; else return ShotcutSettings::TimelineScrolling(settings.value("timeline/scrolling", PageScrolling).toInt()); } bool ShotcutSettings::timelineAutoAddTracks() const { return settings.value("timeline/autoAddTracks", false).toBool(); } void ShotcutSettings::setTimelineAutoAddTracks(bool b) { if (b != timelineAutoAddTracks()) { settings.setValue("timeline/autoAddTracks", b); emit timelineAutoAddTracksChanged(); } } bool ShotcutSettings::timelineRectangleSelect() const { return settings.value("timeline/rectangleSelect", true).toBool(); } void ShotcutSettings::setTimelineRectangleSelect(bool b) { settings.setValue("timeline/rectangleSelect", b); emit timelineRectangleSelectChanged(); } QString ShotcutSettings::filterFavorite(const QString &filterName) { return settings.value("filter/favorite/" + filterName, "").toString(); } void ShotcutSettings::setFilterFavorite(const QString &filterName, const QString &value) { settings.setValue("filter/favorite/" + filterName, value); } double ShotcutSettings::audioInDuration() const { return settings.value("filter/audioInDuration", 1.0).toDouble(); } void ShotcutSettings::setAudioInDuration(double d) { settings.setValue("filter/audioInDuration", d); emit audioInDurationChanged(); } double ShotcutSettings::audioOutDuration() const { return settings.value("filter/audioOutDuration", 1.0).toDouble(); } void ShotcutSettings::setAudioOutDuration(double d) { settings.setValue("filter/audioOutDuration", d); emit audioOutDurationChanged(); } double ShotcutSettings::videoInDuration() const { return settings.value("filter/videoInDuration", 1.0).toDouble(); } void ShotcutSettings::setVideoInDuration(double d) { settings.setValue("filter/videoInDuration", d); emit videoInDurationChanged(); } double ShotcutSettings::videoOutDuration() const { return settings.value("filter/videoOutDuration", 1.0).toDouble(); } void ShotcutSettings::setVideoOutDuration(double d) { settings.setValue("filter/videoOutDuration", d); emit videoOutDurationChanged(); } bool ShotcutSettings::askOutputFilter() const { return settings.value("filter/askOutput", true).toBool(); } void ShotcutSettings::setAskOutputFilter(bool b) { settings.setValue("filter/askOutput", b); emit askOutputFilterChanged(); } bool ShotcutSettings::loudnessScopeShowMeter(const QString &meter) const { return settings.value("scope/loudness/" + meter, true).toBool(); } void ShotcutSettings::setLoudnessScopeShowMeter(const QString &meter, bool b) { settings.setValue("scope/loudness/" + meter, b); } void ShotcutSettings::setMarkerColor(const QColor &color) { settings.setValue("markers/color", color.name()); } QColor ShotcutSettings::markerColor() const { return QColor(settings.value("markers/color", "green").toString()); } void ShotcutSettings::setMarkersShowColumn(const QString &column, bool b) { settings.setValue("markers/columns/" + column, b); } bool ShotcutSettings::markersShowColumn(const QString &column) const { return settings.value("markers/columns/" + column, true).toBool(); } void ShotcutSettings::setMarkerSort(int column, Qt::SortOrder order) { settings.setValue("markers/sortColumn", column); settings.setValue("markers/sortOrder", order); } int ShotcutSettings::getMarkerSortColumn() { return settings.value("markers/sortColumn", -1).toInt(); } Qt::SortOrder ShotcutSettings::getMarkerSortOrder() { return (Qt::SortOrder)settings.value("markers/sortOrder", Qt::AscendingOrder).toInt(); } int ShotcutSettings::drawMethod() const { #ifdef Q_OS_WIN return settings.value("opengl", Qt::AA_UseOpenGLES).toInt(); #else return settings.value("opengl", Qt::AA_UseDesktopOpenGL).toInt(); #endif } void ShotcutSettings::setDrawMethod(int i) { settings.setValue("opengl", i); } bool ShotcutSettings::noUpgrade() const { return settings.value("noupgrade", false).toBool(); } void ShotcutSettings::setNoUpgrade(bool value) { settings.setValue("noupgrade", value); } bool ShotcutSettings::checkUpgradeAutomatic() { return settings.value("checkUpgradeAutomatic", false).toBool(); } void ShotcutSettings::setCheckUpgradeAutomatic(bool b) { settings.setValue("checkUpgradeAutomatic", b); } bool ShotcutSettings::askUpgradeAutomatic() { return settings.value("askUpgradeAutmatic", true).toBool(); } void ShotcutSettings::setAskUpgradeAutomatic(bool b) { settings.setValue("askUpgradeAutmatic", b); } bool ShotcutSettings::askChangeVideoMode() { return settings.value("askChangeVideoMode", true).toBool(); } void ShotcutSettings::setAskChangeVideoMode(bool b) { settings.setValue("askChangeVideoMode", b); } void ShotcutSettings::sync() { settings.sync(); } QString ShotcutSettings::appDataLocation() const { if (!m_appDataLocation.isEmpty()) return m_appDataLocation; else return QStandardPaths::writableLocation(QStandardPaths::AppLocalDataLocation); } void ShotcutSettings::setAppDataForSession(const QString &location) { // This is intended to be called when using a command line option // to set the AppData location. appDataForSession = location; if (instance) instance.reset(new ShotcutSettings(location)); } void ShotcutSettings::setAppDataLocally(const QString &location) { // This is intended to be called when using a GUI action to set the // the new AppData location. // Copy the existing settings if they exist. if (!QFile::exists(location + SHOTCUT_INI_FILENAME)) { QSettings newSettings(location + SHOTCUT_INI_FILENAME, QSettings::IniFormat); foreach (const QString &key, settings.allKeys()) newSettings.setValue(key, settings.value(key)); newSettings.sync(); } // Set the new location. QSettings localSettings; localSettings.setValue(APP_DATA_DIR_KEY, location); localSettings.sync(); } QStringList ShotcutSettings::layouts() const { QStringList result; for (const auto &s : settings.value("layout/layouts").toStringList()) { if (!s.startsWith("__")) result << s; } return result; } bool ShotcutSettings::setLayout(const QString &name, const QByteArray &geometry, const QByteArray &state) { bool isNew = false; QStringList layouts = this->layouts(); if (layouts.indexOf(name) == -1) { isNew = true; layouts.append(name); settings.setValue("layout/layouts", layouts); } settings.setValue(QStringLiteral("layout/%1_%2").arg(name, "geometry"), geometry); settings.setValue(QStringLiteral("layout/%1_%2").arg(name, "state"), state); return isNew; } QByteArray ShotcutSettings::layoutGeometry(const QString &name) { QString key = QStringLiteral("layout/%1_geometry").arg(name); return settings.value(key).toByteArray(); } QByteArray ShotcutSettings::layoutState(const QString &name) { QString key = QStringLiteral("layout/%1_state").arg(name); return settings.value(key).toByteArray(); } bool ShotcutSettings::removeLayout(const QString &name) { QStringList list = layouts(); int index = list.indexOf(name); if (index > -1) { list.removeAt(index); if (list.isEmpty()) settings.remove("layout/layouts"); else settings.setValue("layout/layouts", list); settings.remove(QStringLiteral("layout/%1_%2").arg(name, "geometry")); settings.remove(QStringLiteral("layout/%1_%2").arg(name, "state")); return true; } return false; } int ShotcutSettings::layoutMode() const { return settings.value("layout/mode", -1).toInt(); } void ShotcutSettings::setLayoutMode(int mode) { settings.setValue("layout/mode", mode); } bool ShotcutSettings::clearRecent() const { return settings.value("clearRecent", false).toBool(); } void ShotcutSettings::setClearRecent(bool b) { settings.setValue("clearRecent", b); } QString ShotcutSettings::projectsFolder() const { return settings.value("projectsFolder", QStandardPaths::standardLocations(QStandardPaths::MoviesLocation)).toString(); } void ShotcutSettings::setProjectsFolder(const QString &path) { settings.setValue("projectsFolder", path); } QString ShotcutSettings::audioInput() const { QString defaultValue = "default"; #if defined(Q_OS_MAC) || defined(Q_OS_WIN) for (const auto &deviceInfo : QMediaDevices::audioInputs()) { defaultValue = deviceInfo.description(); } #endif return settings.value("audioInput", defaultValue).toString(); } void ShotcutSettings::setAudioInput(const QString &name) { settings.setValue("audioInput", name); } QString ShotcutSettings::videoInput() const { return settings.value("videoInput").toString(); } void ShotcutSettings::setVideoInput(const QString &name) { settings.setValue("videoInput", name); } QString ShotcutSettings::glaxnimatePath() const { QDir dir(qApp->applicationDirPath()); return settings.value("glaxnimatePath", dir.absoluteFilePath("glaxnimate")).toString(); } void ShotcutSettings::setGlaxnimatePath(const QString &path) { settings.setValue("glaxnimatePath", path); } bool ShotcutSettings::exportRangeMarkers() const { return settings.value("exportRangeMarkers", true).toBool(); } void ShotcutSettings::setExportRangeMarkers(bool b) { settings.setValue("exportRangeMarkers", b); } bool ShotcutSettings::proxyEnabled() const { return settings.value("proxy/enabled", false).toBool(); } void ShotcutSettings::setProxyEnabled(bool b) { settings.setValue("proxy/enabled", b); } QString ShotcutSettings::proxyFolder() const { QDir dir(appDataLocation()); const char *subfolder = "proxies"; if (!dir.cd(subfolder)) { if (dir.mkdir(subfolder)) dir.cd(subfolder); } return settings.value("proxy/folder", dir.path()).toString(); } void ShotcutSettings::setProxyFolder(const QString &path) { settings.setValue("proxy/folder", path); } bool ShotcutSettings::proxyUseProjectFolder() const { return settings.value("proxy/useProjectFolder", true).toBool(); } void ShotcutSettings::setProxyUseProjectFolder(bool b) { settings.setValue("proxy/useProjectFolder", b); } bool ShotcutSettings::proxyUseHardware() const { return settings.value("proxy/useHardware", false).toBool(); } void ShotcutSettings::setProxyUseHardware(bool b) { settings.setValue("proxy/useHardware", b); } void ShotcutSettings::clearShortcuts(const QString &name) { QString key = "shortcuts/" + name; settings.remove(key); } void ShotcutSettings::setShortcuts(const QString &name, const QList<QKeySequence> &shortcuts) { QString key = "shortcuts/" + name; QString shortcutSetting; if (shortcuts.size() > 0) shortcutSetting += shortcuts[0].toString(); shortcutSetting += "||"; if (shortcuts.size() > 1) shortcutSetting += shortcuts[1].toString(); settings.setValue(key, shortcutSetting); } QList<QKeySequence> ShotcutSettings::shortcuts(const QString &name) { QString key = "shortcuts/" + name; QList<QKeySequence> shortcuts; QString shortcutSetting = settings.value(key, "").toString(); if (!shortcutSetting.isEmpty()) { for (const QString &s : shortcutSetting.split("||")) shortcuts << QKeySequence::fromString(s); } return shortcuts; } double ShotcutSettings::slideshowClipDuration(double defaultClipDuration) const { return settings.value("slideshow/clipDuration", defaultClipDuration).toDouble(); } void ShotcutSettings::setSlideshowClipDuration(double clipDuration) { settings.setValue("slideshow/clipDuration", clipDuration); } int ShotcutSettings::slideshowAspectConversion(int defaultAspectConversion) const { return settings.value("slideshow/aspectConversion", defaultAspectConversion).toInt(); } void ShotcutSettings::setSlideshowAspectConversion(int aspectConversion) { settings.setValue("slideshow/aspectConversion", aspectConversion); } int ShotcutSettings::slideshowZoomPercent(int defaultZoomPercent) const { return settings.value("slideshow/zoomPercent", defaultZoomPercent).toInt(); } void ShotcutSettings::setSlideshowZoomPercent(int zoomPercent) { settings.setValue("slideshow/zoomPercent", zoomPercent); } double ShotcutSettings::slideshowTransitionDuration(double defaultTransitionDuration) const { return settings.value("slideshow/transitionDuration", defaultTransitionDuration).toDouble(); } void ShotcutSettings::setSlideshowTransitionDuration(double transitionDuration) { settings.setValue("slideshow/transitionDuration", transitionDuration); } int ShotcutSettings::slideshowTransitionStyle(int defaultTransitionStyle) const { return settings.value("slideshow/transitionStyle", defaultTransitionStyle).toInt(); } void ShotcutSettings::setSlideshowTransitionStyle(int transitionStyle) { settings.setValue("slideshow/transitionStyle", transitionStyle); } int ShotcutSettings::slideshowTransitionSoftness(int defaultTransitionStyle) const { return settings.value("slideshow/transitionSoftness", defaultTransitionStyle).toInt(); } void ShotcutSettings::setSlideshowTransitionSoftness(int transitionSoftness) { settings.setValue("slideshow/transitionSoftness", transitionSoftness); } bool ShotcutSettings::keyframesDragScrub() const { return settings.value("keyframes/dragScrub", false).toBool(); } void ShotcutSettings::setKeyframesDragScrub(bool b) { settings.setValue("keyframes/dragScrub", b); emit keyframesDragScrubChanged(); } void ShotcutSettings::setSubtitlesShowColumn(const QString &column, bool b) { settings.setValue("subtitles/columns/" + column, b); } bool ShotcutSettings::subtitlesShowColumn(const QString &column) const { return settings.value("subtitles/columns/" + column, true).toBool(); } void ShotcutSettings::setSubtitlesTrackTimeline(bool b) { settings.setValue("subtitles/trackTimeline", b); } bool ShotcutSettings::subtitlesTrackTimeline() const { return settings.value("subtitles/trackTimeline", true).toBool(); } void ShotcutSettings::setSubtitlesShowPrevNext(bool b) { settings.setValue("subtitles/showPrevNext", b); } bool ShotcutSettings::subtitlesShowPrevNext() const { return settings.value("subtitles/showPrevNext", true).toBool(); } void ShotcutSettings::setWhisperExe(const QString &path) { settings.setValue("subtitles/whisperExe", path); } QString ShotcutSettings::whisperExe() { QDir dir(qApp->applicationDirPath()); #if defined(Q_OS_WIN) auto exe = "whisper.cpp-main.exe"; #else auto exe = "whisper.cpp-main"; #endif return settings.value("subtitles/whisperExe", dir.absoluteFilePath(exe)).toString(); } void ShotcutSettings::setWhisperModel(const QString &path) { settings.setValue("subtitles/whisperModel", path); } QString ShotcutSettings::whisperModel() { QDir dataPath = QmlApplication::dataDir(); dataPath.cd("shotcut/whisper_models"); return settings.value("subtitles/whisperModel", dataPath.absoluteFilePath("ggml-base-q5_1.bin")).toString(); } void ShotcutSettings::setNotesZoom(int zoom) { settings.setValue("notes/zoom", zoom); } int ShotcutSettings::notesZoom() const { return settings.value("notes/zoom", 0).toInt(); } void ShotcutSettings::reset() { for (auto &key : settings.allKeys()) { settings.remove(key); } } int ShotcutSettings::undoLimit() const { return settings.value("undoLimit", 50).toInt(); } bool ShotcutSettings::warnLowMemory() const { return settings.value("warnLowMemory", true).toBool(); } int ShotcutSettings::backupPeriod() const { return settings.value("backupPeriod", 24 * 60).toInt(); } void ShotcutSettings::setBackupPeriod(int minutes) { settings.setValue("backupPeriod", minutes); } mlt_time_format ShotcutSettings::timeFormat() const { return (mlt_time_format)settings.value("timeFormat", mlt_time_smpte_df).toInt(); } void ShotcutSettings::setTimeFormat(int format) { settings.setValue("timeFormat", format); emit timeFormatChanged(); }
36,623
C++
.cpp
1,186
27.63575
116
0.748338
mltframework/shotcut
10,796
1,118
50
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
13,112
actions.cpp
mltframework_shotcut/src/actions.cpp
/* * Copyright (c) 2013-2023 Meltytech, LLC * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "actions.h" #include <Logger.h> #include "settings.h" #include <QAction> #include <QMenu> const char *ShotcutActions::hardKeyProperty = "_hardkey"; const char *ShotcutActions::displayProperty = "_display"; const char *ShotcutActions::defaultKey1Property = "_defaultKey1"; const char *ShotcutActions::defaultKey2Property = "_defaultKey2"; const char *ShotcutActions::defaultToolTipProperty = "_defaultToolTip"; static QScopedPointer<ShotcutActions> instance; ShotcutActions &ShotcutActions::singleton() { if (!instance) { instance.reset(new ShotcutActions()); } return *instance; } void ShotcutActions::add(const QString &key, QAction *action, QString group) { auto iterator = m_actions.find(key); if (iterator != m_actions.end() && iterator.value() != action) { LOG_ERROR() << "Action already exists with this key" << key; return; } action->setObjectName(key); if (group.isEmpty()) { group = tr("Other"); } action->setProperty(displayProperty, group + " > " + action->iconText()); QList<QKeySequence> sequences = action->shortcuts(); if (sequences.size() > 0) action->setProperty(defaultKey1Property, sequences[0].toString()); if (sequences.size() > 1) action->setProperty(defaultKey2Property, sequences[1].toString()); action->setProperty(defaultToolTipProperty, action->toolTip()); m_actions[key] = action; } void ShotcutActions::loadFromMenu(QMenu *menu, QString group) { if (!menu->title().isEmpty()) { if (!group.isEmpty()) group = group + " > " + menu->menuAction()->iconText(); else group = menu->menuAction()->iconText(); } for (QAction *action : menu->actions()) { if (action->isSeparator() || action->objectName() == "dummyAction") continue; QMenu *submenu = action->menu(); if (submenu) { loadFromMenu(submenu, group); } else { if (action->objectName().isEmpty()) { // Each action must have a unique object name QString newObjectName = group + action->iconText(); newObjectName = newObjectName.replace(" ", ""); newObjectName = newObjectName.replace(">", ""); action->setObjectName(newObjectName); } add(action->objectName(), action, group); } } } QAction *ShotcutActions::operator [](const QString &key) { auto iterator = m_actions.find(key); if (iterator != m_actions.end()) { return iterator.value(); } return nullptr; } QList<QString> ShotcutActions::keys() { return m_actions.keys(); } void ShotcutActions::overrideShortcuts(const QString &key, QList<QKeySequence> shortcuts) { QAction *action = m_actions[key]; if (!action) { LOG_ERROR() << "Invalid action" << key; return; } QList<QKeySequence> defaultShortcuts; QVariant seq = action->property(defaultKey1Property); if (seq.isValid()) defaultShortcuts << QKeySequence::fromString(seq.toString()); seq = action->property(defaultKey2Property); if (seq.isValid()) defaultShortcuts << QKeySequence::fromString(seq.toString()); // Make the lists the same size for easy comparison while (shortcuts.size() < 2) shortcuts << QKeySequence(); while (defaultShortcuts.size() < 2) defaultShortcuts << QKeySequence(); if (shortcuts == defaultShortcuts) { // Shortcuts are set to default - delete all settings Settings.clearShortcuts(action->objectName()); } else { Settings.setShortcuts(action->objectName(), shortcuts); } action->setShortcuts(shortcuts); addShortcutToToolTip(action); } void ShotcutActions::initializeShortcuts() { // Call this function exactly once after all the actions have been // added to the ShotcutActions object. for (auto action : m_actions) { QList<QKeySequence> shortcutSettings = Settings.shortcuts(action->objectName()); if (!shortcutSettings.isEmpty()) action->setShortcuts(shortcutSettings); addShortcutToToolTip(action); } } void ShotcutActions::addShortcutToToolTip(QAction *action) { QString tooltip = action->property(defaultToolTipProperty).toString(); QString shortcut = action->shortcut().toString(QKeySequence::NativeText); if (shortcut.isEmpty()) shortcut = action->property(hardKeyProperty).toString(); if (!shortcut.isEmpty()) { if (!tooltip.isEmpty()) tooltip += " "; tooltip = tooltip + "(" + shortcut + ")"; } action->setToolTip(tooltip); }
5,397
C++
.cpp
144
31.895833
89
0.67062
mltframework/shotcut
10,796
1,118
50
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
13,113
mltcontroller.cpp
mltframework_shotcut/src/mltcontroller.cpp
/* * Copyright (c) 2011-2024 Meltytech, LLC * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "mltcontroller.h" #include <QWidget> #include <QPalette> #include <QMetaType> #include <QFileInfo> #include <QApplication> #include <QProcess> #include <QUuid> #include <QSaveFile> #include <QTextStream> #include <QThreadPool> #include <Logger.h> #include <Mlt.h> #include <cmath> #include <clocale> #include <unistd.h> #include "settings.h" #include "shotcut_mlt_properties.h" #include "mainwindow.h" #include "controllers/filtercontroller.h" #include "qmltypes/qmlmetadata.h" #include "util.h" #include "proxymanager.h" #if defined(Q_OS_WIN) #include "widgets/d3dvideowidget.h" #include "widgets/openglvideowidget.h" #elif defined(Q_OS_MAC) #include "widgets/metalvideowidget.h" #else #include "widgets/openglvideowidget.h" #endif namespace Mlt { static const int kThumbnailOutSeekFactor = 5; static Controller *instance = nullptr; const QString XmlMimeType("application/vnd.mlt+xml"); static const char *kMltXmlPropertyName = "string"; Controller::Controller() : m_profile(kDefaultMltProfile) , m_previewProfile(kDefaultMltProfile) , m_blockRefresh(false) { LOG_DEBUG() << "begin"; ::qputenv("MLT_REPOSITORY_DENY", "libmltqt:libmltglaxnimate"); m_repo = Mlt::Factory::init(); resetLocale(); initFiltersClipboard(); updateAvformatCaching(0); LOG_DEBUG() << "end"; } Controller &Controller::singleton(QObject *parent) { if (!instance) { qRegisterMetaType<Mlt::Frame>("Mlt::Frame"); qRegisterMetaType<SharedFrame>("SharedFrame"); #if defined(Q_OS_WIN) if (QSGRendererInterface::Direct3D11 == QQuickWindow::graphicsApi()) instance = new D3DVideoWidget(parent); else instance = new OpenGLVideoWidget(parent); #elif defined(Q_OS_MAC) instance = new MetalVideoWidget(parent); #else instance = new OpenGLVideoWidget(parent); #endif } return *instance; } Controller::~Controller() { LOG_DEBUG() << "begin"; close(); closeConsumer(); LOG_DEBUG() << "end"; } void Controller::destroy() { delete instance; } int Controller::setProducer(Mlt::Producer *producer, bool) { int error = 0; if (producer != m_producer.data()) close(); if (producer && producer->is_valid()) { m_producer.reset(producer); } else { // Cleanup on error error = 1; delete producer; } return error; } int Controller::open(const QString &url, const QString &urlToSave, bool skipConvert) { int error = checkFile(url); if (error) { return error; } Mlt::Producer *newProducer = nullptr; close(); auto myUrl = url; if (url.endsWith(".mlt")) { // MLT xml producer does URL decoding; so if the URL contains % it must be encoded. myUrl = QUrl::toPercentEncoding(url).constData(); } if (Settings.playerGPU() && !profile().is_explicit()) // Prevent loading normalizing filters, which might be Movit ones that // may not have a proper OpenGL context when requesting a sample frame. newProducer = new Mlt::Producer(profile(), "abnormal", myUrl.toUtf8().constData()); else newProducer = new Mlt::Producer(profile(), myUrl.toUtf8().constData()); if (newProducer && newProducer->is_valid()) { double fps = profile().fps(); if (!profile().is_explicit()) { profile().from_producer(*newProducer); profile().set_width(Util::coerceMultiple(profile().width())); profile().set_height(Util::coerceMultiple(profile().height())); } updatePreviewProfile(); setPreviewScale(Settings.playerPreviewScale()); if (url.endsWith(".mlt")) { // Load the number of audio channels being used when this project was created. int channels = newProducer->get_int(kShotcutProjectAudioChannels); if (!channels) channels = 2; m_audioChannels = channels; } if (Util::isFpsDifferent(profile().fps(), fps) || (Settings.playerGPU() && !profile().is_explicit())) { // Reload with correct FPS or with Movit normalizing filters attached. delete newProducer; newProducer = new Mlt::Producer(profile(), myUrl.toUtf8().constData()); } if (m_url.isEmpty() && QString(newProducer->get("xml")) == "was here") { if (newProducer->get_int("_original_type") != mlt_service_tractor_type || (newProducer->get_int("_original_type") == mlt_service_tractor_type && newProducer->get(kShotcutXmlProperty))) m_url = urlToSave; } Producer *producer = setupNewProducer(newProducer); producer->set(kShotcutSkipConvertProperty, skipConvert); delete newProducer; newProducer = producer; } else { delete newProducer; newProducer = nullptr; error = 1; } m_producer.reset(newProducer); return error; } bool Controller::openXML(const QString &filename) { bool error = true; close(); if (Settings.playerGPU() && profile().is_explicit()) { Profile testProfile; Producer producer(testProfile, filename.toUtf8().constData()); if (testProfile.width() != profile().width() || testProfile.height() != profile().height() || Util::isFpsDifferent(profile().fps(), testProfile.fps())) { return error; } } Producer producer(profile(), filename.toUtf8().constData()); if (producer.is_valid()) { double fps = profile().fps(); if (!profile().is_explicit()) { profile().from_producer(producer); profile().set_width(Util::coerceMultiple(profile().width())); profile().set_height(Util::coerceMultiple(profile().height())); } updatePreviewProfile(); setPreviewScale(Settings.playerPreviewScale()); if (Util::isFpsDifferent(profile().fps(), fps)) { // reopen with the correct fps producer = Producer(profile(), filename.toUtf8().constData()); } producer.set(kShotcutVirtualClip, 1); producer.set("resource", filename.toUtf8().constData()); setProducer(new Producer(producer)); error = false; } return error; } void Controller::close() { if (m_profile.is_explicit()) { pause(); } else if (m_consumer && !m_consumer->is_stopped()) { m_consumer->stop(); } if (isSeekableClip()) { setSavedProducer(m_producer.data()); } m_producer.reset(); } void Controller::closeConsumer() { if (m_consumer) m_consumer->stop(); m_consumer.reset(); m_jackFilter.reset(); } void Controller::play(double speed) { if (m_jackFilter) { if (speed == 1.0) m_jackFilter->fire_event("jack-start"); else stopJack(); } if (m_producer) m_producer->set_speed(speed); if (m_consumer) { m_consumer->start(); refreshConsumer(Settings.playerScrubAudio()); } setVolume(m_volume); } bool Controller::isPaused() const { return m_producer && qAbs(m_producer->get_speed()) < 0.1; } static void fire_jack_seek_event(mlt_properties jack, int position) { mlt_events_fire(jack, "jack-seek", mlt_event_data_from_int(position)); } void Controller::pause() { if (m_producer && !isPaused()) { m_producer->set_speed(0); if (m_consumer && m_consumer->is_valid()) { m_producer->seek(m_consumer->position() + 1); m_consumer->purge(); m_consumer->start(); // The following fixes a bug with frame-dropping. It is possible a video frame rendering // was just dropped. Then, Shotcut does not know the latest position. Next, a filter modifies // a value, which refreshes the consumer, and the position advances. If that value change // creates a keyframe, then a subsequent value change creates an additional keyframe one // (or more?) frames after the previous one. // https://forum.shotcut.org/t/2-keyframes-created-instead-of-one/11252 if (m_consumer->get_int("real_time") > 0) refreshConsumer(); } } if (m_jackFilter) { stopJack(); int position = (m_producer && m_producer->is_valid()) ? m_producer->position() : 0; ++m_skipJackEvents; fire_jack_seek_event(m_jackFilter->get_properties(), position); } setVolume(m_volume); } void Controller::stop() { if (m_consumer && !m_consumer->is_stopped()) m_consumer->stop(); if (m_producer) m_producer->seek(0); stopJack(); } void Controller::on_jack_started(mlt_properties, void *object, mlt_event_data data) { if (object) (static_cast<Controller *>(object))->onJackStarted(Mlt::EventData(data).to_int()); } void Controller::onJackStarted(int position) { if (m_producer) { m_producer->set_speed(1); m_producer->seek(position); Controller::refreshConsumer(); } } void Controller::on_jack_stopped(mlt_properties, void *object, mlt_event_data data) { if (object) (static_cast<Controller *>(object))->onJackStopped(EventData(data).to_int()); } void Controller::onJackStopped(int position) { if (m_skipJackEvents) { --m_skipJackEvents; } else { if (m_producer) { if (!isPaused()) { Event *event = m_consumer->setup_wait_for("consumer-sdl-paused"); int result = m_producer->set_speed(0); if (result == 0 && m_consumer->is_valid() && !m_consumer->is_stopped()) m_consumer->wait_for(event); delete event; } m_producer->seek(position); } if (m_consumer && m_consumer->get_int("real_time") >= -1) m_consumer->purge(); refreshConsumer(); } } void Controller::stopJack() { if (m_jackFilter) { m_skipJackEvents = 2; m_jackFilter->fire_event("jack-stop"); } } void Controller::initFiltersClipboard() { m_filtersClipboard.reset(new Mlt::Producer(profile(), "color", "black")); if (m_filtersClipboard->is_valid()) { m_filtersClipboard->set(kShotcutFiltersClipboard, 1); } } bool Controller::enableJack(bool enable) { if (!m_consumer) return true; if (enable && !m_jackFilter) { m_jackFilter.reset(new Mlt::Filter(profile(), "jack", "Shotcut player")); if (m_jackFilter->is_valid()) { m_jackFilter->set("channels", Settings.playerAudioChannels()); switch (Settings.playerAudioChannels()) { case 8: m_jackFilter->set("in_8", "-"); m_jackFilter->set("out_8", "system:playback_8"); Q_FALLTHROUGH(); case 7: m_jackFilter->set("in_7", "-"); m_jackFilter->set("out_7", "system:playback_7"); Q_FALLTHROUGH(); case 6: m_jackFilter->set("in_6", "-"); m_jackFilter->set("out_6", "system:playback_6"); Q_FALLTHROUGH(); case 5: m_jackFilter->set("in_5", "-"); m_jackFilter->set("out_5", "system:playback_5"); Q_FALLTHROUGH(); case 4: m_jackFilter->set("in_4", "-"); m_jackFilter->set("out_4", "system:playback_4"); Q_FALLTHROUGH(); case 3: m_jackFilter->set("in_3", "-"); m_jackFilter->set("out_3", "system:playback_3"); Q_FALLTHROUGH(); case 2: m_jackFilter->set("in_2", "-"); m_jackFilter->set("out_2", "system:playback_2"); Q_FALLTHROUGH(); case 1: m_jackFilter->set("in_1", "-"); m_jackFilter->set("out_1", "system:playback_1"); Q_FALLTHROUGH(); default: break; } m_consumer->attach(*m_jackFilter); m_consumer->set("audio_off", 1); if (isSeekable()) { m_jackFilter->listen("jack-started", this, reinterpret_cast<mlt_listener>(on_jack_started)); m_jackFilter->listen("jack-stopped", this, reinterpret_cast<mlt_listener>(on_jack_stopped)); } } else { m_jackFilter.reset(); return false; } } else if (!enable && m_jackFilter) { m_consumer->detach(*m_jackFilter); m_jackFilter.reset(); m_consumer->set("audio_off", 0); m_consumer->stop(); m_consumer->start(); } return true; } void Controller::setVolume(double volume, bool muteOnPause) { m_volume = volume; // Keep the consumer muted when paused if (muteOnPause && isPaused()) { volume = 0.0; } if (m_consumer) { if (m_consumer->get("mlt_service") == QStringLiteral("multi")) { m_consumer->set("0.volume", volume); } else { m_consumer->set("volume", volume); } } } double Controller::volume() const { return m_volume; } void Controller::onWindowResize() { bool scrub = isPaused() ? false : Settings.playerScrubAudio(); refreshConsumer(scrub); } void Controller::seek(int position) { setVolume(m_volume, false); if (m_producer) { // Always pause before seeking (if not already paused). m_producer->set_speed(0); m_producer->seek(position); if (m_consumer && m_consumer->is_valid()) { if (m_consumer->is_stopped()) { m_consumer->start(); } else { m_consumer->purge(); Controller::refreshConsumer(Settings.playerScrubAudio()); } } } if (m_jackFilter) { stopJack(); ++m_skipJackEvents; fire_jack_seek_event(m_jackFilter->get_properties(), position); } } void Controller::refreshConsumer(bool scrubAudio) { if (!m_blockRefresh && m_consumer) { // need to refresh consumer when paused m_consumer->set("scrub_audio", scrubAudio); m_consumer->set("refresh", 1); } } bool Controller::saveXML(const QString &filename, Service *service, bool withRelativePaths, QTemporaryFile *tempFile, bool proxy, QString projectNote) { QMutexLocker locker(&m_saveXmlMutex); QFileInfo fi(filename); Consumer c(profile(), "xml", proxy ? filename.toUtf8().constData() : kMltXmlPropertyName); Service s(service ? service->get_service() : m_producer->get_service()); if (s.is_valid()) { // The Shotcut rule for paths in MLT XML is forward slashes as created by QFileDialog and QmlFile. QString root = withRelativePaths ? QDir::fromNativeSeparators(fi.absolutePath()) : ""; s.set(kShotcutProjectAudioChannels, m_audioChannels); s.set(kShotcutProjectFolder, m_projectFolder.isEmpty() ? 0 : 1); if (!projectNote.isEmpty()) { s.set(kShotcutProjectNote, projectNote.toUtf8().constData()); } else { s.clear(kShotcutProjectNote); } int ignore = s.get_int("ignore_points"); if (ignore) s.set("ignore_points", 0); c.set("time_format", "clock"); c.set("store", "shotcut"); c.set("root", root.toUtf8().constData()); c.set("no_root", 1); c.set("title", QStringLiteral("Shotcut version ").append(SHOTCUT_VERSION).toUtf8().constData()); c.connect(s); c.start(); if (ignore) s.set("ignore_points", ignore); auto xml = QString::fromUtf8(c.get(kMltXmlPropertyName)); if (!proxy && ProxyManager::filterXML(xml, root)) { // also verifies if (tempFile) { QTextStream stream(tempFile); stream.setEncoding(QStringConverter::Utf8); stream << xml; if (tempFile->error() != QFileDevice::NoError) { LOG_ERROR() << "error while writing MLT XML file" << tempFile->fileName() << ":" << tempFile->errorString(); return false; } } else { QSaveFile file(filename); file.setDirectWriteFallback(true); if (!file.open(QIODevice::WriteOnly | QIODevice::Truncate)) { LOG_ERROR() << "failed to open MLT XML file for writing" << filename; return false; } QTextStream stream(&file); stream.setEncoding(QStringConverter::Utf8); stream << xml; if (file.error() != QFileDevice::NoError) { LOG_ERROR() << "error while writing MLT XML file" << filename << ":" << file.errorString(); return false; } return file.commit(); } } } return false; } QString Controller::XML(Service *service, bool withProfile, bool withMetadata) { Consumer c(profile(), "xml", kMltXmlPropertyName); Service s(service ? service->get_service() : (m_producer && m_producer->is_valid()) ? m_producer->get_service() : nullptr); if (!s.is_valid()) return ""; int ignore = s.get_int("ignore_points"); if (ignore) s.set("ignore_points", 0); c.set("time_format", "clock"); if (!withMetadata) c.set("no_meta", 1); c.set("no_profile", !withProfile); c.set("store", "shotcut"); c.set("root", ""); c.connect(s); c.start(); if (ignore) s.set("ignore_points", ignore); return QString::fromUtf8(c.get(kMltXmlPropertyName)); } int Controller::consumerChanged() { int error = 0; if (m_consumer) { bool jackEnabled = !m_jackFilter.isNull(); m_consumer->stop(); m_consumer.reset(); m_jackFilter.reset(); error = reconfigure(false); if (m_consumer) { enableJack(jackEnabled); setVolume(m_volume); m_consumer->start(); } } return error; } void Controller::setProfile(const QString &profile_name) { LOG_DEBUG() << "setting to profile" << (profile_name.isEmpty() ? "Automatic" : profile_name); if (!profile_name.isEmpty()) { Mlt::Profile tmp(profile_name.toUtf8().constData()); m_profile.set_colorspace(tmp.colorspace()); auto gcd = Util::greatestCommonDivisor(tmp.frame_rate_num(), tmp.frame_rate_den()); m_profile.set_frame_rate(tmp.frame_rate_num() / gcd, tmp.frame_rate_den() / gcd); m_profile.set_height(Util::coerceMultiple(tmp.height())); m_profile.set_progressive(tmp.progressive()); m_profile.set_sample_aspect(tmp.sample_aspect_num(), tmp.sample_aspect_den()); m_profile.set_display_aspect(tmp.display_aspect_num(), tmp.display_aspect_den()); m_profile.set_width(Util::coerceMultiple(tmp.width())); m_profile.set_explicit(true); } else { m_profile.set_explicit(false); if (m_producer && m_producer->is_valid() && (qstrcmp(m_producer->get("mlt_service"), "color") || qstrcmp(m_producer->get("resource"), "_hide"))) { m_profile.from_producer(*m_producer); m_profile.set_width(Util::coerceMultiple(m_profile.width())); } else { // Use a default profile with the dummy hidden color producer. Mlt::Profile tmp(kDefaultMltProfile); m_profile.set_colorspace(tmp.colorspace()); m_profile.set_frame_rate(tmp.frame_rate_num(), tmp.frame_rate_den()); m_profile.set_height(Util::coerceMultiple(tmp.height())); m_profile.set_progressive(tmp.progressive()); m_profile.set_sample_aspect(tmp.sample_aspect_num(), tmp.sample_aspect_den()); m_profile.set_display_aspect(tmp.display_aspect_num(), tmp.display_aspect_den()); m_profile.set_width(Util::coerceMultiple(tmp.width())); } } updatePreviewProfile(); } void Controller::setAudioChannels(int audioChannels) { LOG_DEBUG() << audioChannels; if (audioChannels != m_audioChannels) { m_audioChannels = audioChannels; restart(); } } QString Controller::resource() const { QString resource; if (!m_producer) return resource; resource = QString::fromUtf8(m_producer->get("resource")); return resource; } bool Controller::isSeekable(Producer *p) const { bool seekable = false; Mlt::Producer *producer = p ? p : m_producer.data(); if (producer && producer->is_valid()) { if (producer->get("force_seekable")) { seekable = producer->get_int("force_seekable"); } else { seekable = producer->get_int("seekable"); if (!seekable && producer->get("mlt_type")) { // MLT xml producer or tractor seekable = !strcmp(producer->get("mlt_type"), "mlt_producer"); } if (!seekable) { // These generators can take an out point to define their length. // TODO: Currently, these max out at 15000 frames, which is arbitrary. QString service(producer->get("mlt_service")); seekable = (service == "color") || service.startsWith("frei0r.") || (service == "tone") || (service == "count") || (service == "noise") || (service == "consumer"); } } } return seekable; } bool Controller::isLiveProducer(Producer *p) const { Mlt::Producer *producer = p ? p : m_producer.data(); if (producer && producer->is_valid()) { return producer->get_length() == std::numeric_limits<int>::max(); } return false; } bool Controller::isClip() const { return producer() && producer()->is_valid() && !isPlaylist() && !isMultitrack(); } bool Controller::isSeekableClip() { return isClip() && isSeekable(); } bool Controller::isPlaylist() const { return m_producer && m_producer->is_valid() && !m_producer->get_int(kShotcutVirtualClip) && (m_producer->get_int("_original_type") == mlt_service_playlist_type || resource() == "<playlist>"); } bool Controller::isMultitrack() const { return m_producer && m_producer->is_valid() && !m_producer->get_int(kShotcutVirtualClip) && (m_producer->get_int("_original_type") == mlt_service_tractor_type || resource() == "<tractor>") && (m_producer->get(kShotcutXmlProperty)); } bool Controller::isImageProducer(Service *service) const { if (service && service->is_valid()) { QString serviceName = service->get("mlt_service"); return (serviceName == "pixbuf" || serviceName == "qimage"); } return false; } bool Controller::isFileProducer(Service *service) const { if (service && service->is_valid()) { QString serviceName = service->get("mlt_service"); return (serviceName == "pixbuf" || serviceName == "qimage" || serviceName == "glaxnimate" || serviceName.startsWith("avformat") || serviceName.startsWith("timewarp")); } return false; } void Controller::rewind(bool forceChangeDirection) { if (!m_producer || !m_producer->is_valid()) return; // Starting the consumer when producer at its end fails. So, first seek to // frame before last. if (m_producer->position() >= m_producer->get_length() - 1) m_producer->seek(m_producer->get_length() - 2); double speed = m_producer->get_speed(); if (speed == 0.0) { play(-1.0); } else { stopJack(); if (forceChangeDirection && speed > 0.0) speed = -0.5; if (speed < 0.0) m_producer->set_speed(speed * 2.0); else m_producer->set_speed(::floor(speed * 0.5)); if (m_consumer && m_consumer->is_valid()) m_consumer->purge(); } } void Controller::fastForward(bool forceChangeDirection) { if (!m_producer || !m_producer->is_valid()) return; double speed = m_producer->get_speed(); if (speed == 0.0) { play(1.0); } else { stopJack(); if (forceChangeDirection && speed < 0.0) speed = 0.5; if (speed > 0.0) m_producer->set_speed(speed * 2.0); else m_producer->set_speed(::ceil(speed * 0.5)); if (m_consumer && m_consumer->is_valid()) m_consumer->purge(); } } void Controller::previous(int currentPosition) { if (isMultitrack()) return; if (currentPosition > m_producer->get_out()) seek(MLT.producer()->get_out()); else if (currentPosition <= m_producer->get_in()) seek(0); else seek(m_producer->get_in()); } void Controller::next(int currentPosition) { if (isMultitrack()) return; if (currentPosition < m_producer->get_in()) seek(m_producer->get_in()); else if (currentPosition >= m_producer->get_out()) seek(m_producer->get_length() - 1); else seek(m_producer->get_out()); } void Controller::setIn(int in) { if (m_producer && m_producer->is_valid()) { int delta = in - m_producer->get_in(); if (!delta) { return; } adjustClipFilters(*m_producer, m_producer->get_in(), m_producer->get_out(), delta, 0, delta); m_producer->set("in", in); Controller::refreshConsumer(); } } void Controller::setOut(int out) { if (m_producer && m_producer->is_valid()) { int delta = out - m_producer->get_out(); if (!delta) { return; } adjustClipFilters(*m_producer, m_producer->get_in(), m_producer->get_out(), 0, -delta, 0); m_producer->set("out", out); Controller::refreshConsumer(); } } class FixLengthPropertiesParser : public Mlt::Parser { public: FixLengthPropertiesParser() : Mlt::Parser() {} int on_start_filter(Mlt::Filter *) { return 0; } int on_start_producer(Mlt::Producer *) { return 0; } int on_end_producer(Mlt::Producer *s) { if (!::strchr(s->get("length"), ':')) s->set("length", s->frames_to_time(s->get_int("length"), mlt_time_clock)); return 0; } int on_start_playlist(Mlt::Playlist *) { return 0; } int on_end_playlist(Mlt::Playlist *) { return 0; } int on_start_tractor(Mlt::Tractor *) { return 0; } int on_end_tractor(Mlt::Tractor *) { return 0; } int on_start_multitrack(Mlt::Multitrack *) { return 0; } int on_end_multitrack(Mlt::Multitrack *) { return 0; } int on_start_track() { return 0; } int on_end_track() { return 0; } int on_end_filter(Mlt::Filter *) { return 0; } int on_start_transition(Mlt::Transition *) { return 0; } int on_end_transition(Mlt::Transition *) { return 0; } int on_start_chain(Mlt::Chain *) { return 0; } int on_end_chain(Mlt::Chain *s) { if (!::strchr(s->get("length"), ':')) s->set("length", s->frames_to_time(s->get_int("length"), mlt_time_clock)); return 0; } int on_start_link(Mlt::Link *) { return 0; } int on_end_link(Mlt::Link *) { return 0; } }; void Controller::fixLengthProperties(Service &service) { FixLengthPropertiesParser parser; parser.start(service); } void Controller::restart(const QString &xml) { if (!m_consumer || !m_consumer->is_valid() || !m_producer || !m_producer->is_valid()) return; const char *position = m_consumer->frames_to_time(m_consumer->position()); double speed = m_producer->get_speed(); QString loadXml = xml; if (loadXml.isEmpty()) loadXml = XML(); stop(); if (!setProducer(new Mlt::Producer(profile(), "xml-string", loadXml.toUtf8().constData()))) { if (m_producer && m_producer->is_valid()) m_producer->seek(position); play(speed); } } void Controller::resetURL() { m_url = QString(); } QImage Controller::image(Mlt::Frame *frame, int width, int height) { QImage result; if (frame && frame->is_valid()) { if (width > 0 && height > 0) { frame->set("consumer.rescale", "bilinear"); frame->set("consumer.deinterlacer", "onefield"); frame->set("consumer.top_field_first", -1); } mlt_image_format format = mlt_image_rgba; const uchar *image = frame->get_image(format, width, height); if (image) { QImage temp(width, height, QImage::Format_ARGB32); memcpy(temp.scanLine(0), image, size_t(width * height * 4)); result = temp.rgbSwapped(); } } else { result = QImage(width, height, QImage::Format_ARGB32); result.fill(QColor(Qt::red).rgb()); } return result; } QImage Controller::image(Producer &producer, int frameNumber, int width, int height) { QImage result; if (frameNumber > producer.get_length() - kThumbnailOutSeekFactor) { producer.seek(frameNumber - kThumbnailOutSeekFactor - 1); for (int i = 0; i < kThumbnailOutSeekFactor; ++i) { QScopedPointer<Mlt::Frame> frame(producer.get_frame()); QImage temp = image(frame.data(), width, height); if (!temp.isNull()) result = temp; } } else { producer.seek(frameNumber); QScopedPointer<Mlt::Frame> frame(producer.get_frame()); result = image(frame.data(), width, height); } return result; } void Controller::updateAvformatCaching(int trackCount) { int i = QThreadPool::globalInstance()->maxThreadCount() + trackCount * 2; mlt_service_cache_set_size(nullptr, "producer_avformat", qMax(4, i)); } bool Controller::isAudioFilter(const QString &name) { QScopedPointer<Properties> metadata(m_repo->metadata(mlt_service_filter_type, name.toLatin1().constData())); if (metadata->is_valid()) { Properties tags(metadata->get_data("tags")); if (tags.is_valid()) { for (int j = 0; j < tags.count(); ++j) { if (!qstricmp(tags.get(j), "Audio")) return true; } } } return false; } int Controller::realTime() const { int realtime = 1; if (!Settings.playerRealtime()) { if (Settings.playerGPU()) { return -1; } #if QT_POINTER_SIZE == 4 // Limit to 1 rendering thread on 32-bit process to reduce memory usage. int threadCount = 1; #else int threadCount = QThread::idealThreadCount(); #endif threadCount = threadCount > 2 ? qMin(threadCount - 1, 4) : 1; realtime = -threadCount; } return realtime; } void Controller::setImageDurationFromDefault(Service *service) const { if (service && service->is_valid()) { if (isImageProducer(service) && !service->get_int("shotcut_sequence")) { service->set("ttl", 1); service->set("length", service->frames_to_time(qRound(m_profile.fps() * kMaxImageDurationSecs), mlt_time_clock)); service->set("out", qRound(m_profile.fps() * Settings.imageDuration()) - 1); } } } void Controller::setDurationFromDefault(Producer *producer) const { if (producer && producer->is_valid()) { int out = qRound(m_profile.fps() * Settings.imageDuration()) - 1; if (out >= producer->get_length()) producer->set("length", producer->frames_to_time(out + 1, mlt_time_clock)); producer->set("length", producer->frames_to_time(qRound(m_profile.fps() * kMaxImageDurationSecs), mlt_time_clock)); producer->set("out", out); } } void Controller::lockCreationTime(Producer *producer) const { // Apply the creation_time property on the producer so that it will persist // through XML serialization/deserialization. if (producer && producer->is_valid() && isFileProducer(producer)) { int64_t creation_time = producer->get_creation_time(); if (creation_time != 0) { producer->set_creation_time(creation_time); } } } Producer *Controller::setupNewProducer(Producer *newProducer) const { // Call this function before adding a new producer to Shotcut so that // It will be configured correctly. The returned producer must be deleted. QString serviceName = newProducer->get("mlt_service"); if (serviceName == "avformat") { // Convert avformat to avformat-novalidate so that XML loads faster. newProducer->set("mlt_service", "avformat-novalidate"); } setImageDurationFromDefault(newProducer); lockCreationTime(newProducer); newProducer->get_length_time(mlt_time_clock); if (serviceName.startsWith("avformat")) { newProducer->set("mute_on_pause", 0); // Encapsulate in a chain to enable timing effects if (newProducer->type() != mlt_service_chain_type) { Mlt::Chain *chain = new Mlt::Chain(MLT.profile()); chain->set_source(*newProducer); chain->get_length_time(mlt_time_clock); chain->attach_normalizers(); // Move all non-loader filters to the chain in case this was a clip-only project. int i = 0; QScopedPointer<Mlt::Filter> filter(newProducer->filter(i)); while (filter && filter->is_valid()) { if (!filter->get_int("_loader") && !filter->get_int(kShotcutHiddenProperty)) { newProducer->detach(*filter); chain->Service::attach(*filter); } else { ++i; } filter.reset(newProducer->filter(i)); } return chain; } } return new Mlt::Producer(newProducer); } QUuid Controller::uuid(Mlt::Properties &properties) const { return QUuid(properties.get(kUuidProperty)); } void Controller::setUuid(Mlt::Properties &properties, QUuid uid) const { properties.set(kUuidProperty, (uid.toByteArray() + '\n').data()); } QUuid Controller::ensureHasUuid(Mlt::Properties &properties) const { if (properties.get(kUuidProperty)) { return uuid(properties); } QUuid newUid = QUuid::createUuid(); setUuid(properties, newUid); return newUid; } static int indexOfFirstNonGpu(Producer &toProducer) { for (int i = 0; i < toProducer.filter_count(); i++) { QScopedPointer<Mlt::Filter> filter(toProducer.filter(i)); if (filter && filter->is_valid() && !filter->get_int("_loader") && !filter->get_int(kShotcutHiddenProperty) && filter->get("mlt_service")) { if (!QString::fromLatin1(filter->get("mlt_service")).startsWith("movit.")) return i; } } Mlt::Chain toChain(toProducer); for (int i = 0; i < toChain.link_count(); i++) { QScopedPointer<Mlt::Link> link(toChain.link(i)); if (link && link->is_valid() && !link->get_int("_loader") && !link->get_int(kShotcutHiddenProperty) && link->get("mlt_service")) { if (!QString::fromLatin1(link->get("mlt_service")).startsWith("movit.")) return i; } } return -1; } void Controller::copyFilters(Producer &fromProducer, Producer &toProducer, bool fromClipboard, bool includeDisabled) { int in = fromProducer.get(kFilterInProperty) ? fromProducer.get_int(kFilterInProperty) : fromProducer.get_in(); int out = fromProducer.get(kFilterOutProperty) ? fromProducer.get_int( kFilterOutProperty) : fromProducer.get_out(); int count = fromProducer.filter_count(); // Get the index of the first non-GPU filter or link in toProducer int firstNonGpuService = fromClipboard ? indexOfFirstNonGpu(toProducer) : -1; for (int i = 0; i < count; i++) { QScopedPointer<Mlt::Filter> fromFilter(fromProducer.filter(i)); if (fromFilter && fromFilter->is_valid() && !fromFilter->get_int("_loader") && !fromFilter->get_int(kShotcutHiddenProperty) && fromFilter->get("mlt_service") && (includeDisabled || !fromFilter->get_int("disable"))) { // Determine if filter can be added auto metadata = MAIN.filterController()->metadataForService(fromFilter.data()); if (metadata) { if (metadata->isClipOnly() && MLT.isTrackProducer(toProducer)) { continue; } if (!metadata->allowMultiple()) { std::unique_ptr<Mlt::Filter> existing(getFilter(metadata->uniqueId(), &toProducer)); if (existing && !existing->get_int("_loader")) { continue; } } } // Add the filter to the target producer Mlt::Filter toFilter(MLT.profile(), fromFilter->get("mlt_service")); if (toFilter.is_valid()) { toFilter.inherit(*fromFilter); // Force any 2-pass filters to require re-analysis toFilter.clear("results"); toProducer.attach(toFilter); if (firstNonGpuService >= 0 && metadata->needsGPU()) toProducer.move_filter(toProducer.filter_count(), firstNonGpuService++); if (!fromClipboard) { toFilter.set(kFilterInProperty, fromFilter->get_in() - in); if (fromFilter->get_out() != out) { toFilter.set(kFilterOutProperty, fromFilter->get_out() - fromFilter->get_in()); } } } } } if (fromProducer.type() == mlt_service_chain_type && toProducer.type() == mlt_service_chain_type) { Mlt::Chain fromChain(fromProducer); Mlt::Chain toChain(toProducer); count = fromChain.link_count(); for (int i = 0; i < count; i++) { QScopedPointer<Mlt::Link> fromLink(fromChain.link(i)); if (fromLink && fromLink->is_valid() && fromLink->get("mlt_service") && !fromLink->get_int("_loader")) { Mlt::Link toLink(fromLink->get("mlt_service")); if (toLink.is_valid()) { toLink.inherit(*fromLink); toChain.attach(toLink); if (firstNonGpuService >= 0 && QString::fromLatin1(fromLink->get("mlt_service")).startsWith("movit.")) toChain.move_link(toChain.link_count(), firstNonGpuService++); } } } } } void Controller::copyFilters(Mlt::Producer *producer) { if (producer && producer->is_valid()) { initFiltersClipboard(); copyFilters(*producer, *m_filtersClipboard, false, false); } else if (m_producer && m_producer->is_valid()) { initFiltersClipboard(); copyFilters(*m_producer, *m_filtersClipboard, false, false); } } void Controller::pasteFilters(Mlt::Producer *producer, Producer *fromProducer) { Mlt::Producer *targetProducer = (producer && producer->is_valid()) ? producer : (m_producer && m_producer->is_valid()) ? m_producer.data() : nullptr; if (targetProducer) { int j = targetProducer->filter_count(); if (fromProducer && fromProducer->is_valid()) { copyFilters(*fromProducer, *targetProducer, true); } else if (hasFiltersOnClipboard()) { copyFilters(*m_filtersClipboard, *targetProducer, true); } adjustFilters(*targetProducer, j); } } void Controller::adjustFilters(Producer &producer, int index) { bool changed = false; int in = producer.get(kFilterInProperty) ? producer.get_int(kFilterInProperty) : producer.get_in(); int out = producer.get(kFilterOutProperty) ? producer.get_int(kFilterOutProperty) : producer.get_out(); int n = producer.filter_count(); for (; index < n; index++) { QScopedPointer<Mlt::Filter> filter(producer.filter(index)); if (filter && filter->is_valid()) { QString filterName = filter->get(kShotcutFilterProperty); if (filterName.startsWith("fadeIn") && !filter->get(kShotcutAnimInProperty)) { // Convert legacy fadeIn filters. filter->set(kShotcutAnimInProperty, filter->get_length()); } else if (filterName.startsWith("fadeOut") && !filter->get(kShotcutAnimOutProperty)) { // Convert legacy fadeIn filters. filter->set(kShotcutAnimOutProperty, filter->get_length()); } if (!filter->get_int("_loader") && !filter->get_int(kShotcutHiddenProperty)) { int filterIn = in; int filterOut = out; if (filter->get(kFilterInProperty)) filterIn += filter->get_int(kFilterInProperty); if (filter->get(kFilterOutProperty)) filterOut = qMin(filterIn + filter->get_int(kFilterOutProperty), out); filter->set_in_and_out(filterIn, filterOut); changed = true; if (filterName == "fadeOutBrightness") { const char *key = filter->get_int("alpha") != 1 ? "alpha" : "level"; filter->clear(key); filter->anim_set(key, 1, filter->get_length() - filter->get_int(kShotcutAnimOutProperty)); filter->anim_set(key, 0, filter->get_length() - 1); } else if (filterName == "fadeOutMovit") { filter->clear("opacity"); filter->anim_set("opacity", 1, filter->get_length() - filter->get_int(kShotcutAnimOutProperty), 0, mlt_keyframe_smooth); filter->anim_set("opacity", 0, filter->get_length() - 1); } else if (filterName == "fadeOutVolume") { filter->clear("level"); filter->anim_set("level", 0, filter->get_length() - filter->get_int(kShotcutAnimOutProperty)); filter->anim_set("level", -60, filter->get_length() - 1); } else if (filter->get_int(kShotcutAnimOutProperty) > 0) { // Update simple keyframes. QmlMetadata *meta = MAIN.filterController()->metadataForService(filter.data()); if (meta && meta->keyframes()) { foreach (QString name, meta->keyframes()->simpleProperties()) { if (!filter->get_animation(name.toUtf8().constData())) { // Cause a string property to be interpreted as animated value. if (meta->keyframes()->parameter(name)->isColor()) filter->anim_get_color(name.toUtf8().constData(), 0, filter->get_length()); else filter->anim_get_double(name.toUtf8().constData(), 0, filter->get_length()); } Mlt::Animation animation = filter->get_animation(name.toUtf8().constData()); if (animation.is_valid()) { int n = animation.key_count(); if (n > 1) { animation.set_length(filter->get_length()); animation.key_set_frame(n - 2, filter->get_length() - filter->get_int(kShotcutAnimOutProperty)); animation.key_set_frame(n - 1, filter->get_length() - 1); } } } } } } } } if (changed) MLT.refreshConsumer(); } static void shiftKeyframes(Mlt::Service *service, QmlMetadata *meta, int delta) { if (!meta || !meta->keyframes() || meta->keyframes()->parameterCount() < 1) { return; } QmlKeyframesMetadata *keyMeta = meta->keyframes(); for (int parameterIndex = 0; parameterIndex < keyMeta->parameterCount(); parameterIndex++) { QmlKeyframesParameter *paramMeta = keyMeta->parameter(parameterIndex); QString name = paramMeta->property(); Mlt::Animation animation = service->get_animation(qUtf8Printable(name)); if (animation.is_valid()) { // Keyframes are not allowed to have negative positions because // there is no way for the user to interact with them. // Handle keyframes that will become negative by deleting them. if (animation.key_get_frame(0) < delta) { // Create a new keyframe at position that will become 0 based on interpolated value int previous = 0; animation.previous_key(delta, previous); mlt_keyframe_type existingType = animation.keyframe_type(previous); if (paramMeta->isRectangle()) { auto value = service->anim_get_rect(qUtf8Printable(name), delta); service->anim_set(qUtf8Printable(name), value, delta, 0, existingType); } else if (paramMeta->isColor()) { auto value = service->anim_get_color(qUtf8Printable(name), delta); service->anim_set(qUtf8Printable(name), value, delta, 0, existingType); } else { double value = service->anim_get_double(qUtf8Printable(name), delta); service->anim_set(qUtf8Printable(name), value, delta, 0, existingType); foreach (QString gangName, paramMeta->gangedProperties()) { Mlt::Animation gangAnim = service->get_animation(qUtf8Printable(gangName)); double gangValue = service->anim_get_double(qUtf8Printable(gangName), delta); service->anim_set(qUtf8Printable(gangName), gangValue, delta, existingType); } } // Remove all keyframes that will be negative position int count = animation.key_count(); for (int keyframeIndex = 0; keyframeIndex < count;) { int frame = animation.key_get_frame(keyframeIndex); if (frame < delta) { animation.remove(frame); animation.interpolate(); --count; } else { break; } } foreach (QString gangName, paramMeta->gangedProperties()) { Mlt::Animation gangAnim = service->get_animation(qUtf8Printable(gangName)); int gangKeyCount = gangAnim.key_count(); for (int keyframeIndex = 0; keyframeIndex < gangKeyCount;) { int frame = gangAnim.key_get_frame(keyframeIndex); if (frame < delta) { gangAnim.remove(frame); gangAnim.interpolate(); gangKeyCount -= 1; } else { break; } } } } // Shift all the keyframes proportional to the delta animation.shift_frames(-delta); foreach (QString gangName, paramMeta->gangedProperties()) { Mlt::Animation gangAnim = service->get_animation(qUtf8Printable(gangName)); if (gangAnim.is_valid()) gangAnim.shift_frames(-delta); } } } } void Controller::adjustFilter(Mlt::Filter *filter, int in, int out, int inDelta, int outDelta, int keyframeDelta) { if (!filter || !filter->is_valid()) { return; } QString filterName = filter->get(kShotcutFilterProperty); QmlMetadata *meta = MAIN.filterController()->metadataForService(filter); if ((inDelta || outDelta) && meta && meta->mlt_service().startsWith("vidstab")) { filter->clear("results"); } if (inDelta) { if (in + inDelta < 0) { inDelta = -in; } if (keyframeDelta && filter->get_int(kShotcutAnimInProperty) == filter->get_int(kShotcutAnimOutProperty)) { // Shift all keyframes proportional to the in delta if they are not simple keyframes shiftKeyframes(filter, meta, keyframeDelta); } if (filterName.startsWith("fadeIn")) { if (!filter->get(kShotcutAnimInProperty)) { // Convert legacy fadeIn filters. filter->set(kShotcutAnimInProperty, filter->get_length()); } filter->set_in_and_out(in + inDelta, filter->get_out()); emit MAIN.serviceInChanged(inDelta, filter); } else if (filterName.startsWith("fadeOut")) { if (!filter->get(kShotcutAnimOutProperty)) { // Convert legacy fadeOut filters. filter->set(kShotcutAnimOutProperty, filter->get_length()); } filter->set_in_and_out(in + inDelta, filter->get_out()); if (filterName == "fadeOutBrightness") { const char *key = filter->get_int("alpha") != 1 ? "alpha" : "level"; filter->clear(key); filter->anim_set(key, 1, filter->get_length() - filter->get_int(kShotcutAnimOutProperty)); filter->anim_set(key, 0, filter->get_length() - 1); } else if (filterName == "fadeOutMovit") { filter->clear("opacity"); filter->anim_set("opacity", 1, filter->get_length() - filter->get_int(kShotcutAnimOutProperty), 0, mlt_keyframe_smooth); filter->anim_set("opacity", 0, filter->get_length() - 1); } else if (filterName == "fadeOutVolume") { filter->clear("level"); filter->anim_set("level", 0, filter->get_length() - filter->get_int(kShotcutAnimOutProperty)); filter->anim_set("level", -60, filter->get_length() - 1); } emit MAIN.serviceInChanged(inDelta, filter); } else if (!filter->get_int("_loader") && !filter->get_int(kShotcutHiddenProperty) && filter->get_in() <= in) { filter->set_in_and_out(in + inDelta, filter->get_out()); emit MAIN.serviceInChanged(inDelta, filter); } } if (outDelta) { if (filterName.startsWith("fadeOut")) { if (!filter->get(kShotcutAnimOutProperty)) { // Convert legacy fadeOut filters. filter->set(kShotcutAnimOutProperty, filter->get_length()); } filter->set_in_and_out(filter->get_in(), out - outDelta); if (filterName == "fadeOutBrightness") { const char *key = filter->get_int("alpha") != 1 ? "alpha" : "level"; filter->clear(key); filter->anim_set(key, 1, filter->get_length() - filter->get_int(kShotcutAnimOutProperty)); filter->anim_set(key, 0, filter->get_length() - 1); } else if (filterName == "fadeOutMovit") { filter->clear("opacity"); filter->anim_set("opacity", 1, filter->get_length() - filter->get_int(kShotcutAnimOutProperty), 0, mlt_keyframe_smooth); filter->anim_set("opacity", 0, filter->get_length() - 1); } else if (filterName == "fadeOutVolume") { filter->clear("level"); filter->anim_set("level", 0, filter->get_length() - filter->get_int(kShotcutAnimOutProperty)); filter->anim_set("level", -60, filter->get_length() - 1); } emit MAIN.serviceOutChanged(outDelta, filter); } else if (!filter->get_int("_loader") && !filter->get_int(kShotcutHiddenProperty) && filter->get_out() >= out) { filter->set_in_and_out(filter->get_in(), out - outDelta); emit MAIN.serviceOutChanged(outDelta, filter); // Update simple keyframes if (filter->get_int(kShotcutAnimOutProperty) && meta && meta->keyframes()) { foreach (QString name, meta->keyframes()->simpleProperties()) { if (!filter->get_animation(name.toUtf8().constData())) { // Cause a string property to be interpreted as animated value. if (meta->keyframes()->parameter(name)->isColor()) filter->anim_get_color(name.toUtf8().constData(), 0, filter->get_length()); else filter->anim_get_double(name.toUtf8().constData(), 0, filter->get_length()); } Mlt::Animation animation = filter->get_animation(name.toUtf8().constData()); if (animation.is_valid()) { int n = animation.key_count(); if (n > 1) { animation.set_length(filter->get_length()); animation.key_set_frame(n - 2, filter->get_length() - filter->get_int(kShotcutAnimOutProperty)); animation.key_set_frame(n - 1, filter->get_length() - 1); } } } } } } } void Controller::adjustClipFilters(Mlt::Producer &producer, int in, int out, int inDelta, int outDelta, int keyframeDelta) { for (int j = 0; j < producer.filter_count(); j++) { QScopedPointer<Mlt::Filter> filter(producer.filter(j)); adjustFilter(filter.data(), in, out, inDelta, outDelta, keyframeDelta); } // Adjust link in/out if (producer.type() == mlt_service_chain_type) { Mlt::Chain chain(producer); int link_count = chain.link_count(); for (int j = 0; j < link_count; j++) { QScopedPointer<Mlt::Link> link(chain.link(j)); QmlMetadata *meta = MAIN.filterController()->metadataForService(link.data()); if (link && link->is_valid()) { if (keyframeDelta) { shiftKeyframes(link.data(), meta, keyframeDelta); } if (link->get_out() >= out) { link->set_in_and_out(link->get_in(), out - outDelta); emit MAIN.serviceOutChanged(outDelta, link.data()); } if (link->get_in() <= in) { link->set_in_and_out(in + inDelta, link->get_out()); emit MAIN.serviceInChanged(inDelta, link.data()); } } } } } void Controller::setSavedProducer(Mlt::Producer *producer) { m_savedProducer.reset(new Mlt::Producer(producer)); } Filter *Controller::getFilter(const QString &name, Service *service) { for (int i = 0; i < service->filter_count(); i++) { Mlt::Filter *filter = service->filter(i); if (filter) { auto filterName = QString::fromUtf8(filter->get(kShotcutFilterProperty)); if (filterName.isEmpty()) { filterName = QString::fromUtf8(filter->get("mlt_service")); } if (name == filterName) return filter; delete filter; } } return nullptr; } void Controller::setProjectFolder(const QString &folderName) { m_projectFolder = folderName; if (!m_projectFolder.isEmpty()) Settings.setSavePath(m_projectFolder); LOG_DEBUG() << "project folder" << m_projectFolder; } QChar Controller::decimalPoint() { QChar result('.'); Mlt::Producer producer(profile(), "color", "black"); if (producer.is_valid()) { const char *timeString = producer.get_length_time(mlt_time_clock); if (qstrlen(timeString) >= 8) // HH:MM:SS.ms result = timeString[8]; } return result; } void Controller::resetLocale() { ::qputenv(MLT_LC_NAME, "C"); ::setlocale(MLT_LC_CATEGORY, "C"); LOG_INFO() << "decimal point ."; } int Controller::filterIn(Playlist &playlist, int clipIndex) { int result = -1; QScopedPointer<Mlt::ClipInfo> info(playlist.clip_info(clipIndex)); if (info) { QScopedPointer<Mlt::ClipInfo> info2(playlist.clip_info(clipIndex - 1)); if (info2 && info2->producer && info2->producer->is_valid() && info2->producer->get(kShotcutTransitionProperty)) { // Factor in a transition left of the clip. result = info->frame_in - info2->frame_count; } else { result = info->frame_in; } } return result; } int Controller::filterOut(Playlist &playlist, int clipIndex) { int result = -1; QScopedPointer<Mlt::ClipInfo> info(playlist.clip_info(clipIndex)); if (info) { QScopedPointer<Mlt::ClipInfo> info2(playlist.clip_info(clipIndex + 1)); if (info2 && info2->producer && info2->producer->is_valid() && info2->producer->get(kShotcutTransitionProperty)) { // Factor in a transition right of the clip. result = info->frame_out + info2->frame_count; } else { result = info->frame_out; } } return result; } void Controller::setPreviewScale(int scale) { auto width = m_profile.width(); auto height = m_profile.height(); if (scale > 0) { height = MIN(scale, m_profile.height()); width = (height == m_profile.height()) ? m_profile.width() : Util::coerceMultiple(height * m_profile.display_aspect_num() / m_profile.display_aspect_den() * m_profile.sample_aspect_den() / m_profile.sample_aspect_num()); } LOG_DEBUG() << width << "x" << height; m_previewProfile.set_width(width); m_previewProfile.set_height(height); if (m_consumer) { m_consumer->set("width", width); m_consumer->set("height", height); } } void Controller::updatePreviewProfile() { m_previewProfile.set_colorspace(m_profile.colorspace()); m_previewProfile.set_frame_rate(m_profile.frame_rate_num(), m_profile.frame_rate_den()); m_previewProfile.set_width(Util::coerceMultiple(m_profile.width())); m_previewProfile.set_height(Util::coerceMultiple(m_profile.height())); m_previewProfile.set_progressive(m_profile.progressive()); m_previewProfile.set_sample_aspect(m_profile.sample_aspect_num(), m_profile.sample_aspect_den()); m_previewProfile.set_display_aspect(m_profile.display_aspect_num(), m_profile.display_aspect_den()); m_previewProfile.set_explicit(true); } void Controller::purgeMemoryPool() { ::mlt_pool_purge(); } bool Controller::fullRange(Producer &producer) { bool full = !qstrcmp(producer.get("meta.media.color_range"), "full"); for (int i = 0; !full && i < producer.get_int("meta.media.nb_streams"); i++) { QString key = QStringLiteral("meta.media.%1.stream.type").arg(i); QString streamType(producer.get(key.toLatin1().constData())); if (streamType == "video") { if (i == producer.get_int("video_index")) { key = QStringLiteral("meta.media.%1.codec.pix_fmt").arg(i); QString pix_fmt = QString::fromLatin1(producer.get(key.toLatin1().constData())); if (pix_fmt.startsWith("yuvj")) { full = true; } else if (pix_fmt.contains("gbr") || pix_fmt.contains("rgb")) { full = true; } } } } return full; } bool Controller::isTrackProducer(Producer &producer) { mlt_service_type service_type = producer.type(); return service_type == mlt_service_playlist_type || (service_type == mlt_service_tractor_type && producer.get_int(kShotcutXmlProperty)); } int Controller::checkFile(const QString &path) { int error = 0; if (path.endsWith(".json") || path.endsWith(".rawr") || path.endsWith(".lottie") || path.endsWith(".riv") || path.endsWith(".tgs") || path.endsWith(".avd") || path.endsWith(".aep")) { QString shotcutPath = qApp->applicationDirPath(); #if defined(Q_OS_UNIX) && !defined(Q_OS_MAC) QFileInfo meltPath(shotcutPath, "melt-7"); #else QFileInfo meltPath(shotcutPath, "melt"); #endif QStringList args; args << "-quiet" << "-consumer" << "null" << "real_time=0" << "out=0" << "terminate_on_pause=1" << "glaxnimate:" + path; LOG_DEBUG() << meltPath.absoluteFilePath() + " " + args.join(' '); error = QProcess::execute(meltPath.absoluteFilePath(), args); } return error; } bool Controller::blockRefresh(bool block) { m_blockRefresh = block; return m_blockRefresh; } void TransportControl::play(double speed) { MLT.play(speed); } void TransportControl::pause() { MLT.pause(); } void TransportControl::stop() { MLT.stop(); } void TransportControl::seek(int position) { MLT.seek(position); } void TransportControl::rewind(bool forceChangeDirection) { MLT.rewind(forceChangeDirection); } void TransportControl::fastForward(bool forceChangeDirection) { MLT.fastForward(forceChangeDirection); } void TransportControl::previous(int currentPosition) { MLT.previous(currentPosition); } void TransportControl::next(int currentPosition) { MLT.next(currentPosition); } void TransportControl::setIn(int in) { MLT.setIn(in); } void TransportControl::setOut(int out) { MLT.setOut(out); } } // namespace
63,402
C++
.cpp
1,621
29.926589
132
0.579862
mltframework/shotcut
10,796
1,118
50
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
13,114
autosavefile.cpp
mltframework_shotcut/src/autosavefile.cpp
/* * Copyright (c) 2011-2016 Meltytech, LLC * Author: Dan Dennedy <dan@dennedy.org> * Loosely based on ideas from KAutoSaveFile by Jacob R Rideout <kde@jacobrideout.net> * and Kdenlive by Jean-Baptiste Mardelle. * * 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 "autosavefile.h" #include "settings.h" #include <QtCore/QDir> #include <QtCore/QCryptographicHash> static const QLatin1String subdir("/autosave"); static const QLatin1String extension(".mlt"); static QString hashName(const QString &name) { return QString::fromLatin1(QCryptographicHash::hash(name.toUtf8(), QCryptographicHash::Md5).toHex()); } AutoSaveFile::AutoSaveFile(const QString &filename, QObject *parent) : QFile(parent) , m_managedFileNameChanged(false) { changeManagedFile(filename); } AutoSaveFile::~AutoSaveFile() { if (!fileName().isEmpty()) remove(); } void AutoSaveFile::changeManagedFile(const QString &filename) { if (!fileName().isEmpty()) remove(); m_managedFile = filename; m_managedFileNameChanged = true; } bool AutoSaveFile::open(OpenMode openmode) { QString tempFile; if (m_managedFileNameChanged) { QString staleFilesDir = path(); if (!QDir().mkpath(staleFilesDir)) { return false; } tempFile = staleFilesDir + QChar::fromLatin1('/') + hashName(m_managedFile) + extension; } else { tempFile = fileName(); } m_managedFileNameChanged = false; setFileName(tempFile); return QFile::open(openmode); } AutoSaveFile *AutoSaveFile::getFile(const QString &filename) { AutoSaveFile *result = 0; QDir appDir(path()); QFileInfo info(appDir.absolutePath(), hashName(filename) + extension); if (info.exists()) { result = new AutoSaveFile(filename); result->setFileName(info.filePath()); result->m_managedFileNameChanged = false; } return result; } QString AutoSaveFile::path() { return Settings.appDataLocation() + subdir; }
2,664
C++
.cpp
80
28.95
96
0.707782
mltframework/shotcut
10,796
1,118
50
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
13,115
mainwindow.cpp
mltframework_shotcut/src/mainwindow.cpp
/* * Copyright (c) 2011-2024 Meltytech, LLC * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "mainwindow.h" #include "ui_mainwindow.h" #include "actions.h" #include "openotherdialog.h" #include "player.h" #include "defaultlayouts.h" #include "widgets/alsawidget.h" #include "widgets/colorbarswidget.h" #include "widgets/colorproducerwidget.h" #include "widgets/countproducerwidget.h" #include "widgets/decklinkproducerwidget.h" #include "widgets/directshowvideowidget.h" #include "widgets/glaxnimateproducerwidget.h" #include "widgets/isingwidget.h" #include "widgets/jackproducerwidget.h" #include "widgets/toneproducerwidget.h" #include "widgets/lissajouswidget.h" #include "widgets/noisewidget.h" #include "widgets/plasmawidget.h" #include "widgets/pulseaudiowidget.h" #include "widgets/video4linuxwidget.h" #include "widgets/x11grabwidget.h" #include "widgets/avformatproducerwidget.h" #include "widgets/imageproducerwidget.h" #include "widgets/blipproducerwidget.h" #include "widgets/newprojectfolder.h" #include "docks/recentdock.h" #include "docks/encodedock.h" #include "docks/jobsdock.h" #include "jobqueue.h" #include "docks/playlistdock.h" #include "videowidget.h" #include "controllers/filtercontroller.h" #include "controllers/scopecontroller.h" #include "docks/filtersdock.h" #include "dialogs/actionsdialog.h" #include "dialogs/customprofiledialog.h" #include "dialogs/resourcedialog.h" #include "dialogs/saveimagedialog.h" #include "settings.h" #include "database.h" #include "docks/timelinedock.h" #include "widgets/lumamixtransition.h" #include "qmltypes/qmlutilities.h" #include "qmltypes/qmlapplication.h" #include "autosavefile.h" #include "commands/playlistcommands.h" #include "shotcut_mlt_properties.h" #include "widgets/avfoundationproducerwidget.h" #include "dialogs/textviewerdialog.h" #include "widgets/gdigrabwidget.h" #include "models/audiolevelstask.h" #include "widgets/trackpropertieswidget.h" #include "widgets/timelinepropertieswidget.h" #include "dialogs/unlinkedfilesdialog.h" #include "docks/keyframesdock.h" #include "docks/markersdock.h" #include "docks/notesdock.h" #include "docks/subtitlesdock.h" #include "util.h" #include "models/keyframesmodel.h" #include "dialogs/listselectiondialog.h" #include "widgets/textproducerwidget.h" #include "qmltypes/qmlprofile.h" #include "dialogs/longuitask.h" #include "dialogs/systemsyncdialog.h" #include "proxymanager.h" #include "transcoder.h" #include "models/motiontrackermodel.h" #if defined(Q_OS_WIN) && (QT_VERSION < QT_VERSION_CHECK(6, 0, 0)) #include "windowstools.h" #endif #include <QtWidgets> #include <Logger.h> #include <QThreadPool> #include <QtConcurrent/QtConcurrentRun> #include <QMutexLocker> #include <QQuickItem> #include <QtNetwork> #include <QJsonDocument> #include <QJSEngine> #include <QDirIterator> #include <QQuickWindow> #include <QVersionNumber> #include <QApplication> #include <QClipboard> #include <QImageReader> #include <algorithm> #define SHOTCUT_THEME static bool eventDebugCallback(void **data) { QEvent *event = reinterpret_cast<QEvent *>(data[1]); if (event->type() == QEvent::KeyPress || event->type() == QEvent::KeyRelease) { QObject *receiver = reinterpret_cast<QObject *>(data[0]); LOG_DEBUG() << event << "->" << receiver; } else if (event->type() == QEvent::MouseButtonPress || event->type() == QEvent::MouseButtonRelease) { QObject *receiver = reinterpret_cast<QObject *>(data[0]); LOG_DEBUG() << event << "->" << receiver; } return false; } static const int AUTOSAVE_TIMEOUT_MS = 60000; static const char *kReservedLayoutPrefix = "__%1"; static const char *kLayoutSwitcherName("layoutSwitcherGrid"); static QRegularExpression kBackupFileRegex("^(.+) ([0-9]{4})-(1[0-2]|0[1-9])-(3[01]|0[1-9]|[12][0-9])T(2[0-3]|[01][0-9])-([0-5][0-9])-([0-5][0-9]).mlt$"); MainWindow::MainWindow() : QMainWindow(0) , ui(new Ui::MainWindow) , m_isKKeyPressed(false) , m_keyerGroup(0) , m_previewScaleGroup(0) , m_keyerMenu(0) , m_multipleFilesLoading(false) , m_isPlaylistLoaded(false) , m_exitCode(EXIT_SUCCESS) , m_upgradeUrl("https://www.shotcut.org/download/") , m_keyframesDock(0) { #if defined(Q_OS_UNIX) && !defined(Q_OS_MAC) QLibrary libJack("libjack.so.0"); if (!libJack.load()) { QMessageBox::critical(this, qApp->applicationName(), tr("Error: This program requires the JACK 1 library.\n\nPlease install it using your package manager. It may be named libjack0, jack-audio-connection-kit, jack, or similar.")); ::exit(EXIT_FAILURE); } else { libJack.unload(); } QLibrary libSDL("libSDL2-2.0.so.0"); if (!libSDL.load()) { QMessageBox::critical(this, qApp->applicationName(), tr("Error: This program requires the SDL 2 library.\n\nPlease install it using your package manager. It may be named libsdl2-2.0-0, SDL2, or similar.")); ::exit(EXIT_FAILURE); } else { libSDL.unload(); } #endif connectFocusSignals(); registerDebugCallback(); LOG_DEBUG() << "begin"; LOG_INFO() << "device pixel ratio =" << devicePixelRatioF(); connect(&m_autosaveTimer, SIGNAL(timeout()), this, SLOT(onAutosaveTimeout())); m_autosaveTimer.start(AUTOSAVE_TIMEOUT_MS); // Initialize all QML types QmlUtilities::registerCommonTypes(); // Create the UI. ui->setupUi(this); setDockNestingEnabled(true); setStyleSheet(QStringLiteral("QMainWindow::separator {" " width: 10px;" "}" "QMainWindow::separator:hover {" " background-color: rgba(23, 92, 118, 20%);" "}")); ui->statusBar->hide(); connectUISignals(); // Accept drag-n-drop of files. this->setAcceptDrops(true); setupAndConnectUndoStack(); // Add the player widget. setupAndConnectPlayerWidget(); setupSettingsMenu(); setupOpenOtherMenu(); readPlayerSettings(); configureVideoWidget(); setupLayoutSwitcher(); centerLayoutInRemainingToolbarSpace(); #ifndef SHOTCUT_NOUPGRADE if (Settings.noUpgrade() || qApp->property("noupgrade").toBool()) #endif delete ui->actionUpgrade; setupAndConnectDocks(); setupMenuFile(); setupMenuView(); connectVideoWidgetSignals(); readWindowSettings(); setupActions(); setFocus(); setCurrentFile(""); connect(&m_network, SIGNAL(finished(QNetworkReply *)), SLOT(onUpgradeCheckFinished(QNetworkReply *))); resetSourceUpdated(); m_clipboardUpdatedAt.setSecsSinceEpoch(0); onClipboardChanged(); connect(QGuiApplication::clipboard(), SIGNAL(dataChanged()), this, SLOT(onClipboardChanged())); QThreadPool::globalInstance()->setMaxThreadCount(qMin(4, QThreadPool::globalInstance()->maxThreadCount())); QImageReader::setAllocationLimit(1024); ProxyManager::removePending(); LOG_DEBUG() << "end"; } void MainWindow::connectFocusSignals() { if (!qgetenv("OBSERVE_FOCUS").isEmpty()) { connect(qApp, &QApplication::focusChanged, this, &MainWindow::onFocusChanged); connect(qApp, &QGuiApplication::focusObjectChanged, this, &MainWindow::onFocusObjectChanged); connect(qApp, &QGuiApplication::focusWindowChanged, this, &MainWindow::onFocusWindowChanged); } } void MainWindow::registerDebugCallback() { if (!qgetenv("EVENT_DEBUG").isEmpty()) QInternal::registerCallback(QInternal::EventNotifyCallback, eventDebugCallback); } void MainWindow::connectUISignals() { connect(ui->actionOpen, SIGNAL(triggered()), this, SLOT(openVideo())); connect(ui->actionAbout_Qt, SIGNAL(triggered()), qApp, SLOT(aboutQt())); connect(this, &MainWindow::producerOpened, this, &MainWindow::onProducerOpened); connect(ui->mainToolBar, SIGNAL(visibilityChanged(bool)), SLOT(onToolbarVisibilityChanged(bool))); ui->actionSave->setEnabled(false); } void MainWindow::setupAndConnectUndoStack() { m_undoStack = new QUndoStack(this); m_undoStack->setUndoLimit(Settings.undoLimit()); QAction *undoAction = m_undoStack->createUndoAction(this); QAction *redoAction = m_undoStack->createRedoAction(this); undoAction->setIcon(QIcon::fromTheme("edit-undo", QIcon(":/icons/oxygen/32x32/actions/edit-undo.png"))); redoAction->setIcon(QIcon::fromTheme("edit-redo", QIcon(":/icons/oxygen/32x32/actions/edit-redo.png"))); undoAction->setShortcut(QString::fromLatin1("Ctrl+Z")); #ifdef Q_OS_WIN redoAction->setShortcut(QString::fromLatin1("Ctrl+Y")); #else redoAction->setShortcut(QString::fromLatin1("Ctrl+Shift+Z")); #endif ui->menuEdit->addAction(undoAction); ui->menuEdit->addAction(redoAction); ui->menuEdit->addSeparator(); ui->actionUndo->setIcon(undoAction->icon()); ui->actionRedo->setIcon(redoAction->icon()); ui->actionUndo->setToolTip(undoAction->toolTip()); ui->actionRedo->setToolTip(redoAction->toolTip()); connect(m_undoStack, SIGNAL(canUndoChanged(bool)), ui->actionUndo, SLOT(setEnabled(bool))); connect(m_undoStack, SIGNAL(canRedoChanged(bool)), ui->actionRedo, SLOT(setEnabled(bool))); } void MainWindow::setupAndConnectPlayerWidget() { m_player = new Player; MLT.videoWidget()->installEventFilter(this); ui->centralWidget->layout()->addWidget(m_player); connect(this, &MainWindow::producerOpened, m_player, &Player::onProducerOpened); connect(m_player, SIGNAL(showStatusMessage(QString)), this, SLOT(showStatusMessage(QString))); connect(m_player, SIGNAL(inChanged(int)), this, SLOT(onCutModified())); connect(m_player, SIGNAL(outChanged(int)), this, SLOT(onCutModified())); connect(m_player, SIGNAL(tabIndexChanged(int)), SLOT(onPlayerTabIndexChanged(int))); connect(MLT.videoWidget(), SIGNAL(started()), SLOT(processMultipleFiles())); connect(MLT.videoWidget(), SIGNAL(started()), SLOT(processSingleFile())); connect(MLT.videoWidget(), SIGNAL(paused()), m_player, SLOT(showPaused())); connect(MLT.videoWidget(), SIGNAL(playing()), m_player, SLOT(showPlaying())); connect(MLT.videoWidget(), SIGNAL(toggleZoom(bool)), m_player, SLOT(toggleZoom(bool))); ui->menuPlayer->addAction(Actions["playerPlayPauseAction"]); ui->menuPlayer->addAction(Actions["playerLoopAction"]); QMenu *loopRangeMenu = new QMenu(tr("Set Loop Range"), this); loopRangeMenu->addAction(Actions["playerLoopRangeAllAction"]); loopRangeMenu->addAction(Actions["playerLoopRangeMarkerAction"]); loopRangeMenu->addAction(Actions["playerLoopRangeSelectionAction"]); loopRangeMenu->addAction(Actions["playerLoopRangeAroundAction"]); ui->menuPlayer->addMenu(loopRangeMenu); ui->menuPlayer->addAction(Actions["playerFastForwardAction"]); ui->menuPlayer->addAction(Actions["playerRewindAction"]); ui->menuPlayer->addAction(Actions["playerSkipNextAction"]); ui->menuPlayer->addAction(Actions["playerSkipPreviousAction"]); ui->menuPlayer->addAction(Actions["playerSeekStartAction"]); ui->menuPlayer->addAction(Actions["playerSeekEndAction"]); ui->menuPlayer->addAction(Actions["playerNextFrameAction"]); ui->menuPlayer->addAction(Actions["playerPreviousFrameAction"]); ui->menuPlayer->addAction(Actions["playerForwardOneSecondAction"]); ui->menuPlayer->addAction(Actions["playerBackwardOneSecondAction"]); ui->menuPlayer->addAction(Actions["playerForwardTwoSecondsAction"]); ui->menuPlayer->addAction(Actions["playerBackwardTwoAction"]); ui->menuPlayer->addAction(Actions["playerForwardFiveSecondsAction"]); ui->menuPlayer->addAction(Actions["playerBackwardFiveSecondsAction"]); ui->menuPlayer->addAction(Actions["playerForwardTenSecondsAction"]); ui->menuPlayer->addAction(Actions["playerBackwardTenSecondsAction"]); ui->menuPlayer->addAction(Actions["playerForwardJumpAction"]); ui->menuPlayer->addAction(Actions["playerBackwardJumpAction"]); ui->menuPlayer->addAction(Actions["playerSetJumpAction"]); ui->menuPlayer->addAction(Actions["playerSetInAction"]); ui->menuPlayer->addAction(Actions["playerSetOutAction"]); ui->menuPlayer->addAction(Actions["playerSetPositionAction"]); ui->menuPlayer->addAction(Actions["playerSwitchSourceProgramAction"]); } void MainWindow::setupLayoutSwitcher() { auto group = new QActionGroup(this); group->addAction(ui->actionLayoutLogging); group->addAction(ui->actionLayoutEditing); group->addAction(ui->actionLayoutEffects); group->addAction(ui->actionLayoutAudio); group->addAction(ui->actionLayoutColor); group->addAction(ui->actionLayoutPlayer); switch (Settings.layoutMode()) { case LayoutMode::Custom: break; case LayoutMode::Logging: ui->actionLayoutLogging->setChecked(true); break; case LayoutMode::Editing: ui->actionLayoutEditing->setChecked(true); break; case LayoutMode::Effects: ui->actionLayoutEffects->setChecked(true); break; case LayoutMode::Color: ui->actionLayoutColor->setChecked(true); break; case LayoutMode::Audio: ui->actionLayoutAudio->setChecked(true); break; case LayoutMode::PlayerOnly: ui->actionLayoutPlayer->setChecked(true); break; default: ui->actionLayoutEditing->setChecked(true); break; } } void MainWindow::centerLayoutInRemainingToolbarSpace() { auto spacer = new QWidget; spacer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); ui->mainToolBar->insertWidget(ui->dummyAction, spacer); spacer = new QWidget; spacer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); ui->mainToolBar->addWidget(spacer); updateLayoutSwitcher(); } void MainWindow::setupAndConnectDocks() { m_scopeController = new ScopeController(this, ui->menuView); QDockWidget *audioMeterDock = findChild<QDockWidget *>("AudioPeakMeterDock"); if (audioMeterDock) { audioMeterDock->toggleViewAction()->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_1)); connect(ui->actionAudioMeter, SIGNAL(triggered()), audioMeterDock->toggleViewAction(), SLOT(trigger())); } m_propertiesDock = new QDockWidget(tr("Properties"), this); m_propertiesDock->hide(); m_propertiesDock->setObjectName("propertiesDock"); m_propertiesDock->setWindowIcon(ui->actionProperties->icon()); m_propertiesDock->toggleViewAction()->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_2)); m_propertiesDock->toggleViewAction()->setIcon(ui->actionProperties->icon()); m_propertiesDock->setMinimumWidth(300); QScrollArea *scroll = new QScrollArea; scroll->setWidgetResizable(true); m_propertiesDock->setWidget(scroll); ui->menuView->addAction(m_propertiesDock->toggleViewAction()); connect(m_propertiesDock->toggleViewAction(), SIGNAL(triggered(bool)), this, SLOT(onPropertiesDockTriggered(bool))); connect(ui->actionProperties, SIGNAL(triggered()), this, SLOT(onPropertiesDockTriggered())); m_recentDock = new RecentDock(this); m_recentDock->hide(); m_recentDock->toggleViewAction()->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_3)); ui->menuView->addAction(m_recentDock->toggleViewAction()); connect(m_recentDock, SIGNAL(itemActivated(QString)), this, SLOT(open(QString))); connect(m_recentDock->toggleViewAction(), SIGNAL(triggered(bool)), this, SLOT(onRecentDockTriggered(bool))); connect(ui->actionRecent, SIGNAL(triggered()), this, SLOT(onRecentDockTriggered())); connect(this, SIGNAL(openFailed(QString)), m_recentDock, SLOT(remove(QString))); connect(m_recentDock, &RecentDock::deleted, m_player->projectWidget(), &NewProjectFolder::updateRecentProjects); m_playlistDock = new PlaylistDock(this); m_playlistDock->hide(); m_playlistDock->toggleViewAction()->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_4)); ui->menuView->addAction(m_playlistDock->toggleViewAction()); connect(m_playlistDock->toggleViewAction(), SIGNAL(triggered(bool)), this, SLOT(onPlaylistDockTriggered(bool))); connect(ui->actionPlaylist, SIGNAL(triggered()), this, SLOT(onPlaylistDockTriggered())); connect(m_playlistDock, SIGNAL(clipOpened(Mlt::Producer *, bool)), this, SLOT(openCut(Mlt::Producer *, bool))); connect(m_playlistDock, SIGNAL(itemActivated(int)), this, SLOT(seekPlaylist(int))); connect(m_playlistDock, SIGNAL(showStatusMessage(QString)), this, SLOT(showStatusMessage(QString))); connect(m_playlistDock->model(), SIGNAL(created()), this, SLOT(onPlaylistCreated())); connect(m_playlistDock->model(), SIGNAL(cleared()), this, SLOT(onPlaylistCleared())); connect(m_playlistDock->model(), SIGNAL(closed()), this, SLOT(onPlaylistClosed())); connect(m_playlistDock->model(), SIGNAL(modified()), this, SLOT(onPlaylistModified())); connect(m_playlistDock->model(), SIGNAL(loaded()), this, SLOT(onPlaylistLoaded())); connect(this, SIGNAL(producerOpened()), m_playlistDock, SLOT(onProducerOpened())); if (!Settings.playerGPU()) connect(m_playlistDock->model(), SIGNAL(loaded()), this, SLOT(updateThumbnails())); connect(m_player, &Player::inChanged, m_playlistDock, &PlaylistDock::onInChanged); connect(m_player, &Player::outChanged, m_playlistDock, &PlaylistDock::onOutChanged); connect(m_playlistDock->model(), &PlaylistModel::inChanged, this, &MainWindow::onPlaylistInChanged); connect(m_playlistDock->model(), &PlaylistModel::outChanged, this, &MainWindow::onPlaylistOutChanged); QMenu *viewModeMenu = ui->menuPlaylist->addMenu(tr("View mode")); viewModeMenu->addAction(Actions["playlistViewDetailsAction"]); viewModeMenu->addAction(Actions["playlistViewTilesAction"]); viewModeMenu->addAction(Actions["playlistViewIconsAction"]); QMenu *subMenu = ui->menuPlaylist->addMenu(tr("Thumbnails")); subMenu->addAction(Actions["playlistThumbnailsHiddenAction"]); subMenu->addAction(Actions["playlistThumbnailsLeftAndRightAction"]); subMenu->addAction(Actions["playlistThumbnailsTopAndBottomAction"]); subMenu->addAction(Actions["playlistThumbnailsInOnlySmallAction"]); subMenu->addAction(Actions["playlistThumbnailsInOnlyLargeAction"]); ui->menuPlaylist->addAction(Actions["playlistPlayAfterOpenAction"]); m_timelineDock = new TimelineDock(this); m_timelineDock->hide(); m_timelineDock->toggleViewAction()->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_5)); ui->menuView->addAction(m_timelineDock->toggleViewAction()); connect(m_timelineDock->toggleViewAction(), SIGNAL(triggered(bool)), this, SLOT(onTimelineDockTriggered(bool))); connect(ui->actionTimeline, SIGNAL(triggered()), SLOT(onTimelineDockTriggered())); connect(m_player, SIGNAL(seeked(int)), m_timelineDock, SLOT(onSeeked(int))); connect(m_timelineDock, SIGNAL(seeked(int)), SLOT(seekTimeline(int))); connect(m_timelineDock, SIGNAL(clipClicked()), SLOT(onTimelineClipSelected())); connect(m_timelineDock, SIGNAL(showStatusMessage(QString)), this, SLOT(showStatusMessage(QString))); connect(m_timelineDock->model(), SIGNAL(showStatusMessage(QString)), this, SLOT(showStatusMessage(QString))); connect(m_timelineDock->model(), SIGNAL(created()), SLOT(onMultitrackCreated())); connect(m_timelineDock->model(), SIGNAL(closed()), SLOT(onMultitrackClosed())); connect(m_timelineDock->model(), SIGNAL(modified()), SLOT(onMultitrackModified())); connect(m_timelineDock->model(), SIGNAL(durationChanged()), SLOT(onMultitrackDurationChanged())); connect(m_timelineDock, SIGNAL(clipOpened(Mlt::Producer *)), SLOT(openCut(Mlt::Producer *))); connect(m_timelineDock->model(), &MultitrackModel::seeked, this, &MainWindow::seekTimeline); connect(m_timelineDock->markersModel(), SIGNAL(modified()), SLOT(onMultitrackModified())); connect(m_timelineDock, SIGNAL(selected(Mlt::Producer *)), SLOT(loadProducerWidget(Mlt::Producer *))); connect(m_timelineDock, SIGNAL(clipCopied()), SLOT(onClipCopied())); connect(m_timelineDock, SIGNAL(filteredClicked()), SLOT(onFiltersDockTriggered())); connect(m_playlistDock, SIGNAL(addAllTimeline(Mlt::Playlist *)), SLOT(onTimelineDockTriggered())); connect(m_playlistDock, SIGNAL(addAllTimeline(Mlt::Playlist *, bool, bool)), SLOT(onAddAllToTimeline(Mlt::Playlist *, bool, bool))); connect(m_player, SIGNAL(previousSought()), m_timelineDock, SLOT(seekPreviousEdit())); connect(m_player, SIGNAL(nextSought()), m_timelineDock, SLOT(seekNextEdit())); connect(m_player, SIGNAL(loopChanged(int, int)), m_timelineDock, SLOT(onLoopChanged(int, int))); connect(m_timelineDock, SIGNAL(isRecordingChanged(bool)), m_player, SLOT(onMuteButtonToggled(bool))); connect(m_player, SIGNAL(trimIn()), m_timelineDock, SLOT(trimClipIn())); connect(m_player, SIGNAL(trimOut()), m_timelineDock, SLOT(trimClipOut())); ui->menuEdit->addAction(Actions["timelineCutAction"]); ui->menuEdit->addAction(Actions["timelineCopyAction"]); ui->menuEdit->addAction(Actions["timelinePasteAction"]); ui->menuTimeline->addAction(Actions["timelineSnapAction"]); ui->menuTimeline->addAction(Actions["timelineSnapAction"]); ui->menuTimeline->addAction(Actions["timelineScrubDragAction"]); ui->menuTimeline->addAction(Actions["timelineRippleAction"]); ui->menuTimeline->addAction(Actions["timelineRippleAllTracksAction"]); ui->menuTimeline->addAction(Actions["timelineRippleMarkersAction"]); ui->menuTimeline->addAction(Actions["timelineToggleRippleAndAllTracksAction"]); ui->menuTimeline->addAction(Actions["timelineToggleRippleAllTracksAndMarkersAction"]); ui->menuTimeline->addAction(Actions["timelineRectangleSelectAction"]); ui->menuTimeline->addAction(Actions["timelineAutoAddTracksAction"]); ui->menuTimeline->addAction(Actions["timelineShowWaveformsAction"]); ui->menuTimeline->addAction(Actions["timelinePerformanceWaveformsAction"]); ui->menuTimeline->addAction(Actions["timelineShowThumbnailsAction"]); auto submenu = ui->menuTimeline->addMenu(tr("Scrolling")); auto *group = new QActionGroup(this); submenu->addAction(Actions["timelineScrollingCenterPlayhead"]); group->addAction(Actions["timelineScrollingCenterPlayhead"]); submenu->addAction(Actions["timelineScrollingNo"]); group->addAction(Actions["timelineScrollingNo"]); submenu->addAction(Actions["timelineScrollingPage"]); group->addAction(Actions["timelineScrollingPage"]); submenu->addAction(Actions["timelineScrollingSmooth"]); group->addAction(Actions["timelineScrollingSmooth"]); submenu->addAction(Actions["timelineScrollZoomAction"]); m_filterController = new FilterController(this); m_filtersDock = new FiltersDock(m_filterController->metadataModel(), m_filterController->attachedModel(), m_filterController->motionTrackerModel(), m_timelineDock->subtitlesModel(), this); m_filtersDock->setMinimumSize(400, 300); m_filtersDock->hide(); m_filtersDock->toggleViewAction()->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_6)); ui->menuView->addAction(m_filtersDock->toggleViewAction()); connect(m_filtersDock, SIGNAL(currentFilterRequested(int)), m_filterController, SLOT(setCurrentFilter(int)), Qt::QueuedConnection); connect(m_filtersDock->toggleViewAction(), SIGNAL(triggered(bool)), this, SLOT(onFiltersDockTriggered(bool))); connect(ui->actionFilters, SIGNAL(triggered()), this, SLOT(onFiltersDockTriggered())); connect(m_filterController, SIGNAL(currentFilterChanged(QmlFilter *, QmlMetadata *, int)), m_filtersDock, SLOT(setCurrentFilter(QmlFilter *, QmlMetadata *, int))); connect(m_filterController, &FilterController::undoOrRedo, m_filtersDock, &FiltersDock::load); connect(this, SIGNAL(producerOpened()), m_filterController, SLOT(setProducer())); connect(m_filterController->attachedModel(), SIGNAL(changed()), SLOT(onFilterModelChanged())); connect(m_filtersDock, SIGNAL(changed()), SLOT(onFilterModelChanged())); connect(m_filterController, SIGNAL(filterChanged(Mlt::Service *)), m_timelineDock->model(), SLOT(onFilterChanged(Mlt::Service *))); connect(m_filterController->attachedModel(), SIGNAL(changed()), m_timelineDock, SLOT(onFilterModelChanged())); connect(m_filtersDock, SIGNAL(changed()), m_timelineDock, SLOT(onFilterModelChanged())); connect(m_filterController->attachedModel(), SIGNAL(addedOrRemoved(Mlt::Producer *)), m_timelineDock->model(), SLOT(filterAddedOrRemoved(Mlt::Producer *))); connect(&QmlApplication::singleton(), SIGNAL(filtersPasted(Mlt::Producer *)), m_timelineDock->model(), SLOT(filterAddedOrRemoved(Mlt::Producer *))); connect(&QmlApplication::singleton(), &QmlApplication::filtersPasted, this, &MainWindow::onProducerModified); connect(m_filterController, SIGNAL(statusChanged(QString)), this, SLOT(showStatusMessage(QString))); connect(m_timelineDock, SIGNAL(fadeInChanged(int)), m_filterController, SLOT(onFadeInChanged())); connect(m_timelineDock, SIGNAL(fadeOutChanged(int)), m_filterController, SLOT(onFadeOutChanged())); connect(m_timelineDock, SIGNAL(selected(Mlt::Producer *)), m_filterController, SLOT(setProducer(Mlt::Producer *))); connect(m_player, SIGNAL(seeked(int)), m_filtersDock, SLOT(onSeeked(int)), Qt::QueuedConnection); connect(m_filtersDock, SIGNAL(seeked(int)), SLOT(seekKeyframes(int))); connect(MLT.videoWidget(), SIGNAL(frameDisplayed(const SharedFrame &)), m_filtersDock, SLOT(onShowFrame(const SharedFrame &))); connect(m_player, SIGNAL(inChanged(int)), m_filtersDock, SIGNAL(producerInChanged(int))); connect(this, SIGNAL(serviceInChanged(int, Mlt::Service *)), m_filtersDock, SLOT(onServiceInChanged(int, Mlt::Service *))); connect(m_player, SIGNAL(outChanged(int)), m_filtersDock, SIGNAL(producerOutChanged(int))); connect(m_player, SIGNAL(inChanged(int)), m_filterController, SLOT(onServiceInChanged(int))); connect(m_player, SIGNAL(outChanged(int)), m_filterController, SLOT(onServiceOutChanged(int))); connect(this, SIGNAL(serviceInChanged(int, Mlt::Service *)), m_filterController, SLOT(onServiceInChanged(int, Mlt::Service *))); connect(this, SIGNAL(serviceOutChanged(int, Mlt::Service *)), m_filterController, SLOT(onServiceOutChanged(int, Mlt::Service *))); connect(m_playlistDock->model(), &PlaylistModel::removing, m_filterController->motionTrackerModel(), &MotionTrackerModel::removeFromService); connect(m_timelineDock->model(), &MultitrackModel::removing, m_filterController->motionTrackerModel(), &MotionTrackerModel::removeFromService); connect(this, SIGNAL(audioChannelsChanged()), m_filterController, SLOT(setProducer())); m_markersDock = new MarkersDock(this); m_markersDock->hide(); m_markersDock->toggleViewAction()->setShortcut(QKeySequence(Qt::CTRL | Qt::SHIFT | Qt::Key_6)); m_markersDock->setModel(m_timelineDock->markersModel()); ui->menuView->addAction(m_markersDock->toggleViewAction()); connect(m_markersDock->toggleViewAction(), SIGNAL(triggered(bool)), this, SLOT(onMarkersDockTriggered(bool))); connect(ui->actionMarkers, SIGNAL(triggered()), this, SLOT(onMarkersDockTriggered())); connect(m_markersDock, SIGNAL(seekRequested(int)), SLOT(seekTimeline(int))); connect(m_markersDock, SIGNAL(addRequested()), m_timelineDock, SLOT(createMarker())); connect(m_markersDock, SIGNAL(addAroundSelectionRequested()), m_timelineDock, SLOT(createOrEditSelectionMarker())); connect(m_timelineDock, SIGNAL(markerSeeked(int)), m_markersDock, SLOT(onMarkerSelectionRequest(int))); m_keyframesDock = new KeyframesDock(m_filtersDock->qmlProducer(), this); m_keyframesDock->hide(); m_keyframesDock->toggleViewAction()->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_7)); ui->menuView->addAction(m_keyframesDock->toggleViewAction()); connect(m_keyframesDock->toggleViewAction(), SIGNAL(triggered(bool)), this, SLOT(onKeyframesDockTriggered(bool))); connect(ui->actionKeyframes, SIGNAL(triggered()), this, SLOT(onKeyframesDockTriggered())); connect(m_filterController, SIGNAL(currentFilterChanged(QmlFilter *, QmlMetadata *, int)), m_keyframesDock, SLOT(setCurrentFilter(QmlFilter *, QmlMetadata *))); connect(m_keyframesDock, SIGNAL(visibilityChanged(bool)), m_filtersDock->qmlProducer(), SLOT(remakeAudioLevels(bool))); connect(m_filterController, &FilterController::undoOrRedo, m_keyframesDock, &KeyframesDock::reload); m_historyDock = new QDockWidget(tr("History"), this); m_historyDock->hide(); m_historyDock->setObjectName("historyDock"); m_historyDock->setWindowIcon(ui->actionHistory->icon()); m_historyDock->toggleViewAction()->setIcon(ui->actionHistory->icon()); m_historyDock->toggleViewAction()->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_8)); m_historyDock->setMinimumWidth(150); ui->menuView->addAction(m_historyDock->toggleViewAction()); connect(m_historyDock->toggleViewAction(), SIGNAL(triggered(bool)), this, SLOT(onHistoryDockTriggered(bool))); connect(ui->actionHistory, SIGNAL(triggered()), this, SLOT(onHistoryDockTriggered())); QUndoView *undoView = new QUndoView(m_undoStack, m_historyDock); undoView->setObjectName("historyView"); undoView->setAlternatingRowColors(true); undoView->setSpacing(2); m_historyDock->setWidget(undoView); ui->actionUndo->setDisabled(true); ui->actionRedo->setDisabled(true); m_encodeDock = new EncodeDock(this); m_encodeDock->hide(); m_encodeDock->toggleViewAction()->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_9)); ui->menuView->addAction(m_encodeDock->toggleViewAction()); connect(this, SIGNAL(producerOpened()), m_encodeDock, SLOT(onProducerOpened())); connect(ui->actionEncode, SIGNAL(triggered()), this, SLOT(onEncodeTriggered())); connect(ui->actionExportVideo, SIGNAL(triggered()), m_encodeDock, SLOT(on_encodeButton_clicked())); connect(m_encodeDock->toggleViewAction(), SIGNAL(triggered(bool)), this, SLOT(onEncodeTriggered(bool))); connect(m_encodeDock, SIGNAL(captureStateChanged(bool)), m_player, SLOT(onCaptureStateChanged(bool))); connect(m_encodeDock, SIGNAL(captureStateChanged(bool)), m_propertiesDock, SLOT(setDisabled(bool))); connect(m_encodeDock, SIGNAL(captureStateChanged(bool)), m_recentDock, SLOT(setDisabled(bool))); connect(m_encodeDock, SIGNAL(captureStateChanged(bool)), m_filtersDock, SLOT(setDisabled(bool))); connect(m_encodeDock, SIGNAL(captureStateChanged(bool)), m_keyframesDock, SLOT(setDisabled(bool))); connect(m_encodeDock, SIGNAL(captureStateChanged(bool)), ui->actionOpen, SLOT(setDisabled(bool))); connect(m_encodeDock, SIGNAL(captureStateChanged(bool)), ui->actionOpenOther, SLOT(setDisabled(bool))); connect(m_encodeDock, SIGNAL(captureStateChanged(bool)), ui->actionExit, SLOT(setDisabled(bool))); connect(m_encodeDock, SIGNAL(captureStateChanged(bool)), this, SLOT(onCaptureStateChanged(bool))); connect(m_encodeDock, SIGNAL(captureStateChanged(bool)), m_historyDock, SLOT(setDisabled(bool))); connect(this, SIGNAL(profileChanged()), m_encodeDock, SLOT(onProfileChanged())); connect(this, SIGNAL(profileChanged()), SLOT(onProfileChanged())); connect(this, SIGNAL(profileChanged()), &QmlProfile::singleton(), SIGNAL(profileChanged())); connect(this, SIGNAL(audioChannelsChanged()), m_encodeDock, SLOT(onAudioChannelsChanged())); connect(m_playlistDock->model(), SIGNAL(modified()), m_encodeDock, SLOT(onProducerOpened())); connect(m_timelineDock, SIGNAL(clipCopied()), m_encodeDock, SLOT(onProducerOpened())); connect(m_timelineDock, SIGNAL(markerRangesChanged()), m_encodeDock, SLOT(onProducerOpened())); connect(m_timelineDock->model(), &MultitrackModel::filteredChanged, m_encodeDock, &EncodeDock::onProfileChanged); connect(m_filterController, &FilterController::filterChanged, this, [&](Mlt::Service * filter) { if (filter && filter->is_valid() && !::qstrcmp("reframe", filter->get(kShotcutFilterProperty))) { m_encodeDock->onReframeChanged(); } }); m_jobsDock = new JobsDock(this); m_jobsDock->hide(); m_jobsDock->toggleViewAction()->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_0)); ui->menuView->addAction(m_jobsDock->toggleViewAction()); connect(&JOBS, SIGNAL(jobAdded()), m_jobsDock, SLOT(onJobAdded())); connect(m_jobsDock->toggleViewAction(), SIGNAL(triggered(bool)), this, SLOT(onJobsDockTriggered(bool))); connect(ui->actionJobs, SIGNAL(triggered()), this, SLOT(onJobsDockTriggered())); m_notesDock = new NotesDock(this); m_notesDock->hide(); m_notesDock->toggleViewAction()->setShortcut(QKeySequence(Qt::CTRL | Qt::SHIFT | Qt::Key_3)); ui->menuView->insertAction(m_playlistDock->toggleViewAction(), m_notesDock->toggleViewAction()); connect(m_notesDock->toggleViewAction(), SIGNAL(triggered(bool)), this, SLOT(onNotesDockTriggered(bool))); connect(ui->actionNotes, SIGNAL(triggered()), this, SLOT(onNotesDockTriggered())); connect(m_notesDock, SIGNAL(modified()), this, SLOT(onNoteModified())); m_subtitlesDock = new SubtitlesDock(this); m_subtitlesDock->hide(); m_subtitlesDock->toggleViewAction()->setShortcut(QKeySequence(Qt::CTRL | Qt::SHIFT | Qt::Key_9)); m_subtitlesDock->setModel(m_timelineDock->subtitlesModel(), m_timelineDock->subtitlesSelectionModel()); ui->menuView->addAction(m_subtitlesDock->toggleViewAction()); connect(m_subtitlesDock->toggleViewAction(), SIGNAL(triggered(bool)), this, SLOT(onSubtitlesDockTriggered(bool))); connect(ui->actionSubtitles, SIGNAL(triggered()), this, SLOT(onSubtitlesDockTriggered())); connect(m_subtitlesDock, SIGNAL(seekRequested(int)), SLOT(seekTimeline(int))); connect(m_timelineDock, SIGNAL(positionChanged(int)), m_subtitlesDock, SLOT(onPositionChanged(int))); connect(m_subtitlesDock, SIGNAL(addAllTimeline(Mlt::Playlist *, bool, bool)), SLOT(onTimelineDockTriggered())); connect(m_subtitlesDock, SIGNAL(addAllTimeline(Mlt::Playlist *, bool, bool)), SLOT(onAddAllToTimeline(Mlt::Playlist *, bool, bool))); connect(m_subtitlesDock, &SubtitlesDock::createOrEditFilterOnOutput, this, &MainWindow::onCreateOrEditFilterOnOutput); connect(m_encodeDock, &EncodeDock::createOrEditFilterOnOutput, this, &MainWindow::onCreateOrEditFilterOnOutput); connect(m_timelineDock->subtitlesModel(), SIGNAL(modified()), this, SLOT(onSubtitleModified())); addDockWidget(Qt::LeftDockWidgetArea, m_propertiesDock); addDockWidget(Qt::RightDockWidgetArea, m_recentDock); addDockWidget(Qt::LeftDockWidgetArea, m_playlistDock); addDockWidget(Qt::BottomDockWidgetArea, m_timelineDock); addDockWidget(Qt::LeftDockWidgetArea, m_filtersDock); addDockWidget(Qt::BottomDockWidgetArea, m_keyframesDock); addDockWidget(Qt::RightDockWidgetArea, m_historyDock); addDockWidget(Qt::LeftDockWidgetArea, m_encodeDock); addDockWidget(Qt::RightDockWidgetArea, m_jobsDock); addDockWidget(Qt::LeftDockWidgetArea, m_notesDock); addDockWidget(Qt::LeftDockWidgetArea, m_subtitlesDock); splitDockWidget(m_timelineDock, m_markersDock, Qt::Horizontal); tabifyDockWidget(m_propertiesDock, m_playlistDock); tabifyDockWidget(m_playlistDock, m_filtersDock); tabifyDockWidget(m_filtersDock, m_encodeDock); tabifyDockWidget(m_encodeDock, m_notesDock); tabifyDockWidget(m_notesDock, m_subtitlesDock); splitDockWidget(m_recentDock, findChild<QDockWidget *>("AudioWaveformDock"), Qt::Vertical); splitDockWidget(audioMeterDock, m_recentDock, Qt::Horizontal); tabifyDockWidget(m_recentDock, m_historyDock); tabifyDockWidget(m_historyDock, m_jobsDock); tabifyDockWidget(m_keyframesDock, m_timelineDock); m_recentDock->raise(); resetDockCorners(); } void MainWindow::setupMenuFile() { #ifdef Q_OS_MAC static auto sep = " "; #else static auto sep = "\t"; #endif connect(ui->menuOtherVersions, &QMenu::aboutToShow, this, [&] { ui->menuOtherVersions->clear(); QDir dir(QFileInfo(m_currentFile).absolutePath()); auto name = Util::baseName(m_currentFile, true); auto match = kBackupFileRegex.match(name); QStringList filters; if (match.hasMatch()) filters << match.captured(1) + "*.mlt"; else filters << QFileInfo(m_currentFile).baseName().split(" - ").first() + "*.mlt"; for (auto &fileInfo : dir.entryInfoList(filters, QDir::Files, QDir::Time)) { auto filename = fileInfo.fileName(); if (filename != name) { auto text = filename; if (!kBackupFileRegex.match(filename).hasMatch()) text += QString::fromLatin1("%1(%2)").arg(sep, fileInfo.lastModified().toString(Qt::ISODate)); ui->menuOtherVersions->addAction(text)->setData(dir.filePath(filename)); } } QCoreApplication::processEvents(); }); connect(ui->menuOtherVersions, &QMenu::triggered, this, [&](QAction * action) { open(action->data().toString()); }); } void MainWindow::setupMenuView() { ui->menuView->addSeparator(); ui->menuView->addAction(ui->actionResources); ui->menuView->addAction(ui->actionApplicationLog); } void MainWindow::connectVideoWidgetSignals() { auto videoWidget = static_cast<Mlt::VideoWidget *>(&MLT); connect(videoWidget, &Mlt::VideoWidget::dragStarted, m_playlistDock, &PlaylistDock::onPlayerDragStarted); connect(videoWidget, &Mlt::VideoWidget::seekTo, m_player, &Player::seek); connect(videoWidget, &Mlt::VideoWidget::gpuNotSupported, this, &MainWindow::onGpuNotSupported); connect(videoWidget->quickWindow(), &QQuickWindow::sceneGraphInitialized, videoWidget, &Mlt::VideoWidget::initialize, Qt::DirectConnection); connect(videoWidget->quickWindow(), &QQuickWindow::beforeRendering, videoWidget, &Mlt::VideoWidget::beforeRendering, Qt::DirectConnection); connect(videoWidget->quickWindow(), &QQuickWindow::beforeRenderPassRecording, videoWidget, &Mlt::VideoWidget::renderVideo, Qt::DirectConnection); connect(videoWidget->quickWindow(), &QQuickWindow::sceneGraphInitialized, this, &MainWindow::onSceneGraphInitialized, Qt::QueuedConnection); connect(videoWidget->quickWindow(), &QQuickWindow::sceneGraphInitialized, m_timelineDock, &TimelineDock::initLoad); connect(videoWidget, &Mlt::VideoWidget::frameDisplayed, m_scopeController, &ScopeController::newFrame); connect(m_filterController, &FilterController::currentFilterChanged, videoWidget, &Mlt::VideoWidget::setCurrentFilter); } void MainWindow::onFocusWindowChanged(QWindow *) const { LOG_DEBUG() << "Focuswindow changed"; LOG_DEBUG() << "Current focusWidget:" << QApplication::focusWidget(); LOG_DEBUG() << "Current focusObject:" << QApplication::focusObject(); LOG_DEBUG() << "Current focusWindow:" << QApplication::focusWindow(); } void MainWindow::onFocusObjectChanged(QObject *) const { LOG_DEBUG() << "Focusobject changed"; LOG_DEBUG() << "Current focusWidget:" << QApplication::focusWidget(); LOG_DEBUG() << "Current focusObject:" << QApplication::focusObject(); LOG_DEBUG() << "Current focusWindow:" << QApplication::focusWindow(); } void MainWindow::onTimelineClipSelected() { // Switch to Project player. if (m_player->tabIndex() != Player::ProjectTabIndex) { m_timelineDock->saveAndClearSelection(); m_player->onTabBarClicked(Player::ProjectTabIndex); } } void MainWindow::onAddAllToTimeline(Mlt::Playlist *playlist, bool skipProxy, bool emptyTrack) { // We stop the player because of a bug on Windows that results in some // strange memory leak when using Add All To Timeline, more noticeable // with (high res?) still image files. if (MLT.isSeekable()) m_player->pause(); else m_player->stop(); m_timelineDock->appendFromPlaylist(playlist, skipProxy, emptyTrack); } MainWindow &MainWindow::singleton() { static MainWindow *instance = new MainWindow; return *instance; } MainWindow::~MainWindow() { delete ui; Mlt::Controller::destroy(); } void MainWindow::setupSettingsMenu() { LOG_DEBUG() << "begin"; QActionGroup *group = new QActionGroup(this); group->addAction(ui->actionChannels1); group->addAction(ui->actionChannels2); group->addAction(ui->actionChannels4); group->addAction(ui->actionChannels6); group = new QActionGroup(this); group->addAction(ui->actionOneField); group->addAction(ui->actionLinearBlend); group->addAction(ui->actionYadifTemporal); group->addAction(ui->actionYadifSpatial); group->addAction(ui->actionBwdif); #if defined(Q_OS_WIN) || defined(Q_OS_LINUX) auto submenu = new QMenu(tr("Audio API")); ui->menuPlayerSettings->insertMenu(ui->actionSync, submenu); group = new QActionGroup(this); #if defined(Q_OS_WIN) group->addAction(submenu->addAction("DirectSound"))->setData("directsound"); group->addAction(submenu->addAction("WASAPI"))->setData("wasapi"); group->addAction(submenu->addAction("Waveform Audio"))->setData("winmm"); #else group->addAction(submenu->addAction("ALSA"))->setData("alsa"); group->addAction(submenu->addAction("ESound"))->setData("esd"); group->addAction(submenu->addAction("OSS"))->setData("dsp"); group->addAction(submenu->addAction("PipeWire"))->setData("pipewire"); group->addAction(submenu->addAction("PulseAudio"))->setData("pulseaudio"); #endif for (auto a : group->actions()) { a->setCheckable(true); const auto data = a->data().toString(); if (data == Settings.playerAudioDriver()) a->setChecked(true); if ((data == "directsound" && Settings.playerAudioChannels() > 2) || (data == "winmm" && Settings.playerAudioChannels() <= 2) || (data == "pulseaudio")) { a->setText(a->text() + QString::fromLatin1(" (%1)").arg(tr("default"))); } } connect(group, &QActionGroup::triggered, this, [&](QAction * action) { Settings.setPlayerAudioDriver(action->data().toString()); QMessageBox dialog(QMessageBox::Information, qApp->applicationName(), tr("You must restart Shotcut to change the audio API.\n" "Do you want to restart now?"), QMessageBox::No | QMessageBox::Yes, this); dialog.setDefaultButton(QMessageBox::Yes); dialog.setEscapeButton(QMessageBox::No); dialog.setWindowModality(QmlApplication::dialogModality()); if (dialog.exec() == QMessageBox::Yes) { ::qunsetenv("SDL_AUDIODRIVER"); m_exitCode = EXIT_RESTART; QApplication::closeAllWindows(); } }); #endif group = new QActionGroup(this); ui->actionBackupManually->setData(0); group->addAction(ui->actionBackupManually); ui->actionBackupHourly->setData(60); group->addAction(ui->actionBackupHourly); ui->actionBackupDaily->setData(24 * 60); group->addAction(ui->actionBackupDaily); ui->actionBackupWeekly->setData(7 * 24 * 60); group->addAction(ui->actionBackupWeekly); for (auto a : group->actions()) { if (Settings.backupPeriod() == a->data().toInt()) a->setChecked(true); } connect(group, &QActionGroup::triggered, this, [&](QAction * action) { Settings.setBackupPeriod(action->data().toInt()); }); m_previewScaleGroup = new QActionGroup(this); m_previewScaleGroup->addAction(ui->actionPreviewNone); m_previewScaleGroup->addAction(ui->actionPreview360); m_previewScaleGroup->addAction(ui->actionPreview540); m_previewScaleGroup->addAction(ui->actionPreview720); group = new QActionGroup(this); group->addAction(ui->actionTimeFrames); ui->actionTimeFrames->setData(mlt_time_frames); group->addAction(ui->actionTimeClock); ui->actionTimeClock->setData(mlt_time_clock); group->addAction(ui->actionTimeDF); ui->actionTimeDF->setData(mlt_time_smpte_df); group->addAction(ui->actionTimeNDF); ui->actionTimeNDF->setData(mlt_time_smpte_ndf); switch (Settings.timeFormat()) { case mlt_time_frames: ui->actionTimeFrames->setChecked(true); break; case mlt_time_clock: ui->actionTimeClock->setChecked(true); break; case mlt_time_smpte_df: ui->actionTimeDF->setChecked(true); break; default: ui->actionTimeNDF->setChecked(true); break; } connect(group, &QActionGroup::triggered, this, [&](QAction * action) { Settings.setTimeFormat(action->data().toInt()); }); group = new QActionGroup(this); group->addAction(ui->actionNearest); group->addAction(ui->actionBilinear); group->addAction(ui->actionBicubic); group->addAction(ui->actionHyper); m_profileGroup = new QActionGroup(this); m_profileGroup->addAction(ui->actionProfileAutomatic); ui->actionProfileAutomatic->setData(QString()); buildVideoModeMenu(ui->menuProfile, m_customProfileMenu, m_profileGroup, ui->actionAddCustomProfile, ui->actionProfileRemove); // Add the SDI and HDMI devices to the Settings menu. m_externalGroup = new QActionGroup(this); ui->actionExternalNone->setData(QString()); m_externalGroup->addAction(ui->actionExternalNone); #ifdef USE_SCREENS_FOR_EXTERNAL_MONITORING QList<QScreen *> screens = QGuiApplication::screens(); int n = screens.size(); for (int i = 0; n > 1 && i < n; i++) { QAction *action = new QAction(tr("Screen %1 (%2 x %3 @ %4 Hz)").arg(i) .arg(screens[i]->size().width() * screens[i]->devicePixelRatio()) .arg(screens[i]->size().height() * screens[i]->devicePixelRatio()) .arg(screens[i]->refreshRate()), this); action->setCheckable(true); action->setData(i); m_externalGroup->addAction(action); } #endif Mlt::Profile profile; Mlt::Consumer decklink(profile, "decklink:"); if (decklink.is_valid()) { decklink.set("list_devices", 1); int n = decklink.get_int("devices"); for (int i = 0; i < n; ++i) { QString device(decklink.get(QStringLiteral("device.%1").arg(i).toLatin1().constData())); if (!device.isEmpty()) { QAction *action = new QAction(device, this); action->setCheckable(true); action->setData(QStringLiteral("decklink:%1").arg(i)); m_externalGroup->addAction(action); if (!m_keyerGroup) { m_keyerGroup = new QActionGroup(this); action = new QAction(tr("Off"), m_keyerGroup); action->setData(QVariant(0)); action->setCheckable(true); action = new QAction(tr("Internal"), m_keyerGroup); action->setData(QVariant(1)); action->setCheckable(true); action = new QAction(tr("External"), m_keyerGroup); action->setData(QVariant(2)); action->setCheckable(true); } } } } if (m_externalGroup->actions().count() > 1) ui->menuExternal->addActions(m_externalGroup->actions()); else { delete ui->menuExternal; ui->menuExternal = 0; } if (m_keyerGroup) { m_keyerMenu = ui->menuExternal->addMenu(tr("DeckLink Keyer")); m_keyerMenu->addActions(m_keyerGroup->actions()); m_keyerMenu->setDisabled(true); connect(m_keyerGroup, SIGNAL(triggered(QAction *)), this, SLOT(onKeyerTriggered(QAction *))); } connect(m_externalGroup, SIGNAL(triggered(QAction *)), this, SLOT(onExternalTriggered(QAction *))); connect(m_profileGroup, SIGNAL(triggered(QAction *)), this, SLOT(onProfileTriggered(QAction *))); // Setup the language menu actions m_languagesGroup = new QActionGroup(this); QAction *a; a = new QAction(QLocale::languageToString(QLocale::Arabic), m_languagesGroup); a->setCheckable(true); a->setData("ar"); a = new QAction(QLocale::languageToString(QLocale::Basque), m_languagesGroup); a->setCheckable(true); a->setData("eu"); a = new QAction(QLocale::languageToString(QLocale::Catalan), m_languagesGroup); a->setCheckable(true); a->setData("ca"); a = new QAction(QLocale::languageToString(QLocale::Chinese).append(" (China)"), m_languagesGroup); a->setCheckable(true); a->setData("zh_CN"); a = new QAction(QLocale::languageToString(QLocale::Chinese).append(" (Taiwan)"), m_languagesGroup); a->setCheckable(true); a->setData("zh_TW"); a = new QAction(QLocale::languageToString(QLocale::Czech), m_languagesGroup); a->setCheckable(true); a->setData("cs"); a = new QAction(QLocale::languageToString(QLocale::Danish), m_languagesGroup); a->setCheckable(true); a->setData("da"); a = new QAction(QLocale::languageToString(QLocale::Dutch), m_languagesGroup); a->setCheckable(true); a->setData("nl"); a = new QAction(QLocale::languageToString(QLocale::English).append(" (Great Britain)"), m_languagesGroup); a->setCheckable(true); a->setData("en_GB"); a = new QAction(QLocale::languageToString(QLocale::English).append(" (United States)"), m_languagesGroup); a->setCheckable(true); a->setData("en_US"); a = new QAction(QLocale::languageToString(QLocale::Estonian), m_languagesGroup); a->setCheckable(true); a->setData("et"); a = new QAction(QLocale::languageToString(QLocale::Finnish), m_languagesGroup); a->setCheckable(true); a->setData("fi"); a = new QAction(QLocale::languageToString(QLocale::French), m_languagesGroup); a->setCheckable(true); a->setData("fr"); a = new QAction(QLocale::languageToString(QLocale::Gaelic), m_languagesGroup); a->setCheckable(true); a->setData("gd"); a = new QAction(QLocale::languageToString(QLocale::Galician), m_languagesGroup); a->setCheckable(true); a->setData("gl"); a = new QAction(QLocale::languageToString(QLocale::German), m_languagesGroup); a->setCheckable(true); a->setData("de"); a = new QAction(QLocale::languageToString(QLocale::Greek), m_languagesGroup); a->setCheckable(true); a->setData("el"); a = new QAction(QLocale::languageToString(QLocale::Hebrew), m_languagesGroup); a->setCheckable(true); a->setData("he_IL"); a = new QAction(QLocale::languageToString(QLocale::Hungarian), m_languagesGroup); a->setCheckable(true); a->setData("hu"); a = new QAction(QLocale::languageToString(QLocale::Italian), m_languagesGroup); a->setCheckable(true); a->setData("it"); a = new QAction(QLocale::languageToString(QLocale::Japanese), m_languagesGroup); a->setCheckable(true); a->setData("ja"); a = new QAction(QLocale::languageToString(QLocale::Korean), m_languagesGroup); a->setCheckable(true); a->setData("ko"); a = new QAction(QLocale::languageToString(QLocale::Nepali), m_languagesGroup); a->setCheckable(true); a->setData("ne"); a = new QAction(QLocale::languageToString(QLocale::NorwegianBokmal), m_languagesGroup); a->setCheckable(true); a->setData("nb"); a = new QAction(QLocale::languageToString(QLocale::NorwegianNynorsk), m_languagesGroup); a->setCheckable(true); a->setData("nn"); a = new QAction(QLocale::languageToString(QLocale::Occitan), m_languagesGroup); a->setCheckable(true); a->setData("oc"); a = new QAction(QLocale::languageToString(QLocale::Polish), m_languagesGroup); a->setCheckable(true); a->setData("pl"); a = new QAction(QLocale::languageToString(QLocale::Portuguese).append(" (Brazil)"), m_languagesGroup); a->setCheckable(true); a->setData("pt_BR"); a = new QAction(QLocale::languageToString(QLocale::Portuguese).append(" (Portugal)"), m_languagesGroup); a->setCheckable(true); a->setData("pt_PT"); a = new QAction(QLocale::languageToString(QLocale::Romanian), m_languagesGroup); a->setCheckable(true); a->setData("ro"); a = new QAction(QLocale::languageToString(QLocale::Russian), m_languagesGroup); a->setCheckable(true); a->setData("ru"); a = new QAction(QLocale::languageToString(QLocale::Slovak), m_languagesGroup); a->setCheckable(true); a->setData("sk"); a = new QAction(QLocale::languageToString(QLocale::Slovenian), m_languagesGroup); a->setCheckable(true); a->setData("sl"); a = new QAction(QLocale::languageToString(QLocale::Spanish), m_languagesGroup); a->setCheckable(true); a->setData("es"); a = new QAction(QLocale::languageToString(QLocale::Swedish), m_languagesGroup); a->setCheckable(true); a->setData("sv"); a = new QAction(QLocale::languageToString(QLocale::Thai), m_languagesGroup); a->setCheckable(true); a->setData("th"); a = new QAction(QLocale::languageToString(QLocale::Turkish), m_languagesGroup); a->setCheckable(true); a->setData("tr"); a = new QAction(QLocale::languageToString(QLocale::Ukrainian), m_languagesGroup); a->setCheckable(true); a->setData("uk"); ui->menuLanguage->addActions(m_languagesGroup->actions()); const QString locale = Settings.language(); foreach (QAction *action, m_languagesGroup->actions()) { if (action->data().toString().startsWith(locale)) { action->setChecked(true); break; } } connect(m_languagesGroup, SIGNAL(triggered(QAction *)), this, SLOT(onLanguageTriggered(QAction *))); // Setup the themes actions #if defined(SHOTCUT_THEME) group = new QActionGroup(this); group->addAction(ui->actionSystemTheme); group->addAction(ui->actionFusionDark); group->addAction(ui->actionFusionLight); if (Settings.theme() == "dark") ui->actionFusionDark->setChecked(true); else if (Settings.theme() == "light") ui->actionFusionLight->setChecked(true); else ui->actionSystemTheme->setChecked(true); #else delete ui->menuTheme; #endif #if defined(Q_OS_WIN) // On Windows, if there is no JACK or it is not running // then Shotcut crashes inside MLT's call to jack_client_open(). // Therefore, the JACK option for Shotcut is banned on Windows. delete ui->actionJack; ui->actionJack = 0; #endif #if defined(Q_OS_UNIX) && !defined(Q_OS_MAC) // Setup the display method actions. if (!Settings.playerGPU()) { group = new QActionGroup(this); delete ui->actionDrawingAutomatic; delete ui->actionDrawingDirectX; ui->actionDrawingOpenGL->setData(Qt::AA_UseDesktopOpenGL); group->addAction(ui->actionDrawingOpenGL); ui->actionDrawingSoftware->setData(Qt::AA_UseSoftwareOpenGL); group->addAction(ui->actionDrawingSoftware); connect(group, SIGNAL(triggered(QAction *)), this, SLOT(onDrawingMethodTriggered(QAction *))); switch (Settings.drawMethod()) { case Qt::AA_UseDesktopOpenGL: ui->actionDrawingOpenGL->setChecked(true); break; case Qt::AA_UseSoftwareOpenGL: ui->actionDrawingSoftware->setChecked(true); break; default: ui->actionDrawingOpenGL->setChecked(true); break; } } else { // GPU mode only works with OpenGL. delete ui->menuDrawingMethod; ui->menuDrawingMethod = 0; } #else delete ui->menuDrawingMethod; ui->menuDrawingMethod = 0; #endif // Setup the job priority actions group = new QActionGroup(this); group->addAction(ui->actionJobPriorityLow); group->addAction(ui->actionJobPriorityNormal); if (Settings.jobPriority() == QThread::LowPriority) ui->actionJobPriorityLow->setChecked(true); else ui->actionJobPriorityNormal->setChecked(true); // Add custom layouts to View > Layout submenu. m_layoutGroup = new QActionGroup(this); connect(m_layoutGroup, SIGNAL(triggered(QAction *)), SLOT(onLayoutTriggered(QAction *))); if (Settings.layouts().size() > 0) { ui->menuLayout->addAction(ui->actionLayoutRemove); ui->menuLayout->addSeparator(); } foreach (QString name, Settings.layouts()) ui->menuLayout->addAction(addLayout(m_layoutGroup, name)); if (qApp->property("clearRecent").toBool()) { ui->actionClearRecentOnExit->setVisible(false); Settings.setRecent(QStringList()); Settings.setClearRecent(true); } else { ui->actionClearRecentOnExit->setChecked(Settings.clearRecent()); } // Initialize the proxy submenu ui->actionUseProxy->setChecked(Settings.proxyEnabled()); ui->actionProxyUseProjectFolder->setChecked(Settings.proxyUseProjectFolder()); ui->actionProxyUseHardware->setChecked(Settings.proxyUseHardware()); LOG_DEBUG() << "end"; } void MainWindow::setupOpenOtherMenu() { // Open Other toolbar menu button QScopedPointer<Mlt::Properties> mltProducers(MLT.repository()->producers()); QScopedPointer<Mlt::Properties> mltFilters(MLT.repository()->filters()); QMenu *otherMenu = new QMenu(this); ui->actionOpenOther2->setMenu(otherMenu); // populate the generators if (mltProducers->get_data("color")) { otherMenu->addAction(tr("Color"), this, SLOT(onOpenOtherTriggered()))->setObjectName("color"); if (mltProducers->get_data("qtext") && mltFilters->get_data("dynamictext")) otherMenu->addAction(tr("Text"), this, SLOT(onOpenOtherTriggered()))->setObjectName("text"); } if (mltProducers->get_data("glaxnimate")) otherMenu->addAction(tr("Animation") + " (Glaxnimate)", this, SLOT(onOpenOtherTriggered()))->setObjectName("glaxnimate"); if (mltProducers->get_data("noise")) otherMenu->addAction(tr("Noise"), this, SLOT(onOpenOtherTriggered()))->setObjectName("noise"); if (mltProducers->get_data("frei0r.ising0r")) otherMenu->addAction(tr("Ising"), this, SLOT(onOpenOtherTriggered()))->setObjectName("ising0r"); if (mltProducers->get_data("frei0r.lissajous0r")) otherMenu->addAction(tr("Lissajous"), this, SLOT(onOpenOtherTriggered()))->setObjectName("lissajous0r"); if (mltProducers->get_data("frei0r.plasma")) otherMenu->addAction(tr("Plasma"), this, SLOT(onOpenOtherTriggered()))->setObjectName("plasma"); if (mltProducers->get_data("frei0r.test_pat_B")) otherMenu->addAction(tr("Color Bars"), this, SLOT(onOpenOtherTriggered()))->setObjectName("test_pat_B"); if (mltProducers->get_data("tone")) otherMenu->addAction(tr("Audio Tone"), this, SLOT(onOpenOtherTriggered()))->setObjectName("tone"); if (mltProducers->get_data("count")) otherMenu->addAction(tr("Count"), this, SLOT(onOpenOtherTriggered()))->setObjectName("count"); if (mltProducers->get_data("blipflash")) otherMenu->addAction(tr("Blip Flash"), this, SLOT(onOpenOtherTriggered()))->setObjectName("blipflash"); #if defined(Q_OS_UNIX) && !defined(Q_OS_MAC) otherMenu->addAction(tr("Video4Linux"), this, SLOT(onOpenOtherTriggered()))->setObjectName("v4l2"); otherMenu->addAction(tr("PulseAudio"), this, SLOT(onOpenOtherTriggered()))->setObjectName("pulse"); otherMenu->addAction(tr("JACK Audio"), this, SLOT(onOpenOtherTriggered()))->setObjectName("jack"); otherMenu->addAction(tr("ALSA Audio"), this, SLOT(onOpenOtherTriggered()))->setObjectName("alsa"); #elif defined(Q_OS_WIN) || defined(Q_OS_MAC) otherMenu->addAction(tr("Audio/Video Device"), this, SLOT(onOpenOtherTriggered()))->setObjectName("device"); #endif if (mltProducers->get_data("decklink")) otherMenu->addAction(tr("SDI/HDMI"), this, SLOT(onOpenOtherTriggered()))->setObjectName("decklink"); } QAction *MainWindow::addProfile(QActionGroup *actionGroup, const QString &desc, const QString &name) { QAction *action = new QAction(desc, this); action->setCheckable(true); action->setData(name); actionGroup->addAction(action); return action; } QAction *MainWindow::addLayout(QActionGroup *actionGroup, const QString &name) { QAction *action = new QAction(name, this); actionGroup->addAction(action); return action; } void MainWindow::open(Mlt::Producer *producer) { if (!producer->is_valid()) showStatusMessage(tr("Failed to open ")); else if (producer->get_int("error")) showStatusMessage(tr("Failed to open ") + producer->get("resource")); // bool ok = false; // int screen = Settings.playerExternal().toInt(&ok); // if (ok && screen < QGuiApplication::screens().count() // && QGuiApplication::screens().at(screen) != this->screen()) { // m_player->moveVideoToScreen(screen); // } // no else here because open() will delete the producer if open fails if (!MLT.setProducer(producer)) { emit producerOpened(); if (MLT.URL().endsWith(".mlt") || MLT.URL().endsWith(".xml")) { m_filterController->motionTrackerModel()->load(); emit profileChanged(); } else if (!MLT.profile().is_explicit()) { emit profileChanged(); } } m_player->setFocus(); emit m_playlistDock->enableUpdate(false); // Needed on Windows. Upon first file open, window is deactivated, perhaps OpenGL-related. activateWindow(); } bool MainWindow::isCompatibleWithGpuMode(MltXmlChecker &checker) { if (checker.needsGPU() && !Settings.playerGPU()) { LOG_INFO() << "file uses GPU but GPU not enabled"; QMessageBox dialog(QMessageBox::Warning, qApp->applicationName(), tr("The file you opened uses GPU effects, but GPU effects are not enabled."), QMessageBox::Ok, this); dialog.setWindowModality(QmlApplication::dialogModality()); dialog.setDefaultButton(QMessageBox::Ok); dialog.setEscapeButton(QMessageBox::Ok); dialog.exec(); return false; } else if (checker.needsCPU() && Settings.playerGPU()) { LOG_INFO() << "file uses GPU incompatible filters but GPU is enabled"; QMessageBox dialog(QMessageBox::Question, qApp->applicationName(), tr("The file you opened uses CPU effects that are incompatible with GPU effects, but GPU effects are enabled.\n" "Do you want to disable GPU effects and restart?"), QMessageBox::No | QMessageBox::Yes, this); dialog.setWindowModality(QmlApplication::dialogModality()); dialog.setDefaultButton(QMessageBox::Yes); dialog.setEscapeButton(QMessageBox::No); int r = dialog.exec(); if (r == QMessageBox::Yes) { ui->actionGPU->setChecked(false); m_exitCode = EXIT_RESTART; QApplication::closeAllWindows(); } return false; } return true; } bool MainWindow::saveRepairedXmlFile(MltXmlChecker &checker, QString &fileName) { QFileInfo fi(fileName); auto filename = QStringLiteral("%1/%2 - %3.%4").arg(fi.path(), fi.completeBaseName(), tr("Repaired"), fi.suffix()); auto caption = tr("Save Repaired XML"); filename = QFileDialog::getSaveFileName(this, caption, filename, tr("MLT XML (*.mlt)"), nullptr, Util::getFileDialogOptions()); if (!filename.isEmpty()) { QFile repaired(filename); repaired.open(QIODevice::WriteOnly); LOG_INFO() << "repaired MLT XML file name" << repaired.fileName(); if (checker.tempFile().exists()) { checker.tempFile().open(); QByteArray xml = checker.tempFile().readAll(); checker.tempFile().close(); if (Settings.proxyEnabled()) { auto s = QString::fromUtf8(xml); if (ProxyManager::filterXML(s, QDir::fromNativeSeparators(fi.absolutePath()))) { xml = s.toUtf8(); } } qint64 n = repaired.write(xml); while (n > 0 && n < xml.size()) { qint64 x = repaired.write(xml.right(xml.size() - n)); if (x > 0) n += x; else n = x; } repaired.close(); if (n == xml.size()) { fileName = repaired.fileName(); return true; } } QMessageBox::warning(this, qApp->applicationName(), tr("Repairing the project failed.")); LOG_WARNING() << "repairing failed"; } return false; } bool MainWindow::isXmlRepaired(MltXmlChecker &checker, QString &fileName) { bool result = true; if (checker.isCorrected()) { LOG_WARNING() << fileName; QMessageBox dialog(QMessageBox::Question, qApp->applicationName(), tr("Shotcut noticed some problems in your project.\n" "Do you want Shotcut to try to repair it?\n\n" "If you choose Yes, Shotcut will create a copy of your project\n" "with \"- Repaired\" in the file name and open it."), QMessageBox::No | QMessageBox::Yes, this); dialog.setWindowModality(QmlApplication::dialogModality()); dialog.setDefaultButton(QMessageBox::Yes); dialog.setEscapeButton(QMessageBox::No); int r = dialog.exec(); if (r == QMessageBox::Yes) result = saveRepairedXmlFile(checker, fileName); } else if (checker.unlinkedFilesModel().rowCount() > 0) { UnlinkedFilesDialog dialog(this); dialog.setModel(checker.unlinkedFilesModel()); dialog.setWindowModality(QmlApplication::dialogModality()); if (dialog.exec() == QDialog::Accepted) { if (checker.check(fileName) == QXmlStreamReader::NoError && checker.isCorrected()) result = saveRepairedXmlFile(checker, fileName); } else { result = false; } } return result; } bool MainWindow::checkAutoSave(QString &url) { QMutexLocker locker(&m_autosaveMutex); // check whether autosave files exist: QSharedPointer<AutoSaveFile> stale(AutoSaveFile::getFile(url)); if (stale) { QMessageBox dialog(QMessageBox::Question, qApp->applicationName(), tr("Auto-saved files exist. Do you want to recover them now?"), QMessageBox::No | QMessageBox::Yes, this); dialog.setWindowModality(QmlApplication::dialogModality()); dialog.setDefaultButton(QMessageBox::Yes); dialog.setEscapeButton(QMessageBox::No); int r = dialog.exec(); if (r == QMessageBox::Yes) { if (!stale->open(QIODevice::ReadWrite)) { LOG_WARNING() << "failed to recover autosave file" << url; } else { m_autosaveFile = stale; url = stale->fileName(); return true; } } } // create new autosave object m_autosaveFile.reset(new AutoSaveFile(url)); return false; } void MainWindow::doAutosave() { QMutexLocker locker(&m_autosaveMutex); if (m_autosaveFile) { bool success = false; if (m_autosaveFile->isOpen() || m_autosaveFile->open(QIODevice::ReadWrite)) { m_autosaveFile->close(); success = saveXML(m_autosaveFile->fileName(), false /* without relative paths */); m_autosaveFile->open(QIODevice::ReadWrite); } if (!success) { LOG_ERROR() << "failed to open autosave file for writing" << m_autosaveFile->fileName(); } } } void MainWindow::setFullScreen(bool isFullScreen) { if (isFullScreen) { showFullScreen(); ui->actionEnterFullScreen->setVisible(false); } } QString MainWindow::untitledFileName() const { QDir dir = Settings.appDataLocation(); if (!dir.exists()) dir.mkpath(dir.path()); return dir.filePath("__untitled__.mlt"); } void MainWindow::setProfile(const QString &profile_name) { LOG_DEBUG() << profile_name; MLT.setProfile(profile_name); emit profileChanged(); } bool MainWindow::isSourceClipMyProject(QString resource, bool withDialog) { if (m_player->tabIndex() == Player::ProjectTabIndex && MLT.savedProducer() && MLT.savedProducer()->is_valid()) resource = QString::fromUtf8(MLT.savedProducer()->get("resource")); if (!resource.isEmpty() && QDir(resource) == QDir(fileName())) { if (withDialog) { QMessageBox dialog(QMessageBox::Information, qApp->applicationName(), tr("You cannot add a project to itself!"), QMessageBox::Ok, this); dialog.setDefaultButton(QMessageBox::Ok); dialog.setEscapeButton(QMessageBox::Ok); dialog.setWindowModality(QmlApplication::dialogModality()); dialog.exec(); } return true; } return false; } bool MainWindow::keyframesDockIsVisible() const { return m_keyframesDock && m_keyframesDock->isVisible(); } void MainWindow::setAudioChannels(int channels) { LOG_DEBUG() << channels; MLT.videoWidget()->setProperty("audio_channels", channels); MLT.setAudioChannels(channels); if (channels == 1) ui->actionChannels1->setChecked(true); else if (channels == 2) ui->actionChannels2->setChecked(true); else if (channels == 4) ui->actionChannels4->setChecked(true); else if (channels == 6) ui->actionChannels6->setChecked(true); emit audioChannelsChanged(); } void MainWindow::showSaveError() { QMessageBox dialog(QMessageBox::Critical, qApp->applicationName(), tr("There was an error saving. Please try again."), QMessageBox::Ok, this); dialog.setDefaultButton(QMessageBox::Ok); dialog.setEscapeButton(QMessageBox::Ok); dialog.setWindowModality(QmlApplication::dialogModality()); dialog.exec(); } void MainWindow::setPreviewScale(int scale) { LOG_DEBUG() << scale; switch (scale) { case 360: ui->actionPreview360->setChecked(true); break; case 540: ui->actionPreview540->setChecked(true); break; case 720: ui->actionPreview720->setChecked(true); break; default: ui->actionPreviewNone->setChecked(true); break; } MLT.setPreviewScale(scale); MLT.refreshConsumer(); } void MainWindow::setVideoModeMenu() { // Find a matching video mode for (const auto action : m_profileGroup->actions()) { auto s = action->data().toString(); Mlt::Profile profile(s.toUtf8().constData()); if (MLT.profile().width() == profile.width() && MLT.profile().height() == profile.height() && MLT.profile().sample_aspect_num() == profile.sample_aspect_num() && MLT.profile().sample_aspect_den() == profile.sample_aspect_den() && MLT.profile().frame_rate_num() == profile.frame_rate_num() && MLT.profile().frame_rate_den() == profile.frame_rate_den() && MLT.profile().colorspace() == profile.colorspace() && MLT.profile().progressive() == profile.progressive()) { // Select it action->setChecked(true); return; } } // Choose Automatic if nothing found m_profileGroup->actions().first()->setChecked(true); } void MainWindow::resetVideoModeMenu() { // Change selected Video Mode back to Settings for (const auto action : m_profileGroup->actions()) { if (action->data().toString() == Settings.playerProfile()) { action->setChecked(true); break; } } } void MainWindow::resetDockCorners() { setCorner(Qt::TopLeftCorner, Qt::LeftDockWidgetArea); setCorner(Qt::TopRightCorner, Qt::RightDockWidgetArea); setCorner(Qt::BottomLeftCorner, Qt::BottomDockWidgetArea); setCorner(Qt::BottomRightCorner, Qt::BottomDockWidgetArea); } void MainWindow::showIncompatibleProjectMessage(const QString &shotcutVersion) { LOG_INFO() << shotcutVersion; QMessageBox dialog(QMessageBox::Information, qApp->applicationName(), tr("This project file requires a newer version!\n\n" "It was made with version ") + shotcutVersion, QMessageBox::Ok, this); dialog.setDefaultButton(QMessageBox::Ok); dialog.setEscapeButton(QMessageBox::Ok); dialog.setWindowModality(QmlApplication::dialogModality()); dialog.exec(); } static void autosaveTask(MainWindow *p) { LOG_DEBUG_TIME(); p->doAutosave(); } void MainWindow::onAutosaveTimeout() { if (isWindowModified()) { // Automatic backup backupPeriodically(); // Auto-save to recovery file auto result = QtConcurrent::run(autosaveTask, this); } static QMessageBox *dialog = nullptr; if (!dialog) { dialog = new QMessageBox(QMessageBox::Critical, qApp->applicationName(), tr("You are running low on available memory!\n\n" "Please close other applications or web browser tabs and retry.\n" "Or save and restart Shotcut."), QMessageBox::Retry | QMessageBox::Save | QMessageBox::Ignore, this); dialog->setDefaultButton(QMessageBox::Retry); dialog->setEscapeButton(QMessageBox::Ignore); dialog->setWindowModality(QmlApplication::dialogModality()); connect(dialog, &QDialog::finished, this, [&](int result) { switch (result) { case QMessageBox::Save: on_actionBackupSave_triggered(); m_exitCode = EXIT_RESTART; QApplication::closeAllWindows(); break; case QMessageBox::Retry: onAutosaveTimeout(); break; default: JOBS.resumeCurrent(); break; } }); } if (Settings.warnLowMemory()) { if (Util::isMemoryLow()) { MLT.pause(); JOBS.pauseCurrent(); dialog->show(); } else if (dialog->isVisible()) { dialog->hide(); QCoreApplication::processEvents(); JOBS.resumeCurrent(); } } } bool MainWindow::open(QString url, const Mlt::Properties *properties, bool play, bool skipConvert) { // returns false when MLT is unable to open the file, possibly because it has percent sign in the path LOG_DEBUG() << url; bool modified = false; MltXmlChecker checker; QFileInfo info(url); if (info.isRelative()) { QDir pwd(QDir::currentPath()); url = pwd.filePath(url); info.setFile(url); } if (url.endsWith(".mlt") || url.endsWith(".xml")) { if (url != untitledFileName()) { showStatusMessage(tr("Opening %1").arg(url)); QCoreApplication::processEvents(); } switch (checker.check(url)) { case QXmlStreamReader::NoError: if (!isCompatibleWithGpuMode(checker)) { showStatusMessage(tr("Failed to open ").append(url)); return true; } break; case QXmlStreamReader::CustomError: showIncompatibleProjectMessage(checker.shotcutVersion()); return true; default: showStatusMessage(tr("Failed to open ").append(url)); return true; } // only check for a modified project when loading a project, not a simple producer if (!continueModified()) return true; QCoreApplication::processEvents(); // close existing project if (playlist()) m_playlistDock->model()->close(); if (multitrack()) m_timelineDock->model()->close(); MLT.purgeMemoryPool(); if (!isXmlRepaired(checker, url)) return true; modified = checkAutoSave(url); if (modified) { if (checker.check(url) == QXmlStreamReader::NoError) { if (!isCompatibleWithGpuMode(checker)) return true; } else { showStatusMessage(tr("Failed to open ").append(url)); showIncompatibleProjectMessage(checker.shotcutVersion()); return true; } if (!isXmlRepaired(checker, url)) return true; } // let the new project change the profile if (modified || QFile::exists(url)) { MLT.profile().set_explicit(false); setWindowModified(modified); resetSourceUpdated(); } } if (!playlist() && !multitrack()) { if (!modified && !continueModified()) return true; setCurrentFile(""); setWindowModified(modified); sourceUpdated(); MLT.resetURL(); // Return to automatic video mode if selected. if (m_profileGroup->checkedAction() && m_profileGroup->checkedAction()->data().toString().isEmpty()) MLT.profile().set_explicit(false); } QString urlToOpen = checker.isUpdated() ? checker.tempFile().fileName() : url; if (!MLT.open(QDir::fromNativeSeparators(urlToOpen), QDir::fromNativeSeparators(url), skipConvert) && MLT.producer() && MLT.producer()->is_valid()) { Mlt::Properties *props = const_cast<Mlt::Properties *>(properties); if (props && props->is_valid()) mlt_properties_inherit(MLT.producer()->get_properties(), props->get_properties()); m_player->setPauseAfterOpen(!play || !MLT.isClip()); setAudioChannels(MLT.audioChannels()); if (url.endsWith(".mlt") || url.endsWith(".xml")) { if (MLT.producer()->get_int(kShotcutProjectFolder)) { MLT.setProjectFolder(info.absolutePath()); ProxyManager::removePending(); } else { MLT.setProjectFolder(QString()); } setVideoModeMenu(); m_notesDock->setText(MLT.producer()->get(kShotcutProjectNote)); } open(MLT.producer()); if (url.startsWith(AutoSaveFile::path())) { QMutexLocker locker(&m_autosaveMutex); if (m_autosaveFile && m_autosaveFile->managedFileName() != untitledFileName()) { m_recentDock->add(m_autosaveFile->managedFileName()); LOG_INFO() << m_autosaveFile->managedFileName(); } } else { m_recentDock->add(url); LOG_INFO() << url; } } else if (url != untitledFileName()) { showStatusMessage(tr("Failed to open ") + url); emit openFailed(url); return false; } return true; } // This one is invoked from the command line. void MainWindow::openMultiple(const QStringList &paths) { if (paths.size() > 1) { QList<QUrl> urls; foreach (const QString &s, paths) urls << s; openMultiple(urls); } else if (!paths.isEmpty()) { open(paths.first()); } } // This one is invoked from above (command line) or drag-n-drop. void MainWindow::openMultiple(const QList<QUrl> &urls) { if (urls.size() > 1) { m_multipleFiles = Util::sortedFileList(Util::expandDirectories(urls)); open(m_multipleFiles.first(), nullptr, true, true); } else if (urls.size() > 0) { QUrl url = urls.first(); if (!open(Util::removeFileScheme(url))) open(Util::removeFileScheme(url, false)); } } // This is one is invoked from the action. void MainWindow::openVideo() { QString path = Settings.openPath(); #ifdef Q_OS_MAC path.append("/*"); #endif LOG_DEBUG() << Util::getFileDialogOptions(); QStringList filenames = QFileDialog::getOpenFileNames(this, tr("Open File"), path, tr("All Files (*);;MLT XML (*.mlt)"), nullptr, Util::getFileDialogOptions()); if (filenames.length() > 0) { Settings.setOpenPath(QFileInfo(filenames.first()).path()); activateWindow(); if (filenames.length() > 1) m_multipleFiles = filenames; open(filenames.first(), nullptr, true, filenames.length() > 1); } else { // If file invalid, then on some platforms the dialog messes up SDL. MLT.onWindowResize(); activateWindow(); } } void MainWindow::openCut(Mlt::Producer *producer, bool play) { m_player->setPauseAfterOpen(!play); open(producer); MLT.seek(producer->get_in()); } void MainWindow::hideProducer() { // This is a hack to release references to the old producer, but it // probably leaves a reference to the new color producer somewhere not // yet identified (root cause). openCut(new Mlt::Producer(MLT.profile(), "color:_hide")); QCoreApplication::processEvents(); openCut(new Mlt::Producer(MLT.profile(), "color:_hide")); QCoreApplication::processEvents(); QScrollArea *scrollArea = (QScrollArea *) m_propertiesDock->widget(); delete scrollArea->widget(); scrollArea->setWidget(nullptr); m_player->reset(); QCoreApplication::processEvents(); } void MainWindow::closeProducer() { QCoreApplication::processEvents(); hideProducer(); m_filterController->motionTrackerModel()->load(); MLT.close(); MLT.setSavedProducer(nullptr); } void MainWindow::showStatusMessage(QAction *action, int timeoutSeconds) { // This object takes ownership of the passed action. // This version does not currently log its message. m_statusBarAction.reset(action); action->setParent(nullptr); m_player->setStatusLabel(action->text(), timeoutSeconds, action); } void MainWindow::showStatusMessage(const QString &message, int timeoutSeconds, QPalette::ColorRole role) { LOG_INFO() << message; auto action = new QAction; connect(action, SIGNAL(triggered()), this, SLOT(onStatusMessageClicked())); m_statusBarAction.reset(action); m_player->setStatusLabel(message, timeoutSeconds, action, role); } void MainWindow::onStatusMessageClicked() { showStatusMessage(QString(), 0); } void MainWindow::seekPlaylist(int start) { if (!playlist()) return; // we bypass this->open() to prevent sending producerOpened signal to self, which causes to reload playlist if (!MLT.producer() || (void *) MLT.producer()->get_producer() != (void *) playlist()->get_playlist()) MLT.setProducer(new Mlt::Producer(*playlist())); m_player->setIn(-1); m_player->setOut(-1); // since we do not emit producerOpened, these components need updating on_actionJack_triggered(ui->actionJack && ui->actionJack->isChecked()); m_player->onProducerOpened(false); m_encodeDock->onProducerOpened(); m_filterController->setProducer(); updateMarkers(); MLT.seek(start); m_player->setFocus(); m_player->switchToTab(Player::ProjectTabIndex); } void MainWindow::seekTimeline(int position, bool seekPlayer) { if (!multitrack()) return; // we bypass this->open() to prevent sending producerOpened signal to self, which causes to reload playlist if (MLT.producer() && (void *) MLT.producer()->get_producer() != (void *) multitrack()->get_producer()) { MLT.setProducer(new Mlt::Producer(*multitrack())); m_player->setIn(-1); m_player->setOut(-1); // since we do not emit producerOpened, these components need updating on_actionJack_triggered(ui->actionJack && ui->actionJack->isChecked()); m_player->onProducerOpened(false); m_encodeDock->onProducerOpened(); m_filterController->setProducer(); updateMarkers(); m_player->setFocus(); m_player->switchToTab(Player::ProjectTabIndex); } if (seekPlayer) m_player->seek(position); else m_player->pause(); } void MainWindow::seekKeyframes(int position) { m_player->seek(position); } void MainWindow::readPlayerSettings() { LOG_DEBUG() << "begin"; ui->actionRealtime->setChecked(Settings.playerRealtime()); ui->actionProgressive->setChecked(Settings.playerProgressive()); ui->actionScrubAudio->setChecked(Settings.playerScrubAudio()); if (ui->actionJack) ui->actionJack->setChecked(Settings.playerJACK()); if (ui->actionGPU) ui->actionGPU->setChecked(Settings.playerGPU()); QString external = Settings.playerExternal(); bool ok = false; external.toInt(&ok); auto isExternalPeripheral = !external.isEmpty() && !ok; setAudioChannels(Settings.playerAudioChannels()); if (isExternalPeripheral) { setPreviewScale(0); m_previewScaleGroup->setEnabled(false); } else { setPreviewScale(Settings.playerPreviewScale()); m_previewScaleGroup->setEnabled(true); } QString deinterlacer = Settings.playerDeinterlacer(); QString interpolation = Settings.playerInterpolation(); if (deinterlacer == "onefield") ui->actionOneField->setChecked(true); else if (deinterlacer == "linearblend") ui->actionLinearBlend->setChecked(true); else if (deinterlacer == "yadif-nospatial") ui->actionYadifTemporal->setChecked(true); else if (deinterlacer == "yadif") ui->actionYadifSpatial->setChecked(true); else ui->actionBwdif->setChecked(true); if (interpolation == "nearest") ui->actionNearest->setChecked(true); else if (interpolation == "bilinear") ui->actionBilinear->setChecked(true); else if (interpolation == "bicubic") ui->actionBicubic->setChecked(true); else ui->actionHyper->setChecked(true); foreach (QAction *a, m_externalGroup->actions()) { #ifndef USE_SCREENS_FOR_EXTERNAL_MONITORING if (isExternalPeripheral) #endif if (a->data() == external) { a->setChecked(true); if (a->data().toString().startsWith("decklink") && m_keyerMenu) m_keyerMenu->setEnabled(true); break; } } if (m_keyerGroup) { int keyer = Settings.playerKeyerMode(); foreach (QAction *a, m_keyerGroup->actions()) { if (a->data() == keyer) { a->setChecked(true); break; } } } QString profile = Settings.playerProfile(); // Automatic not permitted for SDI/HDMI if (isExternalPeripheral && profile.isEmpty()) profile = "atsc_720p_50"; foreach (QAction *a, m_profileGroup->actions()) { // Automatic not permitted for SDI/HDMI if (a->data().toString().isEmpty() && !external.isEmpty() && !ok) a->setDisabled(true); if (a->data().toString() == profile) { a->setChecked(true); break; } } #if defined(Q_OS_WIN) || defined(Q_OS_LINUX) if (!::qEnvironmentVariableIsSet("SDL_AUDIODRIVER")) { ::qputenv("SDL_AUDIODRIVER", Settings.playerAudioDriver().toLocal8Bit().constData()); } #endif LOG_DEBUG() << "end"; } void MainWindow::readWindowSettings() { LOG_DEBUG() << "begin"; Settings.setWindowGeometryDefault(saveGeometry()); Settings.setWindowStateDefault(saveState()); Settings.sync(); if (!Settings.windowGeometry().isEmpty()) { restoreState(Settings.windowState()); restoreGeometry(Settings.windowGeometry()); } else { restoreState(kLayoutEditingDefault); } LOG_DEBUG() << "end"; } void MainWindow::setupActions() { QAction *action; // Setup these actions as separators ui->actionProject->setSeparator(true); ui->actionUser_Interface->setSeparator(true); // Setup full screen action action = ui->actionEnterFullScreen; QList<QKeySequence> fullScreenShortcuts; #ifdef Q_OS_MAC fullScreenShortcuts << QKeySequence(Qt::CTRL | Qt::META | Qt::Key_F); fullScreenShortcuts << QKeySequence(Qt::Key_F11); action->setShortcuts(fullScreenShortcuts); action = new QAction(tr("Preferences"), this); action->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_Comma)); connect(action, &QAction::triggered, this, &MainWindow::showSettingsMenu); ui->menuEdit->addAction(action); #else fullScreenShortcuts << QKeySequence(Qt::Key_F11); fullScreenShortcuts << QKeySequence(Qt::CTRL | Qt::SHIFT | Qt::Key_F); action->setShortcuts(fullScreenShortcuts); #endif action = new QAction(tr("Rename Clip"), this); action->setShortcut(QKeySequence(Qt::Key_F2)); connect(action, &QAction::triggered, this, [&]() { onPropertiesDockTriggered(true); emit renameRequested(); }); addAction(action); Actions.add("propertiesRenameClipAction", action, tr("Properties")); action = new QAction(tr("Find"), this); action->setShortcut(QKeySequence(Qt::Key_F3)); connect(action, &QAction::triggered, this, [&]() { onRecentDockTriggered(true); m_recentDock->find(); }); addAction(action); Actions.add("recentFindAction", action, tr("Recent")); action = new QAction(tr("Reload"), this); action->setShortcut(QKeySequence(Qt::Key_F5)); connect(action, &QAction::triggered, this, [&]() { m_timelineDock->model()->reload(); m_keyframesDock->model().reload(); m_filtersDock->load(); }); addAction(action); Actions.add("timelineReload", action, tr("Timeline")); Actions.loadFromMenu(ui->menuFile); Actions.loadFromMenu(ui->menuEdit); Actions.loadFromMenu(ui->menuView); Actions.loadFromMenu(ui->menuPlayer); Actions.loadFromMenu(ui->menuSettings); Actions.loadFromMenu(ui->menuHelp); auto shortcuts {ui->actionKeyboardShortcuts->shortcuts()}; shortcuts << QKeySequence(Qt::Key_Slash); ui->actionKeyboardShortcuts->setShortcuts(shortcuts); // Shortcuts for actions that are only in context menus do not work unless // they are added to something visible. addAction(Actions["timelineMergeWithNextAction"]); addAction(Actions["timelineDetachAudioAction"]); addAction(Actions["timelineAlignToReferenceAction"]); addAction(Actions["timelineUpdateThumbnailsAction"]); addAction(Actions["timelineRebuildAudioWaveformAction"]); addAction(Actions["keyframesTypePrevHoldAction"]); addAction(Actions["keyframesTypePrevLinearAction"]); addAction(Actions["keyframesTypePrevSmoothNaturalAction"]); addAction(Actions["keyframesTypePrevEaseOutSinuAction"]); addAction(Actions["keyframesTypePrevEaseOutQuadAction"]); addAction(Actions["keyframesTypePrevEaseOutCubeAction"]); addAction(Actions["keyframesTypePrevEaseOutQuartAction"]); addAction(Actions["keyframesTypePrevEaseOutQuintAction"]); addAction(Actions["keyframesTypePrevEaseOutExpoAction"]); addAction(Actions["keyframesTypePrevEaseOutCircAction"]); addAction(Actions["keyframesTypePrevEaseOutBackAction"]); addAction(Actions["keyframesTypePrevEaseOutElasAction"]); addAction(Actions["keyframesTypePrevEaseOutBounAction"]); addAction(Actions["keyframesTypeHoldAction"]); addAction(Actions["keyframesTypeLinearAction"]); addAction(Actions["keyframesTypeSmoothNaturalAction"]); addAction(Actions["keyframesTypeEaseInSinuAction"]); addAction(Actions["keyframesTypeEaseInQuadAction"]); addAction(Actions["keyframesTypeEaseInCubeAction"]); addAction(Actions["keyframesTypeEaseInQuartAction"]); addAction(Actions["keyframesTypeEaseInQuintAction"]); addAction(Actions["keyframesTypeEaseInExpoAction"]); addAction(Actions["keyframesTypeEaseInCircAction"]); addAction(Actions["keyframesTypeEaseInBackAction"]); addAction(Actions["keyframesTypeEaseInElasAction"]); addAction(Actions["keyframesTypeEaseInBounAction"]); addAction(Actions["keyframesTypeEaseInOutSinuAction"]); addAction(Actions["keyframesTypeEaseInOutQuadAction"]); addAction(Actions["keyframesTypeEaseInOutCubeAction"]); addAction(Actions["keyframesTypeEaseInOutQuartAction"]); addAction(Actions["keyframesTypeEaseInOutQuintAction"]); addAction(Actions["keyframesTypeEaseInOutExpoAction"]); addAction(Actions["keyframesTypeEaseInOutCircAction"]); addAction(Actions["keyframesTypeEaseInOutBackAction"]); addAction(Actions["keyframesTypeEaseInOutElasAction"]); addAction(Actions["keyframesTypeEaseInOutBounAction"]); addAction(Actions["keyframesRemoveAction"]); Actions.initializeShortcuts(); } void MainWindow::writeSettings() { #ifndef Q_OS_MAC if (isFullScreen()) showNormal(); #endif Settings.setPlayerGPU(ui->actionGPU->isChecked()); Settings.setWindowGeometry(saveGeometry()); Settings.setWindowState(saveState()); Settings.sync(); } void MainWindow::configureVideoWidget() { LOG_DEBUG() << "begin"; if (m_profileGroup->checkedAction()) setProfile(m_profileGroup->checkedAction()->data().toString()); MLT.videoWidget()->setProperty("realtime", ui->actionRealtime->isChecked()); bool ok = false; m_externalGroup->checkedAction()->data().toInt(&ok); if (!ui->menuExternal || m_externalGroup->checkedAction()->data().toString().isEmpty() || ok) { MLT.videoWidget()->setProperty("progressive", ui->actionProgressive->isChecked()); } else { // DeckLink external monitor must strictly follow video mode MLT.videoWidget()->setProperty("mlt_service", m_externalGroup->checkedAction()->data()); MLT.videoWidget()->setProperty("progressive", MLT.profile().progressive()); ui->actionProgressive->setEnabled(false); } if (ui->actionChannels1->isChecked()) setAudioChannels(1); else if (ui->actionChannels2->isChecked()) setAudioChannels(2); else if (ui->actionChannels4->isChecked()) setAudioChannels(4); else setAudioChannels(6); if (ui->actionOneField->isChecked()) MLT.videoWidget()->setProperty("deinterlacer", "onefield"); else if (ui->actionLinearBlend->isChecked()) MLT.videoWidget()->setProperty("deinterlacer", "linearblend"); else if (ui->actionYadifTemporal->isChecked()) MLT.videoWidget()->setProperty("deinterlacer", "yadif-nospatial"); else if (ui->actionYadifSpatial->isChecked()) MLT.videoWidget()->setProperty("deinterlacer", "yadif"); else MLT.videoWidget()->setProperty("deinterlacer", "bwdif"); if (ui->actionNearest->isChecked()) MLT.videoWidget()->setProperty("rescale", "nearest"); else if (ui->actionBilinear->isChecked()) MLT.videoWidget()->setProperty("rescale", "bilinear"); else if (ui->actionBicubic->isChecked()) MLT.videoWidget()->setProperty("rescale", "bicubic"); else MLT.videoWidget()->setProperty("rescale", "hyper"); if (m_keyerGroup) MLT.videoWidget()->setProperty("keyer", m_keyerGroup->checkedAction()->data()); LOG_DEBUG() << "end"; } void MainWindow::setCurrentFile(const QString &filename) { QString shownName = tr("Untitled"); if (filename == untitledFileName()) m_currentFile.clear(); else m_currentFile = filename; if (!m_currentFile.isEmpty()) shownName = QFileInfo(m_currentFile).fileName(); #ifdef Q_OS_MAC setWindowTitle(QStringLiteral("%1 - %2").arg(shownName).arg(qApp->applicationName())); #else setWindowTitle(QStringLiteral("%1[*] - %2").arg(shownName).arg(qApp->applicationName())); #endif ui->actionShowProjectFolder->setDisabled(m_currentFile.isEmpty()); } void MainWindow::on_actionAbout_Shotcut_triggered() { const auto copyright = QStringLiteral("Copyright &copy; 2011-2024 <a href=\"https://www.meltytech.com/\">Meltytech</a>, LLC"); const auto license = QStringLiteral("<a href=\"https://www.gnu.org/licenses/gpl.html\">GNU General Public License v3.0</a>"); const auto url = QStringLiteral("https://www.shotcut.org/"); QMessageBox::about(this, tr("About %1").arg(qApp->applicationName()), QStringLiteral("<h1>Shotcut version %2</h1>" "<p><a href=\"%3\">%1</a> is a free, open source, cross platform video editor.</p>" "<small><p>%4</p>" "<p>Licensed under the %5</p>" "<p>This program proudly uses the following projects:<ul>" "<li><a href=\"https://www.qt.io/\">Qt</a> application and UI framework</li>" "<li><a href=\"https://www.mltframework.org/\">MLT</a> multimedia authoring framework</li>" "<li><a href=\"https://www.ffmpeg.org/\">FFmpeg</a> multimedia format and codec libraries</li>" "<li><a href=\"https://www.videolan.org/developers/x264.html\">x264</a> H.264 encoder</li>" "<li><a href=\"https://www.videolan.org/projects/dav1d.html\">dav1d</a> AV1 decoder</li>" "<li><a href=\"https://gitlab.com/AOMediaCodec/SVT-AV1\">SVT-AV1</a> AV1 encoder</li>" "<li><a href=\"https://opus-codec.org/\">Opus</a> audio codec</li>" "<li><a href=\"https://www.dyne.org/software/frei0r/\">Frei0r</a> video plugins</li>" "<li><a href=\"https://www.ladspa.org/\">LADSPA</a> audio plugins</li>" "<li><a href=\"https://glaxnimate.mattbas.org/\">Glaxnimate</a> vector animation program</li>" "</ul></p>" "<p>The source code used to build this program can be downloaded from " "<a href=\"%3\">%3</a>.</p>" "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.</small>" ).arg(qApp->applicationName(), qApp->applicationVersion(), url, copyright, license)); } void MainWindow::keyPressEvent(QKeyEvent *event) { if (event->isAccepted()) return; bool handled = true; switch (event->key()) { case Qt::Key_J: if (m_isKKeyPressed) m_player->seek(m_player->position() - 1); else m_player->rewind(false); break; case Qt::Key_K: m_player->pause(); m_isKKeyPressed = true; break; case Qt::Key_L: if (event->modifiers() == Qt::NoModifier) { if (m_isKKeyPressed) m_player->seek(m_player->position() + 1); else m_player->fastForward(false); } break; case Qt::Key_F12: LOG_DEBUG() << "event isAccepted:" << event->isAccepted(); LOG_DEBUG() << "Current focusWidget:" << QApplication::focusWidget(); LOG_DEBUG() << "Current focusObject:" << QApplication::focusObject(); LOG_DEBUG() << "Current focusWindow:" << QApplication::focusWindow(); handled = false; break; default: handled = false; break; } if (handled) event->setAccepted(handled); else QMainWindow::keyPressEvent(event); } void MainWindow::keyReleaseEvent(QKeyEvent *event) { if (event->key() == Qt::Key_K) { m_isKKeyPressed = false; event->setAccepted(true); } else { QMainWindow::keyReleaseEvent(event); } } void MainWindow::hideSetDataDirectory() { ui->actionAppDataSet->setVisible(false); } QAction *MainWindow::actionAddCustomProfile() const { return ui->actionAddCustomProfile; } QAction *MainWindow::actionProfileRemove() const { return ui->actionProfileRemove; } void MainWindow::buildVideoModeMenu(QMenu *topMenu, QMenu *&customMenu, QActionGroup *group, QAction *addAction, QAction *removeAction) { topMenu->addAction(addProfile(group, "HD 720p 50 fps", "atsc_720p_50")); topMenu->addAction(addProfile(group, "HD 720p 59.94 fps", "atsc_720p_5994")); topMenu->addAction(addProfile(group, "HD 720p 60 fps", "atsc_720p_60")); topMenu->addAction(addProfile(group, "HD 1080i 25 fps", "atsc_1080i_50")); topMenu->addAction(addProfile(group, "HD 1080i 29.97 fps", "atsc_1080i_5994")); topMenu->addAction(addProfile(group, "HD 1080p 23.98 fps", "atsc_1080p_2398")); topMenu->addAction(addProfile(group, "HD 1080p 24 fps", "atsc_1080p_24")); topMenu->addAction(addProfile(group, "HD 1080p 25 fps", "atsc_1080p_25")); topMenu->addAction(addProfile(group, "HD 1080p 29.97 fps", "atsc_1080p_2997")); topMenu->addAction(addProfile(group, "HD 1080p 30 fps", "atsc_1080p_30")); topMenu->addAction(addProfile(group, "HD 1080p 50 fps", "atsc_1080p_50")); topMenu->addAction(addProfile(group, "HD 1080p 59.94 fps", "atsc_1080p_5994")); topMenu->addAction(addProfile(group, "HD 1080p 60 fps", "atsc_1080p_60")); topMenu->addAction(addProfile(group, "SD NTSC", "dv_ntsc")); topMenu->addAction(addProfile(group, "SD PAL", "dv_pal")); topMenu->addAction(addProfile(group, "UHD 2160p 23.98 fps", "uhd_2160p_2398")); topMenu->addAction(addProfile(group, "UHD 2160p 24 fps", "uhd_2160p_24")); topMenu->addAction(addProfile(group, "UHD 2160p 25 fps", "uhd_2160p_25")); topMenu->addAction(addProfile(group, "UHD 2160p 29.97 fps", "uhd_2160p_2997")); topMenu->addAction(addProfile(group, "UHD 2160p 30 fps", "uhd_2160p_30")); topMenu->addAction(addProfile(group, "UHD 2160p 50 fps", "uhd_2160p_50")); topMenu->addAction(addProfile(group, "UHD 2160p 59.94 fps", "uhd_2160p_5994")); topMenu->addAction(addProfile(group, "UHD 2160p 60 fps", "uhd_2160p_60")); QMenu *menu = topMenu->addMenu(tr("Non-Broadcast")); menu->addAction(addProfile(group, "640x480 4:3 NTSC", "square_ntsc")); menu->addAction(addProfile(group, "768x576 4:3 PAL", "square_pal")); menu->addAction(addProfile(group, "854x480 16:9 NTSC", "square_ntsc_wide")); menu->addAction(addProfile(group, "1024x576 16:9 PAL", "square_pal_wide")); menu->addAction(addProfile(group, tr("DVD Widescreen NTSC"), "dv_ntsc_wide")); menu->addAction(addProfile(group, tr("DVD Widescreen PAL"), "dv_pal_wide")); menu->addAction(addProfile(group, "HD 720p 23.98 fps", "atsc_720p_2398")); menu->addAction(addProfile(group, "HD 720p 24 fps", "atsc_720p_24")); menu->addAction(addProfile(group, "HD 720p 25 fps", "atsc_720p_25")); menu->addAction(addProfile(group, "HD 720p 29.97 fps", "atsc_720p_2997")); menu->addAction(addProfile(group, "HD 720p 30 fps", "atsc_720p_30")); menu->addAction(addProfile(group, "HD 1080i 60 fps", "atsc_1080i_60")); menu->addAction(addProfile(group, "HDV 1080i 25 fps", "hdv_1080_50i")); menu->addAction(addProfile(group, "HDV 1080i 29.97 fps", "hdv_1080_60i")); menu->addAction(addProfile(group, "HDV 1080p 25 fps", "hdv_1080_25p")); menu->addAction(addProfile(group, "HDV 1080p 29.97 fps", "hdv_1080_30p")); menu->addAction(addProfile(group, tr("Square 1080p 30 fps"), "square_1080p_30")); menu->addAction(addProfile(group, tr("Square 1080p 60 fps"), "square_1080p_60")); menu->addAction(addProfile(group, tr("Vertical HD 30 fps"), "vertical_hd_30")); menu->addAction(addProfile(group, tr("Vertical HD 60 fps"), "vertical_hd_60")); customMenu = topMenu->addMenu(tr("Custom")); customMenu->addAction(addAction); // Load custom profiles QDir dir(Settings.appDataLocation()); if (dir.cd("profiles")) { QStringList profiles = dir.entryList(QDir::Files | QDir::NoDotAndDotDot | QDir::Readable); if (profiles.length() > 0) { customMenu->addAction(removeAction); customMenu->addSeparator(); } foreach (QString name, profiles) customMenu->addAction(addProfile(group, name, dir.filePath(name))); } } void MainWindow::newProject(const QString &filename, bool isProjectFolder) { if (isProjectFolder) { QFileInfo info(filename); MLT.setProjectFolder(info.absolutePath()); } if (saveXML(filename)) { QMutexLocker locker(&m_autosaveMutex); if (m_autosaveFile) m_autosaveFile->changeManagedFile(filename); else m_autosaveFile.reset(new AutoSaveFile(filename)); setCurrentFile(filename); setWindowModified(false); resetSourceUpdated(); if (MLT.producer()) showStatusMessage(tr("Saved %1").arg(m_currentFile)); m_undoStack->setClean(); m_recentDock->add(filename); } else { showSaveError(); } } void MainWindow::addCustomProfile(const QString &name, QMenu *menu, QAction *action, QActionGroup *group) { // Add new profile to the menu. QDir dir(Settings.appDataLocation()); if (dir.cd("profiles")) { QStringList profiles = dir.entryList(QDir::Files | QDir::NoDotAndDotDot | QDir::Readable); if (profiles.length() == 1) { menu->addAction(action); menu->addSeparator(); } action = addProfile(group, name, dir.filePath(name)); action->setChecked(true); menu->addAction(action); Settings.setPlayerProfile(dir.filePath(name)); Settings.sync(); } } void MainWindow::removeCustomProfiles(const QStringList &profiles, QDir &dir, QMenu *menu, QAction *action) { foreach (const QString &profile, profiles) { // Remove the file. dir.remove(profile); // Locate the menu item. foreach (QAction *a, menu->actions()) { if (a->text() == profile) { // Remove the menu item. delete a; break; } } } // If no more custom video modes. if (menu->actions().size() == 3) { // Remove the Remove action and separator. menu->removeAction(action); foreach (QAction *a, menu->actions()) { if (a->isSeparator()) { delete a; break; } } } } // Drag-n-drop events bool MainWindow::eventFilter(QObject *target, QEvent *event) { if (event->type() == QEvent::DragEnter && target == MLT.videoWidget()) { dragEnterEvent(static_cast<QDragEnterEvent *>(event)); return true; } else if (event->type() == QEvent::Drop && target == MLT.videoWidget()) { dropEvent(static_cast<QDropEvent *>(event)); return true; } else if (event->type() == QEvent::KeyPress || event->type() == QEvent::KeyRelease) { if (QEvent::KeyPress == event->type()) { // Let Shift+Escape be a global hook to defocus a widget (assign global player focus). auto keyEvent = static_cast<QKeyEvent *>(event); if (Qt::Key_Escape == keyEvent->key() && Qt::ShiftModifier == keyEvent->modifiers()) { Actions["playerFocus"]->trigger(); return true; } } QQuickWidget *focusedQuickWidget = qobject_cast<QQuickWidget *>(qApp->focusWidget()); if (focusedQuickWidget && focusedQuickWidget->quickWindow()->activeFocusItem()) { event->accept(); #if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)) qApp->sendEvent(focusedQuickWidget->quickWindow()->activeFocusItem(), event); #else focusedQuickWidget->quickWindow()->sendEvent(focusedQuickWidget->quickWindow()->activeFocusItem(), event); #endif QWidget *w = focusedQuickWidget->parentWidget(); if (!event->isAccepted()) qApp->sendEvent(w, event); return true; } } return QMainWindow::eventFilter(target, event); } void MainWindow::dragEnterEvent(QDragEnterEvent *event) { // Simulate the player firing a dragStarted even to make the playlist close // its help text view. This lets one drop a clip directly into the playlist // from a fresh start. auto *videoWidget = (Mlt::VideoWidget *) &Mlt::Controller::singleton(); emit videoWidget->dragStarted(); event->acceptProposedAction(); } void MainWindow::dropEvent(QDropEvent *event) { const QMimeData *mimeData = event->mimeData(); if (mimeData->hasFormat("application/x-qabstractitemmodeldatalist")) { QByteArray encoded = mimeData->data("application/x-qabstractitemmodeldatalist"); QDataStream stream(&encoded, QIODevice::ReadOnly); QMap<int, QVariant> roleDataMap; while (!stream.atEnd()) { int row, col; stream >> row >> col >> roleDataMap; } if (roleDataMap.contains(Qt::ToolTipRole)) { // DisplayRole is just basename, ToolTipRole contains full path open(roleDataMap[Qt::ToolTipRole].toString()); event->acceptProposedAction(); } } else if (mimeData->hasUrls()) { // Use QTimer to workaround stupid drag from Windows Explorer bug const auto &urls = mimeData->urls(); QTimer::singleShot(0, this, [ = ]() { openMultiple(urls); }); event->acceptProposedAction(); } else if (mimeData->hasFormat(Mlt::XmlMimeType) && MLT.XML() != mimeData->data(Mlt::XmlMimeType)) { m_playlistDock->onOpenActionTriggered(); event->acceptProposedAction(); } } void MainWindow::closeEvent(QCloseEvent *event) { m_timelineDock->stopRecording(); if (continueJobsRunning() && continueModified()) { LOG_DEBUG() << "begin"; JOBS.cleanup(); if (m_exitCode != EXIT_RESET) { writeSettings(); } if (m_exitCode == EXIT_SUCCESS) { MLT.stop(); } else { if (multitrack()) m_timelineDock->model()->close(); if (playlist()) m_playlistDock->model()->close(); else onMultitrackClosed(); } QThreadPool::globalInstance()->clear(); AudioLevelsTask::closeAll(); event->accept(); emit aboutToShutDown(); if (m_exitCode == EXIT_SUCCESS) { QApplication::quit(); LOG_DEBUG() << "end"; ::_Exit(0); } else { QApplication::exit(m_exitCode); LOG_DEBUG() << "end"; } return; } event->ignore(); } void MainWindow::showEvent(QShowEvent *event) { // This is needed to prevent a crash on windows on startup when timeline // is visible and dock title bars are hidden. Q_UNUSED(event) ui->actionShowTitleBars->setChecked(Settings.showTitleBars()); on_actionShowTitleBars_triggered(Settings.showTitleBars()); ui->actionShowToolbar->setChecked(Settings.showToolBar()); on_actionShowToolbar_triggered(Settings.showToolBar()); ui->actionShowTextUnderIcons->setChecked(Settings.textUnderIcons()); on_actionShowTextUnderIcons_toggled(Settings.textUnderIcons()); ui->actionShowSmallIcons->setChecked(Settings.smallIcons()); on_actionShowSmallIcons_toggled(Settings.smallIcons()); windowHandle()->installEventFilter(this); #ifndef SHOTCUT_NOUPGRADE if (!Settings.noUpgrade() && !qApp->property("noupgrade").toBool()) QTimer::singleShot(0, this, SLOT(showUpgradePrompt())); #endif #if defined(Q_OS_WIN) && (QT_VERSION < QT_VERSION_CHECK(6, 0, 0)) WindowsTaskbarButton::getInstance().setParentWindow(this); #endif onAutosaveTimeout(); QTimer::singleShot(400, this, [ = ]() { Database::singleton(this); #if defined(Q_OS_WIN) || defined(Q_OS_MAC) this->setProperty("windowOpacity", 1.0); #endif }); } void MainWindow::hideEvent(QHideEvent *event) { Q_UNUSED(event) #if defined(Q_OS_WIN) || defined(Q_OS_MAC) setProperty("windowOpacity", 0.0); #endif } void MainWindow::on_actionOpenOther_triggered() { auto dialog = new OpenOtherDialog(this); if (MLT.producer()) { // open dialog with previous configuration dialog->load(MLT.producer()); } auto result = dialog->exec(); m_producerWidget.reset(dialog->currentWidget()); onOpenOtherFinished(result); } void MainWindow::onProducerOpened(bool withReopen) { QWidget *w = loadProducerWidget(MLT.producer()); if (withReopen && w && !MLT.producer()->get(kMultitrackItemProperty)) { if (-1 != w->metaObject()->indexOfSignal("producerReopened(bool)")) connect(w, SIGNAL(producerReopened(bool)), m_player, SLOT(onProducerOpened(bool))); } else if (MLT.isPlaylist()) { m_playlistDock->model()->load(); if (playlist()) { m_isPlaylistLoaded = true; m_player->setIn(-1); m_player->setOut(-1); m_playlistDock->setVisible(true); m_playlistDock->raise(); m_player->enableTab(Player::ProjectTabIndex); m_player->switchToTab(Player::ProjectTabIndex); } } else if (MLT.isMultitrack()) { m_timelineDock->model()->load(); if (isMultitrackValid()) { m_player->setIn(-1); m_player->setOut(-1); m_timelineDock->setVisible(true); m_timelineDock->raise(); m_player->enableTab(Player::ProjectTabIndex); m_player->switchToTab(Player::ProjectTabIndex); m_timelineDock->selectMultitrack(); m_timelineDock->setSelection(); } } if (MLT.isClip()) { m_filterController->setProducer(MLT.producer()); m_player->enableTab(Player::SourceTabIndex); m_player->switchToTab(Player::SourceTabIndex); Util::getHash(*MLT.producer()); } ui->actionSave->setEnabled(true); QMutexLocker locker(&m_autosaveMutex); if (m_autosaveFile) setCurrentFile(m_autosaveFile->managedFileName()); else if (!MLT.URL().isEmpty()) setCurrentFile(MLT.URL()); on_actionJack_triggered(ui->actionJack && ui->actionJack->isChecked()); } void MainWindow::onProducerChanged() { MLT.refreshConsumer(); if (playlist() && MLT.producer() && MLT.producer()->is_valid() && MLT.producer()->get_int(kPlaylistIndexProperty)) { emit m_playlistDock->enableUpdate(true); } sourceUpdated(); } bool MainWindow::on_actionSave_triggered() { m_timelineDock->stopRecording(); if (m_currentFile.isEmpty()) { return on_actionSave_As_triggered(); } else { if (Util::warnIfNotWritable(m_currentFile, this, tr("Save XML"))) return false; backupPeriodically(); bool success = saveXML(m_currentFile); QMutexLocker locker(&m_autosaveMutex); m_autosaveFile.reset(new AutoSaveFile(m_currentFile)); setCurrentFile(m_currentFile); setWindowModified(false); if (success) { showStatusMessage(tr("Saved %1").arg(m_currentFile)); } else { showSaveError(); } m_undoStack->setClean(); return true; } } bool MainWindow::on_actionSave_As_triggered() { QString path = Settings.savePath(); if (!m_currentFile.isEmpty()) path = m_currentFile; QString caption = tr("Save XML"); QString filename = QFileDialog::getSaveFileName(this, caption, path, tr("MLT XML (*.mlt)"), nullptr, Util::getFileDialogOptions()); if (!filename.isEmpty()) { QFileInfo fi(filename); Settings.setSavePath(fi.path()); if (fi.suffix() != "mlt") filename += ".mlt"; if (Util::warnIfNotWritable(filename, this, caption)) return false; newProject(filename); } return !filename.isEmpty(); } void MainWindow::on_actionBackupSave_triggered() { m_timelineDock->stopRecording(); if (m_currentFile.isEmpty()) { on_actionSave_As_triggered(); } else { backup(); if (isWindowModified()) on_actionSave_triggered(); } } void MainWindow::cropSource(const QRectF &rect) { filterController()->removeCurrent(); auto model = filterController()->attachedModel(); Mlt::Service service; for (int i = 0; i < model->rowCount(); i++) { service = model->getService(i); if (!qstrcmp("crop", service.get("mlt_service"))) break; } if (!service.is_valid()) { auto meta = filterController()->metadata("crop"); service = model->getService(model->add(meta)); service.set("use_profile", 1); } service.set("left", rect.x()); service.set("right", MLT.profile().width() - rect.x() - rect.width()); service.set("top", rect.y()); service.set("bottom", MLT.profile().height() - rect.y() - rect.height()); auto newWidth = Util::coerceMultiple(rect.width()); auto newHeight = Util::coerceMultiple(rect.height()); QMessageBox dialog(QMessageBox::Question, qApp->applicationName(), tr("Do you also want to change the Video Mode to %1 x %2?").arg(newWidth).arg(newHeight), QMessageBox::No | QMessageBox::Yes, this); dialog.setWindowModality(QmlApplication::dialogModality()); dialog.setDefaultButton(QMessageBox::Yes); dialog.setEscapeButton(QMessageBox::No); if (QMessageBox::Yes == dialog.exec()) { auto leftRatio = rect.x() / MLT.profile().width(); auto rightRatio = 1.0 - (rect.x() + newWidth) / MLT.profile().width(); auto topRatio = rect.y() / MLT.profile().height(); auto bottomRatio = 1.0 - (rect.y() + newHeight) / MLT.profile().height(); service.set("left", qRound(leftRatio * newWidth)); service.set("right", qRound(rightRatio * newWidth)); service.set("top", qRound(topRatio * newHeight)); service.set("bottom", qRound(bottomRatio * newHeight)); MLT.profile().set_width(newWidth); MLT.profile().set_height(newHeight); MLT.profile().set_display_aspect(newWidth * MLT.profile().sar(), newHeight); MLT.updatePreviewProfile(); MLT.setPreviewScale(Settings.playerPreviewScale()); auto xml = MLT.XML(); emit profileChanged(); MLT.restart(xml); } emit producerOpened(false); } void MainWindow::getMarkerRange(int position, int *start, int *end) { if (!MLT.isMultitrack()) { showStatusMessage(tr("Timeline is not loaded")); } else { MarkersModel *model = m_timelineDock->markersModel(); int markerIndex = model->rangeMarkerIndexForPosition(position); if (markerIndex >= 0) { Markers::Marker marker = model->getMarker(markerIndex); *start = marker.start; *end = marker.end; return; } else { showStatusMessage(tr("Range marker not found under the timeline cursor")); } } *start = -1; *end = -1; } void MainWindow::getSelectionRange(int *start, int *end) { if (MLT.isMultitrack()) { m_timelineDock->getSelectionRange(start, end); } else if (MLT.isPlaylist()) { m_playlistDock->getSelectionRange(start, end); } else if (MLT.isSeekableClip()) { *start = MLT.producer()->get_in(); *end = MLT.producer()->get_out(); } else { *start = -1; *end = -1; } } bool MainWindow::continueModified() { if (isWindowModified()) { QMessageBox dialog(QMessageBox::Warning, qApp->applicationName(), tr("The project has been modified.\n" "Do you want to save your changes?"), QMessageBox::No | QMessageBox::Cancel | QMessageBox::Yes, this); dialog.setWindowModality(QmlApplication::dialogModality()); dialog.setDefaultButton(QMessageBox::Yes); dialog.setEscapeButton(QMessageBox::Cancel); int r = dialog.exec(); if (r == QMessageBox::Yes || r == QMessageBox::No) { if (r == QMessageBox::Yes) { return on_actionSave_triggered(); } else { QMutexLocker locker(&m_autosaveMutex); m_autosaveFile.reset(); } } else if (r == QMessageBox::Cancel) { return false; } } return true; } bool MainWindow::continueJobsRunning() { if (JOBS.hasIncomplete()) { QMessageBox dialog(QMessageBox::Warning, qApp->applicationName(), tr("There are incomplete jobs.\n" "Do you still want to exit?"), QMessageBox::No | QMessageBox::Yes, this); dialog.setWindowModality(QmlApplication::dialogModality()); dialog.setDefaultButton(QMessageBox::Yes); dialog.setEscapeButton(QMessageBox::No); return (dialog.exec() == QMessageBox::Yes); } if (m_encodeDock->isExportInProgress()) { QMessageBox dialog(QMessageBox::Warning, qApp->applicationName(), tr("An export is in progress.\n" "Do you still want to exit?"), QMessageBox::No | QMessageBox::Yes, this); dialog.setWindowModality(QmlApplication::dialogModality()); dialog.setDefaultButton(QMessageBox::Yes); dialog.setEscapeButton(QMessageBox::No); return (dialog.exec() == QMessageBox::Yes); } return true; } QUndoStack *MainWindow::undoStack() const { return m_undoStack; } void MainWindow::onEncodeTriggered(bool checked) { if (checked) { m_encodeDock->show(); m_encodeDock->raise(); } } void MainWindow::onCaptureStateChanged(bool started) { if (started && (MLT.resource().startsWith("x11grab:") || MLT.resource().startsWith("gdigrab:") || MLT.resource().startsWith("avfoundation")) && !MLT.producer()->get_int(kBackgroundCaptureProperty)) showMinimized(); } void MainWindow::onJobsDockTriggered(bool checked) { if (checked) { m_jobsDock->show(); m_jobsDock->raise(); } } void MainWindow::onRecentDockTriggered(bool checked) { if (checked) { m_recentDock->show(); m_recentDock->raise(); } } void MainWindow::onPropertiesDockTriggered(bool checked) { if (checked) { m_propertiesDock->show(); m_propertiesDock->raise(); } } void MainWindow::onPlaylistDockTriggered(bool checked) { if (checked) { m_playlistDock->show(); m_playlistDock->raise(); } } void MainWindow::onTimelineDockTriggered(bool checked) { if (checked) { m_timelineDock->show(); m_timelineDock->raise(); } } void MainWindow::onHistoryDockTriggered(bool checked) { if (checked) { m_historyDock->show(); m_historyDock->raise(); } } void MainWindow::onFiltersDockTriggered(bool checked) { if (checked) { m_filtersDock->show(); m_filtersDock->raise(); } } void MainWindow::onKeyframesDockTriggered(bool checked) { if (checked) { m_keyframesDock->show(); m_keyframesDock->raise(); } } void MainWindow::onMarkersDockTriggered(bool checked) { if (checked) { m_markersDock->show(); m_markersDock->raise(); } } void MainWindow::onNotesDockTriggered(bool checked) { if (checked) { m_notesDock->show(); m_notesDock->raise(); } } void MainWindow::onSubtitlesDockTriggered(bool checked) { if (checked) { m_subtitlesDock->show(); m_subtitlesDock->raise(); } } void MainWindow::onPlaylistCreated() { if (!playlist() || playlist()->count() == 0) return; m_player->enableTab(Player::ProjectTabIndex, true); } void MainWindow::onPlaylistLoaded() { updateMarkers(); m_player->enableTab(Player::ProjectTabIndex, true); } void MainWindow::onPlaylistCleared() { m_player->onTabBarClicked(Player::SourceTabIndex); setWindowModified(true); } void MainWindow::onPlaylistClosed() { closeProducer(); setProfile(Settings.playerProfile()); resetVideoModeMenu(); setAudioChannels(Settings.playerAudioChannels()); setCurrentFile(""); setWindowModified(false); resetSourceUpdated(); m_undoStack->clear(); MLT.resetURL(); QMutexLocker locker(&m_autosaveMutex); m_autosaveFile.reset(new AutoSaveFile(untitledFileName())); if (!isMultitrackValid()) m_player->enableTab(Player::ProjectTabIndex, false); } void MainWindow::onPlaylistModified() { setWindowModified(true); if (MLT.producer() && playlist() && (void *) MLT.producer()->get_producer() == (void *) playlist()->get_playlist()) m_player->onDurationChanged(); updateMarkers(); m_player->enableTab(Player::ProjectTabIndex, true); } void MainWindow::onMultitrackCreated() { m_player->enableTab(Player::ProjectTabIndex, true); } void MainWindow::onMultitrackClosed() { setAudioChannels(Settings.playerAudioChannels()); closeProducer(); setProfile(Settings.playerProfile()); resetVideoModeMenu(); setCurrentFile(""); setWindowModified(false); resetSourceUpdated(); m_undoStack->clear(); MLT.resetURL(); QMutexLocker locker(&m_autosaveMutex); m_autosaveFile.reset(new AutoSaveFile(untitledFileName())); if (!playlist() || playlist()->count() == 0) m_player->enableTab(Player::ProjectTabIndex, false); } void MainWindow::onMultitrackModified() { setWindowModified(true); // Reflect this playlist info onto the producer for keyframes dock. if (!m_timelineDock->selection().isEmpty()) { int trackIndex = m_timelineDock->selection().first().y(); int clipIndex = m_timelineDock->selection().first().x(); auto info = m_timelineDock->model()->getClipInfo(trackIndex, clipIndex); if (info && info->producer && info->producer->is_valid()) { int expected = info->frame_in; auto info2 = m_timelineDock->model()->getClipInfo(trackIndex, clipIndex - 1); if (info2 && info2->producer && info2->producer->is_valid() && info2->producer->get(kShotcutTransitionProperty)) { // Factor in a transition left of the clip. expected -= info2->frame_count; info->producer->set(kPlaylistStartProperty, info2->start); } else { info->producer->set(kPlaylistStartProperty, info->start); } if (expected != info->producer->get_int(kFilterInProperty)) { int delta = expected - info->producer->get_int(kFilterInProperty); info->producer->set(kFilterInProperty, expected); emit m_filtersDock->producerInChanged(delta); } expected = info->frame_out; info2 = m_timelineDock->model()->getClipInfo(trackIndex, clipIndex + 1); if (info2 && info2->producer && info2->producer->is_valid() && info2->producer->get(kShotcutTransitionProperty)) { // Factor in a transition right of the clip. expected += info2->frame_count; } if (expected != info->producer->get_int(kFilterOutProperty)) { int delta = expected - info->producer->get_int(kFilterOutProperty); info->producer->set(kFilterOutProperty, expected); emit m_filtersDock->producerOutChanged(delta); } } } MLT.refreshConsumer(); } void MainWindow::onMultitrackDurationChanged() { if (MLT.producer() && (void *) MLT.producer()->get_producer() == (void *) multitrack()->get_producer()) m_player->onDurationChanged(); } void MainWindow::onNoteModified() { setWindowModified(true); } void MainWindow::onSubtitleModified() { setWindowModified(true); } void MainWindow::onCutModified() { if (!playlist() && !multitrack()) { setWindowModified(true); } if (playlist()) { emit m_playlistDock->enableUpdate(true); } sourceUpdated(); } void MainWindow::onProducerModified() { setWindowModified(true); sourceUpdated(); } void MainWindow::onFilterModelChanged() { MLT.refreshConsumer(); setWindowModified(true); sourceUpdated(); if (playlist()) { emit m_playlistDock->enableUpdate(true); } } void MainWindow::updateMarkers() { if (playlist() && MLT.isPlaylist()) { QList<int> markers; int n = playlist()->count(); for (int i = 0; i < n; i++) markers.append(playlist()->clip_start(i)); m_player->setMarkers(markers); } } void MainWindow::updateThumbnails() { if (Settings.playlistThumbnails() != "hidden") m_playlistDock->model()->refreshThumbnails(); } void MainWindow::on_actionUndo_triggered() { m_undoStack->undo(); } void MainWindow::on_actionRedo_triggered() { m_undoStack->redo(); } void MainWindow::on_actionFAQ_triggered() { QDesktopServices::openUrl(QUrl("https://www.shotcut.org/FAQ/")); } void MainWindow::on_actionForum_triggered() { QDesktopServices::openUrl(QUrl("https://forum.shotcut.org/")); } bool MainWindow::saveXML(const QString &filename, bool withRelativePaths) { bool result; QString notes = m_notesDock->getText(); if (m_timelineDock->model()->rowCount() > 0) { result = MLT.saveXML(filename, multitrack(), withRelativePaths, nullptr, false, notes); } else if (m_playlistDock->model()->rowCount() > 0 && MLT.producer() && MLT.producer()->is_valid()) { int in = MLT.producer()->get_in(); int out = MLT.producer()->get_out(); MLT.producer()->set_in_and_out(0, MLT.producer()->get_length() - 1); result = MLT.saveXML(filename, playlist(), withRelativePaths, nullptr, false, notes); MLT.producer()->set_in_and_out(in, out); } else if (MLT.producer() && MLT.producer()->is_valid()) { result = MLT.saveXML(filename, (MLT.isMultitrack() || MLT.isPlaylist()) ? MLT.savedProducer() : 0, withRelativePaths, nullptr, false, notes); } else { // Save an empty playlist, which is accepted by both MLT and Shotcut. Mlt::Playlist playlist(MLT.profile()); result = MLT.saveXML(filename, &playlist, withRelativePaths, nullptr, false, notes); } return result; } void MainWindow::changeTheme(const QString &theme) { LOG_DEBUG() << "begin"; auto mytheme = theme; #if !defined(SHOTCUT_THEME) // Workaround Quick Controls not using our custom palette - temporarily? std::unique_ptr<QStyle> style {QStyleFactory::create("fusion")}; auto brightness = style->standardPalette().color(QPalette::Text).lightnessF(); LOG_DEBUG() << brightness; mytheme = brightness < 0.5f ? "light" : "dark"; QApplication::setStyle("Fusion"); QIcon::setThemeName(mytheme); # if defined(Q_OS_MAC) if (mytheme == "dark") { auto palette = QGuiApplication::palette(); palette.setColor(QPalette::AlternateBase, palette.color(QPalette::Base).lighter()); QGuiApplication::setPalette(palette); } # elif defined(Q_OS_WIN) QGuiApplication::setPalette(style->standardPalette()); # endif #else if (mytheme == "dark") { QApplication::setStyle("Fusion"); QPalette palette; palette.setColor(QPalette::Window, QColor(50, 50, 50)); palette.setColor(QPalette::WindowText, QColor(220, 220, 220)); palette.setColor(QPalette::Base, QColor(30, 30, 30)); palette.setColor(QPalette::AlternateBase, QColor(40, 40, 40)); palette.setColor(QPalette::Highlight, QColor(23, 92, 118)); palette.setColor(QPalette::HighlightedText, Qt::white); palette.setColor(QPalette::ToolTipBase, palette.color(QPalette::Highlight)); palette.setColor(QPalette::ToolTipText, palette.color(QPalette::WindowText)); palette.setColor(QPalette::Text, palette.color(QPalette::WindowText)); palette.setColor(QPalette::BrightText, Qt::red); palette.setColor(QPalette::Button, palette.color(QPalette::Window)); palette.setColor(QPalette::ButtonText, palette.color(QPalette::WindowText)); palette.setColor(QPalette::Link, palette.color(QPalette::Highlight).lighter()); palette.setColor(QPalette::LinkVisited, palette.color(QPalette::Highlight)); palette.setColor(QPalette::Disabled, QPalette::Text, Qt::darkGray); palette.setColor(QPalette::Disabled, QPalette::ButtonText, Qt::darkGray); palette.setColor(QPalette::Disabled, QPalette::Light, Qt::transparent); QApplication::setPalette(palette); QIcon::setThemeName("dark"); if (!::qEnvironmentVariableIsSet("QT_QUICK_CONTROLS_CONF")) ::qputenv("QT_QUICK_CONTROLS_CONF", ":/resources/qtquickcontrols2-dark.conf"); } else if (mytheme == "light") { QApplication::setStyle("Fusion"); QPalette palette; palette.setColor(QPalette::Window, "#efefef"); palette.setColor(QPalette::WindowText, "#000000"); palette.setColor(QPalette::Base, "#ffffff"); palette.setColor(QPalette::AlternateBase, "#f7f7f7"); palette.setColor(QPalette::Highlight, "#308cc6"); palette.setColor(QPalette::HighlightedText, "#ffffff"); palette.setColor(QPalette::ToolTipBase, "#308cc6"); palette.setColor(QPalette::ToolTipText, "#000000"); palette.setColor(QPalette::Text, "#000000"); palette.setColor(QPalette::BrightText, "#ffffff"); palette.setColor(QPalette::Button, "#efefef"); palette.setColor(QPalette::ButtonText, "#000000"); palette.setColor(QPalette::Link, "#308cc6"); palette.setColor(QPalette::LinkVisited, "#308cc6"); palette.setColor(QPalette::Disabled, QPalette::Text, Qt::darkGray); palette.setColor(QPalette::Disabled, QPalette::ButtonText, Qt::darkGray); palette.setColor(QPalette::Disabled, QPalette::Light, Qt::transparent); QApplication::setPalette(palette); QIcon::setThemeName("light"); if (!::qEnvironmentVariableIsSet("QT_QUICK_CONTROLS_CONF")) ::qputenv("QT_QUICK_CONTROLS_CONF", ":/resources/qtquickcontrols2-light.conf"); } else { QApplication::setStyle(qApp->property("system-style").toString()); QIcon::setThemeName("oxygen"); if (!::qEnvironmentVariableIsSet("QT_QUICK_CONTROLS_CONF")) { auto brightness = QGuiApplication::palette().color(QPalette::Text).lightnessF(); if (brightness < 0.5f) ::qputenv("QT_QUICK_CONTROLS_CONF", ":/resources/qtquickcontrols2-light.conf"); else ::qputenv("QT_QUICK_CONTROLS_CONF", ":/resources/qtquickcontrols2-dark.conf"); } } #endif // auto pal = QGuiApplication::palette(); // LOG_INFO() << "altBase" << pal.alternateBase().color().name(); // LOG_INFO() << "base" << pal.base().color().name(); // LOG_INFO() << "window" << pal.window().color().name(); // LOG_INFO() << "windowText" << pal.windowText().color().name(); // LOG_INFO() << "toolTipBase" << pal.toolTipBase().color().name(); // LOG_INFO() << "toolTipText" << pal.toolTipText().color().name(); // LOG_INFO() << "text" << pal.text().color().name(); // LOG_INFO() << "button" << pal.button().color().name(); // LOG_INFO() << "buttonText" << pal.buttonText().color().name(); // LOG_INFO() << "placeholderText" << pal.placeholderText().color().name(); // LOG_INFO() << "brightText" << pal.brightText().color().name(); // LOG_INFO() << "highlight" << pal.highlight().color().name(); // LOG_INFO() << "highlightedText" << pal.highlightedText().color().name(); // LOG_INFO() << "link" << pal.link().color().name(); // LOG_INFO() << "linkVisited" << pal.linkVisited().color().name(); LOG_DEBUG() << "end"; } Mlt::Playlist *MainWindow::playlist() const { return m_playlistDock->model()->playlist(); } bool MainWindow::isPlaylistValid() const { return m_playlistDock->model()->playlist() && m_playlistDock->model()->rowCount() > 0; } Mlt::Producer *MainWindow::multitrack() const { return m_timelineDock->model()->tractor(); } bool MainWindow::isMultitrackValid() const { return m_timelineDock->model()->tractor() && !m_timelineDock->model()->trackList().empty(); } QWidget *MainWindow::loadProducerWidget(Mlt::Producer *producer) { QWidget *w = 0; QScrollArea *scrollArea = (QScrollArea *) m_propertiesDock->widget(); if (!producer || !producer->is_valid()) { if (scrollArea->widget()) scrollArea->widget()->deleteLater(); return w; } else { scrollArea->show(); } QString service(producer->get("mlt_service")); QString resource = QString::fromUtf8(producer->get("resource")); QString shotcutProducer(producer->get(kShotcutProducerProperty)); if (resource.startsWith("video4linux2:") || QString::fromUtf8(producer->get("resource1")).startsWith("video4linux2:")) w = new Video4LinuxWidget(this); else if (resource.startsWith("pulse:")) w = new PulseAudioWidget(this); else if (resource.startsWith("jack:")) w = new JackProducerWidget(this); else if (resource.startsWith("alsa:")) w = new AlsaWidget(this); else if (resource.startsWith("dshow:") || QString::fromUtf8(producer->get("resource1")).startsWith("dshow:")) w = new DirectShowVideoWidget(this); else if (resource.startsWith("avfoundation:")) w = new AvfoundationProducerWidget(this); else if (resource.startsWith("x11grab:")) w = new X11grabWidget(this); else if (resource.startsWith("gdigrab:")) w = new GDIgrabWidget(this); else if (service.startsWith("avformat") || shotcutProducer == "avformat") w = new AvformatProducerWidget(this); else if (MLT.isImageProducer(producer)) { w = new ImageProducerWidget(this); connect(m_player, SIGNAL(outChanged(int)), w, SLOT(updateDuration())); } else if (service == "decklink" || resource.contains("decklink")) w = new DecklinkProducerWidget(this); else if (service == "color") w = new ColorProducerWidget(this); else if (service == "glaxnimate") w = new GlaxnimateProducerWidget(this); else if (service == "noise") w = new NoiseWidget(this); else if (service == "frei0r.ising0r") w = new IsingWidget(this); else if (service == "frei0r.lissajous0r") w = new LissajousWidget(this); else if (service == "frei0r.plasma") w = new PlasmaWidget(this); else if (service == "frei0r.test_pat_B") w = new ColorBarsWidget(this); else if (service == "tone") w = new ToneProducerWidget(this); else if (service == "count") w = new CountProducerWidget(this); else if (service == "blipflash") w = new BlipProducerWidget(this); else if (producer->parent().get(kShotcutTransitionProperty)) { w = new LumaMixTransition(producer->parent(), this); scrollArea->setWidget(w); if (-1 != w->metaObject()->indexOfSignal("modified()")) { connect(w, SIGNAL(modified()), SLOT(onProducerModified())); } if (-1 != w->metaObject()->indexOfSlot("onPlaying()")) { connect(MLT.videoWidget(), SIGNAL(playing()), w, SLOT(onPlaying())); } return w; } else if (mlt_service_playlist_type == producer->type()) { int trackIndex = m_timelineDock->currentTrack(); bool isBottomVideo = m_timelineDock->model()->data(m_timelineDock->model()->index(trackIndex), MultitrackModel::IsBottomVideoRole).toBool(); if (!isBottomVideo) { w = new TrackPropertiesWidget(*producer, this); scrollArea->setWidget(w); return w; } } else if (mlt_service_tractor_type == producer->type()) { w = new TimelinePropertiesWidget(*producer, this); scrollArea->setWidget(w); connect(w, SIGNAL(editProfile()), SLOT(on_actionAddCustomProfile_triggered())); return w; } if (w) { dynamic_cast<AbstractProducerWidget *>(w)->setProducer(producer); if (-1 != w->metaObject()->indexOfSignal("producerChanged(Mlt::Producer*)")) { connect(w, SIGNAL(producerChanged(Mlt::Producer *)), SLOT(onProducerChanged())); connect(w, SIGNAL(producerChanged(Mlt::Producer *)), m_filterController, SLOT(setProducer(Mlt::Producer *))); connect(w, SIGNAL(producerChanged(Mlt::Producer *)), m_playlistDock, SLOT(onProducerChanged(Mlt::Producer *))); if (producer->get(kMultitrackItemProperty)) connect(w, SIGNAL(producerChanged(Mlt::Producer *)), m_timelineDock, SLOT(onProducerChanged(Mlt::Producer *))); } if (-1 != w->metaObject()->indexOfSignal("modified()")) { connect(w, SIGNAL(modified()), SLOT(onProducerModified())); connect(w, SIGNAL(modified()), m_playlistDock, SLOT(onProducerModified())); connect(w, SIGNAL(modified()), m_timelineDock, SLOT(onProducerModified())); connect(w, SIGNAL(modified()), m_keyframesDock, SLOT(onProducerModified())); connect(w, SIGNAL(modified()), m_filterController, SLOT(onProducerChanged())); } if (-1 != w->metaObject()->indexOfSlot("updateDuration()")) { connect(m_timelineDock, SIGNAL(durationChanged()), w, SLOT(updateDuration())); } if (-1 != w->metaObject()->indexOfSlot("rename()")) { connect(this, SIGNAL(renameRequested()), w, SLOT(rename())); } if (-1 != w->metaObject()->indexOfSlot("offerConvert(QString)")) { connect(m_filterController->attachedModel(), SIGNAL(requestConvert(QString, bool, bool)), w, SLOT(offerConvert(QString, bool)), Qt::QueuedConnection); } scrollArea->setWidget(w); onProducerChanged(); } else if (scrollArea->widget()) { scrollArea->widget()->deleteLater(); } return w; } void MainWindow::on_actionEnterFullScreen_triggered() { bool isFull = isFullScreen(); if (isFull) { showNormal(); ui->actionEnterFullScreen->setText(tr("Enter Full Screen")); } else { showFullScreen(); ui->actionEnterFullScreen->setText(tr("Exit Full Screen")); } } void MainWindow::onGpuNotSupported() { Settings.setPlayerGPU(false); if (ui->actionGPU) { ui->actionGPU->setChecked(false); ui->actionGPU->setDisabled(true); } LOG_WARNING() << ""; QMessageBox::critical(this, qApp->applicationName(), tr("GPU effects are not supported")); } void MainWindow::onShuttle(float x) { if (x == 0) { m_player->pause(); } else if (x > 0) { m_player->play(10.0 * x); } else { m_player->play(20.0 * x); } } void MainWindow::showUpgradePrompt() { if (Settings.checkUpgradeAutomatic()) { showStatusMessage("Checking for upgrade..."); m_network.get(QNetworkRequest(QUrl("https://check.shotcut.org/version.json"))); } else { QAction *action = new QAction(tr("Click here to check for a new version of Shotcut."), 0); connect(action, SIGNAL(triggered(bool)), SLOT(on_actionUpgrade_triggered())); showStatusMessage(action, 15 /* seconds */); } } void MainWindow::on_actionRealtime_triggered(bool checked) { Settings.setPlayerRealtime(checked); if (Settings.playerGPU()) MLT.pause(); if (MLT.consumer()) { MLT.restart(); } } void MainWindow::on_actionProgressive_triggered(bool checked) { MLT.videoWidget()->setProperty("progressive", checked); if (Settings.playerGPU()) MLT.pause(); if (MLT.consumer()) { MLT.profile().set_progressive(checked); MLT.updatePreviewProfile(); MLT.restart(); } Settings.setPlayerProgressive(checked); } void MainWindow::changeAudioChannels(bool checked, int channels) { if (checked) { Settings.setPlayerAudioChannels(channels); setAudioChannels(Settings.playerAudioChannels()); } } void MainWindow::on_actionChannels1_triggered(bool checked) { changeAudioChannels(checked, 1); } void MainWindow::on_actionChannels2_triggered(bool checked) { changeAudioChannels(checked, 2); } void MainWindow::on_actionChannels4_triggered(bool checked) { changeAudioChannels(checked, 4); } void MainWindow::on_actionChannels6_triggered(bool checked) { changeAudioChannels(checked, 6); } void MainWindow::changeDeinterlacer(bool checked, const char *method) { if (checked) { MLT.videoWidget()->setProperty("deinterlacer", method); if (MLT.consumer()) { MLT.consumer()->set("deinterlacer", method); MLT.refreshConsumer(); } } Settings.setPlayerDeinterlacer(method); } void MainWindow::on_actionOneField_triggered(bool checked) { changeDeinterlacer(checked, "onefield"); } void MainWindow::on_actionLinearBlend_triggered(bool checked) { changeDeinterlacer(checked, "linearblend"); } void MainWindow::on_actionYadifTemporal_triggered(bool checked) { changeDeinterlacer(checked, "yadif-nospatial"); } void MainWindow::on_actionYadifSpatial_triggered(bool checked) { changeDeinterlacer(checked, "yadif"); } void MainWindow::on_actionBwdif_triggered(bool checked) { changeDeinterlacer(checked, "bwdif"); } void MainWindow::changeInterpolation(bool checked, const char *method) { if (checked) { MLT.videoWidget()->setProperty("rescale", method); if (MLT.consumer()) { MLT.consumer()->set("rescale", method); MLT.refreshConsumer(); } } Settings.setPlayerInterpolation(method); } void MainWindow::processMultipleFiles() { if (m_multipleFiles.length() <= 0) return; QStringList multipleFiles = m_multipleFiles; m_multipleFiles.clear(); int count = multipleFiles.length(); if (count > 1) { m_multipleFilesLoading = true; LongUiTask longTask(tr("Open Files")); m_playlistDock->show(); m_playlistDock->raise(); ResourceDialog dialog(this); for (int i = 0; i < count; i++) { QString filename = multipleFiles.takeFirst(); LOG_DEBUG() << filename; longTask.reportProgress(QFileInfo(filename).fileName(), i, count); Mlt::Producer p(MLT.profile(), filename.toUtf8().constData()); if (p.is_valid()) { if (QDir::toNativeSeparators(filename) == QDir::toNativeSeparators(MAIN.fileName())) { MAIN.showStatusMessage(QObject::tr("You cannot add a project to itself!")); continue; } Util::getHash(p); Mlt::Producer *producer = MLT.setupNewProducer(&p); ProxyManager::generateIfNotExists(*producer); producer->set(kShotcutSkipConvertProperty, true); undoStack()->push(new Playlist::AppendCommand(*m_playlistDock->model(), MLT.XML(producer), false)); m_recentDock->add(filename.toUtf8().constData()); dialog.add(producer); delete producer; } } emit m_playlistDock->model()->modified(); if (Settings.showConvertClipDialog() && dialog.hasTroubleClips()) { dialog.selectTroubleClips(); dialog.setWindowTitle(tr("Opened Files")); dialog.exec(); } m_multipleFilesLoading = false; } if (m_isPlaylistLoaded && Settings.playerGPU()) { updateThumbnails(); m_isPlaylistLoaded = false; } } void MainWindow::processSingleFile() { if (!m_multipleFilesLoading && Settings.showConvertClipDialog() && !MLT.producer()->get_int(kShotcutSkipConvertProperty)) { QString convertAdvice = Util::getConversionAdvice(MLT.producer()); if (!convertAdvice.isEmpty()) { MLT.producer()->set(kShotcutSkipConvertProperty, true); LongUiTask::cancel(); MLT.pause(); Util::offerSingleFileConversion(convertAdvice, MLT.producer(), this); } } } void MainWindow::onLanguageTriggered(QAction *action) { Settings.setLanguage(action->data().toString()); QMessageBox dialog(QMessageBox::Information, qApp->applicationName(), tr("You must restart Shotcut to switch to the new language.\n" "Do you want to restart now?"), QMessageBox::No | QMessageBox::Yes, this); dialog.setDefaultButton(QMessageBox::Yes); dialog.setEscapeButton(QMessageBox::No); dialog.setWindowModality(QmlApplication::dialogModality()); if (dialog.exec() == QMessageBox::Yes) { m_exitCode = EXIT_RESTART; QApplication::closeAllWindows(); } } void MainWindow::on_actionNearest_triggered(bool checked) { changeInterpolation(checked, "nearest"); } void MainWindow::on_actionBilinear_triggered(bool checked) { changeInterpolation(checked, "bilinear"); } void MainWindow::on_actionBicubic_triggered(bool checked) { changeInterpolation(checked, "bicubic"); } void MainWindow::on_actionHyper_triggered(bool checked) { changeInterpolation(checked, "hyper"); } void MainWindow::on_actionJack_triggered(bool checked) { Settings.setPlayerJACK(checked); if (!MLT.enableJack(checked)) { if (ui->actionJack) ui->actionJack->setChecked(false); Settings.setPlayerJACK(false); QMessageBox::warning(this, qApp->applicationName(), tr("Failed to connect to JACK.\nPlease verify that JACK is installed and running.")); } } void MainWindow::on_actionGPU_triggered(bool checked) { if (checked) { QMessageBox dialog(QMessageBox::Warning, qApp->applicationName(), tr("GPU effects are experimental and do not work good on all computers. Plan to do some testing after turning this on.\n" "At this time, a project created with GPU effects cannot be converted to a CPU-only project later." "\n\n" "Do you want to enable GPU effects and restart Shotcut?"), QMessageBox::No | QMessageBox::Yes, this); dialog.setDefaultButton(QMessageBox::Yes); dialog.setEscapeButton(QMessageBox::No); dialog.setWindowModality(QmlApplication::dialogModality()); if (dialog.exec() == QMessageBox::Yes) { m_exitCode = EXIT_RESTART; QApplication::closeAllWindows(); } else { ui->actionGPU->setChecked(false); } } else { QMessageBox dialog(QMessageBox::Information, qApp->applicationName(), tr("Shotcut must restart to disable GPU effects." "\n\n" "Disable GPU effects and restart?"), QMessageBox::No | QMessageBox::Yes, this); dialog.setDefaultButton(QMessageBox::Yes); dialog.setEscapeButton(QMessageBox::No); dialog.setWindowModality(QmlApplication::dialogModality()); if (dialog.exec() == QMessageBox::Yes) { m_exitCode = EXIT_RESTART; QApplication::closeAllWindows(); } else { ui->actionGPU->setChecked(true); } } } void MainWindow::onExternalTriggered(QAction *action) { LOG_DEBUG() << action->data().toString(); bool isExternal = !action->data().toString().isEmpty(); Settings.setPlayerExternal(action->data().toString()); MLT.stop(); bool ok = false; int screen = action->data().toInt(&ok); if (ok || action->data().toString().isEmpty()) { m_player->moveVideoToScreen(ok ? screen : -2); isExternal = false; MLT.videoWidget()->setProperty("mlt_service", QVariant()); } else { m_player->moveVideoToScreen(-2); MLT.videoWidget()->setProperty("mlt_service", action->data()); } QString profile = Settings.playerProfile(); // Automatic not permitted for SDI/HDMI if (isExternal && profile.isEmpty()) { profile = "atsc_720p_50"; Settings.setPlayerProfile(profile); setProfile(profile); MLT.restart(); foreach (QAction *a, m_profileGroup->actions()) { if (a->data() == profile) { a->setChecked(true); break; } } } else { MLT.consumerChanged(); } // Automatic not permitted for SDI/HDMI m_profileGroup->actions().at(0)->setEnabled(!isExternal); // Disable progressive option when SDI/HDMI ui->actionProgressive->setEnabled(!isExternal); bool isProgressive = isExternal ? MLT.profile().progressive() : ui->actionProgressive->isChecked(); MLT.videoWidget()->setProperty("progressive", isProgressive); if (MLT.consumer()) { MLT.consumer()->set("progressive", isProgressive); MLT.restart(); } if (m_keyerMenu) m_keyerMenu->setEnabled(action->data().toString().startsWith("decklink")); // Preview scaling not permitted for SDI/HDMI if (isExternal) { setPreviewScale(0); m_previewScaleGroup->setEnabled(false); } else { setPreviewScale(Settings.playerPreviewScale()); m_previewScaleGroup->setEnabled(true); } } void MainWindow::onKeyerTriggered(QAction *action) { LOG_DEBUG() << action->data().toString(); MLT.videoWidget()->setProperty("keyer", action->data()); MLT.consumerChanged(); Settings.setPlayerKeyerMode(action->data().toInt()); } void MainWindow::onProfileTriggered(QAction *action) { if (MLT.producer() && MLT.producer()->is_valid()) { if (!confirmProfileChange()) return; Settings.setPlayerProfile(action->data().toString()); // Figure out the top-level project producer auto producer = MLT.producer(); if (m_timelineDock->model()->rowCount() > 0) { producer = multitrack(); } else if (m_playlistDock->model()->rowCount() > 0) { producer = playlist(); } else if (MLT.isMultitrack() || MLT.isPlaylist()) { producer = MLT.savedProducer(); } MLT.fixLengthProperties(*producer); // Save the XML to get correct in/out points before profile is changed. QString xml = MLT.XML(producer); setProfile(action->data().toString()); MLT.restart(xml); emit producerOpened(false); } else { Settings.setPlayerProfile(action->data().toString()); setProfile(action->data().toString()); } } void MainWindow::onProfileChanged() { if (multitrack() && MLT.isMultitrack() && (m_timelineDock->selection().isEmpty() || m_timelineDock->currentTrack() == -1)) { emit m_timelineDock->selected(multitrack()); } } void MainWindow::on_actionAddCustomProfile_triggered() { QString xml; if (MLT.producer() && MLT.producer()->is_valid()) { if (!confirmProfileChange()) return; // Save the XML to get correct in/out points before profile is changed. xml = MLT.XML(); } CustomProfileDialog dialog(this); dialog.setWindowModality(QmlApplication::dialogModality()); if (dialog.exec() == QDialog::Accepted) { QString name = dialog.profileName(); if (!name.isEmpty()) { addCustomProfile(name, customProfileMenu(), actionProfileRemove(), profileGroup()); } else if (m_profileGroup->checkedAction()) { m_profileGroup->checkedAction()->setChecked(false); } // Use the new profile. emit profileChanged(); if (!xml.isEmpty()) { MLT.restart(xml); emit producerOpened(false); } } } void MainWindow::restartAfterChangeTheme() { QMessageBox dialog(QMessageBox::Information, qApp->applicationName(), tr("You must restart %1 to switch to the new theme.\n" "Do you want to restart now?").arg(qApp->applicationName()), QMessageBox::No | QMessageBox::Yes, this); dialog.setDefaultButton(QMessageBox::Yes); dialog.setEscapeButton(QMessageBox::No); dialog.setWindowModality(QmlApplication::dialogModality()); if (dialog.exec() == QMessageBox::Yes) { // m_exitCode = EXIT_RESTART; QApplication::closeAllWindows(); } } void MainWindow::backup() { QFileInfo info(m_currentFile); auto dateTime = info.lastModified().toString(Qt::ISODate); dateTime.replace(':', '-'); auto filename = QStringLiteral("%1/%2 %3.mlt").arg(info.canonicalPath(), info.completeBaseName(), dateTime); if (!QFile::exists(filename) && !Util::warnIfNotWritable(filename, this, tr("Save XML")) && QFile::copy(m_currentFile, filename)) { showStatusMessage(tr("Saved backup %1").arg(filename)); } } void MainWindow::backupPeriodically() { auto dateTime = QFileInfo(m_currentFile).lastModified(); if (Settings.backupPeriod() > 0 && !kBackupFileRegex.match(m_currentFile).hasMatch() && dateTime.secsTo(QDateTime::currentDateTime()) / 60 > Settings.backupPeriod()) { backup(); } } bool MainWindow::confirmProfileChange() { if (MLT.isClip() || !Settings.askChangeVideoMode()) return true; QMessageBox dialog(QMessageBox::Warning, QCoreApplication::applicationName(), tr("<p>Please review your entire project after making this change.</p>" "<p>Shotcut does not automatically adjust things that are sensitive to size and position if you change resolution or aspect ratio.</p" "<br>The timing of edits and keyframes may be slightly different if you change frame rate.</p>" "<p>It is a good idea to use <b>File > Backup and Save</b> before or after this operation.</p>" "<p>Do you want to change the <b>Video Mode</b> now?</p>"), QMessageBox::No | QMessageBox::Yes, &MAIN); dialog.setWindowModality(QmlApplication::dialogModality()); dialog.setDefaultButton(QMessageBox::Yes); dialog.setEscapeButton(QMessageBox::No); dialog.setCheckBox(new QCheckBox(tr("Do not show this anymore.", "Change video mode warning dialog"))); auto result = QMessageBox::Yes == dialog.exec(); if (dialog.checkBox()->isChecked()) Settings.setAskChangeVideoMode(false); return result; } void MainWindow::on_actionSystemTheme_triggered() { Settings.setTheme("system"); restartAfterChangeTheme(); } void MainWindow::on_actionFusionDark_triggered() { Settings.setTheme("dark"); restartAfterChangeTheme(); } void MainWindow::on_actionFusionLight_triggered() { Settings.setTheme("light"); restartAfterChangeTheme(); } void MainWindow::on_actionJobPriorityLow_triggered() { Settings.setJobPriority("low"); } void MainWindow::on_actionJobPriorityNormal_triggered() { Settings.setJobPriority("normal"); } void MainWindow::on_actionTutorials_triggered() { QDesktopServices::openUrl(QUrl("https://www.shotcut.org/tutorials/")); } void MainWindow::on_actionRestoreLayout_triggered() { auto mode = Settings.layoutMode(); if (mode != LayoutMode::Custom) { // Clear the saved layout for this mode Settings.setLayout(QString(kReservedLayoutPrefix).arg(mode), QByteArray(), QByteArray()); // Reset the layout mode so the current layout is saved as custom when trigger action Settings.setLayoutMode(); } switch (mode) { case LayoutMode::Custom: ui->actionLayoutEditing->setChecked(true); Q_FALLTHROUGH(); case LayoutMode::Editing: on_actionLayoutEditing_triggered(); break; case LayoutMode::Logging: on_actionLayoutLogging_triggered(); break; case LayoutMode::Effects: on_actionLayoutEffects_triggered(); break; case LayoutMode::Color: on_actionLayoutColor_triggered(); break; case LayoutMode::Audio: on_actionLayoutAudio_triggered(); break; case LayoutMode::PlayerOnly: on_actionLayoutPlayer_triggered(); break; } } void MainWindow::on_actionShowTitleBars_triggered(bool checked) { QList <QDockWidget *> docks = findChildren<QDockWidget *>(); for (int i = 0; i < docks.count(); i++) { QDockWidget *dock = docks.at(i); if (checked) { dock->setTitleBarWidget(0); } else { if (!dock->isFloating()) { dock->setTitleBarWidget(new QWidget); } } } Settings.setShowTitleBars(checked); } void MainWindow::on_actionShowToolbar_triggered(bool checked) { ui->mainToolBar->setVisible(checked); } void MainWindow::onToolbarVisibilityChanged(bool visible) { ui->actionShowToolbar->setChecked(visible); Settings.setShowToolBar(visible); } void MainWindow::on_menuExternal_aboutToShow() { #ifdef USE_SCREENS_FOR_EXTERNAL_MONITORING foreach (QAction *action, m_externalGroup->actions()) { bool ok = false; int i = action->data().toInt(&ok); if (ok && i < QGuiApplication::screens().count()) { if (QGuiApplication::screens().at(i) == screen()) { if (action->isChecked()) { m_externalGroup->actions().first()->setChecked(true); Settings.setPlayerExternal(QString()); } action->setDisabled(true); } else { action->setEnabled(true); } } } #endif } void MainWindow::on_actionUpgrade_triggered() { if (Settings.askUpgradeAutomatic()) { QMessageBox dialog(QMessageBox::Question, qApp->applicationName(), tr("Do you want to automatically check for updates in the future?"), QMessageBox::No | QMessageBox::Yes, this); dialog.setWindowModality(QmlApplication::dialogModality()); dialog.setDefaultButton(QMessageBox::Yes); dialog.setEscapeButton(QMessageBox::No); dialog.setCheckBox(new QCheckBox(tr("Do not show this anymore.", "Automatic upgrade check dialog"))); Settings.setCheckUpgradeAutomatic(dialog.exec() == QMessageBox::Yes); if (dialog.checkBox()->isChecked()) Settings.setAskUpgradeAutomatic(false); } showStatusMessage("Checking for upgrade..."); m_network.get(QNetworkRequest(QUrl("https://check.shotcut.org/version.json"))); } void MainWindow::on_actionOpenXML_triggered() { QString path = Settings.openPath(); #ifdef Q_OS_MAC path.append("/*"); #endif QStringList filenames = QFileDialog::getOpenFileNames(this, tr("Open File"), path, tr("MLT XML (*.mlt);;All Files (*)"), nullptr, Util::getFileDialogOptions()); if (filenames.length() > 0) { QString url = filenames.first(); MltXmlChecker checker; if (checker.check(url) == QXmlStreamReader::NoError) { if (!isCompatibleWithGpuMode(checker)) return; isXmlRepaired(checker, url); } else { showStatusMessage(tr("Failed to open ").append(url)); showIncompatibleProjectMessage(checker.shotcutVersion()); return; } Settings.setOpenPath(QFileInfo(url).path()); activateWindow(); if (filenames.length() > 1) m_multipleFiles = filenames; if (!MLT.openXML(url)) { open(MLT.producer()); m_recentDock->add(url); LOG_INFO() << url; } else { showStatusMessage(tr("Failed to open ") + url); emit openFailed(url); } } } void MainWindow::on_actionShowProjectFolder_triggered() { Util::showInFolder(m_currentFile); } void MainWindow::onFocusChanged(QWidget *, QWidget * ) const { LOG_DEBUG() << "Focuswidget changed"; LOG_DEBUG() << "Current focusWidget:" << QApplication::focusWidget(); LOG_DEBUG() << "Current focusObject:" << QApplication::focusObject(); LOG_DEBUG() << "Current focusWindow:" << QApplication::focusWindow(); } void MainWindow::on_actionScrubAudio_triggered(bool checked) { Settings.setPlayerScrubAudio(checked); } #if !defined(Q_OS_MAC) void MainWindow::onDrawingMethodTriggered(QAction *action) { Settings.setDrawMethod(action->data().toInt()); QMessageBox dialog(QMessageBox::Information, qApp->applicationName(), tr("You must restart Shotcut to change the display method.\n" "Do you want to restart now?"), QMessageBox::No | QMessageBox::Yes, this); dialog.setDefaultButton(QMessageBox::Yes); dialog.setEscapeButton(QMessageBox::No); dialog.setWindowModality(QmlApplication::dialogModality()); if (dialog.exec() == QMessageBox::Yes) { m_exitCode = EXIT_RESTART; QApplication::closeAllWindows(); } } #endif void MainWindow::on_actionResources_triggered() { ResourceDialog dialog(this); dialog.search(multitrack()); dialog.search(playlist()); dialog.exec(); } void MainWindow::on_actionApplicationLog_triggered() { TextViewerDialog dialog(this); QDir dir = Settings.appDataLocation(); QFile logFile(dir.filePath("shotcut-log.txt")); logFile.open(QIODevice::ReadOnly | QIODevice::Text); dialog.setText(logFile.readAll()); logFile.close(); dialog.setWindowTitle(tr("Application Log")); const auto previousLogName = dir.filePath("shotcut-log.bak"); if (QFile::exists(previousLogName)) { auto button = dialog.buttonBox()->addButton(tr("Previous"), QDialogButtonBox::ActionRole); connect(button, &QAbstractButton::clicked, this, [&]() { QFile logFile(previousLogName); logFile.open(QIODevice::ReadOnly | QIODevice::Text); dialog.setText(logFile.readAll()); logFile.close(); button->setEnabled(false); }); } dialog.exec(); } void MainWindow::on_actionClose_triggered() { m_timelineDock->stopRecording(); if (continueModified()) { LOG_DEBUG() << ""; QMutexLocker locker(&m_autosaveMutex); m_autosaveFile.reset(); locker.unlock(); setCurrentFile(""); MLT.resetURL(); MLT.setProjectFolder(QString()); ui->actionSave->setEnabled(false); MLT.stop(); if (MLT.consumer() && MLT.consumer()->is_valid()) MLT.consumer()->purge(); QCoreApplication::processEvents(); if (multitrack()) m_timelineDock->model()->close(); if (playlist()) m_playlistDock->model()->close(); else onMultitrackClosed(); m_notesDock->setText(""); m_player->enableTab(Player::SourceTabIndex, false); MLT.purgeMemoryPool(); } } void MainWindow::onPlayerTabIndexChanged(int index) { if (Player::SourceTabIndex == index) m_timelineDock->saveAndClearSelection(); else m_timelineDock->restoreSelection(); } void MainWindow::onUpgradeCheckFinished(QNetworkReply *reply) { if (!reply->error()) { QByteArray response = reply->readAll(); LOG_DEBUG() << "response: " << response; QJsonDocument json = QJsonDocument::fromJson(response); QString current = qApp->applicationVersion(); if (!json.isNull() && json.object().value("version_string").type() == QJsonValue::String) { QString latest = json.object().value("version_string").toString(); if (current != "adhoc" && QVersionNumber::fromString(current) < QVersionNumber::fromString(latest)) { QAction *action = new QAction(tr("Shotcut version %1 is available! Click here to get it.").arg( latest), 0); connect(action, SIGNAL(triggered(bool)), SLOT(onUpgradeTriggered())); if (!json.object().value("url").isUndefined()) m_upgradeUrl = json.object().value("url").toString(); showStatusMessage(action, 15 /* seconds */); } else { showStatusMessage(tr("You are running the latest version of Shotcut.")); } reply->deleteLater(); return; } else { LOG_WARNING() << "failed to parse version.json"; } } else { LOG_WARNING() << reply->errorString(); if (reply->error() == QNetworkReply::UnknownNetworkError) { m_network.get(QNetworkRequest(QUrl("http://check.shotcut.org/version.json"))); } } QAction *action = new QAction( tr("Failed to read version.json when checking. Click here to go to the Web site."), 0); connect(action, SIGNAL(triggered(bool)), SLOT(onUpgradeTriggered())); showStatusMessage(action); reply->deleteLater(); } void MainWindow::onUpgradeTriggered() { QDesktopServices::openUrl(QUrl(m_upgradeUrl)); } void MainWindow::onClipCopied() { m_player->enableTab(Player::SourceTabIndex); } void MainWindow::on_actionExportEDL_triggered() { // Dialog to get export file name. QString path = Settings.savePath(); QString caption = tr("Export EDL"); QString saveFileName = QFileDialog::getSaveFileName(this, caption, path, tr("EDL (*.edl);;All Files (*)"), nullptr, Util::getFileDialogOptions()); if (!saveFileName.isEmpty()) { QFileInfo fi(saveFileName); if (fi.suffix() != "edl") saveFileName += ".edl"; if (Util::warnIfNotWritable(saveFileName, this, caption)) return; // Locate the JavaScript file in the filesystem. QDir qmlDir = QmlUtilities::qmlDir(); qmlDir.cd("export-edl"); QString jsFileName = qmlDir.absoluteFilePath("export-edl.js"); QFile scriptFile(jsFileName); if (scriptFile.open(QIODevice::ReadOnly)) { // Read JavaScript into a string. QTextStream stream(&scriptFile); stream.setEncoding(QStringConverter::Utf8); stream.setAutoDetectUnicode(true); QString contents = stream.readAll(); scriptFile.close(); // Evaluate JavaScript. QJSEngine jsEngine; QJSValue result = jsEngine.evaluate(contents, jsFileName); if (!result.isError()) { // Call the JavaScript main function. QJSValue options = jsEngine.newObject(); options.setProperty("useBaseNameForReelName", true); options.setProperty("useBaseNameForClipComment", true); options.setProperty("channelsAV", "AA/V"); QJSValueList args; args << MLT.XML(0, true, true) << options; result = result.call(args); if (!result.isError()) { // Save the result with the export file name. QFile f(saveFileName); f.open(QIODevice::WriteOnly | QIODevice::Text); f.write(result.toString().toUtf8()); f.close(); } } if (result.isError()) { LOG_ERROR() << "Uncaught exception at line" << result.property("lineNumber").toInt() << ":" << result.toString(); showStatusMessage(tr("A JavaScript error occurred during export.")); } } else { showStatusMessage(tr("Failed to open export-edl.js")); } } } void MainWindow::on_actionExportFrame_triggered() { if (!MLT.producer() || !MLT.producer()->is_valid()) return; filterController()->setCurrentFilter(QmlFilter::DeselectCurrentFilter); auto *videoWidget = qobject_cast<Mlt::VideoWidget *>(MLT.videoWidget()); connect(videoWidget, &Mlt::VideoWidget::imageReady, this, &MainWindow::onVideoWidgetImageReady); MLT.setPreviewScale(0); videoWidget->requestImage(); MLT.refreshConsumer(); } void MainWindow::onVideoWidgetImageReady() { auto *videoWidget = qobject_cast<Mlt::VideoWidget *>(MLT.videoWidget()); QImage image = videoWidget->image(); disconnect(videoWidget, SIGNAL(imageReady()), this, nullptr); if (Settings.playerGPU() || Settings.playerPreviewScale()) { MLT.setPreviewScale(Settings.playerPreviewScale()); } if (!image.isNull() && (videoWidget->imageIsProxy() || (MLT.isMultitrack() && Settings.proxyEnabled())) ) { QMessageBox dialog(QMessageBox::Question, tr("Export frame from proxy?"), tr("This frame may be from a lower resolution proxy instead of the original source.\n\n" "Do you still want to continue?"), QMessageBox::No | QMessageBox::Yes, this); dialog.setDefaultButton(QMessageBox::Yes); dialog.setEscapeButton(QMessageBox::No); dialog.setWindowModality(QmlApplication::dialogModality()); if (dialog.exec() != QMessageBox::Yes) { return; } } if (!image.isNull()) { SaveImageDialog dialog(this, tr("Export Frame"), image); dialog.exec(); if (!dialog.saveFile().isEmpty()) { m_recentDock->add(dialog.saveFile()); } } else { showStatusMessage(tr("Unable to export frame.")); } } void MainWindow::on_actionAppDataSet_triggered() { QMessageBox dialog(QMessageBox::Information, qApp->applicationName(), tr("You must restart Shotcut to change the data directory.\n" "Do you want to continue?"), QMessageBox::No | QMessageBox::Yes, this); dialog.setDefaultButton(QMessageBox::Yes); dialog.setEscapeButton(QMessageBox::No); dialog.setWindowModality(QmlApplication::dialogModality()); if (dialog.exec() != QMessageBox::Yes) return; QString dirName = QFileDialog::getExistingDirectory(this, tr("Data Directory"), Settings.appDataLocation(), Util::getFileDialogOptions()); if (!dirName.isEmpty()) { // Move the data files. QDirIterator it(Settings.appDataLocation()); while (it.hasNext()) { if (!it.filePath().isEmpty() && it.fileName() != "." && it.fileName() != "..") { if (!QFile::exists(dirName + "/" + it.fileName())) { if (it.fileInfo().isDir()) { if (!QFile::rename(it.filePath(), dirName + "/" + it.fileName())) LOG_WARNING() << "Failed to move" << it.filePath() << "to" << dirName + "/" + it.fileName(); } else { if (!QFile::copy(it.filePath(), dirName + "/" + it.fileName())) LOG_WARNING() << "Failed to copy" << it.filePath() << "to" << dirName + "/" + it.fileName(); } } } it.next(); } writeSettings(); Settings.setAppDataLocally(dirName); m_exitCode = EXIT_RESTART; QApplication::closeAllWindows(); } } void MainWindow::on_actionAppDataShow_triggered() { // Make the transitions sub-folder if it does not exist QmlApplication::wipes(); Util::showInFolder(Settings.appDataLocation()); } void MainWindow::on_actionNew_triggered() { on_actionClose_triggered(); } void MainWindow::on_actionKeyboardShortcuts_triggered() { auto name = QString::fromLatin1("actionsDialog"); auto dialog = QObject::findChild<ActionsDialog *>(name, Qt::FindDirectChildrenOnly); if (!dialog) { dialog = new ActionsDialog(this); dialog->setObjectName(name); } dialog->show(); dialog->activateWindow(); dialog->raise(); } void MainWindow::on_actionLayoutLogging_triggered() { Settings.setLayout(QString(kReservedLayoutPrefix).arg(Settings.layoutMode()), QByteArray(), saveState()); Settings.setLayoutMode(LayoutMode::Logging); auto state = Settings.layoutState(QString(kReservedLayoutPrefix).arg(LayoutMode::Logging)); if (state.isEmpty()) { restoreState(kLayoutLoggingDefault); // setCorner(Qt::TopLeftCorner, Qt::LeftDockWidgetArea); // setCorner(Qt::TopRightCorner, Qt::RightDockWidgetArea); // setCorner(Qt::BottomLeftCorner, Qt::LeftDockWidgetArea); // setCorner(Qt::BottomRightCorner, Qt::RightDockWidgetArea); // resizeDocks({m_playlistDock, m_propertiesDock}, // {qFloor(width() * 0.25), qFloor(width() * 0.25)}, Qt::Horizontal); } else { // LOG_DEBUG() << state.toBase64(); restoreState(state); } Settings.setWindowState(saveState()); } void MainWindow::on_actionLayoutEditing_triggered() { Settings.setLayout(QString(kReservedLayoutPrefix).arg(Settings.layoutMode()), QByteArray(), saveState()); Settings.setLayoutMode(LayoutMode::Editing); auto state = Settings.layoutState(QString(kReservedLayoutPrefix).arg(LayoutMode::Editing)); if (state.isEmpty()) { restoreState(kLayoutEditingDefault); // resetDockCorners(); } else { // LOG_DEBUG() << state.toBase64(); restoreState(state); } Settings.setWindowState(saveState()); } void MainWindow::on_actionLayoutEffects_triggered() { Settings.setLayout(QString(kReservedLayoutPrefix).arg(Settings.layoutMode()), QByteArray(), saveState()); Settings.setLayoutMode(LayoutMode::Effects); auto state = Settings.layoutState(QString(kReservedLayoutPrefix).arg(LayoutMode::Effects)); if (state.isEmpty()) { restoreState(kLayoutEffectsDefault); // resetDockCorners(); } else { // LOG_DEBUG() << state.toBase64(); restoreState(state); } Settings.setWindowState(saveState()); } void MainWindow::on_actionLayoutColor_triggered() { Settings.setLayout(QString(kReservedLayoutPrefix).arg(Settings.layoutMode()), QByteArray(), saveState()); Settings.setLayoutMode(LayoutMode::Color); auto state = Settings.layoutState(QString(kReservedLayoutPrefix).arg(LayoutMode::Color)); if (state.isEmpty()) { restoreState(kLayoutColorDefault); // setCorner(Qt::TopLeftCorner, Qt::LeftDockWidgetArea); // setCorner(Qt::TopRightCorner, Qt::RightDockWidgetArea); // setCorner(Qt::BottomLeftCorner, Qt::BottomDockWidgetArea); // setCorner(Qt::BottomRightCorner, Qt::RightDockWidgetArea); } else { // LOG_DEBUG() << state.toBase64(); restoreState(state); } Settings.setWindowState(saveState()); } void MainWindow::on_actionLayoutAudio_triggered() { Settings.setLayout(QString(kReservedLayoutPrefix).arg(Settings.layoutMode()), QByteArray(), saveState()); Settings.setLayoutMode(LayoutMode::Audio); auto state = Settings.layoutState(QString(kReservedLayoutPrefix).arg(LayoutMode::Audio)); if (state.isEmpty()) { restoreState(kLayoutAudioDefault); // setCorner(Qt::TopLeftCorner, Qt::LeftDockWidgetArea); // setCorner(Qt::TopRightCorner, Qt::RightDockWidgetArea); // setCorner(Qt::BottomLeftCorner, Qt::BottomDockWidgetArea); // setCorner(Qt::BottomRightCorner, Qt::RightDockWidgetArea); } else { // LOG_DEBUG() << state.toBase64(); restoreState(state); } Settings.setWindowState(saveState()); } void MainWindow::on_actionLayoutPlayer_triggered() { if (isMultitrackValid()) { // Clearing selection causes Filters to clear, which prevents showing a filter's VUI m_timelineDock->setSelection(); } Settings.setLayout(QString(kReservedLayoutPrefix).arg(Settings.layoutMode()), QByteArray(), saveState()); Settings.setLayoutMode(LayoutMode::PlayerOnly); auto state = Settings.layoutState(QString(kReservedLayoutPrefix).arg(LayoutMode::PlayerOnly)); if (state.isEmpty()) { restoreState(kLayoutPlayerDefault); // resetDockCorners(); } else { // LOG_DEBUG() << state.toBase64(); restoreState(state); } Settings.setWindowState(saveState()); } void MainWindow::on_actionLayoutPlaylist_triggered() { if (Settings.layoutMode() != LayoutMode::Custom) { Settings.setLayout(QString(kReservedLayoutPrefix).arg(Settings.layoutMode()), QByteArray(), saveState()); Settings.setLayoutMode(LayoutMode::Custom); } clearCurrentLayout(); restoreState(Settings.windowStateDefault()); m_recentDock->show(); m_recentDock->raise(); m_playlistDock->show(); m_playlistDock->raise(); Settings.setWindowState(saveState()); } void MainWindow::on_actionLayoutClip_triggered() { if (Settings.layoutMode() != LayoutMode::Custom) { Settings.setLayout(QString(kReservedLayoutPrefix).arg(Settings.layoutMode()), QByteArray(), saveState()); Settings.setLayoutMode(LayoutMode::Custom); } clearCurrentLayout(); restoreState(Settings.windowStateDefault()); m_recentDock->show(); m_recentDock->raise(); m_filtersDock->show(); m_filtersDock->raise(); Settings.setWindowState(saveState()); } void MainWindow::on_actionLayoutAdd_triggered() { QInputDialog dialog(this); dialog.setInputMode(QInputDialog::TextInput); dialog.setWindowTitle(tr("Add Custom Layout")); dialog.setLabelText(tr("Name")); dialog.setWindowModality(QmlApplication::dialogModality()); auto result = dialog.exec(); auto name = dialog.textValue(); if (result == QDialog::Accepted && !name.isEmpty()) { if (Settings.setLayout(name, saveGeometry(), saveState())) { Settings.setLayoutMode(); clearCurrentLayout(); Settings.sync(); if (Settings.layouts().size() == 1) { ui->menuLayout->addAction(ui->actionLayoutRemove); ui->menuLayout->addSeparator(); } ui->menuLayout->addAction(addLayout(m_layoutGroup, name)); } } } void MainWindow::onLayoutTriggered(QAction *action) { if (Settings.layoutMode() != LayoutMode::Custom) { Settings.setLayout(QString(kReservedLayoutPrefix).arg(Settings.layoutMode()), QByteArray(), saveState()); Settings.setLayoutMode(LayoutMode::Custom); } clearCurrentLayout(); restoreState(Settings.layoutState(action->text())); Settings.setWindowState(saveState()); } void MainWindow::on_actionProfileRemove_triggered() { QDir dir(Settings.appDataLocation()); if (dir.cd("profiles")) { // Setup the dialog. QStringList profiles = dir.entryList(QDir::Files | QDir::NoDotAndDotDot | QDir::Readable); ListSelectionDialog dialog(profiles, this); dialog.setWindowModality(QmlApplication::dialogModality()); dialog.setWindowTitle(tr("Remove Video Mode")); // Show the dialog. if (dialog.exec() == QDialog::Accepted) { removeCustomProfiles(dialog.selection(), dir, customProfileMenu(), actionProfileRemove()); } } } void MainWindow::on_actionLayoutRemove_triggered() { // Setup the dialog. ListSelectionDialog dialog(Settings.layouts(), this); dialog.setWindowModality(QmlApplication::dialogModality()); dialog.setWindowTitle(tr("Remove Layout")); // Show the dialog. if (dialog.exec() == QDialog::Accepted) { foreach (const QString &layout, dialog.selection()) { // Update the configuration. if (Settings.removeLayout(layout)) Settings.sync(); // Locate the menu item. foreach (QAction *action, ui->menuLayout->actions()) { if (action->text() == layout) { // Remove the menu item. delete action; break; } } } // If no more custom layouts. if (Settings.layouts().size() == 0) { // Remove the Remove action and separator. ui->menuLayout->removeAction(ui->actionLayoutRemove); bool isSecondSeparator = false; foreach (QAction *action, ui->menuLayout->actions()) { if (action->isSeparator()) { if (isSecondSeparator) { delete action; break; } else { isSecondSeparator = true; } } } } } } void MainWindow::on_actionOpenOther2_triggered() { ui->actionOpenOther2->menu()->popup(mapToGlobal(ui->mainToolBar->geometry().bottomLeft()) + QPoint( 64, 0)); } void MainWindow::onOpenOtherTriggered(QWidget *widget) { m_producerWidget.reset(widget); auto dialog = new QDialog(this); dialog->resize(426, 288); dialog->setWindowModality(QmlApplication::dialogModality()); auto vlayout = new QVBoxLayout(dialog); vlayout->addWidget(widget); auto buttonBox = new QDialogButtonBox(dialog); buttonBox->setOrientation(Qt::Horizontal); buttonBox->setStandardButtons(QDialogButtonBox::Cancel | QDialogButtonBox::Open); if (!AbstractProducerWidget::isDevice(widget)) { auto button = buttonBox->addButton(tr("Add To Timeline"), QDialogButtonBox::ApplyRole); connect(button, &QPushButton::clicked, this, [ = ]() { dialog->done(-1); }); } vlayout->addWidget(buttonBox); connect(buttonBox, &QDialogButtonBox::accepted, dialog, &QDialog::accept); connect(buttonBox, &QDialogButtonBox::rejected, dialog, &QDialog::reject); connect(dialog, &QDialog::finished, this, &MainWindow::onOpenOtherFinished); dialog->show(); } void MainWindow::onOpenOtherFinished(int result) { if (QDialog::Rejected == result || !m_producerWidget) return; if (AbstractProducerWidget::isDevice(m_producerWidget.get()) && !Settings.playerGPU()) closeProducer(); auto &profile = MLT.profile(); auto producer = dynamic_cast<AbstractProducerWidget *>( m_producerWidget.get())->newProducer(profile); if (!(producer && producer->is_valid())) { delete producer; m_producerWidget.reset(); return; } if (!profile.is_explicit()) { profile.from_producer(*producer); profile.set_width(Util::coerceMultiple(profile.width())); profile.set_height(Util::coerceMultiple(profile.height())); } MLT.updatePreviewProfile(); setPreviewScale(Settings.playerPreviewScale()); auto name = m_producerWidget->objectName(); if (QDialog::Accepted == result) { // open in the source player open(producer); // Mlt::Controller owns the producer now } else { auto trackType = ("ToneProducerWidget" == name || "toneWidget" == name) ? AudioTrackType : VideoTrackType; auto trackIndex = m_timelineDock->addTrackIfNeeded(trackType); m_timelineDock->overwrite(trackIndex, -1, MLT.XML(producer), false); delete producer; } if ("TextProducerWidget" == name || "textWidget" == name) { m_filtersDock->show(); m_filtersDock->raise(); } else { m_propertiesDock->show(); m_propertiesDock->raise(); } m_producerWidget.reset(); } void MainWindow::onOpenOtherTriggered() { if (sender()->objectName() == "color") onOpenOtherTriggered(new ColorProducerWidget(this)); else if (sender()->objectName() == "text") onOpenOtherTriggered(new TextProducerWidget(this)); else if (sender()->objectName() == "glaxnimate") onOpenOtherTriggered(new GlaxnimateProducerWidget(this)); else if (sender()->objectName() == "noise") onOpenOtherTriggered(new NoiseWidget(this)); else if (sender()->objectName() == "ising0r") onOpenOtherTriggered(new IsingWidget(this)); else if (sender()->objectName() == "lissajous0r") onOpenOtherTriggered(new LissajousWidget(this)); else if (sender()->objectName() == "plasma") onOpenOtherTriggered(new PlasmaWidget(this)); else if (sender()->objectName() == "test_pat_B") onOpenOtherTriggered(new ColorBarsWidget(this)); else if (sender()->objectName() == "tone") onOpenOtherTriggered(new ToneProducerWidget(this)); else if (sender()->objectName() == "count") onOpenOtherTriggered(new CountProducerWidget(this)); else if (sender()->objectName() == "blipflash") onOpenOtherTriggered(new BlipProducerWidget(this)); else if (sender()->objectName() == "v4l2") onOpenOtherTriggered(new Video4LinuxWidget(this)); else if (sender()->objectName() == "pulse") onOpenOtherTriggered(new PulseAudioWidget(this)); else if (sender()->objectName() == "jack") onOpenOtherTriggered(new JackProducerWidget(this)); else if (sender()->objectName() == "alsa") onOpenOtherTriggered(new AlsaWidget(this)); #if defined(Q_OS_MAC) else if (sender()->objectName() == "device") onOpenOtherTriggered(new AvfoundationProducerWidget(this)); #elif defined(Q_OS_WIN) else if (sender()->objectName() == "device") onOpenOtherTriggered(new DirectShowVideoWidget(this)); #endif else if (sender()->objectName() == "decklink") onOpenOtherTriggered(new DecklinkProducerWidget(this)); } void MainWindow::on_actionClearRecentOnExit_toggled(bool arg1) { Settings.setClearRecent(arg1); if (arg1) Settings.setRecent(QStringList()); } void MainWindow::onSceneGraphInitialized() { if (Settings.playerGPU() && Settings.playerWarnGPU()) { QMessageBox dialog(QMessageBox::Warning, qApp->applicationName(), tr("GPU effects are EXPERIMENTAL, UNSTABLE and UNSUPPORTED! Unsupported means do not report bugs about it.\n\n" "Do you want to disable GPU effects and restart Shotcut?"), QMessageBox::No | QMessageBox::Yes, this); dialog.setDefaultButton(QMessageBox::Yes); dialog.setEscapeButton(QMessageBox::No); dialog.setWindowModality(QmlApplication::dialogModality()); if (dialog.exec() == QMessageBox::Yes) { ui->actionGPU->setChecked(false); m_exitCode = EXIT_RESTART; QApplication::closeAllWindows(); } else { ui->actionGPU->setVisible(true); } } else { ui->actionGPU->setVisible(true); } auto videoWidget = (Mlt::VideoWidget *) & (MLT); videoWidget->setBlankScene(); } void MainWindow::on_actionShowTextUnderIcons_toggled(bool b) { ui->mainToolBar->setToolButtonStyle(b ? Qt::ToolButtonTextUnderIcon : Qt::ToolButtonIconOnly); Settings.setTextUnderIcons(b); updateLayoutSwitcher(); } void MainWindow::on_actionShowSmallIcons_toggled(bool b) { ui->mainToolBar->setIconSize(b ? QSize(16, 16) : QSize()); Settings.setSmallIcons(b); updateLayoutSwitcher(); } void MainWindow::onPlaylistInChanged(int in) { m_player->blockSignals(true); m_player->setIn(in); m_player->blockSignals(false); } void MainWindow::onPlaylistOutChanged(int out) { m_player->blockSignals(true); m_player->setOut(out); m_player->blockSignals(false); } void MainWindow::on_actionPreviewNone_triggered(bool checked) { if (checked) { Settings.setPlayerPreviewScale(0); setPreviewScale(0); m_player->showIdleStatus(); } } void MainWindow::on_actionPreview360_triggered(bool checked) { if (checked) { Settings.setPlayerPreviewScale(360); setPreviewScale(360); m_player->showIdleStatus(); } } void MainWindow::on_actionPreview540_triggered(bool checked) { if (checked) { Settings.setPlayerPreviewScale(540); setPreviewScale(540); m_player->showIdleStatus(); } } void MainWindow::on_actionPreview720_triggered(bool checked) { if (checked) { Settings.setPlayerPreviewScale(720); setPreviewScale(720); m_player->showIdleStatus(); } } QUuid MainWindow::timelineClipUuid(int trackIndex, int clipIndex) { auto info = m_timelineDock->model()->getClipInfo(trackIndex, clipIndex); if (info && info->producer && info->producer->is_valid()) return MLT.ensureHasUuid(*info->producer); return QUuid(); } void MainWindow::replaceInTimeline(const QUuid &uuid, Mlt::Producer &producer) { int trackIndex = -1; int clipIndex = -1; // lookup the current track and clip index by UUID auto info = m_timelineDock->model()->findClipByUuid(uuid, trackIndex, clipIndex); if (info && trackIndex >= 0 && clipIndex >= 0) { Util::getHash(producer); Util::applyCustomProperties(producer, *info->producer, producer.get_in(), producer.get_out()); m_timelineDock->replace(trackIndex, clipIndex, MLT.XML(&producer)); } } void MainWindow::replaceAllByHash(const QString &hash, Mlt::Producer &producer, bool isProxy) { Util::getHash(producer); if (!isProxy) m_recentDock->add(producer.get("resource")); if (MLT.isClip() && Util::getHash(*MLT.producer()) == hash) { Util::applyCustomProperties(producer, *MLT.producer(), MLT.producer()->get_in(), MLT.producer()->get_out()); MLT.copyFilters(*MLT.producer(), producer); MLT.close(); m_player->setPauseAfterOpen(true); open(new Mlt::Producer(MLT.profile(), "xml-string", MLT.XML(&producer).toUtf8().constData())); } else if (MLT.savedProducer() && Util::getHash(*MLT.savedProducer()) == hash) { Util::applyCustomProperties(producer, *MLT.savedProducer(), MLT.savedProducer()->get_in(), MLT.savedProducer()->get_out()); MLT.copyFilters(*MLT.savedProducer(), producer); MLT.setSavedProducer(&producer); } if (playlist()) { if (isProxy) { m_playlistDock->replaceClipsWithHash(hash, producer); } else { // Append to playlist producer.set(kPlaylistIndexProperty, playlist()->count()); MAIN.undoStack()->push( new Playlist::AppendCommand(*m_playlistDock->model(), MLT.XML(&producer))); } } if (isMultitrackValid()) { m_timelineDock->replaceClipsWithHash(hash, producer); } } int MainWindow::mltIndexForTrack(int trackIndex) const { return m_timelineDock->model()->mltIndexForTrack(trackIndex); } int MainWindow::bottomVideoTrackIndex() const { return m_timelineDock->model()->bottomVideoTrackIndex(); } void MainWindow::on_actionTopics_triggered() { QDesktopServices::openUrl(QUrl("https://www.shotcut.org/howtos/")); } void MainWindow::on_actionSync_triggered() { auto dialog = new SystemSyncDialog(this); dialog->show(); dialog->raise(); dialog->activateWindow(); } void MainWindow::on_actionUseProxy_triggered(bool checked) { if (MLT.producer()) { QDir dir(m_currentFile.isEmpty() ? QDir::tempPath() : QFileInfo(m_currentFile).dir()); QScopedPointer<QTemporaryFile> tmp(new QTemporaryFile(dir.filePath("shotcut-XXXXXX.mlt"))); tmp->open(); tmp->close(); QString fileName = tmp->fileName(); tmp->remove(); tmp.reset(); LOG_DEBUG() << fileName; if (saveXML(fileName)) { MltXmlChecker checker; Settings.setProxyEnabled(checked); checker.check(fileName); if (!isXmlRepaired(checker, fileName)) { QFile::remove(fileName); return; } if (checker.isUpdated()) { QFile::remove(fileName); fileName = checker.tempFile().fileName(); } // Open the temporary file int result = 0; { LongUiTask longTask(checked ? tr("Turn Proxy On") : tr("Turn Proxy Off")); QFuture<int> future = QtConcurrent::run([ = ]() { return MLT.open(QDir::fromNativeSeparators(fileName), QDir::fromNativeSeparators(m_currentFile)); }); result = longTask.wait<int>(tr("Converting"), future); } if (!result) { auto position = m_player->position(); m_undoStack->clear(); m_player->stop(); m_player->setPauseAfterOpen(true); open(MLT.producer()); MLT.seek(m_player->position()); m_player->seek(position); if (checked && (isPlaylistValid() || isMultitrackValid())) { // Prompt user if they want to create missing proxies QMessageBox dialog(QMessageBox::Question, qApp->applicationName(), tr("Do you want to create missing proxies for every file in this project?\n\n" "You must reopen your project after all proxy jobs are finished."), QMessageBox::No | QMessageBox::Yes, this); dialog.setWindowModality(QmlApplication::dialogModality()); dialog.setDefaultButton(QMessageBox::Yes); dialog.setEscapeButton(QMessageBox::No); if (dialog.exec() == QMessageBox::Yes) { Mlt::Producer producer(playlist()); if (producer.is_valid()) { ProxyManager::generateIfNotExistsAll(producer); } producer = multitrack(); if (producer.is_valid()) { ProxyManager::generateIfNotExistsAll(producer); } } } } else if (fileName != untitledFileName()) { showStatusMessage(tr("Failed to open ") + fileName); emit openFailed(fileName); } } else { ui->actionUseProxy->setChecked(!checked); showSaveError(); } QFile::remove(fileName); } else { Settings.setProxyEnabled(checked); } m_player->showIdleStatus(); } void MainWindow::on_actionProxyStorageSet_triggered() { // Present folder dialog just like App Data Directory QString dirName = QFileDialog::getExistingDirectory(this, tr("Proxy Folder"), Settings.proxyFolder(), Util::getFileDialogOptions()); if (!dirName.isEmpty() && dirName != Settings.proxyFolder()) { auto oldFolder = Settings.proxyFolder(); Settings.setProxyFolder(dirName); Settings.sync(); // Get a count for the progress dialog auto oldDir = QDir(oldFolder); auto dirList = oldDir.entryList(QDir::Dirs | QDir::Files | QDir::NoDotAndDotDot); auto count = dirList.size(); if (count > 0) { // Prompt user if they want to create missing proxies QMessageBox dialog(QMessageBox::Question, qApp->applicationName(), tr("Do you want to move all files from the old folder to the new folder?"), QMessageBox::No | QMessageBox::Yes, this); dialog.setWindowModality(QmlApplication::dialogModality()); dialog.setDefaultButton(QMessageBox::Yes); dialog.setEscapeButton(QMessageBox::No); if (dialog.exec() == QMessageBox::Yes) { // Move the existing files LongUiTask longTask(tr("Moving Files")); int i = 0; for (const auto &fileName : dirList) { if (!fileName.isEmpty() && !QFile::exists(dirName + "/" + fileName)) { LOG_DEBUG() << "moving" << oldDir.filePath(fileName) << "to" << dirName + "/" + fileName; longTask.reportProgress(fileName, i++, count); if (!QFile::rename(oldDir.filePath(fileName), dirName + "/" + fileName)) LOG_WARNING() << "Failed to move" << oldDir.filePath(fileName); } } } } } } void MainWindow::on_actionProxyStorageShow_triggered() { Util::showInFolder(ProxyManager::dir().path()); } void MainWindow::on_actionProxyUseProjectFolder_triggered(bool checked) { Settings.setProxyUseProjectFolder(checked); } void MainWindow::on_actionProxyUseHardware_triggered(bool checked) { if (checked && Settings.encodeHardware().isEmpty()) { if (!m_encodeDock->detectHardwareEncoders()) ui->actionProxyUseHardware->setChecked(false); } Settings.setProxyUseHardware(ui->actionProxyUseHardware->isChecked()); } void MainWindow::on_actionProxyConfigureHardware_triggered() { m_encodeDock->on_hwencodeButton_clicked(); if (Settings.encodeHardware().isEmpty()) { ui->actionProxyUseHardware->setChecked(false); Settings.setProxyUseHardware(false); } } void MainWindow::updateLayoutSwitcher() { if (Settings.textUnderIcons() && !Settings.smallIcons()) { auto layoutSwitcher = findChild<QWidget *>(kLayoutSwitcherName); if (layoutSwitcher) { layoutSwitcher->show(); for (const auto &child : layoutSwitcher->findChildren<QToolButton *>()) { child->show(); } } else { layoutSwitcher = new QWidget; layoutSwitcher->setObjectName(kLayoutSwitcherName); auto layoutGrid = new QGridLayout(layoutSwitcher); layoutGrid->setContentsMargins(0, 0, 0, 0); ui->mainToolBar->insertWidget(ui->dummyAction, layoutSwitcher); auto button = new QToolButton; button->setAutoRaise(true); button->setDefaultAction(ui->actionLayoutLogging); layoutGrid->addWidget(button, 0, 0, Qt::AlignCenter); button = new QToolButton; button->setAutoRaise(true); button->setDefaultAction(ui->actionLayoutEditing); layoutGrid->addWidget(button, 0, 1, Qt::AlignCenter); button = new QToolButton; button->setAutoRaise(true); button->setDefaultAction(ui->actionLayoutEffects); layoutGrid->addWidget(button, 0, 2, Qt::AlignCenter); button = new QToolButton; button->setAutoRaise(true); button->setDefaultAction(ui->actionLayoutColor); layoutGrid->addWidget(button, 1, 0, Qt::AlignCenter); button = new QToolButton; button->setAutoRaise(true); button->setDefaultAction(ui->actionLayoutAudio); layoutGrid->addWidget(button, 1, 1, Qt::AlignCenter); button = new QToolButton; button->setAutoRaise(true); button->setDefaultAction(ui->actionLayoutPlayer); layoutGrid->addWidget(button, 1, 2, Qt::AlignCenter); } ui->mainToolBar->removeAction(ui->actionLayoutLogging); ui->mainToolBar->removeAction(ui->actionLayoutEditing); ui->mainToolBar->removeAction(ui->actionLayoutEffects); ui->mainToolBar->removeAction(ui->actionLayoutColor); ui->mainToolBar->removeAction(ui->actionLayoutAudio); ui->mainToolBar->removeAction(ui->actionLayoutPlayer); } else { auto layoutSwitcher = findChild<QWidget *>(kLayoutSwitcherName); if (layoutSwitcher) { layoutSwitcher->hide(); for (const auto &child : layoutSwitcher->findChildren<QToolButton *>()) { child->hide(); } ui->mainToolBar->insertAction(ui->dummyAction, ui->actionLayoutLogging); ui->mainToolBar->insertAction(ui->dummyAction, ui->actionLayoutEditing); ui->mainToolBar->insertAction(ui->dummyAction, ui->actionLayoutEffects); ui->mainToolBar->insertAction(ui->dummyAction, ui->actionLayoutColor); ui->mainToolBar->insertAction(ui->dummyAction, ui->actionLayoutAudio); ui->mainToolBar->insertAction(ui->dummyAction, ui->actionLayoutPlayer); } } } void MainWindow::clearCurrentLayout() { auto currentLayout = ui->actionLayoutLogging->actionGroup()->checkedAction(); if (currentLayout) { currentLayout->setChecked(false); } } void MainWindow::onClipboardChanged() { auto s = QGuiApplication::clipboard()->text(); if (MLT.isMltXml(s) && !s.contains(kShotcutFiltersClipboard)) { m_clipboardUpdatedAt = QDateTime::currentDateTime(); LOG_DEBUG() << m_clipboardUpdatedAt; } } void MainWindow::sourceUpdated() { if (MLT.isClip()) { m_sourceUpdatedAt = QDateTime::currentDateTime(); } } void MainWindow::resetSourceUpdated() { m_sourceUpdatedAt.setSecsSinceEpoch(0); } void MainWindow::on_actionExportChapters_triggered() { // Options dialog auto uniqueColors = m_timelineDock->markersModel()->allColors(); if (uniqueColors.isEmpty()) { return; } std::sort(uniqueColors.begin(), uniqueColors.end(), [ = ](const QColor & a, const QColor & b) { if (a.hue() == b.hue()) { if (a.saturation() == b.saturation()) { return a.value() <= b.value(); } return a.saturation() <= b.saturation(); } return a.hue() <= b.hue(); }); QStringList colors; for (auto &color : uniqueColors) { colors << color.name(); } const auto rangesOption = tr("Include ranges (Duration > 1 frame)?"); QStringList initialOptions; for (auto &m : m_timelineDock->markersModel()->getMarkers()) { if (m.end != m.start) { initialOptions << rangesOption; break; } } ListSelectionDialog dialog(initialOptions, this); dialog.setWindowModality(QmlApplication::dialogModality()); dialog.setWindowTitle(tr("Choose Markers")); if (Settings.exportRangeMarkers()) { dialog.setSelection({rangesOption}); } dialog.setColors(colors); if (dialog.exec() != QDialog::Accepted) { return; } auto selection = dialog.selection(); Settings.setExportRangeMarkers(selection.contains(rangesOption)); // Dialog to get export file name QString path = Settings.savePath(); QString caption = tr("Export Chapters"); QString saveFileName = QFileDialog::getSaveFileName(this, caption, path, tr("Text (*.txt);;All Files (*)"), nullptr, Util::getFileDialogOptions()); if (!saveFileName.isEmpty()) { QFileInfo fi(saveFileName); if (fi.suffix() != "txt") saveFileName += ".txt"; if (Util::warnIfNotWritable(saveFileName, this, caption)) return; // Locate the JavaScript file in the filesystem. QDir qmlDir = QmlUtilities::qmlDir(); qmlDir.cd("export-chapters"); QString jsFileName = qmlDir.absoluteFilePath("export-chapters.js"); QFile scriptFile(jsFileName); if (scriptFile.open(QIODevice::ReadOnly)) { // Read JavaScript into a string. QTextStream stream(&scriptFile); stream.setEncoding(QStringConverter::Utf8); stream.setAutoDetectUnicode(true); QString contents = stream.readAll(); scriptFile.close(); // Evaluate JavaScript. QJSEngine jsEngine; QJSValue result = jsEngine.evaluate(contents, jsFileName); if (!result.isError()) { // Call the JavaScript main function. QJSValue options = jsEngine.newObject(); if (selection.contains(rangesOption)) { options.setProperty("includeRanges", true); selection.removeOne(rangesOption); } QJSValue array = jsEngine.newArray(selection.size()); for (int i = 0; i < selection.size(); ++i) array.setProperty(i, selection[i].toUpper()); options.setProperty("colors", array); QJSValueList args; args << MLT.XML(0, true, true) << options; result = result.call(args); if (!result.isError()) { // Save the result with the export file name. QFile f(saveFileName); f.open(QIODevice::WriteOnly | QIODevice::Text); f.write(result.toString().toUtf8()); f.close(); } } if (result.isError()) { LOG_ERROR() << "Uncaught exception at line" << result.property("lineNumber").toInt() << ":" << result.toString(); showStatusMessage(tr("A JavaScript error occurred during export.")); } } else { showStatusMessage(tr("Failed to open export-chapters.js")); } } } void MainWindow::on_actionAudioVideoDevice_triggered() { QDialog dialog(this); dialog.setWindowModality(QmlApplication::dialogModality()); auto layout = new QVBoxLayout(&dialog); QWidget *widget = nullptr; #if defined(Q_OS_LINUX) widget = new Video4LinuxWidget; dialog.resize(500, 400); dialog.setSizeGripEnabled(true); #elif defined(Q_OS_MAC) widget = new AvfoundationProducerWidget; dialog.resize(1, 1); #elif defined(Q_OS_WIN) widget = new DirectShowVideoWidget; dialog.resize(1, 1); #endif layout->addWidget(widget); auto buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); connect(buttonBox, &QDialogButtonBox::accepted, &dialog, &QDialog::accept); connect(buttonBox, &QDialogButtonBox::rejected, &dialog, &QDialog::reject); layout->addWidget(buttonBox); if (dialog.exec() == QDialog::Accepted) { Mlt::Profile profile; profile.set_explicit(1); delete dynamic_cast<AbstractProducerWidget *>(widget)->newProducer(profile); } } void MainWindow::on_actionReset_triggered() { QMessageBox dialog(QMessageBox::Question, qApp->applicationName(), tr("This will reset <b>all</b> settings, and Shotcut must restart afterwards.\n" "Do you want to reset and restart now?"), QMessageBox::No | QMessageBox::Yes, this); dialog.setDefaultButton(QMessageBox::Yes); dialog.setEscapeButton(QMessageBox::No); dialog.setWindowModality(QmlApplication::dialogModality()); if (dialog.exec() == QMessageBox::Yes) { Settings.reset(); m_exitCode = EXIT_RESET; QApplication::closeAllWindows(); } } void MainWindow::onCreateOrEditFilterOnOutput(Mlt::Filter *filter, const QStringList &key_properties) { m_timelineDock->selectMultitrack(); onFiltersDockTriggered(); m_timelineDock->emitSelectedFromSelection(); m_filterController->addOrEditFilter(filter, key_properties); } void MainWindow::showSettingsMenu() const { QPoint point(140 * devicePixelRatioF(), ui->menuBar->height()); #if !defined(Q_OS_MAC) point = ui->menuBar->mapToGlobal(point); #endif ui->menuSettings->popup(point, ui->menuSettings->defaultAction()); }
216,951
C++
.cpp
5,059
34.987152
206
0.644925
mltframework/shotcut
10,796
1,118
50
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
13,116
abstractproducerwidget.cpp
mltframework_shotcut/src/abstractproducerwidget.cpp
/* * Copyright (c) 2012-2023 Meltytech, LLC * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "abstractproducerwidget.h" #include <QWidget> AbstractProducerWidget::AbstractProducerWidget() { } AbstractProducerWidget::~AbstractProducerWidget() { } void AbstractProducerWidget::setProducer(Mlt::Producer *producer) { if (producer) { loadPreset(*producer); m_producer.reset(new Mlt::Producer(producer)); } else { m_producer.reset(); } } bool AbstractProducerWidget::isDevice(const QWidget *widget) { auto name = widget->objectName(); return "AlsaWidget" == name || "alsaWidget" == name || "AvfoundationProducerWidget" == name || "avfoundationWidget" == name || "DecklinkProducerWidget" == name || "decklinkWidget" == name || "DirectShowVideoWidget" == name || "dshowVideoWidget" == name || "GDIgrabWidget" == name || "gdigrabWidget" == name || "PulseAudioWidget" == name || "pulseWidget" == name || "Video4LinuxWidget" == name || "v4lWidget" == name || "X11grabWidget" == name || "x11grabWidget" == name; }
1,743
C++
.cpp
45
34.6
82
0.693444
mltframework/shotcut
10,796
1,118
50
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
13,117
proxymanager.cpp
mltframework_shotcut/src/proxymanager.cpp
/* * Copyright (c) 2020-2024 Meltytech, LLC * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "proxymanager.h" #include "mltcontroller.h" #include "settings.h" #include "shotcut_mlt_properties.h" #include "jobqueue.h" #include "jobs/ffmpegjob.h" #include "jobs/qimagejob.h" #include "util.h" #include <QObject> #include <QVector> #include <QXmlStreamReader> #include <QXmlStreamWriter> #include <QFile> #include <QImageReader> #include <Logger.h> #include <utime.h> static const char *kProxySubfolder = "proxies"; static const char *kProxyVideoExtension = ".mp4"; static const char *kGoProProxyVideoExtension = ".LRV"; static const char *kDJIProxyVideoExtension = ".LRF"; static const char *kProxyPendingVideoExtension = ".pending.mp4"; static const char *kProxyImageExtension = ".jpg"; static const char *kProxyPendingImageExtension = ".pending.jpg"; static const float kProxyResolutionRatio = 1.3f; static const int kFallbackProxyResolution = 540; static const QStringList kPixFmtsWithAlpha = {"pal8", "argb", "rgba", "abgr", "bgra", "yuva420p", "yuva422p", "yuva444p", "yuva420p9be", "yuva420p9le", "yuva422p9be", "yuva422p9le", "yuva444p9be", "yuva444p9le", "yuva420p10be", "yuva420p10le", "yuva422p10be", "yuva422p10le", "yuva444p10be", "yuva444p10le", "yuva420p16be", "yuva420p16le", "yuva422p16be", "yuva422p16le", "yuva444p16be", "yuva444p16le", "rgba64be", "rgba64le", "bgra64be", "bgra64le", "ya8", "ya16le", "ya16be", "gbrap", "gbrap16le", "gbrap16be", "ayuv64le", "ayuv64be", "gbrap12le", "gbrap12be", "gbrap10le", "gbrap10be", "gbrapf32be", "gbrapf32le", "yuva422p12be", "yuva422p12le", "yuva444p12be", "yuva444p12le" }; QDir ProxyManager::dir() { // Use project folder + "/proxies" if using project folder and enabled QDir dir(MLT.projectFolder()); if (!MLT.projectFolder().isEmpty() && dir.exists() && Settings.proxyUseProjectFolder()) { if (!dir.cd(kProxySubfolder)) { if (dir.mkdir(kProxySubfolder)) dir.cd(kProxySubfolder); } } else { // Otherwise, use app setting dir = QDir(Settings.proxyFolder()); } return dir; } QString ProxyManager::resource(Mlt::Service &producer) { QString resource = QString::fromUtf8(producer.get("resource")); if (producer.get_int(kIsProxyProperty) && producer.get(kOriginalResourceProperty)) { resource = QString::fromUtf8(producer.get(kOriginalResourceProperty)); } else if (!::qstrcmp(producer.get("mlt_service"), "timewarp")) { resource = QString::fromUtf8(producer.get("warp_resource")); } return resource; } void ProxyManager::generateVideoProxy(Mlt::Producer &producer, bool fullRange, ScanMode scanMode, const QPoint &aspectRatio, bool replace) { // Always regenerate per preview scaling or 540 if not specified QString resource = ProxyManager::resource(producer); QStringList args; QString hash = Util::getHash(producer); QString fileName = ProxyManager::dir().filePath(hash + kProxyPendingVideoExtension); QString filters; auto hwCodecs = Settings.encodeHardware(); QString hwFilters; // Touch file to make it in progress QFile file(fileName); file.open(QIODevice::WriteOnly); file.resize(0); file.close(); args << "-loglevel" << "verbose"; args << "-noautorotate"; args << "-i" << resource; args << "-max_muxing_queue_size" << "9999"; // transcode all streams except data, subtitles, and attachments auto audioIndex = producer.property_exists(kDefaultAudioIndexProperty) ? producer.get_int( kDefaultAudioIndexProperty) : producer.get_int("audio_index"); if (producer.get_int("video_index") < audioIndex) { // iPhone 16 Pro has a 4 channel (spatial) audio stream with codec "apac" that causes failure. // This is not limited to only iPhone 16 Pro, but I think most iPhones only record one usable audio track. if (!::qstrcmp(producer.get("meta.media.1.stream.type"), "audio") && QString(producer.get("meta.attr.com.apple.quicktime.model.markup")).contains("iPhone")) args << "-map" << "0:V?" << "-map" << "0:a:0"; else args << "-map" << "0:V?" << "-map" << "0:a?"; } else { args << "-map" << "0:a?" << "-map" << "0:V?"; } args << "-map_metadata" << "0" << "-ignore_unknown"; args << "-vf"; if (scanMode == Automatic) { filters = QStringLiteral("yadif=deint=interlaced,"); } else if (scanMode != Progressive) { filters = QStringLiteral("yadif=parity=%1,").arg(scanMode == InterlacedTopFieldFirst ? "tff" : "bff"); } filters += QStringLiteral("scale=width=-2:height=%1").arg(resolution()); if (Settings.proxyUseHardware() && (hwCodecs.contains("hevc_vaapi") || hwCodecs.contains("h264_vaapi"))) { hwFilters = ",format=nv12,hwupload"; } if (fullRange) { args << filters + ":in_range=full:out_range=full" + hwFilters; args << "-color_range" << "jpeg"; } else { args << filters + ":in_range=mpeg:out_range=mpeg" + hwFilters; args << "-color_range" << "mpeg"; } switch (producer.get_int("meta.media.colorspace")) { case 601: if (producer.get_int("meta.media.height") == 576) { args << "-color_primaries" << "bt470bg"; args << "-color_trc" << "smpte170m"; args << "-colorspace" << "bt470bg"; } else { args << "-color_primaries" << "smpte170m"; args << "-color_trc" << "smpte170m"; args << "-colorspace" << "smpte170m"; } break; case 170: args << "-color_primaries" << "smpte170m"; args << "-color_trc" << "smpte170m"; args << "-colorspace" << "smpte170m"; break; case 240: args << "-color_primaries" << "smpte240m"; args << "-color_trc" << "smpte240m"; args << "-colorspace" << "smpte240m"; break; case 470: args << "-color_primaries" << "bt470bg"; args << "-color_trc" << "bt470bg"; args << "-colorspace" << "bt470bg"; break; default: args << "-color_primaries" << "bt709"; args << "-color_trc" << "bt709"; args << "-colorspace" << "bt709"; break; } if (!aspectRatio.isNull()) { args << "-aspect" << QStringLiteral("%1:%2").arg(aspectRatio.x()).arg(aspectRatio.y()); } args << "-f" << "mp4" << "-codec:a" << "ac3" << "-b:a" << "256k"; args << "-pix_fmt" << "yuv420p"; if (Settings.proxyUseHardware()) { if (hwCodecs.contains("hevc_nvenc")) { args << "-codec:v" << "hevc_nvenc"; args << "-rc" << "constqp"; args << "-qp:v" << "37"; args << "-b_ref_mode" << "0"; } else if (hwCodecs.contains("hevc_qsv")) { args << "-load_plugin" << "hevc_hw"; args << "-codec:v" << "hevc_qsv"; args << "-q:v" << "36"; } else if (hwCodecs.contains("hevc_amf")) { args << "-codec:v" << "hevc_amf"; args << "-rc" << "1"; args << "-qp_i" << "32" << "-qp_p" << "32"; } else if (hwCodecs.contains("hevc_vaapi")) { args << "-init_hw_device" << "vaapi=vaapi0:" << "-filter_hw_device" << "vaapi0"; args << "-codec:v" << "hevc_vaapi"; args << "-qp" << "37"; } else if (hwCodecs.contains("h264_nvenc")) { args << "-codec:v" << "h264_nvenc"; args << "-rc" << "constqp"; args << "-qp:v" << "37"; args << "-b_ref_mode" << "0"; } else if (hwCodecs.contains("h264_vaapi")) { args << "-init_hw_device" << "vaapi=vaapi0:" << "-filter_hw_device" << "vaapi0"; args << "-codec:v" << "h264_vaapi"; args << "-qp" << "30"; #if (defined(Q_OS_MAC) && defined(Q_PROCESSOR_ARM)) } else if (!fullRange && hwCodecs.contains("hevc_videotoolbox")) { args << "-codec:v" << "hevc_videotoolbox"; args << "-q:v" << "45"; } else if (!fullRange && hwCodecs.contains("h264_videotoolbox")) { args << "-codec:v" << "h264_videotoolbox"; args << "-q:v" << "45"; #else } else if (hwCodecs.contains("hevc_videotoolbox")) { args << "-codec:v" << "hevc_videotoolbox"; args << "-b:v" << "5M"; } else if (hwCodecs.contains("h264_videotoolbox")) { args << "-codec:v" << "h264_videotoolbox"; args << "-b:v" << "8M"; #endif } else if (hwCodecs.contains("h264_qsv")) { args << "-codec:v" << "h264_qsv"; args << "-q:v" << "36"; } else if (hwCodecs.contains("h264_amf")) { args << "-codec:v" << "h264_amf"; args << "-rc" << "1"; args << "-qp_i" << "32" << "-qp_p" << "32"; } } if (!args.contains("-codec:v")) { args << "-codec:v" << "libx264"; args << "-preset" << "veryfast"; args << "-crf" << "23"; } args << "-g" << QString::fromLatin1(hwCodecs.contains("hevc_nvenc") ? "0" : hwCodecs.contains("h264_nvenc") ? "2" : "1"); args << "-bf" << "0"; args << "-y" << fileName; FfmpegJob *job = new FfmpegJob(fileName, args, true); job->setLabel(QObject::tr("Make proxy for %1").arg(Util::baseName(resource))); if (replace) { job->setPostJobAction(new ProxyReplacePostJobAction(resource, fileName, hash)); } else { job->setPostJobAction(new ProxyFinalizePostJobAction(resource, fileName)); } JOBS.add(job); } void ProxyManager::generateImageProxy(Mlt::Producer &producer, bool replace) { // Always regenerate per preview scaling or 540 if not specified QString resource = ProxyManager::resource(producer); QString hash = Util::getHash(producer); QString fileName = ProxyManager::dir().filePath(hash + kProxyPendingImageExtension); // Touch file to make it in progress QFile file(fileName); file.open(QIODevice::WriteOnly); file.resize(0); file.close(); AbstractJob *job = new QImageJob(fileName, resource, resolution()); if (replace) { job->setPostJobAction(new ProxyReplacePostJobAction(resource, fileName, hash)); } else { job->setPostJobAction(new ProxyFinalizePostJobAction(resource, fileName)); } JOBS.add(job); } typedef QPair<QString, QString> MltProperty; static void processProperties(QXmlStreamWriter &newXml, QVector<MltProperty> &properties, const QString &root) { // Determine if this is a proxy resource bool isProxy = false; QString newResource; QString service; QString speed = "1"; for (const auto &p : properties) { if (p.first == kIsProxyProperty) { isProxy = true; } else if (p.first == kOriginalResourceProperty) { newResource = p.second; } else if (newResource.isEmpty() && p.first == "resource") { newResource = p.second; } else if (p.first == "mlt_service") { service = p.second; } else if (p.first == "warp_speed") { speed = p.second; } } QVector<MltProperty> newProperties; QVector<MltProperty> &propertiesRef = properties; if (isProxy) { // Filter the properties for (const auto &p : properties) { // Replace the resource property if proxy if (p.first == "resource") { // Convert to relative if (!root.isEmpty() && newResource.startsWith(root)) { newResource = newResource.mid(root.size()); } if (service == "timewarp") { newProperties << MltProperty(p.first, QStringLiteral("%1:%2").arg(speed, newResource)); } else { newProperties << MltProperty(p.first, newResource); } } else if (p.first == "warp_resource") { newProperties << MltProperty(p.first, newResource); } else if (p.first != kIsProxyProperty && p.first != kOriginalResourceProperty) { // Remove special proxy and original resource properties newProperties << MltProperty(p.first, p.second); } } propertiesRef = newProperties; } // Write all of the property elements for (const auto &p : propertiesRef) { newXml.writeStartElement("property"); newXml.writeAttribute("name", p.first); newXml.writeCharacters(p.second); newXml.writeEndElement(); } // Reset the saved properties properties.clear(); } bool ProxyManager::filterXML(QString &xmlString, QString root) { QString output; QXmlStreamReader xml(xmlString); QXmlStreamWriter newXml(&output); bool isPropertyElement = false; QVector<MltProperty> properties; // This prevents processProperties() from mis-matching a resource path that begins with root // when it is converting to relative paths. if (!root.isEmpty() && root.endsWith('/')) { root.append('/'); } newXml.setAutoFormatting(true); newXml.setAutoFormattingIndent(2); while (!xml.atEnd()) { switch (xml.readNext()) { case QXmlStreamReader::Characters: if (!isPropertyElement) newXml.writeCharacters(xml.text().toString()); break; case QXmlStreamReader::Comment: newXml.writeComment(xml.text().toString()); break; case QXmlStreamReader::DTD: newXml.writeDTD(xml.text().toString()); break; case QXmlStreamReader::EntityReference: newXml.writeEntityReference(xml.name().toString()); break; case QXmlStreamReader::ProcessingInstruction: newXml.writeProcessingInstruction(xml.processingInstructionTarget().toString(), xml.processingInstructionData().toString()); break; case QXmlStreamReader::StartDocument: newXml.writeStartDocument(xml.documentVersion().toString(), xml.isStandaloneDocument()); break; case QXmlStreamReader::EndDocument: newXml.writeEndDocument(); break; case QXmlStreamReader::StartElement: { const QString element = xml.name().toString(); if (element == "property") { // Save each property element but do not output yet const QString name = xml.attributes().value("name").toString(); properties << MltProperty(name, xml.readElementText()); isPropertyElement = true; } else { // At the start of a non-property element isPropertyElement = false; processProperties(newXml, properties, root); // Write the new start element newXml.writeStartElement(xml.namespaceUri().toString(), element); for (const auto &a : xml.attributes()) { newXml.writeAttribute(a); } } break; } case QXmlStreamReader::EndElement: // At the end of a non-property element if (xml.name().toString() != "property") { processProperties(newXml, properties, root); newXml.writeEndElement(); } break; default: break; } } // Useful for debugging // LOG_DEBUG() << output; if (!xml.hasError()) { xmlString = output; return true; } return false; } bool ProxyManager::fileExists(Mlt::Producer &producer) { QDir proxyDir(Settings.proxyFolder()); QDir projectDir(MLT.projectFolder()); QString service = QString::fromLatin1(producer.get("mlt_service")); QString fileName; if (service.startsWith("avformat")) { if (QFile::exists(GoProProxyFilePath(producer.get("resource")))) { return true; } if (QFile::exists(DJIProxyFilePath(producer.get("resource")))) { return true; } fileName = Util::getHash(producer) + kProxyVideoExtension; } else if (isValidImage(producer)) { fileName = Util::getHash(producer) + kProxyImageExtension; } else { return false; } return (projectDir.cd(kProxySubfolder) && projectDir.exists(fileName)) || proxyDir.exists(fileName); } bool ProxyManager::filePending(Mlt::Producer &producer) { QDir proxyDir(Settings.proxyFolder()); QDir projectDir(MLT.projectFolder()); QString service = QString::fromLatin1(producer.get("mlt_service")); QString fileName; if (service.startsWith("avformat")) { fileName = Util::getHash(producer) + kProxyPendingVideoExtension; } else if (isValidImage(producer)) { fileName = Util::getHash(producer) + kProxyPendingImageExtension; } else { return false; } return (projectDir.cd(kProxySubfolder) && projectDir.exists(fileName)) || proxyDir.exists(fileName); } bool ProxyManager::isValidImage(Mlt::Producer &producer) { QString service = QString::fromLatin1(producer.get("mlt_service")); if ((service == "qimage" || service == "pixbuf") && !producer.get_int(kShotcutSequenceProperty)) { QImageReader reader; reader.setDecideFormatFromContent(true); reader.setFileName(ProxyManager::resource(producer)); return reader.imageCount() == 1 && !reader.read().hasAlphaChannel(); } return false; } bool ProxyManager::isValidVideo(Mlt::Producer producer) { QString service = QString::fromLatin1(producer.get("mlt_service")); int video_index = producer.get_int("video_index"); // video_index -1 means no video if (video_index < 0) return false; if (service == "avformat-novalidate") { producer = Mlt::Producer(MLT.profile(), resource(producer).toUtf8().constData()); service = QString::fromLatin1(producer.get("mlt_service")); producer.set("video_index", video_index); } if (service == "avformat") { QString key = QStringLiteral("meta.media.%1.codec.pix_fmt").arg(video_index); QString pix_fmt = QString::fromLatin1(producer.get(key.toLatin1().constData())); // Cover art is usually 90000 fps and should not be proxied key = QStringLiteral("meta.media.%1.codec.frame_rate").arg(video_index); QString frame_rate = producer.get(key.toLatin1().constData()); key = QStringLiteral("meta.media.%1.codec.name").arg(video_index); QString codec_name = producer.get(key.toLatin1().constData()); bool coverArt = codec_name == "mjpeg" && frame_rate == "90000"; key = QStringLiteral("meta.attr.%1.stream.alpha_mode.markup").arg(video_index); bool alpha_mode = producer.get_int(key.toLatin1().constData()); LOG_DEBUG() << "pix_fmt =" << pix_fmt << " codec.frame_rate =" << frame_rate << " alpha_mode =" << alpha_mode; return !kPixFmtsWithAlpha.contains(pix_fmt) && !alpha_mode && !coverArt; } return false; } // Returns true if the producer exists and was updated with proxy info bool ProxyManager::generateIfNotExists(Mlt::Producer &producer, bool replace) { if (Settings.proxyEnabled() && producer.is_valid() && !producer.get_int(kDisableProxyProperty) && !producer.get_int(kIsProxyProperty)) { if (ProxyManager::fileExists(producer)) { QString service = QString::fromLatin1(producer.get("mlt_service")); QDir projectDir(MLT.projectFolder()); QString fileName = Util::getHash(producer) + kProxyVideoExtension; QDir proxyDir(Settings.proxyFolder()); if (service.startsWith("avformat")) { auto gopro = GoProProxyFilePath(producer.get("resource")); auto dji = DJIProxyFilePath(producer.get("resource")); if (!projectDir.exists(fileName) && !proxyDir.exists(fileName)) { if (QFile::exists(gopro)) { producer.set(kIsProxyProperty, 1); producer.set(kMetaProxyProperty, 1); producer.set(kOriginalResourceProperty, producer.get("resource")); producer.set("resource", gopro.toUtf8().constData()); return true; } else if (QFile::exists(dji)) { producer.set(kIsProxyProperty, 1); producer.set(kMetaProxyProperty, 1); producer.set(kOriginalResourceProperty, producer.get("resource")); producer.set("resource", dji.toUtf8().constData()); return true; } } } else if (isValidImage(producer)) { fileName = Util::getHash(producer) + kProxyImageExtension; } else { return false; } producer.set(kIsProxyProperty, 1); producer.set(kMetaProxyProperty, 1); producer.set(kOriginalResourceProperty, producer.get("resource")); if (projectDir.exists(fileName)) { ::utime(projectDir.filePath(fileName).toUtf8().constData(), nullptr); producer.set("resource", projectDir.filePath(fileName).toUtf8().constData()); } else { ::utime(proxyDir.filePath(fileName).toUtf8().constData(), nullptr); producer.set("resource", proxyDir.filePath(fileName).toUtf8().constData()); } return true; } else if (!filePending(producer)) { if (isValidVideo(producer)) { // Tag this producer so we do not try to generate proxy again in this session delete producer.get_frame(); auto threshold = qRound(kProxyResolutionRatio * resolution()); LOG_DEBUG() << producer.get_int("meta.media.width") << "x" << producer.get_int("meta.media.height") << "threshold" << threshold; if (producer.get_int("meta.media.width") > threshold && producer.get_int("meta.media.height") > threshold) { ProxyManager::generateVideoProxy(producer, MLT.fullRange(producer), Automatic, QPoint(), replace); } } else if (isValidImage(producer)) { // Tag this producer so we do not try to generate proxy again in this session delete producer.get_frame(); auto threshold = qRound(kProxyResolutionRatio * resolution()); LOG_DEBUG() << producer.get_int("meta.media.width") << "x" << producer.get_int("meta.media.height") << "threshold" << threshold; if (producer.get_int("meta.media.width") > threshold && producer.get_int("meta.media.height") > threshold) { ProxyManager::generateImageProxy(producer, replace); } } } } return false; } const char *ProxyManager::videoFilenameExtension() { return kProxyVideoExtension; } const char *ProxyManager::pendingVideoExtension() { return kProxyPendingVideoExtension; } const char *ProxyManager::imageFilenameExtension() { return kProxyImageExtension; } const char *ProxyManager::pendingImageExtension() { return kProxyImageExtension; } int ProxyManager::resolution() { return Settings.playerPreviewScale() ? Settings.playerPreviewScale() : kFallbackProxyResolution; } class FindNonProxyProducersParser : public Mlt::Parser { private: QString m_hash; QList<Mlt::Producer> m_producers; public: FindNonProxyProducersParser() : Mlt::Parser() {} QList<Mlt::Producer> &producers() { return m_producers; } int on_start_filter(Mlt::Filter *) { return 0; } int on_start_producer(Mlt::Producer *producer) { if (!producer->parent().get_int(kIsProxyProperty)) m_producers << Mlt::Producer(producer); return 0; } int on_end_producer(Mlt::Producer *) { return 0; } int on_start_playlist(Mlt::Playlist *) { return 0; } int on_end_playlist(Mlt::Playlist *) { return 0; } int on_start_tractor(Mlt::Tractor *) { return 0; } int on_end_tractor(Mlt::Tractor *) { return 0; } int on_start_multitrack(Mlt::Multitrack *) { return 0; } int on_end_multitrack(Mlt::Multitrack *) { return 0; } int on_start_track() { return 0; } int on_end_track() { return 0; } int on_end_filter(Mlt::Filter *) { return 0; } int on_start_transition(Mlt::Transition *) { return 0; } int on_end_transition(Mlt::Transition *) { return 0; } int on_start_chain(Mlt::Chain *chain) { if (!chain->parent().get_int(kIsProxyProperty)) m_producers << Mlt::Producer(chain); return 0; } int on_end_chain(Mlt::Chain *) { return 0; } int on_start_link(Mlt::Link *) { return 0; } int on_end_link(Mlt::Link *) { return 0; } }; void ProxyManager::generateIfNotExistsAll(Mlt::Producer &producer) { FindNonProxyProducersParser parser; parser.start(producer); for (auto &clip : parser.producers()) { generateIfNotExists(clip, false /* replace */); } } bool ProxyManager::removePending() { bool foundAny = false; QDir dir(MLT.projectFolder()); if (!MLT.projectFolder().isEmpty() && dir.exists()) { dir.cd(kProxySubfolder); } else { dir = QDir(Settings.proxyFolder()); } if (dir.exists()) { dir.setNameFilters(QStringList() << "*.pending.*"); dir.setFilter(QDir::Files | QDir::NoDotAndDotDot | QDir::Writable); for (const auto &s : dir.entryList()) { LOG_INFO() << "removing" << dir.filePath(s); foundAny |= QFile::remove(dir.filePath(s)); } } //TODO if any pending remove, let user know and offer to regenerate? return foundAny; } QString ProxyManager::GoProProxyFilePath(const QString &resource) { auto fi = QFileInfo(resource); auto base = fi.baseName(); base = "GL" + base.mid(2); auto result = fi.absoluteDir().filePath(base + kGoProProxyVideoExtension); LOG_DEBUG() << result; return result; } QString ProxyManager::DJIProxyFilePath(const QString &resource) { auto fi = QFileInfo(resource); auto base = fi.baseName(); auto result = fi.absoluteDir().filePath(base + kDJIProxyVideoExtension); LOG_DEBUG() << result; return result; }
28,105
C++
.cpp
689
31.94775
125
0.591409
mltframework/shotcut
10,796
1,118
50
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
13,119
windowstools.cpp
mltframework_shotcut/src/windowstools.cpp
/* * Copyright (c) 2012-2020 Meltytech, LLC * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "windowstools.h" WindowsTaskbarButton::WindowsTaskbarButton() { } WindowsTaskbarButton &WindowsTaskbarButton::getInstance() { static WindowsTaskbarButton *instance = 0; if (!instance) instance = new WindowsTaskbarButton(); return *instance; } void WindowsTaskbarButton::setParentWindow(QWidget *parent) { m_taskbarButton = new QWinTaskbarButton(parent); m_taskbarButton->setWindow(parent->windowHandle()); m_taskbarProgress = m_taskbarButton->progress(); } void WindowsTaskbarButton::setProgress(int progress) { if (m_taskbarProgress != NULL) { m_taskbarProgress->setVisible(true); m_taskbarProgress->setValue(progress); } } void WindowsTaskbarButton::resetProgress() { if (m_taskbarProgress != NULL) { m_taskbarProgress->setVisible(false); m_taskbarProgress->reset(); } }
1,566
C++
.cpp
47
30.170213
72
0.7462
mltframework/shotcut
10,796
1,118
50
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
13,120
transcoder.cpp
mltframework_shotcut/src/transcoder.cpp
/* * Copyright (c) 2023-2024 Meltytech, LLC * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "transcoder.h" #include "jobqueue.h" #include "jobs/ffmpegjob.h" #include "mainwindow.h" #include "util.h" #include "settings.h" #include "shotcut_mlt_properties.h" #include <QFileDialog> #include <QMessageBox> static const auto kHandleSeconds = 15.0; void Transcoder::setProducers(QList<Mlt::Producer> &producers) { m_producers = producers; } void Transcoder::addProducer(Mlt::Producer &producer) { m_producers.append(producer); } void Transcoder::addProducer(Mlt::Producer *producer) { m_producers.append(*producer); } void Transcoder::convert(TranscodeDialog &dialog) { int result = dialog.exec(); if (dialog.isCheckBoxChecked()) { Settings.setShowConvertClipDialog(false); } if (result != QDialog::Accepted) { return; } QString path = Settings.savePath(); QString suffix = dialog.isSubClip() ? tr("Sub-clip") + ' ' : tr("Converted"); QString filename; QString nameFormat; QString nameFilter; switch (dialog.format()) { case 0: nameFormat = "/%1 - %2.mp4"; nameFilter = tr("MP4 (*.mp4);;All Files (*)"); break; case 1: nameFormat = "/%1 - %2.mov"; nameFilter = tr("MOV (*.mov);;All Files (*)"); break; case 2: nameFormat = "/%1 - %2.mkv"; nameFilter = tr("MKV (*.mkv);;All Files (*)"); break; } if (m_producers.length() == 1) { QString resource = Util::GetFilenameFromProducer(&m_producers[0]); QFileInfo fi(resource); filename = path + nameFormat.arg(fi.completeBaseName(), suffix); if (dialog.isSubClip()) { filename = Util::getNextFile(path); } filename = QFileDialog::getSaveFileName(MAIN.centralWidget(), dialog.windowTitle(), filename, nameFilter, nullptr, Util::getFileDialogOptions()); if (!filename.isEmpty()) { if (filename == QDir::toNativeSeparators(resource)) { QMessageBox::warning(MAIN.centralWidget(), dialog.windowTitle(), QObject::tr("Unable to write file %1\n" "Perhaps you do not have permission.\n" "Try again with a different folder.") .arg(fi.fileName())); return; } if (Util::warnIfNotWritable(filename, MAIN.centralWidget(), dialog.windowTitle())) return; if (Util::warnIfLowDiskSpace(filename)) { MAIN.showStatusMessage(tr("Convert canceled")); return; } } convertProducer(&m_producers[0], dialog, filename); } else if (m_producers.length() > 1) { path = QFileDialog::getExistingDirectory(MAIN.centralWidget(), dialog.windowTitle(), path, Util::getFileDialogOptions()); if (path.isEmpty()) { MAIN.showStatusMessage(tr("Convert canceled")); return; } if (Util::warnIfNotWritable(path, MAIN.centralWidget(), dialog.windowTitle())) { return; } if (Util::warnIfLowDiskSpace(path)) { MAIN.showStatusMessage(tr("Convert canceled")); return; } for (auto &producer : m_producers) { QString resource = Util::GetFilenameFromProducer(&producer); QFileInfo fi(resource); filename = path + nameFormat.arg(fi.completeBaseName(), suffix); filename = Util::getNextFile(filename); convertProducer(&producer, dialog, filename); } } Settings.setSavePath(QFileInfo(filename).path()); } void Transcoder::convertProducer(Mlt::Producer *producer, TranscodeDialog &dialog, QString filename) { QString resource = Util::GetFilenameFromProducer(producer); QStringList args; int in = -1; args << "-loglevel" << "verbose"; args << "-i" << resource; args << "-max_muxing_queue_size" << "9999"; if (dialog.isSubClip()) { if (Settings.proxyEnabled()) { producer->Mlt::Properties::clear(kOriginalResourceProperty); } // set trim options if (producer->get(kFilterInProperty)) { in = producer->get_int(kFilterInProperty); int ss = qMax(0, in - qRound(producer->get_fps() * kHandleSeconds)); auto s = QString::fromLatin1(producer->frames_to_time(ss, mlt_time_clock)); args << "-ss" << s.replace(',', '.'); in -= ss; } else { args << "-ss" << QString::fromLatin1(producer->get_time("in", mlt_time_clock)).replace(',', '.').replace(',', '.'); } if (producer->get(kFilterOutProperty)) { int out = producer->get_int(kFilterOutProperty); int to = qMin(producer->get_playtime() - 1, out + qRound(producer->get_fps() * kHandleSeconds)); auto s = QString::fromLatin1(producer->frames_to_time(to, mlt_time_clock)); args << "-to" << s.replace(',', '.'); } else { args << "-to" << QString::fromLatin1(producer->get_time("out", mlt_time_clock)).replace(',', '.'); } } // transcode all streams except data, subtitles, and attachments auto audioIndex = producer->property_exists(kDefaultAudioIndexProperty) ? producer->get_int( kDefaultAudioIndexProperty) : producer->get_int("audio_index"); if (producer->get_int("video_index") < audioIndex) { args << "-map" << "0:V?" << "-map" << "0:a?"; } else { args << "-map" << "0:a?" << "-map" << "0:V?"; } args << "-map_metadata" << "0" << "-ignore_unknown"; // Set Sample rate if different than source if (!dialog.sampleRate().isEmpty() ) { args << "-ar" << dialog.sampleRate(); } // Set video filters args << "-vf"; QString filterString; if (dialog.deinterlace()) { QString deinterlaceFilter = QStringLiteral("bwdif,"); filterString = filterString + deinterlaceFilter; } QString color_range; if (producer->get("color_range")) { if (producer->get_int("color_range") == 2) { color_range = "full"; } else { color_range = "mpeg"; } } else if (producer->get("force_full_range")) { if (producer->get_int("force_full_range")) { color_range = "full"; } else { color_range = "mpeg"; } } else { color_range = producer->get("meta.media.color_range"); } if (color_range != "full" && color_range != "mpeg") { color_range = "mpeg"; } if (dialog.get709Convert()) { QString convertFilter = QStringLiteral("zscale=t=linear:npl=100,format=gbrpf32le,zscale=p=bt709,tonemap=tonemap=hable:desat=0,zscale=t=bt709:m=bt709:r=tv,format=yuv422p,"); filterString = filterString + convertFilter; } filterString = filterString + QStringLiteral("scale=flags=accurate_rnd+full_chroma_inp+full_chroma_int:in_range=%1:out_range=%2").arg( color_range).arg(color_range); auto fps = dialog.fpsOverride() ? dialog.fps() : Util::getSuggestedFrameRate(producer); auto fpsStr = QStringLiteral("%1").arg(fps, 0, 'f', 6); int numerator, denominator; Util::normalizeFrameRate(fps, numerator, denominator); if (denominator == 1001) { fpsStr = QStringLiteral("%1/%2").arg(numerator).arg(denominator); } QString minterpFilter = QStringLiteral(",minterpolate='mi_mode=%1:mc_mode=aobmc:me_mode=bidir:vsbmc=1:fps=%2'").arg( dialog.frc(), fpsStr); filterString = filterString + minterpFilter; args << filterString; // Specify color range if (color_range == "full") { args << "-color_range" << "2"; } else { args << "-color_range" << "1"; } int progressive = producer->get_int("meta.media.progressive") || producer->get_int("force_progressive"); if (!dialog.deinterlace() && !progressive) { int tff = producer->get_int("meta.media.top_field_first") || producer->get_int("force_tff"); args << "-flags" << "+ildct+ilme" << "-top" << QString::number(tff); } switch (dialog.format()) { case 0: args << "-f" << "mp4" << "-codec:a" << "ac3" << "-b:a" << "512k" << "-codec:v" << "libx264"; args << "-preset" << "medium" << "-g" << "1" << "-crf" << "15"; break; case 1: args << "-f" << "mov" << "-codec:a" << "pcm_f32le"; if (dialog.deinterlace() || progressive) { args << "-codec:v" << "dnxhd" << "-profile:v" << "dnxhr_hq" << "-pix_fmt" << "yuv422p"; } else { // interlaced args << "-codec:v" << "prores_ks" << "-profile:v" << "standard"; } break; case 2: args << "-f" << "matroska" << "-codec:a" << "pcm_f32le" << "-codec:v" << "utvideo"; args << "-pix_fmt" << "yuv422p"; break; } if (dialog.get709Convert()) { args << "-colorspace" << "bt709" << "-color_primaries" << "bt709" << "-color_trc" << "bt709"; } else if (dialog.format() == 2 && producer->get_int("meta.media.colorspace") == 709) { // Work around a limitation that FFMpeg does not pass colorspace for utvideo args << "-colorspace" << "bt709"; } args << "-y" << filename; producer->Mlt::Properties::clear(kOriginalResourceProperty); FfmpegJob *job = new FfmpegJob(filename, args, false); job->setLabel(tr("Convert %1").arg(Util::baseName(filename))); if (dialog.isSubClip()) { if (producer->get(kMultitrackItemProperty)) { QString s = QString::fromLatin1(producer->get(kMultitrackItemProperty)); auto parts = s.split(':'); if (parts.length() == 2) { int clipIndex = parts[0].toInt(); int trackIndex = parts[1].toInt(); QUuid uuid = MAIN.timelineClipUuid(trackIndex, clipIndex); if (!uuid.isNull()) { job->setPostJobAction(new ReplaceOnePostJobAction(resource, filename, QString(), uuid, in)); JOBS.add(job); } } } else { job->setPostJobAction(new OpenPostJobAction(resource, filename, QString())); JOBS.add(job); } return; } job->setPostJobAction(new ReplaceAllPostJobAction(resource, filename, Util::getHash(*producer))); JOBS.add(job); }
11,553
C++
.cpp
272
33.040441
160
0.569664
mltframework/shotcut
10,796
1,118
50
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
13,121
player.cpp
mltframework_shotcut/src/player.cpp
/* * Copyright (c) 2012-2024 Meltytech, LLC * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "player.h" #include "actions.h" #include "scrubbar.h" #include "mainwindow.h" #include "dialogs/durationdialog.h" #include "widgets/statuslabelwidget.h" #include "widgets/timespinbox.h" #include "widgets/audioscale.h" #include "settings.h" #include "widgets/newprojectfolder.h" #include "proxymanager.h" #include "widgets/docktoolbar.h" #include <Logger.h> #include <QtWidgets> #include <limits> #define VOLUME_KNEE (88) #define SEEK_INACTIVE (-1) #define VOLUME_SLIDER_HEIGHT (300) class NoWheelTabBar : public QTabBar { void wheelEvent(QWheelEvent *event) { event->ignore(); }; }; QString blankTime() { switch (Settings.timeFormat()) { case mlt_time_frames: return "--------"; case mlt_time_clock: return "--:--:--.---"; case mlt_time_smpte_df: if (MLT.profile().fps() == 30000.0 / 1001.0 || MLT.profile().fps() == 60000.0 / 1001.0) return "--:--:--;--"; // Fallthrough on purpose default: return "--:--:--:--"; } } Player::Player(QWidget *parent) : QWidget(parent) , m_position(0) , m_playPosition(std::numeric_limits<int>::max()) , m_previousIn(-1) , m_previousOut(-1) , m_duration(0) , m_isSeekable(false) , m_isMeltedPlaying(-1) , m_zoomToggleFactor(Settings.playerZoom() == 0.0f ? 1.0f : Settings.playerZoom()) , m_pauseAfterOpen(false) , m_monitorScreen(-1) , m_currentTransport(nullptr) , m_loopStart(-1) , m_loopEnd(-1) { setObjectName("Player"); Mlt::Controller::singleton(); setupActions(); // Create a layout. QVBoxLayout *vlayout = new QVBoxLayout(this); vlayout->setObjectName("playerLayout"); vlayout->setContentsMargins(0, 0, 0, 0); vlayout->setSpacing(4); // Add tab bar to indicate/select what is playing: clip, playlist, timeline. m_tabs = new NoWheelTabBar; m_tabs->setShape(QTabBar::RoundedSouth); m_tabs->setUsesScrollButtons(false); m_tabs->addTab(tr("Source")); m_tabs->addTab(tr("Project")); m_tabs->setTabEnabled(SourceTabIndex, false); m_tabs->setTabEnabled(ProjectTabIndex, false); QHBoxLayout *tabLayout = new QHBoxLayout; tabLayout->setSpacing(8); tabLayout->addWidget(m_tabs); connect(m_tabs, &QTabBar::tabBarClicked, this, &Player::onTabBarClicked); // Add status bar. m_statusLabel = new StatusLabelWidget(); connect(m_statusLabel, &StatusLabelWidget::statusCleared, this, &Player::onStatusFinished); tabLayout->addWidget(m_statusLabel); tabLayout->addStretch(1); // Add the layouts for managing video view, scroll bars, and audio controls. m_videoLayout = new QHBoxLayout; m_videoLayout->setSpacing(4); m_videoLayout->setContentsMargins(0, 0, 0, 0); vlayout->addLayout(m_videoLayout, 1); m_videoScrollWidget = new QWidget; m_videoLayout->addWidget(m_videoScrollWidget, 10); m_videoLayout->addStretch(); QGridLayout *glayout = new QGridLayout(m_videoScrollWidget); glayout->setSpacing(0); glayout->setContentsMargins(0, 0, 0, 0); // Add the video widgets. m_videoWidget = qobject_cast<QWidget *>(MLT.videoWidget()); Q_ASSERT(m_videoWidget); m_videoWidget->setMinimumSize(QSize(1, 1)); glayout->addWidget(m_videoWidget, 0, 0); m_verticalScroll = new QScrollBar(Qt::Vertical); glayout->addWidget(m_verticalScroll, 0, 1); m_verticalScroll->hide(); m_horizontalScroll = new QScrollBar(Qt::Horizontal); glayout->addWidget(m_horizontalScroll, 1, 0); m_horizontalScroll->hide(); // Add the new project widget. m_projectWidget = new NewProjectFolder(this); vlayout->addWidget(m_projectWidget, 10); vlayout->addStretch(); // Add the volume and signal level meter m_volumePopup = new QFrame(this, Qt::Popup); QVBoxLayout *volumeLayoutV = new QVBoxLayout(m_volumePopup); volumeLayoutV->setContentsMargins(0, 0, 0, 0); volumeLayoutV->addSpacerItem(new QSpacerItem(0, 0, QSizePolicy::Minimum, QSizePolicy::Expanding)); QBoxLayout *volumeLayoutH = new QHBoxLayout; volumeLayoutH->setSpacing(0); volumeLayoutH->setContentsMargins(0, 0, 0, 0); volumeLayoutH->addWidget(new AudioScale); m_volumeSlider = new QSlider(Qt::Vertical); m_volumeSlider->setFocusPolicy(Qt::NoFocus); m_volumeSlider->setMinimumHeight(VOLUME_SLIDER_HEIGHT); m_volumeSlider->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); volumeLayoutH->addWidget(m_volumeSlider); volumeLayoutV->addLayout(volumeLayoutH); m_volumeSlider->setRange(0, 99); m_volumeSlider->setValue(Settings.playerVolume()); setVolume(m_volumeSlider->value()); m_savedVolume = MLT.volume(); m_volumeSlider->setToolTip(tr("Adjust the audio volume")); connect(m_volumeSlider, SIGNAL(valueChanged(int)), this, SLOT(onVolumeChanged(int))); connect(m_volumeSlider, &QAbstractSlider::sliderReleased, m_volumePopup, &QWidget::hide); // Add mute-volume buttons layout #ifdef Q_OS_MAC if (Settings.theme() == "system") volumeLayoutH = new QVBoxLayout; else #endif volumeLayoutH = new QHBoxLayout; volumeLayoutH->setContentsMargins(0, 0, 0, 0); volumeLayoutH->setSpacing(0); volumeLayoutV->addLayout(volumeLayoutH); // Add mute button m_muteButton = new QPushButton(this); m_muteButton->setFocusPolicy(Qt::NoFocus); m_muteButton->setObjectName(QString::fromUtf8("muteButton")); m_muteButton->setIcon(QIcon::fromTheme("audio-volume-muted", QIcon(":/icons/oxygen/32x32/status/audio-volume-muted.png"))); m_muteButton->setToolTip(tr("Silence the audio")); m_muteButton->setCheckable(true); m_muteButton->setChecked(Settings.playerMuted()); volumeLayoutH->addWidget(m_muteButton); connect(m_muteButton, SIGNAL(clicked(bool)), this, SLOT(onMuteButtonToggled(bool))); // Add the scrub bar. m_scrubber = new ScrubBar(this); m_scrubber->setFocusPolicy(Qt::NoFocus); m_scrubber->setObjectName("scrubBar"); m_scrubber->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Preferred); vlayout->addWidget(m_scrubber); // Make a toolbar for the current and total duration times m_currentDurationToolBar = new DockToolBar(tr("Current/Total Times"), this); m_currentDurationToolBar->setAreaHint(Qt::BottomToolBarArea); m_currentDurationToolBar->setContentsMargins(0, 0, 0, 0); m_currentDurationToolBar->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Fixed); m_positionSpinner = new TimeSpinBox(this); m_positionSpinner->setToolTip(tr("Current position")); m_positionSpinner->setEnabled(false); m_positionSpinner->setKeyboardTracking(false); m_currentDurationToolBar->addWidget(m_positionSpinner); m_currentDurationToolBar->addWidget(new QLabel(" / ")); m_durationLabel = new QLabel(this); m_durationLabel->setToolTip(tr("Total Duration")); m_durationLabel->setText(blankTime()); QFontMetrics fm(m_durationLabel->font()); m_durationLabel->setFixedWidth(fm.boundingRect("00:00:00:.000").width() + 2); m_durationLabel->setFixedHeight(m_positionSpinner->sizeHint().height()); m_currentDurationToolBar->addWidget(m_durationLabel); // Make toolbar for transport controls. m_controlsToolBar = new DockToolBar(tr("Player Controls"), this); m_controlsToolBar->setAreaHint(Qt::BottomToolBarArea); m_controlsToolBar->setContentsMargins(0, 0, 0, 0); m_controlsToolBar->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Fixed); m_controlsToolBar->addAction(Actions["playerSkipPreviousAction"]); m_controlsToolBar->addAction(Actions["playerRewindAction"]); m_controlsToolBar->addAction(Actions["playerPlayPauseAction"]); m_controlsToolBar->addAction(Actions["playerFastForwardAction"]); m_controlsToolBar->addAction(Actions["playerSkipNextAction"]); // Make a toolbar for player options m_optionsToolBar = new DockToolBar(tr("Player Options"), this); m_optionsToolBar->setAreaHint(Qt::BottomToolBarArea); m_optionsToolBar->setContentsMargins(0, 0, 0, 0); m_optionsToolBar->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Fixed); // Pause button QToolButton *loopButton = new QToolButton; QMenu *loopMenu = new QMenu(this); loopMenu->addAction(Actions["playerLoopRangeAllAction"]); loopMenu->addAction(Actions["playerLoopRangeMarkerAction"]); loopMenu->addAction(Actions["playerLoopRangeSelectionAction"]); loopMenu->addAction(Actions["playerLoopRangeAroundAction"]); loopButton->setMenu(loopMenu); loopButton->setPopupMode(QToolButton::MenuButtonPopup); loopButton->setDefaultAction(Actions["playerLoopAction"]); m_optionsToolBar->addWidget(loopButton); // Zoom button m_zoomButton = new QToolButton; m_zoomMenu = new QMenu(this); m_zoomMenu->addAction( QIcon::fromTheme("zoom-fit-best", QIcon(":/icons/oxygen/32x32/actions/zoom-fit-best")), tr("Zoom Fit"), this, SLOT(onZoomTriggered()))->setData(0.0f); m_zoomMenu->addAction( QIcon::fromTheme("zoom-out", QIcon(":/icons/oxygen/32x32/actions/zoom-out")), tr("Zoom 10%"), this, SLOT(onZoomTriggered()))->setData(0.1f); m_zoomMenu->addAction( QIcon::fromTheme("zoom-out", QIcon(":/icons/oxygen/32x32/actions/zoom-out")), tr("Zoom 25%"), this, SLOT(onZoomTriggered()))->setData(0.25f); m_zoomMenu->addAction( QIcon::fromTheme("zoom-out", QIcon(":/icons/oxygen/32x32/actions/zoom-out")), tr("Zoom 50%"), this, SLOT(onZoomTriggered()))->setData(0.5f); m_zoomMenu->addAction( QIcon::fromTheme("zoom-original", QIcon(":/icons/oxygen/32x32/actions/zoom-original")), tr("Zoom 100%"), this, SLOT(onZoomTriggered()))->setData(1.0f); m_zoomMenu->addAction( QIcon::fromTheme("zoom-in", QIcon(":/icons/oxygen/32x32/actions/zoom-in")), tr("Zoom 200%"), this, SLOT(onZoomTriggered()))->setData(2.0f); m_zoomMenu->addAction( QIcon::fromTheme("zoom-in", QIcon(":/icons/oxygen/32x32/actions/zoom-in")), tr("Zoom 300%"), this, SLOT(onZoomTriggered()))->setData(3.0f); m_zoomMenu->addAction( QIcon::fromTheme("zoom-in", QIcon(":/icons/oxygen/32x32/actions/zoom-in")), tr("Zoom 400%"), this, SLOT(onZoomTriggered()))->setData(4.0f); m_zoomMenu->addAction( QIcon::fromTheme("zoom-in", QIcon(":/icons/oxygen/32x32/actions/zoom-in")), tr("Zoom 500%"), this, SLOT(onZoomTriggered()))->setData(5.0f); m_zoomMenu->addAction( QIcon::fromTheme("zoom-in", QIcon(":/icons/oxygen/32x32/actions/zoom-in")), tr("Zoom 750%"), this, SLOT(onZoomTriggered()))->setData(7.5f); m_zoomMenu->addAction( QIcon::fromTheme("zoom-in", QIcon(":/icons/oxygen/32x32/actions/zoom-in")), tr("Zoom 1000%"), this, SLOT(onZoomTriggered()))->setData(10.0f); connect(m_zoomButton, SIGNAL(toggled(bool)), SLOT(toggleZoom(bool))); m_zoomButton->setMenu(m_zoomMenu); m_zoomButton->setPopupMode(QToolButton::MenuButtonPopup); m_zoomButton->setCheckable(true); m_zoomButton->setToolTip(tr("Toggle zoom")); m_optionsToolBar->addWidget(m_zoomButton); toggleZoom(false); // Add grid display button to toolbar. m_gridButton = new QToolButton; QMenu *gridMenu = new QMenu(this); m_gridActionGroup = new QActionGroup(this); QAction *action = gridMenu->addAction(tr("2x2 Grid"), this, SLOT(onGridToggled())); action->setCheckable(true); action->setData(2); m_gridDefaultAction = action; m_gridActionGroup->addAction(action); action = gridMenu->addAction(tr("3x3 Grid"), this, SLOT(onGridToggled())); action->setCheckable(true); action->setData(3); m_gridActionGroup->addAction(action); action = gridMenu->addAction(tr("4x4 Grid"), this, SLOT(onGridToggled())); action->setCheckable(true); action->setData(4); m_gridActionGroup->addAction(action); action = gridMenu->addAction(tr("16x16 Grid"), this, SLOT(onGridToggled())); action->setCheckable(true); action->setData(16); m_gridActionGroup->addAction(action); action = gridMenu->addAction(tr("20 Pixel Grid"), this, SLOT(onGridToggled())); action->setCheckable(true); action->setData(10020); m_gridActionGroup->addAction(action); action = gridMenu->addAction(tr("10 Pixel Grid"), this, SLOT(onGridToggled())); action->setCheckable(true); action->setData(10010); m_gridActionGroup->addAction(action); action = gridMenu->addAction(tr("80/90% Safe Areas"), this, SLOT(onGridToggled())); action->setCheckable(true); action->setData(8090); m_gridActionGroup->addAction(action); action = gridMenu->addAction(tr("EBU R95 Safe Areas"), this, SLOT(onGridToggled())); action->setCheckable(true); action->setData(95); m_gridActionGroup->addAction(action); gridMenu->addSeparator(); action = gridMenu->addAction(tr("Snapping")); action->setCheckable(true); action->setChecked(true); connect(action, SIGNAL(toggled(bool)), MLT.videoWidget(), SLOT(setSnapToGrid(bool))); connect(m_gridButton, SIGNAL(toggled(bool)), SLOT(toggleGrid(bool))); m_gridButton->setMenu(gridMenu); m_gridButton->setIcon(QIcon::fromTheme("view-grid", QIcon(":/icons/oxygen/32x32/actions/view-grid"))); m_gridButton->setPopupMode(QToolButton::MenuButtonPopup); m_gridButton->setCheckable(true); m_gridButton->setToolTip(tr("Toggle grid display on the player")); m_optionsToolBar->addWidget(m_gridButton); // Add volume control to toolbar. m_volumeButton = new QToolButton; m_volumeButton->setObjectName(QString::fromUtf8("volumeButton")); m_volumeButton->setIcon(QIcon::fromTheme("player-volume", QIcon(":/icons/oxygen/32x32/actions/player-volume.png"))); m_volumeButton->setText(tr("Volume")); m_volumeButton->setToolTip(tr("Show the volume control")); connect(m_volumeButton, SIGNAL(clicked()), this, SLOT(onVolumeTriggered())); m_optionsToolBar->addWidget(m_volumeButton); // Make a toolbar for in-point and selected duration m_inSelectedToolBar = new DockToolBar(tr("Player Options"), this); m_inSelectedToolBar->setAreaHint(Qt::BottomToolBarArea); m_inSelectedToolBar->setContentsMargins(0, 0, 0, 0); m_inPointLabel = new QLabel(this); m_inPointLabel->setText(blankTime()); m_inPointLabel->setToolTip(tr("In Point")); m_inPointLabel->setFixedWidth(fm.boundingRect("00:00:00.000").width() + 2); m_inPointLabel->setAlignment(Qt::AlignRight | Qt::AlignVCenter); m_inPointLabel->setFixedHeight(m_positionSpinner->sizeHint().height()); m_inSelectedToolBar->addWidget(m_inPointLabel); m_inSelectedToolBar->addWidget(new QLabel(" / ")); m_selectedLabel = new QLabel(this); m_selectedLabel->setText(blankTime()); m_selectedLabel->setToolTip(tr("Selected Duration")); m_selectedLabel->setFixedWidth(fm.boundingRect("00:00:00.000").width() + 2); m_selectedLabel->setAlignment(Qt::AlignLeft | Qt::AlignVCenter); m_selectedLabel->setFixedHeight(m_positionSpinner->sizeHint().height()); m_inSelectedToolBar->addWidget(m_selectedLabel); // Create two rows for the toolbars. // The toolbars will be layed out in one or two rows depending on the width. m_toolRow1 = new QHBoxLayout(); vlayout->addLayout(m_toolRow1); m_toolRow2 = new QHBoxLayout(); vlayout->addLayout(m_toolRow2); vlayout->addLayout(tabLayout); layoutToolbars(); onMuteButtonToggled(Settings.playerMuted()); connect(MLT.videoWidget(), SIGNAL(frameDisplayed(const SharedFrame &)), this, SLOT(onFrameDisplayed(const SharedFrame &))); connect(m_scrubber, SIGNAL(seeked(int)), this, SLOT(seek(int))); connect(m_scrubber, SIGNAL(inChanged(int)), this, SLOT(onInChanged(int))); connect(m_scrubber, SIGNAL(outChanged(int)), this, SLOT(onOutChanged(int))); connect(m_positionSpinner, SIGNAL(valueChanged(int)), this, SLOT(seek(int))); connect(this, SIGNAL(endOfStream()), this, SLOT(pause())); connect(this, SIGNAL(gridChanged(int)), MLT.videoWidget(), SLOT(setGrid(int))); connect(this, SIGNAL(zoomChanged(float)), MLT.videoWidget(), SLOT(setZoom(float))); connect(m_horizontalScroll, SIGNAL(valueChanged(int)), MLT.videoWidget(), SLOT(setOffsetX(int))); connect(m_verticalScroll, SIGNAL(valueChanged(int)), MLT.videoWidget(), SLOT(setOffsetY(int))); connect(MLT.videoWidget(), SIGNAL(offsetChanged(const QPoint &)), SLOT(onOffsetChanged(const QPoint &))); connect(&Settings, &ShotcutSettings::timeFormatChanged, this, [&]() { updateSelection(); if (MLT.isSeekable()) { onDurationChanged(); } }); setFocusPolicy(Qt::StrongFocus); } void Player::connectTransport(const TransportControllable *receiver) { if (receiver == m_currentTransport) return; if (m_currentTransport) disconnect(m_currentTransport); m_currentTransport = receiver; connect(this, SIGNAL(played(double)), receiver, SLOT(play(double))); connect(this, SIGNAL(paused()), receiver, SLOT(pause())); connect(this, SIGNAL(stopped()), receiver, SLOT(stop())); connect(this, SIGNAL(seeked(int)), receiver, SLOT(seek(int))); connect(this, SIGNAL(rewound(bool)), receiver, SLOT(rewind(bool))); connect(this, SIGNAL(fastForwarded(bool)), receiver, SLOT(fastForward(bool))); connect(this, SIGNAL(previousSought(int)), receiver, SLOT(previous(int))); connect(this, SIGNAL(nextSought(int)), receiver, SLOT(next(int))); } void Player::setupActions() { QIcon icon; QAction *action; m_playIcon = QIcon::fromTheme("media-playback-start", QIcon(":/icons/oxygen/32x32/actions/media-playback-start.png")); m_pauseIcon = QIcon::fromTheme("media-playback-pause", QIcon(":/icons/oxygen/32x32/actions/media-playback-pause.png")); m_stopIcon = QIcon::fromTheme("media-playback-stop", QIcon(":/icons/oxygen/32x32/actions/media-playback-stop.png")); action = new QAction(tr("Play/Pause"), this); action->setShortcut(QKeySequence(Qt::Key_Space)); action->setIcon(m_playIcon); action->setDisabled(true); action->setToolTip(tr("Toggle play or pause")); connect(action, &QAction::triggered, this, [&]() { if (Actions["playerPlayPauseAction"]->icon().cacheKey() == m_playIcon.cacheKey()) play(); else if (m_isSeekable) pause(); else stop(); }); Actions.add("playerPlayPauseAction", action); action = new QAction(tr("Loop"), this); action->setShortcut(QKeySequence(Qt::Key_Backslash)); action->setIcon(QIcon::fromTheme("media-playback-loop", QIcon(":/icons/oxygen/32x32/actions/media-playback-loop.png"))); action->setCheckable(true); action->setToolTip(tr("Toggle player looping")); connect(action, &QAction::toggled, this, [&]() { setLoopRange(m_loopStart, m_loopEnd); }); Actions.add("playerLoopAction", action); action = new QAction(tr("Loop All"), this); action->setToolTip(tr("Loop back to the beginning when the end is reached")); connect(action, &QAction::triggered, this, [&]() { Actions["playerLoopAction"]->setChecked(true); setLoopRange(0, m_duration); }); Actions.add("playerLoopRangeAllAction", action); action = new QAction(tr("Loop Marker"), this); action->setToolTip(tr("Loop around the marker under the cursor in the timeline")); connect(action, &QAction::triggered, this, [&]() { int start, end; MAIN.getMarkerRange(m_position, &start, &end); if (start >= 0) { Actions["playerLoopAction"]->setChecked(true); setLoopRange(start, end); } }); Actions.add("playerLoopRangeMarkerAction", action); action = new QAction(tr("Loop Selection"), this); action->setToolTip(tr("Loop around the selected clips")); connect(action, &QAction::triggered, this, [&]() { int start, end; MAIN.getSelectionRange(&start, &end); if (start >= 0) { Actions["playerLoopAction"]->setChecked(true); setLoopRange(start, end); } else { emit showStatusMessage(tr("Nothing selected")); } }); Actions.add("playerLoopRangeSelectionAction", action); action = new QAction(tr("Loop Around Cursor"), this); action->setToolTip(tr("Loop around the current cursor position")); connect(action, &QAction::triggered, this, [&]() { Actions["playerLoopAction"]->setChecked(true); // Set the range one second before and after the cursor int fps = qRound(MLT.profile().fps()); if (m_duration <= fps * 2) { setLoopRange(0, m_duration); } else { int start = position() - fps; int end = position() + fps; if (start < 0) { end -= start; start = 0; } if (end >= m_duration) { start -= end - m_duration; end = m_duration; } setLoopRange(start, end); } }); Actions.add("playerLoopRangeAroundAction", action); action = new QAction(tr("Skip Next"), this); action->setShortcut(QKeySequence(Qt::ALT | Qt::Key_Right)); icon = QIcon::fromTheme("media-skip-forward", QIcon(":/icons/oxygen/32x32/actions/media-skip-forward.png")); action->setIcon(icon); action->setDisabled(true); action->setToolTip(tr("Skip to the next point")); connect(action, &QAction::triggered, this, [&]() { if (m_scrubber->markers().size() > 0) { foreach (int x, m_scrubber->markers()) { if (x > m_position) { emit seeked(x); return; } } emit seeked(m_duration - 1); } else { emit nextSought(m_position); emit nextSought(); } }); Actions.add("playerSkipNextAction", action); action = new QAction(tr("Skip Previous"), this); action->setShortcut(QKeySequence(Qt::ALT | Qt::Key_Left)); icon = QIcon::fromTheme("media-skip-backward", QIcon(":/icons/oxygen/32x32/actions/media-skip-backward.png")); action->setIcon(icon); action->setDisabled(true); action->setToolTip(tr("Skip to the previous point")); connect(action, &QAction::triggered, this, [&]() { if (m_scrubber->markers().size() > 0) { QList<int> markers = m_scrubber->markers(); int n = markers.count(); while (n--) { if (markers[n] < m_position) { emit seeked(markers[n]); return; } } emit seeked(0); } else { emit previousSought(m_position); emit previousSought(); } }); Actions.add("playerSkipPreviousAction", action); action = new QAction(tr("Rewind"), this); action->setProperty(Actions.hardKeyProperty, "J"); icon = QIcon::fromTheme("media-seek-backward", QIcon(":/icons/oxygen/32x32/actions/media-seek-backward.png")); action->setIcon(icon); action->setDisabled(true); action->setToolTip(tr("Play quickly backwards")); connect(action, &QAction::triggered, this, &Player::rewind); Actions.add("playerRewindAction", action); action = new QAction(tr("Fast Forward"), this); action->setProperty(Actions.hardKeyProperty, "L"); icon = QIcon::fromTheme("media-seek-forward", QIcon(":/icons/oxygen/32x32/actions/media-seek-forward.png")); action->setIcon(icon); action->setDisabled(true); action->setToolTip(tr("Play quickly forwards")); connect(action, &QAction::triggered, this, &Player::fastForward); Actions.add("playerFastForwardAction", action); action = new QAction(tr("Seek Start"), this); action->setShortcut(QKeySequence(Qt::Key_Home)); connect(action, &QAction::triggered, this, [&]() { seek(0); }); Actions.add("playerSeekStartAction", action); action = new QAction(tr("Seek End"), this); action->setShortcut(QKeySequence(Qt::Key_End)); connect(action, &QAction::triggered, this, [&]() { if (MLT.producer()) seek(MLT.producer()->get_length()); }); Actions.add("playerSeekEndAction", action); action = new QAction(tr("Next Frame"), this); action->setProperty(Actions.hardKeyProperty, "K+L"); action->setShortcut(QKeySequence(Qt::Key_Right)); connect(action, &QAction::triggered, this, [&]() { if (MLT.producer()) seek(position() + 1); }); Actions.add("playerNextFrameAction", action); action = new QAction(tr("Previous Frame"), this); action->setProperty(Actions.hardKeyProperty, "K+J"); action->setShortcut(QKeySequence(Qt::Key_Left)); connect(action, &QAction::triggered, this, [&]() { if (MLT.producer()) seek(position() - 1); }); Actions.add("playerPreviousFrameAction", action); action = new QAction(tr("Forward One Second"), this); action->setShortcut(QKeySequence(Qt::Key_PageDown)); connect(action, &QAction::triggered, this, [&]() { if (MLT.producer()) seek(position() + qRound(MLT.profile().fps())); }); Actions.add("playerForwardOneSecondAction", action); action = new QAction(tr("Backward One Second"), this); action->setShortcut(QKeySequence(Qt::Key_PageUp)); connect(action, &QAction::triggered, this, [&]() { if (MLT.producer()) seek(position() - qRound(MLT.profile().fps())); }); Actions.add("playerBackwardOneSecondAction", action); action = new QAction(tr("Forward Two Seconds"), this); action->setShortcut(QKeySequence(Qt::SHIFT | Qt::Key_PageDown)); connect(action, &QAction::triggered, this, [&]() { if (MLT.producer()) seek(position() + 2 * qRound(MLT.profile().fps())); }); Actions.add("playerForwardTwoSecondsAction", action); action = new QAction(tr("Backward Two Seconds"), this); action->setShortcut(QKeySequence(Qt::SHIFT | Qt::Key_PageUp)); connect(action, &QAction::triggered, this, [&]() { if (MLT.producer()) seek(position() - 2 * qRound(MLT.profile().fps())); }); Actions.add("playerBackwardTwoAction", action); action = new QAction(tr("Forward Five Seconds"), this); action->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_PageDown)); connect(action, &QAction::triggered, this, [&]() { if (MLT.producer()) seek(position() + 5 * qRound(MLT.profile().fps())); }); Actions.add("playerForwardFiveSecondsAction", action); action = new QAction(tr("Backward Five Seconds"), this); action->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_PageUp)); connect(action, &QAction::triggered, this, [&]() { if (MLT.producer()) seek(position() - 5 * qRound(MLT.profile().fps())); }); Actions.add("playerBackwardFiveSecondsAction", action); action = new QAction(tr("Forward Ten Seconds"), this); action->setShortcut(QKeySequence(Qt::SHIFT | Qt::CTRL | Qt::Key_PageDown)); connect(action, &QAction::triggered, this, [&]() { if (MLT.producer()) seek(position() + 10 * qRound(MLT.profile().fps())); }); Actions.add("playerForwardTenSecondsAction", action); action = new QAction(tr("Backward Ten Seconds"), this); action->setShortcut(QKeySequence(Qt::SHIFT | Qt::CTRL | Qt::Key_PageUp)); connect(action, &QAction::triggered, this, [&]() { if (MLT.producer()) seek(position() - 10 * qRound(MLT.profile().fps())); }); Actions.add("playerBackwardTenSecondsAction", action); action = new QAction(tr("Forward Jump"), this); action->setShortcut(QKeySequence(Qt::ALT | Qt::Key_PageDown)); connect(action, &QAction::triggered, this, [&]() { if (MLT.producer()) seek(position() + qRound(MLT.profile().fps() * Settings.playerJumpSeconds())); }); Actions.add("playerForwardJumpAction", action); action = new QAction(tr("Backward Jump"), this); action->setShortcut(QKeySequence(Qt::ALT | Qt::Key_PageUp)); connect(action, &QAction::triggered, this, [&]() { if (MLT.producer()) seek(position() - qRound(MLT.profile().fps() * Settings.playerJumpSeconds())); }); Actions.add("playerBackwardJumpAction", action); action = new QAction(tr("Set Jump Time"), this); action->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_J)); connect(action, &QAction::triggered, this, [&]() { DurationDialog dialog(this); dialog.setDuration(qRound(MLT.profile().fps() * Settings.playerJumpSeconds())); if (dialog.exec() == QDialog::Accepted) { Settings.setPlayerJumpSeconds((double)dialog.duration() / MLT.profile().fps()); } }); Actions.add("playerSetJumpAction", action); action = new QAction(tr("Trim Clip In"), this); action->setShortcut(QKeySequence(Qt::Key_I)); connect(action, &QAction::triggered, this, [&]() { if (tabIndex() == Player::SourceTabIndex && MLT.isSeekableClip()) { setIn(position()); int delta = position() - MLT.producer()->get_in(); emit inChanged(delta); } else if (tabIndex() == Player::ProjectTabIndex) { emit trimIn(); } }); Actions.add("playerSetInAction", action); action = new QAction(tr("Trim Clip Out"), this); action->setShortcut(QKeySequence(Qt::Key_O)); connect(action, &QAction::triggered, this, [&]() { if (tabIndex() == Player::SourceTabIndex && MLT.isSeekableClip()) { setOut(position()); int delta = position() - MLT.producer()->get_out(); emit outChanged(delta); } else if (tabIndex() == Player::ProjectTabIndex) { emit trimOut(); } }); Actions.add("playerSetOutAction", action); action = new QAction(tr("Set Time Position"), this); action->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_T)); connect(action, &QAction::triggered, this, [&]() { m_positionSpinner->setFocus(Qt::ShortcutFocusReason); }); Actions.add("playerSetPositionAction", action); action = new QAction(tr("Switch Source/Project"), this); action->setShortcut(QKeySequence(Qt::Key_P)); addAction(action); connect(action, &QAction::triggered, this, [&]() { if (MLT.isPlaylist()) { if (MAIN.isMultitrackValid()) onTabBarClicked(Player::ProjectTabIndex); else if (MLT.savedProducer()) onTabBarClicked(Player::SourceTabIndex); } else if (MLT.isMultitrack()) { if (MLT.savedProducer()) onTabBarClicked(Player::SourceTabIndex); // TODO else open clip under playhead of current track if available } else { if (MAIN.isMultitrackValid() || (MAIN.playlist() && MAIN.playlist()->count() > 0)) onTabBarClicked(Player::ProjectTabIndex); } }); Actions.add("playerSwitchSourceProgramAction", action); action = new QAction(tr("Pause"), this); action->setProperty(Actions.hardKeyProperty, "K"); action->setIcon(m_pauseIcon); action->setToolTip(tr("Pause playback")); connect(action, &QAction::triggered, this, &Player::pause); Actions.add("playerPauseAction", action, tr("Player")); action = new QAction(tr("Focus Player"), this); action->setProperty(Actions.hardKeyProperty, "Shift+Esc"); connect(action, &QAction::triggered, this, [&]() { setFocus(); }); Actions.add("playerFocus", action, tr("Player")); } void Player::setIn(int pos) { LOG_DEBUG() << "in" << pos << "out" << m_previousOut; // Changing out must come before in because mlt_playlist will automatically swap them if out < in if (pos >= 0 && pos > m_previousOut) { onOutChanged(m_duration - 1); m_scrubber->setOutPoint(m_duration - 1); } m_scrubber->setInPoint(pos); } void Player::setOut(int pos) { LOG_DEBUG() << "in" << m_previousIn << "out" << pos; // Changing in must come before out because mlt_playlist will automatically swap them if out < in if (pos >= 0 && pos < m_previousIn) { onInChanged(0); m_scrubber->setInPoint(0); } m_scrubber->setOutPoint(pos); } void Player::setMarkers(const QList<int> &markers) { m_scrubber->setMarkers(markers); } QSize Player::videoSize() const { return m_videoWidget->size(); } void Player::resizeEvent(QResizeEvent *) { MLT.onWindowResize(); if (Settings.playerZoom() > 0.0f) { float horizontal = float(m_horizontalScroll->value()) / m_horizontalScroll->maximum(); float vertical = float(m_verticalScroll->value()) / m_verticalScroll->maximum(); adjustScrollBars(horizontal, vertical); } else { m_horizontalScroll->hide(); m_verticalScroll->hide(); } layoutToolbars(); } bool Player::event(QEvent *event) { bool result = QWidget::event(event); if (event->type() == QEvent::PaletteChange) { m_videoScrollWidget->hide(); m_videoScrollWidget->show(); } return result; } void Player::keyPressEvent(QKeyEvent *event) { QWidget::keyPressEvent(event); if (!event->isAccepted()) MAIN.keyPressEvent(event); } void Player::play(double speed) { // Start from beginning if trying to start at the end. if (m_position >= m_duration - 1 && !MLT.isMultitrack()) { emit seeked(m_previousIn); m_position = m_previousIn; } emit played(speed); if (m_isSeekable) { Actions["playerPlayPauseAction"]->setIcon(m_pauseIcon); } else { Actions["playerPlayPauseAction"]->setIcon(m_stopIcon); } m_playPosition = m_position; } void Player::pause() { emit paused(); showPaused(); } void Player::stop() { emit stopped(); Actions["playerPlayPauseAction"]->setIcon(m_playIcon); } void Player::seek(int position) { if (m_isSeekable) { if (position >= 0) { emit seeked(qMin(position, MLT.isMultitrack() ? m_duration : m_duration - 1)); } } // Seek implies pause. Actions["playerPlayPauseAction"]->setIcon(m_playIcon); m_playPosition = std::numeric_limits<int>::max(); } void Player::reset() { m_scrubber->setMarkers(QList<int>()); m_inPointLabel->setText(blankTime()); m_selectedLabel->setText(blankTime()); m_durationLabel->setText(blankTime()); m_scrubber->setDisabled(true); m_scrubber->setScale(1); m_positionSpinner->setValue(0); m_positionSpinner->setDisabled(true); Actions["playerPlayPauseAction"]->setDisabled(true); Actions["playerSkipPreviousAction"]->setDisabled(true); Actions["playerSkipNextAction"]->setDisabled(true); Actions["playerRewindAction"]->setDisabled(true); Actions["playerFastForwardAction"]->setDisabled(true); m_videoWidget->hide(); m_projectWidget->show(); m_previousIn = m_previousOut = -1; } void Player::onProducerOpened(bool play) { m_projectWidget->hide(); m_videoWidget->show(); m_duration = MLT.producer()->get_length(); setLoopRange(0, m_duration - 1); m_isSeekable = MLT.isSeekable(); MLT.producer()->set("ignore_points", 1); m_scrubber->setFramerate(MLT.profile().fps()); m_scrubber->setScale(m_duration); if (!MLT.isPlaylist()) m_scrubber->setMarkers(QList<int>()); m_inPointLabel->setText(blankTime()); m_selectedLabel->setText(blankTime()); if (m_isSeekable) { m_durationLabel->setText(QString(MLT.producer()->get_length_time(Settings.timeFormat()))); MLT.producer()->get_length_time(mlt_time_clock); m_previousIn = MLT.isClip() ? MLT.producer()->get_in() : -1; m_scrubber->setEnabled(true); m_scrubber->setInPoint(m_previousIn); m_previousOut = MLT.isClip() ? MLT.producer()->get_out() : -1; m_scrubber->setOutPoint(m_previousOut); } else { m_durationLabel->setText(tr("Not Seekable")); m_scrubber->setDisabled(true); // cause scrubber redraw m_scrubber->setScale(m_duration); } if (MLT.isMultitrack()) { Actions["playerLoopRangeMarkerAction"]->setEnabled(true); } else { Actions["playerLoopRangeMarkerAction"]->setEnabled(false); } m_positionSpinner->setEnabled(m_isSeekable); setVolume(m_volumeSlider->value()); m_savedVolume = MLT.volume(); onMuteButtonToggled(Settings.playerMuted()); toggleZoom(Settings.playerZoom() > 0.0f); Actions["playerPlayPauseAction"]->setEnabled(true); Actions["playerSkipPreviousAction"]->setEnabled(m_isSeekable); Actions["playerSkipNextAction"]->setEnabled(m_isSeekable); Actions["playerRewindAction"]->setEnabled(m_isSeekable); Actions["playerFastForwardAction"]->setEnabled(m_isSeekable); connectTransport(MLT.transportControl()); // Closing the previous producer might call pause() milliseconds before // calling play() here. Delays while purging the consumer on pause can // interfere with the play() call. So, we delay play a little to let // pause purging to complete. if (play) { if (m_pauseAfterOpen) { m_pauseAfterOpen = false; QTimer::singleShot(500, this, SLOT(postProducerOpened())); if (!MLT.isClip()) { MLT.producer()->seek(0); } } else { if (MLT.consumer()->is_stopped()) { QTimer::singleShot(500, this, SLOT(play())); } else { // This seek purges the consumer to prevent latent end-of-stream detection. seek(0); QTimer::singleShot(500, this, SLOT(play())); } } } } void Player::postProducerOpened() { if (MLT.producer()) seek(MLT.producer()->position()); } void Player::onMeltedUnitOpened() { m_isMeltedPlaying = -1; // unknown m_duration = MLT.producer()->get_length(); m_isSeekable = true; MLT.producer()->set("ignore_points", 1); m_scrubber->setFramerate(MLT.profile().fps()); m_scrubber->setScale(m_duration); m_scrubber->setMarkers(QList<int>()); m_inPointLabel->setText(blankTime()); m_selectedLabel->setText(blankTime()); m_durationLabel->setText(QString(MLT.producer()->get_length_time(Settings.timeFormat()))); MLT.producer()->get_length_time(mlt_time_clock); m_previousIn = MLT.producer()->get_in(); m_scrubber->setEnabled(true); m_scrubber->setInPoint(m_previousIn); m_previousOut = MLT.producer()->get_out(); m_scrubber->setOutPoint(m_previousOut); m_positionSpinner->setEnabled(m_isSeekable); setVolume(m_volumeSlider->value()); m_savedVolume = MLT.volume(); onMuteButtonToggled(Settings.playerMuted()); Actions["playerPlayPauseAction"]->setEnabled(true); Actions["playerSkipPreviousAction"]->setEnabled(m_isSeekable); Actions["playerSkipNextAction"]->setEnabled(m_isSeekable); Actions["playerRewindAction"]->setEnabled(m_isSeekable); Actions["playerFastForwardAction"]->setEnabled(m_isSeekable); setIn(-1); setOut(-1); setFocus(); } void Player::onDurationChanged() { m_duration = MLT.producer()->get_length(); setLoopRange(0, m_duration - 1); m_isSeekable = MLT.isSeekable(); m_scrubber->setScale(m_duration); m_scrubber->setMarkers(QList<int>()); m_durationLabel->setText(QString(MLT.producer()->get_length_time(Settings.timeFormat()))); MLT.producer()->get_length_time(mlt_time_clock); if (MLT.producer()->get_speed() == 0) seek(m_position); else if (m_position >= m_duration) seek(m_duration - 1); } void Player::onFrameDisplayed(const SharedFrame &frame) { if (!MLT.producer() || !MLT.producer()->is_valid()) return; if (MLT.producer()->get_length() != m_duration) { // This can happen if the profile changes. Reload the properties from the producer. onProducerOpened(false); } int position = frame.get_position(); bool loop = position >= (m_loopEnd - 1) && Actions["playerLoopAction"]->isChecked(); if (position > MLT.producer()->get_length()) { position = MLT.producer()->get_length(); } if (position <= m_duration) { m_position = position; m_positionSpinner->blockSignals(true); m_positionSpinner->setValue(position); m_positionSpinner->blockSignals(false); m_scrubber->onSeek(position); if (m_playPosition < m_previousOut && m_position >= m_previousOut && !loop) { seek(m_previousOut); } } if (loop) { MLT.producer()->seek(m_loopStart); MLT.consumer()->purge(); } else if (position >= m_duration - 1) { emit endOfStream(); } } void Player::updateSelection() { if (MLT.producer() && MLT.producer()->get_in() > 0) { m_inPointLabel->setText(QString(MLT.producer()->get_time("in", Settings.timeFormat()))); m_selectedLabel->setText(MLT.producer()->frames_to_time(MLT.producer()->get_playtime(), Settings.timeFormat())); } else { m_inPointLabel->setText(blankTime()); if (MLT.isClip() && MLT.producer()->get_out() < m_duration - 1) { m_selectedLabel->setText(MLT.producer()->frames_to_time(MLT.producer()->get_playtime(), Settings.timeFormat())); } else if (!MLT.producer() || MLT.producer()->get_in() == 0) { m_selectedLabel->setText(blankTime()); } } } void Player::onInChanged(int in) { if (in != m_previousIn && in >= 0) { int delta = in - MLT.producer()->get_in(); MLT.setIn(in); emit inChanged(delta); } m_previousIn = in; updateSelection(); } void Player::onOutChanged(int out) { if (out != m_previousOut && out >= 0) { int delta = out - MLT.producer()->get_out(); MLT.setOut(out); emit outChanged(delta); } m_previousOut = out; m_playPosition = m_previousOut; // prevent O key from pausing updateSelection(); } void Player::rewind(bool forceChangeDirection) { if (m_isSeekable) emit rewound(forceChangeDirection); } void Player::fastForward(bool forceChangeDirection) { if (m_isSeekable) { emit fastForwarded(forceChangeDirection); m_playPosition = m_position; } else { play(); } } void Player::showPaused() { Actions["playerPlayPauseAction"]->setIcon(m_playIcon); } void Player::showPlaying() { Actions["playerPlayPauseAction"]->setIcon(m_pauseIcon); } void Player::switchToTab(TabIndex index) { m_tabs->setCurrentIndex(index); emit tabIndexChanged(index); } void Player::enableTab(TabIndex index, bool enabled) { m_tabs->setTabEnabled(index, enabled); } void Player::onTabBarClicked(int index) { // Do nothing if requested tab is already selected. if (m_tabs->currentIndex() == index) return; switch (index) { case SourceTabIndex: if (MLT.savedProducer() && MLT.savedProducer()->is_valid() && MLT.producer() && MLT.producer()->get_producer() != MLT.savedProducer()->get_producer()) { m_pauseAfterOpen = true; MAIN.open(new Mlt::Producer(MLT.savedProducer())); } break; case ProjectTabIndex: if (MAIN.isMultitrackValid()) { if (!MLT.isMultitrack()) MAIN.seekTimeline(MAIN.multitrack()->position()); } else { if (!MLT.isPlaylist() && MAIN.playlist()) MAIN.seekPlaylist(MAIN.playlist()->position()); } break; } } void Player::setStatusLabel(const QString &text, int timeoutSeconds, QAction *action, QPalette::ColorRole role) { m_statusLabel->setWidth(m_scrubber->width() - m_tabs->width()); m_statusLabel->showText(text, timeoutSeconds, action, role); } void Player::onStatusFinished() { showIdleStatus(); } void Player::onOffsetChanged(const QPoint &offset) { if (!offset.isNull() && m_horizontalScroll->isVisible()) { m_horizontalScroll->setValue(offset.x()); m_verticalScroll->setValue(offset.y()); } } void Player::adjustScrollBars(float horizontal, float vertical) { if (MLT.profile().width() * m_zoomToggleFactor > m_videoWidget->width()) { m_horizontalScroll->setPageStep(m_videoWidget->width()); m_horizontalScroll->setMaximum(MLT.profile().width() * m_zoomToggleFactor - m_horizontalScroll->pageStep()); m_horizontalScroll->setValue(qRound(horizontal * m_horizontalScroll->maximum())); emit m_horizontalScroll->valueChanged(m_horizontalScroll->value()); m_horizontalScroll->show(); } else { int max = MLT.profile().width() * m_zoomToggleFactor - m_videoWidget->width(); emit m_horizontalScroll->valueChanged(qRound(0.5 * max)); m_horizontalScroll->hide(); } if (MLT.profile().height() * m_zoomToggleFactor > m_videoWidget->height()) { m_verticalScroll->setPageStep(m_videoWidget->height()); m_verticalScroll->setMaximum(MLT.profile().height() * m_zoomToggleFactor - m_verticalScroll->pageStep()); m_verticalScroll->setValue(qRound(vertical * m_verticalScroll->maximum())); emit m_verticalScroll->valueChanged(m_verticalScroll->value()); m_verticalScroll->show(); } else { int max = MLT.profile().height() * m_zoomToggleFactor - m_videoWidget->height(); emit m_verticalScroll->valueChanged(qRound(0.5 * max)); m_verticalScroll->hide(); } } double Player::setVolume(int volume) { const double gain = double(volume) / VOLUME_KNEE; MLT.setVolume(gain); return gain; } void Player::setLoopRange(int start, int end) { m_loopStart = start; m_loopEnd = end; if (Actions["playerLoopAction"]->isChecked()) { m_scrubber->setLoopRange(m_loopStart, m_loopEnd); emit loopChanged(m_loopStart, m_loopEnd); } else { m_scrubber->setLoopRange(-1, -1); emit loopChanged(-1, -1); } } void Player::layoutToolbars() { int totalWidth = m_currentDurationToolBar->sizeHint().width() + m_controlsToolBar->sizeHint().width() + m_optionsToolBar->sizeHint().width() + m_inSelectedToolBar->sizeHint().width() + 20; bool twoRowsInUse = m_toolRow2->count() > 0; if (m_toolRow1->count() > 0) { if (totalWidth <= this->width() && !twoRowsInUse) { // Everything still fits in one toolbar. Nothing to change. return; } else if (totalWidth > this->width() && twoRowsInUse) { // Two toolbars still needed. Nothing to change. return; } } // Remove all the widgets from the tool bar area QLayoutItem *child; while ((child = m_toolRow1->takeAt(0)) != nullptr) { QWidget *widget = child->widget(); if (widget->objectName().startsWith("spacer")) { delete widget; } delete child; } while ((child = m_toolRow2->takeAt(0)) != nullptr) { QWidget *widget = child->widget(); if (widget->objectName().startsWith("spacer")) { delete widget; } delete child; } QWidget *spacer; if (totalWidth <= this->width()) { // Use one row m_toolRow1->addWidget(m_currentDurationToolBar); spacer = new QWidget(this); spacer->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Preferred); spacer->setObjectName("spacerLeft"); m_toolRow1->addWidget(spacer); m_toolRow1->addWidget(m_controlsToolBar); m_toolRow1->addWidget(m_optionsToolBar); spacer = new QWidget(this); spacer->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Preferred); spacer->setObjectName("spacerRight"); m_toolRow1->addWidget(spacer); m_toolRow1->addWidget(m_inSelectedToolBar); } else { // Use two rows spacer = new QWidget(this); spacer->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Preferred); spacer->setObjectName("spacerLeft"); m_toolRow1->addWidget(spacer); m_toolRow1->addWidget(m_controlsToolBar); m_toolRow1->addWidget(m_optionsToolBar); spacer = new QWidget(this); spacer->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Preferred); spacer->setObjectName("spacerRight"); m_toolRow1->addWidget(spacer); m_toolRow2->addWidget(m_currentDurationToolBar); spacer = new QWidget(this); spacer->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Preferred); spacer->setObjectName("spacerMiddle"); m_toolRow2->addWidget(spacer); m_toolRow2->addWidget(m_inSelectedToolBar); } } void Player::showIdleStatus() { if (Settings.proxyEnabled() && Settings.playerPreviewScale() > 0) { setStatusLabel(tr("Proxy and preview scaling are ON at %1p").arg(ProxyManager::resolution()), -1, nullptr, QPalette::AlternateBase); } else if (Settings.proxyEnabled()) { setStatusLabel(tr("Proxy is ON at %1p").arg(ProxyManager::resolution()), -1, nullptr, QPalette::AlternateBase); } else if (Settings.playerPreviewScale() > 0) { setStatusLabel(tr("Preview scaling is ON at %1p").arg(Settings.playerPreviewScale()), -1, nullptr, QPalette::AlternateBase); } else { setStatusLabel("", -1, nullptr); } } void Player::focusPositionSpinner() const { m_positionSpinner->setFocus(Qt::ShortcutFocusReason); } void Player::moveVideoToScreen(int screen) { if (screen == m_monitorScreen) return; if (screen == -2) { // -2 = embedded if (!m_videoScrollWidget->isFullScreen()) return; m_videoScrollWidget->showNormal(); m_videoLayout->insertWidget(0, m_videoScrollWidget, 10); } else if (QGuiApplication::screens().size() > 1) { // -1 = find first screen the app is not using for (int i = 0; screen == -1 && i < QGuiApplication::screens().size(); i++) { if (QGuiApplication::screens().at(i) != this->screen()) screen = i; } m_videoScrollWidget->showNormal(); m_videoScrollWidget->setParent(nullptr); m_videoScrollWidget->move(QGuiApplication::screens().at(screen)->geometry().topLeft()); m_videoScrollWidget->showFullScreen(); } m_monitorScreen = screen; QCoreApplication::processEvents(); } void Player::setPauseAfterOpen(bool pause) { m_pauseAfterOpen = pause; } Player::TabIndex Player::tabIndex() const { return TabIndex(m_tabs->currentIndex()); } //---------------------------------------------------------------------------- // IEC standard dB scaling -- as borrowed from meterbridge (c) Steve Harris static inline float IEC_dB ( float fScale ) { float dB = 0.0f; if (fScale < 0.025f) // IEC_Scale(-60.0f) dB = (fScale / 0.0025f) - 70.0f; else if (fScale < 0.075f) // IEC_Scale(-50.0f) dB = (fScale - 0.025f) / 0.005f - 60.0f; else if (fScale < 0.15f) // IEC_Scale(-40.0f) dB = (fScale - 0.075f) / 0.0075f - 50.0f; else if (fScale < 0.3f) // IEC_Scale(-30.0f) dB = (fScale - 0.15f) / 0.015f - 40.0f; else if (fScale < 0.5f) // IEC_Scale(-20.0f) dB = (fScale - 0.3f) / 0.02f - 30.0f; else /* if (fScale < 1.0f) // IED_Scale(0.0f)) */ dB = (fScale - 0.5f) / 0.025f - 20.0f; return (dB > -0.001f && dB < 0.001f ? 0.0f : dB); } void Player::onVolumeChanged(int volume) { const double gain = setVolume(volume); emit showStatusMessage(QStringLiteral("%L1 dB").arg(IEC_dB(gain))); Settings.setPlayerVolume(volume); Settings.setPlayerMuted(false); m_muteButton->setChecked(false); m_volumeButton->setIcon(QIcon::fromTheme("player-volume", QIcon(":/icons/oxygen/32x32/actions/player-volume.png"))); m_muteButton->setIcon(QIcon::fromTheme("audio-volume-muted", QIcon(":/icons/oxygen/32x32/status/audio-volume-muted.png"))); m_muteButton->setToolTip(tr("Mute")); } void Player::onCaptureStateChanged(bool active) { Actions["playerPlayPauseAction"]->setDisabled(active); } void Player::onVolumeTriggered() { // We must show first to realizes the volume popup geometry. m_volumePopup->show(); int x = (m_volumeButton->width() - m_volumePopup->width()) / 2; int y = m_volumeButton->height() - m_volumePopup->height(); m_volumePopup->move(m_volumeButton->mapToGlobal(QPoint(x, y))); m_volumeButton->hide(); m_volumeButton->show(); } void Player::onMuteButtonToggled(bool checked) { m_muteButton->setChecked(checked); if (checked) { m_savedVolume = MLT.volume(); MLT.setVolume(0); m_volumeButton->setIcon(QIcon::fromTheme("audio-volume-muted", QIcon(":/icons/oxygen/32x32/status/audio-volume-muted.png"))); m_muteButton->setIcon(QIcon::fromTheme("audio-volume-high", QIcon(":/icons/oxygen/32x32/status/audio-volume-high.png"))); m_muteButton->setToolTip(tr("Unmute")); } else { MLT.setVolume(m_savedVolume); m_volumeButton->setIcon(QIcon::fromTheme("player-volume", QIcon(":/icons/oxygen/32x32/actions/player-volume.png"))); m_muteButton->setIcon(QIcon::fromTheme("audio-volume-muted", QIcon(":/icons/oxygen/32x32/status/audio-volume-muted.png"))); m_muteButton->setToolTip(tr("Mute")); } Settings.setPlayerMuted(checked); m_volumePopup->hide(); } void Player::setZoom(float factor, const QIcon &icon) { emit zoomChanged(factor); Settings.setPlayerZoom(factor); if (factor == 0.0f) { m_zoomButton->setIcon(icon); m_zoomButton->setChecked(false); m_horizontalScroll->hide(); m_verticalScroll->hide(); } else { m_zoomToggleFactor = factor; adjustScrollBars(0.5f, 0.5f); m_zoomButton->setIcon(icon); m_zoomButton->setChecked(true); } } void Player::onZoomTriggered() { QAction *action = qobject_cast<QAction *>(sender()); setZoom(action->data().toFloat(), action->icon()); } void Player::toggleZoom(bool checked) { foreach (QAction *a, m_zoomMenu->actions()) { if ((!checked || m_zoomToggleFactor == 0.0f) && a->data().toFloat() == 0.0f) { setZoom(0.0f, a->icon()); break; } else if (a->data().toFloat() == m_zoomToggleFactor) { setZoom(m_zoomToggleFactor, a->icon()); break; } } } void Player::onGridToggled() { m_gridButton->setChecked(true); m_gridDefaultAction = qobject_cast<QAction *>(sender()); emit gridChanged(m_gridDefaultAction->data().toInt()); } void Player::toggleGrid(bool checked) { QAction *action = m_gridActionGroup->checkedAction(); if (!checked) { if (action) action->setChecked(false); emit gridChanged(0); } else { if (!action) m_gridDefaultAction->trigger(); } }
56,797
C++
.cpp
1,350
35.337037
111
0.648809
mltframework/shotcut
10,796
1,118
50
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
13,122
database.cpp
mltframework_shotcut/src/database.cpp
/* * Copyright (c) 2013-2022 Meltytech, LLC * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "database.h" #include "settings.h" #include "dialogs/longuitask.h" #include <QtSql> #include <QDir> #include <QFileInfo> #include <Logger.h> #include <utime.h> static QMutex g_mutex; static Database *instance = nullptr; static const int kMaxThumbnailCount = 5000; static const int kDeleteThumbnailsTimeoutMs = 60000; Database::Database(QObject *parent) : QObject(parent) { m_deleteTimer.setInterval(kDeleteThumbnailsTimeoutMs); connect(&m_deleteTimer, SIGNAL(timeout()), this, SLOT(deleteOldThumbnails())); thumbnailsDir(); // convert from db to filesystem if needed m_deleteTimer.start(); } Database &Database::singleton(QObject *parent) { QMutexLocker locker(&g_mutex); if (!instance) { instance = new Database(parent); } return *instance; } static QString toFileName(const QString &s) { QString result = s; return result.replace(':', '-') + + ".png"; } QDir Database::thumbnailsDir() { QDir dir(Settings.appDataLocation()); const char *subfolder = "thumbnails"; if (!dir.cd(subfolder)) { if (dir.mkdir(subfolder)) { dir.cd(subfolder); // Convert the DB data to files on the filesystem. LongUiTask longTask(QObject::tr("Converting Thumbnails")); QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE"); QDir appDir(Settings.appDataLocation()); QString dbFilePath = appDir.filePath("db.sqlite3"); db.setDatabaseName(dbFilePath); if (db.open()) { QSqlQuery query; QImage img; query.setForwardOnly(true); int n = -1; if (query.exec("SELECT COUNT(*) FROM thumbnails;") && query.next()) { n = query.value(0).toInt(); } query.exec( QStringLiteral("SELECT hash, accessed, image FROM thumbnails ORDER BY accessed DESC LIMIT %1").arg( kMaxThumbnailCount)); for (int i = 0; query.next(); i++) { QString fileName = toFileName(query.value(0).toString()); longTask.reportProgress( QObject::tr("Please wait for this one-time update to the thumbnail cache..."), i, n); if (img.loadFromData(query.value(2).toByteArray(), "PNG")) { img.save(dir.filePath(fileName)); auto accessed = query.value(1).toDateTime(); auto offset = accessed.timeZone().offsetFromUtc(accessed); struct utimbuf utimes { accessed.toSecsSinceEpoch() + offset, accessed.toSecsSinceEpoch() + offset }; ::utime(dir.filePath(fileName).toUtf8().constData(), &utimes); } } db.close(); QSqlDatabase::removeDatabase("QSQLITE"); } } } return dir; } bool Database::putThumbnail(const QString &hash, const QImage &image) { return image.save(thumbnailsDir().filePath(toFileName(hash))); } QImage Database::getThumbnail(const QString &hash) { QString filePath = thumbnailsDir().filePath(toFileName(hash)); ::utime(filePath.toUtf8().constData(), nullptr); return QImage(filePath); } void Database::deleteOldThumbnails() { auto result = QtConcurrent::run([ = ]() { QDir dir = thumbnailsDir(); auto ls = dir.entryList(QDir::Files | QDir::NoDotAndDotDot | QDir::Readable, QDir::Time); if (ls.size() - kMaxThumbnailCount > 0) LOG_DEBUG() << "removing" << ls.size() - kMaxThumbnailCount; for (int i = kMaxThumbnailCount; i < ls.size(); i++) { QString filePath = dir.filePath(ls[i]); if (!QFile::remove(filePath)) { LOG_WARNING() << "failed to delete" << filePath; } } }); }
4,665
C++
.cpp
118
31.237288
119
0.615385
mltframework/shotcut
10,796
1,118
50
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
13,123
videowidget.cpp
mltframework_shotcut/src/videowidget.cpp
/* * Copyright (c) 2011-2024 Meltytech, LLC * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <QtWidgets> #include <QUrl> #include <QOffscreenSurface> #include <QOpenGLContext> #include <QtQml> #include <QQuickItem> #include <Mlt.h> #include <Logger.h> #include "videowidget.h" #include "settings.h" #include "qmltypes/qmlutilities.h" #include "qmltypes/qmlfilter.h" #include "mainwindow.h" using namespace Mlt; VideoWidget::VideoWidget(QObject *parent) : QQuickWidget(QmlUtilities::sharedEngine(), (QWidget *) parent) , Controller() , m_grid(0) , m_initSem(0) , m_isInitialized(false) , m_frameRenderer(nullptr) , m_zoom(0.0f) , m_offset(QPoint(0, 0)) , m_snapToGrid(true) , m_scrubAudio(false) , m_maxTextureSize(4096) { LOG_DEBUG() << "begin"; setAttribute(Qt::WA_AcceptTouchEvents); setResizeMode(QQuickWidget::SizeRootObjectToView); setClearColor(palette().window().color()); QDir importPath = QmlUtilities::qmlDir(); importPath.cd("modules"); engine()->addImportPath(importPath.path()); QmlUtilities::setCommonProperties(rootContext()); rootContext()->setContextProperty("video", this); m_refreshTimer.setInterval(10); m_refreshTimer.setSingleShot(true); if (Settings.playerGPU()) m_glslManager.reset(new Filter(profile(), "glsl.manager")); if ((m_glslManager && !m_glslManager->is_valid())) { m_glslManager.reset(); } connect(quickWindow(), &QQuickWindow::visibilityChanged, this, &VideoWidget::setBlankScene, Qt::QueuedConnection); connect(&m_refreshTimer, &QTimer::timeout, this, &VideoWidget::onRefreshTimeout); connect(this, &VideoWidget::rectChanged, this, &VideoWidget::zoomChanged); LOG_DEBUG() << "end"; } VideoWidget::~VideoWidget() { LOG_DEBUG() << "begin"; stop(); if (m_frameRenderer && m_frameRenderer->isRunning()) { m_frameRenderer->quit(); m_frameRenderer->wait(); m_frameRenderer->deleteLater(); } LOG_DEBUG() << "end"; } void VideoWidget::initialize() { LOG_DEBUG() << "begin"; m_frameRenderer = new FrameRenderer(); connect(m_frameRenderer, &FrameRenderer::frameDisplayed, this, &VideoWidget::onFrameDisplayed, Qt::QueuedConnection); connect(m_frameRenderer, &FrameRenderer::frameDisplayed, this, &VideoWidget::frameDisplayed, Qt::QueuedConnection); connect(m_frameRenderer, SIGNAL(imageReady()), SIGNAL(imageReady())); m_initSem.release(); m_isInitialized = true; LOG_DEBUG() << "end"; } void VideoWidget::renderVideo() { } void VideoWidget::setBlankScene() { quickWindow()->setColor(palette().window().color()); setSource(QmlUtilities::blankVui()); m_savedQmlSource.clear(); } void VideoWidget::resizeVideo(int width, int height) { double x, y, w, h; double this_aspect = (double) width / height; double video_aspect = profile().dar(); // Special case optimisation to negate odd effect of sample aspect ratio // not corresponding exactly with image resolution. if ((int) (this_aspect * 1000) == (int) (video_aspect * 1000)) { w = width; h = height; } // Use OpenGL to normalise sample aspect ratio else if (height * video_aspect > width) { w = width; h = width / video_aspect; } else { w = height * video_aspect; h = height; } x = (width - w) / 2.0; y = (height - h) / 2.0; m_rect.setRect(x, y, w, h); emit rectChanged(); } void VideoWidget::resizeEvent(QResizeEvent *event) { QQuickWidget::resizeEvent(event); resizeVideo(event->size().width(), event->size().height()); } void VideoWidget::onRefreshTimeout() { Controller::refreshConsumer(m_scrubAudio); m_scrubAudio = false; } void VideoWidget::mousePressEvent(QMouseEvent *event) { QQuickWidget::mousePressEvent(event); if (event->isAccepted()) return; if (event->button() == Qt::LeftButton) m_dragStart = event->pos(); else if (event->button() == Qt::MiddleButton) m_mousePosition = event->pos(); if (MLT.isClip()) emit dragStarted(); } void VideoWidget::mouseMoveEvent(QMouseEvent *event) { QQuickWidget::mouseMoveEvent(event); if (event->isAccepted()) return; if (event->buttons() & Qt::MiddleButton) { emit offsetChanged(m_offset + m_mousePosition - event->pos()); m_mousePosition = event->pos(); return; } if (event->modifiers() == (Qt::ShiftModifier | Qt::AltModifier) && m_producer) { emit seekTo(m_producer->get_length() * event->position().x() / width()); return; } if (!(event->buttons() & Qt::LeftButton)) return; if (m_dragStart.isNull()) return; if ((event->pos() - m_dragStart).manhattanLength() < QApplication::startDragDistance()) return; // Reset the drag point to prevent repeating drag actions. m_dragStart.setX(0); m_dragStart.setY(0); if (!MLT.producer()) return; if (MLT.isMultitrack() || MLT.isPlaylist()) { MAIN.showStatusMessage(tr("You cannot drag from Project.")); return; } else if (!MLT.isSeekableClip()) { MAIN.showStatusMessage(tr("You cannot drag a non-seekable source")); return; } QDrag *drag = new QDrag(this); QMimeData *mimeData = new QMimeData; mimeData->setData(Mlt::XmlMimeType, MLT.XML().toUtf8()); drag->setMimeData(mimeData); mimeData->setText(QString::number(MLT.producer()->get_playtime())); if (m_frameRenderer && m_frameRenderer->getDisplayFrame().is_valid()) { Mlt::Frame displayFrame(m_frameRenderer->getDisplayFrame().clone(false, true)); QImage displayImage = MLT.image(&displayFrame, 45 * MLT.profile().dar(), 45).scaledToHeight(45); drag->setPixmap(QPixmap::fromImage(displayImage)); } drag->setHotSpot(QPoint(0, 0)); drag->exec(Qt::LinkAction); } void VideoWidget::keyPressEvent(QKeyEvent *event) { QQuickWidget::keyPressEvent(event); if (event->isAccepted()) return; MAIN.keyPressEvent(event); } bool VideoWidget::event(QEvent *event) { bool result = QQuickWidget::event(event); if (event->type() == QEvent::PaletteChange && m_sharedFrame.is_valid()) onFrameDisplayed(m_sharedFrame); return result; } int VideoWidget::setProducer(Mlt::Producer *producer, bool isMulti) { int error = Controller::setProducer(producer, isMulti); if (!error) { error = reconfigure(isMulti); if (!error) { // The profile display aspect ratio may have changed. resizeVideo(width(), height()); } } return error; } void VideoWidget::createThread(RenderThread **thread, thread_function_t function, void *data) { #ifdef Q_OS_WIN // On Windows, MLT event consumer-thread-create is fired from the Qt main thread. while (!m_isInitialized) QCoreApplication::processEvents(); #else if (!m_isInitialized) { m_initSem.acquire(); } #endif if (!m_renderThread) { m_renderThread.reset(new RenderThread(function, data)); (*thread) = m_renderThread.get(); (*thread)->start(); } else { m_renderThread->start(); } } static void onThreadCreate(mlt_properties owner, VideoWidget *self, mlt_event_data data) { Q_UNUSED(owner) auto threadData = (mlt_event_data_thread *) Mlt::EventData(data).to_object(); if (threadData) { self->createThread((RenderThread **) threadData->thread, threadData->function, threadData->data); } } static void onThreadJoin(mlt_properties owner, VideoWidget *self, mlt_event_data data) { Q_UNUSED(owner) Q_UNUSED(self) auto threadData = (mlt_event_data_thread *) Mlt::EventData(data).to_object(); if (threadData && threadData->thread) { auto renderThread = (RenderThread *) *threadData->thread; if (renderThread) { renderThread->quit(); renderThread->wait(); } } } void VideoWidget::startGlsl() { if (m_glslManager) { m_glslManager->fire_event("init glsl"); if (!m_glslManager->get_int("glsl_supported")) { m_glslManager.reset(); // Need to destroy MLT global reference to prevent filters from trying to use GPU. mlt_properties_clear(mlt_global_properties(), "glslManager"); emit gpuNotSupported(); } else { emit started(); } } } static void onThreadStarted(mlt_properties owner, VideoWidget *self) { Q_UNUSED(owner) self->startGlsl(); } void VideoWidget::stopGlsl() { //TODO This is commented out for now because it is causing crashes. //Technically, this should be the correct thing to do, but it appears //some changes in the 15.01 and 15.03 releases have created regression //with respect to restarting the consumer in GPU mode. // m_glslManager->fire_event("close glsl"); } static void onThreadStopped(mlt_properties owner, VideoWidget *self) { Q_UNUSED(owner) self->stopGlsl(); } int VideoWidget::reconfigure(bool isMulti) { int error = 0; // use SDL for audio, OpenGL for video QString serviceName = property("mlt_service").toString(); if (!m_consumer || !m_consumer->is_valid()) { if (serviceName.isEmpty()) { m_consumer.reset(new Mlt::FilteredConsumer(previewProfile(), "sdl2_audio")); if (m_consumer->is_valid()) serviceName = "sdl2_audio"; else serviceName = "rtaudio"; m_consumer.reset(); } if (isMulti) m_consumer.reset(new Mlt::FilteredConsumer(previewProfile(), "multi")); else m_consumer.reset(new Mlt::FilteredConsumer(previewProfile(), serviceName.toLatin1().constData())); m_threadStartEvent.reset(); m_threadStopEvent.reset(); m_threadCreateEvent.reset(); m_threadJoinEvent.reset(); } if (m_consumer->is_valid()) { // Connect the producer to the consumer - tell it to "run" later m_consumer->connect(*m_producer); // Make an event handler for when a frame's image should be displayed m_consumer->listen("consumer-frame-show", this, (mlt_listener) on_frame_show); m_consumer->set("real_time", MLT.realTime()); m_consumer->set("mlt_image_format", serviceName.startsWith("decklink") ? "yuv422p" : "yuv420p"); m_consumer->set("channels", property("audio_channels").toInt()); if (property("audio_channels").toInt() == 4) { m_consumer->set("channel_layout", "quad"); } else { m_consumer->set("channel_layout", "auto"); } switch (MLT.profile().colorspace()) { case 601: case 170: m_consumer->set("color_trc", "smpte170m"); break; case 240: m_consumer->set("color_trc", "smpte240m"); break; case 470: m_consumer->set("color_trc", "bt470bg"); break; default: m_consumer->set("color_trc", "bt709"); break; } if (isMulti) { m_consumer->set("terminate_on_pause", 0); m_consumer->set("0", serviceName.toLatin1().constData()); if (!profile().progressive()) m_consumer->set("0.progressive", property("progressive").toBool()); m_consumer->set("0.rescale", property("rescale").toString().toLatin1().constData()); m_consumer->set("0.deinterlacer", property("deinterlacer").toString().toLatin1().constData()); m_consumer->set("0.buffer", qMax(25, qRound(profile().fps()))); m_consumer->set("0.prefill", 8); m_consumer->set("0.drop_max", qRound(profile().fps() / 4.0)); if (property("keyer").isValid()) m_consumer->set("0.keyer", property("keyer").toInt()); m_consumer->set("0.video_delay", Settings.playerVideoDelayMs()); } else { if (!profile().progressive()) m_consumer->set("progressive", property("progressive").toBool()); m_consumer->set("rescale", property("rescale").toString().toLatin1().constData()); m_consumer->set("deinterlacer", property("deinterlacer").toString().toLatin1().constData()); m_consumer->set("buffer", qMax(25, qRound(profile().fps()))); m_consumer->set("prefill", 8); m_consumer->set("drop_max", qRound(profile().fps() / 4.0)); if (property("keyer").isValid()) m_consumer->set("keyer", property("keyer").toInt()); m_consumer->set("video_delay", Settings.playerVideoDelayMs()); } if (m_glslManager) { if (!m_threadCreateEvent) m_threadCreateEvent.reset(m_consumer->listen("consumer-thread-create", this, (mlt_listener) onThreadCreate)); if (!m_threadJoinEvent) m_threadJoinEvent.reset(m_consumer->listen("consumer-thread-join", this, (mlt_listener) onThreadJoin)); if (!m_threadStartEvent) m_threadStartEvent.reset(m_consumer->listen("consumer-thread-started", this, (mlt_listener) onThreadStarted)); if (!m_threadStopEvent) m_threadStopEvent.reset(m_consumer->listen("consumer-thread-stopped", this, (mlt_listener) onThreadStopped)); } else { emit started(); } } else { // Cleanup on error error = 2; Controller::closeConsumer(); Controller::close(); } return error; } void VideoWidget::refreshConsumer(bool scrubAudio) { scrubAudio |= isPaused() ? scrubAudio : Settings.playerScrubAudio(); m_scrubAudio |= scrubAudio; m_refreshTimer.start(); } QPoint VideoWidget::offset() const { if (m_zoom == 0.0) { return QPoint(0, 0); } else { return QPoint(m_offset.x() - (MLT.profile().width() * m_zoom - width()) / 2, m_offset.y() - (MLT.profile().height() * m_zoom - height()) / 2); } } QImage VideoWidget::image() const { SharedFrame frame = m_frameRenderer->getDisplayFrame(); if (frame.is_valid()) { const uint8_t *image = frame.get_image(mlt_image_rgba); if (image) { int width = frame.get_image_width(); int height = frame.get_image_height(); QImage temp(image, width, height, QImage::Format_RGBA8888); return temp.copy(); } } return QImage(); } bool VideoWidget::imageIsProxy() const { bool isProxy = false; SharedFrame frame = m_frameRenderer->getDisplayFrame(); if (frame.is_valid()) { Mlt::Producer *frameProducer = frame.get_original_producer(); if (frameProducer && frameProducer->is_valid() && frameProducer->get_int(kIsProxyProperty)) { isProxy = true; } delete frameProducer; } return isProxy; } void VideoWidget::requestImage() const { m_frameRenderer->requestImage(); } void VideoWidget::onFrameDisplayed(const SharedFrame &frame) { m_mutex.lock(); m_sharedFrame = frame; m_mutex.unlock(); bool isVui = frame.get_int(kShotcutVuiMetaProperty); if (!isVui && source() != QmlUtilities::blankVui()) { m_savedQmlSource = source(); setSource(QmlUtilities::blankVui()); } else if (isVui && !m_savedQmlSource.isEmpty() && source() != m_savedQmlSource) { setSource(m_savedQmlSource); } quickWindow()->update(); } void VideoWidget::setGrid(int grid) { m_grid = grid; emit gridChanged(); quickWindow()->update(); } void VideoWidget::setZoom(float zoom) { m_zoom = zoom; emit zoomChanged(); // Reset the VUI control setSource(source()); quickWindow()->update(); } void VideoWidget::setOffsetX(int x) { m_offset.setX(x); emit offsetChanged(); quickWindow()->update(); } void VideoWidget::setOffsetY(int y) { m_offset.setY(y); emit offsetChanged(); quickWindow()->update(); } void VideoWidget::setCurrentFilter(QmlFilter *filter, QmlMetadata *meta) { if (meta && meta->type() == QmlMetadata::Filter && QFile::exists(meta->vuiFilePath().toLocalFile())) { filter->producer().set(kShotcutVuiMetaProperty, 1); rootContext()->setContextProperty("filter", filter); setSource(meta->vuiFilePath()); refreshConsumer(); } else { setBlankScene(); } } void VideoWidget::setSnapToGrid(bool snap) { m_snapToGrid = snap; emit snapToGridChanged(); } // MLT consumer-frame-show event handler void VideoWidget::on_frame_show(mlt_consumer, VideoWidget *widget, mlt_event_data data) { auto frame = Mlt::EventData(data).to_frame(); if (frame.is_valid() && frame.get_int("rendered")) { int timeout = (widget->consumer()->get_int("real_time") > 0) ? 0 : 1000; if (widget->m_frameRenderer && widget->m_frameRenderer->semaphore()->tryAcquire(1, timeout)) { QMetaObject::invokeMethod(widget->m_frameRenderer, "showFrame", Qt::QueuedConnection, Q_ARG(Mlt::Frame, frame)); } else if (!Settings.playerRealtime()) { LOG_WARNING() << "VideoWidget dropped frame" << frame.get_position(); } } } RenderThread::RenderThread(thread_function_t function, void *data) : QThread{nullptr} , m_function{function} , m_data{data} , m_context{new QOpenGLContext} , m_surface{new QOffscreenSurface} { QSurfaceFormat format; format.setProfile(QSurfaceFormat::CoreProfile); format.setMajorVersion(3); format.setMinorVersion(2); format.setDepthBufferSize(0); format.setStencilBufferSize(0); m_context->setFormat(format); m_context->create(); m_context->moveToThread(this); m_surface->setFormat(format); m_surface->create(); } RenderThread::~RenderThread() { m_surface->destroy(); } void RenderThread::run() { Q_ASSERT(m_context->isValid()); m_context->makeCurrent(m_surface.get()); m_function(m_data); m_context->doneCurrent(); } FrameRenderer::FrameRenderer() : QThread(nullptr) , m_semaphore(3) , m_imageRequested(false) { setObjectName("FrameRenderer"); moveToThread(this); start(); } FrameRenderer::~FrameRenderer() { } void FrameRenderer::showFrame(Mlt::Frame frame) { m_displayFrame = SharedFrame(frame); emit frameDisplayed(m_displayFrame); if (m_imageRequested) { m_imageRequested = false; emit imageReady(); } m_semaphore.release(); } void FrameRenderer::requestImage() { m_imageRequested = true; } SharedFrame FrameRenderer::getDisplayFrame() { return m_displayFrame; }
19,687
C++
.cpp
563
28.619893
110
0.635363
mltframework/shotcut
10,796
1,118
50
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
13,124
filtersdock.cpp
mltframework_shotcut/src/docks/filtersdock.cpp
/* * Copyright (c) 2013-2024 Meltytech, LLC * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "filtersdock.h" #include <QQuickView> #include <QQuickItem> #include <QtWidgets/QScrollArea> #include <QQmlEngine> #include <QDir> #include <QUrl> #include <QQmlContext> #include <QAction> #include <QIcon> #include <Logger.h> #include "actions.h" #include "mainwindow.h" #include "controllers/filtercontroller.h" #include "qmltypes/qmlapplication.h" #include "qmltypes/qmlfilter.h" #include "qmltypes/qmlutilities.h" #include "qmltypes/qmlview.h" #include "models/metadatamodel.h" #include "models/motiontrackermodel.h" #include "models/subtitlesmodel.h" #include "models/attachedfiltersmodel.h" #include "mltcontroller.h" FiltersDock::FiltersDock(MetadataModel *metadataModel, AttachedFiltersModel *attachedModel, MotionTrackerModel *motionTrackerModel, SubtitlesModel *subtitlesModel, QWidget *parent) : QDockWidget(tr("Filters"), parent), m_qview(QmlUtilities::sharedEngine(), this) { LOG_DEBUG() << "begin"; setObjectName("FiltersDock"); QIcon filterIcon = QIcon::fromTheme("view-filter", QIcon(":/icons/oxygen/32x32/actions/view-filter.png")); setWindowIcon(filterIcon); toggleViewAction()->setIcon(windowIcon()); setMinimumSize(200, 200); setupActions(); m_qview.setFocusPolicy(Qt::StrongFocus); m_qview.quickWindow()->setPersistentSceneGraph(false); #ifndef Q_OS_MAC m_qview.setAttribute(Qt::WA_AcceptTouchEvents); #endif setWidget(&m_qview); QmlUtilities::setCommonProperties(m_qview.rootContext()); m_qview.rootContext()->setContextProperty("view", new QmlView(&m_qview)); m_qview.rootContext()->setContextProperty("metadatamodel", metadataModel); m_qview.rootContext()->setContextProperty("motionTrackerModel", motionTrackerModel); m_qview.rootContext()->setContextProperty("subtitlesModel", subtitlesModel); m_qview.rootContext()->setContextProperty("attachedfiltersmodel", attachedModel); m_qview.rootContext()->setContextProperty("producer", &m_producer); connect(&m_producer, SIGNAL(seeked(int)), SIGNAL(seeked(int))); connect(this, SIGNAL(producerInChanged(int)), &m_producer, SIGNAL(inChanged(int))); connect(this, SIGNAL(producerOutChanged(int)), &m_producer, SIGNAL(outChanged(int))); connect(m_qview.quickWindow(), &QQuickWindow::sceneGraphInitialized, this, &FiltersDock::load, Qt::QueuedConnection); setCurrentFilter(0, 0, QmlFilter::NoCurrentFilter); LOG_DEBUG() << "end"; } void FiltersDock::setCurrentFilter(QmlFilter *filter, QmlMetadata *meta, int index) { if (filter && filter->producer().is_valid()) { m_producer.setProducer(filter->producer()); if (mlt_service_playlist_type != filter->producer().type() && MLT.producer() && MLT.producer()->is_valid()) m_producer.seek(MLT.producer()->position()); } else { Mlt::Producer emptyProducer(mlt_producer(0)); m_producer.setProducer(emptyProducer); } m_qview.rootContext()->setContextProperty("filter", filter); m_qview.rootContext()->setContextProperty("metadata", meta); if (filter) connect(filter, SIGNAL(changed(QString)), SIGNAL(changed())); else disconnect(this, SIGNAL(changed())); QMetaObject::invokeMethod(m_qview.rootObject(), "setCurrentFilter", Q_ARG(QVariant, QVariant(index))); } bool FiltersDock::event(QEvent *event) { bool result = QDockWidget::event(event); if (event->type() == QEvent::PaletteChange || event->type() == QEvent::StyleChange || event->type() == QEvent::Show) { load(); } return result; } void FiltersDock::keyPressEvent(QKeyEvent *event) { QDockWidget::keyPressEvent(event); if (event->key() == Qt::Key_F) { event->ignore(); } else if (event->key() == Qt::Key_Left || event->key() == Qt::Key_Right) { event->accept(); } } void FiltersDock::onSeeked(int position) { if (m_producer.producer().is_valid()) { if (MLT.isMultitrack()) { // Make the position relative to clip's position on a timeline track. position -= m_producer.producer().get_int(kPlaylistStartProperty); } else { // Make the position relative to the clip's in point. position -= m_producer.in(); } m_producer.seek(position); } } void FiltersDock::onShowFrame(const SharedFrame &frame) { if (m_producer.producer().is_valid()) { int position = frame.get_position(); onSeeked(position); } } void FiltersDock::openFilterMenu() const { QMetaObject::invokeMethod(m_qview.rootObject(), "openFilterMenu"); } void FiltersDock::onServiceInChanged(int delta, Mlt::Service *service) { if (delta && service && m_producer.producer().is_valid() && service->get_service() == m_producer.producer().get_service()) { emit producerInChanged(delta); } } void FiltersDock::load() { if (!m_qview.quickWindow()->isSceneGraphInitialized() && loadTries++ < 5) { LOG_WARNING() << "scene graph not yet initialized"; QTimer::singleShot(300, this, &FiltersDock::load); } LOG_DEBUG() << "begin" << "isVisible" << isVisible() << "qview.status" << m_qview.status(); emit currentFilterRequested(QmlFilter::NoCurrentFilter); QDir viewPath = QmlUtilities::qmlDir(); viewPath.cd("views"); viewPath.cd("filter"); m_qview.engine()->addImportPath(viewPath.path()); QDir modulePath = QmlUtilities::qmlDir(); modulePath.cd("modules"); m_qview.engine()->addImportPath(modulePath.path()); m_qview.setResizeMode(QQuickWidget::SizeRootObjectToView); m_qview.quickWindow()->setColor(palette().window().color()); QUrl source = QUrl::fromLocalFile(viewPath.absoluteFilePath("filterview.qml")); m_qview.setSource(source); QObject::connect(m_qview.rootObject(), SIGNAL(currentFilterRequested(int)), SIGNAL(currentFilterRequested(int))); } void FiltersDock::setupActions() { QIcon icon; QAction *action; action = new QAction(tr("Add"), this); action->setShortcut(QKeySequence(Qt::Key_F)); action->setToolTip(tr("Choose a filter to add")); icon = QIcon::fromTheme("list-add", QIcon(":/icons/oxygen/32x32/actions/list-add.png")); action->setIcon(icon); connect(action, &QAction::triggered, this, [ = ]() { show(); raise(); m_qview.setFocus(); openFilterMenu(); }); addAction(action); Actions.add("filtersAddFilterAction", action, windowTitle()); action = new QAction(tr("Remove"), this); action->setShortcut(QKeySequence(Qt::SHIFT | Qt::Key_F)); action->setToolTip(tr("Remove selected filter")); icon = QIcon::fromTheme("list-remove", QIcon(":/icons/oxygen/32x32/actions/list-remove.png")); action->setIcon(icon); connect(action, &QAction::triggered, this, [ = ]() { MAIN.filterController()->removeCurrent(); }); addAction(action); Actions.add("filtersRemoveFilterAction", action, windowTitle()); action = new QAction(tr("Copy Filters"), this); action->setToolTip(tr("Copy checked filters to the clipboard")); icon = QIcon::fromTheme("edit-copy", QIcon(":/icons/oxygen/32x32/actions/edit-copy.png")); action->setIcon(icon); connect(action, &QAction::triggered, this, [ = ]() { QmlApplication::singleton().copyFilters(); }); addAction(action); Actions.add("filtersCopyFiltersAction", action, windowTitle()); action = new QAction(tr("Paste Filters"), this); action->setToolTip(tr("Paste the filters from the clipboard")); icon = QIcon::fromTheme("edit-paste", QIcon(":/icons/oxygen/32x32/actions/edit-paste.png")); action->setIcon(icon); connect(action, &QAction::triggered, this, [ = ]() { QmlApplication::singleton().pasteFilters(); }); addAction(action); Actions.add("filtersPasteFiltersAction", action, windowTitle()); }
8,889
C++
.cpp
215
35.423256
98
0.673451
mltframework/shotcut
10,796
1,118
50
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
13,125
jobsdock.cpp
mltframework_shotcut/src/docks/jobsdock.cpp
/* * Copyright (c) 2012-2024 Meltytech, LLC * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "jobsdock.h" #include "ui_jobsdock.h" #include "jobqueue.h" #include <QtWidgets> #include <Logger.h> #include "dialogs/textviewerdialog.h" JobsDock::JobsDock(QWidget *parent) : QDockWidget(parent), ui(new Ui::JobsDock) { LOG_DEBUG() << "begin"; ui->setupUi(this); toggleViewAction()->setIcon(windowIcon()); ui->treeView->setModel(&JOBS); QHeaderView *header = ui->treeView->header(); header->setStretchLastSection(false); header->setSectionResizeMode(JobQueue::COLUMN_ICON, QHeaderView::Fixed); ui->treeView->setColumnWidth(JobQueue::COLUMN_ICON, 24); header->setSectionResizeMode(JobQueue::COLUMN_OUTPUT, QHeaderView::Stretch); header->setSectionResizeMode(JobQueue::COLUMN_STATUS, QHeaderView::ResizeToContents); ui->cleanButton->hide(); LOG_DEBUG() << "end"; } JobsDock::~JobsDock() { JOBS.cleanup(); delete ui; } AbstractJob *JobsDock::currentJob() const { QModelIndex index = ui->treeView->currentIndex(); if (!index.isValid()) return 0; return JOBS.jobFromIndex(index); } void JobsDock::onJobAdded() { QModelIndex index = JOBS.index(JOBS.rowCount() - 1, JobQueue::COLUMN_OUTPUT); QProgressBar *progressBar = new QProgressBar; progressBar->setMinimum(0); progressBar->setMaximum(100); progressBar->setAutoFillBackground(true); progressBar->setTextVisible(false); QHBoxLayout *layout = new QHBoxLayout(progressBar); QLabel *label = new QLabel; layout->addWidget(label); layout->setContentsMargins(0, 0, 0, 0); ui->treeView->setIndexWidget(index, progressBar); ui->treeView->resizeColumnToContents(JobQueue::COLUMN_STATUS); label->setToolTip(JOBS.data(index).toString()); label->setText(label->fontMetrics().elidedText( JOBS.data(index).toString(), Qt::ElideMiddle, ui->treeView->columnWidth(JobQueue::COLUMN_OUTPUT))); connect(JOBS.jobFromIndex(index), SIGNAL(progressUpdated(QStandardItem *, int)), SLOT(onProgressUpdated(QStandardItem *, int))); show(); raise(); } void JobsDock::onProgressUpdated(QStandardItem *item, int percent) { if (item) { QModelIndex index = JOBS.index(item->row(), JobQueue::COLUMN_OUTPUT); QProgressBar *progressBar = qobject_cast<QProgressBar *>(ui->treeView->indexWidget(index)); if (progressBar && percent > 0) progressBar->setValue(percent); } } void JobsDock::resizeEvent(QResizeEvent *event) { QDockWidget::resizeEvent(event); foreach (QLabel *label, ui->treeView->findChildren<QLabel *>()) { label->setText(label->fontMetrics().elidedText( label->toolTip(), Qt::ElideMiddle, ui->treeView->columnWidth(JobQueue::COLUMN_OUTPUT))); } } void JobsDock::on_treeView_customContextMenuRequested(const QPoint &pos) { QModelIndex index = ui->treeView->currentIndex(); QMenu menu(this); AbstractJob *job = index.isValid() ? JOBS.jobFromIndex(index) : nullptr; if (job) { if (job->ran() && job->state() == QProcess::NotRunning && job->exitStatus() == QProcess::NormalExit) { menu.addActions(job->successActions()); } if (job->stopped() || (JOBS.isPaused() && !job->ran())) menu.addAction(ui->actionRun); if (job->state() == QProcess::Running) menu.addAction(ui->actionStopJob); else menu.addAction(ui->actionRemove); if (job->ran()) menu.addAction(ui->actionViewLog); menu.addActions(job->standardActions()); } for (auto job : JOBS.jobs()) { if (job->ran() && job->state() != QProcess::Running) { menu.addAction(ui->actionRemoveFinished); break; } } menu.exec(mapToGlobal(pos)); } void JobsDock::on_actionStopJob_triggered() { QModelIndex index = ui->treeView->currentIndex(); if (!index.isValid()) return; AbstractJob *job = JOBS.jobFromIndex(index); if (job) job->stop(); } void JobsDock::on_actionViewLog_triggered() { QModelIndex index = ui->treeView->currentIndex(); if (!index.isValid()) return; AbstractJob *job = JOBS.jobFromIndex(index); if (job) { TextViewerDialog dialog(this); dialog.setWindowTitle(tr("Job Log")); dialog.setText(job->log()); auto connection = connect(job, &AbstractJob::progressUpdated, this, [&]() { dialog.setText(job->log(), true); }); dialog.exec(); disconnect(connection); } } void JobsDock::on_pauseButton_toggled(bool checked) { if (checked) JOBS.pause(); else JOBS.resume(); } void JobsDock::on_actionRun_triggered() { QModelIndex index = ui->treeView->currentIndex(); if (!index.isValid()) return; AbstractJob *job = JOBS.jobFromIndex(index); if (job) job->start(); } void JobsDock::on_menuButton_clicked() { on_treeView_customContextMenuRequested(ui->menuButton->mapToParent(QPoint(0, 0))); } void JobsDock::on_treeView_doubleClicked(const QModelIndex &index) { AbstractJob *job = JOBS.jobFromIndex(index); if (job && job->ran() && job->state() == QProcess::NotRunning && job->exitStatus() == QProcess::NormalExit) { foreach (QAction *action, job->successActions()) { if (action->data() == "Open") { action->trigger(); break; } } } } void JobsDock::on_actionRemove_triggered() { QModelIndex index = ui->treeView->currentIndex(); if (!index.isValid()) return; JOBS.remove(index); } void JobsDock::on_actionRemoveFinished_triggered() { JOBS.removeFinished(); } void JobsDock::on_JobsDock_visibilityChanged(bool visible) { if (visible) { foreach (QLabel *label, ui->treeView->findChildren<QLabel *>()) { label->setText(label->fontMetrics().elidedText( label->toolTip(), Qt::ElideMiddle, ui->treeView->columnWidth(JobQueue::COLUMN_OUTPUT))); } } }
6,737
C++
.cpp
190
30.068421
122
0.667637
mltframework/shotcut
10,796
1,118
50
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
13,126
scopedock.cpp
mltframework_shotcut/src/docks/scopedock.cpp
/* * Copyright (c) 2015-2023 Meltytech, LLC * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "scopedock.h" #include "controllers/scopecontroller.h" #include "mltcontroller.h" #include <Logger.h> #include <QtWidgets/QScrollArea> #include <QAction> ScopeDock::ScopeDock(ScopeController *scopeController, ScopeWidget *scopeWidget) : QDockWidget() , m_scopeController(scopeController) , m_scopeWidget(scopeWidget) { LOG_DEBUG() << "begin"; setObjectName(m_scopeWidget->objectName() + "Dock"); QScrollArea *scrollArea = new QScrollArea(); scrollArea->setFrameShape(QFrame::NoFrame); scrollArea->setWidgetResizable(true); scrollArea->setWidget(m_scopeWidget); QDockWidget::setWidget(scrollArea); QDockWidget::setWindowTitle(m_scopeWidget->getTitle()); connect(toggleViewAction(), SIGNAL(toggled(bool)), this, SLOT(onActionToggled(bool))); connect(this, &QDockWidget::dockLocationChanged, m_scopeWidget, &ScopeWidget::moved); LOG_DEBUG() << "end"; } void ScopeDock::resizeEvent(QResizeEvent *e) { if (width() > height()) { m_scopeWidget->setOrientation(Qt::Horizontal); } else { m_scopeWidget->setOrientation(Qt::Vertical); } QDockWidget::resizeEvent(e); } void ScopeDock::onActionToggled(bool checked) { if (checked) { connect(m_scopeController, SIGNAL(newFrame(const SharedFrame &)), m_scopeWidget, SLOT(onNewFrame(const SharedFrame &))); MLT.refreshConsumer(); } else { disconnect(m_scopeController, SIGNAL(newFrame(const SharedFrame &)), m_scopeWidget, SLOT(onNewFrame(const SharedFrame &))); } }
2,274
C++
.cpp
59
34.474576
91
0.724638
mltframework/shotcut
10,796
1,118
50
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
13,127
subtitlesdock.cpp
mltframework_shotcut/src/docks/subtitlesdock.cpp
/* * Copyright (c) 2024 Meltytech, LLC * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "subtitlesdock.h" #include "actions.h" #include "mainwindow.h" #include "settings.h" #include "shotcut_mlt_properties.h" #include "util.h" #include "dialogs/subtitletrackdialog.h" #include "dialogs/transcribeaudiodialog.h" #include "jobqueue.h" #include "jobs/meltjob.h" #include "jobs/whisperjob.h" #include "models/subtitlesmodel.h" #include "models/subtitlesselectionmodel.h" #include "widgets/docktoolbar.h" #include "qmltypes/qmlapplication.h" #include <Logger.h> #include "MltPlaylist.h" #include <QAction> #include <QApplication> #include <QComboBox> #include <QGridLayout> #include <QHBoxLayout> #include <QHeaderView> #include <QIcon> #include <QItemSelection> #include <QItemSelectionModel> #include <QLabel> #include <QMenu> #include <QMessageBox> #include <QProcess> #include <QStandardPaths> #include <QTextDocumentFragment> #include <QTextEdit> #include <QTreeView> #include <QToolButton> #include <QVBoxLayout> #include <QtWidgets/QScrollArea> #define DEFAULT_ITEM_DURATION (2 * 1000) static int64_t positionToMs(mlt_position position) { return position * 1000 * MLT.profile().frame_rate_den() / MLT.profile().frame_rate_num(); } static mlt_position msToPosition(int64_t ms) { return ms * MLT.profile().frame_rate_num() / MLT.profile().frame_rate_den() / 1000; } static QList<Subtitles::SubtitleItem> readSrtFile(const QString &path, int64_t timeOffset, bool includeNonspoken) { QList<Subtitles::SubtitleItem> items; // Read the subtitles Subtitles::SubtitleVector srtItems = Subtitles::readFromSrtFile(path.toUtf8().toStdString()); if (srtItems.size() == 0) { return items; } // Convert the items to the return list Subtitles::SubtitleItem item; for (int i = 0; i < srtItems.size(); i++) { // Clean up the lines QStringList lines = QString::fromStdString(srtItems[i].text).split('\n'); QString text; for (int i = 0; i < lines.size(); i++) { // Remove HTML QString line = QTextDocumentFragment::fromHtml(lines[i]).toPlainText(); // Remove unnecessary space line = line.simplified(); // Remove leading "-" if (line.startsWith("-")) { line = line.remove(0, 1).simplified(); } // Remove unspoken sounds if requested if (!includeNonspoken && ((line.startsWith("[") && line.endsWith("]")) || (line.startsWith("(") && line.endsWith(")")))) { continue; } if (i != 0) { text += "\n"; } text += line; } text = text.trimmed(); if (!text.isEmpty()) { // Shift the subtitles to the position item.start = srtItems[i].start + timeOffset; item.end = srtItems[i].end + timeOffset; item.text = text.toUtf8().toStdString(); items.append(item); } } return items; } SubtitlesDock::SubtitlesDock(QWidget *parent) : QDockWidget(parent) , m_model(nullptr) , m_pos(-1) , m_textEditInProgress(false) { LOG_DEBUG() << "begin"; setObjectName("SubtitlesDock"); QDockWidget::setWindowTitle(tr("Subtitles")); QIcon filterIcon = QIcon::fromTheme("subtitle", QIcon(":/icons/oxygen/32x32/actions/subtitle.png")); setWindowIcon(filterIcon); toggleViewAction()->setIcon(windowIcon()); setupActions(); QScrollArea *scrollArea = new QScrollArea(); scrollArea->setFrameShape(QFrame::NoFrame); scrollArea->setWidgetResizable(true); QDockWidget::setWidget(scrollArea); QVBoxLayout *vboxLayout = new QVBoxLayout(); scrollArea->setLayout(vboxLayout); m_addToTimelineLabel = new QLabel(tr("Add clips to the Timeline to begin editing subtitles.")); vboxLayout->addWidget(m_addToTimelineLabel); QHBoxLayout *tracksLayout = new QHBoxLayout(); m_trackCombo = new QComboBox(); connect(m_trackCombo, &QComboBox::currentIndexChanged, this, [&](int trackIndex) { if (m_selectionModel) { m_selectionModel->setSelectedTrack(trackIndex); selectItemForTime(); } }); tracksLayout->addWidget(m_trackCombo); QToolButton *addTrackButton = new QToolButton(this); addTrackButton->setDefaultAction(Actions["subtitleAddTrackAction"]); addTrackButton->setAutoRaise(true); tracksLayout->addWidget(addTrackButton); QToolButton *removeTrackButton = new QToolButton(this); removeTrackButton->setDefaultAction(Actions["subtitleRemoveTrackAction"]); removeTrackButton->setAutoRaise(true); tracksLayout->addWidget(removeTrackButton); QToolButton *editTrackButton = new QToolButton(this); editTrackButton->setDefaultAction(Actions["subtitleEditTrackAction"]); editTrackButton->setAutoRaise(true); tracksLayout->addWidget(editTrackButton); vboxLayout->addLayout(tracksLayout); m_treeView = new QTreeView(); vboxLayout->addWidget(m_treeView, 1); QMenu *mainMenu = new QMenu("Subtitles", this); QMenu *trackMenu = new QMenu("Tracks", this); trackMenu->addAction(Actions["subtitleAddTrackAction"]); trackMenu->addAction(Actions["subtitleRemoveTrackAction"]); trackMenu->addAction(Actions["subtitleEditTrackAction"]); mainMenu->addMenu(trackMenu); mainMenu->addAction(Actions["SubtitleImportAction"]); mainMenu->addAction(Actions["SubtitleExportAction"]); mainMenu->addAction(Actions["subtitleCreateEditItemAction"]); mainMenu->addAction(Actions["subtitleAddItemAction"]); mainMenu->addAction(Actions["subtitleRemoveItemAction"]); mainMenu->addAction(Actions["subtitleSetStartAction"]); mainMenu->addAction(Actions["subtitleSetEndAction"]); mainMenu->addAction(Actions["subtitleMoveAction"]); mainMenu->addAction(Actions["subtitleBurnInAction"]); mainMenu->addAction(Actions["subtitleGenerateTextAction"]); mainMenu->addAction(Actions["subtitleSpeechToTextAction"]); mainMenu->addAction(Actions["subtitleTrackTimelineAction"]); mainMenu->addAction(Actions["subtitleShowPrevNextAction"]); QAction *action; QMenu *columnsMenu = new QMenu(tr("Columns"), this); action = columnsMenu->addAction(tr("Columns")); action->setEnabled(false); action = columnsMenu->addAction(tr("Start"), this, SLOT(onStartColumnToggled(bool))); action->setCheckable(true); action->setChecked(Settings.subtitlesShowColumn("start")); action = columnsMenu->addAction(tr("End"), this, SLOT(onEndColumnToggled(bool))); action->setCheckable(true); action->setChecked(Settings.subtitlesShowColumn("end")); action = columnsMenu->addAction(tr("Duration"), this, SLOT(onDurationColumnToggled(bool))); action->setCheckable(true); action->setChecked(Settings.subtitlesShowColumn("duration")); mainMenu->addMenu(columnsMenu); Actions.loadFromMenu(columnsMenu); DockToolBar *toolbar = new DockToolBar(tr("Subtitle Controls")); toolbar->setAreaHint(Qt::BottomToolBarArea); auto button = new QToolButton; button->setIcon(QIcon::fromTheme("show-menu", QIcon(":/icons/oxygen/32x32/actions/show-menu.png"))); button->setToolTip(tr("Subtitles Menu")); button->setAutoRaise(true); button->setMenu(mainMenu); button->setPopupMode(QToolButton::QToolButton::InstantPopup); toolbar->addWidget(button); button = new QToolButton; button->setDefaultAction(Actions["SubtitleImportAction"]); button->setAutoRaise(true); toolbar->addWidget(button); button = new QToolButton; button->setDefaultAction(Actions["subtitleAddItemAction"]); button->setAutoRaise(true); toolbar->addWidget(button); button = new QToolButton; button->setDefaultAction(Actions["subtitleRemoveItemAction"]); button->setAutoRaise(true); toolbar->addWidget(button); button = new QToolButton; button->setDefaultAction(Actions["subtitleSetStartAction"]); button->setAutoRaise(true); toolbar->addWidget(button); button = new QToolButton; button->setDefaultAction(Actions["subtitleSetEndAction"]); button->setAutoRaise(true); toolbar->addWidget(button); button = new QToolButton; button->setDefaultAction(Actions["subtitleMoveAction"]); button->setAutoRaise(true); toolbar->addWidget(button); button = new QToolButton; button->setDefaultAction(Actions["subtitleBurnInAction"]); button->setAutoRaise(true); toolbar->addWidget(button); button = new QToolButton; button->setDefaultAction(Actions["subtitleSpeechToTextAction"]); button->setAutoRaise(true); toolbar->addWidget(button); vboxLayout->addWidget(toolbar); QFontMetrics fm(font()); int textHeight = fm.lineSpacing() * 4 + 10; QGridLayout *textLayout = new QGridLayout(); m_prevLabel = new QLabel(tr("Previous")); textLayout->addWidget(m_prevLabel, 0, 0); m_textLabel = new QLabel(tr("Current")); textLayout->addWidget(m_textLabel, 0, 1); m_nextLabel = new QLabel(tr("Next")); textLayout->addWidget(m_nextLabel, 0, 2); m_prev = new QTextEdit(this); m_prev->setMaximumHeight(textHeight); m_prev->setReadOnly(true); m_prev->setLineWrapMode(QTextEdit::NoWrap); textLayout->addWidget(m_prev, 1, 0); m_text = new QTextEdit(this); m_text->setMaximumHeight(textHeight); m_text->setReadOnly(true); m_text->setTabChangesFocus(true); m_text->setLineWrapMode(QTextEdit::NoWrap); connect(m_text, &QTextEdit::textChanged, this, &SubtitlesDock::onTextEdited); textLayout->addWidget(m_text, 1, 1); m_next = new QTextEdit(this); m_next->setMaximumHeight(textHeight); m_next->setReadOnly(true); m_next->setLineWrapMode(QTextEdit::NoWrap); textLayout->addWidget(m_next, 1, 2); vboxLayout->addLayout(textLayout); vboxLayout->addStretch(); LOG_DEBUG() << "end"; } SubtitlesDock::~SubtitlesDock() { } void SubtitlesDock::setupActions() { QAction *action; action = new QAction(tr("Add Subtitle Track"), this); action->setIcon(QIcon::fromTheme("list-add", QIcon(":/icons/oxygen/32x32/actions/list-add.png"))); action->setToolTip(tr("Add a subtitle track")); connect(action, &QAction::triggered, this, [&]() { show(); raise(); addSubtitleTrack(); }); Actions.add("subtitleAddTrackAction", action); action = new QAction(tr("Remove Subtitle Track"), this); action->setIcon(QIcon::fromTheme("list-remove", QIcon(":/icons/oxygen/32x32/actions/list-remove.png"))); action->setToolTip(tr("Remove this subtitle track")); connect(action, &QAction::triggered, this, [&]() { show(); raise(); removeSubtitleTrack(); }); Actions.add("subtitleRemoveTrackAction", action); action = new QAction(tr("Edit Subtitle Track"), this); action->setIcon(QIcon::fromTheme("document-edit", QIcon(":/icons/oxygen/32x32/actions/document-edit.png"))); action->setToolTip(tr("Edit this subtitle track")); connect(action, &QAction::triggered, this, [&]() { show(); raise(); editSubtitleTrack(); }); Actions.add("subtitleEditTrackAction", action); action = new QAction(tr("Import Subtitles From File"), this); action->setIcon(QIcon::fromTheme("document-import", QIcon(":/icons/oxygen/32x32/actions/document-import.png"))); action->setToolTip(tr("Import subtitles from an srt file at the current position")); connect(action, &QAction::triggered, this, [&]() { show(); raise(); importSubtitles(); }); Actions.add("SubtitleImportAction", action); action = new QAction(tr("Export Subtitles To File"), this); action->setIcon(QIcon::fromTheme("document-export", QIcon(":/icons/oxygen/32x32/actions/document-export.png"))); action->setToolTip(tr("Export the current subtitle track to an SRT file")); connect(action, &QAction::triggered, this, [&]() { show(); raise(); exportSubtitles(); }); Actions.add("SubtitleExportAction", action); action = new QAction(tr("Create/Edit Subtitle"), this); action->setShortcut(QKeySequence(Qt::SHIFT | Qt::Key_Q)); action->setIcon(QIcon::fromTheme("subtitle", QIcon(":/icons/oxygen/32x32/actions/subtitle.png"))); action->setToolTip(tr("Create or Edit a subtitle at the cursor position.")); connect(action, &QAction::triggered, this, &SubtitlesDock::onCreateOrEditRequested); Actions.add("subtitleCreateEditItemAction", action, windowTitle()); action = new QAction(tr("Add Subtitle Item"), this); action->setShortcut(QKeySequence(Qt::SHIFT | Qt::Key_W)); action->setIcon(QIcon::fromTheme("list-add", QIcon(":/icons/oxygen/32x32/actions/list-add.png"))); action->setToolTip(tr("Add a subtitle at the cursor position")); connect(action, &QAction::triggered, this, &SubtitlesDock::onAddRequested); Actions.add("subtitleAddItemAction", action, windowTitle()); action = new QAction(tr("Remove Subtitle Item"), this); action->setShortcut(QKeySequence(Qt::SHIFT | Qt::Key_E)); action->setIcon(QIcon::fromTheme("list-remove", QIcon(":/icons/oxygen/32x32/actions/list-remove.png"))); action->setToolTip(tr("Remove the selected subtitle item")); connect(action, &QAction::triggered, this, &SubtitlesDock::onRemoveRequested); Actions.add("subtitleRemoveItemAction", action, windowTitle()); action = new QAction(tr("Set Subtitle Start"), this); action->setShortcut(QKeySequence(Qt::SHIFT | Qt::Key_R)); action->setIcon(QIcon::fromTheme("keyframes-filter-in", QIcon(":/icons/oxygen/32x32/actions/keyframes-filter-in.png"))); action->setToolTip(tr("Set the selected subtitle to start at the cursor position")); connect(action, &QAction::triggered, this, &SubtitlesDock::onSetStartRequested); Actions.add("subtitleSetStartAction", action, windowTitle()); action = new QAction(tr("Set Subtitle End"), this); action->setShortcut(QKeySequence(Qt::SHIFT | Qt::Key_T)); action->setIcon(QIcon::fromTheme("keyframes-filter-out", QIcon(":/icons/oxygen/32x32/actions/keyframes-filter-out.png"))); action->setToolTip(tr("Set the selected subtitle to end at the cursor position")); connect(action, &QAction::triggered, this, &SubtitlesDock::onSetEndRequested); Actions.add("subtitleSetEndAction", action, windowTitle()); action = new QAction(tr("Move Subtitles"), this); action->setShortcut(QKeySequence(Qt::SHIFT | Qt::Key_Y)); action->setIcon(QIcon::fromTheme("4-direction", QIcon(":/icons/oxygen/32x32/actions/4-direction.png"))); action->setToolTip(tr("Move the selected subtitles to the cursor position")); connect(action, &QAction::triggered, this, &SubtitlesDock::onMoveRequested); Actions.add("subtitleMoveAction", action, windowTitle()); action = new QAction(tr("Burn In Subtitles on Output"), this); action->setToolTip( tr("Create or edit a Burn In Subtitles filter on the timeline output.")); action->setIcon(QIcon::fromTheme("font", QIcon(":/icons/oxygen/32x32/actions/font.png"))); connect(action, &QAction::triggered, this, &SubtitlesDock::burnInOnTimeline); Actions.add("subtitleBurnInAction", action, windowTitle()); action = new QAction(tr("Generate Text on Timeline"), this); action->setToolTip( tr("Create a new video track on the timeline with text showing these subtitles.")); connect(action, &QAction::triggered, this, &SubtitlesDock::generateTextOnTimeline); Actions.add("subtitleGenerateTextAction", action, windowTitle()); action = new QAction(tr("Speech to Text..."), this); action->setToolTip( tr("Detect speech and transcribe to a new subtitle track.")); action->setIcon(QIcon::fromTheme("speech-to-text", QIcon(":/icons/oxygen/32x32/actions/speech-to-text.png"))); connect(action, &QAction::triggered, this, &SubtitlesDock::speechToText); Actions.add("subtitleSpeechToTextAction", action, windowTitle()); action = new QAction(tr("Track Timeline Cursor"), this); action->setToolTip(tr("Track the timeline cursor")); action->setCheckable(true); action->setChecked(Settings.subtitlesTrackTimeline()); connect(action, &QAction::toggled, this, [&](bool checked) { Settings.setSubtitlesTrackTimeline(checked); }); Actions.add("subtitleTrackTimelineAction", action, windowTitle()); action = new QAction(tr("Show Previous/Next"), this); action->setToolTip(tr("Show the previous and next subtitles")); action->setCheckable(true); action->setChecked(Settings.subtitlesShowPrevNext()); connect(action, &QAction::toggled, this, [&](bool checked) { Settings.setSubtitlesShowPrevNext(checked); resizeTextWidgets(); }); Actions.add("subtitleShowPrevNextAction", action, windowTitle()); } void SubtitlesDock::setModel(SubtitlesModel *model, SubtitlesSelectionModel *selectionModel) { m_model = model; m_selectionModel = selectionModel; m_treeView->setModel(m_model); m_treeView->setSelectionModel(m_selectionModel); m_treeView->header()->setStretchLastSection(false); m_treeView->header()->setSectionResizeMode(0, QHeaderView::Stretch); m_treeView->setSelectionMode(QAbstractItemView::ContiguousSelection); m_treeView->setSelectionBehavior(QAbstractItemView::SelectRows); m_treeView->setColumnHidden(2, !Settings.subtitlesShowColumn("start")); m_treeView->setColumnHidden(3, !Settings.subtitlesShowColumn("end")); m_treeView->setColumnHidden(4, !Settings.subtitlesShowColumn("duration")); connect(m_selectionModel, &QItemSelectionModel::currentChanged, this, &SubtitlesDock::refreshWidgets); connect(m_selectionModel, &SubtitlesSelectionModel::selectedTrackModelIndexChanged, m_treeView, &QTreeView::setRootIndex); connect(m_treeView, &QTreeView::doubleClicked, this, &SubtitlesDock::onItemDoubleClicked); connect(m_model, &QAbstractItemModel::modelReset, this, &SubtitlesDock::onModelReset); connect(m_model, &SubtitlesModel::tracksChanged, this, &SubtitlesDock::refreshTracksCombo); connect(m_model, &QAbstractItemModel::dataChanged, this, &SubtitlesDock::refreshWidgets); connect(m_model, &QAbstractItemModel::rowsInserted, this, &SubtitlesDock::refreshWidgets); connect(m_model, &QAbstractItemModel::rowsMoved, this, &SubtitlesDock::refreshWidgets); connect(m_model, &QAbstractItemModel::rowsRemoved, this, [&](const QModelIndex & parent, int first, int last) { if (parent.isValid()) { refreshWidgets(); } }); refreshTracksCombo(); refreshWidgets(); } void SubtitlesDock::importSrtFromFile(const QString &srtPath, const QString &trackName, const QString &lang, bool includeNonspoken) { QList<Subtitles::SubtitleItem> items = readSrtFile(srtPath, 0, includeNonspoken); if (items.size() == 0) { MAIN.showStatusMessage(QObject::tr("No subtitles found to import")); return; } SubtitlesModel::SubtitleTrack track; track.name = trackName; track.lang = lang; m_model->importSubtitlesToNewTrack(track, items); MAIN.showStatusMessage(QObject::tr("Imported %1 subtitle items").arg(items.size())); } void SubtitlesDock::addSubtitleTrack() { int newIndex = m_model->trackCount(); if (!MAIN.isMultitrackValid()) { MAIN.showStatusMessage(tr("Add a clip to the timeline to create subtitles.")); return; } QString currentLangCode = QLocale::languageToCode(QLocale::system().language(), QLocale::ISO639Part2); SubtitleTrackDialog dialog(availableTrackName(), currentLangCode, this); if (dialog.exec() == QDialog::Accepted) { SubtitlesModel::SubtitleTrack track; track.name = dialog.getName(); track.lang = dialog.getLanguage(); if (trackNameExists(track.name)) { MAIN.showStatusMessage(tr("Subtitle track already exists: %1").arg(track.name)); return; } m_model->addTrack(track); } m_trackCombo->setCurrentIndex(newIndex); } void SubtitlesDock::removeSubtitleTrack() { QString name = m_trackCombo->currentData().toString(); if (!name.isEmpty()) { Mlt::Producer *multitrack = MAIN.multitrack(); if (multitrack && multitrack->is_valid()) { for (int i = 0; i < multitrack->filter_count(); i++) { QScopedPointer<Mlt::Filter> filter(multitrack->filter(i)); if (!filter || !filter->is_valid() || filter->get("mlt_service") != QStringLiteral("subtitle")) { continue; } if (name == filter->get("feed")) { QMessageBox::warning(this, tr("Remove Subtitle Track"), tr("This track is in use by a subtitle filter.\n" "Remove the subtitle filter before removing this track.")); return; } } } m_model->removeTrack(name); } } void SubtitlesDock::editSubtitleTrack() { if (m_model->trackCount() == 0) { addSubtitleTrack(); return; } int currentIndex = m_selectionModel->selectedTrack(); SubtitlesModel::SubtitleTrack track = m_model->getTrack(currentIndex); SubtitleTrackDialog dialog(track.name, track.lang, this); if (dialog.exec() == QDialog::Accepted) { QList<SubtitlesModel::SubtitleTrack> tracks = m_model->getTracks(); for (int t = 0; t < tracks.count(); t++) { if (t == currentIndex) { if (dialog.getName() == track.name && dialog.getLanguage() == track.lang) { // Nothing changed return; } } else { if (dialog.getName() == track.name) { MAIN.showStatusMessage(tr("Subtitle track already exists: %1").arg(track.name)); return; } } } track.name = dialog.getName(); track.lang = dialog.getLanguage(); m_model->editTrack(currentIndex, track); } m_trackCombo->setCurrentIndex(currentIndex); } void SubtitlesDock::importSubtitles() { // Get the file name from the user. QString subtitlePath = QFileDialog::getOpenFileName(&MAIN, tr("Import Subtitle File"), Settings.openPath(), tr("Subtitle Files (*.srt *.SRT *.vtt *.VTT *.ass *.ASS *.ssa *.SSA)"), nullptr, Util::getFileDialogOptions()); if (subtitlePath.isEmpty()) { return; } QFileInfo subtitleFi(subtitlePath); if (!subtitleFi.exists()) { MAIN.showStatusMessage(tr("Unable to find subtitle file.")); return; } MAIN.showStatusMessage(QObject::tr("Importing subtitles...")); // Convert the subtitles to SRT using FFMpeg QString tmpLocation = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation) + "/"; QScopedPointer<QTemporaryFile> tmp(Util::writableTemporaryFile(tmpLocation, "XXXXXX.srt")); tmp->open(); QString tmpFileName = tmp->fileName(); tmp->close(); QProcess proc; QFileInfo ffmpegPath(qApp->applicationDirPath(), "ffmpeg"); QStringList args; args << "-y" << "-hide_banner" << "-i" << subtitleFi.absoluteFilePath() << tmpFileName; LOG_INFO() << ffmpegPath.absoluteFilePath() << args; MAIN.showStatusMessage(QObject::tr("Importing subtitles...")); proc.setStandardOutputFile(QProcess::nullDevice()); proc.setReadChannel(QProcess::StandardError); proc.start(ffmpegPath.absoluteFilePath(), args, QIODevice::ReadOnly); QCoreApplication::processEvents(); if (!proc.waitForFinished(8000) || proc.exitStatus() != QProcess::NormalExit || proc.exitCode()) { QString output = proc.readAll(); foreach (const QString &line, output.split(QRegularExpression("[\r\n]"), Qt::SkipEmptyParts)) LOG_INFO() << line; } // Read the subtitles int64_t msTime = positionToMs(m_pos); QList<Subtitles::SubtitleItem> items = readSrtFile(tmpFileName, msTime, true); if (items.size() == 0) { MAIN.showStatusMessage(QObject::tr("No subtitles found to import")); return; } ensureTrackExists(); m_model->importSubtitles(m_trackCombo->currentIndex(), msTime, items); MAIN.showStatusMessage(QObject::tr("Imported %1 subtitle items").arg(items.size())); } void SubtitlesDock::exportSubtitles() { auto track = m_model->getTrack(m_trackCombo->currentIndex()); QString suggestedPath = QStringLiteral("%1/%2.srt").arg(Settings.savePath()).arg(track.name); QString srtPath = QFileDialog::getSaveFileName(&MAIN, tr("Export SRT File"), suggestedPath, tr("SRT Files (*.srt *.SRT)"), nullptr, Util::getFileDialogOptions()); if (srtPath.isEmpty()) { return; } m_model->exportSubtitles(srtPath, m_trackCombo->currentIndex()); Settings.setSavePath(srtPath); } void SubtitlesDock::onPositionChanged(int position) { if (position == m_pos) { return; } m_pos = position; if (Actions["subtitleTrackTimelineAction"]->isChecked()) { selectItemForTime(); } } void SubtitlesDock::refreshTracksCombo() { if (m_model) { QList<SubtitlesModel::SubtitleTrack> tracks = m_model->getTracks(); m_trackCombo->clear(); for (auto &track : tracks) { m_trackCombo->addItem(QStringLiteral("%1 (%2)").arg(track.name).arg(track.lang), track.name); } if (tracks.size() > 0) { m_trackCombo->setCurrentIndex(0); m_selectionModel->setSelectedTrack(0); } else { m_trackCombo->setCurrentIndex(-1); m_selectionModel->setSelectedTrack(-1); } selectItemForTime(); } } void SubtitlesDock::onCreateOrEditRequested() { LOG_DEBUG(); ensureTrackExists(); int64_t msTime = positionToMs(m_pos); int trackIndex = m_trackCombo->currentIndex(); int currentItemIndex = m_model->itemIndexAtTime(trackIndex, msTime); if (currentItemIndex >= 0) { setCurrentItem(trackIndex, currentItemIndex); m_text->setFocus(); m_text->selectAll(); } else { onAddRequested(); } } void SubtitlesDock::onAddRequested() { LOG_DEBUG(); ensureTrackExists(); int64_t msTime = positionToMs(m_pos); int trackIndex = m_trackCombo->currentIndex(); if (m_model->itemIndexAtTime(trackIndex, msTime) >= 0) { MAIN.showStatusMessage(tr("A subtitle already exists at this time.")); return; } int64_t maxTime = m_model->maxTime(); int nextIndex = m_model->itemIndexAfterTime(trackIndex, msTime); if (nextIndex > -1) { auto nextItem = m_model->getItem(trackIndex, nextIndex); maxTime = nextItem.start; } if ((maxTime - msTime) < 500) { MAIN.showStatusMessage(tr("Not enough space to add subtitle.")); return; } Subtitles::SubtitleItem item; item.start = msTime; item.end = msTime + DEFAULT_ITEM_DURATION; if (item.end > maxTime) { item.end = msTime + (maxTime - msTime); } m_model->overwriteItem(trackIndex, item); setCurrentItem(trackIndex, m_model->itemIndexAtTime(trackIndex, msTime)); m_text->setFocus(); m_text->selectAll(); } void SubtitlesDock::onRemoveRequested() { LOG_DEBUG(); int trackIndex = m_trackCombo->currentIndex(); QModelIndexList selectedRows = m_selectionModel->selectedRows(); if (selectedRows.size() > 0) { int firstItemIndex = selectedRows[0].row(); int lastItemIndex = selectedRows[selectedRows.size() - 1].row(); m_model->removeItems(trackIndex, firstItemIndex, lastItemIndex); } } void SubtitlesDock::onSetStartRequested() { LOG_DEBUG(); int trackIndex = m_trackCombo->currentIndex(); QModelIndexList selectedRows = m_selectionModel->selectedRows(); if (selectedRows.size() > 0) { int itemIndex = selectedRows[0].row(); int64_t msTime = positionToMs(m_pos); auto currentItem = m_model->getItem(trackIndex, itemIndex); if (msTime >= currentItem.end) { MAIN.showStatusMessage(tr("Start time can not be after end time.")); return; } if (itemIndex > 0) { auto prevItem = m_model->getItem(trackIndex, itemIndex - 1); if (msTime < prevItem.end) { MAIN.showStatusMessage(tr("Start time can not be before previous subtitle.")); return; } } m_model->setItemStart(trackIndex, itemIndex, msTime); } } void SubtitlesDock::onSetEndRequested() { LOG_DEBUG(); int trackIndex = m_trackCombo->currentIndex(); QModelIndexList selectedRows = m_selectionModel->selectedRows(); if (selectedRows.size() > 0) { int itemIndex = selectedRows[0].row(); int64_t msTime = positionToMs(m_pos); auto currentItem = m_model->getItem(trackIndex, itemIndex); if (msTime <= currentItem.start) { MAIN.showStatusMessage(tr("End time can not be before start time.")); return; } int itemCount = m_model->itemCount(trackIndex); if (itemIndex < (itemCount - 1)) { auto nextItem = m_model->getItem(trackIndex, itemIndex + 1); if (msTime > nextItem.start) { MAIN.showStatusMessage(tr("End time can not be after next subtitle.")); return; } } m_model->setItemEnd(trackIndex, itemIndex, msTime); } } void SubtitlesDock::onMoveRequested() { QModelIndexList selectedRows = m_selectionModel->selectedRows(); if (selectedRows.size() <= 0) { return; } int64_t msTime = positionToMs(m_pos); if (m_model->validateMove(selectedRows, msTime)) { int trackIndex = selectedRows[0].parent().row(); int firstItemIndex = selectedRows[0].row(); int lastItemIndex = selectedRows[selectedRows.size() - 1].row(); m_model->moveItems(trackIndex, firstItemIndex, lastItemIndex, msTime); } else { // This existing item will cause a conflict. MAIN.showStatusMessage(tr("Unable to move. Subtitles already exist at this time.")); } } void SubtitlesDock::onTextEdited() { LOG_DEBUG(); QModelIndex currentIndex = m_selectionModel->currentIndex(); if (currentIndex.isValid() && currentIndex.parent().isValid()) { m_textEditInProgress = true; m_model->setText(currentIndex.parent().row(), currentIndex.row(), m_text->toPlainText()); m_textEditInProgress = false; } else { LOG_ERROR() << "Invalid index" << currentIndex; } } void SubtitlesDock::onModelReset() { refreshTracksCombo(); refreshWidgets(); } void SubtitlesDock::onStartColumnToggled(bool checked) { Settings.setSubtitlesShowColumn("start", checked); m_treeView->setColumnHidden(1, !checked); } void SubtitlesDock::onEndColumnToggled(bool checked) { Settings.setSubtitlesShowColumn("end", checked); m_treeView->setColumnHidden(2, !checked); } void SubtitlesDock::onDurationColumnToggled(bool checked) { Settings.setSubtitlesShowColumn("duration", checked); m_treeView->setColumnHidden(3, !checked); } void SubtitlesDock::onItemDoubleClicked(const QModelIndex &index) { if (index.parent().isValid()) { const Subtitles::SubtitleItem item = m_model->getItem(index.parent().row(), index.row()); int64_t position = msToPosition(item.start); emit seekRequested((int)position); } } void SubtitlesDock::resizeEvent(QResizeEvent *e) { QDockWidget::resizeEvent(e); resizeTextWidgets(); } void SubtitlesDock::resizeTextWidgets() { if (Settings.subtitlesShowPrevNext()) { m_prev->setVisible(true); m_prev->setMinimumSize(QSize(width() / 3, m_text->maximumHeight())); m_text->setMinimumSize(QSize(width() / 3, m_text->maximumHeight())); m_next->setVisible(true); m_next->setMinimumSize(QSize(width() / 3, m_text->maximumHeight())); m_prevLabel->setVisible(true); m_textLabel->setVisible(true); m_nextLabel->setVisible(true); } else { m_text->setMinimumSize(QSize(width(), m_text->maximumHeight())); m_prev->setVisible(false); m_next->setVisible(false); m_prevLabel->setVisible(false); m_textLabel->setVisible(false); m_nextLabel->setVisible(false); } } void SubtitlesDock::updateTextWidgets() { Subtitles::SubtitleItem item; const QSignalBlocker blocker(m_text); // First update based on current (selected) item. QModelIndex currentIndex = m_selectionModel->currentIndex(); if (currentIndex.isValid() && currentIndex.parent().isValid()) { int trackIndex = currentIndex.parent().row(); int itemIndex = currentIndex.row(); if (trackIndex >= 0 && trackIndex < m_model->trackCount() && itemIndex >= 0 && itemIndex < m_model->itemCount(trackIndex)) { item = m_model->getItem(trackIndex, itemIndex); m_text->setPlainText(QString::fromStdString(item.text)); m_text->setReadOnly(false); if (itemIndex > 0) { item = m_model->getItem(trackIndex, itemIndex - 1); m_prev->setPlaceholderText(QString::fromStdString(item.text)); } else { m_prev->setPlaceholderText(QString()); } if (itemIndex < (m_model->itemCount(trackIndex) - 1)) { item = m_model->getItem(trackIndex, itemIndex + 1); m_next->setPlaceholderText(QString::fromStdString(item.text)); } else { m_next->setPlaceholderText(QString()); } return; } else { LOG_ERROR() << "Invalid row selected" << currentIndex; } } // If nothing selected, update based on position (but not editable) m_text->setReadOnly(true); int trackIndex = m_trackCombo->currentIndex(); if (trackIndex >= 0 && m_pos >= 0) { int64_t msTime = positionToMs(m_pos); int itemIndex = m_model->itemIndexAtTime(trackIndex, msTime); if (itemIndex >= 0) { item = m_model->getItem(trackIndex, itemIndex); m_text->setPlainText(QString::fromStdString(item.text)); m_text->setReadOnly(false); if (itemIndex > 0) { item = m_model->getItem(trackIndex, itemIndex - 1); m_prev->setPlaceholderText(QString::fromStdString(item.text)); } else { m_prev->setPlaceholderText(QString()); } if (itemIndex < (m_model->itemCount(trackIndex) - 1)) { item = m_model->getItem(trackIndex, itemIndex + 1); m_next->setPlaceholderText(QString::fromStdString(item.text)); } else { m_next->setPlaceholderText(QString()); } } else { m_text->clear(); itemIndex = m_model->itemIndexBeforeTime(trackIndex, msTime); if (itemIndex >= 0) { item = m_model->getItem(trackIndex, itemIndex); m_prev->setPlaceholderText(QString::fromStdString(item.text)); } else { m_prev->setPlaceholderText(QString()); } itemIndex = m_model->itemIndexAfterTime(trackIndex, msTime); if (itemIndex >= 0) { item = m_model->getItem(trackIndex, itemIndex); m_next->setPlaceholderText(QString::fromStdString(item.text)); } else { m_next->setPlaceholderText(QString()); } } } else { m_text->setReadOnly(true); m_text->clear(); m_prev->setPlaceholderText(QString()); m_next->setPlaceholderText(QString()); } } void SubtitlesDock::updateActionAvailablity() { if (!m_model || !m_model->isValid()) { // Disable all actions m_addToTimelineLabel->setVisible(true); Actions["subtitleAddTrackAction"]->setEnabled(false); Actions["subtitleRemoveTrackAction"]->setEnabled(false); Actions["subtitleEditTrackAction"]->setEnabled(false); Actions["SubtitleImportAction"]->setEnabled(false); Actions["SubtitleExportAction"]->setEnabled(false); Actions["subtitleCreateEditItemAction"]->setEnabled(false); Actions["subtitleAddItemAction"]->setEnabled(false); Actions["subtitleRemoveItemAction"]->setEnabled(false); Actions["subtitleMoveAction"]->setEnabled(false); Actions["subtitleSetStartAction"]->setEnabled(false); Actions["subtitleSetEndAction"]->setEnabled(false); Actions["subtitleBurnInAction"]->setEnabled(false); Actions["subtitleGenerateTextAction"]->setEnabled(false); Actions["subtitleSpeechToTextAction"]->setEnabled(false); } else { m_addToTimelineLabel->setVisible(false); Actions["subtitleCreateEditItemAction"]->setEnabled(true); Actions["subtitleAddTrackAction"]->setEnabled(true); Actions["subtitleEditTrackAction"]->setEnabled(true); Actions["SubtitleImportAction"]->setEnabled(true); Actions["subtitleAddItemAction"]->setEnabled(true); Actions["subtitleSpeechToTextAction"]->setEnabled(true); if (m_model->trackCount() == 0) { Actions["subtitleRemoveTrackAction"]->setEnabled(false); Actions["SubtitleExportAction"]->setEnabled(false); Actions["subtitleRemoveItemAction"]->setEnabled(false); Actions["subtitleMoveAction"]->setEnabled(false); Actions["subtitleSetStartAction"]->setEnabled(false); Actions["subtitleSetEndAction"]->setEnabled(false); Actions["subtitleBurnInAction"]->setEnabled(false); Actions["subtitleGenerateTextAction"]->setEnabled(false); } else { Actions["subtitleRemoveTrackAction"]->setEnabled(true); Actions["SubtitleExportAction"]->setEnabled(true); Actions["subtitleBurnInAction"]->setEnabled(true); Actions["subtitleGenerateTextAction"]->setEnabled(true); if (m_selectionModel->selectedRows().size() == 1) { Actions["subtitleSetStartAction"]->setEnabled(true); Actions["subtitleSetEndAction"]->setEnabled(true); } else { Actions["subtitleSetStartAction"]->setEnabled(false); Actions["subtitleSetEndAction"]->setEnabled(false); } if (m_selectionModel->selectedRows().size() > 0) { Actions["subtitleRemoveItemAction"]->setEnabled(true); Actions["subtitleMoveAction"]->setEnabled(true); } else { Actions["subtitleRemoveItemAction"]->setEnabled(false); Actions["subtitleMoveAction"]->setEnabled(false); } } } } void SubtitlesDock::refreshWidgets() { if (m_textEditInProgress) { return; } updateTextWidgets(); updateActionAvailablity(); } void SubtitlesDock::setCurrentItem(int trackIndex, int itemIndex) { if (itemIndex >= 0) { QModelIndex modelIndex = m_model->itemModelIndex(trackIndex, itemIndex); if (modelIndex.isValid()) { m_treeView->setCurrentIndex(modelIndex); return; } } m_treeView->setCurrentIndex(QModelIndex()); } void SubtitlesDock::selectItemForTime() { int trackIndex = m_trackCombo->currentIndex(); if (trackIndex >= 0) { int64_t time = positionToMs(m_pos); int itemIndex = m_model->itemIndexAtTime(trackIndex, time); setCurrentItem(trackIndex, itemIndex); } } QString SubtitlesDock::availableTrackName() { int i = 1; QString suggestedName = tr("Subtitle Track %1").arg(i); while (trackNameExists(suggestedName)) { suggestedName = tr("Subtitle Track %1").arg(i++); } return suggestedName; } bool SubtitlesDock::trackNameExists(const QString &name) { QList<SubtitlesModel::SubtitleTrack> tracks = m_model->getTracks(); for (auto &track : tracks) { if (track.name == name) { return true; } } return false; } void SubtitlesDock::ensureTrackExists() { if (m_model->trackCount() == 0) { SubtitlesModel::SubtitleTrack track; track.name = tr("Subtitle Track %1").arg(1); track.lang = QLocale::languageToCode(QLocale::system().language(), QLocale::ISO639Part2); m_model->addTrack(track); } } void SubtitlesDock::burnInOnTimeline() { int trackIndex = m_trackCombo->currentIndex(); auto track = m_model->getTrack(trackIndex); Mlt::Filter filter(MLT.profile(), "subtitle"); filter.set(kShotcutFilterProperty, "subtitles"); #if defined(Q_OS_WIN) filter.set("family", "Verdana"); #elif defined(Q_OS_MAC) filter.set("family", "Helvetica"); #endif filter.set("fgcolour", "#ffffffff"); filter.set("bgcolour", "#00000000"); filter.set("olcolour", "#aa000000"); filter.set("outline", 3); filter.set("weight", QFont::Bold); filter.set("style", "normal"); filter.set("shotcut:usePointSize", 1); filter.set("size", MLT.profile().height() / 20); filter.set("geometry", "20%/75%:60%x20%"); filter.set("valign", "bottom"); filter.set("halign", "center"); filter.set("feed", track.name.toUtf8().constData()); emit createOrEditFilterOnOutput(&filter, QStringList() << "feed"); } void SubtitlesDock::generateTextOnTimeline() { int trackIndex = m_trackCombo->currentIndex(); int itemCount = m_model->itemCount(trackIndex); if (itemCount == 0) { return; } Mlt::Playlist playlist(MLT.profile()); int lastItemFrameEnd = 0; for (int itemIndex = 0; itemIndex < itemCount; itemIndex++) { auto item = m_model->getItem(trackIndex, itemIndex); int frameStart = msToPosition(item.start); int frameEnd = msToPosition(item.end); // Create a transparent color producer Mlt::Producer producer(MLT.profile(), "color:"); producer.set("resource", "#00000000"); producer.set("mlt_image_format", "rgba"); producer.set("in", 0); producer.set("out", frameEnd - frameStart); producer.set("length", producer.frames_to_time(frameEnd - frameStart + 1, mlt_time_clock)); // Add a text filter Mlt::Filter filter(MLT.profile(), "dynamictext"); filter.set(kShotcutFilterProperty, "dynamicText"); filter.set("argument", item.text.c_str()); #ifdef Q_OS_WIN filter.set("family", "Verdana"); #elif defined(Q_OS_MAC) filter.set("family", "Helvetica"); #endif filter.set("fgcolour", "#ffffffff"); filter.set("bgcolour", "#00000000"); filter.set("olcolour", "#aa000000"); filter.set("outline", 3); filter.set("weight", QFont::Bold); filter.set("style", "normal"); filter.set("shotcut:usePointSize", 1); filter.set("size", MLT.profile().height() / 20); filter.set("geometry", "20%/75%:60%x20%"); filter.set("valign", "bottom"); filter.set("halign", "center"); filter.set_in_and_out(producer.get_in(), producer.get_out()); producer.attach(filter); if (lastItemFrameEnd < (frameStart - 1)) { playlist.blank(frameStart - lastItemFrameEnd - 1); } playlist.append(producer, 0, frameEnd - frameStart - 1); lastItemFrameEnd = frameEnd; } emit addAllTimeline(&playlist, true, true); } void SubtitlesDock::speechToText() { TranscribeAudioDialog dialog(availableTrackName(), this); if (dialog.exec() != QDialog::Accepted) { return; } if (trackNameExists(dialog.name())) { MAIN.showStatusMessage(tr("Subtitle track already exists: %1").arg(dialog.name())); return; } QString tmpLocation = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation) + "/"; // Make a copy of the timeline producer QString xml = MLT.XML(MAIN.multitrack()); std::unique_ptr<Mlt::Producer> tempProducer(new Mlt::Producer(MLT.profile(), "xml-string", xml.toUtf8().constData())); // Mute tracks as requested Mlt::Tractor tractor(*tempProducer.get()); if (!tractor.is_valid()) { LOG_ERROR() << "Invalid tractor"; return; } int trackCount = tractor.count(); if (trackCount <= 0) { LOG_ERROR() << "No tracks"; return; } QList<int> tracks = dialog.tracks(); for (int trackIndex = 0; trackIndex < trackCount; trackIndex++) { std::unique_ptr<Mlt::Producer> track(tractor.track(trackIndex)); if (track) { if (tracks.contains(trackIndex)) { track->set("hide", 0); } else { track->set("hide", 2); } } } // Convert to XML QString wavXml = MLT.XML(tempProducer.get()); // Create a temporary wav file QTemporaryFile *tmpWav = Util::writableTemporaryFile(tmpLocation, "shotcut-XXXXXX.wav"); if (!tmpWav->open()) { LOG_ERROR() << "Failed to open temporary file" << tmpWav->fileName(); return; } tmpWav->close(); // Make the wav file from the timeline QStringList args; args << "-consumer" << "avformat:" + tmpWav->fileName() << "video_off=1" << "ar=16000" << "ac=1"; QString jobName = tr("Extracting Audio"); MeltJob *wavJob = new MeltJob(jobName, wavXml, args, MLT.profile().frame_rate_num(), MLT.profile().frame_rate_den()); tmpWav->setParent(wavJob); JOBS.add(wavJob); // Create a temporary srt file QTemporaryFile *tmpSrt = Util::writableTemporaryFile(tmpLocation, "shotcut-XXXXXX.srt"); if (!tmpSrt->open()) { LOG_ERROR() << "Failed to open temporary file" << tmpSrt->fileName(); return; } tmpWav->close(); // Run speech transcription on the wav file jobName = tr("Speech to Text"); WhisperJob *whisperJob = new WhisperJob(jobName, tmpWav->fileName(), tmpSrt->fileName(), dialog.language(), dialog.translate(), dialog.maxLineLength()); // Ensure the language code is 3 character (part 2) QString langCode = dialog.language(); QLocale::Language lang = QLocale::codeToLanguage(langCode); if (lang != QLocale::AnyLanguage) { langCode = QLocale::languageToCode(lang, QLocale::ISO639Part2); } whisperJob->setPostJobAction(new ImportSrtPostJobAction(tmpSrt->fileName(), dialog.name(), langCode, dialog.includeNonspoken(), this)); tmpSrt->setParent(whisperJob); JOBS.add(whisperJob); }
48,598
C++
.cpp
1,132
35.337456
127
0.651844
mltframework/shotcut
10,796
1,118
50
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
13,128
recentdock.cpp
mltframework_shotcut/src/docks/recentdock.cpp
/* * Copyright (c) 2012-2024 Meltytech, LLC * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "docks/recentdock.h" #include "settings.h" #include "ui_recentdock.h" #include "util.h" #include <QAction> #include <QDir> #include <QKeyEvent> #include <QMenu> #include <Logger.h> static const int MaxItems = 200; RecentDock::RecentDock(QWidget *parent) : QDockWidget(parent), ui(new Ui::RecentDock) { LOG_DEBUG() << "begin"; ui->setupUi(this); toggleViewAction()->setIcon(windowIcon()); m_recent = Settings.recent(); #ifdef Q_OS_WIN // Remove bad entries on Windows due to bug in v17.01. QStringList newList; bool isRepaired = false; foreach (QString s, m_recent) { if (s.size() >= 3 && s[0] == '/' && s[2] == ':') { s.remove(0, 1); isRepaired = true; } newList << s; } if (isRepaired) { m_recent = newList; Settings.setRecent(m_recent); Settings.sync(); } #endif ui->listWidget->setDragEnabled(true); ui->listWidget->setDragDropMode(QAbstractItemView::DragOnly); foreach (QString s, m_recent) { QStandardItem *item = new QStandardItem(Util::baseName(s)); item->setToolTip(QDir::toNativeSeparators(s)); m_model.appendRow(item); } m_proxyModel.setSourceModel(&m_model); m_proxyModel.setFilterCaseSensitivity(Qt::CaseInsensitive); ui->listWidget->setModel(&m_proxyModel); LOG_DEBUG() << "end"; } RecentDock::~RecentDock() { delete ui; } void RecentDock::add(const QString &s) { // Block anything big that can cause a performance problem if (s.size() > ShotcutSettings::MaxPath) return; QString filePath = QDir::fromNativeSeparators(s); if (filePath.startsWith(QDir::tempPath())) return; QString name = remove(s); QStandardItem *item = new QStandardItem(name); item->setToolTip(QDir::toNativeSeparators(s)); m_model.insertRow(0, item); m_recent.prepend(filePath); while (m_recent.count() > MaxItems) m_recent.removeLast(); Settings.setRecent(m_recent); if (filePath.endsWith(".mlt")) { auto projects = Settings.projects(); projects.removeOne(filePath); projects.prepend(filePath); Settings.setProjects(projects); } } void RecentDock::on_listWidget_activated(const QModelIndex &i) { ui->listWidget->setCurrentIndex(QModelIndex()); emit itemActivated(m_proxyModel.itemData(i)[Qt::ToolTipRole].toString()); } QString RecentDock::remove(const QString &s) { QString filePath = QDir::fromNativeSeparators(s); m_recent.removeOne(filePath); Settings.setRecent(m_recent); QString name = Util::baseName(filePath); QList<QStandardItem *> items = m_model.findItems(name); if (items.count() > 0) m_model.removeRow(items.first()->row()); return name; } void RecentDock::find() { ui->lineEdit->setFocus(); ui->lineEdit->selectAll(); } void RecentDock::keyPressEvent(QKeyEvent *event) { if (event->key() == Qt::Key_Backspace || event->key() == Qt::Key_Delete) { on_actionDelete_triggered(); } else { QDockWidget::keyPressEvent(event); } } void RecentDock::on_lineEdit_textChanged(const QString &search) { m_proxyModel.setFilterFixedString(search); } void RecentDock::on_actionDelete_triggered() { if (ui->listWidget->currentIndex().isValid()) { auto row = ui->listWidget->currentIndex().row(); auto url = m_recent[row]; m_recent.removeAt(row); Settings.setRecent(m_recent); m_model.removeRow(row); if (url.endsWith(".mlt")) { auto ls = Settings.projects(); if (ls.removeAll(url) > 0) Settings.setProjects(ls); } emit deleted(url); } } void RecentDock::on_listWidget_customContextMenuRequested(const QPoint &pos) { if (ui->listWidget->currentIndex().isValid()) { QMenu menu(this); menu.addAction(ui->actionDelete); menu.exec(mapToGlobal(pos + QPoint(0, ui->lineEdit->height()))); } }
4,701
C++
.cpp
146
27.472603
78
0.673204
mltframework/shotcut
10,796
1,118
50
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
13,129
notesdock.cpp
mltframework_shotcut/src/docks/notesdock.cpp
/* * Copyright (c) 2022-2024 Meltytech, LLC * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "notesdock.h" #include "actions.h" #include "settings.h" #include <Logger.h> #include <QAction> #include <QIcon> #include <QPlainTextEdit> #include <QApplication> #include <QMenu> #include <QWheelEvent> class TextEditor: public QPlainTextEdit { public: explicit TextEditor(QWidget *parent = nullptr) : QPlainTextEdit() { zoomIn(Settings.notesZoom()); setTabChangesFocus(false); setTabStopDistance(fontMetrics().horizontalAdvance("XXXX")); // Tabstop = 4 spaces setContextMenuPolicy(Qt::CustomContextMenu); auto action = new QAction(tr("Decrease Text Size"), this); action->setShortcut(Qt::CTRL | Qt::ALT | Qt::Key_Minus); addAction(action); Actions.add("notesDecreaseTextSize", action, tr("Notes")); connect(action, &QAction::triggered, this, [ = ]() { setZoom(-4); }); action = new QAction(tr("Increase Text Size"), this); action->setShortcut(Qt::CTRL | Qt::ALT | Qt::Key_Equal); addAction(action); Actions.add("notesIncreaseTextSize", action, tr("Notes")); connect(action, &QAction::triggered, this, [ = ]() { setZoom(4); }); connect(this, &QWidget::customContextMenuRequested, this, [ = ](const QPoint & pos) { std::unique_ptr<QMenu> menu {createStandardContextMenu()}; actions().at(0)->setEnabled(Settings.notesZoom() > 0); menu->addActions(actions()); menu->exec(mapToGlobal(pos)); }); } void setZoom(int delta) { auto zoom = Settings.notesZoom(); zoomIn((zoom + delta >= 0) ? delta : -zoom); Settings.setNotesZoom(std::max<int>(0, zoom + delta)); } protected: void wheelEvent(QWheelEvent *event) override { if (event->modifiers() & Qt::ControlModifier) { setZoom((event->angleDelta().y() < 0) ? -1 : 1); event->accept(); } else { QPlainTextEdit::wheelEvent(event); } } }; NotesDock::NotesDock(QWidget *parent) : QDockWidget(tr("Notes"), parent), m_textEdit(new TextEditor(this)), m_blockUpdate(false) { LOG_DEBUG() << "begin"; setObjectName("NotesDock"); QIcon filterIcon = QIcon::fromTheme("document-edit", QIcon(":/icons/oxygen/32x32/actions/document-edit.png")); setWindowIcon(filterIcon); toggleViewAction()->setIcon(windowIcon()); QObject::connect(m_textEdit, SIGNAL(textChanged()), SLOT(onTextChanged())); QDockWidget::setWidget(m_textEdit); LOG_DEBUG() << "end"; } QString NotesDock::getText() { return m_textEdit->toPlainText(); } void NotesDock::setText(const QString &text) { m_blockUpdate = true; m_textEdit->setPlainText(text); m_blockUpdate = false; } void NotesDock::onTextChanged() { if (!m_blockUpdate) { emit modified(); } }
3,619
C++
.cpp
104
29.192308
97
0.652013
mltframework/shotcut
10,796
1,118
50
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
13,130
timelinedock.cpp
mltframework_shotcut/src/docks/timelinedock.cpp
/* * Copyright (c) 2013-2024 Meltytech, LLC * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "timelinedock.h" #include "actions.h" #include "models/audiolevelstask.h" #include "models/multitrackmodel.h" #include "qmltypes/thumbnailprovider.h" #include "mainwindow.h" #include "commands/timelinecommands.h" #include "qmltypes/qmlapplication.h" #include "qmltypes/qmlutilities.h" #include "qmltypes/qmlview.h" #include "shotcut_mlt_properties.h" #include "settings.h" #include "util.h" #include "proxymanager.h" #include "dialogs/alignaudiodialog.h" #include "dialogs/editmarkerdialog.h" #include "dialogs/longuitask.h" #include "dialogs/resourcedialog.h" #include "widgets/docktoolbar.h" #include <QAction> #include <QActionGroup> #include <QMenu> #include <QSlider> #include <QToolBar> #include <QToolButton> #include <QVBoxLayout> #include <QtQml> #include <QtQuick> #include <QGuiApplication> #include <QClipboard> #include <Logger.h> static const char *kFileUrlProtocol = "file://"; static const char *kFilesUrlDelimiter = ",file://"; static const int kRecordingTimerIntervalMs = 1000; TimelineDock::TimelineDock(QWidget *parent) : QDockWidget(parent), m_quickView(QmlUtilities::sharedEngine(), this), m_position(-1), m_ignoreNextPositionChange(false), m_trimDelta(0), m_transitionDelta(0), m_subtitlesModel(), m_subtitlesSelectionModel(&m_subtitlesModel) { LOG_DEBUG() << "begin"; m_selection.selectedTrack = -1; m_selection.isMultitrackSelected = false; setObjectName("TimelineDock"); QDockWidget::setWindowTitle(tr("Timeline")); resize(400, 300); setMinimumSize(QSize(200, 200)); setAcceptDrops(true); QIcon icon = QIcon::fromTheme("view-time-schedule", QIcon(":/icons/oxygen/32x32/actions/view-time-schedule.png")); setWindowIcon(icon); toggleViewAction()->setIcon(windowIcon()); setupActions(); m_mainMenu = new QMenu(tr("Timeline"), this); QMenu *trackOperationsMenu = new QMenu(tr("Track Operations"), this); trackOperationsMenu->addAction(Actions["timelineAddAudioTrackAction"]); trackOperationsMenu->addAction(Actions["timelineAddVideoTrackAction"]); trackOperationsMenu->addAction(Actions["timelineInsertTrackAction"]); trackOperationsMenu->addAction(Actions["timelineRemoveTrackAction"]); trackOperationsMenu->addAction(Actions["timelineMoveTrackUpAction"]); trackOperationsMenu->addAction(Actions["timelineMoveTrackDownAction"]); trackOperationsMenu->addAction(Actions["timelineToggleTrackHiddenAction"]); trackOperationsMenu->addAction(Actions["timelineToggleTrackLockedAction"]); trackOperationsMenu->addAction(Actions["timelineToggleTrackMuteAction"]); trackOperationsMenu->addAction(Actions["timelineToggleTrackBlendingAction"]); m_mainMenu->addMenu(trackOperationsMenu); QMenu *trackHeightMenu = new QMenu(tr("Track Height"), this); trackHeightMenu->addAction(Actions["timelineTracksShorterAction"]); trackHeightMenu->addAction(Actions["timelineTracksTallerAction"]); trackHeightMenu->addAction(Actions["timelineResetTrackHeightAction"]); m_mainMenu->addMenu(trackHeightMenu); QMenu *selectionMenu = new QMenu(tr("Selection"), this); selectionMenu->addAction(Actions["timelineSelectAllAction"]); selectionMenu->addAction(Actions["timelineSelectAllOnTrackAction"]); selectionMenu->addAction(Actions["timelineSelectNoneAction"]); selectionMenu->addAction(Actions["timelineSelectNextClipAction"]); selectionMenu->addAction(Actions["timelineSelectPrevClipAction"]); selectionMenu->addAction(Actions["timelineSelectClipAboveAction"]); selectionMenu->addAction(Actions["timelineSelectClipBelowAction"]); selectionMenu->addAction(Actions["timelineSelectClipUnderPlayheadAction"]); selectionMenu->addAction(Actions["timelineCurrentTrackAboveAction"]); selectionMenu->addAction(Actions["timelineCurrentTrackBelowAction"]); selectionMenu->addAction(Actions["timelineGroupAction"]); m_mainMenu->addMenu(selectionMenu); QMenu *editMenu = new QMenu(tr("Edit"), this); editMenu->addAction(Actions["timelinePasteAction"]); editMenu->addAction(Actions["timelineAppendAction"]); editMenu->addAction(Actions["timelineOverwriteAction"]); editMenu->addAction(Actions["timelineReplaceAction"]); editMenu->addAction(Actions["timelineRecordAudioAction"]); editMenu->addAction(Actions["playerSetInAction"]); editMenu->addAction(Actions["playerSetOutAction"]); editMenu->addAction(Actions["timelineNudgeForwardAction"]); editMenu->addAction(Actions["timelineNudgeBackwardAction"]); editMenu->addAction(Actions["timelineRippleTrimClipInAction"]); editMenu->addAction(Actions["timelineRippleTrimClipOutAction"]); editMenu->addAction(Actions["timelineSplitAction"]); editMenu->addAction(Actions["timelineSplitAllTracksAction"]); editMenu->addAction(Actions["timelineApplyCopiedFiltersAction"]); m_mainMenu->addMenu(editMenu); QMenu *viewMenu = new QMenu(tr("View"), this); viewMenu->addAction(Actions["timelineZoomOutAction"]); viewMenu->addAction(Actions["timelineZoomInAction"]); viewMenu->addAction(Actions["timelineZoomFitAction"]); viewMenu->addAction(Actions["timelinePropertiesAction"]); m_mainMenu->addMenu(viewMenu); QMenu *markerMenu = new QMenu(tr("Marker"), this); markerMenu->addAction(Actions["timelineMarkerAction"]); markerMenu->addAction(Actions["timelinePrevMarkerAction"]); markerMenu->addAction(Actions["timelineNextMarkerAction"]); markerMenu->addAction(Actions["timelineDeleteMarkerAction"]); markerMenu->addAction(Actions["timelineMarkSelectedClipAction"]); markerMenu->addAction(Actions["timelineCycleMarkerColorAction"]); m_mainMenu->addMenu(markerMenu); Actions.loadFromMenu(m_mainMenu); m_clipMenu = new QMenu(tr("Timeline Clip"), this); m_clipMenu->addAction(Actions["timelineCutAction"]); m_clipMenu->addAction(Actions["timelineCopyAction"]); m_clipMenu->addAction(Actions["timelineDeleteAction"]); m_clipMenu->addAction(Actions["timelineLiftAction"]); m_clipMenu->addAction(Actions["timelineReplaceAction"]); m_clipMenu->addAction(Actions["timelineSplitAction"]); m_clipMenu->addAction(Actions["timelineGroupAction"]); m_clipMenu->addAction(Actions["timelineNudgeForwardAction"]); m_clipMenu->addAction(Actions["timelineNudgeBackwardAction"]); m_clipMenu->addAction(Actions["timelineMergeWithNextAction"]); m_clipMenu->addAction(Actions["timelineDetachAudioAction"]); m_clipMenu->addAction(Actions["timelineAlignToReferenceAction"]); m_clipMenu->addAction(Actions["timelineApplyCopiedFiltersAction"]); m_clipMenu->addAction(Actions["timelineUpdateThumbnailsAction"]); m_clipMenu->addAction(Actions["timelineRebuildAudioWaveformAction"]); m_clipMenu->addAction(Actions["timelinePropertiesAction"]); Actions.loadFromMenu(m_clipMenu); QVBoxLayout *vboxLayout = new QVBoxLayout(); vboxLayout->setSpacing(0); vboxLayout->setContentsMargins(0, 0, 0, 0); DockToolBar *toolbar = new DockToolBar(tr("Timeline Controls")); QToolButton *menuButton = new QToolButton(); menuButton->setIcon(QIcon::fromTheme("show-menu", QIcon(":/icons/oxygen/32x32/actions/show-menu.png"))); menuButton->setToolTip(tr("Timeline Menu")); menuButton->setAutoRaise(true); menuButton->setPopupMode(QToolButton::QToolButton::InstantPopup); menuButton->setMenu(m_mainMenu); toolbar->addWidget(menuButton); toolbar->addSeparator(); toolbar->addAction(Actions["timelineCutAction"]); toolbar->addAction(Actions["timelineCopyAction"]); toolbar->addAction(Actions["timelinePasteAction"]); toolbar->addSeparator(); toolbar->addAction(Actions["timelineAppendAction"]); toolbar->addAction(Actions["timelineDeleteAction"]); toolbar->addAction(Actions["timelineLiftAction"]); toolbar->addAction(Actions["timelineOverwriteAction"]); toolbar->addAction(Actions["timelineSplitAction"]); toolbar->addSeparator(); toolbar->addAction(Actions["timelineMarkerAction"]); toolbar->addAction(Actions["timelinePrevMarkerAction"]); toolbar->addAction(Actions["timelineNextMarkerAction"]); toolbar->addSeparator(); toolbar->addAction(Actions["timelineSnapAction"]); toolbar->addAction(Actions["timelineScrubDragAction"]); toolbar->addAction(Actions["timelineRippleAction"]); toolbar->addAction(Actions["timelineRippleAllTracksAction"]); toolbar->addAction(Actions["timelineRippleMarkersAction"]); toolbar->addSeparator(); toolbar->addAction(Actions["timelineZoomOutAction"]); QSlider *zoomSlider = new QSlider(); zoomSlider->setOrientation(Qt::Horizontal); zoomSlider->setMaximumWidth(200); zoomSlider->setMinimum(0); zoomSlider->setMaximum(300); zoomSlider->setValue(100); zoomSlider->setTracking(false); connect(zoomSlider, &QSlider::valueChanged, this, [&](int value) { if (!isVisible() || !m_quickView.rootObject()) return; emit setZoom(value / 100.0); }); connect(&m_model, &MultitrackModel::scaleFactorChanged, zoomSlider, [ = ]() { double value = round(pow(m_model.scaleFactor() - 0.01, 1.0 / 3.0) * 100.0); zoomSlider->blockSignals(true); zoomSlider->setValue(value); zoomSlider->blockSignals(false); }); toolbar->addWidget(zoomSlider); toolbar->addAction(Actions["timelineZoomInAction"]); toolbar->addAction(Actions["timelineZoomFitAction"]); toolbar->addSeparator(); toolbar->addAction(Actions["timelineRecordAudioAction"]); vboxLayout->setMenuBar(toolbar); qmlRegisterType<MultitrackModel>("Shotcut.Models", 1, 0, "MultitrackModel"); qmlRegisterType<MarkersModel>("Shotcut.Models", 1, 0, "MarkersModel"); QDir importPath = QmlUtilities::qmlDir(); importPath.cd("modules"); m_quickView.engine()->addImportPath(importPath.path()); m_quickView.engine()->addImageProvider(QStringLiteral("thumbnail"), new ThumbnailProvider); QmlUtilities::setCommonProperties(m_quickView.rootContext()); m_quickView.rootContext()->setContextProperty("view", new QmlView(&m_quickView)); m_quickView.rootContext()->setContextProperty("timeline", this); m_quickView.rootContext()->setContextProperty("multitrack", &m_model); m_quickView.rootContext()->setContextProperty("markers", &m_markersModel); m_quickView.rootContext()->setContextProperty("subtitlesModel", &m_subtitlesModel); m_quickView.rootContext()->setContextProperty("subtitlesSelectionModel", &m_subtitlesSelectionModel); m_quickView.setResizeMode(QQuickWidget::SizeRootObjectToView); m_quickView.setClearColor(palette().window().color()); m_quickView.quickWindow()->setPersistentSceneGraph(false); #ifndef Q_OS_MAC m_quickView.setAttribute(Qt::WA_AcceptTouchEvents); #endif m_selectionSignalTimer.setSingleShot(true); m_selectionSignalTimer.setInterval(100); connect(&m_selectionSignalTimer, &QTimer::timeout, this, [&]() { emit selectionChanged(); emitSelectedFromSelection(); }); connect(&m_quickView, &QQuickWidget::statusChanged, this, [&]() { if ( m_quickView.status() == QQuickWidget::Ready) { connect(m_quickView.rootObject(), SIGNAL(clipClicked()), this, SIGNAL(clipClicked())); connect(m_quickView.rootObject(), SIGNAL(timelineRightClicked()), this, SLOT(onTimelineRightClicked())); connect(m_quickView.rootObject(), SIGNAL(clipRightClicked()), this, SLOT(onClipRightClicked())); } }); connect(&m_model, &MultitrackModel::created, this, [&]() { connect(&m_model, &MultitrackModel::modified, this, &TimelineDock::clearSelectionIfInvalid); connect(&m_model, &MultitrackModel::appended, this, &TimelineDock::selectClip); connect(&m_model, &MultitrackModel::inserted, this, &TimelineDock::selectClip); connect(&m_model, &MultitrackModel::overWritten, this, &TimelineDock::selectClip); connect(&m_model, &MultitrackModel::rowsInserted, this, &TimelineDock::onRowsInserted); connect(&m_model, &MultitrackModel::rowsRemoved, this, &TimelineDock::onRowsRemoved); connect(&m_model, &MultitrackModel::rowsMoved, this, &TimelineDock::onRowsMoved); connect(&m_model, &MultitrackModel::noMoreEmptyTracks, this, &TimelineDock::onNoMoreEmptyTracks, Qt::QueuedConnection); reloadTimelineModels(); }); connect(&m_model, &MultitrackModel::aboutToClose, this, [&]() { setSelection(); disconnect(&m_model, &MultitrackModel::modified, this, &TimelineDock::clearSelectionIfInvalid); disconnect(&m_model, &MultitrackModel::appended, this, &TimelineDock::selectClip); disconnect(&m_model, &MultitrackModel::inserted, this, &TimelineDock::selectClip); disconnect(&m_model, &MultitrackModel::overWritten, this, &TimelineDock::selectClip); disconnect(&m_model, &MultitrackModel::rowsInserted, this, &TimelineDock::onRowsInserted); disconnect(&m_model, &MultitrackModel::rowsRemoved, this, &TimelineDock::onRowsRemoved); disconnect(&m_model, &MultitrackModel::rowsMoved, this, &TimelineDock::onRowsMoved); disconnect(&m_model, &MultitrackModel::noMoreEmptyTracks, this, &TimelineDock::onNoMoreEmptyTracks); }); connect(&m_model, &MultitrackModel::closed, this, [&]() { onMultitrackClosed(); reloadTimelineModels(); }); vboxLayout->addWidget(&m_quickView); connect(this, SIGNAL(clipMoved(int, int, int, int, bool)), SLOT(onClipMoved(int, int, int, int, bool)), Qt::QueuedConnection); connect(this, SIGNAL(transitionAdded(int, int, int, bool)), SLOT(onTransitionAdded(int, int, int, bool)), Qt::QueuedConnection); connect(MLT.videoWidget(), SIGNAL(frameDisplayed(const SharedFrame &)), this, SLOT(onShowFrame(const SharedFrame &))); connect(this, SIGNAL(topLevelChanged(bool)), this, SLOT(onTopLevelChanged(bool))); connect(this, SIGNAL(warnTrackLocked(int)), SLOT(onWarnTrackLocked())); connect(&m_markersModel, SIGNAL(rangesChanged()), this, SIGNAL(markerRangesChanged())); QWidget *dockContentsWidget = new QWidget(); dockContentsWidget->setLayout(vboxLayout); QDockWidget::setWidget(dockContentsWidget); LOG_DEBUG() << "end"; } TimelineDock::~TimelineDock() { } void TimelineDock::setupActions() { QIcon icon; QAction *action; action = new QAction(tr("Add Audio Track"), this); action->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_U)); connect(action, &QAction::triggered, this, [&]() { show(); raise(); addAudioTrack(); }); Actions.add("timelineAddAudioTrackAction", action); action = new QAction(tr("Add Video Track"), this); action->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_I)); connect(action, &QAction::triggered, this, [&]() { show(); raise(); addVideoTrack(); }); Actions.add("timelineAddVideoTrackAction", action); action = new QAction(tr("Insert Track"), this); action->setShortcut(QKeySequence(Qt::CTRL | Qt::ALT | Qt::Key_I)); connect(action, &QAction::triggered, this, [&]() { show(); raise(); insertTrack(); }); Actions.add("timelineInsertTrackAction", action); action = new QAction(tr("Remove Track"), this); action->setShortcut(QKeySequence(Qt::CTRL | Qt::ALT | Qt::Key_U)); connect(action, &QAction::triggered, this, [&]() { if (!isMultitrackValid()) return; show(); raise(); removeTrack(); }); Actions.add("timelineRemoveTrackAction", action); action = new QAction(tr("Move Track Up"), this); action->setShortcut(QKeySequence(Qt::SHIFT | Qt::ALT | Qt::Key_Up)); connect(action, &QAction::triggered, this, [&]() { if (!isMultitrackValid()) return; show(); raise(); moveTrackUp(); }); Actions.add("timelineMoveTrackUpAction", action); action = new QAction(tr("Move Track Down"), this); action->setShortcut(QKeySequence(Qt::SHIFT | Qt::ALT | Qt::Key_Down)); connect(action, &QAction::triggered, this, [&]() { if (!isMultitrackValid()) return; show(); raise(); moveTrackDown(); }); Actions.add("timelineMoveTrackDownAction", action); action = new QAction(tr("Show/Hide Selected Track"), this); #ifdef Q_OS_MAC // macOS uses Cmd+H to hide an app. action->setShortcut(QKeySequence(Qt::META | Qt::Key_H)); #else action->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_H)); #endif connect(action, &QAction::triggered, this, [&]() { if (!isMultitrackValid()) return; show(); raise(); toggleTrackHidden(currentTrack()); }); Actions.add("timelineToggleTrackHiddenAction", action); action = new QAction(tr("Lock/Unlock Selected Track"), this); #ifdef Q_OS_MAC // macOS uses Cmd+H to hide an app and Cmd+M to minimize. Therefore, we force // it to be the apple keyboard control key aka meta. Therefore, to be // consistent with all track header toggles, we make the lock toggle also use // meta. action->setShortcut(QKeySequence(Qt::META | Qt::Key_L)); #else action->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_L)); #endif connect(action, &QAction::triggered, this, [&]() { if (!isMultitrackValid()) return; show(); raise(); setTrackLock(currentTrack(), !isTrackLocked(currentTrack())); }); Actions.add("timelineToggleTrackLockedAction", action); action = new QAction(tr("Mute/Unmute Selected Track"), this); #ifdef Q_OS_MAC // macOS uses Cmd+M to minimize an app. action->setShortcut(QKeySequence(Qt::META | Qt::Key_M)); #else action->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_M)); #endif connect(action, &QAction::triggered, this, [&]() { if (!isMultitrackValid()) return; show(); raise(); toggleTrackMute(currentTrack()); }); Actions.add("timelineToggleTrackMuteAction", action); action = new QAction(tr("Blend/Unblend Selected Track"), this); action->setShortcut(QKeySequence(Qt::CTRL | Qt::ALT | Qt::Key_B)); connect(action, &QAction::triggered, this, [&]() { if (!isMultitrackValid()) return; show(); raise(); int trackIndex = currentTrack(); if (trackIndex != model()->bottomVideoTrackIndex()) { bool isComposite = model()->data(model()->index(trackIndex), MultitrackModel::IsCompositeRole).toBool(); setTrackComposite(trackIndex, !isComposite); } }); Actions.add("timelineToggleTrackBlendingAction", action); action = new QAction(tr("Make Tracks Shorter"), this); action->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_Minus)); connect(action, &QAction::triggered, this, [&]() { if (!isMultitrackValid() || !isVisible()) return; m_model.setTrackHeight(std::max(10, m_model.trackHeight() - 20)); }); Actions.add("timelineTracksShorterAction", action); action = new QAction(tr("Make Tracks Taller"), this); action->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_Plus)); connect(action, &QAction::triggered, this, [&]() { if (!isMultitrackValid() || !isVisible()) return; m_model.setTrackHeight(m_model.trackHeight() + 20); }); Actions.add("timelineTracksTallerAction", action); action = new QAction(tr("Reset Track Height"), this); action->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_Equal)); connect(action, &QAction::triggered, this, [&]() { if (!isMultitrackValid() || !isVisible()) return; m_model.setTrackHeight(50); }); Actions.add("timelineResetTrackHeightAction", action); action = new QAction(tr("Select All"), this); action->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_A)); connect(action, &QAction::triggered, this, [&]() { if (!isMultitrackValid()) return; show(); raise(); selectAll(); }); Actions.add("timelineSelectAllAction", action); action = new QAction(tr("Select All On Current Track"), this); action->setShortcut(QKeySequence(Qt::CTRL | Qt::ALT | Qt::Key_A)); connect(action, &QAction::triggered, this, [&]() { if (!isMultitrackValid()) return; show(); raise(); selectAllOnCurrentTrack(); }); Actions.add("timelineSelectAllOnTrackAction", action); action = new QAction(tr("Select None"), this); action->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_D)); connect(action, &QAction::triggered, this, [&]() { if (!isMultitrackValid()) return; show(); raise(); setSelection(); model()->reload(); }); Actions.add("timelineSelectNoneAction", action); action = new QAction(tr("Select Next Clip"), this); action->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_Right)); connect(action, &QAction::triggered, this, [&]() { if (!isMultitrackValid() || !isVisible()) return; if (selection().isEmpty()) { selectClipUnderPlayhead(); } else if (selection().size() == 1) { int newIndex = selection().first().x() + 1; if (newIndex < clipCount(-1)) setSelection(QList<QPoint>() << QPoint(newIndex, selection().first().y())); } }); Actions.add("timelineSelectNextClipAction", action); action = new QAction(tr("Select Previous Clip"), this); action->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_Left)); connect(action, &QAction::triggered, this, [&]() { if (!isMultitrackValid() || !isVisible()) return; if (selection().isEmpty()) { selectClipUnderPlayhead(); } else if (selection().size() == 1) { int newIndex = selection().first().x() - 1; if (newIndex >= 0) setSelection(QList<QPoint>() << QPoint(newIndex, selection().first().y())); } }); Actions.add("timelineSelectPrevClipAction", action); action = new QAction(tr("Select Clip Above"), this); action->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_Up)); connect(action, &QAction::triggered, this, [&]() { if (!isMultitrackValid() || !isVisible()) return; if (selection().isEmpty()) selectClipUnderPlayhead(); int newClipIndex = -1; int trackIndex = currentTrack() - 1; if (!selection().isEmpty() && trackIndex > -1 && !selection().isEmpty()) { int navigationPosition = centerOfClip(selection().first().y(), selection().first().x()); newClipIndex = clipIndexAtPosition(trackIndex, navigationPosition); } incrementCurrentTrack(-1); if (newClipIndex >= 0) { newClipIndex = qMin(newClipIndex, clipCount(trackIndex) - 1); setSelection(QList<QPoint>() << QPoint(newClipIndex, trackIndex)); } }); Actions.add("timelineSelectClipAboveAction", action); action = new QAction(tr("Select Clip Below"), this); action->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_Down)); connect(action, &QAction::triggered, this, [&]() { if (!isMultitrackValid() || !isVisible()) return; if (selection().isEmpty()) selectClipUnderPlayhead(); int newClipIndex = -1; int trackIndex = currentTrack() + 1; if (trackIndex < model()->trackList().count() && !selection().isEmpty()) { int navigationPosition = centerOfClip(selection().first().y(), selection().first().x()); newClipIndex = clipIndexAtPosition(trackIndex, navigationPosition); } incrementCurrentTrack(1); if (newClipIndex >= 0) { newClipIndex = qMin(newClipIndex, clipCount(trackIndex) - 1); setSelection(QList<QPoint>() << QPoint(newClipIndex, trackIndex)); } }); Actions.add("timelineSelectClipBelowAction", action); action = new QAction(tr("Set Current Track Above"), this); action->setShortcut(QKeySequence(Qt::CTRL | Qt::ALT | Qt::Key_Up)); connect(action, &QAction::triggered, this, [&]() { if (!isMultitrackValid() || !isVisible()) return; incrementCurrentTrack(-1); }); Actions.add("timelineCurrentTrackAboveAction", action); action = new QAction(tr("Set Current Track Below"), this); action->setShortcut(QKeySequence(Qt::CTRL | Qt::ALT | Qt::Key_Down)); connect(action, &QAction::triggered, this, [&]() { if (!isMultitrackValid() || !isVisible()) return; incrementCurrentTrack(1); }); Actions.add("timelineCurrentTrackBelowAction", action); action = new QAction(tr("Select Clip Under Playhead"), this); QList<QKeySequence> clipUnderPlayheadShortcuts; clipUnderPlayheadShortcuts << QKeySequence(Qt::CTRL | Qt::Key_Space); #ifdef Q_OS_MAC // Spotlight defaults to Cmd+Space, so also accept Ctrl+Space. clipUnderPlayheadShortcuts << QKeySequence(Qt::META | Qt::Key_Space); #endif action->setShortcuts(clipUnderPlayheadShortcuts); connect(action, &QAction::triggered, this, [&]() { if (!isMultitrackValid() || !isVisible()) return; selectClipUnderPlayhead(); }); Actions.add("timelineSelectClipUnderPlayheadAction", action); action = new QAction(tr("Cu&t"), this); action->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_X)); icon = QIcon::fromTheme("edit-cut", QIcon(":/icons/oxygen/32x32/actions/edit-cut.png")); action->setIcon(icon); action->setEnabled(false); connect(action, &QAction::triggered, this, [&]() { show(); raise(); removeSelection(true); }); connect(this, &TimelineDock::selectionChanged, action, [ = ]() { bool enabled = m_selection.selectedClips.length() > 0; if (enabled && !selection().isEmpty()) { int trackIndex = selection().first().y(); int clipIndex = selection().first().x(); enabled = !isBlank(trackIndex, clipIndex) && !isTransition(trackIndex, clipIndex); } action->setEnabled(enabled); }); Actions.add("timelineCutAction", action); action = new QAction(tr("&Copy"), this); QList<QKeySequence> copyShortcuts; copyShortcuts << QKeySequence(Qt::CTRL | Qt::Key_C); copyShortcuts << QKeySequence(Qt::Key_C); action->setShortcuts(copyShortcuts); icon = QIcon::fromTheme("edit-copy", QIcon(":/icons/oxygen/32x32/actions/edit-copy.png")); action->setIcon(icon); action->setEnabled(false); connect(action, &QAction::triggered, this, [&]() { show(); raise(); if (selection().isEmpty()) { copy(-1, -1); } else { auto &selected = selection().first(); copy(selected.y(), selected.x()); } }); connect(this, &TimelineDock::selectionChanged, action, [ = ]() { bool enabled = m_selection.selectedClips.length() > 0; if (enabled && !selection().isEmpty()) { int trackIndex = selection().first().y(); int clipIndex = selection().first().x(); enabled = !isBlank(trackIndex, clipIndex) && !isTransition(trackIndex, clipIndex); } action->setEnabled(enabled); }); Actions.add("timelineCopyAction", action); action = new QAction(tr("&Paste"), this); QList<QKeySequence> pasteShortcuts; pasteShortcuts << QKeySequence(Qt::CTRL | Qt::Key_V); pasteShortcuts << QKeySequence(Qt::Key_V); action->setShortcuts(pasteShortcuts); icon = QIcon::fromTheme("edit-paste", QIcon(":/icons/oxygen/32x32/actions/edit-paste.png")); action->setIcon(icon); connect(action, &QAction::triggered, this, [&]() { show(); raise(); insert(-1); }); Actions.add("timelinePasteAction", action); action = new QAction(tr("Nudge Forward"), this); action->setShortcut(QKeySequence(Qt::Key_Period)); action->setEnabled(false); connect(action, &QAction::triggered, this, [&]() { auto selectedClips = selection(); if (selectedClips.size() == 1) { int trackIndex = selectedClips.first().y(); int clipIndex = selectedClips.first().x(); bool valid = clipIndex > 0 && !isTransition(trackIndex, clipIndex) && !isBlank(trackIndex, clipIndex); if (valid && !Settings.timelineRipple()) { valid = (clipIndex == clipCount(trackIndex) - 1) || isBlank(trackIndex, clipIndex + 1); } if (!valid) { emit showStatusMessage(tr("Nudge Forward is not available")); return; } auto clipInfo = m_model.getClipInfo(trackIndex, clipIndex); moveClip(trackIndex, trackIndex, clipIndex, clipInfo->start + 1, Settings.timelineRipple()); } }); connect(this, &TimelineDock::selectionChanged, action, [ = ]() { auto selectedClips = selection(); bool enabled = selectedClips.size() == 1; if (enabled) { enabled = !isBlank(selectedClips.first().y(), selectedClips.first().x()) && !isTransition(selectedClips.first().y(), selectedClips.first().x()); } action->setEnabled(enabled); }); Actions.add("timelineNudgeForwardAction", action); action = new QAction(tr("Nudge Backward"), this); action->setShortcut(QKeySequence(Qt::Key_Comma)); action->setEnabled(false); connect(action, &QAction::triggered, this, [&]() { auto selectedClips = selection(); if (selectedClips.size() == 1) { int trackIndex = selectedClips.first().y(); int clipIndex = selectedClips.first().x(); if (clipIndex <= 0 || isTransition(trackIndex, clipIndex) || isBlank(trackIndex, clipIndex) || !isBlank(trackIndex, clipIndex - 1)) { emit showStatusMessage(tr("Nudge Backward is not available")); return; } auto clipInfo = m_model.getClipInfo(trackIndex, clipIndex); moveClip(trackIndex, trackIndex, clipIndex, clipInfo->start - 1, Settings.timelineRipple()); } }); connect(this, &TimelineDock::selectionChanged, action, [ = ]() { auto selectedClips = selection(); bool enabled = selectedClips.size() == 1; if (enabled) { enabled = !isBlank(selectedClips.first().y(), selectedClips.first().x()) && !isTransition(selectedClips.first().y(), selectedClips.first().x()); } action->setEnabled(enabled); }); Actions.add("timelineNudgeBackwardAction", action); action = new QAction(tr("Append"), this); action->setShortcut(QKeySequence(Qt::Key_A)); icon = QIcon::fromTheme("list-add", QIcon(":/icons/oxygen/32x32/actions/list-add.png")); action->setIcon(icon); connect(action, &QAction::triggered, this, [&]() { show(); raise(); append(currentTrack()); }); Actions.add("timelineAppendAction", action); action = new QAction(tr("Ripple Delete"), this); QList<QKeySequence> deleteShortcuts; deleteShortcuts << QKeySequence(Qt::Key_X); deleteShortcuts << QKeySequence(Qt::SHIFT | Qt::Key_Backspace); deleteShortcuts << QKeySequence(Qt::SHIFT | Qt::Key_Delete); action->setShortcuts(deleteShortcuts); icon = QIcon::fromTheme("list-remove", QIcon(":/icons/oxygen/32x32/actions/list-remove.png")); action->setIcon(icon); connect(action, &QAction::triggered, this, [&]() { if (!isMultitrackValid()) return; show(); raise(); removeSelection(); }); Actions.add("timelineDeleteAction", action); action = new QAction(tr("Lift"), this); action->setShortcut(QKeySequence(Qt::Key_Z)); QList<QKeySequence> liftShortcuts; liftShortcuts << QKeySequence(Qt::Key_Z); liftShortcuts << QKeySequence(Qt::Key_Backspace); liftShortcuts << QKeySequence(Qt::Key_Delete); action->setShortcuts(liftShortcuts); icon = QIcon::fromTheme("lift", QIcon(":/icons/oxygen/32x32/actions/lift.png")); action->setIcon(icon); connect(action, &QAction::triggered, this, [&]() { if (!isMultitrackValid()) return; show(); raise(); liftSelection(); }); Actions.add("timelineLiftAction", action); action = new QAction(tr("Overwrite"), this); action->setShortcut(QKeySequence(Qt::Key_B)); icon = QIcon::fromTheme("overwrite", QIcon(":/icons/oxygen/32x32/actions/overwrite.png")); action->setIcon(icon); connect(action, &QAction::triggered, this, [&]() { if (!isMultitrackValid()) return; show(); raise(); overwrite(currentTrack()); }); Actions.add("timelineOverwriteAction", action); action = new QAction(tr("Split At Playhead"), this); action->setShortcut(QKeySequence(Qt::Key_S)); icon = QIcon::fromTheme("slice", QIcon(":/icons/oxygen/32x32/actions/slice.png")); action->setIcon(icon); connect(action, &QAction::triggered, this, [&]() { if (!isMultitrackValid()) return; show(); raise(); int clipIndex = -1; int trackIndex = -1; std::vector<int> tracks; std::vector<int> clips; // First check if any clips are selected under the playhead QList<QPoint> selected = selection(); if (selected.size() > 0) { for (auto c : selected) { clipIndex = c.x(); trackIndex = c.y(); if (clipIndexAtPlayhead(trackIndex) == clipIndex && !isBlank(trackIndex, clipIndex) && !isTransition(trackIndex, clipIndex)) { auto info = m_model.getClipInfo(trackIndex, clipIndex); if (info && m_position > info->start && m_position < info->start + info->frame_count) { tracks.push_back(trackIndex); clips.push_back(clipIndex); } } } } // Next, choose a clip based on track selection if (tracks.size() == 0) { clipIndex = -1; trackIndex = currentTrack(); chooseClipAtPosition(m_position, trackIndex, clipIndex); if (trackIndex < 0 || clipIndex < 0) { return; } else if (isBlank(trackIndex, clipIndex)) { return; } else if (isTransition(trackIndex, clipIndex)) { emit showStatusMessage(tr("You cannot split a transition.")); return; } auto info = m_model.getClipInfo(trackIndex, clipIndex); if (info && m_position > info->start && m_position < info->start + info->frame_count) { setCurrentTrack(trackIndex); tracks.push_back(trackIndex); clips.push_back(clipIndex); } } if (tracks.size() > 0) { setSelection(); // Avoid filter views becoming out of sync MAIN.undoStack()->push(new Timeline::SplitCommand(m_model, tracks, clips, m_position)); } }); Actions.add("timelineSplitAction", action); action = new QAction(tr("Split All Tracks At Playhead"), this); action->setShortcut(QKeySequence(Qt::SHIFT | Qt::Key_S)); connect(action, &QAction::triggered, this, [&]() { if (!isMultitrackValid()) return; show(); raise(); std::vector<int> tracks; std::vector<int> clips; for (int trackIndex = 0; trackIndex < m_model.rowCount(); trackIndex++) { int clipIndex = clipIndexAtPosition(trackIndex, m_position); if (clipIndex < 0 || isBlank(trackIndex, clipIndex)) { continue; } if (isTransition(trackIndex, clipIndex)) { emit showStatusMessage(tr("You cannot split a transition.")); continue; } auto info = m_model.getClipInfo(trackIndex, clipIndex); if (info && m_position > info->start && m_position < info->start + info->frame_count) { tracks.push_back(trackIndex); clips.push_back(clipIndex); } } if (tracks.size() > 0) { setSelection(); // Avoid filter views becoming out of sync MAIN.undoStack()->push(new Timeline::SplitCommand(m_model, tracks, clips, m_position)); } }); Actions.add("timelineSplitAllTracksAction", action); action = new QAction(tr("Replace"), this); action->setShortcut(QKeySequence(Qt::Key_R)); connect(action, &QAction::triggered, this, [&]() { if (!isMultitrackValid()) return; show(); raise(); if (MLT.isClip() || selection().isEmpty()) { replace(-1, -1); } else { auto &selected = selection().first(); replace(selected.y(), selected.x()); } }); connect(this, &TimelineDock::selectionChanged, action, [ = ]() { action->setEnabled(m_selection.selectedClips.length() > 0); }); Actions.add("timelineReplaceAction", action); action = new QAction(tr("Create/Edit Marker"), this); action->setShortcut(QKeySequence(Qt::Key_M)); icon = QIcon::fromTheme("marker", QIcon(":/icons/oxygen/32x32/actions/marker.png")); action->setIcon(icon); connect(action, &QAction::triggered, this, [&]() { if (!isMultitrackValid()) return; show(); raise(); createOrEditMarker(); }); Actions.add("timelineMarkerAction", action); action = new QAction(tr("Previous Marker"), this); action->setShortcut(QKeySequence(Qt::Key_Less)); icon = QIcon::fromTheme("format-indent-less", QIcon(":/icons/oxygen/32x32/actions/format-indent-less.png")); action->setIcon(icon); connect(action, &QAction::triggered, this, [&]() { if (!isMultitrackValid()) return; show(); raise(); seekPrevMarker(); }); Actions.add("timelinePrevMarkerAction", action); action = new QAction(tr("Next Marker"), this); action->setShortcut(QKeySequence(Qt::Key_Greater)); icon = QIcon::fromTheme("format-indent-more", QIcon(":/icons/oxygen/32x32/actions/format-indent-more.png")); action->setIcon(icon); connect(action, &QAction::triggered, this, [&]() { if (!isMultitrackValid()) return; show(); raise(); seekNextMarker(); }); Actions.add("timelineNextMarkerAction", action); action = new QAction(tr("Delete Marker"), this); action->setShortcut(QKeySequence(Qt::CTRL | Qt::SHIFT | Qt::Key_M)); connect(action, &QAction::triggered, this, [&]() { if (!isMultitrackValid()) return; show(); raise(); deleteMarker(); }); Actions.add("timelineDeleteMarkerAction", action); action = new QAction(tr("Cycle Marker Color"), this); action->setShortcut(QKeySequence(Qt::CTRL | Qt::ALT | Qt::Key_M)); connect(action, &QAction::triggered, this, [&]() { int markerIndex = m_markersModel.markerIndexForPosition(m_position); if (markerIndex >= 0) { auto marker = m_markersModel.getMarker(markerIndex); auto allColors = m_markersModel.allColors(); int colorIndex = allColors.indexOf(marker.color); if (colorIndex >= 0) { colorIndex = (colorIndex + 1) % allColors.size(); m_markersModel.setColor(markerIndex, allColors[colorIndex]); } } }); Actions.add("timelineCycleMarkerColorAction", action); action = new QAction(tr("Create Marker Around Selected Clip"), this); action->setShortcut(QKeySequence(Qt::ALT | Qt::Key_M)); connect(action, &QAction::triggered, this, [&]() { if (!isMultitrackValid()) return; show(); raise(); createOrEditSelectionMarker(); }); Actions.add("timelineMarkSelectedClipAction", action); action = new QAction(tr("Rectangle Selection"), this); action->setCheckable(true); action->setChecked(Settings.timelineRectangleSelect()); connect(action, &QAction::triggered, this, [&](bool checked) { Settings.setTimelineRectangleSelect(checked); }); connect(&Settings, &ShotcutSettings::timelineRectangleSelectChanged, action, [ = ]() { action->setChecked(Settings.timelineRectangleSelect()); }); Actions.add("timelineRectangleSelectAction", action); action = new QAction(tr("Automatically Add Tracks"), this); action->setCheckable(true); action->setChecked(Settings.timelineAutoAddTracks()); connect(action, &QAction::triggered, this, [&](bool checked) { Settings.setTimelineAutoAddTracks(checked); }); connect(&Settings, &ShotcutSettings::timelineAutoAddTracksChanged, action, [ = ]() { action->setChecked(Settings.timelineAutoAddTracks()); }); Actions.add("timelineAutoAddTracksAction", action); action = new QAction(tr("Snap"), this); action->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_P)); icon = QIcon::fromTheme("snap", QIcon(":/icons/oxygen/32x32/actions/snap.png")); action->setIcon(icon); action->setCheckable(true); action->setChecked(Settings.timelineSnap()); connect(action, &QAction::triggered, this, [&](bool checked) { Settings.setTimelineSnap(checked); }); connect(&Settings, &ShotcutSettings::timelineSnapChanged, action, [ = ]() { action->setChecked(Settings.timelineSnap()); }); Actions.add("timelineSnapAction", action); action = new QAction(tr("Scrub While Dragging"), this); icon = QIcon::fromTheme("scrub_drag", QIcon(":/icons/oxygen/32x32/actions/scrub_drag.png")); action->setIcon(icon); action->setCheckable(true); action->setChecked(Settings.timelineDragScrub()); connect(action, &QAction::triggered, this, [&](bool checked) { Settings.setTimelineDragScrub(checked); }); connect(&Settings, &ShotcutSettings::timelineDragScrubChanged, action, [ = ]() { action->setChecked(Settings.timelineDragScrub()); }); Actions.add("timelineScrubDragAction", action); action = new QAction(tr("Ripple"), this); action->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_R)); icon = QIcon::fromTheme("target", QIcon(":/icons/oxygen/32x32/actions/target.png")); action->setIcon(icon); action->setCheckable(true); action->setChecked(Settings.timelineRipple()); connect(action, &QAction::triggered, this, [&](bool checked) { Settings.setTimelineRipple(checked); }); connect(&Settings, &ShotcutSettings::timelineRippleChanged, action, [ = ]() { action->setChecked(Settings.timelineRipple()); }); Actions.add("timelineRippleAction", action); action = new QAction(tr("Ripple All Tracks"), this); action->setShortcut(QKeySequence(Qt::CTRL | Qt::ALT | Qt::Key_R)); icon = QIcon::fromTheme("ripple-all", QIcon(":/icons/oxygen/32x32/actions/ripple-all.png")); action->setIcon(icon); action->setCheckable(true); action->setChecked(Settings.timelineRippleAllTracks()); connect(action, &QAction::triggered, this, [&](bool checked) { Settings.setTimelineRippleAllTracks(checked); }); connect(&Settings, &ShotcutSettings::timelineRippleAllTracksChanged, action, [ = ]() { action->setChecked(Settings.timelineRippleAllTracks()); }); Actions.add("timelineRippleAllTracksAction", action); action = new QAction(tr("Ripple Markers"), this); action->setShortcut(QKeySequence(Qt::ALT | Qt::Key_R)); icon = QIcon::fromTheme("ripple-marker", QIcon(":/icons/oxygen/32x32/actions/ripple-marker.png")); action->setIcon(icon); action->setCheckable(true); action->setChecked(Settings.timelineRippleMarkers()); connect(action, &QAction::triggered, this, [&](bool checked) { Settings.setTimelineRippleMarkers(checked); }); connect(&Settings, &ShotcutSettings::timelineRippleMarkersChanged, action, [ = ]() { action->setChecked(Settings.timelineRippleMarkers()); }); Actions.add("timelineRippleMarkersAction", action); action = new QAction(tr("Toggle Ripple And All Tracks"), this); action->setShortcut(QKeySequence(Qt::CTRL | Qt::SHIFT | Qt::Key_R)); connect(action, &QAction::triggered, this, [&]() { Settings.setTimelineRippleAllTracks(!Settings.timelineRipple()); Settings.setTimelineRipple(!Settings.timelineRipple()); }); Actions.add("timelineToggleRippleAndAllTracksAction", action); action = new QAction(tr("Toggle Ripple, All Tracks, And Markers"), this); action->setShortcut(QKeySequence(Qt::ALT | Qt::SHIFT | Qt::Key_R)); connect(action, &QAction::triggered, this, [&]() { Settings.setTimelineRippleAllTracks(!Settings.timelineRipple()); Settings.setTimelineRipple(!Settings.timelineRipple()); Settings.setTimelineRippleMarkers(!Settings.timelineRippleMarkers()); }); Actions.add("timelineToggleRippleAllTracksAndMarkersAction", action); action = new QAction(tr("Show Audio Waveforms"), this); action->setCheckable(true); action->setChecked(Settings.timelineShowWaveforms()); connect(action, &QAction::triggered, this, [&](bool checked) { Settings.setTimelineShowWaveforms(checked); if (!isVisible() || !m_quickView.rootObject()) return; emit refreshWaveforms(); }); connect(&Settings, &ShotcutSettings::timelineShowWaveformsChanged, action, [ = ]() { action->setChecked(Settings.timelineShowWaveforms()); }); Actions.add("timelineShowWaveformsAction", action); action = new QAction(tr("Use Higher Performance Waveforms"), this); action->setCheckable(true); action->setChecked(Settings.timelineFramebufferWaveform()); connect(action, &QAction::triggered, this, [&](bool checked) { Settings.setTimelineFramebufferWaveform(checked); if (!isVisible() || !m_quickView.rootObject()) return; if (Settings.timelineFramebufferWaveform()) { m_model.reload(); } }); connect(&Settings, &ShotcutSettings::timelineFramebufferWaveformChanged, action, [ = ]() { action->setChecked(Settings.timelineFramebufferWaveform()); }); Actions.add("timelinePerformanceWaveformsAction", action); action = new QAction(tr("Show Video Thumbnails"), this); action->setCheckable(true); action->setChecked(Settings.timelineShowThumbnails()); connect(action, &QAction::triggered, this, [&](bool checked) { Settings.setTimelineShowThumbnails(checked); }); connect(&Settings, &ShotcutSettings::timelineShowThumbnailsChanged, action, [ = ]() { action->setChecked(Settings.timelineShowThumbnails()); }); Actions.add("timelineShowThumbnailsAction", action); action = new QAction(tr("No"), this); action->setCheckable(true); action->setChecked(ShotcutSettings::TimelineScrolling::NoScrolling == Settings.timelineScrolling()); connect(action, &QAction::triggered, this, [&](bool checked) { Settings.setTimelineScrolling(ShotcutSettings::TimelineScrolling::NoScrolling); }); connect(&Settings, &ShotcutSettings::timelineScrollingChanged, action, [ = ]() { if (ShotcutSettings::TimelineScrolling::NoScrolling == Settings.timelineScrolling()) action->setChecked(true); }); Actions.add("timelineScrollingNo", action); action = new QAction(tr("Page"), this); action->setCheckable(true); action->setChecked(ShotcutSettings::TimelineScrolling::PageScrolling == Settings.timelineScrolling()); connect(action, &QAction::triggered, this, [&](bool checked) { Settings.setTimelineScrolling(ShotcutSettings::TimelineScrolling::PageScrolling); }); connect(&Settings, &ShotcutSettings::timelineScrollingChanged, action, [ = ]() { if (ShotcutSettings::TimelineScrolling::PageScrolling == Settings.timelineScrolling()) action->setChecked(true); }); Actions.add("timelineScrollingPage", action); action = new QAction(tr("Smooth"), this); action->setCheckable(true); action->setChecked(ShotcutSettings::TimelineScrolling::SmoothScrolling == Settings.timelineScrolling()); connect(action, &QAction::triggered, this, [&](bool checked) { Settings.setTimelineScrolling(ShotcutSettings::TimelineScrolling::SmoothScrolling); }); connect(&Settings, &ShotcutSettings::timelineScrollingChanged, action, [ = ]() { if (ShotcutSettings::TimelineScrolling::SmoothScrolling == Settings.timelineScrolling()) action->setChecked(true); }); Actions.add("timelineScrollingSmooth", action); action = new QAction(tr("Center the Playhead"), this); action->setShortcut(QKeySequence(Qt::CTRL | Qt::SHIFT | Qt::Key_P)); action->setCheckable(true); action->setChecked(ShotcutSettings::TimelineScrolling::CenterPlayhead == Settings.timelineScrolling()); connect(action, &QAction::triggered, this, [&](bool checked) { Settings.setTimelineScrolling(ShotcutSettings::TimelineScrolling::CenterPlayhead); }); connect(&Settings, &ShotcutSettings::timelineScrollingChanged, action, [ = ]() { if (ShotcutSettings::TimelineScrolling::CenterPlayhead == Settings.timelineScrolling()) action->setChecked(true); }); Actions.add("timelineScrollingCenterPlayhead", action); action = new QAction(tr("Scroll to Playhead on Zoom"), this); action->setShortcut(QKeySequence(Qt::CTRL | Qt::ALT | Qt::Key_P)); action->setCheckable(true); action->setChecked(Settings.timelineScrollZoom()); connect(action, &QAction::triggered, this, [&](bool checked) { Settings.setTimelineScrollZoom(checked); }); connect(&Settings, &ShotcutSettings::timelineScrollZoomChanged, action, [ = ]() { action->setChecked(Settings.timelineScrollZoom()); }); Actions.add("timelineScrollZoomAction", action); action = new QAction(tr("Zoom Timeline Out"), this); action->setShortcut(QKeySequence(Qt::Key_Minus)); icon = QIcon::fromTheme("zoom-out", QIcon(":/icons/oxygen/32x32/actions/zoom-out.png")); action->setIcon(icon); connect(action, &QAction::triggered, this, [&]() { if (!isVisible() || !m_quickView.rootObject()) return; emit zoomOut(); }); Actions.add("timelineZoomOutAction", action); action = new QAction(tr("Zoom Timeline In"), this); action->setShortcut(QKeySequence(Qt::Key_Plus)); icon = QIcon::fromTheme("zoom-in", QIcon(":/icons/oxygen/32x32/actions/zoom-in.png")); action->setIcon(icon); connect(action, &QAction::triggered, this, [&]() { if (!isVisible() || !m_quickView.rootObject()) return; emit zoomIn(); }); Actions.add("timelineZoomInAction", action); action = new QAction(tr("Zoom Timeline To Fit"), this); action->setShortcut(QKeySequence(Qt::Key_0)); icon = QIcon::fromTheme("zoom-fit-best", QIcon(":/icons/oxygen/32x32/actions/zoom-fit-best.png")); action->setIcon(icon); connect(action, &QAction::triggered, this, [&]() { if (!isVisible()) return; emit zoomToFit(); }); Actions.add("timelineZoomFitAction", action); action = new QAction(tr("Record Audio"), this); icon = QIcon::fromTheme("audio-input-microphone", QIcon(":/icons/oxygen/32x32/devices/audio-input-microphone.png")); action->setIcon(icon); action->setCheckable(true); action->setChecked(isRecording()); connect(action, &QAction::triggered, this, [&](bool checked) { if (isRecording()) stopRecording(); else recordAudio(); }); connect(this, &TimelineDock::isRecordingChanged, action, [ = ]() { action->setChecked(isRecording()); }); Actions.add("timelineRecordAudioAction", action); action = new QAction(tr("Properties"), this); connect(action, &QAction::triggered, this, [&](bool checked) { openProperties(); }); connect(this, &TimelineDock::selectionChanged, action, [ = ]() { action->setEnabled(!blankIsSelected()); }); Actions.add("timelinePropertiesAction", action); action = new QAction(tr("Rejoin With Next Clip"), this); action->setEnabled(false); connect(action, &QAction::triggered, this, [&](bool checked) { if (m_selection.selectedClips.length() == 1 && !selection().isEmpty()) { mergeClipWithNext(selection().first().y(), selection().first().x(), false); } }); connect(this, &TimelineDock::selectionChanged, action, [ = ]() { bool enabled = false; if (m_selection.selectedClips.length() == 1 && !selection().isEmpty()) { enabled = mergeClipWithNext(selection().first().y(), selection().first().x(), true); } action->setEnabled(enabled); }); Actions.add("timelineMergeWithNextAction", action); action = new QAction(tr("Detach Audio"), this); action->setEnabled(false); connect(action, &QAction::triggered, this, [&](bool checked) { if (m_selection.selectedClips.length() == 1 && !selection().isEmpty()) { detachAudio(selection().first().y(), selection().first().x()); } }); connect(this, &TimelineDock::selectionChanged, action, [ = ]() { bool enabled = false; if (m_selection.selectedClips.length() == 1 && !selection().isEmpty()) { int trackIndex = selection().first().y(); int clipIndex = selection().first().x(); if (trackIndex >= 0 && clipIndex >= 0) { QModelIndex modelIndex = m_model.index(clipIndex, 0, m_model.index(trackIndex)); if (modelIndex.isValid()) { enabled = !modelIndex.data(MultitrackModel::IsBlankRole).toBool() && !modelIndex.data(MultitrackModel::IsTransitionRole).toBool() && !modelIndex.data(MultitrackModel::IsAudioRole).toBool() && (modelIndex.data(MultitrackModel::AudioIndexRole).toInt() > -1 || modelIndex.data(MultitrackModel::AudioIndexRole).toString() == "all"); } } } action->setEnabled(enabled); }); Actions.add("timelineDetachAudioAction", action); action = new QAction(tr("Align To Reference Track"), this); action->setEnabled(false); connect(action, &QAction::triggered, this, [&](bool checked) { if (m_selection.selectedClips.length() > 0) { alignSelectedClips(); } }); connect(this, &TimelineDock::selectionChanged, action, [ = ]() { bool enabled = false; foreach (auto point, selection()) { // At least one selected item must be a valid clip if (!isBlank(point.y(), point.x()) && !isTransition(point.y(), point.x())) { enabled = true; break; } } action->setEnabled(enabled); }); Actions.add("timelineAlignToReferenceAction", action); action = new QAction(tr("Apply Copied Filters"), this); action->setEnabled(false); connect(action, &QAction::triggered, this, [&](bool checked) { if (m_selection.selectedClips.length() > 0) { applyCopiedFiltersToSelectdClips(); } }); connect(this, &TimelineDock::selectionChanged, action, [ = ]() { bool enabled = false; foreach (auto point, selection()) { // At least one selected item must be a valid clip if (!isBlank(point.y(), point.x()) && !isTransition(point.y(), point.x())) { enabled = true; break; } } if (enabled) { auto s = QGuiApplication::clipboard()->text(); enabled = s.contains(kShotcutFiltersClipboard); } action->setEnabled(enabled); }); Actions.add("timelineApplyCopiedFiltersAction", action); action = new QAction(tr("Update Thumbnails"), this); action->setEnabled(false); connect(action, &QAction::triggered, this, [&](bool checked) { foreach (auto point, selection()) { if (!isBlank(point.y(), point.x()) && !isTransition(point.y(), point.x())) { emit updateThumbnails(point.y(), point.x()); } } }); connect(this, &TimelineDock::selectionChanged, action, [ = ]() { bool enabled = false; if (Settings.timelineShowThumbnails()) { foreach (auto point, selection()) { // At least one selected item must be a valid clip if (!isBlank(point.y(), point.x()) && !isTransition(point.y(), point.x())) { enabled = true; break; } } } action->setEnabled(enabled); }); Actions.add("timelineUpdateThumbnailsAction", action); action = new QAction(tr("Rebuild Audio Waveform"), this); action->setEnabled(false); connect(action, &QAction::triggered, this, [&](bool checked) { foreach (auto point, selection()) { if (!isBlank(point.y(), point.x()) && !isTransition(point.y(), point.x())) { remakeAudioLevels(point.y(), point.x()); } } }); connect(this, &TimelineDock::selectionChanged, action, [ = ]() { bool enabled = false; if (Settings.timelineShowWaveforms()) { foreach (auto point, selection()) { // At least one selected item must be a valid clip if (!isBlank(point.y(), point.x()) && !isTransition(point.y(), point.x())) { enabled = true; break; } } } action->setEnabled(enabled); }); Actions.add("timelineRebuildAudioWaveformAction", action); action = new QAction(tr("Ripple Trim Clip In"), this); action->setShortcut(QKeySequence(Qt::SHIFT | Qt::Key_I)); connect(action, &QAction::triggered, this, [&](bool checked) { trimClipAtPlayhead(TimelineDock::TrimInPoint, true); }); Actions.add("timelineRippleTrimClipInAction", action); action = new QAction(tr("Ripple Trim Clip Out"), this); action->setShortcut(QKeySequence(Qt::SHIFT | Qt::Key_O)); connect(action, &QAction::triggered, this, [&](bool checked) { trimClipAtPlayhead(TimelineDock::TrimOutPoint, true); }); Actions.add("timelineRippleTrimClipOutAction", action); action = new QAction(tr("Group/Ungroup"), this); action->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_G)); action->setEnabled(false); connect(action, &QAction::triggered, this, [&](bool checked) { auto selectedClips = selection(); if (selectedClips.size() <= 1) { LOG_ERROR() << "Not enough clips selected" << selectedClips.size(); return; } auto firstClip = m_model.getClipInfo(selectedClips[0].y(), selectedClips[0].x()); if (firstClip->cut->property_exists(kShotcutGroupProperty)) { // First clip is in a group. Need to ungroup Timeline::UngroupCommand *ungroupCommand = new Timeline::UngroupCommand(m_model); foreach (auto point, selectedClips) { ungroupCommand->removeFromGroup(point.y(), point.x()); } MAIN.undoStack()->push(ungroupCommand); } else { // First clip is not in a group - group Timeline::GroupCommand *groupCommand = new Timeline::GroupCommand(m_model); foreach (auto point, selectedClips) { groupCommand->addToGroup(point.y(), point.x()); } MAIN.undoStack()->push(groupCommand); } }); connect(this, &TimelineDock::selectionChanged, action, [ = ]() { action->setEnabled(selection().size() > 1); }); Actions.add("timelineGroupAction", action); } int TimelineDock::addTrackIfNeeded(TrackType trackType) { // See if current track matches with no clips at playhead and beyond bool addTrack = true; auto trackIndex = currentTrack(); // Hunt for next available track while (addTrack && trackIndex >= 0 && trackIndex < m_model.trackList().size()) { auto clipIndex = clipIndexAtPosition(trackIndex, position()); if (clipIndex == -1 || (isBlank(trackIndex, clipIndex) && clipIndex >= clipCount(trackIndex) - 1)) { // This track is available if correct type addTrack = m_model.trackList().at(trackIndex).type != trackType; } if (addTrack) // Still looking trackIndex += (trackType == AudioTrackType) ? 1 : -1; } // Add track if needed if (addTrack) { trackIndex = (trackType == AudioTrackType) ? addAudioTrack() : addVideoTrack(); setCurrentTrack(trackIndex); } return trackIndex; } void TimelineDock::getSelectionRange(int *start, int *end) { auto selected = selection(); if (selected.isEmpty()) { *start = -1; *end = -1; return; } // Find the earliest start and the latest end in the selection *start = std::numeric_limits<int>::max(); *end = std::numeric_limits<int>::min(); for (const auto &clip : selected) { auto info = m_model.getClipInfo(clip.y(), clip.x()); if (info) { if (info->start < *start) { *start = info->start; } if ((info->start + info->frame_count) > *end) { *end = info->start + info->frame_count; } } } } void TimelineDock::setPosition(int position) { if (!m_model.tractor()) return; if (position <= m_model.tractor()->get_length()) { emit seeked(position); } else { m_position = m_model.tractor()->get_length(); emit positionChanged(m_position); } } Mlt::Producer TimelineDock::producerForClip(int trackIndex, int clipIndex) { Mlt::Producer result; auto info = m_model.getClipInfo(trackIndex, clipIndex); if (info) { result = Mlt::Producer(info->producer); } return result; } int TimelineDock::clipIndexAtPlayhead(int trackIndex) { return clipIndexAtPosition(trackIndex, m_position); } int TimelineDock::clipIndexAtPosition(int trackIndex, int position) { int result = -1; if (trackIndex < 0) trackIndex = currentTrack(); if (trackIndex >= 0 && trackIndex < m_model.trackList().size()) { int i = m_model.trackList().at(trackIndex).mlt_index; QScopedPointer<Mlt::Producer> track(m_model.tractor()->track(i)); if (track) { Mlt::Playlist playlist(*track); result = playlist.get_clip_index_at(position); if (result >= playlist.count()) result = -1; } } return result; } bool TimelineDock::isBlank(int trackIndex, int clipIndex) { return trackIndex >= 0 && clipIndex >= 0 && m_model.index(clipIndex, 0, m_model.index(trackIndex)) .data(MultitrackModel::IsBlankRole).toBool(); } bool TimelineDock::clipsAreSelected() { const QList<QPoint> &selection = m_selection.selectedClips; return selection.size() > 0 && !isBlank(selection[0].y(), selection[0].x()); } bool TimelineDock::blankIsSelected() { const QList<QPoint> &selection = m_selection.selectedClips; return selection.size() == 1 && isBlank(selection[0].y(), selection[0].x()); } bool TimelineDock::nothingIsSelected() { const QList<QPoint> &selection = m_selection.selectedClips; return selection.size() == 0 && !m_selection.isMultitrackSelected && m_selection.selectedTrack == -1; } bool TimelineDock::isTransition(int trackIndex, int clipIndex) { return trackIndex >= 0 && clipIndex >= 0 && m_model.index(clipIndex, 0, m_model.index(trackIndex)) .data(MultitrackModel::IsTransitionRole).toBool(); } void TimelineDock::onWarnTrackLocked() { emit showStatusMessage(tr("This track is locked")); } void TimelineDock::emitNonSeekableWarning() { emit showStatusMessage(tr("You cannot add a non-seekable source.")); } void TimelineDock::addTrackIfNeeded(int trackIndex, Mlt::Producer *srcTrack) { const auto n = m_model.trackList().size(); if (trackIndex >= n) { if (m_selection.selectedTrack != -1) setSelection(); if (srcTrack->get_int(kAudioTrackProperty) || (n > 0 && m_model.trackList()[n - 1].type == AudioTrackType)) { MAIN.undoStack()->push( new Timeline::InsertTrackCommand(m_model, trackIndex, AudioTrackType)); } else { MAIN.undoStack()->push( new Timeline::InsertTrackCommand(m_model, trackIndex, VideoTrackType)); } } } void TimelineDock::chooseClipAtPosition(int position, int &trackIndex, int &clipIndex) { QScopedPointer<Mlt::Producer> clip; // Start by checking for a hit at the specified track if (trackIndex != -1 && !isTrackLocked(trackIndex)) { clipIndex = clipIndexAtPosition(trackIndex, position); if (clipIndex != -1 && !isBlank(trackIndex, clipIndex)) return; } // Next we try the current track trackIndex = currentTrack(); clipIndex = qMin(clipIndexAtPosition(trackIndex, position), clipCount(trackIndex) - 1); if (!isTrackLocked(trackIndex) && clipIndex != -1 && !isBlank(trackIndex, clipIndex)) { return; } // if there was no hit, look through the other tracks for (trackIndex = 0; trackIndex < m_model.trackList().size(); (trackIndex)++) { if (trackIndex == currentTrack()) continue; if (isTrackLocked(trackIndex)) continue; clipIndex = clipIndexAtPosition(trackIndex, position); if (clipIndex != -1 && !isBlank(trackIndex, clipIndex)) return; } // As last resort choose blank on current track trackIndex = currentTrack(); if (!isTrackLocked(trackIndex)) { clipIndex = clipIndexAtPosition(trackIndex, position); if (clipIndex != -1) return; } trackIndex = -1; clipIndex = -1; } int TimelineDock::clipCount(int trackIndex) const { if (trackIndex < 0) trackIndex = currentTrack(); if (trackIndex >= 0 && trackIndex < m_model.trackList().size()) { int i = m_model.trackList().at(trackIndex).mlt_index; QScopedPointer<Mlt::Producer> track(m_model.tractor()->track(i)); if (track) { Mlt::Playlist playlist(*track); return playlist.count(); } } return 0; } void TimelineDock::setCurrentTrack(int currentTrack) { if (currentTrack != m_currentTrack) { m_currentTrack = currentTrack; emit currentTrackChanged(); } } int TimelineDock::currentTrack() const { return m_currentTrack; } void TimelineDock::setSelectionFromJS(const QVariantList &list) { QList<QPoint> points; for (const auto &v : list) { points << v.toPoint(); } setSelection(points); } void TimelineDock::setSelection(QList<QPoint> newSelection, int trackIndex, bool isMultitrack) { if (newSelection != selection() || trackIndex != m_selection.selectedTrack || isMultitrack != m_selection.isMultitrackSelected) { LOG_DEBUG() << "Changing selection to" << newSelection << " trackIndex" << trackIndex << "isMultitrack" << isMultitrack; m_selection.selectedClips = newSelection; m_selection.selectedTrack = trackIndex; m_selection.isMultitrackSelected = isMultitrack; // Save the selection in case it will be restored later due to a player tab change. m_savedSelectionUuids = selectionUuids(); m_selectionSignalTimer.start(); } } QVariantList TimelineDock::selectionForJS() const { QVariantList result; foreach (auto point, selection()) result << QVariant(point); return result; } const QList<QPoint> TimelineDock::selection() const { if (!m_quickView.rootObject()) return QList<QPoint>(); return m_selection.selectedClips; } const QVector<QUuid> TimelineDock::selectionUuids() { QVector<QUuid> result; for (const auto &clip : selection()) { auto info = m_model.getClipInfo(clip.y(), clip.x()); if (info && info->cut && info->cut->is_blank()) { result << MLT.ensureHasUuid(*info->cut); } else if (info && info->producer && info->producer->is_valid()) { result << MLT.ensureHasUuid(*info->producer); } } return result; } const QList<QPoint> TimelineDock::uuidsToSelection(QVector<QUuid> uuids) const { QList<QPoint> points; for (int trackIndex = 0; trackIndex < m_model.trackList().size() && uuids.size() > 0; trackIndex++) { int i = m_model.trackList().at(trackIndex).mlt_index; QScopedPointer<Mlt::Producer> track(m_model.tractor()->track(i)); if (track) { Mlt::Playlist playlist(*track); for (int clipIndex = 0; clipIndex < playlist.count() && uuids.size() > 0; clipIndex++) { Mlt::ClipInfo *info; if ((info = playlist.clip_info(clipIndex))) { for (int i = 0; i < uuids.size(); i++ ) { if (MLT.uuid(*info->producer) == uuids[i] || MLT.uuid(*info->cut) == uuids[i]) { points << QPoint(clipIndex, trackIndex); uuids.removeAt(i); break; } } delete info; } } } } return points; } void TimelineDock::saveAndClearSelection() { m_savedSelectedTrack = m_selection.selectedTrack; m_savedIsMultitrackSelected = m_selection.isMultitrackSelected; m_savedSelectionUuids = selectionUuids(); m_selection.selectedClips = QList<QPoint>(); m_selection.selectedTrack = -1; m_selection.isMultitrackSelected = false; emit selectionChanged(); } void TimelineDock::restoreSelection() { QList<QPoint> restoredSelection = uuidsToSelection(m_savedSelectionUuids); setSelection(restoredSelection, m_savedSelectedTrack, m_savedIsMultitrackSelected); } QVariantList TimelineDock::getGroupForClip(int trackIndex, int clipIndex) { QVariantList result; auto info = m_model.getClipInfo(trackIndex, clipIndex); if (!info || !info->cut) { return result; } if (!info->cut->property_exists(kShotcutGroupProperty)) { result << QPoint(clipIndex, trackIndex); } else { int group = info->cut->get_int(kShotcutGroupProperty); for (int trackIndex = 0; trackIndex < m_model.trackList().size(); trackIndex++) { int i = m_model.trackList().at(trackIndex).mlt_index; QScopedPointer<Mlt::Producer> track(m_model.tractor()->track(i)); if (track) { Mlt::Playlist playlist(*track); for (int clipIndex = 0; clipIndex < playlist.count(); clipIndex++) { QScopedPointer<Mlt::ClipInfo> info(playlist.clip_info(clipIndex)); if (info && info->cut && info->cut->property_exists(kShotcutGroupProperty) && info->cut->get_int(kShotcutGroupProperty) == group) { result << QPoint(clipIndex, trackIndex); } } } } } return result; } void TimelineDock::selectClipUnderPlayhead() { int track = -1, clip = -1; chooseClipAtPosition(m_position, track, clip); if (clip == -1) { if (isTrackLocked(currentTrack())) { emit warnTrackLocked(currentTrack()); return; } int idx = clipIndexAtPlayhead(-1); if (idx == -1) setSelection(); else setSelection(QList<QPoint>() << QPoint(idx, track)); return; } if (track != -1) { setCurrentTrack(track); setSelection(QList<QPoint>() << QPoint(clip, track)); } } int TimelineDock::centerOfClip(int trackIndex, int clipIndex) { auto clip = m_model.getClipInfo(trackIndex, clipIndex); return clip ? clip->start + clip->frame_count / 2 : -1; } bool TimelineDock::isTrackLocked(int trackIndex) const { if (trackIndex < 0 || trackIndex >= m_model.trackList().size()) return false; int i = m_model.trackList().at(trackIndex).mlt_index; QScopedPointer<Mlt::Producer> track(m_model.tractor()->track(i)); return track->get_int(kTrackLockProperty); } void TimelineDock::trimClipAtPlayhead(TrimLocation location, bool ripple) { int trackIndex = currentTrack(), clipIndex = -1; chooseClipAtPosition(m_position, trackIndex, clipIndex); if (trackIndex < 0 || clipIndex < 0) return; setCurrentTrack(trackIndex); int i = m_model.trackList().at(trackIndex).mlt_index; QScopedPointer<Mlt::Producer> track(m_model.tractor()->track(i)); if (!track) return; auto info = m_model.getClipInfo(trackIndex, clipIndex); if (!info) return; if (location == TrimInPoint) { MAIN.undoStack()->push( new Timeline::TrimClipInCommand(m_model, m_markersModel, trackIndex, clipIndex, m_position - info->start, ripple)); if (ripple) setPosition(info->start); if (m_updateCommand && m_updateCommand->trackIndex() == trackIndex && m_updateCommand->clipIndex() == clipIndex) m_updateCommand->setPosition(trackIndex, clipIndex, m_updateCommand->position() + m_position - info->start); emit MAIN.serviceInChanged(m_position - info->start, info->producer); } else { MAIN.undoStack()->push( new Timeline::TrimClipOutCommand(m_model, m_markersModel, trackIndex, clipIndex, info->start + info->frame_count - m_position, ripple)); if (m_updateCommand && m_updateCommand->trackIndex() == trackIndex && m_updateCommand->clipIndex() == clipIndex) m_updateCommand->setPosition(trackIndex, clipIndex, -1); } } void TimelineDock::openProperties() { MAIN.onPropertiesDockTriggered(true); } void TimelineDock::emitSelectedChanged(const QVector<int> &roles) { if (selection().isEmpty()) return; auto point = selection().first(); auto index = model()->makeIndex(point.y(), point.x()); emit model()->dataChanged(index, index, roles); } void TimelineDock::clearSelectionIfInvalid() { QList<QPoint> newSelection; foreach (auto clip, selection()) { if (clip.x() >= clipCount(clip.y())) continue; newSelection << QPoint(clip.x(), clip.y()); } setSelection(newSelection); } void TimelineDock::insertTrack() { if (m_selection.selectedTrack != -1) setSelection(); MAIN.undoStack()->push( new Timeline::InsertTrackCommand(m_model, currentTrack())); } void TimelineDock::insertAudioTrack() { if (m_selection.selectedTrack != -1) setSelection(); MAIN.undoStack()->push( new Timeline::InsertTrackCommand(m_model, currentTrack(), AudioTrackType)); } void TimelineDock::insertVideoTrack() { if (m_selection.selectedTrack != -1) setSelection(); MAIN.undoStack()->push( new Timeline::InsertTrackCommand(m_model, currentTrack(), VideoTrackType)); } void TimelineDock::removeTrack() { if (m_model.trackList().size() > 0) { int trackIndex = currentTrack(); MAIN.undoStack()->push( new Timeline::RemoveTrackCommand(m_model, trackIndex)); if (trackIndex >= m_model.trackList().count()) setCurrentTrack(m_model.trackList().count() - 1); } } void TimelineDock::moveTrack(int fromTrackIndex, int toTrackIndex) { const TrackList &trackList = m_model.trackList(); if (fromTrackIndex >= trackList.size()) { LOG_DEBUG() << "From track index out of bounds" << fromTrackIndex; return; } if (toTrackIndex >= trackList.size()) { LOG_DEBUG() << "To track index out of bounds" << toTrackIndex; return; } if (trackList[fromTrackIndex].type != trackList[toTrackIndex].type) { LOG_DEBUG() << "From/To track types do not match"; return; } MAIN.undoStack()->push(new Timeline::MoveTrackCommand(m_model, fromTrackIndex, toTrackIndex)); setCurrentTrack(toTrackIndex); } void TimelineDock::moveTrackUp() { int trackIndex = currentTrack(); const TrackList &trackList = m_model.trackList(); if (trackIndex >= trackList.size()) { LOG_DEBUG() << "Track Index out of bounds" << trackIndex; return; } if (trackList[trackIndex].type == VideoTrackType) { bool topVideo = true; foreach (const Track &t, trackList) { if (t.type == VideoTrackType && t.number > trackList[trackIndex].number) { topVideo = false; break; } } if (topVideo) { MAIN.showStatusMessage(tr("Track %1 was not moved").arg(m_model.getTrackName(trackIndex))); return; } } if (trackList[trackIndex].number == 0 && trackList[trackIndex].type == AudioTrackType) { MAIN.showStatusMessage(tr("Can not move audio track above video track")); return; } MAIN.undoStack()->push(new Timeline::MoveTrackCommand(m_model, trackIndex, trackIndex - 1)); setCurrentTrack(trackIndex - 1); } void TimelineDock::moveTrackDown() { int trackIndex = currentTrack(); const TrackList &trackList = m_model.trackList(); if (trackIndex >= trackList.size()) { LOG_DEBUG() << "Track Index out of bounds" << trackIndex; return; } if (trackList[trackIndex].number == 0 && trackList[trackIndex].type == VideoTrackType) { MAIN.showStatusMessage(tr("Can not move video track below audio track")); return; } if (trackList[trackIndex].type == AudioTrackType) { bool bottomAudio = true; foreach (const Track &t, trackList) { if (t.type == AudioTrackType && t.number > trackList[trackIndex].number) { bottomAudio = false; break; } } if (bottomAudio) { MAIN.showStatusMessage(tr("Track %1 was not moved").arg(m_model.getTrackName(trackIndex))); return; } } MAIN.undoStack()->push(new Timeline::MoveTrackCommand(m_model, trackIndex, trackIndex + 1)); setCurrentTrack(trackIndex + 1); } bool TimelineDock::mergeClipWithNext(int trackIndex, int clipIndex, bool dryrun) { if (dryrun) return m_model.mergeClipWithNext(trackIndex, clipIndex, true); MAIN.undoStack()->push( new Timeline::MergeCommand(m_model, trackIndex, clipIndex)); return true; } void TimelineDock::onProducerChanged(Mlt::Producer *after) { int trackIndex = currentTrack(); if (trackIndex < 0 || selection().isEmpty() || !m_updateCommand || !after || !after->is_valid()) return; if (!selection().isEmpty()) trackIndex = selection().first().y(); if (isTrackLocked(trackIndex)) { emit warnTrackLocked(trackIndex); return; } auto resetRippleAll = true; int i = m_model.trackList().at(trackIndex).mlt_index; QScopedPointer<Mlt::Producer> track(m_model.tractor()->track(i)); if (track) { // Ensure the new XML has same in/out point as selected clip by making // a copy of the changed producer and copying the in/out from timeline. Mlt::Playlist playlist(*track); int clipIndex = selection().first().x(); QScopedPointer<Mlt::ClipInfo> info(playlist.clip_info(clipIndex)); if (info) { QString oldServiceName = info->producer->get("mlt_service"); QString newServiceName = after->get("mlt_service"); if (oldServiceName == "timewarp" || newServiceName == "timewarp") { double oldSpeed = oldServiceName != "timewarp" ? 1.0 : info->producer->get_double("warp_speed"); double newSpeed = newServiceName != "timewarp" ? 1.0 : after->get_double("warp_speed"); double speedRatio = oldSpeed / newSpeed; int length = qRound(info->length * speedRatio); int in = qMin(qRound(info->frame_in * speedRatio), length - 1); int out = qMin(qRound(info->frame_out * speedRatio), length - 1); if (!Settings.timelineRipple() && (clipIndex + 1) < playlist.count()) { // limit the out point to what fits before the next clip if (playlist.is_blank(clipIndex + 1)) { out = qMin(out, in + info->frame_count - 1 + playlist.clip_length(clipIndex + 1)); } else { out = qMin(out, in + info->frame_count - 1); } } after->set_in_and_out(in, out); // Adjust filters. int n = after->filter_count(); for (int j = 0; j < n; j++) { QScopedPointer<Mlt::Filter> filter(after->filter(j)); if (filter && filter->is_valid() && !filter->get_int("_loader") && !filter->get_int(kShotcutHiddenProperty)) { in = qMin(qRound(filter->get_in() * speedRatio), length - 1); out = qMin(qRound(filter->get_out() * speedRatio), length - 1); filter->set_in_and_out(in, out); //TODO: keyframes } } resetRippleAll = false; } else if (newServiceName == "qimage" || newServiceName == "pixbuf") { int oldLength = info->frame_out - info->frame_in; int newLength = after->get_out() - after->get_in(); int lengthDelta = newLength - oldLength; if (lengthDelta != 0) { int in = after->get_in(); int out = after->get_out(); if (!Settings.timelineRipple() && (clipIndex + 1) < playlist.count()) { // limit the out point to what fits before the next clip if (playlist.is_blank(clipIndex + 1)) { out = qMin(out, in + info->frame_count - 1 + playlist.clip_length(clipIndex + 1)); } else { out = qMin(out, in + info->frame_count - 1); } } after->set_in_and_out(in, out); // Adjust filters. int n = after->filter_count(); for (int j = 0; j < n; j++) { QScopedPointer<Mlt::Filter> filter(after->filter(j)); if (filter && filter->is_valid() && !filter->get_int("_loader") && !filter->get_int(kShotcutHiddenProperty)) { in = qMin(filter->get_in(), newLength - 1); out = qMin(filter->get_out() + lengthDelta, newLength - 1); filter->set_in_and_out(in, out); //TODO: keyframes } } } } else { after->set_in_and_out(info->frame_in, info->frame_out); } } } QString xmlAfter = MLT.XML(after); m_updateCommand->setXmlAfter(xmlAfter); if (resetRippleAll) m_updateCommand->setRippleAllTracks(false); setSelection(); // clearing selection prevents a crash MAIN.undoStack()->push(m_updateCommand.release()); } int TimelineDock::addAudioTrack() { if (m_selection.selectedTrack != -1) setSelection(); MAIN.undoStack()->push( new Timeline::AddTrackCommand(m_model, false)); return m_model.trackList().size() - 1; } int TimelineDock::addVideoTrack() { if (m_selection.selectedTrack != -1) setSelection(); MAIN.undoStack()->push( new Timeline::AddTrackCommand(m_model, true)); return 0; } void TimelineDock::alignSelectedClips() { auto selection = selectionUuids(); saveAndClearSelection(); AlignAudioDialog dialog(tr("Align To Reference Track"), &m_model, selection, this); dialog.exec(); restoreSelection(); } void TimelineDock::applyCopiedFiltersToSelectdClips() { QString xmlToUse = QGuiApplication::clipboard()->text(); if (MLT.isMltXml(xmlToUse) && xmlToUse.contains(kShotcutFiltersClipboard)) { if (!Settings.proxyEnabled()) { ProxyManager::filterXML(xmlToUse, ""); } } else { LOG_DEBUG() << "Unable to read copied filters" << xmlToUse; return; } Timeline::ApplyFiltersCommand *command = new Timeline::ApplyFiltersCommand(m_model, xmlToUse); foreach (auto i, m_selection.selectedClips) { if (!isBlank(i.y(), i.x()) && !isTransition(i.y(), i.x())) { command->addClip(i.y(), i.x()); } } MAIN.undoStack()->push(command); } void TimelineDock::onShowFrame(const SharedFrame &frame) { if (m_ignoreNextPositionChange) { m_ignoreNextPositionChange = false; } else if (MLT.isMultitrack() && m_position != frame.get_position() && m_model.tractor()) { m_position = qMin(frame.get_position(), m_model.tractor()->get_length()); emit positionChanged(m_position); } } void TimelineDock::onSeeked(int position) { if (MLT.isMultitrack() && m_position != position) { m_position = qMin(position, m_model.tractor()->get_length()); emit positionChanged(m_position); } } static bool isSystemClipboardValid(const QString &xml) { return MLT.isMltXml(xml) && MAIN.isClipboardNewer() && !xml.contains(kShotcutFiltersClipboard); } void TimelineDock::append(int trackIndex) { if (trackIndex < 0) trackIndex = currentTrack(); if (isTrackLocked(trackIndex)) { emit warnTrackLocked(trackIndex); return; } if (MAIN.isSourceClipMyProject()) return; // Use MLT XML on the clipboard if it exists and is newer than source clip. QString xmlToUse = QGuiApplication::clipboard()->text(); if (isSystemClipboardValid(xmlToUse)) { if (!Settings.proxyEnabled()) { ProxyManager::filterXML(xmlToUse, ""); } } else { xmlToUse.clear(); } if (MLT.isSeekableClip() || MLT.savedProducer() || !xmlToUse.isEmpty()) { Mlt::Producer producer; if (xmlToUse.isEmpty()) { Mlt::Producer producer(MLT.isClip() ? MLT.producer() : MLT.savedProducer()); ProxyManager::generateIfNotExists(producer); xmlToUse = MLT.XML(&producer); } else { producer = Mlt::Producer(MLT.profile(), "xml-string", xmlToUse.toUtf8().constData()); } if (xmlToUse.isEmpty()) { return; } // Insert multiple if the XML is a <tractor> with child <property name="shotcut">1</property> // No need to create a track in an empty timeline. // This can be a macro of QUndoCommands. if (producer.is_valid() && producer.type() == mlt_service_tractor_type && producer.get_int(kShotcutXmlProperty)) { Mlt::Tractor tractor(producer); Mlt::ClipInfo info; MAIN.undoStack()->beginMacro(tr("Append multiple to timeline")); Mlt::Controller::RefreshBlocker blocker; // Loop over each source track for (int mltTrackIndex = 0; mltTrackIndex < tractor.count(); mltTrackIndex++) { QScopedPointer<Mlt::Producer> srcTrack(tractor.track(mltTrackIndex)); if (srcTrack) { const auto trackIndex = currentTrack() + mltTrackIndex; addTrackIfNeeded(trackIndex, srcTrack.get()); // Insert the clips for this track Mlt::Playlist playlist(*srcTrack); for (int mltClipIndex = 0; mltClipIndex < playlist.count(); mltClipIndex++) { if (!playlist.is_blank(mltClipIndex)) { playlist.clip_info(mltClipIndex, &info); Mlt::Producer clip(info.producer); clip.set_in_and_out(info.frame_in, info.frame_out); bool lastClip = mltTrackIndex == tractor.count() - 1 && mltClipIndex == playlist.count() - 1; MAIN.undoStack()->push( new Timeline::AppendCommand(m_model, trackIndex, MLT.XML(&clip), false, lastClip)); } } } } MAIN.undoStack()->endMacro(); MLT.refreshConsumer(); } else { if (m_model.trackList().size() == 0) { addVideoTrack(); } MAIN.undoStack()->push( new Timeline::AppendCommand(m_model, trackIndex, xmlToUse)); } if (m_position < 0) { // This happens when pasting in a new session MAIN.openCut(new Mlt::Producer(m_model.tractor())); } } else if (!MLT.isSeekableClip()) { emitNonSeekableWarning(); } } void TimelineDock::remove(int trackIndex, int clipIndex, bool ignoreTransition) { if (!m_model.trackList().count()) return; if (isTrackLocked(trackIndex)) { emit warnTrackLocked(trackIndex); return; } if (trackIndex < 0 || clipIndex < 0) return; if (!ignoreTransition && isTransition(trackIndex, clipIndex)) { MAIN.undoStack()->beginMacro(tr("Ripple delete transition")); auto info = m_model.getClipInfo(trackIndex, clipIndex); MAIN.undoStack()->push( new Timeline::RemoveCommand(m_model, m_markersModel, trackIndex, clipIndex)); if (clipIndex > 0 && info->producer && info->producer->is_valid()) { // verify the clip after belongs to transition Mlt::Tractor transition(*info->producer); std::unique_ptr<Mlt::Producer> transitionClip(transition.track(1)); auto neighborClip = producerForClip(trackIndex, clipIndex); if (neighborClip.is_valid() && transitionClip && neighborClip.same_clip(*transitionClip)) MAIN.undoStack()->push( new Timeline::TrimClipInCommand(m_model, m_markersModel, trackIndex, clipIndex, -info->frame_count, true)); // verify the clip before belongs to transition transitionClip.reset(transition.track(0)); neighborClip = producerForClip(trackIndex, clipIndex - 1); if (neighborClip.is_valid() && transitionClip && neighborClip.same_clip(*transitionClip)) MAIN.undoStack()->push( new Timeline::TrimClipOutCommand(m_model, m_markersModel, trackIndex, clipIndex - 1, -info->frame_count, true)); } MAIN.undoStack()->endMacro(); } else { Mlt::Producer clip = producerForClip(trackIndex, clipIndex); if (clip.is_valid()) { MAIN.undoStack()->push( new Timeline::RemoveCommand(m_model, m_markersModel, trackIndex, clipIndex)); } } } void TimelineDock::lift(int trackIndex, int clipIndex, bool ignoreTransition) { if (!m_model.trackList().count()) return; if (isTrackLocked(trackIndex)) { emit warnTrackLocked(trackIndex); return; } if (trackIndex < 0 || clipIndex < 0) return; if (!ignoreTransition && isTransition(trackIndex, clipIndex)) { MAIN.undoStack()->beginMacro(tr("Lift transition")); auto info = m_model.getClipInfo(trackIndex, clipIndex); if (clipIndex > 0 && clipIndex + 1 < m_model.rowCount(m_model.index(trackIndex)) && info->producer && info->producer->is_valid()) { // verify the clip after belongs to transition Mlt::Tractor transition(*info->producer); std::unique_ptr<Mlt::Producer> transitionClip(transition.track(1)); auto clipBefore = producerForClip(trackIndex, clipIndex - 1); auto clipAfter = producerForClip(trackIndex, clipIndex + 1); auto duration = info->frame_count; MAIN.undoStack()->push( new Timeline::LiftCommand(m_model, trackIndex, clipIndex)); if (clipBefore.is_valid() && clipAfter.is_valid() && !clipBefore.is_blank() && !clipAfter.is_blank()) duration /= 2; if (clipAfter.is_valid() && transitionClip && clipAfter.same_clip(*transitionClip)) MAIN.undoStack()->push( new Timeline::TrimClipInCommand(m_model, m_markersModel, trackIndex, clipIndex + (clipBefore.is_blank() ? 0 : 1), -duration, false)); // verify the clip before belongs to transition transitionClip.reset(transition.track(0)); if (duration < info->frame_count) duration += info->frame_count % 2; if (clipBefore.is_valid() && transitionClip && clipBefore.same_clip(*transitionClip)) MAIN.undoStack()->push( new Timeline::TrimClipOutCommand(m_model, m_markersModel, trackIndex, clipIndex - 1, -duration, false)); } else { MAIN.undoStack()->push( new Timeline::LiftCommand(m_model, trackIndex, clipIndex)); } MAIN.undoStack()->endMacro(); } else { Mlt::Producer clip(producerForClip(trackIndex, clipIndex)); if (clip.is_valid()) { if (clip.is_blank()) return; MAIN.undoStack()->push( new Timeline::LiftCommand(m_model, trackIndex, clipIndex)); setSelection(); } } } void TimelineDock::removeSelection(bool withCopy) { if (isTrackLocked(currentTrack())) { emit warnTrackLocked(currentTrack()); return; } if (selection().isEmpty()) selectClipUnderPlayhead(); if (selection().isEmpty() || currentTrack() < 0) return; // Cut if (withCopy) { auto clip = selection().first(); copy(clip.y(), clip.x()); if (selection().size() < 2) { remove(clip.y(), clip.x(), false); return; } } // Ripple delete int n = selection().size(); if (n > 1) { if (withCopy) MAIN.undoStack()->beginMacro(tr("Cut %1 from timeline").arg(n)); else MAIN.undoStack()->beginMacro(tr("Remove %1 from timeline").arg(n)); } int trackIndex, clipIndex; for (const auto &uuid : selectionUuids()) { m_model.findClipByUuid(uuid, trackIndex, clipIndex); remove(trackIndex, clipIndex, n > 1); } if (n > 1) MAIN.undoStack()->endMacro(); } void TimelineDock::liftSelection() { if (isTrackLocked(currentTrack())) { emit warnTrackLocked(currentTrack()); return; } if (selection().isEmpty()) selectClipUnderPlayhead(); if (selection().isEmpty()) return; int n = selection().size(); if (n > 1) MAIN.undoStack()->beginMacro(tr("Lift %1 from timeline").arg(n)); int trackIndex, clipIndex; for (const auto &uuid : selectionUuids()) { m_model.findClipByUuid(uuid, trackIndex, clipIndex); lift(trackIndex, clipIndex, n > 1); } if (n > 1) MAIN.undoStack()->endMacro(); } void TimelineDock::incrementCurrentTrack(int by) { int newTrack = currentTrack(); if (by < 0) newTrack = qMax(0, newTrack + by); else newTrack = qMin(m_model.trackList().size() - 1, newTrack + by); setCurrentTrack(newTrack); } void TimelineDock::selectTrackHead(int trackIndex) { if (trackIndex >= 0) { setSelection(QList<QPoint>(), trackIndex); } } void TimelineDock::selectMultitrack() { setSelection(QList<QPoint>(), -1, true); } template<typename T> static void insertSorted(std::vector<T> &vec, T const &item) { vec.insert(std::upper_bound(vec.begin(), vec.end(), item), item); } void TimelineDock::copy(int trackIndex, int clipIndex) { auto selected = selection(); if (selected.size() < 2) { if (trackIndex < 0) trackIndex = currentTrack(); if (clipIndex < 0) clipIndex = clipIndexAtPlayhead(trackIndex); Q_ASSERT(trackIndex >= 0 && clipIndex >= 0); auto info = m_model.getClipInfo(trackIndex, clipIndex); if (info) { QString xml = MLT.XML(info->producer); Mlt::Producer p(MLT.profile(), "xml-string", xml.toUtf8().constData()); p.set_speed(0); p.seek(info->frame_in); p.set_in_and_out(info->frame_in, info->frame_out); MLT.setSavedProducer(&p); QGuiApplication::clipboard()->setText(MLT.XML(&p)); emit clipCopied(); } } else { // Determine the track indices auto minY = std::numeric_limits<int>::max(); auto maxY = -1; auto minStart = std::numeric_limits<int>::max(); for (auto &a : selected) { minY = std::min(minY, a.y()); maxY = std::max(maxY, a.y()); auto info = m_model.getClipInfo(a.y(), a.x()); if (info) minStart = std::min(minStart, info->start); } // Create the tracks Mlt::Tractor tractor(MLT.profile()); tractor.set(kShotcutXmlProperty, 1); for (int trackIndex = minY, i = 0; trackIndex <= maxY; trackIndex++, i++) { Mlt::Playlist playlist(MLT.profile()); if (m_model.trackList()[trackIndex].type == AudioTrackType) { playlist.set("hide", 1); playlist.set(kAudioTrackProperty, 1); } else { playlist.set(kVideoTrackProperty, 1); } tractor.set_track(playlist, i); // Sort all the clips on this track std::vector<int> clipIndices; for (auto &a : selected) { if (a.y() == trackIndex) { clipIndices.insert(std::upper_bound(clipIndices.begin(), clipIndices.end(), a.x()), a.x()); } } // Add the clips to the tracks if (clipIndices.size() > 0) { int prevEnd = minStart; auto mlt_index = m_model.trackList()[trackIndex].mlt_index; QScopedPointer<Mlt::Producer> sourceTrack(m_model.tractor()->track(mlt_index)); if (sourceTrack) { Mlt::Playlist sourcePlaylist(*sourceTrack); Mlt::ClipInfo info; for (auto clipIndex : clipIndices) { sourcePlaylist.clip_info(clipIndex, &info); playlist.blank(info.start - prevEnd - 1); playlist.append(*info.producer, info.frame_in, info.frame_out); prevEnd = info.start + info.frame_count; } } } } // Put XML in clipboard QGuiApplication::clipboard()->setText(MLT.XML(&tractor)); } } void TimelineDock::emitSelectedFromSelection() { if (!m_model.trackList().count()) { if (m_model.tractor()) selectMultitrack(); else emit selected(nullptr); return; } for (auto &clip : selection()) { // We need to set these special properties so time-based filters // can get information about the cut while still applying filters // to the cut parent. int trackIndex = clip.y(); int clipIndex = clip.x(); auto info = m_model.getClipInfo(trackIndex, clipIndex); if (!info) continue; auto info2 = m_model.getClipInfo(trackIndex, clipIndex - 1); if (info2 && info2->producer && info2->producer->is_valid() && info2->producer->get(kShotcutTransitionProperty)) { // Factor in a transition left of the clip. info->producer->set(kFilterInProperty, info->frame_in - info2->frame_count); info->producer->set(kPlaylistStartProperty, info2->start); } else { info->producer->set(kFilterInProperty, info->frame_in); info->producer->set(kPlaylistStartProperty, info->start); } info2 = m_model.getClipInfo(trackIndex, clipIndex + 1); if (info2 && info2->producer && info2->producer->is_valid() && info2->producer->get(kShotcutTransitionProperty)) { // Factor in a transition right of the clip. info->producer->set(kFilterOutProperty, info->frame_out + info2->frame_count); } else { info->producer->set(kFilterOutProperty, info->frame_out); } info->producer->set(kMultitrackItemProperty, QStringLiteral("%1:%2").arg(clipIndex).arg(trackIndex).toLatin1().constData()); } if (selection().size() > 1 || nothingIsSelected()) { emit selected(nullptr); return; } if (selection().isEmpty() && m_selection.selectedTrack > -1) { int i = m_model.trackList().at(m_selection.selectedTrack).mlt_index; std::unique_ptr<Mlt::Producer>producer(m_model.tractor()->track(i)); if (producer && producer->is_valid()) { producer->set(kTrackIndexProperty, m_selection.selectedTrack); emit selected(producer.get()); } return; } if (selection().isEmpty() && m_selection.isMultitrackSelected) { emit multitrackSelected(); emit selected(m_model.tractor()); return; } int trackIndex = selection().isEmpty() ? currentTrack() : selection().first().y(); int clipIndex = selection().isEmpty() ? 0 : selection().first().x(); auto info = m_model.getClipInfo(trackIndex, clipIndex); if (info && info->producer && info->producer->is_valid()) { m_updateCommand.reset(new Timeline::UpdateCommand(*this, trackIndex, clipIndex, info->start)); m_ignoreNextPositionChange = true; emit selected(info->producer); } m_model.tractor()->set(kFilterInProperty, 0); m_model.tractor()->set(kFilterOutProperty, m_model.tractor()->get_length() - 1); } void TimelineDock::remakeAudioLevels(int trackIndex, int clipIndex, bool force) { if (Settings.timelineShowWaveforms()) { QModelIndex modelIndex = m_model.index(clipIndex, 0, m_model.index(trackIndex)); auto info = m_model.getClipInfo(trackIndex, clipIndex); if (info) AudioLevelsTask::start(*info->producer, &m_model, modelIndex, force); } } void TimelineDock::commitTrimCommand() { if (m_trimCommand && (m_trimDelta || m_transitionDelta)) { if (m_undoHelper) m_trimCommand->setUndoHelper(m_undoHelper.release()); MAIN.undoStack()->push(m_trimCommand.release()); } m_trimDelta = 0; m_transitionDelta = 0; } void TimelineDock::onRowsInserted(const QModelIndex &parent, int first, int last) { // Adjust selected clips for changed indices. if (-1 == m_selection.selectedTrack) { QList<QPoint> newSelection; int n = last - first + 1; if (parent.isValid()) { foreach (auto i, m_selection.selectedClips) { if (parent.row() != i.y()) { newSelection << QPoint(i.x(), i.y()); continue; } if (i.x() < first) newSelection << QPoint(i.x(), parent.row()); else newSelection << QPoint(i.x() + n, parent.row()); } } else { foreach (auto i, m_selection.selectedClips) { if (i.y() < first) newSelection << QPoint(i.x(), i.y()); else newSelection << QPoint(i.x(), i.y() + n); } } setSelection(newSelection); if (!parent.isValid()) model()->reload(true); } } void TimelineDock::onRowsRemoved(const QModelIndex &parent, int first, int last) { Q_UNUSED(parent) // Adjust selected clips for changed indices. if (-1 == m_selection.selectedTrack) { QList<QPoint> newSelection; int n = last - first + 1; if (parent.isValid()) { foreach (auto i, m_selection.selectedClips) { if (parent.row() != i.y()) { newSelection << QPoint(i.x(), i.y()); continue; } if (i.x() < first) newSelection << QPoint(i.x(), parent.row()); else if (i.x() > last) newSelection << QPoint(i.x() - n, parent.row()); } } else { foreach (auto i, m_selection.selectedClips) { if (i.y() < first) newSelection << QPoint(i.x(), i.y()); else if (i.y() > last) newSelection << QPoint(i.x(), i.y() - n); } } setSelection(newSelection); if (!parent.isValid()) model()->reload(true); } } void TimelineDock::onRowsMoved(const QModelIndex &parent, int start, int end, const QModelIndex &destination, int row) { Q_UNUSED(parent) Q_UNUSED(start) Q_UNUSED(end) Q_UNUSED(destination) Q_UNUSED(row) // Workaround issue in timeline qml that clip selection becomes inconsistent with the model // Clear the selection and reload the model to trigger reset of the selected clips in the UI QList<QPoint> newSelection; setSelection(newSelection); model()->reload(true); } void TimelineDock::detachAudio(int trackIndex, int clipIndex) { if (!m_model.trackList().count()) return; Q_ASSERT(trackIndex >= 0 && clipIndex >= 0); auto info = m_model.getClipInfo(trackIndex, clipIndex); if (info && info->producer && info->producer->is_valid() && !info->producer->is_blank() && info->producer->get("audio_index") && info->producer->get_int("audio_index") >= 0) { if (!info->producer->property_exists(kDefaultAudioIndexProperty)) { info->producer->set(kDefaultAudioIndexProperty, info->producer->get_int("audio_index")); } Mlt::Producer clip(MLT.profile(), "xml-string", MLT.XML(info->producer).toUtf8().constData()); clip.set_in_and_out(info->frame_in, info->frame_out); MAIN.undoStack()->push( new Timeline::DetachAudioCommand(*this, trackIndex, clipIndex, info->start, MLT.XML(&clip))); } } void TimelineDock::selectAll() { QList<QPoint> selection; for (int y = 0; y < m_model.rowCount(); y++) { for (int x = 0; x < m_model.rowCount(m_model.index(y)); x++) { if (!isBlank(y, x) && !isTrackLocked(y)) selection << QPoint(x, y); } } setSelection(selection); } void TimelineDock::selectAllOnCurrentTrack() { int y = currentTrack(); QList<QPoint> selection; if (y > -1 && y < m_model.rowCount()) { for (int x = 0; x < m_model.rowCount(m_model.index(y)); x++) { if (!isBlank(y, x) && !isTrackLocked(y)) selection << QPoint(x, y); } } setSelection(selection); } void TimelineDock::onProducerModified() { // The clip name may have changed. emitSelectedChanged(QVector<int>() << MultitrackModel::NameRole << MultitrackModel::CommentRole); } void TimelineDock::replace(int trackIndex, int clipIndex, const QString &xml) { if (xml.isEmpty() && !MLT.isClip() && !MLT.savedProducer()) { emit showStatusMessage(tr("There is nothing in the Source player.")); return; } if (!m_model.trackList().count() || MAIN.isSourceClipMyProject()) return; if (trackIndex < 0) trackIndex = currentTrack(); if (isTrackLocked(trackIndex)) { emit warnTrackLocked(trackIndex); return; } if (clipIndex < 0) clipIndex = clipIndexAtPlayhead(trackIndex); Mlt::Producer producer(producerForClip(trackIndex, clipIndex)); if (producer.is_valid() && producer.type() == mlt_service_tractor_type) { emit showStatusMessage(tr("You cannot replace a transition.")); return; } if (MLT.isSeekableClip() || MLT.savedProducer() || !xml.isEmpty()) { Q_ASSERT(trackIndex >= 0 && clipIndex >= 0); QString xmlToUse = !xml.isEmpty() ? xml : MLT.XML(MLT.isClip() ? nullptr : MLT.savedProducer()); MAIN.undoStack()->push( new Timeline::ReplaceCommand(m_model, trackIndex, clipIndex, xmlToUse)); } else if (!MLT.isSeekableClip()) { emitNonSeekableWarning(); } } void TimelineDock::createOrEditMarker() { if (!m_model.trackList().count() || MLT.producer()->get_length() <= 1) return; int index = m_markersModel.markerIndexForPosition(m_position); if (index >= 0) { editMarker(index); return; } createMarker(); } void TimelineDock::createOrEditSelectionMarker() { auto selected = selection(); if (!m_model.trackList().count() || MLT.producer()->get_length() <= 1 || selected.isEmpty()) { emit showStatusMessage(tr("Select a clip in the timeline to create a marker around it")); return; } // Find the earliest start and the latest end in the selection int start = -1; int end = -1; getSelectionRange(&start, &end); if (start > -1) { int index = m_markersModel.markerIndexForRange(start, end); if (index >= 0) { editMarker(index); return; } else { Markers::Marker marker; marker.text = QStringLiteral("Marker %1").arg(m_markersModel.uniqueKey() + 1); marker.color = Settings.markerColor(); marker.start = start; marker.end = end; m_markersModel.append(marker); emit showStatusMessage(tr("Added marker: \"%1\".").arg(marker.text)); return; } } } void TimelineDock::createMarker() { if (!m_model.trackList().count() || MLT.producer()->get_length() <= 1) return; int index = m_markersModel.markerIndexForPosition(m_position); if (index >= 0) { return; } Markers::Marker marker; marker.text = QStringLiteral("Marker %1").arg(m_markersModel.uniqueKey() + 1); marker.color = Settings.markerColor(); marker.start = position(); marker.end = position(); m_markersModel.append(marker); emit showStatusMessage(tr("Added marker: \"%1\". Hold %2 and drag to create a range") .arg(marker.text, QmlApplication::OS() == "macOS" ? "⌘" : "Ctrl")); } void TimelineDock::editMarker(int markerIndex) { Markers::Marker marker = m_markersModel.getMarker(markerIndex); EditMarkerDialog dialog(this, marker.text, marker.color, marker.start, marker.end, m_model.tractor()->get_length() - 1); dialog.setWindowModality(QmlApplication::dialogModality()); if (dialog.exec() == QDialog::Accepted) { marker.text = dialog.getText(); marker.color = dialog.getColor(); marker.start = dialog.getStart(); marker.end = dialog.getEnd(); m_markersModel.update(markerIndex, marker); } } void TimelineDock::deleteMarker(int markerIndex) { if (markerIndex < 0) { markerIndex = m_markersModel.markerIndexForPosition(m_position); } if (markerIndex >= 0) { m_markersModel.remove(markerIndex); } } void TimelineDock::seekNextMarker() { int nextPos = m_markersModel.nextMarkerPosition(m_position); if (nextPos >= 0) { setPosition(nextPos); emit markerSeeked(m_markersModel.markerIndexForPosition(nextPos)); } } void TimelineDock::seekPrevMarker() { int prevPos = m_markersModel.prevMarkerPosition(m_position); if (prevPos >= 0) { setPosition(prevPos); emit markerSeeked(m_markersModel.markerIndexForPosition(prevPos)); } } void TimelineDock::onFilterModelChanged() { if (m_updateCommand) { m_updateCommand->setPosition(-1, -1, -1); } } void TimelineDock::trimClipIn(bool ripple) { trimClipAtPlayhead(TimelineDock::TrimInPoint, ripple); } void TimelineDock::trimClipOut(bool ripple) { trimClipAtPlayhead(TimelineDock::TrimOutPoint, ripple); } void TimelineDock::initLoad() { load(false); } void TimelineDock::handleDrop(int trackIndex, int position, QString xmlOrUrls) { if (xmlOrUrls.startsWith(kFileUrlProtocol)) { QList<QUrl> urls; auto strings = xmlOrUrls.split(kFilesUrlDelimiter); for (auto &s : strings) { #ifdef Q_OS_WIN if (!s.startsWith(kFileUrlProtocol)) { s.prepend(kFileUrlProtocol); } #endif urls << s; } // Use QTimer to workaround stupid drag from Windows Explorer bug QTimer::singleShot(0, this, [ = ]() { auto xml = xmlOrUrls; int i = 0, count = urls.size(); // Handle drop from file manager to empty project. if (!MLT.producer() || !MLT.producer()->is_valid()) { QUrl url = xml.split(kFilesUrlDelimiter).first(); Mlt::Properties properties; properties.set(kShotcutSkipConvertProperty, 1); if (!MAIN.open(Util::removeFileScheme(url), &properties, false /* play */)) MAIN.open(Util::removeFileScheme(url, false), &properties, false /* play */); } LongUiTask longTask(QObject::tr("Drop Files")); Mlt::Playlist playlist(MLT.profile()); ResourceDialog dialog(this); for (const auto &path : Util::sortedFileList(urls)) { if (MAIN.isSourceClipMyProject(path, /* withDialog */ false)) continue; if (MLT.checkFile(path)) { MAIN.showStatusMessage(QObject::tr("Failed to open ").append(path)); continue; } longTask.reportProgress(Util::baseName(path), i++, count); Mlt::Producer p; if (path.endsWith(".mlt") || path.endsWith(".xml")) { if (Settings.playerGPU() && MLT.profile().is_explicit()) { Mlt::Profile testProfile; Mlt::Producer producer(testProfile, path.toUtf8().constData()); if (testProfile.width() != MLT.profile().width() || testProfile.height() != MLT.profile().height() || Util::isFpsDifferent(MLT.profile().fps(), testProfile.fps())) { MAIN.showStatusMessage(QObject::tr("Failed to open ").append(path)); continue; } } p = Mlt::Producer(MLT.profile(), path.toUtf8().constData()); if (p.is_valid()) { p.set(kShotcutVirtualClip, 1); p.set("resource", path.toUtf8().constData()); } } else { p = Mlt::Producer(MLT.profile(), path.toUtf8().constData()); } if (p.is_valid()) { if (!qstrcmp(p.get("mlt_service"), "avformat") && !p.get_int("seekable")) { MAIN.showStatusMessage(QObject::tr("Not adding non-seekable file: ") + Util::baseName(path)); continue; } Mlt::Producer *producer = MLT.setupNewProducer(&p); producer->set(kShotcutSkipConvertProperty, 1); ProxyManager::generateIfNotExists(*producer); playlist.append(*producer); dialog.add(producer); delete producer; } } xml = MLT.XML(&playlist); if (Settings.showConvertClipDialog() && dialog.producerCount() > 1 && dialog.hasTroubleClips()) { dialog.selectTroubleClips(); dialog.setWindowTitle(tr("Dropped Files")); longTask.cancel(); dialog.exec(); } else if (Settings.showConvertClipDialog() && dialog.producerCount() == 1) { Mlt::Producer producer = dialog.producer(0); QString convertAdvice = Util::getConversionAdvice(&producer); if (!convertAdvice.isEmpty()) { longTask.cancel(); Util::offerSingleFileConversion(convertAdvice, &producer, this); } } insertOrOverwriteDrop(trackIndex, position, xml); }); } else { insertOrOverwriteDrop(trackIndex, position, xmlOrUrls); } } void TimelineDock::insertOrOverwriteDrop(int trackIndex, int position, const QString &xml) { auto autoAddTracks = Settings.timelineAutoAddTracks(); Settings.setTimelineAutoAddTracks(false); if (Settings.timelineRipple()) { insert(trackIndex, position, xml, false); } else { overwrite(trackIndex, position, xml, false); } Settings.setTimelineAutoAddTracks(autoAddTracks); if (autoAddTracks) { QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents); m_model.checkForEmptyTracks(trackIndex); } } void TimelineDock::onLoopChanged(int start, int end) { if (MLT.isMultitrack()) { m_loopStart = start; m_loopEnd = end; } else { m_loopStart = -1; m_loopEnd = -1; } emit loopChanged(); } void TimelineDock::setTrackName(int trackIndex, const QString &value) { MAIN.undoStack()->push( new Timeline::NameTrackCommand(m_model, trackIndex, value)); } void TimelineDock::toggleTrackMute(int trackIndex) { MAIN.undoStack()->push( new Timeline::MuteTrackCommand(m_model, trackIndex)); } void TimelineDock::toggleTrackHidden(int trackIndex) { MAIN.undoStack()->push( new Timeline::HideTrackCommand(m_model, trackIndex)); } void TimelineDock::setTrackComposite(int trackIndex, bool composite) { MAIN.undoStack()->push( new Timeline::CompositeTrackCommand(m_model, trackIndex, composite)); } void TimelineDock::setTrackLock(int trackIndex, bool lock) { MAIN.undoStack()->push( new Timeline::LockTrackCommand(m_model, trackIndex, lock)); } bool TimelineDock::moveClip(int fromTrack, int toTrack, int clipIndex, int position, bool ripple) { if (toTrack >= 0 && clipIndex >= 0) { int length = 0; int i = m_model.trackList().at(fromTrack).mlt_index; QScopedPointer<Mlt::Producer> track(m_model.tractor()->track(i)); if (track->is_valid()) { Mlt::Playlist playlist(*track.data()); length = playlist.clip_length(clipIndex); } i = m_model.trackList().at(toTrack).mlt_index; track.reset((m_model.tractor()->track(i))); if (track->is_valid()) { Mlt::Playlist playlist(*track.data()); if (m_model.isTransition(playlist, playlist.get_clip_index_at(position)) || m_model.isTransition(playlist, playlist.get_clip_index_at(position + length - 1))) { return false; } } } if (selection().size() <= 1 && m_model.addTransitionValid(fromTrack, toTrack, clipIndex, position, ripple)) { emit transitionAdded(fromTrack, clipIndex, position, ripple); if (m_updateCommand) m_updateCommand->setPosition(toTrack, clipIndex, position); } else { // Check for locked tracks auto trackDelta = toTrack - fromTrack; for (const auto &clip : selection()) { auto trackIndex = clip.y() + trackDelta; if (isTrackLocked(clip.y())) { emit warnTrackLocked(clip.y()); return false; } if (isTrackLocked(trackIndex)) { emit warnTrackLocked(trackIndex); return false; } } // Workaround bug #326 moving clips between tracks stops allowing drag-n-drop // into Timeline, which appeared with Qt 5.6 upgrade. emit clipMoved(fromTrack, toTrack, clipIndex, position, ripple); if (m_updateCommand) m_updateCommand->setPosition(toTrack, clipIndex, position); } return true; } void TimelineDock::onClipMoved(int fromTrack, int toTrack, int clipIndex, int position, bool ripple) { int n = selection().size(); if (n > 0) { // determine the position delta for (const auto &clip : selection()) { if (clip.y() == fromTrack && clip.x() == clipIndex) { auto info = m_model.getClipInfo(clip.y(), clip.x()); if (info) { position -= info->start; break; } } } auto command = new Timeline::MoveClipCommand(*this, toTrack - fromTrack, position, ripple); for (const auto &clip : selection()) { command->addClip(clip.y(), clip.x()); } setSelection(); if (fromTrack == toTrack) disconnect(&m_model, &MultitrackModel::noMoreEmptyTracks, this, nullptr); MAIN.undoStack()->push(command); if (fromTrack == toTrack) connect(&m_model, &MultitrackModel::noMoreEmptyTracks, this, &TimelineDock::onNoMoreEmptyTracks, Qt::QueuedConnection); } } bool TimelineDock::trimClipIn(int trackIndex, int clipIndex, int oldClipIndex, int delta, bool ripple) { if (dynamic_cast<Timeline::RemoveTransitionByTrimInCommand *>(m_trimCommand.get())) { if (delta < 0) { // Do not trim past the removed tansition return false; } else { // Untrimming - Restore the transition dynamic_cast<Timeline::RemoveTransitionByTrimInCommand *>(m_trimCommand.get())->undo(); m_trimCommand.release(); m_undoHelper.release(); delta += m_trimDelta; m_trimDelta = 0; clipIndex += 1; } } if (!ripple && m_model.addTransitionByTrimInValid(trackIndex, clipIndex, delta)) { clipIndex = m_model.addTransitionByTrimIn(trackIndex, clipIndex, delta); m_transitionDelta += delta; m_trimCommand.reset(new Timeline::AddTransitionByTrimInCommand(*this, trackIndex, clipIndex - 1, m_transitionDelta, m_trimDelta, false)); if (m_updateCommand && m_updateCommand->trackIndex() == trackIndex && m_updateCommand->clipIndex() == clipIndex) m_updateCommand->setPosition(trackIndex, clipIndex, -1); } else if (!ripple && m_model.removeTransitionByTrimInValid(trackIndex, clipIndex, delta)) { Q_ASSERT(trackIndex >= 0 && clipIndex >= 0); std::unique_ptr<Mlt::ClipInfo> clipInfo = m_model.getClipInfo(trackIndex, clipIndex - 1); QString xml = MLT.XML(clipInfo->producer); m_model.liftClip(trackIndex, clipIndex - 1); if (delta < 0 ) { m_model.trimClipIn(trackIndex, clipIndex, -clipInfo->length, false, false); m_trimDelta += -clipInfo->length; } else if (delta > 0) { m_model.trimClipOut(trackIndex, clipIndex - 2, -clipInfo->length, false, false); m_transitionDelta = 0; } m_trimCommand.reset(new Timeline::RemoveTransitionByTrimInCommand(m_model, trackIndex, clipIndex - 1, m_trimDelta, xml, false)); if (m_updateCommand && m_updateCommand->trackIndex() == trackIndex && m_updateCommand->clipIndex() == clipIndex) m_updateCommand->setPosition(trackIndex, clipIndex - 1, -1); } else if (!ripple && m_model.trimTransitionOutValid(trackIndex, clipIndex, delta)) { m_model.trimTransitionOut(trackIndex, clipIndex, delta); m_trimDelta += delta; m_trimCommand.reset(new Timeline::TrimTransitionOutCommand(m_model, trackIndex, clipIndex, m_trimDelta, false)); } else if (m_model.trimClipInValid(trackIndex, clipIndex, delta, ripple)) { if (!m_undoHelper) { m_undoHelper.reset(new UndoHelper(m_model)); if (!ripple) { m_undoHelper->setHints(UndoHelper::SkipXML); } else { m_undoHelper->setHints(UndoHelper::RestoreTracks); } m_undoHelper->recordBeforeState(); } clipIndex = m_model.trimClipIn(trackIndex, clipIndex, delta, ripple, Settings.timelineRippleAllTracks()); m_trimDelta += delta; m_trimCommand.reset(new Timeline::TrimClipInCommand(m_model, m_markersModel, trackIndex, oldClipIndex, m_trimDelta, ripple, false)); if (m_updateCommand && m_updateCommand->trackIndex() == trackIndex && m_updateCommand->clipIndex() == clipIndex) m_updateCommand->setPosition(trackIndex, clipIndex, m_updateCommand->position() + delta); } else return false; // Update duration in properties auto info = m_model.getClipInfo(trackIndex, clipIndex); if (info && !info->producer->get_int(kShotcutSequenceProperty)) emit durationChanged(); return true; } bool TimelineDock::trimClipOut(int trackIndex, int clipIndex, int delta, bool ripple) { if (dynamic_cast<Timeline::RemoveTransitionByTrimOutCommand *>(m_trimCommand.get())) { if (delta < 0) { // Do not trim past the removed tansition return false; } else { // Untrimming - Restore the transition dynamic_cast<Timeline::RemoveTransitionByTrimOutCommand *>(m_trimCommand.get())->undo(); m_trimCommand.release(); m_undoHelper.release(); delta += m_trimDelta; m_trimDelta = 0; } } if (!ripple && m_model.addTransitionByTrimOutValid(trackIndex, clipIndex, delta)) { m_model.addTransitionByTrimOut(trackIndex, clipIndex, delta); m_transitionDelta += delta; m_trimCommand.reset(new Timeline::AddTransitionByTrimOutCommand(m_model, trackIndex, clipIndex, m_transitionDelta, m_trimDelta, false)); if (m_updateCommand && m_updateCommand->trackIndex() == trackIndex && m_updateCommand->clipIndex() == clipIndex) m_updateCommand->setPosition(trackIndex, clipIndex, -1); } else if (!ripple && m_model.removeTransitionByTrimOutValid(trackIndex, clipIndex, delta)) { Q_ASSERT(trackIndex >= 0 && clipIndex >= 0); std::unique_ptr<Mlt::ClipInfo> clipInfo = m_model.getClipInfo(trackIndex, clipIndex + 1); QString xml = MLT.XML(clipInfo->producer); m_model.liftClip(trackIndex, clipIndex + 1); if (delta < 0 ) { m_model.trimClipOut(trackIndex, clipIndex, -clipInfo->length, false, false); m_trimDelta += -clipInfo->length; } else if (delta > 0) { m_model.trimClipIn(trackIndex, clipIndex + 2, -clipInfo->length, false, false); m_transitionDelta = 0; } m_trimCommand.reset(new Timeline::RemoveTransitionByTrimOutCommand(m_model, trackIndex, clipIndex + 1, m_trimDelta, xml, false)); if (m_updateCommand && m_updateCommand->trackIndex() == trackIndex && m_updateCommand->clipIndex() == clipIndex) m_updateCommand->setPosition(trackIndex, clipIndex, -1); } else if (!ripple && m_model.trimTransitionInValid(trackIndex, clipIndex, delta)) { m_model.trimTransitionIn(trackIndex, clipIndex, delta); m_trimDelta += delta; m_trimCommand.reset(new Timeline::TrimTransitionInCommand(m_model, trackIndex, clipIndex, m_trimDelta, false)); } else if (m_model.trimClipOutValid(trackIndex, clipIndex, delta, ripple)) { if (!m_undoHelper) { m_undoHelper.reset(new UndoHelper(m_model)); if (!ripple) m_undoHelper->setHints(UndoHelper::SkipXML); m_undoHelper->recordBeforeState(); } m_model.trimClipOut(trackIndex, clipIndex, delta, ripple, Settings.timelineRippleAllTracks()); m_trimDelta += delta; m_trimCommand.reset(new Timeline::TrimClipOutCommand(m_model, m_markersModel, trackIndex, clipIndex, m_trimDelta, ripple, false)); if (m_updateCommand && m_updateCommand->trackIndex() == trackIndex && m_updateCommand->clipIndex() == clipIndex) m_updateCommand->setPosition(trackIndex, clipIndex, -1); } else return false; // Update duration in properties auto info = m_model.getClipInfo(trackIndex, clipIndex); if (info && !info->producer->get_int(kShotcutSequenceProperty)) emit durationChanged(); return true; } void TimelineDock::insert(int trackIndex, int position, const QString &xml, bool seek) { // Validations if (trackIndex < 0) trackIndex = currentTrack(); if (isTrackLocked(trackIndex)) { emit warnTrackLocked(trackIndex); return; } if (xml.contains(MAIN.fileName()) && MAIN.isSourceClipMyProject()) return; // Use MLT XML on the clipboard if it exists and is newer than source clip. QString xmlToUse = QGuiApplication::clipboard()->text(); if (isSystemClipboardValid(xmlToUse)) { if (!Settings.proxyEnabled()) { ProxyManager::filterXML(xmlToUse, ""); } } else { xmlToUse.clear(); } if (MLT.isSeekableClip() || MLT.savedProducer() || !xml.isEmpty() || !xmlToUse.isEmpty()) { Mlt::Producer producer; if (xmlToUse.isEmpty() && xml.isEmpty()) { Mlt::Producer producer(MLT.isClip() ? MLT.producer() : MLT.savedProducer()); ProxyManager::generateIfNotExists(producer); xmlToUse = MLT.XML(&producer); } else if (!xml.isEmpty()) { xmlToUse = xml; } else { producer = Mlt::Producer(MLT.profile(), "xml-string", xmlToUse.toUtf8().constData()); } if (xmlToUse.isEmpty()) { return; } if (position < 0) { position = qMax(m_position, 0); } // Insert multiple if the XML is a <tractor> with child <property name="shotcut">1</property> // No need to create a track in an empty timeline. // This can be a macro of QUndoCommands. if (producer.is_valid() && producer.type() == mlt_service_tractor_type && producer.get_int(kShotcutXmlProperty)) { Mlt::Tractor tractor(producer); Mlt::ClipInfo info; MAIN.undoStack()->beginMacro(tr("Insert multiple into timeline")); Mlt::Controller::RefreshBlocker blocker; // Loop over each source track for (int mltTrackIndex = 0; mltTrackIndex < tractor.count(); mltTrackIndex++) { QScopedPointer<Mlt::Producer> srcTrack(tractor.track(mltTrackIndex)); if (srcTrack) { const auto trackIndex = currentTrack() + mltTrackIndex; addTrackIfNeeded(trackIndex, srcTrack.get()); // Insert the clips for this track Mlt::Playlist playlist(*srcTrack); for (int mltClipIndex = 0; mltClipIndex < playlist.count(); mltClipIndex++) { if (!playlist.is_blank(mltClipIndex)) { playlist.clip_info(mltClipIndex, &info); Mlt::Producer clip(info.producer); clip.set_in_and_out(info.frame_in, info.frame_out); bool lastClip = mltTrackIndex == tractor.count() - 1 && mltClipIndex == playlist.count() - 1; MAIN.undoStack()->push( new Timeline::InsertCommand(m_model, m_markersModel, trackIndex, position + info.start, MLT.XML(&clip), lastClip)); } } } } MAIN.undoStack()->endMacro(); } else { if (m_model.trackList().size() == 0) { position = 0; addVideoTrack(); } MAIN.undoStack()->push( new Timeline::InsertCommand(m_model, m_markersModel, trackIndex, position, xmlToUse, seek)); } if (m_position < 0) { // This happens when pasting in a new session MAIN.openCut(new Mlt::Producer(m_model.tractor())); } } else if (!MLT.isSeekableClip()) { emitNonSeekableWarning(); } } void TimelineDock::selectClip(int trackIndex, int clipIndex) { setSelection(QList<QPoint>() << QPoint(clipIndex, trackIndex)); } void TimelineDock::onMultitrackClosed() { stopRecording(); m_position = -1; m_ignoreNextPositionChange = false; m_trimDelta = 0; m_transitionDelta = 0; setSelection(); emit setZoom(1.0); } void TimelineDock::reloadTimelineModels() { m_markersModel.load(m_model.tractor()); m_subtitlesModel.load(m_model.tractor()); } void TimelineDock::overwrite(int trackIndex, int position, const QString &xml, bool seek) { // Validations if (trackIndex < 0) trackIndex = currentTrack(); if (isTrackLocked(trackIndex)) { emit warnTrackLocked(trackIndex); return; } if (xml.contains(MAIN.fileName()) && MAIN.isSourceClipMyProject()) return; // Use MLT XML on the clipboard if it exists and is newer than source clip. QString xmlToUse = QGuiApplication::clipboard()->text(); if (isSystemClipboardValid(xmlToUse)) { if (!Settings.proxyEnabled()) { ProxyManager::filterXML(xmlToUse, ""); } } else { xmlToUse.clear(); } if (MLT.isSeekableClip() || MLT.savedProducer() || !xml.isEmpty() || !xmlToUse.isEmpty()) { Mlt::Producer producer; if (xmlToUse.isEmpty() && xml.isEmpty()) { Mlt::Producer producer(MLT.isClip() ? MLT.producer() : MLT.savedProducer()); ProxyManager::generateIfNotExists(producer); xmlToUse = MLT.XML(&producer); } else if (!xml.isEmpty()) { xmlToUse = xml; } else { producer = Mlt::Producer(MLT.profile(), "xml-string", xmlToUse.toUtf8().constData()); } if (position < 0) { position = qMax(m_position, 0); } // Overwrite multiple if the XML is a <tractor> with child <property name="shotcut">1</property> // No need to create a track in an empty timeline. // This can be a macro of QUndoCommands. if (producer.is_valid() && producer.type() == mlt_service_tractor_type && producer.get_int(kShotcutXmlProperty)) { Mlt::Tractor tractor(producer); Mlt::ClipInfo info; MAIN.undoStack()->beginMacro(tr("Overwrite multiple onto timeline")); Mlt::Controller::RefreshBlocker blocker; // Loop over each source track for (int mltTrackIndex = 0; mltTrackIndex < tractor.count(); mltTrackIndex++) { QScopedPointer<Mlt::Producer> srcTrack(tractor.track(mltTrackIndex)); if (srcTrack) { const auto trackIndex = currentTrack() + mltTrackIndex; addTrackIfNeeded(trackIndex, srcTrack.get()); // Insert the clips for this track Mlt::Playlist playlist(*srcTrack); for (int mltClipIndex = 0; mltClipIndex < playlist.count(); mltClipIndex++) { if (!playlist.is_blank(mltClipIndex)) { playlist.clip_info(mltClipIndex, &info); Mlt::Producer clip(info.producer); clip.set_in_and_out(info.frame_in, info.frame_out); bool lastClip = mltTrackIndex == tractor.count() - 1 && mltClipIndex == playlist.count() - 1; MAIN.undoStack()->push( new Timeline::OverwriteCommand(m_model, trackIndex, position + info.start, MLT.XML(&clip), false)); } } } } MAIN.undoStack()->endMacro(); } else { if (m_model.trackList().size() == 0) { position = 0; addVideoTrack(); } MAIN.undoStack()->push( new Timeline::OverwriteCommand(m_model, trackIndex, position, xmlToUse, seek)); } if (m_position < 0) { // This happens when pasting in a new session MAIN.openCut(new Mlt::Producer(m_model.tractor())); } } else if (!MLT.isSeekableClip()) { emitNonSeekableWarning(); } } void TimelineDock::appendFromPlaylist(Mlt::Playlist *playlist, bool skipProxy, bool emptyTrack) { int trackIndex = currentTrack(); if (trackIndex >= 0 && emptyTrack) { if (trackIndex < m_model.trackList().size()) { int i = m_model.trackList().at(trackIndex).mlt_index; QScopedPointer<Mlt::Producer> producer(m_model.tractor()->track(i)); if (producer) { Mlt::Playlist track(*producer); if (!(track.count() == 1 && track.is_blank(0))) { trackIndex = addVideoTrack(); } } } } if (trackIndex < 0) { trackIndex = 0; } if (isTrackLocked(trackIndex)) { emit warnTrackLocked(trackIndex); return; } // Workaround a bug with first slide of slideshow animation not working. if (skipProxy) { // Initialize the multitrack with a bogus clip and remove it. Mlt::Producer producer(playlist->get_clip(0)); auto clipIndex = m_model.appendClip(trackIndex, producer); if (clipIndex >= 0) m_model.removeClip(trackIndex, clipIndex, false); } disconnect(&m_model, &MultitrackModel::appended, this, &TimelineDock::selectClip); auto autoAddTracks = Settings.timelineAutoAddTracks(); Settings.setTimelineAutoAddTracks(false); MAIN.undoStack()->push( new Timeline::AppendCommand(m_model, trackIndex, MLT.XML(playlist), skipProxy)); connect(&m_model, &MultitrackModel::appended, this, &TimelineDock::selectClip, Qt::QueuedConnection); Settings.setTimelineAutoAddTracks(autoAddTracks); m_model.checkForEmptyTracks(trackIndex); } void TimelineDock::fadeIn(int trackIndex, int clipIndex, int duration) { if (isTrackLocked(trackIndex)) { emit warnTrackLocked(trackIndex); return; } if (duration < 0) return; Q_ASSERT(trackIndex >= 0 && clipIndex >= 0); MAIN.undoStack()->push( new Timeline::FadeInCommand(m_model, trackIndex, clipIndex, duration)); emit fadeInChanged(duration); } void TimelineDock::fadeOut(int trackIndex, int clipIndex, int duration) { if (isTrackLocked(trackIndex)) { emit warnTrackLocked(trackIndex); return; } if (duration < 0) return; Q_ASSERT(trackIndex >= 0 && clipIndex >= 0); MAIN.undoStack()->push( new Timeline::FadeOutCommand(m_model, trackIndex, clipIndex, duration)); emit fadeOutChanged(duration); } void TimelineDock::seekPreviousEdit() { if (!MLT.isMultitrack()) return; if (!m_model.tractor()) return; int newPosition = -1; int n = m_model.tractor()->count(); for (int i = 0; i < n; i++) { QScopedPointer<Mlt::Producer> track(m_model.tractor()->track(i)); if (track) { Mlt::Playlist playlist(*track); int clipIndex = playlist.get_clip_index_at(m_position); if (clipIndex >= 0 && m_position == playlist.clip_start(clipIndex)) --clipIndex; if (clipIndex >= 0) newPosition = qMax(newPosition, playlist.clip_start(clipIndex)); } } if (newPosition != m_position) setPosition(newPosition); } void TimelineDock::seekNextEdit() { if (!MLT.isMultitrack()) return; if (!m_model.tractor()) return; int newPosition = std::numeric_limits<int>::max(); int n = m_model.tractor()->count(); for (int i = 0; i < n; i++) { QScopedPointer<Mlt::Producer> track(m_model.tractor()->track(i)); if (track) { Mlt::Playlist playlist(*track); int clipIndex = playlist.get_clip_index_at(m_position) + 1; if (clipIndex < playlist.count()) newPosition = qMin(newPosition, playlist.clip_start(clipIndex)); else if (clipIndex == playlist.count()) newPosition = qMin(newPosition, playlist.clip_start(clipIndex) + playlist.clip_length(clipIndex)); } } if (newPosition != m_position) setPosition(newPosition); } void TimelineDock::seekInPoint(int clipIndex) { if (!MLT.isMultitrack()) return; if (!m_model.tractor()) return; if (clipIndex < 0) return; int mltTrackIndex = m_model.trackList().at(currentTrack()).mlt_index; QScopedPointer<Mlt::Producer> track(m_model.tractor()->track(mltTrackIndex)); if (track) { Mlt::Playlist playlist(*track); if (m_position != playlist.clip_start(clipIndex)) setPosition(playlist.clip_start(clipIndex)); } } void TimelineDock::dragEnterEvent(QDragEnterEvent *event) { LOG_DEBUG() << event->mimeData()->hasFormat(Mlt::XmlMimeType); if (event->mimeData()->hasFormat(Mlt::XmlMimeType)) { MLT.pause(); event->acceptProposedAction(); } } void TimelineDock::dragMoveEvent(QDragMoveEvent *event) { emit dragging(event->position(), event->mimeData()->text().toInt()); } void TimelineDock::dragLeaveEvent(QDragLeaveEvent *event) { Q_UNUSED(event); emit dropped(); } void TimelineDock::dropEvent(QDropEvent *event) { if (event->mimeData()->hasFormat(Mlt::XmlMimeType)) { int trackIndex = currentTrack(); if (trackIndex >= 0) { emit dropAccepted(QString::fromUtf8(event->mimeData()->data(Mlt::XmlMimeType))); event->acceptProposedAction(); } } emit dropped(); } bool TimelineDock::event(QEvent *event) { bool result = QDockWidget::event(event); if (event->type() == QEvent::PaletteChange || event->type() == QEvent::StyleChange) load(true); return result; } void TimelineDock::keyPressEvent(QKeyEvent *event) { QDockWidget::keyPressEvent(event); if (!event->isAccepted()) MAIN.keyPressEvent(event); } void TimelineDock::keyReleaseEvent(QKeyEvent *event) { QDockWidget::keyReleaseEvent(event); if (!event->isAccepted()) MAIN.keyReleaseEvent(event); } void TimelineDock::load(bool force) { if (m_quickView.source().isEmpty() || force) { int saveCurrentTrack = -1; if (!m_quickView.source().isEmpty()) saveCurrentTrack = currentTrack(); QDir sourcePath = QmlUtilities::qmlDir(); sourcePath.cd("views"); sourcePath.cd("timeline"); m_quickView.setFocusPolicy(isFloating() ? Qt::NoFocus : Qt::StrongFocus); m_quickView.setSource(QUrl::fromLocalFile(sourcePath.filePath("timeline.qml"))); if (force && Settings.timelineShowWaveforms()) m_model.reload(); if (saveCurrentTrack != -1) setCurrentTrack(saveCurrentTrack); } else if (Settings.timelineShowWaveforms()) { m_model.reload(); } } void TimelineDock::onTopLevelChanged(bool floating) { m_quickView.setFocusPolicy(floating ? Qt::NoFocus : Qt::StrongFocus); } void TimelineDock::onTransitionAdded(int trackIndex, int clipIndex, int position, bool ripple) { setSelection(); // cleared Timeline::AddTransitionCommand *command = new Timeline::AddTransitionCommand(*this, trackIndex, clipIndex, position, ripple); MAIN.undoStack()->push(command); // Select the transition. setSelection(QList<QPoint>() << QPoint(command->getTransitionIndex(), trackIndex)); } void TimelineDock::onTimelineRightClicked() { m_mainMenu->popup(QCursor::pos()); } void TimelineDock::onClipRightClicked() { m_clipMenu->popup(QCursor::pos()); } void TimelineDock::onNoMoreEmptyTracks(bool isAudio) { if (Settings.timelineAutoAddTracks()) { if (isAudio) { addAudioTrack(); } else { addVideoTrack(); incrementCurrentTrack(1); } } } class FindProducersByHashParser : public Mlt::Parser { private: QString m_hash; QList<Mlt::Producer> m_producers; public: FindProducersByHashParser(const QString &hash) : Mlt::Parser() , m_hash(hash) {} QList<Mlt::Producer> &producers() { return m_producers; } int on_start_filter(Mlt::Filter *) { return 0; } int on_start_producer(Mlt::Producer *producer) { if (producer->is_cut() && Util::getHash(producer->parent()) == m_hash) m_producers << Mlt::Producer(producer); return 0; } int on_end_producer(Mlt::Producer *) { return 0; } int on_start_playlist(Mlt::Playlist *) { return 0; } int on_end_playlist(Mlt::Playlist *) { return 0; } int on_start_tractor(Mlt::Tractor *) { return 0; } int on_end_tractor(Mlt::Tractor *) { return 0; } int on_start_multitrack(Mlt::Multitrack *) { return 0; } int on_end_multitrack(Mlt::Multitrack *) { return 0; } int on_start_track() { return 0; } int on_end_track() { return 0; } int on_end_filter(Mlt::Filter *) { return 0; } int on_start_transition(Mlt::Transition *) { return 0; } int on_end_transition(Mlt::Transition *) { return 0; } int on_start_chain(Mlt::Chain *) { return 0; } int on_end_chain(Mlt::Chain *) { return 0; } int on_start_link(Mlt::Link *) { return 0; } int on_end_link(Mlt::Link *) { return 0; } }; void TimelineDock::replaceClipsWithHash(const QString &hash, Mlt::Producer &producer) { FindProducersByHashParser parser(hash); parser.start(*model()->tractor()); auto n = parser.producers().size(); if (n > 1) MAIN.undoStack()->beginMacro(tr("Replace %n timeline clips", nullptr, n)); for (auto &clip : parser.producers()) { int trackIndex = -1; int clipIndex = -1; // lookup the current track and clip index by UUID auto info = m_model.findClipByUuid(QUuid::fromString(clip.parent().get(kUuidProperty)), trackIndex, clipIndex); if (info && info->producer->is_valid() && trackIndex >= 0 && clipIndex >= 0 && info->producer->type() != mlt_service_tractor_type) { if (producer.get_int(kIsProxyProperty) && info->producer->get_int(kIsProxyProperty)) { // Not much to do on a proxy clip but change its resource info->producer->set(kOriginalResourceProperty, producer.get("resource")); auto caption = Util::baseName(ProxyManager::resource(*info->producer), true); if (!::qstrcmp(info->producer->get("mlt_service"), "timewarp")) { caption = QStringLiteral("%1 (%2x)").arg(caption, info->producer->get("warp_speed")); } info->producer->set(kShotcutCaptionProperty, caption.toUtf8().constData()); } else { int in = clip.get_in(); int out = clip.get_out(); // Factor in a transition left of the clip. auto info2 = m_model.getClipInfo(trackIndex, clipIndex - 1); if (info2 && info2->producer && info2->producer->is_valid() && info2->producer->get(kShotcutTransitionProperty)) { in -= info2->frame_count; } // Factor in a transition right of the clip. info2 = m_model.getClipInfo(trackIndex, clipIndex + 1); if (info2 && info2->producer && info2->producer->is_valid() && info2->producer->get(kShotcutTransitionProperty)) { out += info2->frame_count; } Util::applyCustomProperties(producer, *info->producer, in, out); replace(trackIndex, clipIndex, MLT.XML(&producer)); } } } if (n > 1) MAIN.undoStack()->endMacro(); } void TimelineDock::recordAudio() { // Get the file name. auto filename = QmlApplication::getNextProjectFile("voiceover.opus"); if (filename.isEmpty()) { QString path = Settings.savePath(); path.append("/%1.opus"); path = path.arg(tr("voiceover")); auto nameFilter = tr("Opus (*.opus);;All Files (*)"); filename = QFileDialog::getSaveFileName(this, tr("Record Audio"), path, nameFilter, nullptr, Util::getFileDialogOptions()); } if (filename.isEmpty()) { return; } if (!filename.endsWith(".opus")) { filename += ".opus"; } auto info = QFileInfo(filename); Settings.setSavePath(info.path()); MAIN.undoStack()->beginMacro(tr("Record Audio: %1").arg(info.fileName())); // Add renamed color clip to audio track. auto trackIndex = addTrackIfNeeded(AudioTrackType); auto clip = Mlt::Producer(MLT.profile(), "color:"); clip.set(kShotcutCaptionProperty, info.fileName().toUtf8().constData()); clip.set(kShotcutDetailProperty, filename.toUtf8().constData()); clip.set(kBackgroundCaptureProperty, 1); clip.set("length", std::numeric_limits<int>::max()); clip.set_in_and_out(0, 0); overwrite(trackIndex, -1, MLT.XML(&clip), false); m_recordingTrackIndex = trackIndex; m_recordingClipIndex = clipIndexAtPosition(trackIndex, position()); // Start ffmpeg background job. auto priority = QThread::HighPriority; #if defined(Q_OS_MAC) QStringList args {"-f", "avfoundation", "-i", "none:" + Settings.audioInput()}; priority = QThread::NormalPriority; #elif defined(Q_OS_WIN) QStringList args {"-f", "dshow", "-i", "audio=" + Settings.audioInput()}; #else QStringList args {"-f", "pulse", "-name", "Shotcut", "-i", Settings.audioInput()}; #endif args << "-flush_packets" << "1" << "-y" << filename; m_recordJob.reset(new FfmpegJob("vo", args, false, priority)); connect(m_recordJob.get(), SIGNAL(started()), SLOT(onRecordStarted())); connect(m_recordJob.get(), SIGNAL(finished(AbstractJob *, bool)), SLOT(onRecordFinished(AbstractJob *, bool))); m_recordJob->start(); m_isRecording = true; emit isRecordingChanged(m_isRecording); } void TimelineDock::onRecordStarted() { // Use a timer to increase length of color clip. m_recordingTimer.setInterval(kRecordingTimerIntervalMs); connect(&m_recordingTimer, SIGNAL(timeout()), this, SLOT(updateRecording())); m_recordingTime = QDateTime::currentDateTime(); m_recordingTimer.start(); // Start playback. MLT.play(); } void TimelineDock::updateRecording() { int out = qRound(MLT.profile().fps() * m_recordingTime.secsTo(QDateTime::currentDateTime())); auto info = m_model.getClipInfo(m_recordingTrackIndex, m_recordingClipIndex); if (info) { auto delta = info->frame_out - out; if (delta < 0) { m_model.trimClipOut(m_recordingTrackIndex, m_recordingClipIndex, delta, false, false); } } } void TimelineDock::onRecordFinished(AbstractJob *, bool success) { if (!success) { stopRecording(); Settings.setAudioInput(QString()); // saved input likely no longer valid #if defined(Q_OS_UNIX) && !defined(Q_OS_MAC) emit showStatusMessage(tr("Record Audio error: check PulseAudio settings")); #else emit showStatusMessage(tr("Record Audio error: choose File > Open Other > Audio/Video Device")); #endif } } void TimelineDock::stopRecording() { m_recordingTimer.stop(); if (m_isRecording) { m_isRecording = false; emit isRecordingChanged(m_isRecording); // Stop ffmpeg job. if (m_recordJob && m_recordJob->state() != QProcess::NotRunning) { m_recordJob->stop(); // Stop playback. MLT.pause(); // Wait for ffmpeg to flush the recording. LongUiTask longTask(tr("Record Audio")); longTask.setMinimumDuration(500); QFuture<int> future = QtConcurrent::run([]() { QThread::msleep(3000); return 0; }); longTask.wait<int>(tr("Saving audio recording..."), future); } // Replace color clip. auto info = m_model.getClipInfo(m_recordingTrackIndex, m_recordingClipIndex); if (info && info->producer && info->producer->is_valid()) { Mlt::Producer clip(MLT.profile(), info->producer->get(kShotcutDetailProperty)); lift(m_recordingTrackIndex, m_recordingClipIndex, true); if (clip.is_valid()) { overwrite(m_recordingTrackIndex, info->start, MLT.XML(&clip), false); } } MAIN.undoStack()->endMacro(); } }
156,942
C++
.cpp
3,660
34.083333
131
0.615926
mltframework/shotcut
10,796
1,118
50
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
13,131
keyframesdock.cpp
mltframework_shotcut/src/docks/keyframesdock.cpp
/* * Copyright (c) 2016-2024 Meltytech, LLC * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "keyframesdock.h" #include "actions.h" #include "qmltypes/qmlproducer.h" #include "qmltypes/qmlutilities.h" #include "qmltypes/qmlview.h" #include "widgets/docktoolbar.h" #include "mainwindow.h" #include "settings.h" #include <Logger.h> #include <QAction> #include <QDir> #include <QIcon> #include <QMenu> #include <QUrl> #include <QVBoxLayout> #include <QQmlContext> #include <QQmlEngine> #include <QQuickItem> #include <QQuickView> #include <QSlider> #include <QToolButton> #include <QActionGroup> #include <cmath> static QmlMetadata m_emptyQmlMetadata; static QmlFilter m_emptyQmlFilter; KeyframesDock::KeyframesDock(QmlProducer *qmlProducer, QWidget *parent) : QDockWidget(tr("Keyframes"), parent) , m_qview(QmlUtilities::sharedEngine(), this) , m_qmlProducer(qmlProducer) { LOG_DEBUG() << "begin"; setObjectName("KeyframesDock"); QIcon icon = QIcon::fromTheme("chronometer", QIcon(":/icons/oxygen/32x32/actions/chronometer.png")); setWindowIcon(icon); toggleViewAction()->setIcon(windowIcon()); setMinimumSize(200, 50); setupActions(); m_mainMenu = new QMenu(tr("Keyframes"), this); m_mainMenu->addAction(Actions["keyframesTrimInAction"]); m_mainMenu->addAction(Actions["keyframesTrimOutAction"]); m_mainMenu->addAction(Actions["keyframesAnimateInAction"]); m_mainMenu->addAction(Actions["keyframesAnimateOutAction"]); m_mainMenu->addAction(Actions["keyframesScrubDragAction"]); m_mainMenu->addAction(Actions["keyframesToggleKeyframeAction"]); m_mainMenu->addAction(Actions["keyframesSeekPreviousAction"]); m_mainMenu->addAction(Actions["keyframesSeekNextAction"]); QMenu *viewMenu = new QMenu(tr("View"), this); viewMenu->addAction(Actions["keyframesZoomOutAction"]); viewMenu->addAction(Actions["keyframesZoomInAction"]); viewMenu->addAction(Actions["keyframesZoomFitAction"]); m_mainMenu->addMenu(viewMenu); Actions.loadFromMenu(m_mainMenu); m_keyMenu = new QMenu(tr("Keyframe"), this); m_keyTypePrevMenu = new QMenu(tr("From Previous"), this); m_keyTypePrevMenu->addAction(Actions["keyframesTypePrevHoldAction"]); m_keyTypePrevMenu->addAction(Actions["keyframesTypePrevLinearAction"]); m_keyTypePrevMenu->addAction(Actions["keyframesTypePrevSmoothNaturalAction"]); #if LIBMLT_VERSION_INT >= ((7<<16)+(21<<8)) QMenu *keyEaseOutMenu = new QMenu(tr("Ease Out"), this); icon = QIcon::fromTheme("keyframe-ease-out", QIcon(":/icons/oxygen/32x32/actions/keyframe-ease-out.png")); keyEaseOutMenu->setIcon(icon); keyEaseOutMenu->addAction(Actions["keyframesTypePrevEaseOutSinuAction"]); keyEaseOutMenu->addAction(Actions["keyframesTypePrevEaseOutQuadAction"]); keyEaseOutMenu->addAction(Actions["keyframesTypePrevEaseOutCubeAction"]); keyEaseOutMenu->addAction(Actions["keyframesTypePrevEaseOutQuartAction"]); keyEaseOutMenu->addAction(Actions["keyframesTypePrevEaseOutQuintAction"]); keyEaseOutMenu->addAction(Actions["keyframesTypePrevEaseOutExpoAction"]); keyEaseOutMenu->addAction(Actions["keyframesTypePrevEaseOutCircAction"]); keyEaseOutMenu->addAction(Actions["keyframesTypePrevEaseOutBackAction"]); keyEaseOutMenu->addAction(Actions["keyframesTypePrevEaseOutElasAction"]); keyEaseOutMenu->addAction(Actions["keyframesTypePrevEaseOutBounAction"]); m_keyTypePrevMenu->addMenu(keyEaseOutMenu); #endif m_keyMenu->addMenu(m_keyTypePrevMenu); m_keyTypeNextMenu = new QMenu(tr("To Next"), this); m_keyTypeNextMenu->addAction(Actions["keyframesTypeHoldAction"]); m_keyTypeNextMenu->addAction(Actions["keyframesTypeLinearAction"]); m_keyTypeNextMenu->addAction(Actions["keyframesTypeSmoothNaturalAction"]); #if LIBMLT_VERSION_INT >= ((7<<16)+(21<<8)) QMenu *keyEaseInMenu = new QMenu(tr("Ease In"), this); icon = QIcon::fromTheme("keyframe-ease-in", QIcon(":/icons/oxygen/32x32/actions/keyframe-ease-in.png")); keyEaseInMenu->setIcon(icon); keyEaseInMenu->addAction(Actions["keyframesTypeEaseInSinuAction"]); keyEaseInMenu->addAction(Actions["keyframesTypeEaseInQuadAction"]); keyEaseInMenu->addAction(Actions["keyframesTypeEaseInCubeAction"]); keyEaseInMenu->addAction(Actions["keyframesTypeEaseInQuartAction"]); keyEaseInMenu->addAction(Actions["keyframesTypeEaseInQuintAction"]); keyEaseInMenu->addAction(Actions["keyframesTypeEaseInExpoAction"]); keyEaseInMenu->addAction(Actions["keyframesTypeEaseInCircAction"]); keyEaseInMenu->addAction(Actions["keyframesTypeEaseInBackAction"]); keyEaseInMenu->addAction(Actions["keyframesTypeEaseInElasAction"]); keyEaseInMenu->addAction(Actions["keyframesTypeEaseInBounAction"]); m_keyTypeNextMenu->addMenu(keyEaseInMenu); QMenu *keyEaseInOutMenu = new QMenu(tr("Ease In/Out"), this); icon = QIcon::fromTheme("keyframe-ease-inout", QIcon(":/icons/oxygen/32x32/actions/keyframe-ease-inout.png")); keyEaseInOutMenu->setIcon(icon); keyEaseInOutMenu->addAction(Actions["keyframesTypeEaseInOutSinuAction"]); keyEaseInOutMenu->addAction(Actions["keyframesTypeEaseInOutQuadAction"]); keyEaseInOutMenu->addAction(Actions["keyframesTypeEaseInOutCubeAction"]); keyEaseInOutMenu->addAction(Actions["keyframesTypeEaseInOutQuartAction"]); keyEaseInOutMenu->addAction(Actions["keyframesTypeEaseInOutQuintAction"]); keyEaseInOutMenu->addAction(Actions["keyframesTypeEaseInOutExpoAction"]); keyEaseInOutMenu->addAction(Actions["keyframesTypeEaseInOutCircAction"]); keyEaseInOutMenu->addAction(Actions["keyframesTypeEaseInOutBackAction"]); keyEaseInOutMenu->addAction(Actions["keyframesTypeEaseInOutElasAction"]); keyEaseInOutMenu->addAction(Actions["keyframesTypeEaseInOutBounAction"]); m_keyTypeNextMenu->addMenu(keyEaseInOutMenu); #endif m_keyMenu->addMenu(m_keyTypeNextMenu); m_keyMenu->addAction(Actions["keyframesRemoveAction"]); Actions.loadFromMenu(m_keyMenu); m_clipMenu = new QMenu(tr("Keyframes Clip"), this); m_clipMenu->addAction(Actions["keyframesRebuildAudioWaveformAction"]); Actions.loadFromMenu(m_clipMenu); QVBoxLayout *vboxLayout = new QVBoxLayout(); vboxLayout->setSpacing(0); vboxLayout->setContentsMargins(0, 0, 0, 0); DockToolBar *toolbar = new DockToolBar(tr("Keyframes Controls")); QToolButton *menuButton = new QToolButton(); menuButton->setIcon(QIcon::fromTheme("show-menu", QIcon(":/icons/oxygen/32x32/actions/show-menu.png"))); menuButton->setToolTip(tr("Keyframes Menu")); menuButton->setAutoRaise(true); menuButton->setPopupMode(QToolButton::QToolButton::InstantPopup); menuButton->setMenu(m_mainMenu); toolbar->addWidget(menuButton); toolbar->addSeparator(); toolbar->addAction(Actions["keyframesTrimInAction"]); toolbar->addAction(Actions["keyframesTrimOutAction"]); toolbar->addAction(Actions["keyframesAnimateInAction"]); toolbar->addAction(Actions["keyframesAnimateOutAction"]); toolbar->addSeparator(); toolbar->addAction(Actions["timelineSnapAction"]); toolbar->addAction(Actions["keyframesScrubDragAction"]); toolbar->addSeparator(); toolbar->addAction(Actions["keyframesZoomOutAction"]); QSlider *zoomSlider = new QSlider(); zoomSlider->setOrientation(Qt::Horizontal); zoomSlider->setMaximumWidth(200); zoomSlider->setMinimum(0); zoomSlider->setMaximum(300); zoomSlider->setValue(100); zoomSlider->setTracking(false); connect(zoomSlider, &QSlider::valueChanged, this, [&](int value) { if (!isVisible() || !m_qview.rootObject()) return; emit setZoom(value / 100.0); }); connect(this, &KeyframesDock::timeScaleChanged, zoomSlider, [ = ]() { double value = round(pow(m_timeScale - 0.01, 1.0 / 3.0) * 100.0); zoomSlider->setValue(value); }); toolbar->addWidget(zoomSlider); toolbar->addAction(Actions["keyframesZoomInAction"]); toolbar->addAction(Actions["keyframesZoomFitAction"]); vboxLayout->setMenuBar(toolbar); m_qview.setFocusPolicy(Qt::StrongFocus); m_qview.quickWindow()->setPersistentSceneGraph(false); #ifndef Q_OS_MAC m_qview.setAttribute(Qt::WA_AcceptTouchEvents); #endif setWidget(&m_qview); QmlUtilities::setCommonProperties(m_qview.rootContext()); m_qview.rootContext()->setContextProperty("keyframes", this); m_qview.rootContext()->setContextProperty("view", new QmlView(&m_qview)); m_qview.rootContext()->setContextProperty("parameters", &m_model); m_qview.setResizeMode(QQuickWidget::SizeRootObjectToView); m_qview.setClearColor(palette().window().color()); m_qview.quickWindow()->setPersistentSceneGraph(false); #ifndef Q_OS_MAC m_qview.setAttribute(Qt::WA_AcceptTouchEvents); #endif setCurrentFilter(0, 0); connect(this, SIGNAL(visibilityChanged(bool)), this, SLOT(load(bool))); vboxLayout->addWidget(&m_qview); QWidget *dockContentsWidget = new QWidget(); dockContentsWidget->setLayout(vboxLayout); QDockWidget::setWidget(dockContentsWidget); LOG_DEBUG() << "end"; } void KeyframesDock::setupActions() { QIcon icon; QAction *action; action = new QAction(tr("Set Filter Start"), this); action->setShortcut(QKeySequence(Qt::Key_BracketLeft)); icon = QIcon::fromTheme("keyframes-filter-in", QIcon(":/icons/oxygen/32x32/actions/keyframes-filter-in.png")); action->setIcon(icon); connect(action, &QAction::triggered, this, [&]() { if (m_qmlProducer && m_filter && m_filter->allowTrim()) { int i = m_qmlProducer->position() + m_qmlProducer->in(); m_model.trimFilterIn(i); } }); connect(this, &KeyframesDock::newFilter, action, [ = ]() { bool enabled = false; if (m_filter && m_filter->allowTrim()) enabled = true; action->setEnabled(enabled); }); Actions.add("keyframesTrimInAction", action); action = new QAction(tr("Set Filter End"), this); action->setShortcut(QKeySequence(Qt::Key_BracketRight)); icon = QIcon::fromTheme("keyframes-filter-out", QIcon(":/icons/oxygen/32x32/actions/keyframes-filter-out.png")); action->setIcon(icon); connect(action, &QAction::triggered, this, [&]() { if (m_qmlProducer && m_filter && m_filter->allowTrim()) { int i = m_qmlProducer->position() + m_qmlProducer->in(); m_model.trimFilterOut(i); } }); connect(this, &KeyframesDock::newFilter, action, [ = ]() { bool enabled = false; if (m_filter && m_filter->allowTrim()) enabled = true; action->setEnabled(enabled); }); Actions.add("keyframesTrimOutAction", action); action = new QAction(tr("Set First Simple Keyframe"), this); action->setShortcut(QKeySequence(Qt::Key_BraceLeft)); icon = QIcon::fromTheme("keyframes-simple-in", QIcon(":/icons/oxygen/32x32/actions/keyframes-simple-in.png")); action->setIcon(icon); connect(action, &QAction::triggered, this, [&]() { if (m_qmlProducer && m_filter && m_filter->allowAnimateIn()) { int i = m_qmlProducer->position() + m_qmlProducer->in() - m_filter->in(); m_filter->setAnimateIn(i); } }); connect(this, &KeyframesDock::newFilter, action, [ = ]() { bool enabled = false; if (m_filter && m_filter->allowAnimateIn()) enabled = true; action->setEnabled(enabled); }); Actions.add("keyframesAnimateInAction", action); action = new QAction(tr("Set Second Simple Keyframe"), this); action->setShortcut(QKeySequence(Qt::Key_BraceRight)); icon = QIcon::fromTheme("keyframes-simple-out", QIcon(":/icons/oxygen/32x32/actions/keyframes-simple-out.png")); action->setIcon(icon); connect(action, &QAction::triggered, this, [&]() { if (m_qmlProducer && m_filter && m_filter->allowAnimateOut()) { int i = m_filter->out() - (m_qmlProducer->position() + m_qmlProducer->in()); m_filter->setAnimateOut(i); } }); connect(this, &KeyframesDock::newFilter, action, [ = ]() { bool enabled = false; if (m_filter && m_filter->allowAnimateOut()) enabled = true; action->setEnabled(enabled); }); Actions.add("keyframesAnimateOutAction", action); action = new QAction(tr("Scrub While Dragging"), this); icon = QIcon::fromTheme("scrub_drag", QIcon(":/icons/oxygen/32x32/actions/scrub_drag.png")); action->setIcon(icon); action->setCheckable(true); action->setChecked(Settings.keyframesDragScrub()); connect(action, &QAction::triggered, this, [&](bool checked) { Settings.setKeyframesDragScrub(checked); }); connect(&Settings, &ShotcutSettings::keyframesDragScrubChanged, action, [ = ]() { action->setChecked(Settings.keyframesDragScrub()); }); Actions.add("keyframesScrubDragAction", action); action = new QAction(tr("Zoom Keyframes Out"), this); action->setShortcut(QKeySequence(Qt::ALT | Qt::Key_Minus)); icon = QIcon::fromTheme("zoom-out", QIcon(":/icons/oxygen/32x32/actions/zoom-out.png")); action->setIcon(icon); connect(action, &QAction::triggered, this, [&]() { if (!isVisible() || !m_qview.rootObject()) return; emit zoomOut(); }); Actions.add("keyframesZoomOutAction", action); action = new QAction(tr("Zoom Keyframes In"), this); action->setShortcut(QKeySequence(Qt::ALT | Qt::Key_Plus)); icon = QIcon::fromTheme("zoom-in", QIcon(":/icons/oxygen/32x32/actions/zoom-in.png")); action->setIcon(icon); connect(action, &QAction::triggered, this, [&]() { if (!isVisible() || !m_qview.rootObject()) return; emit zoomIn(); }); Actions.add("keyframesZoomInAction", action); action = new QAction(tr("Zoom Keyframes To Fit"), this); action->setShortcut(QKeySequence(Qt::ALT | Qt::Key_0)); icon = QIcon::fromTheme("zoom-fit-best", QIcon(":/icons/oxygen/32x32/actions/zoom-fit-best.png")); action->setIcon(icon); connect(action, &QAction::triggered, this, [&]() { if (!isVisible() || !m_qview.rootObject()) return; emit zoomToFit(); }); Actions.add("keyframesZoomFitAction", action); // Actions to modify previous keyframes QActionGroup *keyframeTypePrevActionGroup = new QActionGroup(this); keyframeTypePrevActionGroup->setExclusive(true); action = new QAction(tr("Hold"), this); connect(action, &QAction::triggered, this, [&]() { if (!isVisible() || !m_qview.rootObject()) return; int currentTrack = m_qview.rootObject()->property("currentTrack").toInt(); for (auto keyframeIndex : m_qview.rootObject()->property("selection").toList()) { m_model.setInterpolation(currentTrack, keyframeIndex.toInt() - 1, KeyframesModel::DiscreteInterpolation); } }); icon = QIcon::fromTheme("keyframe-hold", QIcon(":/icons/oxygen/32x32/actions/keyframe-hold.png")); action->setIcon(icon); keyframeTypePrevActionGroup->addAction(action); Actions.add("keyframesTypePrevHoldAction", action); action = new QAction(tr("Linear"), this); connect(action, &QAction::triggered, this, [&]() { if (!isVisible() || !m_qview.rootObject()) return; int currentTrack = m_qview.rootObject()->property("currentTrack").toInt(); for (auto keyframeIndex : m_qview.rootObject()->property("selection").toList()) { m_model.setInterpolation(currentTrack, keyframeIndex.toInt() - 1, KeyframesModel::LinearInterpolation); } }); icon = QIcon::fromTheme("keyframe-linear", QIcon(":/icons/oxygen/32x32/actions/keyframe-linear.png")); action->setIcon(icon); keyframeTypePrevActionGroup->addAction(action); Actions.add("keyframesTypePrevLinearAction", action); action = new QAction(tr("Smooth"), this); connect(action, &QAction::triggered, this, [&]() { if (!isVisible() || !m_qview.rootObject()) return; int currentTrack = m_qview.rootObject()->property("currentTrack").toInt(); for (auto keyframeIndex : m_qview.rootObject()->property("selection").toList()) { #if LIBMLT_VERSION_INT >= ((7<<16)+(21<<8)) m_model.setInterpolation(currentTrack, keyframeIndex.toInt() - 1, KeyframesModel::SmoothNaturalInterpolation); #else m_model.setInterpolation(currentTrack, keyframeIndex.toInt() - 1, KeyframesModel::SmoothLooseInterpolation); #endif } }); icon = QIcon::fromTheme("keyframe-smooth", QIcon(":/icons/oxygen/32x32/actions/keyframe-smooth.png")); action->setIcon(icon); keyframeTypePrevActionGroup->addAction(action); Actions.add("keyframesTypePrevSmoothNaturalAction", action); action = new QAction(tr("Ease Out Sinusoidal"), this); connect(action, &QAction::triggered, this, [&]() { if (!isVisible() || !m_qview.rootObject()) return; int currentTrack = m_qview.rootObject()->property("currentTrack").toInt(); for (auto keyframeIndex : m_qview.rootObject()->property("selection").toList()) { m_model.setInterpolation(currentTrack, keyframeIndex.toInt() - 1, KeyframesModel::EaseOutSinusoidal); } }); icon = QIcon::fromTheme("ease-out-sinu", QIcon(":/icons/oxygen/32x32/actions/ease-out-sinu.png")); action->setIcon(icon); keyframeTypePrevActionGroup->addAction(action); Actions.add("keyframesTypePrevEaseOutSinuAction", action); action = new QAction(tr("Ease Out Quadratic"), this); connect(action, &QAction::triggered, this, [&]() { if (!isVisible() || !m_qview.rootObject()) return; int currentTrack = m_qview.rootObject()->property("currentTrack").toInt(); for (auto keyframeIndex : m_qview.rootObject()->property("selection").toList()) { m_model.setInterpolation(currentTrack, keyframeIndex.toInt() - 1, KeyframesModel::EaseOutQuadratic); } }); icon = QIcon::fromTheme("ease-out-quad", QIcon(":/icons/oxygen/32x32/actions/ease-out-quad.png")); action->setIcon(icon); keyframeTypePrevActionGroup->addAction(action); Actions.add("keyframesTypePrevEaseOutQuadAction", action); action = new QAction(tr("Ease Out Cubic"), this); connect(action, &QAction::triggered, this, [&]() { if (!isVisible() || !m_qview.rootObject()) return; int currentTrack = m_qview.rootObject()->property("currentTrack").toInt(); for (auto keyframeIndex : m_qview.rootObject()->property("selection").toList()) { m_model.setInterpolation(currentTrack, keyframeIndex.toInt() - 1, KeyframesModel::EaseOutCubic); } }); icon = QIcon::fromTheme("ease-out-cube", QIcon(":/icons/oxygen/32x32/actions/ease-out-cube.png")); action->setIcon(icon); keyframeTypePrevActionGroup->addAction(action); Actions.add("keyframesTypePrevEaseOutCubeAction", action); action = new QAction(tr("Ease Out Quartic"), this); connect(action, &QAction::triggered, this, [&]() { if (!isVisible() || !m_qview.rootObject()) return; int currentTrack = m_qview.rootObject()->property("currentTrack").toInt(); for (auto keyframeIndex : m_qview.rootObject()->property("selection").toList()) { m_model.setInterpolation(currentTrack, keyframeIndex.toInt() - 1, KeyframesModel::EaseOutQuartic); } }); icon = QIcon::fromTheme("ease-out-quar", QIcon(":/icons/oxygen/32x32/actions/ease-out-quar.png")); action->setIcon(icon); keyframeTypePrevActionGroup->addAction(action); Actions.add("keyframesTypePrevEaseOutQuartAction", action); action = new QAction(tr("Ease Out Quintic"), this); connect(action, &QAction::triggered, this, [&]() { if (!isVisible() || !m_qview.rootObject()) return; int currentTrack = m_qview.rootObject()->property("currentTrack").toInt(); for (auto keyframeIndex : m_qview.rootObject()->property("selection").toList()) { m_model.setInterpolation(currentTrack, keyframeIndex.toInt() - 1, KeyframesModel::EaseOutQuintic); } }); icon = QIcon::fromTheme("ease-out-quin", QIcon(":/icons/oxygen/32x32/actions/ease-out-quin.png")); action->setIcon(icon); keyframeTypePrevActionGroup->addAction(action); Actions.add("keyframesTypePrevEaseOutQuintAction", action); action = new QAction(tr("Ease Out Exponential"), this); connect(action, &QAction::triggered, this, [&]() { if (!isVisible() || !m_qview.rootObject()) return; int currentTrack = m_qview.rootObject()->property("currentTrack").toInt(); for (auto keyframeIndex : m_qview.rootObject()->property("selection").toList()) { m_model.setInterpolation(currentTrack, keyframeIndex.toInt() - 1, KeyframesModel::EaseOutExponential); } }); icon = QIcon::fromTheme("ease-out-expo", QIcon(":/icons/oxygen/32x32/actions/ease-out-expo.png")); action->setIcon(icon); keyframeTypePrevActionGroup->addAction(action); Actions.add("keyframesTypePrevEaseOutExpoAction", action); action = new QAction(tr("Ease Out Circular"), this); connect(action, &QAction::triggered, this, [&]() { if (!isVisible() || !m_qview.rootObject()) return; int currentTrack = m_qview.rootObject()->property("currentTrack").toInt(); for (auto keyframeIndex : m_qview.rootObject()->property("selection").toList()) { m_model.setInterpolation(currentTrack, keyframeIndex.toInt() - 1, KeyframesModel::EaseOutCircular); } }); icon = QIcon::fromTheme("ease-out-circ", QIcon(":/icons/oxygen/32x32/actions/ease-out-circ.png")); action->setIcon(icon); keyframeTypePrevActionGroup->addAction(action); Actions.add("keyframesTypePrevEaseOutCircAction", action); action = new QAction(tr("Ease Out Back"), this); connect(action, &QAction::triggered, this, [&]() { if (!isVisible() || !m_qview.rootObject()) return; int currentTrack = m_qview.rootObject()->property("currentTrack").toInt(); for (auto keyframeIndex : m_qview.rootObject()->property("selection").toList()) { m_model.setInterpolation(currentTrack, keyframeIndex.toInt() - 1, KeyframesModel::EaseOutBack); } }); connect(this, &KeyframesDock::newFilter, action, [ = ]() { bool enabled = true; if (m_metadata && m_metadata->keyframes() && !m_metadata->keyframes()->allowOvershoot()) { enabled = false; } action->setVisible(enabled); action->setEnabled(enabled); }); icon = QIcon::fromTheme("ease-out-back", QIcon(":/icons/oxygen/32x32/actions/ease-out-back.png")); action->setIcon(icon); keyframeTypePrevActionGroup->addAction(action); Actions.add("keyframesTypePrevEaseOutBackAction", action); action = new QAction(tr("Ease Out Elastic"), this); connect(action, &QAction::triggered, this, [&]() { if (!isVisible() || !m_qview.rootObject()) return; int currentTrack = m_qview.rootObject()->property("currentTrack").toInt(); for (auto keyframeIndex : m_qview.rootObject()->property("selection").toList()) { m_model.setInterpolation(currentTrack, keyframeIndex.toInt() - 1, KeyframesModel::EaseOutElastic); } }); connect(this, &KeyframesDock::newFilter, action, [ = ]() { bool enabled = true; if (m_metadata && m_metadata->keyframes() && !m_metadata->keyframes()->allowOvershoot()) { enabled = false; } action->setVisible(enabled); action->setEnabled(enabled); }); icon = QIcon::fromTheme("ease-out-elas", QIcon(":/icons/oxygen/32x32/actions/ease-out-elas.png")); action->setIcon(icon); keyframeTypePrevActionGroup->addAction(action); Actions.add("keyframesTypePrevEaseOutElasAction", action); action = new QAction(tr("Ease Out Bounce"), this); connect(action, &QAction::triggered, this, [&]() { if (!isVisible() || !m_qview.rootObject()) return; int currentTrack = m_qview.rootObject()->property("currentTrack").toInt(); for (auto keyframeIndex : m_qview.rootObject()->property("selection").toList()) { m_model.setInterpolation(currentTrack, keyframeIndex.toInt() - 1, KeyframesModel::EaseOutBounce); } }); icon = QIcon::fromTheme("ease-out-boun", QIcon(":/icons/oxygen/32x32/actions/ease-out-boun.png")); action->setIcon(icon); keyframeTypePrevActionGroup->addAction(action); Actions.add("keyframesTypePrevEaseOutBounAction", action); // Actions to modify selected keyframes QActionGroup *keyframeTypeActionGroup = new QActionGroup(this); keyframeTypeActionGroup->setExclusive(true); action = new QAction(tr("Hold"), this); connect(action, &QAction::triggered, this, [&]() { if (!isVisible() || !m_qview.rootObject()) return; int currentTrack = m_qview.rootObject()->property("currentTrack").toInt(); for (auto keyframeIndex : m_qview.rootObject()->property("selection").toList()) { m_model.setInterpolation(currentTrack, keyframeIndex.toInt(), KeyframesModel::DiscreteInterpolation); } }); icon = QIcon::fromTheme("keyframe-hold", QIcon(":/icons/oxygen/32x32/actions/keyframe-hold.png")); action->setIcon(icon); keyframeTypeActionGroup->addAction(action); Actions.add("keyframesTypeHoldAction", action); action = new QAction(tr("Linear"), this); connect(action, &QAction::triggered, this, [&]() { if (!isVisible() || !m_qview.rootObject()) return; int currentTrack = m_qview.rootObject()->property("currentTrack").toInt(); for (auto keyframeIndex : m_qview.rootObject()->property("selection").toList()) { m_model.setInterpolation(currentTrack, keyframeIndex.toInt(), KeyframesModel::LinearInterpolation); } }); icon = QIcon::fromTheme("keyframe-linear", QIcon(":/icons/oxygen/32x32/actions/keyframe-linear.png")); action->setIcon(icon); keyframeTypeActionGroup->addAction(action); Actions.add("keyframesTypeLinearAction", action); action = new QAction(tr("Smooth"), this); connect(action, &QAction::triggered, this, [&]() { if (!isVisible() || !m_qview.rootObject()) return; int currentTrack = m_qview.rootObject()->property("currentTrack").toInt(); for (auto keyframeIndex : m_qview.rootObject()->property("selection").toList()) { #if LIBMLT_VERSION_INT >= ((7<<16)+(21<<8)) m_model.setInterpolation(currentTrack, keyframeIndex.toInt(), KeyframesModel::SmoothNaturalInterpolation); #else m_model.setInterpolation(currentTrack, keyframeIndex.toInt(), KeyframesModel::SmoothLooseInterpolation); #endif } }); icon = QIcon::fromTheme("keyframe-smooth", QIcon(":/icons/oxygen/32x32/actions/keyframe-smooth.png")); action->setIcon(icon); keyframeTypeActionGroup->addAction(action); Actions.add("keyframesTypeSmoothNaturalAction", action); action = new QAction(tr("Ease In Sinusoidal"), this); connect(action, &QAction::triggered, this, [&]() { if (!isVisible() || !m_qview.rootObject()) return; int currentTrack = m_qview.rootObject()->property("currentTrack").toInt(); for (auto keyframeIndex : m_qview.rootObject()->property("selection").toList()) { m_model.setInterpolation(currentTrack, keyframeIndex.toInt(), KeyframesModel::EaseInSinusoidal); } }); icon = QIcon::fromTheme("ease-in-sinu", QIcon(":/icons/oxygen/32x32/actions/ease-in-sinu.png")); action->setIcon(icon); keyframeTypeActionGroup->addAction(action); Actions.add("keyframesTypeEaseInSinuAction", action); action = new QAction(tr("Ease In Quadratic"), this); connect(action, &QAction::triggered, this, [&]() { if (!isVisible() || !m_qview.rootObject()) return; int currentTrack = m_qview.rootObject()->property("currentTrack").toInt(); for (auto keyframeIndex : m_qview.rootObject()->property("selection").toList()) { m_model.setInterpolation(currentTrack, keyframeIndex.toInt(), KeyframesModel::EaseInQuadratic); } }); icon = QIcon::fromTheme("ease-in-quad", QIcon(":/icons/oxygen/32x32/actions/ease-in-quad.png")); action->setIcon(icon); keyframeTypeActionGroup->addAction(action); Actions.add("keyframesTypeEaseInQuadAction", action); action = new QAction(tr("Ease In Cubic"), this); connect(action, &QAction::triggered, this, [&]() { if (!isVisible() || !m_qview.rootObject()) return; int currentTrack = m_qview.rootObject()->property("currentTrack").toInt(); for (auto keyframeIndex : m_qview.rootObject()->property("selection").toList()) { m_model.setInterpolation(currentTrack, keyframeIndex.toInt(), KeyframesModel::EaseInCubic); } }); icon = QIcon::fromTheme("ease-in-cube", QIcon(":/icons/oxygen/32x32/actions/ease-in-cube.png")); action->setIcon(icon); keyframeTypeActionGroup->addAction(action); Actions.add("keyframesTypeEaseInCubeAction", action); action = new QAction(tr("Ease In Quartic"), this); connect(action, &QAction::triggered, this, [&]() { if (!isVisible() || !m_qview.rootObject()) return; int currentTrack = m_qview.rootObject()->property("currentTrack").toInt(); for (auto keyframeIndex : m_qview.rootObject()->property("selection").toList()) { m_model.setInterpolation(currentTrack, keyframeIndex.toInt(), KeyframesModel::EaseInQuartic); } }); icon = QIcon::fromTheme("ease-in-quar", QIcon(":/icons/oxygen/32x32/actions/ease-in-quar.png")); action->setIcon(icon); keyframeTypeActionGroup->addAction(action); Actions.add("keyframesTypeEaseInQuartAction", action); action = new QAction(tr("Ease In Quintic"), this); connect(action, &QAction::triggered, this, [&]() { if (!isVisible() || !m_qview.rootObject()) return; int currentTrack = m_qview.rootObject()->property("currentTrack").toInt(); for (auto keyframeIndex : m_qview.rootObject()->property("selection").toList()) { m_model.setInterpolation(currentTrack, keyframeIndex.toInt(), KeyframesModel::EaseInQuintic); } }); icon = QIcon::fromTheme("ease-in-quin", QIcon(":/icons/oxygen/32x32/actions/ease-in-quin.png")); action->setIcon(icon); keyframeTypeActionGroup->addAction(action); Actions.add("keyframesTypeEaseInQuintAction", action); action = new QAction(tr("Ease In Exponential"), this); connect(action, &QAction::triggered, this, [&]() { if (!isVisible() || !m_qview.rootObject()) return; int currentTrack = m_qview.rootObject()->property("currentTrack").toInt(); for (auto keyframeIndex : m_qview.rootObject()->property("selection").toList()) { m_model.setInterpolation(currentTrack, keyframeIndex.toInt(), KeyframesModel::EaseInExponential); } }); icon = QIcon::fromTheme("ease-in-expo", QIcon(":/icons/oxygen/32x32/actions/ease-in-expo.png")); action->setIcon(icon); keyframeTypeActionGroup->addAction(action); Actions.add("keyframesTypeEaseInExpoAction", action); action = new QAction(tr("Ease In Circular"), this); connect(action, &QAction::triggered, this, [&]() { if (!isVisible() || !m_qview.rootObject()) return; int currentTrack = m_qview.rootObject()->property("currentTrack").toInt(); for (auto keyframeIndex : m_qview.rootObject()->property("selection").toList()) { m_model.setInterpolation(currentTrack, keyframeIndex.toInt(), KeyframesModel::EaseInCircular); } }); icon = QIcon::fromTheme("ease-in-circ", QIcon(":/icons/oxygen/32x32/actions/ease-in-circ.png")); action->setIcon(icon); keyframeTypeActionGroup->addAction(action); Actions.add("keyframesTypeEaseInCircAction", action); action = new QAction(tr("Ease In Back"), this); connect(action, &QAction::triggered, this, [&]() { if (!isVisible() || !m_qview.rootObject()) return; int currentTrack = m_qview.rootObject()->property("currentTrack").toInt(); for (auto keyframeIndex : m_qview.rootObject()->property("selection").toList()) { m_model.setInterpolation(currentTrack, keyframeIndex.toInt(), KeyframesModel::EaseInBack); } }); connect(this, &KeyframesDock::newFilter, action, [ = ]() { bool enabled = true; if (m_metadata && m_metadata->keyframes() && !m_metadata->keyframes()->allowOvershoot()) { enabled = false; } action->setVisible(enabled); action->setEnabled(enabled); }); icon = QIcon::fromTheme("ease-in-back", QIcon(":/icons/oxygen/32x32/actions/ease-in-back.png")); action->setIcon(icon); keyframeTypeActionGroup->addAction(action); Actions.add("keyframesTypeEaseInBackAction", action); action = new QAction(tr("Ease In Elastic"), this); connect(action, &QAction::triggered, this, [&]() { if (!isVisible() || !m_qview.rootObject()) return; int currentTrack = m_qview.rootObject()->property("currentTrack").toInt(); for (auto keyframeIndex : m_qview.rootObject()->property("selection").toList()) { m_model.setInterpolation(currentTrack, keyframeIndex.toInt(), KeyframesModel::EaseInElastic); } }); connect(this, &KeyframesDock::newFilter, action, [ = ]() { bool enabled = true; if (m_metadata && m_metadata->keyframes() && !m_metadata->keyframes()->allowOvershoot()) { enabled = false; } action->setVisible(enabled); action->setEnabled(enabled); }); icon = QIcon::fromTheme("ease-in-elas", QIcon(":/icons/oxygen/32x32/actions/ease-in-elas.png")); action->setIcon(icon); keyframeTypeActionGroup->addAction(action); Actions.add("keyframesTypeEaseInElasAction", action); action = new QAction(tr("Ease In Bounce"), this); connect(action, &QAction::triggered, this, [&]() { if (!isVisible() || !m_qview.rootObject()) return; int currentTrack = m_qview.rootObject()->property("currentTrack").toInt(); for (auto keyframeIndex : m_qview.rootObject()->property("selection").toList()) { m_model.setInterpolation(currentTrack, keyframeIndex.toInt(), KeyframesModel::EaseInBounce); } }); icon = QIcon::fromTheme("ease-in-boun", QIcon(":/icons/oxygen/32x32/actions/ease-in-boun.png")); action->setIcon(icon); keyframeTypeActionGroup->addAction(action); Actions.add("keyframesTypeEaseInBounAction", action); action = new QAction(tr("Ease In/Out Sinusoidal"), this); connect(action, &QAction::triggered, this, [&]() { if (!isVisible() || !m_qview.rootObject()) return; int currentTrack = m_qview.rootObject()->property("currentTrack").toInt(); for (auto keyframeIndex : m_qview.rootObject()->property("selection").toList()) { m_model.setInterpolation(currentTrack, keyframeIndex.toInt(), KeyframesModel::EaseInOutSinusoidal); } }); icon = QIcon::fromTheme("ease-inout-sinu", QIcon(":/icons/oxygen/32x32/actions/ease-inout-sinu.png")); action->setIcon(icon); keyframeTypeActionGroup->addAction(action); Actions.add("keyframesTypeEaseInOutSinuAction", action); action = new QAction(tr("Ease In/Out Quadratic"), this); connect(action, &QAction::triggered, this, [&]() { if (!isVisible() || !m_qview.rootObject()) return; int currentTrack = m_qview.rootObject()->property("currentTrack").toInt(); for (auto keyframeIndex : m_qview.rootObject()->property("selection").toList()) { m_model.setInterpolation(currentTrack, keyframeIndex.toInt(), KeyframesModel::EaseInOutQuadratic); } }); icon = QIcon::fromTheme("ease-inout-quad", QIcon(":/icons/oxygen/32x32/actions/ease-inout-quad.png")); action->setIcon(icon); keyframeTypeActionGroup->addAction(action); Actions.add("keyframesTypeEaseInOutQuadAction", action); action = new QAction(tr("Ease In/Out Cubic"), this); connect(action, &QAction::triggered, this, [&]() { if (!isVisible() || !m_qview.rootObject()) return; int currentTrack = m_qview.rootObject()->property("currentTrack").toInt(); for (auto keyframeIndex : m_qview.rootObject()->property("selection").toList()) { m_model.setInterpolation(currentTrack, keyframeIndex.toInt(), KeyframesModel::EaseInOutCubic); } }); icon = QIcon::fromTheme("ease-inout-cube", QIcon(":/icons/oxygen/32x32/actions/ease-inout-cube.png")); action->setIcon(icon); keyframeTypeActionGroup->addAction(action); Actions.add("keyframesTypeEaseInOutCubeAction", action); action = new QAction(tr("Ease In/Out Quartic"), this); connect(action, &QAction::triggered, this, [&]() { if (!isVisible() || !m_qview.rootObject()) return; int currentTrack = m_qview.rootObject()->property("currentTrack").toInt(); for (auto keyframeIndex : m_qview.rootObject()->property("selection").toList()) { m_model.setInterpolation(currentTrack, keyframeIndex.toInt(), KeyframesModel::EaseInOutQuartic); } }); icon = QIcon::fromTheme("ease-inout-quar", QIcon(":/icons/oxygen/32x32/actions/ease-inout-quar.png")); action->setIcon(icon); keyframeTypeActionGroup->addAction(action); Actions.add("keyframesTypeEaseInOutQuartAction", action); action = new QAction(tr("Ease In/Out Quintic"), this); connect(action, &QAction::triggered, this, [&]() { if (!isVisible() || !m_qview.rootObject()) return; int currentTrack = m_qview.rootObject()->property("currentTrack").toInt(); for (auto keyframeIndex : m_qview.rootObject()->property("selection").toList()) { m_model.setInterpolation(currentTrack, keyframeIndex.toInt(), KeyframesModel::EaseInOutQuintic); } }); icon = QIcon::fromTheme("ease-inout-quin", QIcon(":/icons/oxygen/32x32/actions/ease-inout-quin.png")); action->setIcon(icon); keyframeTypeActionGroup->addAction(action); Actions.add("keyframesTypeEaseInOutQuintAction", action); action = new QAction(tr("Ease In/Out Exponential"), this); connect(action, &QAction::triggered, this, [&]() { if (!isVisible() || !m_qview.rootObject()) return; int currentTrack = m_qview.rootObject()->property("currentTrack").toInt(); for (auto keyframeIndex : m_qview.rootObject()->property("selection").toList()) { m_model.setInterpolation(currentTrack, keyframeIndex.toInt(), KeyframesModel::EaseInOutExponential); } }); icon = QIcon::fromTheme("ease-inout-expo", QIcon(":/icons/oxygen/32x32/actions/ease-inout-expo.png")); action->setIcon(icon); keyframeTypeActionGroup->addAction(action); Actions.add("keyframesTypeEaseInOutExpoAction", action); action = new QAction(tr("Ease In/Out Circular"), this); connect(action, &QAction::triggered, this, [&]() { if (!isVisible() || !m_qview.rootObject()) return; int currentTrack = m_qview.rootObject()->property("currentTrack").toInt(); for (auto keyframeIndex : m_qview.rootObject()->property("selection").toList()) { m_model.setInterpolation(currentTrack, keyframeIndex.toInt(), KeyframesModel::EaseInOutCircular); } }); icon = QIcon::fromTheme("ease-inout-circ", QIcon(":/icons/oxygen/32x32/actions/ease-inout-circ.png")); action->setIcon(icon); keyframeTypeActionGroup->addAction(action); Actions.add("keyframesTypeEaseInOutCircAction", action); action = new QAction(tr("Ease In/Out Back"), this); connect(action, &QAction::triggered, this, [&]() { if (!isVisible() || !m_qview.rootObject()) return; int currentTrack = m_qview.rootObject()->property("currentTrack").toInt(); for (auto keyframeIndex : m_qview.rootObject()->property("selection").toList()) { m_model.setInterpolation(currentTrack, keyframeIndex.toInt(), KeyframesModel::EaseInOutBack); } }); connect(this, &KeyframesDock::newFilter, action, [ = ]() { bool enabled = true; if (m_metadata && m_metadata->keyframes() && !m_metadata->keyframes()->allowOvershoot()) { enabled = false; } action->setVisible(enabled); action->setEnabled(enabled); }); icon = QIcon::fromTheme("ease-inout-back", QIcon(":/icons/oxygen/32x32/actions/ease-inout-back.png")); action->setIcon(icon); keyframeTypeActionGroup->addAction(action); Actions.add("keyframesTypeEaseInOutBackAction", action); action = new QAction(tr("Ease In/Out Elastic"), this); connect(action, &QAction::triggered, this, [&]() { if (!isVisible() || !m_qview.rootObject()) return; int currentTrack = m_qview.rootObject()->property("currentTrack").toInt(); for (auto keyframeIndex : m_qview.rootObject()->property("selection").toList()) { m_model.setInterpolation(currentTrack, keyframeIndex.toInt(), KeyframesModel::EaseInOutElastic); } }); connect(this, &KeyframesDock::newFilter, action, [ = ]() { bool enabled = true; if (m_metadata && m_metadata->keyframes() && !m_metadata->keyframes()->allowOvershoot()) { enabled = false; } action->setVisible(enabled); action->setEnabled(enabled); }); icon = QIcon::fromTheme("ease-inout-elas", QIcon(":/icons/oxygen/32x32/actions/ease-inout-elas.png")); action->setIcon(icon); keyframeTypeActionGroup->addAction(action); Actions.add("keyframesTypeEaseInOutElasAction", action); action = new QAction(tr("Ease In/Out Bounce"), this); connect(action, &QAction::triggered, this, [&]() { if (!isVisible() || !m_qview.rootObject()) return; int currentTrack = m_qview.rootObject()->property("currentTrack").toInt(); for (auto keyframeIndex : m_qview.rootObject()->property("selection").toList()) { m_model.setInterpolation(currentTrack, keyframeIndex.toInt(), KeyframesModel::EaseInOutBounce); } }); icon = QIcon::fromTheme("ease-inout-boun", QIcon(":/icons/oxygen/32x32/actions/ease-inout-boun.png")); action->setIcon(icon); keyframeTypeActionGroup->addAction(action); Actions.add("keyframesTypeEaseInOutBounAction", action); action = new QAction(tr("Remove"), this); connect(action, &QAction::triggered, this, [&]() { if (!isVisible() || !m_qview.rootObject()) return; int currentTrack = m_qview.rootObject()->property("currentTrack").toInt(); for (auto keyframeIndex : m_qview.rootObject()->property("selection").toList()) { m_model.remove(currentTrack, keyframeIndex.toInt()); } }); Actions.add("keyframesRemoveAction", action); action = new QAction(tr("Rebuild Audio Waveform"), this); action->setEnabled(Settings.timelineShowWaveforms()); connect(action, &QAction::triggered, this, [&](bool checked) { if (m_qmlProducer && Settings.timelineShowWaveforms()) { m_qmlProducer->remakeAudioLevels(); } }); connect(&Settings, &ShotcutSettings::timelineShowWaveformsChanged, action, [ = ]() { action->setEnabled(Settings.timelineShowWaveforms()); }); Actions.add("keyframesRebuildAudioWaveformAction", action); action = new QAction(tr("Seek Previous Keyframe"), this); action->setShortcut(QKeySequence(Qt::ALT | Qt::Key_BracketLeft)); action->setEnabled(m_qmlProducer && m_filter); connect(action, &QAction::triggered, this, [&]() { if (m_qmlProducer && m_filter) { if (m_model.advancedKeyframesInUse()) seekPrevious(); else emit seekPreviousSimple(); } }); connect(this, &KeyframesDock::newFilter, action, [ = ]() { action->setEnabled(m_qmlProducer && m_filter); }); Actions.add("keyframesSeekPreviousAction", action); action = new QAction(tr("Seek Next Keyframe"), this); action->setShortcut(QKeySequence(Qt::ALT | Qt::Key_BracketRight)); action->setEnabled(m_qmlProducer && m_filter); connect(action, &QAction::triggered, this, [&]() { if (m_qmlProducer && m_filter) { if (m_model.advancedKeyframesInUse()) seekNext(); else emit seekNextSimple(); } }); connect(this, &KeyframesDock::newFilter, action, [ = ]() { action->setEnabled(m_qmlProducer && m_filter); }); Actions.add("keyframesSeekNextAction", action); action = new QAction(tr("Toggle Keyframe At Playhead"), this); action->setShortcut(QKeySequence(Qt::Key_Semicolon)); action->setEnabled(m_qmlProducer && m_filter); connect(action, &QAction::triggered, this, [&]() { if (m_qmlProducer && m_filter && currentParameter() >= 0) { auto position = m_qmlProducer->position() - (m_filter->in() - m_qmlProducer->in()); auto parameterIndex = currentParameter(); if (m_model.isKeyframe(parameterIndex, position)) { auto keyframeIndex = m_model.keyframeIndex(parameterIndex, position); m_model.remove(parameterIndex, keyframeIndex); } else { m_model.addKeyframe(parameterIndex, position); } } }); connect(this, &KeyframesDock::newFilter, action, [ = ]() { action->setEnabled(m_qmlProducer && m_filter); }); Actions.add("keyframesToggleKeyframeAction", action); } int KeyframesDock::seekPrevious() { if (m_qmlProducer) { int position = m_model.previousKeyframePosition(currentParameter(), m_qmlProducer->position() + m_qmlProducer->in()); position -= m_qmlProducer->in(); m_qmlProducer->setPosition(position); return m_model.keyframeIndex(currentParameter(), position + m_qmlProducer->in() - m_filter->in()); } return 0; } int KeyframesDock::seekNext() { if (m_qmlProducer) { int position = m_model.nextKeyframePosition(currentParameter(), m_qmlProducer->position() + m_qmlProducer->in()); position -= m_qmlProducer->in(); if (position > m_qmlProducer->position()) m_qmlProducer->setPosition(position); else position = m_qmlProducer->position(); return m_model.keyframeIndex(currentParameter(), position + m_qmlProducer->in() - m_filter->in()); } return 0; } void KeyframesDock::setCurrentFilter(QmlFilter *filter, QmlMetadata *meta) { m_filter = filter; m_metadata = meta; if (!m_filter || !m_filter->producer().is_valid()) { m_filter = &m_emptyQmlFilter; m_metadata = &m_emptyQmlMetadata; } m_model.load(m_filter, m_metadata); disconnect(this, SIGNAL(changed())); connect(m_filter, SIGNAL(changed(QString)), SIGNAL(changed())); connect(m_filter, SIGNAL(changed(QString)), &m_model, SLOT(onFilterChanged(QString))); connect(m_filter, SIGNAL(animateInChanged()), &m_model, SLOT(reload())); connect(m_filter, SIGNAL(animateOutChanged()), &m_model, SLOT(reload())); connect(m_filter, SIGNAL(inChanged(int)), &m_model, SLOT(onFilterInChanged(int))); emit newFilter(); } bool KeyframesDock::event(QEvent *event) { bool result = QDockWidget::event(event); if (event->type() == QEvent::PaletteChange || event->type() == QEvent::StyleChange) { load(true); } return result; } void KeyframesDock::keyPressEvent(QKeyEvent *event) { QDockWidget::keyPressEvent(event); if (!event->isAccepted()) MAIN.keyPressEvent(event); } void KeyframesDock::keyReleaseEvent(QKeyEvent *event) { QDockWidget::keyReleaseEvent(event); if (!event->isAccepted()) MAIN.keyReleaseEvent(event); } int KeyframesDock::currentParameter() const { if (!m_qview.rootObject()) return 0; return m_qview.rootObject()->property("currentTrack").toInt(); } void KeyframesDock::setTimeScale(double value) { m_timeScale = value; emit timeScaleChanged(); } void KeyframesDock::load(bool force) { LOG_DEBUG() << "begin" << m_qview.source().isEmpty() << force; if (m_qview.source().isEmpty() || force) { QDir viewPath = QmlUtilities::qmlDir(); viewPath.cd("views"); viewPath.cd("keyframes"); m_qview.engine()->addImportPath(viewPath.path()); QDir modulePath = QmlUtilities::qmlDir(); modulePath.cd("modules"); m_qview.engine()->addImportPath(modulePath.path()); m_qview.setResizeMode(QQuickWidget::SizeRootObjectToView); m_qview.quickWindow()->setColor(palette().window().color()); QUrl source = QUrl::fromLocalFile(viewPath.absoluteFilePath("keyframes.qml")); m_qview.setSource(source); connect(m_qview.rootObject(), SIGNAL(rightClicked()), this, SLOT(onDockRightClicked())); connect(m_qview.rootObject(), SIGNAL(keyframeRightClicked()), this, SLOT(onKeyframeRightClicked())); connect(m_qview.rootObject(), SIGNAL(clipRightClicked()), this, SLOT(onClipRightClicked())); emit timeScaleChanged(); } } void KeyframesDock::reload() { load(true); } void KeyframesDock::onProducerModified() { // The clip name may have changed. if (m_qmlProducer) emit m_qmlProducer->producerChanged(); } void KeyframesDock::onDockRightClicked() { m_mainMenu->popup(QCursor::pos()); } void KeyframesDock::onKeyframeRightClicked() { if (!m_qview.rootObject()) return; bool firstKey = false; bool lastKey = false; for (auto keyframeIndex : m_qview.rootObject()->property("selection").toList()) { int keyIndex = keyframeIndex.toInt(); if (keyIndex == 0) { firstKey = true; } if (keyIndex >= m_model.keyframeCount(currentParameter()) - 1) { lastKey = true; } } m_keyTypePrevMenu->setEnabled(!firstKey); m_keyTypeNextMenu->setEnabled(!lastKey); m_keyMenu->popup(QCursor::pos()); } void KeyframesDock::onClipRightClicked() { m_clipMenu->popup(QCursor::pos()); }
53,812
C++
.cpp
1,088
40.837316
111
0.645921
mltframework/shotcut
10,796
1,118
50
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
13,132
playlistdock.cpp
mltframework_shotcut/src/docks/playlistdock.cpp
/* * Copyright (c) 2012-2024 Meltytech, LLC * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "playlistdock.h" #include "ui_playlistdock.h" #include "actions.h" #include "dialogs/durationdialog.h" #include "dialogs/filedatedialog.h" #include "dialogs/longuitask.h" #include "dialogs/resourcedialog.h" #include "dialogs/slideshowgeneratordialog.h" #include "mainwindow.h" #include "settings.h" #include "shotcut_mlt_properties.h" #include "widgets/docktoolbar.h" #include "widgets/playlisticonview.h" #include "widgets/playlisttable.h" #include "widgets/playlistlistview.h" #include "util.h" #include "commands/playlistcommands.h" #include "proxymanager.h" #include "qmltypes/qmlapplication.h" #include <Logger.h> #include <QItemSelectionModel> #include <QMenu> #include <QStyledItemDelegate> #include <QToolButton> #include <QPainter> #include <QDebug> #include <QHeaderView> #include <QKeyEvent> #include <QDir> #include <QGuiApplication> #include <QClipboard> #include <QActionGroup> static const auto kInOutChangedTimeoutMs = 100; static const auto kTilePaddingPx = 10; #define kDetailedMode "detailed" #define kIconsMode "icons" #define kTiledMode "tiled" class TiledItemDelegate : public QStyledItemDelegate { Q_OBJECT public: TiledItemDelegate(QAbstractItemView *view, QWidget *parent = nullptr) : QStyledItemDelegate(parent), m_view(view) { connect(&Settings, SIGNAL(playlistThumbnailsChanged()), SLOT(emitSizeHintChanged())); } void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { const QImage thumb = index.data(Qt::DecorationRole).value<QImage>(); const QString setting = Settings.playlistThumbnails(); const int lineHeight = painter->fontMetrics().height(); const bool roomEnoughForAllDetails = lineHeight * 3 < thumb.height() + kTilePaddingPx; const QFont oldFont = painter->font(); QFont boldFont(oldFont); boldFont.setBold(true); if (option.state & QStyle::State_Selected) { painter->fillRect(option.rect, option.palette.highlight().color()); } else { if (option.features & QStyleOptionViewItem::Alternate) painter->fillRect(option.rect, option.palette.alternateBase()); } QRect thumbRect(QPoint(), thumb.size()); thumbRect.moveCenter(option.rect.center()); thumbRect.moveLeft(0); painter->drawImage(thumbRect, thumb); const QPoint indexPos = option.rect.topLeft() + QPoint(5, 20); const QString indexStr = "#" + index.data(PlaylistModel::FIELD_INDEX).toString(); painter->setFont(boldFont); painter->setPen(option.palette.color(QPalette::Dark).darker()); painter->drawText(indexPos, indexStr); painter->setPen(option.palette.color(QPalette::WindowText)); painter->drawText(indexPos - QPoint(1, 1), indexStr); painter->setFont(oldFont); QRect centeredTextRect = option.rect; centeredTextRect.setHeight(lineHeight * (roomEnoughForAllDetails ? 3 : 2) + kTilePaddingPx); centeredTextRect.moveCenter(option.rect.center()); QRect textRect = centeredTextRect; textRect.setLeft(thumb.width() + (("hidden" == setting) ? PlaylistModel::THUMBNAIL_HEIGHT : 10)); QPoint textPoint = textRect.topLeft(); textPoint.setY(textPoint.y() + lineHeight); painter->setFont(boldFont); QStringList nameParts = index.data(Qt::DisplayRole).toString().split('\n'); painter->drawText(textPoint, painter->fontMetrics().elidedText(nameParts.first(), Qt::ElideMiddle, textRect.width())); painter->setFont(oldFont); if (nameParts.size() > 1) { textPoint.setY(textPoint.y() + lineHeight); painter->drawText(textPoint, nameParts.last()); } textPoint.setY(textPoint.y() + lineHeight); painter->drawText(textPoint, tr("Duration: %1").arg(index.data( PlaylistModel::FIELD_DURATION).toString())); if (roomEnoughForAllDetails) { textPoint.setY(textPoint.y() + lineHeight); painter->drawText(textPoint, tr("Date: %1").arg(index.data(PlaylistModel::FIELD_DATE).toString())); } } QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const { Q_UNUSED(option); Q_UNUSED(index); const bool doubleHeight = Settings.playlistThumbnails() == "tall" || Settings.playlistThumbnails() == "large"; return QSize(m_view->viewport()->width(), PlaylistModel::THUMBNAIL_HEIGHT * (doubleHeight ? 2 : 1) + kTilePaddingPx); } private slots: void emitSizeHintChanged() { emit sizeHintChanged(QModelIndex()); } private: QAbstractItemView *m_view; }; PlaylistDock::PlaylistDock(QWidget *parent) : QDockWidget(parent), ui(new Ui::PlaylistDock), m_blockResizeColumnsToContents(false) { LOG_DEBUG() << "begin"; ui->setupUi(this); toggleViewAction()->setIcon(windowIcon()); m_selectionModel = new QItemSelectionModel(&m_model, this); connect(m_selectionModel, &QItemSelectionModel::selectionChanged, this, &PlaylistDock::selectionChanged); setupActions(); m_mainMenu = new QMenu(tr("Playlist"), this); m_mainMenu->addAction(Actions["playlistOpenAction"]); m_mainMenu->addAction(Actions["playlistOpenPreviousAction"]); m_mainMenu->addAction(Actions["playlistOpenNextAction"]); m_mainMenu->addAction(Actions["playlistGoToAction"]); m_mainMenu->addAction(Actions["playlistRemoveCutAction"]); m_mainMenu->addAction(Actions["playlistCopyAction"]); m_mainMenu->addAction(Actions["playlistInsertCutAction"]); m_mainMenu->addAction(Actions["playlistUpdateAction"]); m_mainMenu->addAction(Actions["playlistMoveUpAction"]); m_mainMenu->addAction(Actions["playlistMoveDownAction"]); m_mainMenu->addAction(Actions["playlistUpdateThumbnailsAction"]); m_mainMenu->addAction(Actions["playlistSetFileDateAction"]); m_mainMenu->addAction(Actions["playlistAddFilesAction"]); m_mainMenu->addAction(Actions["playlistAppendCutAction"]); m_mainMenu->addSeparator(); QMenu *selectMenu = m_mainMenu->addMenu(tr("Select")); selectMenu->addAction(Actions["playlistSelectAllAction"]); selectMenu->addAction(Actions["playlistSelectNoneAction"]); selectMenu->addAction(Actions["playlistSelectClip1Action"]); selectMenu->addAction(Actions["playlistSelectClip2Action"]); selectMenu->addAction(Actions["playlistSelectClip3Action"]); selectMenu->addAction(Actions["playlistSelectClip4Action"]); selectMenu->addAction(Actions["playlistSelectClip5Action"]); selectMenu->addAction(Actions["playlistSelectClip6Action"]); selectMenu->addAction(Actions["playlistSelectClip7Action"]); selectMenu->addAction(Actions["playlistSelectClip8Action"]); selectMenu->addAction(Actions["playlistSelectClip9Action"]); m_mainMenu->addSeparator(); m_mainMenu->addAction(Actions["playlistRemoveAllAction"]); m_mainMenu->addAction(Actions["playlistAddToTimelineAction"]); m_mainMenu->addAction(Actions["playlistAddToSlideshowAction"]); m_mainMenu->addSeparator(); QMenu *sortByMenu = m_mainMenu->addMenu(tr("Sort")); sortByMenu->addAction(Actions["playlistSortByNameAction"]); sortByMenu->addAction(Actions["playlistSortByDateAction"]); QMenu *columnsMenu = m_mainMenu->addMenu(tr("Columns")); columnsMenu->addAction(Actions["playlistColumnsToggleThumbnailsAction"]); columnsMenu->addAction(Actions["playlistColumnsToggleClipAction"]); columnsMenu->addAction(Actions["playlistColumnsToggleInAction"]); columnsMenu->addAction(Actions["playlistColumnsToggleDurationAction"]); columnsMenu->addAction(Actions["playlistColumnsToggleStartAction"]); columnsMenu->addAction(Actions["playlistColumnsToggleDateAction"]); Actions.loadFromMenu(m_mainMenu); DockToolBar *toolbar = new DockToolBar(tr("Playlist Controls")); toolbar->setAreaHint(Qt::BottomToolBarArea); QToolButton *menuButton = new QToolButton(); menuButton->setIcon(QIcon::fromTheme("show-menu", QIcon(":/icons/oxygen/32x32/actions/show-menu.png"))); menuButton->setToolTip(tr("Playlist Menu")); menuButton->setAutoRaise(true); menuButton->setPopupMode(QToolButton::QToolButton::InstantPopup); menuButton->setMenu(m_mainMenu); toolbar->addWidget(menuButton); toolbar->addSeparator(); toolbar->addAction(Actions["playlistAppendCutAction"]); toolbar->addAction(Actions["playlistRemoveCutAction"]); toolbar->addAction(Actions["playlistAddFilesAction"]); toolbar->addAction(Actions["playlistUpdateAction"]); toolbar->addSeparator(); toolbar->addAction(Actions["playlistViewDetailsAction"]); toolbar->addAction(Actions["playlistViewTilesAction"]); toolbar->addAction(Actions["playlistViewIconsAction"]); toolbar->addSeparator(); ui->verticalLayout->addWidget(toolbar); ui->verticalLayout->addSpacing(2); ui->stackedWidget->setCurrentIndex(0); m_iconsView = new PlaylistIconView(this); ui->listView->parentWidget()->layout()->addWidget(m_iconsView); m_iconsView->setSelectionMode(QAbstractItemView::SingleSelection); QList<QAbstractItemView *> views; views << ui->tableView; views << ui->listView; views << m_iconsView; foreach (QAbstractItemView *view, views) { view->setDragDropMode(QAbstractItemView::DragDrop); view->setDropIndicatorShown(true); view->setDragDropOverwriteMode(false); view->setAcceptDrops(true); view->setDefaultDropAction(Qt::MoveAction); view->setAlternatingRowColors(true); connect(view, SIGNAL(customContextMenuRequested(QPoint)), SLOT(viewCustomContextMenuRequested(QPoint))); connect(view, SIGNAL(doubleClicked(QModelIndex)), SLOT(viewDoubleClicked(QModelIndex))); } connect(ui->tableView, SIGNAL(movedToEnd()), SLOT(onMovedToEnd())); connect(ui->listView, SIGNAL(movedToEnd()), SLOT(onMovedToEnd())); connect(&m_model, SIGNAL(cleared()), this, SLOT(onPlaylistCleared())); connect(&m_model, SIGNAL(created()), this, SLOT(onPlaylistCreated())); connect(&m_model, SIGNAL(loaded()), this, SLOT(onPlaylistLoaded())); connect(&m_model, SIGNAL(modified()), this, SLOT(onPlaylistModified())); connect(&m_model, SIGNAL(dropped(const QMimeData *, int)), this, SLOT(onDropped(const QMimeData *, int))); connect(&m_model, SIGNAL(moveClip(int, int)), SLOT(onMoveClip(int, int))); m_defaultRowHeight = ui->tableView->verticalHeader()->defaultSectionSize(); QString thumbs = Settings.playlistThumbnails(); if (thumbs == "wide") { Actions["playlistThumbnailsLeftAndRightAction"]->trigger(); } else if (thumbs == "tall") { Actions["playlistThumbnailsTopAndBottomAction"]->trigger(); } else if (thumbs == "small") { Actions["playlistThumbnailsInOnlySmallAction"]->trigger(); } else if (thumbs == "large") { Actions["playlistThumbnailsInOnlyLargeAction"]->trigger(); } else { Actions["playlistThumbnailsHiddenAction"]->trigger(); } if (Settings.viewMode() == kDetailedMode) { Actions["playlistViewDetailsAction"]->trigger(); } else if (Settings.viewMode() == kTiledMode) { Actions["playlistViewTilesAction"]->trigger(); } else { /* if (Settings.viewMode() == kIconsMode) */ Actions["playlistViewIconsAction"]->trigger(); } m_inChangedTimer.setInterval(kInOutChangedTimeoutMs); m_inChangedTimer.setSingleShot(true); m_outChangedTimer.setInterval(kInOutChangedTimeoutMs); m_outChangedTimer.setSingleShot(true); connect(&m_inChangedTimer, SIGNAL(timeout()), this, SLOT(onInTimerFired())); connect(&m_outChangedTimer, SIGNAL(timeout()), this, SLOT(onOutTimerFired())); LOG_DEBUG() << "end"; } PlaylistDock::~PlaylistDock() { delete ui; } void PlaylistDock::setupActions() { QIcon icon; QAction *action; action = new QAction(tr("Append"), this); action->setShortcut(QKeySequence(Qt::SHIFT | Qt::Key_A)); action->setToolTip(tr("Add the Source to the playlist")); icon = QIcon::fromTheme("list-add", QIcon(":/icons/oxygen/32x32/actions/list-add.png")); action->setIcon(icon); connect(action, &QAction::triggered, this, &PlaylistDock::onAppendCutActionTriggered); Actions.add("playlistAppendCutAction", action); action = new QAction(tr("Remove"), this); QList<QKeySequence> removeShortcuts; removeShortcuts << QKeySequence(Qt::SHIFT | Qt::Key_X); removeShortcuts << QKeySequence(Qt::SHIFT | Qt::Key_Z); action->setShortcuts(removeShortcuts); action->setToolTip(tr("Remove cut")); icon = QIcon::fromTheme("list-remove", QIcon(":/icons/oxygen/32x32/actions/list-remove.png")); action->setIcon(icon); action->setEnabled(false); connect(action, &QAction::triggered, this, &PlaylistDock::onRemoveActionTriggered); connect(this, &PlaylistDock::selectionChanged, action, [ = ]() { action->setEnabled(m_view->selectionModel()->selectedIndexes().size() > 0); }); Actions.add("playlistRemoveCutAction", action); action = new QAction(tr("Add Files"), this); action->setToolTip(tr("Add files to playlist")); icon = QIcon::fromTheme("list-add-files", QIcon(":/icons/oxygen/32x32/actions/list-add-files.png")); action->setIcon(icon); connect(action, &QAction::triggered, this, &PlaylistDock::onAddFilesActionTriggered); Actions.add("playlistAddFilesAction", action); action = new QAction(tr("Update"), this); action->setShortcut(QKeySequence(Qt::SHIFT | Qt::Key_B)); icon = QIcon::fromTheme("dialog-ok", QIcon(":/icons/oxygen/32x32/actions/dialog-ok.png")); action->setIcon(icon); connect(action, &QAction::triggered, this, &PlaylistDock::onUpdateActionTriggered); connect(this, &PlaylistDock::enableUpdate, action, &QAction::setEnabled); Actions.add("playlistUpdateAction", action); QActionGroup *modeGroup = new QActionGroup(this); modeGroup->setExclusive(true); action = new QAction(tr("Tiles"), this); action->setToolTip(tr("View as tiles")); icon = QIcon::fromTheme("view-list-details", QIcon(":/icons/oxygen/32x32/actions/view-list-details.png")); action->setIcon(icon); action->setCheckable(true); connect(action, &QAction::triggered, this, [&](bool checked) { Settings.setViewMode(kTiledMode); updateViewMode(); }); modeGroup->addAction(action); Actions.add("playlistViewTilesAction", action); action = new QAction(tr("Icons"), this); action->setToolTip(tr("View as icons")); icon = QIcon::fromTheme("view-list-icons", QIcon(":/icons/oxygen/32x32/actions/view-list-icons.png")); action->setIcon(icon); action->setCheckable(true); connect(action, &QAction::triggered, this, [&](bool checked) { Settings.setViewMode(kIconsMode); updateViewMode(); }); modeGroup->addAction(action); Actions.add("playlistViewIconsAction", action); action = new QAction(tr("Details"), this); action->setToolTip(tr("View as details")); icon = QIcon::fromTheme("view-list-text", QIcon(":/icons/oxygen/32x32/actions/view-list-text.png")); action->setIcon(icon); action->setCheckable(true); connect(action, &QAction::triggered, this, [&](bool checked) { Settings.setViewMode(kDetailedMode); updateViewMode(); }); modeGroup->addAction(action); Actions.add("playlistViewDetailsAction", action); action = new QAction(tr("Open"), this); action->setToolTip(tr("Open the clip in the Source player")); action->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_Return)); action->setEnabled(false); connect(action, &QAction::triggered, this, &PlaylistDock::onOpenActionTriggered); connect(this, &PlaylistDock::selectionChanged, action, [ = ]() { action->setEnabled(m_view->currentIndex().isValid() && m_model.playlist()); }); Actions.add("playlistOpenAction", action); action = new QAction(tr("GoTo"), this); action->setToolTip(tr("Go to the start of this clip in the Project player")); action->setShortcut(QKeySequence(Qt::SHIFT | Qt::Key_Return)); connect(action, &QAction::triggered, this, &PlaylistDock::onGotoActionTriggered); Actions.add("playlistGoToAction", action); action = new QAction(tr("Copy"), this); action->setToolTip(tr("Open a copy of the clip in the Source player")); action->setShortcut(QKeySequence(Qt::SHIFT | Qt::Key_C)); action->setEnabled(false); connect(action, &QAction::triggered, this, &PlaylistDock::onCopyActionTriggered); connect(this, &PlaylistDock::selectionChanged, action, [ = ]() { action->setEnabled(m_view->currentIndex().isValid() && m_model.playlist()); }); Actions.add("playlistCopyAction", action); action = new QAction(tr("Insert"), this); action->setToolTip(tr("Insert")); action->setShortcut(QKeySequence(Qt::SHIFT | Qt::Key_V)); connect(action, &QAction::triggered, this, &PlaylistDock::onInsertCutActionTriggered); Actions.add("playlistInsertCutAction", action); action = new QAction(tr("Update Thumbnails"), this); action->setEnabled(false); connect(action, &QAction::triggered, this, &PlaylistDock::onUpdateThumbnailsActionTriggered); connect(this, &PlaylistDock::selectionChanged, action, [ = ]() { action->setEnabled(m_model.rowCount() > 0); }); Actions.add("playlistUpdateThumbnailsAction", action); action = new QAction(tr("Set Creation Time..."), this); action->setEnabled(false); connect(action, &QAction::triggered, this, &PlaylistDock::onSetFileDateActionTriggered); connect(this, &PlaylistDock::selectionChanged, action, [ = ]() { action->setEnabled(m_view->currentIndex().isValid() && m_model.playlist()); }); Actions.add("playlistSetFileDateAction", action); action = new QAction(tr("Remove All"), this); action->setToolTip(tr("Remove all items from the playlist")); connect(action, &QAction::triggered, this, &PlaylistDock::onRemoveAllActionTriggered); action->setEnabled(m_model.rowCount() > 0); Actions.add("playlistRemoveAllAction", action); action = new QAction(tr("Select All"), this); action->setShortcut(QKeySequence(Qt::CTRL | Qt::SHIFT | Qt::Key_A)); connect(action, &QAction::triggered, this, &PlaylistDock::onSelectAllActionTriggered); action->setEnabled(m_model.rowCount() > 0); Actions.add("playlistSelectAllAction", action); action = new QAction(tr("Select None"), this); action->setShortcut(QKeySequence(Qt::CTRL | Qt::SHIFT | Qt::Key_D)); connect(action, &QAction::triggered, m_selectionModel, &QItemSelectionModel::clearSelection); connect(this, &PlaylistDock::selectionChanged, action, [ = ]() { action->setEnabled(m_selectionModel->selection().size() > 0); }); Actions.add("playlistSelectNoneAction", action); action = new QAction(tr("Move Up"), this); action->setShortcut(QKeySequence(Qt::CTRL | Qt::SHIFT | Qt::Key_Up)); connect(action, &QAction::triggered, m_selectionModel, [ = ]() { raise(); moveClipUp(); decrementIndex(); }); connect(this, &PlaylistDock::selectionChanged, action, [ = ]() { action->setEnabled(m_view->currentIndex().isValid() && m_model.playlist()); }); Actions.add("playlistMoveUpAction", action); action = new QAction(tr("Move Down"), this); action->setShortcut(QKeySequence(Qt::CTRL | Qt::SHIFT | Qt::Key_Down)); connect(action, &QAction::triggered, m_selectionModel, [ = ]() { raise(); moveClipDown(); incrementIndex(); }); connect(this, &PlaylistDock::selectionChanged, action, [ = ]() { action->setEnabled(m_view->currentIndex().isValid() && m_model.playlist()); }); Actions.add("playlistMoveDownAction", action); action = new QAction(tr("Add Selected to Timeline"), this); connect(action, &QAction::triggered, this, &PlaylistDock::onAddToTimelineActionTriggered); connect(this, &PlaylistDock::selectionChanged, action, [ = ]() { action->setEnabled(m_selectionModel->selection().size() > 0); }); Actions.add("playlistAddToTimelineAction", action); action = new QAction(tr("Add Selected to Slideshow"), this); connect(action, &QAction::triggered, this, &PlaylistDock::onAddToSlideshowActionTriggered); connect(this, &PlaylistDock::selectionChanged, action, [ = ]() { action->setEnabled(m_selectionModel->selection().size() > 0); }); Actions.add("playlistAddToSlideshowAction", action); action = new QAction(tr("Sort By Name"), this); connect(action, &QAction::triggered, this, [&](bool checked) { resetPlaylistIndex(); MAIN.undoStack()->push(new Playlist::SortCommand(m_model, PlaylistModel::COLUMN_RESOURCE, Qt::AscendingOrder)); }); Actions.add("playlistSortByNameAction", action); action = new QAction(tr("Sort By Date"), this); connect(action, &QAction::triggered, this, [&](bool checked) { resetPlaylistIndex(); MAIN.undoStack()->push(new Playlist::SortCommand(m_model, PlaylistModel::COLUMN_DATE, Qt::AscendingOrder)); }); Actions.add("playlistSortByDateAction", action); QActionGroup *thumbnailGroup = new QActionGroup(this); thumbnailGroup->setExclusive(true); action = new QAction(tr("Hidden"), this); action->setCheckable(true); connect(action, &QAction::triggered, this, [&](bool checked) { if (checked) { Settings.setPlaylistThumbnails("hidden"); ui->tableView->setColumnHidden(PlaylistModel::COLUMN_THUMBNAIL, true); ui->tableView->verticalHeader()->setDefaultSectionSize(m_defaultRowHeight); } }); thumbnailGroup->addAction(action); Actions.add("playlistThumbnailsHiddenAction", action); action = new QAction(tr("In and Out - Left/Right"), this); action->setCheckable(true); connect(action, &QAction::triggered, this, [&](bool checked) { if (checked) { bool refreshThumbs = Settings.playlistThumbnails() != "tall"; Settings.setPlaylistThumbnails("wide"); if (refreshThumbs) m_model.refreshThumbnails(); ui->tableView->setColumnHidden(PlaylistModel::COLUMN_THUMBNAIL, false); ui->tableView->verticalHeader()->setDefaultSectionSize(PlaylistModel::THUMBNAIL_HEIGHT); ui->tableView->resizeColumnToContents(PlaylistModel::COLUMN_THUMBNAIL); } }); thumbnailGroup->addAction(action); Actions.add("playlistThumbnailsLeftAndRightAction", action); action = new QAction(tr("In and Out - Top/Bottom"), this); action->setCheckable(true); connect(action, &QAction::triggered, this, [&](bool checked) { if (checked) { bool refreshThumbs = Settings.playlistThumbnails() != "wide"; Settings.setPlaylistThumbnails("tall"); if (refreshThumbs) m_model.refreshThumbnails(); ui->tableView->setColumnHidden(PlaylistModel::COLUMN_THUMBNAIL, false); ui->tableView->verticalHeader()->setDefaultSectionSize(PlaylistModel::THUMBNAIL_HEIGHT * 2); ui->tableView->resizeColumnToContents(PlaylistModel::COLUMN_THUMBNAIL); } }); thumbnailGroup->addAction(action); Actions.add("playlistThumbnailsTopAndBottomAction", action); action = new QAction(tr("In Only - Small"), this); action->setCheckable(true); connect(action, &QAction::triggered, this, [&](bool checked) { if (checked) { bool refreshThumbs = Settings.playlistThumbnails() == "hidden"; Settings.setPlaylistThumbnails("small"); if (refreshThumbs) m_model.refreshThumbnails(); ui->tableView->setColumnHidden(PlaylistModel::COLUMN_THUMBNAIL, false); ui->tableView->verticalHeader()->setDefaultSectionSize(PlaylistModel::THUMBNAIL_HEIGHT); ui->tableView->resizeColumnToContents(PlaylistModel::COLUMN_THUMBNAIL); } }); thumbnailGroup->addAction(action); Actions.add("playlistThumbnailsInOnlySmallAction", action); action = new QAction(tr("In Only - Large"), this); action->setCheckable(true); connect(action, &QAction::triggered, this, [&](bool checked) { if (checked) { bool refreshThumbs = Settings.playlistThumbnails() == "hidden"; Settings.setPlaylistThumbnails("large"); if (refreshThumbs) m_model.refreshThumbnails(); ui->tableView->setColumnHidden(PlaylistModel::COLUMN_THUMBNAIL, false); ui->tableView->verticalHeader()->setDefaultSectionSize(PlaylistModel::THUMBNAIL_HEIGHT * 2); ui->tableView->resizeColumnToContents(PlaylistModel::COLUMN_THUMBNAIL); } }); thumbnailGroup->addAction(action); Actions.add("playlistThumbnailsInOnlyLargeAction", action); action = new QAction(tr("Play After Open"), this); action->setCheckable(true); action->setChecked(Settings.playlistAutoplay()); connect(action, &QAction::triggered, this, [&](bool checked) { Settings.setPlaylistAutoplay(checked); }); Actions.add("playlistPlayAfterOpenAction", action); action = new QAction(tr("Open Previous"), this); action->setShortcut(QKeySequence(Qt::ALT | Qt::Key_Up)); action->setEnabled(false); connect(action, &QAction::triggered, this, [ = ]() { raise(); decrementIndex(); onOpenActionTriggered(); }); connect(this, &PlaylistDock::selectionChanged, action, [ = ]() { action->setEnabled(m_view->currentIndex().isValid() && m_model.playlist()); }); Actions.add("playlistOpenPreviousAction", action); action = new QAction(tr("Open Next"), this); action->setShortcut(QKeySequence(Qt::ALT | Qt::Key_Down)); action->setEnabled(false); connect(action, &QAction::triggered, this, [ = ]() { raise(); incrementIndex(); onOpenActionTriggered(); }); connect(this, &PlaylistDock::selectionChanged, action, [ = ]() { action->setEnabled(m_view->currentIndex().isValid() && m_model.playlist()); }); Actions.add("playlistOpenNextAction", action); action = new QAction(tr("Select Clip 1"), this); action->setShortcut(QKeySequence(Qt::Key_1)); action->setEnabled(false); connect(action, &QAction::triggered, this, [ = ]() { raise(); setIndex(0); }); connect(this, &PlaylistDock::selectionChanged, action, [ = ]() { action->setEnabled(m_model.rowCount() > 0); }); Actions.add("playlistSelectClip1Action", action); \ action = new QAction(tr("Select Clip 2"), this); action->setShortcut(QKeySequence(Qt::Key_2)); action->setEnabled(false); connect(action, &QAction::triggered, this, [ = ]() { raise(); setIndex(1); }); connect(this, &PlaylistDock::selectionChanged, action, [ = ]() { action->setEnabled(m_model.rowCount() > 1); }); Actions.add("playlistSelectClip2Action", action); action = new QAction(tr("Select Clip 3"), this); action->setShortcut(QKeySequence(Qt::Key_3)); action->setEnabled(false); connect(action, &QAction::triggered, this, [ = ]() { raise(); setIndex(2); }); connect(this, &PlaylistDock::selectionChanged, action, [ = ]() { action->setEnabled(m_model.rowCount() > 2); }); Actions.add("playlistSelectClip3Action", action); action = new QAction(tr("Select Clip 4"), this); action->setShortcut(QKeySequence(Qt::Key_4)); action->setEnabled(false); connect(action, &QAction::triggered, this, [ = ]() { raise(); setIndex(3); }); connect(this, &PlaylistDock::selectionChanged, action, [ = ]() { action->setEnabled(m_model.rowCount() > 3); }); Actions.add("playlistSelectClip4Action", action); action = new QAction(tr("Select Clip 5"), this); action->setShortcut(QKeySequence(Qt::Key_5)); action->setEnabled(false); connect(action, &QAction::triggered, this, [ = ]() { raise(); setIndex(4); }); connect(this, &PlaylistDock::selectionChanged, action, [ = ]() { action->setEnabled(m_model.rowCount() > 4); }); Actions.add("playlistSelectClip5Action", action); action = new QAction(tr("Select Clip 6"), this); action->setShortcut(QKeySequence(Qt::Key_6)); action->setEnabled(false); connect(action, &QAction::triggered, this, [ = ]() { raise(); setIndex(5); }); connect(this, &PlaylistDock::selectionChanged, action, [ = ]() { action->setEnabled(m_model.rowCount() > 5); }); Actions.add("playlistSelectClip6Action", action); action = new QAction(tr("Select Clip 7"), this); action->setShortcut(QKeySequence(Qt::Key_7)); action->setEnabled(false); connect(action, &QAction::triggered, this, [ = ]() { raise(); setIndex(6); }); connect(this, &PlaylistDock::selectionChanged, action, [ = ]() { action->setEnabled(m_model.rowCount() > 6); }); Actions.add("playlistSelectClip7Action", action); action = new QAction(tr("Select Clip 8"), this); action->setShortcut(QKeySequence(Qt::Key_8)); action->setEnabled(false); connect(action, &QAction::triggered, this, [ = ]() { raise(); setIndex(7); }); connect(this, &PlaylistDock::selectionChanged, action, [ = ]() { action->setEnabled(m_model.rowCount() > 7); }); Actions.add("playlistSelectClip8Action", action); action = new QAction(tr("Select Clip 9"), this); action->setShortcut(QKeySequence(Qt::Key_9)); action->setEnabled(false); connect(action, &QAction::triggered, this, [ = ]() { raise(); setIndex(8); }); connect(this, &PlaylistDock::selectionChanged, action, [ = ]() { action->setEnabled(m_model.rowCount() > 8); }); Actions.add("playlistSelectClip9Action", action); action = new QAction(tr("Thumbnails"), this); action->setChecked(Settings.playlistShowColumn("thumbnails")); action->setCheckable(true); connect(action, &QAction::triggered, this, [ = ](bool checked) { Settings.setPlaylistShowColumn("thumbnails", checked); ui->tableView->setColumnHidden(PlaylistModel::COLUMN_THUMBNAIL, !checked); }); Actions.add("playlistColumnsToggleThumbnailsAction", action); action = new QAction(tr("Clip"), this); action->setChecked(Settings.playlistShowColumn("clip")); action->setCheckable(true); connect(action, &QAction::triggered, this, [ = ](bool checked) { Settings.setPlaylistShowColumn("clip", checked); ui->tableView->setColumnHidden(PlaylistModel::COLUMN_RESOURCE, !checked); }); Actions.add("playlistColumnsToggleClipAction", action); action = new QAction(tr("In"), this); action->setChecked(Settings.playlistShowColumn("in")); action->setCheckable(true); connect(action, &QAction::triggered, this, [ = ](bool checked) { Settings.setPlaylistShowColumn("in", checked); ui->tableView->setColumnHidden(PlaylistModel::COLUMN_IN, !checked); }); Actions.add("playlistColumnsToggleInAction", action); action = new QAction(tr("Duration"), this); action->setChecked(Settings.playlistShowColumn("duration")); action->setCheckable(true); connect(action, &QAction::triggered, this, [ = ](bool checked) { Settings.setPlaylistShowColumn("duration", checked); ui->tableView->setColumnHidden(PlaylistModel::COLUMN_DURATION, !checked); }); Actions.add("playlistColumnsToggleDurationAction", action); action = new QAction(tr("Start"), this); action->setChecked(Settings.playlistShowColumn("start")); action->setCheckable(true); connect(action, &QAction::triggered, this, [ = ](bool checked) { Settings.setPlaylistShowColumn("start", checked); ui->tableView->setColumnHidden(PlaylistModel::COLUMN_START, !checked); }); Actions.add("playlistColumnsToggleStartAction", action); action = new QAction(tr("Date"), this); action->setChecked(Settings.playlistShowColumn("date")); action->setCheckable(true); connect(action, &QAction::triggered, this, [ = ](bool checked) { Settings.setPlaylistShowColumn("date", checked); ui->tableView->setColumnHidden(PlaylistModel::COLUMN_DATE, !checked); }); Actions.add("playlistColumnsToggleDateAction", action); } int PlaylistDock::position() { int result = -1; QModelIndex index = m_view->currentIndex(); if (index.isValid() && m_model.playlist()) { Mlt::ClipInfo *i = m_model.playlist()->clip_info(index.row()); if (i) result = i->start; delete i; } return result; } void PlaylistDock::replaceClipsWithHash(const QString &hash, Mlt::Producer &producer) { QList<Mlt::Producer> producers; for (int i = 0; i < m_model.rowCount(); ++i) { QScopedPointer<Mlt::Producer> clip(m_model.playlist()->get_clip(i)); if (Util::getHash(clip->parent()) == hash) { clip->set(kPlaylistIndexProperty, i + 1); producers << *clip; } } auto n = producers.size(); if (n > 1) { MAIN.undoStack()->beginMacro(tr("Replace %n playlist items", nullptr, n)); } for (auto &clip : producers) { Util::applyCustomProperties(producer, clip.parent(), clip.get_in(), clip.get_out()); MAIN.undoStack()->push( new Playlist::ReplaceCommand(m_model, MLT.XML(&producer), clip.get_int(kPlaylistIndexProperty) - 1)); } if (n > 1) { MAIN.undoStack()->endMacro(); } } void PlaylistDock::getSelectionRange(int *start, int *end) { Mlt::Playlist *playlist = m_model.playlist(); if (!playlist || !m_view->selectionModel() || !m_view->selectionModel()->selectedIndexes().size() ) { *start = -1; *end = -1; return; } // Find the earliest start and the latest end in the selection *start = std::numeric_limits<int>::max(); *end = -1; foreach (auto index, m_view->selectionModel()->selectedIndexes()) { int row = index.row(); int clipStart = playlist->clip_start(row); int clipEnd = clipStart + playlist->clip_length(row); *start = qMin(*start, clipStart); *end = qMax(*end, clipEnd); } } void PlaylistDock::incrementIndex() { QModelIndex index = m_view->currentIndex(); if (!index.isValid()) index = m_model.createIndex(0, 0); else index = m_model.incrementIndex(index); if (index.isValid()) m_view->setCurrentIndex(index); } void PlaylistDock::decrementIndex() { QModelIndex index = m_view->currentIndex(); if (!index.isValid()) index = m_model.createIndex(0, 0); else index = m_model.decrementIndex(index); if (index.isValid()) m_view->setCurrentIndex(index); } void PlaylistDock::setIndex(int row) { QModelIndex index = m_model.createIndex(row, 0); if (index.isValid()) m_view->setCurrentIndex(index); } void PlaylistDock::moveClipUp() { int row = m_view->currentIndex().row(); if (row > 0) { MAIN.undoStack()->push(new Playlist::MoveCommand(m_model, row, row - 1)); resetPlaylistIndex(); } } void PlaylistDock::moveClipDown() { int row = m_view->currentIndex().row(); if (row + 1 < m_model.rowCount()) { MAIN.undoStack()->push(new Playlist::MoveCommand(m_model, row, row + 1)); resetPlaylistIndex(); } } void PlaylistDock::addFiles(int row, const QList<QUrl> &urls) { auto resetIndex = true; ResourceDialog dialog(this); LongUiTask longTask(tr("Add Files")); int insertNextAt = row; bool first = true; QStringList fileNames = Util::sortedFileList(Util::expandDirectories(urls)); qsizetype i = 0, count = fileNames.size(); for (auto &path : fileNames) { if (MAIN.isSourceClipMyProject(path)) continue; longTask.reportProgress(Util::baseName(path), i++, count); if (MLT.checkFile(path)) { emit showStatusMessage(tr("Failed to open ").append(path)); continue; } Mlt::Producer p; if (path.endsWith(".mlt") || path.endsWith(".xml")) { if (Settings.playerGPU() && MLT.profile().is_explicit()) { Mlt::Profile testProfile; Mlt::Producer producer(testProfile, path.toUtf8().constData()); if (testProfile.width() != MLT.profile().width() || testProfile.height() != MLT.profile().height() || Util::isFpsDifferent(MLT.profile().fps(), testProfile.fps())) { emit showStatusMessage(tr("Failed to open ").append(path)); continue; } } p = Mlt::Producer(MLT.profile(), path.toUtf8().constData()); if (p.is_valid()) { // Convert MLT XML to a virtual clip. p.set(kShotcutVirtualClip, 1); p.set("resource", path.toUtf8().constData()); first = false; } } else { p = Mlt::Producer(MLT.profile(), path.toUtf8().constData()); } if (p.is_valid()) { Mlt::Producer *producer = &p; if (first) { first = false; if (!MLT.producer() || !MLT.producer()->is_valid()) { Mlt::Properties properties; properties.set(kShotcutSkipConvertProperty, 1); MAIN.open(path, &properties, false); if (MLT.producer() && MLT.producer()->is_valid()) { producer = MLT.producer(); first = true; } } } producer = MLT.setupNewProducer(producer); producer->set(kShotcutSkipConvertProperty, 1); if (!MLT.isLiveProducer(producer) || producer->get_int(kShotcutVirtualClip)) { ProxyManager::generateIfNotExists(*producer); if (row == -1) MAIN.undoStack()->push(new Playlist::AppendCommand(m_model, MLT.XML(producer))); else MAIN.undoStack()->push(new Playlist::InsertCommand(m_model, MLT.XML(producer), insertNextAt++)); } else { LongUiTask::cancel(); DurationDialog durationDialog(this); durationDialog.setDuration(MLT.profile().fps() * 5); if (durationDialog.exec() == QDialog::Accepted) { producer->set_in_and_out(0, durationDialog.duration() - 1); if (row == -1) MAIN.undoStack()->push(new Playlist::AppendCommand(m_model, MLT.XML(producer))); else MAIN.undoStack()->push(new Playlist::InsertCommand(m_model, MLT.XML(producer), insertNextAt++)); } } if (first) { first = false; setIndex(0); resetIndex = false; } dialog.add(producer); delete producer; } } if (Settings.showConvertClipDialog() && dialog.producerCount() > 1 && dialog.hasTroubleClips()) { dialog.selectTroubleClips(); dialog.setWindowTitle(tr("Dropped Files")); longTask.cancel(); dialog.exec(); } else if (Settings.showConvertClipDialog() && dialog.producerCount() == 1) { Mlt::Producer producer = dialog.producer(0); QString convertAdvice = Util::getConversionAdvice(&producer); if (!convertAdvice.isEmpty()) { longTask.cancel(); Util::offerSingleFileConversion(convertAdvice, &producer, this); } } if (resetIndex) resetPlaylistIndex(); } void PlaylistDock::onInsertCutActionTriggered() { if (MLT.isClip() || MLT.savedProducer()) { show(); raise(); QMimeData mimeData; mimeData.setData(Mlt::XmlMimeType, MLT.XML( MLT.isClip() ? nullptr : MLT.savedProducer()).toUtf8()); onDropped(&mimeData, m_view->currentIndex().row()); } } void PlaylistDock::onAppendCutActionTriggered() { Mlt::Producer producer(MLT.isClip() ? MLT.producer() : MLT.savedProducer()); if (producer.is_valid() && !MAIN.isSourceClipMyProject()) { if (!MLT.isLiveProducer(&producer)) { ProxyManager::generateIfNotExists(producer); MAIN.undoStack()->push( new Playlist::AppendCommand(m_model, MLT.XML(&producer))); setPlaylistIndex(&producer, m_model.playlist()->count() - 1); emit enableUpdate(true); } else { DurationDialog dialog(this); dialog.setDuration(MLT.profile().fps() * 5); if (dialog.exec() == QDialog::Accepted) { producer.set_in_and_out(0, dialog.duration() - 1); if (producer.get("mlt_service") && !strcmp(producer.get("mlt_service"), "avformat")) producer.set("mlt_service", "avformat-novalidate"); MAIN.undoStack()->push(new Playlist::AppendCommand(m_model, MLT.XML())); setPlaylistIndex(&producer, m_model.playlist()->count() - 1); emit enableUpdate(true); } } } } void PlaylistDock::onUpdateActionTriggered() { QModelIndex index = m_view->currentIndex(); if (!index.isValid() || !m_model.playlist() || MAIN.isSourceClipMyProject()) return; QScopedPointer<Mlt::ClipInfo> info(m_model.playlist()->clip_info(index.row())); Mlt::Producer producer(MLT.isClip() ? MLT.producer() : MLT.savedProducer()); if (!info || !producer.is_valid()) return; if (producer.type() != mlt_service_playlist_type) { show(); raise(); if (!MLT.isLiveProducer(&producer)) { ProxyManager::generateIfNotExists(producer); MAIN.undoStack()->push(new Playlist::UpdateCommand(m_model, MLT.XML(&producer), index.row())); setPlaylistIndex(&producer, index.row()); emit enableUpdate(true); } else { // change the duration DurationDialog dialog(this); dialog.setDuration(info->frame_count); if (dialog.exec() == QDialog::Accepted) { producer.set_in_and_out(0, dialog.duration() - 1); if (producer.get("mlt_service") && !strcmp(producer.get("mlt_service"), "avformat")) producer.set("mlt_service", "avformat-novalidate"); MAIN.undoStack()->push(new Playlist::UpdateCommand(m_model, MLT.XML(), index.row())); setPlaylistIndex(&producer, index.row()); emit enableUpdate(true); } } } else { emit showStatusMessage(tr("You cannot insert a playlist into a playlist!")); emit enableUpdate(false); } } void PlaylistDock::onRemoveActionTriggered() { if (!m_model.playlist() || !m_view->selectionModel()) return; show(); raise(); QList<int> rowsRemoved; int n = m_view->selectionModel()->selectedIndexes().size(); if (n > 1) MAIN.undoStack()->beginMacro(tr("Remove %n playlist items", nullptr, n)); foreach (auto index, m_view->selectionModel()->selectedIndexes()) { int row = index.row(); if (!rowsRemoved.contains(row)) { int adjustment = 0; foreach (int i, rowsRemoved) { if (row > i) --adjustment; } row += adjustment; rowsRemoved << index.row(); if (m_model.playlist()->clip_length(row) > 0) MAIN.undoStack()->push(new Playlist::RemoveCommand(m_model, row)); } } if (n > 1) MAIN.undoStack()->endMacro(); if (rowsRemoved.contains(MLT.producer()->get_int(kPlaylistIndexProperty))) { // Remove the playlist index property on the producer. resetPlaylistIndex(); emit enableUpdate(false); } } void PlaylistDock::onSetFileDateActionTriggered() { QModelIndex index = m_view->currentIndex(); if (!index.isValid() || !m_model.playlist()) return; int count = m_model.playlist()->count(); if (count == 0) return; int i = index.row() >= count ? count - 1 : index.row(); QScopedPointer<Mlt::ClipInfo> info(m_model.playlist()->clip_info(i)); if (info && info->producer && info->producer->is_valid()) { show(); raise(); QString title = info->producer->get("mlt_service"); QString resource = ProxyManager::resource(*info->producer); QFileInfo fileInfo(resource); if (fileInfo.exists()) { title = fileInfo.baseName(); } FileDateDialog dialog(resource, info->producer, this); dialog.setWindowModality(QmlApplication::dialogModality()); dialog.exec(); } } void PlaylistDock::onProducerOpened() { if (MLT.producer() && MLT.producer()->is_valid()) { auto row = MLT.producer()->get_int(kPlaylistIndexProperty) - 1; if (row < 0 && m_model.rowCount() > 0) { resetPlaylistIndex(); emit m_model.dataChanged(m_model.createIndex(0, PlaylistModel::COLUMN_THUMBNAIL), m_model.createIndex(m_model.playlist()->count() - 1, PlaylistModel::COLUMN_THUMBNAIL), QVector<int>() << PlaylistModel::COLUMN_THUMBNAIL); } } emit producerOpened(); } void PlaylistDock::onInChanged() { // Order of in/out timers can be important, resolve the other first if (m_outChangedTimer.isActive()) { m_outChangedTimer.stop(); onOutTimerFired(); } m_inChangedTimer.start(); } void PlaylistDock::onOutChanged() { // Order of in/out timers can be important, resolve the other first if (m_inChangedTimer.isActive()) { m_inChangedTimer.stop(); onInTimerFired(); } m_outChangedTimer.start(); } void PlaylistDock::onOpenActionTriggered() { QModelIndex index = m_view->currentIndex(); if (!index.isValid() || !m_model.playlist()) return; Mlt::ClipInfo *i = m_model.playlist()->clip_info(index.row()); if (i) { Mlt::Producer *p = new Mlt::Producer(i->producer); p->set_in_and_out(i->frame_in, i->frame_out); setPlaylistIndex(p, index.row()); emit clipOpened(p, Settings.playlistAutoplay()); delete i; m_iconsView->resetMultiSelect(); } } void PlaylistDock::viewCustomContextMenuRequested(const QPoint &pos) { QModelIndex index = m_view->currentIndex(); if (index.isValid() && m_model.playlist()) { QMenu menu(this); menu.addAction(Actions["playlistOpenAction"]); menu.addAction(Actions["playlistGoToAction"]); menu.addAction(Actions["playlistRemoveCutAction"]); menu.addAction(Actions["playlistCopyAction"]); menu.addAction(Actions["playlistInsertCutAction"]); menu.addAction(Actions["playlistUpdateAction"]); menu.addAction(Actions["playlistUpdateThumbnailsAction"]); menu.addAction(Actions["playlistUpdateThumbnailsAction"]); menu.addAction(Actions["playlistSetFileDateAction"]); menu.exec(mapToGlobal(pos)); } } void PlaylistDock::viewDoubleClicked(const QModelIndex &index) { if (!m_model.playlist()) return; Mlt::ClipInfo *i = m_model.playlist()->clip_info(index.row()); if (i) { if (qApp->keyboardModifiers() == Qt::ShiftModifier) { emit itemActivated(i->start); } else { Mlt::Producer *p = new Mlt::Producer(i->producer); p->set_in_and_out(i->frame_in, i->frame_out); setPlaylistIndex(p, index.row()); emit clipOpened(p, Settings.playlistAutoplay()); } delete i; m_iconsView->resetMultiSelect(); } } void PlaylistDock::onGotoActionTriggered() { QModelIndex index = m_view->currentIndex(); Mlt::ClipInfo *i = m_model.playlist()->clip_info(index.row()); if (i) { emit itemActivated(i->start); delete i; m_iconsView->resetMultiSelect(); } } void PlaylistDock::onRemoveAllActionTriggered() { resetPlaylistIndex(); MAIN.undoStack()->push(new Playlist::ClearCommand(m_model)); } void PlaylistDock::onPlaylistCreated() { emit enableUpdate(false); updateViewMode(); ui->stackedWidget->setCurrentIndex(1); } void PlaylistDock::onPlaylistLoaded() { onPlaylistCreated(); bool nonEmptyModel = m_model.rowCount() > 0; Actions["playlistRemoveAllAction"]->setEnabled(nonEmptyModel); Actions["playlistSelectAllAction"]->setEnabled(nonEmptyModel); } void PlaylistDock::onPlaylistModified() { if (!m_blockResizeColumnsToContents) { ui->tableView->resizeColumnsToContents(); m_blockResizeColumnsToContents = true; } bool nonEmptyModel = m_model.rowCount() > 0; Actions["playlistRemoveAllAction"]->setEnabled(nonEmptyModel); Actions["playlistSelectAllAction"]->setEnabled(nonEmptyModel); } void PlaylistDock::onPlaylistCleared() { emit enableUpdate(false); m_blockResizeColumnsToContents = false; bool nonEmptyModel = m_model.rowCount() > 0; Actions["playlistRemoveAllAction"]->setEnabled(nonEmptyModel); Actions["playlistSelectAllAction"]->setEnabled(nonEmptyModel); } void PlaylistDock::onDropped(const QMimeData *data, int row) { if (data && data->hasUrls()) { // Use QTimer to workaround stupid drag from Windows Explorer bug const auto &urls = data->urls(); QTimer::singleShot(0, this, [ = ]() { addFiles(row, urls); }); } else if (data && data->hasFormat(Mlt::XmlMimeType)) { if (MLT.producer() && MLT.producer()->is_valid()) { if (MLT.producer()->type() == mlt_service_playlist_type) { emit showStatusMessage(tr("You cannot insert a playlist into a playlist!")); } else if (MAIN.isSourceClipMyProject()) { return; } else if (!MLT.isLiveProducer()) { Mlt::Producer p(MLT.profile(), "xml-string", data->data(Mlt::XmlMimeType).constData()); ProxyManager::generateIfNotExists(p); if (row == -1) { MAIN.undoStack()->push(new Playlist::AppendCommand(m_model, MLT.XML(&p))); setPlaylistIndex(MLT.producer(), m_model.playlist()->count() - 1); } else { MAIN.undoStack()->push(new Playlist::InsertCommand(m_model, MLT.XML(&p), row)); setPlaylistIndex(MLT.producer(), row); } emit enableUpdate(true); } else { LongUiTask::cancel(); DurationDialog dialog(this); dialog.setDuration(MLT.profile().fps() * 5); if (dialog.exec() == QDialog::Accepted) { MLT.producer()->set_in_and_out(0, dialog.duration() - 1); if (MLT.producer()->get("mlt_service") && !strcmp(MLT.producer()->get("mlt_service"), "avformat")) MLT.producer()->set("mlt_service", "avformat-novalidate"); if (row == -1) MAIN.undoStack()->push(new Playlist::AppendCommand(m_model, MLT.XML())); else MAIN.undoStack()->push(new Playlist::InsertCommand(m_model, MLT.XML(), row)); } } } } } void PlaylistDock::onMoveClip(int from, int to) { MAIN.undoStack()->push(new Playlist::MoveCommand(m_model, from, to)); m_view->clearSelection(); resetPlaylistIndex(); } void PlaylistDock::onPlayerDragStarted() { if (isVisible()) ui->stackedWidget->setCurrentIndex(1); } void PlaylistDock::onAddToTimelineActionTriggered() { const QModelIndexList &indexes = m_view->selectionModel()->selectedIndexes(); Mlt::Playlist playlist(MLT.profile()); foreach (auto index, indexes) { if (index.column()) continue; QScopedPointer<Mlt::ClipInfo> info(m_model.playlist()->clip_info(index.row())); if (info && info->producer) { playlist.append(*info->producer, info->frame_in, info->frame_out); } } emit addAllTimeline(&playlist); } void PlaylistDock::onAddToSlideshowActionTriggered() { MLT.pause(); const QModelIndexList &indexes = m_view->selectionModel()->selectedIndexes(); Mlt::Playlist playlist(MLT.profile()); foreach (auto index, indexes) { if (index.column()) continue; QScopedPointer<Mlt::ClipInfo> info(m_model.playlist()->clip_info(index.row())); if (info && info->producer) { playlist.append(*info->producer, info->frame_in, info->frame_out); } } if (playlist.count() <= 0 ) { return; } SlideshowGeneratorDialog dialog(this, playlist); dialog.setWindowModality(QmlApplication::dialogModality()); if (dialog.exec() == QDialog::Accepted ) { LongUiTask longTask(QObject::tr("Generate Slideshow")); Mlt::Playlist *slideshow = longTask.runAsync<Mlt::Playlist *>(tr("Generating"), &SlideshowGeneratorDialog::getSlideshow, &dialog); if (slideshow) { if ( slideshow->count() > 0 ) { emit addAllTimeline(slideshow, /* skipProxy */ true); } delete slideshow; } } } void PlaylistDock::onProducerChanged(Mlt::Producer *producer) { if (!producer || !producer->is_valid()) return; int index = producer->get_int(kPlaylistIndexProperty) - 1; if (index < 0 || !m_model.playlist() || !m_model.playlist()->is_valid() || index >= m_model.playlist()->count()) return; MAIN.undoStack()->push(new Playlist::UpdateCommand(m_model, MLT.XML(producer), index)); emit enableUpdate(false); } void PlaylistDock::updateViewMode() { ui->listView->setModel(nullptr); ui->tableView->setModel(nullptr); m_iconsView->setModel(nullptr); ui->listView->hide(); ui->tableView->hide(); m_iconsView->hide(); if (ui->listView->itemDelegate()) { QAbstractItemDelegate *delegate = ui->listView->itemDelegate(); ui->listView->setItemDelegate(nullptr); delete delegate; } QString mode = Settings.viewMode(); if (mode == kDetailedMode) { m_model.setViewMode(PlaylistModel::Detailed); m_view = ui->tableView; ui->tableView->setModel(&m_model); ui->tableView->setColumnHidden(PlaylistModel::COLUMN_THUMBNAIL, !Settings.playlistShowColumn("thumbnails")); ui->tableView->setColumnHidden(PlaylistModel::COLUMN_RESOURCE, !Settings.playlistShowColumn("clip")); ui->tableView->setColumnHidden(PlaylistModel::COLUMN_IN, !Settings.playlistShowColumn("in")); ui->tableView->setColumnHidden(PlaylistModel::COLUMN_DURATION, !Settings.playlistShowColumn("duration")); ui->tableView->setColumnHidden(PlaylistModel::COLUMN_START, !Settings.playlistShowColumn("start")); ui->tableView->setColumnHidden(PlaylistModel::COLUMN_DATE, !Settings.playlistShowColumn("date")); ui->tableView->resizeColumnsToContents(); ui->tableView->show(); ui->tableView->resizeColumnsToContents(); } else if (mode == kTiledMode) { m_model.setViewMode(PlaylistModel::Tiled); m_view = ui->listView; ui->listView->setDragEnabled(true); ui->listView->setItemDelegate(new TiledItemDelegate(ui->listView)); ui->listView->setModel(&m_model); ui->listView->show(); } else { /* if (mode == kIconsMode) */ m_model.setViewMode(PlaylistModel::Icons); m_view = m_iconsView; m_iconsView->setModel(&m_model); m_iconsView->show(); } m_view->setSelectionModel(m_selectionModel); emit selectionChanged(); m_model.refreshThumbnails(); } void PlaylistDock::resetPlaylistIndex() { if (!m_model.playlist() || !m_model.playlist()->is_valid()) return; if (MLT.producer()) MLT.producer()->set(kPlaylistIndexProperty, nullptr, 0); // Clear the old values for (int j = 0; j < m_model.playlist()->count(); ++j) { Mlt::Producer clip(m_model.playlist()->get_clip(j)); clip.parent().Mlt::Properties::clear(kPlaylistIndexProperty); } emit enableUpdate(false); } void PlaylistDock::emitDataChanged(const QVector<int> &roles) { auto row = MLT.producer()->get_int(kPlaylistIndexProperty) - 1; if (row < 0 || row >= m_model.rowCount()) return; auto index = m_model.createIndex(row, PlaylistModel::COLUMN_RESOURCE); emit m_model.dataChanged(index, index, roles); } void PlaylistDock::setPlaylistIndex(Mlt::Producer *producer, int row) { // Clear the old values for (int j = 0; j < m_model.playlist()->count(); ++j) { Mlt::Producer clip(m_model.playlist()->get_clip(j)); clip.parent().Mlt::Properties::clear(kPlaylistIndexProperty); } producer->set(kPlaylistIndexProperty, row + 1); } #include "playlistdock.moc" void PlaylistDock::onMovedToEnd() { onMoveClip(m_view->currentIndex().row(), model()->rowCount()); } void PlaylistDock::onInTimerFired() { int index = MLT.producer()->get_int(kPlaylistIndexProperty) - 1; if (index < 0 || !m_model.playlist() || !m_model.playlist()->is_valid()) return; QScopedPointer<Mlt::ClipInfo> info(m_model.playlist()->clip_info(index)); if (info && info->producer && info->producer->get_producer() == MLT.producer()->get_producer() && info->frame_in != MLT.producer()->get_in()) { MAIN.undoStack()->push(new Playlist::TrimClipInCommand(m_model, index, MLT.producer()->get_in())); emit enableUpdate(false); } } void PlaylistDock::onOutTimerFired() { int index = MLT.producer()->get_int(kPlaylistIndexProperty) - 1; if (index < 0 || !m_model.playlist() || !m_model.playlist()->is_valid()) return; QScopedPointer<Mlt::ClipInfo> info(m_model.playlist()->clip_info(index)); if (info && info->producer && info->producer->get_producer() == MLT.producer()->get_producer() && info->frame_out != MLT.producer()->get_out()) { MAIN.undoStack()->push(new Playlist::TrimClipOutCommand(m_model, index, MLT.producer()->get_out())); emit enableUpdate(false); } } void PlaylistDock::keyPressEvent(QKeyEvent *event) { QDockWidget::keyPressEvent(event); if (event->key() == Qt::Key_Up || event->key() == Qt::Key_Down) event->accept(); if (!event->isAccepted()) MAIN.keyPressEvent(event); } void PlaylistDock::keyReleaseEvent(QKeyEvent *event) { QDockWidget::keyReleaseEvent(event); if (!event->isAccepted()) MAIN.keyReleaseEvent(event); } void PlaylistDock::onCopyActionTriggered() { QModelIndex index = m_view->currentIndex(); if (!index.isValid() || !m_model.playlist()) return; Mlt::ClipInfo *i = m_model.playlist()->clip_info(index.row()); if (i) { show(); raise(); resetPlaylistIndex(); QString xml = MLT.XML(i->producer); Mlt::Producer *p = new Mlt::Producer(MLT.profile(), "xml-string", xml.toUtf8().constData()); p->set_in_and_out(i->frame_in, i->frame_out); QGuiApplication::clipboard()->setText(MLT.XML(p)); emit clipOpened(p); delete i; m_iconsView->resetMultiSelect(); } } void PlaylistDock::onSelectAllActionTriggered() { show(); raise(); m_view->selectionModel()->clearSelection(); for (int i = 0; i < m_model.rowCount(); i++) { m_view->selectionModel()->select(m_model.index(i, 0), QItemSelectionModel::Select | QItemSelectionModel::Rows); } } void PlaylistDock::onUpdateThumbnailsActionTriggered() { if (!m_model.playlist()) return; m_view->selectionModel()->clearSelection(); for (auto i = 0; i < m_model.rowCount(); i++) { m_model.updateThumbnails(i); } } void PlaylistDock::onProducerModified() { if (!m_model.playlist()) return; emit enableUpdate(true); // The clip name may have changed. emitDataChanged(QVector<int>() << PlaylistModel::FIELD_RESOURCE); } void PlaylistDock::onAddFilesActionTriggered() { QMimeData mimeData; QList<QUrl> urls; QString path = Settings.openPath(); #ifdef Q_OS_MAC path.append("/*"); #endif LOG_DEBUG() << Util::getFileDialogOptions(); QStringList filenames = QFileDialog::getOpenFileNames(this, tr("Open File"), path, tr("All Files (*);;MLT XML (*.mlt)"), nullptr, Util::getFileDialogOptions()); if (filenames.length() > 0) { Settings.setOpenPath(QFileInfo(filenames.first()).path()); foreach (const QString &s, filenames) { urls << s; } mimeData.setUrls(urls); onDropped(&mimeData, m_view->currentIndex().row() + 1); } }
62,896
C++
.cpp
1,438
36.196106
135
0.646243
mltframework/shotcut
10,796
1,118
50
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
13,133
encodedock.cpp
mltframework_shotcut/src/docks/encodedock.cpp
/* * Copyright (c) 2012-2024 Meltytech, LLC * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "encodedock.h" #include "ui_encodedock.h" #include "dialogs/addencodepresetdialog.h" #include "dialogs/multifileexportdialog.h" #include "jobqueue.h" #include "mltcontroller.h" #include "mainwindow.h" #include "settings.h" #include "qmltypes/qmlapplication.h" #include "jobs/encodejob.h" #include "shotcut_mlt_properties.h" #include "util.h" #include "dialogs/listselectiondialog.h" #include "qmltypes/qmlfilter.h" #include "models/markersmodel.h" #include <Logger.h> #include <QtWidgets> #include <QtXml> #include <QtMath> #include <QTimer> #include <QFileInfo> #include <QProcess> #include <QRegularExpression> // formulas to map absolute value ranges to percentages as int #define TO_ABSOLUTE(min, max, rel) qRound(float(min) + float((max) - (min)) * float(rel) / 100.0f) #define TO_RELATIVE(min, max, abs) qRound(100.0f * float((abs) - (min)) / float((max) - (min))) static const int kOpenCaptureFileDelayMs = 1500; static const int kCustomPresetFileNameRole = Qt::UserRole + 1; #ifdef Q_OS_WIN static const QString kNullTarget = "nul"; #else static const QString kNullTarget = "/dev/null"; #endif static double getBufferSize(Mlt::Properties &preset, const char *property); static Mlt::Filter getReframeFilter(Mlt::Service *service) { if (service && service->is_valid()) for (auto i = 0; i < service->filter_count(); ++i) { std::unique_ptr<Mlt::Filter> filter(service->filter(i)); if (filter && filter->is_valid() && !::qstrcmp("reframe", filter->get(kShotcutFilterProperty))) return Mlt::Filter(filter->get_filter()); } return Mlt::Filter(); } EncodeDock::EncodeDock(QWidget *parent) : QDockWidget(parent), ui(new Ui::EncodeDock), m_presets(Mlt::Repository::presets()), m_immediateJob(0), m_profiles(Mlt::Profile::list()), m_isDefaultSettings(true), m_fps(0.0) { LOG_DEBUG() << "begin"; initSpecialCodecLists(); ui->setupUi(this); Util::setColorsToHighlight(ui->resampleWarningLabel); hideResampleWarning(true); // TODO: Reframe does not work--even affine filter if (Settings.playerGPU()) { ui->reframeLabel->hide(); ui->reframeButton->hide(); delete ui->horizontalLayout_22; } ui->stopCaptureButton->hide(); ui->advancedButton->setChecked(Settings.encodeAdvanced()); ui->advancedCheckBox->setChecked(Settings.encodeAdvanced()); on_advancedButton_clicked(ui->advancedButton->isChecked()); #if QT_POINTER_SIZE == 4 // On 32-bit process, limit multi-threading to mitigate running out of memory. ui->parallelCheckbox->setChecked(false); ui->parallelCheckbox->setHidden(true); #else ui->parallelCheckbox->setChecked(Settings.encodeParallelProcessing()); ui->videoCodecThreadsSpinner->setMaximum(QThread::idealThreadCount()); #endif if (QThread::idealThreadCount() < 3) ui->parallelCheckbox->setHidden(true); toggleViewAction()->setIcon(windowIcon()); connect(ui->videoBitrateCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(on_videoBufferDurationChanged())); connect(ui->videoBufferSizeSpinner, SIGNAL(valueChanged(double)), this, SLOT(on_videoBufferDurationChanged())); m_presetsModel.setSourceModel(new QStandardItemModel(this)); m_presetsModel.setFilterCaseSensitivity(Qt::CaseInsensitive); ui->presetsTree->setModel(&m_presetsModel); loadPresets(); // populate the combos Mlt::Consumer c(MLT.profile(), "avformat"); c.set("f", "list"); c.set("acodec", "list"); c.set("vcodec", "list"); c.start(); c.stop(); Mlt::Properties *p = new Mlt::Properties(c.get_data("f")); ui->formatCombo->blockSignals(true); for (int i = 0; i < p->count(); i++) { if (ui->formatCombo->findText(p->get(i)) == -1) ui->formatCombo->addItem(p->get(i)); } delete p; ui->formatCombo->model()->sort(0); ui->formatCombo->insertItem(0, tr("Automatic from extension")); ui->formatCombo->blockSignals(false); p = new Mlt::Properties(c.get_data("acodec")); for (int i = 0; i < p->count(); i++) ui->audioCodecCombo->addItem(p->get(i)); delete p; ui->audioCodecCombo->model()->sort(0); ui->audioCodecCombo->insertItem(0, tr("Default for format")); p = new Mlt::Properties(c.get_data("vcodec")); for (int i = 0; i < p->count(); i++) { if (qstrcmp("nvenc", p->get(i)) // redundant codec names nvenc_... && qstrcmp("wrapped_avframe", p->get(i))) // not usable ui->videoCodecCombo->addItem(p->get(i)); } delete p; ui->videoCodecCombo->model()->sort(0); ui->videoCodecCombo->insertItem(0, tr("Default for format")); ui->hwencodeCheckBox->setChecked(Settings.encodeUseHardware() && !Settings.encodeHardware().isEmpty()); on_resetButton_clicked(); LOG_DEBUG() << "end"; } EncodeDock::~EncodeDock() { if (m_immediateJob) m_immediateJob->stop(); delete ui; delete m_presets; delete m_profiles; } void EncodeDock::loadPresetFromProperties(Mlt::Properties &preset) { int audioQuality = -1; int videoQuality = -1; QStringList other; QChar decimalPoint = MLT.decimalPoint(); QString acodec = QString::fromLatin1(preset.get("acodec")); QString vcodec = QString::fromLatin1(preset.get("vcodec")); if (ui->hwencodeCheckBox->isChecked()) { foreach (const QString &hw, Settings.encodeHardware()) { if ((vcodec == "libx264" && hw.startsWith("h264")) || (vcodec == "libx265" && hw.startsWith("hevc")) || (vcodec == "libvpx-vp9" && hw.startsWith("vp9")) || (vcodec == "libsvtav1" && hw.startsWith("av1"))) { vcodec = hw; break; } } } ui->disableAudioCheckbox->setChecked(preset.get_int("an")); ui->disableVideoCheckbox->setChecked(preset.get_int("vn")); m_extension.clear(); // Default the HEVC crf to 28 per libx265 default. if (vcodec == "libx265" || vcodec.contains("hevc")) { ui->videoQualitySpinner->setValue(45); // Apple needs codec ID hvc1 even though technically that is not what we are writing. QString f = preset.get("f"); if (!preset.property_exists("vtag") && (f == "mp4" || f == "mov")) { other.append("vtag=hvc1"); } } bool qmin_nvenc_amf = preset.get("qmin") && (vcodec.contains("nvenc") || vcodec.endsWith("_amf")); for (int i = 0; i < preset.count(); i++) { QString name(preset.get_name(i)); // Convert numeric strings to the current MLT numeric locale. QString value = QString::fromUtf8(preset.get(i)).trimmed(); if (Util::convertNumericString(value, decimalPoint)) preset.set(name.toUtf8().constData(), value.toUtf8().constData()); if (name == "f") { for (int j = 0; j < ui->formatCombo->count(); j++) if (ui->formatCombo->itemText(j) == value) { ui->formatCombo->blockSignals(true); ui->formatCombo->setCurrentIndex(j); ui->formatCombo->blockSignals(false); break; } } else if (name == "acodec") { for (int j = 0; j < ui->audioCodecCombo->count(); j++) if (ui->audioCodecCombo->itemText(j) == value) ui->audioCodecCombo->setCurrentIndex(j); } else if (name == "vcodec") { for (int j = 0; j < ui->videoCodecCombo->count(); j++) if (ui->videoCodecCombo->itemText(j) == vcodec) ui->videoCodecCombo->setCurrentIndex(j); } else if (name == "channels") setAudioChannels( preset.get_int("channels") ); else if (name == "ar") ui->sampleRateCombo->lineEdit()->setText(value); else if (name == "ab") ui->audioBitrateCombo->lineEdit()->setText(value); else if (name == "vb") { ui->videoRateControlCombo->setCurrentIndex((preset.get_int("vb") > 0) ? RateControlAverage : RateControlQuality); ui->videoBitrateCombo->lineEdit()->setText(value); } else if (name == "g") ui->gopSpinner->setValue(preset.get_int("g")); else if (name == "sc_threshold" && !preset.get_int("sc_threshold")) ui->strictGopCheckBox->setChecked(true); else if (name == "keyint_min" && preset.get_int("keyint_min") == preset.get_int("g")) ui->strictGopCheckBox->setChecked(true); else if (name == "bf") ui->bFramesSpinner->setValue(preset.get_int("bf")); else if (name == "deinterlace") { ui->scanModeCombo->setCurrentIndex(preset.get_int("deinterlace")); on_scanModeCombo_currentIndexChanged(ui->scanModeCombo->currentIndex()); } else if (name == "progressive") { ui->scanModeCombo->setCurrentIndex(preset.get_int("progressive")); on_scanModeCombo_currentIndexChanged(ui->scanModeCombo->currentIndex()); } else if (name == "top_field_first") { ui->fieldOrderCombo->setCurrentIndex(preset.get_int("top_field_first")); } else if (name == "width") { ui->widthSpinner->setValue(preset.get_int("width")); } else if (name == "height") { ui->heightSpinner->setValue(preset.get_int("height")); } else if (name == "aspect") { double dar = preset.get_double("aspect"); switch (int(dar * 100)) { case 133: ui->aspectNumSpinner->setValue(4); ui->aspectDenSpinner->setValue(3); break; case 177: ui->aspectNumSpinner->setValue(16); ui->aspectDenSpinner->setValue(9); break; case 56: ui->aspectNumSpinner->setValue(9); ui->aspectDenSpinner->setValue(16); break; default: { const auto p = QPoint(preset.get_int("width"), preset.get_int("height")); auto gcd = Util::greatestCommonDivisor(p.x(), p.y()); ui->aspectNumSpinner->setValue(p.x() / gcd); ui->aspectDenSpinner->setValue(p.y() / gcd); break; } } } else if (name == "r") { ui->fpsSpinner->setValue(preset.get_double("r")); } else if (name == "frame_rate_num") { if (preset.get_int("frame_rate_den")) ui->fpsSpinner->setValue(preset.get_double("frame_rate_num") / preset.get_double("frame_rate_den")); } else if (name == "pix_fmt") { // Handle 10 bit encoding with hardware encoder and GPU Effects if (value.contains("p10le")) { if (Settings.playerGPU()) { if (value == "yuva444p10le") { other.append("mlt_image_format=rgba"); } else { other.append("mlt_image_format=yuv444p10"); } } else if (!other.contains("mlt_image_format=rgb")) { other.append("mlt_image_format=rgb"); } // Hardware encoder if (vcodec.endsWith("_nvenc") || vcodec.endsWith("_qsv") || vcodec.endsWith("_vaapi") || vcodec.endsWith("_videotoolbox")) { value = "p010le"; } } if (!value.isEmpty()) other.append(QStringLiteral("%1=%2").arg(name, value)); } else if (name == "pass") ui->dualPassCheckbox->setChecked(true); else if (name == "v2pass") ui->dualPassCheckbox->setChecked(preset.get_int("v2pass")); else if (name == "aq") { ui->audioRateControlCombo->setCurrentIndex(RateControlQuality); audioQuality = preset.get_int("aq"); } else if (name == "compression_level") { ui->audioRateControlCombo->setCurrentIndex(RateControlQuality); audioQuality = preset.get_int("compression_level"); } else if (name == "vbr") { // libopus rate mode if (value == "off") ui->audioRateControlCombo->setCurrentIndex(RateControlConstant); else if (value == "constrained") ui->audioRateControlCombo->setCurrentIndex(RateControlAverage); else ui->audioRateControlCombo->setCurrentIndex(RateControlQuality); } else if (name == "abr") { if (preset.get_int("abr")) ui->audioRateControlCombo->setCurrentIndex(RateControlAverage); } else if (name == "vq" || name == "vqp" || name == "vglobal_quality" || name == "qscale" || qmin_nvenc_amf || name == "cq" || name == "crf") { // On macOS videotoolbox, constant quality is only on Apple Silicon #if defined(Q_OS_MAC) && !defined(Q_PROCESSOR_ARM) ui->videoRateControlCombo->setCurrentIndex(preset.get("vbufsize") ? RateControlConstrained : vcodec.endsWith("_videotoolbox") ? RateControlAverage : RateControlQuality); #else ui->videoRateControlCombo->setCurrentIndex(preset.get("vbufsize") ? RateControlConstrained : RateControlQuality); #endif videoQuality = preset.get_int(name.toUtf8().constData()); } else if (name == "bufsize" || name == "vbufsize") { // traditionally "bufsize" means video only if (preset.get("vq") || preset.get("qscale") || preset.get("crf") || qmin_nvenc_amf) ui->videoRateControlCombo->setCurrentIndex(RateControlConstrained); else ui->videoRateControlCombo->setCurrentIndex(RateControlConstant); ui->videoBufferSizeSpinner->setValue(getBufferSize(preset, name.toLatin1().constData())); } else if (name == "vmaxrate") { ui->videoBitrateCombo->lineEdit()->setText(value); } else if (name == "threads") { // TODO: should we save the thread count and restore it if preset is not 1? if (preset.get_int("threads") == 1) ui->videoCodecThreadsSpinner->setValue(1); } else if (name == "meta.preset.extension") { m_extension = value; } else if (name == "deinterlace_method" || name == "deinterlacer") { name = preset.get("deinterlacer") ? preset.get("deinterlacer") : preset.get("deinterlace_method"); if (name == "onefield") ui->deinterlacerCombo->setCurrentIndex(0); else if (name == "linearblend") ui->deinterlacerCombo->setCurrentIndex(1); else if (name == "yadif-nospatial") ui->deinterlacerCombo->setCurrentIndex(2); else if (name == "yadif") ui->deinterlacerCombo->setCurrentIndex(3); else if (name == "bwdif") ui->deinterlacerCombo->setCurrentIndex(4); } else if (name == "rescale") { if (value == "nearest" || value == "neighbor") ui->interpolationCombo->setCurrentIndex(0); else if (value == "bilinear") ui->interpolationCombo->setCurrentIndex(1); else if (value == "bicubic") ui->interpolationCombo->setCurrentIndex(2); else if (value == "hyper" || value == "lanczos") ui->interpolationCombo->setCurrentIndex(3); } else if (name == "color_range" && (value == "pc" || value == "jpeg")) { ui->rangeComboBox->setCurrentIndex(1); } else if (name != "an" && name != "vn" && name != "threads" && !(name == "frame_rate_den" && preset.property_exists("frame_rate_num")) && !name.startsWith('_') && !name.startsWith("qp_") && !name.startsWith("meta.preset.")) { other.append(QStringLiteral("%1=%2").arg(name, value)); } } filterCodecParams(vcodec, other); ui->advancedTextEdit->setPlainText(other.join("\n")); // normalize the quality settings // quality depends on codec if (ui->audioRateControlCombo->currentIndex() == RateControlQuality && audioQuality > -1) { const QString &acodec = ui->audioCodecCombo->currentText(); if (acodec == "libmp3lame") // 0 (best) - 9 (worst) ui->audioQualitySpinner->setValue(TO_RELATIVE(9, 0, audioQuality)); if (acodec == "libvorbis" || acodec == "vorbis" || acodec == "libopus") // 0 (worst) - 10 (best) ui->audioQualitySpinner->setValue(TO_RELATIVE(0, 10, audioQuality)); else // aac: 0 (worst) - 500 (best) ui->audioQualitySpinner->setValue(TO_RELATIVE(0, 500, audioQuality)); } if (acodec == "vorbis" || acodec == "libvorbis") ui->audioRateControlCombo->setCurrentIndex(RateControlAverage); if ((ui->videoRateControlCombo->currentIndex() == RateControlQuality || ui->videoRateControlCombo->currentIndex() == RateControlConstrained) && videoQuality > -1) { //val = min + (max - min) * paramval; if (vcodec.startsWith("libx264") || vcodec == "libx265" || vcodec.contains("nvenc") || vcodec.endsWith("_amf") || vcodec.endsWith("_vaapi")) { // 0 (best, 100%) - 51 (worst) const auto qmax = QString::fromLatin1(preset.get("vcodec")) == "libsvtav1" ? 63 : 51; ui->videoQualitySpinner->setValue(TO_RELATIVE(qmax, 0, videoQuality)); } else if (vcodec.endsWith("_videotoolbox")) { #if defined(Q_OS_MAC) && defined(Q_PROCESSOR_ARM) ui->videoQualitySpinner->setValue(ui->hwencodeCheckBox->isChecked() ? videoQuality * 55.0 / 23.0 : videoQuality); #else ui->videoQualitySpinner->setValue(videoQuality); #endif } else if (vcodec.endsWith("_qsv")) { // 1 (best, 100%) - 51 (worst) ui->videoQualitySpinner->setValue(TO_RELATIVE(51, 1, videoQuality)); } else if (vcodec.startsWith("libvpx") || vcodec.startsWith("libaom-") || vcodec == "libsvtav1") { // 0 (best, 100%) - 63 (worst) ui->videoQualitySpinner->setValue(TO_RELATIVE(63, 0, videoQuality)); } else if (vcodec.startsWith("libwebp")) { // 100 (best) - 0 (worst) ui->videoQualitySpinner->setValue(TO_RELATIVE(0, 100, videoQuality)); } else { // 1 (best, NOT 100%) - 31 (worst) ui->videoQualitySpinner->setValue(TO_RELATIVE(31, 1, videoQuality)); } } vcodec = QString::fromLatin1(preset.get("vcodec")); auto resetBframes = !vcodec.contains("nvenc") && !vcodec.endsWith("_amf") && !vcodec.endsWith("_qsv"); onVideoCodecComboChanged(ui->videoCodecCombo->currentIndex(), true, resetBframes); on_audioRateControlCombo_activated(ui->audioRateControlCombo->currentIndex()); on_videoRateControlCombo_activated(ui->videoRateControlCombo->currentIndex()); if (m_extension.isEmpty()) { defaultFormatExtension(); } } bool EncodeDock::isExportInProgress() const { return !m_immediateJob.isNull(); } void EncodeDock::onProducerOpened() { int index = 0; ui->fromCombo->blockSignals(true); ui->fromCombo->clear(); if (MAIN.isMultitrackValid()) ui->fromCombo->addItem(tr("Timeline"), "timeline"); if (MAIN.playlist() && MAIN.playlist()->count() > 0) { ui->fromCombo->addItem(tr("Playlist"), "playlist"); ui->fromCombo->addItem(tr("Each Playlist Item"), "batch"); } if (MLT.isClip() && qstrcmp("_hide", MLT.producer()->get("resource"))) { ui->fromCombo->addItem(tr("Source"), "clip"); if (MLT.producer()->get_int(kBackgroundCaptureProperty) || MLT.producer()->get_int(kExportFromProperty)) index = ui->fromCombo->count() - 1; } else if (MLT.savedProducer() && MLT.savedProducer()->is_valid() && qstrcmp("_hide", MLT.savedProducer()->get("resource"))) { ui->fromCombo->addItem(tr("Source"), "clip"); } if (MAIN.isMultitrackValid()) { MarkersModel markersModel; markersModel.load(MAIN.multitrack()); const auto markerStr = tr("Marker"); auto ranges = markersModel.ranges(); for (auto i = ranges.constBegin(); i != ranges.constEnd(); ++i) { QString comboText; if (i.value().startsWith(markerStr)) { comboText = i.value(); } else { comboText = QStringLiteral("%1: %2").arg(tr("Marker"), i.value()); } comboText = ui->fromCombo->fontMetrics().elidedText(comboText, Qt::ElideRight, 400); ui->fromCombo->addItem(comboText, QStringLiteral("marker:%1").arg(i.key())); } } ui->fromCombo->blockSignals(false); if (!m_immediateJob) { ui->fromCombo->setCurrentIndex(index); on_fromCombo_currentIndexChanged(index); } ui->otherTipLabel->setText(tr("You must enter numeric values using '%1' as the decimal point.").arg( MLT.decimalPoint())); } void EncodeDock::loadPresets() { QStandardItemModel *sourceModel = (QStandardItemModel *) m_presetsModel.sourceModel(); sourceModel->clear(); QStandardItem *grandParentItem = new QStandardItem(tr("Custom")); QStandardItem *parentItem = grandParentItem; sourceModel->invisibleRootItem()->appendRow(parentItem); QDir dir(Settings.appDataLocation()); if (dir.cd("presets") && dir.cd("encode")) { QStringList entries = dir.entryList(QDir::Files | QDir::NoDotAndDotDot | QDir::Readable); foreach (QString name, entries) { // Create a category node if the name includes a ). QStringList nameParts = name.split(')'); if (nameParts.count() > 1 && !nameParts[1].isEmpty() && !name.contains('(')) { // See if there is already a category node with this name. int row; for (row = 0; row < grandParentItem->rowCount(); row++) { if (grandParentItem->child(row)->text() == nameParts[0]) { // There is already a category node; use it. parentItem = grandParentItem->child(row); break; } } if (row == grandParentItem->rowCount()) { // There is no category node yet; create it. parentItem = new QStandardItem(nameParts[0]); parentItem->setData(QString()); grandParentItem->appendRow(parentItem); } // Remove the category from the name. nameParts.removeFirst(); } else { parentItem = grandParentItem; } QStandardItem *item = new QStandardItem(nameParts.join(')')); item->setData(name); parentItem->appendRow(item); } } grandParentItem = new QStandardItem(tr("Stock")); parentItem = grandParentItem; sourceModel->invisibleRootItem()->appendRow(parentItem); parentItem->appendRow(new QStandardItem(tr("Default"))); QString prefix("consumer/avformat/"); if (m_presets && m_presets->is_valid()) { for (int j = 0; j < m_presets->count(); j++) { QString name(m_presets->get_name(j)); if (name.startsWith(prefix)) { Mlt::Properties preset((mlt_properties) m_presets->get_data(name.toLatin1().constData())); if (preset.get_int("meta.preset.hidden")) continue; if (preset.get("meta.preset.name")) name = QString::fromUtf8(preset.get("meta.preset.name")); else { // use relative path and filename name.remove(0, prefix.length()); QStringList textParts = name.split('/'); if (textParts.count() > 1) { // if the path is a profile name, then change it to "preset (profile)" QString profile = textParts.at(0); textParts.removeFirst(); if (m_profiles->get_data(profile.toLatin1().constData())) name = QStringLiteral("%1 (%2)").arg(textParts.join('/'), profile); } } // Create a category node if the name includes a slash. QStringList nameParts = name.split('/'); if (nameParts.count() > 1) { // See if there is already a category node with this name. int row; for (row = 0; row < grandParentItem->rowCount(); row++) { if (grandParentItem->child(row)->text() == nameParts[0]) { // There is already a category node; use it. parentItem = grandParentItem->child(row); break; } } if (row == grandParentItem->rowCount()) { // There is no category node yet; create it. parentItem = new QStandardItem(nameParts[0]); grandParentItem->appendRow(parentItem); } // Remove the category from the name. nameParts.removeFirst(); } else { parentItem = grandParentItem; } QStandardItem *item = new QStandardItem(nameParts.join('/')); item->setData(QString(m_presets->get_name(j))); if (preset.get("meta.preset.note")) item->setToolTip(QStringLiteral("<p>%1</p>").arg(QString::fromUtf8( preset.get("meta.preset.note")))); parentItem->appendRow(item); } } } m_presetsModel.sort(0); ui->presetsTree->expandAll(); } template<typename T> static void setIfNotSet(Mlt::Properties *properties, const char *name, T value) { if (!properties->get(name)) properties->set(name, value); } Mlt::Properties *EncodeDock::collectProperties(int realtime, bool includeProfile) { Mlt::Properties *p = new Mlt::Properties; if (p && p->is_valid()) { foreach (QString line, ui->advancedTextEdit->toPlainText().split("\n")) p->parse(line.toUtf8().constData()); if (realtime) setIfNotSet(p, "real_time", realtime); if (ui->formatCombo->currentIndex() != 0) setIfNotSet(p, "f", ui->formatCombo->currentText().toLatin1().constData()); if (ui->disableAudioCheckbox->isChecked()) { setIfNotSet(p, "an", 1); setIfNotSet(p, "audio_off", 1); } else { const QString &acodec = ui->audioCodecCombo->currentText(); if (ui->audioCodecCombo->currentIndex() > 0) setIfNotSet(p, "acodec", ui->audioCodecCombo->currentText().toLatin1().constData()); if (ui->audioChannelsCombo->currentIndex() == AudioChannels1) { setIfNotSet(p, "channels", 1); setIfNotSet(p, "channel_layout", "auto"); } else if (ui->audioChannelsCombo->currentIndex() == AudioChannels2) { setIfNotSet(p, "channels", 2); setIfNotSet(p, "channel_layout", "auto"); } else if (ui->audioChannelsCombo->currentIndex() == AudioChannels4) { setIfNotSet(p, "channels", 4); setIfNotSet(p, "channel_layout", "quad"); } else { setIfNotSet(p, "channels", 6); setIfNotSet(p, "channel_layout", "auto"); } setIfNotSet(p, "ar", ui->sampleRateCombo->currentText().toLatin1().constData()); if (ui->audioRateControlCombo->currentIndex() == RateControlAverage || ui->audioRateControlCombo->currentIndex() == RateControlConstant) { setIfNotSet(p, "ab", ui->audioBitrateCombo->currentText().toLatin1().constData()); if (RateControlConstant == ui->audioRateControlCombo->currentIndex()) setIfNotSet(p, "vbr", "off"); else setIfNotSet(p, "vbr", "constrained"); if (acodec == "libmp3lame" && ui->audioRateControlCombo->currentIndex() == RateControlAverage) setIfNotSet(p, "abr", "1"); } else if (acodec == "libopus") { setIfNotSet(p, "vbr", "on"); setIfNotSet(p, "compression_level", TO_ABSOLUTE(0, 10, ui->audioQualitySpinner->value())); } else { setIfNotSet(p, "vbr", "on"); double aq = ui->audioQualitySpinner->value(); if (acodec == "libmp3lame") aq = TO_ABSOLUTE(9, 0, aq); else if (acodec == "aac") aq = 0.1 + 1.9 * aq / 100.0; else if (acodec == "libvorbis" || acodec == "vorbis") aq = TO_ABSOLUTE(0, 10, aq); else aq = TO_ABSOLUTE(0, 500, aq); setIfNotSet(p, "aq", aq); } } if (ui->disableVideoCheckbox->isChecked()) { setIfNotSet(p, "vn", 1); setIfNotSet(p, "video_off", 1); } else { const QString &vcodec = ui->videoCodecCombo->currentText(); const QString &vbitrate = ui->videoBitrateCombo->currentText(); double cvbr = ::atof(vbitrate.toLatin1().constData()); int vq = ui->videoQualitySpinner->value(); if (vbitrate.endsWith('M')) cvbr *= 1000000.0; else if (vbitrate.endsWith('k')) cvbr *= 1000.0; cvbr *= double(vq) / 100.0; if (ui->videoCodecCombo->currentIndex() > 0) setIfNotSet(p, "vcodec", vcodec.toLatin1().constData()); if (vcodec == "libx265") { // Most x265 parameters must be supplied through x265-params. QString x265params = QString::fromUtf8(p->get("x265-params")); switch (ui->videoRateControlCombo->currentIndex()) { case RateControlAverage: setIfNotSet(p, "vb", ui->videoBitrateCombo->currentText().toLatin1().constData()); break; case RateControlConstant: { QString b = ui->videoBitrateCombo->currentText(); // x265 does not expect bitrate suffixes and requires Kb/s b.replace('k', "").replace('M', "000"); x265params = QStringLiteral("bitrate=%1:vbv-bufsize=%2:vbv-maxrate=%3:%4") .arg(b).arg(int(ui->videoBufferSizeSpinner->value() * 8)).arg(b).arg(x265params); setIfNotSet(p, "vb", b.toLatin1().constData()); setIfNotSet(p, "vbufsize", int(ui->videoBufferSizeSpinner->value() * 8 * 1024)); break; } case RateControlQuality: { x265params = QStringLiteral("crf=%1:%2").arg(TO_ABSOLUTE(51, 0, vq)).arg(x265params); // Also set crf property so that custom presets can be interpreted properly. setIfNotSet(p, "crf", TO_ABSOLUTE(51, 0, vq)); break; } case RateControlConstrained: { QString b = ui->videoBitrateCombo->currentText(); // x265 does not expect bitrate suffixes and requires Kb/s b.replace('k', "").replace('M', "000"); x265params = QStringLiteral("crf=%1:vbv-bufsize=%2:vbv-maxrate=%3:%4") .arg(TO_ABSOLUTE(51, 0, vq)).arg(int(ui->videoBufferSizeSpinner->value() * 8)).arg(b).arg( x265params); // Also set properties so that custom presets can be interpreted properly. setIfNotSet(p, "crf", TO_ABSOLUTE(51, 0, vq)); setIfNotSet(p, "vbufsize", int(ui->videoBufferSizeSpinner->value() * 8 * 1024)); setIfNotSet(p, "vmaxrate", ui->videoBitrateCombo->currentText().toLatin1().constData()); break; } } x265params = QStringLiteral("keyint=%1:bframes=%2:%3").arg(ui->gopSpinner->value()) .arg(ui->bFramesSpinner->value()).arg(x265params); if (ui->strictGopCheckBox->isChecked()) { x265params = QStringLiteral("scenecut=0:%1").arg(x265params); setIfNotSet(p, "sc_threshold", 0); } if (ui->scanModeCombo->currentIndex() == 0 && !x265params.contains("interlace=")) { x265params = QStringLiteral("interlace=%1:%2").arg( ui->fieldOrderCombo->currentIndex() ? "tff" : "bff", x265params); } // Also set some properties so that custom presets can be interpreted properly. setIfNotSet(p, "g", ui->gopSpinner->value()); setIfNotSet(p, "bf", ui->bFramesSpinner->value()); p->set("x265-params", x265params.toUtf8().constData()); } else if (vcodec == "libsvtav1") { QString bitrate_text = ui->videoBitrateCombo->currentText(); int bitrate_kbps = qMax(QString(bitrate_text).replace('k', "").replace('M', "000").toInt(), 1); int buffer_bits = qRound(ui->videoBufferSizeSpinner->value() * 1024.0 * 8.0); int buffer_ms = qRound(float(buffer_bits) / float(bitrate_kbps)); QStringList encParams; switch (ui->videoRateControlCombo->currentIndex()) { case RateControlAverage: { setIfNotSet(p, "vb", bitrate_text.toLatin1().constData()); break; } case RateControlConstant: { encParams << QStringLiteral("rc=2"); encParams << QStringLiteral("tbr=%1").arg(bitrate_text); encParams << QStringLiteral("buf-sz=%1").arg(buffer_ms); setIfNotSet(p, "vb", bitrate_text.toLatin1().constData()); setIfNotSet(p, "vbufsize", buffer_bits); break; } case RateControlQuality: { setIfNotSet(p, "crf", TO_ABSOLUTE(63, 0, vq)); break; } case RateControlConstrained: { setIfNotSet(p, "crf", TO_ABSOLUTE(63, 0, vq)); setIfNotSet(p, "vmaxrate", bitrate_text.toLatin1().constData()); setIfNotSet(p, "vbufsize", buffer_bits); // For UI only; not used by svtav1-params break; } } setIfNotSet(p, "g", ui->gopSpinner->value()); if (ui->strictGopCheckBox->isChecked()) { encParams << QStringLiteral("scd=0"); encParams << QStringLiteral("enable-dg=0"); setIfNotSet(p, "sc_threshold", 0); } else { encParams << QStringLiteral("scd=1"); encParams << QStringLiteral("enable-dg=1"); setIfNotSet(p, "sc_threshold", 1); } // SVT-AV1 does not offer direct control of the // B-frame count, but we can control whether // delta frames are bi-directional or not. if (ui->bFramesSpinner->value() == 0) encParams << QStringLiteral("pred-struct=1"); else encParams << QStringLiteral("pred-struct=2"); setIfNotSet(p, "bf", ui->bFramesSpinner->value()); encParams << QStringLiteral("lp=%1").arg(ui->videoCodecThreadsSpinner->value()); // AV1 spec does not support interlacing. setIfNotSet(p, "progressive", 1); QString origParams = QString::fromUtf8(p->get("svtav1-params")); if (!origParams.isEmpty()) encParams << origParams; p->set("svtav1-params", encParams.join(':').toUtf8().constData()); } else if (vcodec.contains("nvenc")) { switch (ui->videoRateControlCombo->currentIndex()) { case RateControlAverage: setIfNotSet(p, "vb", ui->videoBitrateCombo->currentText().toLatin1().constData()); break; case RateControlConstant: { const QString &b = ui->videoBitrateCombo->currentText(); setIfNotSet(p, "cbr", 1); setIfNotSet(p, "vb", b.toLatin1().constData()); setIfNotSet(p, "vminrate", b.toLatin1().constData()); setIfNotSet(p, "vmaxrate", b.toLatin1().constData()); setIfNotSet(p, "vbufsize", int(ui->videoBufferSizeSpinner->value() * 8 * 1024)); break; } case RateControlQuality: { setIfNotSet(p, "rc", "vbr"); setIfNotSet(p, "cq", TO_ABSOLUTE(51, 0, vq)); break; } case RateControlConstrained: { const QString &b = ui->videoBitrateCombo->currentText(); setIfNotSet(p, "qmin", TO_ABSOLUTE(51, 0, vq)); setIfNotSet(p, "vb", qRound(cvbr)); setIfNotSet(p, "vmaxrate", b.toLatin1().constData()); setIfNotSet(p, "vbufsize", int(ui->videoBufferSizeSpinner->value() * 8 * 1024)); break; } } if (ui->dualPassCheckbox->isChecked()) setIfNotSet(p, "v2pass", 1); if (ui->strictGopCheckBox->isChecked()) { setIfNotSet(p, "sc_threshold", 0); setIfNotSet(p, "strict_gop", 1); } // Also set some properties so that custom presets can be interpreted properly. setIfNotSet(p, "g", ui->gopSpinner->value()); setIfNotSet(p, "bf", ui->bFramesSpinner->value()); } else if (vcodec.endsWith("_amf")) { switch (ui->videoRateControlCombo->currentIndex()) { case RateControlAverage: setIfNotSet(p, "vb", ui->videoBitrateCombo->currentText().toLatin1().constData()); break; case RateControlConstant: { const QString &b = ui->videoBitrateCombo->currentText(); setIfNotSet(p, "rc", "cbr"); setIfNotSet(p, "vb", b.toLatin1().constData()); setIfNotSet(p, "vminrate", b.toLatin1().constData()); setIfNotSet(p, "vmaxrate", b.toLatin1().constData()); setIfNotSet(p, "vbufsize", int(ui->videoBufferSizeSpinner->value() * 8 * 1024)); break; } case RateControlQuality: { setIfNotSet(p, "rc", "cqp"); setIfNotSet(p, "qp_i", TO_ABSOLUTE(51, 0, vq)); setIfNotSet(p, "qp_p", TO_ABSOLUTE(51, 0, vq)); setIfNotSet(p, "qp_b", TO_ABSOLUTE(51, 0, vq)); setIfNotSet(p, "vq", TO_ABSOLUTE(51, 0, vq)); break; } case RateControlConstrained: { setIfNotSet(p, "rc", "vbr_peak"); setIfNotSet(p, "qmin", TO_ABSOLUTE(51, 0, vq)); setIfNotSet(p, "vb", qRound(cvbr)); setIfNotSet(p, "vmaxrate", vbitrate.toLatin1().constData()); setIfNotSet(p, "vbufsize", int(ui->videoBufferSizeSpinner->value() * 8 * 1024)); break; } } if (ui->dualPassCheckbox->isChecked()) setIfNotSet(p, "v2pass", 1); if (ui->strictGopCheckBox->isChecked()) { setIfNotSet(p, "sc_threshold", 0); setIfNotSet(p, "strict_gop", 1); } // Also set some properties so that custom presets can be interpreted properly. setIfNotSet(p, "g", ui->gopSpinner->value()); setIfNotSet(p, "bf", ui->bFramesSpinner->value()); } else { switch (ui->videoRateControlCombo->currentIndex()) { case RateControlAverage: setIfNotSet(p, "vb", ui->videoBitrateCombo->currentText().toLatin1().constData()); break; case RateControlConstant: { const QString &b = ui->videoBitrateCombo->currentText(); setIfNotSet(p, "vb", b.toLatin1().constData()); setIfNotSet(p, "vminrate", b.toLatin1().constData()); setIfNotSet(p, "vmaxrate", b.toLatin1().constData()); setIfNotSet(p, "vbufsize", int(ui->videoBufferSizeSpinner->value() * 8 * 1024)); break; } case RateControlQuality: { if (vcodec.startsWith("libx264")) { setIfNotSet(p, "crf", TO_ABSOLUTE(51, 0, vq)); } else if (vcodec.startsWith("libvpx") || vcodec.startsWith("libaom-")) { setIfNotSet(p, "crf", TO_ABSOLUTE(63, 0, vq)); setIfNotSet(p, "vb", 0); // VP9 needs this to prevent constrained quality mode. } else if (vcodec.endsWith("_vaapi")) { setIfNotSet(p, "vglobal_quality", TO_ABSOLUTE(51, 0, vq)); setIfNotSet(p, "vq", TO_ABSOLUTE(51, 0, vq)); } else if (vcodec.endsWith("_qsv")) { setIfNotSet(p, "qscale", TO_ABSOLUTE(51, 1, vq)); } else if (vcodec.endsWith("_videotoolbox")) { setIfNotSet(p, "qscale", vq); } else if (vcodec.startsWith("libwebp")) { setIfNotSet(p, "qscale", TO_ABSOLUTE(0, 100, vq)); } else { setIfNotSet(p, "qscale", TO_ABSOLUTE(31, 1, vq)); } break; } case RateControlConstrained: { if (vcodec.startsWith("libx264")) { setIfNotSet(p, "crf", TO_ABSOLUTE(51, 0, vq)); } else if (vcodec.startsWith("libvpx") || vcodec.startsWith("libaom-")) { setIfNotSet(p, "crf", TO_ABSOLUTE(63, 0, vq)); } else if (vcodec.endsWith("_qsv")) { setIfNotSet(p, "vb", qRound(cvbr)); } else if (vcodec.endsWith("_videotoolbox")) { setIfNotSet(p, "vb", qRound(cvbr)); setIfNotSet(p, "vq", vq); } else if (vcodec.endsWith("_vaapi")) { setIfNotSet(p, "vb", vbitrate.toLatin1().constData()); setIfNotSet(p, "vglobal_quality", TO_ABSOLUTE(51, 0, vq)); setIfNotSet(p, "vq", TO_ABSOLUTE(51, 0, vq)); } else if (vcodec.startsWith("libwebp")) { setIfNotSet(p, "qscale", TO_ABSOLUTE(0, 100, vq)); } else { setIfNotSet(p, "qscale", TO_ABSOLUTE(31, 1, vq)); } setIfNotSet(p, "vmaxrate", vbitrate.toLatin1().constData()); setIfNotSet(p, "vbufsize", int(ui->videoBufferSizeSpinner->value() * 8 * 1024)); break; } } setIfNotSet(p, "g", ui->gopSpinner->value()); setIfNotSet(p, "bf", ui->bFramesSpinner->value()); if (ui->strictGopCheckBox->isChecked()) { if (vcodec.startsWith("libvpx") || vcodec.startsWith("libaom-")) setIfNotSet(p, "keyint_min", ui->gopSpinner->value()); else setIfNotSet(p, "sc_threshold", 0); } if (vcodec.endsWith("_videotoolbox")) { setIfNotSet(p, "pix_fmt", "nv12"); } else if (vcodec.endsWith("_vaapi")) { setIfNotSet(p, "vprofile", "main"); } } if (includeProfile || ui->widthSpinner->value() != MLT.profile().width()) { if (ui->widthSpinner->isEnabled()) setIfNotSet(p, "width", ui->widthSpinner->value()); } if (includeProfile || ui->heightSpinner->value() != MLT.profile().height()) { if (ui->heightSpinner->isEnabled()) setIfNotSet(p, "height", ui->heightSpinner->value()); } if (ui->previewScaleCheckBox->isChecked() && !p->get("scale") && Settings.playerPreviewScale() > 0) { p->set("scale", double(Settings.playerPreviewScale()) / MLT.profile().height()); } if (includeProfile || ui->aspectNumSpinner->value() != MLT.profile().display_aspect_num() || ui->aspectDenSpinner->value() != MLT.profile().display_aspect_den() || ui->widthSpinner->value() != MLT.profile().width() || ui->heightSpinner->value() != MLT.profile().height()) { if (ui->aspectNumSpinner->isEnabled()) setIfNotSet(p, "aspect", double(ui->aspectNumSpinner->value()) / double( ui->aspectDenSpinner->value())); } if (includeProfile || ui->scanModeCombo->currentIndex() != MLT.profile().progressive()) { setIfNotSet(p, "progressive", ui->scanModeCombo->currentIndex()); } setIfNotSet(p, "top_field_first", ui->fieldOrderCombo->currentIndex()); switch (ui->deinterlacerCombo->currentIndex()) { case 0: setIfNotSet(p, "deinterlacer", "onefield"); break; case 1: setIfNotSet(p, "deinterlacer", "linearblend"); break; case 2: setIfNotSet(p, "deinterlacer", "yadif-nospatial"); break; case 3: setIfNotSet(p, "deinterlacer", "yadif"); break; default: setIfNotSet(p, "deinterlacer", "bwdif"); break; } switch (ui->interpolationCombo->currentIndex()) { case 0: setIfNotSet(p, "rescale", "nearest"); break; case 1: setIfNotSet(p, "rescale", "bilinear"); break; case 2: setIfNotSet(p, "rescale", "bicubic"); break; default: setIfNotSet(p, "rescale", "hyper"); break; } // If the frame rate is not specified in Other. if (!p->get("r") && !(p->get("frame_rate_num") && p->get("frame_rate_den")) // Only if the frame rate spinner does not match the profile. && (includeProfile || qRound(ui->fpsSpinner->value() * 1000000.0) != qRound(MLT.profile().fps() * 1000000.0))) { int numerator, denominator; Util::normalizeFrameRate(ui->fpsSpinner->value(), numerator, denominator); p->set("frame_rate_num", numerator); p->set("frame_rate_den", denominator); } if (ui->rangeComboBox->currentIndex()) { setIfNotSet(p, "color_range", "pc"); } if (ui->formatCombo->currentText() == "image2") setIfNotSet(p, "threads", 1); else if (ui->videoCodecThreadsSpinner->value() == 0 && !ui->videoCodecCombo->currentText().startsWith("libx264") && ui->videoCodecCombo->currentText() != "libx265" && ui->videoCodecCombo->currentText() != "libsvtav1") setIfNotSet(p, "threads", ui->videoCodecThreadsSpinner->maximum() - 1); else setIfNotSet(p, "threads", ui->videoCodecThreadsSpinner->value()); if (ui->videoRateControlCombo->currentIndex() != RateControlQuality && !vcodec.contains("nvenc") && !vcodec.endsWith("_amf") && !vcodec.endsWith("_qsv") && !vcodec.endsWith("_videotoolbox") && !vcodec.endsWith("_vaapi") && ui->dualPassCheckbox->isEnabled() && ui->dualPassCheckbox->isChecked()) setIfNotSet(p, "pass", 1); if (ui->scanModeCombo->currentIndex() == 0 && ui->fieldOrderCombo->currentIndex() == 0 && vcodec.startsWith("libx264")) { QString x264params = QString::fromUtf8(p->get("x264-params")); if (!x264params.contains("bff=") && !x264params.contains("tff=")) { x264params.prepend("bff=1:"); p->set("x264-params", x264params.toUtf8().constData()); } } } } return p; } void EncodeDock::collectProperties(QDomElement &node, int realtime) { Mlt::Properties *p = collectProperties(realtime); if (p && p->is_valid()) { for (int i = 0; i < p->count(); i++) if (p->get_name(i) && strcmp(p->get_name(i), "")) node.setAttribute(p->get_name(i), p->get(i)); } delete p; } void EncodeDock::setSubtitleProperties(QDomElement &node, Mlt::Producer *service) { if (!service) { return; } int subIndex = 0; for (int i = 0; i < service->filter_count(); i++) { QScopedPointer<Mlt::Filter> filter(service->filter(i)); if (filter && filter->is_valid() && filter->get("mlt_service") == QStringLiteral("subtitle_feed")) { QString key = QStringLiteral("subtitle.%1.feed").arg(subIndex); node.setAttribute(key, filter->get("feed")); key = QStringLiteral("subtitle.%1.lang").arg(subIndex); node.setAttribute(key, filter->get("lang")); subIndex++; } } } QPoint EncodeDock::addConsumerElement(Mlt::Producer *service, QDomDocument &dom, const QString &target, int realtime, int pass) { QDomElement consumerNode = dom.createElement("consumer"); QDomNodeList profiles = dom.elementsByTagName("profile"); if (profiles.isEmpty()) dom.documentElement().insertAfter(consumerNode, dom.documentElement()); else dom.documentElement().insertAfter(consumerNode, profiles.at(profiles.length() - 1)); consumerNode.setAttribute("mlt_service", "avformat"); consumerNode.setAttribute("target", pass == 1 ? kNullTarget : target); collectProperties(consumerNode, realtime); if ("libx265" == ui->videoCodecCombo->currentText()) { if (pass == 1 || pass == 2) { QString x265params = consumerNode.attribute("x265-params"); x265params = QStringLiteral("pass=%1:stats=%2:%3") .arg(pass).arg(QString(target).replace(":", "\\:") + "_2pass.log").arg(x265params); consumerNode.setAttribute("x265-params", x265params); } } else if ("libsvtav1" == ui->videoCodecCombo->currentText()) { if (pass == 1 || pass == 2) { QStringList encParams; encParams << QStringLiteral("passes=2"); encParams << QStringLiteral("pass=%1").arg(pass); encParams << QStringLiteral("stats=%1").arg(QString(target).replace(":", "\\:") + "_2pass.log"); QString origParams = consumerNode.attribute("svtav1-params"); if (!origParams.isEmpty()) encParams << origParams; consumerNode.setAttribute("svtav1-params", encParams.join(':')); } } else { if (pass == 1 || pass == 2) { consumerNode.setAttribute("pass", pass); consumerNode.setAttribute("passlogfile", target + "_2pass.log"); } if (pass == 1) { consumerNode.setAttribute("fastfirstpass", 1); consumerNode.removeAttribute("acodec"); consumerNode.setAttribute("an", 1); } else { consumerNode.removeAttribute("fastfirstpass"); } } if (ui->formatCombo->currentIndex() == 0 && ui->audioCodecCombo->currentIndex() == 0 && (target.endsWith(".mp4") || target.endsWith(".mov"))) consumerNode.setAttribute("strict", "experimental"); if (!ui->disableSubtitlesCheckbox->isChecked()) setSubtitleProperties(consumerNode, service); return QPoint(consumerNode.hasAttribute("frame_rate_num") ? consumerNode.attribute("frame_rate_num").toInt() : MLT.profile().frame_rate_num(), consumerNode.hasAttribute("frame_rate_den") ? consumerNode.attribute("frame_rate_den").toInt() : MLT.profile().frame_rate_den()); } MeltJob *EncodeDock::convertReframe(Mlt::Producer *service, QTemporaryFile *tmp, const QString &target, int realtime, int pass, const QThread::Priority priority) { MeltJob *job = nullptr; // Look for the reframe filter for (auto i = 0; !job && i < service->filter_count(); ++i) { Mlt::Filter filter(service->filter(i)); if (!::qstrcmp("reframe", filter.get(kShotcutFilterProperty)) && !filter.get_int("disable")) { // If it exists, make another XML with new profile based on reframe rect width and height auto rect = filter.anim_get_rect("rect", 0); LOG_DEBUG() << "Found Reframe" << rect.w << "x" << rect.h << tmp->fileName(); Mlt::Profile reframeProfile; reframeProfile.set_explicit(1); reframeProfile.set_colorspace(MLT.profile().colorspace()); reframeProfile.set_frame_rate(MLT.profile().frame_rate_num(), MLT.profile().frame_rate_den()); reframeProfile.set_sample_aspect(1, 1); reframeProfile.set_width(rect.w); reframeProfile.set_height(rect.h); auto gcd = Util::greatestCommonDivisor(rect.w, rect.h); reframeProfile.set_display_aspect(rect.w / gcd, rect.h / gcd); LOG_DEBUG() << "reframe profile" << reframeProfile.width() << "x" << reframeProfile.height(); Mlt::Producer producer(reframeProfile, "consumer", (QStringLiteral("xml:%1").arg(tmp->fileName())).toUtf8().constData()); Mlt::Filter affine; auto rectPropertyName("rect"); // TODO: GPU filters on the tractor do not work yet if (Settings.playerGPU()) { affine = Mlt::Filter(reframeProfile, "movit.rect"); affine.set("valign", "middle"); filter.set("halign", "center"); } else { affine = Mlt::Filter(reframeProfile, "affine"); affine.set("transition.valign", "middle"); affine.set("transition.halign", "center"); rectPropertyName = "transition.rect"; } producer.attach(affine); // set affine rect width and height same as video mode // compute (negate) new affine rect X and Y for each reframe rect keyframe // melt .mlt -attach affine transition.rect='-250 0 1280 720' -consumer avformat:test.mp4 width=404 height=720 display_aspect_num=404 display_aspect_den=720 sample_aspect_num=1 sample_aspect_den=1 an=1 auto anim = filter.get_anim("rect"); if (anim->key_count() > 0) { // Handle keyframes for (auto k = 0; k < anim->key_count(); ++k) { auto frameNum = anim->key_get_frame(k); if (frameNum >= 0) { rect = filter.anim_get_rect("rect", frameNum); rect.x = -rect.x; rect.y = -rect.y; rect.w = MLT.profile().width(); rect.h = MLT.profile().height(); affine.anim_set(rectPropertyName, rect, frameNum, 0, anim->key_get_type(k)); if (k + 1 == anim->key_count()) affine.anim_set(rectPropertyName, rect, service->get_out()); } } } else { // No keyframes rect.x = -rect.x; rect.y = -rect.y; rect.w = MLT.profile().width(); rect.h = MLT.profile().height(); affine.set(rectPropertyName, rect); } // Serialize Mlt::Consumer consumer(reframeProfile, "xml", "string"); consumer.set("root", ""); consumer.connect(producer); consumer.start(); // Parse XML to add consumer element QXmlStreamReader xmlReader(consumer.get("string")); QDomDocument dom; dom.setContent(&xmlReader, false); auto fps = addConsumerElement(service, dom, target, realtime, pass); job = new EncodeJob(QDir::toNativeSeparators(target), dom.toString(2), fps.x(), fps.y(), priority); tmp->setParent(job); // job gets ownership to delete object and temp file } } return job; } MeltJob *EncodeDock::createMeltJob(Mlt::Producer *service, const QString &target, int realtime, int pass, const QThread::Priority priority) { QString caption = tr("Export File"); if (Util::warnIfNotWritable(target, this, caption)) return nullptr; // if image sequence, change filename to include number QString mytarget = target; if (!ui->disableVideoCheckbox->isChecked()) { const QString &codec = ui->videoCodecCombo->currentText(); if (codec == "bmp" || codec == "dpx" || codec == "png" || codec == "ppm" || (codec == "libwebp" && ui->formatCombo->currentText() == "image2") || codec == "targa" || codec == "tiff" || (codec == "mjpeg" && ui->formatCombo->currentText() == "image2")) { QFileInfo fi(mytarget); mytarget = QStringLiteral("%1/%2-%05d.%3").arg(fi.path(), fi.baseName(), fi.completeSuffix()); } } // Fix in/out points of filters on clip-only project. QScopedPointer<Mlt::Producer> tempProducer; if (MLT.isSeekable(service) && service->type() != mlt_service_chain_type) if (ui->fromCombo->currentData().toString() == "clip" || ui->fromCombo->currentData().toString() == "batch") { QString xml = MLT.XML(service); tempProducer.reset(new Mlt::Producer(MLT.profile(), "xml-string", xml.toUtf8().constData())); service = tempProducer.data(); int producerIn = tempProducer->get_in(); if (producerIn > 0) { int n = tempProducer->filter_count(); for (int i = 0; i < n; i++) { QScopedPointer<Mlt::Filter> filter(tempProducer->filter(i)); if (filter->get_in() > 0) filter->set_in_and_out(filter->get_in() - producerIn, filter->get_out() - producerIn); } } } // get temp filename auto tmp = new QTemporaryFile {Util::writableTemporaryFile(target)}; tmp->open(); QString fileName = tmp->fileName(); auto isProxy = ui->previewScaleCheckBox->isChecked() && Settings.proxyEnabled(); MLT.saveXML(fileName, service, false /* without relative paths */, tmp, isProxy); tmp->close(); // parse xml QFile f1(fileName); f1.open(QIODevice::ReadOnly); QXmlStreamReader xmlReader(&f1); QDomDocument dom(fileName); dom.setContent(&xmlReader, false); f1.close(); // Check if the target file is a member of the project. QString xml = dom.toString(0); if (xml.contains(QDir::fromNativeSeparators(target))) { QMessageBox::warning(this, caption, tr("You cannot write to a file that is in your project.\n" "Try again with a different folder or file name.")); return nullptr; } // Add autoclose to playlists. QDomNodeList playlists = dom.elementsByTagName("playlist"); for (auto i = 0; i < playlists.length(); ++i) playlists.item(i).toElement().setAttribute("autoclose", 1); MeltJob *job = convertReframe(service, tmp, mytarget, realtime, pass, priority); if (!job) { auto fps = addConsumerElement(service, dom, mytarget, realtime, pass); job = new EncodeJob(QDir::toNativeSeparators(target), dom.toString(2), fps.x(), fps.y(), priority); job->setUseMultiConsumer( ui->widthSpinner->value() != MLT.profile().width() || ui->heightSpinner->value() != MLT.profile().height() || double(ui->aspectNumSpinner->value()) / double(ui->aspectDenSpinner->value()) != MLT.profile().dar() || (ui->fromCombo->currentData().toString() != "clip" && qFloor(ui->fpsSpinner->value() * 10000.0) != qFloor(MLT.profile().fps() * 10000.0))); delete tmp; } const auto &from = ui->fromCombo->currentData().toString(); if (MAIN.isMultitrackValid() && from.startsWith("marker:")) { bool ok = false; int index = from.mid(7).toInt(&ok); if (ok) { MarkersModel markersModel; markersModel.load(MAIN.multitrack()); auto marker = markersModel.getMarker(index); if (marker.end > marker.start) { job->setInAndOut(marker.start, marker.end); } } } return job; } void EncodeDock::runMelt(const QString &target, int realtime) { Mlt::Producer *service = fromProducer(); if (!service) { // For each playlist item. if (MAIN.playlist() && MAIN.playlist()->count() > 0) { // Use the first playlist item. QScopedPointer<Mlt::ClipInfo> info(MAIN.playlist()->clip_info(0)); if (!info) return; QString xml = MLT.XML(info->producer); QScopedPointer<Mlt::Producer> producer( new Mlt::Producer(MLT.profile(), "xml-string", xml.toUtf8().constData())); producer->set_in_and_out(info->frame_in, info->frame_out); m_immediateJob.reset(createMeltJob(producer.data(), target, realtime)); if (m_immediateJob) { m_immediateJob->setIsStreaming(true); connect(m_immediateJob.data(), SIGNAL(finished(AbstractJob *, bool, QString)), this, SLOT(onFinished(AbstractJob *, bool))); m_immediateJob->start(); } return; } else { service = MLT.producer(); } } m_immediateJob.reset(createMeltJob(service, target, realtime)); if (m_immediateJob) { m_immediateJob->setIsStreaming(true); connect(m_immediateJob.data(), SIGNAL(finished(AbstractJob *, bool, QString)), this, SLOT(onFinished(AbstractJob *, bool))); m_immediateJob->start(); } } class FindAnalysisFilterParser : public Mlt::Parser { private: QUuid m_uuid; QList<Mlt::Filter> m_filters; public: FindAnalysisFilterParser() : Mlt::Parser() {} QList<Mlt::Filter> &filters() { return m_filters; } int on_start_filter(Mlt::Filter *filter) { QString serviceName = filter->get("mlt_service"); if (serviceName == "loudness" || serviceName == "vidstab") { // If the results property does not exist, empty, or file does not exist. QString results = filter->get("results"); if (results.isEmpty()) { if (serviceName == "vidstab") { // vidstab requires a filename, which is only available when using a project folder. QString filename = filter->get("filename"); if (filename.isEmpty() || filename.endsWith("vidstab.trf")) { filename = QmlApplication::getNextProjectFile("stab"); } if (!filename.isEmpty()) { filter->set("filename", filename.toUtf8().constData()); m_filters << Mlt::Filter(*filter); // Touch file to prevent overwriting the same file QFile file(filename); file.open(QIODevice::WriteOnly); file.resize(0); file.close(); } } else { m_filters << Mlt::Filter(*filter); } } } return 0; } int on_start_producer(Mlt::Producer *) { return 0; } int on_end_producer(Mlt::Producer *) { return 0; } int on_start_playlist(Mlt::Playlist *) { return 0; } int on_end_playlist(Mlt::Playlist *) { return 0; } int on_start_tractor(Mlt::Tractor *) { return 0; } int on_end_tractor(Mlt::Tractor *) { return 0; } int on_start_multitrack(Mlt::Multitrack *) { return 0; } int on_end_multitrack(Mlt::Multitrack *) { return 0; } int on_start_track() { return 0; } int on_end_track() { return 0; } int on_end_filter(Mlt::Filter *) { return 0; } int on_start_transition(Mlt::Transition *) { return 0; } int on_end_transition(Mlt::Transition *) { return 0; } int on_start_chain(Mlt::Chain *) { return 0; } int on_end_chain(Mlt::Chain *) { return 0; } int on_start_link(Mlt::Link *) { return 0; } int on_end_link(Mlt::Link *) { return 0; } }; void EncodeDock::enqueueAnalysis() { Mlt::Producer *producer = fromProducer(); if (producer && producer->is_valid()) { // Look in the producer for all filters requiring analysis. FindAnalysisFilterParser parser; parser.start(*producer); // If there are Filters show a dialog. if (parser.filters().size() > 0) { QMessageBox dialog(QMessageBox::Question, windowTitle(), tr("Shotcut found filters that require analysis jobs that have not run.\n" "Do you want to run the analysis jobs now?"), QMessageBox::No | QMessageBox::Yes, this); dialog.setDefaultButton(QMessageBox::Yes); dialog.setEscapeButton(QMessageBox::No); dialog.setWindowModality(QmlApplication::dialogModality()); if (QMessageBox::Yes == dialog.exec()) { // If dialog accepted enqueue jobs. foreach (Mlt::Filter filter, parser.filters()) { QScopedPointer<QmlMetadata> meta(new QmlMetadata); QmlFilter qmlFilter(filter, meta.data()); bool isAudio = !::qstrcmp("loudness", filter.get("mlt_service")); qmlFilter.analyze(isAudio, false); } } } } } void EncodeDock::enqueueMelt(const QStringList &targets, int realtime) { Mlt::Producer *service = fromProducer(); int pass = (ui->videoRateControlCombo->currentIndex() != RateControlQuality && !ui->videoCodecCombo->currentText().contains("nvenc") && !ui->videoCodecCombo->currentText().endsWith("_amf") && !ui->videoCodecCombo->currentText().endsWith("_qsv") && !ui->videoCodecCombo->currentText().endsWith("_videotoolbox") && !ui->videoCodecCombo->currentText().endsWith("_vaapi") && ui->dualPassCheckbox->isEnabled() && ui->dualPassCheckbox->isChecked()) ? 1 : 0; if (!service) { // For each playlist item. if (MAIN.playlist() && MAIN.playlist()->count() > 0) { int n = MAIN.playlist()->count(); for (int i = 0; i < n; i++) { QScopedPointer<Mlt::ClipInfo> info(MAIN.playlist()->clip_info(i)); if (!info) continue; QString xml = MLT.XML(info->producer); QScopedPointer<Mlt::Producer> producer( new Mlt::Producer(MLT.profile(), "xml-string", xml.toUtf8().constData())); producer->set_in_and_out(info->frame_in, info->frame_out); MeltJob *job = createMeltJob(producer.data(), targets[i], realtime, pass); if (job) { JOBS.add(job); if (pass) { job = createMeltJob(producer.data(), targets[i], realtime, 2); if (job) JOBS.add(job); } } } } } else { MeltJob *job = createMeltJob(service, targets[0], realtime, pass); if (job) { JOBS.add(job); if (pass) { job = createMeltJob(service, targets[0], realtime, 2); if (job) JOBS.add(job); } } } } void EncodeDock::encode(const QString &target) { bool isMulti = true; Mlt::Producer *producer = new Mlt::Producer(MLT.producer()); double volume = MLT.volume(); MLT.closeConsumer(); MLT.close(); producer->seek(0); MLT.setProducer(producer, isMulti); MLT.consumer()->set("1", "avformat"); MLT.consumer()->set("1.target", target.toUtf8().constData()); Mlt::Properties *p = collectProperties(-1); if (p && p->is_valid()) { for (int i = 0; i < p->count(); i++) MLT.consumer()->set(QStringLiteral("1.%1").arg(p->get_name(i)).toLatin1().constData(), p->get(i)); } delete p; if (ui->formatCombo->currentIndex() == 0 && ui->audioCodecCombo->currentIndex() == 0 && (target.endsWith(".mp4") || target.endsWith(".mov"))) MLT.consumer()->set("1.strict", "experimental"); MLT.setVolume(volume); MLT.play(); } void EncodeDock::resetOptions() { // Reset all controls to default values. ui->formatCombo->setCurrentIndex(0); ui->scanModeCombo->setCurrentIndex(1); on_scanModeCombo_currentIndexChanged(ui->scanModeCombo->currentIndex()); ui->deinterlacerCombo->setCurrentIndex(4); ui->interpolationCombo->setCurrentIndex(1); ui->rangeComboBox->setCurrentIndex(0); ui->videoRateControlCombo->setCurrentIndex(RateControlQuality); ui->videoBitrateCombo->lineEdit()->setText("12M"); ui->videoBufferSizeSpinner->setValue(1500); ui->gopSpinner->blockSignals(true); ui->gopSpinner->setValue(qRound(MLT.profile().fps() * 5.0)); ui->gopSpinner->blockSignals(false); ui->strictGopCheckBox->setChecked(false); ui->bFramesSpinner->setValue(3); ui->videoCodecThreadsSpinner->setValue(0); ui->dualPassCheckbox->setChecked(false); ui->disableVideoCheckbox->setChecked(false); setAudioChannels(MLT.audioChannels()); ui->sampleRateCombo->lineEdit()->setText("48000"); ui->audioRateControlCombo->setCurrentIndex(1); ui->audioBitrateCombo->lineEdit()->setText("384k"); ui->audioQualitySpinner->setValue(50); ui->disableAudioCheckbox->setChecked(false); on_videoBufferDurationChanged(); Mlt::Properties preset; preset.set("f", "mp4"); preset.set("movflags", "+faststart"); preset.set("vcodec", "libx264"); preset.set("crf", "23"); preset.set("preset", "fast"); preset.set("acodec", "aac"); preset.set("meta.preset.extension", "mp4"); loadPresetFromProperties(preset); } Mlt::Producer *EncodeDock::fromProducer() const { QString from = ui->fromCombo->currentData().toString(); if (from == "clip") return MLT.isClip() ? MLT.producer() : MLT.savedProducer(); else if (from == "playlist") return MAIN.playlist(); else if (from == "timeline" || from.startsWith("marker:")) return MAIN.multitrack(); else return nullptr; } void EncodeDock::filterCodecParams(const QString &vcodec, QStringList &other) { QString codecKey; QStringList filterKeys; if (vcodec == "libx265") { codecKey = "x265-params="; filterKeys << "bitrate"; filterKeys << "vbv-bufsize"; filterKeys << "crf"; filterKeys << "vbv-maxrate"; filterKeys << "keyint"; filterKeys << "scenecut"; filterKeys << "bframes"; filterKeys << "interlace"; } else if (vcodec == "libsvtav1") { codecKey = "svtav1-params="; filterKeys << "rc"; filterKeys << "tbr"; filterKeys << "buf-sz"; filterKeys << "crf"; filterKeys << "mbr"; filterKeys << "keyint"; filterKeys << "scd"; filterKeys << "enable-dg"; filterKeys << "pred-struct"; filterKeys << "lp"; } else return; int i = 0; foreach (const QString &line, other) { if (line.startsWith(codecKey)) break; ++i; } if (i >= other.size()) return; QString origParams = other[i].mid(codecKey.length()); QStringList keepParams; foreach (const QString &kv_str, origParams.split(':', Qt::SkipEmptyParts)) { QStringList kv_parts = kv_str.split('=', Qt::SkipEmptyParts); if (kv_parts.size() > 1) // found key and value if (!filterKeys.contains(kv_parts[0])) keepParams << kv_str; } other.removeAt(i); if (keepParams.size() > 0) other.insert(i, codecKey + keepParams.join(':')); } void EncodeDock::onVideoCodecComboChanged(int index, bool ignorePreset, bool resetBframes) { Q_UNUSED(index) QString vcodec = ui->videoCodecCombo->currentText(); if (vcodec.contains("nvenc")) { if (!ignorePreset) { QString newValue; foreach (QString line, ui->advancedTextEdit->toPlainText().split("\n")) { if (!line.startsWith("preset=")) { newValue += line; newValue += "\n"; } } ui->advancedTextEdit->setPlainText(newValue); } if (resetBframes) ui->bFramesSpinner->setValue(0); ui->dualPassCheckbox->setChecked(false); ui->dualPassCheckbox->setEnabled(false); } else if (vcodec.endsWith("_amf")) { if (resetBframes && vcodec.startsWith("hevc_")) ui->bFramesSpinner->setValue(0); ui->dualPassCheckbox->setChecked(false); ui->dualPassCheckbox->setEnabled(false); } else if (vcodec.endsWith("_qsv")) { if (vcodec.startsWith("hevc_") && !ui->advancedTextEdit->toPlainText().contains("load_plugin=")) ui->advancedTextEdit->appendPlainText("\nload_plugin=hevc_hw\n"); if (resetBframes && vcodec.startsWith("av1_")) ui->bFramesSpinner->setValue(0); ui->dualPassCheckbox->setChecked(false); ui->dualPassCheckbox->setEnabled(false); } else if (vcodec.endsWith("_videotoolbox")) { // According to FFmpeg source code, this is only on Apple Silicon #if defined(Q_OS_MAC) && !defined(Q_PROCESSOR_ARM) if (ui->videoRateControlCombo->currentIndex() == RateControlQuality) { ui->videoRateControlCombo->setCurrentIndex(RateControlAverage); } #endif ui->dualPassCheckbox->setChecked(false); ui->dualPassCheckbox->setEnabled(false); } else if (vcodec.endsWith("_vaapi")) { ui->dualPassCheckbox->setChecked(false); ui->dualPassCheckbox->setEnabled(false); } else { ui->dualPassCheckbox->setEnabled(true); } on_videoQualitySpinner_valueChanged(ui->videoQualitySpinner->value()); } static double getBufferSize(Mlt::Properties &preset, const char *property) { double size = preset.get_double(property); const QString &s = preset.get(property); // evaluate suffix if (s.endsWith('k')) size *= 1000; if (s.endsWith('M')) size *= 1000000; // convert to KiB return double(qRound(size / 1024 / 8 * 100)) / 100; } void EncodeDock::on_presetsTree_clicked(const QModelIndex &index) { if (!index.parent().isValid()) return; QString name = m_presetsModel.data(index, kCustomPresetFileNameRole).toString(); if (!name.isEmpty()) { Mlt::Properties *preset; if (m_presetsModel.data(index.parent()).toString() == tr("Custom") || m_presetsModel.data(index.parent().parent()).toString() == tr("Custom")) { ui->removePresetButton->setEnabled(true); preset = new Mlt::Properties(); QDir dir(Settings.appDataLocation()); if (dir.cd("presets") && dir.cd("encode")) preset->load(dir.absoluteFilePath(name).toLatin1().constData()); } else { ui->removePresetButton->setEnabled(false); preset = new Mlt::Properties((mlt_properties) m_presets->get_data(name.toLatin1().constData())); } if (preset->is_valid()) { QStringList textParts = name.split('/'); resetOptions(); if (textParts.count() > 3) { // textParts = ['consumer', 'avformat', profile, preset]. QString folder = textParts.at(2); if (m_profiles->get_data(folder.toLatin1().constData())) { // only set these fields if the folder is a profile Mlt::Profile p(folder.toLatin1().constData()); ui->widthSpinner->setValue(p.width()); ui->heightSpinner->setValue(p.height()); ui->aspectNumSpinner->setValue(p.display_aspect_num()); ui->aspectDenSpinner->setValue(p.display_aspect_den()); ui->scanModeCombo->setCurrentIndex(p.progressive()); ui->fpsSpinner->setValue(p.fps()); } } loadPresetFromProperties(*preset); } delete preset; } else { on_resetButton_clicked(); } } void EncodeDock::on_presetsTree_activated(const QModelIndex &index) { on_presetsTree_clicked(index); } void EncodeDock::on_encodeButton_clicked() { if (!MLT.producer()) return; if (m_immediateJob) { m_immediateJob->stop(); ui->fromCombo->setEnabled(true); QTimer::singleShot(kOpenCaptureFileDelayMs, this, SLOT(openCaptureFile())); return; } if (ui->encodeButton->text() == tr("Stop Capture")) { MLT.closeConsumer(); emit captureStateChanged(false); ui->streamButton->setDisabled(false); QTimer::singleShot(kOpenCaptureFileDelayMs, this, SLOT(openCaptureFile())); return; } bool seekable = MLT.isSeekable(fromProducer()); if (seekable && checkForMissingFiles()) { return; } MLT.pause(); QString directory = Settings.encodePath(); auto projectBaseName = QFileInfo(MAIN.fileName()).completeBaseName(); if (!m_extension.isEmpty()) { if (!MAIN.fileName().isEmpty()) { directory += QStringLiteral("/%1.%2").arg(projectBaseName, m_extension); } } else { if (!MAIN.fileName().isEmpty()) { directory += "/" + projectBaseName; } } QString caption = seekable ? tr("Export File") : tr("Capture File"); if (ui->fromCombo->currentData().toString() == "batch") { caption = tr("Export Files"); MultiFileExportDialog dialog(tr("Export Each Playlist Item"), MAIN.playlist(), directory, projectBaseName, m_extension, this); if (dialog.exec() != QDialog::Accepted) { return; } m_outputFilenames = dialog.getExportFiles(); } else { QString nameFilter; if (!m_extension.isEmpty()) nameFilter = tr("%1 (*.%2);;All Files (*)").arg(ui->formatCombo->currentText(), m_extension); else nameFilter = tr("Determined by Export (*)"); QString newName = QFileDialog::getSaveFileName(this, caption, directory, nameFilter, nullptr, Util::getFileDialogOptions()); if (!newName.isEmpty() && !m_extension.isEmpty()) { QFileInfo fi(newName); if (fi.suffix().isEmpty()) { newName += '.'; newName += m_extension; } } m_outputFilenames = QStringList(newName); } if (m_outputFilenames.isEmpty() || m_outputFilenames[0].isEmpty()) { return; } if (Util::warnIfLowDiskSpace(m_outputFilenames[0])) { MAIN.showStatusMessage(tr("Export canceled")); return; } QFileInfo fi(m_outputFilenames[0]); Settings.setEncodePath(fi.path()); if (seekable) { MLT.purgeMemoryPool(); // Batch encode int threadCount = QThread::idealThreadCount(); if (threadCount > 2 && ui->parallelCheckbox->isChecked()) threadCount = qMin(threadCount - 1, 4); else threadCount = 1; enqueueAnalysis(); enqueueMelt(m_outputFilenames, Settings.playerGPU() ? -1 : -threadCount); } else if (MLT.producer()->get_int(kBackgroundCaptureProperty)) { // Capture in background ui->dualPassCheckbox->setChecked(false); #if defined(Q_OS_MAC) auto priority = QThread::NormalPriority; #else auto priority = QThread::HighPriority; #endif m_immediateJob.reset(createMeltJob(fromProducer(), m_outputFilenames[0], -1, 0, priority)); if (m_immediateJob) { // Close the player's producer to prevent resource contention. MAIN.hideProducer(); m_immediateJob->setIsStreaming(true); connect(m_immediateJob.data(), SIGNAL(finished(AbstractJob *, bool, QString)), this, SLOT(onFinished(AbstractJob *, bool))); if (MLT.resource().startsWith("gdigrab:") || MLT.resource().startsWith("x11grab:")) { ui->stopCaptureButton->show(); } else { ui->encodeButton->setText(tr("Stop Capture")); ui->fromCombo->setDisabled(true); } if (MLT.resource().startsWith("gdigrab:")) MAIN.showMinimized(); int msec = MLT.producer()->get_int(kBackgroundCaptureProperty) * 1000; QTimer::singleShot(msec, m_immediateJob.data(), SLOT(start())); } } else { // Capture to file // use multi consumer to encode and preview simultaneously ui->dualPassCheckbox->setChecked(false); ui->encodeButton->setText(tr("Stop Capture")); encode(m_outputFilenames[0]); emit captureStateChanged(true); ui->streamButton->setDisabled(true); } } void EncodeDock::onAudioChannelsChanged() { setAudioChannels(MLT.audioChannels()); } void EncodeDock::setResolutionAspectFromProfile() { int width = MLT.profile().width(); int height = MLT.profile().height(); double sar = MLT.profile().sar(); int dar_numerator = width * sar; int dar_denominator = height; if (height > 0) { switch (int(sar * width / height * 100)) { case 133: dar_numerator = 4; dar_denominator = 3; break; case 177: dar_numerator = 16; dar_denominator = 9; break; case 56: dar_numerator = 9; dar_denominator = 16; break; } } ui->widthSpinner->setValue(width); ui->heightSpinner->setValue(height); ui->aspectNumSpinner->setValue(dar_numerator); ui->aspectDenSpinner->setValue(dar_denominator); } void EncodeDock::onProfileChanged() { setResolutionAspectFromProfile(); ui->scanModeCombo->setCurrentIndex(MLT.profile().progressive()); on_scanModeCombo_currentIndexChanged(ui->scanModeCombo->currentIndex()); ui->fpsSpinner->setValue(MLT.profile().fps()); ui->fpsSpinner->setMinimum(qRound(MLT.profile().fps() / 3.0)); if (m_isDefaultSettings) { ui->gopSpinner->blockSignals(true); ui->gopSpinner->setValue(qRound(MLT.profile().fps() * 5.0)); ui->gopSpinner->blockSignals(false); } onReframeChanged(); } void EncodeDock::onReframeChanged() { auto producer = fromProducer(); ui->reframeButton->setEnabled(producer && producer == MAIN.multitrack()); auto reframe = getReframeFilter(producer); if (reframe.is_valid()) { // If reframe's disable property changed auto enabled = !reframe.get_int("disable"); if (enabled == ui->widthSpinner->isEnabled()) { setReframeEnabled(enabled); if (enabled) hideResampleWarning(); else setResolutionAspectFromProfile(); } // If reframe is on and its resolution changed if (enabled) { auto rect = reframe.anim_get_rect("rect", 0); if (rect.w > 0 && rect.h > 0 && (rect.w != ui->widthSpinner->value() || rect.h != ui->heightSpinner->value())) { ui->widthSpinner->setValue(rect.w); ui->heightSpinner->setValue(rect.h); auto gcd = Util::greatestCommonDivisor(rect.w, rect.h); ui->aspectNumSpinner->setValue(rect.w / gcd); ui->aspectDenSpinner->setValue(rect.h / gcd); } } } } void EncodeDock::on_streamButton_clicked() { if (m_immediateJob) { m_immediateJob->stop(); return; } if (ui->streamButton->text() == tr("Stop Stream")) { bool isMulti = false; MLT.closeConsumer(); MLT.setProducer(MLT.producer(), isMulti); MLT.play(); ui->streamButton->setText(tr("Stream")); emit captureStateChanged(false); ui->encodeButton->setDisabled(false); return; } QInputDialog dialog(this); dialog.setInputMode(QInputDialog::TextInput); dialog.setWindowTitle(tr("Stream")); dialog.setLabelText( tr("Enter the network protocol scheme, address, port, and parameters as an URL:")); dialog.setTextValue("udp://224.224.224.224:1234?pkt_size=1316&reuse=1"); dialog.setWindowModality(QmlApplication::dialogModality()); int r = dialog.exec(); QString url = dialog.textValue(); if (r == QDialog::Accepted && !url.isEmpty()) { MLT.pause(); ui->dualPassCheckbox->setChecked(false); ui->streamButton->setText(tr("Stop Stream")); if (MLT.isSeekable()) // Stream in background runMelt(url, 1); else if (MLT.producer()->get_int(kBackgroundCaptureProperty)) { // Stream Shotcut screencast MLT.stop(); runMelt(url, 1); ui->stopCaptureButton->show(); } else { // Live streaming in foreground encode(url); emit captureStateChanged(true); ui->encodeButton->setDisabled(true); } m_outputFilenames.clear(); } } void EncodeDock::on_addPresetButton_clicked() { QScopedPointer<Mlt::Properties> data(collectProperties(0, true)); AddEncodePresetDialog dialog(this); QStringList ls; if (data && data->is_valid()) { // Revert collectProperties() overwriting user-specified advanced options (x265-params). foreach (QString line, ui->advancedTextEdit->toPlainText().split("\n")) data->parse(line.toUtf8().constData()); for (int i = 0; i < data->count(); i++) if (strlen(data->get_name(i)) > 0) ls << QStringLiteral("%1=%2").arg(data->get_name(i), data->get(i)); } dialog.setWindowTitle(tr("Add Export Preset")); dialog.setProperties(ls.join("\n")); if (dialog.exec() == QDialog::Accepted) { QString preset = dialog.presetName(); QDir dir(Settings.appDataLocation()); QString subdir("encode"); if (!preset.isEmpty()) { if (!dir.exists()) dir.mkpath(dir.path()); if (!dir.cd("presets")) { if (dir.mkdir("presets")) dir.cd("presets"); } if (!dir.cd(subdir)) { if (dir.mkdir(subdir)) dir.cd(subdir); } { QFile f(dir.filePath(preset)); if (f.open(QIODevice::WriteOnly | QIODevice::Text)) f.write(dialog.properties().toUtf8()); } // add the preset and select it loadPresets(); QModelIndex parentIndex = m_presetsModel.index(0, 0); int n = m_presetsModel.rowCount(parentIndex); for (int i = 0; i < n; i++) { QModelIndex index = m_presetsModel.index(i, 0, parentIndex); if (m_presetsModel.data(index, kCustomPresetFileNameRole).toString() == preset) { ui->presetsTree->setCurrentIndex(index); break; } } } } } void EncodeDock::on_removePresetButton_clicked() { QModelIndex index = ui->presetsTree->currentIndex(); QString preset = m_presetsModel.data(index, kCustomPresetFileNameRole).toString(); QMessageBox dialog(QMessageBox::Question, tr("Delete Preset"), tr("Are you sure you want to delete %1?").arg(preset), QMessageBox::No | QMessageBox::Yes, this); dialog.setDefaultButton(QMessageBox::Yes); dialog.setEscapeButton(QMessageBox::No); dialog.setWindowModality(QmlApplication::dialogModality()); int result = dialog.exec(); if (result == QMessageBox::Yes) { QDir dir(Settings.appDataLocation()); if (dir.cd("presets") && dir.cd("encode")) { dir.remove(preset); m_presetsModel.removeRow(index.row(), index.parent()); } } } void EncodeDock::onFinished(AbstractJob *job, bool isSuccess) { Q_UNUSED(job) Q_UNUSED(isSuccess) on_fromCombo_currentIndexChanged(0); ui->streamButton->setText(tr("Stream")); m_immediateJob.reset(); emit captureStateChanged(false); ui->encodeButton->setDisabled(false); } void EncodeDock::on_stopCaptureButton_clicked() { ui->stopCaptureButton->hide(); if (m_immediateJob) m_immediateJob->stop(); if (!m_outputFilenames.isEmpty()) QTimer::singleShot(kOpenCaptureFileDelayMs, this, SLOT(openCaptureFile())); } void EncodeDock::on_videoRateControlCombo_activated(int index) { switch (index) { case RateControlAverage: ui->videoBitrateCombo->show(); ui->videoBufferSizeSpinner->hide(); ui->videoQualitySpinner->hide(); ui->dualPassCheckbox->show(); ui->videoBitrateLabel->show(); ui->videoBitrateSuffixLabel->show(); ui->videoBufferSizeLabel->hide(); ui->videoBufferSizeSuffixLabel->hide(); ui->videoQualityLabel->hide(); ui->videoQualitySuffixLabel->hide(); break; case RateControlConstant: ui->videoBitrateCombo->show(); ui->videoBufferSizeSpinner->show(); ui->videoQualitySpinner->hide(); ui->dualPassCheckbox->show(); ui->videoBitrateLabel->show(); ui->videoBitrateSuffixLabel->show(); ui->videoBufferSizeLabel->show(); ui->videoBufferSizeSuffixLabel->show(); ui->videoQualityLabel->hide(); ui->videoQualitySuffixLabel->hide(); break; case RateControlQuality: ui->videoBitrateCombo->hide(); ui->videoBufferSizeSpinner->hide(); ui->videoQualitySpinner->show(); ui->dualPassCheckbox->hide(); ui->videoBitrateLabel->hide(); ui->videoBitrateSuffixLabel->hide(); ui->videoBufferSizeLabel->hide(); ui->videoBufferSizeSuffixLabel->hide(); ui->videoQualityLabel->show(); ui->videoQualitySuffixLabel->show(); break; case RateControlConstrained: ui->videoBitrateCombo->show(); ui->videoBufferSizeSpinner->show(); ui->videoQualitySpinner->show(); ui->dualPassCheckbox->show(); ui->videoBitrateLabel->show(); ui->videoBitrateSuffixLabel->show(); ui->videoBufferSizeLabel->show(); ui->videoBufferSizeSuffixLabel->show(); ui->videoQualityLabel->show(); ui->videoQualitySuffixLabel->show(); break; } on_videoQualitySpinner_valueChanged(ui->videoQualitySpinner->value()); } void EncodeDock::on_audioRateControlCombo_activated(int index) { switch (index) { case RateControlAverage: ui->audioBitrateCombo->show(); ui->audioQualitySpinner->hide(); ui->audioBitrateLabel->show(); ui->audioBitrateSuffixLabel->show(); ui->audioQualityLabel->hide(); ui->audioQualitySuffixLabel->hide(); break; case RateControlConstant: ui->audioBitrateCombo->show(); ui->audioQualitySpinner->hide(); ui->audioBitrateLabel->show(); ui->audioBitrateSuffixLabel->show(); ui->audioQualityLabel->hide(); ui->audioQualitySuffixLabel->hide(); break; case RateControlQuality: ui->audioBitrateCombo->hide(); ui->audioQualitySpinner->show(); ui->audioBitrateLabel->hide(); ui->audioBitrateSuffixLabel->hide(); ui->audioQualityLabel->show(); ui->audioQualitySuffixLabel->show(); break; } } void EncodeDock::on_scanModeCombo_currentIndexChanged(int index) { if (index == 0) { // Interlaced ui->fieldOrderCombo->removeItem(2); // None, if it exists } else { // Progressive if (ui->fieldOrderCombo->count() < 3) ui->fieldOrderCombo->addItem(tr("None")); ui->fieldOrderCombo->setCurrentIndex(ui->fieldOrderCombo->count() - 1); } ui->fieldOrderCombo->setDisabled(index); } void EncodeDock::on_presetsSearch_textChanged(const QString &search) { m_presetsModel.setFilterFixedString(search); if (search.isEmpty()) ui->presetsTree->expandAll(); } bool PresetsProxyModel::filterAcceptsRow(int source_row, const QModelIndex &source_parent) const { QModelIndex index = sourceModel()->index(source_row, 0, source_parent); // Show categories with descendants that match. for (int i = 0; i < sourceModel()->rowCount(index); i++) if (filterAcceptsRow(i, index)) return true; return sourceModel()->data(index).toString().contains(filterRegularExpression()) || sourceModel()->data(index, Qt::ToolTipRole).toString().contains(filterRegularExpression()); } void EncodeDock::on_resetButton_clicked() { m_isDefaultSettings = true; resetOptions(); onProfileChanged(); ui->presetsTree->setCurrentIndex(QModelIndex()); } void EncodeDock::openCaptureFile() { MAIN.open(m_outputFilenames[0]); } void EncodeDock::on_formatCombo_currentIndexChanged(int index) { Q_UNUSED(index); m_extension.clear(); if (index > 0) defaultFormatExtension(); } void EncodeDock::on_videoBufferDurationChanged() { QString vb = ui->videoBitrateCombo->currentText(); vb.replace('k', "").replace('M', "000"); double duration = (double)ui->videoBufferSizeSpinner->value() * 8.0 / vb.toDouble(); QString label = tr("KiB (%1s)").arg(duration); ui->videoBufferSizeSuffixLabel->setText(label); } void EncodeDock::on_gopSpinner_valueChanged(int value) { Q_UNUSED(value); m_isDefaultSettings = false; } void EncodeDock::on_fromCombo_currentIndexChanged(int index) { Q_UNUSED(index) auto producer = fromProducer(); ui->reframeButton->setEnabled(producer && producer == MAIN.multitrack()); if (MLT.isSeekable(producer)) ui->encodeButton->setText(tr("Export File")); else ui->encodeButton->setText(tr("Capture File")); } void EncodeDock::on_videoCodecCombo_currentIndexChanged(int index) { auto lossy = !m_losslessVideoCodecs.contains(ui->videoCodecCombo->currentText()); ui->videoRateControlCombo->setEnabled(lossy); ui->videoBitrateCombo->setEnabled(lossy); ui->videoBufferSizeSpinner->setEnabled(lossy); ui->videoQualitySpinner->setEnabled(lossy); auto intraOnly = m_intraOnlyCodecs.contains(ui->videoCodecCombo->currentText()); ui->gopSpinner->setEnabled(!intraOnly); ui->strictGopCheckBox->setEnabled(!intraOnly); ui->bFramesSpinner->setEnabled(!intraOnly); onVideoCodecComboChanged(index); } void EncodeDock::on_audioCodecCombo_currentIndexChanged(int index) { Q_UNUSED(index) auto lossy = !m_losslessAudioCodecs.contains(ui->audioCodecCombo->currentText()); ui->audioRateControlCombo->setEnabled(lossy); ui->audioBitrateCombo->setEnabled(lossy); ui->audioQualitySpinner->setEnabled(lossy); on_audioQualitySpinner_valueChanged(ui->audioQualitySpinner->value()); } void EncodeDock::setAudioChannels( int channels ) { switch (channels) { case 1: ui->audioChannelsCombo->setCurrentIndex(AudioChannels1); break; case 2: ui->audioChannelsCombo->setCurrentIndex(AudioChannels2); break; case 4: ui->audioChannelsCombo->setCurrentIndex(AudioChannels4); break; case 6: ui->audioChannelsCombo->setCurrentIndex(AudioChannels6); break; } } void EncodeDock::on_widthSpinner_editingFinished() { ui->widthSpinner->setValue(Util::coerceMultiple(ui->widthSpinner->value())); } void EncodeDock::on_heightSpinner_editingFinished() { ui->heightSpinner->setValue(Util::coerceMultiple(ui->heightSpinner->value())); } void EncodeDock::on_advancedButton_clicked(bool checked) { ui->advancedCheckBox->setVisible(checked); ui->streamButton->setVisible(false); ui->formatLabel->setVisible(checked); ui->formatCombo->setVisible(checked); ui->tabWidget->setVisible(checked); ui->helpLabel->setVisible(!checked); } static QStringList codecs() { QStringList codecs; #if defined(Q_OS_WIN) codecs << "h264_nvenc"; codecs << "hevc_nvenc"; codecs << "av1_nvenc"; codecs << "h264_amf"; codecs << "hevc_amf"; codecs << "av1_amf"; codecs << "h264_qsv"; codecs << "hevc_qsv"; codecs << "vp9_qsv"; codecs << "av1_qsv"; #elif defined(Q_OS_MAC) codecs << "h264_videotoolbox"; codecs << "hevc_videotoolbox"; #else codecs << "av1_nvenc"; codecs << "h264_nvenc"; codecs << "hevc_nvenc"; codecs << "h264_vaapi"; codecs << "hevc_vaapi"; codecs << "av1_vaapi"; #endif return codecs; } void EncodeDock::on_hwencodeCheckBox_clicked(bool checked) { if (checked && Settings.encodeHardware().isEmpty()) { if (!detectHardwareEncoders()) ui->hwencodeCheckBox->setChecked(false); } Settings.setEncodeUseHardware(ui->hwencodeCheckBox->isChecked()); std::unique_ptr<Mlt::Properties> properties {collectProperties(0, true)}; resetOptions(); if (properties && properties->is_valid()) { QString value = QString::fromLatin1(properties->get("vcodec")); if (value.startsWith("av1_")) { value = "libsvtav1"; } else if (value.startsWith("h264_")) { value = "libx264"; } else if (value.startsWith("hevc_")) { value = "libx265"; } properties->set("vcodec", value.toUtf8().constData()); value = QString::fromLatin1(properties->get("pix_fmt")); if (value.contains("p010le")) properties->set("pix_fmt", "yuv420p10le"); loadPresetFromProperties(*properties); } } void EncodeDock::on_hwencodeButton_clicked() { ListSelectionDialog dialog(codecs(), this); dialog.setWindowModality(QmlApplication::dialogModality()); dialog.setWindowTitle(tr("Configure Hardware Encoding")); dialog.setSelection(Settings.encodeHardware()); QPushButton *button = dialog.buttonBox()->addButton(tr("Detect"), QDialogButtonBox::ResetRole); connect(button, SIGNAL(clicked()), &dialog, SLOT(reject())); connect(button, SIGNAL(clicked()), this, SLOT(detectHardwareEncoders())); // Show the dialog. if (dialog.exec() == QDialog::Accepted) { Settings.setEncodeHardware(dialog.selection()); if (dialog.selection().isEmpty()) { ui->hwencodeCheckBox->setChecked(false); Settings.setEncodeUseHardware(false); } } } void EncodeDock::on_advancedCheckBox_clicked(bool checked) { Settings.setEncodeAdvanced(checked); } void EncodeDock::on_fpsSpinner_editingFinished() { if (ui->fpsSpinner->value() != m_fps) { const QString caption(tr("Export Frames/sec")); if (ui->fpsSpinner->value() == 23.98 || ui->fpsSpinner->value() == 23.976) { Util::showFrameRateDialog(caption, 24000, ui->fpsSpinner, this); } else if (ui->fpsSpinner->value() == 29.97) { Util::showFrameRateDialog(caption, 30000, ui->fpsSpinner, this); } else if (ui->fpsSpinner->value() == 47.95) { Util::showFrameRateDialog(caption, 48000, ui->fpsSpinner, this); } else if (ui->fpsSpinner->value() == 59.94) { Util::showFrameRateDialog(caption, 60000, ui->fpsSpinner, this); } m_fps = ui->fpsSpinner->value(); checkFrameRate(); } } void EncodeDock::on_fpsComboBox_activated(int arg1) { if (!ui->fpsComboBox->itemText(arg1).isEmpty()) { ui->fpsSpinner->setValue(ui->fpsComboBox->itemText(arg1).toDouble()); checkFrameRate(); } } void EncodeDock::on_videoQualitySpinner_valueChanged(int vq) { const QString &vcodec = ui->videoCodecCombo->currentText(); QString s; if (vcodec.startsWith("libx264") || vcodec == "libx265") { s = QStringLiteral("crf=%1").arg(TO_ABSOLUTE(51, 0, vq)); } else if (vcodec.startsWith("libvpx") || vcodec.startsWith("libaom-") || vcodec == "libsvtav1") { s = QStringLiteral("crf=%1").arg(TO_ABSOLUTE(63, 0, vq)); } else if (vcodec.contains("nvenc")) { vq = TO_ABSOLUTE(51, 0, vq); if (ui->videoRateControlCombo->currentIndex() == RateControlQuality) s = QStringLiteral("cq=%1 %2").arg(vq).arg(vq == 0 ? tr("(auto)") : ""); else s = QStringLiteral("qmin=%1").arg(TO_ABSOLUTE(51, 0, vq)); } else if (vcodec.endsWith("_amf")) { s = QStringLiteral("qp_i=qp_p=qp_b=%1").arg(TO_ABSOLUTE(51, 0, vq)); } else if (vcodec.endsWith("_vaapi")) { s = QStringLiteral("vglobal_quality=%1").arg(TO_ABSOLUTE(51, 0, vq)); } else if (vcodec.endsWith("_qsv")) { s = QStringLiteral("qscale=%1").arg(TO_ABSOLUTE(51, 1, vq)); } else if (vcodec.endsWith("_videotoolbox")) { s = QStringLiteral("qscale=%1").arg(vq); } else if (vcodec.startsWith("libwebp")) { s = QStringLiteral("qscale=%1").arg(TO_ABSOLUTE(0, 100, vq)); } else { s = QStringLiteral("qscale=%1").arg(TO_ABSOLUTE(31, 1, vq)); } ui->videoQualitySuffixLabel->setText(s); } void EncodeDock::on_audioQualitySpinner_valueChanged(int aq) { const QString &acodec = ui->audioCodecCombo->currentText(); QString s("aq=%1"); if (acodec == "aac") { auto a = 0.1 + 1.9 * aq / 100.0; ui->audioQualitySuffixLabel->setText(s.arg(a)); } else { if (acodec == "libmp3lame") aq = TO_ABSOLUTE(9, 0, aq); else if (acodec == "libvorbis" || acodec == "vorbis") aq = TO_ABSOLUTE(0, 10, aq); else aq = TO_ABSOLUTE(0, 500, aq); ui->audioQualitySuffixLabel->setText(s.arg(aq)); } } void EncodeDock::on_parallelCheckbox_clicked(bool checked) { Settings.setEncodeParallelProcessing(checked); } bool EncodeDock::detectHardwareEncoders() { MAIN.showStatusMessage(tr("Detecting hardware encoders...")); QStringList hwlist; QFileInfo ffmpegPath(qApp->applicationDirPath(), "ffmpeg"); foreach (const QString &codec, codecs()) { LOG_INFO() << "checking for" << codec; QProcess proc; QStringList args; args << "-hide_banner" << "-f" << "lavfi" << "-i" << "color=s=640x360" << "-frames" << "1" << "-an"; if (codec.endsWith("_vaapi")) args << "-init_hw_device" << "vaapi=vaapi0:" << "-filter_hw_device" << "vaapi0" << "-vf" << "format=nv12,hwupload"; else if (codec == "hevc_qsv") args << "-load_plugin" << "hevc_hw"; else if (codec.endsWith("_videotoolbox")) args << "-pix_fmt" << "nv12"; args << "-c:v" << codec << "-f" << "rawvideo" << "pipe:"; LOG_DEBUG() << ffmpegPath.absoluteFilePath() + " " + args.join(' '); proc.setStandardOutputFile(QProcess::nullDevice()); proc.setReadChannel(QProcess::StandardError); proc.start(ffmpegPath.absoluteFilePath(), args, QIODevice::ReadOnly); bool started = proc.waitForStarted(2000); bool finished = false; QCoreApplication::processEvents(); if (started) { finished = proc.waitForFinished(4000); QCoreApplication::processEvents(); } if (started && finished && proc.exitStatus() == QProcess::NormalExit && !proc.exitCode()) { hwlist << codec; } else { QString output = proc.readAll(); foreach (const QString &line, output.split(QRegularExpression("[\r\n]"), Qt::SkipEmptyParts)) LOG_DEBUG() << line; } } if (hwlist.isEmpty()) { MAIN.showStatusMessage(tr("Nothing found"), 10); } else { MAIN.showStatusMessage(tr("Found %1").arg(hwlist.join(", "))); Settings.setEncodeHardware(hwlist); } return !hwlist.isEmpty(); } QString &EncodeDock::defaultFormatExtension() { auto format = ui->formatCombo->currentText(); QFileInfo ffmpegPath(qApp->applicationDirPath(), "ffmpeg"); QProcess proc; QStringList args; args << "-hide_banner" << "-h" << format.prepend("muxer="); LOG_DEBUG() << ffmpegPath.absoluteFilePath() << args.join(' '); proc.setStandardErrorFile(QProcess::nullDevice()); proc.setReadChannel(QProcess::StandardOutput); proc.start(ffmpegPath.absoluteFilePath(), args, QIODevice::ReadOnly); bool started = proc.waitForStarted(2000); bool finished = false; QCoreApplication::processEvents(); if (started) { finished = proc.waitForFinished(4000); QCoreApplication::processEvents(); } if (started && finished && proc.exitStatus() == QProcess::NormalExit && !proc.exitCode()) { QString output = proc.readAll(); for (auto &line : output.split(QRegularExpression("[\r\n]"), Qt::SkipEmptyParts)) { LOG_DEBUG() << line; if (line.startsWith(" Common extensions:")) { auto parts = line.split(':').last().split(','); m_extension = parts.first().replace('.', "").trimmed(); LOG_DEBUG() << "extension =" << m_extension; break; } } } else { LOG_ERROR() << "ffmpeg failed with" << proc.exitCode(); } return m_extension; } void EncodeDock::initSpecialCodecLists() { m_intraOnlyCodecs << "a64multi"; m_intraOnlyCodecs << "a64multi5"; m_intraOnlyCodecs << "alias_pix"; m_intraOnlyCodecs << "amv"; m_intraOnlyCodecs << "apng"; m_intraOnlyCodecs << "asv1"; m_intraOnlyCodecs << "asv2"; m_intraOnlyCodecs << "avrp"; m_intraOnlyCodecs << "avui"; m_intraOnlyCodecs << "ayuv"; m_intraOnlyCodecs << "bitpacked"; m_intraOnlyCodecs << "bmp"; m_intraOnlyCodecs << "cljr"; m_intraOnlyCodecs << "dnxhd"; m_intraOnlyCodecs << "dpx"; m_intraOnlyCodecs << "dvvideo"; m_intraOnlyCodecs << "exr"; m_intraOnlyCodecs << "ffvhuff"; m_intraOnlyCodecs << "fits"; m_intraOnlyCodecs << "gif"; m_intraOnlyCodecs << "hdr"; m_intraOnlyCodecs << "huffyuv"; m_intraOnlyCodecs << "jpeg2000"; m_intraOnlyCodecs << "jpegls"; m_intraOnlyCodecs << "ljpeg"; m_intraOnlyCodecs << "magicyuv"; m_intraOnlyCodecs << "mjpeg"; m_intraOnlyCodecs << "mjpeg_vaapi"; m_intraOnlyCodecs << "pam"; m_intraOnlyCodecs << "pbm"; m_intraOnlyCodecs << "pcx"; m_intraOnlyCodecs << "pfm"; m_intraOnlyCodecs << "pgm"; m_intraOnlyCodecs << "pgmyuv"; m_intraOnlyCodecs << "phm"; m_intraOnlyCodecs << "png"; m_intraOnlyCodecs << "ppm"; m_intraOnlyCodecs << "prores"; m_intraOnlyCodecs << "prores_aw"; m_intraOnlyCodecs << "prores_ks"; m_intraOnlyCodecs << "qoi"; m_intraOnlyCodecs << "r10k"; m_intraOnlyCodecs << "r210"; m_intraOnlyCodecs << "rawvideo"; m_intraOnlyCodecs << "sgi"; m_intraOnlyCodecs << "speedhq"; m_intraOnlyCodecs << "sunrast"; m_intraOnlyCodecs << "targa"; m_intraOnlyCodecs << "tiff"; m_intraOnlyCodecs << "utvideo"; m_intraOnlyCodecs << "v210"; m_intraOnlyCodecs << "v308"; m_intraOnlyCodecs << "v408"; m_intraOnlyCodecs << "v410"; m_intraOnlyCodecs << "wbmp"; m_intraOnlyCodecs << "libwebp_anim"; m_intraOnlyCodecs << "libwebp"; m_intraOnlyCodecs << "xbm"; m_intraOnlyCodecs << "xface"; m_intraOnlyCodecs << "xwd"; m_intraOnlyCodecs << "y41p"; m_intraOnlyCodecs << "yuv4"; m_intraOnlyCodecs << "zlib"; m_losslessVideoCodecs << "alias_pix"; m_losslessVideoCodecs << "apng"; m_losslessVideoCodecs << "avrp"; m_losslessVideoCodecs << "avui"; m_losslessVideoCodecs << "ayuv"; m_losslessVideoCodecs << "bitpacked"; m_losslessVideoCodecs << "bmp"; m_losslessVideoCodecs << "dpx"; m_losslessVideoCodecs << "ffv1"; m_losslessVideoCodecs << "ffvhuff"; m_losslessVideoCodecs << "fits"; m_losslessVideoCodecs << "flashsv"; m_losslessVideoCodecs << "gif"; m_losslessVideoCodecs << "huffyuv"; m_losslessVideoCodecs << "ljpeg"; m_losslessVideoCodecs << "magicyuv"; m_losslessVideoCodecs << "pam"; m_losslessVideoCodecs << "pbm"; m_losslessVideoCodecs << "pcx"; m_losslessVideoCodecs << "pfm"; m_losslessVideoCodecs << "pgm"; m_losslessVideoCodecs << "pgmyuv"; m_losslessVideoCodecs << "phm"; m_losslessVideoCodecs << "png"; m_losslessVideoCodecs << "ppm"; m_losslessVideoCodecs << "qoi"; m_losslessVideoCodecs << "qtrle"; m_losslessVideoCodecs << "r10k"; m_losslessVideoCodecs << "r210"; m_losslessVideoCodecs << "rawvideo"; m_losslessVideoCodecs << "sgi"; m_losslessVideoCodecs << "sunrast"; m_losslessVideoCodecs << "targa"; m_losslessVideoCodecs << "tiff"; m_losslessVideoCodecs << "utvideo"; m_losslessVideoCodecs << "v210"; m_losslessVideoCodecs << "v308"; m_losslessVideoCodecs << "v408"; m_losslessVideoCodecs << "v410"; m_losslessVideoCodecs << "wbmp"; m_losslessVideoCodecs << "wrapped_avframe"; m_losslessVideoCodecs << "xbm"; m_losslessVideoCodecs << "xwd"; m_losslessVideoCodecs << "y41p"; m_losslessVideoCodecs << "yuv4"; m_losslessVideoCodecs << "zlib"; m_losslessVideoCodecs << "zmbv"; m_losslessAudioCodecs << "alac"; m_losslessAudioCodecs << "flac"; m_losslessAudioCodecs << "mlp"; m_losslessAudioCodecs << "pcm_bluray"; m_losslessAudioCodecs << "pcm_dvd"; m_losslessAudioCodecs << "pcm_f32be"; m_losslessAudioCodecs << "pcm_f32le"; m_losslessAudioCodecs << "pcm_f64be"; m_losslessAudioCodecs << "pcm_f64le"; m_losslessAudioCodecs << "pcm_s16be"; m_losslessAudioCodecs << "pcm_s16be_planar"; m_losslessAudioCodecs << "pcm_s16le"; m_losslessAudioCodecs << "pcm_s16le_planar"; m_losslessAudioCodecs << "pcm_s24be"; m_losslessAudioCodecs << "pcm_s24daud"; m_losslessAudioCodecs << "pcm_s24le"; m_losslessAudioCodecs << "pcm_s24le_planar"; m_losslessAudioCodecs << "pcm_s32be"; m_losslessAudioCodecs << "pcm_s32le"; m_losslessAudioCodecs << "pcm_s32le_planar"; m_losslessAudioCodecs << "pcm_s64be"; m_losslessAudioCodecs << "pcm_s64le"; m_losslessAudioCodecs << "pcm_s8"; m_losslessAudioCodecs << "pcm_s8_planar"; m_losslessAudioCodecs << "pcm_u16be"; m_losslessAudioCodecs << "pcm_u16le"; m_losslessAudioCodecs << "pcm_u24be"; m_losslessAudioCodecs << "pcm_u24le"; m_losslessAudioCodecs << "pcm_u32be"; m_losslessAudioCodecs << "pcm_u32le"; m_losslessAudioCodecs << "pcm_u8"; m_losslessAudioCodecs << "s302m"; m_losslessAudioCodecs << "truehd"; m_losslessAudioCodecs << "tta"; } bool EncodeDock::checkForMissingFiles() { Mlt::Producer *service = fromProducer(); if (!service) { service = MAIN.playlist(); } if (!service) { LOG_ERROR() << "Encode: No service to encode"; return true; } QScopedPointer<QTemporaryFile> tmp; if (MAIN.fileName().isEmpty()) { tmp.reset(Util::writableTemporaryFile(QStandardPaths::writableLocation( QStandardPaths::AppDataLocation) + "/")); } else { QFileInfo info(MAIN.fileName()); QString templateFileName = QStringLiteral("%1.XXXXXX").arg(QCoreApplication::applicationName()); tmp.reset(new QTemporaryFile(info.dir().filePath(templateFileName))); } tmp->open(); QString fileName = tmp->fileName(); auto isProxy = ui->previewScaleCheckBox->isChecked() && Settings.proxyEnabled(); MLT.saveXML(fileName, service, false /* without relative paths */, tmp.get(), isProxy); tmp->close(); MltXmlChecker checker; if (checker.check(fileName) != QXmlStreamReader::NoError) { LOG_ERROR() << "Encode: Unable to check XML - skipping check"; } else if (checker.unlinkedFilesModel().rowCount() > 0) { QMessageBox dialog(QMessageBox::Critical, qApp->applicationName(), tr("Your project is missing some files.\n\n" "Save your project, close it, and reopen it.\n" "Shotcut will attempt to repair your project."), QMessageBox::Ok | QMessageBox::Ignore, this); dialog.setWindowModality(QmlApplication::dialogModality()); dialog.setDefaultButton(QMessageBox::Ok); if (QMessageBox::Ignore == dialog.exec()) { return false; } return true; } return false; } void EncodeDock::on_resolutionComboBox_activated(int arg1) { if (ui->resolutionComboBox->itemText(arg1).isEmpty()) return; auto parts = ui->resolutionComboBox->itemText(arg1).split(' '); ui->widthSpinner->setValue(parts[0].toInt()); ui->heightSpinner->setValue(parts[2].toInt()); } void EncodeDock::on_reframeButton_clicked() { Mlt::Filter filter(MLT.profile(), "mask_start"); filter.set(kShotcutFilterProperty, "reframe"); filter.set("filter", "0"); filter.set("transition.valign", "middle"); filter.set("transition.halign", "center"); auto width = qRound(9.0 / 16.0 * MLT.profile().height()); width += width % 2; mlt_rect rect; rect.x = qRound(0.5 * (MLT.profile().width() - width)); rect.y = 0.0; rect.w = width; rect.h = MLT.profile().height(); rect.o = 1.0; filter.set("rect", rect); emit createOrEditFilterOnOutput(&filter); } void EncodeDock::on_aspectNumSpinner_valueChanged(int value) { if (ui->widthSpinner->isEnabled() && double(ui->aspectNumSpinner->value()) / double(ui->aspectDenSpinner->value()) != MLT.profile().dar()) showResampleWarning(tr("Aspect ratio does not match project Video Mode, which causes black bars.")); else hideResampleWarning(); } void EncodeDock::on_aspectDenSpinner_valueChanged(int value) { on_aspectNumSpinner_valueChanged(value); } void EncodeDock::setReframeEnabled(bool enabled) { ui->widthSpinner->setDisabled(enabled); ui->heightSpinner->setDisabled(enabled); ui->resolutionComboBox->setDisabled(enabled); ui->aspectNumSpinner->setDisabled(enabled); ui->aspectDenSpinner->setDisabled(enabled); ui->fpsSpinner->setDisabled(enabled); ui->fpsComboBox->setDisabled(enabled); } void EncodeDock::showResampleWarning(const QString &message) { ui->resampleWarningLabel->setText(message); hideResampleWarning(false); } void EncodeDock::hideResampleWarning(bool hide) { ui->resampleWarningIcon->setVisible(!hide); ui->resampleWarningLabel->setVisible(!hide); } void EncodeDock::checkFrameRate() { if (ui->fromCombo->currentData().toString() != "clip" && qFloor(ui->fpsSpinner->value() * 10000.0) > qFloor(MLT.profile().fps() * 10000.0)) showResampleWarning( tr("Frame rate is higher than project Video Mode, which causes frames to repeat.")); else hideResampleWarning(); }
119,353
C++
.cpp
2,697
33.821283
213
0.577889
mltframework/shotcut
10,796
1,118
50
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
13,134
markersdock.cpp
mltframework_shotcut/src/docks/markersdock.cpp
/* * Copyright (c) 2021-2022 Meltytech, LLC * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "markersdock.h" #include "actions.h" #include "mainwindow.h" #include "models/markersmodel.h" #include "settings.h" #include "widgets/docktoolbar.h" #include "widgets/editmarkerwidget.h" #include "util.h" #include <Logger.h> #include <QAction> #include <QDebug> #include <QHBoxLayout> #include <QHeaderView> #include <QIcon> #include <QLineEdit> #include <QMenu> #include <QMouseEvent> #include <QSortFilterProxyModel> #include <QSpacerItem> #include <QTreeView> #include <QToolButton> #include <QVBoxLayout> #include <QtWidgets/QScrollArea> #include <QStyledItemDelegate> #include <QPainter> class ColorItemDelegate : public QStyledItemDelegate { Q_OBJECT public: ColorItemDelegate(QAbstractItemView *view, QWidget *parent = nullptr) : QStyledItemDelegate(parent) , m_view(view) { } void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { const auto color = index.data(MarkersModel::ColorRole).value<QColor>(); const auto textColor(Util::textColor(color)); painter->fillRect(option.rect, color); const auto point = option.rect.topLeft() + QPoint(2 * m_view->devicePixelRatioF(), option.fontMetrics.ascent() + m_view->devicePixelRatioF()); painter->setPen(textColor); painter->drawText(point, color.name()); } QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const { Q_UNUSED(index); return QSize(m_view->viewport()->width(), option.fontMetrics.height() + 2 * m_view->devicePixelRatioF()); } private: QAbstractItemView *m_view; }; class MarkerTreeView : public QTreeView { Q_OBJECT public: // Make this function public using QTreeView::selectedIndexes; void blockSelectionEvent(bool block) { m_blockSelectionEvent = block; } signals: void rowClicked(const QModelIndex &index); void markerSelected(QModelIndex &index); protected: void selectionChanged(const QItemSelection &selected, const QItemSelection &deselected) { QTreeView::selectionChanged(selected, deselected); if (!m_blockSelectionEvent) { QModelIndex signalIndex; QModelIndexList indices = selectedIndexes(); if (indices.size() > 0) { signalIndex = indices[0]; } emit markerSelected(signalIndex); } } void mouseReleaseEvent(QMouseEvent *event) { QTreeView::mouseReleaseEvent(event); QModelIndex signalIndex = indexAt(event->pos()); if (signalIndex.isValid()) { emit rowClicked(signalIndex); } } private: bool m_blockSelectionEvent = false; }; // Include this so that MarkerTreeView can be declared in the source file. #include "markersdock.moc" MarkersDock::MarkersDock(QWidget *parent) : QDockWidget(parent) , m_model(nullptr) , m_proxyModel(nullptr) , m_editInProgress(false) { LOG_DEBUG() << "begin"; setObjectName("MarkersDock"); QDockWidget::setWindowTitle(tr("Markers")); QIcon filterIcon = QIcon::fromTheme("marker", QIcon(":/icons/oxygen/32x32/actions/marker.png")); setWindowIcon(filterIcon); toggleViewAction()->setIcon(windowIcon()); QScrollArea *scrollArea = new QScrollArea(); scrollArea->setFrameShape(QFrame::NoFrame); scrollArea->setWidgetResizable(true); QDockWidget::setWidget(scrollArea); QVBoxLayout *vboxLayout = new QVBoxLayout(); scrollArea->setLayout(vboxLayout); m_treeView = new MarkerTreeView(); m_treeView->setItemDelegateForColumn(0, new ColorItemDelegate(m_treeView)); m_treeView->setItemsExpandable(false); m_treeView->setRootIsDecorated(false); m_treeView->setUniformRowHeights(true); m_treeView->setSortingEnabled(true); connect(m_treeView, SIGNAL(markerSelected(QModelIndex &)), this, SLOT(onSelectionChanged(QModelIndex &))); connect(m_treeView, SIGNAL(rowClicked(const QModelIndex &)), this, SLOT(onRowClicked(const QModelIndex &))); vboxLayout->addWidget(m_treeView, 1); QMenu *mainMenu = new QMenu("Markers", this); mainMenu->addAction(Actions["timelineMarkerAction"]); mainMenu->addAction(Actions["timelinePrevMarkerAction"]); mainMenu->addAction(Actions["timelineNextMarkerAction"]); mainMenu->addAction(Actions["timelineDeleteMarkerAction"]); mainMenu->addAction(Actions["timelineMarkSelectedClipAction"]); mainMenu->addAction(Actions["timelineCycleMarkerColorAction"]); mainMenu->addAction(tr("Remove All Markers"), this, SLOT(onRemoveAllRequested())); QAction *action; QMenu *columnsMenu = new QMenu(tr("Columns"), this); action = columnsMenu->addAction(tr("Columns")); action->setEnabled(false); action = columnsMenu->addAction(tr("Color"), this, SLOT(onColorColumnToggled(bool))); action->setCheckable(true); action->setChecked(Settings.markersShowColumn("color")); action = columnsMenu->addAction(tr("Name"), this, SLOT(onTextColumnToggled(bool))); action->setCheckable(true); action->setChecked(Settings.markersShowColumn("text")); action = columnsMenu->addAction(tr("Start"), this, SLOT(onStartColumnToggled(bool))); action->setCheckable(true); action->setChecked(Settings.markersShowColumn("start")); action = columnsMenu->addAction(tr("End"), this, SLOT(onEndColumnToggled(bool))); action->setCheckable(true); action->setChecked(Settings.markersShowColumn("end")); action = columnsMenu->addAction(tr("Duration"), this, SLOT(onDurationColumnToggled(bool))); action->setCheckable(true); action->setChecked(Settings.markersShowColumn("duration")); mainMenu->addMenu(columnsMenu); Actions.loadFromMenu(mainMenu); DockToolBar *toolbar = new DockToolBar(tr("Markers Controls")); toolbar->setAreaHint(Qt::BottomToolBarArea); QToolButton *menuButton = new QToolButton(this); menuButton->setIcon(QIcon::fromTheme("show-menu", QIcon(":/icons/oxygen/32x32/actions/show-menu.png"))); menuButton->setToolTip(tr("Markers Menu")); menuButton->setAutoRaise(true); menuButton->setMenu(mainMenu); menuButton->setPopupMode(QToolButton::QToolButton::InstantPopup); toolbar->addWidget(menuButton); m_addButton = new QToolButton(this); m_addButton->setIcon(QIcon::fromTheme("list-add", QIcon(":/icons/oxygen/32x32/actions/list-add.png"))); m_addButton->setToolTip(tr("Add a marker at the current time")); m_addButton->setAutoRaise(true); if (!connect(m_addButton, &QAbstractButton::clicked, this, &MarkersDock::onAddRequested)) connect(m_addButton, SIGNAL(clicked()), SLOT(onAddRequested())); toolbar->addWidget(m_addButton); m_removeButton = new QToolButton(this); m_removeButton->setIcon(QIcon::fromTheme("list-remove", QIcon(":/icons/oxygen/32x32/actions/list-remove.png"))); m_removeButton->setToolTip(tr("Remove the selected marker")); m_removeButton->setAutoRaise(true); if (!connect(m_removeButton, &QAbstractButton::clicked, this, &MarkersDock::onRemoveRequested)) connect(m_removeButton, SIGNAL(clicked()), SLOT(onRemoveRequested())); toolbar->addWidget(m_removeButton); m_clearButton = new QToolButton(this); m_clearButton->setIcon(QIcon::fromTheme("window-close", QIcon(":/icons/oxygen/32x32/actions/window-close.png"))); m_clearButton->setToolTip(tr("Deselect the marker")); m_clearButton->setAutoRaise(true); if (!connect(m_clearButton, &QAbstractButton::clicked, this, &MarkersDock::onClearSelectionRequested)) connect(m_clearButton, SIGNAL(clicked()), SLOT(onClearSelectionRequested())); toolbar->addWidget(m_clearButton); m_searchField = new QLineEdit(this); m_searchField->setPlaceholderText(tr("search")); if (!connect(m_searchField, &QLineEdit::textChanged, this, &MarkersDock::onSearchChanged)) connect(m_searchField, SIGNAL(textChanged(const QString &)), SLOT(onSearchChanged())); toolbar->addWidget(m_searchField); m_clearSearchButton = new QToolButton(this); m_clearSearchButton->setIcon(QIcon::fromTheme("edit-clear", QIcon(":/icons/oxygen/32x32/actions/edit-clear.png"))); m_clearSearchButton->setToolTip(tr("Clear search")); m_clearSearchButton->setAutoRaise(true); if (!connect(m_clearSearchButton, &QAbstractButton::clicked, m_searchField, &QLineEdit::clear)) connect(m_clearSearchButton, SIGNAL(clicked()), m_searchField, SLOT(clear())); toolbar->addWidget(m_clearSearchButton); vboxLayout->addWidget(toolbar); enableButtons(false); m_editMarkerWidget = new EditMarkerWidget(this, "", "", 0, 0, 0); m_editMarkerWidget->setVisible(false); connect(m_editMarkerWidget, SIGNAL(valuesChanged()), SLOT(onValuesChanged())); vboxLayout->addWidget(m_editMarkerWidget); vboxLayout->addStretch(); LOG_DEBUG() << "end"; } MarkersDock::~MarkersDock() { } void MarkersDock::setModel(MarkersModel *model) { m_treeView->blockSelectionEvent(true); m_model = model; m_proxyModel = new QSortFilterProxyModel(this); m_proxyModel->setSourceModel(m_model); m_proxyModel->setFilterKeyColumn(1); m_treeView->setModel(m_proxyModel); m_treeView->setColumnHidden(0, !Settings.markersShowColumn("color")); m_treeView->setColumnHidden(1, !Settings.markersShowColumn("text")); m_treeView->setColumnHidden(2, !Settings.markersShowColumn("start")); m_treeView->setColumnHidden(3, !Settings.markersShowColumn("end")); m_treeView->setColumnHidden(4, !Settings.markersShowColumn("duration")); m_treeView->sortByColumn(Settings.getMarkerSortColumn(), Settings.getMarkerSortOrder()); connect(m_model, SIGNAL(rowsInserted(const QModelIndex &, int, int)), this, SLOT(onRowsInserted(const QModelIndex &, int, int))); connect(m_model, SIGNAL(dataChanged(const QModelIndex &, const QModelIndex &, const QVector<int> &)), this, SLOT(onDataChanged(const QModelIndex &, const QModelIndex &, const QVector<int> &))); connect(m_model, SIGNAL(modelReset()), this, SLOT(onModelReset())); connect(m_treeView->header(), SIGNAL(sortIndicatorChanged(int, Qt::SortOrder)), this, SLOT(onSortIndicatorChanged(int, Qt::SortOrder))); m_treeView->blockSelectionEvent(false); } void MarkersDock::onMarkerSelectionRequest(int markerIndex) { QModelIndex sourceIndex = m_model->modelIndexForRow(markerIndex); QModelIndex insertedIndex = m_proxyModel->mapFromSource(sourceIndex); if (insertedIndex.isValid()) { m_treeView->setCurrentIndex(insertedIndex); } } void MarkersDock::onSelectionChanged(QModelIndex &index) { if (m_model && m_proxyModel && MAIN.multitrack() && index.isValid()) { QModelIndex realIndex = m_proxyModel->mapToSource(index); if (realIndex.isValid()) { Markers::Marker marker = m_model->getMarker(realIndex.row()); enableButtons(true); m_editMarkerWidget->setVisible(true); QSignalBlocker editBlocker(m_editMarkerWidget); m_editMarkerWidget->setValues(marker.text, marker.color, marker.start, marker.end, MAIN.multitrack()->get_length() - 1); return; } } m_editMarkerWidget->setVisible(false); enableButtons(false); } void MarkersDock::onRowClicked(const QModelIndex &index) { if (m_model && m_proxyModel && MAIN.multitrack() && index.isValid()) { QModelIndex realIndex = m_proxyModel->mapToSource(index); if (realIndex.isValid()) { Markers::Marker marker = m_model->getMarker(realIndex.row()); emit seekRequested(marker.start); } } } void MarkersDock::onAddRequested() { emit addRequested(); } void MarkersDock::onRemoveRequested() { if (m_model && m_proxyModel) { QModelIndexList indices = m_treeView->selectedIndexes(); if (indices.size() > 0) { QModelIndex realIndex = m_proxyModel->mapToSource(indices[0]); if (realIndex.isValid()) { m_model->remove(realIndex.row()); } } } } void MarkersDock::onClearSelectionRequested() { m_treeView->clearSelection(); } void MarkersDock::onRemoveAllRequested() { m_model->clear(); } void MarkersDock::onSearchChanged() { if (m_proxyModel) { m_proxyModel->setFilterCaseSensitivity(Qt::CaseInsensitive); m_proxyModel->setFilterFixedString(m_searchField->text()); } } void MarkersDock::onColorColumnToggled(bool checked) { Settings.setMarkersShowColumn("color", checked); m_treeView->setColumnHidden(0, !checked); } void MarkersDock::onTextColumnToggled(bool checked) { Settings.setMarkersShowColumn("text", checked); m_treeView->setColumnHidden(1, !checked); } void MarkersDock::onStartColumnToggled(bool checked) { Settings.setMarkersShowColumn("start", checked); m_treeView->setColumnHidden(2, !checked); } void MarkersDock::onEndColumnToggled(bool checked) { Settings.setMarkersShowColumn("end", checked); m_treeView->setColumnHidden(3, !checked); } void MarkersDock::onDurationColumnToggled(bool checked) { Settings.setMarkersShowColumn("duration", checked); m_treeView->setColumnHidden(4, !checked); } void MarkersDock::onRowsInserted(const QModelIndex &parent, int first, int last) { Q_UNUSED(parent); Q_UNUSED(last); QModelIndex sourceIndex = m_model->modelIndexForRow(first); QModelIndex insertedIndex = m_proxyModel->mapFromSource(sourceIndex); m_treeView->setCurrentIndex(insertedIndex); } void MarkersDock::onDataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight, const QVector<int> &roles) { Q_UNUSED(topLeft); Q_UNUSED(bottomRight); Q_UNUSED(roles); if (m_model && m_proxyModel && !m_editInProgress) { QModelIndexList indices = m_treeView->selectedIndexes(); if (indices.size() > 0) { QModelIndex realIndex = m_proxyModel->mapToSource(indices[0]); if (realIndex.isValid()) { Markers::Marker marker = m_model->getMarker(realIndex.row()); m_editMarkerWidget->setVisible(true); QSignalBlocker editBlocker(m_editMarkerWidget); m_editMarkerWidget->setValues(marker.text, marker.color, marker.start, marker.end, MAIN.multitrack()->get_length() - 1); return; } } } } void MarkersDock::onValuesChanged() { if (m_model && m_proxyModel) { QModelIndexList indices = m_treeView->selectedIndexes(); if (indices.size() > 0) { QModelIndex realIndex = m_proxyModel->mapToSource(indices[0]); if (realIndex.isValid()) { Markers::Marker marker; marker.text = m_editMarkerWidget->getText(); marker.color = m_editMarkerWidget->getColor(); marker.start = m_editMarkerWidget->getStart(); marker.end = m_editMarkerWidget->getEnd(); m_editInProgress = true; m_model->update(realIndex.row(), marker); m_editInProgress = false; } } } } void MarkersDock::onModelReset() { m_treeView->clearSelection(); m_editMarkerWidget->setVisible(false); } void MarkersDock::onSortIndicatorChanged(int logicalIndex, Qt::SortOrder order) { Settings.setMarkerSort(logicalIndex, order); } void MarkersDock::enableButtons(bool enable) { m_removeButton->setEnabled(enable); m_clearButton->setEnabled(enable); }
16,856
C++
.cpp
404
35.069307
130
0.686665
mltframework/shotcut
10,796
1,118
50
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
13,135
timelineitems.cpp
mltframework_shotcut/src/qmltypes/timelineitems.cpp
/* * Copyright (c) 2015-2020 Meltytech, LLC * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "timelineitems.h" #include "mltcontroller.h" #include "settings.h" #include <Logger.h> #include <QQuickPaintedItem> #include <QPainter> #include <QPalette> #include <QPainterPath> #include <QLinearGradient> class TimelineTransition : public QQuickPaintedItem { Q_OBJECT Q_PROPERTY(QColor colorA MEMBER m_colorA NOTIFY propertyChanged) Q_PROPERTY(QColor colorB MEMBER m_colorB NOTIFY propertyChanged) public: TimelineTransition() { setAntialiasing(true); connect(this, SIGNAL(propertyChanged()), this, SLOT(update())); } void paint(QPainter *painter) { QLinearGradient gradient(0, 0, 0, height()); gradient.setColorAt(0, m_colorA); gradient.setColorAt(1, m_colorB); QPainterPath path; path.moveTo(0, 0); path.lineTo(width(), height()); path.lineTo(width(), 0); path.lineTo(0, height()); painter->fillPath(path, gradient); painter->strokePath(path, painter->pen()); } signals: void propertyChanged(); private: QColor m_colorA; QColor m_colorB; }; class TimelinePlayhead : public QQuickPaintedItem { void paint(QPainter *painter) { QPainterPath path; path.moveTo(width(), 0); path.lineTo(width() / 2.0, height()); path.lineTo(0, 0); QPalette p; painter->fillPath(path, p.color(QPalette::WindowText)); } }; class TimelineTriangle : public QQuickPaintedItem { public: TimelineTriangle() { setAntialiasing(true); } void paint(QPainter *painter) { QPainterPath path; path.moveTo(0, 0); path.lineTo(width(), 0); path.lineTo(0, height()); painter->fillPath(path, Qt::black); } }; class TimelineWaveform : public QQuickPaintedItem { Q_OBJECT Q_PROPERTY(QVariant levels MEMBER m_audioLevels NOTIFY propertyChanged) Q_PROPERTY(QColor fillColor MEMBER m_color NOTIFY propertyChanged) Q_PROPERTY(int inPoint MEMBER m_inPoint NOTIFY inPointChanged) Q_PROPERTY(int outPoint MEMBER m_outPoint NOTIFY outPointChanged) Q_PROPERTY(bool active MEMBER m_isActive NOTIFY propertyChanged) public: TimelineWaveform() { setAntialiasing(false); setOpaquePainting(true); if (Settings.timelineFramebufferWaveform()) setRenderTarget(QQuickPaintedItem::FramebufferObject); connect(this, SIGNAL(propertyChanged()), this, SLOT(update())); } void paint(QPainter *painter) { if (!m_isActive) return; QVariantList data = m_audioLevels.toList(); if (data.isEmpty()) return; // In and out points are # frames at current fps, // but audio levels are created at 25 fps. // Scale in and out point to 25 fps. const int inPoint = qRound(m_inPoint / MLT.profile().fps() * 25.0); const int outPoint = qRound(m_outPoint / MLT.profile().fps() * 25.0); const qreal indicesPrPixel = qreal(outPoint - inPoint) / width(); // LOG_DEBUG() << "In/out points" << inPoint << "/" << outPoint; QPainterPath path; path.moveTo(-1, height()); int i = 0; for (; i < width(); ++i) { int idx = inPoint + int(i * indicesPrPixel); if ((idx < 0) || (idx + 2 >= data.length())) break; qreal level = qMax(data.at(idx).toReal(), data.at(idx + 1).toReal()) / 256; path.lineTo(i, height() - level * height()); } path.lineTo(i, height()); painter->fillPath(path, m_color.lighter()); QPen pen(painter->pen()); pen.setColor(m_color.darker()); painter->strokePath(path, pen); } signals: void propertyChanged(); void inPointChanged(); void outPointChanged(); private: QVariant m_audioLevels; int m_inPoint; int m_outPoint; QColor m_color; bool m_isActive {true}; }; class MarkerStart : public QQuickPaintedItem { Q_OBJECT Q_PROPERTY(QColor fillColor MEMBER m_color NOTIFY propertyChanged) public: MarkerStart() { setAntialiasing(true); connect(this, SIGNAL(propertyChanged()), this, SLOT(update())); } void paint(QPainter *painter) { QPainterPath path; path.moveTo(0, 0); path.lineTo(0, 10); path.lineTo(7, 17); path.lineTo(7, 0); path.lineTo(0, 0); painter->fillPath(path, m_color); } signals: void propertyChanged(); private: QColor m_color; }; class MarkerEnd : public QQuickPaintedItem { Q_OBJECT Q_PROPERTY(QColor fillColor MEMBER m_color NOTIFY propertyChanged) public: MarkerEnd() { setAntialiasing(true); connect(this, SIGNAL(propertyChanged()), this, SLOT(update())); } void paint(QPainter *painter) { QPainterPath path; path.moveTo(0, 17); path.lineTo(7, 10); path.lineTo(7, 0); path.lineTo(0, 0); painter->fillPath(path, m_color); } signals: void propertyChanged(); private: QColor m_color; }; void registerTimelineItems() { qmlRegisterType<TimelineTransition>("Shotcut.Controls", 1, 0, "TimelineTransition"); qmlRegisterType<TimelinePlayhead>("Shotcut.Controls", 1, 0, "TimelinePlayhead"); qmlRegisterType<TimelineTriangle>("Shotcut.Controls", 1, 0, "TimelineTriangle"); qmlRegisterType<TimelineWaveform>("Shotcut.Controls", 1, 0, "TimelineWaveform"); qmlRegisterType<MarkerStart>("Shotcut.Controls", 1, 0, "MarkerStart"); qmlRegisterType<MarkerEnd>("Shotcut.Controls", 1, 0, "MarkerEnd"); } #include "timelineitems.moc"
6,381
C++
.cpp
200
26.275
88
0.66
mltframework/shotcut
10,796
1,118
50
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
13,136
colorpickeritem.cpp
mltframework_shotcut/src/qmltypes/colorpickeritem.cpp
/* * Copyright (c) 2014-2022 Meltytech, LLC * Inspiration: KDENLIVE colorpickerwidget.cpp by Till Theato (root@ttill.de) * Inspiration: QColorDialog.cpp * * 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 "colorpickeritem.h" #include <QApplication> #include <QGuiApplication> #include <QImage> #include <QScreen> #include <QTimer> ColorPickerItem::ColorPickerItem(QObject *parent) : QObject(parent) { connect(this, SIGNAL(pickColor()), &m_selector, SLOT(startSelection())); connect(&m_selector, SIGNAL(screenSelected(const QRect &)), this, SLOT(screenSelected(const QRect &))); connect(&m_selector, SIGNAL(cancelled()), SIGNAL(cancelled())); } void ColorPickerItem::screenSelected(const QRect &rect) { m_selectedRect = rect; // Give the frame buffer time to clear the selector window before // grabbing the color. QTimer::singleShot(200, this, SLOT(grabColor())); } void ColorPickerItem::grabColor() { QScreen *screen = QGuiApplication::screenAt(m_selectedRect.topLeft()); QPixmap screenGrab = screen->grabWindow(0, m_selectedRect.x(), m_selectedRect.y(), m_selectedRect.width(), m_selectedRect.height()); QImage image = screenGrab.toImage(); int numPixel = image.width() * image.height(); int sumR = 0; int sumG = 0; int sumB = 0; for (int x = 0; x < image.width(); ++x) { for (int y = 0; y < image.height(); ++y) { QColor color = image.pixel(x, y); sumR += color.red(); sumG += color.green(); sumB += color.blue(); } } QColor avgColor(sumR / numPixel, sumG / numPixel, sumB / numPixel); emit colorPicked(avgColor); }
2,335
C++
.cpp
60
34.25
93
0.684303
mltframework/shotcut
10,796
1,118
50
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
13,137
qmleditmenu.cpp
mltframework_shotcut/src/qmltypes/qmleditmenu.cpp
/* * Copyright (c) 2022 Meltytech, LLC * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "qmleditmenu.h" #include <QMenu> QmlEditMenu::QmlEditMenu(QObject *parent) : QObject(parent) , m_showPastePlain(false) , m_readOnly(false) { } void QmlEditMenu::popup() { QMenu menu; QAction undoAction(tr("Undo")); undoAction.setShortcut(QKeySequence::Undo); connect(&undoAction, &QAction::triggered, this, &QmlEditMenu::undoTriggered); if (!m_readOnly) menu.addAction(&undoAction); QAction redoAction(tr("Redo")); redoAction.setShortcut(QKeySequence::Redo); connect(&redoAction, &QAction::triggered, this, &QmlEditMenu::redoTriggered); if (!m_readOnly) menu.addAction(&redoAction); if (!m_readOnly) menu.addSeparator(); QAction cutAction(tr("Cut")); cutAction.setShortcut(QKeySequence::Cut); connect(&cutAction, &QAction::triggered, this, &QmlEditMenu::cutTriggered); if (!m_readOnly) menu.addAction(&cutAction); QAction copyAction(tr("Copy")); copyAction.setShortcut(QKeySequence::Copy); connect(&copyAction, &QAction::triggered, this, &QmlEditMenu::copyTriggered); menu.addAction(&copyAction); QAction pasteAction(tr("Paste")); pasteAction.setShortcut(QKeySequence::Paste); connect(&pasteAction, &QAction::triggered, this, &QmlEditMenu::pasteTriggered); if (!m_readOnly) menu.addAction(&pasteAction); QAction pastePlainAction(tr("Paste Text Only")); pastePlainAction.setShortcut(QKeySequence(Qt::CTRL | Qt::SHIFT | Qt::Key_V)); connect(&pastePlainAction, &QAction::triggered, this, &QmlEditMenu::pastePlainTriggered); if (m_showPastePlain && !m_readOnly) menu.addAction(&pastePlainAction); QAction deleteAction(tr("Delete")); deleteAction.setShortcut(QKeySequence::Delete); connect(&deleteAction, &QAction::triggered, this, &QmlEditMenu::deleteTriggered); if (!m_readOnly) menu.addAction(&deleteAction); QAction clearAction(tr("Clear")); connect(&clearAction, &QAction::triggered, this, &QmlEditMenu::clearTriggered); if (!m_readOnly) menu.addAction(&clearAction); if (!m_readOnly) menu.addSeparator(); QAction selectAllAction(tr("Select All")); selectAllAction.setShortcut(QKeySequence::SelectAll); connect(&selectAllAction, &QAction::triggered, this, &QmlEditMenu::selectAllTriggered); menu.addAction(&selectAllAction); menu.exec(QCursor::pos()); }
3,112
C++
.cpp
75
36.88
93
0.72327
mltframework/shotcut
10,796
1,118
50
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
13,138
qmlapplication.cpp
mltframework_shotcut/src/qmltypes/qmlapplication.cpp
/* * Copyright (c) 2013-2024 Meltytech, LLC * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "qmlapplication.h" #include "mainwindow.h" #include "mltcontroller.h" #include "controllers/filtercontroller.h" #include "models/attachedfiltersmodel.h" #include "videowidget.h" #include "settings.h" #include "util.h" #include <QApplication> #include <QSysInfo> #include <QCursor> #include <QPalette> #include <QStyle> #include <QFileInfo> #include <QMessageBox> #include <QCheckBox> #include <QClipboard> #ifdef Q_OS_WIN #include <QLocale> #else #include <clocale> #endif #include <limits> QmlApplication &QmlApplication::singleton() { static QmlApplication instance; return instance; } QmlApplication::QmlApplication() : QObject() { } Qt::WindowModality QmlApplication::dialogModality() { #ifdef Q_OS_MAC return Qt::WindowModal; #else return Qt::ApplicationModal; #endif } QPoint QmlApplication::mousePos() { return QCursor::pos(); } QColor QmlApplication::toolTipBaseColor() { #if defined(Q_OS_UNIX) && !defined(Q_OS_MAC) if ("gtk+" == QApplication::style()->objectName()) return QApplication::palette().highlight().color(); #endif return QApplication::palette().toolTipBase().color(); } QColor QmlApplication::toolTipTextColor() { #if defined(Q_OS_UNIX) && !defined(Q_OS_MAC) if ("gtk+" == QApplication::style()->objectName()) return QApplication::palette().highlightedText().color(); #endif return QApplication::palette().toolTipText().color(); } QString QmlApplication::OS() { #if defined(Q_OS_MAC) return "macOS"; #elif defined(Q_OS_LINUX) return "Linux"; #elif defined(Q_OS_UNIX) return "UNIX"; #elif defined(Q_OS_WIN) return "Windows"; #else return ""; #endif } QRect QmlApplication::mainWinRect() { return MAIN.geometry(); } bool QmlApplication::hasFiltersOnClipboard() { return MLT.hasFiltersOnClipboard(); } void QmlApplication::copyFilters() { QScopedPointer<Mlt::Producer> producer(new Mlt::Producer( MAIN.filterController()->attachedModel()->producer())); MLT.copyFilters(producer.data()); QGuiApplication::clipboard()->setText(MLT.filtersClipboardXML()); emit QmlApplication::singleton().filtersCopied(); } void QmlApplication::pasteFilters() { QScopedPointer<Mlt::Producer> producer(new Mlt::Producer( MAIN.filterController()->attachedModel()->producer())); if (confirmOutputFilter()) { QString s = QGuiApplication::clipboard()->text(); if (MLT.isMltXml(s)) { Mlt::Profile profile(kDefaultMltProfile); Mlt::Producer filtersProducer(profile, "xml-string", s.toUtf8().constData()); if (filtersProducer.is_valid() && filtersProducer.filter_count() > 0 && filtersProducer.get_int(kShotcutFiltersClipboard)) { MLT.pasteFilters(producer.get(), &filtersProducer); } else { MLT.pasteFilters(producer.data()); } } else { MLT.pasteFilters(producer.data()); } emit QmlApplication::singleton().filtersPasted( MAIN.filterController()->attachedModel()->producer()); } } QString QmlApplication::clockFromFrames(int frames) { if (MLT.producer()) { return MLT.producer()->frames_to_time(frames, mlt_time_clock); } return QString(); } QString QmlApplication::timeFromFrames(int frames) { if (MLT.producer()) { return MLT.producer()->frames_to_time(frames, Settings.timeFormat()); } return QString(); } int QmlApplication::audioChannels() { return MLT.audioChannels(); } QString QmlApplication::getNextProjectFile(const QString &filename) { QDir dir(MLT.projectFolder()); if (!MLT.projectFolder().isEmpty() && dir.exists()) { QFileInfo info(filename); QString basename = info.completeBaseName(); QString extension = info.suffix(); if (extension.isEmpty()) { extension = basename; basename = QString(); } for (unsigned i = 1; i < std::numeric_limits<unsigned>::max(); i++) { QString filename = QString::fromLatin1("%1%2.%3").arg(basename).arg(i).arg(extension); if (!dir.exists(filename)) return dir.filePath(filename); } } return QString(); } bool QmlApplication::isProjectFolder() { QDir dir(MLT.projectFolder()); return (!MLT.projectFolder().isEmpty() && dir.exists()); } qreal QmlApplication::devicePixelRatio() { return MAIN.devicePixelRatioF(); } void QmlApplication::showStatusMessage(const QString &message, int timeoutSeconds) { MAIN.showStatusMessage(message, timeoutSeconds); } int QmlApplication::maxTextureSize() { auto *videoWidget = qobject_cast<Mlt::VideoWidget *>(MLT.videoWidget()); return videoWidget ? videoWidget->maxTextureSize() : 0; } bool QmlApplication::confirmOutputFilter() { bool result = true; if (MAIN.filterController()->isOutputTrackSelected() && Settings.askOutputFilter()) { QMessageBox dialog(QMessageBox::Warning, qApp->applicationName(), tr("<p>Do you really want to add filters to <b>Output</b>?</p>" "<p><b>Timeline > Output</b> is currently selected. " "Adding filters to <b>Output</b> affects ALL clips in the " "timeline including new ones that will be added.</p>"), QMessageBox::No | QMessageBox::Yes, &MAIN); dialog.setWindowModality(dialogModality()); dialog.setDefaultButton(QMessageBox::No); dialog.setEscapeButton(QMessageBox::Yes); dialog.setCheckBox(new QCheckBox(tr("Do not show this anymore.", "confirm output filters dialog"))); result = dialog.exec() == QMessageBox::Yes; if (dialog.checkBox()->isChecked()) { Settings.setAskOutputFilter(false); } } return result; } QDir QmlApplication::dataDir() { QDir dir(qApp->applicationDirPath()); #if defined(Q_OS_MAC) dir.cdUp(); dir.cd("Resources"); #else #if defined(Q_OS_UNIX) || (defined(Q_OS_WIN) && defined(NODEPLOY)) dir.cdUp(); #endif dir.cd("share"); #endif return dir; } QColor QmlApplication::contrastingColor(QString color) { return Util::textColor(color); } QStringList QmlApplication::wipes() { QStringList result; const auto transitions = QString::fromLatin1("transitions"); QDir dir(Settings.appDataLocation()); if (!dir.exists(transitions)) { dir.mkdir(transitions); } if (dir.cd(transitions)) { for (auto &s : dir.entryList(QDir::Files | QDir::Readable)) { result << dir.filePath(s); } } return result; } bool QmlApplication::addWipe(const QString &filePath) { const auto transitions = QString::fromLatin1("transitions"); QDir dir(Settings.appDataLocation()); if (!dir.exists(transitions)) { dir.mkdir(transitions); } if (dir.cd(transitions)) { return QFile::copy(filePath, dir.filePath(QFileInfo(filePath).fileName())); } return false; } bool QmlApplication::intersects(const QRectF &a, const QRectF &b) { return a.intersects(b); }
7,971
C++
.cpp
254
26.311024
108
0.671564
mltframework/shotcut
10,796
1,118
50
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
13,141
qmlfile.cpp
mltframework_shotcut/src/qmltypes/qmlfile.cpp
/* * Copyright (c) 2014-2022 Meltytech, LLC * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "qmlfile.h" #include <QFileInfo> #include <QFile> #include <QDir> #include <Logger.h> QmlFile::QmlFile(QObject *parent) : QObject(parent) , m_url() { } QString QmlFile::getUrl() { auto s = QUrl::fromPercentEncoding(m_url.toString().toUtf8()); #ifdef Q_OS_WIN if (s.size() > 2 && s[1] == ':' && s[2] == '/') { s[0] = s[0].toUpper(); } #endif return s; } void QmlFile::setUrl(QString text) { QUrl url = text.replace('\\', "/"); QString s = url.toString();; QUrl::FormattingOptions options = QUrl::RemoveScheme | QUrl::RemovePassword | QUrl::RemoveUserInfo | QUrl::RemovePort | QUrl::RemoveAuthority | QUrl::RemoveQuery; if (s.startsWith("file://") && s.size() > 9 && s[9] != ':') { // QUrl removes the host from a UNC path when removing the scheme. options ^= QUrl::RemoveScheme; options ^= QUrl::RemoveAuthority; } #ifdef Q_OS_WIN // If the scheme is a drive letter, do not remove it. if (url.scheme().size() == 1) { options ^= QUrl::RemoveScheme; } #endif s = url.adjusted(options).toString(); #ifdef Q_OS_WIN // If there is a slash before a drive letter. // On Windows, file URLs look like file:///C:/Users/.... // The scheme is removed but only "://" (not 3 slashes) between scheme and path. if (s.size() > 2 && s[0] == '/' && s[2] == ':') { // Remove the leading slash. s = s.mid(1); } #endif if (s.startsWith("file://")) { // UNC path // Remove the scheme. s = s.mid(5); } if (s.startsWith("///")) { // Linux leaves 3 leading slashes sometimes s = s.mid(2); } QUrl adj = s; if (m_url != adj) { m_url = adj; emit urlChanged(m_url); } } QString QmlFile::getFileName() { return QFileInfo(getUrl()).fileName(); } QString QmlFile::getPath() { return QDir::toNativeSeparators(QFileInfo(getUrl()).path()); } QString QmlFile::getFilePath() { return QDir::toNativeSeparators(getUrl()); } void QmlFile::copyFromFile(QString source) { if (QFile::exists(m_url.toString())) { QFile::remove(m_url.toString()); } QFile inFile(source); QFile outfile(m_url.toString()); inFile.open(QFile::ReadOnly); outfile.open(QFile::WriteOnly); outfile.write(inFile.readAll()); outfile.close(); } bool QmlFile::exists() { return QFileInfo(m_url.toString()).exists(); } QString QmlFile::suffix() { return QFileInfo(m_url.toString()).suffix(); } void QmlFile::watch() { m_watcher.reset(new QFileSystemWatcher({getUrl()})); connect(m_watcher.get(), &QFileSystemWatcher::fileChanged, this, &QmlFile::fileChanged); }
3,444
C++
.cpp
119
24.890756
92
0.640545
mltframework/shotcut
10,796
1,118
50
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
13,142
qmlmetadata.cpp
mltframework_shotcut/src/qmltypes/qmlmetadata.cpp
/* * Copyright (c) 2013-2024 Meltytech, LLC * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "qmlmetadata.h" #include "settings.h" #include <Logger.h> #include <QVersionNumber> QmlMetadata::QmlMetadata(QObject *parent) : QObject(parent) , m_type(Filter) , m_needsGPU(false) , m_qmlFileName("") , m_vuiFileName("") , m_isAudio(false) , m_isHidden(false) , m_isFavorite(false) , m_gpuAlt("") , m_allowMultiple(true) , m_isClipOnly(false) , m_isTrackOnly(false) , m_isOutputOnly(false) , m_isGpuCompatible(true) , m_isDeprecated(false) , m_seekReverse(false) { } void QmlMetadata::loadSettings() { //Override the default favorite setting if it has been set by the user. QString favorite = Settings.filterFavorite(uniqueId()); if (favorite == "yes") { m_isFavorite = true; } else if (favorite == "no") { m_isFavorite = false; } } void QmlMetadata::setType(QmlMetadata::PluginType type) { m_type = type; } void QmlMetadata::setName(const QString &name) { m_name = name; emit changed(); } void QmlMetadata::set_mlt_service(const QString &service) { m_mlt_service = service; } QString QmlMetadata::uniqueId() const { if (!objectName().isEmpty()) { return objectName(); } else if (m_type == FilterSet) { return m_name; } else { return mlt_service(); } } void QmlMetadata::setNeedsGPU(bool needs) { m_needsGPU = needs; emit changed(); } void QmlMetadata::setQmlFileName(const QString &fileName) { m_qmlFileName = fileName; } void QmlMetadata::setVuiFileName(const QString &fileName) { m_vuiFileName = fileName; } void QmlMetadata::setPath(const QDir &path) { m_path = path; } QUrl QmlMetadata::qmlFilePath() const { QUrl retVal = QUrl(); if (!m_qmlFileName.isEmpty()) { retVal = QUrl::fromLocalFile(m_path.absoluteFilePath(m_qmlFileName)); } return retVal; } QUrl QmlMetadata::vuiFilePath() const { QUrl retVal = QUrl(); if (!m_vuiFileName.isEmpty()) { retVal = QUrl::fromLocalFile(m_path.absoluteFilePath(m_vuiFileName)); } return retVal; } void QmlMetadata::setIconFileName(const QString &fileName) { m_icon = fileName; } void QmlMetadata::setIsAudio(bool isAudio) { m_isAudio = isAudio; emit changed(); } void QmlMetadata::setIsHidden(bool isHidden) { m_isHidden = isHidden; emit changed(); } void QmlMetadata::setIsFavorite(bool isFavorite) { m_isFavorite = isFavorite; if (!uniqueId().isEmpty()) { if (isFavorite) { Settings.setFilterFavorite(uniqueId(), "yes"); } else { Settings.setFilterFavorite(uniqueId(), "no"); } } emit changed(); } void QmlMetadata::setGpuAlt(const QString &gpuAlt) { m_gpuAlt = gpuAlt; emit changed(); } void QmlMetadata::setAllowMultiple(bool allowMultiple) { m_allowMultiple = allowMultiple; } void QmlMetadata::setIsClipOnly(bool isClipOnly) { m_isClipOnly = isClipOnly; } void QmlMetadata::setIsTrackOnly(bool isTrackOnly) { m_isTrackOnly = isTrackOnly; } void QmlMetadata::setIsOutputOnly(bool isOutputOnly) { m_isOutputOnly = isOutputOnly; } bool QmlMetadata::isMltVersion(const QString &version) { if (!m_minimumVersion.isEmpty()) { LOG_DEBUG() << "MLT version:" << version << "Shotcut minimumVersion:" << m_minimumVersion; if (QVersionNumber::fromString(version) < QVersionNumber::fromString(m_minimumVersion)) return false; } return true; } QmlKeyframesMetadata::QmlKeyframesMetadata(QObject *parent) : QObject(parent) , m_allowTrim(true) , m_allowAnimateIn(false) , m_allowAnimateOut(false) , m_enabled(true) , m_allowOvershoot(true) { } QmlKeyframesParameter *QmlKeyframesMetadata::parameter(const QString &propertyName) const { for (const auto &p : m_parameters) { if (propertyName == p->property()) return p; } return nullptr; } void QmlKeyframesMetadata::checkVersion(const QString &version) { if (!m_minimumVersion.isEmpty()) { LOG_DEBUG() << "MLT version:" << version << "Shotcut minimumVersion:" << m_minimumVersion; if (QVersionNumber::fromString(version) < QVersionNumber::fromString(m_minimumVersion)) setDisabled(); } } void QmlKeyframesMetadata::setDisabled() { m_enabled = m_allowAnimateIn = m_allowAnimateOut = false; } QmlKeyframesParameter::QmlKeyframesParameter(QObject *parent) : QObject(parent) , m_isCurve(false) , m_minimum(0.0) , m_maximum(0.0) , m_units("") , m_isRectangle(false) , m_rangeType(MinMax) , m_isColor(false) { }
5,324
C++
.cpp
201
22.781095
98
0.694739
mltframework/shotcut
10,796
1,118
50
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
13,143
messagedialog.cpp
mltframework_shotcut/src/qmltypes/messagedialog.cpp
/* * Copyright (c) 2023 Meltytech, LLC * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "messagedialog.h" #include "qmlapplication.h" #include <Logger.h> #include <QApplication> MessageDialog::MessageDialog(QObject *parent) : QObject{parent} , m_buttons{0} { } void MessageDialog::open() { QMessageBox dialog; if (m_buttons & QMessageBox::No) { dialog.setIcon(QMessageBox::Question); dialog.setStandardButtons(QMessageBox::StandardButtons(m_buttons)); dialog.setDefaultButton(QMessageBox::Yes); dialog.setEscapeButton(QMessageBox::No); } else if (!m_buttons) { dialog.setIcon(QMessageBox::Information); dialog.setDefaultButton(QMessageBox::Ok); } else { dialog.setStandardButtons(QMessageBox::StandardButtons(m_buttons)); } if (!m_title.isEmpty()) { dialog.setWindowTitle(m_title); } else { dialog.setWindowTitle(QApplication::applicationName()); } dialog.setText(m_text); dialog.setWindowModality(QmlApplication::dialogModality()); auto button = QMessageBox::StandardButton(dialog.exec()); if (QMessageBox::Ok == button || QMessageBox::Yes == button) { emit accepted(); } else { emit rejected(); } } void MessageDialog::setTitle(const QString &title) { if (title != m_title) { m_title = title; emit titleChanged(title); } } void MessageDialog::setText(const QString &text) { if (text != m_text) { m_text = text; emit textChanged(text); } } void MessageDialog::setButtons(int buttons) { if (buttons != m_buttons) { m_buttons = buttons; emit buttonsChanged(buttons); } }
2,396
C++
.cpp
74
26.959459
76
0.67201
mltframework/shotcut
10,796
1,118
50
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
13,145
qmlrichtextmenu.cpp
mltframework_shotcut/src/qmltypes/qmlrichtextmenu.cpp
/* * Copyright (c) 2022 Meltytech, LLC * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "qmlrichtextmenu.h" #include <QMenu> QmlRichTextMenu::QmlRichTextMenu(QObject *parent) : QObject(parent) { } void QmlRichTextMenu::popup() { QMenu menu; QMenu *fileMenu = menu.addMenu(tr("File")); QAction openAction(tr("Open...")); connect(&openAction, &QAction::triggered, this, &QmlRichTextMenu::openTriggered); fileMenu->addAction(&openAction); QAction saveAsAction(tr("Save As...")); connect(&saveAsAction, &QAction::triggered, this, &QmlRichTextMenu::saveAsTriggered); fileMenu->addAction(&saveAsAction); QMenu *editMenu = menu.addMenu(tr("Edit")); QAction undoAction(tr("Undo")); undoAction.setShortcut(QKeySequence::Undo); connect(&undoAction, &QAction::triggered, this, &QmlRichTextMenu::undoTriggered); editMenu->addAction(&undoAction); QAction redoAction(tr("Redo")); redoAction.setShortcut(QKeySequence::Redo); connect(&redoAction, &QAction::triggered, this, &QmlRichTextMenu::redoTriggered); editMenu->addAction(&redoAction); editMenu->addSeparator(); QAction cutAction(tr("Cut")); cutAction.setShortcut(QKeySequence::Cut); connect(&cutAction, &QAction::triggered, this, &QmlRichTextMenu::cutTriggered); editMenu->addAction(&cutAction); QAction copyAction(tr("Copy")); copyAction.setShortcut(QKeySequence::Copy); connect(&copyAction, &QAction::triggered, this, &QmlRichTextMenu::copyTriggered); editMenu->addAction(&copyAction); QAction pasteAction(tr("Paste")); pasteAction.setShortcut(QKeySequence::Paste); connect(&pasteAction, &QAction::triggered, this, &QmlRichTextMenu::pasteTriggered); editMenu->addAction(&pasteAction); QAction pastePlainAction(tr("Paste Text Only")); pastePlainAction.setShortcut(QKeySequence(Qt::CTRL | Qt::SHIFT | Qt::Key_V)); connect(&pastePlainAction, &QAction::triggered, this, &QmlRichTextMenu::pastePlainTriggered); editMenu->addAction(&pastePlainAction); QAction selectAllAction(tr("Select All")); selectAllAction.setShortcut(QKeySequence::SelectAll); connect(&selectAllAction, &QAction::triggered, this, &QmlRichTextMenu::selectAllTriggered); menu.addAction(&selectAllAction); QAction tableAction(tr("Insert Table")); connect(&tableAction, &QAction::triggered, this, &QmlRichTextMenu::insertTableTriggered); menu.addAction(&tableAction); menu.exec(QCursor::pos()); }
3,106
C++
.cpp
67
42.298507
97
0.745118
mltframework/shotcut
10,796
1,118
50
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
13,146
qmlfilter.cpp
mltframework_shotcut/src/qmltypes/qmlfilter.cpp
/* * Copyright (c) 2013-2024 Meltytech, LLC * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "qmlfilter.h" #include "mltcontroller.h" #include "mainwindow.h" #include "commands/filtercommands.h" #include "controllers/filtercontroller.h" #include "jobqueue.h" #include "jobs/encodejob.h" #include "shotcut_mlt_properties.h" #include "settings.h" #include "util.h" #include "proxymanager.h" #include <Logger.h> #include <QDir> #include <QIODevice> #include <QTemporaryFile> #include <QFile> #include <QtXml> #include <QGuiApplication> #include <QClipboard> #include <MltProducer.h> QmlFilter::QmlFilter() : QObject(nullptr) , m_metadata(nullptr) , m_service(mlt_service(nullptr)) , m_producer(mlt_producer(nullptr)) , m_isNew(false) , m_changeInProgress(0) { connect(this, SIGNAL(inChanged(int)), this, SIGNAL(durationChanged())); connect(this, SIGNAL(outChanged(int)), this, SIGNAL(durationChanged())); } QmlFilter::QmlFilter(Mlt::Service &mltService, const QmlMetadata *metadata, QObject *parent) : QObject(parent) , m_metadata(metadata) , m_service(mltService) , m_producer(mlt_producer(nullptr)) , m_path(m_metadata->path().absolutePath().append('/')) , m_isNew(false) , m_changeInProgress(false) { if (m_service.type() == mlt_service_filter_type) { // Every attached filter has a service property that points to the service to which it is attached. m_producer = Mlt::Producer(mlt_producer(m_service.is_valid() ? m_service.get_data("service") : 0)); } else if (m_service.type() == mlt_service_link_type) { // Every attached link has a chain property that points to the chain to which it is attached. m_producer = Mlt::Producer(mlt_producer(m_service.is_valid() ? m_service.get_data("chain") : 0)); } } QmlFilter::~QmlFilter() { } QString QmlFilter::get(QString name, int position) { if (m_service.is_valid()) { if (position < 0) return QString::fromUtf8(m_service.get(qUtf8Printable(name))); else return QString::fromUtf8(m_service.anim_get(qUtf8Printable(name), position, duration())); } else { return QString(); } } QColor QmlFilter::getColor(QString name, int position) { mlt_color color = {0, 0, 0, 0}; if (m_service.is_valid()) { if (position < 0) color = m_service.get_color(qUtf8Printable(name)); else color = m_service.anim_get_color(qUtf8Printable(name), position, duration()); } return QColor(color.r, color.g, color.b, color.a); } double QmlFilter::getDouble(QString name, int position) { if (m_service.is_valid()) { if (position < 0) return m_service.get_double(qUtf8Printable(name)); else return m_service.anim_get_double(qUtf8Printable(name), position, duration()); } else { return 0.0; } } QRectF QmlFilter::getRect(QString name, int position) { if (!m_service.is_valid()) return QRectF(); const char *s = m_service.get(qUtf8Printable(name)); if (s) { mlt_rect rect; if (position < 0) { rect = m_service.get_rect(qUtf8Printable(name)); } else { rect = m_service.anim_get_rect(qUtf8Printable(name), position, duration()); } if (::strchr(s, '%')) { return QRectF(qRound(rect.x * MLT.profile().width()), qRound(rect.y * MLT.profile().height()), qRound(rect.w * MLT.profile().width()), qRound(rect.h * MLT.profile().height())); } else { return QRectF(rect.x, rect.y, rect.w, rect.h); } } else { return QRectF(0.0, 0.0, 0.0, 0.0); } } void QmlFilter::removeRectPercents(QString name) { // This method iterates over each keyframe and converts the percentage values to absolute. if (!m_service.is_valid()) return; const char *s = m_service.get(qUtf8Printable(name)); if (s && ::strchr(s, '%')) { m_service.anim_get_rect(qUtf8Printable(name), 0, duration()); auto anim = m_service.get_anim(qUtf8Printable(name)); if (anim && anim->is_valid()) { mlt_rect rect; for (int i = 0; i < anim->key_count(); ++i) { int position; mlt_keyframe_type keyType; anim->key_get(i, position, keyType); rect = m_service.anim_get_rect(qUtf8Printable(name), position, duration()); auto r = QRectF(qRound(rect.x * MLT.profile().width()), qRound(rect.y * MLT.profile().height()), qRound(rect.w * MLT.profile().width()), qRound(rect.h * MLT.profile().height())); LOG_DEBUG() << r << position; set(name, r.x(), r.y(), r.width(), r.height(), 1.0, position, keyType); LOG_DEBUG() << m_service.get(qUtf8Printable(name)); } } } } QStringList QmlFilter::getGradient(QString name) { QStringList list; for (int i = 1; i <= 10; i++) { QString colorName = name + "." + QString::number(i); const char *value = m_service.get(qUtf8Printable(colorName)); if (value) { list.append(QString::fromUtf8(value)); } else { break; } } return list; } void QmlFilter::set(QString name, QString value, int position) { if (!m_service.is_valid()) return; if (position < 0) { if (qstrcmp(m_service.get(qUtf8Printable(name)), qUtf8Printable(value))) { m_service.set_string(qUtf8Printable(name), qUtf8Printable(value)) ; emit changed(name); updateUndoCommand(name); } } else { // Only set an animation keyframe if it does not already exist with the same value. Mlt::Animation animation(m_service.get_animation(qUtf8Printable(name))); if (!animation.is_valid() || !animation.is_key(position) || value != m_service.anim_get(qUtf8Printable(name), position, duration())) { m_service.anim_set(qUtf8Printable(name), qUtf8Printable(value), position, duration()); emit changed(name); updateUndoCommand(name); } } } void QmlFilter::set(QString name, const QColor &value, int position, mlt_keyframe_type keyframeType) { if (!m_service.is_valid()) return; if (position < 0) { auto mltColor = m_service.get_color(qUtf8Printable(name)); if (!m_service.get(qUtf8Printable(name)) || value != QColor(mltColor.r, mltColor.g, mltColor.b, mltColor.a)) { m_service.set(qUtf8Printable(name), Util::mltColorFromQColor(value)); emit changed(name); updateUndoCommand(name); } } else { // Only set an animation keyframe if it does not already exist with the same value. Mlt::Animation animation(m_service.get_animation(qUtf8Printable(name))); auto mltColor = m_service.anim_get_color(qUtf8Printable(name), position, duration()); if (!animation.is_valid() || !animation.is_key(position) || value != QColor(mltColor.r, mltColor.g, mltColor.b, mltColor.a)) { m_service.anim_set(qUtf8Printable(name), Util::mltColorFromQColor(value), position, duration()); emit changed(name); updateUndoCommand(name); } } } void QmlFilter::set(QString name, double value, int position, mlt_keyframe_type keyframeType) { if (!m_service.is_valid()) return; if (position < 0) { if (!m_service.get(qUtf8Printable(name)) || m_service.get_double(qUtf8Printable(name)) != value) { double delta = value - m_service.get_double(qUtf8Printable(name)); m_service.set(qUtf8Printable(name), value); emit changed(name); if (name == "in") { emit inChanged(delta); } else if (name == "out") { emit outChanged(delta); } updateUndoCommand(name); } } else { // Only set an animation keyframe if it does not already exist with the same value. Mlt::Animation animation(m_service.get_animation(qUtf8Printable(name))); if (!animation.is_valid() || !animation.is_key(position) || value != m_service.anim_get_double(qUtf8Printable(name), position, duration())) { mlt_keyframe_type type = getKeyframeType(animation, position, keyframeType); m_service.anim_set(qUtf8Printable(name), value, position, duration(), type); emit changed(name); updateUndoCommand(name); } } } void QmlFilter::set(QString name, int value, int position, mlt_keyframe_type keyframeType) { if (!m_service.is_valid()) return; if (position < 0) { if (!m_service.get(qUtf8Printable(name)) || m_service.get_int(qUtf8Printable(name)) != value) { int delta = value - m_service.get_int(qUtf8Printable(name)); m_service.set(qUtf8Printable(name), value); emit changed(name); if (name == "in") { emit inChanged(delta); } else if (name == "out") { emit outChanged(delta); } updateUndoCommand(name); } } else { // Only set an animation keyframe if it does not already exist with the same value. Mlt::Animation animation(m_service.get_animation(qUtf8Printable(name))); if (!animation.is_valid() || !animation.is_key(position) || value != m_service.anim_get_int(qUtf8Printable(name), position, duration())) { mlt_keyframe_type type = getKeyframeType(animation, position, keyframeType); m_service.anim_set(qUtf8Printable(name), value, position, duration(), type); emit changed(name); updateUndoCommand(name); } } } void QmlFilter::set(QString name, bool value, int position, mlt_keyframe_type keyframeType) { set(name, value ? 1 : 0, position, keyframeType); } void QmlFilter::set(QString name, double x, double y, double width, double height, double opacity, int position, mlt_keyframe_type keyframeType) { if (!m_service.is_valid()) return; if (position < 0) { mlt_rect rect = m_service.get_rect(qUtf8Printable(name)); if (!m_service.get(qUtf8Printable(name)) || x != rect.x || y != rect.y || width != rect.w || height != rect.h || opacity != rect.o) { m_service.set(qUtf8Printable(name), x, y, width, height, opacity); emit changed(name); updateUndoCommand(name); } } else { mlt_rect rect = m_service.anim_get_rect(qUtf8Printable(name), position, duration()); // Only set an animation keyframe if it does not already exist with the same value. Mlt::Animation animation(m_service.get_animation(qUtf8Printable(name))); if (!animation.is_valid() || !animation.is_key(position) || x != rect.x || y != rect.y || width != rect.w || height != rect.h || opacity != rect.o) { if (animation.key_count() < 1) { // Clear the string value when setting animation for the first time m_service.clear(qUtf8Printable(name)); } rect.x = x; rect.y = y; rect.w = width; rect.h = height; rect.o = opacity; mlt_keyframe_type type = getKeyframeType(animation, position, keyframeType); m_service.anim_set(qUtf8Printable(name), rect, position, duration(), type); emit changed(name); updateUndoCommand(name); } } } void QmlFilter::setGradient(QString name, const QStringList &gradient) { for (int i = 1; i <= 10; i++) { QString colorName = name + "." + QString::number(i); if (i <= gradient.length()) { m_service.set(qUtf8Printable(colorName), qUtf8Printable(gradient[i - 1])); } else { m_service.clear(qUtf8Printable(colorName)); } } emit changed(name.toUtf8().constData()); updateUndoCommand(name); } void QmlFilter::set(QString name, const QRectF &rect, int position, mlt_keyframe_type keyframeType) { set(name, rect.x(), rect.y(), rect.width(), rect.height(), 1.0, position, keyframeType); } void QmlFilter::loadPresets() { m_presets.clear(); QDir dir(Settings.appDataLocation()); if (dir.cd("presets")) { QStringList entries = dir.entryList(QDir::Dirs | QDir::NoDotAndDotDot | QDir::Executable); foreach (QString s, entries) { if (s == objectNameOrService() && dir.cd(s)) { m_presets.append(""); for (auto &s : dir.entryList(QDir::Files | QDir::Readable)) { if (s == QUrl::toPercentEncoding(QUrl::fromPercentEncoding(s.toUtf8()))) m_presets << QUrl::fromPercentEncoding(s.toUtf8()); else m_presets << s; } break; } } } emit presetsChanged(); } int QmlFilter::savePreset(const QStringList &propertyNames, const QString &name) { Mlt::Properties properties; QDir dir(Settings.appDataLocation()); properties.pass_list(m_service, propertyNames.join('\t').toLatin1().constData()); if (!dir.exists()) dir.mkpath(dir.path()); if (!dir.cd("presets")) { if (dir.mkdir("presets")) dir.cd("presets"); } if (!dir.cd(objectNameOrService())) { if (dir.mkdir(objectNameOrService())) dir.cd(objectNameOrService()); } QString preset = name.isEmpty() ? tr("(defaults)") : QString::fromUtf8(QUrl::toPercentEncoding( name)); // Convert properties to YAML string. char *yamlStr = properties.serialise_yaml(); QString yaml = yamlStr; free(yamlStr); // Save YAML to file QFile yamlFile(dir.filePath(preset)); if (!yamlFile.open(QIODevice::WriteOnly)) { LOG_ERROR() << "Failed to save preset: " << dir.filePath(preset); } yamlFile.write(yaml.toUtf8()); yamlFile.close(); loadPresets(); return m_presets.indexOf(name); } void QmlFilter::deletePreset(const QString &name) { QDir dir(Settings.appDataLocation()); if (dir.cd("presets") && dir.cd(objectNameOrService())) { if (!QFile(dir.filePath(QUrl::toPercentEncoding(name))).remove()) QFile(dir.filePath(name)).remove(); } m_presets.removeOne(name); emit presetsChanged(); } void QmlFilter::analyze(bool isAudio, bool deferJob) { // Analyze is only supported for filters, not links. if (m_service.type() != mlt_service_filter_type) return; Mlt::Filter mltFilter(m_service); Mlt::Service service(mlt_service(mltFilter.get_data("service"))); auto in = service.get_int("in"); auto out = service.get_int("out"); // get temp file for input xml QString filename(mltFilter.get("filename")); QScopedPointer<QTemporaryFile> tmp(Util::writableTemporaryFile(filename)); tmp->open(); mltFilter.clear("results"); int disable = mltFilter.get_int("disable"); mltFilter.set("disable", 0); if (!isAudio) mltFilter.set("analyze", 1); // Tag the filter with a UUID stored in a shotcut property to uniquely find it later auto uuid = QUuid::createUuid(); auto ba = uuid.toByteArray(); mltFilter.set(kShotcutHashProperty, ba.constData()); // Fix in/out points of filters on clip-only project. if (MLT.isSeekableClip() && mlt_service_chain_type != MLT.producer()->type()) { Mlt::Producer producer(MLT.profile(), "xml-string", MLT.XML().toUtf8().constData()); service = Mlt::Service(producer); int producerIn = producer.get_in(); if (producerIn > 0) { int n = producer.filter_count(); for (int i = 0; i < n; i++) { Mlt::Filter filter(*producer.filter(i)); if (filter.get_in() > 0) filter.set_in_and_out(filter.get_in() - producerIn, filter.get_out() - producerIn); } } } else { service.set("in", mltFilter.get_in()); service.set("out", mltFilter.get_out()); if (mlt_service_producer_type == service.type()) mltFilter.set_in_and_out(0, mltFilter.get_length() - 1); } // Write the job XML MLT.saveXML(tmp->fileName(), &service, false /* without relative paths */, tmp.data()); tmp->close(); if (!MLT.isSeekableClip()) { service.set("in", in); service.set("out", out); } if (!isAudio) mltFilter.set("analyze", 0); mltFilter.set("disable", disable); // get temp filename for output xml QScopedPointer<QTemporaryFile> tmpTarget(Util::writableTemporaryFile(filename)); tmpTarget->open(); tmpTarget->close(); // parse xml QFile f1(tmp->fileName()); f1.open(QIODevice::ReadOnly); QDomDocument dom(tmp->fileName()); dom.setContent(&f1); f1.close(); // add consumer element QDomElement consumerNode = dom.createElement("consumer"); QDomNodeList profiles = dom.elementsByTagName("profile"); if (profiles.isEmpty()) dom.documentElement().insertAfter(consumerNode, dom.documentElement()); else dom.documentElement().insertAfter(consumerNode, profiles.at(profiles.length() - 1)); consumerNode.setAttribute("mlt_service", "xml"); consumerNode.setAttribute("all", 1); if (isAudio) consumerNode.setAttribute("video_off", 1); else consumerNode.setAttribute("audio_off", 1); consumerNode.setAttribute("resource", tmpTarget->fileName()); AbstractJob *job = new MeltJob(tmpTarget->fileName(), dom.toString(2), MLT.profile().frame_rate_num(), MLT.profile().frame_rate_den()); if (job) { AnalyzeDelegate *delegate = new AnalyzeDelegate(mltFilter); connect(job, &AbstractJob::finished, delegate, &AnalyzeDelegate::onAnalyzeFinished); connect(job, &AbstractJob::finished, this, &QmlFilter::analyzeFinished); job->setLabel(tr("Analyze %1").arg(Util::baseName(ProxyManager::resource(service)))); // Touch the target .stab file. This prevents multiple jobs from trying // to write the same file. if (!filename.isEmpty() && !QFile::exists(filename)) { job->setProperty("filename", filename); QFile file(filename); file.open(QFile::WriteOnly); file.write(""); } if (deferJob) { QTimer::singleShot(0, this, [ = ]() { JOBS.add(job); }); } else { JOBS.add(job); } } } int QmlFilter::framesFromTime(const QString &time) { if (MLT.producer()) { return MLT.producer()->time_to_frames(time.toLatin1().constData()); } return 0; } void QmlFilter::getHash() { if (m_service.is_valid()) Util::getHash(m_service); } int QmlFilter::in() { int result = 0; if (m_service.is_valid()) { if (m_service.type() == mlt_service_link_type || (m_service.get_int("in") == 0 && m_service.get_int("out") == 0)) { // undefined/always-on if (!m_producer.is_valid()) { result = 0; } else if (m_producer.get(kFilterInProperty)) { // Shots on the timeline will set the producer to the cut parent. // However, we want time-based filters such as fade in/out to use // the cut's in/out and not the parent's. result = m_producer.get_int(kFilterInProperty); } else { result = m_producer.get_in(); } } else { result = m_service.get_int("in"); } } return result; } int QmlFilter::out() { int result = 0; if (m_service.is_valid()) { if (m_service.type() == mlt_service_link_type || (m_service.get_int("in") == 0 && m_service.get_int("out") == 0)) { // undefined/always-on if (!m_producer.is_valid()) { result = 0; } else if (m_producer.get(kFilterOutProperty)) { // Shots on the timeline will set the producer to the cut parent. // However, we want time-based filters such as fade in/out to use // the cut's in/out and not the parent's. result = m_producer.get_int(kFilterOutProperty); } else { result = m_producer.get_out(); } } else { result = m_service.get_int("out"); } } return result; } int QmlFilter::animateIn() { return m_service.time_to_frames(m_service.get(kShotcutAnimInProperty)); } void QmlFilter::setAnimateIn(int value) { value = qBound(0, value, duration()); if (value != m_service.time_to_frames(m_service.get(kShotcutAnimInProperty))) { m_service.set(kShotcutAnimInProperty, m_service.frames_to_time(value, mlt_time_clock)); if (value == 0 && m_service.time_to_frames(m_service.get(kShotcutAnimOutProperty)) == 0) { // Clear simple keyframes for (int i = 0; i < m_metadata->keyframes()->parameterCount(); i++) { QString name = m_metadata->keyframes()->parameter(i)->property(); Mlt::Animation anim = getAnimation(name); if (anim.is_valid() && anim.key_count() > 0) { QString value; if (anim.key_count() > 1) { // The second keyframe should be the "middle" simple keyframe. value = m_service.anim_get(qUtf8Printable(name), 1); } else { // Failsafe. This should not happen value = m_service.anim_get(qUtf8Printable(name), 0); } m_service.clear(qUtf8Printable(name)); m_service.set(qUtf8Printable(name), qUtf8Printable(value)); } } } updateUndoCommand(kShotcutAnimInProperty); emit animateInChanged(); } } int QmlFilter::animateOut() { return m_service.time_to_frames(m_service.get(kShotcutAnimOutProperty)); } void QmlFilter::setAnimateOut(int value) { value = qBound(0, value, duration()); if (value != m_service.time_to_frames(m_service.get(kShotcutAnimOutProperty))) { m_service.set(kShotcutAnimOutProperty, m_service.frames_to_time(value, mlt_time_clock)); if (value == 0 && m_service.time_to_frames(m_service.get(kShotcutAnimInProperty)) == 0) { // Clear simple keyframes for (int i = 0; i < m_metadata->keyframes()->parameterCount(); i++) { QString name = m_metadata->keyframes()->parameter(i)->property(); Mlt::Animation anim = getAnimation(name); if (anim.is_valid() && anim.key_count() > 0) { QString value; // The first keyframe value should be the "middle" simple keyframe value = m_service.anim_get(qUtf8Printable(name), 0); m_service.clear(qUtf8Printable(name)); m_service.set(qUtf8Printable(name), qUtf8Printable(value)); } } } updateUndoCommand(kShotcutAnimOutProperty); emit animateOutChanged(); } } void QmlFilter::clearAnimateInOut() { bool inChanged = false; bool outChanged = false; if (0 != m_service.time_to_frames(m_service.get(kShotcutAnimInProperty))) { m_service.set(kShotcutAnimInProperty, m_service.frames_to_time(0, mlt_time_clock)); inChanged = true; } if (0 != m_service.time_to_frames(m_service.get(kShotcutAnimOutProperty))) { m_service.set(kShotcutAnimOutProperty, m_service.frames_to_time(0, mlt_time_clock)); outChanged = true; } if (inChanged) emit animateInChanged(); if (outChanged) emit animateOutChanged(); } int QmlFilter::duration() { return out() - in() + 1; } Mlt::Animation QmlFilter::getAnimation(const QString &name) { if (m_service.is_valid()) { if (!m_service.get_animation(qUtf8Printable(name))) { // Cause a string property to be interpreted as animated value. m_service.anim_get_double(qUtf8Printable(name), 0, duration()); } return m_service.get_animation(qUtf8Printable(name)); } return Mlt::Animation(); } int QmlFilter::keyframeCount(const QString &name) { return getAnimation(name).key_count(); } void QmlFilter::resetProperty(const QString &name) { m_service.clear(qUtf8Printable(name)); emit changed(name.toUtf8().constData()); } void QmlFilter::clearSimpleAnimation(const QString &name) { // Reset the animation if there are no keyframes yet. if (animateIn() <= 0 && animateOut() <= 0 && keyframeCount(name) <= 0) resetProperty(name); setAnimateIn(0); setAnimateOut(0); } void QmlFilter::preset(const QString &name) { if (!m_service.is_valid()) return; QDir dir(Settings.appDataLocation()); if (!dir.cd("presets") || !dir.cd(objectNameOrService())) return; auto fileName = dir.filePath(QUrl::toPercentEncoding(name)); // Detect the preset file format bool isYaml = false; QFile presetFile(fileName); if (presetFile.open(QIODevice::ReadOnly)) { if (presetFile.readLine(4) == "---") { isYaml = true; } presetFile.close(); } else { presetFile.setFileName(dir.filePath(name)); if (presetFile.open(QIODevice::ReadOnly)) { fileName = dir.filePath(name); if (presetFile.readLine(4) == "---") { isYaml = true; } presetFile.close(); } } if (isYaml) { // Load from YAML file. QScopedPointer<Mlt::Properties> properties(Mlt::Properties::parse_yaml(qUtf8Printable(fileName))); if (properties && properties->is_valid()) { QChar decimalPoint = MLT.decimalPoint(); for (int i = 0; i < properties->count(); i++) { QString name(properties->get_name(i)); if (m_metadata->mlt_service() == "dynamictext" && name == "argument") continue; // Convert numeric strings to the current MLT numeric locale. QString value = QString::fromUtf8(properties->get(i)); if (Util::convertDecimalPoints(value, decimalPoint)) properties->set(qUtf8Printable(name), qUtf8Printable(value)); } m_service.inherit(*properties); } } else { // Load from legacy preset file m_service.load(qUtf8Printable(fileName)); } emit changed(); } QString QmlFilter::objectNameOrService() { return m_metadata->objectName().isEmpty() ? m_metadata->mlt_service() : m_metadata->objectName(); } int QmlFilter::keyframeIndex(Mlt::Animation &animation, int position) { int result = -1; if (animation.is_valid()) { for (int i = 0; i < animation.key_count() && result == -1; i++) { int frame = animation.key_get_frame(i); if (frame == position) result = i; else if (frame > position) break; } } return result; } void QmlFilter::startUndoTracking() { m_previousState = Mlt::Properties(); m_previousState.inherit(m_service); if (!m_previousState.property_exists(kShotcutAnimInProperty)) { m_previousState.set(kShotcutAnimInProperty, 0); } if (!m_previousState.property_exists(kShotcutAnimOutProperty)) { m_previousState.set(kShotcutAnimOutProperty, 0); } } void QmlFilter::startUndoParameterCommand(const QString &desc) { if (!m_previousState.count()) { // LOG_DEBUG() << "Undo tracking has not started yet"; return; } m_changeInProgress++; if (m_changeInProgress > 1) { // LOG_DEBUG() << "Nested change command" << m_changeInProgress; return; } auto command = new Filter::UndoParameterCommand(m_metadata->name(), MAIN.filterController(), MAIN.filterController()->currentIndex(), m_previousState, desc); MAIN.undoStack()->push(command); } void QmlFilter::startUndoAddKeyframeCommand() { if (!m_previousState.count()) { // LOG_DEBUG() << "Undo tracking has not started yet"; return; } m_changeInProgress++; if (m_changeInProgress > 1) { // LOG_DEBUG() << "Nested change command" << m_changeInProgress; return; } auto command = new Filter::UndoAddKeyframeCommand(m_metadata->name(), MAIN.filterController(), MAIN.filterController()->currentIndex(), m_previousState); MAIN.undoStack()->push(command); } void QmlFilter::startUndoRemoveKeyframeCommand() { if (!m_previousState.count()) { // LOG_DEBUG() << "Undo tracking has not started yet"; return; } m_changeInProgress++; if (m_changeInProgress > 1) { // LOG_DEBUG() << "Nested change command" << m_changeInProgress; return; } auto command = new Filter::UndoRemoveKeyframeCommand( m_metadata->name(), MAIN.filterController(), MAIN.filterController()->currentIndex(), m_previousState); MAIN.undoStack()->push(command); } void QmlFilter::startUndoModifyKeyframeCommand(int paramIndex, int keyframeIndex) { if (!m_previousState.count()) { // LOG_DEBUG() << "Undo tracking has not started yet"; return; } m_changeInProgress++; if (m_changeInProgress > 1) { // LOG_DEBUG() << "Nested change command" << m_changeInProgress; return; } auto command = new Filter::UndoModifyKeyframeCommand( m_metadata->name(), MAIN.filterController(), MAIN.filterController()->currentIndex(), m_previousState, paramIndex, keyframeIndex); MAIN.undoStack()->push(command); } void QmlFilter::updateUndoCommand(const QString &name) { if (!m_previousState.count()) { // LOG_DEBUG() << "Undo tracking has not started yet"; return; } if (m_changeInProgress) { const QUndoCommand *lastCommand = MAIN.undoStack()->command(MAIN.undoStack()->count() - 1); Filter::UndoParameterCommand *command = dynamic_cast<Filter::UndoParameterCommand *> (const_cast<QUndoCommand *>(lastCommand)); if (command) { // Update the change that is already in progress command->update(name); } else { LOG_ERROR() << "Unable to find command in progress"; return; } } else { // Nothing in progress... make a generic command for this update auto command = new Filter::UndoParameterCommand(m_metadata->name(), MAIN.filterController(), MAIN.filterController()->currentIndex(), m_previousState); MAIN.undoStack()->push(command); } m_previousState.pass_property(m_service, name.toUtf8().constData()); } void QmlFilter::endUndoCommand() { if (!m_previousState.count()) { // LOG_DEBUG() << "Undo tracking has not started yet"; return; } if (!m_changeInProgress) { LOG_ERROR() << "Change is not in progress"; return; } m_changeInProgress--; } mlt_keyframe_type QmlFilter::getKeyframeType(Mlt::Animation &animation, int position, mlt_keyframe_type defaultType) { mlt_keyframe_type result = mlt_keyframe_linear; if (animation.is_valid()) { mlt_keyframe_type existingType = defaultType; if (animation.is_key(position)) { existingType = animation.key_get_type(keyframeIndex(animation, position)); } else if (defaultType < 0) { int previous = 0; bool error = animation.previous_key(position, previous); if (!error) existingType = animation.keyframe_type(previous); } if (existingType >= 0) result = existingType; } return result; } int QmlFilter::getNextKeyframePosition(const QString &name, int position) { int result = -1; Mlt::Animation animation = getAnimation(name); if (animation.is_valid()) { animation.next_key(animation.is_key(position) ? position + 1 : position, result); } return result; } int QmlFilter::getPrevKeyframePosition(const QString &name, int position) { int result = -1; Mlt::Animation animation = getAnimation(name); if (animation.is_valid()) { animation.previous_key(animation.is_key(position) ? position - 1 : position, result); } return result; } bool QmlFilter::isAtLeastVersion(const QString &version) { QVersionNumber v1 = QVersionNumber::fromString(version); QVersionNumber v2 = QVersionNumber::fromString(m_metadata->property("version").toString()); return v2 >= v1; } void QmlFilter::deselect() { MAIN.filterController()->setCurrentFilter(DeselectCurrentFilter); } bool QmlFilter::allowTrim() const { if (m_metadata && m_metadata->keyframes()) return m_metadata->keyframes()->allowTrim(); return false; } bool QmlFilter::allowAnimateIn() const { if (m_metadata && m_metadata->keyframes()) return m_metadata->keyframes()->allowAnimateIn(); return false; } bool QmlFilter::allowAnimateOut() const { if (m_metadata && m_metadata->keyframes()) return m_metadata->keyframes()->allowAnimateOut(); return false; } void QmlFilter::copyParameters() { auto name = "color"; Mlt::Producer dummy(MLT.profile(), name); dummy.inherit(m_service); dummy.set("mlt_service", name); QGuiApplication::clipboard()->setText(MLT.XML(&dummy)); } void QmlFilter::pasteParameters(const QStringList &propertyNames) { auto xml = QGuiApplication::clipboard()->text(); Mlt::Producer producer(MLT.profile(), "xml-string", xml.toUtf8().constData()); if (!producer.is_valid()) { LOG_WARNING() << "failed to parse MLT XML on clipboard" << xml; return; } auto isChanged = false; for (const auto &name : propertyNames) { if (producer.property_exists(name.toUtf8().constData())) { LOG_DEBUG() << name << "=" << producer.get(name.toUtf8().constData()); m_service.pass_property(producer, name.toUtf8().constData()); isChanged = true; emit changed(name); } } if (isChanged) emit changed(); } void QmlFilter::crop(const QRectF &rect) { MAIN.cropSource(rect); } AnalyzeDelegate::AnalyzeDelegate(Mlt::Filter &filter) : QObject(nullptr) , m_uuid(filter.get(kShotcutHashProperty)) { } class FindFilterParser : public Mlt::Parser { private: QUuid m_uuid; QList<Mlt::Filter> m_filters; public: FindFilterParser(QUuid uuid) : Mlt::Parser() , m_uuid(uuid) {} QList<Mlt::Filter> &filters() { return m_filters; } int on_start_filter(Mlt::Filter *filter) { QByteArray uuid = filter->get(kShotcutHashProperty); if (uuid == m_uuid.toByteArray()) m_filters << Mlt::Filter(*filter); return 0; } int on_start_producer(Mlt::Producer *) { return 0; } int on_end_producer(Mlt::Producer *) { return 0; } int on_start_playlist(Mlt::Playlist *) { return 0; } int on_end_playlist(Mlt::Playlist *) { return 0; } int on_start_tractor(Mlt::Tractor *) { return 0; } int on_end_tractor(Mlt::Tractor *) { return 0; } int on_start_multitrack(Mlt::Multitrack *) { return 0; } int on_end_multitrack(Mlt::Multitrack *) { return 0; } int on_start_track() { return 0; } int on_end_track() { return 0; } int on_end_filter(Mlt::Filter *) { return 0; } int on_start_transition(Mlt::Transition *) { return 0; } int on_end_transition(Mlt::Transition *) { return 0; } int on_start_chain(Mlt::Chain *) { return 0; } int on_end_chain(Mlt::Chain *) { return 0; } int on_start_link(Mlt::Link *) { return 0; } int on_end_link(Mlt::Link *) { return 0; } }; void AnalyzeDelegate::updateJob(EncodeJob *job, const QString &results) { bool isUpdated = false; // parse the xml QFile file(job->xmlPath()); file.open(QIODevice::ReadOnly); QDomDocument dom(job->xmlPath()); dom.setContent(&file); file.close(); // look for the matching filter elements QDomNodeList filters = dom.elementsByTagName("filter"); for (int i = 0; i < filters.size(); i++) { QDomNode filterNode = filters.at(i); bool found = false; QDomNodeList properties = filterNode.toElement().elementsByTagName("property"); for (int j = 0; j < properties.size(); j++) { QDomNode propertyNode = properties.at(j); if (propertyNode.attributes().namedItem("name").toAttr().value() == kShotcutHashProperty && propertyNode.toElement().text() == m_uuid.toString()) { // found a matching filter found = true; break; } } if (found) { // remove existing results if any for (int j = 0; j < properties.size(); j++) { QDomNode propertyNode = properties.at(j); if (propertyNode.attributes().namedItem("name").toAttr().value() == "results") { filterNode.removeChild(propertyNode); break; } } // add the results QDomText textNode = dom.createTextNode(results); QDomElement propertyNode = dom.createElement("property"); propertyNode.setAttribute("name", "results"); propertyNode.appendChild(textNode); filterNode.appendChild(propertyNode); isUpdated = true; LOG_INFO() << "updated pending job" << job->label() << "with results:" << results; } } if (isUpdated) { // Save the new XML. file.open(QIODevice::WriteOnly); QTextStream textStream(&file); dom.save(textStream, 2); file.close(); } } void AnalyzeDelegate::onAnalyzeFinished(AbstractJob *job, bool isSuccess) { QString fileName = job->objectName(); if (isSuccess) { QString results = resultsFromXml(fileName); if (!results.isEmpty()) { // look for filters by UUID in each pending export job. foreach (AbstractJob *job, JOBS.jobs()) { if (!job->ran() && typeid(*job) == typeid(EncodeJob)) { updateJob(dynamic_cast<EncodeJob *>(job), results); } } // Locate filters in memory by UUID. if (MAIN.isMultitrackValid()) { FindFilterParser graphParser(m_uuid); graphParser.start(*MAIN.multitrack()); foreach (Mlt::Filter filter, graphParser.filters()) updateFilter(filter, results); } if (MAIN.playlist() && MAIN.playlist()->count() > 0) { FindFilterParser graphParser(m_uuid); graphParser.start(*MAIN.playlist()); foreach (Mlt::Filter filter, graphParser.filters()) updateFilter(filter, results); } Mlt::Producer producer(MLT.isClip() ? MLT.producer() : MLT.savedProducer()); if (producer.is_valid()) { FindFilterParser graphParser(m_uuid); graphParser.start(producer); foreach (Mlt::Filter filter, graphParser.filters()) updateFilter(filter, results); } emit MAIN.filterController()->attachedModel()->changed(); } } else if (!job->property("filename").isNull()) { QFile file(job->property("filename").toString()); if (file.exists() && file.size() == 0) file.remove(); } QFile::remove(fileName); deleteLater(); } QString AnalyzeDelegate::resultsFromXml(const QString &fileName) { // parse the xml QFile file(fileName); file.open(QIODevice::ReadOnly); QDomDocument dom(fileName); dom.setContent(&file); file.close(); QDomNodeList filters = dom.elementsByTagName("filter"); for (int i = 0; i < filters.size(); i++) { QDomNode filterNode = filters.at(i); bool found = false; QDomNodeList properties = filterNode.toElement().elementsByTagName("property"); for (int j = 0; j < properties.size(); j++) { QDomNode propertyNode = properties.at(j); if (propertyNode.attributes().namedItem("name").toAttr().value() == kShotcutHashProperty && propertyNode.toElement().text() == m_uuid.toString()) { found = true; break; } } if (found) { for (int j = 0; j < properties.size(); j++) { QDomNode propertyNode = properties.at(j); if (propertyNode.attributes().namedItem("name").toAttr().value() == "results") { return propertyNode.toElement().text(); } } break; } } return QString(); } void AnalyzeDelegate::updateFilter(Mlt::Filter &filter, const QString &results) { filter.set("results", qUtf8Printable(results)); filter.set("reload", 1); filter.clear(kShotcutHashProperty); LOG_INFO() << "updated filter" << filter.get("mlt_service") << "with results:" << results; if (QString::fromLatin1("opencv.tracker") == filter.get("mlt_service")) { auto model = MAIN.filterController()->motionTrackerModel(); if (model) { auto name = QString::fromUtf8(filter.get(kTrackNameProperty)); if (name.isEmpty()) { name = model->nextName(); filter.set(kTrackNameProperty, name.toUtf8().constData()); } auto key = model->keyForFilter(&filter); if (key.isEmpty()) { key = model->add(name, results); if (!key.isEmpty()) { filter.set(kUuidProperty, key.toUtf8().constData()); } } else { model->updateData(key, results); } } } }
43,712
C++
.cpp
1,158
29.682211
141
0.601347
mltframework/shotcut
10,796
1,118
50
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false