Merge branch 'master' into ocio_node

This commit is contained in:
Thomas Wilshaw
2022-05-03 18:54:02 +01:00
218 changed files with 5015 additions and 2165 deletions
+6 -6
View File
@@ -406,7 +406,7 @@ void CurveView::FirstChanceMouseRelease(QMouseEvent *event)
void CurveView::KeyframeDragStart(QMouseEvent *event)
{
drag_keyframe_values_.resize(GetSelectedKeyframes().size());
for (int i=0; i<GetSelectedKeyframes().size(); i++) {
for (size_t i=0; i<GetSelectedKeyframes().size(); i++) {
NodeKeyframe *key = GetSelectedKeyframes().at(i);
drag_keyframe_values_[i] = key->value();
}
@@ -418,7 +418,7 @@ void CurveView::KeyframeDragMove(QMouseEvent *event, QString &tip)
{
if (event->modifiers() & Qt::ShiftModifier) {
// Lock to X axis only and set original values on all keys
for (int i=0; i<GetSelectedKeyframes().size(); i++) {
for (size_t i=0; i<GetSelectedKeyframes().size(); i++) {
NodeKeyframe *key = GetSelectedKeyframes().at(i);
key->set_value(drag_keyframe_values_.at(i));
}
@@ -429,7 +429,7 @@ void CurveView::KeyframeDragMove(QMouseEvent *event, QString &tip)
double scaled_diff = (mapToScene(event->pos()).y() - drag_start_.y()) / GetYScale();
// Validate movement - ensure no keyframe goes above its max point or below its min point
for (int i=0; i<GetSelectedKeyframes().size(); i++) {
for (size_t i=0; i<GetSelectedKeyframes().size(); i++) {
NodeKeyframe *key = GetSelectedKeyframes().at(i);
FloatSlider::DisplayType display = GetFloatDisplayTypeFromKeyframe(key);
@@ -453,13 +453,13 @@ void CurveView::KeyframeDragMove(QMouseEvent *event, QString &tip)
}
// Set values
for (int i=0; i<GetSelectedKeyframes().size(); i++) {
for (size_t i=0; i<GetSelectedKeyframes().size(); i++) {
NodeKeyframe *key = GetSelectedKeyframes().at(i);
FloatSlider::DisplayType display = GetFloatDisplayTypeFromKeyframe(key);
key->set_value(FloatSlider::TransformDisplayToValue(FloatSlider::TransformValueToDisplay(drag_keyframe_values_.at(i).toDouble(), display) - scaled_diff, display));
}
NodeKeyframe *tip_item = GetSelectedKeyframes().first();
NodeKeyframe *tip_item = GetSelectedKeyframes().front();
bool ok;
double num_value = tip_item->value().toDouble(&ok);
@@ -472,7 +472,7 @@ void CurveView::KeyframeDragMove(QMouseEvent *event, QString &tip)
void CurveView::KeyframeDragRelease(QMouseEvent *event, MultiUndoCommand *command)
{
for (int i=0; i<GetSelectedKeyframes().size(); i++) {
for (size_t i=0; i<GetSelectedKeyframes().size(); i++) {
NodeKeyframe *k = GetSelectedKeyframes().at(i);
if (!qFuzzyCompare(k->value().toDouble(), drag_keyframe_values_.at(i).toDouble())) {
command->add_child(new NodeParamSetKeyframeValueCommand(k, k->value(), drag_keyframe_values_.at(i)));
+9 -7
View File
@@ -31,6 +31,7 @@
#include "common/timecodefunctions.h"
#include "node/node.h"
#include "widget/keyframeview/keyframeviewundo.h"
#include "widget/timeruler/timeruler.h"
namespace olive {
@@ -92,6 +93,7 @@ CurveWidget::CurveWidget(QWidget *parent) :
view_ = new CurveView();
ConnectTimelineView(view_);
view_->SetSnapService(this);
ruler_view_layout->addWidget(view_);
layout->addLayout(ruler_view_layout);
@@ -251,16 +253,16 @@ void CurveWidget::ConnectInputInternal(Node *node, const QString &input, int ele
void CurveWidget::SelectionChanged()
{
const QVector<NodeKeyframe*> &selected = view_->GetSelectedKeyframes();
const std::vector<NodeKeyframe*> &selected = view_->GetSelectedKeyframes();
SetKeyframeButtonChecked(false);
SetKeyframeButtonEnabled(!selected.isEmpty());
SetKeyframeButtonEnabled(!selected.empty());
if (!selected.isEmpty()) {
if (!selected.empty()) {
bool all_same_type = true;
NodeKeyframe::Type type = selected.first()->type();
NodeKeyframe::Type type = selected.front()->type();
for (int i=1;i<selected.size();i++) {
for (size_t i=1;i<selected.size();i++) {
NodeKeyframe* prev_item = selected.at(i-1);
NodeKeyframe* this_item = selected.at(i);
@@ -287,8 +289,8 @@ void CurveWidget::KeyframeTypeButtonTriggered(bool checked)
}
// Get selected items and do nothing if there are none
const QVector<NodeKeyframe*> &selected = view_->GetSelectedKeyframes();
if (selected.isEmpty()) {
const std::vector<NodeKeyframe*> &selected = view_->GetSelectedKeyframes();
if (selected.empty()) {
return;
}
+10
View File
@@ -67,6 +67,16 @@ protected:
virtual void ConnectedNodeChangeEvent(ViewerOutput* n) override;
virtual const QVector<KeyframeViewInputConnection*> *GetSnapKeyframes() const override
{
return &view_->GetKeyframeTracks();
}
virtual const std::vector<NodeKeyframe*> *GetSnapIgnoreKeyframes() const override
{
return &view_->GetSelectedKeyframes();
}
private:
void SetKeyframeButtonEnabled(bool enable);
+5 -5
View File
@@ -462,11 +462,11 @@ void KeyframeView::ShowContextMenu()
QAction* bezier_key_action = nullptr;
QAction* hold_key_action = nullptr;
if (!GetSelectedKeyframes().isEmpty()) {
if (!GetSelectedKeyframes().empty()) {
bool all_keys_are_same_type = true;
NodeKeyframe::Type type = GetSelectedKeyframes().first()->type();
NodeKeyframe::Type type = GetSelectedKeyframes().front()->type();
for (int i=1;i<GetSelectedKeyframes().size();i++) {
for (size_t i=1;i<GetSelectedKeyframes().size();i++) {
NodeKeyframe* key_item = GetSelectedKeyframes().at(i);
NodeKeyframe* prev_item = GetSelectedKeyframes().at(i-1);
@@ -507,7 +507,7 @@ void KeyframeView::ShowContextMenu()
ContextMenuEvent(m);
if (!GetSelectedKeyframes().isEmpty()) {
if (!GetSelectedKeyframes().empty()) {
m.addSeparator();
QAction* properties_action = m.addAction(tr("P&roperties"));
@@ -542,7 +542,7 @@ void KeyframeView::ShowContextMenu()
void KeyframeView::ShowKeyframePropertiesDialog()
{
if (!GetSelectedKeyframes().isEmpty()) {
if (!GetSelectedKeyframes().empty()) {
KeyframePropertiesDialog kd(GetSelectedKeyframes(), timebase(), this);
kd.exec();
}
+6 -1
View File
@@ -58,11 +58,16 @@ public:
void Clear();
const QVector<NodeKeyframe*> &GetSelectedKeyframes() const
const std::vector<NodeKeyframe*> &GetSelectedKeyframes() const
{
return selection_manager_.GetSelectedObjects();
}
const QVector<KeyframeViewInputConnection*> &GetKeyframeTracks() const
{
return tracks_;
}
virtual void SelectionManagerSelectEvent(void *obj) override;
virtual void SelectionManagerDeselectEvent(void *obj) override;
@@ -50,7 +50,7 @@ public:
void SetYBehavior(YBehavior e);
const QVector<NodeKeyframe*> GetKeyframes() const
const QVector<NodeKeyframe*> &GetKeyframes() const
{
return input_.input().node()->GetKeyframeTracks(input_.input()).at(input_.track());
}
+37 -23
View File
@@ -28,6 +28,8 @@
#include "common/functiontimer.h"
#include "common/timecodefunctions.h"
#include "node/output/viewer/viewer.h"
#include "widget/nodeview/nodeviewundo.h"
#include "widget/timeruler/timeruler.h"
namespace olive {
@@ -116,6 +118,7 @@ NodeParamView::NodeParamView(bool create_keyframe_view, QWidget *parent) :
// Create keyframe view
keyframe_view_ = new KeyframeView();
keyframe_view_->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
keyframe_view_->SetSnapService(this);
ConnectTimelineView(keyframe_view_);
keyframe_area_layout->addWidget(keyframe_view_);
@@ -283,6 +286,16 @@ void NodeParamView::UpdateContexts()
void NodeParamView::ItemAboutToBeRemoved(NodeParamViewItem *item)
{
if (keyframe_view_) {
for (auto it=item->GetKeyframeConnections().begin(); it!=item->GetKeyframeConnections().end(); it++) {
for (auto jt=it->begin(); jt!=it->end(); jt++) {
for (auto kt=jt->begin(); kt!=jt->end(); kt++) {
keyframe_view_->RemoveKeyframesOfTrack(*kt);
}
}
}
}
if (focused_node_ == item) {
focused_node_ = nullptr;
emit FocusedNodeChanged(nullptr);
@@ -359,8 +372,28 @@ Node *NodeParamView::GetTimeTarget() const
void NodeParamView::DeleteSelected()
{
if (keyframe_view_) {
if (keyframe_view_ && keyframe_view_->hasFocus()) {
keyframe_view_->DeleteSelected();
} else if (focused_node_) {
MultiUndoCommand *c = new MultiUndoCommand();
Node *n = focused_node_->GetNode();
// Create command to delete node from context and/or graph
NodeViewDeleteCommand *dc = new NodeViewDeleteCommand();
dc->AddNode(n, focused_node_->GetContext());
c->add_child(dc);
// Copy any outputs that were connected
if (n->GetEffectInput().IsValid()) {
if (Node *out = n->GetEffectInput().GetConnectedOutput()) {
for (auto it=n->output_connections().cbegin(); it!=n->output_connections().cend(); it++) {
c->add_child(new NodeEdgeAddCommand(out, it->second));
}
}
}
Core::instance()->undo_stack()->push(c);
}
}
@@ -455,27 +488,6 @@ void NodeParamView::AddNode(Node *n, Node *ctx, NodeParamViewContext *context)
}
}
void NodeParamView::RemoveNode(Node *n, Node *ctx)
{
foreach (NodeParamViewContext *ctx_item, context_items_) {
NodeParamViewItem *item = ctx_item->GetItem(n, ctx);
if (item) {
if (keyframe_view_) {
for (auto it=item->GetKeyframeConnections().begin(); it!=item->GetKeyframeConnections().end(); it++) {
for (auto jt=it->begin(); jt!=it->end(); jt++) {
for (auto kt=jt->begin(); kt!=jt->end(); kt++) {
keyframe_view_->RemoveKeyframesOfTrack(*kt);
}
}
}
}
}
ctx_item->RemoveNode(n, ctx);
}
}
int GetDistanceBetweenNodes(Node *start, Node *end)
{
if (start == end) {
@@ -675,7 +687,9 @@ void NodeParamView::NodeRemovedFromContext(Node *n)
{
Node *ctx = static_cast<Node*>(sender());
RemoveNode(n, ctx);
foreach (NodeParamViewContext *ctx_item, context_items_) {
ctx_item->RemoveNode(n, ctx);
}
if (keyframe_view_) {
QueueKeyframePositionUpdate();
+10 -2
View File
@@ -88,6 +88,16 @@ protected:
virtual void ConnectedNodeChangeEvent(ViewerOutput* n) override;
virtual const QVector<KeyframeViewInputConnection*> *GetSnapKeyframes() const override
{
return keyframe_view_ ? &keyframe_view_->GetKeyframeTracks() : nullptr;
}
virtual const std::vector<NodeKeyframe*> *GetSnapIgnoreKeyframes() const override
{
return keyframe_view_ ? &keyframe_view_->GetSelectedKeyframes() : nullptr;
}
private:
void UpdateItemTime(const rational &time);
@@ -99,8 +109,6 @@ private:
void AddNode(Node* n, Node *ctx, NodeParamViewContext *context);
void RemoveNode(Node *n, Node *ctx);
void SortItemsInContext(NodeParamViewContext *context);
NodeParamViewContext *GetContextItemFromContext(Node *context);
@@ -23,6 +23,8 @@
#include <QMessageBox>
#include "node/block/clip/clip.h"
#include "node/factory.h"
#include "widget/nodeview/nodeviewundo.h"
namespace olive {
@@ -130,7 +132,45 @@ void NodeParamViewContext::Retranslate()
void NodeParamViewContext::AddEffectButtonClicked()
{
QMessageBox::information(this, tr("STUB"), tr("This feature is coming soon. Thanks for testing development builds of Olive :)"));
Menu *m = NodeFactory::CreateMenu(this, false, Node::kCategoryUnknown, Node::kVideoEffect);
connect(m, &Menu::triggered, this, &NodeParamViewContext::AddEffectMenuItemTriggered);
m->exec(QCursor::pos());
delete m;
}
void NodeParamViewContext::AddEffectMenuItemTriggered(QAction *a)
{
Node *n = NodeFactory::CreateFromMenuAction(a);
if (n) {
NodeInput new_node_input = n->GetEffectInput();
MultiUndoCommand *command = new MultiUndoCommand();
QVector<NodeGraph*> graphs_added_to;
foreach (Node *ctx, contexts_) {
NodeInput ctx_input = ctx->GetEffectInput();
if (!graphs_added_to.contains(ctx->parent())) {
command->add_child(new NodeAddCommand(ctx->parent(), n));
graphs_added_to.append(ctx->parent());
}
command->add_child(new NodeSetPositionCommand(n, ctx, ctx->GetNodePositionInContext(ctx)));
command->add_child(new NodeSetPositionCommand(ctx, ctx, ctx->GetNodePositionInContext(ctx) + QPointF(1, 0)));
if (ctx_input.IsConnected()) {
Node *prev_output = ctx_input.GetConnectedOutput();
command->add_child(new NodeEdgeRemoveCommand(prev_output, ctx_input));
command->add_child(new NodeEdgeAddCommand(prev_output, new_node_input));
}
command->add_child(new NodeEdgeAddCommand(n, ctx_input));
}
Core::instance()->undo_stack()->pushIfHasChildren(command);
}
}
}
@@ -91,6 +91,8 @@ private:
private slots:
void AddEffectButtonClicked();
void AddEffectMenuItemTriggered(QAction *a);
};
}
@@ -63,6 +63,11 @@ NodeParamViewItem::NodeParamViewItem(Node *node, NodeParamViewCheckBoxBehavior c
setBackgroundRole(QPalette::Window);
// Connect title bar enabled checkbox
//title_bar()->SetEnabledCheckBoxVisible(true);
//title_bar()->SetEnabledCheckBoxChecked(node_->IsEnabled());
//connect(title_bar(), &NodeParamViewItemTitleBar::EnabledCheckBoxClicked, node_, &Node::SetEnabled);
Retranslate();
}
@@ -56,6 +56,11 @@ NodeParamViewItemTitleBar::NodeParamViewItemTitleBar(QWidget *parent) :
pin_btn_->setVisible(false);
layout->addWidget(pin_btn_);
connect(pin_btn_, &QPushButton::clicked, this, &NodeParamViewItemTitleBar::PinToggled);
enabled_checkbox_ = new QCheckBox();
enabled_checkbox_->setVisible(false);
layout->addWidget(enabled_checkbox_);
connect(enabled_checkbox_, &QCheckBox::clicked, this, &NodeParamViewItemTitleBar::EnabledCheckBoxClicked);
}
void NodeParamViewItemTitleBar::SetExpanded(bool e)
@@ -21,6 +21,7 @@
#ifndef NODEPARAMVIEWITEMTITLEBAR_H
#define NODEPARAMVIEWITEMTITLEBAR_H
#include <QCheckBox>
#include <QLabel>
#include <QWidget>
@@ -59,6 +60,16 @@ public slots:
add_fx_btn_->setVisible(e);
}
void SetEnabledCheckBoxVisible(bool e)
{
enabled_checkbox_->setVisible(e);
}
void SetEnabledCheckBoxChecked(bool e)
{
enabled_checkbox_->setChecked(e);
}
signals:
void ExpandedStateChanged(bool e);
@@ -66,6 +77,8 @@ signals:
void AddEffectButtonClicked();
void EnabledCheckBoxClicked(bool e);
protected:
virtual void paintEvent(QPaintEvent *event) override;
@@ -82,6 +95,8 @@ private:
QPushButton *add_fx_btn_;
QCheckBox *enabled_checkbox_;
};
}
+81 -63
View File
@@ -32,6 +32,7 @@
#include "node/distort/transform/transformdistortnode.h"
#include "node/factory.h"
#include "node/group/group.h"
#include "node/project/serializer/serializer.h"
#include "node/traverser.h"
#include "ui/icons/icons.h"
#include "widget/menu/menushared.h"
@@ -203,7 +204,31 @@ void NodeView::CopySelected(bool cut)
return;
}
CopyNodesToClipboard(selected_nodes_);
QString copy_str;
QXmlStreamWriter writer(&copy_str);
ProjectSerializer::SaveData sdata(selected_nodes_.first()->project());
sdata.SetOnlySerializeNodesAndResolveGroups(selected_nodes_);
ProjectSerializer::SerializedProperties properties;
for (Node *n : selected_nodes_) {
NodeViewItem *item = GetAssumedItemForSelectedNode(n);
if (item) {
Node::Position pos = item->GetNodePositionData();
properties[n][QStringLiteral("x")] = QString::number(pos.position.x());
properties[n][QStringLiteral("y")] = QString::number(pos.position.y());
properties[n][QStringLiteral("expanded")] = QString::number(pos.expanded);
}
}
sdata.SetProperties(properties);
ProjectSerializer::Save(&writer, sdata, QStringLiteral("nodes"));
Core::CopyStringToClipboard(copy_str);
if (cut) {
DeleteSelected();
@@ -212,9 +237,31 @@ void NodeView::CopySelected(bool cut)
void NodeView::Paste()
{
if (!contexts_.isEmpty()) {
PasteNodesFromClipboard();
if (contexts_.isEmpty()) {
return;
}
ProjectSerializer::Result res = ProjectSerializer::Paste(QStringLiteral("nodes"));
if (res.GetLoadedNodes().isEmpty()) {
return;
}
Node::PositionMap map;
for (auto it=res.GetLoadData().properties.cbegin(); it!=res.GetLoadData().properties.cend(); it++) {
Node::Position pos;
const QMap<QString, QString> &node_props = it.value();
pos.position.setX(node_props.value(QStringLiteral("x")).toDouble());
pos.position.setY(node_props.value(QStringLiteral("y")).toDouble());
pos.expanded = node_props.value(QStringLiteral("expanded")).toDouble();
qDebug() << it.key() << pos.position;
map.insert(it.key(), pos);
}
PostPaste(res.GetLoadedNodes(), map);
}
void NodeView::Duplicate()
@@ -450,8 +497,10 @@ void NodeView::mousePressEvent(QMouseEvent *event)
}
}
// Default QGraphicsView functionality (selecting, dragging, etc.)
super::mousePressEvent(event);
if (attached_items_.isEmpty()) {
// Default QGraphicsView functionality (selecting, dragging, etc.)
super::mousePressEvent(event);
}
// For any selected item, store its position in case the user is dragging it somewhere else
auto selected_items = scene_.GetSelectedItems();
@@ -472,7 +521,9 @@ void NodeView::mouseMoveEvent(QMouseEvent *event)
return;
}
super::mouseMoveEvent(event);
if (attached_items_.isEmpty()) {
super::mouseMoveEvent(event);
}
// See if there are any items attached
if (!attached_items_.isEmpty()) {
@@ -499,26 +550,26 @@ void NodeView::mouseMoveEvent(QMouseEvent *event)
if (new_drop_edge) {
drop_input_.Reset();
NodeValue::Type drop_edge_data_type = NodeValue::kNone;
NodeValue::Type drop_edge_data_type = new_drop_edge->input().GetDataType();
// Run the Node and determine what type is being used
NodeTraverser traverser;
NodeValue drop_edge_value = traverser.GenerateRow(new_drop_edge->output(), TimeRange(0, 0))[new_drop_edge->input().input()];
drop_edge_data_type = drop_edge_value.type();
// Determine best input to connect to our new node
if (attached_node->GetEffectInput().IsValid()) {
// If node specifies an effect input, use that immediately
drop_input_ = attached_node->GetEffectInput();
} else {
// Otherwise, we may have to iterate to find a valid one
for (const QString& input : attached_node->inputs()) {
NodeInput i(attached_node, input);
// Iterate through the inputs of our dragging node and see if our node has any acceptable
// inputs to connect to for this type
for (const QString& input : attached_node->inputs()) {
NodeInput i(attached_node, input);
if (attached_node->IsInputConnectable(input)) {
if (attached_node->GetInputDataType(input) == drop_edge_data_type) {
// Found exactly the type we're looking for, set and break this loop
drop_input_ = i;
break;
} else if (!drop_input_.IsValid()) {
// Default to first connectable input
drop_input_ = i;
if (attached_node->IsInputConnectable(input)) {
if (attached_node->GetInputDataType(input) == drop_edge_data_type) {
// Found exactly the type we're looking for, set and break this loop
drop_input_ = i;
break;
} else if (!drop_input_.IsValid()) {
// Default to first connectable input
drop_input_ = i;
}
}
}
}
@@ -559,6 +610,8 @@ void NodeView::mouseReleaseEvent(QMouseEvent *event)
Node *select_context = nullptr;
QVector<Node*> select_nodes;
bool had_attached_items = !attached_items_.isEmpty();
if (!attached_items_.isEmpty()) {
select_context = nullptr;
@@ -642,7 +695,9 @@ void NodeView::mouseReleaseEvent(QMouseEvent *event)
Core::instance()->undo_stack()->pushIfHasChildren(command);
super::mouseReleaseEvent(event);
if (!had_attached_items) {
super::mouseReleaseEvent(event);
}
if (select_context) {
scene_.context_map().value(select_context)->Select(select_nodes);
@@ -998,43 +1053,6 @@ bool NodeView::eventFilter(QObject *object, QEvent *event)
return super::eventFilter(object, event);
}
void NodeView::CopyNodesToClipboardCallback(const QVector<Node*> &nodes, ProjectSerializer::SaveData *sdata, void *userdata)
{
ProjectSerializer::SerializedProperties properties;
for (Node *n : nodes) {
NodeViewItem *item = GetAssumedItemForSelectedNode(n);
if (item) {
Node::Position pos = item->GetNodePositionData();
properties[n][QStringLiteral("x")] = QString::number(pos.position.x());
properties[n][QStringLiteral("y")] = QString::number(pos.position.y());
properties[n][QStringLiteral("expanded")] = QString::number(pos.expanded);
}
}
sdata->SetProperties(properties);
}
void NodeView::PasteNodesToClipboardCallback(const QVector<Node *> &nodes, const ProjectSerializer::LoadData &ldata, void *userdata)
{
Node::PositionMap map;
for (auto it=ldata.properties.cbegin(); it!=ldata.properties.cend(); it++) {
Node::Position pos;
const QMap<QString, QString> &node_props = it.value();
pos.position.setX(node_props.value(QStringLiteral("x")).toDouble());
pos.position.setY(node_props.value(QStringLiteral("y")).toDouble());
pos.expanded = node_props.value(QStringLiteral("expanded")).toDouble();
map.insert(it.key(), pos);
}
PostPaste(nodes, map);
}
void NodeView::changeEvent(QEvent *e)
{
// Add translation code
@@ -1539,7 +1557,7 @@ void NodeView::PostPaste(const QVector<Node *> &new_nodes, const Node::PositionM
AttachedItem &ai = new_attached[i];
if (ai.item) {
ai.original_pos = first_item->pos() - ai.item->pos();
ai.original_pos = ai.item->pos() - first_item->pos();
}
}
}
+1 -5
View File
@@ -26,7 +26,6 @@
#include "core.h"
#include "node/graph.h"
#include "node/nodecopypaste.h"
#include "nodeviewedge.h"
#include "nodeviewcontext.h"
#include "nodeviewminimap.h"
@@ -42,7 +41,7 @@ namespace olive {
* This widget takes a NodeGraph object and constructs a QGraphicsScene representing its data, viewing and allowing
* the user to make modifications to it.
*/
class NodeView : public HandMovableView, public NodeCopyPasteService
class NodeView : public HandMovableView
{
Q_OBJECT
public:
@@ -139,9 +138,6 @@ protected:
virtual bool eventFilter(QObject *object, QEvent *event) override;
virtual void CopyNodesToClipboardCallback(const QVector<Node *> &nodes, ProjectSerializer::SaveData *data, void* userdata) override;
virtual void PasteNodesToClipboardCallback(const QVector<Node*> &nodes, const ProjectSerializer::LoadData &ldata, void *userdata) override;
virtual void changeEvent(QEvent *e) override;
private:
@@ -55,6 +55,7 @@ PlaybackControls::PlaybackControls(QWidget *parent) :
cur_tc_lbl_ = new RationalSlider();
cur_tc_lbl_->SetDisplayType(RationalSlider::kTime);
cur_tc_lbl_->SetMinimum(0);
connect(cur_tc_lbl_, &RationalSlider::ValueChanged, this, &PlaybackControls::TimeChanged);
lower_left_layout->addWidget(cur_tc_lbl_);
lower_left_layout->addStretch();
@@ -155,6 +156,10 @@ PlaybackControls::PlaybackControls(QWidget *parent) :
SetAudioVideoDragButtonsVisible(false);
connect(Core::instance(), &Core::TimecodeDisplayChanged, this, &PlaybackControls::TimecodeChanged);
play_blink_timer_ = new QTimer(this);
play_blink_timer_->setInterval(500);
connect(play_blink_timer_, &QTimer::timeout, this, &PlaybackControls::PlayBlink);
}
void PlaybackControls::SetTimecodeEnabled(bool enabled)
@@ -230,10 +235,20 @@ void PlaybackControls::UpdateIcons()
audio_drag_btn_->setIcon(icon::Audio);
}
void PlaybackControls::SetButtonRecordingState(QPushButton *btn, bool on)
{
btn->setStyleSheet(on ? QStringLiteral("background: red;") : QString());
}
void PlaybackControls::TimecodeChanged()
{
// Update end time
SetEndTime(end_time_);
}
void PlaybackControls::PlayBlink()
{
SetButtonRecordingState(play_btn_, play_btn_->styleSheet().isEmpty());
}
}
@@ -61,6 +61,23 @@ public slots:
void ShowPlayButton();
void StartPlayBlink()
{
play_blink_timer_->start();
SetButtonRecordingState(play_btn_, true);
}
void StopPlayBlink()
{
play_blink_timer_->stop();
SetButtonRecordingState(play_btn_, false);
}
void SetPauseButtonRecordingState(bool on)
{
SetButtonRecordingState(pause_btn_, on);
}
signals:
/**
* @brief Signal emitted when "Go to Start" is clicked
@@ -108,6 +125,8 @@ protected:
private:
void UpdateIcons();
static void SetButtonRecordingState(QPushButton *btn, bool on);
QWidget* lower_left_container_;
QWidget* lower_right_container_;
@@ -129,9 +148,13 @@ private:
QStackedWidget* playpause_stack_;
QTimer *play_blink_timer_;
private slots:
void TimecodeChanged();
void PlayBlink();
};
}
@@ -25,6 +25,8 @@
#include <QStyleOptionSlider>
#include <QtMath>
#include "ui/colorcoding.h"
namespace olive {
ResizableTimelineScrollBar::ResizableTimelineScrollBar(QWidget* parent) :
@@ -48,6 +50,7 @@ void ResizableTimelineScrollBar::ConnectTimelinePoints(TimelinePoints *points)
disconnect(points_->workarea(), &TimelineWorkArea::EnabledChanged, this, static_cast<void (ResizableTimelineScrollBar::*)()>(&ResizableTimelineScrollBar::update));
disconnect(points_->markers(), &TimelineMarkerList::MarkerAdded, this, static_cast<void (ResizableTimelineScrollBar::*)()>(&ResizableTimelineScrollBar::update));
disconnect(points_->markers(), &TimelineMarkerList::MarkerRemoved, this, static_cast<void (ResizableTimelineScrollBar::*)()>(&ResizableTimelineScrollBar::update));
disconnect(points_->markers(), &TimelineMarkerList::MarkerModified, this, static_cast<void (ResizableTimelineScrollBar::*)()>(&ResizableTimelineScrollBar::update));
}
points_ = points;
@@ -57,6 +60,7 @@ void ResizableTimelineScrollBar::ConnectTimelinePoints(TimelinePoints *points)
connect(points_->workarea(), &TimelineWorkArea::EnabledChanged, this, static_cast<void (ResizableTimelineScrollBar::*)()>(&ResizableTimelineScrollBar::update));
connect(points_->markers(), &TimelineMarkerList::MarkerAdded, this, static_cast<void (ResizableTimelineScrollBar::*)()>(&ResizableTimelineScrollBar::update));
connect(points_->markers(), &TimelineMarkerList::MarkerRemoved, this, static_cast<void (ResizableTimelineScrollBar::*)()>(&ResizableTimelineScrollBar::update));
connect(points_->markers(), &TimelineMarkerList::MarkerModified, this, static_cast<void (ResizableTimelineScrollBar::*)()>(&ResizableTimelineScrollBar::update));
}
update();
@@ -75,7 +79,7 @@ void ResizableTimelineScrollBar::paintEvent(QPaintEvent *event)
if (points_
&& !timebase().isNull()
&& (points_->workarea()->enabled() || !points_->markers()->list().isEmpty())) {
&& (points_->workarea()->enabled() || !points_->markers()->empty())) {
QStyleOptionSlider opt;
initStyleOption(&opt);
@@ -108,11 +112,13 @@ void ResizableTimelineScrollBar::paintEvent(QPaintEvent *event)
workarea_color);
}
if (!points_->markers()->list().isEmpty()) {
QColor marker_color(0, 255, 0, 128);
foreach (TimelineMarker* marker, points_->markers()->list()) {
int64_t in = qRound64(ratio * TimeToScene(marker->time().in()));
int64_t out = qRound64(ratio * TimeToScene(marker->time().out()));
if (!points_->markers()->empty()) {
for (auto it=points_->markers()->cbegin(); it!=points_->markers()->cend(); it++) {
TimelineMarker* marker = *it;
QColor marker_color = ColorCoding::GetColor(marker->color()).toQColor();
int64_t in = qRound64(ratio * TimeToScene(marker->time_range().in()));
int64_t out = qRound64(ratio * TimeToScene(marker->time_range().out()));
int64_t length = qMax(int64_t(1), out-in);
p.fillRect(gr.x() + in,
-22
View File
@@ -1,22 +0,0 @@
# Olive - Non-Linear Video Editor
# Copyright (C) 2021 Olive Team
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
set(OLIVE_SOURCES
${OLIVE_SOURCES}
widget/snapservice/snapservice.cpp
widget/snapservice/snapservice.h
PARENT_SCOPE
)
-1
View File
@@ -1 +0,0 @@
#include "snapservice.h"
-31
View File
@@ -1,31 +0,0 @@
#ifndef SNAPSERVICE_H
#define SNAPSERVICE_H
#include "common/rational.h"
namespace olive {
class SnapService
{
public:
SnapService() = default;
enum SnapPoints {
kSnapToClips = 0x1,
kSnapToPlayhead = 0x2,
kSnapToMarkers = 0x4,
kSnapAll = 0xFF
};
/**
* @brief Snaps point `start_point` that is moving by `movement` to currently existing clips
*/
virtual bool SnapPoint(QVector<rational> start_times, rational *movement, int snap_points = kSnapAll) = 0;
virtual void HideSnaps() = 0;
};
}
#endif // SNAPSERVICE_H
+3 -7
View File
@@ -26,6 +26,7 @@
#include <QTimer>
#include "common/timecodefunctions.h"
#include "widget/timebased/timebasedwidget.h"
namespace olive {
@@ -63,7 +64,7 @@ void TimeBasedView::TimebaseChangedEvent(const rational &)
viewport()->update();
}
void TimeBasedView::EnableSnap(const QVector<rational> &points)
void TimeBasedView::EnableSnap(const std::vector<rational> &points)
{
snapped_ = true;
snap_time_ = points;
@@ -78,11 +79,6 @@ void TimeBasedView::DisableSnap()
viewport()->update();
}
void TimeBasedView::SetSnapService(SnapService *service)
{
snap_service_ = service;
}
const double &TimeBasedView::GetYScale() const
{
return y_scale_;
@@ -211,7 +207,7 @@ bool TimeBasedView::PlayheadMove(QMouseEvent *event)
if (Core::instance()->snapping() && snap_service_) {
rational movement;
snap_service_->SnapPoint({mouse_time}, &movement, SnapService::kSnapAll & ~SnapService::kSnapToPlayhead);
snap_service_->SnapPoint({mouse_time}, &movement, TimeBasedWidget::kSnapAll & ~TimeBasedWidget::kSnapToPlayhead);
mouse_time += movement;
}
+10 -10
View File
@@ -22,28 +22,33 @@
#define TIMELINEVIEWBASE_H
#include <QGraphicsView>
#include <vector>
#include "core.h"
#include "timescaledobject.h"
#include "widget/handmovableview/handmovableview.h"
#include "widget/snapservice/snapservice.h"
namespace olive {
class TimeBasedWidget;
class TimeBasedView : public HandMovableView, public TimeScaledObject
{
Q_OBJECT
public:
TimeBasedView(QWidget* parent = nullptr);
void EnableSnap(const QVector<rational> &points);
void EnableSnap(const std::vector<rational> &points);
void DisableSnap();
bool IsSnapped() const
{
return snapped_;
}
void SetSnapService(SnapService* service);
const rational &GetTime() const { return playhead_; }
TimeBasedWidget *GetSnapService() const { return snap_service_; }
void SetSnapService(TimeBasedWidget* service) { snap_service_ = service; }
const double& GetYScale() const;
void SetYScale(const double& y_scale);
@@ -85,11 +90,6 @@ protected:
virtual void ZoomIntoCursorPosition(QWheelEvent *event, double multiplier, const QPointF &cursor_pos) override;
const rational &GetPlayheadTime() const
{
return playhead_;
}
bool PlayheadPress(QMouseEvent* event);
bool PlayheadMove(QMouseEvent* event);
bool PlayheadRelease(QMouseEvent* event);
@@ -119,11 +119,11 @@ private:
QGraphicsScene scene_;
bool snapped_;
QVector<rational> snap_time_;
std::vector<rational> snap_time_;
rational end_time_;
SnapService* snap_service_;
TimeBasedWidget* snap_service_;
bool y_axis_enabled_;
@@ -22,5 +22,4 @@
namespace olive {
}
@@ -29,6 +29,7 @@
#include "common/rational.h"
#include "common/timecodefunctions.h"
#include "timebasedview.h"
#include "timebasedwidget.h"
namespace olive {
@@ -38,9 +39,15 @@ class TimeBasedViewSelectionManager
public:
TimeBasedViewSelectionManager(TimeBasedView *view) :
view_(view),
rubberband_(nullptr)
rubberband_(nullptr),
snap_mask_(TimeBasedWidget::kSnapAll)
{}
void SetSnapMask(TimeBasedWidget::SnapMask e)
{
snap_mask_ = e;
}
void ClearDrawnObjects()
{
drawn_objects_.clear();
@@ -48,7 +55,7 @@ public:
void DeclareDrawnObject(T *object, const QRectF &pos)
{
drawn_objects_.append({object, pos});
drawn_objects_.push_back({object, pos});
}
bool Select(T *key)
@@ -56,7 +63,7 @@ public:
Q_ASSERT(key);
if (!IsSelected(key)) {
selected_.append(key);
selected_.push_back(key);
return true;
}
@@ -67,7 +74,13 @@ public:
{
Q_ASSERT(key);
return selected_.removeOne(key);
auto it = std::find(selected_.cbegin(), selected_.cend(), key);
if (it == selected_.cend()) {
return false;
} else {
selected_.erase(it);
return true;
}
}
void ClearSelection()
@@ -77,10 +90,10 @@ public:
bool IsSelected(T *key) const
{
return selected_.contains(key);
return std::find(selected_.cbegin(), selected_.cend(), key) != selected_.cend();
}
const QVector<T*> &GetSelectedObjects() const
const std::vector<T*> &GetSelectedObjects() const
{
return selected_;
}
@@ -142,7 +155,7 @@ public:
bool IsDragging() const
{
return !dragging_.isEmpty();
return !dragging_.empty();
}
void DragStart(T *initial_item, QMouseEvent *event)
@@ -150,39 +163,80 @@ public:
initial_drag_item_ = initial_item;
dragging_.resize(selected_.size());
for (int i=0; i<selected_.size(); i++) {
snap_points_.resize(selected_.size()*2);
for (size_t i=0; i<selected_.size(); i++) {
T *obj = selected_.at(i);
dragging_[i] = {obj->time(), view_->TimeToScene(obj->time())};
dragging_[i] = obj->time();
snap_points_[i] = obj->time();
snap_points_[i+selected_.size()] = obj->time_range().out();
}
drag_mouse_start_ = view_->mapToScene(event->pos());
}
void DragMove(QMouseEvent *event, const QString &tip_format)
void SnapPoints(rational *movement)
{
QPointF diff = view_->mapToScene(event->pos()) - drag_mouse_start_;
if (Core::instance()->snapping() && view_->GetSnapService()) {
view_->GetSnapService()->SnapPoint(snap_points_, movement, snap_mask_);
}
}
for (int i=0; i<selected_.size(); i++) {
rational proposed_time = view_->SceneToTimeNoGrid(dragging_.at(i).x + diff.x());
void Unsnap()
{
if (view_->GetSnapService()) {
view_->GetSnapService()->HideSnaps();
}
}
void DragMove(QMouseEvent *event, const QString &tip_format = QString())
{
rational time_diff = view_->SceneToTimeNoGrid(view_->mapToScene(event->pos()).x() - drag_mouse_start_.x());
// Snap points
SnapPoints(&time_diff);
// Validate movement
for (size_t i=0; i<selected_.size(); i++) {
rational proposed_time = dragging_.at(i) + time_diff;
T *sel = selected_.at(i);
// Magic number: use interval of 1ms to avoid collisions
rational adj(1, 1000);
if (dragging_.at(i).time < proposed_time) {
if (dragging_.at(i) < proposed_time) {
// Negate adjustment value if origin is less than proposed time
adj = -adj;
}
while (true) {
NodeKeyframe *key_at_time = sel->parent()->GetKeyframeAtTimeOnTrack(sel->input(), proposed_time, sel->track(), sel->element());
if (!key_at_time || key_at_time == sel) {
break;
bool loop;
do {
loop = false;
while (sel->has_sibling_at_time(proposed_time)) {
proposed_time += adj;
Unsnap();
}
proposed_time += adj;
}
if (proposed_time < 0) {
// Prevent any object from going below zero
proposed_time = 0;
Unsnap();
sel->set_time(proposed_time);
// Setting our proposed time to zero may (re)introduce a conflict that we just avoided
// with the sibling check above, so we request it to happen again. To avoid a negative
// adj bringing us back below zero, we force adj to positive so it'll only nudge higher
adj = qAbs(adj);
loop = true;
}
} while (loop);
time_diff = proposed_time - dragging_.at(i);
}
// Apply movement
for (size_t i=0; i<selected_.size(); i++) {
selected_.at(i)->set_time(dragging_.at(i) + time_diff);
}
// Show information about this keyframe
@@ -201,11 +255,12 @@ public:
{
QToolTip::hideText();
for (int i=0; i<selected_.size(); i++) {
command->add_child(new SetTimeCommand(selected_.at(i), selected_.at(i)->time(), dragging_.at(i).time));
for (size_t i=0; i<selected_.size(); i++) {
command->add_child(new SetTimeCommand(selected_.at(i), selected_.at(i)->time(), dragging_.at(i)));
}
dragging_.clear();
Unsnap();
}
void RubberBandStart(QMouseEvent *event)
@@ -271,7 +326,7 @@ private:
virtual Project* GetRelevantProject() const override
{
return key_->parent()->project();
return Project::GetProjectFromObject(key_);
}
protected:
@@ -296,17 +351,12 @@ private:
TimeBasedView *view_;
using DrawnObject = QPair<T*, QRectF>;
QVector<DrawnObject> drawn_objects_;
std::vector<DrawnObject> drawn_objects_;
QVector<T*> selected_;
std::vector<T*> selected_;
struct DragObject
{
rational time;
double x;
};
QVector<DragObject> dragging_;
std::vector<rational> dragging_;
std::vector<rational> snap_points_;
T *initial_drag_item_;
@@ -316,7 +366,9 @@ private:
QRubberBand *rubberband_;
QPoint rubberband_start_;
QVector<T*> rubberband_preselected_;
std::vector<T*> rubberband_preselected_;
TimeBasedWidget::SnapMask snap_mask_;
};
+187 -30
View File
@@ -23,10 +23,13 @@
#include <QInputDialog>
#include "common/autoscroll.h"
#include "common/range.h"
#include "common/timecodefunctions.h"
#include "config/config.h"
#include "core.h"
#include "dialog/markerproperties/markerpropertiesdialog.h"
#include "node/project/sequence/sequence.h"
#include "widget/timeruler/timeruler.h"
#include "widget/timelinewidget/undo/timelineundoworkarea.h"
namespace olive {
@@ -39,7 +42,8 @@ TimeBasedWidget::TimeBasedWidget(bool ruler_text_visible, bool ruler_cache_statu
auto_set_timebase_(true)
{
ruler_ = new TimeRuler(ruler_text_visible, ruler_cache_status_visible, this);
connect(ruler_, &TimeRuler::TimeChanged, this, &TimeBasedWidget::SetTimeAndSignal);
ConnectTimelineView(ruler_, true);
ruler()->SetSnapService(this);
scrollbar_ = new ResizableTimelineScrollBar(Qt::Horizontal, this);
connect(scrollbar_, &ResizableScrollBar::ResizeBegan, this, &TimeBasedWidget::ScrollBarResizeBegan);
@@ -588,18 +592,36 @@ void TimeBasedWidget::SetMarker()
return;
}
bool ok;
QString marker_name;
TimelineMarkerList *markers = GetConnectedNode()->GetTimelinePoints()->markers();
if (Config::Current()[QStringLiteral("SetNameWithMarker")].toBool()) {
marker_name = QInputDialog::getText(this, tr("Set Marker"), tr("Marker name:"), QLineEdit::Normal, QString(), &ok);
if (TimelineMarker *existing = markers->GetMarkerAtTime(GetTime())) {
// We already have a marker here, so pop open the edit dialog
MarkerPropertiesDialog mpd({existing}, timebase(), this);
mpd.exec();
} else {
ok = true;
}
// Create a new marker and place it here
int color;
if (TimelineMarker *closest = markers->GetClosestMarkerToTime(GetTime())) {
// Copy color of closest marker to this time
color = closest->color();
} else {
// Fallback to default color in preferences
color = Config::Current()[QStringLiteral("MarkerColor")].toInt();
}
if (ok) {
Core::instance()->undo_stack()->push(new MarkerAddCommand(GetConnectedNode()->project(),
GetConnectedNode()->GetTimelinePoints()->markers(), TimeRange(GetTime(), GetTime()), marker_name));
TimelineMarker *marker = new TimelineMarker(color, TimeRange(GetTime(), GetTime()));
if (Config::Current()[QStringLiteral("SetNameWithMarker")].toBool()) {
MarkerPropertiesDialog mpd({marker}, timebase(), this);
if (mpd.exec() != QDialog::Accepted) {
delete marker;
marker = nullptr;
}
}
if (marker) {
Core::instance()->undo_stack()->push(new MarkerAddCommand(markers, marker));
}
}
}
@@ -658,27 +680,11 @@ void TimeBasedWidget::GoToOut()
}
}
TimeBasedWidget::MarkerAddCommand::MarkerAddCommand(Project *project, TimelineMarkerList *marker_list, const TimeRange &range, const QString &name) :
project_(project),
marker_list_(marker_list),
range_(range),
name_(name)
void TimeBasedWidget::DeleteSelected()
{
}
Project *TimeBasedWidget::MarkerAddCommand::GetRelevantProject() const
{
return project_;
}
void TimeBasedWidget::MarkerAddCommand::redo()
{
added_marker_ = marker_list_->AddMarker(range_, name_);
}
void TimeBasedWidget::MarkerAddCommand::undo()
{
marker_list_->RemoveMarker(added_marker_);
if (ruler_->underMouse()) {
ruler_->DeleteSelected();
}
}
bool TimeBasedWidget::eventFilter(QObject *object, QEvent *event)
@@ -690,4 +696,155 @@ bool TimeBasedWidget::eventFilter(QObject *object, QEvent *event)
return false;
}
struct SnapData {
rational time;
rational movement;
};
void AttemptSnap(std::vector<SnapData> &snap_data,
const std::vector<double>& screen_pt,
double compare_pt,
const std::vector<rational>& start_times,
const rational& compare_time)
{
const qreal kSnapRange = 10; // FIXME: Hardcoded number
for (size_t i=0;i<screen_pt.size();i++) {
// Attempt snapping to clip out point
if (InRange(screen_pt.at(i), compare_pt, kSnapRange)) {
snap_data.push_back({compare_time, compare_time - start_times.at(i)});
}
}
}
bool TimeBasedWidget::SnapPoint(const std::vector<rational> &start_times, rational *movement, SnapMask snap_points)
{
std::vector<double> screen_pt(start_times.size());
for (size_t i=0; i<start_times.size(); i++) {
screen_pt[i] = TimeToScene(start_times.at(i) + *movement);
}
std::vector<SnapData> potential_snaps;
if (snap_points & kSnapToPlayhead) {
rational playhead_abs_time = GetTime();
qreal playhead_pos = TimeToScene(playhead_abs_time);
AttemptSnap(potential_snaps, screen_pt, playhead_pos, start_times, playhead_abs_time);
}
if ((snap_points & kSnapToClips) && GetSnapBlocks()) {
for (auto it=GetSnapBlocks()->cbegin(); it!=GetSnapBlocks()->cend(); it++) {
Block *b = *it;
qreal rect_left = TimeToScene(b->in());
qreal rect_right = TimeToScene(b->out());
// Attempt snapping to clip in point
AttemptSnap(potential_snaps, screen_pt, rect_left, start_times, b->in());
// Attempt snapping to clip out point
AttemptSnap(potential_snaps, screen_pt, rect_right, start_times, b->out());
if (snap_points & kSnapToMarkers) {
// Snap to clip markers too
if (ClipBlock *clip = dynamic_cast<ClipBlock*>(b)) {
if (clip->connected_viewer()) {
TimelineMarkerList *markers = clip->connected_viewer()->GetTimelinePoints()->markers();
for (auto jt=markers->cbegin(); jt!=markers->cend(); jt++) {
TimelineMarker *marker = *jt;
TimeRange marker_range = marker->time_range() + clip->in() - clip->media_in();
qreal marker_in_screen = TimeToScene(marker_range.in());
qreal marker_out_screen = TimeToScene(marker_range.out());
AttemptSnap(potential_snaps, screen_pt, marker_in_screen, start_times, marker_range.in());
AttemptSnap(potential_snaps, screen_pt, marker_out_screen, start_times, marker_range.out());
}
}
}
}
}
}
if ((snap_points & kSnapToMarkers) && ruler()->GetTimelinePoints()) {
for (auto it=ruler()->GetTimelinePoints()->markers()->cbegin(); it!=ruler()->GetTimelinePoints()->markers()->cend(); it++) {
TimelineMarker* m = *it;
qreal marker_pos = TimeToScene(m->time_range().in());
AttemptSnap(potential_snaps, screen_pt, marker_pos, start_times, m->time_range().in());
if (m->time_range().in() != m->time_range().out()) {
marker_pos = TimeToScene(m->time_range().out());
AttemptSnap(potential_snaps, screen_pt, marker_pos, start_times, m->time_range().out());
}
}
}
if ((snap_points & kSnapToKeyframes) && GetSnapKeyframes()) {
for (auto it=GetSnapKeyframes()->cbegin(); it!=GetSnapKeyframes()->cend(); it++) {
const QVector<NodeKeyframe*> &keys = (*it)->GetKeyframes();
for (auto jt=keys.cbegin(); jt!=keys.cend(); jt++) {
NodeKeyframe *key = *jt;
auto ignore = GetSnapIgnoreKeyframes();
if (ignore && std::find(ignore->cbegin(), ignore->cend(), key) != ignore->cend()) {
continue;
}
qreal key_scene_pt = TimeToScene(key->time());
AttemptSnap(potential_snaps, screen_pt, key_scene_pt, start_times, key->time());
}
}
}
if (potential_snaps.empty()) {
HideSnaps();
return false;
}
int closest_snap = 0;
rational closest_diff = qAbs(potential_snaps.at(0).movement - *movement);
// Determine which snap point was the closest
for (size_t i=1; i<potential_snaps.size(); i++) {
rational this_diff = qAbs(potential_snaps.at(i).movement - *movement);
if (this_diff < closest_diff) {
closest_snap = i;
closest_diff = this_diff;
}
}
*movement = potential_snaps.at(closest_snap).movement;
// Find all points at this movement
std::vector<rational> snap_times;
foreach (const SnapData& d, potential_snaps) {
if (d.movement == *movement) {
snap_times.push_back(d.time);
}
}
ShowSnaps(snap_times);
return true;
}
void TimeBasedWidget::ShowSnaps(const std::vector<rational> &times)
{
foreach (TimeBasedView* view, timeline_views_) {
view->EnableSnap(times);
}
}
void TimeBasedWidget::HideSnaps()
{
foreach (TimeBasedView* view, timeline_views_) {
view->DisableSnap();
}
}
}
+25 -20
View File
@@ -25,13 +25,15 @@
#include "node/output/viewer/viewer.h"
#include "timeline/timelinecommon.h"
#include "widget/keyframeview/keyframeviewinputconnection.h"
#include "widget/resizablescrollbar/resizabletimelinescrollbar.h"
#include "widget/timebased/timescaledobject.h"
#include "widget/timelinewidget/view/timelineview.h"
#include "widget/timeruler/timeruler.h"
namespace olive {
class TimeRuler;
class TimeBasedWidget : public TimelineScaledWidget
{
Q_OBJECT
@@ -54,6 +56,22 @@ public:
virtual bool eventFilter(QObject* object, QEvent* event) override;
using SnapMask = uint32_t;
enum SnapPoints {
kSnapToClips = 0x1,
kSnapToPlayhead = 0x2,
kSnapToMarkers = 0x4,
kSnapToKeyframes = 0x8,
kSnapAll = UINT32_MAX
};
/**
* @brief Snaps point `start_point` that is moving by `movement` to currently existing clips
*/
bool SnapPoint(const std::vector<rational> &start_times, rational *movement, SnapMask snap_points = kSnapAll);
void ShowSnaps(const std::vector<rational> &times);
void HideSnaps();
public slots:
void SetTime(const rational &time);
@@ -91,6 +109,8 @@ public slots:
void GoToOut();
void DeleteSelected();
protected slots:
void SetTimeAndSignal(const rational& t);
@@ -117,6 +137,10 @@ protected:
void PassWheelEventsToScrollBar(QObject* object);
virtual const QVector<Block*> *GetSnapBlocks() const { return nullptr; }
virtual const QVector<KeyframeViewInputConnection*> *GetSnapKeyframes() const { return nullptr; }
virtual const std::vector<NodeKeyframe*> *GetSnapIgnoreKeyframes() const { return nullptr; }
protected slots:
/**
* @brief Slot to center the horizontal scroll bar on the playhead's current position
@@ -139,26 +163,7 @@ signals:
void ConnectedNodeChanged(ViewerOutput* old, ViewerOutput* now);
private:
class MarkerAddCommand : public UndoCommand
{
public:
MarkerAddCommand(Project* project, TimelineMarkerList* marker_list, const TimeRange& range, const QString& name);
virtual Project* GetRelevantProject() const override;
protected:
virtual void redo() override;
virtual void undo() override;
private:
Project* project_;
TimelineMarkerList* marker_list_;
TimeRange range_;
QString name_;
TimelineMarker* added_marker_;
};
/**
* @brief Set either in or out point to the current playhead
+1
View File
@@ -24,6 +24,7 @@
#include <QWidget>
#include "common/rational.h"
#include "node/block/block.h"
namespace olive {
+106 -181
View File
@@ -31,6 +31,8 @@
#include "dialog/sequence/sequence.h"
#include "dialog/speedduration/speeddurationdialog.h"
#include "node/block/transition/transition.h"
#include "node/project/serializer/serializer.h"
#include "task/project/import/import.h"
#include "tool/add.h"
#include "tool/beam.h"
#include "tool/edit.h"
@@ -53,6 +55,7 @@
#include "widget/menu/menu.h"
#include "widget/menu/menushared.h"
#include "widget/nodeview/nodeviewundo.h"
#include "widget/timeruler/timeruler.h"
namespace olive {
@@ -76,11 +79,11 @@ TimelineWidget::TimelineWidget(QWidget *parent) :
timecode_label_->SetAlignment(Qt::AlignCenter);
timecode_label_->SetDisplayType(RationalSlider::kTime);
timecode_label_->setVisible(false);
timecode_label_->SetMinimum(0);
connect(timecode_label_, &RationalSlider::ValueChanged, this, &TimelineWidget::SetTimeAndSignal);
ruler_and_time_layout->addWidget(timecode_label_);
ruler_and_time_layout->addWidget(ruler());
ruler()->SetSnapService(this);
// Create list of TimelineViews - these MUST correspond to the ViewType enum
@@ -310,66 +313,6 @@ void TimelineWidget::DisconnectNodeEvent(ViewerOutput *n)
}
}
void TimelineWidget::CopyNodesToClipboardCallback(const QVector<Node *> &nodes, ProjectSerializer::SaveData *sdata, void *userdata)
{
// Cache the earliest in point so all copied clips have a "relative" in point that can be pasted anywhere
QVector<Block*>& selected = *static_cast<QVector<Block*>*>(userdata);
rational earliest_in = RATIONAL_MAX;
ProjectSerializer::SerializedProperties properties;
foreach (Block* block, selected) {
earliest_in = qMin(earliest_in, block->in());
}
foreach (Block* block, selected) {
properties[block][QStringLiteral("in")] = (block->in() - earliest_in).toString();
properties[block][QStringLiteral("track")] = block->track()->ToReference().ToString();
}
sdata->SetProperties(properties);
}
void TimelineWidget::PasteNodesToClipboardCallback(const QVector<Node *> &nodes, const ProjectSerializer::LoadData &load_data, void *userdata)
{
bool insert = *(bool*)userdata;
MultiUndoCommand *command = new MultiUndoCommand();
foreach (Node *n, nodes) {
command->add_child(new NodeAddCommand(GetConnectedNode()->project(), n));
}
rational paste_start = GetTime();
if (insert) {
rational paste_end = GetTime();
for (auto it=load_data.properties.cbegin(); it!=load_data.properties.cend(); it++) {
rational length = static_cast<Block*>(it.key())->length();
rational in = rational::fromString(it.value()[QStringLiteral("in")]);
paste_end = qMax(paste_end, paste_start + in + length);
}
if (paste_end != paste_start) {
InsertGapsAt(paste_start, paste_end - paste_start, command);
}
}
for (auto it=load_data.properties.cbegin(); it!=load_data.properties.cend(); it++) {
Block *block = static_cast<Block*>(it.key());
rational in = rational::fromString(it.value()[QStringLiteral("in")]);
Track::Reference track = Track::Reference::FromString(it.value()[QStringLiteral("track")]);
command->add_child(new TrackPlaceBlockCommand(sequence()->track_list(track.type()),
track.index(),
block,
paste_start + in));
}
Core::instance()->undo_stack()->pushIfHasChildren(command);
}
void TimelineWidget::SelectAll()
{
QVector<Block*> newly_selected_blocks;
@@ -494,6 +437,11 @@ void TimelineWidget::ReplaceBlocksWithGaps(const QVector<Block *> &blocks,
void TimelineWidget::DeleteSelected(bool ripple)
{
if (ruler()->hasFocus()) {
ruler()->DeleteSelected();
return;
}
QVector<Block*> selected_list = GetSelectedBlocks();
QVector<Block*> blocks_to_delete;
@@ -626,15 +574,17 @@ void TimelineWidget::CopySelected(bool cut)
return;
}
QVector<Block*> selected = GetSelectedBlocks();
if (ruler()->hasFocus() && ruler()->CopySelected(cut)) {
return;
}
if (selected.isEmpty()) {
if (selected_blocks_.isEmpty()) {
return;
}
QVector<Node*> selected_nodes;
foreach (Block* block, selected) {
foreach (Block* block, selected_blocks_) {
selected_nodes.append(block);
QVector<Node*> deps = block->GetDependencies();
@@ -646,7 +596,25 @@ void TimelineWidget::CopySelected(bool cut)
}
}
CopyNodesToClipboard(selected_nodes, &selected);
ProjectSerializer::SaveData sdata(selected_nodes.first()->project());
sdata.SetOnlySerializeNodesAndResolveGroups(selected_nodes);
// Cache the earliest in point so all copied clips have a "relative" in point that can be pasted anywhere
rational earliest_in = RATIONAL_MAX;
ProjectSerializer::SerializedProperties properties;
foreach (Block* block, selected_blocks_) {
earliest_in = qMin(earliest_in, block->in());
}
foreach (Block* block, selected_blocks_) {
properties[block][QStringLiteral("in")] = (block->in() - earliest_in).toString();
properties[block][QStringLiteral("track")] = block->track()->ToReference().ToString();
}
sdata.SetProperties(properties);
ProjectSerializer::Copy(sdata, QStringLiteral("timeline"));
if (cut) {
DeleteSelected();
@@ -659,7 +627,50 @@ void TimelineWidget::Paste(bool insert)
return;
}
PasteNodesFromClipboard(&insert);
if (ruler()->hasFocus() && ruler()->PasteMarkers(insert, GetTime())) {
return;
}
ProjectSerializer::Result res = ProjectSerializer::Paste(QStringLiteral("timeline"));
if (res.GetLoadedNodes().isEmpty()) {
return;
}
MultiUndoCommand *command = new MultiUndoCommand();
foreach (Node *n, res.GetLoadedNodes()) {
command->add_child(new NodeAddCommand(GetConnectedNode()->project(), n));
}
rational paste_start = GetTime();
if (insert) {
rational paste_end = GetTime();
for (auto it=res.GetLoadData().properties.cbegin(); it!=res.GetLoadData().properties.cend(); it++) {
rational length = static_cast<Block*>(it.key())->length();
rational in = rational::fromString(it.value()[QStringLiteral("in")]);
paste_end = qMax(paste_end, paste_start + in + length);
}
if (paste_end != paste_start) {
InsertGapsAt(paste_start, paste_end - paste_start, command);
}
}
for (auto it=res.GetLoadData().properties.cbegin(); it!=res.GetLoadData().properties.cend(); it++) {
Block *block = static_cast<Block*>(it.key());
rational in = rational::fromString(it.value()[QStringLiteral("in")]);
Track::Reference track = Track::Reference::FromString(it.value()[QStringLiteral("track")]);
command->add_child(new TrackPlaceBlockCommand(sequence()->track_list(track.type()),
track.index(),
block,
paste_start + in));
}
Core::instance()->undo_stack()->pushIfHasChildren(command);
}
void TimelineWidget::DeleteInToOut(bool ripple)
@@ -778,6 +789,35 @@ void TimelineWidget::ShowSpeedDurationDialogForSelectedClips()
}
}
void TimelineWidget::RecordingCallback(const QString &filename, const TimeRange &time, const Track::Reference &track)
{
ProjectImportTask task(GetConnectedNode()->project()->root(), {filename});
task.Start();
MultiUndoCommand *import_command = task.GetCommand();
Core::instance()->undo_stack()->pushIfHasChildren(import_command);
if (task.GetImportedFootage().empty()) {
qCritical() << "Failed to import recorded audio file" << filename;
} else {
import_tool_->PlaceAt({task.GetImportedFootage().front()}, time.in(), false, track.index());
}
}
void TimelineWidget::EnableRecordingOverlay(const TimelineCoordinate &coord)
{
foreach (TimelineAndTrackView* tview, views_) {
tview->view()->EnableRecordingOverlay(coord);
}
}
void TimelineWidget::DisableRecordingOverlay()
{
foreach (TimelineAndTrackView* tview, views_) {
tview->view()->DisableRecordingOverlay();
}
}
void TimelineWidget::InsertGapsAt(const rational &earliest_point, const rational &insert_length, MultiUndoCommand *command)
{
for (int i=0;i<Track::kCount;i++) {
@@ -1505,13 +1545,6 @@ void TimelineWidget::EditTo(Timeline::MovementMode mode)
Core::instance()->undo_stack()->pushIfHasChildren(command);
}
void TimelineWidget::ShowSnap(const QVector<rational> &times)
{
foreach (TimelineAndTrackView* tview, views_) {
tview->view()->EnableSnap(times);
}
}
void TimelineWidget::UpdateViewports(const Track::Type &type)
{
if (type == Track::kNone) {
@@ -1563,13 +1596,6 @@ QVector<Block *> TimelineWidget::GetBlocksInGlobalRect(const QPoint &p1, const Q
return blocks_in_rect;
}
void TimelineWidget::HideSnaps()
{
foreach (TimelineAndTrackView* tview, views_) {
tview->view()->DisableSnap();
}
}
QByteArray TimelineWidget::SaveSplitterState() const
{
return view_splitter_->saveState();
@@ -1724,107 +1750,6 @@ Block *TimelineWidget::GetItemAtScenePos(const TimelineCoordinate& coord)
return views_.at(coord.GetTrack().type())->view()->GetItemAtScenePos(coord.GetFrame(), coord.GetTrack().index());
}
struct SnapData {
rational time;
rational movement;
};
QVector<SnapData> AttemptSnap(const QVector<double>& screen_pt,
double compare_pt,
const QVector<rational>& start_times,
const rational& compare_time) {
const qreal kSnapRange = 10; // FIXME: Hardcoded number
QVector<SnapData> snap_data;
for (int i=0;i<screen_pt.size();i++) {
// Attempt snapping to clip out point
if (InRange(screen_pt.at(i), compare_pt, kSnapRange)) {
snap_data.append({compare_time, compare_time - start_times.at(i)});
}
}
return snap_data;
}
bool TimelineWidget::SnapPoint(QVector<rational> start_times, rational* movement, int snap_points)
{
if (!GetConnectedNode()) {
return false;
}
QVector<double> screen_pt;
foreach (const rational& s, start_times) {
screen_pt.append(TimeToScene(s + *movement));
}
QVector<SnapData> potential_snaps;
if (snap_points & kSnapToPlayhead) {
rational playhead_abs_time = GetTime();
qreal playhead_pos = TimeToScene(playhead_abs_time);
potential_snaps.append(AttemptSnap(screen_pt, playhead_pos, start_times, playhead_abs_time));
}
if (snap_points & kSnapToClips) {
foreach (Block* b, added_blocks_) {
qreal rect_left = TimeToScene(b->in());
qreal rect_right = TimeToScene(b->out());
// Attempt snapping to clip in point
potential_snaps.append(AttemptSnap(screen_pt, rect_left, start_times, b->in()));
// Attempt snapping to clip out point
potential_snaps.append(AttemptSnap(screen_pt, rect_right, start_times, b->out()));
}
}
if ((snap_points & kSnapToMarkers)) {
foreach (TimelineMarker* m, GetConnectedNode()->GetTimelinePoints()->markers()->list()) {
qreal marker_pos = TimeToScene(m->time().in());
potential_snaps.append(AttemptSnap(screen_pt, marker_pos, start_times, m->time().in()));
if (m->time().in() != m->time().out()) {
marker_pos = TimeToScene(m->time().out());
potential_snaps.append(AttemptSnap(screen_pt, marker_pos, start_times, m->time().out()));
}
}
}
if (potential_snaps.isEmpty()) {
HideSnaps();
return false;
}
int closest_snap = 0;
rational closest_diff = qAbs(potential_snaps.at(0).movement - *movement);
// Determine which snap point was the closest
for (int i=1; i<potential_snaps.size(); i++) {
rational this_diff = qAbs(potential_snaps.at(i).movement - *movement);
if (this_diff < closest_diff) {
closest_snap = i;
closest_diff = this_diff;
}
}
*movement = potential_snaps.at(closest_snap).movement;
// Find all points at this movement
QVector<rational> snap_times;
foreach (const SnapData& d, potential_snaps) {
if (d.movement == *movement) {
snap_times.append(d.time);
}
}
ShowSnap(snap_times);
return true;
}
void TimelineWidget::SetSplitterSizesCommand::redo()
{
old_sizes_ = splitter_->sizes();
+15 -11
View File
@@ -27,12 +27,10 @@
#include "core.h"
#include "node/block/transition/transition.h"
#include "node/nodecopypaste.h"
#include "node/output/viewer/viewer.h"
#include "timeline/timelinecommon.h"
#include "timelineandtrackview.h"
#include "widget/slider/rationalslider.h"
#include "widget/snapservice/snapservice.h"
#include "widget/timebased/timebasedwidget.h"
#include "widget/timelinewidget/timelinewidgetselections.h"
#include "widget/timelinewidget/tool/import.h"
@@ -45,7 +43,7 @@ namespace olive {
*
* Encapsulates TimelineViews, TimeRulers, and scrollbars for a complete widget to manipulate Timelines
*/
class TimelineWidget : public TimeBasedWidget, public NodeCopyPasteService, public SnapService
class TimelineWidget : public TimeBasedWidget
{
Q_OBJECT
public:
@@ -101,6 +99,12 @@ public:
void ShowSpeedDurationDialogForSelectedClips();
void RecordingCallback(const QString &filename, const TimeRange &time, const Track::Reference &track);
void EnableRecordingOverlay(const TimelineCoordinate &coord);
void DisableRecordingOverlay();
/**
* @brief Timelines should always be connected to sequences
*/
@@ -114,10 +118,6 @@ public:
return selected_blocks_;
}
virtual bool SnapPoint(QVector<rational> start_times, rational *movement, int snap_points = kSnapAll) override;
virtual void HideSnaps() override;
QByteArray SaveSplitterState() const;
void RestoreSplitterState(const QByteArray& state);
@@ -216,6 +216,11 @@ public:
*/
void SignalDeselectedAllBlocks();
void Refresh()
{
UpdateViewports();
}
MultiUndoCommand *TakeSubtitleSectionCommand()
{
// Copy pointer
@@ -262,6 +267,8 @@ public:
signals:
void BlockSelectionChanged(const QVector<Block*>& selected_blocks);
void RequestCaptureStart(const TimeRange &time, const Track::Reference &track);
protected:
virtual void resizeEvent(QResizeEvent *event) override;
@@ -272,8 +279,7 @@ protected:
virtual void ConnectNodeEvent(ViewerOutput* n) override;
virtual void DisconnectNodeEvent(ViewerOutput* n) override;
virtual void CopyNodesToClipboardCallback(const QVector<Node*> &nodes, ProjectSerializer::SaveData *data, void *userdata) override;
virtual void PasteNodesToClipboardCallback(const QVector<Node*> &nodes, const ProjectSerializer::LoadData &load_data, void *userdata) override;
virtual const QVector<Block*> *GetSnapBlocks() const override { return &added_blocks_; }
private:
QVector<Timeline::EditToInfo> GetEditToInfo(const rational &playhead_time, Timeline::MovementMode mode);
@@ -282,8 +288,6 @@ private:
void EditTo(Timeline::MovementMode mode);
void ShowSnap(const QVector<rational>& times);
void UpdateViewports(const Track::Type& type = Track::kNone);
QVector<Block*> GetBlocksInGlobalRect(const QPoint &p1, const QPoint &p2);
+1 -1
View File
@@ -79,7 +79,7 @@ void AddTool::MousePress(TimelineViewMouseEvent *event)
ghost_->SetTrack(track);
parent()->AddGhost(ghost_);
snap_points_.append(drag_start_point_);
snap_points_.push_back(drag_start_point_);
}
}
+6 -6
View File
@@ -173,7 +173,7 @@ void ImportTool::DragDrop(TimelineViewMouseEvent *event)
}
}
void ImportTool::PlaceAt(const QVector<ViewerOutput *> &footage, const rational &start, bool insert)
void ImportTool::PlaceAt(const QVector<ViewerOutput *> &footage, const rational &start, bool insert, int track_offset)
{
DraggedFootageData refs;
@@ -181,10 +181,10 @@ void ImportTool::PlaceAt(const QVector<ViewerOutput *> &footage, const rational
refs.append({f, f->GetEnabledStreamsAsReferences()});
}
PlaceAt(refs, start, insert);
PlaceAt(refs, start, insert, track_offset);
}
void ImportTool::PlaceAt(const DraggedFootageData &footage, const rational &start, bool insert)
void ImportTool::PlaceAt(const DraggedFootageData &footage, const rational &start, bool insert, int track_offset)
{
dragged_footage_ = footage;
@@ -192,7 +192,7 @@ void ImportTool::PlaceAt(const DraggedFootageData &footage, const rational &star
return;
}
PrepGhosts(start, 0);
PrepGhosts(start, track_offset);
DropGhosts(insert);
}
@@ -243,8 +243,8 @@ void ImportTool::FootageToGhosts(rational ghost_start, const DraggedFootageData
ghost->SetMediaIn(ghost_in);
ghost->SetTrack(Track::Reference(track_type, track_offsets.at(track_type)));
snap_points_.append(ghost->GetIn());
snap_points_.append(ghost->GetOut());
snap_points_.push_back(ghost->GetIn());
snap_points_.push_back(ghost->GetOut());
// Increment track count for this track type
track_offsets[track_type]++;
+2 -2
View File
@@ -37,8 +37,8 @@ public:
using DraggedFootageData = QVector<QPair<ViewerOutput*, QVector<Track::Reference> > >;
void PlaceAt(const QVector<ViewerOutput *> &footage, const rational& start, bool insert);
void PlaceAt(const DraggedFootageData &footage, const rational& start, bool insert);
void PlaceAt(const QVector<ViewerOutput *> &footage, const rational& start, bool insert, int track_offset = 0);
void PlaceAt(const DraggedFootageData &footage, const rational& start, bool insert, int track_offset = 0);
enum DropWithoutSequenceBehavior {
kDWSAsk,
+8 -4
View File
@@ -35,6 +35,7 @@
#include "pointer.h"
#include "widget/nodeview/nodeviewundo.h"
#include "widget/timelinewidget/undo/timelineundopointer.h"
#include "widget/timeruler/timeruler.h"
namespace olive {
@@ -136,6 +137,9 @@ void PointerTool::MousePress(TimelineViewMouseEvent *event)
if (can_rubberband_select_) {
drag_global_start_ = QCursor::pos();
}
// If we click anywhere other than a marker, deselect all markers
parent()->ruler()->DeselectAllMarkers();
}
void PointerTool::MouseMove(TimelineViewMouseEvent *event)
@@ -790,14 +794,14 @@ void PointerTool::AddGhostInternal(TimelineViewGhostItem* ghost, Timeline::Movem
// Prepare snap points (optimizes snapping for later)
switch (mode) {
case Timeline::kMove:
snap_points_.append(ghost->GetIn());
snap_points_.append(ghost->GetOut());
snap_points_.push_back(ghost->GetIn());
snap_points_.push_back(ghost->GetOut());
break;
case Timeline::kTrimIn:
snap_points_.append(ghost->GetIn());
snap_points_.push_back(ghost->GetIn());
break;
case Timeline::kTrimOut:
snap_points_.append(ghost->GetOut());
snap_points_.push_back(ghost->GetOut());
break;
default:
break;
+78 -1
View File
@@ -1,11 +1,88 @@
#include "record.h"
#include "widget/timelinewidget/timelinewidget.h"
namespace olive {
RecordTool::RecordTool(TimelineWidget *parent) :
BeamTool(parent)
BeamTool(parent),
ghost_(nullptr)
{
}
void RecordTool::MousePress(TimelineViewMouseEvent *event)
{
const Track::Reference& track = event->GetTrack();
// Check if track is locked
Track* t = parent()->GetTrackFromReference(track);
if (t && t->IsLocked()) {
return;
}
if (t->type() != Track::kAudio) {
// We only support audio tracks here
return;
}
drag_start_point_ = ValidatedCoordinate(event->GetCoordinates(true)).GetFrame();
ghost_ = new TimelineViewGhostItem();
ghost_->SetIn(drag_start_point_);
ghost_->SetOut(drag_start_point_);
ghost_->SetTrack(track);
parent()->AddGhost(ghost_);
snap_points_.push_back(drag_start_point_);
}
void RecordTool::MouseMove(TimelineViewMouseEvent *event)
{
if (!ghost_) {
return;
}
// Calculate movement
rational movement = event->GetFrame() - drag_start_point_;
// Validation: Ensure in point never goes below 0
if (movement < -ghost_->GetIn()) {
movement = -ghost_->GetIn();
}
// Snap movement
bool snapped;
if (Core::instance()->snapping()) {
snapped = parent()->SnapPoint(snap_points_, &movement);
} else {
snapped = false;
}
// Make adjustment
if (!movement) {
ghost_->SetInAdjustment(0);
ghost_->SetOutAdjustment(0);
} else if (movement > 0) {
ghost_->SetInAdjustment(0);
ghost_->SetOutAdjustment(movement);
} else if (movement < 0) {
ghost_->SetInAdjustment(movement);
ghost_->SetOutAdjustment(0);
}
Q_UNUSED(snapped)
}
void RecordTool::MouseRelease(TimelineViewMouseEvent *event)
{
if (ghost_) {
emit parent()->RequestCaptureStart(TimeRange(ghost_->GetAdjustedIn(), ghost_->GetAdjustedOut()), ghost_->GetTrack());
parent()->ClearGhosts();
snap_points_.clear();
ghost_ = nullptr;
}
}
}
+12
View File
@@ -29,6 +29,18 @@ class RecordTool : public BeamTool
{
public:
RecordTool(TimelineWidget* parent);
virtual void MousePress(TimelineViewMouseEvent *event) override;
virtual void MouseMove(TimelineViewMouseEvent *event) override;
virtual void MouseRelease(TimelineViewMouseEvent *event) override;
protected:
void MouseMoveInternal(const rational& cursor_frame, bool outwards);
TimelineViewGhostItem* ghost_;
rational drag_start_point_;
};
}
+1 -1
View File
@@ -78,7 +78,7 @@ protected:
void InsertGapsAtGhostDestination(MultiUndoCommand* command);
QVector<rational> snap_points_;
std::vector<rational> snap_points_;
bool dragging_;
@@ -73,7 +73,7 @@ void TransitionTool::MousePress(TimelineViewMouseEvent *event)
parent()->AddGhost(ghost_);
snap_points_.append(transition_start_point);
snap_points_.push_back(transition_start_point);
// Set the drag start point
drag_start_point_ = event->GetFrame();
+75 -12
View File
@@ -32,7 +32,10 @@
#include "common/qtutils.h"
#include "common/timecodefunctions.h"
#include "node/project/footage/footage.h"
#include "panel/panelmanager.h"
#include "panel/timeline/timeline.h"
#include "ui/colorcoding.h"
#include "widget/timelinewidget/timelinewidget.h"
namespace olive {
@@ -59,6 +62,22 @@ TimelineView::TimelineView(Qt::Alignment vertical_alignment, QWidget *parent) :
void TimelineView::mousePressEvent(QMouseEvent *event)
{
// If we click on marker, jump to that point in the timeline
QPointF scene_pos = mapToScene(event->pos());
for (auto it=clip_marker_rects_.cbegin(); it!=clip_marker_rects_.cend(); it++) {
if (it.value().contains(scene_pos)) {
QObject *p = this->parent();
while (p) {
if (TimelineWidget *timeline = dynamic_cast<TimelineWidget *>(p)) {
timeline->SetTime(it.key()->time());
break;
}
p = p->parent();
}
}
}
TimelineViewMouseEvent timeline_event = CreateMouseEvent(event);
if (HandPress(event)
@@ -329,6 +348,16 @@ void TimelineView::drawForeground(QPainter *painter, const QRectF &rect)
track_y + GetTrackHeight(track_index));
}
// Draw recording overlay
if (recording_overlay_ && recording_coord_.GetTrack().type() == connected_track_list_->type()) {
painter->setPen(QPen(Qt::red, 2));
painter->setBrush(QColor(255, 128, 128));
int x = TimeToScene(recording_coord_.GetFrame());
painter->drawRect(x, GetTrackY(recording_coord_.GetTrack().index()),
TimeToScene(GetTime()) - x, GetTrackHeight(recording_coord_.GetTrack().index()));
}
// Draw standard TimelineViewBase things (such as playhead)
super::drawForeground(painter, rect);
}
@@ -345,6 +374,7 @@ void TimelineView::ToolChangedEvent(Tool::Item tool)
case Tool::kAdd:
case Tool::kTransition:
case Tool::kZoom:
case Tool::kRecord :
setCursor(Qt::CrossCursor);
break;
case Tool::kTrackSelect:
@@ -497,21 +527,41 @@ void TimelineView::DrawBlock(QPainter *painter, bool foreground, Block *block, q
SceneToTime(block_left - block_in, GetScale(), connected_track_list_->parent()->GetAudioParams().sample_rate_as_time_base()));
}
// Draw zebra stripes
if (clip->connected_viewer() && !clip->connected_viewer()->GetLength().isNull()) {
if (clip->media_in() < 0) {
// Draw stripes for sections of clip < 0
qreal zebra_right = TimeToScene(-clip->media_in());
if (zebra_right > GetTimelineLeftBound()) {
DrawZebraStripes(painter, QRectF(block_left, block_top, zebra_right, block_height));
// Draw zebra stripes and markers
if (clip->connected_viewer()) {
if (!clip->connected_viewer()->GetLength().isNull()) {
if (clip->media_in() < 0) {
// Draw stripes for sections of clip < 0
qreal zebra_right = TimeToScene(-clip->media_in());
if (zebra_right > GetTimelineLeftBound()) {
DrawZebraStripes(painter, QRectF(block_left, block_top, zebra_right, block_height));
}
}
if (clip->length() + clip->media_in() > clip->connected_viewer()->GetLength()) {
// Draw stripes for sections for clip > clip length
qreal zebra_left = TimeToScene(clip->out() - (clip->media_in() + clip->length() - clip->connected_viewer()->GetLength()));
if (zebra_left < GetTimelineRightBound()) {
DrawZebraStripes(painter, QRectF(zebra_left, block_top, block_right - zebra_left, block_height));
}
}
}
if (clip->length() + clip->media_in() > clip->connected_viewer()->GetLength()) {
// Draw stripes for sections for clip > clip length
qreal zebra_left = TimeToScene(clip->out() - (clip->media_in() + clip->length() - clip->connected_viewer()->GetLength()));
if (zebra_left < GetTimelineRightBound()) {
DrawZebraStripes(painter, QRectF(zebra_left, block_top, block_right - zebra_left, block_height));
TimelineMarkerList *marker_list = clip->connected_viewer()->GetTimelinePoints()->markers();
if (!marker_list->empty()) {
clip_marker_rects_.clear();
for (auto it=marker_list->cbegin(); it!=marker_list->cend(); it++) {
TimelineMarker *marker = *it;
// Make sure marker is within In/Out points of the clip
if (marker->time_range().in() >= clip->media_in() && marker->time_range().out() <= clip->media_in() + clip->length()) {
QPoint marker_pt(TimeToScene(clip->in() - clip->media_in() + marker->time_range().in()), block_top + block_height);
painter->setClipRect(r);
QRect marker_rect = marker->Draw(painter, marker_pt, GetScale(), false);
clip_marker_rects_.insert(marker, marker_rect);
painter->setClipping(false);
}
}
}
}
@@ -706,6 +756,19 @@ void TimelineView::SetTransitionOverlay(ClipBlock *out, ClipBlock *in)
}
}
void TimelineView::EnableRecordingOverlay(const TimelineCoordinate &coord)
{
recording_overlay_ = true;
recording_coord_ = coord;
viewport()->update();
}
void TimelineView::DisableRecordingOverlay()
{
recording_overlay_ = false;
viewport()->update();
}
int TimelineView::SceneToTrack(double y)
{
int track = -1;
@@ -56,6 +56,8 @@ public:
void SetBeamCursor(const TimelineCoordinate& coord);
void SetTransitionOverlay(ClipBlock *out, ClipBlock *in);
void EnableRecordingOverlay(const TimelineCoordinate &coord);
void DisableRecordingOverlay();
void SetSelectionList(QHash<Track::Reference, TimeRangeList>* s)
{
@@ -155,6 +157,11 @@ private:
ClipBlock *transition_overlay_out_;
ClipBlock *transition_overlay_in_;
QMap<TimelineMarker*, QRectF> clip_marker_rects_;
bool recording_overlay_;
TimelineCoordinate recording_coord_;
private slots:
void TrackListChanged();
+216 -77
View File
@@ -20,21 +20,29 @@
#include "seekablewidget.h"
#include <QInputDialog>
#include <QMouseEvent>
#include <QPainter>
#include <QtMath>
#include "common/qtutils.h"
#include "core.h"
#include "dialog/markerproperties/markerpropertiesdialog.h"
#include "node/project/serializer/serializer.h"
#include "widget/colorlabelmenu/colorlabelmenu.h"
#include "widget/menu/menushared.h"
#include "widget/timebased/timebasedwidget.h"
namespace olive {
#define super TimeBasedView
SeekableWidget::SeekableWidget(QWidget* parent) :
TimelineScaledWidget(parent),
super(parent),
timeline_points_(nullptr),
scroll_(0),
snap_service_(nullptr),
dragging_(false)
dragging_(false),
ignore_next_focus_out_(false),
selection_manager_(this)
{
QFontMetrics fm = fontMetrics();
@@ -44,113 +52,214 @@ SeekableWidget::SeekableWidget(QWidget* parent) :
playhead_width_ = QtUtils::QFontMetricsWidth(fm, "H");
setContextMenuPolicy(Qt::CustomContextMenu);
setFocusPolicy(Qt::ClickFocus);
selection_manager_.SetSnapMask(TimeBasedWidget::kSnapAll & ~TimeBasedWidget::kSnapToMarkers);
}
void SeekableWidget::ConnectTimelinePoints(TimelinePoints *points)
{
if (timeline_points_) {
disconnect(timeline_points_->workarea(), &TimelineWorkArea::RangeChanged, this, static_cast<void (SeekableWidget::*)()>(&SeekableWidget::update));
disconnect(timeline_points_->workarea(), &TimelineWorkArea::EnabledChanged, this, static_cast<void (SeekableWidget::*)()>(&SeekableWidget::update));
disconnect(timeline_points_->markers(), &TimelineMarkerList::MarkerAdded, this, static_cast<void (SeekableWidget::*)()>(&SeekableWidget::update));
disconnect(timeline_points_->markers(), &TimelineMarkerList::MarkerRemoved, this, static_cast<void (SeekableWidget::*)()>(&SeekableWidget::update));
selection_manager_.ClearSelection();
disconnect(timeline_points_->workarea(), &TimelineWorkArea::RangeChanged, viewport(), static_cast<void (QWidget::*)()>(&QWidget::update));
disconnect(timeline_points_->workarea(), &TimelineWorkArea::EnabledChanged, viewport(), static_cast<void (QWidget::*)()>(&QWidget::update));
disconnect(timeline_points_->markers(), &TimelineMarkerList::MarkerAdded, viewport(), static_cast<void (QWidget::*)()>(&QWidget::update));
disconnect(timeline_points_->markers(), &TimelineMarkerList::MarkerRemoved, viewport(), static_cast<void (QWidget::*)()>(&QWidget::update));
disconnect(timeline_points_->markers(), &TimelineMarkerList::MarkerModified, viewport(), static_cast<void (QWidget::*)()>(&QWidget::update));
}
timeline_points_ = points;
if (timeline_points_) {
connect(timeline_points_->workarea(), &TimelineWorkArea::RangeChanged, this, static_cast<void (SeekableWidget::*)()>(&SeekableWidget::update));
connect(timeline_points_->workarea(), &TimelineWorkArea::EnabledChanged, this, static_cast<void (SeekableWidget::*)()>(&SeekableWidget::update));
connect(timeline_points_->markers(), &TimelineMarkerList::MarkerAdded, this, static_cast<void (SeekableWidget::*)()>(&SeekableWidget::update));
connect(timeline_points_->markers(), &TimelineMarkerList::MarkerRemoved, this, static_cast<void (SeekableWidget::*)()>(&SeekableWidget::update));
connect(timeline_points_->workarea(), &TimelineWorkArea::RangeChanged, viewport(), static_cast<void (QWidget::*)()>(&QWidget::update));
connect(timeline_points_->workarea(), &TimelineWorkArea::EnabledChanged, viewport(), static_cast<void (QWidget::*)()>(&QWidget::update));
connect(timeline_points_->markers(), &TimelineMarkerList::MarkerAdded, viewport(), static_cast<void (QWidget::*)()>(&QWidget::update));
connect(timeline_points_->markers(), &TimelineMarkerList::MarkerRemoved, viewport(), static_cast<void (QWidget::*)()>(&QWidget::update));
connect(timeline_points_->markers(), &TimelineMarkerList::MarkerModified, viewport(), static_cast<void (QWidget::*)()>(&QWidget::update));
}
update();
viewport()->update();
}
void SeekableWidget::SetSnapService(SnapService *service)
void SeekableWidget::DeleteSelected()
{
snap_service_ = service;
MultiUndoCommand* command = new MultiUndoCommand();
foreach (TimelineMarker *marker, selection_manager_.GetSelectedObjects()) {
command->add_child(new MarkerRemoveCommand(marker));
}
Core::instance()->undo_stack()->pushIfHasChildren(command);
}
const int &SeekableWidget::GetScroll() const
bool SeekableWidget::CopySelected(bool cut)
{
return scroll_;
if (!selection_manager_.GetSelectedObjects().empty()) {
ProjectSerializer::SaveData sdata(Project::GetProjectFromObject(timeline_points_));
sdata.SetOnlySerializeMarkers(selection_manager_.GetSelectedObjects());
ProjectSerializer::Copy(sdata, QStringLiteral("markers"));
if (cut) {
DeleteSelected();
}
return true;
} else {
return false;
}
}
bool SeekableWidget::PasteMarkers(bool insert, rational insert_time)
{
ProjectSerializer::Result res = ProjectSerializer::Paste(QStringLiteral("markers"));
if (res == ProjectSerializer::kSuccess) {
const std::vector<TimelineMarker*> &markers = res.GetLoadData().markers;
if (!markers.empty()) {
MultiUndoCommand *command = new MultiUndoCommand();
// Normalize markers to start at playhead
rational min = RATIONAL_MAX;
for (auto it=markers.cbegin(); it!=markers.cend(); it++) {
min = qMin(min, (*it)->time());
}
min -= GetTime();
// Avoid duplicates
bool loop;
do {
loop = false;
for (auto it=markers.cbegin(); it!=markers.cend(); it++) {
rational proposed_time = (*it)->time() - min;
if (timeline_points_->markers()->GetMarkerAtTime(proposed_time)) {
min -= timebase();
loop = true;
break;
}
}
} while (loop);
for (auto it=markers.cbegin(); it!=markers.cend(); it++) {
TimelineMarker *m = *it;
m->set_time(m->time() - min);
command->add_child(new MarkerAddCommand(timeline_points_->markers(), m));
}
Core::instance()->undo_stack()->push(command);
return true;
}
}
return false;
}
void SeekableWidget::mousePressEvent(QMouseEvent *event)
{
if (event->button() == Qt::LeftButton) {
SeekToScreenPoint(event->pos().x());
if (TimelineMarker *initial = selection_manager_.MousePress(event)) {
selection_manager_.DragStart(initial, event);
} else if (!selection_manager_.GetObjectAtPoint(event->pos()) && event->button() == Qt::LeftButton) {
SeekToScenePoint(mapToScene(event->pos()).x());
dragging_ = true;
DeselectAllMarkers();
}
}
void SeekableWidget::mouseMoveEvent(QMouseEvent *event)
{
if (event->buttons() & Qt::LeftButton) {
SeekToScreenPoint(event->pos().x());
if (selection_manager_.IsDragging()) {
selection_manager_.DragMove(event);
} else if (dragging_) {
SeekToScenePoint(mapToScene(event->pos()).x());
}
}
void SeekableWidget::mouseReleaseEvent(QMouseEvent *event)
{
Q_UNUSED(event)
if (selection_manager_.IsDragging()) {
MultiUndoCommand *command = new MultiUndoCommand();
selection_manager_.DragStop(command);
Core::instance()->undo_stack()->pushIfHasChildren(command);
}
if (snap_service_) {
snap_service_->HideSnaps();
if (GetSnapService()) {
GetSnapService()->HideSnaps();
}
dragging_ = false;
}
void SeekableWidget::ScaleChangedEvent(const double &)
void SeekableWidget::mouseDoubleClickEvent(QMouseEvent *event)
{
update();
super::mouseDoubleClickEvent(event);
if (selection_manager_.GetObjectAtPoint(event->pos()) && !selection_manager_.GetSelectedObjects().empty()) {
ShowMarkerProperties();
}
}
TimelinePoints *SeekableWidget::timeline_points() const
void SeekableWidget::focusOutEvent(QFocusEvent *event)
{
return timeline_points_;
super::focusOutEvent(event);
if (ignore_next_focus_out_) {
ignore_next_focus_out_ = false;
} else {
// Deselect everything when we lose focus
DeselectAllMarkers();
}
}
void SeekableWidget::SetTime(const rational &r)
void SeekableWidget::DeselectAllMarkers()
{
time_ = r;
selection_manager_.ClearSelection();
update();
viewport()->update();
}
void SeekableWidget::SetScroll(int s)
void SeekableWidget::SetMarkerColor(int c)
{
scroll_ = s;
MultiUndoCommand *command = new MultiUndoCommand();
update();
foreach(TimelineMarker* marker, selection_manager_.GetSelectedObjects()) {
command->add_child(new MarkerChangeColorCommand(marker, c));
}
Core::instance()->undo_stack()->pushIfHasChildren(command);
}
int SeekableWidget::TimeToScreen(const rational &time) const
void SeekableWidget::ShowMarkerProperties()
{
return qFloor(TimeToScene(time)) - scroll_;
MarkerPropertiesDialog mpd(selection_manager_.GetSelectedObjects(), timebase(), this);
ignore_next_focus_out_ = true;
mpd.exec();
}
rational SeekableWidget::ScreenToTime(int x) const
void SeekableWidget::TimebaseChangedEvent(const rational &t)
{
return qMax(rational(0), SceneToTime(x + scroll_));
super::TimebaseChangedEvent(t);
selection_manager_.SetTimebase(t);
}
void SeekableWidget::SeekToScreenPoint(int screen)
void SeekableWidget::SeekToScenePoint(qreal scene)
{
if (timebase().isNull()) {
return;
}
rational playhead_time = ScreenToTime(screen);
rational playhead_time = SceneToTime(scene);
if (Core::instance()->snapping() && snap_service_) {
if (Core::instance()->snapping() && GetSnapService()) {
rational movement;
snap_service_->SnapPoint({playhead_time},
&movement,
SnapService::kSnapAll & ~SnapService::kSnapToPlayhead);
GetSnapService()->SnapPoint({playhead_time},
&movement,
TimeBasedWidget::kSnapAll & ~TimeBasedWidget::kSnapToPlayhead);
playhead_time += movement;
}
@@ -162,59 +271,62 @@ void SeekableWidget::SeekToScreenPoint(int screen)
}
}
void SeekableWidget::SelectionManagerSelectEvent(void *obj)
{
super::SelectionManagerSelectEvent(obj);
viewport()->update();
}
void SeekableWidget::SelectionManagerDeselectEvent(void *obj)
{
super::SelectionManagerDeselectEvent(obj);
viewport()->update();
}
void SeekableWidget::DrawTimelinePoints(QPainter* p, int marker_bottom)
{
if (!timeline_points()) {
if (!GetTimelinePoints()) {
return;
}
int lim_left = GetScroll();
int lim_right = lim_left + width();
selection_manager_.ClearDrawnObjects();
// Draw in/out workarea
if (timeline_points()->workarea()->enabled()) {
int workarea_left = qMax(0, TimeToScreen(timeline_points()->workarea()->in()));
if (GetTimelinePoints()->workarea()->enabled()) {
int workarea_left = qMax(qreal(lim_left), TimeToScene(GetTimelinePoints()->workarea()->in()));
int workarea_right;
if (timeline_points()->workarea()->out() == TimelineWorkArea::kResetOut) {
workarea_right = width();
if (GetTimelinePoints()->workarea()->out() == TimelineWorkArea::kResetOut) {
workarea_right = lim_right;
} else {
workarea_right = qMin(width(), TimeToScreen(timeline_points()->workarea()->out()));
workarea_right = qMin(qreal(lim_right), TimeToScene(GetTimelinePoints()->workarea()->out()));
}
p->fillRect(workarea_left, 0, workarea_right - workarea_left, height(), palette().highlight());
}
// Draw markers
if (marker_bottom > 0 && !timeline_points()->markers()->list().isEmpty()) {
if (marker_bottom > 0 && !GetTimelinePoints()->markers()->empty()) {
for (auto it=GetTimelinePoints()->markers()->cbegin(); it!=GetTimelinePoints()->markers()->cend(); it++) {
TimelineMarker* marker = *it;
int marker_top = marker_bottom - text_height_;
// FIXME: Hardcoded marker colors
p->setPen(Qt::black);
p->setBrush(Qt::green);
foreach (TimelineMarker* marker, timeline_points()->markers()->list()) {
int marker_left = TimeToScreen(marker->time().in());
int marker_right = TimeToScreen(marker->time().out());
if (marker_left >= width() || marker_right < 0) {
int marker_right = TimeToScene(marker->time_range().out());
if (marker_right < lim_left) {
continue;
}
if (marker->time().length() == 0) {
// Single point in time marker
DrawPlayhead(p, marker_left, marker_bottom);
} else {
// Marker range
int rect_left = qMax(0, marker_left);
int rect_right = qMin(width(), marker_right);
QRect marker_rect(rect_left, marker_top, rect_right - rect_left, marker_bottom - marker_top);
p->drawRect(marker_rect);
if (!marker->name().isEmpty()) {
p->drawText(marker_rect, marker->name());
}
int marker_left = TimeToScene(marker->time_range().in());
if (marker_left >= lim_right) {
break;
}
QRect marker_rect = marker->Draw(p, QPoint(marker_left, marker_bottom), GetScale(), selection_manager_.IsSelected(marker));
selection_manager_.DeclareDrawnObject(marker, marker_rect);
}
}
}
@@ -245,4 +357,31 @@ void SeekableWidget::DrawPlayhead(QPainter *p, int x, int y)
p->setRenderHint(QPainter::Antialiasing, false);
}
bool SeekableWidget::ShowContextMenu(const QPoint &p)
{
if (selection_manager_.GetObjectAtPoint(p) && !selection_manager_.GetSelectedObjects().empty()) {
// Show marker-specific menu
Menu m;
ColorLabelMenu color_coding_menu;
connect(&color_coding_menu, &ColorLabelMenu::ColorSelected, this, &SeekableWidget::SetMarkerColor);
m.addMenu(&color_coding_menu);
m.addSeparator();
MenuShared::instance()->AddItemsForEditMenu(&m, false);
m.addSeparator();
QAction *properties_action = m.addAction(tr("Properties"));
connect(properties_action, &QAction::triggered, this, &SeekableWidget::ShowMarkerProperties);
ignore_next_focus_out_ = true;
m.exec(mapToGlobal(p));
return true;
} else {
return false;
}
}
}
+41 -31
View File
@@ -21,56 +21,66 @@
#ifndef SEEKABLEWIDGET_H
#define SEEKABLEWIDGET_H
#include <QHBoxLayout>
#include <QScrollBar>
#include "common/rational.h"
#include "timeline/timelinepoints.h"
#include "widget/snapservice/snapservice.h"
#include "widget/timebased/timescaledobject.h"
#include "widget/menu/menu.h"
#include "widget/timebased/timebasedviewselectionmanager.h"
namespace olive {
class SeekableWidget : public TimelineScaledWidget
class SeekableWidget : public TimeBasedView
{
Q_OBJECT
public:
SeekableWidget(QWidget *parent = nullptr);
const rational& GetTime() const
int GetScroll() const
{
return time_;
return horizontalScrollBar()->value();
}
const int& GetScroll() const;
TimelinePoints* GetTimelinePoints() const { return timeline_points_; }
void ConnectTimelinePoints(TimelinePoints* points);
void SetSnapService(SnapService* service);
bool IsDraggingPlayhead() const
{
return dragging_;
}
public slots:
void SetTime(const rational &r);
void DeleteSelected();
void SetScroll(int s);
bool CopySelected(bool cut);
bool PasteMarkers(bool insert, rational insert_time);
void DeselectAllMarkers();
void SeekToScenePoint(qreal scene);
virtual void SelectionManagerSelectEvent(void *obj) override;
virtual void SelectionManagerDeselectEvent(void *obj) override;
public slots:
void SetScroll(int i)
{
horizontalScrollBar()->setValue(i);
}
virtual void TimebaseChangedEvent(const rational &) override;
protected:
void SeekToScreenPoint(int screen);
virtual void mousePressEvent(QMouseEvent *event) override;
virtual void mouseMoveEvent(QMouseEvent *event) override;
virtual void mouseReleaseEvent(QMouseEvent *event) override;
virtual void mouseDoubleClickEvent(QMouseEvent *event) override;
virtual void ScaleChangedEvent(const double&) override;
virtual void focusOutEvent(QFocusEvent *event) override;
void DrawTimelinePoints(QPainter *p, int marker_bottom = 0);
TimelinePoints* timeline_points() const;
int TimeToScreen(const rational& time) const;
rational ScreenToTime(int x) const;
void DrawPlayhead(QPainter* p, int x, int y);
inline const int& text_height() const {
@@ -81,27 +91,27 @@ protected:
return playhead_width_;
}
signals:
/**
* @brief Signal emitted whenever the time changes on this ruler, either by user or programmatically
*/
void TimeChanged(const rational &time);
protected slots:
virtual bool ShowContextMenu(const QPoint &p);
private:
rational time_;
TimelinePoints* timeline_points_;
int scroll_;
int text_height_;
int playhead_width_;
SnapService* snap_service_;
bool dragging_;
bool ignore_next_focus_out_;
TimeBasedViewSelectionManager<TimelineMarker> selection_manager_;
private slots:
void SetMarkerColor(int c);
void ShowMarkerProperties();
};
}
+61 -49
View File
@@ -32,8 +32,10 @@
namespace olive {
#define super SeekableWidget
TimeRuler::TimeRuler(bool text_visible, bool cache_status_visible, QWidget* parent) :
SeekableWidget(parent),
super(parent),
text_visible_(text_visible),
centered_text_(true),
show_cache_status_(cache_status_visible),
@@ -58,6 +60,17 @@ TimeRuler::TimeRuler(bool text_visible, bool cache_status_visible, QWidget* pare
// Connect context menu
connect(this, &TimeRuler::customContextMenuRequested, this, &TimeRuler::ShowContextMenu);
setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
//horizontalScrollBar()->setVisible(false);
setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
setBackgroundRole(QPalette::Window);
setFrameShape(QFrame::NoFrame);
// NOTE: One day it might be preferable to use AlignBottom because the lines are anchored to
// the bottom of the widget. However, for now this makes sense since we just ported this
// from a QWidget's paintEvent.
setAlignment(Qt::AlignLeft | Qt::AlignTop);
}
void TimeRuler::SetPlaybackCache(PlaybackCache *cache)
@@ -83,28 +96,17 @@ void TimeRuler::SetPlaybackCache(PlaybackCache *cache)
update();
}
void TimeRuler::paintEvent(QPaintEvent *)
void TimeRuler::drawForeground(QPainter *p, const QRectF &rect)
{
// Nothing to paint if the timebase is invalid
if (timebase().isNull()) {
return;
}
QPainter p(this);
// Draw timeline points if connected
if (timeline_points()) {
int marker_bottom = height() - text_height();
if (show_cache_status_) {
marker_bottom -= cache_status_height_;
}
if (text_visible_) {
marker_bottom -= cache_status_height_;
}
DrawTimelinePoints(&p, marker_bottom);
int marker_height = TimelineMarker::GetMarkerHeight(p->fontMetrics());
if (GetTimelinePoints()) {
DrawTimelinePoints(p, marker_height);
}
double width_of_frame = timebase_dbl() * GetScale();
@@ -173,11 +175,11 @@ void TimeRuler::paintEvent(QPaintEvent *)
}
// Set line color to main text color
p.setBrush(Qt::NoBrush);
p.setPen(palette().text().color());
p->setBrush(Qt::NoBrush);
p->setPen(palette().text().color());
// Calculate line dimensions
QFontMetrics fm = p.fontMetrics();
QFontMetrics fm = p->fontMetrics();
int line_bottom = height();
if (show_cache_status_) {
@@ -197,8 +199,8 @@ void TimeRuler::paintEvent(QPaintEvent *)
// FIXME: Hardcoded number
const int kAverageTextWidth = 200;
for (int i=-kAverageTextWidth;i<width()+kAverageTextWidth;i++) {
double screen_pt = static_cast<double>(i + GetScroll());
for (int i=GetScroll()-kAverageTextWidth;i<GetScroll()+width()+kAverageTextWidth;i++) {
double screen_pt = static_cast<double>(i);
if (long_interval > -1) {
int this_long_unit = qFloor(screen_pt/long_interval);
@@ -208,16 +210,16 @@ void TimeRuler::paintEvent(QPaintEvent *)
if (text_visible_) {
QRect text_rect;
Qt::Alignment text_align;
QString timecode_str = Timecode::time_to_timecode(ScreenToTime(i), timebase(), Core::instance()->GetTimecodeDisplay());
QString timecode_str = Timecode::time_to_timecode(SceneToTime(i), timebase(), Core::instance()->GetTimecodeDisplay());
int timecode_width = QtUtils::QFontMetricsWidth(fm, timecode_str);
int timecode_left;
if (centered_text_) {
text_rect = QRect(i - kAverageTextWidth/2, 0, kAverageTextWidth, fm.height());
text_rect = QRect(i - kAverageTextWidth/2, marker_height, kAverageTextWidth, fm.height());
text_align = Qt::AlignCenter;
timecode_left = i - timecode_width/2;
} else {
text_rect = QRect(i, 0, kAverageTextWidth, fm.height());
text_rect = QRect(i, marker_height, kAverageTextWidth, fm.height());
text_align = Qt::AlignLeft | Qt::AlignVCenter;
timecode_left = i;
@@ -226,9 +228,9 @@ void TimeRuler::paintEvent(QPaintEvent *)
}
if (timecode_left > last_text_draw) {
p.drawText(text_rect,
static_cast<int>(text_align),
timecode_str);
p->drawText(text_rect,
static_cast<int>(text_align),
timecode_str);
last_text_draw = timecode_left + timecode_width;
@@ -238,7 +240,7 @@ void TimeRuler::paintEvent(QPaintEvent *)
}
}
p.drawLine(i, line_y, i, line_bottom);
p->drawLine(i, line_y, i, line_bottom);
last_long_unit = this_long_unit;
}
}
@@ -246,7 +248,7 @@ void TimeRuler::paintEvent(QPaintEvent *)
if (short_interval > -1) {
int this_short_unit = qFloor(screen_pt/short_interval);
if (this_short_unit != last_short_unit) {
p.drawLine(i, short_y, i, line_bottom);
p->drawLine(i, short_y, i, line_bottom);
last_short_unit = this_short_unit;
}
}
@@ -256,45 +258,49 @@ void TimeRuler::paintEvent(QPaintEvent *)
if (show_cache_status_ && playback_cache_) {
// FIXME: Hardcoded to get video length, if we ever need audio length, this will have to change
rational len = playback_cache_->viewer_parent()->GetVideoLength();
int lim_left = GetScroll();
int lim_right = lim_left + width();
int cache_screen_length = qMin(TimeToScreen(len), width());
int cache_screen_length = TimeToScene(len);
if (cache_screen_length > 0) {
int cache_y = height() - cache_status_height_;
p.fillRect(0, cache_y, cache_screen_length , cache_status_height_, Qt::green);
p->fillRect(0, cache_y, cache_screen_length, cache_status_height_, Qt::green);
foreach (const TimeRange& range, playback_cache_->GetInvalidatedRanges(len)) {
int range_left = TimeToScreen(range.in());
int range_left = TimeToScene(range.in());
if (range_left >= width()) {
continue;
}
int range_right = TimeToScreen(range.out());
int range_right = TimeToScene(range.out());
if (range_right < 0) {
continue;
}
int adjusted_left = qMax(0, range_left);
int adjusted_left = qMax(lim_left, range_left);
p.fillRect(adjusted_left,
cache_y,
qMin(width(), range_right) - adjusted_left,
cache_status_height_,
Qt::red);
p->fillRect(adjusted_left,
cache_y,
qMin(lim_right, range_right) - adjusted_left,
cache_status_height_,
Qt::red);
}
}
}
// Draw the playhead if it's on screen at the moment
int playhead_pos = TimeToScreen(GetTime());
p.setPen(Qt::NoPen);
p.setBrush(PLAYHEAD_COLOR);
DrawPlayhead(&p, playhead_pos, line_bottom);
int playhead_pos = TimeToScene(GetTime());
p->setPen(Qt::NoPen);
p->setBrush(PLAYHEAD_COLOR);
DrawPlayhead(p, playhead_pos, line_bottom);
}
void TimeRuler::TimebaseChangedEvent(const rational &tb)
{
super::TimebaseChangedEvent(tb);
timebase_flipped_dbl_ = tb.flipped().toDouble();
update();
@@ -305,14 +311,20 @@ int TimeRuler::CacheStatusHeight() const
return fontMetrics().height() / 4;
}
void TimeRuler::ShowContextMenu()
bool TimeRuler::ShowContextMenu(const QPoint &p)
{
Menu m(this);
if (super::ShowContextMenu(p)) {
return true;
} else {
Menu m(this);
MenuShared::instance()->AddItemsForTimeRulerMenu(&m);
MenuShared::instance()->AboutToShowTimeRulerActions(timebase());
MenuShared::instance()->AddItemsForTimeRulerMenu(&m);
MenuShared::instance()->AboutToShowTimeRulerActions(timebase());
m.exec(QCursor::pos());
m.exec(mapToGlobal(p));
return true;
}
}
void TimeRuler::UpdateHeight()
@@ -330,7 +342,7 @@ void TimeRuler::UpdateHeight()
}
// Add marker height
height += text_height();
height += TimelineMarker::GetMarkerHeight(fontMetrics());
setFixedHeight(height);
}
+4 -4
View File
@@ -41,10 +41,13 @@ public:
void SetPlaybackCache(PlaybackCache* cache);
protected:
virtual void paintEvent(QPaintEvent* e) override;
virtual void drawForeground(QPainter *painter, const QRectF &rect) override;
virtual void TimebaseChangedEvent(const rational& tb) override;
protected slots:
virtual bool ShowContextMenu(const QPoint &p) override;
private:
void UpdateHeight();
@@ -64,9 +67,6 @@ private:
PlaybackCache* playback_cache_;
private slots:
void ShowContextMenu();
};
}
+1 -1
View File
@@ -126,7 +126,7 @@ void Toolbar::Retranslate()
void Toolbar::UpdateIcons()
{
btn_pointer_tool_->setIcon(icon::ToolPointer);
btn_trackselect_tool_->setIcon(icon::TriRight); // FIXME: Procure real icon
btn_trackselect_tool_->setIcon(icon::ToolTrackSelect);
btn_edit_tool_->setIcon(icon::ToolEdit);
btn_ripple_tool_->setIcon(icon::ToolRipple);
btn_rolling_tool_->setIcon(icon::ToolRolling);
+15 -10
View File
@@ -38,6 +38,13 @@ AudioWaveformView::AudioWaveformView(QWidget *parent) :
{
setAutoFillBackground(true);
setBackgroundRole(QPalette::Base);
setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
// NOTE: At some point it might make sense for this to be AlignCenter since the waveform
// originates from the center. But we're leaving it top/left for now since it was just
// ported from a QWidget's paintEvent.
setAlignment(Qt::AlignLeft | Qt::AlignTop);
}
void AudioWaveformView::SetViewer(AudioPlaybackCache *playback)
@@ -60,9 +67,9 @@ void AudioWaveformView::SetViewer(AudioPlaybackCache *playback)
}
}
void AudioWaveformView::paintEvent(QPaintEvent *event)
void AudioWaveformView::drawForeground(QPainter *p, const QRectF &rect)
{
super::paintEvent(event);
super::drawForeground(p, rect);
if (!playback_) {
return;
@@ -74,20 +81,18 @@ void AudioWaveformView::paintEvent(QPaintEvent *event)
return;
}
QPainter p(this);
// Draw in/out points
DrawTimelinePoints(&p);
DrawTimelinePoints(p);
// Draw waveform
p.setPen(QColor(64, 255, 160)); // FIXME: Hardcoded color
AudioVisualWaveform::DrawWaveform(&p, rect(), GetScale(), playback_->visual(), SceneToTime(GetScroll()));
p->setPen(QColor(64, 255, 160)); // FIXME: Hardcoded color
AudioVisualWaveform::DrawWaveform(p, rect.toRect(), GetScale(), playback_->visual(), SceneToTime(GetScroll()));
// Draw playhead
p.setPen(PLAYHEAD_COLOR);
p->setPen(PLAYHEAD_COLOR);
int playhead_x = TimeToScreen(GetTime());
p.drawLine(playhead_x, 0, playhead_x, height());
int playhead_x = TimeToScene(GetTime());
p->drawLine(playhead_x, 0, playhead_x, height());
}
}
+1 -1
View File
@@ -39,7 +39,7 @@ public:
void SetViewer(AudioPlaybackCache *playback);
protected:
virtual void paintEvent(QPaintEvent* event) override;
virtual void drawForeground(QPainter *painter, const QRectF &rect) override;
private:
QThreadPool pool_;
+76 -12
View File
@@ -43,6 +43,7 @@
#include "viewerpreventsleep.h"
#include "widget/menu/menu.h"
#include "window/mainwindow/mainwindow.h"
#include "widget/timeruler/timeruler.h"
namespace olive {
@@ -64,7 +65,9 @@ ViewerWidget::ViewerWidget(QWidget *parent) :
color_menu_enabled_(true),
time_changed_from_timer_(false),
prequeuing_video_(false),
prequeuing_audio_(0)
prequeuing_audio_(0),
record_armed_(false),
recording_(false)
{
// Set up main layout
QVBoxLayout* layout = new QVBoxLayout(this);
@@ -97,6 +100,7 @@ ViewerWidget::ViewerWidget(QWidget *parent) :
// Create waveform view when audio is connected and video isn't
waveform_view_ = new AudioWaveformView();
ConnectTimelineView(waveform_view_, true);
PassWheelEventsToScrollBar(waveform_view_);
stack_->addWidget(waveform_view_);
@@ -125,7 +129,6 @@ ViewerWidget::ViewerWidget(QWidget *parent) :
SetScale(48.0);
// Ensures that seeking on the waveform view updates the time as expected
connect(waveform_view_, &AudioWaveformView::TimeChanged, this, &ViewerWidget::SetTimeAndSignal);
connect(waveform_view_, &AudioWaveformView::customContextMenuRequested, this, &ViewerWidget::ShowContextMenu);
connect(&playback_backup_timer_, &QTimer::timeout, this, &ViewerWidget::PlaybackTimerUpdate);
@@ -157,6 +160,10 @@ void ViewerWidget::TimeChangedEvent(const rational &time)
PauseInternal();
}
if (record_armed_) {
DisarmRecording();
}
controls_->SetTime(time);
waveform_view_->SetTime(time);
@@ -376,6 +383,17 @@ void ViewerWidget::SetGizmos(Node *node)
display_widget_->SetGizmos(node);
}
void ViewerWidget::StartCapture(TimelineWidget *source, const TimeRange &time, const Track::Reference &track)
{
SetTimeAndSignal(time.in());
ArmForRecording();
recording_filename_ = QStringLiteral("/home/matt/Desktop/ass.mp3");
recording_callback_ = source;
recording_range_ = time;
recording_track_ = track;
}
FramePtr ViewerWidget::DecodeCachedImage(const QString &cache_path, const QByteArray& hash, const rational& time)
{
FramePtr frame = FrameHashCache::LoadCacheFrame(cache_path, hash);
@@ -427,6 +445,18 @@ void ViewerWidget::DecrementPrequeuedAudio()
}
}
void ViewerWidget::ArmForRecording()
{
controls_->StartPlayBlink();
record_armed_ = true;
}
void ViewerWidget::DisarmRecording()
{
controls_->StopPlayBlink();
record_armed_ = false;
}
void ViewerWidget::QueueNextAudioBuffer()
{
rational queue_end = audio_playback_queue_time_ + (kAudioPlaybackInterval * playback_speed_);
@@ -594,13 +624,20 @@ void ViewerWidget::PlayInternal(int speed, bool in_to_out_only)
viewer->auto_cacher_.SetAudioPaused(true);
}
// Disarm recording if armed
if (record_armed_) {
DisarmRecording();
}
// If the playhead is beyond the end, restart at 0
rational last_frame = GetConnectedNode()->GetLength() - timebase();
if (!in_to_out_only && GetTime() >= last_frame) {
if (speed > 0) {
SetTimeAndSignal(0);
} else {
SetTimeAndSignal(last_frame);
if (!recording_) {
rational last_frame = GetConnectedNode()->GetLength() - timebase();
if (!in_to_out_only && GetTime() >= last_frame) {
if (speed > 0) {
SetTimeAndSignal(0);
} else {
SetTimeAndSignal(last_frame);
}
}
}
@@ -656,6 +693,15 @@ void ViewerWidget::PlayInternal(int speed, bool in_to_out_only)
void ViewerWidget::PauseInternal()
{
if (recording_) {
AudioManager::instance()->StopRecording();
recording_ = false;
controls_->SetPauseButtonRecordingState(false);
recording_callback_->DisableRecordingOverlay();
recording_callback_->RecordingCallback(recording_filename_, recording_range_, recording_track_);
}
if (IsPlaying()) {
playback_speed_ = 0;
controls_->ShowPlayButton();
@@ -1120,6 +1166,17 @@ void ViewerWidget::Play(bool in_to_out_only)
} else {
in_to_out_only = false;
}
} else if (record_armed_) {
if (AudioManager::instance()->StartRecording(recording_filename_, GetConnectedNode()->GetAudioParams())) {
recording_ = true;
controls_->SetPauseButtonRecordingState(true);
recording_callback_->EnableRecordingOverlay(TimelineCoordinate(recording_range_.in(), recording_track_));
} else {
QMessageBox::critical(this, tr("Audio Recording"), tr("Failed to start audio recording"));
return;
}
DisarmRecording();
}
PlayInternal(1, in_to_out_only);
@@ -1204,7 +1261,13 @@ void ViewerWidget::PlaybackTimerUpdate()
rational min_time, max_time;
if (play_in_to_out_only_ && GetConnectedNode()->GetTimelinePoints()->workarea()->enabled()) {
if (recording_ && recording_range_.out() != recording_range_.in()) {
// Limit recording range if applicable
min_time = recording_range_.in();
max_time = recording_range_.out();
} else if (play_in_to_out_only_ && GetConnectedNode()->GetTimelinePoints()->workarea()->enabled()) {
// If "play in to out" is enabled or we're looping AND we have a workarea, only play the workarea
min_time = GetConnectedNode()->GetTimelinePoints()->workarea()->in();
@@ -1228,8 +1291,9 @@ void ViewerWidget::PlaybackTimerUpdate()
bool end_of_line = false;
bool play_after_pause = false;
if ((playback_speed_ < 0 && current_time <= min_time)
|| (playback_speed_ > 0 && current_time >= max_time)) {
if ((!recording_ || recording_range_.out() != recording_range_.in())
&& ((playback_speed_ < 0 && current_time <= min_time)
|| (playback_speed_ > 0 && current_time >= max_time))) {
// Determine which timestamp we tripped
rational tripped_time;
@@ -1244,7 +1308,7 @@ void ViewerWidget::PlaybackTimerUpdate()
// or restart playback
end_of_line = true;
if (Config::Current()[QStringLiteral("Loop")].toBool()) {
if (Config::Current()[QStringLiteral("Loop")].toBool() && !recording_) {
// If we're looping, jump to the other side of the workarea and continue
time_to_set = (tripped_time == min_time) ? max_time : min_time;
+14
View File
@@ -41,6 +41,7 @@
#include "viewerwindow.h"
#include "widget/playbackcontrols/playbackcontrols.h"
#include "widget/timebased/timebasedwidget.h"
#include "widget/timelinewidget/timelinewidget.h"
namespace olive {
@@ -87,6 +88,8 @@ public:
void SetGizmos(Node* node);
void StartCapture(TimelineWidget *source, const TimeRange &time, const Track::Reference &track);
public slots:
void Play(bool in_to_out_only);
@@ -205,6 +208,10 @@ private:
void DecrementPrequeuedAudio();
void ArmForRecording();
void DisarmRecording();
QStackedWidget* stack_;
ViewerSizer* sizer_;
@@ -255,6 +262,13 @@ private:
static QVector<ViewerWidget*> instances_;
bool record_armed_;
bool recording_;
TimelineWidget *recording_callback_;
TimeRange recording_range_;
Track::Reference recording_track_;
QString recording_filename_;
private slots:
void PlaybackTimerUpdate();
+1 -1
View File
@@ -519,7 +519,7 @@ void ViewerDisplayWidget::OnPaint()
QPainter p(inner_widget());
p.setWorldTransform(GenerateWorldTransform());
p.setPen(Qt::lightGray);
p.setPen(QPen(Qt::lightGray, 0));
p.setBrush(Qt::NoBrush);
int x = 0, y = 0, w = width(), h = height();
+3 -2
View File
@@ -359,7 +359,7 @@ ViewerTextEditorToolBar::ViewerTextEditorToolBar(QWidget *parent) :
strikethrough_btn_ = new QPushButton();
connect(strikethrough_btn_, &QPushButton::clicked, this, &ViewerTextEditorToolBar::StrikethroughChanged);
strikethrough_btn_->setCheckable(true);
strikethrough_btn_->setText(tr("S")); // FIXME: Source icon
strikethrough_btn_->setIcon(icon::TextStrikethrough);
basic_layout->addWidget(strikethrough_btn_);
basic_layout->addWidget(QtUtils::CreateVerticalLine());
@@ -441,7 +441,8 @@ ViewerTextEditorToolBar::ViewerTextEditorToolBar(QWidget *parent) :
connect(line_height_slider_, &FloatSlider::ValueChanged, this, &ViewerTextEditorToolBar::LineHeightChanged);
advanced_layout->addWidget(line_height_slider_);
small_caps_btn_ = new QPushButton(tr("Small Caps")); // FIXME: Procure icon
small_caps_btn_ = new QPushButton();
small_caps_btn_->setIcon(icon::TextSmallCaps);
small_caps_btn_->setCheckable(true);
connect(small_caps_btn_, &QPushButton::clicked, this, &ViewerTextEditorToolBar::SmallCapsChanged);
advanced_layout->addWidget(small_caps_btn_);